planetarium 0.2.0

Sub-pixel precision light spot rendering library
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
//! Planetarium
//! ===========
//!
//! Canvas image export support definitions
//! ---------------------------------------
//!
//! Defines an enum for the supported image export formats
//! and image export methods for `Canvas`.
//!
//! Defines a custom error enum type `EncoderError`.

mod raw;

#[cfg(feature = "png")]
mod png;

use crate::{Canvas, Pixel};

/// Canvas image window coordinates
///
/// Defines a rectangular window on the canvas to export the image from.
///
/// The window origin is defined by its the upper left corner.
///
/// Basic operations
/// ----------------
///
/// ```
/// use planetarium::Window;
///
/// // Create a new rectangular window with origin at (0, 0).
/// let wnd1 = Window::new(128, 64);
///
/// // Move the window origin to (250, 150).
/// let wnd2 = wnd1.at(250, 150);
///
/// // Check the resulting string representation.
/// assert_eq!(wnd2.to_string(), "(250, 150)+(128, 64)");
/// ```
///
/// Conversions
/// -----------
///
/// ```
/// # use planetarium::Window;
/// // From a tuple of tuples representing the origin coordinates
/// // and window dimensions
/// let wnd1 = Window::from(((100, 200), (128, 128)));
///
/// // Check the resulting string representation.
/// assert_eq!(wnd1.to_string(), "(100, 200)+(128, 128)");
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Window {
    /// Window origin X coordinate
    pub x: u32,
    /// Window origin Y coordinate
    pub y: u32,
    /// Width in X direction
    pub w: u32,
    /// Height in Y direction
    pub h: u32,
}

/// Exportable canvas image formats
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum ImageFormat {
    // Internal encoders:
    /// 8-bit gamma-compressed grayscale RAW
    RawGamma8Bpp,
    /// 10-bit linear light grayscale little-endian RAW
    RawLinear10BppLE,
    /// 12-bit linear light grayscale little-endian RAW
    RawLinear12BppLE,

    // Require "png" feature:
    /// 8-bit gamma-compressed grayscale PNG
    PngGamma8Bpp,
    /// 16-bit linear light grayscale PNG
    PngLinear16Bpp,
}

/// Image export encoder error type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EncoderError {
    /// Requested image format not supported
    NotImplemented,
    /// Requested image window is out of bounds
    BrokenWindow,
    /// Requested image subsampling factors are too large or zero
    InvalidSubsamplingRate,
}

/// Canvas window image scanlines iterator
///
/// Yields the window image pixel spans as `&[Pixel]` slices.
///
/// Usage
/// -----
///
/// ```
/// use planetarium::{Canvas, Window};
///
/// let c = Canvas::new(100, 100);
///
/// // Define a 10x10 window rectangle with origin at (50, 50).
/// let wnd = Window::new(10, 10).at(50, 50);
///
/// // Iterate over the window image scanlines yielding 10-pixel spans.
/// for span in c.window_spans(wnd).unwrap() {
///     // Dummy check
///     assert_eq!(span, [0u16; 10]);
/// }
/// ```
pub struct WindowSpans<'a> {
    /// Source canvas object
    canvas: &'a Canvas,

    /// Canvas window rectangle
    window: Window,

    /// Current scanline index
    scanline: u32,
}

impl<'a> Iterator for WindowSpans<'a> {
    /// Image pixel span type
    type Item = &'a [Pixel];

    /// Iterates over the window image scanlines and returns the resulting
    /// image pixel spans as `&'a [Pixel]`.
    fn next(&mut self) -> Option<Self::Item> {
        // Terminate when the current scanline is outside of the window rectangle.
        if self.scanline >= self.window.y + self.window.h {
            return None;
        }

        // Calculate the current pixel span indexes.
        let base = (self.canvas.width * self.scanline + self.window.x) as usize;
        let end = base + self.window.w as usize;

        self.scanline += 1;

        Some(&self.canvas.pixbuf[base..end])
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let size = (self.window.y + self.window.h - self.scanline) as usize;

        (size, Some(size))
    }
}

