feat(engine): PNG frames and sequences can export transparent (#536)

Export Frame as PNG and Export PNG Sequence always painted the stage
colour behind the artwork, though the guide said they were transparent.
Both take background (default true: as before; false: real alpha where
the stage has nothing), and Publish Settings has "Stage colour as
background" for both, kept in the document's publish profile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ayberk A.andClaude Opus 5.5 committed 2026-11-23 13:04:24 +03:00
1 parent 2df7775907
commit 656d953d3d
7 files changed
+70 -15

No files matched your search

+4
View File
@@ -226,6 +226,8 @@ format_settings!(
PngSequenceSettings, PublishFormat::PngSequence, false, {
range: FrameRange = FrameRange::default(),
scale: f32 = 1.0,
/// The stage colour behind each frame; off: transparent (#536).
background: bool = true,
}
);
format_settings!(
@@ -234,6 +236,8 @@ format_settings!(
/// The movie frame (0-based, every scene in order).
frame: u32 = 0,
scale: f32 = 1.0,
/// The stage colour behind it; off: transparent (#536).
background: bool = true,
}
);
format_settings!(
+31
View File
@@ -495,3 +495,34 @@ fn shared_apng_container_preserves_exact_wire_bytes() {
assert!(apng_file(3, 2, 0, &[]).is_err());
assert!(apng_file(3, 2, 0, &[(&second, (1, 1))]).is_err());
}
/// #536: Export Frame as PNG and Export PNG Sequence keep the stage colour by default, and
/// with `background: false` write real alpha: the empty stage is clear and the artwork opaque.
#[test]
fn png_frames_export_transparent_when_asked() {
let dir = tmp("png-alpha");
let mut s = Session::default();
run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 200, "fill": "#ff0000", "stroke": null}));
// (corner pixel's alpha, the rectangle's middle pixel's alpha), at scale 0.5.
let alphas = |bytes: &[u8]| {
let px = anicraft_doc::decode_png(bytes).expect("a PNG");
let a = |x: u32, y: u32| px.rgba[((y * px.width + x) * 4 + 3) as usize];
(a(1, 1), a(100, 100))
};
for background in [true, false] {
let path = dir.join(format!("frame-{background}.png"));
run(&mut s, "file.export_png", json!({"path": path.display().to_string(), "scale": 0.5, "background": background}));
let (corner, art) = alphas(&std::fs::read(&path).unwrap());
assert_eq!(art, 255, "the artwork is opaque either way");
assert_eq!(corner == 255, background, "the empty stage: the stage colour, or clear");
let seq = dir.join(format!("seq-{background}"));
run(&mut s, "file.export_png_sequence", json!({"dir": seq.display().to_string(), "scale": 0.5, "background": background}));
let (corner, _) = alphas(&std::fs::read(seq.join("frame_00001.png")).unwrap());
assert_eq!(corner == 255, background, "the sequence too");
}
// Left out, it is the stage colour, as before.
let path = dir.join("frame-default.png");
run(&mut s, "file.export_png", json!({"path": path.display().to_string(), "scale": 0.5}));
assert_eq!(alphas(&std::fs::read(&path).unwrap()).0, 255);
let _ = std::fs::remove_dir_all(&dir);
}
+17 -5
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
save(s, p)
},
},
CommandSpec { id: "file.export_png", label: "Export Frame as PNG…", menu: "File/Export", shortcut: None, params: "{path, frame? (in the current scene), scale?}", mutates: false, run: export_png },
CommandSpec { id: "file.export_png", label: "Export Frame as PNG…", menu: "File/Export", shortcut: None, params: "{path, frame? (in the current scene), scale?, background? (default true: the stage colour; false: transparent)}", mutates: false, run: export_png },
CommandSpec {
id: "file.import",
label: "Import to Stage…",
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Export PNG Sequence…",
menu: "File/Export",
shortcut: None,
params: "{dir, from?, to? (movie frames: every scene in order), scale?}",
params: "{dir, from?, to? (movie frames: every scene in order), scale?, background? (default true: the stage colour; false: transparent)}",
mutates: false,
run: export_sequence,
},
@@ -261,8 +261,18 @@ pub(crate) fn scale_param(p: &Value) -> Result<f32> {
/// Renders movie frame `frame` (scenes in order) of `doc` to PNG bytes.
pub fn render_png(doc: &Document, frame: u32, scale: f32) -> Result<Vec<u8>> {
render_png_on(doc, frame, scale, true)
}
/// [`render_png`] with the stage colour behind the frame, or (`background` false) nothing: a
/// transparent PNG with real alpha (#536).
pub fn render_png_on(doc: &Document, frame: u32, scale: f32, background: bool) -> Result<Vec<u8>> {
let dl = anicraft_doc::evaluate(doc, frame);
let (pm, _) = render(&dl, &View::stage(doc, scale))?;
let mut view = View::stage(doc, scale);
if !background {
view.background = None;
}
let (pm, _) = render(&dl, &view)?;
Ok(pm.encode_png()?)
}
@@ -270,7 +280,8 @@ fn export_png(s: &mut Session, p: &Value) -> Result<Value> {
let path = PathBuf::from(str_req(p, "path")?);
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame);
// `frame` is within the current scene; the renderer takes movie frames.
let bytes = render_png(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame), scale_param(p)?)?;
let background = opt_bool(p, "background")?.unwrap_or(true);
let bytes = render_png_on(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame), scale_param(p)?, background)?;
crate::vfs::write(&path, &bytes)?;
Ok(json!({"written": path.display().to_string(), "bytes": bytes.len(), "frame": frame}))
}
@@ -767,6 +778,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Param("'to' must not be before 'from'".into()));
}
let scale = scale_param(p)?;
let background = opt_bool(p, "background")?.unwrap_or(true);
crate::vfs::create_dir_all(&dir)?;
// Frames are independent: render and encode them in parallel (each render is itself
// row-parallel; rayon balances both levels), a batch at a time so memory stays bounded.
@@ -777,7 +789,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result<Value> {
let mut files = 0usize;
let frames: Vec<u32> = (from..=to).collect();
for batch in frames.chunks(64) {
let pngs = batch.par_iter().map(|&f| render_png(doc, f, scale)).collect::<Result<Vec<_>>>()?;
let pngs = batch.par_iter().map(|&f| render_png_on(doc, f, scale, background)).collect::<Result<Vec<_>>>()?;
for (f, png) in batch.iter().zip(pngs) {
crate::vfs::write(&dir.join(format!("frame_{:05}.png", f + 1)), png)?;
files += 1;
+7 -3
View File
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Publish Settings",
menu: "",
shortcut: None,
params: "{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}",
params: "{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale, background (png_sequence); frame, scale, background (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}",
mutates: true,
run: settings_set,
},
@@ -248,6 +248,7 @@ pub fn plan(doc: &Document, path: Option<&Path>, only: Option<&[PublishFormat]>)
let q = &prof.png_sequence;
let n = range_params(&mut p, q.range, last);
p.insert("scale".into(), json!(q.scale));
p.insert("background".into(), json!(q.background));
("file.export_png_sequence", n, vec![out])
}
PublishFormat::Png => {
@@ -255,6 +256,7 @@ pub fn plan(doc: &Document, path: Option<&Path>, only: Option<&[PublishFormat]>)
scene = sc;
p.insert("frame".into(), json!(local));
p.insert("scale".into(), json!(prof.png.scale));
p.insert("background".into(), json!(prof.png.background));
("file.export_png", 1, vec![out])
}
PublishFormat::Svg => {
@@ -564,8 +566,8 @@ fn option_keys(f: PublishFormat) -> &'static [&'static str] {
PublishFormat::Video => &["from", "to", "scale", "audio"],
PublishFormat::Lottie => &["from", "to", "background"],
PublishFormat::SpriteSheet => &["from", "to", "scale", "columns", "padding", "background"],
PublishFormat::PngSequence => &["from", "to", "scale"],
PublishFormat::Png => &["frame", "scale"],
PublishFormat::PngSequence => &["from", "to", "scale", "background"],
PublishFormat::Png => &["frame", "scale", "background"],
PublishFormat::Svg => &["frame"],
PublishFormat::Audio => &["from", "to", "rate", "bits"],
}
@@ -685,12 +687,14 @@ fn apply(prof: &mut PublishProfile, f: PublishFormat, p: &Value) -> Result<()> {
PublishFormat::PngSequence => {
set_range(&mut prof.png_sequence.range, p)?;
set_scale(&mut prof.png_sequence.scale, p)?;
set_bool(&mut prof.png_sequence.background, p, "background")?;
}
PublishFormat::Png => {
if let Some(fr) = opt_u32(p, "frame")? {
prof.png.frame = fr.min(crate::MAX_FRAME);
}
set_scale(&mut prof.png.scale, p)?;
set_bool(&mut prof.png.background, p, "background")?;
}
PublishFormat::Svg => {
if let Some(fr) = opt_u32(p, "frame")? {
+6 -4
View File
@@ -47,8 +47,10 @@ exported frames of its kind.
### Stills and sequences
* **PNG image** and **PNG sequence** have real transparency where the stage has nothing, and
can be scaled up to 800 %. The sequence writes `frame_00001.png` and on into its folder.
* **PNG image** and **PNG sequence** show the stage colour behind the artwork. Turn off
**Stage colour as background** in Publish Settings (or pass `background: false`) for real
transparency where the stage has nothing. Both can be scaled up to 800 %. The sequence writes
`frame_00001.png` and on into its folder.
* **SVG image** writes one frame as a standalone vector drawing that matches the stage: shapes,
strokes, gradients, masks (as clip paths), filters (as SVG filters) and blend modes. Bitmaps
are embedded.
@@ -151,8 +153,8 @@ work. Your choices are saved in the document, and every change can be undone.
| Video | Frames, Scale, Include sound |
| Lottie | Frames, Stage colour as background |
| Sprite sheet | Frames, Scale, Columns, Padding, Stage colour as background |
| PNG sequence | Frames, Scale |
| PNG image | Frame (or **Playhead**), Scale |
| PNG sequence | Frames, Scale, Stage colour as background |
| PNG image | Frame (or **Playhead**), Scale, Stage colour as background |
| SVG image | Frame (or **Playhead**) |
| Audio | Frames, Sample rate, Bit depth |
+3 -3
View File
@@ -21,7 +21,7 @@ This page is generated from the command registry, so it always matches the versi
- **Save as Template…** `file.save_as_template`
Parameters: `{folder (the user templates folder), name, category? (default “My Templates”), confirm? (to replace a template of that name)} → {path, thumbnail}: the document as it is, kept as <folder>/<category>/<name>.anicraft with a picture of its first frame; the open document is unchanged`
- **Export Frame as PNG…** `file.export_png` · File › Export
Parameters: `{path, frame? (in the current scene), scale?}`
Parameters: `{path, frame? (in the current scene), scale?, background? (default true: the stage colour; false: transparent)}`
- **Import to Stage…** `file.import` · File › Import · **Ctrl+R** (macOS **⌘R**) · changes the document
Parameters: `{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred), cx?, cy? (centred on that point instead), layer? (new (default) | active: a one-layer drawing goes into the active layer's keyframe at the playhead)}`
- **Export Frame as SVG…** `file.export_svg` · File › Export
@@ -31,7 +31,7 @@ This page is generated from the command registry, so it always matches the versi
- **Export Sprite Sheet…** `file.export_sprite_sheet` · File › Export
Parameters: `{path (.png; the frame map goes beside it as .json), from?, to? (movie frames), scale?, columns?, padding?, background?, confirm?}`
- **Export PNG Sequence…** `file.export_png_sequence` · File › Export
Parameters: `{dir, from?, to? (movie frames: every scene in order), scale?}`
Parameters: `{dir, from?, to? (movie frames: every scene in order), scale?, background? (default true: the stage colour; false: transparent)}`
- **Export SVG Sequence…** `file.export_svg_sequence` · File › Export
Parameters: `{dir, from?, to? (movie frames: every scene in order), confirm?} → one frame_00001.svg per frame (vectors, gradients and masks kept)`
- **Export Animated GIF…** `file.export_gif` · File › Export
@@ -322,7 +322,7 @@ These commands have no menu item: the panels, the stage and the timeline use the
- **Close Envelope** `modify.envelope_close` · changes the document
Parameters: `{} closes the open envelope: bent raw shapes merge with the drawing they now touch (as after a move). Nothing to close is no error → {closed}`
- **Publish Settings** `publish.settings_set` · changes the document
Parameters: `{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}`
Parameters: `{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale, background (png_sequence); frame, scale, background (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}`
- **Open Recent** `file.open_recent`
Parameters: `{index? (in file.recent_list order, from 0) | path?, confirm? (needed over unsaved changes)}: opens it as file.open does; a file that is no longer there stays on the list, marked missing`
- **Recent Files** `file.recent_list`
+2
View File
@@ -525,11 +525,13 @@ fn options(app: &mut App, ui: &mut egui::Ui, f: PublishFormat) {
PublishFormat::PngSequence => {
range_row(app, ui, f, p.png_sequence.range);
scale_row(app, ui, f, p.png_sequence.scale);
check(app, ui, f, "background", p.png_sequence.background, tr!("Stage colour as background"), tr!("Off: transparent"));
form_note(ui, FORM_LABEL_DIALOG, text(Type::Caption, tr!("The output is a folder; the frames in it are frame_00001.png and on.")));
}
PublishFormat::Png => {
frame_row(app, ui, f, p.png.frame);
scale_row(app, ui, f, p.png.scale);
check(app, ui, f, "background", p.png.background, tr!("Stage colour as background"), tr!("Off: transparent"));
}
PublishFormat::Svg => frame_row(app, ui, f, p.svg.frame),
PublishFormat::Audio => {