Compare commits
2 commits
auto_unloa
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 80fc9f25a9 | |||
| b48fbc4266 |
28 changed files with 6844 additions and 9493 deletions
3
.gitmodules
vendored
3
.gitmodules
vendored
|
|
@ -4,3 +4,6 @@
|
|||
[submodule "submodules/raylib"]
|
||||
path = submodules/raylib
|
||||
url = https://github.com/raysan5/raylib.git
|
||||
[submodule "submodules/raygui"]
|
||||
path = submodules/raygui
|
||||
url = https://github.com/raysan5/raygui.git
|
||||
|
|
|
|||
213
Makefile
213
Makefile
|
|
@ -1,17 +1,14 @@
|
|||
# hate-no-d
|
||||
#
|
||||
# Native platforms are auto-detected from uname. Cross targets are explicit:
|
||||
# Platforms are auto-detected from uname; cross targets are explicit:
|
||||
# make
|
||||
# make PLATFORM=Android ANDROID_NDK=/opt/android-ndk [ANDROID_ABI=... ANDROID_API=...]
|
||||
# make PLATFORM=Windows WIN_ARCH=x86_64 (cross build with mingw-w64)
|
||||
#
|
||||
# Targets:
|
||||
# make the CLI (hate-no-d or hate-no-d.exe)
|
||||
# make PLATFORM=Android ANDROID_NDK=/opt/ndk [ANDROID_ABI=... ANDROID_API=...]
|
||||
# make help every target and option
|
||||
#
|
||||
# raylib is linked into the CLI. Objects, rlparser and its generated API tables
|
||||
# go to build/; only the CLI and hate-no-d.lua land in the repository root.
|
||||
# raylib and LuaJIT build in their own trees (both gitignore their output).
|
||||
# LuaJIT and raylib build inside their own submodule trees. Objects, rlparser
|
||||
# and its API tables go to build/; only the CLI and the generated hate-no-d.lua
|
||||
# land in the repository root.
|
||||
|
||||
# luajit requires GNU Make. BSD make fails on .FEATURES before this guard.
|
||||
ifndef .FEATURES
|
||||
|
|
@ -20,34 +17,46 @@ endif
|
|||
|
||||
.DEFAULT_GOAL := all
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Paths and outputs
|
||||
# ---------------------------------------------------------------------------
|
||||
LUAJIT_DIR := submodules/luajit
|
||||
LUAJIT_SRC := $(LUAJIT_DIR)/src
|
||||
LUAJIT_AR := $(LUAJIT_SRC)/libluajit.a
|
||||
|
||||
RAYLIB_DIR := submodules/raylib
|
||||
RAYLIB_SRC := $(RAYLIB_DIR)/src
|
||||
RAYLIB_AR := $(RAYLIB_SRC)/libraylib.a
|
||||
RLPARSER_DIR := $(RAYLIB_DIR)/tools/rlparser
|
||||
|
||||
RAYGUI_DIR := submodules/raygui
|
||||
RAYGUI_SRC := $(RAYGUI_DIR)/src
|
||||
|
||||
BUILD_DIR := build
|
||||
API_DIR := $(BUILD_DIR)/api
|
||||
RLPARSER := $(BUILD_DIR)/rlparser
|
||||
RAYLIB_API := $(API_DIR)/raylib_api.lua
|
||||
BINDING := hate-no-d.lua
|
||||
OWNERSHIP_SNAPSHOT := ownership.txt
|
||||
OBJ := $(BUILD_DIR)/hate-no-d.o
|
||||
|
||||
RAYLIB_API := $(API_DIR)/raylib_api.lua
|
||||
RLGL_API := $(API_DIR)/rlgl_api.lua
|
||||
RAYMATH_API := $(API_DIR)/raymath_api.lua
|
||||
RAYGUI_API := $(API_DIR)/raygui_api.lua
|
||||
|
||||
BINDING := hate-no-d.lua
|
||||
BIN := hate-no-d
|
||||
|
||||
GEN_FLAGS := --raylib=$(API_DIR)/raylib_api.lua \
|
||||
--rlgl=$(API_DIR)/rlgl_api.lua \
|
||||
--raymath=$(API_DIR)/raymath_api.lua
|
||||
|
||||
# Archiver passed to raylib's build. Cross toolchains ship their own.
|
||||
AR ?= ar
|
||||
# ---------------------------------------------------------------------------
|
||||
# Platform detection
|
||||
# ---------------------------------------------------------------------------
|
||||
# PLATFORM= always wins over uname.
|
||||
PLATFORM ?= $(shell uname -s)
|
||||
|
||||
LUAJIT_XCFLAGS := -DLUAJIT_ENABLE_LUA52COMPAT
|
||||
LUAJIT_EXTRA :=
|
||||
|
||||
# Platform detection. PLATFORM= always wins over uname.
|
||||
PLATFORM ?= $(shell uname -s)
|
||||
# raylib build args; per-platform blocks below override them.
|
||||
RAYLIB_MAKE_ARGS := PLATFORM=PLATFORM_DESKTOP RAYLIB_LIBTYPE=STATIC
|
||||
RAYLIB_LINK := -Wl,--whole-archive $(RAYLIB_AR) -Wl,--no-whole-archive
|
||||
|
||||
ifeq ($(PLATFORM),Linux)
|
||||
OS_KIND := linux
|
||||
|
|
@ -73,10 +82,6 @@ else ifneq (,$(filter $(PLATFORM),FreeBSD OpenBSD NetBSD DragonFly))
|
|||
OS_KIND := bsd
|
||||
endif
|
||||
|
||||
# raylib build args; per-platform overrides follow.
|
||||
RAYLIB_MAKE_ARGS := PLATFORM=PLATFORM_DESKTOP RAYLIB_LIBTYPE=STATIC
|
||||
RAYLIB_LINK := -Wl,--whole-archive $(RAYLIB_AR) -Wl,--no-whole-archive
|
||||
|
||||
# Linux (ELF)
|
||||
ifeq ($(OS_KIND),linux)
|
||||
EXPORT_LDFLAGS := -Wl,-E
|
||||
|
|
@ -84,15 +89,12 @@ ifeq ($(OS_KIND),linux)
|
|||
LINK_TARGET := $(BIN)
|
||||
endif
|
||||
|
||||
# BSD (ELF, dlopen lives in libc)
|
||||
# BSD (ELF, dlopen lives in libc). ld searches /usr/lib only, while pkg(8)
|
||||
# installs into /usr/local, pkgsrc into /usr/pkg and base X11 into /usr/X11R6
|
||||
# or /usr/X11R7, so every -l below needs an explicit -L. raylib's own BSD link
|
||||
# list also omits the X11 set.
|
||||
ifeq ($(OS_KIND),bsd)
|
||||
EXPORT_LDFLAGS := -Wl,-E
|
||||
# ld searches /usr/lib only. pkg(8) installs into /usr/local (FreeBSD,
|
||||
# DragonFly), pkgsrc into /usr/pkg (NetBSD), and base X11 lives in
|
||||
# /usr/X11R6 (OpenBSD) or /usr/X11R7 (NetBSD), so every -l below needs an
|
||||
# explicit -L. raylib's own BSD link list omits the X11 set and these paths,
|
||||
# which is why its examples only link on a system with the libs on the
|
||||
# default search path.
|
||||
BSD_LIBDIRS := -L/usr/local/lib
|
||||
ifneq (,$(filter OpenBSD NetBSD,$(PLATFORM)))
|
||||
BSD_LIBDIRS += -L/usr/pkg/lib -L/usr/X11R6/lib -L/usr/X11R7/lib
|
||||
|
|
@ -105,8 +107,8 @@ ifeq ($(OS_KIND),bsd)
|
|||
LINK_TARGET := $(BIN)
|
||||
endif
|
||||
|
||||
# Windows (PE, cross-compiled from a POSIX host with mingw-w64; native builds use
|
||||
# build.bat). i686 needs a 32-bit host compiler, since LuaJIT's buildvm runs
|
||||
# Windows (PE), cross-compiled from a POSIX host with mingw-w64; native builds
|
||||
# use build.bat. i686 needs a 32-bit host compiler, since LuaJIT's buildvm runs
|
||||
# natively and must match the target pointer size:
|
||||
# make PLATFORM=Windows WIN_ARCH=i686 HOST_CC="gcc -m32"
|
||||
ifeq ($(OS_KIND),windows)
|
||||
|
|
@ -159,10 +161,9 @@ ifeq ($(OS_KIND),macos)
|
|||
endif
|
||||
endif
|
||||
|
||||
# Android (ELF, cross-compiled with the NDK)
|
||||
#
|
||||
# 64-bit ABIs build on any 64-bit host. armeabi-v7a additionally needs a
|
||||
# 32-bit host compiler: make ... HOST_CC="gcc -m32"
|
||||
# Android (ELF), cross-compiled with the NDK. 64-bit ABIs build on any 64-bit
|
||||
# host; armeabi-v7a also needs a 32-bit host compiler:
|
||||
# make PLATFORM=Android ANDROID_NDK=... HOST_CC="gcc -m32"
|
||||
ifeq ($(OS_KIND),android)
|
||||
ANDROID_NDK ?= $(ANDROID_NDK_HOME)
|
||||
ANDROID_API ?= 21
|
||||
|
|
@ -227,62 +228,44 @@ ifndef LINK_TARGET
|
|||
$(error Unsupported platform '$(PLATFORM)' -- supported: Linux, Android, Darwin, Windows, BSD)
|
||||
endif
|
||||
|
||||
# Host compiler for build-time tools (rlparser); the Windows branch pins gcc.
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tools and flags
|
||||
# ---------------------------------------------------------------------------
|
||||
# Host compiler for build-time tools (rlparser, LuaJIT's minilua/buildvm).
|
||||
HOST_CC ?= cc
|
||||
# Host LuaJIT that runs the binding generator.
|
||||
LUAJIT ?= luajit
|
||||
# Archiver passed to raylib's build. Cross toolchains ship their own.
|
||||
AR ?= ar
|
||||
|
||||
# raylib's RELEASE build appends -O1; -O2 is a big win for CPU-bound code.
|
||||
# Changing it needs `make clean` -- objects are not flag-aware.
|
||||
RAYLIB_OPT ?= -O2
|
||||
RAYLIB_MAKE_ARGS += CUSTOM_CFLAGS="$(RAYLIB_OPT)"
|
||||
|
||||
# Compiler / linker flags
|
||||
CFLAGS ?= -O2 -Wall
|
||||
CPPFLAGS += -I$(LUAJIT_SRC)
|
||||
|
||||
# LuaJIT: static archive only, built through the upstream GNU Makefile.
|
||||
# raygui.h includes raylib.h, hence both include paths. raymath needs no header
|
||||
# here: rcore.c already compiled it into libraylib.a. raygui has no such owner,
|
||||
# so its implementation is force-included into the CLI's translation unit.
|
||||
CPPFLAGS += -I$(LUAJIT_SRC) -I$(RAYLIB_SRC) -I$(RAYGUI_SRC) \
|
||||
-DRAYGUI_IMPLEMENTATION -include $(RAYGUI_SRC)/raygui.h
|
||||
|
||||
LUAJIT_MAKE_ARGS := BUILDMODE=static XCFLAGS="$(LUAJIT_XCFLAGS)" $(LUAJIT_EXTRA)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Submodules (static archives only)
|
||||
# ---------------------------------------------------------------------------
|
||||
$(LUAJIT_AR):
|
||||
$(MAKE) -C $(LUAJIT_SRC) $(LUAJIT_MAKE_ARGS) "LJCORE_O=ljamalg.o" libluajit.a
|
||||
|
||||
# raylib: static archive only; CC/AR are pinned, its Makefile defaults to host gcc/ar.
|
||||
# CC/AR are pinned: raylib's Makefile would otherwise pick host defaults.
|
||||
$(RAYLIB_AR):
|
||||
$(MAKE) -C $(RAYLIB_SRC) $(RAYLIB_MAKE_ARGS) CC="$(CC)" AR="$(AR)"
|
||||
|
||||
# Targets
|
||||
help:
|
||||
@echo "hate-no-d -- LuaJIT-based Lua runtime"
|
||||
@echo ""
|
||||
@echo "Targets:"
|
||||
@echo " make [all] CLI for the current platform + hate-no-d.lua"
|
||||
@echo " make bindings regenerate hate-no-d.lua only"
|
||||
@echo " make check-bindings verify hate-no-d.lua is reproducible and loads"
|
||||
@echo " make test run the functional test matrix"
|
||||
@echo " make check-valgrind run RAM-only tests under valgrind"
|
||||
@echo " make ownership regenerate the ownership snapshot (ownership.txt)"
|
||||
@echo " make check bindings + test matrix + valgrind"
|
||||
@echo " make print-config resolved configuration for the current target"
|
||||
@echo " make clean remove build/ and submodule build artifacts"
|
||||
@echo " make help this text"
|
||||
@echo ""
|
||||
@echo "Options (pass as VAR=value):"
|
||||
@echo " PLATFORM= Linux | Android | Darwin | Windows | a BSD"
|
||||
@echo " (default: uname -s)"
|
||||
@echo " WIN_ARCH= x86_64 | i686 [Windows]"
|
||||
@echo " ANDROID_NDK= NDK root, or export ANDROID_NDK_HOME [Android]"
|
||||
@echo " ANDROID_ABI= arm64-v8a | armeabi-v7a | x86_64 | x86 [Android]"
|
||||
@echo " ANDROID_API= target API level, default 21 [Android]"
|
||||
@echo " MACOSX_HRT= hardened-runtime JIT, default 1 [macOS]"
|
||||
@echo " MACOSX_DEPLOYMENT_TARGET= default 11.0 [macOS]"
|
||||
@echo " HOST_CC= host compiler for minilua/buildvm; needed"
|
||||
@echo " when the target is 32-bit and the host is not"
|
||||
@echo " LUAJIT= host LuaJIT for the generator, default luajit"
|
||||
@echo " CFLAGS= default -O2 -Wall"
|
||||
@echo " RAYLIB_OPT= raylib optimization flags, default -O2"
|
||||
@echo " LDFLAGS= extra linker flags"
|
||||
@echo " AR= archiver for raylib's build"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI
|
||||
# ---------------------------------------------------------------------------
|
||||
all: $(LINK_TARGET) $(BINDING)
|
||||
|
||||
$(BUILD_DIR):
|
||||
|
|
@ -303,13 +286,16 @@ $(BIN): $(OBJ) $(LUAJIT_AR) $(RAYLIB_AR)
|
|||
# ---------------------------------------------------------------------------
|
||||
# Lua bindings (hate-no-d.lua)
|
||||
#
|
||||
# gen-hate-no-d.lua turns the rlparser tables for raylib.h, rlgl.h and raymath.h
|
||||
# into one ffi.cdef block plus constants, wrappers and LuaCATS comments.
|
||||
# generate.lua turns the rlparser tables for raylib.h, rlgl.h, raymath.h and
|
||||
# raygui.h into one globals-only LuaJIT FFI binding: a single ffi.cdef block,
|
||||
# the constants, and one global wrapper per C function, all with LuaLS
|
||||
# annotations.
|
||||
#
|
||||
# The tables are generated into build/api from the pinned submodule headers, so
|
||||
# raylib's tools/rlparser/output (where raylib_api.lua is tracked) stays clean.
|
||||
# rlparser itself is built with HOST_CC, never the target CC: cross builds still
|
||||
# run it to produce the platform-independent binding.
|
||||
# rlparser runs on HOST_CC, never the target CC: cross builds still produce the
|
||||
# same platform-independent binding. generate.lua reads build/api/*.lua and
|
||||
# writes hate-no-d.lua (pass a different output path as its first argument).
|
||||
# ---------------------------------------------------------------------------
|
||||
$(RLPARSER): $(RLPARSER_DIR)/rlparser.c | $(BUILD_DIR)
|
||||
$(HOST_CC) -O2 -Wall -std=c99 -o $@ $(RLPARSER_DIR)/rlparser.c
|
||||
|
|
@ -317,41 +303,60 @@ $(RLPARSER): $(RLPARSER_DIR)/rlparser.c | $(BUILD_DIR)
|
|||
$(RAYLIB_API): $(RLPARSER) $(RAYLIB_SRC)/raylib.h | $(API_DIR)
|
||||
$(RLPARSER) -i $(RAYLIB_SRC)/raylib.h -o $@ -f LUA -d RLAPI
|
||||
|
||||
$(API_DIR)/rlgl_api.lua: $(RLPARSER) $(RAYLIB_SRC)/rlgl.h | $(API_DIR)
|
||||
$(RLGL_API): $(RLPARSER) $(RAYLIB_SRC)/rlgl.h | $(API_DIR)
|
||||
$(RLPARSER) -i $(RAYLIB_SRC)/rlgl.h -o $@ -f LUA -d RLAPI -t "RLGL IMPLEMENTATION"
|
||||
|
||||
$(API_DIR)/raymath_api.lua: $(RLPARSER) $(RAYLIB_SRC)/raymath.h | $(API_DIR)
|
||||
$(RAYMATH_API): $(RLPARSER) $(RAYLIB_SRC)/raymath.h | $(API_DIR)
|
||||
$(RLPARSER) -i $(RAYLIB_SRC)/raymath.h -o $@ -f LUA -d RMAPI
|
||||
|
||||
$(BINDING): gen-hate-no-d.lua $(API_DIR)/rlgl_api.lua $(API_DIR)/raymath_api.lua $(RAYLIB_API)
|
||||
$(RAYGUI_API): $(RLPARSER) $(RAYGUI_SRC)/raygui.h | $(API_DIR)
|
||||
$(RLPARSER) -i $(RAYGUI_SRC)/raygui.h -o $@ -f LUA -d RAYGUIAPI
|
||||
|
||||
$(BINDING): generate.lua $(RLGL_API) $(RAYMATH_API) $(RAYLIB_API) $(RAYGUI_API)
|
||||
@command -v $(LUAJIT) >/dev/null 2>&1 || { \
|
||||
echo "hate-no-d: cannot run '$(LUAJIT)' -- install LuaJIT or set LUAJIT=..." >&2; exit 1; }
|
||||
$(LUAJIT) gen-hate-no-d.lua --out=$@ $(GEN_FLAGS)
|
||||
$(LUAJIT) generate.lua
|
||||
|
||||
bindings: $(BINDING)
|
||||
|
||||
# Fail if regeneration is not byte-identical, the ownership classification
|
||||
# changed, or the module does not load.
|
||||
# Fail if regeneration is not byte-identical or the binding does not load.
|
||||
check-bindings: $(BINDING)
|
||||
$(LUAJIT) gen-hate-no-d.lua --out=$(BUILD_DIR)/hate-no-d.lua.tmp $(GEN_FLAGS)
|
||||
cmp $(BINDING) $(BUILD_DIR)/hate-no-d.lua.tmp
|
||||
rm -f $(BUILD_DIR)/hate-no-d.lua.tmp
|
||||
$(LUAJIT) gen-hate-no-d.lua --dump-ownership=$(BUILD_DIR)/ownership.txt $(GEN_FLAGS)
|
||||
cmp $(OWNERSHIP_SNAPSHOT) $(BUILD_DIR)/ownership.txt
|
||||
$(LUAJIT) -e 'local M = dofile("$(BINDING)"); assert(type(M) == "table"); assert(type(M.GetMousePosition) == "function", "raylib"); assert(type(M.rlLoadIdentity) == "function", "rlgl"); assert(type(M.Vector2Add) == "function", "raymath"); print("bindings ok")'
|
||||
@before=$$(cksum $(BINDING)); \
|
||||
$(LUAJIT) generate.lua; \
|
||||
[ "$$before" = "$$(cksum $(BINDING))" ] || { \
|
||||
echo "hate-no-d.lua: regeneration is not byte-identical" >&2; exit 1; }
|
||||
$(LUAJIT) -e 'dofile("$(BINDING)"); assert(type(GetMousePosition) == "function", "raylib"); assert(type(rlLoadIdentity) == "function", "rlgl"); assert(type(Vector2Add) == "function", "raymath"); assert(type(GuiButton) == "function", "raygui"); print("bindings ok")'
|
||||
|
||||
# Regenerate the committed ownership classification snapshot.
|
||||
ownership:
|
||||
$(LUAJIT) gen-hate-no-d.lua --dump-ownership=$(OWNERSHIP_SNAPSHOT) $(GEN_FLAGS)
|
||||
|
||||
test: $(LINK_TARGET) $(BINDING)
|
||||
sh tests/run.sh
|
||||
|
||||
check-valgrind: $(LINK_TARGET) $(BINDING)
|
||||
sh tests/run-valgrind.sh
|
||||
|
||||
check: all check-bindings test check-valgrind
|
||||
@echo "check: ok"
|
||||
# ---------------------------------------------------------------------------
|
||||
# Info and maintenance
|
||||
# ---------------------------------------------------------------------------
|
||||
help:
|
||||
@echo "hate-no-d -- LuaJIT-based Lua runtime"
|
||||
@echo ""
|
||||
@echo "Targets:"
|
||||
@echo " make [all] CLI for the current platform + hate-no-d.lua"
|
||||
@echo " make bindings regenerate hate-no-d.lua only"
|
||||
@echo " make check-bindings verify hate-no-d.lua is reproducible and loads"
|
||||
@echo " make print-config resolved configuration for the current target"
|
||||
@echo " make clean remove build/ and submodule build artifacts"
|
||||
@echo " make help this text"
|
||||
@echo ""
|
||||
@echo "Options (pass as VAR=value):"
|
||||
@echo " PLATFORM= Linux | Android | Darwin | Windows | a BSD"
|
||||
@echo " (default: uname -s)"
|
||||
@echo " WIN_ARCH= x86_64 | i686 [Windows]"
|
||||
@echo " ANDROID_NDK= NDK root, or export ANDROID_NDK_HOME [Android]"
|
||||
@echo " ANDROID_ABI= arm64-v8a | armeabi-v7a | x86_64 | x86 [Android]"
|
||||
@echo " ANDROID_API= target API level, default 21 [Android]"
|
||||
@echo " MACOSX_HRT= hardened-runtime JIT, default 1 [macOS]"
|
||||
@echo " MACOSX_DEPLOYMENT_TARGET= default 11.0 [macOS]"
|
||||
@echo " HOST_CC= host compiler for minilua/buildvm; needed"
|
||||
@echo " when the target is 32-bit and the host is not"
|
||||
@echo " LUAJIT= host LuaJIT for the generator, default luajit"
|
||||
@echo " CFLAGS= default -O2 -Wall"
|
||||
@echo " RAYLIB_OPT= raylib optimization flags, default -O2"
|
||||
@echo " LDFLAGS= extra linker flags"
|
||||
@echo " AR= archiver for raylib's build"
|
||||
|
||||
# Resolved configuration for the current target; useful before a cross build.
|
||||
print-config:
|
||||
|
|
@ -385,7 +390,5 @@ clean:
|
|||
rm -rf $(BUILD_DIR)
|
||||
rm -f $(BIN) hate-no-d.exe libhate-no-d.a libhate-no-d.a.mri $(LUAJIT_AR) $(RAYLIB_AR)
|
||||
rm -f $(BINDING)
|
||||
rm -f hate-no-d.o # object from builds that predate the move into build/
|
||||
|
||||
.PHONY: all clean print-config help bindings check-bindings \
|
||||
test check check-valgrind ownership
|
||||
.PHONY: all clean print-config help bindings check-bindings
|
||||
|
|
|
|||
87
README.md
87
README.md
|
|
@ -17,25 +17,25 @@ Should work on:
|
|||
Save this as `quick-start.lua`:
|
||||
|
||||
```lua
|
||||
local hnd = require("hate-no-d")
|
||||
require("hate-no-d")
|
||||
|
||||
hnd.InitWindow(1280, 720, "hate-no-d")
|
||||
hnd.SetTargetFPS(60)
|
||||
InitWindow(1280, 720, "hate-no-d")
|
||||
SetTargetFPS(60)
|
||||
|
||||
local text = "Your first hate-no-d application!"
|
||||
local fontSize = 48
|
||||
|
||||
while not hnd.WindowShouldClose() do
|
||||
hnd.BeginDrawing()
|
||||
hnd.ClearBackground(hnd.SKYBLUE)
|
||||
while not WindowShouldClose() do
|
||||
BeginDrawing()
|
||||
ClearBackground(SKYBLUE)
|
||||
|
||||
local width = hnd.MeasureText(text, fontSize)
|
||||
hnd.DrawText(text, (hnd.GetScreenWidth() - width)/2, (hnd.GetScreenHeight() - fontSize)/2, fontSize, hnd.DARKBLUE)
|
||||
local width = MeasureText(text, fontSize)
|
||||
DrawText(text, (GetScreenWidth() - width)/2, (GetScreenHeight() - fontSize)/2, fontSize, DARKBLUE)
|
||||
|
||||
hnd.EndDrawing()
|
||||
EndDrawing()
|
||||
end
|
||||
|
||||
hnd.CloseWindow()
|
||||
CloseWindow()
|
||||
```
|
||||
|
||||
Run it:
|
||||
|
|
@ -50,70 +50,9 @@ On Windows:
|
|||
hate-no-d.exe quick-start.lua
|
||||
```
|
||||
|
||||
`hate-no-d.lua` is the generated raylib/rlgl/raymath binding; release archives
|
||||
ship it next to the binary.
|
||||
|
||||
## Resource ownership
|
||||
|
||||
Every `Load*`/`Gen*` result that raylib hands to the caller is owned by the Lua
|
||||
value you get back. hate-no-d attaches a finalizer to the underlying cdata, so
|
||||
dropping the last reference is enough:
|
||||
|
||||
```lua
|
||||
local tex = hnd.LoadTexture("sprite.png") -- armed
|
||||
tex = nil
|
||||
collectgarbage() -- raylib UnloadTexture() runs here
|
||||
```
|
||||
|
||||
This covers textures, render textures, shaders, meshes, models, materials,
|
||||
fonts, waves, sounds, music streams, audio streams, images, automation event
|
||||
lists, directory listings, VR stereo configs, and the raw-pointer loaders
|
||||
(`LoadImageColors`, `LoadImagePalette`, `LoadFontData`, `LoadMaterials`,
|
||||
`LoadModelAnimations`, `LoadRandomSequence`, `LoadWaveSamples`,
|
||||
`LoadCodepoints`, `LoadTextLines`, `LoadFileData`, `CompressData`,
|
||||
`DecompressData`, `DecodeDataBase64`, `ExportImageToMemory`, `MemAlloc`, and
|
||||
rlgl's pixel readers).
|
||||
|
||||
- **Readiness gates.** A finalizer never touches a dead subsystem. GPU releases
|
||||
only run while a window is alive, audio releases only while the audio device
|
||||
is alive, and anything still armed when a window is closed or recreated is
|
||||
skipped rather than freed. `InitWindow`/`CloseWindow` bump an internal GPU
|
||||
generation so stale handles are never unloaded against a new context.
|
||||
- **`Unload*` is explicit and idempotent.** `hnd.UnloadImage(img)` frees
|
||||
immediately, zeroes the struct, and is safe to call again. It also cancels
|
||||
the finalizer, so a resource is never released twice. `M._ownership` exposes
|
||||
`armed`/`released`/`skipped`/`errors` counters (mostly useful for tests).
|
||||
- **Array loaders return their count.** Functions that fill a C `int *` count
|
||||
out-parameter (`LoadImagePalette`, `LoadFontData`, `LoadMaterials`,
|
||||
`LoadModelAnimations`, `LoadTextLines`, `LoadFileData`, `CompressData`,
|
||||
`DecompressData`, `DecodeDataBase64`, `ExportImageToMemory`) now return
|
||||
`pointer, count`. Passing a cdata still fills it, so existing code keeps
|
||||
working; the extra return value is safe to ignore.
|
||||
- **Views are never freed.** Values that alias raylib-owned memory are plain
|
||||
copies: `font.texture`, `rt.texture`, `rt.depth`, `model.meshes[i]`,
|
||||
`model.materials[i]`, `GetGlyphInfo()`, `GetFontDefault()`,
|
||||
`GetShapesTexture()`, and `LoadDroppedFiles()`. Keep the owner alive while you
|
||||
use a view — `GetGlyphInfo()`'s `image.data` points into the font.
|
||||
- **Materials are special.** `UnloadMaterial`/the material finalizer free only
|
||||
the `maps` array, never the shader or textures it references (those may be
|
||||
shared). Textures assigned with `SetMaterialTexture` are pinned for the
|
||||
lifetime of the material; `SetShapesTexture` pins the shapes texture, and
|
||||
unloading that texture restores the previous one.
|
||||
- **Mesh ownership transfers.** `LoadModelFromMesh(mesh)` consumes the mesh —
|
||||
the model frees it. Calling `UnloadMesh` on the consumed handle is a no-op.
|
||||
`LoadSoundAlias(src)` keeps `src` alive until the alias is released, and
|
||||
`LoadMusicStreamFromMemory` keeps its buffer alive.
|
||||
- **Raw memory.** `MemAlloc`/`MemRealloc` results are GC-managed; `MemFree`
|
||||
cancels the finalizer before freeing, so explicit frees are safe.
|
||||
`M.C` is the raw `ffi` namespace: calls made through it are unmanaged.
|
||||
- **Process exit.** The CLI runs finalizers on normal exit (it calls
|
||||
`lua_close`). `os.exit()` skips them; use `os.exit(code, true)` if you need
|
||||
them to run.
|
||||
|
||||
The ownership classification is exhaustive: the generator refuses to emit a
|
||||
binding if any function's return shape is unclassified, and `make check-bindings`
|
||||
diffs `ownership.txt` against the current raylib API. `make check` runs the test
|
||||
suite (including a valgrind pass over the RAM-only cases).
|
||||
`hate-no-d.lua` is the generated raylib/rlgl/raymath/raygui binding. It defines
|
||||
every function and constant as a Lua global, so `require("hate-no-d")` is all
|
||||
the setup you need; release archives ship it next to the binary.
|
||||
|
||||
## Building
|
||||
|
||||
|
|
|
|||
11
build.bat
11
build.bat
|
|
@ -109,7 +109,10 @@ echo === Building hate-no-d.exe ===
|
|||
if not exist "build" mkdir "build"
|
||||
if exist "build\hate-no-d.obj" del /q "build\hate-no-d.obj"
|
||||
cl /nologo /c /O2 /W4 /MT /D_CRT_SECURE_NO_WARNINGS ^
|
||||
/I "submodules\luajit\src" /Fo"build\hate-no-d.obj" hate-no-d.c
|
||||
/I "submodules\luajit\src" /I "submodules\raylib\src" /I "submodules\raygui\src" ^
|
||||
/DRAYGUI_IMPLEMENTATION /FI"submodules\raygui\src\raygui.h" ^
|
||||
/D"RAYGUIAPI=__declspec(dllexport)" ^
|
||||
/Fo"build\hate-no-d.obj" hate-no-d.c
|
||||
if errorlevel 1 goto :fail
|
||||
|
||||
link /nologo /OUT:hate-no-d.exe "build\hate-no-d.obj" ^
|
||||
|
|
@ -118,10 +121,10 @@ link /nologo /OUT:hate-no-d.exe "build\hate-no-d.obj" ^
|
|||
opengl32.lib gdi32.lib winmm.lib user32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib advapi32.lib
|
||||
if errorlevel 1 goto :fail
|
||||
|
||||
@rem ffi.C reads the exe's export table, so verify raylib really got exported.
|
||||
dumpbin /nologo /exports hate-no-d.exe | findstr /C:"InitWindow" >nul
|
||||
@rem ffi.C reads the exe's export table, so verify raylib and raygui really got exported.
|
||||
dumpbin /nologo /exports hate-no-d.exe | findstr /C:"InitWindow" /C:"GuiButton" >nul
|
||||
if errorlevel 1 (
|
||||
echo build.bat: hate-no-d.exe does not export raylib - ffi.C would not find it.
|
||||
echo build.bat: hate-no-d.exe does not export raylib/raygui - ffi.C would not find it.
|
||||
goto :fail
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1 +1,5 @@
|
|||
-I./submodules/luajit/src
|
||||
-I./submodules/raylib/src
|
||||
-I./submodules/raygui/src
|
||||
-DRAYGUI_IMPLEMENTATION
|
||||
-include ./submodules/raygui/src/raygui.h
|
||||
|
|
|
|||
2347
gen-hate-no-d.lua
2347
gen-hate-no-d.lua
File diff suppressed because it is too large
Load diff
810
generate.lua
Normal file
810
generate.lua
Normal file
|
|
@ -0,0 +1,810 @@
|
|||
---@class ApiParam
|
||||
---@field name string
|
||||
---@field type string
|
||||
---@field description string
|
||||
|
||||
---@class ApiField
|
||||
---@field name string
|
||||
---@field type string
|
||||
---@field description string
|
||||
|
||||
---@class ApiStruct
|
||||
---@field name string
|
||||
---@field description string
|
||||
---@field fields ApiField[]
|
||||
|
||||
---@class ApiAlias
|
||||
---@field name string
|
||||
---@field type string
|
||||
---@field description string
|
||||
|
||||
---@class ApiCallback
|
||||
---@field name string
|
||||
---@field description string
|
||||
---@field returnType string
|
||||
---@field params? ApiParam[]
|
||||
|
||||
---@class ApiFunction
|
||||
---@field name string
|
||||
---@field description string
|
||||
---@field returnType string
|
||||
---@field params? ApiParam[]
|
||||
|
||||
---@class ApiDefine
|
||||
---@field name string
|
||||
---@field type string
|
||||
---@field value string|number
|
||||
---@field description string
|
||||
|
||||
---@class ApiEnumValue
|
||||
---@field name string
|
||||
---@field description string
|
||||
---@field value string|number
|
||||
|
||||
---@class ApiEnum
|
||||
---@field name string
|
||||
---@field description string
|
||||
---@field values ApiEnumValue[]
|
||||
|
||||
---@class Api
|
||||
---@field structs ApiStruct[]
|
||||
---@field aliases ApiAlias[]
|
||||
---@field callbacks ApiCallback[]
|
||||
---@field functions ApiFunction[]
|
||||
---@field defines ApiDefine[]
|
||||
---@field enums ApiEnum[]
|
||||
|
||||
---@class CType
|
||||
---@field const boolean
|
||||
---@field base string
|
||||
---@field ptr integer
|
||||
|
||||
---@class ParamInfo
|
||||
---@field ann string
|
||||
---@field pre string[]|nil
|
||||
---@field arg string|nil
|
||||
|
||||
---@class GenState
|
||||
---@field struct_ffi string[]
|
||||
---@field callback_ffi string[]
|
||||
---@field function_ffi string[]
|
||||
---@field define_lines string[]
|
||||
---@field enum_lines string[]
|
||||
---@field alias_lines string[]
|
||||
---@field struct_lines string[]
|
||||
---@field callback_lines string[]
|
||||
---@field function_lines string[]
|
||||
---@field struct_types table<string, boolean>
|
||||
---@field callback_types table<string, boolean>
|
||||
---@field seen_struct_ffi table<string, boolean>
|
||||
---@field seen_alias_ffi table<string, boolean>
|
||||
---@field seen_callback_ffi table<string, boolean>
|
||||
---@field seen_function_ffi table<string, boolean>
|
||||
---@field seen_define table<string, boolean>
|
||||
---@field seen_enum_alias table<string, boolean>
|
||||
---@field seen_constant table<string, boolean>
|
||||
---@field seen_struct_doc table<string, boolean>
|
||||
---@field seen_alias_doc table<string, boolean>
|
||||
---@field seen_callback_doc table<string, boolean>
|
||||
---@field seen_function_doc table<string, boolean>
|
||||
|
||||
---@param fmt string
|
||||
---@param ... any
|
||||
---@return nil
|
||||
local function die(fmt, ...)
|
||||
io.stderr:write("[ERROR] " .. string.format(fmt, ...) .. "\n")
|
||||
os.exit(1)
|
||||
end
|
||||
|
||||
---@param file_path string
|
||||
---@return Api
|
||||
local function load_api_file(file_path)
|
||||
local chunk, err = loadfile(file_path)
|
||||
if not chunk then die("could not load %s: %s", file_path, err) end
|
||||
---@cast chunk -nil
|
||||
|
||||
local ok, data = pcall(chunk)
|
||||
if not ok then die("could not run %s: %s", file_path, data) end
|
||||
|
||||
if type(data) ~= "table" then die("%s did not return a table", file_path) end
|
||||
|
||||
---@cast data Api
|
||||
return data
|
||||
end
|
||||
|
||||
---Register a name the first time it is seen.
|
||||
---@param seen table<string, boolean>
|
||||
---@param name string
|
||||
---@return boolean claimed true when this is the first occurrence
|
||||
local function claim(seen, name)
|
||||
if seen[name] then return false end
|
||||
seen[name] = true
|
||||
return true
|
||||
end
|
||||
|
||||
---rlgl's parser output contains C preprocessor fragments in some field types;
|
||||
---ffi.cdef cannot parse those, so they are dropped.
|
||||
---@param field ApiField
|
||||
---@return boolean
|
||||
local function is_usable_field(field)
|
||||
return field.type:sub(1, 1) ~= "#"
|
||||
end
|
||||
|
||||
---@param strs ApiStruct[]
|
||||
---@param aliases ApiAlias[]|nil
|
||||
---@param seen_structs table<string, boolean>
|
||||
---@param seen_aliases table<string, boolean>
|
||||
---@return string[]
|
||||
local function structs_and_aliases_as_fii_lines(strs, aliases, seen_structs, seen_aliases)
|
||||
local result = {}
|
||||
-- Group aliases by their base struct so we emit them right after the struct is defined
|
||||
---@type table<string, ApiAlias[]>
|
||||
local alias_by_base = {}
|
||||
for _, a in ipairs(aliases or {}) do
|
||||
local base = a.type:match("^([%w_]+)")
|
||||
if not base then die("could not determine base type for alias %s", a.name) end
|
||||
alias_by_base[base] = alias_by_base[base] or {}
|
||||
table.insert(alias_by_base[base], a)
|
||||
end
|
||||
|
||||
for _, str in ipairs(strs) do
|
||||
if claim(seen_structs, str.name) then
|
||||
local fields = ""
|
||||
---@type table<string, boolean>
|
||||
local field_names = {}
|
||||
for _, field in ipairs(str.fields) do
|
||||
if is_usable_field(field) and not field_names[field.name] then
|
||||
field_names[field.name] = true
|
||||
local base_type, arr_size = field.type:match("^(.-)(%[%d+%])$")
|
||||
if base_type then
|
||||
fields = fields .. base_type .. " " .. field.name .. arr_size .. "; "
|
||||
else
|
||||
fields = fields .. field.type .. " " .. field.name .. "; "
|
||||
end
|
||||
end
|
||||
end
|
||||
if fields == "" then die("created a struct with an empty fields list") end
|
||||
table.insert(result, string.format("typedef struct %s { %s} %s;", str.name, fields, str.name))
|
||||
end
|
||||
|
||||
-- Aliases are emitted once per name, even if the base struct came from an
|
||||
-- earlier API (the typedef is already in the cdef by then).
|
||||
if alias_by_base[str.name] then
|
||||
for _, a in ipairs(alias_by_base[str.name]) do
|
||||
if claim(seen_aliases, a.name) then
|
||||
table.insert(result, string.format("typedef %s %s;", a.type, a.name))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return result
|
||||
end
|
||||
|
||||
---@param callbacks ApiCallback[]|nil
|
||||
---@param seen table<string, boolean>
|
||||
---@return string[]
|
||||
local function callbacks_as_ffi_lines(callbacks, seen)
|
||||
local result = {}
|
||||
for _, cb in ipairs(callbacks or {}) do
|
||||
if claim(seen, cb.name) then
|
||||
local params = {}
|
||||
for _, p in ipairs(cb.params or {}) do
|
||||
table.insert(params, p.type .. " " .. p.name)
|
||||
end
|
||||
table.insert(result, string.format("typedef %s (*%s)(%s);", cb.returnType, cb.name, table.concat(params, ", ")))
|
||||
end
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
---@param funcs ApiFunction[]
|
||||
---@param seen table<string, boolean>
|
||||
---@return string[]
|
||||
local function functions_as_ffi_lines(funcs, seen)
|
||||
local result = {}
|
||||
for _, func in ipairs(funcs) do
|
||||
if claim(seen, func.name) then
|
||||
local params = {}
|
||||
for _, param in ipairs(func.params or {}) do
|
||||
if param.type == "..." then
|
||||
table.insert(params, "...")
|
||||
else
|
||||
table.insert(params, param.type .. " " .. param.name)
|
||||
end
|
||||
end
|
||||
table.insert(result, string.format("%s %s(%s);", func.returnType, func.name, table.concat(params, ", ")))
|
||||
end
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
---@param defs ApiDefine[]
|
||||
---@param seen table<string, boolean>
|
||||
---@param seen_defines table<string, boolean>
|
||||
---@return string[]
|
||||
local function defines_as_lines(defs, seen, seen_defines)
|
||||
local result = {}
|
||||
for _, def in ipairs(defs) do
|
||||
local def_type = def.type
|
||||
local ignored = def_type == "GUARD" or def_type == "MACRO" or def_type == "UNKNOWN"
|
||||
if not ignored and claim(seen, def.name) then
|
||||
seen_defines[def.name] = true
|
||||
if def_type == "INT" or def_type == "STRING" or def_type == "FLOAT" or def_type == "INT_MATH" then
|
||||
local value = def.value
|
||||
if def_type == "STRING" then value = "\"" .. tostring(def.value) .. "\"" end
|
||||
local str = "" .. def.name .. " = " .. tostring(value)
|
||||
if def.description ~= "" then str = str .. " --" .. def.description end
|
||||
table.insert(result, str)
|
||||
elseif def_type == "FLOAT_MATH" then
|
||||
if def.name == "DEG2RAD" then
|
||||
table.insert(result, "DEG2RAD = 0.017453292519943")
|
||||
elseif def.name == "RAD2DEG" then
|
||||
table.insert(result, "RAD2DEG = 57.295779513082")
|
||||
else
|
||||
die("unknown float math define name %s", def.name)
|
||||
end
|
||||
elseif def_type == "COLOR" then
|
||||
local r, g, b, a = tostring(def.value):match("{%s*(%d+)%s*,%s*(%d+)%s*,%s*(%d+)%s*,%s*(%d+)%s*}")
|
||||
if not r then die("could not parse color define %s", def.name) end
|
||||
local str = string.format('%s = ffi.new("Color", { r = %s, g = %s, b = %s, a = %s })', def.name, r, g, b, a)
|
||||
table.insert(result, str)
|
||||
else
|
||||
die("unknown define type %s", def_type)
|
||||
end
|
||||
end
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
---@param enums ApiEnum[]
|
||||
---@param seen_aliases table<string, boolean>
|
||||
---@param seen_values table<string, boolean>
|
||||
---@return string[]
|
||||
local function enums_as_lines(enums, seen_aliases, seen_values)
|
||||
local result = {}
|
||||
for _, enum in ipairs(enums) do
|
||||
if claim(seen_aliases, enum.name) then
|
||||
table.insert(result, string.format("---%s", enum.description))
|
||||
table.insert(result, string.format("---@alias %s", enum.name))
|
||||
for _, value in ipairs(enum.values) do
|
||||
table.insert(result, string.format("---| `%s` #%s", value.name, value.description))
|
||||
end
|
||||
end
|
||||
for _, value in ipairs(enum.values) do
|
||||
if claim(seen_values, value.name) then
|
||||
if value.description ~= "" then table.insert(result, string.format("--- %s", value.description)) end
|
||||
table.insert(result, string.format("%s = %s", value.name, value.value))
|
||||
end
|
||||
end
|
||||
table.insert(result, "")
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
---@type table<string, string>
|
||||
local c_type_map = {
|
||||
["bool"] = "boolean",
|
||||
["float"] = "number",
|
||||
["double"] = "number",
|
||||
["int"] = "integer",
|
||||
["unsigned int"] = "integer",
|
||||
["long"] = "integer",
|
||||
["unsigned long"] = "integer",
|
||||
["short"] = "integer",
|
||||
["unsigned short"] = "integer",
|
||||
["char"] = "integer",
|
||||
["unsigned char"] = "integer",
|
||||
}
|
||||
|
||||
---@param c_type string
|
||||
---@return string
|
||||
local function map_type(c_type)
|
||||
-- Strip leading "const " first so "const char *" and "const void *" match cleanly
|
||||
c_type = c_type:gsub("^const%s+", "")
|
||||
|
||||
-- Special cases for C strings and void pointers in Raylib
|
||||
if c_type == "char *" or c_type:match("^char%[%d+%]$") then
|
||||
return "string"
|
||||
elseif c_type == "void *" or c_type == "rAudioBuffer *" or c_type == "rAudioProcessor *" or c_type == "va_list" then
|
||||
return "ffi.cdata*"
|
||||
end
|
||||
|
||||
-- Fixed-size arrays like "float[4]" or "Matrix[2]"
|
||||
local base_type = c_type:match("^(.-)%[%d+%]$")
|
||||
if base_type then
|
||||
return map_type(base_type) .. "[]"
|
||||
end
|
||||
|
||||
-- Pointers like "int *" or "Rectangle **"
|
||||
local ptr_base = c_type:match("^(.-)%s*%*$")
|
||||
if ptr_base then
|
||||
return map_type(ptr_base) .. "[]"
|
||||
end
|
||||
|
||||
return c_type_map[c_type] or c_type
|
||||
end
|
||||
|
||||
---Split a C type into pointer depth, constness and base name.
|
||||
---@param c_type string
|
||||
---@return CType
|
||||
local function parse_ctype(c_type)
|
||||
local s = c_type:gsub("^%s+", ""):gsub("%s+$", "")
|
||||
local is_const = false
|
||||
if s:match("^const%s+") then
|
||||
is_const = true
|
||||
s = s:gsub("^const%s+", "")
|
||||
end
|
||||
|
||||
local ptr = 0
|
||||
while true do
|
||||
local stripped = s:gsub("%s*%*%s*$", "")
|
||||
if stripped == s then break end
|
||||
ptr = ptr + 1
|
||||
s = stripped:gsub("%s+$", "")
|
||||
-- const after the pointer is not used by these APIs, but tolerate it
|
||||
s = s:gsub("^const%s+", "")
|
||||
end
|
||||
|
||||
return { const = is_const, base = s, ptr = ptr }
|
||||
end
|
||||
|
||||
---@param aliases ApiAlias[]
|
||||
---@param seen table<string, boolean>
|
||||
---@return string[]
|
||||
local function aliases_as_lines(aliases, seen)
|
||||
local result = {}
|
||||
for _, alias in ipairs(aliases) do
|
||||
if claim(seen, alias.name) then
|
||||
table.insert(result, string.format("---%s", alias.description))
|
||||
table.insert(result, string.format("---@alias %s %s", alias.name, map_type(alias.type)))
|
||||
table.insert(result, "")
|
||||
end
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
---@param strs ApiStruct[]
|
||||
---@param seen table<string, boolean>
|
||||
---@return string[]
|
||||
local function structs_as_lines(strs, seen)
|
||||
local result = {}
|
||||
for _, str in ipairs(strs) do
|
||||
if claim(seen, str.name) then
|
||||
table.insert(result, string.format("---%s", str.description))
|
||||
table.insert(result, string.format("---@class %s", str.name))
|
||||
---@type table<string, boolean>
|
||||
local field_names = {}
|
||||
for _, field in ipairs(str.fields) do
|
||||
if is_usable_field(field) and not field_names[field.name] then
|
||||
field_names[field.name] = true
|
||||
table.insert(result, string.format("---@field %s %s %s", field.name, map_type(field.type), field.description))
|
||||
end
|
||||
end
|
||||
table.insert(result, "")
|
||||
end
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
---@param callbacks ApiCallback[]
|
||||
---@param seen table<string, boolean>
|
||||
---@return string[]
|
||||
local function callbacks_as_lines(callbacks, seen)
|
||||
local result = {}
|
||||
for _, c in ipairs(callbacks) do
|
||||
if claim(seen, c.name) then
|
||||
if c.description ~= "" then
|
||||
table.insert(result, string.format("---%s", c.description))
|
||||
end
|
||||
local params = ""
|
||||
if c.params then
|
||||
for i, param in ipairs(c.params) do
|
||||
params = params .. param.name .. ": " .. map_type(param.type)
|
||||
if #c.params > 1 and i < #c.params then params = params .. ", " end
|
||||
end
|
||||
end
|
||||
local ret = ""
|
||||
if c.returnType ~= "void" then
|
||||
ret = ": " .. map_type(c.returnType)
|
||||
end
|
||||
table.insert(result, string.format("---@alias %s fun(%s)%s", c.name, params, ret))
|
||||
table.insert(result, "")
|
||||
end
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
---@type table<string, string>
|
||||
local param_enum_map = {
|
||||
-- By parameter name across Raylib:
|
||||
["key"] = "KeyboardKey",
|
||||
["logLevel"] = "TraceLogLevel",
|
||||
["cursor"] = "MouseCursor",
|
||||
["axis"] = "GamepadAxis",
|
||||
["uniformType"] = "ShaderUniformDataType",
|
||||
["filter"] = "TextureFilter",
|
||||
["wrap"] = "TextureWrap",
|
||||
["gesture"] = "Gesture",
|
||||
["mapType"] = "MaterialMapIndex",
|
||||
-- Disambiguated by FunctionName.paramName:
|
||||
["IsWindowState.flag"] = "ConfigFlags",
|
||||
["SetWindowState.flags"] = "ConfigFlags",
|
||||
["ClearWindowState.flags"] = "ConfigFlags",
|
||||
["SetConfigFlags.flags"] = "ConfigFlags",
|
||||
["SetGesturesEnabled.flags"] = "Gesture",
|
||||
["BeginBlendMode.mode"] = "BlendMode",
|
||||
["UpdateCamera.mode"] = "CameraMode",
|
||||
["LoadTextureCubemap.layout"] = "CubemapLayout",
|
||||
["IsMouseButtonPressed.button"] = "MouseButton",
|
||||
["IsMouseButtonDown.button"] = "MouseButton",
|
||||
["IsMouseButtonReleased.button"] = "MouseButton",
|
||||
["IsMouseButtonUp.button"] = "MouseButton",
|
||||
["IsGamepadButtonPressed.button"] = "GamepadButton",
|
||||
["IsGamepadButtonDown.button"] = "GamepadButton",
|
||||
["IsGamepadButtonReleased.button"] = "GamepadButton",
|
||||
["IsGamepadButtonUp.button"] = "GamepadButton",
|
||||
}
|
||||
|
||||
---@type table<string, string>
|
||||
local return_enum_map = {
|
||||
["GetKeyPressed"] = "KeyboardKey",
|
||||
["GetGamepadButtonPressed"] = "GamepadButton",
|
||||
["GetGestureDetected"] = "Gesture",
|
||||
}
|
||||
|
||||
---@param dst string[]
|
||||
---@param src string[]
|
||||
---@return nil
|
||||
local function append_all(dst, src)
|
||||
for _, line in ipairs(src) do
|
||||
dst[#dst + 1] = line
|
||||
end
|
||||
end
|
||||
|
||||
---@param func ApiFunction
|
||||
---@param param ApiParam
|
||||
---@param index integer
|
||||
---@param pname string
|
||||
---@param struct_types table<string, boolean>
|
||||
---@param callback_types table<string, boolean>
|
||||
---@return ParamInfo
|
||||
local function param_info(func, param, index, pname, struct_types, callback_types)
|
||||
local ct = parse_ctype(param.type)
|
||||
local var = "_a" .. index
|
||||
|
||||
if ct.ptr == 0 then
|
||||
if callback_types[ct.base] then
|
||||
return { ann = "ffi.cdata*", pre = nil, arg = nil }
|
||||
end
|
||||
local ptype = param_enum_map[func.name .. "." .. pname]
|
||||
or ((param.type == "int" or param.type == "unsigned int") and param_enum_map[pname])
|
||||
or map_type(param.type)
|
||||
return { ann = ptype, pre = nil, arg = nil }
|
||||
end
|
||||
|
||||
-- char ** / const char **: array of Lua strings
|
||||
if ct.base == "char" and ct.ptr == 2 then
|
||||
local array = 'to_array("const char *", ' .. pname .. ")"
|
||||
if not ct.const then
|
||||
array = 'ffi.cast("char **", ' .. array .. ")"
|
||||
end
|
||||
return {
|
||||
ann = "string[]|ffi.cdata*",
|
||||
arg = var,
|
||||
pre = {
|
||||
"local " .. var,
|
||||
'if type(' .. pname .. ') == "table" then ' .. var .. " = " .. array,
|
||||
"else " .. var .. " = " .. pname .. " end",
|
||||
},
|
||||
}
|
||||
end
|
||||
|
||||
-- const char * accepts a Lua string; non-const char * is a mutable buffer
|
||||
if ct.base == "char" and ct.ptr == 1 then
|
||||
if ct.const then
|
||||
return { ann = "string", pre = nil, arg = nil }
|
||||
end
|
||||
return { ann = "ffi.cdata*", pre = nil, arg = nil }
|
||||
end
|
||||
|
||||
if ct.base == "unsigned char" and ct.ptr == 1 and ct.const then
|
||||
return {
|
||||
ann = "string|integer[]|ffi.cdata*",
|
||||
arg = var,
|
||||
pre = {
|
||||
"local " .. var,
|
||||
string.format('if type(%s) == "string" then %s = ffi.cast("const unsigned char *", %s)', pname, var, pname),
|
||||
string.format('elseif type(%s) == "table" then %s = to_array("unsigned char", %s)', pname, var, pname),
|
||||
"else " .. var .. " = " .. pname .. " end",
|
||||
},
|
||||
}
|
||||
end
|
||||
|
||||
if ct.base == "void" and ct.ptr == 1 and ct.const then
|
||||
return {
|
||||
ann = "string|ffi.cdata*",
|
||||
arg = var,
|
||||
pre = {
|
||||
"local " .. var,
|
||||
string.format('if type(%s) == "string" then %s = ffi.cast("const void *", %s)', pname, var, pname),
|
||||
"else " .. var .. " = " .. pname .. " end",
|
||||
},
|
||||
}
|
||||
end
|
||||
|
||||
-- const T * where T is a scalar or a known struct/alias: tables become arrays
|
||||
if ct.const and ct.ptr == 1 and (c_type_map[ct.base] ~= nil or struct_types[ct.base]) then
|
||||
return {
|
||||
ann = map_type(ct.base) .. "[]|ffi.cdata*",
|
||||
arg = var,
|
||||
pre = {
|
||||
"local " .. var,
|
||||
string.format('if type(%s) == "table" then %s = to_array("%s", %s)', pname, var, ct.base, pname),
|
||||
"else " .. var .. " = " .. pname .. " end",
|
||||
},
|
||||
}
|
||||
end
|
||||
|
||||
return { ann = "ffi.cdata*", pre = nil, arg = nil }
|
||||
end
|
||||
|
||||
---@param func ApiFunction
|
||||
---@return string|nil
|
||||
local function return_ann(func)
|
||||
local ct = parse_ctype(func.returnType)
|
||||
if ct.ptr == 0 then
|
||||
if ct.base == "void" then return nil end
|
||||
return return_enum_map[func.name] or map_type(func.returnType)
|
||||
end
|
||||
if ct.base == "char" and ct.ptr == 1 then
|
||||
return ct.const and "string" or "string|nil"
|
||||
end
|
||||
return "ffi.cdata*"
|
||||
end
|
||||
|
||||
---@param funcs ApiFunction[]
|
||||
---@param seen table<string, boolean>
|
||||
---@param struct_types table<string, boolean>
|
||||
---@param callback_types table<string, boolean>
|
||||
---@return string[]
|
||||
local function functions_as_lines(funcs, seen, struct_types, callback_types)
|
||||
local result = {}
|
||||
for _, func in ipairs(funcs) do
|
||||
if claim(seen, func.name) then
|
||||
if func.name == "TextFormat" then
|
||||
-- LuaJIT cannot forward Lua varargs to a C vararg function with
|
||||
-- unknown types, so format in Lua and never call C here.
|
||||
table.insert(result, "---" .. func.description)
|
||||
table.insert(result, "---@param fmt string")
|
||||
table.insert(result, "---@param ... any")
|
||||
table.insert(result, "---@return string")
|
||||
table.insert(result, "function TextFormat(fmt, ...)")
|
||||
table.insert(result, ' if select("#", ...) == 0 then')
|
||||
table.insert(result, " return fmt")
|
||||
table.insert(result, " end")
|
||||
table.insert(result, " return string_format(fmt, ...)")
|
||||
table.insert(result, "end")
|
||||
elseif func.name == "TraceLog" then
|
||||
table.insert(result, "---" .. func.description)
|
||||
table.insert(result, "---@param level TraceLogLevel")
|
||||
table.insert(result, "---@param fmt string")
|
||||
table.insert(result, "---@param ... any")
|
||||
table.insert(result, "---@return nil")
|
||||
table.insert(result, "function TraceLog(level, fmt, ...)")
|
||||
table.insert(result, ' if select("#", ...) == 0 then')
|
||||
table.insert(result, ' C.TraceLog(level, "%s", fmt)')
|
||||
table.insert(result, " else")
|
||||
table.insert(result, ' C.TraceLog(level, "%s", string_format(fmt, ...))')
|
||||
table.insert(result, " end")
|
||||
table.insert(result, "end")
|
||||
else
|
||||
table.insert(result, "---" .. func.description)
|
||||
local sig = {}
|
||||
local args = {}
|
||||
local pre = {}
|
||||
local ann = {}
|
||||
for i, param in ipairs(func.params or {}) do
|
||||
local pname = (param.name == "end") and "_end" or param.name
|
||||
if param.type == "..." then
|
||||
table.insert(ann, "---@param ... any")
|
||||
table.insert(sig, "...")
|
||||
table.insert(args, "...")
|
||||
else
|
||||
local info = param_info(func, param, i, pname, struct_types, callback_types)
|
||||
table.insert(ann, string.format("---@param %s %s", pname, info.ann))
|
||||
if info.pre then append_all(pre, info.pre) end
|
||||
table.insert(sig, pname)
|
||||
table.insert(args, info.arg or pname)
|
||||
end
|
||||
end
|
||||
|
||||
for _, line in ipairs(ann) do table.insert(result, line) end
|
||||
local ra = return_ann(func)
|
||||
if ra then table.insert(result, "---@return " .. ra) end
|
||||
|
||||
local param_str = table.concat(sig, ", ")
|
||||
local call = string.format("C.%s(%s)", func.name, table.concat(args, ", "))
|
||||
table.insert(result, string.format("function %s(%s)", func.name, param_str))
|
||||
for _, line in ipairs(pre) do table.insert(result, " " .. line) end
|
||||
|
||||
local ct = parse_ctype(func.returnType)
|
||||
if ra == nil then
|
||||
table.insert(result, " " .. call)
|
||||
elseif ct.base == "char" and ct.ptr == 1 and ct.const then
|
||||
table.insert(result, " local _r = " .. call)
|
||||
table.insert(result, ' return _r ~= nil and ffi.string(_r) or ""')
|
||||
elseif ct.base == "char" and ct.ptr == 1 then
|
||||
table.insert(result, " local _r = " .. call)
|
||||
table.insert(result, " if _r == nil then return nil end")
|
||||
table.insert(result, " return ffi.string(_r)")
|
||||
else
|
||||
table.insert(result, " return " .. call)
|
||||
end
|
||||
table.insert(result, "end")
|
||||
end
|
||||
table.insert(result, "")
|
||||
end
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
---@param tbl table<string, boolean>
|
||||
---@return integer
|
||||
local function count_keys(tbl)
|
||||
local n = 0
|
||||
for _ in pairs(tbl) do n = n + 1 end
|
||||
return n
|
||||
end
|
||||
|
||||
---@return GenState
|
||||
local function new_state()
|
||||
return {
|
||||
struct_ffi = {},
|
||||
callback_ffi = {},
|
||||
function_ffi = {},
|
||||
define_lines = {},
|
||||
enum_lines = {},
|
||||
alias_lines = {},
|
||||
struct_lines = {},
|
||||
callback_lines = {},
|
||||
function_lines = {},
|
||||
struct_types = {},
|
||||
callback_types = {},
|
||||
|
||||
seen_struct_ffi = {},
|
||||
seen_alias_ffi = {},
|
||||
seen_callback_ffi = {},
|
||||
seen_function_ffi = {},
|
||||
seen_define = {},
|
||||
seen_enum_alias = {},
|
||||
seen_constant = {},
|
||||
seen_struct_doc = {},
|
||||
seen_alias_doc = {},
|
||||
seen_callback_doc = {},
|
||||
seen_function_doc = {},
|
||||
}
|
||||
end
|
||||
|
||||
---@param api Api
|
||||
---@param st GenState
|
||||
---@return nil
|
||||
local function wapi(api, st)
|
||||
append_all(st.struct_ffi, structs_and_aliases_as_fii_lines(
|
||||
api.structs, api.aliases, st.seen_struct_ffi, st.seen_alias_ffi))
|
||||
append_all(st.callback_ffi, callbacks_as_ffi_lines(api.callbacks, st.seen_callback_ffi))
|
||||
append_all(st.function_ffi, functions_as_ffi_lines(api.functions, st.seen_function_ffi))
|
||||
append_all(st.define_lines, defines_as_lines(api.defines, st.seen_constant, st.seen_define))
|
||||
append_all(st.enum_lines, enums_as_lines(api.enums, st.seen_enum_alias, st.seen_constant))
|
||||
append_all(st.alias_lines, aliases_as_lines(api.aliases, st.seen_alias_doc))
|
||||
append_all(st.struct_lines, structs_as_lines(api.structs, st.seen_struct_doc))
|
||||
append_all(st.callback_lines, callbacks_as_lines(api.callbacks, st.seen_callback_doc))
|
||||
append_all(st.function_lines, functions_as_lines(
|
||||
api.functions, st.seen_function_doc, st.struct_types, st.callback_types))
|
||||
end
|
||||
|
||||
local lines = {}
|
||||
|
||||
---@param line string
|
||||
---@return nil
|
||||
local function aline(line)
|
||||
lines[#lines + 1] = line -- append a line.
|
||||
end
|
||||
|
||||
-- Load order determines output order.
|
||||
---@type string[]
|
||||
local api_paths = {
|
||||
"build/api/raylib_api.lua",
|
||||
"build/api/rlgl_api.lua",
|
||||
"build/api/raymath_api.lua",
|
||||
"build/api/raygui_api.lua",
|
||||
}
|
||||
|
||||
---@type Api[]
|
||||
local apis = {}
|
||||
for _, path in ipairs(api_paths) do
|
||||
apis[#apis + 1] = load_api_file(path)
|
||||
end
|
||||
|
||||
local st = new_state()
|
||||
|
||||
---@type string[]
|
||||
local api_labels = {}
|
||||
for i, api in ipairs(apis) do
|
||||
for _, str in ipairs(api.structs) do st.struct_types[str.name] = true end
|
||||
for _, alias in ipairs(api.aliases) do st.struct_types[alias.name] = true end
|
||||
for _, cb in ipairs(api.callbacks) do st.callback_types[cb.name] = true end
|
||||
local label = api_paths[i]:match("([^/]+)_api%.lua$") or api_paths[i]
|
||||
api_labels[#api_labels + 1] = string.format("%s (%d functions)", label, #api.functions)
|
||||
end
|
||||
|
||||
for _, api in ipairs(apis) do
|
||||
wapi(api, st)
|
||||
end
|
||||
|
||||
---@type string
|
||||
local out_path = (arg and arg[1]) or "hate-no-d.lua"
|
||||
|
||||
local n_functions = count_keys(st.seen_function_doc)
|
||||
local n_structs = count_keys(st.seen_struct_doc)
|
||||
local n_aliases = count_keys(st.seen_alias_doc)
|
||||
local n_callbacks = count_keys(st.seen_callback_doc)
|
||||
local n_defines = count_keys(st.seen_define)
|
||||
local n_enums = count_keys(st.seen_enum_alias)
|
||||
|
||||
aline("--[[")
|
||||
aline(string.format(" %s - generated by generate.lua, do not edit.", out_path))
|
||||
aline(" APIs: " .. table.concat(api_labels, ", "))
|
||||
aline(string.format(" %d functions, %d structs, %d aliases, %d callbacks, %d defines, %d enums",
|
||||
n_functions, n_structs, n_aliases, n_callbacks, n_defines, n_enums))
|
||||
aline("]]")
|
||||
aline("")
|
||||
aline('local ffi = require("ffi")')
|
||||
aline("")
|
||||
aline("ffi.cdef[[")
|
||||
aline("typedef struct rAudioBuffer rAudioBuffer;")
|
||||
aline("typedef struct rAudioProcessor rAudioProcessor;")
|
||||
for _, l in ipairs(st.struct_ffi) do aline(l) end
|
||||
aline("")
|
||||
for _, l in ipairs(st.callback_ffi) do aline(l) end
|
||||
aline("")
|
||||
for _, l in ipairs(st.function_ffi) do aline(l) end
|
||||
aline("]]")
|
||||
aline("")
|
||||
aline("local C = ffi.C")
|
||||
aline("local string_format = string.format")
|
||||
aline("local type, select = type, select")
|
||||
aline("")
|
||||
aline("local function to_array(ct, t, n)")
|
||||
aline(" n = n or #t")
|
||||
aline(' local a = ffi.new(ct .. "[?]", n)')
|
||||
aline(" for i = 1, n do")
|
||||
aline(" a[i - 1] = t[i]")
|
||||
aline(" end")
|
||||
aline(" return a")
|
||||
aline("end")
|
||||
aline("")
|
||||
for _, l in ipairs(st.define_lines) do aline(l) end
|
||||
aline("")
|
||||
for _, l in ipairs(st.enum_lines) do aline(l) end
|
||||
aline("")
|
||||
for _, l in ipairs(st.alias_lines) do aline(l) end
|
||||
aline("")
|
||||
for _, l in ipairs(st.struct_lines) do aline(l) end
|
||||
aline("")
|
||||
for _, l in ipairs(st.callback_lines) do aline(l) end
|
||||
aline("")
|
||||
for _, l in ipairs(st.function_lines) do aline(l) end
|
||||
|
||||
local fh, open_err = io.open(out_path, "wb")
|
||||
if not fh then die("could not open %s for writing: %s", out_path, open_err) end
|
||||
---@cast fh -nil
|
||||
|
||||
fh:write(table.concat(lines, "\n"))
|
||||
fh:write("\n")
|
||||
fh:close()
|
||||
|
||||
io.stderr:write(string.format(
|
||||
"generate: wrote %s (%d functions, %d structs, %d aliases, %d callbacks, %d defines, %d enums)\n",
|
||||
out_path, n_functions, n_structs, n_aliases, n_callbacks, n_defines, n_enums
|
||||
))
|
||||
11923
hate-no-d.lua
11923
hate-no-d.lua
File diff suppressed because it is too large
Load diff
|
|
@ -1 +1 @@
|
|||
Subproject commit a4c064539ea931274d407e1249b4bb575424a0f4
|
||||
Subproject commit ea9eb7edb5eac4a9d175d74523db34fac0fa5180
|
||||
1
submodules/raygui
Submodule
1
submodules/raygui
Submodule
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 1abccb3a5303d041dc14404b7dd874fa665dd4af
|
||||
|
|
@ -1 +1 @@
|
|||
Subproject commit ad124dd7f5864fcdd9cc8868d5baae61041a7d3c
|
||||
Subproject commit 2f4b7d8e9f4aef3d5ed81a683b54594849e9d7a7
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
-- 01: 10k textures all reach the GC and are released; RSS plateaus.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local R = M.load()
|
||||
|
||||
if not M.window(64, 64) then
|
||||
M.skip("01_many_textures", "no window")
|
||||
return
|
||||
end
|
||||
|
||||
M.reset()
|
||||
local N = 10000
|
||||
local img = R.GenImageColor(2, 2, R.RED)
|
||||
M.ok(img.data ~= nil, "source image valid")
|
||||
|
||||
local b0 = M.snapshot()
|
||||
do
|
||||
local tex = {}
|
||||
for i = 1, N do tex[i] = R.LoadTextureFromImage(img) end
|
||||
end
|
||||
|
||||
M.eq(M.delta(b0, "armed"), N, "armed delta after batch 1")
|
||||
M.gc(3)
|
||||
M.eq(M.delta(b0, "released"), N, "released delta after batch 1")
|
||||
M.eq(M.delta(b0, "errors"), 0, "errors after batch 1")
|
||||
|
||||
-- Second batch: compared against the RSS after the first batch has been
|
||||
-- collected, so allocator warm-up does not count as growth.
|
||||
local rss1 = M.rss_kb()
|
||||
local b1 = M.snapshot()
|
||||
do
|
||||
local tex = {}
|
||||
for i = 1, N do tex[i] = R.LoadTextureFromImage(img) end
|
||||
end
|
||||
M.gc(3)
|
||||
M.eq(M.delta(b1, "released"), N, "released delta after batch 2")
|
||||
M.eq(M.delta(b1, "errors"), 0, "errors after batch 2")
|
||||
|
||||
local rss2 = M.rss_kb()
|
||||
if rss1 > 0 then
|
||||
local growth = (rss2 - rss1) / rss1
|
||||
M.ok(growth < 0.05, string.format(
|
||||
"rss did not plateau: %d kB -> %d kB (%.1f%%)", rss1, rss2, growth * 100))
|
||||
end
|
||||
|
||||
R.UnloadImage(img)
|
||||
print("ok 01_many_textures")
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
-- 02: explicit UnloadImage is immediate, idempotent, and does not double-free
|
||||
-- when the object is later collected.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local R = M.load()
|
||||
|
||||
M.reset()
|
||||
local b = M.snapshot()
|
||||
|
||||
local img = R.GenImageColor(4, 4, R.RED)
|
||||
M.ok(img.data ~= nil, "image data allocated")
|
||||
M.eq(M.delta(b, "armed"), 1, "image armed")
|
||||
|
||||
R.UnloadImage(img)
|
||||
M.eq(M.delta(b, "released"), 1, "explicit unload released exactly once")
|
||||
M.eq(img.data, nil, "img.data nil after unload")
|
||||
M.eq(img.width, 0, "img.width zero after unload")
|
||||
M.eq(img.height, 0, "img.height zero after unload")
|
||||
|
||||
-- Calling it again is a no-op.
|
||||
R.UnloadImage(img)
|
||||
M.eq(M.delta(b, "released"), 1, "second explicit unload is a no-op")
|
||||
|
||||
-- Dropping the disarmed object must not release it a second time.
|
||||
img = nil
|
||||
M.gc(3)
|
||||
M.eq(M.delta(b, "released"), 1, "GC after explicit unload is a no-op")
|
||||
|
||||
-- A plain GC-collected image releases exactly once.
|
||||
local img2 = R.GenImageColor(4, 4, R.RED)
|
||||
img2 = nil
|
||||
M.gc(3)
|
||||
M.eq(M.delta(b, "released"), 2, "GC released the second image exactly once")
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
|
||||
|
||||
print("ok 02_explicit")
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
-- 03: GetShapesTexture / GetFontDefault return borrowed views: they must not
|
||||
-- be armed and must stay stable across a GC cycle.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local R = M.load()
|
||||
|
||||
if not M.window(64, 64) then
|
||||
M.skip("03_borrowed", "no window")
|
||||
return
|
||||
end
|
||||
|
||||
M.reset()
|
||||
local b = M.snapshot()
|
||||
|
||||
local a = R.GetShapesTexture()
|
||||
local f = R.GetFontDefault()
|
||||
local ida, idb = a.id, f.texture.id
|
||||
M.ok(ida ~= 0, "default shapes texture has an id")
|
||||
M.eq(M.delta(b, "armed"), 0, "borrowed shapes texture was not armed")
|
||||
|
||||
-- Drop the views (and anything derived from them) and force a full GC. If
|
||||
-- these were armed, the finalizers would unload raylib's static resources.
|
||||
a, f = nil, nil
|
||||
M.gc(3)
|
||||
|
||||
local a2 = R.GetShapesTexture()
|
||||
local f2 = R.GetFontDefault()
|
||||
M.eq(a2.id, ida, "shapes texture id survived GC")
|
||||
M.eq(f2.texture.id, idb, "default font texture id survived GC")
|
||||
M.eq(M.delta(b, "armed"), 0, "no borrowed resource was armed")
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
|
||||
|
||||
print("ok 03_borrowed")
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
-- 04: LoadModelFromMesh consumes the mesh; unloading the model releases it
|
||||
-- once, and a saved (zeroed) mesh copy is a harmless no-op.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local ffi = require("ffi")
|
||||
local R = M.load()
|
||||
|
||||
if not M.window(64, 64) then
|
||||
M.skip("04_model_from_mesh", "no window")
|
||||
return
|
||||
end
|
||||
|
||||
M.reset()
|
||||
local b = M.snapshot()
|
||||
|
||||
local mesh = R.GenMeshCube(1, 1, 1)
|
||||
M.ok(mesh.vertexCount > 0, "cube mesh built")
|
||||
|
||||
local model = R.LoadModelFromMesh(mesh)
|
||||
M.eq(model.meshCount, 1, "model has one mesh")
|
||||
M.ok(model.meshes[0].vertexCount > 0, "model mesh is valid")
|
||||
if R.IsModelReady ~= nil then
|
||||
M.ok(R.IsModelReady(model), "model is ready")
|
||||
end
|
||||
|
||||
-- Ownership moved to the model: the mesh was disarmed and zeroed.
|
||||
M.ok(mesh.vertices == nil,
|
||||
"mesh was consumed (vertices cleared) by LoadModelFromMesh")
|
||||
local mesh_copy = ffi.new("Mesh[1]", mesh)
|
||||
|
||||
mesh = nil
|
||||
M.gc(3)
|
||||
M.eq(M.delta(b, "released"), 0, "consumed mesh was not released separately")
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors before unload")
|
||||
|
||||
R.UnloadModel(model)
|
||||
M.eq(M.delta(b, "released"), 1, "UnloadModel released exactly once")
|
||||
|
||||
-- A saved copy of the (zeroed) mesh must be a no-op, not a crash/double free.
|
||||
R.UnloadMesh(mesh_copy[0])
|
||||
M.eq(M.delta(b, "errors"), 0, "saved mesh copy raised no errors")
|
||||
M.ok(M.delta(b, "released") <= 2,
|
||||
"saved mesh copy did not free the model's mesh again")
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
|
||||
|
||||
print("ok 04_model_from_mesh")
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
-- 05: LoadSoundAlias keeps the source alive, and dropping the alias does not
|
||||
-- invalidate the source.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local R = M.load()
|
||||
|
||||
if not M.audio() then
|
||||
M.skip("05_sound_alias", "no audio device")
|
||||
return
|
||||
end
|
||||
|
||||
M.reset()
|
||||
|
||||
local data, size = M.wav_bytes(4410) -- 0.1 s, 44100 Hz mono s16
|
||||
local wave = R.LoadWaveFromMemory(".wav", data, size)
|
||||
M.ok(wave.data ~= nil, "WAV decoded")
|
||||
M.eq(wave.channels, 1, "wave is mono")
|
||||
M.ok(wave.frameCount > 0, "wave has samples")
|
||||
|
||||
local src = R.LoadSoundFromWave(wave)
|
||||
M.ok(src.stream.buffer ~= nil, "sound created")
|
||||
R.UnloadWave(wave)
|
||||
|
||||
-- Test A: alias outlives the Lua reference to its source.
|
||||
local alias = R.LoadSoundAlias(src)
|
||||
M.ok(alias.stream.buffer ~= nil, "alias created")
|
||||
|
||||
src = nil
|
||||
M.gc(3)
|
||||
M.ok(alias.stream.buffer ~= nil, "alias buffer valid after source GC")
|
||||
M.ok(M.ow().errors == 0, "no finalizer errors with a live alias")
|
||||
|
||||
R.UnloadSoundAlias(alias)
|
||||
alias = nil
|
||||
M.gc(3)
|
||||
|
||||
-- Test B: dropping the alias first leaves the source usable.
|
||||
local wave2 = R.LoadWaveFromMemory(".wav", data, size)
|
||||
local src2 = R.LoadSoundFromWave(wave2)
|
||||
R.UnloadWave(wave2)
|
||||
M.ok(src2.stream.buffer ~= nil, "second sound created")
|
||||
|
||||
local alias2 = R.LoadSoundAlias(src2)
|
||||
M.ok(alias2.stream.buffer ~= nil, "second alias created")
|
||||
|
||||
alias2 = nil
|
||||
M.gc(3)
|
||||
M.ok(src2.stream.buffer ~= nil, "source survives alias GC")
|
||||
R.PlaySound(src2) -- must not crash / must not use a freed buffer
|
||||
|
||||
R.UnloadSound(src2)
|
||||
src2 = nil
|
||||
M.gc(3)
|
||||
|
||||
print("ok 05_sound_alias")
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
-- 06: closing the window makes GPU finalizers skip instead of calling into a
|
||||
-- dead GL context. The process must survive and report no errors.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local R = M.load()
|
||||
|
||||
if not M.window(64, 64) then
|
||||
M.skip("06_teardown", "no window")
|
||||
return
|
||||
end
|
||||
|
||||
M.reset()
|
||||
local img = R.GenImageColor(4, 4, R.RED)
|
||||
local b = M.snapshot()
|
||||
|
||||
-- Hold every resource until after CloseWindow so nothing can be collected
|
||||
-- while the GPU context is still alive.
|
||||
local pool = {}
|
||||
for i = 1, 5 do
|
||||
pool[i] = R.LoadTextureFromImage(img)
|
||||
M.ok(pool[i].id ~= 0, "texture " .. i .. " created")
|
||||
end
|
||||
pool[6] = R.GenImageColor(4, 4, R.WHITE)
|
||||
pool[7] = R.GenImageColor(4, 4, R.BLUE)
|
||||
-- Kept out of the pool so it can be explicitly unloaded after the window dies.
|
||||
local late = R.LoadTextureFromImage(img)
|
||||
M.eq(M.delta(b, "armed"), 8, "six textures and two images armed")
|
||||
|
||||
R.CloseWindow()
|
||||
|
||||
-- Explicit unload after CloseWindow must also be a safe no-op: no GL call, the
|
||||
-- handle is zeroed, and the counters stay clean.
|
||||
local rel = M.snapshot()
|
||||
R.UnloadTexture(late)
|
||||
M.eq(M.delta(rel, "errors"), 0, "explicit unload after CloseWindow is safe")
|
||||
M.eq(M.delta(rel, "released"), 0, "explicit unload after CloseWindow is skipped")
|
||||
M.eq(late.id, 0, "explicit unload after CloseWindow zeroes the handle")
|
||||
late = nil
|
||||
|
||||
-- After CloseWindow the five texture finalizers must refuse to touch the dead
|
||||
-- GPU context. The two RAM images may still be released.
|
||||
pool = nil
|
||||
M.gc(3)
|
||||
M.ok(M.delta(b, "skipped") >= 5,
|
||||
string.format("expected >=5 skipped finalizers, got %d",
|
||||
M.delta(b, "skipped")))
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors after CloseWindow")
|
||||
M.eq(M.delta(b, "released"), 2, "RAM images still released after CloseWindow")
|
||||
|
||||
img = nil
|
||||
M.gc(2)
|
||||
|
||||
print("ok 06_teardown")
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
-- 07: inout Image parameters mutate the caller's cdata in place, and the
|
||||
-- wrapper returns that same object so the GC sees exactly one owner.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local R = M.load()
|
||||
|
||||
M.reset()
|
||||
local b = M.snapshot()
|
||||
|
||||
local rgba = R.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
|
||||
local gray = R.PIXELFORMAT_UNCOMPRESSED_GRAYSCALE
|
||||
|
||||
local img = R.GenImageColor(4, 4, R.RED)
|
||||
M.eq(img.format, rgba, "GenImageColor produced RGBA")
|
||||
|
||||
local out = R.ImageFormat(img, gray)
|
||||
M.ok(rawequal(out, img), "ImageFormat returned the caller's cdata")
|
||||
M.eq(img.format, gray, "ImageFormat mutated the cdata")
|
||||
|
||||
img = nil
|
||||
out = nil
|
||||
M.gc(3)
|
||||
M.eq(M.delta(b, "released"), 1, "ImageFormat did not create a second owner")
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
|
||||
|
||||
local img2 = R.GenImageColor(4, 4, R.RED)
|
||||
local resized = R.ImageResize(img2, 2, 2)
|
||||
M.ok(rawequal(resized, img2), "ImageResize returned the caller's cdata")
|
||||
M.eq(img2.width, 2, "ImageResize width")
|
||||
M.eq(img2.height, 2, "ImageResize height")
|
||||
|
||||
img2 = nil
|
||||
resized = nil
|
||||
M.gc(3)
|
||||
M.eq(M.delta(b, "released"), 2, "ImageResize did not create a second owner")
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors after resize")
|
||||
|
||||
print("ok 07_inout")
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
-- 08: pinned textures (shapes texture, material maps) stay alive while pinned,
|
||||
-- and the pins are dropped when the owning object is released.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local ffi = require("ffi")
|
||||
local R = M.load()
|
||||
|
||||
if not M.window(64, 64) then
|
||||
M.skip("08_pins", "no window")
|
||||
return
|
||||
end
|
||||
|
||||
M.reset()
|
||||
local b = M.snapshot()
|
||||
|
||||
local img = R.GenImageColor(2, 2, R.WHITE)
|
||||
|
||||
-- (a) shapes texture pin
|
||||
local tex = R.LoadTextureFromImage(img)
|
||||
local tex_id = tex.id
|
||||
M.ok(tex_id ~= 0, "shapes texture created")
|
||||
local tex_copy = ffi.new("Texture2D[1]", tex)
|
||||
M.eq(tex_copy[0].id, tex_id, "saved raw texture copy")
|
||||
|
||||
R.SetShapesTexture(tex, ffi.new("Rectangle", 0, 0, 1, 1))
|
||||
|
||||
tex = nil
|
||||
M.gc(3)
|
||||
M.eq(M.delta(b, "released"), 0, "pinned shapes texture was not collected")
|
||||
local shape = R.GetShapesTexture()
|
||||
M.ok(shape.id ~= 0, "shapes texture is installed")
|
||||
M.eq(shape.id, tex_id, "installed shapes texture is the pinned one")
|
||||
|
||||
-- Explicit unload of the saved copy must restore the previous shapes texture
|
||||
-- and not crash. (The original cdata is the one held by the pin.)
|
||||
R.UnloadTexture(tex_copy[0])
|
||||
M.ok(R.GetShapesTexture().id ~= tex_id, "previous shapes texture restored")
|
||||
|
||||
-- (b) material map pin
|
||||
local mat = R.LoadMaterialDefault()
|
||||
M.ok(mat.maps ~= nil, "default material has maps")
|
||||
local tex2 = R.LoadTextureFromImage(img)
|
||||
local tex2_id = tex2.id
|
||||
R.SetMaterialTexture(mat, R.MATERIAL_MAP_DIFFUSE, tex2)
|
||||
M.eq(mat.maps[R.MATERIAL_MAP_DIFFUSE].texture.id, tex2_id,
|
||||
"material map references the texture")
|
||||
|
||||
tex2 = nil
|
||||
M.gc(3)
|
||||
M.ok(mat.maps[R.MATERIAL_MAP_DIFFUSE].texture.id ~= 0,
|
||||
"material pin kept the map texture alive")
|
||||
M.eq(mat.maps[R.MATERIAL_MAP_DIFFUSE].texture.id, tex2_id,
|
||||
"material map still points at the pinned texture")
|
||||
|
||||
R.UnloadMaterial(mat)
|
||||
mat = nil
|
||||
-- Pins are dropped with the material; the texture can now go away.
|
||||
M.gc(3)
|
||||
|
||||
R.UnloadImage(img)
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
|
||||
|
||||
print("ok 08_pins")
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
-- 08b: model sub-objects (meshes[i], materials[i], shader views) are views:
|
||||
-- reading them must not arm anything, and the model owns the release.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local R = M.load()
|
||||
|
||||
if not M.window(64, 64) then
|
||||
M.skip("08b_views", "no window")
|
||||
return
|
||||
end
|
||||
|
||||
M.reset()
|
||||
|
||||
local mesh = R.GenMeshCube(1, 1, 1)
|
||||
local model = R.LoadModelFromMesh(mesh)
|
||||
mesh = nil
|
||||
M.eq(model.meshCount, 1, "model has one mesh")
|
||||
M.eq(model.materialCount, 1, "model has one material")
|
||||
|
||||
local b = M.snapshot()
|
||||
|
||||
local m1 = model.meshes[0]
|
||||
local mat1 = model.materials[0]
|
||||
local probe = m1.vertexCount + mat1.shader.id
|
||||
M.ok(m1.vertexCount > 0, "mesh view is readable (probe=" .. probe .. ")")
|
||||
|
||||
m1, mat1 = nil, nil
|
||||
M.gc(3)
|
||||
M.eq(M.delta(b, "armed"), 0, "views never arm")
|
||||
|
||||
R.UnloadModel(model)
|
||||
M.ok(M.delta(b, "released") >= 1, "model released")
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
|
||||
model = nil
|
||||
M.gc(2)
|
||||
|
||||
print("ok 08b_views")
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
-- 08c: GenImageFontAtlas attaches the Rectangle* output to the returned Image;
|
||||
-- both must be freed exactly once (run under valgrind for the real proof).
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local ffi = require("ffi")
|
||||
local R = M.load()
|
||||
|
||||
M.reset()
|
||||
local b = M.snapshot()
|
||||
|
||||
local keep = {}
|
||||
local glyphs = ffi.new("GlyphInfo[2]")
|
||||
for i = 0, 1 do
|
||||
local im = R.GenImageColor(4, 4, R.WHITE)
|
||||
keep[#keep + 1] = im
|
||||
glyphs[i].value = 65 + i
|
||||
glyphs[i].offsetX = 0
|
||||
glyphs[i].offsetY = 0
|
||||
glyphs[i].advanceX = 4
|
||||
glyphs[i].image = im
|
||||
end
|
||||
|
||||
local atlas, recs = R.GenImageFontAtlas(glyphs, 2, 8, 1, 0)
|
||||
M.ok(atlas ~= nil, "font atlas returned")
|
||||
M.ok(atlas.data ~= nil, "font atlas has pixel data")
|
||||
M.ok(recs ~= nil, "glyph rectangles returned")
|
||||
|
||||
atlas, recs = nil, nil
|
||||
keep = nil
|
||||
glyphs = nil
|
||||
M.gc(3)
|
||||
|
||||
M.ok(M.delta(b, "released") >= 1,
|
||||
"atlas Image and attached Rectangle* were released")
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
|
||||
|
||||
print("ok 08c_font_atlas")
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
-- 09: every owned-pointer return releases exactly one allocation at GC time.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local ffi = require("ffi")
|
||||
local R = M.load()
|
||||
|
||||
M.reset()
|
||||
|
||||
local img = R.GenImageColor(2, 2, R.RED)
|
||||
M.ok(img.data ~= nil, "source image valid")
|
||||
|
||||
-- Baseline after the image exists: the image is armed too, and it is released
|
||||
-- explicitly at the end of the case.
|
||||
local b = M.snapshot()
|
||||
|
||||
local count = M.out_int()
|
||||
local comp_size = M.out_int()
|
||||
|
||||
-- Keep every result alive until the batch is complete, then drop them all at
|
||||
-- once so a single GC verifies the whole set.
|
||||
local keep = {}
|
||||
keep[#keep + 1] = R.LoadImageColors(img)
|
||||
keep[#keep + 1] = R.LoadImagePalette(img, 8, count)
|
||||
keep[#keep + 1] = R.LoadRandomSequence(4, 1, 5)
|
||||
keep[#keep + 1] = R.LoadCodepoints("abc", count)
|
||||
keep[#keep + 1] = R.LoadTextLines("a\nb\n", count)
|
||||
keep[#keep + 1] = R.CompressData("abcd", 4, comp_size)
|
||||
keep[#keep + 1] = R.DecodeDataBase64(
|
||||
R.EncodeDataBase64("abcd", 4, count), count)
|
||||
keep[#keep + 1] = R.TextReplaceAlloc("a", "a", "b")
|
||||
local n = #keep
|
||||
M.ok(n >= 8, "created at least 8 owned pointers, got " .. n)
|
||||
for i = 1, n do
|
||||
M.ok(keep[i] ~= nil, "pointer " .. i .. " is non-nil")
|
||||
end
|
||||
|
||||
keep = nil
|
||||
M.gc(3)
|
||||
|
||||
-- 7 of the 8 results are owned pointers; EncodeDataBase64/TextReplaceAlloc
|
||||
-- return owned strings that the wrapper copies and frees immediately (valgrind
|
||||
-- proves those). Every owned pointer must be armed and released exactly once.
|
||||
M.ok(M.delta(b, "armed") >= 7,
|
||||
string.format("expected >=7 armed pointers, got %d", M.delta(b, "armed")))
|
||||
M.ok(M.delta(b, "released") >= 7,
|
||||
string.format("expected >=7 released pointers, got %d",
|
||||
M.delta(b, "released")))
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
|
||||
|
||||
R.UnloadImage(img)
|
||||
print("ok 09_pointers")
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
-- 10: RAM-only owned structs (Image, AutomationEventList, FilePathList, Wave)
|
||||
-- release at GC time and Image churn does not grow RSS.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local R = M.load()
|
||||
|
||||
M.reset()
|
||||
local b = M.snapshot()
|
||||
|
||||
do
|
||||
local img = R.GenImageColor(4, 4, R.RED)
|
||||
M.ok(img.data ~= nil, "image allocated")
|
||||
end
|
||||
M.gc(2)
|
||||
|
||||
do
|
||||
local list = R.LoadAutomationEventList(nil)
|
||||
M.ok(list.events ~= nil, "empty automation event list allocated")
|
||||
end
|
||||
M.gc(2)
|
||||
|
||||
do
|
||||
local files = R.LoadDirectoryFiles(".")
|
||||
M.ok(files.paths ~= nil, "directory file list allocated")
|
||||
M.ok(files.count > 0, "directory file list is non-empty")
|
||||
end
|
||||
M.gc(2)
|
||||
|
||||
do
|
||||
local data, size = M.wav_bytes(441)
|
||||
local wave = R.LoadWaveFromMemory(".wav", data, size)
|
||||
M.ok(wave.data ~= nil, "wave allocated")
|
||||
end
|
||||
M.gc(2)
|
||||
|
||||
M.ok(M.delta(b, "released") >= 4,
|
||||
string.format("expected >=4 released RAM resources, got %d",
|
||||
M.delta(b, "released")))
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
|
||||
|
||||
-- 200 batches of 128x128 images: a leaked 64 kB image per batch would add
|
||||
-- ~12.8 MB. Allow generous allocator noise, but not a real leak.
|
||||
local rss0 = M.rss_kb()
|
||||
for i = 1, 200 do
|
||||
local im = R.GenImageColor(128, 128, R.RED)
|
||||
M.ok(im.data ~= nil, "batch image " .. i .. " allocated")
|
||||
M.gc(1)
|
||||
end
|
||||
M.gc(3)
|
||||
local rss1 = M.rss_kb()
|
||||
if rss0 > 0 and not M.under_valgrind() then
|
||||
local growth_kb = rss1 - rss0
|
||||
M.ok(growth_kb < 8 * 1024, string.format(
|
||||
"rss grew %d kB across 200 image batches (%d -> %d kB)",
|
||||
growth_kb, rss0, rss1))
|
||||
end
|
||||
|
||||
print("ok 10_ram")
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
-- 11: string-returning wrappers copy and free inside the wrapper. This is a
|
||||
-- regression test for TextInsertAlloc / TextReplaceAlloc / TextReplaceBetweenAlloc
|
||||
-- and friends: no reference is kept, so RSS must not grow. Valgrind is the
|
||||
-- authoritative leak check.
|
||||
local M = dofile("tests/helpers.lua")
|
||||
local ffi = require("ffi")
|
||||
local R = M.load()
|
||||
|
||||
M.reset()
|
||||
local b = M.snapshot()
|
||||
|
||||
local path = M.tmpfile("hate-no-d string regression\n")
|
||||
local cps = ffi.new("int[3]", 97, 98, 99)
|
||||
local out_size = M.out_int()
|
||||
local failures = {}
|
||||
|
||||
local function check(label, v)
|
||||
if v == nil then failures[#failures + 1] = label end
|
||||
end
|
||||
|
||||
M.gc(2)
|
||||
local rss0 = M.rss_kb()
|
||||
|
||||
for _ = 1, 2000 do
|
||||
check("LoadFileText", R.LoadFileText(path))
|
||||
check("LoadUTF8", R.LoadUTF8(cps, 3))
|
||||
check("EncodeDataBase64", R.EncodeDataBase64("hello", 5, out_size))
|
||||
check("TextInsertAlloc", R.TextInsertAlloc("abcd", "X", 2))
|
||||
check("TextReplaceAlloc", R.TextReplaceAlloc("aaaa", "a", "b"))
|
||||
check("TextReplaceBetweenAlloc",
|
||||
R.TextReplaceBetweenAlloc("abcdef", "b", "e", "X"))
|
||||
end
|
||||
|
||||
M.gc(3)
|
||||
local rss1 = M.rss_kb()
|
||||
os.remove(path)
|
||||
|
||||
M.eq(#failures, 0, "wrappers returned nil: " .. table.concat(failures, ", "))
|
||||
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
|
||||
if rss0 > 0 and not M.under_valgrind() then
|
||||
local growth_kb = rss1 - rss0
|
||||
M.ok(growth_kb < 20 * 1024, string.format(
|
||||
"rss grew %d kB across 2000 string iterations (%d -> %d kB)",
|
||||
growth_kb, rss0, rss1))
|
||||
end
|
||||
|
||||
print("ok 11_strings")
|
||||
|
|
@ -1,189 +0,0 @@
|
|||
-- tests/helpers.lua -- shared support for the hate-no-d test cases.
|
||||
--
|
||||
-- Cases are plain Lua runs under ./hate-no-d (the embedded raylib + LuaJIT
|
||||
-- runtime). The module is cached here so a case can call helpers repeatedly
|
||||
-- without re-executing hate-no-d.lua.
|
||||
|
||||
local ffi = require("ffi")
|
||||
|
||||
local M = {}
|
||||
|
||||
local ROOT = os.getenv("HATE_NO_D_ROOT") or "."
|
||||
local CACHE = {}
|
||||
|
||||
--- Load (and cache) the generated binding.
|
||||
function M.load()
|
||||
if CACHE.M == nil then
|
||||
CACHE.M = dofile(ROOT .. "/hate-no-d.lua")
|
||||
-- Tests exercise thousands of loads; raylib's INFO logging would drown the
|
||||
-- assertions (and valgrind output).
|
||||
if CACHE.M.SetTraceLogLevel and CACHE.M.LOG_WARNING then
|
||||
CACHE.M.SetTraceLogLevel(CACHE.M.LOG_WARNING)
|
||||
end
|
||||
end
|
||||
return CACHE.M
|
||||
end
|
||||
|
||||
--- The generated raylib module table (alias used by the spec's examples).
|
||||
function M.R()
|
||||
return M.load()
|
||||
end
|
||||
|
||||
--- Run the Lua GC n times.
|
||||
function M.gc(n)
|
||||
for _ = 1, (n or 2) do collectgarbage("collect") end
|
||||
end
|
||||
|
||||
--- M._ownership, with a clear error when the generator has not landed yet.
|
||||
function M.ow()
|
||||
local mod = M.load()
|
||||
local o = mod._ownership
|
||||
if type(o) ~= "table" then
|
||||
error("hate-no-d.lua has no M._ownership (regenerate the binding)", 2)
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
function M.reset()
|
||||
M.ow().reset()
|
||||
end
|
||||
|
||||
function M.snapshot()
|
||||
local o = M.ow()
|
||||
return {
|
||||
armed = o.armed,
|
||||
released = o.released,
|
||||
skipped = o.skipped,
|
||||
errors = o.errors,
|
||||
}
|
||||
end
|
||||
|
||||
function M.delta(before, field)
|
||||
return M.ow()[field] - before[field]
|
||||
end
|
||||
|
||||
function M.eq(a, b, msg)
|
||||
if a ~= b then
|
||||
error(string.format("%s: expected %s, got %s",
|
||||
msg or "assert", tostring(b), tostring(a)), 2)
|
||||
end
|
||||
end
|
||||
|
||||
function M.ok(v, msg)
|
||||
if not v then error(msg or "assertion failed", 2) end
|
||||
end
|
||||
|
||||
--- RSS in kB from /proc/self/status, or 0 when unavailable.
|
||||
function M.rss_kb()
|
||||
local f = io.open("/proc/self/status", "r")
|
||||
if f == nil then return 0 end
|
||||
local rss = 0
|
||||
for line in f:lines() do
|
||||
local kb = line:match("^VmRSS:%s*(%d+)%s*kB")
|
||||
if kb then rss = tonumber(kb); break end
|
||||
end
|
||||
f:close()
|
||||
return rss
|
||||
end
|
||||
|
||||
--- True when the runner told us there is no display.
|
||||
function M.headless()
|
||||
return os.getenv("HATE_NO_D_HEADLESS") == "1"
|
||||
end
|
||||
|
||||
--- True when running under valgrind (RSS measurements are meaningless then).
|
||||
function M.under_valgrind()
|
||||
return os.getenv("HATE_NO_D_VALGRIND") == "1"
|
||||
end
|
||||
|
||||
--- Ensure a window exists. Returns false (rather than failing) when the
|
||||
--- environment cannot provide one, so callers can print "skip <name>".
|
||||
function M.window(w, h)
|
||||
if M.headless() then return false end
|
||||
local R = M.load()
|
||||
if not R.C.IsWindowReady() then
|
||||
R.InitWindow(w or 64, h or 64, "hate-no-d test")
|
||||
end
|
||||
return R.C.IsWindowReady() and true or false
|
||||
end
|
||||
|
||||
--- Ensure an audio device exists (same skip-friendly contract as window()).
|
||||
function M.audio()
|
||||
local R = M.load()
|
||||
if not R.IsAudioDeviceReady() then
|
||||
pcall(R.InitAudioDevice)
|
||||
end
|
||||
return R.IsAudioDeviceReady() and true or false
|
||||
end
|
||||
|
||||
function M.skip(name, reason)
|
||||
if reason then
|
||||
print(string.format("skip %s (%s)", name, reason))
|
||||
else
|
||||
print("skip " .. name)
|
||||
end
|
||||
end
|
||||
|
||||
--- Accept either a Lua string (owned-string wrappers) or a cdata char* and
|
||||
--- return a Lua string. Used where lane A may still hand back a pointer.
|
||||
function M.tostr(x)
|
||||
if type(x) == "string" then return x end
|
||||
if x == nil then return nil end
|
||||
return ffi.string(x)
|
||||
end
|
||||
|
||||
function M.out_int(v)
|
||||
local p = ffi.new("int[1]")
|
||||
if v ~= nil then p[0] = v end
|
||||
return p
|
||||
end
|
||||
|
||||
function M.tmpfile(contents)
|
||||
local path = os.tmpname()
|
||||
local f = assert(io.open(path, "wb"))
|
||||
f:write(contents)
|
||||
f:close()
|
||||
return path
|
||||
end
|
||||
|
||||
--- Build a PCM WAV in memory: mono, 44100 Hz, signed 16-bit, `samples`
|
||||
--- samples of silence. Returns (cdata uint8_t[44 + samples*2], size).
|
||||
function M.wav_bytes(samples)
|
||||
local data_size = samples * 2
|
||||
local total = 44 + data_size
|
||||
local b = ffi.new("uint8_t[?]", total)
|
||||
|
||||
local function put8(off, v) b[off] = v end
|
||||
local function put16(off, v)
|
||||
b[off] = v % 256
|
||||
b[off + 1] = math.floor(v / 256) % 256
|
||||
end
|
||||
local function put32(off, v)
|
||||
b[off] = v % 256
|
||||
b[off + 1] = math.floor(v / 256) % 256
|
||||
b[off + 2] = math.floor(v / 65536) % 256
|
||||
b[off + 3] = math.floor(v / 16777216) % 256
|
||||
end
|
||||
local function puts(off, s)
|
||||
for i = 1, #s do b[off + i - 1] = s:byte(i) end
|
||||
end
|
||||
|
||||
puts(0, "RIFF")
|
||||
put32(4, 36 + data_size)
|
||||
puts(8, "WAVE")
|
||||
puts(12, "fmt ")
|
||||
put32(16, 16) -- fmt chunk size
|
||||
put16(20, 1) -- PCM
|
||||
put16(22, 1) -- mono
|
||||
put32(24, 44100) -- sample rate
|
||||
put32(28, 44100 * 2) -- byte rate
|
||||
put16(32, 2) -- block align
|
||||
put16(34, 16) -- bits per sample
|
||||
puts(36, "data")
|
||||
put32(40, data_size)
|
||||
-- samples stay zero (silence)
|
||||
|
||||
return b, total
|
||||
end
|
||||
|
||||
return M
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
#!/bin/sh
|
||||
# RAM-only cases under valgrind. Definite leaks are fatal (exit code 42).
|
||||
#
|
||||
# GPU finalizers are deliberately excluded: a headless/valgrind process has no
|
||||
# GL context, so those cases would only exercise the "skip" gate.
|
||||
set -u
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||
cd "$ROOT" || exit 1
|
||||
export HATE_NO_D_ROOT="$ROOT"
|
||||
|
||||
if ! command -v valgrind >/dev/null 2>&1; then
|
||||
echo "skip valgrind (not installed)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ ! -x ./hate-no-d ]; then
|
||||
echo "run-valgrind.sh: ./hate-no-d not built (run make)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CASES="02_explicit 07_inout 08c_font_atlas 09_pointers 10_ram 11_strings"
|
||||
fail=0
|
||||
HATE_NO_D_VALGRIND=1
|
||||
export HATE_NO_D_VALGRIND
|
||||
|
||||
for name in $CASES; do
|
||||
case="tests/cases/$name.lua"
|
||||
if [ ! -f "$case" ]; then
|
||||
echo "FAIL $name (missing $case)" >&2
|
||||
fail=1
|
||||
continue
|
||||
fi
|
||||
echo "valgrind $name"
|
||||
if valgrind --quiet --error-exitcode=42 \
|
||||
--leak-check=full --show-leak-kinds=definite \
|
||||
--errors-for-leak-kinds=definite \
|
||||
--suppressions=tests/valgrind.supp \
|
||||
./hate-no-d "$case"; then
|
||||
:
|
||||
else
|
||||
status=$?
|
||||
echo "FAIL $name (valgrind exit $status)" >&2
|
||||
fail=1
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$fail" -eq 0 ]; then
|
||||
echo "check-valgrind: ok"
|
||||
fi
|
||||
exit "$fail"
|
||||
62
tests/run.sh
62
tests/run.sh
|
|
@ -1,62 +0,0 @@
|
|||
#!/bin/sh
|
||||
# Functional test matrix for hate-no-d.
|
||||
#
|
||||
# Every case is a self-contained process: it prints "ok <name>" or
|
||||
# "skip <name> (...)", or raises with a specific message. Cases must run under
|
||||
# ./hate-no-d -- the system luajit has no raylib symbols.
|
||||
set -u
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||
cd "$ROOT" || exit 1
|
||||
export HATE_NO_D_ROOT="$ROOT"
|
||||
|
||||
if [ ! -x ./hate-no-d ]; then
|
||||
echo "run.sh: ./hate-no-d not built (run make)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# If there is no display, retry the whole matrix under a virtual X server when
|
||||
# one is available. Otherwise mark the run headless and let window cases skip.
|
||||
if [ -z "${DISPLAY:-}" ] && [ "${HATE_NO_D_XVFB:-0}" != "1" ]; then
|
||||
if command -v xvfb-run >/dev/null 2>&1; then
|
||||
HATE_NO_D_XVFB=1
|
||||
export HATE_NO_D_XVFB
|
||||
exec xvfb-run -a "$0" "$@"
|
||||
fi
|
||||
echo "run.sh: no DISPLAY and no xvfb-run; window cases will be skipped" >&2
|
||||
HATE_NO_D_HEADLESS=1
|
||||
export HATE_NO_D_HEADLESS
|
||||
fi
|
||||
|
||||
# Cases that need a window. The cases themselves also gate on IsWindowReady;
|
||||
# this list just avoids starting them at all when the runner knows it is
|
||||
# headless.
|
||||
WINDOW_CASES="01_many_textures 03_borrowed 04_model_from_mesh 06_teardown 08_pins 08b_views"
|
||||
|
||||
is_window_case() {
|
||||
for w in $WINDOW_CASES; do
|
||||
[ "$w" = "$1" ] && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
fail=0
|
||||
for case in tests/cases/*.lua; do
|
||||
name=$(basename "$case" .lua)
|
||||
if [ "${HATE_NO_D_HEADLESS:-0}" = "1" ] && is_window_case "$name"; then
|
||||
echo "skip $name (no display)"
|
||||
continue
|
||||
fi
|
||||
if out=$(./hate-no-d "$case" 2>&1); then
|
||||
echo "$out"
|
||||
else
|
||||
echo "FAIL $name" >&2
|
||||
echo "$out" >&2
|
||||
fail=1
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$fail" -eq 0 ]; then
|
||||
echo "test: ok"
|
||||
fi
|
||||
exit "$fail"
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
# Valgrind suppressions for the hate-no-d test suite.
|
||||
#
|
||||
# Start empty. Only suppress reports that originate inside LuaJIT, the JIT
|
||||
# tracer, or glibc internals -- never frames from _release_* / Unload* /
|
||||
# MemFree, because those are exactly what the RAM cases exist to check.
|
||||
#
|
||||
# Each entry needs a comment naming the rule, for example:
|
||||
#
|
||||
# # LuaJIT allocator arena still reachable at exit (not a definite leak).
|
||||
# {
|
||||
# luajit-alloc-arena
|
||||
# Memcheck:Leak
|
||||
# match-leak-kinds: reachable
|
||||
# ...
|
||||
# }
|
||||
Loading…
Reference in a new issue