Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Add character sheet view toggles

Bittiaf61bce8fdc0
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 452fc5f..34c68b6 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -11,7 +11,7 @@ This alpha update adds LAN generation workers, Linux support, expanded color gra
- Renamed Colour correction to Basic Corrections and added temperature, tint, brightness, highlights, shadows, whites and blacks alongside exposure, contrast and saturation.
- Added Creative with eight built-in procedural looks and intensity, faded film, sharpen and vibrance controls; RGB and hue/saturation/luma curve editors; and shadow, midtone and highlight Color Wheels with individual lightness controls.
- Vignette now includes midpoint, roundness and feather, plus negative amounts for lighter edges. Grading settings are saved with the project and applied consistently in preview and export.
-- Configure a character sheet from the Image toolbar's Template menu, with one reference-enabled prompt for clothing and other details, a resolution selection controlling sheet height (512–2048 px), and step count and seed controls, then select Execute. A square waist-up shot and three 9:16 full-body views are combined into one child image in the image bar. The front view provides a shared clothing reference for the other views; all four views share the selected step count and seed.
+- Configure a character sheet from the Image toolbar's Template menu, with one reference-enabled prompt for clothing and other details, a resolution selection controlling sheet height (512–2048 px), and step count and seed controls, then select Execute. Selected close-up and 9:16 full-body views are combined into one child image in the image bar. When enabled, the front view provides a shared clothing reference for the other views; all selected views share the step count and seed.
- Continue scenes from a selected scene's saved latents, with adjustable overlap and a choice of beginning or end. This replaces Previous scene in First & last frame.
- Share URL-based generator templates using Import and Export in Generator settings. Versioned `.slop` JSON bundles include GPU download variants, LoRAs and additional safetensors, preserve existing templates on import, and leave local paths out of shared files.
- The agent can inspect, create and edit generator templates, scan local weight folders to identify model components from filenames and safetensors metadata, and register LoRAs for preparation in Settings.
@@ -32,6 +32,7 @@ This alpha update adds LAN generation workers, Linux support, expanded color gra
## Fixes and improvements
+- Character Sheet lets you enable Close up, Front view, Side view and Back view independently. Side view is off by default; generation and the combined image include only enabled views.
- Real-ESRGAN and SeedVR2 weights support local file paths in Other weights settings. SeedVR2 sends selected local files to the worker and downloads any missing components there.
- Scene continuation offers a Lock Overlap toggle for local and worker generation, constraining overlapping video and audio to the source scene.
- Image and video exports share a work queue with progress, cancellation, and retained results. SeedVR2 upscaling runs on the selected CUDA worker, which prepares its own models.
@@ -40,7 +41,7 @@ This alpha update adds LAN generation workers, Linux support, expanded color gra
- Image and video export offer None, Real-ESRGAN and SeedVR2 upscaling through SlopFab. Download their models from the new Other weights section in Settings → Generator.
- Image export offers sizes closest to the selected image's actual aspect ratio, even when project or saved generation settings differ.
- Click a work queue job to open its image, scene, reference, generator download or export. Navigation works across projects and preserves unsaved project edits.
-- Character Sheet offers Debug prompt when debug options are enabled, exposing the separate compiled prompt for each of its four views.
+- Character Sheet offers Debug prompt when debug options are enabled, exposing the separate compiled prompt for each enabled view.
- Updated the bundled SlopFab runtime to API 1.18 for refmod export and support for version-5 refmod bundles.
- LAN workers select weight downloads using their own GPU type and VRAM, even when a different variant is already downloaded on the client.
- Continue preserves the full joined video and audio from Slopfab. Adjacent source and continuation scenes use that shared decode in preview and export, preserving context across the cut. Regenerate older Continue scenes to apply the fix.
diff --git a/src-tauri/src/commands/character_sheet.rs b/src-tauri/src/commands/character_sheet.rs
index 04b93b1..a53fc31 100644
--- a/src-tauri/src/commands/character_sheet.rs
+++ b/src-tauri/src/commands/character_sheet.rs
@@ -58,24 +58,30 @@ fn write_view(
crate::storage::atomic::write_atomically(&directory.join(format!("{index}.png")), &png)
}
-/// Assemble a square portrait and three tall views without stretching or cropping.
+/// Assemble the selected views without stretching, cropping or empty columns.
#[tauri::command]
pub(crate) fn combine_character_sheet(
folder_path: String,
sheet_id: String,
+ indices: Option<Vec<usize>>,
) -> Result<super::artifacts::GeneratedImageFile, String> {
+ let indices = indices.unwrap_or_else(|| vec![0, 1, 2, 3]);
+ if indices.is_empty() || indices.len() > 4 || indices.iter().any(|&index| index >= 4)
+ || indices.windows(2).any(|pair| pair[0] >= pair[1]) {
+ return Err("Choose character sheet views in display order without duplicates.".into());
+ }
let root = ProjectRoot::open(&folder_path)?;
let directory = cache_directory(&sheet_id)?;
let mut views = Vec::new();
let mut total_width = 0;
let mut common_height = 0;
- for index in 0..4 {
+ for index in indices {
let path = root.existing(&format!("{directory}/{index}.png"))?;
let (width, height) = image::image_dimensions(&path).map_err(|error| error.to_string())?;
if width == 0 || width > 2048 || height == 0 || height > 8192 {
return Err("Invalid character sheet view dimensions.".into());
}
- if index > 0 && common_height != height {
+ if !views.is_empty() && common_height != height {
return Err("Character sheet views must have matching heights.".into());
}
common_height = height;
@@ -148,7 +154,7 @@ mod tests {
.unwrap();
}
write_view(&path, "other-sheet", 0, 2, 3, &colors[0].repeat(6)).unwrap();
- let saved = combine_character_sheet(path.clone(), "sheet-test".into()).unwrap();
+ let saved = combine_character_sheet(path.clone(), "sheet-test".into(), None).unwrap();
assert_eq!((saved.width, saved.height), (43, 16));
let image = image::open(folder.path().join(&saved.relative_path))
.unwrap()
@@ -173,6 +179,31 @@ mod tests {
assert!(discard_character_sheet_views(path, "../other-sheet".into()).is_err());
}
+ #[test]
+ fn character_sheet_combines_only_selected_views_without_empty_columns() {
+ for indices in [vec![0], vec![1], vec![2], vec![3], vec![0, 1, 3], vec![2, 3]] {
+ let folder = project_folder();
+ let path = folder.path().to_string_lossy().into_owned();
+ let mut width = 0;
+ for &index in &indices {
+ let view_width = if index == 0 { 16 } else { 9 };
+ write_view(&path, "selected", index, view_width, 16, &[index as u8, 0, 0, 255].repeat(view_width as usize * 16)).unwrap();
+ width += view_width;
+ }
+ let saved = combine_character_sheet(path, "selected".into(), Some(indices.clone())).unwrap();
+ assert_eq!((u32::from(saved.width), saved.height), (width, 16));
+ let image = image::open(folder.path().join(saved.relative_path)).unwrap().to_rgba8();
+ let mut x = 0;
+ for index in indices {
+ assert_eq!(image.get_pixel(x, 0).0, [index as u8, 0, 0, 255]);
+ x += if index == 0 { 16 } else { 9 };
+ }
+ }
+ for indices in [vec![], vec![4], vec![1, 1], vec![3, 0]] {
+ assert!(combine_character_sheet(String::new(), "invalid".into(), Some(indices)).is_err());
+ }
+ }
+
#[test]
fn character_sheet_rejects_missing_mismatched_and_oversized_views() {
let folder = project_folder();
@@ -180,11 +211,11 @@ mod tests {
assert!(write_view(&path, "sheet", 4, 1, 1, &[0; 4]).is_err());
assert!(write_view(&path, "sheet", 0, 2049, 1, &[0; 4]).is_err());
write_view(&path, "sheet", 0, 1, 1, &[0; 4]).unwrap();
- assert!(combine_character_sheet(path.clone(), "sheet".into()).is_err());
+ assert!(combine_character_sheet(path.clone(), "sheet".into(), None).is_err());
for index in 1..4 {
write_view(&path, "sheet", index, 2, 2, &[0; 16]).unwrap();
}
- assert!(combine_character_sheet(path, "sheet".into()).is_err());
+ assert!(combine_character_sheet(path, "sheet".into(), None).is_err());
assert!(!folder.path().join("media/generated/sheet.png").exists());
}
}
diff --git a/src-tauri/src/project/image.rs b/src-tauri/src/project/image.rs
index 4d19e2f..b884ba2 100644
--- a/src-tauri/src/project/image.rs
+++ b/src-tauri/src/project/image.rs
@@ -32,14 +32,26 @@ pub(crate) struct ImageTemplateSnapshot {
pub bounds: Option<ImageBox>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub height: Option<u32>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub views: Option<CharacterSheetViews>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub(crate) struct CharacterSheetViews {
+ pub close_up: bool,
+ pub front: bool,
+ pub side: bool,
+ pub back: bool,
}
impl ImageTemplateSnapshot {
pub(crate) fn validate(&self) -> Result<(), String> {
let valid_options = match self.kind.as_str() {
- "extend" => self.height.is_none() && self.bounds.as_ref().is_some_and(|b|
+ "extend" => self.views.is_none() && self.height.is_none() && self.bounds.as_ref().is_some_and(|b|
[b.x, b.y, b.width, b.height].iter().all(|v| v.is_finite()) && b.width > 0.0 && b.height > 0.0),
- "character-sheet" => self.bounds.is_none() && matches!(self.height, Some(512 | 1024 | 1536 | 2048)),
+ "character-sheet" => self.bounds.is_none() && matches!(self.height, Some(512 | 1024 | 1536 | 2048))
+ && self.views.as_ref().is_none_or(|views| views.close_up || views.front || views.side || views.back),
_ => false,
};
if !valid_options || self.source_id.is_empty() || self.source_name.is_empty() || self.generator_name.is_empty()
diff --git a/src-tauri/src/tests/images.rs b/src-tauri/src/tests/images.rs
index 1a92a75..8be0213 100644
--- a/src-tauri/src/tests/images.rs
+++ b/src-tauri/src/tests/images.rs
@@ -190,6 +190,7 @@ fn image_template_settings_survive_save_and_reopen() {
for template in [
serde_json::json!({"kind":"extend", "sourceId":"source", "sourceName":"Original", "generatorName":"Default generator", "prompt":"Continue the forest", "steps":28, "seed":-1, "bounds":{"x":-64,"y":-32,"width":768,"height":640}}),
serde_json::json!({"kind":"character-sheet", "sourceId":"source", "sourceName":"Original", "generatorName":"Default generator", "prompt":"Red coat", "steps":28, "seed":0, "height":1024}),
+ serde_json::json!({"kind":"character-sheet", "sourceId":"source", "sourceName":"Original", "generatorName":"Default generator", "prompt":"Red coat", "steps":28, "seed":0, "height":1024, "views":{"closeUp":false,"front":false,"side":true,"back":true}}),
] {
for pending in [true, false] {
let mut config = image_fixture();
diff --git a/src/components/ImageProject.integration.test.tsx b/src/components/ImageProject.integration.test.tsx
index 56a551e..f14e801 100644
--- a/src/components/ImageProject.integration.test.tsx
+++ b/src/components/ImageProject.integration.test.tsx
@@ -47,7 +47,15 @@ it("opens template settings and executes only after configuring prompts and clot
const panel = within(screen.getByRole("complementary", { name: "Character sheet settings" }));
const before = structuredClone(queue.project(project).getSnapshot().config);
choose("Character sheet resolution", "2048 px high");
+ expect(panel.getByRole("switch", { name: "Side view" })).not.toBeChecked();
+ for (const name of ["Close up", "Front view", "Back view"]) expect(panel.getByRole("switch", { name })).toBeChecked();
+ expect(panel.getByText(/Sheet size:/)).toHaveTextContent("4352 × 2048 px");
+ fireEvent.click(panel.getByRole("switch", { name: "Side view" }));
expect(panel.getByText(/Sheet size:/)).toHaveTextContent("5504 × 2048 px");
+ for (const name of ["Close up", "Front view", "Side view", "Back view"]) fireEvent.click(panel.getByRole("switch", { name }));
+ expect(panel.getByRole("button", { name: "Execute" })).toBeDisabled();
+ fireEvent.click(panel.getByRole("switch", { name: "Back view" }));
+ expect(panel.getByText(/Sheet size:/)).toHaveTextContent("1152 × 2048 px");
fireEvent.change(panel.getByRole("spinbutton", { name: "Steps" }), { target: { value: "" } });
expect(panel.getByRole("button", { name: "Execute" })).toBeDisabled();
fireEvent.change(panel.getByRole("spinbutton", { name: "Steps" }), { target: { value: "37" } });
@@ -61,7 +69,8 @@ it("opens template settings and executes only after configuring prompts and clot
expect(prompt.querySelector(".prompt-chip")).toHaveTextContent("Red coat");
expect(queue.project(project).getSnapshot().config).toEqual(before);
fireEvent.click(panel.getByRole("button", { name: "Execute" }));
- expect(generate).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ id: "test" }), "Selected", { prompt: "Soft studio lighting. Wear @[ref:outfit]", height: 2048, steps: 37, seed: 0 });
+ expect(generate).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ id: "test" }), "Selected", { prompt: "Soft studio lighting. Wear @[ref:outfit]", height: 2048, steps: 37, seed: 0,
+ views: { closeUp: false, front: false, side: false, back: true } });
fireEvent.click(panel.getByRole("button", { name: "Close template settings" }));
expect(screen.getByRole("complementary", { name: "Image node inspector" })).toBeInTheDocument();
fireEvent.click(toolbar.getByRole("button", { name: "Template" }));
diff --git a/src/components/workspace/CharacterSheetSettings.tsx b/src/components/workspace/CharacterSheetSettings.tsx
index b04b0aa..e66c4ec 100644
--- a/src/components/workspace/CharacterSheetSettings.tsx
+++ b/src/components/workspace/CharacterSheetSettings.tsx
@@ -1,7 +1,7 @@
import { useMemo, useState } from "react";
-import { CHARACTER_SHEET_HEIGHTS, CHARACTER_SHEET_ORDER, CHARACTER_SHEET_VIEWS, characterSheetDimensions, compileCharacterSheet, emptyCharacterSheetOptions, type CharacterSheetOptions } from "../../lib/characterSheet";
+import { CHARACTER_SHEET_HEIGHTS, CHARACTER_SHEET_ORDER, CHARACTER_SHEET_VIEWS, characterSheetDimensions, characterSheetViewIndices, characterSheetViews, compileCharacterSheet, emptyCharacterSheetOptions, type CharacterSheetOptions } from "../../lib/characterSheet";
import type { ProjectAsset, ProjectConfig } from "../../lib/project";
-import { ComboBox, InfoBar, ItemHeader, PropRow } from "../ui";
+import { ComboBox, InfoBar, ItemHeader, PropRow, ToggleSwitch } from "../ui";
import { Dismiss16, Sparkle16 } from "../ui/icons";
import { PromptTextField, type PromptReference } from "./PromptTextField";
import { TemplateDebugPrompt } from "./TemplateDebugPrompt";
@@ -13,8 +13,12 @@ export function CharacterSheetSettings({ config, source, references, missingLabe
onExecute: (options: CharacterSheetOptions) => void; onClose: () => void;
}) {
const [options, setOptions] = useState<CharacterSheetOptions>(() => ({ ...emptyCharacterSheetOptions(), height: characterSheetDimensions(config.settings.resolution)[0].height,
- steps: config.imageScene?.steps ?? defaultSteps, seed: config.imageScene?.seed ?? -1, ...initialOptions }));
+ steps: config.imageScene?.steps ?? defaultSteps, seed: config.imageScene?.seed ?? -1, ...initialOptions,
+ // Older submitted sheets always generated all four views.
+ ...(initialOptions && !initialOptions.views ? { views: { closeUp: true, front: true, side: true, back: true } } : {}) }));
const dimensions = characterSheetDimensions(config.settings.resolution, options.height);
+ const selectedViews = characterSheetViews(options);
+ const indices = characterSheetViewIndices(options);
const [error, setError] = useState<string | null>(null);
const compiled = useMemo(() => {
try { return { views: compileCharacterSheet(config, source, "cache/character-sheet-preview/1.png", options), error: null }; }
@@ -34,23 +38,27 @@ export function CharacterSheetSettings({ config, source, references, missingLabe
}}>
<div className="image-inspector__fields image-template-settings__fields">
<p className="image-inspector__caption">Source: {source.name}</p>
- <p className="image-inspector__caption">A square waist-up shot and three full-body views (front, side, back), combined into one image.</p>
+ <p className="image-inspector__caption">Combine selected views into one image: a square waist-up close up and full-body front, side, or back views.</p>
+ {CHARACTER_SHEET_VIEWS.map((view) => <PropRow key={view.id} label={view.label} htmlFor={`character-sheet-${view.id}`}>
+ <ToggleSwitch id={`character-sheet-${view.id}`} aria-label={view.label} checked={selectedViews[view.id]} disabled={busy}
+ onChange={(checked) => update("views", { ...selectedViews, [view.id]: checked })} />
+ </PropRow>)}
<PropRow label="Resolution" htmlFor="character-sheet-resolution"><ComboBox id="character-sheet-resolution" aria-label="Character sheet resolution" value={options.height} disabled={busy}
options={CHARACTER_SHEET_HEIGHTS.map((height) => ({ value: height, label: `${height} px high` }))} onChange={(height) => update("height", height)} /></PropRow>
- <p className="image-inspector__caption">Sheet size: {dimensions.reduce((width, view) => width + view.width, 0)} × {dimensions[0].height} px. Width follows the four view proportions.</p>
+ <p className="image-inspector__caption">Sheet size: {indices.reduce((width, index) => width + dimensions[index].width, 0)} × {dimensions[0].height} px. Width follows the selected view proportions.</p>
<PropRow label="Steps" htmlFor="character-sheet-steps"><input id="character-sheet-steps" className="text-field" type="number" min="2" max="1000" step="1" required disabled={busy}
value={Number.isNaN(options.steps) ? "" : options.steps} onChange={(event) => update("steps", event.target.valueAsNumber)} /></PropRow>
<PropRow label="Seed" htmlFor="character-sheet-seed"><input id="character-sheet-seed" className="text-field" type="number" min="-1" max={Number.MAX_SAFE_INTEGER} step="1" required disabled={busy}
value={Number.isNaN(options.seed) ? "" : options.seed} onChange={(event) => update("seed", event.target.valueAsNumber)} /></PropRow>
- <p className="image-inspector__caption">Use -1 for a random seed. All four views use the same seed and step count.</p>
+ <p className="image-inspector__caption">Use -1 for a random seed. All selected views use the same seed and step count.</p>
<div className="image-inspector__area"><span>Prompt</span>
<PromptTextField aria-label="Character sheet prompt" value={options.prompt} onChange={(value) => update("prompt", value)} references={references} missingLabel={missingLabel} disabled={busy} placeholder="Describe the character, clothing, accessories, style, or lighting…" />
</div>
- <p className="image-inspector__caption">Use the prompt and references for clothing and other details. Leave it blank to keep the source appearance. Clothing instructions apply to the front view, then the same outfit is used for every angle.</p>
+ <p className="image-inspector__caption">Use the prompt and references for clothing and other details. Leave it blank to keep the source appearance. When enabled, the front view provides the outfit reference for other views; otherwise each view uses the source image.</p>
{(validation || error) && <InfoBar severity="error" title="Couldn't prepare the template" message={validation ?? error ?? ""} />}
</div>
<div className="image-template-settings__footer">
- <TemplateDebugPrompt name="Character sheet" prompts={compiled.views ? CHARACTER_SHEET_ORDER.map((index) => ({ label: CHARACTER_SHEET_VIEWS[index].label, prompt: compiled.views![index].prompt })) : []} />
+ <TemplateDebugPrompt name="Character sheet" prompts={compiled.views ? CHARACTER_SHEET_ORDER.filter((index) => indices.includes(index)).map((index) => ({ label: CHARACTER_SHEET_VIEWS[index].label, prompt: compiled.views![index].prompt })) : []} />
{disabledReason && <p className="image-inspector__caption">{disabledReason}</p>}
<button type="submit" className="primary-button" disabled={Boolean(disabledReason || validation || busy)}><Sparkle16 aria-hidden="true" />{busy ? "Executing…" : "Execute"}</button>
</div>
diff --git a/src/lib/characterSheet.test.ts b/src/lib/characterSheet.test.ts
index b54bf64..9929ac9 100644
--- a/src/lib/characterSheet.test.ts
+++ b/src/lib/characterSheet.test.ts
@@ -9,7 +9,7 @@ import { createProjectConfig, parseProjectConfig, type ProjectRecord } from "./p
import { cancelSlopfabGeneration, enqueueSlopfabGeneration, resolveSlopfabPlan } from "./runtime";
import { EMPTY_ENGINE_SETTINGS, type GeneratorTemplate } from "./settings";
import { WorkQueue } from "./workQueue";
-import { CHARACTER_SHEET_HEIGHTS, characterSheetDimensions, compileCharacterSheet } from "./characterSheet";
+import { CHARACTER_SHEET_HEIGHTS, CHARACTER_SHEET_VIEWS, characterSheetDimensions, compileCharacterSheet, type CharacterSheetViews } from "./characterSheet";
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));
@@ -18,7 +18,7 @@ vi.mock("./runtime", () => ({ cancelSlopfabGeneration: vi.fn(), enqueueSlopfabGe
const handlers = new Map<string, (event: { payload: unknown }) => void>();
let stop: (() => void) | undefined;
const template: GeneratorTemplate = { id: "h3", name: "H3", modelType: "minimax-h3", defaultSteps: 20, attention: "sage2", paths: { ...EMPTY_ENGINE_SETTINGS, transformer: "C:/h3.safetensors" } };
-const result = { relativePath: "media/generated/sheet.png", width: 2752, height: 1024 };
+const result = { relativePath: "media/generated/sheet.png", width: 2176, height: 1024 };
beforeEach(() => {
localStorage.clear(); vi.resetAllMocks(); handlers.clear();
Object.assign(window, { __TAURI_INTERNALS__: {} });
@@ -55,15 +55,16 @@ it.each([false, true])("uses a shared front-view outfit with square portrait and
const id = queue.getSnapshot()[0].id;
const pending = parseProjectConfig(JSON.parse(JSON.stringify(session.getSnapshot().config)));
expect(pending.assets).toHaveLength(2);
- expect(pending.assets[1]).toMatchObject({ id, imageDraft: true, parentAssetId: "source", width: 2752, height: 1024,
+ expect(pending.assets[1]).toMatchObject({ id, imageDraft: true, parentAssetId: "source", width: 2176, height: 1024,
imageGeneration: { template: { kind: "character-sheet", sourceId: "source", sourceName: "Hero", generatorName: template.name, prompt: "", height: 1024 } } });
expect(pending.assets[1].relativePath).toBeUndefined();
expect(pending.imageScene!.outputAssetId).toBe(id);
expect(queue.getSnapshot()[0].imageDraftId).toBe(id);
expect(saveImageDraft(restoreGeneratedImage(pending, id)).assets).toEqual(pending.assets);
let seed: number | undefined;
- const order = [1, 0, 2, 3];
- for (let index = 0; index < 4; index++) {
+ const order = [1, 0, 3];
+ expect(queue.getSnapshot()[0].settings.frames).toBe(3);
+ for (let index = 0; index < 3; index++) {
const request = await requestAt(index);
seed ??= request.seed;
const viewIndex = order[index];
@@ -88,12 +89,14 @@ it.each([false, true])("uses a shared front-view outfit with square portrait and
expect(session.getSnapshot().config.assets[1]).toMatchObject({ id, imageDraft: true });
if (changed && index === 0) session.update((current) => restoreGeneratedImage(current, "source"));
emit("framesReady", request.jobId);
- if (index < 3) {
+ if (index < 2) {
await waitFor(() => expect(releaseRendered).toHaveBeenCalledWith(request.jobId));
expect(invoke).toHaveBeenCalledWith("save_character_sheet_view", { folderPath: "C:/Character", sheetId: id, jobId: request.jobId, index: viewIndex });
}
}
await waitFor(() => expect(queue.getSnapshot()[0].status).toBe("completed"));
+ expect(invoke).toHaveBeenCalledWith("combine_character_sheet", { folderPath: "C:/Character", sheetId: id, indices: [0, 1, 3] });
+ expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(3);
const reopened = parseProjectConfig(JSON.parse(JSON.stringify(session.getSnapshot().config)));
expect(reopened.assets).toHaveLength(2);
expect(reopened.assets[0]).toEqual(original.assets[0]);
@@ -115,11 +118,42 @@ it.each(["416p", "768p", "1080p", "2048p", "4k"] as const)("keeps exact aspect r
for (const { width, height } of sizes) { expect(width % 32).toBe(0); expect(height % 32).toBe(0); }
});
+it.each([[0], [1], [2], [3], [0, 2, 3]].map((indices) => ({ indices })))("generates only selected views $indices without an implicit front view", async ({ indices }) => {
+ const { queue, session } = setup();
+ const views = Object.fromEntries(CHARACTER_SHEET_VIEWS.map((view, index) => [view.id, indices.includes(index)])) as CharacterSheetViews;
+ queue.enqueueCharacterSheet(session, template, "source", { prompt: "Wear a red coat", views });
+ const frozen = { ...views };
+ views.front = !views.front;
+ const id = queue.getSnapshot()[0].id;
+ const pending = parseProjectConfig(JSON.parse(JSON.stringify(session.getSnapshot().config)));
+ expect(pending.assets[1].imageGeneration!.template).toMatchObject({ views: frozen });
+ expect(pending.assets[1].width).toBe(indices.reduce((width, index) => width + (index === 0 ? 1024 : 576), 0));
+ for (let index = 0; index < indices.length; index++) {
+ const request = await requestAt(index);
+ expect(request.jobId).toBe(`${id}-view-${indices[index] + 1}`);
+ expect(request.referencePaths).toEqual(["C:/Character/media/hero.png"]);
+ expect(request.prompt).not.toContain("<Picture 2>");
+ expect(request.prompt).toContain("Wear a red coat");
+ handlers.get("slopfab-progress")?.({ payload: { jobId: request.jobId, step: 1, totalSteps: 2 } });
+ expect(queue.getSnapshot()[0].progress).toBeCloseTo((index + 0.5) / indices.length * 0.9);
+ emit("framesReady", request.jobId);
+ }
+ await waitFor(() => expect(queue.getSnapshot()[0].status).toBe("completed"));
+ expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(indices.length);
+ expect(invoke).toHaveBeenCalledWith("combine_character_sheet", { folderPath: "C:/Character", sheetId: id, indices });
+});
+
+it("rejects a sheet with every view disabled before queueing", () => {
+ const { queue, session } = setup();
+ expect(() => queue.enqueueCharacterSheet(session, template, "source", { prompt: "", views: { closeUp: false, front: false, side: false, back: false } })).toThrow("at least one");
+ expect(queue.getSnapshot()).toHaveLength(0);
+});
+
it.each(CHARACTER_SHEET_HEIGHTS)("generates all four views at the selected %s px height", async (height) => {
const { queue, session } = setup();
const saved = { ...result, width: height * 43 / 16, height };
vi.mocked(invoke).mockImplementation(async (command) => command === "combine_character_sheet" ? saved : undefined);
- const options = { prompt: "", height };
+ const options = { prompt: "", height, views: { closeUp: true, front: true, side: true, back: true } };
queue.enqueueCharacterSheet(session, template, "source", options);
expect(queue.getSnapshot()[0].settings.canvasHeight).toBe(height);
options.height = 512; // Queued dimensions must not follow later settings edits.
@@ -147,6 +181,7 @@ it("keeps the required view after template instructions without repeating orient
const snapshot = structuredClone(config);
const views = compileCharacterSheet(config, config.assets[0], "cache/front.png", {
prompt: "Wear a red coat with a chest badge, looking straight at the camera.",
+ views: { closeUp: true, front: true, side: true, back: true },
});
const back = views[3].prompt;
const retention = back.split("retention_analysis:\n")[1].split("\n\ndetailed_description:")[0];
@@ -169,7 +204,7 @@ it.each([0, 12345, -1])("uses template steps and seed %s for every view and save
expect(usedSeed).toBeGreaterThanOrEqual(0);
if (seed !== -1) expect(usedSeed).toBe(seed);
expect(queue.getSnapshot()[0].settings.steps).toBe(37);
- for (let index = 0; index < 4; index++) {
+ for (let index = 0; index < 3; index++) {
const request = await requestAt(index);
expect(request).toMatchObject({ steps: 37, seed: usedSeed });
expect(session.getSnapshot().config.imageScene).toMatchObject({ outputAssetId: queue.getSnapshot()[0].id, steps: 37, seed });
@@ -211,16 +246,16 @@ it("keeps the finished sheet available when project saving fails and retries wit
const { queue, session, writer } = setup();
queue.enqueueCharacterSheet(session, template, "source");
const id = queue.getSnapshot()[0].id;
- for (let index = 0; index < 4; index++) {
+ for (let index = 0; index < 3; index++) {
const request = await requestAt(index);
- if (index === 3) writer.mockRejectedValueOnce(new Error("Disk full"));
+ if (index === 2) writer.mockRejectedValueOnce(new Error("Disk full"));
emit("framesReady", request.jobId);
}
await waitFor(() => expect(queue.getSnapshot()[0]).toMatchObject({ status: "failed", needsSave: true }));
expect(session.getSnapshot().config.assets).toHaveLength(2);
await queue.retrySave(id);
expect(queue.getSnapshot()[0]).toMatchObject({ status: "completed", needsSave: false });
- expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(4);
+ expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(3);
});
it("rejects an empty source without queuing work", () => {
@@ -238,7 +273,7 @@ it("conditions every view on prompt references and freezes the requested outfit
queue.enqueueCharacterSheet(session, template, "source", options);
options.prompt = "Changed after execution";
const id = queue.getSnapshot()[0].id;
- for (let index = 0; index < 4; index++) {
+ for (let index = 0; index < 3; index++) {
const request = await requestAt(index);
expect(request.referencePaths).toEqual(["C:/Character/media/hero.png", ...(index > 0 ? [`C:/Character/cache/character-sheets/${id}/1.png`] : []), "C:/Character/references/coat.png"]);
expect(request.refmods).toEqual([{ path: "C:/Character/references/coat.safetensors", strength: 0.75, copies: 1 }]);
@@ -274,12 +309,12 @@ it("does not publish a partial result when combining fails and lets the next job
const id = queue.getSnapshot()[0].id;
session.update((current) => ({ ...current, assets: [...current.assets, { ...current.assets[0], id: "another", name: "Another" }] }));
queue.enqueueCharacterSheet(session, template, "another");
- for (let index = 0; index < 4; index++) emit("framesReady", (await requestAt(index)).jobId);
+ for (let index = 0; index < 3; index++) emit("framesReady", (await requestAt(index)).jobId);
await waitFor(() => expect(queue.getSnapshot()[0]).toMatchObject({ status: "failed", error: "Could not combine views" }));
expect(session.getSnapshot().config.assets.map((asset) => asset.id)).toEqual(["source", id, "another", queue.getSnapshot()[1].id]);
expect(session.getSnapshot().config.assets.filter((asset) => asset.imageDraft)).toHaveLength(2);
expect(invoke).toHaveBeenCalledWith("discard_character_sheet_views", { folderPath: "C:/Character", sheetId: id });
- const next = await requestAt(4);
+ const next = await requestAt(3);
await queue.cancel(queue.getSnapshot()[1].id);
emit("cancelled", next.jobId);
await waitFor(() => expect(queue.getSnapshot()[1].status).toBe("cancelled"));
diff --git a/src/lib/characterSheet.ts b/src/lib/characterSheet.ts
index eb22c71..7034e92 100644
--- a/src/lib/characterSheet.ts
+++ b/src/lib/characterSheet.ts
@@ -4,18 +4,21 @@ import { outputDimensions } from "./export";
import type { ProjectAsset, ProjectConfig, ProjectReference } from "./project";
export const CHARACTER_SHEET_VIEWS = [
- { label: "Upper body front", description: "Waist-up front view, facing the camera, entire head visible." },
- { label: "Full body front", description: "Full body front view, facing the camera, neutral standing pose, head to feet visible." },
- { label: "Full body side", description: "Full body side view, head and body in left-facing profile, neutral standing pose, head to feet visible." },
- { label: "Full body back", description: "Full body back view, head and body facing away, face hidden, neutral standing pose, head to feet visible." },
+ { id: "closeUp", label: "Close up", description: "Waist-up front view, facing the camera, entire head visible." },
+ { id: "front", label: "Front view", description: "Full body front view, facing the camera, neutral standing pose, head to feet visible." },
+ { id: "side", label: "Side view", description: "Full body side view, head and body in left-facing profile, neutral standing pose, head to feet visible." },
+ { id: "back", label: "Back view", description: "Full body back view, head and body facing away, face hidden, neutral standing pose, head to feet visible." },
] as const;
// Establish the complete outfit before asking for any other camera angle.
export const CHARACTER_SHEET_ORDER = [1, 0, 2, 3] as const;
export const CHARACTER_SHEET_HEIGHTS = [512, 1024, 1536, 2048] as const;
-export interface CharacterSheetOptions { prompt: string; height?: number; steps?: number; seed?: number }
-export const emptyCharacterSheetOptions = (): CharacterSheetOptions => ({ prompt: "" });
+export type CharacterSheetViews = Record<typeof CHARACTER_SHEET_VIEWS[number]["id"], boolean>;
+export interface CharacterSheetOptions { prompt: string; height?: number; steps?: number; seed?: number; views?: CharacterSheetViews }
+export const characterSheetViews = (options?: CharacterSheetOptions): CharacterSheetViews => ({ closeUp: true, front: true, side: false, back: true, ...options?.views });
+export const characterSheetViewIndices = (options?: CharacterSheetOptions) => CHARACTER_SHEET_VIEWS.flatMap((view, index) => characterSheetViews(options)[view.id] ? [index] : []);
+export const emptyCharacterSheetOptions = (): CharacterSheetOptions => ({ prompt: "", views: characterSheetViews() });
export function characterSheetDimensions(resolution: ProjectConfig["settings"]["resolution"], requestedHeight?: number) {
// A shared height divisible by 512 makes both 1:1 and 9:16 exact on H3's
@@ -26,6 +29,8 @@ export function characterSheetDimensions(resolution: ProjectConfig["settings"]["
}
export function compileCharacterSheet(config: ProjectConfig, source: ProjectAsset, frontRelativePath: string, options: CharacterSheetOptions = emptyCharacterSheetOptions()) {
+ const indices = characterSheetViewIndices(options);
+ if (!indices.length) throw new Error("Enable at least one character sheet view.");
if (options.steps !== undefined && (!Number.isInteger(options.steps) || options.steps < 2 || options.steps > 1000)) throw new Error("Steps must be a whole number from 2 to 1000.");
if (options.seed !== undefined && (!Number.isSafeInteger(options.seed) || options.seed < -1)) throw new Error("Seed must be -1 for random or a whole number from 0 to 9007199254740991.");
let sourceReferenceId = "character-sheet-source";
@@ -36,19 +41,21 @@ export function compileCharacterSheet(config: ProjectConfig, source: ProjectAsse
intendedUse: ["character"], createdAt: source.createdAt,
images: [{ id: "character-sheet-source-image", name: source.name, relativePath: source.relativePath, sourcePath: source.sourcePath }],
};
- return CHARACTER_SHEET_VIEWS.map((view, index) => {
- const wardrobe = index === 1
+ return Object.fromEntries(indices.map((index) => {
+ const view = CHARACTER_SHEET_VIEWS[index];
+ const useFront = index !== 1 && characterSheetViews(options).front;
+ const wardrobe = !useFront
? "Keep the outfit from <Picture 1> unless the template instructions change it; complete any unseen clothing."
: "Use <Picture 1> for identity and match the outfit in <Picture 2> from the requested angle.";
const selectedReference = { ...reference,
- images: index === 1 ? reference.images : [...reference.images!, { id: "character-sheet-front", name: "Full body front wardrobe reference", relativePath: frontRelativePath }],
+ images: !useFront ? reference.images : [...reference.images!, { id: "character-sheet-front", name: "Full body front wardrobe reference", relativePath: frontRelativePath }],
};
const instructions = options.prompt.trim() ? `Template instructions: ${options.prompt.trim()}` : "";
const scene = createImageScene(`One character reference view of @[ref:${reference.id}]. ${wardrobe} Plain light gray background, soft even lighting, no text.\n${instructions}\nRequired view: ${view.description}`);
scene.style = { mode: "art", medium: "the same visual medium and rendering style as <Picture 1>", aesthetics: "", lighting: "", detail: "" };
- return compileImagePrompt({
+ return [index, compileImagePrompt({
...config, settings: { ...config.settings, defaultLook: null }, references: [selectedReference, ...config.references],
imageScene: scene,
- }, { referenceTransformations: { [reference.id]: "Keep the character's identity; use the requested outfit and view." } });
- });
+ }, { referenceTransformations: { [reference.id]: "Keep the character's identity; use the requested outfit and view." } })] as const;
+ }));
}
diff --git a/src/lib/project.ts b/src/lib/project.ts
index 2ab6793..a6b15fc 100644
--- a/src/lib/project.ts
+++ b/src/lib/project.ts
@@ -146,7 +146,9 @@ const imageTemplateSnapshotSchema = z.discriminatedUnion("kind", [
z.object({ ...imageTemplateFields, kind: z.literal("extend"), bounds: z.object({
x: z.number().finite(), y: z.number().finite(), width: z.number().positive().finite(), height: z.number().positive().finite(),
}) }),
- z.object({ ...imageTemplateFields, kind: z.literal("character-sheet"), height: z.number().int().refine((height) => [512, 1024, 1536, 2048].includes(height), "Unsupported character sheet height.") }),
+ z.object({ ...imageTemplateFields, kind: z.literal("character-sheet"), height: z.number().int().refine((height) => [512, 1024, 1536, 2048].includes(height), "Unsupported character sheet height."),
+ views: z.object({ closeUp: z.boolean(), front: z.boolean(), side: z.boolean(), back: z.boolean() })
+ .refine((views) => Object.values(views).some(Boolean), "Enable at least one character sheet view.").optional() }),
]);
export const imageGenerationSnapshotSchema = z.object({
diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.ts
index 818c02d..ed630b7 100644
--- a/src/lib/workQueue.ts
+++ b/src/lib/workQueue.ts
@@ -4,7 +4,7 @@ import { createImageEditScene, createImageScene, imageScenePrompt } from "./imag
import { compileImageEdits, imageEditDebugPrompt } from "./imageEditing";
import { compileImagePrompt } from "./imagePrompt";
import { compileExtendImage, type ExtendOptions } from "./extendImage";
-import { CHARACTER_SHEET_ORDER, CHARACTER_SHEET_VIEWS, characterSheetDimensions, compileCharacterSheet, type CharacterSheetOptions } from "./characterSheet";
+import { CHARACTER_SHEET_ORDER, CHARACTER_SHEET_VIEWS, characterSheetDimensions, characterSheetViewIndices, characterSheetViews, compileCharacterSheet, type CharacterSheetOptions } from "./characterSheet";
import { completeImageDraft, createTemplateImageDraft, imageFamilyRoot, imageGenerationSnapshot, saveImageDraft } from "./imageHistory";
import type { ImageGenerationSnapshot } from "./project";
import { outputDimensions } from "./export";
@@ -62,6 +62,7 @@ interface PendingWork {
characterSheet?: {
views: ReturnType<typeof compileCharacterSheet>; sourceId: string; name: string; index: number;
dimensions: ReturnType<typeof characterSheetDimensions>;
+ order: number[];
ready?: { resolve: () => void; reject: (reason: Error) => void };
};
outputFrames?: number;
@@ -350,7 +351,9 @@ export class WorkQueue {
steps: generationStepsWithLoras(options?.steps ?? current.imageScene?.steps ?? template.defaultSteps, config),
seed: options?.seed ?? current.imageScene?.seed ?? -1 };
const dimensions = characterSheetDimensions(config.settings.resolution, options?.height);
- const firstView = CHARACTER_SHEET_ORDER[0];
+ const indices = characterSheetViewIndices(options);
+ const order = CHARACTER_SHEET_ORDER.filter((index) => indices.includes(index));
+ const firstView = order[0];
const { width, height } = dimensions[firstView];
let finish!: () => void;
const done = new Promise<void>((resolve) => { finish = resolve; });
@@ -360,22 +363,22 @@ export class WorkQueue {
referencePaths: views[firstView].references.flatMap((reference) => referenceImages(reference).map((image) => projectItemPath(session.record.folderPath, image)!)),
refmods: referenceRefmodInputs(session.record.folderPath, views[firstView].references) };
const imageGeneration: ImageGenerationSnapshot = {
- ...imageGenerationSnapshot({ ...config, imageScene: { ...createImageScene(options?.prompt ?? ""), steps: request.steps, seed: config.imageScene.seed } }, views.map((view) => view.prompt).join("\n\n"), template.id),
+ ...imageGenerationSnapshot({ ...config, imageScene: { ...createImageScene(options?.prompt ?? ""), steps: request.steps, seed: config.imageScene.seed } }, indices.map((index) => views[index].prompt).join("\n\n"), template.id),
usedSeed: request.seed,
- references: [...new Map(views.flatMap((view) => view.references.slice(1)).map((reference) => [reference.id, reference])).values()],
+ references: [...new Map(indices.flatMap((index) => views[index].references.slice(1)).map((reference) => [reference.id, reference])).values()],
template: { kind: "character-sheet", sourceId, sourceName: source.name, generatorName: template.name, prompt: options?.prompt ?? "",
- height, steps: request.steps, seed: config.imageScene.seed },
+ height, steps: request.steps, seed: config.imageScene.seed, views: characterSheetViews(options) },
};
- this.work.set(id, { id, image: true, imageDraftId: id, characterSheet: { views, dimensions, sourceId, name: `Character sheet - ${source.name}`, index: 0 },
+ this.work.set(id, { id, image: true, imageDraftId: id, characterSheet: { views, dimensions, order, sourceId, name: `Character sheet - ${source.name}`, index: 0 },
imageGeneration,
session, sceneId: current.imageScene?.nodes[0].id ?? "image-root", config, snapshot: JSON.stringify(current.imageScene),
request, submitted: false, cancelled: false, done, finish });
this.items = [...this.items, { id, kind: "image", imageAssetId: sourceId, imageDraftId: id, projectKey, folderPath: session.record.folderPath, projectName: config.name,
sceneId: this.work.get(id)!.sceneId, title: `Character sheet · ${source.name}`, submittedAt: new Date().toISOString(),
status: "queued", progress: 0, detail: "Waiting to generate character sheet", error: null, completionAt: null, cancelling: false, needsSave: false,
- settings: { frames: 4, steps: request.steps, seed: request.seed, canvasWidth: width, canvasHeight: height } }];
+ settings: { frames: order.length, steps: request.steps, seed: request.seed, canvasWidth: width, canvasHeight: height } }];
session.update((current) => createTemplateImageDraft(current, id, `Character sheet - ${source.name}`, imageGeneration,
- { width: dimensions.reduce((total, view) => total + view.width, 0), height }));
+ { width: indices.reduce((total, index) => total + dimensions[index].width, 0), height }));
this.publish(); this.icons.yieldToVideo(); void this.pump();
}
/** Queues encoding one reference's images, video or sound into a refmod file. */
@@ -552,8 +555,8 @@ export class WorkQueue {
if (work.characterSheet) {
const sheet = work.characterSheet;
const fraction = event.totalSteps > 0 ? Math.max(0, Math.min(1, event.step / event.totalSteps)) : 0;
- this.patch(work.id, { progress: Math.max(item.progress, (sheet.index + fraction) / 4 * 0.9),
- detail: item.cancelling ? "Cancelling generation" : `Character sheet ${sheet.index + 1}/4 · ${CHARACTER_SHEET_VIEWS[CHARACTER_SHEET_ORDER[sheet.index]].label}` });
+ this.patch(work.id, { progress: Math.max(item.progress, (sheet.index + fraction) / sheet.order.length * 0.9),
+ detail: item.cancelling ? "Cancelling generation" : `Character sheet ${sheet.index + 1}/${sheet.order.length} · ${CHARACTER_SHEET_VIEWS[sheet.order[sheet.index]].label}` });
return;
}
const progress = Math.max(item.progress, event.totalSteps > 0 ? Math.min(0.88, 0.12 + Math.max(0, event.step) / event.totalSteps * 0.76) : event.stage === "delivering" ? 0.88 : 0.08);
@@ -592,10 +595,10 @@ export class WorkQueue {
const folderPath = work.session.record.folderPath;
const dimensions = sheet.dimensions;
try {
- for (let index = 0; index < sheet.views.length; index++) {
+ for (let index = 0; index < sheet.order.length; index++) {
if (work.cancelled) return;
sheet.index = index;
- const viewIndex = CHARACTER_SHEET_ORDER[index];
+ const viewIndex = sheet.order[index];
const { width, height } = dimensions[viewIndex];
work.submitted = false;
const view = sheet.views[viewIndex];
@@ -603,25 +606,25 @@ export class WorkQueue {
canvasWidth: width, canvasHeight: height,
referencePaths: view.references.flatMap((reference) => referenceImages(reference).map((image) => projectItemPath(folderPath, image)!)),
refmods: referenceRefmodInputs(folderPath, view.references) };
- this.patch(work.id, { status: "preparing", detail: `Preparing character sheet view ${index + 1}/4` });
+ this.patch(work.id, { status: "preparing", detail: `Preparing character sheet view ${index + 1}/${sheet.order.length}` });
await resolveSlopfabPlan(work.request, work.config, folderPath);
if (work.cancelled) return;
const ready = new Promise<void>((resolve, reject) => { sheet.ready = { resolve, reject }; });
// Events can arrive before native submission returns.
void ready.catch(() => undefined);
- this.patch(work.id, { status: "generating", detail: `Character sheet ${index + 1}/4 · ${CHARACTER_SHEET_VIEWS[viewIndex].label}` });
+ this.patch(work.id, { status: "generating", detail: `Character sheet ${index + 1}/${sheet.order.length} · ${CHARACTER_SHEET_VIEWS[viewIndex].label}` });
await enqueueSlopfabGeneration(work.request, work.config, folderPath);
work.submitted = true;
if (work.cancelled) await this.requestNativeCancellation(work);
await ready;
sheet.ready = undefined;
if (work.cancelled) { this.cancelled(work); return; }
- this.patch(work.id, { status: "encoding", detail: `Saving character sheet view ${index + 1}/4` });
+ this.patch(work.id, { status: "encoding", detail: `Saving character sheet view ${index + 1}/${sheet.order.length}` });
await invoke("save_character_sheet_view", { folderPath, sheetId: work.id, jobId: work.request.jobId, index: viewIndex });
await releaseRendered(work.request.jobId);
}
this.patch(work.id, { status: "encoding", progress: 0.95, detail: "Combining character sheet", completionAt: null });
- const saved = await invoke<{ relativePath: string; width: number; height: number }>("combine_character_sheet", { folderPath, sheetId: work.id });
+ const saved = await invoke<{ relativePath: string; width: number; height: number }>("combine_character_sheet", { folderPath, sheetId: work.id, indices: [...sheet.order].sort((a, b) => a - b) });
const scene = createImageEditScene({ ...saved, name: sheet.name }, work.config.imageScene ?? undefined);
scene.referenceIds = [];
const generation = { ...work.imageGeneration!, scene };