ditherlib 1.0.0

Non-destructive image effects and dithering for whole images and custom selections
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use super::cells::{PixelGrid, SamplingMode, quantise_cells};
use super::noise::{BLUE_NOISE_16X16, BLUE_NOISE_SIZE};
use super::palette::Palette;
use crate::{DitherError, Effect, ErrorKind, Mask, Result};

const THRESHOLD_STRENGTH_SCALE: u16 = 256;

/// Deterministically maps each selected pixel to its nearest palette colour.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Threshold {
    palette: Palette,
    grid: PixelGrid,
}

impl Threshold {
    /// Creates threshold dithering with the supplied palette.
    pub const fn new(palette: Palette) -> Self {
        Self {
            palette,
            grid: PixelGrid::new(),
        }
    }

    /// Returns the target palette.
    pub const fn palette(&self) -> &Palette {
        &self.palette
    }

    /// Sets the logical pixel width.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidParameter`] when `width` is zero.
    pub fn with_pixel_width(mut self, width: u32) -> Result<Self> {
        self.grid = self.grid.with_width(width)?;
        Ok(self)
    }

    /// Returns the logical pixel width.
    pub const fn pixel_width(&self) -> u32 {
        self.grid.width()
    }

    /// Sets the logical pixel height.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidParameter`] when `height` is zero.
    pub fn with_pixel_height(mut self, height: u32) -> Result<Self> {
        self.grid = self.grid.with_height(height)?;
        Ok(self)
    }

    /// Returns the logical pixel height.
    pub const fn pixel_height(&self) -> u32 {
        self.grid.height()
    }

    /// Sets the logical pixel width and height.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidParameter`] when either dimension is zero.
    pub fn with_pixel_size(mut self, width: u32, height: u32) -> Result<Self> {
        self.grid = self.grid.with_size(width, height)?;
        Ok(self)
    }

    /// Returns the logical pixel dimensions as `(width, height)`.
    pub const fn pixel_size(&self) -> (u32, u32) {
        self.grid.size()
    }

    /// Offsets the logical pixel grid in image pixels.
    pub const fn with_grid_offset(mut self, x: i32, y: i32) -> Self {
        self.grid = self.grid.with_offset(x, y);
        self
    }

    /// Returns the logical pixel grid offset as `(x, y)` image pixels.
    pub const fn grid_offset(&self) -> (i32, i32) {
        self.grid.offset()
    }

    /// Selects the source-colour sampling used for each logical pixel.
    pub const fn with_sampling(mut self, sampling: SamplingMode) -> Self {
        self.grid = self.grid.with_sampling(sampling);
        self
    }

    /// Returns the source-colour sampling mode.
    pub const fn sampling(&self) -> SamplingMode {
        self.grid.sampling()
    }
}

impl Effect for Threshold {
    fn apply(
        &self,
        input: &[u8],
        output: &mut [u8],
        dimensions: (u32, u32),
        mask: &Mask,
    ) -> Result<()> {
        quantise_cells(
            input,
            output,
            dimensions,
            mask,
            self.grid,
            |colour, _, _| self.palette.nearest_colour(colour),
        );
        Ok(())
    }
}

/// A validated rectangular pattern of threshold ranks.
///
/// Each rank must be less than the number of entries in the map. Ranks may be
/// repeated, which permits patterns beyond dispersed-dot matrices.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ThresholdMap {
    width: u32,
    height: u32,
    thresholds: Box<[u32]>,
}

