alpha2-layout 0.9.0

Text and layout boxes measures for alpha2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Text animators applied to a laid-out text: each cluster's selection and resulting state.
//!
//! Selection follows After Effects' text animators. A Range selector counts units
//! (characters, non-space characters, words or lines) and shapes its range at the ends. A
//! Timing selector picks the characters of runs by the run's time against the current time.
//! A Class selector picks the characters of runs that carry a class. Only `+ - * /` and
//! `sqrt` enter the selection, so native and wasm agree bit for bit.

use alpha2_eval::{SampledAnimator, SampledSelector};
use alpha2_model::{RangeShape, RangeUnits, RunState, RunTime, TextRun, TextUnit};
use alpha2_text::{ClusterState, ColorMix, MAX_CLUSTER_SCALE, RevealEdge, TextLayout};
use alpha2_time::MediaTime;

/// The selection in `[0, 1]` that `selector` gives each cluster of `layout`, at `time` for a
/// Timing selector. `runs` is empty for a plain string.
#[must_use]
pub fn selection(
    selector: &SampledSelector,
    layout: &TextLayout,
    runs: &[TextRun],
    time: MediaTime,
) -> Vec<f32> {
    match selector {
        SampledSelector::Range {
            based_on,
            units,
            start,
            end,
            offset,
            shape,
            amount,
        } => {
            let (unit_of, count) = units_of(layout, *based_on);
            #[allow(clippy::cast_precision_loss)]
            let count_f = count as f32;
            let (mut s, mut e) = match units {
                RangeUnits::Percent => (
                    (start + offset) / 100.0 * count_f,
                    (end + offset) / 100.0 * count_f,
                ),
                RangeUnits::Index => (start + offset, end + offset),
            };
            if s > e {
                std::mem::swap(&mut s, &mut e);
            }
            unit_of
                .iter()
                .map(|unit| unit.map_or(0.0, |unit| range_value(*shape, unit, s, e) * amount))
                .collect()
        }
        SampledSelector::Timing { state, ramp, sweep } => {
            timing(layout, runs, time, *state, *ramp, *sweep)
        }
        SampledSelector::Class { class } => {
            let run_of = run_of_clusters(layout, runs);
            run_of
                .iter()
                .map(|run| {
                    let selected =
                        run.is_some_and(|run| runs[run].class.iter().any(|name| name == class));
                    if selected { 1.0 } else { 0.0 }
                })
                .collect()
        }
    }
}

/// Each cluster's unit index under `based_on` (`None` for a cluster in no unit, such as a
/// space under `words`), and the unit count.
fn units_of(layout: &TextLayout, based_on: TextUnit) -> (Vec<Option<u32>>, u32) {
    let clusters = &layout.clusters;
    match based_on {
        TextUnit::Characters => (
            (0..u32::try_from(clusters.len()).unwrap_or(u32::MAX))
                .map(Some)
                .collect(),
            u32::try_from(clusters.len()).unwrap_or(u32::MAX),
        ),
        TextUnit::CharactersExcludingSpaces => {
            let mut next = 0;
            let units = clusters
                .iter()
                .map(|cluster| {
                    (!cluster.is_space).then(|| {
                        next += 1;
                        next - 1
                    })
                })
                .collect();
            (units, next)
        }
        TextUnit::Words => {
            let count = clusters
                .iter()
                .filter_map(|cluster| cluster.word)
                .max()
                .map_or(0, |last| last + 1);
            (clusters.iter().map(|cluster| cluster.word).collect(), count)
        }
        TextUnit::Lines => (
            clusters.iter().map(|cluster| Some(cluster.line)).collect(),
            u32::try_from(layout.lines.len()).unwrap_or(u32::MAX),
        ),
    }
}

