1use alloc::{vec, vec::Vec};
44
45use crate::{
46 canvas::{Canvas, Error},
47 format::{Format, Packed},
48 geom::{Dims, Rect, RectSet, DEFAULT_SET_CAPACITY},
49 ops::{PixelOps, ScalarOps},
50 view::{Source, View},
51};
52
53pub struct OwnedSurface<O: PixelOps = ScalarOps> {
60 words: Vec<u32>,
61 dims: Dims,
62 format: Format,
63 ops: O,
64 dirty: RectSet<DEFAULT_SET_CAPACITY>,
65 track_dirty: bool,
66}
67
68impl<O: PixelOps> core::fmt::Debug for OwnedSurface<O> {
69 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
70 f.debug_struct("OwnedSurface")
71 .field("dims", &self.dims)
72 .field("format", &self.format)
73 .field("dirty", &self.dirty)
74 .field("track_dirty", &self.track_dirty)
75 .finish_non_exhaustive()
76 }
77}
78
79impl<O: PixelOps + Copy> OwnedSurface<O> {
80 pub fn with_ops(dims: Dims, format: Format, ops: O) -> Result<Self, Error> {
86 if dims.is_empty() {
87 return Err(Error::EmptySurface);
88 }
89 if format.bits_per_pixel() != 32 {
90 return Err(Error::UnsupportedFormat {
91 bits_per_pixel: format.bits_per_pixel(),
92 });
93 }
94 if !format.is_valid() {
95 return Err(Error::InvalidFormat);
96 }
97 let area = (dims.w as usize)
98 .checked_mul(dims.h as usize)
99 .ok_or(Error::Overflow)?;
100 Ok(Self {
101 words: vec![0u32; area],
102 dims,
103 format,
104 ops,
105 dirty: RectSet::empty(),
106 track_dirty: true,
107 })
108 }
109
110 pub fn from_words(words: Vec<u32>, dims: Dims, format: Format, ops: O) -> Result<Self, Error> {
115 if dims.is_empty() {
116 return Err(Error::EmptySurface);
117 }
118 if format.bits_per_pixel() != 32 {
119 return Err(Error::UnsupportedFormat {
120 bits_per_pixel: format.bits_per_pixel(),
121 });
122 }
123 if !format.is_valid() {
124 return Err(Error::InvalidFormat);
125 }
126 let area = (dims.w as usize)
127 .checked_mul(dims.h as usize)
128 .ok_or(Error::Overflow)?;
129 if words.len() < area {
130 return Err(Error::BufferTooSmall {
131 len: words.len() * 4,
132 required: area * 4,
133 });
134 }
135 Ok(Self {
136 words,
137 dims,
138 format,
139 ops,
140 dirty: RectSet::empty(),
141 track_dirty: true,
142 })
143 }
144
145 #[inline]
146 pub fn dims(&self) -> Dims {
147 self.dims
148 }
149
150 #[inline]
151 pub fn format(&self) -> Format {
152 self.format
153 }
154
155 #[inline]
157 pub fn pitch(&self) -> usize {
158 self.dims.w as usize * 4
159 }
160
161 #[inline]
162 pub fn bounds(&self) -> Rect {
163 Rect::new(0, 0, self.dims.w, self.dims.h)
164 }
165
166 #[inline]
169 pub fn words(&self) -> &[u32] {
170 &self.words
171 }
172
173 #[inline]
175 pub fn words_mut(&mut self) -> &mut [u32] {
176 &mut self.words
177 }
178
179 #[inline]
181 pub fn mark_dirty(&mut self, rect: Rect) {
182 if self.track_dirty {
183 self.dirty.include(rect);
184 }
185 }
186
187 #[inline]
188 pub fn dirty(&self) -> &RectSet<DEFAULT_SET_CAPACITY> {
189 &self.dirty
190 }
191
192 #[inline]
193 pub fn take_dirty(&mut self) -> RectSet<DEFAULT_SET_CAPACITY> {
194 core::mem::take(&mut self.dirty)
195 }
196
197 #[inline]
198 pub fn clear_dirty(&mut self) {
199 self.dirty.clear();
200 }
201
202 #[inline]
203 pub fn set_tracking(&mut self, on: bool) {
204 self.track_dirty = on;
205 if !on {
206 self.dirty.clear();
207 }
208 }
209
210 fn canvas(&mut self) -> Canvas<'_, O> {
215 let len = self.words.len() * 4;
216 let bytes =
219 unsafe { core::slice::from_raw_parts_mut(self.words.as_mut_ptr() as *mut u8, len) };
220 Canvas::with_ops(bytes, self.dims, self.pitch(), self.format, self.ops)
221 .expect("an owned surface is always a valid canvas")
222 }
223
224 pub fn view(&self) -> View<'_> {
226 let len = self.words.len() * 4;
227 let bytes = unsafe { core::slice::from_raw_parts(self.words.as_ptr() as *const u8, len) };
229 View::new(bytes, self.dims, self.pitch(), self.format)
230 .expect("an owned surface is always a valid view")
231 }
232
233 pub fn draw<T>(&mut self, f: impl FnOnce(&mut Canvas<'_, O>) -> T) -> T {
238 let tracking = self.track_dirty;
239 let (out, damage) = {
242 let mut canvas = self.canvas();
243 canvas.set_tracking(tracking);
244 let out = f(&mut canvas);
245 (out, canvas.take_dirty())
246 };
247 if tracking {
248 self.dirty.include_set(&damage);
249 }
250 out
251 }
252
253 pub fn fill_rect(&mut self, rect: Rect, color: Packed) -> Option<Rect> {
254 self.draw(|canvas| canvas.fill_rect(rect, color))
255 }
256
257 pub fn fill(&mut self, color: Packed) -> Rect {
258 let bounds = self.bounds();
259 self.fill_rect(bounds, color).unwrap_or(Rect::EMPTY)
260 }
261
262 pub fn blit<S: Source + ?Sized>(
263 &mut self,
264 dst: Rect,
265 src: &S,
266 src_rect: Rect,
267 ) -> Result<Option<Rect>, Error> {
268 self.draw(|canvas| canvas.blit(dst, src, src_rect))
269 }
270
271 pub fn blend_rect<S: Source + ?Sized>(
272 &mut self,
273 dst: Rect,
274 src: &S,
275 src_rect: Rect,
276 alpha: u8,
277 ) -> Result<Option<Rect>, Error> {
278 self.draw(|canvas| canvas.blend_rect(dst, src, src_rect, alpha))
279 }
280
281 pub fn convert_from<S: Source + ?Sized>(
282 &mut self,
283 dst: Rect,
284 src: &S,
285 src_rect: Rect,
286 ) -> Result<Option<Rect>, Error> {
287 self.draw(|canvas| canvas.convert_from(dst, src, src_rect))
288 }
289
290 pub fn read_pixel(&self, x: u32, y: u32) -> Option<Packed> {
291 self.view().read_pixel(x, y)
292 }
293
294 pub fn write_pixel(&mut self, x: u32, y: u32, pixel: Packed) -> bool {
295 self.draw(|canvas| canvas.write_pixel(x, y, pixel))
296 }
297}
298
299impl OwnedSurface<ScalarOps> {
300 pub fn new(dims: Dims, format: Format) -> Result<Self, Error> {
302 Self::with_ops(dims, format, ScalarOps)
303 }
304}
305
306unsafe impl<O: PixelOps> Source for OwnedSurface<O> {
309 #[inline]
310 fn dims(&self) -> Dims {
311 self.dims
312 }
313
314 #[inline]
315 fn format(&self) -> Format {
316 self.format
317 }
318
319 #[inline]
320 fn pitch(&self) -> usize {
321 self.dims.w as usize * 4
322 }
323
324 #[inline]
325 unsafe fn row_ptr(&self, y: u32) -> *const u8 {
326 unsafe {
329 self.words
330 .as_ptr()
331 .cast::<u8>()
332 .add(y as usize * (self.dims.w as usize * 4))
333 }
334 }
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340 use crate::format::Rgb;
341
342 #[test]
343 fn damage_survives_across_drawing_calls() {
344 let mut back = OwnedSurface::new(Dims::new(8, 8), Format::XRGB8888).unwrap();
345 back.fill_rect(Rect::new(0, 0, 2, 2), Format::XRGB8888.white());
346 back.fill_rect(Rect::new(4, 4, 2, 2), Format::XRGB8888.white());
347 assert_eq!(back.dirty().len(), 2);
348 assert_eq!(back.dirty().total_area(), 8);
349 }
350
351 #[test]
352 fn drawing_goes_through_the_canvas() {
353 let mut back = OwnedSurface::new(Dims::new(4, 4), Format::XRGB8888).unwrap();
354 back.fill_rect(Rect::new(1, 1, 2, 2), Format::XRGB8888.rgb(1, 2, 3));
355 assert_eq!(
356 Format::XRGB8888.unpack(Packed::raw(back.words()[4 + 1])),
357 Rgb::new(1, 2, 3)
358 );
359 assert_eq!(back.words()[0], 0);
360 }
361
362 #[test]
363 fn two_owned_surfaces_copy_between_each_other() {
364 let mut src = OwnedSurface::new(Dims::new(4, 4), Format::XRGB8888).unwrap();
365 let mut dst = OwnedSurface::new(Dims::new(8, 8), Format::XRGB8888).unwrap();
366 src.fill(Format::XRGB8888.white());
367 let written = dst
368 .blit(Rect::new(2, 2, 4, 4), &src, Rect::new(0, 0, 4, 4))
369 .unwrap();
370 assert_eq!(written, Some(Rect::new(2, 2, 4, 4)));
371 assert_eq!(dst.words()[2 * 8 + 2], 0xFFFF_FFFF);
372 assert_eq!(dst.words()[8 + 1], 0);
373 assert_eq!(dst.dirty().bounds(), Rect::new(2, 2, 4, 4));
374 }
375
376 #[test]
377 fn full_frame_blit_uses_the_contiguous_path() {
378 let mut src = OwnedSurface::new(Dims::new(8, 8), Format::XRGB8888).unwrap();
379 let mut dst = OwnedSurface::new(Dims::new(8, 8), Format::XRGB8888).unwrap();
380 for y in 0..8 {
381 for x in 0..8 {
382 src.write_pixel(x, y, Format::XRGB8888.rgb(x as u8, y as u8, 0x5A));
383 }
384 }
385 let written = dst
386 .blit(Rect::new(0, 0, 8, 8), &src, Rect::new(0, 0, 8, 8))
387 .unwrap();
388 assert_eq!(written, Some(Rect::new(0, 0, 8, 8)));
389 assert_eq!(dst.words(), src.words());
390 }
391
392 #[test]
393 fn owned_surface_converts_to_24bpp_view() {
394 let mut src = [0u8; 8 * 8 * 3];
397 src[0..3].copy_from_slice(&[0x30, 0x20, 0x10]);
398 let view = View::new(&src, Dims::new(8, 8), 8 * 3, Format::RGB888).unwrap();
399 let mut dst = OwnedSurface::new(Dims::new(8, 8), Format::XRGB8888).unwrap();
400 dst.convert_from(Rect::new(0, 0, 1, 1), &view, Rect::new(0, 0, 1, 1))
401 .unwrap();
402 assert_eq!(
403 Format::XRGB8888.unpack(Packed::raw(dst.words()[0])),
404 Rgb::new(0x10, 0x20, 0x30)
405 );
406 }
407
408 #[test]
409 fn raw_words_must_be_marked_manually() {
410 let mut back = OwnedSurface::new(Dims::new(2, 2), Format::XRGB8888).unwrap();
411 back.words_mut()[0] = 0xFFFF_FFFF;
412 assert!(back.dirty().is_empty());
413 back.mark_dirty(Rect::new(0, 0, 1, 1));
414 assert_eq!(back.dirty().len(), 1);
415 }
416
417 #[test]
418 fn constructor_rejects_bad_input() {
419 assert!(OwnedSurface::new(Dims::ZERO, Format::XRGB8888).is_err());
420 assert!(OwnedSurface::new(Dims::new(2, 2), Format::RGB888).is_err());
421 assert!(OwnedSurface::from_words(
422 alloc::vec![0u32; 2],
423 Dims::new(2, 2),
424 Format::XRGB8888,
425 ScalarOps
426 )
427 .is_err());
428 }
429}