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