roast2d_internal 0.4.0

Roast2D internal crate
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
//! Geometry utilities for 3D rendering.
//!
//! This module provides:
//! - `DrawMode` - Rendering modes (solid, wireframe, points)
//! - `Billboard` - Camera-facing sprites in 3D space
//! - `AABB` - Axis-aligned bounding boxes for collision
//! - `Ray3D` - Rays for raycasting and picking

use crate::engine::Engine;

use super::mesh::Mesh3D;
use super::vertex::Mesh3DVertex;

/// Draw mode for 3D meshes
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DrawMode {
    /// Filled triangles (default)
    #[default]
    Solid,
    /// Wireframe rendering (lines)
    Wireframe,
    /// Point cloud rendering
    Points,
}

/// Billboard type for 3D sprites that face the camera
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BillboardMode {
    /// Full spherical billboard - always faces camera from any direction
    #[default]
    Spherical,
    /// Cylindrical billboard - only rotates around the Y axis (useful for trees, characters)
    Cylindrical,
}

/// Billboard utility for creating camera-facing quads in 3D space.
///
/// Billboards are 2D planes that always face the camera, useful for:
/// - Sprites in 3D worlds
/// - Particle effects
/// - Text labels
/// - Distant objects (impostors)
#[derive(Debug, Clone, Copy)]
pub struct Billboard {
    /// World position of the billboard center
    pub position: glam::Vec3,
    /// Size of the billboard (width, height)
    pub size: glam::Vec2,
    /// Billboard mode (Spherical or Cylindrical)
    pub mode: BillboardMode,
}

impl Billboard {
    /// Create a new spherical billboard at the given position and size.
    pub fn new(position: glam::Vec3, size: glam::Vec2) -> Self {
        Self {
            position,
            size,
            mode: BillboardMode::Spherical,
        }
    }

    /// Create a cylindrical billboard that only rotates around the Y axis.
    pub fn cylindrical(position: glam::Vec3, size: glam::Vec2) -> Self {
        Self {
            position,
            size,
            mode: BillboardMode::Cylindrical,
        }
    }

    /// Compute the model matrix for this billboard facing the camera.
    ///
    /// # Arguments
    /// * `camera_pos` - World position of the camera
    /// * `camera_up` - Up vector of the camera (usually Vec3::Y)
    pub fn model_matrix(&self, camera_pos: glam::Vec3, camera_up: glam::Vec3) -> glam::Mat4 {
        match self.mode {
            BillboardMode::Spherical => self.spherical_matrix(camera_pos, camera_up),
            BillboardMode::Cylindrical => self.cylindrical_matrix(camera_pos),
        }
    }

    /// Compute a spherical billboard matrix (faces camera from any direction).
    fn spherical_matrix(&self, camera_pos: glam::Vec3, camera_up: glam::Vec3) -> glam::Mat4 {
        // Direction from billboard to camera
        let look = (camera_pos - self.position).normalize_or_zero();

        // Handle degenerate case where billboard is at camera position
        if look == glam::Vec3::ZERO {
            return glam::Mat4::from_scale_rotation_translation(
                glam::Vec3::new(self.size.x, self.size.y, 1.0),
                glam::Quat::IDENTITY,
                self.position,
            );
        }

        // Compute right vector (perpendicular to look and up)
        let right = camera_up.cross(look).normalize_or_zero();

        // Handle degenerate case where look is parallel to up
        let right = if right == glam::Vec3::ZERO {
            glam::Vec3::X
        } else {
            right
        };

        // Recompute up to ensure orthogonality
        let up = look.cross(right);

        // Build rotation matrix from basis vectors
        let rotation = glam::Mat3::from_cols(right, up, look);

        // Combine scale, rotation, and translation
        glam::Mat4::from_scale_rotation_translation(
            glam::Vec3::new(self.size.x, self.size.y, 1.0),
            glam::Quat::from_mat3(&rotation),
            self.position,
        )
    }

    /// Compute a cylindrical billboard matrix (rotates only around Y axis).
    fn cylindrical_matrix(&self, camera_pos: glam::Vec3) -> glam::Mat4 {
        // Project direction onto XZ plane
        let mut look = camera_pos - self.position;
        look.y = 0.0;
        let look = look.normalize_or_zero();

        // Handle degenerate case
        if look == glam::Vec3::ZERO {
            return glam::Mat4::from_scale_rotation_translation(
                glam::Vec3::new(self.size.x, self.size.y, 1.0),
                glam::Quat::IDENTITY,
                self.position,
            );
        }

        // Compute rotation angle around Y axis
        let angle = look.z.atan2(look.x) - std::f32::consts::FRAC_PI_2;

        glam::Mat4::from_scale_rotation_translation(
            glam::Vec3::new(self.size.x, self.size.y, 1.0),
            glam::Quat::from_rotation_y(angle),
            self.position,
        )
    }

