alpha2-eval 0.10.0

Pure alpha2 timeline evaluation.
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Keyframe curve services on project-form JSON; times in ticks, velocities in value per second.

use super::{time, to_text};
use crate::curves::{self, AutoTangent, CurveError, SegmentKind};
use alpha2_model::{Animated, AnimatedPoint, Interpolation, ValueBezier};
use alpha2_time::{MediaTime, TimeRange};
use serde_json::{Value, json};

fn number(json: &str) -> Result<Animated<f32>, String> {
    let animation: Animated<f32> =
        serde_json::from_str(json).map_err(|error| format!("invalid curve: {error}"))?;
    if !animation.is_valid() {
        return Err("invalid curve: not an animated number a project can hold".into());
    }
    Ok(animation)
}

fn refused(error: CurveError) -> String {
    format!("invalid curve: {error}")
}

fn range(start: f64, end: f64) -> Result<TimeRange, String> {
    TimeRange::new(time(start)?, time(end)?)
        .map_err(|_| "invalid curve: the range ends before it starts".to_owned())
}

fn finite(values: &[f64]) -> Result<(), String> {
    if values.iter().all(|value| value.is_finite()) {
        Ok(())
    } else {
        Err("invalid curve: a number is not finite".into())
    }
}

fn length(seconds: f64) -> Result<(), String> {
    if seconds.is_finite() && seconds > 0.0 {
        Ok(())
    } else {
        Err(format!(
            "invalid curve: a segment is longer than no time, not {seconds} seconds"
        ))
    }
}

fn value_curve(curve: ValueBezier) -> Result<String, String> {
    to_text(&Interpolation::ValueBezier(curve))
}

pub(crate) const fn kind_name(kind: SegmentKind) -> &'static str {
    match kind {
        SegmentKind::Hold => "hold",
        SegmentKind::Linear => "linear",
        SegmentKind::Timing => "timing",
        SegmentKind::Value => "value",
        SegmentKind::Steps => "steps",
        SegmentKind::Points => "points",
    }
}

pub(crate) fn tangent_mode(mode: &str) -> Result<AutoTangent, String> {
    match mode {
        "smooth" => Ok(AutoTangent::Smooth),
        "monotone" => Ok(AutoTangent::Monotone),
        "flat" => Ok(AutoTangent::Flat),
        "linear" => Ok(AutoTangent::Linear),
        other => Err(format!(
            "invalid curve: a tangent mode is smooth, monotone, flat or linear, not {other}"
        )),
    }
}

/// The segments of an animated number as JSON `[{ kind, start, end, controls }]`.
///
/// # Errors
/// Refuses a value that is not a valid animated number.
pub fn curve_segments(animation_json: &str) -> Result<String, String> {
    let point = |(time, value): (f64, f64)| json!({ "time": time, "value": value });
    #[expect(clippy::cast_precision_loss, reason = "ticks as a JSON number")]
    let key = |(time, value): (i64, f64)| point((time as f64, value));
    let segments: Vec<Value> = curves::segments(&number(animation_json)?)
        .into_iter()
        .map(|segment| {
            json!({
                "kind": kind_name(segment.kind),
                "start": key(segment.start),
                "end": key(segment.end),
                "controls": segment.controls.map(|[first, second]| json!([point(first), point(second)])),
            })
        })
        .collect();
    to_text(&segments)
}

/// The value and velocity at each time, as JSON `[[value, velocity]]`.
///
/// # Errors
/// Refuses a value that is not a valid animated number.
pub fn sample_curve(animation_json: &str, times: &[i64]) -> Result<String, String> {
    let times: Vec<MediaTime> = times.iter().copied().map(MediaTime).collect();
    let samples: Vec<Value> = curves::sample(&number(animation_json)?, &times)
        .into_iter()
        .map(|sample| json!([sample.value, sample.velocity]))
        .collect();
    to_text(&samples)
}

/// The least and greatest value over a range of ticks, as JSON `[low, high]`.
///
/// # Errors
/// Refuses a value that is not a valid animated number, or a bad range.
pub fn curve_range(animation_json: &str, start: f64, end: f64) -> Result<String, String> {
    to_text(&curves::range(&number(animation_json)?, range(start, end)?))
}

/// The animated number with a keyframe added that changes no value.
///
/// # Errors
/// Refuses a value that is not a valid animated number, a time outside its keyframes or on
/// one, and a value already at the keyframe limit.
pub fn insert_key(animation_json: &str, ticks: f64) -> Result<String, String> {
    let mut animation = number(animation_json)?;
    curves::insert_key(&mut animation, time(ticks)?).map_err(refused)?;
    to_text(&animation)
}

