smolworld / src /js /matrix.js
p3nGu1nZz's picture
✨ Add vector, quaternion, transform, and matrix classes; implement 3D transformations and rendering for square objects
df38526
export class Matrix {
static identity() {
return [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
}
static multiply(a, b) {
const result = new Array(16);
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
let sum = 0;
for (let k = 0; k < 4; k++) {
sum += a[i * 4 + k] * b[k * 4 + j];
}
result[i * 4 + j] = sum;
}
}
return result;
}
static translation(x, y, z) {
return [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
x, y, z, 1
];
}
static scaling(sx, sy, sz) {
return [
sx, 0, 0, 0,
0, sy, 0, 0,
0, 0, sz, 0,
0, 0, 0, 1
];
}
static perspective(fov, aspect, near, far) {
const f = Math.tan(Math.PI * 0.5 - 0.5 * fov);
const rangeInv = 1.0 / (near - far);
return [
f / aspect, 0, 0, 0,
0, f, 0, 0,
0, 0, (near + far) * rangeInv, -1,
0, 0, near * far * rangeInv * 2, 0
];
}
static fromQuaternion(q) {
const x = q.x, y = q.y, z = q.z, w = q.w;
const x2 = x + x, y2 = y + y, z2 = z + z;
const xx = x * x2, xy = x * y2, xz = x * z2;
const yy = y * y2, yz = y * z2, zz = z * z2;
const wx = w * x2, wy = w * y2, wz = w * z2;
return [
1 - (yy + zz), xy - wz, xz + wy, 0,
xy + wz, 1 - (xx + zz), yz - wx, 0,
xz - wy, yz + wx, 1 - (xx + yy), 0,
0, 0, 0, 1
];
}
static transformPoint(matrix, vector) {
const w = matrix[3] * vector.x + matrix[7] * vector.y + matrix[11] * vector.z + matrix[15];
return {
x: (matrix[0] * vector.x + matrix[4] * vector.y + matrix[8] * vector.z + matrix[12]) / w,
y: (matrix[1] * vector.x + matrix[5] * vector.y + matrix[9] * vector.z + matrix[13]) / w,
z: (matrix[2] * vector.x + matrix[6] * vector.y + matrix[10] * vector.z + matrix[14]) / w
};
}
}