impl ThresholdMap {
    /// Creates a custom row-major threshold map.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidParameter`] when either dimension is zero,
    /// the number of thresholds does not match the dimensions, or a threshold
    /// is outside the map's rank range.
    pub fn new(width: u32, height: u32, thresholds: impl Into<Box<[u32]>>) -> Result<Self> {
        let thresholds = thresholds.into();
        let Some(length) = width.checked_mul(height) else {
            return Err(DitherError::new(
                ErrorKind::InvalidParameter,
                "threshold map dimensions are too large",
            ));
        };
        if length == 0 {
            return Err(DitherError::new(
                ErrorKind::InvalidParameter,
                "threshold map dimensions must be greater than zero",
            ));
        }
        if thresholds.len() != length as usize {
            return Err(DitherError::new(
                ErrorKind::InvalidParameter,
                "threshold count must match the map dimensions",
            ));
        }
        if thresholds.iter().any(|&threshold| threshold >= length) {
            return Err(DitherError::new(
                ErrorKind::InvalidParameter,
                "threshold ranks must be less than the map length",
            ));
        }

        Ok(Self {
            width,
            height,
            thresholds,
        })
    }

    /// Creates the standard 2x2 Bayer threshold map.
    pub fn bayer_2x2() -> Self {
        Self::bayer(2)
    }

    /// Creates the standard 4x4 Bayer threshold map.
    pub fn bayer_4x4() -> Self {
        Self::bayer(4)
    }

    /// Creates the standard 8x8 Bayer threshold map.
    pub fn bayer_8x8() -> Self {
        Self::bayer(8)
    }

    /// Creates a 16x16 blue-noise threshold map.
    pub fn blue_noise_16x16() -> Self {
        Self::preset(BLUE_NOISE_SIZE, BLUE_NOISE_SIZE, BLUE_NOISE_16X16)
    }

    /// Creates a 6x6 clustered-dot threshold map.
    pub fn clustered_dots() -> Self {
        Self::preset(
            6,
            6,
            [
                34, 25, 21, 17, 29, 33, 30, 13, 9, 5, 12, 24, 18, 6, 1, 0, 8, 20, 22, 10, 2, 3, 4,
                16, 26, 14, 7, 11, 15, 28, 35, 31, 19, 23, 27, 32,
            ],
        )
    }

    /// Creates a 4x4 horizontal-line threshold map.
    pub fn horizontal_lines() -> Self {
        Self::preset(4, 4, [0, 0, 0, 0, 8, 8, 8, 8, 12, 12, 12, 12, 4, 4, 4, 4])
    }

    /// Creates a 4x4 vertical-line threshold map.
    pub fn vertical_lines() -> Self {
        Self::preset(4, 4, [0, 8, 12, 4, 0, 8, 12, 4, 0, 8, 12, 4, 0, 8, 12, 4])
    }

    /// Creates a 4x4 diagonal-line threshold map.
    pub fn diagonal_lines() -> Self {
        Self::preset(4, 4, [0, 4, 8, 12, 4, 8, 12, 0, 8, 12, 0, 4, 12, 0, 4, 8])
    }

    /// Creates a 4x4 crosshatch threshold map.
    pub fn crosshatch() -> Self {
        Self::preset(4, 4, [0, 0, 0, 0, 0, 8, 8, 4, 0, 8, 12, 4, 0, 4, 4, 4])
    }

    /// Creates a 4x4 checkerboard threshold map.
    pub fn checkerboard() -> Self {
        Self::preset(
            4,
            4,
            [0, 0, 12, 12, 0, 0, 12, 12, 12, 12, 4, 4, 12, 12, 4, 4],
        )
    }

    /// Creates a 3x3 dispersed-dot threshold map.
    pub fn dispersed_dots_3x3() -> Self {
        Self::preset(3, 3, [6, 8, 4, 1, 0, 3, 5, 2, 7])
    }

    /// Creates a 5x5 dispersed-dot threshold map.
    pub fn dispersed_dots_5x5() -> Self {
        Self::preset(
            5,
            5,
            [
                0, 12, 3, 15, 6, 17, 9, 21, 1, 13, 4, 16, 7, 19, 10, 22, 2, 14, 5, 18, 8, 20, 11,
                23, 24,
            ],
        )
    }

    /// Returns the map width.
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// Returns the map height.
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// Returns the row-major threshold ranks.
    pub fn thresholds(&self) -> &[u32] {
        &self.thresholds
    }

