use hashbrown::HashMap;
use crate::platform::types::TextureResource;
#[derive(Default)]
pub struct TextureCache {
map: HashMap<u64, TextureResource>,
}
impl TextureCache {
pub fn insert(&mut self, id: u64, res: TextureResource) {
self.map.insert(id, res);
}
pub fn remove(&mut self, id: &u64) {
self.map.remove(id);
}
pub fn get(&self, id: &u64) -> Option<&TextureResource> {
self.map.get(id)
}
pub fn create_texture(
device: &wgpu::Device,
queue: &wgpu::Queue,
img: image::DynamicImage,
) -> TextureResource {
let rgba = img.to_rgba8();
let (width, height) = rgba.dimensions();
let size = wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
};
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("texture"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8UnormSrgb,
usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&rgba,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * width),
rows_per_image: Some(height),
},
size,
);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor::default());
TextureResource {
texture,
view,
sampler,
}
}
pub fn create_raw_texture(device: &wgpu::Device, texture: wgpu::Texture) -> TextureResource {
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor::default());
TextureResource {
texture,
view,
sampler,
}
}
}