motion-core 0.2.0

Backend-independent motion engine primitives
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
//! Snapshot transitions; all captures use the shared linear fill pipeline.
//!
//! ```
//! use motion_core::prelude::*;
//! use motion_core::{
//!     DisplayList, RasterLimits, ResourceStore, ValidatedDisplayList, MAX_PATH_VERBS,
//!     MAX_STROKE_VERBS, MAX_SVG_PATH_BYTES, sample_offsets,
//! };
//! use motion_core::authoring::Scene as _;
//! let first = (|context: &SceneContext<'_>| Node::from(context.bounds().fill(Color::WHITE)))
//!     .with_duration(1.seconds());
//! let next = (|context: &SceneContext<'_>| Node::from(context.bounds().fill(Color::BLACK)))
//!     .with_duration(1.seconds());
//! let timeline = Timeline::new(Size::new(8.0, 4.0), fps!(30)).track(|track| {
//!     track
//!         .push(first)
//!         .transition(CrossFade, 500.milliseconds())
//!         .push(next)
//! }).build()?;
//! assert_eq!(timeline.frame_count(), 45);
//! let cache = SceneCache::default();
//! let context = SceneContext::new(Time::ZERO, timeline.frame_rate(), timeline.size(), &cache);
//! timeline.render(&context).compile(
//!     timeline.size(),
//!     PixelSize::new(8, 4),
//!     ValidationLimits::default(),
//! )?;
//! # Ok::<(), motion_core::Error>(())
//! ```

use crate::{Color, Node, NodeModifiers, Point, Rect, SceneContext, Shape};

/// A stateless composition of two already evaluated clip snapshots.
pub trait Transition: Send + Sync {
    /// Composes finite progress in 0..=1 inside the context design viewport.
    fn compose(
        &self,
        progress: f64,
        outgoing: Node,
        incoming: Node,
        context: &SceneContext<'_>,
    ) -> Node;

    /// continuous-time easing; finite overshoot is clamped by the scheduler.
    fn easing(&self) -> crate::Easing {
        crate::Easing::Linear
    }
}

impl Transition for std::sync::Arc<dyn Transition> {
    fn compose(
        &self,
        progress: f64,
        outgoing: Node,
        incoming: Node,
        context: &SceneContext<'_>,
    ) -> Node {
        self.as_ref().compose(progress, outgoing, incoming, context)
    }

    fn easing(&self) -> crate::Easing {
        self.as_ref().easing()
    }
}

struct Failure(crate::ValidationError);

impl crate::Drawable for Failure {
    fn bounds(&self, _: &crate::DrawContext) -> Result<Rect, crate::ValidationError> {
        Err(self.0.clone())
    }

    fn draw(
        &self,
        _: &crate::DrawContext,
        _: &mut crate::Canvas<'_>,
    ) -> Result<(), crate::ValidationError> {
        Err(self.0.clone())
    }
}

/// Retains a construction failure as a checked node instead of drawing fallback content.
pub fn diagnostic(error: crate::ValidationError) -> Node {
    Node::from(Failure(error))
}

pub(crate) fn failure(field: &str, message: &str) -> Node {
    diagnostic(crate::ValidationError::invalid(
        "transition",
        field,
        message,
    ))
}

fn sum(samples: impl IntoIterator<Item = (Node, f64)>) -> Node {
    Node::weighted_sum(samples).expect("bounded built-in transition weights")
}

fn endpoint(
    progress: f64,
    outgoing: &Node,
    incoming: &Node,
    context: &SceneContext<'_>,
) -> Option<Node> {
    if !progress.is_finite() || !(0.0..=1.0).contains(&progress) {
        return Some(failure(
            "progress",
            "Transition progress must be finite in 0..=1",
        ));
    }
    if progress == 0.0 {
        return Some(
            Node::group([
                outgoing.clone(),
                Node::group([incoming.clone()]).opacity(0.0),
            ])
            .clip_with(context.bounds(), crate::ClipMode::Geometric),
        );
    }
    if progress == 1.0 {
        return Some(
            Node::group([
                Node::group([outgoing.clone()]).opacity(0.0),
                incoming.clone(),
            ])
            .clip_with(context.bounds(), crate::ClipMode::Geometric),
        );
    }
    None
}