    fn bayer(size: u32) -> Self {
        Self {
            width: size,
            height: size,
            thresholds: (0..size)
                .flat_map(|y| (0..size).map(move |x| u32::from(bayer_value(x, y, size as u8))))
                .collect(),
        }
    }

    fn preset<const LENGTH: usize>(width: u32, height: u32, thresholds: [u32; LENGTH]) -> Self {
        debug_assert_eq!(width as usize * height as usize, LENGTH);
        debug_assert!(
            thresholds
                .iter()
                .all(|&threshold| threshold < LENGTH as u32)
        );
        Self {
            width,
            height,
            thresholds: Box::new(thresholds),
        }
    }

    fn bayer_size(&self) -> Option<u32> {
        matches!(self.width, 2 | 4 | 8)
            .then_some(self.width)
            .filter(|&size| self.height == size)
            .filter(|&size| {
                self.thresholds.iter().enumerate().all(|(index, &value)| {
                    let index = index as u32;
                    value == u32::from(bayer_value(index % size, index / size, size as u8))
                })
            })
    }
}

/// A clockwise rotation applied to a threshold map.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum ThresholdRotation {
    /// Leaves the map unrotated.
    #[default]
    None,
    /// Rotates the map 90 degrees clockwise.
    Clockwise90,
    /// Rotates the map 180 degrees clockwise.
    Clockwise180,
    /// Rotates the map 270 degrees clockwise.
    Clockwise270,
}

/// Applies ordered dithering using a configurable threshold map.
///
/// The map is anchored to image-origin logical pixel coordinates, including
/// when rendering a polygon selection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OrderedDither {
    palette: Palette,
    map: ThresholdMap,
    grid: PixelGrid,
    strength: u16,
    offset: (i32, i32),
    rotation: ThresholdRotation,
    mirror_x: bool,
    mirror_y: bool,
}

impl OrderedDither {
    /// Creates ordered dithering with a validated threshold map.
    pub const fn new(palette: Palette, map: ThresholdMap) -> Self {
        Self {
            palette,
            map,
            grid: PixelGrid::new(),
            strength: THRESHOLD_STRENGTH_SCALE,
            offset: (0, 0),
            rotation: ThresholdRotation::None,
            mirror_x: false,
            mirror_y: false,
        }
    }

    /// Returns the target palette.
    pub const fn palette(&self) -> &Palette {
        &self.palette
    }

    /// Returns the threshold map.
    pub const fn map(&self) -> &ThresholdMap {
        &self.map
    }

    /// Sets the logical pixel width.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidParameter`] when `width` is zero.
    pub fn with_pixel_width(mut self, width: u32) -> Result<Self> {
        self.grid = self.grid.with_width(width)?;
        Ok(self)
    }

    /// Returns the logical pixel width.
    pub const fn pixel_width(&self) -> u32 {
        self.grid.width()
    }

    /// Sets the logical pixel height.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidParameter`] when `height` is zero.
    pub fn with_pixel_height(mut self, height: u32) -> Result<Self> {
        self.grid = self.grid.with_height(height)?;
        Ok(self)
    }

    /// Returns the logical pixel height.
    pub const fn pixel_height(&self) -> u32 {
        self.grid.height()
    }

    /// Sets the logical pixel width and height.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidParameter`] when either dimension is zero.
    pub fn with_pixel_size(mut self, width: u32, height: u32) -> Result<Self> {
        self.grid = self.grid.with_size(width, height)?;
        Ok(self)
    }

    /// Returns the logical pixel dimensions as `(width, height)`.
    pub const fn pixel_size(&self) -> (u32, u32) {
        self.grid.size()
    }

    /// Offsets the logical pixel grid in image pixels.
    pub const fn with_grid_offset(mut self, x: i32, y: i32) -> Self {
        self.grid = self.grid.with_offset(x, y);
        self
    }

    /// Returns the logical pixel grid offset as `(x, y)` image pixels.
    pub const fn grid_offset(&self) -> (i32, i32) {
        self.grid.offset()
    }

