1#[derive(Debug, Clone, Copy, PartialEq)]
5pub struct Color {
6 pub r: f64,
8 pub g: f64,
10 pub b: f64,
12}
13
14impl Color {
15 pub const BLACK: Self = Self::rgb(0.0, 0.0, 0.0);
17 pub const WHITE: Self = Self::rgb(1.0, 1.0, 1.0);
19
20 pub const fn rgb(r: f64, g: f64, b: f64) -> Self {
22 Self { r, g, b }
23 }
24
25 pub fn from_bytes(r: u8, g: u8, b: u8) -> Self {
27 Self::rgb(
28 f64::from(r) / 255.0,
29 f64::from(g) / 255.0,
30 f64::from(b) / 255.0,
31 )
32 }
33
34 pub fn to_bytes(self) -> [u8; 3] {
36 [
37 component_to_byte(self.r),
38 component_to_byte(self.g),
39 component_to_byte(self.b),
40 ]
41 }
42
43 pub fn from_cmyk(c: f64, m: f64, y: f64, k: f64) -> Self {
46 let c = c.clamp(0.0, 1.0);
47 let m = m.clamp(0.0, 1.0);
48 let y = y.clamp(0.0, 1.0);
49 let k = k.clamp(0.0, 1.0);
50 Self::rgb(
51 (1.0 - c) * (1.0 - k),
52 (1.0 - m) * (1.0 - k),
53 (1.0 - y) * (1.0 - k),
54 )
55 }
56}
57
58fn component_to_byte(value: f64) -> u8 {
59 let scaled = (value.clamp(0.0, 1.0) * 255.0).round();
60 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
61 let byte = scaled as u8;
62 byte
63}
64
65#[derive(Debug, Clone, PartialEq)]
67pub struct Canvas {
68 width: u32,
69 height: u32,
70 pixels: Vec<u8>,
71 background: [u8; 4],
73}
74
75impl Canvas {
76 pub fn new(width: u32, height: u32, background: Color) -> Self {
78 let [r, g, b] = background.to_bytes();
79 let background = [r, g, b, 255];
80 let mut pixels = Vec::with_capacity((width as usize) * (height as usize) * 4);
81 for _ in 0..(width as usize) * (height as usize) {
82 pixels.extend_from_slice(&[r, g, b, 255]);
83 }
84 Self {
85 width,
86 height,
87 pixels,
88 background,
89 }
90 }
91
92 pub fn width(&self) -> u32 {
94 self.width
95 }
96
97 pub fn height(&self) -> u32 {
99 self.height
100 }
101
102 pub fn pixels(&self) -> &[u8] {
104 &self.pixels
105 }
106
107 pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
109 if x >= self.width || y >= self.height {
110 return None;
111 }
112 let index = ((y as usize) * (self.width as usize) + (x as usize)) * 4;
113 let slice = &self.pixels[index..index + 4];
114 Some([slice[0], slice[1], slice[2], slice[3]])
115 }
116
117 pub fn is_blank(&self) -> bool {
123 let background = self.background;
124 self.pixels
125 .as_chunks::<4>()
126 .0
127 .iter()
128 .all(|pixel| *pixel == background)
129 }
130
131 pub fn blend(&mut self, x: u32, y: u32, color: Color, alpha: f64) {
133 self.blend_with(x, y, color, alpha, BlendMode::Normal);
134 }
135
136 pub fn blend_with(&mut self, x: u32, y: u32, color: Color, alpha: f64, mode: BlendMode) {
142 if x >= self.width || y >= self.height || alpha <= 0.0 {
143 return;
144 }
145 let alpha = alpha.clamp(0.0, 1.0);
146 let [r, g, b] = color.to_bytes();
147 let index = ((y as usize) * (self.width as usize) + (x as usize)) * 4;
148 let target = &mut self.pixels[index..index + 4];
149 let backdrop = [
150 f64::from(target[0]) / 255.0,
151 f64::from(target[1]) / 255.0,
152 f64::from(target[2]) / 255.0,
153 ];
154 let source = [
155 f64::from(r) / 255.0,
156 f64::from(g) / 255.0,
157 f64::from(b) / 255.0,
158 ];
159 let blended = if mode == BlendMode::Normal {
160 source
161 } else if mode.is_non_separable() {
162 non_separable(mode, backdrop, source)
163 } else {
164 [
165 separable(mode, backdrop[0], source[0]),
166 separable(mode, backdrop[1], source[1]),
167 separable(mode, backdrop[2], source[2]),
168 ]
169 };
170 for (slot, (backdrop, blended)) in target.iter_mut().zip(backdrop.iter().zip(blended)) {
171 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
172 let value = ((blended * alpha + backdrop * (1.0 - alpha)).clamp(0.0, 1.0) * 255.0)
173 .round() as u8;
174 *slot = value;
175 }
176 target[3] = 255;
177 }
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
184pub enum BlendMode {
185 #[default]
187 Normal,
188 Multiply,
190 Screen,
192 Overlay,
194 Darken,
196 Lighten,
198 ColorDodge,
200 ColorBurn,
202 HardLight,
204 SoftLight,
206 Difference,
208 Exclusion,
210 Hue,
212 Saturation,
214 Color,
216 Luminosity,
218}
219
220impl BlendMode {
221 pub fn from_name(name: &[u8]) -> Option<Self> {
223 Some(match name {
224 b"Normal" | b"Compatible" => Self::Normal,
225 b"Multiply" => Self::Multiply,
226 b"Screen" => Self::Screen,
227 b"Overlay" => Self::Overlay,
228 b"Darken" => Self::Darken,
229 b"Lighten" => Self::Lighten,
230 b"ColorDodge" => Self::ColorDodge,
231 b"ColorBurn" => Self::ColorBurn,
232 b"HardLight" => Self::HardLight,
233 b"SoftLight" => Self::SoftLight,
234 b"Difference" => Self::Difference,
235 b"Exclusion" => Self::Exclusion,
236 b"Hue" => Self::Hue,
237 b"Saturation" => Self::Saturation,
238 b"Color" => Self::Color,
239 b"Luminosity" => Self::Luminosity,
240 _ => return None,
241 })
242 }
243
244 fn is_non_separable(self) -> bool {
246 matches!(
247 self,
248 Self::Hue | Self::Saturation | Self::Color | Self::Luminosity
249 )
250 }
251}
252
253fn separable(mode: BlendMode, backdrop: f64, source: f64) -> f64 {
255 match mode {
256 BlendMode::Multiply => backdrop * source,
257 BlendMode::Screen => backdrop + source - backdrop * source,
258 BlendMode::Overlay => separable(BlendMode::HardLight, source, backdrop),
259 BlendMode::Darken => backdrop.min(source),
260 BlendMode::Lighten => backdrop.max(source),
261 BlendMode::ColorDodge => {
262 if backdrop <= 0.0 {
263 0.0
264 } else if source >= 1.0 {
265 1.0
266 } else {
267 (backdrop / (1.0 - source)).min(1.0)
268 }
269 }
270 BlendMode::ColorBurn => {
271 if backdrop >= 1.0 {
272 1.0
273 } else if source <= 0.0 {
274 0.0
275 } else {
276 1.0 - ((1.0 - backdrop) / source).min(1.0)
277 }
278 }
279 BlendMode::HardLight => {
280 if source <= 0.5 {
281 separable(BlendMode::Multiply, backdrop, 2.0 * source)
282 } else {
283 separable(BlendMode::Screen, backdrop, 2.0 * source - 1.0)
284 }
285 }
286 BlendMode::SoftLight => {
287 if source <= 0.5 {
288 backdrop - (1.0 - 2.0 * source) * backdrop * (1.0 - backdrop)
289 } else {
290 let d = if backdrop <= 0.25 {
291 ((16.0 * backdrop - 12.0) * backdrop + 4.0) * backdrop
292 } else {
293 backdrop.sqrt()
294 };
295 backdrop + (2.0 * source - 1.0) * (d - backdrop)
296 }
297 }
298 BlendMode::Difference => (backdrop - source).abs(),
299 BlendMode::Exclusion => backdrop + source - 2.0 * backdrop * source,
300 _ => source,
302 }
303}
304
305fn luminance(colour: [f64; 3]) -> f64 {
307 0.3 * colour[0] + 0.59 * colour[1] + 0.11 * colour[2]
308}
309
310fn clip_colour(colour: [f64; 3]) -> [f64; 3] {
311 let l = luminance(colour);
312 let low = colour.iter().copied().fold(f64::MAX, f64::min);
313 let high = colour.iter().copied().fold(f64::MIN, f64::max);
314 if low < 0.0 {
315 let scale = l / (l - low);
316 colour.map(|value| l + (value - l) * scale)
317 } else if high > 1.0 {
318 let scale = (1.0 - l) / (high - l);
319 colour.map(|value| l + (value - l) * scale)
320 } else {
321 colour
322 }
323}
324
325fn set_luminance(colour: [f64; 3], l: f64) -> [f64; 3] {
326 let delta = l - luminance(colour);
327 clip_colour(colour.map(|value| value + delta))
328}
329
330fn saturation(colour: [f64; 3]) -> f64 {
331 let low = colour.iter().copied().fold(f64::MAX, f64::min);
332 let high = colour.iter().copied().fold(f64::MIN, f64::max);
333 high - low
334}
335
336fn set_saturation(colour: [f64; 3], s: f64) -> [f64; 3] {
337 let mut order = [0_usize, 1, 2];
338 order.sort_by(|left, right| {
339 colour[*left]
340 .partial_cmp(&colour[*right])
341 .unwrap_or(core::cmp::Ordering::Equal)
342 });
343 let (min, mid, max) = (order[0], order[1], order[2]);
344 let mut result = [0.0; 3];
345 if colour[max] > colour[min] {
346 result[mid] = (colour[mid] - colour[min]) * s / (colour[max] - colour[min]);
347 result[max] = s;
348 }
349 result[min] = 0.0;
350 result
351}
352
353fn non_separable(mode: BlendMode, backdrop: [f64; 3], source: [f64; 3]) -> [f64; 3] {
355 match mode {
356 BlendMode::Hue => set_luminance(
357 set_saturation(source, saturation(backdrop)),
358 luminance(backdrop),
359 ),
360 BlendMode::Saturation => set_luminance(
361 set_saturation(backdrop, saturation(source)),
362 luminance(backdrop),
363 ),
364 BlendMode::Color => set_luminance(source, luminance(backdrop)),
365 _ => set_luminance(backdrop, luminance(source)),
366 }
367}
368
369#[derive(Debug, Clone, PartialEq)]
374pub struct ClipMask {
375 width: u32,
376 height: u32,
377 coverage: Vec<u8>,
381}
382
383impl ClipMask {
384 pub fn all(width: u32, height: u32) -> Self {
386 Self {
387 width,
388 height,
389 coverage: vec![255; (width as usize) * (height as usize)],
390 }
391 }
392
393 pub fn none(width: u32, height: u32) -> Self {
395 Self {
396 width,
397 height,
398 coverage: vec![0; (width as usize) * (height as usize)],
399 }
400 }
401
402 pub fn contains(&self, x: u32, y: u32) -> bool {
404 if x >= self.width || y >= self.height {
405 return false;
406 }
407 self.coverage[(y as usize) * (self.width as usize) + (x as usize)] > 0
408 }
409
410 pub fn alpha(&self, x: u32, y: u32) -> f64 {
412 if x >= self.width || y >= self.height {
413 return 0.0;
414 }
415 f64::from(self.coverage[(y as usize) * (self.width as usize) + (x as usize)]) / 255.0
416 }
417
418 pub fn multiply_luminosity(&mut self, group: &Canvas) {
423 if group.width != self.width || group.height != self.height {
424 return;
425 }
426 for y in 0..self.height {
427 for x in 0..self.width {
428 let pixel = group.pixel(x, y).unwrap_or([0, 0, 0, 255]);
429 let luminance = 0.3 * f64::from(pixel[0])
430 + 0.59 * f64::from(pixel[1])
431 + 0.11 * f64::from(pixel[2]);
432 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
433 let coverage = (luminance * 255.0 / 255.0).round() as u8;
434 let index = (y as usize) * (self.width as usize) + (x as usize);
435 let scaled = u16::from(self.coverage[index]) * u16::from(coverage) / 255;
436 #[allow(clippy::cast_possible_truncation)]
437 let scaled = scaled as u8;
438 self.coverage[index] = scaled;
439 }
440 }
441 }
442
443 pub fn intersect(&mut self, other: &Self) {
445 if other.width != self.width || other.height != self.height {
446 return;
447 }
448 for (coverage, other) in self.coverage.iter_mut().zip(&other.coverage) {
449 let product = u16::from(*coverage) * u16::from(*other) / 255;
450 *coverage = u8::try_from(product).unwrap_or(u8::MAX);
451 }
452 }
453
454 pub fn set(&mut self, x: u32, y: u32, inside: bool) {
456 if x < self.width && y < self.height {
457 let value = if inside { 255 } else { 0 };
458 self.coverage[(y as usize) * (self.width as usize) + (x as usize)] = value;
459 }
460 }
461
462 pub fn count(&self) -> usize {
464 self.coverage
465 .iter()
466 .filter(|coverage| **coverage > 0)
467 .count()
468 }
469}
470
471#[cfg(test)]
472mod tests {
473 use super::{Canvas, ClipMask, Color};
474
475 #[test]
476 fn a_new_canvas_is_uniformly_filled() {
477 let canvas = Canvas::new(3, 2, Color::WHITE);
478 assert_eq!(canvas.width(), 3);
479 assert_eq!(canvas.height(), 2);
480 assert_eq!(canvas.pixels().len(), 3 * 2 * 4);
481 for y in 0..2 {
482 for x in 0..3 {
483 assert_eq!(canvas.pixel(x, y), Some([255, 255, 255, 255]));
484 }
485 }
486 assert_eq!(canvas.pixel(3, 0), None);
487 }
488
489 #[test]
490 fn blending_mixes_towards_the_source() {
491 let mut canvas = Canvas::new(1, 1, Color::WHITE);
492 canvas.blend(0, 0, Color::BLACK, 1.0);
493 assert_eq!(canvas.pixel(0, 0), Some([0, 0, 0, 255]));
494 let mut canvas = Canvas::new(1, 1, Color::BLACK);
495 canvas.blend(0, 0, Color::WHITE, 0.5);
496 assert_eq!(canvas.pixel(0, 0), Some([128, 128, 128, 255]));
497 canvas.blend(0, 0, Color::WHITE, 0.0);
498 assert_eq!(canvas.pixel(0, 0), Some([128, 128, 128, 255]));
499 }
500
501 #[test]
502 fn cmyk_conversion_is_the_naive_one() {
503 let red = Color::from_cmyk(0.0, 1.0, 1.0, 0.0);
504 assert_eq!(red.to_bytes(), [255, 0, 0]);
505 assert_eq!(Color::from_cmyk(0.0, 0.0, 0.0, 1.0).to_bytes(), [0, 0, 0]);
506 }
507
508 #[test]
509 fn clip_masks_intersect() {
510 let mut mask = ClipMask::all(4, 2);
511 assert_eq!(mask.count(), 8);
512 mask.set(1, 1, false);
513 assert!(!mask.contains(1, 1));
514 let mut other = ClipMask::all(4, 2);
515 other.set(0, 0, false);
516 mask.intersect(&other);
517 assert!(!mask.contains(0, 0));
518 assert!(mask.contains(2, 0));
519 assert_eq!(mask.count(), 6);
520 assert!(!mask.contains(4, 0));
521 }
522}