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
use delaunator::EPSILON;
use super::Point;

#[derive(PartialEq, Copy, Clone, Debug)]
pub enum BoundingBoxTopBottomEdge {
    Top,
    Bottom,
    None
}

#[derive(PartialEq, Copy, Clone, Debug)]
pub enum BoundingBoxLeftRightEdge {
    Left,
    Right,
    None
}

/// Defines a rectangular bounding box.
#[derive(Debug, Clone)]
pub struct BoundingBox {
    /// The center point of a rectangle.
    center: Point,

    /// The top right point of a rectangle.
    top_right: Point,
}

impl Default for BoundingBox {
    fn default() -> Self {
        Self::new_centered(1.0, 1.0)
    }
}

impl BoundingBox {
    /// Constructs a new bounding box.
    ///
    /// # Arguments
    ///
    /// * `origin` - The position of the center of the bounding box
    /// * `width` - The bounding box's width
    /// * `height` - The bounding box's height
    ///
    pub fn new(origin: Point, width: f64, height: f64) -> Self {
        Self {
            top_right: Point { x: origin.x + width / 2.0, y: origin.y + height / 2.0 },
            center: origin,
        }
    }

    /// Constructs a new bounding box centeterd at origin with the provided width and height.
    pub fn new_centered(width: f64, height: f64) -> Self {
        Self::new(Point { x: 0.0, y: 0.0 }, width, height)
    }

    /// Constructs a new square bounding box centeterd at origin with the provided width.
    pub fn new_centered_square(width: f64) -> Self {
        Self::new_centered(width, width)
    }

    /// Gets the position of the box's center.
    #[inline]
    pub fn center(&self) -> &Point {
        &self.center
    }

    /// Gets the position of the top right corner of the bounding box.
    #[inline]
    pub fn top_right(&self) -> &Point {
        &self.top_right
    }

    /// Getst the width of the bounding box.
    #[inline]
    pub fn width(&self) -> f64 {
        2.0 * (self.top_right.x - self.center.x)
    }

    /// Getst the height of the bounding box.
    #[inline]
    pub fn height(&self) -> f64 {
        2.0 * (self.top_right.y - self.center.y)
    }

    /// Returns whether a given point is inside (or on the edges) of the bounding box.
    #[inline]
    pub fn is_inside(&self, point: &Point) -> bool {
        point.x.abs() <= self.top_right.x && point.y.abs() <= self.top_right.y
    }

    // /// Same as inside, but return false if point is on the box edge.
    // #[inline]
    // pub fn is_exclusively_inside(&self, point: &Point) -> bool {
    //     point.x.abs() < self.top_right.x && point.y.abs() < self.top_right.y
    // }

    /// Returns which edge, if any, the given `point` is located.
    #[inline]
    pub (crate) fn which_edge(&self, point: &Point) -> (BoundingBoxTopBottomEdge, BoundingBoxLeftRightEdge) {
        (
            if point.y == self.top_right.y {
                // top
                BoundingBoxTopBottomEdge::Top
            } else if point.y == -self.top_right.y {
                BoundingBoxTopBottomEdge::Bottom
            } else {
                BoundingBoxTopBottomEdge::None
            },

            if point.x == self.top_right.x {
                // right
                BoundingBoxLeftRightEdge::Right
            } else if point.x == - self.top_right.x {
                // left
                BoundingBoxLeftRightEdge::Left
            } else {
                BoundingBoxLeftRightEdge::None
            }
        )
    }

    /// Intersects a line represented by points 'a' and 'b' and returns the two intersecting points with the box, or None
    pub (crate) fn intersect_line(&self, a: &Point, b: &Point) -> (Option<Point>, Option<Point>) {
        let c_x = b.x - a.x;
        let c_y = b.y - a.y;
        let c = c_y / c_x;
        let d = a.y - (a.x * c);

        let mut f = None;
        let mut g = None;
        let mut h = None;
        let mut i = None;

        // intersection left, right edges
        if c_x.abs() > EPSILON {
            // y = c*x + d
            let right_y = (self.top_right.x * c) + d;
            let left_y = d - (self.top_right.x * c);

            if right_y.abs() <= self.top_right.y {
                f = Some(Point { x: self.top_right.x, y: right_y });
            }

            if left_y.abs() <= self.top_right.y {
                g = Some(Point { x: -self.top_right.x, y: left_y })
            }

            if g.is_some() && f.is_some() {
                // can't have more than 2 intersections, we are done
                return (f, g);
            }
        } // else line is parallel to y, won't intersect with left/right

        // intersection top, bottom edges
        if c_y.abs() > EPSILON {
            if c_x.abs() < EPSILON {
                // line is parallel to y
                if a.x.abs() <= self.top_right.x {
                    // and crosses box
                    return (
                        Some(Point { x: a.x, y: self.top_right.y }),
                        Some(Point { x: a.x, y: -self.top_right.y })
                    );
                } else {
                    // does not cross box
                    return (None, None);
                }
            }

            // x = (y - d) / c
            let top_x = (self.top_right.y - d) / c;
            let bottom_x = -(d + self.top_right.y) / c;

            if top_x.abs() <= self.top_right.x {
                h = Some(Point { x: top_x, y: self.top_right.y })
            }

            if bottom_x.abs() <= self.top_right.x {
                i = Some(Point { x: bottom_x, y: -self.top_right.y })
            }

            if h.is_some() && i.is_some() {
                // can't have more than 2 intersections, we are done
                return (h, i);
            }
        } // else line is parallel to x, won't intersect with top / bottom

        (f.or(g), h.or(i))
    }

