bevy_light/
spot_light.rs

1use bevy_asset::Handle;
2use bevy_camera::{
3    primitives::Frustum,
4    visibility::{self, Visibility, VisibilityClass, VisibleMeshEntities},
5};
6use bevy_color::Color;
7use bevy_ecs::prelude::*;
8use bevy_image::Image;
9use bevy_math::{Affine3A, Dir3, Mat3, Mat4, Vec3};
10use bevy_reflect::prelude::*;
11use bevy_transform::components::{GlobalTransform, Transform};
12
13use crate::cluster::{ClusterVisibilityClass, GlobalVisibleClusterableObjects};
14
15/// A light that emits light in a given direction from a central point.
16///
17/// Behaves like a point light in a perfectly absorbent housing that
18/// shines light only in a given direction. The direction is taken from
19/// the transform, and can be specified with [`Transform::looking_at`](Transform::looking_at).
20///
21/// To control the resolution of the shadow maps, use the [`DirectionalLightShadowMap`](`crate::DirectionalLightShadowMap`)  resource.
22#[derive(Component, Debug, Clone, Copy, Reflect)]
23#[reflect(Component, Default, Debug, Clone)]
24#[require(Frustum, VisibleMeshEntities, Transform, Visibility, VisibilityClass)]
25#[component(on_add = visibility::add_visibility_class::<ClusterVisibilityClass>)]
26pub struct SpotLight {
27    /// The color of the light.
28    ///
29    /// By default, this is white.
30    pub color: Color,
31
32    /// Luminous power in lumens, representing the amount of light emitted by this source in all directions.
33    pub intensity: f32,
34
35    /// Range in meters that this light illuminates.
36    ///
37    /// Note that this value affects resolution of the shadow maps; generally, the
38    /// higher you set it, the lower-resolution your shadow maps will be.
39    /// Consequently, you should set this value to be only the size that you need.
40    pub range: f32,
41
42    /// Simulates a light source coming from a spherical volume with the given
43    /// radius.
44    ///
45    /// This affects the size of specular highlights created by this light, as
46    /// well as the soft shadow penumbra size. Because of this, large values may
47    /// not produce the intended result -- for example, light radius does not
48    /// affect shadow softness or diffuse lighting.
49    pub radius: f32,
50
51    /// Whether this light casts shadows.
52    ///
53    /// Note that shadows are rather expensive and become more so with every
54    /// light that casts them. In general, it's best to aggressively limit the
55    /// number of lights with shadows enabled to one or two at most.
56    pub shadows_enabled: bool,
57
58    /// Whether soft shadows are enabled.
59    ///
60    /// Soft shadows, also known as *percentage-closer soft shadows* or PCSS,
61    /// cause shadows to become blurrier (i.e. their penumbra increases in
62    /// radius) as they extend away from objects. The blurriness of the shadow
63    /// depends on the [`SpotLight::radius`] of the light; larger lights result in larger
64    /// penumbras and therefore blurrier shadows.
65    ///
66    /// Currently, soft shadows are rather noisy if not using the temporal mode.
67    /// If you enable soft shadows, consider choosing
68    /// [`ShadowFilteringMethod::Temporal`] and enabling temporal antialiasing
69    /// (TAA) to smooth the noise out over time.
70    ///
71    /// Note that soft shadows are significantly more expensive to render than
72    /// hard shadows.
73    ///
74    /// [`ShadowFilteringMethod::Temporal`]: crate::ShadowFilteringMethod::Temporal
75    #[cfg(feature = "experimental_pbr_pcss")]
76    pub soft_shadows_enabled: bool,
77
78    /// Whether this spot light contributes diffuse lighting to meshes with
79    /// lightmaps.
80    ///
81    /// Set this to false if your lightmap baking tool bakes the direct diffuse
82    /// light from this directional light into the lightmaps in order to avoid
83    /// counting the radiance from this light twice. Note that the specular
84    /// portion of the light is always considered, because Bevy currently has no
85    /// means to bake specular light.
86    ///
87    /// By default, this is set to true.
88    pub affects_lightmapped_mesh_diffuse: bool,
89
90    /// A value that adjusts the tradeoff between self-shadowing artifacts and
91    /// proximity of shadows to their casters.
92    ///
93    /// This value frequently must be tuned to the specific scene; this is
94    /// normal and a well-known part of the shadow mapping workflow. If set too
95    /// low, unsightly shadow patterns appear on objects not in shadow as
96    /// objects incorrectly cast shadows on themselves, known as *shadow acne*.
97    /// If set too high, shadows detach from the objects casting them and seem
98    /// to "fly" off the objects, known as *Peter Panning*.
99    pub shadow_depth_bias: f32,
100
101    /// A bias applied along the direction of the fragment's surface normal. It is scaled to the
102    /// shadow map's texel size so that it can be small close to the camera and gets larger further
103    /// away.
104    pub shadow_normal_bias: f32,
105
106    /// The distance from the light to the near Z plane in the shadow map.
107    ///
108    /// Objects closer than this distance to the light won't cast shadows.
109    /// Setting this higher increases the shadow map's precision.
110    ///
111    /// This only has an effect if shadows are enabled.
112    pub shadow_map_near_z: f32,
113
114    /// Angle defining the distance from the spot light direction to the outer limit
115    /// of the light's cone of effect.
116    /// `outer_angle` should be < `PI / 2.0`.
117    /// `PI / 2.0` defines a hemispherical spot light, but shadows become very blocky as the angle
118    /// approaches this limit.
119    pub outer_angle: f32,
120
121    /// Angle defining the distance from the spot light direction to the inner limit
122    /// of the light's cone of effect.
123    /// Light is attenuated from `inner_angle` to `outer_angle` to give a smooth falloff.
124    /// `inner_angle` should be <= `outer_angle`
125    pub inner_angle: f32,
126}
127
128impl SpotLight {
129    pub const DEFAULT_SHADOW_DEPTH_BIAS: f32 = 0.02;
130    pub const DEFAULT_SHADOW_NORMAL_BIAS: f32 = 1.8;
131    pub const DEFAULT_SHADOW_MAP_NEAR_Z: f32 = 0.1;
132}
133
134impl Default for SpotLight {
135    fn default() -> Self {
136        // a quarter arc attenuating from the center
137        Self {
138            color: Color::WHITE,
139            // 1,000,000 lumens is a very large "cinema light" capable of registering brightly at Bevy's
140            // default "very overcast day" exposure level. For "indoor lighting" with a lower exposure,
141            // this would be way too bright.
142            intensity: 1_000_000.0,
143            range: 20.0,
144            radius: 0.0,
145            shadows_enabled: false,
146            affects_lightmapped_mesh_diffuse: true,
147            shadow_depth_bias: Self::DEFAULT_SHADOW_DEPTH_BIAS,
148            shadow_normal_bias: Self::DEFAULT_SHADOW_NORMAL_BIAS,
149            shadow_map_near_z: Self::DEFAULT_SHADOW_MAP_NEAR_Z,
150            inner_angle: 0.0,
151            outer_angle: core::f32::consts::FRAC_PI_4,
152            #[cfg(feature = "experimental_pbr_pcss")]
153            soft_shadows_enabled: false,
154        }
155    }
156}
157
158/// Constructs a right-handed orthonormal basis from a given unit Z vector.
159///
160/// This method of constructing a basis from a [`Vec3`] is used by [`bevy_math::Vec3::any_orthonormal_pair`]
161// we will also construct it in the fragment shader and need our implementations to match exactly,
162// so we reproduce it here to avoid a mismatch if glam changes.
163// See bevy_render/maths.wgsl:orthonormalize
164pub fn orthonormalize(z_basis: Dir3) -> Mat3 {
165    let sign = 1f32.copysign(z_basis.z);
166    let a = -1.0 / (sign + z_basis.z);
167    let b = z_basis.x * z_basis.y * a;
168    let x_basis = Vec3::new(
169        1.0 + sign * z_basis.x * z_basis.x * a,
170        sign * b,
171        -sign * z_basis.x,
172    );
173    let y_basis = Vec3::new(b, sign + z_basis.y * z_basis.y * a, -z_basis.y);
174    Mat3::from_cols(x_basis, y_basis, z_basis.into())
175}
176/// Constructs a right-handed orthonormal basis with translation, using only the forward direction and translation of a given [`GlobalTransform`].
177///
178/// This is a version of [`orthonormalize`] which also includes translation.
179pub fn spot_light_world_from_view(transform: &GlobalTransform) -> Affine3A {
180    // the matrix z_local (opposite of transform.forward())
181    let fwd_dir = transform.back();
182
183    let basis = orthonormalize(fwd_dir);
184    Affine3A::from_mat3_translation(basis, transform.translation())
185}
186
187pub fn spot_light_clip_from_view(angle: f32, near_z: f32) -> Mat4 {
188    // spot light projection FOV is 2x the angle from spot light center to outer edge
189    Mat4::perspective_infinite_reverse_rh(angle * 2.0, 1.0, near_z)
190}
191
192/// Add to a [`SpotLight`] to add a light texture effect.
193/// A texture mask is applied to the light source to modulate its intensity,  
194/// simulating patterns like window shadows, gobo/cookie effects, or soft falloffs.
195#[derive(Clone, Component, Debug, Reflect)]
196#[reflect(Component, Debug)]
197#[require(SpotLight)]
198pub struct SpotLightTexture {
199    /// The texture image. Only the R channel is read.
200    /// Note the border of the image should be entirely black to avoid leaking light.
201    pub image: Handle<Image>,
202}
203
204pub fn update_spot_light_frusta(
205    global_lights: Res<GlobalVisibleClusterableObjects>,
206    mut views: Query<
207        (Entity, &GlobalTransform, &SpotLight, &mut Frustum),
208        Or<(Changed<GlobalTransform>, Changed<SpotLight>)>,
209    >,
210) {
211    for (entity, transform, spot_light, mut frustum) in &mut views {
212        // The frusta are used for culling meshes to the light for shadow mapping
213        // so if shadow mapping is disabled for this light, then the frusta are
214        // not needed.
215        // Also, if the light is not relevant for any cluster, it will not be in the
216        // global lights set and so there is no need to update its frusta.
217        if !spot_light.shadows_enabled || !global_lights.entities.contains(&entity) {
218            continue;
219        }
220
221        // ignore scale because we don't want to effectively scale light radius and range
222        // by applying those as a view transform to shadow map rendering of objects
223        let view_backward = transform.back();
224
225        let spot_world_from_view = spot_light_world_from_view(transform);
226        let spot_clip_from_view =
227            spot_light_clip_from_view(spot_light.outer_angle, spot_light.shadow_map_near_z);
228        let clip_from_world = spot_clip_from_view * spot_world_from_view.inverse();
229
230        *frustum = Frustum::from_clip_from_world_custom_far(
231            &clip_from_world,
232            &transform.translation(),
233            &view_backward,
234            spot_light.range,
235        );
236    }
237}