/// The position with a keyframe added that changes neither its path nor its speed.
///
/// # Errors
/// As [`insert_key`], and where the timing curve overshoots at the time or a part of it has no
/// timing curve.
pub fn insert_point_key(
    point_json: &str,
    ticks: f64,
    width: u32,
    height: u32,
) -> Result<String, String> {
    let size = super::canvas(width, height)?;
    let mut point: AnimatedPoint =
        serde_json::from_str(point_json).map_err(|error| format!("invalid curve: {error}"))?;
    if !point.is_valid() {
        return Err("invalid curve: not a position a project can hold".into());
    }
    curves::insert_point_key(&mut point, time(ticks)?, super::aspect(size)).map_err(refused)?;
    to_text(&point)
}

/// The animated number with timing curves and straight lines as value curves.
///
/// # Errors
/// Refuses a value that is not a valid animated number.
pub fn to_value_curves(animation_json: &str) -> Result<String, String> {
    let mut animation = number(animation_json)?;
    curves::to_value_curves(&mut animation);
    to_text(&animation)
}

/// The animated number with value curves as timing curves.
///
/// # Errors
/// Refuses a value that is not a valid animated number, or one with a value curve between two
/// equal keyframes.
pub fn to_timing_curves(animation_json: &str) -> Result<String, String> {
    let mut animation = number(animation_json)?;
    curves::to_timing_curves(&mut animation).map_err(refused)?;
    to_text(&animation)
}

/// The animated number with handles computed from its keyframes, at `keys` or at all of them.
///
/// # Errors
/// Refuses a value that is not a valid animated number, or an unknown mode.
pub fn auto_tangents(
    animation_json: &str,
    mode: &str,
    keys: Option<&[i64]>,
) -> Result<String, String> {
    let mode = tangent_mode(mode)?;
    let mut animation = number(animation_json)?;
    let keys: Option<Vec<MediaTime>> =
        keys.map(|keys| keys.iter().copied().map(MediaTime).collect());
    curves::auto_tangents(&mut animation, mode, keys.as_deref());
    to_text(&animation)
}

/// A value curve from a speed and an influence at each end, as `(speed, influence)`.
///
/// # Errors
/// Refuses a segment without length and numbers that are not finite.
pub fn curve_from_speed_influence(
    seconds: f64,
    leave: (f64, f64),
    arrive: (f64, f64),
) -> Result<String, String> {
    length(seconds)?;
    finite(&[leave.0, leave.1, arrive.0, arrive.1])?;
    value_curve(curves::from_speed_influence(seconds, leave, arrive))
}

/// A value curve from the slope at each end.
///
/// # Errors
/// Refuses a segment without length and numbers that are not finite.
pub fn curve_from_slopes(seconds: f64, leave: f64, arrive: f64) -> Result<String, String> {
    length(seconds)?;
    finite(&[leave, arrive])?;
    value_curve(curves::from_slopes(seconds, leave, arrive))
}

/// A value curve from its four control points, as eight numbers.
///
/// # Errors
/// Refuses a segment without length and numbers that are not finite.
pub fn curve_from_handle_points(points: &[f64]) -> Result<String, String> {
    let &[t0, v0, t1, v1, t2, v2, t3, v3] = points else {
        return Err(format!(
            "invalid curve: four control points are 8 numbers, not {}",
            points.len()
        ));
    };
    finite(points)?;
    length(t3 - t0)?;
    value_curve(curves::from_handle_points(
        (t0, v0),
        (t1, v1),
        (t2, v2),
        (t3, v3),
    ))
}

/// A value curve with its handles shortened into the segment; other interpolations as given.
///
/// # Errors
/// Refuses JSON that is not an interpolation.
pub fn contain_curve(interpolation_json: &str) -> Result<String, String> {
    let interpolation: Interpolation = serde_json::from_str(interpolation_json)
        .map_err(|error| format!("invalid curve: {error}"))?;
    to_text(&match interpolation {
        Interpolation::ValueBezier(curve) => Interpolation::ValueBezier(curves::contain(curve)),
        other => other,
    })
}

/// The clockwise angle in degrees of a position's path where the position is.
///
/// # Errors
/// Refuses a value that is not a valid position, or a bad size or time.
pub fn path_angle(point_json: &str, ticks: f64, width: u32, height: u32) -> Result<f64, String> {
    let size = super::canvas(width, height)?;
    let point: AnimatedPoint =
        serde_json::from_str(point_json).map_err(|error| format!("invalid curve: {error}"))?;
    if !point.is_valid() {
        return Err("invalid curve: not a position a project can hold".into());
    }
    Ok(crate::path_angle(
        &point,
        time(ticks)?,
        super::aspect(size),
        &crate::SampleContext::NONE,
    ))
}

