bevy_pbr 0.19.0

Adds PBR rendering to Bevy Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
//! Light probes for baked global illumination.

use bevy_app::{App, Plugin};
use bevy_asset::AssetId;
use bevy_camera::{visibility::VisibleEntities, Camera3d};
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
    component::Component,
    entity::Entity,
    query::{QueryData, ReadOnlyQueryData, With},
    resource::Resource,
    schedule::IntoScheduleConfigs,
    system::{Commands, Local, Query, Res, ResMut},
};
use bevy_image::Image;
use bevy_light::{
    cluster::ClusterVisibilityClass, EnvironmentMapLight, IrradianceVolume, LightProbe,
};
use bevy_math::{Affine3A, FloatOrd, Mat4, Quat, Vec3, Vec4};
use bevy_platform::collections::HashMap;
use bevy_render::{
    extract_instances::ExtractInstancesPlugin,
    render_asset::RenderAssets,
    render_resource::{DynamicUniformBuffer, Sampler, ShaderType, TextureView},
    renderer::{RenderAdapter, RenderAdapterInfo, RenderDevice, RenderQueue, WgpuWrapper},
    settings::WgpuFeatures,
    sync_world::{MainEntity, MainEntityHashMap, RenderEntity},
    texture::{FallbackImage, GpuImage},
    view::ExtractedView,
    Extract, ExtractSchedule, GpuResourceAppExt, Render, RenderApp, RenderSystems,
};
use bevy_shader::load_shader_library;
use bevy_transform::prelude::GlobalTransform;
use bitflags::bitflags;
use tracing::error;

use core::{any::TypeId, hash::Hash, ops::Deref};

use crate::{
    extract_clusters_for_cpu_clustering, generate::EnvironmentMapGenerationPlugin,
    gpu::extract_clusters_for_gpu_clustering, light_probe::environment_map::EnvironmentMapIds,
};

pub mod environment_map;
pub mod generate;
pub mod irradiance_volume;

/// The maximum number of each type of light probe that each view will consider.
///
/// Because the fragment shader does a linear search through the list for each
/// fragment, this number needs to be relatively small.
pub const MAX_VIEW_LIGHT_PROBES: usize = 8;

/// How many texture bindings are used in the fragment shader, *not* counting
/// environment maps or irradiance volumes.
const STANDARD_MATERIAL_FRAGMENT_SHADER_MIN_TEXTURE_BINDINGS: usize = 16;

/// Adds support for light probes: cuboid bounding regions that apply global
/// illumination to objects within them.
///
/// This also adds support for view environment maps: diffuse and specular
/// cubemaps applied to all objects that a view renders.
pub struct LightProbePlugin;

/// A GPU type that stores information about a light probe.
#[derive(Clone, Copy, ShaderType, Default)]
struct RenderLightProbe {
    /// The transform from the world space to the model space. This is used to
    /// efficiently check for bounding box intersection.
    light_from_world_transposed: [Vec4; 3],

    /// The falloff region, specified as a fraction of the light probe's
    /// bounding box.
    ///
    /// See the comments in [`LightProbe`] for more details.
    falloff: Vec3,

    /// The radius of the bounding sphere that encompasses this light probe.
    ///
    /// This could be computed from [`Self::light_from_world_transposed`], but
    /// that requires inverting a matrix, which we don't want to do in the GPU
    /// light clustering kernel.
    bounding_sphere_radius: f32,

    /// The boundaries of the simulated space used for parallax correction,
    /// specified as *half* extents in light probe space.
    ///
    /// If parallax correction is disabled in [`RenderLightProbe::flags`], this
    /// field is ignored.
    ///
    /// See the comments in [`bevy_light::ParallaxCorrection::Custom`] for more
    /// details.
    parallax_correction_bounds: Vec3,

    /// Scale factor applied to the light generated by this light probe.
    ///
    /// See the comment in [`EnvironmentMapLight`] for details.
    intensity: f32,

    /// The world-space position of this light probe.
    ///
    /// This could be computed from [`Self::light_from_world_transposed`], but
    /// that requires inverting a matrix, which we don't want to do in the GPU
    /// light clustering kernel.
    world_position: Vec3,

    /// The index of the texture or textures in the appropriate binding array or
    /// arrays.
    ///
    /// For example, for reflection probes this is the index of the cubemap in
    /// the diffuse and specular texture arrays.
    texture_index: i32,

