VoxelEngine/MatrixStuff/Transformations.py

72 lines
2.3 KiB
Python
Raw Permalink Normal View History

2017-08-27 12:51:26 +02:00
import math as math
import numpy as np
2020-07-19 10:41:08 +02:00
def lookAt(eyeX, eyeY, eyeZ, cX, cY, cZ, upX, upY, upZ):
2020-11-08 10:20:23 +01:00
F = np.matrix([eyeX - cX, eyeY -cY, eyeZ - cZ])
2020-07-19 10:41:08 +02:00
UP = np.matrix([upX, upY, upZ])
2017-08-27 12:51:26 +02:00
f = F / math.sqrt(np.sum(np.square(F)))
UP = UP / math.sqrt(np.sum(np.square(UP)))
2020-07-19 10:41:08 +02:00
s = np.cross(f, UP)
u = np.cross((s / math.sqrt(np.sum(np.square(s)))), f)
2017-08-27 12:51:26 +02:00
mat = np.matrix([
2020-07-19 10:41:08 +02:00
[s[0, 0], s[0, 1], s[0, 2], 0],
[u[0, 0], u[0, 1], u[0, 2], 0],
[-f[0, 0], -f[0, 1], -f[0, 2], 0],
[0, 0, 0, 1]
2017-08-27 12:51:26 +02:00
])
return np.transpose(mat)
2020-07-19 10:41:08 +02:00
def orthogonalMatrix(r, l, t, b, f, n):
2017-08-27 12:51:26 +02:00
mat = np.matrix([
2020-07-19 10:41:08 +02:00
[2 / (r - l), 0, 0, -(r + l) / (r - l)],
[0, 2 / (t - b), 0, -(t + b) / (t - b)],
[0, 0, -2 / (f - n), -(f + n) / (f - n)],
[0, 0, 0, 1]
2017-08-27 12:51:26 +02:00
])
return np.transpose(mat)
2020-07-19 10:41:08 +02:00
def perspectiveMatrix(fovy, aspect, znear, zfar):
fovy_rads = fovy * math.pi / 180
f = math.cos(fovy_rads / 2.0) / math.sin(fovy_rads / 2.0)
a = (zfar + znear) / (znear - zfar)
2017-08-27 12:51:26 +02:00
b = (2 * zfar * znear) / (znear - zfar)
2020-07-19 10:41:08 +02:00
mat = np.matrix([[f / aspect, 0, 0, 0],
[0, f, 0, 0],
[0, 0, a, b],
[0, 0, -1, 0]], np.float32)
2017-08-27 12:51:26 +02:00
return np.transpose(mat)
2020-07-19 10:41:08 +02:00
2017-08-27 12:51:26 +02:00
def translate(x, y, z):
mat = np.matrix([[1, 0, 0, x],
[0, 1, 0, y],
[0, 0, 1, z],
[0, 0, 0, 1]], np.float32)
return np.transpose(mat)
2020-07-19 10:41:08 +02:00
def rotate(x, y, z, d4=False):
2017-08-27 12:51:26 +02:00
if not d4:
mat = np.matrix([[1, 0, 0], [0, math.cos(x), -math.sin(x)], [0, math.sin(x), math.cos(x)]], np.float32)
mat = mat * np.matrix([[math.cos(y), 0, -math.sin(y)], [0, 1, 0], [math.sin(y), 0, math.cos(y)]], np.float32)
mat = mat * np.matrix([[math.cos(z), -math.sin(z), 0], [math.sin(z), math.cos(z), 0], [0, 0, 1]], np.float32)
else:
2020-07-19 10:41:08 +02:00
mat = np.matrix(
[[1, 0, 0, 0], [0, math.cos(x), -math.sin(x), 0], [0, math.sin(x), math.cos(x), 0], [0, 0, 0, 1]],
np.float32)
mat = mat * np.matrix(
[[math.cos(y), 0, -math.sin(y), 0], [0, 1, 0, 0], [math.sin(y), 0, math.cos(y), 0], [0, 0, 0, 1]],
np.float32)
mat = mat * np.matrix(
[[math.cos(z), -math.sin(z), 0, 0], [math.sin(z), math.cos(z), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]],
np.float32)
2017-08-27 12:51:26 +02:00
return np.transpose(mat)