forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

titleanim.rs375 lines, 14.2 KiBHistoryRawDownload
1//! A title's entrance and exit animations: which one it plays, and how far along it is at a
2//! frame. The export ([`crate::export`]) and the preview both read the same [`Motion`] from
3//! [`crate::project::Title::motion_at`], so the two agree on when a word is up, where it sits and
4//! how big it is. An exit is its entrance played backwards: the same effect runs from its
5//! resting state down to nothing, with the easing reversed (ease-out in, ease-in out).
6
7use crate::project::Title;
8use crate::transform::{KeyEase, Keyed, sample};
9
10/// The shortest and longest scale a title key may set, as a multiple of the title's size.
11pub const KEY_SCALE_RANGE: (f32, f32) = (0.05, 10.0);
12
13/// One point of a title's own keyframe animation: how far the title is moved, how much it is
14/// scaled and how much it is faded at `at` frames from its first frame. Its values add onto
15/// (shift) or multiply (scale, opacity) what the title's entrance and exit already do, and
16/// between two keys they blend the way a clip's keys do.
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct TitleKey {
19 /// Frames from the title's first frame. A key past the title's length holds its value.
20 pub at: u32,
21 /// Added to the horizontal shift, as a share of the picture's width, `-1..=1`.
22 pub x: f32,
23 /// Added to the vertical shift, as a share of the picture's height, `-1..=1`; down is positive.
24 pub y: f32,
25 /// Multiplies the size, within [`KEY_SCALE_RANGE`]. `1` leaves it alone.
26 pub scale: f32,
27 /// Multiplies the opacity, `0..=1`. `1` leaves it alone.
28 pub opacity: f32,
29 /// The easing of the segment that leaves this key.
30 pub ease: KeyEase,
31}
32
33impl Keyed for TitleKey {
34 fn at(&self) -> u32 {
35 self.at
36 }
37 fn ease(&self) -> KeyEase {
38 self.ease
39 }
40 fn placed(self, at: u32, ease: KeyEase) -> Self {
41 Self { at, ease, ..self }
42 }
43 fn mix(a: &Self, b: &Self, t: f32) -> Self {
44 let l = |x: f32, y: f32| x + (y - x) * t;
45 Self {
46 x: l(a.x, b.x),
47 y: l(a.y, b.y),
48 scale: l(a.scale, b.scale),
49 opacity: l(a.opacity, b.opacity),
50 ..*a
51 }
52 }
53}
54
55/// One of the animations a title plays on the way in or out.
56#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
57pub enum TitleAnim {
58 /// The title is simply there, and simply gone.
59 #[default]
60 None,
61 /// The title fades in or out.
62 Fade,
63 /// The letters appear one by one (and go one by one on the way out).
64 Typewriter,
65 /// The title rises into place from below.
66 SlideUp,
67 /// The title moves in from the right.
68 SlideLeft,
69 /// The title grows from 60% to full size with a slight overshoot.
70 Pop,
71 /// The words appear one by one.
72 WordByWord,
73}
74
75impl TitleAnim {
76 pub const ALL: [TitleAnim; 7] = [
77 Self::None,
78 Self::Fade,
79 Self::Typewriter,
80 Self::SlideUp,
81 Self::SlideLeft,
82 Self::Pop,
83 Self::WordByWord,
84 ];
85
86 /// The word the file, the MCP and the GUI spell it.
87 pub fn name(self) -> &'static str {
88 match self {
89 Self::None => "none",
90 Self::Fade => "fade",
91 Self::Typewriter => "typewriter",
92 Self::SlideUp => "slide_up",
93 Self::SlideLeft => "slide_left",
94 Self::Pop => "pop",
95 Self::WordByWord => "word_by_word",
96 }
97 }
98
99 pub fn from_name(name: &str) -> Option<Self> {
100 Self::ALL.into_iter().find(|a| a.name() == name)
101 }
102}
103
104/// The length an animation gets when none is given, in seconds.
105pub const DEFAULT_SECS: f64 = 0.5;
106
107/// How far a slide travels, as a share of the picture's height (up) or width (left).
108pub const SLIDE: f32 = 0.08;
109
110/// The size a pop starts at, as a share of the title's full size.
111pub const POP_FROM: f32 = 0.6;
112
113/// Which unit a reveal counts in.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub enum Unit {
116 /// Letters, not counting spaces and line breaks.
117 Letters,
118 /// Words, as a run of non-space characters.
119 Words,
120}
121
122/// What an animation does to a title at one frame. Every field is at rest when the title is in
123/// place: full alpha, no offset, full size, all of the text.
124#[derive(Clone, Debug, PartialEq)]
125pub struct Motion {
126 /// The opacity, 0 to 255, with the title's fades already in.
127 pub alpha: u8,
128 /// Shift to the right, as a share of the picture's width.
129 pub dx: f32,
130 /// Shift down, as a share of the picture's height.
131 pub dy: f32,
132 /// The size as a share of the title's full size (1 at rest).
133 pub scale: f32,
134 /// The part of the text that shows, as `(unit, share)`, or `None` for all of it.
135 pub reveal: Option<(Unit, f32)>,
136}
137
138/// The part of a title's text a reveal lets through at one frame: its first `chars` characters
139/// are drawn and the rest are not. The text is always laid out whole, so the drawn part stays
140/// where it is and nothing moves while it types on.
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub struct Shown {
143 /// The characters drawn, counted from the start of the text (spaces included).
144 pub chars: usize,
145 /// The letters among them: non-whitespace characters, the count a wrapped layout can use.
146 pub ink: usize,
147}
148
149impl Motion {
150 /// The part of `text` drawn at this frame, or `None` when all of it is (no reveal, or one
151 /// that has finished). A letter reveal shows letters one by one; a word reveal shows whole
152 /// words, the next one from its first letter.
153 pub fn revealed(&self, text: &str) -> Option<Shown> {
154 let (unit, share) = self.reveal?;
155 let share = share.clamp(0.0, 1.0);
156 let units = match unit {
157 Unit::Letters => text.chars().filter(|c| !c.is_whitespace()).count(),
158 Unit::Words => word_starts(text).count(),
159 };
160 // A share above nothing shows at least one unit, so the first frame of a reveal has a letter.
161 let show = ((share * units as f32).ceil() as usize).min(units);
162 if show == units {
163 return None;
164 }
165 let total = text.chars().count();
166 let stop = match unit {
167 Unit::Letters => text
168 .chars()
169 .enumerate()
170 .filter(|(_, c)| !c.is_whitespace())
171 .nth(show)
172 .map_or(total, |(i, _)| i),
173 Unit::Words => word_starts(text).nth(show).unwrap_or(total),
174 };
175 let ink = text.chars().take(stop).filter(|c| !c.is_whitespace()).count();
176 Some(Shown { chars: stop, ink })
177 }
178}
179
180/// The character index where each word of `text` starts.
181fn word_starts(text: &str) -> impl Iterator<Item = usize> + '_ {
182 let mut prev_space = true;
183 text.chars().enumerate().filter_map(move |(i, c)| {
184 let start = prev_space && !c.is_whitespace();
185 prev_space = c.is_whitespace();
186 start.then_some(i)
187 })
188}
189
190/// Eased out: quick at first, settling into place.
191fn ease_out(x: f32) -> f32 {
192 let x = x.clamp(0.0, 1.0);
193 1.0 - (1.0 - x).powi(3)
194}
195
196/// Eased in: slow at first, quick at the end.
197fn ease_in(x: f32) -> f32 {
198 let x = x.clamp(0.0, 1.0);
199 x * x * x
200}
201
202/// The overshoot curve a pop grows along: it passes 1 a little before it settles there.
203fn overshoot(p: f32) -> f32 {
204 const C1: f32 = 1.70158;
205 const C3: f32 = C1 + 1.0;
206 let q = p - 1.0;
207 1.0 + C3 * q * q * q + C1 * q * q
208}
209
210/// One animation's effect at presence `p` (0 gone, 1 in place), before it is combined with the
211/// other end's. The same function serves an entrance (presence climbs) and an exit (it falls).
212struct Part {
213 alpha: f32,
214 dx: f32,
215 dy: f32,
216 scale: f32,
217 reveal: Option<(Unit, f32)>,
218}
219
220impl Part {
221 const REST: Part = Part { alpha: 1.0, dx: 0.0, dy: 0.0, scale: 1.0, reveal: None };
222}
223
224fn effect(anim: TitleAnim, p: f32) -> Part {
225 let rest = Part::REST;
226 match anim {
227 TitleAnim::None => rest,
228 TitleAnim::Fade => Part { alpha: p, ..rest },
229 TitleAnim::Typewriter => Part { reveal: Some((Unit::Letters, p)), ..rest },
230 TitleAnim::WordByWord => Part { reveal: Some((Unit::Words, p)), ..rest },
231 TitleAnim::SlideUp => Part { dy: (1.0 - p) * SLIDE, ..rest },
232 TitleAnim::SlideLeft => Part { dx: (1.0 - p) * SLIDE, ..rest },
233 TitleAnim::Pop => Part { scale: POP_FROM + (1.0 - POP_FROM) * overshoot(p), ..rest },
234 }
235}
236
237impl Title {
238 /// The entrance the title plays, and its length in frames. A title with a fade-in and no
239 /// entrance animation reads as a fade of that length, which is what it always was.
240 pub fn entrance(&self) -> (TitleAnim, u32) {
241 match self.in_anim {
242 TitleAnim::None if self.fade_in > 0 => (TitleAnim::Fade, self.fade_in),
243 anim => (anim, self.anim_frames),
244 }
245 }
246
247 /// The exit the title plays, and its length in frames, read as [`Title::entrance`] reads it.
248 pub fn exit(&self) -> (TitleAnim, u32) {
249 match self.out_anim {
250 TitleAnim::None if self.fade_out > 0 => (TitleAnim::Fade, self.fade_out),
251 anim => (anim, self.anim_frames),
252 }
253 }
254
255 /// Moves a plain fade into the entrance and exit it is: a title that has one reads and edits as
256 /// the animations it plays. Its length is the longer of the two fades, since they share one.
257 pub fn adopt_fades(&mut self) {
258 if self.in_anim == TitleAnim::None && self.fade_in > 0 {
259 self.in_anim = TitleAnim::Fade;
260 }
261 if self.out_anim == TitleAnim::None && self.fade_out > 0 {
262 self.out_anim = TitleAnim::Fade;
263 }
264 if (self.in_anim != TitleAnim::None && self.fade_in > 0) || (self.out_anim != TitleAnim::None && self.fade_out > 0) {
265 self.anim_frames = self.fade_in.max(self.fade_out);
266 self.fade_in = 0;
267 self.fade_out = 0;
268 }
269 }
270
271 /// What the title looks like at timeline frame `frame`, or `None` outside its span.
272 pub fn motion_at(&self, frame: u32) -> Option<Motion> {
273 if frame < self.start || frame >= self.end() {
274 return None;
275 }
276 let k = frame - self.start;
277 let left = self.frames - k;
278 // The fades the title always had, linear and counted as they always were.
279 let mut alpha = 1.0f32;
280 if self.fade_in > 0 && k < self.fade_in {
281 alpha = alpha.min((k + 1) as f32 / (self.fade_in + 1) as f32);
282 }
283 if self.fade_out > 0 && left <= self.fade_out {
284 alpha = alpha.min(left as f32 / (self.fade_out + 1) as f32);
285 }
286 // The fades above are the old linear ones; the animations are the new ones, read as set.
287 let (in_anim, in_frames) = (self.in_anim, self.anim_frames);
288 let (out_anim, out_frames) = (self.out_anim, self.anim_frames);
289 let presence_in = match in_anim {
290 TitleAnim::None => 1.0,
291 _ if k < in_frames => ease_out((k + 1) as f32 / in_frames as f32),
292 _ => 1.0,
293 };
294 let presence_out = match out_anim {
295 TitleAnim::None => 1.0,
296 _ if left <= out_frames => ease_in(left as f32 / out_frames as f32),
297 _ => 1.0,
298 };
299 let (a, b) = (effect(in_anim, presence_in), effect(out_anim, presence_out));
300 let reveal = match (a.reveal, b.reveal) {
301 (Some(x), Some(y)) => Some(if x.1 <= y.1 { x } else { y }),
302 (x, y) => x.or(y),
303 };
304 let mut motion = Motion {
305 alpha: (alpha * a.alpha * b.alpha * 255.0) as u8,
306 dx: a.dx + b.dx,
307 dy: a.dy + b.dy,
308 scale: a.scale * b.scale,
309 reveal,
310 };
311 // The title's own keys come last: they shift, scale and fade whatever the entrance left.
312 if let Some(key) = sample(&self.keys, f64::from(k)) {
313 motion.dx += key.x;
314 motion.dy += key.y;
315 motion.scale *= key.scale;
316 motion.alpha = (f32::from(motion.alpha) * key.opacity).round() as u8;
317 }
318 Some(motion)
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325 use crate::project::Title;
326 use crate::text::TextStyle;
327
328 fn title(anim: TitleAnim, frames: u32) -> Title {
329 Title {
330 start: 0,
331 frames,
332 text: "Hello big world".into(),
333 style: TextStyle::default(),
334 fade_in: 0,
335 fade_out: 0,
336 in_anim: anim,
337 out_anim: TitleAnim::None,
338 anim_frames: 12,
339 keys: Vec::new(),
340 }
341 }
342
343 #[test]
344 fn two_keys_fade_and_shift_a_title_halfway_between_them() {
345 // Opacity goes 0 to 1 and x 0 to 0.2 over the first ten frames: at frame 5 that is half
346 // the alpha and a shift of 0.1 of the width.
347 let key = |at, x, opacity| crate::titleanim::TitleKey { at, x, y: 0.0, scale: 1.0, opacity, ease: crate::transform::KeyEase::Linear };
348 let t = Title { keys: vec![key(0, 0.0, 0.0), key(10, 0.2, 1.0)], ..title(TitleAnim::None, 60) };
349 let m = t.motion_at(5).expect("up");
350 assert!(m.alpha.abs_diff(128) <= 1, "alpha {}", m.alpha);
351 assert!((m.dx - 0.1).abs() < 1e-6, "dx {}", m.dx);
352 }
353
354 #[test]
355 fn a_typewriter_title_shows_more_letters_from_its_start_to_its_middle_to_its_end() {
356 // A 26-frame typewriter in a 60-frame title: the letters come up over its first 26 frames.
357 let t = Title { anim_frames: 26, ..title(TitleAnim::Typewriter, 60) };
358 let letters = |f: u32| {
359 let m = t.motion_at(f).expect("up");
360 m.revealed(&t.text).map_or(13, |s| s.ink)
361 };
362 let (start, middle, end) = (letters(0), letters(6), letters(25));
363 assert!(start >= 1 && start < middle && middle < end, "{start} {middle} {end}");
364 assert_eq!(end, 13, "all 13 letters are up at the end of the animation");
365 // The typed part is drawn exactly where the whole line is drawn: nothing moves while it types on.
366 let style = TextStyle::default();
367 let lines = vec![t.text.clone()];
368 let full = crate::text::overlay(&style, 640, 360, &lines);
369 let part = crate::text::overlay_revealed(&style, 640, 360, &lines, 5);
370 let (f, p) = (full.fill(), part.fill());
371 assert!(p.iter().zip(f).all(|(&p, &f)| p == 0 || p == f), "the typed part sits where the whole line does");
372 let drawn = |v: &[u8]| v.iter().filter(|&&x| x > 0).count();
373 assert!(0 < drawn(p) && drawn(p) < drawn(f), "{} {}", drawn(p), drawn(f));
374 }
375}