/// The easing a name stands for, as JSON.
///
/// # Errors
/// Refuses a name that is no easing's.
pub fn easing_preset(name: &str) -> Result<String, String> {
    let easing = alpha2_model::easing_presets::named(name).ok_or_else(|| {
        format!(
            "invalid curve: no easing is named {name}; the names are the CSS ones, step-start, \
             step-end, and ease-in-, ease-out- or ease-in-out- before one of {}",
            alpha2_model::easing_presets::EASING_FAMILIES.join(", ")
        )
    })?;
    to_text(&easing)
}

/// A spring's motion, from `(mass, stiffness, damping, velocity)`, as JSON
/// `{ easing, settleSeconds }`.
///
/// # Errors
/// Refuses a spring that cannot be or does not settle, and a tolerance that is not above 0.
pub fn spring_easing(
    (mass, stiffness, damping, velocity): (f64, f64, f64, f64),
    tolerance: f64,
    max_points: u32,
) -> Result<String, String> {
    if !(tolerance.is_finite() && tolerance > 0.0) {
        return Err(format!(
            "invalid curve: a tolerance is above 0, not {tolerance}"
        ));
    }
    let made = alpha2_model::easing_presets::spring(
        alpha2_model::easing_presets::Spring {
            mass,
            stiffness,
            damping,
            velocity,
        },
        tolerance,
        max_points as usize,
    )
    .ok_or_else(|| {
        format!(
            "invalid curve: a spring has a mass, a stiffness and a damping above 0, and settles \
             within {} seconds",
            alpha2_model::easing_presets::MAX_SPRING_SECONDS
        )
    })?;
    to_text(&json!({ "easing": made.easing, "settleSeconds": made.settle_seconds }))
}

/// The animated number with its extrapolation over a range written as keyframes.
///
/// # Errors
/// Refuses a value that is not a valid animated number, a bad range, and a result past the
/// keyframe limit.
pub fn materialize_curve(animation_json: &str, start: f64, end: f64) -> Result<String, String> {
    let mut animation = number(animation_json)?;
    curves::materialize(&mut animation, range(start, end)?).map_err(refused)?;
    to_text(&animation)
}

/// The keyframes that show what a position on a path shows over a range of ticks.
///
/// # Errors
/// Refuses a value that is not a valid position, one not on a path or whose distance is bound
/// to data, a bad range or size, and a result past the keyframe limit.
pub fn path_to_keys(
    point_json: &str,
    start: f64,
    end: f64,
    width: u32,
    height: u32,
) -> Result<String, String> {
    let size = super::canvas(width, height)?;
    let point: AnimatedPoint =
        serde_json::from_str(point_json).map_err(|error| format!("invalid curve: {error}"))?;
    if !point.is_valid() {
        return Err("invalid curve: not a position a project can hold".into());
    }
    let AnimatedPoint::Path(motion) = point else {
        return Err("invalid curve: the position is not on a path".into());
    };
    let keys =
        curves::path_to_keys(&motion, range(start, end)?, super::aspect(size)).map_err(refused)?;
    to_text(&keys)
}

