Skip to main content

alpha2_model/
generator.rs

1//! Sources the engine draws itself: fills, gradients, shapes, and text.
2
3use crate::{
4    ClipEffect, GeneratorIssue, LayoutNode, MAX_TEXT_CONTENT_BYTES, MAX_TEXT_GENERATOR_FONT_SIZE,
5    ShapeItem, TextStyle, Vec2,
6};
7use serde::{Deserialize, Serialize};
8
9/// Most stops in one gradient.
10pub const MAX_GRADIENT_STOPS: usize = 16;
11
12/// A straight (not premultiplied), sRGB-encoded color with alpha, each component in `0..=1`.
13///
14/// Read from the object or CSS hex (`"#rgb"`, `"#rgba"`, `"#rrggbb"`, `"#rrggbbaa"`, any
15/// case). Always written back as the object, since components need not be multiples of 1/255.
16#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
17#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
18#[cfg_attr(
19    feature = "schema",
20    schemars(rename = "Rgba", transform = crate::schema::with_hex_form)
21)]
22#[serde(remote = "Self", deny_unknown_fields)]
23pub struct Rgba {
24    /// Red component.
25    pub red: f32,
26    /// Green component.
27    pub green: f32,
28    /// Blue component.
29    pub blue: f32,
30    /// Coverage.
31    pub alpha: f32,
32}
33
34impl Rgba {
35    /// Creates a color from sRGB-encoded components and alpha.
36    #[must_use]
37    pub const fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
38        Self {
39            red,
40            green,
41            blue,
42            alpha,
43        }
44    }
45
46    pub(crate) fn is_valid(self) -> bool {
47        [self.red, self.green, self.blue, self.alpha]
48            .iter()
49            .all(|value| (0.0..=1.0).contains(value))
50    }
51
52    /// The color a CSS hex string names, if it is one.
53    #[must_use]
54    pub fn from_hex(text: &str) -> Option<Self> {
55        let digits = text.strip_prefix('#')?.as_bytes();
56        let nibble = |index: usize| char::from(digits[index]).to_digit(16);
57        let component = |value: u32| u8::try_from(value).ok().map(|byte| f32::from(byte) / 255.0);
58        let channels = match digits.len() {
59            3 | 4 => (0..digits.len())
60                .map(|index| component(nibble(index)? * 17))
61                .collect::<Option<Vec<_>>>()?,
62            6 | 8 => (0..digits.len() / 2)
63                .map(|index| component(nibble(index * 2)? * 16 + nibble(index * 2 + 1)?))
64                .collect::<Option<Vec<_>>>()?,
65            _ => return None,
66        };
67        Some(Self::new(
68            channels[0],
69            channels[1],
70            channels[2],
71            channels.get(3).copied().unwrap_or(1.0),
72        ))
73    }
74}
75
76/// Reads a hex string or the object.
77struct RgbaVisitor;
78
79impl<'de> serde::de::Visitor<'de> for RgbaVisitor {
80    type Value = Rgba;
81
82    fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        formatter.write_str("a color: the {red, green, blue, alpha} object or a CSS hex string")
84    }
85
86    fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Rgba, E> {
87        Rgba::from_hex(value).ok_or_else(|| {
88            E::custom(format!(
89                "invalid color \"{value}\": write #rgb, #rgba, #rrggbb, or #rrggbbaa"
90            ))
91        })
92    }
93
94    fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<Rgba, A::Error> {
95        Rgba::deserialize(serde::de::value::MapAccessDeserializer::new(map))
96    }
97}
98
99impl<'de> Deserialize<'de> for Rgba {
100    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
101        deserializer.deserialize_any(RgbaVisitor)
102    }
103}
104
105impl Serialize for Rgba {
106    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
107        Self::serialize(self, serializer)
108    }
109}
110
111/// The picture of a generated source.
112///
113/// A generated picture has the canvas's size and aspect. Positions are normalized, `(0, 0)`
114/// top-left to `(1, 1)` bottom-right, and lengths are fractions of the shorter side, so the
115/// picture is the same at any render resolution. A fill never changes over time; text
116/// changes only through its style's animators; shapes, layouts and effects may change.
117#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
118#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
119#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
120pub enum Generator {
121    /// Paint over the whole picture.
122    Fill {
123        /// What covers the picture.
124        paint: Paint,
125    },
126    /// Shapes drawn from an ordered content tree, as an After Effects or Lottie shape layer draws
127    /// them. Every value in the tree may be keyframed in picture time.
128    Shapes {
129        /// The content tree, front first. See [`ShapeItem`].
130        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_SHAPE_ITEMS }>")]
131        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_SHAPE_ITEMS)))]
132        items: Vec<ShapeItem>,
133    },
134    /// Text on a transparent picture, laid out and placed by its style as caption cues are, and
135    /// drawn with the host's registered fonts.
136    Text {
137        /// The text, a string or runs; `\n` starts a line. Non-empty, at most
138        /// [`MAX_TEXT_CONTENT_BYTES`] bytes. Run times are picture time.
139        text: crate::TextContent,
140        /// How it looks and where it lies. The font size is at most
141        /// [`MAX_TEXT_GENERATOR_FONT_SIZE`].
142        #[serde(default)]
143        style: Box<TextStyle>,
144    },
145    /// Boxes laid out by CSS flexbox around their text and shapes, with the engine's fonts. Any
146    /// value in the tree may be keyframed in picture time. See [`LayoutNode`].
147    Layout {
148        /// The root box: the whole picture.
149        root: Box<LayoutNode>,
150    },
151    /// A generator effect drawn over the whole picture: a built-in generator of
152    /// `schema/effects.v1.json` or one the host registers.
153    Effect {
154        /// The versioned generator and its parameters, which may be keyframed in picture time
155        /// and take no data.
156        effect: ClipEffect,
157    },
158}
159
160/// A color or gradient.
161///
162/// Gradients interpolate premultiplied stops in linear light, so a gradient between two colors
163/// passes through their physical mix and a stop fading to transparent does not darken its
164/// neighbour. A bare color is read as a solid paint; paints are written back tagged.
165#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
166#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
167#[cfg_attr(
168    feature = "schema",
169    schemars(rename = "Paint", transform = crate::schema::with_color_form)
170)]
171#[serde(
172    remote = "Self",
173    tag = "type",
174    rename_all = "snake_case",
175    deny_unknown_fields
176)]
177pub enum Paint {
178    /// One color.
179    Solid {
180        /// The color.
181        color: Rgba,
182    },
183    /// Colors along the line from `start` to `end`, constant across it.
184    LinearGradient {
185        /// Where offset 0 lies.
186        start: Vec2,
187        /// Where offset 1 lies. Distinct from `start`.
188        end: Vec2,
189        /// Two to [`MAX_GRADIENT_STOPS`] stops.
190        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
191        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
192        stops: Vec<GradientStop>,
193        /// What lies beyond the first and last offsets.
194        #[serde(default)]
195        spread: Spread,
196    },
197    /// Colors along the radius of a circle.
198    RadialGradient {
199        /// Where offset 0 lies.
200        center: Vec2,
201        /// The distance of offset 1 from the centre, as a fraction of the picture's shorter side.
202        /// Positive.
203        radius: f32,
204        /// Two to [`MAX_GRADIENT_STOPS`] stops.
205        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
206        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
207        stops: Vec<GradientStop>,
208        /// What lies beyond the first and last offsets.
209        #[serde(default)]
210        spread: Spread,
211    },
212    /// Colors around a point: offsets 0 to 1 are one clockwise turn.
213    ConicGradient {
214        /// The point the gradient turns around.
215        center: Vec2,
216        /// Where offset 0 lies, in degrees clockwise from straight up.
217        #[serde(default)]
218        angle_degrees: f32,
219        /// Two to [`MAX_GRADIENT_STOPS`] stops.
220        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
221        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
222        stops: Vec<GradientStop>,
223    },
224}
225
226impl<'de> Deserialize<'de> for Paint {
227    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
228        use serde::de::Error as _;
229        // Only the presence of a tag tells the two forms apart.
230        let value = serde_json::Value::deserialize(deserializer)?;
231        if value.get("type").is_some() {
232            Self::deserialize(value).map_err(D::Error::custom)
233        } else {
234            <Rgba as Deserialize>::deserialize(value)
235                .map(|color| Self::Solid { color })
236                .map_err(D::Error::custom)
237        }
238    }
239}
240
241impl Serialize for Paint {
242    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
243        Self::serialize(self, serializer)
244    }
245}
246
247/// One color of a gradient.
248#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
249#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
250#[serde(deny_unknown_fields)]
251pub struct GradientStop {
252    /// Position along the gradient, in `0..=1`, not before the previous stop.
253    pub offset: f32,
254    /// Color at that position.
255    pub color: Rgba,
256}
257
258/// What a linear or radial gradient shows outside its first and last stops.
259#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
260#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
261#[serde(rename_all = "snake_case")]
262pub enum Spread {
263    /// The end colors continue.
264    #[default]
265    Pad,
266    /// The gradient starts again.
267    Repeat,
268    /// The gradient runs back and forth.
269    Reflect,
270}
271
272impl Generator {
273    /// Whether every field is in range, as a project needs it to be.
274    #[must_use]
275    pub fn is_valid(&self) -> bool {
276        self.validate().is_ok()
277    }
278
279    /// Checks every field. A shapes or layout generator's problem names where in its tree it
280    /// lies, and an effect under [`crate::BUILTIN_EFFECT_PREFIX`] is checked against its built-in
281    /// generator. A layout's pixel font sizes are checked only by [`Self::validate_on`], which
282    /// knows the canvas.
283    ///
284    /// # Errors
285    /// Returns the first problem, if any.
286    pub fn validate(&self) -> Result<(), GeneratorIssue> {
287        self.validate_canvas(None)
288    }
289
290    /// [`Self::validate`] for a generator drawn on a `width` by `height` canvas, which a layout's
291    /// pixel lengths refer to.
292    ///
293    /// # Errors
294    /// Returns the first problem, if any.
295    pub fn validate_on(&self, width: u32, height: u32) -> Result<(), GeneratorIssue> {
296        self.validate_canvas(Some((width, height)))
297    }
298
299    fn validate_canvas(&self, canvas: Option<(u32, u32)>) -> Result<(), GeneratorIssue> {
300        let valid = match self {
301            Self::Fill { paint } => paint.is_valid(),
302            Self::Shapes { items } => {
303                return crate::shapes::validate_shape_items(items).map_err(GeneratorIssue::Shape);
304            }
305            Self::Layout { root } => return crate::layout::validate_layout(root, canvas),
306            Self::Effect { effect } => {
307                if !effect.is_valid() {
308                    return Err(GeneratorIssue::Invalid);
309                }
310                return crate::effect_spec::check_builtin(
311                    effect,
312                    crate::EffectKind::Generator,
313                    None,
314                )
315                .map_err(|problem| GeneratorIssue::Effect {
316                    id: effect.id.clone(),
317                    problem,
318                });
319            }
320            Self::Text { text, style } => {
321                if !(text.is_valid(MAX_TEXT_CONTENT_BYTES)
322                    && style.is_valid(MAX_TEXT_GENERATOR_FONT_SIZE))
323                {
324                    return Err(GeneratorIssue::Invalid);
325                }
326                return match text.invalid_run_style(crate::text_animation::FontSelection::of(style))
327                {
328                    Some(run) => Err(GeneratorIssue::TextRun { run }),
329                    None => Ok(()),
330                };
331            }
332        };
333        valid.then_some(()).ok_or(GeneratorIssue::Invalid)
334    }
335}
336
337impl Paint {
338    pub(crate) fn is_valid(&self) -> bool {
339        match self {
340            Self::Solid { color } => color.is_valid(),
341            Self::LinearGradient {
342                start, end, stops, ..
343            } => finite(*start) && finite(*end) && start != end && valid_stops(stops),
344            Self::RadialGradient {
345                center,
346                radius,
347                stops,
348                ..
349            } => finite(*center) && radius.is_finite() && *radius > 0.0 && valid_stops(stops),
350            Self::ConicGradient {
351                center,
352                angle_degrees,
353                stops,
354            } => finite(*center) && angle_degrees.is_finite() && valid_stops(stops),
355        }
356    }
357}
358
359fn finite(value: Vec2) -> bool {
360    value.x.is_finite() && value.y.is_finite()
361}
362
363fn valid_stops(stops: &[GradientStop]) -> bool {
364    (2..=MAX_GRADIENT_STOPS).contains(&stops.len())
365        && stops
366            .iter()
367            .all(|stop| (0.0..=1.0).contains(&stop.offset) && stop.color.is_valid())
368        && stops
369            .windows(2)
370            .all(|pair| pair[0].offset <= pair[1].offset)
371}