engeom 0.5.0

Library for working with geometry with a focus on engineering metrology applications.
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
use crate::common::PCoords;
use crate::geom3::circle3::Circle3;
use crate::geom3::line3::Line3;
use crate::geom3::plane3::Plane3;
use crate::na::Matrix3;
use crate::{Iso3, Point3, Result, SurfacePoint3, UnitVec3, Vector3};
use std::ops;

mod fitting;

/// A sphere in 3D space, defined by a center point and a radius.
///
/// This is one of `engeom`'s 3D geometric primitives.
#[derive(Debug, Clone, PartialEq)]
pub struct Sphere3 {
    pub center: Point3,
    pub radius: f64,
}

impl Sphere3 {
    /// Create a new sphere from a centerpoint and a radius
    ///
    /// # Arguments
    ///
    /// * `center`: a set of coordinates indicating the center of the sphere
    /// * `radius`: the radius of the sphere, expected to be a positive value
    ///
    /// returns: Sphere3
    ///
    /// # Examples
    ///
    /// ```
    ///
    /// ```
    pub fn new(center: &impl PCoords<3>, radius: f64) -> Self {
        let center = Point3::from(center.coords());
        Self { center, radius }
    }

    pub fn r(&self) -> f64 {
        self.radius
    }

    /// Attempts to create the unique sphere that passes through four 3d points. If the points are
    /// coplanar this will return an `Err`
    ///
    /// # Arguments
    ///
    /// * `p0`: a point on the surface of the sphere, distinct and non-coplanar with the others
    /// * `p1`: a point on the surface of the sphere, distinct and non-coplanar with the others
    /// * `p2`: a point on the surface of the sphere, distinct and non-coplanar with the others
    /// * `p3`: a point on the surface of the sphere, distinct and non-coplanar with the others
    ///
    /// returns: Result<Sphere3, Box<dyn Error, Global>>
    ///
    /// # Examples
    ///
    /// ```
    ///
    /// ```
    pub fn from_4_points(
        p0: &impl PCoords<3>,
        p1: &impl PCoords<3>,
        p2: &impl PCoords<3>,
        p3: &impl PCoords<3>,
    ) -> Result<Self> {
        let a = Point3::from(p0.coords());
        let b = Point3::from(p1.coords());
        let c = Point3::from(p2.coords());
        let d = Point3::from(p3.coords());

        // The center is equidistant from all four points. Subtracting the squared-distance
        // equation for `a` from those of `b`, `c`, and `d` cancels the quadratic center terms,
        // leaving a linear system `m * center = rhs`.
        let m = Matrix3::from_rows(&[
            (b - a).transpose(),
            (c - a).transpose(),
            (d - a).transpose(),
        ]);
        let rhs = 0.5
            * Vector3::new(
                b.coords.norm_squared() - a.coords.norm_squared(),
                c.coords.norm_squared() - a.coords.norm_squared(),
                d.coords.norm_squared() - a.coords.norm_squared(),
            );

        let center = m
            .lu()
            .solve(&rhs)
            .map(Point3::from)
            .ok_or("Points are coplanar")?;
        let radius = (center - a).norm();
        Ok(Self::new(&center, radius))
    }

    /// Creates the smallest sphere containing every point in expected O(n) time.
    ///
    /// A single point or identical points produce a zero-radius sphere. Collinear and coplanar
    /// points produce the smallest sphere in their affine subspace. Returns an error for an empty
    /// point set.
    ///
    /// # Arguments
    ///
    /// * `points`: a slice of points to enclose; must not be empty
    ///
    /// returns: Result<Sphere3, Box<dyn Error, Global>>
    ///
    /// # Examples
    ///
    /// ```
    /// use engeom::{Point3, geom3::Sphere3};
    /// use approx::assert_relative_eq;
    ///
    /// // The six vertices of a regular octahedron, plus an interior point
    /// let points = [
    ///     Point3::new(1.0, 0.0, 0.0),
    ///     Point3::new(-1.0, 0.0, 0.0),
    ///     Point3::new(0.0, 1.0, 0.0),
    ///     Point3::new(0.0, -1.0, 0.0),
    ///     Point3::new(0.0, 0.0, 1.0),
    ///     Point3::new(0.0, 0.0, -1.0),
    ///     Point3::new(0.1, 0.2, 0.3),
    /// ];
    ///
    /// let sphere = Sphere3::from_min_enclosing(&points).unwrap();
    /// assert_relative_eq!(sphere.center, Point3::origin(), epsilon = 1e-12);
    /// assert_relative_eq!(sphere.radius, 1.0, epsilon = 1e-12);
    /// ```
    pub fn from_min_enclosing(points: &[impl PCoords<3>]) -> Result<Self> {
        let (center, radius) = crate::common::min_ball::compute_min_ball(points)?;
        Ok(Self { center, radius })
    }