    /// Create a quad mesh suitable for billboard rendering.
    /// The quad is centered at origin on the XY plane facing +Z.
    pub fn create_quad(g: &Engine) -> Mesh3D {
        let vertices = vec![
            Mesh3DVertex::new(
                glam::Vec3::new(-0.5, -0.5, 0.0),
                glam::Vec3::Z,
                glam::Vec2::new(0.0, 1.0),
            ),
            Mesh3DVertex::new(
                glam::Vec3::new(0.5, -0.5, 0.0),
                glam::Vec3::Z,
                glam::Vec2::new(1.0, 1.0),
            ),
            Mesh3DVertex::new(
                glam::Vec3::new(0.5, 0.5, 0.0),
                glam::Vec3::Z,
                glam::Vec2::new(1.0, 0.0),
            ),
            Mesh3DVertex::new(
                glam::Vec3::new(-0.5, 0.5, 0.0),
                glam::Vec3::Z,
                glam::Vec2::new(0.0, 0.0),
            ),
        ];
        let indices = vec![0, 1, 2, 2, 3, 0];

        Mesh3D::new(g, &vertices, &indices)
    }
}

/// Axis-Aligned Bounding Box for 3D collision detection.
///
/// An AABB is defined by its minimum and maximum corners, forming a box
/// aligned with the world axes. This makes intersection tests very efficient.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AABB {
    /// Minimum corner (smallest x, y, z values)
    pub min: glam::Vec3,
    /// Maximum corner (largest x, y, z values)
    pub max: glam::Vec3,
}

impl AABB {
    /// Create a new AABB from min and max corners.
    pub fn new(min: glam::Vec3, max: glam::Vec3) -> Self {
        Self { min, max }
    }

    /// Create an AABB centered at a position with given half-extents.
    pub fn from_center_half_extents(center: glam::Vec3, half_extents: glam::Vec3) -> Self {
        Self {
            min: center - half_extents,
            max: center + half_extents,
        }
    }

    /// Create an AABB from a list of points (computes the bounding box).
    pub fn from_points(points: &[glam::Vec3]) -> Option<Self> {
        if points.is_empty() {
            return None;
        }

        let mut min = points[0];
        let mut max = points[0];

        for &point in &points[1..] {
            min = min.min(point);
            max = max.max(point);
        }

        Some(Self { min, max })
    }

    /// Get the center of the AABB.
    pub fn center(&self) -> glam::Vec3 {
        (self.min + self.max) * 0.5
    }

    /// Get the half-extents (half-size) of the AABB.
    pub fn half_extents(&self) -> glam::Vec3 {
        (self.max - self.min) * 0.5
    }

    /// Get the full size of the AABB.
    pub fn size(&self) -> glam::Vec3 {
        self.max - self.min
    }

    /// Check if a point is inside the AABB.
    pub fn contains_point(&self, point: glam::Vec3) -> bool {
        point.x >= self.min.x
            && point.x <= self.max.x
            && point.y >= self.min.y
            && point.y <= self.max.y
            && point.z >= self.min.z
            && point.z <= self.max.z
    }

    /// Check if this AABB intersects another AABB.
    pub fn intersects(&self, other: &AABB) -> bool {
        self.min.x <= other.max.x
            && self.max.x >= other.min.x
            && self.min.y <= other.max.y
            && self.max.y >= other.min.y
            && self.min.z <= other.max.z
            && self.max.z >= other.min.z
    }

    /// Compute the intersection of two AABBs.
    /// Returns None if they don't intersect.
    pub fn intersection(&self, other: &AABB) -> Option<AABB> {
        if !self.intersects(other) {
            return None;
        }

        Some(AABB {
            min: self.min.max(other.min),
            max: self.max.min(other.max),
        })
    }

    /// Merge this AABB with another, returning the bounding box of both.
    pub fn merge(&self, other: &AABB) -> AABB {
        AABB {
            min: self.min.min(other.min),
            max: self.max.max(other.max),
        }
    }

    /// Expand this AABB to include a point.
    pub fn expand_to_include(&mut self, point: glam::Vec3) {
        self.min = self.min.min(point);
        self.max = self.max.max(point);
    }

