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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! A shape type representing circles and ellipses used for drawing.
//!
//! # Examples
//!
//! You can create an [Ellipse] or circle using [`Ellipse::new`] or [`Ellipse::circle`]:
//!
//! ```
//! use pix_engine::prelude::*;
//!
//! let e = Ellipse::new(10, 20, 100, 200);
//! let c = Ellipse::circle(10, 20, 100);
//! ```
//!
//! ...or by using the [ellipse!] [circle!] macros:
//!
//! ```
//! use pix_engine::prelude::*;
//!
//! let e = ellipse!(10, 20, 100, 200);
//! let c = circle!(10, 20, 100);
//!
//! // using a point
//! let e = ellipse!([10, 20], 100, 200);
//! let e = ellipse!(point![10, 20], 100, 200);
//! let c = circle!([10, 20], 100);
//! let c = circle!(point![10, 20], 100);
//! ```

use crate::prelude::*;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// An `Ellipse` positioned at `(x, y)`, with `width` and `height`. A circle is an `Ellipse` where
/// `width` and `height` are equal.
///
/// Please see the [module-level documentation] for examples.
///
/// [module-level documentation]: crate::shape::ellipse
#[derive(Default, Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[repr(transparent)]
#[must_use]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Ellipse<T = i32>(pub(crate) [T; 4]);

/// Constructs an [Ellipse] at position `(x, y)` with `width` and `height`.
///
/// ```
/// # use pix_engine::prelude::*;
/// let p = point!(10, 20);
/// let e = ellipse!(p, 100, 200);
/// assert_eq!(e.x(), 10);
/// assert_eq!(e.y(), 20);
/// assert_eq!(e.width(), 100);
/// assert_eq!(e.height(), 200);
///
/// let e = ellipse!(10, 20, 100, 200);
/// assert_eq!(e.x(), 10);
/// assert_eq!(e.y(), 20);
/// assert_eq!(e.width(), 100);
/// assert_eq!(e.height(), 200);
/// ```
#[macro_export]
macro_rules! ellipse {
    ($p:expr, $r:expr$(,)?) => {
        ellipse!($p, $r, $r)
    };
    ($p:expr, $width:expr, $height:expr$(,)?) => {
        $crate::prelude::Ellipse::with_position($p, $width, $height)
    };
    ($x:expr, $y:expr, $width:expr, $height:expr$(,)?) => {
        $crate::prelude::Ellipse::new($x, $y, $width, $height)
    };
}

/// Constructs a circle [Ellipse] at position `(x, y`) with `radius`.
///
/// ```
/// # use pix_engine::prelude::*;
/// let p = point!(10, 20);
/// let c = circle!(p, 100);
/// assert_eq!(c.x(), 10);
/// assert_eq!(c.y(), 20);
/// assert_eq!(c.radius(), 100);
///
/// let c = circle!(10, 20, 100);
/// assert_eq!(c.x(), 10);
/// assert_eq!(c.y(), 20);
/// assert_eq!(c.radius(), 100);
/// ```
#[macro_export]
macro_rules! circle {
    ($p:expr, $r:expr$(,)?) => {
        $crate::prelude::Ellipse::circle_with_position($p, $r)
    };
    ($x:expr, $y:expr, $r:expr$(,)?) => {
        $crate::prelude::Ellipse::circle($x, $y, $r)
    };
}

impl<T> Ellipse<T> {
    /// Constructs an `Ellipse` at position `(x, y)` with `width` and `height`.
    pub const fn new(x: T, y: T, width: T, height: T) -> Self {
        Self([x, y, width, height])
    }
}

impl<T: Copy> Ellipse<T> {
    /// Returns `Ellipse` values as `[x, y, width, height]`.
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// let e = ellipse!(5, 10, 100, 100);
    /// assert_eq!(e.as_array(), [5, 10, 100, 100]);
    /// ```
    #[inline]
    pub fn as_array(&self) -> [T; 4] {
        self.0
    }