    /// Various flags associated with the light probe: the bit value of
    /// [`RenderLightProbeFlags`].
    flags: u32,
}

/// A per-view shader uniform that specifies all the light probes that the view
/// takes into account.
#[derive(ShaderType)]
pub struct LightProbesUniform {
    /// The list of applicable reflection probes, sorted from nearest to the
    /// camera to the farthest away from the camera.
    reflection_probes: [RenderLightProbe; MAX_VIEW_LIGHT_PROBES],

    /// The list of applicable irradiance volumes, sorted from nearest to the
    /// camera to the farthest away from the camera.
    irradiance_volumes: [RenderLightProbe; MAX_VIEW_LIGHT_PROBES],

    /// The number of reflection probes in the list.
    reflection_probe_count: i32,

    /// The number of irradiance volumes in the list.
    irradiance_volume_count: i32,

    /// The index of the diffuse and specular environment maps associated with
    /// the view itself. This is used as a fallback if no reflection probe in
    /// the list contains the fragment.
    view_cubemap_index: i32,

    /// The smallest valid mipmap level for the specular environment cubemap
    /// associated with the view.
    smallest_specular_mip_level_for_view: u32,

    /// World space rotation applied to environment map cubemaps associated with the view itself.
    view_rotation: Vec4,

    /// The intensity of the environment cubemap associated with the view.
    ///
    /// See the comment in [`EnvironmentMapLight`] for details.
    intensity_for_view: f32,

    /// Whether the environment map attached to the view affects the diffuse
    /// lighting for lightmapped meshes.
    ///
    /// This will be 1 if the map does affect lightmapped meshes or 0 otherwise.
    view_environment_map_affects_lightmapped_mesh_diffuse: u32,
}

/// A GPU buffer that stores information about all light probes.
#[derive(Resource, Default, Deref, DerefMut)]
pub struct LightProbesBuffer(DynamicUniformBuffer<LightProbesUniform>);

/// A component attached to each camera in the render world that stores the
/// index of the [`LightProbesUniform`] in the [`LightProbesBuffer`].
#[derive(Component, Default, Deref, DerefMut)]
pub struct ViewLightProbesUniformOffset(u32);

/// Information that [`gather_light_probes`] keeps about each light probe.
///
/// This information is parameterized by the [`LightProbeComponent`] type. This
/// will either be [`EnvironmentMapLight`] for reflection probes or
/// [`IrradianceVolume`] for irradiance volumes.
struct LightProbeInfo<C>
where
    C: LightProbeComponent,
{
    // The entity of the light probe in the main world.
    main_entity: MainEntity,

    // The transform from world space to light probe space.
    // Stored as the transpose of the inverse transform to compress the structure
    // on the GPU (from 4 `Vec4`s to 3 `Vec4`s). The shader will transpose it
    // to recover the original inverse transform.
    light_from_world: [Vec4; 3],

    // The transform from light probe space to world space.
    world_from_light: Affine3A,

    /// The radius of the bounding sphere that encompasses this light probe.
    ///
    /// This could be computed from [`Self::light_from_world`], but that
    /// requires inverting a matrix, which we don't want to do in the GPU light
    /// clustering kernel.
    bounding_sphere_radius: f32,

    // The falloff region, specified as a fraction of the light probe's
    // bounding box.
    //
    // See the comments in [`LightProbe`] for more details.
    falloff: Vec3,

    /// The boundaries of the simulated space used for parallax correction,
    /// specified as *half* extents in light probe space.
    ///
    /// If parallax correction is disabled in [`RenderLightProbe::flags`], this
    /// field is ignored.
    ///
    /// See the comments in [`bevy_light::ParallaxCorrection::Custom`] for more
    /// details.
    parallax_correction_bounds: Vec3,

    // Scale factor applied to the diffuse and specular light generated by this
    // reflection probe.
    //
    // See the comment in [`EnvironmentMapLight`] for details.
    intensity: f32,

    // Various flags associated with the light probe.
    flags: RenderLightProbeFlags,

    // The IDs of all assets associated with this light probe.
    //
    // Because each type of light probe component may reference different types
    // of assets (e.g. a reflection probe references two cubemap assets while an
    // irradiance volume references a single 3D texture asset), this is generic.
    asset_id: C::AssetId,
}

