Skip to main content

alpha2_eval/
text_animation.rs

1//! Text animators sampled at a time: the plain numbers each animator applies.
2
3use alpha2_geometry::StableHash;
4use alpha2_model::{
5    Animated, Interpolation, Keyframe, RangeShape, RangeUnits, RunState, TextAnimator, TextRun,
6    TextSelector, TextUnit,
7};
8use alpha2_time::MediaTime;
9
10use crate::{SampleContext, sample_rgba, sample_scalar, sample_vec2};
11
12/// An animator's selector and properties at one time.
13#[derive(Clone, Debug, PartialEq)]
14pub struct SampledAnimator {
15    /// What it selects.
16    pub selector: SampledSelector,
17    /// Offset in font sizes, +y down.
18    pub offset: Option<[f32; 2]>,
19    /// Scale about each character's centre.
20    pub scale: Option<[f32; 2]>,
21    /// Clockwise degrees about each character's centre.
22    pub rotation_degrees: Option<f32>,
23    /// Target opacity.
24    pub opacity: Option<f32>,
25    /// Target fill color, straight sRGB.
26    pub fill: Option<[f32; 4]>,
27    /// Target stroke color, straight sRGB.
28    pub stroke: Option<[f32; 4]>,
29    /// Extra space after each character, font sizes.
30    pub tracking: Option<f32>,
31    /// Whether the advance follows the horizontal scale.
32    pub advance_follows_scale: bool,
33    /// The reveal's edge, its values held to their ranges.
34    pub reveal: Option<SampledReveal>,
35}
36
37/// A text reveal at one time.
38#[derive(Copy, Clone, Debug, PartialEq)]
39pub struct SampledReveal {
40    /// How much of a fully selected unit shows, in `[0, 1]`.
41    pub progress: f32,
42    /// The direction the edge travels, clockwise degrees.
43    pub angle_degrees: f32,
44    /// The edge's softness, font sizes in `[0, MAX_REVEAL_FEATHER]`.
45    pub feather: f32,
46}
47
48/// A selector at one time.
49#[derive(Clone, Debug, PartialEq)]
50pub enum SampledSelector {
51    /// A Range selector's values.
52    Range {
53        /// What it counts.
54        based_on: TextUnit,
55        /// Percents or indices.
56        units: RangeUnits,
57        /// Start, with the offset not added.
58        start: f32,
59        /// End, with the offset not added.
60        end: f32,
61        /// Added to start and end.
62        offset: f32,
63        /// How selection rises and falls.
64        shape: RangeShape,
65        /// Selection scale.
66        amount: f32,
67    },
68    /// A Timing selector (its values are not animated).
69    Timing {
70        /// Which runs.
71        state: RunState,
72        /// Fade length.
73        ramp: MediaTime,
74        /// Sweep each run's characters in order.
75        sweep: bool,
76    },
77    /// A Class selector.
78    Class {
79        /// The class name.
80        class: String,
81    },
82}
83
84/// `animators` sampled at `time`, in order.
85#[must_use]
86pub fn sample_text_animators(animators: &[TextAnimator], time: MediaTime) -> Vec<SampledAnimator> {
87    animators
88        .iter()
89        .map(|animator| {
90            let properties = &animator.properties;
91            let pair = |value: alpha2_model::Vec2| [value.x, value.y];
92            let color =
93                |value: alpha2_model::Rgba| [value.red, value.green, value.blue, value.alpha];
94            SampledAnimator {
95                selector: match &animator.selector {
96                    TextSelector::Range {
97                        based_on,
98                        units,
99                        start,
100                        end,
101                        offset,
102                        shape,
103                        amount,
104                    } => SampledSelector::Range {
105                        based_on: *based_on,
106                        units: *units,
107                        start: sample_scalar(start, time, &SampleContext::NONE),
108                        end: sample_scalar(end, time, &SampleContext::NONE),
109                        offset: sample_scalar(offset, time, &SampleContext::NONE),
110                        shape: *shape,
111                        amount: sample_scalar(amount, time, &SampleContext::NONE).clamp(0.0, 1.0),
112                    },
113                    TextSelector::Timing { state, ramp, sweep } => SampledSelector::Timing {
114                        state: *state,
115                        ramp: *ramp,
116                        sweep: *sweep,
117                    },
118                    TextSelector::Class { class } => SampledSelector::Class {
119                        class: class.clone(),
120                    },
121                },
122                offset: properties.offset.as_ref().map(|value| {
123                    let bound = alpha2_model::MAX_ANIMATOR_OFFSET;
124                    pair(sample_vec2(value, time, &SampleContext::NONE))
125                        .map(|axis| axis.clamp(-bound, bound))
126                }),
127                scale: properties.scale.as_ref().map(|value| {
128                    pair(sample_vec2(value, time, &SampleContext::NONE)).map(|axis| axis.max(0.0))
129                }),
130                rotation_degrees: properties
131                    .rotation_degrees
132                    .as_ref()
133                    .map(|value| sample_scalar(value, time, &SampleContext::NONE)),
134                opacity: properties
135                    .opacity
136                    .as_ref()
137                    .map(|value| sample_scalar(value, time, &SampleContext::NONE).clamp(0.0, 1.0)),
138                fill: properties
139                    .fill
140                    .as_ref()
141                    .map(|value| color(sample_rgba(value, time))),
142                stroke: properties
143                    .stroke
144                    .as_ref()
145                    .map(|value| color(sample_rgba(value, time))),
146                tracking: properties
147                    .tracking
148                    .as_ref()
149                    .map(|value| sample_scalar(value, time, &SampleContext::NONE)),
150                advance_follows_scale: properties.advance_follows_scale,
151                reveal: properties.reveal.as_ref().map(|reveal| SampledReveal {
152                    progress: sample_scalar(&reveal.progress, time, &SampleContext::NONE)
153                        .clamp(0.0, 1.0),
154                    angle_degrees: sample_scalar(&reveal.angle_degrees, time, &SampleContext::NONE),
155                    feather: sample_scalar(&reveal.feather, time, &SampleContext::NONE)
156                        .clamp(0.0, alpha2_model::MAX_REVEAL_FEATHER),
157                }),
158            }
159        })
160        .collect()
161}
162
163/// Feeds every value of `animators` to `hash`.
164pub fn hash_sampled_animators(hash: &mut StableHash, animators: &[SampledAnimator]) {
165    hash.u64(animators.len() as u64);
166    for animator in animators {
167        match &animator.selector {
168            SampledSelector::Range {
169                based_on,
170                units,
171                start,
172                end,
173                offset,
174                shape,
175                amount,
176            } => {
177                hash.u32(0);
178                hash.u32(*based_on as u32);
179                hash.u32(*units as u32);
180                hash.u32(*shape as u32);
181                for value in [start, end, offset, amount] {
182                    hash.f32(*value);
183                }
184            }
185            SampledSelector::Timing { state, ramp, sweep } => {
186                hash.u32(1);
187                hash.u32(*state as u32);
188                hash.u64(ramp.ticks().cast_unsigned());
189                hash.u32(u32::from(*sweep));
190            }
191            SampledSelector::Class { class } => {
192                hash.u32(2);
193                hash.bytes(class.as_bytes());
194            }
195        }
196        let mut option = |values: Option<&[f32]>| match values {
197            None => hash.u32(0),
198            Some(values) => {
199                hash.u32(1);
200                for value in values {
201                    hash.f32(*value);
202                }
203            }
204        };
205        option(animator.offset.as_ref().map(<[f32; 2]>::as_slice));
206        option(animator.scale.as_ref().map(<[f32; 2]>::as_slice));
207        option(animator.rotation_degrees.as_ref().map(std::slice::from_ref));
208        option(animator.opacity.as_ref().map(std::slice::from_ref));
209        option(animator.fill.as_ref().map(<[f32; 4]>::as_slice));
210        option(animator.stroke.as_ref().map(<[f32; 4]>::as_slice));
211        option(animator.tracking.as_ref().map(std::slice::from_ref));
212        if animator.advance_follows_scale {
213            hash.u32(0xadf5);
214        }
215        if let Some(reveal) = animator.reveal {
216            hash.u32(0x2e7e);
217            for value in [reveal.progress, reveal.angle_degrees, reveal.feather] {
218                hash.f32(value);
219            }
220        }
221    }
222}
223
224/// The largest factor any cluster's advance can be widened by under `animators` over a text of
225/// `runs`: per animator whose advance follows its scale, `1 + w (s - 1)` with `s` its largest
226/// horizontal scale and `w` its largest selection, at least 1; their product, at most the
227/// largest animator scale, which also bounds a cluster's. 1 when none pushes.
228///
229/// Keyframes count every value and each eased segment's extremes, so an overshooting curve
230/// reserves its overshoot. A value bound to data, which text animators refuse, takes its range's
231/// bound.
232#[must_use]
233pub fn advance_headroom(animators: &[TextAnimator], runs: &[TextRun]) -> f32 {
234    let mut headroom = 1.0_f64;
235    for animator in animators {
236        let properties = &animator.properties;
237        let Some(scale) = properties
238            .scale
239            .as_ref()
240            .filter(|_| properties.advance_follows_scale)
241        else {
242            continue;
243        };
244        let largest_scale = largest(scale, |value| value.x, *ANIMATOR_SCALE.end()).max(0.0);
245        let selection = match &animator.selector {
246            TextSelector::Range { amount, .. } => {
247                largest(amount, |value| *value, 1.0).clamp(0.0, 1.0)
248            }
249            TextSelector::Timing { .. } => {
250                if runs.iter().any(|run| run.time.is_some()) {
251                    1.0
252                } else {
253                    0.0
254                }
255            }
256            TextSelector::Class { class } => {
257                if runs.iter().any(|run| run.class.contains(class)) {
258                    1.0
259                } else {
260                    0.0
261                }
262            }
263        };
264        headroom *= (1.0 + selection * (largest_scale - 1.0)).max(1.0);
265    }
266    #[expect(
267        clippy::cast_possible_truncation,
268        reason = "at most the cluster scale limit"
269    )]
270    let headroom = headroom.min(f64::from(*ANIMATOR_SCALE.end())) as f32;
271    headroom
272}
273
274const ANIMATOR_SCALE: std::ops::RangeInclusive<f32> = alpha2_model::ANIMATOR_SCALE_RANGE;
275
276/// The largest `component` an animated value takes, `bound` for one bound to data.
277fn largest<T>(animated: &Animated<T>, component: impl Fn(&T) -> f32, bound: f32) -> f64 {
278    match animated {
279        Animated::Constant { value } => f64::from(component(value)),
280        Animated::Keyframes { keyframes } => keyframes
281            .iter()
282            .zip(keyframes.iter().skip(1).map(Some).chain([None]))
283            .map(|(left, right)| segment_largest(left, right, &component))
284            .fold(f64::NEG_INFINITY, f64::max),
285        Animated::Data(_) => f64::from(bound),
286    }
287}
288
289/// The largest `component` from keyframe `left` to `right`, the left value alone for the last.
290fn segment_largest<T>(
291    left: &Keyframe<T>,
292    right: Option<&Keyframe<T>>,
293    component: &impl Fn(&T) -> f32,
294) -> f64 {
295    let from = f64::from(component(&left.value));
296    let Some(right) = right else {
297        return from;
298    };
299    let to = f64::from(component(&right.value));
300    let [low, high] = match left.interpolation {
301        Interpolation::Hold => return from,
302        Interpolation::Linear => [0.0, 1.0],
303        Interpolation::CubicBezier(curve) => {
304            bezier_output_range(f64::from(curve.y1), f64::from(curve.y2))
305        }
306    };
307    (from + (to - from) * low).max(from + (to - from) * high)
308}
309
310/// The least and largest output of a `cubic-bezier` with these `y1`, `y2` over its whole
311/// parameter range: its ends and where its derivative, a quadratic, is zero.
312fn bezier_output_range(y1: f64, y2: f64) -> [f64; 2] {
313    let output = |t: f64| {
314        let rest = 1.0 - t;
315        3.0 * rest * rest * t * y1 + 3.0 * rest * t * t * y2 + t * t * t
316    };
317    let (d0, d1, d2) = (y1, y2 - y1, 1.0 - y2);
318    let (a, b, c) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0);
319    let mut roots = [None, None];
320    if a.abs() <= f64::EPSILON {
321        if b.abs() > f64::EPSILON {
322            roots[0] = Some(-c / b);
323        }
324    } else {
325        let discriminant = b * b - 4.0 * a * c;
326        if discriminant >= 0.0 {
327            let root = discriminant.sqrt();
328            roots = [Some((-b + root) / (2.0 * a)), Some((-b - root) / (2.0 * a))];
329        }
330    }
331    roots
332        .into_iter()
333        .flatten()
334        .filter(|t| *t > 0.0 && *t < 1.0)
335        .map(output)
336        .fold([0.0, 1.0], |[low, high], value| {
337            [low.min(value), high.max(value)]
338        })
339}