Skip to main content

sui_render_wgpu/
renderer.rs

1use crate::WgpuRenderer;
2use crate::device::default_wgpu_instance;
3use crate::diagnostics::RendererFrameStats;
4use crate::interop::WgpuExternalTextureRegistry;
5use crate::output::ColorManagementMode;
6use crate::output::DisplayCapabilities;
7use crate::output::OutputStrategy;
8use crate::output::RendererCapabilities;
9use crate::resources::FrameResources;
10use crate::surface::normalize_framebuffer_size;
11use crate::text::RendererTextCacheSnapshot;
12use crate::text_engine::TextEngine;
13use crate::text_policy::FeatheringOptions;
14use crate::text_policy::StemDarkening;
15use crate::text_policy::TextCoveragePolicy;
16use crate::text_policy::TextHinting;
17use crate::text_policy::TextRenderMode;
18use std::collections::HashMap;
19use std::fmt;
20use sui_core::Result;
21use sui_core::WindowId;
22use sui_scene::SceneFrame;
23pub use sui_scene::TextSubpixelOrder;
24
25impl WgpuRenderer {
26    pub fn new() -> Self {
27        Self::default()
28    }
29
30    pub fn with_feathering(mut self, feathering: FeatheringOptions) -> Self {
31        self.set_feathering(feathering);
32        self
33    }
34
35    pub fn with_feathering_enabled(mut self, enabled: bool) -> Self {
36        self.set_feathering_enabled(enabled);
37        self
38    }
39
40    pub fn with_text_coverage_policy(mut self, policy: TextCoveragePolicy) -> Self {
41        self.set_text_coverage_policy(policy);
42        self
43    }
44
45    pub fn with_text_render_mode(mut self, mode: TextRenderMode) -> Self {
46        self.set_text_render_mode(mode);
47        self
48    }
49
50    pub fn with_text_subpixel_order(mut self, order: TextSubpixelOrder) -> Self {
51        self.set_text_subpixel_order(order);
52        self
53    }
54
55    pub fn with_text_hinting(mut self, hinting: TextHinting) -> Self {
56        self.set_text_hinting(hinting);
57        self
58    }
59
60    pub fn with_stem_darkening(mut self, darkening: StemDarkening) -> Self {
61        self.set_stem_darkening(darkening);
62        self
63    }
64
65    pub fn with_feather_width(mut self, feather_width: f32) -> Self {
66        self.set_feather_width(feather_width);
67        self
68    }
69
70    pub fn with_vsync_enabled(mut self, enabled: bool) -> Self {
71        self.set_vsync_enabled(enabled);
72        self
73    }
74
75    pub fn with_external_texture_registry(mut self, registry: WgpuExternalTextureRegistry) -> Self {
76        self.set_external_texture_registry(registry);
77        self
78    }
79
80    pub fn feathering(&self) -> FeatheringOptions {
81        FeatheringOptions::new(self.feathering_enabled, self.feather_width)
82    }
83
84    pub fn feathering_enabled(&self) -> bool {
85        self.feathering_enabled
86    }
87
88    pub fn feather_width(&self) -> f32 {
89        self.feather_width
90    }
91
92    pub fn vsync_enabled(&self) -> bool {
93        self.vsync_enabled
94    }
95
96    pub fn external_texture_registry(&self) -> Option<&WgpuExternalTextureRegistry> {
97        self.external_texture_registry.as_ref()
98    }
99
100    pub fn set_external_texture_registry(&mut self, registry: WgpuExternalTextureRegistry) {
101        if let Some(shared) = &self.shared {
102            registry.attach(
103                shared.device.clone(),
104                shared.queue.clone(),
105                shared.adapter.get_info(),
106            );
107        }
108        self.external_texture_registry = Some(registry);
109        self.external_image_cache.clear();
110    }
111
112    pub fn text_coverage_policy(&self) -> TextCoveragePolicy {
113        self.text_coverage_policy
114    }
115
116    pub fn text_render_mode(&self) -> TextRenderMode {
117        self.text_render_mode
118    }
119
120    pub fn text_subpixel_order(&self) -> TextSubpixelOrder {
121        self.text_subpixel_order
122    }
123
124    pub fn text_hinting(&self) -> TextHinting {
125        self.text_hinting
126    }
127
128    pub fn stem_darkening(&self) -> StemDarkening {
129        self.stem_darkening
130    }
131
132    pub fn set_feathering(&mut self, feathering: FeatheringOptions) {
133        let feathering = feathering.clamped();
134        self.feathering_enabled = feathering.enabled;
135        self.feather_width = feathering.width;
136    }
137
138    pub fn set_feathering_enabled(&mut self, enabled: bool) {
139        self.feathering_enabled = enabled;
140    }
141
142    pub fn set_text_coverage_policy(&mut self, policy: TextCoveragePolicy) {
143        let policy = policy.normalized();
144        if self.text_coverage_policy == policy {
145            return;
146        }
147
148        self.text_coverage_policy = policy;
149        if let Some(text_engine) = self.text_engine.as_mut() {
150            text_engine.set_text_coverage_policy(policy);
151        }
152        self.invalidate_text_render_state();
153    }
154
155    pub fn set_text_render_mode(&mut self, mode: TextRenderMode) {
156        if self.text_render_mode == mode {
157            return;
158        }
159
160        self.text_render_mode = mode;
161        if let Some(text_engine) = self.text_engine.as_mut() {
162            text_engine.set_text_render_mode(mode);
163        }
164        self.invalidate_text_render_state();
165    }
166
167    pub fn set_text_subpixel_order(&mut self, order: TextSubpixelOrder) {
168        if self.text_subpixel_order == order {
169            return;
170        }
171
172        self.text_subpixel_order = order;
173        if let Some(text_engine) = self.text_engine.as_mut() {
174            text_engine.set_text_subpixel_order(order);
175        }
176        self.invalidate_text_render_state();
177    }
178
179    pub fn set_text_hinting(&mut self, hinting: TextHinting) {
180        let hinting = hinting.normalized();
181        if self.text_hinting == hinting {
182            return;
183        }
184
185        self.text_hinting = hinting;
186        if let Some(text_engine) = self.text_engine.as_mut() {
187            text_engine.set_text_hinting(hinting);
188        }
189    }
190
191    pub fn set_stem_darkening(&mut self, darkening: StemDarkening) {
192        let darkening = darkening.normalized();
193        if self.stem_darkening == darkening {
194            return;
195        }
196
197        self.stem_darkening = darkening;
198        if let Some(text_engine) = self.text_engine.as_mut() {
199            text_engine.set_stem_darkening(darkening);
200        }
201    }
202
203    pub fn set_feather_width(&mut self, feather_width: f32) {
204        self.feather_width = feather_width.max(0.0);
205    }
206
207    pub fn set_vsync_enabled(&mut self, enabled: bool) {
208        self.vsync_enabled = enabled;
209    }
210
211    pub fn set_window_display_capabilities(
212        &mut self,
213        window_id: WindowId,
214        capabilities: DisplayCapabilities,
215    ) -> Result<()> {
216        let Some(surface) = self.surfaces.get_mut(&window_id) else {
217            // Offscreen windows render as if presenting to this display.
218            self.offscreen_outputs
219                .entry(window_id)
220                .or_default()
221                .display_capabilities = capabilities;
222            return Ok(());
223        };
224        if surface.display_capabilities == capabilities {
225            return Ok(());
226        }
227        surface.display_capabilities = capabilities;
228        self.configure_existing_surface(window_id)
229    }
230
231    /// The subpixel order the system antialiases text for on the window's
232    /// display, without cloning its whole capability profile.
233    pub(crate) fn window_system_text_subpixel_order(
234        &self,
235        window_id: WindowId,
236    ) -> TextSubpixelOrder {
237        self.surfaces
238            .get(&window_id)
239            .map(|surface| surface.display_capabilities.text_subpixel_order)
240            .or_else(|| {
241                self.offscreen_outputs
242                    .get(&window_id)
243                    .map(|output| output.display_capabilities.text_subpixel_order)
244            })
245            .unwrap_or_default()
246    }
247
248    pub fn window_display_capabilities(&self, window_id: WindowId) -> Option<DisplayCapabilities> {
249        self.surfaces
250            .get(&window_id)
251            .map(|surface| surface.display_capabilities.clone())
252            .or_else(|| {
253                self.offscreen_outputs
254                    .get(&window_id)
255                    .map(|output| output.display_capabilities.clone())
256            })
257    }
258
259    pub fn set_window_color_management(
260        &mut self,
261        window_id: WindowId,
262        color_management: ColorManagementMode,
263    ) -> Result<()> {
264        let Some(surface) = self.surfaces.get_mut(&window_id) else {
265            // Offscreen windows fit and capture with it too.
266            self.offscreen_outputs
267                .entry(window_id)
268                .or_default()
269                .color_management = color_management;
270            return Ok(());
271        };
272        if surface.color_management == color_management {
273            return Ok(());
274        }
275        surface.color_management = color_management;
276        self.configure_existing_surface(window_id)
277    }
278
279    /// The color management `window_id` renders with.
280    pub fn window_color_management(&self, window_id: WindowId) -> ColorManagementMode {
281        self.surfaces
282            .get(&window_id)
283            .map(|surface| surface.color_management)
284            .or_else(|| {
285                self.offscreen_outputs
286                    .get(&window_id)
287                    .map(|output| output.color_management)
288            })
289            .unwrap_or_default()
290    }
291
292    /// The strategy `window_id` presents with. A window without a surface
293    /// reports the strategy it would use on the display it was given.
294    pub fn window_output_strategy(&self, window_id: WindowId) -> Option<OutputStrategy> {
295        self.surfaces
296            .get(&window_id)
297            .map(|surface| surface.output_strategy)
298            .or_else(|| {
299                self.offscreen_outputs
300                    .get(&window_id)
301                    .map(crate::output::OffscreenOutput::output_strategy)
302            })
303    }
304
305    pub fn window_surface_formats(&self, window_id: WindowId) -> Option<Vec<wgpu::TextureFormat>> {
306        self.surfaces
307            .get(&window_id)
308            .map(|surface| surface.available_surface_formats.clone())
309    }
310
311    pub fn set_runtime_feathering_override(&mut self, feathering: Option<FeatheringOptions>) {
312        self.runtime_feathering_override = feathering.map(FeatheringOptions::clamped);
313    }
314
315    pub fn set_runtime_text_subpixel_order_override(&mut self, order: Option<TextSubpixelOrder>) {
316        self.runtime_text_subpixel_order_override = order;
317    }
318
319    /// Whether the window being rendered follows the system's text smoothing:
320    /// LCD text in the order its display capabilities report
321    /// ([`DisplayCapabilities::text_subpixel_order`]). On by default.
322    pub fn set_runtime_system_text_smoothing_enabled(&mut self, enabled: bool) {
323        self.runtime_system_text_smoothing_enabled = enabled;
324    }
325
326    pub fn set_runtime_text_hinting_override(&mut self, hinting: Option<TextHinting>) {
327        self.runtime_text_hinting_override = hinting.map(TextHinting::normalized);
328    }
329
330    pub fn set_runtime_stem_darkening_override(&mut self, darkening: Option<StemDarkening>) {
331        self.runtime_stem_darkening_override = darkening.map(StemDarkening::normalized);
332    }
333
334    pub fn set_runtime_text_coverage_policy_override(
335        &mut self,
336        policy: Option<TextCoveragePolicy>,
337    ) {
338        self.runtime_text_coverage_policy_override = policy.map(TextCoveragePolicy::normalized);
339    }
340
341    pub fn set_runtime_diagnostics_enabled(&mut self, enabled: bool) {
342        self.runtime_diagnostics_enabled = enabled;
343        if let Some(shared) = &mut self.shared {
344            shared.collect_pipeline_timings = enabled;
345        }
346        if let Some(text_engine) = self.text_engine.as_mut() {
347            text_engine.set_diagnostics_enabled(enabled);
348        }
349        for compositor in self.compositors.values_mut() {
350            compositor.set_diagnostics_enabled(enabled);
351        }
352    }
353
354    pub(crate) fn active_feather_width(&self) -> f32 {
355        self.runtime_feathering_override
356            .unwrap_or_else(|| self.feathering())
357            .effective_width()
358    }
359
360    pub(crate) fn active_text_hinting(&self) -> TextHinting {
361        self.runtime_text_hinting_override
362            .unwrap_or(self.text_hinting)
363            .normalized()
364    }
365
366    pub(crate) fn active_text_subpixel_order(&self) -> TextSubpixelOrder {
367        self.runtime_text_subpixel_order_override
368            .unwrap_or(self.text_subpixel_order)
369    }
370
371    pub(crate) fn active_stem_darkening(&self) -> StemDarkening {
372        self.runtime_stem_darkening_override
373            .unwrap_or(self.stem_darkening)
374            .normalized()
375    }
376
377    pub(crate) fn active_text_coverage_policy(&self) -> TextCoveragePolicy {
378        self.runtime_text_coverage_policy_override
379            .unwrap_or(self.text_coverage_policy)
380            .normalized()
381    }
382
383    pub(crate) fn invalidate_text_render_state(&mut self) {
384        self.text_engine = None;
385        self.text_atlas_array = None;
386        self.compositors.clear();
387        self.last_frames.clear();
388        self.last_frame_stats.clear();
389    }
390
391    pub fn remove_window(&mut self, window_id: WindowId) {
392        self.prepared_surfaces.remove(&window_id);
393        #[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))]
394        if self
395            .device_preparation
396            .as_ref()
397            .is_some_and(|pending| pending.window == Some(window_id))
398        {
399            self.device_preparation = None;
400        }
401        self.frame_resources.fragments.remove(&window_id);
402        self.frame_resources.output_transforms.remove(&window_id);
403        self.surfaces.remove(&window_id);
404        self.offscreen_outputs.remove(&window_id);
405        self.offscreen_targets.remove(&window_id);
406        self.intermediate_targets.remove(&window_id);
407        self.last_frames.remove(&window_id);
408        self.last_frame_stats.remove(&window_id);
409        self.compositors.remove(&window_id);
410        self.debug_captures_in_flight
411            .retain(|capture| capture.window_id != window_id);
412    }
413
414    pub fn render(&mut self, frame: &SceneFrame) -> Result<()> {
415        let pipeline_before = self.shared.as_ref().map_or((0, 0), |shared| {
416            (shared.pipeline_create_time_us, shared.pipeline_create_count)
417        });
418        let viewport = normalize_framebuffer_size(frame.surface_size);
419        let mut frame_stats = RendererFrameStats::default();
420
421        if let Some(size) = viewport {
422            if self.surfaces.contains_key(&frame.window_id) {
423                frame_stats = self.render_surface(frame, size)?;
424            } else {
425                frame_stats = self.render_offscreen(frame, size)?;
426            }
427        }
428
429        frame_stats.device_prepare_time_us =
430            std::mem::take(&mut self.pending_device_prepare_time_us);
431        frame_stats.device_prepare_wait_time_us =
432            std::mem::take(&mut self.pending_device_wait_time_us);
433        if let Some(shared) = &self.shared {
434            frame_stats.pipeline_create_time_us =
435                shared.pipeline_create_time_us - pipeline_before.0;
436            frame_stats.pipeline_create_count = shared.pipeline_create_count - pipeline_before.1;
437        }
438        self.frames_rendered += 1;
439        self.last_frames.insert(frame.window_id, frame.clone());
440        self.last_frame_stats.insert(frame.window_id, frame_stats);
441        self.analytic_path_cache
442            .retain(|_, entry| self.frames_rendered.saturating_sub(entry.last_used_frame) <= 120);
443        self.image_cache
444            .retain(|_, entry| self.frames_rendered.saturating_sub(entry.last_used_frame) <= 120);
445        Ok(())
446    }
447
448    pub fn capabilities(&self) -> RendererCapabilities {
449        self.capabilities
450    }
451
452    /// Adapter metadata after initialization, without requiring an interop registry.
453    pub fn adapter_info(&self) -> Option<wgpu::AdapterInfo> {
454        self.shared.as_ref().map(|shared| shared.adapter.get_info())
455    }
456
457    pub fn frames_rendered(&self) -> usize {
458        self.frames_rendered
459    }
460
461    pub fn last_frame(&self, window_id: WindowId) -> Option<&SceneFrame> {
462        self.last_frames.get(&window_id)
463    }
464
465    pub fn last_frame_stats(&self, window_id: WindowId) -> Option<RendererFrameStats> {
466        self.last_frame_stats.get(&window_id).cloned()
467    }
468
469    pub fn text_cache_snapshot(&self, window_id: WindowId) -> RendererTextCacheSnapshot {
470        let mut snapshot = self
471            .text_engine
472            .as_ref()
473            .map(TextEngine::cache_snapshot)
474            .unwrap_or_default();
475        snapshot.path = self
476            .compositors
477            .get(&window_id)
478            .map(|compositor| compositor.path_cache.snapshot())
479            .unwrap_or_default();
480        snapshot
481    }
482}
483
484impl Default for WgpuRenderer {
485    fn default() -> Self {
486        Self {
487            instance: default_wgpu_instance(),
488            feathering_enabled: FeatheringOptions::default().enabled,
489            feather_width: FeatheringOptions::default().width,
490            text_render_mode: TextRenderMode::default(),
491            text_subpixel_order: TextSubpixelOrder::default(),
492            text_hinting: TextHinting::default(),
493            stem_darkening: StemDarkening::default(),
494            text_coverage_policy: TextCoveragePolicy::default(),
495            vsync_enabled: true,
496            runtime_feathering_override: None,
497            runtime_text_subpixel_order_override: None,
498            runtime_system_text_smoothing_enabled: true,
499            runtime_text_hinting_override: None,
500            runtime_stem_darkening_override: None,
501            runtime_text_coverage_policy_override: None,
502            runtime_diagnostics_enabled: true,
503            pending_device_prepare_time_us: 0,
504            pending_device_wait_time_us: 0,
505            #[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))]
506            device_preparation: None,
507            prepared_surfaces: HashMap::new(),
508            frames_rendered: 0,
509            capabilities: RendererCapabilities::default(),
510            last_frames: HashMap::new(),
511            last_frame_stats: HashMap::new(),
512            shared: None,
513            text_engine: None,
514            image_cache: HashMap::new(),
515            external_texture_registry: None,
516            external_image_cache: HashMap::new(),
517            text_atlas_array: None,
518            analytic_path_cache: HashMap::new(),
519            compositors: HashMap::new(),
520            surfaces: HashMap::new(),
521            offscreen_targets: HashMap::new(),
522            intermediate_targets: HashMap::new(),
523            offscreen_outputs: HashMap::new(),
524            frame_resources: FrameResources::default(),
525            debug_captures_in_flight: Vec::new(),
526            next_debug_capture_id: 1,
527        }
528    }
529}
530
531impl fmt::Debug for WgpuRenderer {
532    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533        f.debug_struct("WgpuRenderer")
534            .field("feathering_enabled", &self.feathering_enabled)
535            .field("feather_width", &self.feather_width)
536            .field("text_coverage_policy", &self.text_coverage_policy)
537            .field("frames_rendered", &self.frames_rendered)
538            .field("capabilities", &self.capabilities)
539            .field("last_frame_count", &self.last_frames.len())
540            .field("last_frame_stats_count", &self.last_frame_stats.len())
541            .field("has_device", &self.shared.is_some())
542            .field("surface_count", &self.surfaces.len())
543            .finish()
544    }
545}