    /// Returns a new sphere transformed by the given isometry, without modifying the original.
    /// Only the translation component affects the sphere (rotation does not change a sphere).
    ///
    /// # Arguments
    ///
    /// * `iso`: an isometry that will be applied to the sphere's center point
    ///
    /// returns: Sphere3
    pub fn transformed_by(&self, iso: &Iso3) -> Self {
        Self::new(&(iso * self.center), self.radius)
    }

    /// Returns the closest point on the sphere's surface to `test_point`, along with the outward
    /// surface normal at that point, or `None` if `test_point` is at the exact center of the
    /// sphere.
    ///
    ///
    /// # Arguments
    ///
    /// * `test_point`: a point in world space to test
    ///
    /// returns: Option<SurfacePoint<3>>
    pub fn closest_point(&self, test_point: &impl PCoords<3>) -> Option<SurfacePoint3> {
        let v = Point3::from(test_point.coords()) - self.center;
        let dist = v.norm();
        if dist < 1e-10 {
            return None;
        }
        let normal = UnitVec3::new_normalize(v);
        let point = self.center + normal.into_inner() * self.radius;
        Some(SurfacePoint3::new(point, normal))
    }

    /// Intersects the sphere with a plane, returning the resulting `Circle3`, or `None` if the
    /// plane does not intersect the sphere.
    ///
    /// # Arguments
    ///
    /// * `plane`: the plane to intersect with
    ///
    /// returns: Option<Circle3>
    pub fn intersect_plane(&self, plane: &Plane3) -> Option<Circle3> {
        let dist = plane.signed_distance_to_point(&self.center);
        if dist.abs() > self.radius {
            return None;
        }
        let circle_radius = (self.radius * self.radius - dist * dist).sqrt();
        let circle_center = self.center - plane.normal.into_inner() * dist;
        Some(Circle3::new(circle_center, plane.normal, circle_radius))
    }

    /// Intersects this sphere with another sphere, returning the resulting `Circle3`, or `None` if
    /// the spheres do not intersect (too far apart, one inside the other, or concentric).
    ///
    /// # Arguments
    ///
    /// * `other`: the other sphere to intersect with
    ///
    /// returns: Option<Circle3>
    pub fn intersect_sphere(&self, other: &Sphere3) -> Option<Circle3> {
        let axis = other.center - self.center;
        let d = axis.norm();
        if d < 1e-10 || d > self.radius + other.radius || d < (self.radius - other.radius).abs() {
            return None;
        }
        let h = (d * d + self.radius * self.radius - other.radius * other.radius) / (2.0 * d);
        let circle_radius = (self.radius * self.radius - h * h).max(0.0).sqrt();
        let normal = UnitVec3::new_normalize(axis);
        let circle_center = self.center + normal.into_inner() * h;
        Some(Circle3::new(circle_center, normal, circle_radius))
    }

    /// Intersects a ray with the sphere, where the ray is expressed as a `Line3` and only
    /// intersections in the forward (positive `direction`) half are considered. Returns the
    /// first such intersection as a surface point with the outward normal, or `None` if the ray
    /// does not intersect.
    pub fn intersect_ray(&self, line: &Line3) -> Option<SurfacePoint3> {
        let roots =
            solve_sphere_quadratic(&line.origin, &line.direction, &self.center, self.radius);
        let t = roots
            .into_iter()
            .filter(|&t| t >= 0.0)
            .fold(f64::MAX, f64::min);
        if t == f64::MAX {
            return None;
        }
        let point = line.at(t);
        let normal = UnitVec3::new_normalize(point - self.center);
        Some(SurfacePoint3::new(point, normal))
    }
}

