Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_pbr/src/decal/clustered.rs
9441 views
1
//! Clustered decals, bounding regions that project textures onto surfaces.
2
//!
3
//! A *clustered decal* is a bounding box that projects a texture onto any
4
//! surface within its bounds along the positive Z axis. In Bevy, clustered
5
//! decals use the *clustered forward* rendering technique.
6
//!
7
//! Clustered decals are the highest-quality types of decals that Bevy supports,
8
//! but they require bindless textures. This means that they presently can't be
9
//! used on WebGL 2 or WebGPU. Bevy's clustered decals can be used
10
//! with forward or deferred rendering and don't require a prepass.
11
//!
12
//! Each clustered decal may contain up to 4 textures. By default, the 4
13
//! textures correspond to the base color, a normal map, a metallic-roughness
14
//! map, and an emissive map respectively. However, with a custom shader, you
15
//! can use these 4 textures for whatever you wish. Additionally, you can use
16
//! the built-in *tag* field to store additional application-specific data; by
17
//! reading the tag in the shader, you can modify the appearance of a clustered
18
//! decal arbitrarily. See the documentation in `clustered.wgsl` for more
19
//! information and the `clustered_decals` example for an example of use.
20
21
use core::{num::NonZero, ops::Deref};
22
23
use bevy_app::{App, Plugin};
24
use bevy_asset::{AssetId, Handle};
25
use bevy_camera::visibility::ViewVisibility;
26
use bevy_derive::{Deref, DerefMut};
27
use bevy_ecs::{
28
entity::{Entity, EntityHashMap},
29
query::With,
30
resource::Resource,
31
schedule::IntoScheduleConfigs as _,
32
system::{Commands, Local, Query, Res, ResMut},
33
};
34
use bevy_image::Image;
35
use bevy_light::{ClusteredDecal, DirectionalLightTexture, PointLightTexture, SpotLightTexture};
36
use bevy_math::Mat4;
37
use bevy_platform::collections::HashMap;
38
use bevy_render::{
39
render_asset::RenderAssets,
40
render_resource::{
41
binding_types, BindGroupLayoutEntryBuilder, Buffer, BufferUsages, RawBufferVec, Sampler,
42
SamplerBindingType, ShaderType, TextureSampleType, TextureView,
43
},
44
renderer::{RenderAdapter, RenderDevice, RenderQueue},
45
settings::WgpuFeatures,
46
sync_component::{SyncComponent, SyncComponentPlugin},
47
sync_world::RenderEntity,
48
texture::{FallbackImage, GpuImage},
49
Extract, ExtractSchedule, Render, RenderApp, RenderSystems,
50
};
51
use bevy_shader::load_shader_library;
52
use bevy_transform::components::GlobalTransform;
53
use bytemuck::{Pod, Zeroable};
54
55
use crate::{binding_arrays_are_usable, prepare_lights, GlobalClusterableObjectMeta};
56
57
/// The number of textures that can be associated with each clustered decal.
58
const IMAGES_PER_DECAL: usize = 4;
59
60
/// A plugin that adds support for clustered decals.
61
///
62
/// In environments where bindless textures aren't available, clustered decals
63
/// can still be added to a scene, but they won't project any decals.
64
pub struct ClusteredDecalPlugin;
65
66
/// Stores information about all the clustered decals in the scene.
67
#[derive(Resource, Default)]
68
pub struct RenderClusteredDecals {
69
/// Maps an index in the shader binding array to the associated decal image.
70
///
71
/// The `texture_to_binding_index` field holds the inverse mapping.
72
pub binding_index_to_textures: Vec<AssetId<Image>>,
73
/// Maps a decal image to the shader binding array.
74
///
75
/// [`Self::binding_index_to_textures`] holds the inverse mapping.
76
texture_to_binding_index: HashMap<AssetId<Image>, i32>,
77
/// The information concerning each decal that we provide to the shader.
78
decals: Vec<RenderClusteredDecal>,
79
/// Maps the [`bevy_render::sync_world::RenderEntity`] of each decal to the
80
/// index of that decal in the [`Self::decals`] list.
81
entity_to_decal_index: EntityHashMap<usize>,
82
}
83
84
impl RenderClusteredDecals {
85
/// Clears out this [`RenderClusteredDecals`] in preparation for a new
86
/// frame.
87
fn clear(&mut self) {
88
self.binding_index_to_textures.clear();
89
self.texture_to_binding_index.clear();
90
self.decals.clear();
91
self.entity_to_decal_index.clear();
92
}
93
94
pub fn insert_decal(
95
&mut self,
96
entity: Entity,
97
images: [Option<AssetId<Image>>; IMAGES_PER_DECAL],
98
local_from_world: Mat4,
99
tag: u32,
100
) {
101
let image_indices = images.map(|maybe_image_id| match maybe_image_id {
102
Some(ref image_id) => self.get_or_insert_image(image_id),
103
None => -1,
104
});
105
let decal_index = self.decals.len();
106
self.decals.push(RenderClusteredDecal {
107
local_from_world,
108
image_indices,
109
tag,
110
pad_a: 0,
111
pad_b: 0,
112
pad_c: 0,
113
});
114
self.entity_to_decal_index.insert(entity, decal_index);
115
}
116
117
pub fn get(&self, entity: Entity) -> Option<usize> {
118
self.entity_to_decal_index.get(&entity).copied()
119
}
120
}
121
122
/// The per-view bind group entries pertaining to decals.
123
pub(crate) struct RenderViewClusteredDecalBindGroupEntries<'a> {
124
/// The list of decals, corresponding to `mesh_view_bindings::decals` in the
125
/// shader.
126
pub(crate) decals: &'a Buffer,
127
/// The list of textures, corresponding to
128
/// `mesh_view_bindings::decal_textures` in the shader.
129
pub(crate) texture_views: Vec<&'a <TextureView as Deref>::Target>,
130
/// The sampler that the shader uses to sample decals, corresponding to
131
/// `mesh_view_bindings::decal_sampler` in the shader.
132
pub(crate) sampler: &'a Sampler,
133
}
134
135
/// A render-world resource that holds the buffer of [`ClusteredDecal`]s ready
136
/// to upload to the GPU.
137
#[derive(Resource, Deref, DerefMut)]
138
pub struct DecalsBuffer(RawBufferVec<RenderClusteredDecal>);
139
140
impl Default for DecalsBuffer {
141
fn default() -> Self {
142
DecalsBuffer(RawBufferVec::new(BufferUsages::STORAGE))
143
}
144
}
145
146
impl Plugin for ClusteredDecalPlugin {
147
fn build(&self, app: &mut App) {
148
load_shader_library!(app, "clustered.wgsl");
149
150
app.add_plugins(SyncComponentPlugin::<ClusteredDecal, Self>::default());
151
152
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
153
return;
154
};
155
156
render_app
157
.init_resource::<DecalsBuffer>()
158
.init_resource::<RenderClusteredDecals>()
159
.add_systems(ExtractSchedule, (extract_decals, extract_clustered_decal))
160
.add_systems(
161
Render,
162
prepare_decals
163
.in_set(RenderSystems::ManageViews)
164
.after(prepare_lights),
165
)
166
.add_systems(
167
Render,
168
upload_decals.in_set(RenderSystems::PrepareResources),
169
);
170
}
171
}
172
173
impl SyncComponent<ClusteredDecalPlugin> for ClusteredDecal {
174
type Out = Self;
175
}
176
177
// This is needed because of the orphan rule not allowing implementing
178
// foreign trait ExtractComponent on foreign type ClusteredDecal
179
fn extract_clustered_decal(
180
mut commands: Commands,
181
mut previous_len: Local<usize>,
182
query: Extract<Query<(RenderEntity, &ClusteredDecal)>>,
183
) {
184
let mut values = Vec::with_capacity(*previous_len);
185
for (entity, query_item) in &query {
186
values.push((entity, query_item.clone()));
187
}
188
*previous_len = values.len();
189
commands.try_insert_batch(values);
190
}
191
192
/// The GPU data structure that stores information about each decal.
193
#[derive(Clone, Copy, Default, ShaderType, Pod, Zeroable)]
194
#[repr(C)]
195
pub struct RenderClusteredDecal {
196
/// The inverse of the model matrix.
197
///
198
/// The shader uses this in order to back-transform world positions into
199
/// model space.
200
local_from_world: Mat4,
201
/// The index of each decal texture in the binding array.
202
///
203
/// These are in the order of the base color texture, the normal map
204
/// texture, the metallic-roughness map texture, and finally the emissive
205
/// texture.
206
///
207
/// If the decal doesn't have a texture assigned to a slot, the index at
208
/// that slot will be -1.
209
image_indices: [i32; 4],
210
/// A custom tag available for application-defined purposes.
211
tag: u32,
212
/// Padding.
213
pad_a: u32,
214
/// Padding.
215
pad_b: u32,
216
/// Padding.
217
pad_c: u32,
218
}
219
220
/// Extracts decals from the main world into the render world.
221
pub fn extract_decals(
222
decals: Extract<
223
Query<(
224
RenderEntity,
225
&ClusteredDecal,
226
&GlobalTransform,
227
&ViewVisibility,
228
)>,
229
>,
230
spot_light_textures: Extract<
231
Query<(
232
RenderEntity,
233
&SpotLightTexture,
234
&GlobalTransform,
235
&ViewVisibility,
236
)>,
237
>,
238
point_light_textures: Extract<
239
Query<(
240
RenderEntity,
241
&PointLightTexture,
242
&GlobalTransform,
243
&ViewVisibility,
244
)>,
245
>,
246
directional_light_textures: Extract<
247
Query<(
248
RenderEntity,
249
&DirectionalLightTexture,
250
&GlobalTransform,
251
&ViewVisibility,
252
)>,
253
>,
254
mut render_decals: ResMut<RenderClusteredDecals>,
255
) {
256
// Clear out the `RenderDecals` in preparation for a new frame.
257
render_decals.clear();
258
259
extract_clustered_decals(&decals, &mut render_decals);
260
extract_spot_light_textures(&spot_light_textures, &mut render_decals);
261
extract_point_light_textures(&point_light_textures, &mut render_decals);
262
extract_directional_light_textures(&directional_light_textures, &mut render_decals);
263
}
264
265
/// Extracts all clustered decals and light textures from the scene and transfers
266
/// them to the render world.
267
fn extract_clustered_decals(
268
decals: &Extract<
269
Query<(
270
RenderEntity,
271
&ClusteredDecal,
272
&GlobalTransform,
273
&ViewVisibility,
274
)>,
275
>,
276
render_decals: &mut RenderClusteredDecals,
277
) {
278
// Loop over each decal.
279
for (decal_entity, clustered_decal, global_transform, view_visibility) in decals {
280
// If the decal is invisible, skip it.
281
if !view_visibility.get() {
282
continue;
283
}
284
285
// Insert the decal, grabbing the ID of every associated texture as we
286
// do.
287
render_decals.insert_decal(
288
decal_entity,
289
[
290
clustered_decal.base_color_texture.as_ref().map(Handle::id),
291
clustered_decal.normal_map_texture.as_ref().map(Handle::id),
292
clustered_decal
293
.metallic_roughness_texture
294
.as_ref()
295
.map(Handle::id),
296
clustered_decal.emissive_texture.as_ref().map(Handle::id),
297
],
298
global_transform.affine().inverse().into(),
299
clustered_decal.tag,
300
);
301
}
302
}
303
304
/// Extracts all textures from spot lights from the main world to the render
305
/// world as clustered decals.
306
fn extract_spot_light_textures(
307
spot_light_textures: &Extract<
308
Query<(
309
RenderEntity,
310
&SpotLightTexture,
311
&GlobalTransform,
312
&ViewVisibility,
313
)>,
314
>,
315
render_decals: &mut RenderClusteredDecals,
316
) {
317
for (decal_entity, texture, global_transform, view_visibility) in spot_light_textures {
318
// If the texture is invisible, skip it.
319
if !view_visibility.get() {
320
continue;
321
}
322
323
render_decals.insert_decal(
324
decal_entity,
325
[Some(texture.image.id()), None, None, None],
326
global_transform.affine().inverse().into(),
327
0,
328
);
329
}
330
}
331
332
/// Extracts all textures from point lights from the main world to the render
333
/// world as clustered decals.
334
fn extract_point_light_textures(
335
point_light_textures: &Extract<
336
Query<(
337
RenderEntity,
338
&PointLightTexture,
339
&GlobalTransform,
340
&ViewVisibility,
341
)>,
342
>,
343
render_decals: &mut RenderClusteredDecals,
344
) {
345
for (decal_entity, texture, global_transform, view_visibility) in point_light_textures {
346
// If the texture is invisible, skip it.
347
if !view_visibility.get() {
348
continue;
349
}
350
351
render_decals.insert_decal(
352
decal_entity,
353
[Some(texture.image.id()), None, None, None],
354
global_transform.affine().inverse().into(),
355
texture.cubemap_layout as u32,
356
);
357
}
358
}
359
360
/// Extracts all textures from directional lights from the main world to the
361
/// render world as clustered decals.
362
fn extract_directional_light_textures(
363
directional_light_textures: &Extract<
364
Query<(
365
RenderEntity,
366
&DirectionalLightTexture,
367
&GlobalTransform,
368
&ViewVisibility,
369
)>,
370
>,
371
render_decals: &mut RenderClusteredDecals,
372
) {
373
for (decal_entity, texture, global_transform, view_visibility) in directional_light_textures {
374
// If the texture is invisible, skip it.
375
if !view_visibility.get() {
376
continue;
377
}
378
379
render_decals.insert_decal(
380
decal_entity,
381
[Some(texture.image.id()), None, None, None],
382
global_transform.affine().inverse().into(),
383
if texture.tiled { 1 } else { 0 },
384
);
385
}
386
}
387
388
/// Adds all decals in the scene to the [`GlobalClusterableObjectMeta`] table.
389
fn prepare_decals(
390
decals: Query<Entity, With<ClusteredDecal>>,
391
mut global_clusterable_object_meta: ResMut<GlobalClusterableObjectMeta>,
392
render_decals: Res<RenderClusteredDecals>,
393
) {
394
for decal_entity in &decals {
395
if let Some(index) = render_decals.entity_to_decal_index.get(&decal_entity) {
396
global_clusterable_object_meta
397
.entity_to_index
398
.insert(decal_entity, *index);
399
}
400
}
401
}
402
403
/// Returns the layout for the clustered-decal-related bind group entries for a
404
/// single view.
405
pub(crate) fn get_bind_group_layout_entries(
406
render_device: &RenderDevice,
407
render_adapter: &RenderAdapter,
408
) -> Option<[BindGroupLayoutEntryBuilder; 3]> {
409
// If binding arrays aren't supported on the current platform, we have no
410
// bind group layout entries.
411
if !clustered_decals_are_usable(render_device, render_adapter) {
412
return None;
413
}
414
415
Some([
416
// `decals`
417
binding_types::storage_buffer_read_only::<RenderClusteredDecal>(false),
418
// `decal_textures`
419
binding_types::texture_2d(TextureSampleType::Float { filterable: true })
420
.count(NonZero::<u32>::new(max_view_decals(render_device)).unwrap()),
421
// `decal_sampler`
422
binding_types::sampler(SamplerBindingType::Filtering),
423
])
424
}
425
426
impl<'a> RenderViewClusteredDecalBindGroupEntries<'a> {
427
/// Creates and returns the bind group entries for clustered decals for a
428
/// single view.
429
pub(crate) fn get(
430
render_decals: &RenderClusteredDecals,
431
decals_buffer: &'a DecalsBuffer,
432
images: &'a RenderAssets<GpuImage>,
433
fallback_image: &'a FallbackImage,
434
render_device: &RenderDevice,
435
render_adapter: &RenderAdapter,
436
) -> Option<RenderViewClusteredDecalBindGroupEntries<'a>> {
437
// Skip the entries if decals are unsupported on the current platform.
438
if !clustered_decals_are_usable(render_device, render_adapter) {
439
return None;
440
}
441
442
// We use the first sampler among all the images. This assumes that all
443
// images use the same sampler, which is a documented restriction. If
444
// there's no sampler, we just use the one from the fallback image.
445
let sampler = match render_decals
446
.binding_index_to_textures
447
.iter()
448
.filter_map(|image_id| images.get(*image_id))
449
.next()
450
{
451
Some(gpu_image) => &gpu_image.sampler,
452
None => &fallback_image.d2.sampler,
453
};
454
455
// Gather up the decal textures.
456
let mut texture_views = vec![];
457
for image_id in &render_decals.binding_index_to_textures {
458
match images.get(*image_id) {
459
None => texture_views.push(&*fallback_image.d2.texture_view),
460
Some(gpu_image) => texture_views.push(&*gpu_image.texture_view),
461
}
462
}
463
464
// If required on this platform, pad out the binding array to its
465
// maximum length.
466
if !render_device
467
.features()
468
.contains(WgpuFeatures::PARTIALLY_BOUND_BINDING_ARRAY)
469
{
470
let max_view_decals = max_view_decals(render_device);
471
while texture_views.len() < max_view_decals as usize {
472
texture_views.push(&*fallback_image.d2.texture_view);
473
}
474
} else if texture_views.is_empty() {
475
texture_views.push(&*fallback_image.d2.texture_view);
476
}
477
478
Some(RenderViewClusteredDecalBindGroupEntries {
479
decals: decals_buffer.buffer()?,
480
texture_views,
481
sampler,
482
})
483
}
484
}
485
486
impl RenderClusteredDecals {
487
/// Returns the index of the given image in the decal texture binding array,
488
/// adding it to the list if necessary.
489
fn get_or_insert_image(&mut self, image_id: &AssetId<Image>) -> i32 {
490
*self
491
.texture_to_binding_index
492
.entry(*image_id)
493
.or_insert_with(|| {
494
let index = self.binding_index_to_textures.len() as i32;
495
self.binding_index_to_textures.push(*image_id);
496
index
497
})
498
}
499
}
500
501
/// Uploads the list of decals from [`RenderClusteredDecals::decals`] to the
502
/// GPU.
503
fn upload_decals(
504
render_decals: Res<RenderClusteredDecals>,
505
mut decals_buffer: ResMut<DecalsBuffer>,
506
render_device: Res<RenderDevice>,
507
render_queue: Res<RenderQueue>,
508
) {
509
decals_buffer.clear();
510
511
for &decal in &render_decals.decals {
512
decals_buffer.push(decal);
513
}
514
515
// Make sure the buffer is non-empty.
516
// Otherwise there won't be a buffer to bind.
517
if decals_buffer.is_empty() {
518
decals_buffer.push(RenderClusteredDecal::default());
519
}
520
521
decals_buffer.write_buffer(&render_device, &render_queue);
522
}
523
524
/// Returns true if clustered decals are usable on the current platform or false
525
/// otherwise.
526
///
527
/// Clustered decals are currently disabled on macOS and iOS due to insufficient
528
/// texture bindings and limited bindless support in `wgpu`.
529
pub fn clustered_decals_are_usable(
530
render_device: &RenderDevice,
531
render_adapter: &RenderAdapter,
532
) -> bool {
533
// Disable binding arrays on Metal. There aren't enough texture bindings available.
534
// See issue #17553.
535
// Re-enable this when `wgpu` has first-class bindless.
536
binding_arrays_are_usable(render_device, render_adapter)
537
&& cfg!(feature = "pbr_clustered_decals")
538
}
539
540
/// Returns the maximum number of decals that can be in the scene, taking
541
/// platform limitations into account.
542
fn max_view_decals(render_device: &RenderDevice) -> u32 {
543
// If the current `wgpu` platform doesn't support partially-bound binding
544
// arrays, limit the number of decals to a low number. If we didn't do this,
545
// then on such platforms we'd pay the maximum overhead even if there are no
546
// decals are in the scene.
547
if render_device
548
.features()
549
.contains(WgpuFeatures::PARTIALLY_BOUND_BINDING_ARRAY)
550
{
551
// This number was determined arbitrarily as a reasonable value that
552
// would encompass most use cases (e.g. bullet holes in walls) while
553
// offering a failsafe to prevent shaders becoming too slow if there are
554
// extremely large numbers of decals.
555
1024
556
} else {
557
8
558
}
559
}
560
561