fyrox_impl/scene/light/
point.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! Point light can be represented as light bulb which hangs on wire - it is
22//! spherical light source which emits light in all directions. It has single
23//! parameter - radius at which intensity will be zero. Intensity of light will
24//! be calculated using inverse square root law.
25//!
26//! # Light scattering
27//!
28//! Point light support light scattering feature - it means that you'll see light
29//! volume as well as lighted surfaces. Simple example from real life: light bulb
30//! in the fog. This effect significantly improves perception of light, but should
31//! be used carefully with sane values of light scattering, otherwise you'll get
32//! bright glowing sphere instead of slightly visible light volume.
33//!
34//! # Performance notes
35//!
36//! Point lights supports shadows, but keep in mind - they're very expensive and
37//! can easily ruin performance of your game, especially on low-end hardware. Light
38//! scattering is relatively heavy too.
39
40use crate::scene::base::BaseBuilder;
41use crate::scene::node::constructor::NodeConstructor;
42use crate::{
43    core::{
44        color::Color,
45        math::aabb::AxisAlignedBoundingBox,
46        pool::Handle,
47        reflect::prelude::*,
48        type_traits::prelude::*,
49        uuid::{uuid, Uuid},
50        variable::InheritableVariable,
51        visitor::{Visit, VisitResult, Visitor},
52    },
53    scene::{
54        base::Base,
55        debug::SceneDrawingContext,
56        graph::Graph,
57        light::{BaseLight, BaseLightBuilder},
58        node::{Node, NodeTrait},
59    },
60};
61use fyrox_graph::constructor::ConstructorProvider;
62use fyrox_graph::BaseSceneGraph;
63use std::ops::{Deref, DerefMut};
64
65/// See module docs.
66#[derive(Debug, Reflect, Clone, Visit, ComponentProvider)]
67pub struct PointLight {
68    #[component(include)]
69    base_light: BaseLight,
70
71    #[reflect(min_value = 0.0, step = 0.001)]
72    #[reflect(setter = "set_shadow_bias")]
73    shadow_bias: InheritableVariable<f32>,
74
75    #[reflect(min_value = 0.0, step = 0.1)]
76    #[reflect(setter = "set_radius")]
77    radius: InheritableVariable<f32>,
78}
79
80impl Deref for PointLight {
81    type Target = Base;
82
83    fn deref(&self) -> &Self::Target {
84        &self.base_light.base
85    }
86}
87
88impl DerefMut for PointLight {
89    fn deref_mut(&mut self) -> &mut Self::Target {
90        &mut self.base_light.base
91    }
92}
93
94impl TypeUuidProvider for PointLight {
95    fn type_uuid() -> Uuid {
96        uuid!("c81dcc31-7cb9-465f-abd9-b385ac6f4d37")
97    }
98}
99
100impl PointLight {
101    /// Returns a reference to base light.    
102    pub fn base_light_ref(&self) -> &BaseLight {
103        &self.base_light
104    }
105
106    /// Returns a reference to base light.
107    pub fn base_light_mut(&mut self) -> &mut BaseLight {
108        &mut self.base_light
109    }
110
111    /// Sets radius of point light. This parameter also affects radius of spherical
112    /// light volume that is used in light scattering.
113    #[inline]
114    pub fn set_radius(&mut self, radius: f32) -> f32 {
115        self.radius.set_value_and_mark_modified(radius.abs())
116    }
117
118    /// Returns radius of point light.
119    #[inline]
120    pub fn radius(&self) -> f32 {
121        *self.radius
122    }
123
124    /// Sets new shadow bias value. Bias will be used to offset fragment's depth before
125    /// compare it with shadow map value, it is used to remove "shadow acne".
126    pub fn set_shadow_bias(&mut self, bias: f32) -> f32 {
127        self.shadow_bias.set_value_and_mark_modified(bias)
128    }
129
130    /// Returns current value of shadow bias.
131    pub fn shadow_bias(&self) -> f32 {
132        *self.shadow_bias
133    }
134}
135
136impl ConstructorProvider<Node, Graph> for PointLight {
137    fn constructor() -> NodeConstructor {
138        NodeConstructor::new::<Self>()
139            .with_variant("Point Light", |_| {
140                PointLightBuilder::new(BaseLightBuilder::new(
141                    BaseBuilder::new().with_name("PointLight"),
142                ))
143                .with_radius(10.0)
144                .build_node()
145                .into()
146            })
147            .with_group("Light")
148    }
149}
150
151impl NodeTrait for PointLight {
152    fn local_bounding_box(&self) -> AxisAlignedBoundingBox {
153        AxisAlignedBoundingBox::from_radius(*self.radius)
154    }
155
156    fn world_bounding_box(&self) -> AxisAlignedBoundingBox {
157        // Discard scaling part, light emission distance does not affected by scaling.
158        self.local_bounding_box()
159            .transform(&self.global_transform_without_scaling())
160    }
161
162    fn id(&self) -> Uuid {
163        Self::type_uuid()
164    }
165
166    fn debug_draw(&self, ctx: &mut SceneDrawingContext) {
167        ctx.draw_wire_sphere(self.global_position(), self.radius(), 30, Color::GREEN);
168    }
169}
170
171impl Default for PointLight {
172    fn default() -> Self {
173        Self {
174            base_light: Default::default(),
175            shadow_bias: InheritableVariable::new_modified(0.025),
176            radius: InheritableVariable::new_modified(10.0),
177        }
178    }
179}
180
181/// Allows you to build point light in declarative manner.
182pub struct PointLightBuilder {
183    base_light_builder: BaseLightBuilder,
184    shadow_bias: f32,
185    radius: f32,
186}
187
188impl PointLightBuilder {
189    /// Creates new builder instance.
190    pub fn new(base_light_builder: BaseLightBuilder) -> Self {
191        Self {
192            base_light_builder,
193            shadow_bias: 0.025,
194            radius: 10.0,
195        }
196    }
197
198    /// Sets desired radius.
199    pub fn with_radius(mut self, radius: f32) -> Self {
200        self.radius = radius;
201        self
202    }
203
204    /// Sets desired shadow bias.
205    pub fn with_shadow_bias(mut self, bias: f32) -> Self {
206        self.shadow_bias = bias;
207        self
208    }
209
210    /// Builds new instance of point light.
211    pub fn build_point_light(self) -> PointLight {
212        PointLight {
213            base_light: self.base_light_builder.build(),
214            radius: self.radius.into(),
215            shadow_bias: self.shadow_bias.into(),
216        }
217    }
218
219    /// Builds new instance of point light node.
220    pub fn build_node(self) -> Node {
221        Node::new(self.build_point_light())
222    }
223
224    /// Builds new instance of point light and adds it to the graph.
225    pub fn build(self, graph: &mut Graph) -> Handle<Node> {
226        graph.add_node(self.build_node())
227    }
228}