/// Solve `|origin + t*dir - center|² = r²` for t, returning the real roots.
pub(crate) fn solve_sphere_quadratic(
    origin: &Point3,
    dir: &Vector3,
    center: &Point3,
    r: f64,
) -> Vec<f64> {
    // TODO: should this return a tuple instead of a Vec?, seems wasteful
    let d = origin - center;
    let a = dir.norm_squared();
    let b = 2.0 * d.dot(dir);
    let c = d.norm_squared() - r * r;
    let discriminant = b * b - 4.0 * a * c;
    if discriminant < -1e-10 {
        vec![]
    } else if discriminant.abs() <= 1e-10 {
        vec![-b / (2.0 * a)]
    } else {
        let sq = discriminant.sqrt();
        vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
    }
}

impl ops::Mul<Sphere3> for Iso3 {
    type Output = Sphere3;
    fn mul(self, rhs: Sphere3) -> Sphere3 {
        rhs.transformed_by(&self)
    }
}

impl ops::Mul<&Sphere3> for Iso3 {
    type Output = Sphere3;
    fn mul(self, rhs: &Sphere3) -> Sphere3 {
        rhs.transformed_by(&self)
    }
}

impl ops::Mul<Sphere3> for &Iso3 {
    type Output = Sphere3;
    fn mul(self, rhs: Sphere3) -> Sphere3 {
        rhs.transformed_by(self)
    }
}