fn select(mask: Node, outgoing: Node, incoming: Node, context: &SceneContext<'_>) -> Node {
    sum([
        (
            outgoing.mask(mask.clone(), crate::MaskMode::InvertedAlpha),
            1.0,
        ),
        (incoming.mask(mask, crate::MaskMode::Alpha), 1.0),
    ])
    .clip_with(context.bounds(), crate::ClipMode::Geometric)
}

/// Exact linear-premultiplied interpolation, including transparent snapshots.
#[derive(Clone, Copy, Debug, Default)]
pub struct CrossFade;

impl Transition for CrossFade {
    fn compose(
        &self,
        progress: f64,
        outgoing: Node,
        incoming: Node,
        context: &SceneContext<'_>,
    ) -> Node {
        if let Some(node) = endpoint(progress, &outgoing, &incoming, context) {
            return node;
        }
        sum([(outgoing, 1.0 - progress), (incoming, progress)])
            .clip_with(context.bounds(), crate::ClipMode::Geometric)
    }
}

/// Incoming viewport moves in the selected direction over a stationary outgoing view.
#[derive(Clone, Copy, Debug)]
pub struct Slide {
    /// Incoming travel direction.
    pub direction: Direction,
}

/// Both viewports move in the selected direction with an adjoining boundary.
#[derive(Clone, Copy, Debug)]
pub struct Push {
    /// Viewport travel direction.
    pub direction: Direction,
}

fn displacement(direction: Direction, context: &SceneContext<'_>) -> (f64, f64) {
    match direction {
        Direction::Left => (-context.size().width, 0.0),
        Direction::Right => (context.size().width, 0.0),
        Direction::Up => (0.0, -context.size().height),
        Direction::Down => (0.0, context.size().height),
    }
}

impl Transition for Slide {
    fn compose(
        &self,
        progress: f64,
        outgoing: Node,
        incoming: Node,
        context: &SceneContext<'_>,
    ) -> Node {
        if let Some(node) = endpoint(progress, &outgoing, &incoming, context) {
            return node;
        }
        let (horizontal, vertical) = displacement(self.direction, context);
        let offset = (-horizontal * (1.0 - progress), -vertical * (1.0 - progress));
        let mask = Node::from(context.bounds().fill(Color::WHITE)).translate(offset.0, offset.1);
        let incoming = incoming
            .clip_with(context.bounds(), crate::ClipMode::Geometric)
            .translate(offset.0, offset.1);
        sum([
            (outgoing.mask(mask, crate::MaskMode::InvertedAlpha), 1.0),
            (incoming, 1.0),
        ])
        .clip_with(context.bounds(), crate::ClipMode::Geometric)
    }
}

impl Transition for Push {
    fn compose(
        &self,
        progress: f64,
        outgoing: Node,
        incoming: Node,
        context: &SceneContext<'_>,
    ) -> Node {
        if let Some(node) = endpoint(progress, &outgoing, &incoming, context) {
            return node;
        }
        let (horizontal, vertical) = displacement(self.direction, context);
        sum([
            (
                outgoing
                    .clip_with(context.bounds(), crate::ClipMode::Geometric)
                    .translate(horizontal * progress, vertical * progress),
                1.0,
            ),
            (
                incoming
                    .clip_with(context.bounds(), crate::ClipMode::Geometric)
                    .translate(-horizontal * (1.0 - progress), -vertical * (1.0 - progress)),
                1.0,
            ),
        ])
        .clip_with(context.bounds(), crate::ClipMode::Geometric)
    }
}

/// Projection wipe: radians from +X, with a nonnegative logical-pixel feather.
#[derive(Clone, Copy, Debug, Default)]
pub struct Wipe {
    /// Direction of the advancing edge's normal.
    pub angle: f64,
    /// Linear transition width in design pixels; zero is hard.
    pub feather: f64,
}