bitflags! {
    /// Various flags that can be associated with light probes.
    #[derive(Clone, Copy, PartialEq, Debug)]
    pub struct RenderLightProbeFlags: u8 {
        /// Whether this light probe adds to the diffuse contribution of the
        /// irradiance for meshes with lightmaps.
        const AFFECTS_LIGHTMAPPED_MESH_DIFFUSE = 1;
        /// Whether this light probe has parallax correction enabled.
        ///
        /// See the comments in [`bevy_light::NoParallaxCorrection`] for more
        /// information.
        const ENABLE_PARALLAX_CORRECTION = 2;
    }
}

/// A component, part of the render world, that stores the mapping from asset ID
/// or IDs to the texture index in the appropriate binding arrays.
///
/// Cubemap textures belonging to environment maps are collected into binding
/// arrays, and the index of each texture is presented to the shader for runtime
/// lookup. 3D textures belonging to reflection probes are likewise collected
/// into binding arrays, and the shader accesses the 3D texture by index.
///
/// This component is attached to each view in the render world, because each
/// view may have a different set of light probes that it considers and therefore
/// the texture indices are per-view.
#[derive(Component, Default)]
pub struct RenderViewLightProbes<C>
where
    C: LightProbeComponent,
{
    /// The list of environment maps presented to the shader, in order.
    pub binding_index_to_textures: Vec<C::AssetId>,

    /// The reverse of `binding_index_to_cubemap`: a map from the texture ID to
    /// the index in `binding_index_to_cubemap`.
    cubemap_to_binding_index: HashMap<C::AssetId, u32>,

    /// Information about each light probe, ready for upload to the GPU, sorted
    /// in order from closest to the camera to farthest.
    ///
    /// Note that this is not necessarily ordered by binding index. So don't
    /// write code like
    /// `render_light_probes[cubemap_to_binding_index[asset_id]]`; instead
    /// search for the light probe with the appropriate binding index in this
    /// array.
    render_light_probes: Vec<RenderLightProbe>,

    /// A mapping from the main world entity to the index in
    /// `render_light_probes`.
    pub main_entity_to_render_light_probe_index: MainEntityHashMap<u32>,

    /// Information needed to render the light probe attached directly to the
    /// view, if applicable.
    ///
    /// A light probe attached directly to a view represents a "global" light
    /// probe that affects all objects not in the bounding region of any light
    /// probe. Currently, the only light probe type that supports this is the
    /// [`EnvironmentMapLight`].
    view_light_probe_info: Option<C::ViewLightProbeInfo>,
}

/// A trait implemented by all components that represent light probes.
///
/// Currently, the two light probe types are [`EnvironmentMapLight`] and
/// [`IrradianceVolume`], for reflection probes and irradiance volumes
/// respectively.
///
/// Most light probe systems are written to be generic over the type of light
/// probe. This allows much of the code to be shared and enables easy addition
/// of more light probe types (e.g. real-time reflection planes) in the future.
pub trait LightProbeComponent: Send + Sync + Component + Sized {
    /// Holds [`AssetId`]s of the texture or textures that this light probe
    /// references.
    ///
    /// This can just be [`AssetId`] if the light probe only references one
    /// texture. If it references multiple textures, it will be a structure
    /// containing those asset IDs.
    type AssetId: Send + Sync + Clone + Eq + Hash;

    /// If the light probe can be attached to the view itself (as opposed to a
    /// cuboid region within the scene), this contains the information that will
    /// be passed to the GPU in order to render it. Otherwise, this will be
    /// `()`.
    ///
    /// Currently, only reflection probes (i.e. [`EnvironmentMapLight`]) can be
    /// attached directly to views.
    type ViewLightProbeInfo: Send + Sync + Default;

    /// Any additional query data needed to determine the
    /// [`RenderLightProbeFlags`] for this light probe.
    type QueryData: ReadOnlyQueryData;

    /// Returns the asset ID or asset IDs of the texture or textures referenced
    /// by this light probe.
    fn id(&self, image_assets: &RenderAssets<GpuImage>) -> Option<Self::AssetId>;

    /// Returns the intensity of this light probe.
    ///
    /// This is a scaling factor that will be multiplied by the value or values
    /// sampled from the texture.
    fn intensity(&self) -> f32;

    /// Returns the appropriate value of [`RenderLightProbeFlags`] for this
    /// component.
    fn flags(
        &self,
        query_components: &<Self::QueryData as QueryData>::Item<'_, '_>,
    ) -> RenderLightProbeFlags;

