Some checks failed
release / linux/x86_64 (pull_request) Failing after 1m54s
release / freebsd/x86_64 (pull_request) Successful in 5m1s
release / linux/aarch64 (pull_request) Failing after 1m54s
release / linux/armv7 (pull_request) Failing after 2m12s
release / linux/i686 (pull_request) Failing after 1m59s
release / android (pull_request) Successful in 2m54s
release / windows/i686 (pull_request) Successful in 2m3s
release / windows/x86_64 (pull_request) Successful in 2m15s
2347 lines
73 KiB
Lua
2347 lines
73 KiB
Lua
#!/usr/bin/env luajit
|
|
--[[
|
|
gen-hate-no-d.lua - generate hate-no-d.lua from raylib's own parser output.
|
|
|
|
The generated file contains:
|
|
* one ffi.cdef block with every typedef/struct/alias/callback/prototype
|
|
* Lua constants (enums, #defines, colors)
|
|
* one Lua wrapper per C function, with ffi.string() handling for char*
|
|
returns, array conversions for const T* params, in/out helpers for
|
|
asset structs (Image*, Mesh*, ...) and callback pinning
|
|
* complete LuaCATS annotations (---@class / @field / @param / @return)
|
|
|
|
Inputs are plain Lua tables produced by raylib's tools/rlparser. The Makefile
|
|
generates them into build/api (the parser itself into build/rlparser), so a
|
|
build never writes into raylib's tools/ tree:
|
|
|
|
build/rlparser -i submodules/raylib/src/raylib.h \
|
|
-o build/api/raylib_api.lua -f LUA -d RLAPI
|
|
build/rlparser -i submodules/raylib/src/rlgl.h \
|
|
-o build/api/rlgl_api.lua -f LUA -d RLAPI -t "RLGL IMPLEMENTATION"
|
|
build/rlparser -i submodules/raylib/src/raymath.h \
|
|
-o build/api/raymath_api.lua -f LUA -d RMAPI
|
|
|
|
Usage:
|
|
luajit gen-hate-no-d.lua [--out=hate-no-d.lua] [--no-rlgl] [--no-raymath]
|
|
[--raylib=path] [--rlgl=path] [--raymath=path]
|
|
|
|
raymath needs no extra translation unit: raylib's own rcore.c defines
|
|
RAYMATH_IMPLEMENTATION before including raymath.h, so libraylib.a already
|
|
contains all 146 raymath symbols (verified with nm). Linking the library
|
|
with --whole-archive exposes them to ffi.C.
|
|
]]
|
|
|
|
local CFG = {
|
|
raylib = "build/api/raylib_api.lua",
|
|
rlgl = "build/api/rlgl_api.lua",
|
|
raymath = "build/api/raymath_api.lua",
|
|
out = "hate-no-d.lua",
|
|
out_explicit = false,
|
|
use_rlgl = true,
|
|
use_raymath = true,
|
|
dump_ownership = false, -- false | true (stdout) | path
|
|
}
|
|
|
|
local USAGE = [[
|
|
usage: luajit gen-hate-no-d.lua [options]
|
|
|
|
--out=PATH output file (default: hate-no-d.lua)
|
|
--raylib=PATH raylib parser table (default: build/api/raylib_api.lua)
|
|
--rlgl=PATH rlgl parser table (default: build/api/rlgl_api.lua)
|
|
--raymath=PATH raymath parser table(default: build/api/raymath_api.lua)
|
|
--dump-ownership[=PATH]
|
|
write the ownership map to PATH (default: stdout)
|
|
--no-rlgl skip rlgl
|
|
--no-raymath skip raymath
|
|
-h, --help this text
|
|
]]
|
|
|
|
local function die(fmt, ...)
|
|
io.stderr:write("gen-hate-no-d: " .. string.format(fmt, ...) .. "\n")
|
|
os.exit(1)
|
|
end
|
|
|
|
local function warn(fmt, ...)
|
|
io.stderr:write("gen-hate-no-d: warning: " .. string.format(fmt, ...) .. "\n")
|
|
end
|
|
|
|
for i = 1, #arg do
|
|
local a = arg[i]
|
|
local key, value = a:match("^%-%-([%w%-]+)=(.*)$")
|
|
if key == "out" then
|
|
CFG.out = value
|
|
CFG.out_explicit = true
|
|
elseif key == "raylib" then
|
|
CFG.raylib = value
|
|
elseif key == "rlgl" then
|
|
CFG.rlgl = value
|
|
elseif key == "raymath" then
|
|
CFG.raymath = value
|
|
elseif key == "dump-ownership" then
|
|
CFG.dump_ownership = (value ~= "") and value or true
|
|
elseif key then
|
|
die("unknown option --%s", key)
|
|
elseif a == "--dump-ownership" then
|
|
CFG.dump_ownership = true
|
|
elseif a == "--no-rlgl" then
|
|
CFG.use_rlgl = false
|
|
elseif a == "--no-raymath" then
|
|
CFG.use_raymath = false
|
|
elseif a == "-h" or a == "--help" then
|
|
io.write(USAGE)
|
|
os.exit(0)
|
|
else
|
|
die("unknown argument %s", a)
|
|
end
|
|
end
|
|
|
|
----------------------------------------------------------------------------
|
|
-- loading
|
|
----------------------------------------------------------------------------
|
|
|
|
local function load_api(path, optional)
|
|
local chunk, err = loadfile(path)
|
|
if not chunk then
|
|
if optional then
|
|
warn("skipping %s (%s)", path, err)
|
|
return nil
|
|
end
|
|
die("cannot load %s: %s", path, err)
|
|
return nil
|
|
end
|
|
local ok, data = pcall(chunk)
|
|
if not ok then
|
|
die("cannot run %s: %s", path, data)
|
|
end
|
|
if type(data) ~= "table" then
|
|
die("%s did not return a table", path)
|
|
end
|
|
return data
|
|
end
|
|
|
|
local apis = {}
|
|
|
|
local raylib_api = load_api(CFG.raylib)
|
|
apis[#apis + 1] = { tag = "raylib", data = raylib_api }
|
|
|
|
if CFG.use_rlgl then
|
|
local data = load_api(CFG.rlgl, false)
|
|
if data then
|
|
apis[#apis + 1] = { tag = "rlgl", data = data }
|
|
else
|
|
warn("rlgl API table missing, building raylib.h only")
|
|
end
|
|
end
|
|
|
|
if CFG.use_raymath then
|
|
local data = load_api(CFG.raymath, false)
|
|
if data then
|
|
apis[#apis + 1] = { tag = "raymath", data = data }
|
|
else
|
|
warn("raymath API table missing, building without raymath")
|
|
end
|
|
end
|
|
|
|
local function find_define(data, name)
|
|
for _, d in ipairs(data.defines or {}) do
|
|
if d.name == name then
|
|
return d.value
|
|
end
|
|
end
|
|
return nil
|
|
end
|
|
|
|
local version = tostring(find_define(raylib_api, "RAYLIB_VERSION") or "unknown")
|
|
|
|
----------------------------------------------------------------------------
|
|
-- type model
|
|
----------------------------------------------------------------------------
|
|
|
|
local SCALAR = {
|
|
["void"] = true, bool = true, char = true, short = true, int = true,
|
|
long = true, float = true, double = true,
|
|
["unsigned char"] = true, ["unsigned short"] = true,
|
|
["unsigned int"] = true, ["unsigned long"] = true,
|
|
["signed char"] = true, ["long long"] = true, ["size_t"] = true,
|
|
}
|
|
|
|
local INTEGER = {
|
|
char = true, short = true, int = true, long = true,
|
|
["unsigned char"] = true, ["unsigned short"] = true,
|
|
["unsigned int"] = true, ["unsigned long"] = true,
|
|
["signed char"] = true, ["long long"] = true, ["size_t"] = true,
|
|
}
|
|
|
|
local NUMBER = { float = true, double = true }
|
|
|
|
local STRUCTS, ALIASES, CALLBACKS = {}, {}, {}
|
|
local DEFS = {}
|
|
|
|
local function norm(s)
|
|
return (s:gsub("%s+", " "):gsub("^ ", ""):gsub(" $", ""))
|
|
end
|
|
|
|
-- Parse a raylib parser type string into base / pointer depth / const / array.
|
|
local function parse_type(t)
|
|
local s = norm(t)
|
|
local array = s:match("%[(%d+)%]%s*$")
|
|
if array then
|
|
s = s:gsub("%[%d+%]%s*$", "")
|
|
s = norm(s)
|
|
end
|
|
local is_const = false
|
|
if s:match("^const ") then
|
|
is_const = true
|
|
s = norm(s:sub(7))
|
|
end
|
|
local ptr = select(2, s:gsub("%*", ""))
|
|
s = norm((s:gsub("%*", "")))
|
|
return { base = s, ptr = ptr, const = is_const, array = tonumber(array) }
|
|
end
|
|
|
|
local function is_structish(base)
|
|
return STRUCTS[base] ~= nil or ALIASES[base] ~= nil
|
|
end
|
|
|
|
----------------------------------------------------------------------------
|
|
-- merge the three API tables
|
|
----------------------------------------------------------------------------
|
|
|
|
local FUNCS = {}
|
|
|
|
-- rlparser is line-oriented and does not evaluate the preprocessor: rlgl.h
|
|
-- struct fields guarded by #if/#endif leak into the output as bogus fields
|
|
-- ("#endif indices", "#if defined(...) unsigned int * indices"). Drop those
|
|
-- and keep the first real field with a given name.
|
|
local function sanitize_fields(fields)
|
|
local clean, seen = {}, {}
|
|
for _, f in ipairs(fields) do
|
|
local ftype = norm(f.type or "")
|
|
local fname = norm(f.name or "")
|
|
if fname ~= "" and not fname:match("^#") and not ftype:match("^#") and not seen[fname] then
|
|
seen[fname] = true
|
|
clean[#clean + 1] = f
|
|
end
|
|
end
|
|
return clean
|
|
end
|
|
|
|
local function add_api(tag)
|
|
local data
|
|
for _, item in ipairs(apis) do
|
|
if item.tag == tag then
|
|
data = item.data
|
|
break
|
|
end
|
|
end
|
|
if not data then
|
|
return
|
|
end
|
|
|
|
for _, s in ipairs(data.structs or {}) do
|
|
if not STRUCTS[s.name] and not ALIASES[s.name] then
|
|
STRUCTS[s.name] = {
|
|
kind = "struct",
|
|
name = s.name,
|
|
fields = sanitize_fields(s.fields or {}),
|
|
description = s.description,
|
|
}
|
|
DEFS[#DEFS + 1] = STRUCTS[s.name]
|
|
end
|
|
end
|
|
|
|
for _, a in ipairs(data.aliases or {}) do
|
|
if not ALIASES[a.name] and not STRUCTS[a.name] then
|
|
-- rlparser stores the target in `type` and the new name in `name`.
|
|
ALIASES[a.name] = {
|
|
kind = "alias",
|
|
name = a.name,
|
|
target = a.type,
|
|
description = a.description,
|
|
}
|
|
DEFS[#DEFS + 1] = ALIASES[a.name]
|
|
end
|
|
end
|
|
|
|
for _, c in ipairs(data.callbacks or {}) do
|
|
if not CALLBACKS[c.name] then
|
|
CALLBACKS[c.name] = c
|
|
end
|
|
end
|
|
|
|
for _, f in ipairs(data.functions or {}) do
|
|
f._tag = tag
|
|
FUNCS[#FUNCS + 1] = f
|
|
end
|
|
end
|
|
|
|
for _, item in ipairs(apis) do
|
|
add_api(item.tag)
|
|
end
|
|
|
|
-- TraceLogCallback carries va_list, which LuaJIT cannot pass to a Lua
|
|
-- callback; drop the callback and the single function using it.
|
|
CALLBACKS.TraceLogCallback = nil
|
|
|
|
local SKIP = {
|
|
SetTraceLogCallback = true,
|
|
}
|
|
|
|
local function params_of(f)
|
|
return f.params or {}
|
|
end
|
|
|
|
local function is_skipped(f)
|
|
if SKIP[f.name] then
|
|
return true
|
|
end
|
|
for _, p in ipairs(params_of(f)) do
|
|
if norm(p.type) == "va_list" then
|
|
return true
|
|
end
|
|
end
|
|
return false
|
|
end
|
|
|
|
----------------------------------------------------------------------------
|
|
-- validation
|
|
----------------------------------------------------------------------------
|
|
|
|
local function check_type(t, where)
|
|
local p = parse_type(t)
|
|
if p.base == "..." or p.base == "va_list" then
|
|
return
|
|
end
|
|
if SCALAR[p.base] or is_structish(p.base) or CALLBACKS[p.base] then
|
|
return
|
|
end
|
|
if p.ptr > 0 then
|
|
return -- opaque pointer (rAudioBuffer *, ...)
|
|
end
|
|
die("unknown type %q in %s", p.base, where)
|
|
end
|
|
|
|
local func_names = {}
|
|
for _, f in ipairs(FUNCS) do
|
|
if func_names[f.name] then
|
|
die("duplicate function name %s", f.name)
|
|
end
|
|
func_names[f.name] = true
|
|
if not is_skipped(f) then
|
|
check_type(f.returnType, f.name .. " return")
|
|
for _, p in ipairs(params_of(f)) do
|
|
check_type(p.type, f.name .. " param " .. p.name)
|
|
end
|
|
end
|
|
end
|
|
|
|
for _, def in ipairs(DEFS) do
|
|
if def.kind == "struct" then
|
|
for _, f in ipairs(def.fields) do
|
|
check_type(f.type, def.name .. "." .. f.name)
|
|
end
|
|
else
|
|
check_type(def.target, def.name .. " alias")
|
|
end
|
|
end
|
|
|
|
-- Opaque struct names (forward declarations in the cdef).
|
|
local OPAQUE = {}
|
|
local function scan_opaque(t)
|
|
local p = parse_type(t)
|
|
if p.base == "..." or p.base == "va_list" then
|
|
return
|
|
end
|
|
if SCALAR[p.base] or is_structish(p.base) or CALLBACKS[p.base] then
|
|
return
|
|
end
|
|
OPAQUE[p.base] = true
|
|
end
|
|
|
|
for _, def in ipairs(DEFS) do
|
|
if def.kind == "struct" then
|
|
for _, f in ipairs(def.fields) do
|
|
scan_opaque(f.type)
|
|
end
|
|
end
|
|
end
|
|
for _, f in ipairs(FUNCS) do
|
|
if not is_skipped(f) then
|
|
scan_opaque(f.returnType)
|
|
for _, p in ipairs(params_of(f)) do
|
|
scan_opaque(p.type)
|
|
end
|
|
end
|
|
end
|
|
|
|
local opaque_names = {}
|
|
for name in pairs(OPAQUE) do
|
|
opaque_names[#opaque_names + 1] = name
|
|
end
|
|
table.sort(opaque_names)
|
|
|
|
----------------------------------------------------------------------------
|
|
-- dependency order (typedefs must be declared before use)
|
|
----------------------------------------------------------------------------
|
|
|
|
local function deps_of(def)
|
|
local deps = {}
|
|
local function add(t)
|
|
local p = parse_type(t)
|
|
if is_structish(p.base) and p.base ~= def.name then
|
|
deps[#deps + 1] = p.base
|
|
end
|
|
end
|
|
if def.kind == "struct" then
|
|
for _, f in ipairs(def.fields) do
|
|
add(f.type)
|
|
end
|
|
else
|
|
add(def.target)
|
|
end
|
|
return deps
|
|
end
|
|
|
|
local ordered = {}
|
|
local state = {}
|
|
|
|
local function visit(name)
|
|
if state[name] == "done" then
|
|
return
|
|
end
|
|
if state[name] == "active" then
|
|
die("cyclic typedef involving %s", name)
|
|
end
|
|
local def = STRUCTS[name] or ALIASES[name]
|
|
if not def then
|
|
return
|
|
end
|
|
state[name] = "active"
|
|
for _, dep in ipairs(deps_of(def)) do
|
|
visit(dep)
|
|
end
|
|
state[name] = "done"
|
|
ordered[#ordered + 1] = def
|
|
end
|
|
|
|
for _, def in ipairs(DEFS) do
|
|
visit(def.name)
|
|
end
|
|
|
|
----------------------------------------------------------------------------
|
|
-- C rendering
|
|
----------------------------------------------------------------------------
|
|
|
|
local function c_base(base)
|
|
if SCALAR[base] or is_structish(base) or CALLBACKS[base] then
|
|
return base
|
|
end
|
|
return "struct " .. base
|
|
end
|
|
|
|
local function c_type(t)
|
|
local p = parse_type(t)
|
|
if p.base == "..." then
|
|
return "..."
|
|
end
|
|
local s = c_base(p.base)
|
|
if p.ptr > 0 then
|
|
s = s .. " " .. string.rep("*", p.ptr)
|
|
end
|
|
if p.const then
|
|
s = "const " .. s
|
|
end
|
|
return s
|
|
end
|
|
|
|
local function c_field(ftype, fname)
|
|
local p = parse_type(ftype)
|
|
local base = c_base(p.base)
|
|
if p.array then
|
|
return base .. " " .. fname .. "[" .. p.array .. "]"
|
|
end
|
|
if p.ptr > 0 then
|
|
return base .. " " .. string.rep("*", p.ptr) .. fname
|
|
end
|
|
return base .. " " .. fname
|
|
end
|
|
|
|
----------------------------------------------------------------------------
|
|
-- LuaCATS rendering
|
|
----------------------------------------------------------------------------
|
|
|
|
local CHAR_BUFFER = "raylib.char_buffer"
|
|
local CSTRING_ARRAY = "raylib.cstring_array"
|
|
|
|
local function ann_scalar(base)
|
|
if base == "bool" then
|
|
return "boolean"
|
|
end
|
|
if INTEGER[base] then
|
|
return "integer"
|
|
end
|
|
if NUMBER[base] then
|
|
return "number"
|
|
end
|
|
return nil
|
|
end
|
|
|
|
local function ann_value(base)
|
|
local scalar = ann_scalar(base)
|
|
if scalar then
|
|
return scalar
|
|
end
|
|
if is_structish(base) then
|
|
return "raylib." .. base
|
|
end
|
|
return "ffi.cdata*"
|
|
end
|
|
|
|
local function ann_field(ftype)
|
|
local p = parse_type(ftype)
|
|
if p.array then
|
|
if p.base == "char" then
|
|
return CHAR_BUFFER
|
|
end
|
|
local elem = ann_scalar(p.base)
|
|
if elem then
|
|
return elem .. "[]"
|
|
end
|
|
if is_structish(p.base) then
|
|
return "raylib." .. p.base .. "[]"
|
|
end
|
|
return "ffi.cdata*"
|
|
end
|
|
if p.ptr > 0 then
|
|
if p.base == "char" then
|
|
return p.ptr == 1 and CHAR_BUFFER or CSTRING_ARRAY
|
|
end
|
|
if p.base == "void" then
|
|
return "ffi.cdata*"
|
|
end
|
|
if INTEGER[p.base] then
|
|
return "integer[]"
|
|
end
|
|
if NUMBER[p.base] then
|
|
return "number[]"
|
|
end
|
|
if is_structish(p.base) then
|
|
return "raylib." .. p.base .. "[]"
|
|
end
|
|
return "ffi.cdata*"
|
|
end
|
|
return ann_value(p.base)
|
|
end
|
|
|
|
-- Struct pointers that are genuinely in/out: the caller passes the handle and
|
|
-- gets the (possibly mutated) handle back. Owned types are mutated in place
|
|
-- (address-of); the rest go through a one-element array copy.
|
|
local OUT_STRUCT = {
|
|
Image = true, Texture2D = true, Mesh = true, Wave = true, Material = true,
|
|
Model = true, RenderTexture2D = true, Camera = true, AutomationEventList = true,
|
|
}
|
|
|
|
-- Struct-pointer params that are not in/out: pass them through (optionally
|
|
-- converting a Lua table) instead of copying one element.
|
|
local INOUT_EXCLUDE = {
|
|
SetWindowIcons = true,
|
|
}
|
|
|
|
-- Functions whose struct-pointer parameters are pure outputs. Those params are
|
|
-- optional on the Lua side and become extra return values.
|
|
local OUT_OVERRIDES = {
|
|
MatrixDecompose = { 2, 3, 4 },
|
|
}
|
|
|
|
----------------------------------------------------------------------------
|
|
-- ownership classification (issue #4)
|
|
--
|
|
-- Every function's return shape must land in exactly one bucket, or generation
|
|
-- dies. That is the guarantee: a raylib bump that adds an asset type or an
|
|
-- array loader cannot silently leak.
|
|
----------------------------------------------------------------------------
|
|
|
|
-- Resolve struct aliases to the canonical type (Texture2D -> Texture, ...).
|
|
local function canon(base)
|
|
local seen = {}
|
|
while ALIASES[base] and not seen[base] do
|
|
seen[base] = true
|
|
local target = ALIASES[base].target or ALIASES[base].type
|
|
base = parse_type(target).base
|
|
end
|
|
return base
|
|
end
|
|
|
|
-- Struct values that own memory. `kind` gates the release on device readiness,
|
|
-- `release` is the C unloader (checked against the API tables).
|
|
local OWNED = {
|
|
Image = { kind = "ram", release = "UnloadImage" },
|
|
Texture = { kind = "gpu", release = "UnloadTexture" },
|
|
RenderTexture = { kind = "gpu", release = "UnloadRenderTexture" },
|
|
Shader = { kind = "gpu", release = "UnloadShader" },
|
|
Mesh = { kind = "gpu", release = "UnloadMesh" },
|
|
Model = { kind = "gpu", release = "UnloadModel" },
|
|
Material = { kind = "gpu", release = "UnloadMaterial" }, -- maps only, see _release_Material
|
|
Font = { kind = "gpu", release = "UnloadFont" },
|
|
Wave = { kind = "ram", release = "UnloadWave" },
|
|
Sound = { kind = "audio", release = "UnloadSound" },
|
|
Music = { kind = "audio", release = "UnloadMusicStream" },
|
|
AudioStream = { kind = "audio", release = "UnloadAudioStream" },
|
|
AutomationEventList = { kind = "ram", release = "UnloadAutomationEventList" },
|
|
FilePathList = { kind = "ram", release = "UnloadDirectoryFiles" },
|
|
VrStereoConfig = { kind = "gpu", release = "UnloadVrStereoConfig" },
|
|
}
|
|
|
|
-- Struct returns that own no memory at all.
|
|
local VALUE_ONLY = {
|
|
Vector2 = true, Vector3 = true, Vector4 = true, Matrix = true,
|
|
float16 = true, float3 = true,
|
|
Color = true, Rectangle = true, Ray = true, BoundingBox = true,
|
|
RayCollision = true,
|
|
GlyphInfo = true, -- GlyphInfo.image aliases the font; never armed
|
|
}
|
|
|
|
-- Struct returns owned elsewhere (raylib globals, or a view of another owner).
|
|
local BORROWED = {
|
|
GetShapesTexture = true,
|
|
GetFontDefault = true,
|
|
LoadDroppedFiles = true, -- aliases CORE.Window.dropFilepaths
|
|
GetGlyphInfo = true, -- GlyphInfo.image.data aliases the font's glyph array
|
|
}
|
|
|
|
-- Pointer/array returns that must be freed by the caller.
|
|
local OWNED_POINTER = {
|
|
LoadImageColors = { kind = "ram", release = "UnloadImageColors" },
|
|
LoadImagePalette = { kind = "ram", release = "UnloadImagePalette", count = "colorCount" },
|
|
LoadFontData = { kind = "ram", release = "UnloadFontData", count = "glyphCount" },
|
|
-- raylib has no UnloadMaterials(): free every material's maps, then the array.
|
|
LoadMaterials = { kind = "ram", release = "UnloadMaterial", count = "materialCount",
|
|
per_item = true, free = "MemFree" },
|
|
LoadModelAnimations = { kind = "ram", release = "UnloadModelAnimations", count = "animCount",
|
|
init_count = true },
|
|
LoadRandomSequence = { kind = "ram", release = "UnloadRandomSequence" },
|
|
LoadWaveSamples = { kind = "ram", release = "UnloadWaveSamples" },
|
|
LoadCodepoints = { kind = "ram", release = "UnloadCodepoints", count = "count" },
|
|
LoadTextLines = { kind = "ram", release = "UnloadTextLines", count = "count" },
|
|
LoadFileData = { kind = "ram", release = "UnloadFileData", count = "dataSize" },
|
|
CompressData = { kind = "ram", release = "MemFree", count = "compDataSize" },
|
|
DecompressData = { kind = "ram", release = "MemFree", count = "dataSize" },
|
|
DecodeDataBase64 = { kind = "ram", release = "MemFree", count = "outputSize" },
|
|
ExportImageToMemory = { kind = "ram", release = "MemFree", count = "fileSize" },
|
|
MemAlloc = { kind = "ram", release = "MemFree" },
|
|
MemRealloc = { kind = "ram", release = "MemFree" },
|
|
rlReadScreenPixels = { kind = "ram", release = "MemFree" },
|
|
rlReadTexturePixels = { kind = "ram", release = "MemFree" },
|
|
rlLoadRenderBatch = { kind = "gpu", release = "rlUnloadRenderBatch" },
|
|
}
|
|
|
|
-- Pointer returns that must never be freed (raylib static buffers).
|
|
local BORROWED_STATIC = {
|
|
ComputeMD5 = true, ComputeSHA1 = true, ComputeSHA256 = true, -- static unsigned int[4]
|
|
GetWindowHandle = true, rlGetProcAddress = true, rlGetShaderLocsDefault = true,
|
|
TextSplit = true, -- static char* buffers
|
|
}
|
|
|
|
-- char* returns that must be copied, then freed.
|
|
local OWNED_STRING = {
|
|
LoadFileText = "UnloadFileText",
|
|
LoadUTF8 = "UnloadUTF8",
|
|
EncodeDataBase64 = "MemFree",
|
|
TextReplaceAlloc = "MemFree",
|
|
TextReplaceBetweenAlloc = "MemFree",
|
|
TextInsertAlloc = "MemFree",
|
|
}
|
|
|
|
-- char* returns owned by raylib / static: copy only.
|
|
local BORROWED_STRING = {
|
|
CodepointToUTF8 = true, GetApplicationDirectory = true, GetClipboardText = true,
|
|
GetDirectoryPath = true, GetFileExtension = true, GetFileName = true,
|
|
GetFileNameWithoutExt = true, GetGamepadName = true, GetKeyName = true,
|
|
GetMonitorName = true, GetPrevDirectoryPath = true, GetTextBetween = true,
|
|
GetWorkingDirectory = true, TextFormat = true, TextInsert = true,
|
|
TextJoin = true, TextRemoveSpaces = true, TextReplace = true,
|
|
TextReplaceBetween = true, TextSubtext = true, TextToCamel = true,
|
|
TextToLower = true, TextToPascal = true, TextToSnake = true, TextToUpper = true,
|
|
rlGetPixelFormatName = true,
|
|
}
|
|
|
|
-- Pointer returns that are genuinely inert handles (none today). A new raylib
|
|
-- pointer return must be listed here, in OWNED_POINTER or in BORROWED_STATIC.
|
|
local NON_OWNING = {}
|
|
|
|
-- Functions that move ownership of a parameter to their return value.
|
|
local CONSUMES = {
|
|
LoadModelFromMesh = { param = "mesh", type = "Mesh", valid_field = "meshCount" },
|
|
}
|
|
|
|
-- Functions that retain a parameter: it becomes a finalizer upvalue.
|
|
local KEEPS = {
|
|
LoadSoundAlias = { keep = "source", own = "SoundAlias", release = "UnloadSoundAlias" },
|
|
LoadMusicStreamFromMemory = { keep = "data", own = "Music" },
|
|
}
|
|
|
|
-- Owner variants that are not plain struct types.
|
|
local EXTRA_OWNERS = {
|
|
-- LoadSoundAlias shares the sample data with its source, so it must NOT be
|
|
-- released with UnloadSound.
|
|
SoundAlias = { kind = "audio", release = "UnloadSoundAlias", valid = "Sound" },
|
|
}
|
|
|
|
-- Window instance counter: finalizers armed under an older GPU generation
|
|
-- refuse to run, because the GL context (and its ids) is gone.
|
|
local POST_CALL = {
|
|
-- A new or destroyed GL context invalidates every pin: keeping them would
|
|
-- both point at dead ids and keep the pinned Lua objects alive forever.
|
|
InitWindow = "_gpu_gen = _gpu_gen + 1; _st.gen = _gpu_gen; _fin_cache = {}; _pins.shapes = nil; _pins.shapes_prev = nil; _pins.material = {}; _pins.auto = nil",
|
|
CloseWindow = "_gpu_gen = _gpu_gen + 1; _st.gen = _gpu_gen; _fin_cache = {}; _pins.shapes = nil; _pins.shapes_prev = nil; _pins.material = {}; _pins.auto = nil",
|
|
}
|
|
|
|
-- Extra doc lines for wrappers whose lifetime contract is easy to get wrong.
|
|
local EXTRA_DOC = {
|
|
GetGlyphInfo = "NOTE: the returned GlyphInfo.image.data aliases the font's glyph array; keep the font alive while using it.",
|
|
GetShapesTexture = "NOTE: this is a view; the texture is owned by raylib.",
|
|
GetFontDefault = "NOTE: this is a view; raylib owns the default font.",
|
|
LoadDroppedFiles = "NOTE: this is a view of raylib's internal dropped-file state.",
|
|
}
|
|
|
|
-- Functions emitted by hand (signature or lifetime differs from the C shape).
|
|
local SPECIAL = {
|
|
TextFormat = true,
|
|
TraceLog = true,
|
|
CodepointToUTF8 = true,
|
|
GenImageFontAtlas = true,
|
|
LoadModelFromMesh = true,
|
|
LoadSoundAlias = true,
|
|
LoadMusicStreamFromMemory = true,
|
|
SetShapesTexture = true,
|
|
SetMaterialTexture = true,
|
|
SetAutomationEventList = true,
|
|
SetWindowIcons = true,
|
|
MemAlloc = true,
|
|
MemRealloc = true,
|
|
MemFree = true,
|
|
}
|
|
|
|
local INOUT_ALLOW = { Camera = true }
|
|
|
|
-- Small validity predicates: a failed load must not be armed.
|
|
local VALID = {
|
|
Image = "x.data ~= nil",
|
|
Texture = "x.id ~= 0",
|
|
RenderTexture = "x.id ~= 0",
|
|
Shader = "x.id ~= 0",
|
|
Font = "x.texture.id ~= 0",
|
|
Wave = "x.data ~= nil",
|
|
Sound = "x.stream.buffer ~= nil",
|
|
Music = "x.stream.buffer ~= nil",
|
|
AudioStream = "x.buffer ~= nil",
|
|
AutomationEventList = "x.events ~= nil",
|
|
FilePathList = "x.paths ~= nil",
|
|
Model = "x.meshCount > 0",
|
|
}
|
|
|
|
local funcs_by_name = {}
|
|
for _, f in ipairs(FUNCS) do
|
|
funcs_by_name[f.name] = f
|
|
end
|
|
|
|
local function has_func(name)
|
|
local f = funcs_by_name[name]
|
|
return f ~= nil and not is_skipped(f)
|
|
end
|
|
|
|
-- Buckets: owned | value | borrowed | owned_pointer | borrowed_static |
|
|
-- owned_string | borrowed_string | non_owning
|
|
local CLASS = {}
|
|
|
|
local function classify(f)
|
|
local name = f.name
|
|
local ret = parse_type(f.returnType)
|
|
|
|
if ret.base == "char" and ret.ptr == 1 then
|
|
if OWNED_STRING[name] then
|
|
return { bucket = "owned_string", release = OWNED_STRING[name], kind = "ram" }
|
|
end
|
|
if BORROWED_STRING[name] then
|
|
return { bucket = "borrowed_string" }
|
|
end
|
|
return nil, string.format("unclassified char* return %s", name)
|
|
end
|
|
|
|
if ret.ptr > 0 then
|
|
local op = OWNED_POINTER[name]
|
|
if op then
|
|
return {
|
|
bucket = "owned_pointer", type = canon(ret.base), kind = op.kind,
|
|
release = op.release, count = op.count, init_count = op.init_count,
|
|
per_item = op.per_item, free = op.free,
|
|
}
|
|
end
|
|
if BORROWED_STATIC[name] then
|
|
return { bucket = "borrowed_static" }
|
|
end
|
|
if NON_OWNING[name] then
|
|
return { bucket = "non_owning" }
|
|
end
|
|
return nil, string.format("unclassified pointer return %s -> %s", name, norm(f.returnType))
|
|
end
|
|
|
|
if ret.base == "void" then
|
|
return { bucket = "non_owning" }
|
|
end
|
|
|
|
if is_structish(ret.base) then
|
|
local c = canon(ret.base)
|
|
-- BORROWED wins over OWNED: that is the override mechanism for raylib
|
|
-- globals that have an owned type (GetFontDefault, LoadDroppedFiles).
|
|
if BORROWED[name] then
|
|
return { bucket = "borrowed", type = c }
|
|
end
|
|
if OWNED[c] then
|
|
return { bucket = "owned", type = c, kind = OWNED[c].kind, release = OWNED[c].release }
|
|
end
|
|
local op = OWNED_POINTER[name]
|
|
if op then
|
|
-- value structs with an unload function (rlLoadRenderBatch)
|
|
return { bucket = "owned_pointer", type = c, kind = op.kind, release = op.release }
|
|
end
|
|
if VALUE_ONLY[c] then
|
|
return { bucket = "value", type = c }
|
|
end
|
|
return nil, string.format("unclassified struct return %s -> %s", name, c)
|
|
end
|
|
|
|
return { bucket = "non_owning" }
|
|
end
|
|
|
|
local function validate_ownership()
|
|
local errors = {}
|
|
local function bad(fmt, ...)
|
|
errors[#errors + 1] = string.format(fmt, ...)
|
|
end
|
|
local function need_func(name, where)
|
|
if not has_func(name) then
|
|
bad("%s: %s is not an API function", where, tostring(name))
|
|
end
|
|
end
|
|
local function need_struct(name, where)
|
|
if not STRUCTS[name] then
|
|
bad("%s: %s is not an API struct", where, tostring(name))
|
|
end
|
|
end
|
|
|
|
-- Total classification: every emitted function lands in exactly one bucket.
|
|
for _, f in ipairs(FUNCS) do
|
|
if not is_skipped(f) then
|
|
local cls, err = classify(f)
|
|
if cls then
|
|
CLASS[f.name] = cls
|
|
else
|
|
bad("%s", err)
|
|
end
|
|
end
|
|
end
|
|
|
|
for t, o in pairs(OWNED) do
|
|
need_struct(t, "OWNED")
|
|
need_func(o.release, "OWNED." .. t)
|
|
if o.kind ~= "ram" and o.kind ~= "gpu" and o.kind ~= "audio" then
|
|
bad("OWNED.%s: bad kind %q", t, tostring(o.kind))
|
|
end
|
|
if VALUE_ONLY[t] then
|
|
bad("%s is in both OWNED and VALUE_ONLY", t)
|
|
end
|
|
end
|
|
for t in pairs(VALUE_ONLY) do
|
|
need_struct(t, "VALUE_ONLY")
|
|
end
|
|
for fn in pairs(BORROWED) do
|
|
need_func(fn, "BORROWED")
|
|
if OWNED_POINTER[fn] or OWNED_STRING[fn] or CONSUMES[fn] or KEEPS[fn] then
|
|
bad("%s is in both BORROWED and an owning table", fn)
|
|
end
|
|
end
|
|
for fn in pairs(BORROWED_STATIC) do
|
|
need_func(fn, "BORROWED_STATIC")
|
|
end
|
|
for fn in pairs(BORROWED_STRING) do
|
|
need_func(fn, "BORROWED_STRING")
|
|
end
|
|
for fn, release in pairs(OWNED_STRING) do
|
|
need_func(fn, "OWNED_STRING")
|
|
need_func(release, "OWNED_STRING." .. fn)
|
|
end
|
|
for fn, o in pairs(OWNED_POINTER) do
|
|
need_func(fn, "OWNED_POINTER")
|
|
need_func(o.release, "OWNED_POINTER." .. fn)
|
|
if o.free then
|
|
need_func(o.free, "OWNED_POINTER." .. fn .. ".free")
|
|
end
|
|
if o.count then
|
|
local found = false
|
|
for _, p in ipairs(params_of(funcs_by_name[fn])) do
|
|
if p.name == o.count then
|
|
found = true
|
|
local pt = parse_type(p.type)
|
|
if pt.ptr ~= 1 or not INTEGER[pt.base] then
|
|
bad("OWNED_POINTER.%s.count %s is not an integer out-param", fn, o.count)
|
|
end
|
|
end
|
|
end
|
|
if not found then
|
|
bad("OWNED_POINTER.%s.count %s is not a parameter", fn, o.count)
|
|
end
|
|
end
|
|
end
|
|
for fn in pairs(NON_OWNING) do
|
|
need_func(fn, "NON_OWNING")
|
|
end
|
|
for fn, c in pairs(CONSUMES) do
|
|
need_func(fn, "CONSUMES")
|
|
local found = false
|
|
for _, p in ipairs(params_of(funcs_by_name[fn])) do
|
|
if p.name == c.param then
|
|
found = true
|
|
if canon(parse_type(p.type).base) ~= c.type then
|
|
bad("CONSUMES.%s.param %s is not a %s", fn, c.param, c.type)
|
|
end
|
|
end
|
|
end
|
|
if not found then
|
|
bad("CONSUMES.%s.param %s is not a parameter", fn, c.param)
|
|
end
|
|
end
|
|
for fn, k in pairs(KEEPS) do
|
|
need_func(fn, "KEEPS")
|
|
if k.release then
|
|
need_func(k.release, "KEEPS." .. fn)
|
|
end
|
|
if not OWNED[k.own] and not EXTRA_OWNERS[k.own] then
|
|
bad("KEEPS.%s.own %s is not an owned type", fn, tostring(k.own))
|
|
end
|
|
local found = false
|
|
for _, p in ipairs(params_of(funcs_by_name[fn])) do
|
|
if p.name == k.keep then
|
|
found = true
|
|
end
|
|
end
|
|
if not found then
|
|
bad("KEEPS.%s.keep %s is not a parameter", fn, k.keep)
|
|
end
|
|
end
|
|
for fn in pairs(POST_CALL) do
|
|
need_func(fn, "POST_CALL")
|
|
end
|
|
for fn in pairs(SPECIAL) do
|
|
need_func(fn, "SPECIAL")
|
|
end
|
|
|
|
-- In/out struct params must be owned types (or an explicit exception).
|
|
for t in pairs(OUT_STRUCT) do
|
|
if not OWNED[canon(t)] and not INOUT_ALLOW[t] then
|
|
bad("OUT_STRUCT.%s is not an owned type", t)
|
|
end
|
|
end
|
|
|
|
if #errors > 0 then
|
|
for _, e in ipairs(errors) do
|
|
io.stderr:write("gen-hate-no-d: ownership: " .. e .. "\n")
|
|
end
|
|
die("%d ownership classification error(s)", #errors)
|
|
end
|
|
end
|
|
|
|
validate_ownership()
|
|
|
|
-- Counts for the summary line and the ownership map.
|
|
local function ownership_summary()
|
|
local n = {
|
|
owned = 0, value = 0, borrowed = 0, owned_pointer = 0,
|
|
borrowed_static = 0, owned_string = 0, borrowed_string = 0, non_owning = 0,
|
|
}
|
|
for _, f in ipairs(FUNCS) do
|
|
local cls = CLASS[f.name]
|
|
if cls then
|
|
n[cls.bucket] = n[cls.bucket] + 1
|
|
end
|
|
end
|
|
return n
|
|
end
|
|
|
|
local function ownership_map()
|
|
local lines = {}
|
|
local fmt = "%-6s %-36s %-16s %-5s %s"
|
|
local types = {}
|
|
for t in pairs(OWNED) do
|
|
types[#types + 1] = t
|
|
end
|
|
table.sort(types)
|
|
for _, t in ipairs(types) do
|
|
lines[#lines + 1] = string.format(fmt, "struct", t, "owned", OWNED[t].kind, OWNED[t].release)
|
|
end
|
|
local values = {}
|
|
for t in pairs(VALUE_ONLY) do
|
|
values[#values + 1] = t
|
|
end
|
|
table.sort(values)
|
|
for _, t in ipairs(values) do
|
|
lines[#lines + 1] = string.format(fmt, "struct", t, "value", "-", "-")
|
|
end
|
|
for _, f in ipairs(FUNCS) do
|
|
local cls = CLASS[f.name]
|
|
if cls then
|
|
lines[#lines + 1] = string.format(fmt, "func", f.name, cls.bucket,
|
|
cls.kind or "-", cls.release or "-")
|
|
end
|
|
end
|
|
table.sort(lines)
|
|
local header = {
|
|
"# hate-no-d ownership map",
|
|
"# raylib " .. version,
|
|
"# class: owned | value | borrowed | owned_pointer | borrowed_static |" ..
|
|
" owned_string | borrowed_string | non_owning",
|
|
}
|
|
local all = {}
|
|
for _, h in ipairs(header) do
|
|
all[#all + 1] = h
|
|
end
|
|
for _, l in ipairs(lines) do
|
|
all[#all + 1] = l
|
|
end
|
|
return table.concat(all, "\n") .. "\n"
|
|
end
|
|
|
|
|
|
local function ann_param(p, is_out)
|
|
local pt = parse_type(p.type)
|
|
if pt.base == "..." then
|
|
return "any"
|
|
end
|
|
if CALLBACKS[pt.base] then
|
|
return "raylib." .. pt.base
|
|
end
|
|
if pt.ptr == 0 then
|
|
return ann_value(pt.base)
|
|
end
|
|
if is_out then
|
|
return "raylib." .. pt.base
|
|
end
|
|
if pt.base == "char" then
|
|
if pt.ptr == 1 then
|
|
return pt.const and "string" or (CHAR_BUFFER .. "|string")
|
|
end
|
|
return "string[]|" .. CSTRING_ARRAY
|
|
end
|
|
if pt.base == "void" then
|
|
return "ffi.cdata*|string"
|
|
end
|
|
if pt.base == "unsigned char" and pt.const then
|
|
return "string|integer[]"
|
|
end
|
|
if pt.const then
|
|
local elem = ann_scalar(pt.base)
|
|
if elem then
|
|
return elem .. "[]"
|
|
end
|
|
if is_structish(pt.base) then
|
|
return "raylib." .. pt.base .. "[]"
|
|
end
|
|
end
|
|
return "ffi.cdata*"
|
|
end
|
|
|
|
local function ann_return(t)
|
|
local p = parse_type(t)
|
|
if p.base == "void" and p.ptr == 0 then
|
|
return "nil"
|
|
end
|
|
if p.ptr == 0 then
|
|
return ann_value(p.base)
|
|
end
|
|
if p.base == "char" and p.ptr == 1 then
|
|
return "string|nil"
|
|
end
|
|
return "ffi.cdata*"
|
|
end
|
|
|
|
----------------------------------------------------------------------------
|
|
-- out-params / array conversions
|
|
----------------------------------------------------------------------------
|
|
|
|
local function out_params(f)
|
|
local out = {}
|
|
local ret = parse_type(f.returnType)
|
|
if ret.base ~= "void" or ret.ptr ~= 0 then
|
|
return out
|
|
end
|
|
if OUT_OVERRIDES[f.name] then
|
|
for _, i in ipairs(OUT_OVERRIDES[f.name]) do
|
|
out[i] = "out"
|
|
end
|
|
return out
|
|
end
|
|
if INOUT_EXCLUDE[f.name] then
|
|
return out
|
|
end
|
|
local params = params_of(f)
|
|
for i, p in ipairs(params) do
|
|
local pt = parse_type(p.type)
|
|
if pt.ptr == 1 and not pt.const and OUT_STRUCT[pt.base] then
|
|
out[i] = "inout"
|
|
end
|
|
end
|
|
return out
|
|
end
|
|
|
|
-- Convert Lua-friendly argument forms (string / table) to cdata without
|
|
-- reassigning the annotated parameter: doing that makes LuaLS warn with
|
|
-- cast-local-type. The result goes into an untyped local instead.
|
|
local function conversion_for(name, ptype, idx)
|
|
local pt = parse_type(ptype)
|
|
local var = "_a" .. idx
|
|
if pt.base == "unsigned char" and pt.ptr == 1 and pt.const then
|
|
return { arg = var, lines = {
|
|
"local " .. var,
|
|
'if type(' .. name .. ') == "string" then ' .. var .. ' = ffi.cast("const unsigned char *", ' .. name .. ")",
|
|
'elseif type(' .. name .. ') == "table" then ' .. var .. ' = to_array("unsigned char", ' .. name .. ")",
|
|
"else " .. var .. " = " .. name .. " end",
|
|
} }
|
|
end
|
|
if pt.base == "void" and pt.ptr == 1 then
|
|
return { arg = var, lines = {
|
|
"local " .. var,
|
|
'if type(' .. name .. ') == "string" then ' .. var .. ' = ffi.cast("const void *", ' .. name .. ")",
|
|
"else " .. var .. " = " .. name .. " end",
|
|
} }
|
|
end
|
|
if pt.base == "char" and pt.ptr == 2 then
|
|
-- raylib takes char** (non-const), but an array of const char* is what a
|
|
-- Lua table naturally builds; the cast is safe because these parameters
|
|
-- are read-only in practice.
|
|
local array = 'to_array("const char *", ' .. name .. ")"
|
|
if not pt.const then
|
|
array = 'ffi.cast("char **", ' .. array .. ")"
|
|
end
|
|
return { arg = var, lines = {
|
|
"local " .. var,
|
|
'if type(' .. name .. ') == "table" then ' .. var .. " = " .. array,
|
|
"else " .. var .. " = " .. name .. " end",
|
|
} }
|
|
end
|
|
if pt.const and pt.ptr == 1 and pt.base ~= "char" and pt.base ~= "void" then
|
|
return { arg = var, lines = {
|
|
"local " .. var,
|
|
'if type(' .. name .. ') == "table" then ' .. var .. ' = to_array("' .. pt.base .. '", ' .. name .. ")",
|
|
"else " .. var .. " = " .. name .. " end",
|
|
} }
|
|
end
|
|
return nil
|
|
end
|
|
|
|
----------------------------------------------------------------------------
|
|
-- emitted source
|
|
----------------------------------------------------------------------------
|
|
|
|
local out = {}
|
|
local function w(line)
|
|
out[#out + 1] = line or ""
|
|
end
|
|
|
|
local function clean_description(s)
|
|
if not s or s == "" then
|
|
return nil
|
|
end
|
|
s = s:gsub("%s+", " "):gsub("^ ", ""):gsub(" $", "")
|
|
return s
|
|
end
|
|
|
|
w("--[[")
|
|
w(" hate-no-d.lua - generated by gen-hate-no-d.lua, do not edit.")
|
|
w("")
|
|
w(" raylib " .. version .. " / rlgl / raymath")
|
|
w(" Functions: " .. tostring(#FUNCS))
|
|
w("")
|
|
w(" raymath symbols come from rcore.o (RAYMATH_IMPLEMENTATION) in libraylib.a.")
|
|
w("]]")
|
|
w("")
|
|
w('local ffi = require("ffi")')
|
|
w("")
|
|
w("ffi.cdef[[")
|
|
for _, name in ipairs(opaque_names) do
|
|
w("struct " .. name .. ";")
|
|
end
|
|
if #opaque_names > 0 then
|
|
w("")
|
|
end
|
|
|
|
for _, def in ipairs(ordered) do
|
|
if def.kind == "struct" then
|
|
w("typedef struct " .. def.name .. " {")
|
|
for _, f in ipairs(def.fields) do
|
|
w(" " .. c_field(f.type, f.name) .. ";")
|
|
end
|
|
w("} " .. def.name .. ";")
|
|
else
|
|
w("typedef " .. c_type(def.target) .. " " .. def.name .. ";")
|
|
end
|
|
w("")
|
|
end
|
|
|
|
for _, cb in ipairs({ CALLBACKS.AudioCallback, CALLBACKS.LoadFileDataCallback,
|
|
CALLBACKS.SaveFileDataCallback, CALLBACKS.LoadFileTextCallback,
|
|
CALLBACKS.SaveFileTextCallback }) do
|
|
if cb then
|
|
local args = {}
|
|
for _, p in ipairs(params_of(cb)) do
|
|
if parse_type(p.type).base == "..." then
|
|
args[#args + 1] = "..."
|
|
else
|
|
args[#args + 1] = c_type(p.type) .. " " .. p.name
|
|
end
|
|
end
|
|
if #args == 0 then
|
|
args[1] = "void"
|
|
end
|
|
w("typedef " .. c_type(cb.returnType) .. " (*" .. cb.name .. ")(" .. table.concat(args, ", ") .. ");")
|
|
w("")
|
|
end
|
|
end
|
|
|
|
for _, f in ipairs(FUNCS) do
|
|
if not is_skipped(f) then
|
|
local args = {}
|
|
for _, p in ipairs(params_of(f)) do
|
|
if parse_type(p.type).base == "..." then
|
|
args[#args + 1] = "..."
|
|
else
|
|
args[#args + 1] = c_type(p.type) .. " " .. p.name
|
|
end
|
|
end
|
|
if #args == 0 then
|
|
args[1] = "void"
|
|
end
|
|
w(c_type(f.returnType) .. " " .. f.name .. "(" .. table.concat(args, ", ") .. ");")
|
|
end
|
|
end
|
|
|
|
w("]]")
|
|
w("")
|
|
w("local C = ffi.C")
|
|
w("local string_format = string.format")
|
|
w("local ffi_string = ffi.string")
|
|
w("local type, select = type, select")
|
|
w("")
|
|
w("local M = {}")
|
|
w("")
|
|
w("-- Raw namespace for hot paths that want to skip the Lua wrapper.")
|
|
w("---@type ffi.namespace*")
|
|
w("M.C = C")
|
|
w("")
|
|
w("---@class raylib.char_buffer")
|
|
w("---@field [integer] integer")
|
|
w("")
|
|
w("---@class raylib.cstring_array")
|
|
w("---@field [integer] ffi.cdata*")
|
|
w("")
|
|
w("local pinned = {}")
|
|
w("local callback_cache = {}")
|
|
w("local function pin(ctype, fn)")
|
|
w(" if fn == nil then")
|
|
w(" return nil")
|
|
w(" end")
|
|
w(" local by_type = callback_cache[fn]")
|
|
w(" if by_type == nil then")
|
|
w(" by_type = {}")
|
|
w(" callback_cache[fn] = by_type")
|
|
w(" end")
|
|
w(" local cb = by_type[ctype]")
|
|
w(" if cb == nil then")
|
|
w(" cb = ffi.cast(ctype, fn)")
|
|
w(" by_type[ctype] = cb")
|
|
w(" pinned[#pinned + 1] = cb")
|
|
w(" end")
|
|
w(" return cb")
|
|
w("end")
|
|
w("")
|
|
w("local function to_array(ct, t, n)")
|
|
w(" n = n or #t")
|
|
w(' local a = ffi.new(ct .. "[?]", n)')
|
|
w(" for i = 1, n do")
|
|
w(" a[i - 1] = t[i]")
|
|
w(" end")
|
|
w(" return a")
|
|
w("end")
|
|
w("")
|
|
|
|
----------------------------------------------------------------------------
|
|
-- ownership runtime (emitted only when at least one owned type exists)
|
|
----------------------------------------------------------------------------
|
|
|
|
local function emit_ownership_preamble()
|
|
local owned_types = {}
|
|
for t in pairs(OWNED) do
|
|
owned_types[#owned_types + 1] = t
|
|
end
|
|
table.sort(owned_types)
|
|
|
|
local extra_types = {}
|
|
for t in pairs(EXTRA_OWNERS) do
|
|
extra_types[#extra_types + 1] = t
|
|
end
|
|
table.sort(extra_types)
|
|
|
|
local ptr_loaders = {}
|
|
for fn in pairs(OWNED_POINTER) do
|
|
if not SPECIAL[fn] then
|
|
ptr_loaders[#ptr_loaders + 1] = fn
|
|
end
|
|
end
|
|
table.sort(ptr_loaders)
|
|
|
|
w("-- ---------------------------------------------------------------------------")
|
|
w("-- Resource ownership")
|
|
w("--")
|
|
w("-- Owned struct values returned by raylib are armed with an FFI finalizer that")
|
|
w("-- calls the matching Unload* function. The finalizer only runs while the")
|
|
w("-- device it needs is still up, and GPU owners are pinned to the window")
|
|
w("-- generation they were created in. M.C stays raw: nothing is armed for direct")
|
|
w("-- ffi.C calls. See 'Resource ownership' in README.md.")
|
|
w("--")
|
|
w("-- One finalizer slot per cdata: a second ffi.gc() replaces the first. Never")
|
|
w("-- arm views/reference cdata (model.meshes[i], rt.texture, ...): only values")
|
|
w("-- that came straight out of a C return are owned.")
|
|
w("-- ---------------------------------------------------------------------------")
|
|
w("---@class raylib.ownership_stats")
|
|
w("---@field armed integer resources handed to the GC with a finalizer")
|
|
w("---@field released integer finalizers that actually freed a resource")
|
|
w("---@field skipped integer finalizers that refused (device gone / stale generation)")
|
|
w("---@field errors integer finalizers whose release call raised")
|
|
w("---@field gen integer current GPU generation (window instance)")
|
|
w("---@field reset fun()")
|
|
w("M._ownership = { armed = 0, released = 0, skipped = 0, errors = 0, gen = 0 }")
|
|
w("local _st = M._ownership")
|
|
w("function _st.reset()")
|
|
w(" _st.armed, _st.released, _st.skipped, _st.errors = 0, 0, 0, 0")
|
|
w("end")
|
|
w("")
|
|
w("local _gpu_gen = 0")
|
|
w('local _dead = setmetatable({}, { __mode = "k" })')
|
|
w('local _attached = setmetatable({}, { __mode = "k" })')
|
|
w("local _fin_cache = {}")
|
|
w("")
|
|
w("local _pins = {")
|
|
w(" shapes = nil,")
|
|
w(" shapes_prev = nil,")
|
|
w(" auto = nil,")
|
|
w(" material = {},")
|
|
w("}")
|
|
w("")
|
|
w("local function _can_unload(kind)")
|
|
w(' if kind == "gpu" then return C.IsWindowReady() end')
|
|
w(' if kind == "audio" then return C.IsAudioDeviceReady() end')
|
|
w(" return true")
|
|
w("end")
|
|
w("")
|
|
w("-- `keep` is the release function's optional second argument (owned extras,")
|
|
w("-- retained buffers). It is also an upvalue here, which is what keeps it alive")
|
|
w("-- until this finalizer runs: weak tables are cleared before finalizers, so a")
|
|
w("-- weak map cannot be used for keep-alive.")
|
|
w("local function _fire(kind, gen, release, x, keep)")
|
|
w(' if kind == "gpu" and gen ~= _gpu_gen then')
|
|
w(" _st.skipped = _st.skipped + 1")
|
|
w(" return")
|
|
w(" end")
|
|
w(" if not _can_unload(kind) then")
|
|
w(" _st.skipped = _st.skipped + 1")
|
|
w(" return")
|
|
w(" end")
|
|
w(" local ok = pcall(release, x, keep)")
|
|
w(" if ok then _st.released = _st.released + 1 else _st.errors = _st.errors + 1 end")
|
|
w(" -- keep is referenced here so the closure retains it until finalization.")
|
|
w(" if keep ~= nil then keep = nil end")
|
|
w("end")
|
|
w("")
|
|
w("-- One finalizer closure per (release, generation), not per object.")
|
|
w("local function _finalizer(kind, gen, release)")
|
|
w(" local by_gen = _fin_cache[release]")
|
|
w(" if by_gen == nil then")
|
|
w(" by_gen = {}")
|
|
w(" _fin_cache[release] = by_gen")
|
|
w(" end")
|
|
w(" local fin = by_gen[gen]")
|
|
w(" if fin == nil then")
|
|
w(" fin = function(x) _fire(kind, gen, release, x, nil) end")
|
|
w(" by_gen[gen] = fin")
|
|
w(" end")
|
|
w(" return fin")
|
|
w("end")
|
|
w("")
|
|
w("local function _arm(kind, release, valid, x, keep)")
|
|
w(" if x == nil then return x end")
|
|
w(" if valid ~= nil and not valid(x) then return x end")
|
|
w(" -- Pointer cdata is keyed by address, and the allocator reuses addresses")
|
|
w(" -- after a free: a stale _dead entry must never suppress this allocation.")
|
|
w(" _dead[x] = nil")
|
|
w(" _st.armed = _st.armed + 1")
|
|
w(" local gen = _gpu_gen")
|
|
w(" if keep ~= nil then")
|
|
w(" return ffi.gc(x, function(y) _fire(kind, gen, release, y, keep) end)")
|
|
w(" end")
|
|
w(" return ffi.gc(x, _finalizer(kind, gen, release))")
|
|
w("end")
|
|
w("")
|
|
w("local function _free_attached(x)")
|
|
w(" local extra = _attached[x]")
|
|
w(" if extra == nil then return nil end")
|
|
w(" _attached[x] = nil")
|
|
w(" for i = 1, #extra do C.MemFree(extra[i]) end")
|
|
w(" return extra")
|
|
w("end")
|
|
w("")
|
|
w("-- Raw pointer release: MemAlloc/MemRealloc and the loaders that hand back")
|
|
w("-- RL_MALLOC'd buffers (MemFree is free()).")
|
|
w("local function _release_raw(p)")
|
|
w(" if p == nil or _dead[p] then return end")
|
|
w(" _dead[p] = true")
|
|
w(" C.MemFree(p)")
|
|
w("end")
|
|
w("")
|
|
|
|
for _, t in ipairs(owned_types) do
|
|
local release = OWNED[t].release
|
|
if t == "Image" or t == "Font" then
|
|
w("local function _release_" .. t .. "(x, extra)")
|
|
w(" if _dead[x] then return end")
|
|
w(" _dead[x] = true")
|
|
w(" if extra == nil then extra = _attached[x] end")
|
|
w(" _attached[x] = nil")
|
|
w(" if extra ~= nil then")
|
|
w(" for i = 1, #extra do C.MemFree(extra[i]) end")
|
|
w(" end")
|
|
w(" C." .. release .. "(x)")
|
|
w(" ffi.fill(x, ffi.sizeof(x))")
|
|
w("end")
|
|
elseif t == "Texture" then
|
|
w("local function _release_Texture(x)")
|
|
w(" if _dead[x] then return end")
|
|
w(" _dead[x] = true")
|
|
w(" local prev = _pins.shapes_prev")
|
|
w(" if _pins.shapes ~= nil and _pins.shapes.id == x.id then")
|
|
w(" if prev ~= nil and prev.tex ~= nil and prev.tex.id ~= 0 and C.IsWindowReady() then")
|
|
w(" C.SetShapesTexture(prev.tex, prev.rec)")
|
|
w(" end")
|
|
w(" _pins.shapes = nil")
|
|
w(" _pins.shapes_prev = nil")
|
|
w(" end")
|
|
w(" C.UnloadTexture(x)")
|
|
w(" ffi.fill(x, ffi.sizeof(x))")
|
|
w("end")
|
|
elseif t == "Model" then
|
|
w("local function _release_Model(x)")
|
|
w(" if _dead[x] then return end")
|
|
w(" _dead[x] = true")
|
|
w(" if x.materials ~= nil then")
|
|
w(" for i = 0, x.materialCount - 1 do")
|
|
w(" local maps = x.materials[i].maps")
|
|
w(" if maps ~= nil then")
|
|
w(' _pins.material[tostring(ffi.cast("void *", maps))] = nil')
|
|
w(" end")
|
|
w(" end")
|
|
w(" end")
|
|
w(" C.UnloadModel(x)")
|
|
w(" ffi.fill(x, ffi.sizeof(x))")
|
|
w("end")
|
|
elseif t == "Material" then
|
|
w("-- UnloadMaterial() deletes the material's shader and map textures, which may")
|
|
w("-- be owned by separate Lua objects. The Material owner owns only its maps.")
|
|
w("local function _release_Material(x)")
|
|
w(" if _dead[x] then return end")
|
|
w(" _dead[x] = true")
|
|
w(" if x.maps ~= nil then")
|
|
w(' _pins.material[tostring(ffi.cast("void *", x.maps))] = nil')
|
|
w(" C.MemFree(x.maps)")
|
|
w(" end")
|
|
w(" ffi.fill(x, ffi.sizeof(x))")
|
|
w("end")
|
|
elseif t == "AutomationEventList" then
|
|
w("local function _release_AutomationEventList(x)")
|
|
w(" if _dead[x] then return end")
|
|
w(" _dead[x] = true")
|
|
w(" local pinned = _pins.auto")
|
|
w(" if pinned ~= nil and (pinned == x or (pinned.events ~= nil and pinned.events == x.events)) then")
|
|
w(" _pins.auto = nil")
|
|
w(" C.SetAutomationEventList(nil)")
|
|
w(" end")
|
|
w(" C.UnloadAutomationEventList(x)")
|
|
w(" ffi.fill(x, ffi.sizeof(x))")
|
|
w("end")
|
|
else
|
|
w("local function _release_" .. t .. "(x)")
|
|
w(" if _dead[x] then return end")
|
|
w(" _dead[x] = true")
|
|
w(" C." .. release .. "(x)")
|
|
w(" ffi.fill(x, ffi.sizeof(x))")
|
|
w("end")
|
|
end
|
|
w("")
|
|
end
|
|
|
|
for _, t in ipairs(extra_types) do
|
|
local release = EXTRA_OWNERS[t].release
|
|
w("local function _release_" .. t .. "(x)")
|
|
w(" if _dead[x] then return end")
|
|
w(" _dead[x] = true")
|
|
w(" C." .. release .. "(x)")
|
|
w(" ffi.fill(x, ffi.sizeof(x))")
|
|
w("end")
|
|
w("")
|
|
end
|
|
|
|
for _, fn in ipairs(ptr_loaders) do
|
|
local o = OWNED_POINTER[fn]
|
|
local relf = funcs_by_name[o.release]
|
|
local nparams = #params_of(relf)
|
|
if o.release == "MemFree" then
|
|
-- released through _release_raw
|
|
elseif o.per_item then
|
|
w("local function _release_" .. fn .. "(p, n)")
|
|
w(" if p == nil or _dead[p] then return end")
|
|
w(" _dead[p] = true")
|
|
w(" n = n or 0")
|
|
w(" for i = 0, n - 1 do C." .. o.release .. "(p[i]) end")
|
|
w(" C." .. (o.free or "MemFree") .. "(p)")
|
|
w("end")
|
|
w("")
|
|
else
|
|
w("local function _release_" .. fn .. "(p, n)")
|
|
w(" if p == nil or _dead[p] then return end")
|
|
w(" _dead[p] = true")
|
|
if nparams >= 2 then
|
|
w(" C." .. o.release .. "(p, n or 0)")
|
|
else
|
|
w(" C." .. o.release .. "(p)")
|
|
end
|
|
w("end")
|
|
w("")
|
|
end
|
|
end
|
|
|
|
local valid_types = {}
|
|
for _, t in ipairs(owned_types) do
|
|
if VALID[t] then
|
|
valid_types[#valid_types + 1] = t
|
|
end
|
|
end
|
|
for _, t in ipairs(extra_types) do
|
|
local v = EXTRA_OWNERS[t].valid
|
|
if v and VALID[v] then
|
|
valid_types[#valid_types + 1] = t
|
|
end
|
|
end
|
|
table.sort(valid_types)
|
|
for _, t in ipairs(valid_types) do
|
|
local v = VALID[t] or VALID[EXTRA_OWNERS[t].valid]
|
|
w("local function _valid_" .. t .. "(x) return " .. v .. " end")
|
|
end
|
|
if #valid_types > 0 then
|
|
w("")
|
|
end
|
|
|
|
local function owner_expr(t, keep)
|
|
local kind, release, valid
|
|
if OWNED[t] then
|
|
kind, release, valid = OWNED[t].kind, OWNED[t].release, VALID[t]
|
|
else
|
|
local e = EXTRA_OWNERS[t]
|
|
kind, release, valid = e.kind, e.release, VALID[e.valid]
|
|
end
|
|
local valid_arg = valid and ("_valid_" .. t) or "nil"
|
|
local args = "x"
|
|
if keep then
|
|
args = "x, keep"
|
|
end
|
|
return kind, release, valid_arg, args
|
|
end
|
|
|
|
for _, t in ipairs(owned_types) do
|
|
local kind, release, valid_arg, args = owner_expr(t, false)
|
|
w("local function _own_" .. t .. "(" .. args .. ")")
|
|
w(' return _arm("' .. kind .. '", _release_' .. t .. ", " .. valid_arg .. ", x)")
|
|
w("end")
|
|
w("")
|
|
end
|
|
|
|
-- keep variants: the retained object becomes a finalizer upvalue
|
|
local keep_types = {}
|
|
for _, k in pairs(KEEPS) do
|
|
if k.own then
|
|
keep_types[k.own] = true
|
|
end
|
|
end
|
|
local keep_order = {}
|
|
for t in pairs(keep_types) do
|
|
keep_order[#keep_order + 1] = t
|
|
end
|
|
table.sort(keep_order)
|
|
for _, t in ipairs(keep_order) do
|
|
local kind, release, valid_arg = owner_expr(t, true)
|
|
w("local function _own_" .. t .. "_keep(x, keep)")
|
|
w(' return _arm("' .. kind .. '", _release_' .. t .. ", " .. valid_arg .. ", x, keep)")
|
|
w("end")
|
|
w("")
|
|
end
|
|
|
|
for _, fn in ipairs(ptr_loaders) do
|
|
local o = OWNED_POINTER[fn]
|
|
local has_count = o.count ~= nil
|
|
local sig = has_count and "p, n" or "p"
|
|
local release = (o.release == "MemFree") and "_release_raw" or ("_release_" .. fn)
|
|
w("local function _own_ptr_" .. fn .. "(" .. sig .. ")")
|
|
if has_count then
|
|
-- The count is needed by the release call (UnloadFontData,
|
|
-- UnloadMaterials, UnloadModelAnimations, UnloadTextLines) and doubles as
|
|
-- the keep-alive upvalue that makes the closure per-object.
|
|
w(' return _arm("' .. o.kind .. '", ' .. release .. ", nil, p, n)")
|
|
else
|
|
w(' return _arm("' .. o.kind .. '", ' .. release .. ", nil, p)")
|
|
end
|
|
w("end")
|
|
w("")
|
|
end
|
|
|
|
w("local function _own_raw(p)")
|
|
w(' return _arm("ram", _release_raw, nil, p)')
|
|
w("end")
|
|
w("")
|
|
w("-- GenImageFontAtlas: the Rectangle* out-param belongs to the Image. The")
|
|
w("-- explicit-unload path finds it through _attached; the finalizer carries it")
|
|
w("-- as an upvalue (weak tables are cleared before finalizers run).")
|
|
w("local function _own_Image_extra(x, extra)")
|
|
w(" if extra == nil then return _own_Image(x) end")
|
|
w(" if x == nil or x.data == nil then")
|
|
w(" for i = 1, #extra do C.MemFree(extra[i]) end")
|
|
w(" return x")
|
|
w(" end")
|
|
w(" _attached[x] = extra")
|
|
w(" _st.armed = _st.armed + 1")
|
|
w(" local gen = _gpu_gen")
|
|
w(" return ffi.gc(x, function(y) _fire(\"ram\", gen, _release_Image, y, extra) end)")
|
|
w("end")
|
|
w("")
|
|
w("-- Ownership of a struct value moves to another object (LoadModelFromMesh):")
|
|
w("-- disarm it, mark it dead and zero it so a stale unload is a no-op.")
|
|
w("local function _consume(x)")
|
|
w(" if x == nil then return end")
|
|
w(" ffi.gc(x, nil)")
|
|
w(" _dead[x] = true")
|
|
w(" ffi.fill(x, ffi.sizeof(x))")
|
|
w("end")
|
|
w("")
|
|
w("local function _consume_ptr(p)")
|
|
w(" if p == nil then return end")
|
|
w(" ffi.gc(p, nil)")
|
|
w(" _dead[p] = true")
|
|
w("end")
|
|
w("")
|
|
end
|
|
|
|
if next(OWNED) then
|
|
emit_ownership_preamble()
|
|
end
|
|
|
|
----------------------------------------------------------------------------
|
|
-- constants
|
|
----------------------------------------------------------------------------
|
|
|
|
local enum_constants = {}
|
|
local seen_const = {}
|
|
|
|
for _, item in ipairs(apis) do
|
|
for _, enum in ipairs(item.data.enums or {}) do
|
|
w("---@enum raylib." .. enum.name)
|
|
w("M." .. enum.name .. " = {")
|
|
for _, v in ipairs(enum.values or {}) do
|
|
local value
|
|
if type(v.value) == "number" then
|
|
value = tostring(v.value)
|
|
elseif type(v.value) == "string" then
|
|
value = string.format("%q", v.value)
|
|
else
|
|
value = tostring(v.value)
|
|
end
|
|
w(" " .. v.name .. " = " .. value .. ",")
|
|
enum_constants[v.name] = enum.name
|
|
seen_const[v.name] = true
|
|
end
|
|
w("}")
|
|
w("")
|
|
end
|
|
end
|
|
|
|
for _, item in ipairs(apis) do
|
|
for _, enum in ipairs(item.data.enums or {}) do
|
|
for _, v in ipairs(enum.values or {}) do
|
|
w("---@type raylib." .. enum.name)
|
|
w("M." .. v.name .. " = M." .. enum.name .. "." .. v.name)
|
|
end
|
|
end
|
|
end
|
|
w("")
|
|
|
|
local alias_defines = {}
|
|
local pi_value = nil
|
|
|
|
local function eval_float_math(expr)
|
|
expr = expr:gsub("PI", tostring(pi_value or math.pi))
|
|
expr = expr:gsub("(%d)f", "%1")
|
|
local chunk = load("return " .. expr)
|
|
if not chunk then
|
|
return nil
|
|
end
|
|
local ok, value = pcall(chunk)
|
|
if not ok or type(value) ~= "number" then
|
|
return nil
|
|
end
|
|
return value
|
|
end
|
|
|
|
for _, item in ipairs(apis) do
|
|
for _, d in ipairs(item.data.defines or {}) do
|
|
if not seen_const[d.name] then
|
|
local dtype = d.type
|
|
local emitted = false
|
|
if dtype == "FLOAT" or dtype == "INT" then
|
|
if type(d.value) == "number" then
|
|
if d.name == "PI" then
|
|
pi_value = d.value
|
|
end
|
|
w("M." .. d.name .. " = " .. tostring(d.value))
|
|
emitted = true
|
|
end
|
|
elseif dtype == "FLOAT_MATH" then
|
|
local value = eval_float_math(tostring(d.value))
|
|
if value then
|
|
w("M." .. d.name .. " = " .. tostring(value))
|
|
emitted = true
|
|
end
|
|
elseif dtype == "STRING" then
|
|
w("M." .. d.name .. " = " .. string.format("%q", tostring(d.value)))
|
|
emitted = true
|
|
elseif dtype == "COLOR" then
|
|
local r, g, b, a = tostring(d.value):match("{%s*(%d+)%s*,%s*(%d+)%s*,%s*(%d+)%s*,%s*(%d+)%s*}")
|
|
if r then
|
|
w("---@type raylib.Color")
|
|
w(string.format('M.%s = ffi.new("Color", { r = %s, g = %s, b = %s, a = %s })',
|
|
d.name, r, g, b, a))
|
|
emitted = true
|
|
end
|
|
elseif dtype == "UNKNOWN" then
|
|
local target = tostring(d.value)
|
|
if target:match("^[A-Z_][A-Z0-9_]*$") then
|
|
alias_defines[#alias_defines + 1] = { name = d.name, target = target }
|
|
end
|
|
end
|
|
if emitted then
|
|
seen_const[d.name] = true
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
for _, a in ipairs(alias_defines) do
|
|
if seen_const[a.target] then
|
|
local enum = enum_constants[a.target]
|
|
if enum then
|
|
w("---@type raylib." .. enum)
|
|
end
|
|
w("M." .. a.name .. " = M." .. a.target)
|
|
end
|
|
end
|
|
w("")
|
|
|
|
----------------------------------------------------------------------------
|
|
-- struct / alias / callback annotations
|
|
----------------------------------------------------------------------------
|
|
|
|
for _, def in ipairs(ordered) do
|
|
local desc = clean_description(def.description)
|
|
if def.kind == "struct" then
|
|
if desc then
|
|
w("---" .. desc)
|
|
end
|
|
w("---@class raylib." .. def.name)
|
|
for _, f in ipairs(def.fields) do
|
|
local fdesc = clean_description(f.description)
|
|
local line = "---@field " .. f.name .. " " .. ann_field(f.type)
|
|
if fdesc then
|
|
line = line .. " " .. fdesc
|
|
end
|
|
w(line)
|
|
end
|
|
else
|
|
local pt = parse_type(def.target)
|
|
if pt.ptr > 0 then
|
|
w("---@alias raylib." .. def.name .. " ffi.cdata*")
|
|
else
|
|
w("---@alias raylib." .. def.name .. " raylib." .. pt.base)
|
|
end
|
|
end
|
|
w("")
|
|
end
|
|
|
|
for _, cb in ipairs({ CALLBACKS.AudioCallback, CALLBACKS.LoadFileDataCallback,
|
|
CALLBACKS.SaveFileDataCallback, CALLBACKS.LoadFileTextCallback,
|
|
CALLBACKS.SaveFileTextCallback }) do
|
|
if cb then
|
|
local parts = {}
|
|
for _, p in ipairs(params_of(cb)) do
|
|
local pt = parse_type(p.type)
|
|
local ann
|
|
if pt.base == "char" and pt.ptr == 1 then
|
|
ann = "string"
|
|
elseif pt.base == "void" and pt.ptr == 1 then
|
|
ann = "ffi.cdata*"
|
|
else
|
|
ann = ann_value(pt.base)
|
|
end
|
|
parts[#parts + 1] = (p.name or "arg") .. ": " .. ann
|
|
end
|
|
local ret = parse_type(cb.returnType)
|
|
local ret_ann = ""
|
|
if ret.base ~= "void" then
|
|
if ret.base == "char" and ret.ptr == 1 then
|
|
ret_ann = ": string"
|
|
else
|
|
ret_ann = ": " .. ann_return(cb.returnType)
|
|
end
|
|
end
|
|
w("---@alias raylib." .. cb.name .. " fun(" .. table.concat(parts, ", ") .. ")" .. ret_ann)
|
|
w("")
|
|
end
|
|
end
|
|
|
|
----------------------------------------------------------------------------
|
|
-- wrappers
|
|
----------------------------------------------------------------------------
|
|
|
|
local LUA_KEYWORDS = {
|
|
["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true,
|
|
["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true,
|
|
["function"] = true, ["if"] = true, ["in"] = true, ["local"] = true,
|
|
["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true,
|
|
["return"] = true, ["then"] = true, ["true"] = true, ["until"] = true,
|
|
["while"] = true,
|
|
}
|
|
|
|
local function lua_name(name)
|
|
if LUA_KEYWORDS[name] then
|
|
return name .. "_"
|
|
end
|
|
return name
|
|
end
|
|
|
|
-- Explicit unload functions: disarm the finalizer, then release through the
|
|
-- same idempotent helper the finalizer uses.
|
|
local RELEASE_OWNER = {}
|
|
for t, o in pairs(OWNED) do
|
|
RELEASE_OWNER[o.release] = t
|
|
end
|
|
for t, e in pairs(EXTRA_OWNERS) do
|
|
RELEASE_OWNER[e.release] = t
|
|
end
|
|
|
|
local POINTER_RELEASE = {}
|
|
for fn, o in pairs(OWNED_POINTER) do
|
|
if o.release ~= "MemFree" and not RELEASE_OWNER[o.release] then
|
|
POINTER_RELEASE[o.release] = fn
|
|
end
|
|
end
|
|
|
|
local emitted_wrappers = 0
|
|
|
|
local function emit_special(f)
|
|
local desc = clean_description(f.description)
|
|
if f.name == "TextFormat" then
|
|
w("---" .. (desc or "Text formatting"))
|
|
w("---@param fmt string")
|
|
w("---@param ... any")
|
|
w("---@return string")
|
|
w("function M.TextFormat(fmt, ...)")
|
|
w(' if select("#", ...) == 0 then')
|
|
w(" return fmt")
|
|
w(" end")
|
|
w(" return string_format(fmt, ...)")
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "TraceLog" then
|
|
w("---" .. (desc or "Show trace log messages"))
|
|
w("---@param level integer")
|
|
w("---@param fmt string")
|
|
w("---@param ... any")
|
|
w("---@return nil")
|
|
w("function M.TraceLog(level, fmt, ...)")
|
|
w(' if select("#", ...) == 0 then')
|
|
w(' C.TraceLog(level, "%s", fmt)')
|
|
w(" else")
|
|
w(' C.TraceLog(level, "%s", string_format(fmt, ...))')
|
|
w(" end")
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "CodepointToUTF8" then
|
|
w("---" .. (desc or "Encode a codepoint"))
|
|
w("---@param codepoint integer")
|
|
w("---@return string|nil")
|
|
w("function M.CodepointToUTF8(codepoint)")
|
|
w(' local size = ffi.new("int[1]")')
|
|
w(" local p = C.CodepointToUTF8(codepoint, size)")
|
|
w(" if p == nil then return nil end")
|
|
w(" return ffi_string(p, size[0])")
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "GenImageFontAtlas" then
|
|
w("---" .. (desc or "Generate image font atlas using chars info"))
|
|
w("---@param glyphs raylib.GlyphInfo[]|ffi.cdata*")
|
|
w("---@param glyphCount integer")
|
|
w("---@param fontSize integer")
|
|
w("---@param padding integer")
|
|
w("---@param packMethod integer")
|
|
w("---@return raylib.Image, ffi.cdata*")
|
|
w("-- NOTE: the Rectangle* out-param belongs to the returned Image and is")
|
|
w("-- released with it; the second result is a borrowed view.")
|
|
w("function M.GenImageFontAtlas(glyphs, glyphCount, fontSize, padding, packMethod)")
|
|
w(" local _a1")
|
|
w(' if type(glyphs) == "table" then _a1 = to_array("GlyphInfo", glyphs) else _a1 = glyphs end')
|
|
w(' local _recs = ffi.new("Rectangle *[1]")')
|
|
w(" local _img = C.GenImageFontAtlas(_a1, _recs, glyphCount, fontSize, padding, packMethod)")
|
|
w(" if _recs[0] == nil then")
|
|
w(" return _own_Image(_img), nil")
|
|
w(" end")
|
|
w(' return _own_Image_extra(_img, { ffi.cast("void *", _recs[0]) }), _recs[0]')
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "LoadModelFromMesh" then
|
|
w("---" .. (desc or "Load model from generated mesh"))
|
|
w("---@param mesh raylib.Mesh")
|
|
w("---@return raylib.Model")
|
|
w("-- NOTE: the mesh's data becomes part of the model; the mesh is consumed")
|
|
w("-- (disarmed and zeroed), so a later UnloadMesh(mesh) is a no-op.")
|
|
w("function M.LoadModelFromMesh(mesh)")
|
|
w(" local _r = C.LoadModelFromMesh(mesh)")
|
|
w(" local _o = _own_Model(_r)")
|
|
w(" if _r.meshCount > 0 then _consume(mesh) end")
|
|
w(" return _o")
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "LoadSoundAlias" then
|
|
w("---" .. (desc or "Load sound alias sharing same sample data"))
|
|
w("---@param source raylib.Sound")
|
|
w("---@return raylib.Sound")
|
|
w("-- NOTE: the alias shares the source's sample data; the source is kept")
|
|
w("-- alive until the alias is released, and the alias is released with")
|
|
w("-- UnloadSoundAlias (not UnloadSound).")
|
|
w("function M.LoadSoundAlias(source)")
|
|
w(" return _own_SoundAlias_keep(C.LoadSoundAlias(source), source)")
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "LoadMusicStreamFromMemory" then
|
|
w("---" .. (desc or "Load music stream from data"))
|
|
w("---@param fileType string")
|
|
w("---@param data string|integer[]|ffi.cdata*")
|
|
w("---@param dataSize integer")
|
|
w("---@return raylib.Music")
|
|
w("-- NOTE: raylib retains the buffer; it is kept alive until the Music is")
|
|
w("-- released (a finalizer upvalue, not a weak map).")
|
|
w("function M.LoadMusicStreamFromMemory(fileType, data, dataSize)")
|
|
w(" local _a2")
|
|
w(' if type(data) == "string" then _a2 = ffi.cast("const unsigned char *", data)')
|
|
w(' elseif type(data) == "table" then _a2 = to_array("unsigned char", data)')
|
|
w(" else _a2 = data end")
|
|
w(" return _own_Music_keep(C.LoadMusicStreamFromMemory(fileType, _a2, dataSize), _a2)")
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "SetShapesTexture" then
|
|
w("---" .. (desc or "Set texture and rectangle to be used on shapes drawing"))
|
|
w("---@param texture raylib.Texture2D")
|
|
w("---@param rec raylib.Rectangle|ffi.cdata*")
|
|
w("---@return nil")
|
|
w("function M.SetShapesTexture(texture, rec)")
|
|
w(' if type(rec) == "table" then rec = ffi.new("Rectangle", rec) end')
|
|
w(" if C.IsWindowReady() then")
|
|
w(" _pins.shapes_prev = { tex = C.GetShapesTexture(), rec = C.GetShapesTextureRectangle() }")
|
|
w(" end")
|
|
w(" _pins.shapes = texture")
|
|
w(" C.SetShapesTexture(texture, rec)")
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "SetAutomationEventList" then
|
|
w("---" .. (desc or "Set automation event list to record to"))
|
|
w("---@param list? raylib.AutomationEventList")
|
|
w("---@return nil")
|
|
w("-- NOTE: raylib stores the pointer, so the list is pinned until it is")
|
|
w("-- unloaded or replaced (previously this passed a temporary array).")
|
|
w("function M.SetAutomationEventList(list)")
|
|
w(" if list == nil then")
|
|
w(" _pins.auto = nil")
|
|
w(" C.SetAutomationEventList(nil)")
|
|
w(" return")
|
|
w(" end")
|
|
w(" _pins.auto = list")
|
|
w(' C.SetAutomationEventList(ffi.cast("AutomationEventList *", list))')
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "SetMaterialTexture" then
|
|
w("---" .. (desc or "Set texture for a material map type"))
|
|
w("---@param material raylib.Material")
|
|
w("---@param mapType integer")
|
|
w("---@param texture raylib.Texture2D")
|
|
w("---@return nil")
|
|
w("-- NOTE: the texture is pinned by the material's maps address (the material")
|
|
w("-- may be a reference cdata such as model.materials[i]).")
|
|
w("function M.SetMaterialTexture(material, mapType, texture)")
|
|
w(" if material.maps ~= nil then")
|
|
w(' _pins.material[tostring(ffi.cast("void *", material.maps))] = texture')
|
|
w(" end")
|
|
w(' C.SetMaterialTexture(ffi.cast("Material *", material), mapType, texture)')
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "SetWindowIcons" then
|
|
w("---" .. (desc or "Set window icons"))
|
|
w("---@param images raylib.Image[]|ffi.cdata*")
|
|
w("---@param count integer")
|
|
w("---@return nil")
|
|
w("function M.SetWindowIcons(images, count)")
|
|
w(" local _a1")
|
|
w(' if type(images) == "table" then _a1 = to_array("Image", images) else _a1 = images end')
|
|
w(" C.SetWindowIcons(_a1, count)")
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "MemAlloc" then
|
|
w("---" .. (desc or "Internal memory allocator"))
|
|
w("---@param size integer")
|
|
w("---@return ffi.cdata*")
|
|
w("function M.MemAlloc(size)")
|
|
w(" return _own_raw(C.MemAlloc(size))")
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "MemRealloc" then
|
|
w("---" .. (desc or "Internal memory reallocator"))
|
|
w("---@param ptr ffi.cdata*")
|
|
w("---@param size integer")
|
|
w("---@return ffi.cdata*")
|
|
w("function M.MemRealloc(ptr, size)")
|
|
w(" _consume_ptr(ptr)")
|
|
w(" return _own_raw(C.MemRealloc(ptr, size))")
|
|
w("end")
|
|
w("")
|
|
elseif f.name == "MemFree" then
|
|
w("---" .. (desc or "Internal memory free"))
|
|
w("---@param ptr ffi.cdata*")
|
|
w("---@return nil")
|
|
w("function M.MemFree(ptr)")
|
|
w(" if ptr == nil then return end")
|
|
w(" ffi.gc(ptr, nil)")
|
|
w(" _release_raw(ptr)")
|
|
w("end")
|
|
w("")
|
|
end
|
|
emitted_wrappers = emitted_wrappers + 1
|
|
end
|
|
|
|
local function emit_function(f)
|
|
local params = params_of(f)
|
|
local outs = out_params(f)
|
|
local cls = CLASS[f.name]
|
|
if cls == nil then
|
|
die("no ownership classification for %s", f.name)
|
|
end
|
|
|
|
local sig = {}
|
|
local pre = {}
|
|
local args = {}
|
|
local arg_ann = {}
|
|
local out_vars = {}
|
|
local out_ann = {}
|
|
local arg_expr = {}
|
|
local raw_names = {}
|
|
|
|
local ptr_info = OWNED_POINTER[f.name]
|
|
local count_idx = nil
|
|
if ptr_info and ptr_info.count and not SPECIAL[f.name] then
|
|
for i, p in ipairs(params) do
|
|
if p.name == ptr_info.count then
|
|
count_idx = i
|
|
end
|
|
end
|
|
end
|
|
|
|
for i, p in ipairs(params) do
|
|
local pt = parse_type(p.type)
|
|
local name = lua_name(p.name)
|
|
raw_names[i] = name
|
|
if pt.base == "..." then
|
|
sig[#sig + 1] = "..."
|
|
args[#args + 1] = "..."
|
|
arg_expr[i] = "..."
|
|
arg_ann[#arg_ann + 1] = "---@param ... any"
|
|
elseif i == count_idx then
|
|
-- Optional count out-param: allocate it internally and hand the value
|
|
-- back as an extra return value. A caller-supplied cdata is filled too.
|
|
local var = "_n" .. i
|
|
pre[#pre + 1] = 'local ' .. var .. ' = ffi.new("' .. pt.base .. '[1]")'
|
|
if ptr_info.init_count then
|
|
pre[#pre + 1] = var .. "[0] = 0"
|
|
end
|
|
sig[#sig + 1] = name
|
|
args[#args + 1] = var
|
|
arg_expr[i] = var
|
|
arg_ann[#arg_ann + 1] = "---@param " .. name .. "? ffi.cdata*"
|
|
elseif outs[i] then
|
|
local var = "_o" .. i
|
|
if outs[i] == "inout" and OWNED[canon(pt.base)] then
|
|
-- Mutate in place and return the same cdata: raylib's own Image* /
|
|
-- Mesh* contract. Copying here loses reallocations (double free).
|
|
arg_ann[#arg_ann + 1] = "---@param " .. name .. " raylib." .. pt.base
|
|
args[#args + 1] = 'ffi.cast("' .. pt.base .. ' *", ' .. name .. ')'
|
|
arg_expr[i] = name
|
|
out_vars[#out_vars + 1] = name
|
|
out_ann[#out_ann + 1] = "---@return raylib." .. pt.base
|
|
elseif outs[i] == "inout" then
|
|
pre[#pre + 1] = 'local ' .. var .. ' = ffi.new("' .. pt.base .. '[1]", ' .. name .. ')'
|
|
arg_ann[#arg_ann + 1] = "---@param " .. name .. " raylib." .. pt.base
|
|
args[#args + 1] = var
|
|
arg_expr[i] = var
|
|
out_vars[#out_vars + 1] = var .. "[0]"
|
|
out_ann[#out_ann + 1] = "---@return raylib." .. pt.base
|
|
else
|
|
pre[#pre + 1] = 'local ' .. var .. ' = ffi.new("' .. pt.base .. '[1]")'
|
|
pre[#pre + 1] = "if " .. name .. " ~= nil then " .. var .. "[0] = " .. name .. " end"
|
|
arg_ann[#arg_ann + 1] = "---@param " .. name .. "? raylib." .. pt.base
|
|
args[#args + 1] = var
|
|
arg_expr[i] = var
|
|
out_vars[#out_vars + 1] = var .. "[0]"
|
|
out_ann[#out_ann + 1] = "---@return raylib." .. pt.base
|
|
end
|
|
sig[#sig + 1] = name
|
|
else
|
|
sig[#sig + 1] = name
|
|
arg_ann[#arg_ann + 1] = "---@param " .. name .. " " .. ann_param(p, false)
|
|
|
|
if CALLBACKS[pt.base] then
|
|
local var = "_cb" .. i
|
|
pre[#pre + 1] = "local " .. var .. ' = pin("' .. pt.base .. '", ' .. name .. ")"
|
|
args[#args + 1] = var
|
|
arg_expr[i] = var
|
|
else
|
|
local conv = conversion_for(name, p.type, i)
|
|
if conv then
|
|
for _, line in ipairs(conv.lines) do
|
|
pre[#pre + 1] = line
|
|
end
|
|
args[#args + 1] = conv.arg
|
|
arg_expr[i] = conv.arg
|
|
else
|
|
args[#args + 1] = name
|
|
arg_expr[i] = name
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
local desc = clean_description(f.description)
|
|
if desc then
|
|
w("---" .. desc)
|
|
end
|
|
if EXTRA_DOC[f.name] then
|
|
w("---" .. EXTRA_DOC[f.name])
|
|
end
|
|
for _, line in ipairs(arg_ann) do
|
|
w(line)
|
|
end
|
|
if #out_vars > 0 then
|
|
for _, line in ipairs(out_ann) do
|
|
w(line)
|
|
end
|
|
elseif count_idx then
|
|
w("---@return ffi.cdata*, integer")
|
|
elseif parse_type(f.returnType).base == "void" and parse_type(f.returnType).ptr == 0 then
|
|
w("---@return nil")
|
|
else
|
|
w("---@return " .. ann_return(f.returnType))
|
|
end
|
|
|
|
-- Explicit unload: disarm, then release through the idempotent helper.
|
|
local owner = RELEASE_OWNER[f.name]
|
|
local powner = POINTER_RELEASE[f.name]
|
|
if owner or powner then
|
|
local first = raw_names[1]
|
|
w("function M." .. f.name .. "(" .. table.concat(sig, ", ") .. ")")
|
|
w(" if " .. first .. " == nil then return end")
|
|
w(" ffi.gc(" .. first .. ", nil)")
|
|
local kind = owner and
|
|
((OWNED[owner] and OWNED[owner].kind) or
|
|
(EXTRA_OWNERS[owner] and EXTRA_OWNERS[owner].kind))
|
|
-- Material/VrStereoConfig only free RAM (maps / nothing), so they must run
|
|
-- even after the GPU context is gone.
|
|
if (kind == "gpu" or kind == "audio") and
|
|
owner ~= "Material" and owner ~= "VrStereoConfig" then
|
|
w(' if not _can_unload("' .. kind .. '") then')
|
|
w(" _dead[" .. first .. "] = true")
|
|
w(" ffi.fill(" .. first .. ", ffi.sizeof(" .. first .. "))")
|
|
w(" return")
|
|
w(" end")
|
|
end
|
|
w(" if not _dead[" .. first .. "] then")
|
|
if owner then
|
|
w(" _release_" .. owner .. "(" .. first .. ")")
|
|
else
|
|
w(" _release_" .. powner .. "(" .. table.concat(raw_names, ", ") .. ")")
|
|
end
|
|
w(" _st.released = _st.released + 1")
|
|
w(" end")
|
|
w("end")
|
|
w("")
|
|
emitted_wrappers = emitted_wrappers + 1
|
|
return
|
|
end
|
|
|
|
w("function M." .. f.name .. "(" .. table.concat(sig, ", ") .. ")")
|
|
for _, line in ipairs(pre) do
|
|
w(" " .. line)
|
|
end
|
|
|
|
local call = "C." .. f.name .. "(" .. table.concat(args, ", ") .. ")"
|
|
local ret = parse_type(f.returnType)
|
|
local post = POST_CALL[f.name]
|
|
|
|
if #out_vars > 0 then
|
|
w(" " .. call)
|
|
if post then
|
|
w(" " .. post)
|
|
end
|
|
w(" return " .. table.concat(out_vars, ", "))
|
|
elseif ret.base == "void" and ret.ptr == 0 then
|
|
w(" " .. call)
|
|
if post then
|
|
w(" " .. post)
|
|
end
|
|
elseif ret.base == "char" and ret.ptr == 1 then
|
|
w(" local _p = " .. call)
|
|
w(" if _p == nil then")
|
|
w(" return nil")
|
|
w(" end")
|
|
w(" local _s = ffi_string(_p)")
|
|
if cls.bucket == "owned_string" then
|
|
w(" C." .. cls.release .. "(_p)")
|
|
end
|
|
w(" return _s")
|
|
elseif cls.bucket == "owned_pointer" then
|
|
if count_idx then
|
|
local cname = raw_names[count_idx]
|
|
local nvar = "_n" .. count_idx
|
|
w(" local _p = " .. call)
|
|
w(" local _c = " .. nvar .. "[0]")
|
|
w(" if " .. cname .. " ~= nil then " .. cname .. "[0] = _c end")
|
|
w(" return _own_ptr_" .. f.name .. "(_p, _c), _c")
|
|
else
|
|
w(" return _own_ptr_" .. f.name .. "(" .. call .. ")")
|
|
end
|
|
elseif cls.bucket == "owned" then
|
|
local consumes = CONSUMES[f.name]
|
|
local keeps = KEEPS[f.name]
|
|
if consumes then
|
|
local idx
|
|
for i, p in ipairs(params) do
|
|
if p.name == consumes.param then
|
|
idx = i
|
|
end
|
|
end
|
|
w(" local _r = " .. call)
|
|
w(" local _o = _own_" .. cls.type .. "(_r)")
|
|
w(" if _r." .. consumes.valid_field .. " > 0 then _consume(" .. raw_names[idx] .. ") end")
|
|
w(" return _o")
|
|
elseif keeps then
|
|
local idx
|
|
for i, p in ipairs(params) do
|
|
if p.name == keeps.keep then
|
|
idx = i
|
|
end
|
|
end
|
|
w(" return _own_" .. keeps.own .. "_keep(" .. call .. ", " .. arg_expr[idx] .. ")")
|
|
else
|
|
w(" return _own_" .. cls.type .. "(" .. call .. ")")
|
|
end
|
|
else
|
|
w(" return " .. call)
|
|
end
|
|
w("end")
|
|
w("")
|
|
emitted_wrappers = emitted_wrappers + 1
|
|
end
|
|
|
|
for _, f in ipairs(FUNCS) do
|
|
if not is_skipped(f) then
|
|
if SPECIAL[f.name] then
|
|
emit_special(f)
|
|
else
|
|
emit_function(f)
|
|
end
|
|
end
|
|
end
|
|
|
|
w("return M")
|
|
|
|
----------------------------------------------------------------------------
|
|
-- write
|
|
----------------------------------------------------------------------------
|
|
|
|
-- A pure --dump-ownership run (no explicit --out) only produces the map; it
|
|
-- must not rewrite the binding as a side effect.
|
|
local write_binding = not (CFG.dump_ownership and not CFG.out_explicit)
|
|
if write_binding then
|
|
local text = table.concat(out, "\n") .. "\n"
|
|
local file, err = io.open(CFG.out, "wb")
|
|
if not file then
|
|
die("cannot write %s: %s", CFG.out, err)
|
|
return
|
|
end
|
|
file:write(text)
|
|
file:close()
|
|
|
|
local n_struct, n_alias, n_cb = 0, 0, 0
|
|
for _, d in ipairs(ordered) do
|
|
if d.kind == "struct" then
|
|
n_struct = n_struct + 1
|
|
else
|
|
n_alias = n_alias + 1
|
|
end
|
|
end
|
|
for _ in pairs(CALLBACKS) do
|
|
n_cb = n_cb + 1
|
|
end
|
|
io.stderr:write(string.format(
|
|
"gen-hate-no-d: wrote %s (%d functions, %d structs, %d aliases, %d callbacks, %d lines)\n",
|
|
CFG.out, emitted_wrappers, n_struct, n_alias, n_cb, #out))
|
|
end
|
|
|
|
if CFG.dump_ownership then
|
|
local map = ownership_map()
|
|
if CFG.dump_ownership == true then
|
|
io.write(map)
|
|
else
|
|
local dump, derr = io.open(CFG.dump_ownership, "wb")
|
|
if not dump then
|
|
die("cannot write %s: %s", CFG.dump_ownership, derr)
|
|
return
|
|
end
|
|
dump:write(map)
|
|
dump:close()
|
|
end
|
|
end
|
|
|
|
local counts = ownership_summary()
|
|
io.stderr:write(string.format(
|
|
"gen-hate-no-d: ownership: %d owned-struct callsites, %d owned pointers, " ..
|
|
"%d owned strings, %d borrowed structs, %d borrowed statics, " ..
|
|
"%d borrowed strings, %d value structs, %d non-owning\n",
|
|
counts.owned, counts.owned_pointer, counts.owned_string, counts.borrowed,
|
|
counts.borrowed_static, counts.borrowed_string, counts.value, counts.non_owning))
|