/// The value `shape` gives unit `unit` (covering `[unit, unit + 1)`) of a range from `s` to
/// `e` in unit space, `s <= e`.
#[allow(clippy::cast_precision_loss, clippy::many_single_char_names)]
fn range_value(shape: RangeShape, unit: u32, s: f32, e: f32) -> f32 {
    #[allow(clippy::float_cmp)]
    if e == s {
        return 0.0;
    }
    let i = unit as f32;
    let ramp = || (i + 0.5 - s) / (e - s);
    let triangle = |u: f32| {
        if (0.0..=1.0).contains(&u) {
            1.0 - (2.0 * u - 1.0).abs()
        } else {
            0.0
        }
    };
    match shape {
        RangeShape::Square => (e.min(i + 1.0) - s.max(i)).clamp(0.0, 1.0),
        RangeShape::RampUp => ramp().clamp(0.0, 1.0),
        RangeShape::RampDown => 1.0 - ramp().clamp(0.0, 1.0),
        RangeShape::Triangle => triangle(ramp()),
        RangeShape::Round => {
            let u = ramp();
            if (0.0..=1.0).contains(&u) {
                let x = 2.0 * u - 1.0;
                (1.0 - x * x).max(0.0).sqrt()
            } else {
                0.0
            }
        }
        RangeShape::Smooth => {
            let t = triangle(ramp());
            t * t * (3.0 - 2.0 * t)
        }
    }
}

/// The run each cluster belongs to, by the run holding its first byte; `None` without runs.
fn run_of_clusters(layout: &TextLayout, runs: &[TextRun]) -> Vec<Option<usize>> {
    let mut ends = Vec::with_capacity(runs.len());
    let mut end = 0;
    for run in runs {
        end += run.text.len();
        ends.push(end);
    }
    layout
        .clusters
        .iter()
        .map(|cluster| {
            let run = ends.partition_point(|&end| end <= cluster.bytes.start);
            (run < runs.len()).then_some(run)
        })
        .collect()
}

/// A Timing selector's selection of each cluster at `time`.
#[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
fn timing(
    layout: &TextLayout,
    runs: &[TextRun],
    time: MediaTime,
    state: RunState,
    ramp: MediaTime,
    sweep: bool,
) -> Vec<f32> {
    let run_of = run_of_clusters(layout, runs);
    let ramp = ramp.ticks();
    // How far past `at` the time is, faded over the ramp: a step without one.
    let reached = |at: i64| -> f32 {
        let past = time.ticks().saturating_sub(at);
        if ramp <= 0 {
            if past >= 0 { 1.0 } else { 0.0 }
        } else {
            (past as f64 / ramp as f64).clamp(0.0, 1.0) as f32
        }
    };
    // Each run's clusters in order, for a sweep's share of the run.
    let mut place = vec![(0_usize, 0_usize); run_of.len()];
    let mut counts = vec![0_usize; runs.len()];
    for (cluster, run) in run_of.iter().enumerate() {
        if let Some(run) = run {
            place[cluster].0 = counts[*run];
            counts[*run] += 1;
        }
    }
    for (cluster, run) in run_of.iter().enumerate() {
        if let Some(run) = run {
            place[cluster].1 = counts[*run];
        }
    }
    run_of
        .iter()
        .zip(place)
        .map(|(run, (index, count))| {
            let Some(span) = run.and_then(|run| runs[run].time) else {
                return 0.0;
            };
            let (start, end) = (span.start.ticks(), span.end.ticks());
            let (a, b) = if sweep && count > 0 {
                let length = i128::from(end - start);
                let share = |at: usize| {
                    i64::try_from(i128::from(start) + length * at as i128 / count as i128)
                        .unwrap_or(end)
                };
                (share(index), share(index + 1))
            } else {
                (start, end)
            };
            let (begun, ended) = (reached(a), reached(b));
            match state {
                RunState::Upcoming => 1.0 - begun,
                RunState::Active => begun * (1.0 - ended),
                RunState::Spoken => ended,
            }
        })
        .collect()
}

