1use std::sync::Arc;
22
23use crate::grid::{GridError, PxRect, TileGrid, rgba_byte_len};
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27#[non_exhaustive]
28pub enum Alpha {
29 Unmultiplied,
32 Premultiplied,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
38#[non_exhaustive]
39pub enum SplitError {
40 #[error("RGBA buffer has {actual} bytes, but the image size needs {expected}")]
42 BufferLength {
43 expected: usize,
45 actual: usize,
47 },
48 #[error("crop rect {rect:?} lies outside the {}x{} image", image_size[0], image_size[1])]
50 RectOutOfBounds {
51 rect: PxRect,
53 image_size: [usize; 2],
55 },
56 #[error(transparent)]
59 Grid(#[from] GridError),
60}
61
62fn check_bounds(rect: PxRect, image_size: [usize; 2]) -> Result<(), SplitError> {
64 let fits = |start: usize, len: usize, limit: usize| start.checked_add(len).is_some_and(|end| end <= limit);
65 if fits(rect.x, rect.width, image_size[0]) && fits(rect.y, rect.height, image_size[1]) {
66 Ok(())
67 } else {
68 Err(SplitError::RectOutOfBounds { rect, image_size })
69 }
70}
71
72fn check_rgba_len(pixels: &[u8], image_size: [usize; 2]) -> Result<(), SplitError> {
74 let expected = rgba_byte_len(image_size).ok_or(GridError::TooLarge { image_size })?;
75 if pixels.len() == expected {
76 Ok(())
77 } else {
78 Err(SplitError::BufferLength { expected, actual: pixels.len() })
79 }
80}
81
82pub fn crop_rgba(pixels: &[u8], image_size: [usize; 2], alpha: Alpha, rect: PxRect) -> Result<egui::ColorImage, SplitError> {
90 check_rgba_len(pixels, image_size)?;
91 check_bounds(rect, image_size)?;
92 Ok(crop_rgba_unchecked(pixels, image_size[0], alpha, rect))
93}
94
95fn crop_rgba_unchecked(pixels: &[u8], row_width: usize, alpha: Alpha, rect: PxRect) -> egui::ColorImage {
98 let convert: fn(&[u8]) -> egui::Color32 = match alpha {
99 Alpha::Unmultiplied => |p| egui::Color32::from_rgba_unmultiplied(p[0], p[1], p[2], p[3]),
100 Alpha::Premultiplied => |p| egui::Color32::from_rgba_premultiplied(p[0], p[1], p[2], p[3]),
101 };
102 let mut out = Vec::with_capacity(rect.width * rect.height);
103 for row in rect.y..rect.y + rect.height {
104 let start = (row * row_width + rect.x) * 4;
105 out.extend(pixels[start..start + rect.width * 4].chunks_exact(4).map(convert));
106 }
107 egui::ColorImage::new([rect.width, rect.height], out)
108}
109
110pub fn crop_color_image(image: &egui::ColorImage, rect: PxRect) -> Result<egui::ColorImage, SplitError> {
116 check_color_image(image)?;
117 check_bounds(rect, image.size)?;
118 Ok(crop_color_image_unchecked(image, rect))
119}
120
121fn check_color_image(image: &egui::ColorImage) -> Result<(), SplitError> {
123 let expected = image.size[0].checked_mul(image.size[1]).ok_or(GridError::TooLarge { image_size: image.size })?;
124 if image.pixels.len() == expected {
125 Ok(())
126 } else {
127 Err(SplitError::BufferLength {
128 expected: expected.saturating_mul(4),
129 actual: image.pixels.len().saturating_mul(4),
130 })
131 }
132}
133
134fn crop_color_image_unchecked(image: &egui::ColorImage, rect: PxRect) -> egui::ColorImage {
136 let row_width = image.size[0];
137 let mut out = Vec::with_capacity(rect.width * rect.height);
138 for row in rect.y..rect.y + rect.height {
139 let start = row * row_width + rect.x;
140 out.extend_from_slice(&image.pixels[start..start + rect.width]);
141 }
142 egui::ColorImage::new([rect.width, rect.height], out)
143}
144
145#[derive(Clone, Debug)]
150pub struct PreparedTiles {
151 grid: TileGrid,
152 tiles: Vec<Arc<egui::ColorImage>>,
153}
154
155impl PreparedTiles {
156 pub fn from_rgba(pixels: &[u8], image_size: [usize; 2], alpha: Alpha, tile_side: usize) -> Result<Self, SplitError> {
162 let grid = TileGrid::new(image_size, tile_side)?;
163 grid.check_materializable()?;
164 check_rgba_len(pixels, image_size)?;
165 let tiles = grid
166 .tiles()
167 .map(|(_, rect)| Arc::new(crop_rgba_unchecked(pixels, image_size[0], alpha, rect)))
168 .collect();
169 Ok(Self { grid, tiles })
170 }
171
172 pub fn from_color_image(image: &egui::ColorImage, tile_side: usize) -> Result<Self, SplitError> {
178 let grid = TileGrid::new(image.size, tile_side)?;
179 grid.check_materializable()?;
180 check_color_image(image)?;
181 let tiles = grid.tiles().map(|(_, rect)| Arc::new(crop_color_image_unchecked(image, rect))).collect();
182 Ok(Self { grid, tiles })
183 }
184
185 #[must_use]
187 pub fn grid(&self) -> &TileGrid {
188 &self.grid
189 }
190
191 #[must_use]
193 pub fn tile(&self, index: usize) -> Option<&Arc<egui::ColorImage>> {
194 self.tiles.get(index)
195 }
196
197 #[must_use]
199 pub fn byte_size(&self) -> usize {
200 self.tiles.iter().map(|t| t.pixels.len().saturating_mul(4)).fold(0, usize::saturating_add)
202 }
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 fn coded_rgba(w: usize, h: usize) -> Vec<u8> {
211 let mut out = Vec::with_capacity(w * h * 4);
212 for y in 0..h {
213 for x in 0..w {
214 out.extend_from_slice(&[u8::try_from(x % 251).unwrap_or(0), u8::try_from(y % 251).unwrap_or(0), 7, 128]);
215 }
216 }
217 out
218 }
219
220 #[test]
221 fn crop_rgba_matches_crop_then_convert() -> Result<(), SplitError> {
222 let (w, h) = (37, 23);
223 let raw = coded_rgba(w, h);
224 let rect = PxRect::new(5, 3, 20, 11);
225 for alpha in [Alpha::Unmultiplied, Alpha::Premultiplied] {
226 let tile = crop_rgba(&raw, [w, h], alpha, rect)?;
227 let mut bytes = Vec::new();
229 for y in rect.y..rect.y + rect.height {
230 bytes.extend_from_slice(&raw[(y * w + rect.x) * 4..(y * w + rect.x + rect.width) * 4]);
231 }
232 let reference = match alpha {
233 Alpha::Unmultiplied => egui::ColorImage::from_rgba_unmultiplied([20, 11], &bytes),
234 Alpha::Premultiplied => egui::ColorImage::from_rgba_premultiplied([20, 11], &bytes),
235 };
236 assert_eq!(tile, reference);
237 }
238 Ok(())
239 }
240
241 #[test]
242 fn premultiplied_and_unmultiplied_differ_for_translucent_pixels() -> Result<(), SplitError> {
243 let raw = [200, 100, 50, 128];
244 let un = crop_rgba(&raw, [1, 1], Alpha::Unmultiplied, PxRect::new(0, 0, 1, 1))?;
245 let pre = crop_rgba(&raw, [1, 1], Alpha::Premultiplied, PxRect::new(0, 0, 1, 1))?;
246 assert_ne!(un.pixels[0], pre.pixels[0]);
247 assert_eq!(pre.pixels[0].to_array(), [200, 100, 50, 128]);
248 Ok(())
249 }
250
251 #[test]
252 fn bad_input_is_an_error_not_a_panic() {
253 let raw = coded_rgba(4, 4);
254 assert_eq!(
255 crop_rgba(&raw[..60], [4, 4], Alpha::Unmultiplied, PxRect::new(0, 0, 1, 1)),
256 Err(SplitError::BufferLength { expected: 64, actual: 60 })
257 );
258 let rect = PxRect::new(3, 0, 2, 1);
259 assert_eq!(
260 crop_rgba(&raw, [4, 4], Alpha::Unmultiplied, rect),
261 Err(SplitError::RectOutOfBounds { rect, image_size: [4, 4] })
262 );
263 let rect = PxRect::new(usize::MAX, 0, 2, 1);
264 assert!(matches!(crop_rgba(&raw, [4, 4], Alpha::Unmultiplied, rect), Err(SplitError::RectOutOfBounds { .. })));
265 assert!(matches!(
266 PreparedTiles::from_rgba(&raw, [4, 4], Alpha::Unmultiplied, 0),
267 Err(SplitError::Grid(GridError::ZeroTileSide))
268 ));
269 let broken = egui::ColorImage { size: [4, 4], source_size: egui::vec2(4.0, 4.0), pixels: vec![egui::Color32::RED; 3] };
270 assert!(matches!(crop_color_image(&broken, PxRect::new(0, 0, 1, 1)), Err(SplitError::BufferLength { .. })));
271 assert!(matches!(PreparedTiles::from_color_image(&broken, 2), Err(SplitError::BufferLength { .. })));
272 let big = vec![0_u8; 2048 * 1024 * 4];
274 assert!(matches!(
275 PreparedTiles::from_rgba(&big, [2048, 1024], Alpha::Unmultiplied, 1),
276 Err(SplitError::Grid(GridError::TooManyTiles { .. }))
277 ));
278 }
279
280 #[test]
281 fn prepared_tiles_cover_the_image() -> Result<(), SplitError> {
282 let (w, h) = (50, 70);
283 let raw = coded_rgba(w, h);
284 let prepared = PreparedTiles::from_rgba(&raw, [w, h], Alpha::Unmultiplied, 32)?;
285 assert_eq!(prepared.grid().len(), 6);
286 assert_eq!(prepared.byte_size(), w * h * 4);
287 for (index, rect) in prepared.grid().tiles() {
288 let tile = prepared.tile(index).ok_or(SplitError::BufferLength { expected: 0, actual: 0 })?;
289 assert_eq!(**tile, crop_rgba(&raw, [w, h], Alpha::Unmultiplied, rect)?);
290 }
291 assert!(prepared.tile(6).is_none());
292
293 let full = egui::ColorImage::from_rgba_premultiplied([w, h], &raw);
294 let from_image = PreparedTiles::from_color_image(&full, 32)?;
295 for (index, rect) in from_image.grid().tiles() {
296 assert_eq!(from_image.tile(index).map(|t| &**t), Some(&crop_rgba(&raw, [w, h], Alpha::Premultiplied, rect)?));
297 }
298 Ok(())
299 }
300
301 #[test]
302 fn empty_image_splits_into_nothing() -> Result<(), SplitError> {
303 let prepared = PreparedTiles::from_rgba(&[], [0, 10], Alpha::Unmultiplied, 16)?;
304 assert!(prepared.grid().is_empty());
305 assert_eq!(prepared.byte_size(), 0);
306 Ok(())
307 }
308}