1use anyhow::{Context as _, Result};
24use std::{
25 borrow::Cow,
26 collections::HashMap,
27 sync::{
28 Arc,
29 atomic::{AtomicBool, AtomicU32, Ordering},
30 },
31};
32
33use crate::fast::layers::scene::LAYER_TILE_TEXTURE_BASE;
34use crate::{
35 AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, DevicePixels, Pixels, PolychromeSprite,
36 TileId, Window, point,
37};
38
39const BYTES_PER_PIXEL: usize = 4;
42
43const DYNAMIC_INDEX_BASE: u32 = 0xE000_0000;
52
53const DYNAMIC_ID_LIMIT: u32 = LAYER_TILE_TEXTURE_BASE - DYNAMIC_INDEX_BASE;
55
56#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
58pub struct DynamicTextureId(u32);
59
60impl DynamicTextureId {
61 pub fn atlas_texture_id(self) -> AtlasTextureId {
65 AtlasTextureId {
66 index: DYNAMIC_INDEX_BASE.wrapping_add(self.0),
67 kind: AtlasTextureKind::Polychrome,
68 }
69 }
70
71 pub fn from_atlas_texture_id(id: AtlasTextureId) -> Option<Self> {
73 (id.kind == AtlasTextureKind::Polychrome
74 && id.index >= DYNAMIC_INDEX_BASE
75 && id.index - DYNAMIC_INDEX_BASE < DYNAMIC_ID_LIMIT)
76 .then(|| Self(id.index - DYNAMIC_INDEX_BASE))
77 }
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct DynamicTexture {
88 id: DynamicTextureId,
89 size: crate::Size<DevicePixels>,
90}
91
92impl DynamicTexture {
93 pub fn id(&self) -> DynamicTextureId {
96 self.id
97 }
98
99 pub fn new_gpu(size: crate::Size<DevicePixels>) -> Result<Self> {
105 anyhow::ensure!(
106 size.width.0 > 0 && size.height.0 > 0,
107 "dynamic texture dimensions must be positive"
108 );
109 allocate(size, TextureSource::Gpu, |_| Ok(()))
110 }
111
112 pub fn remove(self) {
118 remove(self);
119 }
120}
121
122pub trait DynamicTexturePlatform: Send + Sync {
128 fn create_texture(
130 &self,
131 id: DynamicTextureId,
132 size: crate::Size<DevicePixels>,
133 bytes: &[u8],
134 ) -> Result<()>;
135
136 fn update_texture(
143 &self,
144 id: DynamicTextureId,
145 bounds: Bounds<DevicePixels>,
146 bytes: &[u8],
147 ) -> Result<()>;
148
149 fn remove_texture(&self, id: DynamicTextureId);
151}
152
153static PLATFORM: parking_lot::RwLock<Option<Arc<dyn DynamicTexturePlatform>>> =
154 parking_lot::RwLock::new(None);
155
156pub fn set_dynamic_texture_platform(backend: Arc<dyn DynamicTexturePlatform>) {
162 let mut platform = PLATFORM.write();
163 if platform.is_none() {
164 *platform = Some(backend);
165 }
166}
167
168fn platform() -> Result<Arc<dyn DynamicTexturePlatform>> {
169 require_platform(PLATFORM.read().clone())
170}
171
172fn require_platform(
178 platform: Option<Arc<dyn DynamicTexturePlatform>>,
179) -> Result<Arc<dyn DynamicTexturePlatform>> {
180 platform.context("dynamic textures are not supported on this platform")
181}
182
183static NEXT_TEXTURE_ID: AtomicU32 = AtomicU32::new(0);
184
185static IDS_EXHAUSTED: AtomicBool = AtomicBool::new(false);
190
191static LIVE_TEXTURES: parking_lot::Mutex<Option<HashMap<DynamicTextureId, TextureState>>> =
194 parking_lot::Mutex::new(None);
195
196#[derive(Clone, Copy)]
198struct TextureState {
199 size: crate::Size<DevicePixels>,
200 source: TextureSource,
201 version: u32,
206}
207
208#[derive(Clone, Copy, PartialEq, Eq)]
209enum TextureSource {
210 Upload,
211 Gpu,
212}
213
214fn live_textures() -> parking_lot::MappedMutexGuard<'static, HashMap<DynamicTextureId, TextureState>>
215{
216 parking_lot::MutexGuard::map(LIVE_TEXTURES.lock(), |textures| {
217 textures.get_or_insert_with(HashMap::new)
218 })
219}
220
221fn painted_version(id: DynamicTextureId) -> u32 {
225 live_textures()
226 .get(&id)
227 .map_or(1, |state| state.version.max(1))
228}
229
230pub(crate) fn create(
239 size: crate::Size<DevicePixels>,
240 bytes: &[u8],
241 bytes_per_row: u32,
242) -> Result<DynamicTexture> {
243 let width = usize::try_from(size.width.0).context("negative texture width")?;
244 let height = usize::try_from(size.height.0).context("negative texture height")?;
245 anyhow::ensure!(
246 width > 0 && height > 0,
247 "dynamic texture dimensions must be positive"
248 );
249
250 let row_bytes = width
251 .checked_mul(BYTES_PER_PIXEL)
252 .context("dynamic texture row size overflow")?;
253 let stride = usize::try_from(bytes_per_row).context("negative bytes per row")?;
254 anyhow::ensure!(
255 stride >= row_bytes,
256 "dynamic texture stride is smaller than one row"
257 );
258
259 let required = checked_payload_len(height, stride, row_bytes)?;
260 anyhow::ensure!(
261 bytes.len() >= required,
262 "dynamic texture payload is shorter than its dimensions"
263 );
264
265 let packed = pack_rows(bytes, stride, row_bytes, height);
266 let backend = platform()?;
267 allocate(size, TextureSource::Upload, |id| {
268 backend.create_texture(id, size, &packed)
269 })
270}
271
272fn allocate(
275 size: crate::Size<DevicePixels>,
276 source: TextureSource,
277 create: impl FnOnce(DynamicTextureId) -> Result<()>,
278) -> Result<DynamicTexture> {
279 let id = DynamicTextureId(NEXT_TEXTURE_ID.fetch_add(1, Ordering::Relaxed));
280 if IDS_EXHAUSTED.load(Ordering::Relaxed) || id.0 >= DYNAMIC_ID_LIMIT {
285 IDS_EXHAUSTED.store(true, Ordering::Relaxed);
286 anyhow::bail!("dynamic texture ids are exhausted");
287 }
288 create(id).with_context(|| format!("failed to create dynamic texture {id:?}"))?;
289 live_textures().insert(
290 id,
291 TextureState {
292 size,
293 source,
294 version: 1,
295 },
296 );
297
298 Ok(DynamicTexture { id, size })
299}
300
301pub(crate) fn update(
309 texture: DynamicTexture,
310 bounds: Bounds<DevicePixels>,
311 bytes: &[u8],
312 bytes_per_row: u32,
313) -> Result<()> {
314 let state = live_textures()
315 .get(&texture.id)
316 .copied()
317 .context("unknown dynamic texture")?;
318 anyhow::ensure!(
319 state.source == TextureSource::Upload,
320 "GPU-written textures must be updated by their producer"
321 );
322 let packed = validate_region(state.size, bounds, bytes, bytes_per_row)?;
323
324 platform()?
325 .update_texture(texture.id, bounds, &packed)
326 .with_context(|| format!("failed to update dynamic texture {texture:?}"))?;
327 if let Some(state) = live_textures().get_mut(&texture.id) {
328 state.version = state.version.wrapping_add(1).max(1);
329 }
330
331 Ok(())
332}
333
334pub(crate) fn mark_written(texture: DynamicTexture) -> Result<()> {
337 let mut textures = live_textures();
338 let state = textures
339 .get_mut(&texture.id)
340 .context("unknown dynamic texture")?;
341 state.version = state.version.wrapping_add(1).max(1);
342 Ok(())
343}
344
345pub(crate) fn paint(
349 window: &mut Window,
350 bounds: Bounds<Pixels>,
351 texture: DynamicTexture,
352) -> Result<()> {
353 window.invalidator.debug_assert_paint();
354
355 let texture_size = live_size(texture.id)?;
356
357 let tile = AtlasTile {
363 texture_id: texture.id.atlas_texture_id(),
364 tile_id: TileId(texture.id.0),
365 padding: 0,
366 bounds: Bounds {
367 origin: point(DevicePixels(0), DevicePixels(0)),
368 size: texture_size,
369 },
370 };
371 window.next_frame.scene.insert_primitive(PolychromeSprite {
372 order: 0,
373 pad: painted_version(texture.id),
374 grayscale: false.into(),
375 bounds: window.snap_bounds(bounds),
376 content_mask: window.snapped_content_mask(),
377 corner_radii: Default::default(),
378 tile,
379 opacity: window.element_opacity(),
380 });
381
382 Ok(())
383}
384
385pub(crate) fn remove(texture: DynamicTexture) {
387 let state = live_textures().remove(&texture.id);
388 if state.is_some_and(|state| state.source == TextureSource::Upload)
389 && let Ok(backend) = platform()
390 {
391 backend.remove_texture(texture.id);
392 }
393}
394
395impl Window {
396 pub fn create_dynamic_texture(
406 &mut self,
407 size: crate::Size<DevicePixels>,
408 bytes: &[u8],
409 bytes_per_row: u32,
410 ) -> Result<DynamicTexture> {
411 create(size, bytes, bytes_per_row)
412 }
413
414 pub fn update_dynamic_texture(
432 &mut self,
433 texture: DynamicTexture,
434 bounds: Bounds<DevicePixels>,
435 bytes: &[u8],
436 bytes_per_row: u32,
437 ) -> Result<()> {
438 update(texture, bounds, bytes, bytes_per_row)?;
439 self.refresh();
440 Ok(())
441 }
442
443 pub fn refresh_dynamic_texture(&mut self, texture: DynamicTexture) -> Result<()> {
450 mark_written(texture)?;
451 self.refresh();
452 Ok(())
453 }
454
455 pub fn paint_dynamic_texture(
460 &mut self,
461 bounds: Bounds<Pixels>,
462 texture: DynamicTexture,
463 ) -> Result<()> {
464 paint(self, bounds, texture)
465 }
466
467 pub fn remove_dynamic_texture(&mut self, texture: DynamicTexture) {
469 remove(texture);
470 }
471}
472
473fn live_size(id: DynamicTextureId) -> Result<crate::Size<DevicePixels>> {
475 live_textures()
476 .get(&id)
477 .map(|state| state.size)
478 .context("unknown dynamic texture")
479}
480
481fn validate_region<'a>(
484 texture_size: crate::Size<DevicePixels>,
485 bounds: Bounds<DevicePixels>,
486 bytes: &'a [u8],
487 bytes_per_row: u32,
488) -> Result<Cow<'a, [u8]>> {
489 let (origin_x, origin_y) = (bounds.origin.x.0 as i64, bounds.origin.y.0 as i64);
492 let (width, height) = (bounds.size.width.0 as i64, bounds.size.height.0 as i64);
493 anyhow::ensure!(
494 origin_x >= 0
495 && origin_y >= 0
496 && width > 0
497 && height > 0
498 && origin_x + width <= texture_size.width.0 as i64
499 && origin_y + height <= texture_size.height.0 as i64,
500 "dynamic texture update is outside the texture"
501 );
502
503 let (width, height) = (width as usize, height as usize);
506 let row_bytes = width
507 .checked_mul(BYTES_PER_PIXEL)
508 .context("dynamic texture region row size overflow")?;
509 let stride = usize::try_from(bytes_per_row).context("negative bytes per row")?;
510 anyhow::ensure!(
511 stride >= row_bytes,
512 "dynamic texture stride is smaller than one row"
513 );
514
515 let required = checked_payload_len(height, stride, row_bytes)?;
516 anyhow::ensure!(
517 bytes.len() >= required,
518 "dynamic texture update is shorter than the region"
519 );
520
521 Ok(pack_rows(bytes, stride, row_bytes, height))
522}
523
524fn checked_payload_len(height: usize, stride: usize, row_bytes: usize) -> Result<usize> {
527 (height - 1)
528 .checked_mul(stride)
529 .and_then(|length| length.checked_add(row_bytes))
530 .context("dynamic texture payload size overflow")
531}
532
533fn pack_rows(bytes: &[u8], stride: usize, row_bytes: usize, height: usize) -> Cow<'_, [u8]> {
536 if stride == row_bytes || height <= 1 {
537 return Cow::Borrowed(&bytes[..row_bytes * height]);
538 }
539 let mut packed = Vec::with_capacity(row_bytes * height);
540 for row in 0..height {
541 let start = row * stride;
542 packed.extend_from_slice(&bytes[start..start + row_bytes]);
543 }
544 Cow::Owned(packed)
545}
546
547#[cfg(test)]
548mod tests {
549 use super::{
550 BYTES_PER_PIXEL, DYNAMIC_INDEX_BASE, DynamicTexture, DynamicTextureId,
551 DynamicTexturePlatform, create, live_size, mark_written, pack_rows, painted_version,
552 remove, set_dynamic_texture_platform, update, validate_region,
553 };
554 use crate::{
555 AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, ContentMask, DevicePixels,
556 PolychromeSprite, ScaledPixels, Scene, TileId, point, size,
557 };
558 use anyhow::Result;
559 use std::{
560 borrow::Cow,
561 sync::{
562 Arc,
563 atomic::{AtomicBool, AtomicUsize, Ordering},
564 },
565 };
566
567 struct MockPlatform {
572 created: parking_lot::Mutex<Vec<(DynamicTextureId, crate::Size<DevicePixels>, usize)>>,
573 updated: parking_lot::Mutex<Vec<(DynamicTextureId, Bounds<DevicePixels>, usize)>>,
574 removed: parking_lot::Mutex<Vec<DynamicTextureId>>,
575 last_bytes_ptr: AtomicUsize,
576 fail_updates: AtomicBool,
577 }
578
579 impl DynamicTexturePlatform for MockPlatform {
580 fn create_texture(
581 &self,
582 id: DynamicTextureId,
583 size: crate::Size<DevicePixels>,
584 bytes: &[u8],
585 ) -> Result<()> {
586 self.last_bytes_ptr
587 .store(bytes.as_ptr() as usize, Ordering::SeqCst);
588 self.created.lock().push((id, size, bytes.len()));
589 Ok(())
590 }
591
592 fn update_texture(
593 &self,
594 id: DynamicTextureId,
595 bounds: Bounds<DevicePixels>,
596 bytes: &[u8],
597 ) -> Result<()> {
598 if self.fail_updates.load(Ordering::SeqCst) {
599 anyhow::bail!("backend refused the update");
600 }
601 self.last_bytes_ptr
602 .store(bytes.as_ptr() as usize, Ordering::SeqCst);
603 self.updated.lock().push((id, bounds, bytes.len()));
604 Ok(())
605 }
606
607 fn remove_texture(&self, id: DynamicTextureId) {
608 self.removed.lock().push(id);
609 }
610 }
611
612 static MOCK_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
614
615 fn shared_mock() -> &'static Arc<MockPlatform> {
617 static MOCK: std::sync::OnceLock<Arc<MockPlatform>> = std::sync::OnceLock::new();
618 MOCK.get_or_init(|| {
619 let mock = Arc::new(MockPlatform {
620 created: parking_lot::Mutex::new(Vec::new()),
621 updated: parking_lot::Mutex::new(Vec::new()),
622 removed: parking_lot::Mutex::new(Vec::new()),
623 last_bytes_ptr: AtomicUsize::new(0),
624 fail_updates: AtomicBool::new(false),
625 });
626 set_dynamic_texture_platform(mock.clone());
627 mock
628 })
629 }
630
631 fn fresh_mock() -> (parking_lot::MutexGuard<'static, ()>, Arc<MockPlatform>) {
633 let lock = MOCK_LOCK.lock();
634 let mock = shared_mock();
635 mock.created.lock().clear();
636 mock.updated.lock().clear();
637 mock.removed.lock().clear();
638 mock.last_bytes_ptr.store(0, Ordering::SeqCst);
639 mock.fail_updates.store(false, Ordering::SeqCst);
640 (lock, mock.clone())
641 }
642
643 fn size_of(width: i32, height: i32) -> crate::Size<DevicePixels> {
644 size(DevicePixels(width), DevicePixels(height))
645 }
646
647 fn bounds_at(origin: (i32, i32), width: i32, height: i32) -> Bounds<DevicePixels> {
648 Bounds {
649 origin: point(DevicePixels(origin.0), DevicePixels(origin.1)),
650 size: size(DevicePixels(width), DevicePixels(height)),
651 }
652 }
653
654 fn packed_bytes(width: i32, height: i32) -> Vec<u8> {
656 vec![0u8; width as usize * height as usize * BYTES_PER_PIXEL]
657 }
658
659 #[test]
660 fn create_reports_missing_platform() {
661 let error = super::require_platform(None)
665 .err()
666 .expect("a missing backend is an error");
667 assert_eq!(
668 error.to_string(),
669 "dynamic textures are not supported on this platform"
670 );
671 }
672
673 #[test]
674 fn create_requires_every_row_and_ignores_trailing_bytes() {
675 let (_lock, mock) = fresh_mock();
676
677 let short = create(size_of(4, 4), &packed_bytes(4, 4)[..63], 16);
678 assert!(short.is_err(), "one byte short must be refused");
679
680 let _padded = create(size_of(4, 4), &[0u8; 4 * 16], 16).expect("created");
683 {
684 let created = mock.created.lock();
685 assert_eq!(created.last().expect("created").2, 4 * 4 * BYTES_PER_PIXEL);
686 }
687
688 let empty = create(size_of(4, 4), &[], 16);
689 assert!(empty.is_err());
690
691 let zero = create(size_of(0, 4), &[], 0);
692 assert!(zero.is_err(), "zero width must be refused");
693 }
694
695 #[test]
696 fn create_rejects_a_stride_smaller_than_a_row() {
697 let (_lock, _mock) = fresh_mock();
698
699 let result = create(
700 size_of(4, 4),
701 &packed_bytes(4, 4),
702 3 * BYTES_PER_PIXEL as u32,
703 );
704 assert!(result.is_err());
705 }
706
707 #[test]
708 fn create_packs_rows_and_allocates_distinct_ids() {
709 let (_lock, mock) = fresh_mock();
710
711 let stride = (4 * BYTES_PER_PIXEL + 2) as u32;
715 let mut strided = vec![0u8; stride as usize + 4 * BYTES_PER_PIXEL];
716 for byte in strided.iter_mut().step_by(stride as usize) {
717 *byte = 0xFF;
718 }
719
720 let texture = create(size_of(4, 2), &strided, stride).expect("created");
721 {
722 let created = mock.created.lock();
723 let (created_id, created_size, packed_len) =
724 created.last().expect("create reached the platform");
725 assert_eq!(*created_id, texture.id);
726 assert_eq!(*created_size, texture.size);
727 assert_eq!(
728 *packed_len,
729 4 * 2 * BYTES_PER_PIXEL,
730 "rows must arrive tightly packed"
731 );
732 }
733
734 let other = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created again");
737 assert_ne!(texture.id, other.id, "ids must not repeat");
738 }
739
740 #[test]
741 fn update_validates_the_region_against_the_created_size() {
742 let (_lock, mock) = fresh_mock();
743
744 let texture_size = size_of(8, 8);
745 let texture = create(texture_size, &packed_bytes(8, 8), 32).expect("created");
746
747 let inside = bounds_at((0, 0), 4, 4);
748 let inside_bytes = packed_bytes(4, 4);
749 let packed = validate_region(texture_size, inside, &inside_bytes, 16)
750 .expect("a region inside the texture is accepted");
751 assert_eq!(packed.len(), 4 * 4 * BYTES_PER_PIXEL);
752
753 let offset = bounds_at((4, 4), 4, 4);
754 assert!(validate_region(texture_size, offset, &packed_bytes(4, 4), 16).is_ok());
755
756 let too_wide = bounds_at((0, 0), 9, 4);
757 assert!(
758 validate_region(texture_size, too_wide, &packed_bytes(9, 4), 36).is_err(),
759 "a region past the texture must be refused"
760 );
761
762 let negative = bounds_at((-1, 0), 4, 4);
763 assert!(validate_region(texture_size, negative, &packed_bytes(4, 4), 16).is_err());
764
765 let empty = bounds_at((0, 0), 0, 4);
766 assert!(validate_region(texture_size, empty, &[], 0).is_err());
767
768 let unknown = DynamicTexture {
769 id: DynamicTextureId(u32::MAX),
770 size: texture_size,
771 };
772 assert!(
773 live_size(unknown.id).is_err(),
774 "an unknown id must be refused"
775 );
776
777 remove(texture);
778 assert!(
779 live_size(texture.id).is_err(),
780 "a removed texture must be refused"
781 );
782 assert_eq!(mock.created.lock().len(), 1);
783 assert_eq!(mock.updated.lock().len(), 0);
784 assert_eq!(mock.removed.lock().len(), 1);
785 }
786
787 #[test]
788 fn update_requires_a_full_final_row() {
789 let (_lock, _mock) = fresh_mock();
790
791 let texture_size = size_of(8, 8);
792 let bounds = bounds_at((0, 0), 4, 4);
793 let row_bytes = 4 * BYTES_PER_PIXEL;
794
795 let short_by_one = &packed_bytes(4, 4)[..4 * row_bytes - 1];
796 assert!(
797 validate_region(texture_size, bounds, short_by_one, row_bytes as u32).is_err(),
798 "a final row missing bytes must be refused"
799 );
800 }
801
802 #[test]
803 fn remove_releases_the_texture_once() {
804 let (_lock, mock) = fresh_mock();
805
806 let texture = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
807 remove(texture);
808 remove(texture);
809
810 assert_eq!(
811 mock.removed.lock().len(),
812 1,
813 "the platform sees one removal"
814 );
815 }
816
817 #[test]
818 fn a_failing_backend_leaves_no_stale_state() {
819 let (_lock, mock) = fresh_mock();
820 mock.fail_updates.store(true, Ordering::SeqCst);
821
822 let texture = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
823 let version = painted_version(texture.id);
824 let result = update(texture, bounds_at((0, 0), 2, 2), &packed_bytes(2, 2), 8);
825 assert!(result.is_err(), "the backend's error must propagate");
826 assert!(
827 live_size(texture.id).is_ok(),
828 "the texture stays live for the next attempt"
829 );
830 assert_eq!(
831 painted_version(texture.id),
832 version,
833 "a refused update must not advance the version the next paint carries"
834 );
835 }
836
837 #[test]
838 fn atlas_ids_stay_out_of_the_atlas_range() {
839 let id = DynamicTextureId(0);
840 let atlas_id = id.atlas_texture_id();
841 assert_eq!(
842 DynamicTextureId::from_atlas_texture_id(atlas_id),
843 Some(id),
844 "the mapping must round-trip"
845 );
846
847 let atlas_id = AtlasTextureId {
848 index: 7,
849 kind: AtlasTextureKind::Polychrome,
850 };
851 assert_eq!(DynamicTextureId::from_atlas_texture_id(atlas_id), None);
852
853 let atlas_id = AtlasTextureId {
854 index: DYNAMIC_INDEX_BASE,
855 kind: AtlasTextureKind::Monochrome,
856 };
857 assert_eq!(
858 DynamicTextureId::from_atlas_texture_id(atlas_id),
859 None,
860 "a dynamic range index in another kind must not match"
861 );
862 }
863
864 fn scene_with_texture(texture: DynamicTexture, pad: u32) -> Scene {
868 let mut scene = Scene::default();
869 scene.insert_primitive(PolychromeSprite {
870 order: 0,
871 pad,
872 tile: AtlasTile {
873 texture_id: texture.id.atlas_texture_id(),
874 tile_id: TileId(texture.id.0),
875 padding: 0,
876 bounds: Bounds {
877 origin: point(DevicePixels(0), DevicePixels(0)),
878 size: texture.size,
879 },
880 },
881 grayscale: false.into(),
882 opacity: 1.,
883 bounds: Bounds {
884 origin: point(ScaledPixels(0.), ScaledPixels(0.)),
885 size: size(ScaledPixels(64.), ScaledPixels(64.)),
886 },
887 content_mask: ContentMask {
888 bounds: Bounds {
889 origin: point(ScaledPixels(0.), ScaledPixels(0.)),
890 size: size(ScaledPixels(128.), ScaledPixels(128.)),
891 },
892 },
893 corner_radii: Default::default(),
894 });
895 scene
896 }
897
898 #[test]
899 fn repainting_an_updated_texture_dirties_its_tiles() {
900 let (_lock, _mock) = fresh_mock();
901
902 let texture = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
903 let region = Bounds {
904 origin: point(ScaledPixels(0.), ScaledPixels(0.)),
905 size: size(ScaledPixels(128.), ScaledPixels(128.)),
906 };
907
908 let before = crate::fast::layers::tiles::tile_hashes(
909 &scene_with_texture(texture, painted_version(texture.id)),
910 64,
911 region,
912 );
913
914 update(texture, bounds_at((0, 0), 2, 2), &packed_bytes(2, 2), 8).expect("updated");
917
918 let after = crate::fast::layers::tiles::tile_hashes(
919 &scene_with_texture(texture, painted_version(texture.id)),
920 64,
921 region,
922 );
923 assert_ne!(before, after, "tiles showing the texture must be dirtied");
924
925 let other = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
928 let unchanged = crate::fast::layers::tiles::tile_hashes(
929 &scene_with_texture(other, painted_version(other.id)),
930 64,
931 region,
932 );
933 assert_eq!(
934 crate::fast::layers::tiles::tile_hashes(
935 &scene_with_texture(other, painted_version(other.id)),
936 64,
937 region,
938 ),
939 unchanged,
940 );
941 }
942
943 #[test]
944 fn gpu_metadata_never_calls_the_upload_platform() {
945 let (_lock, mock) = fresh_mock();
946 assert!(DynamicTexture::new_gpu(size_of(0, 4)).is_err());
947 let texture = DynamicTexture::new_gpu(size_of(4, 4)).expect("GPU metadata");
948 assert!(mock.created.lock().is_empty());
949 let version = painted_version(texture.id);
950 mark_written(texture).expect("recorded GPU write");
951 assert_ne!(painted_version(texture.id), version);
952 assert!(update(texture, bounds_at((0, 0), 4, 4), &packed_bytes(4, 4), 16).is_err());
953 texture.remove();
954 assert!(mock.updated.lock().is_empty());
955 assert!(mock.removed.lock().is_empty());
956 assert!(mark_written(texture).is_err());
957 }
958
959 #[test]
960 fn tight_and_single_row_uploads_borrow_caller_slice_without_repacking() {
961 let (_lock, mock) = fresh_mock();
962
963 let mut tight = vec![0xAB; 4 * 4 * BYTES_PER_PIXEL + 12];
965 tight[0] = 0x11;
966 let texture = create(size_of(4, 4), &tight, 16).expect("created");
967 assert_eq!(
968 mock.last_bytes_ptr.load(Ordering::SeqCst),
969 tight.as_ptr() as usize,
970 "tightly packed create must forward the caller slice without copying"
971 );
972 assert_eq!(
973 mock.created.lock().last().unwrap().2,
974 4 * 4 * BYTES_PER_PIXEL
975 );
976
977 let single_row_padded = [0xCDu8; 24];
979 update(texture, bounds_at((0, 0), 4, 1), &single_row_padded, 24).expect("updated");
980 assert_eq!(
981 mock.last_bytes_ptr.load(Ordering::SeqCst),
982 single_row_padded.as_ptr() as usize,
983 "single-row update must borrow the visible prefix without copying"
984 );
985 assert_eq!(mock.updated.lock().last().unwrap().2, 4 * BYTES_PER_PIXEL);
986
987 let strided = [1, 2, 3, 4, 0xEE, 0xEE, 5, 6, 7, 8];
989 let repacked = pack_rows(&strided, 6, 4, 2);
990 assert!(matches!(repacked, Cow::Owned(_)));
991 assert_eq!(&*repacked, &[1, 2, 3, 4, 5, 6, 7, 8]);
992
993 remove(texture);
994 }
995}