rive_rs/animation/
key_frame_color.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::animation::KeyFrame;
6use crate::core::{Core, Object, ObjectRef, OnAdded, Property};
7use crate::shapes::paint::Color32;
8
9use super::Animator;
10
11#[derive(Debug, Default)]
12pub struct KeyFrameColor {
13    key_frame: KeyFrame,
14    value: Property<Color32>,
15}
16
17impl ObjectRef<'_, KeyFrameColor> {
18    pub fn value(&self) -> Color32 {
19        self.value.get()
20    }
21
22    pub fn set_value(&self, value: Color32) {
23        self.value.set(value);
24    }
25}
26
27fn apply_color(core: Object, property_key: u64, mix: f32, value: Color32) {
28    let core = core.as_ref();
29    let property = core
30        .get_property::<Color32>(property_key as u16)
31        .expect("KeyFrameColor references wrong property");
32    if mix == 1.0 {
33        core.animate(&core, property_key, &Animator::new(value));
34    } else {
35        core.animate(&core, property_key, &Animator::new(property.get().lerp(value, mix)));
36    }
37}
38
39impl ObjectRef<'_, KeyFrameColor> {
40    pub fn apply(&self, core: Object, property_key: u64, mix: f32) {
41        apply_color(core, property_key, mix, self.value());
42    }
43
44    pub fn apply_interpolation(
45        &self,
46        core: Object,
47        property_key: u64,
48        current_time: f32,
49        next_frame: ObjectRef<'_, KeyFrame>,
50        mix: f32,
51    ) {
52        let key_frame = self.cast::<KeyFrame>();
53        let next_color = next_frame.cast::<KeyFrameColor>();
54        let mut f =
55            (current_time - key_frame.seconds()) / (next_frame.seconds() - key_frame.seconds());
56
57        if let Some(cubic_interpolator) = key_frame.interpolator() {
58            f = cubic_interpolator.as_ref().transform(f);
59        }
60
61        apply_color(core, property_key, mix, self.value().lerp(next_color.value(), f));
62    }
63}
64
65impl Core for KeyFrameColor {
66    parent_types![(key_frame, KeyFrame)];
67
68    properties![(88, value, set_value), key_frame];
69}
70
71impl OnAdded for ObjectRef<'_, KeyFrameColor> {
72    on_added!(KeyFrame);
73}