1use super::{
4 Arc, GpuTimingBatch, GpuTimingStatistics, INITIAL_VERTEX_CAPACITY, ImageRenderer,
5 LogicalScreenPosition, LogicalViewport, Mesh3dRenderer, PhysicalScreenPosition,
6 PipelineResources, RendererConfigurationError, RendererCoordinateError, RendererInitError,
7 RendererSurfacePresentMode, WgpuRenderer, WgpuRendererOptions, create_multisample_target,
8 create_pipeline, create_submitted_particle_unit_buffer, create_vertex_buffer, frame,
9 gpu_timing, invoke_pre_present_notify, logical_to_physical_screen, physical_to_logical_screen,
10 preferred_sample_count, select_surface_present_mode, validate_scale_factor,
11 validate_surface_dimensions,
12};
13
14impl WgpuRenderer {
15 pub async fn new(
22 surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
23 width: u32,
24 height: u32,
25 ) -> Result<Self, RendererInitError> {
26 Self::new_with_options(
27 surface_target,
28 width,
29 height,
30 WgpuRendererOptions::default(),
31 )
32 .await
33 }
34
35 pub async fn new_with_options(
40 surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
41 width: u32,
42 height: u32,
43 options: WgpuRendererOptions,
44 ) -> Result<Self, RendererInitError> {
45 let instance =
46 wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
47 let surface = instance
48 .create_surface(surface_target)
49 .map_err(RendererInitError::CreateSurface)?;
50 let adapter = instance
51 .request_adapter(&wgpu::RequestAdapterOptions {
52 power_preference: wgpu::PowerPreference::HighPerformance,
53 force_fallback_adapter: false,
54 compatible_surface: Some(&surface),
55 apply_limit_buckets: false,
56 })
57 .await
58 .map_err(RendererInitError::RequestAdapter)?;
59 let adapter_info = adapter.get_info();
60
61 let (device, queue) = adapter
62 .request_device(&wgpu::DeviceDescriptor {
63 label: Some("sim-engine device"),
64 required_features: gpu_timing::requested_features(
65 adapter.features(),
66 options.gpu_timing(),
67 ),
68 required_limits: wgpu::Limits::default(),
69 experimental_features: wgpu::ExperimentalFeatures::disabled(),
70 memory_hints: wgpu::MemoryHints::Performance,
71 trace: wgpu::Trace::Off,
72 })
73 .await
74 .map_err(RendererInitError::RequestDevice)?;
75
76 let width = width.max(1);
77 let height = height.max(1);
78 let dimension_limit = device.limits().max_texture_dimension_2d;
79 if width > dimension_limit || height > dimension_limit {
80 return Err(RendererInitError::SurfaceDimensionsTooLarge {
81 width,
82 height,
83 limit: dimension_limit,
84 });
85 }
86 let surface_capabilities = surface.get_capabilities(&adapter);
87 let mut config = surface
88 .get_default_config(&adapter, width, height)
89 .ok_or(RendererInitError::NoSurfaceConfig)?;
90 let surface_present_mode = select_surface_present_mode(
91 options.present_mode(),
92 &surface_capabilities.present_modes,
93 );
94 config.present_mode = surface_present_mode.to_wgpu();
95 surface.configure(&device, &config);
96
97 let sample_count = preferred_sample_count(&adapter, config.format);
98 let PipelineResources {
99 pipeline,
100 target_pipeline,
101 dynamic_pipeline,
102 particle_pipeline,
103 target_particle_pipeline,
104 heatmap_pipeline,
105 target_heatmap_pipeline,
106 composition_pipelines,
107 target_composition_pipelines,
108 camera_uniform_buffer,
109 camera_bind_group,
110 camera_bind_group_layout,
111 heatmap_uniform_buffer,
112 heatmap_bind_group_layout,
113 } = create_pipeline(&device, config.format, sample_count);
114 let vertex_buffer = Arc::new(create_vertex_buffer(&device, INITIAL_VERTEX_CAPACITY));
115 let particle_unit_buffer = create_submitted_particle_unit_buffer(&device, &queue);
116 let multisample_target = create_multisample_target(&device, &config, sample_count);
117 let image_renderer = ImageRenderer::new(&device, config.format, sample_count);
118 let mesh3d_renderer = Mesh3dRenderer::new(&device, config.format);
119 let gpu_timing = gpu_timing::GpuTimingCollector::new(&device, &queue, options.gpu_timing());
120
121 Ok(Self {
122 renderer_identity: Arc::new(()),
123 _instance: instance,
124 surface,
125 _adapter: adapter,
126 adapter_info,
127 device,
128 queue,
129 config,
130 requested_present_mode: options.present_mode(),
131 surface_present_mode,
132 pre_present_notify: None,
133 scale_factor: options.scale_factor(),
134 pipeline,
135 target_pipeline,
136 dynamic_pipeline,
137 particle_pipeline,
138 target_particle_pipeline,
139 heatmap_pipeline,
140 target_heatmap_pipeline,
141 composition_pipelines,
142 target_composition_pipelines,
143 image_renderer,
144 mesh3d_renderer,
145 gpu_timing,
146 gpu_timing_requested: options.gpu_timing(),
147 camera_uniform_buffer,
148 camera_bind_group,
149 camera_bind_group_layout,
150 heatmap_uniform_buffer,
151 heatmap_bind_group_layout,
152 color_map_cache: None,
153 frame_cache: frame::FrameCache::default(),
154 vertex_buffer,
155 particle_unit_buffer,
156 vertex_capacity: INITIAL_VERTEX_CAPACITY,
157 multisample_target,
158 sample_count,
159 vertices: Vec::new(),
160 draw_batches: Vec::new(),
161 retired_devices: Vec::new(),
162 max_quarantined_devices: options.max_quarantined_devices(),
163 })
164 }
165
166 pub fn size(&self) -> (u32, u32) {
168 (self.config.width, self.config.height)
169 }
170
171 pub fn gpu_timing_statistics(&self) -> GpuTimingStatistics {
174 self.gpu_timing.statistics()
175 }
176
177 pub fn collect_gpu_timings(&mut self) -> GpuTimingBatch {
185 self.gpu_timing.collect(&self.device)
186 }
187
188 pub fn logical_size(&self) -> (f32, f32) {
193 let scale_factor = self.scale_factor as f32;
194 (
195 self.config.width as f32 / scale_factor,
196 self.config.height as f32 / scale_factor,
197 )
198 }
199
200 pub fn logical_viewport(&self) -> Result<LogicalViewport, crate::LogicalViewportError> {
202 let (width, height) = self.logical_size();
203 LogicalViewport::new(width, height)
204 }
205
206 pub fn physical_to_logical_screen(
208 &self,
209 position: PhysicalScreenPosition,
210 ) -> Result<LogicalScreenPosition, RendererCoordinateError> {
211 physical_to_logical_screen(position, self.scale_factor as f32)
212 }
213
214 pub fn logical_to_physical_screen(
216 &self,
217 position: LogicalScreenPosition,
218 ) -> Result<PhysicalScreenPosition, RendererCoordinateError> {
219 logical_to_physical_screen(position, self.scale_factor as f32)
220 }
221
222 pub fn scale_factor(&self) -> f64 {
224 self.scale_factor
225 }
226
227 pub fn surface_present_mode(&self) -> RendererSurfacePresentMode {
233 self.surface_present_mode
234 }
235
236 pub fn set_pre_present_notify(&mut self, notify: impl Fn() + Send + Sync + 'static) {
245 self.pre_present_notify = Some(Arc::new(notify));
246 }
247
248 pub fn clear_pre_present_notify(&mut self) {
250 self.pre_present_notify = None;
251 }
252
253 pub(super) fn notify_before_present(&self) {
254 invoke_pre_present_notify(
255 self.surface_present_mode,
256 self.pre_present_notify.as_deref(),
257 );
258 }
259
260 pub fn adapter_name(&self) -> &str {
262 &self.adapter_info.name
263 }
264
265 pub fn adapter_backend(&self) -> &'static str {
267 self.adapter_info.backend.to_str()
268 }
269
270 pub fn adapter_vendor_id(&self) -> u32 {
272 self.adapter_info.vendor
273 }
274
275 pub fn adapter_device_id(&self) -> u32 {
277 self.adapter_info.device
278 }
279
280 pub fn adapter_pci_bus_id(&self) -> &str {
287 &self.adapter_info.device_pci_bus_id
288 }
289
290 pub fn surface_format(&self) -> wgpu::TextureFormat {
292 self.config.format
293 }
294
295 pub fn surface_sample_count(&self) -> u32 {
297 self.sample_count
298 }
299
300 pub fn adapter_driver(&self) -> &str {
302 &self.adapter_info.driver
303 }
304
305 pub fn adapter_driver_info(&self) -> &str {
307 &self.adapter_info.driver_info
308 }
309
310 pub fn quarantined_device_count(&self) -> usize {
312 self.retired_devices.len()
313 }
314
315 pub fn max_quarantined_device_count(&self) -> usize {
317 self.max_quarantined_devices
318 }
319
320 pub fn remaining_device_recoveries(&self) -> usize {
322 self.max_quarantined_devices
323 .saturating_sub(self.retired_devices.len())
324 }
325
326 pub fn wait_for_gpu_idle(&self) -> Result<(), wgpu::PollError> {
332 self.device
333 .poll(wgpu::PollType::wait_indefinitely())
334 .map(|_| ())
335 }
336
337 pub fn set_scale_factor(
341 &mut self,
342 scale_factor: f64,
343 ) -> Result<(), RendererConfigurationError> {
344 validate_scale_factor(scale_factor)?;
345 self.scale_factor = scale_factor;
346 Ok(())
347 }
348
349 pub fn resize(&mut self, width: u32, height: u32) -> Result<(), RendererConfigurationError> {
354 if width == 0 || height == 0 {
355 return Ok(());
356 }
357 validate_surface_dimensions(width, height, self.device.limits().max_texture_dimension_2d)?;
358
359 self.config.width = width;
360 self.config.height = height;
361 self.surface.configure(&self.device, &self.config);
362 self.multisample_target =
363 create_multisample_target(&self.device, &self.config, self.sample_count);
364 Ok(())
365 }
366
367 pub fn resize_with_scale_factor(
373 &mut self,
374 width: u32,
375 height: u32,
376 scale_factor: f64,
377 ) -> Result<(), RendererConfigurationError> {
378 validate_scale_factor(scale_factor)?;
379 if width != 0 && height != 0 {
380 validate_surface_dimensions(
381 width,
382 height,
383 self.device.limits().max_texture_dimension_2d,
384 )?;
385 }
386 self.resize(width, height)?;
387 self.scale_factor = scale_factor;
388 Ok(())
389 }
390}