bevy_firefly 0.18.1-alpha

2d lighting crate for the Bevy game engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Module containing structs and functions relevant to Occluders.

use bevy::{
    camera::visibility::{VisibilityClass, add_visibility_class},
    color::palettes::css::BLACK,
    math::bounding::{Aabb2d, BoundingVolume},
    prelude::*,
    render::{render_resource::ShaderType, sync_world::SyncToRenderWorld},
};
use bytemuck::{NoUninit, Pod, Zeroable};
use core::f32;

use crate::visibility::{OccluderAabb, VisibilityTimer};
use crate::{buffers::BufferIndex, change::Changes};

/// An occluder that blocks light.
///
/// Can be semi-transparent, have a color, any polygonal shape
/// and a few other select shapes (capsule, circle, round_rectangle).
///
/// Can be moved around or rotated by their transform.
///
/// Only z-axis rotations are allowed, any other type of rotation can cause unexpected behavior and bugs.
#[derive(Component, Clone, Reflect, Default)]
#[require(
    SyncToRenderWorld,
    Transform,
    VisibilityClass,
    ViewVisibility,
    VisibilityTimer,
    OccluderAabb,
    Changes
)]
#[component(on_add = add_visibility_class::<Occluder2d>)]
pub struct Occluder2d {
    shape: Occluder2dShape,

    /// Color of the occluder. **Alpha is ignored**.
    pub color: Color,

    /// Opacity of the occluder.
    ///
    /// An occluder of opacity 0 won't block any light.
    /// An occluder of opacity 1 will completely both light (and cast a fully black shadow).
    ///
    /// Anything in-between will cast a colored shadow depending on how opaque it is.
    pub opacity: f32,

    /// If true, this occluder won't cast shadows over sprites with a higher z value.
    ///
    /// This does nothing if z_sorting is set to false in the [config](crate::prelude::FireflyConfig::z_sorting).
    pub z_sorting: bool,

    /// Offset to the position of the occluder.
    ///
    /// **Default**: [Vec3::ZERO].
    pub offset: Vec3,
}

impl Occluder2d {
    /// Get the occluder's **internal shape**.
    pub fn shape(&self) -> &Occluder2dShape {
        &self.shape
    }

    fn from_shape(shape: Occluder2dShape) -> Self {
        Self {
            shape,
            opacity: 1.,
            color: bevy::prelude::Color::Srgba(BLACK),
            z_sorting: true,
            offset: default(),
        }
    }

    /// Construct a new occluder with the specified [color](Occluder2d::color).
    pub fn with_color(&self, color: Color) -> Self {
        let mut res = self.clone();
        res.color = color;
        res
    }

    /// Construct a new occluder with the specified [opacity](Occluder2d::opacity).
    pub fn with_opacity(&self, opacity: f32) -> Self {
        let mut res = self.clone();
        res.opacity = opacity;
        res
    }

    /// Construct a new occluder with the specified [z-sorting](Occluder2d::z_sorting).
    pub fn with_z_sorting(&self, z_sorting: bool) -> Self {
        let mut res = self.clone();
        res.z_sorting = z_sorting;
        res
    }

    /// Construct a new occluder with the specified [offset](Occluder2d::offset).
    pub fn with_offset(&self, offset: Vec3) -> Self {
        let mut res = self.clone();
        res.offset = offset;
        res
    }

    /// Construct a polygonal occluder from the given points.
    ///
    /// The points can form a convex or concave polygon. However,
    /// having self-intersections can cause unexpected behavior.
    ///
    /// The points should be relative to the entity's translation.
    ///
    /// # Failure
    /// This returns None if the provided list doesn't contain at least 2 vertices.
    pub fn polygon(vertices: Vec<Vec2>) -> Option<Self> {
        normalize_vertices(vertices).and_then(|mut vertices| {
            vertices.push(vertices[0]);
            Some(Self::from_shape(Occluder2dShape::Polygon { vertices }))
        })
    }

    /// Construct a polyline occluder from the given points.
    ///
    /// Having self-intersections can cause unexpected behavior.
    ///
    /// The points should be relative to the entity's translation.
    ///
    /// # Failure
    /// This returns None if the provided list doesn't contain at least 2 vertices.
    pub fn polyline(mut vertices: Vec<Vec2>) -> Option<Self> {
        let mut vertices_clone = vertices.clone();
        vertices_clone.reverse();
        vertices.extend_from_slice(&vertices_clone[1..vertices_clone.len()]);

        normalize_vertices(vertices)
            .and_then(|vertices| Some(Self::from_shape(Occluder2dShape::Polyline { vertices })))
    }