/// Each cluster's state under `animators` at `time`, in pixels of a `font_size`-pixel font,
/// and a hash of the states. The hash is 0 when every state is identity, so the text draws as
/// it would without animators. `base_fill` and `base_stroke` are where color mixes start.
///
/// No selector counts the ellipsis of a clamped text. It takes the state of the cluster before
/// it, so it moves and fades with the text it ends.
#[must_use]
pub fn cluster_states(
    layout: &TextLayout,
    runs: &[TextRun],
    animators: &[SampledAnimator],
    time: MediaTime,
    font_size: f32,
) -> (Vec<ClusterState>, u64) {
    let Some(mark) = layout.clusters.iter().position(|cluster| cluster.ellipsis) else {
        return text_states(layout, runs, animators, time, font_size);
    };
    let mut text = layout.clone();
    text.clusters.remove(mark);
    for line in &mut text.lines {
        let shift = |index: usize| index - usize::from(index > mark);
        line.clusters = shift(line.clusters.start)..shift(line.clusters.end);
    }
    let (mut states, hash) = text_states(&text, runs, animators, time, font_size);
    let before = mark
        .checked_sub(1)
        .map_or(ClusterState::IDENTITY, |index| states[index]);
    states.insert(mark, before);
    (states, hash)
}

fn text_states(
    layout: &TextLayout,
    runs: &[TextRun],
    animators: &[SampledAnimator],
    time: MediaTime,
    font_size: f32,
) -> (Vec<ClusterState>, u64) {
    let mut states = vec![ClusterState::IDENTITY; layout.clusters.len()];
    // Rotation is summed in degrees and turned into radians once.
    let mut degrees = vec![0.0_f32; states.len()];
    for animator in animators {
        let weights = selection(&animator.selector, layout, runs, time);
        for ((state, degrees), weight) in states.iter_mut().zip(&mut degrees).zip(weights) {
            if weight <= 0.0 {
                continue;
            }
            if let Some([x, y]) = animator.offset {
                state.offset[0] += weight * x * font_size;
                state.offset[1] += weight * y * font_size;
            }
            if let Some(scale) = animator.scale {
                for (axis, target) in state.scale.iter_mut().zip(scale) {
                    *axis *= 1.0 + weight * (target - 1.0);
                }
                if animator.advance_follows_scale {
                    state.advance_scale *= 1.0 + weight * (scale[0] - 1.0);
                }
            }
            if let Some(rotation) = animator.rotation_degrees {
                *degrees += weight * rotation;
            }
            if let Some(opacity) = animator.opacity {
                state.opacity *= 1.0 + weight * (opacity - 1.0);
            }
            if let Some(target) = animator.fill {
                state.fill = Some(mix_toward(state.fill, target, weight));
            }
            if let Some(target) = animator.stroke {
                state.stroke = Some(mix_toward(state.stroke, target, weight));
            }
            if let Some(tracking) = animator.tracking {
                state.tracking += weight * tracking * font_size;
            }
            if let Some(reveal) = animator.reveal {
                let progress = 1.0 + weight * (reveal.progress - 1.0);
                if progress < 1.0
                    && let Some(slot) = state.reveals.iter_mut().find(|slot| slot.is_none())
                {
                    let angle = reveal.angle_degrees.to_radians();
                    *slot = Some(RevealEdge {
                        direction: [libm::cosf(angle), libm::sinf(angle)],
                        progress: progress.max(0.0),
                        feather: reveal.feather * font_size,
                    });
                }
            }
        }
    }
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    let mut feed = |value: f32| {
        for byte in value.to_bits().to_le_bytes() {
            hash = (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3);
        }
    };
    let mut identity = true;
    for (state, degrees) in states.iter_mut().zip(degrees) {
        state.rotation = degrees.to_radians();
        state.opacity = state.opacity.clamp(0.0, 1.0);
        // Scales of several animators multiply; the product keeps one animator's limit.
        state.scale = state.scale.map(|axis| axis.min(MAX_CLUSTER_SCALE));
        state.advance_scale = state.advance_scale.min(MAX_CLUSTER_SCALE);
        identity &= state.is_identity();
        let mixes = [state.fill, state.stroke].map(|mix| {
            mix.map_or([1.0, 0.0, 0.0, 0.0, 0.0], |mix| {
                [mix.keep, mix.add[0], mix.add[1], mix.add[2], mix.add[3]]
            })
        });
        for value in state
            .offset
            .into_iter()
            .chain(state.scale)
            .chain([state.rotation, state.opacity, state.tracking])
            .chain(mixes.into_iter().flatten())
        {
            feed(value);
        }
        if state.advance_scale.to_bits() != 1.0_f32.to_bits() {
            feed(state.advance_scale);
        }
        for edge in state.reveals.iter().flatten() {
            for value in [
                edge.direction[0],
                edge.direction[1],
                edge.progress,
                edge.feather,
            ] {
                feed(value);
            }
        }
    }
    (states, if identity { 0 } else { hash.max(1) })
}