impl Transition for Wipe {
    fn compose(
        &self,
        progress: f64,
        outgoing: Node,
        incoming: Node,
        context: &SceneContext<'_>,
    ) -> Node {
        if !self.angle.is_finite() || !self.feather.is_finite() || self.feather < 0.0 {
            return failure("wipe", "Wipe requires finite angle and nonnegative feather");
        }
        if let Some(node) = endpoint(progress, &outgoing, &incoming, context) {
            return node;
        }
        let normal = Point::new(libm::cos(self.angle), libm::sin(self.angle));
        let projections = [
            0.0,
            context.size().width * normal.x,
            context.size().height * normal.y,
            context.size().width * normal.x + context.size().height * normal.y,
        ];
        let minimum = projections.iter().copied().fold(f64::INFINITY, f64::min);
        let maximum = projections
            .iter()
            .copied()
            .fold(f64::NEG_INFINITY, f64::max);
        let position = minimum - self.feather * 0.5 + (maximum - minimum + self.feather) * progress;
        let mask = if self.feather == 0.0 {
            let radius = libm::hypot(context.size().width, context.size().height) * 2.0;
            Node::from(Rect::new(-radius, -radius, position, radius).fill(Color::WHITE))
                .pivot(crate::Pivot::Point(Point::ORIGIN))
                .rotate(self.angle)
        } else {
            let first = Point::new(
                normal.x * (position - self.feather * 0.5),
                normal.y * (position - self.feather * 0.5),
            );
            let last = Point::new(
                normal.x * (position + self.feather * 0.5),
                normal.y * (position + self.feather * 0.5),
            );
            Node::from(
                context.bounds().fill(
                    crate::LinearGradient::new(first, last)
                        .stop(0.0, Color::WHITE)
                        .stop(1.0, Color::WHITE.with_alpha(0.0))
                        .units(crate::GradientUnits::UserSpace)
                        .space(crate::GradientSpace::LinearRgb),
                ),
            )
        };
        select(mask, outgoing, incoming, context)
    }
}

/// Built-in iris reveal geometry centered in the design viewport.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "snake_case")
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum IrisShape {
    /// Circle reaches every viewport corner at progress one.
    #[default]
    Circle,
    /// Rectangle grows proportionally in both dimensions.
    Rectangle,
}

/// Centered growing-shape selection of the incoming snapshot.
#[derive(Clone, Copy, Debug, Default)]
pub struct Iris {
    /// Reveal geometry.
    pub shape: IrisShape,
}

impl Transition for Iris {
    fn compose(
        &self,
        progress: f64,
        outgoing: Node,
        incoming: Node,
        context: &SceneContext<'_>,
    ) -> Node {
        if let Some(node) = endpoint(progress, &outgoing, &incoming, context) {
            return node;
        }
        let center = context.center();
        let mask = match self.shape {
            IrisShape::Circle => {
                match crate::Circle::new(center, libm::hypot(center.x, center.y) * progress) {
                    Ok(circle) => Node::from(circle.fill(Color::WHITE)),
                    Err(error) => return diagnostic(error),
                }
            }
            IrisShape::Rectangle => Node::from(
                Rect::new(
                    center.x * (1.0 - progress),
                    center.y * (1.0 - progress),
                    center.x * (1.0 + progress),
                    center.y * (1.0 + progress),
                )
                .fill(Color::WHITE),
            ),
        };
        select(mask, outgoing, incoming, context)
    }
}

/// Twelve spatial zoom samples per snapshot; no Gaussian substitute or time resampling.
#[derive(Clone, Copy, Debug, Default)]
pub struct ZoomBlur;

impl Transition for ZoomBlur {
    fn compose(
        &self,
        progress: f64,
        outgoing: Node,
        incoming: Node,
        context: &SceneContext<'_>,
    ) -> Node {
        if let Some(node) = endpoint(progress, &outgoing, &incoming, context) {
            return node;
        }
        let blur = |node: Node, base: f64| {
            let samples = (0..12).map(|index| {
                node.clone()
                    .clip_with(context.bounds(), crate::ClipMode::Geometric)
                    .pivot(crate::Pivot::Point(context.center()))
                    .scale(
                        base + libm::sin(std::f64::consts::PI * progress)
                            * 0.2
                            * (f64::from(index) + 0.5)
                            / 12.0,
                    )
            });
            Node::accumulate(samples).expect("fixed zoom samples")
        };
        CrossFade.compose(
            progress,
            blur(outgoing, 1.0 + progress * 0.25),
            blur(incoming, 0.75 + progress * 0.25),
            context,
        )
    }
}

/// A movement vector in layer-local coordinates, not the edge of entry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "snake_case")
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Direction {
    /// Move/reveal toward decreasing X; incoming push content enters from the right.
    Left,
    /// Move/reveal toward increasing X; incoming push content enters from the left.
    Right,
    /// Move/reveal toward decreasing Y; incoming push content enters from below.
    Up,
    /// Move/reveal toward increasing Y; incoming push content enters from above.
    Down,
}