1use std::any::Any;
7use std::rc::Rc;
8
9use mln_gfx::texture2d::{self, SamplerState};
10use mln_gfx::types::{TextureChannelDataType, TextureFilterType, TexturePixelType, TextureWrapType};
11use mln_util::image::PremultipliedImage;
12use mln_util::size::Size;
13
14use crate::context::Context;
15
16const BYTES_PER_ROW_ALIGNMENT: usize = 256;
17
18struct UploadCopyData {
19 data: Vec<u8>,
20 bytes_per_row: u32,
21}
22
23fn prepare_copy_data(pixel_data: &[u8], region_size: Size, pixel_stride: usize) -> Option<UploadCopyData> {
25 if region_size.width == 0 || region_size.height == 0 {
26 return None;
27 }
28 let row_stride = region_size.width as usize * pixel_stride;
29 let data_size = row_stride * region_size.height as usize;
30 if region_size.height > 1 && !row_stride.is_multiple_of(BYTES_PER_ROW_ALIGNMENT) {
31 let aligned = row_stride.div_ceil(BYTES_PER_ROW_ALIGNMENT) * BYTES_PER_ROW_ALIGNMENT;
32 let mut staging = vec![0u8; aligned * region_size.height as usize];
33 for row in 0..region_size.height as usize {
34 staging[row * aligned..row * aligned + row_stride]
35 .copy_from_slice(&pixel_data[row * row_stride..(row + 1) * row_stride]);
36 }
37 return Some(UploadCopyData { data: staging, bytes_per_row: aligned as u32 });
38 }
39 Some(UploadCopyData { data: pixel_data[..data_size].to_vec(), bytes_per_row: row_stride as u32 })
40}
41
42pub struct Texture2D {
43 context: Rc<Context>,
44 texture: Option<wgpu::Texture>,
45 texture_view: Option<wgpu::TextureView>,
46 sampler: Option<wgpu::Sampler>,
47 usage_flags: wgpu::TextureUsages,
48 native_format: Option<wgpu::TextureFormat>,
49 size: Size,
50 pixel_format: TexturePixelType,
51 channel_type: TextureChannelDataType,
52 sampler_state: SamplerState,
53 image: Option<Rc<PremultipliedImage>>,
54 dirty: bool,
55 counted_bytes: usize,
57}
58
59impl Texture2D {
60 pub fn new(context: Rc<Context>) -> Self {
61 Texture2D {
62 context,
63 texture: None,
64 texture_view: None,
65 sampler: None,
66 usage_flags: wgpu::TextureUsages::TEXTURE_BINDING
67 | wgpu::TextureUsages::COPY_DST
68 | wgpu::TextureUsages::COPY_SRC,
69 native_format: None,
70 size: Size { width: 0, height: 0 },
71 pixel_format: TexturePixelType::RGBA,
72 channel_type: TextureChannelDataType::UnsignedByte,
73 sampler_state: SamplerState::default(),
74 image: None,
75 dirty: false,
76 counted_bytes: 0,
77 }
78 }
79
80 fn release_texture(&mut self) {
82 if self.texture.take().is_some() {
83 let mut stats = self.context.rendering_stats_mut();
84 stats.num_active_textures -= 1;
85 stats.mem_textures -= self.counted_bytes as i32;
86 self.counted_bytes = 0;
87 }
88 }
89
90 pub fn set_usage(&mut self, usage_flags: wgpu::TextureUsages) {
91 self.usage_flags = usage_flags;
92 }
93
94 #[must_use]
95 pub fn get_native_format(&self) -> Option<wgpu::TextureFormat> {
96 self.native_format
97 }
98 #[must_use]
99 pub fn get_texture(&self) -> Option<&wgpu::Texture> {
100 self.texture.as_ref()
101 }
102 #[must_use]
103 pub fn get_texture_view(&self) -> Option<&wgpu::TextureView> {
104 self.texture_view.as_ref()
105 }
106 #[must_use]
107 pub fn get_sampler(&self) -> Option<&wgpu::Sampler> {
108 self.sampler.as_ref()
109 }
110 #[must_use]
111 pub fn get_sampler_state(&self) -> &SamplerState {
112 &self.sampler_state
113 }
114
115 fn write(&self, texture: &wgpu::Texture, copy: &UploadCopyData, origin: wgpu::Origin3d, region: Size) {
116 let Some(queue) = self.context.get_backend().get_queue() else {
117 return;
118 };
119 {
120 let mut stats = self.context.rendering_stats_mut();
121 stats.num_texture_updates += 1;
122 let bytes = region.width as usize * region.height as usize * texture2d::Texture2D::get_pixel_stride(self);
123 stats.texture_update_bytes = stats.texture_update_bytes.wrapping_add(bytes);
124 }
125 queue.write_texture(
126 wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin, aspect: wgpu::TextureAspect::All },
127 ©.data,
128 wgpu::TexelCopyBufferLayout {
129 offset: 0,
130 bytes_per_row: Some(copy.bytes_per_row),
131 rows_per_image: Some(region.height),
132 },
133 wgpu::Extent3d { width: region.width, height: region.height, depth_or_array_layers: 1 },
134 );
135 }
136}
137
138impl Drop for Texture2D {
139 fn drop(&mut self) {
140 self.release_texture();
141 }
142}
143
144impl texture2d::Texture2D for Texture2D {
145 fn set_sampler_configuration(&mut self, sampler_state: SamplerState) {
146 let mut safe_state = sampler_state;
147 if safe_state.max_anisotropy < 1 {
148 safe_state.max_anisotropy = 1;
149 }
150 if self.sampler.is_some() && self.sampler_state == safe_state {
154 return;
155 }
156 self.sampler_state = safe_state;
157 self.sampler = None;
158
159 let filter = if self.sampler_state.filter == TextureFilterType::Linear {
160 wgpu::FilterMode::Linear
161 } else {
162 wgpu::FilterMode::Nearest
163 };
164 let map_wrap_mode = |wrap: TextureWrapType| match wrap {
165 TextureWrapType::Repeat => wgpu::AddressMode::Repeat,
166 TextureWrapType::Clamp => wgpu::AddressMode::ClampToEdge,
167 };
168 if let Some(device) = self.context.get_backend().get_device() {
169 self.sampler = Some(device.create_sampler(&wgpu::SamplerDescriptor {
170 label: Some("Texture Sampler"),
171 address_mode_u: map_wrap_mode(self.sampler_state.wrap_u),
172 address_mode_v: map_wrap_mode(self.sampler_state.wrap_v),
173 address_mode_w: wgpu::AddressMode::ClampToEdge,
174 mag_filter: filter,
175 min_filter: filter,
176 mipmap_filter: if self.sampler_state.mipmapped {
177 wgpu::MipmapFilterMode::Linear
178 } else {
179 wgpu::MipmapFilterMode::Nearest
180 },
181 anisotropy_clamp: u16::from(self.sampler_state.max_anisotropy),
182 ..Default::default()
183 }));
184 }
185 }
186
187 fn set_format(&mut self, pixel_format: TexturePixelType, channel_type: TextureChannelDataType) {
188 self.pixel_format = pixel_format;
189 self.channel_type = channel_type;
190 }
191
192 fn set_size(&mut self, size: Size) {
193 if self.size == size {
194 return;
195 }
196 self.size = size;
197 self.dirty = true;
198 }
199
200 fn set_image(&mut self, image: Option<Rc<PremultipliedImage>>) {
201 if let Some(img) = &image {
202 self.size = img.size;
203 self.dirty = true;
204 }
205 self.image = image;
206 }
207
208 fn get_format(&self) -> TexturePixelType {
209 self.pixel_format
210 }
211
212 fn get_size(&self) -> Size {
213 self.size
214 }
215
216 fn get_data_size(&self) -> usize {
217 self.size.width as usize * self.size.height as usize * self.get_pixel_stride()
218 }
219
220 fn get_pixel_stride(&self) -> usize {
221 match self.pixel_format {
222 TexturePixelType::Alpha | TexturePixelType::Luminance => match self.channel_type {
223 TextureChannelDataType::UnsignedByte => 1,
224 TextureChannelDataType::HalfFloat => 2,
225 TextureChannelDataType::Float => 4,
226 },
227 TexturePixelType::RGBA => match self.channel_type {
228 TextureChannelDataType::UnsignedByte => 4,
229 TextureChannelDataType::HalfFloat => 8,
230 TextureChannelDataType::Float => 16,
231 },
232 _ => 4,
233 }
234 }
235
236 fn num_channels(&self) -> usize {
237 match self.pixel_format {
238 TexturePixelType::Alpha | TexturePixelType::Luminance => 1,
239 _ => 4,
240 }
241 }
242
243 fn create(&mut self) {
244 if self.texture.is_some() && self.texture_view.is_some() {
247 return;
248 }
249 self.texture_view = None;
250 self.release_texture();
251
252 let Some(device) = self.context.get_backend().get_device() else {
253 return;
254 };
255 if self.size.width == 0 || self.size.height == 0 {
256 return;
257 }
258
259 let mut usage = self.usage_flags;
261 let format = match self.pixel_format {
262 TexturePixelType::Alpha | TexturePixelType::Luminance => match self.channel_type {
263 TextureChannelDataType::UnsignedByte => wgpu::TextureFormat::R8Unorm,
264 TextureChannelDataType::HalfFloat => {
265 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
266 wgpu::TextureFormat::R16Float
267 }
268 TextureChannelDataType::Float => {
269 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
270 wgpu::TextureFormat::R32Float
271 }
272 },
273 TexturePixelType::Depth => {
274 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
275 wgpu::TextureFormat::Depth32Float
276 }
277 TexturePixelType::Stencil => {
278 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
281 wgpu::TextureFormat::Depth24PlusStencil8
282 }
283 TexturePixelType::RGBA => match self.channel_type {
284 TextureChannelDataType::UnsignedByte => wgpu::TextureFormat::Rgba8Unorm,
285 TextureChannelDataType::HalfFloat => {
286 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
287 wgpu::TextureFormat::Rgba16Float
288 }
289 TextureChannelDataType::Float => {
290 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
291 wgpu::TextureFormat::Rgba32Float
292 }
293 },
294 };
295 self.native_format = Some(format);
296
297 if self.pixel_format == TexturePixelType::RGBA {
299 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
300 }
301
302 let texture = device.create_texture(&wgpu::TextureDescriptor {
303 label: Some("Texture2D"),
304 size: wgpu::Extent3d { width: self.size.width, height: self.size.height, depth_or_array_layers: 1 },
305 mip_level_count: 1,
306 sample_count: 1,
307 dimension: wgpu::TextureDimension::D2,
308 format,
309 usage,
310 view_formats: &[],
311 });
312 self.texture_view = Some(texture.create_view(&wgpu::TextureViewDescriptor {
313 label: Some("Texture2D View"),
314 format: Some(format),
315 dimension: Some(wgpu::TextureViewDimension::D2),
316 usage: None,
317 aspect: wgpu::TextureAspect::All,
318 base_mip_level: 0,
319 mip_level_count: Some(1),
320 base_array_layer: 0,
321 array_layer_count: Some(1),
322 }));
323 self.texture = Some(texture);
324 self.counted_bytes = self.get_data_size();
325 {
326 let mut stats = self.context.rendering_stats_mut();
327 stats.num_created_textures += 1;
328 stats.num_active_textures += 1;
329 stats.mem_textures += self.counted_bytes as i32;
330 }
331
332 if self.sampler.is_none() {
334 let state = self.sampler_state;
335 self.set_sampler_configuration(state);
336 }
337 }
338
339 fn upload_data(&mut self, pixel_data: Option<&[u8]>, size: Size) {
340 self.size = size;
341 if self.texture.is_none() {
343 self.create();
344 }
345 let (Some(texture), Some(pixel_data)) = (self.texture.clone(), pixel_data) else {
346 return;
347 };
348 let Some(copy) = prepare_copy_data(pixel_data, size, self.get_pixel_stride()) else {
349 return;
350 };
351 self.write(&texture, ©, wgpu::Origin3d::ZERO, size);
352 }
353
354 fn upload_sub_region(&mut self, pixel_data: Option<&[u8]>, region_size: Size, x_offset: u16, y_offset: u16) {
355 let (Some(texture), Some(pixel_data)) = (self.texture.clone(), pixel_data) else {
356 return;
357 };
358 let Some(copy) = prepare_copy_data(pixel_data, region_size, self.get_pixel_stride()) else {
359 return;
360 };
361 let origin = wgpu::Origin3d { x: u32::from(x_offset), y: u32::from(y_offset), z: 0 };
362 self.write(&texture, ©, origin, region_size);
363 }
364
365 fn upload(&mut self) {
366 if let Some(image) = self.image.clone() {
367 self.upload_data(Some(&image.data), image.size);
368 self.dirty = false;
369 }
370 }
371
372 fn needs_upload(&self) -> bool {
373 self.dirty
374 }
375
376 fn as_any(&self) -> &dyn Any {
377 self
378 }
379
380 fn as_any_mut(&mut self) -> &mut dyn Any {
381 self
382 }
383}