veloren_voxygen/render/renderer/
mod.rs

1mod binding;
2mod compiler;
3pub(super) mod drawer;
4// Consts and bind groups for post-process and clouds
5mod locals;
6mod pipeline_creation;
7mod rain_occlusion_map;
8mod screenshot;
9mod shaders;
10mod shadow_map;
11
12use locals::Locals;
13use pipeline_creation::{
14    IngameAndShadowPipelines, InterfacePipelines, PipelineCreation, Pipelines, ShadowPipelines,
15};
16use shaders::Shaders;
17use shadow_map::{ShadowMap, ShadowMapRenderer};
18
19use self::{pipeline_creation::RainOcclusionPipelines, rain_occlusion_map::RainOcclusionMap};
20
21use super::{
22    AddressMode, FilterMode, OtherModes, PipelineModes, PresentMode, RenderError, RenderMode,
23    ShadowMapMode, ShadowMode, Vertex,
24    buffer::Buffer,
25    consts::Consts,
26    instances::Instances,
27    mesh::Mesh,
28    model::{DynamicModel, Model},
29    pipelines::{
30        GlobalsBindGroup, GlobalsLayouts, ShadowTexturesBindGroup, blit, bloom, clouds, debug,
31        figure, postprocess, rain_occlusion, rope, shadow, sprite, terrain, ui,
32    },
33    texture::Texture,
34};
35use common::assets::{self, AssetExt, AssetHandle, ReloadWatcher};
36use common_base::span;
37use core::convert::TryFrom;
38use std::sync::Arc;
39use tracing::{error, info, warn};
40use vek::*;
41
42const QUAD_INDEX_BUFFER_U16_START_VERT_LEN: u16 = 3000;
43const QUAD_INDEX_BUFFER_U32_START_VERT_LEN: u32 = 3000;
44
45/// A type that stores all the layouts associated with this renderer that never
46/// change when the RenderMode is modified.
47struct ImmutableLayouts {
48    global: GlobalsLayouts,
49
50    debug: debug::DebugLayout,
51    figure: figure::FigureLayout,
52    shadow: shadow::ShadowLayout,
53    rain_occlusion: rain_occlusion::RainOcclusionLayout,
54    sprite: sprite::SpriteLayout,
55    terrain: terrain::TerrainLayout,
56    rope: rope::RopeLayout,
57    clouds: clouds::CloudsLayout,
58    bloom: bloom::BloomLayout,
59    ui: ui::UiLayout,
60    premultiply_alpha: ui::PremultiplyAlphaLayout,
61    blit: blit::BlitLayout,
62}
63
64/// A type that stores all the layouts associated with this renderer.
65struct Layouts {
66    immutable: Arc<ImmutableLayouts>,
67
68    postprocess: Arc<postprocess::PostProcessLayout>,
69}
70
71impl core::ops::Deref for Layouts {
72    type Target = ImmutableLayouts;
73
74    fn deref(&self) -> &Self::Target { &self.immutable }
75}
76
77/// Render target views
78struct Views {
79    // NOTE: unused for now, maybe... we will want it for something
80    _win_depth: wgpu::TextureView,
81
82    tgt_color: wgpu::TextureView,
83    tgt_mat: wgpu::TextureView,
84    tgt_depth: wgpu::TextureView,
85
86    bloom_tgts: Option<[wgpu::TextureView; bloom::NUM_SIZES]>,
87    // TODO: rename
88    tgt_color_pp: wgpu::TextureView,
89}
90
91/// Shadow rendering textures, layouts, pipelines, and bind groups
92struct Shadow {
93    rain_map: RainOcclusionMap,
94    map: ShadowMap,
95    bind: ShadowTexturesBindGroup,
96}
97
98/// Represent two states of the renderer:
99/// 1. Only interface pipelines created
100/// 2. All of the pipelines have been created
101#[expect(clippy::large_enum_variant)]
102enum State {
103    // NOTE: this is used as a transient placeholder for moving things out of State temporarily
104    Nothing,
105    Interface {
106        pipelines: InterfacePipelines,
107        shadow_views: Option<(Texture, Texture)>,
108        rain_occlusion_view: Option<Texture>,
109        // In progress creation of the remaining pipelines in the background
110        creating: PipelineCreation<IngameAndShadowPipelines>,
111    },
112    Complete {
113        pipelines: Pipelines,
114        shadow: Shadow,
115        recreating: Option<(
116            PipelineModes,
117            PipelineCreation<
118                Result<
119                    (
120                        Pipelines,
121                        ShadowPipelines,
122                        RainOcclusionPipelines,
123                        Arc<postprocess::PostProcessLayout>,
124                    ),
125                    RenderError,
126                >,
127            >,
128        )>,
129    },
130}
131
132/// A type that encapsulates rendering state. `Renderer` is central to Voxygen's
133/// rendering subsystem and contains any state necessary to interact with the
134/// GPU, along with pipeline state objects (PSOs) needed to renderer different
135/// kinds of models to the screen.
136pub struct Renderer {
137    device: wgpu::Device,
138    queue: wgpu::Queue,
139    surface: wgpu::Surface<'static>,
140    surface_config: wgpu::SurfaceConfiguration,
141
142    sampler: wgpu::Sampler,
143    depth_sampler: wgpu::Sampler,
144
145    state: State,
146    // Some if there is a pending need to recreate the pipelines (e.g. RenderMode change or shader
147    // hotloading)
148    recreation_pending: Option<PipelineModes>,
149
150    layouts: Layouts,
151    // Note: we keep these here since their bind groups need to be updated if we resize the
152    // color/depth textures
153    locals: Locals,
154    views: Views,
155    noise_tex: Texture,
156
157    quad_index_buffer_u16: Buffer<u16>,
158    quad_index_buffer_u32: Buffer<u32>,
159
160    shaders: AssetHandle<Shaders>,
161    shaders_watcher: ReloadWatcher,
162
163    pipeline_modes: PipelineModes,
164    other_modes: OtherModes,
165    resolution: Vec2<u32>,
166
167    // If this is Some then a screenshot will be taken and passed to the handler here
168    take_screenshot: Option<screenshot::ScreenshotFn>,
169
170    profiler: wgpu_profiler::GpuProfiler,
171    profile_times: Vec<wgpu_profiler::GpuTimerQueryResult>,
172    profiler_features_enabled: bool,
173
174    ui_premultiply_uploads: ui::BatchedUploads,
175
176    #[cfg(feature = "egui-ui")]
177    egui_renderpass: egui_wgpu_backend::RenderPass,
178
179    // This checks is added because windows resizes the window to 0,0 when
180    // minimizing and this causes a bunch of validation errors
181    is_minimized: bool,
182
183    // To remember the backend info after initialization for debug purposes
184    graphics_backend: String,
185
186    /// The texture format used for the intermediate rendering passes
187    intermediate_format: wgpu::TextureFormat,
188
189    /// Supported present modes.
190    present_modes: Vec<PresentMode>,
191    /// Cached max texture size.
192    max_texture_size: u32,
193}
194
195impl Renderer {
196    /// Create a new `Renderer` from a variety of backend-specific components
197    /// and the window targets.
198    pub fn new(
199        window: Arc<winit::window::Window>,
200        mode: RenderMode,
201        runtime: &tokio::runtime::Runtime,
202    ) -> Result<Self, RenderError> {
203        let (pipeline_modes, mut other_modes) = mode.split();
204        // Enable seamless cubemaps globally, where available--they are essentially a
205        // strict improvement on regular cube maps.
206        //
207        // Note that since we only have to enable this once globally, there is no point
208        // in doing this on rerender.
209        // Self::enable_seamless_cube_maps(&mut device);
210
211        // TODO: fix panic on wayland with opengl?
212        // TODO: fix backend defaulting to opengl on wayland.
213        let backends = std::env::var("WGPU_BACKEND")
214            .ok()
215            .and_then(|backend| match backend.to_lowercase().as_str() {
216                "vulkan" | "vk" => Some(wgpu::Backends::VULKAN),
217                "metal" => Some(wgpu::Backends::METAL),
218                "dx12" => Some(wgpu::Backends::DX12),
219                "primary" => Some(wgpu::Backends::PRIMARY),
220                "opengl" | "gl" => Some(wgpu::Backends::GL),
221                "secondary" => Some(wgpu::Backends::SECONDARY),
222                "all" => Some(wgpu::Backends::all()),
223                _ => None,
224            })
225            .unwrap_or(wgpu::Backends::PRIMARY | wgpu::Backends::SECONDARY);
226
227        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
228            backends,
229            // TODO: Look into what we want here.
230            flags: wgpu::InstanceFlags::from_build_config().with_env(),
231            backend_options: wgpu::BackendOptions::default(),
232            memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
233        });
234
235        let dims = window.inner_size();
236
237        let surface = instance
238            .create_surface(window)
239            .expect("Failed to create a surface");
240
241        let adapters = instance.enumerate_adapters(backends);
242
243        for (i, adapter) in adapters.iter().enumerate() {
244            let info = adapter.get_info();
245            info!(
246                ?info.name,
247                ?info.vendor,
248                ?info.backend,
249                ?info.device,
250                ?info.device_type,
251                "graphics device #{}", i,
252            );
253        }
254
255        let adapter = match std::env::var("WGPU_ADAPTER").ok() {
256            Some(filter) if !filter.is_empty() => adapters
257                .into_iter()
258                .enumerate()
259                .find_map(|(i, adapter)| {
260                    let info = adapter.get_info();
261
262                    let full_name = format!("#{} {} {:?}", i, info.name, info.device_type,);
263
264                    full_name.contains(&filter).then_some(adapter)
265                })
266                .ok_or(RenderError::CouldNotFindAdapter)?,
267            Some(_) | None => {
268                runtime.block_on(instance.request_adapter(&wgpu::RequestAdapterOptionsBase {
269                    power_preference: wgpu::PowerPreference::HighPerformance,
270                    compatible_surface: Some(&surface),
271                    force_fallback_adapter: false,
272                }))?
273            },
274        };
275
276        let info = adapter.get_info();
277        info!(
278            ?info.name,
279            ?info.vendor,
280            ?info.backend,
281            ?info.device,
282            ?info.device_type,
283            "selected graphics device"
284        );
285        let graphics_backend = format!("{:?}", &info.backend);
286
287        let required_limits = wgpu::Limits {
288            max_push_constant_size: 64,
289            ..Default::default()
290        };
291
292        #[cfg(any())] // Add this back when tracing is added back to `wgpu`
293        let trace = if let Some(v) = std::env::var_os("WGPU_TRACE_DIR") {
294            let path = std::path::Path::new(&v);
295            // We don't want to continue if we can't actually collect the api trace
296            assert!(
297                path.exists(),
298                "WGPU_TRACE_DIR is set to the path \"{}\" which doesn't exist",
299                path.display()
300            );
301            assert!(
302                path.is_dir(),
303                "WGPU_TRACE_DIR is set to the path \"{}\" which is not a directory",
304                path.display()
305            );
306            assert!(
307                path.read_dir()
308                    .expect("Could not read the directory that is specified by WGPU_TRACE_DIR")
309                    .next()
310                    .is_none(),
311                "WGPU_TRACE_DIR is set to the path \"{}\" which already contains other files",
312                path.display()
313            );
314
315            wgpu::Trace::Directory(path)
316        } else {
317            wgpu::Trace::Off
318        };
319
320        let (device, queue) =
321            runtime.block_on(adapter.request_device(&wgpu::DeviceDescriptor {
322                // TODO
323                label: None,
324                required_features: wgpu::Features::DEPTH_CLIP_CONTROL
325                    | wgpu::Features::ADDRESS_MODE_CLAMP_TO_BORDER
326                    | wgpu::Features::PUSH_CONSTANTS
327                    | (adapter.features() & wgpu_profiler::GpuProfiler::ALL_WGPU_TIMER_FEATURES),
328                required_limits,
329                memory_hints: wgpu::MemoryHints::Performance,
330                trace: wgpu::Trace::Off,
331            }))?;
332
333        // Set error handler for wgpu errors
334        // This is better for use than their default because it includes the error in
335        // the panic message
336        device.on_uncaptured_error(Box::new(move |error| {
337            error!("{}", &error);
338            panic!(
339                "wgpu error (handling all wgpu errors as fatal):\n{:?}\n{:?}",
340                &error, &info,
341            );
342        }));
343
344        let profiler_features_enabled = device
345            .features()
346            .intersects(wgpu_profiler::GpuProfiler::ALL_WGPU_TIMER_FEATURES);
347        if !profiler_features_enabled {
348            info!(
349                "The features for GPU profiling (timestamp queries) are not available on this \
350                 adapter"
351            );
352        }
353
354        let max_texture_size = device.limits().max_texture_dimension_2d;
355
356        let surface_capabilities = surface.get_capabilities(&adapter);
357        let format = surface_capabilities.formats[0];
358        info!("Using {:?} as the surface format", format);
359
360        let present_mode = other_modes.present_mode.into();
361        let surface_config = wgpu::SurfaceConfiguration {
362            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
363            desired_maximum_frame_latency: 2,
364            format,
365            width: dims.width,
366            height: dims.height,
367            present_mode: if surface_capabilities.present_modes.contains(&present_mode) {
368                present_mode
369            } else {
370                *surface_capabilities
371                    .present_modes
372                    .iter()
373                    .find(|mode| PresentMode::try_from(**mode).is_ok())
374                    .expect("There should never be no supported present modes")
375            },
376            alpha_mode: wgpu::CompositeAlphaMode::Opaque,
377            view_formats: Vec::new(),
378        };
379
380        let supported_internal_formats = [wgpu::TextureFormat::Rgba16Float, format];
381        let intermediate_format = supported_internal_formats
382            .into_iter()
383            .find(|format| {
384                use wgpu::TextureUsages as Usages;
385                use wgpu::TextureFormatFeatureFlags as Flags;
386                use super::AaMode;
387
388                let features = adapter
389                    .get_texture_format_features(*format);
390
391                let usage_ok = features
392                    .allowed_usages
393                    .contains(Usages::RENDER_ATTACHMENT | Usages::COPY_SRC | Usages::TEXTURE_BINDING);
394
395                let msaa_flags = match pipeline_modes.aa {
396                    AaMode::None | AaMode::Fxaa | AaMode::Hqx | AaMode::FxUpscale | AaMode::Bilinear => Flags::empty(),
397                    AaMode::MsaaX4 => Flags::MULTISAMPLE_X4,
398                    AaMode::MsaaX8 => Flags::MULTISAMPLE_X8,
399                    AaMode::MsaaX16 => Flags::MULTISAMPLE_X8, // TODO?
400                };
401
402                let flags_ok = features.flags.contains(Flags::FILTERABLE | msaa_flags);
403
404                usage_ok && flags_ok
405            })
406            // This should be unreachable as the surface format should always support the
407            // needed capabilities
408            .expect("No supported intermediate format");
409        info!("Using {:?} as the intermediate format", intermediate_format);
410
411        surface.configure(&device, &surface_config);
412
413        let shadow_views = ShadowMap::create_shadow_views(
414            &device,
415            (dims.width, dims.height),
416            &ShadowMapMode::try_from(pipeline_modes.shadow).unwrap_or_default(),
417            max_texture_size,
418        )
419        .map_err(|err| {
420            warn!("Could not create shadow map views: {:?}", err);
421        })
422        .ok();
423
424        let rain_occlusion_view = RainOcclusionMap::create_view(
425            &device,
426            &pipeline_modes.rain_occlusion,
427            max_texture_size,
428        )
429        .map_err(|err| {
430            warn!("Could not create rain occlusion map views: {:?}", err);
431        })
432        .ok();
433
434        let shaders = Shaders::load_expect("");
435        let shaders_watcher = shaders.reload_watcher();
436
437        let layouts = {
438            let global = GlobalsLayouts::new(&device);
439
440            let debug = debug::DebugLayout::new(&device);
441            let figure = figure::FigureLayout::new(&device);
442            let shadow = shadow::ShadowLayout::new(&device);
443            let rain_occlusion = rain_occlusion::RainOcclusionLayout::new(&device);
444            let sprite = sprite::SpriteLayout::new(&device);
445            let terrain = terrain::TerrainLayout::new(&device);
446            let rope = rope::RopeLayout::new(&device);
447            let clouds = clouds::CloudsLayout::new(&device);
448            let bloom = bloom::BloomLayout::new(&device);
449            let postprocess = Arc::new(postprocess::PostProcessLayout::new(
450                &device,
451                &pipeline_modes,
452            ));
453            let ui = ui::UiLayout::new(&device);
454            let premultiply_alpha = ui::PremultiplyAlphaLayout::new(&device);
455            let blit = blit::BlitLayout::new(&device);
456
457            let immutable = Arc::new(ImmutableLayouts {
458                global,
459
460                debug,
461                figure,
462                shadow,
463                rain_occlusion,
464                sprite,
465                terrain,
466                rope,
467                clouds,
468                bloom,
469                ui,
470                premultiply_alpha,
471                blit,
472            });
473
474            Layouts {
475                immutable,
476                postprocess,
477            }
478        };
479
480        let (interface_pipelines, creating) = pipeline_creation::initial_create_pipelines(
481            device.clone(),
482            Layouts {
483                immutable: Arc::clone(&layouts.immutable),
484                postprocess: Arc::clone(&layouts.postprocess),
485            },
486            shaders.cloned(),
487            pipeline_modes.clone(),
488            surface_config.clone(), // Note: cheap clone
489            shadow_views.is_some(),
490            intermediate_format,
491        )?;
492
493        let state = State::Interface {
494            pipelines: interface_pipelines,
495            shadow_views,
496            rain_occlusion_view,
497            creating,
498        };
499
500        let (views, bloom_sizes) = Self::create_rt_views(
501            &device,
502            (dims.width, dims.height),
503            &pipeline_modes,
504            &other_modes,
505            intermediate_format,
506        );
507
508        let create_sampler = |filter| {
509            device.create_sampler(&wgpu::SamplerDescriptor {
510                label: None,
511                address_mode_u: AddressMode::ClampToEdge,
512                address_mode_v: AddressMode::ClampToEdge,
513                address_mode_w: AddressMode::ClampToEdge,
514                mag_filter: filter,
515                min_filter: filter,
516                mipmap_filter: FilterMode::Nearest,
517                compare: None,
518                ..Default::default()
519            })
520        };
521
522        let sampler = create_sampler(FilterMode::Linear);
523        let depth_sampler = create_sampler(FilterMode::Nearest);
524
525        let noise_tex = Texture::new(
526            &device,
527            &queue,
528            &assets::Image::load_expect("voxygen.texture.noise").read().0,
529            Some(FilterMode::Linear),
530            Some(AddressMode::Repeat),
531        )?;
532
533        let clouds_locals =
534            Self::create_consts_inner(&device, &queue, &[clouds::Locals::default()]);
535        let postprocess_locals =
536            Self::create_consts_inner(&device, &queue, &[postprocess::Locals::default()]);
537
538        let locals = Locals::new(
539            &device,
540            &layouts,
541            clouds_locals,
542            postprocess_locals,
543            &views.tgt_color,
544            &views.tgt_mat,
545            &views.tgt_depth,
546            views.bloom_tgts.as_ref().map(|tgts| locals::BloomParams {
547                locals: bloom_sizes.map(|size| {
548                    Self::create_consts_inner(&device, &queue, &[bloom::Locals::new(size)])
549                }),
550                src_views: [&views.tgt_color_pp, &tgts[1], &tgts[2], &tgts[3], &tgts[4]],
551                final_tgt_view: &tgts[0],
552            }),
553            &views.tgt_color_pp,
554            &sampler,
555            &depth_sampler,
556        );
557
558        let quad_index_buffer_u16 =
559            create_quad_index_buffer_u16(&device, QUAD_INDEX_BUFFER_U16_START_VERT_LEN as usize);
560        let quad_index_buffer_u32 =
561            create_quad_index_buffer_u32(&device, QUAD_INDEX_BUFFER_U32_START_VERT_LEN as usize);
562        other_modes.profiler_enabled &= profiler_features_enabled;
563        let profiler =
564            wgpu_profiler::GpuProfiler::new(&device, wgpu_profiler::GpuProfilerSettings {
565                enable_timer_queries: other_modes.profiler_enabled,
566                enable_debug_groups: other_modes.profiler_enabled,
567                max_num_pending_frames: 4,
568            })
569            .expect("Error creating profiler");
570
571        #[cfg(feature = "egui-ui")]
572        let egui_renderpass = egui_wgpu_backend::RenderPass::new(&device, format, 1);
573
574        let present_modes = surface
575            .get_capabilities(&adapter)
576            .present_modes
577            .into_iter()
578            .filter_map(|present_mode| PresentMode::try_from(present_mode).ok())
579            .collect();
580
581        Ok(Self {
582            device,
583            queue,
584            surface,
585            surface_config,
586
587            state,
588            recreation_pending: None,
589
590            layouts,
591            locals,
592            views,
593
594            sampler,
595            depth_sampler,
596            noise_tex,
597
598            quad_index_buffer_u16,
599            quad_index_buffer_u32,
600
601            shaders,
602            shaders_watcher,
603
604            pipeline_modes,
605            other_modes,
606            resolution: Vec2::new(dims.width, dims.height),
607
608            take_screenshot: None,
609
610            profiler,
611            profile_times: Vec::new(),
612            profiler_features_enabled,
613
614            ui_premultiply_uploads: Default::default(),
615
616            #[cfg(feature = "egui-ui")]
617            egui_renderpass,
618
619            is_minimized: false,
620
621            graphics_backend,
622
623            intermediate_format,
624
625            present_modes,
626            max_texture_size,
627        })
628    }
629
630    /// Get the graphics backend being used
631    pub fn graphics_backend(&self) -> &str { &self.graphics_backend }
632
633    /// Check the status of the intial pipeline creation
634    /// Returns `None` if complete
635    /// Returns `Some((total, complete))` if in progress
636    pub fn pipeline_creation_status(&self) -> Option<(usize, usize)> {
637        if let State::Interface { creating, .. } = &self.state {
638            Some(creating.status())
639        } else {
640            None
641        }
642    }
643
644    /// Check the status the pipeline recreation
645    /// Returns `None` if pipelines are currently not being recreated
646    /// Returns `Some((total, complete))` if in progress
647    pub fn pipeline_recreation_status(&self) -> Option<(usize, usize)> {
648        if let State::Complete { recreating, .. } = &self.state {
649            recreating.as_ref().map(|(_, c)| c.status())
650        } else {
651            None
652        }
653    }
654
655    /// Change the render mode.
656    pub fn set_render_mode(&mut self, mode: RenderMode) -> Result<(), RenderError> {
657        let (pipeline_modes, other_modes) = mode.split();
658
659        if self.other_modes != other_modes {
660            self.other_modes = other_modes;
661
662            // Update present mode in swap chain descriptor if it is supported.
663            if self.present_modes.contains(&self.other_modes.present_mode) {
664                self.surface_config.present_mode = self.other_modes.present_mode.into()
665            }
666
667            // Only enable profiling if the wgpu features are enabled
668            self.other_modes.profiler_enabled &= self.profiler_features_enabled;
669            // Enable/disable profiler
670            if !self.other_modes.profiler_enabled {
671                // Clear the times if disabled
672                core::mem::take(&mut self.profile_times);
673            }
674            self.profiler
675                .change_settings(wgpu_profiler::GpuProfilerSettings {
676                    enable_timer_queries: self.other_modes.profiler_enabled,
677                    enable_debug_groups: self.other_modes.profiler_enabled,
678                    max_num_pending_frames: 4,
679                })
680                .expect("Error creating profiler");
681
682            // Recreate render target
683            self.on_resize(self.resolution);
684        }
685
686        // We can't cancel the pending recreation even if the new settings are equal
687        // to the current ones becuase the recreation could be triggered by something
688        // else like shader hotloading
689        if self.pipeline_modes != pipeline_modes
690            || self
691                .recreation_pending
692                .as_ref()
693                .is_some_and(|modes| modes != &pipeline_modes)
694        {
695            // Recreate pipelines with new modes
696            self.recreate_pipelines(pipeline_modes);
697        }
698
699        Ok(())
700    }
701
702    /// Get the pipelines mode.
703    pub fn pipeline_modes(&self) -> &PipelineModes { &self.pipeline_modes }
704
705    /// Get the supported present modes.
706    pub fn present_modes(&self) -> &[PresentMode] { &self.present_modes }
707
708    /// Get the current profiling times
709    /// Nested timings immediately follow their parent
710    /// Returns Vec<(how nested this timing is, label, length in seconds)>
711    pub fn timings(&self) -> Vec<(u8, &str, f64)> {
712        fn recursive_collect<'a>(
713            vec: &mut Vec<(u8, &'a str, f64)>,
714            result: &'a wgpu_profiler::GpuTimerQueryResult,
715            nest_level: u8,
716        ) {
717            if let Some(time) = &result.time {
718                vec.push((nest_level, &result.label, time.end - time.start));
719            }
720            result
721                .nested_queries
722                .iter()
723                .for_each(|child| recursive_collect(vec, child, nest_level + 1));
724        }
725        let mut vec = Vec::new();
726        self.profile_times
727            .iter()
728            .for_each(|child| recursive_collect(&mut vec, child, 0));
729        vec
730    }
731
732    /// Resize internal render targets to match window render target dimensions.
733    pub fn on_resize(&mut self, dims: Vec2<u32>) {
734        // Avoid panics when creating texture with w,h of 0,0.
735        if dims.x != 0 && dims.y != 0 {
736            self.is_minimized = false;
737            // Resize swap chain
738            self.resolution = dims;
739            self.surface_config.width = dims.x;
740            self.surface_config.height = dims.y;
741            self.surface.configure(&self.device, &self.surface_config);
742
743            // Resize other render targets
744            let (views, bloom_sizes) = Self::create_rt_views(
745                &self.device,
746                (dims.x, dims.y),
747                &self.pipeline_modes,
748                &self.other_modes,
749                self.intermediate_format,
750            );
751            self.views = views;
752
753            let bloom_params = self
754                .views
755                .bloom_tgts
756                .as_ref()
757                .map(|tgts| locals::BloomParams {
758                    locals: bloom_sizes.map(|size| {
759                        Self::create_consts_inner(&self.device, &self.queue, &[bloom::Locals::new(
760                            size,
761                        )])
762                    }),
763                    src_views: [
764                        &self.views.tgt_color_pp,
765                        &tgts[1],
766                        &tgts[2],
767                        &tgts[3],
768                        &tgts[4],
769                    ],
770                    final_tgt_view: &tgts[0],
771                });
772
773            self.locals.rebind(
774                &self.device,
775                &self.layouts,
776                &self.views.tgt_color,
777                &self.views.tgt_mat,
778                &self.views.tgt_depth,
779                bloom_params,
780                &self.views.tgt_color_pp,
781                &self.sampler,
782                &self.depth_sampler,
783            );
784
785            // Get mutable reference to shadow views out of the current state
786            let shadow_views = match &mut self.state {
787                State::Interface {
788                    shadow_views,
789                    rain_occlusion_view,
790                    ..
791                } => shadow_views
792                    .as_mut()
793                    .map(|s| (&mut s.0, &mut s.1))
794                    .zip(rain_occlusion_view.as_mut()),
795                State::Complete {
796                    shadow:
797                        Shadow {
798                            map: ShadowMap::Enabled(shadow_map),
799                            rain_map: RainOcclusionMap::Enabled(rain_occlusion_map),
800                            ..
801                        },
802                    ..
803                } => Some((
804                    (&mut shadow_map.point_depth, &mut shadow_map.directed_depth),
805                    &mut rain_occlusion_map.depth,
806                )),
807                State::Complete { .. } => None,
808                State::Nothing => None, // Should never hit this
809            };
810
811            let mut update_shadow_bind = false;
812            let (shadow_views, rain_views) = shadow_views.unzip();
813
814            if let (Some((point_depth, directed_depth)), ShadowMode::Map(mode)) =
815                (shadow_views, self.pipeline_modes.shadow)
816            {
817                match ShadowMap::create_shadow_views(
818                    &self.device,
819                    (dims.x, dims.y),
820                    &mode,
821                    self.max_texture_size,
822                ) {
823                    Ok((new_point_depth, new_directed_depth)) => {
824                        *point_depth = new_point_depth;
825                        *directed_depth = new_directed_depth;
826
827                        update_shadow_bind = true;
828                    },
829                    Err(err) => {
830                        warn!("Could not create shadow map views: {:?}", err);
831                    },
832                }
833            }
834            if let Some(rain_depth) = rain_views {
835                match RainOcclusionMap::create_view(
836                    &self.device,
837                    &self.pipeline_modes.rain_occlusion,
838                    self.max_texture_size,
839                ) {
840                    Ok(new_rain_depth) => {
841                        *rain_depth = new_rain_depth;
842
843                        update_shadow_bind = true;
844                    },
845                    Err(err) => {
846                        warn!("Could not create rain occlusion map view: {:?}", err);
847                    },
848                }
849            }
850            if update_shadow_bind {
851                // Recreate the shadow bind group if needed
852                if let State::Complete {
853                    shadow:
854                        Shadow {
855                            bind,
856                            map: ShadowMap::Enabled(shadow_map),
857                            rain_map: RainOcclusionMap::Enabled(rain_occlusion_map),
858                            ..
859                        },
860                    ..
861                } = &mut self.state
862                {
863                    *bind = self.layouts.global.bind_shadow_textures(
864                        &self.device,
865                        &shadow_map.point_depth,
866                        &shadow_map.directed_depth,
867                        &rain_occlusion_map.depth,
868                    );
869                }
870            }
871        } else {
872            self.is_minimized = true;
873        }
874    }
875
876    pub fn maintain(&self) {
877        if self.is_minimized {
878            self.queue.submit(std::iter::empty());
879        }
880
881        let _ = self.device.poll(wgpu::PollType::Poll);
882    }
883
884    /// Create render target views
885    fn create_rt_views(
886        device: &wgpu::Device,
887        size: (u32, u32),
888        pipeline_modes: &PipelineModes,
889        other_modes: &OtherModes,
890        format: wgpu::TextureFormat,
891    ) -> (Views, [Vec2<f32>; bloom::NUM_SIZES]) {
892        let upscaled = Vec2::<u32>::from(size)
893            .map(|e| (e as f32 * other_modes.upscale_mode.factor) as u32)
894            .into_tuple();
895        let (width, height) = upscaled;
896        let sample_count = pipeline_modes.aa.samples();
897        let levels = 1;
898
899        let color_view = |width, height, format| {
900            let tex = device.create_texture(&wgpu::TextureDescriptor {
901                label: None,
902                size: wgpu::Extent3d {
903                    width,
904                    height,
905                    depth_or_array_layers: 1,
906                },
907                mip_level_count: levels,
908                sample_count,
909                dimension: wgpu::TextureDimension::D2,
910                format,
911                usage: wgpu::TextureUsages::TEXTURE_BINDING
912                    | wgpu::TextureUsages::RENDER_ATTACHMENT,
913                view_formats: &[],
914            });
915
916            tex.create_view(&wgpu::TextureViewDescriptor {
917                label: None,
918                format: Some(format),
919                dimension: Some(wgpu::TextureViewDimension::D2),
920                usage: None,
921                // TODO: why is this not Color?
922                aspect: wgpu::TextureAspect::All,
923                base_mip_level: 0,
924                mip_level_count: None,
925                base_array_layer: 0,
926                array_layer_count: None,
927            })
928        };
929
930        let tgt_color_view = color_view(width, height, format);
931        let tgt_color_pp_view = color_view(width, height, format);
932
933        let tgt_mat_view = color_view(width, height, wgpu::TextureFormat::Rgba8Uint);
934
935        let mut size_shift = 0;
936        // TODO: skip creating bloom stuff when it is disabled
937        let bloom_sizes = [(); bloom::NUM_SIZES].map(|()| {
938            // .max(1) to ensure we don't create zero sized textures
939            let size = Vec2::new(width, height).map(|e| (e >> size_shift).max(1));
940            size_shift += 1;
941            size
942        });
943
944        let bloom_tgt_views = pipeline_modes
945            .bloom
946            .is_on()
947            .then(|| bloom_sizes.map(|size| color_view(size.x, size.y, format)));
948
949        let tgt_depth_tex = device.create_texture(&wgpu::TextureDescriptor {
950            label: None,
951            size: wgpu::Extent3d {
952                width,
953                height,
954                depth_or_array_layers: 1,
955            },
956            mip_level_count: levels,
957            sample_count,
958            dimension: wgpu::TextureDimension::D2,
959            format: wgpu::TextureFormat::Depth32Float,
960            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
961            view_formats: &[],
962        });
963        let tgt_depth_view = tgt_depth_tex.create_view(&wgpu::TextureViewDescriptor {
964            label: None,
965            format: Some(wgpu::TextureFormat::Depth32Float),
966            dimension: Some(wgpu::TextureViewDimension::D2),
967            usage: None,
968            aspect: wgpu::TextureAspect::DepthOnly,
969            base_mip_level: 0,
970            mip_level_count: None,
971            base_array_layer: 0,
972            array_layer_count: None,
973        });
974
975        let win_depth_tex = device.create_texture(&wgpu::TextureDescriptor {
976            label: None,
977            size: wgpu::Extent3d {
978                width: size.0,
979                height: size.1,
980                depth_or_array_layers: 1,
981            },
982            mip_level_count: levels,
983            sample_count,
984            dimension: wgpu::TextureDimension::D2,
985            format: wgpu::TextureFormat::Depth32Float,
986            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
987            view_formats: &[],
988        });
989        // TODO: Consider no depth buffer for the final draw to the window?
990        let win_depth_view = win_depth_tex.create_view(&wgpu::TextureViewDescriptor {
991            label: None,
992            format: Some(wgpu::TextureFormat::Depth32Float),
993            dimension: Some(wgpu::TextureViewDimension::D2),
994            usage: None,
995            aspect: wgpu::TextureAspect::DepthOnly,
996            base_mip_level: 0,
997            mip_level_count: None,
998            base_array_layer: 0,
999            array_layer_count: None,
1000        });
1001
1002        (
1003            Views {
1004                tgt_color: tgt_color_view,
1005                tgt_mat: tgt_mat_view,
1006                tgt_depth: tgt_depth_view,
1007                bloom_tgts: bloom_tgt_views,
1008                tgt_color_pp: tgt_color_pp_view,
1009                _win_depth: win_depth_view,
1010            },
1011            bloom_sizes.map(|s| s.map(|e| e as f32)),
1012        )
1013    }
1014
1015    /// Get the resolution of the render target.
1016    pub fn resolution(&self) -> Vec2<u32> { self.resolution }
1017
1018    /// Get the resolution of the shadow render target.
1019    pub fn get_shadow_resolution(&self) -> (Vec2<u32>, Vec2<u32>) {
1020        match &self.state {
1021            State::Interface { shadow_views, .. } => shadow_views.as_ref().map(|s| (&s.0, &s.1)),
1022            State::Complete {
1023                shadow:
1024                    Shadow {
1025                        map: ShadowMap::Enabled(shadow_map),
1026                        ..
1027                    },
1028                ..
1029            } => Some((&shadow_map.point_depth, &shadow_map.directed_depth)),
1030            State::Complete { .. } | State::Nothing => None,
1031        }
1032        .map(|(point, directed)| (point.get_dimensions().xy(), directed.get_dimensions().xy()))
1033        .unwrap_or_else(|| (Vec2::new(1, 1), Vec2::new(1, 1)))
1034    }
1035
1036    /// Start recording the frame
1037    /// When the returned `Drawer` is dropped the recorded draw calls will be
1038    /// submitted to the queue
1039    /// If there is an intermittent issue with the swap chain then Ok(None) will
1040    /// be returned
1041    pub fn start_recording_frame<'a>(
1042        &'a mut self,
1043        globals: &'a GlobalsBindGroup,
1044    ) -> Result<Option<drawer::Drawer<'a>>, RenderError> {
1045        span!(
1046            _guard,
1047            "start_recording_frame",
1048            "Renderer::start_recording_frame"
1049        );
1050
1051        if self.is_minimized {
1052            return Ok(None);
1053        }
1054
1055        // Try to get the latest profiling results
1056        if self.other_modes.profiler_enabled {
1057            // Note: this lags a few frames behind
1058            let timestamp_period = self.queue.get_timestamp_period();
1059            if let Some(profile_times) = self.profiler.process_finished_frame(timestamp_period) {
1060                self.profile_times = profile_times;
1061            }
1062        }
1063
1064        // Handle polling background pipeline creation/recreation
1065        // Temporarily set to nothing and then replace in the statement below
1066        let state = core::mem::replace(&mut self.state, State::Nothing);
1067        // Indicator for if pipeline recreation finished and we need to recreate bind
1068        // groups / render targets (handling defered so that State will be valid
1069        // when calling Self::on_resize)
1070        let mut trigger_on_resize = false;
1071        // If still creating initial pipelines, check if complete
1072        self.state = if let State::Interface {
1073            pipelines: interface,
1074            shadow_views,
1075            rain_occlusion_view,
1076            creating,
1077        } = state
1078        {
1079            match creating.try_complete() {
1080                Ok(pipelines) => {
1081                    let IngameAndShadowPipelines {
1082                        ingame,
1083                        shadow,
1084                        rain_occlusion,
1085                    } = pipelines;
1086
1087                    let pipelines = Pipelines::consolidate(interface, ingame);
1088
1089                    let shadow_map = ShadowMap::new(
1090                        &self.device,
1091                        &self.queue,
1092                        shadow.point,
1093                        shadow.directed,
1094                        shadow.figure,
1095                        shadow.debug,
1096                        shadow_views,
1097                    );
1098
1099                    let rain_occlusion_map = RainOcclusionMap::new(
1100                        &self.device,
1101                        &self.queue,
1102                        rain_occlusion.terrain,
1103                        rain_occlusion.figure,
1104                        rain_occlusion_view,
1105                    );
1106
1107                    let shadow_bind = {
1108                        let (point, directed) = shadow_map.textures();
1109                        self.layouts.global.bind_shadow_textures(
1110                            &self.device,
1111                            point,
1112                            directed,
1113                            rain_occlusion_map.texture(),
1114                        )
1115                    };
1116
1117                    let shadow = Shadow {
1118                        rain_map: rain_occlusion_map,
1119                        map: shadow_map,
1120                        bind: shadow_bind,
1121                    };
1122
1123                    State::Complete {
1124                        pipelines,
1125                        shadow,
1126                        recreating: None,
1127                    }
1128                },
1129                // Not complete
1130                Err(creating) => State::Interface {
1131                    pipelines: interface,
1132                    shadow_views,
1133                    rain_occlusion_view,
1134                    creating,
1135                },
1136            }
1137        // If recreating the pipelines, check if that is complete
1138        } else if let State::Complete {
1139            pipelines,
1140            mut shadow,
1141            recreating: Some((new_pipeline_modes, pipeline_creation)),
1142        } = state
1143        {
1144            match pipeline_creation.try_complete() {
1145                Ok(Ok((
1146                    pipelines,
1147                    shadow_pipelines,
1148                    rain_occlusion_pipelines,
1149                    postprocess_layout,
1150                ))) => {
1151                    if let (
1152                        Some(point_pipeline),
1153                        Some(terrain_directed_pipeline),
1154                        Some(figure_directed_pipeline),
1155                        Some(debug_directed_pipeline),
1156                        ShadowMap::Enabled(shadow_map),
1157                    ) = (
1158                        shadow_pipelines.point,
1159                        shadow_pipelines.directed,
1160                        shadow_pipelines.figure,
1161                        shadow_pipelines.debug,
1162                        &mut shadow.map,
1163                    ) {
1164                        shadow_map.point_pipeline = point_pipeline;
1165                        shadow_map.terrain_directed_pipeline = terrain_directed_pipeline;
1166                        shadow_map.figure_directed_pipeline = figure_directed_pipeline;
1167                        shadow_map.debug_directed_pipeline = debug_directed_pipeline;
1168                    }
1169
1170                    if let (
1171                        Some(terrain_directed_pipeline),
1172                        Some(figure_directed_pipeline),
1173                        RainOcclusionMap::Enabled(rain_occlusion_map),
1174                    ) = (
1175                        rain_occlusion_pipelines.terrain,
1176                        rain_occlusion_pipelines.figure,
1177                        &mut shadow.rain_map,
1178                    ) {
1179                        rain_occlusion_map.terrain_pipeline = terrain_directed_pipeline;
1180                        rain_occlusion_map.figure_pipeline = figure_directed_pipeline;
1181                    }
1182
1183                    self.pipeline_modes = new_pipeline_modes;
1184                    self.layouts.postprocess = postprocess_layout;
1185                    // TODO: we have the potential to skip recreating bindings / render targets on
1186                    // pipeline recreation trigged by shader reloading (would need to ensure new
1187                    // postprocess_layout is not created...)
1188                    trigger_on_resize = true;
1189
1190                    State::Complete {
1191                        pipelines,
1192                        shadow,
1193                        recreating: None,
1194                    }
1195                },
1196                Ok(Err(e)) => {
1197                    error!(?e, "Could not recreate shaders from assets due to an error");
1198                    State::Complete {
1199                        pipelines,
1200                        shadow,
1201                        recreating: None,
1202                    }
1203                },
1204                // Not complete
1205                Err(pipeline_creation) => State::Complete {
1206                    pipelines,
1207                    shadow,
1208                    recreating: Some((new_pipeline_modes, pipeline_creation)),
1209                },
1210            }
1211        } else {
1212            state
1213        };
1214
1215        // Call on_resize to recreate render targets and their bind groups if the
1216        // pipelines were recreated with a new postprocess layout and or changes in the
1217        // render modes
1218        if trigger_on_resize {
1219            self.on_resize(self.resolution);
1220        }
1221
1222        // If the shaders files were changed attempt to recreate the shaders
1223        if self.shaders_watcher.reloaded() {
1224            self.recreate_pipelines(self.pipeline_modes.clone());
1225        }
1226
1227        // Or if we have a recreation pending
1228        if matches!(&self.state, State::Complete {
1229            recreating: None,
1230            ..
1231        }) && let Some(new_pipeline_modes) = self.recreation_pending.take()
1232        {
1233            self.recreate_pipelines(new_pipeline_modes);
1234        }
1235
1236        let texture = match self.surface.get_current_texture() {
1237            Ok(texture) => texture,
1238            // If lost recreate the swap chain
1239            Err(err @ wgpu::SurfaceError::Lost) => {
1240                warn!("{}. Recreating swap chain. A frame will be missed", err);
1241                self.on_resize(self.resolution);
1242                return Ok(None);
1243            },
1244            Err(wgpu::SurfaceError::Timeout) => {
1245                // This will probably be resolved on the next frame
1246                // NOTE: we don't log this because it happens very frequently with
1247                // PresentMode::Fifo and unlimited FPS on certain machines
1248                return Ok(None);
1249            },
1250            Err(err @ wgpu::SurfaceError::Outdated) => {
1251                warn!("{}. Recreating the swapchain", err);
1252                self.surface.configure(&self.device, &self.surface_config);
1253                return Ok(None);
1254            },
1255            Err(err @ (wgpu::SurfaceError::OutOfMemory | wgpu::SurfaceError::Other)) => {
1256                return Err(err.into());
1257            },
1258        };
1259        let encoder = self
1260            .device
1261            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1262                label: Some("A render encoder"),
1263            });
1264
1265        Ok(Some(drawer::Drawer::new(encoder, self, texture, globals)))
1266    }
1267
1268    /// Recreate the pipelines
1269    fn recreate_pipelines(&mut self, pipeline_modes: PipelineModes) {
1270        match &mut self.state {
1271            State::Complete { recreating, .. } if recreating.is_some() => {
1272                // Defer recreation so that we are not building multiple sets of pipelines in
1273                // the background at once
1274                self.recreation_pending = Some(pipeline_modes);
1275            },
1276            State::Complete {
1277                recreating, shadow, ..
1278            } => {
1279                *recreating = Some((
1280                    pipeline_modes.clone(),
1281                    pipeline_creation::recreate_pipelines(
1282                        self.device.clone(),
1283                        Arc::clone(&self.layouts.immutable),
1284                        self.shaders.cloned(),
1285                        pipeline_modes,
1286                        // NOTE: if present_mode starts to be used to configure pipelines then it
1287                        // needs to become a part of the pipeline modes
1288                        // (note here since the present mode is accessible
1289                        // through the swap chain descriptor)
1290                        self.surface_config.clone(), // Note: cheap clone
1291                        shadow.map.is_enabled(),
1292                        self.intermediate_format,
1293                    ),
1294                ));
1295            },
1296            State::Interface { .. } => {
1297                // Defer recreation so that we are not building multiple sets of pipelines in
1298                // the background at once
1299                self.recreation_pending = Some(pipeline_modes);
1300            },
1301            State::Nothing => {},
1302        }
1303    }
1304
1305    /// Create a new set of constants with the provided values.
1306    pub fn create_consts<T: Copy + bytemuck::Pod>(&mut self, vals: &[T]) -> Consts<T> {
1307        Self::create_consts_inner(&self.device, &self.queue, vals)
1308    }
1309
1310    pub fn create_consts_inner<T: Copy + bytemuck::Pod>(
1311        device: &wgpu::Device,
1312        queue: &wgpu::Queue,
1313        vals: &[T],
1314    ) -> Consts<T> {
1315        let mut consts = Consts::new(device, vals.len());
1316        consts.update(queue, vals, 0);
1317        consts
1318    }
1319
1320    /// Update a set of constants with the provided values.
1321    pub fn update_consts<T: Copy + bytemuck::Pod>(&self, consts: &mut Consts<T>, vals: &[T]) {
1322        consts.update(&self.queue, vals, 0)
1323    }
1324
1325    pub fn update_clouds_locals(&mut self, new_val: clouds::Locals) {
1326        self.locals.clouds.update(&self.queue, &[new_val], 0)
1327    }
1328
1329    pub fn update_postprocess_locals(&mut self, new_val: postprocess::Locals) {
1330        self.locals.postprocess.update(&self.queue, &[new_val], 0)
1331    }
1332
1333    /// Create a new set of instances with the provided values.
1334    pub fn create_instances<T: Copy + bytemuck::Pod>(&mut self, vals: &[T]) -> Instances<T> {
1335        let mut instances = Instances::new(&self.device, vals.len());
1336        instances.update(&self.queue, vals, 0);
1337        instances
1338    }
1339
1340    /// Ensure that the quad index buffer is large enough for a quad vertex
1341    /// buffer with this many vertices
1342    pub(super) fn ensure_sufficient_index_length<V: Vertex>(
1343        &mut self,
1344        // Length of the vert buffer with 4 verts per quad
1345        vert_length: usize,
1346    ) {
1347        let quad_index_length = vert_length / 4 * 6;
1348
1349        match V::QUADS_INDEX {
1350            Some(wgpu::IndexFormat::Uint16) => {
1351                // Make sure the global quad index buffer is large enough
1352                if self.quad_index_buffer_u16.len() < quad_index_length {
1353                    // Make sure we aren't over the max
1354                    if vert_length > u16::MAX as usize {
1355                        panic!(
1356                            "Vertex type: {} needs to use a larger index type, length: {}",
1357                            core::any::type_name::<V>(),
1358                            vert_length
1359                        );
1360                    }
1361                    self.quad_index_buffer_u16 =
1362                        create_quad_index_buffer_u16(&self.device, vert_length);
1363                }
1364            },
1365            Some(wgpu::IndexFormat::Uint32) => {
1366                // Make sure the global quad index buffer is large enough
1367                if self.quad_index_buffer_u32.len() < quad_index_length {
1368                    // Make sure we aren't over the max
1369                    if vert_length > u32::MAX as usize {
1370                        panic!(
1371                            "More than u32::MAX({}) verts({}) for type({}) using an index buffer!",
1372                            u32::MAX,
1373                            vert_length,
1374                            core::any::type_name::<V>()
1375                        );
1376                    }
1377                    self.quad_index_buffer_u32 =
1378                        create_quad_index_buffer_u32(&self.device, vert_length);
1379                }
1380            },
1381            None => {},
1382        }
1383    }
1384
1385    pub fn create_sprite_verts(&mut self, mesh: Mesh<sprite::Vertex>) -> sprite::SpriteVerts {
1386        self.ensure_sufficient_index_length::<sprite::Vertex>(sprite::VERT_PAGE_SIZE as usize);
1387        sprite::create_verts_buffer(&self.device, mesh)
1388    }
1389
1390    /// Create a new model from the provided mesh.
1391    /// If the provided mesh is empty this returns None
1392    pub fn create_model<V: Vertex>(&mut self, mesh: &Mesh<V>) -> Option<Model<V>> {
1393        self.ensure_sufficient_index_length::<V>(mesh.vertices().len());
1394        Model::new(&self.device, mesh)
1395    }
1396
1397    /// Create a new dynamic model with the specified size.
1398    pub fn create_dynamic_model<V: Vertex>(&mut self, size: usize) -> DynamicModel<V> {
1399        self.ensure_sufficient_index_length::<V>(size);
1400        DynamicModel::new(&self.device, size)
1401    }
1402
1403    /// Update a dynamic model with a mesh and a offset.
1404    pub fn update_model<V: Vertex>(&self, model: &DynamicModel<V>, mesh: &Mesh<V>, offset: usize) {
1405        model.update(&self.queue, mesh, offset)
1406    }
1407
1408    /// Return the maximum supported texture size.
1409    pub fn max_texture_size(&self) -> u32 { self.max_texture_size }
1410
1411    /// Create a new immutable texture from the provided image.
1412    /// # Panics
1413    /// If the provided data doesn't completely fill the texture this function
1414    /// will panic.
1415    pub fn create_texture_with_data_raw(
1416        &mut self,
1417        texture_info: &wgpu::TextureDescriptor,
1418        view_info: &wgpu::TextureViewDescriptor,
1419        sampler_info: &wgpu::SamplerDescriptor,
1420        data: &[u8],
1421    ) -> Texture {
1422        let tex = Texture::new_raw(&self.device, texture_info, view_info, sampler_info);
1423
1424        let size = texture_info.size;
1425        let block_size = texture_info.format.block_copy_size(None).unwrap();
1426        assert_eq!(
1427            size.width as usize
1428                * size.height as usize
1429                * size.depth_or_array_layers as usize
1430                * block_size as usize,
1431            data.len(),
1432            "Provided data length {} does not fill the provided texture size {:?}",
1433            data.len(),
1434            size,
1435        );
1436
1437        tex.update(
1438            &self.queue,
1439            [0; 2],
1440            [texture_info.size.width, texture_info.size.height],
1441            data,
1442        );
1443
1444        tex
1445    }
1446
1447    /// Create a new raw texture.
1448    pub fn create_texture_raw(
1449        &mut self,
1450        texture_info: &wgpu::TextureDescriptor,
1451        view_info: &wgpu::TextureViewDescriptor,
1452        sampler_info: &wgpu::SamplerDescriptor,
1453    ) -> Texture {
1454        let texture = Texture::new_raw(&self.device, texture_info, view_info, sampler_info);
1455        texture.clear(&self.queue); // Needs to be fully initialized for partial writes to work on Dx12 AMD
1456        texture
1457    }
1458
1459    /// Create a new texture from the provided image.
1460    pub fn create_texture(
1461        &mut self,
1462        image: &image::DynamicImage,
1463        filter_method: Option<FilterMode>,
1464        address_mode: Option<AddressMode>,
1465    ) -> Result<Texture, RenderError> {
1466        Texture::new(
1467            &self.device,
1468            &self.queue,
1469            image,
1470            filter_method,
1471            address_mode,
1472        )
1473    }
1474
1475    /// Create a new dynamic texture with the specified dimensions.
1476    ///
1477    /// Currently only supports Rgba8Srgb.
1478    pub fn create_dynamic_texture(&mut self, dims: Vec2<u32>) -> Texture {
1479        Texture::new_dynamic(&self.device, &self.queue, dims.x, dims.y)
1480    }
1481
1482    /// Update a texture with the provided offset, size, and data.
1483    pub fn update_texture<T: bytemuck::Pod>(
1484        &mut self,
1485        texture: &Texture,
1486        offset: [u32; 2],
1487        size: [u32; 2],
1488        data: &[T],
1489    ) {
1490        texture.update(&self.queue, offset, size, bytemuck::cast_slice(data))
1491    }
1492
1493    /// See docs on [`ui::BatchedUploads::submit`].
1494    pub fn ui_premultiply_upload(
1495        &mut self,
1496        target_texture: &Arc<Texture>,
1497        batch: ui::UploadBatchId,
1498        image: &image::RgbaImage,
1499        offset: Vec2<u16>,
1500    ) -> ui::UploadBatchId {
1501        let upload = ui::PremultiplyUpload::prepare(
1502            &self.device,
1503            &self.queue,
1504            &self.layouts.premultiply_alpha,
1505            image,
1506            offset,
1507        );
1508        self.ui_premultiply_uploads
1509            .submit(target_texture, batch, upload)
1510    }
1511
1512    /// Queue to obtain a screenshot on the next frame render
1513    pub fn create_screenshot(
1514        &mut self,
1515        screenshot_handler: impl FnOnce(Result<image::RgbImage, String>) + Send + 'static,
1516    ) {
1517        // Queue screenshot
1518        self.take_screenshot = Some(Box::new(screenshot_handler));
1519        // Take profiler snapshot
1520        if self.other_modes.profiler_enabled {
1521            let file_name = format!(
1522                "frame-trace_{}.json",
1523                std::time::SystemTime::now()
1524                    .duration_since(std::time::SystemTime::UNIX_EPOCH)
1525                    .map(|d| d.as_millis())
1526                    .unwrap_or(0)
1527            );
1528
1529            if let Err(err) = wgpu_profiler::chrometrace::write_chrometrace(
1530                std::path::Path::new(&file_name),
1531                &self.profile_times,
1532            ) {
1533                error!(?err, "Failed to save GPU timing snapshot");
1534            } else {
1535                info!("Saved GPU timing snapshot as: {}", file_name);
1536            }
1537        }
1538    }
1539
1540    // Consider reenabling at some time
1541    //
1542    // /// Queue the rendering of the player silhouette in the upcoming frame.
1543    // pub fn render_player_shadow(
1544    //     &mut self,
1545    //     _model: &figure::FigureModel,
1546    //     _col_lights: &Texture<ColLightFmt>,
1547    //     _global: &GlobalModel,
1548    //     _bones: &Consts<figure::BoneData>,
1549    //     _lod: &lod_terrain::LodData,
1550    //     _locals: &Consts<shadow::Locals>,
1551    // ) { // FIXME: Consider reenabling at some point. /* let (point_shadow_maps,
1552    //   directed_shadow_maps) = if let Some(shadow_map) = &mut self.shadow_map { (
1553    //   ( shadow_map.point_res.clone(), shadow_map.point_sampler.clone(), ), (
1554    //   shadow_map.directed_res.clone(), shadow_map.directed_sampler.clone(), ), )
1555    //   } else { ( (self.noise_tex.srv.clone(), self.noise_tex.sampler.clone()),
1556    //   (self.noise_tex.srv.clone(), self.noise_tex.sampler.clone()), ) }; let
1557    //   model = &model.opaque;
1558
1559    //     self.encoder.draw(
1560    //         &gfx::Slice {
1561    //             start: model.vertex_range().start,
1562    //             end: model.vertex_range().end,
1563    //             base_vertex: 0,
1564    //             instances: None,
1565    //             buffer: gfx::IndexBuffer::Auto,
1566    //         },
1567    //         &self.player_shadow_pipeline.pso,
1568    //         &figure::pipe::Data {
1569    //             vbuf: model.vbuf.clone(),
1570    //             col_lights: (col_lights.srv.clone(), col_lights.sampler.clone()),
1571    //             locals: locals.buf.clone(),
1572    //             globals: global.globals.buf.clone(),
1573    //             bones: bones.buf.clone(),
1574    //             lights: global.lights.buf.clone(),
1575    //             shadows: global.shadows.buf.clone(),
1576    //             light_shadows: global.shadow_mats.buf.clone(),
1577    //             point_shadow_maps,
1578    //             directed_shadow_maps,
1579    //             noise: (self.noise_tex.srv.clone(),
1580    // self.noise_tex.sampler.clone()),             alt: (lod.alt.srv.clone(),
1581    // lod.alt.sampler.clone()),             horizon: (lod.horizon.srv.clone(),
1582    // lod.horizon.sampler.clone()),             tgt_color:
1583    // self.tgt_color_view.clone(),             tgt_depth:
1584    // (self.tgt_depth_view.clone()/* , (0, 0) */),         },
1585    //     ); */
1586    // }
1587}
1588
1589fn create_quad_index_buffer_u16(device: &wgpu::Device, vert_length: usize) -> Buffer<u16> {
1590    assert!(vert_length <= u16::MAX as usize);
1591    let indices = [0, 1, 2, 2, 1, 3]
1592        .iter()
1593        .cycle()
1594        .copied()
1595        .take(vert_length / 4 * 6)
1596        .enumerate()
1597        .map(|(i, b)| (i / 6 * 4 + b) as u16)
1598        .collect::<Vec<_>>();
1599
1600    Buffer::new(device, wgpu::BufferUsages::INDEX, &indices)
1601}
1602
1603fn create_quad_index_buffer_u32(device: &wgpu::Device, vert_length: usize) -> Buffer<u32> {
1604    assert!(vert_length <= u32::MAX as usize);
1605    let indices = [0, 1, 2, 2, 1, 3]
1606        .iter()
1607        .cycle()
1608        .copied()
1609        .take(vert_length / 4 * 6)
1610        .enumerate()
1611        .map(|(i, b)| (i / 6 * 4 + b) as u32)
1612        .collect::<Vec<_>>();
1613
1614    Buffer::new(device, wgpu::BufferUsages::INDEX, &indices)
1615}
1616
1617/// Terrain-related buffers segment themselves by depth to allow us to do
1618/// primitive occlusion culling based on whether the camera is underground or
1619/// not. This struct specifies the buffer offsets at which various layers start
1620/// and end.
1621///
1622/// 'Deep' structures appear within the range `0..deep_end`.
1623///
1624/// 'Shallow' structures appear within the range `deep_end..underground_end`.
1625///
1626/// 'Surface' structures appear within the range `underground_end..`.
1627pub struct AltIndices {
1628    pub deep_end: usize,
1629    pub underground_end: usize,
1630}
1631
1632/// The mode with which culling based on the camera position relative to the
1633/// terrain is performed.
1634#[derive(Copy, Clone, Default)]
1635pub enum CullingMode {
1636    /// We need to render all elements of the given structure
1637    #[default]
1638    None,
1639    /// We only need to render surface and shallow (i.e: in the overlapping
1640    /// region) elements of the structure
1641    Surface,
1642    /// We only need to render shallow (i.e: in the overlapping region) and deep
1643    /// elements of the structure
1644    Underground,
1645}