    /// Creates an instance of [`RenderViewLightProbes`] containing all the
    /// information needed to render this light probe.
    ///
    /// This is called for every light probe in view every frame.
    fn create_render_view_light_probes(
        view_component: Option<&Self>,
        image_assets: &RenderAssets<GpuImage>,
    ) -> RenderViewLightProbes<Self>;

    /// Given the matrix value of the `GlobalTransform` of the light probe,
    /// returns the matrix that transforms world positions into light probe
    /// space.
    ///
    /// The default implementation simply returns the matrix unchanged, but some
    /// light probes may want to perform other transforms.
    fn get_world_from_light_matrix(&self, original_world_from_light: &Affine3A) -> Affine3A {
        *original_world_from_light
    }

    /// Returns the appropriate parallax correction bounds, as half extents in
    /// light probe space, for this component.
    ///
    /// See the comments in [`bevy_light::ParallaxCorrection::Custom`] for more
    /// details.
    fn parallax_correction_bounds(
        &self,
        _query_components: &<Self::QueryData as QueryData>::Item<'_, '_>,
    ) -> Vec3 {
        Vec3::ZERO
    }
}

impl Plugin for LightProbePlugin {
    fn build(&self, app: &mut App) {
        load_shader_library!(app, "light_probe.wgsl");
        load_shader_library!(app, "environment_map.wgsl");
        load_shader_library!(app, "irradiance_volume.wgsl");

        app.add_plugins((
            EnvironmentMapGenerationPlugin,
            ExtractInstancesPlugin::<EnvironmentMapIds>::new(),
        ));

        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
            return;
        };

        render_app
            .init_gpu_resource::<LightProbesBuffer>()
            .add_systems(
                ExtractSchedule,
                gather_light_probes::<EnvironmentMapLight>
                    .before(extract_clusters_for_cpu_clustering)
                    .before(extract_clusters_for_gpu_clustering),
            )
            .add_systems(
                ExtractSchedule,
                gather_light_probes::<IrradianceVolume>
                    .before(extract_clusters_for_cpu_clustering)
                    .before(extract_clusters_for_gpu_clustering),
            )
            .add_systems(
                Render,
                upload_light_probes.in_set(RenderSystems::PrepareResources),
            );
    }
}

/// Gathers up all light probes of a single type in the scene and assigns them
/// to views, performing frustum culling and distance sorting in the process.
fn gather_light_probes<C>(
    image_assets: Res<RenderAssets<GpuImage>>,
    light_probe_query: Extract<Query<(Entity, &GlobalTransform, &LightProbe, &C, C::QueryData)>>,
    view_query: Extract<
        Query<(RenderEntity, &GlobalTransform, &VisibleEntities, Option<&C>), With<Camera3d>>,
    >,
    mut view_light_probe_info: Local<Vec<LightProbeInfo<C>>>,
    mut commands: Commands,
) where
    C: LightProbeComponent,
{
    // Build up the light probes uniform and the key table.
    for (view_entity, view_transform, visible_entities, view_component) in view_query.iter() {
        view_light_probe_info.clear();
        let visible_light_probes = visible_entities.get(TypeId::of::<ClusterVisibilityClass>());
        for &main_entity in visible_light_probes {
            let Ok(query_row) = light_probe_query.get(main_entity) else {
                // This might not be a light probe. If so, ignore it.
                continue;
            };
            // If we don't successfully create `LightProbeInfo`, that means
            // the light probe hasn't loaded yet. We don't add such light
            // probes to `view_light_probe_info` so that they don't waste
            // space in the GPU light probe buffer, which has a limited
            // size.
            if let Some(light_probe_info) = LightProbeInfo::new(query_row, &image_assets) {
                view_light_probe_info.push(light_probe_info);
            }
        }

        // Sort by distance to camera.
        view_light_probe_info.sort_by_cached_key(|light_probe_info| {
            light_probe_info.camera_distance_sort_key(view_transform)
        });

        // Create the light probes list.
        let mut render_view_light_probes =
            C::create_render_view_light_probes(view_component, &image_assets);

        // Gather up the light probes in the list.
        render_view_light_probes.maybe_gather_light_probes(&view_light_probe_info);

        // Record the per-view light probes.
        if render_view_light_probes.is_empty() {
            commands
                .get_entity(view_entity)
                .expect("View entity wasn't synced.")
                .remove::<RenderViewLightProbes<C>>();
        } else {
            commands
                .get_entity(view_entity)
                .expect("View entity wasn't synced.")
                .insert(render_view_light_probes);
        }
    }
}

