cgar 0.2.0

CGAL-like computational geometry library in Rust
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
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
// SPDX-License-Identifier: MIT
//
// Copyright (c) 2025 Alexandre Severino
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use crate::geometry::point::PointOps;
use crate::geometry::segment::Segment;
use crate::geometry::spatial_element::SpatialElement;
use crate::geometry::util::EPS;
use crate::geometry::vector::VectorOps;
use crate::geometry::{Point2, Point3};
use crate::geometry::{point::Point, vector::Vector};
use crate::numeric::cgar_f64::CgarF64;
use crate::numeric::scalar::{RefInto, Scalar};
use std::ops::{Add, Div, Mul, Sub};

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TrianglePoint {
    Off,
    OnEdge,
    OnVertex,
    In,
}

pub fn are_equal<T: Scalar, const N: usize>(p1: &Point<T, N>, p2: &Point<T, N>) -> bool
where
    for<'a> &'a T: Sub<&'a T, Output = T> + Mul<&'a T, Output = T>,
{
    for i in 0..N {
        if !(&p1.coords[i] - &p2.coords[i]).is_zero() {
            return false;
        }
    }

    return true;
}

pub fn are_approximately_equal<T: Scalar, const N: usize>(
    p1: &Point<T, N>,
    p2: &Point<T, N>,
) -> bool
where
    for<'a> &'a T: Sub<&'a T, Output = T>,
{
    for i in 0..N {
        let diff = &p1.coords[i] - &p2.coords[i];

        // Fast path: try approximation first
        if let Some(diff_f64) = diff.as_f64_fast() {
            if diff_f64.abs() > T::point_merge_threshold().as_f64_fast().unwrap_or(EPS) {
                return false;
            }
        } else {
            // Fallback: use exact comparison only if approximation unavailable
            if !diff.is_zero() {
                return false;
            }
        }
    }
    true
}

pub fn are_collinear<T, const N: usize>(a: &Point<T, N>, b: &Point<T, N>, c: &Point<T, N>) -> bool
where
    T: Scalar,
    for<'a> &'a T: Sub<&'a T, Output = T>
        + Add<&'a T, Output = T>
        + Mul<&'a T, Output = T>
        + Div<&'a T, Output = T>,
{
    for i in 0..N {
        let ui = &b.coords[i] - &a.coords[i];
        let vi = &c.coords[i] - &a.coords[i];

        if ui.abs().is_positive() {
            // first non-zero component gives the candidate scale factor
            let r = &vi / &ui;

            // every remaining coordinate must satisfy vj = r * uj
            for j in (i + 1)..N {
                let uj = &b.coords[j] - &a.coords[j];
                let vj = &c.coords[j] - &a.coords[j];
                if (&vj - &(&uj * &r)).abs().is_positive() {
                    return false; // breaks proportionality
                }
            }
            return true; // all coordinates match
        } else if vi.abs().is_positive() {
            return false; // ui ≈ 0 but vi isn’t ⇒ not collinear
        }
    }
    // all ui ≈ 0  ⇒  A and B coincide; collinear iff C coincides too
    true
}

pub fn triangle_is_degenerate<T: Scalar, const N: usize>(
    a: &Point<T, N>,
    b: &Point<T, N>,
    c: &Point<T, N>,
) -> bool
where
    for<'a> &'a T: Sub<&'a T, Output = T>
        + Mul<&'a T, Output = T>
        + Add<&'a T, Output = T>
        + Div<&'a T, Output = T>,
{
    // Coincidence or collinearity → zero area
    are_equal(a, b) || are_equal(a, c) || are_equal(b, c) || are_collinear(a, b, c)
}