    /// Intersects a ray with the bounding box. The first intersection is returned first.
    pub (crate) fn project_ray(&self, point: &Point, direction: &Point) -> (Option<Point>, Option<Point>) {
        let b = Point { x: point.x + direction.x, y: point.y + direction.y };
        let (a, b) = self.intersect_line(point, &b);
        order_points_on_ray(point, direction, a, b)
    }

    /// Same as `project_ray` when you don't care abount the second intersecting point.
    pub (crate) fn project_ray_closest(&self, point: &Point, direction: &Point) -> Option<Point> {
        self.project_ray(point, direction).0
    }
}

/// Given a ray defined by `point` and `direction, and two points on such ray `a` and `b`, returns a tuple (w, z) where point <= w <= z.
/// If either `a` or `b` are smaller than `point`, None is returned.
pub (crate) fn order_points_on_ray(point: &Point, direction: &Point, a: Option<Point>, b: Option<Point>) -> (Option<Point>, Option<Point>) {
    if let Some(va) = a {
        if let Some(vb) = b {
            // point, a and b are just an scalar times direction, so we can compare any non-zero
            // direction component, use the largest
            let (d, da, db) = if direction.x.abs() > direction.y.abs() {
                // use x for comparison
                (direction.x, va.x - point.x, vb.x - point.x)
            } else {
                (direction.y, va.y - point.y, vb.y - point.y)
            };

            if d.signum() == da.signum() {
                // a is reacheable
                if d.signum() == db.signum() {
                    // b is reacheable
                    if da.abs() > db.abs() {
                        // b is closer
                        (Some(vb), Some(va))
                    } else {
                        // a is closer
                        (Some(va), Some(vb))
                    }
                } else {
                    // b will never be reached
                    (Some(va), None)
                }
            } else if d.signum() == db.signum() {
                // a will never be reached
                (Some(vb), None)
            } else {
                // neither will be reached
                (None, None)
            }
        } else if direction.x.signum() == va.x.signum() && direction.y.signum() == va.y.signum() {
            // a is in the right direction
            (Some(va), None)
        } else {
            // a can't be reached
            (None, None)
        }
    } else {
        // no intersection
        (None, None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn line(x: f64, c: f64, d: f64) -> Point {
        Point { x, y: (x * c) + d }
    }
    fn direction(a: &Point, b: &Point) -> Point {
        Point { x: a.x - b.x, y: a.y - b.y }
    }

    fn assert_close_enough(a: Point, b: Option<Point>, message: &str) {
        let b = b.expect(&format!("Expected value, but found None. {}", message));
        let close_enough = 5.0 * EPSILON;
        assert!((a.x - b.x).abs() < close_enough, "a.x [{:?}] and b.x [{:?}] expected to be close enough. Difference was: [{}]. {}", a.x, b.x, (a.x - b.x).abs(), message);
        assert!((a.y - b.y).abs() < close_enough, "a.y [{:?}] and b.y [{:?}] expected to be close enough. Difference was: [{}]. {}", a.y, b.y, (a.y - b.y).abs(), message);
    }

    #[test]
    fn intersect_line_tests() {
        // square centered on origin with edges on x = +-1, y= +-1
        let bbox = BoundingBox::new_centered_square(2.0);

        // line parallel to x, outside box
        let (a, b) = bbox.intersect_line(&Point { x: 5.0, y: 0.0 }, &Point { x: 5.0, y: 1.0 }); // x = 5
        assert_eq!(a, None, "No intersection expected for a parallel line to X outside of the box");
        assert_eq!(b, None, "No intersection expected for a parallel line to X outside of the box");

        // line parallel to y, outside box
        let (a, b) = bbox.intersect_line(&Point { x: 0.0, y: 5.0 }, &Point { x: 1.0, y: 5.0 }); // y = 5
        assert_eq!(a, None, "No intersection expected for a parallel line to Y outside of the box");
        assert_eq!(b, None, "No intersection expected for a parallel line to Y outside of the box");

        // line parallel to x, crossing box
        let (a, b) = bbox.intersect_line(&Point { x: 0.0, y: 0.0 }, &Point { x: 0.0, y: 1.0 }); // x = 0
        assert_eq!(Some(Point { x: 0.0, y: 1.0 }), a, "Expected intersection with top edge");
        assert_eq!(Some(Point { x: 0.0, y: -1.0 }), b, "Expected intersection with bottom edge");

        // line parallel to y, crossing box
        let (a, b) = bbox.intersect_line(&Point { x: 0.0, y: 0.0 }, &Point { x: 1.0, y: 0.0 }); // y = 0
        assert_eq!(Some(Point { x: 1.0, y: 0.0 }), a, "Expected intersection with right edge");
        assert_eq!(Some(Point { x: -1.0, y: 0.0 }), b, "Expected intersection with left edge");

        // line congruent to top edge
        let (a, b) = bbox.intersect_line(&Point { x: 0.0, y: 1.0 }, &Point { x: 1.0, y: 1.0 }); // y = 1
        assert_eq!(Some(Point { x: 1.0, y: 1.0 }), a, "Expected intersection with top right corner");
        assert_eq!(Some(Point { x: -1.0, y: 1.0 }), b, "Expected intersection with top left corner");

        // line congruent to bottom edge
        let (a, b) = bbox.intersect_line(&Point { x: 0.0, y: -1.0 }, &Point { x: 1.0, y: -1.0 }); // y = -1
        assert_eq!(Some(Point { x: 1.0, y: -1.0 }), a, "Expected intersection with bottom right corner");
        assert_eq!(Some(Point { x: -1.0, y: -1.0 }), b, "Expected intersection with bottom left corner");

        // line congruent to right edge
        let (a, b) = bbox.intersect_line(&Point { x: 1.0, y: 0.0 }, &Point { x: 1.0, y: 1.0 }); // x = 1
        assert_eq!(Some(Point { x: 1.0, y: 1.0 }), a, "Expected intersection with top right corner");
        assert_eq!(Some(Point { x: 1.0, y: -1.0 }), b, "Expected intersection with bottom right corner");

        // line congruent to left edge
        let (a, b) = bbox.intersect_line(&Point { x: -1.0, y: 0.0 }, &Point { x: -1.0, y: 1.0 }); // x = -1
        assert_eq!(Some(Point { x: -1.0, y: 1.0 }), a, "Expected intersection with top left corner");
        assert_eq!(Some(Point { x: -1.0, y: -1.0 }), b, "Expected intersection with bottom left corner");

        // 45 degree line from box origin
        let (a, b) = bbox.intersect_line(&Point { x: 0.0, y: 0.0 }, &Point { x: 1.0, y: 1.0 });
        assert_eq!(Some(Point { x: 1.0, y: 1.0 }), a, "Expected intersection with top right corner");
        assert_eq!(Some(Point { x: -1.0, y: -1.0 }), b, "Expected intersection with left bottom corner");

        // -45 degree line from box origin
        let (a, b) = bbox.intersect_line(&Point { x: 0.0, y: 0.0 }, &Point { x: -1.0, y: -1.0 });
        assert_eq!(Some(Point { x: 1.0, y: 1.0 }), a, "Expected intersection with top right corner");
        assert_eq!(Some(Point { x: -1.0, y: -1.0 }), b, "Expected intersection with left bottom corner");

        // -45 degree line translated by (0.5,0.5) - top right ear
        let (a, b) = bbox.intersect_line(&Point { x: 0.5, y: 0.5 }, &Point { x: 0.4, y: 0.6 });
        assert_eq!(Some(Point { x: 1.0, y: 0.0 }), a, "Expected intersection with middle of the right edge");
        assert_eq!(Some(Point { x: 0.0, y: 1.0 }), b, "Expected intersection with middle of the top edge");

        // 45 degree line translated by (-0.5,0.5) - top left ear
        let (a, b) = bbox.intersect_line(&Point { x: -0.5, y: 0.5 }, &Point { x: -0.4, y: 0.6 });
        assert_eq!(Some(Point { x: -1.0, y: 0.0 }), a, "Expected intersection with middle of the left edge");
        assert_eq!(Some(Point { x: 0.0, y: 1.0 }), b, "Expected intersection with middle of the top edge");

        // -45 degree line translated by (-0.5,-0.5) - bottom left ear
        let (a, b) = bbox.intersect_line(&Point { x: -0.5, y: -0.5 }, &Point { x: -0.4, y: -0.6 });
        assert_eq!(Some(Point { x: -1.0, y: 0.0 }), a, "Expected intersection with middle of the left edge");
        assert_eq!(Some(Point { x: 0.0, y: -1.0 }), b, "Expected intersection with middle of the bottom edge");

        // 45 degree line translated by (0.5,-0.5) - bottom right ear
        let (a, b) = bbox.intersect_line(&Point { x: 0.5, y: -0.5 }, &Point { x: 0.4, y: -0.6 });
        assert_eq!(Some(Point { x: 1.0, y: 0.0 }), a, "Expected intersection with middle of the right edge");
        assert_eq!(Some(Point { x: 0.0, y: -1.0 }), b, "Expected intersection with middle of the bottom edge");
    }

    #[test]
    fn project_ray_tests() {
        // square centered on origin with edges on x = +-1, y= +-1
        let bbox = BoundingBox::new_centered_square(2.0);

        // point to the right of right side, directed to origin
        let (a, b) = bbox.project_ray(&Point { x: 2.0, y: 0.0 }, &Point { x: -0.1, y: 0.0 });
        assert_eq!(Some(Point { x: 1.0, y: 0.0 }), a, "Expected to hit right side first");
        assert_eq!(Some(Point { x: -1.0, y: 0.0 }), b, "And then hit the left side");

        // point to the left of right side, inside, directed to origin
        let (a, b) = bbox.project_ray(&Point { x: 0.9, y: 0.0 }, &Point { x: -0.1, y: 0.0 });
        assert_eq!(Some(Point { x: -1.0, y: 0.0 }), a, "Expected to hit left side first");
        assert_eq!(None, b, "and only that");

        // point to the right of left side, inside, directed to origin
        let (a, b) = bbox.project_ray(&Point { x: -0.9, y: 0.0 }, &Point { x: 0.1, y: 0.0 });
        assert_eq!(Some(Point { x: 1.0, y: 0.0 }), a, "Expected to hit right side first");
        assert_eq!(None, b, "and only that");

        // point to the left of left side, directed to origin
        let (a, b) = bbox.project_ray(&Point { x: -2.0, y: 0.0 }, &Point { x: 0.1, y: 0.0 });
        assert_eq!(Some(Point { x: -1.0, y: 0.0 }), a, "Expected to hit left side first");
        assert_eq!(Some(Point { x: 1.0, y: 0.0 }), b, "And then hit the right side");

        // point to the top of top side, directed to origin
        let (a, b) = bbox.project_ray(&Point { x: 0.0, y: 3.0 }, &Point { x: 0.0, y: -10.0 });
        assert_eq!(Some(Point { x: 0.0, y: 1.0 }), a, "Expected to hit top side first");
        assert_eq!(Some(Point { x: 0.0, y: -1.0 }), b, "And then hit the bottom side");

        // point to the bottom of top side, inside, directed to origin
        let (a, b) = bbox.project_ray(&Point { x: 0.0, y: 0.5 }, &Point { x: 0.0, y: -10.0 });
        assert_eq!(Some(Point { x: 0.0, y: -1.0 }), a, "Expected to hit bottom side first");
        assert_eq!(None, b, "and only that");

        // point to the top of bottom side, directed to origin
        let (a, b) = bbox.project_ray(&Point { x: 0.0, y: -0.5 }, &Point { x: 0.0, y: 0.2 });
        assert_eq!(Some(Point { x: 0.0, y: 1.0 }), a, "Expected to hit top side first");
        assert_eq!(None, b, "and only that");

        // point to the right of top side, inside, directed to origin
        let (a, b) = bbox.project_ray(&Point { x: 0.0, y: 0.5 }, &Point { x: 0.0, y: -10.0 });
        assert_eq!(Some(Point { x: 0.0, y: -1.0 }), a, "Expected to hit bottom side first");
        assert_eq!(None, b, "and only that");

        // point to the right, outside box, negatively inclined
        let c = -0.8;
        let d = 1.0;
        let (a, b) = bbox.project_ray(&line(2.0, c, d), &direction(&line(-20.0, c, d), &line(2.0, c, d)));
        assert_close_enough(line(1.0, c, d), a, "Expected to hit left side first");
        assert_close_enough(line(0.0, c, d), b, "And then top side");

        // point to the inside box, negatively inclined
        let (a, b) = bbox.project_ray(&Point { x: -0.5, y: 0.0 }, &Point { x: -1.0, y: 0.8 });
        assert_eq!(Some(Point { x: -1.0, y: 0.4 }), a, "Expected to hit bottom side first");
        assert_eq!(None, b, "No collision");

        // point to the right, outside box, positively inclined
        let (a, b) = bbox.project_ray(&Point { x: -10.0, y: 0.0 }, &Point { x: 1.0, y: 0.8 });
        assert_eq!(None, a, "No collision");
        assert_eq!(None, b, "No collision");
    }
}