// A system that runs after [`gather_light_probes`] and populates the GPU
// uniforms with the results.
//
// Note that, unlike [`gather_light_probes`], this system is not generic over
// the type of light probe. It collects light probes of all types together into
// a single structure, ready to be passed to the shader.
fn upload_light_probes(
    mut commands: Commands,
    views: Query<Entity, With<ExtractedView>>,
    mut light_probes_buffer: ResMut<LightProbesBuffer>,
    mut view_light_probes_query: Query<(
        Option<&RenderViewLightProbes<EnvironmentMapLight>>,
        Option<&RenderViewLightProbes<IrradianceVolume>>,
    )>,
    render_device: Res<RenderDevice>,
    render_queue: Res<RenderQueue>,
) {
    // If there are no views, bail.
    if views.is_empty() {
        return;
    }

    // Initialize the uniform buffer writer.
    let Some(mut writer) =
        light_probes_buffer.get_writer(views.iter().len(), &render_device, &render_queue)
    else {
        return;
    };

    // Process each view.
    for view_entity in views.iter() {
        let Ok((render_view_environment_maps, render_view_irradiance_volumes)) =
            view_light_probes_query.get_mut(view_entity)
        else {
            error!("Failed to find `RenderViewLightProbes` for the view!");
            continue;
        };

        // Initialize the uniform with only the view environment map, if there
        // is one.
        let maybe_view_light_probe_info =
            render_view_environment_maps.and_then(|maps| maps.view_light_probe_info.as_ref());
        let mut light_probes_uniform = LightProbesUniform {
            reflection_probes: [RenderLightProbe::default(); MAX_VIEW_LIGHT_PROBES],
            irradiance_volumes: [RenderLightProbe::default(); MAX_VIEW_LIGHT_PROBES],
            reflection_probe_count: render_view_environment_maps
                .map(RenderViewLightProbes::len)
                .unwrap_or_default()
                .min(MAX_VIEW_LIGHT_PROBES) as i32,
            irradiance_volume_count: render_view_irradiance_volumes
                .map(RenderViewLightProbes::len)
                .unwrap_or_default()
                .min(MAX_VIEW_LIGHT_PROBES) as i32,
            view_cubemap_index: match maybe_view_light_probe_info {
                Some(view_light_probe_info) => view_light_probe_info.cubemap_index,
                None => -1,
            },
            smallest_specular_mip_level_for_view: match maybe_view_light_probe_info {
                Some(view_light_probe_info) => view_light_probe_info.smallest_specular_mip_level,
                None => 0,
            },
            intensity_for_view: match maybe_view_light_probe_info {
                Some(view_light_probe_info) => view_light_probe_info.intensity,
                None => 1.0,
            },
            view_environment_map_affects_lightmapped_mesh_diffuse: match maybe_view_light_probe_info
            {
                Some(view_light_probe_info) => {
                    view_light_probe_info.affects_lightmapped_mesh_diffuse as u32
                }
                None => 1,
            },
            view_rotation: match maybe_view_light_probe_info {
                Some(view_light_probe_info) => view_light_probe_info.rotation.inverse().into(),
                None => Quat::IDENTITY.into(),
            },
        };

        // Add any environment maps that [`gather_light_probes`] found to the
        // uniform.
        if let Some(render_view_environment_maps) = render_view_environment_maps {
            render_view_environment_maps.add_to_uniform(
                &mut light_probes_uniform.reflection_probes,
                &mut light_probes_uniform.reflection_probe_count,
            );
        }

        // Add any irradiance volumes that [`gather_light_probes`] found to the
        // uniform.
        if let Some(render_view_irradiance_volumes) = render_view_irradiance_volumes {
            render_view_irradiance_volumes.add_to_uniform(
                &mut light_probes_uniform.irradiance_volumes,
                &mut light_probes_uniform.irradiance_volume_count,
            );
        }

        // Queue the view's uniforms to be written to the GPU.
        let uniform_offset = writer.write(&light_probes_uniform);

        commands
            .entity(view_entity)
            .insert(ViewLightProbesUniformOffset(uniform_offset));
    }
}