    /// Construct a rectangle occluder from width and height.
    pub fn rectangle(width: f32, height: f32) -> Self {
        Self::round_rectangle(width, height, 0.)
    }

    /// Construct a round rectangle occluder from width, height and radius.
    ///
    /// The resulted occluder is esentially a rectangle with a radius-sized padding around it.
    ///  
    /// For instance, a circle is a round rectangle with no height or width, and a capsule
    /// is a round rectangle with only height or only width (and radius).
    pub fn round_rectangle(width: f32, height: f32, radius: f32) -> Self {
        Self::from_shape(Occluder2dShape::RoundRectangle {
            width,
            height,
            radius,
        })
    }

    /// Construct a circle occluder.
    pub fn circle(radius: f32) -> Self {
        Self::round_rectangle(0., 0., radius)
    }

    /// Construct a vertical capsule occluder.
    pub fn vertical_capsule(length: f32, radius: f32) -> Self {
        Self::round_rectangle(0., length, radius)
    }

    /// Construct a horizontal_capsule occluder.
    pub fn horizontal_capsule(length: f32, radius: f32) -> Self {
        Self::round_rectangle(length, 0., radius)
    }

    /// Construct a capsule occluder. This is vertical by default. For a horizontal capsule check [`Occluder2d::horizontal_capsule()`].
    pub fn capsule(length: f32, radius: f32) -> Self {
        Self::vertical_capsule(length, radius)
    }
}

/// Component with data extracted to the Render World from Occluders.
#[derive(Component, Clone)]
#[require(RoundOccluderIndex, PolyOccluderIndex)]
pub struct ExtractedOccluder {
    pub pos: Vec2,
    pub rot: f32,
    pub shape: Occluder2dShape,
    pub aabb: Aabb2d,
    pub z: f32,
    pub color: Color,
    pub opacity: f32,
    pub z_sorting: bool,
    pub changes: Changes,
}

impl PartialEq for ExtractedOccluder {
    fn eq(&self, other: &Self) -> bool {
        self.pos == other.pos && self.rot == other.rot && self.shape == other.shape
    }
}

impl ExtractedOccluder {
    /// Get the occluder's vertices. This will be an empty Vec if the occluder has no vertices.
    pub fn vertices(&self) -> Vec<Vec2> {
        self.shape.vertices(self.pos, Rot2::radians(self.rot))
    }
    /// Get an iterator of the occluder's vertices. This will panic if the occluder has no vertices.
    pub fn vertices_iter<'a>(&'a self) -> Box<dyn 'a + DoubleEndedIterator<Item = Vec2>> {
        self.shape
            .vertices_iter(self.pos, Rot2::radians(self.rot))
            .unwrap()
    }
}

// rotates vertices to be clockwise
fn normalize_vertices(vertices: Vec<Vec2>) -> Option<Vec<Vec2>> {
    if vertices.len() < 2 {
        warn!("Not enough vertices to form shape");
        return None;
    }

    if vertices.len() < 3 {
        return Some(vertices.to_vec());
    }

    let mut orientations: Vec<_> = vertices
        .windows(3)
        .map(|line| orientation(line[0], line[1], line[2]))
        .collect();

    orientations.push(orientation(
        vertices[vertices.len() - 2],
        vertices[vertices.len() - 1],
        vertices[0],
    ));
    orientations.push(orientation(
        vertices[vertices.len() - 1],
        vertices[0],
        vertices[1],
    ));

    if orientations.contains(&Orientation::Left) && orientations.contains(&Orientation::Right) {
        return Some(vertices.to_vec());
    }

    if orientations.contains(&Orientation::Left) {
        return Some(vertices.iter().rev().map(|x| *x).collect());
    }

    Some(vertices.to_vec())
}

#[derive(PartialEq, Eq)]
enum Orientation {
    Touch,
    Left,
    Right,
}

fn orientation(a: Vec2, b: Vec2, p: Vec2) -> Orientation {
    let res = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y);
    if res < 0. {
        return Orientation::Right;
    }
    if res > 0. {
        return Orientation::Left;
    }
    Orientation::Touch
}

pub(crate) fn point_inside_poly(p: Vec2, mut poly: Vec<Vec2>, aabb: Aabb2d) -> bool {
    if !aabb.contains(&Aabb2d { min: p, max: p }) {
        return false;
    }

    poly.push(poly[0]);

    let mut inside = false;

    for line in poly.windows(2) {
        if p.y > line[0].y.min(line[1].y)
            && p.y <= line[0].y.max(line[1].y)
            && p.x <= line[0].x.max(line[1].x)
        {
            let x_intersection =
                (p.y - line[0].y) * (line[1].x - line[0].x) / (line[1].y - line[0].y) + line[0].x;

            if line[0].x == line[1].x || p.x <= x_intersection {
                inside = !inside;
            }
        }
    }
    inside
}

