mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Park render cache tiles out of view in the texture pool (#5060)
This commit is contained in:
1 parent
9517b006fa
commit
c8e8fbf8d1
1 file changed
+174
-41
@@ -6,6 +6,7 @@ use core_types::transform::{Footprint, RenderQuality, Transform};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Generations, NodeError, OwnedContextImpl, Poll};
|
||||
use glam::{DAffine2, DVec2, I64Vec2, UVec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphic_types::raster_types::{Texture, TextureWeakRef};
|
||||
use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::Hash;
|
||||
@@ -14,7 +15,7 @@ use vector_types::vector::style::RenderMode;
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
pub const TILE_SIZE: u32 = 256;
|
||||
pub const MAX_CACHE_MEMORY_BYTES: usize = 512 * 1024 * 1024;
|
||||
const MAX_CACHE_KEYS: usize = 8;
|
||||
const BYTES_PER_PIXEL: usize = 4;
|
||||
|
||||
/// A tile in the grid laid out in device pixels from the document's origin, which deep zoom puts too far away to count in 32 bits.
|
||||
@@ -29,8 +30,14 @@ pub struct CachedRegion {
|
||||
pub output: Poll<RenderOutput>,
|
||||
pub size: UVec2,
|
||||
pub tiles: Vec<TileCoord>,
|
||||
last_access: u64,
|
||||
memory_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ParkedRegion {
|
||||
metadata: Poll<rendering::RenderMetadata>,
|
||||
texture: TextureWeakRef,
|
||||
size: UVec2,
|
||||
tiles: Vec<TileCoord>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
|
||||
@@ -108,10 +115,8 @@ impl TileCache {
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct TileCacheImpl {
|
||||
regions: Vec<CachedRegion>,
|
||||
timestamp: u64,
|
||||
total_memory: usize,
|
||||
cache_key: CacheKey,
|
||||
keys: Vec<(CacheKey, Vec<ParkedRegion>)>,
|
||||
view: Vec<Texture>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -163,25 +168,37 @@ fn tiles_bounds(tiles: &[TileCoord]) -> AxisAlignedBbox {
|
||||
|
||||
impl TileCacheImpl {
|
||||
fn query(&mut self, viewport_bounds: &AxisAlignedBbox, cache_key: &CacheKey, max_region_size: u32) -> CacheQuery {
|
||||
if &self.cache_key != cache_key {
|
||||
self.invalidate_all();
|
||||
self.cache_key = cache_key.clone();
|
||||
}
|
||||
let regions = match self.keys.iter().position(|(key, _)| key == cache_key) {
|
||||
Some(index) => self.keys.remove(index).1,
|
||||
None => Vec::new(),
|
||||
};
|
||||
self.keys.insert(0, (cache_key.clone(), regions));
|
||||
self.keys.truncate(MAX_CACHE_KEYS);
|
||||
|
||||
let required_tiles = bounds_to_tiles(viewport_bounds);
|
||||
let required_tile_set: HashSet<_> = required_tiles.iter().cloned().collect();
|
||||
let mut cached_regions = Vec::new();
|
||||
let mut covered_tiles = HashSet::new();
|
||||
let mut view = Vec::new();
|
||||
|
||||
for region in &mut self.regions {
|
||||
self.keys[0].1.retain(|region| {
|
||||
let Some(texture) = region.texture.upgrade() else { return false };
|
||||
let region_tiles: HashSet<_> = region.tiles.iter().cloned().collect();
|
||||
if region_tiles.iter().any(|t| required_tile_set.contains(t)) {
|
||||
region.last_access = self.timestamp;
|
||||
self.timestamp += 1;
|
||||
cached_regions.push(region.clone());
|
||||
view.push(texture.clone());
|
||||
cached_regions.push(CachedRegion {
|
||||
output: region.metadata.clone().map(|metadata| RenderOutput {
|
||||
data: RenderOutputType::Texture(texture),
|
||||
metadata,
|
||||
}),
|
||||
size: region.size,
|
||||
tiles: region.tiles.clone(),
|
||||
});
|
||||
covered_tiles.extend(region_tiles);
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
self.view = view;
|
||||
|
||||
let missing_tiles: Vec<_> = required_tiles.into_iter().filter(|t| !covered_tiles.contains(t)).collect();
|
||||
let missing_regions = group_into_regions(&missing_tiles, max_region_size);
|
||||
@@ -189,30 +206,25 @@ impl TileCacheImpl {
|
||||
}
|
||||
|
||||
fn store_regions(&mut self, new_regions: Vec<CachedRegion>) {
|
||||
for mut region in new_regions {
|
||||
region.last_access = self.timestamp;
|
||||
self.timestamp += 1;
|
||||
self.total_memory += region.memory_size;
|
||||
self.regions.push(region);
|
||||
}
|
||||
self.evict_until_under_budget();
|
||||
}
|
||||
let Some((_, regions)) = self.keys.first_mut() else { return };
|
||||
for region in new_regions {
|
||||
let output = match ®ion.output {
|
||||
Poll::Final(output) | Poll::Partial(output) => output,
|
||||
Poll::Fallback(boxed) => &boxed.0,
|
||||
Poll::Pending | Poll::Error(_) => continue,
|
||||
};
|
||||
let RenderOutputType::Texture(texture) = &output.data else { continue };
|
||||
let texture = texture.clone();
|
||||
|
||||
fn evict_until_under_budget(&mut self) {
|
||||
while self.total_memory > MAX_CACHE_MEMORY_BYTES && !self.regions.is_empty() {
|
||||
if let Some((oldest_idx, _)) = self.regions.iter().enumerate().min_by_key(|(_, r)| r.last_access) {
|
||||
let removed = self.regions.remove(oldest_idx);
|
||||
self.total_memory = self.total_memory.saturating_sub(removed.memory_size);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
regions.push(ParkedRegion {
|
||||
metadata: region.output.map(|output| output.metadata),
|
||||
texture: texture.downgrade(),
|
||||
size: region.size,
|
||||
tiles: region.tiles,
|
||||
});
|
||||
self.view.push(texture);
|
||||
}
|
||||
}
|
||||
|
||||
fn invalidate_all(&mut self) {
|
||||
self.regions.clear();
|
||||
self.total_memory = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Groups tiles into rectangular regions no wider or taller than `max_region_size` pixels.
|
||||
@@ -490,8 +502,6 @@ where
|
||||
output,
|
||||
size: region_pixel_size,
|
||||
tiles: region.tiles.clone(),
|
||||
last_access: 0,
|
||||
memory_size: (region_pixel_size.x * region_pixel_size.y) as usize * BYTES_PER_PIXEL,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -717,8 +727,6 @@ mod tests {
|
||||
output: Poll::Pending,
|
||||
size: tiles_bounds(®ion.tiles).size().as_uvec2(),
|
||||
tiles: region.tiles,
|
||||
last_access: 0,
|
||||
memory_size: 0,
|
||||
};
|
||||
if let Some(placement) = region_placement(®ion, &device_origin_offset, resolution) {
|
||||
covered += placement.size.x as u64 * placement.size.y as u64;
|
||||
@@ -727,4 +735,129 @@ mod tests {
|
||||
assert_eq!(covered, resolution.x as u64 * resolution.y as u64, "with the document's origin offset by {device_origin_offset}");
|
||||
}
|
||||
}
|
||||
|
||||
fn texture(device: &wgpu::Device) -> Texture {
|
||||
device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
fn view(column: i64) -> AxisAlignedBbox {
|
||||
let start = DVec2::new(column as f64, 0.) * TILE_SIZE as f64;
|
||||
AxisAlignedBbox {
|
||||
start,
|
||||
end: start + DVec2::splat(2. * TILE_SIZE as f64),
|
||||
}
|
||||
}
|
||||
|
||||
fn zoom(zoom: u64) -> CacheKey {
|
||||
CacheKey { zoom, ..Default::default() }
|
||||
}
|
||||
|
||||
fn show(cache: &TileCache, device: &wgpu::Device, view: &AxisAlignedBbox, key: &CacheKey) -> (Vec<Texture>, Vec<Texture>) {
|
||||
let query = cache.query(view, key, 4096);
|
||||
let reused = query
|
||||
.cached_regions
|
||||
.iter()
|
||||
.filter_map(|region| match ®ion.output {
|
||||
Poll::Final(RenderOutput {
|
||||
data: RenderOutputType::Texture(texture),
|
||||
..
|
||||
}) => Some(texture.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let rendered: Vec<_> = query.missing_regions.iter().map(|_| texture(device)).collect();
|
||||
let regions = query.missing_regions.into_iter().zip(&rendered).map(|(region, texture)| CachedRegion {
|
||||
output: Poll::Final(RenderOutput {
|
||||
data: RenderOutputType::Texture(texture.clone()),
|
||||
metadata: Default::default(),
|
||||
}),
|
||||
size: tiles_bounds(®ion.tiles).size().as_uvec2(),
|
||||
tiles: region.tiles,
|
||||
});
|
||||
cache.store_regions(regions.collect());
|
||||
|
||||
(reused, rendered)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regions_out_of_view_are_held_weakly_and_those_in_view_strongly() {
|
||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
||||
let cache = TileCache::default();
|
||||
|
||||
let mut pool = Vec::new();
|
||||
for column in [0, 4, 8, 12] {
|
||||
pool.extend(show(&cache, &context.device, &view(column), &zoom(1)).1);
|
||||
|
||||
let (in_view, out_of_view) = pool.split_last().unwrap();
|
||||
assert!(in_view.is_shared());
|
||||
assert!(out_of_view.iter().all(|texture| !texture.is_shared() && texture.is_weakly_shared()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parked_region_back_in_view_is_reused() {
|
||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
||||
let cache = TileCache::default();
|
||||
|
||||
let (_, parked) = show(&cache, &context.device, &view(0), &zoom(1));
|
||||
show(&cache, &context.device, &view(4), &zoom(1));
|
||||
|
||||
assert_eq!(show(&cache, &context.device, &view(0), &zoom(1)), (parked, Vec::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parked_region_the_pool_evicted_is_rendered_again() {
|
||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
||||
let cache = TileCache::default();
|
||||
|
||||
let (_, evicted) = show(&cache, &context.device, &view(0), &zoom(1));
|
||||
show(&cache, &context.device, &view(4), &zoom(1));
|
||||
drop(evicted);
|
||||
|
||||
let (reused, rendered) = show(&cache, &context.device, &view(0), &zoom(1));
|
||||
assert!(reused.is_empty());
|
||||
assert_eq!(rendered.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_regions_of_an_earlier_cache_key_are_reused_on_returning_to_it() {
|
||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
||||
let cache = TileCache::default();
|
||||
|
||||
let (_, parked) = show(&cache, &context.device, &view(0), &zoom(1));
|
||||
show(&cache, &context.device, &view(0), &zoom(2));
|
||||
|
||||
assert_eq!(show(&cache, &context.device, &view(0), &zoom(1)), (parked, Vec::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_regions_of_cache_keys_older_than_the_most_recent_ones_are_released() {
|
||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
||||
let cache = TileCache::default();
|
||||
|
||||
let (_, oldest) = show(&cache, &context.device, &view(0), &zoom(0));
|
||||
for key in 1..MAX_CACHE_KEYS as u64 {
|
||||
show(&cache, &context.device, &view(0), &zoom(key));
|
||||
}
|
||||
assert!(oldest[0].is_weakly_shared());
|
||||
|
||||
show(&cache, &context.device, &view(0), &zoom(MAX_CACHE_KEYS as u64));
|
||||
assert!(!oldest[0].is_weakly_shared());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user