/// Answers on fixed inputs that every surface gives byte for byte
/// (`tests/golden/curve_services.json`), by service name.
///
/// # Panics
/// Panics if a fixed input is refused.
#[must_use]
pub fn parity_cases() -> Vec<(&'static str, String)> {
    let number = r#"{ "mode": "keyframes", "after": "ping_pong", "keyframes": [
        { "time": 0, "value": 0.25,
          "interpolation": { "type": "cubic_bezier", "x1": 0.9, "y1": -0.5, "x2": 0, "y2": 1.5 } },
        { "time": 1200, "value": 2,
          "interpolation": { "type": "value_bezier", "x1": 0.25, "leave": 1.5, "x2": 0.5, "arrive": -3 } },
        { "time": 3000, "value": -1, "interpolation": { "type": "linear" } },
        { "time": 3600, "value": 0.5, "interpolation": { "type": "hold" } },
        { "time": 4800, "value": 1, "interpolation": { "type": "linear" } } ] }"#;
    let position = r#"{ "mode": "keyframes", "keyframes": [
        { "time": 0, "value": { "x": 0.2, "y": 0.5 },
          "interpolation": { "type": "cubic_bezier", "x1": 0.42, "y1": 0, "x2": 0.58, "y2": 1 },
          "out_tangent": { "x": 0.1, "y": -0.3 } },
        { "time": 1000, "value": { "x": 0.8, "y": 0.5 }, "interpolation": { "type": "hold" },
          "in_tangent": { "x": -0.1, "y": -0.3 } } ] }"#;
    let valued = to_value_curves(number).expect("value curves");
    vec![
        ("curveSegments", curve_segments(number).expect("segments")),
        (
            "sampleCurve",
            sample_curve(number, &[-300, 0, 600, 1200, 2100, 3300, 4800, 5400, 9000])
                .expect("samples"),
        ),
        (
            "curveRange",
            curve_range(number, -1000.0, 12_000.0).expect("range"),
        ),
        ("insertKey", insert_key(number, 700.0).expect("a key")),
        ("insertValueKey", insert_key(number, 2000.0).expect("a key")),
        (
            "insertPointKey",
            insert_point_key(position, 400.0, 320, 180).expect("a position key"),
        ),
        (
            "toTimingCurves",
            to_timing_curves(&valued).expect("timing curves"),
        ),
        ("toValueCurves", valued),
        (
            "autoTangents",
            ["smooth", "monotone", "flat", "linear"]
                .map(|mode| auto_tangents(number, mode, None).expect("tangents"))
                .join("\n"),
        ),
        (
            "autoTangentsAtOneKey",
            auto_tangents(number, "smooth", Some(&[1200])).expect("tangents"),
        ),
        (
            "curveFromSpeedInfluence",
            curve_from_speed_influence(0.5, (3.0, 20.0), (-1.0, 50.0)).expect("a curve"),
        ),
        (
            "curveFromSlopes",
            curve_from_slopes(2.0, 1.5, -0.5).expect("a curve"),
        ),
        (
            "curveFromHandlePoints",
            curve_from_handle_points(&[10.0, 1.0, 24.0, 4.0, 8.0, -2.0, 18.0, 3.0])
                .expect("a curve"),
        ),
        (
            "containCurve",
            contain_curve(
                r#"{ "type": "value_bezier", "x1": 1.75, "leave": 3, "x2": -0.25, "arrive": -2 }"#,
            )
            .expect("a curve"),
        ),
        (
            "materializeCurve",
            materialize_curve(number, 0.0, 12_000.0).expect("keyframes"),
        ),
        (
            "pathToKeys",
            path_to_keys(PATH_POSITION, 0.0, 12_000.0, 320, 180).expect("position keys"),
        ),
    ]
    .into_iter()
    .chain(stepped_and_made_cases())
    .collect()
}

const PATH_POSITION: &str = r#"{ "mode": "path",
    "path": { "subpaths": [ { "closed": true, "vertices": [
        { "point": { "x": 0.2, "y": 0.3 }, "out_tangent": { "x": 0.3, "y": 0 } },
        { "point": { "x": 0.8, "y": 0.7 }, "in_tangent": { "x": 0, "y": -0.25 } },
        { "point": { "x": 0.3, "y": 0.8 } } ] } ] },
    "distance": { "mode": "keyframes", "after": "ping_pong", "keyframes": [
        { "time": 0, "value": -0.1,
          "interpolation": { "type": "cubic_bezier", "x1": 0.42, "y1": -0.4, "x2": 0.58, "y2": 1 } },
        { "time": 6000, "value": 1.2,
          "interpolation": { "type": "value_bezier", "leave": 0.5, "arrive": 0.5 } },
        { "time": 9000, "value": 1.2, "interpolation": { "type": "hold" } } ] } }"#;

fn stepped_and_made_cases() -> Vec<(&'static str, String)> {
    let stepped = r#"{ "mode": "keyframes", "before": "ping_pong", "keyframes": [
        { "time": 100, "value": 0.5,
          "interpolation": { "type": "steps", "count": 3, "position": "start" } },
        { "time": 160, "value": 2, "interpolation": { "type": "points", "points": [
            { "x": 0.25, "y": 1.5 }, { "x": 0.625, "y": -0.5 } ] } },
        { "time": 240, "value": 0.25, "interpolation": { "type": "linear" } } ] }"#;
    vec![
        (
            "steppedSegments",
            curve_segments(stepped).expect("segments"),
        ),
        (
            "steppedSamples",
            sample_curve(stepped, &[40, 99, 100, 101, 120, 140, 159, 180, 210, 240])
                .expect("samples"),
        ),
        (
            "insertSteppedKey",
            insert_key(stepped, 130.0).expect("held keys"),
        ),
        (
            "insertTableKey",
            insert_key(stepped, 200.0).expect("two tables"),
        ),
        (
            "materializeStepped",
            materialize_curve(stepped, 0.0, 240.0).expect("keyframes"),
        ),
        (
            "easingPresets",
            alpha2_model::easing_presets::easing_names()
                .iter()
                .map(|name| easing_preset(name).expect("a preset"))
                .collect::<Vec<_>>()
                .join("\n"),
        ),
        (
            "springEasing",
            [(10.0, 0.0), (20.0, 0.0), (45.0, -3.0)]
                .map(|(damping, velocity)| {
                    spring_easing((1.0, 100.0, damping, velocity), 5e-4, 64).expect("a spring")
                })
                .join("\n"),
        ),
    ]
}

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