1use std::collections::HashMap;
2use std::path::Path;
3
4use anyhow::{Context, Result};
5
6#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
7pub struct TextureId(pub u32);
8
9pub struct Texture {
10 pub size: [u32; 2],
11 pub(crate) bind_group: wgpu::BindGroup,
12 #[allow(dead_code)]
13 pub(crate) texture: wgpu::Texture,
14 #[allow(dead_code)]
15 pub(crate) view: wgpu::TextureView,
16}
17
18pub(crate) struct TextureRegistry {
19 map: HashMap<TextureId, Texture>,
20 next: u32,
21 pub(crate) layout: wgpu::BindGroupLayout,
22 sampler: wgpu::Sampler,
23 white: TextureId,
24}
25
26impl TextureRegistry {
27 pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
28 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
29 label: Some("sprite.texture_bgl"),
30 entries: &[
31 wgpu::BindGroupLayoutEntry {
32 binding: 0,
33 visibility: wgpu::ShaderStages::FRAGMENT,
34 ty: wgpu::BindingType::Texture {
35 sample_type: wgpu::TextureSampleType::Float { filterable: true },
36 view_dimension: wgpu::TextureViewDimension::D2,
37 multisampled: false,
38 },
39 count: None,
40 },
41 wgpu::BindGroupLayoutEntry {
42 binding: 1,
43 visibility: wgpu::ShaderStages::FRAGMENT,
44 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
45 count: None,
46 },
47 ],
48 });
49
50 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
51 label: Some("sprite.sampler"),
52 address_mode_u: wgpu::AddressMode::ClampToEdge,
53 address_mode_v: wgpu::AddressMode::ClampToEdge,
54 address_mode_w: wgpu::AddressMode::ClampToEdge,
55 mag_filter: wgpu::FilterMode::Nearest,
56 min_filter: wgpu::FilterMode::Nearest,
57 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
58 ..Default::default()
59 });
60
61 let mut me = Self {
62 map: HashMap::new(),
63 next: 1,
64 layout,
65 sampler,
66 white: TextureId(0),
67 };
68 me.white = me.create_from_rgba(device, queue, 1, 1, &[255, 255, 255, 255], Some("white"));
69 me
70 }
71
72 pub fn white(&self) -> TextureId {
73 self.white
74 }
75
76 pub fn bind_group(&self, id: TextureId) -> &wgpu::BindGroup {
77 &self
78 .map
79 .get(&id)
80 .unwrap_or_else(|| self.map.get(&self.white).expect("white texture"))
81 .bind_group
82 }
83
84 pub fn get(&self, id: TextureId) -> Option<&Texture> {
85 self.map.get(&id)
86 }
87
88 #[cfg(not(target_arch = "wasm32"))]
89 pub fn load_file(
90 &mut self,
91 device: &wgpu::Device,
92 queue: &wgpu::Queue,
93 path: impl AsRef<Path>,
94 ) -> Result<TextureId> {
95 let path = path.as_ref();
96 let img = image::open(path).with_context(|| format!("loading {}", path.display()))?;
97 let rgba = img.to_rgba8();
98 let (w, h) = rgba.dimensions();
99 Ok(self.create_from_rgba(
100 device,
101 queue,
102 w,
103 h,
104 rgba.as_raw(),
105 path.file_name().and_then(|s| s.to_str()),
106 ))
107 }
108
109 pub fn load_bytes(
111 &mut self,
112 device: &wgpu::Device,
113 queue: &wgpu::Queue,
114 bytes: &[u8],
115 label: Option<&str>,
116 ) -> Result<TextureId> {
117 let img = image::load_from_memory(bytes)
118 .with_context(|| format!("decoding {}", label.unwrap_or("image")))?;
119 let rgba = img.to_rgba8();
120 let (w, h) = rgba.dimensions();
121 Ok(self.create_from_rgba(device, queue, w, h, rgba.as_raw(), label))
122 }
123
124 pub fn reload(
127 &mut self,
128 device: &wgpu::Device,
129 queue: &wgpu::Queue,
130 id: TextureId,
131 path: impl AsRef<Path>,
132 ) -> Result<()> {
133 let path = path.as_ref();
134 let img = image::open(path).with_context(|| format!("reloading {}", path.display()))?;
135 let rgba = img.to_rgba8();
136 let (w, h) = rgba.dimensions();
137 self.replace(
138 device,
139 queue,
140 id,
141 w,
142 h,
143 rgba.as_raw(),
144 path.file_name().and_then(|s| s.to_str()),
145 );
146 Ok(())
147 }
148
149 #[allow(clippy::too_many_arguments)]
150 pub fn replace(
151 &mut self,
152 device: &wgpu::Device,
153 queue: &wgpu::Queue,
154 id: TextureId,
155 width: u32,
156 height: u32,
157 rgba: &[u8],
158 label: Option<&str>,
159 ) {
160 let new_id = self.create_from_rgba(device, queue, width, height, rgba, label);
161 if let Some(new_tex) = self.map.remove(&new_id) {
162 self.map.insert(id, new_tex);
163 }
164 }
165
166 pub fn create_from_rgba(
167 &mut self,
168 device: &wgpu::Device,
169 queue: &wgpu::Queue,
170 width: u32,
171 height: u32,
172 rgba: &[u8],
173 label: Option<&str>,
174 ) -> TextureId {
175 let size = wgpu::Extent3d {
176 width,
177 height,
178 depth_or_array_layers: 1,
179 };
180 let texture = device.create_texture(&wgpu::TextureDescriptor {
181 label,
182 size,
183 mip_level_count: 1,
184 sample_count: 1,
185 dimension: wgpu::TextureDimension::D2,
186 format: wgpu::TextureFormat::Rgba8UnormSrgb,
187 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
188 view_formats: &[],
189 });
190 queue.write_texture(
191 wgpu::TexelCopyTextureInfo {
192 texture: &texture,
193 mip_level: 0,
194 origin: wgpu::Origin3d::ZERO,
195 aspect: wgpu::TextureAspect::All,
196 },
197 rgba,
198 wgpu::TexelCopyBufferLayout {
199 offset: 0,
200 bytes_per_row: Some(4 * width),
201 rows_per_image: Some(height),
202 },
203 size,
204 );
205 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
206 let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
207 label,
208 layout: &self.layout,
209 entries: &[
210 wgpu::BindGroupEntry {
211 binding: 0,
212 resource: wgpu::BindingResource::TextureView(&view),
213 },
214 wgpu::BindGroupEntry {
215 binding: 1,
216 resource: wgpu::BindingResource::Sampler(&self.sampler),
217 },
218 ],
219 });
220
221 let id = TextureId(self.next);
222 self.next += 1;
223 self.map.insert(
224 id,
225 Texture {
226 size: [width, height],
227 bind_group,
228 texture,
229 view,
230 },
231 );
232 id
233 }
234}