    /// Get the 8 corners of the AABB.
    pub fn corners(&self) -> [glam::Vec3; 8] {
        [
            glam::Vec3::new(self.min.x, self.min.y, self.min.z),
            glam::Vec3::new(self.max.x, self.min.y, self.min.z),
            glam::Vec3::new(self.min.x, self.max.y, self.min.z),
            glam::Vec3::new(self.max.x, self.max.y, self.min.z),
            glam::Vec3::new(self.min.x, self.min.y, self.max.z),
            glam::Vec3::new(self.max.x, self.min.y, self.max.z),
            glam::Vec3::new(self.min.x, self.max.y, self.max.z),
            glam::Vec3::new(self.max.x, self.max.y, self.max.z),
        ]
    }

    /// Test ray intersection using the slab method.
    /// Returns the distance along the ray to the intersection point, or None if no intersection.
    pub fn ray_intersection(&self, ray: &Ray3D) -> Option<f32> {
        ray.intersect_aabb(self)
    }
}

/// A 3D ray for raycasting operations.
///
/// A ray has an origin point and a direction, extending infinitely in that direction.
/// Useful for picking, visibility tests, and physics simulations.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Ray3D {
    /// Origin point of the ray
    pub origin: glam::Vec3,
    /// Direction of the ray (should be normalized)
    pub direction: glam::Vec3,
}

impl Ray3D {
    /// Create a new ray from origin and direction.
    /// The direction will be normalized.
    pub fn new(origin: glam::Vec3, direction: glam::Vec3) -> Self {
        Self {
            origin,
            direction: direction.normalize_or_zero(),
        }
    }

    /// Create a ray from two points (from origin towards target).
    pub fn from_points(origin: glam::Vec3, target: glam::Vec3) -> Self {
        Self::new(origin, target - origin)
    }

    /// Get a point along the ray at distance t.
    pub fn point_at(&self, t: f32) -> glam::Vec3 {
        self.origin + self.direction * t
    }

    /// Test intersection with an AABB using the slab method.
    /// Returns the distance along the ray to the near intersection point, or None if no intersection.
    pub fn intersect_aabb(&self, aabb: &AABB) -> Option<f32> {
        let inv_dir = glam::Vec3::new(
            if self.direction.x != 0.0 {
                1.0 / self.direction.x
            } else {
                f32::INFINITY
            },
            if self.direction.y != 0.0 {
                1.0 / self.direction.y
            } else {
                f32::INFINITY
            },
            if self.direction.z != 0.0 {
                1.0 / self.direction.z
            } else {
                f32::INFINITY
            },
        );

        let t1 = (aabb.min.x - self.origin.x) * inv_dir.x;
        let t2 = (aabb.max.x - self.origin.x) * inv_dir.x;
        let t3 = (aabb.min.y - self.origin.y) * inv_dir.y;
        let t4 = (aabb.max.y - self.origin.y) * inv_dir.y;
        let t5 = (aabb.min.z - self.origin.z) * inv_dir.z;
        let t6 = (aabb.max.z - self.origin.z) * inv_dir.z;

        let tmin = t1.min(t2).max(t3.min(t4)).max(t5.min(t6));
        let tmax = t1.max(t2).min(t3.max(t4)).min(t5.max(t6));

        // If tmax < 0, ray is intersecting AABB but in the negative direction
        // If tmin > tmax, ray doesn't intersect AABB
        if tmax < 0.0 || tmin > tmax {
            return None;
        }

        // Return the near intersection point (or 0 if we're inside the AABB)
        Some(if tmin < 0.0 { 0.0 } else { tmin })
    }

    /// Test intersection with a sphere.
    /// Returns the distance along the ray to the near intersection point, or None if no intersection.
    pub fn intersect_sphere(&self, center: glam::Vec3, radius: f32) -> Option<f32> {
        let oc = self.origin - center;
        let a = self.direction.dot(self.direction);
        let b = 2.0 * oc.dot(self.direction);
        let c = oc.dot(oc) - radius * radius;
        let discriminant = b * b - 4.0 * a * c;

        if discriminant < 0.0 {
            return None;
        }

        let sqrt_discriminant = discriminant.sqrt();
        let t1 = (-b - sqrt_discriminant) / (2.0 * a);
        let t2 = (-b + sqrt_discriminant) / (2.0 * a);

        if t1 >= 0.0 {
            Some(t1)
        } else if t2 >= 0.0 {
            Some(t2)
        } else {
            None
        }
    }