    /// Selects the source-colour sampling used for each logical pixel.
    pub const fn with_sampling(mut self, sampling: SamplingMode) -> Self {
        self.grid = self.grid.with_sampling(sampling);
        self
    }

    /// Returns the source-colour sampling mode.
    pub const fn sampling(&self) -> SamplingMode {
        self.grid.sampling()
    }

    /// Sets the strength of the threshold adjustment.
    ///
    /// Strength is rounded to the nearest 1/256. Zero disables the map's
    /// adjustment, one uses it unchanged, and two doubles it.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidParameter`] unless `strength` is finite and
    /// between zero and two inclusive.
    pub fn with_strength(mut self, strength: f32) -> Result<Self> {
        if !strength.is_finite() || !(0.0..=2.0).contains(&strength) {
            return Err(DitherError::new(
                ErrorKind::InvalidParameter,
                "threshold strength must be between zero and two",
            ));
        }
        self.strength = (strength * f32::from(THRESHOLD_STRENGTH_SCALE)).round() as u16;
        Ok(self)
    }

    /// Returns the threshold adjustment strength.
    pub fn strength(&self) -> f32 {
        f32::from(self.strength) / f32::from(THRESHOLD_STRENGTH_SCALE)
    }

    /// Offsets the map by logical pixels along the x and y axes.
    pub const fn with_offset(mut self, x: i32, y: i32) -> Self {
        self.offset = (x, y);
        self
    }

    /// Returns the map offset as `(x, y)` logical pixels.
    pub const fn offset(&self) -> (i32, i32) {
        self.offset
    }

    /// Rotates the threshold map clockwise around its origin.
    pub const fn with_rotation(mut self, rotation: ThresholdRotation) -> Self {
        self.rotation = rotation;
        self
    }

    /// Returns the map rotation.
    pub const fn rotation(&self) -> ThresholdRotation {
        self.rotation
    }

    /// Mirrors the transformed map horizontally and vertically.
    pub const fn with_mirroring(mut self, horizontal: bool, vertical: bool) -> Self {
        self.mirror_x = horizontal;
        self.mirror_y = vertical;
        self
    }

    /// Returns whether horizontal mirroring is enabled.
    pub const fn mirror_x(&self) -> bool {
        self.mirror_x
    }

    /// Returns whether vertical mirroring is enabled.
    pub const fn mirror_y(&self) -> bool {
        self.mirror_y
    }

    pub(super) fn transformed_dimensions(&self) -> (u32, u32) {
        match self.rotation {
            ThresholdRotation::None | ThresholdRotation::Clockwise180 => {
                (self.map.width, self.map.height)
            }
            ThresholdRotation::Clockwise90 | ThresholdRotation::Clockwise270 => {
                (self.map.height, self.map.width)
            }
        }
    }

    fn transformed_threshold(&self, mut x: u32, mut y: u32) -> u32 {
        let (width, height) = self.transformed_dimensions();
        debug_assert!(x < width && y < height);
        if self.mirror_x {
            x = width - x - 1;
        }
        if self.mirror_y {
            y = height - y - 1;
        }
        let (x, y) = match self.rotation {
            ThresholdRotation::None => (x, y),
            ThresholdRotation::Clockwise90 => (y, self.map.height - x - 1),
            ThresholdRotation::Clockwise180 => (self.map.width - x - 1, self.map.height - y - 1),
            ThresholdRotation::Clockwise270 => (self.map.width - y - 1, x),
        };
        self.map.thresholds[(y * self.map.width + x) as usize]
    }

    #[cfg(test)]
    pub(super) fn threshold(&self, x: u32, y: u32) -> u32 {
        let (width, height) = self.transformed_dimensions();
        let x = (i64::from(x) - i64::from(self.offset.0)).rem_euclid(i64::from(width)) as u32;
        let y = (i64::from(y) - i64::from(self.offset.1)).rem_euclid(i64::from(height)) as u32;
        self.transformed_threshold(x, y)
    }
}

