1use anyhow::{Context as _, Result};
24use collections::FxHashMap;
25use std::{
26 borrow::Cow,
27 collections::HashMap,
28 sync::{
29 Arc,
30 atomic::{AtomicBool, AtomicU32, Ordering},
31 },
32};
33
34use crate::fast::layers::{Layer, scene::LAYER_TILE_TEXTURE_BASE};
35use crate::scene::{PaintOperation, Primitive};
36use crate::{
37 AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, DevicePixels, GlobalElementId, Pixels,
38 PolychromeSprite, Scene, TileId, Window, point,
39};
40
41const BYTES_PER_PIXEL: usize = 4;
44
45const DYNAMIC_INDEX_BASE: u32 = 0xE000_0000;
54
55const DYNAMIC_ID_LIMIT: u32 = LAYER_TILE_TEXTURE_BASE - DYNAMIC_INDEX_BASE;
57
58#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
60pub struct DynamicTextureId(u32);
61
62impl DynamicTextureId {
63 pub fn atlas_texture_id(self) -> AtlasTextureId {
67 AtlasTextureId {
68 index: DYNAMIC_INDEX_BASE.wrapping_add(self.0),
69 kind: AtlasTextureKind::Polychrome,
70 }
71 }
72
73 pub fn from_atlas_texture_id(id: AtlasTextureId) -> Option<Self> {
75 (id.kind == AtlasTextureKind::Polychrome
76 && id.index >= DYNAMIC_INDEX_BASE
77 && id.index - DYNAMIC_INDEX_BASE < DYNAMIC_ID_LIMIT)
78 .then(|| Self(id.index - DYNAMIC_INDEX_BASE))
79 }
80}
81
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub struct DynamicTexture {
90 id: DynamicTextureId,
91 size: crate::Size<DevicePixels>,
92}
93
94impl DynamicTexture {
95 pub fn id(&self) -> DynamicTextureId {
98 self.id
99 }
100
101 pub fn new_gpu(size: crate::Size<DevicePixels>) -> Result<Self> {
107 anyhow::ensure!(
108 size.width.0 > 0 && size.height.0 > 0,
109 "dynamic texture dimensions must be positive"
110 );
111 allocate(size, TextureSource::Gpu, |_| Ok(()))
112 }
113
114 pub fn remove(self) {
120 remove(self);
121 }
122}
123
124pub trait DynamicTexturePlatform: Send + Sync {
130 fn create_texture(
132 &self,
133 id: DynamicTextureId,
134 size: crate::Size<DevicePixels>,
135 bytes: &[u8],
136 ) -> Result<()>;
137
138 fn update_texture(
145 &self,
146 id: DynamicTextureId,
147 bounds: Bounds<DevicePixels>,
148 bytes: &[u8],
149 ) -> Result<()>;
150
151 fn remove_texture(&self, id: DynamicTextureId);
153}
154
155static PLATFORM: parking_lot::RwLock<Option<Arc<dyn DynamicTexturePlatform>>> =
156 parking_lot::RwLock::new(None);
157
158pub fn set_dynamic_texture_platform(backend: Arc<dyn DynamicTexturePlatform>) {
164 let mut platform = PLATFORM.write();
165 if platform.is_none() {
166 *platform = Some(backend);
167 }
168}
169
170fn platform() -> Result<Arc<dyn DynamicTexturePlatform>> {
171 require_platform(PLATFORM.read().clone())
172}
173
174fn require_platform(
180 platform: Option<Arc<dyn DynamicTexturePlatform>>,
181) -> Result<Arc<dyn DynamicTexturePlatform>> {
182 platform.context("dynamic textures are not supported on this platform")
183}
184
185static NEXT_TEXTURE_ID: AtomicU32 = AtomicU32::new(0);
186
187static IDS_EXHAUSTED: AtomicBool = AtomicBool::new(false);
192
193static LIVE_TEXTURES: parking_lot::Mutex<Option<HashMap<DynamicTextureId, TextureState>>> =
196 parking_lot::Mutex::new(None);
197
198#[derive(Clone, Copy)]
200struct TextureState {
201 size: crate::Size<DevicePixels>,
202 source: TextureSource,
203 version: u32,
208}
209
210#[derive(Clone, Copy, PartialEq, Eq)]
211enum TextureSource {
212 Upload,
213 Gpu,
214}
215
216fn live_textures() -> parking_lot::MappedMutexGuard<'static, HashMap<DynamicTextureId, TextureState>>
217{
218 parking_lot::MutexGuard::map(LIVE_TEXTURES.lock(), |textures| {
219 textures.get_or_insert_with(HashMap::new)
220 })
221}
222
223fn painted_version(id: DynamicTextureId) -> u32 {
227 live_textures()
228 .get(&id)
229 .map_or(1, |state| state.version.max(1))
230}
231
232pub(crate) fn create(
241 size: crate::Size<DevicePixels>,
242 bytes: &[u8],
243 bytes_per_row: u32,
244) -> Result<DynamicTexture> {
245 let width = usize::try_from(size.width.0).context("negative texture width")?;
246 let height = usize::try_from(size.height.0).context("negative texture height")?;
247 anyhow::ensure!(
248 width > 0 && height > 0,
249 "dynamic texture dimensions must be positive"
250 );
251
252 let row_bytes = width
253 .checked_mul(BYTES_PER_PIXEL)
254 .context("dynamic texture row size overflow")?;
255 let stride = usize::try_from(bytes_per_row).context("negative bytes per row")?;
256 anyhow::ensure!(
257 stride >= row_bytes,
258 "dynamic texture stride is smaller than one row"
259 );
260
261 let required = checked_payload_len(height, stride, row_bytes)?;
262 anyhow::ensure!(
263 bytes.len() >= required,
264 "dynamic texture payload is shorter than its dimensions"
265 );
266
267 let packed = pack_rows(bytes, stride, row_bytes, height);
268 let backend = platform()?;
269 allocate(size, TextureSource::Upload, |id| {
270 backend.create_texture(id, size, &packed)
271 })
272}
273
274fn allocate(
277 size: crate::Size<DevicePixels>,
278 source: TextureSource,
279 create: impl FnOnce(DynamicTextureId) -> Result<()>,
280) -> Result<DynamicTexture> {
281 let id = DynamicTextureId(NEXT_TEXTURE_ID.fetch_add(1, Ordering::Relaxed));
282 if IDS_EXHAUSTED.load(Ordering::Relaxed) || id.0 >= DYNAMIC_ID_LIMIT {
287 IDS_EXHAUSTED.store(true, Ordering::Relaxed);
288 anyhow::bail!("dynamic texture ids are exhausted");
289 }
290 create(id).with_context(|| format!("failed to create dynamic texture {id:?}"))?;
291 live_textures().insert(
292 id,
293 TextureState {
294 size,
295 source,
296 version: 1,
297 },
298 );
299
300 Ok(DynamicTexture { id, size })
301}
302
303pub(crate) fn update(
311 texture: DynamicTexture,
312 bounds: Bounds<DevicePixels>,
313 bytes: &[u8],
314 bytes_per_row: u32,
315) -> Result<()> {
316 let state = live_textures()
317 .get(&texture.id)
318 .copied()
319 .context("unknown dynamic texture")?;
320 anyhow::ensure!(
321 state.source == TextureSource::Upload,
322 "GPU-written textures must be updated by their producer"
323 );
324 let packed = validate_region(state.size, bounds, bytes, bytes_per_row)?;
325
326 platform()?
327 .update_texture(texture.id, bounds, &packed)
328 .with_context(|| format!("failed to update dynamic texture {texture:?}"))?;
329 if let Some(state) = live_textures().get_mut(&texture.id) {
330 state.version = state.version.wrapping_add(1).max(1);
331 }
332
333 Ok(())
334}
335
336pub(crate) fn mark_written(texture: DynamicTexture) -> Result<()> {
339 let mut textures = live_textures();
340 let state = textures
341 .get_mut(&texture.id)
342 .context("unknown dynamic texture")?;
343 state.version = state.version.wrapping_add(1).max(1);
344 Ok(())
345}
346
347pub(crate) fn paint(
351 window: &mut Window,
352 bounds: Bounds<Pixels>,
353 texture: DynamicTexture,
354) -> Result<()> {
355 window.invalidator.debug_assert_paint();
356
357 let texture_size = live_size(texture.id)?;
358
359 let tile = AtlasTile {
365 texture_id: texture.id.atlas_texture_id(),
366 tile_id: TileId(texture.id.0),
367 padding: 0,
368 bounds: Bounds {
369 origin: point(DevicePixels(0), DevicePixels(0)),
370 size: texture_size,
371 },
372 };
373 window.next_frame.scene.insert_primitive(PolychromeSprite {
374 order: 0,
375 pad: painted_version(texture.id),
376 grayscale: false.into(),
377 bounds: window.snap_bounds(bounds),
378 content_mask: window.snapped_content_mask(),
379 corner_radii: Default::default(),
380 tile,
381 opacity: window.element_opacity(),
382 });
383
384 Ok(())
385}
386
387pub(crate) fn remove(texture: DynamicTexture) {
389 let state = live_textures().remove(&texture.id);
390 if state.is_some_and(|state| state.source == TextureSource::Upload)
391 && let Ok(backend) = platform()
392 {
393 backend.remove_texture(texture.id);
394 }
395}
396
397#[derive(Default)]
398pub(crate) struct TextureDependencies(FxHashMap<DynamicTextureId, TextureUse>);
399
400#[derive(Default)]
401struct TextureUse {
402 direct: bool,
403 tiled: bool,
404 cached_layers: Vec<GlobalElementId>,
405}
406
407impl TextureDependencies {
408 fn rebuild(&mut self, scene: &Scene, layers: &FxHashMap<GlobalElementId, Layer>) {
409 self.0.clear();
410 for texture in painted_textures(&scene.paint_operations) {
411 self.0.entry(texture).or_default().direct = true;
412 }
413 for layer in scene
414 .layers
415 .frames
416 .iter()
417 .filter(|layer| layer.tile_size != 0)
418 {
419 for texture in painted_textures(layer.content.operations()) {
420 self.0.entry(texture).or_default().tiled = true;
421 }
422 }
423 for (id, layer) in layers {
424 if let Some(record) = &layer.record {
425 for texture in painted_textures(record.content.operations()) {
426 let cached = &mut self.0.entry(texture).or_default().cached_layers;
427 if cached.last() != Some(id) {
428 cached.push(id.clone());
429 }
430 }
431 }
432 }
433 }
434}
435
436fn painted_textures<'a>(
437 operations: impl IntoIterator<Item = &'a PaintOperation>,
438) -> impl Iterator<Item = DynamicTextureId> {
439 operations
440 .into_iter()
441 .filter_map(|operation| match operation {
442 PaintOperation::Primitive(Primitive::PolychromeSprite(sprite)) => {
443 DynamicTextureId::from_atlas_texture_id(sprite.tile.texture_id)
444 }
445 _ => None,
446 })
447}
448
449pub(crate) fn finish_frame(window: &mut Window) {
450 if let Some(dependencies) = &mut window.fast_layers.texture_dependencies {
451 dependencies.rebuild(&window.next_frame.scene, &window.fast_layers.layers);
452 }
453}
454
455impl Window {
456 pub fn create_dynamic_texture(
466 &mut self,
467 size: crate::Size<DevicePixels>,
468 bytes: &[u8],
469 bytes_per_row: u32,
470 ) -> Result<DynamicTexture> {
471 create(size, bytes, bytes_per_row)
472 }
473
474 pub fn update_dynamic_texture(
492 &mut self,
493 texture: DynamicTexture,
494 bounds: Bounds<DevicePixels>,
495 bytes: &[u8],
496 bytes_per_row: u32,
497 ) -> Result<()> {
498 update(texture, bounds, bytes, bytes_per_row)?;
499 self.refresh();
500 Ok(())
501 }
502
503 pub fn refresh_dynamic_texture(&mut self, texture: DynamicTexture) -> Result<()> {
508 mark_written(texture)?;
509 if !self.invalidator.not_drawing() {
510 return Ok(());
511 }
512
513 let layers = &mut self.fast_layers;
514 let dependencies = layers.texture_dependencies.get_or_insert_with(|| {
515 let mut dependencies = TextureDependencies::default();
516 dependencies.rebuild(&self.rendered_frame.scene, &layers.layers);
517 dependencies
518 });
519 let Some(usage) = dependencies.0.get(&texture.id) else {
520 self.refresh();
521 return Ok(());
522 };
523
524 for id in &usage.cached_layers {
525 if let Some(layer) = layers.layers.get_mut(id) {
526 layer.invalidate_content();
527 }
528 }
529
530 if usage.direct && !usage.tiled && usage.cached_layers.is_empty() {
531 self.needs_present.set(true);
532 self.platform_window.schedule_frame();
533 self.invalidator.wake_platform();
534 } else {
535 self.refresh();
536 }
537 Ok(())
538 }
539
540 pub fn paint_dynamic_texture(
545 &mut self,
546 bounds: Bounds<Pixels>,
547 texture: DynamicTexture,
548 ) -> Result<()> {
549 paint(self, bounds, texture)
550 }
551
552 pub fn remove_dynamic_texture(&mut self, texture: DynamicTexture) {
554 remove(texture);
555 }
556}
557
558fn live_size(id: DynamicTextureId) -> Result<crate::Size<DevicePixels>> {
560 live_textures()
561 .get(&id)
562 .map(|state| state.size)
563 .context("unknown dynamic texture")
564}
565
566fn validate_region<'a>(
569 texture_size: crate::Size<DevicePixels>,
570 bounds: Bounds<DevicePixels>,
571 bytes: &'a [u8],
572 bytes_per_row: u32,
573) -> Result<Cow<'a, [u8]>> {
574 let (origin_x, origin_y) = (bounds.origin.x.0 as i64, bounds.origin.y.0 as i64);
577 let (width, height) = (bounds.size.width.0 as i64, bounds.size.height.0 as i64);
578 anyhow::ensure!(
579 origin_x >= 0
580 && origin_y >= 0
581 && width > 0
582 && height > 0
583 && origin_x + width <= texture_size.width.0 as i64
584 && origin_y + height <= texture_size.height.0 as i64,
585 "dynamic texture update is outside the texture"
586 );
587
588 let (width, height) = (width as usize, height as usize);
591 let row_bytes = width
592 .checked_mul(BYTES_PER_PIXEL)
593 .context("dynamic texture region row size overflow")?;
594 let stride = usize::try_from(bytes_per_row).context("negative bytes per row")?;
595 anyhow::ensure!(
596 stride >= row_bytes,
597 "dynamic texture stride is smaller than one row"
598 );
599
600 let required = checked_payload_len(height, stride, row_bytes)?;
601 anyhow::ensure!(
602 bytes.len() >= required,
603 "dynamic texture update is shorter than the region"
604 );
605
606 Ok(pack_rows(bytes, stride, row_bytes, height))
607}
608
609fn checked_payload_len(height: usize, stride: usize, row_bytes: usize) -> Result<usize> {
612 (height - 1)
613 .checked_mul(stride)
614 .and_then(|length| length.checked_add(row_bytes))
615 .context("dynamic texture payload size overflow")
616}
617
618fn pack_rows(bytes: &[u8], stride: usize, row_bytes: usize, height: usize) -> Cow<'_, [u8]> {
621 if stride == row_bytes || height <= 1 {
622 return Cow::Borrowed(&bytes[..row_bytes * height]);
623 }
624 let mut packed = Vec::with_capacity(row_bytes * height);
625 for row in 0..height {
626 let start = row * stride;
627 packed.extend_from_slice(&bytes[start..start + row_bytes]);
628 }
629 Cow::Owned(packed)
630}
631
632#[cfg(test)]
633mod tests {
634 use super::{
635 BYTES_PER_PIXEL, DYNAMIC_INDEX_BASE, DynamicTexture, DynamicTextureId,
636 DynamicTexturePlatform, create, live_size, mark_written, pack_rows, painted_version,
637 remove, set_dynamic_texture_platform, update, validate_region,
638 };
639 use crate::{
640 AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, ContentMask, DevicePixels,
641 PolychromeSprite, ScaledPixels, Scene, TileId, point, size,
642 };
643 use anyhow::Result;
644 use std::{
645 borrow::Cow,
646 sync::{
647 Arc,
648 atomic::{AtomicBool, AtomicUsize, Ordering},
649 },
650 };
651
652 struct MockPlatform {
657 created: parking_lot::Mutex<Vec<(DynamicTextureId, crate::Size<DevicePixels>, usize)>>,
658 updated: parking_lot::Mutex<Vec<(DynamicTextureId, Bounds<DevicePixels>, usize)>>,
659 removed: parking_lot::Mutex<Vec<DynamicTextureId>>,
660 last_bytes_ptr: AtomicUsize,
661 fail_updates: AtomicBool,
662 }
663
664 impl DynamicTexturePlatform for MockPlatform {
665 fn create_texture(
666 &self,
667 id: DynamicTextureId,
668 size: crate::Size<DevicePixels>,
669 bytes: &[u8],
670 ) -> Result<()> {
671 self.last_bytes_ptr
672 .store(bytes.as_ptr() as usize, Ordering::SeqCst);
673 self.created.lock().push((id, size, bytes.len()));
674 Ok(())
675 }
676
677 fn update_texture(
678 &self,
679 id: DynamicTextureId,
680 bounds: Bounds<DevicePixels>,
681 bytes: &[u8],
682 ) -> Result<()> {
683 if self.fail_updates.load(Ordering::SeqCst) {
684 anyhow::bail!("backend refused the update");
685 }
686 self.last_bytes_ptr
687 .store(bytes.as_ptr() as usize, Ordering::SeqCst);
688 self.updated.lock().push((id, bounds, bytes.len()));
689 Ok(())
690 }
691
692 fn remove_texture(&self, id: DynamicTextureId) {
693 self.removed.lock().push(id);
694 }
695 }
696
697 static MOCK_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
699
700 fn shared_mock() -> &'static Arc<MockPlatform> {
702 static MOCK: std::sync::OnceLock<Arc<MockPlatform>> = std::sync::OnceLock::new();
703 MOCK.get_or_init(|| {
704 let mock = Arc::new(MockPlatform {
705 created: parking_lot::Mutex::new(Vec::new()),
706 updated: parking_lot::Mutex::new(Vec::new()),
707 removed: parking_lot::Mutex::new(Vec::new()),
708 last_bytes_ptr: AtomicUsize::new(0),
709 fail_updates: AtomicBool::new(false),
710 });
711 set_dynamic_texture_platform(mock.clone());
712 mock
713 })
714 }
715
716 fn fresh_mock() -> (parking_lot::MutexGuard<'static, ()>, Arc<MockPlatform>) {
718 let lock = MOCK_LOCK.lock();
719 let mock = shared_mock();
720 mock.created.lock().clear();
721 mock.updated.lock().clear();
722 mock.removed.lock().clear();
723 mock.last_bytes_ptr.store(0, Ordering::SeqCst);
724 mock.fail_updates.store(false, Ordering::SeqCst);
725 (lock, mock.clone())
726 }
727
728 fn size_of(width: i32, height: i32) -> crate::Size<DevicePixels> {
729 size(DevicePixels(width), DevicePixels(height))
730 }
731
732 fn bounds_at(origin: (i32, i32), width: i32, height: i32) -> Bounds<DevicePixels> {
733 Bounds {
734 origin: point(DevicePixels(origin.0), DevicePixels(origin.1)),
735 size: size(DevicePixels(width), DevicePixels(height)),
736 }
737 }
738
739 fn packed_bytes(width: i32, height: i32) -> Vec<u8> {
741 vec![0u8; width as usize * height as usize * BYTES_PER_PIXEL]
742 }
743
744 #[test]
745 fn create_reports_missing_platform() {
746 let error = super::require_platform(None)
750 .err()
751 .expect("a missing backend is an error");
752 assert_eq!(
753 error.to_string(),
754 "dynamic textures are not supported on this platform"
755 );
756 }
757
758 #[test]
759 fn create_requires_every_row_and_ignores_trailing_bytes() {
760 let (_lock, mock) = fresh_mock();
761
762 let short = create(size_of(4, 4), &packed_bytes(4, 4)[..63], 16);
763 assert!(short.is_err(), "one byte short must be refused");
764
765 let _padded = create(size_of(4, 4), &[0u8; 4 * 16], 16).expect("created");
768 {
769 let created = mock.created.lock();
770 assert_eq!(created.last().expect("created").2, 4 * 4 * BYTES_PER_PIXEL);
771 }
772
773 let empty = create(size_of(4, 4), &[], 16);
774 assert!(empty.is_err());
775
776 let zero = create(size_of(0, 4), &[], 0);
777 assert!(zero.is_err(), "zero width must be refused");
778 }
779
780 #[test]
781 fn create_rejects_a_stride_smaller_than_a_row() {
782 let (_lock, _mock) = fresh_mock();
783
784 let result = create(
785 size_of(4, 4),
786 &packed_bytes(4, 4),
787 3 * BYTES_PER_PIXEL as u32,
788 );
789 assert!(result.is_err());
790 }
791
792 #[test]
793 fn create_packs_rows_and_allocates_distinct_ids() {
794 let (_lock, mock) = fresh_mock();
795
796 let stride = (4 * BYTES_PER_PIXEL + 2) as u32;
800 let mut strided = vec![0u8; stride as usize + 4 * BYTES_PER_PIXEL];
801 for byte in strided.iter_mut().step_by(stride as usize) {
802 *byte = 0xFF;
803 }
804
805 let texture = create(size_of(4, 2), &strided, stride).expect("created");
806 {
807 let created = mock.created.lock();
808 let (created_id, created_size, packed_len) =
809 created.last().expect("create reached the platform");
810 assert_eq!(*created_id, texture.id);
811 assert_eq!(*created_size, texture.size);
812 assert_eq!(
813 *packed_len,
814 4 * 2 * BYTES_PER_PIXEL,
815 "rows must arrive tightly packed"
816 );
817 }
818
819 let other = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created again");
822 assert_ne!(texture.id, other.id, "ids must not repeat");
823 }
824
825 #[test]
826 fn update_validates_the_region_against_the_created_size() {
827 let (_lock, mock) = fresh_mock();
828
829 let texture_size = size_of(8, 8);
830 let texture = create(texture_size, &packed_bytes(8, 8), 32).expect("created");
831
832 let inside = bounds_at((0, 0), 4, 4);
833 let inside_bytes = packed_bytes(4, 4);
834 let packed = validate_region(texture_size, inside, &inside_bytes, 16)
835 .expect("a region inside the texture is accepted");
836 assert_eq!(packed.len(), 4 * 4 * BYTES_PER_PIXEL);
837
838 let offset = bounds_at((4, 4), 4, 4);
839 assert!(validate_region(texture_size, offset, &packed_bytes(4, 4), 16).is_ok());
840
841 let too_wide = bounds_at((0, 0), 9, 4);
842 assert!(
843 validate_region(texture_size, too_wide, &packed_bytes(9, 4), 36).is_err(),
844 "a region past the texture must be refused"
845 );
846
847 let negative = bounds_at((-1, 0), 4, 4);
848 assert!(validate_region(texture_size, negative, &packed_bytes(4, 4), 16).is_err());
849
850 let empty = bounds_at((0, 0), 0, 4);
851 assert!(validate_region(texture_size, empty, &[], 0).is_err());
852
853 let unknown = DynamicTexture {
854 id: DynamicTextureId(u32::MAX),
855 size: texture_size,
856 };
857 assert!(
858 live_size(unknown.id).is_err(),
859 "an unknown id must be refused"
860 );
861
862 remove(texture);
863 assert!(
864 live_size(texture.id).is_err(),
865 "a removed texture must be refused"
866 );
867 assert_eq!(mock.created.lock().len(), 1);
868 assert_eq!(mock.updated.lock().len(), 0);
869 assert_eq!(mock.removed.lock().len(), 1);
870 }
871
872 #[test]
873 fn update_requires_a_full_final_row() {
874 let (_lock, _mock) = fresh_mock();
875
876 let texture_size = size_of(8, 8);
877 let bounds = bounds_at((0, 0), 4, 4);
878 let row_bytes = 4 * BYTES_PER_PIXEL;
879
880 let short_by_one = &packed_bytes(4, 4)[..4 * row_bytes - 1];
881 assert!(
882 validate_region(texture_size, bounds, short_by_one, row_bytes as u32).is_err(),
883 "a final row missing bytes must be refused"
884 );
885 }
886
887 #[test]
888 fn remove_releases_the_texture_once() {
889 let (_lock, mock) = fresh_mock();
890
891 let texture = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
892 remove(texture);
893 remove(texture);
894
895 assert_eq!(
896 mock.removed.lock().len(),
897 1,
898 "the platform sees one removal"
899 );
900 }
901
902 #[test]
903 fn a_failing_backend_leaves_no_stale_state() {
904 let (_lock, mock) = fresh_mock();
905 mock.fail_updates.store(true, Ordering::SeqCst);
906
907 let texture = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
908 let version = painted_version(texture.id);
909 let result = update(texture, bounds_at((0, 0), 2, 2), &packed_bytes(2, 2), 8);
910 assert!(result.is_err(), "the backend's error must propagate");
911 assert!(
912 live_size(texture.id).is_ok(),
913 "the texture stays live for the next attempt"
914 );
915 assert_eq!(
916 painted_version(texture.id),
917 version,
918 "a refused update must not advance the version the next paint carries"
919 );
920 }
921
922 #[test]
923 fn atlas_ids_stay_out_of_the_atlas_range() {
924 let id = DynamicTextureId(0);
925 let atlas_id = id.atlas_texture_id();
926 assert_eq!(
927 DynamicTextureId::from_atlas_texture_id(atlas_id),
928 Some(id),
929 "the mapping must round-trip"
930 );
931
932 let atlas_id = AtlasTextureId {
933 index: 7,
934 kind: AtlasTextureKind::Polychrome,
935 };
936 assert_eq!(DynamicTextureId::from_atlas_texture_id(atlas_id), None);
937
938 let atlas_id = AtlasTextureId {
939 index: DYNAMIC_INDEX_BASE,
940 kind: AtlasTextureKind::Monochrome,
941 };
942 assert_eq!(
943 DynamicTextureId::from_atlas_texture_id(atlas_id),
944 None,
945 "a dynamic range index in another kind must not match"
946 );
947 }
948
949 fn scene_with_texture(texture: DynamicTexture, pad: u32) -> Scene {
953 let mut scene = Scene::default();
954 scene.insert_primitive(PolychromeSprite {
955 order: 0,
956 pad,
957 tile: AtlasTile {
958 texture_id: texture.id.atlas_texture_id(),
959 tile_id: TileId(texture.id.0),
960 padding: 0,
961 bounds: Bounds {
962 origin: point(DevicePixels(0), DevicePixels(0)),
963 size: texture.size,
964 },
965 },
966 grayscale: false.into(),
967 opacity: 1.,
968 bounds: Bounds {
969 origin: point(ScaledPixels(0.), ScaledPixels(0.)),
970 size: size(ScaledPixels(64.), ScaledPixels(64.)),
971 },
972 content_mask: ContentMask {
973 bounds: Bounds {
974 origin: point(ScaledPixels(0.), ScaledPixels(0.)),
975 size: size(ScaledPixels(128.), ScaledPixels(128.)),
976 },
977 },
978 corner_radii: Default::default(),
979 });
980 scene
981 }
982
983 #[test]
984 fn repainting_an_updated_texture_dirties_its_tiles() {
985 let (_lock, _mock) = fresh_mock();
986
987 let texture = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
988 let region = Bounds {
989 origin: point(ScaledPixels(0.), ScaledPixels(0.)),
990 size: size(ScaledPixels(128.), ScaledPixels(128.)),
991 };
992
993 let before = crate::fast::layers::tiles::tile_hashes(
994 &scene_with_texture(texture, painted_version(texture.id)),
995 64,
996 region,
997 );
998
999 update(texture, bounds_at((0, 0), 2, 2), &packed_bytes(2, 2), 8).expect("updated");
1002
1003 let after = crate::fast::layers::tiles::tile_hashes(
1004 &scene_with_texture(texture, painted_version(texture.id)),
1005 64,
1006 region,
1007 );
1008 assert_ne!(before, after, "tiles showing the texture must be dirtied");
1009
1010 let other = create(size_of(4, 4), &packed_bytes(4, 4), 16).expect("created");
1013 let unchanged = crate::fast::layers::tiles::tile_hashes(
1014 &scene_with_texture(other, painted_version(other.id)),
1015 64,
1016 region,
1017 );
1018 assert_eq!(
1019 crate::fast::layers::tiles::tile_hashes(
1020 &scene_with_texture(other, painted_version(other.id)),
1021 64,
1022 region,
1023 ),
1024 unchanged,
1025 );
1026 }
1027
1028 #[crate::test]
1029 fn refresh_dynamic_texture_invalidates_content_without_discarding_the_layer(
1030 cx: &mut crate::TestAppContext,
1031 ) {
1032 use crate::fast::layers::{paint::layer_mut, record::LayerRecord};
1033 use crate::{GlobalElementId, LayerFrame, LayerKey};
1034
1035 let window = cx.add_window(|_, _| crate::Empty);
1036 window
1037 .update(cx, |_, window, _| {
1038 let texture = DynamicTexture::new_gpu(size_of(4, 4)).unwrap();
1039 let direct = scene_with_texture(texture, painted_version(texture.id));
1040 let content = scene_with_texture(texture, painted_version(texture.id)).into();
1041 window.rendered_frame.scene = direct;
1042
1043 let layer_id = GlobalElementId::new(&[]);
1044 let layer = layer_mut(window, &layer_id);
1045 let key = layer.key;
1046 layer.generation = 7;
1047 layer.record = Some(LayerRecord {
1048 content,
1049 ..Default::default()
1050 });
1051
1052 window.invalidator.set_dirty(false);
1053 window.needs_present.set(false);
1054 window.refresh_dynamic_texture(texture).unwrap();
1055 assert!(window.invalidator.is_dirty());
1056 assert!(!window.needs_present.get());
1057 let layer = &window.fast_layers.layers[&layer_id];
1058 assert_eq!(layer.key, key);
1059 assert_eq!(layer.generation, 7);
1060 assert!(layer.record.is_none());
1061
1062 window.next_frame.scene = scene_with_texture(texture, painted_version(texture.id));
1063 window.next_frame.scene.layers.frames.push(LayerFrame {
1064 key: LayerKey(0),
1065 generation: 8,
1066 background: Default::default(),
1067 tile_size: 64,
1068 content: scene_with_texture(texture, painted_version(texture.id)).into(),
1069 dirty_tiles: Vec::new(),
1070 });
1071 super::finish_frame(window);
1072 window.invalidator.set_dirty(false);
1073 window.refresh_dynamic_texture(texture).unwrap();
1074 assert!(window.invalidator.is_dirty());
1075 texture.remove();
1076 })
1077 .unwrap();
1078 }
1079
1080 #[test]
1081 fn gpu_metadata_never_calls_the_upload_platform() {
1082 let (_lock, mock) = fresh_mock();
1083 assert!(DynamicTexture::new_gpu(size_of(0, 4)).is_err());
1084 let texture = DynamicTexture::new_gpu(size_of(4, 4)).expect("GPU metadata");
1085 assert!(mock.created.lock().is_empty());
1086 let version = painted_version(texture.id);
1087 mark_written(texture).expect("recorded GPU write");
1088 assert_ne!(painted_version(texture.id), version);
1089 assert!(update(texture, bounds_at((0, 0), 4, 4), &packed_bytes(4, 4), 16).is_err());
1090 texture.remove();
1091 assert!(mock.updated.lock().is_empty());
1092 assert!(mock.removed.lock().is_empty());
1093 assert!(mark_written(texture).is_err());
1094 }
1095
1096 #[test]
1097 fn tight_and_single_row_uploads_borrow_caller_slice_without_repacking() {
1098 let (_lock, mock) = fresh_mock();
1099
1100 let mut tight = vec![0xAB; 4 * 4 * BYTES_PER_PIXEL + 12];
1102 tight[0] = 0x11;
1103 let texture = create(size_of(4, 4), &tight, 16).expect("created");
1104 assert_eq!(
1105 mock.last_bytes_ptr.load(Ordering::SeqCst),
1106 tight.as_ptr() as usize,
1107 "tightly packed create must forward the caller slice without copying"
1108 );
1109 assert_eq!(
1110 mock.created.lock().last().unwrap().2,
1111 4 * 4 * BYTES_PER_PIXEL
1112 );
1113
1114 let single_row_padded = [0xCDu8; 24];
1116 update(texture, bounds_at((0, 0), 4, 1), &single_row_padded, 24).expect("updated");
1117 assert_eq!(
1118 mock.last_bytes_ptr.load(Ordering::SeqCst),
1119 single_row_padded.as_ptr() as usize,
1120 "single-row update must borrow the visible prefix without copying"
1121 );
1122 assert_eq!(mock.updated.lock().last().unwrap().2, 4 * BYTES_PER_PIXEL);
1123
1124 let strided = [1, 2, 3, 4, 0xEE, 0xEE, 5, 6, 7, 8];
1126 let repacked = pack_rows(&strided, 6, 4, 2);
1127 assert!(matches!(repacked, Cow::Owned(_)));
1128 assert_eq!(&*repacked, &[1, 2, 3, 4, 5, 6, 7, 8]);
1129
1130 remove(texture);
1131 }
1132}