    /// Test intersection with a plane defined by a point and normal.
    /// Returns the distance along the ray to the intersection point, or None if parallel.
    pub fn intersect_plane(
        &self,
        plane_point: glam::Vec3,
        plane_normal: glam::Vec3,
    ) -> Option<f32> {
        let denom = plane_normal.dot(self.direction);

        // Ray is parallel to the plane
        if denom.abs() < 1e-6 {
            return None;
        }

        let t = (plane_point - self.origin).dot(plane_normal) / denom;

        if t >= 0.0 { Some(t) } else { None }
    }

    /// Create a picking ray from screen coordinates.
    ///
    /// # Arguments
    /// * `screen_pos` - Screen position in pixels (origin at top-left)
    /// * `screen_size` - Size of the screen/window
    /// * `view_proj_inverse` - Inverse of the view-projection matrix
    pub fn from_screen(
        screen_pos: glam::Vec2,
        screen_size: glam::Vec2,
        view_proj_inverse: glam::Mat4,
    ) -> Self {
        // Convert screen coordinates to NDC (-1 to 1)
        let ndc_x = (screen_pos.x / screen_size.x) * 2.0 - 1.0;
        let ndc_y = 1.0 - (screen_pos.y / screen_size.y) * 2.0; // Flip Y

        // Near and far points in NDC
        let near_ndc = glam::Vec4::new(ndc_x, ndc_y, 0.0, 1.0);
        let far_ndc = glam::Vec4::new(ndc_x, ndc_y, 1.0, 1.0);

        // Transform to world space
        let near_world = view_proj_inverse * near_ndc;
        let far_world = view_proj_inverse * far_ndc;

        // Perspective divide
        let near_world = near_world.truncate() / near_world.w;
        let far_world = far_world.truncate() / far_world.w;

        Self::new(near_world, far_world - near_world)
    }
}

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

    // ==================== AABB Tests ====================

    #[test]
    fn test_aabb_new() {
        let aabb = AABB::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 10.0, 10.0));
        assert_eq!(aabb.min, Vec3::ZERO);
        assert_eq!(aabb.max, Vec3::splat(10.0));
    }

    #[test]
    fn test_aabb_from_center_half_extents() {
        let aabb =
            AABB::from_center_half_extents(Vec3::new(5.0, 5.0, 5.0), Vec3::new(5.0, 5.0, 5.0));
        assert_eq!(aabb.min, Vec3::ZERO);
        assert_eq!(aabb.max, Vec3::splat(10.0));
    }

    #[test]
    fn test_aabb_from_points() {
        let points = vec![
            Vec3::new(1.0, 2.0, 3.0),
            Vec3::new(5.0, 1.0, 2.0),
            Vec3::new(2.0, 6.0, 1.0),
        ];
        let aabb = AABB::from_points(&points).unwrap();
        assert_eq!(aabb.min, Vec3::new(1.0, 1.0, 1.0));
        assert_eq!(aabb.max, Vec3::new(5.0, 6.0, 3.0));
    }

    #[test]
    fn test_aabb_from_points_empty() {
        let aabb = AABB::from_points(&[]);
        assert!(aabb.is_none());
    }

    #[test]
    fn test_aabb_from_points_single() {
        let aabb = AABB::from_points(&[Vec3::new(3.0, 4.0, 5.0)]).unwrap();
        assert_eq!(aabb.min, Vec3::new(3.0, 4.0, 5.0));
        assert_eq!(aabb.max, Vec3::new(3.0, 4.0, 5.0));
    }

    #[test]
    fn test_aabb_center() {
        let aabb = AABB::new(Vec3::ZERO, Vec3::splat(10.0));
        assert_eq!(aabb.center(), Vec3::splat(5.0));
    }

    #[test]
    fn test_aabb_half_extents() {
        let aabb = AABB::new(Vec3::ZERO, Vec3::splat(10.0));
        assert_eq!(aabb.half_extents(), Vec3::splat(5.0));
    }

    #[test]
    fn test_aabb_size() {
        let aabb = AABB::new(Vec3::new(1.0, 2.0, 3.0), Vec3::new(4.0, 6.0, 9.0));
        assert_eq!(aabb.size(), Vec3::new(3.0, 4.0, 6.0));
    }

    #[test]
    fn test_aabb_contains_point_inside() {
        let aabb = AABB::new(Vec3::ZERO, Vec3::splat(10.0));
        assert!(aabb.contains_point(Vec3::splat(5.0)));
    }

    #[test]
    fn test_aabb_contains_point_outside() {
        let aabb = AABB::new(Vec3::ZERO, Vec3::splat(10.0));
        assert!(!aabb.contains_point(Vec3::splat(11.0)));
        assert!(!aabb.contains_point(Vec3::new(-1.0, 5.0, 5.0)));
    }

    #[test]
    fn test_aabb_contains_point_boundary() {
        let aabb = AABB::new(Vec3::ZERO, Vec3::splat(10.0));
        assert!(aabb.contains_point(Vec3::ZERO)); // min corner
        assert!(aabb.contains_point(Vec3::splat(10.0))); // max corner
        assert!(aabb.contains_point(Vec3::new(10.0, 0.0, 0.0))); // edge
    }

    #[test]
    fn test_aabb_intersects_overlapping() {
        let a = AABB::new(Vec3::ZERO, Vec3::splat(10.0));
        let b = AABB::new(Vec3::splat(5.0), Vec3::splat(15.0));
        assert!(a.intersects(&b));
        assert!(b.intersects(&a));
    }

    #[test]
    fn test_aabb_intersects_separate() {
        let a = AABB::new(Vec3::ZERO, Vec3::splat(5.0));
        let b = AABB::new(Vec3::splat(10.0), Vec3::splat(15.0));
        assert!(!a.intersects(&b));
        assert!(!b.intersects(&a));
    }

    #[test]
    fn test_aabb_intersects_touching() {
        let a = AABB::new(Vec3::ZERO, Vec3::splat(5.0));
        let b = AABB::new(Vec3::new(5.0, 0.0, 0.0), Vec3::new(10.0, 5.0, 5.0));
        assert!(a.intersects(&b)); // touching at face
    }

    #[test]
    fn test_aabb_intersects_contained() {
        let outer = AABB::new(Vec3::ZERO, Vec3::splat(10.0));
        let inner = AABB::new(Vec3::splat(2.0), Vec3::splat(8.0));
        assert!(outer.intersects(&inner));
        assert!(inner.intersects(&outer));
    }

    #[test]
    fn test_aabb_intersection() {
        let a = AABB::new(Vec3::ZERO, Vec3::splat(10.0));
        let b = AABB::new(Vec3::splat(5.0), Vec3::splat(15.0));
        let intersection = a.intersection(&b).unwrap();
        assert_eq!(intersection.min, Vec3::splat(5.0));
        assert_eq!(intersection.max, Vec3::splat(10.0));
    }

    #[test]
    fn test_aabb_intersection_none() {
        let a = AABB::new(Vec3::ZERO, Vec3::splat(5.0));
        let b = AABB::new(Vec3::splat(10.0), Vec3::splat(15.0));
        assert!(a.intersection(&b).is_none());
    }

    #[test]
    fn test_aabb_merge() {
        let a = AABB::new(Vec3::ZERO, Vec3::splat(5.0));
        let b = AABB::new(Vec3::splat(3.0), Vec3::splat(10.0));
        let merged = a.merge(&b);
        assert_eq!(merged.min, Vec3::ZERO);
        assert_eq!(merged.max, Vec3::splat(10.0));
    }

    #[test]
    fn test_aabb_expand_to_include() {
        let mut aabb = AABB::new(Vec3::ZERO, Vec3::splat(5.0));
        aabb.expand_to_include(Vec3::new(10.0, -2.0, 3.0));
        assert_eq!(aabb.min, Vec3::new(0.0, -2.0, 0.0));
        assert_eq!(aabb.max, Vec3::new(10.0, 5.0, 5.0));
    }

    #[test]
    fn test_aabb_corners() {
        let aabb = AABB::new(Vec3::ZERO, Vec3::ONE);
        let corners = aabb.corners();
        assert_eq!(corners.len(), 8);
        assert!(corners.contains(&Vec3::ZERO));
        assert!(corners.contains(&Vec3::ONE));
        assert!(corners.contains(&Vec3::new(1.0, 0.0, 0.0)));
        assert!(corners.contains(&Vec3::new(0.0, 1.0, 1.0)));
    }

    // ==================== Ray3D Tests ====================

    #[test]
    fn test_ray_new_normalizes_direction() {
        let ray = Ray3D::new(Vec3::ZERO, Vec3::new(10.0, 0.0, 0.0));
        assert!((ray.direction.length() - 1.0).abs() < 1e-6);
        assert_eq!(ray.direction, Vec3::X);
    }

    #[test]
    fn test_ray_from_points() {
        let ray = Ray3D::from_points(Vec3::ZERO, Vec3::new(5.0, 0.0, 0.0));
        assert_eq!(ray.origin, Vec3::ZERO);
        assert!((ray.direction - Vec3::X).length() < 1e-6);
    }

    #[test]
    fn test_ray_point_at() {
        let ray = Ray3D::new(Vec3::ZERO, Vec3::X);
        assert_eq!(ray.point_at(0.0), Vec3::ZERO);
        assert_eq!(ray.point_at(5.0), Vec3::new(5.0, 0.0, 0.0));
        assert_eq!(ray.point_at(-2.0), Vec3::new(-2.0, 0.0, 0.0));
    }

    #[test]
    fn test_ray_intersect_aabb_hit() {
        let aabb = AABB::new(Vec3::splat(5.0), Vec3::splat(10.0));
        let ray = Ray3D::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0));
        let t = ray.intersect_aabb(&aabb);
        assert!(t.is_some());
        let hit_point = ray.point_at(t.unwrap());
        // Hit point should be on or near the AABB surface
        assert!(hit_point.x >= 4.9 && hit_point.x <= 5.1);
    }

    #[test]
    fn test_ray_intersect_aabb_miss() {
        let aabb = AABB::new(Vec3::splat(5.0), Vec3::splat(10.0));
        let ray = Ray3D::new(Vec3::ZERO, Vec3::new(-1.0, 0.0, 0.0)); // pointing away
        assert!(ray.intersect_aabb(&aabb).is_none());
    }

    #[test]
    fn test_ray_intersect_aabb_inside() {
        let aabb = AABB::new(Vec3::ZERO, Vec3::splat(10.0));
        let ray = Ray3D::new(Vec3::splat(5.0), Vec3::X); // origin inside AABB
        let t = ray.intersect_aabb(&aabb);
        assert!(t.is_some());
        assert_eq!(t.unwrap(), 0.0); // should return 0 when inside
    }

    #[test]
    fn test_ray_intersect_sphere_hit() {
        let ray = Ray3D::new(Vec3::ZERO, Vec3::Z);
        let t = ray.intersect_sphere(Vec3::new(0.0, 0.0, 5.0), 1.0);
        assert!(t.is_some());
        // Should hit at z = 4 (sphere surface closest to origin)
        assert!((t.unwrap() - 4.0).abs() < 0.01);
    }

    #[test]
    fn test_ray_intersect_sphere_miss() {
        let ray = Ray3D::new(Vec3::ZERO, Vec3::X);
        let t = ray.intersect_sphere(Vec3::new(0.0, 10.0, 0.0), 1.0); // sphere off to the side
        assert!(t.is_none());
    }

    #[test]
    fn test_ray_intersect_sphere_inside() {
        let ray = Ray3D::new(Vec3::ZERO, Vec3::X);
        let t = ray.intersect_sphere(Vec3::ZERO, 5.0); // ray starts inside sphere
        assert!(t.is_some());
        assert!((t.unwrap() - 5.0).abs() < 0.01); // exits at radius
    }

    #[test]
    fn test_ray_intersect_sphere_behind() {
        let ray = Ray3D::new(Vec3::new(0.0, 0.0, 10.0), Vec3::Z);
        let t = ray.intersect_sphere(Vec3::ZERO, 1.0); // sphere behind ray
        assert!(t.is_none());
    }

    #[test]
    fn test_ray_intersect_plane_hit() {
        let ray = Ray3D::new(Vec3::new(0.0, 5.0, 0.0), Vec3::new(0.0, -1.0, 0.0));
        let t = ray.intersect_plane(Vec3::ZERO, Vec3::Y);
        assert!(t.is_some());
        assert!((t.unwrap() - 5.0).abs() < 0.01);
    }

    #[test]
    fn test_ray_intersect_plane_parallel() {
        let ray = Ray3D::new(Vec3::new(0.0, 5.0, 0.0), Vec3::X); // parallel to XZ plane
        let t = ray.intersect_plane(Vec3::ZERO, Vec3::Y);
        assert!(t.is_none());
    }

    #[test]
    fn test_ray_intersect_plane_behind() {
        let ray = Ray3D::new(Vec3::new(0.0, 5.0, 0.0), Vec3::Y); // pointing away from plane
        let t = ray.intersect_plane(Vec3::ZERO, Vec3::Y);
        assert!(t.is_none());
    }
}