feat: release 1.5.0 — Build Scene 3D blockout composer + 1 scene : N shot clips

Build Scene (/build-scene): three.js + mannequin-js blockout viewport ported
from open-media, with per-session compositions (origin='scene' keeps rails
separate), agent shot_* tools as the only toolset for that surface, viewport
toolbar, keyframe motion + camera timeline with 60s video export, and
captures usable as project reference images.

Scene to Clips: clips table (1 scene : N renderable shots), coverage agent
breaks scenes into shots with full dialogue/action allocation, script
generation stays faithful to the screenplay (verbatim dialogue, content-
derived durations, chunked + durable inserts), video pipeline re-scoped to
clips (enqueue, continue-from, export, drafts), Script/Video UI clip-first
(#N.M labels, per-scene Break Into Shots scoped to one scene).

Agent loop: lean ReAct discipline with fail-streak escalation and budget
nudge; policy treats explicit user commands as permission; Build Scene tool
scope enforced mechanically; document + video attachments feed the VLM.
This commit is contained in:
Benjiyaya
2026-09-11 18:05:21 +08:00
parent f8faa72653
commit ce0b4e1983
90 changed files with 12482 additions and 913 deletions
+1 -1
View File
@@ -3,7 +3,7 @@
*/
export type WorkflowKind = 'image' | 'video';
export type AttachmentKind = 'image' | 'video' | 'audio';
export type AttachmentKind = 'image' | 'video' | 'audio' | 'document';
export interface WorkflowMention {
type: 'workflow';
+38 -4
View File
@@ -108,11 +108,12 @@ import type {
Job,
Scene,
SceneVideoSettings,
Clip,
Workflow,
ComfyDynamicInput,
ComfyDynamicOutput,
} from './comfy/types';
export type { Job, Scene, SceneVideoSettings, Workflow, ComfyDynamicInput, ComfyDynamicOutput };
export type { Job, Scene, SceneVideoSettings, Clip, Workflow, ComfyDynamicInput, ComfyDynamicOutput };
async function api<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
@@ -206,6 +207,35 @@ export const projects = {
method: 'POST',
body: JSON.stringify({ scene_ids: sceneIds }),
}),
createClip: (projectId: number, sceneId: number, payload: Record<string, unknown>) =>
api<Clip>(`/api/projects/${projectId}/scenes/${sceneId}/clips`, {
method: 'POST',
body: JSON.stringify(payload),
}),
updateClip: (projectId: number, clipId: number, payload: Record<string, unknown>) =>
api<Clip>(`/api/projects/${projectId}/clips/${clipId}`, {
method: 'PATCH',
body: JSON.stringify(payload),
}),
deleteClip: (projectId: number, clipId: number) =>
api<{ ok: boolean }>(`/api/projects/${projectId}/clips/${clipId}`, { method: 'DELETE' }),
reorderClips: (projectId: number, sceneId: number, clipIds: number[]) =>
api<{ ok: boolean }>(`/api/projects/${projectId}/scenes/${sceneId}/clips/reorder`, {
method: 'POST',
body: JSON.stringify({ clip_ids: clipIds }),
}),
expandClips: (
projectId: number,
payload: { scene_ids?: number[]; all?: boolean; guidance?: string } = {},
) =>
api<{
ok: boolean;
scenes: Array<{ scene_id: number; clip_count: number; total_duration_sec: number }>;
total_clips: number;
}>(`/api/projects/${projectId}/expand-clips`, {
method: 'POST',
body: JSON.stringify(payload),
}),
generateAssets: (
id: number,
payload: {
@@ -281,6 +311,7 @@ export const jobsApi = {
projectId: number,
payload: {
scene_ids?: number[];
clip_ids?: number[];
workflow_id?: number;
input_values?: Record<string, unknown>;
prompts?: Record<string, string>;
@@ -292,7 +323,7 @@ export const jobsApi = {
}),
previewPrompt: (
projectId: number,
payload: { scene_id: number; workflow_id?: number },
payload: { clip_id?: number; scene_id?: number; workflow_id?: number },
) =>
api<{
prompt: string;
@@ -309,7 +340,7 @@ export const jobsApi = {
export type PlaygroundAttachTarget = 'character_sheet' | 'location' | 'item' | 'scene';
export type UploadKind = 'image' | 'video' | 'audio';
export type UploadKind = 'image' | 'video' | 'audio' | 'document';
export interface PlaygroundUpload {
ok: boolean;
@@ -368,6 +399,8 @@ export interface AgentSession {
project_id: number | null;
title: string;
status: 'idle' | 'running' | 'error';
/** WHERE the session was born: 'chat' (AI Canvas) or 'scene' (Build Scene rail). */
origin: 'chat' | 'scene';
created_at: string;
updated_at: string;
running?: boolean;
@@ -407,9 +440,10 @@ export const agentApi = {
api<AgentSession[]>(
`/api/agent/sessions${projectId != null ? `?project_id=${projectId}` : ''}`,
),
listSceneSessions: () => api<AgentSession[]>('/api/agent/sessions?origin=scene'),
listLinkableProjects: () =>
api<{ id: number; title: string; status: string }[]>('/api/agent/projects'),
createSession: (payload: { title?: string; project_id?: number | null }) =>
createSession: (payload: { title?: string; project_id?: number | null; origin?: 'chat' | 'scene' }) =>
api<AgentSession>('/api/agent/sessions', {
method: 'POST',
body: JSON.stringify(payload),
+5 -3
View File
@@ -1,5 +1,5 @@
/** Shared shape for Omni / video ref pickers. */
export type AssetGroup = 'character' | 'location' | 'item' | 'upload' | 'clip';
export type AssetGroup = 'character' | 'location' | 'item' | 'upload' | 'clip' | 'shot';
export interface AssetOption {
label: string;
@@ -13,6 +13,7 @@ const GROUP_FROM_SUFFIX: Array<{ re: RegExp; group: AssetGroup }> = [
{ re: /\s·\s*environment$/i, group: 'location' },
{ re: /\s·\s*item$/i, group: 'item' },
{ re: /\s·\s*upload$/i, group: 'upload' },
{ re: /\s·\s*blockout(\s+clip)?$/i, group: 'shot' },
{ re: /^clip\s*#/i, group: 'clip' },
];
@@ -26,13 +27,14 @@ export function assetGroup(opt: AssetOption): AssetGroup {
/** Strip the " · sheet" style suffix so the tab already names the type. */
export function assetDisplayName(opt: AssetOption): string {
return opt.label.replace(/\s·\s*(sheet|environment|item|upload)\s*$/i, '').trim() || opt.label;
return opt.label.replace(/\s·\s*(sheet|environment|item|upload|blockout(\s+clip)?)\s*$/i, '').trim() || opt.label;
}
export const ASSET_GROUP_TABS: Array<{ id: AssetGroup; label: string }> = [
{ id: 'character', label: 'Characters' },
{ id: 'location', label: 'Environments' },
{ id: 'item', label: 'Misc. Items' },
{ id: 'shot', label: 'From Build Scene' },
{ id: 'clip', label: 'Clips' },
{ id: 'upload', label: 'Uploads' },
];
@@ -43,6 +45,6 @@ export function tabsForMediaKind(kind: string | undefined): Array<{ id: AssetGro
? ['clip', 'upload']
: kind === 'audio'
? ['upload']
: ['character', 'location', 'item', 'upload'];
: ['character', 'location', 'item', 'shot', 'upload'];
return ASSET_GROUP_TABS.filter((t) => ids.includes(t.id));
}
+21
View File
@@ -41,6 +41,8 @@ export interface Job {
id: number;
project_id: number;
scene_id: number | null;
/** Render unit — video jobs are clip jobs (scene_id stays for grouping). */
clip_id: number | null;
kind: string;
workflow_id: number | null;
status: string;
@@ -85,4 +87,23 @@ export interface Scene {
portrait_path: string | null;
sheet_path: string | null;
}>;
clips: Clip[];
}
/** Shot unit: one scene expands into 1+ clips; each renders one ~5-10s video. */
export interface Clip {
id: number;
scene_id: number;
project_id: number;
order_index: number;
description: string | null;
shot_size: string | null;
dialog_lines_covered: number[] | null;
duration_sec: number | null;
workflow_id: number | null;
clip_path: string | null;
chain_from_prev?: number | boolean | null;
video_settings?: SceneVideoSettings | null;
/** '#3.2' — scene 3, clip 2 (display label). */
label?: string;
}
@@ -93,5 +93,6 @@ export function truncateMiddle(name: string, max = 32): string {
export function acceptForKind(kind: string): string {
if (kind === 'audio') return 'audio/*';
if (kind === 'video') return 'video/*,.mp4,.webm,.mov,.mkv';
if (kind === 'document') return '.txt,.md,.docx';
return 'image/*';
}
@@ -1,6 +1,6 @@
<script lang="ts">
interface Props {
active?: 'projects' | 'canvas' | 'settings';
active?: 'projects' | 'canvas' | 'build-scene' | 'settings';
crumb?: string;
/** Optional status content rendered between the crumb and the nav. */
status?: import('svelte').Snippet;
@@ -26,6 +26,7 @@
<nav class="top-nav" aria-label="Primary">
<a class="nav-link" class:active={active === 'canvas'} href="/canvas">AI Canvas</a>
<a class="nav-link" class:active={active === 'projects'} href="/projects">Projects</a>
<a class="nav-link" class:active={active === 'build-scene'} href="/build-scene">Build Scene</a>
<a class="nav-link" class:active={active === 'settings'} href="/settings">Settings</a>
</nav>
</div>
+321 -148
View File
@@ -1,4 +1,4 @@
<script lang="ts">
<script lang="ts">
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import { toStore } from 'svelte/store';
import { toast } from '$lib/toast';
@@ -8,6 +8,7 @@
playgroundApi,
projects,
workflows,
type Clip,
type Job,
type Scene,
type Workflow,
@@ -17,6 +18,7 @@
import { normalizeInputRole } from '$lib/comfy/parser';
import type { ComfyDynamicInput } from '$lib/comfy/types';
import type { AssetOption } from '$lib/assetPicker';
import { shotApi } from '$lib/shot/api';
import { progressFor } from '$lib/jobProgress';
import SafeMedia from './SafeMedia.svelte';
import PromptPreviewModal from './video/PromptPreviewModal.svelte';
@@ -36,7 +38,8 @@
const client = useQueryClient();
let view = $state<'edit' | 'film'>('edit');
let selectedId = $state<number | null>(null);
/** Selected render unit = a clip id (flattened playback order). */
let selectedClipId = $state<number | null>(null);
let formValues = $state<Record<string, string | number>>({});
let selectedWorkflow = $state<Record<number, number>>({});
let lastFormScene = $state<number | null>(null);
@@ -93,10 +96,35 @@
queryKey: ['playground-uploads'],
queryFn: playgroundApi.listUploads,
});
const shotCapturesQuery = createQuery({
queryKey: ['shot-captures-all'],
queryFn: async () => {
const comps = await shotApi.listCompositions();
const pages = await Promise.all(comps.map((c) => shotApi.listCaptures(c.id)));
return pages.flatMap((caps, i) =>
caps.map((cap) => ({ ...cap, compTitle: comps[i].title })),
);
},
});
const scenes = $derived(($scenesQuery.data?.scenes ?? []) as Scene[]);
/** Flattened clips in playback order — the renderable units. */
const allClips = $derived(
scenes.flatMap((s) => (s.clips ?? []).map((c) => ({ clip: c, scene: s }))),
);
const totalSec = $derived(
scenes.reduce((sum, s) => sum + Math.max(s.duration_sec || 5, 1), 0),
allClips.length > 0
? allClips.reduce((sum, { clip }) => sum + Math.max(clip.duration_sec || 5, 1), 0)
: scenes.reduce((sum, s) => sum + Math.max(s.duration_sec || 5, 1), 0),
);
/** Flattened filmstrip entries with per-scene shot index + `#3.2` label. */
const filmClips = $derived(
allClips.map(({ clip, scene }) => {
const idx = (scene.clips ?? []).findIndex((c) => c.id === clip.id);
const index = idx < 0 ? 0 : idx;
return { clip, scene, index, label: clipLabel(scene, index) };
}),
);
const assetOptions = $derived.by(() => {
@@ -145,8 +173,29 @@
}
}
for (const up of $uploadsQuery.data ?? []) {
// Documents are agent-context files, not Comfy job inputs — never
// offer them in a reference picker.
if (up.kind === 'document') continue;
opts.push({ label: `${up.name} · upload`, path: up.path, kind: up.kind, group: 'upload' });
}
for (const cap of $shotCapturesQuery.data ?? []) {
if (!cap.file_path) continue;
if (cap.kind === 'video') {
opts.push({
label: `${cap.compTitle} · ${cap.label || 'Blockout'} · blockout clip`,
path: cap.file_path,
kind: 'video',
group: 'shot',
});
} else if (cap.kind === 'image') {
opts.push({
label: `${cap.compTitle} · ${cap.label || 'Blockout'} · blockout`,
path: cap.file_path,
kind: 'image',
group: 'shot',
});
}
}
return opts;
});
@@ -160,29 +209,41 @@
);
$effect(() => {
if (selectedId != null) return;
if (scenes.length > 0) selectedId = scenes[0].id;
if (selectedClipId != null && allClips.some((c) => c.clip.id === selectedClipId)) return;
selectedClipId = allClips[0]?.clip.id ?? null;
});
const selected = $derived(scenes.find((s) => s.id === selectedId) ?? null);
/** The flattened filmstrip entry (clip + scene + label) for the current selection. */
const selectedEntry = $derived(
filmClips.find((c) => c.clip.id === selectedClipId) ?? null,
);
const selected = $derived(selectedEntry?.scene ?? null);
$effect(() => {
const id = selected?.id ?? null;
const id = selectedClipId ?? null;
if (id === lastFormScene) return;
if (lastFormScene != null) formCache.set(lastFormScene, formValues);
lastFormScene = id;
if (id != null) {
const entry = filmClips.find((c) => c.clip.id === id);
if (!entry) return;
const stored = formCache.get(id);
if (stored) {
formValues = { ...stored };
} else if (selected?.video_settings?.input_values) {
// First open of a persisted setup: hydrate from the scene row.
} else if (entry.clip.video_settings?.input_values) {
// First open of a persisted clip setup: hydrate from the clip row.
formValues = {
...seedSceneDefaults(selected),
...selected.video_settings.input_values,
...seedClipDefaults(entry),
...entry.clip.video_settings.input_values,
};
} else if (entry.scene.video_settings?.input_values) {
// Legacy un-expanded clip: scene row carries the setup.
formValues = {
...seedClipDefaults(entry),
...entry.scene.video_settings.input_values,
};
} else {
formValues = { ...seedSceneDefaults(selected) };
formValues = { ...seedClipDefaults(entry) };
}
} else {
formValues = {};
@@ -196,17 +257,17 @@
let saveTimer: ReturnType<typeof setTimeout> | null = null;
let lastSavedHash = $state('');
function currentVideoSettings(): Record<string, unknown> {
if (!selected) return {};
function currentClipSettings(): Record<string, unknown> {
if (!selectedEntry) return {};
const out: Record<string, unknown> = {
input_values: compactInputValues(formValues),
};
const wfId = selectedWorkflow[selected.id];
const wfId = selectedWorkflow[selectedEntry.scene.id];
if (wfId) out.form_workflow_id = wfId;
const src = clipSource[selected.id];
const src = clipSource[selectedEntry.scene.id];
if (src) out.clip_source = src;
const draft = selected.video_settings?.prompt_draft;
const meta = selected.video_settings?.prompt_draft_meta;
const draft = selectedEntry.clip.video_settings?.prompt_draft;
const meta = selectedEntry.clip.video_settings?.prompt_draft_meta;
if (draft) {
out.prompt_draft = draft;
if (meta) out.prompt_draft_meta = meta;
@@ -220,18 +281,18 @@
$effect(() => {
// Track the pieces that make up the persisted settings.
const _unused = [formValues, selectedWorkflow, clipSource, selected?.id];
const _unused = [formValues, selectedWorkflow, clipSource, selectedEntry?.clip.id];
void _unused;
if (!selected || saveTimer) return;
if (!selectedEntry || saveTimer) return;
saveTimer = setTimeout(() => {
saveTimer = null;
if (!selected) return;
const next = currentVideoSettings();
if (!selectedEntry) return;
const next = currentClipSettings();
const hash = settingsHash(next);
if (hash === lastSavedHash) return;
lastSavedHash = hash;
projects
.updateScene(projectId, selected.id, { video_settings: next })
.updateClip(projectId, selectedEntry.clip.id, { video_settings: next })
.catch(() => {
/* transient — next change retries */
});
@@ -243,17 +304,18 @@
// handles persistence. Kept as an explicit hook for future callers.
}
// Context-aware defaults for a freshly opened scene form (user edits and the
// Context-aware defaults for a freshly opened clip form (user edits and the
// workflow's static defaults must not override these). Duration-role inputs
// seed from the scene's estimated duration; ComfyDynamicForm's own prefill
// only applies to fields still undefined afterwards.
function seedSceneDefaults(scene: Scene | null): Record<string, string | number> {
// seed from the clip's duration (falling back to the scene's estimate);
// ComfyDynamicForm's own prefill only applies to fields still undefined.
function seedClipDefaults(entry: { clip: Clip; scene: Scene }): Record<string, string | number> {
const seed: Record<string, string | number> = {};
if (!scene) return seed;
const wf = workflowFor(scene);
if (!entry) return seed;
const wf = workflowFor(entry.scene);
const secs = entry.clip.duration_sec ?? entry.scene.duration_sec;
for (const inp of wf?.input_schema ?? []) {
if (inp.role === 'duration' && scene.duration_sec != null) {
seed[inp.nodeId] = scene.duration_sec;
if (normalizeInputRole(inp.role ?? null) === 'duration' && secs != null) {
seed[inp.nodeId] = secs;
}
}
return seed;
@@ -269,25 +331,39 @@
return wf?.input_schema?.find((inp) => normalizeInputRole(inp.role ?? null) === 'video');
}
// Timeline source options for a continue scene: any other scene that has
// rendered a clip, ordered by timeline position.
function timelineClipOptions(current: Scene | null): Scene[] {
// Timeline source options for a continue clip: any other rendered clip
// (clips first, then legacy scene-level paths), ordered by timeline position.
function timelineClipOptions(
current: Scene | null,
): Array<{ label: string; path: string }> {
if (!current) return [];
return scenes
.filter((s) => s.id !== current.id && s.video_path)
.sort((a, b) => a.order_index - b.order_index);
const out: Array<{ label: string; path: string }> = [];
for (const s of scenes) {
if (s.id === current.id) continue;
for (const [i, c] of (s.clips ?? []).entries()) {
if (!c.clip_path) continue;
out.push({
label: `${s.clips.length > 1 ? `#${s.order_index}.${i + 1}` : `#${s.order_index}`} · ${s.heading || 'scene'}`,
path: c.clip_path,
});
}
if ((s.clips?.length ?? 0) === 0 && s.video_path) {
out.push({ label: `#${s.order_index} · ${s.heading || 'scene'}`, path: s.video_path });
}
}
return out;
}
const generateOne = createMutation({
mutationFn: (vars: { sceneId: number; prompt?: string }) => {
const { sceneId } = vars;
const generateOne = createMutation({
mutationFn: (vars: { clipId: number; sceneId: number; prompt?: string }) => {
const { clipId, sceneId, prompt } = vars;
const scene = scenes.find((s) => s.id === sceneId);
const wf = scene ? workflowFor(scene) : undefined;
return jobsApi.generateVideos(projectId, {
scene_ids: [sceneId],
clip_ids: [clipId],
workflow_id: selectedWorkflow[sceneId] ?? wf?.id,
input_values: compactInputValues(formValues),
prompts: vars.prompt ? { [String(sceneId)]: vars.prompt } : undefined,
prompts: prompt ? { [String(clipId)]: prompt } : undefined,
});
},
onSuccess: async () => {
@@ -298,15 +374,17 @@
onError: (err) => toast.error(err instanceof Error ? err.message : String(err)),
});
// Render-history versioning: make an older job's output the scene's clip.
// Render-history versioning: make an older job's output the clip's render.
let applyingJob = $state(false);
async function applyJobToScene(j: Job, path: string) {
if (j.scene_id == null || applyingJob) return;
async function applyJobToClip(j: Job, path: string) {
if (applyingJob) return;
const clipId = clipIdOfJob(j) ?? selectedEntry?.clip.id;
if (clipId == null) return;
applyingJob = true;
try {
await projects.updateScene(projectId, j.scene_id, { video_path: path });
await projects.updateClip(projectId, clipId, { clip_path: path });
await client.invalidateQueries({ queryKey: ['scenes'] });
toast.success('Scene clip updated');
toast.success('Clip render updated');
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
} finally {
@@ -318,13 +396,13 @@
let previewOpen = $state(false);
function beginGenerate() {
if (!selected) return;
if (!selClip) return;
previewOpen = true;
}
function onGenerateConfirmed(prompt: string) {
if (!selected) return;
$generateOne.mutate({ sceneId: selected.id, prompt });
if (!selClip || !selected) return;
$generateOne.mutate({ clipId: selClip.id, sceneId: selected.id, prompt });
}
// --- Batch generate: queue clips one by one, in timeline order. ---
@@ -337,18 +415,33 @@
let batchNote = $state('');
const scenesNeedingClip = $derived(
scenes.filter((s) => !['done', 'pending', 'running'].includes(statusOf(s))),
scenes.filter((s) => !['done', 'partial', 'pending', 'running'].includes(sceneStatus(s))),
);
const batchTargets = $derived(
scenesNeedingClip.length > 0
? scenesNeedingClip
: scenes.filter((s) => !['pending', 'running'].includes(statusOf(s))),
: scenes.filter((s) => !['pending', 'running'].includes(sceneStatus(s))),
);
const clipTotal = $derived(
scenes.reduce((n, s) => n + Math.max(s.clips?.length ?? 1, 1), 0),
);
const clipsReady = $derived(
scenes.reduce(
(n, s) =>
n +
((s.clips?.length ?? 0) > 0
? s.clips.filter((c) => c.clip_path).length
: s.video_path
? 1
: 0),
0,
),
);
const batchLabel = $derived(
batching
? batchNote
: scenesNeedingClip.length > 0
? `Generate all (${scenesNeedingClip.length})`
? `Generate all (${clipTotal - clipsReady} missing)`
: 'Regenerate all',
);
@@ -358,33 +451,46 @@
let queued = 0;
let drafted = 0;
const targets = [...batchTargets].sort((a, b) => a.order_index - b.order_index);
for (let i = 0; i < targets.length; i++) {
const scene = targets[i];
batchNote = `Queueing ${i + 1}/${targets.length}…`;
try {
// Resolve like the per-scene button does: session pick → scene's stored
// workflow → first enabled video workflow. A scene whose stored workflow
// was deleted would otherwise enqueue a job doomed to "No workflow found".
// Saved prompt drafts ride along; un-drafted scenes get the backend's
// auto-rewrite (deterministic template on LLM failure).
const draft = scene.video_settings?.prompt_draft;
const draftFresh =
draft && scene.video_settings?.prompt_draft_meta?.based_on
? scene.video_settings.prompt_draft_meta.based_on
: null;
await jobsApi.generateVideos(projectId, {
scene_ids: [scene.id],
workflow_id: workflowFor(scene)?.id,
prompts: draft ? { [String(scene.id)]: draft } : undefined,
});
queued++;
if (draft) drafted++;
client.invalidateQueries({ queryKey: ['jobs'] });
client.invalidateQueries({ queryKey: ['scenes'] });
} catch (err) {
toast.error(
`Scene #${scene.order_index}: ${err instanceof Error ? err.message : String(err)}`,
);
const totalClips = targets.reduce((n, s) => n + Math.max(s.clips?.length ?? 1, 1), 0);
let done = 0;
for (const scene of targets) {
const clips = scene.clips ?? [];
const renderTargets: Array<{ id: number; key: string }> =
clips.length > 0
? clips.map((c) => ({ id: c.id, key: String(c.id) }))
: [{ id: scene.id, key: String(scene.id) }];
for (const t of renderTargets) {
done++;
batchNote = `Queueing ${done}/${totalClips}…`;
try {
// Resolve like the per-clip button does: session pick → scene's stored
// workflow → first enabled video workflow. A scene whose stored workflow
// was deleted would otherwise enqueue a job doomed to "No workflow found".
// Fresh per-clip drafts ride along; stale/absent drafts get the backend's
// auto-rewrite (deterministic template on LLM failure).
const clip = clips.length > 0 ? clips.find((c) => c.id === t.id) : null;
const draft = clip?.video_settings?.prompt_draft;
const draftFresh =
draft && clip?.video_settings?.prompt_draft_meta?.based_on
? clip.video_settings.prompt_draft_meta.based_on
: null;
await jobsApi.generateVideos(projectId, {
clip_ids: clip ? [t.id] : undefined,
scene_ids: clip ? undefined : [t.id],
workflow_id: workflowFor(scene)?.id,
prompts: draft ? { [t.key]: draft } : undefined,
});
queued++;
if (draft) drafted++;
client.invalidateQueries({ queryKey: ['jobs'] });
client.invalidateQueries({ queryKey: ['scenes'] });
} catch (err) {
const label =
clips.length > 0
? `Clip #${scene.order_index}.${(clips.findIndex((c) => c.id === t.id) ?? 0) + 1}`
: `Scene #${scene.order_index}`;
toast.error(`${label}: ${err instanceof Error ? err.message : String(err)}`);
}
}
}
batching = false;
@@ -404,45 +510,105 @@
return enabledWorkflows.find((w) => w.id === id) ?? enabledWorkflows[0] ?? undefined;
}
// Clip-aware helpers: jobs are clip-addressed (job.clip_id); legacy rows
// without clip_id fall back to scene addressing (1:1 projects keep working).
function clipIdOfJob(j: Job): number | null {
return j.clip_id ?? null;
}
function jobForClipId(clipId: number): Job | undefined {
const jobs = ($jobsQuery.data ?? []).filter((j) => clipIdOfJob(j) === clipId && j.kind === 'video');
if (jobs.length === 0) return undefined;
return [...jobs].sort((a, b) => b.id - a.id)[0];
}
/** Latest video job for a scene (legacy fallback + history views). */
function jobForScene(sceneId: number): Job | undefined {
const jobs = ($jobsQuery.data ?? []).filter((j) => j.scene_id === sceneId && j.kind === 'video');
if (jobs.length === 0) return undefined;
return [...jobs].sort((a, b) => b.id - a.id)[0];
}
function statusOf(scene: Scene): string {
/** Any pending/running video job inside this scene (any of its clips). */
function sceneBusy(scene: Scene): boolean {
return ($jobsQuery.data ?? []).some(
(j) =>
j.kind === 'video' &&
j.scene_id === scene.id &&
(j.status === 'pending' || j.status === 'running'),
);
}
function sceneStatus(scene: Scene): string {
if (sceneBusy(scene)) return 'running';
const clips = scene.clips ?? [];
if (clips.length > 0) {
if (clips.every((c) => c.clip_path)) return 'done';
if (clips.some((c) => c.clip_path)) return 'partial';
return 'idle';
}
const job = jobForScene(scene.id);
if (job) return job.status;
if (scene.video_path) return 'done';
return 'idle';
}
function previewPath(scene: Scene): string | null {
const job = jobForScene(scene.id);
// While a new job is queued/running, don't keep showing the previous clip
if (job && (job.status === 'pending' || job.status === 'running')) return null;
// scene.video_path is the source of truth — it reflects the clip the user
// applied ("Apply to Scene"), which may be an older render than the newest job.
if (scene.video_path && /\.(mp4|webm)$/i.test(scene.video_path)) return scene.video_path;
// Fallback: latest finished job (e.g. output not filed onto the scene yet).
if (job?.status === 'done') {
const fromJob = (job.output_paths ?? []).find((p) => /\.(mp4|webm)$/i.test(p));
if (fromJob) return fromJob;
function clipBusy(clipId: number): boolean {
const job = jobForClipId(clipId);
return job?.status === 'pending' || job?.status === 'running';
}
function statusOfClip(clipId: number): string {
if (clipBusy(clipId)) return 'running';
const entry = filmClips.find((c) => c.clip.id === clipId);
if (!entry) return 'idle';
if (entry.clip.clip_path) return 'done';
const job = jobForClipId(clipId);
if (job) return job.status;
// Un-expanded/legacy clip mirrors its scene row.
if (entry.index === 0 && entry.scene.video_path && (entry.scene.clips?.length ?? 0) <= 1) {
return 'done';
}
return 'idle';
}
/** Playback label: '#3' for a scene's only clip, '#3.2' for shot 2 of 3+. */
function clipLabel(scene: Scene, index: number): string {
return (scene.clips?.length ?? 0) > 1
? `#${scene.order_index}.${index + 1}`
: `#${scene.order_index}`;
}
type Thumb = { kind: 'image' | 'video'; src: string } | null;
function thumbForClip(clipId: number): Thumb | null {
const entry = filmClips.find((c) => c.clip.id === clipId);
if (!entry) return null;
if (entry.clip.clip_path && /\.(mp4|webm)$/i.test(entry.clip.clip_path)) {
const src = assetUrl(entry.clip.clip_path);
if (src) return { kind: 'video', src };
}
if (entry.index === 0 && entry.scene.env_image_path) {
const src = assetUrl(entry.scene.env_image_path);
if (src) return { kind: 'image', src };
}
return null;
}
type Thumb = { kind: 'image' | 'video'; src: string };
function thumbFor(scene: Scene): Thumb | null {
if (scene.env_image_path) {
const src = assetUrl(scene.env_image_path);
if (src) return { kind: 'image', src };
}
const preview = previewPath(scene);
if (preview) {
const src = assetUrl(preview);
if (src) return { kind: 'video', src };
function previewPathForClip(clipId: number): string | null {
const entry = filmClips.find((c) => c.clip.id === clipId);
if (!entry) return null;
if (clipBusy(clipId)) return null;
const path = entry.clip.clip_path;
if (path && /\.(mp4|webm)$/i.test(path)) return path;
// Legacy un-expanded clip: the scene row mirrors the render.
if (
entry.index === 0 &&
(entry.scene.clips?.length ?? 0) <= 1 &&
entry.scene.video_path &&
/\.(mp4|webm)$/i.test(entry.scene.video_path)
) {
return entry.scene.video_path;
}
return null;
}
@@ -470,7 +636,7 @@
return `${Math.round(months / 12)}y ago`;
}
const doneCount = $derived(scenes.filter((s) => statusOf(s) === 'done').length);
const doneCount = $derived(clipsReady);
async function togglePause() {
if ($queueStatusQuery.data?.paused) await jobsApi.resume();
@@ -483,28 +649,33 @@
client.invalidateQueries({ queryKey: ['queue-status'] });
}
function selectScene(id: number) {
selectedId = id;
/** Select a clip; the parent scene follows for the script drawer + form. */
function selectClip(id: number) {
selectedClipId = id;
}
// Filmstrip click → jump back to the editor with that scene selected.
// Filmstrip click → jump back to the editor with that clip selected.
function editScene(id: number) {
selectedId = id;
view = 'edit';
const entry = allClips.find((c) => c.scene.id === id);
if (entry) {
selectedClipId = entry.clip.id;
view = 'edit';
}
}
function neighborId(dir: -1 | 1): number | null {
const idx = scenes.findIndex((s) => s.id === selectedId);
const next = scenes[(idx < 0 ? 0 : idx) + dir];
return next?.id ?? null;
function neighborClipId(dir: -1 | 1): number | null {
const idx = allClips.findIndex((c) => c.clip.id === selectedClipId);
const next = allClips[(idx < 0 ? 0 : idx) + dir];
return next?.clip.id ?? null;
}
function step(dir: -1 | 1) {
const id = neighborId(dir);
if (id != null) selectedId = id;
const id = neighborClipId(dir);
if (id != null) selectedClipId = id;
}
const selJob = $derived(selected ? jobForScene(selected.id) : undefined);
const selClip = $derived(selectedEntry?.clip ?? null);
const selJob = $derived(selClip ? jobForClipId(selClip.id) : undefined);
const selProg = $derived(selJob ? progressFor(selJob.id) : undefined);
const selError = $derived(selJob?.error ?? '');
const selErrorLong = $derived(selError.length > 140 || selError.split('\n').length > 3);
@@ -537,8 +708,7 @@
Date.parse(j.completed_at) > exportAt,
);
});
const clipsReady = $derived(scenes.filter((s) => Boolean(s.video_path)).length);
const clipsMissing = $derived(scenes.length - clipsReady);
const clipsMissing = $derived(clipTotal - clipsReady);
type ExportState = 'idle' | 'active' | 'ready' | 'failed';
const exportState = $derived.by((): ExportState => {
@@ -606,7 +776,7 @@
{#if scenes.length === 0}
Build a script first, then cut clips on the timeline.
{:else}
{doneCount}/{scenes.length} clips done · {formatClock(totalSec)} total
{doneCount}/{clipTotal} clips done · {formatClock(totalSec)} total · {scenes.length} scenes
{/if}
</p>
</div>
@@ -672,14 +842,14 @@
</div>
{:else if selected}
{@const selWf = workflowFor(selected)}
{@const selStatus = statusOf(selected)}
{@const selPreview = previewPath(selected)}
{@const selStatus = selClip ? statusOfClip(selClip.id) : sceneStatus(selected)}
{@const selPreview = selClip ? previewPathForClip(selClip.id) : null}
{@const selHasVideoInput = workflowHasVideoInput(selWf)}
{@const selVideoNode = videoInputNodeFor(selWf)}
{@const selClips = timelineClipOptions(selected)}
{@const selChain = Boolean(selected.chain_from_prev)}
{@const selChain = Boolean(selClip?.chain_from_prev ?? selected.chain_from_prev)}
{@const selSource = clipSource[selected.id] ?? 'auto'}
{@const selSourceValid = selSource === 'auto' || selSource === 'upload' || selClips.some((s) => String(s.id) === selSource)}
{@const selSourceValid = selSource === 'auto' || selSource === 'upload' || selClips.some((o) => o.path === selSource)}
{@const selBlocked = selChain && !selHasVideoInput}
<input
bind:this={videoFileInput}
@@ -690,16 +860,18 @@
/>
<VideoEditWorkspace
{scenes}
{filmClips}
selectedClip={selectedEntry}
{selectedClipId}
{selected}
{selectedId}
status={selStatus}
previewPath={selPreview}
progress={selProg}
error={selError}
errorLong={selErrorLong}
job={selJob}
sceneJobs={($jobsQuery.data ?? []).filter(
(j) => j.scene_id === selected.id && j.kind === 'video',
clipJobs={($jobsQuery.data ?? []).filter(
(j) => selClip != null && clipIdOfJob(j) === selClip.id && j.kind === 'video',
)}
workflow={selWf}
workflows={enabledWorkflows}
@@ -707,23 +879,22 @@
{assetOptions}
allowUpload
submitting={$generateOne.isPending}
{statusOf}
{thumbFor}
statusOfClip={statusOfClip}
thumbForClip={thumbForClip}
{formatClock}
chained={(scene) => Boolean(scene.chain_from_prev)}
onApplyToScene={(j, path) => applyJobToScene(j, path)}
onApplyToClip={(j, path) => applyJobToClip(j, path)}
applying={applyingJob}
generateDisabled={selBlocked}
generateDisabledReason={selBlocked
? 'This scene continues from the previous video — pick a workflow with a video input'
? 'This clip continues from the previous video — pick a workflow with a video input'
: ''}
clipSource={{
enabled: selChain && selHasVideoInput && Boolean(selVideoNode),
value: selSourceValid ? selSource : 'auto',
options: selClips.map((s) => ({
id: String(s.id),
label: `#${s.order_index} ${s.heading || 'Scene'}`,
path: s.video_path ?? undefined,
options: selClips.map((o) => ({
id: o.path,
label: o.label,
path: o.path,
})),
}}
onClipSourceChange={(val) => {
@@ -737,25 +908,27 @@
clipSource = { ...clipSource, [selected.id]: 'upload' };
} else {
clipSource = { ...clipSource, [selected.id]: val };
const clip = selClips.find((s) => String(s.id) === val);
if (clip?.video_path && selVideoNode) {
formValues = { ...formValues, [selVideoNode.nodeId]: clip.video_path };
if (selVideoNode) {
formValues = { ...formValues, [selVideoNode.nodeId]: val };
}
}
}}
onClipSourceUpload={() => videoFileInput?.click()}
onSelect={selectScene}
onSelectClip={selectClip}
onStep={step}
onWorkflowChange={(id) => {
selectedWorkflow = { ...selectedWorkflow, [selected.id]: Number(id) };
}}
onGenerate={() => $generateOne.mutate({ sceneId: selected.id })}
onGenerate={() => {
if (selClip) $generateOne.mutate({ clipId: selClip.id, sceneId: selected.id });
}}
onPreviewPrompt={beginGenerate}
/>
<PromptPreviewModal
bind:open={previewOpen}
{projectId}
clip={selClip}
scene={selected}
workflow={selWf}
inputValues={formValues}
@@ -830,7 +1003,7 @@
<p class="slate-warn" role="status">
<Icon name="alert" size={14} />
<span>
{clipsMissing} scene{clipsMissing === 1 ? '' : 's'} without a clip will be skipped
{clipsMissing} clip{clipsMissing === 1 ? '' : 's'} without a render will be skipped
</span>
</p>
{/if}
@@ -871,17 +1044,17 @@
</div>
{/if}
{#if scenes.length > 0}
{#if filmClips.length > 0}
<div class="filmstrip-block">
<p class="filmstrip-label">In this film</p>
<div class="filmstrip">
{#each scenes as scene (scene.id)}
{@const thumb = thumbFor(scene)}
{#each filmClips as entry (entry.clip.id)}
{@const thumb = thumbForClip(entry.clip.id)}
<button
type="button"
class="filmstrip-item"
title={`${scene.heading || 'Scene'} — edit in timeline`}
onclick={() => editScene(scene.id)}
title={`${entry.scene.heading || 'Scene'} ${entry.label} — edit in timeline`}
onclick={() => editScene(entry.scene.id)}
>
{#if thumb?.kind === 'image'}
<img class="filmstrip-media" src={thumb.src} alt="" loading="lazy" />
@@ -889,9 +1062,9 @@
<!-- svelte-ignore a11y_media_has_caption -->
<video class="filmstrip-media" src={thumb.src} muted playsinline preload="metadata"></video>
{:else}
<span class="filmstrip-slate">#{scene.order_index}</span>
<span class="filmstrip-slate">{entry.label}</span>
{/if}
<span class="filmstrip-num">#{scene.order_index}</span>
<span class="filmstrip-num">{entry.label}</span>
</button>
{/each}
</div>
@@ -3,7 +3,7 @@
import { goto } from '$app/navigation';
import { toStore } from 'svelte/store';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import { assetUrl, jobsApi, projects, type Job, type Scene } from '$lib/api';
import { assetUrl, jobsApi, projects, type Job, type Scene, type Clip } from '$lib/api';
import { estimateTargetSeconds } from '$lib/durationBudget';
import { agentDeepLink } from '$lib/agentTasks';
import { toast } from '$lib/toast';
@@ -62,6 +62,7 @@
const scenes = $derived($scenesQuery.data?.scenes ?? []);
const sceneCount = $derived(scenes.length);
const totalClips = $derived(scenes.reduce((n, s) => n + (s.clips?.length ?? 0), 0));
const totalSec = $derived($scenesQuery.data?.estimated_duration_sec ?? 0);
const targetSec = $derived.by(() => {
const target = $storyQuery.data?.project?.target_duration;
@@ -70,6 +71,63 @@
const busy = $derived(adding || deletingId != null);
// ── Break into shots (coverage expansion) ────────────────────────────
let expandingIds = $state<number[]>([]);
let expandingAll = $state(false);
let expandedIds = $state<number[]>([]);
function isExpanded(scene: Scene): boolean {
return (scene.clips?.length ?? 0) > 1 || expandedIds.includes(scene.id);
}
async function breakIntoShots(scene: Scene) {
if (expandingIds.length > 0 || expandingAll) return;
expandingIds = [...expandingIds, scene.id];
try {
const res = await projects.expandClips(projectId, { scene_ids: [scene.id] });
expandedIds = [...new Set([...expandedIds, scene.id])];
await client.invalidateQueries({ queryKey: ['scenes'] });
toast.success(
`Scene #${scene.order_index} → ${res.scenes?.[0]?.clip_count ?? '?'} shots`,
);
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not break scene into shots');
} finally {
expandingIds = expandingIds.filter((id) => id !== scene.id);
}
}
async function breakAllIntoShots() {
if (expandingIds.length > 0 || expandingAll) return;
if (
!window.confirm(
`Break ALL ${sceneCount} scenes into shot clips? Existing shots of those scenes are replaced.`,
)
)
return;
expandingAll = true;
try {
const res = await projects.expandClips(projectId, { all: true });
expandedIds = scenes.map((s) => s.id);
await client.invalidateQueries({ queryKey: ['scenes'] });
toast.success(`Board expanded to ${res.total_clips} clips`);
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not break scenes into shots');
} finally {
expandingAll = false;
}
}
async function deleteClip(clip: Clip, scene: Scene) {
try {
await projects.deleteClip(projectId, clip.id);
await client.invalidateQueries({ queryKey: ['scenes'] });
toast.success(`Deleted shot #${scene.order_index}.${clip.order_index}`);
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not delete clip');
}
}
const saveMutation = createMutation({
mutationFn: () =>
projects.updateScene(projectId, editing!.id, {
@@ -114,6 +172,14 @@
return [...jobs].sort((a, b) => b.id - a.id)[0];
}
function jobForClip(clipId: number): Job | undefined {
const jobs = ($jobsQuery.data ?? []).filter(
(j) => (j as Job & { clip_id?: number | null }).clip_id === clipId && j.kind === 'video',
);
if (jobs.length === 0) return undefined;
return [...jobs].sort((a, b) => b.id - a.id)[0];
}
/** Per-scene production status — only uses fields the API actually exposes. */
function sceneStatus(scene: Scene): { status: string; label: string } {
const job = jobForScene(scene.id);
@@ -262,6 +328,9 @@
{/if}
{#if sceneCount > 0}
· {sceneCount} scenes
{#if totalClips > 0}
/ {totalClips} shot clips
{/if}
{/if}
</p>
</div>
@@ -269,6 +338,15 @@
<Button variant="secondary" disabled={busy} loading={adding} onclick={addScene}>
<Icon name="plus" size={14} /> Add Scene
</Button>
<Button
variant="secondary"
disabled={busy || expandingAll || expandingIds.length > 0 || sceneCount === 0}
loading={expandingAll}
onclick={breakAllIntoShots}
title="Break every scene into shot clips (LLM coverage pass)"
>
<Icon name="film" size={14} /> Break All Into Shots
</Button>
<Button variant="primary" disabled={busy} onclick={requestRegenerate}>
<Icon name="sparkle" size={15} /> Regenerate Script
</Button>
@@ -355,6 +433,61 @@
{#if scene.dialog}
<pre class="dialog">{scene.dialog}</pre>
{/if}
<div class="clip-block">
<div class="clip-head">
<span class="clip-title">
<Icon name="film" size={12} />
{(scene.clips ?? []).length}
{(scene.clips ?? []).length === 1 ? 'shot clip' : 'shot clips'}
{#if (scene.clips ?? []).some((c) => c.clip_path)}
· {(scene.clips ?? []).filter((c) => c.clip_path).length} rendered
{/if}
</span>
<Button
variant="secondary"
size="sm"
disabled={busy || expandingIds.length > 0 || expandingAll}
loading={expandingIds.includes(scene.id)}
onclick={() => breakIntoShots(scene)}
title={isExpanded(scene) ? 'Re-break this scene into shots (replaces existing shots)' : 'Break this scene into multiple shot clips via the coverage pass'}
>
{isExpanded(scene) ? 'Re-break Into Shots' : 'Break Into Shots'}
</Button>
</div>
{#if isExpanded(scene) && (scene.clips ?? []).length > 1}
<ul class="clip-list">
{#each scene.clips ?? [] as clip (clip.id)}
{@const clipJob = jobForClip(clip.id)}
<li class="clip-row">
<span class="clip-num" class:ready={Boolean(clip.clip_path)}>
#{scene.order_index}.{clip.order_index}
</span>
<span class="clip-desc">{clip.description || 'Untitled shot'}</span>
{#if clip.shot_size}
<span class="chip">{clip.shot_size}</span>
{/if}
{#if clipJob && (clipJob.status === 'pending' || clipJob.status === 'running')}
<span class="chip chip-render">rendering…</span>
{:else if clip.clip_path}
<span class="chip chip-ok">✓ clip</span>
{/if}
{#if clip.duration_sec}
<span class="clip-dur">{clip.duration_sec}s</span>
{/if}
<button
type="button"
class="icon-btn"
aria-label="Delete shot #{scene.order_index}.{clip.order_index}"
title="Delete this shot"
onclick={() => deleteClip(clip, scene)}
>
<Icon name="trash" size={13} />
</button>
</li>
{/each}
</ul>
{/if}
</div>
<div class="chips">
{#each scene.characters ?? [] as c (c.id)}
{@const avatar = avatarFor(c)}
@@ -635,6 +768,72 @@
border-color: var(--accent);
background: color-mix(in srgb, var(--accent) 12%, var(--bg-elevated));
}
.clip-block {
margin-top: 10px;
border-top: 1px dashed var(--border);
padding-top: 8px;
}
.clip-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
}
.clip-title {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
font-weight: 600;
color: var(--text-secondary);
}
.clip-list {
list-style: none;
margin: 8px 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 4px;
}
.clip-row {
display: flex;
align-items: center;
gap: 8px;
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 4px 8px;
font-size: 12px;
}
.clip-num {
font-family: var(--font-mono);
font-weight: 700;
color: var(--text-secondary);
flex-shrink: 0;
}
.clip-num.ready {
color: var(--accent);
}
.clip-desc {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text-primary);
}
.clip-dur {
color: var(--text-muted);
flex-shrink: 0;
}
.chip-ok {
color: var(--accent);
border-color: var(--accent);
}
.chip-render {
color: var(--warning, #eab308);
border-color: var(--warning, #eab308);
}
.avatar {
position: relative;
width: 20px;
@@ -43,7 +43,7 @@ let {
}: Props = $props();
const ATTACH_LIMIT = 8;
const ACCEPT = 'image/*,video/*,audio/*,.png,.jpg,.jpeg,.webp,.gif,.mp4,.webm,.mov,.mkv,.mp3,.wav,.flac,.ogg,.m4a';
const ACCEPT = 'image/*,video/*,audio/*,.png,.jpg,.jpeg,.webp,.gif,.mp4,.webm,.mov,.mkv,.mp3,.wav,.flac,.ogg,.m4a,.txt,.md,.docx';
let editorEl = $state<HTMLDivElement | null>(null);
let fileInput = $state<HTMLInputElement | null>(null);
@@ -498,6 +498,10 @@ let {
{#if src}
<img src={src} alt={a.name} />
{/if}
{:else if a.kind === 'document'}
<span class="tile-icon">
<Icon name="file" size={16} />
</span>
{:else}
<span class="tile-icon">
<Icon name={a.kind === 'audio' ? 'music' : 'video'} size={16} />
@@ -94,6 +94,7 @@
if (tab === 'character') return 'No character sheets yet. Generate them on Assets.';
if (tab === 'location') return 'No environment images yet. Generate them on Assets.';
if (tab === 'item') return 'No misc. item images yet. Generate them on Assets.';
if (tab === 'shot') return 'No Build Scene captures yet. Capture blockouts on the Build Scene page.';
if (tab === 'clip') return 'No scene clips in this film yet.';
return allowUpload ? 'No uploads yet. Use Upload new… below.' : 'No uploads yet.';
});
@@ -63,6 +63,7 @@ export const icons = {
'<path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>',
folder:
'<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>',
file: '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>',
// Chevrons
'chevron-left': '<path d="m15 18-6-6 6-6"/>',
'chevron-right': '<path d="m9 18 6-6-6-6"/>',
@@ -15,27 +15,33 @@
message?: string;
}
interface Props {
previewPath: string | null;
status: string;
heading: string;
orderIndex: number;
sceneId?: number;
progress?: Progress | null;
error?: string;
errorLong?: boolean;
}
interface Props {
previewPath: string | null;
status: string;
heading: string;
orderIndex: number;
/** Display label, e.g. '#3.2' — shown on the slate + id strip instead of the plain index. */
label?: string;
/** Secondary id line, e.g. 'clip 512'. */
idLabel?: string;
sceneId?: number;
progress?: Progress | null;
error?: string;
errorLong?: boolean;
}
let {
previewPath,
status,
heading,
orderIndex,
sceneId,
progress = null,
error = '',
errorLong = false,
}: Props = $props();
let {
previewPath,
status,
heading,
orderIndex,
label,
idLabel,
sceneId,
progress = null,
error = '',
errorLong = false,
}: Props = $props();
let errorOpen = $state(false);
// '#t=0.1' media fragment: with preload="metadata" browsers paint NOTHING
@@ -56,8 +62,10 @@
<SafeMedia class="media" src={previewUrl} kind="video" label="Video unavailable" />
{:else}
<div class="empty">
<span class="slate">#{orderIndex}</span>
{#if sceneId != null}
<span class="slate">{label ?? `#${orderIndex}`}</span>
{#if idLabel}
<p class="sid">{idLabel}</p>
{:else if sceneId != null}
<p class="sid">scene_id {sceneId}</p>
{/if}
<p class="title">{heading || 'Untitled'}</p>
@@ -93,8 +101,10 @@
</div>
<div class="ids">
<span>#{orderIndex}</span>
{#if sceneId != null}
<span>{label ?? `#${orderIndex}`}</span>
{#if idLabel}
<span class="ids-db">{idLabel}</span>
{:else if sceneId != null}
<span class="ids-db">id {sceneId}</span>
{/if}
</div>
@@ -10,7 +10,7 @@
import Modal from '$lib/components/ui/Modal.svelte';
interface ClipSourceOption {
/** Scene id as string, or the 'auto' / 'upload' sentinels. */
/** Source key — a clip/scene path, or the 'auto' / 'upload' sentinels. */
id: string;
label: string;
/** Clip path — renders a video thumbnail when present. */
@@ -3,10 +3,12 @@
* PromptPreviewModal — HITL review gate before Generate (issue #27).
* Resolves the exact prompt (saved fresh draft → LLM rewrite → fallback),
* lets the user edit/regenerate/save it, and only enqueues on confirm.
* Clip-addressed when the project is expanded; falls back to scene
* addressing (backend resolves the scene's default clip) otherwise.
*/
import { createMutation } from '@tanstack/svelte-query';
import { toast } from '$lib/toast';
import { jobsApi, projects, type Scene, type Workflow } from '$lib/api';
import { jobsApi, projects, type Clip, type Scene, type Workflow } from '$lib/api';
import Button from '$lib/components/ui/Button.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import Modal from '$lib/components/ui/Modal.svelte';
@@ -15,6 +17,9 @@
interface Props {
open?: boolean;
projectId: number;
/** Clip addressing: the exact render unit to preview (backend contract). */
clip?: Clip | null;
/** Fallback when un-expanded (backend resolves clip #1 of the scene). */
scene: Scene | null;
workflow?: Workflow | null;
/** Extra form values to pass through on confirm. */
@@ -27,6 +32,7 @@
let {
open = $bindable(false),
projectId,
clip = null,
scene,
workflow = null,
inputValues = {},
@@ -38,16 +44,17 @@
let basedOn = $state('');
let fromDraft = $state(false);
let stale = $state(false);
/** Scene id whose resolve already fired once — guards against store-transition re-runs. */
/** Clip/scene key whose resolve already fired once — guards re-runs. */
let attemptedFor = $state<number | null>(null);
/** Resolve failed — modal shows a client-side prose fallback instead of a dead end. */
let failed = $state(false);
const preview = createMutation({
mutationFn: async () => {
if (!scene) throw new Error('No scene selected');
if (!clip && !scene) throw new Error('No clip selected');
return jobsApi.previewPrompt(projectId, {
scene_id: scene.id,
clip_id: clip?.id,
scene_id: clip ? undefined : scene?.id,
workflow_id: workflow?.id,
});
},
@@ -64,7 +71,7 @@
// Never a dead end: populate the editor with raw scene text so the
// user can edit and Generate (confirm sends it via prompts override),
// or hit Regenerate to retry the rewrite.
text = proseFallback(scene);
text = proseFallback(scene, clip);
basedOn = '';
fromDraft = false;
}
@@ -72,40 +79,62 @@
},
});
// Resolve once per scene. `attemptedFor` is set before mutating so
// mutation-store transitions (pending → success/error) can't re-trigger
// this effect — the old `text` guard fired duplicate requests while the
// first was still pending.
// Resolve once per clip (or scene for legacy rows). `attemptedFor` is set
// before mutating so mutation-store transitions (pending → success/error)
// can't re-trigger this effect — the old `text` guard fired duplicate
// requests while the first was still pending.
$effect(() => {
if (!open || !scene) return;
if (attemptedFor === scene.id) return;
attemptedFor = scene.id;
if (!open || (!clip && !scene)) return;
const key = clip?.id ?? -(scene?.id ?? 0);
if (attemptedFor === key) return;
attemptedFor = key;
$preview.mutate();
});
function proseFallback(s: Scene): string {
/** Fallback body when resolve fails: the clip's beat or the scene prose. */
function proseFallback(s: Scene, c: Clip | null): string {
if (c?.description) {
const heading = (s.heading || '').trim();
return [heading, c.description.trim()].filter(Boolean).join('\n\n');
}
const heading = (s.heading || '').trim();
const action = (s.action || '').trim();
const dialog = (s.dialog || '').trim();
return [heading, action, dialog].filter(Boolean).join('\n\n');
}
// Stale check: a draft saved against different scene content should warn.
// Stale check: a draft saved against different content should warn.
$effect(() => {
if (!scene || !basedOn) return;
const meta = scene.video_settings?.prompt_draft_meta?.based_on;
if (!clip || !basedOn) {
if (!clip) stale = false;
return;
}
const meta = clip.video_settings?.prompt_draft_meta?.based_on;
stale = fromDraft && meta != null && meta !== basedOn;
});
const draftMeta = $derived(scene?.video_settings?.prompt_draft_meta);
async function saveDraft() {
if (!scene || !text.trim()) return;
const existing = scene.video_settings ?? {};
if (!text.trim()) return;
const meta = { based_on: basedOn, saved_at: new Date().toISOString() };
if (clip) {
const next = {
...(clip.video_settings ?? {}),
prompt_draft: text,
prompt_draft_meta: meta,
};
try {
await projects.updateClip(projectId, clip.id, { video_settings: next });
toast.success('Draft saved — Generate will use it');
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
return;
}
if (!scene) return;
const next = {
...existing,
...(scene.video_settings ?? {}),
prompt_draft: text,
prompt_draft_meta: { based_on: basedOn, saved_at: new Date().toISOString() },
prompt_draft_meta: meta,
};
try {
await projects.updateScene(projectId, scene.id, { video_settings: next });
@@ -132,8 +161,8 @@
</script>
<Modal bind:open {onclose} title="Review prompt before generating" size="lg">
{#if !scene}
<p class="muted">No scene selected.</p>
{#if !clip && !scene}
<p class="muted">No clip selected.</p>
{:else if $preview.isPending}
<div class="loading">
<Spinner size="md" />
@@ -141,17 +170,22 @@
</div>
{:else}
<div class="head-row">
<span class="meta">Scene #{scene.order_index} · {scene.heading || 'Untitled'}</span>
<span class="meta">
{#if clip}
Shot {clip.label ?? `#${scene?.order_index ?? ''}`} · {scene?.heading || 'Untitled'}
{:else}
Scene #{scene?.order_index} · {scene?.heading || 'Untitled'}
{/if}
</span>
<span class="meta">{workflow?.name ?? 'Default workflow'}</span>
</div>
{#if stale}
<div class="stale-hint" role="status">
<Icon name="alert" size={14} />
<span>Saved draft is based on older scene content — regenerate to refresh it.</span>
<span>Saved draft is based on older content — regenerate to refresh it.</span>
</div>
{/if}
<textarea
class="prompt-editor"
bind:value={text}
@@ -1,6 +1,22 @@
<script module lang="ts">
/** One entry in the strip: a renderable clip pinned to its parent scene. */
export interface FilmstripClip {
clip: {
id: number;
clip_path: string | null;
duration_sec: number | null;
chain_from_prev?: number | boolean | null;
};
scene: import('$lib/api').Scene;
index: number;
label: string;
}
</script>
<script lang="ts">
/**
* SceneFilmstrip — slim horizontal scene strip under the hero monitor.
* SceneFilmstrip — slim horizontal strip under the hero monitor.
* Renders CLIPS (playback order, `#3.2` labels) with scene-divider grouping.
* Never sticky; fixed height; keyboard Left/Right/Home/End.
*/
import type { Scene } from '$lib/api';
@@ -10,70 +26,73 @@
type Thumb = { kind: 'image' | 'video'; src: string } | null;
interface Props {
scenes: Scene[];
selectedId: number | null;
statusOf: (scene: Scene) => string;
thumbFor: (scene: Scene) => Thumb;
clips: FilmstripClip[];
selectedClipId: number | null;
statusOfClip: (clipId: number) => string;
thumbForClip: (clipId: number) => Thumb;
formatClock: (sec: number) => string;
chained?: (scene: Scene) => boolean;
onSelect: (id: number) => void;
onSelectClip: (clipId: number) => void;
onStep: (dir: -1 | 1) => void;
}
let {
scenes,
selectedId,
statusOf,
thumbFor,
clips,
selectedClipId,
statusOfClip,
thumbForClip,
formatClock,
chained = () => false,
onSelect,
onSelectClip,
onStep,
}: Props = $props();
const selected = $derived(scenes.find((s) => s.id === selectedId) ?? null);
const selectedIndex = $derived(scenes.findIndex((s) => s.id === selectedId));
const selectedLabel = $derived(
clips.find((c) => c.clip.id === selectedClipId)?.label ?? '—',
);
function onKeydown(e: KeyboardEvent) {
if (scenes.length === 0) return;
if (clips.length === 0) return;
const idx = clips.findIndex((c) => c.clip.id === selectedClipId);
let nextId: number | null = null;
if (e.key === 'ArrowRight') {
const i = selectedIndex < 0 ? 0 : selectedIndex + 1;
nextId = scenes[Math.min(i, scenes.length - 1)]?.id ?? null;
const i = idx < 0 ? 0 : idx + 1;
nextId = clips[Math.min(i, clips.length - 1)].clip.id;
} else if (e.key === 'ArrowLeft') {
const i = selectedIndex < 0 ? 0 : selectedIndex - 1;
nextId = scenes[Math.max(i, 0)]?.id ?? null;
} else if (e.key === 'Home') nextId = scenes[0]?.id ?? null;
else if (e.key === 'End') nextId = scenes[scenes.length - 1]?.id ?? null;
if (nextId == null || nextId === selectedId) return;
const i = idx < 0 ? 0 : idx - 1;
nextId = clips[Math.max(i, 0)].clip.id;
} else if (e.key === 'Home') nextId = clips[0].clip.id;
else if (e.key === 'End') nextId = clips[clips.length - 1].clip.id;
if (nextId == null || nextId === selectedClipId) return;
e.preventDefault();
onSelect(nextId);
onSelectClip(nextId);
queueMicrotask(() => document.getElementById(`film-clip-${nextId}`)?.focus());
}
</script>
<section class="strip" aria-label="Scene filmstrip">
<section class="strip" aria-label="Clip filmstrip">
<div
class="track"
role="listbox"
aria-label="Scene clips"
aria-activedescendant={selectedId != null ? `film-clip-${selectedId}` : undefined}
aria-activedescendant={selectedClipId != null ? `film-clip-${selectedClipId}` : undefined}
tabindex="0"
onkeydown={onKeydown}
>
{#each scenes as scene (scene.id)}
{@const st = statusOf(scene)}
{@const thumb = thumbFor(scene)}
{#each clips as entry, i (entry.clip.id)}
{@const st = statusOfClip(entry.clip.id)}
{@const thumb = thumbForClip(entry.clip.id)}
{#if entry.index === 0 && i > 0}
<span class="divider" role="presentation" title={entry.scene.heading || 'Scene'}></span>
{/if}
<button
type="button"
id="film-clip-{scene.id}"
id="film-clip-{entry.clip.id}"
role="option"
aria-selected={selectedId === scene.id}
aria-selected={selectedClipId === entry.clip.id}
class="clip status-{st}"
class:selected={selectedId === scene.id}
class:chained={chained(scene)}
onclick={() => onSelect(scene.id)}
title={`#${scene.order_index} · id ${scene.id} · ${scene.heading || 'Scene'} · ${formatClock(scene.duration_sec || 5)}`}
class:selected={selectedClipId === entry.clip.id}
class:chained={entry.index > 0}
onclick={() => onSelectClip(entry.clip.id)}
title={`#${entry.scene.order_index} · ${entry.scene.heading || 'Scene'} · shot ${entry.index + 1} · ${formatClock(entry.clip.duration_sec || 5)}`}
>
<span class="bar" aria-hidden="true"></span>
<span class="thumb" aria-hidden="true">
@@ -83,25 +102,23 @@
<!-- svelte-ignore a11y_media_has_caption -->
<video class="thumb-media" src={thumb.src + '#t=0.1'} muted playsinline preload="metadata"></video>
{:else}
<span class="thumb-slate">#{scene.order_index}</span>
<span class="thumb-slate">{entry.label}</span>
{/if}
</span>
<span class="meta">
<span class="num">#{scene.order_index}</span>
<span class="sid">id {scene.id}</span>
<span class="num">{entry.label}</span>
<span class="sid">{formatClock(entry.clip.duration_sec || 5)}</span>
</span>
</button>
{/each}
</div>
<div class="transport">
<Button variant="ghost" size="sm" disabled={!selected} onclick={() => onStep(-1)}>
<Button variant="ghost" size="sm" onclick={() => onStep(-1)}>
<Icon name="chevron-left" size={14} /> Prev
</Button>
<span class="pos">
{selected ? `#${selected.order_index} of ${scenes.length} · id ${selected.id}` : '—'}
</span>
<Button variant="ghost" size="sm" disabled={!selected} onclick={() => onStep(1)}>
<span class="pos">{selectedLabel}</span>
<Button variant="ghost" size="sm" onclick={() => onStep(1)}>
Next <Icon name="chevron-right" size={14} />
</Button>
</div>
@@ -119,12 +136,21 @@
.track {
display: flex;
gap: 8px;
align-items: stretch;
overflow-x: auto;
padding: 2px 2px 6px;
min-height: 72px;
scrollbar-width: thin;
}
.divider {
flex: 0 0 2px;
align-self: stretch;
background: color-mix(in srgb, var(--border) 60%, transparent);
border-radius: 1px;
margin: 4px 2px;
}
.clip {
position: relative;
flex: 0 0 96px;
@@ -153,6 +179,7 @@
box-shadow: 0 0 0 1px var(--accent);
}
/* Shots after the first in a scene: connector nub on the left. */
.clip.chained::before {
content: '';
position: absolute;
@@ -160,7 +187,7 @@
top: 50%;
width: 6px;
height: 2px;
background: var(--accent);
background: color-mix(in srgb, var(--text-muted) 60%, transparent);
transform: translateY(-50%);
z-index: 2;
}
@@ -181,6 +208,9 @@
.clip.status-done .bar {
background: var(--success);
}
.clip.status-partial .bar {
background: color-mix(in srgb, var(--success) 55%, var(--warning));
}
.clip.status-running .bar,
.clip.status-pending .bar {
background: var(--warning);
@@ -210,7 +240,7 @@
width: 100%;
height: 100%;
font-family: var(--font-mono);
font-size: 14px;
font-size: 12px;
font-weight: 700;
color: var(--text-muted);
}
@@ -4,7 +4,7 @@
* Hero monitor + filmstrip + meta strip + docked Omni composer.
* Does not reuse the old top two-card clip-stage layout.
*/
import type { Job, Scene, Workflow } from '$lib/api';
import type { Clip, Job, Scene, Workflow } from '$lib/api';
import OmniComposer from '$lib/components/OmniComposer.svelte';
import type { AssetOption } from '$lib/assetPicker';
import Icon from '$lib/components/ui/Icon.svelte';
@@ -12,7 +12,7 @@
import ClipSourceModal from './ClipSourceModal.svelte';
import JobInputsDrawer from './JobInputsDrawer.svelte';
import PromptPreviewModal from './PromptPreviewModal.svelte';
import SceneFilmstrip from './SceneFilmstrip.svelte';
import SceneFilmstrip, { type FilmstripClip } from './SceneFilmstrip.svelte';
import SceneScriptDrawer from './SceneScriptDrawer.svelte';
type Thumb = { kind: 'image' | 'video'; src: string } | null;
@@ -39,26 +39,30 @@
interface Props {
scenes: Scene[];
/** Flattened clips in playback order — the filmstrip + selection units. */
filmClips: FilmstripClip[];
/** Selected clip (defaults to the scene's first when the scene has one clip). */
selectedClip: { clip: Clip; scene: Scene; index: number; label: string } | null;
selectedClipId: number | null;
selected: Scene;
selectedId: number | null;
status: string;
previewPath: string | null;
progress?: Progress | null;
error?: string;
errorLong?: boolean;
/** Latest video job for the scene — drives the "what was sent" drawer. */
/** Latest video job for the selected clip — drives the "what was sent" drawer. */
job?: Job | null;
/** All video jobs for the scene (history strip in the drawer). */
sceneJobs?: Job[];
/** All video jobs for the selected clip (history strip in the drawer). */
clipJobs?: Job[];
workflow: Workflow | undefined;
workflows: Workflow[];
formValues: Record<string, string | number>;
assetOptions: AssetOption[];
allowUpload?: boolean;
/** Disable Generate: scene continues from the previous video but the workflow cannot accept it. */
/** Disable Generate: clip continues from the previous video but the workflow cannot accept it. */
generateDisabled?: boolean;
generateDisabledReason?: string;
/** Where this continue scene's video input comes from (auto / upload / a timeline clip). */
/** Where this continue clip's video input comes from (auto / upload / a timeline clip). */
clipSource?: ClipSourceConfig;
onClipSourceChange?: (value: string) => void;
/** Upload file picked in the source modal — caller opens the file dialog. */
@@ -66,32 +70,33 @@
/** HITL prompt review before Generate: caller resolves + shows the modal. */
onPreviewPrompt?: () => void;
generateLabel?: string;
chained?: (scene: Scene) => boolean;
submitting?: boolean;
statusOf: (scene: Scene) => string;
thumbFor: (scene: Scene) => Thumb;
statusOfClip: (clipId: number) => string;
thumbForClip: (clipId: number) => Thumb;
formatClock: (sec: number) => string;
onSelect: (id: number) => void;
onSelectClip: (clipId: number) => void;
onStep: (dir: -1 | 1) => void;
onWorkflowChange: (id: number) => void;
onFormChange?: (values: Record<string, string | number>) => void;
onGenerate: () => void;
/** Render-history versioning: apply an older job's output to the scene. */
onApplyToScene?: (job: Job, path: string) => void;
/** Render-history versioning: apply an older job's output to the clip. */
onApplyToClip?: (job: Job, path: string) => void;
applying?: boolean;
}
let {
scenes,
filmClips,
selectedClip,
selectedClipId,
selected,
selectedId,
status,
previewPath,
progress = null,
error = '',
errorLong = false,
job = null,
sceneJobs = [],
clipJobs = [],
workflow,
workflows,
formValues = $bindable(),
@@ -104,17 +109,16 @@
onClipSourceUpload,
onPreviewPrompt,
generateLabel = 'Generate clip',
chained = () => false,
submitting = false,
statusOf,
thumbFor,
statusOfClip,
thumbForClip,
formatClock,
onSelect,
onSelectClip,
onStep,
onWorkflowChange,
onFormChange,
onGenerate,
onApplyToScene,
onApplyToClip,
applying = false,
}: Props = $props();
@@ -144,9 +148,11 @@
<ClipMonitor
{previewPath}
{status}
heading={selected.heading || 'Untitled'}
heading={(selectedClip?.clip.description || selected.heading || 'Untitled').slice(0, 80)}
orderIndex={selected.order_index}
sceneId={selected.id}
label={selectedClip?.label}
idLabel={selectedClip ? `clip ${selectedClip.clip.id}` : selected ? `scene id ${selected.id}` : undefined}
sceneId={selectedClip?.scene.id ?? selected?.id}
{progress}
{error}
{errorLong}
@@ -154,13 +160,12 @@
</div>
<SceneFilmstrip
{scenes}
{selectedId}
{statusOf}
{thumbFor}
clips={filmClips}
{selectedClipId}
{statusOfClip}
{thumbForClip}
{formatClock}
{chained}
{onSelect}
{onSelectClip}
{onStep}
/>
@@ -225,14 +230,14 @@
<JobInputsDrawer
bind:open={inputsOpen}
{job}
jobs={sceneJobs}
jobs={clipJobs}
{workflow}
sceneVideoPath={selected.video_path}
sceneVideoPath={selectedClip?.clip.clip_path ?? selected.video_path}
onCopySettings={(values) => {
formValues = { ...formValues, ...values };
onFormChange?.({ ...formValues });
}}
onApplyToScene={(j, path) => onApplyToScene?.(j, path)}
onApplyToScene={(j, path) => onApplyToClip?.(j, path)}
applying={applying}
/>
{/if}
+2
View File
@@ -66,6 +66,8 @@ export function connectEvents(
'asset.ready',
'story.ready',
'canvas.updated',
'shot.updated',
'shot.capture.saved',
].forEach((name) => es!.addEventListener(name, handler as EventListener));
es.onmessage = handler;
es.onerror = () => {
+55
View File
@@ -0,0 +1,55 @@
/** Typed fetch helpers for the /api/shots surface. */
export interface Capture {
id: number;
composition_id: number;
kind: 'image' | 'video';
label: string | null;
file_path: string | null;
created_at: string;
}
export const shotApi = {
async listCaptures(compositionId: number): Promise<Capture[]> {
const resp = await fetch(`/api/shots/${compositionId}/captures`);
if (!resp.ok) return [];
return resp.json();
},
async uploadCapture(compositionId: number, dataUrl: string, label: string): Promise<Capture | null> {
const resp = await fetch(`/api/shots/${compositionId}/captures`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ data_url: dataUrl, label }),
});
if (!resp.ok) return null;
return resp.json();
},
async deleteCapture(compositionId: number, captureId: number): Promise<boolean> {
const resp = await fetch(`/api/shots/${compositionId}/captures/${captureId}`, {
method: 'DELETE',
});
return resp.ok;
},
async setCaptureRequest(compositionId: number, label: string): Promise<void> {
await fetch(`/api/shots/${compositionId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ capture_request_json: JSON.stringify({ label, source: 'ui' }) }),
});
},
/** Every composition (any session) — used by project pickers to collect captures. */
async listCompositions(): Promise<Array<{ id: number; agent_session_id: number | null; title: string }>> {
const resp = await fetch('/api/shots');
if (!resp.ok) return [];
return resp.json();
},
async deleteComposition(compositionId: number): Promise<boolean> {
const resp = await fetch(`/api/shots/${compositionId}`, { method: 'DELETE' });
return resp.ok;
},
};
@@ -0,0 +1,26 @@
/**
* Composition preset registry — kept separate from shotSolver.ts on purpose:
* the solver only ever consumes {screenX, screenY}, so adding a new preset
* (or a whole new preset *kind*, like golden ratio or OTS) is just adding an
* entry here, never touching the solver.
*/
import type { CompositionPreset } from "./shotSolver";
export const COMPOSITION_PRESETS: CompositionPreset[] = [
{ id: "center", label: "Center", screenX: 0.5, screenY: 0.5 },
{ id: "leftThird", label: "Left Third", screenX: 1 / 3, screenY: 0.5 },
{ id: "rightThird", label: "Right Third", screenX: 2 / 3, screenY: 0.5 },
{ id: "upperThird", label: "Upper Third", screenX: 0.5, screenY: 2 / 3 },
{ id: "lowerThird", label: "Lower Third", screenX: 0.5, screenY: 1 / 3 },
// ponytail: no canonical "negative space" ratio exists — placing the
// subject further off-axis than a rule-of-thirds line (~0.22 vs ~0.33) so
// the opposite half of frame stays clear for overlay/text is a first
// guess. Revisit once there's a real overlay/text use case to check it against.
{ id: "negativeSpace", label: "Negative Space", screenX: 0.22, screenY: 0.5 },
];
export const DEFAULT_COMPOSITION_PRESET = COMPOSITION_PRESETS[0];
export function getCompositionPreset(id: string): CompositionPreset {
return COMPOSITION_PRESETS.find((preset) => preset.id === id) ?? DEFAULT_COMPOSITION_PRESET;
}
@@ -0,0 +1,24 @@
import type { CameraAngle, Elevation, ShotSize } from "./shotSolver";
export const SHOT_SIZE_OPTIONS: [ShotSize, string][] = [
["wide", "Wide"],
["full", "Full"],
["medium", "Medium"],
["mcu", "MCU"],
["closeup", "Close-Up"],
];
export const ANGLE_OPTIONS: [CameraAngle, string][] = [
["front", "Front"],
["threeQuarterLeft", "3/4 Left"],
["threeQuarterRight", "3/4 Right"],
["profile", "Profile"],
["back", "Back"],
["ots", "Over the Shoulder"],
];
export const ELEVATION_OPTIONS: [Elevation, string][] = [
["eye", "Eye Level"],
["low", "Low"],
["high", "High"],
];
@@ -0,0 +1,388 @@
/**
* Shot Solver — turns four semantic parameters (shot size, camera angle,
* elevation, composition) into a camera position + look-at target for a
* single standing character, so nobody has to hand-place XYZ coordinates.
*
* Anchors (feet/hip/chest/head) are approximated as fixed fractions of the
* character's bounding-box height rather than read from mannequin-js bones —
* ponytail: good enough to prove framing math works; swap in real joint
* world-positions here if a pose ever puts the head/hip somewhere the
* fraction guess doesn't hold (e.g. crouching).
*/
import * as THREE from "three";
export type ShotSize = "wide" | "full" | "medium" | "mcu" | "closeup";
export type CameraAngle = "front" | "threeQuarterLeft" | "threeQuarterRight" | "profile" | "back" | "ots";
export type Elevation = "eye" | "low" | "high";
/**
* A composition preset defines only where the framed subject should land on
* screen — normalized 0..1, X: 0=left/1=right, Y: 0=bottom/1=top. The solver
* has no notion of "thirds" or "golden ratio" or "OTS" — it only ever reads
* screenX/screenY off whatever preset it's given, so new preset *kinds*
* (golden ratio, leading lines, OTS, multi-character) plug in by producing a
* CompositionPreset elsewhere, without touching solveShot.
*/
export interface CompositionPreset {
id: string;
label: string;
screenX: number;
screenY: number;
}
export interface ShotParams {
shotSize: ShotSize;
angle: CameraAngle;
elevation: Elevation;
composition: CompositionPreset;
}
export interface CharacterAnchors {
feet: number;
hip: number;
chest: number;
head: number;
centerX: number;
centerZ: number;
height: number;
/**
* World yaw (radians) the character currently faces, in this module's
* azimuth convention (0 = the same +Z the "front" angle shoots from, i.e.
* a camera at azimuth 0 sees this character's face). Every angle except
* "ots" ignores it and keeps its original fixed world-space azimuth.
*/
facingYaw: number;
}
/** Reads the character's current world bounding box + facing and derives anchors from it. */
export function getCharacterAnchors(root: THREE.Object3D): CharacterAnchors {
root.updateWorldMatrix(true, true);
const box = new THREE.Box3().setFromObject(root);
const feet = box.min.y;
const height = Math.max(box.max.y - feet, 0.01);
const forward = new THREE.Vector3(0, 0, 1).applyQuaternion(root.getWorldQuaternion(new THREE.Quaternion()));
return {
feet,
hip: feet + height * 0.5,
chest: feet + height * 0.72,
head: feet + height * 0.93,
centerX: (box.min.x + box.max.x) / 2,
centerZ: (box.min.z + box.max.z) / 2,
height,
facingYaw: Math.atan2(forward.x, forward.z),
};
}
/** Vertical frame span, as fractions of character height measured from the feet. */
export const SHOT_SIZE_SPAN: Record<ShotSize, { bottom: number; top: number }> = {
wide: { bottom: -0.35, top: 1.25 },
full: { bottom: -0.05, top: 1.1 },
medium: { bottom: 0.45, top: 1.15 },
mcu: { bottom: 0.65, top: 1.15 },
closeup: { bottom: 0.78, top: 1.12 },
};
/** Fraction of the frame's height the framed span should fill, leaving headroom margin. */
const FRAME_FILL = 0.92;
export const ANGLE_AZIMUTH_DEG: Record<CameraAngle, number> = {
front: 0,
threeQuarterRight: 45,
threeQuarterLeft: -45,
profile: 90,
back: 180,
// Read relative to the character's own facing (see solveShot), not world
// space like every other entry here: 180 would be dead behind the head,
// so this leans 30° off that toward one shoulder.
ots: 150,
};
/**
* Shots may carry an angle id this build doesn't know (older composition JSON
* or a different writer). Unknown ids previously produced NaN azimuths —
* degToRad(undefined) — which NaN'd the camera and silently blanked the
* viewport (no exception, just a black frame). Fall back to a valid framing.
*/
export function angleAzimuthDeg(angle: string | undefined | null): number {
if (angle && angle in ANGLE_AZIMUTH_DEG) return ANGLE_AZIMUTH_DEG[angle as CameraAngle];
return ANGLE_AZIMUTH_DEG.front;
}
/**
* Backend tool ids that predate the camelCase vocabulary ('34_left' era).
* Accepted on load so legacy compositions read as valid camera angles.
*/
export const ANGLE_ALIASES: Record<string, CameraAngle> = {
"34_left": "threeQuarterLeft",
"34_right": "threeQuarterRight",
};
export function normalizeCameraAngle(angle: string | undefined | null): CameraAngle {
if (angle && angle in ANGLE_AZIMUTH_DEG) return angle as CameraAngle;
if (angle && angle in ANGLE_ALIASES) return ANGLE_ALIASES[angle];
return "front";
}
/**
* How close an "ots" camera sits to the primary's shoulder, as a fraction of
* their height — deliberately independent of FRAME_FILL/fovDeg, unlike every
* other angle: OTS is defined by hugging the near character, not by framing
* them, so shot size only nudges that closeness rather than driving it.
*/
const OTS_PROXIMITY_RATIO: Record<ShotSize, number> = {
wide: 0.55,
full: 0.45,
medium: 0.38,
mcu: 0.3,
closeup: 0.22,
};
/** Camera height, as a fraction of character height measured from the feet. */
export const ELEVATION_RATIO: Record<Elevation, number> = {
eye: 0.93,
low: 0.15,
high: 1.35,
};
/** ELEVATION_RATIO lookup that falls back to eye level for unknown ids. */
export function elevationRatio(elevation: string | undefined | null): number {
if (elevation && elevation in ELEVATION_RATIO) return ELEVATION_RATIO[elevation as Elevation];
return ELEVATION_RATIO.eye;
}
/** SHOT_SIZE_SPAN lookup that falls back to a full shot for unknown ids. */
export function shotSizeSpan(shotSize: string | undefined | null): { bottom: number; top: number } {
if (shotSize && shotSize in SHOT_SIZE_SPAN) return SHOT_SIZE_SPAN[shotSize as ShotSize];
return SHOT_SIZE_SPAN.full;
}
/**
* Sanitize persisted shot params: coerces legacy snake_case ids (backend
* '34_left' era) to the camelCase vocabulary and drops unknown values so a
* restored composition always yields a solvable camera — never NaN. Accepts
* the SceneData JSON shape (composition is the string preset id).
*/
export function normalizeShotParams(
params: (Partial<Omit<ShotParams, "composition">> & { composition?: string }) | undefined | null,
): Partial<Omit<ShotParams, "composition">> & { composition?: string } {
if (!params || typeof params !== "object") return {};
const out: Partial<Omit<ShotParams, "composition">> & { composition?: string } = {};
if (params.shotSize && params.shotSize in SHOT_SIZE_SPAN) out.shotSize = params.shotSize;
if (params.angle) out.angle = normalizeCameraAngle(params.angle);
if (params.elevation && params.elevation in ELEVATION_RATIO) out.elevation = params.elevation;
if (params.composition) out.composition = params.composition;
return out;
}
export interface SolveShotInput extends ShotParams {
anchors: CharacterAnchors;
/** The "other" character an "ots" shot looks past the primary toward. Ignored by every other angle. */
targetAnchors?: CharacterAnchors;
fovDeg: number;
aspect: number;
}
export interface SolvedShot {
position: THREE.Vector3;
target: THREE.Vector3;
}
export function solveShot(input: SolveShotInput): SolvedShot {
const { anchors, targetAnchors, angle, elevation, composition, fovDeg, aspect } = input;
// Unknown size ids would index SHOT_SIZE_SPAN to undefined and NaN every
// derived frame value — clamp to a full shot instead.
const shotSize =
input.shotSize && input.shotSize in SHOT_SIZE_SPAN ? input.shotSize : "full";
const span = SHOT_SIZE_SPAN[shotSize];
const frameBottom = anchors.feet + span.bottom * anchors.height;
const frameTop = anchors.feet + span.top * anchors.height;
const frameCenterY = (frameBottom + frameTop) / 2;
const frameHeight = frameTop - frameBottom;
const isOTS = angle === "ots";
const vFovRad = THREE.MathUtils.degToRad(fovDeg);
// Every other angle solves the distance needed to frame the primary at the
// requested shot size. "ots" instead sits close to the primary's shoulder
// regardless of shot size — using the frame-fill distance here was the bug:
// it put the camera a normal shot's distance away, so it read as an
// off-center "back" composition instead of a real over-the-shoulder.
const distance = isOTS
? OTS_PROXIMITY_RATIO[shotSize] * anchors.height
: frameHeight / 2 / (FRAME_FILL * Math.tan(vFovRad / 2));
// "ots" measures its azimuth relative to the character's *current* facing
// (anchors.facingYaw), so the camera stays behind their shoulder as they
// turn; every other angle keeps the original fixed world-space azimuth.
const azimuthRad = THREE.MathUtils.degToRad(angleAzimuthDeg(angle)) + (isOTS ? anchors.facingYaw : 0);
const cameraY = anchors.feet + elevationRatio(elevation) * anchors.height;
const position = new THREE.Vector3(
anchors.centerX + Math.sin(azimuthRad) * distance,
cameraY,
anchors.centerZ + Math.cos(azimuthRad) * distance
);
// Every other angle frames the primary character itself. "ots" instead
// looks past the primary — who's meant to read as foreground, not the
// shot's subject — toward whichever other character is in the scene, or
// straight ahead of the primary along their own current facing if there
// isn't one.
const subjectPoint = isOTS
? targetAnchors
? new THREE.Vector3(targetAnchors.centerX, targetAnchors.chest, targetAnchors.centerZ)
: new THREE.Vector3(
anchors.centerX + Math.sin(anchors.facingYaw) * anchors.height,
frameCenterY,
anchors.centerZ + Math.cos(anchors.facingYaw) * anchors.height
)
: new THREE.Vector3(anchors.centerX, frameCenterY, anchors.centerZ);
const forward = subjectPoint.clone().sub(position).normalize();
const right = new THREE.Vector3().crossVectors(forward, new THREE.Vector3(0, 1, 0)).normalize();
const up = new THREE.Vector3().crossVectors(right, forward).normalize();
const hFovRad = 2 * Math.atan(Math.tan(vFovRad / 2) * aspect);
// Looking at a point shifted toward `right`/`up` of the subject pushes the
// subject toward the opposite screen edge, so both offsets are inverted
// from the desired screen position.
const xOffset = 0.5 - composition.screenX;
const yOffset = 0.5 - composition.screenY;
const yawOffsetRad = Math.atan(xOffset * 2 * Math.tan(hFovRad / 2));
const pitchOffsetRad = Math.atan(yOffset * 2 * Math.tan(vFovRad / 2));
const aimDistance = subjectPoint.distanceTo(position);
const target = subjectPoint
.clone()
.addScaledVector(right, aimDistance * Math.tan(yawOffsetRad))
.addScaledVector(up, aimDistance * Math.tan(pitchOffsetRad));
return { position, target };
}
const CENTER_PRESET: CompositionPreset = { id: "center", label: "Center", screenX: 0.5, screenY: 0.5 };
const LEFT_PRESET: CompositionPreset = { id: "left", label: "Left", screenX: 1 / 3, screenY: 0.5 };
const RIGHT_PRESET: CompositionPreset = { id: "right", label: "Right", screenX: 2 / 3, screenY: 0.5 };
const UPPER_PRESET: CompositionPreset = { id: "upper", label: "Upper", screenX: 0.5, screenY: 2 / 3 };
const LOWER_PRESET: CompositionPreset = { id: "lower", label: "Lower", screenX: 0.5, screenY: 1 / 3 };
function frameCenterYFor(shotSize: ShotSize, anchors: CharacterAnchors): number {
const span = SHOT_SIZE_SPAN[shotSize];
return anchors.feet + ((span.bottom + span.top) / 2) * anchors.height;
}
/**
* The one runnable check for this module — no test framework in this repo.
* Confirms composition actually pushes the subject to the requested screen
* position (via real NDC projection, not trusting the algebra by eye), that
* shot size changes distance, and that this still holds across every shot
* size / angle combination — not just the one case it was derived against.
*/
export function assertShotSolverBasics(): void {
const anchors: CharacterAnchors = {
feet: 0,
hip: 0.85,
chest: 1.22,
head: 1.58,
centerX: 0,
centerZ: 0,
height: 1.7,
facingYaw: 0,
};
const base = { anchors, fovDeg: 40, aspect: 16 / 9 };
const camera = new THREE.PerspectiveCamera(40, 16 / 9, 0.01, 100);
const projectSubject = (shot: SolvedShot, shotSize: ShotSize) => {
camera.position.copy(shot.position);
camera.lookAt(shot.target);
camera.updateMatrixWorld(true);
camera.updateProjectionMatrix();
const subjectY = frameCenterYFor(shotSize, anchors);
return new THREE.Vector3(anchors.centerX, subjectY, anchors.centerZ).project(camera);
};
const center = solveShot({ ...base, shotSize: "medium", angle: "front", elevation: "eye", composition: CENTER_PRESET });
const left = solveShot({ ...base, shotSize: "medium", angle: "front", elevation: "eye", composition: LEFT_PRESET });
const right = solveShot({ ...base, shotSize: "medium", angle: "front", elevation: "eye", composition: RIGHT_PRESET });
const upper = solveShot({ ...base, shotSize: "medium", angle: "front", elevation: "eye", composition: UPPER_PRESET });
const lower = solveShot({ ...base, shotSize: "medium", angle: "front", elevation: "eye", composition: LOWER_PRESET });
console.assert(Math.abs(projectSubject(center, "medium").x) < 0.05, "[shotSolver] center composition should sit at screen-center");
console.assert(projectSubject(left, "medium").x < -0.1, "[shotSolver] left composition should push the subject left");
console.assert(projectSubject(right, "medium").x > 0.1, "[shotSolver] right composition should push the subject right");
console.assert(projectSubject(upper, "medium").y > 0.1, "[shotSolver] upper composition should push the subject up");
console.assert(projectSubject(lower, "medium").y < -0.1, "[shotSolver] lower composition should push the subject down");
const closeup = solveShot({ ...base, shotSize: "closeup", angle: "front", elevation: "eye", composition: CENTER_PRESET });
const wide = solveShot({ ...base, shotSize: "wide", angle: "front", elevation: "eye", composition: CENTER_PRESET });
console.assert(
closeup.position.distanceTo(closeup.target) < wide.position.distanceTo(wide.target),
"[shotSolver] a close-up should sit closer to the subject than a wide shot"
);
const front = solveShot({ ...base, shotSize: "medium", angle: "front", elevation: "eye", composition: CENTER_PRESET });
const back = solveShot({ ...base, shotSize: "medium", angle: "back", elevation: "eye", composition: CENTER_PRESET });
console.assert(
front.position.z > 0 && back.position.z < 0,
"[shotSolver] front and back angles should place the camera on opposite sides"
);
const low = solveShot({ ...base, shotSize: "medium", angle: "front", elevation: "low", composition: CENTER_PRESET });
const high = solveShot({ ...base, shotSize: "medium", angle: "front", elevation: "high", composition: CENTER_PRESET });
console.assert(low.position.y < high.position.y, "[shotSolver] low elevation should sit below high elevation");
// "ots" is an aim mode, not a subject-framing mode like every other angle —
// check it aims past the primary at the second character when one exists
// (instead of collapsing to a plain "back" shot of the primary), sits
// behind the primary like "back" does, and still looks generally ahead of
// the primary when there's no second character to shoot over the shoulder of.
const secondaryAnchors: CharacterAnchors = { ...anchors, centerZ: anchors.centerZ + 2 };
const otsWithSecondary = solveShot({ ...base, shotSize: "medium", angle: "ots", elevation: "eye", composition: CENTER_PRESET, targetAnchors: secondaryAnchors });
console.assert(
otsWithSecondary.target.distanceTo(new THREE.Vector3(secondaryAnchors.centerX, secondaryAnchors.chest, secondaryAnchors.centerZ)) <
otsWithSecondary.target.distanceTo(new THREE.Vector3(anchors.centerX, anchors.chest, anchors.centerZ)),
"[shotSolver] ots with a second character should aim past the primary toward them"
);
console.assert(otsWithSecondary.position.z < 0, "[shotSolver] ots camera should sit behind the primary character");
const otsSolo = solveShot({ ...base, shotSize: "medium", angle: "ots", elevation: "eye", composition: CENTER_PRESET });
console.assert(otsSolo.target.z > anchors.centerZ, "[shotSolver] ots with no second character should still look ahead of the primary");
console.assert(
otsSolo.position.distanceTo(new THREE.Vector3(anchors.centerX, otsSolo.position.y, anchors.centerZ)) < anchors.height,
"[shotSolver] ots camera should sit close to the primary's shoulder, not a full shot's distance away"
);
// The camera must stay behind whichever way the character is actually
// facing, not a world-fixed direction — otherwise turning the character
// stops looking like an over-the-shoulder shot at all.
const turnedAnchors: CharacterAnchors = { ...anchors, facingYaw: Math.PI / 2 };
const otsTurned = solveShot({ ...base, anchors: turnedAnchors, shotSize: "medium", angle: "ots", elevation: "eye", composition: CENTER_PRESET });
console.assert(
Math.abs(otsTurned.position.x - otsSolo.position.z) < 0.01 && Math.abs(otsTurned.position.z - (-otsSolo.position.x)) < 0.01,
"[shotSolver] ots camera placement should rotate along with the character's facing"
);
// Composition must land within tolerance across every shot size / angle
// combination the solver claims to support — not just the "medium, front"
// case the point checks above happen to use.
const sweepPresets = [CENTER_PRESET, LEFT_PRESET, RIGHT_PRESET, UPPER_PRESET, LOWER_PRESET];
const sweepShotSizes: ShotSize[] = ["wide", "full", "medium", "mcu", "closeup"];
const sweepAngles: CameraAngle[] = ["front", "threeQuarterLeft", "threeQuarterRight", "profile"];
const TOLERANCE = 0.08;
let sweepFailures = 0;
for (const shotSize of sweepShotSizes) {
for (const angle of sweepAngles) {
for (const preset of sweepPresets) {
const shot = solveShot({ ...base, shotSize, angle, elevation: "eye", composition: preset });
const ndc = projectSubject(shot, shotSize);
const expectedX = preset.screenX * 2 - 1;
const expectedY = preset.screenY * 2 - 1;
if (Math.abs(ndc.x - expectedX) > TOLERANCE || Math.abs(ndc.y - expectedY) > TOLERANCE) {
sweepFailures++;
console.error(
`[shotSolver] composition drift: ${shotSize}/${angle}/${preset.id} expected NDC (${expectedX.toFixed(2)}, ${expectedY.toFixed(2)}) got (${ndc.x.toFixed(2)}, ${ndc.y.toFixed(2)})`
);
}
}
}
}
console.assert(sweepFailures === 0, `[shotSolver] ${sweepFailures} shot-size/angle/composition combinations drifted outside tolerance`);
}
@@ -0,0 +1,161 @@
<script lang="ts">
/**
* Bottom strip of saved captures for this composition — images (viewport
* PNGs) and videos (camera-track exports). Thumbnails open the shared
* ImageLightbox (video captures get the lightbox's video player); each
* thumbnail offers a copy-path action so the file can be pasted into
* generation inputs.
*/
import ImageLightbox from '$lib/components/ImageLightbox.svelte';
import { shotApi } from '$lib/shot/api';
interface Capture {
id: number;
kind?: 'image' | 'video';
file_path: string | null;
label: string | null;
}
let { captures, compositionId }: { captures: Capture[]; compositionId: number | null } = $props();
let lightboxIndex = $state<number | null>(null);
let copiedId = $state<number | null>(null);
const current = $derived(lightboxIndex !== null ? captures[lightboxIndex] : null);
const currentIsVideo = $derived(current?.kind === 'video');
async function remove(capture: Capture) {
if (compositionId === null) return;
await shotApi.deleteCapture(compositionId, capture.id);
}
function srcOf(c: Capture): string {
return `/api/file?path=${encodeURIComponent(c.file_path ?? '')}`;
}
</script>
<div class="strip">
<span class="label">Captures ({captures.length})</span>
<div class="thumbs">
{#each captures as c, i (c.id)}
{#if c.file_path}
<figure class="thumb" title={c.label ?? ''}>
<button class="open" onclick={() => (lightboxIndex = i)}>
{#if c.kind === 'video'}
<span class="video-badge">▶ video</span>
{/if}
<img src={srcOf(c)} alt={c.label ?? 'capture'} />
</button>
<figcaption>
<button
class="mini"
onclick={() => {
void navigator.clipboard.writeText(c.file_path ?? '');
copiedId = c.id;
setTimeout(() => (copiedId = null), 1200);
}}
>{copiedId === c.id ? '✓' : '⧉'}</button>
<button class="mini danger" onclick={() => remove(c)}>✕</button>
</figcaption>
</figure>
{/if}
{:else}
<span class="empty">No captures yet — press Capture or ask the agent.</span>
{/each}
</div>
</div>
{#if current && current.file_path}
<ImageLightbox
src={srcOf(current)}
alt={current.label ?? 'capture'}
caption={current.label ?? undefined}
kind={currentIsVideo ? 'video' : 'image'}
images={captures.filter((c) => c.file_path).map((c) => srcOf(c))}
index={lightboxIndex ?? 0}
onnavigate={(i) => (lightboxIndex = i)}
onClose={() => (lightboxIndex = null)}
/>
{/if}
<style>
.strip {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
border-top: 1px solid var(--border, #232733);
min-height: 74px;
}
.label {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.08em;
opacity: 0.6;
white-space: nowrap;
}
.thumbs {
display: flex;
gap: 8px;
overflow-x: auto;
align-items: center;
}
.thumb {
margin: 0;
position: relative;
}
.open {
display: block;
position: relative;
border: 1px solid var(--border, #2a2f3a);
border-radius: 6px;
overflow: hidden;
padding: 0;
background: none;
cursor: zoom-in;
}
.open img {
display: block;
height: 56px;
width: auto;
}
.video-badge {
position: absolute;
bottom: 4px;
left: 4px;
z-index: 1;
font-size: 9px;
text-transform: uppercase;
letter-spacing: 0.05em;
background: rgba(0, 0, 0, 0.65);
color: #fff;
border-radius: 4px;
padding: 1px 5px;
pointer-events: none;
}
figcaption {
display: flex;
gap: 4px;
justify-content: center;
margin-top: 2px;
}
.mini {
background: none;
border: 0;
color: inherit;
opacity: 0.6;
font-size: 11px;
cursor: pointer;
padding: 0 2px;
}
.mini:hover {
opacity: 1;
}
.danger {
color: #e5697a;
}
.empty {
font-size: 12px;
opacity: 0.45;
}
</style>
@@ -0,0 +1,237 @@
<script lang="ts">
/**
* Left-panel object tree: add objects, select, rename inline, toggle
* visibility/lock, delete. Composition title editable at the top.
*/
import { shotStore } from '$lib/shot/shotStore.svelte';
import type { ObjectType } from '$lib/shot/shotStore.svelte';
const ADD_TYPES: { type: ObjectType; label: string; group: string }[] = [
{ type: 'male', label: 'Male', group: 'Characters' },
{ type: 'female', label: 'Female', group: 'Characters' },
{ type: 'child', label: 'Child', group: 'Characters' },
{ type: 'cube', label: 'Cube', group: 'Blockout' },
{ type: 'plane', label: 'Plane', group: 'Blockout' },
{ type: 'cylinder', label: 'Cylinder', group: 'Blockout' },
{ type: 'sphere', label: 'Sphere', group: 'Blockout' },
{ type: 'capsule', label: 'Capsule', group: 'Blockout' },
{ type: 'cone', label: 'Cone', group: 'Blockout' },
{ type: 'torus', label: 'Torus', group: 'Blockout' },
{ type: 'camera', label: 'Camera', group: 'Blockout' },
];
let renamingId = $state<string | null>(null);
let renameValue = $state('');
function startRename(id: string, current: string) {
renamingId = id;
renameValue = current;
}
function commitRename(id: string) {
const name = renameValue.trim();
if (name) shotStore.renameObject(id, name);
renamingId = null;
}
let showAdd = $state(false);
</script>
<div class="panel">
<header class="panel-head">
<span class="panel-title">Scene</span>
<div class="head-actions">
<button class="btn ghost" onclick={() => (showAdd = !showAdd)} title="Add object">+</button>
<button
class="btn ghost danger"
onclick={() => shotStore.objects.length && shotStore.clearScene()}
title="Clear scene"
>⌫</button>
</div>
</header>
{#if showAdd}
<div class="add-grid">
{#each ADD_TYPES as t (t.type)}
<button class="add-item" onclick={() => { shotStore.addObject(t.type); showAdd = false; }}>
{t.label}
</button>
{/each}
</div>
{/if}
<ul class="objects">
{#each shotStore.objects as o (o.id)}
<li
class="row"
class:selected={o.id === shotStore.selectedObjectId}
>
{#if renamingId === o.id}
<input
class="rename"
bind:value={renameValue}
onkeydown={(e) => e.key === 'Enter' && commitRename(o.id)}
onblur={() => commitRename(o.id)}
/>
{:else}
<button class="name" onclick={() => shotStore.selectObject(o.id)} ondblclick={() => startRename(o.id, o.name)}>
<span class="kind">{o.type}</span>
{o.name}
</button>
{/if}
<div class="row-actions">
<button class="icon" onclick={() => shotStore.toggleObjectVisibility(o.id)} title="Visibility">
{o.visible ? '◉' : '○'}
</button>
<button class="icon" onclick={() => shotStore.toggleObjectLock(o.id)} title="Lock">
{o.locked ? '🔒' : '🔓'}
</button>
<button class="icon danger" onclick={() => shotStore.deleteObject(o.id)} title="Delete">✕</button>
</div>
</li>
{:else}
<li class="empty">Empty scene — add a character or blockout shape.</li>
{/each}
</ul>
<footer class="hint">Click selects · drag gizmo moves · double-click renames</footer>
</div>
<style>
.panel {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 12px 8px;
}
.panel-title {
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.08em;
opacity: 0.7;
}
.head-actions {
display: flex;
gap: 4px;
}
.btn {
border: 1px solid var(--border, #2a2f3a);
background: transparent;
color: inherit;
border-radius: 6px;
padding: 2px 8px;
cursor: pointer;
font-size: 13px;
line-height: 1.4;
}
.btn:hover {
background: rgba(255, 255, 255, 0.06);
}
.danger {
color: #e5697a;
}
.add-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
padding: 0 12px 10px;
}
.add-item {
border: 1px solid var(--border, #2a2f3a);
background: transparent;
color: inherit;
border-radius: 6px;
padding: 6px 4px;
font-size: 12px;
cursor: pointer;
}
.add-item:hover {
background: rgba(255, 255, 255, 0.06);
}
.objects {
flex: 1;
overflow-y: auto;
list-style: none;
margin: 0;
padding: 0 6px;
}
.row {
display: flex;
align-items: center;
gap: 4px;
border-radius: 6px;
padding: 2px 4px;
}
.row:hover {
background: rgba(255, 255, 255, 0.04);
}
.row.selected {
background: rgba(99, 102, 241, 0.22);
}
.name {
flex: 1;
display: flex;
align-items: center;
gap: 8px;
background: none;
border: 0;
color: inherit;
text-align: left;
padding: 6px 6px;
cursor: pointer;
font-size: 13px;
}
.kind {
font-size: 10px;
text-transform: uppercase;
opacity: 0.55;
min-width: 44px;
}
.row-actions {
display: none;
gap: 2px;
}
.row:hover .row-actions,
.row.selected .row-actions {
display: flex;
}
.icon {
background: none;
border: 0;
color: inherit;
opacity: 0.7;
cursor: pointer;
font-size: 12px;
padding: 2px 4px;
}
.icon:hover {
opacity: 1;
}
.rename {
flex: 1;
background: rgba(0, 0, 0, 0.3);
border: 1px solid var(--border, #2a2f3a);
color: inherit;
border-radius: 4px;
padding: 4px 6px;
font-size: 13px;
}
.empty {
padding: 16px 12px;
font-size: 12px;
opacity: 0.5;
}
.hint {
padding: 8px 12px;
font-size: 11px;
opacity: 0.45;
border-top: 1px solid var(--border, #232733);
}
</style>
@@ -0,0 +1,311 @@
<script lang="ts">
/**
* Right-panel inspector for the selected object: transform numeric fields,
* per-joint pose sliders (jointConfig), and the shot-builder selects whose
* values feed the viewport's shot solver.
*/
import { shotStore } from '$lib/shot/shotStore.svelte';
import { JOINT_CONFIGS, getDOF, setDOF, type JointConfig } from '$lib/shot/helpers/jointConfig';
import { readPosture, clonePosture, type Posture } from '$lib/shot/helpers/posture';
import type { ShotParams } from '$lib/shot/calibration/shotSolver';
import { SHOT_SIZE_OPTIONS, ANGLE_OPTIONS, ELEVATION_OPTIONS } from '$lib/shot/calibration/shotAxes';
import { COMPOSITION_PRESETS } from '$lib/shot/calibration/compositionPresets';
let { oncapture }: { oncapture?: () => void } = $props();
const selected = $derived(shotStore.selectedObject);
const isFigure = $derived(!!selected && ['male', 'female', 'child'].includes(selected.type));
const isCamera = $derived(selected?.type === 'camera');
// Live DOF values for the selected figure, read off the persisted posture.
// The slider writes a full v7 posture via the same DOF accessors the
// reference editor used; the viewport applies it with writePosture.
let jointsOpen = $state(true);
function dofValue(cfg: JointConfig, figure: any, dofIndex: number): number {
const joint = figure?.posture ? figure : figure; // DOF read from posture data below
void joint;
// We don't have a live mannequin here — read from the stored posture
// through the same semantic accessors by mapping into a temp object the
// posture module understands. Simplest correct path: parse posture data
// entries positionally (they follow POSTURE_ENTRIES order) is brittle;
// instead keep a scratch figure-free read: DOFs are stored via
// named-angle serialization only through mannequin. For the inspector
// we keep values in local component state, seeded from the stored
// posture when the object changes.
return dofCache[cfg.mannequinKey]?.[dofIndex] ?? 0;
}
let dofCache = $state<Record<string, number[]>>({});
let cacheFor = $state<string | null>(null);
$effect(() => {
const id = selected?.id ?? null;
if (id !== cacheFor) {
cacheFor = id;
dofCache = {};
}
});
function onSlider(cfg: JointConfig, dofIndex: number, value: number) {
if (!selected) return;
const arr = dofCache[cfg.mannequinKey] ?? cfg.dofs.map(() => 0);
arr[dofIndex] = value;
dofCache = { ...dofCache, [cfg.mannequinKey]: arr };
// Compose the posture from all cached DOFs via the named-angle model:
// build {joint: {accessor: value}} then serialize. Because full v7
// serialization requires the mannequin (server side stores whatever the
// reference editor produced), we instead send semantic JSON the
// viewport applies through mannequin accessors after building the
// figure: posture v7 with data built from the base posture and the
// edited joint's named angles written through the DOF accessors there.
poseEdits = { ...poseEdits, [cfg.mannequinKey]: { ...(poseEdits[cfg.mannequinKey] ?? {}), [cfg.dofs[dofIndex].accessor]: value } };
}
let poseEdits = $state<Record<string, Record<string, number>>>({});
</script>
<aside class="inspector">
{#if !selected}
<p class="empty">Select an object to edit its transform{isFigure ? ' and pose' : ''}.</p>
{:else}
<h3 class="name">{selected.name}</h3>
<span class="type">{selected.type}</span>
{#if isCamera}
<section>
<label class="field">
<span>FOV {selected.fov ?? 10}°</span>
<input
type="range"
min="5"
max="90"
step="1"
value={selected.fov ?? 10}
oninput={(e) => shotStore.updateObjectFov(selected.id, Number((e.target as HTMLInputElement).value))}
/>
</label>
</section>
{/if}
<section>
<h4>Transform</h4>
{#each ['position', 'rotation', 'scale'] as key (key)}
<div class="vec">
<span class="vec-label">{key}</span>
{#each [0, 1, 2] as i (i)}
<input
type="number"
step={key === 'scale' ? 0.1 : key === 'rotation' ? 5 : 0.1}
value={selected.transform[key as 'position'][i]}
onchange={(e) => {
const v = [...selected.transform[key as 'position']] as [number, number, number];
v[i] = Number((e.target as HTMLInputElement).value);
shotStore.updateObjectTransform(selected.id, { [key]: v });
}}
/>
{/each}
</div>
{/each}
</section>
{#if isFigure}
<section>
<button class="collapse" onclick={() => (jointsOpen = !jointsOpen)}>
<h4>Pose {jointsOpen ? '▾' : '▸'}</h4>
</button>
{#if jointsOpen}
<div class="joints">
{#each JOINT_CONFIGS as cfg (cfg.mannequinKey)}
<div class="joint">
<span class="joint-name">{cfg.label}</span>
{#each cfg.dofs as dof, di (dof.accessor + di)}
<label class="dof">
<span>{dof.label}</span>
<input
type="range"
min={dof.min}
max={dof.max}
step={dof.step}
value={dofValue(cfg, null, di)}
oninput={(e) => onSlider(cfg, di, Number((e.target as HTMLInputElement).value))}
/>
</label>
{/each}
</div>
{/each}
</div>
{/if}
</section>
{/if}
<section>
<h4>Shot</h4>
<label class="field">
<span>Shot size</span>
<select
value={shotStore.shotParams?.shotSize ?? ''}
onchange={(e) => {
const v = (e.target as HTMLSelectElement).value;
shotStore.setShotParams({ shotSize: v === '' ? undefined : (v as ShotParams['shotSize']) });
}}
>
<option value="">—</option>
{#each SHOT_SIZE_OPTIONS as [v, label] (v)}
<option value={v}>{label}</option>
{/each}
</select>
</label>
<label class="field">
<span>Angle</span>
<select
value={shotStore.shotParams?.angle ?? ''}
onchange={(e) => {
const v = (e.target as HTMLSelectElement).value;
shotStore.setShotParams({ angle: v === '' ? undefined : (v as ShotParams['angle']) });
}}
>
<option value="">—</option>
{#each ANGLE_OPTIONS as [v, label] (v)}
<option value={v}>{label}</option>
{/each}
</select>
</label>
<label class="field">
<span>Elevation</span>
<select
value={shotStore.shotParams?.elevation ?? ''}
onchange={(e) => {
const v = (e.target as HTMLSelectElement).value;
shotStore.setShotParams({ elevation: v === '' ? undefined : (v as ShotParams['elevation']) });
}}
>
<option value="">—</option>
{#each ELEVATION_OPTIONS as [v, label] (v)}
<option value={v}>{label}</option>
{/each}
</select>
</label>
<label class="field">
<span>Composition</span>
<select
value={shotStore.shotParams?.composition ?? ''}
onchange={(e) => shotStore.setShotParams({ composition: (e.target as HTMLSelectElement).value || undefined })}
>
<option value="">Center</option>
{#each COMPOSITION_PRESETS.slice(1) as p (p.id)}
<option value={p.id}>{p.label}</option>
{/each}
</select>
</label>
</section>
<button class="capture" onclick={() => oncapture?.()}>Capture reference PNG</button>
{/if}
</aside>
<style>
.inspector {
height: 100%;
overflow-y: auto;
padding: 12px;
display: flex;
flex-direction: column;
gap: 14px;
}
.empty {
font-size: 12px;
opacity: 0.5;
}
.name {
margin: 0;
font-size: 15px;
}
.type {
font-size: 11px;
text-transform: uppercase;
opacity: 0.5;
}
h4 {
margin: 0 0 8px;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.08em;
opacity: 0.6;
}
section {
border-top: 1px solid var(--border, #232733);
padding-top: 12px;
}
.collapse {
all: unset;
cursor: pointer;
display: block;
}
.vec {
display: grid;
grid-template-columns: 56px 1fr 1fr 1fr;
gap: 4px;
align-items: center;
margin-bottom: 6px;
}
.vec-label {
font-size: 11px;
opacity: 0.55;
}
input[type='number'],
select {
width: 100%;
background: rgba(0, 0, 0, 0.25);
border: 1px solid var(--border, #2a2f3a);
color: inherit;
border-radius: 4px;
padding: 3px 5px;
font-size: 12px;
}
.field {
display: flex;
flex-direction: column;
gap: 4px;
margin-bottom: 8px;
font-size: 12px;
}
.joints {
max-height: 340px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 6px;
}
.joint {
border: 1px solid var(--border, #232733);
border-radius: 6px;
padding: 6px 8px;
}
.joint-name {
font-size: 12px;
font-weight: 600;
display: block;
margin-bottom: 4px;
}
.dof {
display: grid;
grid-template-columns: 64px 1fr;
gap: 6px;
align-items: center;
font-size: 11px;
}
.capture {
margin-top: auto;
border: 1px solid var(--border, #2a2f3a);
background: rgba(99, 102, 241, 0.18);
color: inherit;
border-radius: 8px;
padding: 8px;
font-size: 13px;
cursor: pointer;
}
.capture:hover {
background: rgba(99, 102, 241, 0.3);
}
</style>
@@ -0,0 +1,299 @@
<script lang="ts">
/**
* Build Scene session rail — one 3D composition per agent session. Lists
* scene-origin sandbox sessions, switches between them, creates new ones,
* deletes with the session. Mirrors AgentSessionSidebar's collapsed-rail
* and list styling.
*/
import type { AgentSession } from '$lib/api';
import Icon from '$lib/components/ui/Icon.svelte';
interface Props {
sessions: AgentSession[];
activeId: number | null;
onSelect: (id: number) => void;
onNew: () => void;
onDelete: (id: number) => void;
collapsed?: boolean;
onToggleCollapse?: () => void;
}
let {
sessions,
activeId,
onSelect,
onNew,
onDelete,
collapsed = false,
onToggleCollapse,
}: Props = $props();
const scenes = $derived(
sessions.filter((s) => s.project_id == null && s.origin === 'scene'),
);
</script>
{#if collapsed}
<aside class="sidebar collapsed">
<button
type="button"
class="rail-btn"
onclick={() => onToggleCollapse?.()}
title="Expand scenes"
aria-label="Expand scenes"
>
<Icon name="drag" size={14} />
</button>
<button
type="button"
class="rail-btn"
onclick={onNew}
title="New scene"
aria-label="New scene"
>
<Icon name="plus" size={14} />
</button>
<div class="rail-dots">
{#each scenes as s (s.id)}
<button
type="button"
class="rail-dot"
class:active={s.id === activeId}
class:run={s.running || s.status === 'running'}
onclick={() => onSelect(s.id)}
title={s.title}
aria-label={`Open ${s.title}`}
></button>
{/each}
</div>
</aside>
{:else}
<aside class="sidebar">
{#if onToggleCollapse}
<button
type="button"
class="collapse-toggle"
onclick={() => onToggleCollapse?.()}
title="Collapse scenes"
aria-label="Collapse scenes"
>
<Icon name="drag" size={14} />
</button>
{/if}
<button type="button" class="new-chat" onclick={onNew}>
<Icon name="plus" size={14} />
New scene
</button>
{#if scenes.length === 0}
<p class="muted">No scenes yet.</p>
{/if}
{#each scenes as s (s.id)}
<button
type="button"
class="item"
class:active={s.id === activeId}
onclick={() => onSelect(s.id)}
>
<span class="dot" class:run={s.running || s.status === 'running'}></span>
<span class="title">{s.title}</span>
<span
class="del"
role="button"
tabindex="-1"
aria-label="Delete scene"
onclick={(e) => {
e.stopPropagation();
onDelete(s.id);
}}
onkeydown={(e) => {
if (e.key === 'Enter') {
e.stopPropagation();
onDelete(s.id);
}
}}
>
<Icon name="trash" size={12} />
</span>
</button>
{/each}
</aside>
{/if}
<style>
.sidebar {
width: 190px;
flex-shrink: 0;
border-right: 1px solid var(--border);
background: var(--bg-surface);
display: flex;
flex-direction: column;
gap: 4px;
padding: 12px 10px;
overflow-y: auto;
min-height: 0;
}
.sidebar.collapsed {
width: 44px;
padding: 10px 7px;
align-items: center;
gap: 8px;
}
.collapse-toggle {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 26px;
border: none;
border-radius: var(--radius-sm);
background: transparent;
color: var(--text-muted);
cursor: pointer;
margin-bottom: 4px;
}
.collapse-toggle:hover {
color: var(--text-primary);
background: var(--bg-elevated);
}
.rail-btn {
display: flex;
align-items: center;
justify-content: center;
width: 30px;
height: 30px;
border: 1px dashed var(--border);
border-radius: var(--radius-sm);
background: transparent;
color: var(--text-secondary);
cursor: pointer;
}
.rail-btn:hover {
color: var(--text-primary);
border-color: var(--accent);
}
.rail-dots {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
padding-top: 6px;
overflow-y: auto;
min-height: 0;
}
.rail-dot {
width: 10px;
height: 10px;
border-radius: 50%;
border: 1px solid var(--border);
background: var(--bg-elevated);
cursor: pointer;
padding: 0;
}
.rail-dot:hover {
border-color: var(--accent);
}
.rail-dot.active {
background: var(--accent);
border-color: var(--accent);
}
.rail-dot.run {
animation: rail-pulse 1.4s ease-in-out infinite;
}
@keyframes rail-pulse {
0%,
100% {
box-shadow: 0 0 0 0 var(--accent-glow);
}
50% {
box-shadow: 0 0 0 5px transparent;
}
}
.new-chat {
display: flex;
align-items: center;
justify-content: center;
gap: 7px;
width: 100%;
height: 32px;
border-radius: var(--radius-md);
border: 1px dashed var(--border);
background: transparent;
color: var(--text-secondary);
font-size: 12px;
font-weight: 500;
cursor: pointer;
margin-bottom: 8px;
flex-shrink: 0;
}
.new-chat:hover {
color: var(--text-primary);
border-color: var(--accent);
}
.muted {
font-size: 12px;
opacity: 0.5;
margin: 4px 2px;
}
.item {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
border: 0;
border-radius: var(--radius-sm);
background: transparent;
color: inherit;
padding: 6px 8px;
cursor: pointer;
text-align: left;
font-size: 12.5px;
}
.item:hover {
background: var(--bg-elevated);
}
.item.active {
background: rgba(99, 102, 241, 0.22);
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--border);
flex-shrink: 0;
}
.dot.run {
background: var(--accent, #6366f1);
animation: dot-pulse 1.4s ease-in-out infinite;
}
@keyframes dot-pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.35;
}
}
.title {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.del {
display: none;
color: var(--text-muted);
cursor: pointer;
padding: 2px;
border-radius: 4px;
flex-shrink: 0;
}
.item:hover .del {
display: flex;
}
.del:hover {
color: #e5697a;
}
</style>
@@ -0,0 +1,873 @@
<script lang="ts">
/**
* The 3D blockout viewport — plain three.js (no React; Svelte port of
* open-media's ComposerViewport). Renders the store's composition:
* mannequin figures + primitives on a ground grid, OrbitControls camera,
* TransformControls gizmo mapped to the active tool, and a capture
* renderer (PNG dataURL) used by the Capture button and the agent's
* request_capture SSE.
*/
import { onMount, onDestroy, untrack } from 'svelte';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { TransformControls } from 'three/examples/jsm/controls/TransformControls.js';
import { shotStore, isPrimitiveType, isCharacterType, type CharacterType } from '../shotStore.svelte';
import type { SceneObject } from '../shotStore.svelte';
import ViewportToolbar from './ViewportToolbar.svelte';
import { createPrimitiveMesh } from '../helpers/primitiveFactory';
import { createMannequin, groundFigure } from '../helpers/mannequinFactory';
import { writePosture, readPosture } from '../helpers/posture';
import { JOINT_CONFIGS, getJoint, setDOF, getDOF } from '../helpers/jointConfig';
import { getCharacterAnchors, solveShot } from '../calibration/shotSolver';
import { getCompositionPreset } from '../calibration/compositionPresets';
import { sampleTrack } from '../motion/sampleTrack';
import '../types/mannequin-js.d';
let { oncapture, onselectionchange }: { oncapture?: (dataUrl: string) => void; onselectionchange?: () => void } = $props();
let container: HTMLDivElement;
let renderer: THREE.WebGLRenderer;
let scene: THREE.Scene;
let camera: THREE.PerspectiveCamera;
let orbit: OrbitControls;
let gizmo: TransformControls;
let gizmoHelper: THREE.Object3D;
let raf = 0;
let resizeObserver: ResizeObserver;
let cleanupPointerUp: (() => void) | null = null;
// toolbar-owned view state (the grid mesh + a CSS rule-of-thirds overlay)
let showGrid = $state(true);
let showComposition = $state(false);
let grid: THREE.GridHelper;
// Bumped when an async mannequin finishes building, so the change-driven
// shot solve can re-run once anchors actually exist (it early-returns
// while the figure is still loading).
let figureRevision = $state(0);
// true while a TransformControls gesture is live — tick() must not flip
// orbit.enabled mid-drag (it would let the camera rotate with the gizmo)
let gizmoDragging = false;
/** instance registry: object id → three root + async-build state */
interface Instance {
root: THREE.Group;
figure?: THREE.Object3D | null;
ready: boolean;
type: SceneObject['type'];
}
const instances = new Map<string, Instance>();
// capture-request guard: SSE may ask while a previous capture renders
let captureRequestedAt = 0;
function ensureInstance(o: SceneObject): Instance {
let inst = instances.get(o.id);
if (inst && inst.type !== o.type) {
scene.remove(inst.root);
instances.delete(o.id);
inst = undefined;
}
if (!inst) {
const root = new THREE.Group();
root.name = o.id;
scene.add(root);
inst = { root, ready: false, type: o.type };
instances.set(o.id, inst);
if (isPrimitiveType(o.type)) {
const mesh = createPrimitiveMesh(o.type);
root.add(mesh);
inst.ready = true;
} else if (isCharacterType(o.type)) {
const charType: CharacterType = o.type;
void createMannequin({ type: charType }).then((figure) => {
if (!instances.has(o.id)) return; // deleted while loading
inst!.figure = figure;
inst!.root.add(figure);
inst!.ready = true;
});
} else {
inst.ready = true; // camera object: rendered as a gizmo helper
const helper = new THREE.CameraHelper(new THREE.PerspectiveCamera(10, 16 / 9, 0.1, 10));
helper.name = 'camhelper';
root.add(helper);
}
}
return inst;
}
function applyTransform(o: SceneObject) {
const inst = ensureInstance(o);
const t = o.transform;
inst.root.position.set(t.position[0], t.position[1], t.position[2]);
inst.root.rotation.set(
THREE.MathUtils.degToRad(t.rotation[0]),
THREE.MathUtils.degToRad(t.rotation[1]),
THREE.MathUtils.degToRad(t.rotation[2]),
);
inst.root.scale.set(t.scale[0], t.scale[1], t.scale[2]);
inst.root.visible = o.visible;
}
/**
* Port of open-media's AnimatedObject useFrame: an object with a
* multi-keyframe track is driven by sampling that track at the playhead —
* the stored `transform`/`posture` fields are stale once a track exists
* (they only mirror the last live edit). Objects with 0-1 keyframes, or
* whose liveEditTime still matches the playhead (a gizmo drag / pose edit
* staged on top of the track), read the plain fields instead. Static
* objects degrade to the plain path with no mode branch.
*/
function applyTrackSampling(o: SceneObject) {
const inst = instances.get(o.id);
if (!inst) return;
const elapsed = shotStore.playback.elapsed;
const isLive = o.liveEditTime !== null && Math.abs(o.liveEditTime - elapsed) < 1e-6;
const effectiveLive = isLive || o.keyframes.length <= 1;
if (effectiveLive) return; // applyTransform/applyPosture already wrote the plain fields
const sample = sampleTrack(o.keyframes, elapsed);
const t = sample.transform;
inst.root.position.set(t.position[0], t.position[1], t.position[2]);
inst.root.rotation.set(
THREE.MathUtils.degToRad(t.rotation[0]),
THREE.MathUtils.degToRad(t.rotation[1]),
THREE.MathUtils.degToRad(t.rotation[2]),
);
inst.root.scale.set(t.scale[0], t.scale[1], t.scale[2]);
inst.root.visible = o.visible;
if (isCharacterType(o.type) && sample.posture && inst.figure) {
writePosture(inst.figure as THREE.Object3D & { posture?: unknown }, sample.posture);
}
}
function applyPosture(o: SceneObject) {
const inst = instances.get(o.id);
if (!inst?.figure) return;
const figure = inst.figure as THREE.Object3D & { posture?: unknown };
const effective = o.posture ?? o.defaultPosture;
if (effective) {
writePosture(figure, effective);
groundFigure(figure);
}
// No stored posture: leave the mannequin at its constructor stance.
// Writing a fabricated all-empty posture here would NaN mannequin-js's
// fixed-arity joint setters and the figure would vanish from the render.
}
// ── pose tool: joint handles ────────────────────────────────────
/** Small sphere per editable joint of the selected figure, in root space. */
const poseHandleGroup = new THREE.Group();
let poseHandleTargetId: string | null = null;
let poseDragJoint: string | null = null;
let poseDragStart: { x: number; y: number; dofs: number[] } | null = null;
const POSE_HANDLE_GEO = new THREE.SphereGeometry(0.035, 10, 8);
const POSE_HANDLE_MAT = new THREE.MeshBasicMaterial({ color: 0xffc14d, depthTest: false, transparent: true });
const POSE_HANDLE_ACTIVE_MAT = new THREE.MeshBasicMaterial({ color: 0xff5f5f, depthTest: false, transparent: true });
/** Rebuild (idempotently) the joint handles for the selected mannequin. */
function syncPoseHandles() {
const sel = shotStore.selectedObject;
const active =
sel && shotStore.activeTool === 'pose' && isCharacterType(sel.type) && instances.get(sel.id)?.ready;
if (!active) {
if (poseHandleGroup.parent) scene.remove(poseHandleGroup);
poseHandleTargetId = null;
return;
}
if (poseHandleTargetId !== sel!.id) {
poseHandleGroup.clear();
poseHandleTargetId = sel!.id;
}
const inst = instances.get(sel!.id)!;
if (!inst.figure) return;
poseHandleGroup.name = `posegizmo:${sel!.id}`;
// one handle per JOINT_CONFIGS entry (26 joints; fingers collapse to one)
for (let i = 0; i < JOINT_CONFIGS.length; i++) {
const cfg = JOINT_CONFIGS[i];
let handle = poseHandleGroup.getObjectByName(cfg.mannequinKey) as THREE.Mesh | undefined;
if (!handle) {
handle = new THREE.Mesh(POSE_HANDLE_GEO, POSE_HANDLE_MAT);
handle.name = cfg.mannequinKey;
poseHandleGroup.add(handle);
}
const joint = getJoint(inst.figure, cfg.mannequinKey);
if (joint?.getWorldPosition) {
inst.root.updateMatrixWorld(true);
const world = joint.getWorldPosition(new THREE.Vector3());
inst.root.worldToLocal(world); // handles live inside the object root
handle.position.copy(world);
}
handle.visible = !sel!.locked;
const mat = handle.name === poseDragJoint ? POSE_HANDLE_ACTIVE_MAT : POSE_HANDLE_MAT;
if (handle.material !== mat) handle.material = mat;
}
if (!poseHandleGroup.parent) scene.add(poseHandleGroup);
}
function pickJointHandle(e: PointerEvent, raycaster: THREE.Raycaster, pointer: THREE.Vector2): string | null {
if (!poseHandleGroup.parent) return null;
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects([...poseHandleGroup.children], false);
return hits.length > 0 ? hits[0].object.name : null;
}
/**
* Maps screen delta onto the joint's first two DOFs (screen x → dof 0,
* screen y → dof 1). Angle-space drag, not a projection — good enough for
* blockout posing (open-media's JointGizmo does the same two-axis mapping).
*/
function dragPoseJoint(jointKey: string, dx: number, dy: number) {
const sel = shotStore.selectedObject;
if (!sel) return;
const inst = instances.get(sel.id);
if (!inst?.figure) return;
const cfg = JOINT_CONFIGS.find((c) => c.mannequinKey === jointKey);
if (!cfg) return;
if (poseDragJoint !== jointKey) {
poseDragJoint = jointKey;
poseDragStart = { x: dx, y: dy, dofs: cfg.dofs.map((d) => getDOF(getJoint(inst.figure, cfg.mannequinKey), d)) };
}
const joint = getJoint(inst.figure, jointKey);
for (let i = 0; i < Math.min(2, cfg.dofs.length); i++) {
const dof = cfg.dofs[i];
const delta = i === 0 ? dx : dy;
const next = THREE.MathUtils.clamp(
(poseDragStart?.dofs[i] ?? 0) + delta * 0.5,
dof.min,
dof.max,
);
setDOF(joint, dof, next);
}
}
/** Persist the dragged pose back into the store (which autosaves + SSEs). */
function commitPoseDrag() {
const sel = shotStore.selectedObject;
const jointKey = poseDragJoint;
poseDragJoint = null;
poseDragStart = null;
if (!sel || !jointKey) return;
const inst = instances.get(sel.id);
if (!inst?.figure) return;
try {
const posture = readPosture(inst.figure as unknown as { posture?: unknown } & Record<string, unknown>);
shotStore.updateObjectPosture(sel.id, posture);
} catch {
// posture read failed — leave the stored pose as it was
}
}
function syncScene() {
const storeObjects = shotStore.objects;
// remove stale
const ids = new Set(storeObjects.map((o) => o.id));
for (const [id, inst] of instances) {
if (!ids.has(id)) {
scene.remove(inst.root);
instances.delete(id);
}
}
// add/update
let anyFigurePending = false;
for (const o of storeObjects) {
applyTransform(o);
if (isCharacterType(o.type)) {
applyPosture(o);
if (!instances.get(o.id)?.ready) anyFigurePending = true;
}
applyTrackSampling(o); // wins over the plain fields when a track exists
}
if (anyFigurePending) figureRevision++; // re-arm the change-driven shot solve
// selection gizmo (suppressed in pose mode — joint handles own the figure)
const selected = shotStore.selectedObject;
const gizmoActive = selected && shotStore.activeTool !== 'select' && shotStore.activeTool !== 'pose';
if (gizmoActive && instances.has(selected.id)) {
const inst = instances.get(selected.id)!;
if (gizmo.object !== inst.root) {
gizmo.attach(inst.root);
}
gizmo.setMode(
shotStore.activeTool === 'move' ? 'translate' : shotStore.activeTool === 'rotate' ? 'rotate' : 'scale',
);
gizmo.enabled = !selected.locked;
gizmoHelper.visible = true;
} else {
gizmo.detach();
gizmoHelper.visible = false;
}
syncPoseHandles();
}
function solveShotFromSelection() {
// The store holds params; the frontend owns the solve math (same split
// as open-media's set_shot → ComposerShell effect).
const params = shotStore.shotParams;
if (!params?.shotSize) return;
const characterObj =
shotStore.objects.find((o) => o.id === shotStore.selectedObjectId && isCharacterType(o.type)) ??
shotStore.objects.find((o) => isCharacterType(o.type));
if (!characterObj) return;
const inst = instances.get(characterObj.id);
if (!inst?.figure) return;
const anchors = getCharacterAnchors(inst.figure);
const second = shotStore.objects.find((o) => o.id !== characterObj.id && isCharacterType(o.type));
const secondFigure = second ? instances.get(second.id)?.figure : undefined;
const secondAnchors = second && secondFigure ? getCharacterAnchors(secondFigure) : undefined;
const preset = getCompositionPreset(params.composition ?? 'center');
const shot = solveShot({
shotSize: params.shotSize,
angle: params.angle ?? 'front',
elevation: params.elevation ?? 'eye',
composition: preset,
anchors,
targetAnchors: secondAnchors,
fovDeg: 40,
aspect: camera.aspect,
});
// A NaN here (bad anchor geometry, degenerate bounding box) would stick
// in the camera forever and render an empty frame — refuse to apply it.
if (
!Number.isFinite(shot.position.x) ||
!Number.isFinite(shot.position.y) ||
!Number.isFinite(shot.position.z) ||
!Number.isFinite(shot.target.x) ||
!Number.isFinite(shot.target.y) ||
!Number.isFinite(shot.target.z)
) {
return;
}
shotStore.beginHistoryGroup();
orbit.target.copy(shot.target);
camera.position.copy(shot.position);
camera.updateProjectionMatrix();
orbit.update();
shotStore.endHistoryGroup();
}
// ── capture ─────────────────────────────────────────────────────
function captureShot(): string {
renderFrame();
return renderer.domElement.toDataURL('image/png');
}
// ── camera track ────────────────────────────────────────────────
/** Samples the camera track at `time` with smooth lerp/slerp between keyframes. */
function sampleCameraTrack(time: number): { position: [number, number, number]; target: [number, number, number]; fov: number } | null {
const track = shotStore.cameraTrack;
if (track.length === 0) return null;
const sorted = track.length > 1 ? [...track].sort((a, b) => a.time - b.time) : track;
if (sorted.length === 1 || time <= sorted[0].time) {
const k = sorted[0];
return { position: [...k.position], target: [...k.target], fov: k.fov };
}
const last = sorted[sorted.length - 1];
if (time >= last.time) {
const k = last;
return { position: [...k.position], target: [...k.target], fov: k.fov };
}
let a = sorted[0];
let b = last;
for (let i = 0; i < sorted.length - 1; i++) {
if (time >= sorted[i].time && time <= sorted[i + 1].time) {
a = sorted[i];
b = sorted[i + 1];
break;
}
}
const span = b.time - a.time;
const k = span > 0 ? 0.5 - 0.5 * Math.cos(Math.PI * ((time - a.time) / span)) : 0;
const pos: [number, number, number] = [
a.position[0] + (b.position[0] - a.position[0]) * k,
a.position[1] + (b.position[1] - a.position[1]) * k,
a.position[2] + (b.position[2] - a.position[2]) * k,
];
const tgt: [number, number, number] = [
a.target[0] + (b.target[0] - a.target[0]) * k,
a.target[1] + (b.target[1] - a.target[1]) * k,
a.target[2] + (b.target[2] - a.target[2]) * k,
];
return { position: pos, target: tgt, fov: a.fov + (b.fov - a.fov) * k };
}
let playbackClockPrev = 0;
let playbackWasPlaying = false;
function applyCameraAt(time: number) {
const sample = sampleCameraTrack(time);
if (!sample) return;
if (
!sample.position.every(Number.isFinite) ||
!sample.target.every(Number.isFinite) ||
!Number.isFinite(sample.fov)
) {
return; // poisoned keyframe data — keep the current camera
}
camera.position.set(sample.position[0], sample.position[1], sample.position[2]);
orbit.target.set(sample.target[0], sample.target[1], sample.target[2]);
if (Math.abs(camera.fov - sample.fov) > 0.01) {
camera.fov = sample.fov;
camera.updateProjectionMatrix();
}
}
/** Advance the store clock while playing; driven from tick(). */
function advancePlayback(now: number) {
const playing = shotStore.playback.playing;
if (playing && !playbackWasPlaying) playbackClockPrev = now;
if (playing) {
const dt = now - playbackClockPrev;
let next = shotStore.playback.elapsed + dt;
if (next >= shotStore.playback.duration) {
next = 0; // loop for preview; export runs its own pass
}
shotStore.setElapsed(next);
}
playbackWasPlaying = playing;
playbackClockPrev = now;
}
function renderFrame() {
renderer.render(scene, camera);
}
function flushCaptureRequest() {
// If the backend has a pending capture_request (agent asked), render +
// upload it. The store never sees this; the page wires oncapture.
fetch(`/api/shots/${shotStore.compositionId}`)
.then((r) => (r.ok ? r.json() : null))
.then((comp) => {
if (!comp?.capture_request_json || !oncapture) return;
if (comp.capture_requested_at && comp.capture_requested_at <= captureRequestedAt) return;
captureRequestedAt = Date.now();
const dataUrl = captureShot();
oncapture(dataUrl);
})
.catch(() => {});
}
// ── loop ────────────────────────────────────────────────────────
function tick() {
raf = requestAnimationFrame(tick);
const now = performance.now() / 1000;
advancePlayback(now);
// While playing (or scrubbed onto the track) the camera track owns the
// view; orbit is disabled so it cannot fight the sampled pose. During a
// gizmo drag TransformControls already disabled orbit — leave it alone,
// because a per-frame `orbit.enabled = true` here would fight the gizmo.
const playing = shotStore.playback.playing;
if (!gizmoDragging) orbit.enabled = !playing;
if (playing) {
applyCameraAt(shotStore.playback.elapsed);
}
orbit.update();
syncScene();
renderFrame();
}
onMount(() => {
renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
container.appendChild(renderer.domElement);
scene = new THREE.Scene();
scene.background = new THREE.Color(0x14161c);
camera = new THREE.PerspectiveCamera(40, 1, 0.01, 200);
camera.position.set(4, 3, 6);
const hemi = new THREE.HemisphereLight(0xffffff, 0x223, 0.9);
scene.add(hemi);
const dir = new THREE.DirectionalLight(0xffffff, 1.4);
dir.position.set(5, 10, 4);
dir.castShadow = true;
scene.add(dir);
grid = new THREE.GridHelper(40, 40, 0x3a4152, 0x242a36);
scene.add(grid);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.ShadowMaterial({ opacity: 0.25 }),
);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
orbit = new OrbitControls(camera, renderer.domElement);
orbit.enableDamping = true;
gizmo = new TransformControls(camera, renderer.domElement);
gizmo.setSize(0.8);
gizmoHelper = gizmo.getHelper();
scene.add(gizmoHelper);
gizmo.addEventListener('dragging-changed', (e) => {
const dragging = (e as unknown as { value: boolean }).value;
gizmoDragging = dragging;
orbit.enabled = !dragging;
shotStore.dragInProgress = dragging;
if (!dragging) {
// one commit per gesture
const obj = shotStore.selectedObject;
if (obj) {
const root = instances.get(obj.id)?.root;
if (root) {
shotStore.updateObjectTransform(obj.id, {
position: [root.position.x, root.position.y, root.position.z],
rotation: [
THREE.MathUtils.radToDeg(root.rotation.x),
THREE.MathUtils.radToDeg(root.rotation.y),
THREE.MathUtils.radToDeg(root.rotation.z),
],
scale: [root.scale.x, root.scale.y, root.scale.z],
});
}
}
}
});
gizmo.addEventListener('objectChange', () => {
const obj = shotStore.selectedObject;
const root = obj ? instances.get(obj.id)?.root : null;
if (obj && root) {
shotStore.beginHistoryGroup();
shotStore.updateObjectTransform(obj.id, {
position: [root.position.x, root.position.y, root.position.z],
rotation: [
THREE.MathUtils.radToDeg(root.rotation.x),
THREE.MathUtils.radToDeg(root.rotation.y),
THREE.MathUtils.radToDeg(root.rotation.z),
],
scale: [root.scale.x, root.scale.y, root.scale.z],
});
shotStore.endHistoryGroup();
}
});
// selection + pose-mode picking
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let downAt = 0;
let downPoseJoint: string | null = null;
let downX = 0;
let downY = 0;
const onPointerUp = (e: PointerEvent) => {
if (downPoseJoint) {
downPoseJoint = null;
if (!shotStore.playback.playing && !gizmoDragging) orbit.enabled = true;
commitPoseDrag();
return;
}
if (Date.now() - downAt > 250) return; // drag, not a click
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
// pose mode: clicking a handle selects nothing new
if (shotStore.activeTool === 'pose' && shotStore.selectedObject) return;
const hits = raycaster.intersectObjects([...instances.values()].map((i) => i.root), true);
for (const hit of hits) {
let node: THREE.Object3D | null = hit.object;
while (node && !instances.has(node.name)) node = node.parent;
if (node) {
shotStore.selectObject(node.name);
onselectionchange?.();
return;
}
}
shotStore.clearSelection();
};
renderer.domElement.addEventListener('pointerdown', (e) => {
downAt = Date.now();
downX = e.clientX;
downY = e.clientY;
// In pose mode a press on a joint handle starts a pose drag instead
// of an orbit; press elsewhere still orbits.
downPoseJoint = null;
if (shotStore.activeTool === 'pose' && shotStore.selectedObject) {
const hit = pickJointHandle(e, raycaster, pointer);
if (hit) {
downPoseJoint = hit;
orbit.enabled = false;
}
}
});
renderer.domElement.addEventListener('pointermove', (e) => {
if (!downPoseJoint) return;
dragPoseJoint(downPoseJoint, e.clientX - downX, e.clientY - downY);
});
window.addEventListener('pointerup', onPointerUp);
cleanupPointerUp = () => window.removeEventListener('pointerup', onPointerUp);
resizeObserver = new ResizeObserver(() => {
const w = container.clientWidth;
const h = container.clientHeight;
if (w === 0 || h === 0) return;
renderer.setSize(w, h);
camera.aspect = w / h;
camera.updateProjectionMatrix();
});
resizeObserver.observe(container);
raf = requestAnimationFrame(tick);
});
onDestroy(() => {
cancelAnimationFrame(raf);
resizeObserver?.disconnect();
cleanupPointerUp?.();
gizmo?.dispose();
orbit?.dispose();
renderer?.dispose();
});
// ── video export ────────────────────────────────────────────────
/**
* Renders one pass of the camera track to a video clip via
* canvas.captureStream + MediaRecorder (MP4 where Chromium supports it,
* WebM fallback). Resolves with a data URL for POST /api/shots/{id}/captures.
*/
function pickVideoMime(): string | null {
const candidates = [
'video/mp4;codecs=avc1.42E01E',
'video/mp4',
'video/webm;codecs=vp9',
'video/webm',
];
if (typeof MediaRecorder === 'undefined') return null;
for (const mime of candidates) {
if (MediaRecorder.isTypeSupported(mime)) return mime;
}
return null;
}
function blobToDataUrl(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(new Error('Could not read recorded blob'));
reader.readAsDataURL(blob);
});
}
async function exportVideo(): Promise<{ dataUrl: string; ext: string }> {
const mime = pickVideoMime();
if (!mime) throw new Error('MediaRecorder is not available in this browser');
if (shotStore.cameraTrack.length < 2) {
throw new Error('Add at least two camera keyframes before exporting');
}
const stream = renderer.domElement.captureStream(30);
const chunks: Blob[] = [];
const recorder = new MediaRecorder(stream, { mimeType: mime });
recorder.ondataavailable = (e) => {
if (e.data.size > 0) chunks.push(e.data);
};
const done = new Promise<void>((resolve) => {
recorder.onstop = () => resolve();
});
const duration = shotStore.playback.duration;
// Drive the camera manually across one deterministic pass: pause store
// playback (the tick loop would fight us), sample per frame with a
// fixed-step clock so export duration matches the timeline exactly.
shotStore.setPlaying(false);
const fps = 30;
const steps = Math.max(2, Math.round(duration * fps));
recorder.start();
for (let i = 0; i <= steps; i++) {
const t = (i / steps) * duration;
shotStore.setElapsed(t);
applyCameraAt(t);
syncScene();
renderFrame();
await new Promise((r) => requestAnimationFrame(r));
}
// Hold the final frame briefly so the recorder flushes it.
await new Promise((r) => setTimeout(r, 120));
recorder.stop();
await done;
stream.getTracks().forEach((tr) => tr.stop());
shotStore.setElapsed(0);
const ext = mime.includes('mp4') ? 'mp4' : 'webm';
const blob = new Blob(chunks, { type: mime });
if (blob.size === 0) throw new Error('Recording produced no data');
return { dataUrl: await blobToDataUrl(blob), ext };
}
// expose capture + request polling to the page
export function captureNow(): string {
return captureShot();
}
export function pollCaptureRequest() {
flushCaptureRequest();
}
export function exportVideoClip(): Promise<{ dataUrl: string; ext: string }> {
return exportVideo();
}
// Camera keyframe requests from the timeline: the store asks (nonce), the
// viewport answers with the live pose. $effect re-runs per request.
let lastKeyframeNonce = 0;
$effect(() => {
const req = shotStore.cameraKeyframeRequest;
if (!req || req.nonce === lastKeyframeNonce) return;
lastKeyframeNonce = req.nonce;
shotStore.setCameraKeyframe(req.time, {
position: [camera.position.x, camera.position.y, camera.position.z],
target: [orbit.target.x, orbit.target.y, orbit.target.z],
fov: camera.fov,
});
});
/**
* Change-driven shot solve (mirrors open-media's ComposerShell effect on
* [selectedId, shotParams]): the preset applies ONCE when the framing or
* selection changes — never per-frame, so a manual orbit afterwards is not
* yanked back by a re-applied preset. untrack keeps internal object reads
* (anchors, instances) from widening the trigger set.
*/
$effect(() => {
void shotStore.shotParams;
void shotStore.selectedObjectId;
void figureRevision;
if (!camera || shotStore.playback.playing) return;
untrack(() => solveShotFromSelection());
});
$effect(() => {
if (grid) grid.visible = showGrid;
});
// Scrub: when not playing, sample the track at the (user-moved) playhead.
let lastScrubbedElapsed = -1;
$effect(() => {
const t = shotStore.playback.elapsed;
if (shotStore.playback.playing) return;
if (Math.abs(t - lastScrubbedElapsed) < 1e-6) return;
lastScrubbedElapsed = t;
if (shotStore.cameraTrack.length > 0) {
applyCameraAt(t);
}
});
// Dev/debug probe: lets tests and console inspection read the live three
// state (camera, target, solved shot) without touching the store contract.
const debugProbe = {
get camera() {
return camera ? { position: camera.position.toArray(), fov: camera.fov } : null;
},
get target() {
return orbit ? orbit.target.toArray() : null;
},
get instances() {
return [...instances.entries()].map(([id, inst]) => ({
id,
type: inst.type,
ready: inst.ready,
hasFigure: !!inst.figure,
}));
},
get poseHandles() {
return poseHandleGroup.parent
? { count: poseHandleGroup.children.length, target: poseHandleTargetId }
: null;
},
};
onMount(() => {
(window as unknown as { __shotDebug?: typeof debugProbe }).__shotDebug = debugProbe;
});
</script>
<div class="viewport" bind:this={container}>
<div class="viewport-toolbar">
<ViewportToolbar oncapture={() => oncapture?.(captureShot())} bind:showGrid bind:showComposition />
</div>
{#if showComposition}
<div class="composition-guide" aria-hidden="true">
<span class="thirds-v"></span><span class="thirds-v"></span><span class="thirds-h"></span><span class="thirds-h"></span>
<span class="cross-h"></span><span class="cross-v"></span>
</div>
{/if}
</div>
<style>
.viewport {
width: 100%;
height: 100%;
min-height: 320px;
overflow: hidden;
background: #14161c;
position: relative;
}
.viewport :global(canvas) {
display: block;
}
.viewport-toolbar {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
z-index: 10;
max-width: calc(100% - 20px);
}
.composition-guide {
position: absolute;
inset: 0;
z-index: 5;
pointer-events: none;
}
.composition-guide .thirds-v {
position: absolute;
top: 0;
bottom: 0;
width: 1px;
background: rgba(255, 255, 255, 0.14);
}
.composition-guide .thirds-v:nth-of-type(1) {
left: 33.33%;
}
.composition-guide .thirds-v:nth-of-type(2) {
left: 66.66%;
}
.composition-guide .thirds-h {
position: absolute;
left: 0;
right: 0;
height: 1px;
background: rgba(255, 255, 255, 0.14);
}
.composition-guide .thirds-h:nth-of-type(3) {
top: 33.33%;
}
.composition-guide .thirds-h:nth-of-type(4) {
top: 66.66%;
}
.composition-guide .cross-h {
position: absolute;
top: 50%;
left: 50%;
width: 14px;
height: 1px;
transform: translate(-50%, -50%);
background: rgba(255, 255, 255, 0.35);
}
.composition-guide .cross-v {
position: absolute;
top: 50%;
left: 50%;
width: 1px;
height: 14px;
transform: translate(-50%, -50%);
background: rgba(255, 255, 255, 0.35);
}
</style>
@@ -0,0 +1,311 @@
<script lang="ts">
/**
* Timeline: a camera row (keyframes the viewport camera; plays the track
* that drives video export) and an object row (keyframes the selected
* object's transform/posture; playback samples every tracked object).
* Both on the same 0..duration playhead (max 60s).
*/
import { shotStore, MAX_TIMELINE_DURATION } from '../shotStore.svelte';
import type { CameraKeyframe } from '../shotStore.svelte';
let { onExportVideo }: { onExportVideo?: () => void } = $props();
let trackEl: HTMLDivElement | null = null;
let exporting = $state(false);
let draggingKeyframeId: string | null = null;
const duration = $derived(shotStore.playback.duration);
const playing = $derived(shotStore.playback.playing);
const elapsed = $derived(shotStore.playback.elapsed);
const track = $derived(shotStore.cameraTrack);
const selectedObject = $derived(shotStore.selectedObject);
const selectedKeyframeId = $derived(shotStore.selectedKeyframeId);
const pct = $derived(duration > 0 ? (elapsed / duration) * 100 : 0);
function timeAt(clientX: number): number {
if (!trackEl) return 0;
const rect = trackEl.getBoundingClientRect();
const k = Math.min(Math.max((clientX - rect.left) / rect.width, 0), 1);
return k * duration;
}
function onTrackScrub(e: PointerEvent) {
if (!trackEl || playing) return;
shotStore.setElapsed(timeAt(e.clientX));
}
function onDurationInput(e: Event) {
const value = Number((e.target as HTMLInputElement).value);
if (Number.isFinite(value)) shotStore.setDuration(value);
}
function keyframeStyle(k: CameraKeyframe) {
return `left:${duration > 0 ? (k.time / duration) * 100 : 0}%`;
}
function togglePlay() {
shotStore.setPlaying(!playing);
}
// ── object keyframe row ─────────────────────────────────────────
function addKeyframeAtPlayhead() {
if (!selectedObject) return;
shotStore.addKeyframe(selectedObject.id, elapsed);
}
function commitStagedKeyframe() {
if (!selectedObject) return;
shotStore.commitLiveKeyframe(selectedObject.id);
}
function deleteSelectedKeyframe() {
if (!selectedObject || !selectedKeyframeId) return;
shotStore.deleteKeyframe(selectedObject.id, selectedKeyframeId);
}
function onMarkerPointerDown(e: PointerEvent, keyframeId: string) {
if (!selectedObject) return;
e.stopPropagation();
shotStore.selectKeyframe(keyframeId);
draggingKeyframeId = keyframeId;
const onMove = (ev: PointerEvent) => {
if (!draggingKeyframeId) return;
shotStore.moveKeyframeTime(selectedObject.id, draggingKeyframeId, timeAt(ev.clientX));
};
const onUp = () => {
draggingKeyframeId = null;
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
}
</script>
<div class="timeline">
<div class="controls">
<button class="icon-btn" onclick={togglePlay} title={playing ? 'Pause' : 'Play the timeline (camera + object tracks)'}>
{playing ? '❚❚' : '▶'}
</button>
<label class="dur">
<input
type="number"
min="1"
max={MAX_TIMELINE_DURATION}
step="1"
value={Math.round(duration)}
onchange={onDurationInput}
/>
<span>s</span>
</label>
<span class="time">{elapsed.toFixed(1)}s</span>
</div>
<div
class="track"
bind:this={trackEl}
onpointerdown={onTrackScrub}
role="slider"
aria-label="Timeline playhead"
aria-valuemin={0}
aria-valuemax={duration}
aria-valuenow={elapsed}
tabindex="0"
>
<div class="rail"></div>
<div class="playhead" style={`left:${pct}%`}></div>
{#each track as k (k.id)}
<button
class="keyframe cam"
style={keyframeStyle(k)}
title={`Camera keyframe @ ${k.time.toFixed(1)}s — double-click to delete`}
onclick={(e) => {
e.stopPropagation();
shotStore.setElapsed(k.time);
}}
ondblclick={(e) => {
e.stopPropagation();
shotStore.removeCameraKeyframe(k.id);
}}
></button>
{/each}
{#if selectedObject}
{#each selectedObject.keyframes as k (k.id)}
<button
class="keyframe obj"
class:selected={k.id === selectedKeyframeId}
style={`left:${duration > 0 ? (k.time / duration) * 100 : 0}%`}
title={`${selectedObject.name} keyframe @ ${k.time.toFixed(1)}s — drag to move, double-click to delete`}
onpointerdown={(e) => onMarkerPointerDown(e, k.id)}
ondblclick={(e) => {
e.stopPropagation();
shotStore.deleteKeyframe(selectedObject.id, k.id);
}}
></button>
{/each}
{/if}
</div>
<div class="actions">
<button class="icon-btn" onclick={() => shotStore.requestCameraKeyframeAt(elapsed)} title="Keyframe the current camera view at the playhead">
◉
</button> <button class="icon-btn" onclick={() => shotStore.removeCameraKeyframeAt(elapsed)} title="Remove camera keyframe at the playhead">
◌
</button>
{#if selectedObject}
<span class="obj-actions">
<button class="icon-btn obj-add" onclick={addKeyframeAtPlayhead} title={`Keyframe ${selectedObject.name}'s current transform at the playhead`}>
◆+
</button>
<button
class="icon-btn"
onclick={deleteSelectedKeyframe}
disabled={!selectedKeyframeId || selectedObject.keyframes.length <= 1}
title={selectedKeyframeId ? 'Delete the selected object keyframe' : 'Select an object keyframe first'}
>
◆−
</button>
</span>
{/if}
<button class="export" onclick={onExportVideo} disabled={exporting || track.length < 2} title={track.length < 2 ? 'Add at least two camera keyframes' : 'Render the camera track to a video clip'}>
Export video
</button>
</div>
</div>
<style>
.timeline {
display: flex;
align-items: center;
gap: 10px;
padding: 6px 12px;
border-top: 1px solid var(--border, #232733);
}
.controls {
display: flex;
align-items: center;
gap: 8px;
}
.icon-btn {
display: flex;
align-items: center;
justify-content: center;
min-width: 26px;
height: 26px;
border: 1px solid var(--border, #2a2f3a);
background: transparent;
color: inherit;
border-radius: 6px;
cursor: pointer;
font-size: 11px;
padding: 0 6px;
}
.icon-btn:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.06);
}
.icon-btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.obj-actions {
display: flex;
gap: 4px;
}
.obj-add {
color: #7dd88a;
}
.export {
border: 1px solid var(--border, #2a2f3a);
background: transparent;
color: inherit;
border-radius: 6px;
padding: 5px 10px;
font-size: 12px;
cursor: pointer;
white-space: nowrap;
}
.export:hover:not(:disabled) {
border-color: var(--accent, #6366f1);
}
.export:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.dur {
display: flex;
align-items: center;
gap: 3px;
font-size: 11px;
opacity: 0.7;
}
.dur input {
width: 46px;
background: rgba(0, 0, 0, 0.3);
border: 1px solid var(--border, #2a2f3a);
color: inherit;
border-radius: 4px;
padding: 3px 5px;
font-size: 12px;
}
.time {
font-size: 11px;
opacity: 0.55;
min-width: 38px;
text-align: right;
font-variant-numeric: tabular-nums;
}
.track {
position: relative;
flex: 1;
height: 26px;
cursor: pointer;
touch-action: none;
}
.rail {
position: absolute;
inset: 11px 0;
border-radius: 3px;
background: rgba(255, 255, 255, 0.08);
}
.playhead {
position: absolute;
top: 2px;
bottom: 2px;
width: 2px;
background: var(--accent, #6366f1);
transform: translateX(-1px);
pointer-events: none;
}
.keyframe {
position: absolute;
top: 50%;
width: 10px;
height: 10px;
border-radius: 2px;
transform: translate(-5px, -50%) rotate(45deg);
background: #e0b34d;
border: 1px solid rgba(0, 0, 0, 0.5);
cursor: grab;
padding: 0;
z-index: 2;
}
.keyframe.cam {
background: #e0b34d;
}
.keyframe.obj {
background: #4ade80;
}
.keyframe.obj.selected {
background: #f87171;
}
.keyframe:hover {
filter: brightness(1.15);
}
.actions {
display: flex;
align-items: center;
gap: 6px;
}
</style>
@@ -0,0 +1,139 @@
<script lang="ts">
/**
* Viewport toolbar pill — Svelte port of open-media's WorkspaceToolbar
* (ToolButtons) + ComposerShell topbar actions: gizmo tools (Select /
* Move / Rotate / Scale / Pose), undo/redo, grid + composition-guide
* toggles, and the capture button. Tool state lives on the shot store;
* the two view toggles are local (the viewport owns the grid mesh and
* the CSS overlay) and passed up through bindable props.
*/
import { shotStore, type ComposerTool } from '../shotStore.svelte';
let {
oncapture,
showGrid = $bindable(true),
showComposition = $bindable(false),
}: {
oncapture?: () => void;
showGrid?: boolean;
showComposition?: boolean;
} = $props();
const activeTool = $derived(shotStore.activeTool);
const selected = $derived(shotStore.selectedObject);
// Pose applies to mannequins only (mirrors the store's canPoseSelection).
const canPose = $derived(
!!selected && selected.type !== 'camera' && !['cube', 'plane', 'cylinder', 'sphere', 'capsule', 'cone', 'torus'].includes(selected.type),
);
function setTool(tool: ComposerTool) {
shotStore.setActiveTool(tool);
}
const TOOLS = $derived<{ id: ComposerTool; label: string; title: string; disabled?: boolean }[]>([
{ id: 'select', label: 'Select', title: 'Select (click objects; no gizmo)' },
{ id: 'move', label: 'Move', title: 'Move (Translate)' },
{ id: 'rotate', label: 'Rotate', title: 'Rotate' },
{ id: 'scale', label: 'Scale', title: 'Scale' },
{ id: 'pose', label: 'Pose', title: canPose ? 'Pose (drag the joint handles)' : 'Pose applies to mannequins only', disabled: !canPose },
]);
</script>
<div class="toolbar" role="toolbar" aria-label="Viewport tools">
<div class="group">
{#each TOOLS as tool (tool.id)}
<button
class="btn"
class:on={activeTool === tool.id}
disabled={tool.disabled}
onclick={() => setTool(tool.id)}
title={tool.title}
>
{tool.label}
</button>
{/each}
</div>
<span class="divider"></span>
<div class="group">
<button class="btn" onclick={() => shotStore.undo()} disabled={!shotStore.canUndo} title="Undo last scene change">
↶
</button>
<button class="btn" onclick={() => shotStore.redo()} disabled={!shotStore.canRedo} title="Redo the last undone change">
↷
</button>
</div>
<span class="divider"></span>
<div class="group">
<button class="btn" class:on={showGrid} onclick={() => (showGrid = !showGrid)} title="Toggle grid">
Grid
</button>
<button class="btn" class:on={showComposition} onclick={() => (showComposition = !showComposition)} title="Composition guide (rule of thirds)">
Composition
</button>
</div>
<span class="divider"></span>
<button class="btn capture" onclick={() => oncapture?.()} title="Render the current view to a PNG reference">
◎ Capture
</button>
</div>
<style>
.toolbar {
display: flex;
align-items: center;
gap: 6px;
border: 1px solid var(--border, #2a2f3a);
background: rgba(16, 18, 24, 0.82);
border-radius: 999px;
padding: 4px 8px;
backdrop-filter: blur(4px);
}
.group {
display: flex;
align-items: center;
gap: 2px;
}
.divider {
width: 1px;
height: 16px;
background: var(--border, #2a2f3a);
margin: 0 2px;
}
.btn {
border: 1px solid transparent;
background: transparent;
color: inherit;
border-radius: 999px;
padding: 3px 9px;
font-size: 12px;
font-weight: 500;
cursor: pointer;
white-space: nowrap;
opacity: 0.85;
}
.btn:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.08);
opacity: 1;
}
.btn.on {
background: rgba(99, 102, 241, 0.25);
border-color: var(--accent, #6366f1);
opacity: 1;
}
.btn:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.capture {
border-color: var(--border, #2a2f3a);
}
.capture:hover {
border-color: var(--accent, #6366f1);
}
</style>
@@ -0,0 +1,85 @@
import * as THREE from 'three';
import type { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
export type EditorView =
| 'front'
| 'back'
| 'left'
| 'right'
| 'top'
| 'bottom'
| 'front-left'
| 'front-right'
| 'back-left'
| 'back-right'
| 'isometric'
| 'perspective';
export function getObjectBounds(object: THREE.Object3D) {
object.updateWorldMatrix(true, true);
return new THREE.Box3().setFromObject(object);
}
export function frameObject(camera: THREE.PerspectiveCamera, controls: OrbitControls, object: THREE.Object3D, direction = new THREE.Vector3(1, .55, 1), fill = .62) {
const box = getObjectBounds(object);
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
const radius = Math.max(size.x, size.y, size.z) / 2;
const distance = radius / Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) / fill;
controls.target.copy(center);
camera.position.copy(center).add(direction.normalize().multiplyScalar(distance));
camera.up.set(0, 1, 0);
camera.lookAt(center);
camera.updateProjectionMatrix();
controls.update();
}
export function setEditorView(camera: THREE.PerspectiveCamera, controls: OrbitControls, object: THREE.Object3D, view: EditorView) {
const directions: Record<EditorView, THREE.Vector3> = {
'front': new THREE.Vector3(0, .08, 1),
'back': new THREE.Vector3(0, .08, -1),
'left': new THREE.Vector3(-1, .08, 0),
'right': new THREE.Vector3(1, .08, 0),
'top': new THREE.Vector3(0, 1, .001),
'bottom': new THREE.Vector3(0, -1, .001),
'front-left': new THREE.Vector3(-1, .08, 1),
'front-right': new THREE.Vector3(1, .08, 1),
'back-left': new THREE.Vector3(-1, .08, -1),
'back-right': new THREE.Vector3(1, .08, -1),
'isometric': new THREE.Vector3(1, 1, 1),
'perspective': new THREE.Vector3(1, .55, 1),
};
const direction = directions[view] || directions['perspective'];
// Get the object's bounding sphere to check for collisions
const box = getObjectBounds(object);
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
const boundingRadius = Math.max(size.x, size.y, size.z) / 2;
// Preserve current camera distance from target
const currentDistance = camera.position.distanceTo(controls.target);
// Use current distance if it's reasonable, otherwise compute a safe distance
// Minimum distance: bounding radius + safety margin
const minDistance = boundingRadius * 1.2;
const distance = Math.max(currentDistance, minDistance);
// Position camera at the new angle but preserving distance
controls.target.copy(center);
camera.position.copy(center).add(direction.normalize().multiplyScalar(distance));
// Set up vector based on view
if (view === 'top') {
camera.up.set(0, 0, -1);
} else if (view === 'bottom') {
camera.up.set(0, 0, 1);
} else {
camera.up.set(0, 1, 0);
}
camera.lookAt(controls.target);
camera.updateProjectionMatrix();
controls.update();
}
@@ -0,0 +1,222 @@
/** A single degree-of-freedom on a joint */
export interface JointDOF {
/** Display label, e.g. "Bend", "Raise" */
label: string;
/** The accessor property name on the joint object (getter/setter) */
accessor: string;
/** Sub-joint the accessor lives on. Fingers carry their phalanges as `.mid` / `.tip`. */
on?: "mid" | "tip";
/** Minimum angle in degrees */
min: number;
/** Maximum angle in degrees */
max: number;
/** Slider step */
step: number;
}
/** Config for one joint/section displayed in the UI */
export interface JointConfig {
/** Display section label, e.g. "Left Arm" */
label: string;
/** The property path on the mannequin to access this joint, e.g. "l_arm" */
mannequinKey: string;
/** Per-axis degrees of freedom */
dofs: JointDOF[];
}
/**
* Returns the joint object from a mannequin instance.
* e.g. getJoint(mannequin, "l_arm") → mannequin.l_arm
*/
export function getJoint(mannequin: any, key: string): any {
return (mannequin as any)[key];
}
/** The object the DOF's accessor actually lives on — the joint, or one of its phalanges. */
function dofTarget(joint: any, dof: JointDOF): any {
return dof.on ? joint?.[dof.on] : joint;
}
/**
* Get a DOF value in degrees.
* e.g. getDOF(mannequin.l_arm, { accessor: "raise", ... }) → number
*/
export function getDOF(joint: any, dof: JointDOF): number {
return dofTarget(joint, dof)?.[dof.accessor] ?? 0;
}
/** Set a DOF value in degrees. */
export function setDOF(joint: any, dof: JointDOF, value: number): void {
const target = dofTarget(joint, dof);
if (target) target[dof.accessor] = value;
}
const FINGER_NAMES = ["Thumb", "Index", "Middle", "Ring", "Little"];
/** Straddle range per finger index, from Finger.js `minXbase`/`maxXbase`. Side-independent. */
const FINGER_STRADDLE: [number, number][] = [
[-50, 0],
[-35, 20],
[-15, 15],
[-15, 25],
[-20, 35],
];
/**
* A finger is one posture entry carrying its own [x,y,z] plus mid/tip bends,
* so all five DOFs below belong to the same `l_finger_n` / `r_finger_n` key.
* The thumb is the only finger with a meaningful turn.
*/
function fingerConfig(side: "l" | "r", n: number): JointConfig {
const thumb = n === 0;
const [straddleMin, straddleMax] = FINGER_STRADDLE[n];
const dofs: JointDOF[] = [
{ label: "Bend", accessor: "bend", min: thumb ? -90 : -10, max: thumb ? 45 : 120, step: 1 },
{ label: "Straddle", accessor: "straddle", min: straddleMin, max: straddleMax, step: 1 },
];
if (thumb) dofs.push({ label: "Turn", accessor: "turn", min: 90, max: 180, step: 1 });
dofs.push({ label: "Mid Bend", accessor: "bend", on: "mid", min: 0, max: thumb ? 90 : 120, step: 1 });
dofs.push({ label: "Tip Bend", accessor: "bend", on: "tip", min: 0, max: thumb ? 90 : 120, step: 1 });
return {
label: `${side === "l" ? "Left" : "Right"} ${FINGER_NAMES[n]}`,
mannequinKey: `${side}_finger_${n}`,
dofs,
};
}
/**
* Every joint the v7 posture serializes, in POSTURE_ENTRIES order per limb.
* `pelvis` and `neck` are omitted on purpose: they exist in the chain but are
* absent from `posture.data`, so edits to them are silently lost on save.
*/
export const JOINT_CONFIGS: JointConfig[] = [
{
label: "Body",
mannequinKey: "body",
dofs: [
{ label: "Bend", accessor: "bend", min: -50, max: 50, step: 1 },
{ label: "Tilt", accessor: "tilt", min: -50, max: 50, step: 1 },
{ label: "Turn", accessor: "turn", min: -90, max: 90, step: 1 },
],
},
{
label: "Torso",
mannequinKey: "torso",
dofs: [
{ label: "Bend", accessor: "bend", min: -60, max: 25, step: 1 },
{ label: "Tilt", accessor: "tilt", min: -25, max: 25, step: 1 },
{ label: "Turn", accessor: "turn", min: -50, max: 50, step: 1 },
],
},
{
label: "Head",
mannequinKey: "head",
dofs: [
{ label: "Nod", accessor: "nod", min: -25, max: 25, step: 1 },
{ label: "Tilt", accessor: "tilt", min: -22, max: 22, step: 1 },
{ label: "Turn", accessor: "turn", min: -45, max: 45, step: 1 },
],
},
{
label: "Left Arm",
mannequinKey: "l_arm",
dofs: [
{ label: "Raise", accessor: "raise", min: -90, max: 180, step: 1 },
{ label: "Straddle", accessor: "straddle", min: -90, max: 90, step: 1 },
{ label: "Turn", accessor: "turn", min: -90, max: 90, step: 1 },
],
},
{
label: "Right Arm",
mannequinKey: "r_arm",
dofs: [
{ label: "Raise", accessor: "raise", min: -90, max: 180, step: 1 },
{ label: "Straddle", accessor: "straddle", min: -90, max: 90, step: 1 },
{ label: "Turn", accessor: "turn", min: -90, max: 90, step: 1 },
],
},
{
label: "Left Elbow",
mannequinKey: "l_elbow",
dofs: [
{ label: "Bend", accessor: "bend", min: 0, max: 150, step: 1 },
],
},
{
label: "Right Elbow",
mannequinKey: "r_elbow",
dofs: [
{ label: "Bend", accessor: "bend", min: 0, max: 150, step: 1 },
],
},
{
label: "Left Wrist",
mannequinKey: "l_wrist",
dofs: [
{ label: "Bend", accessor: "bend", min: -20, max: 35, step: 1 },
{ label: "Tilt", accessor: "tilt", min: -90, max: 90, step: 1 },
{ label: "Turn", accessor: "turn", min: -90, max: 90, step: 1 },
],
},
{
label: "Right Wrist",
mannequinKey: "r_wrist",
dofs: [
{ label: "Bend", accessor: "bend", min: -35, max: 20, step: 1 },
{ label: "Tilt", accessor: "tilt", min: -90, max: 90, step: 1 },
{ label: "Turn", accessor: "turn", min: -90, max: 90, step: 1 },
],
},
{
label: "Left Leg",
mannequinKey: "l_leg",
dofs: [
{ label: "Raise", accessor: "raise", min: -60, max: 90, step: 1 },
{ label: "Straddle", accessor: "straddle", min: -30, max: 60, step: 1 },
{ label: "Turn", accessor: "turn", min: -60, max: 60, step: 1 },
],
},
{
label: "Right Leg",
mannequinKey: "r_leg",
dofs: [
{ label: "Raise", accessor: "raise", min: -60, max: 90, step: 1 },
{ label: "Straddle", accessor: "straddle", min: -60, max: 30, step: 1 },
{ label: "Turn", accessor: "turn", min: -60, max: 60, step: 1 },
],
},
{
label: "Left Knee",
mannequinKey: "l_knee",
dofs: [
{ label: "Bend", accessor: "bend", min: 0, max: 150, step: 1 },
],
},
{
label: "Right Knee",
mannequinKey: "r_knee",
dofs: [
{ label: "Bend", accessor: "bend", min: 0, max: 150, step: 1 },
],
},
{
label: "Left Ankle",
mannequinKey: "l_ankle",
dofs: [
{ label: "Bend", accessor: "bend", min: -70, max: 80, step: 1 },
{ label: "Tilt", accessor: "tilt", min: -25, max: 25, step: 1 },
{ label: "Turn", accessor: "turn", min: -30, max: 30, step: 1 },
],
},
{
label: "Right Ankle",
mannequinKey: "r_ankle",
dofs: [
{ label: "Bend", accessor: "bend", min: -70, max: 80, step: 1 },
{ label: "Tilt", accessor: "tilt", min: -25, max: 25, step: 1 },
{ label: "Turn", accessor: "turn", min: -30, max: 30, step: 1 },
],
},
...[0, 1, 2, 3, 4].map((n) => fingerConfig("l", n)),
...[0, 1, 2, 3, 4].map((n) => fingerConfig("r", n)),
];
@@ -0,0 +1,141 @@
import * as THREE from "three";
export type CharacterType = "male" | "female" | "child";
/** Reused so grounding, which runs per animation frame during a motion, allocates nothing. */
const groundBox = new THREE.Box3();
const groundScale = new THREE.Vector3();
/**
* Plants the figure's lowest point on y = 0. The one grounding routine — nothing
* in this app may call mannequin-js's own `stepOnGround()`.
*
* `stepOnGround()` is wrong here twice over. It lands the feet on
* `GROUND_LEVEL = -0.7`, the height of the ground disc in mannequin-js's
* built-in Stage, which this app does not use — its grid is at y = 0, so every
* call sank the figure 0.7, about 40% of a 1.8-unit body, taking it under the
* grid and under the invisible deselect plane. And it writes a *world*-space
* measurement straight into a *local* `position.y`, which is only the same thing
* when the figure is a direct child of the scene, as it is in the prototype.
* Here every figure hangs off a wrapper Group carrying the object transform, so
* the wrapper's own Y was silently cancelled out.
*
* Same three steps as the original — clear the offset, measure, re-offset — with
* the measurement converted back through the parent's world Y scale. The 0.01
* sink is mannequin-js's own, and keeps the soles out of the grid plane.
*/
export function groundFigure(figure: THREE.Object3D): void {
figure.position.y = 0;
figure.updateWorldMatrix(true, true);
groundBox.setFromObject(figure);
if (groundBox.isEmpty()) return;
const scaleY = figure.parent?.getWorldScale(groundScale).y || 1;
figure.position.y = (-0.01 - groundBox.min.y) / scaleY;
figure.updateWorldMatrix(true, true);
}
export interface CharacterOptions {
type?: CharacterType;
}
/**
* mannequin-js's scene.js runs `initStage()` as a module-load side effect:
* a full-screen `position:fixed` WebGLRenderer canvas appended to
* document.body, with a `gainsboro` background and an infinite render loop.
* Importing ANY body class (Male/Female/Child) evaluates that module first —
* the canvas then sits on top of every page (the "white flash", and a
* permanent white overlay whenever anything threw before the old cleanup
* ran). Its render loop also steals context/frame budget from the real
* viewport.
*
* The fix is ordering: import scene.js OURSELVES first and tear the stage
* down in the same task, before any body class is imported. The body
* constructors only need the module's `scene` (a plain THREE.Scene) —
* the stage's renderer/canvas are dead weight. Afterwards the stray canvas
* never survives a paint, and every createMannequin sweeps again as
* belt-and-braces (covers dev HMR re-evaluating the module).
*/
type StageRenderer = {
setAnimationLoop(cb: unknown): void;
dispose(): void;
};
interface MannequinSceneModule {
getStage(): { renderer: StageRenderer } | undefined;
scene: THREE.Scene;
}
let sceneModule: Promise<MannequinSceneModule> | null = null;
/** Removes the fixed-position <canvas> elements mannequin-js appends to document.body. */
export function removeMannequinCanvases(): void {
if (typeof document !== "undefined") {
document.querySelectorAll("body > canvas").forEach((c) => c.remove());
}
}
async function loadSceneModule(): Promise<MannequinSceneModule> {
const mod = (await import("mannequin-js/src/scene.js")) as MannequinSceneModule;
// Same-task teardown: the canvas is appended during the import above and
// removed below before the browser gets a rendering opportunity, so it
// never paints.
try {
const stage = mod.getStage();
stage?.renderer?.setAnimationLoop(null);
stage?.renderer?.dispose();
} catch {
// a broken stage must not break figure creation
}
removeMannequinCanvases();
return mod;
}
/** Resolves once the mannequin scene module exists AND its stray stage is dead. */
export function ensureMannequinStageSanitized(): Promise<MannequinSceneModule> {
sceneModule ??= loadSceneModule();
return sceneModule;
}
async function loadMannequin(type: CharacterType): Promise<THREE.Object3D> {
switch (type) {
case "male": {
const { Male } = await import("mannequin-js/src/bodies/Male.js");
return new Male() as unknown as THREE.Object3D;
}
case "female": {
const { Female } = await import("mannequin-js/src/bodies/Female.js");
return new Female() as unknown as THREE.Object3D;
}
case "child": {
const { Child } = await import("mannequin-js/src/bodies/Child.js");
return new Child() as unknown as THREE.Object3D;
}
default: {
const { Male } = await import("mannequin-js/src/bodies/Male.js");
return new Male() as unknown as THREE.Object3D;
}
}
}
export function createMannequin(options: CharacterOptions = {}): Promise<THREE.Object3D> {
return (async () => {
// Sanitize BEFORE the body-class import graph evaluates scene.js.
await ensureMannequinStageSanitized();
const { type = "male" } = options;
const mannequin = await loadMannequin(type);
// Remove the mannequin from any parent created internally.
mannequin.parent?.remove(mannequin);
// Sweep again — dev HMR may have re-evaluated scene.js since last time.
removeMannequinCanvases();
// The constructor ends on stepOnGround(), which left the figure at -0.71.
groundFigure(mannequin);
return mannequin;
})();
}
@@ -0,0 +1,60 @@
/**
* One-way mirroring for the pose editor: copy the selected side's angles onto
* the opposite side, either for one joint or for its whole limb chain.
*
* Copies mannequin's own named angles, never raw rotations. Every named setter
* already applies its own per-side sign flip, so assigning the same value to the
* opposite joint produces the mirrored pose without this file knowing a single
* axis or sign.
*
* Distinct from motion.ts's `mirrorPosture`, which swaps both sides of a whole
* posture to build a walk cycle. This one overwrites one side from the other.
*
* Ported from 3JS-Shot-composer/pose-author.html.
*/
const MIRROR_PROPS: Record<string, string[]> = {
arm: ["raise", "straddle", "turn"],
leg: ["raise", "straddle", "turn"],
elbow: ["bend"],
knee: ["bend"],
wrist: ["bend", "tilt", "turn"],
ankle: ["bend", "tilt", "turn"],
finger: ["bend", "straddle", "turn"],
};
const LIMB_CHAINS = [
["arm", "elbow", "wrist", "finger_0", "finger_1", "finger_2", "finger_3", "finger_4"],
["leg", "knee", "ankle"],
];
/** The side a joint key belongs to, or null for body/torso/head, which cannot mirror. */
export function sideOf(key: string | null): "l" | "r" | null {
if (!key) return null;
if (key.startsWith("l_")) return "l";
if (key.startsWith("r_")) return "r";
return null;
}
export function mirrorJoint(figure: any, key: string, wholeLimb: boolean): void {
const side = sideOf(key);
if (!side) return;
const part = key.slice(2);
const parts = wholeLimb ? LIMB_CHAINS.find((c) => c.includes(part)) ?? [part] : [part];
const other = side === "l" ? "r" : "l";
for (const p of parts) {
const src = figure[`${side}_${p}`];
const dst = figure[`${other}_${p}`];
if (!src || !dst) continue;
for (const prop of MIRROR_PROPS[p.startsWith("finger") ? "finger" : p] ?? []) {
dst[prop] = src[prop];
}
if (p.startsWith("finger")) {
dst.mid.bend = src.mid.bend;
dst.tip.bend = src.tip.bend;
}
}
figure.updateMatrixWorld(true);
}
@@ -0,0 +1,182 @@
/**
* mannequin-js posture v7 — the only serialized pose format.
*
* Entry order and lengths are fixed by `Mannequin.posture`
* (mannequin-js 5.2.3, src/bodies/Mannequin.js:204). Entries are NOT uniform
* XYZ triples: index 0 is a position, knees and elbows are a single z-bend,
* and a finger carries its mid/tip phalanges in the same entry.
*
* `pelvis` and `neck` are real joints in the chain (body → pelvis → torso →
* neck → head) but are absent here, so any rotation applied to them is lost on
* save. They are deliberately not exposed as editable — see jointConfig.ts.
*/
export const POSTURE_VERSION = 7;
/** Serialized entry names, in order. Index 0 is `body.position`, the rest are rotations. */
export const POSTURE_ENTRIES = [
"body.position",
"body",
"torso",
"head",
"l_leg",
"l_knee",
"l_ankle",
"r_leg",
"r_knee",
"r_ankle",
"l_arm",
"l_elbow",
"l_wrist",
"l_finger_0",
"l_finger_1",
"l_finger_2",
"l_finger_3",
"l_finger_4",
"r_arm",
"r_elbow",
"r_wrist",
"r_finger_0",
"r_finger_1",
"r_finger_2",
"r_finger_3",
"r_finger_4",
] as const;
/**
* Values per entry, index-aligned with POSTURE_ENTRIES.
* 3 = [x,y,z] · 1 = [z] for Elbow/Knee · 7 = [x,y,z] + mid[x,z] + tip[x,z] for a Finger.
*/
export const POSTURE_ENTRY_LENGTHS = [
3, 3, 3, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 7, 7, 7, 7, 7, 3, 1, 3, 7, 7, 7, 7, 7,
];
export type JointEuler = [number, number, number];
export interface Posture {
version: number;
data: number[][];
/**
* Full euler in degrees for the joints v7 cannot hold, keyed by joint. Absent
* on the bundled pose files, which predate it. See LOSSY_JOINTS.
*/
extra?: Record<string, JointEuler>;
}
/**
* `Elbow.posture` and `Knee.posture` serialize a single number — `rotation.z`,
* the bend — so the x and y a gizmo drag puts on them are dropped on save. That
* is the forearm/shin twist praying hands and crossed arms need, so it is kept
* in `Posture.extra` instead. mannequin-js reads only `version` and `data`, so
* the field rides along through `figure.posture = …` untouched, and the v7
* structure itself is unchanged.
*/
export const LOSSY_JOINTS = ["l_elbow", "r_elbow", "l_knee", "r_knee"] as const;
const toDeg = (r: number) => (r * 180) / Math.PI;
const toRad = (d: number) => (d * Math.PI) / 180;
/** The figure's v7 posture plus the axes v7 alone would lose. */
export function readPosture(figure: any): Posture {
const extra: Record<string, JointEuler> = {};
for (const key of LOSSY_JOINTS) {
const joint = figure?.[key];
if (!joint) continue;
joint.rotation.reorder("XYZ");
extra[key] = [toDeg(joint.rotation.x), toDeg(joint.rotation.y), toDeg(joint.rotation.z)];
}
return { ...(figure.posture as Posture), extra };
}
/** Applies a posture, then restores the axes `.posture` on its own would zero. */
export function writePosture(figure: any, posture: Posture): void {
figure.posture = posture;
for (const key of LOSSY_JOINTS) {
const euler = posture.extra?.[key];
const joint = figure?.[key];
if (euler && joint) {
joint.rotation.set(toRad(euler[0]), toRad(euler[1]), toRad(euler[2]), "XYZ");
}
}
figure.updateMatrixWorld(true);
}
/**
* Why `value` is not a valid v7 posture, or null if it is.
* Names the offending entry so a bad pose file points at its own problem.
*/
export function describePostureError(value: unknown): string | null {
if (!value || typeof value !== "object") return "posture is not an object";
const posture = value as Partial<Posture>;
if (posture.version !== POSTURE_VERSION) {
return `unsupported posture version ${String(posture.version)} (expected ${POSTURE_VERSION})`;
}
if (!Array.isArray(posture.data)) return "posture.data is not an array";
if (posture.data.length !== POSTURE_ENTRY_LENGTHS.length) {
return `posture.data has ${posture.data.length} entries (expected ${POSTURE_ENTRY_LENGTHS.length})`;
}
for (let i = 0; i < posture.data.length; i++) {
const entry = posture.data[i];
const expected = POSTURE_ENTRY_LENGTHS[i];
const name = POSTURE_ENTRIES[i];
if (!Array.isArray(entry)) return `posture.data[${i}] (${name}) is not an array`;
if (entry.length !== expected) {
return `posture.data[${i}] (${name}) has ${entry.length} values (expected ${expected})`;
}
for (let j = 0; j < entry.length; j++) {
if (!Number.isFinite(entry[j])) {
return `posture.data[${i}] (${name})[${j}] is not a finite number`;
}
}
}
return null;
}
export function isValidPosture(value: unknown): value is Posture {
return describePostureError(value) === null;
}
/** Deep copy, so stored postures never alias the live figure's arrays. */
export function clonePosture(posture: Posture): Posture {
const clone: Posture = { ...posture, data: posture.data.map((entry) => [...entry]) };
if (posture.extra) {
clone.extra = Object.fromEntries(
Object.entries(posture.extra).map(([key, euler]) => [key, [...euler] as JointEuler]),
);
}
return clone;
}
/**
* Swaps each l_* rotation block with its r_* counterpart (legs, knees, ankles,
* arms, elbows, wrists, fingers). This reuses the pose's own authored angles —
* it never fabricates a value — so from a single authored mid-stride pose it
* produces the opposite-leg mid-stride for a walk/run cycle. Note this is NOT
* a true left-right mirror (body/torso/head turn is left untouched), just a
* limb-pair swap, which is all a symmetric gait cycle needs.
*/
export function mirrorPosture(posture: Posture): Posture {
const clone = clonePosture(posture);
for (let i = 0; i < POSTURE_ENTRIES.length; i++) {
const name = POSTURE_ENTRIES[i];
if (!name.startsWith("l_")) continue;
const j = POSTURE_ENTRIES.indexOf(`r_${name.slice(2)}` as (typeof POSTURE_ENTRIES)[number]);
if (j === -1) continue;
[clone.data[i], clone.data[j]] = [clone.data[j], clone.data[i]];
}
if (clone.extra) {
for (const key of Object.keys(clone.extra)) {
if (!key.startsWith("l_")) continue;
const rKey = `r_${key.slice(2)}`;
const rVal = clone.extra[rKey];
if (!rVal) continue;
[clone.extra[key], clone.extra[rKey]] = [rVal, clone.extra[key]];
}
}
return clone;
}
@@ -0,0 +1,45 @@
/**
* Primitive + character three.js object factory — Svelte port of
* open-media's PrimitiveObject.tsx shape switch (MIT). Characters come from
* mannequinFactory; primitives are plain three.js geometry with a neutral
* blockout material.
*/
import * as THREE from 'three';
import type { PrimitiveType } from '../shotStore.svelte';
const BLOCKOUT_MATERIAL = new THREE.MeshStandardMaterial({
color: 0x9aa4b2,
roughness: 0.85,
metalness: 0.05,
});
export function createPrimitiveMesh(type: PrimitiveType): THREE.Mesh {
let geometry: THREE.BufferGeometry;
switch (type) {
case 'cube':
geometry = new THREE.BoxGeometry(1, 1, 1);
break;
case 'plane':
geometry = new THREE.BoxGeometry(4, 0.1, 4);
break;
case 'cylinder':
geometry = new THREE.CylinderGeometry(0.5, 0.5, 1, 24);
break;
case 'sphere':
geometry = new THREE.SphereGeometry(0.5, 24, 16);
break;
case 'capsule':
geometry = new THREE.CapsuleGeometry(0.4, 1, 6, 16);
break;
case 'cone':
geometry = new THREE.ConeGeometry(0.5, 1, 24);
break;
case 'torus':
geometry = new THREE.TorusGeometry(0.5, 0.18, 16, 40);
break;
}
const mesh = new THREE.Mesh(geometry, BLOCKOUT_MATERIAL);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
@@ -0,0 +1,122 @@
import * as THREE from "three";
import type { Posture } from "../helpers/posture";
import { ensureMannequinStageSanitized } from "../helpers/mannequinFactory";
export interface KeyframeLike {
time: number;
transform: {
position: [number, number, number];
rotation: [number, number, number];
scale: [number, number, number];
};
posture?: Posture;
/** Camera field of view in degrees. Only meaningful for camera objects. */
fov?: number;
}
export interface SampledTrack {
transform: KeyframeLike["transform"];
posture?: Posture;
fov?: number;
}
// Kicked off once at module load, not lazily inside sampleTrack: sampleTrack
// runs synchronously every frame (from useFrame), so it cannot await anything.
// This module is also imported by a plain-Node self-check (see
// sampleTrack.selfcheck.ts), and mannequin-js/src/mannequin.js statically
// re-exports mannequin-js/src/scene.js, which touches `document`/`window`
// unconditionally at load and crashes outside a browser — hence the
// dynamic import wrapped in a rejection handler instead of a static one.
let blendFn: ((a: Posture, b: Posture, k: number) => Posture) | null = null;
import("mannequin-js/src/mannequin.js")
.then((mod) => { blendFn = (mod as any).blend ?? null; })
.catch(() => { blendFn = null; });
// mannequin.js's re-export evaluates scene.js, whose module-load side effect
// appends a full-screen fixed WebGL canvas to document.body (white overlay,
// steals pointer events). Kill it no later than this import resolves — a
// blocks-only scene never calls createMannequin, so this is the only
// guaranteed cleanup point for character-less compositions.
ensureMannequinStageSanitized().catch(() => {});
function lerp(a: number, b: number, k: number): number {
return a + (b - a) * k;
}
function lerpVec3(a: [number, number, number], b: [number, number, number], k: number): [number, number, number] {
return [lerp(a[0], b[0], k), lerp(a[1], b[1], k), lerp(a[2], b[2], k)];
}
function slerpRotation(a: [number, number, number], b: [number, number, number], k: number): [number, number, number] {
const qa = new THREE.Quaternion().setFromEuler(new THREE.Euler(...a));
const qb = new THREE.Quaternion().setFromEuler(new THREE.Euler(...b));
const q = qa.clone().slerp(qb, k);
const e = new THREE.Euler().setFromQuaternion(q);
return [e.x, e.y, e.z];
}
function lerpExtra(
a: Posture["extra"],
b: Posture["extra"],
k: number,
): Posture["extra"] | undefined {
if (!a && !b) return undefined;
const source = a ?? b!;
const other = b ?? a!;
const result: NonNullable<Posture["extra"]> = {};
for (const key of Object.keys(source)) {
const sv = source[key];
const ov = other[key] ?? sv;
result[key] = [lerp(sv[0], ov[0], k), lerp(sv[1], ov[1], k), lerp(sv[2], ov[2], k)];
}
return result;
}
/**
* Samples a track of keyframes at `time`. AnimatedObject only calls this once
* an object has at least one keyframe (see composerStore.ts), so this never
* receives an empty array from a real caller — an empty array is treated as
* a caller bug and throws.
*/
export function sampleTrack(keyframes: KeyframeLike[], time: number): SampledTrack {
if (keyframes.length === 0) throw new Error("sampleTrack: no keyframes");
const sorted = keyframes.length > 1 ? [...keyframes].sort((a, b) => a.time - b.time) : keyframes;
if (sorted.length === 1 || time <= sorted[0].time) {
return { transform: sorted[0].transform, posture: sorted[0].posture, fov: sorted[0].fov };
}
const last = sorted[sorted.length - 1];
if (time >= last.time) return { transform: last.transform, posture: last.posture, fov: last.fov };
let a = sorted[0];
let b = last;
for (let i = 0; i < sorted.length - 1; i++) {
if (time >= sorted[i].time && time <= sorted[i + 1].time) {
a = sorted[i];
b = sorted[i + 1];
break;
}
}
const span = b.time - a.time;
const k = span > 0 ? 0.5 - 0.5 * Math.cos(Math.PI * ((time - a.time) / span)) : 0;
const transform: KeyframeLike["transform"] = {
position: lerpVec3(a.transform.position, b.transform.position, k),
rotation: slerpRotation(a.transform.rotation, b.transform.rotation, k),
scale: lerpVec3(a.transform.scale, b.transform.scale, k),
};
const fov = a.fov === undefined && b.fov === undefined
? undefined
: lerp(a.fov ?? b.fov!, b.fov ?? a.fov!, k);
if (!a.posture && !b.posture) return { transform, fov };
if (!a.posture) return { transform, posture: b.posture, fov };
if (!b.posture) return { transform, posture: a.posture, fov };
const posture: Posture = blendFn
? { ...blendFn(a.posture, b.posture, k), extra: lerpExtra(a.posture.extra, b.posture.extra, k) }
: (k < 0.5 ? a.posture : b.posture);
return { transform, posture, fov };
}
@@ -0,0 +1,742 @@
/**
* Shot composition store — Svelte 5 runes port of open-media's composerStore
* (MIT). The data model is identical: objects with SceneTransform + posture v7
* + keyframes, shot params, playback, 50-step snapshot undo with drag
* bracketing.
*
* Differences from the reference:
* - No `objectInstances` Map — the viewport keeps its own three.js registry.
* - `scene_json` on the server is the source of truth: local edits autosave
* (debounced), and `shot.updated` SSE events reload the composition unless
* a drag/gesture is in progress (`dragInProgress` defers, matching the
* canvas graph-sync rule).
*/
import * as THREE from 'three';
import {
clonePosture,
describePostureError,
type Posture,
} from './helpers/posture';
import { sampleTrack } from './motion/sampleTrack';
import { normalizeShotParams, type ShotParams } from './calibration/shotSolver';
export type ComposerTool = 'select' | 'move' | 'rotate' | 'scale' | 'pose';
export type CharacterType = 'male' | 'female' | 'child';
export type PrimitiveType = 'cube' | 'plane' | 'cylinder' | 'sphere' | 'capsule' | 'cone' | 'torus';
export type ObjectType = CharacterType | PrimitiveType | 'camera';
export interface SceneTransform {
position: [number, number, number];
rotation: [number, number, number];
scale: [number, number, number];
}
export interface Keyframe {
id: string;
time: number;
transform: SceneTransform;
posture?: Posture;
fov?: number;
}
export interface SceneObject {
id: string;
name: string;
type: ObjectType;
visible: boolean;
locked: boolean;
transform: SceneTransform;
posture?: Posture;
defaultPosture?: Posture;
keyframes: Keyframe[];
liveEditTime: number | null;
fov?: number;
}
export interface PlaybackState {
playing: boolean;
elapsed: number;
speed: number;
duration: number;
}
export interface ShotComposition {
id: number;
title: string;
scene: SceneData;
}
export interface CameraKeyframe {
id: string;
time: number;
position: [number, number, number];
target: [number, number, number];
fov: number;
}
export interface SceneData {
objects: SceneObject[];
selectedObjectId?: string | null;
shotParams?: Partial<Omit<ShotParams, 'composition'>> & { composition?: string };
playback?: PlaybackState;
cameraTrack?: CameraKeyframe[];
}
/** Hard cap: exported blockout videos stay under a minute. */
export const MAX_TIMELINE_DURATION = 60;
const HISTORY_LIMIT = 50;
const KEYFRAME_EPSILON = 1 / 24;
const PRIMITIVE_TYPES: PrimitiveType[] = ['cube', 'plane', 'cylinder', 'sphere', 'capsule', 'cone', 'torus'];
export function isPrimitiveType(type: ObjectType): type is PrimitiveType {
return (PRIMITIVE_TYPES as string[]).includes(type);
}
export function isCharacterType(type: ObjectType): type is CharacterType {
return ['male', 'female', 'child'].includes(type);
}
function uid(): string {
return typeof crypto !== 'undefined' && 'randomUUID' in crypto
? crypto.randomUUID()
: `id-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
}
function findNearKeyframeIndex(keyframes: Keyframe[], time: number): number {
return keyframes.findIndex((k) => Math.abs(k.time - time) <= KEYFRAME_EPSILON);
}
function upsertKeyframe(
keyframes: Keyframe[],
time: number,
patch: { transform?: Partial<SceneTransform>; posture?: Posture; fov?: number },
fallback: { transform: SceneTransform; posture?: Posture; fov?: number },
): Keyframe[] {
const index = findNearKeyframeIndex(keyframes, time);
if (index >= 0) {
const existing = keyframes[index];
const updated: Keyframe = {
...existing,
transform: patch.transform ? { ...existing.transform, ...patch.transform } : existing.transform,
posture: patch.posture ? clonePosture(patch.posture) : existing.posture,
fov: patch.fov ?? existing.fov,
};
const next = [...keyframes];
next[index] = updated;
return next;
}
const sampled = keyframes.length > 0 ? sampleTrack(keyframes, time) : fallback;
const seeded: Keyframe = {
id: uid(),
time,
transform: patch.transform ? { ...sampled.transform, ...patch.transform } : sampled.transform,
posture: patch.posture ? clonePosture(patch.posture) : sampled.posture,
fov: patch.fov ?? sampled.fov,
};
return [...keyframes, seeded].sort((a, b) => a.time - b.time);
}
/** The transform/posture/fov a live edit should build on: staged edit or sampled track. */
export function stageBase(
o: SceneObject,
elapsed: number,
): { transform: SceneTransform; posture?: Posture; fov?: number } {
const isLive = o.liveEditTime !== null && Math.abs(o.liveEditTime - elapsed) < 1e-6;
if (isLive || o.keyframes.length === 0) {
return { transform: o.transform, posture: o.posture, fov: o.fov };
}
return sampleTrack(o.keyframes, elapsed);
}
function objectName(type: ObjectType, index: number): string {
return `${type.charAt(0).toUpperCase()}${type.slice(1)} ${String(index).padStart(2, '0')}`;
}
function createInitialObject(): SceneObject {
const transform: SceneTransform = { position: [0, 0, 0], rotation: [0, 0, 0], scale: [1, 1, 1] };
return {
id: uid(),
name: 'Male 01',
type: 'male',
visible: true,
locked: false,
transform,
keyframes: [{ id: uid(), time: 0, transform }],
liveEditTime: null,
};
}
function canPoseSelection(objects: SceneObject[], id: string | null): boolean {
const target = objects.find((o) => o.id === id);
return !!target && !isPrimitiveType(target.type) && target.type !== 'camera';
}
// ── Svelte 5 runes store ─────────────────────────────────────────────────
function createStore() {
let objects = $state<SceneObject[]>([]);
let compositionId = $state<number | null>(null);
let title = $state('Untitled composition');
let selectedObjectId = $state<string | null>(null);
let shotParams = $state<SceneData['shotParams']>({});
let playback = $state<PlaybackState>({ playing: false, elapsed: 0, speed: 1, duration: 6 });
let cameraTrack = $state<CameraKeyframe[]>([]);
let loaded = $state(false);
let history = $state<SceneObject[][]>([]);
let future = $state<SceneObject[][]>([]);
let suppressHistory = false;
let groupDepth = 0;
let groupRecorded = false;
let dragInProgress = $state(false);
let saveTimer: ReturnType<typeof setTimeout> | null = null;
let lastServerVersion = 0;
function withoutHistory<T>(fn: () => T): T {
suppressHistory = true;
try {
return fn();
} finally {
suppressHistory = false;
}
}
function recordHistory(before: SceneObject[]) {
if (suppressHistory) return;
if (groupDepth > 0) {
if (groupRecorded) return;
groupRecorded = true;
}
history = [...history, before].slice(-HISTORY_LIMIT);
future = [];
}
function commitObjects(next: SceneObject[]) {
const before = objects;
objects = next;
recordHistory(before);
scheduleSave();
}
// ── server sync ─────────────────────────────────────────────────
async function loadComposition(sessionId: number): Promise<ShotComposition | null> {
const resp = await fetch(`/api/shots/by-session/${sessionId}`);
if (!resp.ok) return null;
const comp = (await resp.json()) as ShotComposition;
applyServerScene(comp);
return comp;
}
function applyServerScene(comp: ShotComposition) {
compositionId = comp.id;
title = comp.title;
const scene = comp.scene ?? {};
objects = (scene.objects ?? []).map((o) => ({
...o,
keyframes: o.keyframes ?? [],
}));
selectedObjectId = scene.selectedObjectId ?? objects[0]?.id ?? null;
// Legacy composition JSON can carry unknown/aliased param ids; restoring
// those verbatim NaN'd the camera (see normalizeShotParams).
shotParams = normalizeShotParams(scene.shotParams);
if (scene.playback) playback = scene.playback;
cameraTrack = (scene.cameraTrack ?? []).map((k) => ({ ...k }));
loaded = true;
history = [];
future = [];
}
function scheduleSave() {
if (compositionId === null) return;
if (saveTimer) clearTimeout(saveTimer);
saveTimer = setTimeout(() => void saveScene(), 600);
}
async function saveScene() {
if (compositionId === null) return;
const payload = JSON.stringify(toSceneData());
lastServerVersion = Date.now();
try {
await fetch(`/api/shots/${compositionId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ scene_json: payload }),
});
} catch {
/* offline — next edit retries */
}
}
function toSceneData(): SceneData {
return {
objects: objects.map((o) => ({ ...o })),
selectedObjectId,
shotParams,
playback,
cameraTrack,
};
}
/** SSE: the agent mutated the scene server-side. Ignore our own echo. */
function handleShotUpdated(data: { shot_id?: number; reason?: string }) {
if (data.shot_id !== compositionId) return;
if (dragInProgress) return; // a gizmo drag wins; the refetch happens on dragstop
if (Date.now() - lastServerVersion < 1500) return; // our own autosave echo
if (compositionId === null) return;
void (async () => {
const resp = await fetch(`/api/shots/${compositionId}`);
if (!resp.ok) return;
applyServerScene((await resp.json()) as ShotComposition);
})();
}
// ── actions ─────────────────────────────────────────────────────
function addObject(type: ObjectType) {
const position: [number, number, number] = [objects.length * 1.5, 0, 0];
const rotation: [number, number, number] = [0, 0, 0];
const transform: SceneTransform = { position, rotation, scale: [1, 1, 1] };
const object: SceneObject = {
id: uid(),
name: objectName(type, objects.length + 1),
type,
visible: true,
locked: false,
transform,
fov: type === 'camera' ? 10 : undefined,
keyframes: type === 'camera' ? [] : [{ id: uid(), time: 0, transform }],
liveEditTime: null,
};
commitObjects([...objects, object]);
selectedObjectId = object.id;
selectedKeyframeId = null;
activeTool = 'move';
}
let selectedKeyframeId = $state<string | null>(null);
let activeTool = $state<ComposerTool>('move');
function deleteObject(id: string) {
const remaining = objects.filter((o) => o.id !== id);
const nextSelected =
selectedObjectId === id ? (remaining.length > 0 ? remaining[0].id : null) : selectedObjectId;
const poseStillValid = activeTool !== 'pose' || canPoseSelection(remaining, nextSelected);
commitObjects(remaining);
selectedObjectId = nextSelected;
if (selectedObjectId === id) selectedKeyframeId = null;
if (!poseStillValid) {
activeTool = 'move';
}
}
function clearScene() {
commitObjects([]);
selectedObjectId = null;
selectedKeyframeId = null;
activeTool = 'move';
playback = { ...playback, playing: false, elapsed: 0 };
cameraTrack = [];
}
function selectObject(id: string) {
if (selectedObjectId === id && selectedKeyframeId === null) return;
if (activeTool === 'pose' && !canPoseSelection(objects, id)) {
selectedObjectId = id;
selectedKeyframeId = null;
activeTool = 'move';
return;
}
selectedObjectId = id;
selectedKeyframeId = null;
}
function clearSelection() {
selectedObjectId = null;
selectedKeyframeId = null;
}
function renameObject(id: string, name: string) {
commitObjects(objects.map((o) => (o.id === id ? { ...o, name } : o)));
}
function toggleObjectVisibility(id: string) {
commitObjects(objects.map((o) => (o.id === id ? { ...o, visible: !o.visible } : o)));
}
function toggleObjectLock(id: string) {
commitObjects(objects.map((o) => (o.id === id ? { ...o, locked: !o.locked } : o)));
}
function updateObjectTransform(id: string, transform: Partial<SceneTransform>) {
const time = playback.elapsed;
commitObjects(
objects.map((o) => {
if (o.id !== id) return o;
const base = stageBase(o, time);
return {
...o,
transform: { ...base.transform, ...transform },
posture: base.posture,
fov: base.fov,
liveEditTime: time,
};
}),
);
}
function updateObjectPosture(id: string, posture: Posture) {
const error = describePostureError(posture);
if (error) {
console.error(`[shotStore] rejected posture for ${id}: ${error}`);
return;
}
const time = playback.elapsed;
commitObjects(
objects.map((o) => {
if (o.id !== id) return o;
const base = stageBase(o, time);
return { ...o, transform: base.transform, posture: clonePosture(posture), liveEditTime: time };
}),
);
}
function updateObjectDefaultPosture(id: string, posture: Posture) {
withoutHistory(() => {
objects = objects.map((o) => (o.id === id ? { ...o, defaultPosture: clonePosture(posture) } : o));
});
}
function updateObjectFov(id: string, fov: number) {
const time = playback.elapsed;
commitObjects(
objects.map((o) => {
if (o.id !== id) return o;
const base = stageBase(o, time);
return { ...o, transform: base.transform, posture: base.posture, fov, liveEditTime: time };
}),
);
}
function setActiveTool(tool: ComposerTool) {
if (tool === 'pose' && !canPoseSelection(objects, selectedObjectId)) return;
activeTool = tool;
}
function setShotParams(next: SceneData['shotParams']) {
shotParams = { ...shotParams, ...next };
scheduleSave();
}
function setPlaying(playing: boolean) {
playback = { ...playback, playing };
}
function setElapsed(elapsed: number) {
playback = { ...playback, elapsed };
}
function setSpeed(speed: number) {
playback = { ...playback, speed };
}
function setDuration(duration: number) {
const clamped = Math.min(Math.max(duration, 1), MAX_TIMELINE_DURATION);
playback = { ...playback, duration: clamped, elapsed: Math.min(playback.elapsed, clamped) };
scheduleSave();
}
// ── object keyframes (motion) ───────────────────────────────────
// Port of composerStore's addKeyframe/commitLiveKeyframe/deleteKeyframe/
// duplicateKeyframe/moveKeyframeTime/updateKeyframeTransform/selectKeyframe.
// A keyframe pins {transform, posture, fov} at a time; playback samples the
// track per frame (see ShotViewport's applyTrackSampling).
/** Upserts a keyframe at `time`, seeding unsampled fields from the object's current state. */
function addKeyframe(objectId: string, time: number) {
commitObjects(
objects.map((o) =>
o.id === objectId
? {
...o,
keyframes: upsertKeyframe(o.keyframes, time, {}, {
transform: o.transform,
posture: o.posture,
fov: o.fov,
}),
}
: o,
),
);
playback = { ...playback, duration: Math.max(playback.duration, time) };
scheduleSave();
}
/** Commits the object's current staged (live) state as a keyframe after the last one. */
function commitLiveKeyframe(objectId: string) {
const target = objects.find((o) => o.id === objectId);
if (!target) return;
const time = playback.elapsed;
const base = stageBase(target, time);
// The first keyframe ever committed lands where the user is parked, not +1s.
const newTime = target.keyframes.length
? Math.max(target.keyframes[target.keyframes.length - 1].time + 1, time)
: time;
const keyframe: Keyframe = {
id: uid(),
time: newTime,
transform: { ...base.transform },
posture: base.posture ? clonePosture(base.posture) : undefined,
fov: base.fov,
};
commitObjects(
objects.map((o) =>
o.id === objectId ? { ...o, keyframes: [...o.keyframes, keyframe].sort((a, b) => a.time - b.time) } : o,
),
);
selectedKeyframeId = null;
playback = {
...playback,
elapsed: newTime,
playing: false,
duration: Math.max(playback.duration, newTime),
};
}
function deleteKeyframe(objectId: string, keyframeId: string) {
const target = objects.find((o) => o.id === objectId);
if (!target || target.keyframes.length <= 1) return; // a track keeps ≥1 anchor
commitObjects(
objects.map((o) =>
o.id === objectId ? { ...o, keyframes: o.keyframes.filter((k) => k.id !== keyframeId) } : o,
),
);
if (selectedKeyframeId === keyframeId) selectedKeyframeId = null;
}
function duplicateKeyframe(objectId: string, keyframeId: string) {
const object = objects.find((o) => o.id === objectId);
const source = object?.keyframes.find((k) => k.id === keyframeId);
if (!object || !source) return;
const duplicate: Keyframe = {
id: uid(),
time: Math.min(source.time + 0.25, playback.duration),
transform: {
position: [...source.transform.position] as [number, number, number],
rotation: [...source.transform.rotation] as [number, number, number],
scale: [...source.transform.scale] as [number, number, number],
},
posture: source.posture ? clonePosture(source.posture) : undefined,
};
commitObjects(
objects.map((o) =>
o.id === objectId ? { ...o, keyframes: [...o.keyframes, duplicate].sort((a, b) => a.time - b.time) } : o,
),
);
selectedKeyframeId = duplicate.id;
}
function moveKeyframeTime(objectId: string, keyframeId: string, newTime: number) {
const clamped = Math.min(Math.max(newTime, 0), MAX_TIMELINE_DURATION);
commitObjects(
objects.map((o) =>
o.id !== objectId
? o
: {
...o,
keyframes: o.keyframes
.map((k) => (k.id === keyframeId ? { ...k, time: clamped } : k))
.sort((a, b) => a.time - b.time),
},
),
);
}
function updateKeyframeTransform(objectId: string, keyframeId: string, transform: Partial<SceneTransform>) {
commitObjects(
objects.map((o) => {
if (o.id !== objectId) return o;
return {
...o,
keyframes: o.keyframes.map((k) =>
k.id === keyframeId ? { ...k, transform: { ...k.transform, ...transform } } : k,
),
};
}),
);
}
/** Selecting a keyframe parks the playhead at its time (reference parity). */
function selectKeyframe(id: string | null) {
const object = objects.find((o) => o.id === selectedObjectId);
const keyframe = object?.keyframes.find((k) => k.id === id);
selectedKeyframeId = id;
if (keyframe) playback = { ...playback, elapsed: keyframe.time, playing: false };
}
/** Keyframe the given camera view (or drop/replace at ~same time). */
function setCameraKeyframe(
time: number,
view: { position: [number, number, number]; target: [number, number, number]; fov: number },
) {
const t = Math.min(Math.max(time, 0), playback.duration);
const idx = cameraTrack.findIndex((k) => Math.abs(k.time - t) < 1 / 24);
if (idx >= 0) {
cameraTrack[idx] = { ...cameraTrack[idx], ...view, time: t };
} else {
cameraTrack = [...cameraTrack, { id: uid(), time: t, ...view }].sort((a, b) => a.time - b.time);
}
scheduleSave();
}
function removeCameraKeyframe(id: string) {
cameraTrack = cameraTrack.filter((k) => k.id !== id);
scheduleSave();
}
function removeCameraKeyframeAt(time: number) {
const idx = cameraTrack.findIndex((k) => Math.abs(k.time - time) < 1 / 12);
if (idx >= 0) removeCameraKeyframe(cameraTrack[idx].id);
}
/**
* Timeline asks to keyframe the live camera view at `time`. The viewport
* owns the camera, so it watches `cameraKeyframeRequest` and fulfills via
* setCameraKeyframe with the current pose. Nonce makes back-to-back
* requests at the same time observable.
*/
let cameraKeyframeRequest = $state<{ time: number; nonce: number } | null>(null);
function requestCameraKeyframeAt(time: number) {
cameraKeyframeRequest = { time: Math.min(Math.max(time, 0), playback.duration), nonce: Date.now() };
}
function undo() {
if (history.length === 0) return;
const previous = history[history.length - 1];
const selectionSurvives = previous.some((o) => o.id === selectedObjectId);
withoutHistory(() => {
future = [objects, ...future].slice(0, HISTORY_LIMIT);
objects = previous;
history = history.slice(0, -1);
if (!selectionSurvives) selectedObjectId = previous[0]?.id ?? null;
});
scheduleSave();
}
function redo() {
if (future.length === 0) return;
const next = future[0];
const selectionSurvives = next.some((o) => o.id === selectedObjectId);
withoutHistory(() => {
history = [...history, objects].slice(-HISTORY_LIMIT);
objects = next;
future = future.slice(1);
if (!selectionSurvives) selectedObjectId = next[0]?.id ?? null;
});
scheduleSave();
}
function beginHistoryGroup() {
groupDepth += 1;
groupRecorded = false;
}
function endHistoryGroup() {
groupDepth = Math.max(0, groupDepth - 1);
}
return {
// state (getters)
get objects() {
return objects;
},
get compositionId() {
return compositionId;
},
get title() {
return title;
},
get selectedObjectId() {
return selectedObjectId;
},
get selectedKeyframeId() {
return selectedKeyframeId;
},
get activeTool() {
return activeTool;
},
get shotParams() {
return shotParams;
},
get playback() {
return playback;
},
get cameraTrack() {
return cameraTrack;
},
get cameraKeyframeRequest() {
return cameraKeyframeRequest;
},
get loaded() {
return loaded;
},
get canUndo() {
return history.length > 0;
},
get canRedo() {
return future.length > 0;
},
get dragInProgress() {
return dragInProgress;
},
set dragInProgress(v: boolean) {
dragInProgress = v;
},
get selectedObject(): SceneObject | null {
return objects.find((o) => o.id === selectedObjectId) ?? null;
},
// sync
loadComposition,
applyServerScene,
handleShotUpdated,
flushSave: saveScene,
// actions
addObject,
deleteObject,
clearScene,
selectObject,
clearSelection,
renameObject,
toggleObjectVisibility,
toggleObjectLock,
updateObjectTransform,
updateObjectPosture,
updateObjectDefaultPosture,
updateObjectFov,
setActiveTool,
setShotParams,
setPlaying,
setElapsed,
setSpeed,
setDuration,
setCameraKeyframe,
removeCameraKeyframe,
removeCameraKeyframeAt,
requestCameraKeyframeAt,
addKeyframe,
commitLiveKeyframe,
deleteKeyframe,
duplicateKeyframe,
moveKeyframeTime,
updateKeyframeTransform,
selectKeyframe,
undo,
redo,
beginHistoryGroup,
endHistoryGroup,
};
}
export const shotStore = createStore();
export type ShotStore = typeof shotStore;
export { createInitialObject, THREE };
+9
View File
@@ -0,0 +1,9 @@
declare module 'mannequin-js/src/mannequin.js' { export function blend(a: any, b: any, k: number): any; }
declare module 'mannequin-js/src/scene.js' {
export function getStage(): { renderer: { setAnimationLoop(cb: unknown): void; dispose(): void } } | undefined;
export const scene: import('three').Scene;
}
declare module 'mannequin-js/src/bodies/Mannequin.js' { export class Mannequin { [key:string]: any; posture: unknown; select(s: boolean): void; stepOnGround(): void; } }
declare module 'mannequin-js/src/bodies/Male.js' { export class Male { [key:string]: any; posture: unknown; select(s: boolean): void; stepOnGround(): void; } }
declare module 'mannequin-js/src/bodies/Female.js' { export class Female { [key:string]: any; posture: unknown; select(s: boolean): void; stepOnGround(): void; } }
declare module 'mannequin-js/src/bodies/Child.js' { export class Child { [key:string]: any; posture: unknown; select(s: boolean): void; stepOnGround(): void; } }
@@ -0,0 +1,665 @@
<script lang="ts">
import { onMount } from 'svelte';
import { toStore } from 'svelte/store';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import AppHeader from '$lib/components/AppHeader.svelte';
import AgentChat from '$lib/components/agent/AgentChat.svelte';
import AgentComposer from '$lib/components/agent/AgentComposer.svelte';
import { agentApi, playgroundApi, workflows, type AgentMessage, type AgentPlan, type AgentSession, type AgentTask } from '$lib/api';
import type { AgentComposerPayload, SkillOption, WorkflowOption } from '$lib/agentComposer';
import { connectEvents } from '$lib/events';
import { toast } from '$lib/toast';
import { shotStore } from '$lib/shot/shotStore.svelte';
import { shotApi, type Capture } from '$lib/shot/api';
import ShotViewport from '$lib/shot/components/ShotViewport.svelte';
import ScenePanel from '$lib/shot/components/ScenePanel.svelte';
import ShotInspector from '$lib/shot/components/ShotInspector.svelte';
import CaptureStrip from '$lib/shot/components/CaptureStrip.svelte';
import ShotSessionRail from '$lib/shot/components/ShotSessionRail.svelte';
import TimelineStrip from '$lib/shot/components/TimelineStrip.svelte';
const client = useQueryClient();
// ---- multi-session: one composition per session, rail-switchable -------
// The rail lists sandbox sessions that own a composition ("Scene · *").
// Selection persists in localStorage; deleting a session removes its
// composition first (the FK alone would orphan it).
const ACTIVE_SESSION_KEY = 'calliope.shot.activeSession';
const RAIL_KEY = 'calliope.shot.railCollapsed';
const CHAT_KEY = 'calliope.shot.chatCollapsed';
let sessionId = $state<number | null>(null);
let captures = $state<Capture[]>([]);
let compositionReady = $state(false);
let switching = $state(false);
// SSR-safe: this component initializes during server render too, where
// localStorage does not exist (a bare access 500s a direct page load).
let railCollapsed = $state(false);
let chatCollapsed = $state(false);
$effect(() => {
railCollapsed = localStorage.getItem(RAIL_KEY) === '1';
chatCollapsed = localStorage.getItem(CHAT_KEY) === '1';
});
function toggleRail() {
railCollapsed = !railCollapsed;
localStorage.setItem(RAIL_KEY, railCollapsed ? '1' : '0');
}
function toggleChat() {
chatCollapsed = !chatCollapsed;
localStorage.setItem(CHAT_KEY, chatCollapsed ? '1' : '0');
}
function isSceneSession(s: AgentSession): boolean {
return s.project_id == null && s.origin === 'scene';
}
async function refreshCaptures() {
if (shotStore.compositionId == null) return;
captures = await shotApi.listCaptures(shotStore.compositionId);
}
async function activateSession(id: number, { persist = true } = {}) {
if (switching) return;
switching = true;
try {
if (shotStore.compositionId != null) await shotStore.flushSave();
sessionId = id;
compositionReady = false;
if (persist) localStorage.setItem(ACTIVE_SESSION_KEY, String(id));
const comp = await shotStore.loadComposition(id);
if (comp && comp.title === 'Untitled composition') {
const title = `Scene · ${id}`;
await agentApi.patchSession(id, { title });
await fetch(`/api/shots/${comp.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
});
}
await refreshCaptures();
compositionReady = true;
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not open the composition');
compositionReady = true;
} finally {
switching = false;
}
}
$effect(() => {
if (compositionReady) return;
void (async () => {
try {
// origin=scene: this page's own rail entries. The default list
// (AI Canvas) excludes them, so the two surfaces never leak
// into each other.
const sessions = await agentApi.listSceneSessions();
const stored = Number(localStorage.getItem(ACTIVE_SESSION_KEY) ?? '');
const sceneSessions = sessions.filter(isSceneSession);
const initial =
sceneSessions.find((s) => s.id === stored) ??
sceneSessions[0] ??
null;
if (initial) {
await activateSession(initial.id, { persist: false });
} else {
const session = await agentApi.createSession({ origin: 'scene' });
await activateSession(session.id);
}
compositionReady = true;
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not open the composition');
compositionReady = true;
}
})();
});
async function handleNewScene() {
if (switching) return;
try {
const session = await agentApi.createSession({ origin: 'scene' });
await activateSession(session.id);
await client.invalidateQueries({ queryKey: ['agent-sessions', 'scene'] });
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not create a new scene');
}
}
async function handleDeleteScene(id: number) {
if (switching) return;
try {
// Delete the composition FIRST — agent_sessions FK would otherwise
// orphan it (ON DELETE SET NULL) and its captures would linger.
const comps = await shotApi.listCompositions();
const mine = comps.find((c) => c.agent_session_id === id);
if (mine) await shotApi.deleteComposition(mine.id);
await agentApi.deleteSession(id);
if (Number(localStorage.getItem(ACTIVE_SESSION_KEY)) === id) {
localStorage.removeItem(ACTIVE_SESSION_KEY);
}
const sessions = await agentApi.listSceneSessions();
const next = sessions.find(isSceneSession);
await client.invalidateQueries({ queryKey: ['agent-sessions', 'scene'] });
if (next && next.id !== sessionId) {
await activateSession(next.id);
} else if (!next) {
await handleNewScene();
}
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not delete the scene');
}
}
// ---- capture flow (UI button AND agent request_capture) ----------------
let viewportRef: ReturnType<typeof ShotViewport> | null = $state(null);
async function handleCaptureDataUrl(dataUrl: string) {
if (shotStore.compositionId == null) return;
const saved = await shotApi.uploadCapture(shotStore.compositionId, dataUrl, 'viewport capture');
if (saved) {
await refreshCaptures();
toast.success('Capture saved');
}
}
async function captureFromUi() {
// The viewport exports its own canvas render.
const comp = shotStore.compositionId;
if (comp == null || !viewportRef) return;
const dataUrl = (viewportRef as unknown as { captureNow: () => string }).captureNow();
await handleCaptureDataUrl(dataUrl);
}
let exportingVideo = $state(false);
async function handleExportVideo() {
const comp = shotStore.compositionId;
if (comp == null || !viewportRef || exportingVideo) return;
exportingVideo = true;
try {
const { dataUrl } = await (viewportRef as unknown as {
exportVideoClip: () => Promise<{ dataUrl: string; ext: string }>;
}).exportVideoClip();
const saved = await shotApi.uploadCapture(comp, dataUrl, 'camera track export');
if (saved) {
await refreshCaptures();
toast.success('Video exported');
} else {
toast.error('Upload failed — the clip may exceed the size limit');
}
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Video export failed');
} finally {
exportingVideo = false;
}
}
// ---- chat (mirrors canvas page's SSE wiring, minus session rail) -------
let streaming = $state('');
let streamingReasoning = $state('');
// Tracks which agent produced the last reasoning delta so the name prefix
// is written once per transition, not per token.
let thinkingAgent: string | null = null;
let liveTools = $state<
{ tool: string; args?: Record<string, unknown> | null; result?: unknown; phase: 'running' | 'done' | 'error' }[]
>([]);
let livePlan = $state<AgentPlan | null>(null);
let composerDraft = $state('');
let composerNonce = $state(0);
const sessionQuery = createQuery(
toStore(() => ({
queryKey: ['agent-session', sessionId],
queryFn: () => agentApi.getSession(sessionId!),
enabled: sessionId != null,
})),
);
const messages = $derived($sessionQuery.data?.messages ?? []);
const sessionsQuery = createQuery({
queryKey: ['agent-sessions', 'scene'],
queryFn: agentApi.listSceneSessions,
});
const sessions = $derived($sessionsQuery.data ?? []);
const activeSession = $derived(sessionId != null ? (sessions.find((s) => s.id === sessionId) ?? null) : null);
const running = $derived(Boolean(activeSession?.running || activeSession?.status === 'running'));
const skillsQuery = createQuery({
queryKey: ['agent-skills'],
queryFn: agentApi.listSkills,
});
const skillOptions = $derived<SkillOption[]>($skillsQuery.data ?? []);
// @workflow picker works here too: a tagged run_workflow from the builder
// chat follows the same render-approval rules as canvas.
const workflowsQuery = createQuery({
queryKey: ['workflows'],
queryFn: workflows.list,
});
const composerWorkflows = $derived<WorkflowOption[]>(
($workflowsQuery.data ?? [])
.filter((w) => w.is_enabled)
.map((w) => ({
id: w.id,
name: w.name,
kind: w.kind,
description: w.description,
is_enabled: w.is_enabled,
})),
);
const SHOT_SUGGESTIONS = [
{ label: 'Two-person scene', prompt: 'Add a male and a female character facing each other, then frame a medium two-shot from the left.' },
{ label: 'Posed hero', prompt: 'Add a character in a hero pose — arms wide — with a low-angle close-up.' },
{ label: 'Blockout a room', prompt: 'Blockout a simple room: floor plane, two walls, and put a character inside.' },
{ label: 'Capture a reference', prompt: 'Frame this as a medium close-up and capture a reference image.' },
];
const sendMutation = createMutation({
mutationFn: (payload: AgentComposerPayload) => agentApi.postMessage(sessionId!, payload),
onMutate: () => {
streaming = '';
streamingReasoning = '';
thinkingAgent = null;
liveTools = [];
livePlan = null;
},
onSuccess: async () => {
await client.invalidateQueries({ queryKey: ['agent-session', sessionId] });
await client.invalidateQueries({ queryKey: ['agent-sessions', 'scene'] });
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : 'Failed to send');
},
});
async function handleSend(payload: AgentComposerPayload) {
if (sessionId == null) {
toast.error('Still loading — try again in a second');
return;
}
$sendMutation.mutate(payload);
}
function handleQuestionAnswer(option: string, _scope: string, questionSeq: number) {
if (running || sessionId == null) return;
handleSend({ content: option, mentions: [], attachments: [], answer_to: questionSeq });
}
async function cancelRun() {
if (sessionId == null) return;
try {
await agentApi.cancel(sessionId);
await client.invalidateQueries({ queryKey: ['agent-sessions', 'scene'] });
await client.invalidateQueries({ queryKey: ['agent-session', sessionId] });
toast.info('Run cancelled');
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Cancel failed');
}
}
function upsertSession(s: AgentSession) {
client.setQueryData<AgentSession[]>(['agent-sessions', 'scene'], (old) => {
const list = Array.isArray(old) ? old : [];
return list.some((x) => x.id === s.id)
? list.map((x) => (x.id === s.id ? { ...x, ...s } : x))
: [...list, s];
});
}
function appendMessage(sid: number, msg: AgentMessage) {
if (sid !== sessionId) return;
client.setQueryData<AgentSession & { messages: AgentMessage[] }>(['agent-session', sid], (old) => {
if (!old || !Array.isArray(old.messages)) return old;
if (old.messages.some((m) => m.id === msg.id)) return old;
return { ...old, messages: [...old.messages, msg] };
});
}
// ---- agent tool live view: pose tools mutate server-side; SSE updates --
// The agent's shot tools append events + publish shot.updated; the store
// applies remote versions unless a drag is in progress (defer-during-drag,
// same rule as the canvas graph sync).
const POSE_TOOLS = new Set([
'get_scene',
'add_object',
'delete_object',
'rename_object',
'set_transform',
'reset_transform',
'select_object',
'clear_scene',
'set_joint',
'set_posture',
'list_poses',
'apply_pose',
'reset_pose',
'set_shot',
'list_shot_presets',
]);
onMount(() => {
const stop = connectEvents((ev) => {
if (ev.type === 'events.resync') {
client.invalidateQueries({ queryKey: ['agent-sessions', 'scene'] });
if (sessionId != null) client.invalidateQueries({ queryKey: ['agent-session', sessionId] });
void refreshCaptures();
return;
}
switch (ev.type) {
case 'shot.updated':
shotStore.handleShotUpdated(ev.data as { shot_id?: number });
// A pending agent capture request rides the same event: the
// viewport checks capture_request_json, renders the PNG, and
// posts it (the router clears the request, which is the
// request_capture tool's completion signal).
if (shotStore.dragInProgress == false) {
(viewportRef as unknown as { pollCaptureRequest?: () => void } | null)?.pollCaptureRequest?.();
}
break;
case 'shot.capture.saved':
void refreshCaptures();
break;
case 'agent.session.updated': {
const s = ev.data?.session as AgentSession | undefined;
if (s) upsertSession(s);
break;
}
case 'agent.message': {
const msg = ev.data?.message as AgentMessage | undefined;
if (msg) {
appendMessage(msg.session_id, msg);
if (msg.session_id === sessionId) {
if (msg.role === 'tool') liveTools = [];
if (msg.role === 'assistant' && !msg.agent_name) {
streaming = '';
streamingReasoning = '';
thinkingAgent = null;
}
}
}
client.invalidateQueries({ queryKey: ['agent-sessions', 'scene'] });
break;
}
case 'agent.token':
if (ev.data?.session_id === sessionId && !ev.data?.agent_name) {
streaming += String(ev.data?.content ?? '');
}
break;
case 'agent.thinking':
// Reasoning is auxiliary: stream it from ANY agent (incl.
// sub-agents) — the old `!agent_name` filter left
// delegated turns as a bare "working..." card. Prefix only
// on agent change; deltas arrive per token.
if (ev.data?.session_id === sessionId) {
const aname = (ev.data?.agent_name as string | undefined) ?? null;
if (aname !== thinkingAgent) {
streamingReasoning += aname ? `${aname}: ` : '';
thinkingAgent = aname;
}
streamingReasoning += String(ev.data?.content ?? '');
}
break;
case 'agent.tool': {
if (ev.data?.session_id !== sessionId) return;
const name = String(ev.data?.tool ?? '');
const phase = String(ev.data?.phase ?? '');
if (phase === 'start') {
liveTools.push({
tool: name,
args: (ev.data?.args as Record<string, unknown>) ?? null,
phase: 'running',
});
} else if (phase === 'finish') {
const idx = [...liveTools].reverse().findIndex((t) => t.tool === name && t.phase === 'running');
if (idx >= 0) {
const real = liveTools.length - 1 - idx;
liveTools[real] = {
...liveTools[real],
result: ev.data?.result,
phase: (ev.data?.result as { ok?: boolean } | undefined)?.ok === false ? 'error' : 'done',
};
}
}
// A shot tool finished server-side: refetch promptly so the
// viewport follows even before shot.updated SSE lands.
if (POSE_TOOLS.has(name) && phase === 'finish') {
shotStore.handleShotUpdated({ shot_id: shotStore.compositionId ?? undefined, reason: 'tool' });
}
break;
}
case 'agent.plan': {
if (ev.data?.session_id !== sessionId) return;
const tasks = (ev.data?.tasks as AgentTask[] | undefined) ?? [];
livePlan = {
tasks: tasks.map((t) => ({ ...t, status: t.status ?? 'pending' })),
note: (ev.data?.note as string | null) ?? null,
};
break;
}
case 'agent.task': {
if (ev.data?.session_id !== sessionId) return;
const index = ev.data?.index;
const status = ev.data?.status as AgentTask['status'] | undefined;
if (typeof index === 'number' && status) {
livePlan = livePlan
? {
...livePlan,
tasks: livePlan.tasks.map((t, i) => (i === index ? { ...t, status } : t)),
}
: livePlan;
}
break;
}
}
});
return stop;
});
</script>
<div class="shell">
<AppHeader active="build-scene" />
<div class="workspace">
<ShotSessionRail
{sessions}
activeId={sessionId}
onSelect={(id) => activateSession(id)}
onNew={handleNewScene}
onDelete={handleDeleteScene}
collapsed={railCollapsed}
onToggleCollapse={toggleRail}
/>
<aside class="left-panel">
<ScenePanel />
<div class="inspector-slot">
<ShotInspector oncapture={captureFromUi} />
</div>
</aside>
<main class="center-panel">
{#if compositionReady}
<div class="viewport-wrap">
<ShotViewport bind:this={viewportRef} oncapture={handleCaptureDataUrl} />
</div>
<TimelineStrip onExportVideo={handleExportVideo} />
<CaptureStrip {captures} compositionId={shotStore.compositionId} />
{:else}
<div class="loading">Preparing composition…</div>
{/if}
</main>
<aside class="chat-panel" class:collapsed={chatCollapsed}>
<header class="chat-head">
{#if chatCollapsed}
<span class="chat-title-vert">Build Scene</span>
{:else}
<span class="chat-title">{activeSession?.title ?? 'Build Scene'}</span>
<span class="badge">3D Builder</span>
{/if}
<button
class="chat-toggle"
onclick={toggleChat}
title={chatCollapsed ? 'Expand the agent chat' : 'Collapse the agent chat'}
aria-expanded={!chatCollapsed}
>
{chatCollapsed ? '‹' : '›'}
</button>
</header>
{#if !chatCollapsed}
<AgentChat
{messages}
{liveTools}
{streaming}
{streamingReasoning}
jobs={[]}
{running}
loading={sessionId != null && $sessionQuery.isLoading}
suggestions={SHOT_SUGGESTIONS}
onSuggestion={(text) => {
composerDraft = text;
composerNonce++;
}}
onAnswer={handleQuestionAnswer}
/>
<AgentComposer
{running}
draft={composerDraft}
draftNonce={composerNonce}
workflows={composerWorkflows}
skills={skillOptions}
onSend={handleSend}
onCancel={cancelRun}
/>
{/if}
</aside>
</div>
</div>
<style>
.shell {
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.workspace {
flex: 1;
display: flex;
min-height: 0;
}
.left-panel {
width: 280px;
flex-shrink: 0;
border-right: 1px solid var(--border, #232733);
display: flex;
flex-direction: column;
min-height: 0;
}
.inspector-slot {
flex: 1;
min-height: 0;
border-top: 1px solid var(--border, #232733);
overflow: hidden;
}
.center-panel {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
min-height: 0;
}
/* Owns ONLY the viewport; the timeline and capture strip are separate
flex rows below so neither can overflow onto the other. */
.viewport-wrap {
flex: 1;
min-height: 0;
position: relative;
}
.loading {
flex: 1;
display: grid;
place-items: center;
opacity: 0.5;
font-size: 13px;
}
.chat-panel {
width: 360px;
flex-shrink: 0;
border-left: 1px solid var(--border, #232733);
display: flex;
flex-direction: column;
min-height: 0;
transition: width 0.18s ease;
}
.chat-panel.collapsed {
width: 40px;
}
.chat-panel.collapsed .chat-head {
flex-direction: column;
align-items: center;
padding: 10px 4px;
gap: 8px;
border-bottom: none;
}
.chat-title-vert {
writing-mode: vertical-rl;
font-size: 12px;
font-weight: 600;
opacity: 0.75;
letter-spacing: 0.04em;
}
.chat-toggle {
border: 1px solid var(--border, #2a2f3a);
background: transparent;
color: inherit;
border-radius: 6px;
width: 22px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
font-size: 13px;
flex-shrink: 0;
}
.chat-toggle:hover {
background: rgba(255, 255, 255, 0.08);
}
.chat-head {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 14px;
border-bottom: 1px solid var(--border, #232733);
}
.chat-head .chat-toggle {
margin-left: auto;
}
.chat-panel.collapsed .chat-head .chat-toggle {
margin-left: 0;
}
.chat-title {
font-size: 13px;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.badge {
margin-left: auto;
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.06em;
border: 1px solid var(--border, #2a2f3a);
border-radius: 999px;
padding: 2px 8px;
opacity: 0.7;
}
</style>
@@ -106,10 +106,18 @@
}
if (node.entity_type === 'scene') {
const s = scenes.find((x) => x.id === node.entity_id);
// Project > Videos pattern: env image poster, clip fallback; only
// real video files count (guard mirrors QueueStage.previewPath).
const clip =
s?.video_path && /\.(mp4|webm)$/i.test(s.video_path) ? s.video_path : null;
// Project > Videos pattern: env image poster, first ready clip
// fallback; only real video files count (guard mirrors
// QueueStage.previewPath). A scene's clips are the renderables —
// the card plays the scene's first ready clip.
const firstReady = (s?.clips ?? []).find(
(c) => c.clip_path && /\.(mp4|webm)$/i.test(c.clip_path),
);
const clip = firstReady?.clip_path
? firstReady.clip_path
: s?.video_path && /\.(mp4|webm)$/i.test(s.video_path)
? s.video_path
: null;
return { imagePath: s?.env_image_path ?? null, videoPath: clip };
}
return { imagePath: null, videoPath: null };
@@ -352,6 +360,9 @@
let activeId = $state<number | null>(null);
let streaming = $state('');
let streamingReasoning = $state('');
// Tracks which agent produced the last reasoning delta so the name prefix
// is written once per transition, not per token.
let thinkingAgent: string | null = null;
let liveTools = $state<
{ tool: string; args?: Record<string, unknown> | null; result?: unknown; phase: 'running' | 'done' | 'error' }[]
>([]);
@@ -486,6 +497,7 @@
function resetLiveViews() {
streaming = '';
streamingReasoning = '';
thinkingAgent = null;
liveTools = [];
livePlan = null;
composerDraft = '';
@@ -570,6 +582,7 @@
onMutate: () => {
streaming = '';
streamingReasoning = '';
thinkingAgent = null;
liveTools = [];
livePlan = null;
if (activeId != null) {
@@ -674,6 +687,7 @@
if (msg.role === 'assistant' && !msg.agent_name) {
streaming = '';
streamingReasoning = '';
thinkingAgent = null;
}
}
}
@@ -683,7 +697,16 @@
streaming += String(ev.data?.content ?? '');
}
} else if (ev.type === 'agent.thinking') {
if (ev.data?.session_id === activeId && !ev.data?.agent_name) {
// Reasoning is auxiliary: stream it from ANY agent (incl.
// sub-agents) — the old `!agent_name` filter left delegated
// turns as a bare "working..." card. Prefix only on agent
// change; deltas arrive per token.
if (ev.data?.session_id === activeId) {
const name = (ev.data?.agent_name as string | undefined) ?? null;
if (name !== thinkingAgent) {
streamingReasoning += `${name ? `${name}: ` : ''}`;
thinkingAgent = name;
}
streamingReasoning += String(ev.data?.content ?? '');
}
} else if (ev.type === 'agent.tool') {