/// Plugin that adds general main-world behavior relating to occluders. This is mainly responsible for
/// change and visibility detection. It is added automatically by the [`FireflyPlugin`](crate::prelude::FireflyPlugin).   
pub struct OccluderPlugin;

impl Plugin for OccluderPlugin {
    fn build(&self, _app: &mut App) {}
}

/// Data that is transferred to the GPU to be read inside shaders.
#[repr(C)]
#[derive(ShaderType, Clone, Copy, Default, NoUninit)]
pub struct UniformOccluder {
    pub vertex_start: u32,
    pub n_vertices: u32,
    pub z: f32,
    pub color: Vec3,
    pub _pad0: f32,
    pub opacity: f32,
    pub z_sorting: u32,
    pub _pad1: [u32; 3],
}

/// Data that is transferred to the GPU to be read inside shaders.
#[repr(C)]
#[derive(ShaderType, Clone, Copy, Default, NoUninit)]
pub struct UniformRoundOccluder {
    pub pos: Vec2,
    pub rot: f32,
    pub width: f32,
    pub height: f32,
    pub radius: f32,
    pub z: f32,
    pub color: Vec3,
    pub _pad0: f32,
    pub opacity: f32,
    pub z_sorting: u32,
    pub _pad1: [u32; 3],
}

#[repr(C)]
#[derive(ShaderType, Clone, Copy, Zeroable, Pod, Default)]
pub(crate) struct UniformVertex {
    pub angle: f32,
    pub pos: Vec2,
}

/// The internal shape of an [`Occluder`](crate::prelude::Occluder2d). This is intended to be generated automatically through
/// the occluder's constructor methods and not added by hand.   
#[derive(Reflect, Clone, Debug, PartialEq)]
pub enum Occluder2dShape {
    Polygon {
        vertices: Vec<Vec2>,
    },
    Polyline {
        vertices: Vec<Vec2>,
    },
    RoundRectangle {
        width: f32,
        height: f32,
        radius: f32,
    },
}

impl Default for Occluder2dShape {
    fn default() -> Self {
        Self::RoundRectangle {
            width: 10.,
            height: 10.,
            radius: 0.,
        }
    }
}

impl Occluder2dShape {
    pub(crate) fn n_vertices(&self) -> u32 {
        match &self {
            Self::Polygon { vertices } => vertices.len() as u32,
            Self::Polyline { vertices } => vertices.len() as u32,
            Self::RoundRectangle { .. } => 0,
        }
    }

    pub(crate) fn vertices(&self, pos: Vec2, rot: Rot2) -> Vec<Vec2> {
        match &self {
            Self::Polygon { vertices, .. } => translate_vertices(vertices.to_vec(), pos, rot),
            Self::Polyline { vertices, .. } => translate_vertices(vertices.to_vec(), pos, rot),
            Self::RoundRectangle { .. } => default(),
        }
    }
    pub(crate) fn vertices_iter<'a>(
        &'a self,
        pos: Vec2,
        rot: Rot2,
    ) -> Option<Box<dyn 'a + DoubleEndedIterator<Item = Vec2>>> {
        match self {
            Self::Polygon { vertices, .. } => Some(translate_vertices_iter(
                Box::new(vertices.iter().map(|v| *v)),
                pos,
                rot,
            )),
            Self::Polyline { vertices, .. } => Some(translate_vertices_iter(
                Box::new(vertices.iter().map(|v| *v)),
                pos,
                rot,
            )),
            Self::RoundRectangle { .. } => None,
        }
    }
}

pub(crate) fn translate_vertices(vertices: Vec<Vec2>, pos: Vec2, rot: Rot2) -> Vec<Vec2> {
    vertices.iter().map(|v| rot * *v + pos).collect()
}

pub(crate) fn translate_vertices_iter<'a>(
    vertices: Box<dyn 'a + DoubleEndedIterator<Item = Vec2>>,
    pos: Vec2,
    rot: Rot2,
) -> Box<dyn 'a + DoubleEndedIterator<Item = Vec2>> {
    Box::new(vertices.map(move |v| rot * v + pos))
}

#[derive(Component, Clone, Copy, Default)]
pub struct RoundOccluderIndex(pub Option<BufferIndex>);

#[derive(Component, Clone, Copy, Default)]
pub struct PolyOccluderIndex {
    pub occluder: Option<BufferIndex>,
    pub vertices: Option<BufferIndex>,
}