Skip to main content

alpha2_model/
generator.rs

1//! Sources the engine draws itself: fills, gradients, shapes, and text.
2
3use crate::{
4    GeneratorIssue, LayoutNode, MAX_TEXT_CONTENT_BYTES, MAX_TEXT_GENERATOR_FONT_SIZE, ShapeItem,
5    TextStyle, Vec2,
6};
7use serde::{Deserialize, Serialize};
8
9/// Most stops in one gradient.
10pub const MAX_GRADIENT_STOPS: usize = 8;
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 and layouts 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}
152
153/// A color or gradient.
154///
155/// Gradients interpolate premultiplied stops in linear light, so a gradient between two colors
156/// passes through their physical mix and a stop fading to transparent does not darken its
157/// neighbour. A bare color is read as a solid paint; paints are written back tagged.
158#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
159#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
160#[cfg_attr(
161    feature = "schema",
162    schemars(rename = "Paint", transform = crate::schema::with_color_form)
163)]
164#[serde(
165    remote = "Self",
166    tag = "type",
167    rename_all = "snake_case",
168    deny_unknown_fields
169)]
170pub enum Paint {
171    /// One color.
172    Solid {
173        /// The color.
174        color: Rgba,
175    },
176    /// Colors along the line from `start` to `end`, constant across it.
177    LinearGradient {
178        /// Where offset 0 lies.
179        start: Vec2,
180        /// Where offset 1 lies. Distinct from `start`.
181        end: Vec2,
182        /// Two to [`MAX_GRADIENT_STOPS`] stops.
183        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
184        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
185        stops: Vec<GradientStop>,
186        /// What lies beyond the first and last offsets.
187        #[serde(default)]
188        spread: Spread,
189    },
190    /// Colors along the radius of a circle.
191    RadialGradient {
192        /// Where offset 0 lies.
193        center: Vec2,
194        /// The distance of offset 1 from the centre, as a fraction of the picture's shorter side.
195        /// Positive.
196        radius: f32,
197        /// Two to [`MAX_GRADIENT_STOPS`] stops.
198        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
199        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
200        stops: Vec<GradientStop>,
201        /// What lies beyond the first and last offsets.
202        #[serde(default)]
203        spread: Spread,
204    },
205    /// Colors around a point: offsets 0 to 1 are one clockwise turn.
206    ConicGradient {
207        /// The point the gradient turns around.
208        center: Vec2,
209        /// Where offset 0 lies, in degrees clockwise from straight up.
210        #[serde(default)]
211        angle_degrees: f32,
212        /// Two to [`MAX_GRADIENT_STOPS`] stops.
213        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
214        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
215        stops: Vec<GradientStop>,
216    },
217}
218
219impl<'de> Deserialize<'de> for Paint {
220    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
221        use serde::de::Error as _;
222        // Only the presence of a tag tells the two forms apart.
223        let value = serde_json::Value::deserialize(deserializer)?;
224        if value.get("type").is_some() {
225            Self::deserialize(value).map_err(D::Error::custom)
226        } else {
227            <Rgba as Deserialize>::deserialize(value)
228                .map(|color| Self::Solid { color })
229                .map_err(D::Error::custom)
230        }
231    }
232}
233
234impl Serialize for Paint {
235    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
236        Self::serialize(self, serializer)
237    }
238}
239
240/// One color of a gradient.
241#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
242#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
243#[serde(deny_unknown_fields)]
244pub struct GradientStop {
245    /// Position along the gradient, in `0..=1`, not before the previous stop.
246    pub offset: f32,
247    /// Color at that position.
248    pub color: Rgba,
249}
250
251/// What a linear or radial gradient shows outside its first and last stops.
252#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
253#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
254#[serde(rename_all = "snake_case")]
255pub enum Spread {
256    /// The end colors continue.
257    #[default]
258    Pad,
259    /// The gradient starts again.
260    Repeat,
261    /// The gradient runs back and forth.
262    Reflect,
263}
264
265impl Generator {
266    /// Whether every field is in range, as a project needs it to be.
267    #[must_use]
268    pub fn is_valid(&self) -> bool {
269        self.validate().is_ok()
270    }
271
272    /// Checks every field. A shapes or layout generator's problem names where in its tree it
273    /// lies. A layout's pixel font sizes are checked only by [`Self::validate_on`], which knows
274    /// the canvas.
275    ///
276    /// # Errors
277    /// Returns the first problem, if any.
278    pub fn validate(&self) -> Result<(), GeneratorIssue> {
279        self.validate_canvas(None)
280    }
281
282    /// [`Self::validate`] for a generator drawn on a `width` by `height` canvas, which a layout's
283    /// pixel lengths refer to.
284    ///
285    /// # Errors
286    /// Returns the first problem, if any.
287    pub fn validate_on(&self, width: u32, height: u32) -> Result<(), GeneratorIssue> {
288        self.validate_canvas(Some((width, height)))
289    }
290
291    fn validate_canvas(&self, canvas: Option<(u32, u32)>) -> Result<(), GeneratorIssue> {
292        let valid = match self {
293            Self::Fill { paint } => paint.is_valid(),
294            Self::Shapes { items } => {
295                return crate::shapes::validate_shape_items(items).map_err(GeneratorIssue::Shape);
296            }
297            Self::Layout { root } => return crate::layout::validate_layout(root, canvas),
298            Self::Text { text, style } => {
299                text.is_valid(MAX_TEXT_CONTENT_BYTES)
300                    && style.is_valid(MAX_TEXT_GENERATOR_FONT_SIZE)
301            }
302        };
303        valid.then_some(()).ok_or(GeneratorIssue::Invalid)
304    }
305}
306
307impl Paint {
308    pub(crate) fn is_valid(&self) -> bool {
309        match self {
310            Self::Solid { color } => color.is_valid(),
311            Self::LinearGradient {
312                start, end, stops, ..
313            } => finite(*start) && finite(*end) && start != end && valid_stops(stops),
314            Self::RadialGradient {
315                center,
316                radius,
317                stops,
318                ..
319            } => finite(*center) && radius.is_finite() && *radius > 0.0 && valid_stops(stops),
320            Self::ConicGradient {
321                center,
322                angle_degrees,
323                stops,
324            } => finite(*center) && angle_degrees.is_finite() && valid_stops(stops),
325        }
326    }
327}
328
329fn finite(value: Vec2) -> bool {
330    value.x.is_finite() && value.y.is_finite()
331}
332
333fn valid_stops(stops: &[GradientStop]) -> bool {
334    (2..=MAX_GRADIENT_STOPS).contains(&stops.len())
335        && stops
336            .iter()
337            .all(|stop| (0.0..=1.0).contains(&stop.offset) && stop.color.is_valid())
338        && stops
339            .windows(2)
340            .all(|pair| pair[0].offset <= pair[1].offset)
341}