rendy_resource/sampler/
cache.rsuse {
super::Sampler,
crate::escape::Handle,
rendy_core::hal::{image::SamplerDesc, Backend},
std::{
collections::hash_map::{Entry, HashMap},
ops::{Deref, DerefMut},
},
};
#[derive(Debug)]
pub struct SamplerCache<B: Backend> {
samplers: HashMap<SamplerDesc, Handle<Sampler<B>>>,
}
impl<B> Default for SamplerCache<B>
where
B: Backend,
{
fn default() -> Self {
SamplerCache {
samplers: HashMap::default(),
}
}
}
impl<B> SamplerCache<B>
where
B: Backend,
{
pub fn get(
&mut self,
info: SamplerDesc,
create: impl FnOnce() -> Result<Handle<Sampler<B>>, rendy_core::hal::device::AllocationError>,
) -> Result<Handle<Sampler<B>>, rendy_core::hal::device::AllocationError> {
Ok(match self.samplers.entry(info) {
Entry::Occupied(occupied) => occupied.get().clone(),
Entry::Vacant(vacant) => {
let sampler = create()?;
vacant.insert(sampler).clone()
}
})
}
pub fn get_with_upgradable_lock<R, W, U>(
read: R,
upgrade: U,
info: SamplerDesc,
create: impl FnOnce() -> Result<Handle<Sampler<B>>, rendy_core::hal::device::AllocationError>,
) -> Result<Handle<Sampler<B>>, rendy_core::hal::device::AllocationError>
where
R: Deref<Target = Self>,
W: DerefMut<Target = Self>,
U: FnOnce(R) -> W,
{
if let Some(sampler) = read.samplers.get(&info) {
return Ok(sampler.clone());
}
let sampler = create()?;
{
upgrade(read).samplers.insert(info, sampler.clone());
}
Ok(sampler)
}
}