    /// Returns `Ellipse` values as a byte slice `&[x, y, width, height]`.
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// let e = ellipse!(5, 10, 100, 100);
    /// assert_eq!(e.as_bytes(), &[5, 10, 100, 100]);
    /// ```
    #[inline]
    pub fn as_bytes(&self) -> &[T; 4] {
        &self.0
    }

    /// Returns `Ellipse` values as a mutable byte slice `&[x, y, width, height]`.
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// let mut e = ellipse!(5, 10, 100, 100);
    /// for v in e.as_bytes_mut() {
    ///     *v += 5;
    /// }
    /// assert_eq!(e.as_bytes(), &[10, 15, 105, 105]);
    /// ```
    #[inline]
    pub fn as_bytes_mut(&mut self) -> &mut [T; 4] {
        &mut self.0
    }

    /// Returns the `x-coordinate` of the ellipse.
    #[inline]
    pub fn x(&self) -> T {
        self.0[0]
    }

    /// Sets the `x-coordinate` of the ellipse.
    #[inline]
    pub fn set_x(&mut self, x: T) {
        self.0[0] = x;
    }

    /// Returns the `y-coordinate` of the ellipse.
    #[inline]
    pub fn y(&self) -> T {
        self.0[1]
    }

    /// Sets the `y-coordinate` of the ellipse.
    #[inline]
    pub fn set_y(&mut self, y: T) {
        self.0[1] = y;
    }

    /// Returns the `width` of the ellipse.
    #[inline]
    pub fn width(&self) -> T {
        self.0[2]
    }

    /// Sets the `width` of the ellipse.
    #[inline]
    pub fn set_width(&mut self, width: T) {
        self.0[2] = width;
    }

    /// Returns the `height` of the ellipse.
    #[inline]
    pub fn height(&self) -> T {
        self.0[3]
    }

    /// Sets the `height` of the ellipse.
    #[inline]
    pub fn set_height(&mut self, height: T) {
        self.0[3] = height;
    }
}

impl<T: Num> Ellipse<T> {
    /// Constructs a circle `Ellipse` at position `(x, y)` with `radius`.
    pub fn circle(x: T, y: T, radius: T) -> Self {
        let two = T::one() + T::one();
        let diameter = radius * two;
        Self::new(x, y, diameter, diameter)
    }

    /// Constructs an `Ellipse` at position [Point] with `width` and `height`.
    pub fn with_position<P: Into<Point<T, 2>>>(p: P, width: T, height: T) -> Self {
        let p = p.into();
        Self::new(p.x(), p.y(), width, height)
    }

    /// Constructs a circle `Ellipse` at position [Point] with `radius`.
    pub fn circle_with_position<P: Into<Point<T, 2>>>(p: P, radius: T) -> Self {
        let p = p.into();
        Self::circle(p.x(), p.y(), radius)
    }

    /// Constructs an `Ellipse` centered at position `(x, y)` with `width` and `height`.
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// let e = Ellipse::from_center([50, 50], 100, 100);
    /// assert_eq!(e.as_array(), [0, 0, 100, 100]);
    /// ```
    pub fn from_center<P: Into<Point<T, 2>>>(p: P, width: T, height: T) -> Self {
        let p = p.into();
        let two = T::one() + T::one();
        Self::new(p.x() - width / two, p.y() - height / two, width, height)
    }

    /// Constructs a circle `Ellipse` centered at position `(x, y)` with `radius`.
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// let c = Ellipse::circle_from_center([50, 50], 100);
    /// assert_eq!(c.as_array(), [0, 0, 200, 200]);
    /// ```
    pub fn circle_from_center<P: Into<Point<T, 2>>>(p: P, radius: T) -> Self {
        let p = p.into();
        let two = T::one() + T::one();
        Self::circle_with_position(p - radius / two, radius)
    }

