Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_pbr/src/light_probe/mod.rs
6604 views
1
//! Light probes for baked global illumination.
2
3
use bevy_app::{App, Plugin};
4
use bevy_asset::AssetId;
5
use bevy_camera::{
6
primitives::{Aabb, Frustum},
7
Camera3d,
8
};
9
use bevy_derive::{Deref, DerefMut};
10
use bevy_ecs::{
11
component::Component,
12
entity::Entity,
13
query::With,
14
resource::Resource,
15
schedule::IntoScheduleConfigs,
16
system::{Commands, Local, Query, Res, ResMut},
17
};
18
use bevy_image::Image;
19
use bevy_light::{EnvironmentMapLight, IrradianceVolume, LightProbe};
20
use bevy_math::{Affine3A, FloatOrd, Mat4, Vec3A, Vec4};
21
use bevy_platform::collections::HashMap;
22
use bevy_render::{
23
extract_instances::ExtractInstancesPlugin,
24
render_asset::RenderAssets,
25
render_resource::{DynamicUniformBuffer, Sampler, ShaderType, TextureView},
26
renderer::{RenderAdapter, RenderAdapterInfo, RenderDevice, RenderQueue, WgpuWrapper},
27
settings::WgpuFeatures,
28
sync_world::RenderEntity,
29
texture::{FallbackImage, GpuImage},
30
view::ExtractedView,
31
Extract, ExtractSchedule, Render, RenderApp, RenderSystems,
32
};
33
use bevy_shader::load_shader_library;
34
use bevy_transform::{components::Transform, prelude::GlobalTransform};
35
use tracing::error;
36
37
use core::{hash::Hash, ops::Deref};
38
39
use crate::{
40
generate::EnvironmentMapGenerationPlugin, light_probe::environment_map::EnvironmentMapIds,
41
};
42
43
pub mod environment_map;
44
pub mod generate;
45
pub mod irradiance_volume;
46
47
/// The maximum number of each type of light probe that each view will consider.
48
///
49
/// Because the fragment shader does a linear search through the list for each
50
/// fragment, this number needs to be relatively small.
51
pub const MAX_VIEW_LIGHT_PROBES: usize = 8;
52
53
/// How many texture bindings are used in the fragment shader, *not* counting
54
/// environment maps or irradiance volumes.
55
const STANDARD_MATERIAL_FRAGMENT_SHADER_MIN_TEXTURE_BINDINGS: usize = 16;
56
57
/// Adds support for light probes: cuboid bounding regions that apply global
58
/// illumination to objects within them.
59
///
60
/// This also adds support for view environment maps: diffuse and specular
61
/// cubemaps applied to all objects that a view renders.
62
pub struct LightProbePlugin;
63
64
/// A GPU type that stores information about a light probe.
65
#[derive(Clone, Copy, ShaderType, Default)]
66
struct RenderLightProbe {
67
/// The transform from the world space to the model space. This is used to
68
/// efficiently check for bounding box intersection.
69
light_from_world_transposed: [Vec4; 3],
70
71
/// The index of the texture or textures in the appropriate binding array or
72
/// arrays.
73
///
74
/// For example, for reflection probes this is the index of the cubemap in
75
/// the diffuse and specular texture arrays.
76
texture_index: i32,
77
78
/// Scale factor applied to the light generated by this light probe.
79
///
80
/// See the comment in [`EnvironmentMapLight`] for details.
81
intensity: f32,
82
83
/// Whether this light probe adds to the diffuse contribution of the
84
/// irradiance for meshes with lightmaps.
85
affects_lightmapped_mesh_diffuse: u32,
86
}
87
88
/// A per-view shader uniform that specifies all the light probes that the view
89
/// takes into account.
90
#[derive(ShaderType)]
91
pub struct LightProbesUniform {
92
/// The list of applicable reflection probes, sorted from nearest to the
93
/// camera to the farthest away from the camera.
94
reflection_probes: [RenderLightProbe; MAX_VIEW_LIGHT_PROBES],
95
96
/// The list of applicable irradiance volumes, sorted from nearest to the
97
/// camera to the farthest away from the camera.
98
irradiance_volumes: [RenderLightProbe; MAX_VIEW_LIGHT_PROBES],
99
100
/// The number of reflection probes in the list.
101
reflection_probe_count: i32,
102
103
/// The number of irradiance volumes in the list.
104
irradiance_volume_count: i32,
105
106
/// The index of the diffuse and specular environment maps associated with
107
/// the view itself. This is used as a fallback if no reflection probe in
108
/// the list contains the fragment.
109
view_cubemap_index: i32,
110
111
/// The smallest valid mipmap level for the specular environment cubemap
112
/// associated with the view.
113
smallest_specular_mip_level_for_view: u32,
114
115
/// The intensity of the environment cubemap associated with the view.
116
///
117
/// See the comment in [`EnvironmentMapLight`] for details.
118
intensity_for_view: f32,
119
120
/// Whether the environment map attached to the view affects the diffuse
121
/// lighting for lightmapped meshes.
122
///
123
/// This will be 1 if the map does affect lightmapped meshes or 0 otherwise.
124
view_environment_map_affects_lightmapped_mesh_diffuse: u32,
125
}
126
127
/// A GPU buffer that stores information about all light probes.
128
#[derive(Resource, Default, Deref, DerefMut)]
129
pub struct LightProbesBuffer(DynamicUniformBuffer<LightProbesUniform>);
130
131
/// A component attached to each camera in the render world that stores the
132
/// index of the [`LightProbesUniform`] in the [`LightProbesBuffer`].
133
#[derive(Component, Default, Deref, DerefMut)]
134
pub struct ViewLightProbesUniformOffset(u32);
135
136
/// Information that [`gather_light_probes`] keeps about each light probe.
137
///
138
/// This information is parameterized by the [`LightProbeComponent`] type. This
139
/// will either be [`EnvironmentMapLight`] for reflection probes or
140
/// [`IrradianceVolume`] for irradiance volumes.
141
struct LightProbeInfo<C>
142
where
143
C: LightProbeComponent,
144
{
145
// The transform from world space to light probe space.
146
light_from_world: Affine3A,
147
148
// The transform from light probe space to world space.
149
world_from_light: Affine3A,
150
151
// Scale factor applied to the diffuse and specular light generated by this
152
// reflection probe.
153
//
154
// See the comment in [`EnvironmentMapLight`] for details.
155
intensity: f32,
156
157
// Whether this light probe adds to the diffuse contribution of the
158
// irradiance for meshes with lightmaps.
159
affects_lightmapped_mesh_diffuse: bool,
160
161
// The IDs of all assets associated with this light probe.
162
//
163
// Because each type of light probe component may reference different types
164
// of assets (e.g. a reflection probe references two cubemap assets while an
165
// irradiance volume references a single 3D texture asset), this is generic.
166
asset_id: C::AssetId,
167
}
168
169
/// A component, part of the render world, that stores the mapping from asset ID
170
/// or IDs to the texture index in the appropriate binding arrays.
171
///
172
/// Cubemap textures belonging to environment maps are collected into binding
173
/// arrays, and the index of each texture is presented to the shader for runtime
174
/// lookup. 3D textures belonging to reflection probes are likewise collected
175
/// into binding arrays, and the shader accesses the 3D texture by index.
176
///
177
/// This component is attached to each view in the render world, because each
178
/// view may have a different set of light probes that it considers and therefore
179
/// the texture indices are per-view.
180
#[derive(Component, Default)]
181
pub struct RenderViewLightProbes<C>
182
where
183
C: LightProbeComponent,
184
{
185
/// The list of environment maps presented to the shader, in order.
186
binding_index_to_textures: Vec<C::AssetId>,
187
188
/// The reverse of `binding_index_to_cubemap`: a map from the texture ID to
189
/// the index in `binding_index_to_cubemap`.
190
cubemap_to_binding_index: HashMap<C::AssetId, u32>,
191
192
/// Information about each light probe, ready for upload to the GPU, sorted
193
/// in order from closest to the camera to farthest.
194
///
195
/// Note that this is not necessarily ordered by binding index. So don't
196
/// write code like
197
/// `render_light_probes[cubemap_to_binding_index[asset_id]]`; instead
198
/// search for the light probe with the appropriate binding index in this
199
/// array.
200
render_light_probes: Vec<RenderLightProbe>,
201
202
/// Information needed to render the light probe attached directly to the
203
/// view, if applicable.
204
///
205
/// A light probe attached directly to a view represents a "global" light
206
/// probe that affects all objects not in the bounding region of any light
207
/// probe. Currently, the only light probe type that supports this is the
208
/// [`EnvironmentMapLight`].
209
view_light_probe_info: C::ViewLightProbeInfo,
210
}
211
212
/// A trait implemented by all components that represent light probes.
213
///
214
/// Currently, the two light probe types are [`EnvironmentMapLight`] and
215
/// [`IrradianceVolume`], for reflection probes and irradiance volumes
216
/// respectively.
217
///
218
/// Most light probe systems are written to be generic over the type of light
219
/// probe. This allows much of the code to be shared and enables easy addition
220
/// of more light probe types (e.g. real-time reflection planes) in the future.
221
pub trait LightProbeComponent: Send + Sync + Component + Sized {
222
/// Holds [`AssetId`]s of the texture or textures that this light probe
223
/// references.
224
///
225
/// This can just be [`AssetId`] if the light probe only references one
226
/// texture. If it references multiple textures, it will be a structure
227
/// containing those asset IDs.
228
type AssetId: Send + Sync + Clone + Eq + Hash;
229
230
/// If the light probe can be attached to the view itself (as opposed to a
231
/// cuboid region within the scene), this contains the information that will
232
/// be passed to the GPU in order to render it. Otherwise, this will be
233
/// `()`.
234
///
235
/// Currently, only reflection probes (i.e. [`EnvironmentMapLight`]) can be
236
/// attached directly to views.
237
type ViewLightProbeInfo: Send + Sync + Default;
238
239
/// Returns the asset ID or asset IDs of the texture or textures referenced
240
/// by this light probe.
241
fn id(&self, image_assets: &RenderAssets<GpuImage>) -> Option<Self::AssetId>;
242
243
/// Returns the intensity of this light probe.
244
///
245
/// This is a scaling factor that will be multiplied by the value or values
246
/// sampled from the texture.
247
fn intensity(&self) -> f32;
248
249
/// Returns true if this light probe contributes diffuse lighting to meshes
250
/// with lightmaps or false otherwise.
251
fn affects_lightmapped_mesh_diffuse(&self) -> bool;
252
253
/// Creates an instance of [`RenderViewLightProbes`] containing all the
254
/// information needed to render this light probe.
255
///
256
/// This is called for every light probe in view every frame.
257
fn create_render_view_light_probes(
258
view_component: Option<&Self>,
259
image_assets: &RenderAssets<GpuImage>,
260
) -> RenderViewLightProbes<Self>;
261
}
262
263
/// The uniform struct extracted from [`EnvironmentMapLight`].
264
/// Will be available for use in the Environment Map shader.
265
#[derive(Component, ShaderType, Clone)]
266
pub struct EnvironmentMapUniform {
267
/// The world space transformation matrix of the sample ray for environment cubemaps.
268
transform: Mat4,
269
}
270
271
impl Default for EnvironmentMapUniform {
272
fn default() -> Self {
273
EnvironmentMapUniform {
274
transform: Mat4::IDENTITY,
275
}
276
}
277
}
278
279
/// A GPU buffer that stores the environment map settings for each view.
280
#[derive(Resource, Default, Deref, DerefMut)]
281
pub struct EnvironmentMapUniformBuffer(pub DynamicUniformBuffer<EnvironmentMapUniform>);
282
283
/// A component that stores the offset within the
284
/// [`EnvironmentMapUniformBuffer`] for each view.
285
#[derive(Component, Default, Deref, DerefMut)]
286
pub struct ViewEnvironmentMapUniformOffset(u32);
287
288
impl Plugin for LightProbePlugin {
289
fn build(&self, app: &mut App) {
290
load_shader_library!(app, "light_probe.wgsl");
291
load_shader_library!(app, "environment_map.wgsl");
292
load_shader_library!(app, "irradiance_volume.wgsl");
293
294
app.add_plugins((
295
EnvironmentMapGenerationPlugin,
296
ExtractInstancesPlugin::<EnvironmentMapIds>::new(),
297
));
298
299
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
300
return;
301
};
302
303
render_app
304
.init_resource::<LightProbesBuffer>()
305
.init_resource::<EnvironmentMapUniformBuffer>()
306
.add_systems(ExtractSchedule, gather_environment_map_uniform)
307
.add_systems(ExtractSchedule, gather_light_probes::<EnvironmentMapLight>)
308
.add_systems(ExtractSchedule, gather_light_probes::<IrradianceVolume>)
309
.add_systems(
310
Render,
311
(upload_light_probes, prepare_environment_uniform_buffer)
312
.in_set(RenderSystems::PrepareResources),
313
);
314
}
315
}
316
317
/// Extracts [`EnvironmentMapLight`] from views and creates [`EnvironmentMapUniform`] for them.
318
///
319
/// Compared to the `ExtractComponentPlugin`, this implementation will create a default instance
320
/// if one does not already exist.
321
fn gather_environment_map_uniform(
322
view_query: Extract<Query<(RenderEntity, Option<&EnvironmentMapLight>), With<Camera3d>>>,
323
mut commands: Commands,
324
) {
325
for (view_entity, environment_map_light) in view_query.iter() {
326
let environment_map_uniform = if let Some(environment_map_light) = environment_map_light {
327
EnvironmentMapUniform {
328
transform: Transform::from_rotation(environment_map_light.rotation)
329
.to_matrix()
330
.inverse(),
331
}
332
} else {
333
EnvironmentMapUniform::default()
334
};
335
commands
336
.get_entity(view_entity)
337
.expect("Environment map light entity wasn't synced.")
338
.insert(environment_map_uniform);
339
}
340
}
341
342
/// Gathers up all light probes of a single type in the scene and assigns them
343
/// to views, performing frustum culling and distance sorting in the process.
344
fn gather_light_probes<C>(
345
image_assets: Res<RenderAssets<GpuImage>>,
346
light_probe_query: Extract<Query<(&GlobalTransform, &C), With<LightProbe>>>,
347
view_query: Extract<
348
Query<(RenderEntity, &GlobalTransform, &Frustum, Option<&C>), With<Camera3d>>,
349
>,
350
mut reflection_probes: Local<Vec<LightProbeInfo<C>>>,
351
mut view_reflection_probes: Local<Vec<LightProbeInfo<C>>>,
352
mut commands: Commands,
353
) where
354
C: LightProbeComponent,
355
{
356
// Create [`LightProbeInfo`] for every light probe in the scene.
357
reflection_probes.clear();
358
reflection_probes.extend(
359
light_probe_query
360
.iter()
361
.filter_map(|query_row| LightProbeInfo::new(query_row, &image_assets)),
362
);
363
364
// Build up the light probes uniform and the key table.
365
for (view_entity, view_transform, view_frustum, view_component) in view_query.iter() {
366
// Cull light probes outside the view frustum.
367
view_reflection_probes.clear();
368
view_reflection_probes.extend(
369
reflection_probes
370
.iter()
371
.filter(|light_probe_info| light_probe_info.frustum_cull(view_frustum))
372
.cloned(),
373
);
374
375
// Sort by distance to camera.
376
view_reflection_probes.sort_by_cached_key(|light_probe_info| {
377
light_probe_info.camera_distance_sort_key(view_transform)
378
});
379
380
// Create the light probes list.
381
let mut render_view_light_probes =
382
C::create_render_view_light_probes(view_component, &image_assets);
383
384
// Gather up the light probes in the list.
385
render_view_light_probes.maybe_gather_light_probes(&view_reflection_probes);
386
387
// Record the per-view light probes.
388
if render_view_light_probes.is_empty() {
389
commands
390
.get_entity(view_entity)
391
.expect("View entity wasn't synced.")
392
.remove::<RenderViewLightProbes<C>>();
393
} else {
394
commands
395
.get_entity(view_entity)
396
.expect("View entity wasn't synced.")
397
.insert(render_view_light_probes);
398
}
399
}
400
}
401
402
/// Gathers up environment map settings for each applicable view and
403
/// writes them into a GPU buffer.
404
pub fn prepare_environment_uniform_buffer(
405
mut commands: Commands,
406
views: Query<(Entity, Option<&EnvironmentMapUniform>), With<ExtractedView>>,
407
mut environment_uniform_buffer: ResMut<EnvironmentMapUniformBuffer>,
408
render_device: Res<RenderDevice>,
409
render_queue: Res<RenderQueue>,
410
) {
411
let Some(mut writer) =
412
environment_uniform_buffer.get_writer(views.iter().len(), &render_device, &render_queue)
413
else {
414
return;
415
};
416
417
for (view, environment_uniform) in views.iter() {
418
let uniform_offset = match environment_uniform {
419
None => 0,
420
Some(environment_uniform) => writer.write(environment_uniform),
421
};
422
commands
423
.entity(view)
424
.insert(ViewEnvironmentMapUniformOffset(uniform_offset));
425
}
426
}
427
428
// A system that runs after [`gather_light_probes`] and populates the GPU
429
// uniforms with the results.
430
//
431
// Note that, unlike [`gather_light_probes`], this system is not generic over
432
// the type of light probe. It collects light probes of all types together into
433
// a single structure, ready to be passed to the shader.
434
fn upload_light_probes(
435
mut commands: Commands,
436
views: Query<Entity, With<ExtractedView>>,
437
mut light_probes_buffer: ResMut<LightProbesBuffer>,
438
mut view_light_probes_query: Query<(
439
Option<&RenderViewLightProbes<EnvironmentMapLight>>,
440
Option<&RenderViewLightProbes<IrradianceVolume>>,
441
)>,
442
render_device: Res<RenderDevice>,
443
render_queue: Res<RenderQueue>,
444
) {
445
// If there are no views, bail.
446
if views.is_empty() {
447
return;
448
}
449
450
// Initialize the uniform buffer writer.
451
let mut writer = light_probes_buffer
452
.get_writer(views.iter().len(), &render_device, &render_queue)
453
.unwrap();
454
455
// Process each view.
456
for view_entity in views.iter() {
457
let Ok((render_view_environment_maps, render_view_irradiance_volumes)) =
458
view_light_probes_query.get_mut(view_entity)
459
else {
460
error!("Failed to find `RenderViewLightProbes` for the view!");
461
continue;
462
};
463
464
// Initialize the uniform with only the view environment map, if there
465
// is one.
466
let mut light_probes_uniform = LightProbesUniform {
467
reflection_probes: [RenderLightProbe::default(); MAX_VIEW_LIGHT_PROBES],
468
irradiance_volumes: [RenderLightProbe::default(); MAX_VIEW_LIGHT_PROBES],
469
reflection_probe_count: render_view_environment_maps
470
.map(RenderViewLightProbes::len)
471
.unwrap_or_default()
472
.min(MAX_VIEW_LIGHT_PROBES) as i32,
473
irradiance_volume_count: render_view_irradiance_volumes
474
.map(RenderViewLightProbes::len)
475
.unwrap_or_default()
476
.min(MAX_VIEW_LIGHT_PROBES) as i32,
477
view_cubemap_index: render_view_environment_maps
478
.map(|maps| maps.view_light_probe_info.cubemap_index)
479
.unwrap_or(-1),
480
smallest_specular_mip_level_for_view: render_view_environment_maps
481
.map(|maps| maps.view_light_probe_info.smallest_specular_mip_level)
482
.unwrap_or(0),
483
intensity_for_view: render_view_environment_maps
484
.map(|maps| maps.view_light_probe_info.intensity)
485
.unwrap_or(1.0),
486
view_environment_map_affects_lightmapped_mesh_diffuse: render_view_environment_maps
487
.map(|maps| maps.view_light_probe_info.affects_lightmapped_mesh_diffuse as u32)
488
.unwrap_or(1),
489
};
490
491
// Add any environment maps that [`gather_light_probes`] found to the
492
// uniform.
493
if let Some(render_view_environment_maps) = render_view_environment_maps {
494
render_view_environment_maps.add_to_uniform(
495
&mut light_probes_uniform.reflection_probes,
496
&mut light_probes_uniform.reflection_probe_count,
497
);
498
}
499
500
// Add any irradiance volumes that [`gather_light_probes`] found to the
501
// uniform.
502
if let Some(render_view_irradiance_volumes) = render_view_irradiance_volumes {
503
render_view_irradiance_volumes.add_to_uniform(
504
&mut light_probes_uniform.irradiance_volumes,
505
&mut light_probes_uniform.irradiance_volume_count,
506
);
507
}
508
509
// Queue the view's uniforms to be written to the GPU.
510
let uniform_offset = writer.write(&light_probes_uniform);
511
512
commands
513
.entity(view_entity)
514
.insert(ViewLightProbesUniformOffset(uniform_offset));
515
}
516
}
517
518
impl Default for LightProbesUniform {
519
fn default() -> Self {
520
Self {
521
reflection_probes: [RenderLightProbe::default(); MAX_VIEW_LIGHT_PROBES],
522
irradiance_volumes: [RenderLightProbe::default(); MAX_VIEW_LIGHT_PROBES],
523
reflection_probe_count: 0,
524
irradiance_volume_count: 0,
525
view_cubemap_index: -1,
526
smallest_specular_mip_level_for_view: 0,
527
intensity_for_view: 1.0,
528
view_environment_map_affects_lightmapped_mesh_diffuse: 1,
529
}
530
}
531
}
532
533
impl<C> LightProbeInfo<C>
534
where
535
C: LightProbeComponent,
536
{
537
/// Given the set of light probe components, constructs and returns
538
/// [`LightProbeInfo`]. This is done for every light probe in the scene
539
/// every frame.
540
fn new(
541
(light_probe_transform, environment_map): (&GlobalTransform, &C),
542
image_assets: &RenderAssets<GpuImage>,
543
) -> Option<LightProbeInfo<C>> {
544
environment_map.id(image_assets).map(|id| LightProbeInfo {
545
world_from_light: light_probe_transform.affine(),
546
light_from_world: light_probe_transform.affine().inverse(),
547
asset_id: id,
548
intensity: environment_map.intensity(),
549
affects_lightmapped_mesh_diffuse: environment_map.affects_lightmapped_mesh_diffuse(),
550
})
551
}
552
553
/// Returns true if this light probe is in the viewing frustum of the camera
554
/// or false if it isn't.
555
fn frustum_cull(&self, view_frustum: &Frustum) -> bool {
556
view_frustum.intersects_obb(
557
&Aabb {
558
center: Vec3A::default(),
559
half_extents: Vec3A::splat(0.5),
560
},
561
&self.world_from_light,
562
true,
563
false,
564
)
565
}
566
567
/// Returns the squared distance from this light probe to the camera,
568
/// suitable for distance sorting.
569
fn camera_distance_sort_key(&self, view_transform: &GlobalTransform) -> FloatOrd {
570
FloatOrd(
571
(self.world_from_light.translation - view_transform.translation_vec3a())
572
.length_squared(),
573
)
574
}
575
}
576
577
impl<C> RenderViewLightProbes<C>
578
where
579
C: LightProbeComponent,
580
{
581
/// Creates a new empty list of light probes.
582
fn new() -> RenderViewLightProbes<C> {
583
RenderViewLightProbes {
584
binding_index_to_textures: vec![],
585
cubemap_to_binding_index: HashMap::default(),
586
render_light_probes: vec![],
587
view_light_probe_info: C::ViewLightProbeInfo::default(),
588
}
589
}
590
591
/// Returns true if there are no light probes in the list.
592
pub(crate) fn is_empty(&self) -> bool {
593
self.binding_index_to_textures.is_empty()
594
}
595
596
/// Returns the number of light probes in the list.
597
pub(crate) fn len(&self) -> usize {
598
self.binding_index_to_textures.len()
599
}
600
601
/// Adds a cubemap to the list of bindings, if it wasn't there already, and
602
/// returns its index within that list.
603
pub(crate) fn get_or_insert_cubemap(&mut self, cubemap_id: &C::AssetId) -> u32 {
604
*self
605
.cubemap_to_binding_index
606
.entry((*cubemap_id).clone())
607
.or_insert_with(|| {
608
let index = self.binding_index_to_textures.len() as u32;
609
self.binding_index_to_textures.push((*cubemap_id).clone());
610
index
611
})
612
}
613
614
/// Adds all the light probes in this structure to the supplied array, which
615
/// is expected to be shipped to the GPU.
616
fn add_to_uniform(
617
&self,
618
render_light_probes: &mut [RenderLightProbe; MAX_VIEW_LIGHT_PROBES],
619
render_light_probe_count: &mut i32,
620
) {
621
render_light_probes[0..self.render_light_probes.len()]
622
.copy_from_slice(&self.render_light_probes[..]);
623
*render_light_probe_count = self.render_light_probes.len() as i32;
624
}
625
626
/// Gathers up all light probes of the given type in the scene and records
627
/// them in this structure.
628
fn maybe_gather_light_probes(&mut self, light_probes: &[LightProbeInfo<C>]) {
629
for light_probe in light_probes.iter().take(MAX_VIEW_LIGHT_PROBES) {
630
// Determine the index of the cubemap in the binding array.
631
let cubemap_index = self.get_or_insert_cubemap(&light_probe.asset_id);
632
633
// Transpose the inverse transform to compress the structure on the
634
// GPU (from 4 `Vec4`s to 3 `Vec4`s). The shader will transpose it
635
// to recover the original inverse transform.
636
let light_from_world_transposed = Mat4::from(light_probe.light_from_world).transpose();
637
638
// Write in the light probe data.
639
self.render_light_probes.push(RenderLightProbe {
640
light_from_world_transposed: [
641
light_from_world_transposed.x_axis,
642
light_from_world_transposed.y_axis,
643
light_from_world_transposed.z_axis,
644
],
645
texture_index: cubemap_index as i32,
646
intensity: light_probe.intensity,
647
affects_lightmapped_mesh_diffuse: light_probe.affects_lightmapped_mesh_diffuse
648
as u32,
649
});
650
}
651
}
652
}
653
654
impl<C> Clone for LightProbeInfo<C>
655
where
656
C: LightProbeComponent,
657
{
658
fn clone(&self) -> Self {
659
Self {
660
light_from_world: self.light_from_world,
661
world_from_light: self.world_from_light,
662
intensity: self.intensity,
663
affects_lightmapped_mesh_diffuse: self.affects_lightmapped_mesh_diffuse,
664
asset_id: self.asset_id.clone(),
665
}
666
}
667
}
668
669
/// Adds a diffuse or specular texture view to the `texture_views` list, and
670
/// populates `sampler` if this is the first such view.
671
pub(crate) fn add_cubemap_texture_view<'a>(
672
texture_views: &mut Vec<&'a <TextureView as Deref>::Target>,
673
sampler: &mut Option<&'a Sampler>,
674
image_id: AssetId<Image>,
675
images: &'a RenderAssets<GpuImage>,
676
fallback_image: &'a FallbackImage,
677
) {
678
match images.get(image_id) {
679
None => {
680
// Use the fallback image if the cubemap isn't loaded yet.
681
texture_views.push(&*fallback_image.cube.texture_view);
682
}
683
Some(image) => {
684
// If this is the first texture view, populate `sampler`.
685
if sampler.is_none() {
686
*sampler = Some(&image.sampler);
687
}
688
689
texture_views.push(&*image.texture_view);
690
}
691
}
692
}
693
694
/// Many things can go wrong when attempting to use texture binding arrays
695
/// (a.k.a. bindless textures). This function checks for these pitfalls:
696
///
697
/// 1. If GLSL support is enabled at the feature level, then in debug mode
698
/// `naga_oil` will attempt to compile all shader modules under GLSL to check
699
/// validity of names, even if GLSL isn't actually used. This will cause a crash
700
/// if binding arrays are enabled, because binding arrays are currently
701
/// unimplemented in the GLSL backend of Naga. Therefore, we disable binding
702
/// arrays if the `shader_format_glsl` feature is present.
703
///
704
/// 2. If there aren't enough texture bindings available to accommodate all the
705
/// binding arrays, the driver will panic. So we also bail out if there aren't
706
/// enough texture bindings available in the fragment shader.
707
///
708
/// 3. If binding arrays aren't supported on the hardware, then we obviously
709
/// can't use them. Adreno <= 610 claims to support bindless, but seems to be
710
/// too buggy to be usable.
711
///
712
/// 4. If binding arrays are supported on the hardware, but they can only be
713
/// accessed by uniform indices, that's not good enough, and we bail out.
714
///
715
/// If binding arrays aren't usable, we disable reflection probes and limit the
716
/// number of irradiance volumes in the scene to 1.
717
pub(crate) fn binding_arrays_are_usable(
718
render_device: &RenderDevice,
719
render_adapter: &RenderAdapter,
720
) -> bool {
721
let adapter_info = RenderAdapterInfo(WgpuWrapper::new(render_adapter.get_info()));
722
723
!cfg!(feature = "shader_format_glsl")
724
&& bevy_render::get_adreno_model(&adapter_info).is_none_or(|model| model > 610)
725
&& render_device.limits().max_storage_textures_per_shader_stage
726
>= (STANDARD_MATERIAL_FRAGMENT_SHADER_MIN_TEXTURE_BINDINGS + MAX_VIEW_LIGHT_PROBES)
727
as u32
728
&& render_device.features().contains(
729
WgpuFeatures::TEXTURE_BINDING_ARRAY
730
| WgpuFeatures::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING,
731
)
732
}
733
734