impl Default for LightProbesUniform {
    fn default() -> Self {
        Self {
            reflection_probes: [RenderLightProbe::default(); MAX_VIEW_LIGHT_PROBES],
            irradiance_volumes: [RenderLightProbe::default(); MAX_VIEW_LIGHT_PROBES],
            reflection_probe_count: 0,
            irradiance_volume_count: 0,
            view_cubemap_index: -1,
            smallest_specular_mip_level_for_view: 0,
            intensity_for_view: 1.0,
            view_environment_map_affects_lightmapped_mesh_diffuse: 1,
            view_rotation: Quat::IDENTITY.into(),
        }
    }
}

impl<C> LightProbeInfo<C>
where
    C: LightProbeComponent,
{
    /// Given the set of light probe components, constructs and returns
    /// [`LightProbeInfo`]. This is done for every light probe in the scene
    /// every frame.
    fn new(
        (main_entity, light_probe_transform, light_probe, environment_map, query_components): (
            Entity,
            &GlobalTransform,
            &LightProbe,
            &C,
            <C::QueryData as QueryData>::Item<'_, '_>,
        ),
        image_assets: &RenderAssets<GpuImage>,
    ) -> Option<LightProbeInfo<C>> {
        let world_from_light =
            environment_map.get_world_from_light_matrix(&light_probe_transform.affine());
        let light_from_world_transposed = Mat4::from(world_from_light.inverse()).transpose();
        let bounding_sphere_radius = (world_from_light.matrix3 * Vec3::ONE).length();
        environment_map.id(image_assets).map(|id| LightProbeInfo {
            main_entity: main_entity.into(),
            world_from_light,
            light_from_world: [
                light_from_world_transposed.x_axis,
                light_from_world_transposed.y_axis,
                light_from_world_transposed.z_axis,
            ],
            bounding_sphere_radius,
            falloff: light_probe.falloff,
            parallax_correction_bounds: environment_map
                .parallax_correction_bounds(&query_components),
            asset_id: id,
            intensity: environment_map.intensity(),
            flags: environment_map.flags(&query_components),
        })
    }

    /// Returns the squared distance from this light probe to the camera,
    /// suitable for distance sorting.
    fn camera_distance_sort_key(&self, view_transform: &GlobalTransform) -> FloatOrd {
        FloatOrd(
            (self.world_from_light.translation - view_transform.translation_vec3a())
                .length_squared(),
        )
    }
}

impl<C> RenderViewLightProbes<C>
where
    C: LightProbeComponent,
{
    /// Creates a new empty list of light probes.
    fn new() -> RenderViewLightProbes<C> {
        RenderViewLightProbes {
            binding_index_to_textures: vec![],
            cubemap_to_binding_index: HashMap::default(),
            main_entity_to_render_light_probe_index: HashMap::default(),
            render_light_probes: vec![],
            view_light_probe_info: None,
        }
    }

    /// Returns true if there are no light probes in the list.
    pub(crate) fn is_empty(&self) -> bool {
        self.render_light_probes.is_empty() && self.view_light_probe_info.is_none()
    }

    /// Returns the number of light probes in the list.
    pub(crate) fn len(&self) -> usize {
        self.render_light_probes.len()
    }

    /// Adds a cubemap to the list of bindings, if it wasn't there already, and
    /// returns its index within that list.
    pub(crate) fn get_or_insert_cubemap(&mut self, cubemap_id: &C::AssetId) -> u32 {
        *self
            .cubemap_to_binding_index
            .entry((*cubemap_id).clone())
            .or_insert_with(|| {
                let index = self.binding_index_to_textures.len() as u32;
                self.binding_index_to_textures.push((*cubemap_id).clone());
                index
            })
    }

    /// Adds all the light probes in this structure to the supplied array, which
    /// is expected to be shipped to the GPU.
    fn add_to_uniform(
        &self,
        render_light_probes: &mut [RenderLightProbe; MAX_VIEW_LIGHT_PROBES],
        render_light_probe_count: &mut i32,
    ) {
        render_light_probes[0..self.render_light_probes.len()]
            .copy_from_slice(&self.render_light_probes[..]);
        *render_light_probe_count = self.render_light_probes.len() as i32;
    }

    /// Gathers up all light probes of the given type in the scene and records
    /// them in this structure.
    fn maybe_gather_light_probes(&mut self, light_probes: &[LightProbeInfo<C>]) {
        for light_probe in light_probes.iter().take(MAX_VIEW_LIGHT_PROBES) {
            // Determine the index of the cubemap in the binding array.
            let cubemap_index = self.get_or_insert_cubemap(&light_probe.asset_id);

            // Assign an ID, and write in the index.
            let render_light_probe_index = self.render_light_probes.len() as u32;
            debug_assert!((render_light_probe_index as usize) < MAX_VIEW_LIGHT_PROBES);
            self.main_entity_to_render_light_probe_index
                .insert(light_probe.main_entity, render_light_probe_index);

            // Write in the light probe data.
            self.render_light_probes.push(RenderLightProbe {
                light_from_world_transposed: light_probe.light_from_world,
                falloff: light_probe.falloff,
                parallax_correction_bounds: light_probe.parallax_correction_bounds,
                world_position: light_probe.world_from_light.translation.into(),
                bounding_sphere_radius: light_probe.bounding_sphere_radius,
                texture_index: cubemap_index as i32,
                intensity: light_probe.intensity,
                flags: light_probe.flags.bits() as u32,
            });
        }
    }
}

