fyrox_impl/scene/
decal.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//! Decal is an image that gets projected to a geometry of a scene.
22//!
23//! For more info see [`Decal`]
24
25use crate::{
26    core::{
27        color::Color,
28        math::aabb::AxisAlignedBoundingBox,
29        pool::Handle,
30        reflect::prelude::*,
31        type_traits::prelude::*,
32        uuid::{uuid, Uuid},
33        variable::InheritableVariable,
34        visitor::prelude::*,
35    },
36    resource::texture::TextureResource,
37    scene::node::constructor::NodeConstructor,
38    scene::{
39        base::{Base, BaseBuilder},
40        graph::Graph,
41        node::{Node, NodeTrait},
42    },
43};
44use fyrox_graph::constructor::ConstructorProvider;
45use fyrox_graph::BaseSceneGraph;
46use std::ops::{Deref, DerefMut};
47
48/// Decal is an image that gets projected to a geometry of a scene. Blood splatters, bullet holes, scratches
49/// etc. are done via decals.
50///
51/// # Size and transformations
52///
53/// A decal defines a cube that projects a texture on every pixel of a scene that got into the cube. Exact cube
54/// size is defines by decal's `local scale`. For example, if you have a decal with scale (1.0, 2.0, 0.1) then
55/// the size of the cube (in local coordinates) will be `width = 1.0`, `height = 2.0`, `depth = 0.1`. The decal
56/// can be rotated as any other scene node. Its final size and orientation is defined by the chain of
57/// transformations of parent nodes.
58///
59/// # Masking
60///
61/// Often you need to ensure that decal will be applied only on desired surfaces. For example a crack on the wall
62/// should not affect any surrounding objects, this can be achieved by using decal mask. Each decal has layer index,
63/// it will be drawn only if the index matches the index of the object that inside of decal bounds.
64///
65/// # Supported maps
66///
67/// Currently, only diffuse and normal maps are supported. Diffuse and normal maps will be automatically projected
68/// on the data stored in G-Buffer.
69///
70/// # Limitations
71///
72/// Current implementation works only with Deferred render path. Custom materials that uses Forward pass should
73/// implement decals manually.
74///
75/// # Performance
76///
77/// It should be noted that decals are not cheap, keep amount (and size) of decals at reasonable values! This
78/// means that unused decals (bullet holes for example) must be removed after some time.
79///
80/// # Example
81///
82/// ```
83/// # use fyrox_impl::{
84/// #         asset::manager::ResourceManager,
85/// #         core::pool::Handle,
86/// #         scene::{
87/// #         node::Node,
88/// #         graph::Graph,
89/// #         decal::DecalBuilder,
90/// #         base::BaseBuilder,
91/// #         transform::TransformBuilder
92/// #     },
93/// #     core::algebra::Vector3
94/// # };
95/// # use fyrox_impl::resource::texture::Texture;
96///
97/// fn create_bullet_hole(resource_manager: ResourceManager, graph: &mut Graph) -> Handle<Node> {
98///     DecalBuilder::new(
99///             BaseBuilder::new()
100///                 .with_local_transform(
101///                     TransformBuilder::new()
102///                         .with_local_scale(Vector3::new(2.0, 2.0, 2.0))
103///                         .build()
104///         ))
105///         .with_diffuse_texture(resource_manager.request::<Texture>("bullet_hole.png"))
106///         .build(graph)
107/// }
108/// ```
109#[derive(Debug, Visit, Default, Clone, Reflect, ComponentProvider)]
110pub struct Decal {
111    base: Base,
112
113    #[reflect(setter = "set_diffuse_texture")]
114    diffuse_texture: InheritableVariable<Option<TextureResource>>,
115
116    #[reflect(setter = "set_normal_texture")]
117    normal_texture: InheritableVariable<Option<TextureResource>>,
118
119    #[reflect(setter = "set_color")]
120    color: InheritableVariable<Color>,
121
122    #[reflect(min_value = 0.0)]
123    #[reflect(setter = "set_layer")]
124    layer: InheritableVariable<u8>,
125}
126
127impl Deref for Decal {
128    type Target = Base;
129
130    fn deref(&self) -> &Self::Target {
131        &self.base
132    }
133}
134
135impl DerefMut for Decal {
136    fn deref_mut(&mut self) -> &mut Self::Target {
137        &mut self.base
138    }
139}
140
141impl TypeUuidProvider for Decal {
142    fn type_uuid() -> Uuid {
143        uuid!("c4d24e48-edd1-4fb2-ad82-4b3d3ea985d8")
144    }
145}
146
147impl Decal {
148    /// Sets new diffuse texture.
149    pub fn set_diffuse_texture(
150        &mut self,
151        diffuse_texture: Option<TextureResource>,
152    ) -> Option<TextureResource> {
153        std::mem::replace(
154            self.diffuse_texture.get_value_mut_and_mark_modified(),
155            diffuse_texture,
156        )
157    }
158
159    /// Returns current diffuse texture.
160    pub fn diffuse_texture(&self) -> Option<&TextureResource> {
161        self.diffuse_texture.as_ref()
162    }
163
164    /// Returns current diffuse texture.
165    pub fn diffuse_texture_value(&self) -> Option<TextureResource> {
166        (*self.diffuse_texture).clone()
167    }
168
169    /// Sets new normal texture.
170    pub fn set_normal_texture(
171        &mut self,
172        normal_texture: Option<TextureResource>,
173    ) -> Option<TextureResource> {
174        std::mem::replace(
175            self.normal_texture.get_value_mut_and_mark_modified(),
176            normal_texture,
177        )
178    }
179
180    /// Returns current normal texture.
181    pub fn normal_texture(&self) -> Option<&TextureResource> {
182        self.normal_texture.as_ref()
183    }
184
185    /// Returns current normal texture.
186    pub fn normal_texture_value(&self) -> Option<TextureResource> {
187        (*self.normal_texture).clone()
188    }
189
190    /// Sets new color for the decal.
191    pub fn set_color(&mut self, color: Color) -> Color {
192        self.color.set_value_and_mark_modified(color)
193    }
194
195    /// Returns current color of the decal.
196    pub fn color(&self) -> Color {
197        *self.color
198    }
199
200    /// Sets layer index of the decal. Layer index allows you to apply decals only on desired
201    /// surfaces. For example, static geometry could have `index == 0` and dynamic `index == 1`.
202    /// To "filter" decals all you need to do is to set appropriate layer index to decal, for
203    /// example blood splatter decal will have `index == 0` in this case. In case of dynamic
204    /// objects (like bots, etc.) index will be 1.
205    pub fn set_layer(&mut self, layer: u8) -> u8 {
206        self.layer.set_value_and_mark_modified(layer)
207    }
208
209    /// Returns current layer index.
210    pub fn layer(&self) -> u8 {
211        *self.layer
212    }
213}
214
215impl ConstructorProvider<Node, Graph> for Decal {
216    fn constructor() -> NodeConstructor {
217        NodeConstructor::new::<Self>().with_variant("Decal", |_| {
218            DecalBuilder::new(BaseBuilder::new().with_name("Decal"))
219                .build_node()
220                .into()
221        })
222    }
223}
224
225impl NodeTrait for Decal {
226    /// Returns current **local-space** bounding box.
227    #[inline]
228    fn local_bounding_box(&self) -> AxisAlignedBoundingBox {
229        // TODO: Maybe calculate AABB using frustum corners?
230        self.base.local_bounding_box()
231    }
232
233    /// Returns current **world-space** bounding box.
234    fn world_bounding_box(&self) -> AxisAlignedBoundingBox {
235        self.base.world_bounding_box()
236    }
237
238    fn id(&self) -> Uuid {
239        Self::type_uuid()
240    }
241}
242
243/// Allows you to create a Decal in a declarative manner.
244pub struct DecalBuilder {
245    base_builder: BaseBuilder,
246    diffuse_texture: Option<TextureResource>,
247    normal_texture: Option<TextureResource>,
248    color: Color,
249    layer: u8,
250}
251
252impl DecalBuilder {
253    /// Creates a new instance of the builder.
254    pub fn new(base_builder: BaseBuilder) -> Self {
255        Self {
256            base_builder,
257            diffuse_texture: None,
258            normal_texture: None,
259            color: Color::opaque(255, 255, 255),
260            layer: 0,
261        }
262    }
263
264    /// Sets desired diffuse texture.
265    pub fn with_diffuse_texture(mut self, diffuse_texture: TextureResource) -> Self {
266        self.diffuse_texture = Some(diffuse_texture);
267        self
268    }
269
270    /// Sets desired normal texture.
271    pub fn with_normal_texture(mut self, normal_texture: TextureResource) -> Self {
272        self.normal_texture = Some(normal_texture);
273        self
274    }
275
276    /// Sets desired decal color.
277    pub fn with_color(mut self, color: Color) -> Self {
278        self.color = color;
279        self
280    }
281
282    /// Sets desired layer index.
283    pub fn with_layer(mut self, layer: u8) -> Self {
284        self.layer = layer;
285        self
286    }
287
288    /// Creates new Decal node.
289    pub fn build_decal(self) -> Decal {
290        Decal {
291            base: self.base_builder.build_base(),
292            diffuse_texture: self.diffuse_texture.into(),
293            normal_texture: self.normal_texture.into(),
294            color: self.color.into(),
295            layer: self.layer.into(),
296        }
297    }
298
299    /// Creates new Decal node.
300    pub fn build_node(self) -> Node {
301        Node::new(self.build_decal())
302    }
303
304    /// Creates new instance of Decal node and puts it in the given graph.
305    pub fn build(self, graph: &mut Graph) -> Handle<Node> {
306        graph.add_node(self.build_node())
307    }
308}