/// The highlight's steps at `time` over a text of `runs`: the byte ranges of the timed runs that
/// have started, in the order they started (ties in text order), each with the eased progress of
/// its slide, the first at 1. Earlier steps a step at 1 replaces are left out. Empty before the
/// first run starts, and with [`alpha2_model::HighlightGap::Hide`] once the current run ended.
#[must_use]
pub fn highlight_steps(
    runs: &[TextRun],
    time: MediaTime,
    highlight: &alpha2_model::TextHighlight,
) -> Vec<(std::ops::Range<usize>, f32)> {
    let mut start = 0;
    let mut started = runs
        .iter()
        .filter_map(|run| {
            let bytes = start..start + run.text.len();
            start = bytes.end;
            run.time
                .filter(|span| span.start <= time)
                .map(|span| (span, bytes))
        })
        .collect::<Vec<_>>();
    started.sort_by_key(|(span, bytes)| (span.start, bytes.start));
    let Some((current, _)) = started.last() else {
        return Vec::new();
    };
    let hide = highlight.gap == alpha2_model::HighlightGap::Hide;
    if hide && time >= current.end {
        return Vec::new();
    }
    let mut steps = Vec::<(std::ops::Range<usize>, f32)>::with_capacity(started.len());
    let mut previous: Option<RunTime> = None;
    for (span, bytes) in started {
        let jumps = previous.is_none_or(|previous| hide && span.start > previous.end);
        let progress = if jumps || highlight.transition <= MediaTime::ZERO {
            1.0
        } else {
            #[expect(clippy::cast_precision_loss, reason = "ticks within ten seconds")]
            let linear =
                (time.ticks() - span.start.ticks()) as f64 / highlight.transition.ticks() as f64;
            #[expect(
                clippy::cast_possible_truncation,
                reason = "eased progress near [0, 1]"
            )]
            let eased = highlight.easing.apply(linear) as f32;
            if linear >= 1.0 {
                1.0
            } else {
                eased.clamp(0.0, 1.0)
            }
        };
        if progress >= 1.0 {
            steps.clear();
        }
        steps.push((bytes, progress));
        previous = Some(span);
    }
    if steps.len() > alpha2_text::MAX_HIGHLIGHT_STEPS {
        steps.drain(..steps.len() - alpha2_text::MAX_HIGHLIGHT_STEPS);
        steps[0].1 = 1.0;
    }
    steps
}

/// `mix` (or the color unchanged) mixed toward the straight sRGB `target` by `weight`, in
/// premultiplied linear light.
fn mix_toward(mix: Option<ColorMix>, target: [f32; 4], weight: f32) -> ColorMix {
    let mix = mix.unwrap_or(ColorMix {
        keep: 1.0,
        add: [0.0; 4],
    });
    let target = premultiplied_linear(target);
    ColorMix {
        keep: mix.keep * (1.0 - weight),
        add: std::array::from_fn(|channel| {
            mix.add[channel] * (1.0 - weight) + target[channel] * weight
        }),
    }
}

/// Straight sRGB to premultiplied linear light, as paint stops convert.
fn premultiplied_linear(color: [f32; 4]) -> [f32; 4] {
    let alpha = color[3].clamp(0.0, 1.0);
    let linear = |value: f32| {
        let value = value.clamp(0.0, 1.0);
        if value >= 1.0 {
            1.0
        } else if value <= 0.040_45 {
            value / 12.92
        } else {
            libm::powf((value + 0.055) / 1.055, 2.4)
        }
    };
    [
        linear(color[0]) * alpha,
        linear(color[1]) * alpha,
        linear(color[2]) * alpha,
        alpha,
    ]
}

#[cfg(test)]
#[path = "text_animation_tests.rs"]
mod tests;