1use std::cell::{Cell, RefCell};
7use std::rc::Rc;
8
9use mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
10use mln_gfx::gpu::{Gpu as _, ResourceId, TargetFormats};
11use mln_gfx::{ConsumerSync, DepthStencilFormat, DepthStencilFormats, GpuSync, SyncKind, SyncKinds};
12use mln_util::error::Error;
13use mln_util::logging::{Event, Log};
14use mln_util::size::Size;
15
16use crate::gpu::from_wgpu_format;
17use crate::renderer_backend::RendererBackend;
18
19#[derive(Clone, Debug, PartialEq)]
22pub struct BorrowedTextures {
23 pub textures: Vec<wgpu::Texture>,
24 pub size: Size,
25 pub depth_textures: Vec<wgpu::Texture>,
29}
30
31impl BorrowedTextures {
32 #[must_use]
36 pub fn sync_kinds() -> (SyncKinds, SyncKinds) {
37 let kinds = SyncKinds::of(&[SyncKind::CpuComplete, SyncKind::QueueOrder]);
38 (kinds, kinds)
39 }
40
41 #[must_use]
43 pub fn depth_stencil_formats(device: &wgpu::Device) -> DepthStencilFormats {
44 let formats = DepthStencilFormats::of(&[DepthStencilFormat::Depth24Stencil8]);
45 if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
46 formats.with(DepthStencilFormat::Depth32FloatStencil8)
47 } else {
48 formats
49 }
50 }
51
52 pub fn check(&self) -> Result<(), Error> {
61 let Some(first) = self.textures.first() else {
62 return Err(Error::invalid_argument("a ring needs at least one texture"));
63 };
64 if let Some(depth) = self.depth_textures.first() {
65 if self.depth_textures.len() != self.textures.len() {
66 return Err(Error::invalid_argument("a ring's depth textures must be one for each of its textures"));
67 }
68 if depth_stencil_format(depth.format()).is_none() {
69 return Err(Error::unsupported("a ring's depth textures must have a depth and stencil format"));
70 }
71 }
72 for texture in self.textures.iter().chain(&self.depth_textures) {
73 let size = texture.size();
74 if (size.width, size.height) != (self.size.width, self.size.height) {
75 return Err(Error::invalid_argument("each texture's size must match the ring's physical size"));
76 }
77 let kin =
78 if texture.format().is_depth_stencil_format() { self.depth_textures.first() } else { Some(first) };
79 if Some(texture.format()) != kin.map(wgpu::Texture::format) {
80 return Err(Error::invalid_argument("the ring's textures must share a format"));
81 }
82 if !texture.usage().contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
83 || texture.dimension() != wgpu::TextureDimension::D2
84 || texture.mip_level_count() != 1
85 || texture.sample_count() != 1
86 || size.depth_or_array_layers != 1
87 {
88 return Err(Error::invalid_argument(
89 "each texture must be 2D with one layer, mip level and sample, and render-attachment usage",
90 ));
91 }
92 }
93 Ok(())
94 }
95
96 fn format(&self) -> Option<wgpu::TextureFormat> {
97 self.textures.first().map(wgpu::Texture::format)
98 }
99
100 fn depth_format(&self) -> Option<wgpu::TextureFormat> {
101 self.depth_textures.first().map(wgpu::Texture::format)
102 }
103}
104
105#[must_use]
107pub fn depth_stencil_format(format: wgpu::TextureFormat) -> Option<DepthStencilFormat> {
108 match format {
109 wgpu::TextureFormat::Depth24PlusStencil8 => Some(DepthStencilFormat::Depth24Stencil8),
110 wgpu::TextureFormat::Depth32FloatStencil8 => Some(DepthStencilFormat::Depth32FloatStencil8),
111 _ => None,
112 }
113}
114
115pub struct BorrowedTarget {
117 backend: Rc<RendererBackend>,
118 textures: RefCell<BorrowedTextures>,
119 selected: Cell<usize>,
121 producer: SyncKind,
122 depth_stencil_format: wgpu::TextureFormat,
123 depth_stencil: Cell<Option<wgpu::Texture>>,
126 imports: Cell<Option<(usize, FrameImage)>>,
129}
130
131impl BorrowedTarget {
132 pub fn new(backend: Rc<RendererBackend>, textures: BorrowedTextures, producer: SyncKind) -> Result<Self, Error> {
140 textures.check()?;
141 if !BorrowedTextures::sync_kinds().0.contains(producer) {
142 return Err(Error::unsupported(format!("a WebGPU target hands frames over with no {producer:?}")));
143 }
144 let depth_stencil_format =
145 if backend.device().device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
146 wgpu::TextureFormat::Depth32FloatStencil8
147 } else {
148 wgpu::TextureFormat::Depth24PlusStencil8
149 };
150 Ok(BorrowedTarget {
151 backend,
152 textures: RefCell::new(textures),
153 selected: Cell::new(0),
154 producer,
155 depth_stencil_format,
156 depth_stencil: Cell::new(None),
157 imports: Cell::new(None),
158 })
159 }
160
161 pub fn select(&self, slot: usize) {
163 self.selected.set(slot);
164 }
165
166 #[expect(
169 clippy::needless_pass_by_value,
170 reason = "the release takes the host's sync, as every backend's does, and drops it"
171 )]
172 pub fn release(&self, _slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
173 match consumer.sync.kind {
174 SyncKind::CpuComplete | SyncKind::QueueOrder => Ok(()),
175 kind => Err(Error::unsupported(format!("the WebGPU target waits for no {kind:?}"))),
176 }
177 }
178
179 pub fn discard(&self, _slot: usize) {}
182
183 pub fn replace(&self, textures: BorrowedTextures) -> Result<(), Error> {
191 let current = self.textures.borrow();
192 if textures.textures.len() != current.textures.len() {
193 return Err(Error::invalid_argument("a ring keeps its depth"));
194 }
195 if (textures.format(), textures.depth_format()) != (current.format(), current.depth_format()) {
196 return Err(Error::unsupported("a ring keeps its formats, and its depth textures or their lack"));
197 }
198 drop(current);
199 textures.check()?;
200 if let Some((_, image)) = self.imports.take() {
202 self.destroy_imports(image);
203 }
204 *self.textures.borrow_mut() = textures;
205 Ok(())
206 }
207
208 fn depth_stencil(&self, textures: &BorrowedTextures) -> wgpu::Texture {
211 if let Some(depth) = textures.depth_textures.get(self.selected.get()) {
212 return depth.clone();
213 }
214 let size = textures.size;
215 let texture = match self.depth_stencil.take() {
216 Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture,
217 _ => self.backend.device().device().create_texture(&wgpu::TextureDescriptor {
218 label: Some("borrowed ring depth and stencil"),
219 size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
220 mip_level_count: 1,
221 sample_count: 1,
222 dimension: wgpu::TextureDimension::D2,
223 format: self.depth_stencil_format,
224 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
225 view_formats: &[],
226 }),
227 };
228 self.depth_stencil.set(Some(texture.clone()));
229 texture
230 }
231
232 fn destroy_imports(&self, image: FrameImage) {
233 let mut gpu = self.backend.gpu();
234 for import in [Some(image.color), image.depth_stencil].into_iter().flatten() {
235 gpu.destroy(ResourceId::Texture(import));
236 }
237 }
238}
239
240impl Drop for BorrowedTarget {
241 fn drop(&mut self) {
243 if let Some((_, image)) = self.imports.take() {
244 self.destroy_imports(image);
245 }
246 }
247}
248
249impl FrameTarget for BorrowedTarget {
250 fn begin_frame(&self) -> Option<FrameImage> {
251 let slot = self.selected.get();
252 match self.imports.take() {
253 Some((imported, image)) if imported == slot => {
254 self.imports.set(Some((imported, image)));
255 return Some(image);
256 }
257 Some((_, image)) => self.destroy_imports(image),
259 None => {}
260 }
261 let textures = self.textures.borrow();
262 let texture = textures.textures.get(slot)?;
263 let depth_stencil = self.depth_stencil(&textures);
264 let mut gpu = self.backend.gpu();
265 let image = FrameImage {
266 size: textures.size,
267 color: gpu.import_texture(texture),
268 depth_stencil: Some(gpu.import_texture(&depth_stencil)),
269 targets: TargetFormats {
270 color: from_wgpu_format(texture.format()),
271 depth_stencil: from_wgpu_format(depth_stencil.format()),
272 },
273 };
274 self.imports.set(Some((slot, image)));
275 Some(image)
276 }
277
278 fn end_frame(&self) -> Handoff {
279 let Some((_, image)) = self.imports.take() else {
280 return Handoff::Dropped;
281 };
282 self.destroy_imports(image);
283 let sync = if self.producer == SyncKind::QueueOrder {
284 GpuSync::of(SyncKind::QueueOrder)
285 } else {
286 if let Err(error) = self.backend.gpu().flush(true) {
287 Log::error(Event::Render, format!("WebGPU: waiting for a borrowed texture's frame failed: {error}"));
288 return Handoff::Dropped;
289 }
290 GpuSync::of(SyncKind::CpuComplete)
291 };
292 Handoff::GivenBack { slot: self.selected.get(), sync }
293 }
294}