impl ops::Mul<&Sphere3> for &Iso3 {
    type Output = Sphere3;
    fn mul(self, rhs: &Sphere3) -> Sphere3 {
        rhs.transformed_by(self)
    }
}

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

    fn unit_sphere() -> Sphere3 {
        Sphere3::new(&Point3::origin(), 1.0)
    }

    fn offset_sphere() -> Sphere3 {
        Sphere3::new(&Point3::new(1.0, 2.0, 3.0), 2.0)
    }

    #[test]
    fn min_enclosing_mixed_boundary_and_interior() {
        // Two antipodal points fix the sphere; everything else is strictly interior
        let points = [
            Point3::new(-2.0, 1.0, 1.0),
            Point3::new(4.0, 1.0, 1.0),
            Point3::new(1.0, 2.0, 1.0),
            Point3::new(1.0, 1.0, 0.0),
            Point3::new(2.0, 1.5, 1.5),
        ];
        let sphere = Sphere3::from_min_enclosing(&points).unwrap();
        assert_relative_eq!(sphere.center, Point3::new(1.0, 1.0, 1.0), epsilon = 1e-12);
        assert_relative_eq!(sphere.radius, 3.0, epsilon = 1e-12);
    }

    #[test]
    fn transform_by_moves_center() {
        let sphere = Sphere3::new(&Point3::origin(), 2.0);
        let iso = Iso3::translation(1.0, 2.0, 3.0);
        let moved = sphere.transformed_by(&iso);
        assert_relative_eq!(moved.center, Point3::new(1.0, 2.0, 3.0), epsilon = 1e-12);
        assert_relative_eq!(moved.r(), 2.0, epsilon = 1e-12);
    }

    #[test]
    fn closest_point_outside_is_on_surface() {
        let sphere = unit_sphere();
        let test = Point3::new(3.0, 0.0, 0.0);
        let sp = sphere.closest_point(&test).unwrap();
        assert_relative_eq!(sp.point, Point3::new(1.0, 0.0, 0.0), epsilon = 1e-12);
        assert_relative_eq!(sp.normal.into_inner(), crate::Vector3::x(), epsilon = 1e-12);
    }

    #[test]
    fn closest_point_inside_is_on_surface() {
        let sphere = unit_sphere();
        let test = Point3::new(0.5, 0.0, 0.0);
        let sp = sphere.closest_point(&test).unwrap();
        // should still project to the surface in the same direction
        assert_relative_eq!(
            (sp.point - sphere.center).norm(),
            sphere.r(),
            epsilon = 1e-12
        );
        assert_relative_eq!(sp.point, Point3::new(1.0, 0.0, 0.0), epsilon = 1e-12);
    }

    #[test]
    fn closest_point_offset_sphere() {
        let sphere = offset_sphere();
        // test point directly above the center along Z
        let test = Point3::new(1.0, 2.0, 10.0);
        let sp = sphere.closest_point(&test).unwrap();
        assert_relative_eq!(sp.point, Point3::new(1.0, 2.0, 5.0), epsilon = 1e-12);
        assert_relative_eq!(sp.normal.into_inner(), crate::Vector3::z(), epsilon = 1e-12);
    }

    #[test]
    fn closest_point_at_center_returns_none() {
        let sphere = unit_sphere();
        assert!(sphere.closest_point(&Point3::origin()).is_none());
    }

    #[test]
    fn plane_through_center_gives_great_circle() {
        let sphere = unit_sphere();
        let plane = Plane3::xy(); // z=0 through origin
        let circle = sphere.intersect_plane(&plane).unwrap();
        assert_relative_eq!(circle.r(), 1.0, epsilon = 1e-12);
        assert_relative_eq!(circle.center, Point3::origin(), epsilon = 1e-12);
        assert_relative_eq!(circle.normal.into_inner(), Vector3::z(), epsilon = 1e-12);
    }

    #[test]
    fn plane_tangent_gives_point_circle() {
        let sphere = unit_sphere();
        // plane z=1 is tangent at the top of the unit sphere
        let plane = Plane3::new(Vector3::z_axis(), 1.0);
        let circle = sphere.intersect_plane(&plane).unwrap();
        assert_relative_eq!(circle.r(), 0.0, epsilon = 1e-12);
        assert_relative_eq!(circle.center, Point3::new(0.0, 0.0, 1.0), epsilon = 1e-12);
    }

    #[test]
    fn plane_misses_sphere_returns_none() {
        let sphere = unit_sphere();
        let plane = Plane3::new(Vector3::z_axis(), 2.0); // z=2, outside sphere
        let result = sphere.intersect_plane(&plane);
        assert!(result.is_none());
    }

    #[test]
    fn plane_intersection_circle_radius_correct() {
        // Sphere radius 5, plane at distance 3 from center → circle radius = sqrt(25-9) = 4
        let sphere = Sphere3::new(&Point3::origin(), 5.0);
        let plane = Plane3::new(Vector3::z_axis(), 3.0);
        let circle = sphere.intersect_plane(&plane).unwrap();
        assert_relative_eq!(circle.r(), 4.0, epsilon = 1e-12);
    }

    #[test]
    fn plane_intersection_circle_center_on_plane() {
        let sphere = offset_sphere(); // center (1,2,3), radius 2
        let plane = Plane3::new(Vector3::z_axis(), 3.0); // z=3 passes through center
        let circle = sphere.intersect_plane(&plane).unwrap();
        // circle center should be the projection of sphere center onto the plane
        assert_relative_eq!(circle.center, Point3::new(1.0, 2.0, 3.0), epsilon = 1e-12);
        assert_relative_eq!(circle.r(), 2.0, epsilon = 1e-12);
    }

    #[test]
    fn plane_intersection_circle_normal_matches_plane() {
        let sphere = unit_sphere();
        let normal = UnitVec3::new_normalize(Vector3::new(1.0, 1.0, 0.0));
        let plane = Plane3::new(normal, 0.0);
        let circle = sphere.intersect_plane(&plane).unwrap();
        assert_relative_eq!(
            circle.normal.into_inner(),
            normal.into_inner(),
            epsilon = 1e-12
        );
    }

    #[test]
    fn two_unit_spheres_adjacent_gives_great_circle() {
        // Two unit spheres with centers 2 apart touch at origin; intersection is a point (r=0)
        // But two unit spheres with centers sqrt(2) apart: h = sqrt(2)/2, circle_r = sqrt(1 - 0.5) = sqrt(0.5)
        let s1 = Sphere3::new(&Point3::new(-1.0, 0.0, 0.0), 1.0);
        let s2 = Sphere3::new(&Point3::new(1.0, 0.0, 0.0), 1.0);
        // d=2 = r1+r2, tangent externally → point circle at origin
        let circle = s1.intersect_sphere(&s2).unwrap();
        assert_relative_eq!(circle.r(), 0.0, epsilon = 1e-12);
        assert_relative_eq!(circle.center, Point3::origin(), epsilon = 1e-12);
    }

    #[test]
    fn equal_spheres_offset_along_x() {
        // Two equal spheres radius 5, centers 6 apart: h = 3, circle_r = sqrt(25-9) = 4
        let s1 = Sphere3::new(&Point3::new(-3.0, 0.0, 0.0), 5.0);
        let s2 = Sphere3::new(&Point3::new(3.0, 0.0, 0.0), 5.0);
        let circle = s1.intersect_sphere(&s2).unwrap();
        assert_relative_eq!(circle.r(), 4.0, epsilon = 1e-12);
        // circle center should be at the midpoint
        assert_relative_eq!(circle.center, Point3::origin(), epsilon = 1e-12);
        // normal should point along X
        assert_relative_eq!(circle.normal.into_inner().x.abs(), 1.0, epsilon = 1e-12);
    }

    #[test]
    fn unequal_spheres_circle_center_correct() {
        // s1 radius 3 at origin, s2 radius 4 at (5,0,0)
        // d=5, h=(25+9-16)/10 = 18/10 = 1.8, circle_r = sqrt(9-3.24) = sqrt(5.76) = 2.4
        let s1 = Sphere3::new(&Point3::origin(), 3.0);
        let s2 = Sphere3::new(&Point3::new(5.0, 0.0, 0.0), 4.0);
        let circle = s1.intersect_sphere(&s2).unwrap();
        assert_relative_eq!(circle.r(), 2.4, epsilon = 1e-10);
        assert_relative_eq!(circle.center, Point3::new(1.8, 0.0, 0.0), epsilon = 1e-10);
    }

    #[test]
    fn spheres_too_far_apart_returns_none() {
        let s1 = Sphere3::new(&Point3::origin(), 1.0);
        let s2 = Sphere3::new(&Point3::new(10.0, 0.0, 0.0), 1.0);
        assert!(s1.intersect_sphere(&s2).is_none());
    }

    #[test]
    fn sphere_inside_other_returns_none() {
        let s1 = Sphere3::new(&Point3::origin(), 5.0);
        let s2 = Sphere3::new(&Point3::new(1.0, 0.0, 0.0), 1.0);
        assert!(s1.intersect_sphere(&s2).is_none());
    }

    #[test]
    fn concentric_spheres_returns_none() {
        let s1 = Sphere3::new(&Point3::origin(), 1.0);
        let s2 = Sphere3::new(&Point3::origin(), 2.0);
        assert!(s1.intersect_sphere(&s2).is_none());
    }

    #[test]
    fn intersection_circle_lies_on_both_spheres() {
        // Verify several points on the circle lie on both sphere surfaces. `Circle3` has no
        // angle-based API, so points are generated here with a test-only parametrization.
        let s1 = Sphere3::new(&Point3::new(0.0, 0.0, 0.0), 5.0);
        let s2 = Sphere3::new(&Point3::new(4.0, 0.0, 0.0), 4.0);
        let circle = s1.intersect_sphere(&s2).unwrap();

        let n = circle.normal.into_inner();
        let reference = if n.z.abs() < 0.9 {
            Vector3::z()
        } else {
            Vector3::x()
        };
        let x_axis = reference.cross(&n).normalize();
        let y_axis = n.cross(&x_axis);

        for t in [0.0_f64, 1.0, 2.0, 3.0, 4.0, 5.0] {
            let pt =
                circle.center + x_axis * (circle.r() * t.cos()) + y_axis * (circle.r() * t.sin());
            assert_relative_eq!((pt - s1.center).norm(), s1.r(), epsilon = 1e-10);
            assert_relative_eq!((pt - s2.center).norm(), s2.r(), epsilon = 1e-10);
        }
    }

    #[test]
    fn ray_hits_front_of_unit_sphere() {
        let sphere = unit_sphere();
        let line = Line3::new(Point3::new(5.0, 0.0, 0.0), (-Vector3::x()).normalize());
        let sp = sphere.intersect_ray(&line).unwrap();
        assert_relative_eq!(sp.point, Point3::new(1.0, 0.0, 0.0), epsilon = 1e-12);
        assert_relative_eq!(sp.normal.into_inner(), Vector3::x(), epsilon = 1e-12);
    }

    #[test]
    fn ray_misses_returns_none() {
        let sphere = unit_sphere();
        let line = Line3::new(Point3::new(5.0, 5.0, 0.0), (-Vector3::x()).normalize());
        assert!(sphere.intersect_ray(&line).is_none());
    }

    #[test]
    fn intersect_ray_point_is_on_surface() {
        let sphere = offset_sphere();
        let origin = Point3::new(10.0, 2.0, 3.0);
        let dir = (sphere.center - origin).normalize();
        let line = Line3::new(origin, dir);
        let sp = sphere.intersect_ray(&line).unwrap();
        let dist = (sp.point - sphere.center).norm();
        assert_relative_eq!(dist, sphere.r(), epsilon = 1e-12);
    }

    #[test]
    fn intersect_ray_normal_points_outward() {
        let sphere = unit_sphere();
        let line = Line3::new(Point3::new(0.0, 5.0, 0.0), (-Vector3::y()).normalize());
        let sp = sphere.intersect_ray(&line).unwrap();
        // normal at the top of the sphere should point in +Y
        assert_relative_eq!(sp.normal.into_inner(), Vector3::y(), epsilon = 1e-12);
    }

    #[test]
    fn from_4_points_matches_known_sphere() {
        let sphere = offset_sphere(); // center (1,2,3), radius 2
        let p0 = sphere.center + Vector3::new(2.0, 0.0, 0.0);
        let p1 = sphere.center + Vector3::new(-2.0, 0.0, 0.0);
        let p2 = sphere.center + Vector3::new(0.0, 2.0, 0.0);
        let p3 = sphere.center + Vector3::new(0.0, 0.0, 2.0);
        let result = Sphere3::from_4_points(&p0, &p1, &p2, &p3).unwrap();
        assert_relative_eq!(result.center, sphere.center, epsilon = 1e-10);
        assert_relative_eq!(result.r(), sphere.r(), epsilon = 1e-10);
    }

    #[test]
    fn from_4_points_general_position() {
        let center = Point3::new(0.3, -1.1, 2.4);
        let radius = 3.7;
        let dirs = [
            Vector3::new(1.0, 0.3, -0.2).normalize(),
            Vector3::new(-0.5, 1.0, 0.1).normalize(),
            Vector3::new(0.2, -0.7, 1.0).normalize(),
            Vector3::new(-1.0, -0.4, -0.6).normalize(),
        ];
        let pts: Vec<Point3> = dirs.iter().map(|d| center + d * radius).collect();
        let result = Sphere3::from_4_points(&pts[0], &pts[1], &pts[2], &pts[3]).unwrap();
        assert_relative_eq!(result.center, center, epsilon = 1e-8);
        assert_relative_eq!(result.r(), radius, epsilon = 1e-8);
    }

    #[test]
    fn from_4_coplanar_points_returns_error() {
        let p0 = Point3::new(0.0, 0.0, 0.0);
        let p1 = Point3::new(1.0, 0.0, 0.0);
        let p2 = Point3::new(0.0, 1.0, 0.0);
        let p3 = Point3::new(1.0, 1.0, 0.0);
        assert!(Sphere3::from_4_points(&p0, &p1, &p2, &p3).is_err());
    }

    #[test]
    fn ray_from_inside_hits_back_surface() {
        let sphere = unit_sphere();
        // Ray starting inside, heading +X, should hit the back (+X side)
        let line = Line3::new(Point3::new(0.0, 0.0, 0.0), Vector3::x());
        let sp = sphere.intersect_ray(&line).unwrap();
        assert_relative_eq!(sp.point, Point3::new(1.0, 0.0, 0.0), epsilon = 1e-12);
    }
}