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 % BYTES_PER_ROW_ALIGNMENT != 0 {
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 size_changed_callback: Option<Box<dyn Fn(Size)>>,
56}
57
58impl Texture2D {
59 pub fn new(context: Rc<Context>) -> Self {
60 Texture2D {
61 context,
62 texture: None,
63 texture_view: None,
64 sampler: None,
65 usage_flags: wgpu::TextureUsages::TEXTURE_BINDING
66 | wgpu::TextureUsages::COPY_DST
67 | wgpu::TextureUsages::COPY_SRC,
68 native_format: None,
69 size: Size { width: 0, height: 0 },
70 pixel_format: TexturePixelType::RGBA,
71 channel_type: TextureChannelDataType::UnsignedByte,
72 sampler_state: SamplerState::default(),
73 image: None,
74 dirty: false,
75 size_changed_callback: None,
76 }
77 }
78
79 pub fn set_usage(&mut self, usage_flags: wgpu::TextureUsages) {
80 self.usage_flags = usage_flags;
81 }
82
83 pub fn set_size_changed_callback(&mut self, callback: Option<Box<dyn Fn(Size)>>) {
84 self.size_changed_callback = callback;
85 }
86
87 pub fn get_native_format(&self) -> Option<wgpu::TextureFormat> {
88 self.native_format
89 }
90 pub fn get_texture(&self) -> Option<&wgpu::Texture> {
91 self.texture.as_ref()
92 }
93 pub fn get_texture_view(&self) -> Option<&wgpu::TextureView> {
94 self.texture_view.as_ref()
95 }
96 pub fn get_sampler(&self) -> Option<&wgpu::Sampler> {
97 self.sampler.as_ref()
98 }
99 pub fn get_sampler_state(&self) -> &SamplerState {
100 &self.sampler_state
101 }
102
103 fn write(&self, texture: &wgpu::Texture, copy: &UploadCopyData, origin: wgpu::Origin3d, region: Size) {
104 let Some(queue) = self.context.get_backend().get_queue() else {
105 return;
106 };
107 queue.write_texture(
108 wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin, aspect: wgpu::TextureAspect::All },
109 ©.data,
110 wgpu::TexelCopyBufferLayout {
111 offset: 0,
112 bytes_per_row: Some(copy.bytes_per_row),
113 rows_per_image: Some(region.height),
114 },
115 wgpu::Extent3d { width: region.width, height: region.height, depth_or_array_layers: 1 },
116 );
117 }
118}
119
120impl texture2d::Texture2D for Texture2D {
121 fn set_sampler_configuration(&mut self, sampler_state: SamplerState) {
122 let mut safe_state = sampler_state;
123 if safe_state.max_anisotropy < 1 {
124 safe_state.max_anisotropy = 1;
125 }
126 if self.sampler.is_some() && self.sampler_state == safe_state {
130 return;
131 }
132 self.sampler_state = safe_state;
133 self.sampler = None;
134
135 let filter = if self.sampler_state.filter == TextureFilterType::Linear {
136 wgpu::FilterMode::Linear
137 } else {
138 wgpu::FilterMode::Nearest
139 };
140 let map_wrap_mode = |wrap: TextureWrapType| match wrap {
141 TextureWrapType::Repeat => wgpu::AddressMode::Repeat,
142 TextureWrapType::Clamp => wgpu::AddressMode::ClampToEdge,
143 };
144 if let Some(device) = self.context.get_backend().get_device() {
145 self.sampler = Some(device.create_sampler(&wgpu::SamplerDescriptor {
146 label: Some("Texture Sampler"),
147 address_mode_u: map_wrap_mode(self.sampler_state.wrap_u),
148 address_mode_v: map_wrap_mode(self.sampler_state.wrap_v),
149 address_mode_w: wgpu::AddressMode::ClampToEdge,
150 mag_filter: filter,
151 min_filter: filter,
152 mipmap_filter: if self.sampler_state.mipmapped {
153 wgpu::MipmapFilterMode::Linear
154 } else {
155 wgpu::MipmapFilterMode::Nearest
156 },
157 anisotropy_clamp: u16::from(self.sampler_state.max_anisotropy),
158 ..Default::default()
159 }));
160 }
161 }
162
163 fn set_format(&mut self, pixel_format: TexturePixelType, channel_type: TextureChannelDataType) {
164 self.pixel_format = pixel_format;
165 self.channel_type = channel_type;
166 }
167
168 fn set_size(&mut self, size: Size) {
169 if self.size == size {
170 return;
171 }
172 self.size = size;
173 self.dirty = true;
174 if let Some(callback) = &self.size_changed_callback {
175 callback(size);
176 }
177 }
178
179 fn set_image(&mut self, image: Option<Rc<PremultipliedImage>>) {
180 if let Some(img) = &image {
181 self.size = img.size;
182 self.dirty = true;
183 }
184 self.image = image;
185 }
186
187 fn get_format(&self) -> TexturePixelType {
188 self.pixel_format
189 }
190
191 fn get_size(&self) -> Size {
192 self.size
193 }
194
195 fn get_data_size(&self) -> usize {
196 self.size.width as usize * self.size.height as usize * self.get_pixel_stride()
197 }
198
199 fn get_pixel_stride(&self) -> usize {
200 match self.pixel_format {
201 TexturePixelType::Alpha | TexturePixelType::Luminance => match self.channel_type {
202 TextureChannelDataType::UnsignedByte => 1,
203 TextureChannelDataType::HalfFloat => 2,
204 TextureChannelDataType::Float => 4,
205 },
206 TexturePixelType::RGBA => match self.channel_type {
207 TextureChannelDataType::UnsignedByte => 4,
208 TextureChannelDataType::HalfFloat => 8,
209 TextureChannelDataType::Float => 16,
210 },
211 _ => 4,
212 }
213 }
214
215 fn num_channels(&self) -> usize {
216 match self.pixel_format {
217 TexturePixelType::Alpha | TexturePixelType::Luminance => 1,
218 _ => 4,
219 }
220 }
221
222 fn create(&mut self) {
223 if self.texture.is_some() && self.texture_view.is_some() {
226 return;
227 }
228 self.texture_view = None;
229 self.texture = None;
230
231 let Some(device) = self.context.get_backend().get_device() else {
232 return;
233 };
234 if self.size.width == 0 || self.size.height == 0 {
235 return;
236 }
237
238 let mut usage = self.usage_flags;
240 let format = match self.pixel_format {
241 TexturePixelType::Alpha | TexturePixelType::Luminance => match self.channel_type {
242 TextureChannelDataType::UnsignedByte => wgpu::TextureFormat::R8Unorm,
243 TextureChannelDataType::HalfFloat => {
244 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
245 wgpu::TextureFormat::R16Float
246 }
247 TextureChannelDataType::Float => {
248 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
249 wgpu::TextureFormat::R32Float
250 }
251 },
252 TexturePixelType::Depth => {
253 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
254 wgpu::TextureFormat::Depth32Float
255 }
256 TexturePixelType::Stencil => {
257 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
260 wgpu::TextureFormat::Depth24PlusStencil8
261 }
262 TexturePixelType::RGBA => match self.channel_type {
263 TextureChannelDataType::UnsignedByte => wgpu::TextureFormat::Rgba8Unorm,
264 TextureChannelDataType::HalfFloat => {
265 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
266 wgpu::TextureFormat::Rgba16Float
267 }
268 TextureChannelDataType::Float => {
269 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
270 wgpu::TextureFormat::Rgba32Float
271 }
272 },
273 };
274 self.native_format = Some(format);
275
276 if self.pixel_format == TexturePixelType::RGBA {
278 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
279 }
280
281 let texture = device.create_texture(&wgpu::TextureDescriptor {
282 label: Some("Texture2D"),
283 size: wgpu::Extent3d { width: self.size.width, height: self.size.height, depth_or_array_layers: 1 },
284 mip_level_count: 1,
285 sample_count: 1,
286 dimension: wgpu::TextureDimension::D2,
287 format,
288 usage,
289 view_formats: &[],
290 });
291 self.texture_view = Some(texture.create_view(&wgpu::TextureViewDescriptor {
292 label: Some("Texture2D View"),
293 format: Some(format),
294 dimension: Some(wgpu::TextureViewDimension::D2),
295 usage: None,
296 aspect: wgpu::TextureAspect::All,
297 base_mip_level: 0,
298 mip_level_count: Some(1),
299 base_array_layer: 0,
300 array_layer_count: Some(1),
301 }));
302 self.texture = Some(texture);
303
304 if self.sampler.is_none() {
306 let state = self.sampler_state;
307 self.set_sampler_configuration(state);
308 }
309 }
310
311 fn upload_data(&mut self, pixel_data: Option<&[u8]>, size: Size) {
312 self.size = size;
313 if self.texture.is_none() {
315 self.create();
316 }
317 let (Some(texture), Some(pixel_data)) = (self.texture.clone(), pixel_data) else {
318 return;
319 };
320 let Some(copy) = prepare_copy_data(pixel_data, size, self.get_pixel_stride()) else {
321 return;
322 };
323 self.write(&texture, ©, wgpu::Origin3d::ZERO, size);
324 }
325
326 fn upload_sub_region(&mut self, pixel_data: Option<&[u8]>, region_size: Size, x_offset: u16, y_offset: u16) {
327 let (Some(texture), Some(pixel_data)) = (self.texture.clone(), pixel_data) else {
328 return;
329 };
330 let Some(copy) = prepare_copy_data(pixel_data, region_size, self.get_pixel_stride()) else {
331 return;
332 };
333 let origin = wgpu::Origin3d { x: u32::from(x_offset), y: u32::from(y_offset), z: 0 };
334 self.write(&texture, ©, origin, region_size);
335 }
336
337 fn upload(&mut self) {
338 if let Some(image) = self.image.clone() {
339 self.upload_data(Some(&image.data), image.size);
340 self.dirty = false;
341 }
342 }
343
344 fn needs_upload(&self) -> bool {
345 self.dirty
346 }
347
348 fn as_any(&self) -> &dyn Any {
349 self
350 }
351
352 fn as_any_mut(&mut self) -> &mut dyn Any {
353 self
354 }
355}