impl<C> Clone for LightProbeInfo<C>
where
    C: LightProbeComponent,
{
    fn clone(&self) -> Self {
        Self {
            main_entity: self.main_entity,
            light_from_world: self.light_from_world,
            world_from_light: self.world_from_light,
            falloff: self.falloff,
            parallax_correction_bounds: self.parallax_correction_bounds,
            bounding_sphere_radius: self.bounding_sphere_radius,
            intensity: self.intensity,
            flags: self.flags,
            asset_id: self.asset_id.clone(),
        }
    }
}

/// Adds a diffuse or specular texture view to the `texture_views` list, and
/// populates `sampler` if this is the first such view.
pub(crate) fn add_cubemap_texture_view<'a>(
    texture_views: &mut Vec<&'a <TextureView as Deref>::Target>,
    sampler: &mut Option<&'a Sampler>,
    image_id: AssetId<Image>,
    images: &'a RenderAssets<GpuImage>,
    fallback_image: &'a FallbackImage,
) {
    match images.get(image_id) {
        None => {
            // Use the fallback image if the cubemap isn't loaded yet.
            texture_views.push(&*fallback_image.cube.texture_view);
        }
        Some(image) => {
            // If this is the first texture view, populate `sampler`.
            if sampler.is_none() {
                *sampler = Some(&image.sampler);
            }

            texture_views.push(&*image.texture_view);
        }
    }
}

/// Many things can go wrong when attempting to use texture binding arrays
/// (a.k.a. bindless textures). This function checks for these pitfalls:
///
/// 1. If GLSL support is enabled at the feature level, then in debug mode
///    `naga_oil` will attempt to compile all shader modules under GLSL to check
///    validity of names, even if GLSL isn't actually used. This will cause a crash
///    if binding arrays are enabled, because binding arrays are currently
///    unimplemented in the GLSL backend of Naga. Therefore, we disable binding
///    arrays if the `shader_format_glsl` feature is present.
///
/// 2. If there aren't enough texture bindings available to accommodate all the
///    binding arrays, the driver will panic. So we also bail out if there aren't
///    enough texture bindings available in the fragment shader.
///
/// 3. If binding arrays aren't supported on the hardware, then we obviously
///    can't use them. Adreno <= 610 claims to support bindless, but seems to be
///    too buggy to be usable.
///
/// 4. If binding arrays are supported on the hardware, but they can only be
///    accessed by uniform indices, that's not good enough, and we bail out.
///
/// If binding arrays aren't usable, we disable reflection probes and limit the
/// number of irradiance volumes in the scene to 1.
pub(crate) fn binding_arrays_are_usable(
    render_device: &RenderDevice,
    render_adapter: &RenderAdapter,
) -> bool {
    let adapter_info = RenderAdapterInfo(WgpuWrapper::new(render_adapter.get_info()));

    !cfg!(feature = "shader_format_glsl")
        && bevy_render::get_adreno_model(&adapter_info).is_none_or(|model| model > 610)
        && render_device.limits().max_storage_textures_per_shader_stage
            >= (STANDARD_MATERIAL_FRAGMENT_SHADER_MIN_TEXTURE_BINDINGS + MAX_VIEW_LIGHT_PROBES)
                as u32
        && render_device.features().contains(
            WgpuFeatures::TEXTURE_BINDING_ARRAY
                | WgpuFeatures::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING,
        )
}