    /// Returns the `radius` of the circle.
    ///
    /// # Panics
    ///
    /// Panics if not a circle.
    #[inline]
    pub fn radius(&self) -> T {
        let two = T::one() + T::one();
        self.diameter() / two
    }

    /// Sets the `radius` of the circle.
    #[inline]
    pub fn set_radius(&mut self, radius: T) {
        let two = T::one() + T::one();
        let diameter = radius * two;
        self.0[2] = diameter;
        self.0[3] = diameter;
    }

    /// Returns the `diameter` of the circle.
    ///
    /// # Panics
    ///
    /// Panics if not a circle.
    #[inline]
    pub fn diameter(&self) -> T {
        assert!(self.0[2] == self.0[3], "shape is not a circle");
        self.0[2]
    }

    /// Offsets an ellipse by shifting coordinates by given amount.
    ///
    #[inline]
    pub fn offset<P>(&mut self, offsets: P)
    where
        P: Into<Point<T, 2>>,
    {
        let offsets = offsets.into();
        for (v, o) in self.iter_mut().take(2).zip(offsets) {
            *v += o;
        }
    }

    /// Offsets the `x-coordinate` of the ellipse by a given amount.
    #[inline]
    pub fn offset_x(&mut self, offset: T) {
        self.0[0] += offset;
    }

    /// Offsets the `y-coordinate` of the ellipse by a given amount.
    #[inline]
    pub fn offset_y(&mut self, offset: T) {
        self.0[1] += offset;
    }

    /// Offsets the `width` of the ellipse by a given amount.
    #[inline]
    pub fn offset_width(&mut self, offset: T) {
        self.0[2] += offset;
    }

    /// Offsets the `height` of the ellipse by a given amount.
    #[inline]
    pub fn offset_height(&mut self, offset: T) {
        self.0[3] += offset;
    }

    /// Offsets the `radius` of the circle by a given amount.
    #[inline]
    pub fn offset_radius(&mut self, offset: T) {
        self.0[2] += offset;
        self.0[3] += offset;
    }

    /// Returns the `size` of the ellipse as a `Point`.
    #[inline]
    pub fn size(&self) -> Point<T, 2> {
        point!(self.width(), self.height())
    }

    /// Returns the bounding [Rect] of the ellipse.
    #[inline]
    pub fn bounding_rect(&self) -> Rect<T> {
        rect![self.left(), self.top(), self.width(), self.height()]
    }

    /// Returns `Ellipse` as a [Vec].
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// let e = ellipse!(5, 10, 100, 100);
    /// assert_eq!(e.to_vec(), vec![5, 10, 100, 100]);
    /// ```
    pub fn to_vec(self) -> Vec<T> {
        self.0.to_vec()
    }

    /// Returns the horizontal position of the left edge.
    pub fn left(&self) -> T {
        let two = T::one() + T::one();
        self.x() - self.width() / two
    }

    /// Returns the horizontal position of the right edge.
    pub fn right(&self) -> T {
        let two = T::one() + T::one();
        self.x() + self.width() / two
    }

    /// Returns the horizontal position of the top edge.
    pub fn top(&self) -> T {
        let two = T::one() + T::one();
        self.y() - self.height() / two
    }

    /// Returns the vertical position of the bottom edge.
    pub fn bottom(&self) -> T {
        let two = T::one() + T::one();
        self.y() + self.height() / two
    }

    /// Set the horizontal position of the left edge.
    pub fn set_left(&mut self, left: T) {
        let two = T::one() + T::one();
        self.set_x(left + self.width() / two);
    }

    /// Set the horizontal position of the right edge.
    pub fn set_right(&mut self, right: T) {
        let two = T::one() + T::one();
        self.set_x(right - self.width() / two);
    }

    /// Set the vertical position of the top edge.
    pub fn set_top(&mut self, top: T) {
        let two = T::one() + T::one();
        self.set_y(top + self.height() / two);
    }

