Files
game/modules/math/matrix44.sx
2026-02-22 13:22:29 +02:00

60 lines
1.6 KiB
Plaintext

#import "math.sx";
Matrix44 :: union {
data: [16]f32;
struct { c0, c1, c2, c3: Vector(4, f32); };
}
mat4_perspective :: (fov: f32, aspect: f32, near: f32, far: f32) -> Matrix44 {
half := fov / 2.0;
f := cos(half) / sin(half);
m : Matrix44 = ---;
m.c0 = .[f / aspect, 0.0, 0.0, 0.0];
m.c1 = .[0.0, f, 0.0, 0.0];
m.c2 = .[0.0, 0.0, (far + near) / (near - far), -1.0];
m.c3 = .[0.0, 0.0, (2.0 * far * near) / (near - far), 0.0];
return m;
}
mat4_translate :: (tx: f32, ty: f32, tz: f32) -> Matrix44 {
m : Matrix44 = ---;
m.c0 = .[1.0, 0.0, 0.0, 0.0];
m.c1 = .[0.0, 1.0, 0.0, 0.0];
m.c2 = .[0.0, 0.0, 1.0, 0.0];
m.c3 = .[tx, ty, tz, 1.0];
return m;
}
mat4_rotate_y :: (angle: f32) -> Matrix44 {
c := cos(angle);
s := sin(angle);
m : Matrix44 = ---;
m.c0 = .[c, 0.0, 0.0 - s, 0.0];
m.c1 = .[0.0, 1.0, 0.0, 0.0];
m.c2 = .[s, 0.0, c, 0.0];
m.c3 = .[0.0, 0.0, 0.0, 1.0];
return m;
}
mat4_rotate_x :: (angle: f32) -> Matrix44 {
c := cos(angle);
s := sin(angle);
m : Matrix44 = ---;
m.c0 = .[1.0, 0.0, 0.0, 0.0];
m.c1 = .[0.0, c, s, 0.0];
m.c2 = .[0.0, 0.0 - s, c, 0.0];
m.c3 = .[0.0, 0.0, 0.0, 1.0];
m;
}
mat4_multiply :: (a: *Matrix44, b: *Matrix44) -> Matrix44 {
out: Matrix44 = ---;
out.c0 = a.c0 * b.c0.x + a.c1 * b.c0.y + a.c2 * b.c0.z + a.c3 * b.c0.w;
out.c1 = a.c0 * b.c1.x + a.c1 * b.c1.y + a.c2 * b.c1.z + a.c3 * b.c1.w;
out.c2 = a.c0 * b.c2.x + a.c1 * b.c2.y + a.c2 * b.c2.z + a.c3 * b.c2.w;
out.c3 = a.c0 * b.c3.x + a.c1 * b.c3.y + a.c2 * b.c3.z + a.c3 * b.c3.w;
return out;
}
multiply :: ufcs mat4_multiply;