console_display/display/
pixel_display.rs

1use core::array;
2
3use num_traits::NumCast;
4
5use crate::{
6    console_display::{
7        DynamicConsoleDisplay,
8        StaticConsoleDisplay,
9    },
10    drawing::DynamicCanvas,
11    pixel::Pixel,
12    widget::{
13        DynamicWidget,
14        StaticWidget,
15        StringData,
16    },
17};
18
19pub struct DynamicPixelDisplay<T: Pixel> {
20    data: Box<[T]>,
21    width: usize,
22    height: usize,
23}
24
25impl<T: Pixel> DynamicPixelDisplay<T> {
26    /// Convenience method to build a blank display struct with specified dimensions.
27    ///
28    /// # Panics
29    ///
30    /// This function panics if the data generated from the fill does not match the dimensions of the display.
31    /// This should not happen and is subject to change in the future.
32    pub fn new(width: usize, height: usize, fill: T::U) -> Self
33    where
34        Self: Sized,
35        [(); T::WIDTH * T::HEIGHT]:,
36    {
37        let data: Vec<T::U> = vec![fill; width * height];
38        Self::build_from_data(width, height, &data).expect(
39            "Invariant violated, data does not mach specified dimensions.",
40        )
41    }
42
43    /// Builds a display struct from the given data with the specified dimensions.
44    ///
45    /// # Errors
46    ///
47    /// Returns an error when the length of the data does not match the dimensions of the display.
48    pub fn build_from_data(
49        width: usize,
50        height: usize,
51        data: &[T::U],
52    ) -> Result<Self, String>
53    where
54        Self: Sized,
55        [(); T::WIDTH * T::HEIGHT]:,
56    {
57        if !width.is_multiple_of(T::WIDTH) ||
58            !height.is_multiple_of(T::HEIGHT)
59        {
60            return Err(format!(
61                "Width and height must be multiples of multipixel dimensions. Got width = {width}, height = {height}."
62            ));
63        }
64        if data.len() != width * height {
65            return Err(format!(
66                "Data does not match specified dimensions. Expected length of {}, got {}.",
67                width * height,
68                data.len()
69            ));
70        }
71
72        let block_count_x = width / T::WIDTH;
73        let block_count_y = height / T::HEIGHT;
74
75        let mut multi_pixels =
76            Vec::with_capacity(block_count_x * block_count_y);
77
78        for row in 0..block_count_y {
79            for col in 0..block_count_x {
80                let block_x: usize = col * T::WIDTH;
81                let block_y: usize = row * T::HEIGHT;
82
83                let mut args: Vec<T::U> =
84                    Vec::with_capacity(T::WIDTH * T::HEIGHT);
85
86                for y in 0..T::HEIGHT {
87                    for x in 0..T::WIDTH {
88                        args.push(
89                            data[block_x + x + (block_y + y) * width],
90                        );
91                    }
92                }
93
94                multi_pixels.push(T::build(&args)?);
95            }
96        }
97
98        Ok(Self {
99            width,
100            height,
101            data: multi_pixels.into_boxed_slice(),
102        })
103    }
104}
105
106impl<T: Pixel> DynamicConsoleDisplay<T> for DynamicPixelDisplay<T> {
107    fn width(&self) -> usize {
108        self.width
109    }
110
111    fn height(&self) -> usize {
112        self.height
113    }
114
115    fn data(&self) -> &[T] {
116        &self.data
117    }
118
119    fn data_mut(&mut self) -> &mut Box<[T]> {
120        &mut self.data
121    }
122}
123
124impl<T: Pixel> DynamicWidget for DynamicPixelDisplay<T> {
125    fn width_characters(&self) -> usize {
126        self.width / T::WIDTH
127    }
128
129    fn height_characters(&self) -> usize {
130        self.height / T::HEIGHT
131    }
132
133    fn string_data(&self) -> StringData {
134        StringData {
135            data: self
136                .data
137                .chunks(self.width_characters())
138                .map(|chunk| chunk.iter().map(|x| (*x).into()).collect())
139                .collect(),
140        }
141    }
142}
143
144impl<S: Pixel> DynamicCanvas<S> for DynamicPixelDisplay<S> {
145    type A = usize;
146
147    fn pixel(&self, x: Self::A, y: Self::A) -> Result<S::U, String>
148    where
149        [(); S::WIDTH * S::HEIGHT]:,
150    {
151        let x: Option<usize> = NumCast::from(x);
152        let y: Option<usize> = NumCast::from(y);
153        if let Some(x) = x &&
154            let Some(y) = y
155        {
156            if x >= self.width() || y >= self.height() {
157                return Err(format!(
158                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
159                ));
160            }
161
162            let block_x: usize = x / S::WIDTH;
163            let block_y: usize = y / S::HEIGHT;
164            let offset_x: usize = x % S::WIDTH;
165            let offset_y: usize = y % S::HEIGHT;
166
167            let pixel =
168                &self.data()[block_x + block_y * self.width_characters()];
169
170            Ok(pixel
171                .subpixel(offset_x, offset_y)
172                .expect("Offset should be 0 or 1."))
173        }
174        else {
175            Err("Coordinates could not be converted to usize.".to_string())
176        }
177    }
178
179    fn set_pixel(
180        &mut self,
181        x: Self::A,
182        y: Self::A,
183        value: S::U,
184    ) -> Result<(), String>
185    where
186        [(); S::WIDTH * S::HEIGHT]:,
187    {
188        let x: Option<usize> = NumCast::from(x);
189        let y: Option<usize> = NumCast::from(y);
190        if let Some(x) = x &&
191            let Some(y) = y
192        {
193            if x >= self.width() || y >= self.height() {
194                return Err(format!(
195                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
196                ));
197            }
198
199            let block_x: usize = x / S::WIDTH;
200            let block_y: usize = y / S::HEIGHT;
201            let offset_x: usize = x % S::WIDTH;
202            let offset_y: usize = y % S::HEIGHT;
203
204            let width_characters = self.width_characters();
205            let pixel =
206                &mut self.data_mut()[block_x + block_y * width_characters];
207            pixel
208                .set_subpixel(offset_x, offset_y, value)
209                .expect("Offset should be 0 or 1.");
210
211            Ok(())
212        }
213        else {
214            Err("Coordinates could not be converted to usize.".to_string())
215        }
216    }
217}
218
219/// Represents a console display with a width and height in pixels.
220pub struct StaticPixelDisplay<
221    T: Pixel,
222    const WIDTH: usize,
223    const HEIGHT: usize,
224> {
225    data: Box<[T]>,
226}
227
228impl<T: Pixel, const WIDTH: usize, const HEIGHT: usize>
229    StaticPixelDisplay<T, WIDTH, HEIGHT>
230{
231    /// Convenience method to create a blank display struct with specified dimensions known at compile time.
232    pub fn new(fill: T::U) -> Self
233    where
234        [(); T::WIDTH * T::HEIGHT]:,
235        [(); WIDTH * HEIGHT]:,
236        [(); 0 - WIDTH % T::WIDTH]:,
237        [(); 0 - HEIGHT % T::HEIGHT]:,
238    {
239        let data: [T::U; WIDTH * HEIGHT] = [fill; WIDTH * HEIGHT];
240        Self::new_from_data(&data)
241    }
242
243    /// Creates a display struct from the given data with the specified dimensions known at compile time.
244    pub fn new_from_data(data: &[T::U; WIDTH * HEIGHT]) -> Self
245    where
246        [(); T::WIDTH * T::HEIGHT]:,
247        [(); 0 - WIDTH % T::WIDTH]:,
248        [(); 0 - HEIGHT % T::HEIGHT]:,
249    {
250        let mut multi_pixels = Vec::with_capacity(
251            Self::WIDTH_CHARACTERS * Self::HEIGHT_CHARACTERS,
252        );
253
254        for row in 0..Self::HEIGHT_CHARACTERS {
255            for col in 0..Self::WIDTH_CHARACTERS {
256                let block_x: usize = col * T::WIDTH;
257                let block_y: usize = row * T::HEIGHT;
258
259                let args: [T::U; T::WIDTH * T::HEIGHT] =
260                    array::from_fn(|i| {
261                        let x = i % T::WIDTH;
262                        let y = i / T::WIDTH;
263                        data[block_x + x + (block_y + y) * WIDTH]
264                    });
265
266                multi_pixels.push(T::new(args));
267            }
268        }
269
270        Self {
271            data: multi_pixels.into_boxed_slice(),
272        }
273    }
274}
275
276impl<T: Pixel, const WIDTH: usize, const HEIGHT: usize>
277    StaticConsoleDisplay<T> for StaticPixelDisplay<T, WIDTH, HEIGHT>
278{
279    const WIDTH: usize = WIDTH;
280
281    const HEIGHT: usize = HEIGHT;
282}
283
284impl<T: Pixel, const WIDTH: usize, const HEIGHT: usize>
285    DynamicConsoleDisplay<T> for StaticPixelDisplay<T, WIDTH, HEIGHT>
286{
287    fn width(&self) -> usize {
288        WIDTH
289    }
290
291    fn height(&self) -> usize {
292        HEIGHT
293    }
294
295    fn data(&self) -> &[T] {
296        &self.data
297    }
298
299    fn data_mut(&mut self) -> &mut Box<[T]> {
300        &mut self.data
301    }
302}
303
304impl<T: Pixel, const WIDTH: usize, const HEIGHT: usize> const StaticWidget
305    for StaticPixelDisplay<T, WIDTH, HEIGHT>
306{
307    const WIDTH_CHARACTERS: usize = WIDTH / T::WIDTH;
308
309    const HEIGHT_CHARACTERS: usize = HEIGHT / T::HEIGHT;
310}
311
312impl<T: Pixel, const WIDTH: usize, const HEIGHT: usize> DynamicWidget
313    for StaticPixelDisplay<T, WIDTH, HEIGHT>
314{
315    fn width_characters(&self) -> usize {
316        Self::WIDTH_CHARACTERS
317    }
318
319    fn height_characters(&self) -> usize {
320        Self::HEIGHT_CHARACTERS
321    }
322
323    fn string_data(&self) -> StringData {
324        StringData {
325            data: self
326                .data
327                .chunks(Self::WIDTH_CHARACTERS)
328                .map(|chunk| chunk.iter().map(|x| (*x).into()).collect())
329                .collect(),
330        }
331    }
332}
333
334impl<S: Pixel, const WIDTH: usize, const HEIGHT: usize> DynamicCanvas<S>
335    for StaticPixelDisplay<S, WIDTH, HEIGHT>
336{
337    type A = usize;
338
339    fn pixel(&self, x: Self::A, y: Self::A) -> Result<S::U, String>
340    where
341        [(); S::WIDTH * S::HEIGHT]:,
342    {
343        let x: Option<usize> = NumCast::from(x);
344        let y: Option<usize> = NumCast::from(y);
345        if let Some(x) = x &&
346            let Some(y) = y
347        {
348            if x >= self.width() || y >= self.height() {
349                return Err(format!(
350                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
351                ));
352            }
353
354            let block_x: usize = x / S::WIDTH;
355            let block_y: usize = y / S::HEIGHT;
356            let offset_x: usize = x % S::WIDTH;
357            let offset_y: usize = y % S::HEIGHT;
358
359            let pixel =
360                &self.data()[block_x + block_y * self.width_characters()];
361
362            Ok(pixel
363                .subpixel(offset_x, offset_y)
364                .expect("Offset should be 0 or 1."))
365        }
366        else {
367            Err("Coordinates could not be converted to usize.".to_string())
368        }
369    }
370
371    fn set_pixel(
372        &mut self,
373        x: Self::A,
374        y: Self::A,
375        value: S::U,
376    ) -> Result<(), String>
377    where
378        [(); S::WIDTH * S::HEIGHT]:,
379    {
380        let x: Option<usize> = NumCast::from(x);
381        let y: Option<usize> = NumCast::from(y);
382        if let Some(x) = x &&
383            let Some(y) = y
384        {
385            if x >= self.width() || y >= self.height() {
386                return Err(format!(
387                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
388                ));
389            }
390
391            let block_x: usize = x / S::WIDTH;
392            let block_y: usize = y / S::HEIGHT;
393            let offset_x: usize = x % S::WIDTH;
394            let offset_y: usize = y % S::HEIGHT;
395
396            let width_characters = self.width_characters();
397            let pixel =
398                &mut self.data_mut()[block_x + block_y * width_characters];
399            pixel
400                .set_subpixel(offset_x, offset_y, value)
401                .expect("Offset should be 0 or 1.");
402
403            Ok(())
404        }
405        else {
406            Err("Coordinates could not be converted to usize.".to_string())
407        }
408    }
409}
410
411#[cfg(test)]
412mod tests {
413    use crate::pixel::monochrome_pixel::SinglePixel;
414
415    use super::*;
416
417    mod dynamic_pixel_display {
418        use crate::drawing::DynamicCanvas;
419
420        use super::*;
421
422        #[test]
423        fn build_from_data_success() {
424            let dynamic_pixel_display =
425                DynamicPixelDisplay::<SinglePixel>::build_from_data(
426                    1,
427                    1,
428                    &[false],
429                );
430            assert!(dynamic_pixel_display.is_ok());
431        }
432
433        #[test]
434        fn build_from_data_failure_less() {
435            let dynamic_pixel_display =
436                DynamicPixelDisplay::<SinglePixel>::build_from_data(
437                    23,
438                    1,
439                    &[false; 22],
440                );
441            assert!(dynamic_pixel_display.is_err());
442        }
443
444        #[test]
445        fn build_from_data_failure_more() {
446            let dynamic_pixel_display =
447                DynamicPixelDisplay::<SinglePixel>::build_from_data(
448                    23,
449                    1,
450                    &[false; 24],
451                );
452            assert!(dynamic_pixel_display.is_err());
453        }
454
455        #[test]
456        fn pixel_success() {
457            let dynamic_pixel_display =
458                DynamicPixelDisplay::<SinglePixel>::new(2, 1, false);
459            let pixel = dynamic_pixel_display.pixel(1, 0);
460            assert!(pixel.is_ok());
461        }
462
463        #[test]
464        fn pixel_failure() {
465            let dynamic_pixel_display =
466                DynamicPixelDisplay::<SinglePixel>::new(2, 1, false);
467            let pixel = dynamic_pixel_display.pixel(0, 1);
468            assert!(pixel.is_err());
469        }
470
471        #[test]
472        fn set_pixel_success() {
473            let mut dynamic_pixel_display =
474                DynamicPixelDisplay::<SinglePixel>::new(2, 1, false);
475            let res = dynamic_pixel_display.set_pixel(1, 0, true);
476            let pixel = dynamic_pixel_display.pixel(1, 0);
477            assert!(res.is_ok());
478            assert_eq!(pixel, Ok(true));
479        }
480
481        #[test]
482        fn set_pixel_failure() {
483            let mut dynamic_pixel_display =
484                DynamicPixelDisplay::<SinglePixel>::new(2, 1, false);
485            let res = dynamic_pixel_display.set_pixel(0, 1, true);
486            assert!(res.is_err());
487        }
488    }
489}