    /// Set the vertical position of the bottom edge.
    pub fn set_bottom(&mut self, bottom: T) {
        let two = T::one() + T::one();
        self.set_y(bottom - self.height() / two);
    }

    /// Returns the center position as [Point].
    pub fn center(&self) -> Point<T, 2> {
        point!(self.x(), self.y())
    }

    /// Returns the top-left position as [Point].
    pub fn top_left(&self) -> Point<T, 2> {
        point!(self.left(), self.top())
    }

    /// Returns the top-right position as [Point].
    pub fn top_right(&self) -> Point<T, 2> {
        point!(self.right(), self.top())
    }

    /// Returns the bottom-left position as [Point].
    pub fn bottom_left(&self) -> Point<T, 2> {
        point!(self.left(), self.bottom())
    }

    /// Returns the bottom-right position as [Point].
    pub fn bottom_right(&self) -> Point<T, 2> {
        point!(self.right(), self.bottom())
    }

    /// Set position centered on a [Point].
    pub fn center_on<P: Into<Point<T, 2>>>(&mut self, p: P) {
        let p = p.into();
        self.set_x(p.x());
        self.set_y(p.y());
    }
}

impl<T: Num, const N: usize> Contains<T, N> for Ellipse<T> {
    type Shape = Ellipse<T>;

    /// Returns whether this ellipse contains a given [Point].
    fn contains_point<P>(&self, p: P) -> bool
    where
        P: Into<Point<T, N>>,
    {
        let p = p.into();
        let px = p.x() - self.x();
        let py = p.y() - self.y();
        let two = T::one() + T::one();
        let rx = self.width() / two;
        let ry = self.height() / two;
        (px * px) / (rx * rx) + (py * py) / (ry * ry) <= T::one()
    }

    /// Returns whether this ellipse completely contains another ellipse.
    fn contains_shape<O>(&self, other: O) -> bool
    where
        O: Into<Self::Shape>,
    {
        let other = other.into();
        let px = self.x() - other.x();
        let py = self.y() - other.y();
        let rx = self.width() + other.width();
        let ry = self.height() + other.height();
        (px * px) / (rx * rx) + (py * py) / (ry * ry) <= T::one()
    }
}

impl<T: Num> Intersects<T, 2> for Ellipse<T> {
    type Shape = Ellipse<T>;

    /// Returns the closest intersection point with a given line and distance along the line or
    /// `None` if there is no intersection.
    fn intersects_line<L>(&self, _line: L) -> Option<(Point<T, 2>, T)>
    where
        L: Into<Line<T, 2>>,
    {
        todo!("ellipse intersects_line")
    }

    /// Returns whether this circle intersects with another circle.
    fn intersects_shape<O>(&self, other: O) -> bool
    where
        O: Into<Self::Shape>,
    {
        let other = other.into();
        let px = self.x() - other.x();
        let py = self.y() - other.y();
        if self.width() == self.height() {
            let r = self.width() + other.width();
            (px * px + py * py) <= r * r
        } else {
            todo!("ellipse intersects_shape")
        }
    }
}

impl Draw for Ellipse<i32> {
    /// Draw `Ellipse` to the current [`PixState`] canvas.
    fn draw(&self, s: &mut PixState) -> PixResult<()> {
        s.ellipse(*self)
    }
}

impl<T: Num> From<[T; 3]> for Ellipse<T> {
    /// Converts `[T; 3]` into `Ellipse<T>`.
    #[inline]
    fn from([x, y, r]: [T; 3]) -> Self {
        Self::circle(x, y, r)
    }
}

impl<T: Num> From<&[T; 3]> for Ellipse<T> {
    /// Converts `&[T; 3]` into `Ellipse<T>`.
    #[inline]
    fn from(&[x, y, r]: &[T; 3]) -> Self {
        Self::circle(x, y, r)
    }
}