impl Effect for OrderedDither {
    fn apply(
        &self,
        input: &[u8],
        output: &mut [u8],
        dimensions: (u32, u32),
        mask: &Mask,
    ) -> Result<()> {
        let bayer_size = self.map.bayer_size();
        if self.strength == THRESHOLD_STRENGTH_SCALE
            && self.offset == (0, 0)
            && self.rotation == ThresholdRotation::None
            && !self.mirror_x
            && !self.mirror_y
            && let Some(size) = bayer_size
        {
            let levels = (size * size) as i32;
            let mut adjustments = [0; 64];
            for y in 0..size {
                for x in 0..size {
                    let threshold = i32::from(bayer_value(x, y, size as u8));
                    adjustments[(y * size + x) as usize] =
                        (2 * threshold + 1 - levels) * 255 / (2 * levels);
                }
            }
            quantise_cells(
                input,
                output,
                dimensions,
                mask,
                self.grid,
                |colour, x, y| {
                    let x = x.rem_euclid(i64::from(size)) as usize;
                    let y = y.rem_euclid(i64::from(size)) as usize;
                    let adjustment = adjustments[y * size as usize + x];
                    let colour =
                        colour.map(|channel| (i32::from(channel) + adjustment).clamp(0, 255) as u8);
                    self.palette.nearest_colour(colour)
                },
            );
            return Ok(());
        }

        let (width, height) = self.transformed_dimensions();
        let levels = i64::from(self.map.width * self.map.height);
        let adjustments = (0..height)
            .flat_map(|y| {
                (0..width).map(move |x| {
                    let threshold = i64::from(self.transformed_threshold(x, y));
                    let adjustment = (2 * threshold + 1 - levels) * 255 / (2 * levels);
                    (adjustment * i64::from(self.strength) / i64::from(THRESHOLD_STRENGTH_SCALE))
                        as i32
                })
            })
            .collect::<Box<[_]>>();
        let offset_x = i64::from(self.offset.0).rem_euclid(i64::from(width)) as u32;
        let offset_y = i64::from(self.offset.1).rem_euclid(i64::from(height)) as u32;
        if offset_x == 0 && offset_y == 0 {
            quantise_cells(
                input,
                output,
                dimensions,
                mask,
                self.grid,
                |colour, x, y| {
                    let x = x.rem_euclid(i64::from(width)) as usize;
                    let y = y.rem_euclid(i64::from(height)) as usize;
                    let adjustment = adjustments[y * width as usize + x];
                    let colour =
                        colour.map(|channel| (i32::from(channel) + adjustment).clamp(0, 255) as u8);
                    self.palette.nearest_colour(colour)
                },
            );
            return Ok(());
        }
        quantise_cells(
            input,
            output,
            dimensions,
            mask,
            self.grid,
            |colour, x, y| {
                let x = x.rem_euclid(i64::from(width)) as u32;
                let y = y.rem_euclid(i64::from(height)) as u32;
                let x = if x >= offset_x {
                    x - offset_x
                } else {
                    width - (offset_x - x)
                };
                let y = if y >= offset_y {
                    y - offset_y
                } else {
                    height - (offset_y - y)
                };
                let adjustment = adjustments[(y * width + x) as usize];
                let colour =
                    colour.map(|channel| (i32::from(channel) + adjustment).clamp(0, 255) as u8);
                self.palette.nearest_colour(colour)
            },
        );
        Ok(())
    }
}

/// The dot geometry used by a [`Halftone`] screen.
fn bayer_value(x: u32, y: u32, size: u8) -> u8 {
    if size == 1 {
        return 0;
    }

    let x = x % u32::from(size);
    let y = y % u32::from(size);
    let half = u32::from(size / 2);
    let offset = match (x / half, y / half) {
        (0, 0) => 0,
        (1, 0) => 2,
        (0, 1) => 3,
        (1, 1) => 1,
        _ => unreachable!("coordinates are reduced to the Bayer matrix size"),
    };

    4 * bayer_value(x % half, y % half, size / 2) + offset
}