mln_webgpu/
offscreen_texture.rs1use std::any::Any;
12use std::cell::RefCell;
13use std::rc::Rc;
14
15use mln_gfx::offscreen_texture;
16use mln_gfx::renderable::{Renderable, RenderableBase};
17use mln_gfx::texture2d::{SamplerState, Texture2D as _, Texture2DPtr};
18use mln_gfx::types::{TextureChannelDataType, TextureFilterType, TexturePixelType, TextureWrapType};
19use mln_util::image::PremultipliedImage;
20use mln_util::size::Size;
21
22use crate::context::Context;
23use crate::renderable_resource::{RenderableResource, RenderableResourceBox, downcast_resource};
24use crate::texture2d::Texture2D;
25
26const BYTES_PER_ROW_ALIGNMENT: u32 = 256;
27
28fn linear_clamp() -> SamplerState {
29 SamplerState {
30 filter: TextureFilterType::Linear,
31 wrap_u: TextureWrapType::Clamp,
32 wrap_v: TextureWrapType::Clamp,
33 ..SamplerState::default()
34 }
35}
36
37pub struct OffscreenTextureResource {
38 context: Rc<Context>,
39 size: Size,
40 type_: TextureChannelDataType,
41 color_texture: RefCell<Option<Rc<RefCell<Texture2D>>>>,
42 depth_texture: Option<Rc<RefCell<Texture2D>>>,
43}
44
45impl OffscreenTextureResource {
46 pub fn new(context: Rc<Context>, size: Size, type_: TextureChannelDataType, depth: bool, stencil: bool) -> Self {
47 debug_assert!(size.width != 0 && size.height != 0);
48 let mut res =
49 OffscreenTextureResource { context, size, type_, color_texture: RefCell::new(None), depth_texture: None };
50 *res.color_texture.borrow_mut() = Some(res.create_color_texture());
52
53 if depth || stencil {
56 let depth_texture = res.context.create_webgpu_texture_2d();
57 {
58 let mut t = depth_texture.borrow_mut();
59 t.set_size(size);
60 if depth && stencil {
62 t.set_format(TexturePixelType::Stencil, TextureChannelDataType::UnsignedByte);
63 } else if depth {
64 t.set_format(TexturePixelType::Depth, TextureChannelDataType::Float);
65 } else {
66 t.set_format(TexturePixelType::Stencil, TextureChannelDataType::UnsignedByte);
67 }
68 t.set_usage(wgpu::TextureUsages::RENDER_ATTACHMENT);
69 t.set_sampler_configuration(linear_clamp());
70 }
71 res.depth_texture = Some(depth_texture);
72 }
73 res
74 }
75
76 fn create_color_texture(&self) -> Rc<RefCell<Texture2D>> {
77 let texture = self.context.create_webgpu_texture_2d();
78 {
79 let mut t = texture.borrow_mut();
80 t.set_size(self.size);
81 t.set_format(TexturePixelType::RGBA, self.type_);
82 t.set_usage(
83 wgpu::TextureUsages::TEXTURE_BINDING
84 | wgpu::TextureUsages::COPY_DST
85 | wgpu::TextureUsages::COPY_SRC
86 | wgpu::TextureUsages::RENDER_ATTACHMENT,
87 );
88 t.set_sampler_configuration(linear_clamp());
89 }
90 texture
91 }
92
93 fn color(&self) -> Option<Rc<RefCell<Texture2D>>> {
94 self.color_texture.borrow().clone()
95 }
96
97 pub fn read_still_image(&self) -> PremultipliedImage {
98 let bytes_per_pixel = 4u32; let size = self.size;
101 let row_stride = size.width * bytes_per_pixel;
102 let aligned_row_stride = row_stride.div_ceil(BYTES_PER_ROW_ALIGNMENT) * BYTES_PER_ROW_ALIGNMENT;
103 let aligned_data_size = u64::from(aligned_row_stride) * u64::from(size.height);
104 let mut data = vec![0u8; row_stride as usize * size.height as usize];
105
106 let backend = self.context.get_backend();
107 let (Some(device), Some(queue)) = (backend.get_device(), backend.get_queue()) else {
108 eprintln!("WebGPU: No device or queue available for readback");
109 return PremultipliedImage::from_vec(size, data);
110 };
111
112 let staging_buffer = device.create_buffer(&wgpu::BufferDescriptor {
114 label: Some("Readback Buffer"),
115 size: aligned_data_size,
116 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
117 mapped_at_creation: false,
118 });
119
120 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
122 let color = self.color();
123 let texture = color.as_ref().and_then(|c| c.borrow().get_texture().cloned());
124 if let Some(texture) = texture {
125 encoder.copy_texture_to_buffer(
126 wgpu::TexelCopyTextureInfo {
127 texture: &texture,
128 mip_level: 0,
129 origin: wgpu::Origin3d::ZERO,
130 aspect: wgpu::TextureAspect::All,
131 },
132 wgpu::TexelCopyBufferInfo {
133 buffer: &staging_buffer,
134 layout: wgpu::TexelCopyBufferLayout {
135 offset: 0,
136 bytes_per_row: Some(aligned_row_stride),
137 rows_per_image: Some(size.height),
138 },
139 },
140 wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
141 );
142 queue.submit([encoder.finish()]);
143 } else {
144 eprintln!("WebGPU: Color texture is null");
145 }
146
147 let (tx, rx) = std::sync::mpsc::channel();
149 staging_buffer.map_async(wgpu::MapMode::Read, .., move |result| {
150 let _ = tx.send(result);
151 });
152 if let Err(e) = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }) {
153 eprintln!("WebGPU: Buffer mapping wait failed: {e}");
154 }
155 match rx.try_recv() {
156 Ok(Ok(())) => match staging_buffer.get_mapped_range(..) {
157 Ok(mapped) => {
158 if aligned_row_stride == row_stride {
159 let n = data.len();
160 data.copy_from_slice(&mapped[..n]);
161 } else {
162 let rs = row_stride as usize;
163 let ars = aligned_row_stride as usize;
164 for row in 0..size.height as usize {
165 data[row * rs..(row + 1) * rs].copy_from_slice(&mapped[row * ars..row * ars + rs]);
166 }
167 }
168 }
169 Err(e) => eprintln!("WebGPU: Failed to get mapped range: {e}"),
170 },
171 Ok(Err(e)) => eprintln!("WebGPU: Buffer mapping failed with status: {e}"),
172 Err(_) => eprintln!("WebGPU: Buffer mapping timeout after polling"),
173 }
174 staging_buffer.unmap();
175 PremultipliedImage::from_vec(size, data)
176 }
177
178 pub fn get_texture(&self) -> Texture2DPtr {
179 self.color().expect("offscreen texture without color texture")
180 }
181
182 pub fn take_texture(&self) -> Option<Texture2DPtr> {
183 let taken: Texture2DPtr = self.color_texture.borrow_mut().take()?;
184 *self.color_texture.borrow_mut() = Some(self.create_color_texture());
185 Some(taken)
186 }
187}
188
189impl Drop for OffscreenTextureResource {
190 fn drop(&mut self) {
191 self.context.rendering_stats_mut().num_frame_buffers -= 1;
192 }
193}
194
195impl RenderableResource for OffscreenTextureResource {
196 fn bind(&self) {
197 if let Some(color) = self.color() {
199 color.borrow_mut().create();
200 }
201 if let Some(depth) = &self.depth_texture {
202 depth.borrow_mut().create();
203 }
204 }
205
206 fn swap(&self) {
207 }
209
210 fn get_color_texture_view(&self) -> Option<wgpu::TextureView> {
211 let color = self.color()?;
212 let mut texture = color.borrow_mut();
213 texture.create();
214 texture.get_texture_view().cloned()
215 }
216
217 fn get_color_texture_format(&self) -> Option<wgpu::TextureFormat> {
218 self.color()?.borrow().get_native_format()
219 }
220
221 fn get_depth_stencil_texture_view(&self) -> Option<wgpu::TextureView> {
222 let depth = self.depth_texture.as_ref()?;
223 let mut texture = depth.borrow_mut();
224 texture.create();
225 texture.get_texture_view().cloned()
226 }
227
228 fn get_depth_stencil_texture_format(&self) -> Option<wgpu::TextureFormat> {
229 self.depth_texture.as_ref()?.borrow().get_native_format()
230 }
231
232 fn as_any(&self) -> &dyn Any {
233 self
234 }
235}
236
237pub struct OffscreenTexture {
239 renderable: RenderableBase,
240}
241
242impl OffscreenTexture {
243 pub fn new(context: Rc<Context>, size: Size, type_: TextureChannelDataType, depth: bool, stencil: bool) -> Self {
244 let resource =
245 RenderableResourceBox::new_rc(OffscreenTextureResource::new(context, size, type_, depth, stencil));
246 OffscreenTexture { renderable: RenderableBase::new(size, Some(resource)) }
247 }
248
249 fn with_resource<R>(&self, f: impl FnOnce(&OffscreenTextureResource) -> R) -> Option<R> {
250 let resource = self.get_resource()?;
251 downcast_resource::<OffscreenTextureResource>(&*resource).map(f)
252 }
253
254 pub fn take_texture(&self) -> Option<Texture2DPtr> {
255 self.with_resource(|r| r.take_texture()).flatten()
256 }
257}
258
259impl Renderable for OffscreenTexture {
260 fn renderable_base(&self) -> &RenderableBase {
261 &self.renderable
262 }
263}
264
265impl offscreen_texture::OffscreenTexture for OffscreenTexture {
266 fn is_renderable(&self) -> bool {
268 self.with_resource(|r| r.color().is_some()).unwrap_or(false)
269 }
270
271 fn read_still_image(&self) -> PremultipliedImage {
272 self.with_resource(|r| r.read_still_image()).unwrap_or_else(|| PremultipliedImage::new(self.get_size()))
273 }
274
275 fn get_texture(&self) -> Texture2DPtr {
276 self.with_resource(|r| r.get_texture()).expect("offscreen texture without resource")
277 }
278
279 fn as_any(&self) -> &dyn Any {
280 self
281 }
282}