pub fn is_point_on_segment<T, const N: usize>(p: &Point<T, N>, seg: &Segment<T, N>) -> bool
where
    T: Scalar,
    for<'a> &'a T: Sub<&'a T, Output = T>
        + Add<&'a T, Output = T>
        + Mul<&'a T, Output = T>
        + Div<&'a T, Output = T>,
    T: PartialOrd, // needed for comparisons inside the loop
{
    // 1.  If P, A, B are not collinear, P cannot lie on AB
    if !are_collinear(p, &seg.a, &seg.b) {
        return false;
    }

    // 2.  For every coordinate axis, P must lie between A and B
    for i in 0..N {
        let ai = &seg.a.coords[i];
        let bi = &seg.b.coords[i];

        // min_i, max_i bounds
        let (min_i, max_i) = if ai <= bi { (ai, bi) } else { (bi, ai) };

        let pi = &p.coords[i];
        if pi < min_i || pi > max_i {
            return false; // outside on some axis ⇒ not on segment
        }
    }

    true
}

pub fn point_u_on_segment<T: Scalar + PartialOrd, const N: usize>(
    a: &Point<T, N>,
    b: &Point<T, N>,
    p: &Point<T, N>,
) -> Option<T>
where
    Point<T, N>: PointOps<T, N, Vector = crate::geometry::vector::Vector<T, N>>,
    crate::geometry::vector::Vector<T, N>: VectorOps<T, N>,
    for<'a> &'a T: Add<&'a T, Output = T>
        + Sub<&'a T, Output = T>
        + Mul<&'a T, Output = T>
        + Div<&'a T, Output = T>,
{
    // Direction and offset
    let ab = (b - a).as_vector();
    let ap = (p - a).as_vector();

    // Degenerate segment?
    let ab2 = ab.dot(&ab);
    if ab2.is_zero() {
        return if are_equal(a, p) {
            Some(T::zero())
        } else if are_equal(b, p) {
            Some(T::one())
        } else {
            None
        };
    }

    // Must be collinear with AB
    if !are_collinear(a, b, p) {
        return None;
    }

    // Parametric coordinate along AB
    let u = ap.dot(&ab) / ab2;
    if u < T::zero() || u > T::one() {
        None
    } else {
        Some(u)
    }
}

pub fn point_u_on_segment_with_tolerance<T: Scalar + PartialOrd, const N: usize>(
    a: &Point<T, N>,
    b: &Point<T, N>,
    p: &Point<T, N>,
    tolerance: &T,
) -> Option<T>
where
    Point<T, N>: PointOps<T, N, Vector = crate::geometry::vector::Vector<T, N>>,
    crate::geometry::vector::Vector<T, N>: VectorOps<T, N>,
    for<'a> &'a T: Add<&'a T, Output = T>
        + Sub<&'a T, Output = T>
        + Mul<&'a T, Output = T>
        + Div<&'a T, Output = T>,
{
    fn are_approx<TT: Scalar, const NN: usize>(
        p1: &Point<TT, NN>,
        p2: &Point<TT, NN>,
        tolerance: &TT,
    ) -> bool
    where
        for<'a> &'a TT:
            Add<&'a TT, Output = TT> + Sub<&'a TT, Output = TT> + Mul<&'a TT, Output = TT>,
    {
        let tolerance_sq = tolerance * tolerance;
        let mut distance_sq = TT::zero();

        for i in 0..NN {
            let diff = &p1.coords[i] - &p2.coords[i];
            distance_sq = &distance_sq + &(&diff * &diff);
        }

        (distance_sq - tolerance_sq).is_negative_or_zero()
    }

    // Direction and offset
    let ab = (b - a).as_vector();
    let ap = (p - a).as_vector();

    // Degenerate segment?
    let ab2 = ab.dot(&ab);
    if ab2.is_zero() {
        return if are_approx(a, p, tolerance) {
            Some(T::zero())
        } else if are_approx(b, p, tolerance) {
            Some(T::one())
        } else {
            None
        };
    }

    // Parametric coordinate along AB
    let u = ap.dot(&ab) / ab2;

    // Clamp u to [0, 1] range for distance calculation
    let u_clamped = if u < T::zero() {
        T::zero()
    } else if u > T::one() {
        T::one()
    } else {
        u.clone()
    };

    // Calculate closest point on segment
    let closest_point_vector = ab.scale(&u_clamped);
    let closest_point = a + &closest_point_vector.0;

    // Calculate distance from p to closest point on segment
    let distance_vector = (p - &closest_point).as_vector();
    let distance_sq = distance_vector.dot(&distance_vector);
    let tolerance_sq = tolerance * tolerance;

    // Check if point is within tolerance of the segment
    if distance_sq <= tolerance_sq {
        // Return the original u parameter (not clamped) if within tolerance
        Some(u)
    } else {
        None
    }
}

