Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/color.rs

45.3 KiB, 29 runs

created by r1870400018:63222, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// U3 owns this file. Colour constructors and methods, gradients, colour maps and the named colours (`red`,
2// `luma`...). `Color::to_rgba` is the one conversion flow and the emitters use.
3//
4// Arithmetic is in `f32`, as Typst's (palette's) is, so a component read back with `components()`
5// carries the same rounding. sRGB, linear sRGB, luma, Oklab/Oklch, HSL and HSV convert by formula
6// (Oklab by Ottosson's matrices, luminance by the sRGB primaries). CMYK to RGB is an ICC transform in
7// Typst; `fe2o3_graphics::colour::cmyk_to_srgb` reproduces it from a 17-point-per-axis grid sampled from
8// the `typst` 0.15.1 oracle with quadrilinear interpolation, within two eight-bit steps of Typst
9// everywhere the oracle was probed. RGB to CMYK is Typst's naive formula; luma to CMYK its fixed ink
10// ratios.
11
12use crate::diag::DiagnosticKind;
13use crate::eval::args::Args;
14use crate::eval::func::{
15 Func,
16 NativeFunc,
17};
18use crate::eval::lib::foundations::{
19 finish,
20 format_float,
21 mismatch,
22 need,
23 no_method,
24 receiver,
25 repr_angle,
26 repr_ratio,
27 repr_str,
28};
29use crate::eval::scope::Scope;
30use crate::eval::value::{
31 Angle,
32 Color,
33 ColorSpace,
34 Direction,
35 Gradient,
36 GradientKind,
37 Module,
38 Ratio,
39 RelativeTo,
40 Type,
41 Value,
42};
43use crate::eval::Engine;
44use crate::syntax::Span;
45
46use oxedyne_fe2o3_core::prelude::*;
47use oxedyne_fe2o3_graphics::colour::{
48 cmyk_to_srgb,
49 unit_to_u8,
50 Ink,
51 Rgba,
52};
53
54use std::sync::Arc;
55
56native_fns! {
57 pub enum ColorFn {
58 Rgb => "rgb",
59 Luma => "luma",
60 Cmyk => "cmyk",
61 Oklab => "oklab",
62 Oklch => "oklch",
63 LinearRgb => "linear-rgb",
64 Hsl => "hsl",
65 Hsv => "hsv",
66 Mix => "mix",
67 Lighten => "lighten",
68 Darken => "darken",
69 Saturate => "saturate",
70 Desaturate => "desaturate",
71 Negate => "negate",
72 Rotate => "rotate",
73 Components => "components",
74 Space => "space",
75 ToHex => "to-hex",
76 Transparentize => "transparentize",
77 Opacify => "opacify",
78 GradientLinear => "linear",
79 GradientRadial => "radial",
80 GradientConic => "conic",
81 GradientSample => "sample",
82 GradientSamples => "samples",
83 GradientStops => "stops",
84 GradientSharp => "sharp",
85 GradientRepeat => "repeat",
86 GradientKindOf => "kind",
87 GradientSpace => "space",
88 GradientRelative => "relative",
89 GradientAngle => "angle",
90 GradientCenter => "center",
91 GradientRadius => "radius",
92 GradientFocalCenter => "focal-center",
93 GradientFocalRadius => "focal-radius",
94 }
95}
96
97mod data {
98 include!("color_data.rs");
99}
100
101// Typst's own literals, not eight-bit values over 255: `red`'s green is 0.254902, not 65/255, and a mix
102// or conversion rounds on that difference.
103const NAMED: [(&str, ColorSpace, [f32; 3]); 18] = [
104 ("black", ColorSpace::Luma, [0.0, 0.0, 0.0]),
105 ("gray", ColorSpace::Luma, [0.6666666, 0.0, 0.0]),
106 ("silver", ColorSpace::Luma, [0.8666667, 0.0, 0.0]),
107 ("white", ColorSpace::Luma, [1.0, 0.0, 0.0]),
108 ("navy", ColorSpace::Rgb, [0.0, 0.121569, 0.247059]),
109 ("blue", ColorSpace::Rgb, [0.0, 0.454902, 0.85098]),
110 ("aqua", ColorSpace::Rgb, [0.4980392, 0.858823, 1.0]),
111 ("teal", ColorSpace::Rgb, [0.223529, 0.8, 0.8]),
112 ("eastern", ColorSpace::Rgb, [0.13725, 0.615686, 0.678431]),
113 ("purple", ColorSpace::Rgb, [0.694118, 0.050980, 0.788235]),
114 ("fuchsia", ColorSpace::Rgb, [0.941177, 0.070588, 0.745098]),
115 ("maroon", ColorSpace::Rgb, [0.521569, 0.078431, 0.294118]),
116 ("red", ColorSpace::Rgb, [1.0, 0.254902, 0.211765]),
117 ("orange", ColorSpace::Rgb, [1.0, 0.521569, 0.105882]),
118 ("yellow", ColorSpace::Rgb, [1.0, 0.8627451, 0.0]),
119 ("olive", ColorSpace::Rgb, [0.239216, 0.6, 0.4392157]),
120 ("green", ColorSpace::Rgb, [0.1803922, 0.8, 0.2509804]),
121 ("lime", ColorSpace::Rgb, [0.0039216, 1.0, 0.4392157]),
122];
123
124fn func(f: ColorFn) -> Value { Value::Func(Func::Native(NativeFunc::Color(f))) }
125
126pub fn define(scope: &mut Scope) {
127 for f in [ColorFn::Rgb, ColorFn::Luma, ColorFn::Cmyk, ColorFn::Oklab, ColorFn::Oklch] {
128 scope.define(f.name(), func(f));
129 }
130 for (name, space, c) in NAMED {
131 let col = Color { space, c: [c[0], c[1], c[2], 0.0], alpha: 1.0 };
132 scope.define(name, Value::Color(col));
133 }
134}
135
136/// `color.name`: the constructors Typst scopes under the type, `mix`, and the colour maps.
137pub fn color_static(name: &str) -> Option<Value> {
138 let f = match name {
139 "linear-rgb" => ColorFn::LinearRgb,
140 "hsl" => ColorFn::Hsl,
141 "hsv" => ColorFn::Hsv,
142 "mix" => ColorFn::Mix,
143 "rgb" => ColorFn::Rgb,
144 "luma" => ColorFn::Luma,
145 "cmyk" => ColorFn::Cmyk,
146 "oklab" => ColorFn::Oklab,
147 "oklch" => ColorFn::Oklch,
148 "map" => return Some(Value::Module(Arc::new(color_maps()))),
149 _ => return None,
150 };
151 Some(func(f))
152}
153
154fn color_maps() -> Module {
155 let mut s = Scope::new();
156 for (n, (name, cols)) in data::COLOR_MAPS.iter().enumerate() {
157 let arr = cols.iter().map(|c| Value::Color(rgb8(c[0], c[1], c[2], 255))).collect();
158 crate::eval::lib::foundations::define_nth(&mut s, n, name, Value::array(arr));
159 }
160 Module::new("map", s)
161}
162
163pub fn gradient_static(name: &str) -> Option<Value> {
164 let f = match name {
165 "linear" => ColorFn::GradientLinear,
166 "radial" => ColorFn::GradientRadial,
167 "conic" => ColorFn::GradientConic,
168 _ => return None,
169 };
170 Some(func(f))
171}
172
173pub fn method(name: &str) -> Option<ColorFn> {
174 let f = match name {
175 "lighten" => ColorFn::Lighten,
176 "darken" => ColorFn::Darken,
177 "saturate" => ColorFn::Saturate,
178 "desaturate" => ColorFn::Desaturate,
179 "negate" => ColorFn::Negate,
180 "rotate" => ColorFn::Rotate,
181 "components" => ColorFn::Components,
182 "space" => ColorFn::Space,
183 "to-hex" => ColorFn::ToHex,
184 "transparentize" => ColorFn::Transparentize,
185 "opacify" => ColorFn::Opacify,
186 other => return gradient_method(other),
187 };
188 Some(f)
189}
190
191pub fn gradient_method(name: &str) -> Option<ColorFn> {
192 let f = match name {
193 "sample" => ColorFn::GradientSample,
194 "samples" => ColorFn::GradientSamples,
195 "stops" => ColorFn::GradientStops,
196 "sharp" => ColorFn::GradientSharp,
197 "repeat" => ColorFn::GradientRepeat,
198 "kind" => ColorFn::GradientKindOf,
199 "space" => ColorFn::GradientSpace,
200 "relative" => ColorFn::GradientRelative,
201 "angle" => ColorFn::GradientAngle,
202 "center" => ColorFn::GradientCenter,
203 "radius" => ColorFn::GradientRadius,
204 "focal-center" => ColorFn::GradientFocalCenter,
205 "focal-radius" => ColorFn::GradientFocalRadius,
206 _ => return None,
207 };
208 Some(f)
209}
210
211// Colour arithmetic.
212
213fn rgb8(r: u8, g: u8, b: u8, a: u8) -> Color {
214 Color { space: ColorSpace::Rgb, c: [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 0.0], alpha: a as f32 / 255.0 }
215}
216
217fn decode(x: f32) -> f32 { if x <= 0.04045 { x / 12.92 } else { ((x + 0.055) / 1.055).powf(2.4) } }
218
219fn encode(x: f32) -> f32 { if x <= 0.0031308 { x * 12.92 } else { 1.055 * x.powf(1.0 / 2.4) - 0.055 } }
220
221fn norm_hue(h: f32) -> f32 {
222 let r = h % 360.0;
223 if r < 0.0 { r + 360.0 } else { r }
224}
225
226fn lin_to_oklab(r: f32, g: f32, b: f32) -> [f32; 3] {
227 let l = 0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b;
228 let m = 0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b;
229 let s = 0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b;
230 let (l, m, s) = (l.cbrt(), m.cbrt(), s.cbrt());
231 [
232 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s,
233 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s,
234 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s,
235 ]
236}
237
238fn oklab_to_lin(l: f32, a: f32, b: f32) -> [f32; 3] {
239 let l_ = l + 0.396_337_78 * a + 0.215_803_76 * b;
240 let m_ = l - 0.105_561_346 * a - 0.063_854_17 * b;
241 let s_ = l - 0.089_484_18 * a - 1.291_485_5 * b;
242 let (l, m, s) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
243 [
244 4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s,
245 -1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s,
246 -0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s,
247 ]
248}
249
250fn rgb_to_hsx(r: f32, g: f32, b: f32, hsv: bool) -> [f32; 3] {
251 let max = r.max(g).max(b);
252 let min = r.min(g).min(b);
253 let chroma = max - min;
254 let hue = if chroma == 0.0 {
255 0.0
256 } else if max == r {
257 60.0 * ((g - b) / chroma)
258 } else if max == g {
259 60.0 * ((b - r) / chroma + 2.0)
260 } else {
261 60.0 * ((r - g) / chroma + 4.0)
262 };
263 if hsv {
264 let s = if max == 0.0 { 0.0 } else { chroma / max };
265 [norm_hue(hue), s, max]
266 } else {
267 let l = (max + min) / 2.0;
268 let s = if chroma == 0.0 { 0.0 } else { chroma / (1.0 - (2.0 * l - 1.0).abs()) };
269 [norm_hue(hue), s, l]
270 }
271}
272
273fn hsx_to_rgb(h: f32, s: f32, x: f32, hsv: bool) -> [f32; 3] {
274 let (c, m) = if hsv {
275 let c = x * s;
276 (c, x - c)
277 } else {
278 let c = (1.0 - (2.0 * x - 1.0).abs()) * s;
279 (c, x - c / 2.0)
280 };
281 let hp = norm_hue(h) / 60.0;
282 let xx = c * (1.0 - (hp % 2.0 - 1.0).abs());
283 let (r, g, b) = match hp as u32 {
284 0 => (c, xx, 0.0),
285 1 => (xx, c, 0.0),
286 2 => (0.0, c, xx),
287 3 => (0.0, xx, c),
288 4 => (xx, 0.0, c),
289 _ => (c, 0.0, xx),
290 };
291 [r + m, g + m, b + m]
292}
293
294fn rgb_to_cmyk(r: f32, g: f32, b: f32) -> [f32; 4] {
295 let k = 1.0 - r.max(g).max(b);
296 if k == 1.0 {
297 return [0.0, 0.0, 0.0, 1.0];
298 }
299 [(1.0 - r - k) / (1.0 - k), (1.0 - g - k) / (1.0 - k), (1.0 - b - k) / (1.0 - k), k]
300}
301
302/// The colour as gamma-encoded sRGB components.
303fn to_srgb(c: &Color) -> [f32; 3] {
304 let [a, b, d, e] = c.c;
305 match c.space {
306 ColorSpace::Rgb => [a, b, d],
307 ColorSpace::Luma => [a, a, a],
308 ColorSpace::Hsl => hsx_to_rgb(a, b, d, false),
309 ColorSpace::Hsv => hsx_to_rgb(a, b, d, true),
310 ColorSpace::Cmyk => cmyk_to_srgb([a, b, d, e]),
311 ColorSpace::LinearRgb => [encode(a), encode(b), encode(d)],
312 ColorSpace::Oklab | ColorSpace::Oklch => {
313 let [r, g, bl] = to_linear(c);
314 [encode(r), encode(g), encode(bl)]
315 }
316 }
317}
318
319fn to_linear(c: &Color) -> [f32; 3] {
320 let [a, b, d, _] = c.c;
321 match c.space {
322 ColorSpace::LinearRgb => [a, b, d],
323 ColorSpace::Oklab => oklab_to_lin(a, b, d),
324 ColorSpace::Oklch => {
325 let h = d.to_radians();
326 oklab_to_lin(a, b * h.cos(), b * h.sin())
327 }
328 ColorSpace::Luma => {
329 let l = decode(a);
330 [l, l, l]
331 }
332 _ => {
333 let [r, g, bl] = to_srgb(c);
334 [decode(r), decode(g), decode(bl)]
335 }
336 }
337}
338
339fn to_oklab(c: &Color) -> [f32; 3] {
340 match c.space {
341 ColorSpace::Oklab => [c.c[0], c.c[1], c.c[2]],
342 ColorSpace::Oklch => {
343 let h = c.c[2].to_radians();
344 [c.c[0], c.c[1] * h.cos(), c.c[1] * h.sin()]
345 }
346 // A grey is neutral in Oklab: its lightness alone.
347 ColorSpace::Luma => [decode(c.c[0]).cbrt(), 0.0, 0.0],
348 _ => {
349 let [r, g, b] = to_linear(c);
350 lin_to_oklab(r, g, b)
351 }
352 }
353}
354
355/// The colour in another space, alpha carried over (CMYK has none).
356pub fn to_space(c: &Color, space: ColorSpace) -> Color {
357 if c.space == space {
358 return *c;
359 }
360 let alpha = if c.space == ColorSpace::Cmyk { 1.0 } else { c.alpha };
361 let v: [f32; 4] = match space {
362 ColorSpace::Rgb => {
363 let [r, g, b] = to_srgb(c);
364 [r, g, b, 0.0]
365 }
366 ColorSpace::LinearRgb => {
367 let [r, g, b] = to_linear(c);
368 [r, g, b, 0.0]
369 }
370 ColorSpace::Luma => {
371 let [r, g, b] = to_linear(c);
372 let y = 0.212_672_9 * r + 0.715_152_2 * g + 0.072_175 * b;
373 [encode(y), 0.0, 0.0, 0.0]
374 }
375 ColorSpace::Oklab => {
376 let [l, a, b] = to_oklab(c);
377 [l, a, b, 0.0]
378 }
379 ColorSpace::Oklch => {
380 let [l, a, b] = to_oklab(c);
381 [l, (a * a + b * b).sqrt(), norm_hue(b.atan2(a).to_degrees()), 0.0]
382 }
383 ColorSpace::Hsl | ColorSpace::Hsv => {
384 let [r, g, b] = to_srgb(c);
385 let [h, s, x] = rgb_to_hsx(r, g, b, space == ColorSpace::Hsv);
386 [h, s, x, 0.0]
387 }
388 ColorSpace::Cmyk => {
389 if c.space == ColorSpace::Luma {
390 let l = 1.0 - c.c[0];
391 [l * 0.75, l * 0.68, l * 0.67, l * 0.90]
392 } else {
393 let [r, g, b] = to_srgb(c);
394 rgb_to_cmyk(r, g, b)
395 }
396 }
397 };
398 Color { space, c: v, alpha: if space == ColorSpace::Cmyk { 1.0 } else { alpha } }
399}
400
401// Eight-bit quantisation rounds half to even, as Typst's does: 30% is 0x4c, 10% is 0x1a.
402fn to_u8(x: f32) -> u8 { unit_to_u8(x) }
403
404impl Color {
405 /// The colour with the space it was written in, for the back end: `luma` stays grey, `cmyk` stays
406 /// CMYK, every other space is eight-bit sRGB.
407 pub fn to_ink(&self) -> Ink {
408 let [a, b, d, e] = self.c;
409 match self.space {
410 ColorSpace::Luma => Ink::Grey { v: a, a: to_u8(self.alpha) },
411 ColorSpace::Cmyk => Ink::Cmyk { c: a, m: b, y: d, k: e, a: 255 },
412 _ => {
413 let [r, g, bl] = to_srgb(self);
414 Ink::Rgb(Rgba::new(to_u8(r), to_u8(g), to_u8(bl), to_u8(self.alpha)))
415 },
416 }
417 }
418
419 /// The colour as eight-bit sRGB with alpha, for the screen.
420 pub fn to_rgba(&self) -> Outcome<Rgba> {
421 Ok(self.to_ink().to_rgba())
422 }
423}
424
425pub fn to_hex(c: &Color) -> String {
426 let [r, g, b] = to_srgb(c);
427 let a = if c.space == ColorSpace::Cmyk { 1.0 } else { c.alpha };
428 let a8 = to_u8(a);
429 if a8 == 255 {
430 fmt!("#{:02x}{:02x}{:02x}", to_u8(r), to_u8(g), to_u8(b))
431 } else {
432 fmt!("#{:02x}{:02x}{:02x}{:02x}", to_u8(r), to_u8(g), to_u8(b), a8)
433 }
434}
435
436fn ratio(x: f32) -> String { repr_ratio(Ratio(x as f64)) }
437
438fn component(x: f32) -> String { format_float(x as f64, Some(3), false, "") }
439
440fn hue(x: f32) -> String { repr_angle(Angle((norm_hue(x) as f64).to_radians())) }
441
442pub fn repr_color(c: &Color) -> String {
443 let [a, b, d, e] = c.c;
444 let alpha = c.alpha != 1.0;
445 match c.space {
446 ColorSpace::Rgb => fmt!("rgb({})", repr_str(&to_hex(c))),
447 ColorSpace::Luma => if alpha {
448 fmt!("luma({}, {})", ratio(a), ratio(c.alpha))
449 } else {
450 fmt!("luma({})", ratio(a))
451 },
452 ColorSpace::LinearRgb => if alpha {
453 fmt!("color.linear-rgb({}, {}, {}, {})", ratio(a), ratio(b), ratio(d), ratio(c.alpha))
454 } else {
455 fmt!("color.linear-rgb({}, {}, {})", ratio(a), ratio(b), ratio(d))
456 },
457 ColorSpace::Cmyk => fmt!("cmyk({}, {}, {}, {})", ratio(a), ratio(b), ratio(d), ratio(e)),
458 ColorSpace::Oklab => if alpha {
459 fmt!("oklab({}, {}, {}, {})", ratio(a), component(b), component(d), ratio(c.alpha))
460 } else {
461 fmt!("oklab({}, {}, {})", ratio(a), component(b), component(d))
462 },
463 ColorSpace::Oklch => if alpha {
464 fmt!("oklch({}, {}, {}, {})", ratio(a), component(b), hue(d), ratio(c.alpha))
465 } else {
466 fmt!("oklch({}, {}, {})", ratio(a), component(b), hue(d))
467 },
468 ColorSpace::Hsl | ColorSpace::Hsv => {
469 let name = if c.space == ColorSpace::Hsl { "hsl" } else { "hsv" };
470 if alpha {
471 fmt!("color.{}({}, {}, {}, {})", name, hue(a), ratio(b), ratio(d), ratio(c.alpha))
472 } else {
473 fmt!("color.{}({}, {}, {})", name, hue(a), ratio(b), ratio(d))
474 }
475 }
476 }
477}
478
479fn space_fn(s: ColorSpace) -> ColorFn {
480 match s {
481 ColorSpace::Rgb => ColorFn::Rgb,
482 ColorSpace::Luma => ColorFn::Luma,
483 ColorSpace::Cmyk => ColorFn::Cmyk,
484 ColorSpace::Oklab => ColorFn::Oklab,
485 ColorSpace::Oklch => ColorFn::Oklch,
486 ColorSpace::LinearRgb => ColorFn::LinearRgb,
487 ColorSpace::Hsl => ColorFn::Hsl,
488 ColorSpace::Hsv => ColorFn::Hsv,
489 }
490}
491
492/// A colour space named by its constructor (`space: rgb`).
493fn space_of(engine: &mut Engine, span: Span, v: &Value) -> Outcome<ColorSpace> {
494 let s = match v {
495 Value::Func(Func::Native(NativeFunc::Color(f))) => match f {
496 ColorFn::Rgb => Some(ColorSpace::Rgb),
497 ColorFn::Luma => Some(ColorSpace::Luma),
498 ColorFn::Cmyk => Some(ColorSpace::Cmyk),
499 ColorFn::Oklab => Some(ColorSpace::Oklab),
500 ColorFn::Oklch => Some(ColorSpace::Oklch),
501 ColorFn::LinearRgb => Some(ColorSpace::LinearRgb),
502 ColorFn::Hsl => Some(ColorSpace::Hsl),
503 ColorFn::Hsv => Some(ColorSpace::Hsv),
504 _ => None,
505 },
506 _ => None,
507 };
508 match s {
509 Some(s) => Ok(s),
510 None => Err(engine.error(DiagnosticKind::Type, span,
511 "expected `rgb`, `luma`, `cmyk`, `oklab`, `oklch`, `color.linear-rgb`, `color.hsl`, or `color.hsv`")),
512 }
513}
514
515// Typst's `luma`: a colour anywhere among the arguments converts; otherwise the grey component, whose
516// failed cast or absence Typst quietly takes as 100%, then an optional ratio alpha.
517fn luma(engine: &mut Engine, span: Span, mut vals: Vec<Value>) -> Outcome<Color> {
518 if let Some(i) = vals.iter().position(|v| matches!(v, Value::Color(_))) {
519 let c = vals.remove(i);
520 if !vals.is_empty() {
521 return Err(engine.error(DiagnosticKind::Type, span, "unexpected argument"));
522 }
523 if let Value::Color(c) = c {
524 return Ok(to_space(&c, ColorSpace::Luma));
525 }
526 }
527 let mut it = vals.into_iter();
528 let l = match it.next() {
529 Some(Value::Int(i)) if (0..=255).contains(&i) => i as f32 / 255.0,
530 Some(Value::Ratio(r)) if (0.0..=1.0).contains(&r.0) => r.0 as f32,
531 _ => 1.0,
532 };
533 let a = match it.next() {
534 None => 1.0,
535 Some(v) => res!(ratio_only(engine, span, v)),
536 };
537 if it.next().is_some() {
538 return Err(engine.error(DiagnosticKind::Type, span, "unexpected argument"));
539 }
540 Ok(Color { space: ColorSpace::Luma, c: [l, 0.0, 0.0, 0.0], alpha: a })
541}
542
543// Constructors' component casts.
544
545// An eight-bit int or a ratio.
546fn comp(engine: &mut Engine, span: Span, v: Value) -> Outcome<f32> {
547 match v {
548 Value::Int(i) if (0..=255).contains(&i) => Ok(i as f32 / 255.0),
549 Value::Int(_) => Err(engine.error(DiagnosticKind::Type, span, "number must be between 0 and 255")),
550 Value::Ratio(r) => ratio_comp(engine, span, r),
551 other => Err(mismatch(engine, span, "integer or ratio", &other)),
552 }
553}
554
555fn ratio_comp(engine: &mut Engine, span: Span, r: Ratio) -> Outcome<f32> {
556 if (0.0..=1.0).contains(&r.0) {
557 Ok(r.0 as f32)
558 } else {
559 Err(engine.error(DiagnosticKind::Type, span, "ratio must be between 0% and 100%"))
560 }
561}
562
563fn ratio_only(engine: &mut Engine, span: Span, v: Value) -> Outcome<f32> {
564 match v {
565 Value::Ratio(r) => ratio_comp(engine, span, r),
566 other => Err(mismatch(engine, span, "ratio", &other)),
567 }
568}
569
570// Oklab's a and b and Oklch's chroma: a float, or a ratio of 0.4.
571fn chroma(engine: &mut Engine, span: Span, v: Value) -> Outcome<f32> {
572 match v {
573 Value::Float(f) => Ok(f as f32),
574 Value::Int(i) => Ok(i as f32),
575 Value::Ratio(r) => Ok((r.0 * 0.4) as f32),
576 other => Err(mismatch(engine, span, "float or ratio", &other)),
577 }
578}
579
580fn angle_deg(engine: &mut Engine, span: Span, v: Value) -> Outcome<f32> {
581 match v {
582 Value::Angle(a) => Ok(a.0.to_degrees() as f32),
583 other => Err(mismatch(engine, span, "angle", &other)),
584 }
585}
586
587fn color_of(engine: &mut Engine, span: Span, v: Value) -> Outcome<Color> {
588 match v {
589 Value::Color(c) => Ok(c),
590 other => Err(mismatch(engine, span, "color", &other)),
591 }
592}
593
594fn ratio_arg(engine: &mut Engine, span: Span, v: Value) -> Outcome<f32> {
595 match v {
596 Value::Ratio(r) => Ok(r.0 as f32),
597 other => Err(mismatch(engine, span, "ratio", &other)),
598 }
599}
600
601fn parse_hex(engine: &mut Engine, span: Span, s: &str) -> Outcome<Color> {
602 let h = s.strip_prefix('#').unwrap_or(s);
603 if !h.bytes().all(|b| b.is_ascii_hexdigit()) {
604 return Err(engine.error(DiagnosticKind::Type, span, "color string contains non-hexadecimal letters"));
605 }
606 let nib = |i: usize| u8::from_str_radix(&h[i..i + 1], 16).map(|x| x * 17).unwrap_or(0);
607 let byte = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).unwrap_or(0);
608 let c = match h.len() {
609 3 => rgb8(nib(0), nib(1), nib(2), 255),
610 4 => rgb8(nib(0), nib(1), nib(2), nib(3)),
611 6 => rgb8(byte(0), byte(2), byte(4), 255),
612 8 => rgb8(byte(0), byte(2), byte(4), byte(6)),
613 _ => return Err(engine.error(DiagnosticKind::Type, span, "color string has wrong length")),
614 };
615 Ok(c)
616}
617
618fn construct(f: ColorFn, engine: &mut Engine, args: &mut Args) -> Outcome<Color> {
619 let span = args.span;
620 let vals = res!(args.all::<Value>());
621 if f == ColorFn::Luma {
622 return luma(engine, span, vals);
623 }
624 if vals.len() == 1 {
625 if let Value::Color(c) = &vals[0] {
626 let space = match f {
627 ColorFn::Rgb => ColorSpace::Rgb,
628 ColorFn::Luma => ColorSpace::Luma,
629 ColorFn::Cmyk => ColorSpace::Cmyk,
630 ColorFn::Oklab => ColorSpace::Oklab,
631 ColorFn::Oklch => ColorSpace::Oklch,
632 ColorFn::LinearRgb => ColorSpace::LinearRgb,
633 ColorFn::Hsl => ColorSpace::Hsl,
634 _ => ColorSpace::Hsv,
635 };
636 return Ok(to_space(c, space));
637 }
638 if f == ColorFn::Rgb {
639 if let Value::Str(s) = &vals[0] {
640 return parse_hex(engine, span, s);
641 }
642 }
643 }
644 let (need_n, names): (usize, &[&str]) = match f {
645 ColorFn::Luma => (1, &["lightness", "alpha"]),
646 ColorFn::Cmyk => (4, &["cyan", "magenta", "yellow", "key"]),
647 ColorFn::Oklab => (3, &["lightness", "a", "b", "alpha"]),
648 ColorFn::Oklch => (3, &["lightness", "chroma", "hue", "alpha"]),
649 ColorFn::Hsl => (3, &["hue", "saturation", "lightness", "alpha"]),
650 ColorFn::Hsv => (3, &["hue", "saturation", "value", "alpha"]),
651 _ => (3, &["red", "green", "blue", "alpha"]),
652 };
653 if vals.len() < need_n {
654 return Err(engine.error(DiagnosticKind::Type, span, fmt!("missing argument: {}", names[vals.len()])));
655 }
656 if vals.len() > names.len() {
657 return Err(engine.error(DiagnosticKind::Type, span, "unexpected argument"));
658 }
659 let mut it = vals.into_iter();
660 let mut next = || it.next().unwrap_or(Value::None);
661 let c = match f {
662 ColorFn::Luma => {
663 let l = res!(comp(engine, span, next()));
664 let a = match next() {
665 Value::None => 1.0,
666 v => res!(comp(engine, span, v)),
667 };
668 Color { space: ColorSpace::Luma, c: [l, 0.0, 0.0, 0.0], alpha: a }
669 }
670 ColorFn::Cmyk => {
671 let c = res!(ratio_only(engine, span, next()));
672 let m = res!(ratio_only(engine, span, next()));
673 let y = res!(ratio_only(engine, span, next()));
674 let k = res!(ratio_only(engine, span, next()));
675 Color { space: ColorSpace::Cmyk, c: [c, m, y, k], alpha: 1.0 }
676 }
677 ColorFn::Oklab | ColorFn::Oklch => {
678 let l = res!(ratio_only(engine, span, next()));
679 let x = res!(chroma(engine, span, next()));
680 let y = if f == ColorFn::Oklab {
681 res!(chroma(engine, span, next()))
682 } else {
683 norm_hue(res!(angle_deg(engine, span, next())))
684 };
685 let a = match next() {
686 Value::None => 1.0,
687 v => res!(ratio_only(engine, span, v)),
688 };
689 let space = if f == ColorFn::Oklab { ColorSpace::Oklab } else { ColorSpace::Oklch };
690 Color { space, c: [l, x, y, 0.0], alpha: a }
691 }
692 ColorFn::Hsl | ColorFn::Hsv => {
693 let h = norm_hue(res!(angle_deg(engine, span, next())));
694 let s = res!(comp(engine, span, next()));
695 let x = res!(comp(engine, span, next()));
696 let a = match next() {
697 Value::None => 1.0,
698 v => res!(comp(engine, span, v)),
699 };
700 let space = if f == ColorFn::Hsl { ColorSpace::Hsl } else { ColorSpace::Hsv };
701 Color { space, c: [h, s, x, 0.0], alpha: a }
702 }
703 _ => {
704 let r = res!(comp(engine, span, next()));
705 let g = res!(comp(engine, span, next()));
706 let b = res!(comp(engine, span, next()));
707 let a = match next() {
708 Value::None => 1.0,
709 v => res!(comp(engine, span, v)),
710 };
711 let space = if f == ColorFn::LinearRgb { ColorSpace::LinearRgb } else { ColorSpace::Rgb };
712 Color { space, c: [r, g, b, 0.0], alpha: a }
713 }
714 };
715 Ok(c)
716}
717
718// Each space's components as a four-vector, hue in degrees, for mixing.
719fn to_vec4(c: &Color) -> [f32; 4] {
720 match c.space {
721 ColorSpace::Luma => [c.c[0], c.c[0], c.c[0], c.alpha],
722 ColorSpace::Cmyk => c.c,
723 _ => [c.c[0], c.c[1], c.c[2], c.alpha],
724 }
725}
726
727fn from_vec4(space: ColorSpace, v: [f32; 4]) -> Color {
728 match space {
729 ColorSpace::Luma => Color { space, c: [v[0], 0.0, 0.0, 0.0], alpha: v[3] },
730 ColorSpace::Cmyk => Color { space, c: v, alpha: 1.0 },
731 ColorSpace::Hsl | ColorSpace::Hsv => Color { space, c: [norm_hue(v[0]), v[1], v[2], 0.0], alpha: v[3] },
732 ColorSpace::Oklch => Color { space, c: [v[0], v[1], norm_hue(v[2]), 0.0], alpha: v[3] },
733 _ => Color { space, c: [v[0], v[1], v[2], 0.0], alpha: v[3] },
734 }
735}
736
737fn hue_index(space: ColorSpace) -> Option<usize> {
738 match space {
739 ColorSpace::Hsl | ColorSpace::Hsv => Some(0),
740 ColorSpace::Oklch => Some(2),
741 _ => None,
742 }
743}
744
745/// Mixes weighted colours in a space, hue the short way round for polar spaces, as Typst's `mix_iter`.
746pub fn mix(colors: &[(Color, f32)], space: ColorSpace) -> std::result::Result<Color, &'static str> {
747 if hue_index(space).is_some() && colors.len() > 2 {
748 return Err("cannot mix more than two colors in a hue-based space");
749 }
750 let m = if let (Some(hi), [(c0, w0), (c1, w1)]) = (hue_index(space), colors) {
751 let a = to_vec4(&to_space(c0, space));
752 let b = to_vec4(&to_space(c1, space));
753 if w0 + w1 <= 0.0 {
754 return Err("sum of weights must be positive");
755 }
756 let mut m = [0f32; 4];
757 for i in 0..4 {
758 m[i] = (w0 * a[i] + w1 * b[i]) / (w0 + w1);
759 }
760 if (a[hi] - b[hi]).abs() > 180.0 {
761 let (h0, h1) = if a[hi] < b[hi] { (a[hi] + 360.0, b[hi]) } else { (a[hi], b[hi] + 360.0) };
762 m[hi] = (w0 * h0 + w1 * h1) / (w0 + w1);
763 }
764 m
765 } else {
766 let mut total = 0f32;
767 let mut acc = [0f32; 4];
768 for (c, w) in colors {
769 let v = to_vec4(&to_space(c, space));
770 for i in 0..4 {
771 acc[i] += w * v[i];
772 }
773 total += w;
774 }
775 if total <= 0.0 {
776 return Err("sum of weights must be positive");
777 }
778 acc.map(|x| x / total)
779 };
780 Ok(from_vec4(space, m))
781}
782
783// Relative lighten and darken, palette's: move towards the maximum or minimum by a factor of the gap.
784fn lighten_ch(x: f32, f: f32) -> f32 { if f >= 0.0 { x + (1.0 - x) * f } else { x + x * f } }
785
786fn darken_ch(x: f32, f: f32) -> f32 { if f >= 0.0 { x - x * f } else { x - (1.0 - x) * f } }
787
788fn lighten(c: &Color, f: f32, dark: bool) -> Color {
789 let op = |x: f32| if dark { darken_ch(x, f) } else { lighten_ch(x, f) };
790 let mut out = *c;
791 match c.space {
792 ColorSpace::Luma | ColorSpace::Oklab | ColorSpace::Oklch => out.c[0] = op(c.c[0]),
793 ColorSpace::Rgb | ColorSpace::LinearRgb => for i in 0..3 {
794 out.c[i] = op(c.c[i]);
795 },
796 ColorSpace::Hsl | ColorSpace::Hsv => out.c[2] = op(c.c[2]),
797 ColorSpace::Cmyk => for i in 0..4 {
798 out.c[i] = if dark {
799 (c.c[i] + (1.0 - c.c[i]) * f).clamp(0.0, 1.0)
800 } else {
801 (c.c[i] - c.c[i] * f).clamp(0.0, 1.0)
802 };
803 },
804 }
805 out
806}
807
808fn saturate(c: &Color, f: f32, de: bool) -> Color {
809 let op = |s: f32| if de { darken_ch(s, f) } else { lighten_ch(s, f) };
810 match c.space {
811 ColorSpace::Hsl | ColorSpace::Hsv => {
812 let mut out = *c;
813 out.c[1] = op(c.c[1]);
814 out
815 }
816 _ => {
817 let mut hsv = to_space(c, ColorSpace::Hsv);
818 hsv.c[1] = op(hsv.c[1]);
819 to_space(&hsv, c.space)
820 }
821 }
822}
823
824fn negate(c: &Color, space: ColorSpace) -> Color {
825 let s = to_space(c, space);
826 let mut n = s;
827 match space {
828 ColorSpace::Luma => n.c[0] = 1.0 - s.c[0],
829 ColorSpace::Oklab => n.c = [1.0 - s.c[0], -s.c[1], -s.c[2], 0.0],
830 ColorSpace::Oklch => n.c = [1.0 - s.c[0], s.c[1], norm_hue(s.c[2] + 180.0), 0.0],
831 ColorSpace::Rgb | ColorSpace::LinearRgb => n.c = [1.0 - s.c[0], 1.0 - s.c[1], 1.0 - s.c[2], 0.0],
832 ColorSpace::Cmyk => n.c = [1.0 - s.c[0], 1.0 - s.c[1], 1.0 - s.c[2], s.c[3]],
833 ColorSpace::Hsl | ColorSpace::Hsv => n.c[0] = norm_hue(s.c[0] + 180.0),
834 }
835 to_space(&n, c.space)
836}
837
838fn scale_alpha(alpha: f32, factor: f32) -> f32 {
839 let a = if factor >= 0.0 { alpha * (1.0 - factor) } else { alpha + (-factor) * (1.0 - alpha) };
840 a.clamp(0.0, 1.0)
841}
842
843fn components(c: &Color, alpha: bool) -> Vec<Value> {
844 let r = |x: f32| Value::Ratio(Ratio(x as f64));
845 let fl = |x: f32| Value::Float(x as f64);
846 let an = |x: f32| Value::Angle(Angle((x as f64).to_radians()));
847 let mut v = match c.space {
848 ColorSpace::Luma => vec![r(c.c[0])],
849 ColorSpace::Oklab => vec![r(c.c[0]), fl(c.c[1]), fl(c.c[2])],
850 ColorSpace::Oklch => vec![r(c.c[0]), fl(c.c[1]), an(c.c[2])],
851 ColorSpace::Rgb | ColorSpace::LinearRgb => vec![r(c.c[0]), r(c.c[1]), r(c.c[2])],
852 ColorSpace::Cmyk => return vec![r(c.c[0]), r(c.c[1]), r(c.c[2]), r(c.c[3])],
853 ColorSpace::Hsl | ColorSpace::Hsv => vec![an(c.c[0]), r(c.c[1]), r(c.c[2])],
854 };
855 if alpha {
856 v.push(r(c.alpha));
857 }
858 v
859}
860
861// Gradients.
862
863fn stops_of(engine: &mut Engine, span: Span, vals: Vec<Value>, conic: bool) -> Outcome<Vec<(Color, Ratio)>> {
864 let mut raw: Vec<(Color, Option<Ratio>)> = Vec::with_capacity(vals.len());
865 for v in vals {
866 match v {
867 Value::Color(c) => raw.push((c, None)),
868 Value::Array(a) if a.len() == 2 => {
869 let c = res!(color_of(engine, span, a[0].clone()));
870 let o = match &a[1] {
871 Value::Ratio(r) => *r,
872 Value::Angle(x) if conic => Ratio(x.0 / std::f64::consts::TAU),
873 other => return Err(mismatch(engine, span, "ratio", other)),
874 };
875 raw.push((c, Some(o)));
876 }
877 other => return Err(mismatch(engine, span, "color or array", &other)),
878 }
879 }
880 if raw.len() < 2 {
881 return Err(engine.error_hint(DiagnosticKind::Type, span, "a gradient must have at least two stops",
882 "try filling the shape with a single color instead"));
883 }
884 if raw.iter().any(|(_, o)| o.is_some()) {
885 let mut last = f64::NEG_INFINITY;
886 for (_, o) in &raw {
887 match o {
888 None => return Err(engine.error_hint(DiagnosticKind::Type, span, "either all stops must have an offset or none of them can",
889 "try adding an offset to all stops")),
890 Some(r) => {
891 if r.0 < last {
892 return Err(engine.error(DiagnosticKind::Type, span, "offsets must be in monotonic order"));
893 }
894 last = r.0;
895 }
896 }
897 }
898 let out: Vec<(Color, Ratio)> = raw.into_iter().map(|(c, o)| (c, o.unwrap_or(Ratio(0.0)))).collect();
899 for (_, o) in &out {
900 if o.0 < 0.0 || o.0 > 1.0 {
901 return Err(engine.error(DiagnosticKind::Type, span, "offset must be between 0 and 1"));
902 }
903 }
904 if out.first().map(|s| (s.1).0 != 0.0).unwrap_or(false) {
905 return Err(engine.error_hint(DiagnosticKind::Type, span, "first stop must have an offset of 0", "try setting this stop to `0%`"));
906 }
907 if out.last().map(|s| (s.1).0 != 1.0).unwrap_or(false) {
908 return Err(engine.error_hint(DiagnosticKind::Type, span, "last stop must have an offset of 100%", "try setting this stop to `100%`"));
909 }
910 return Ok(out);
911 }
912 let n = raw.len();
913 Ok(raw.into_iter().enumerate().map(|(i, (c, _))| (c, Ratio(i as f64 / (n - 1) as f64))).collect())
914}
915
916fn relative_of(engine: &mut Engine, span: Span, v: Option<Value>) -> Outcome<RelativeTo> {
917 match v {
918 None | Some(Value::Auto) => Ok(RelativeTo::Auto),
919 Some(Value::Str(s)) if s.as_str() == "self" => Ok(RelativeTo::SelfBox),
920 Some(Value::Str(s)) if s.as_str() == "parent" => Ok(RelativeTo::Parent),
921 Some(other) => Err(engine.error(DiagnosticKind::Type, span,
922 crate::eval::lib::foundations::keyword_message(crate::eval::lib::visual::RELATIVE_TO, &other))),
923 }
924}
925
926fn pair_of(engine: &mut Engine, span: Span, v: Value) -> Outcome<(Ratio, Ratio)> {
927 match v {
928 Value::Array(a) if a.len() == 2 => match (&a[0], &a[1]) {
929 (Value::Ratio(x), Value::Ratio(y)) => Ok((*x, *y)),
930 _ => Err(engine.error(DiagnosticKind::Type, span, "expected a pair of ratios")),
931 },
932 other => Err(mismatch(engine, span, "array", &other)),
933 }
934}
935
936fn make_gradient(f: ColorFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> {
937 let span = args.span;
938 let space = match res!(args.named::<Value>("space")) {
939 None => ColorSpace::Oklab,
940 Some(v) => res!(space_of(engine, span, &v)),
941 };
942 let rel = res!(args.named::<Value>("relative"));
943 let relative = res!(relative_of(engine, span, rel));
944 let kind = match f {
945 ColorFn::GradientLinear => {
946 let angle = res!(args.named::<Value>("angle"));
947 let dir = res!(args.named::<Value>("dir"));
948 let a = match (angle, dir) {
949 (Some(Value::Angle(a)), _) => a,
950 (Some(other), _) => return Err(mismatch(engine, span, "angle", &other)),
951 (None, Some(Value::Direction(d))) => Angle(match d {
952 Direction::Ltr => 0.0,
953 Direction::Rtl => std::f64::consts::PI,
954 Direction::Ttb => std::f64::consts::FRAC_PI_2,
955 Direction::Btt => 3.0 * std::f64::consts::FRAC_PI_2,
956 }),
957 (None, Some(other)) => return Err(mismatch(engine, span, "direction", &other)),
958 (None, None) => Angle(0.0),
959 };
960 GradientKind::Linear { angle: a }
961 }
962 ColorFn::GradientRadial => {
963 let center = match res!(args.named::<Value>("center")) {
964 None => (Ratio(0.5), Ratio(0.5)),
965 Some(v) => res!(pair_of(engine, span, v)),
966 };
967 let radius = match res!(args.named::<Value>("radius")) {
968 None => Ratio(0.5),
969 Some(Value::Ratio(r)) => r,
970 Some(other) => return Err(mismatch(engine, span, "ratio", &other)),
971 };
972 let focal_center = match res!(args.named::<Value>("focal-center")) {
973 None | Some(Value::Auto) => center,
974 Some(v) => res!(pair_of(engine, span, v)),
975 };
976 let focal_radius = match res!(args.named::<Value>("focal-radius")) {
977 None => Ratio(0.0),
978 Some(Value::Ratio(r)) => r,
979 Some(other) => return Err(mismatch(engine, span, "ratio", &other)),
980 };
981 if focal_radius.0 > radius.0 {
982 return Err(engine.error_hint(DiagnosticKind::Type, span, "the focal radius must be smaller than the end radius",
983 "try using a focal radius of `0%` instead"));
984 }
985 let d = (((focal_center.0).0 - (center.0).0).powi(2) + ((focal_center.1).0 - (center.1).0).powi(2)).sqrt();
986 if d + focal_radius.0 > radius.0 {
987 return Err(engine.error_hint(DiagnosticKind::Type, span, "the focal circle must be inside of the end circle",
988 "try using a focal center of `auto` instead"));
989 }
990 GradientKind::Radial { center, radius, focal_center, focal_radius }
991 }
992 _ => {
993 let angle = match res!(args.named::<Value>("angle")) {
994 None => Angle(0.0),
995 Some(Value::Angle(a)) => a,
996 Some(other) => return Err(mismatch(engine, span, "angle", &other)),
997 };
998 let center = match res!(args.named::<Value>("center")) {
999 None => (Ratio(0.5), Ratio(0.5)),
1000 Some(v) => res!(pair_of(engine, span, v)),
1001 };
1002 GradientKind::Conic { center, angle }
1003 }
1004 };
1005 let vals = res!(args.all::<Value>());
1006 res!(finish(engine, args));
1007 let stops = res!(stops_of(engine, span, vals, f == ColorFn::GradientConic));
1008 let stops = stops.into_iter().map(|(c, r)| (to_space(&c, space), r)).collect();
1009 Ok(Value::Gradient(Arc::new(Gradient { kind, stops, space, relative })))
1010}
1011
1012/// The colour at `t` (0 to 1) along a gradient's stops, mixed in its space.
1013pub fn sample(g: &Gradient, t: f64) -> Color {
1014 let t = t.clamp(0.0, 1.0);
1015 let stops = &g.stops;
1016 let mut lo = 0;
1017 let mut hi = stops.len();
1018 while lo < hi {
1019 let mid = (lo + hi) / 2;
1020 if (stops[mid].1).0 < t {
1021 lo = mid + 1;
1022 } else {
1023 hi = mid;
1024 }
1025 }
1026 if lo == 0 {
1027 lo = 1;
1028 }
1029 if lo >= stops.len() {
1030 lo = stops.len() - 1;
1031 }
1032 let (c0, p0) = stops[lo - 1];
1033 let (c1, p1) = stops[lo];
1034 let span = p1.0 - p0.0;
1035 let u = if span == 0.0 { 0.0 } else { (t - p0.0) / span };
1036 match mix(&[(c0, (1.0 - u) as f32), (c1, u as f32)], g.space) {
1037 Ok(c) => c,
1038 Err(_) => c0,
1039 }
1040}
1041
1042fn sample_at(engine: &mut Engine, span: Span, g: &Gradient, v: Value) -> Outcome<Color> {
1043 let t = match v {
1044 Value::Ratio(r) => r.0,
1045 Value::Angle(a) => a.0.to_degrees().rem_euclid(360.0) / 360.0,
1046 other => return Err(mismatch(engine, span, "ratio or angle", &other)),
1047 };
1048 Ok(sample(g, t))
1049}
1050
1051fn same_stop(a: &(Color, Ratio), b: &(Color, Ratio)) -> bool { a.0 == b.0 && a.1 == b.1 }
1052
1053fn dedup(v: Vec<(Color, Ratio)>) -> Vec<(Color, Ratio)> {
1054 let mut out: Vec<(Color, Ratio)> = Vec::with_capacity(v.len());
1055 for s in v {
1056 if out.last().map(|l| same_stop(l, &s)).unwrap_or(false) {
1057 continue;
1058 }
1059 out.push(s);
1060 }
1061 out
1062}
1063
1064pub fn repr_gradient(g: &Gradient) -> String {
1065 let mut r = String::new();
1066 let pair = |p: (Ratio, Ratio)| fmt!("({}, {})", repr_ratio(p.0), repr_ratio(p.1));
1067 match &g.kind {
1068 GradientKind::Linear { angle } => {
1069 r.push_str("gradient.linear(");
1070 let a = angle.0.rem_euclid(std::f64::consts::TAU);
1071 let eps = f64::EPSILON;
1072 if a.abs() < eps {
1073 } else if (a - std::f64::consts::FRAC_PI_2).abs() < eps {
1074 r.push_str("dir: rtl, ");
1075 } else if (a - std::f64::consts::PI).abs() < eps {
1076 r.push_str("dir: ttb, ");
1077 } else if (a - 3.0 * std::f64::consts::FRAC_PI_2).abs() < eps {
1078 r.push_str("dir: btt, ");
1079 } else {
1080 r.push_str(&fmt!("angle: {}, ", repr_angle(*angle)));
1081 }
1082 }
1083 GradientKind::Radial { center, radius, focal_center, focal_radius } => {
1084 r.push_str("gradient.radial(");
1085 if (center.0).0 != 0.5 || (center.1).0 != 0.5 {
1086 r.push_str(&fmt!("center: {}, ", pair(*center)));
1087 }
1088 if radius.0 != 0.5 {
1089 r.push_str(&fmt!("radius: {}, ", repr_ratio(*radius)));
1090 }
1091 if focal_center != center {
1092 r.push_str(&fmt!("focal-center: {}, ", pair(*focal_center)));
1093 }
1094 if focal_radius.0 != 0.0 {
1095 r.push_str(&fmt!("focal-radius: {}, ", repr_ratio(*focal_radius)));
1096 }
1097 }
1098 GradientKind::Conic { center, angle } => {
1099 r.push_str("gradient.conic(");
1100 if angle.0 != 0.0 {
1101 r.push_str(&fmt!("angle: {}, ", repr_angle(*angle)));
1102 }
1103 if (center.0).0 != 0.5 || (center.1).0 != 0.5 {
1104 r.push_str(&fmt!("center: {}, ", pair(*center)));
1105 }
1106 }
1107 }
1108 if g.space != ColorSpace::Oklab {
1109 r.push_str(&fmt!("space: {}, ", space_fn(g.space).name()));
1110 }
1111 match g.relative {
1112 RelativeTo::Auto => (),
1113 RelativeTo::SelfBox => r.push_str("relative: \"self\", "),
1114 RelativeTo::Parent => r.push_str("relative: \"parent\", "),
1115 }
1116 let conic = matches!(g.kind, GradientKind::Conic { .. });
1117 let stops: Vec<String> = g.stops.iter().map(|(c, o)| if conic {
1118 fmt!("({}, {})", repr_color(c), repr_angle(Angle(o.0 * std::f64::consts::TAU)))
1119 } else {
1120 fmt!("({}, {})", repr_color(c), repr_ratio(*o))
1121 }).collect();
1122 r.push_str(&stops.join(", "));
1123 r.push(')');
1124 r
1125}
1126
1127fn with_stops(g: &Gradient, stops: Vec<(Color, Ratio)>) -> Value {
1128 Value::Gradient(Arc::new(Gradient { kind: g.kind.clone(), stops, space: g.space, relative: g.relative }))
1129}
1130
1131fn gradient_call(f: ColorFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> {
1132 let span = args.span;
1133 let g = match res!(receiver(&mut args)) {
1134 Value::Gradient(g) => g,
1135 other => return Err(mismatch(engine, span, "gradient", &other)),
1136 };
1137 let out = match f {
1138 ColorFn::GradientStops => Value::array(g.stops.iter()
1139 .map(|(c, r)| Value::array(vec![Value::Color(*c), Value::Ratio(*r)])).collect()),
1140 ColorFn::GradientSpace => func(space_fn(g.space)),
1141 ColorFn::GradientRelative => match g.relative {
1142 RelativeTo::Auto => Value::Auto,
1143 RelativeTo::SelfBox => Value::str("self"),
1144 RelativeTo::Parent => Value::str("parent"),
1145 },
1146 ColorFn::GradientKindOf => func(match g.kind {
1147 GradientKind::Linear { .. } => ColorFn::GradientLinear,
1148 GradientKind::Radial { .. } => ColorFn::GradientRadial,
1149 GradientKind::Conic { .. } => ColorFn::GradientConic,
1150 }),
1151 ColorFn::GradientAngle => match g.kind {
1152 GradientKind::Linear { angle } | GradientKind::Conic { angle, .. } => Value::Angle(angle),
1153 _ => Value::None,
1154 },
1155 ColorFn::GradientCenter => match g.kind {
1156 GradientKind::Radial { center, .. } | GradientKind::Conic { center, .. } =>
1157 Value::array(vec![Value::Ratio(center.0), Value::Ratio(center.1)]),
1158 _ => Value::None,
1159 },
1160 ColorFn::GradientRadius => match g.kind {
1161 GradientKind::Radial { radius, .. } => Value::Ratio(radius),
1162 _ => Value::None,
1163 },
1164 ColorFn::GradientFocalCenter => match g.kind {
1165 GradientKind::Radial { focal_center, .. } =>
1166 Value::array(vec![Value::Ratio(focal_center.0), Value::Ratio(focal_center.1)]),
1167 _ => Value::None,
1168 },
1169 ColorFn::GradientFocalRadius => match g.kind {
1170 GradientKind::Radial { focal_radius, .. } => Value::Ratio(focal_radius),
1171 _ => Value::None,
1172 },
1173 ColorFn::GradientSample => {
1174 let t = res!(need(engine, &mut args, "t"));
1175 Value::Color(res!(sample_at(engine, span, &g, t)))
1176 }
1177 ColorFn::GradientSamples => {
1178 let ts = res!(args.all::<Value>());
1179 let mut out = Vec::with_capacity(ts.len());
1180 for t in ts {
1181 out.push(Value::Color(res!(sample_at(engine, span, &g, t))));
1182 }
1183 Value::array(out)
1184 }
1185 ColorFn::GradientSharp => {
1186 let n = match res!(need(engine, &mut args, "steps")) {
1187 Value::Int(i) => i,
1188 other => return Err(mismatch(engine, span, "integer", &other)),
1189 };
1190 let smooth = match res!(args.named::<Value>("smoothness")) {
1191 None => 0.0,
1192 Some(Value::Ratio(r)) => r.0,
1193 Some(other) => return Err(mismatch(engine, span, "ratio", &other)),
1194 };
1195 if n < 2 {
1196 return Err(engine.error(DiagnosticKind::Type, span, "sharp gradients must have at least two stops"));
1197 }
1198 if !(0.0..=1.0).contains(&smooth) {
1199 return Err(engine.error(DiagnosticKind::Type, span, "smoothness must be between 0 and 1"));
1200 }
1201 let n = n as usize;
1202 let colors: Vec<Color> = (0..n).flat_map(|i| {
1203 let c = sample(&g, i as f64 / (n - 1) as f64);
1204 [c, c]
1205 }).collect();
1206 let progress = smooth / (4.0 * n as f64);
1207 let mut pos = vec![0f64; 2 * n];
1208 for i in 0..n {
1209 let j = 2 * i;
1210 pos[j] = i as f64 / n as f64;
1211 if j > 0 {
1212 pos[j] += progress;
1213 }
1214 pos[j + 1] = (i + 1) as f64 / n as f64;
1215 if j + 1 < colors.len() - 1 {
1216 pos[j + 1] -= progress;
1217 }
1218 }
1219 let stops = colors.into_iter().zip(pos).map(|(c, p)| (c, Ratio(p))).collect();
1220 with_stops(&g, dedup(stops))
1221 }
1222 ColorFn::GradientRepeat => {
1223 let n = match res!(need(engine, &mut args, "repetitions")) {
1224 Value::Int(i) => i,
1225 other => return Err(mismatch(engine, span, "integer", &other)),
1226 };
1227 let mirror = match res!(args.named::<Value>("mirror")) {
1228 None => false,
1229 Some(Value::Bool(b)) => b,
1230 Some(other) => return Err(mismatch(engine, span, "boolean", &other)),
1231 };
1232 if n <= 0 {
1233 return Err(engine.error(DiagnosticKind::Type, span, "must repeat at least once"));
1234 }
1235 let n = n as usize;
1236 let mut stops = Vec::new();
1237 for i in 0..n {
1238 let mut part: Vec<(Color, Ratio)> = g.stops.iter().map(|(c, o)| {
1239 if i % 2 == 1 && mirror {
1240 (*c, Ratio((i as f64 + 1.0 - o.0) / n as f64))
1241 } else {
1242 (*c, Ratio((i as f64 + o.0) / n as f64))
1243 }
1244 }).collect();
1245 if i % 2 == 1 && mirror {
1246 part.reverse();
1247 }
1248 stops.extend(part);
1249 }
1250 with_stops(&g, dedup(stops))
1251 }
1252 _ => Value::None,
1253 };
1254 res!(finish(engine, args));
1255 Ok(out)
1256}
1257
1258pub fn call(f: ColorFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> {
1259 let span = args.span;
1260 // Colour and gradient share one method table; `space` is both types', every other name one type's.
1261 let recv_ty = args.items.iter().find(|a| a.name.is_none()).map(|a| a.value.ty());
1262 let f = match (f, recv_ty) {
1263 (ColorFn::Space, Some(Type::Gradient)) => ColorFn::GradientSpace,
1264 (f, _) => f,
1265 };
1266 if let Some(ty) = recv_ty {
1267 let owner = if gradient_method(f.name()) == Some(f) {
1268 Some(Type::Gradient)
1269 } else if method(f.name()) == Some(f) {
1270 Some(Type::Color)
1271 } else {
1272 None
1273 };
1274 if let Some(owner) = owner {
1275 if owner != ty {
1276 return Err(no_method(engine, span, ty, f.name()));
1277 }
1278 }
1279 }
1280 match f {
1281 ColorFn::Rgb | ColorFn::Luma | ColorFn::Cmyk | ColorFn::Oklab | ColorFn::Oklch
1282 | ColorFn::LinearRgb | ColorFn::Hsl | ColorFn::Hsv => {
1283 let c = res!(construct(f, engine, &mut args));
1284 res!(finish(engine, args));
1285 return Ok(Value::Color(c));
1286 }
1287 ColorFn::Mix => {
1288 let space = match res!(args.named::<Value>("space")) {
1289 None => ColorSpace::Oklab,
1290 Some(v) => res!(space_of(engine, span, &v)),
1291 };
1292 let vals = res!(args.all::<Value>());
1293 res!(finish(engine, args));
1294 let mut cs = Vec::with_capacity(vals.len());
1295 for v in vals {
1296 match v {
1297 Value::Color(c) => cs.push((c, 1.0f32)),
1298 Value::Array(a) if a.len() == 2 => {
1299 let c = res!(color_of(engine, span, a[0].clone()));
1300 let w = match &a[1] {
1301 Value::Ratio(r) => r.0 as f32,
1302 Value::Float(x) => *x as f32,
1303 Value::Int(i) => *i as f32,
1304 other => return Err(mismatch(engine, span, "ratio or float", other)),
1305 };
1306 cs.push((c, w));
1307 }
1308 other => return Err(mismatch(engine, span, "color or array", &other)),
1309 }
1310 }
1311 return match mix(&cs, space) {
1312 Ok(c) => Ok(Value::Color(c)),
1313 Err(m) => Err(engine.error(DiagnosticKind::Type, span, m)),
1314 };
1315 }
1316 ColorFn::GradientLinear | ColorFn::GradientRadial | ColorFn::GradientConic => {
1317 return make_gradient(f, engine, args);
1318 }
1319 ColorFn::GradientSample | ColorFn::GradientSamples | ColorFn::GradientStops | ColorFn::GradientSharp
1320 | ColorFn::GradientRepeat | ColorFn::GradientKindOf | ColorFn::GradientSpace
1321 | ColorFn::GradientRelative | ColorFn::GradientAngle | ColorFn::GradientCenter
1322 | ColorFn::GradientRadius | ColorFn::GradientFocalCenter | ColorFn::GradientFocalRadius => {
1323 return gradient_call(f, engine, args);
1324 }
1325 _ => (),
1326 }
1327 let c = match res!(receiver(&mut args)) {
1328 Value::Color(c) => c,
1329 other => return Err(mismatch(engine, span, "color", &other)),
1330 };
1331 let out = match f {
1332 ColorFn::Lighten | ColorFn::Darken => {
1333 let x = res!(need(engine, &mut args, "factor"));
1334 let x = res!(ratio_arg(engine, span, x));
1335 Value::Color(lighten(&c, x, f == ColorFn::Darken))
1336 }
1337 ColorFn::Saturate | ColorFn::Desaturate => {
1338 let x = res!(need(engine, &mut args, "factor"));
1339 let x = res!(ratio_arg(engine, span, x));
1340 if c.space == ColorSpace::Luma {
1341 let verb = if f == ColorFn::Saturate { "saturate" } else { "desaturate" };
1342 return Err(engine.error_hint(DiagnosticKind::Type, span, fmt!("cannot {} grayscale color", verb),
1343 "try converting your color to RGB first"));
1344 }
1345 Value::Color(saturate(&c, x, f == ColorFn::Desaturate))
1346 }
1347 ColorFn::Negate => {
1348 let space = match res!(args.named::<Value>("space")) {
1349 None => ColorSpace::Oklab,
1350 Some(v) => res!(space_of(engine, span, &v)),
1351 };
1352 Value::Color(negate(&c, space))
1353 }
1354 ColorFn::Rotate => {
1355 let a = res!(need(engine, &mut args, "angle"));
1356 let deg = res!(angle_deg(engine, span, a));
1357 let space = match res!(args.named::<Value>("space")) {
1358 None => ColorSpace::Oklch,
1359 Some(v) => res!(space_of(engine, span, &v)),
1360 };
1361 let hi = match hue_index(space) {
1362 Some(h) => h,
1363 None => return Err(engine.error(DiagnosticKind::Type, span, "this color space does not support hue rotation")),
1364 };
1365 let mut s = to_space(&c, space);
1366 s.c[hi] = norm_hue(s.c[hi] + deg);
1367 Value::Color(to_space(&s, c.space))
1368 }
1369 ColorFn::Components => {
1370 let alpha = match res!(args.named::<Value>("alpha")) {
1371 None => true,
1372 Some(Value::Bool(b)) => b,
1373 Some(other) => return Err(mismatch(engine, span, "boolean", &other)),
1374 };
1375 Value::array(components(&c, alpha))
1376 }
1377 ColorFn::Space => func(space_fn(c.space)),
1378 ColorFn::ToHex => Value::str(to_hex(&c)),
1379 ColorFn::Transparentize | ColorFn::Opacify => {
1380 let x = res!(need(engine, &mut args, "scale"));
1381 let x = res!(ratio_arg(engine, span, x));
1382 if c.space == ColorSpace::Cmyk {
1383 return Err(engine.error(DiagnosticKind::Type, span, "CMYK does not have an alpha component"));
1384 }
1385 let factor = if f == ColorFn::Transparentize { x } else { -x };
1386 let mut out = c;
1387 out.alpha = scale_alpha(c.alpha, factor);
1388 Value::Color(out)
1389 }
1390 _ => Value::None,
1391 };
1392 res!(finish(engine, args));
1393 Ok(out)
1394}