79 lines
1.7 KiB
Zig
79 lines
1.7 KiB
Zig
|
const math = @import("std").math;
|
||
|
|
||
|
pub const Vec3 = packed struct {
|
||
|
x: f32 = 0.0,
|
||
|
y: f32 = 0.0,
|
||
|
z: f32 = 0.0,
|
||
|
|
||
|
pub fn add(u: Vec3, v: Vec3) Vec3 {
|
||
|
return Vec3{
|
||
|
.x = u.x + v.x,
|
||
|
.y = u.y + v.y,
|
||
|
.z = u.z + v.z,
|
||
|
};
|
||
|
}
|
||
|
|
||
|
pub fn sub(u: Vec3, v: Vec3) Vec3 {
|
||
|
return Vec3{
|
||
|
.x = u.x - v.x,
|
||
|
.y = u.y - v.y,
|
||
|
.z = u.z - v.z,
|
||
|
};
|
||
|
}
|
||
|
|
||
|
pub fn mul(self: Vec3, scalar: f32) Vec3 {
|
||
|
return Vec3{
|
||
|
.x = self.x * scalar,
|
||
|
.y = self.y * scalar,
|
||
|
.z = self.z * scalar,
|
||
|
};
|
||
|
}
|
||
|
|
||
|
pub fn div(self: Vec3, scalar: f32) Vec3 {
|
||
|
return Vec3{
|
||
|
.x = self.x / scalar,
|
||
|
.y = self.y / scalar,
|
||
|
.z = self.z / scalar,
|
||
|
};
|
||
|
}
|
||
|
|
||
|
pub fn length(self: Vec3) f32 {
|
||
|
return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z);
|
||
|
}
|
||
|
|
||
|
pub fn dot(u: Vec3, v: Vec3) f32 {
|
||
|
return u.x * v.x + u.y * v.y + u.z * v.z;
|
||
|
}
|
||
|
|
||
|
pub fn cross(u: Vec3, v: Vec3) Vec3 {
|
||
|
return Vec3{
|
||
|
.x = u.y * v.z - u.z * v.y,
|
||
|
.y = u.z * v.x - u.x * v.z,
|
||
|
.z = u.x * v.y - u.y * v.x,
|
||
|
};
|
||
|
}
|
||
|
|
||
|
// pub fn unit_vector() Vec3 {
|
||
|
// return
|
||
|
// }
|
||
|
};
|
||
|
|
||
|
pub fn unitVector(vec: Vec3) Vec3 {
|
||
|
return vec.div(vec.length());
|
||
|
}
|
||
|
|
||
|
pub const Point3 = Vec3;
|
||
|
pub const Color = Vec3;
|
||
|
|
||
|
const assert = @import("std").debug.assert;
|
||
|
|
||
|
fn assert_cmp(actual: f32, expected: f32) void {
|
||
|
const epsilon: f32 = 1e-5;
|
||
|
assert(math.fabs(actual - expected) < epsilon);
|
||
|
}
|
||
|
|
||
|
test "Vec3.length" {
|
||
|
const v = Vec3{ .x = 1.0, .y = 1.0, .z = 1.0 };
|
||
|
assert_cmp(v.length(), 1.7320508);
|
||
|
}
|