pub fn point_in_or_on_triangle_old<T: Scalar, const N: usize>(
    p: &Point<T, N>,
    a: &Point<T, N>,
    b: &Point<T, N>,
    c: &Point<T, N>,
) -> TrianglePoint
where
    Point<T, N>: PointOps<T, N, Vector = Vector<T, N>>,
    Vector<T, N>: VectorOps<T, N>,
    for<'a> &'a T: Sub<&'a T, Output = T>
        + Mul<&'a T, Output = T>
        + Add<&'a T, Output = T>
        + Div<&'a T, Output = T>,
{
    // Barycentric setup
    let v0 = (c - a).as_vector();
    let v1 = (b - a).as_vector();
    let v2 = (p - a).as_vector();

    let dot00 = v0.dot(&v0);
    let dot01 = v0.dot(&v1);
    let dot02 = v0.dot(&v2);
    let dot11 = v1.dot(&v1);
    let dot12 = v1.dot(&v2);

    let denom = &dot00 * &dot11 - &dot01 * &dot01;

    // Degenerate triangle (zero/near-zero area)
    if denom.abs() < T::tolerance() {
        return TrianglePoint::Off;
    }

    let inv = T::one() / denom;
    let u = &(&dot11 * &dot02 - &dot01 * &dot12) * &inv;
    let v = &(&dot00 * &dot12 - &dot01 * &dot02) * &inv;
    let sum_uv = &u + &v;
    let w = &T::one() - &sum_uv;

    // Classification with tolerance
    let e = T::tolerance();
    let neg_e = e.clone().neg();

    // Outside if any barycentric is below -eps or u+v exceeds 1+eps
    if u < neg_e || v < neg_e || sum_uv > &T::one() + &e {
        return TrianglePoint::Off;
    }

    // On if any barycentric is within eps of the boundary
    // Check if on vertex (distance to vertex is zero)
    if are_equal(p, a) || are_equal(p, b) || are_equal(p, c) {
        return TrianglePoint::OnVertex;
    }

    // Check if on edge (one barycentric coordinate is zero)
    if u.is_zero() || v.is_zero() || w.is_zero() {
        return TrianglePoint::OnEdge;
    }

    TrianglePoint::In
}

