1use mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
6use mln_gfx::gpu::{Gpu as _, ReadbackId, ResourceId, TargetFormats, TextureId, TextureRegion, destroy_unused};
7use mln_gfx::{Error, FramePixels, Size};
8
9use crate::device::Device;
10use crate::gpu::{WebGpu, from_wgpu_format};
11use crate::log_target;
12use crate::renderer_backend::RendererBackend;
13
14const ALPHA_MODE: wgpu::CompositeAlphaMode =
19 if cfg!(target_family = "wasm") { wgpu::CompositeAlphaMode::PreMultiplied } else { wgpu::CompositeAlphaMode::Auto };
20
21pub struct OverlayTarget<'a> {
24 pub device: &'a wgpu::Device,
25 pub queue: &'a wgpu::Queue,
26 pub view: &'a wgpu::TextureView,
27 pub format: wgpu::TextureFormat,
28 pub size: Size,
30}
31
32pub type Overlay = Box<dyn FnMut(&OverlayTarget<'_>)>;
35
36#[derive(Clone, Copy, Debug)]
38pub struct SurfaceOptions {
39 pub cap_frame_rate: bool,
42 pub usages: Option<wgpu::TextureUsages>,
47 pub format: Option<wgpu::TextureFormat>,
50}
51
52impl Default for SurfaceOptions {
53 fn default() -> Self {
54 SurfaceOptions { cap_frame_rate: true, usages: None, format: None }
55 }
56}
57
58pub struct SurfaceTarget {
65 state: Box<State>,
66}
67
68struct State {
69 current: Option<wgpu::SurfaceTexture>,
71 depth_stencil: Option<wgpu::Texture>,
73 overlay: Option<Overlay>,
74 surface: wgpu::Surface<'static>,
75
76 format: wgpu::TextureFormat,
77 usage: wgpu::TextureUsages,
78 present_mode: wgpu::PresentMode,
79 depth_stencil_format: wgpu::TextureFormat,
80 size: Size,
82 configured: Option<Size>,
85
86 color_import: Option<TextureId>,
90 depth_import: Option<TextureId>,
91
92 readback_requested: bool,
93 pending_readback: Option<(ReadbackId, Size)>,
96 readback: Option<FramePixels>,
97 device: Device,
98}
99
100impl SurfaceTarget {
101 pub fn new(
114 backend: &RendererBackend,
115 surface: wgpu::Surface<'static>,
116 framebuffer_size: Size,
117 options: SurfaceOptions,
118 ) -> Result<SurfaceTarget, Error> {
119 let device = backend.device();
120 let (format, mut usage, vsync_present_mode) = if let Some(adapter) = device.adapter() {
121 let capabilities = surface.get_capabilities(adapter);
122 if capabilities.formats.is_empty() {
123 return Err(Error::unsupported("The WebGPU adapter can't present to the surface"));
124 }
125 let format = match options.format.or(device.surface_format()) {
126 Some(format) if capabilities.formats.contains(&format) => format,
127 Some(format) => {
128 return Err(Error::unsupported(format!("The surface does not take the {format:?} format")));
129 }
130 None => {
131 const RENDERED: [wgpu::TextureFormat; 4] = [
132 wgpu::TextureFormat::Bgra8Unorm,
133 wgpu::TextureFormat::Bgra8UnormSrgb,
134 wgpu::TextureFormat::Rgba8Unorm,
135 wgpu::TextureFormat::Rgba8UnormSrgb,
136 ];
137 let format = if cfg!(target_family = "wasm") {
141 capabilities.formats.iter().copied().find(|f| RENDERED.contains(f))
142 } else {
143 RENDERED.into_iter().find(|f| capabilities.formats.contains(f))
144 };
145 format
146 .ok_or_else(|| Error::unsupported("The surface takes none of the formats the map renders in"))?
147 }
148 };
149 let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (capabilities.usages & wgpu::TextureUsages::COPY_SRC);
150 let present_mode = if capabilities.present_modes.contains(&wgpu::PresentMode::Mailbox) {
154 wgpu::PresentMode::Mailbox
155 } else {
156 wgpu::PresentMode::Fifo
157 };
158 (format, usage, present_mode)
159 } else {
160 let format = options.format.or(device.surface_format()).ok_or_else(|| {
161 Error::invalid_argument("A surface on a device without an adapter needs the device's surface format")
162 })?;
163 (format, wgpu::TextureUsages::RENDER_ATTACHMENT, wgpu::PresentMode::Fifo)
164 };
165 if let Some(usages) = options.usages {
166 usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (usages & wgpu::TextureUsages::COPY_SRC);
167 }
168 let depth_stencil_format = if device.device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
169 wgpu::TextureFormat::Depth32FloatStencil8
170 } else {
171 wgpu::TextureFormat::Depth24PlusStencil8
172 };
173
174 Ok(SurfaceTarget {
175 state: Box::new(State {
176 current: None,
177 depth_stencil: None,
178 overlay: None,
179 surface,
180 format,
181 usage,
182 present_mode: if options.cap_frame_rate { vsync_present_mode } else { wgpu::PresentMode::Immediate },
183 depth_stencil_format,
184 size: framebuffer_size,
185 configured: None,
186 color_import: None,
187 depth_import: None,
188 readback_requested: false,
189 pending_readback: None,
190 readback: None,
191 device: device.clone(),
192 }),
193 })
194 }
195
196 #[must_use]
198 pub fn format(&self) -> wgpu::TextureFormat {
199 self.state.format
200 }
201
202 #[must_use]
204 pub fn size(&self) -> Size {
205 self.state.size
206 }
207
208 pub fn request_readback(&mut self) {
210 self.state.readback_requested = true;
211 }
212
213 #[must_use]
217 pub fn take_readback(&mut self, gpu: &mut WebGpu) -> Option<FramePixels> {
218 self.state.finish_readback(gpu, false);
219 self.state.readback.take()
220 }
221
222 pub fn set_overlay(&mut self, overlay: Option<Overlay>) {
225 self.state.overlay = overlay;
226 }
227}
228
229impl State {
230 fn acquire(&mut self) -> Option<Size> {
234 let size_of = |texture: &wgpu::SurfaceTexture| Size::new(texture.texture.width(), texture.texture.height());
235 if let Some(current) = &self.current {
236 return Some(size_of(current));
237 }
238 let size = self.size;
239 if self.configured != Some(size) && size.width != 0 && size.height != 0 {
242 self.surface.configure(
243 self.device.device(),
244 &wgpu::SurfaceConfiguration {
245 usage: self.usage,
246 format: self.format,
247 width: size.width,
248 height: size.height,
249 present_mode: self.present_mode,
250 desired_maximum_frame_latency: 2,
251 alpha_mode: ALPHA_MODE,
252 view_formats: vec![self.format],
253 color_space: wgpu::SurfaceColorSpace::Auto,
254 },
255 );
256 self.configured = Some(size);
257 }
258 self.configured?;
259 let texture = match self.surface.get_current_texture() {
260 wgpu::CurrentSurfaceTexture::Success(texture) | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
261 wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
262 self.configured = None;
263 return None;
264 }
265 wgpu::CurrentSurfaceTexture::Timeout
266 | wgpu::CurrentSurfaceTexture::Occluded
267 | wgpu::CurrentSurfaceTexture::Validation => return None,
268 };
269 Some(size_of(self.current.insert(texture)))
270 }
271
272 fn depth_stencil_import(&mut self, gpu: &mut WebGpu, size: Size) -> TextureId {
274 let texture = match self.depth_stencil.take() {
275 Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture,
276 _ => {
277 if let Some(import) = self.depth_import.take() {
278 destroy_unused(gpu, [ResourceId::Texture(import)]);
279 }
280 self.device.device().create_texture(&wgpu::TextureDescriptor {
281 label: Some("surface depth and stencil"),
282 size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
283 mip_level_count: 1,
284 sample_count: 1,
285 dimension: wgpu::TextureDimension::D2,
286 format: self.depth_stencil_format,
287 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
288 view_formats: &[],
289 })
290 }
291 };
292 let import = *self.depth_import.get_or_insert_with(|| gpu.import_texture(&texture));
293 self.depth_stencil = Some(texture);
294 import
295 }
296
297 fn read_back(&mut self, gpu: &mut WebGpu, texture: &wgpu::Texture) {
299 if !self.usage.contains(wgpu::TextureUsages::COPY_SRC) {
300 tracing::warn!(target: log_target::RENDER, "WebGPU: the surface does not support readback (no COPY_SRC)");
301 return;
302 }
303 let size = Size::new(texture.width(), texture.height());
304 let imported = gpu.import_texture(texture);
305 let readback = gpu.read_texture(imported, TextureRegion::whole(size));
306 destroy_unused(gpu, [ResourceId::Texture(imported)]);
307 match readback {
308 Ok(readback) => {
309 if let Some((stale, _)) = self.pending_readback.replace((readback, size)) {
310 destroy_unused(gpu, [ResourceId::Readback(stale)]);
311 }
312 }
313 Err(error) => {
314 tracing::error!(target: log_target::RENDER, error = %error, "WebGPU: reading the frame back failed");
315 }
316 }
317 }
318
319 fn finish_readback(&mut self, gpu: &mut WebGpu, wait: bool) {
322 let Some((readback, size)) = self.pending_readback.take() else {
323 return;
324 };
325 let mut texels = match gpu.take_readback(readback, wait) {
326 Ok(Some(texels)) => texels,
327 Ok(None) => {
328 self.pending_readback = Some((readback, size));
329 return;
330 }
331 Err(error) => {
332 return tracing::error!(target: log_target::RENDER, error = %error, "WebGPU: reading the frame back failed");
333 }
334 };
335 if matches!(self.format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb) {
336 for texel in texels.as_chunks_mut::<4>().0 {
337 texel.swap(0, 2);
338 }
339 }
340 self.readback = Some(FramePixels { size, data: texels });
341 }
342}
343
344impl FrameTarget for SurfaceTarget {
345 type Gpu = WebGpu;
346
347 fn resize(&mut self, _gpu: &mut WebGpu, size: Size) {
349 self.state.size = size;
350 }
351
352 fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
355 self.state.begin_frame(gpu)
356 }
357
358 fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
361 self.state.end_frame(gpu)
362 }
363
364 fn tear_down(&mut self, gpu: &mut WebGpu) {
365 let state = &mut *self.state;
366 if let Some((readback, _)) = state.pending_readback.take() {
367 destroy_unused(gpu, [ResourceId::Readback(readback)]);
368 }
369 let imports = [state.color_import.take(), state.depth_import.take()].into_iter().flatten();
370 destroy_unused(gpu, imports.map(ResourceId::Texture));
371 }
372}
373
374impl State {
375 fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
376 let size = self.acquire()?;
377 let depth_stencil = self.depth_stencil_import(gpu, size);
378 let current = self.current.as_ref()?;
379 let color = *self.color_import.get_or_insert_with(|| gpu.import_texture(¤t.texture));
380 let targets = TargetFormats {
381 color: from_wgpu_format(self.format),
382 depth_stencil: from_wgpu_format(self.depth_stencil_format),
383 };
384 Some(FrameImage { size, color, depth_stencil: Some(depth_stencil), targets })
385 }
386
387 fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
388 if let Some(color) = self.color_import.take() {
389 destroy_unused(gpu, [ResourceId::Texture(color)]);
390 }
391 let Some(current) = self.current.take() else {
392 return Handoff::Dropped;
393 };
394 if let Some(overlay) = self.overlay.as_mut() {
395 let view = current.texture.create_view(&wgpu::TextureViewDescriptor::default());
396 overlay(&OverlayTarget {
397 device: self.device.device(),
398 queue: self.device.queue(),
399 view: &view,
400 format: self.format,
401 size: Size::new(current.texture.width(), current.texture.height()),
402 });
403 }
404 if std::mem::take(&mut self.readback_requested) {
405 self.read_back(gpu, ¤t.texture);
406 self.finish_readback(gpu, true);
409 }
410 self.device.queue().present(current);
411 Handoff::Presented
412 }
413}
414
415impl Drop for State {
416 fn drop(&mut self) {
417 drop(self.current.take());
419 drop(self.depth_stencil.take());
420 drop(self.overlay.take());
421 let _ = self.device.device().poll(wgpu::PollType::Poll);
423 }
424}