//! Document → SWF export orchestration (ADR 0135). //! //! Maps AniCraft's document model to SWF v10+ tags: `FileAttributes`, `SetBackgroundColor`, //! `DefineShape4`, `DefineSprite`, `DefineButton2`, `DefineMorphShape2`, `DefineEditText`, //! `DefineBitsLossless2`, `DefineSound`/`StartSound`, `SoundStreamHead2`/`SoundStreamBlock`, //! `PlaceObject3`, `RemoveObject2`, `FrameLabel`, `ShowFrame` and `End`. use std::collections::{HashMap, HashSet}; use std::sync::Arc; use anicraft_doc::{ BitmapId, BlendMode, ColorTransform, Document, Element, ElementId, ElementKind, Filter, LayerId, LayerKind, Paint, Rgba, Shape, Sound, SoundId, SoundSync, Stroke, Symbol, SymbolId, SymbolKind, TextBlock, Timeline, TweenKind, evaluate_layer_elements, expand_groups, publish::SwfScriptTarget, }; use anicraft_geom::{Affine, FillRule, Path, PathCmd, Rect, Vec2}; use crate::effects::{blend_code, filter_list_body}; use crate::media::{self, PreparedSound}; use crate::shape::{self, Layer as ShapeLayer, ShapeInput}; use crate::text::define_edit_text; use crate::writer::{px_to_twips, signed_bits_of, tag, twips_matrix, Writer}; const TAG_END: u16 = 0; const TAG_SHOW_FRAME: u16 = 1; const TAG_SET_BACKGROUND_COLOR: u16 = 9; const TAG_DO_ACTION: u16 = 12; const TAG_DEFINE_SOUND: u16 = 14; const TAG_START_SOUND: u16 = 15; const TAG_DEFINE_BUTTON_SOUND: u16 = 17; const TAG_SOUND_STREAM_BLOCK: u16 = 19; const TAG_REMOVE_OBJECT2: u16 = 28; const TAG_DEFINE_BUTTON2: u16 = 34; const TAG_DEFINE_BITS_LOSSLESS2: u16 = 36; const TAG_DEFINE_EDIT_TEXT: u16 = 37; const TAG_DEFINE_SPRITE: u16 = 39; const TAG_FRAME_LABEL: u16 = 43; const TAG_SOUND_STREAM_HEAD2: u16 = 45; const TAG_EXPORT_ASSETS: u16 = 56; const TAG_DO_INIT_ACTION: u16 = 59; const TAG_FILE_ATTRIBUTES: u16 = 69; const TAG_PLACE_OBJECT3: u16 = 70; const TAG_DEFINE_SCALING_GRID: u16 = 78; const TAG_DEFINE_SHAPE4: u16 = 83; const TAG_DEFINE_MORPH_SHAPE2: u16 = 84; fn twips(v: f32) -> i32 { px_to_twips(v) } /// Export options. #[derive(Clone, Debug)] pub struct ExportOptions { /// zlib `CWS` (true) or uncompressed `FWS` (false). pub compress: bool, /// SWF version (8 for AVM1, at least 10 for AVM2). pub version: u8, /// `FileAttributes` UseNetwork flag (default false: local playback). pub use_network: bool, /// Script VM target (`Auto` picks AVM1 if the document has AS1/AS2 scripts, else AVM2). pub script_target: SwfScriptTarget, /// Sibling `.as` files `(filename, source)` for AVM1 `#include` and `DoInitAction` classes. pub as2_files: Vec<(String, String)>, } impl Default for ExportOptions { fn default() -> Self { ExportOptions { compress: true, version: 10, use_network: false, script_target: SwfScriptTarget::Auto, as2_files: Vec::new(), } } } /// What was left out or downgraded, for honest reporting (AGENTS.md rule 15). #[derive(Default)] pub struct ExportReport { pub bytes: usize, pub frames: u32, pub characters: u32, /// Frame scripts compiled natively to AVM2 bytecode (`DoABC` + `SymbolClass`). pub scripts_compiled: u32, /// Frame scripts that could not be compiled natively (reported in `notes`). pub scripts_unsupported: u32, pub notes: Vec, } /// A finished SWF and its report. pub struct SwfExport { pub swf: Vec, pub report: ExportReport, /// `(character_id, class_name)` pairs for exported library symbols with linkage. pub symbol_classes: Vec<(u16, String)>, } /// Exports `doc` to a SWF binary. pub fn export(doc: &Document, opts: &ExportOptions) -> Result { let is_avm1 = resolve_avm1(doc, opts.script_target); let version = if is_avm1 { 8 } else { opts.version.max(10) }; let mut dict = Dict::new(); let mut defs = Writer::new(); let mut root = Writer::new(); let mut report = ExportReport::default(); let frames = doc.frame_count(); report.frames = frames; emit_movie(doc, is_avm1, &opts.as2_files, &mut dict, &mut defs, &mut root, &mut report)?; // Deduplicate notes while preserving first-seen order. let mut seen_notes = HashSet::new(); report.notes.retain(|n| seen_notes.insert(n.clone())); let mut body = Writer::new(); body.rect(0, twips(doc.stage.width as f32), 0, twips(doc.stage.height as f32)); body.u16((doc.stage.fps.clamp(1.0, 240.0) * 256.0).round() as u16); body.u16(frames.min(u16::MAX as u32) as u16); body.bytes(&file_attributes(opts.use_network, !is_avm1)); body.bytes(&set_background(doc.stage.background)); body.bytes(defs.as_bytes()); body.bytes(root.as_bytes()); body.bytes(&tag(TAG_END, &[])); let swf = assemble(version, &body.into_bytes(), opts.compress); report.bytes = swf.len(); report.characters = u32::from(dict.next.saturating_sub(1)); let symbol_classes = collect_symbol_classes(doc, &dict); Ok(SwfExport { swf, report, symbol_classes }) } fn resolve_avm1(doc: &Document, target: SwfScriptTarget) -> bool { match target { SwfScriptTarget::ActionScript2 => true, SwfScriptTarget::ActionScript3 => false, SwfScriptTarget::Auto => { let mut has_as12 = !doc.instance_scripts.is_empty(); let mut has_as3 = false; let scan_tl = |tl: &Timeline, as12: &mut bool, as3: &mut bool| { for l in &tl.layers { for k in &l.keyframes { if let Some(anicraft_actions::FrameScript::Source(src)) = &k.script { match src.language { anicraft_actions::Language::ActionScript1or2 => *as12 = true, anicraft_actions::Language::ActionScript3 => *as3 = true, anicraft_actions::Language::Other => {} } } } } }; for s in &doc.scenes { scan_tl(&s.timeline, &mut has_as12, &mut has_as3); } for sym in &doc.library { scan_tl(&sym.timeline, &mut has_as12, &mut has_as3); } has_as12 && !has_as3 } } } fn assemble(version: u8, body: &[u8], compress: bool) -> Vec { let signature: &[u8; 3] = if compress { b"CWS" } else { b"FWS" }; let payload: Vec = if compress { miniz_oxide::deflate::compress_to_vec_zlib(body, 6) } else { body.to_vec() }; let uncompressed_len = 8 + body.len() as u32; let mut out = Vec::with_capacity(8 + payload.len()); out.extend_from_slice(signature); out.push(version); out.extend_from_slice(&uncompressed_len.to_le_bytes()); out.extend_from_slice(&payload); out } fn file_attributes(network: bool, is_as3: bool) -> Vec { let mut w = Writer::new(); // SWF v19 FileAttributes: bit 3 = ActionScript3 (0x08), bit 0 = UseNetwork (0x01) in byte 0. let flags: u32 = (if is_as3 { 0x08 } else { 0x00 }) | u32::from(network); w.u32(flags); tag(TAG_FILE_ATTRIBUTES, &w.into_bytes()) } fn set_background(c: Rgba) -> Vec { let mut w = Writer::new(); w.rgb(c); tag(TAG_SET_BACKGROUND_COLOR, &w.into_bytes()) } // ----- character dictionary ------------------------------------------------------------------- struct Dict { next: u16, shapes: HashMap, sprites: HashMap, /// Single-frame snapshots of Graphic symbols (`LoopMode::SingleFrame`), keyed by `(symbol, frame)`. graphic_frames: HashMap<(SymbolId, u32), u16>, buttons: HashMap, /// Per-instance `DefineButton2` IDs for buttons carrying AVM1 `on(...)` scripts. button_instances: HashMap, bitmaps: HashMap, sounds: HashMap, /// Prepared (resampled) sounds, cached by sound id. prepared_sounds: HashMap>, } impl Dict { fn new() -> Self { // SWF character IDs are 1-based; 0 is reserved for the main timeline. Dict { next: 1, shapes: HashMap::new(), sprites: HashMap::new(), graphic_frames: HashMap::new(), buttons: HashMap::new(), button_instances: HashMap::new(), bitmaps: HashMap::new(), sounds: HashMap::new(), prepared_sounds: HashMap::new(), } } fn alloc(&mut self) -> u16 { let id = self.next; self.next = self.next.wrapping_add(1); id } } /// The whole movie: every scene's timeline, one after the other, on the root timeline. fn emit_movie( doc: &Document, is_avm1: bool, as2_files: &[(String, String)], dict: &mut Dict, defs: &mut Writer, root: &mut Writer, report: &mut ExportReport, ) -> Result<(), String> { if is_avm1 && !as2_files.is_empty() { emit_avm1_init_classes(as2_files, dict, defs, report); } let mut carry_depths: Vec = Vec::new(); for scene in &doc.scenes { carry_depths = emit_timeline(doc, &scene.timeline, is_avm1, as2_files, &carry_depths, dict, defs, root, report)?; } if is_avm1 { emit_avm1_exports(doc, as2_files, dict, defs, report); } else { emit_avm2(doc, dict, defs, report); } Ok(()) } /// Compile sibling AS2 class `.as` files into `DoInitAction` (tag 59) tags so `_global.` /// is registered before frame 1 runs. fn emit_avm1_init_classes(as2_files: &[(String, String)], dict: &mut Dict, defs: &mut Writer, report: &mut ExportReport) { for (filename, src) in as2_files { let expanded = expand_includes(src, as2_files, 0); match anicraft_avm1::compile_as2_class(&expanded) { Ok((_class_name, actions)) => { // Attach each DoInitAction to a dedicated empty helper sprite so Flash/Ruffle executes it once. let sprite_id = dict.alloc(); let mut sp = Writer::new(); sp.u16(sprite_id); sp.u16(1); sp.bytes(&tag(TAG_SHOW_FRAME, &[])); sp.bytes(&tag(TAG_END, &[])); defs.bytes(&tag(TAG_DEFINE_SPRITE, &sp.into_bytes())); let mut init = Writer::new(); init.u16(sprite_id); init.bytes(&actions); defs.bytes(&tag(TAG_DO_INIT_ACTION, &init.into_bytes())); report.scripts_compiled += 1; } Err(e) if expanded.contains("class ") => { report.scripts_unsupported += 1; report.notes.push(format!("AS2 class file '{filename}' could not be compiled ({e})")); } Err(_) => {} } } } /// Resolve `#include "file.as"` directives in an AS1/AS2 script against `as2_files`. fn expand_includes(src: &str, as2_files: &[(String, String)], depth: usize) -> String { if depth >= 4 || as2_files.is_empty() || !src.contains("#include") { return src.to_string(); } let mut out = String::with_capacity(src.len()); for line in src.split_inclusive(['\n', '\r']) { let trimmed = line.trim(); if let Some(rest) = trimmed.strip_prefix("#include") { let target = rest.trim().trim_matches(['"', '\'']); if let Some((_, inc_src)) = as2_files.iter().find(|(name, _)| name == target || name.ends_with(&format!("/{target}"))) { out.push_str(&expand_includes(inc_src, as2_files, depth + 1)); out.push('\n'); continue; } } out.push_str(line); } out } /// Emit `ExportAssets` (tag 56) for linked library symbols so AVM1 `attachMovie` can instantiate them. fn emit_avm1_exports(doc: &Document, as2_files: &[(String, String)], dict: &mut Dict, defs: &mut Writer, report: &mut ExportReport) { let mut exports: Vec<(u16, String)> = Vec::new(); for sym in &doc.library { let Some(linkage) = &sym.linkage else { continue }; if linkage.class.is_empty() { continue; } let char_id = match sym.kind { SymbolKind::Button => emit_button(doc, sym, &[], true, as2_files, dict, defs, report), _ => emit_sprite(doc, sym, true, as2_files, dict, defs, report), }; exports.push((char_id, linkage.class.clone())); } for s in &doc.sounds { let Some(linkage) = &s.linkage else { continue }; if linkage.is_empty() { continue; } if let Ok(char_id) = sound_char(doc, s.id, dict, defs, report) { exports.push((char_id, linkage.clone())); } } if exports.is_empty() { return; } let mut w = Writer::new(); w.u16(exports.len().min(u16::MAX as usize) as u16); for (id, name) in exports.iter().take(u16::MAX as usize) { w.u16(*id); w.string(name); } defs.bytes(&tag(TAG_EXPORT_ASSETS, &w.into_bytes())); } fn collect_symbol_classes(doc: &Document, dict: &Dict) -> Vec<(u16, String)> { let mut out = Vec::new(); for sym in &doc.library { let Some(linkage) = &sym.linkage else { continue }; if linkage.class.is_empty() { continue; } if let Some(&id) = dict.sprites.get(&sym.id).or_else(|| dict.buttons.get(&sym.id)) { out.push((id, linkage.class.clone())); } } out } /// Compile supported AS3 frame scripts natively to AVM2 (`DoABC` + `SymbolClass`). fn emit_avm2(doc: &Document, dict: &Dict, defs: &mut Writer, report: &mut ExportReport) { let mut movie = anicraft_avm2::Movie::default(); let root_class = if doc.document_class.trim().is_empty() { "MainTimeline" } else { doc.document_class.trim() }; if let Some(root_tl) = collect_root_scripts(doc, root_class, report) { movie.timelines.push(root_tl); } for sym in &doc.library { let Some(&char_id) = dict.sprites.get(&sym.id) else { continue }; let class_name = sym .linkage .as_ref() .filter(|l| !l.class.is_empty()) .map_or_else(|| format!("Symbol_{char_id}"), |l| l.class.clone()); if let Some(sym_tl) = collect_timeline_scripts(&sym.timeline, &class_name, char_id, 0, report) { movie.timelines.push(sym_tl); } } if movie.timelines.is_empty() { return; } let out = movie.compile(); if out.ok() && !out.do_abc.is_empty() { defs.bytes(&out.do_abc); defs.bytes(&out.symbol_class); report.scripts_compiled = out.scripts_compiled as u32; } else { report.scripts_unsupported += out.scripts_unsupported as u32 + out.scripts_compiled as u32; for d in out.diagnostics { report.notes.push(format!("AVM2 compilation skipped: {d}")); } } } fn collect_root_scripts(doc: &Document, class_name: &str, report: &mut ExportReport) -> Option { let mut compiled_scripts = Vec::new(); let mut decl_inputs = Vec::new(); let mut offset = 0u32; for scene in &doc.scenes { gather_timeline_scripts(&scene.timeline, offset, &mut compiled_scripts, &mut decl_inputs, report); offset = offset.saturating_add(scene.timeline.frame_count().max(1)); } if compiled_scripts.is_empty() { return None; } let decls = anicraft_actions::as3::Decls::build(decl_inputs.iter()); let mut tl = anicraft_avm2::Timeline::new(class_name, 0, decls); tl.scripts = compiled_scripts; Some(tl) } fn collect_timeline_scripts( tl: &Timeline, class_name: &str, char_id: u16, frame_offset: u32, report: &mut ExportReport, ) -> Option { let mut compiled_scripts = Vec::new(); let mut decl_inputs = Vec::new(); gather_timeline_scripts(tl, frame_offset, &mut compiled_scripts, &mut decl_inputs, report); if compiled_scripts.is_empty() { return None; } let decls = anicraft_actions::as3::Decls::build(decl_inputs.iter()); let mut out = anicraft_avm2::Timeline::new(class_name, char_id, decls); out.scripts = compiled_scripts; Some(out) } fn gather_timeline_scripts( tl: &Timeline, frame_offset: u32, out: &mut Vec, decls_in: &mut Vec, report: &mut ExportReport, ) { let mut by_frame: Vec<(u32, usize, &anicraft_actions::FrameScript)> = Vec::new(); for (li, layer) in tl.layers.iter().enumerate() { for kf in &layer.keyframes { if let Some(script) = &kf.script { by_frame.push((frame_offset.saturating_add(kf.start), li, script)); } } } by_frame.sort_by_key(|(f, li, _)| (*f, *li)); for (frame, _, script) in by_frame { match script { anicraft_actions::FrameScript::Source(src) => match src.compiled() { Ok(compiled) => { out.push(anicraft_avm2::FrameScript { frame, body: compiled.body.clone(), inner: compiled.inner.clone(), line: 1, }); decls_in.push(compiled.clone()); } Err(problems) => { report.scripts_unsupported += 1; if let Some(first) = problems.first() { report.notes.push(format!("frame {}: script not compiled natively ({first}); configure ANICRAFT_AS3C for full AS3", frame + 1)); } } }, anicraft_actions::FrameScript::Actions(_) | anicraft_actions::FrameScript::Plugin { .. } => { report.scripts_unsupported += 1; report.notes.push(format!("frame {}: non-AS3 frame script skipped in native SWF export", frame + 1)); } } } } // ----- depth assignment ----------------------------------------------------------------------- struct DepthMap { depth: HashMap, /// Clip depth for each mask element (the highest masked depth below it). clip: HashMap, } /// Layer indices in depth-assignment order (lower depth first), mask-aware. fn depth_order(tl: &Timeline) -> Vec { let n = tl.layers.len(); let mut order = Vec::new(); for i in (0..n).rev() { let layer = &tl.layers[i]; match layer.kind { LayerKind::Mask => { order.push(i); let j = tl.group_range(i).end; for k in (i + 1..j).rev() { order.push(k); } } LayerKind::Folder | LayerKind::Guide | LayerKind::Camera => {} _ => { if !is_masked(tl, i) { order.push(i); } } } } order } /// Whether the layer at `index` sits inside a mask group. fn is_masked(tl: &Timeline, index: usize) -> bool { tl.layers.iter().enumerate().any(|(m, mask)| m < index && mask.kind == LayerKind::Mask && tl.is_inside(index, mask.id)) } fn collect_ids(elements: &[Arc], out: &mut Vec, depth: usize) { for e in elements { if let ElementKind::Group { members } = &e.kind && depth < 32 { for l in &members.layers { for k in &l.keyframes { collect_ids(&k.elements, out, depth + 1); } } } else { out.push(e.id); } } } fn assign_depths(tl: &Timeline) -> DepthMap { let mut map = DepthMap { depth: HashMap::new(), clip: HashMap::new() }; let mut next: u16 = 1; let mut mask_top: HashMap = HashMap::new(); for i in depth_order(tl) { let layer = &tl.layers[i]; let mut ids = Vec::new(); for k in &layer.keyframes { collect_ids(&k.elements, &mut ids, 0); } let mut max_here = 0u16; for id in ids { match map.depth.entry(id) { std::collections::hash_map::Entry::Vacant(e) => { e.insert(next); max_here = max_here.max(next); next = next.wrapping_add(1); } std::collections::hash_map::Entry::Occupied(e) => max_here = max_here.max(*e.get()), } } // If this layer is masked (its parent is a mask), note its top depth for that mask. if let Some(parent) = layer.parent && let Some(mask) = tl.layer(parent) && mask.kind == LayerKind::Mask { let top = mask_top.entry(parent).or_insert(0); *top = (*top).max(max_here); } // If this is a mask layer, its elements clip to the masked content's top depth. if layer.kind == LayerKind::Mask { let clip = mask_top.get(&layer.id).copied(); if let Some(clip) = clip { for k in &layer.keyframes { let mut ids = Vec::new(); collect_ids(&k.elements, &mut ids, 0); for id in ids { map.clip.insert(id, clip); } } } } } map } // ----- place objects -------------------------------------------------------------------------- #[derive(Clone, PartialEq)] struct Placement { depth: u16, character: u16, matrix: Affine, color: ColorTransform, blend: Option, filters: Vec, clip: Option, name: String, ratio: Option, clip_actions: Vec, } fn place_object3(p: &Placement, prev: Option<&Placement>) -> Vec { let mut w = Writer::new(); let is_move = prev.is_some_and(|q| q.character == p.character); let has_clip_actions = !is_move && !p.clip_actions.is_empty(); let has_clip = p.clip.is_some(); let has_name = !p.name.is_empty(); let has_ratio = p.ratio.is_some(); // On a move, emit CXFORM even when returning to identity so the player resets the previous tint/alpha. let has_color = !p.color.is_identity() || prev.is_some_and(|q| q.color != p.color); let has_matrix = true; let has_character = !is_move; let has_filters = !p.filters.is_empty(); let blend = p.blend.filter(|&b| b != 0); let reset_blend = blend.is_none() && prev.is_some_and(|q| q.blend.is_some()); let has_blend = blend.is_some() || reset_blend; // SWF v19 PlaceObject3: two separate flag bytes. let flags1: u8 = (u8::from(has_clip_actions) << 7) | (u8::from(has_clip) << 6) | (u8::from(has_name) << 5) | (u8::from(has_ratio) << 4) | (u8::from(has_color) << 3) | (u8::from(has_matrix) << 2) | (u8::from(has_character) << 1) | u8::from(is_move); let flags2: u8 = (u8::from(has_blend) << 1) | u8::from(has_filters); w.u8(flags1); w.u8(flags2); w.u16(p.depth); if has_character { w.u16(p.character); } if has_matrix { w.matrix(&p.matrix); } if has_color { w.cxform_with_alpha(p.color.mul, p.color.add); } if has_ratio { w.u16(p.ratio.unwrap_or(0)); } if has_name { w.string(&p.name); } if has_clip { w.u16(p.clip.unwrap_or(0)); } if has_filters { w.bytes(&filter_list_body(&p.filters)); } if has_blend { // 1 = Normal when resetting from a previous non-normal blend mode. w.u8(blend.unwrap_or(1)); } if has_clip_actions { // SWF 6+ CLIPACTIONS: Reserved (UI16=0), AllEventFlags (UI32), records, EndFlag (UI32=0). w.u16(0); let all_flags = p.clip_actions.iter().fold(0u32, |acc, h| acc | h.event_flags); w.u32(all_flags); for h in &p.clip_actions { w.u32(h.event_flags); let offset = h.actions.len() as u32 + u32::from(h.key_code.is_some()); w.u32(offset); if let Some(k) = h.key_code { w.u8(k); } w.bytes(&h.actions); } w.u32(0); } tag(TAG_PLACE_OBJECT3, &w.into_bytes()) } // ----- timeline emission ---------------------------------------------------------------------- struct MorphSpan { layer: usize, element: ElementId, start: u32, end: u32, char_id: u16, transform: Affine, color: ColorTransform, } #[allow(clippy::too_many_arguments)] fn emit_timeline( doc: &Document, tl: &Timeline, is_avm1: bool, as2_files: &[(String, String)], clear_depths: &[u16], dict: &mut Dict, defs: &mut Writer, body: &mut Writer, report: &mut ExportReport, ) -> Result, String> { let n = tl.frame_count(); let depths = assign_depths(tl); let morphs = detect_morph_spans(tl, dict, defs, report)?; // Frame labels, by frame. let mut labels: HashMap> = HashMap::new(); for layer in &tl.layers { for k in &layer.keyframes { if !k.label.is_empty() { labels.entry(k.start).or_default().push(k.label.clone()); } } } let mut prev: HashMap = HashMap::new(); for frame in 0..n { // When a new scene begins on the root timeline, remove every display object left on stage // by the previous scene before placing this scene's frame 0. if frame == 0 { for &d in clear_depths { let mut w = Writer::new(); w.u16(d); body.bytes(&tag(TAG_REMOVE_OBJECT2, &w.into_bytes())); } } // Emit sounds that start on this frame (event/start/stop), then stream heads. emit_frame_sounds(doc, tl, frame, dict, defs, body, report)?; if let Some(names) = labels.get(&frame) { for name in names { let mut w = Writer::new(); w.string(name); body.bytes(&tag(TAG_FRAME_LABEL, &w.into_bytes())); } } let mut cur: HashMap = HashMap::new(); for (idx, layer) in tl.layers.iter().enumerate() { if layer_skipped(tl, idx) { continue; } let opacity = tl.layer_opacity(idx); // A morph span on this layer overrides the per-frame shape evaluation. if let Some(m) = morphs.iter().find(|m| m.layer == idx && frame >= m.start && frame < m.end) { let duration = (m.end - m.start).max(1); let ratio = ((frame - m.start) as f32 / duration as f32 * 65535.0).round() as u16; let depth = depths.depth.get(&m.element).copied().unwrap_or(0); let clip = depths.clip.get(&m.element).copied(); cur.insert(m.element, Placement { depth, character: m.char_id, matrix: m.transform, color: m.color, blend: None, filters: Vec::new(), clip, name: String::new(), ratio: Some(ratio), clip_actions: Vec::new(), }); continue; } if let Some((_, elements)) = evaluate_layer_elements(layer, frame) { let elements = expand_groups(&elements).into_owned(); for el in elements { let depth = depths.depth.get(&el.id).copied().unwrap_or(0); if depth == 0 { continue; } let Some(character) = emit_element_def(doc, &el, is_avm1, as2_files, dict, defs, report) else { continue }; let mut color = el.color.transform(); if opacity < 1.0 - 1e-4 { color.mul[3] *= opacity; color.add[3] *= opacity; } let (blend, filters, name, clip_actions) = match &el.kind { ElementKind::Symbol { symbol, blend, filters, .. } => { let is_button = doc.symbol(*symbol).is_some_and(|s| s.kind == SymbolKind::Button); let clip_actions = if is_avm1 && !is_button { match doc.instance_script(el.id) { Some(src) => match anicraft_avm1::compile_clip_handlers(src) { Ok(h) => { report.scripts_compiled += 1; h } Err(e) => { report.scripts_unsupported += 1; report.notes.push(format!("instance script skipped: {e}")); Vec::new() } }, None => Vec::new(), } } else { Vec::new() }; (*blend, filters.iter().filter(|f| f.enabled).map(|f| f.filter.clone()).collect(), el.name.clone(), clip_actions) } ElementKind::Text(t) => (BlendMode::Normal, t.filters.iter().filter(|f| f.enabled).map(|f| f.filter.clone()).collect(), el.name.clone(), Vec::new()), _ => (BlendMode::Normal, Vec::new(), String::new(), Vec::new()), }; let clip = depths.clip.get(&el.id).copied(); let p = Placement { depth, character, matrix: twips_matrix(&el.transform), color, blend: blend_code(blend), filters, clip, name, ratio: None, clip_actions, }; cur.insert(el.id, p); } } } // Diff and emit. let mut ids: HashSet = cur.keys().copied().collect(); ids.extend(prev.keys().copied()); for id in &ids { match (cur.get(id), prev.get(id)) { (Some(p), None) => body.bytes(&place_object3(p, None)), (Some(p), Some(q)) if p != q => { body.bytes(&place_object3(p, Some(q))); } (None, Some(_)) => { let mut w = Writer::new(); w.u16(depths.depth.get(id).copied().unwrap_or(0)); body.bytes(&tag(TAG_REMOVE_OBJECT2, &w.into_bytes())); } _ => {} } } prev = cur; // Emit AVM1 `DoAction` (tag 12) for any frame scripts starting on this frame. if is_avm1 { for layer in &tl.layers { for k in &layer.keyframes { if k.start != frame { continue; } let Some(anicraft_actions::FrameScript::Source(src)) = &k.script else { continue }; if src.text.trim().is_empty() { continue; } let expanded = expand_includes(&src.text, as2_files, 0); match anicraft_avm1::compile_frame_script(&expanded) { Ok(bytes) => { body.bytes(&tag(TAG_DO_ACTION, &bytes)); report.scripts_compiled += 1; } Err(e) => { report.scripts_unsupported += 1; report.notes.push(format!("frame {}: AVM1 script skipped ({e})", frame + 1)); } } } } } body.bytes(&tag(TAG_SHOW_FRAME, &[])); } let mut live: Vec = prev.values().map(|p| p.depth).collect(); live.sort_unstable(); live.dedup(); Ok(live) } fn layer_skipped(tl: &Timeline, idx: usize) -> bool { let l = &tl.layers[idx]; !l.visible || matches!(l.kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Guide) || tl.hidden_by_folder(idx) } // ----- character definitions ------------------------------------------------------------------ /// Emits the definition of `el` to `defs` and returns its character id, or `None` when it draws /// nothing (a camera). fn emit_element_def(doc: &Document, el: &Element, is_avm1: bool, as2_files: &[(String, String)], dict: &mut Dict, defs: &mut Writer, report: &mut ExportReport) -> Option { match &el.kind { ElementKind::Shape(s) => Some(emit_shape(doc, s, dict, defs)), ElementKind::Symbol { symbol, loop_mode, first_frame, .. } => { let sym = doc.symbol(*symbol)?; Some(match sym.kind { SymbolKind::Button => { if is_avm1 && let Some(&cached) = dict.button_instances.get(&el.id) { cached } else { let handlers = if is_avm1 { match doc.instance_script(el.id) { Some(src) => match anicraft_avm1::compile_button_handlers(src) { Ok(h) => { report.scripts_compiled += 1; h } Err(e) => { report.scripts_unsupported += 1; report.notes.push(format!("button script skipped: {e}")); Vec::new() } }, None => Vec::new(), } } else { Vec::new() }; let id = emit_button(doc, sym, &handlers, is_avm1, as2_files, dict, defs, report); if !handlers.is_empty() { dict.button_instances.insert(el.id, id); } id } } SymbolKind::Graphic if *loop_mode == anicraft_doc::LoopMode::SingleFrame => { emit_graphic_single_frame(doc, sym, *first_frame, is_avm1, as2_files, dict, defs, report) } _ => emit_sprite(doc, sym, is_avm1, as2_files, dict, defs, report), }) } ElementKind::Text(t) => Some(emit_text(t, dict, defs, report)), ElementKind::Camera => None, ElementKind::Group { .. } => None, // expanded earlier } } /// A stable key for a shape's content, for deduplication. fn shape_key(path: &Path, fill: Option<&Paint>, stroke: Option<&Stroke>, fill_rule: FillRule) -> String { format!("{}|{:?}|{:?}|{:?}", path.to_svg(), fill, stroke, fill_rule) } fn emit_shape(doc: &Document, s: &Shape, dict: &mut Dict, defs: &mut Writer) -> u16 { let key = shape_key(&s.path, s.fill.as_ref(), s.stroke.as_ref(), s.fill_rule); if let Some(&id) = dict.shapes.get(&key) { return id; } let id = dict.alloc(); dict.shapes.insert(key, id); let layers = shape_layers(s); let owned: Vec> = layers.iter().map(|l| ShapeLayer { fill: l.fill.as_ref(), stroke: l.stroke.as_ref(), path: &l.path }).collect(); let input = ShapeInput { fill_rule: s.fill_rule, layers: owned }; let mut bitmap_char = |b: BitmapId| emit_bitmap(doc, b, dict, defs); let body = shape::encode_shape4(&input, &mut bitmap_char); let mut w = Writer::new(); w.u16(id); w.bytes(&body); defs.bytes(&tag(TAG_DEFINE_SHAPE4, &w.into_bytes())); id } /// Owned layers of a shape, with expanded strokes for dashed or variable-width lines. struct OwnedLayer { fill: Option, stroke: Option, path: Arc, } fn shape_layers(s: &Shape) -> Vec { let mut out = Vec::new(); let uniform = s.stroke.as_ref().filter(|st| st.style.dash.is_none() && st.profile.is_none()); if let Some(fill) = &s.fill { out.push(OwnedLayer { fill: Some(fill.clone()), stroke: uniform.cloned(), path: s.path.clone() }); } else if let Some(st) = uniform { out.push(OwnedLayer { fill: None, stroke: Some(st.clone()), path: s.path.clone() }); } if let Some(st) = &s.stroke && (st.style.dash.is_some() || st.profile.is_some()) && let Some(outline) = expand_stroke(&s.path, st) { out.push(OwnedLayer { fill: Some(Paint::Solid(st.color)), stroke: None, path: Arc::new(outline) }); } out } fn expand_stroke(path: &Path, stroke: &Stroke) -> Option { use anicraft_doc::{Cap, Join}; use anicraft_geom::outline::{LineCap, LineJoin, StrokeShape, stroke_outline}; let cap = match stroke.style.cap { Cap::Round => LineCap::Round, Cap::Butt => LineCap::Butt, Cap::Square => LineCap::Square, }; let join = match stroke.style.join { Join::Round => LineJoin::Round, Join::Miter => LineJoin::Miter, Join::Bevel => LineJoin::Bevel, }; let dash = stroke.style.dash.as_ref().map(|d| d.pattern(stroke.width)); let profile = stroke.profile.as_ref(); let width_closure; let widths: Option<&dyn Fn(f32) -> (f32, f32)> = match profile { Some(p) => { width_closure = |t: f32| p.at(t); Some(&width_closure) } None => None, }; let shape = StrokeShape { half_width: stroke.width * 0.5, cap, join, miter_limit: stroke.style.miter_limit, dash: dash.as_ref().map(|(l, o)| (l.as_slice(), *o)), widths, to_local: None, flip: false, }; stroke_outline(path, &shape) } fn emit_bitmap(doc: &Document, id: BitmapId, dict: &mut Dict, defs: &mut Writer) -> u16 { if let Some(&c) = dict.bitmaps.get(&id) { return c; } let c = dict.alloc(); dict.bitmaps.insert(id, c); if let Some(bitmap) = doc.bitmap(id) && let Ok(body) = media::define_bits_lossless2(c, bitmap) { defs.bytes(&tag(TAG_DEFINE_BITS_LOSSLESS2, &body)); } c } fn emit_text(t: &TextBlock, dict: &mut Dict, defs: &mut Writer, report: &mut ExportReport) -> u16 { let id = dict.alloc(); if t.kind() == anicraft_doc::TextKind::Static { // Static text is drawn as vector outlines: a filled shape. if !t.fills.is_empty() { report.notes.push("a text block with several colours is exported in its first colour".into()); } let fill = Paint::Solid(t.color); let layers = vec![ShapeLayer { fill: Some(&fill), stroke: None, path: &t.outline }]; let input = ShapeInput { fill_rule: FillRule::NonZero, layers }; let body = shape::encode_shape4(&input, &mut |_: BitmapId| 0); let mut w = Writer::new(); w.u16(id); w.bytes(&body); defs.bytes(&tag(TAG_DEFINE_SHAPE4, &w.into_bytes())); } else { report.notes.push("a dynamic or input text field uses a device font (font embedding is not yet exported)".into()); let variable = t.field.as_ref().map_or("", |f| f.variable.as_str()); let body = define_edit_text(id, variable, t); defs.bytes(&tag(TAG_DEFINE_EDIT_TEXT, &body)); } id } fn emit_sprite(doc: &Document, sym: &Symbol, is_avm1: bool, as2_files: &[(String, String)], dict: &mut Dict, defs: &mut Writer, report: &mut ExportReport) -> u16 { if let Some(&id) = dict.sprites.get(&sym.id) { return id; } let id = dict.alloc(); dict.sprites.insert(sym.id, id); let mut body = Writer::new(); emit_timeline(doc, &sym.timeline, is_avm1, as2_files, &[], dict, defs, &mut body, report).ok(); // A Graphic symbol with a scaling grid. if let Some(grid) = sym.scale_grid { let mut w = Writer::new(); w.u16(id); w.rect(twips(grid.left), twips(grid.right), twips(grid.top), twips(grid.bottom)); defs.bytes(&tag(TAG_DEFINE_SCALING_GRID, &w.into_bytes())); } let mut body = body.into_bytes(); body.extend_from_slice(&tag(TAG_END, &[])); let mut w = Writer::new(); w.u16(id); w.u16(sym.timeline.frame_count().min(u16::MAX as u32) as u16); w.bytes(&body); defs.bytes(&tag(TAG_DEFINE_SPRITE, &w.into_bytes())); id } /// Emit a 1-frame `DefineSprite` holding only `first_frame` of a `SymbolKind::Graphic` placed /// with `LoopMode::SingleFrame` so it stays fixed on that pose instead of looping. #[allow(clippy::too_many_arguments)] fn emit_graphic_single_frame( doc: &Document, sym: &Symbol, first_frame: u32, is_avm1: bool, as2_files: &[(String, String)], dict: &mut Dict, defs: &mut Writer, report: &mut ExportReport, ) -> u16 { let fc = sym.timeline.frame_count().max(1); let target = first_frame.min(fc - 1); if let Some(&id) = dict.graphic_frames.get(&(sym.id, target)) { return id; } let id = dict.alloc(); dict.graphic_frames.insert((sym.id, target), id); let depths = assign_depths(&sym.timeline); let mut body = Writer::new(); for (idx, layer) in sym.timeline.layers.iter().enumerate() { if layer_skipped(&sym.timeline, idx) { continue; } let opacity = sym.timeline.layer_opacity(idx); if let Some((_, elements)) = evaluate_layer_elements(layer, target) { for el in expand_groups(&elements).into_owned() { let depth = depths.depth.get(&el.id).copied().unwrap_or(0); if depth == 0 { continue; } let Some(character) = emit_element_def(doc, &el, is_avm1, as2_files, dict, defs, report) else { continue }; let mut color = el.color.transform(); if opacity < 1.0 - 1e-4 { color.mul[3] *= opacity; color.add[3] *= opacity; } let p = Placement { depth, character, matrix: twips_matrix(&el.transform), color, blend: None, filters: Vec::new(), clip: depths.clip.get(&el.id).copied(), name: el.name.clone(), ratio: None, clip_actions: Vec::new(), }; body.bytes(&place_object3(&p, None)); } } } body.bytes(&tag(TAG_SHOW_FRAME, &[])); body.bytes(&tag(TAG_END, &[])); let mut w = Writer::new(); w.u16(id); w.u16(1); w.bytes(&body.into_bytes()); defs.bytes(&tag(TAG_DEFINE_SPRITE, &w.into_bytes())); id } #[allow(clippy::too_many_arguments)] fn emit_button( doc: &Document, sym: &Symbol, handlers: &[anicraft_avm1::ButtonHandler], is_avm1: bool, as2_files: &[(String, String)], dict: &mut Dict, defs: &mut Writer, report: &mut ExportReport, ) -> u16 { if handlers.is_empty() && let Some(&id) = dict.buttons.get(&sym.id) { return id; } let id = dict.alloc(); if handlers.is_empty() { dict.buttons.insert(sym.id, id); } // Build button records first so we know `ActionOffset` when `handlers` is non-empty. // A button's timeline frames 0..4 are Up, Over, Down, Hit. In Flash/SWF, a button without a // Hit record (bit 3) has an empty hit area and cannot be clicked; fall back to Up (frame 0) // when Hit (or Down) has no frame of its own. let mut rec = Writer::new(); let fc = sym.timeline.frame_count(); for (state, flag_bit) in [(0u32, 0u8), (1, 1), (2, 2), (3, 3)] { let src_frame = if state < fc { state } else if flag_bit == 3 { 0 } else if flag_bit == 2 && fc > 1 { 1 } else { continue; }; emit_button_state(doc, &sym.timeline, src_frame, flag_bit, is_avm1, as2_files, dict, defs, report, &mut rec); } rec.u8(0); // end of button records let rec_bytes = rec.into_bytes(); // A button's timeline frames 0..4 are Up, Over, Down, Hit. let mut w = Writer::new(); w.u16(id); w.bits(0, 7); // reserved flags w.bit(false); // TrackAsMenu if handlers.is_empty() { w.u16(0); // ActionOffset (no button actions) w.bytes(&rec_bytes); } else if let Ok(action_offset) = u16::try_from(2 + rec_bytes.len()) { w.u16(action_offset); w.bytes(&rec_bytes); for (i, h) in handlers.iter().enumerate() { let is_last = i + 1 == handlers.len(); let cond_size = if is_last { 0u16 } else { (4 + h.actions.len()).min(u16::MAX as usize) as u16 }; w.u16(cond_size); w.u16(h.cond_flags); w.bytes(&h.actions); } } else { report.notes.push("button records exceed SWF DefineButton2 ActionOffset limit; button actions omitted".into()); w.u16(0); w.bytes(&rec_bytes); } defs.bytes(&tag(TAG_DEFINE_BUTTON2, &w.into_bytes())); emit_button_sounds(doc, &sym.timeline, id, dict, defs, report); id } /// Emit `DefineButtonSound` (tag 17) when any of the button's 4 state frames (Up=0, Over=1, /// Down=2, Hit=3) carries a frame sound. fn emit_button_sounds( doc: &Document, tl: &Timeline, button_id: u16, dict: &mut Dict, defs: &mut Writer, report: &mut ExportReport, ) { let mut slots: [Option<&anicraft_doc::FrameSound>; 4] = [None; 4]; for (idx, layer) in tl.layers.iter().enumerate() { if layer_skipped(tl, idx) { continue; } for k in &layer.keyframes { if let Some(fs) = &k.sound && (k.start as usize) < 4 && slots[k.start as usize].is_none() && doc.sound(fs.sound).is_some() { slots[k.start as usize] = Some(fs); } } } if slots.iter().all(Option::is_none) { return; } let mut bs = Writer::new(); bs.u16(button_id); for slot in slots { if let Some(fs) = slot && let Ok(c) = sound_char(doc, fs.sound, dict, defs, report) { bs.bytes(&media::start_sound(c, fs.sync, fs.repeat, fs.looping)); } else { bs.u16(0); } } defs.bytes(&tag(TAG_DEFINE_BUTTON_SOUND, &bs.into_bytes())); } #[allow(clippy::too_many_arguments)] fn emit_button_state( doc: &Document, tl: &Timeline, frame: u32, flag_bit: u8, is_avm1: bool, as2_files: &[(String, String)], dict: &mut Dict, defs: &mut Writer, report: &mut ExportReport, w: &mut Writer, ) { let depths = assign_depths(tl); let mut placements: Vec = Vec::new(); for (idx, layer) in tl.layers.iter().enumerate() { if layer_skipped(tl, idx) { continue; } if let Some((_, elements)) = evaluate_layer_elements(layer, frame) { for el in expand_groups(&elements).into_owned() { let Some(depth) = depths.depth.get(&el.id).copied() else { continue }; if let Some(char_id) = emit_element_def(doc, &el, is_avm1, as2_files, dict, defs, report) { let (blend, filters) = match &el.kind { ElementKind::Symbol { blend, filters, .. } => { (*blend, filters.iter().filter(|f| f.enabled).map(|f| f.filter.clone()).collect()) } ElementKind::Text(t) => { (BlendMode::Normal, t.filters.iter().filter(|f| f.enabled).map(|f| f.filter.clone()).collect()) } _ => (BlendMode::Normal, Vec::new()), }; placements.push(Placement { depth, character: char_id, matrix: twips_matrix(&el.transform), color: el.color.transform(), blend: blend_code(blend), filters, clip: None, name: String::new(), ratio: None, clip_actions: Vec::new(), }); } } } } // Button records are listed in depth order. placements.sort_by_key(|p| p.depth); for p in placements { let flag = 1u8 << flag_bit; let has_blend = p.blend.is_some(); let has_filters = !p.filters.is_empty(); w.bits(0, 2); // reserved w.bit(has_blend); // ButtonHasBlendMode w.bit(has_filters); // ButtonHasFilterList w.bit(flag & 0b1000 != 0); // Hit w.bit(flag & 0b0100 != 0); // Down w.bit(flag & 0b0010 != 0); // Over w.bit(flag & 0b0001 != 0); // Up w.u16(p.character); w.u16(p.depth); w.matrix(&p.matrix); w.cxform_with_alpha(p.color.mul, p.color.add); if has_filters { w.bytes(&crate::effects::filter_list_body(&p.filters)); } if let Some(b) = p.blend { w.u8(b); } } } // ----- morph shapes --------------------------------------------------------------------------- /// Emits morph definitions and returns the spans, or a per-frame fallback (empty spans). fn detect_morph_spans(tl: &Timeline, dict: &mut Dict, defs: &mut Writer, report: &mut ExportReport) -> Result, String> { let mut spans = Vec::new(); for (idx, layer) in tl.layers.iter().enumerate() { for (ki, kf) in layer.keyframes.iter().enumerate() { let Some(tween) = &kf.tween else { continue }; if tween.kind != TweenKind::Shape { continue; } let Some(next) = layer.keyframes.get(ki + 1) else { continue }; if next.start != kf.end() { continue; } let Some((start_shape, end_shape)) = morphable(kf, next) else { report.notes.push("a shape tween whose contours don't align is exported as per-frame keyframes".into()); continue; }; let el = &kf.elements[0]; let id = dict.alloc(); emit_morph(id, start_shape, end_shape, defs); spans.push(MorphSpan { layer: idx, element: el.id, start: kf.start, end: kf.end(), char_id: id, transform: twips_matrix(&el.transform), color: el.color.transform(), }); } } Ok(spans) } fn morphable<'a>(kf: &'a anicraft_doc::Keyframe, next: &'a anicraft_doc::Keyframe) -> Option<(&'a Shape, &'a Shape)> { if kf.elements.len() != 1 || next.elements.len() != 1 { return None; } let (ElementKind::Shape(a), ElementKind::Shape(b)) = (&kf.elements[0].kind, &next.elements[0].kind) else { return None }; let fill_ok = |s: &Shape| matches!(&s.fill, None | Some(Paint::Solid(_))); if a.stroke.is_some() || b.stroke.is_some() || !fill_ok(a) || !fill_ok(b) { return None; } morph_edges(&a.path, &b.path)?; Some((a, b)) } fn emit_morph(id: u16, start: &Shape, end: &Shape, defs: &mut Writer) { let Some((start_edges, end_edges, sb, eb)) = morph_edges(&start.path, &end.path) else { return }; // Fill styles first (before the Offset field, which points past them). let mut fill_buf = Writer::new(); match (&start.fill, &end.fill) { (Some(Paint::Solid(a)), Some(Paint::Solid(b))) => { fill_buf.u8(1); fill_buf.u8(0x00); // solid fill_buf.rgba(*a); fill_buf.rgba(*b); } _ => fill_buf.u8(0), } let mut line_buf = Writer::new(); line_buf.u8(0); // Start and end edges each carry a fill-bits / line-bits header. let mut start_full = Writer::new(); start_full.bits(1, 4); start_full.bits(1, 4); start_full.bytes(&start_edges); let start_full = start_full.into_bytes(); let mut end_full = Writer::new(); end_full.bits(1, 4); end_full.bits(1, 4); end_full.bytes(&end_edges); let end_full = end_full.into_bytes(); // Offset = bytes from after this field to EndEdges. let offset = fill_buf.as_bytes().len() + line_buf.as_bytes().len() + start_full.len(); let mut w = Writer::new(); w.u16(id); write_rect(&mut w, sb); write_rect(&mut w, eb); write_rect(&mut w, sb); write_rect(&mut w, eb); w.bits(0, 6); w.bit(false); // UsesNonScalingStrokes w.bit(false); // UsesScalingStrokes w.u32(offset as u32); w.bytes(fill_buf.as_bytes()); w.bytes(line_buf.as_bytes()); w.bytes(&start_full); w.bytes(&end_full); defs.bytes(&tag(TAG_DEFINE_MORPH_SHAPE2, &w.into_bytes())); } fn write_rect(w: &mut Writer, r: Rect) { let r = if r.is_empty() || !r.min.is_finite() || !r.max.is_finite() { Rect::new(0.0, 0.0, 0.0, 0.0) } else { r }; w.rect(twips(r.min.x), twips(r.max.x), twips(r.min.y), twips(r.max.y)); } /// Parallel edge streams for a morph, or `None` when the two paths don't align. fn morph_edges(start: &Path, end: &Path) -> Option<(Vec, Vec, Rect, Rect)> { if start.cmds.len() != end.cmds.len() { return None; } if !start.cmds.iter().zip(&end.cmds).all(|(a, b)| std::mem::discriminant(a) == std::mem::discriminant(b)) { return None; } let mut sw = Writer::new(); let mut ew = Writer::new(); let mut ps = (0i32, 0i32); let mut pe = (0i32, 0i32); let mut start_s = (0i32, 0i32); let mut start_e = (0i32, 0i32); let mut first = true; for (a, b) in start.cmds.iter().zip(&end.cmds) { match (a, b) { (PathCmd::MoveTo(p), PathCmd::MoveTo(q)) => { let (sx, sy) = (twips(p.x), twips(p.y)); let (ex, ey) = (twips(q.x), twips(q.y)); let nb = signed_bits_of(&[sx, sy, ex, ey]).max(1); morph_move(&mut sw, sx, sy, nb, first); morph_move(&mut ew, ex, ey, nb, false); first = false; ps = (sx, sy); pe = (ex, ey); start_s = ps; start_e = pe; } (PathCmd::LineTo(p), PathCmd::LineTo(q)) => { let (sx, sy) = (twips(p.x), twips(p.y)); let (ex, ey) = (twips(q.x), twips(q.y)); let (sdx, sdy) = (sx - ps.0, sy - ps.1); let (edx, edy) = (ex - pe.0, ey - pe.1); morph_straight(&mut sw, &mut ew, sdx, sdy, edx, edy); ps = (sx, sy); pe = (ex, ey); } (PathCmd::QuadTo(c, p), PathCmd::QuadTo(d, q)) => { let (scx, scy) = (twips(c.x), twips(c.y)); let (sax, say) = (twips(p.x), twips(p.y)); let (ecx, ecy) = (twips(d.x), twips(d.y)); let (eax, eay) = (twips(q.x), twips(q.y)); morph_curve(&mut sw, &mut ew, scx - ps.0, scy - ps.1, sax - scx, say - scy, ecx - pe.0, ecy - pe.1, eax - ecx, eay - ecy); ps = (sax, say); pe = (eax, eay); } (PathCmd::CubicTo(c1, c2, p), PathCmd::CubicTo(d1, d2, q)) => { let s_quads = cubic_quads(ps, c1, c2, p); let e_quads = cubic_quads(pe, d1, d2, q); if s_quads.len() != e_quads.len() { return None; } for (sq, eq) in s_quads.iter().zip(&e_quads) { let (qx, qy) = (sq.control.x.round() as i32, sq.control.y.round() as i32); let (ax, ay) = (sq.end.x.round() as i32, sq.end.y.round() as i32); let (eqx, eqy) = (eq.control.x.round() as i32, eq.control.y.round() as i32); let (eax, eay) = (eq.end.x.round() as i32, eq.end.y.round() as i32); morph_curve(&mut sw, &mut ew, qx - ps.0, qy - ps.1, ax - qx, ay - qy, eqx - pe.0, eqy - pe.1, eax - eqx, eay - eqy); ps = (ax, ay); pe = (eax, eay); } } (PathCmd::Close, PathCmd::Close) => { if ps != start_s || pe != start_e { morph_straight(&mut sw, &mut ew, start_s.0 - ps.0, start_s.1 - ps.1, start_e.0 - pe.0, start_e.1 - pe.1); ps = start_s; pe = start_e; } } _ => return None, } } sw.bits(0, 6); ew.bits(0, 6); Some((sw.into_bytes(), ew.into_bytes(), start.bounds(), end.bounds())) } fn cubic_quads(pen: (i32, i32), c1: &Vec2, c2: &Vec2, p: &Vec2) -> Vec { let mut out = Vec::new(); crate::cubic::cubic_to_quads( Vec2::new(pen.0 as f32, pen.1 as f32), Vec2::new(twips(c1.x) as f32, twips(c1.y) as f32), Vec2::new(twips(c2.x) as f32, twips(c2.y) as f32), Vec2::new(twips(p.x) as f32, twips(p.y) as f32), 0.25, &mut out, ); out } fn morph_move(w: &mut Writer, dx: i32, dy: i32, nb: u32, with_fill: bool) { w.bit(false); // TypeFlag w.bit(false); // StateNewStyles w.bit(false); // StateLineStyle w.bit(false); // StateFillStyle1 w.bit(with_fill); // StateFillStyle0 w.bit(true); // StateMoveTo w.bits(nb, 5); w.sbits(dx, nb); w.sbits(dy, nb); if with_fill { w.bits(1, 1); // FillStyle0 = 1 } } fn morph_straight(sw: &mut Writer, ew: &mut Writer, sdx: i32, sdy: i32, edx: i32, edy: i32) { let nb = signed_bits_of(&[sdx, sdy, edx, edy]).max(2); sw.bit(true); sw.bit(true); sw.bits(nb - 2, 4); sw.bit(true); sw.sbits(sdx, nb); sw.sbits(sdy, nb); ew.bit(true); ew.bit(true); ew.bits(nb - 2, 4); ew.bit(true); ew.sbits(edx, nb); ew.sbits(edy, nb); } #[allow(clippy::too_many_arguments)] fn morph_curve(sw: &mut Writer, ew: &mut Writer, scx: i32, scy: i32, sax: i32, say: i32, ecx: i32, ecy: i32, eax: i32, eay: i32) { let nb = signed_bits_of(&[scx, scy, sax, say, ecx, ecy, eax, eay]).max(2); sw.bit(true); sw.bit(false); sw.bits(nb - 2, 4); sw.sbits(scx, nb); sw.sbits(scy, nb); sw.sbits(sax, nb); sw.sbits(say, nb); ew.bit(true); ew.bit(false); ew.bits(nb - 2, 4); ew.sbits(ecx, nb); ew.sbits(ecy, nb); ew.sbits(eax, nb); ew.sbits(eay, nb); } // ----- sounds --------------------------------------------------------------------------------- fn emit_frame_sounds(doc: &Document, tl: &Timeline, frame: u32, dict: &mut Dict, defs: &mut Writer, body: &mut Writer, report: &mut ExportReport) -> Result<(), String> { for layer in &tl.layers { if layer_skipped(tl, tl.layers.iter().position(|l| l.id == layer.id).unwrap_or(0)) { continue; } for k in &layer.keyframes { let Some(fs) = &k.sound else { continue }; let Some(sound) = doc.sound(fs.sound) else { continue }; if fs.sync == SoundSync::Stream { // A stream sound plays over its keyframe's whole span. if frame >= k.start && frame < k.end() { emit_stream(doc, fs, sound, k, frame, dict, body, report)?; } } else if k.start == frame && let Ok(c) = sound_char(doc, fs.sound, dict, defs, report) { body.bytes(&tag(TAG_START_SOUND, &media::start_sound(c, fs.sync, fs.repeat, fs.looping))); } } } Ok(()) } fn sound_char(doc: &Document, id: SoundId, dict: &mut Dict, defs: &mut Writer, report: &mut ExportReport) -> Result { if let Some(&c) = dict.sounds.get(&id) { return Ok(c); } let prepared = match dict.prepared_sounds.get(&id) { Some(p) => p.clone(), None => { let sound = doc.sound(id).ok_or_else(|| "missing sound".to_string())?; match media::prepare_sound(sound) { Ok(p) => { let p = Arc::new(p); dict.prepared_sounds.insert(id, p.clone()); p } Err(e) => { report.notes.push(e.clone()); return Err(e); } } } }; let c = dict.alloc(); dict.sounds.insert(id, c); let body = media::define_sound(c, &prepared); defs.bytes(&tag(TAG_DEFINE_SOUND, &body)); Ok(c) } #[allow(clippy::too_many_arguments)] fn emit_stream(doc: &Document, fs: &anicraft_doc::FrameSound, sound: &Sound, k: &anicraft_doc::Keyframe, frame: u32, dict: &mut Dict, body: &mut Writer, report: &mut ExportReport) -> Result<(), String> { let prepared = match dict.prepared_sounds.get(&fs.sound) { Some(p) => p.clone(), None => { match media::prepare_sound(sound) { Ok(p) => { let p = Arc::new(p); dict.prepared_sounds.insert(fs.sound, p.clone()); p } Err(e) => { report.notes.push(e); return Ok(()); } } } }; let fps = doc.stage.fps.clamp(1.0, 240.0); let samples_per_frame = (prepared.rate as f32 / fps).round().clamp(1.0, f32::from(u16::MAX)) as u16; let channels = u32::from(prepared.channels); let bytes_per_frame = u32::from(samples_per_frame) * 2 * channels; // The head is declared once, at the stream's first frame. if frame == k.start { body.bytes(&tag(TAG_SOUND_STREAM_HEAD2, &media::sound_stream_head(&prepared, samples_per_frame))); } let offset = u64::from(frame - k.start) * u64::from(bytes_per_frame); let start = (offset.min(prepared.pcm16.len() as u64)) as usize; let end = (start.saturating_add(bytes_per_frame as usize)).min(prepared.pcm16.len()); if end > start { body.bytes(&tag(TAG_SOUND_STREAM_BLOCK, &media::sound_stream_block(&prepared.pcm16[start..end]))); } let _ = report; Ok(()) }