Skip to content

Instantly share code, notes, and snippets.

@DoctorGester
Created November 3, 2018 00:34
Show Gist options
  • Save DoctorGester/9004ce772ff89f4640b71a8f209eddd9 to your computer and use it in GitHub Desktop.
Save DoctorGester/9004ce772ff89f4640b71a8f209eddd9 to your computer and use it in GitHub Desktop.
local ffi = require "ffi"
ffi.cdef [[
typedef struct {
float x;
float y;
} vector;
]]
local storage_size = 8096
local storage = ffi.new("vector[?]", storage_size)
local storage_pointer = 0
function vector(x, y)
local v = storage[storage_pointer]
storage_pointer = storage_pointer + 1
v.x = x or 0
v.y = y or 0
return v
end
function reset_vector_storage()
storage_pointer = 0
end
local vector_meta = {
__add = function(v1, v2)
return vector(v1.x + v2.x, v1.y + v2.y)
end,
__sub = function(v1, v2)
return vector(v1.x - v2.x, v1.y - v2.y)
end,
__mul = function(v1, v2)
if ffi.istype("vector", v1) then
if ffi.istype("vector", v2) then
return vector(v1.x * v2.x, v1.y * v2.y)
else
return vector(v1.x * v2, v1.y * v2)
end
else -- v1 is number
if ffi.istype("vector", v2) then
return vector(v1 * v2.x, v1 * v2.y)
end
end
return vector(v1.x * v2.x, v1.y * v2.y)
end,
__div = function(v1, v2)
if ffi.istype("vector", v1) then
if ffi.istype("vector", v2) then
return vector(v1.x / v2.x, v1.y / v2.y)
else
return vector(v1.x / v2, v1.y / v2)
end
else -- v1 is number
if ffi.istype("vector", v2) then
return vector(v1 / v2.x, v1 / v2.y)
end
end
return vector(v1.x / v2.x, v1.y / v2.y)
end,
__unm = function(v)
return vector(-v.x, -v.y)
end,
__tostring = function(v)
return "(" .. tonumber(v.x) .. "," .. tonumber(v.y) .. ")"
end,
__index = {
persist = function(v)
return ffi.new("vector", v.x, v.y)
end,
set = function(target, source)
target.x = source.x
target.y = source.y
end,
length = function(v)
return math.sqrt(v.x * v.x + v.y * v.y)
end,
unpack = function(v)
return v.x, v.y
end
}
}
ffi.metatype("vector", vector_meta)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment