Skip to main content

mln_style/expression/forms/
interpolate.rs

1use crate::color::{Color, ColorSpace};
2use crate::conversion::Convertible;
3use crate::expression::interpolator::{CubicBezierInterpolator, ExponentialInterpolator, Interpolator};
4use crate::expression::parse::{ParseResult, ParsingContext};
5use crate::expression::stops::{Stops, covering_stops};
6use crate::expression::type_::{self, Type};
7use crate::expression::value::{Value, type_of};
8use crate::expression::{EvalResult, EvaluationContext, EvaluationError, EvaluationResult, Expr, Node};
9use crate::feature::Value as FeatureValue;
10use crate::padding::Padding;
11use crate::range::Range;
12use crate::types::{ColorArray, NumberArray, VariableAnchorOffsetCollection};
13
14/// The type of an interpolation's outputs.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, mln_wire::Wire)]
16enum InterpolateOutput {
17    Number,
18    Color,
19    NumberArray,
20    ColorArray,
21    Padding,
22    ProjectionDefinition,
23    VariableAnchorOffsetCollection,
24    Array,
25}
26
27impl InterpolateOutput {
28    fn expression_type(self) -> Type {
29        match self {
30            InterpolateOutput::Number => Type::Number,
31            InterpolateOutput::Color => Type::Color,
32            InterpolateOutput::NumberArray => Type::NumberArray,
33            InterpolateOutput::ColorArray => Type::ColorArray,
34            InterpolateOutput::Padding => Type::Padding,
35            InterpolateOutput::ProjectionDefinition => Type::ProjectionDefinition,
36            InterpolateOutput::VariableAnchorOffsetCollection => Type::VariableAnchorOffsetCollection,
37            InterpolateOutput::Array => Type::array(Type::Value),
38        }
39    }
40
41    fn holds(self, v: &Value) -> bool {
42        matches!(
43            (self, v),
44            (InterpolateOutput::Number, Value::Number(_))
45                | (InterpolateOutput::Color, Value::Color(_))
46                | (InterpolateOutput::NumberArray, Value::NumberArray(_))
47                | (InterpolateOutput::ColorArray, Value::ColorArray(_))
48                | (InterpolateOutput::Padding, Value::Padding(_))
49                | (InterpolateOutput::ProjectionDefinition, Value::ProjectionDefinition(_))
50                | (InterpolateOutput::VariableAnchorOffsetCollection, Value::VariableAnchorOffsetCollection(_))
51                | (InterpolateOutput::Array, Value::Array(_))
52        )
53    }
54}
55
56fn interpolate_float(a: f32, b: f32, t: f64) -> f32 {
57    (f64::from(a) * (1.0 - t) + f64::from(b) * t) as f32
58}
59
60/// Linear interpolation from `a` to `b`.
61fn interpolate_double(a: f64, b: f64, t: f64) -> f64 {
62    a * (1.0 - t) + b * t
63}
64
65/// `["interpolate", interpolation, input, label, output, ...]` and its color
66/// space variants.
67#[derive(Clone, PartialEq, mln_wire::Wire)]
68pub struct Interpolate {
69    ty: Type,
70    interpolator: Interpolator,
71    color_space: ColorSpace,
72    input: Expr,
73    stops: Stops,
74    output: InterpolateOutput,
75}
76
77/// The stops an input falls between.
78enum Located<'a> {
79    At(&'a Expr),
80    Between(&'a Expr, &'a Expr, f64),
81}
82
83impl Interpolate {
84    pub(crate) fn ty(&self) -> &Type {
85        &self.ty
86    }
87
88    #[must_use]
89    pub(crate) fn input(&self) -> &Expr {
90        &self.input
91    }
92
93    #[must_use]
94    pub fn stop_count(&self) -> usize {
95        self.stops.len()
96    }
97
98    pub fn each_stop(&self, mut visit: impl FnMut(f64, &Expr)) {
99        for (k, v) in self.stops.iter() {
100            visit(k, v);
101        }
102    }
103
104    /// The inputs of the stops, in order.
105    pub(crate) fn stop_inputs(&self) -> impl Iterator<Item = f64> + '_ {
106        self.stops.iter().map(|(input, _)| input)
107    }
108
109    /// Return the smallest range of stops that covers the interval
110    /// [lower, upper].
111    #[must_use]
112    pub fn covering_stops(&self, lower: f64, upper: f64) -> Range<f64> {
113        covering_stops(&self.stops, lower, upper)
114    }
115
116    #[must_use]
117    pub fn interpolation_factor(&self, input_levels: Range<f64>, input_value: f64) -> f64 {
118        self.interpolator.interpolation_factor(input_levels, input_value)
119    }
120
121    pub(crate) fn operator(&self) -> &'static str {
122        match self.color_space {
123            ColorSpace::Lab => "interpolate-lab",
124            ColorSpace::Hcl => "interpolate-hcl",
125            ColorSpace::Oklch => "interpolate-oklch",
126            ColorSpace::Oklab => "interpolate-oklab",
127            ColorSpace::Rgb => "interpolate",
128        }
129    }
130
131    pub(crate) fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
132        visit(&self.input);
133        self.stops.values().for_each(visit);
134    }
135
136    /// The stop outputs the input selects, and how far it is between them.
137    fn locate(&self, params: &EvaluationContext<'_>) -> EvalResult<Located<'_>> {
138        let x = self.input.eval_num(params)?;
139        if x.is_nan() {
140            return Err(EvaluationError::new("Input is not a number."));
141        }
142
143        if self.stops.is_empty() {
144            return Err(EvaluationError::new("No stops in exponential curve."));
145        }
146
147        let it = self.stops.upper_bound(x);
148        if it == self.stops.len() {
149            return Ok(Located::At(self.stops.output(self.stops.len() - 1)));
150        }
151        if it == 0 {
152            return Ok(Located::At(self.stops.output(0)));
153        }
154        let t = self.interpolation_factor(Range::new(self.stops.key(it - 1), self.stops.key(it)), x);
155        let (lower, upper) = (self.stops.output(it - 1), self.stops.output(it));
156        Ok(if t == 0.0 {
157            Located::At(lower)
158        } else if t == 1.0 {
159            Located::At(upper)
160        } else {
161            Located::Between(lower, upper, t)
162        })
163    }
164
165    pub(crate) fn eval_num(&self, params: &EvaluationContext<'_>) -> EvalResult<f64> {
166        match self.locate(params)? {
167            Located::At(output) => output.eval_num(params),
168            Located::Between(lower, upper, t) => {
169                Ok(interpolate_double(lower.eval_num(params)?, upper.eval_num(params)?, t))
170            }
171        }
172    }
173
174    pub(crate) fn eval_color(&self, params: &EvaluationContext<'_>) -> EvalResult<Color> {
175        match self.locate(params)? {
176            Located::At(output) => output.eval_color(params),
177            Located::Between(lower, upper, t) => {
178                let (lower, upper) = (lower.eval_color(params)?, upper.eval_color(params)?);
179                Ok(Color::interpolate(&lower, &upper, t, self.color_space))
180            }
181        }
182    }
183
184    pub(crate) fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
185        let (lower_expr, upper_expr, t) = match self.locate(params)? {
186            Located::At(output) => return output.evaluate(params),
187            Located::Between(lower, upper, t) => (lower, upper, t),
188        };
189        let lower = lower_expr.evaluate(params)?;
190        let upper = upper_expr.evaluate(params)?;
191
192        if !self.output.holds(&lower) {
193            return Err(EvaluationError::new(format!(
194                "Expected value to be of type {}, but found {} instead.",
195                type_::to_string(&self.output.expression_type()),
196                type_::to_string(&type_of(&lower))
197            )));
198        }
199
200        if !self.output.holds(&upper) {
201            return Err(EvaluationError::new(format!(
202                "Expected value to be of type {}, but found {} instead.",
203                type_::to_string(&self.output.expression_type()),
204                type_::to_string(&type_of(&upper))
205            )));
206        }
207        self.interpolate_outputs(&lower, &upper, t)
208    }
209
210    fn interpolate_outputs(&self, lower: &Value, upper: &Value, t: f64) -> EvaluationResult {
211        Ok(match (lower, upper) {
212            (Value::Number(a), Value::Number(b)) => Value::Number(interpolate_double(*a, *b, t)),
213            (Value::Color(a), Value::Color(b)) => Value::Color(Color::interpolate(a, b, t, self.color_space)),
214            (Value::NumberArray(a), Value::NumberArray(b)) => match NumberArray::interpolate_checked(a, b, t) {
215                Ok(v) => Value::NumberArray(v),
216                Err(e) => return Err(EvaluationError::new(e)),
217            },
218            (Value::ColorArray(a), Value::ColorArray(b)) => {
219                match ColorArray::interpolate_in_space(a, b, t, self.color_space) {
220                    Ok(v) => Value::ColorArray(v),
221                    Err(e) => return Err(EvaluationError::new(e)),
222                }
223            }
224            (Value::Padding(a), Value::Padding(b)) => Value::Padding(Padding::new(
225                interpolate_float(a.top, b.top, t),
226                interpolate_float(a.right, b.right, t),
227                interpolate_float(a.bottom, b.bottom, t),
228                interpolate_float(a.left, b.left, t),
229            )),
230            (Value::ProjectionDefinition(a), Value::ProjectionDefinition(b)) => {
231                Value::ProjectionDefinition(crate::interpolate::interpolate(a, b, t))
232            }
233            (Value::VariableAnchorOffsetCollection(a), Value::VariableAnchorOffsetCollection(b)) => {
234                // The offsets are f32. Collections whose anchors differ fail
235                // to evaluate.
236                match VariableAnchorOffsetCollection::interpolate(a, b, t) {
237                    Ok(v) => Value::VariableAnchorOffsetCollection(v),
238                    Err(e) => return Err(EvaluationError::new(e)),
239                }
240            }
241            (Value::Array(a), Value::Array(b)) => {
242                debug_assert_eq!(a.len(), b.len());
243                if a.is_empty() {
244                    return Ok(Value::Array(Vec::new()));
245                }
246                let mut result = Vec::with_capacity(a.len());
247                for (ai, bi) in a.iter().zip(b) {
248                    let (Value::Number(ai), Value::Number(bi)) = (ai, bi) else {
249                        let item = if matches!(ai, Value::Number(_)) { bi } else { ai };
250                        return Err(EvaluationError::type_mismatch(&Type::Number, item));
251                    };
252                    result.push(Value::Number(interpolate_double(*ai, *bi, t)));
253                }
254                Value::Array(result)
255            }
256            _ => return Err(EvaluationError::type_mismatch(&type_of(lower), upper)),
257        })
258    }
259
260    pub(crate) fn serialize(&self) -> FeatureValue {
261        let mut serialized = vec![FeatureValue::String(self.operator().to_owned())];
262
263        match &self.interpolator {
264            Interpolator::Exponential(exponential) => {
265                if exponential.base == 1.0 {
266                    serialized.push(FeatureValue::Array(vec![FeatureValue::String("linear".to_owned())]));
267                } else {
268                    serialized.push(FeatureValue::Array(vec![
269                        FeatureValue::String("exponential".to_owned()),
270                        FeatureValue::Double(exponential.base),
271                    ]));
272                }
273            }
274            Interpolator::CubicBezier(cubic_bezier) => {
275                let [x1, y1, x2, y2] = cubic_bezier.control_points();
276                serialized.push(FeatureValue::Array(vec![
277                    FeatureValue::String("cubic-bezier".to_owned()),
278                    FeatureValue::Double(x1),
279                    FeatureValue::Double(y1),
280                    FeatureValue::Double(x2),
281                    FeatureValue::Double(y2),
282                ]));
283            }
284        }
285        serialized.push(self.input.serialize());
286        for (k, v) in self.stops.iter() {
287            serialized.push(FeatureValue::Double(k));
288            serialized.push(v.serialize());
289        }
290        FeatureValue::Array(serialized)
291    }
292}
293
294/// The label of an interpolate/step stop: a number.
295pub(crate) fn parse_stop_label(value: &Convertible<'_>) -> Option<f64> {
296    value.to_double()
297}
298
299pub(crate) fn parse_interpolate(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
300    debug_assert!(value.is_array());
301
302    let length = value.array_length();
303
304    if length < 2 {
305        ctx.error("Expected an interpolation type expression.".to_owned());
306        return None;
307    }
308
309    let interp = value.array_member(1);
310    if !interp.is_array() || interp.array_length() == 0 {
311        ctx.error("Expected an interpolation type expression.".to_owned());
312        return None;
313    }
314
315    let op = value.array_member(0).to_string();
316    let color_space = match op.as_deref() {
317        Some("interpolate-lab") => ColorSpace::Lab,
318        Some("interpolate-hcl") => ColorSpace::Hcl,
319        Some("interpolate-oklch") => ColorSpace::Oklch,
320        Some("interpolate-oklab") => ColorSpace::Oklab,
321        _ => ColorSpace::Rgb,
322    };
323
324    let mut interpolator: Option<Interpolator> = None;
325
326    let interp_name = interp.array_member(0).to_string();
327    if interp_name.as_deref() == Some("linear") {
328        interpolator = Some(ExponentialInterpolator::new(1.0).into());
329    } else if interp_name.as_deref() == Some("exponential") {
330        let mut base = None;
331        if interp.array_length() >= 2 {
332            base = interp.array_member(1).to_double();
333        }
334        let Some(base) = base else {
335            ctx.error_at2("Exponential interpolation requires a numeric base.".to_owned(), 1, 1);
336            return None;
337        };
338        interpolator = Some(ExponentialInterpolator::new(base).into());
339    } else if interp_name.as_deref() == Some("cubic-bezier") {
340        let (mut x1, mut y1, mut x2, mut y2) = (None, None, None, None);
341        if interp.array_length() == 5 {
342            x1 = interp.array_member(1).to_double();
343            y1 = interp.array_member(2).to_double();
344            x2 = interp.array_member(3).to_double();
345            y2 = interp.array_member(4).to_double();
346        }
347        let in_unit = |v: Option<f64>| v.filter(|&v| !(v < 0.0 || v > 1.0));
348        let (Some(x1), Some(y1), Some(x2), Some(y2)) = (in_unit(x1), in_unit(y1), in_unit(x2), in_unit(y2)) else {
349            ctx.error_at(
350                "Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.".to_owned(),
351                1,
352            );
353            return None;
354        };
355        interpolator = Some(CubicBezierInterpolator::new(x1, y1, x2, y2).into());
356    }
357
358    let Some(interpolator) = interpolator else {
359        ctx.error_at2(format!("Unknown interpolation type {}", interp_name.as_deref().unwrap_or("")), 1, 0);
360        return None;
361    };
362
363    let min_args = 4;
364    if length - 1 < min_args {
365        ctx.error(format!("Expected at least 4 arguments, but found only {}.", length - 1));
366        return None;
367    }
368
369    // [interpolation, interp_type, input, 2 * (n pairs)...]
370    if !(length - 1).is_multiple_of(2) {
371        ctx.error("Expected an even number of arguments.".to_owned());
372        return None;
373    }
374
375    let input = ctx.parse(&value.array_member(2), 2, Some(Type::Number), None)?;
376
377    let mut stops = Stops::new();
378    let mut output_type: Option<Type> = None;
379    if color_space != ColorSpace::Rgb {
380        output_type = Some(if ctx.expected() == Some(Type::ColorArray) { Type::ColorArray } else { Type::Color });
381    } else if let Some(expected) = ctx.expected()
382        && expected != Type::Value
383    {
384        output_type = Some(expected);
385    }
386
387    let mut previous = f64::NEG_INFINITY;
388
389    let mut i = 3;
390    while i + 1 < length {
391        let Some(label) = parse_stop_label(&value.array_member(i)) else {
392            ctx.error_at(
393                r#"Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values."#
394                    .to_owned(),
395                i,
396            );
397            return None;
398        };
399
400        if label <= previous {
401            ctx.error_at(
402                r#"Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order."#
403                    .to_owned(),
404                i,
405            );
406            return None;
407        }
408        previous = label;
409
410        let output = ctx.parse(&value.array_member(i + 1), i + 1, output_type.clone(), None)?;
411        if output_type.is_none() {
412            output_type = Some(output.ty());
413        }
414
415        stops.emplace(label, output);
416        i += 2;
417    }
418
419    let Some(output_type) = output_type else {
420        ctx.error(format!("Expected at least 4 arguments, but found only {}.", length - 1));
421        return None;
422    };
423
424    create_interpolate(output_type, interpolator, color_space, input, stops, ctx)
425}
426
427pub(crate) fn create_interpolate(
428    ty: Type,
429    interpolator: Interpolator,
430    color_space: ColorSpace,
431    input: Expr,
432    stops: Stops,
433    ctx: &mut ParsingContext,
434) -> ParseResult {
435    debug_assert!(color_space == ColorSpace::Rgb || matches!(ty, Type::Color | Type::ColorArray));
436    let output = match &ty {
437        Type::Number => InterpolateOutput::Number,
438        Type::Color => InterpolateOutput::Color,
439        Type::NumberArray => InterpolateOutput::NumberArray,
440        Type::ColorArray => InterpolateOutput::ColorArray,
441        Type::Padding => InterpolateOutput::Padding,
442        Type::ProjectionDefinition => InterpolateOutput::ProjectionDefinition,
443        Type::VariableAnchorOffsetCollection => InterpolateOutput::VariableAnchorOffsetCollection,
444        Type::Array(array_type) => {
445            if array_type.item_type != Type::Number || array_type.n.is_none() {
446                ctx.error(format!("Type {} is not interpolatable.", type_::to_string(&ty)));
447                return None;
448            }
449            InterpolateOutput::Array
450        }
451        _ => {
452            ctx.error(format!("Type {} is not interpolatable.", type_::to_string(&ty)));
453            return None;
454        }
455    };
456    assert_eq!(input.ty(), Type::Number);
457    Some(Expr::new(Node::Interpolate(Box::new(Interpolate { ty, interpolator, color_space, input, stops, output }))))
458}