ring/mat4.lua

86 lines
2.0 KiB
Lua

--column major!
local love = assert( love )
local ffi = require('ffi')
local cmat4 = ffi.typeof( [[struct{ float x[4][4]; }]] )
--this is actually the argument we need to send to shader:send
local data = love.data.newByteData( ffi.sizeof( cmat4 ) * 1024 )
print( "size", data:getSize() )
local t = {}
t.__index = t
ffi.metatype( cmat4, t )
function t.__tostring( m )
return ([[
|%05.2f %05.2f %05.2f %05.2f|
|%05.2f %05.2f %05.2f %05.2f|
|%05.2f %05.2f %05.2f %05.2f|
|%05.2f %05.2f %05.2f %05.2f|]]):format(
m.x[0][0], m.x[1][0], m.x[2][0], m.x[3][0],
m.x[0][1], m.x[1][1], m.x[2][1], m.x[3][1],
m.x[0][2], m.x[1][2], m.x[2][2], m.x[3][2],
m.x[0][3], m.x[1][3], m.x[2][3], m.x[3][3])
end
function t.__mul( A, B )
local C = ffi.gc(cmat4(),nil)
for j = 1, 4 do
for i = 1, 4 do
C.x[j][i] =
A.x[1][i] * B.x[j][1] +
A.x[2][i] * B.x[j][2] +
A.x[3][i] * B.x[j][3] +
A.x[4][i] * B.x[j][4]
end
end
return C
end
function t.__add( A, B )
local C = cmat4()
for i = 1, 4 do
for j = 1, 4 do
C[i][j] = A.x[i][j] + B.x[i][j]
end
end
return C
end
function t:rotate( a, b, g )
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 cmat4(
ca*cb, sa*cb, -sb, 0,
ca*sb*sg - sa*cg, sa*sb*sg + ca*cg, cb*sg, 0,
ca*sb*cg + sa*sg, sa*sb*cg - ca*sg, cb*cg, 0,
0, 0, 0, 1
) * self
end
function t:scale( x, y, z )
return cmat4(
x, 0, 0, 0,
0, y, 0, 0,
0, 0, z, 0,
0, 0, 0, 1
) * self
end
function t:translate( x, y, z )
local a = cmat4()
a.x[0][0], a.x[1][1], a.x[2][2], a.x[3][3] = 1, 1, 1, 1
a.x[3][0], a.x[3][1], a.x[3][2] = x, y, z
return a * self
end
do --tests
print( cmat4() ); io.flush()
local a = ffi.gc(cmat4(), nil)
a.x[0][0], a.x[1][1], a.x[2][2],a.x[3][3] = 1,1,1,1
print( a ); io.flush()
print( a:translate( 1, 2, 3 ) );
io.flush()
end
return cmat4