1use mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
7use mln_gfx::gpu::{Gpu as _, ResourceId, TargetFormats, destroy_unused};
8use mln_gfx::{ConsumerSync, DepthStencilFormat, DepthStencilFormats, Error, GpuSync, Size, SyncKind, SyncKinds};
9
10use crate::gpu::{WebGpu, from_wgpu_format};
11use crate::log_target;
12use crate::renderer_backend::RendererBackend;
13
14#[derive(Clone, Debug, PartialEq)]
17pub struct BorrowedTextures {
18 pub textures: Vec<wgpu::Texture>,
19 pub size: Size,
20 pub depth_textures: Vec<wgpu::Texture>,
24}
25
26impl BorrowedTextures {
27 #[must_use]
31 pub fn sync_kinds() -> (SyncKinds, SyncKinds) {
32 let kinds = SyncKinds::of(&[SyncKind::CpuComplete, SyncKind::QueueOrder]);
33 (kinds, kinds)
34 }
35
36 #[must_use]
38 pub fn depth_stencil_formats(device: &wgpu::Device) -> DepthStencilFormats {
39 let formats = DepthStencilFormats::of(&[DepthStencilFormat::Depth24Stencil8]);
40 if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
41 formats.with(DepthStencilFormat::Depth32FloatStencil8)
42 } else {
43 formats
44 }
45 }
46
47 pub fn check(&self) -> Result<(), Error> {
56 let Some(first) = self.textures.first() else {
57 return Err(Error::invalid_argument("a ring needs at least one texture"));
58 };
59 if let Some(depth) = self.depth_textures.first() {
60 if self.depth_textures.len() != self.textures.len() {
61 return Err(Error::invalid_argument("a ring's depth textures must be one for each of its textures"));
62 }
63 if depth_stencil_format(depth.format()).is_none() {
64 return Err(Error::unsupported("a ring's depth textures must have a depth and stencil format"));
65 }
66 }
67 for texture in self.textures.iter().chain(&self.depth_textures) {
68 let size = texture.size();
69 if (size.width, size.height) != (self.size.width, self.size.height) {
70 return Err(Error::invalid_argument("each texture's size must match the ring's physical size"));
71 }
72 let kin =
73 if texture.format().is_depth_stencil_format() { self.depth_textures.first() } else { Some(first) };
74 if Some(texture.format()) != kin.map(wgpu::Texture::format) {
75 return Err(Error::invalid_argument("the ring's textures must share a format"));
76 }
77 if !texture.usage().contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
78 || texture.dimension() != wgpu::TextureDimension::D2
79 || texture.mip_level_count() != 1
80 || texture.sample_count() != 1
81 || size.depth_or_array_layers != 1
82 {
83 return Err(Error::invalid_argument(
84 "each texture must be 2D with one layer, mip level and sample, and render-attachment usage",
85 ));
86 }
87 }
88 Ok(())
89 }
90
91 fn format(&self) -> Option<wgpu::TextureFormat> {
92 self.textures.first().map(wgpu::Texture::format)
93 }
94
95 fn depth_format(&self) -> Option<wgpu::TextureFormat> {
96 self.depth_textures.first().map(wgpu::Texture::format)
97 }
98}
99
100#[must_use]
102pub fn depth_stencil_format(format: wgpu::TextureFormat) -> Option<DepthStencilFormat> {
103 match format {
104 wgpu::TextureFormat::Depth24PlusStencil8 => Some(DepthStencilFormat::Depth24Stencil8),
105 wgpu::TextureFormat::Depth32FloatStencil8 => Some(DepthStencilFormat::Depth32FloatStencil8),
106 _ => None,
107 }
108}
109
110pub struct BorrowedTarget {
112 device: wgpu::Device,
113 textures: Option<BorrowedTextures>,
115 selected: usize,
117 producer: SyncKind,
118 depth_stencil_format: wgpu::TextureFormat,
119 depth_stencil: Option<wgpu::Texture>,
122 imports: Option<(usize, FrameImage)>,
125}
126
127impl BorrowedTarget {
128 pub fn new(backend: &RendererBackend, textures: BorrowedTextures, producer: SyncKind) -> Result<Self, Error> {
136 textures.check()?;
137 if !BorrowedTextures::sync_kinds().0.contains(producer) {
138 return Err(Error::unsupported(format!("a WebGPU target hands frames over with no {producer:?}")));
139 }
140 let device = backend.device().device().clone();
141 let depth_stencil_format = if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
142 wgpu::TextureFormat::Depth32FloatStencil8
143 } else {
144 wgpu::TextureFormat::Depth24PlusStencil8
145 };
146 Ok(BorrowedTarget {
147 device,
148 textures: Some(textures),
149 selected: 0,
150 producer,
151 depth_stencil_format,
152 depth_stencil: None,
153 imports: None,
154 })
155 }
156
157 pub fn select(&mut self, slot: usize) {
159 self.selected = slot;
160 }
161
162 #[expect(
165 clippy::needless_pass_by_value,
166 reason = "the release takes the host's sync, as every backend's does, and drops it"
167 )]
168 pub fn release(&mut self, _slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
169 match consumer.sync.kind {
170 SyncKind::CpuComplete | SyncKind::QueueOrder => Ok(()),
171 kind => Err(Error::unsupported(format!("the WebGPU target waits for no {kind:?}"))),
172 }
173 }
174
175 pub fn discard(&mut self, _slot: usize) {}
178
179 pub fn replace(&mut self, gpu: &mut WebGpu, textures: BorrowedTextures) -> Result<GpuSync, Error> {
191 let Some(current) = &self.textures else {
192 return Err(Error::invalid_state("the ring let go of its textures"));
193 };
194 if textures.textures.len() != current.textures.len() {
195 return Err(Error::invalid_argument("a ring keeps its depth"));
196 }
197 if (textures.format(), textures.depth_format()) != (current.format(), current.depth_format()) {
198 return Err(Error::unsupported("a ring keeps its formats, and its depth textures or their lack"));
199 }
200 textures.check()?;
201 let sync = self.end_work(gpu)?;
202 self.textures = Some(textures);
203 Ok(sync)
204 }
205
206 pub fn release_textures(&mut self, gpu: &mut WebGpu) -> Result<GpuSync, Error> {
216 if self.textures.is_none() {
217 return Err(Error::invalid_state("the ring let go of its textures"));
218 }
219 let sync = self.end_work(gpu)?;
220 self.textures = None;
221 self.depth_stencil = None;
222 Ok(sync)
223 }
224
225 fn end_work(&mut self, gpu: &mut WebGpu) -> Result<GpuSync, Error> {
228 if let Some((_, image)) = self.imports.take() {
229 destroy_imports(gpu, image);
230 }
231 let wait = self.producer == SyncKind::CpuComplete;
232 gpu.flush(wait).map_err(|error| Error::native(format!("Submitting a ring's frames failed: {error}")))?;
233 Ok(GpuSync::of(self.producer))
234 }
235}
236
237fn own_depth_stencil(
240 device: &wgpu::Device,
241 format: wgpu::TextureFormat,
242 own: &mut Option<wgpu::Texture>,
243 size: Size,
244) -> wgpu::Texture {
245 match own {
246 Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture.clone(),
247 _ => own
248 .insert(device.create_texture(&wgpu::TextureDescriptor {
249 label: Some("borrowed ring depth and stencil"),
250 size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
251 mip_level_count: 1,
252 sample_count: 1,
253 dimension: wgpu::TextureDimension::D2,
254 format,
255 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
256 view_formats: &[],
257 }))
258 .clone(),
259 }
260}
261
262fn destroy_imports(gpu: &mut WebGpu, image: FrameImage) {
263 let imports = [Some(image.color), image.depth_stencil].into_iter().flatten();
264 destroy_unused(gpu, imports.map(ResourceId::Texture));
265}
266
267impl FrameTarget for BorrowedTarget {
268 type Gpu = WebGpu;
269
270 fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
271 let slot = self.selected;
272 match self.imports {
273 Some((imported, image)) if imported == slot => return Some(image),
274 Some((_, image)) => {
276 self.imports = None;
277 destroy_imports(gpu, image);
278 }
279 None => {}
280 }
281 let textures = self.textures.as_ref()?;
282 let texture = textures.textures.get(slot)?.clone();
283 let depth_stencil = match textures.depth_textures.get(slot) {
286 Some(depth) => depth.clone(),
287 None => own_depth_stencil(&self.device, self.depth_stencil_format, &mut self.depth_stencil, textures.size),
288 };
289 let image = FrameImage {
290 size: textures.size,
291 color: gpu.import_texture(&texture),
292 depth_stencil: Some(gpu.import_texture(&depth_stencil)),
293 targets: TargetFormats {
294 color: from_wgpu_format(texture.format()),
295 depth_stencil: from_wgpu_format(depth_stencil.format()),
296 },
297 };
298 self.imports = Some((slot, image));
299 Some(image)
300 }
301
302 fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
303 let Some((_, image)) = self.imports.take() else {
304 return Handoff::Dropped;
305 };
306 destroy_imports(gpu, image);
307 let sync = if self.producer == SyncKind::QueueOrder {
308 GpuSync::of(SyncKind::QueueOrder)
309 } else {
310 if let Err(error) = gpu.flush(true) {
311 log::error!(
312 target: log_target::RENDER,
313 "WebGPU: waiting for a borrowed texture's frame failed: {error}"
314 );
315 return Handoff::Dropped;
316 }
317 GpuSync::of(SyncKind::CpuComplete)
318 };
319 Handoff::GivenBack { slot: self.selected, sync }
320 }
321
322 fn tear_down(&mut self, gpu: &mut WebGpu) {
324 if let Some((_, image)) = self.imports.take() {
325 destroy_imports(gpu, image);
326 }
327 }
328}