impl<'a> ExactSizeIterator for WindowSpans<'a> {}

impl From<((u32, u32), (u32, u32))> for Window {
    /// Creates a window from a tuple `((x, y), (w, h))`.
    fn from(tuple: ((u32, u32), (u32, u32))) -> Self {
        let ((x, y), (w, h)) = tuple;

        Window { x, y, w, h }
    }
}

impl std::fmt::Display for Window {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "({}, {})+({}, {})", self.x, self.y, self.w, self.h)
    }
}

impl std::fmt::Display for EncoderError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        // FIXME: Put full length error descriptions here.
        write!(f, "{self:?}")
    }
}

impl std::error::Error for EncoderError {}

impl Window {
    /// Creates a new window with given dimensions located at the origin.
    #[must_use]
    pub fn new(width: u32, height: u32) -> Self {
        Window {
            x: 0,
            y: 0,
            w: width,
            h: height,
        }
    }

    /// Moves the window origin to the given origin coordinates.
    #[must_use]
    pub fn at(&self, x: u32, y: u32) -> Window {
        let w = self.w;
        let h = self.h;

        Window { x, y, w, h }
    }

    /// Checks if the window rectangle is inside the canvas rectangle.
    #[must_use]
    fn is_inside(&self, width: u32, height: u32) -> bool {
        self.x + self.w <= width && self.y + self.h <= height
    }

    /// Returns the total number of pixels in the window.
    #[must_use]
    fn len(&self) -> usize {
        (self.w * self.h) as usize
    }
}

/// Maximum supported image subsampling factor value
const MAX_SUBSAMPLING_RATE: u32 = 16;

/// Validates user-provided image subsampling factors
///
/// # Errors
///
/// Returns [`EncoderError::InvalidSubsamplingRate`] if the image subsampling
/// factors are too large or zero.
fn validate_subsampling_rate(factors: (u32, u32)) -> Result<(), EncoderError> {
    let is_valid = |x| x > 0 && x <= MAX_SUBSAMPLING_RATE;

    if is_valid(factors.0) && is_valid(factors.1) {
        Ok(())
    } else {
        Err(EncoderError::InvalidSubsamplingRate)
    }
}

impl Canvas {
    /// Returns an iterator over the canvas window image scanlines.
    ///
    /// The iteration starts from the window origin and goes in the positive Y direction.
    /// Each window scanline is represented as a pixel span (`&[Pixel]` slice).
    ///
    /// # Errors
    ///
    /// Returns `None` is the window rectangle origin or dimensions
    /// are out of the canvas bounds.
    #[must_use]
    pub fn window_spans(&self, window: Window) -> Option<WindowSpans<'_>> {
        if !window.is_inside(self.width, self.height) {
            return None;
        }

        let canvas = self;

        // Start iterating from the window origin.
        let scanline = window.y;

        let iter = WindowSpans {
            canvas,
            window,
            scanline,
        };

