Files
akbasic/examples/galaga/main.c
Tachikoma 8ef0b253b2 Add the galaga example: a C engine with akbasic as its enemy brain
A GALAGA-style fixed shooter whose engine is C on libakgl (null physics)
with the interpreter embedded as the scripting engine that owns every
enemy's behavior. One DEF-only script is called per enemy per frame
through a custom akgl_Actor update hook; SELF@, ACTOR@ and GAME@ are host
bindings, so the script reads and writes the engine's real memory -- the
boss even swaps its own damage sprite by raising an actor state bit from
BASIC. Bullets, collision, scoring and screens stay C.

Structure arguments were measured and rejected for the per-frame path:
each pointer parameter spends a value-pool slot the pool never reclaims,
1,015 calls to exhaustion against an unbounded rebind (issue #36).

Built when AKBASIC_WITH_AKGL=ON. Two CTest entries: a 600-frame headless
autoplay run under the dummy SDL drivers, and an interop round-trip test
that links the real script.c and galaga.bas and pins the four boundary
claims, 24,000 sustained calls among them. docs_galaga_figures
regenerates the two checked-in figures. Art is Kenney CC0, byte for
byte, with provenance.

Co-authored-by: andrew <andrew@aklabs.net>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XiGgpHuXUm2mR4Wzndw3dc
2026-08-04 20:05:41 -04:00

699 lines
22 KiB
C

/**
* @file main.c
* @brief Startup, the frame loop, the screens, and teardown.
*
* The startup order is libakgl's one sequence that works (deps/libakgl
* include/akgl/game.h): metadata, akgl_game_init(), screen properties,
* akgl_render_2d_init(), a physics backend -- and then, new in this example,
* the interpreter. The scripts compute, the engine draws; the interpreter is
* lent no devices at all, so a script that tries SPRITE is refused by name.
*/
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <SDL3/SDL.h>
#include <SDL3_image/SDL_image.h>
#include <SDL3_ttf/SDL_ttf.h>
#include <akerror.h>
#include <akstdlib.h>
#include <akgl/actor.h>
#include <akgl/character.h>
#include <akgl/controller.h>
#include <akgl/draw.h>
#include <akgl/game.h>
#include <akgl/heap.h>
#include <akgl/physics.h>
#include <akgl/registry.h>
#include <akgl/renderer.h>
#include <akgl/sprite.h>
#include <akgl/text.h>
#include <akgl/ui.h>
#include "galaga.h"
/** @brief Where the example's assets live. CMake defines it; `--assets` overrides. */
#ifndef GALAGA_ASSET_DIR
#define GALAGA_ASSET_DIR "."
#endif
/** @brief The enemy script. CMake defines it; `--script` overrides. */
#ifndef GALAGA_SCRIPT_PATH
#define GALAGA_SCRIPT_PATH "galaga.bas"
#endif
/** @brief The HUD font. CMake defines it; headless runs still need it for the UI. */
#ifndef GALAGA_FONT_PATH
#define GALAGA_FONT_PATH "font.ttf"
#endif
#define GALAGA_PATH_MAX 1024
galaga_Game galaga_game;
galaga_Shared galaga_shared;
/** @brief Where `--screenshot` writes, and on which frame. NULL means never. */
static char *SHOTPATH = NULL;
static int SHOTFRAME = 0;
/** @brief Set in HANDLE_DEFAULT and read after FINISH; see the note in main. */
static int FAILED = 0;
/* ------------------------------------------------------------- starfield --- */
/*
* No parallax facility exists in libakgl and none is needed: a fixed array of
* stars advanced per frame and drawn with akgl_draw_point() between
* frame_start and akgl_game_update(). Two speed bands give the depth for
* free -- the slow band reads as far away.
*/
#define GALAGA_STARS 96
static struct
{
float x;
float y;
float speed;
Uint8 bright;
} STARS[GALAGA_STARS];
static void starfield_seed(void)
{
int i = 0;
for ( i = 0; i < GALAGA_STARS; i++ ) {
STARS[i].x = galaga_random() * (float)GALAGA_VIEW_WIDTH;
STARS[i].y = galaga_random() * (float)GALAGA_VIEW_HEIGHT;
if ( (i % 2) == 0 ) {
STARS[i].speed = 40.0f; /* the far band */
STARS[i].bright = 110;
} else {
STARS[i].speed = 110.0f; /* the near band */
STARS[i].bright = 220;
}
}
}
static akerr_ErrorContext *starfield_draw(void)
{
SDL_Color color = { 255, 255, 255, 255 };
int i = 0;
PREPARE_ERROR(errctx);
for ( i = 0; i < GALAGA_STARS; i++ ) {
STARS[i].y += STARS[i].speed * galaga_game.dt;
if ( STARS[i].y > (float)GALAGA_VIEW_HEIGHT ) {
STARS[i].y -= (float)GALAGA_VIEW_HEIGHT;
STARS[i].x = galaga_random() * (float)GALAGA_VIEW_WIDTH;
}
color.r = STARS[i].bright;
color.g = STARS[i].bright;
color.b = STARS[i].bright;
PASS(errctx, akgl_draw_point(akgl_renderer, STARS[i].x, STARS[i].y, color));
}
SUCCEED_RETURN(errctx);
}
/* ------------------------------------------------------------ screenshots --- */
/**
* @brief Read the render target back and write it out as a PNG.
*
* Called after everything has drawn and before the frame is presented,
* because SDL_RenderPresent is where the target stops being readable. The
* figures in docs/20 and docs/21 are output from this program rather than
* pictures somebody took once, so they cannot show a game that no longer
* exists.
*/
static akerr_ErrorContext *save_screenshot(char *path)
{
SDL_Surface *shot = NULL;
PREPARE_ERROR(errctx);
FAIL_ZERO_RETURN(errctx, path, AKERR_NULLPOINTER, "path");
shot = SDL_RenderReadPixels(akgl_renderer->sdl_renderer, NULL);
FAIL_ZERO_RETURN(errctx, shot, AKGL_ERR_SDL, "SDL_RenderReadPixels: %s", SDL_GetError());
ATTEMPT {
FAIL_ZERO_BREAK(errctx, IMG_SavePNG(shot, path), AKGL_ERR_SDL,
"IMG_SavePNG(%s): %s", path, SDL_GetError());
} CLEANUP {
SDL_DestroySurface(shot);
} PROCESS(errctx) {
} FINISH(errctx, true);
SDL_Log("Wrote %s", path);
SUCCEED_RETURN(errctx);
}
/* ---------------------------------------------------------------- assets --- */
static char *SPRITE_FILES[] = {
"sprite_galaga_player.json",
"sprite_galaga_bee.json",
"sprite_galaga_butterfly.json",
"sprite_galaga_boss.json",
"sprite_galaga_boss_hurt.json",
"sprite_galaga_playershot.json",
"sprite_galaga_enemyshot.json",
"sprite_galaga_boom.json",
NULL
};
static char *CHARACTER_FILES[] = {
"character_galaga_player.json",
"character_galaga_bee.json",
"character_galaga_butterfly.json",
"character_galaga_boss.json",
"character_galaga_playershot.json",
"character_galaga_enemyshot.json",
"character_galaga_boom.json",
NULL
};
static akerr_ErrorContext *asset_path(char *dir, char *name, char *dest, size_t size)
{
int count = 0;
PREPARE_ERROR(errctx);
FAIL_ZERO_RETURN(errctx, dir, AKERR_NULLPOINTER, "dir");
FAIL_ZERO_RETURN(errctx, name, AKERR_NULLPOINTER, "name");
FAIL_ZERO_RETURN(errctx, dest, AKERR_NULLPOINTER, "dest");
PASS(errctx, aksl_snprintf(&count, dest, size, "%s/%s", dir, name));
SUCCEED_RETURN(errctx);
}
/**
* @brief Sprites first, characters second. Not a preference: a character's
* JSON names its sprites by registry name, so a character loaded first fails
* on the first sprite it cannot find.
*/
static akerr_ErrorContext *load_assets(char *assetdir)
{
char path[GALAGA_PATH_MAX];
int i = 0;
PREPARE_ERROR(errctx);
FAIL_ZERO_RETURN(errctx, assetdir, AKERR_NULLPOINTER, "assetdir");
for ( i = 0; SPRITE_FILES[i] != NULL; i++ ) {
PASS(errctx, asset_path(assetdir, SPRITE_FILES[i], (char *)&path, sizeof(path)));
PASS(errctx, akgl_sprite_load_json((char *)&path));
}
for ( i = 0; CHARACTER_FILES[i] != NULL; i++ ) {
PASS(errctx, asset_path(assetdir, CHARACTER_FILES[i], (char *)&path, sizeof(path)));
PASS(errctx, akgl_character_load_json((char *)&path));
}
SUCCEED_RETURN(errctx);
}
/* --------------------------------------------------------------- startup --- */
/** @brief Replacement for akgl_game.lowfpsfunc, which logs a line per frame. */
static void galaga_lowfps(void)
{
}
static akerr_ErrorContext *startup(void)
{
PREPARE_ERROR(errctx);
PASS(errctx, aksl_strncpy((char *)&akgl_game.name, sizeof(akgl_game.name),
"akbasic galaga tutorial", sizeof(akgl_game.name) - 1));
PASS(errctx, aksl_strncpy((char *)&akgl_game.version, sizeof(akgl_game.version),
"1.0.0", sizeof(akgl_game.version) - 1));
PASS(errctx, aksl_strncpy((char *)&akgl_game.uri, sizeof(akgl_game.uri),
"net.aklabs.akbasic.galaga", sizeof(akgl_game.uri) - 1));
PASS(errctx, akgl_game_init());
akgl_game.lowfpsfunc = &galaga_lowfps;
/* Properties before the renderer: akgl_render_2d_init reads both, and an
* unset one defaults to the string "0" -- a zero-sized window. */
PASS(errctx, akgl_set_property("game.screenwidth", "1280"));
PASS(errctx, akgl_set_property("game.screenheight", "960"));
PASS(errctx, akgl_render_2d_init(akgl_renderer));
FAIL_ZERO_RETURN(
errctx,
SDL_SetRenderLogicalPresentation(
akgl_renderer->sdl_renderer,
GALAGA_VIEW_WIDTH,
GALAGA_VIEW_HEIGHT,
SDL_LOGICAL_PRESENTATION_INTEGER_SCALE),
AKGL_ERR_SDL,
"%s",
SDL_GetError()
);
/* The view is what the camera looks through, so it says the same thing. */
akgl_camera->x = 0.0f;
akgl_camera->y = 0.0f;
akgl_camera->w = (float)GALAGA_VIEW_WIDTH;
akgl_camera->h = (float)GALAGA_VIEW_HEIGHT;
/*
* akgl_game_init does NOT install a physics backend, whatever physics.h's
* file comment says (libakgl docs/14-physics.md). Null physics accepts
* every call and moves nothing: whatever writes x and y directly is the
* mover, and in this game that is BASIC writing through ACTOR@.
*/
PASS(errctx, akgl_physics_init_null(akgl_physics));
SUCCEED_RETURN(errctx);
}
/* ---------------------------------------------------------------- the UI --- */
static akgl_UiMenu TITLE_MENU = {
"titlemenu", { "START", "QUIT" }, 2, 0, false, NULL
};
static akgl_UiMenu AGAIN_MENU = {
"againmenu", { "PLAY AGAIN", "QUIT" }, 2, 0, false, NULL
};
/* Clay borrows label text until frame_end, so these cannot be locals. */
static char HUD_SCORE[64];
static char HUD_LIVES[64];
/**
* @brief Draw a headline centred above the menu, in the banner font.
*
* Direct text rather than a ui label: the menu owns AKGL_UI_ANCHOR_CENTER,
* and a label anchored there disappears behind it -- there is no
* top-centre anchor to reach for. Drawn before the UI bracket, so the menu
* still paints over it if the two ever meet.
*/
static akerr_ErrorContext *draw_banner(char *text)
{
SDL_Color ink = { 235, 235, 235, 255 };
TTF_Font *font = NULL;
int w = 0;
int h = 0;
PREPARE_ERROR(errctx);
FAIL_ZERO_RETURN(errctx, text, AKERR_NULLPOINTER, "text");
font = SDL_GetPointerProperty(AKGL_REGISTRY_FONT, "banner", NULL);
FAIL_ZERO_RETURN(errctx, font, AKERR_KEY, "the banner font is not loaded");
PASS(errctx, akgl_text_measure(font, text, &w, &h));
PASS(errctx, akgl_text_rendertextat(font, text, ink, 0,
(GALAGA_VIEW_WIDTH - w) / 2, 280));
SUCCEED_RETURN(errctx);
}
static akerr_ErrorContext *declare_title(void)
{
PREPARE_ERROR(errctx);
PASS(errctx, akgl_ui_menu(&TITLE_MENU));
SUCCEED_RETURN(errctx);
}
static akerr_ErrorContext *declare_play(void)
{
int count = 0;
PREPARE_ERROR(errctx);
PASS(errctx, aksl_snprintf(&count, HUD_SCORE, sizeof(HUD_SCORE),
"SCORE %06d", galaga_game.score));
PASS(errctx, aksl_snprintf(&count, HUD_LIVES, sizeof(HUD_LIVES),
"LIVES %d WAVE %d", galaga_game.lives, galaga_shared.wave));
PASS(errctx, akgl_ui_label("score", HUD_SCORE, AKGL_UI_ANCHOR_TOP_LEFT, NULL)); <