Skip to main content

mln_webgpu/
offscreen_texture.rs

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