1use std::sync::{Arc, Mutex};
4
5use cadkit_scene::MeshScene;
6
7use crate::{GpuError, MeshRenderer, OrbitCamera, PreparedMeshes, check, linear, scopes};
8
9#[derive(Debug, Clone, PartialEq, Eq)]
11#[non_exhaustive]
12pub struct AdapterSummary {
13 pub name: String,
15 pub backend: String,
17 pub device_type: String,
19 pub driver: String,
21}
22
23impl AdapterSummary {
24 pub fn new(info: &wgpu::AdapterInfo) -> Self {
26 Self {
27 name: info.name.clone(),
28 backend: format!("{:?}", info.backend),
29 device_type: format!("{:?}", info.device_type),
30 driver: info.driver.clone(),
31 }
32 }
33}
34
35#[non_exhaustive]
38pub struct RenderedTexture {
39 pub texture: wgpu::Texture,
41 pub view: wgpu::TextureView,
43 pub width: u32,
45 pub height: u32,
47}
48
49#[derive(Default)]
50struct ColorPool {
51 size: [u32; 2],
52 available: Vec<RenderedTexture>,
53}
54
55#[derive(Clone, Default)]
57pub struct RenderTextureRecycler {
58 pool: Arc<Mutex<ColorPool>>,
59}
60
61impl RenderTextureRecycler {
62 pub fn recycle(&self, image: RenderedTexture) {
64 if let Ok(mut pool) = self.pool.lock()
65 && pool.size == [image.width, image.height]
66 && pool.available.len() < 2
67 {
68 pool.available.push(image);
69 }
70 }
71}
72
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
75#[non_exhaustive]
76pub struct RenderTargetStats {
77 pub color_allocations: u64,
79 pub color_reuses: u64,
81 pub depth_allocations: u64,
83}
84
85#[derive(Default)]
87pub struct RenderTargetCache {
88 background: Option<wgpu::Color>,
89 recycler: RenderTextureRecycler,
90 depth: Option<([u32; 2], wgpu::Texture)>,
91 stats: RenderTargetStats,
92}
93
94impl RenderTargetCache {
95 pub fn set_background_srgb(&mut self, rgb: [u8; 3]) {
97 self.background = Some(wgpu::Color {
98 r: linear(rgb[0]),
99 g: linear(rgb[1]),
100 b: linear(rgb[2]),
101 a: 1.,
102 });
103 }
104
105 pub fn recycler(&self) -> RenderTextureRecycler {
107 self.recycler.clone()
108 }
109
110 pub fn stats(&self) -> RenderTargetStats {
112 self.stats
113 }
114}
115
116pub async fn render_texture(
118 device: &wgpu::Device,
119 queue: &wgpu::Queue,
120 renderer: &MeshRenderer,
121 prepared: &PreparedMeshes,
122 width: u32,
123 height: u32,
124) -> Result<RenderedTexture, GpuError> {
125 render_texture_cached(
126 device,
127 queue,
128 renderer,
129 prepared,
130 width,
131 height,
132 &mut RenderTargetCache::default(),
133 )
134 .await
135}
136
137pub async fn render_texture_cached(
140 device: &wgpu::Device,
141 queue: &wgpu::Queue,
142 renderer: &MeshRenderer,
143 prepared: &PreparedMeshes,
144 width: u32,
145 height: u32,
146 targets: &mut RenderTargetCache,
147) -> Result<RenderedTexture, GpuError> {
148 let max = device.limits().max_texture_dimension_2d;
149 if width == 0 || height == 0 || width > max || height > max {
150 return Err(GpuError::TextureSize(width, height));
151 }
152 let (validation, allocation) = scopes(device);
153 let texture = |format, usage| {
154 device.create_texture(&wgpu::TextureDescriptor {
155 label: Some("cadkit offscreen attachment"),
156 size: wgpu::Extent3d {
157 width,
158 height,
159 depth_or_array_layers: 1,
160 },
161 mip_level_count: 1,
162 sample_count: 1,
163 dimension: wgpu::TextureDimension::D2,
164 format,
165 usage,
166 view_formats: if format == wgpu::TextureFormat::Rgba8UnormSrgb {
167 &[wgpu::TextureFormat::Rgba8Unorm]
168 } else {
169 &[]
170 },
171 })
172 };
173 let size = [width, height];
174 let available = {
175 let mut pool = targets
176 .recycler
177 .pool
178 .lock()
179 .map_err(|_| GpuError::Device("texture pool lock poisoned".into()))?;
180 if pool.size != size {
181 pool.size = size;
182 pool.available.clear();
183 }
184 pool.available.pop()
185 };
186 let output = if let Some(image) = available {
187 targets.stats.color_reuses += 1;
188 image.texture
189 } else {
190 targets.stats.color_allocations += 1;
191 texture(
192 wgpu::TextureFormat::Rgba8UnormSrgb,
193 wgpu::TextureUsages::RENDER_ATTACHMENT
194 | wgpu::TextureUsages::COPY_SRC
195 | wgpu::TextureUsages::TEXTURE_BINDING,
196 )
197 };
198 let depth = match &targets.depth {
199 Some((old, depth)) if *old == size => depth,
200 _ => {
201 targets.stats.depth_allocations += 1;
202 let depth = texture(
203 wgpu::TextureFormat::Depth32Float,
204 wgpu::TextureUsages::RENDER_ATTACHMENT,
205 );
206 &targets.depth.insert((size, depth)).1
207 }
208 };
209 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
210 label: Some("cadkit mesh commands"),
211 });
212 {
213 let color = output.create_view(&Default::default());
214 let depth = depth.create_view(&Default::default());
215 let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
216 label: Some("cadkit mesh pass"),
217 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
218 view: &color,
219 resolve_target: None,
220 depth_slice: None,
221 ops: wgpu::Operations {
222 load: wgpu::LoadOp::Clear(targets.background.unwrap_or(wgpu::Color {
223 r: 0.025,
224 g: 0.035,
225 b: 0.05,
226 a: 1.,
227 })),
228 store: wgpu::StoreOp::Store,
229 },
230 })],
231 depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
232 view: &depth,
233 depth_ops: Some(wgpu::Operations {
234 load: wgpu::LoadOp::Clear(1.),
235 store: wgpu::StoreOp::Discard,
236 }),
237 stencil_ops: None,
238 }),
239 occlusion_query_set: None,
240 timestamp_writes: None,
241 multiview_mask: None,
242 });
243 renderer.paint(&mut pass, prepared);
244 }
245 let submission = queue.submit([encoder.finish()]);
246 device
248 .poll(wgpu::PollType::Wait {
249 submission_index: Some(submission),
250 timeout: Some(std::time::Duration::from_secs(15)),
251 })
252 .map_err(|error| GpuError::Poll(error.to_string()))?;
253 check(validation, allocation).await?;
254 let view = output.create_view(&wgpu::TextureViewDescriptor {
255 format: Some(wgpu::TextureFormat::Rgba8Unorm),
256 ..Default::default()
257 });
258 Ok(RenderedTexture {
259 texture: output,
260 view,
261 width,
262 height,
263 })
264}
265
266#[derive(Debug, Clone, PartialEq, Eq)]
268#[non_exhaustive]
269pub struct OffscreenImage {
270 pub width: u32,
272 pub height: u32,
274 pub rgba: Vec<u8>,
276 pub adapter: AdapterSummary,
278}
279
280pub async fn render_offscreen(
284 scene: &MeshScene,
285 camera: OrbitCamera,
286 width: u32,
287 height: u32,
288) -> Result<OffscreenImage, GpuError> {
289 if width == 0 || height == 0 || width > 4096 || height > 4096 {
290 return Err(GpuError::TextureSize(width, height));
291 }
292 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
293 let adapter = instance
294 .request_adapter(&wgpu::RequestAdapterOptions {
295 power_preference: wgpu::PowerPreference::HighPerformance,
296 force_fallback_adapter: false,
297 compatible_surface: None,
298 ..Default::default()
299 })
300 .await
301 .map_err(|error| GpuError::AdapterUnavailable(error.to_string()))?;
302 let summary = AdapterSummary::new(&adapter.get_info());
303 let (device, queue) = adapter
304 .request_device(&wgpu::DeviceDescriptor {
305 label: Some("cadkit offscreen"),
306 ..Default::default()
307 })
308 .await
309 .map_err(|error| GpuError::DeviceUnavailable(error.to_string()))?;
310 let errors = Arc::new(Mutex::new(Vec::<GpuError>::new()));
311 let sink = Arc::clone(&errors);
312 device.on_uncaptured_error(Arc::new(move |error: wgpu::Error| {
313 if let Ok(mut errors) = sink.lock() {
314 errors.push(GpuError::Device(error.to_string()));
315 }
316 }));
317 let sink = Arc::clone(&errors);
318 device.set_device_lost_callback(move |reason, message| {
319 if let Ok(mut errors) = sink.lock() {
320 errors.push(GpuError::Device(format!("{reason:?}: {message}")));
321 }
322 });
323 let rgba = render_pixels(&device, &queue, scene, camera, width, height).await?;
324 if let Some(error) = errors
325 .lock()
326 .map_err(|_| GpuError::Device("error channel poisoned".into()))?
327 .pop()
328 {
329 return Err(error);
330 }
331 Ok(OffscreenImage {
332 width,
333 height,
334 rgba,
335 adapter: summary,
336 })
337}
338
339pub async fn render_offscreen_with(
342 device: &wgpu::Device,
343 queue: &wgpu::Queue,
344 scene: &MeshScene,
345 camera: OrbitCamera,
346 width: u32,
347 height: u32,
348) -> Result<Vec<u8>, GpuError> {
349 render_pixels(device, queue, scene, camera, width, height).await
350}
351
352async fn render_pixels(
353 device: &wgpu::Device,
354 queue: &wgpu::Queue,
355 scene: &MeshScene,
356 camera: OrbitCamera,
357 width: u32,
358 height: u32,
359) -> Result<Vec<u8>, GpuError> {
360 let (validation, allocation) = scopes(device);
361 let renderer = MeshRenderer::new(device, wgpu::TextureFormat::Rgba8UnormSrgb).await?;
362 let prepared = renderer
363 .prepare(device, scene, camera, width as f32 / height as f32, 1e-4)
364 .await?;
365 let rendered = render_texture(device, queue, &renderer, &prepared, width, height).await?;
366 let rgba = read_texture(device, queue, &rendered.texture, width, height).await;
367 check(validation, allocation).await?;
368 rgba
369}
370
371pub(crate) async fn read_texture(
373 device: &wgpu::Device,
374 queue: &wgpu::Queue,
375 texture: &wgpu::Texture,
376 width: u32,
377 height: u32,
378) -> Result<Vec<u8>, GpuError> {
379 let row = width
380 .checked_mul(4)
381 .ok_or(GpuError::TextureSize(width, height))?;
382 let stride = row.div_ceil(256) * 256;
383 let readback = device.create_buffer(&wgpu::BufferDescriptor {
384 label: Some("cadkit readback"),
385 size: u64::from(stride) * u64::from(height),
386 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
387 mapped_at_creation: false,
388 });
389 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
390 label: Some("cadkit readback commands"),
391 });
392 encoder.copy_texture_to_buffer(
393 wgpu::TexelCopyTextureInfo {
394 texture,
395 mip_level: 0,
396 origin: wgpu::Origin3d::ZERO,
397 aspect: wgpu::TextureAspect::All,
398 },
399 wgpu::TexelCopyBufferInfo {
400 buffer: &readback,
401 layout: wgpu::TexelCopyBufferLayout {
402 offset: 0,
403 bytes_per_row: Some(stride),
404 rows_per_image: Some(height),
405 },
406 },
407 wgpu::Extent3d {
408 width,
409 height,
410 depth_or_array_layers: 1,
411 },
412 );
413 let submission = queue.submit([encoder.finish()]);
414 let (sender, receiver) = std::sync::mpsc::sync_channel(1);
415 readback
416 .slice(..)
417 .map_async(wgpu::MapMode::Read, move |result| {
418 let _ = sender.send(result);
419 });
420 device
421 .poll(wgpu::PollType::Wait {
422 submission_index: Some(submission),
423 timeout: Some(std::time::Duration::from_secs(15)),
424 })
425 .map_err(|error| GpuError::Poll(error.to_string()))?;
426 receiver
427 .recv_timeout(std::time::Duration::from_secs(2))
428 .map_err(|error| GpuError::Readback(error.to_string()))?
429 .map_err(|error| GpuError::Readback(error.to_string()))?;
430 let mapped = readback
431 .slice(..)
432 .get_mapped_range()
433 .map_err(|error| GpuError::Readback(error.to_string()))?;
434 let row = row as usize;
435 let mut rgba = Vec::with_capacity(row * height as usize);
436 for line in mapped.chunks_exact(stride as usize) {
437 rgba.extend_from_slice(line.get(..row).unwrap_or_default());
438 }
439 drop(mapped);
440 readback.unmap();
441 Ok(rgba)
442}