        Some(iter)
    }

    /// Exports the canvas contents in the requested image format.
    ///
    /// # Errors
    ///
    /// Returns [`EncoderError::NotImplemented`] if the requested image format
    /// is not yet supported.
    #[cfg(not(feature = "png"))]
    pub fn export_image(&self, format: ImageFormat) -> Result<Vec<u8>, EncoderError> {
        // Export the entire canvas.
        let window = Window::new(self.width, self.height);

        match format {
            ImageFormat::RawGamma8Bpp => self.export_raw8bpp(window),
            ImageFormat::RawLinear10BppLE => self.export_raw1xbpp::<10>(window),
            ImageFormat::RawLinear12BppLE => self.export_raw1xbpp::<12>(window),
            _ => Err(EncoderError::NotImplemented),
        }
    }

    /// Exports the canvas window image in the requested image format.
    ///
    /// # Errors
    ///
    /// Returns [`EncoderError::NotImplemented`] if the requested image format
    /// is not yet supported.
    ///
    /// Returns [`EncoderError::BrokenWindow`] if the window rectangle origin
    /// or dimensions are out of the canvas bounds.
    #[cfg(not(feature = "png"))]
    pub fn export_window_image(
        &self,
        window: Window,
        format: ImageFormat,
    ) -> Result<Vec<u8>, EncoderError> {
        if !window.is_inside(self.width, self.height) {
            return Err(EncoderError::BrokenWindow);
        }

        match format {
            ImageFormat::RawGamma8Bpp => self.export_raw8bpp(window),
            ImageFormat::RawLinear10BppLE => self.export_raw1xbpp::<10>(window),
            ImageFormat::RawLinear12BppLE => self.export_raw1xbpp::<12>(window),
            _ => Err(EncoderError::NotImplemented),
        }
    }

    /// Exports the subsampled canvas image in the requested image format.
    ///
    /// The integer subsampling factors in X and Y directions
    /// are passed in `factors`.
    ///
    /// # Errors
    ///
    /// Returns [`EncoderError::NotImplemented`] if the requested image format
    /// is not yet supported.
    #[cfg(not(feature = "png"))]
    pub fn export_subsampled_image(
        &self,
        factors: (u32, u32),
        format: ImageFormat,
    ) -> Result<Vec<u8>, EncoderError> {
        validate_subsampling_rate(factors)?;

        match format {
            ImageFormat::RawGamma8Bpp => self.export_sub_raw8bpp(factors),
            ImageFormat::RawLinear10BppLE => self.export_sub_raw1xbpp::<10>(factors),
            ImageFormat::RawLinear12BppLE => self.export_sub_raw1xbpp::<12>(factors),
            _ => Err(EncoderError::NotImplemented),
        }
    }

    /// Exports the canvas contents in the requested image format.
    ///
    /// # Errors
    ///
    /// Returns [`EncoderError::NotImplemented`] if the requested image format
    /// is not yet supported.
    #[cfg(feature = "png")]
    pub fn export_image(&self, format: ImageFormat) -> Result<Vec<u8>, EncoderError> {
        // Export the entire canvas.
        let window = Window::new(self.width, self.height);

        match format {
            ImageFormat::RawGamma8Bpp => self.export_raw8bpp(window),
            ImageFormat::RawLinear10BppLE => self.export_raw1xbpp::<10>(window),
            ImageFormat::RawLinear12BppLE => self.export_raw1xbpp::<12>(window),
            ImageFormat::PngGamma8Bpp => self.export_png8bpp(window),
            ImageFormat::PngLinear16Bpp => self.export_png16bpp(window),
        }
    }

    /// Exports the canvas window image in the requested image format.
    ///
    /// # Errors
    ///
    /// Returns [`EncoderError::NotImplemented`] if the requested image format
    /// is not yet supported.
    ///
    /// Returns [`EncoderError::BrokenWindow`] if the window rectangle origin
    /// or dimensions are out of the canvas bounds.
    #[cfg(feature = "png")]
    pub fn export_window_image(
        &self,
        window: Window,
        format: ImageFormat,
    ) -> Result<Vec<u8>, EncoderError> {
        if !window.is_inside(self.width, self.height) {
            return Err(EncoderError::BrokenWindow);
        }

        match format {
            ImageFormat::RawGamma8Bpp => self.export_raw8bpp(window),
            ImageFormat::RawLinear10BppLE => self.export_raw1xbpp::<10>(window),
            ImageFormat::RawLinear12BppLE => self.export_raw1xbpp::<12>(window),
            ImageFormat::PngGamma8Bpp => self.export_png8bpp(window),
            ImageFormat::PngLinear16Bpp => self.export_png16bpp(window),
        }
    }

    /// Exports the subsampled canvas image in the requested image format.
    ///
    /// The integer subsampling factors in X and Y directions
    /// are passed in `factors`.
    ///
    /// # Errors
    ///
    /// Returns [`EncoderError::NotImplemented`] if the requested image format
    /// is not yet supported.
    #[cfg(feature = "png")]
    pub fn export_subsampled_image(
        &self,
        factors: (u32, u32),
        format: ImageFormat,
    ) -> Result<Vec<u8>, EncoderError> {
        validate_subsampling_rate(factors)?;

        match format {
            ImageFormat::RawGamma8Bpp => self.export_sub_raw8bpp(factors),
            ImageFormat::RawLinear10BppLE => self.export_sub_raw1xbpp::<10>(factors),
            ImageFormat::RawLinear12BppLE => self.export_sub_raw1xbpp::<12>(factors),
            ImageFormat::PngGamma8Bpp => self.export_sub_png8bpp(factors),
            ImageFormat::PngLinear16Bpp => self.export_sub_png16bpp(factors),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::SpotShape;

    #[cfg(not(feature = "png"))]
    #[test]
    fn image_format_error() {
        let c = Canvas::new(0, 0);

        assert_eq!(
            c.export_image(ImageFormat::PngGamma8Bpp),
            Err(EncoderError::NotImplemented)
        );
    }

    #[test]
    fn broken_window_error() {
        let c = Canvas::new(10, 10);
        let wnd = Window::new(8, 8).at(5, 5);

        assert_eq!(
            c.export_window_image(wnd, ImageFormat::RawGamma8Bpp),
            Err(EncoderError::BrokenWindow)
        );
    }

    #[test]
    fn subsampling_rate_error() {
        let c = Canvas::new(0, 0);

        assert_eq!(
            c.export_subsampled_image((1, 0), ImageFormat::RawGamma8Bpp),
            Err(EncoderError::InvalidSubsamplingRate)
        );
        assert_eq!(
            c.export_subsampled_image((0, 1), ImageFormat::RawLinear10BppLE),
            Err(EncoderError::InvalidSubsamplingRate)
        );
        assert_eq!(
            c.export_subsampled_image((4, 17), ImageFormat::RawLinear12BppLE),
            Err(EncoderError::InvalidSubsamplingRate)
        );
    }

    #[test]
    fn window_ops() {
        let wnd = Window::new(128, 64).at(200, 100);

        assert_eq!(wnd.len(), 128 * 64);
        assert!(wnd.is_inside(400, 500));
        assert!(!wnd.is_inside(100, 100));
        assert!(!wnd.at(300, 100).is_inside(400, 500));
    }

    #[test]
    fn get_window_spans() {
        let mut c = Canvas::new(100, 100);

        c.add_spot((50.75, 50.5), SpotShape::default(), 1.0);
        c.draw();

        let wnd1 = Window::new(4, 3).at(50, 50);

        let mut vec = Vec::new();
        for span in c.window_spans(wnd1).unwrap() {
            vec.extend_from_slice(span);
        }

        assert_eq!(
            vec,
            [542, 18087, 1146, 0, 542, 18087, 1146, 0, 193, 731, 0, 0]
        );

        let wnd2 = wnd1.at(48, 51);

        vec.clear();
        for span in c.window_spans(wnd2).unwrap() {
            vec.extend_from_slice(span);
        }

        assert_eq!(vec, [0, 0, 542, 18087, 0, 0, 193, 731, 0, 0, 0, 0]);
    }

    #[test]
    fn broken_windows() {
        let c = Canvas::new(100, 100);

        let wnd1 = Window::new(4, 100).at(50, 50);
        assert!(c.window_spans(wnd1).is_none());

        let wnd2 = Window::new(4, 5).at(100, 100);
        assert!(c.window_spans(wnd2).is_none());

        let wnd3 = Window::new(1, 1).at(100, 100);
        assert!(c.window_spans(wnd3).is_none());

        let wnd4 = Window::new(0, 0).at(100, 100);
        let mut spans = c.window_spans(wnd4).unwrap();
        assert_eq!(spans.len(), 0);
        assert!(spans.next().is_none());
    }
}