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