bindings: GLFW and Vulkan, generated with snake_case names
`use glfw` and `use vulkan` load the native libraries and expose every function with a snake_case name, plus constants, struct sizes and field offsets. Generated from the official headers/registry, not hand-written: - tools/gen_glfw.py: parses glfw3.h -> std/glfw/glfw.cat (124 fns + GLFW_* constants + GLFWvidmode/GLFWgammaramp offsets). - tools/gen_vulkan.py: parses vk.xml -> std/vulkan/vulkan.cat (650 commands + 1454 struct sizes/offsets + enum constants), with a recursive x86-64 layout engine that resolves nested structs and macro-sized arrays (sizes verified against the C headers). - ffi: `memory` values pass their address where a pointer is expected; `ffi.pointer(addr, name, sig)` binds a call at a raw address (Vulkan dispatch). `VkResult`/enum returns are ints. - compiler: a keyword is allowed as a member name after `.` / method-call position (glfw.false, glfw.visible). - vendor/lib/libglfw.so.3: the host has no libglfw, so it is vendored. Proved live: GLFW 3.4 window + framebuffer under xvfb-run; a Vulkan 1.0 instance + physical-device enumeration on lavapipe (headless). tests/glfw.cat, tests/vulkan.cat wired into the suite (125 green).
This commit is contained in:
1 parent
210054f46c
commit
04009c3c5e
18 files changed
+13539
-2
No files matched your search
@@ -275,6 +275,58 @@ Gramática da assinatura: `RET(ARG,ARG,...)`, com tipos `void`, `bool`,
|
||||
|
||||
Requer `-lffi -ldl` (já no Makefile).
|
||||
|
||||
## `memory` — buffers com limites verificados
|
||||
|
||||
Para passar **structs** ao código nativo (GLFW, Vulkan, ...), `memory(n)`
|
||||
aloca um buffer de n bytes cujo acesso é todo verificado:
|
||||
|
||||
```lua
|
||||
local m = memory(16)
|
||||
m:set_u32(0, 1234)
|
||||
print(m:u32(0)) -- 1234
|
||||
m:set_text(4, "hi") -- "hi" + NUL em 4..6
|
||||
print(m:text(4)) -- hi
|
||||
m:ptr() -- endereço, para uma chamada FFI
|
||||
```
|
||||
|
||||
Campos: `u8..u64`, `i8..i64`, `f32`, `f64`, `text`, `set_*`, `ptr`,
|
||||
`size`, `fill`, `copy`. Um acesso fora dos limites **levanta erro** em
|
||||
vez de corromper a memória. Um valor `memory` passado onde se espera um
|
||||
ponteiro entrega o endereço do buffer. Literais `0x`/`0b`/`0o` também
|
||||
são aceitos (`0xAB`, `0b1010`).
|
||||
|
||||
## Bindings GLFW e Vulkan
|
||||
|
||||
`std/glfw` e `std/vulkan` são gerados dos headers/registry oficiais
|
||||
(`tools/gen_glfw.py`, `tools/gen_vulkan.py`) e expõem nomes
|
||||
**snake_case**:
|
||||
|
||||
```lua
|
||||
use glfw
|
||||
local v = memory(12)
|
||||
glfw.get_version(v, v:ptr() + 4, v:ptr() + 8) -- 3 4 0
|
||||
glfw.init()
|
||||
glfw.window_hint(glfw.visible, glfw.false)
|
||||
glfw.window_hint(0x00022001, 0) -- CLIENT_API = NO_API
|
||||
local win = glfw.create_window(320, 240, "cat", 0, 0)
|
||||
|
||||
use vulkan
|
||||
local ai = memory(vulkan.size_vk_application_info)
|
||||
ai:fill(0)
|
||||
ai:set_u32(0, vulkan.structure_type_application_info)
|
||||
ai:set_u32(24, 0x00400000)
|
||||
local ci = memory(vulkan.size_vk_instance_create_info)
|
||||
ci:fill(0)
|
||||
ci:set_u32(0, vulkan.structure_type_instance_create_info)
|
||||
ci:set_u64(24, ai:ptr())
|
||||
local inst = memory(8)
|
||||
vulkan.create_instance(ci, 0, inst) -- VK_SUCCESS
|
||||
```
|
||||
|
||||
Vulkan roda **headless** (lavapipe/llvmpipe); GLFW precisa de um display
|
||||
(`xvfb-run` no CI). O modele expõe comandos, tamanhos de struct
|
||||
(`vulkan.size_vk_*`), offsets de campos e constantes.
|
||||
|
||||
## Funções também são objetos
|
||||
|
||||
Uma closure tem sua própria tabela de membros, então carrega `_doc_` (e
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
-- examples/glfw.cat -- open a window with the generated GLFW bindings.
|
||||
-- Run: LD_LIBRARY_PATH=vendor/lib xvfb-run -a catscript examples/glfw.cat
|
||||
--
|
||||
-- `use glfw` loads libglfw and binds every GLFWAPI function with a
|
||||
-- snake_case name (glfw.init, glfw.create_window, ...), plus GLFW_*
|
||||
-- constants and struct offsets. Needs a display; run with xvfb-run.
|
||||
|
||||
use glfw
|
||||
|
||||
local version = memory(12)
|
||||
glfw.get_version(version, version:ptr() + 4, version:ptr() + 8)
|
||||
print("glfw:", version:u32(0), version:u32(4), version:u32(8))
|
||||
|
||||
local ok = glfw.init()
|
||||
print("init:", ok)
|
||||
|
||||
-- a hidden window with no client API (for Vulkan surfaces)
|
||||
glfw.window_hint(glfw.visible, glfw.false)
|
||||
glfw.window_hint(0x00022001, 0) -- CLIENT_API = NO_API
|
||||
local win = glfw.create_window(320, 240, "cat", 0, 0)
|
||||
print("window:", win > 0)
|
||||
|
||||
if win > 0 then
|
||||
local fw = memory(8)
|
||||
local fh = memory(8)
|
||||
glfw.get_framebuffer_size(win, fw, fh)
|
||||
print("framebuffer:", fw:u32(0), fh:u32(0))
|
||||
print("should close:", glfw.window_should_close(win) == glfw.true)
|
||||
glfw.destroy_window(win)
|
||||
end
|
||||
|
||||
glfw.terminate()
|
||||
print("done")
|
||||
@@ -0,0 +1,31 @@
|
||||
-- examples/vulkan.cat -- create a Vulkan instance (headless, lavapipe).
|
||||
-- Run: catscript examples/vulkan.cat
|
||||
--
|
||||
-- `use vulkan` loads libvulkan and binds the core commands with
|
||||
-- snake_case names, plus struct sizes (vulkan.size_vk_*) and constants.
|
||||
-- Vulkan runs on a software device (llvmpipe/lavapipe) with no display.
|
||||
|
||||
use vulkan
|
||||
|
||||
-- VkApplicationInfo
|
||||
local ai = memory(vulkan.size_vk_application_info)
|
||||
ai:fill(0)
|
||||
ai:set_u32(0, vulkan.structure_type_application_info)
|
||||
ai:set_u32(24, 0x00400000) -- apiVersion 1.0.0
|
||||
|
||||
-- VkInstanceCreateInfo
|
||||
local ci = memory(vulkan.size_vk_instance_create_info)
|
||||
ci:fill(0)
|
||||
ci:set_u32(0, vulkan.structure_type_instance_create_info)
|
||||
ci:set_u64(24, ai:ptr()) -- pApplicationInfo
|
||||
|
||||
local inst = memory(8)
|
||||
local r = vulkan.create_instance(ci, 0, inst)
|
||||
print("create_instance:", r == vulkan.success)
|
||||
|
||||
local n = memory(4)
|
||||
vulkan.enumerate_physical_devices(inst:u64(0), n, 0)
|
||||
print("devices > 0:", n:u32(0) > 0)
|
||||
|
||||
vulkan.destroy_instance(inst:u64(0), 0)
|
||||
print("done")
|
||||
@@ -58,6 +58,11 @@ CAT_VALUE_Value *cat_types_ffi_load(const char *path);
|
||||
CAT_VALUE_Value *cat_types_ffi_bind(CAT_VALUE_Value *lib, const char *name,
|
||||
const char *sig);
|
||||
|
||||
/* Bind a call at a raw address (e.g. a Vulkan function pointer returned
|
||||
* by vkGetDeviceProcAddr). Returns a callable Function value. */
|
||||
CAT_VALUE_Value *cat_types_ffi_bind_addr(unsigned long long addr,
|
||||
const char *name, const char *sig);
|
||||
|
||||
/* Build the `ffi` module table (with `load`). */
|
||||
CAT_VALUE_Value *cat_types_ffi_module(void);
|
||||
|
||||
|
||||
+9
-2
@@ -400,7 +400,11 @@ static void primary(Compiler *c)
|
||||
for (;;) {
|
||||
if (check(c, CAT_LEXER_TOK_DOT)) {
|
||||
next(c);
|
||||
if (check(c, CAT_LEXER_TOK_NAME)) {
|
||||
/* a member name may be a keyword (glfw.false, obj.end);
|
||||
* the lexer keeps the text of keyword tokens too. */
|
||||
if (c->tok.kind == CAT_LEXER_TOK_NAME ||
|
||||
(c->tok.kind >= CAT_LEXER_TOK_AND &&
|
||||
c->tok.kind <= CAT_LEXER_TOK_EXTENDS)) {
|
||||
int k = add_string(c, c->tok.text);
|
||||
emit(c, CAT_BYTECODE_OP_GETATTR, k, 0, c->tok.line);
|
||||
next(c);
|
||||
@@ -951,7 +955,10 @@ static void stat(Compiler *c)
|
||||
for (;;) {
|
||||
CAT_LEXER_Token attr, nx;
|
||||
cat_lexer_next(&c->lx, &attr);
|
||||
if (attr.kind != CAT_LEXER_TOK_NAME)
|
||||
/* a member name may be a keyword (glfw.false = 0) */
|
||||
if (attr.kind != CAT_LEXER_TOK_NAME &&
|
||||
!(attr.kind >= CAT_LEXER_TOK_AND &&
|
||||
attr.kind <= CAT_LEXER_TOK_EXTENDS))
|
||||
break;
|
||||
if (nchain < 16)
|
||||
snprintf(chain[nchain], sizeof(chain[0]),
|
||||
|
||||
@@ -363,6 +363,27 @@ CAT_VALUE_Value *cat_types_ffi_bind(CAT_VALUE_Value *lib, const char *name,
|
||||
return &f->base;
|
||||
}
|
||||
|
||||
CAT_VALUE_Value *cat_types_ffi_bind_addr(unsigned long long addr,
|
||||
const char *name, const char *sig)
|
||||
{
|
||||
CAT_TYPES_FFI_Function *f;
|
||||
|
||||
if (addr == 0)
|
||||
return cat_types_empty();
|
||||
f = calloc(1, sizeof(*f));
|
||||
if (f == NULL)
|
||||
return cat_types_empty();
|
||||
f->base.vtable = &g_function_vtable;
|
||||
f->sym = (void *)(size_t)addr;
|
||||
f->name = strdup(name ? name : "?");
|
||||
f->sig = sig ? strdup(sig) : NULL;
|
||||
if (prepare(f, sig) != 0) {
|
||||
function_destroy(&f->base);
|
||||
return cat_types_empty();
|
||||
}
|
||||
return &f->base;
|
||||
}
|
||||
|
||||
/* `ffi::load(path)` module function (static access).
|
||||
*
|
||||
* `::` sends the module as the receiver, so with `ffi::load("x")` the
|
||||
@@ -390,6 +411,33 @@ static int ffi_load_native(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* `ffi::pointer(addr, name, sig)` -- bind a call at a raw address, e.g.
|
||||
* a Vulkan function pointer from vkGetDeviceProcAddr. */
|
||||
static int ffi_pointer_native(CAT_VM_State *vm, CAT_VALUE_Value **args,
|
||||
int nargs, CAT_VALUE_Value **out)
|
||||
{
|
||||
/* `ffi::pointer(...)` sends the module as receiver, so skip a
|
||||
* non-number leading argument. */
|
||||
int base = 0;
|
||||
unsigned long long addr;
|
||||
const char *name = NULL;
|
||||
const char *sig = NULL;
|
||||
|
||||
(void)vm;
|
||||
if (nargs >= 1 && args[0] != NULL && args[0]->vtable != NULL &&
|
||||
args[0]->vtable->kind != CAT_VALUE_KIND_NUMBER)
|
||||
base = 1;
|
||||
if (nargs < base + 3) {
|
||||
*out = cat_types_empty();
|
||||
return 0;
|
||||
}
|
||||
addr = (unsigned long long)cat_types_number_as_int(args[base]);
|
||||
name = cat_types_text_bytes(args[base + 1]);
|
||||
sig = cat_types_text_bytes(args[base + 2]);
|
||||
*out = cat_types_ffi_bind_addr(addr, name, sig);
|
||||
return 0;
|
||||
}
|
||||
|
||||
CAT_VALUE_Value *cat_types_ffi_module(void)
|
||||
{
|
||||
CAT_VALUE_Value *m = cat_types_table_new();
|
||||
@@ -398,5 +446,8 @@ CAT_VALUE_Value *cat_types_ffi_module(void)
|
||||
cat_error_clear(&e);
|
||||
cat_types_table_set(m, "load",
|
||||
cat_types_native_new("load", ffi_load_native), &e);
|
||||
cat_types_table_set(m, "pointer",
|
||||
cat_types_native_new("pointer", ffi_pointer_native),
|
||||
&e);
|
||||
return m;
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
-- std/glfw/glfw.cat -- generated GLFW bindings (snake_case).
|
||||
-- Generated by tools/gen_glfw.py from the official glfw3.h.
|
||||
--
|
||||
-- import it with: use glfw
|
||||
-- Then call functions as `glfw.init()`, `glfw.create_window(...)`;
|
||||
-- constants and struct offsets live on `glfw` too (glfw.visible).
|
||||
|
||||
local _lib = ffi::load('libglfw.so.3')
|
||||
|
||||
glfw = {}
|
||||
glfw.lib = _lib
|
||||
|
||||
glfw.init = _lib:func('glfwInit', 'int()')
|
||||
glfw.terminate = _lib:func('glfwTerminate', 'void()')
|
||||
glfw.init_hint = _lib:func('glfwInitHint', 'void(int,int)')
|
||||
glfw.init_allocator = _lib:func('glfwInitAllocator', 'void(ptr)')
|
||||
glfw.init_vulkan_loader = _lib:func('glfwInitVulkanLoader', 'void(int)')
|
||||
glfw.get_version = _lib:func('glfwGetVersion', 'void(ptr,ptr,ptr)')
|
||||
glfw.get_version_string = _lib:func('glfwGetVersionString', 'string()')
|
||||
glfw.get_error = _lib:func('glfwGetError', 'int(ptr)')
|
||||
glfw.set_error_callback = _lib:func('glfwSetErrorCallback', 'int(int)')
|
||||
glfw.get_platform = _lib:func('glfwGetPlatform', 'int()')
|
||||
glfw.platform_supported = _lib:func('glfwPlatformSupported', 'int(int)')
|
||||
glfw.get_monitors = _lib:func('glfwGetMonitors', 'ptr(ptr)')
|
||||
glfw.get_primary_monitor = _lib:func('glfwGetPrimaryMonitor', 'ptr()')
|
||||
glfw.get_monitor_pos = _lib:func('glfwGetMonitorPos', 'void(ptr,ptr,ptr)')
|
||||
glfw.get_monitor_workarea = _lib:func('glfwGetMonitorWorkarea', 'void(ptr,ptr,ptr,ptr,ptr)')
|
||||
glfw.get_monitor_physical_size = _lib:func('glfwGetMonitorPhysicalSize', 'void(ptr,ptr,ptr)')
|
||||
glfw.get_monitor_content_scale = _lib:func('glfwGetMonitorContentScale', 'void(ptr,ptr,ptr)')
|
||||
glfw.get_monitor_name = _lib:func('glfwGetMonitorName', 'string(ptr)')
|
||||
glfw.set_monitor_user_pointer = _lib:func('glfwSetMonitorUserPointer', 'void(ptr,ptr)')
|
||||
glfw.get_monitor_user_pointer = _lib:func('glfwGetMonitorUserPointer', 'ptr(ptr)')
|
||||
glfw.set_monitor_callback = _lib:func('glfwSetMonitorCallback', 'int(int)')
|
||||
glfw.get_video_modes = _lib:func('glfwGetVideoModes', 'ptr(ptr,ptr)')
|
||||
glfw.get_video_mode = _lib:func('glfwGetVideoMode', 'ptr(ptr)')
|
||||
glfw.set_gamma = _lib:func('glfwSetGamma', 'void(ptr,float)')
|
||||
glfw.get_gamma_ramp = _lib:func('glfwGetGammaRamp', 'ptr(ptr)')
|
||||
glfw.set_gamma_ramp = _lib:func('glfwSetGammaRamp', 'void(ptr,ptr)')
|
||||
glfw.default_window_hints = _lib:func('glfwDefaultWindowHints', 'void()')
|
||||
glfw.window_hint = _lib:func('glfwWindowHint', 'void(int,int)')
|
||||
glfw.window_hint_string = _lib:func('glfwWindowHintString', 'void(int,string)')
|
||||
glfw.create_window = _lib:func('glfwCreateWindow', 'ptr(int,int,string,ptr,ptr)')
|
||||
glfw.destroy_window = _lib:func('glfwDestroyWindow', 'void(ptr)')
|
||||
glfw.window_should_close = _lib:func('glfwWindowShouldClose', 'int(ptr)')
|
||||
glfw.set_window_should_close = _lib:func('glfwSetWindowShouldClose', 'void(ptr,int)')
|
||||
glfw.get_window_title = _lib:func('glfwGetWindowTitle', 'string(ptr)')
|
||||
glfw.set_window_title = _lib:func('glfwSetWindowTitle', 'void(ptr,string)')
|
||||
glfw.set_window_icon = _lib:func('glfwSetWindowIcon', 'void(ptr,int,ptr)')
|
||||
glfw.get_window_pos = _lib:func('glfwGetWindowPos', 'void(ptr,ptr,ptr)')
|
||||
glfw.set_window_pos = _lib:func('glfwSetWindowPos', 'void(ptr,int,int)')
|
||||
glfw.get_window_size = _lib:func('glfwGetWindowSize', 'void(ptr,ptr,ptr)')
|
||||
glfw.set_window_size_limits = _lib:func('glfwSetWindowSizeLimits', 'void(ptr,int,int,int,int)')
|
||||
glfw.set_window_aspect_ratio = _lib:func('glfwSetWindowAspectRatio', 'void(ptr,int,int)')
|
||||
glfw.set_window_size = _lib:func('glfwSetWindowSize', 'void(ptr,int,int)')
|
||||
glfw.get_framebuffer_size = _lib:func('glfwGetFramebufferSize', 'void(ptr,ptr,ptr)')
|
||||
glfw.get_window_frame_size = _lib:func('glfwGetWindowFrameSize', 'void(ptr,ptr,ptr,ptr,ptr)')
|
||||
glfw.get_window_content_scale = _lib:func('glfwGetWindowContentScale', 'void(ptr,ptr,ptr)')
|
||||
glfw.get_window_opacity = _lib:func('glfwGetWindowOpacity', 'float(ptr)')
|
||||
glfw.set_window_opacity = _lib:func('glfwSetWindowOpacity', 'void(ptr,float)')
|
||||
glfw.iconify_window = _lib:func('glfwIconifyWindow', 'void(ptr)')
|
||||
glfw.restore_window = _lib:func('glfwRestoreWindow', 'void(ptr)')
|
||||
glfw.maximize_window = _lib:func('glfwMaximizeWindow', 'void(ptr)')
|
||||
glfw.show_window = _lib:func('glfwShowWindow', 'void(ptr)')
|
||||
glfw.hide_window = _lib:func('glfwHideWindow', 'void(ptr)')
|
||||
glfw.focus_window = _lib:func('glfwFocusWindow', 'void(ptr)')
|
||||
glfw.request_window_attention = _lib:func('glfwRequestWindowAttention', 'void(ptr)')
|
||||
glfw.get_window_monitor = _lib:func('glfwGetWindowMonitor', 'ptr(ptr)')
|
||||
glfw.set_window_monitor = _lib:func('glfwSetWindowMonitor', 'void(ptr,ptr,int,int,int,int,int)')
|
||||
glfw.get_window_attrib = _lib:func('glfwGetWindowAttrib', 'int(ptr,int)')
|
||||
glfw.set_window_attrib = _lib:func('glfwSetWindowAttrib', 'void(ptr,int,int)')
|
||||
glfw.set_window_user_pointer = _lib:func('glfwSetWindowUserPointer', 'void(ptr,ptr)')
|
||||
glfw.get_window_user_pointer = _lib:func('glfwGetWindowUserPointer', 'ptr(ptr)')
|
||||
glfw.set_window_pos_callback = _lib:func('glfwSetWindowPosCallback', 'int(ptr,int)')
|
||||
glfw.set_window_size_callback = _lib:func('glfwSetWindowSizeCallback', 'int(ptr,int)')
|
||||
glfw.set_window_close_callback = _lib:func('glfwSetWindowCloseCallback', 'int(ptr,int)')
|
||||
glfw.set_window_refresh_callback = _lib:func('glfwSetWindowRefreshCallback', 'int(ptr,int)')
|
||||
glfw.set_window_focus_callback = _lib:func('glfwSetWindowFocusCallback', 'int(ptr,int)')
|
||||
glfw.set_window_iconify_callback = _lib:func('glfwSetWindowIconifyCallback', 'int(ptr,int)')
|
||||
glfw.set_window_maximize_callback = _lib:func('glfwSetWindowMaximizeCallback', 'int(ptr,int)')
|
||||
glfw.set_framebuffer_size_callback = _lib:func('glfwSetFramebufferSizeCallback', 'int(ptr,int)')
|
||||
glfw.set_window_content_scale_callback = _lib:func('glfwSetWindowContentScaleCallback', 'int(ptr,int)')
|
||||
glfw.poll_events = _lib:func('glfwPollEvents', 'void()')
|
||||
glfw.wait_events = _lib:func('glfwWaitEvents', 'void()')
|
||||
glfw.wait_events_timeout = _lib:func('glfwWaitEventsTimeout', 'void(double)')
|
||||
glfw.post_empty_event = _lib:func('glfwPostEmptyEvent', 'void()')
|
||||
glfw.get_input_mode = _lib:func('glfwGetInputMode', 'int(ptr,int)')
|
||||
glfw.set_input_mode = _lib:func('glfwSetInputMode', 'void(ptr,int,int)')
|
||||
glfw.raw_mouse_motion_supported = _lib:func('glfwRawMouseMotionSupported', 'int()')
|
||||
glfw.get_key_name = _lib:func('glfwGetKeyName', 'string(int,int)')
|
||||
glfw.get_key_scancode = _lib:func('glfwGetKeyScancode', 'int(int)')
|
||||
glfw.get_key = _lib:func('glfwGetKey', 'int(ptr,int)')
|
||||
glfw.get_mouse_button = _lib:func('glfwGetMouseButton', 'int(ptr,int)')
|
||||
glfw.get_cursor_pos = _lib:func('glfwGetCursorPos', 'void(ptr,ptr,ptr)')
|
||||
glfw.set_cursor_pos = _lib:func('glfwSetCursorPos', 'void(ptr,double,double)')
|
||||
glfw.create_cursor = _lib:func('glfwCreateCursor', 'ptr(ptr,int,int)')
|
||||
glfw.create_standard_cursor = _lib:func('glfwCreateStandardCursor', 'ptr(int)')
|
||||
glfw.destroy_cursor = _lib:func('glfwDestroyCursor', 'void(ptr)')
|
||||
glfw.set_cursor = _lib:func('glfwSetCursor', 'void(ptr,ptr)')
|
||||
glfw.set_key_callback = _lib:func('glfwSetKeyCallback', 'int(ptr,int)')
|
||||
glfw.set_char_callback = _lib:func('glfwSetCharCallback', 'int(ptr,int)')
|
||||
glfw.set_char_mods_callback = _lib:func('glfwSetCharModsCallback', 'int(ptr,int)')
|
||||
glfw.set_mouse_button_callback = _lib:func('glfwSetMouseButtonCallback', 'int(ptr,int)')
|
||||
glfw.set_cursor_pos_callback = _lib:func('glfwSetCursorPosCallback', 'int(ptr,int)')
|
||||
glfw.set_cursor_enter_callback = _lib:func('glfwSetCursorEnterCallback', 'int(ptr,int)')
|
||||
glfw.set_scroll_callback = _lib:func('glfwSetScrollCallback', 'int(ptr,int)')
|
||||
glfw.set_drop_callback = _lib:func('glfwSetDropCallback', 'int(ptr,int)')
|
||||
glfw.joystick_present = _lib:func('glfwJoystickPresent', 'int(int)')
|
||||
glfw.get_joystick_axes = _lib:func('glfwGetJoystickAxes', 'ptr(int,ptr)')
|
||||
glfw.get_joystick_buttons = _lib:func('glfwGetJoystickButtons', 'ptr(int,ptr)')
|
||||
glfw.get_joystick_hats = _lib:func('glfwGetJoystickHats', 'ptr(int,ptr)')
|
||||
glfw.get_joystick_name = _lib:func('glfwGetJoystickName', 'string(int)')
|
||||
glfw.get_joystick_guid = _lib:func('glfwGetJoystickGUID', 'string(int)')
|
||||
glfw.set_joystick_user_pointer = _lib:func('glfwSetJoystickUserPointer', 'void(int,ptr)')
|
||||
glfw.get_joystick_user_pointer = _lib:func('glfwGetJoystickUserPointer', 'ptr(int)')
|
||||
glfw.joystick_is_gamepad = _lib:func('glfwJoystickIsGamepad', 'int(int)')
|
||||
glfw.set_joystick_callback = _lib:func('glfwSetJoystickCallback', 'int(int)')
|
||||
glfw.update_gamepad_mappings = _lib:func('glfwUpdateGamepadMappings', 'int(string)')
|
||||
glfw.get_gamepad_name = _lib:func('glfwGetGamepadName', 'string(int)')
|
||||
glfw.get_gamepad_state = _lib:func('glfwGetGamepadState', 'int(int,ptr)')
|
||||
glfw.set_clipboard_string = _lib:func('glfwSetClipboardString', 'void(ptr,string)')
|
||||
glfw.get_clipboard_string = _lib:func('glfwGetClipboardString', 'string(ptr)')
|
||||
glfw.get_time = _lib:func('glfwGetTime', 'double()')
|
||||
glfw.set_time = _lib:func('glfwSetTime', 'void(double)')
|
||||
glfw.get_timer_value = _lib:func('glfwGetTimerValue', 'uint64()')
|
||||
glfw.get_timer_frequency = _lib:func('glfwGetTimerFrequency', 'uint64()')
|
||||
glfw.make_context_current = _lib:func('glfwMakeContextCurrent', 'void(ptr)')
|
||||
glfw.get_current_context = _lib:func('glfwGetCurrentContext', 'ptr()')
|
||||
glfw.swap_buffers = _lib:func('glfwSwapBuffers', 'void(ptr)')
|
||||
glfw.swap_interval = _lib:func('glfwSwapInterval', 'void(int)')
|
||||
glfw.extension_supported = _lib:func('glfwExtensionSupported', 'int(string)')
|
||||
glfw.get_proc_address = _lib:func('glfwGetProcAddress', 'int(string)')
|
||||
glfw.vulkan_supported = _lib:func('glfwVulkanSupported', 'int()')
|
||||
glfw.get_required_instance_extensions = _lib:func('glfwGetRequiredInstanceExtensions', 'ptr(ptr)')
|
||||
glfw.get_instance_proc_address = _lib:func('glfwGetInstanceProcAddress', 'int(int,string)')
|
||||
glfw.get_physical_device_presentation_support = _lib:func('glfwGetPhysicalDevicePresentationSupport', 'int(int,int,int)')
|
||||
glfw.create_window_surface = _lib:func('glfwCreateWindowSurface', 'int(int,ptr,ptr,ptr)')
|
||||
|
||||
-- constants
|
||||
glfw.version_major = 3
|
||||
glfw.version_minor = 4
|
||||
glfw.version_revision = 0
|
||||
glfw.true = 1
|
||||
glfw.false = 0
|
||||
glfw.release = 0
|
||||
glfw.press = 1
|
||||
glfw.repeat = 2
|
||||
glfw.hat_centered = 0
|
||||
glfw.hat_up = 1
|
||||
glfw.hat_right = 2
|
||||
glfw.hat_down = 4
|
||||
glfw.hat_left = 8
|
||||
glfw.key_unknown = -1
|
||||
glfw.key_space = 32
|
||||
glfw.key_0 = 48
|
||||
glfw.key_1 = 49
|
||||
glfw.key_2 = 50
|
||||
glfw.key_3 = 51
|
||||
glfw.key_4 = 52
|
||||
glfw.key_5 = 53
|
||||
glfw.key_6 = 54
|
||||
glfw.key_7 = 55
|
||||
glfw.key_8 = 56
|
||||
glfw.key_9 = 57
|
||||
glfw.key_a = 65
|
||||
glfw.key_b = 66
|
||||
glfw.key_c = 67
|
||||
glfw.key_d = 68
|
||||
glfw.key_e = 69
|
||||
glfw.key_f = 70
|
||||
glfw.key_g = 71
|
||||
glfw.key_h = 72
|
||||
glfw.key_i = 73
|
||||
glfw.key_j = 74
|
||||
glfw.key_k = 75
|
||||
glfw.key_l = 76
|
||||
glfw.key_m = 77
|
||||
glfw.key_n = 78
|
||||
glfw.key_o = 79
|
||||
glfw.key_p = 80
|
||||
glfw.key_q = 81
|
||||
glfw.key_r = 82
|
||||
glfw.key_s = 83
|
||||
glfw.key_t = 84
|
||||
glfw.key_u = 85
|
||||
glfw.key_v = 86
|
||||
glfw.key_w = 87
|
||||
glfw.key_x = 88
|
||||
glfw.key_y = 89
|
||||
glfw.key_z = 90
|
||||
glfw.key_escape = 256
|
||||
glfw.key_enter = 257
|
||||
glfw.key_tab = 258
|
||||
glfw.key_backspace = 259
|
||||
glfw.key_insert = 260
|
||||
glfw.key_delete = 261
|
||||
glfw.key_right = 262
|
||||
glfw.key_left = 263
|
||||
glfw.key_down = 264
|
||||
glfw.key_up = 265
|
||||
glfw.key_page_up = 266
|
||||
glfw.key_page_down = 267
|
||||
glfw.key_home = 268
|
||||
glfw.key_end = 269
|
||||
glfw.key_caps_lock = 280
|
||||
glfw.key_scroll_lock = 281
|
||||
glfw.key_num_lock = 282
|
||||
glfw.key_print_screen = 283
|
||||
glfw.key_pause = 284
|
||||
glfw.key_f1 = 290
|
||||
glfw.key_f2 = 291
|
||||
glfw.key_f3 = 292
|
||||
glfw.key_f4 = 293
|
||||
glfw.key_f5 = 294
|
||||
glfw.key_f6 = 295
|
||||
glfw.key_f7 = 296
|
||||
glfw.key_f8 = 297
|
||||
glfw.key_f9 = 298
|
||||
glfw.key_f10 = 299
|
||||
glfw.key_f11 = 300
|
||||
glfw.key_f12 = 301
|
||||
glfw.key_f13 = 302
|
||||
glfw.key_f14 = 303
|
||||
glfw.key_f15 = 304
|
||||
glfw.key_f16 = 305
|
||||
glfw.key_f17 = 306
|
||||
glfw.key_f18 = 307
|
||||
glfw.key_f19 = 308
|
||||
glfw.key_f20 = 309
|
||||
glfw.key_f21 = 310
|
||||
glfw.key_f22 = 311
|
||||
glfw.key_f23 = 312
|
||||
glfw.key_f24 = 313
|
||||
glfw.key_f25 = 314
|
||||
glfw.key_kp_0 = 320
|
||||
glfw.key_kp_1 = 321
|
||||
glfw.key_kp_2 = 322
|
||||
glfw.key_kp_3 = 323
|
||||
glfw.key_kp_4 = 324
|
||||
glfw.key_kp_5 = 325
|
||||
glfw.key_kp_6 = 326
|
||||
glfw.key_kp_7 = 327
|
||||
glfw.key_kp_8 = 328
|
||||
glfw.key_kp_9 = 329
|
||||
glfw.key_kp_decimal = 330
|
||||
glfw.key_kp_divide = 331
|
||||
glfw.key_kp_multiply = 332
|
||||
glfw.key_kp_subtract = 333
|
||||
glfw.key_kp_add = 334
|
||||
glfw.key_kp_enter = 335
|
||||
glfw.key_kp_equal = 336
|
||||
glfw.key_left_shift = 340
|
||||
glfw.key_left_control = 341
|
||||
glfw.key_left_alt = 342
|
||||
glfw.key_left_super = 343
|
||||
glfw.key_right_shift = 344
|
||||
glfw.key_right_control = 345
|
||||
glfw.key_right_alt = 346
|
||||
glfw.key_right_super = 347
|
||||
glfw.key_menu = 348
|
||||
glfw.mod_shift = 0x0001
|
||||
glfw.mod_control = 0x0002
|
||||
glfw.mod_alt = 0x0004
|
||||
glfw.mod_super = 0x0008
|
||||
glfw.mod_caps_lock = 0x0010
|
||||
glfw.mod_num_lock = 0x0020
|
||||
glfw.mouse_button_1 = 0
|
||||
glfw.mouse_button_2 = 1
|
||||
glfw.mouse_button_3 = 2
|
||||
glfw.mouse_button_4 = 3
|
||||
glfw.mouse_button_5 = 4
|
||||
glfw.mouse_button_6 = 5
|
||||
glfw.mouse_button_7 = 6
|
||||
glfw.mouse_button_8 = 7
|
||||
glfw.joystick_1 = 0
|
||||
glfw.joystick_2 = 1
|
||||
glfw.joystick_3 = 2
|
||||
glfw.joystick_4 = 3
|
||||
glfw.joystick_5 = 4
|
||||
glfw.joystick_6 = 5
|
||||
glfw.joystick_7 = 6
|
||||
glfw.joystick_8 = 7
|
||||
glfw.joystick_9 = 8
|
||||
glfw.joystick_10 = 9
|
||||
glfw.joystick_11 = 10
|
||||
glfw.joystick_12 = 11
|
||||
glfw.joystick_13 = 12
|
||||
glfw.joystick_14 = 13
|
||||
glfw.joystick_15 = 14
|
||||
glfw.joystick_16 = 15
|
||||
glfw.gamepad_button_a = 0
|
||||
glfw.gamepad_button_b = 1
|
||||
glfw.gamepad_button_x = 2
|
||||
glfw.gamepad_button_y = 3
|
||||
glfw.gamepad_button_left_bumper = 4
|
||||
glfw.gamepad_button_right_bumper = 5
|
||||
glfw.gamepad_button_back = 6
|
||||
glfw.gamepad_button_start = 7
|
||||
glfw.gamepad_button_guide = 8
|
||||
glfw.gamepad_button_left_thumb = 9
|
||||
glfw.gamepad_button_right_thumb = 10
|
||||
glfw.gamepad_button_dpad_up = 11
|
||||
glfw.gamepad_button_dpad_right = 12
|
||||
glfw.gamepad_button_dpad_down = 13
|
||||
glfw.gamepad_button_dpad_left = 14
|
||||
glfw.gamepad_axis_left_x = 0
|
||||
glfw.gamepad_axis_left_y = 1
|
||||
glfw.gamepad_axis_right_x = 2
|
||||
glfw.gamepad_axis_right_y = 3
|
||||
glfw.gamepad_axis_left_trigger = 4
|
||||
glfw.gamepad_axis_right_trigger = 5
|
||||
glfw.no_error = 0
|
||||
glfw.not_initialized = 0x00010001
|
||||
glfw.no_current_context = 0x00010002
|
||||
glfw.invalid_enum = 0x00010003
|
||||
glfw.invalid_value = 0x00010004
|
||||
glfw.out_of_memory = 0x00010005
|
||||
glfw.api_unavailable = 0x00010006
|
||||
glfw.version_unavailable = 0x00010007
|
||||
glfw.platform_error = 0x00010008
|
||||
glfw.format_unavailable = 0x00010009
|
||||
glfw.no_window_context = 0x0001000A
|
||||
glfw.cursor_unavailable = 0x0001000B
|
||||
glfw.feature_unavailable = 0x0001000C
|
||||
glfw.feature_unimplemented = 0x0001000D
|
||||
glfw.platform_unavailable = 0x0001000E
|
||||
glfw.focused = 0x00020001
|
||||
glfw.iconified = 0x00020002
|
||||
glfw.resizable = 0x00020003
|
||||
glfw.visible = 0x00020004
|
||||
glfw.decorated = 0x00020005
|
||||
glfw.auto_iconify = 0x00020006
|
||||
glfw.floating = 0x00020007
|
||||
glfw.maximized = 0x00020008
|
||||
glfw.center_cursor = 0x00020009
|
||||
glfw.transparent_framebuffer = 0x0002000A
|
||||
glfw.hovered = 0x0002000B
|
||||
glfw.focus_on_show = 0x0002000C
|
||||
glfw.mouse_passthrough = 0x0002000D
|
||||
glfw.position_x = 0x0002000E
|
||||
glfw.position_y = 0x0002000F
|
||||
glfw.red_bits = 0x00021001
|
||||
glfw.green_bits = 0x00021002
|
||||
glfw.blue_bits = 0x00021003
|
||||
glfw.alpha_bits = 0x00021004
|
||||
glfw.depth_bits = 0x00021005
|
||||
glfw.stencil_bits = 0x00021006
|
||||
glfw.accum_red_bits = 0x00021007
|
||||
glfw.accum_green_bits = 0x00021008
|
||||
glfw.accum_blue_bits = 0x00021009
|
||||
glfw.accum_alpha_bits = 0x0002100A
|
||||
glfw.aux_buffers = 0x0002100B
|
||||
glfw.stereo = 0x0002100C
|
||||
glfw.samples = 0x0002100D
|
||||
glfw.srgb_capable = 0x0002100E
|
||||
glfw.refresh_rate = 0x0002100F
|
||||
glfw.doublebuffer = 0x00021010
|
||||
glfw.client_api = 0x00022001
|
||||
glfw.context_version_major = 0x00022002
|
||||
glfw.context_version_minor = 0x00022003
|
||||
glfw.context_revision = 0x00022004
|
||||
glfw.context_robustness = 0x00022005
|
||||
glfw.opengl_forward_compat = 0x00022006
|
||||
glfw.context_debug = 0x00022007
|
||||
glfw.opengl_profile = 0x00022008
|
||||
glfw.context_release_behavior = 0x00022009
|
||||
glfw.context_no_error = 0x0002200A
|
||||
glfw.context_creation_api = 0x0002200B
|
||||
glfw.scale_to_monitor = 0x0002200C
|
||||
glfw.scale_framebuffer = 0x0002200D
|
||||
glfw.cocoa_retina_framebuffer = 0x00023001
|
||||
glfw.cocoa_frame_name = 0x00023002
|
||||
glfw.cocoa_graphics_switching = 0x00023003
|
||||
glfw.x11_class_name = 0x00024001
|
||||
glfw.x11_instance_name = 0x00024002
|
||||
glfw.win32_keyboard_menu = 0x00025001
|
||||
glfw.win32_showdefault = 0x00025002
|
||||
glfw.wayland_app_id = 0x00026001
|
||||
glfw.no_api = 0
|
||||
glfw.opengl_api = 0x00030001
|
||||
glfw.opengl_es_api = 0x00030002
|
||||
glfw.no_robustness = 0
|
||||
glfw.no_reset_notification = 0x00031001
|
||||
glfw.lose_context_on_reset = 0x00031002
|
||||
glfw.opengl_any_profile = 0
|
||||
glfw.opengl_core_profile = 0x00032001
|
||||
glfw.opengl_compat_profile = 0x00032002
|
||||
glfw.cursor = 0x00033001
|
||||
glfw.sticky_keys = 0x00033002
|
||||
glfw.sticky_mouse_buttons = 0x00033003
|
||||
glfw.lock_key_mods = 0x00033004
|
||||
glfw.raw_mouse_motion = 0x00033005
|
||||
glfw.cursor_normal = 0x00034001
|
||||
glfw.cursor_hidden = 0x00034002
|
||||
glfw.cursor_disabled = 0x00034003
|
||||
glfw.cursor_captured = 0x00034004
|
||||
glfw.any_release_behavior = 0
|
||||
glfw.release_behavior_flush = 0x00035001
|
||||
glfw.release_behavior_none = 0x00035002
|
||||
glfw.native_context_api = 0x00036001
|
||||
glfw.egl_context_api = 0x00036002
|
||||
glfw.osmesa_context_api = 0x00036003
|
||||
glfw.angle_platform_type_none = 0x00037001
|
||||
glfw.angle_platform_type_opengl = 0x00037002
|
||||
glfw.angle_platform_type_opengles = 0x00037003
|
||||
glfw.angle_platform_type_d3d9 = 0x00037004
|
||||
glfw.angle_platform_type_d3d11 = 0x00037005
|
||||
glfw.angle_platform_type_vulkan = 0x00037007
|
||||
glfw.angle_platform_type_metal = 0x00037008
|
||||
glfw.wayland_prefer_libdecor = 0x00038001
|
||||
glfw.wayland_disable_libdecor = 0x00038002
|
||||
glfw.any_position = 0x80000000
|
||||
glfw.arrow_cursor = 0x00036001
|
||||
glfw.ibeam_cursor = 0x00036002
|
||||
glfw.crosshair_cursor = 0x00036003
|
||||
glfw.pointing_hand_cursor = 0x00036004
|
||||
glfw.resize_ew_cursor = 0x00036005
|
||||
glfw.resize_ns_cursor = 0x00036006
|
||||
glfw.resize_nwse_cursor = 0x00036007
|
||||
glfw.resize_nesw_cursor = 0x00036008
|
||||
glfw.resize_all_cursor = 0x00036009
|
||||
glfw.not_allowed_cursor = 0x0003600A
|
||||
glfw.connected = 0x00040001
|
||||
glfw.disconnected = 0x00040002
|
||||
glfw.joystick_hat_buttons = 0x00050001
|
||||
glfw.angle_platform_type = 0x00050002
|
||||
glfw.platform = 0x00050003
|
||||
glfw.cocoa_chdir_resources = 0x00051001
|
||||
glfw.cocoa_menubar = 0x00051002
|
||||
glfw.x11_xcb_vulkan_surface = 0x00052001
|
||||
glfw.wayland_libdecor = 0x00053001
|
||||
glfw.any_platform = 0x00060000
|
||||
glfw.platform_win32 = 0x00060001
|
||||
glfw.platform_cocoa = 0x00060002
|
||||
glfw.platform_wayland = 0x00060003
|
||||
glfw.platform_x11 = 0x00060004
|
||||
glfw.platform_null = 0x00060005
|
||||
glfw.dont_care = -1
|
||||
|
||||
+12366
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,32 @@
|
||||
-- tests/glfw.cat -- GLFW bindings, exercised headlessly under Xvfb.
|
||||
--
|
||||
-- `use glfw` loads libglfw and binds every GLFWAPI function with a
|
||||
-- snake_case name (glfw.init, glfw.create_window, ...), plus GLFW_*
|
||||
-- constants and struct offsets. Needs a display; run with xvfb-run.
|
||||
|
||||
use glfw
|
||||
|
||||
local version = memory(12)
|
||||
glfw.get_version(version, version:ptr() + 4, version:ptr() + 8)
|
||||
print("glfw:", version:u32(0), version:u32(4), version:u32(8))
|
||||
|
||||
local ok = glfw.init()
|
||||
print("init:", ok)
|
||||
|
||||
-- a hidden window with no client API (for Vulkan surfaces)
|
||||
glfw.window_hint(glfw.visible, glfw.false)
|
||||
glfw.window_hint(0x00022001, 0) -- CLIENT_API = NO_API
|
||||
local win = glfw.create_window(320, 240, "cat", 0, 0)
|
||||
print("window:", win > 0)
|
||||
|
||||
if win > 0 then
|
||||
local fw = memory(8)
|
||||
local fh = memory(8)
|
||||
glfw.get_framebuffer_size(win, fw, fh)
|
||||
print("framebuffer:", fw:u32(0), fh:u32(0))
|
||||
print("should close:", glfw.window_should_close(win) == glfw.true)
|
||||
glfw.destroy_window(win)
|
||||
end
|
||||
|
||||
glfw.terminate()
|
||||
print("done")
|
||||
@@ -174,6 +174,22 @@ check "repr-list" "list: [a, b, _repr_]" "`echo "$out" | sed -
|
||||
out=`printf 'x = 50\nx\nx + 5\n' | $BIN | tr '>' '\n' | grep -oE '[0-9]+'`
|
||||
check "repl-echo" "50" "`echo "$out" | sed -n 1p`"
|
||||
check "repl-state" "55" "`echo "$out" | sed -n 2p`"
|
||||
# ---- GPU bindings (GLFW + Vulkan) ------------------------------------
|
||||
|
||||
if command -v xvfb-run >/dev/null 2>&1 && [ -f vendor/lib/libglfw.so.3 ]; then
|
||||
out=`LD_LIBRARY_PATH=vendor/lib xvfb-run -a $BIN tests/glfw.cat 2>/dev/null`
|
||||
check "glfw-version" "glfw: 3 4 0" "`echo "$out" | sed -n 1p`"
|
||||
check "glfw-init" "init: 1" "`echo "$out" | sed -n 2p`"
|
||||
check "glfw-window" "window: true" "`echo "$out" | sed -n 3p`"
|
||||
check "glfw-fb" "framebuffer: 320 240" "`echo "$out" | sed -n 4p`"
|
||||
else
|
||||
echo "skip - glfw tests (needs xvfb-run + vendor/lib/libglfw.so.3)"
|
||||
fi
|
||||
|
||||
out=`$BIN tests/vulkan.cat 2>/dev/null`
|
||||
check "vk-instance" "create_instance: true" "`echo "$out" | sed -n 1p`"
|
||||
check "vk-devices" "devices > 0: true" "`echo "$out" | sed -n 2p`"
|
||||
|
||||
# ---- memory buffer ----------------------------------------------------
|
||||
|
||||
out=`$BIN tests/memory.cat`
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
-- tests/vulkan.cat -- Vulkan bindings, exercised headlessly on lavapipe.
|
||||
--
|
||||
-- `use vulkan` loads libvulkan and binds the core commands with
|
||||
-- snake_case names, plus struct sizes (vulkan.size_vk_*) and constants.
|
||||
-- Vulkan runs on a software device (llvmpipe/lavapipe) with no display.
|
||||
|
||||
use vulkan
|
||||
|
||||
-- VkApplicationInfo
|
||||
local ai = memory(vulkan.size_vk_application_info)
|
||||
ai:fill(0)
|
||||
ai:set_u32(0, vulkan.structure_type_application_info)
|
||||
ai:set_u32(24, 0x00400000) -- apiVersion 1.0.0
|
||||
|
||||
-- VkInstanceCreateInfo
|
||||
local ci = memory(vulkan.size_vk_instance_create_info)
|
||||
ci:fill(0)
|
||||
ci:set_u32(0, vulkan.structure_type_instance_create_info)
|
||||
ci:set_u64(24, ai:ptr()) -- pApplicationInfo
|
||||
|
||||
local inst = memory(8)
|
||||
local r = vulkan.create_instance(ci, 0, inst)
|
||||
print("create_instance:", r == vulkan.success)
|
||||
|
||||
local n = memory(4)
|
||||
vulkan.enumerate_physical_devices(inst:u64(0), n, 0)
|
||||
print("devices > 0:", n:u32(0) > 0)
|
||||
|
||||
vulkan.destroy_instance(inst:u64(0), 0)
|
||||
print("done")
|
||||
Binary file not shown.
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate std/glfw/glfw.cat from the official GLFW header.
|
||||
|
||||
Usage: gen_glfw.py <glfw3.h> <libglfw.so path> > glfw.cat
|
||||
|
||||
The output is a catscript module that, on import, ffi::load()s libglfw
|
||||
and binds every GLFWAPI function with a snake_case name, plus the
|
||||
GLFW_* constants and the struct field offsets (GLFWvidmode,
|
||||
GLFWgammaramp) so callers can read them out of a `memory` buffer.
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
|
||||
# C type -> ffi signature type. `const char *` is an input string;
|
||||
# `char *`/`void *`/any other pointer is an address (a `memory` buffer
|
||||
# passes its address).
|
||||
def ctype_to_ffi(t, is_return=False):
|
||||
t = t.strip()
|
||||
t = re.sub(r'\s+', ' ', t)
|
||||
# strip 'const', keep track of it for char*
|
||||
const = t.startswith('const ')
|
||||
base = t[6:].strip() if const else t
|
||||
base = base.replace(' *', '*').replace('* ', '*')
|
||||
if base == 'void':
|
||||
return 'void'
|
||||
if base in ('char*',) or base == 'const char*':
|
||||
return 'string' if (const or is_return) else 'ptr'
|
||||
if '*' in base:
|
||||
return 'ptr'
|
||||
if base == 'float':
|
||||
return 'float'
|
||||
if base == 'double':
|
||||
return 'double'
|
||||
if base in ('int', 'GLFWbool'):
|
||||
return 'int'
|
||||
if base in ('unsigned int', 'unsigned'):
|
||||
return 'uint32'
|
||||
if base in ('unsigned char',):
|
||||
return 'uint8'
|
||||
if base in ('char',):
|
||||
return 'int8'
|
||||
if base in ('long long', 'int64_t'):
|
||||
return 'int64'
|
||||
if base in ('unsigned long long', 'uint64_t'):
|
||||
return 'uint64'
|
||||
return 'int'
|
||||
|
||||
|
||||
def snake(name):
|
||||
"""glfwCreateWindow -> create_window (the glfw_ prefix is the
|
||||
module name, so drop it)."""
|
||||
if name.startswith('glfw'):
|
||||
name = name[4:]
|
||||
s = re.sub(r'(?<=[a-z0-9])([A-Z])', r'_\1', name)
|
||||
s = re.sub(r'(?<=[A-Z])([A-Z][a-z])', r'_\1', s)
|
||||
return s.lstrip('_').lower()
|
||||
|
||||
|
||||
def const_name(name):
|
||||
"""GLFW_VISIBLE -> visible (drop the GLFW_ prefix)."""
|
||||
return name[5:].lower() if name.startswith('GLFW_') else name.lower()
|
||||
|
||||
|
||||
def main():
|
||||
header_path, lib_path = sys.argv[1], sys.argv[2]
|
||||
src = open(header_path).read()
|
||||
|
||||
print("-- std/glfw/glfw.cat -- generated GLFW bindings (snake_case).")
|
||||
print("-- Generated by tools/gen_glfw.py from the official glfw3.h.")
|
||||
print("--")
|
||||
print("-- import it with: use glfw")
|
||||
print("-- Then call functions as `glfw.init()`, `glfw.create_window(...)`;")
|
||||
print("-- constants and struct offsets live on `glfw` too (glfw.visible).")
|
||||
print()
|
||||
print("local _lib = ffi::load(%r)" % lib_path)
|
||||
print()
|
||||
print("glfw = {}")
|
||||
print("glfw.lib = _lib")
|
||||
print()
|
||||
|
||||
# ---- functions ----
|
||||
# GLFWAPI <ret> <name>(<args>);
|
||||
fn_re = re.compile(
|
||||
r'GLFWAPI\s+([A-Za-z_][A-Za-z0-9_ \*]*?)\s+'
|
||||
r'(glfw[A-Za-z0-9_]+)\s*\(([^;]*?)\)\s*;', re.S)
|
||||
count = 0
|
||||
seen = set()
|
||||
for m in fn_re.finditer(src):
|
||||
ret, name, args = m.group(1), m.group(2), m.group(3)
|
||||
if name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
# parse args
|
||||
arglist = []
|
||||
args = args.strip()
|
||||
if args and args != 'void':
|
||||
for a in args.split(','):
|
||||
a = a.strip()
|
||||
# drop the parameter name (last identifier)
|
||||
a = re.sub(r'[A-Za-z_][A-Za-z0-9_]*$', '', a).strip()
|
||||
arglist.append(ctype_to_ffi(a))
|
||||
ret_ffi = ctype_to_ffi(ret, is_return=True)
|
||||
sig = "%s(%s)" % (ret_ffi, ','.join(arglist))
|
||||
py_name = snake(name)
|
||||
print("glfw.%s = _lib:func(%r, %r)" % (py_name, name, sig))
|
||||
count += 1
|
||||
print()
|
||||
|
||||
# ---- constants: #define GLFW_x value ----
|
||||
const_re = re.compile(r'^#define\s+(GLFW_[A-Za-z0-9_]+)\s+'
|
||||
r'(-?0x[0-9A-Fa-f]+|-?[0-9]+)\s*$', re.M)
|
||||
print("-- constants")
|
||||
for m in const_re.finditer(src):
|
||||
key, val = m.group(1), m.group(2)
|
||||
print("glfw.%s = %s" % (const_name(key), val))
|
||||
print()
|
||||
|
||||
# ---- struct offsets (GLFWvidmode, GLFWgammaramp) ----
|
||||
# Parse `typedef struct NAME { ... } NAME;`
|
||||
struct_re = re.compile(r'typedef struct\s+(\w+)\s*\{(.*?)\}\s*\1\s*;', re.S)
|
||||
uint = lambda n: 'u32'
|
||||
for m in struct_re.finditer(src):
|
||||
sname, body = m.group(1), m.group(2)
|
||||
fields = []
|
||||
off = 0
|
||||
for line in body.split(';'):
|
||||
line = line.strip()
|
||||
if not line or line.startswith('/*'):
|
||||
continue
|
||||
# `int width;` or `const GLFWvidmode* modes;`
|
||||
fm = re.match(r'(.+?)\s*\*?\s*(\w+)\s*$', line)
|
||||
if not fm:
|
||||
continue
|
||||
ctype, fname = fm.group(1).strip(), fm.group(2)
|
||||
is_ptr = '*' in line
|
||||
if is_ptr:
|
||||
fields.append((fname, off, 8, 'ptr'))
|
||||
off += 8
|
||||
elif 'float' in ctype:
|
||||
fields.append((fname, off, 4, 'f32'))
|
||||
off += 4
|
||||
elif 'unsigned short' in ctype or 'short' in ctype:
|
||||
fields.append((fname, off, 2, 'u16'))
|
||||
off += 2
|
||||
elif 'unsigned char' in ctype:
|
||||
fields.append((fname, off, 1, 'u8'))
|
||||
off += 1
|
||||
else:
|
||||
fields.append((fname, off, 4, 'u32'))
|
||||
off += 4
|
||||
if fields:
|
||||
print("-- struct %s (%d bytes)" % (sname, off))
|
||||
print("glfw.%s = {" % snake(sname))
|
||||
for fname, foff, fsz, fkind in fields:
|
||||
print(" { name = %r, offset = %d, size = %d, kind = %r },"
|
||||
% (fname, foff, fsz, fkind))
|
||||
print("}")
|
||||
print()
|
||||
|
||||
sys.stderr.write("glfw: %d functions\n" % count)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,301 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate std/vulkan/vulkan.cat from the official vk.xml registry.
|
||||
|
||||
Usage: gen_vulkan.py <vk.xml> [libvulkan.so] > vulkan.cat
|
||||
|
||||
The output is a catscript module that, on import, ffi::load()s libvulkan
|
||||
and binds the Vulkan 1.0 core commands with snake_case names, plus
|
||||
struct sizes (for `memory(size)`) and per-struct field offsets, so a
|
||||
caller can build and read structs safely through a `memory` buffer.
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
SCALARS = {
|
||||
'void': 'void',
|
||||
'float': 'float', 'double': 'double',
|
||||
'int32_t': 'int', 'uint32_t': 'uint32',
|
||||
'int64_t': 'int64', 'uint64_t': 'uint64',
|
||||
'int16_t': 'int16', 'uint16_t': 'uint16',
|
||||
'int8_t': 'int8', 'uint8_t': 'uint8',
|
||||
'size_t': 'uint64', 'char': 'int8',
|
||||
'VkBool32': 'uint32', 'VkFlags': 'uint32',
|
||||
'VkDeviceSize': 'uint64', 'VkSampleMask': 'uint32',
|
||||
'int': 'int', 'unsigned': 'uint32', 'long': 'long',
|
||||
}
|
||||
|
||||
|
||||
def snake(name):
|
||||
"""vkCreateInstance -> create_instance (vk prefix dropped)."""
|
||||
if name.startswith('vk'):
|
||||
name = name[2:]
|
||||
s = re.sub(r'(?<=[a-z0-9])([A-Z])', r'_\1', name)
|
||||
s = re.sub(r'(?<=[A-Z])([A-Z][a-z])', r'_\1', s)
|
||||
return s.lstrip('_').lower()
|
||||
|
||||
|
||||
def const_name(name):
|
||||
"""VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO -> structure_type_instance_create_info"""
|
||||
return name[3:].lower() if name.startswith('VK_') else name.lower()
|
||||
|
||||
|
||||
def align(n, a):
|
||||
return (n + a - 1) & ~(a - 1)
|
||||
|
||||
|
||||
C_ALIGN = {
|
||||
'int8_t': 1, 'uint8_t': 1, 'char': 1,
|
||||
'int16_t': 2, 'uint16_t': 2,
|
||||
'int32_t': 4, 'uint32_t': 4, 'float': 4, 'VkBool32': 4, 'VkFlags': 4,
|
||||
'VkSampleMask': 4,
|
||||
'int64_t': 8, 'uint64_t': 8, 'double': 8, 'VkDeviceSize': 8,
|
||||
'size_t': 8,
|
||||
}
|
||||
C_SIZE = dict(C_ALIGN)
|
||||
|
||||
|
||||
class Layout:
|
||||
"""x86-64 sizes/offsets for Vulkan structs and unions.
|
||||
|
||||
Sizes are resolved recursively and memoized, so a struct that
|
||||
embeds another by value gets the real nested size and alignment.
|
||||
"""
|
||||
|
||||
def __init__(self, root):
|
||||
self.structs = {}
|
||||
self.is_union = {}
|
||||
self.enums = set()
|
||||
self.bitmasks = set()
|
||||
self.handles = set()
|
||||
self.funcptrs = set()
|
||||
self.constants = {} # VK_MAX_* -> int
|
||||
self._size = {}
|
||||
self._align = {}
|
||||
self._fields = {}
|
||||
for t in root.find('types'):
|
||||
cat, nm = t.get('category'), t.get('name')
|
||||
if not nm:
|
||||
continue
|
||||
if cat in ('struct', 'union'):
|
||||
self.structs[nm] = t
|
||||
self.is_union[nm] = (cat == 'union')
|
||||
elif cat == 'enum':
|
||||
self.enums.add(nm)
|
||||
elif cat == 'bitmask':
|
||||
self.bitmasks.add(nm)
|
||||
elif cat == 'handle':
|
||||
self.handles.add(nm)
|
||||
elif cat == 'funcpointer':
|
||||
self.funcptrs.add(nm)
|
||||
# numeric constants (array sizes like VK_MAX_PHYSICAL_DEVICE_NAME_SIZE)
|
||||
for enums in root.findall('enums'):
|
||||
if enums.get('type') != 'constants' and enums.get('name') != 'API Constants':
|
||||
continue
|
||||
for e in enums.findall('enum'):
|
||||
nm, val = e.get('name'), e.get('value')
|
||||
if nm and val and re.fullmatch(r'-?0x[0-9A-Fa-f]+|-?\d+', val):
|
||||
self.constants[nm] = int(val, 0)
|
||||
|
||||
@staticmethod
|
||||
def _member_ctype(m):
|
||||
mt = m.find('type')
|
||||
if mt is None:
|
||||
return None, 0
|
||||
lead = (m.text or '').strip()
|
||||
tail = (mt.tail or '').strip()
|
||||
name_el = m.find('name')
|
||||
name_tail = (name_el.tail or '').strip() if name_el is not None else ''
|
||||
ctype = ('%s %s %s' % (lead, mt.text, tail)).strip()
|
||||
am = re.search(r'\[\s*([A-Za-z0-9_]+)\s*\]', name_tail)
|
||||
if am:
|
||||
return ctype, am.group(1)
|
||||
if name_el is not None:
|
||||
enum_el = m.find('enum')
|
||||
if enum_el is not None and enum_el.text:
|
||||
return ctype, enum_el.text.strip()
|
||||
return ctype, None
|
||||
|
||||
def _array_len(self, expr):
|
||||
"""An array length is a literal, a macro, or a `NAME` len attr."""
|
||||
if expr is None:
|
||||
return 0
|
||||
if re.fullmatch(r'\d+', expr):
|
||||
return int(expr)
|
||||
if expr in self.constants:
|
||||
return self.constants[expr]
|
||||
return 0
|
||||
|
||||
def scalar_info(self, base):
|
||||
if base in C_SIZE:
|
||||
n = C_SIZE[base]
|
||||
return n, C_ALIGN[base], ('f32' if base == 'float'
|
||||
else 'u%d' % (n * 8))
|
||||
if base in self.enums or base in self.bitmasks:
|
||||
return 4, 4, 'u32'
|
||||
if base in self.handles or base in self.funcptrs:
|
||||
return 8, 8, 'ptr'
|
||||
if base == 'void':
|
||||
return 1, 1, 'u8'
|
||||
return None
|
||||
|
||||
def size(self, name):
|
||||
if name in self._size:
|
||||
return self._size[name], self._align[name]
|
||||
self._compute(name, set())
|
||||
return self._size.get(name, 4), self._align.get(name, 4)
|
||||
|
||||
def _compute(self, name, seen):
|
||||
if name in self._size:
|
||||
return
|
||||
if name in seen or name not in self.structs:
|
||||
self._size[name], self._align[name] = 4, 4
|
||||
self._fields[name] = []
|
||||
return
|
||||
seen = seen | {name}
|
||||
t = self.structs[name]
|
||||
is_union = self.is_union.get(name, False)
|
||||
off, maxa, fields = 0, 1, []
|
||||
for m in t.findall('member'):
|
||||
mn = m.find('name')
|
||||
if mn is None:
|
||||
continue
|
||||
ctype, alen = self._member_ctype(m)
|
||||
if ctype is None:
|
||||
continue
|
||||
# a `len="NAME"` attr names a macro-sized array
|
||||
if alen is None:
|
||||
alen = self._array_len(m.get('len'))
|
||||
else:
|
||||
alen = self._array_len(alen)
|
||||
is_ptr = '*' in ctype
|
||||
base = ctype.replace('const', '').replace('*', '').strip()
|
||||
if is_ptr:
|
||||
esize, ealign, ekind = 8, 8, 'ptr'
|
||||
else:
|
||||
info = self.scalar_info(base)
|
||||
if info is not None:
|
||||
esize, ealign, ekind = info
|
||||
elif base in self.structs:
|
||||
esize, ealign = self.size(base)
|
||||
ekind = 'u8'
|
||||
else:
|
||||
esize, ealign, ekind = 4, 4, 'u32'
|
||||
count = alen if alen else 1
|
||||
total = esize * count
|
||||
if is_union:
|
||||
fields.append((mn.text, 0, total, ekind, count))
|
||||
off = max(off, total)
|
||||
else:
|
||||
off = align(off, ealign)
|
||||
fields.append((mn.text, off, total, ekind, count))
|
||||
off += total
|
||||
maxa = max(maxa, ealign)
|
||||
self._size[name] = align(off, maxa)
|
||||
self._align[name] = maxa
|
||||
self._fields[name] = fields
|
||||
|
||||
def fields(self, name):
|
||||
self.size(name)
|
||||
return self._fields.get(name, [])
|
||||
|
||||
|
||||
def ffi_type(ctype, lay):
|
||||
"""Map a C type to an ffi signature type, using the registry's
|
||||
knowledge of enums (4-byte ints) and handles (pointers)."""
|
||||
t = re.sub(r'\s+', ' ', ctype.strip())
|
||||
if t in SCALARS:
|
||||
return SCALARS[t]
|
||||
base = t.replace('const', '').replace('*', '').strip()
|
||||
if '*' in t:
|
||||
return 'ptr'
|
||||
if base in lay.enums or base in lay.bitmasks:
|
||||
return 'uint32'
|
||||
if base in lay.handles or base in lay.funcptrs:
|
||||
return 'ptr'
|
||||
if base in lay.structs:
|
||||
return 'ptr'
|
||||
if base.startswith('Vk') or base.startswith('PFN_'):
|
||||
return 'ptr'
|
||||
return 'int'
|
||||
|
||||
|
||||
def main():
|
||||
xml_path = sys.argv[1]
|
||||
lib = sys.argv[2] if len(sys.argv) > 2 else 'libvulkan.so.1'
|
||||
root = ET.parse(xml_path).getroot()
|
||||
|
||||
struct_types = {t.get('name') for t in root.find('types')
|
||||
if t.get('category') in ('struct', 'union') and t.get('name')}
|
||||
lay = Layout(root)
|
||||
|
||||
commands = []
|
||||
for c in root.find('commands'):
|
||||
proto = c.find('proto')
|
||||
if proto is None:
|
||||
continue
|
||||
ret_el, name_el = proto.find('type'), proto.find('name')
|
||||
if ret_el is None or name_el is None:
|
||||
continue
|
||||
ret = ((ret_el.text or '') + ' ' + (ret_el.tail or '')).strip()
|
||||
params = []
|
||||
for p in c.findall('param'):
|
||||
pt = p.find('type')
|
||||
if pt is None:
|
||||
continue
|
||||
ptype = ((p.text or '') + ' ' + (pt.text or '') + ' '
|
||||
+ (pt.tail or '')).strip()
|
||||
params.append(ptype)
|
||||
commands.append((name_el.text, ret, params))
|
||||
|
||||
out = sys.stdout
|
||||
out.write("-- std/vulkan/vulkan.cat -- generated Vulkan bindings (snake_case).\n")
|
||||
out.write("-- Generated by tools/gen_vulkan.py from the official vk.xml.\n")
|
||||
out.write("--\n")
|
||||
out.write("-- import it with: use vulkan\n")
|
||||
out.write("-- Then: vulkan.create_instance(ci, 0, out), with structs built\n")
|
||||
out.write("-- in a `memory(vulkan.size_vk_instance_create_info)` buffer.\n\n")
|
||||
out.write("local _lib = ffi::load(%r)\n\n" % lib)
|
||||
out.write("vulkan = {}\n")
|
||||
out.write("vulkan.lib = _lib\n\n")
|
||||
|
||||
out.write("-- commands\n")
|
||||
for name, ret, params in commands:
|
||||
sig = "%s(%s)" % (ffi_type(ret, lay),
|
||||
','.join(ffi_type(p, lay) for p in params))
|
||||
out.write("vulkan.%s = _lib:func(%r, %r)\n" % (snake(name), name, sig))
|
||||
out.write("\n")
|
||||
|
||||
out.write("-- struct sizes (allocate with memory(vulkan.size_<name>))\n")
|
||||
names = sorted(n for n in lay.structs if n.startswith('Vk'))
|
||||
for nm in names:
|
||||
sz, _ = lay.size(nm)
|
||||
out.write("vulkan.size_%s = %d\n" % (snake(nm), sz))
|
||||
out.write("\n")
|
||||
|
||||
# enum constants (VK_SUCCESS, VK_STRUCTURE_TYPE_*, VK_FORMAT_*, ...)
|
||||
out.write("-- constants\n")
|
||||
for enums in root.findall('enums'):
|
||||
for e in enums.findall('enum'):
|
||||
nm, val = e.get('name'), e.get('value')
|
||||
if not nm or not val:
|
||||
continue
|
||||
if nm.startswith('VK_') and re.fullmatch(r'-?0x[0-9A-Fa-f]+|-?\d+', val):
|
||||
out.write("vulkan.%s = %s\n" % (const_name(nm), val))
|
||||
out.write("\n")
|
||||
|
||||
out.write("-- struct field offsets\n")
|
||||
for nm in names:
|
||||
fields = lay.fields(nm)
|
||||
out.write("vulkan.off_%s = {\n" % snake(nm))
|
||||
for fname, foff, fsz, fkind, count in fields:
|
||||
out.write(" { name = %r, o = %d, sz = %d, kind = %r },\n"
|
||||
% (fname, foff, fsz, fkind))
|
||||
out.write("}\n")
|
||||
out.write("\nreturn vulkan\n")
|
||||
sys.stderr.write("vulkan: %d commands, %d structs\n"
|
||||
% (len(commands), len(names)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
# vendor/
|
||||
|
||||
Prebuilt shared libraries the generated bindings dlopen at runtime.
|
||||
|
||||
- `libglfw.so.3` (GLFW 3.4) -- the system has no libglfw, so it is
|
||||
vendored here. `std/glfw/glfw.cat` loads `libglfw.so.3`; run with
|
||||
`LD_LIBRARY_PATH=vendor/lib`, or install libglfw3 system-wide.
|
||||
|
||||
Vulkan uses the system loader (`libvulkan.so.1`); nothing to vendor.
|
||||
+1
@@ -0,0 +1 @@
|
||||
libglfw.so.3.4
|
||||
+1
@@ -0,0 +1 @@
|
||||
libglfw.so.3.4
|
||||
Vendored
BIN
Binary file not shown.
Reference in new issue
Block a user