#[inline(always)]
pub fn point_in_or_on_triangle<T: Scalar + PartialOrd, const N: usize>(
    p: &Point<T, N>,
    a: &Point<T, N>,
    b: &Point<T, N>,
    c: &Point<T, N>,
) -> TrianglePoint
where
    Point<T, N>: PointOps<T, N, Vector = Vector<T, N>>,
    Vector<T, N>: VectorOps<T, N>,
    for<'a> &'a T: Add<&'a T, Output = T>
        + Sub<&'a T, Output = T>
        + Mul<&'a T, Output = T>
        + Div<&'a T, Output = T>,
{
    #[inline(always)]
    fn near_edge_approx<TS: Scalar>(e0: &TS, e1: &TS, e2: &TS) -> bool {
        let eps = RefInto::<CgarF64>::ref_into(&TS::query_tolerance()).0;
        let e0f = RefInto::<CgarF64>::ref_into(e0).0;
        let e1f = RefInto::<CgarF64>::ref_into(e1).0;
        let e2f = RefInto::<CgarF64>::ref_into(e2).0;
        e0f.abs() <= eps || e1f.abs() <= eps || e2f.abs() <= eps
    }

    #[inline(always)]
    fn classify_from_edges<TS: Scalar + PartialOrd>(e0: &TS, e1: &TS, e2: &TS) -> TrianglePoint {
        let zero = TS::zero();

        // exact zero flags
        let z0 = e0.is_zero();
        let z1 = e1.is_zero();
        let z2 = e2.is_zero();
        let zc = (z0 as u8) + (z1 as u8) + (z2 as u8);

        // mixed signs => strictly outside
        let has_neg = (!z0 && *e0 < zero) || (!z1 && *e1 < zero) || (!z2 && *e2 < zero);
        let has_pos = (!z0 && *e0 > zero) || (!z1 && *e1 > zero) || (!z2 && *e2 > zero);
        if has_neg && has_pos {
            return TrianglePoint::Off;
        }

        // boundary cases
        if zc >= 2 {
            return TrianglePoint::OnVertex; // exactly at a vertex
        }
        if zc == 1 {
            return TrianglePoint::OnEdge; // exactly on a unique edge
        }

        // inside (all nonzero and same sign)
        TrianglePoint::In
    }

    if N == 2 {
        // degenerate?
        let abx = &b[0] - &a[0];
        let aby = &b[1] - &a[1];
        let acx = &c[0] - &a[0];
        let acy = &c[1] - &a[1];
        let area2 = &(&abx * &acy) - &(&aby * &acx);
        if area2.is_zero() {
            return TrianglePoint::Off;
        }

        // edge functions
        let bcx = &c[0] - &b[0];
        let bcy = &c[1] - &b[1];
        let cax = &a[0] - &c[0];
        let cay = &a[1] - &c[1];

        let apx = &p[0] - &a[0];
        let apy = &p[1] - &a[1];
        let bpx = &p[0] - &b[0];
        let bpy = &p[1] - &b[1];
        let cpx = &p[0] - &c[0];
        let cpy = &p[1] - &c[1];

        let e0 = &(&abx * &apy) - &(&aby * &apx);
        let e1 = &(&bcx * &bpy) - &(&bcy * &bpx);
        let e2 = &(&cax * &cpy) - &(&cay * &cpx);

        // near-edge fast path -> confirm exact boundary kind
        if near_edge_approx::<T>(&e0, &e1, &e2) && (e0.is_zero() || e1.is_zero() || e2.is_zero()) {
            // figure out vertex vs edge by zero-count
            let zc = (e0.is_zero() as u8) + (e1.is_zero() as u8) + (e2.is_zero() as u8);
            return if zc >= 2 {
                TrianglePoint::OnVertex
            } else {
                TrianglePoint::OnEdge
            };
        }

        return classify_from_edges(&e0, &e1, &e2);
    } else if N == 3 {
        // normal and degeneracy
        let ab = (b - a).as_vector_3();
        let ac = (c - a).as_vector_3();
        let n = ab.cross(&ac);
        if n[0].is_zero() && n[1].is_zero() && n[2].is_zero() {
            return TrianglePoint::Off;
        }

        // edge functions projected on n
        let ap = (p - a).as_vector_3();
        let bp = (p - b).as_vector_3();
        let cp = (p - c).as_vector_3();
        let bc = (c - b).as_vector_3();
        let ca = (a - c).as_vector_3();

        let e0 = ab.cross(&ap).dot(&n);
        let e1 = bc.cross(&bp).dot(&n);
        let e2 = ca.cross(&cp).dot(&n);

        if near_edge_approx::<T>(&e0, &e1, &e2) && (e0.is_zero() || e1.is_zero() || e2.is_zero()) {
            let zc = (e0.is_zero() as u8) + (e1.is_zero() as u8) + (e2.is_zero() as u8);
            return if zc >= 2 {
                TrianglePoint::OnVertex
            } else {
                TrianglePoint::OnEdge
            };
        }

        return classify_from_edges(&e0, &e1, &e2);
    } else {
        panic!("point_in_or_on_triangle only supports N = 2 or N = 3");
    }
}

