Compare commits

..

No commits in common. "master" and "v0.1.0" have entirely different histories.

16 changed files with 177 additions and 13157 deletions

View file

@ -18,13 +18,9 @@ if [ $# -lt 1 ]; then
echo "usage: $0 <output-file> [source-dir]" >&2
exit 2
fi
# Both paths are resolved before the cd into $WORK below: a relative output
# directory would otherwise be created under the work dir, and the artifact
# copy would look for it there.
OUT_DIR=$(dirname "$1")
mkdir -p "$OUT_DIR"
OUT_DIR=$(cd "$OUT_DIR" && pwd)
OUT="$OUT_DIR/$(basename "$1")"
OUT=$(cd "$OUT_DIR" && pwd)/$(basename "$1")
SRC=$(cd "${2:-.}" && pwd)
WORK="${FBSD_WORK:-${TMPDIR:-/tmp}/fbsd-ci}"
@ -113,16 +109,13 @@ done
log "guest up after ~$((i * 2))s: $(ssh_vm 'uname -sr')"
# --- build -------------------------------------------------------------------
log "installing gmake, luajit and the X11/GL prerequisites in guest"
# libglvnd, not mesa-libs: raylib's GL 3.3 path uses its bundled GLAD loader, so
# only libGL.so is needed for the link. mesa-libs pulls llvm19 (~1 GB) and fills
# the cloud image's root filesystem.
ssh_vm 'set -e; env ASSUME_ALWAYS_YES=yes pkg install -y gmake luajit libX11 libXrandr libXinerama libXi libXcursor libglvnd >/dev/null; gmake --version | head -1'
log "installing gmake in guest"
ssh_vm 'set -e; env ASSUME_ALWAYS_YES=yes pkg install -y gmake >/dev/null 2>&1; gmake --version | head -1'
log "transferring source"
tar czf "$WORK/src.tar.gz" -C "$SRC" \
--exclude=.git --exclude=.build --exclude=build --exclude=hate-no-d \
--exclude=hate-no-d.lua --exclude='*.o' --exclude='*.a' --exclude='*.so' .
--exclude=.git --exclude=.build --exclude=hate-no-d \
--exclude='*.o' --exclude='*.a' --exclude='*.so' .
scp $SCP_OPTS "$WORK/src.tar.gz" "root@127.0.0.1:/root/src.tar.gz"
# FreeBSD has no gcc: CC must be on the command line to reach the sub-make.
@ -134,8 +127,8 @@ ssh_vm 'set -e
gmake CC=cc clean >/dev/null 2>&1 || true
gmake CC=cc all'
log "fetching artifact"
log "fetching binary"
mkdir -p "$(dirname "$OUT")"
scp $SCP_OPTS "root@127.0.0.1:/root/src/hate-no-d" "$OUT"
scp $SCP_OPTS "root@127.0.0.1:/root/src/hate-no-d.lua" "$OUT_DIR/hate-no-d.lua"
log "built $OUT ($(wc -c < "$OUT") bytes)"

View file

@ -1,66 +0,0 @@
#!/bin/sh
# Stage one release asset into a directory and pack it, so every download is a
# self-contained "folder" instead of a bare binary.
#
# make-archive.sh <asset-name> <tar.gz|zip> <payload>...
#
# asset-name e.g. hate-no-d-linux-x86_64; also the directory inside the
# archive, so unpacking never scatters files
# format tar.gz for Unix payloads (keeps the executable bit), zip for
# Windows ones
# payload files to pack, each keeping its basename
#
# LICENSE and README.md are added from the working directory when present.
# Writes ./<asset-name>.<format> and leaves the staging directory behind.
set -eu
if [ $# -lt 3 ]; then
echo "usage: $0 <asset-name> <tar.gz|zip> <payload>..." >&2
exit 2
fi
name=$1
format=$2
shift 2
# Guard the rm -rf below.
case "$name" in
'' | */*) echo "make-archive: bad asset name: '$name'" >&2; exit 2 ;;
esac
case "$format" in
tar.gz | zip) ;;
*) echo "make-archive: unknown format: '$format'" >&2; exit 2 ;;
esac
for f in "$@"; do
[ -f "$f" ] || { echo "make-archive: no such file: $f" >&2; exit 1; }
done
rm -rf "$name"
mkdir -p "$name"
# The first payload is the binary: make its mode deterministic instead of
# trusting whatever the build/copy path produced.
first=1
for f in "$@"; do
cp "$f" "$name/$(basename "$f")"
if [ "$first" = 1 ]; then
chmod 755 "$name/$(basename "$f")"
first=0
fi
done
for f in LICENSE README.md; do
if [ -f "$f" ]; then
cp "$f" "$name/"
fi
done
case "$format" in
tar.gz) tar -czf "$name.tar.gz" "$name" ;;
zip) zip -qr -X "$name.zip" "$name" >/dev/null ;;
esac
echo "make-archive: wrote $name.$format"
ls -l "$name" | sed 's/^/make-archive: /'

View file

@ -1,7 +1,7 @@
# macOS, kept out of release.yml: it needs a `macos` runner. Gating it there
# with `if: vars.*` does not work -- Forgejo does not evaluate `vars` in `if:`,
# so the job queued forever and the run never finished. Manual dispatch only,
# until a Mac runner exists.
# Apple targets (macOS + iOS), kept out of release.yml: they need a `macos`
# runner. Gating them there with `if: vars.*` does not work -- Forgejo does not
# evaluate `vars` in `if:`, so the jobs queued forever and the run never
# finished. Manual dispatch only, until a Mac runner exists.
name: apple
on:
@ -40,9 +40,6 @@ jobs:
- name: Fetch submodules
run: git submodule update --init --recursive
- name: Install LuaJIT
run: brew install luajit
- name: Build
run: |
make \
@ -56,11 +53,34 @@ jobs:
file ./hate-no-d
file ./hate-no-d | grep -q '${{ matrix.arch }}'
- name: Package
- name: Attach to release
if: github.event.inputs.tag != ''
run: sh .forgejo/scripts/release-asset.sh ./hate-no-d "hate-no-d-macos-${{ matrix.arch }}"
# ---------------------------------------------------------------------------
# iOS. Builds only the archive (JIT compiled out) for an Xcode app target.
# ---------------------------------------------------------------------------
ios:
name: ios/arm64
runs-on: macos
steps:
- name: Checkout
uses: https://data.forgejo.org/actions/checkout@v4
with:
submodules: false
- name: Fetch submodules
run: git submodule update --init --recursive
- name: Build libluajit.a
run: make PLATFORM=iOS IOS_ARCH=arm64 all
- name: Verify archive
run: |
sh .forgejo/scripts/make-archive.sh "hate-no-d-macos-${{ matrix.arch }}" tar.gz \
./hate-no-d ./hate-no-d.lua
set -eu
lipo -info submodules/luajit/src/libluajit.a
lipo -info submodules/luajit/src/libluajit.a | grep -q arm64
- name: Attach to release
if: github.event.inputs.tag != ''
run: sh .forgejo/scripts/release-asset.sh "./hate-no-d-macos-${{ matrix.arch }}.tar.gz"
run: sh .forgejo/scripts/release-asset.sh submodules/luajit/src/libluajit.a hate-no-d-ios-arm64-luajit.a

View file

@ -3,11 +3,8 @@
# push / pull_request -> build only
# tag 'v*' -> build + release assets
#
# Assets: one archive per target, named hate-no-d-<os>-<arch>.tar.gz (zip on
# Windows), each unpacking to a directory of the same name holding the binary
# plus LICENSE and README.md. Release attachments are a flat list with no
# folders, so the archive is what groups a target's files together.
# macOS lives in apple.yml; everything here builds on the Linux runner.
# Assets: hate-no-d-linux-*, -android-*, -windows_mingw_w64-*.exe, -freebsd-x86_64.
# macOS/iOS live in apple.yml; everything here builds on the Linux runner.
name: release
on:
@ -48,21 +45,18 @@ jobs:
- arch: x86_64
machine: X86-64
make_args: ''
multiarch: ''
packages: 'libx11-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev'
packages: ''
# 32-bit target: leaving HOST_CC unset keeps minilua/buildvm 32-bit
# too. Host and target pointer sizes must match -- do not use HOST_CC=gcc.
- arch: i686
machine: 'Intel 80386'
make_args: 'CC="gcc -m32"'
multiarch: 'i386'
packages: 'gcc-multilib libc6-dev-i386 libx11-dev:i386 libxrandr-dev:i386 libxinerama-dev:i386 libxcursor-dev:i386 libxi-dev:i386 libgl-dev:i386'
packages: 'gcc-multilib libc6-dev-i386'
# 64-bit host -> 64-bit target, so host tools stay native.
- arch: aarch64
machine: AArch64
make_args: 'CC=aarch64-linux-gnu-gcc HOST_CC=gcc'
multiarch: 'arm64'
packages: 'gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user-static libx11-dev:arm64 libxrandr-dev:arm64 libxinerama-dev:arm64 libxcursor-dev:arm64 libxi-dev:arm64 libgl-dev:arm64'
packages: 'gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user-static'
# 32-bit target, so the host tools must be 32-bit too. gcc-multilib
# cannot be installed (gcc-12-arm-linux-gnueabihf conflicts with it);
# lib32gcc-12-dev + libc6-dev-i386 replace it, and linux-libc-dev:i386
@ -70,8 +64,8 @@ jobs:
- arch: armv7
machine: ARM
make_args: 'CC=arm-linux-gnueabihf-gcc HOST_CC="gcc -m32"'
multiarch: 'armhf i386'
packages: 'gcc-arm-linux-gnueabihf libc6-dev-armhf-cross lib32gcc-12-dev libc6-dev-i386 linux-libc-dev:i386 qemu-user-static libx11-dev:armhf libxrandr-dev:armhf libxinerama-dev:armhf libxcursor-dev:armhf libxi-dev:armhf libgl-dev:armhf'
packages: 'gcc-arm-linux-gnueabihf libc6-dev-armhf-cross lib32gcc-12-dev libc6-dev-i386 linux-libc-dev:i386 qemu-user-static'
multiarch_i386: true
steps:
- name: Checkout
uses: https://data.forgejo.org/actions/checkout@v4
@ -84,20 +78,13 @@ jobs:
- name: Install toolchain
run: |
set -eu
# raylib's GLFW backend needs the X11/GL headers even when only a
# static archive is produced, and the final link needs the target's
# libX11/libGL stubs. Cross jobs therefore install the *foreign* arch
# dev packages; only the native job installs the host's.
# armv7 additionally needs linux-libc-dev:i386 for its 32-bit host
# tools (gcc -m32), hence two foreign arches there.
if [ -n '${{ matrix.multiarch }}' ]; then
for arch in ${{ matrix.multiarch }}; do
dpkg --add-architecture "$arch"
done
# Only armv7: linux-libc-dev:i386 provides its 32-bit asm/ headers.
if [ '${{ matrix.multiarch_i386 }}' = 'true' ]; then
dpkg --add-architecture i386
fi
apt-get update -qq
apt-get install -y --no-install-recommends \
make gcc libc6-dev binutils jq curl ca-certificates luajit ${{ matrix.packages }}
make gcc libc6-dev binutils jq curl ca-certificates ${{ matrix.packages }}
- name: Build
run: make ${{ matrix.make_args }} all
@ -109,18 +96,9 @@ jobs:
readelf -h ./hate-no-d | grep -F 'Machine:' | grep -F '${{ matrix.machine }}'
echo "architecture ok: ${{ matrix.machine }}"
# The parser tables are generated into build/api from the pinned raylib
# headers, so assert they still reproduce the shipped binding byte for
# byte before it goes into a release archive.
- name: Verify bindings
run: make check-bindings
- name: Package
run: sh .forgejo/scripts/make-archive.sh "hate-no-d-linux-${{ matrix.arch }}" tar.gz ./hate-no-d ./hate-no-d.lua
- name: Attach to release
if: startsWith(github.ref, 'refs/tags/')
run: sh .forgejo/scripts/release-asset.sh "./hate-no-d-linux-${{ matrix.arch }}.tar.gz"
run: sh .forgejo/scripts/release-asset.sh ./hate-no-d "hate-no-d-linux-${{ matrix.arch }}"
# ---------------------------------------------------------------------------
# Android. One job for all ABIs so the ~630 MB NDK is downloaded once. The
@ -150,7 +128,7 @@ jobs:
set -eu
apt-get update -qq
apt-get install -y --no-install-recommends \
make gcc libc6-dev binutils jq curl ca-certificates unzip luajit \
make gcc libc6-dev binutils jq curl ca-certificates unzip \
gcc-multilib libc6-dev-i386
- name: Install NDK r27c
@ -177,16 +155,7 @@ jobs:
ANDROID_ABI="$abi" HOST_CC=gcc all
fi
readelf -h ./hate-no-d | grep -F 'Machine:' | grep -E 'AArch64|ARM|X86-64'
mkdir -p "dist/$abi"
cp ./hate-no-d "dist/$abi/hate-no-d"
done
- name: Package
run: |
set -eu
for abi in arm64-v8a armeabi-v7a x86_64; do
sh .forgejo/scripts/make-archive.sh "hate-no-d-android-$abi" tar.gz \
"dist/$abi/hate-no-d" ./hate-no-d.lua
cp ./hate-no-d "dist/hate-no-d-android-$abi"
done
- name: Attach to release
@ -194,7 +163,7 @@ jobs:
run: |
set -eu
for abi in arm64-v8a armeabi-v7a x86_64; do
sh .forgejo/scripts/release-asset.sh "hate-no-d-android-$abi.tar.gz"
sh .forgejo/scripts/release-asset.sh "dist/hate-no-d-android-$abi" "hate-no-d-android-$abi"
done
# ---------------------------------------------------------------------------
@ -228,24 +197,16 @@ jobs:
run: |
set -eu
mkdir -p dist
sh .forgejo/scripts/freebsd-build.sh dist/hate-no-d .
# Both artifacts come back from the guest (the VM builds its own
# hate-no-d.lua), so package dist/, not the checked-out copy.
- name: Package
run: |
sh .forgejo/scripts/make-archive.sh hate-no-d-freebsd-x86_64 tar.gz \
dist/hate-no-d dist/hate-no-d.lua
sh .forgejo/scripts/freebsd-build.sh dist/hate-no-d-freebsd-x86_64 .
- name: Attach to release
if: startsWith(github.ref, 'refs/tags/')
run: sh .forgejo/scripts/release-asset.sh ./hate-no-d-freebsd-x86_64.tar.gz
run: sh .forgejo/scripts/release-asset.sh dist/hate-no-d-freebsd-x86_64 hate-no-d-freebsd-x86_64
# ---------------------------------------------------------------------------
# Windows. Cross-compiled with mingw-w64; no Windows machine or MSVC involved.
# i686 needs a 32-bit host compiler for the native buildvm. The asset is a zip
# (Windows convention) holding hate-no-d.exe; the toolchain is not part of the
# name because it is not a compatibility axis for anyone downloading it.
# i686 needs a 32-bit host compiler for the native buildvm. The build stays
# hate-no-d.exe -- only the release asset name carries the toolchain.
# ---------------------------------------------------------------------------
windows:
name: windows/${{ matrix.arch }}
@ -257,8 +218,10 @@ jobs:
matrix:
include:
- arch: x86_64
tag: windows_mingw_w64-x64
host_cc: gcc
- arch: i686
tag: windows_mingw_w64-x86
host_cc: gcc -m32
steps:
- name: Checkout
@ -270,13 +233,12 @@ jobs:
run: git submodule update --init --recursive
# --no-install-recommends omits libc6-dev, and minilua needs limits.h.
# zip: the release asset is a .zip, matching the Windows convention.
- name: Install toolchain
run: |
set -eu
apt-get update -qq
apt-get install -y --no-install-recommends \
make gcc libc6-dev gcc-multilib mingw-w64 jq zip luajit
make gcc libc6-dev gcc-multilib mingw-w64 jq
- name: Build
run: make PLATFORM=Windows WIN_ARCH=${{ matrix.arch }} HOST_CC="${{ matrix.host_cc }}" all
@ -288,24 +250,9 @@ jobs:
file "./$bin" | grep -q 'for MS Windows'
deps=$(${{ matrix.arch }}-w64-mingw32-objdump -p "./$bin" | awk '/DLL Name/{print $3}')
echo "$deps"
# raylib imports the Win32 system DLLs (gdi32/user32/shell32/winmm)
# plus what the mingw link records (advapi32/ole32/...); anything
# outside that set is a toolchain DLL leaking into a release. Names
# are case-insensitive: mingw writes WINMM.dll, not winmm.dll.
# (opengl32 is in the list for the MSVC path, where it does appear.)
bad=$(printf '%s\n' "$deps" | grep -viE '^(kernel32|gdi32|user32|shell32|winmm|opengl32|advapi32|ole32|oleaut32|uuid|msvcrt|api-ms-win-[a-z0-9-]+)\.dll$' || true)
bad=$(printf '%s\n' "$deps" | grep -v -E '^(KERNEL32|msvcrt)\.dll$' || true)
[ -z "$bad" ] || { echo "unexpected runtime DLL dependency: $bad" >&2; exit 1; }
# raylib loads GL through the driver at runtime, so there is no
# opengl32 import to assert; what must hold is that ffi.C can resolve
# raylib through the exe's export table (PE has no --export-dynamic).
${{ matrix.arch }}-w64-mingw32-objdump -p "./$bin" | grep -qw InitWindow \
|| { echo "hate-no-d.exe does not export raylib symbols" >&2; exit 1; }
- name: Package
run: |
sh .forgejo/scripts/make-archive.sh "hate-no-d-windows-${{ matrix.arch }}" zip \
./hate-no-d.exe ./hate-no-d.lua
- name: Attach to release
if: startsWith(github.ref, 'refs/tags/')
run: sh .forgejo/scripts/release-asset.sh "./hate-no-d-windows-${{ matrix.arch }}.zip"
run: sh .forgejo/scripts/release-asset.sh ./hate-no-d.exe hate-no-d-${{ matrix.tag }}.exe

13
.gitignore vendored
View file

@ -1,16 +1,3 @@
hate-no-d
hate-no-d.exe
quick-start.lua
# Release staging dirs and archives (.forgejo/scripts/make-archive.sh).
hate-no-d-*/
hate-no-d-*.tar.gz
hate-no-d-*.zip
# Build artifacts: objects, the host rlparser, generated parser tables, and
# build.bat's CMake trees. The CLI and hate-no-d.lua stay in the root.
/build/
# Stray objects from an out-of-tree compile.
*.o
*.obj

6
.gitmodules vendored
View file

@ -1,9 +1,3 @@
[submodule "submodules/luajit"]
path = submodules/luajit
url = https://luajit.org/git/luajit.git
[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

View file

@ -1,6 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/LuaLS/vscode-lua/master/setting/schema.json",
"runtime.version": "LuaJIT",
"workspace.checkThirdParty": false,
"workspace.library": ["./hate-no-d.lua"]
}

351
Makefile
View file

@ -1,62 +1,29 @@
# hate-no-d
#
# Platforms are auto-detected from uname; cross targets are explicit:
# Native platforms are auto-detected from uname. Cross targets are selected explicitly:
# make
# make PLATFORM=Android ANDROID_NDK=/opt/android-ndk
# make PLATFORM=Android ANDROID_NDK=... ANDROID_ABI=armeabi-v7a ANDROID_API=21
# make PLATFORM=iOS IOS_ARCH=arm64 IOS_MIN=12.0
# make PLATFORM=Windows WIN_ARCH=x86_64 (cross build with mingw-w64)
# make PLATFORM=Android ANDROID_NDK=/opt/ndk [ANDROID_ABI=... ANDROID_API=...]
# make help every target and option
#
# 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.
# luajit requires GNU Make (use `gmake` on FreeBSD/OpenBSD/NetBSD).
ifndef .FEATURES
$(error This build requires GNU Make -- on BSD use 'gmake')
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
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
# ---------------------------------------------------------------------------
# Platform detection
# ---------------------------------------------------------------------------
# PLATFORM= always wins over uname.
PLATFORM ?= $(shell uname -s)
LUAJIT_XCFLAGS := -DLUAJIT_ENABLE_LUA52COMPAT
LUAJIT_EXTRA :=
# 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
# Platform detection. PLATFORM= always wins over uname.
PLATFORM ?= $(shell uname -s)
ifeq ($(PLATFORM),Linux)
OS_KIND := linux
@ -64,53 +31,49 @@ else ifeq ($(PLATFORM),Android)
OS_KIND := android
else ifeq ($(PLATFORM),Darwin)
OS_KIND := macos
else ifeq ($(PLATFORM),iOS)
OS_KIND := ios
else ifeq ($(PLATFORM),Windows)
OS_KIND := windows
else ifneq (,$(filter MINGW% MSYS% CYGWIN%,$(PLATFORM)))
# Native MinGW/MSYS2/Cygwin shell: uname reports e.g. MINGW64_NT-10.0.
OS_KIND := windows
PLATFORM := Windows
MINGW_ARCH := $(shell uname -m)
ifeq ($(MINGW_ARCH),amd64)
WIN_ARCH ?= x86_64
else ifeq ($(MINGW_ARCH),x86)
WIN_ARCH ?= i686
else
WIN_ARCH ?= $(MINGW_ARCH)
endif
else ifneq (,$(filter $(PLATFORM),FreeBSD OpenBSD NetBSD DragonFly))
else ifneq (,$(filter $(PLATFORM),FreeBSD OpenBSD NetBSD DragonFly GNU/kFreeBSD))
OS_KIND := bsd
else
OS_KIND := posix
endif
# Linux (ELF)
ifeq ($(OS_KIND),linux)
EXPORT_LDFLAGS := -Wl,-E
PLAT_LIBS := -lm -ldl -lGL -lX11 -lpthread -lrt
PLAT_LIBS := -lm -ldl
LINK_TARGET := $(BIN)
endif
# 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.
# BSD (ELF or Mach-O, dlopen lives in libc)
ifeq ($(OS_KIND),bsd)
EXPORT_LDFLAGS := -Wl,-E
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
endif
PLAT_LIBS := $(BSD_LIBDIRS) -lm -lGL -lpthread \
-lX11 -lXrandr -lXinerama -lXi -lXcursor
ifneq (,$(filter $(PLATFORM),OpenBSD NetBSD))
PLAT_LIBS += -lossaudio
endif
PLAT_LIBS := -lm
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
# natively and must match the target pointer size:
# Generic POSIX fallback (Solaris/illumos, AIX, Haiku, ...).
# Note: Solaris ld's -E is NOT --export-dynamic, so it is deliberately off.
ifeq ($(OS_KIND),posix)
EXPORT_LDFLAGS :=
PLAT_LIBS := -lm
LINK_TARGET := $(BIN)
endif
# Windows (PE, cross-compiled from a POSIX host with mingw-w64)
#
# Native builds use build.bat.
#
# 64-bit targets build on any 64-bit host. i686 also needs a 32-bit host
# compiler, because LuaJIT's buildvm runs natively and its pointer size must
# match the target:
# make PLATFORM=Windows WIN_ARCH=i686 HOST_CC="gcc -m32"
#
# No export table: ffi.C resolves through msvcrt/kernel32 handles on Windows,
# unlike ELF where the Lua API has to be exported with -Wl,-E.
ifeq ($(OS_KIND),windows)
WIN_ARCH ?= x86_64
@ -119,26 +82,22 @@ ifeq ($(OS_KIND),windows)
endif
CC := $(WIN_ARCH)-w64-mingw32-gcc
AR := $(WIN_ARCH)-w64-mingw32-ar
HOST_CC ?= gcc
PLAT_LIBS := -lm -lopengl32 -lgdi32 -lwinmm
PLAT_LIBS := -lm
BIN := $(BIN).exe
LINK_TARGET := $(BIN)
# raylib detects the host's OS, so pin the target for cross builds.
RAYLIB_MAKE_ARGS := PLATFORM=PLATFORM_DESKTOP RAYLIB_LIBTYPE=STATIC PLATFORM_OS=WINDOWS
# Export the exe's symbols so ffi.C can resolve raylib on Windows.
EXPORT_LDFLAGS := -Wl,--export-all-symbols
# LuaJIT derives HOST_CC from CC: label both, or the host tools are built with
# the cross compiler.
# LuaJIT derives HOST_CC from CC, so label both to the sub-make: otherwise
# the host tools (minilua, buildvm) are compiled with the cross compiler.
LUAJIT_EXTRA := "CC=$(CC)" "HOST_CC=$(HOST_CC)" TARGET_SYS=Windows
endif
# macOS (Mach-O). ld64 exports main-executable globals by default;
# -export_dynamic keeps -dead_strip/LTO from discarding the Lua API. JIT under
# the hardened runtime needs MAP_JIT, so the deployment target must be >= 11.0.
# macOS (Mach-O)
#
# ld64 exports main-executable globals by default; -export_dynamic only stops
# -dead_strip / LTO from discarding the Lua API. GC64 is mandatory on arm64.
# JIT under the hardened runtime needs MAP_JIT, which is compiled in only when
# the deployment target is >= 11.0.
ifeq ($(OS_KIND),macos)
ifeq ($(origin CC),default)
CC := clang
@ -147,23 +106,21 @@ ifeq ($(OS_KIND),macos)
export MACOSX_DEPLOYMENT_TARGET
EXPORT_LDFLAGS := -Wl,-export_dynamic
PLAT_LIBS := -lm -framework OpenGL -framework Cocoa -framework IOKit \
-framework CoreAudio -framework CoreVideo -framework QuartzCore
PLAT_LIBS := -lm
LINK_TARGET := $(BIN)
# ld64 has no --whole-archive.
RAYLIB_LINK := -Wl,-force_load,$(RAYLIB_AR)
# MAP_JIT path, needed for the hardened runtime (and thus notarization).
# MAP_JIT path: needed for the hardened runtime (and therefore notarization).
# Requires MACOSX_DEPLOYMENT_TARGET >= 11.0 or LuaJIT compiles it back out.
MACOSX_HRT ?= 1
ifeq ($(MACOSX_HRT),1)
LUAJIT_XCFLAGS += -DLUAJIT_ENABLE_OSX_HRT
endif
endif
# 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"
# 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"
ifeq ($(OS_KIND),android)
ANDROID_NDK ?= $(ANDROID_NDK_HOME)
ANDROID_API ?= 21
@ -173,10 +130,6 @@ ifeq ($(OS_KIND),android)
$(error PLATFORM=Android requires ANDROID_NDK (or ANDROID_NDK_HOME) to be set)
endif
ifneq (,$(filter MINGW% MSYS% CYGWIN%,$(shell uname -s)))
$(error PLATFORM=Android must be built from a Linux or macOS host)
endif
ifeq ($(ANDROID_ABI),arm64-v8a)
ANDROID_TRIPLET := aarch64-linux-android
else ifeq ($(ANDROID_ABI),armeabi-v7a)
@ -198,197 +151,83 @@ ifeq ($(OS_KIND),android)
ANDROID_BIN := $(ANDROID_NDK)/toolchains/llvm/prebuilt/$(ANDROID_HOST_TAG)/bin
ANDROID_CC := $(ANDROID_BIN)/$(ANDROID_TRIPLET)$(ANDROID_API)-clang
ifeq ($(ANDROID_ABI),arm64-v8a)
RAYLIB_ANDROID_ARCH := arm64
else ifeq ($(ANDROID_ABI),armeabi-v7a)
RAYLIB_ANDROID_ARCH := arm
else ifeq ($(ANDROID_ABI),x86_64)
RAYLIB_ANDROID_ARCH := x86_64
else
RAYLIB_ANDROID_ARCH := x86
endif
RAYLIB_MAKE_ARGS := PLATFORM=PLATFORM_ANDROID RAYLIB_LIBTYPE=STATIC \
ANDROID_NDK=$(ANDROID_NDK) ANDROID_ARCH=$(RAYLIB_ANDROID_ARCH) \
ANDROID_API_VERSION=$(ANDROID_API)
CC := $(ANDROID_CC)
AR := $(ANDROID_BIN)/llvm-ar
EXPORT_LDFLAGS := -Wl,-E
# -Wl,--wrap=fopen is raylib's APK asset hook.
PLAT_LIBS := -lm -llog -landroid -lEGL -lGLESv2 -lOpenSLES -ldl -Wl,--wrap=fopen
PLAT_LIBS := -lm
LINK_TARGET := $(BIN)
LUAJIT_EXTRA := CROSS=$(ANDROID_BIN)/$(ANDROID_TRIPLET)- \
STATIC_CC=$(ANDROID_CC) TARGET_LD=$(ANDROID_CC) \
"TARGET_AR=$(ANDROID_BIN)/llvm-ar rcus" \
TARGET_STRIP=$(ANDROID_BIN)/llvm-strip TARGET_SYS=Linux
LUAJIT_EXTRA := CROSS=$(ANDROID_BIN)/$(ANDROID_TRIPLET)- STATIC_CC=$(ANDROID_CC) TARGET_LD=$(ANDROID_CC) "TARGET_AR=$(ANDROID_BIN)/llvm-ar rcus" TARGET_STRIP=$(ANDROID_BIN)/llvm-strip
endif
# iOS (Mach-O, ARM64 only)
#
# There is no runnable binary: link libluajit.a into your Xcode app target.
# The JIT is compiled out by LuaJIT itself (no runtime code generation is
# allowed on iOS), so you get the fast interpreter only.
ifeq ($(OS_KIND),ios)
IOS_SDK ?= $(shell xcrun --sdk iphoneos --show-sdk-path 2>/dev/null)
IOS_CC ?= $(shell xcrun --sdk iphoneos --find clang 2>/dev/null)
IOS_ARCH ?= arm64
IOS_MIN ?= 12.0
ifeq ($(strip $(IOS_SDK)),)
$(error PLATFORM=iOS requires Xcode/xcrun on the build host)
endif
IOS_FLAGS := -arch $(IOS_ARCH) -isysroot $(IOS_SDK) -mios-version-min=$(IOS_MIN)
CC := $(IOS_CC)
EXPORT_LDFLAGS :=
PLAT_LIBS :=
LINK_TARGET := $(LUAJIT_AR)
# DEFAULT_CC keeps the host toolchain (minilua/buildvm) native; CROSS
# switches only the target objects to the iOS SDK.
LUAJIT_EXTRA := DEFAULT_CC=clang CROSS=$(dir $(IOS_CC)) TARGET_SYS=iOS "TARGET_FLAGS=$(IOS_FLAGS)"
endif
ifndef LINK_TARGET
$(error Unsupported platform '$(PLATFORM)' -- supported: Linux, Android, Darwin, Windows, BSD)
$(error Unsupported platform '$(PLATFORM)')
endif
# ---------------------------------------------------------------------------
# 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)
# 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: static archive only, built through the upstream GNU Makefile.
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
# 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
all: $(LINK_TARGET)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
all: $(LINK_TARGET) $(BINDING)
$(BIN): hate-no-d.c $(LUAJIT_AR)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ hate-no-d.c \
$(LUAJIT_AR) $(EXPORT_LDFLAGS) $(LDFLAGS) $(PLAT_LIBS)
$(BUILD_DIR):
@mkdir -p $@
luajit: $(LUAJIT_AR)
$(API_DIR): | $(BUILD_DIR)
@mkdir -p $@
$(OBJ): hate-no-d.c | $(BUILD_DIR)
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ hate-no-d.c
# raylib is pulled in whole: nothing references it, so the linker would drop it
# and ffi.C would have nothing to resolve.
$(BIN): $(OBJ) $(LUAJIT_AR) $(RAYLIB_AR)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $(OBJ) \
$(RAYLIB_LINK) $(LUAJIT_AR) $(EXPORT_LDFLAGS) $(LDFLAGS) $(PLAT_LIBS)
# ---------------------------------------------------------------------------
# Lua bindings (hate-no-d.lua)
#
# 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 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
$(RAYLIB_API): $(RLPARSER) $(RAYLIB_SRC)/raylib.h | $(API_DIR)
$(RLPARSER) -i $(RAYLIB_SRC)/raylib.h -o $@ -f LUA -d RLAPI
$(RLGL_API): $(RLPARSER) $(RAYLIB_SRC)/rlgl.h | $(API_DIR)
$(RLPARSER) -i $(RAYLIB_SRC)/rlgl.h -o $@ -f LUA -d RLAPI -t "RLGL IMPLEMENTATION"
$(RAYMATH_API): $(RLPARSER) $(RAYLIB_SRC)/raymath.h | $(API_DIR)
$(RLPARSER) -i $(RAYLIB_SRC)/raymath.h -o $@ -f LUA -d RMAPI
$(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) generate.lua
bindings: $(BINDING)
# Fail if regeneration is not byte-identical or the binding does not load.
check-bindings: $(BINDING)
@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")'
# ---------------------------------------------------------------------------
# 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.
# Show the resolved configuration for the current (or selected) platform.
# Useful for checking a cross build before committing to it.
print-config:
@echo "PLATFORM = $(PLATFORM)"
@echo "OS_KIND = $(OS_KIND)"
@echo "CC / AR = $(CC) / $(AR)"
@echo "CC = $(CC)"
@echo "CFLAGS = $(CFLAGS)"
@echo "RAYLIB_OPT = $(RAYLIB_OPT)"
@echo "CPPFLAGS = $(CPPFLAGS)"
@echo "EXPORT_LDFLAGS = $(EXPORT_LDFLAGS)"
@echo "PLAT_LIBS = $(PLAT_LIBS)"
@echo "BSD_LIBDIRS = $(BSD_LIBDIRS)"
@echo "LINK_TARGET = $(LINK_TARGET)"
@echo "OBJ = $(OBJ)"
@echo "HOST_CC = $(HOST_CC)"
@echo "LUAJIT = $(LUAJIT)"
@echo "BUILD_DIR = $(BUILD_DIR)"
@echo "API_DIR = $(API_DIR)"
@echo "RLPARSER = $(RLPARSER)"
@echo "BINDING = $(BINDING)"
@echo "LUAJIT_MAKE_ARGS = $(LUAJIT_MAKE_ARGS)"
@echo "RAYLIB_AR = $(RAYLIB_AR)"
@echo "RAYLIB_MAKE_ARGS = $(RAYLIB_MAKE_ARGS)"
@echo "MACOSX_DEPLOYMENT_TARGET = $(MACOSX_DEPLOYMENT_TARGET) (HRT=$(MACOSX_HRT))"
@echo "ANDROID_ABI / API = $(ANDROID_ABI) / $(ANDROID_API)"
@echo "IOS_ARCH / MIN = $(IOS_ARCH) / $(IOS_MIN)"
@echo "WIN_ARCH = $(WIN_ARCH) (HOST_CC=$(HOST_CC))"
clean:
@if [ -f $(LUAJIT_DIR)/Makefile ]; then $(MAKE) -C $(LUAJIT_DIR) clean; fi
@if [ -f $(RAYLIB_SRC)/Makefile ]; then $(MAKE) -C $(RAYLIB_SRC) clean; fi
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)
$(MAKE) -C $(LUAJIT_DIR) clean
rm -f $(BIN)
.PHONY: all clean print-config help bindings check-bindings
.PHONY: all clean luajit print-config

138
README.md
View file

@ -2,136 +2,25 @@
A [Love2D](https://www.love2d.org/) antagonist.
A glorified [Makefile](./Makefile).
Should work on:
- Linux (x86, x86_64, ARM, ARM64)
- Android (armeabi-v7a, arm64-v8a, x86, x86_64)
- macOS (x86_64, ARM64)
- Windows (x86, x86_64 via MinGW; ARM64 via MSVC)
- FreeBSD, OpenBSD, NetBSD (x86, x86_64) or DragonFly BSD (x86_64)
## Quick Start
Save this as `quick-start.lua`:
```lua
require("hate-no-d")
InitWindow(1280, 720, "hate-no-d")
SetTargetFPS(60)
local text = "Your first hate-no-d application!"
local fontSize = 48
while not WindowShouldClose() do
BeginDrawing()
ClearBackground(SKYBLUE)
local width = MeasureText(text, fontSize)
DrawText(text, (GetScreenWidth() - width)/2, (GetScreenHeight() - fontSize)/2, fontSize, DARKBLUE)
EndDrawing()
end
CloseWindow()
```
Run it:
### On Linux, macOS, BSD, POSIX or Windows-MinGW
```sh
echo -e 'print("Hey! I am hate-no-d!")' > quick-start.lua
./hate-no-d quick-start.lua
```
On Windows:
### On Windows MSVC
```bat
echo print("Hey! I am hate-no-d!") > quick-start.lua
hate-no-d.exe quick-start.lua
```
`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.
## Build
## Building
Precompiled builds can be found on the [releases page](https://git.pbento.pt/pedro-bento/hate-no-d/releases).
### Linux prerequisites
Install a C toolchain, `git`, LuaJIT and the OpenGL/X11 headers.
Debian/Ubuntu:
```sh
sudo apt install build-essential git luajit libgl1-mesa-dev libx11-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev
```
Fedora:
```sh
sudo dnf install gcc make git luajit mesa-libGL-devel libX11-devel libXrandr-devel libXinerama-devel libXcursor-devel libXi-devel
```
Arch:
```sh
sudo pacman -S --needed base-devel git luajit mesa libx11 libxrandr libxinerama libxcursor libxi
```
Void:
```sh
sudo xbps-install -S base-devel git luajit MesaLib-devel libX11-devel libXrandr-devel libXinerama-devel libXcursor-devel libXi-devel
```
Gentoo:
```sh
sudo emerge --ask sys-devel/gcc dev-build/make dev-vcs/git dev-lang/luajit media-libs/mesa x11-libs/libX11 x11-libs/libXrandr x11-libs/libXinerama x11-libs/libXcursor x11-libs/libXi
```
### macOS prerequisites
```sh
xcode-select --install
brew install luajit
```
The Command Line Tools provide `make` and `clang`; LuaJIT runs the binding
generator.
### BSD prerequisites
FreeBSD:
```sh
sudo pkg install gmake luajit libX11 libXrandr libXinerama libXi libXcursor libglvnd
```
On OpenBSD, NetBSD and DragonFly install `gmake`, `luajit` (`pkg_add`, `pkgin`
or `pkg`) and the X11/GL libraries if they are missing. Use `gmake` instead of
`make`.
### Android prerequisites
Cross-compile from Linux or macOS with the Android NDK, passed as `ANDROID_NDK`
or exported as `ANDROID_NDK_HOME`.
### Windows prerequisites
MSVC: install Visual Studio 2022 with the "Desktop development with C++"
workload. `build.bat` finds it. raylib needs CMake 3.22+, so install CMake if the
bundled copy is older.
MinGW: use MSYS2 with the mingw-w64 toolchain and `make`. A native MSYS2 shell is
detected automatically; cross-compiling from elsewhere needs `PLATFORM=Windows`
(and `WIN_ARCH=i686` for 32-bit).
### Building from source
Linux, macOS and the BSDs:
### On Linux, macOS, BSD, POSIX or Windows-MinGW
```sh
git clone --recurse-submodules https://git.pbento.pt/pedro-bento/hate-no-d.git
@ -139,23 +28,10 @@ cd hate-no-d
make
```
`make` builds the CLI and regenerates `hate-no-d.lua`, which needs a host `luajit`
in `PATH` (override with `make LUAJIT=/path/to/luajit`). On the BSDs use `gmake`.
Windows with MSVC:
### On Windows MSVC
```bat
git clone --recurse-submodules https://git.pbento.pt/pedro-bento/hate-no-d.git
cd hate-no-d
build.bat
```
Android from Linux or macOS:
```sh
make PLATFORM=Android ANDROID_NDK=/path/to/ndk
```
`ANDROID_ABI` defaults to `arm64-v8a` and `ANDROID_API` to `21`; `make help` lists
the other ABIs. Building `armeabi-v7a` on a 64-bit host also needs
`HOST_CC="gcc -m32"`.

View file

@ -7,8 +7,7 @@
@rem
@rem Works from a plain cmd.exe (locates Visual Studio itself) or from an
@rem existing Developer Command Prompt. Produces hate-no-d.exe in this
@rem directory, statically linked against LuaJIT and raylib. raylib is built
@rem with CMake (shipped with Visual Studio) and linked in whole.
@rem directory, statically linked against LuaJIT.
@echo off
setlocal EnableExtensions
@ -42,18 +41,12 @@ if not exist "submodules\luajit\src\msvcbuild.bat" (
@rem msvcbuild.bat only ever appends options in a fixed order and deletes its
@rem own .obj files at the end, so every run is a full rebuild anyway.
@rem Pin /MT through the CL environment so LuaJIT's static CRT matches raylib's
@rem below; the static branch of msvcbuild.bat does not choose a runtime itself.
echo === Building LuaJIT (static, lua52compat) for Windows/%ARCH% ===
if exist "submodules\luajit\src\lua51.lib" del /q "submodules\luajit\src\lua51.lib"
set "HNOD_CL=%CL%"
set "CL=/MT"
pushd "submodules\luajit\src" >nul
call msvcbuild.bat lua52compat static
popd >nul
set "CL=%HNOD_CL%"
set "HNOD_CL="
@rem msvcbuild.bat does not set errorlevel when it fails, so the artifact is
@rem the only trustworthy signal.
@ -63,72 +56,16 @@ if not exist "submodules\luajit\src\lua51.lib" (
goto :fail
)
@rem raylib is built through CMake, which ships with Visual Studio.
@rem It uses the static CRT to match LuaJIT's default msvcbuild output, and
@rem defines BUILD_LIBTYPE_SHARED so its RLAPI functions carry dllexport and
@rem land in the exe's export table -- MSVC has no --export-dynamic, and ffi.C
@rem resolves C symbols through that table at runtime.
if not exist "submodules\raylib\CMakeLists.txt" (
echo build.bat: submodules\raylib is missing.
echo Fetch it with: git submodule update --init submodules/raylib
goto :fail
)
where cmake >nul 2>&1
if errorlevel 1 (
echo build.bat: cmake not found - install CMake 3.22+ or use a Developer Command Prompt.
goto :fail
)
if /I "%ARCH%"=="x64" set "CMAKE_ARCH=x64"
if /I "%ARCH%"=="x86" set "CMAKE_ARCH=Win32"
if /I "%ARCH%"=="arm64" set "CMAKE_ARCH=ARM64"
@rem One build tree per arch: CMake refuses to reuse a cache configured for
@rem another -A platform, so `build.bat x86` after x64 must not share it.
set "RAYLIB_BUILD=build\raylib-%ARCH%"
echo === Building raylib (static) for Windows/%ARCH% ===
cmake -S "submodules\raylib" -B "%RAYLIB_BUILD%" -A %CMAKE_ARCH% ^
-DBUILD_SHARED_LIBS=OFF ^
-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded ^
-DCMAKE_C_FLAGS_RELEASE="/O2 /Ob2 /DNDEBUG /DBUILD_LIBTYPE_SHARED" ^
-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE="%CD%\%RAYLIB_BUILD%\lib" ^
-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG="%CD%\%RAYLIB_BUILD%\lib"
if errorlevel 1 goto :fail
cmake --build "%RAYLIB_BUILD%" --config Release --target raylib
if errorlevel 1 goto :fail
if not exist "%RAYLIB_BUILD%\lib\raylib.lib" (
echo build.bat: raylib.lib was not produced.
goto :fail
)
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" /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 exist hate-no-d.obj del /q hate-no-d.obj
cl /nologo /c /O2 /W4 /D_CRT_SECURE_NO_WARNINGS ^
/I "submodules\luajit\src" /Fo"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" ^
"/WHOLEARCHIVE:%CD%\%RAYLIB_BUILD%\lib\raylib.lib" ^
"submodules\luajit\src\lua51.lib" ^
opengl32.lib gdi32.lib winmm.lib user32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib advapi32.lib
link /nologo /OUT:hate-no-d.exe hate-no-d.obj "submodules\luajit\src\lua51.lib"
if errorlevel 1 goto :fail
@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/raygui - ffi.C would not find it.
goto :fail
)
del /q "build\hate-no-d.obj"
del /q hate-no-d.obj
echo.
echo === Built %CD%\hate-no-d.exe ===
@ -138,10 +75,7 @@ exit /b 0
:clean
echo === Cleaning ===
rem Every build product lives under build\ or in the submodules' own trees;
rem only hate-no-d.exe is left at the root by a build.
if exist "hate-no-d.exe" del /q "hate-no-d.exe"
if exist "hate-no-d.obj" del /q "hate-no-d.obj"
for %%f in (hate-no-d.exe hate-no-d.obj) do if exist "%%f" del /q "%%f"
if exist "submodules\luajit\src" (
pushd "submodules\luajit\src" >nul
for %%f in (lua51.lib lua51.dll luajit.exe minilua.exe buildvm.exe) do if exist "%%f" del /q "%%f"
@ -150,7 +84,6 @@ if exist "submodules\luajit\src" (
del /q *.obj host\*.obj *.manifest >nul 2>&1
popd >nul
)
if exist "build" rmdir /s /q "build"
popd >nul
endlocal
exit /b 0

View file

@ -1,5 +1 @@
-I./submodules/luajit/src
-I./submodules/raylib/src
-I./submodules/raygui/src
-DRAYGUI_IMPLEMENTATION
-include ./submodules/raygui/src/raygui.h

View file

@ -1,810 +0,0 @@
---@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
))

File diff suppressed because it is too large Load diff

@ -1 +1 @@
Subproject commit ea9eb7edb5eac4a9d175d74523db34fac0fa5180
Subproject commit a4c064539ea931274d407e1249b4bb575424a0f4

@ -1 +0,0 @@
Subproject commit 1abccb3a5303d041dc14404b7dd874fa665dd4af

@ -1 +0,0 @@
Subproject commit 2f4b7d8e9f4aef3d5ed81a683b54594849e9d7a7