ring/mat4.lua

98 lines
1.9 KiB
Lua

--column major!
local love = assert( love )
local math = math
local t = {}
--scale
--rotate
--translate
function t.TRS( x, y, z, a, b, g, dx, dy, dz )
local c, s = math.cos, math.sin
local ca, sa, cb, sb, cg, sg = c(a), s(a), c(b), s(b), c(g), s(g)
return {
{x*ca*cb, y*sa*cb, z*(-sb), 0},
{x*(ca*sb*sg - sa*cg), y*(sa*sb*sg+ca*cg), z*(cb*sg), 0},
{x*(ca*sb*cg+sa*sg), y*(sa*sb*cg-ca*sg), z*cb*cg, 0},
{dx, dy, dz, 1}}
end
--position of camera x y z
--yaw a
--pitch b
function t.view( x, y, z, a, b )
local c, s = math.cos, math.sin
local ca, cb, sa, sb = c(a), c(b), s(a), s(b)
return t.__mul(
{
{1, 0, 0, 0},
{0, cb, sb, 0},
{0,-sb, cb, 0},
{0, 0, 0, 1},
},
t.__mul(
{
{ca, 0,-sa, 0},
{0, 1, 0, 0},
{sa, 0, ca, 0},
{0, 0, 0, 1},
},
{
{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{-x, -y, z, 1}
}))
end
function t.projection(n, f, fov)
local r = love.graphics.getWidth() / 2
local t = love.graphics.getHeight() / 2
local aspect = r/t
local a = 1.0 / math.tan( fov / 2 )
return
{ {a, 0, 0, 0},
{0,-a, 0, 0},
{0, 0, (f+n)/(n-f), -1},
{0, 0, 2*f*n/(n-f), 0},
}
end
function t.transpose( A )
for i = 1, 4 do
for j = 1, 4 do
A[i][j] = A[j][i]
end
end
end
function t.__mul( A, B )
local C = {{},{},{},{}}
for j = 1, 4 do
for i = 1, 4 do
C[j][i] =
A[1][i] * B[j][1] +
A[2][i] * B[j][2] +
A[3][i] * B[j][3] +
A[4][i] * B[j][4]
end
end
return C
end
function t.__add( A, B )
local C = {}
for i = 1, 4 do
for j = 1, 4 do
C[i][j] = A[i][j] + B[i][j]
end
end
return C
end
function t.id()
return {{ 1, 0, 0, 0 },{ 0, 1, 0, 0 },{0, 0, 1, 0},{0, 0, 0, 1}}
end
return t