Skip to main content

mln_style/
bitmap.rs

1// Decoding images and encoding PNGs live in //crates/mln_engine/src/image,
2// so that this file stays dependency-free.
3
4use std::fmt;
5use std::marker::PhantomData;
6
7use geometry::Point;
8
9use crate::size::Size;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub enum ImageAlphaMode {
13    Unassociated,
14    Premultiplied,
15    /// Alpha-channel only.
16    Exclusive,
17}
18
19/// The alpha mode of an [`Image`], as its type parameter.
20pub trait AlphaMode {
21    const MODE: ImageAlphaMode;
22    /// The bytes per pixel: 1 for `Exclusive`, 4 otherwise.
23    const CHANNELS: usize;
24}
25
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
27pub struct Unassociated;
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub struct Premultiplied;
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
31pub struct Exclusive;
32
33impl AlphaMode for Unassociated {
34    const MODE: ImageAlphaMode = ImageAlphaMode::Unassociated;
35    const CHANNELS: usize = 4;
36}
37impl AlphaMode for Premultiplied {
38    const MODE: ImageAlphaMode = ImageAlphaMode::Premultiplied;
39    const CHANNELS: usize = 4;
40}
41impl AlphaMode for Exclusive {
42    const MODE: ImageAlphaMode = ImageAlphaMode::Exclusive;
43    const CHANNELS: usize = 1;
44}
45
46/// Why an image operation failed.
47#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
48pub enum ImageError {
49    /// The pixel buffer's length doesn't match the image's size.
50    #[error("the pixels don't match the image's size")]
51    WrongLength,
52    /// The source or destination image has no pixels.
53    #[error("the image has no pixels")]
54    NoPixels,
55    /// The rectangle doesn't fit inside the source or destination image.
56    #[error("the rectangle is outside the image")]
57    OutsideImage,
58}
59
60/// An image: `size` plus `channels * width * height` bytes.
61///
62/// An empty `data` is an image without pixels, such as the default image.
63///
64/// An image crosses with its pixels as a payload (serialization/payload.rs),
65/// and only images whose pixels fill their size read back.
66pub struct Image<M: AlphaMode> {
67    pub size: Size,
68    pub data: Vec<u8>,
69    _mode: PhantomData<M>,
70}
71
72impl<M: AlphaMode> mln_wire::Wire for Image<M> {
73    fn write(&self, w: &mut mln_wire::Writer) {
74        self.size.write(w);
75        mln_wire::payload::bytes::write(&self.data, w);
76    }
77
78    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
79        let size = Size::read(r)?;
80        let data = mln_wire::payload::bytes::read(r)?;
81        Image::try_from(ImageParts { size, data }).ok().or_else(|| r.fail("pixels that don't fill their image"))
82    }
83}
84
85/// What `Image` is read from.
86struct ImageParts {
87    size: Size,
88    data: Vec<u8>,
89}
90
91impl<M: AlphaMode> TryFrom<ImageParts> for Image<M> {
92    type Error = String;
93
94    fn try_from(ImageParts { size, data }: ImageParts) -> Result<Self, String> {
95        // In u64: on wasm32 `bytes()` would wrap for a large size.
96        let bytes =
97            u64::from(size.width).checked_mul(u64::from(size.height)).and_then(|n| n.checked_mul(M::CHANNELS as u64));
98        if bytes != Some(data.len() as u64) {
99            return Err(format!("{} bytes for a {}x{} image", data.len(), size.width, size.height));
100        }
101        Ok(Image::from_vec(size, data))
102    }
103}
104
105pub type UnassociatedImage = Image<Unassociated>;
106pub type PremultipliedImage = Image<Premultiplied>;
107pub type AlphaImage = Image<Exclusive>;
108
109impl<M: AlphaMode> Image<M> {
110    pub const CHANNELS: usize = M::CHANNELS;
111
112    /// An image of zeroed pixels.
113    #[must_use]
114    pub fn new(size: Size) -> Self {
115        let bytes = M::CHANNELS * size.width as usize * size.height as usize;
116        Image { size, data: vec![0; bytes], _mode: PhantomData }
117    }
118
119    pub fn from_slice(size: Size, src: &[u8]) -> Result<Self, ImageError> {
120        let mut image = Image { size, data: Vec::new(), _mode: PhantomData };
121        if src.len() != image.bytes() {
122            return Err(ImageError::WrongLength);
123        }
124        if image.bytes() != 0 {
125            image.data = src.to_vec();
126        }
127        Ok(image)
128    }
129
130    /// Takes the buffer as is, without checking its length against `size`.
131    #[must_use]
132    pub fn from_vec(size: Size, data: Vec<u8>) -> Self {
133        Image { size, data, _mode: PhantomData }
134    }
135
136    /// Splits the image into its size and pixel buffer, which can make an
137    /// image of another alpha mode.
138    #[must_use]
139    pub fn into_parts(self) -> (Size, Vec<u8>) {
140        (self.size, self.data)
141    }
142
143    #[must_use]
144    pub fn valid(&self) -> bool {
145        !self.size.is_empty() && !self.data.is_empty()
146    }
147
148    #[must_use]
149    pub fn stride(&self) -> usize {
150        M::CHANNELS * self.size.width as usize
151    }
152
153    #[must_use]
154    pub fn bytes(&self) -> usize {
155        self.stride() * self.size.height as usize
156    }
157
158    pub fn fill(&mut self, value: u8) {
159        if self.valid() {
160            let bytes = self.bytes();
161            self.data[..bytes].fill(value);
162        }
163    }
164
165    pub fn resize(&mut self, size: Size) {
166        if self.size == size {
167            return;
168        }
169        let mut new_image = Image::<M>::new(size);
170        if !size.is_empty() && self.valid() {
171            new_image.fill(0);
172            let copy_size =
173                Size::new(std::cmp::min(self.size.width, size.width), std::cmp::min(self.size.height, size.height));
174            // Both rectangles are in bounds by construction.
175            Self::copy(self, &mut new_image, Point::new(0, 0), Point::new(0, 0), copy_size)
176                .expect("resize copy is in bounds");
177        }
178        *self = new_image;
179    }
180
181    /// Clears the rect area specified by `pt` and `size` from `dst_img`.
182    pub fn clear(dst_img: &mut Self, pt: Point<u32>, size: Size) -> Result<(), ImageError> {
183        if size.is_empty() {
184            return Ok(());
185        }
186
187        if !dst_img.valid() {
188            return Err(ImageError::NoPixels);
189        }
190
191        if size.width > dst_img.size.width
192            || size.height > dst_img.size.height
193            || pt.x > dst_img.size.width - size.width
194            || pt.y > dst_img.size.height - size.height
195        {
196            return Err(ImageError::OutsideImage);
197        }
198
199        let stride = dst_img.stride();
200        for y in 0..size.height {
201            let dst_offset = (pt.y + y) as usize * stride + pt.x as usize * M::CHANNELS;
202            dst_img.data[dst_offset..dst_offset + size.width as usize * M::CHANNELS].fill(0);
203        }
204        Ok(())
205    }
206
207    /// Copy image data within `rect` from `src` to the rectangle of the same
208    /// size at `pt` in `dst`. If the specified bounds exceed the bounds of the
209    /// source or destination, return `ImageError::OutsideImage`. Borrowing
210    /// rules rule out copying within a single image.
211    pub fn copy(
212        src_img: &Self,
213        dst_img: &mut Self,
214        src_pt: Point<u32>,
215        dst_pt: Point<u32>,
216        size: Size,
217    ) -> Result<(), ImageError> {
218        if size.is_empty() {
219            return Ok(());
220        }
221
222        if !src_img.valid() {
223            return Err(ImageError::NoPixels);
224        }
225
226        if !dst_img.valid() {
227            return Err(ImageError::NoPixels);
228        }
229
230        if size.width > src_img.size.width
231            || size.height > src_img.size.height
232            || src_pt.x > src_img.size.width - size.width
233            || src_pt.y > src_img.size.height - size.height
234        {
235            return Err(ImageError::OutsideImage);
236        }
237
238        if size.width > dst_img.size.width
239            || size.height > dst_img.size.height
240            || dst_pt.x > dst_img.size.width - size.width
241            || dst_pt.y > dst_img.size.height - size.height
242        {
243            return Err(ImageError::OutsideImage);
244        }
245
246        let src_stride = src_img.stride();
247        let dst_stride = dst_img.stride();
248        let row = size.width as usize * M::CHANNELS;
249        for y in 0..size.height {
250            let src_offset = (src_pt.y + y) as usize * src_stride + src_pt.x as usize * M::CHANNELS;
251            let dst_offset = (dst_pt.y + y) as usize * dst_stride + dst_pt.x as usize * M::CHANNELS;
252            dst_img.data[dst_offset..dst_offset + row].copy_from_slice(&src_img.data[src_offset..src_offset + row]);
253        }
254        Ok(())
255    }
256
257    fn pixels(&self) -> &[u8] {
258        let bytes = self.bytes();
259        self.data.get(..bytes).unwrap_or(&self.data)
260    }
261}
262
263impl<M: AlphaMode> Default for Image<M> {
264    fn default() -> Self {
265        Image { size: Size::default(), data: Vec::new(), _mode: PhantomData }
266    }
267}
268
269impl<M: AlphaMode> Clone for Image<M> {
270    fn clone(&self) -> Self {
271        Image { size: self.size, data: self.data.clone(), _mode: PhantomData }
272    }
273}
274
275/// Images are equal when their sizes and pixels are; bytes of `data` past the
276/// pixels don't count.
277impl<M: AlphaMode> PartialEq for Image<M> {
278    fn eq(&self, other: &Self) -> bool {
279        self.size == other.size && self.pixels() == other.pixels()
280    }
281}
282
283impl<M: AlphaMode> Eq for Image<M> {}
284
285impl<M: AlphaMode> fmt::Debug for Image<M> {
286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287        f.debug_struct("Image")
288            .field("mode", &M::MODE)
289            .field("size", &self.size)
290            .field("data.len()", &self.data.len())
291            .finish()
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    // Ports TEST(Image, Resize) from test/util/image.test.cpp.
300    // gtest: Image.Resize
301    #[test]
302    fn resize() {
303        let mut image = AlphaImage::new(Size::new(0, 0));
304
305        image.resize(Size::new(1, 1));
306        assert_eq!(image.size, Size::new(1, 1));
307
308        image.fill(100);
309        image.resize(Size::new(2, 1));
310        assert_eq!(image.size, Size::new(2, 1));
311        assert_eq!(image.data[0], 100);
312        assert_eq!(image.data[1], 0);
313
314        image.resize(Size::new(0, 0));
315        assert_eq!(image.size, Size::new(0, 0));
316    }
317
318    // Ports TEST(Image, Copy) from test/util/image.test.cpp.
319    // gtest: Image.Copy
320    #[test]
321    fn copy() {
322        let src5 = PremultipliedImage::new(Size::new(5, 5));
323        let mut dst5 = PremultipliedImage::new(Size::new(5, 5));
324        let src10 = PremultipliedImage::new(Size::new(10, 10));
325        let mut dst10 = PremultipliedImage::new(Size::new(10, 10));
326        let p = |x, y| Point::new(x, y);
327        let s = Size::new;
328        let out_of_range = |r: Result<(), ImageError>| matches!(r, Err(ImageError::OutsideImage));
329
330        assert!(out_of_range(PremultipliedImage::copy(&src5, &mut dst10, p(0, 0), p(0, 0), s(6, 1))));
331        assert!(out_of_range(PremultipliedImage::copy(&src5, &mut dst10, p(0, 0), p(0, 0), s(1, 6))));
332        assert!(out_of_range(PremultipliedImage::copy(&src5, &mut dst10, p(1, 1), p(0, 0), s(5, 1))));
333        assert!(out_of_range(PremultipliedImage::copy(&src5, &mut dst10, p(1, 1), p(0, 0), s(1, 5))));
334
335        assert!(out_of_range(PremultipliedImage::copy(&src10, &mut dst5, p(0, 0), p(0, 0), s(6, 1))));
336        assert!(out_of_range(PremultipliedImage::copy(&src10, &mut dst5, p(0, 0), p(0, 0), s(1, 6))));
337        assert!(out_of_range(PremultipliedImage::copy(&src10, &mut dst5, p(0, 0), p(1, 1), s(5, 1))));
338        assert!(out_of_range(PremultipliedImage::copy(&src10, &mut dst5, p(0, 0), p(1, 1), s(1, 5))));
339
340        let max = u32::MAX;
341
342        let src10b = src10.clone();
343        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(max, 0), p(0, 0), s(1, 1))));
344        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, max), p(0, 0), s(1, 1))));
345        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, 0), p(max, 0), s(1, 1))));
346        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, 0), p(0, max), s(1, 1))));
347
348        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(1, 0), p(0, 0), s(max, 1))));
349        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, 1), p(0, 0), s(1, max))));
350        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, 0), p(1, 0), s(max, 1))));
351        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, 0), p(0, 1), s(1, max))));
352    }
353
354    // Ports TEST(Image, Move): a Rust move leaves nothing behind to inspect;
355    // `std::mem::take` is the equivalent of the C++ moved-from state.
356    // gtest: Image.Move
357    #[test]
358    fn move_() {
359        let mut rgba = UnassociatedImage::new(Size::new(1, 1));
360        rgba.data.copy_from_slice(&[255, 254, 253, 128]);
361
362        let moved = std::mem::take(&mut rgba);
363
364        assert_eq!(rgba.size.width, 0);
365        assert_eq!(rgba.data, Vec::<u8>::new());
366        assert_eq!(moved.data[1], 254);
367        assert_eq!(moved.size.width, 1);
368    }
369
370    // Not in the C++ suite: the remaining Image members.
371    #[test]
372    fn construct_clear_equality() {
373        let image = PremultipliedImage::new(Size::new(2, 3));
374        assert_eq!((image.bytes(), image.stride()), (24, 8));
375        assert!(image.valid() && image.data.iter().all(|&b| b == 0));
376        assert_eq!(AlphaImage::new(Size::new(2, 3)).bytes(), 6);
377        assert!(!PremultipliedImage::default().valid());
378        assert!(!PremultipliedImage::new(Size::new(0, 3)).valid());
379        assert_eq!(PremultipliedImage::from_slice(Size::new(1, 1), &[1, 2, 3]), Err(ImageError::WrongLength));
380        assert_eq!(PremultipliedImage::from_slice(Size::new(1, 1), &[1, 2, 3, 4]).unwrap().data, vec![1, 2, 3, 4]);
381
382        let mut image = PremultipliedImage::new(Size::new(3, 3));
383        image.fill(7);
384        PremultipliedImage::clear(&mut image, Point::new(1, 1), Size::new(2, 2)).unwrap();
385        assert_eq!(&image.data[0..16], &[7; 16]);
386        assert_eq!(&image.data[16..24], &[0; 8]);
387        assert_eq!(&image.data[24..28], &[7; 4]);
388        assert_eq!(&image.data[28..36], &[0; 8]);
389        assert!(matches!(
390            PremultipliedImage::clear(&mut image, Point::new(2, 2), Size::new(2, 2)),
391            Err(ImageError::OutsideImage)
392        ));
393        let mut empty = PremultipliedImage::default();
394        assert!(matches!(
395            PremultipliedImage::clear(&mut empty, Point::new(0, 0), Size::new(1, 1)),
396            Err(ImageError::NoPixels)
397        ));
398        PremultipliedImage::clear(&mut empty, Point::new(0, 0), Size::new(0, 1)).unwrap();
399
400        let mut src = UnassociatedImage::new(Size::new(4, 4));
401        let mut dst = UnassociatedImage::new(Size::new(4, 4));
402        src.fill(0xFF);
403        UnassociatedImage::copy(&src, &mut dst, Point::new(0, 0), Point::new(1, 1), Size::new(2, 2)).unwrap();
404        for y in 0..4usize {
405            for x in 0..4usize {
406                let inside = (1..3).contains(&x) && (1..3).contains(&y);
407                let px = &dst.data[(y * 4 + x) * 4..(y * 4 + x) * 4 + 4];
408                assert_eq!(px, if inside { &[0xFF; 4] } else { &[0; 4] }, "({x}, {y})");
409            }
410        }
411
412        let a = PremultipliedImage::from_vec(Size::new(1, 1), vec![1, 2, 3, 4]);
413        assert_eq!(a, PremultipliedImage::from_vec(Size::new(1, 1), vec![1, 2, 3, 4]));
414        assert_ne!(a, PremultipliedImage::from_vec(Size::new(1, 1), vec![1, 2, 3, 5]));
415    }
416}