#[inline]
pub fn orient2d<T: Scalar>(a: &Point2<T>, b: &Point2<T>, c: &Point2<T>) -> T
where
    for<'a> &'a T: std::ops::Sub<&'a T, Output = T>
        + std::ops::Mul<&'a T, Output = T>
        + std::ops::Add<&'a T, Output = T>
        + std::ops::Div<&'a T, Output = T>
        + std::ops::Neg<Output = T>,
{
    let det = (&b[0] - &a[0]) * (&c[1] - &a[1]) - (&b[1] - &a[1]) * (&c[0] - &a[0]);

    let scale_approx = if let (Some(a0), Some(a1), Some(b0), Some(b1), Some(c0), Some(c1)) = (
        a[0].as_f64_fast(),
        a[1].as_f64_fast(),
        b[0].as_f64_fast(),
        b[1].as_f64_fast(),
        c[0].as_f64_fast(),
        c[1].as_f64_fast(),
    ) {
        (a0.abs() + a1.abs() + b0.abs() + b1.abs() + c0.abs() + c1.abs()) * EPS
    } else {
        EPS // Conservative fallback without exact computation
    };

    if let Some(det_approx) = det.as_f64_fast() {
        if det_approx.abs() <= scale_approx {
            T::zero()
        } else {
            det
        }
    } else {
        det // Can't determine with approximation, return raw determinant
    }
}

#[inline]
pub fn incircle<T: Scalar>(a: &Point2<T>, b: &Point2<T>, c: &Point2<T>, d: &Point2<T>) -> T
where
    for<'a> &'a T: std::ops::Sub<&'a T, Output = T>
        + std::ops::Mul<&'a T, Output = T>
        + std::ops::Add<&'a T, Output = T>
        + std::ops::Div<&'a T, Output = T>
        + std::ops::Neg<Output = T>,
{
    // Compute with standard determinant expansion; apply light scaling guard.
    // (Assumes abc CCW. If not, caller should flip sign or reorder.)
    let ax = &a[0] - &d[0];
    let ay = &a[1] - &d[1];
    let a2 = &ax * &ax + &ay * &ay;
    let bx = &b[0] - &d[0];
    let by = &b[1] - &d[1];
    let b2 = &bx * &bx + &by * &by;
    let cx = &c[0] - &d[0];
    let cy = &c[1] - &d[1];
    let c2 = &cx * &cx + &cy * &cy;

    let det = &ax * &(&(&by * &c2) - &(&b2 * &cy)) - &ay * &(&(&bx * &c2) - &(&b2 * &cx))
        + &a2 * &(&(&bx * &cy) - &(&by * &cx));

    let scale =
        (&ax.abs() + &ay.abs() + bx.abs() + by.abs() + cx.abs() + cy.abs()).max(T::from(1.0));
    let eps = &scale * &scale * T::from(EPS);
    if (&det.abs() - &eps).is_negative_or_zero() {
        T::zero()
    } else {
        det
    }
}

#[inline]
pub fn bbox2d<T: Scalar>(pts: &[Point2<T>]) -> (Point2<T>, Point2<T>)
where
    for<'a> &'a T: std::ops::Sub<&'a T, Output = T>
        + std::ops::Mul<&'a T, Output = T>
        + std::ops::Add<&'a T, Output = T>
        + std::ops::Div<&'a T, Output = T>
        + std::ops::Neg<Output = T>,
{
    let mut minx = &pts[0][0];
    let mut miny = &pts[0][1];
    let mut maxx = &pts[0][0];
    let mut maxy = &pts[0][1];
    for p in &pts[1..] {
        if (&p[0] - &minx).is_negative() {
            minx = &p[0];
        }
        if (&p[1] - &miny).is_negative() {
            miny = &p[1];
        }
        if (&p[0] - &maxx).is_positive() {
            maxx = &p[0];
        }
        if (&p[1] - maxy).is_positive() {
            maxy = &p[1];
        }
    }
    (
        Point2::<T>::from_vals([minx.clone(), miny.clone()]),
        Point2::<T>::from_vals([maxx.clone(), maxy.clone()]),
    )
}

