Skip to content

Implement Vector/Angle types as ffi types #55

@Srlion

Description

@Srlion

Implementing Vector/Angle should benefit performance by a lot, hence why lots of people implement one in Lua and then convert to C++ if they do lot's of operations, I'm not sure how it could be done from C++ side,

https://luajit.org/ext_ffi_tutorial.html

local ffi = require("ffi")
local type = type

ffi.cdef [[
typedef struct { float x, y, z; } GMOD_Vector_t;
]]

function isvector(v)
    return ffi.istype("GMOD_Vector_t", v)
end

local Vector
local methods = {}
local mt = {
    __index = function(s, k)
        if type(k) == "number" then
            if k == 1 then
                return s.x
            elseif k == 2 then
                return s.y
            elseif k == 3 then
                return s.z
            end
        end
        return methods[k]
    end,
    __eq = function(a, b)
        if not isvector(b) then return false end
        return a.x == b.x and a.y == b.y and a.z == b.z
    end,
    __add = function(a, b) return Vector(a.x + b.x, a.y + b.y, a.z + b.z) end,
    __sub = function(a, b) return Vector(a.x - b.x, a.y - b.y, a.z - b.z) end,
    __mul = function(a, b) return Vector(a.x * b.x, a.y * b.y, a.z * b.z) end,
    __div = function(a, b) return Vector(a.x / b.x, a.y / b.y, a.z / b.z) end,
    __unm = function(a) return Vector(-a.x, -a.y, -a.z) end,
    __tostring = function(a)
        return string.format("%f %f %f", a.x, a.y, a.z)
    end,
}

function methods:Add(v)
    self.x, self.y, self.z = self.x + v.x, self.y + v.y, self.z + v.z
end

Vector = ffi.metatype("GMOD_Vector_t", mt)

local a = Vector()
print(a)

Adding type checking for most functions would be needed, also would need to make sure that the struct matches the source engine's struct

If user decides to disable ffi, could just add the vector type then disable ffi by not allowing access to it

Metadata

Metadata

Assignees

Labels

LuaJITThis will require changes to LuaJIT itselfcomplexThis issue is quite complex and will take a whilepartially implementedplanned

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions