use crate::{CubicBezier, DataBinding, Easing};
use serde::{Deserialize, Serialize};
#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Vec2 {
pub x: f32,
pub y: f32,
}
impl Vec2 {
#[must_use]
pub const fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
#[must_use]
pub fn is_zero(&self) -> bool {
self.x == 0.0 && self.y == 0.0
}
}
pub const MAX_KEYFRAMES: usize = 100_000;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum Animated<T> {
Constant {
value: T,
},
Keyframes {
keyframes: Vec<Keyframe<T>>,
},
Data(Box<DataBinding>),
}
mod sealed {
pub trait Sealed {}
}
pub trait AnimatedValue: sealed::Sealed {
const ACCEPTS_DATA: bool;
}
macro_rules! animated_value {
($accepts:literal: $($type:ty),+) => {
$(
impl sealed::Sealed for $type {}
impl AnimatedValue for $type {
const ACCEPTS_DATA: bool = $accepts;
}
)+
};
}
animated_value!(true: f32, Vec2, crate::EffectValue);
animated_value!(
false: String,
crate::Paint,
crate::Rgba,
crate::Path,
crate::LayoutLength,
crate::LayoutSize,
crate::LayoutOffset,
crate::Insets
);
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", schemars(rename = "Animated_{T}"))]
enum AnimatedWire<T> {
Constant {
value: T,
},
Keyframes {
#[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
#[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
keyframes: Vec<Keyframe<T>>,
},
Data(DataBinding),
}
impl<'de, T: Deserialize<'de> + AnimatedValue> Deserialize<'de> for Animated<T> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(match AnimatedWire::<T>::deserialize(deserializer)? {
AnimatedWire::Constant { value } => Self::Constant { value },
AnimatedWire::Keyframes { keyframes } => Self::Keyframes { keyframes },
AnimatedWire::Data(binding) if T::ACCEPTS_DATA => Self::Data(Box::new(binding)),
AnimatedWire::Data(_) => {
return Err(serde::de::Error::custom(
"this value takes no `data` mode; use `constant` or `keyframes`",
));
}
})
}
}
#[cfg(feature = "schema")]
impl<T: schemars::JsonSchema + AnimatedValue> schemars::JsonSchema for Animated<T> {
fn schema_name() -> std::borrow::Cow<'static, str> {
if T::ACCEPTS_DATA {
AnimatedWire::<T>::schema_name()
} else {
format!("Keyframed_{}", T::schema_name()).into()
}
}
fn schema_id() -> std::borrow::Cow<'static, str> {
if T::ACCEPTS_DATA {
AnimatedWire::<T>::schema_id()
} else {
format!("alpha2_model::Keyframed<{}>", T::schema_id()).into()
}
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
let mut schema = AnimatedWire::<T>::json_schema(generator);
if !T::ACCEPTS_DATA {
crate::schema::drop_data_mode(&mut schema);
schema.insert(
"description".to_owned(),
"A value that is constant or controlled by sorted keyframes.".into(),
);
}
schema
}
}
impl<T> Animated<T> {
#[must_use]
pub fn map<U>(&self, map: impl Fn(&T) -> U) -> Animated<U> {
match self {
Self::Constant { value } => Animated::Constant { value: map(value) },
Self::Keyframes { keyframes } => Animated::Keyframes {
keyframes: keyframes
.iter()
.map(|keyframe| Keyframe {
time: keyframe.time,
value: map(&keyframe.value),
interpolation: keyframe.interpolation,
})
.collect(),
},
Self::Data(binding) => Animated::Data(binding.clone()),
}
}
#[must_use]
pub const fn data(&self) -> Option<&DataBinding> {
match self {
Self::Data(binding) => Some(binding),
Self::Constant { .. } | Self::Keyframes { .. } => None,
}
}
#[must_use]
pub const fn varies(&self) -> bool {
!matches!(self, Self::Constant { .. })
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum AnimatedPoint {
Constant {
value: Vec2,
},
Keyframes {
#[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
#[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
keyframes: Vec<PointKeyframe>,
},
Data(Box<DataBinding>),
}
impl Default for AnimatedPoint {
fn default() -> Self {
Self::Constant {
value: Vec2::default(),
}
}
}
impl From<Animated<Vec2>> for AnimatedPoint {
fn from(animation: Animated<Vec2>) -> Self {
match animation {
Animated::Constant { value } => Self::Constant { value },
Animated::Keyframes { keyframes } => Self::Keyframes {
keyframes: keyframes
.into_iter()
.map(|keyframe| PointKeyframe {
time: keyframe.time,
value: keyframe.value,
interpolation: keyframe.interpolation,
out_tangent: Vec2::default(),
in_tangent: Vec2::default(),
})
.collect(),
},
Animated::Data(binding) => Self::Data(binding),
}
}
}
impl AnimatedPoint {
#[must_use]
pub const fn is_animated(&self) -> bool {
!matches!(self, Self::Constant { .. })
}
#[must_use]
pub const fn data(&self) -> Option<&DataBinding> {
match self {
Self::Data(binding) => Some(binding),
Self::Constant { .. } | Self::Keyframes { .. } => None,
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct PointKeyframe {
pub time: alpha2_time::MediaTime,
pub value: Vec2,
pub interpolation: Interpolation,
#[serde(default, skip_serializing_if = "Vec2::is_zero")]
pub out_tangent: Vec2,
#[serde(default, skip_serializing_if = "Vec2::is_zero")]
pub in_tangent: Vec2,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schema", schemars(rename = "Keyframe_{T}"))]
pub struct Keyframe<T> {
pub time: alpha2_time::MediaTime,
pub value: T,
pub interpolation: Interpolation,
}
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case", from = "InterpolationWire")]
pub enum Interpolation {
Hold,
Linear,
CubicBezier(CubicBezier),
}
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "Interpolation"))]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum InterpolationWire {
Hold {},
Linear {},
CubicBezier(CubicBezier),
}
impl From<InterpolationWire> for Interpolation {
fn from(wire: InterpolationWire) -> Self {
match wire {
InterpolationWire::Hold {} => Self::Hold,
InterpolationWire::Linear {} => Self::Linear,
InterpolationWire::CubicBezier(curve) => Self::CubicBezier(curve),
}
}
}
impl Interpolation {
#[must_use]
pub fn amount(self, progress: f64) -> Option<f64> {
match self {
Self::Hold => None,
Self::Linear => Some(Easing::Linear.apply(progress)),
Self::CubicBezier(curve) => Some(curve.apply(progress)),
}
}
#[must_use]
pub fn is_valid(self) -> bool {
match self {
Self::Hold | Self::Linear => true,
Self::CubicBezier(curve) => curve.is_valid(),
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct VisualProperties {
#[serde(default = "centre_point")]
pub position: AnimatedPoint,
#[serde(default = "centre")]
pub anchor: Vec2,
#[serde(default = "unit_scale")]
pub scale: Animated<Vec2>,
#[serde(default = "no_rotation")]
pub rotation_degrees: Animated<f32>,
#[serde(default = "opaque")]
pub opacity: Animated<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub correction: Option<crate::CorrectionRef>,
}
impl Default for VisualProperties {
fn default() -> Self {
Self {
position: centre_point(),
anchor: centre(),
scale: unit_scale(),
rotation_degrees: no_rotation(),
opacity: opaque(),
correction: None,
}
}
}
const fn centre() -> Vec2 {
Vec2::new(0.5, 0.5)
}
const fn centre_point() -> AnimatedPoint {
AnimatedPoint::Constant { value: centre() }
}
pub(crate) const fn unit_scale() -> Animated<Vec2> {
Animated::Constant {
value: Vec2::new(1.0, 1.0),
}
}
const fn no_rotation() -> Animated<f32> {
Animated::Constant { value: 0.0 }
}
pub(crate) const fn opaque() -> Animated<f32> {
Animated::Constant { value: 1.0 }
}
pub(crate) enum Keyed<'a> {
Times(&'a [alpha2_time::MediaTime]),
Data(&'a DataBinding, PlaceType),
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum PlaceType {
Point,
Vec2,
Scalar,
Effect,
Other,
}
pub(crate) trait Placed {
const PLACE: PlaceType;
}
macro_rules! placed {
($place:ident: $($type:ty),+) => {
$(impl Placed for $type {
const PLACE: PlaceType = PlaceType::$place;
})+
};
}
placed!(Scalar: f32);
placed!(Vec2: Vec2);
placed!(Effect: crate::EffectValue);
placed!(
Other: String,
crate::Paint,
crate::Rgba,
crate::Path,
crate::LayoutLength,
crate::LayoutSize,
crate::LayoutOffset,
crate::Insets
);
pub(crate) fn visit_keyed<T: Placed>(
at: &str,
animated: &Animated<T>,
visit: &mut impl FnMut(&str, Keyed<'_>),
) {
match animated {
Animated::Keyframes { keyframes } => {
let times = keyframes
.iter()
.map(|keyframe| keyframe.time)
.collect::<Vec<_>>();
visit(at, Keyed::Times(×));
}
Animated::Data(binding) => visit(at, Keyed::Data(binding, T::PLACE)),
Animated::Constant { .. } => {}
}
}
pub(crate) fn visit_keyed_point(
at: &str,
animated: &AnimatedPoint,
visit: &mut impl FnMut(&str, Keyed<'_>),
) {
match animated {
AnimatedPoint::Keyframes { keyframes } => {
let times = keyframes
.iter()
.map(|keyframe| keyframe.time)
.collect::<Vec<_>>();
visit(at, Keyed::Times(×));
}
AnimatedPoint::Data(binding) => visit(at, Keyed::Data(binding, PlaceType::Point)),
AnimatedPoint::Constant { .. } => {}
}
}
impl VisualProperties {
pub(crate) fn validate(&self) -> bool {
self.anchor.is_finite()
&& valid_point_animation(&self.position)
&& valid_vec2_animation(&self.scale)
&& valid_scalar_animation(&self.rotation_degrees, false)
&& valid_scalar_animation(&self.opacity, true)
}
}
fn valid_vec2_animation(animation: &Animated<Vec2>) -> bool {
match animation {
Animated::Constant { value } => value.is_finite(),
Animated::Keyframes { keyframes } => {
valid_keyframes(keyframes)
&& keyframes.iter().all(|keyframe| keyframe.value.is_finite())
}
Animated::Data(_) => true,
}
}
pub(crate) fn valid_point_animation(animation: &AnimatedPoint) -> bool {
match animation {
AnimatedPoint::Constant { value } => value.is_finite(),
AnimatedPoint::Data(_) => true,
AnimatedPoint::Keyframes { keyframes } => {
!keyframes.is_empty()
&& keyframes.len() <= MAX_KEYFRAMES
&& keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
&& keyframes.iter().all(|keyframe| {
keyframe.interpolation.is_valid()
&& keyframe.value.is_finite()
&& keyframe.out_tangent.is_finite()
&& keyframe.in_tangent.is_finite()
})
}
}
}
fn valid_scalar_animation(animation: &Animated<f32>, unit_interval: bool) -> bool {
let domain = if unit_interval {
crate::Domain::UNIT
} else {
crate::Domain::ANY
};
let valid_value = |value: f32| domain.contains(value);
match animation {
Animated::Constant { value } => valid_value(*value),
Animated::Keyframes { keyframes } => {
valid_keyframes(keyframes)
&& keyframes.iter().all(|keyframe| valid_value(keyframe.value))
}
Animated::Data(_) => true,
}
}
pub(crate) fn valid_scalar_values(animation: &Animated<f32>, check: impl Fn(f32) -> bool) -> bool {
let valid = |value: f32| value.is_finite() && check(value);
match animation {
Animated::Constant { value } => valid(*value),
Animated::Keyframes { keyframes } => {
valid_keyframes(keyframes) && keyframes.iter().all(|keyframe| valid(keyframe.value))
}
Animated::Data(_) => true,
}
}
pub(crate) fn valid_keyframes<T>(keyframes: &[Keyframe<T>]) -> bool {
!keyframes.is_empty()
&& keyframes.len() <= MAX_KEYFRAMES
&& keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
&& keyframes
.iter()
.all(|keyframe| keyframe.interpolation.is_valid())
}