#! Contains `plane`, a flat surface without end, and which side of one something #! lies on: what bounds a frustum, a floor or a wall a ray meets, and what splits #! a space in two. import linear; module geometry; #! A plane: the places as far along its normal, a direction of length 1, as #! `distance`. Its front is the side the normal points to. pub struct plane { pub var normal: vec3; pub var distance: f32; } #! Which side of a plane something lies on. pub enum side: u8 { front, #! Wholly where the normal points. back, #! Wholly behind. across, #! On both sides, or touching it. } #! The plane through a place, facing a direction, made of length 1. pub def plane::through(point: vec3, normal: vec3): plane { val n := normal.normalized(); return plane{ n, n.dot(point) }; } #! The plane through three places, facing where they turn counterclockwise, as #! a triangle's front does. pub def plane::of_points(a: vec3, b: vec3, c: vec3): plane { return plane::through(a, (b - a).cross(c - a)); } pub def plane::equals(&this, other: &plane): bool { return this.normal == other.normal && this.distance == other.distance; } #! How far a place is in front of the plane, negative behind it. pub def plane::distance_to(&this, p: vec3): f32 { return dot_of(&this.normal, &p) - this.distance; } #! The plane's place nearest another. pub def plane::closest(&this, p: vec3): vec3 { return p - this.normal * this.distance_to(p); } #! The same plane facing the other way. pub def plane::flipped(&this): plane { return plane{ -this.normal, -this.distance }; } #! Which side of the plane a box lies on: how far its center is in front, #! against how far the box reaches along the normal. pub def plane::side_of(&this, b: bounds): side { val half := b.half_size; return side_at(this.distance_to(b.center), dot_of(&half, &this.normal.abs())); } #! Which side of the plane a sphere lies on. pub def plane::side_of(&this, s: sphere): side { return side_at(this.distance_to(s.center), s.radius); } # The side of what is centered so far in front of a plane, and reaches so far. def side_at(at: f32, reach: f32): side { return side::front if at > reach; return side::back if at < -reach; return side::across; }