#[inline]
pub fn bbox_approx2d<T: Scalar>(pts: &[Point2<T>]) -> (Point2<T>, Point2<T>) {
    let mut minx = pts[0][0].ball_center_f64();
    let mut miny = pts[0][1].ball_center_f64();
    let mut maxx = minx;
    let mut maxy = miny;

    for p in &pts[1..] {
        let px = p[0].ball_center_f64();
        let py = p[1].ball_center_f64();

        if px < minx {
            minx = px;
        }
        if py < miny {
            miny = py;
        }
        if px > maxx {
            maxx = px;
        }
        if py > maxy {
            maxy = py;
        }
    }

    (
        Point2::<T>::from_vals([minx.clone(), miny.clone()]),
        Point2::<T>::from_vals([maxx.clone(), maxy.clone()]),
    )
}

#[inline]
pub fn bbox3d<T: Scalar>(pts: &[Point3<T>]) -> (Point3<T>, Point3<T>)
where
    for<'a> &'a T: std::ops::Sub<&'a T, Output = T>
        + std::ops::Mul<&'a T, Output = T>
        + std::ops::Add<&'a T, Output = T>
        + std::ops::Div<&'a T, Output = T>
        + std::ops::Neg<Output = T>,
{
    let mut minx = &pts[0][0];
    let mut miny = &pts[0][1];
    let mut minz = &pts[0][2];
    let mut maxx = &pts[0][0];
    let mut maxy = &pts[0][1];
    let mut maxz = &pts[0][2];
    for p in &pts[1..] {
        if (&p[0] - &minx).is_negative() {
            minx = &p[0];
        }
        if (&p[1] - &miny).is_negative() {
            miny = &p[1];
        }
        if (&p[2] - &minz).is_negative() {
            minz = &p[2];
        }
        if (&p[0] - &maxx).is_positive() {
            maxx = &p[0];
        }
        if (&p[1] - maxy).is_positive() {
            maxy = &p[1];
        }
        if (&p[2] - &maxz).is_positive() {
            maxz = &p[2];
        }
    }
    (
        Point3::<T>::from_vals([minx.clone(), miny.clone(), minz.clone()]),
        Point3::<T>::from_vals([maxx.clone(), maxy.clone(), maxz.clone()]),
    )
}

#[inline]
pub fn bbox_approx3d<T: Scalar>(pts: &[Point3<T>]) -> (Point3<T>, Point3<T>) {
    let mut minx = pts[0][0].ball_center_f64();
    let mut miny = pts[0][1].ball_center_f64();
    let mut minz = pts[0][2].ball_center_f64();
    let mut maxx = minx;
    let mut maxy = miny;
    let mut maxz = minz;

    for p in &pts[1..] {
        let px = p[0].ball_center_f64();
        let py = p[1].ball_center_f64();
        let pz = p[2].ball_center_f64();
        if px < minx {
            minx = px;
        }
        if py < miny {
            miny = py;
        }
        if pz < minz {
            minz = pz;
        }
        if px > maxx {
            maxx = px;
        }
        if py > maxy {
            maxy = py;
        }
        if pz > maxz {
            maxz = pz;
        }
    }

    (
        Point3::<T>::from_vals([minx.clone(), miny.clone(), minz.clone()]),
        Point3::<T>::from_vals([maxx.clone(), maxy.clone(), maxz.clone()]),
    )
}

#[inline]
pub fn centroid2<T: Scalar>(a: &Point2<T>, b: &Point2<T>) -> Point2<T>
where
    for<'a> &'a T: std::ops::Sub<&'a T, Output = T>
        + std::ops::Mul<&'a T, Output = T>
        + std::ops::Add<&'a T, Output = T>
        + std::ops::Div<&'a T, Output = T>
        + std::ops::Neg<Output = T>,
{
    Point::<T, 2>::from_vals([
        T::from_num_den(1, 2) * (&a[0] + &b[0]),
        T::from_num_den(1, 2) * (&a[1] + &b[1]),
    ])
}