1use ::wgpu;
4use std::eprintln;
5use std::string::String;
6use std::sync::Arc;
7use std::vec::Vec;
8
9use crate::motion::DrawOp;
10use crate::solver::Region;
11use crate::style::Color;
12
13use super::pipeline::WgpuRenderer;
14use super::{block_on, create_wgpu_instance};
15
16pub struct PreparedWgpuContext {
22 precompiled_renderer: Option<(wgpu::TextureFormat, WgpuRenderer)>,
24 queue: wgpu::Queue,
25 device: wgpu::Device,
26 adapter: Option<wgpu::Adapter>,
27 instance: Option<wgpu::Instance>,
28 adapter_name: String,
29 backend_name: &'static str,
30 adapter_luid: Option<[u8; 8]>,
31 device_uuid: Option<[u8; 16]>,
32}
33
34unsafe impl Send for PreparedWgpuContext {}
37
38impl PreparedWgpuContext {
39 fn try_init_headless_with_backends(backends: wgpu::Backends) -> Option<Self> {
40 let trace = std::env::var_os("VELOX_STARTUP_TRACE").is_some();
41 let t0 = std::time::Instant::now();
42 let instance = create_wgpu_instance(backends);
43 let t_inst = t0.elapsed();
44
45 let adapter = if std::env::var_os("WGPU_ADAPTER_NAME").is_some()
46 || std::env::var_os("WGPU_POWER_PREFERENCE").is_some()
47 {
48 block_on(wgpu::util::initialize_adapter_from_env_or_default(
49 &instance, None,
50 ))
51 .ok()?
52 } else {
53 block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
54 power_preference: wgpu::PowerPreference::LowPower,
55 compatible_surface: None,
56 force_fallback_adapter: false,
57 ..Default::default()
58 }))
59 .ok()?
60 };
61 let t_adap = t0.elapsed();
62
63 let info = adapter.get_info();
64 if info.device_type == wgpu::DeviceType::Cpu {
65 return None;
66 }
67
68 let required_limits = wgpu::Limits {
69 max_inter_stage_shader_variables: 15,
70 ..wgpu::Limits::default()
71 };
72
73 let (device, queue) = block_on(adapter.request_device(&wgpu::DeviceDescriptor {
74 label: Some("velox_wgpu_device"),
75 required_features: wgpu::Features::empty(),
76 required_limits,
77 memory_hints: wgpu::MemoryHints::MemoryUsage,
78 trace: wgpu::Trace::default(),
79 experimental_features: wgpu::ExperimentalFeatures::default(),
80 }))
81 .ok()?;
82 let t_dev = t0.elapsed();
83
84 device.on_uncaptured_error(Arc::new(|err| {
85 eprintln!("[velox::gpu] WGPU uncaptured error: {err:?}");
86 }));
87
88 let preferred_fmt = wgpu::TextureFormat::Bgra8Unorm;
90 let renderer = WgpuRenderer::new(&device, preferred_fmt);
91 let t_ren = t0.elapsed();
92
93 let backend_name = match info.backend {
94 wgpu::Backend::Dx12 => "DX12",
95 wgpu::Backend::Vulkan => "Vulkan",
96 wgpu::Backend::Metal => "Metal",
97 wgpu::Backend::Gl => "OpenGL",
98 wgpu::Backend::BrowserWebGpu => "WebGPU",
99 wgpu::Backend::Noop => "Noop",
100 };
101
102 if trace {
103 std::println!(
104 "[VELOX_STARTUP_TRACE] async bg wgpu warmup ({} / {}): instance={:.1}ms, adapter=+{:.1}ms, device=+{:.1}ms, precompile_pipeline=+{:.1}ms, total={:.1}ms",
105 info.name,
106 backend_name,
107 t_inst.as_secs_f64() * 1000.0,
108 (t_adap - t_inst).as_secs_f64() * 1000.0,
109 (t_dev - t_adap).as_secs_f64() * 1000.0,
110 (t_ren - t_dev).as_secs_f64() * 1000.0,
111 t_ren.as_secs_f64() * 1000.0,
112 );
113 }
114
115 Some(Self {
116 precompiled_renderer: Some((preferred_fmt, renderer)),
117 queue,
118 device,
119 adapter: Some(adapter),
120 instance: Some(instance),
121 adapter_name: info.name,
122 backend_name,
123 adapter_luid: None,
124 device_uuid: None,
125 })
126 }
127
128 pub fn init_headless() -> Option<Self> {
130 if let Some(env_backends) = wgpu::Backends::from_env() {
131 return Self::try_init_headless_with_backends(env_backends);
132 }
133 #[cfg(target_os = "windows")]
134 {
135 if let Some(ctx) = Self::try_init_headless_with_backends(wgpu::Backends::DX12) {
136 return Some(ctx);
137 }
138 Self::try_init_headless_with_backends(wgpu::Backends::VULKAN)
139 }
140 #[cfg(not(target_os = "windows"))]
141 {
142 Self::try_init_headless_with_backends(wgpu::Backends::PRIMARY)
143 }
144 }
145
146 pub fn from_shared_device(
151 device: wgpu::Device,
152 queue: wgpu::Queue,
153 adapter: Option<wgpu::Adapter>,
154 instance: Option<wgpu::Instance>,
155 preferred_format: wgpu::TextureFormat,
156 adapter_name: impl Into<String>,
157 backend_name: &'static str,
158 ) -> Self {
159 let renderer = WgpuRenderer::new(&device, preferred_format);
160 Self {
161 precompiled_renderer: Some((preferred_format, renderer)),
162 queue,
163 device,
164 adapter,
165 instance,
166 adapter_name: adapter_name.into(),
167 backend_name,
168 adapter_luid: None,
169 device_uuid: None,
170 }
171 }
172
173 pub fn from_host_adapter_id(
179 adapter_luid: Option<[u8; 8]>,
180 device_uuid: Option<[u8; 16]>,
181 ) -> Option<Self> {
182 #[cfg(feature = "gpu-interop")]
183 {
184 if let Some(ctx) = super::interop::init_aligned_wgpu_context(adapter_luid, device_uuid) {
185 return Some(ctx);
186 }
187 }
188 let mut ctx = Self::init_headless()?;
189 ctx.adapter_luid = adapter_luid;
190 ctx.device_uuid = device_uuid;
191 Some(ctx)
192 }
193
194 #[cfg(feature = "gpu-interop")]
196 #[allow(clippy::too_many_arguments)]
197 pub(crate) fn from_interop_parts(
198 instance: wgpu::Instance,
199 adapter: wgpu::Adapter,
200 device: wgpu::Device,
201 queue: wgpu::Queue,
202 preferred_format: wgpu::TextureFormat,
203 adapter_name: String,
204 backend_name: &'static str,
205 adapter_luid: Option<[u8; 8]>,
206 device_uuid: Option<[u8; 16]>,
207 ) -> Self {
208 let renderer = WgpuRenderer::new(&device, preferred_format);
209 Self {
210 precompiled_renderer: Some((preferred_format, renderer)),
211 queue,
212 device,
213 adapter: Some(adapter),
214 instance: Some(instance),
215 adapter_name,
216 backend_name,
217 adapter_luid,
218 device_uuid,
219 }
220 }
221
222 #[inline]
224 pub fn device(&self) -> &wgpu::Device {
225 &self.device
226 }
227
228 #[inline]
230 pub fn queue(&self) -> &wgpu::Queue {
231 &self.queue
232 }
233
234 #[inline]
236 pub fn adapter(&self) -> Option<&wgpu::Adapter> {
237 self.adapter.as_ref()
238 }
239
240 #[inline]
242 pub fn instance(&self) -> Option<&wgpu::Instance> {
243 self.instance.as_ref()
244 }
245
246 #[inline]
248 pub fn adapter_name(&self) -> &str {
249 &self.adapter_name
250 }
251
252 #[inline]
254 pub const fn backend_name(&self) -> &'static str {
255 self.backend_name
256 }
257
258 #[inline]
260 pub const fn adapter_luid(&self) -> Option<[u8; 8]> {
261 self.adapter_luid
262 }
263
264 #[inline]
266 pub const fn device_uuid(&self) -> Option<[u8; 16]> {
267 self.device_uuid
268 }
269
270 pub fn take_or_create_renderer(&mut self, format: wgpu::TextureFormat) -> WgpuRenderer {
272 match self.precompiled_renderer.take() {
273 Some((fmt, r)) if fmt == format => r,
274 _ => WgpuRenderer::new(&self.device, format),
275 }
276 }
277}
278
279pub struct WgpuWindowRenderer {
284 renderer: WgpuRenderer,
286 surface: wgpu::Surface<'static>,
287 surface_config: wgpu::SurfaceConfiguration,
288 queue: wgpu::Queue,
289 device: wgpu::Device,
290 _instance: wgpu::Instance,
291 adapter_name: String,
292 backend_name: &'static str,
293}
294
295impl WgpuWindowRenderer {
296 fn try_init_with_backends<T>(
297 target: T,
298 width: u32,
299 height: u32,
300 backends: wgpu::Backends,
301 ) -> Option<Self>
302 where
303 T: Into<wgpu::SurfaceTarget<'static>>,
304 {
305 let trace = std::env::var_os("VELOX_STARTUP_TRACE").is_some();
306 let t0 = std::time::Instant::now();
307 let instance = create_wgpu_instance(backends);
308 let t_inst = t0.elapsed();
309 let surface = instance.create_surface(target).ok()?;
310 let t_surf = t0.elapsed();
311
312 let adapter = if std::env::var_os("WGPU_ADAPTER_NAME").is_some()
313 || std::env::var_os("WGPU_POWER_PREFERENCE").is_some()
314 {
315 block_on(wgpu::util::initialize_adapter_from_env_or_default(
316 &instance,
317 Some(&surface),
318 ))
319 .ok()?
320 } else {
321 block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
324 power_preference: wgpu::PowerPreference::LowPower,
325 compatible_surface: Some(&surface),
326 force_fallback_adapter: false,
327 ..Default::default()
328 }))
329 .ok()?
330 };
331 let t_adap = t0.elapsed();
332
333 let info = adapter.get_info();
334 if info.device_type == wgpu::DeviceType::Cpu {
335 return None;
336 }
337
338 let caps = surface.get_capabilities(&adapter);
339 let format = [
340 wgpu::TextureFormat::Bgra8Unorm,
341 wgpu::TextureFormat::Rgba8Unorm,
342 ]
343 .into_iter()
344 .find(|f| caps.formats.contains(f))
345 .or_else(|| caps.formats.first().copied())?;
346
347 let alpha_mode = if caps.alpha_modes.contains(&wgpu::CompositeAlphaMode::Opaque) {
348 wgpu::CompositeAlphaMode::Opaque
349 } else {
350 caps.alpha_modes.first().copied()?
351 };
352
353 let required_limits = wgpu::Limits {
354 max_inter_stage_shader_variables: 15,
355 ..wgpu::Limits::default()
356 };
357
358 let (device, queue) = block_on(adapter.request_device(&wgpu::DeviceDescriptor {
359 label: Some("velox_wgpu_device"),
360 required_features: wgpu::Features::empty(),
361 required_limits,
362 memory_hints: wgpu::MemoryHints::MemoryUsage,
363 trace: wgpu::Trace::default(),
364 experimental_features: wgpu::ExperimentalFeatures::default(),
365 }))
366 .ok()?;
367 let t_dev = t0.elapsed();
368
369 device.on_uncaptured_error(Arc::new(|err| {
370 eprintln!("[velox::gpu] WGPU uncaptured error: {err:?}");
371 }));
372
373 let w = width.max(1);
374 let h = height.max(1);
375 let surface_config = wgpu::SurfaceConfiguration {
376 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
377 format,
378 width: w,
379 height: h,
380 present_mode: wgpu::PresentMode::AutoVsync,
381 desired_maximum_frame_latency: 1,
382 alpha_mode,
383 view_formats: Vec::new(),
384 color_space: wgpu::SurfaceColorSpace::Auto,
385 };
386 surface.configure(&device, &surface_config);
387 let t_cfg = t0.elapsed();
388
389 let renderer = WgpuRenderer::new(&device, format);
390 let t_ren = t0.elapsed();
391 if trace {
392 std::println!(
393 "[VELOX_STARTUP_TRACE] wgpu init: instance={:.1}ms, surface=+{:.1}ms, adapter=+{:.1}ms, device=+{:.1}ms, configure=+{:.1}ms, pipeline=+{:.1}ms, total={:.1}ms",
394 t_inst.as_secs_f64() * 1000.0,
395 (t_surf - t_inst).as_secs_f64() * 1000.0,
396 (t_adap - t_surf).as_secs_f64() * 1000.0,
397 (t_dev - t_adap).as_secs_f64() * 1000.0,
398 (t_cfg - t_dev).as_secs_f64() * 1000.0,
399 (t_ren - t_cfg).as_secs_f64() * 1000.0,
400 t_ren.as_secs_f64() * 1000.0,
401 );
402 }
403 let backend_name = match info.backend {
404 wgpu::Backend::Dx12 => "DX12",
405 wgpu::Backend::Vulkan => "Vulkan",
406 wgpu::Backend::Metal => "Metal",
407 wgpu::Backend::Gl => "OpenGL",
408 wgpu::Backend::BrowserWebGpu => "WebGPU",
409 wgpu::Backend::Noop => "Noop",
410 };
411
412 Some(Self {
413 renderer,
414 surface,
415 surface_config,
416 queue,
417 device,
418 _instance: instance,
419 adapter_name: info.name,
420 backend_name,
421 })
422 }
423
424 pub fn from_prepared<T>(
426 prepared: PreparedWgpuContext,
427 target: T,
428 width: u32,
429 height: u32,
430 ) -> Option<Self>
431 where
432 T: Into<wgpu::SurfaceTarget<'static>>,
433 {
434 let trace = std::env::var_os("VELOX_STARTUP_TRACE").is_some();
435 let t0 = std::time::Instant::now();
436 let PreparedWgpuContext {
437 precompiled_renderer,
438 queue,
439 device,
440 adapter,
441 instance,
442 adapter_name,
443 backend_name,
444 ..
445 } = prepared;
446
447 let instance = instance?;
448 let adapter = adapter?;
449 let surface = instance.create_surface(target).ok()?;
450 let caps = surface.get_capabilities(&adapter);
451 if caps.formats.is_empty() || caps.alpha_modes.is_empty() {
452 return None;
453 }
454 let format = [
455 wgpu::TextureFormat::Bgra8Unorm,
456 wgpu::TextureFormat::Rgba8Unorm,
457 ]
458 .into_iter()
459 .find(|f| caps.formats.contains(f))
460 .or_else(|| caps.formats.first().copied())?;
461
462 let alpha_mode = if caps.alpha_modes.contains(&wgpu::CompositeAlphaMode::Opaque) {
463 wgpu::CompositeAlphaMode::Opaque
464 } else {
465 caps.alpha_modes.first().copied()?
466 };
467
468 let w = width.max(1);
469 let h = height.max(1);
470 let surface_config = wgpu::SurfaceConfiguration {
471 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
472 format,
473 width: w,
474 height: h,
475 present_mode: wgpu::PresentMode::AutoVsync,
476 desired_maximum_frame_latency: 1,
477 alpha_mode,
478 view_formats: Vec::new(),
479 color_space: wgpu::SurfaceColorSpace::Auto,
480 };
481 surface.configure(&device, &surface_config);
482
483 let renderer = match precompiled_renderer {
484 Some((fmt, r)) if fmt == format => r,
485 _ => WgpuRenderer::new(&device, format),
486 };
487 if trace {
488 std::println!(
489 "[VELOX_STARTUP_TRACE] main-thread GPU surface attach & promote: {:.1}ms",
490 t0.elapsed().as_secs_f64() * 1000.0
491 );
492 }
493
494 Some(Self {
495 renderer,
496 surface,
497 surface_config,
498 queue,
499 device,
500 _instance: instance,
501 adapter_name,
502 backend_name,
503 })
504 }
505
506 pub fn new<T>(target: T, width: u32, height: u32) -> Option<Self>
508 where
509 T: Into<wgpu::SurfaceTarget<'static>> + Clone,
510 {
511 if let Some(env_backends) = wgpu::Backends::from_env() {
512 return Self::try_init_with_backends(target, width, height, env_backends);
513 }
514
515 #[cfg(target_os = "windows")]
516 {
517 if let Some(surf) =
519 Self::try_init_with_backends(target.clone(), width, height, wgpu::Backends::DX12)
520 {
521 return Some(surf);
522 }
523 Self::try_init_with_backends(target, width, height, wgpu::Backends::VULKAN)
524 }
525 #[cfg(not(target_os = "windows"))]
526 {
527 Self::try_init_with_backends(target, width, height, wgpu::Backends::PRIMARY)
528 }
529 }
530
531 #[inline]
533 pub fn adapter_name(&self) -> &str {
534 &self.adapter_name
535 }
536
537 #[inline]
539 pub const fn backend_name(&self) -> &'static str {
540 self.backend_name
541 }
542
543 #[inline]
545 pub fn last_primitive_count(&self) -> usize {
546 self.renderer.last_primitive_count()
547 }
548
549 #[inline]
551 pub const fn atlas_sizes(&self) -> (u32, u32) {
552 self.renderer.atlas_sizes()
553 }
554
555 #[inline]
557 pub fn device(&self) -> &wgpu::Device {
558 &self.device
559 }
560
561 #[inline]
563 pub fn queue(&self) -> &wgpu::Queue {
564 &self.queue
565 }
566
567 #[inline]
569 pub fn renderer(&self) -> &WgpuRenderer {
570 &self.renderer
571 }
572
573 #[inline]
575 pub fn renderer_mut(&mut self) -> &mut WgpuRenderer {
576 &mut self.renderer
577 }
578
579 #[inline]
581 pub fn register_external_texture(
582 &mut self,
583 view: wgpu::TextureView,
584 sampler: Option<wgpu::Sampler>,
585 ) -> crate::paint::ExternalTextureId {
586 self.renderer.register_external_texture(view, sampler)
587 }
588
589 #[inline]
591 pub fn update_external_texture(
592 &mut self,
593 id: crate::paint::ExternalTextureId,
594 view: wgpu::TextureView,
595 ) -> bool {
596 self.renderer.update_external_texture(id, view)
597 }
598
599 #[inline]
601 pub fn unregister_external_texture(&mut self, id: crate::paint::ExternalTextureId) -> bool {
602 self.renderer.unregister_external_texture(id)
603 }
604
605 pub fn resize(&mut self, width: u32, height: u32) {
607 if width == 0 || height == 0 {
608 return;
609 }
610 if self.surface_config.width == width && self.surface_config.height == height {
611 return;
612 }
613 self.surface_config.width = width;
614 self.surface_config.height = height;
615 self.surface.configure(&self.device, &self.surface_config);
616 }
617
618 fn acquire_surface_texture(&self) -> Option<wgpu::SurfaceTexture> {
619 match self.surface.get_current_texture() {
620 wgpu::CurrentSurfaceTexture::Success(tex)
621 | wgpu::CurrentSurfaceTexture::Suboptimal(tex) => Some(tex),
622 wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
623 self.surface.configure(&self.device, &self.surface_config);
624 match self.surface.get_current_texture() {
625 wgpu::CurrentSurfaceTexture::Success(tex)
626 | wgpu::CurrentSurfaceTexture::Suboptimal(tex) => Some(tex),
627 _ => None,
628 }
629 }
630 _ => None,
631 }
632 }
633
634 pub fn render(&mut self, ops: &[DrawOp<'_>], viewport: Region, dpi_scale: i16) -> bool {
636 self.render_scaled(ops, viewport, dpi_scale.max(1) as f32)
637 }
638
639 pub fn render_scaled(&mut self, ops: &[DrawOp<'_>], viewport: Region, scale_factor: f32) -> bool {
641 self.render_scaled_with_clear(ops, viewport, scale_factor, Color::rgb(0, 0, 0))
642 }
643
644 pub fn render_scaled_with_clear(
646 &mut self,
647 ops: &[DrawOp<'_>],
648 viewport: Region,
649 scale_factor: f32,
650 clear: Color,
651 ) -> bool {
652 let Some(frame) = self.acquire_surface_texture() else {
653 return false;
654 };
655 let frame_view = frame
656 .texture
657 .create_view(&wgpu::TextureViewDescriptor::default());
658 let clear_color = if self.surface_config.format.is_srgb() {
659 let srgb_to_lin = |c: u8| -> f64 {
660 let s = (c as f64) / 255.0;
661 if s <= 0.04045 {
662 s / 12.92
663 } else {
664 ((s + 0.055) / 1.055).powf(2.4)
665 }
666 };
667 wgpu::Color {
668 r: srgb_to_lin(clear.r()),
669 g: srgb_to_lin(clear.g()),
670 b: srgb_to_lin(clear.b()),
671 a: 1.0,
672 }
673 } else {
674 wgpu::Color {
675 r: (clear.r() as f64) / 255.0,
676 g: (clear.g() as f64) / 255.0,
677 b: (clear.b() as f64) / 255.0,
678 a: 1.0,
679 }
680 };
681 self.renderer.render_to_view(
682 &self.device,
683 &self.queue,
684 ops,
685 viewport,
686 scale_factor,
687 &frame_view,
688 self.surface_config.width,
689 self.surface_config.height,
690 clear_color,
691 );
692 self.queue.present(frame);
693 true
694 }
695
696 #[inline]
698 pub fn flush_and_wait(&self) {
699 let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
700 }
701}