pxl8/pxl8d/src/math.rs

107 lines
2.1 KiB
Rust
Raw Normal View History

2026-01-25 09:26:30 -06:00
use core::ops::{Add, Mul, Sub};
2026-02-02 17:48:25 -06:00
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
2026-02-02 17:48:25 -06:00
pub struct Vec2 {
pub x: f32,
pub y: f32,
}
2026-01-31 09:31:17 -06:00
2026-02-02 17:48:25 -06:00
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
2026-02-02 17:48:25 -06:00
pub struct Vec3 {
pub x: f32,
pub y: f32,
pub z: f32,
}
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
2026-02-02 17:48:25 -06:00
pub struct Vec4 {
pub x: f32,
pub y: f32,
pub z: f32,
pub w: f32,
}
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
2026-02-02 17:48:25 -06:00
pub struct Mat4 {
pub m: [f32; 16],
}
#[allow(non_camel_case_types)]
pub type pxl8_vec2 = Vec2;
#[allow(non_camel_case_types)]
pub type pxl8_vec3 = Vec3;
#[allow(non_camel_case_types)]
pub type pxl8_vec4 = Vec4;
#[allow(non_camel_case_types)]
pub type pxl8_mat4 = Mat4;
2026-01-25 09:26:30 -06:00
impl Vec3 {
pub const ZERO: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 0.0 };
pub const Y: Vec3 = Vec3 { x: 0.0, y: 1.0, z: 0.0 };
2026-01-31 09:31:17 -06:00
pub fn new(x: f32, y: f32, z: f32) -> Self {
2026-01-25 09:26:30 -06:00
Self { x, y, z }
}
pub fn dot(self, rhs: Self) -> f32 {
2026-01-25 09:26:30 -06:00
self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
}
pub fn cross(self, rhs: Self) -> Self {
Self {
x: self.y * rhs.z - self.z * rhs.y,
y: self.z * rhs.x - self.x * rhs.z,
z: self.x * rhs.y - self.y * rhs.x,
}
}
pub fn length(self) -> f32 {
libm::sqrtf(self.dot(self))
}
pub fn normalize(self) -> Self {
let len_sq = self.dot(self);
if len_sq < 1e-12 {
return Self::ZERO;
}
self * (1.0 / libm::sqrtf(len_sq))
2026-01-31 09:31:17 -06:00
}
}
impl Add for Vec3 {
2026-01-25 09:26:30 -06:00
type Output = Self;
fn add(self, rhs: Self) -> Self {
2026-01-31 09:31:17 -06:00
Self {
x: self.x + rhs.x,
y: self.y + rhs.y,
z: self.z + rhs.z,
}
2026-01-25 09:26:30 -06:00
}
}
impl Sub for Vec3 {
2026-01-25 09:26:30 -06:00
type Output = Self;
fn sub(self, rhs: Self) -> Self {
2026-01-31 09:31:17 -06:00
Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
z: self.z - rhs.z,
}
2026-01-25 09:26:30 -06:00
}
}
impl Mul<f32> for Vec3 {
2026-01-25 09:26:30 -06:00
type Output = Self;
fn mul(self, rhs: f32) -> Self {
2026-01-31 09:31:17 -06:00
Self {
x: self.x * rhs,
y: self.y * rhs,
z: self.z * rhs,
}
2026-01-25 09:26:30 -06:00
}
}