diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e74e883..18c495f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,22 @@ * **Erasing inside symbols**: open a symbol or drawing object (double-click) and the Eraser erases its lines and fills; on the stage it keeps them and the status bar says how. * Fix: the curve fitter could send a handle far off on a tiny, nearly closed stretch. +* **Surviving graphics card failures, and filters in the Motion Editor** (ADR 0092, M3). + * **The stage keeps drawing when the graphics card fails mid-session**: the CPU takes it over + at once, the status bar says so, and the graphics card is tried again after 3, 15, 60 and + 300 seconds (sooner when the window is resized). Preferences › Stage says why. + * **A graphics driver error no longer closes AniCraft** (#255: `Surface::configure` "Failed to + wait for GPU to come idle"): the error goes to the log, unsaved work is autosaved at once, + and a surface that fails is reconfigured, then made anew. If the window loses its graphics + device, AniCraft saves the work, reopens the window a safer way and offers the work back; + the next three starts try that safer way first (#207). + * **Filters animate in the Motion Editor**: each filter of a movie clip in a motion tween lists + its numbers (Blur X/Y, Strength, Angle, Distance, Adjust Color's four) under its name, with + curves, keys, eases and retiming like the other properties. Changing a filter in Properties + with the playhead inside the tween keys it; reordering or removing filters takes their keys + along. Headless: `motion.set_key {"property": "filter.0.blur_x", …}`; files keep the tracks + under `filter_tracks`, so older builds still open them. + * **Shape armatures, second slice: painted weights and reshaping** (ADR 0090, M7). * The **Bind** tool's **Paint Weights** (Properties › Bone) brushes a bone's influence onto the points of its shape: **Add**, **Subtract** or **Smooth**, with a size (`[` and `]`) diff --git a/crates/doc/src/filter.rs b/crates/doc/src/filter.rs index ed5a4d9e..635c6988 100644 --- a/crates/doc/src/filter.rs +++ b/crates/doc/src/filter.rs @@ -401,6 +401,187 @@ impl Filter { } } +/// A number of a filter a motion tween can animate (ADR 0092), in the units the Motion Editor +/// and the Filters panel show: pixels, percent (strength) and degrees. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum FilterParam { + BlurX, + BlurY, + /// Percent (100 = the filter's full strength). + Strength, + /// Degrees, clockwise from the right; not wrapped in keys, so 0 → 720 turns twice. + Angle, + Distance, + /// Adjust Color's four. + Brightness, + Contrast, + Saturation, + Hue, +} + +impl FilterParam { + pub const ALL: [FilterParam; 9] = [ + FilterParam::BlurX, + FilterParam::BlurY, + FilterParam::Strength, + FilterParam::Angle, + FilterParam::Distance, + FilterParam::Brightness, + FilterParam::Contrast, + FilterParam::Saturation, + FilterParam::Hue, + ]; + + /// The name in files and commands (`blur_x`, `strength`…), as the filter's own field. + pub fn key(self) -> &'static str { + match self { + FilterParam::BlurX => "blur_x", + FilterParam::BlurY => "blur_y", + FilterParam::Strength => "strength", + FilterParam::Angle => "angle", + FilterParam::Distance => "distance", + FilterParam::Brightness => "brightness", + FilterParam::Contrast => "contrast", + FilterParam::Saturation => "saturation", + FilterParam::Hue => "hue", + } + } + + pub fn from_key(s: &str) -> Option { + let s = s.trim().to_ascii_lowercase().replace([' ', '-'], "_"); + let s = match s.as_str() { + "blurx" => "blur_x", + "blury" => "blur_y", + other => other, + }; + FilterParam::ALL.into_iter().find(|p| p.key() == s) + } + + pub fn label(self) -> &'static str { + match self { + FilterParam::BlurX => "Blur X", + FilterParam::BlurY => "Blur Y", + FilterParam::Strength => "Strength", + FilterParam::Angle => "Angle", + FilterParam::Distance => "Distance", + FilterParam::Brightness => "Brightness", + FilterParam::Contrast => "Contrast", + FilterParam::Saturation => "Saturation", + FilterParam::Hue => "Hue", + } + } + + pub fn unit(self) -> &'static str { + match self { + FilterParam::BlurX | FilterParam::BlurY | FilterParam::Distance => "px", + FilterParam::Strength => "%", + FilterParam::Angle | FilterParam::Hue => "°", + FilterParam::Brightness | FilterParam::Contrast | FilterParam::Saturation => "", + } + } + + /// Values a key may hold (the filter itself then brings the value into its own range). + pub fn range(self) -> std::ops::RangeInclusive { + match self { + FilterParam::BlurX | FilterParam::BlurY => 0.0..=MAX_BLUR, + FilterParam::Strength => 0.0..=1000.0, + FilterParam::Angle => -100_000.0..=100_000.0, + FilterParam::Distance => -1000.0..=1000.0, + FilterParam::Brightness | FilterParam::Contrast | FilterParam::Saturation => -100.0..=100.0, + FilterParam::Hue => -180.0..=180.0, + } + } + + fn index(self) -> usize { + FilterParam::ALL.iter().position(|p| *p == self).unwrap_or(0) + } +} + +/// How many [`FilterParam`]s there are. +pub const FILTER_PARAMS: usize = 9; + +impl Filter { + /// The numbers of this filter a motion tween can animate, in the Filters panel's order. + pub fn params(&self) -> &'static [FilterParam] { + use FilterParam::*; + match self { + Filter::Blur { .. } => &[BlurX, BlurY], + Filter::Glow { .. } => &[BlurX, BlurY, Strength], + Filter::DropShadow { .. } | Filter::Bevel { .. } | Filter::GradientGlow { .. } | Filter::GradientBevel { .. } => &[BlurX, BlurY, Strength, Angle, Distance], + Filter::AdjustColor { .. } => &[Brightness, Contrast, Saturation, Hue], + } + } + + /// The filter's value of `p` in the Motion Editor's units; `None` when it has no such number. + pub fn param(&self, p: FilterParam) -> Option { + if !self.params().contains(&p) { + return None; + } + let mut out = None; + self.visit(p, |v, scale| out = Some(*v * scale)); + out + } + + /// Sets `p` to `v` (Motion Editor units, brought into the filter's range when drawn); false + /// when the filter has no such number. + pub fn set_param(&mut self, p: FilterParam, v: f32) -> bool { + if !self.params().contains(&p) || !v.is_finite() { + return false; + } + let mut done = false; + self.visit_mut(p, |x, scale| { + *x = v / scale; + done = true; + }); + done + } + + /// The field holding `p` and the factor to the Motion Editor's units (strength in percent). + fn visit(&self, p: FilterParam, f: impl FnOnce(&f32, f32)) { + let mut c = self.clone(); + c.visit_mut(p, |x, s| f(x, s)); + } + + fn visit_mut(&mut self, p: FilterParam, f: impl FnOnce(&mut f32, f32)) { + use FilterParam as P; + let field: Option<(&mut f32, f32)> = match (self, p) { + (Filter::Blur { blur_x, .. }, P::BlurX) => Some((blur_x, 1.0)), + (Filter::Blur { blur_y, .. }, P::BlurY) => Some((blur_y, 1.0)), + (Filter::DropShadow { blur_x, .. } | Filter::Glow { blur_x, .. } | Filter::Bevel { blur_x, .. } | Filter::GradientGlow { blur_x, .. } | Filter::GradientBevel { blur_x, .. }, P::BlurX) => Some((blur_x, 1.0)), + (Filter::DropShadow { blur_y, .. } | Filter::Glow { blur_y, .. } | Filter::Bevel { blur_y, .. } | Filter::GradientGlow { blur_y, .. } | Filter::GradientBevel { blur_y, .. }, P::BlurY) => Some((blur_y, 1.0)), + (Filter::DropShadow { strength, .. } | Filter::Glow { strength, .. } | Filter::Bevel { strength, .. } | Filter::GradientGlow { strength, .. } | Filter::GradientBevel { strength, .. }, P::Strength) => Some((strength, 100.0)), + (Filter::DropShadow { angle, .. } | Filter::Bevel { angle, .. } | Filter::GradientGlow { angle, .. } | Filter::GradientBevel { angle, .. }, P::Angle) => Some((angle, 1.0)), + (Filter::DropShadow { distance, .. } | Filter::Bevel { distance, .. } | Filter::GradientGlow { distance, .. } | Filter::GradientBevel { distance, .. }, P::Distance) => Some((distance, 1.0)), + (Filter::AdjustColor { brightness, .. }, P::Brightness) => Some((brightness, 1.0)), + (Filter::AdjustColor { contrast, .. }, P::Contrast) => Some((contrast, 1.0)), + (Filter::AdjustColor { saturation, .. }, P::Saturation) => Some((saturation, 1.0)), + (Filter::AdjustColor { hue, .. }, P::Hue) => Some((hue, 1.0)), + _ => None, + }; + if let Some((x, s)) = field { + f(x, s); + } + } +} + +/// A filter's number addressed in an instance's list (ADR 0092): the filter's place (0 is the +/// first, applied first) and the number. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct FilterProp { + pub slot: u8, + pub param: FilterParam, +} + +/// Most filter slots a motion tween addresses (an instance holds at most 16 filters). +pub const MAX_FILTER_SLOTS: u8 = 16; + +impl FilterProp { + /// Its place among the filter properties: by slot, then in [`FilterParam::ALL`] order. + pub fn index(self) -> usize { + usize::from(self.slot) * FILTER_PARAMS + self.param.index() + } +} + fn yes() -> bool { true } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 84caf250..920e2919 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -34,13 +34,13 @@ pub mod templates; pub mod sound; pub mod swatch; -pub use filter::{Filter, FilterEntry, FilterSide, active as active_filters, any_active as any_active_filter, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; +pub use filter::{FILTER_PARAMS, Filter, FilterEntry, FilterParam, FilterProp, FilterSide, MAX_FILTER_SLOTS, active as active_filters, any_active as any_active_filter, pairs_up as filters_pair_up, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_decode, base64_encode, decode_png, image_to_png}; pub use easing::{CustomEase, EaseDir, EaseFamily, EasePoint, Easing, Handle, MAX_EASE_NAME, MAX_EASE_POINTS, MAX_EASE_SAMPLES, MAX_EASE_Y, MAX_SAVED_EASES, SampledEase, SavedEase, ease_name}; pub use color_effect::{ADVANCED_ADD, ADVANCED_MUL, ColorEffect, ColorStyle, ColorTransform}; pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre}; pub use library::{FolderId, LibraryEntry, LibraryFolder, LibraryItem, LibraryTree, NameError}; -pub use motion::{KeyRef, MotionTween, OnPath, PROPERTIES, Pin, PinError, Property, PropertyKey, Props, Track, motion_path}; +pub use motion::{KeyRef, MotionTween, OnPath, PROPERTIES, Pin, PinError, Property, PropertyKey, Props, Track, filter_properties, motion_path, own_value}; pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, SoundId, SoundSync}; pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; pub use stroke_style::{Cap, Dash, DashKind, Join, StrokeStyle}; diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index 096bebd5..02dbdd76 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -21,7 +21,8 @@ //! time the whole path when only the ends are pinned. Anchors that aren't pinned shape the path //! only. -use crate::{ColorEffect, ColorStyle, ColorTransform, Element, ElementId, Easing, Rgba}; +use crate::{ColorEffect, ColorStyle, ColorTransform, Element, ElementId, ElementKind, Easing, FilterParam, FilterProp, MAX_FILTER_SLOTS, Rgba}; +use std::borrow::Cow; use anicraft_geom::edit::ANCHOR; use anicraft_geom::walk::CurveWalk; use anicraft_geom::{Affine, Decomposed, Path, PathCmd, Vec2}; @@ -39,8 +40,9 @@ pub const MAX_PATH_SEGMENTS: usize = 1_000; /// A property a motion tween animates. Values are in the units the Motion Editor shows: /// pixels, percent, degrees, and 0–255 for colour channels and offsets (as Animate shows them). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] +/// In files and commands a property is its [`Property::key`]: `x`, `scale_x`, `alpha`…, and a +/// filter's number `filter..` (`filter.0.blur_x`, ADR 0092). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Property { /// Registration point, stage pixels. X, @@ -70,9 +72,24 @@ pub enum Property { GreenOffset, BlueOffset, AlphaOffset, + /// A number of a filter on the target (ADR 0092), by the filter's place in its list. + Filter(FilterProp), } -/// How many properties there are. +impl Serialize for Property { + fn serialize(&self, s: S) -> Result { + s.serialize_str(&self.key()) + } +} + +impl<'de> Deserialize<'de> for Property { + fn deserialize>(d: D) -> Result { + let k = Cow::::deserialize(d)?; + Property::from_key(&k).ok_or_else(|| serde::de::Error::custom(format!("unknown motion tween property '{k}'"))) + } +} + +/// How many properties there are (besides the filters' numbers). pub const PROPERTIES: usize = 20; impl Property { @@ -111,9 +128,9 @@ impl Property { Property::AlphaOffset, ]; - /// The name used in files and commands (`x`, `scale_x`, `alpha`…). - pub fn key(self) -> &'static str { - match self { + /// The name used in files and commands (`x`, `scale_x`, `alpha`…, `filter.0.blur_x`). + pub fn key(self) -> Cow<'static, str> { + Cow::Borrowed(match self { Property::X => "x", Property::Y => "y", Property::ScaleX => "scale_x", @@ -134,9 +151,23 @@ impl Property { Property::GreenOffset => "green_offset", Property::BlueOffset => "blue_offset", Property::AlphaOffset => "alpha_offset", + Property::Filter(f) => return Cow::Owned(format!("filter.{}.{}", f.slot, f.param.key())), + }) + } + + /// The filter number this is, if it is one. + pub fn filter(self) -> Option { + match self { + Property::Filter(f) => Some(f), + _ => None, } } + pub fn is_filter(self) -> bool { + self.filter().is_some() + } + + /// The label (for a filter's number, the number's: the Motion Editor shows the filter above). pub fn label(self) -> &'static str { match self { Property::X => "X", @@ -159,11 +190,13 @@ impl Property { Property::GreenOffset => "Green offset", Property::BlueOffset => "Blue offset", Property::AlphaOffset => "Alpha offset", + Property::Filter(f) => f.param.label(), } } pub fn unit(self) -> &'static str { match self { + Property::Filter(f) => f.param.unit(), Property::X | Property::Y => "px", Property::ScaleX | Property::ScaleY | Property::Alpha | Property::Brightness | Property::Tint => "%", Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier => "%", @@ -172,8 +205,11 @@ impl Property { } } - /// The Motion Editor's groups: Position, Transform, Colour effect. + /// The Motion Editor's groups: Position, Transform, Colour effect, Filters. pub fn group(self) -> &'static str { + if self.is_filter() { + return "Filters"; + } match self.style() { None if matches!(self, Property::X | Property::Y) => "Position", None => "Transform", @@ -181,9 +217,11 @@ impl Property { } } - /// The colour effect style a colour property belongs to (`None` for position and transform). + /// The colour effect style a colour property belongs to (`None` for position, transform + /// and filters). pub fn style(self) -> Option { match self { + Property::Filter(_) => None, Property::X | Property::Y | Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => None, Property::Alpha => Some(ColorStyle::Alpha), Property::Brightness => Some(ColorStyle::Brightness), @@ -193,6 +231,12 @@ impl Property { } pub fn from_key(s: &str) -> Option { + // `filter..`: a filter's number, by the filter's place in the list. + if let Some(rest) = s.trim().strip_prefix("filter.") { + let (slot, param) = rest.split_once('.')?; + let slot = slot.trim().parse::().ok().filter(|n| *n < MAX_FILTER_SLOTS)?; + return Some(Property::Filter(FilterProp { slot, param: FilterParam::from_key(param)? })); + } let s = s.trim().to_ascii_lowercase().replace([' ', '-'], "_"); let s = match s.as_str() { "scalex" => "scale_x", @@ -208,6 +252,7 @@ impl Property { /// Values a key may hold (commands reject others; files are clamped into it). pub fn range(self) -> std::ops::RangeInclusive { match self { + Property::Filter(f) => f.param.range(), Property::X | Property::Y => -1_000_000.0..=1_000_000.0, Property::ScaleX | Property::ScaleY => -1_000_000.0..=1_000_000.0, Property::Rotation => -100_000.0..=100_000.0, @@ -219,12 +264,18 @@ impl Property { } } - fn index(self) -> usize { - Property::ALL.iter().position(|p| *p == self).unwrap_or(0) + /// Its place in a tween's track list: [`Property::ALL`]'s order, then the filters' numbers + /// by slot. Only the first [`PROPERTIES`] index into [`Props`]. + pub(crate) fn index(self) -> usize { + match self { + Property::Filter(f) => PROPERTIES + f.index(), + p => Property::ALL.iter().position(|q| *q == p).unwrap_or(0), + } } - fn is_transform(self) -> bool { - self.style().is_none() + /// Position and transform (the properties the element's matrix holds). + pub fn is_transform(self) -> bool { + self.style().is_none() && !self.is_filter() } fn clamp(self, v: f32) -> f32 { @@ -314,6 +365,33 @@ impl Props { } } +/// The object's own value of `p`: its transform's and colour effect's, or a filter's number +/// (`None` when it has no filter there with that number, ADR 0092). +pub fn own_value(el: &Element, p: Property) -> Option { + match p { + Property::Filter(f) => filter_entry(el, f.slot).and_then(|e| e.filter.param(f.param)), + p => Some(Props::of(el).get(p)), + } +} + +fn filter_entry(el: &Element, slot: u8) -> Option<&crate::FilterEntry> { + match &el.kind { + ElementKind::Symbol { filters, .. } => filters.get(usize::from(slot)), + _ => None, + } +} + +/// Every filter number the object has, in its list's order (the Motion Editor's filter rows). +pub fn filter_properties(el: &Element) -> Vec { + let ElementKind::Symbol { filters, .. } = &el.kind else { return Vec::new() }; + filters + .iter() + .take(usize::from(MAX_FILTER_SLOTS)) + .enumerate() + .flat_map(|(slot, e)| e.filter.params().iter().map(move |¶m| Property::Filter(FilterProp { slot: slot as u8, param }))) + .collect() +} + /// A property keyframe. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PropertyKey { @@ -436,28 +514,60 @@ pub enum PinError { } /// A motion tween on a keyframe span (see the module docs). +/// +/// In files the filters' tracks are kept apart, under `filter_tracks` (ADR 0092): a build from +/// before them ignores that key and opens the file, the filters then holding still. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(from = "TweenFile", into = "TweenFile")] pub struct MotionTween { /// The object it animates. When no element has this id but the keyframe holds exactly one /// element, that one is the target (so edits that replace the object keep its motion). pub target: ElementId, - /// At most one per property, in [`Property::ALL`] order. - #[serde(default, skip_serializing_if = "Vec::is_empty")] + /// At most one per property, in [`Property::ALL`] order, then the filters' numbers by slot. pub tracks: Vec, /// The motion path (ADR 0030), in the layer's space: a move and cubics (see /// [`motion_path`]). Its ends are the start and end positions; the X/Y curves give the /// timing along it. - #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option, /// Orient to path: the object turns as the path turns (relative to its turn at the start). - #[serde(default, skip_serializing_if = "is_false")] pub orient: bool, /// Anchors between the ends pinned to frames (ADR 0049), by frame; both frames and anchors /// increase. Files from before pins have none: only the ends are pinned. - #[serde(default, skip_serializing_if = "Vec::is_empty")] pub pins: Vec, } +/// A [`MotionTween`] as files hold it. +#[derive(Clone, Serialize, Deserialize)] +struct TweenFile { + target: ElementId, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + tracks: Vec, + /// The filters' tracks (ADR 0092). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + filter_tracks: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + path: Option, + #[serde(default, skip_serializing_if = "is_false")] + orient: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pins: Vec, +} + +impl From for MotionTween { + fn from(f: TweenFile) -> MotionTween { + let mut tracks = f.tracks; + tracks.extend(f.filter_tracks); + MotionTween { target: f.target, tracks, path: f.path, orient: f.orient, pins: f.pins } + } +} + +impl From for TweenFile { + fn from(m: MotionTween) -> TweenFile { + let (filter_tracks, tracks) = m.tracks.into_iter().partition(|t| t.property.is_filter()); + TweenFile { target: m.target, tracks, filter_tracks, path: m.path, orient: m.orient, pins: m.pins } + } +} + fn is_false(b: &bool) -> bool { !*b } @@ -1013,6 +1123,17 @@ impl MotionTween { if self.tracks.is_empty() && self.path.is_none() { return el; } + // The filters' numbers (ADR 0092): a track whose filter isn't there, or has no such + // number, does nothing (its filter was replaced by another kind). + if let ElementKind::Symbol { filters, .. } = &mut el.kind { + for t in self.tracks.iter().filter(|t| t.property.is_filter()) { + if let (Some(f), Some(v)) = (t.property.filter(), t.value_at(frame)) + && let Some(e) = filters.get_mut(usize::from(f.slot)) + { + e.filter.set_param(f.param, v); + } + } + } let base_props = Props::of(base); let mut props = self.props_at(&base_props, frame); let on_path = self.on_path(&base_props); @@ -1031,7 +1152,7 @@ impl MotionTween { } } // Colour: the styles keyed here and the target's own, composed (ADR 0056). - if self.tracks.iter().any(|t| !t.property.is_transform()) { + if self.tracks.iter().any(|t| t.property.style().is_some()) { el.color = props.color_effect(&self.colour_styles(&base.color)); } el @@ -1061,8 +1182,8 @@ impl MotionTween { if frame > 0 { keys.push(PropertyKey { frame: 0, value: p.clamp(base), ease: Easing::Linear }); } - let at = Property::ALL.iter().position(|x| *x == p).unwrap_or(0); - let pos = self.tracks.partition_point(|t| Property::ALL.iter().position(|x| *x == t.property).unwrap_or(0) < at); + let at = p.index(); + let pos = self.tracks.partition_point(|t| t.property.index() < at); self.tracks.insert(pos, Track { property: p, keys }); } if let Some(t) = self.track_mut(p) { @@ -1152,6 +1273,24 @@ impl MotionTween { tail } + /// The target's filter list changed shape (ADR 0092): `map[old]` is where the filter that + /// was at slot `old` is now (`None`: it went). Its tracks follow it; the tracks of filters + /// that went go too. + pub fn remap_filters(&mut self, map: &[Option]) { + self.tracks.retain_mut(|t| { + let Some(f) = t.property.filter() else { return true }; + match map.get(usize::from(f.slot)).copied().flatten().and_then(|n| u8::try_from(n).ok()).filter(|n| *n < MAX_FILTER_SLOTS) { + Some(slot) => { + t.property = Property::Filter(FilterProp { slot, ..f }); + true + } + None => false, + } + }); + self.tracks.sort_by_key(|t| t.property.index()); + self.tracks.dedup_by_key(|t| t.property); + } + /// Whether loading must repair it (unsorted or duplicate keys, values out of range, /// duplicate or empty tracks). pub fn is_sane(&self) -> bool { @@ -1319,7 +1458,7 @@ mod tests { #[test] fn property_keys_round_trip() { for p in Property::ALL { - assert_eq!(Property::from_key(p.key()), Some(p)); + assert_eq!(Property::from_key(&p.key()), Some(p)); assert!(!p.label().is_empty() && (!p.unit().is_empty() || p.range() == (0.0..=255.0) || p.range() == (-255.0..=255.0)) && !p.group().is_empty()); } assert_eq!(Property::from_key("Scale X"), Some(Property::ScaleX)); @@ -1805,4 +1944,138 @@ mod tests { m.sanitize(); assert!(m.pins.is_empty()); } + + /// A movie clip instance with `filters`, at (x, 0). + fn clip(x: f32, filters: Vec) -> Element { + Element { + kind: ElementKind::Symbol { symbol: crate::SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: filters.into_iter().map(crate::FilterEntry::from).collect(), events: Vec::new() }, + ..el(1, x, 0.0) + } + } + + fn blur_x(e: &Element, slot: usize) -> Option { + match &e.kind { + ElementKind::Symbol { filters, .. } => filters.get(slot).and_then(|f| f.filter.param(FilterParam::BlurX)), + _ => None, + } + } + + fn fp(slot: u8, param: FilterParam) -> Property { + Property::Filter(FilterProp { slot, param }) + } + + /// ADR 0092: a filter's number tweens like any property, eased per segment; untracked + /// numbers and the other filters keep the object's own. + #[test] + fn a_blur_tweens_on_its_own_curve() { + let blur = crate::Filter::new("blur").unwrap(); + let shadow = crate::Filter::new("drop_shadow").unwrap(); + let base = clip(0.0, vec![shadow.clone(), blur]); + let mut m = MotionTween::new(ElementId(1)); + m.set_key(fp(1, FilterParam::BlurX), 10, 25.0, 5.0); + assert_eq!(m.track(fp(1, FilterParam::BlurX)).map(|t| t.keys.len()), Some(2), "the first key pins the span's start to the object's own value"); + assert_eq!(blur_x(&m.apply(&base, 0.0), 1), Some(5.0)); + assert_eq!(blur_x(&m.apply(&base, 4.0), 1), Some(13.0)); + assert_eq!(blur_x(&m.apply(&base, 10.0), 1), Some(25.0)); + assert_eq!(blur_x(&m.apply(&base, 4.0), 0), shadow.param(FilterParam::BlurX), "the shadow keeps its own blur"); + let at4 = m.apply(&base, 4.0); + assert_eq!((at4.transform, at4.color), (base.transform, base.color), "a filter-only tween keeps the transform and colour bit for bit"); + // Eased: CubicOut on 0..10. + if let Some(k) = m.track_mut(fp(1, FilterParam::BlurX)).and_then(|t| t.keys.first_mut()) { + k.ease = Easing::CubicOut; + } + let want = 5.0 + 20.0 * Easing::CubicOut.apply(0.4); + assert!((blur_x(&m.apply(&base, 4.0), 1).unwrap() - want).abs() < 1e-4); + // Strength is shown in percent; the filter holds a multiplier. + m.set_key(fp(0, FilterParam::Strength), 10, 300.0, 100.0); + let ElementKind::Symbol { filters, .. } = &m.apply(&base, 5.0).kind else { panic!() }; + let crate::Filter::DropShadow { strength, .. } = filters[0].filter else { panic!() }; + assert!((strength - 2.0).abs() < 1e-5, "{strength}"); + // A track whose filter isn't there (or is another kind) does nothing, and never panics. + let plain = clip(0.0, vec![crate::Filter::new("adjust_color").unwrap()]); + assert_eq!(m.apply(&plain, 5.0).kind, plain.kind); + let shape = el(1, 0.0, 0.0); + assert_eq!(m.apply(&shape, 5.0), shape); + assert_eq!(own_value(&base, fp(1, FilterParam::BlurX)), Some(5.0)); + assert_eq!(own_value(&base, fp(1, FilterParam::Angle)), None, "a blur has no angle"); + assert_eq!(own_value(&base, fp(5, FilterParam::BlurX)), None); + assert_eq!(filter_properties(&base).len(), 5 + 2); + } + + /// In files a filter's track sits under `filter_tracks`, addressed `filter..`, + /// so a build from before them still opens the file (the filters hold still there). + #[test] + fn filter_tracks_round_trip_apart_from_the_others() { + let mut m = MotionTween::new(ElementId(1)); + m.set_key(Property::X, 10, 50.0, 0.0); + m.set_key(fp(2, FilterParam::Hue), 10, 90.0, 0.0); + let v = serde_json::to_value(&m).unwrap(); + assert_eq!(v["tracks"].as_array().map(Vec::len), Some(1)); + assert_eq!(v["tracks"][0]["property"], "x"); + assert_eq!(v["filter_tracks"][0]["property"], "filter.2.hue"); + let back: MotionTween = serde_json::from_value(v).unwrap(); + assert_eq!(back, m); + // Without filter tracks the file is exactly as before. + let mut plain = MotionTween::new(ElementId(1)); + plain.set_key(Property::X, 10, 50.0, 0.0); + assert!(serde_json::to_value(&plain).unwrap().get("filter_tracks").is_none()); + // Keys parse and print the same; nonsense is refused. + for k in ["filter.0.blur_x", "filter.15.distance", "filter.3.strength"] { + assert_eq!(Property::from_key(k).map(Property::key).as_deref(), Some(k)); + } + for k in ["filter.16.blur_x", "filter.0.sparkle", "filter.x.blur_x", "filter.", "filter.0"] { + assert_eq!(Property::from_key(k), None, "{k}"); + } + assert!(serde_json::from_str::(r#"{"target":1,"tracks":[{"property":"filter.99.blur_x","keys":[]}]}"#).is_err()); + assert!(!fp(0, FilterParam::BlurX).is_transform() && fp(0, FilterParam::BlurX).style().is_none()); + // Ordered after the twenty, by slot. + assert!(fp(0, FilterParam::Hue).index() > Property::AlphaOffset.index() && fp(1, FilterParam::BlurX).index() > fp(0, FilterParam::Hue).index()); + } + + /// Tracks follow their filter when the list is reordered, and go with it. + #[test] + fn filter_tracks_follow_their_filter() { + let mut m = MotionTween::new(ElementId(1)); + m.set_key(fp(0, FilterParam::BlurX), 4, 10.0, 0.0); + m.set_key(fp(1, FilterParam::Strength), 4, 10.0, 0.0); + m.set_key(fp(2, FilterParam::Hue), 4, 10.0, 0.0); + // 0 → 2, 1 gone, 2 → 0. + m.remap_filters(&[Some(2), None, Some(0)]); + let props: Vec = m.tracks.iter().map(|t| t.property).collect(); + assert_eq!(props, vec![fp(0, FilterParam::Hue), fp(2, FilterParam::BlurX)]); + assert!(m.is_sane()); + } + + /// Retiming and splitting treat filter keys as any other. + #[test] + fn filter_keys_retime_split_and_join() { + let base = clip(0.0, vec![crate::Filter::new("blur").unwrap()]); + let mut m = MotionTween::new(ElementId(1)); + m.set_key(fp(0, FilterParam::BlurX), 10, 45.0, 5.0); + m.set_key(Property::X, 20, 100.0, 0.0); + let (by, now) = m.move_keys(&[(fp(0, FilterParam::BlurX), 10)], 4, 20); + assert_eq!((by, now), (4, vec![(fp(0, FilterParam::BlurX), 14)])); + let mut s = m.clone(); + s.stretch(21, 41); + assert_eq!(s.track(fp(0, FilterParam::BlurX)).map(|t| t.keys.iter().map(|k| k.frame).collect::>()), Some(vec![0, 28])); + // Split, then join: the same motion on every frame. + let props = Props::of(&base); + let tail = m.split_at(&props, 7); + let tail_base = m.apply(&base, 7.0); + let j = m.join(&base, 7, &tail, &tail_base).expect("joins"); + for f in 0..=20 { + assert_eq!(blur_x(&j.apply(&base, f as f32), 0), blur_x(&m.apply(&base, f as f32), 0), "frame {f}"); + } + // Two tweens joined anew (not one split): each frame keeps its blur. + let mut a = MotionTween::new(ElementId(1)); + a.set_key(fp(0, FilterParam::BlurX), 9, 30.0, 5.0); + let b_base = clip(0.0, vec![crate::Filter::Blur { blur_x: 2.0, blur_y: 5.0, quality: 1 }]); + let b = MotionTween::new(ElementId(1)); + let j = a.join(&base, 10, &b, &b_base).expect("joins"); + for f in 0..10 { + assert!((blur_x(&j.apply(&base, f as f32), 0).unwrap() - blur_x(&a.apply(&base, f as f32), 0).unwrap()).abs() < 1e-4, "frame {f}"); + } + assert_eq!(blur_x(&j.apply(&base, 12.0), 0), Some(2.0), "the next span's own blur"); + assert!(j.is_sane()); + } } diff --git a/crates/doc/src/motion/retime.rs b/crates/doc/src/motion/retime.rs index 6f44d2c5..d5f0dd7c 100644 --- a/crates/doc/src/motion/retime.rs +++ b/crates/doc/src/motion/retime.rs @@ -3,7 +3,7 @@ //! //! Frames are offsets into the span, as everywhere in a [`MotionTween`]. -use super::{MotionTween, Pin, Property, PropertyKey, Props, Track}; +use super::{MotionTween, Pin, Property, PropertyKey, Props, Track, own_value}; use crate::{Easing, Element}; /// A property key picked for retiming: its property and its frame (offset into the span). @@ -162,12 +162,21 @@ impl MotionTween { if self.path.is_some() || next.path.is_some() || frames == 0 { return None; } - let pb = Props::of(next_base); let last = frames - 1; let mut tracks = Vec::new(); - for p in Property::ALL { + // Every property, and the filters' numbers both objects have (ADR 0092; a filter only + // one of them has can't be joined, and its track goes). + let mut props: Vec = Property::ALL.to_vec(); + for t in self.tracks.iter().chain(&next.tracks).filter(|t| t.property.is_filter()) { + if !props.contains(&t.property) && own_value(base, t.property).is_some() && own_value(next_base, t.property).is_some() { + props.push(t.property); + } + } + props.sort_by_key(|p| p.index()); + for p in props { let (ta, tb) = (self.track(p), next.track(p)); - if ta.is_none() && tb.is_none() && (pa.get(p) - pb.get(p)).abs() <= SAME { + let (va, vb) = (own_value(base, p).unwrap_or(0.0), own_value(next_base, p).unwrap_or(0.0)); + if ta.is_none() && tb.is_none() && (va - vb).abs() <= SAME { continue; } // This span's part: its keys before the cut, and its value on its last frame when @@ -179,18 +188,18 @@ impl MotionTween { if (v.is_empty() || runs_on) && t.key_at(last).is_none() { let at = if v.is_empty() { 0 } else { last }; let ease = t.segment_at(at).and_then(|i| t.keys.get(i)).map_or(Easing::Linear, |k| k.ease.clone()); - v.push(PropertyKey { frame: at, value: t.value_at(at as f32).unwrap_or(pa.get(p)), ease }); + v.push(PropertyKey { frame: at, value: t.value_at(at as f32).unwrap_or(va), ease }); } v } - None => vec![PropertyKey { frame: 0, value: pa.get(p), ease: Easing::Linear }], + None => vec![PropertyKey { frame: 0, value: va, ease: Easing::Linear }], }; - let end = keys.last().map_or(pa.get(p), |k| k.value); + let end = keys.last().map_or(va, |k| k.value); // The next span's part, after the cut. Its rotation turns on from where this one // ended (the same look, whole turns added), so the curve doesn't spin back. let mut after: Vec = match tb { Some(t) => t.keys.iter().map(|k| PropertyKey { frame: k.frame.saturating_add(frames), ..k.clone() }).collect(), - None => vec![PropertyKey { frame: frames, value: pb.get(p), ease: Easing::Linear }], + None => vec![PropertyKey { frame: frames, value: vb, ease: Easing::Linear }], }; if p == Property::Rotation && let Some(first) = after.first() diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index afb9177b..0c294c86 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -7,6 +7,10 @@ //! [`finish_edit`] turns whatever changed in its transform or colour effect into property keys //! and puts the base object back (with any other change, a new fill say, kept). //! +//! Filters (ADR 0092): a filter's numbers tween as properties too, addressed by the filter's place +//! (`filter.0.blur_x`). An edit of a filter's number at the playhead keys it there; an edit that +//! reorders, removes or adds filters takes the tracks along with their filters. +//! //! On a motion path, moving the object at a frame pins the path there (ADR 0049): the anchor //! pinned to that frame moves (an end, at the first or last position key), or a new anchor is //! added where the object is, pinned to the frame, and moved; after the last position key the @@ -15,7 +19,7 @@ use crate::cmds_timeline::target; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{Element, ElementId, Keyframe, Layer, LayerId, LayerKind, MotionTween, Pin, PinError, Property, Props}; +use anicraft_doc::{Element, ElementId, ElementKind, FilterEntry, Keyframe, Layer, LayerId, LayerKind, MotionTween, Pin, PinError, Property, Props, filter_properties, own_value}; use anicraft_geom::{Affine, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -23,7 +27,7 @@ use std::sync::Arc; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("motion.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255), value (px, %, °), frame?, layer?} (colour properties of several styles compose into Advanced, ADR 0056)", true, set_key as crate::RunFn), + c("motion.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255)|filter.. (a number of the object's filter at that place, 0 the first; ADR 0092), value (px, %, °), frame?, layer?} (colour properties of several styles compose into Advanced, ADR 0056)", true, set_key as crate::RunFn), c("motion.remove_key", "Remove Property Keyframe", "", None, "{property? (default: every property), frame?, layer?}", true, remove_key), c("motion.set_ease", "Property Ease", "", None, "{easing (as timeline.set_easing takes it, saved eases too), property? (default: every property), frame? (inside the segment), layer?}", true, set_ease), c("motion.info", "Motion Tween", "", None, "{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path, its anchors pinned to frames (pins) and where the object is", false, info), @@ -120,9 +124,13 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { m.set_key(p, e.offset, v, base_props.get(p)); } } - let tracks_xf = m.tracks.iter().any(|t| t.property.style().is_none()); + let tracks_xf = m.tracks.iter().any(|t| t.property.is_transform()); let tracks_color = m.tracks.iter().any(|t| t.property.style().is_some()); + let filters = key_filters(m, &e, &after); let mut base = after; + if let (Some(f), ElementKind::Symbol { filters: slot, .. }) = (filters, &mut base.kind) { + *slot = f; + } // Exact where nothing is keyed on the first frame: the edited object is the new base. base.transform = match (base_xf, e.offset == 0 && !tracks_xf) { (true, true) => base.transform, @@ -140,6 +148,67 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { } } +/// The filters of an edited target (ADR 0092). The command saw them as they look at the +/// playhead (`e.before`) and left them as `after` has them. When the list kept its shape (the +/// same kinds in the same order), each number it changed becomes a key at the playhead (on the +/// span's first frame, an untracked number changes the object's own), and the tracked numbers +/// keep the object's own values underneath. When the shape changed (filters reordered, removed +/// or added), each filter is found again by what it holds, its tracks go where it went, and +/// those of filters that went go too. The base's new list, or `None` when there are no filters +/// to look after. +fn key_filters(m: &mut MotionTween, e: &MotionEdit, after: &Element) -> Option> { + let list = |el: &Element| match &el.kind { + ElementKind::Symbol { filters, .. } => Some(filters.clone()), + _ => None, + }; + let (before, base, mut now) = (list(&e.before)?, list(&e.base)?, list(after)?); + if !anicraft_doc::filters_pair_up(&before, &now) { + // Where each filter went: the first one left that holds the same. + let mut taken = vec![false; now.len()]; + let map: Vec> = before + .iter() + .map(|b| { + let i = now.iter().enumerate().position(|(i, n)| !taken.get(i).copied().unwrap_or(true) && n.filter == b.filter)?; + if let Some(t) = taken.get_mut(i) { + *t = true; + } + Some(i) + }) + .collect(); + m.remap_filters(&map); + // A filter that moved is the base's underneath (with its switch as the edit left it), + // not the playhead's. + for (old, new) in map.iter().enumerate() { + if let (Some(n), Some(b)) = (new, base.get(old)) + && let Some(slot) = now.get_mut(*n) + { + let enabled = slot.enabled; + *slot = FilterEntry { enabled, ..b.clone() }; + } + } + return Some(now); + } + for (slot, (was, is)) in before.iter().zip(&now).enumerate().take(usize::from(anicraft_doc::MAX_FILTER_SLOTS)) { + for ¶m in is.filter.params() { + let p = Property::Filter(anicraft_doc::FilterProp { slot: slot as u8, param }); + let (Some(v0), Some(v1)) = (was.filter.param(param), is.filter.param(param)) else { continue }; + if (v1 - v0).abs() > 1e-4 && !(e.offset == 0 && m.track(p).is_none()) { + let own = base.get(slot).and_then(|b| b.filter.param(param)).unwrap_or(v0); + m.set_key(p, e.offset, v1, own); + } + } + } + // Tracked numbers: the object's own underneath (the curves give the rest). + for t in &m.tracks { + if let Some(f) = t.property.filter() + && let (Some(slot), Some(own)) = (now.get_mut(usize::from(f.slot)), base.get(usize::from(f.slot)).and_then(|b| b.filter.param(f.param))) + { + slot.filter.set_param(f.param, own); + } + } + Some(now) +} + /// Most bends [`move_on_path`] makes to land the object where it was put off the path; each /// takes 15–35% off the miss on typical paths (the path's length changes as it bends, sliding the /// object). @@ -516,8 +585,16 @@ pub(crate) fn key_all_at(layer: &mut Layer, frame: u32) -> bool { } let offset = frame - kf.start; let Some(m) = kf.motion.as_mut() else { return false }; - let Some(base) = m.target_index(&kf.elements).and_then(|t| kf.elements.get(t)).map(|e| Props::of(e)) else { return true }; + let Some(target) = m.target_index(&kf.elements).and_then(|t| kf.elements.get(t)).cloned() else { return true }; + let base = Props::of(&target); let now = m.props_at(&base, offset as f32); + // The filters' numbers too (ADR 0092), as they are on that frame. + let at = m.apply(&target, offset as f32); + for p in filter_properties(&target) { + if let (Some(v), Some(own)) = (own_value(&at, p), own_value(&target, p)) { + m.set_key(p, offset, v, own); + } + } // On a motion path the frame's place is an anchor pinned to it (ADR 0049), where the // object is: nothing moves on this frame. let pinned = m.path.is_some() && m.pin_here(offset, &base).is_ok(); @@ -629,8 +706,8 @@ fn property(p: &Value) -> Result> { match opt_str(p, "property")? { None => Ok(None), Some(k) => Property::from_key(k).map(Some).ok_or_else(|| { - let all: Vec<&str> = Property::ALL.iter().map(|p| p.key()).collect(); - EngineError::Param(format!("unknown property '{k}' ({})", all.join(", "))) + let all: Vec = Property::ALL.iter().map(|p| p.key().into_owned()).collect(); + EngineError::Param(format!("unknown property '{k}' ({}, or filter.., slot 0 to 15)", all.join(", "))) }), } } @@ -643,8 +720,19 @@ fn set_key(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param(format!("{} must be between {} and {} {}", prop.label(), r.start(), r.end(), prop.unit()))); } let (kf, offset) = motion_span(s, p)?; - let base = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).and_then(|i| kf.elements.get(i)).map(|e| Props::of(e)); - let base = base.ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?; + let target = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).and_then(|i| kf.elements.get(i)).cloned(); + let target = target.ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?; + let base = Props::of(&target); + let own = own_value(&target, prop).ok_or_else(|| match prop.filter() { + Some(f) => EngineError::State(match &target.kind { + ElementKind::Symbol { filters, .. } => match filters.get(usize::from(f.slot)) { + Some(e) => format!("filter {} of the tween's object is a {}, which has no {}", f.slot, e.filter.label(), f.param.label()), + None => format!("the tween's object has no filter {} (it has {}; 0 is the first)", f.slot, filters.len()), + }, + _ => "filters apply to movie clip and button instances: the tween's object has none".into(), + }), + None => EngineError::State("the motion tween's object has no such property".into()), + })?; let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; // On a path, the X/Y keys of a pinned frame are its anchor's place: setting one moves the @@ -658,7 +746,7 @@ fn set_key(s: &mut Session, p: &Value) -> Result { } return Ok(json!({"property": prop.key(), "frame": start + offset, "value": value, "anchor": pin.anchor})); } - m.set_key(prop, offset, value, base.get(prop)); + m.set_key(prop, offset, value, own); Ok(json!({"property": prop.key(), "frame": start + offset, "value": value})) } @@ -669,7 +757,8 @@ fn remove_key(s: &mut Session, p: &Value) -> Result { let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; // Removing a pinned frame's X or Y key lets the pin go, with both keys (ADR 0049). let pin = m.live_pins().into_iter().find(|q| q.frame == offset).filter(|_| only.is_none_or(|o| matches!(o, Property::X | Property::Y))); - let mut removed: Vec<&str> = Property::ALL.into_iter().filter(|x| only.is_none_or(|o| o == *x)).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect(); + let keyed: Vec = m.tracks.iter().map(|t| t.property).collect(); + let mut removed: Vec> = keyed.into_iter().filter(|x| only.is_none_or(|o| o == *x)).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect(); if pin.is_some() { for k in [Property::X.key(), Property::Y.key()] { if !removed.contains(&k) { @@ -709,17 +798,36 @@ fn info(s: &mut Session, p: &Value) -> Result { let layer = s.timeline().layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; let kf = layer.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; let m = kf.motion.as_ref().ok_or_else(|| EngineError::State(format!("frame {} is not in a motion tween", frame + 1)))?; - let base = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| Props::of(e)); + let target = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)); + let base = target.map(|e| Props::of(e)); let now = base.map(|b| m.props_at(&b, (frame - kf.start) as f32)); + let filter_of = |slot: u8| match target.map(|e| &e.kind) { + Some(ElementKind::Symbol { filters, .. }) => filters.get(usize::from(slot)).map(|e| e.filter.label()), + _ => None, + }; let tracks: Vec = m .tracks .iter() .map(|t| { let keys: Vec = t.keys.iter().map(|k| json!({"frame": kf.start + k.frame, "value": k.value, "ease": k.ease.label(), "easing": easing_json(&k.ease), "bezier": k.ease.as_bezier()})).collect(); - json!({"property": t.property.key(), "label": t.property.label(), "unit": t.property.unit(), "keys": keys}) + let mut v = json!({"property": t.property.key(), "label": t.property.label(), "unit": t.property.unit(), "keys": keys}); + // A filter's number: which filter (ADR 0092); its kind `null` when it isn't there now. + if let Some(f) = t.property.filter() { + v["filter"] = json!({"slot": f.slot, "kind": filter_of(f.slot)}); + } + v }) .collect(); - let values: serde_json::Map = Property::ALL.iter().filter_map(|p| now.map(|n| (p.key().to_string(), json!(n.get(*p))))).collect(); + let mut values: serde_json::Map = Property::ALL.iter().filter_map(|p| now.map(|n| (p.key().into_owned(), json!(n.get(*p))))).collect(); + // And the filters' numbers at the frame. + if let Some(e) = target { + let at = m.apply(e, (frame - kf.start) as f32); + for p in filter_properties(e) { + if let Some(v) = own_value(&at, p) { + values.insert(p.key().into_owned(), json!(v)); + } + } + } // Where the object is (on a motion path the X/Y values are its timing, not its place). let position = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| m.apply(e, (frame - kf.start) as f32).transform.translation()).map(|q| json!([q.x, q.y])); let path = m.path.as_ref().map(|p| p.to_svg()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1db14f0e..662c0a05 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1150,6 +1150,8 @@ mod tests_warp; #[cfg(test)] mod tests_filter; #[cfg(test)] +mod tests_filter_tracks; +#[cfg(test)] mod merge_tests; #[cfg(test)] mod raw_tests; diff --git a/crates/engine/src/tests_filter_tracks.rs b/crates/engine/src/tests_filter_tracks.rs new file mode 100644 index 00000000..413be9ab --- /dev/null +++ b/crates/engine/src/tests_filter_tracks.rs @@ -0,0 +1,149 @@ +//! Motion tween tracks for filters (ADR 0092), through the command registry: keys, eases and +//! retiming on a filter's numbers, auto-key when a filter is edited inside the tween, tracks +//! following their filter, F6, undo and the file round trip. + +use super::*; +use anicraft_doc::{ElementKind, FilterEntry, FilterParam, FilterProp, Property}; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +/// A red 100 × 100 movie clip at (100, 100) with `filters`, selected, in a one-second motion +/// tween. +fn tweened(filters: Value) -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + run(&mut s, "symbol.set_kind", json!({"kind": "movie_clip"})); + run(&mut s, "element.set_filters", json!({ "filters": filters })); + run(&mut s, "timeline.create_motion_tween", json!({})); + s +} + +/// The object's filters as the base holds them. +fn base_list(s: &Session) -> Vec { + match &s.doc.timeline(s.scene).layers[0].keyframes[0].elements[0].kind { + ElementKind::Symbol { filters, .. } => filters.clone(), + _ => Vec::new(), + } +} + +fn value(s: &mut Session, frame: u32, key: &str) -> f64 { + let v = run(s, "motion.info", json!({ "frame": frame })); + v["values"][key].as_f64().unwrap_or_else(|| panic!("no {key} in {}", v["values"])) +} + +fn track_keys(s: &mut Session, key: &str) -> Vec<(u64, f64)> { + let v = run(s, "motion.info", json!({})); + let t = v["tracks"].as_array().and_then(|ts| ts.iter().find(|t| t["property"] == key).cloned()); + t.map(|t| t["keys"].as_array().map(|ks| ks.iter().map(|k| (k["frame"].as_u64().unwrap_or(0), k["value"].as_f64().unwrap_or(0.0))).collect()).unwrap_or_default()).unwrap_or_default() +} + +/// The green of a pixel: 1 on the white stage, less where the red box's blur reaches. +fn green_at(s: &Session, frame: u32, x: u32, y: u32) -> f32 { + anicraft_render::render_frame(&s.doc, frame, 1.0).unwrap().pixel(x, y).unwrap()[1] +} + +#[test] +fn a_blur_tweens_by_commands_with_eases_and_retiming() { + let mut s = tweened(json!([{"type": "blur", "blur_x": 0, "blur_y": 0}])); + run(&mut s, "motion.set_key", json!({"property": "filter.0.blur_x", "frame": 12, "value": 40})); + run(&mut s, "motion.set_key", json!({"property": "filter.0.blur_y", "frame": 12, "value": 40})); + assert_eq!(track_keys(&mut s, "filter.0.blur_x"), vec![(0, 0.0), (12, 40.0)]); + assert_eq!(value(&mut s, 6, "filter.0.blur_x"), 20.0); + let info = run(&mut s, "motion.info", json!({})); + let t = info["tracks"].as_array().unwrap().iter().find(|t| t["property"] == "filter.0.blur_x").unwrap().clone(); + assert_eq!((t["label"].as_str(), t["unit"].as_str(), &t["filter"]), (Some("Blur X"), Some("px"), &json!({"slot": 0, "kind": "Blur"}))); + // The render follows: at frame 0 the box's edge is sharp, at frame 12 the blur spills out. + assert!((green_at(&s, 0, 95, 150) - 1.0).abs() < 1e-6); + assert!(green_at(&s, 12, 95, 150) < 0.95); + // Eases like any property's segment. + run(&mut s, "motion.set_ease", json!({"property": "filter.0.blur_x", "frame": 3, "easing": "CubicOut"})); + assert!(value(&mut s, 6, "filter.0.blur_x") > 30.0, "cubic out is past halfway at half time"); + // Retimed: the key moves with its value and ease. + let v = run(&mut s, "motion.move_keys", json!({"keys": [{"property": "filter.0.blur_x", "frame": 12}], "by": 4})); + assert_eq!(v["keys"], json!([{"property": "filter.0.blur_x", "frame": 16}])); + assert_eq!(value(&mut s, 16, "filter.0.blur_x"), 40.0); + // Removed. + let v = run(&mut s, "motion.remove_key", json!({"property": "filter.0.blur_y", "frame": 12})); + assert_eq!(v["removed"], json!(["filter.0.blur_y"])); + // What can't be keyed says why. + for (p, want) in [(json!({"property": "filter.1.blur_x", "value": 3}), "no filter 1"), (json!({"property": "filter.0.angle", "value": 3}), "has no Angle"), (json!({"property": "filter.0.blur_x", "value": 900}), "between"), (json!({"property": "filter.0.sparkle", "value": 1}), "unknown property")] { + let e = s.execute("motion.set_key", &p).expect_err("refused").to_string(); + assert!(e.contains(want), "{p}: {e}"); + } +} + +#[test] +fn editing_a_filter_inside_the_tween_keys_it_and_undo_takes_it_back() { + let mut s = tweened(json!([{"type": "drop_shadow", "distance": 4}])); + let steps = s.history_len(); + s.set_frame(10); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "drop_shadow", "distance": 24}]})); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + assert_eq!(track_keys(&mut s, "filter.0.distance"), vec![(0, 4.0), (10, 24.0)]); + assert!(track_keys(&mut s, "filter.0.blur_x").is_empty(), "only the number that changed is keyed"); + // The object keeps its own distance underneath; the curve gives the rest. + assert_eq!(base_list(&s)[0].filter.param(FilterParam::Distance), Some(4.0)); + assert_eq!(value(&mut s, 5, "filter.0.distance"), 14.0); + // Switching the filter off keeps the tween (the list keeps its shape). + run(&mut s, "filter.enable", json!({"enabled": false, "index": 0})); + assert!(!base_list(&s)[0].enabled && track_keys(&mut s, "filter.0.distance").len() == 2); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(track_keys(&mut s, "filter.0.distance").is_empty()); + // On the span's first frame an untracked number changes the object itself. + s.set_frame(0); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "drop_shadow", "distance": 9}]})); + assert!(track_keys(&mut s, "filter.0.distance").is_empty()); + assert_eq!(base_list(&s)[0].filter.param(FilterParam::Distance), Some(9.0)); +} + +#[test] +fn tracks_follow_their_filter_when_the_list_is_reordered_or_cut() { + let mut s = tweened(json!([{"type": "blur"}, {"type": "glow", "strength": 1}])); + run(&mut s, "motion.set_key", json!({"property": "filter.1.strength", "frame": 10, "value": 300})); + run(&mut s, "motion.set_key", json!({"property": "filter.0.blur_x", "frame": 10, "value": 30})); + // Reordered at a frame inside the tween: the glow goes first, its track with it, and the + // object's own values stay underneath (not the playhead's). + s.set_frame(5); + run(&mut s, "filter.move", json!({"from": 1, "to": 0})); + assert_eq!(track_keys(&mut s, "filter.0.strength"), vec![(0, 100.0), (10, 300.0)]); + assert_eq!(track_keys(&mut s, "filter.1.blur_x"), vec![(0, 5.0), (10, 30.0)]); + let base = base_list(&s); + assert_eq!((base[0].filter.label(), base[0].filter.param(FilterParam::Strength)), ("Glow", Some(100.0))); + assert_eq!(base[1].filter.param(FilterParam::BlurX), Some(5.0)); + assert_eq!(value(&mut s, 10, "filter.0.strength"), 300.0); + // The glow removed: its track goes; the blur's moves up. + run(&mut s, "filter.remove", json!({"index": 0})); + assert!(track_keys(&mut s, "filter.0.strength").is_empty()); + assert_eq!(track_keys(&mut s, "filter.0.blur_x"), vec![(0, 5.0), (10, 30.0)]); + // A filter pasted after it leaves the tracks where they are. + run(&mut s, "filter.copy", json!({})); + run(&mut s, "filter.paste", json!({})); + assert_eq!(base_list(&s).len(), 2); + assert_eq!(track_keys(&mut s, "filter.0.blur_x").len(), 2); +} + +#[test] +fn f6_keys_the_filters_and_the_file_keeps_their_tracks() { + let mut s = tweened(json!([{"type": "adjust_color", "hue": 0}])); + run(&mut s, "motion.set_key", json!({"property": "filter.0.hue", "frame": 20, "value": 120})); + s.set_frame(10); + run(&mut s, "timeline.insert_keyframe", json!({})); + let hue = track_keys(&mut s, "filter.0.hue"); + assert!(hue.contains(&(10, 60.0)), "{hue:?}"); + assert_eq!(track_keys(&mut s, "filter.0.saturation"), vec![(0, 0.0), (10, 0.0)]); + // The document round-trips through JSON (the file format), tracks and all. + let json = serde_json::to_string(&s.doc).unwrap(); + assert!(json.contains("\"filter_tracks\"") && json.contains("filter.0.hue")); + let back: anicraft_doc::Document = serde_json::from_str(&json).unwrap(); + assert!(back == s.doc); + let m = back.timeline(0).layers[0].keyframes[0].motion.clone().unwrap(); + assert!(m.track(Property::Filter(FilterProp { slot: 0, param: FilterParam::Hue })).is_some()); +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index c1d0d1bb..43ebd905 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -513,6 +513,13 @@ impl GpuRenderer { self.broken.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(|| why.to_string()); } + /// Marks the renderer failed from outside (ADR 0092): a renderer on the window's device + /// hears of the device's loss from the window, which owns the device's callbacks. Every + /// later call refuses with `why` (the first reason given stays), and callers draw on the CPU. + pub fn fail(&self, why: &str) { + self.mark_broken(why); + } + /// Bitmaps uploaded and kept, and their bytes (at most about [`images::IMAGE_BUDGET`]). pub fn cached_images(&self) -> (usize, u64) { self.images.lock().unwrap_or_else(PoisonError::into_inner).held() diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index e74a607e..0186c76f 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -876,6 +876,39 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() { assert!(g.broken().is_none()); } +/// ADR 0092: a device lost mid-session (here destroyed on purpose, the way a driver reset +/// takes it) never panics: every later call is an error saying why, so the stage hands the +/// frame to the CPU. A renderer told from outside (the window's device was lost) refuses too. +#[test] +fn a_lost_device_turns_every_call_into_an_error_and_says_why() { + // A device of its own: the shared one stays for the other tests. + let opened = GpuRenderer::new().or_else(|_| GpuRenderer::software()); + let Ok(g) = opened else { + eprintln!("skipping the lost-device test: no GPU"); + return; + }; + let dl = list(vec![item(Path::rect(1.0, 1.0, 6.0, 6.0), Paint::Solid(Rgba::BLACK))]); + assert!(g.render(&dl, &view(8, 8, None), Output::Premul8).is_ok()); + g.device.destroy(); + let _ = g.wait_idle(); + let first = g.render(&dl, &view(8, 8, None), Output::Premul8); + assert!(matches!(first, Err(GpuError::Device(_))), "a lost device fails the frame"); + assert!(g.broken().is_some(), "and the renderer says it is broken"); + assert!(matches!(g.render_texture(&dl, &view(8, 8, None)), Err(GpuError::Device(_)))); + // Told from outside: the first reason stays. + let why = g.broken(); + g.fail("the window's device was lost"); + assert_eq!(g.broken(), why); + // A fresh renderer told from outside refuses at once, with that reason. + if let Ok(h) = GpuRenderer::new().or_else(|_| GpuRenderer::software()) { + h.fail("the window's device was lost"); + match h.render(&dl, &view(8, 8, None), Output::Premul8) { + Err(GpuError::Device(e)) => assert!(e.contains("window's device"), "{e}"), + other => panic!("expected a device error, got {:?}", other.map(|f| f.width)), + } + } +} + #[test] fn gpu_renders_from_many_threads_at_once() { let Some(g) = gpu() else { return }; diff --git a/docs/adr/0092-surviving-gpu-failures-and-motion-editor-filter-tracks.md b/docs/adr/0092-surviving-gpu-failures-and-motion-editor-filter-tracks.md new file mode 100644 index 00000000..6d6e0cd3 --- /dev/null +++ b/docs/adr/0092-surviving-gpu-failures-and-motion-editor-filter-tracks.md @@ -0,0 +1,188 @@ +# ADR 0092: Surviving GPU failures mid-session, and Motion Editor filter tracks + +* Status: accepted (2026-11-13) +* Relates to: roadmap M3 (GPU stage) and M5 (filters), issues #207 and #255, ADR 0006 + (cross-platform start-up), ADR 0015 (autosave), ADR 0016 (motion tweens), ADR 0029 and 0032 + (the GPU stage on the window's device), ADR 0081 (eases), ADR 0083 (retiming), ADR 0091 + (filter lists) + +Two parts, one PR: both finish things earlier ADRs left as "later". + +## Part 1: surviving GPU failures mid-session + +### Context + +Start-up already falls back between graphics interfaces (`startup::plan`, #207). A running +session did not. Under heavy GPU load the lead saw `Surface::configure` fail with "Failed to wait +for GPU to come idle before reconfiguring the Surface" (#255), and AniCraft closed. + +The cause is in wgpu, not the driver: every error nobody catches goes to the device's +uncaptured-error handler, and **wgpu's default handler panics**. `Surface::configure` reports its +errors that way. eframe installs no handler, so the panic unwound out of eframe and the window +closed, with whatever was unsaved since the last autosave. + +The GPU stage was already careful on its own: each call runs in error scopes and `catch_unwind`, +and a broken renderer handed every frame to the CPU. But it never came back, and a renderer on +the window's device never heard that the device was lost (ADR 0029 installed nothing on the +window's device). + +### Decision + +1. **The window's device gets our handlers** (`src/gpu_watch.rs`), installed by the app at + creation: + * an uncaptured-error handler that writes the error down (the log gets the first 20 in full, + then one in 500) instead of panicking; + * a device-lost callback that records the loss (a deliberate `Destroyed` isn't one). + + This replaces ADR 0029's "nothing is installed on the device". The window owns its device, so + the app installs the handlers; the stage renderer still uses only its own thread-local error + scopes. +2. **The surface is retried, not skipped for ever.** eframe asks `on_surface_status` what to do + with a frame the surface couldn't give. Ours (set on every wgpu attempt) reconfigures after + `Outdated` or a validation error. After three failed reconfigures in a row it makes the + surface anew; a lost surface is made anew at once. Hidden windows and timeouts skip the frame. + Before, a surface whose configure had failed stayed unconfigured, and every later frame was + skipped. +3. **The app acts on the news each frame:** + * **An error the window survived** autosaves unsaved work at once (not waiting for the + interval), and the status bar says AniCraft carried on, at most once a minute. + * **The device lost, or the surface failing for 8 s on end**, can't be repaired: eframe 0.36 + can't make a new device for a running window. So the app: + * writes the work to the recovery folder one last time; + * records the attempt in `Logs/graphics-lost`; + * asks `main` to reopen; + * closes the window. + + `main` then opens the window again with that attempt last. The Recover window offers the + work back (a saved, unchanged document simply reopens). It does this at most twice per run. +4. **The startup record.** `startup::begin` returns the attempts to try last: + * the one in `graphics-lost`, for the next 3 starts (`LOST_STARTS`, counted down each start); + * then the one a start died in (the existing marker). + + After the third start the fastest way gets its chance again: the driver may have been updated, + or the load that brought it down may be gone. A panic after the window was up that reads as a + graphics failure (wgpu, surface, DXGI, Vulkan…) leaves the same record. +5. **The GPU stage falls back at once and retries with a bounded backoff** (`gpu_stage::Retry`): + * **Falling back.** When the renderer reports itself broken, the service's rasterizer is + removed and the CPU draws. The frame that failed was already redrawn by the oracle, so + nothing is ever missing. A status-bar notice and a log line say why. + * **Retrying.** The GPU is tried again after 3, 15, 60 and 300 s. Each try counts as a failure + if it can't start. A change of the stage's size brings a try forward, but no sooner than 1 s + after the failure. After five failures in a row the CPU keeps the stage for the session. A + renderer that runs for 10 minutes without trouble starts the count afresh. + * **The window's device lost.** It is never retried, because the window reopens. A renderer + sharing that device is failed from outside (`GpuRenderer::fail`), since a device has one + loss callback and the window owns it. + * **Preferences and the status bar** show the new state (`Stopped`: why, and whether a retry + is coming). + +### Tests + +* `anicraft-gpu`: a device destroyed mid-session (as a driver reset takes it) makes every call + an error that says why, never a panic. A renderer failed from outside refuses with that reason. + This needs a GPU or a software adapter, and skips without one. +* Shell, with a stand-in renderer (unit tests open no device). An injected loss: + * the frame is drawn on the CPU; + * the rasterizer goes, with a notice; + * no retry before its time, then a retry that draws again ("back"); + * a longer wait after a second failure; + * a resize bringing the try forward; + * a failed retry waiting longer still. + + A lost window device is never retried. The backoff's rules are tested on their own. +* The surface policy; errors and the loss reaching the app once; the notice rate. +* The start-up plan after a mid-session death, the record's parsing, and its countdown over three + starts, through the real log folder. + +### Not in this part + +* Recreating the window's device in place: eframe doesn't offer it. Reopening is the fallback. +* A GPU runner in CI to exercise real driver resets. + +## Part 2: Motion Editor filter tracks + +### Context + +ADR 0091 left "motion-tween tracks per filter property … addressed by slot and parameter … +following moves and removals of filters" for later. Animate's Motion Editor animates filter +values beside position, transform and colour, and artists expect a blur to ease in like +anything else. + +### Decision + +1. **A property is also a filter's number.** `Property::Filter(FilterProp { slot, param })`: + * `slot` is the filter's place in the instance's list (0 is applied first, at most 16); + * `param` is a `FilterParam`: Blur X, Blur Y, Strength (%), Angle (°), Distance (px), and + Adjust Color's Brightness, Contrast, Saturation and Hue. + + `Filter::params` says which numbers a kind has. Colours, ramps, quality and switches are not + numbers on a curve and stay the object's own. Everything built on `Property` gets filter + tracks for free, and they behave as any track: keys, per-segment eases (ADR 0081), moving keys + in time, stretching, split and join (ADR 0083), the All lane, and `motion.move_keys`. +2. **Addressed as `filter..`** in commands and files (`filter.0.blur_x`). The other + properties keep their names. `Property` serializes as that string (it was the serde name + before, so nothing else changes). +3. **Files keep them apart.** + * Filter tracks are written under the tween's `filter_tracks` key, and `tracks` holds only the + twenty properties older builds know. + * An older build ignores the new key and opens the file, with the filters holding still. If + the filter tracks were mixed into `tracks`, an unknown property name would make it refuse + the whole document. + * Reading merges the two lists, so a hand-written file with a filter in `tracks` works too. + * Files without filter tracks are byte-for-byte as before. +4. **Evaluation stays pure.** `MotionTween::apply` sets each tracked number on the target's + filter at that slot. A track whose slot is empty, or whose filter has no such number (the + filter was replaced by another kind), does nothing. Off filters are still left out by + `evaluate` (ADR 0091), so no renderer or exporter changed. The CPU oracle, the GPU stage and + every export draw the tweened values. +5. **Auto-key, like moving the object.** A command that edits the target inside the tween (Properties + › Filters, `element.set_filters`, `filter.*`) goes through `finish_edit` as every edit does. + * **The list kept its shape** (the same kinds in order): each number it changed is keyed at + the playhead. On the span's first frame an untracked number changes the object's own value + instead. Tracked numbers keep the object's own values underneath. + * **The shape changed** (moved, removed, pasted): each filter is found again by what it holds, + its tracks follow it to its new slot, and the tracks of filters that went go too. The moved + filters get the object's own values back underneath. + * Commands don't need to know any of this. One undo step, as before. +6. **F6 inside a tween** keys the filters' numbers too. `motion.info` lists filter tracks with + their filter (`{"slot", "kind"}`) and the filters' values at the frame. +7. **The Motion Editor** lists each filter after the colour effect: the filter's name as a row + (faint and "(off)" when switched off), its numbers under it. Each row has the value field, the + key diamond, the curve and the ease footer, like the other properties. Screen readers hear + "Blur: Blur X". + Filters are added in Properties, as in Animate; the Motion Editor animates what is there. + +### Tests + +* Doc: + * a blur tweening on its own curve, eased; + * strength in percent; + * inert tracks never panicking; + * the file round trip with `filter_tracks` and old files unchanged; + * key parsing and its refusals; + * remapping; + * retiming, stretching, split and join keeping every frame. +* Engine, through the commands: + * keys, eases, `motion.move_keys` and removal on a blur, and the render following it; + * errors that say why; + * auto-key from `element.set_filters` with one undo step; + * a switched-off filter keeping its tween; + * tracks following `filter.move`, going with `filter.remove`, untouched by `filter.paste`; + * F6, and the document round trip. +* Shell: the filter rows under their names. Screenshot: `--open motionfilters` (the Star's blur + tweening, eased, in the Motion Editor). + +### Not in this part + +* Filter colours (shadow, glow, highlight) as tracks: they would need a colour row like the + tint's. +* Quality and switches as stepped tracks. +* Animate's filter tracks from XFL motion tweens. + +## Consequences + +* A graphics driver failure now costs the stage's speed for a while, or the window for a moment, + but never the work or the session. +* `Property` is no longer a closed list of twenty. Code that walks every property for an object + (F6, join, the editor's rows) adds `filter_properties(target)`. Code indexing `Props` still sees + only the twenty. diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index d2f71669..25fb2f6e 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -388,7 +388,7 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Warp Mesh** `warp.info` Parameters: `{element?, frame?} → the artwork's warp at the frame: resolution, the mesh's columns, rows, vertices and triangles, whether it is bent, and its pins (id, where they show in stage px, and where they were placed on the artwork as drawn, in its own space)` - **Property Keyframe** `motion.set_key` · changes the document - Parameters: `{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255), value (px, %, °), frame?, layer?} (colour properties of several styles compose into Advanced, ADR 0056)` + Parameters: `{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255)|filter.. (a number of the object's filter at that place, 0 the first; ADR 0092), value (px, %, °), frame?, layer?} (colour properties of several styles compose into Advanced, ADR 0056)` - **Remove Property Keyframe** `motion.remove_key` · changes the document Parameters: `{property? (default: every property), frame?, layer?}` - **Property Ease** `motion.set_ease` · changes the document diff --git a/docs/guide/troubleshooting-and-faq.md b/docs/guide/troubleshooting-and-faq.md index 76c8aac2..fbab3bb5 100644 --- a/docs/guide/troubleshooting-and-faq.md +++ b/docs/guide/troubleshooting-and-faq.md @@ -47,6 +47,27 @@ is set, that environment variable overrides Preferences; remove it to choose aga Exports always use the CPU renderer, so a stage problem never ends up in your files. +## The graphics card stopped in the middle of my work + +Under heavy load (a game or a render running beside AniCraft, a very large scene) a graphics +driver can stop answering or reset itself. AniCraft keeps going: + +* **The stage** switches to the CPU at once and the status bar says so. The picture is the same, + only slower on big scenes. AniCraft tries the graphics card again after a few seconds, then + after longer pauses (and sooner when you resize the window); the status bar says when it is + back. After several failures in a row the CPU keeps the stage for the rest of the session. +* **A driver error** the window survives is written to the log, your unsaved work is autosaved + straight away, and the status bar says AniCraft carried on. +* **If the window itself loses the graphics card**, AniCraft saves your work, closes the window + and opens it again a safer way (on Windows, DirectX 12 on the built-in graphics chip, then + OpenGL). The **Recover unsaved work** window offers your work back. The next three starts try + that safer way first too, then the fastest way gets its chance again. + +If it keeps happening, update the graphics driver, or choose another way in **Preferences › +Stage › Window graphics**. The log (`anicraft.log`, in the `Logs` folder of the +[settings folder](#where-settings-live)) says what the driver reported; please attach it to a +bug report. + ## Fonts look different or are missing * **The interface font.** AniCraft's builds normally include the Inter and JetBrains Mono diff --git a/docs/guide/tweens.md b/docs/guide/tweens.md index 812aae02..7c603107 100644 --- a/docs/guide/tweens.md +++ b/docs/guide/tweens.md @@ -182,6 +182,19 @@ all** gives every property's segment there the same ease. Each drag is one undo **Remove Tween** takes the motion tween away, leaving the object as it is on the span's first frame. +### Animating filters + +A movie clip or button with filters (see **Properties › Filters**) lists each filter in the +Motion Editor, below the colour effect, with its numbers under its name: **Blur X** and **Blur Y**, +**Strength**, **Angle** and **Distance** for the shadows, glows and bevels, and **Brightness**, +**Contrast**, **Saturation** and **Hue** for Adjust Color. They key, curve, ease and retime like +any other property, so a blur can sharpen with an ease-out and then pulse. + +You can also change a filter in **Properties › Filters** with the playhead inside the tween: the +number you changed gets a key there, as moving the object does. Reordering or removing filters +takes their keys along with them. A filter's colours, quality and switches aren't animated yet; +they stay as the object has them. + ### Moving keys in time Drag a key **sideways** to move it to another frame. It snaps to whole frames, carries its value diff --git a/docs/roadmap.md b/docs/roadmap.md index 78a60cb7..c80224ba 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -9,7 +9,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Dimension | Status | |---|---| | Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). | -| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. Filters apply in list order and may be switched off (ADR 0091): `evaluate` leaves switched-off ones out, so every renderer and export draws them as absent. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | +| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. Filters apply in list order and may be switched off (ADR 0091): `evaluate` leaves switched-off ones out, so every renderer and export draws them as absent. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). **Mid-session failures** (ADR 0092): a broken GPU stage hands the stage to the CPU at once with a status-bar notice and a log line, and is retried with a bounded backoff; driver errors on the window's device are logged instead of panicking (the #255 `Surface::configure` panic), and a lost window device autosaves and reopens the window on a safer way. Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | | Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it; a motion tween's keys stretch in proportion, ADR 0083). Side dock tab strips never run under the panel menu (names shrink with an ellipsis, then the strip scrolls). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with **ease presets and custom eases** (ADR 0081: Classic Ease with a strength and Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic In/Out/In Out; custom eases of up to 64 Bézier points in the Custom Ease window, x kept monotonic, overshoot allowed, keyboard operable, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, colour, filters, and instance filters tween; XFL custom and per-property eases import exactly; `ease.*` headless) + curve preview, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (any preset, saved ease or custom ease of several segments, ADR 0081; overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Retiming** (ADR 0083): keys drag sideways in time (snapped to frames, never past a neighbour), Shift-click picks keys across properties, an All lane picks a frame's keys, Left/Right move picked keys with the curve focused; dragging a span's end stretches a motion tween's keys in proportion (Shift keeps them); a click picks a whole motion span and dragging (or a selection of whole tween spans) moves it at its length, Alt-drag copies; **Split Motion** / **Join Motion** (split then join is exact). Headless: `motion.move_keys`, `timeline.resize_span`, `timeline.move_spans`, `motion.split`, `motion.join`. Not yet: joining two independent motion paths, retiming from a span's left edge. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start: a bone from a chained instance always starts at its joint; branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone (the grabbed point follows) or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. **Shape armatures** (ADR 0071): the Bone tool draws bones inside a shape (it moves to an armature layer as an object, outside merge drawing); its points are bound to the nearest bones automatically (weights by distance to each bone, up to four, summing to 1) and bend by linear blend skinning (handles with their anchors, strokes keep their width, the rest pose exact); the **Bind tool** (Shift+M) shows the points (squares, triangles where shared) and binds them by click, Shift/Ctrl-click or box; the same IK, poses and tweens; `bone.add_in_shape`, `bone.bind`, `bone.info {points}`. **Painted weights and reshaping** (ADR 0090): the Bind tool's **Paint Weights** brush (Add, Subtract, Smooth; size with `[`/`]`, strength; soft falloff) paints a bone's share onto the points under it, shown live as a heat map (blue none to red all) on the outline and points; weights stay normalised per point (the other bones share the rest, a point's only bone gives way to its nearest other bones), painted points are hand-bound, one undo step per stroke (1.15 ms for 32 dabs over 20,000 points); a focused point's weights as numbers in Properties › Bone (keyboard); Subselection edits a bound shape's outline at the rest pose (move, add, delete, smooth/corner) keeping the binding: moved points keep their weights, new points blend their neighbours', deleted points drop theirs, the rest pose exact; `bone.paint_weights`, `bone.set_weight`. **Springs, joint translation and members in place** (ADR 0084): joints slide along X/Y of what they start on, freely or within pixel limits, as part of each pose (IK slides only where turning can't reach); per-bone Spring and Damping swing bones after the motion and settle, evaluated as a pure replay of up to six seconds of motion (seeking equals playing bit for bit; 0.33 ms a frame for 16 sprung bones), shown on the stage, in Test Movie and every export, switched off per armature for posing; a picked bone's instance takes colour effect, blending and filters in place on every pose; `bone.set_translation`, `bone.set_spring`, `bone.enable_springs`. Not yet: runtime armatures, XFL import, mixing instances and shapes in one armature (proposed in ADR 0084 and 0090), reshaping at a posed frame, gravity and wind. **Asset Warp** (ADR 0079): the **Asset Warp tool** (Shift+Q) pins a shape or a bitmap (the first pin covers it with a warp mesh: a grid over its bounds, 2–48 cells along the longer side, Properties › Asset Warp); dragging a pin bends the artwork around the other pins by rigid moving least squares (Schaefer et al. 2006) at the mesh's vertices, live, one undo step per drag; Delete removes a pin; pins are added to every keyframe holding the artwork and their poses tween with classic tweens and easing; shapes bend through the mesh (straight edges exactly, curves split), bitmaps are drawn through its triangles by the CPU oracle (bilinear) and the GPU stage takes the same prepared fill (parity exact); the rest pose is the drawing bit for bit; every raster export, SVG (a bent bitmap baked as an image), Lottie and HTML (a bent bitmap reported) go through `evaluate`; `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`, `warp.remove`, `warp.info`. Not yet: as-rigid-as-possible solving on a mesh that follows the outline, symbols and text, binding warp pins to bones, a GPU textured-triangle path, bent bitmaps in HTML and Lottie, XFL import of warped assets. eases saved in the document and offered everywhere; copy/paste of an ease; classic tweens eased per property group: position, **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. **Camera, second slice** (ADR 0082): layer depth in a pinhole perspective (deeper layers move and zoom less, draw behind nearer ones; depth 0 bit-exact), depth keyed over time (linear between keys), **Window › Layer Depth** (layers by depth, drag nearer or farther, key, attach), **Attach Layer to Camera** (timeline toggle; HUDs stay on screen), camera colour effects (Brightness, Tint, Advanced), and the Selection tool picking and moving artwork while previewing through the camera; headless `layer.set_depth {key, frame}`, `layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view: camera}`. Not yet: other tools while previewing, depth inside symbols, depth keys moving with inserted frames, XFL camera and layer-depth import (no public format description). **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Width profiles take part in the merge since ADR 0093. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. **Tilt, texture and scatter** (ADR 0093): per-sample pen tilt (Pointer Events altitude and azimuth in `draw.brush` points) turns the tip by the azimuth and widens it up to 2× as the pen leans (Brush › Tilt: Angle, Width, shown once a pen reports tilt; the Paint Brush's width too), a fixed paper grain of holes (Texture) and dabs thrown either side (Scatter), all vector fills; built-in Charcoal and Spatter (nine brushes). Not yet: reading tilt from the pen on desktop systems (winit 0.30 reports it only on iOS), opacity varying along a stroke, bitmap or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Since ADR 0093: width-profiled lines erase and merge, each piece keeping its widths; gradient pieces keep their gradient where it was; inside an open symbol or drawing object the Eraser erases its shapes, and on the stage the status bar says how. Not yet: eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. **Exporter and ease plug-ins** (ADR 0088): `kind: "exporter"` declares a format (name, extension, options) and gets evaluated frames (`movie`, `frame`: the flattened display list, never the document), returning the file's bytes from `ac_export` (64 MiB cap, 5·10¹⁰ instructions, 10 min); File › Export lists it with an Export window (options, frames, file, progress bar and Cancel on a worker thread); `file.export_plugin`, `file.export_formats`, `anicraft-cli export --format ` and `formats`. `kind: "ease"` declares named eases, `ac_ease(i, t)` sampled into 257 values at load (NaN, unbounded or end-missing eases refused); `Easing::Sampled` keeps the table in the document, so it plays the same without the plug-in; the ease menus list them under Plug-in eases; `{plugin, ease}` easing params. Samples: Plain Text Frames and Stepped Eases, built and run in CI. Not yet: plug-in formats in Publish, bitmaps' pixels and sounds for exporters, ease plug-ins with parameters, background runs of command plug-ins, a binary document view. | @@ -36,9 +36,9 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. | | **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅; ~~groups, Combine Objects, Selection-tool modifiers~~ ✅ first slice (ADR 0073); ~~gradient editor, Gradient Transform tool and Lock Fill~~ ✅ (ADR 0074: the colour picker sets a fill's type, with a keyboard-operable stop bar, overflow, Linear RGB, focal point and bitmap fills; the Gradient Transform tool (F)); ~~rulers, grid and guides with one snap engine~~ ✅ first slice (ADR 0076). | | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016; the ease presets, saved and custom eases of ADR 0081 per segment); ~~Motion Editor and timeline retiming, Split/Join Motion~~ ✅ (ADR 0083); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | -| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. | +| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); ~~surviving GPU failures mid-session~~ ✅ (ADR 0092: the stage drops to the CPU at once and retries the GPU after 3, 15, 60 and 300 s or on a resize; the window's device gets an error handler and a loss callback instead of wgpu's panic, a failing surface is reconfigured then recreated, and a lost window device autosaves, reopens the window a safer way and makes the next 3 starts try it late; not yet: recreating the window's device in place, which eframe doesn't offer); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); ~~sound and video items, self-extracting and top-folder `.fla` archives~~ ✅ (ADR 0086: sound effects and custom envelopes, every sound and video that doesn't come across named with its format, Screen Video stills, zipped XFL folders and self-extracting stubs; not yet: sound in/out points, AIFF and compressed WAV, video playback); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (~~easing curves instead of per-frame keys~~ ✅, ADR 0089: keyframes with Bézier eases, moving artwork under group transforms, playback parity at every frame; not yet: motion along curved guides as spatial tangents, orient to path, nested tweens as nested transforms); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). | -| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters; motion-tween tracks per filter property in the Motion Editor, filters on text fields and built-in presets later) and ~~blend modes~~ ✅ on Movie Clips. | +| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters), ~~motion-tween tracks per filter property in the Motion Editor~~ ✅ (ADR 0092: blur, strength, angle, distance and Adjust Color's four, by filter slot, with curves, eases and retiming, auto-keyed from Properties › Filters, following reorders and removals; not yet: filter colours, quality and switches as tracks, Animate's filter tracks from XFL; filters on text fields and built-in presets later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool); ~~painted weights and reshaping a bound shape~~ ✅ second slice (ADR 0090; not yet: instances and shapes in one armature, reshaping at a posed frame); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles) and brush library; ~~tilt, textured brushes, erasing inside symbols, gradients and width profiles in the merge~~ ✅ second slice (ADR 0093: tilt turns and widens the tip per sample, paper-grain texture and scatter as vector paint, Charcoal and Spatter, the Eraser's hint for symbols and objects, width profiles carried into each merged piece; not yet: reading tilt on desktop systems (winit 0.30 reports it only on iOS), bitmap, art and pattern brushes, eraser pressure and presets, the live preview through texture and tilt); ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). | | **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout), second slice ✅ (ADR 0087: the tools move like any panel, as a slim bar on any side or a tab laid out in columns; floating windows hold several tabs and drag back into a dock by their grip or title bar with the drop targets shown; docks collapse to strips of panel icons with flyouts over the stage (Esc or a click outside closes them); Manage Workspaces renames and deletes your own (built-in ones reset only); every panel fits the narrowest dock (200 pt), form rows wrapping under their label, checked by test in English and the pseudo-locale; not yet: dragging between two windows of their own on mixed-DPI screens verified by hand, panels side by side inside a floating window, columns of groups in one dock, minimum sizes per panel, panel shortcut keys). | diff --git a/src/app.rs b/src/app.rs index 65aa2158..a7238b70 100644 --- a/src/app.rs +++ b/src/app.rs @@ -617,6 +617,12 @@ impl App { // The GPU stage shares the window's device when it runs on wgpu (ADR 0029). #[cfg(gpu_stage)] app.stage_cache.gpu.set_window_device(cc.wgpu_render_state.as_ref()); + // The driver's errors and the device's loss are written down instead of closing the + // window (ADR 0092). + #[cfg(not(target_arch = "wasm32"))] + if let Some(rs) = cc.wgpu_render_state.as_ref() { + crate::gpu_watch::watch(&rs.device, &cc.egui_ctx); + } app } @@ -2481,6 +2487,33 @@ impl App { self.me_shot_drag = true; self.run("timeline.goto", json!({"frame": start + mid + 3})); } + Some("motionfilters") => { + // A blur tweening in the Motion Editor (ADR 0092): the Star becomes a movie clip + // with a blur and a glow, its tween keys the blur up and down again with an ease + // and pulses the glow, and the editor shows the Blur X curve mid-way. + self.run("layer.select", json!({"index": 1})); + self.run("timeline.goto", json!({"frame": 0})); + self.run("edit.select_all", json!({})); + self.run("symbol.set_kind", json!({"kind": "movie_clip"})); + self.run("element.set_filters", json!({"filters": [{"type": "blur", "blur_x": 0, "blur_y": 0, "quality": 2}, {"type": "glow", "color": "#ffd54a", "blur_x": 12, "blur_y": 12, "strength": 1}]})); + if self.run("timeline.create_motion_tween", json!({"frame": 0})).is_some() { + let frames = self.s.active_layer().and_then(|l| l.keyframes.first()).map_or(24, |k| k.duration); + let (mid, end) = (frames / 2, frames.saturating_sub(1)); + for (p, f, v) in [("filter.0.blur_x", mid, 24.0), ("filter.0.blur_x", end, 0.0), ("filter.0.blur_y", mid, 8.0), ("filter.0.blur_y", end, 0.0), ("filter.1.strength", mid, 260.0), ("filter.1.strength", end, 100.0)] { + self.run("motion.set_key", json!({"property": p, "frame": f, "value": v})); + } + self.run("motion.set_ease", json!({"property": "filter.0.blur_x", "frame": 1, "easing": "CubicOut"})); + self.run("motion.set_ease", json!({"property": "filter.0.blur_x", "frame": mid + 1, "easing": {"bezier": [0.5, 0.0, 0.3, 1.0]}})); + self.s.mark_saved(); + self.show_panel(crate::dock::Panel::MotionEditor); + self.me_prop = anicraft_engine::doc::Property::from_key("filter.0.blur_x").unwrap_or(anicraft_engine::doc::Property::X); + self.me_key = Some(0); + // The filter rows in view. + self.me_vscroll = 6.0; + self.run("timeline.goto", json!({"frame": mid / 2})); + let _ = self.s.execute("edit.deselect", &json!({})); + } + } Some("motionstretch") => { // A motion span stretched by its end (ADR 0083): `motionspan`'s tween made half // as long again, its keys in proportion, and its end being dragged further. @@ -3719,6 +3752,9 @@ impl App { crate::dock_ui::save_when_settled(self, &ctx); // After this frame's edits: start a recovery copy when one is due (off this thread). autosave::tick(self, &ctx); + // The graphics driver's trouble: autosave at once, or close to open again (ADR 0092). + #[cfg(not(target_arch = "wasm32"))] + crate::gpu_watch::tick(self, &ctx); // Open Recent changed (an open, a save, a pin): into the preferences. crate::recent::sync(self); crate::brush_panel::sync(self); diff --git a/src/autosave.rs b/src/autosave.rs index 61b8e7c5..1e8a7209 100644 --- a/src/autosave.rs +++ b/src/autosave.rs @@ -135,6 +135,22 @@ impl Recovery { self.show = self.show && !self.found.is_empty(); } + /// Writes a copy of unsaved work now, without waiting for the interval (the graphics driver + /// reported trouble, ADR 0092: the next thing may be the window going). Whether one was + /// started; nothing to do when the newest copy already holds this state. + pub fn write_now(&mut self, s: &anicraft_engine::Session) -> bool { + let Some(saver) = &mut self.saver else { return false }; + if !s.is_dirty() || self.written == Some(s.state) { + return false; + } + saver.write(s.doc.clone(), s.path.as_deref()); + self.has_copy = true; + self.written = Some(s.state); + self.rev_at_copy = s.revision; + self.dirty_since = None; + true + } + /// Ends the session: a clean exit removes this session's copy; anything else (unsaved work /// the user didn't decide about) is written one last time for the next start. pub fn finish(&mut self, s: &anicraft_engine::Session, clean: bool) { diff --git a/src/dialogs.rs b/src/dialogs.rs index ecb3a3c0..472e019c 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -506,6 +506,8 @@ fn preferences(app: &mut App, ctx: &egui::Context) { State::Running { adapter, direct: true } => Some(tr!("Drawing on {adapter}, straight into the window.", adapter = adapter)), State::Running { adapter, direct: false } => Some(tr!("Drawing on {adapter}, then copied to the window (slower: the window's graphics device can't be shared).", adapter = adapter)), State::Failed(why) => Some(tr!("The graphics card can't draw the stage, so the CPU does: {why}", why = why)), + State::Stopped { why, retry_at: Some(_) } => Some(tr!("The graphics card stopped drawing the stage, so the CPU does for now; AniCraft tries the graphics card again soon. It said: {why}", why = why)), + State::Stopped { why, retry_at: None } => Some(tr!("The graphics card stopped drawing the stage, so the CPU does for the rest of this session. It said: {why}", why = why)), }; if crate::gpu_stage::wanted(p.stage_renderer) != p.stage_renderer { form_note(ui, LW, text(Type::Caption, tr!("ANICRAFT_STAGE_RENDERER is set, and it takes precedence over this choice."))); diff --git a/src/gpu_stage.rs b/src/gpu_stage.rs index 142dde27..93ebdd83 100644 --- a/src/gpu_stage.rs +++ b/src/gpu_stage.rs @@ -14,6 +14,14 @@ //! can't (the window on OpenGL, or the window's device lacks what the stage needs) it opens a //! device of its own and reads the tiles back, as in the first slice. //! +//! **Failing mid-session (ADR 0092).** When the renderer breaks while drawing (its device lost, +//! an error in a frame, out of graphics memory), the CPU takes the stage over at once (the +//! frame being drawn is drawn again by the oracle), the status bar says so and the log says +//! why. The GPU is tried again later, after a growing pause ([`RETRY_SECS`]), or sooner when +//! the stage changes size; a renderer that then runs [`STABLE_SECS`] without trouble starts the +//! count afresh. When the window's own device was lost there is nothing to retry on: the window +//! closes to open again another way (`gpu_watch`). +//! //! `ANICRAFT_STAGE_RENDERER=gpu|cpu` overrides the preference (also in `--screenshot` runs, //! which otherwise use default preferences). @@ -21,7 +29,7 @@ use crate::prefs::StageRenderer; use anicraft_engine::render_service::{NativeImage, RenderService}; /// Where the GPU stage is. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] #[cfg_attr(not(gpu_stage), allow(dead_code))] pub enum State { /// The CPU draws (by choice, or because this build has no GPU stage). @@ -29,8 +37,80 @@ pub enum State { Starting, /// Drawing, on this adapter; `direct` when straight into the window's textures. Running { adapter: String, direct: bool }, - /// Could not start or stopped working; the CPU draws. The reason, for Preferences. + /// Could not start; the CPU draws. The reason, for Preferences. Failed(String), + /// Stopped working mid-session (ADR 0092); the CPU draws. Why, and when the GPU is tried + /// again (app time, seconds; `None`: not again this session). + Stopped { why: String, retry_at: Option }, +} + +/// What happened to the GPU stage this frame, for the status bar. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(not(gpu_stage), allow(dead_code))] +pub enum Notice { + /// It stopped and the CPU draws now; the GPU is tried again in this many seconds (`None`: + /// not again this session). + Stopped { retry_in: Option }, + /// It was tried again and draws again. + Back, +} + +/// Pauses before trying the GPU stage again after each failure in a row (seconds); after the +/// last the CPU keeps the stage for the session. +pub const RETRY_SECS: [f64; 4] = [3.0, 15.0, 60.0, 300.0]; +/// A renderer that draws this long without failing starts the count of failures afresh. +pub const STABLE_SECS: f64 = 600.0; +/// A change of the stage's size brings a retry forward, but never sooner than this after the +/// failure. +pub const RESIZE_SOONEST_SECS: f64 = 1.0; + +/// When to try the GPU again (ADR 0092): a bounded backoff. Pure, so its rules are tested. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Retry { + /// Failures in a row (since the last stable run). + failures: u32, + failed_at: Option, + /// When the next try is due. + at: Option, + running_since: Option, +} + +impl Retry { + /// The renderer failed at `now`: when it is tried again, or `None` when it has failed too + /// often in a row. + pub fn failed(&mut self, now: f64) -> Option { + if self.running_since.is_some_and(|t| now - t >= STABLE_SECS) { + self.failures = 0; + } + self.running_since = None; + self.failed_at = Some(now); + let wait = RETRY_SECS.get(self.failures as usize).copied(); + self.failures = self.failures.saturating_add(1); + self.at = wait.map(|w| now + w); + self.at + } + + /// Whether a try is due at `now` (`resized`: the stage changed size this frame). + pub fn due(&self, now: f64, resized: bool) -> bool { + let Some(at) = self.at else { return false }; + now >= at || (resized && self.failed_at.is_some_and(|f| now - f >= RESIZE_SOONEST_SECS)) + } + + /// A try began: no other is due until it ends. + pub fn trying(&mut self) { + self.at = None; + } + + /// The renderer is drawing again (or for the first time). + pub fn running(&mut self, now: f64) { + self.at = None; + self.running_since = Some(now); + } + + #[cfg(test)] + pub fn failures(&self) -> u32 { + self.failures + } } /// Whether this build has the GPU stage at all. @@ -81,12 +161,16 @@ impl GpuStage { /// Applies the choice to the render service (called every frame; cheap when nothing /// changes). Starting the renderer happens on its own thread and repaints when done. + /// `size` is the stage's in pixels (a change brings a retry forward). What happened, for + /// the status bar. #[allow(unused_variables)] - pub fn sync(&mut self, pref: StageRenderer, svc: &RenderService, ctx: &egui::Context) { + pub fn sync(&mut self, pref: StageRenderer, svc: &RenderService, ctx: &egui::Context, size: (u32, u32)) -> Option { // Unit tests never open a graphics device (as they never open an audio one): a start-up // thread still inside the driver when the test process exits can crash it. #[cfg(gpu_stage)] - self.imp.sync(wanted(pref) == StageRenderer::Gpu && !cfg!(test), svc, ctx); + return self.imp.sync(wanted(pref) == StageRenderer::Gpu && !cfg!(test), svc, ctx, ctx.input(|i| i.time), size); + #[cfg(not(gpu_stage))] + None } /// Shows a picture the GPU drew into a texture: registers it with the window's renderer. @@ -100,24 +184,87 @@ impl GpuStage { } } +/// The status bar's words for a notice. +pub fn notice_text(n: &Notice) -> String { + match n { + Notice::Stopped { retry_in: Some(s) } => tr!("The graphics card stopped drawing the stage, so the CPU draws it now; AniCraft tries the graphics card again in {seconds} s.", seconds = s.round() as u32), + Notice::Stopped { retry_in: None } => tr!("The graphics card stopped drawing the stage, so the CPU draws it for the rest of this session.").into(), + Notice::Back => tr!("The graphics card draws the stage again.").into(), + } +} + #[cfg(gpu_stage)] mod imp { - use super::{NativeTile, State}; + use super::{NativeTile, Notice, Retry, State}; use anicraft_engine::render_service::{NativeImage, Raster, Rasterizer, RenderService}; use anicraft_gpu::{GpuError, GpuRenderer, GpuTexture, Output}; use eframe::egui_wgpu::{RenderState, Renderer}; use std::sync::{Arc, mpsc}; - pub struct Imp { + /// What the stage needs of a renderer: [`GpuRenderer`], or a stand-in in tests. + pub trait StageDevice: Send + Sync + 'static { + fn adapter(&self) -> String; + /// Whether it draws on the window's device. + fn shared(&self) -> bool; + fn broken(&self) -> Option; + fn fail(&self, why: &str); + fn rasterizer(self: Arc) -> Rasterizer; + } + + impl StageDevice for GpuRenderer { + fn adapter(&self) -> String { + self.adapter.clone() + } + fn shared(&self) -> bool { + self.shared + } + fn broken(&self) -> Option { + GpuRenderer::broken(self) + } + fn fail(&self, why: &str) { + GpuRenderer::fail(self, why); + } + fn rasterizer(self: Arc) -> Rasterizer { + let g = self; + let why = |e: GpuError| match e { + GpuError::NeedsFull(why) => why.to_string(), + e => e.to_string(), + }; + if g.shared { + Arc::new(move |dl, view| match g.render_texture(dl, view) { + Ok(t) => { + let (width, height, stats) = (t.width, t.height, t.stats); + Ok((Raster::Native { image: Arc::new(t), width, height }, stats)) + } + Err(e) => Err(why(e)), + }) + } else { + Arc::new(move |dl, view| match g.render(dl, view, Output::Premul8) { + Ok(f) => Ok((Raster::Premul8(f.premul8), f.stats)), + Err(e) => Err(why(e)), + }) + } + } + } + + /// Opens a renderer (on its own thread). + pub type Starter = Arc) -> Result + Send + Sync>; + + pub struct Imp { pub state: State, pub window: Option, - renderer: Option>, - starting: Option>>, + renderer: Option>, + starting: Option>>, + retry: Retry, + size: Option<(u32, u32)>, + starter: Starter, + /// The window's device's loss, if it happened (`gpu_watch`). + window_lost: fn() -> Option, } impl Default for Imp { fn default() -> Self { - Imp { state: State::Off, window: None, renderer: None, starting: None } + Imp::with(Arc::new(start), crate::gpu_watch::lost) } } @@ -150,16 +297,37 @@ mod imp { }) } - impl Imp { - pub fn sync(&mut self, want: bool, svc: &RenderService, ctx: &egui::Context) { + impl Imp { + pub fn with(starter: Starter, window_lost: fn() -> Option) -> Self { + Imp { state: State::Off, window: None, renderer: None, starting: None, retry: Retry::default(), size: None, starter, window_lost } + } + + /// One frame at app time `now` (seconds) with the stage `size` pixels: starts, checks + /// and (after a failure) retries the renderer, and gives the render service the + /// rasterizer that should draw. What happened, for the status bar. + pub fn sync(&mut self, want: bool, svc: &RenderService, ctx: &egui::Context, now: f64, size: (u32, u32)) -> Option { + let mut notice = None; + let resized = self.size.is_some_and(|s| s != size); + self.size = Some(size); if let Some(rx) = &self.starting && let Ok(r) = rx.try_recv() { self.starting = None; + let retrying = matches!(self.state, State::Stopped { .. }); match r { Ok(g) => { - crate::startup::line(&format!("stage on the GPU: {}", g.adapter)); + crate::startup::line(&format!("stage on the GPU{}: {}", if retrying { " again" } else { "" }, g.adapter())); self.renderer = Some(Arc::new(g)); + self.retry.running(now); + if retrying { + notice = Some(Notice::Back); + } + } + // A retry that can't start waits longer, as a failure does. + Err(e) if retrying => { + let retry_at = self.retry.failed(now); + crate::startup::line(&format!("the GPU stage did not start again ({e}); {}", retry_line(retry_at, now))); + self.state = State::Stopped { why: e, retry_at }; } Err(e) => { crate::startup::line(&format!("the stage is drawn on the CPU: {e}")); @@ -167,53 +335,60 @@ mod imp { } } } + let window_lost = (self.window_lost)(); + if let Some(g) = &self.renderer + && g.shared() + && let Some(w) = &window_lost + { + g.fail(&format!("the window's graphics device was lost: {w}")); // i18n-exempt: the driver's reason, as GPU errors are + } if let Some(g) = &self.renderer && let Some(e) = g.broken() { self.renderer = None; - crate::startup::line(&format!("the GPU stage stopped, the CPU draws: {e}")); - self.state = State::Failed(e); + // Nothing to retry on when the window's device is gone (the window reopens). + let retry_at = if window_lost.is_some() { None } else { self.retry.failed(now) }; + crate::startup::line(&format!("the GPU stage stopped, the CPU draws: {e}; {}", retry_line(retry_at, now))); + self.state = State::Stopped { why: e, retry_at }; + notice = Some(Notice::Stopped { retry_in: retry_at.map(|t| t - now) }); } - if want && self.renderer.is_none() && self.starting.is_none() && !matches!(self.state, State::Failed(_)) { + let retry_due = matches!(self.state, State::Stopped { .. }) && window_lost.is_none() && self.retry.due(now, resized); + let fresh = !matches!(self.state, State::Failed(_) | State::Stopped { .. }); + if want && self.renderer.is_none() && self.starting.is_none() && (fresh || retry_due) { let (tx, rx) = mpsc::channel(); - let ctx = ctx.clone(); + let c = ctx.clone(); let window = self.window.clone(); + let starter = self.starter.clone(); let spawned = std::thread::Builder::new().name("anicraft-gpu-start".into()).spawn(move || { - let _ = tx.send(start(window)); - ctx.request_repaint(); + let _ = tx.send(starter(window)); + c.request_repaint(); }); match spawned { Ok(_) => { self.starting = Some(rx); - self.state = State::Starting; + if retry_due { + self.retry.trying(); + crate::startup::line("trying the GPU stage again"); // i18n-exempt: log text + if let State::Stopped { retry_at, .. } = &mut self.state { + *retry_at = None; + } + } else { + self.state = State::Starting; + } } Err(e) => self.state = State::Failed(e.to_string()), } } + // Wake for the retry even when nothing else happens. + if let State::Stopped { retry_at: Some(t), .. } = self.state { + ctx.request_repaint_after(std::time::Duration::from_secs_f64((t - now).clamp(0.05, 3600.0))); + } let drawing = self.renderer.as_ref().filter(|_| want); match (drawing, svc.has_rasterizer()) { (Some(g), false) => { let g = g.clone(); - self.state = State::Running { adapter: g.adapter.clone(), direct: g.shared }; - let why = |e: GpuError| match e { - GpuError::NeedsFull(why) => why.to_string(), - e => e.to_string(), - }; - let raster: Rasterizer = if g.shared { - Arc::new(move |dl, view| match g.render_texture(dl, view) { - Ok(t) => { - let (width, height, stats) = (t.width, t.height, t.stats); - Ok((Raster::Native { image: Arc::new(t), width, height }, stats)) - } - Err(e) => Err(why(e)), - }) - } else { - Arc::new(move |dl, view| match g.render(dl, view, Output::Premul8) { - Ok(f) => Ok((Raster::Premul8(f.premul8), f.stats)), - Err(e) => Err(why(e)), - }) - }; - svc.set_rasterizer(Some(raster)); + self.state = State::Running { adapter: g.adapter(), direct: g.shared() }; + svc.set_rasterizer(Some(g.rasterizer())); ctx.request_repaint(); } (None, true) => { @@ -222,9 +397,10 @@ mod imp { } _ => {} } - if !want && !matches!(self.state, State::Failed(_)) { + if !want && !matches!(self.state, State::Failed(_) | State::Stopped { .. }) { self.state = State::Off; } + notice } pub fn register(&self, native: &NativeImage) -> Option { @@ -235,4 +411,215 @@ mod imp { Some(NativeTile { id, _keep: Registered { id, renderer: rs.renderer.clone(), _texture: native.clone() } }) } } + + fn retry_line(retry_at: Option, now: f64) -> String { + match retry_at { + Some(t) => format!("trying the GPU again in {:.0} s", t - now), // i18n-exempt: log text + None => "not trying the GPU again this session".into(), // i18n-exempt: log text + } + } + + /// ADR 0092: the stage's fallback driven by an injected device loss, with a stand-in + /// renderer (unit tests never open a graphics device). + #[cfg(test)] + mod tests { + use super::*; + use anicraft_engine::doc::sample; + use anicraft_engine::render_service::DEFAULT_CACHE_BYTES; + use std::sync::Mutex; + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + + /// Draws by asking the CPU oracle, and fails like a lost device once told to. + struct Fake { + broken: Arc>>, + } + + impl StageDevice for Fake { + fn adapter(&self) -> String { + "Test GPU (Vulkan)".into() + } + fn shared(&self) -> bool { + false + } + fn broken(&self) -> Option { + self.broken.lock().ok().and_then(|g| g.clone()) + } + fn fail(&self, why: &str) { + if let Ok(mut g) = self.broken.lock() { + g.get_or_insert_with(|| why.to_string()); + } + } + fn rasterizer(self: Arc) -> Rasterizer { + Arc::new(move |dl, view| { + if let Some(e) = self.broken() { + return Err(format!("GPU error: {e}")); + } + let (p, st) = anicraft_engine::render::render(dl, view).map_err(|e| e.to_string())?; + Ok((Raster::Premul8(p.to_premul_rgba8()), st)) + }) + } + } + + static STARTS: AtomicU32 = AtomicU32::new(0); + static START_FAILS: AtomicBool = AtomicBool::new(false); + /// The newest stand-in's failure, for the test to set (as a driver would). + static LAST: Mutex>>>> = Mutex::new(None); + + fn lose(why: &str) { + if let Some(b) = LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref() { + *b.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(why.to_string()); + } + } + + fn no_window_loss() -> Option { + None + } + + fn window_lost() -> Option { + Some("DXGI_ERROR_DEVICE_REMOVED".into()) + } + + fn imp(lost: fn() -> Option) -> Imp { + Imp::with( + Arc::new(|_| { + STARTS.fetch_add(1, Ordering::SeqCst); + if START_FAILS.load(Ordering::SeqCst) { + return Err("no usable GPU: the driver is resetting".into()); + } + let broken = Arc::new(Mutex::new(None)); + *LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(broken.clone()); + Ok(Fake { broken }) + }), + lost, + ) + } + + /// Frames until the start thread has answered (bounded). + fn settle(m: &mut Imp, svc: &RenderService, ctx: &egui::Context, now: f64, size: (u32, u32)) -> Vec { + let mut out = Vec::new(); + for _ in 0..400 { + out.extend(m.sync(true, svc, ctx, now, size)); + if m.starting.is_none() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + out + } + + fn draws_on_gpu(svc: &RenderService) -> bool { + let doc = sample::demo(); + let view = anicraft_engine::render::View::stage(&doc, 0.25); + // A new document state each time, so no cached picture answers. + static STATE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let state = STATE.fetch_add(1, Ordering::SeqCst); + let img = svc.render_now_batch(vec![svc.job(state, &doc, 0, view, None)]); + let img = img.first().expect("a frame"); + assert!(img.error.is_none(), "{:?}", img.error); + img.gpu + } + + #[test] + fn a_lost_device_hands_the_stage_to_the_cpu_and_the_gpu_comes_back_later() { + let _g = crate::gpu_watch::TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + STARTS.store(0, Ordering::SeqCst); + START_FAILS.store(false, Ordering::SeqCst); + let ctx = egui::Context::default(); + let svc = RenderService::new(DEFAULT_CACHE_BYTES, None); + let mut m = imp(no_window_loss); + assert!(settle(&mut m, &svc, &ctx, 0.0, (800, 600)).is_empty()); + assert!(matches!(m.state, State::Running { .. }) && svc.has_rasterizer()); + assert!(draws_on_gpu(&svc)); + // The device is lost mid-session: the frame fails on the GPU and the CPU draws it. + lose("device lost: DXGI_ERROR_DEVICE_HUNG"); + assert!(!draws_on_gpu(&svc), "the oracle draws the failed frame"); + let n = m.sync(true, &svc, &ctx, 10.0, (800, 600)); + assert_eq!(n, Some(Notice::Stopped { retry_in: Some(super::super::RETRY_SECS[0]) })); + assert!(matches!(&m.state, State::Stopped { why, retry_at: Some(_) } if why.contains("DEVICE_HUNG"))); + assert!(!svc.has_rasterizer() && !draws_on_gpu(&svc), "the CPU draws the stage now"); + // Not tried again before its time. + assert_eq!(m.sync(true, &svc, &ctx, 11.0, (800, 600)), None); + assert_eq!(STARTS.load(Ordering::SeqCst), 1); + // Then it is, and draws again. + let n = settle(&mut m, &svc, &ctx, 13.5, (800, 600)); + assert_eq!(n, vec![Notice::Back]); + assert_eq!(STARTS.load(Ordering::SeqCst), 2); + m.sync(true, &svc, &ctx, 13.6, (800, 600)); + assert!(matches!(m.state, State::Running { .. }) && draws_on_gpu(&svc)); + // A second failure waits longer; a resize brings the try forward. + lose("device lost again"); + let n = m.sync(true, &svc, &ctx, 20.0, (800, 600)); + assert_eq!(n, Some(Notice::Stopped { retry_in: Some(super::super::RETRY_SECS[1]) })); + assert!(settle(&mut m, &svc, &ctx, 20.5, (800, 600)).is_empty() && STARTS.load(Ordering::SeqCst) == 2, "too soon even when resized"); + // A retry that can't start waits longer still, and the CPU keeps drawing. + START_FAILS.store(true, Ordering::SeqCst); + assert!(settle(&mut m, &svc, &ctx, 22.0, (1024, 600)).is_empty()); + assert_eq!(STARTS.load(Ordering::SeqCst), 3, "the resize brought it forward"); + assert!(matches!(&m.state, State::Stopped { retry_at: Some(t), .. } if (*t - (22.0 + super::super::RETRY_SECS[2])).abs() < 1e-9), "{:?}", m.state); + assert!(!svc.has_rasterizer()); + } + + #[test] + fn a_lost_window_device_is_not_retried() { + let _g = crate::gpu_watch::TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + START_FAILS.store(false, Ordering::SeqCst); + let ctx = egui::Context::default(); + let svc = RenderService::new(DEFAULT_CACHE_BYTES, None); + let mut m = imp(no_window_loss); + settle(&mut m, &svc, &ctx, 0.0, (640, 480)); + assert!(matches!(m.state, State::Running { .. })); + // The window's device goes: the stage stops for good (the window reopens). + m.window_lost = window_lost; + lose("the window's graphics device was lost"); + assert_eq!(m.sync(true, &svc, &ctx, 5.0, (640, 480)), Some(Notice::Stopped { retry_in: None })); + let before = STARTS.load(Ordering::SeqCst); + assert!(settle(&mut m, &svc, &ctx, 5000.0, (800, 480)).is_empty()); + assert_eq!(STARTS.load(Ordering::SeqCst), before); + assert!(!svc.has_rasterizer()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The backoff (ADR 0092): growing pauses, a bounded number of tries, a resize bringing a + /// try forward (not too soon), and a long good run starting the count afresh. + #[test] + fn the_gpu_is_tried_again_after_growing_pauses_and_not_for_ever() { + let mut r = Retry::default(); + assert!(!r.due(0.0, true), "nothing failed"); + assert_eq!(r.failed(100.0), Some(100.0 + RETRY_SECS[0])); + assert!(!r.due(101.0, false) && r.due(100.0 + RETRY_SECS[0], false)); + assert!(!r.due(100.5, true), "a resize right after the failure waits"); + assert!(r.due(101.5, true), "a resize a moment later tries at once"); + r.trying(); + assert!(!r.due(10_000.0, true), "one try at a time"); + // Failing again at once: each pause longer, then no more. + let mut t = 200.0; + for wait in RETRY_SECS.iter().skip(1) { + assert_eq!(r.failed(t), Some(t + wait)); + t += wait; + } + assert_eq!(r.failed(t), None, "after {} failures in a row the CPU keeps the stage", RETRY_SECS.len() + 1); + assert!(!r.due(1e9, true)); + // A renderer that ran a long while without trouble starts afresh. + let mut r = Retry::default(); + r.failed(0.0); + r.failed(10.0); + r.running(20.0); + assert_eq!(r.failed(20.0 + STABLE_SECS), Some(20.0 + STABLE_SECS + RETRY_SECS[0])); + assert_eq!(r.failures(), 1); + // And a short run doesn't. + r.running(1000.0); + assert_eq!(r.failed(1005.0), Some(1005.0 + RETRY_SECS[1])); + } + + #[test] + fn notices_read_as_sentences() { + assert!(notice_text(&Notice::Stopped { retry_in: Some(3.0) }).contains('3')); + assert!(!notice_text(&Notice::Stopped { retry_in: None }).is_empty()); + assert!(!notice_text(&Notice::Back).is_empty()); + } } diff --git a/src/gpu_watch.rs b/src/gpu_watch.rs new file mode 100644 index 00000000..508b0b31 --- /dev/null +++ b/src/gpu_watch.rs @@ -0,0 +1,296 @@ +//! Keeping the window up when the graphics driver fails mid-session (ADR 0092; #207, #255). +//! +//! wgpu treats an error nobody catches as fatal: its default handler panics, eframe unwinds and +//! the window closes, unsaved work and all. Seen under heavy GPU load: `Surface::configure` → +//! "Failed to wait for GPU to come idle before reconfiguring the Surface". So the window's +//! device gets handlers of ours ([`watch`]) that write down what happened instead of panicking: +//! an uncaptured-error handler and a device-lost callback. And the window's surface statuses go +//! through [`surface_action`], which reconfigures a surface that failed and, when that keeps +//! failing, makes a new one. +//! +//! Each frame the app reads the news ([`take_news`], [`tick`]): +//! * **an error** the driver reported: unsaved work is autosaved at once and the status bar says +//! AniCraft carried on (once a minute at most); the log has the details; +//! * **the device lost**, or the surface failing for [`STUCK_SECS`] on end: nothing can draw on +//! this device again (eframe can't make a new one), so the work is autosaved one last time, +//! the startup record ([`crate::startup::lost_mid_session`]) makes the next starts try another +//! way first, and the window closes and opens again on that way, offering the work back. +//! +//! The GPU stage hears of the device's loss through [`lost`] (a renderer sharing the window's +//! device can't install callbacks of its own: one per device), and drops to the CPU. + +use std::sync::Mutex; +use std::sync::PoisonError; +use std::time::{Duration, Instant}; + +/// Errors written to the log in full; after that, one in [`LOG_EVERY`] (a driver can report one +/// a frame). +const LOG_FIRST: u32 = 20; +const LOG_EVERY: u32 = 500; +/// A surface failing for this long without a pause counts as lost. +pub const STUCK_SECS: f32 = 8.0; +/// A pause this long between surface failures ends the streak (the window drew in between). +const STREAK_GAP: Duration = Duration::from_millis(1500); +/// Failed reconfigures in a row before the surface is made anew. +const RECREATE_AFTER: u32 = 3; +/// The status bar says the driver reported a problem at most this often. +const NOTICE_EVERY_SECS: f64 = 60.0; + +#[derive(Default)] +struct Health { + /// Errors the driver reported (uncaptured), and the newest one's text. + errors: u32, + last_error: Option, + /// Errors not yet seen by the app. + unseen: bool, + /// The device's loss, with the driver's words. + lost: Option, + /// The surface's current run of failures: since when, the latest, and how many reconfigures + /// in a row failed. + failing_since: Option, + last_failure: Option, + in_a_row: u32, + /// The app was told the device is gone (so it acts once). + handled: bool, + /// When the app last said so in the status bar (app time). + noticed_at: Option, +} + +static HEALTH: Mutex> = Mutex::new(None); + +fn with(f: impl FnOnce(&mut Health) -> R) -> R { + let mut g = HEALTH.lock().unwrap_or_else(PoisonError::into_inner); + f(g.get_or_insert_with(Health::default)) +} + +/// Notes an error the driver reported (never panics; the log gets the first ones in full). +pub fn record_error(text: &str) { + let n = with(|h| { + h.errors = h.errors.saturating_add(1); + h.last_error = Some(text.chars().take(2000).collect()); + h.unseen = true; + h.errors + }); + if n <= LOG_FIRST || n.is_multiple_of(LOG_EVERY) { + crate::startup::line(&format!("graphics error {n} (AniCraft carried on): {}", text.trim())); + } +} + +/// Notes that the device was lost (a driver reset, or the GPU taken away). +pub fn record_lost(why: &str) { + let first = with(|h| { + let first = h.lost.is_none(); + h.lost.get_or_insert_with(|| why.chars().take(2000).collect()); + first + }); + if first { + crate::startup::line(&format!("the window's graphics device was lost: {}", why.trim())); + } +} + +/// The device's loss, if it happened (the GPU stage then stops using the window's device). +pub fn lost() -> Option { + with(|h| h.lost.clone()) +} + +/// What the window's surface said when a frame couldn't be had (the cases of +/// `wgpu::CurrentSurfaceTexture` other than success). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Surface { + Timeout, + Occluded, + Outdated, + Lost, + /// An error inside the call (it went to the error handler): for one, the surface could not + /// be configured, and every frame fails until it is. + Validation, +} + +/// What to do about a frame the surface couldn't give, the `in_a_row`-th failed reconfigure +/// in a row: reconfigure it (the next frame tries again), make a new surface when reconfiguring +/// keeps failing or the surface is gone, and skip the frame while the window is hidden or the +/// GPU is busy. +pub fn surface_action(s: Surface, in_a_row: u32) -> eframe::egui_wgpu::SurfaceErrorAction { + use eframe::egui_wgpu::SurfaceErrorAction as A; + match s { + Surface::Occluded | Surface::Timeout => A::SkipFrame, + Surface::Lost => A::RecreateSurface, + Surface::Outdated | Surface::Validation if in_a_row >= RECREATE_AFTER => A::RecreateSurface, + Surface::Outdated | Surface::Validation => A::Reconfigure, + } +} + +/// eframe's surface-status callback (set on every wgpu attempt, [`crate::startup::Attempt::options`]). +pub fn on_surface_status(status: &eframe::wgpu::CurrentSurfaceTexture) -> eframe::egui_wgpu::SurfaceErrorAction { + use eframe::wgpu::CurrentSurfaceTexture as C; + let s = match status { + C::Timeout => Surface::Timeout, + C::Occluded => Surface::Occluded, + C::Outdated => Surface::Outdated, + C::Lost => Surface::Lost, + // Success and Suboptimal never come here (egui draws those frames). + _ => Surface::Validation, + }; + let now = Instant::now(); + let in_a_row = with(|h| { + if s == Surface::Occluded { + return 0; + } + if h.last_failure.is_none_or(|t| now.duration_since(t) > STREAK_GAP) { + h.failing_since = Some(now); + h.in_a_row = 0; + } + h.last_failure = Some(now); + if matches!(s, Surface::Validation | Surface::Outdated) { + h.in_a_row = h.in_a_row.saturating_add(1); + } + h.in_a_row + }); + let action = surface_action(s, in_a_row); + let recreate = matches!(action, eframe::egui_wgpu::SurfaceErrorAction::RecreateSurface); + // The first of a run, and each new surface: a failing surface would otherwise log a line a frame. + if (s == Surface::Validation && in_a_row <= 1) || recreate { + crate::startup::line(&format!("the window's surface: {s:?}, {} ({in_a_row} in a row)", match action { + eframe::egui_wgpu::SurfaceErrorAction::Reconfigure => "reconfiguring it", // i18n-exempt: log text + eframe::egui_wgpu::SurfaceErrorAction::RecreateSurface => "making it anew", // i18n-exempt: log text + eframe::egui_wgpu::SurfaceErrorAction::SkipFrame => "skipping the frame", // i18n-exempt: log text + })); + } + if in_a_row >= RECREATE_AFTER { + with(|h| h.in_a_row = 0); + } + action +} + +/// Installs our handlers on the window's device: errors and the device's loss are written down +/// (and the window woken to act on them) instead of panicking. +pub fn watch(device: &eframe::wgpu::Device, ctx: &egui::Context) { + let c = ctx.clone(); + device.on_uncaptured_error(std::sync::Arc::new(move |e: eframe::wgpu::Error| { + record_error(&e.to_string()); + c.request_repaint(); + })); + let c = ctx.clone(); + device.set_device_lost_callback(move |reason, msg| { + // Dropping the device on purpose (closing the window) isn't a failure. + if reason != eframe::wgpu::DeviceLostReason::Destroyed { + record_lost(&msg); + } + c.request_repaint(); + }); +} + +/// What happened since the app last looked. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct News { + /// A new error the driver reported, the newest. + pub error: Option, + /// The device is gone (lost, or its surface failing for [`STUCK_SECS`] on end): the window + /// must close. Said once. + pub gone: Option, + /// The surface is failing right now (the app keeps waking to see it through). + pub failing: bool, +} + +/// The news for this frame. +pub fn take_news() -> News { + let now = Instant::now(); + with(|h| { + let error = if std::mem::take(&mut h.unseen) { h.last_error.clone() } else { None }; + let failing = h.last_failure.is_some_and(|t| now.duration_since(t) <= STREAK_GAP); + let stuck = failing && h.failing_since.is_some_and(|t| now.duration_since(t).as_secs_f32() >= STUCK_SECS); + let gone_now = h.lost.clone().or_else(|| stuck.then(|| format!("the window's surface kept failing for {STUCK_SECS} s"))); // i18n-exempt: log text + let gone = if h.handled { None } else { gone_now }; + if gone.is_some() { + h.handled = true; + } + News { error, gone, failing } + }) +} + +/// Whether the status bar should say so now (at most once a minute). +fn notice_due(at: f64) -> bool { + with(|h| { + let due = h.noticed_at.is_none_or(|t| at - t >= NOTICE_EVERY_SECS || at < t); + if due { + h.noticed_at = Some(at); + } + due + }) +} + +/// Per frame (desktop): acts on the news. A reported error autosaves at once and says so; a +/// device gone saves the work for the next window, records how it went, and closes this one so +/// it can open again another way ([`crate::startup::ask_reopen`]). +pub fn tick(app: &mut crate::app::App, ctx: &egui::Context) { + let news = take_news(); + if news.error.is_some() || news.failing { + app.recovery.write_now(&app.s); + } + if news.failing { + ctx.request_repaint_after(Duration::from_millis(500)); + } + if news.error.is_some() && news.gone.is_none() && app.shot.is_none() && notice_due(ctx.input(|i| i.time)) { + app.status_err(tr!("The graphics driver reported a problem; AniCraft carried on and autosaved your work (the details are in anicraft.log).")); + } + let Some(why) = news.gone else { return }; + crate::startup::line(&format!("closing the window to open it again another way ({why})")); + // The work goes to the recovery folder for the next window (the lock goes, so it finds it). + app.recovery.finish(&app.s, false); + crate::startup::lost_mid_session(); + // A saved document opens again as it was; unsaved work is offered back. + let file = app.s.path.clone().filter(|_| !app.s.is_dirty()); + crate::startup::ask_reopen(file); + app.allow_close = true; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); +} + +/// Tests that touch the process's graphics health take turns. +#[cfg(test)] +pub static TEST_LOCK: Mutex<()> = Mutex::new(()); + +/// Tests: forget everything (the state is the process's). +#[cfg(test)] +pub fn reset() { + *HEALTH.lock().unwrap_or_else(PoisonError::into_inner) = None; +} + +#[cfg(test)] +mod tests { + use super::*; + use eframe::egui_wgpu::SurfaceErrorAction as A; + + /// The surface policy: a failed configure (the error of #255) is retried by reconfiguring, + /// then by a new surface; a hidden window or a busy GPU skips the frame. + #[test] + fn a_failing_surface_is_reconfigured_then_made_anew() { + assert!(matches!(surface_action(Surface::Validation, 1), A::Reconfigure)); + assert!(matches!(surface_action(Surface::Outdated, 2), A::Reconfigure)); + assert!(matches!(surface_action(Surface::Validation, RECREATE_AFTER), A::RecreateSurface)); + assert!(matches!(surface_action(Surface::Lost, 0), A::RecreateSurface)); + assert!(matches!(surface_action(Surface::Occluded, 9), A::SkipFrame)); + assert!(matches!(surface_action(Surface::Timeout, 0), A::SkipFrame)); + } + + /// Errors and the device's loss are written down, never a panic; the app hears of each + /// once. + #[test] + fn errors_and_the_loss_come_to_the_app_once() { + let _g = TEST_LOCK.lock().unwrap_or_else(PoisonError::into_inner); + reset(); + assert_eq!(take_news(), News::default()); + record_error("Failed to wait for GPU to come idle before reconfiguring the Surface"); + let n = take_news(); + assert!(n.error.as_deref().is_some_and(|e| e.contains("come idle")) && n.gone.is_none()); + assert_eq!(take_news().error, None, "said once"); + assert_eq!(lost(), None); + record_lost("Device lost: DXGI_ERROR_DEVICE_HUNG"); + record_lost("a second loss keeps the first reason"); + assert_eq!(lost().as_deref(), Some("Device lost: DXGI_ERROR_DEVICE_HUNG")); + assert!(take_news().gone.is_some()); + assert_eq!(take_news().gone, None, "the app acts once"); + // The notice comes at most once a minute. + assert!(notice_due(10.0) && !notice_due(30.0) && notice_due(75.0)); + reset(); + } +} diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index df80706d..83167b8c 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -122,6 +122,9 @@ fn all_keys() -> BTreeSet { } add(&doc::Easing::Linear.label()); doc::Property::ALL.iter().for_each(|p| add(p.label())); + doc::FilterParam::ALL.iter().for_each(|p| add(p.label())); + add("Filters"); + add("Filter"); doc::ColorStyle::ALL.iter().for_each(|s| add(s.label())); doc::EaseFamily::ALL.iter().for_each(|f| add(f.label())); doc::EaseDir::ALL.iter().for_each(|d| add(d.label())); diff --git a/src/main.rs b/src/main.rs index 63f76352..f9931a63 100644 --- a/src/main.rs +++ b/src/main.rs @@ -48,6 +48,8 @@ mod dock_ui; mod drop; mod ease_editor; mod gpu_stage; +#[cfg(not(target_arch = "wasm32"))] +mod gpu_watch; mod gradient_tool; mod icons; mod keymap; @@ -308,31 +310,60 @@ fn main() -> eframe::Result { // The window: the graphics asked for, then this platform's order down to OpenGL. A way that // fails or panics before the window is up falls through to the next; a start that died // inside a driver last time tries that way last (#207, `startup`). - let died_in = startup::begin(platform::log_dir()); - let attempts = startup::plan(platform::forced_backend(renderer.as_deref()), prefs::Prefs::load().window_backend, &platform::window_attempts(platform::OS), died_in.as_deref()); + let mut last = startup::begin(platform::log_dir()); + let mut file = file; + let mut reopened = 0; let mut why = String::from("no attempt"); // i18n-exempt: log text - for (n, attempt) in attempts.iter().enumerate() { - startup::trying(attempt, n + 1, attempts.len()); - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(*attempt, file.as_deref(), shot.clone(), open.clone(), look.clone()))); - why = match result { - Ok(Ok(())) => { - startup::line("closed"); - return Ok(()); + // Once, and again each time the window closed to reopen another way. + let mut opening = true; + while opening { + opening = false; + let attempts = startup::plan(platform::forced_backend(renderer.as_deref()), prefs::Prefs::load().window_backend, &platform::window_attempts(platform::OS), &last); + for (n, attempt) in attempts.iter().enumerate() { + startup::trying(attempt, n + 1, attempts.len()); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(*attempt, file.as_deref(), shot.clone(), open.clone(), look.clone()))); + why = match result { + Ok(Ok(())) => { + // The window's graphics device was lost mid-session (ADR 0092): it closed + // with the work autosaved, to open again another way, which offers it back. + if let Some(reopen) = startup::take_reopen() + && reopened < MAX_REOPENS + { + reopened += 1; + startup::line(&format!("opening the window again, {} last", attempt.label())); + last.retain(|l| *l != attempt.label()); + last.push(attempt.label()); + file = reopen; + opening = true; + break; + } + startup::line("closed"); + return Ok(()); + } + Ok(Err(e)) => e.to_string(), + Err(p) => format!("{} panicked: {}", attempt.label(), startup::panic_text(p.as_ref())), // i18n-exempt: a log line + }; + startup::line(&format!("{} failed: {why}", attempt.label())); + // It ran and then stopped: not a start-up problem, and opening a second window would + // surprise (autosave offers the work back next time). A graphics failure makes the + // next starts try this way late (ADR 0092). + if startup::started() { + if startup::is_graphics_failure(&why) { + startup::lost_mid_session(); + } + return Err(eframe::Error::AppCreation(why.into())); } - Ok(Err(e)) => e.to_string(), - Err(p) => format!("{} panicked: {}", attempt.label(), startup::panic_text(p.as_ref())), // i18n-exempt: a log line - }; - startup::line(&format!("{} failed: {why}", attempt.label())); - // It ran and then stopped: not a start-up problem, and opening a second window would - // surprise (autosave offers the work back next time). - if startup::started() { - return Err(eframe::Error::AppCreation(why.into())); } } startup::give_up(&why); Err(eframe::Error::AppCreation(why.into())) } +/// Times one run opens the window again after its graphics device was lost (ADR 0092); past +/// that it closes, and the next start offers the work back. +#[cfg(not(target_arch = "wasm32"))] +const MAX_REOPENS: u32 = 2; + #[cfg(test)] mod args_tests { use super::*; diff --git a/src/motion_editor.rs b/src/motion_editor.rs index 3572a269..baecda19 100644 --- a/src/motion_editor.rs +++ b/src/motion_editor.rs @@ -14,11 +14,14 @@ //! On X and Y, the keys of frames pinned to a motion path point (ADR 0049) are drawn in the //! motion colour: they are the point's place and its timing, so dragging one moves the point on //! the stage, and removing one unpins it. +//! +//! Below the colour effect, each filter of the object (ADR 0092) lists its numbers under the +//! filter's name (Blur X, Blur Y, Strength…), curves and keys like the other properties. use crate::a11y::{self, Named}; use crate::app::App; use crate::theme::{SQUARE, T, TARGET, Type, color, font, text, with_type}; -use anicraft_engine::doc::{ColorStyle, Easing, MotionTween, Pin, Property, Props, Track}; +use anicraft_engine::doc::{ColorStyle, Easing, Element, ElementKind, MotionTween, Pin, Property, Props, Track, filter_properties, own_value}; use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, WidgetType, pos2, vec2}; use serde_json::json; @@ -60,14 +63,36 @@ pub enum MeDrag { Scrub, } -/// The motion tween at the playhead on the active layer: its first frame, length and data, and -/// the colour effect styles it shows (ADR 0056). -fn current(app: &App) -> Option<(u32, u32, MotionTween, Props, Vec)> { +/// The motion tween at the playhead on the active layer: its first frame, length and data, the +/// colour effect styles it shows (ADR 0056), and its object. +fn current(app: &App) -> Option<(u32, u32, MotionTween, Props, Vec, Element)> { let k = app.s.active_layer()?.keyframe_at(app.s.frame)?; let m = k.motion.clone()?; let target = m.target_index(&k.elements).and_then(|i| k.elements.get(i))?; let styles = m.colour_styles(&target.color); - Some((k.start, k.duration, m, Props::of(target), styles)) + Some((k.start, k.duration, m, Props::of(target), styles, (**target).clone())) +} + +/// A row of the property list: a property, or the name of a filter above its numbers. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Row { + Prop(Property), + /// A filter's place, name and whether it is on. + Filter(u8, &'static str, bool), +} + +/// The rows: [`listed`]'s properties, then each filter of the object with its numbers. +fn rows_for(used: &[ColorStyle], added: &[ColorStyle], target: &Element) -> Vec { + let mut out: Vec = listed(used, added).into_iter().map(Row::Prop).collect(); + let ElementKind::Symbol { filters, .. } = &target.kind else { return out }; + let mut props = filter_properties(target).into_iter().peekable(); + for (slot, e) in filters.iter().enumerate() { + out.push(Row::Filter(slot as u8, e.filter.label(), e.enabled)); + while let Some(p) = props.next_if(|p| p.filter().is_some_and(|f| usize::from(f.slot) == slot)) { + out.push(Row::Prop(p)); + } + } + out } /// The properties the list shows: position and transform, and the colour effect styles the @@ -139,7 +164,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.rect_filled(body, 0.0, T.panel); painter.line_segment([body.left_top(), body.right_top()], Stroke::new(1.0, T.border)); - let Some((start, frames, m, base, used)) = current(app) else { + let Some((start, frames, m, base, used, target)) = current(app) else { empty_state(app, ui, body); return; }; @@ -163,17 +188,23 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.text(pos2(list.left() + 10.0, list.top() + RULER_H * 0.5), Align2::LEFT_CENTER, tr!("Property"), font(Type::Heading), color(Type::Heading)); painter.text(pos2(list.right() - 44.0, list.top() + RULER_H * 0.5), Align2::RIGHT_CENTER, tr!("Frame {frame}", frame = app.s.frame + 1), font(Type::DataSmall), color(Type::DataSmall)); let now = m.props_at(&base, offset as f32); + // The object at the playhead, for its filters' numbers (ADR 0092). + let at = m.apply(&target, offset as f32); + // A property's own value (its base) and its value at the playhead. + let own = |p: Property| if p.is_filter() { own_value(&target, p).unwrap_or(0.0) } else { base.get(p) }; + let now_of = |p: Property| if p.is_filter() { own_value(&at, p).unwrap_or(0.0) } else { now.get(p) }; // Frames pinned to path points: their X and Y keys are the points' places (ADR 0049). let pins = m.pinned_anchors(&base); let pin_at = |p: Property, f: u32| pins.iter().find(|q| q.frame == f).copied().filter(|_| matches!(p, Property::X | Property::Y)); let rows_top = list.top() + RULER_H; // Rows that don't fit scroll with the wheel over the list. let fit = (((list.bottom() - rows_top) / ROW_H).floor() as usize).max(1); - let rows = listed(&used, &app.me_styles); + let list_rows = rows_for(&used, &app.me_styles, &target); + let rows: Vec = list_rows.iter().filter_map(|r| if let Row::Prop(p) = r { Some(*p) } else { None }).collect(); if !rows.contains(&app.me_prop) { app.me_prop = Property::X; } - let n = rows.len(); + let n = list_rows.len(); if ui.rect_contains_pointer(list) { let d = ui.input(|i| i.smooth_scroll_delta.y); app.me_vscroll = (app.me_vscroll - d / ROW_H).clamp(0.0, n.saturating_sub(fit) as f32); @@ -181,9 +212,23 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.me_vscroll = app.me_vscroll.min(n.saturating_sub(fit) as f32); let first = app.me_vscroll.floor() as usize; let mut last_group = ""; - for (r, p) in rows.iter().copied().enumerate().skip(first).take(fit) { + for (r, item) in list_rows.iter().copied().enumerate().skip(first).take(fit) { let y = rows_top + (r - first) as f32 * ROW_H; let row = Rect::from_min_size(pos2(list.left(), y), vec2(LIST_W, ROW_H)); + let p = match item { + Row::Prop(p) => p, + Row::Filter(_, name, on) => { + // A filter's name above its numbers, set apart by a rule (faint when it is off). + painter.rect_filled(row, 0.0, T.panel_alt); + painter.line_segment([row.left_top(), row.right_top()], Stroke::new(1.0, T.border)); + let name = crate::i18n::t(name); + let label = if on { name.to_string() } else { tr!("{filter} (off)", filter = name) }; + painter.text(pos2(row.left() + 10.0, row.center().y), Align2::LEFT_CENTER, label, font(Type::Label), if on { color(Type::Label) } else { T.text_faint }); + painter.line_segment([row.left_bottom(), row.right_bottom()], Stroke::new(1.0, T.separator)); + last_group = "Filters"; // i18n-exempt: a group key (Property::group), not shown + continue; + } + }; let selected = app.me_prop == p; painter.rect_filled(row, 0.0, if selected { T.accent_dim } else if r % 2 == 0 { T.panel } else { T.panel_alt }); let track = m.track(p); @@ -200,6 +245,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.text(pos2(row.left() + 84.0, row.center().y), Align2::LEFT_CENTER, tr!("keyed"), font(Type::Caption), T.tween_motion); } let rr = ui.interact(row, ui.id().with(("me_row", p.key())), Sense::click()); + let label = match p.filter() { + // Named with its filter for screen readers and tips ("Blur: Blur X"). + Some(f) => tr!("{filter}: {property}", filter = crate::i18n::t(filter_name(&target, f.slot)), property = label), + None => label.to_string(), + }; + let label = label.as_str(); a11y::control(ui, &rr, WidgetType::SelectableLabel, &if track.is_some() { tr!("{property} · keyed", property = label) } else { label.to_string() }, Some(selected)); if rr.clicked() { app.me_prop = p; @@ -207,7 +258,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } // The value at the playhead: drag or type it to key the property there. let field = Rect::from_min_size(pos2(row.right() - 128.0, row.top() + 3.0), vec2(88.0, ROW_H - 6.0)); - let mut v = now.get(p); + let mut v = now_of(p); let range = p.range(); let speed = if matches!(p, Property::X | Property::Y) { 1.0 } else { 0.5 }; let suffix = if p.unit() == "px" { " px" } else { p.unit() }; @@ -241,7 +292,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { if keyed { app.run("motion.remove_key", json!({"property": p.key(), "frame": app.s.frame})); } else { - app.run("motion.set_key", json!({"property": p.key(), "frame": app.s.frame, "value": now.get(p)})); + app.run("motion.set_key", json!({"property": p.key(), "frame": app.s.frame, "value": now_of(p)})); } } painter.line_segment([row.left_bottom(), row.right_bottom()], Stroke::new(1.0, T.separator)); @@ -251,10 +302,13 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // ---- graph ----------------------------------------------------------------------------- let p = app.me_prop; let track = m.track(p); - let label = crate::i18n::t(p.label()); + let label = match p.filter() { + Some(f) => tr!("{filter}: {property}", filter = crate::i18n::t(filter_name(&target, f.slot)), property = crate::i18n::t(p.label())), + None => crate::i18n::t(p.label()).to_string(), + }; let (lo, hi) = match app.me_drag { Some(MeDrag::Key { lo, hi, lane: false, .. } | MeDrag::Handle { lo, hi, .. }) => (lo, hi), - _ => value_range(track, base.get(p), frames, p), + _ => value_range(track, own(p), frames, p), }; let last = frames.saturating_sub(1).max(1) as f32; // Wider on the left: the value labels sit there, clear of the first key. @@ -274,7 +328,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } let y = y_of(v); gp.line_segment([pos2(graph.left(), y), pos2(graph.right(), y)], Stroke::new(1.0, T.separator)); - gp.text(pos2(graph.left() + 4.0, y - 1.0), Align2::LEFT_BOTTOM, format!("{v:.0}"), font(Type::DataSmall), T.text_faint); + gp.text(pos2(graph.left() + 4.0, y - 1.0), Align2::LEFT_BOTTOM, format!("{:.0}", v + 0.0), font(Type::DataSmall), T.text_faint); v += step; } let px_per_frame = inner.width() / last; @@ -303,14 +357,14 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let mut x = inner.left(); while x <= inner.right() + 0.5 { let f = f_of(x); - let v = track.and_then(|t| t.value_at(f)).unwrap_or(base.get(p)); + let v = track.and_then(|t| t.value_at(f)).unwrap_or(own(p)); pts.push(pos2(x, y_of(v))); x += 2.0; } gp.add(egui::Shape::line(pts, Stroke::new(2.0, if track.is_some() { T.tween_motion } else { T.text_faint }))); - gp.text(pos2(graph.right() - 8.0, graph.top() + 6.0), Align2::RIGHT_TOP, format!("{label} · {}", fmt(p, now.get(p))), font(Type::Data), color(Type::Data)); + gp.text(pos2(graph.right() - 8.0, graph.top() + 6.0), Align2::RIGHT_TOP, format!("{label} · {}", fmt(p, now_of(p))), font(Type::Data), color(Type::Data)); if track.is_none() { - gp.text(graph.center(), Align2::CENTER_CENTER, tr!("{property} has no keyframes: it stays {value}. Click ◇ or drag its value to key it here.", property = label, value = fmt(p, base.get(p))), font(Type::Caption), color(Type::Caption)); + gp.text(graph.center(), Align2::CENTER_CENTER, tr!("{property} has no keyframes: it stays {value}. Click ◇ or drag its value to key it here.", property = label, value = fmt(p, own(p))), font(Type::Caption), color(Type::Caption)); } // Keys and the selected segment's handles. @@ -368,7 +422,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let gr = ui.interact(graph_full, ui.id().with("me_graph"), Sense::click_and_drag()); // Where frames and values are drawn, for tests that point at keys. ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("me_geometry"), (inner, lane, last, lo, hi))); - a11y::surface(ui, &gr, &tr!("{property} curve: Left and Right move the picked keys a frame", property = crate::i18n::t(app.me_prop.label()))); + a11y::surface(ui, &gr, &tr!("{property} curve: Left and Right move the picked keys a frame", property = label)); keyboard(app, ui, &gr, start); let hover = gr.hover_pos(); let near_key = |pt: Pos2| keys.iter().find(|k| pt.y > lane.bottom() && pos2(x_of(k.0 as f32), y_of(k.1)).distance(pt) <= GRAB).map(|k| k.0); @@ -542,7 +596,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { { // A key on the curve where it is now (the motion doesn't change until it is dragged). let f = to_frame(pt.x); - let v = track.and_then(|t| t.value_at((f - start) as f32)).unwrap_or(base.get(p)); + let v = track.and_then(|t| t.value_at((f - start) as f32)).unwrap_or(own(p)); if app.run("motion.set_key", json!({"property": p.key(), "frame": f, "value": v})).is_some() { app.me_key = Some(f - start); } @@ -555,7 +609,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { }; } - footer(app, ui, body, track, sel_key, start, &rows); + footer(app, ui, body, track, sel_key, start, &rows, &label); +} + +/// The name of the object's filter at `slot` (Animate's, for the list and screen readers). +fn filter_name(target: &Element, slot: u8) -> &'static str { + match &target.kind { + ElementKind::Symbol { filters, .. } => filters.get(usize::from(slot)).map_or("Filter", |e| e.filter.label()), // i18n-exempt: translated where drawn (i18n::t) + _ => "Filter", // i18n-exempt: translated where drawn (i18n::t) + } } /// Picks `keys` (every property's keys on one frame): instead of the pick, or added to it. @@ -648,7 +710,8 @@ fn diamond(p: &egui::Painter, c: Pos2, r: f32, fill: Color32, stroke: Stroke) { } /// The ease of the selected segment, and the tween's own actions. -fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, sel_key: Option, start: u32, rows: &[Property]) { +#[allow(clippy::too_many_arguments)] +fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, sel_key: Option, start: u32, rows: &[Property], label: &str) { let bar = Rect::from_min_max(pos2(body.left(), body.bottom() - FOOTER_H), body.right_bottom()); ui.painter().rect_filled(bar, SQUARE, T.panel_alt); ui.painter().line_segment([bar.left_top(), bar.right_top()], Stroke::new(1.0, T.border)); @@ -656,7 +719,7 @@ fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, s let ui = &mut child; let p = app.me_prop; let seg = sel_key.zip(track).and_then(|(f, t)| t.key_at(f).filter(|i| *i + 1 < t.keys.len()).and_then(|i| t.keys.get(i)).map(|k| (f, k.ease.clone()))); - ui.label(text(Type::Label, tr!("{property} ease", property = crate::i18n::t(p.label())))); + ui.label(text(Type::Label, tr!("{property} ease", property = label))); match seg { Some((f, ease)) => { // The presets and the saved eases (ADR 0081); Edit Ease… shapes the segment's curve. @@ -725,6 +788,24 @@ fn empty_state(app: &mut App, ui: &mut egui::Ui, body: Rect) { mod tests { use super::*; + /// ADR 0092: each filter of the object is listed by name, its numbers under it, after the + /// colour effect. + #[test] + fn filters_list_their_numbers_under_their_names() { + use anicraft_engine::doc::{ColorEffect, ElementId, Filter, FilterEntry, SymbolId}; + use anicraft_engine::geom::Affine; + let filters = vec![FilterEntry::from(Filter::new("blur").unwrap()), FilterEntry { filter: Filter::new("adjust_color").unwrap(), enabled: false }]; + let clip = Element { id: ElementId(1), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters, events: Vec::new() } }; + let rows = rows_for(&[], &[], &clip); + let names: Vec = rows.iter().skip_while(|r| matches!(r, Row::Prop(p) if !p.is_filter())).map(|r| match r { + Row::Filter(slot, name, on) => format!("[{slot} {name} {on}]"), + Row::Prop(p) => p.key().into_owned(), + }).collect(); + assert_eq!(names, ["[0 Blur true]", "filter.0.blur_x", "filter.0.blur_y", "[1 Adjust Color false]", "filter.1.brightness", "filter.1.contrast", "filter.1.saturation", "filter.1.hue"]); + assert_eq!(filter_name(&clip, 1), "Adjust Color"); + assert_eq!(filter_name(&clip, 7), "Filter"); + } + #[test] fn grid_steps_are_round_numbers() { for (span, want) in [(4.0, 1.0), (10.0, 5.0), (100.0, 50.0), (360.0, 100.0), (0.0, 0.001)] { diff --git a/src/panels.rs b/src/panels.rs index f1c6b95e..42213b6f 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -403,6 +403,8 @@ fn renderer_tag(app: &App) -> Option { Some(match (app.stage_cache.gpu.state(), &app.stage_cache.drawn_by) { (State::Starting, _) => tr!("GPU starting").into(), (State::Failed(_), _) => tr!("CPU (GPU unavailable)").into(), + (State::Stopped { retry_at: Some(_), .. }, _) => tr!("CPU (GPU stopped; trying again soon)").into(), + (State::Stopped { retry_at: None, .. }, _) => tr!("CPU (GPU stopped)").into(), (State::Running { .. }, Some((true, _))) => "GPU".into(), // i18n-exempt: renderer name (State::Running { .. }, Some((false, Some(why)))) => tr!("CPU for {reason}", reason = crate::i18n::t_dyn(why)), _ => "CPU".into(), // i18n-exempt: renderer name diff --git a/src/stage.rs b/src/stage.rs index c69d3b4c..693a6969 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -903,7 +903,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.stage_cache.service = Some(RenderService::new(DEFAULT_CACHE_BYTES, Some(Box::new(move || ctx.request_repaint())))); } if let Some(svc) = &app.stage_cache.service { - app.stage_cache.gpu.sync(app.prefs.stage_renderer, svc, ui.ctx()); + // The stage's size in pixels: a change brings a GPU retry forward (ADR 0092). + let size = ((vis.width() * ppp).round() as u32, (vis.height() * ppp).round() as u32); + if let Some(n) = app.stage_cache.gpu.sync(app.prefs.stage_renderer, svc, ui.ctx(), size) { + let text = crate::gpu_stage::notice_text(&n); + match n { + crate::gpu_stage::Notice::Back => app.status_ok(text), + crate::gpu_stage::Notice::Stopped { .. } => app.status_err(text), + } + } } // Jobs are keyed by who draws them, so a renderer switch re-renders (old tiles stand in). let raster = app.stage_cache.service.as_ref().map_or(0, RenderService::raster_id); diff --git a/src/startup.rs b/src/startup.rs index d0f3b4c8..dd2a5d1a 100644 --- a/src/startup.rs +++ b/src/startup.rs @@ -49,6 +49,9 @@ impl Attempt { return base; } base.renderer = eframe::Renderer::Wgpu; + // A surface that fails is reconfigured, then made anew, instead of the frame being + // skipped for ever (ADR 0092). + base.wgpu_options.on_surface_status = std::sync::Arc::new(crate::gpu_watch::on_surface_status); let mut setup = WgpuSetupCreateNew::without_display_handle(); match self.backend { WindowBackend::Vulkan => setup.instance_descriptor.backends = wgpu::Backends::VULKAN, @@ -65,9 +68,10 @@ impl Attempt { } /// The attempts in order: `forced` (the command line) or else `chosen` (Preferences) first, then -/// the platform's order `platform`, each once. The attempt named `died_in` (the previous start -/// crashed or hung in it) goes last. -pub fn plan(forced: Option, chosen: WindowBackend, platform: &[(WindowBackend, bool)], died_in: Option<&str>) -> Vec { +/// the platform's order `platform`, each once. The attempts named in `last` (the previous start +/// crashed or hung in one; a session lost its graphics device in another, ADR 0092) go last, in +/// that order. +pub fn plan(forced: Option, chosen: WindowBackend, platform: &[(WindowBackend, bool)], last: &[String]) -> Vec { let mut out: Vec = Vec::new(); let first = forced.unwrap_or(chosen); if first != WindowBackend::Auto { @@ -82,16 +86,35 @@ pub fn plan(forced: Option, chosen: WindowBackend, platform: &[(W if out.is_empty() { out.push(Attempt { backend: WindowBackend::Auto, low_power: false }); } - if let Some(dead) = died_in - && let Some(i) = out.iter().position(|a| a.label() == dead) - && out.len() > 1 - { - let a = out.remove(i); - out.push(a); + for dead in last { + if let Some(i) = out.iter().position(|a| a.label() == *dead) + && out.len() > 1 + { + let a = out.remove(i); + out.push(a); + } } out } +/// Starts the record of a mid-session loss counts for: that many starts try another way first, +/// then the fastest way gets its chance again (the driver may have been updated, or the load +/// that brought it down gone). +pub const LOST_STARTS: u32 = 3; + +/// The record a mid-session loss leaves (ADR 0092): the attempt's label and the starts it still +/// counts for, one per line. +pub fn lost_record(text: &str) -> Option<(String, u32)> { + let mut lines = text.lines(); + let label = lines.next()?.trim().chars().take(200).collect::(); + let left = lines.next().and_then(|l| l.trim().parse::().ok()).unwrap_or(0).min(LOST_STARTS); + (!label.is_empty() && left > 0).then_some((label, left)) +} + +fn lost_record_text(label: &str, left: u32) -> String { + format!("{label}\n{left}\n") +} + /// Longest log written in one run: enough for any start-up, bounded however long AniCraft runs. const MAX_LOG_BYTES: u64 = 1024 * 1024; /// Frames the window draws before the start counts as working. @@ -102,6 +125,7 @@ const SLOW_START_SECS: u64 = 20; const LOG_NAME: &str = "anicraft.log"; const PREVIOUS_LOG_NAME: &str = "anicraft.previous.log"; const MARKER_NAME: &str = "starting"; +const LOST_NAME: &str = "graphics-lost"; struct Log { dir: PathBuf, @@ -112,14 +136,29 @@ struct Log { static LOG: Mutex> = Mutex::new(None); static FRAMES: AtomicU32 = AtomicU32::new(0); +/// The attempt the window runs on now (for the record a mid-session loss leaves). +static CURRENT: Mutex> = Mutex::new(None); +/// The window closed to open again another way (ADR 0092), with the document to open then. +static REOPEN: Mutex>> = Mutex::new(None); /// Opens the log in `dir` for this run (the previous run's becomes `anicraft.previous.log`) and -/// returns the attempt the previous start died in, if its marker is still there. Panics are -/// written to the log from now on. -pub fn begin(dir: Option) -> Option { - let dir = dir?; +/// returns the attempts to try last: the one an earlier session lost its graphics device in (for +/// [`LOST_STARTS`] starts, ADR 0092), then the one the previous start died in, if its marker is +/// still there. Panics are written to the log from now on. +pub fn begin(dir: Option) -> Vec { + let Some(dir) = dir else { return Vec::new() }; let _ = std::fs::create_dir_all(&dir); let died_in = std::fs::read_to_string(dir.join(MARKER_NAME)).ok().map(|s| s.trim().chars().take(200).collect::()).filter(|s| !s.is_empty()); + // This start uses up one of the record's starts. + let lost = std::fs::read_to_string(dir.join(LOST_NAME)).ok().and_then(|t| lost_record(&t)); + match &lost { + Some((label, left)) if *left > 1 => { + let _ = std::fs::write(dir.join(LOST_NAME), lost_record_text(label, left - 1)); + } + _ => { + let _ = std::fs::remove_file(dir.join(LOST_NAME)); + } + } let _ = std::fs::rename(dir.join(LOG_NAME), dir.join(PREVIOUS_LOG_NAME)); let file = std::fs::File::create(dir.join(LOG_NAME)).ok(); if let Ok(mut g) = LOG.lock() { @@ -134,10 +173,49 @@ pub fn begin(dir: Option) -> Option { })); let unix = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()); line(&format!("AniCraft {} ({}), {} {}, started at {unix} (Unix time)", env!("CARGO_PKG_VERSION"), crate::app::RELEASE_STAGE, std::env::consts::OS, std::env::consts::ARCH)); + if let Some((l, left)) = &lost { + line(&format!("a session lost its graphics device with {l}: trying it late ({left} more start(s) counting this one)")); + } if let Some(d) = &died_in { line(&format!("the previous start stopped while opening the window with {d}: trying it last")); } - died_in + lost.map(|(l, _)| l).into_iter().chain(died_in).collect() +} + +/// The window's graphics device was lost after it was up (ADR 0092): the next [`LOST_STARTS`] +/// starts try the attempt it ran on late. +pub fn lost_mid_session() { + let Some(label) = current() else { return }; + let dir = LOG.lock().ok().and_then(|g| g.as_ref().map(|l| l.dir.clone())); + if let Some(d) = dir { + let _ = std::fs::write(d.join(LOST_NAME), lost_record_text(&label, LOST_STARTS)); + } + line(&format!("the next {LOST_STARTS} starts try {label} late")); +} + +/// The attempt the window runs on now. +pub fn current() -> Option { + CURRENT.lock().ok().and_then(|g| g.clone()) +} + +/// The window is closing to open again another way, then with `file` (the app asks this when +/// its graphics device is gone). +pub fn ask_reopen(file: Option) { + if let Ok(mut g) = REOPEN.lock() { + *g = Some(file); + } +} + +/// Whether the window that just closed asked to open again, and with which document. +pub fn take_reopen() -> Option> { + REOPEN.lock().ok().and_then(|mut g| g.take()) +} + +/// Whether a failure after the window was up came from the graphics (wgpu, its surface, the +/// driver): then it counts as a mid-session loss. +pub fn is_graphics_failure(why: &str) -> bool { + let w = why.to_ascii_lowercase(); + ["wgpu", "surface", "device lost", "gpu", "dxgi", "vk_error", "vulkan", "direct3d"].iter().any(|k| w.contains(k)) // i18n-exempt: words looked for in a log line } /// Adds a line to the log (and the console in debug builds), with the seconds since it began. @@ -169,6 +247,9 @@ pub fn log_path() -> Option { /// notes in the log if the window is still not up after a while (a driver that hangs). pub fn trying(a: &Attempt, n: usize, of: usize) { line(&format!("opening the window with {} (attempt {n} of {of})", a.label())); + if let Ok(mut g) = CURRENT.lock() { + *g = Some(a.label()); + } let marker = LOG.lock().ok().and_then(|g| g.as_ref().map(|l| l.dir.join(MARKER_NAME))); if let Some(m) = marker { let _ = std::fs::write(m, a.label()); @@ -244,15 +325,15 @@ mod tests { #[test] fn automatic_tries_the_platform_order_ending_with_opengl() { - assert_eq!(labels(&plan(None, Auto, WINDOWS, None)), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]); + assert_eq!(labels(&plan(None, Auto, WINDOWS, &[])), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]); } #[test] fn a_chosen_or_forced_interface_goes_first_and_still_falls_back() { - assert_eq!(labels(&plan(None, Vulkan, WINDOWS, None)), ["wgpu Vulkan", "wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]); + assert_eq!(labels(&plan(None, Vulkan, WINDOWS, &[])), ["wgpu Vulkan", "wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]); // The command line wins over Preferences; OpenGL isn't tried twice. - assert_eq!(labels(&plan(Some(OpenGl), Dx12, WINDOWS, None)), ["OpenGL", "wgpu (automatic)", "wgpu DirectX 12, low-power GPU"]); - assert_eq!(labels(&plan(Some(Auto), Dx12, WINDOWS, None)), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"], "--renderer wgpu is automatic"); + assert_eq!(labels(&plan(Some(OpenGl), Dx12, WINDOWS, &[])), ["OpenGL", "wgpu (automatic)", "wgpu DirectX 12, low-power GPU"]); + assert_eq!(labels(&plan(Some(Auto), Dx12, WINDOWS, &[])), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"], "--renderer wgpu is automatic"); } /// Each attempt sets the window up as it says: OpenGL through glow, the others through @@ -288,9 +369,27 @@ mod tests { /// #207: when the last start died inside a driver (nothing to catch), that way goes last. #[test] fn the_way_the_last_start_died_in_goes_last() { - assert_eq!(labels(&plan(None, Auto, WINDOWS, Some("wgpu (automatic)"))), ["wgpu DirectX 12, low-power GPU", "OpenGL", "wgpu (automatic)"]); - assert_eq!(labels(&plan(None, Auto, WINDOWS, Some("something else"))), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]); - assert_eq!(labels(&plan(None, Auto, &[], None)), ["wgpu (automatic)"], "never nothing to try"); + assert_eq!(labels(&plan(None, Auto, WINDOWS, &["wgpu (automatic)".into()])), ["wgpu DirectX 12, low-power GPU", "OpenGL", "wgpu (automatic)"]); + assert_eq!(labels(&plan(None, Auto, WINDOWS, &["something else".into()])), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]); + assert_eq!(labels(&plan(None, Auto, &[], &[])), ["wgpu (automatic)"], "never nothing to try"); + } + + /// ADR 0092: a session that lost its graphics device mid-way makes the next starts try that + /// way late (after a start that died in a driver, which goes last of all), for + /// [`LOST_STARTS`] starts; then the fastest way gets its chance again. + #[test] + fn the_plan_after_a_mid_session_death_tries_that_way_late() { + assert_eq!(lost_record("wgpu (automatic)\n3\n"), Some(("wgpu (automatic)".into(), 3))); + assert_eq!(lost_record("wgpu (automatic)\n99"), Some(("wgpu (automatic)".into(), LOST_STARTS)), "never more than the limit"); + assert_eq!(lost_record("wgpu (automatic)\n0"), None); + assert_eq!(lost_record("\n2"), None); + assert_eq!(lost_record("garbage"), None); + let last = ["wgpu (automatic)".to_string(), "wgpu DirectX 12, low-power GPU".to_string()]; + assert_eq!(labels(&plan(None, Auto, WINDOWS, &last)), ["OpenGL", "wgpu (automatic)", "wgpu DirectX 12, low-power GPU"]); + assert_eq!(labels(&plan(None, Auto, WINDOWS, &last[..1])), ["wgpu DirectX 12, low-power GPU", "OpenGL", "wgpu (automatic)"]); + assert!(is_graphics_failure("wgpu error: Validation Error\n\nCaused by:\n In Surface::configure")); + assert!(is_graphics_failure("Failed to wait for GPU to come idle before reconfiguring the Surface")); + assert!(!is_graphics_failure("index out of bounds: the len is 3 but the index is 7")); } /// The log, the crash marker and the previous run's log, in a folder of their own. @@ -298,11 +397,11 @@ mod tests { fn the_log_keeps_the_previous_run_and_finds_a_crashed_start() { let dir = std::env::temp_dir().join(format!("anicraft-startup-log-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); - assert_eq!(begin(Some(dir.clone())), None, "a first start"); + assert!(begin(Some(dir.clone())).is_empty(), "a first start"); trying(&Attempt { backend: Dx12, low_power: true }, 1, 3); line("hello"); // Killed here (a driver crash): the marker stays, and the next start finds it. - assert_eq!(begin(Some(dir.clone())).as_deref(), Some("wgpu DirectX 12, low-power GPU")); + assert_eq!(begin(Some(dir.clone())), ["wgpu DirectX 12, low-power GPU"]); let previous = std::fs::read_to_string(dir.join(PREVIOUS_LOG_NAME)).unwrap(); assert!(previous.contains("opening the window with wgpu DirectX 12, low-power GPU (attempt 1 of 3)") && previous.contains("hello"), "{previous}"); let now = std::fs::read_to_string(dir.join(LOG_NAME)).unwrap(); @@ -315,6 +414,12 @@ mod tests { assert!(started()); assert!(!dir.join(MARKER_NAME).exists()); assert_eq!(log_path(), Some(dir.join(LOG_NAME))); + // The window lost its device mid-session: the next starts try it late, then not. + lost_mid_session(); + for left in (1..=LOST_STARTS).rev() { + assert_eq!(begin(Some(dir.clone())).first().map(String::as_str), Some("OpenGL"), "{left} start(s) left"); + } + assert!(begin(Some(dir.clone())).is_empty(), "the record is used up"); // A panic is written down. let _ = std::panic::catch_unwind(|| panic!("the driver said no")); assert!(std::fs::read_to_string(dir.join(LOG_NAME)).unwrap().contains("the driver said no"));