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