Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local matrix = {
- add = function(self, o)
- n = { } for i=1,4 do
- n[i] = {}
- for j=1,4 do
- n[i][j] = self[i][j] + o[i][j]
- end
- end
- return new(n)
- end;
- mul = function(self, o)
- n = { }
- if not o then error("value is nil!") end
- --Scalar multiplication
- if type(o) == "number" then
- for i=1,4 do
- n[i] = {}
- for j=1,4 do
- n[i][j] = self[i][j] * o
- end
- end
- --Matrix multiplication
- elseif type(o) == "table" then
- for i=1,4 do
- n[i] = {}
- for j=1,4 do
- n[i][j] = self[i][1] * o[1][j] +
- self[i][2] * o[2][j] +
- self[i][3] * o[3][j] +
- self[i][4] * o[4][j]
- end
- end
- end
- return new(n)
- end;
- --Transforms vectors by a matrix
- apply = function(self, vertex)
- local x = vertex.x * self[1][1] +
- vertex.y * self[2][1] +
- vertex.z * self[3][1] +
- 1 * self[4][1] --where w == 1 for moves in space
- local y = vertex.x * self[1][2] +
- vertex.y * self[2][2] +
- vertex.z * self[3][2] +
- 1 * self[4][2]
- local z = vertex.x * self[1][3] +
- vertex.y * self[2][3] +
- vertex.z * self[3][3] +
- 1 * self[4][3]
- return vector.new(x,y,z)
- end;
- tostring = function(self)
- str = ""
- for i=1,4 do
- str = str.."[ "
- for j=1,4 do
- str = str..self[i][j].." "
- end
- str = str.."]"
- if i < 4 then str = str.."\n" end
- end
- return str
- end;
- }
- local matmeta = {
- __index = matrix;
- __add = matrix.add;
- __mul = matrix.mul;
- __unm = function(self)
- return self:mul(-1)
- end;
- __tostring = matrix.tostring;
- }
- identity = function()
- n = {
- {1, 0, 0, 0},
- {0, 1, 0, 0},
- {0, 0, 1, 0},
- {0, 0, 0, 1}
- }
- return new(n)
- end
- createTranslation = function(p1,p2,p3)
- x,y,z = 0,p2,p3
- if type(p1) == "table" then
- x = p1.x
- y = p1.y
- z = p1.z
- else x = p1 end
- n = {
- {1, 0, 0, 0},
- {0, 1, 0, 0},
- {0, 0, 1, 0},
- {x, y, z, 1}
- }
- return new(n)
- end
- createScale = function(s)
- n = {
- {s, 0, 0, 0},
- {0, s, 0, 0},
- {0, 0, s, 0},
- {0, 0, 0, 1}
- }
- return new(n)
- end
- --TODO: Trigonometry Lookup Tables
- createRotationX = function(r)
- n = {
- {1, 0, 0, 0},
- {0, math.cos(r), math.sin(r), 0},
- {0,-math.sin(r), math.cos(r), 0},
- {0, 0, 0, 1}
- }
- return new(n)
- end
- createRotationY = function(r)
- n = {
- {math.cos(r), 0,-math.sin(r), 0},
- {0, 1, 0, 0},
- {math.sin(r), 0, math.cos(r), 0},
- {0, 0, 0, 1}
- }
- return new(n)
- end
- createRotationZ = function(r)
- n = {
- { math.cos(r), math.sin(r), 0, 0},
- {-math.sin(r), math.cos(r), 0, 0},
- {0, 0, 1, 0},
- {0, 0, 0, 1}
- }
- return new(n)
- end
- --More an internal function- I think most people will just work
- --with the identity matrix.
- function new(n)
- if not n then
- n = { }
- for i=1,4 do n[i] = {}
- for j=1,4 do n[i][j] = 0 end
- end
- end
- setmetatable(n, matmeta)
- return n
- end
Advertisement
Add Comment
Please, Sign In to add comment