Tidepod 1.0.0-rc5 Generated 2026-10-23

Tidepod Documentation & Developer Guide

Guides, tool references and the complete library reference for building TI-99/4A software with Tidepod.

← Back to IDE Overview Download PDF (13.6 MB)
Tidepod Development Environment

Tidepod
Reference Manual

Complete Guide to the Tidepod IDE, Toolchain, Language Support, and Runtime APIs

Version 1.0.0-rc5 • Reference Edition
Core Environment Tidepod Integrated Development Environment
tms9900-gcc (GCC 14.2.0 C99) & binutils 2.42
tms9900-packer automatic banking & layout engine
Language & Runtime Libraries Tidepod libc (C runtime) & Extended BASIC support
F18A GPU coprocessor toolkit & vector pipeline
Extended BASIC cross-compiler & runtime support
Published by shennannigans.net • October 2026

Contents

Chapter 6API Reference
  1. API Reference144
  2. cgetc, kbhit, getchar153
  3. conio154
  4. cputc, cputs, cprintf, clrscr155
  5. gotoxy, gotox, gotoy, wherex, wherey156
  6. fclose157
  7. fcopy_path, fcopy_path_pg, fcopy_path_typed158
  8. fgetc159
  9. fgets160
  10. fopen, fclose, fread, fwrite, fflush, feof, ferror, clearerr, vdp_load_file, vdp_save_file, fcopy_path161
  11. fprintf163
  12. fputc164
  13. fputs165
  14. fread, fwrite166
  15. fseek, ftell, rewind167
  16. ftell168
  17. fwrite168
  18. printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, vsnprintf169
  19. putchar170
  20. puts171
  21. snprintf172
  22. sprintf172
  23. sscanf, scanf173
  24. stdio_enable174
  25. stdio_enable_all_disk175
  26. stdio_enable_chip176
  27. stdio_enable_fat177
  28. stdio_enable_prog178
  29. stdio_enable_wds179
  30. stdio_last_error180
  31. stdio_set_vdp_base181
  32. stdio_set_wds_vdp_buf, stdio_get_wds_vdp_buf182
  33. ti_text_mode, ti_text_load_builtin_font183
  34. remove, unlink, rename184
  35. ti_dsr_enum, ti_dsr_enum_ex185
  36. ti_opendir, ti_readdir, ti_closedir, ti_dir_volume, opendir, readdir, closedir186
  37. ti_stat, ti_protect, ti_mkdir, ti_rmdir188
  38. ti_vdp_detect, ti_vdp_text80_ok, ti_vdp_has_attrs, ti_vdp_has_gpu, console_gpu_invalidate, ti_load_ega_palette, ti_load_tms9918_palette189
  39. resource_copy, unwrap, rom_to_vram, rom_to_ram, rom_to_vram_ex, rom_to_ram_ex191
  40. rom_to_vram, rom_to_ram, rom_to_vram_ex, rom_to_ram_ex, unwrap193
  41. sams196
  42. debug, __dbg_printf, BRK200
  43. profiler, PROF_FRAME_END, PROF_BEGIN, PROF_END202
  44. f18a_gpu, F18A_GPU_IDLE, F18A_GPU_MMIO8, F18A_GPU_MMIO16204
  45. f18a_gpu_host206
  46. memchr208
  47. memcmp209
  48. memcpy210
  49. memmove211
  50. memset212
  51. strcat213
  52. strcmp214
  53. strcpy215
  54. strlen216
  55. strncat217
  56. strncmp218
  57. strncpy219
  58. strnlen220
  59. strstr221
  60. strtok222
  61. ctype, isalnum, isalpha, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit, tolower, toupper223
  62. isalnum225
  63. isalpha226
  64. iscntrl227
  65. isdigit228
  66. isgraph229
  67. islower230
  68. isprint231
  69. ispunct232
  70. isspace233
  71. isupper234
  72. isxdigit235
  73. tolower236
  74. toupper237
  75. abort238
  76. abs239
  77. atoi, atol240
  78. atol240
  79. calloc241
  80. exit, _Exit242
  81. free243
  82. malloc, free, calloc, realloc, mallinfo, get_free_heap, malloc_walk244
  83. qsort245
  84. rand, srand246
  85. realloc247
  86. strtol, strtoul, atoi, atol248
  87. strtoul249
  88. errno250
  89. atanf251
  90. ceilf, floorf252
  91. cosf, sinf, tanf253
  92. expf254
  93. fabsf255
  94. floorf, ceilf256
  95. fmodf257
  96. logf258
  97. powf259
  98. sinf, cosf, tanf260
  99. sqrtf261
  100. tanf, sinf, cosf262
  101. libc263
  102. SAMS_FAR, SAMS_FAR_PTR, SAMS_FAR_OBJ, sams_new, sams_new_bytes, sams_delete, SAMS_WITH_NEAR264
  103. ASC265
  104. CHAR266
  105. CHARSET267
  106. chr268
  107. CLEAR269
  108. COINC270
  109. COLOR271
  110. DELSPRITE272
  111. DISPLAY AT273
  112. DISTANCE274
  113. GCHAR275
  114. HCHAR276
  115. INIT277
  116. JOYST278
  117. KEY279
  118. LEN280
  119. LOAD281
  120. LOCATE282
  121. MAGNIFY283
  122. MOTION284
  123. PATTERN285
  124. PEEK286
  125. PEEKB287
  126. PEEKV288
  127. POKE289
  128. POKEB290
  129. POKEV291
  130. POSITION292
  131. RND293
  132. SCREEN294
  133. seg295
  134. SOUND296
  135. SOUND_LIST297
  136. SOUND_STOP298
  137. SPRITE299
  138. str300
  139. VAL301
  140. VCHAR302
  141. VDPMEMCPY303
  142. VDPMEMSET304
  143. VDPREAD305
  144. VSYNC306
  145. xb-control307
  146. xb-data309
  147. xb-input310
  148. xb-io312
  149. xb-math313
  150. xb-misc315
  151. xb-screen317
  152. xb-sound319
  153. xb-sprites321
  154. xb-string323
  155. xb-sub325
  156. xb-tiles326
  157. xb-variables327
  158. xb-vdp329
Chapter 1

Getting Started

Docs / Getting Started

What is Tidepod?

Overview

Tidepod is a development suite for the TI-99/4A. You write C (or compiled Extended BASIC, or assembly), and Tidepod turns it into a cartridge image or disk program, runs it in an emulator and lets you debug it at source level. The same tidepod binary is both the graphical IDE and a command-line project manager.

This page describes the pieces and how they fit together. You do not need to build any of them: every release ships with the complete toolchain.

Components

ComponentWhat it isYou interact with it via
tidepodIDE (editor, build, embedded emulator, debugger, graphics viewers, profiler) and CLI project manager.GUI, or tidepod new/add/remove/list/set-type/sync/run
.projectJSON project description: type, source list, per-file placement, build and emulator settings.CLI and IDE dialogs (reference)
MakefileGenerated from .project by tidepod sync. Never edited by hand.make, make debug, make clean
tms9900-elf-gccGCC 14.2 cross compiler for the TMS9900, plus binutils (as, ld, objdump, objcopy, …) and tms9900-elf-gdb. Also compiles Extended BASIC (-x xb).Invoked by the Makefile
tms9900-packerAuto-banker: distributes code and data over 8 KB cartridge banks, writes the linker script, cross-bank trampolines and resource headers, and produces EA5 disk images.Invoked by the Makefile (details)
gpu-image-mapGenerates the map header for F18A GPU images.Invoked by the Makefile (details)
libc.aC library: strings, ctype, stdlib (with optional near heap and SAMS far heap), console I/O and conio, keyboard, soft-float math, disk I/O through fopen and friends, VDP detection, F18A GPU host helpers, ROM resource copy.#include (API reference)
libxb.aRuntime for compiled Extended BASIC programs (CALL SPRITE, CALL SOUND, …).XB projects
crt0_*.oStart-up code per project type (8K, banked, EA5, XB, GPU).Selected by project type
ti994a-emuStand-alone emulator with GDB server, headless mode, key injection and screenshots. The IDE embeds the same core.tidepod run or directly (reference)
man pagesReference pages for libc, the XB runtime and the XB language.IDE help, man, and the API section of this site
Agent skillti99-tidepod-gamedev: instructions for AI coding agents, copied into every new project.Your AI agent (details)
ExamplesComplete projects: pong, pong_xb, f18a_bump, ghostbusters, ccleste_ti, fileman, …resources/examples/ in the install

From source to cartridge

Build flow
  your sources (.c .asm .bas)  +  binary resources (.dat)
                 │
                 │  tidepod new / add / remove        ──►  MyGame.project
                 │  tidepod sync                      ──►  Makefile (generated)
                 ▼
  make  ─┬─ tms9900-elf-gcc / as          .c .bas .asm  ──►  .o
         ├─ tms9900-packer                .o + .dat     ──►  autobank.ld, trampolines,
         │                                                    include/resource_defs.h,
         │                                                    bank_report.json
         ├─ tms9900-elf-ld                               ──►  mygame.bin  (+ mygame.debug)
         └─ zip                                          ──►  mygame.rpk  (cartridge)
                 │                                            mygame.dsk  (EA5 projects)
                 ▼
  tidepod run  ──►  ti994a-emu --cart mygame.rpk --autorun …

The details of each step, and every generated file, are covered in Build pipeline.

Project types

--type"type" in .projectLanguageOutputNeeds 32K expansion
8k0CSingle 8 KB cartridge, no banking. .data/.bss live in scratchpad.No
banked (default)1CBank-switched cartridge (paged378 PCB).Yes
xb2Extended BASIC, compiledBank-switched cartridge.Yes
ea53CEditor/Assembler option 5 program files on a .dsk image.Yes
custom4anyYou provide the build; no Makefile generation.—
—5C8 KB cartridge that uses the 32K expansion (IDE only).Yes

Memory map as Tidepod uses it

RangeRegionUsed by Tidepod for
0x2000–0x3FFFLow 8K expansion RAM.persistent: runtime stubs, cross-bank trampolines, code you mark persistent.
0x4000–0x5FFFPeripheral DSR spaceDisk controller ROMs (not yours).
0x6000–0x7FFFCartridge windowOne 8 KB bank of your code/data/resources at a time.
0x8300–0x83FFScratchpad RAMWorkspace registers; .scratchpad code from 0x8342 by default. 0x83C0–0x83FF belongs to the console ISR/GPL.
0x8400, 0x8800–0x8C02Sound / VDP portsMemory-mapped I/O, not RAM.
0xA000–0xFFFFHigh 24K expansion RAM.data, .bss and the C stack (grows down from the top).

Video RAM (16 KB) is on a separate bus and is only reachable through the VDP ports. Where your code and data end up is controlled per file; see Memory placement.

What happens at power-on (banked carts)

  1. Bank 0: the console finds the cartridge header and jumps to _start. Interrupts are off. A small copier is copied into scratchpad (0x8342) and started.
  2. Scratchpad copier: copies .persistent to low RAM (0x2000), .data to high RAM (0xA000), then your .scratchpad code over itself.
  3. _persistent_init: clears .bss and calls main().

If main() returns, the C runtime startup code (crt0) safely catches it in an endless loop (while (1) {}). Returning from main() is completely safe and will not crash or jump into uninitialized memory.

Type model

int and size_t are 16-bit, long is 32-bit, and float is IEEE binary32 implemented in software. The near-heap allocator (malloc, calloc, realloc, free in high 32K RAM) defaults to 0 bytes unless enabled via "heapSize" in .project (or --heap-size on tms9900-packer), and <sams.h> provides a far-heap allocator (sams_malloc) for SAMS paged memory; prefer static or global buffers when dynamic allocation isn't needed. For a detailed breakdown of 16-bit type pitfalls, memory banking constraints, and performance tips, see the C Programming Gotchas & Porting Guide.

Docs / Getting Started

Installation

macOS · Linux · Windows

Tidepod is distributed as a completely self-contained offline developer suite. Each release package includes the graphical IDE, command-line interface, the full tms9900-elf-* GCC toolchain, standard C and Extended BASIC runtime libraries, assembler and linker scripts, manual pages, bundled example projects, the AI coding agent skill, and the stand-alone ti994a-emu emulator with integrated GDB server.

Pre-built binaries are provided for macOS (Apple Silicon DMG), Linux (x86-64 and arm64 DEB packages), and Windows 64-bit (interactive Setup installer and zero-install portable ZIP archive).

macOS (Apple Silicon)

  1. Open tidepod-<version>-macos-arm64.dmg and drag Tidepod.app to Applications.
  2. To use the CLI and toolchain from a terminal, add both directories to your PATH:
~/.zshrc
export PATH="/Applications/Tidepod.app/Contents/MacOS:$PATH"
export PATH="/Applications/Tidepod.app/Contents/Resources/toolchain/bin:$PATH"

Linux (Debian / Ubuntu, amd64 or arm64)

Terminal
sudo apt install ./tidepod-<version>-linux-amd64.deb

The package installs to /opt/tidepod and links /usr/bin/tidepod. The toolchain lives in /opt/tidepod/resources/toolchain/bin; add it to your PATH if you want to call tms9900-elf-gcc, tms9900-elf-gdb or ti994a-emu directly:

~/.bashrc
export PATH="/opt/tidepod/resources/toolchain/bin:$PATH"

Windows (x86-64)

  • Installer (…-windows-x86_64-setup.exe): installs to Program Files\Tidepod, adds Start Menu and desktop shortcuts, and by default puts Tidepod and the toolchain on the system PATH. Uninstall from Settings → Apps.
  • Portable (…-windows-x86_64.zip): unpack anywhere and run tidepod.exe. PATH is not changed; the IDE still finds its bundled toolchain. The bundle includes the small set of Unix tools the generated Makefiles need.

Check the installation

Terminal
tidepod new --help            # CLI usage for "new"
tms9900-elf-gcc --version     # GCC 14.2.0 for the TMS9900
ti994a-emu --version
Note

tidepod with no command, or with an argument it doesn't recognise as a command, opens the IDE. Use a subcommand with --help to stay in the terminal.

What's in the install

Path (inside the install)Contents
toolchain/bintms9900-elf-*, tms9900-packer, gpu-image-map, ti994a-emu
toolchain/liblibc.a, libxb.a, crt0_*.o, cartridge headers
toolchain/includelibc headers (stdio.h, conio.h, resource_copy.h, f18a_gpu_host.h, debug.h, profiler.h, …)
toolchain/ldscriptsLinker script templates used by the packer
resources/manMan pages (also in the API reference)
resources/examplesExample projects
resources/agent-skillsThe ti99-tidepod-gamedev agent skill

On macOS these directories are under Tidepod.app/Contents/Resources/; on Linux under /opt/tidepod/resources/.

Docs / Getting Started

Quick start: build and run a project

5 minutes

This guide walks through creating, compiling, and running a complete banked C cartridge using the Tidepod toolchain. In under two minutes, you will establish a reproducible build workflow that targets the TMS9900 CPU and TMS9918A VDP. The workflow operates identically from the command line or within the integrated IDE.

1. Create the project

Scaffold a new project using the tidepod new command. Specifying --type banked configures an auto-banked cartridge utilizing the standard 378/379 bank-switching latch, while --menu "HELLO" defines the exact menu label displayed by the TI-99/4A master console selection screen upon power-on.

Terminal
tidepod new hello --type banked --menu "HELLO" --path ./hello
cd hello

In the IDE: Choose File → New Project… (Cmd+Shift+N on macOS, Ctrl+N on Linux/Windows). In the creation dialog, enter Project Name: hello, set Cart Menu Title: to HELLO, choose your workspace directory in Location:, select Project Type: C Banked Cartridge - 32K, and click Create. The IDE creates the files and opens the workspace immediately with main.c active in the editor tab and the directory structure listed in the Files sidebar.

The scaffolding establishes a standardized directory layout designed to isolate your source code from toolchain-generated artifacts. The table below details each generated file and its lifecycle during compilation:

FilePurposeEdit?
hello.projectProject description (JSON)Through the CLI/IDE; hand edits need tidepod sync
main.cYour program (template prints two lines)Yes
.cart_header.asmCartridge header with the menu name (hidden file)No; regenerated by sync. To customise, copy it to cart_header.asm, which then takes precedence
include/bankswitch.hswitchtobank() macroNo
MakefileGenerated buildNever
Makefile.customYour extra make rules; included by the Makefile and never regeneratedYes
layout.xmlRPK cartridge layoutNo (regenerated by sync)
.agents/skills/, .cursor/skills/The agent skillNo

Notice that the root Makefile is managed entirely by Tidepod. Whenever you add files, change compiler flags, or adjust memory placement pragmas, Tidepod regenerates the Makefile to ensure dependency graphs and bank allocations remain perfectly synchronized. If your build requires custom pre-processing stages (such as asset conversion scripts or automated tests), define them in Makefile.custom, which is automatically included and preserved across synchronizations.

2. Build

Compile the project by running make in the project directory. The build pipeline invokes tms9900-elf-gcc with optimization flags, compiles main.c against Tidepod libc runtime headers, and runs tms9900-packer to produce both a raw binary and an RPK cartridge package:

Terminal
make

In the IDE: Click the Build (Wrench) button on the top toolbar or press F7 (or choose Build → Build). Compiler diagnostics and bank-packing messages stream into the Build Log panel at the bottom. If an error occurs, clicking the red diagnostic line jumps directly to the offending source line in the editor.

The build produces two distinct output artifacts in the project root:

  • hello.bin: A flat binary image containing the physical ROM banks concatenated in order. This image is ready for flashing directly to physical cartridge EEPROMs or modern flash multi-carts.
  • hello.rpk: An emulator package containing the ROM slices and a generated layout.xml. The descriptor specifies the memory socket mapping, cartridge board type (e.g. paged378), and 32 KB expansion requirements for ti994a-emu and MAME.

To build with full symbolic debugging information from the command line, run make debug instead. This compiles with -O0 -g -gdwarf-2, generating rich DWARF symbols and line mappings required by the embedded debugger and GDB. In the IDE, initiating a debug session with F5 automatically triggers a debug build.

3. Run

Launch your software immediately in the emulator:

Terminal
tidepod run

tidepod run initializes ti994a-emu, attaches the hello.rpk package, configures the console peripheral expansion box (PEB) cards, and executes the console startup sequence with automatic menu bypass so your program starts instantly. Note that tidepod run executes the existing build output without recompiling: always run make before testing your changes in the terminal.

In the IDE: Click the Run (Play) button on the toolbar or press Mod+R (or choose Build → Run). The IDE automatically saves open files, performs an incremental build if sources have changed, and starts execution inside the embedded Emulator panel. Click inside the emulator display to capture keyboard and joystick input (click back into the editor to resume typing). Press F6 to pause or resume execution at any time. To debug step-by-step with register inspection and breakpoints, press F5 (or click the Debug (Bug) icon) instead.

4. Add files as the project grows

As your codebase expands into multiple translation units and graphics assets, register each file with Tidepod so the build engine can manage dependencies and auto-banking:

Terminal
tidepod add src/player.c src/level.c   # new C sources
tidepod add resources/tiles.dat         # a binary resource
tidepod list                            # inspect active build members
make

The tidepod add command updates hello.project, routes the new sources through the appropriate compiler or resource packer, and re-emits the Makefile in a single atomic step. When you compile with make, the tms9900-packer automatically measures the size of each compiled object and places functions into ROM banks according to your configured packing heuristic.

In the IDE: You manage project members visually through the Files sidebar:

  • Create or import: Right-click inside the workspace tree and choose New File… or New Folder…, or copy files from your desktop into the project directory.
  • Register member: Right-click any file in the Files sidebar and check Include in Build. The IDE inspects the file extension, registers it under srcFiles (or libFiles for .a archives) in hello.project, and updates the Makefile automatically.
  • Configure placement: Right-click a source file in the Files sidebar and toggle Force Persistent, Force Scratchpad, or F18A GPU source (which opens the F18A GPU source dialog to configure VRAM base: and Stack top:, later editable via Edit GPU base / stack…).
The scaffolded project open in the Tidepod IDE, ready to build and run.
The scaffolded project open in the Tidepod IDE, ready to build and run.
Docs / Getting Started

Project types and the .project file

Reference

Every Tidepod project is anchored by a single <name>.project file in its root directory. This JSON manifest is the single source of truth for the entire build pipeline: it specifies the target cartridge architecture, all C and assembly build members, binary resources, memory placement directives, bank-packing heuristics, and compiler optimization levels. Whenever you modify project settings through the IDE or using CLI commands like tidepod add and tidepod set-type, the project file is updated and Tidepod automatically regenerates the underlying Makefile, linker scripts, and emulator layout.xml cartridge descriptor.

Project types

The project type determines how the linker organizes the object code and what physical hardware environment is assumed. You select the target architecture when initializing a new workspace via tidepod new --type …, or switch existing projects using tidepod set-type or the Project Settings dialog in the IDE.

--type"type"OutputUse it for
8k08 KB cartridge (.bin + .rpk), no 32K RAM expansion requiredSmall programs that fit one ROM bank and the console's 256 bytes of scratchpad RAM
—58 KB cartridge that uses the 32K expansionSmall code, more RAM. Selected in Project Settings (“8K Cart + 32K RAM”)
banked (default)1Bank-switched cartridge, any number of 8 KB banks; requires 32KAlmost everything: the packer spreads your code and data over banks automatically
xb2Banked cartridge built from Extended BASIC source (main.bas) compiled to machine codeBASIC programs that need to run fast
ea53Editor/Assembler option 5 program files (NAME1, NAME2, …) and a .dsk image containing themDisk-loaded programs
custom4Whatever your own Makefile buildsProjects with their own build; Tidepod never writes the Makefile

Banked Cartridges (Type 1) represent the standard configuration for modern TI-99/4A software. Under this model, the 8 KB cartridge memory space mapped at address range 0x6000–0x7FFF is bank-switched dynamically using inverted 378/379 latch writes. Because banked carts require the 32 KB Memory Expansion, persistent variables and the execution stack reside in dedicated CPU RAM, while the tms9900-packer distributes compiled C functions across any number of 8 KB ROM banks and automatically synthesizes transparent cross-bank trampolines.

Unexpanded 8K Cartridges (Type 0 and 5) are designed for standalone distribution where no peripheral expansion box is assumed. Because an unexpanded console provides only 256 bytes of internal scratchpad RAM (0x8300–0x83FF), Type 0 cartridges must manage memory with extreme care: static variables and call frames must fit within the unreserved portions of the scratchpad. Type 5 retains the single 8 KB ROM limitation but enables the 32 KB expansion RAM for larger heap and stack allocations.

Extended BASIC (Type 2) ingests standard Extended BASIC source code (main.bas) and translates it via GCC's Extended BASIC frontend into native TMS9900 machine code. Rather than interpreting tokens through the console's GPL interpreter, the compiled binary links directly against Tidepod libc, producing standalone cartridges that execute 20 to 50 times faster while preserving the familiar BASIC syntax.

A typical file

Below is a complete example of a banked game project file. It defines compiler flags, cycle budget targets for the frame profiler, scratchpad memory offsets, auto-mounted floppy disks, and per-file placement rules:

mygame.project
{
  "name": "mygame",
  "cartMenuName": "MY GAME",
  "type": 1,
  "workspacePath": "/Users/me/projects/mygame",
  "toolchainPath": "/Applications/Tidepod.app/Contents/Resources/toolchain",
  "optLevelDebug": 0,
  "optLevelRelease": 3,
  "target_fps": 60,
  "includePaths": "",
  "libPaths": "",
  "customCompilerFlags": "",
  "customLinkerFlags": "",
  "scratchpadBase": "0x8380",
  "scratchpadSize": 128,
  "packing_algo": 0,
  "pcbType": "paged378",
  "dsk1": "disks/data.dsk",
  "srcFiles": [
    {"path": "src/main.c"},
    {"path": "src/isr.c", "forcePersistent": true},
    {"path": "src/gpu.c", "forceGpu": true, "gpuBase": "0x3000", "gpuStack": "0x3F00"},
    {"path": "resources/tiles.dat"}
  ],
  "libFiles": [
  ]
}

Field reference

The project manifest exposes fine-grained control over the compilation pipeline, memory placement, and emulator integration. Below is a complete breakdown of each supported configuration key:

KeyMeaning
nameProject name. The output files are named after it in lower case (mygame.bin, mygame.rpk).
cartMenuNameText shown in the console's cartridge menu (upper case, max. 31 characters).
typeProject type, see the table above.
workspacePathProject directory.
toolchainPathToolchain used by the Makefile. Tidepod corrects it automatically when it points at a toolchain that no longer exists (for example after moving the install).
optLevelDebug, optLevelRelease0, 1, 2 → -O0…-O2; 3 → -Os. Defaults: debug 0, release 3.
target_fpsFrame-rate target used by the profiler to compute the frame budget: 60, 30, 20, 15 or 10. Budget = (60 / target) × 50,065 CPU cycles.
includePathsExtra include directories, separated by spaces or ;. Each becomes -I….
libPathsExtra library directories.
customCompilerFlags, customLinkerFlagsAppended verbatim to the compile / link commands.
scratchpadBase, scratchpadSizeWhere the packer may place scratchpad code. Omitted = packer default (base 0x8342, up to 0x8400). Project Settings offers presets under Scratchpad Base:: Full scratchpad (0x8320), +libtivgm2 (0x8340), +disk access (0x8380), and Custom.
heapSizeNear-heap size in bytes reserved in high 32K expansion RAM for malloc, calloc, realloc, and free (integer, default 0). Passed as --heap-size to tms9900-packer.
packing_algoBank packing strategy: 0 = best-fit decreasing (bfd), 1 = first-fit decreasing (ffd), 2 = call-graph clustering (cluster).
pcbTypeCartridge board written to layout.xml: standard (8K), paged378 (banked default) or paged379i (inverted bank order; old projects that carry it by mistake are migrated automatically).
dsk1–dsk3Disk images mounted when the project is opened in the IDE or run with tidepod run. Workspace-relative or absolute paths. See Disks & peripherals.
hard1–hard3Raw hard-disk images (.hd, .hdf, .raw) for an HFDC controller.
emuOptional per-project emulator overrides (PEB cards, VDP). See The emulator.
srcFilesBuild members, see below.
libFilesExtra static libraries (.a) to link. "forcePersistent": true puts the whole library in persistent RAM (--persistent-lib).

Compiler Optimization Strategies: Setting optLevelRelease to 3 invokes GCC's -Os size-optimization profile. On the TMS9900 16-bit processor, where each instruction requires two to four bytes of ROM and memory access is bounded by 8-bit multiplexed bus cycles, optimizing for code compactness almost always yields the highest overall execution speed. GCC minimizes stack frame manipulation, maximizes utilization of the 16 workspace registers (R0–R15), and eliminates redundant SWPB byte-swapping operations. For active debugging, optLevelDebug: 0 emits unoptimized, line-accurate code with full DWARF debug symbols that map cleanly to source lines in the debugger.

Bank Packing Algorithms: The packing_algo parameter directs how the tms9900-packer assigns compiled object files into physical 8 KB ROM banks. Best-Fit Decreasing (bfd, algo 0) packs the largest translation units first into the tightest available bank space to minimize slack bytes. First-Fit Decreasing (ffd, algo 1) fills banks sequentially. Call-Graph Clustering (cluster, algo 2) analyzes call trees across functions: tightly coupled caller and callee routines are deliberately co-located within the same bank, dramatically reducing runtime bank-switching overhead during time-critical game loops.

Scratchpad Memory Management: The console's internal 256 bytes of 16-bit scratchpad RAM (0x8300–0x83FF) offers zero-wait-state access, making it several times faster than external 32K expansion RAM. However, the console BIOS reserves specific regions: 0x8300–0x831F for the primary workspace registers, 0x8320–0x833F for sound players, and 0x834A–0x837F for disk controller DSR communication buffers (plus 0x83C0–0x83FF if the console ISR is enabled). New projects leave scratchpadBase empty, which uses the packer default (0x8342, or 0x8320 / 0x8340 / 0x8380 via the Scratchpad Base: preset in Project Settings), ensuring user routines do not clobber active system hooks while squeezing maximum performance out of critical hot paths.

srcFiles entries

Each entry in srcFiles describes a build artifact and optional placement directives. Tidepod inspects the file extension to route the member through the appropriate compilation stage:

  • .c — compiled with tms9900-elf-gcc.
  • .asm — assembled with tms9900-elf-as.
  • .bas — Extended BASIC, compiled with tms9900-elf-gcc -x xb (XB projects).
  • .dat — any binary file; becomes a ROM resource.
OptionCLI equivalentEffect
"forcePersistent": trueadd --persistentCode and data go to RAM that is always mapped, instead of a ROM bank.
"forceScratchpad": trueadd --scratchpadCode goes to the fast 16-bit scratchpad RAM.
"forceGpu": true, "gpuBase", "gpuStack"add --gpu --gpu-base … --gpu-stack …Builds the file as an F18A GPU image instead of host code. See F18A GPU code.

Persistent RAM Placement: In a banked cartridge, switching the ROM bank at 0x6000 causes all functions and constants located in that bank to immediately vanish from the CPU address space. This creates a severe hazard for Interrupt Service Routines (ISRs) and audio playback engines, which can be triggered at any moment by the 60 Hz vertical blank interrupt. Applying "forcePersistent": true (or #pragma bank persistent) instructs the linker to place the compiled code into the unbanked 32 KB expansion RAM. Persistent code is always resident and immediately callable without bank transition penalties.

Fast Scratchpad Routines: Code tagged with "forceScratchpad": true (or #pragma bank scratchpad) is packed into the cartridge ROM but copied into the console's zero-wait-state scratchpad RAM at startup. This is ideal for cycle-critical inner loops such as sprite coordinate transformers, collision detection routines, or software math functions.

F18A GPU Coprocessor Execution: When a source file is marked with "forceGpu": true, Tidepod compiles it with the GPU target flags, outputs a binary blob, and embeds it as a ROM resource. It also generates a companion header (e.g. gpu_map.h) containing the VRAM load address and entry points. At runtime, the host CPU copies this code into VRAM and signals the F18A GPU to execute asynchronously.

The same placement can be requested from inside a C file with #pragma bank persistent, #pragma bank scratchpad or #pragma bank gpu (plus #pragma gpu base / #pragma gpu stack). The pragmas are read when the project is synced.

Editing by hand

You can edit the .project file in any editor. Run tidepod sync afterwards so the Makefile and layout.xml are regenerated from it.

Docs / Getting Started

The Tidepod IDE

Reference

The IDE combines a code editor, the build pipeline, an integrated emulator and a source-level debugger in one window. Start it from the terminal with tidepod (empty workspace) or tidepod path/to/name.project. It runs the exact same make and emulator core as the command line, ensuring your code builds and runs identically in both environments.

The Tidepod IDE with a project open, showing editor, emulator and sidebar.
The Tidepod IDE with a project open, showing editor, emulator and sidebar.

Window layout

AreaWhat it does
Sidebar (left)Three view tabs:
  • Files — Workspace directory tree. Double-click any source file to open it in an editor tab; double-click bank_report.json to open the interactive graphical bank report viewer.
  • Git — Track repository status, view diffs and commit changes.
  • Docs — Built-in manual page reference library. Double-click any entry to view the man page in an editor tab.
Toggle the sidebar with View → Toggle Explorer.
Editor (centre)Tabbed source editor featuring syntax highlighting for C, TMS9900 assembly and Extended BASIC; multi-cursor editing; and gutter breakpoint toggling. Man pages open in read-only tabs.
EmulatorThe running TI-99/4A emulator panel. Click directly inside the display area to capture keyboard and joystick input; click back into the editor to return focus to coding. Toggle with View → Toggle Emulator or the toolbar button.
Debug panelActive during debugging sessions with eight specialised tabs:
  • CPU — Active workspaces (WP, PC, ST), registers R0–R15, and RAM hex inspect.
  • VDP — Standard registers VR0–VR7 (plus enhanced F18A/Pico registers VR0–VR57) and VRAM inspector.
  • ASM — Live TMS9900 disassembly synchronized to the current Program Counter.
  • BRK — Breakpoint list manager (__dbg_printf logpoints appear in the Debug Log).
  • WCH — Watch expressions with struct field expansion.
  • GFX — Visual inspection of Pattern Tables, Sprite Attribute Tables, and Color Tables.
  • DSK — Floppy and hard disk mounts, catalog inspection, and the New Disk creation tool.
  • PRF — Function-level execution profiler and cycle counts.
Bottom panelThree bottom tabs:
  • Build Log — Output from compiler, banker, and linker passes with clickable error diagnostics.
  • Debug Log — Runtime debugger events, cartridge trap notifications, and logpoint prints.
  • Search — Project-wide search results.
Toggle with View → Toggle Output.
The debug panel tabs: CPU, VDP, ASM, BRK, WCH, GFX, DSK and PRF.
The debug panel tabs: CPU, VDP, ASM, BRK, WCH, GFX, DSK and PRF.

Toolbars

The IDE divides quick actions between two toolbars:

  • Top Toolbar:
    • Debug (Bug) — Start a debug session (F5; builds with debug info and attaches the debugger).
    • Stop — Terminate the active debug session.
    • Toggle Emulator Panel — Show or hide the embedded emulator and debugger pane.
    • Build Project (Wrench) — Compile and link the active project (F7).
    • Build & Run (Play) — Compile and launch the program in the emulator (Mod+R).
    • Clean Workspace (Broom) — Remove build artifacts and regenerated headers (Mod+Shift+K).
    • Fullscreen & Volume — Toggle full-screen workspace and adjust emulator audio volume.
  • Emulator / Debugger Toolbar (below the CRT display):
    • Pause / Resume — Halt or continue execution in the emulator (F6).
    • Step Line / Step Over — Source-level C/XB step into (F11) and step over (F10).
    • Step Inst / Step OvInst — Assembly instruction-level step into (Shift+F11) and step over (Shift+F10).
    • Load Cartridge — Open an external .rpk or .bin cartridge image directly in the emulator.
    • Disk Drive Controller (Floppy icon) — Configure per-project PEB: controller, VDP: type, DSK1:–DSK3: floppy images, and HARD1:–HARD3: hard disk images.

Menus

  • File — New / Open / Save / Save As / Close Tab; Save Snapshot… / Load Snapshot… (emulator state); New / Open / Save / Close Project; Project Settings…; Preferences….
  • Edit — Undo, Redo, Cut, Copy, Paste, Select All, Find…, Find in Project…, Replace…, Replace in Project….
  • View — Toggle Explorer, Toggle Output, Toggle Emulator.
  • Build — Build, Run, Debug, Clean Workspace.

Default keyboard shortcuts

Mod is Cmd on macOS and Ctrl on Linux and Windows. All shortcuts can be rebound in Preferences.

ActionShortcut
Build (release)F7
Build & RunMod+R
Build & Debug (debug build, debugger attached)F5
Pause / continueF6
CleanMod+Shift+K
Step over / step into (source line)F10 / F11
Step over / step into (assembly instruction: Step OvInst / Step Inst)Shift+F10 / Shift+F11
Save fileMod+S
New / open fileMod+N / Mod+O
New / open projectCmd+Shift+N / Cmd+Shift+O (macOS); Ctrl+N / Ctrl+O (Linux/Windows)
Find / find in projectMod+F / Mod+Shift+F
Next / previous resultMod+G / Mod+Shift+G
Replace / replace in projectMod+Alt+F / Mod+Alt+Shift+F (Option on macOS)
Build onlyF7 (also Cmd+B on macOS)
Undo / redoMod+Z / Mod+Shift+Z
Add cursor above / belowmacOS Ctrl+Shift+↑/↓; others Ctrl+Alt+↑/↓
Select next occurrenceMod+D

Project Settings

File → Project Settings… opens the configuration dialog editing the .project file: project type (banked, 8k, ea5, xb, custom), cartridge menu label, optimization levels for release and debug, scratchpad preset (Scratchpad Base:), banker packing algorithm, include and library paths, and custom compiler/linker flags. Saving regenerates the Makefile automatically.

Project Settings modal dialog.
Project Settings modal dialog.

Disks and emulator settings

The Disk Drive Controller dialog (floppy icon on the emulator toolbar) and the DSK tab mount floppy (.dsk) and hard-disk (.hd) images to DSK1–3 and HARD1–3, and select the per-project PEB configuration (Inherit, None, TI Controller, HFDC, WHT SCSI) and VDP override. Project-specific mounts are saved directly into the .project file. Global machine defaults (default VDP engine, global PEB configuration) live in File → Preferences…. See Disks & peripherals.

Preferences dialog modal.
Preferences dialog modal.

Session restore

The IDE remembers the active project, open file tabs, window layout, and panel visibility, restoring them automatically on the next launch.

Chapter 2

Tutorials

Docs / Tutorials

Tutorial 1: Hello, text mode

Beginner

This first tutorial builds a cartridge that prints text, draws a box with line-drawing characters and echoes key presses. You'll use the console I/O functions from stdio.h and conio.h. No hardware programming is needed: the C library handles the screen and keyboard for you.

The finished program after pressing H, I and Q (stock TMS9918A, 40 columns).
The finished program after pressing H, I and Q (stock TMS9918A, 40 columns).

What you'll learn

  • Creating, building and running a project from the command line or the IDE.
  • Switching to text mode and loading the built-in font.
  • Printing with printf, positioning with gotoxy and drawing boxes.
  • Reading keys with cgetc.

Step 1: Create the project

Terminal
tidepod new hello
cd hello

tidepod new creates a folder hello/ with a project file (hello.project), a starter main.c, a generated Makefile and an empty Makefile.custom for your own rules. Without --type you get a banked cartridge, which can grow as big as you need. See Projects for the other types.

In the IDE: Choose File → New Project… (Cmd+Shift+N on macOS, Ctrl+N on Linux/Windows), enter Project Name: hello, ensure Project Type: is set to C Banked Cartridge - 32K, and click Create. The starter main.c opens directly in the central editor tab, with project files listed in the Files sidebar.

Step 2: Write the program

Replace the contents of main.c with:

main.c
#include <stdio.h>
#include <conio.h>

int main(void) {
  unsigned char width, height;
  int count = 0;

  ti_text_mode(40);
  ti_text_load_builtin_font();
  bgcolor(4);
  textcolor(15);
  clrscr();
  screensize(&width, &height);

  printf("Hello from Tidepod!\n");
  printf("The screen is %u x %u characters.\n", width, height);

  cputcxy(0, 3, CH_ULCORNER);
  chlinexy(1, 3, width - 2);
  cputcxy(width - 1, 3, CH_URCORNER);
  cvlinexy(0, 4, 3);
  cvlinexy(width - 1, 4, 3);
  cputcxy(0, 7, CH_LLCORNER);
  chlinexy(1, 7, width - 2);
  cputcxy(width - 1, 7, CH_LRCORNER);

  cputsxy(2, 4, "Press some keys. Q stops.");

  for (;;) {
    unsigned char key = cgetc();
    count++;
    gotoxy(2, 6);
    cprintf("Key %3d: code %3u '%c'", count, key, key);
    if (key == 'Q' || key == 'q') {
      break;
    }
  }

  cputsxy(2, 9, "Bye!");
  return 0;
}

Line by line

Lines 1–2
stdio.h declares printf and the screen set-up functions ti_text_mode and ti_text_load_builtin_font. conio.h declares the console functions: cursor positioning, colours, box drawing, and cgetc for the keyboard. It also defines the line-drawing character codes (CH_ULCORNER and friends).
Line 4
main is called by the Tidepod start-up code once memory is set up. Interrupts are disabled when main starts and stay disabled unless you enable them yourself.
Lines 5–6
Local variables: the screen size (filled in on line 13) and a counter for key presses. Locals live on the stack in the 32K memory expansion.
Line 8
ti_text_mode(40) switches the video chip to 40-column text mode and resets the cursor to the top-left. It puts the screen (the name table) at VRAM 0x0000 and the character patterns at 0x1000. Ask for 80 and you get 80 columns on an F18A, or 40 columns on a stock video chip.
Line 9
ti_text_mode doesn't load any character shapes, so without this line the screen would show blank or garbage characters. ti_text_load_builtin_font() copies Tidepod's 5×8 font (all 256 codes, including the box-drawing characters) to 0x1000. It is only linked into your cartridge if you call it. To use your own font instead, copy it to 0x1000 with rom_to_vram (see Tutorial 3).
Lines 10–11
Set the background to colour 4 (dark blue) and the text to colour 15 (white). Colours are the 16 standard TMS9918A palette indices. On an F18A, ti_text_mode loads an EGA-style palette, so the same numbers look different there (compare the two screenshots below).
Line 12
clrscr() fills the screen with spaces and moves the cursor to (0, 0).
Line 13
screensize stores the current width and height in characters. Using it instead of hard-coding 40 is what lets the same program draw a correct box in 80-column mode.
Lines 15–16
printf writes at the cursor position and \n moves to the start of the next line, just like on a PC. %u prints an unsigned number. Text output goes straight to video memory; there is no buffering.
Lines 18–25
Draw a box from row 3 to row 7, the full width of the screen. cputcxy(x, y, c) puts one character at a position; chlinexy(x, y, len) draws a horizontal line and cvlinexy(x, y, len) a vertical one. The corners use the CH_…CORNER constants. All console coordinates are (column, row), starting at 0.
Line 27
cputsxy prints a string at a position, inside the box.
Lines 29–31
An endless loop. cgetc() waits for a key press and returns its character code. The console starts with Alpha Lock on, so letters normally arrive as upper case.
Lines 32–33
gotoxy(2, 6) moves the cursor and cprintf prints formatted text there. Because the fields have fixed widths (%3d, %3u), each new line overwrites the previous one exactly.
Lines 34–36
Leave the loop on Q. Both cases are checked in case Alpha Lock is off.
Lines 39–41
Print a goodbye and return. A cartridge has nowhere to return to: when main returns, the runtime simply loops forever, so the screen stays as it is. To start over, reset the emulator.

Step 3: Build and run

Terminal
make
tidepod run

make compiles main.c, packs the code into banks and writes hello.rpk. tidepod run starts the stand-alone emulator with that cartridge and passes --autorun, launching directly into your program (bypassing the TI title screen and cartridge menu; run ti994a-emu --cart hello.rpk without --autorun if you want to see the console title screen and select HELLO manually).

In the IDE: Click the Build & Run (Play) button in the top toolbar or press Mod+R (or press F7 to compile only). The Build Log panel at the bottom confirms compiler progress, and the cartridge boots instantly inside the integrated Emulator panel on the right. Click directly inside the emulator window to capture keyboard input and type keys into the program. Press F6 to pause or resume execution at any time.

The hello project in the IDE, running in the built-in emulator.
The hello project in the IDE, running in the built-in emulator.

Try it: 80 columns

Change line 8 to ti_text_mode(80);, rebuild, and run the emulator with an F18A:

Terminal
make
ti994a-emu --f18a --cart hello.rpk

The box now spans 80 columns because the code uses screensize. On a stock console the same cartridge falls back to 40 columns. To always run this project with an F18A from the command line, add "emu": { "vdp": "tidepod-f18a" } to hello.project (see The emulator).

In the IDE: Click the Disk Drive Controller button (floppy disk icon on the emulator/debugger toolbar below the CRT display) and set VDP: to F18A (or pico-f18a) for this project—or change the global default in File → Preferences… (Emulator tab → VDP Type:)—then press Mod+R. The emulator launches directly into high-resolution 80-column mode.

ti_text_mode(40) on a stock TMS9918A.
ti_text_mode(40) on a stock TMS9918A.
ti_text_mode(80) on an F18A. The border shows the backdrop colour from the F18A palette.
ti_text_mode(80) on an F18A. The border shows the backdrop colour from the F18A palette.
Next

The console functions are the easiest way to show text. For games you usually program the video chip directly: Tutorial 2 sets up graphics mode, a sprite, the joystick and sound.

Docs / Tutorials

Tutorial 2: Sprites, joystick and sound

Beginner

Games usually skip the console library and talk to the video chip directly. In this tutorial you set up graphics mode yourself, move a sprite with joystick 1 and beep when fire is pressed. Everything here is plain C plus one small piece of inline assembly. The program uses a handful of tiny helper functions that you can copy into your own projects.

The ball sprite after moving right and up. The bottom line shows its position.
The ball sprite after moving right and up. The bottom line shows its position.

What you'll learn

  • Writing video chip (VDP) registers and video memory (VRAM) from C.
  • Where graphics mode keeps its tables, and how to use the built-in font outside text mode.
  • Defining and moving a sprite, in sync with the screen refresh.
  • Reading the joystick with inline assembly, and making a sound.

Step 1: Create the project

Terminal
tidepod new sprites
cd sprites

In the IDE: Select File → New Project… (Cmd+Shift+N on macOS, Ctrl+N on Linux/Windows), set Project Name: to sprites, leave Project Type: as C Banked Cartridge - 32K, and click Create.

Step 2: Write the program

Replace main.c with the listing below. The walkthrough after it covers every line.

main.c
#include <stdio.h>

/* Memory-mapped I/O ports */
#define VDP_DATA   (*(volatile unsigned char *)0x8C00)
#define VDP_ADDR   (*(volatile unsigned char *)0x8C02)
#define VDP_STATUS (*(volatile unsigned char *)0x8802)
#define SOUND      (*(volatile unsigned char *)0x8400)

/* Where the VDP tables live in video RAM */
#define NAME_TABLE   0x0000
#define COLOR_TABLE  0x0300
#define SPRITE_ATTRS 0x0380
#define SPRITE_PATS  0x0800
#define PATTERNS     0x1000

/* Joystick bits returned by read_joystick1() */
#define JOY_FIRE  0x01
#define JOY_LEFT  0x02
#define JOY_RIGHT 0x04
#define JOY_DOWN  0x08
#define JOY_UP    0x10

static void vdp_reg(unsigned char reg, unsigned char value) {
  VDP_ADDR = value;
  VDP_ADDR = 0x80 | reg;
}

static void vdp_write_at(unsigned int addr) {
  VDP_ADDR = addr & 0xFF;
  VDP_ADDR = 0x40 | (addr >> 8);
}

static void vdp_fill(unsigned int addr, unsigned char value, unsigned int count) {
  vdp_write_at(addr);
  while (count--) {
    VDP_DATA = value;
  }
}

static void vdp_copy(unsigned int addr, const unsigned char *src, unsigned int count) {
  vdp_write_at(addr);
  while (count--) {
    VDP_DATA = *src++;
  }
}

static void vdp_print(int col, int row, const char *s) {
  vdp_write_at(NAME_TABLE + row * 32 + col);
  while (*s) {
    VDP_DATA = *s++;
  }
}

static void wait_vblank(void) {
  while (!(VDP_STATUS & 0x80)) {
  }
}

static unsigned char read_joystick1(void) {
  register unsigned int column __asm__("r2") = 0x0600;
  register unsigned int rows __asm__("r1");
  __asm__ __volatile__("li r12,>0024\n\t"
                       "ldcr r2,3\n\t"
                       "src r12,7\n\t"
                       "li r12,>0006\n\t"
                       "clr r1\n\t"
                       "stcr r1,8"
                       : "=r"(rows)
                       : "r"(column)
                       : "r12");
  return (unsigned char)(~rows >> 8);
}

static void sound_off(void) {
  SOUND = 0x9F;
  SOUND = 0xBF;
  SOUND = 0xDF;
  SOUND = 0xFF;
}

static void beep_on(unsigned int period) {
  SOUND = 0x80 | (period & 0x0F);
  SOUND = (period >> 4) & 0x3F;
  SOUND = 0x90;
}

static const unsigned char ball[8] = {
  0x3C, 0x7E, 0xFF, 0xFF, 0xFF, 0xFF, 0x7E, 0x3C
};

int main(void) {
  unsigned char x = 120, y = 88;
  unsigned char beep_frames = 0;
  char line[33];

  sound_off();

  vdp_reg(1, 0x80);
  vdp_reg(0, 0x00);
  vdp_reg(2, NAME_TABLE / 0x400);
  vdp_reg(3, COLOR_TABLE / 0x40);
  vdp_reg(4, PATTERNS / 0x800);
  vdp_reg(5, SPRITE_ATTRS / 0x80);
  vdp_reg(6, SPRITE_PATS / 0x800);
  vdp_reg(7, 0x04);

  ti_text_load_builtin_font();
  vdp_fill(NAME_TABLE, ' ', 768);
  vdp_fill(COLOR_TABLE, 0xF0, 32);
  vdp_copy(SPRITE_PATS, ball, sizeof ball);
  vdp_fill(SPRITE_ATTRS, 0xD0, 1);

  vdp_print(1, 0, "JOYSTICK 1 MOVES, FIRE BEEPS");
  vdp_reg(1, 0xC1);

  for (;;) {
    unsigned char joy = read_joystick1();

    if ((joy & JOY_LEFT) && x > 0) x -= 2;
    if ((joy & JOY_RIGHT) && x < 240) x += 2;
    if ((joy & JOY_UP) && y > 8) y -= 2;
    if ((joy & JOY_DOWN) && y < 174) y += 2;

    if ((joy & JOY_FIRE) && beep_frames == 0) {
      beep_on(127);
      beep_frames = 8;
    }

    wait_vblank();

    vdp_write_at(SPRITE_ATTRS);
    VDP_DATA = y;
    VDP_DATA = x;
    VDP_DATA = 0;
    VDP_DATA = 0x0B;
    VDP_DATA = 0xD0;

    if (beep_frames > 0 && --beep_frames == 0) {
      sound_off();
    }

    snprintf(line, sizeof line, "X=%3u Y=%3u", x, y);
    vdp_print(1, 23, line);
  }
  return 0;
}

Line by line

Line 1
Only stdio.h is needed, for snprintf and ti_text_load_builtin_font.
Lines 3–7
The hardware is controlled through fixed memory addresses. Each macro turns an address into a byte variable you can read or write. volatile is essential: it tells the compiler that every access matters, so it won't drop or merge repeated writes. 0x8C00 writes VRAM data, 0x8C02 sets a VRAM address or a VDP register, 0x8802 reads the VDP status, and 0x8400 is the sound chip.
Lines 9–14
The VDP has 16 KB of its own memory (VRAM). In graphics mode it reads several tables from there; you choose where each table lives. This layout fits them all below 0x1800: the name table (768 bytes, one character code per screen cell, 32×24), the colour table (32 bytes, one colour pair per group of 8 characters), the sprite attribute table (4 bytes per sprite), the sprite patterns, and the character patterns (8 bytes per character). The character patterns are at 0x1000 on purpose: that's where ti_text_load_builtin_font puts the font.
Lines 16–21
Names for the bits returned by read_joystick1, so the main loop reads naturally.
Lines 23–26
vdp_reg writes a VDP register: first the value, then the register number with the top bit set (0x80), both to the address port.
Lines 28–31
vdp_write_at prepares a VRAM write: the low byte of the address, then the high byte with bit 0x40 set (meaning "write"). After this, every byte written to VDP_DATA goes to the next VRAM address automatically.
Lines 33–45
vdp_fill writes the same byte count times; vdp_copy copies a buffer from CPU memory to VRAM. Both rely on the auto-increment.
Lines 47–52
vdp_print writes a string into the name table. The screen is 32 cells wide, so cell (col, row) is at row * 32 + col. Each character code selects a pattern from the font.
Lines 54–57
wait_vblank waits until the VDP has finished drawing a frame. The top bit of the status register is set once per frame (60 times a second) and cleared when the status is read. Since interrupts are disabled, polling it is the simplest way to keep to a steady 60 frames per second, and updating sprites right after it avoids flicker.
Lines 59–72
Joystick 1 is read through the keyboard matrix, which is only reachable with the CPU's CRU instructions. C can't express those, so this uses GCC-style inline assembly. The two register … __asm__("rN") variables pin the C values to registers R2 and R1. li r12,>0024 and ldcr r2,3 select column 6 (joystick 1). src r12,7 is only a short delay. li r12,>0006 and stcr r1,8 read the eight row lines into the high byte of R1. The : "=r"(rows) : "r"(column) : "r12" part tells the compiler what goes in, what comes out, and that R12 is overwritten. A pressed direction reads as 0, so the result is inverted and shifted down: bit 0 is fire, then left, right, down and up.
Lines 74–79
sound_off sets the volume of all four sound channels (three tones and noise) to silent. The sound chip isn't reset when a cartridge starts, so it's good practice to do this first.
Lines 81–85
beep_on sets tone channel 1 to a 10-bit period (two bytes: low 4 bits, then high 6 bits) and its volume to maximum (0x90). A higher period gives a lower pitch; 127 is roughly 880 Hz.
Lines 87–89
The sprite's shape: 8 rows of 8 pixels, one byte per row, leftmost pixel in the top bit. const keeps it in cartridge ROM instead of copying it to RAM.
Lines 92–94
The sprite position (pixels; the screen is 256×192), a countdown for the beep, and a text buffer for the status line (32 characters plus the terminating zero).
Line 96
Silence the sound chip.
Lines 98–105
Program the VDP. Register 1 is written first with 0x80 (16 KB VRAM, display off) so nothing is shown while the tables are being filled. Register 0 = 0x00 selects graphics mode. Registers 2–6 hold the table addresses, each divided by its required alignment: that's why the code divides by 0x400, 0x40, 0x800, 0x80 and 0x800. Register 7 sets the backdrop colour (4, dark blue).
Line 107
Load the built-in font to 0x1000. It works in graphics mode too because the pattern table is there.
Lines 108–111
Clear the screen with spaces; give all characters white text on a transparent background (0xF0: high nibble foreground, low nibble background); copy the ball shape to sprite pattern 0; and write 0xD0 as the first sprite's Y position. 0xD0 means "no more sprites", which hides all sprites until the loop draws one.
Lines 113–114
Print the title, then turn the display on: 0xC1 is 16 KB, display on, 8×8 sprites, magnified to 16×16.
Lines 116–122
The game loop. Read the joystick once per frame and move 2 pixels in each pressed direction, staying on screen.
Lines 124–127
On fire, start a beep that lasts 8 frames. Checking beep_frames == 0 stops holding fire from restarting it every frame.
Line 129
Wait for the end of the frame.
Lines 131–136
Write sprite 0: Y, X, pattern number 0 and colour 0x0B (light yellow). The following 0xD0 ends the sprite list.
Lines 138–140
Count the beep down and silence it when it reaches zero.
Lines 142–143
Format the position with snprintf (which never writes past sizeof line) and print it on the last row.
Lines 145–146
Never reached; it keeps the compiler happy.

Step 3: Build and run

Terminal
make
tidepod run

In the emulator, joystick 1 is on the arrow keys, with Tab as fire.

In the IDE: Click the Run (Play) button on the toolbar or press Mod+R. Click the Emulator panel on the right to capture input focus. Use the arrow keys to move the ball sprite and press Tab to trigger the beep.

Live VDP Inspection: To inspect how the video chip manages tables in memory, start a debug session with F5 (or click the Debug (Bug) icon). In the debug panel, switch to the GFX tab to view pattern bitmaps, color assignments, and the live sprite attribute table (SAT). As you move the joystick, the X/Y coordinates in the SAT update in real time. Switch to the VDP tab to inspect the exact values in registers VR0 through VR7.

Why not use interrupts?

Tidepod starts main with interrupts disabled, and the C library doesn't need them. Polling the VDP status, as in wait_vblank, is the usual way to time a game loop.

Try it

  • Change vdp_reg(1, 0xC1) to 0xC0 to see the sprite at its real 8×8 size.
  • Add a second sprite: write 4 more bytes before the 0xD0.
  • Make the beep pitch depend on x.
Next

Drawing tiles by hand gets tedious. Tutorial 3 generates graphics with a script and lets the build pack them into the cartridge.

Docs / Tutorials

Tutorial 3: Graphics from a script (resources)

Beginner

Real games carry far more graphics than you'd want to type into C arrays. Tidepod treats any binary file you add to the project as a resource: the build packs it into the cartridge and gives you its location as #defines, and rom_to_vram copies it to video memory. In this tutorial a small Python script generates four tiles and a screen map, and a rule in Makefile.custom re-runs it when it changes.

The screen map: a brick border, a diagonal grid of boxes and a sine wave of diamonds.
The screen map: a brick border, a diagonal grid of boxes and a sine wave of diamonds.

What you'll learn

  • Adding binary .dat files to a project and reading resource_defs.h.
  • Copying resources to VRAM with rom_to_vram and unwrap.
  • Generating assets during the build with Makefile.custom.
  • How graphics-mode colours work per group of 8 characters.

Step 1: Create the project and the generator

Terminal
tidepod new assets
cd assets
mkdir tools

In the IDE: Choose File → New Project… (Cmd+Shift+N on macOS, Ctrl+N on Linux/Windows), set Project Name: to assets, leave Project Type: as C Banked Cartridge - 32K, and click Create. In the Files sidebar, right-click the project root, choose New Folder…, and name it tools. Right-click tools/, choose New File…, name it make_assets.py, and paste the script below.

Save this as tools/make_assets.py:

tools/make_assets.py
#!/usr/bin/env python3
"""Generate resources/tiles.dat and resources/screen.dat for Tutorial 3."""
import math
import os

os.makedirs("resources", exist_ok=True)

# Four 8x8 tiles, one byte per pixel row, most significant bit = leftmost pixel.
tiles = [
    [0x00] * 8,                                          # 0: empty
    [0xFF, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xFF],  # 1: hollow box
    [0xFE, 0xFE, 0xFE, 0x00, 0xEF, 0xEF, 0xEF, 0x00],  # 2: bricks
    [0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x7E, 0x3C, 0x18],  # 3: diamond
]
with open("resources/tiles.dat", "wb") as f:
    for tile in tiles:
        f.write(bytes(tile))

# A 32x24 screen map: brick border, diamonds on a sine wave inside.
screen = bytearray(32 * 24)
for row in range(24):
    for col in range(32):
        if row in (0, 23) or col in (0, 31):
            tile = 2
        elif row == 12 + round(6 * math.sin(col / 3)):
            tile = 3
        elif (row + col) % 8 == 0:
            tile = 1
        else:
            tile = 0
        screen[row * 32 + col] = 0x80 + tile * 8
with open("resources/screen.dat", "wb") as f:
    f.write(screen)
Lines 1–6
A plain Python 3 script with no dependencies. It runs from the project folder and makes sure resources/ exists.
Lines 8–17
Four tiles of 8 bytes each, written back to back: tiles.dat is 32 bytes. Each byte is one row of 8 pixels; a 1 bit is drawn in the foreground colour, a 0 bit in the background colour.
Lines 19–31
A 32×24 map, one byte per screen cell, exactly the layout of the VDP name table. Each byte is the character code to show. The tiles will be loaded as characters 0x80, 0x88, 0x90 and 0x98, so tile n is 0x80 + n * 8. The spacing of 8 is explained in the C code below.
Lines 32–33
Write the 768-byte map.

Step 2: Generate once, then add the resources

Terminal
python3 tools/make_assets.py
tidepod add resources/tiles.dat resources/screen.dat

tidepod add lists the files in assets.project and regenerates the Makefile. Any file that isn't C or assembly is treated as a binary resource. The resource name is the file name without its extension: tiles and screen.

In the IDE: Once the script has run and generated the files, expand the resources/ directory in the Files sidebar. Right-click tiles.dat and check Include in Build, then right-click screen.dat and check Include in Build. The IDE registers both as cartridge resources in assets.project.

Step 3: Rebuild the assets automatically

Add these lines to the end of Makefile.custom. Tidepod never overwrites this file, and the generated Makefile includes it.

Makefile.custom
resources/tiles.dat: tools/make_assets.py
	python3 tools/make_assets.py

resources/screen.dat: resources/tiles.dat

The first rule says: tiles.dat is out of date when the script is newer, and the script rebuilds it. The second says screen.dat comes along with tiles.dat (the script writes both). The recipe line must start with a tab. Now editing the script, or deleting the .dat files, makes the next make regenerate them before anything else.

In the IDE: Double-click Makefile.custom in the Files sidebar to open it in an editor tab, paste the rules above, and press Mod+S to save.

Why two rules?

GNU make 4.3 can say "one recipe makes both files" with &:, but macOS ships make 3.81, which doesn't support it. The two-rule form works everywhere.

Step 4: Write the program

Replace main.c with:

main.c
#include <resource_copy.h>
#include "resource_defs.h"

#define VDP_DATA (*(volatile unsigned char *)0x8C00)
#define VDP_ADDR (*(volatile unsigned char *)0x8C02)

#define NAME_TABLE   0x0000
#define COLOR_TABLE  0x0300
#define SPRITE_ATTRS 0x0380
#define PATTERNS     0x0800

#define FIRST_TILE 0x80
#define TILE_COUNT 4

static void vdp_reg(unsigned char reg, unsigned char value) {
  VDP_ADDR = value;
  VDP_ADDR = 0x80 | reg;
}

static void vdp_write_at(unsigned int addr) {
  VDP_ADDR = addr & 0xFF;
  VDP_ADDR = 0x40 | (addr >> 8);
}

/* Foreground (high nibble) and background (low nibble) per tile. */
static const unsigned char tile_colors[TILE_COUNT] = { 0x11, 0x41, 0x96, 0xB1 };

int main(void) {
  unsigned int i;

  vdp_reg(1, 0x80);
  vdp_reg(0, 0x00);
  vdp_reg(2, NAME_TABLE / 0x400);
  vdp_reg(3, COLOR_TABLE / 0x40);
  vdp_reg(4, PATTERNS / 0x800);
  vdp_reg(5, SPRITE_ATTRS / 0x80);
  vdp_reg(7, 0x01);

  vdp_write_at(SPRITE_ATTRS);
  VDP_DATA = 0xD0;

  for (i = 0; i < TILE_COUNT; i++) {
    unsigned int ch = FIRST_TILE + i * 8;
    rom_to_vram(tiles_bank, tiles_offset + i * 8, 8, PATTERNS + ch * 8);
    vdp_write_at(COLOR_TABLE + ch / 8);
    VDP_DATA = tile_colors[i];
  }

  rom_to_vram(unwrap(screen), NAME_TABLE);

  vdp_reg(1, 0xC0);
  for (;;) {
  }
  return 0;
}

Line by line

Line 1
resource_copy.h declares rom_to_vram (and rom_to_ram) and the unwrap macro.
Line 2
include/resource_defs.h is generated by the build. For each resource it defines a bank, an offset and a length. For this project it contains:
#define tiles_bank   0
#define tiles_offset 0
#define tiles_length 32
#define screen_bank   0
#define screen_offset 32
#define screen_length 768
The numbers change as you add resources, which is why you always use the names.
Lines 4–23
The same VDP port macros and helpers as in Tutorial 2. This time the character patterns are at 0x0800, because this program doesn't use the built-in font.
Lines 12–13
The tiles become characters starting at 0x80, well away from the letters and digits.
Lines 25–26
One colour byte per tile: black on black for the empty tile, dark blue boxes, light red bricks on dark red, and light yellow diamonds. In graphics mode each colour-table byte covers a group of 8 consecutive characters. That's why the tiles are 8 character codes apart: each tile gets a group, and therefore a colour, of its own.
Lines 31–37
Display off, graphics mode, table addresses, and a black backdrop (register 7 = 1). Register 6 (sprite patterns) isn't needed because there are no sprites.
Lines 39–40
Write 0xD0 as the first sprite's Y so no stray sprites show up.
Lines 42–47
For each tile: work out its character code, copy its 8 bytes from the cartridge to that character's pattern (PATTERNS + ch * 8), and write its colour to the group's colour-table byte (COLOR_TABLE + ch / 8). The four rom_to_vram arguments are the source bank, the offset within it, the length and the VRAM destination. Copying part of a resource is just a matter of adding to the offset.
Line 49
unwrap(screen) expands to screen_bank, screen_offset, screen_length, so this copies the whole map into the name table in one call.
Lines 51–54
Turn the display on and stay here. The picture is now entirely in VRAM; the CPU has nothing left to do.

Step 5: Build and run

Terminal
make
tidepod run

One make is enough. The build first assigns resource locations and writes resource_defs.h (the [RES] line), then compiles main.c against it:

make (excerpt)
python3 tools/make_assets.py
  [RES] 2 resources (0 KB, 1 banks)
  [BK] Running tms9900-banker ...
  [BK] Bank packing complete: 1 bank(s), 0 trampoline(s) generated
  [LD] assets.bin
  [PAD] assets.bin padded to 8KB
  [ZP] assets.rpk

Change a tile in the script, run make again, and the new graphics appear. See Resources for how resources are placed and for using them from banked code.

In the IDE: Press Mod+R (or click Run (Play)). The IDE executes make, which invokes tools/make_assets.py if the assets are missing or modified, packs the newly generated tiles into ROM bank 0, and runs the cartridge in the embedded Emulator panel.

Next

Tutorial 4 splits a program over several files and looks at where the packer puts your code.

Docs / Tutorials

Tutorial 4: Multiple source files and code placement

Intermediate

As a program grows you'll split it over several files. On a banked cartridge that raises a question that doesn't exist on a PC: where does each piece of code end up? This tutorial builds a small game skeleton (title screen, play, game over) as a state machine in three files, shows when code has to be placed in RAM, and how to check what the packer did.

The title state, showing the best score so far.
The title state, showing the best score so far.
The play state after a few keys, followed by game over.
The play state after a few keys, followed by game over.

What you'll learn

  • Organising sources in a src/ folder with a shared header.
  • Why code called through function pointers must be persistent, and how to mark it.
  • How the packer promotes frequently called code to RAM on its own.
  • Reading bank_report.json.

Step 1: Set up the project

Terminal
tidepod new multi
cd multi
rm main.c
tidepod remove main.c
mkdir src

The starter main.c is removed from disk and from the project. Create the four files below, then add the three C files:

Terminal
tidepod add src/main.c src/states.c src/score.c

Headers aren't listed in the project. game.h sits next to the C files that include it, so #include "game.h" finds it.

In the IDE: Choose File → New Project… (Cmd+Shift+N on macOS, Ctrl+N on Linux/Windows), set Project Name: to multi, leave Project Type: as C Banked Cartridge - 32K, and click Create. In the Files sidebar, right-click the root main.c and select Delete. Right-click the project folder, select New Folder…, and name it src. Create the four files inside src/. Then right-click src/main.c, src/states.c, and src/score.c and check Include in Build.

To mark a file persistent without using a source code pragma, right-click src/states.c in the Files sidebar and check Force Persistent. The IDE sets "forcePersistent": true in multi.project and regenerates the Makefile flags.

The shared header

src/game.h
#ifndef GAME_H
#define GAME_H

enum state { STATE_TITLE, STATE_PLAY, STATE_OVER, STATE_COUNT };

typedef enum state (*state_fn)(void);

/* states.c (persistent RAM) */
extern const state_fn state_table[STATE_COUNT];

/* score.c (banked) */
void score_reset(void);
void score_add(unsigned int points);
unsigned int score_get(void);
unsigned int score_best(void);

#endif
Lines 1–2, 17
The usual include guard.
Line 4
One value per screen of the game. STATE_COUNT is not a state; it's the number of states, used to size the table.
Line 6
state_fn is a pointer to a function that takes nothing and returns the next state. Each state runs until something happens, then says where to go next.
Lines 8–9
The table of state functions, defined in states.c.
Lines 11–15
A small score module. The rest of the program only uses these four functions, never the variables behind them.

The score module

src/score.c
#include "game.h"

static unsigned int score;
static unsigned int best;

void score_reset(void) {
  score = 0;
}

void score_add(unsigned int points) {
  score += points;
  if (score > best) {
    best = score;
  }
}

unsigned int score_get(void) {
  return score;
}

unsigned int score_best(void) {
  return best;
}
Lines 3–4
static keeps the variables private to this file. Like all globals they live in RAM (in .bss), and the start-up code sets them to zero, so best starts at 0.
Lines 6–23
Reset, add (keeping the best score up to date), and two getters. There's nothing special here: ordinary functions in an ordinary C file, which the packer is free to place wherever it likes.

The states

src/states.c
/* Called through function pointers, so it must live in RAM. */
#pragma bank persistent

#include <stdio.h>
#include <conio.h>
#include "game.h"

static enum state title(void) {
  clrscr();
  printf("TUTORIAL 4: STATES\n\n");
  printf("Best score: %u\n\n", score_best());
  printf("Press any key to play.\n");
  cgetc();
  score_reset();
  return STATE_PLAY;
}

static enum state play(void) {
  unsigned char key;

  clrscr();
  printf("Press keys to score points.\n");
  printf("Digits are worth their value.\n");
  printf("Press X to end the game.\n");
  for (;;) {
    gotoxy(0, 5);
    cprintf("Score: %5u", score_get());
    key = cgetc();
    if (key == 'X') {
      return STATE_OVER;
    }
    if (key >= '0' && key <= '9') {
      score_add(key - '0');
    } else {
      score_add(1);
    }
  }
}

static enum state over(void) {
  gotoxy(0, 8);
  cprintf("Game over! You scored %u.", score_get());
  gotoxy(0, 10);
  cprintf("Press any key.");
  cgetc();
  return STATE_TITLE;
}

const state_fn state_table[STATE_COUNT] = { title, play, over };
Lines 1–2
#pragma bank persistent puts this whole file in persistent RAM: it's copied from the cartridge to the 32K expansion at start-up and is always reachable.

Why it matters: a banked cartridge only shows one 8 KB bank at a time. When you call a banked function by name, the packer knows the target and inserts a small trampoline that switches to the right bank. A call through a function pointer has no name, so no trampoline can be inserted; the CPU would jump into whatever bank happens to be visible. Code in RAM doesn't have that problem.

The pragma must come before the first line of code (comments are fine). Tidepod reads it when it generates the Makefile and compiles the file with -mpersistent; you'll see src/states.o: CCFLAGS += -mpersistent in the Makefile. The command-line alternative is tidepod add src/states.c --persistent.
Lines 4–6
Console I/O (see Tutorial 1) and the shared header.
Lines 8–16
The title state: clear the screen, show the best score, wait for a key, reset the score and move on to STATE_PLAY. static hides the function from other files; they reach it through the table.
Lines 18–38
The play state: print the rules, then loop. Each turn redraws the score in a fixed-width field and waits for a key. X ends the game. Digits add their value (key - '0' turns '7' into 7) and any other key adds 1. Letters arrive in upper case because Alpha Lock is on by default.
Lines 40–47
Game over: print the result below the score, wait for a key, back to the title.
Line 49
The table, in the same order as enum state. It's const, so it holds only addresses of functions that are in RAM.

The main loop

src/main.c
#include <stdio.h>
#include "game.h"

int main(void) {
  enum state current = STATE_TITLE;

  ti_text_mode(40);
  ti_text_load_builtin_font();

  for (;;) {
    current = state_table[current]();
  }
}
Lines 5–8
Start at the title, in 40-column text mode with the built-in font.
Lines 10–12
The whole state machine: call the function for the current state and store whatever it returns. Adding a state means adding an enum value, a function and a table entry; this loop never changes.

Step 2: Build and run

Terminal
make
tidepod run

In the IDE: Click the Run (Play) button on the toolbar or press Mod+R. If you edit game.h, choose Build → Clean Workspace (Mod+Shift+K) before rebuilding to ensure every file including the header re-compiles.

Changing a header

The generated Makefile doesn't yet know which C files include game.h. After changing a header, rebuild everything with make clean && make.

Step 3: Where did the code go?

Every build writes bank_report.json. In the terminal, list every placed unit with its bank, classification, size and "hotness":

Terminal
jq -r '.banks[] | .bank_id as $b | .items[] | "\($b)\t\(.classification)\t\(.filename)\t\(.size)\t\(.hotness)"' bank_report.json
Output (excerpt)
0	pinned	.cart_header.o	46	0
0	pinned	crt0_banked.o	130	1
0	persistent	main.o	38	1
0	persistent	states.o	486	0
0	persistent	score.o	40	5
0	persistent	console_vdp.o	194	52
0	persistent	printf_core.o	1546	11
0	persistent	keyboard.o	810	4
...
0	persistent_high	ti_text_builtin_font.o	1358	1
1	persistent_high	ti_text_builtin_font.o	716	1

states.o is persistent, as requested. But so are main.o, score.o and most of the C library, even though nothing asked for that. This is the packer's persistent promotion:

  • After placing the code you marked, the packer ranks the remaining units by hotness: how many call sites in the program refer to them.
  • Starting with the hottest, it moves units into the persistent region while they fit, then into high RAM (persistent_high).
  • Whatever is left goes into banks.

Code in RAM needs no trampolines, so small programs often end up with none at all. Check the summary and the free space per region:

Terminal
jq -c '.summary, .regions' bank_report.json
Output
{"total_banks":2,"total_trampolines":0}
{"persistent_lower":{"capacity":7936,"used":6366,"free":1570},"persistent_high":{"capacity":24576,"used":2214,"free":22362}}

To see the decisions as they're made, build with the packer in verbose mode and look for "Phase 2.5":

Terminal
make clean
make PACKER_EXTRA_FLAGS=-v
Output (excerpt)
--- Phase 2.5: Profile-Guided Persistent Promotion ---
  Persistent space currently used: 1854 / 7660 bytes
  auto-promoted 'console_vdp.o' to persistent (hotness: 52, size: 194)
  auto-promoted 'console_attr.o' to persistent (hotness: 11, size: 540)
  auto-promoted 'printf_core.o' to persistent (hotness: 11, size: 1546)
  ...
  auto-promoted 'score.o' to persistent (hotness: 5, size: 40)
  ...
  auto-promoted 'ti_text_builtin_font.o' to persistent_high (hotness: 1, size: 2074)
Promotion is not a promise

Promotion depends on how much room is left, so code that's in RAM today can end up banked when the program grows. If code must be in RAM (function pointers, callbacks, interrupt handlers), mark it persistent yourself, as states.c does. See Code placement.

In the IDE: Visual Bank Report Viewer
You do not need command-line tools like jq in the IDE. In the Files sidebar, simply double-click bank_report.json. This opens the interactive graphical bank report viewer:

  • Memory Region Bars: Color-coded horizontal bar graphs show exact capacity and free headroom for ROM Bank 0, ROM Bank 1, Low Persistent RAM (persistent_lower), and High RAM (persistent_high).
  • Unit Manifest: Browse each placed object file with its byte size, assigned ROM bank or RAM address, and hotness score. Units marked with forcePersistent appear with a persistent badge, while auto-promoted units display an "auto-promoted" tag.
  • Call Graph and Trampolines: Hover over any unit to trace inbound and outbound function calls and see whether cross-bank trampolines were synthesized.
The same information in the IDE's bank report view.
The same information in the IDE's bank report view.

Try it

  • Add a STATE_PAUSE state that P switches to during play.
  • Remove the pragma, run tidepod sync and make, and check where states.o ends up. It may well still be in RAM thanks to promotion, but nothing guarantees it.
Next

Tutorial 5 runs C code on the F18A's own processor.

Docs / Tutorials

Tutorial 5: Running C on the F18A GPU

Intermediate

The F18A FPGA replacement (and compatible cores like the Pico9918) features an integrated, high-speed 16-bit coprocessor known as the GPU. While the console's primary TMS9900 CPU operates at 3.0 MHz and accesses video memory indirectly through bottlenecked 8-bit memory-mapped I/O ports (0x8C00/0x8C02), the F18A GPU executes instructions directly out of VRAM at up to 100 MHz. This architecture provides orders of magnitude higher bandwidth for graphical operations, procedural animation, tile manipulation, and physics routines, completely freeing the host CPU for game logic and audio playback.

Tidepod provides first-class support for compiling standard C code targeting the F18A GPU. The build pipeline compiles the GPU code in a freestanding environment, links it against the designated VRAM memory map, packages the resulting binary as a cartridge resource, and generates C symbol bindings (gpu_map.h) for the host program. In this tutorial, you will implement a true asymmetric dual-processor application: the GPU runs an autonomous loop in VRAM that rotates screen tiles and updates a hardware frame counter, while the host CPU detects the video chip, bootstraps the GPU, and polls the shared counter across the VDP bus.

With an F18A: the middle row is rotated by the GPU, and the frame counter is written by the GPU and printed by the CPU.
With an F18A: the middle row is rotated by the GPU, and the frame counter is written by the GPU and printed by the CPU.
The same cartridge on a stock TMS9918A.
The same cartridge on a stock TMS9918A.

What you'll learn

  • Adding a dedicated GPU translation unit with tidepod add --gpu and configuring memory anchors.
  • Architecting a shared VRAM layout between host TMS9900 code and coprocessor code via a shared header.
  • Runtime hardware detection with ti_vdp_detect(), unlocking enhanced registers via VR57, and starting the coprocessor.
  • Reading back coprocessor output across the VDP memory bus with zero CPU contention.

Step 1: Set up the project

Begin by initializing a clean project directory using the Tidepod command-line tool. Because this project contains two distinct executables—the cartridge ROM binary for the console and the VRAM binary for the GPU—we remove the default main.c and organize our sources into a structured layout:

Terminal
tidepod new gpudemo --menu "GPU DEMO"
cd gpudemo
rm main.c
tidepod remove main.c
mkdir -p src include

Next, register the GPU source file and host application with Tidepod. When adding a GPU source unit, you must supply the target VRAM load address and the stack pointer:

Terminal
tidepod add src/gpu.c --gpu --gpu-base 0x3000 --gpu-stack 0x3F00
tidepod add src/main.c

The --gpu flag instructs the build system that src/gpu.c is not destined for cartridge ROM banks. Instead, the toolchain compiles it with -ffreestanding -nostdlib -ffixed-r15 -Os, links it with crt0_gpu.o, and resolves all absolute pointers relative to 0x3000. The GPU's stack is anchored at 0x3F00 and grows downwards towards the code section. In your gpudemo.project manifest, Tidepod records this metadata under "forceGpu": true, "gpuBase": "0x3000", and "gpuStack": "0x3F00".

In the IDE: Choose File → New Project… (Cmd+Shift+N on macOS, Ctrl+N on Linux/Windows), enter Project Name: gpudemo, set Cart Menu Title: to GPU DEMO, leave Project Type: as C Banked Cartridge - 32K, and click Create. In the Files sidebar, delete the starter main.c, create src/ and include/ folders, and create the files.

To register and configure the GPU code without command-line flags: right-click src/gpu.c in the Files sidebar, check Include in Build, and select F18A GPU source. In the F18A GPU source dialog, enter VRAM base: 0x3000 and Stack top: 0x3F00 (you can adjust these later via Edit GPU base / stack…). Then right-click src/main.c and check Include in Build.

The shared VRAM layout

Because the host CPU and the F18A GPU communicate through video memory, both programs must strictly adhere to an identical memory layout. VRAM addresses must be partitioned to prevent display tables, tile patterns, and executable coprocessor code from overwriting each other:

include/shared.h
#ifndef SHARED_H
#define SHARED_H

/* VRAM layout shared by the host program and the GPU program. */
#define NAME_TABLE   0x0000
#define COLOR_TABLE  0x0300
#define SPRITE_ATTRS 0x0380
#define GPU_FRAMES   0x0400  /* 16-bit counter, written by the GPU */
#define PATTERNS     0x1000

#define SCROLL_ROW   (NAME_TABLE + 12 * 32)

#endif

In this partition, standard display tables occupy the bottom 8 KB of VRAM: the screen name table sits at 0x0000 (768 bytes), the color attribute table at 0x0300, sprite attributes at 0x0380, and font patterns at 0x1000. Notice GPU_FRAMES at offset 0x0400: this two-byte word serves as an inter-processor communication mailbox. The GPU increments this word once per video frame, and the host CPU reads it back to monitor coprocessor activity. Everything fits safely below 0x3000, ensuring complete isolation from the GPU executable image and stack.

The GPU program

src/gpu.c
#include <f18a_gpu.h>
#include "shared.h"

void main(void) __attribute__((noreturn));

void main(void) {
  volatile unsigned char *row = (volatile unsigned char *)SCROLL_ROW;
  unsigned int frames = 0;

  for (;;) {
    F18A_GPU_IDLE();

    frames++;
    F18A_GPU_MMIO16(GPU_FRAMES) = frames;

    if ((frames & 3) == 0) {
      unsigned char first = row[0];
      unsigned int i;
      for (i = 0; i < 31; i++) {
        row[i] = row[i + 1];
      }
      row[31] = first;
    }
  }
}
Lines 1–2
GPU programs can't use the C library; f18a_gpu.h provides the few helpers they need.
Lines 4–6
The GPU start-up code calls main, which must never return: there's nothing to return to. noreturn tells the compiler so.
Line 7
The GPU sees VRAM as its own memory, starting at address 0. So a plain pointer to SCROLL_ROW points straight at screen row 12. volatile makes sure every read and write really happens.
Line 11
F18A_GPU_IDLE() puts the GPU to sleep until its trigger fires. The main program sets the trigger to "once per frame", so this line paces the loop at 60 times a second.
Lines 13–14
Count the frame and store the count as a 16-bit word at GPU_FRAMES. F18A_GPU_MMIO16(addr) is a volatile word access to an address.
Lines 16–23
Every fourth frame, rotate the 32 characters of the row one place to the left: remember the first, shift the other 31, put the first at the end. The text appears to scroll, and the console CPU isn't involved at all.

The main program

src/main.c
#include <stdio.h>
#include <vdpinfo.h>
#include <f18a_gpu_host.h>
#include <resource_copy.h>
#include "resource_defs.h"
#include "gpu_map.h"
#include "shared.h"

#define VDP_DATA   (*(volatile unsigned char *)0x8C00)
#define VDP_ADDR   (*(volatile unsigned char *)0x8C02)
#define VDP_READ   (*(volatile unsigned char *)0x8800)
#define VDP_STATUS (*(volatile unsigned char *)0x8802)

static void vdp_reg(unsigned char reg, unsigned char value) {
  VDP_ADDR = value;
  VDP_ADDR = 0x80 | reg;
}

static void vdp_write_at(unsigned int addr) {
  VDP_ADDR = addr & 0xFF;
  VDP_ADDR = 0x40 | (addr >> 8);
}

static void vdp_fill(unsigned int addr, unsigned char value, unsigned int count) {
  vdp_write_at(addr);
  while (count--) {
    VDP_DATA = value;
  }
}

static void vdp_print(int col, int row, const char *s) {
  vdp_write_at(NAME_TABLE + row * 32 + col);
  while (*s) {
    VDP_DATA = *s++;
  }
}

static unsigned int vdp_read_word(unsigned int addr) {
  unsigned int value;
  VDP_ADDR = addr & 0xFF;
  VDP_ADDR = addr >> 8;
  value = VDP_READ << 8;
  value |= VDP_READ;
  return value;
}

static void wait_vblank(void) {
  while (!(VDP_STATUS & 0x80)) {
  }
}

int main(void) {
  char line[33];
  int chip = ti_vdp_detect();

  vdp_reg(1, 0x80);
  vdp_reg(0, 0x00);
  vdp_reg(2, NAME_TABLE / 0x400);
  vdp_reg(3, COLOR_TABLE / 0x40);
  vdp_reg(4, PATTERNS / 0x800);
  vdp_reg(5, SPRITE_ATTRS / 0x80);
  vdp_reg(7, 0x04);

  ti_text_load_builtin_font();
  vdp_fill(NAME_TABLE, ' ', 768);
  vdp_fill(COLOR_TABLE, 0xF0, 32);
  vdp_fill(SPRITE_ATTRS, 0xD0, 1);
  vdp_fill(GPU_FRAMES, 0, 2);

  if (chip == TI_VDP_STOCK) {
    vdp_print(2, 10, "NO F18A FOUND.");
    vdp_print(2, 12, "RUN THE EMULATOR WITH --f18a");
    vdp_reg(1, 0xC0);
    for (;;) {
    }
  }

  vdp_reg(57, 0x1C);
  vdp_reg(57, 0x1C);
  vdp_reg(30, 32);

  vdp_print(2, 2, "TUTORIAL 5: F18A GPU");
  vdp_print(0, 12, "  THIS ROW IS MOVED BY THE GPU  ");
  vdp_reg(1, 0xC0);

  rom_to_vram(unwrap(gpu), gpu_base);
  vdp_reg(50, 0x20);
  f18a_gpu_start(gpu_entry);

  for (;;) {
    wait_vblank();
    snprintf(line, sizeof line, "GPU FRAMES: %5u", vdp_read_word(GPU_FRAMES));
    vdp_print(2, 20, line);
  }
}
Lines 1–7
vdpinfo.h has ti_vdp_detect; f18a_gpu_host.h has f18a_gpu_start; resource_copy.h and resource_defs.h are as in Tutorial 3. gpu_map.h is generated from the GPU build and defines gpu_base, gpu_entry, gpu_stack and gpu_size. The GPU program is packed as a resource named gpu (after the file name), so resource_defs.h also has gpu_bank, gpu_offset and gpu_length.
Lines 9–36, 47–50
The VDP helpers from Tutorial 2, plus the VRAM read port 0x8800.
Lines 38–45
vdp_read_word reads two bytes from VRAM. Setting an address without the 0x40 bit prepares a read; each read from 0x8800 then returns the next byte. The GPU stored the counter high byte first, so the first byte read is the high byte.
Line 54
ti_vdp_detect() finds out which video chip is fitted: TI_VDP_STOCK, TI_VDP_F18A or TI_VDP_PICO9918. Do this first, before setting up the screen.
Lines 56–68
The same graphics-mode set-up as Tutorial 2, with the built-in font at 0x1000. The counter in VRAM is zeroed so the CPU never shows a stale value.
Lines 70–76
On a stock chip there is no GPU, so explain and stop. Writing F18A registers to a stock chip would scramble its normal registers, so this check has to come before any of the F18A code below.
Lines 78–80
The F18A's extra registers are locked at power-on. Writing 0x1C to register 57 twice unlocks them. Register 30 is then set to 32, the number of sprites allowed per scanline. Its reset value is 4, which would make sprites disappear unexpectedly in a real game.
Lines 82–84
Print a title and the row the GPU will scroll, then turn the display on.
Line 86
Copy the GPU program from the cartridge to VRAM 0x3000. It must go to the address it was built for, which is exactly what gpu_base holds.
Line 87
Register 50 bit 0x20 makes the GPU's IDLE wake up once per frame (at vertical sync). Without it, F18A_GPU_IDLE() would sleep forever.
Line 88
f18a_gpu_start sets the GPU's program counter to the entry point and starts it. From here on both processors run at the same time.
Lines 90–94
Once per frame, read the GPU's counter and print it on row 20. The CPU's only job is reporting.

Step 2: Build and run

Terminal
make
ti994a-emu --f18a --cart gpudemo.rpk

The build compiles the GPU program first ([GPU-CC], [GPU-LD], [GPU-BIN]), then the main program. Run it with tidepod run instead and you'll get whatever video chip Preferences selects; with a stock chip you'll see the "NO F18A FOUND" message. To make the F18A the default for this project from the command line, add "emu": { "vdp": "tidepod-f18a" } to gpudemo.project.

In the IDE: Configure the project to use the enhanced video processor by clicking the Disk Drive Controller button (floppy disk icon on the emulator/debugger toolbar below the CRT display) and setting VDP: to F18A (or pico-f18a)—or by setting the global default in File → Preferences… (Emulator tab → VDP Type:). Press Mod+R (or click Build & Run (Play)). The IDE compiles both the GPU freestanding binary and the host cartridge, starts the embedded emulator with F18A coprocessor support enabled, and begins real-time execution.

The generated include/gpu_map.h shows how small the GPU program is:

include/gpu_map.h (generated)
#define gpu_base  0x3000u
#define gpu_entry 0x3000u  /* _gpu_start */
#define gpu_stack 0x3F00u
#define gpu_size  64u

Understanding the Dual-Processor Architecture

Programming the F18A GPU requires thinking in terms of two asynchronous processors operating on a shared memory bus. The console's host CPU (TMS9900) executes from ROM and system RAM at 3.0 MHz, while the GPU executes directly from video RAM at 100 MHz. Unlike standard desktop multi-threading where cache coherency and mutexes are managed by an operating system, here you manage memory synchronization directly through VRAM and VDP hardware registers.

The host CPU communicates with VRAM through memory-mapped I/O ports at 0x8C00 (data write), 0x8C02 (address latch), and 0x8800 (data read). Every byte transferred across this interface requires setting up a 14-bit VRAM address pointer in the VDP and performing byte-wide read or write operations. In sharp contrast, the F18A GPU treats VRAM as its native flat address space from 0x0000 to 0x3FFF. A C pointer dereference such as *row = val translates into a single 16-bit memory store inside the VDP itself, completing in a single 100 MHz clock cycle. Because the F18A memory controller arbitrates access between the host port and the GPU core transparently during display scanlines, the two processors never crash or lock up each other's memory bus.

Hardware safety is maintained by the F18A's register lock mechanism. At console power-on, all registers beyond VR7 are locked to maintain strict backward compatibility with legacy TMS9918A games. Writing the magic sequence 0x1C twice to VDP Register 57 (VR57) unlocks the enhanced register file. Immediately following unlock, our host code sets VR30 to 32. On a stock TMS9918A, a scanline containing more than 4 sprites causes subsequent sprites to drop out (flicker). The F18A supports up to 32 active sprites per scanline; configuring VR30 unlocks this capacity for the entire frame.

Pacing the GPU is controlled through VDP Register 50. Setting bit 0x20 (decimal 32) instructs the F18A to issue an execution trigger at the start of each vertical blanking interval. When the GPU executes F18A_GPU_IDLE(), it suspends execution and consumes negligible internal bus bandwidth until the VSYNC pulse arrives. Once awakened, the GPU performs its row rotation and increments GPU_FRAMES in under a fraction of a millisecond, then immediately returns to the idle state. This hardware synchronization completely eliminates tearing and race conditions without requiring spinlocks or semaphores.

Try it

  • Scroll every frame instead of every fourth, or scroll the other way.
  • Let the CPU write a value into VRAM that the GPU reads, for example a scroll speed.
  • See resources/examples/f18a_bump in the Tidepod install for a GPU that draws pixels in bitmap mode.
Next

Tutorial 6 saves a game to disk.

Docs / Tutorials

Tutorial 6: Saving a game to disk

Intermediate

The C library's fopen, fread and fwrite work on TI disk files. In this tutorial the program keeps a small save game on DSK1: how many times it has run, a player name and a best score. You'll also create a blank disk image and tell the emulator to use it.

First run: there's no save file yet, so the program starts fresh and saves a score of 420.
First run: there's no save file yet, so the program starts fresh and saves a score of 420.
Second run: the save game is loaded back from the disk.
Second run: the save game is loaded back from the disk.

What you'll learn

  • Creating a disk image and mounting it from the project file.
  • Writing and reading a struct with fwrite and fread.
  • Telling "no file yet" apart from a real error with stdio_last_error.
  • Project settings for programs that use disks.
TI FDC vs HFDC missing-file codes

Opening a missing file returns NULL on both controllers (it must not hang). TI FDC reports stdio_last_error() == 2; HFDC reports 7 (STDIO_ERR_FILE). This tutorial uses the HFDC so the sample can treat “no save yet” as error 7. See docs/stdio_errors.md and stdio_last_error(3).

Step 1: Create the project and a blank disk

Terminal
tidepod new notes
cd notes
mkdir tools disks

From the command line, this script writes a blank 90 KB disk (single-sided, single density). Save it as tools/blank_dsk.py:

tools/blank_dsk.py
#!/usr/bin/env python3
"""Create a blank, formatted 90 KB (single-sided, single-density) TI disk image."""
import sys

SECTORS = 360
path = sys.argv[1]
name = (sys.argv[2] if len(sys.argv) > 2 else "BLANK").upper()

image = bytearray(SECTORS * 256)

vib = bytearray(256)
vib[0:10] = name.ljust(10)[:10].encode("ascii")  # disk name, space padded
vib[10:12] = SECTORS.to_bytes(2, "big")         # total sectors
vib[12] = 9                                      # sectors per track
vib[13:16] = b"DSK"                              # format marker
vib[16] = 0x20                                   # not protected
vib[17] = 40                                     # tracks per side
vib[18] = 1                                      # sides
vib[19] = 1                                      # density
vib[0x38] = 0x03                                 # bitmap: sectors 0 and 1 in use
for i in range(0x38 + SECTORS // 8, 256):
    vib[i] = 0xFF                                # sectors that don't exist

image[0:256] = vib
# Sector 1 (the file index) stays all zeros: no files.

with open(path, "wb") as f:
    f.write(image)
Lines 5–9
A disk image is just its sectors in order: 360 sectors of 256 bytes. The disk name comes from the command line.
Lines 11–19
Sector 0 describes the disk: its name, size and geometry, and the DSK marker that identifies a formatted disk.
Lines 20–22
From offset 0x38, one bit per sector says whether it's in use (lowest bit = lowest sector). Sectors 0 and 1 belong to the disk itself; bytes beyond the last sector are marked as used so nothing is ever allocated there.
Lines 24–28
Sector 1, the list of files, stays empty. Everything else is zeros too.
Terminal
python3 tools/blank_dsk.py disks/notes.dsk NOTES

In the IDE (no script required): Create the project via File → New Project… (Cmd+Shift+N on macOS, Ctrl+N on Linux/Windows) with Project Name: notes. Then switch to the DSK tab in the right-hand debug panel, select drive DSK1, and click New Disk. Choose a save path such as disks/notes.dsk in the file dialog: the IDE creates a formatted 90 KB (SSSD) disk image and immediately mounts it in DSK1.

Step 2: Configure the project

Open notes.project in an editor and add three entries after "libFiles" (mind the comma after the ]):

notes.project (excerpt)
  "libFiles": [],
  "dsk1": "disks/notes.dsk",
  "scratchpadBase": "0x8380",
  "emu": {
    "peb": "custom",
    "pebCards": [ { "type": "hfdc", "cru": 4352 } ]
  }
EntryWhy
dsk1The emulator mounts this image as DSK1 whenever it runs the project. The path is relative to the project folder.
scratchpadBaseThe disk system uses part of the console's scratchpad RAM. Starting Tidepod's scratchpad area at 0x8380 (the +disk access (0x8380) preset in Project Settings) keeps the two apart. See Code placement.
emuUse only an HFDC disk controller at CRU 0x1100 (4352) for this project, instead of the controllers set in Preferences. See The emulator.

Then regenerate the Makefile so it picks up the new scratchpad base:

Terminal
tidepod sync

In the IDE: Rather than editing JSON by hand, configure these options through the IDE dialogs:

  • Open File → Project Settings…, set Scratchpad Base: to +disk access (0x8380), and click Save.
  • Click the Disk Drive Controller button (floppy disk icon on the emulator/debugger toolbar below the CRT display). Set PEB: to HFDC (>1100), ensure disks/notes.dsk is mounted under DSK1:, and close the dialog. The IDE writes these settings directly to notes.project.

Step 3: Write the program

Replace main.c with:

main.c
#include <stdio.h>
#include <string.h>
#include <conio.h>

#define SAVE_FILE  "DSK1.SAVEGAME"
#define SAVE_MAGIC 0x5444

struct save_game {
  unsigned int magic;
  unsigned int runs;
  unsigned int best;
  char name[12];
};

static struct save_game save;

static int load_game(void) {
  FILE *f = fopen(SAVE_FILE, "rb");
  size_t got;

  if (f == NULL) {
    return 0;
  }
  got = fread(&save, sizeof save, 1, f);
  fclose(f);
  return got == 1 && save.magic == SAVE_MAGIC;
}

static int save_game(void) {
  FILE *f = fopen(SAVE_FILE, "wb");
  size_t put;

  if (f == NULL) {
    return 0;
  }
  put = fwrite(&save, sizeof save, 1, f);
  fclose(f);
  return put == 1;
}

static unsigned int read_number(void) {
  unsigned int value = 0;
  unsigned char key;

  for (;;) {
    key = cgetc();
    if (key == KEY_ENTER) {
      return value;
    }
    if (key >= '0' && key <= '9' && value < 6000) {
      value = value * 10 + (key - '0');
      cputc(key);
    }
  }
}

int main(void) {
  unsigned int score;

  ti_text_mode(40);
  ti_text_load_builtin_font();
  stdio_set_vdp_base(0x2000);

  if (load_game()) {
    printf("Save game loaded from disk.\n");
  } else {
    printf("No save game (error %u).\n", stdio_last_error());
    memset(&save, 0, sizeof save);
    save.magic = SAVE_MAGIC;
    strcpy(save.name, "PLAYER ONE");
  }

  save.runs++;
  printf("\nName: %s\n", save.name);
  printf("Runs: %u\n", save.runs);
  printf("Best: %u\n", save.best);

  printf("\nType a score and press ENTER: ");
  score = read_number();
  if (score > save.best) {
    save.best = score;
    printf("\nNew best score!");
  }

  if (save_game()) {
    printf("\nSaved to %s.\n", SAVE_FILE);
  } else {
    printf("\nSave failed (error %u).\n", stdio_last_error());
  }
  return 0;
}

Line by line

Lines 1–3
File functions and printf from stdio.h; memset and strcpy from string.h; cgetc, cputc and KEY_ENTER from conio.h.
Lines 5–6
TI file names include the device: DSK1.SAVEGAME is the file SAVEGAME on drive 1. File names are at most 10 characters. The magic number (the letters "TD") lets the program recognise its own file.
Lines 8–15
Everything that's saved, in one struct (18 bytes). It's a global so it isn't on the small stack, and static keeps it private to this file.
Lines 17–27
load_game opens the file for binary reading ("rb"). fopen returns NULL if it can't open it, typically because it doesn't exist yet. fread returns the number of whole items read; the load counts as good only if one full struct came back and it carries the magic number. Always fclose a file you opened.
Lines 29–39
save_game does the reverse with "wb", which creates the file or replaces it. Binary files are created as TI "INTERNAL/FIXED 128" files: data is stored in 128-byte records, so this 18-byte struct takes one record. See fopen(3) for the other file types.
Lines 41–55
read_number reads digits until ENTER, echoing each digit with cputc. Other keys are ignored, and the value < 6000 check keeps the result within an unsigned int (16 bits).
Lines 60–61
Text mode and font, as in Tutorial 1.
Line 62
stdio_set_vdp_base(0x2000) moves the DSR Peripheral Access Block (PAB) and VDP record buffers to VRAM 0x2000 so disk operations do not collide with the 40-column font pattern table at 0x0800–0x0FFF (or 0x1000–0x17FF). See stdio_set_vdp_base(3).
Lines 64–71
Try to load. If that fails, show why with stdio_last_error(), which returns the error code of the last failed file operation, and start a fresh save game. On a fresh disk you'll see error 7: the file isn't there.
Lines 73–76
Count this run and show the save game.
Lines 78–83
Ask for a score and keep it if it's a new best.
Lines 85–89
Write the save game back and report the result.
Lines 90–91
Return; the runtime then loops forever with the text still on screen.

Step 4: Build and run

Terminal
make
tidepod run

tidepod run mounts disks/notes.dsk and uses the HFDC from the project file. The first time, the program reports "No save game (error 7)". Type a score and press ENTER. Run it again and the save game comes back. To start over, recreate the disk with the script.

In the IDE: Press Mod+R (or click Run (Play)). The embedded emulator boots with disks/notes.dsk attached to drive 1. Click inside the emulator panel, type a number, and press Enter.

Inspecting the Disk Catalog: While the program is running (or paused), switch to the DSK tab in the debug panel. The drive list shows DSK1: disks/notes.dsk with an active directory catalog: you will see SAVEGAME listed alongside its record format (INT/FIX 128) and sector count.

To run the emulator directly from the command line outside of Tidepod, pass the equivalent hardware switches:

Terminal
ti994a-emu --peb-card hfdc@1100 --dsk1 disks/notes.dsk --cart notes.rpk
The DSK tab in the IDE, with notes.dsk mounted in DSK1 and SAVEGAME in its file list.
The DSK tab in the IDE, with notes.dsk mounted in DSK1 and SAVEGAME in its file list.
Text files

This tutorial sticks to binary fwrite/fread. For DISPLAY/VARIABLE text, open with "w" or "w:dv:80" and write lines with fputs/fprintf that include \n (each newline ends a record). See fopen(3) and fputs(3).

Try it

  • Let the player type a name and store it in save.name (leave room for the terminating zero).
  • Keep a top-five table instead of one best score.

See Disks and peripherals for hard disks, the other controllers and the IDE's disk tools.

Docs / Tutorials

Tutorial 7: Compiled Extended BASIC

Beginner

Tidepod includes a full optimizing compiler for TI Extended BASIC. Rather than interpreting tokens slowly through the console ROM's GPL runtime, Tidepod translates Extended BASIC source (.bas) directly into native TMS9900 machine code, linking it with libxb.a and libc.a.

The resulting cartridge images run between 20× and 100× faster than the original 1980s interpreter. This tutorial covers:

  • The critical role of CALL VSYNC and frame synchronization in compiled code.
  • The interplay between CALL VSYNC, CALL MOTION, and asynchronous CALL SOUND.
  • Example 1: Classic line-numbered Extended BASIC (100% retro type-in compatible).
  • Example 2: Modern structured Extended BASIC (labels, WHILE, IF/ENDIF, and SUB routines).
  • Creating, building, and running an Extended BASIC project in Tidepod.

The Heartbeat of Compiled Games: CALL VSYNC

On the original 1980s Extended BASIC cartridge, interpreted programs executed so slowly that game loops naturally took several video frames per iteration. Furthermore, background tasks—such as updating automotion sprites and decrementing sound timers—were serviced automatically by the console's vertical-blank interrupt service routine (ISR).

In compiled native machine code, a tight loop executes tens of thousands of times per second. Without throttling, a game loop would spin uncontrollably fast.

What CALL VSYNC Does

CALL VSYNC is a statement provided by libxb. It halts CPU execution until the next VDP vertical blanking interrupt (60 Hz on NTSC, 50 Hz on PAL). Calling CALL VSYNC inside your game loop accomplishes two vital things:

1. Locks framerate: Paces your game loop to a rock-solid, smooth 60 FPS.
2. Drives the background engine: It serves as the heartbeat dispatcher for CALL MOTION sprite automotion and asynchronous CALL SOUND durations.

The Interplay: VSYNC, MOTION, and SOUND

Understanding how these three statements cooperate is essential for writing responsive games:

1. Sprite Automotion (CALL MOTION)

CALL MOTION(#sprite, row_vel, col_vel) assigns independent row and column velocities (−128 to 127) to a hardware sprite. Velocities use 12.4 fixed-point scaling, where a value of 16 advances the sprite by 1 pixel per 60 Hz frame (60 pixels/second).

  • In compiled mode, sprites only advance their positions when CALL VSYNC is called!
  • Each time CALL VSYNC executes, the runtime adds velocity to each sprite's 12.4 fixed-point accumulator and updates VRAM coordinates from the integer part. If you forget CALL VSYNC, sprites with automotion will freeze in place.

2. Non-Blocking Audio (CALL SOUND with negative duration)

CALL SOUND(duration, freq, vol, ...) plays tones or noise through the SN76489 sound chip:

  • Positive duration: (e.g. CALL SOUND(150, 440, 2)) — Synchronous. The program halts and waits 150 ms before executing the next line of code.
  • Negative duration: (e.g. CALL SOUND(-300, 220, 0) or CALL SOUND(-200, -7, 0) for an explosion) — Asynchronous. The sound chip begins playing immediately, and execution returns to your program with zero delay.
The Audio Timer Gotcha

Asynchronous sound duration counters are decremented frame-by-frame inside CALL VSYNC. If your loop does not call CALL VSYNC, negative-duration sounds will never expire and will play forever!

How they work together in an event loop

! Trigger an asynchronous explosion sound (does not pause gameplay)
CALL SOUND(-250, -7, 0)

! Launch an enemy missile gliding diagonally (16 = 1 px/frame)
CALL MOTION(#2, 6, 8)

! The central game loop pumps both systems:
WHILE GAME_ACTIVE%
    CALL VSYNC            ! 1. Waits for 60Hz tick
                          ! 2. Moves sprite #2 by (6/16, 8/16) = (0.375, 0.5) px/frame
                          ! 3. Decrements sound countdown by 16.6ms
    CALL KEY(1, K%, S%)
    ! Read input, check collisions, update game state...
WEND

Example 1: Classic Line-Numbered Extended BASIC

Tidepod compiles traditional 1980s line-numbered BASIC without modification. Below is a complete, playable meteor evasion game written in classic syntax. Adding a single CALL VSYNC at line 320 is all it takes to adapt a classic game to run at locked 60 FPS compiled speed.

Classic Extended BASIC running compiled in the TI-99/4A emulator: Meteor Dodge with sprite automotion and sound.
Classic Extended BASIC running compiled in the TI-99/4A emulator: Meteor Dodge with sprite automotion and sound.
meteor.bas (Classic Style)
100 REM =====================================
110 REM METEOR DODGE - CLASSIC TI EXTENDED BASIC
120 REM =====================================
130 CALL CLEAR :: CALL SCREEN(2)
140 CALL MAGNIFY(2)
150 CALL CHAR(96,"183C7EFFFF7E3C18")
160 CALL CHAR(100,"00183C3C18000000")
170 CALL COLOR(9,7,1) :: CALL COLOR(10,9,1)
180 DISPLAY AT(1,9):"METEOR DODGE"
190 DISPLAY AT(24,1):"JOYSTICK 1: MOVE   FIRE: SPEED"
200 REM --- SETUP SPRITES ---
210 REM #1 = Player (Cyan, row 150, col 128)
220 CALL SPRITE(#1,96,7,150,128)
230 REM #2 = Meteor with automotion downward
240 CALL SPRITE(#2,100,9,10,64)
250 CALL MOTION(#2,12,0)
260 SCORE% = 0 :: LIVES% = 3 :: SEED% = 42 :: PX% = 128
270 REM --- ASYNCHRONOUS ENGINE SOUND ---
280 CALL SOUND(-200, 110, 15)
290 REM =====================================
300 REM MAIN GAME LOOP
310 REM =====================================
320 CALL VSYNC
330 CALL JOYST(1, JX%, JY%)
340 CALL KEY(1, K%, S%)
350 REM Move player horizontally
360 IF JX% = 4 THEN PX% = PX% + 4 ELSE IF JX% = -4 THEN PX% = PX% - 4
370 IF PX% < 10 THEN PX% = 10 ELSE IF PX% > 240 THEN PX% = 240
380 CALL LOCATE(#1, 150, PX%)
390 REM Check if meteor reached bottom of screen
400 CALL POSITION(#2, MY%, MX%)
410 IF MY% > 160 THEN GOSUB 600
420 REM Check collision between player and meteor
430 CALL COINC(#1, #2, 12, HIT%)
440 IF HIT% <> 0 THEN GOSUB 700
450 SCORE% = SCORE% + 1
460 IF LIVES% > 0 THEN 320
470 REM =====================================
480 REM GAME OVER
490 REM =====================================
500 CALL DELSPRITE(ALL)
510 DISPLAY AT(12,10):"GAME OVER!"
520 DISPLAY AT(14,8):"SCORE: ";SCORE%
530 CALL SOUND(800, 150, 0)
540 GOTO 540
550 REM =====================================
560 REM SUBROUTINE: RESET METEOR
570 REM =====================================
600 SCORE% = SCORE% + 50
610 CALL SOUND(-80, 880, 5)
620 SEED% = (SEED% * 37 + 11) MOD 200
630 RANDOM_COL% = SEED% + 20
640 CALL LOCATE(#2, 1, RANDOM_COL%)
650 CALL MOTION(#2, (SEED% MOD 6) + 6, 0)
660 RETURN
670 REM =====================================
680 REM SUBROUTINE: PLAYER HIT
690 REM =====================================
700 LIVES% = LIVES% - 1
710 REM Trigger non-blocking explosion noise (-7 is white noise)
720 CALL SOUND(-350, -7, 0)
730 CALL LOCATE(#2, 1, 128)
740 RETURN

Example 2: Modern Structured Extended BASIC

Tidepod also supports modern structured Extended BASIC. You do not need line numbers. You can use named labels, WHILE / ENDWHILE loops, native 16-bit integer variables (% suffix for maximum speed), and modular SUB definitions with parameters.

Modern Structured Extended BASIC: Paddle Bounce with custom characters, modular SUBs, and locked 60 FPS pacing.
Modern Structured Extended BASIC: Paddle Bounce with custom characters, modular SUBs, and locked 60 FPS pacing.
paddle.bas (Structured Style)
! =======================================================
! PADDLE BOUNCE - MODERN STRUCTURED EXTENDED BASIC
! =======================================================

CALL SCREEN(1)
CALL CLEAR
CALL MAGNIFY(2)

! Define custom characters
CALL CHAR(96, "FFFFFFFFFFFFFFFF")   ! Paddle bar
CALL CHAR(100, "3C7EFFFFFFFF7E3C")  ! Ball

! Initialize Globals (Integer % for high speed)
PADDLE_X% = 120
BALL_X% = 128
BALL_Y% = 30
DX% = 3
DY% = 3
SCORE% = 0
RUNNING% = 1

! Create Sprites
CALL SPRITE(#1, 96, 7, 160, PADDLE_X%)
CALL SPRITE(#2, 100, 15, BALL_Y%, BALL_X%)

! Draw UI
DISPLAY AT(1, 1): "SCORE:"
CALL UPDATE_HUD(SCORE%)

! Non-blocking start sound
CALL SOUND(-250, 659, 0)

! =======================================================
! MAIN GAME LOOP
! =======================================================
WHILE RUNNING%
    CALL VSYNC()

    ! Read Joystick 1
    CALL JOYST(1, JX%, JY%)
    IF JX% = 4 THEN PADDLE_X% = PADDLE_X% + 4
    IF JX% = -4 THEN PADDLE_X% = PADDLE_X% - 4

    ! Clamp paddle to screen boundaries
    IF PADDLE_X% < 16 THEN PADDLE_X% = 16
    IF PADDLE_X% > 224 THEN PADDLE_X% = 224
    CALL LOCATE(#1, 160, PADDLE_X%)

    ! Update Ball Position
    BALL_X% = BALL_X% + DX%
    BALL_Y% = BALL_Y% + DY%

    ! Bounce off left / right walls
    IF (BALL_X% < 8) OR (BALL_X% > 240) THEN
        DX% = -DX%
        CALL SOUND(-60, 1200, 4)
    ENDIF

    ! Bounce off ceiling
    IF BALL_Y% < 10 THEN
        DY% = -DY%
        CALL SOUND(-60, 1000, 4)
    ENDIF

    ! Check Paddle Collision
    CALL COINC(#1, #2, 16, HIT%)
    IF HIT% <> 0 THEN
        DY% = -DY%
        BALL_Y% = 152
        SCORE% = SCORE% + 10
        CALL UPDATE_HUD(SCORE%)
        CALL SOUND(-80, 800, 2)
    ENDIF

    ! Check Bottom Miss (Game Over)
    IF BALL_Y% > 170 THEN RUNNING% = 0

    ! Update Ball Sprite Position
    CALL LOCATE(#2, BALL_Y%, BALL_X%)
ENDWHILE

! =======================================================
! GAME OVER SEQUENCE
! =======================================================
CALL DELSPRITE(ALL)
DISPLAY AT(12, 11): "GAME OVER"
DISPLAY AT(14, 9): "FINAL: "; SCORE%
CALL SOUND(600, -7, 0)

@GAMEOVER_LOOP:
CALL VSYNC()
GOTO @GAMEOVER_LOOP

! =======================================================
! SUBROUTINES
! =======================================================
SUB UPDATE_HUD(S%)
    DISPLAY AT(1, 8): S%
SUBEND

Step-by-Step: Creating an Extended BASIC Project

Using the Command Line

Terminal
# Create a new Extended BASIC project
tidepod new my_xb_game --type xb
cd my_xb_game

# Run directly in the built-in emulator
tidepod run

This creates a project file my_xb_game.project with "type": 2 (Extended BASIC), a template main.bas, and a generated Makefile.

Using the IDE

  1. Open Tidepod and select File → New Project… (Cmd+Shift+N on macOS, Ctrl+N on Linux/Windows).
  2. Enter Project Name: (e.g. my_xb_game).
  3. In the Project Type: dropdown, select Extended BASIC.
  4. Click Create. The IDE opens main.bas directly in the syntax-highlighted editor.
  5. Press Mod+R (or click Build & Run) to compile and launch in the embedded emulator.

Performance Tips for Compiled Extended BASIC

  • Use integer variables (% suffix): Plain variables (e.g. X) are treated as 32-bit IEEE floats. Adding a percent sign (e.g. X%) forces 16-bit native TMS9900 hardware math, which is dramatically faster.
  • Always place CALL VSYNC in loops: Without CALL VSYNC, loops spin thousands of times per second, burning CPU cycles and breaking automotion and sound timers.
  • Prefer WHILE/WEND over GOTO: In structured code, WHILE/WEND produces cleaner assembly branch patterns and makes complex logic easier to maintain.
Docs / Tutorials

Tutorial 8: SuperAMS — fat pointers that look like C

Intermediate

SuperAMS does not give the TMS9900 a flat megabyte of RAM. Native char * stays 16-bit. Extra SRAM is reached by remapping 4K windows. Tidepod’s GNU C named address space __sams (and the optional <sams_far.h> macros) let you write far memory almost like ordinary C: p[i] = …, static far tables, typed allocs, and a lock helper for hot loops.

The finished tutorial cart after each sugar check (emulator with --mem sams).
The finished tutorial cart after each sugar check (emulator with --mem sams).

What you'll learn

  • Near vs far memory, and when to use each.
  • Allocating with sams_malloc / sams_new and indexing with p[i].
  • Declaring static far objects in .sams_bss.
  • Optional sugar in <sams_far.h>, and locking a page for bulk fills.
Requires SAMS in the emulator

Always run with --mem sams (or real SuperAMS hardware). Without it, sams_init() fails and far allocs return null. Tidepod projects default to -std=gnu99 so the __sams qualifier is available; plain -std=c99 rejects it.

Near vs far (one table)

KindTypeWhere it livesHow you touch it
Nearchar *, int *.data / .bss / stack / lock windowOrdinary C
FarT __sams * / sams_ptr_tSAMS pages (fat heap or .sams_*)p[i], or lock → near

Keep code, small state, and hot working sets near; put large tables and level data far. Linking any sams_* symbol forces the packer’s SAMS near map (near image under >C000, 8K) so lock windows stay free. See sams(3).

Step 1: Create the project

Terminal
tidepod new sams_demo
cd sams_demo

A banked cartridge is fine. Replace main.c with the program below (or study the ready-made cart in Tidepod’s resources/examples/sams_tutorial/).

In the IDE: File → New Project…, name it sams_demo, type C Banked Cartridge - 32K. Paste the listing into main.c. When you run from the IDE, set memory expansion to SAMS in Preferences (or pass --mem sams on the command line).

Step 2: The program

main.c
#include <conio.h>
#include <sams_far.h>
#include <stdio.h>

/* Static far BSS — zeroed by crt0 via sams_static_init. */
SAMS_FAR_OBJ(unsigned char, g_marks)[64];

static void hang(void) {
  volatile int h = 1;
  while (h) { }
}

static void fail(const char *msg) {
  clrscr();
  cputsxy(0, 0, msg);
  cputsxy(0, 22, "RESULT: FAIL");
  hang();
}

int main(void) {
  SAMS_FAR_PTR(unsigned char) buf;
  SAMS_FAR_PTR(unsigned) words;
  unsigned i;

  __asm__ __volatile__("limi 0" : : : "cc");
  ti_text_mode(40);
  ti_text_load_builtin_font();
  clrscr();

  cputsxy(0, 0, "SAMS tutorial");
  cputsxy(0, 1, "sugar + far heap");

  if (sams_init() != 0)
    fail("NO SAMS (use --mem sams)");

  /* 1. Untyped alloc — sams_malloc returns void __sams * (no cast). */
  buf = sams_new_bytes(128);
  if (!buf)
    fail("OOM bytes");
  for (i = 0; i < 128; i++)
    buf[i] = (unsigned char)(i & 0xFFu);
  for (i = 0; i < 128; i++) {
    if (buf[i] != (unsigned char)(i & 0xFFu))
      fail("FAIL p[i]");
  }

  /* 2. Typed alloc + 16-bit store. */
  words = sams_new(unsigned, 16);
  if (!words)
    fail("OOM words");
  words[0] = 0xBEEFu;
  if (buf[1] != 1)
    fail("FAIL isolation");
  if ((unsigned char)(words[0] >> 8) != 0xBE)
    fail("FAIL hi");

  /* 3. Static far object. */
  for (i = 0; i < 64; i++)
    g_marks[i] = (unsigned char)(0x40u + (i & 0x0Fu));
  if (g_marks[3] != 0x43)
    fail("FAIL static");

  /* 4. Lock once for a fast near fill. */
  SAMS_WITH_NEAR(buf, unsigned char, near, {
    for (i = 0; i < 128; i++)
      near[i] = 0xA5;
  });
  if (buf[0] != 0xA5 || buf[127] != 0xA5)
    fail("FAIL lock");

  sams_delete(words);
  sams_delete(buf);

  cputsxy(0, 3, "1 malloc p[i]   OK");
  cputsxy(0, 4, "2 sams_new HI   OK");
  cputsxy(0, 5, "3 static FAR    OK");
  cputsxy(0, 6, "4 WITH_NEAR     OK");
  cputsxy(0, 22, "RESULT: PASS");
  hang();
  return 0;
}
Include
<sams_far.h> pulls in <sams.h> and defines the sugar macros. You can use raw __sams instead; the header is optional.
g_marks
SAMS_FAR_OBJ expands to unsigned char __sams g_marks. The linker places it in .sams_bss at a fat VMA (page 0x10 onward). crt0 zeroes it before main.
sams_init
Probe the card, identity-map classic windows, enable MAP mode. Call once before any far alloc or access.
sams_new_bytes / p[i]
Fat heap alloc. Each buf[i] expands to a map + load/store through the accessor window. Fine for sparse access; slow for multi-kilobyte fills (see lock below).
sams_new / words[0]
Typed sams_calloc. A 16-bit store on the same page maps the accessor window once.
SAMS_WITH_NEAR
Locks the page into >C000 or >D000, runs the block with a native near pointer, then unlocks. Only two lock windows exist — nested locks of the same page refcount.

Step 3: Build and run

Terminal
make
ti994a-emu --cart sams_demo.rpk --mem sams --autorun --f18a

You should see four OK lines and RESULT: PASS. Without --mem sams, expect NO SAMS.

Optional sugar cheat sheet

MacroExpands to
SAMS_FAR__sams
SAMS_FAR_PTR(T)T __sams *
SAMS_FAR_OBJ(T, name)T __sams name
sams_new(T, n)typed sams_calloc
sams_new_bytes(n)sams_malloc as unsigned char __sams *
sams_delete(p)sams_free
SAMS_WITH_NEAR(...)lock → block → unlock

Full API: sams(3), sams_far(3). Deeper guide (locks, porting, pitfalls): Working with SuperAMS memory.

What to try next

  • Move a large lookup table from near static to SAMS_FAR_OBJ and watch near BSS shrink in bank_report.json.
  • Compare fill speed: per-byte p[i] vs SAMS_WITH_NEAR on a 1K buffer.
  • Study resources/examples/sams_chunk_demo/ for a lock-vs-accessor game pattern.
Chapter 3

Advanced Techniques

Docs / Advanced Techniques

Working with SuperAMS memory

Advanced

If you have written a game or utility in C for a desktop PC—or another retro platform with a flat address space—porting it to the TI-99/4A often hits a wall as soon as your data outgrows the standard 32 KB RAM expansion.

A SuperAMS (SAMS) memory card expands the console up to 1 MB of RAM, which is plenty of room for large tilemaps, level layouts, lookup tables, and dynamic objects. However, using that extra memory requires a slightly different mental model than desktop C. This guide walks through how SAMS memory works in plain terms, how locks work when you need several far arrays at once, and how to adapt an existing C codebase step by step.

If you haven't tried SAMS in a small program yet, start with Tutorial 8: SuperAMS first, or keep the sams(3) reference page handy.

1. Why You Can't Just Call malloc(200000)

On a modern computer, a pointer (char *) is 32 or 64 bits wide. The CPU can point directly to any byte in gigabytes of RAM at any time.

The TI-99/4A's TMS9900 processor has a 16-bit address bus. Every normal C pointer (void *, char *, int *) is only 2 bytes wide and can only address 64 KB (0x0000–0xFFFF) in total. Half of that 64 KB is permanently wired to console ROM, cartridge ROM, and hardware registers—leaving only 32 KB of CPU address space for RAM (0x2000–0x3FFF and 0xA000–0xFFFF).

So how does a 1 MB SAMS card fit into a 32 KB space? Paging.

  • The SAMS card divides its 1 MB of RAM into 256 pages of 4 KB each.
  • The CPU still sees the same 32 KB of RAM addresses, divided into eight 4 KB "windows."
  • At any moment, you can tell the SAMS card: "Show me SAMS page #42 inside one of my 4 KB RAM windows."

Because a SAMS buffer isn't permanently sitting at a fixed 16-bit CPU address, Tidepod distinguishes between two kinds of pointers:

Pointer KindHow to Write ItSizeWhat It Means
Regular ("Near") Pointer unsigned char *p 2 bytes (16-bit) Points directly to standard RAM that is always visible to the CPU. Fast (one instruction per access), but limited to ~16 KB of working space.
SAMS ("Far") Pointer unsigned char __sams *p
or SAMS_FAR_PTR(unsigned char) p
4 bytes (32-bit) Stores both a SAMS page number and a byte offset (0–4095) within that page. Whenever you read or write p[i], the compiler automatically maps the right 4 KB page into view.
How Tidepod Organizes RAM When You Use SAMS

As soon as your program uses any sams_* function, Tidepod automatically reserves the 4 KB windows at 0xC000–0xEFFF as temporary staging windows for SAMS pages (and keeps 0xF000–0xFFFF for the C call stack). Your normal global variables (.data / .bss) and regular malloc heap live in the 8 KB block at 0xA000–0xBFFF.

2. Deciding What Goes Where

You don't need to move every single variable into SAMS. In fact, your program will be much simpler and faster if you only move the bulky data:

  • Keep in regular RAM: Loop counters, player coordinates, state flags, small structs, file handles, and anything your code touches dozens of times every frame.
  • Move to SAMS (__sams): Large arrays, world maps, decompressed graphics buffers, level history, and large dynamically allocated tables.
  • Stream from disk when needed: Remember that SAMS is volatile RAM—it starts empty when the console powers on. If you have hundreds of kilobytes of pre-built level data, store it in cartridge ROM banks (see Binary Resources) or on disk, and unpack or generate your working state in SAMS at runtime.

3. Step-by-Step Code Changes

Step A: Initialize SAMS at Startup

Before touching any SAMS variable or calling sams_malloc(), call sams_init() once at the beginning of main(). It checks that a SAMS card is attached, sets up the default 4 KB windows, and turns on page mapping.

main.c
#include <sams.h>
#include <sams_far.h> /* Optional helper macros */

int main(void) {
    if (sams_init() != 0) {
        /* SAMS card not enabled — remind the user to pass --mem sams */
        return 1;
    }
    /* Safe to use __sams arrays and sams_malloc() from here on */
}

Step B: Move Large Global and Static Arrays to SAMS

The quickest way to free up regular RAM is to find your biggest global or static arrays and add the __sams qualifier (or the SAMS_FAR_OBJ macro from <sams_far.h>):

Before → After
/* Before: Takes up 4 KB of precious regular RAM */
static unsigned char dungeon_map[64 * 64];

/* After: Lives in SAMS RAM instead — zero regular RAM used! */
static unsigned char __sams dungeon_map[64 * 64];

/* Or using the optional <sams_far.h> macro: */
static SAMS_FAR_OBJ(unsigned char, dungeon_map)[64 * 64];

You can still read and write dungeon_map[i] just like a normal array. Note that SAMS global arrays cannot have compile-time initializers (like = {1, 2, 3}); they start zeroed out at boot and should be filled by your code at runtime.

Step C: Replace Large malloc Calls with sams_malloc

If your C program dynamically allocates large buffers with malloc(), switch those allocations to the SAMS heap functions:

Standard C Heap (Regular RAM)SAMS Heap (1 MB SAMS RAM)<sams_far.h> Shorthand
malloc(bytes)sams_malloc(bytes)sams_new_bytes(bytes)
calloc(count, size)sams_calloc(count, size)sams_new(Type, count)
realloc(ptr, bytes)sams_realloc(ptr, bytes)—
free(ptr)sams_free(ptr)sams_delete(ptr)

Important 4 KB limit per allocation: Each individual sams_malloc() allocation must fit inside a single 4 KB SAMS page (up to ~4,080 bytes). If your original program allocates a single 32 KB block with malloc(32768), split it into an array of eight 4 KB SAMS pointers (or allocate per room/chunk instead of one giant block).

Step D: Update Function Parameters and Struct Pointers

Because a regular pointer is 2 bytes and a SAMS pointer is 4 bytes, the compiler treats unsigned char * and unsigned char __sams * as different types. If a function receives a SAMS buffer, add __sams to its parameter declaration in both the .c file and the .h header:

Updating Function Signatures & Structs
/* Function that reads directly from a SAMS buffer */
void render_map_row(unsigned char __sams *row_data, int width);

/* Struct living in regular RAM, holding a pointer to a large buffer in SAMS */
struct LevelRoom {
    int width, height;                 /* Small fields: stay in regular RAM */
    char title[16];                    /* Small string: stays in regular RAM */
    unsigned char __sams *tile_buffer; /* Large array: lives in SAMS! */
};

4. Working with Functions That Expect Regular Pointers

What if you have an existing function—or a standard library function like memcpy()—that expects a regular char * or void *, and you don't want to rewrite it to take __sams pointers? You have two easy tools:

Option 1: Temporarily "Lock" the SAMS Page into Regular RAM

Calling sams_lock(far_ptr) maps that SAMS page into one of two dedicated 4 KB windows in regular RAM (>C000 and >D000) and returns a normal 16-bit pointer (void *) to it. While it is locked, any function can read or write that memory using standard C pointers at full CPU speed. When you're done, call sams_unlock(far_ptr).

Using sams_lock() / sams_unlock()
/* An existing function that only accepts a regular C pointer */
void unpack_room(unsigned char *dest, int size);

void load_room_into_sams(unsigned char __sams *far_buf, int size) {
    /* 1. Pin the SAMS page into regular RAM and get a normal pointer */
    unsigned char *near_buf = (unsigned char *)sams_lock(far_buf);
    if (!near_buf) return;

    /* 2. Pass the normal pointer to our unchanged function */
    unpack_room(near_buf, size);

    /* 3. Unpin the page when finished */
    sams_unlock(far_buf);
}

The SAMS_WITH_NEAR macro in <sams_far.h> does the lock and unlock automatically for a block of code:

Using SAMS_WITH_NEAR
SAMS_WITH_NEAR(far_buf, unsigned char, near_buf, {
    unpack_room(near_buf, size);
});

Locking several SAMS arrays at once

Yes — you can hold more than one lock at a time, including when the arrays live on different SAMS pages. Tidepod reserves exactly two lock windows (SAMS_LOCK_SLOTS is 2):

  • Two far arrays on different pages: both can be locked together. Each call returns its own near pointer (one in >C000, one in >D000), and you can use both in the same loop — for example, copying from one SAMS buffer into another.
  • Two far arrays on the same page: they share one slot. A second sams_lock of that page bumps a refcount and returns another near pointer into the same window.
  • A third distinct page while two different pages are already locked: sams_lock returns NULL. Unlock one of the held pages first, then lock the third.
Two different SAMS pages locked together
void copy_sams_to_sams(unsigned char __sams *src,
                       unsigned char __sams *dst,
                       unsigned n) {
    unsigned char *s = (unsigned char *)sams_lock(src);
    unsigned char *d = (unsigned char *)sams_lock(dst);
    unsigned i;

    if (!s || !d) {
        /* Third distinct page already locked elsewhere, or no SAMS */
        if (s) sams_unlock(src);
        if (d) sams_unlock(dst);
        return;
    }
    for (i = 0; i < n; i++)
        d[i] = s[i];
    sams_unlock(dst);
    sams_unlock(src);
}
Locks vs p[i] accessors

Element access like far[i] uses a separate scratch window (>E000) and does not consume a lock slot. You can keep two pages locked for hot near loops and still touch other SAMS data with p[i] / sams_read8 in the same function — just don't expect that third buffer to have a long-lived near pointer until you unlock something and lock it.

Option 2: Copy or Fill with SAMS Helper Functions

Standard memcpy() and memset() from <string.h> only work on regular 16-bit pointers. To copy data between regular RAM and SAMS (or fill a SAMS buffer), use the built-in SAMS helpers:

  • sams_memcpy_to(far_dst, near_src, bytes) — Copy from regular RAM into SAMS.
  • sams_memcpy_from(near_dst, far_src, bytes) — Copy from SAMS into regular RAM.
  • sams_memset(far_dst, byte_val, bytes) — Fill a SAMS buffer with a byte value.

5. Keeping Performance Snappy

Reading or writing far_ptr[i] is super convenient, but behind the scenes each access calls a small helper function that maps the SAMS page before reading or writing the byte.

  • For occasional reads and writes (checking a tile where the player is standing, updating an inventory item), far_ptr[i] is plenty fast and keeps your code clean.
  • For tight loops over hundreds of bytes (clearing a screen buffer, decompressing a level, copying a row of tiles), lock the page once with SAMS_WITH_NEAR (or sams_lock) and loop over the regular pointer inside. That maps the page just once instead of hundreds of times, running at full native CPU speed.
Slow vs. Fast Loop Over a SAMS Buffer
/* Slower: Remaps the SAMS window 1,024 times (once per byte) */
for (int i = 0; i < 1024; i++) {
    far_buf[i] = 0;
}

/* Fast: Maps the SAMS window ONCE, then loops at full native speed */
SAMS_WITH_NEAR(far_buf, unsigned char, near_buf, {
    for (int i = 0; i < 1024; i++) {
        near_buf[i] = 0;
    }
});

6. Common Pitfalls to Avoid

  • Don't cast a SAMS pointer to a regular pointer: Writing (char *)far_ptr throws away the SAMS page number and leaves you with a bogus memory address. Always use sams_lock(far_ptr) when you need a regular pointer.
  • Don't keep a locked pointer after sams_unlock(): Once unlocked, that 4 KB window in regular RAM may be reused by the next SAMS page lock. Unlock as soon as your loop or function finishes.
  • Only two different SAMS pages at once: See Locking several SAMS arrays at once above. Two pages is the hard ABI limit; a third distinct sams_lock returns NULL.
  • Don't mix free() and sams_free(): Pointers from malloc() must be freed with free(); pointers from sams_malloc() must be freed with sams_free() (or sams_delete()).
  • Remember to enable SAMS in the emulator: Pass --mem sams to ti994a-emu (or select SAMS under Memory Expansion in Tidepod's Preferences), otherwise sams_init() will report that no SAMS card is installed.
Docs / Advanced Techniques

Debugging in the Tidepod IDE

Advanced

The Debugging chapter introduces the debugger panels. This guide is about using them well on real projects: where breakpoints can land on a banked cartridge, how stepping behaves across bank trampolines, how to read watches on SuperAMS (__sams) data, what the bank and SAMS lines on the CPU tab mean, and what to expect from Extended BASIC projects.

If you prefer a terminal or an external frontend, see The Standalone GDB Bridge. For banked carts and XB the IDE debugger is currently the more capable of the two.

1. Open the Project and Build Debug

Open the project (tidepod mygame.project, or File → Open Project) and start a session with Build → Debug (F5, or Cmd+D on macOS). That runs make debug, which compiles with -O<optLevelDebug> -g -gdwarf-2 and keeps __dbg_printf and BRK(). The packer writes <project>.debug next to the .rpk: an ELF sidecar holding DWARF, the bank map (.tms9900.bankmap) and logpoints. The IDE loads it fresh on every debug launch.

Debug at -O0

Keep optLevelDebug at 0. From -O1 up, locals move into registers or disappear, line rows merge, and stepping jumps around. A plain Run builds release (-DNDEBUG, stripped): there is no .debug, so breakpoints and watches do nothing.

2. Breakpoints

WhereHow
SourceClick the gutter next to an executable line.
AssemblyClick an address in the ASM tab.
CodeBRK() from debug.h pauses when reached (debug builds only).
ListThe BRK tab jumps to or deletes any breakpoint.

Breakpoints are keyed by bank and address. On a banked cart the same >6000–>7FFF address exists in every bank, so a source breakpoint takes its bank from the DWARF line row (through the bank map, with --bank-base applied) and fires only when that bank is selected. A breakpoint set in the ASM tab uses whichever bank is selected at that moment.

A gutter click on a line with no code (a comment, a declaration with no initializer, most closing braces) has no line row to bind to. Put the breakpoint on the next statement.

3. Stepping

KeyAction
F6Pause / continue
F10Step over (C line)
F11Step into (C line)
Shift+F11Step out
Shift+F10Step one TMS9900 instruction

Line steps run until the program counter maps to a different source line. Cross-bank calls go through packer trampolines, which have no line rows, so Step Into passes straight through them and stops in the callee. To watch a trampoline switch banks, step by instruction in the ASM tab. All bindings can be changed under Preferences → Shortcuts.

4. Watches

Type a name into the WCH tab and press Add. Watches are re-resolved against the current PC, so a local is shown only while it is live at that PC. Outside its range it shows as unresolved, not as stale memory. Double-click a value to edit it.

KindShown asNotes
Scalardecimal / hexSize from the DWARF type (uint8_t is 1 byte, long is 4).
StructexpandableOne level of members per expansion.
Array-> @0xADDRElements from the DWARF array bounds.
Near pointer-> @0xADDRExpands the first 10 elements of the pointed-to type.
T __sams * / sams_ptr_t-> @pPPPP:OOOO4-byte fat pointer: SAMS page and offset.

Reading __sams watches

A SAMS pointer is a page number plus an offset, not a CPU address (see Working with SuperAMS memory). The watch shows the raw pair. If that page is currently mapped into one of the CPU's 4 KB windows, it also shows the near address the CPU would use:

WCH tab
level      -> @p0042:0123 (=0xE123)    page 0x42 is in the >E000 window
tiles      -> @p0051:0000              page 0x51 is not mapped right now

You can expand a fat pointer's elements only while its page is mapped. The debugger never remaps SAMS behind your program's back, because that would change the state you are debugging. To look inside an unmapped buffer, break in code that has it locked (sams_lock / SAMS_WITH_NEAR) and watch the near pointer sams_lock returned.

Ordinary globals, the near heap and stack locals are read through the SAMS mapper exactly as the CPU sees them. With Tidepod's SAMS layout they sit in >A000–>BFFF and >F000, so they always resolve.

5. The CPU Tab: Banks and SAMS Map Registers

CPU tab
PC: 6148 <main+12>
WP: 8300  ST: 4000  BNK: 3
FLAGS: .A...
SAMS MAP=1 ACC=0
2:02 3:03 A:0A B:0B C:51 D:0D E:42 F:0F
  • BNK is the physical cart bank currently selected on the cartridge board. Breakpoints and the bank map use the same number. Projects built with --bank-base N number their logical banks from N, so BNK can differ from the names in bank_report.json by that offset.
  • SAMS MAP / ACC are the mapper's mapping-mode and register-access bits. The SAMS lines appear only when the emulator runs with SAMS. tidepod run turns SAMS on by itself when bank_report.json shows the project uses the SAMS memory layout.
  • The page row lists the SAMS page in each 4 KB window. In Tidepod's layout C and D are the two sams_lock windows, E is the scratch window used by p[i] accesses, and F holds the stack. A window showing its own number (A:0A) is identity-mapped.
  • The RAM hex view shows the CPU's current view, so >C000–>EFFF show whichever page is mapped there right now.
Debugger reads are passive

Inspecting memory never disturbs the machine. Reads have no VDP, GROM or sound side effects and cost no cycles, and the I/O ports at >8400–>9FFF read as 0. Edits in the cart window (>6000–>7FFF) are ignored, so a hex-view poke can never switch banks by accident. With SAMS enabled, >4000–>5FFF shows the mapper registers.

6. Extended BASIC Projects

XB projects are compiled by xb1, Tidepod's GCC Extended BASIC front end (see Tutorial 7). The debugger knows when a project is BASIC:

  • Pause lands on your BASIC. If you pause inside the runtime (sound, CALL helpers, the interrupt handler), the debugger keeps running until it reaches a line of your .bas file.
  • Every statement has a line. xb1 emits a line entry for each executable statement, including assignments, GOSUB/RETURN, NEXT, ELSE and SUBEND, plus markers for lines that generate no code. Breakpoints on assignments and inside GOSUB bodies hit the right line.
  • Variables are typed. Main-program variables are emitted as real debug variables with named types, so X%, SCORE and NAME$ watch like C globals.
  • Optimised builds work. FOR loops no longer crash the compiler at -O1/-Os.
Similar variable names

Name matching is still loose. A watch on BALL% can bind to BALL_SPEED% if the exact name is not found. When two variables share a prefix, check the type and address in the watch row.

7. Known Limits

  • No data breakpoints. Neither the IDE nor the GDB stub has watchpoints yet. Break where the value is written, or add __dbg_printf at the suspect sites.
  • Unmapped SAMS pages are not browsable. Fat-pointer children and the hex view show only pages that are currently mapped.
  • Physical bank numbers only. BNK and breakpoint banks are physical. A logical/physical display is planned.
  • Optimised code. Above -O0 expect missing locals, merged lines, and Step Over stopping on the same line twice.
  • IDE-only features. BASIC auto-skip and line stepping are not yet in the standalone emulator, so ti994a-emu --gdb behaves like plain GDB.
  • One level of pointer expansion. Children of an expanded pointer don't expand further.
Docs / Advanced Techniques

The Standalone GDB Bridge

Advanced

ti994a-emu has a GDB Remote Serial Protocol server built in. Use it from a terminal, from CI scripts, or from any GDB/MI frontend such as VS Code. Host GDB doesn't know the TMS9900, so always connect with the toolchain's tms9900-elf-gdb.

This guide covers starting the stub, the extra bank register, how breakpoints pick a bank, monitor sams, frontend setup, and an honest list of what does not work yet. For interactive debugging of banked carts and XB programs, the IDE debugger is currently more capable.

1. Start the Stub

Terminal 1
make debug
tidepod run --debug          # emulator window + GDB server on :3333

# Or drive the emulator directly / headless in CI:
ti994a-emu --cart mygame.rpk --autorun --headless --gdb 3333
ti994a-emu --cart mygame.rpk --autorun --gdb 4444 --debug-dwarf build/mygame.debug
GDB_TRACE=1 ti994a-emu --cart mygame.rpk --autorun --gdb   # log every packet to stderr

tidepod run --debug uses the same machine setup as the IDE: VDP, PEB cards, memory expansion and disk mounts from Preferences and the project's "emu" settings. --gdb with no port listens on 3333. The emulator finds the matching .debug next to the cartridge (mygame.rpk → mygame.debug) and uses it to pick breakpoint banks and to print __dbg_printf logpoints.

Network exposure

The stub listens on all network interfaces and accepts one client at a time. Don't run it on a network you don't trust.

2. Connect

Terminal 2
tms9900-elf-gdb mygame.debug -ex 'target remote :3333'
0x0000601a in _vector ()
(gdb) break main
Breakpoint 1 at 0x65a6: file src/main.c, line 148.
(gdb) continue
Breakpoint 1, main (argc=..., argv=...) at src/main.c:148
148     int main(int argc, char *argv[]) {
(gdb) next
152       init_graphics();

The CPU halts wherever it happens to be when GDB connects. With --autorun that is usually already inside your cartridge; without it, the console is still on the title screen.

You may see Python Exception … No module named 'gdb' warnings at startup. They are harmless: regular commands and MI still work.

3. Registers and the Bank Register

Besides pc, wp, st and r0–r15, the stub exposes a bank register holding the physical cartridge bank that is currently selected:

gdb
(gdb) p $bank
$1 = 0
(gdb) set $bank = 1
(gdb) x/2xh 0x6000          # now reads bank 1's ROM
0x6000: 0x022a  0xfffc
(gdb) set $bank = 99
Could not write register "bank"; remote failure reply '01'

Writes are checked against the cartridge size. Changing bank swaps the ROM under the running program, so set it back before you continue. It is for looking at other banks, not for redirecting execution.

4. Breakpoints and Banks

Only software breakpoints are supported. Each breakpoint address in the cart window (>6000–>7FFF) exists once per bank, so the stub decides which bank you meant:

  1. Addresses outside the cart window match in any bank.
  2. Otherwise, if the debug info has a source line at that address, the stub uses that line's bank.
  3. Otherwise it uses the bank that is currently selected.

So break file.c:42 and break function do the right thing on banked carts in most cases. To force a bank, the stub accepts the bank in the high bits of the address (0x1713a = bank 1, >713A). GDB's TMS9900 addresses are 16 bits wide, so break *0x1713a is truncated before it reaches the stub. Send the raw packet instead:

gdb
(gdb) maint packet Z0,1713a,2      # insert: bank 1, >713A
received: "OK"
(gdb) maint packet z0,1713a,2      # remove

GDB doesn't track breakpoints set this way. When one hits, it just reports a SIGTRAP.

5. SuperAMS: monitor sams

gdb
(gdb) monitor sams
SAMS MAP=0 ACC=0 CRU=1E00
  2:02 3:03 A:0A B:0B C:0C* D:0D* E:0Ea F:0Fs
  (* lock  a accessor  s stack)

This prints the mapper state and the SAMS page in each 4 KB CPU window, using the same window roles as Working with SuperAMS memory. Without SAMS enabled the reply is SAMS not enabled.

GDB reads memory through the CPU's current mapping. A __sams pointer prints as its raw 32-bit value: page in the high word, offset in the low word. To read the data behind it, find the window that holds the page in monitor sams and read window base + offset, or stop where your program has the page locked.

6. Interrupting and Memory Access

  • Interrupt: Ctrl+C in GDB (or -exec-interrupt in MI) pauses the CPU and reports SIGINT. An interrupt sent while already stopped is ignored. Older stubs answered it with a second stop reply, which knocked frontends out of sync.
  • Reads are passive and shared with the IDE debugger. They have no VDP, GROM or sound side effects, go through the SAMS mapper, and the cart window shows the current bank.
  • Writes to RAM and scratchpad go straight to memory. Writes to console ROM or the cart window (>6000–>7FFF) are refused, so GDB reports Cannot access memory instead of silently switching banks. Writes to the VDP, GROM and sound ports still reach the hardware. Use $bank to change banks.

7. Frontends: GDB/MI and VS Code

The stub implements the packets that target remote and GDB/MI need, including target description, no-ack mode, continue/step, register and memory access, breakpoints, monitor, detach and kill. Raw MI looks like this:

GDB/MI
tms9900-elf-gdb --interpreter=mi2 mygame.debug
-target-select remote localhost:3333
-break-insert main
-exec-continue
-exec-next
-data-list-register-values x
-exec-interrupt

For VS Code with the C/C++ extension, start the emulator first (for example from a task running tidepod run --debug) and attach with:

.vscode/launch.json
{
  "name": "TI-99 (tms9900-elf-gdb)",
  "type": "cppdbg",
  "request": "launch",
  "program": "${workspaceFolder}/mygame.debug",
  "cwd": "${workspaceFolder}",
  "MIMode": "gdb",
  "miDebuggerPath": "/path/to/tidepod/toolchain/bin/tms9900-elf-gdb",
  "miDebuggerServerAddress": "localhost:3333",
  "stopAtConnect": true,
  "setupCommands": [
    { "text": "set can-use-hw-watchpoints 0" }
  ]
}
Starting point, not a tested recipe

This configuration has not been through an automated MI test yet. If a frontend hangs, restart the emulator with GDB_TRACE=1 and look at the last packet it logged.

8. What Works and What Doesn't

WorksNotes
break (file:line, function, *addr), tbreak, deleteBank chosen from debug info (section 4).
continue, stepi, nexti, step, nextstep/next run one packet per instruction.
info registers, p $bank, set $bank = N20 registers including bank.
x, print of globals and locals at -O0Current bank and SAMS mapping.
monitor samsSAMS window/page map.
Ctrl+C / -exec-interruptSafe to send while already stopped.
detachEmulator keeps running; you can reconnect.
Doesn't work (yet)Workaround
hbreak, hardware watch/rwatch/awatchhbreak fails on insert. A software watch single-steps the whole program and is far too slow. Break at the write site instead.
Source lines on banked cartsGDB has no map of cartridge banks. Breakpoints land, but at a stop GDB may show a resource symbol and "No line number information". Use the IDE, or debug code that sits in an unbanked cart or persistent RAM.
break *0xBAAAA with a bankTruncated to 16 bits by GDB. Use maint packet Z0,BAAAA,2.
GDB's built-in int is 4 bytesVariables print with their real 16-bit types. In casts, use short / unsigned short.
Deep backtraces, finishThe unwinder may stop with "frame did not save the PC" after the first frame or two.
killExits the emulator. Use detach to keep it running.
Other banks and unmapped SAMS pagesPeek with set $bank and restore it afterwards, or stop where the page is mapped.
BASIC auto-skip, XB line steppingIDE only for now. See Debugging in the Tidepod IDE.
Docs / Advanced Techniques

C Programming Gotchas & Porting Guide

Architecture

The TI-99/4A uses a 16-bit, big-endian TMS9900 CPU paired with an 8 KB banked cartridge memory model. While Tidepod provides a modern GCC 14.2 C99 compiler, bare-metal 16-bit systems have fundamental architectural constraints that will surprise experienced desktop C developers or anyone porting existing C code.

This guide highlights the most common architectural gotchas, silent bugs, memory placement rules, and code generation traps to watch out for.

1. Memory Model & Variable Storage

Where variables live: memory regions and storage classes

In a modern desktop OS, memory feels like a flat 64-bit pool. On the TI-99/4A, memory is partitioned into distinct hardware regions with very different speeds, persistence guarantees, and banking behaviors:

Storage Class / DeclarationSectionMemory Region & AddressAccess & Lifetime
int local_var; (in function) Stack / Regs High RAM (0xFFFF down) or Workspace (0x8300) Allocated on stack (or kept in registers R1–R8). Destroyed when function returns.
int global_score = 100; .data High RAM (0xA000–0xFFFF) Read-write global RAM. Initial values copied from cartridge ROM by crt0 at boot.
int enemy_buffer[64]; (uninitialized) .bss High RAM (0xA000–0xFFFF) Read-write global RAM. Cleared to zero by crt0 during system boot.
const uint8_t level_tiles[] = { ... }; .rodata Cartridge ROM (0x6000–0x7FFF) Read-only. Stays in the source file's assigned bank. Only visible when that bank is switched in!
__attribute__((section(".persistent"))) .persistent Low RAM (0x2000–0x3FFF) Always visible regardless of active ROM bank. Ideal for trampolines and shared state.
__attribute__((section(".scratchpad"))) .scratchpad Scratchpad RAM (0x8342–0x83BF) Internal 16-bit CPU RAM. Zero wait-states, ultra-fast access, but extremely limited in size.
// --- Example: Variable placement in practice ---

// Placed in ROM (.rodata) inside this file's assigned bank:
const uint8_t TILE_MAP[256] = { 0x01, 0x02, ... };

// Placed in High RAM (.data) at 0xA000+; initialized from ROM at startup:
int player_lives = 3;

// Placed in High RAM (.bss) at 0xA000+; zero-initialized at startup:
int high_scores[10];

// Placed in Low RAM (.persistent) at 0x2000+; always accessible across all banks:
__attribute__((section(".persistent"))) int active_bank_payload;

void update_player(int delta) {
    // Kept in workspace register R1-R8 (0x8302-0x8310 in Scratchpad RAM),
    // or spilled to stack at top of High RAM (growing down from 0xFFFF):
    int new_x = player_lives * delta;
}

16-bit pointers cannot encode a bank

Pointers in the TMS9900 C ABI are strictly 16-bit addresses (0x0000–0xFFFF). A pointer has no bits reserved for a cartridge bank number. If a function in Bank 1 takes a pointer to local read-only data in Bank 1, and you pass that pointer to a function in Bank 2, dereferencing the pointer in Bank 2 will read whatever bytes happen to sit at that offset in Bank 2 ROM.

The Rule for Shared Data

Any data passed between functions across different banks by reference must reside in RAM: either persistent low RAM (0x2000–0x3FFF), high expansion RAM (.data / .bss at 0xA000–0xFFFF), or Scratchpad RAM (0x8300–0x83FF).

Local string literal arrays vs. static strings

In standard C, declaring an initialized local array inside a function allocates stack space and copies the string from ROM on every single function call:

// AVOID: Allocates 16 bytes on the stack and runs memcpy from ROM on every call
void show_dialog(void) {
    char msg[] = "Press Any Key!";
    con_puts(msg);
}

// PREFERRED: Zero stack allocation, directly references ROM string constant
void show_dialog(void) {
    static const char * const msg = "Press Any Key!";
    con_puts(msg);
}

On a system where stack memory is precious, declaring local string arrays or large local buffers triggers hidden runtime copy overhead and consumes stack headroom.

Dynamic heap (malloc / free) is opt-in

libc.a provides both a near-heap allocator (malloc(), calloc(), realloc(), and free() in high 32K expansion RAM; see malloc(3)) and a SAMS far-heap allocator (sams_malloc(), sams_calloc(), sams_realloc(), and sams_free() in <sams.h>; see sams_init(3)). However, the near-heap reservation defaults to 0 bytes unless you set "heapSize" in your .project file (or pass --heap-size <bytes> to tms9900-packer). Because 32K RAM is shared with .data, .bss, overflow persistent code, and the stack, prefer static allocation when dynamic allocation isn't needed:

  • Static pre-allocated object pools (e.g., fixed array of sprite/entity structs).
  • Fixed-size ring buffers for I/O queues and audio commands.
  • Global scratch buffers placed in designated high RAM.

Scratchpad RAM layout & CPU workspace registers

The TMS9900 has a unique architectural property: its 16 general-purpose registers (R0–R15) do not live inside the CPU silicon—they are physically mapped to memory in Scratchpad RAM (0x8300–0x831F).

In unexpanded console configurations (or when using Scratchpad for user stack space), stack overflow is catastrophic: a downward-growing stack will silently overwrite the current register workspace, destroying return addresses (R11), frame pointers (R9), and console ISR hooks (0x83C4). Always keep call depths shallow and local variables small.

2. CPU Architecture & C Integer Semantics

Strict word alignment & silent LSB masking

The TMS9900 requires 16-bit word operations (uint16_t, int, pointers) to be aligned to even memory addresses.

The Silent Read Trap

On modern processors (x86, ARM), an unaligned word read either succeeds via hardware unaligned support or raises a hardware fault. On the TMS9900, the CPU hardware silently ignores bit 0 of the address for word operations! If you attempt to read a 16-bit word from odd address 0xA005, the CPU will execute the read from 0xA004 without error. Ensure packed binary structs and asset parsers respect 2-byte alignment.

16-bit int and size_t

Under GCC for TMS9900, sizeof(int) == 2, sizeof(short) == 2, and sizeof(size_t) == 2. Only long and long long are 32-bit (4 bytes) and 64-bit (8 bytes).

  • Shift overflows: 1 << 16 evaluates to 0! To shift into a 32-bit quantity, explicitly cast the literal: 1UL << 16.
  • Arithmetic truncation: int area = width * height; will overflow if the product exceeds 32,767. Use long for products of large numbers.
  • Pointer subtraction: Difference between pointers yields a 16-bit signed ptrdiff_t.

High-byte register convention for byte operations

The TMS9900 is strictly Big-Endian. Crucially, the hardware instruction MOVB operates on the most significant (high) byte (bits 0–7) of a workspace register, whereas standard C integer expressions evaluate in the low byte (bits 8–15).

The compiler automatically emits SWPB (Swap Bytes) instructions when loading and storing bytes to maintain standard C semantics. However, if you write inline assembly or use union casting tricks (such as reading ((char*)&my_int)[0]), remember that index 0 corresponds to the high byte.

Heavy cost of 32-bit math & software floating-point

The TMS9900 provides hardware 16-bit integer multiplication (MPY) and division (DIV). However:

  • 32-bit integer arithmetic (long multiplication, division, modulo) is synthesized through multi-instruction software library calls.
  • All floating-point types (float, double) are soft-float routines.

Avoid floating-point calculations in performance-critical code such as physics engines, sprite movement, or raster loops. Instead, use fixed-point arithmetic (typically Q8.8 with 16-bit integers, or Q16.16 with 32-bit integers).

Float format is IEEE 754, NOT TI RADIX-100

TI-99/4A veterans and developers interfacing with legacy console ROM routines, TI BASIC, or Extended BASIC will naturally expect the platform's historical RADIX-100 floating-point format (an 8-byte, base-100 excess-64 representation).

RADIX-100 vs. IEEE 754 (binary32)

Tidepod's C compiler uses standard IEEE 754 single-precision (binary32) for float (4 bytes) and IEEE 754 double-precision (binary64) for double (8 bytes).

Crucial Gotcha: You cannot directly cast or memcpy floating-point values between TI BASIC variables, disk catalog sectors, and C float variables! When reading raw disk catalog records (which encode file sizes and record lengths as 8-byte RADIX-100 floats) or calling console GPL subroutines, numbers must be converted explicitly (as performed internally by ti_opendir).

Note: A dedicated suite of bidirectional conversion helpers (radix100_to_float() and float_to_radix100()) is planned for a future release of Tidepod's libc.

If you need to unpack an 8-byte RADIX-100 buffer (e.g., from raw disk catalog sectors or file metadata) into a C float or double, you can use the following decoder:

// Converts an 8-byte TI RADIX-100 buffer to standard IEEE double/float
double radix100_to_double(const unsigned char *r) {
    if (r[0] == 0 && r[1] == 0) return 0.0;

    unsigned char b0 = r[0], b1 = r[1];
    double sign = 1.0;

    // Negative numbers have the first 16-bit word two's-complemented
    if (b0 & 0x80) {
        unsigned int w = ((unsigned int)(~b0) << 8) | (unsigned int)(~b1);
        w = (w + 1u) & 0xFFFFu;
        b0 = (unsigned char)(w >> 8);
        b1 = (unsigned char)w;
        sign = -1.0;
    }

    int exp = (int)b0 - 0x40; // Excess-64 exponent (powers of 100)
    double val = 0.0;
    double scale = 1.0;

    if (exp >= 0) {
        for (int i = 0; i < exp; i++) scale *= 100.0;
    } else {
        for (int i = 0; i < -exp; i++) scale /= 100.0;
    }

    // Each mantissa byte is a base-100 digit (0..99)
    for (int i = 0; i < 7; i++) {
        unsigned char digit = (i == 0) ? b1 : r[i + 1];
        if (digit > 99) digit = 99;
        val += (double)digit * scale;
        scale /= 100.0;
    }

    return sign * val;
}

3. Writing Efficient Code & Function Design

Loop induction variable sizing: prefer unsigned int over char

Many developers instinctively use uint8_t or unsigned char for small loop counters thinking it saves memory:

// SLOWER & LARGER: Compiler inserts byte masking / SWPB to simulate 8-bit overflow
for (unsigned char i = 0; i < 100; i++) { ... }

// FASTER & SMALLER: Matches native 16-bit register width directly (INC / CI / JLT)
for (unsigned int i = 0; i < 100; i++) { ... }

Because CPU registers are 16 bits wide, arithmetic on 8-bit types forces GCC to emit truncation instructions after every increment to simulate 8-bit wrap-around. Use native unsigned int or int for loop counters and math temporaries.

Avoid recursion

Each function call on TMS9900 pushes the return address (R11), the caller's frame pointer (R9), and any preserved callee-saved registers (R4–R8) to the stack. Recursive tree searches or recursive pathfinding algorithms will quickly exhaust the stack and trigger silent memory corruption. Always write iterative algorithms with explicit small state buffers.

Function pointers across banks

The auto-banker (tms9900-packer) generates cross-bank trampolines for direct function calls using the linker's --wrap feature.

Function Pointers are Not Wrapped

Calling a function through a function pointer ((*fn_ptr)(arg)) is an indirect branch (B *R1) that bypasses the trampoline and executes in whatever cartridge bank happens to be active. Functions called via function pointers (such as state machine dispatch tables or event handlers) must either reside in the same source file as the caller, or be placed into persistent RAM.

Memory-mapped I/O and the volatile keyword

When interacting directly with memory-mapped hardware ports (such as sound registers at 0x8400 or custom expansion devices), you must access them through volatile pointers:

#define SOUND_PORT (*(volatile unsigned char *)0x8400)

// Without volatile, the compiler optimizer would eliminate the first two writes!
SOUND_PORT = 0x9F;  // Silence voice 1
SOUND_PORT = 0xBF;  // Silence voice 2
SOUND_PORT = 0xDF;  // Silence voice 3

Without volatile, GCC's Dead Code Elimination (DCE) pass will fold sequential stores to the same memory location into a single write, breaking multi-byte hardware protocols.

4. Translation Units & Packer Strategies

Keep your Translation Units (TUs) small

In Tidepod's banking architecture, the translation unit (a single .c or .asm file) is an atomic, indivisible block. tms9900-packer places entire object files into 8 KB banks; it cannot split individual functions of one file across multiple banks.

Modularity Prevents Bank Overflow

If you write a monolithic 7 KB game.c, the packer has almost zero flexibility: that file can only fit into an almost empty bank, causing severe internal fragmentation in other banks and often triggering Bank overflow could not be resolved.

Best Practice: Break your codebase into small, focused files (e.g., player.c, enemies.c, physics.c, title_screen.c, sound_driver.c). Smaller chunks (1–3 KB each) give the bin-packing algorithm maximum puzzle flexibility to pack 8 KB banks tightly with minimal wasted ROM.

Understanding packer strategies (packing_algo)

The packer implements three distinct bin-packing algorithms to partition your compiled translation units across 8 KB banks. You can configure the strategy in your project settings ("packing_algo" in .project) or pass it via command-line options:

IDOptionStrategyHow It Works & Trade-offs
0 (Default) bfd Best-Fit Decreasing Sorts all translation units by compiled size in descending order, then fits each unit into the bank with the least remaining space that can still hold it.
Objective: Maximum density. Produces the smallest total number of ROM banks and minimal wasted cartridge space.
1 ffd First-Fit Decreasing Sorts units by size and inserts each into the first bank with sufficient headroom.
Objective: Deterministic layout stability. Reduces cascade shifts across banks during incremental compilation when one file changes slightly.
2 cluster Call-Graph Clustering Parses the static call graph generated by the compiler and clusters tightly coupled translation units that call each other into the same bank.
Objective: Maximum execution speed. Drastically slashes cross-bank trampolines and trampoline latency, at the cost of potentially needing 1 extra ROM bank.

To evaluate the impact of different strategies on your build, compare summary.total_trampolines and bank headroom in bank_report.json. For games with tight 60 FPS inner loops calling helper functions across modules, switching to cluster can reclaim valuable CPU cycles.

Chapter 4

Build System

Docs / Build System

The build pipeline

make · make debug

Tidepod generates a plain GNU Makefile from the .project file. The IDE's Build command runs exactly this Makefile, so make in a terminal gives the same result. This page follows a banked cartridge build step by step; the other cartridge types use the same steps with a different start-up object and linker template.

Targets

CommandResult
makeRelease build: <name>.bin and <name>.rpk.
make debugDebug build: the same plus <name>.debug (an ELF file with DWARF debug info), which is also packed into the .rpk for the debugger.
make cleanRemoves objects, packer output and build results.

Switching between make and make debug deletes the project's objects first (the mode is remembered in .build_mode), so you never link a mix of release and debug objects.

What happens during make

Each step prints a short tag:

make output (banked project with two resources)
  [AS] .cart_header.asm
  [RES] 2 resources (0 KB, 1 banks)
  [CC] main.c
  [BK] Running tms9900-banker ...
  [BK] Bank packing complete: 1 bank(s), 0 trampoline(s) generated
  [BK] RAM Overhead: .data 0B | .bss 0B | Stack 112B
  [BK] Upper RAM Free: 23.9 KB | Lower RAM Free: 6.7 KB
  [BK] Detailed memory map written to 'bank_report.json'
  [AS] autobank_trampolines.s
  [LD] assets.bin
  [PAD] assets.bin padded to 8KB
  [ZP] assets.rpk
TagStep
[RES]Each .dat resource is wrapped into an object file, and a packer pre-pass computes where every resource will live. The result is include/resource_defs.h, which your C code includes to find resources. Because every C object depends on this header, it is written before anything is compiled, and one make is always enough. See Binary resources.
[CC] / [AS]Each C file is compiled with tms9900-elf-gcc, each .asm file assembled with tms9900-elf-as. Every source file (translation unit) becomes one object.
[BK]tms9900-packer reads all objects plus libc.a, measures each translation unit, builds the call graph and distributes the units over 8 KB banks. It writes the linker script and the cross-bank call stubs. See Banking and the packer.
[AS] trampolinesThe generated autobank_trampolines.s is assembled.
[LD]tms9900-elf-ld links everything with the generated autobank.ld. The link map is written to link.map.
[PAD]The ROM image is padded to the next power of two (8, 16, 32 KB, …) so cartridge boards and emulators accept it.
[ZP]The .rpk is a zip of layout.xml, the .bin, the .debug file (debug builds) and any disk images in the project directory.

Compiler flags

BuildFlags
Release-std=c99 -Werror -Wall -Os -s -DNDEBUG -fno-function-sections -fno-data-sections -Iinclude -I<toolchain>/include
Debug-std=c99 -Werror -Wall -O0 -g -gdwarf-2 -fno-function-sections -fno-data-sections -Iinclude -I<toolchain>/include

The optimisation level comes from optLevelRelease / optLevelDebug, include paths and customCompilerFlags are appended. Note -Werror: every warning stops the build. Files placed in persistent RAM or scratchpad additionally get -mpersistent or -mscratchpad (see Code placement).

Generated files

Do not edit these; they are rewritten by tidepod sync or by every build.

FileWritten byContents
MakefilesyncThe build. Starts with # [GENERATED BY TI-99 IDE - DO NOT EDIT MANUALLY].
layout.xmlsyncCartridge board description for the .rpk.
.cart_header.asmsyncCartridge header with the menu name.
include/resource_defs.hbuildBank, offset and length of every resource.
autobank.ldbuildLinker script with the bank assignment.
autobank_trampolines.s, autobank_wrap.txtbuildCross-bank call stubs and the matching --wrap linker options.
autobank_mapping.hbuildWhich function ended up in which bank.
bank_report.jsonbuildMachine-readable layout report, see Reading bank_report.json.
link.mapbuildLinker map.
include/<prefix>_map.hbuildAddresses of an F18A GPU image, see F18A GPU code.

Your own build steps go in Makefile.custom, which is included by the Makefile and never overwritten. See Makefile.custom.

Things to know

Header changes are not tracked

The %.o: %.c rule has no dependencies on your own headers (only on include/resource_defs.h). After changing a header, rebuild everything with make clean && make, or list the dependencies in Makefile.custom.

EA5 projects

EA5 projects link a single ELF and run tms9900-packer --ea5, which slices it into Editor/Assembler option 5 program files (NAME1, NAME2, …) and writes them to <name>.dsk. There is no bank packing.

Docs / Build System

Banking and the packer

tms9900-packer

A cartridge sees ROM through one 8 KB window at 0x6000–0x7FFF. Larger cartridges are split into 8 KB banks; writing to an address in the window selects which bank is visible. Tidepod hides this from you: you write normal C, and tms9900-packer decides which bank every source file goes into and generates the glue for calls between banks.

The unit of packing is the source file

The packer places whole translation units (one .c or .asm file = one object). All functions of one file end up in the same bank. Consequences:

  • No single source file may be larger than one bank (8 KB of code and read-only data). Split big files.
  • Calls between functions in the same file are always direct and cost nothing extra.
  • Keep functions that call each other a lot in the same file, or put the hot one in persistent RAM.

Memory layout of a banked cartridge

RegionAddressWhat the toolchain puts there
Cartridge ROM window0x6000–0x7FFFThe current bank: header and start-up code (bank 0 only), your code (“auto” units), resources.
Low expansion RAM0x2000–0x3FFF“Persistent” code: C runtime, bank-switch stubs, files you mark persistent.
High expansion RAM0xA000–0xFFFF.data, .bss, persistent overflow, and the stack (top of RAM, growing down).
Scratchpad RAM0x8300–0x83FFRegisters/workspace, and code you mark scratchpad (from 0x8342 by default).

Start-up

When the console starts a banked cartridge:

  1. _start (bank 0) disables interrupts, checks that the 32K memory expansion is present (if not, it prints 32K MEM REQUIRED! and stops) and copies a small copier routine into scratchpad.
  2. The copier copies the persistent section to 0x2000. It can read from any bank, so this section can sit at the end of the ROM.
  3. _persistent_init (now running from RAM) copies the scratchpad section over the copier, copies high persistent code and .data to high RAM, clears .bss, maps bank 0 and calls main().

main() starts with interrupts disabled, and the runtime never enables them. If your program needs the console interrupt routine, enable interrupts yourself. If main() returns, the runtime loops forever.

Cross-bank calls (trampolines)

When a function in bank 2 calls a function in bank 5, the call is redirected (with the linker's --wrap) to a small stub in persistent RAM. The stub saves the current bank, switches to bank 5, calls the function, switches back and returns. You do not write anything for this, but it costs a few dozen cycles per call. The number of stubs is reported as summary.total_trampolines in bank_report.json.

Function pointers are not wrapped

Only direct calls get a trampoline. If you take the address of a function and call it through a pointer from another bank, the call jumps into whatever bank is currently mapped. Put functions that are called through pointers (callbacks, state-machine tables) in persistent RAM, or call them only from their own file.

Automatic persistent promotion (Phase 2.5)

Before packing translation units into cartridge ROM banks, the packer analyzes the static call graph and calculates a hotness score for each unit (the number of static call sites referencing it).

If free capacity remains in low persistent RAM (0x2000–0x3EFF), the packer automatically promotes the hottest units into persistent memory. If low persistent RAM fills up, remaining hot units overflow into high expansion RAM (persistent_high).

  • Promoted code runs from RAM and needs no trampolines when called from any bank.
  • Common C library routines (such as console_vdp.o, printf_core.o, and arithmetic helpers) and frequently invoked project units are often auto-promoted in small cartridges.
  • You can observe promotion decisions in verbose packer output (make PACKER_EXTRA_FLAGS=-v) and in the classification field of bank_report.json.
Explicit vs. Automatic

Automatic promotion is opportunistic: as your project grows, units previously promoted to RAM may be placed back into banked ROM. If a routine must reside in RAM (such as functions called via pointers or interrupt handlers), always mark it explicitly with #pragma bank persistent or tidepod add --persistent. See Code placement.

Strings and constants across banks

A pointer to read-only data in bank 2 is useless once bank 5 is mapped. For every file that calls into another bank, the packer therefore moves string literals and small constants (.rodata.str*, .rodata.cst* and plain .rodata up to 128 bytes) into always-mapped RAM. So printf("score %d", s) from banked code just works. Large const tables stay in their bank: don't pass pointers to them into functions in other files — copy the data first, or put the table in a persistent file.

Switching banks yourself

Normally you never do this. Banked projects get include/bankswitch.h, which defines switchtobank(n) (a write to 0x6000 + (n << 1)) and declares currentbank, the variable the trampolines keep up to date. The resource copy functions use it to restore the bank after reading from another one. If you switch manually, only do it from persistent or scratchpad code and switch back before returning.

Packing Heuristics and Trade-offs

Distributing dozens of translation units across fixed 8 KB ROM boundaries is an NP-hard bin-packing problem. tms9900-packer implements three distinct heuristic algorithms to solve this partitioning. You can select the active strategy via packing_algo in your project settings or pass it directly on the command line:

Algorithm IDPacker OptionStrategy & Optimization Objective
0 (Default) bfd Best-Fit Decreasing: Sorts all translation units by compiled byte size in descending order, then places each unit into the tightest-fitting bank that can accommodate it. Minimizes internal fragmentation and produces the absolute smallest number of ROM banks.
1 ffd First-Fit Decreasing: Sorts units by size and inserts each into the first bank with sufficient headroom. Simpler deterministic placement that can reduce cascade shifts during incremental builds.
2 cluster Call-Graph Clustering: Analyzes call graph edges and groups tightly coupled functions into the same bank. May require additional ROM banks, but significantly reduces cross-bank trampolines and execution latency.

For most projects, bfd is the recommended choice because it packs cartridge ROM images into the fewest physical EEPROM chips. However, if your application features high-frequency calls between multiple game modules, switching to cluster will trade a small amount of ROM space for substantial reductions in trampoline overhead. After changing algorithms, check summary.total_trampolines in bank_report.json to evaluate the improvement.

Packer Command-Line Options

Tidepod's generated Makefile automatically supplies the appropriate flags to tms9900-packer based on your project manifest. For advanced customization—such as integrating custom bootloaders, adjusting stack allocation, or building multi-cartridge collections—you can inject additional flags via PACKER_EXTRA_FLAGS in Makefile.custom:

Command-Line OptionArgumentDescription & Operational Details
--bank-sizeN (bytes)Overrides the default 8,192-byte bank capacity. Useful when targeting experimental hardware or non-standard paging schemes.
--bank-baseN (index)Sets the physical cartridge bank offset corresponding to logical bank 0. Used when merging your binary into a multi-bank compilation image behind other ROM cartridges.
--heap-sizeN (bytes)Reserves expansion RAM for dynamic allocation pools when custom runtime allocators are integrated.
--stack-sizeN (bytes)Overrides the static stack depth calculated from the call graph. Essential when code uses function pointers or recursion that static analysis cannot trace.
--no-32kFlagCompiles and packs targeting an unexpanded console (8K ROM Cartridge type). Allocates all variables, buffers, and workspaces within internal scratchpad RAM.
--flat-romFlagDisables bank switching entirely, generating a single unbanked 8 KB cartridge image.
--persistent-libpath/to/lib.aForces an entire static archive to reside in persistent expansion RAM (equivalent to libFiles[].forcePersistent).
--scratchpad-base0x83xxSpecifies the starting VMA address for code compiled with -mscratchpad (default is 0x8342).
--scratchpad-sizeN (bytes)Defines the maximum byte capacity allocated for scratchpad code routines.
--packing-algobfd|ffd|clusterSelects the bin-packing heuristic for translation unit placement.
--ea5ELF BASEEditor/Assembler #5 conversion mode: slices a linked ELF binary into disk-loadable program image files and generates a bootable DSK image.
-vFlagEnables verbose diagnostic logging, printing step-by-step unit placement, hotness calculations, and relocation tracking to stdout.
Docs / Build System

Code placement: banked, persistent, scratchpad

Performance

Memory architecture on the TI-99/4A is strictly segmented across distinct physical buses with radically different performance characteristics. By default, Tidepod treats every C and assembly source file as banked code: the object is placed in one of the cartridge's 8 KB ROM banks and swapped into view at 0x6000–0x7FFF on demand. While this allows cartridges to scale up to 512 KB or larger, calling functions across different banks incurs trampoline switching overhead.

To maximize application responsiveness, Tidepod provides explicit code placement controls. You can direct critical subsystems into persistent expansion RAM (always mapped, zero trampoline penalty) or internal scratchpad RAM (16-bit wide, zero wait states). In addition, Tidepod's automated linker pass implements profile-guided promotion, elevating the hottest call-target modules into free persistent RAM automatically.

Memory Placement Characteristics

Placement ModePhysical Memory RangeIdeal Use CasesPerformance & Memory Cost
Banked (Default) Cartridge ROM Banks (0x6000–0x7FFF) General game logic, menus, level data, initialization code, dialogue systems. Zero RAM cost. Calls from other ROM banks require a 12-to-24 cycle trampoline stub.
Persistent Low Expansion RAM (0x2000–0x3FFF), overflow to High RAM (0xA000+) Interrupt handlers (VBLANK ISR), audio engines, callbacks, jump tables, functions called via pointers. Consumes 32K Expansion RAM. Copied from cartridge ROM at cold boot. Direct calls from any bank without trampolines.
Scratchpad Console Internal RAM (0x8342–0x83FF) Time-critical inner loops (tile blitters, sprite collision matrices, decompression kernels). Extremely scarce (< 190 bytes). Runs on the 16-bit internal bus with 0 wait states, delivering maximum CPU throughput.

Marking a Translation Unit for Placement

Code placement in Tidepod is configured at the granularity of the translation unit (the source file). You can mark placement either from the command-line CLI or directly inside the source code using pragmas:

Terminal
tidepod add src/isr.c --persistent
tidepod add src/blit.c --scratchpad

Alternatively, declare placement at the very top of your C file using #pragma bank:

src/blit.c
/* High-performance software tile renderer */
#pragma bank scratchpad
#include "blit.h"

void blit_tile_row(const unsigned char *src, unsigned char *dst, unsigned int count) {
    while (count--) {
        *dst++ = *src++;
    }
}

Tidepod scans for #pragma bank persistent or #pragma bank scratchpad within the leading comment and preprocessor block of the file. Any pragma appearing after the first executable statement is ignored. Whenever you add or modify a pragma, run tidepod sync (or save project settings in the IDE). The build system automatically appends -mpersistent or -mscratchpad to the compiler flags for that file, directing GCC to emit functions into the appropriate ELF memory section.

Unexpanded 8K Cartridges

Persistent expansion RAM and large scratchpad allocations require the physical 32K memory expansion. For unexpanded 8K cartridges (Project Type 0), persistent placement is ignored, and all global variables and workspaces are packed into internal scratchpad memory.

Placing Third-Party Libraries in RAM

When linking precompiled static libraries (such as sound drivers, PSG audio players, or math routines) that are invoked frequently throughout your game loop, placing individual object files into RAM manually is impractical. You can add a library with tidepod add lib/libsound.a --persistent, or set "forcePersistent": true on any entry in libFiles in your <name>.project file:

<name>.project
"libFiles": [
    {
        "path": "lib/libsound.a",
        "forcePersistent": true
    }
]

The build system passes --persistent-lib lib/libsound.a to tms9900-packer, which relocates every symbol in the archive into low expansion RAM during the link phase.

Scratchpad Layout Presets and Hardware Safety

The TI-99/4A console contains only 256 bytes of internal scratchpad RAM (0x8300–0x83FF). Because the CPU workspace (R0–R15) resides at 0x8300 (32 bytes), scratchpad code is anchored at scratchpadBase (defaulting to 0x8342 when omitted) and by default can allocate up to 0x8400 unless restricted by scratchpadSize or the 0x83C0 console ISR workspace boundary. To prevent memory corruption with console ROM subsystems, Tidepod's Scratchpad Base: dropdown in Project Settings provides four presets:

Preset Name (IDE)Base AddressAvailable Code SpaceHardware Coexistence & Safety Requirements
Full scratchpad (0x8320) 0x8320 224 B to 0x8400 (160 B below 0x83C0) Maximizes scratchpad code capacity immediately above the C workspace. Safe only if no music drivers or disk routines use scratchpad.
+libtivgm2 (0x8340) 0x8340 192 B to 0x8400 (128 B below 0x83C0) Leaves 32 bytes (0x8320–0x833F) reserved for TI-99/4A chiptune sound players (such as libtivgm2) and envelope generators.
+disk access (0x8380) 0x8380 128 B to 0x8400 (64 B below 0x83C0) Mandatory for disk access: Disk controller DSRs use scratchpad between 0x834A and 0x837F (plus 0x83C0+ during DSR execution). Placing code below 0x8380 causes crashes during file I/O.
Custom User defined Variable Allows advanced developers to set an arbitrary base address (must be ≥ 0x8320) and optional scratchpadSize.
The Upper Scratchpad Danger Zone (0x83C0–0x83FF)

Addresses 0x83C0–0x83FF are reserved by the TI-99/4A console ROM for the interrupt service routine, GROM address counters, and sound generator shadow registers. If console interrupts are enabled, the console ISR writes to this memory 60 times a second. Never place scratchpad code above 0x83BF unless your cartridge permanently disables console interrupts (limi 0) and never returns control to the master console menu.

Validating Placement in the Build Report

After relocating code or modifying pragmas, always review bank_report.json. Inspect regions.persistent_lower.free and regions.persistent_high.free to ensure adequate headroom remains for initialized globals (.data) and uninitialized buffers (.bss). Overfilling high RAM will cause the descending stack to collide with global memory.

Docs / Build System

Binary resources (.dat files)

resource_copy.h

Graphics, fonts, level data, music: anything that is just bytes can be added to a cartridge as a resource. Resources are stored in ROM banks after your code and copied to VRAM or RAM when you need them. They cost no RAM until you load them.

1. Add the file

Give the file a .dat extension and a base name that is a valid C identifier, then add it:

Terminal
tidepod add resources/tiles.dat
make

The Makefile turns the file into an object (ld -r -b binary, renamed to a .resource section), and the packer assigns it a place in ROM before any C file is compiled, so a single make is enough.

2. The generated header

The packer writes three constants per resource, named after the file, into include/resource_defs.h:

include/resource_defs.h (generated)
#define height_bank   0
#define height_offset 0
#define height_length 6144
#define gpu_bank   0
#define gpu_offset 6144
#define gpu_length 564

Treat bank and offset as opaque values for the copy functions. _length is the file size in bytes.

3. Copy it where you need it

resource_copy.h (in the toolchain include directory) provides:

resource_copy.h
#define unwrap(x) x##_bank, x##_offset, x##_length

void rom_to_vram(unsigned int srcbank, unsigned int srcoffset,
                 unsigned int length, unsigned int dst);
void rom_to_ram(unsigned int srcbank, unsigned int srcoffset,
                unsigned int length, unsigned char *dst);

typedef void (*resource_copy_hook_t)(unsigned int bytes_copied, unsigned int total_bytes);

void rom_to_vram_ex(unsigned int srcbank, unsigned int srcoffset, unsigned int length,
                    unsigned int dst, unsigned int chunk_size, resource_copy_hook_t hook);
void rom_to_ram_ex(unsigned int srcbank, unsigned int srcoffset, unsigned int length,
                   unsigned char *dst, unsigned int chunk_size, resource_copy_hook_t hook);
  • unwrap(name) expands to the three constants, so the first three arguments are always written as unwrap(name).
  • rom_to_vram copies to a VRAM address; rom_to_ram to a CPU RAM buffer.
  • The _ex variants copy in chunks of chunk_size bytes and call hook with progress, e.g. to draw a loading bar or keep music playing during a long copy.
  • The functions switch banks to read the data and restore currentbank afterwards, so they can be called from any bank.

Example, from the f18a_bump sample:

src/main.c
#include "resource_copy.h"
#include "resource_defs.h"

    rom_to_vram(unwrap(height), HEIGHT_BASE);   /* resources/height.dat → VRAM 0x0C00 */
    rom_to_vram(unwrap(gpu), gpu_base);          /* the GPU program image → VRAM 0x3000 */

Producing .dat files

Tidepod does not convert images or audio. Produce raw bytes in the format your code expects (pattern tables, colour tables, sound lists, …) with your own tools, and add the result. A Makefile.custom rule can regenerate a .dat from its source automatically; see Makefile.custom and Tutorial 3, which does exactly that with a Python script.

You don't need a font resource for text

libc has a built-in 5×8 font: call ti_text_load_builtin_font() after ti_text_mode() and it is copied to the pattern table at 0x1000. It is only linked if you call it, and it covers all 256 codes, including the CP437 box-drawing characters used by chline() and cvline(). Use a font resource only if you want a different look.

Never edit RESOURCE_OBJS

The resource list in the Makefile comes from the project. Use tidepod add / tidepod remove; hand edits are lost on the next sync.

Docs / Build System

F18A GPU code in C

f18a_gpu.h · f18a_gpu_host.h

The F18A (and the Pico9918) video replacements contain their own TMS9900-compatible processor, the GPU, which runs from VRAM in parallel with the console CPU. Tidepod can compile a C file for the GPU, pack the resulting program as a resource, and give the host code the addresses it needs to load and start it.

The canonical, complete example is resources/examples/f18a_bump in the Tidepod install. The snippets on this page come from it.

1. Add the GPU source

Terminal
tidepod add src/gpu.c --gpu --gpu-base 0x3000 --gpu-stack 0x3F00
  • --gpu-base is the VRAM address the program is linked for and loaded at; it is also the entry point.
  • --gpu-stack is the initial GPU stack pointer (VRAM address; the stack grows down).
  • Both are required. Alternatively put #pragma bank gpu, #pragma gpu base 0x3000 and #pragma gpu stack 0x3F00 in the file.
  • Choose addresses that don't overlap the VRAM tables your host program uses.

2. What the build does with it

A GPU file is not part of the cartridge code. The Makefile:

  1. compiles it with -ffreestanding -nostdlib -fno-builtin -fomit-frame-pointer -ffixed-r15 -Os ([GPU-CC]),
  2. links it with the GPU start-up code crt0_gpu.o at the base address ([GPU-LD]),
  3. turns it into a binary src/gpu.dat plus a header include/gpu_map.h with gpu-image-map ([GPU-BIN]),
  4. packs gpu.dat as a normal resource named gpu.
include/gpu_map.h (generated)
#define gpu_base  0x3000u
#define gpu_entry 0x3000u  /* _gpu_start */
#define gpu_stack 0x3F00u
#define gpu_size  564u

The prefix is the file's base name: src/fx.c gives include/fx_map.h, fx_base, fx_entry, and the resource fx.

3. The GPU Execution Environment

The F18A GPU is a custom, hardware-implemented 16-bit processor integrated directly onto the FPGA alongside the VDP core. Because it shares internal routing with video RAM, it can read and modify tiles, pattern bitmaps, and sprite attribute tables with zero wait states at 100 MHz.

GPU translation units run in an unhosted, freestanding environment. They do not link against the standard C library (no malloc, printf, or standard file I/O). Instead, <f18a_gpu.h> provides direct hardware definitions, status register accessors, and memory-mapped I/O macros:

src/gpu.c (excerpt)
#include <f18a_gpu.h>
#include "layout.h"           /* VRAM addresses shared with the host */

void main(void) __attribute__((noreturn));

void main(void)
{
    for (;;) {
        F18A_GPU_IDLE();      /* Sleep until the host-configured trigger (e.g. VSYNC) */

        int lx = (signed char)F18A_GPU_MMIO8(LIGHT_LX);   /* Read a parameter written by host */
        ...
        /* Write pixel data directly to VRAM via 16-bit pointers at 100 MHz */
    }
}

GPU Runtime Header Reference (f18a_gpu.h)

Symbol / MacroValue / SignatureOperational Mechanics & Usage Notes
F18A_GPU_IDLE() Macro (idle instruction) Puts the GPU into a low-power hardware sleep state until an event trigger configured in VR50 (such as VSYNC) fires. Paces the GPU frame loop without burning memory cycles or polling.
F18A_GPU_MMIO8(addr) *(volatile uint8_t *)(addr) Performs a volatile byte read or write to any VRAM location or GPU status register.
F18A_GPU_MMIO16(addr) *(volatile uint16_t *)(addr) Performs a single-cycle 16-bit word transfer to even VRAM addresses.
F18A_GPU_VRAM_BASE 0x0000 The base address of the 16 KB VRAM space as mapped within the GPU's flat memory view.
F18A_GPU_GRAM_BASE 0x4000 The base address of the 2 KB dedicated GPU private static RAM on original F18A hardware.
F18A_GPU_WS_BASE 0x4800 The fixed hardware workspace register base (R0–R15).
F18A_GPU_SCANLINE 0x7000 Memory-mapped read-only register reporting the currently rendering raster beam scanline (0–261).
F18A_GPU_BLANKING 0x7001 Read-only status bit indicating active display blanking. Using F18A_GPU_IDLE() is strongly preferred over busy-wait polling.
F18A_ECM3_P0/P1/P2 Plane offsets Precomputed byte offsets for Enhanced Color Mode 3 (ECM3) bitplane patterns.
Hardware GPU Constraints

The F18A GPU workspace is permanently hard-wired to address 0x4800. Never execute LWPI (Load Workspace Pointer Immediate) in GPU C or inline assembly; changing the workspace pointer will crash the core. Additionally, register R15 is the F18A GPU's hardware subroutine stack pointer used by CALL, RET, PUSH, and POP (initialized to _gpu_stack in crt0_gpu.asm and reserved from register allocation by -ffixed-r15).

4. Host Control Interface

The host TMS9900 CPU controls the GPU lifecycle through enhanced VDP registers. The host is responsible for unlocking the register set, configuring hardware triggers, copying the GPU binary image into VRAM, and starting execution:

src/main.c (excerpt)
#include "vdp.h"
#include "f18a_gpu_host.h"
#include "resource_copy.h"
#include "resource_defs.h"
#include "gpu_map.h"

void f18a_unlock(void)
{
    /* Unlock enhanced register file by writing 0x1C twice to VR57 */
    VDP_SET_REGISTER(57, 0x1C);
    VDP_SET_REGISTER(57, 0x1C);
}

int main(void)
{
    f18a_unlock();
    
    /* Load the compiled GPU executable image into VRAM at gpu_base */
    rom_to_vram(unwrap(gpu), gpu_base);

    /* Configure VR50 to trigger GPU wakeup on vertical sync (0x20) */
    VDP_SET_REGISTER(50, 0x20);

    /* Set GPU program counter to entry point and start execution */
    f18a_gpu_start(gpu_entry);

    for (;;) {
        /* Host continues running standard game logic */
    }
}

Host Control API Reference (f18a_gpu_host.h)

FunctionParametersAction & Register Manipulation
f18a_gpu_start unsigned int entry_pc Writes the target execution address into GPU Program Counter registers VR54 (high byte) and VR55 (low byte), then asserts the run bit in VR56.
f18a_gpu_stop void Clears the run bit in VR56, immediately halting coprocessor execution.
f18a_gpu_load_at unsigned int vram_addr, const unsigned char *src, unsigned int len Streams a preloaded binary image from host CPU RAM into the specified VRAM destination address.
f18a_gpu_load_and_start unsigned int vram_addr, const unsigned char *src, unsigned int len, unsigned int entry_pc Transfers the image into VRAM and initiates execution in a single combined call.

When your GPU binary is bundled as a cartridge resource using tidepod add --gpu, you will typically copy it directly from cartridge ROM to VRAM using rom_to_vram(unwrap(gpu), gpu_base) followed by f18a_gpu_start(gpu_entry). The load variants are intended for dynamic overlays or code loaded from floppy disk.

Host Initialization Checklist

Always perform runtime chip detection using ti_vdp_detect() before attempting to unlock or write to registers beyond VR7. On an original TMS9918A, writing to register addresses above 7 corrupts standard display registers and locks up video output. After unlocking, remember to set VR30 to 32 to activate 32-sprite-per-scanline mode.

Running it

Run with an F18A-capable VDP: ti994a-emu --cart game.rpk --f18a, or select tidepod-f18a / pico-f18a as VDP in Preferences or in the project's emu settings.

Docs / Build System

Extending the build with Makefile.custom

Extension point

The generated Makefile is rewritten whenever the project changes, so you never edit it. Everything you want to add goes into Makefile.custom in the project directory. Tidepod creates it once (with a comment header) and never touches it again.

How it is included

The Makefile includes Makefile.custom after it has defined its variables (OBJECT_LIST, RESOURCE_OBJS, CCFLAGS, …) and .DEFAULT_GOAL := all, but before the all and debug recipes. So you can:

  • read and change variables — the recipes use your values;
  • add your own rules and targets without changing what plain make builds;
  • add prerequisites to existing objects.

Available variables include $(NAME), $(CC), $(AS), $(LD), $(OBJCOPY), $(CCFLAGS), $(CCFLAGS_DBG), $(OBJECT_LIST), $(RESOURCE_OBJS), $(STARTUP_OBJS), $(GCC_TOOLS) (toolchain bin), $(TOOLCHAIN_INC) and $(TOOLCHAIN_LIB).

Hooks

VariableEffect
POST_BUILDA shell command run at the very end of all and debug, after the .rpk is zipped. Use it for post-processing instead of overriding the targets.
PACKER_EXTRA_FLAGSExtra packer options, e.g. --stack-size 1280 or --bank-base 2.
MAKEFILE_CUSTOM_POST := 1Includes Makefile.custom a second time at the end of the Makefile, after the stock recipes, for the rare case where you need to see or wrap them.

Recipes

Track header dependencies. The generated %.o: %.c rule doesn't know about headers. List them yourself so objects rebuild when a header changes:

Makefile.custom
main.o player.o level.o: game.h
player.o enemy.o: sprites.h

Generate a resource from its source. If resources/tiles.dat is in the project, make it depend on the file it is converted from:

Makefile.custom
resources/tiles.dat: art/tiles.png tools/png2pat.py
	python3 tools/png2pat.py $< $@

The Makefile's own %.o: %.dat rule then picks up the new .dat.

Copy the result somewhere after each build.

Makefile.custom
POST_BUILD = cp $(NAME).rpk ~/Dropbox/ti99/

Raise the stack estimate. The packer computes the stack size from the call graph; recursion and calls through pointers are invisible to it.

Makefile.custom
PACKER_EXTRA_FLAGS := --stack-size 1024
A large real-world example

resources/examples/fileman/Makefile.custom adds header dependencies, reorders resources, uses its own start-up objects, checks GPU image sizes and merges the cartridge with another ROM in POST_BUILD.

Don't re-implement the build

Avoid redefining all or debug (make will warn about overriding recipes, and the IDE relies on them). Add sources with tidepod add rather than appending to OBJECT_LIST, so the packer, the IDE and the debugger all know about them.

Docs / Build System

Reading bank_report.json

Packer report

Every successful compilation in Tidepod produces bank_report.json in the project root. Generated by tms9900-packer during the final packaging phase, this file contains a complete structural blueprint of your cartridge image. It records the exact byte allocation across every 8 KB ROM bank, tracks memory utilization in both low and high expansion RAM, calculates static stack depth projections, and enumerates every cross-bank trampoline generated by the linker.

Because retro development on the TI-99/4A operates under tight hardware boundaries—an 8 KB cartridge paging window and a 32 KB RAM expansion—careful inspection of this report is the most effective way to catch memory leaks, stack overflows, and cross-bank performance regressions before testing on hardware.

Top-Level Report Structure

The root object of bank_report.json organizes your cartridge's memory and call graph into dedicated subsections. Each key isolates a specific layer of the binary layout:

JSON KeyTypeDescription & Engineering Significance
summary Object High-level binary metrics, including total_banks allocated in ROM and total_trampolines synthesized for cross-bank calls.
ram_overhead Object Comprehensive expansion RAM metrics: data_bytes (initialized globals), bss_bytes (zero-initialized globals), stack_vma (top of stack, typically 0xFFFE), and max_stack_depth (worst-case call chain in bytes).
regions Object Memory region descriptors for persistent_lower (8 KB at 0x2000–0x3FFF) and persistent_high (24 KB at 0xA000–0xFFFF), reporting total capacity, used bytes, and remaining free bytes.
ram_items Array Fixed RAM summary regions: .data (system_data), .bss (system_bss), WP_Reserved (wp_reserved at 0x8300), and Stack (stack). Individual RAM-resident object files (persistent, persistent_high, scratchpad) appear inside banks[b].items under the ROM bank holding their load image (lma), with vma set to their RAM execution address.
banks Array The physical ROM bank layout: an array of bank objects specifying bank_id (0 to N), capacity (8,192 bytes), used bytes, and an items array detailing the translation units packed into that bank.
call_edges Array The static call graph extracted from .tms9900.callgraph ELF sections and relocation tables: lists caller, callee, caller_tu, callee_tu, caller_bank, callee_bank, call weight, and is_trampoline (true whenever a global --wrap trampoline exists for callee).
trampolines Array The synthesized linker wrappers: reports each symbol redirected through a persistent RAM stub and its target_bank.

Object Classifications

The packer categorizes every translation unit and data object into a distinct classification. These classifications govern where the code resides at runtime, how it is bootstrapped at power-on, and how calls into it are resolved:

ClassificationTarget MemoryBootstrapping & Runtime Behavior
pinned ROM Bank 0 (0x6000) Anchored permanently at the base of the cartridge ROM. Contains the standard TI-99/4A cartridge header, the power-on reset vector, memory expansion detection routines, and initial boot code.
boot_copier Scratchpad RAM (0x8342) A small, self-contained machine routine copied into scratchpad during cold boot. It copies the persistent runtime and initialized data from ROM into expansion RAM, then executes _persistent_init.
auto Cartridge ROM Banks (1 to N) Standard banked C and assembly modules. The packer assigns these objects automatically using the selected packing heuristic (such as Best-Fit Decreasing) to optimize ROM capacity and minimize cross-bank calls.
persistent Low RAM (0x2000–0x3FFF) High-speed resident code copied from ROM at start-up. Includes routines explicitly tagged with #pragma bank persistent, as well as modules automatically promoted by the packer during Phase 2.5 hotness scoring.
persistent_high High RAM (0xA000–0xFFFF) Overflow persistent code placed in high expansion RAM when low RAM is exhausted. Shares space with .data, .bss, and the descending C stack.
scratchpad Scratchpad (0x8342–0x83FF) Ultra-hot computational routines running directly from 16-bit internal scratchpad memory with zero wait states.
resource Cartridge ROM Banks Binary data files (graphics tiles, sound streams, maps) packaged via tidepod add --resource and accessed at runtime via rom_to_vram or rom_to_ram.
system_data, system_bss High RAM (0xA000+) The C runtime global data segments in ram_items: initialized global/static variables copied from ROM (.data) and zero-cleared runtime buffers (.bss).
wp_reserved, stack Scratchpad (0x8300) / High RAM (0xFFFE down) Fixed system reservations in ram_items: the reserved CPU workspace registers (WP_Reserved) and the C execution stack region (Stack).

Visual Bank Report in the IDE

In the Tidepod IDE, double-clicking bank_report.json in the Files sidebar opens an interactive graphical bank report viewer. It displays color-coded capacity bars for each ROM bank and RAM region, lists every unit with its size and hotness, and visualizes cross-bank trampolines.

The visual bank report viewer in the Tidepod IDE.
The visual bank report viewer in the Tidepod IDE.

Critical Metrics: Avoiding Memory Collision and Performance Traps

When evaluating build health, four primary metrics must be monitored to ensure system stability:

  1. High RAM Clearance (regions.persistent_high.free): In the TI-99/4A architecture, High Expansion RAM (24 KB, 0xA000–0xFFFF) is a shared arena. Static globals (.data and .bss) grow upwards from 0xA000, while the C execution stack grows downwards from 0xFFFE. If persistent_high.free drops below 1,024 bytes, deep function nesting or interrupt service routines can cause the stack pointer to collide with global variables, creating silent memory corruption.
  2. Static Stack Projection (ram_overhead.max_stack_depth): The packer analyzes the static call graph to calculate the maximum cumulative stack frame depth from main() down to the deepest leaf function. While recursive functions and function pointers cannot be modeled statically, this number provides a baseline. Ensure that free RAM in high memory comfortably exceeds max_stack_depth.
  3. Trampoline Inflation (summary.total_trampolines): A sudden increase in total trampolines indicates that functions frequently calling each other have been split across different ROM banks. Each trampoline incurs a 12-to-24 cycle penalty to switch banks and restore state. If a time-critical game loop begins dropping frames, inspect call_edges to identify which cross-bank calls can be eliminated.
  4. Unit Migration: Because the packer runs a bin-packing heuristic on whole translation units, modifying one source file can cause other files to shift into different ROM banks. If your code calls a function through a raw function pointer across banks, such a shift will break execution (see Banking).

Automating CI Verification with jq

You can integrate automated layout assertions into your build scripts using jq. These queries verify that critical performance and memory thresholds are maintained across Git commits:

Terminal
# 1. Print executive memory overview:
jq '{summary, ram_overhead, regions}' bank_report.json

# 2. Assert remaining High RAM headroom is greater than 2 KB:
jq -e '.regions.persistent_high.free >= 2048' bank_report.json > /dev/null \
  || echo "CRITICAL WARNING: High RAM headroom is dangerously low!"

# 3. List fill percentage across all ROM banks:
jq -r '.banks[] | "Bank \(.bank_id): \(.used)/\(.capacity) bytes (\((.used*100/.capacity)|round)%)"' bank_report.json

# 4. Enumerate all functions wrapped by cross-bank trampolines:
jq -r '.trampolines[] | "Trampoline -> \(.symbol) in Bank \(.target_bank)"' bank_report.json

# 5. Identify the top 5 largest translation units in the project:
jq -r '[.banks[].items[] | select(.classification=="auto")] | sort_by(-.size) | .[0:5][] | "\(.size) bytes\t\(.filename)"' bank_report.json
Commit Your Baseline

Commit bank_report.json to your repository alongside major releases. Running git diff bank_report.json after refactoring reveals exactly how your changes affected bank allocation, trampoline counts, and RAM margins.

Chapter 5

Tools & Workflows

Docs / Tools & Workflows

Tidepod command line

tidepod <command>

The tidepod executable is both the IDE and a command-line tool. With a command it works on a project and exits; without one (or with a .project path) it opens the IDE.

Usage
tidepod <command> [options]
tidepod [project.project]          # open the IDE
tidepod <command> --help           # options of one command

Commands that work on an existing project find it through --project <file>, a *.project argument, or the single .project file in the current directory.

CommandWhat it does
newCreate a project directory with boilerplate.
addAdd files to the build and regenerate the Makefile.
removeRemove files from the build (the files stay on disk).
listShow project info and the file list with their flags.
set-typeChange the project type and regenerate the Makefile.
syncRegenerate the Makefile (and layout.xml, cartridge header) from the .project file.
runStart the stand-alone emulator with the project's cartridge.

There is no build command: run make or make debug in the project directory.

tidepod new

Synopsis
tidepod new <name> [--type 8k|banked|xb|ea5|custom] [--menu <name>] [--path <dir>]
OptionDefaultMeaning
--typebankedProject type.
--menuname in upper caseText in the console's cartridge menu.
--path./<name>Project directory (created if needed).

Creates <name>.project, a starter main.c (main.bas for XB), the cartridge header, the Makefile, Makefile.custom, layout.xml, and installs the agent skill under .agents/skills/ and .cursor/skills/.

tidepod add

Synopsis
tidepod add <file...> [--persistent | --scratchpad | --gpu --gpu-base HEX --gpu-stack HEX] [--project <file>]

Accepts .c, .asm, .dat resources, .a static libraries, and .bas/.xb Extended BASIC sources. Paths are relative to the project directory.

OptionMeaning
--persistentPlace the file in persistent RAM. See Code placement.
--scratchpadPlace the file in scratchpad RAM.
--gpuBuild the file as an F18A GPU image. Requires --gpu-base (VRAM link/entry address) and --gpu-stack (stack top, grows down). See F18A GPU code.
--projectExplicit project file.
Examples
tidepod add src/player.c src/enemy.c
tidepod add src/isr.c --persistent
tidepod add resources/tiles.dat
tidepod add src/gpu.c --gpu --gpu-base 0x3000 --gpu-stack 0x3F00

tidepod remove

Synopsis
tidepod remove <file...> [--project <file>]

Removes the files from the build list and regenerates the Makefile. Nothing is deleted from disk.

tidepod list

Prints the project name, type, and every build member with its placement flags.

tidepod set-type

Synopsis
tidepod set-type 8k|banked|xb|ea5|custom [--project <file>]

tidepod sync

Regenerates the Makefile, layout.xml and the cartridge header from the .project file, and re-reads #pragma bank … / #pragma gpu … from the sources. Run it after editing the .project file by hand or adding a placement pragma.

tidepod run

Synopsis
tidepod run [--debug] [--project <file>]

Starts ti994a-emu with <name>.rpk from the project directory and --autorun. The emulator configuration is layered:

  1. the machine defaults from Tidepod's preferences.json (PEB cards, VDP engine),
  2. the project's optional "emu" overrides,
  3. the project's disk mounts dsk1–dsk3 and hard1–hard3.

--debug also starts the GDB server on port 3333 (see Debugging). run does not build — run make first — and it opens the stand-alone emulator, not the IDE. For headless runs and other options, call ti994a-emu directly (The emulator).

Docs / Tools & Workflows

The stand-alone emulator (ti994a-emu)

ti994a-emu

ti994a-emu is the emulator used by the IDE, packaged as a separate program. It ships in the toolchain's bin directory next to the compiler. tidepod run starts it for you; call it directly for headless runs, screenshots, snapshots and anything else on this page.

Common invocations

Terminal
ti994a-emu --cart game.rpk                        # boot to the title screen, pick the cart yourself
ti994a-emu --cart game.rpk --autorun              # start the cartridge directly
ti994a-emu --cart game.rpk --f18a                 # with an F18A
ti994a-emu --cart game.rpk --dsk1 data.dsk        # with a disk in DSK1
ti994a-emu --cart game.rpk --gdb                  # with the GDB server on :3333

Cartridge and machine state

OptionMeaning
--cart <file>Load a cartridge: .rpk (recommended, includes the board type and debug info) or raw .bin.
--carts <list>Comma-separated multi-file cartridge (C/D/G images).
--autorunSkip the title screen and menu and start the cartridge immediately.
--mem <mode>Memory expansion mode: 32k (default 32 KB expansion), none (unexpanded console), or sams (1 MB SAMS paged memory expansion).
--save-state <path>Save a snapshot on exit (use with --frames).
--load-state <path>Restore a snapshot after loading the cartridge.
--pause-at <N>Pause when frame N is reached.
--step-n <K>When paused, execute K instructions.
--print-configPrint the resolved VDP, cartridge and disk configuration and exit.
--version, -h/--helpVersion / option list.
--autorun is a shortcut, not a test

--autorun jumps into the cartridge without going through the console's title screen and menu, a path real users never take. A program can behave differently that way. To check that a build really boots, start normally and select it with key injection; see Headless testing.

Video

--vdp engineEmulates
tidepod-tms9918aThe stock TMS9918A (default).
tidepod-f18aF18A (also selected by --f18a).
pico-f18aF18A, Pico9918-based core.
pico-v9938V9938 (Pico9918-based core).
pico-pico9918Pico9918 PRO.

Disks and peripherals

--dsk1…--dsk4, --hard1…--hard3, --peb-card, --peb-none, --dsr and --fast-disk are described in Disks & peripherals.

Automation and debugging

OptionMeaning
--headlessNo window.
--frames <N>Run N frames (60 per second), then exit.
--keys <script>, --key-fifo <path>Inject keystrokes. See Headless testing.
--screenshot-at <list>, --screenshot-path <p>Save PNG screenshots at the given frames.
--gdb [port]Start the GDB server (default port 3333).
--debug-dwarf <file>Load a .debug file for source-level information (not needed for .rpk files built with make debug, which contain it).
--dump-regs <N>Run N frames, then print CPU registers, interrupt state, scratchpad and VRAM tables (implies both --headless and --autorun).
-v, --verboseLog every interrupt with its source (VDP / timer / external).

See Debugging for GDB and --dump-regs in practice.

Configuration used by tidepod run and the IDE

The emulator itself only knows its command-line options. Tidepod builds them from three layers: the machine defaults in Preferences (stored in preferences.json), the optional "emu" block in the project, and the project's disk mounts. The "emu" block:

mygame.project (excerpt)
"emu": {
  "peb": "custom",
  "pebCards": [ { "type": "hfdc", "cru": 4352 } ],
  "vdp": "tidepod-f18a"
}
KeyValues
pebinherit (default; use Preferences), none (empty PEB, disk mounts are skipped), custom (use pebCards only).
pebCardsList of {"type": "tifdc"|"hfdc"|"whtscsi", "cru": N}. cru is decimal (4352 = 0x1100, 4608 = 0x1200).
vdpinherit or an engine name from the table above.

The block is omitted from the file when everything is inherit.

Docs / Tools & Workflows

Disks and peripherals

DSK · HARD · PEB

Programs that read or write files need a disk controller card in the emulated Peripheral Expansion Box (PEB) and a disk image to work on. This page covers how to set that up for the IDE, tidepod run and ti994a-emu. For the C side (fopen and friends) see the API reference.

Disk images in a project

Mount images in the IDE's Disk dialog or DSK tab, or put them in the project file. Paths can be relative to the project directory:

mygame.project (excerpt)
"dsk1": "disks/game.dsk",
"dsk2": "disks/save.dsk",
"hard1": "disks/work.hd",

The IDE mounts them when the project opens and tidepod run passes them to the emulator via --dsk1…--dsk3 and --hard1…--hard3. Disk images (*.dsk, *.hd, …) in the project directory are also archived into the .rpk by the build for distribution, though ti994a-emu mounts disk images from the explicit --dsk1..3 / --hard1..3 flags (which the IDE and tidepod run supply automatically).

The DSK tab in the IDE: mounted disks, catalog inspection, and the New Disk tool.
The DSK tab in the IDE: mounted disks, catalog inspection, and the New Disk tool.

Emulator options

OptionMeaning
--dsk1 … --dsk3 <file>Mount a sector disk image (.dsk).
--dsk4 <file>Fourth floppy drive; needs the HFDC card.
--hard1 … --hard3 <file>Mount a hard-disk image (HFDC).
--peb-card <type@cru>Add a card: tifdc@1100, hfdc@1100 or whtscsi@1200. Repeatable; the first use replaces the default TI FDC.
--peb-noneEmpty PEB: no disk controller at all.
--dsr <base>:<file>Load a DSR ROM at a CRU base, e.g. 1100:disk.bin.
--fast-diskDisable realistic disk timing.

Controller cards

TypeDefault CRUNotes
tifdc1100TI floppy disk controller. The default when nothing is configured.
hfdc1100Myarc HFDC: floppies (including DSK4) and hard disks.
whtscsi1200WHT SCSI card; work in progress.

Combinations are explicit: --peb-card tifdc@1100 --peb-card whtscsi@1200. Two cards on the same CRU base are emulated as a bus clash, not refused.

Hard-disk images

Hard-disk images must be raw sector dumps (.hd, .hdf, .raw). MAME CHD files are refused at mount time; convert them first:

Terminal
chdman extracthd -i disk.chd -o disk.hd

chdman is part of MAME's tools (Homebrew package rom-tools).

Testing without a disk controller

Set "peb": "none" in the project's "emu" block (or pass --peb-none) to check how your program behaves on a console without disks. The dsk/hard entries stay in the project but are not mounted.

Programs that use disk files

  • Use the +disk access (0x8380) scratchpad preset in Project Settings; the disk system uses lower scratchpad. See Code placement.
  • By default fopen goes through the disk controller's own file routines. Other back-ends are opt-in: see stdio_enable(3).
  • After a failed call, stdio_last_error(3) tells you why.
  • Don't put sector-sized buffers (256 bytes and up) on the stack; make them static. The stack is small.
Docs / Tools & Workflows

Debugging

IDE · GDB · logpoints

Debugging on 1970s and 1980s retro hardware typically involves painful trial-and-error, blinking screen borders, or slow serial monitor routines. Tidepod brings modern, source-level debugging to the TI-99/4A through a tightly integrated toolchain. By emitting standard DWARF symbol tables into an ELF container and embedding them directly within the cartridge bundle, Tidepod allows you to set visual breakpoints, single-step through C source statements, evaluate complex structs, inspect hardware VDP tables live, and trace variables without altering cycle timing.

Whether you prefer the all-in-one graphical debugger inside the Tidepod IDE or command-line scripting with tms9900-elf-gdb, the underlying execution engine remains cycle-accurate and hardware-faithful.

Source-Level Debugging in the IDE

When you initiate a debug build (F5 or make debug), Tidepod invokes GCC with -O0 -g and creates <project>.debug alongside the cartridge image. The IDE boots the internal emulator, attaches to the CPU execution pipeline, and loads the symbol database:

  1. Setting breakpoints: Click in the margin gutter next to any executable C statement. A red marker indicates an active hardware breakpoint.
  2. Execution control: Launch with F5. Control execution with standard debugger shortcuts:
    • F10 — Step Over: Execute the current statement, stepping over function calls.
    • F11 — Step Into (Step Line): Follow execution into the called function body.
    • Shift+F10 — Step OvInst: Step over one TMS9900 machine instruction.
    • Shift+F11 — Step Out: Run until the current function returns.
    • F6 — Pause / Continue: Toggle execution state.
  3. State inspection panels (8 debugger tabs):
    • CPU: Displays the Workspace Pointer (WP), Program Counter (PC), Status Register (ST), the 16 primary workspace registers (R0–R15) in hex and decimal, and RAM hex view.
    • VDP: Displays VDP registers VR0–VR7 (plus F18A/Pico enhanced registers VR8–VR57) and VRAM hex inspector.
    • ASM: Disassembles the active memory window in real time, synchronized to the current Program Counter.
    • BRK: Manages active source and address breakpoints.
    • WCH (Watch): Evaluates local variables, global symbols, and complex pointer chains. Structs expand hierarchically.
    • GFX: Visualizes live pattern generator tables, color tables, and sprite attribute tables.
    • DSK: Inspects mounted floppy/hard disk catalogs and creates formatted 90 KB disk images (New Disk).
    • PRF: Real-time cycle-accurate frame profiler and block breakdown charts.
Source-level debugging in the IDE: paused at a breakpoint with variable watches.
Source-level debugging in the IDE: paused at a breakpoint with variable watches.

For breakpoints on banked carts, __sams watches, the CPU tab's bank and SAMS map lines, Extended BASIC behaviour and known limits, see Debugging in the Tidepod IDE.

Remote Debugging with GDB

For automated testing, scripting, or developers who prefer terminal workflows, the stand-alone emulator (ti994a-emu) includes a built-in GDB Remote Serial Protocol server. Because standard host GDB installations do not support the TMS9900 architecture, you must use the cross-debugger provided with Tidepod: tms9900-elf-gdb.

Terminal 1 — Start the Emulator with GDB Server
make debug
# Run with graphical display and GDB server listening on port 3333:
tidepod run --debug

# Or run headless in continuous integration:
ti994a-emu --cart mygame.rpk --autorun --headless --gdb 3333
Terminal 2 — Connect tms9900-elf-gdb
tms9900-elf-gdb mygame.debug -ex 'target remote :3333'
(gdb) break main
(gdb) continue
Continuing.
Breakpoint 1, main () at src/main.c:42
42        player_init(&hero);
(gdb) print hero
$1 = {x = 120, y = 80, dx = 0, dy = 0, health = 100, state = 1}
(gdb) info registers
wp             0x8300   33536
pc             0x6148   0x6148 <main+12>
st             0x0000   0
r0             0x0078   120
r1             0x0050   80
...
(gdb) backtrace
#0  main () at src/main.c:42
Where GDB Stops on Connect

When target remote :3333 connects, the emulator halts wherever the CPU is at that moment. With --autorun that is usually already inside the cartridge. Set your breakpoints and issue continue.

The bank register, bank-qualified breakpoints, monitor sams, VS Code / MI setup and the full list of what the stub does and doesn't support are covered in The Standalone GDB Bridge.

Zero-Cost Logpoints: __dbg_printf

Calling standard printf on an embedded 16-bit processor is notoriously heavy: it pulls hundreds of bytes of format-parsing routines into memory and takes thousands of clock cycles to format strings, frequently causing games to miss their 60 Hz frame deadline. Tidepod solves this with zero-overhead host logpoints via debug.h.

At compile time, each __dbg_printf call emits only a single 2-byte NOP instruction in the executable binary. The format string literal and the symbolic names of the arguments are segregated into a custom ELF section (.tms9900.logpoints) in the .debug sidecar. When the emulator hits the NOP, the host reads argument values via DWARF, formats the message on your workstation, and prints it — in the IDE’s Debug Log, or on the console of standalone ti994a-emu when --debug-dwarf <file>, --gdb, or --dump-regs is passed (matching uses physical cart bank + address in the >6000 window):

src/player.c
#include "debug.h"

void player_take_damage(int amount) {
    player.health -= amount;
    
    /* Zero-overhead trace: formats on your Mac/PC, zero cycles on the TI */
    __dbg_printf(DBG_RED "DAMAGE: " DBG_RESET "player took %d dmg, remaining=%d", amount, player.health);

    if (player.health <= 0) {
        __dbg_printf(DBG_BRIGHT_RED "PLAYER DIED at x=%d, y=%d" DBG_RESET, player.x, player.y);
        BRK();  /* Software breakpoint: halts the debugger immediately */
    }
}

Logpoint Specifications

FeatureSyntax / MacroBehavior & Constraints
Format StringStandard C specifiers (%d, %u, %x, %s, %p)Formatted on host workstation; no C formatting code linked into TI ROM.
Max ArgumentsUp to 8 argumentsArguments must be named variables or parameters resolvable via DWARF symbols.
Terminal ColorsDBG_RED, DBG_GREEN, DBG_YELLOW, DBG_RESETANSI escape sequences rendered in the IDE Debug Log.
Cursor ControlDBG_CLEAR, DBG_HOME, DBG_GOTO(row, col)Positions log messages on a host debugging dashboard.
Software BreakpointBRK()Triggers an immediate debugger pause in the IDE when hit.
Release Builds-DNDEBUG in release CCFLAGSTidepod’s generated Makefile defines NDEBUG for make (release). Logpoints and BRK() expand to nothing; use make debug to keep them.
Logpoint traces displayed in the IDE's Debug Log panel.
Logpoint traces displayed in the IDE's Debug Log panel.

Diagnosing Crashes, Hangs, and Bank Faults

When an embedded program locks up, the console screen often freezes without giving any diagnostic feedback. ti994a-emu provides automated autopsy dumps through --dump-regs (which implies both --headless and --autorun) and verbose interrupt tracing:

Terminal
# Auto-start headless (--dump-regs implies --headless and --autorun), simulate keys, and dump registers at frame 900:
ti994a-emu --cart mygame.rpk -v \
  --keys "WAIT:120 ENTER WAIT:300" \
  --dump-regs 900 --frames 920 2>interrupts.log | tee register_dump.log

Common Crash Signatures and Root Causes

Observed SymptomPrimary Root CauseRemediation Workflow
Illegal Opcode Exception: Console reports invalid instruction or halts in unmapped ROM space. Calling a function pointer across banks without switching the cartridge bank register. Direct calls use wrapped trampolines; indirect calls do not. Move functions called via pointers into persistent RAM using #pragma bank persistent or tidepod add --persistent. See Banking.
Spontaneous Reboot or Data Corruption: Variables suddenly change values or game resets during deep recursion. The C stack (growing downwards from 0xFFFE) has collided with ascending static variables in .bss. Inspect ram_overhead.max_stack_depth and regions.persistent_high.free in bank_report.json. Reduce local array sizes or allocate buffers statically.
Garbled Graphics / Tile Corruption: Screen fills with scrambled patterns after VDP update. Missing address setup byte or failing to observe VDP port delay constraints during high-speed VRAM writes. Ensure write addresses set bit 0x40 on the second byte to latch write mode. Use standard library routines like vdpmemcpy.
Frozen Execution Loop: Program hangs with PC stuck in console ROM (0x0000–0x1FFF). Console interrupt routine was executed while workspace or scratchpad vectors were modified. Keep interrupts disabled (__asm__("limi 0")) if using scratchpad memory between 0x83C0 and 0x83FF.
Docs / Tools & Workflows

Frame profiler

profiler.h · PRF tab

High-performance TI-99/4A programming requires budgeting every CPU instruction against the 60 Hz vertical blanking interval. The Tidepod IDE features a built-in cycle-accurate Frame Profiler (PRF) that monitors execution timing in real time. By inserting lightweight markers from profiler.h into your C source, you can partition your game loop into distinct visual categories—such as physics, input handling, sprite animation, and VDP rendering—and immediately see how many clock cycles each subsystem consumes relative to your target frame budget.

Unlike software profilers that inject instrumentation calls, timestamp traps, or interrupt polling overhead, Tidepod's profiler is completely non-invasive. The instrumentation macros emit zero machine instructions and consume zero clock cycles: they simply export linker symbol labels that the emulator tracks passively at the hardware bus level.

Instrumenting a main loop

To profile an application, include <profiler.h> and wrap functional blocks in your game loop with PROF_BEGIN and PROF_END macros. Mark the boundary between consecutive display frames using PROF_FRAME_END():

src/main.c
#include "profiler.h"

for (;;) {
    PROF_FRAME_END();                 /* Mark start of frame boundary */

    PROF_BEGIN(808080, vblank_wait);  /* Grey: idle wait for vertical blank */
    wait_for_vblank();                /* Polling VDP status flag */
    PROF_END(808080, vblank_wait);

    PROF_BEGIN(4FC3F7, input);        /* Cyan: joystick & keyboard polling */
    read_input();
    PROF_END(4FC3F7, input);

    PROF_BEGIN(81C784, update);       /* Green: game simulation */
    update_world();
      PROF_BEGIN(FFB74D, physics);    /* Orange: nested physics calculations */
      run_physics();
      PROF_END(FFB74D, physics);
    PROF_END(81C784, update);

    PROF_BEGIN(E57373, render);       /* Red: VDP sprite and tile transfers */
    render_screen();
    PROF_END(E57373, render);
}

Instrumentation Rules and Semantics

The profiler macros operate by mapping the TMS9900 Program Counter (PC) against the symbol table emitted during compilation:

  1. Color syntax: The color argument must be six hexadecimal digits (RRGGBB) without a leading 0x or #. This color defines the visual band displayed in the IDE's flame chart.
  2. Label identifiers: The block name is a bare C token, not a string literal: write PROF_BEGIN(FF8800, render) rather than quotes.
  3. Strict pairing: Every PROF_BEGIN(col, name) invocation must be matched by a closing PROF_END(col, name) with an identical name and color tag.
  4. Proper nesting: Profiler blocks may be nested arbitrarily deep (for example, timing an inner algorithm inside a larger subsystem), but overlapping or interleaved blocks are invalid and will corrupt the profile stack.
  5. Frame delimitation: Call PROF_FRAME_END() exactly once per game iteration, typically at the top of your loop immediately before awaiting the vertical blank interrupt. The profiler counts hardware VDP interrupts between successive delimiters to calculate effective FPS.
  6. Accounting for idle time: Always wrap your vertical sync wait routine with a profiler block (conventionally colored grey 808080). This makes it easy to visualize your frame budget headroom: any time spent in vblank_wait represents unused CPU capacity.

Frame Budget and Hardware Clocking

The TMS9900 CPU in the TI-99/4A runs at a master frequency of 3.0 MHz, generated by dividing the console's 10.738635 MHz crystal by 3.58 via the TIM9904 clock driver. Under standard NTSC video timing, the screen refreshes at approximately 59.94 Hz. This establishes a fixed budget of approximately 50,065 CPU cycles per video frame:

Target Frame RateFrame PeriodTotal CPU Cycles AvailablePrimary Use Case
60 FPS (1 VSYNC)16.68 ms50,065 cyclesSmooth action games, scrolling platformers, shoot-'em-ups
30 FPS (2 VSYNCs)33.36 ms100,130 cyclesComplex simulations, RPGs, board games with heavy AI
20 FPS (3 VSYNCs)50.04 ms150,195 cycles3D wireframe renderers, raycasters, deep strategy games
15 FPS (4 VSYNCs)66.72 ms200,260 cyclesTurn-based adventure games, text-heavy engines

In the IDE's PRF tab, you can select your desired target frame rate from the dropdown (60, 30, 20, 15, or 10 FPS). The profiler renders two live charts:

  • FRAME PERFORMANCE PROFILER: A rolling 120-frame line chart plotting total CPU cycles per frame against a horizontal budget threshold line (100% of the target frame budget). When a frame exceeds the budget line, the indicator highlights the frame hitch. If your game misses the 50,065-cycle mark by even a single cycle, it waits for the next VSYNC pulse, dropping from 60 FPS to 30 FPS.
  • BLOCK BREAKDOWN: A per-frame stacked breakdown bar chart and legend showing the cycle count and percentage of the frame budget consumed by each instrumented PROF_BEGIN / PROF_END block (up to 10 color-coded blocks per frame).

Memory Architecture and Cycle Penalties

When analyzing profiler results, keep in mind that TMS9900 instruction cycle counts vary drastically depending on where code and data reside in memory:

  • 16-bit Scratchpad RAM (0x8300–0x83FF): Located directly on the CPU's internal 16-bit bus with zero wait states. A register-to-register operation like MOV R1, R2 executes in its baseline 14 clock cycles. Inner loops placed in scratchpad run at maximum hardware speed.
  • Cartridge ROM and 32K Expansion RAM: Connected through the TI-99/4A's multiplexed 8-bit bus. Every 16-bit word read or write requires two sequential 8-bit cycles, injecting 4 hardware wait states per word. The same MOV instruction accessing variables in expansion RAM takes substantially longer.
  • Cross-bank Trampolines: Direct calls across cartridge ROM banks require a trampoline stub in persistent RAM to latch the new bank register and restore the caller's bank upon return. This adds 12 to 24 cycles of overhead per call.

Optimization Strategies from Profiler Insights

When the PRF tab reveals that a specific block is consuming excessive cycles, apply these proven optimization steps:

  • Relocate hot functions: Mark the most cycle-intensive routines with #pragma bank scratchpad or tidepod add --scratchpad. Putting a 100-byte collision routine in scratchpad can save thousands of cycles per frame.
  • Eliminate trampoline thrashing: If the profiler shows high overhead in inter-module calls, place frequently called functions in persistent RAM (#pragma bank persistent) or consolidate tightly coupled functions into the same translation unit so they pack into a single ROM bank.
  • Precalculate complex math: Avoid software multiplication and division in per-frame loops. Use lookup tables for sine, cosine, screen offsets, and fixed-point physics.
  • Tune compiler optimization: Debug builds (make debug) compile with -O0, leaving local variables on the stack frame. Rebuilding with -Os or increasing optLevelDebug promotes variables into TMS9900 workspace registers (R0–R15), dramatically shrinking cycle counts.
The PRF (profiler) tab showing the 120-frame performance chart and per-block cycle breakdown.
The PRF (profiler) tab showing the 120-frame performance chart and per-block cycle breakdown.
Docs / Tools & Workflows

Headless testing and automation

CI · scripts

ti994a-emu can run without a window, type on the TI keyboard from a script and save screenshots. That is enough to check in a script or CI job that a build boots and reaches a given screen.

A boot test

Terminal
ti994a-emu --headless --cart mygame.rpk \
  --keys "WAIT:240 SPACE WAIT:90 2 WAIT:300" \
  --screenshot-at 600 --screenshot-path /tmp/boot.png --frames 660
  1. Wait 240 frames (4 s) for the title screen.
  2. Press Space to get to the cartridge menu, wait 1.5 s.
  3. Press 2 to start the second menu entry (your cartridge; entry 1 is TI BASIC), wait 5 s.
  4. Save a screenshot at frame 600 and exit at frame 660.

This goes through the same title screen and menu as a real user, which --autorun skips.

Key script syntax (--keys)

Tokens are separated by spaces or commas.

TokenMeaning
WAIT:nDo nothing for n frames (60 frames = 1 second).
HOLD:nHold the following keys down for n frames (default 6).
GAP:nRelease for n frames between the following keys (default 10).
ENTER SPACE SHIFT CTRL FCTN EQUAL PERIOD COMMA SLASH SEMINamed keys.
FCTN+E, CTRL+SHIFT+XCombinations with up to three modifiers.
2, R, qAny single key on the TI keyboard.

Keys go through the emulated keyboard matrix, exactly as if typed.

Live input (--key-fifo)

Terminal
mkfifo /tmp/k
ti994a-emu --cart mygame.rpk --key-fifo /tmp/k &
echo "SPACE WAIT:60 2" > /tmp/k

Screenshots

  • --screenshot-at 300,600,900 captures several frames; with more than one, the frame number is appended to the file name.
  • The default path is screenshot.png.
  • Images are cropped to the active display. In 80-column mode every scanline is doubled (512×384) so the pixels are square.

Making it a test

  • Look for illegal-opcode messages in the output: they mean the program jumped somewhere it shouldn't.
  • Compare the screenshot with a known-good reference image.
  • --dump-regs N gives you register and VRAM state at frame N as text, easy to grep. See Debugging.
Merged cartridges

If your cartridge image is placed behind other ROM banks (packer --bank-base), the bank numbers the emulator reports are offset from the ones in bank_report.json.

Docs / Tools & Workflows

Troubleshooting

FAQ

Symptoms you are likely to run into, and what to do about them.

Build

SymptomCause and fix
A warning stops the buildBuilds use -Werror. Fix the warning.
A header change has no effectObjects don't depend on your headers. Rebuild with make clean && make, or list the dependencies in Makefile.custom.
The packer reports a unit that doesn't fit in a bankOne source file has more than 8 KB of code and constant data. Split it. See Banking.
Changes to the .project file are ignoredRun tidepod sync.
malloc returns NULL immediatelyThe near-heap reservation defaults to 0 bytes; set "heapSize" in your .project file (or pass --heap-size <bytes> to tms9900-packer), use sams_malloc from <sams.h>, or use static buffers. See malloc(3).
Make warns about overriding recipesMakefile.custom redefines all or debug. Use POST_BUILD instead.

Running

SymptomCause and fix
tidepod run shows the old versionrun doesn't build. Run make first.
Works with --autorun but not from the menu (or the other way round)Test the real boot path with key injection; see Headless testing.
Crash or illegal-opcode flood after calling through a function pointerCalls through pointers are not bank-switched. Move the target function to persistent RAM. See Banking.
A string or table passed to another file reads as garbageIt points into a bank that is no longer mapped. Copy it first or move the table to a persistent file.
Random corruption that gets worse as the program growsStack overflow into .bss. Move large locals to static, check max_stack_depth and RAM headroom in bank_report.json.
Disk access corrupts the program or hangsScratchpad code overlaps the disk system's area. Use the +disk access (0x8380) preset in Project Settings. See Code placement.
Hard-disk image is refusedCHD images are not supported; extract a raw image with chdman extracthd. See Disks.
Text mode shows blanks or garbage instead of lettersti_text_mode sets up the mode but loads no font. Call ti_text_load_builtin_font() right after it, or copy your own font to 0x1000 with rom_to_vram.
The screen says 32K MEM REQUIRED!Banked cartridges need the 32K memory expansion. On real hardware, check that it is installed and switched on. For a console-only cartridge use the 8K project type.
Only 4 sprites per line on the F18ASet VR30 after unlocking; its reset value is 4. See F18A GPU code.

Debugging

SymptomCause and fix
No source lines in the debuggerBuild with make debug (F5 in the IDE).
GDB stops at PC=0024That's the reset vector; continue.
GDB shows nonsense for VRAM addressesx/ reads CPU memory. Use the VDP tab or --dump-regs.
Logpoints print nothingBuild with make debug (release defines -DNDEBUG and strips them). They fire in the IDE debugger and in standalone ti994a-emu when DWARF / --debug-dwarf is loaded. Match is physical cart bank + address in the cart window.
Chapter 6

API Reference

Docs / API Reference

API Reference

157 man pages

Every page in this section is generated from the man pages shipped with Tidepod (resources/man), so it always matches the library you have installed. The same pages are available offline in the IDE and with man. 157 pages are listed below; use the filter or the tree.

Function(s)PageDescription
cgetc, kbhit, getcharcgetc(3)keyboard and joystick 1 input
conioconio(3)console cursor I/O (cc65/libti99-shaped)
cputc, cputs, cprintf, clrscrcputc(3)console output at cursor
gotoxy, gotox, gotoy, wherex, whereygotoxy(3)console cursor position
fclosefclose(3)close a disk stream
fcopy_path, fcopy_path_pg, fcopy_path_typedfcopy_path(3)bit-preserving file copy via fopen family
fgetcfgetc(3)read a character from a stream
fgetsfgets(3)read a line from a stream
fopen, fclose, fread, fwrite, fflush, feof, ferror, clearerr, vdp_load_file, vdp_save_file, fcopy_pathfopen(3)disk file streams (DSR / AU)
fprintffprintf(3)formatted output (see printf)
fputcfputc(3)write a character to a stream
fputsfputs(3)write a string to a stream
fread, fwritefread(3)stream I/O (record or PROGRAM AU cache)
fseek, ftell, rewindfseek(3)reposition a disk stream
ftellftell(3)report stream position
fwritefwrite(3)write to a stream
printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, vsnprintfprintf(3)formatted output
putcharputchar(3)output a character to standard output
putsputs(3)output a line to standard output
snprintfsnprintf(3)formatted output (see printf)
sprintfsprintf(3)formatted output (see printf)
sscanf, scanfsscanf(3)formatted input (minimal)
stdio_enable_chip, stdio_enable_fat, stdio_enable_wds, stdio_enable_prog, stdio_enable_all_diskstdio_enable(3)opt-in native disk backends for fopen
stdio_enable_all_diskstdio_enable_all_disk(3)enable every optional fopen disk backend
stdio_enable_chipstdio_enable_chip(3)enable TI chip FS stdio backend for DSK*
stdio_enable_fatstdio_enable_fat(3)enable FAT12 HFDC stdio backend for DSK*
stdio_enable_progstdio_enable_prog(3)enable DSR PROGRAM AU byte-stream backend
stdio_enable_wdsstdio_enable_wds(3)enable HFDC WDS* chip stdio backend
stdio_last_errorstdio_last_error(3)last disk/DSR error code from Tidepod libc
stdio_set_vdp_basestdio_set_vdp_base(3)set the VDP RAM base address for Level-3 disk PABs and record buffers
stdio_set_wds_vdp_buf, stdio_get_wds_vdp_bufstdio_set_wds_vdp_buf(3)choose HFDC/WDS Level-2 sector buffer in VRAM
ti_text_mode, ti_text_load_builtin_fontti_text_mode(3)select console text geometry and load a default font
remove, unlink, renameremove(3)delete or rename a disk file
ti_dsr_enum, ti_dsr_enum_exti_dsr_enum(3)list catalogable DSR unit names via CRU scan
ti_opendir, ti_readdir, ti_closedir, ti_dir_volume, opendir, readdir, closedirti_opendir(3)TI disk catalog and POSIX directory wrappers
ti_stat, ti_protect, ti_mkdir, ti_rmdirti_stat(3)file metadata and directory mutate helpers
ti_vdp_detect, ti_vdp_text80_ok, ti_vdp_has_attrs, ti_vdp_has_gpu, console_gpu_invalidate, ti_load_ega_palette, ti_load_tms9918_paletteti_vdp_detect(3)detect F18A / Pico9918 capabilities and manage VDP palette / GPU state
resource_copy, unwrap, rom_to_vram, rom_to_ram, rom_to_vram_ex, rom_to_ram_exresource_copy(3)banked cartridge asset pipeline and copy API
rom_to_vram, rom_to_ram, rom_to_vram_ex, rom_to_ram_ex, unwraprom_to_vram(3)copy banked cartridge ROM resources into VRAM or CPU RAM
sams_init, sams_present, sams_page_count, sams_map, sams_get, sams_ptr, sams_page_of, sams_offset_of, sams_add, sams_lock, sams_unlock, sams_read8, sams_write8, sams_read16, sams_write16, sams_memcpy_from, sams_memcpy_to, sams_memset, sams_malloc, sams_free, sams_calloc, sams_realloc, sams_get_free_heap, __sams_load_qi, __sams_store_qi, __sams_load_hi, __sams_store_hisams(3)SuperAMS mapper helpers, fat pointers, fat heap, and __sams address space
debug, __dbg_printf, BRKdebug(3)zero-cost host-evaluated debug logpoints, ANSI trace styling, and soft breakpoints
profiler, PROF_FRAME_END, PROF_BEGIN, PROF_ENDprofiler(3)zero-cost cycle profiler annotations for the Tidepod IDE
f18a_gpu, F18A_GPU_IDLE, F18A_GPU_MMIO8, F18A_GPU_MMIO16f18a_gpu(3)GPU-side freestanding definitions for F18A / Pico9918 coprocessor programs
f18a_gpu_load_at, f18a_gpu_start, f18a_gpu_stop, f18a_gpu_load_and_startf18a_gpu_host(3)host-side control and VRAM loader for the F18A / Pico9918 GPU coprocessor
memchrmemchr(3)locate byte in byte string
memcmpmemcmp(3)compare byte strings
memcpymemcpy(3)copy memory
memmovememmove(3)copy memory (overlap-safe)
memsetmemset(3)fill memory with a byte
strcatstrcat(3)concatenate strings
strcmpstrcmp(3)compare strings
strcpystrcpy(3)copy a string
strlenstrlen(3)string length
strncatstrncat(3)concatenate strings with length limit
strncmpstrncmp(3)compare strings with length limit
strncpystrncpy(3)copy a string with length limit
strnlenstrnlen(3)bounded string length
strstrstrstr(3)locate a substring in a string
strtokstrtok(3)string tokens
ctype, isalnum, isalpha, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit, tolower, toupperctype(3)character classification and case conversion functions
isalnumisalnum(3)alphanumeric character test
isalphaisalpha(3)alphabetic character test
iscntrliscntrl(3)control character test
isdigitisdigit(3)decimal-digit character test
isgraphisgraph(3)printing character test (excluding space)
islowerislower(3)lower-case character test
isprintisprint(3)printing character test (including space)
ispunctispunct(3)punctuation character test
isspaceisspace(3)white-space character test
isupperisupper(3)upper-case character test
isxdigitisxdigit(3)hexadecimal-digit character test
tolowertolower(3)upper case to lower case letter conversion
touppertoupper(3)lower case to upper case letter conversion
abortabort(3)abnormal program termination
absabs(3)integer absolute value
atoi, atolatoi(3)convert string to integer
atolatol(3)convert string to long
calloccalloc(3)allocate zero-initialized near-heap memory in high 32K expansion
exit, _Exitexit(3)halt the program
freefree(3)free near-heap memory in high 32K expansion
malloc, free, calloc, realloc, mallinfo, get_free_heap, malloc_walkmalloc(3)near-heap allocator in high 32K expansion
qsortqsort(3)sort an array
rand, srandrand(3)simple pseudo-random number generator
reallocrealloc(3)resize near-heap allocation in high 32K expansion
strtol, strtoul, atoi, atolstrtol(3)convert string to integer
strtoulstrtoul(3)convert string to unsigned long
errnoerrno(3)system and library error numbers
atanfatanf(3)inverse tangent (float)
floorf, ceilfceilf(3)floor and ceiling functions (float)
sinf, cosf, tanfcosf(3)trigonometric functions (float)
expfexpf(3)exponential function (float)
fabsffabsf(3)absolute value (float)
floorf, ceilffloorf(3)floor and ceiling functions (float)
fmodffmodf(3)floating-point remainder
logflogf(3)natural logarithm (float)
powfpowf(3)power function (float)
sinf, cosf, tanfsinf(3)trigonometric functions (float)
sqrtfsqrtf(3)square root (float)
sinf, cosf, tanftanf(3)trigonometric functions (float)
libclibc(3)TI-99/4A C library overview
SAMS_FAR, SAMS_FAR_PTR, SAMS_FAR_OBJ, sams_new, sams_new_bytes, sams_delete, SAMS_WITH_NEARsams_far(3)optional syntactic sugar for SuperAMS __sams pointers
ASCasc(3xb)return ASCII code of a string's first character (not implemented yet)
CHARchar(3xb)redefine a character's graphical pattern
CHARSETcharset(3xb)restore standard character patterns
CHR$chr(3xb)return character corresponding to ASCII code (not implemented yet)
CLEARclear(3xb)clear the screen and reset the VDP cursor
COINCcoinc(3xb)detect collisions between sprites or dots
COLORcolor(3xb)define foreground and background colors for a character set
DELSPRITEdelsprite(3xb)delete a specific sprite or all active sprites
DISPLAY ATdisplay_at(3xb)print text at a specific screen location
DISTANCEdistance(3xb)compute the squared distance between two sprites
GCHARgchar(3xb)read the character code at a screen position
HCHARhchar(3xb)draw a horizontal line of characters
INITinit(3xb)initialize Extended BASIC expansion state
JOYSTjoyst(3xb)read joystick directional input
KEYkey(3xb)scan the keyboard or joysticks for input
LENlen(3xb)return the length of a string (not implemented yet)
LOADload(3xb)write bytes into CPU RAM (not implemented yet)
LOCATElocate(3xb)move an existing sprite to a new row and column
MAGNIFYmagnify(3xb)set the global sprite magnification factor
MOTIONmotion(3xb)update the row and column velocities of a sprite
PATTERNpattern(3xb)change the character pattern used by a sprite
PEEKpeek(3xb)read a 16-bit word from CPU memory
PEEKBpeekb(3xb)read a single unsigned byte from CPU memory
PEEKVpeekv(3xb)read a byte from VDP (Video) RAM
POKEpoke(3xb)write a 16-bit word to CPU memory
POKEBpokeb(3xb)write a single byte to CPU memory
POKEVpokev(3xb)write a byte directly into VDP (Video) RAM
POSITIONposition(3xb)read the current screen coordinates of a sprite
RNDrnd(3xb)generate a pseudo-random float via CALL RND
SCREENscreen(3xb)set the background screen color
SEG$seg(3xb)extract a substring from a string (not implemented yet)
SOUNDsound(3xb)play sounds/noise through the SN76489 sound chip
SOUND_LISTsound_list(3xb)play an asynchronous VDP/ROM sound list
SOUND_STOPsound_stop(3xb)stop active asynchronous sound or sound list playback
SPRITEsprite(3xb)define and display a sprite
STR$str(3xb)convert numeric value to string (not implemented yet)
VALval(3xb)convert string to numeric value (not implemented yet)
VCHARvchar(3xb)draw a vertical line of characters
VDPMEMCPYvdpmemcpy(3xb)bulk copy ROM/CPU data to VDP RAM
VDPMEMSETvdpmemset(3xb)fill a block of VDP RAM with a byte value
VDPREADvdpread(3xb)read a single byte from VDP RAM
VSYNCvsync(3xb)halt execution until the next VDP vertical blanking interrupt
xb-controlxb-control(7)XB BASIC control flow statements (partial)
xb-dataxb-data(7)XB BASIC DATA, READ, RESTORE, and BYTES directives
xb-inputxb-input(7)XB BASIC joystick, keyboard, and timing commands
xb-ioxb-io(7)XB BASIC print, display, and input statements (partial)
xb-mathxb-math(7)XB BASIC built-in numeric functions (partial)
xb-miscxb-misc(7)XB BASIC miscellaneous statements and directives (partial)
xb-screenxb-screen(7)XB BASIC screen, color, and character definition commands
xb-soundxb-sound(7)XB BASIC sound generation commands (partial)
xb-spritesxb-sprites(7)XB BASIC sprite creation, movement, and collision commands
xb-stringxb-string(7)XB BASIC built-in string functions (partial)
xb-subxb-sub(7)XB BASIC subroutine definition and invocation
xb-tilesxb-tiles(7)XB BASIC tile placement and reading commands
xb-variablesxb-variables(7)XB BASIC variable types, arrays, and declarations
xb-vdpxb-vdp(7)XB BASIC VDP memory access and bulk transfer commands
Docs / API Reference / Console & keyboard (conio.h)

cgetc, kbhit, getchar

cgetc(3)

keyboard and joystick 1 input

NAME

cgetc, kbhit, getchar — keyboard and joystick 1 input

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <conio.h>

unsigned char
cgetc(void);

unsigned char
kbhit(void);

#include <stdio.h>

int
getchar(void);

DESCRIPTION

CRU matrix scan with edge detection. kbhit() is nonzero when a new key (or joystick) edge is available. cgetc() blocks until input arrives and returns KEY_* codes or ASCII. getchar() returns EOF if nothing is waiting, otherwise the same codes.

Direction

  • Fctn-E / Fctn-S / Fctn-D / Fctn-X map to KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_DOWN.
  • Joystick 1 (and host arrow keys in the Tidepod emu) map to the same KEY_* values. Joystick fire maps to KEY_TAB (pane-switch convention for apps like fileman).

Common chords

Fctn-=
KEY_ESC (TI QUIT)
Fctn-1
KEY_DEL (0x7F, TI DEL)
Fctn-6
KEY_TAB (TI PROC'D)
Ctrl-H
KEY_BS (0x08, Backspace)
Ctrl-I
KEY_TAB
Ctrl-C
KEY_ESC

Held keys support VSync-paced auto-repeat after an initial delay. Plain digit and letter keys return ASCII (e.g. 3, 5, Q). Fctn+digit is not translated to KEY_F1 ... KEY_F5; prefer plain numerics for app commands.

SEE ALSO

conio(3)

Source: resources/man/man3/cgetc.3

Docs / API Reference / Console & keyboard (conio.h)

conio

conio(3)

console cursor I/O (cc65/libti99-shaped)

NAME

conio — console cursor I/O (cc65/libti99-shaped)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <conio.h>

DESCRIPTION

Addressable console functions sharing state with putchar(3) / printf(3). Coordinates are 0-based. Use conio for panel UIs; avoid mixing with streaming printf() on the same screen.

Absolute draws (cputcxy, cputsxy, cclearxy, chlinexy, cvlinexy) clip at the screen edge and do not wrap or scroll (safe for dual-pane UIs). Streaming cputc() / putchar() still wrap and scroll.

chline() / cvline() emit CP437 box-drawing codes (CH_HLINE, CH_VLINE, CH_DHLINE, CH_DVLINE, corners/tees, etc.) so the pattern descriptor table must include those glyphs (e.g. fileman's 6x8 box set in the 5x8 font resource).

Additional helpers declared in <conio.h>:

  • Clearing and positioning: clrscr(), clreol(), cclear(), cclearxy(), gotoxy(), gotox(), gotoy(), wherex(), wherey(), screensize().
  • Text and line output: cputc(), cputcxy(), cputs(), cputsxy(), cprintf(), vcprintf() (128-byte stack format buffer), chline(), chlinexy(), cvline(), cvlinexy().
  • Rectangle scroll: cscrollu(), cscrolld() (F18A/Pico9918 GPU blit or host VDP burst fallback).
  • Colors and per-cell F18A/Pico9918 attributes: textcolor(), bgcolor(), bordercolor(), reverse(), cattrxy(), cattr_row(), cputsxy_attr(), console_attr_pack(), console_attr_set_default(), console_attrs_refresh(), console_attrs_enable(), console_attrs_disable().

API inspired by Tursi's public-domain libti99 conio; reimplemented on Tidepod libc.

SEE ALSO

gotoxy(3), cputc(3), cgetc(3), ti_text_mode(3)

Source: resources/man/man3/conio.3

Docs / API Reference / Console & keyboard (conio.h)

cputc, cputs, cprintf, clrscr

cputc(3)

console output at cursor

NAME

cputc, cputs, cprintf, clrscr — console output at cursor

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <conio.h>

void
cputc(int ch);

void
cputs(const char *s);

int
cprintf(const char *fmt, ...);

void
clrscr(void);

DESCRIPTION

Write at the current cursor with wrap/scroll like putchar(3).

SEE ALSO

conio(3), gotoxy(3)

Source: resources/man/man3/cputc.3

Docs / API Reference / Console & keyboard (conio.h)

gotoxy, gotox, gotoy, wherex, wherey

gotoxy(3)

console cursor position

NAME

gotoxy, gotox, gotoy, wherex, wherey — console cursor position

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <conio.h>

void
gotoxy(int x, int y);

void
gotox(int x);

void
gotoy(int y);

int
wherex(void);

int
wherey(void);

DESCRIPTION

0-based cursor. Clamped to the current screensize().

SEE ALSO

conio(3)

Source: resources/man/man3/gotoxy.3

Docs / API Reference / Standard I/O & disk (stdio.h)

fcopy_path, fcopy_path_pg, fcopy_path_typed

fcopy_path(3)

bit-preserving file copy via fopen family

NAME

fcopy_path, fcopy_path_pg, fcopy_path_typed — bit-preserving file copy via fopen family

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

int
fcopy_path(const char *src, const char *dst);

int
fcopy_path_pg(const char *src, const char *dst);

int
fcopy_path_typed(const char *src, const char *dst, int ti_type, unsigned reclen);

DESCRIPTION

fcopy_path() probes src (same FDR path as) fopen() on an existing file , opens dst with a matching create mode (e.g. wb:pg, wb:if:64, w:dv:80), and copies with fread() / fwrite() only. No VDP LOAD/SAVE.

fcopy_path_pg() copies a PROGRAM (:pg) file directly using only two pointer arguments, which is safe across banked cartridge trampolines.

fcopy_path_typed() copies src to dst using a caller-supplied TI catalog type ti_type (TI_DF, TI_DV, TI_IF, TI_IV, or TI_PG) and record length reclen (e.g. from ti_readdir(3)) without re-probing the source FDR.

RETURN VALUES

Returns 0 on success, -1 on failure. Check stdio_last_error(3) first (DSR status); errno may also be set by some backends.

SEE ALSO

fopen(3), stdio_last_error(3), stdio_enable(3), remove(3)

Source: resources/man/man3/fcopy_path.3

Docs / API Reference / Standard I/O & disk (stdio.h)

fgetc

fgetc(3)

read a character from a stream

NAME

fgetc — read a character from a stream

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

int
fgetc(FILE *stream);

DESCRIPTION

Reads one byte from stream. On stdin it uses the console keyboard path. On a disk stream it is implemented via fread() and inherits that stream's record type and buffering (DISPLAY/VARIABLE newlines, FIXED records, PROGRAM AU, chip/FAT/WDS backends); see fopen(3).

RETURN VALUES

The byte as an unsigned char cast to int, or EOF on end-of-file or error.

SEE ALSO

fgets(3), fread(3), fopen(3)

Source: resources/man/man3/fgetc.3

Docs / API Reference / Standard I/O & disk (stdio.h)

fgets

fgets(3)

read a line from a stream

NAME

fgets — read a line from a stream

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

char *
fgets(char *s, int n, FILE *stream);

DESCRIPTION

Reads at most n−1 bytes into s, stopping at newline or EOF, and NUL-terminates the buffer. On disk streams this uses fread() with the same buffering and DISPLAY VARIABLE newline rules as fopen(3).

RETURN VALUES

s on success, or NULL on end-of-file or error before any data is read.

SEE ALSO

fgetc(3), fread(3), fopen(3)

Source: resources/man/man3/fgets.3

Docs / API Reference / Standard I/O & disk (stdio.h)

fopen, fclose, fread, fwrite, fflush, feof, ferror, clearerr, vdp_load_file, vdp_save_file, fcopy_path

fopen(3)

disk file streams (DSR / AU)

NAME

fopen, fclose, fread, fwrite, fflush, feof, ferror, clearerr, vdp_load_file, vdp_save_file, fcopy_path — disk file streams (DSR / AU)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

FILE *
fopen(const char *path, const char *mode);

int
fclose(FILE *stream);

size_t
fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

size_t
fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

int
fflush(FILE *stream);

int
feof(FILE *stream);

int
ferror(FILE *stream);

void
clearerr(FILE *stream);

int
vdp_load_file(const char *path, uint16_t vdp_addr);

int
vdp_save_file(const char *path, const uint8_t *src, uint16_t len);

int
fcopy_path(const char *src, const char *dst);

DESCRIPTION

Paths are TI device names such as “DSK1.MYFILE” or “WDS1.DIR.FILE”.

fopen() mode grammar:

mode := access [ "b" ] [ "+" ] [ ":" type [ ":" reclen ] ]
access := "r" | "w" | "a"
type := "df" | "dv" | "if" | "iv" | "pg"

Existing files: FDR probe always wins for type and record length. A :type[:reclen] suffix on open is ignored so helpers can reuse one mode builder.

Create defaults:

  • no b → DISPLAY/VARIABLE 80 (w) creates DV80
  • b present → INTERNAL/FIXED 128 (wb) creates IF128
  • explicit :df|:dv|:if|:iv|:pg[:reclen] overrides the b defaults (e.g. wb:df:80, wb:pg, wb:if:64)

b on create without a type selects INTERNAL/FIXED 128. On an existing DISPLAY file (df / dv), plain r / rb applies record→newline text munging. Opaque DISPLAY I/O requires an explicit type with b (e.g. rb:df:80, wb:dv:80). fcopy_path always uses typed opaque modes for bit-identical copies. For text lines (fprintf(), fputs()) with newline record boundaries, open w or w:dv:80 (not wb:dv:…), which treats newlines as data.

PROGRAM (pg) uses an AU/sector byte stream inside libc. Each FILE carries a STDIO_SECTOR_BUF (128-byte) FILE.sector_buf cache with buf_pos / buf_len. Apps never issue LOAD/SAVE for copy or normal read/write. Record files (df/dv/if/iv) use Level-3 READ/WRITE; libc caches one record (up to 128 bytes in sector_buf) so a one-byte fread() does not re-hit the DSR every time.

Paths and mode are copied into stack scratch at entry (up to TI_PATH_MAX) / STDIO_MODE_MAX so a later cart-bank trampoline cannot invalidate a caller pointer. Banked callers should keep mode strings in RAM (not banked .rodata).

At most STDIO_MAX_FILES (3) simultaneous disk FILE objects are supported.

Optional backends: by default fopen() uses Level-3 DSR PAB only (classic floppy DSK*) Native chip FS, FAT12, WDS*, and DSR PROGRAM-AU streams are opt-in so game carts do not pull their .bss from libc.a. Call stdio_enable_chip(3), stdio_enable_fat(3), stdio_enable_wds(3), and/or stdio_enable_prog(3) (or) stdio_enable_all_disk(3) before disk I/O when those paths are required. See stdio_enable(3).

HFDC/WDS Level-2 AU I/O uses a 256-byte VRAM sector buffer (default 0x3DA8), high under FILES . Call stdio_set_wds_vdp_buf(3) if that window overlaps your screen, attributes, or PAB arena (fileman parks it at 0x3600); Text80 attrs live at >2000, pattern generator table at >0800.

feof() and ferror() return nonzero when the stream end-of-file or error indicator is set; clearerr() clears both indicators on stream.

vdp_load_file() and vdp_save_file() issue classic Level-3 DSR LOAD (opcode 5) and SAVE (opcode 6) for PROGRAM images directly to/from VDP RAM at vdp_addr (or copying len bytes from CPU RAM src via VDP) using the PAB arena at stdio_vdp_base.

fcopy_path() copies src to dst using only fopen(/) fread(/) fwrite(/) fclose() (probes source type; bit-preserving for probed kinds); see fcopy_path(3).

stdin, stdout, and stderr are console sentinels, not disk files.

RETURN VALUES

fopen() returns a FILE * or NULL on failure. fread() / fwrite() return the number of complete elements transferred. fcopy_path() returns 0 on success, -1 on failure.

ERRORS

On fopen() / fcopy_path() failure, call stdio_last_error(3) for the DSR-style status (primary signal). errno may also be set by native backends (chip / FAT / WDS) but is often left unchanged after classic PAB/DSR failures — do not rely on errno alone.

SEE ALSO

stdio_last_error(3), fgetc(3), fseek(3), remove(3), stdio_enable(3), stdio_set_wds_vdp_buf(3), ti_opendir(3), printf(3)

Source: resources/man/man3/fopen.3

Docs / API Reference / Standard I/O & disk (stdio.h)

fprintf

fprintf(3)

formatted output (see printf)

NAME

fprintf — formatted output (see printf)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

See printf(3).

DESCRIPTION

TI-99/4A fprintf is documented with the printf(3) family. asprintf() is not provided.

SEE ALSO

printf(3)

Source: resources/man/man3/fprintf.3

Docs / API Reference / Standard I/O & disk (stdio.h)

fputc

fputc(3)

write a character to a stream

NAME

fputc — write a character to a stream

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

int
fputc(int c, FILE *stream);

DESCRIPTION

Writes the low 8 bits of c to stream. On stdout / stderr this goes through putchar(). On a disk stream it uses fwrite() and the stream's record/AU buffering (see fopen(3)). A newline on a DISPLAY VARIABLE text stream ends the current record.

RETURN VALUES

c on success, or EOF on error.

SEE ALSO

fputs(3), fwrite(3), fopen(3)

Source: resources/man/man3/fputc.3

Docs / API Reference / Standard I/O & disk (stdio.h)

fputs

fputs(3)

write a string to a stream

NAME

fputs — write a string to a stream

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

int
fputs(const char *s, FILE *stream);

DESCRIPTION

Writes the NUL-terminated string s to stream without appending a newline. On stdout / stderr each character goes through putchar(). On disk streams the string is written with fwrite() (same buffering and DISPLAY VARIABLE newline rules as) fopen(3).

For one record per line on DISPLAY VARIABLE files, open with w or w:dv:80 and include \n in the string (or call) fputs() then write a lone newline. Do not use wb:dv:… for text; that mode keeps newlines as opaque bytes.

RETURN VALUES

Returns 0 on success, or EOF on error.

SEE ALSO

fopen(3), fwrite(3), fprintf(3), putchar(3)

Source: resources/man/man3/fputs.3

Docs / API Reference / Standard I/O & disk (stdio.h)

fread, fwrite

fread(3)

stream I/O (record or PROGRAM AU cache)

NAME

fread, fwrite — stream I/O (record or PROGRAM AU cache)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

size_t
fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

size_t
fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

DESCRIPTION

Transfer size × nmemb bytes to/from stream. Bytes come from FILE.sector_buf (STDIO_SECTOR_BUF, 128 bytes) when the cache still has unread data; otherwise libc fills the next Level-3 record or PROGRAM AU chunk and continues. A one-byte fread() does not re-read the disk sector every call.

DISPLAY streams without b may map newlines to VARIABLE record boundaries. INTERNAL / b / PROGRAM streams are opaque byte streams.

See fopen(3).

SEE ALSO

fopen(3), fgetc(3), fseek(3)

Source: resources/man/man3/fread.3

Docs / API Reference / Standard I/O & disk (stdio.h)

fseek, ftell, rewind

fseek(3)

reposition a disk stream

NAME

fseek, ftell, rewind — reposition a disk stream

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

int
fseek(FILE *stream, long offset, int whence);

long
ftell(FILE *stream);

void
rewind(FILE *stream);

DESCRIPTION

fseek() repositions a disk FILE. Console streams are not seekable.

Native backends (chip, FAT12, WDS, PROGRAM-AU) implement byte seeks when available. The default Level-3 PAB path supports SEEK_SET and SEEK_CUR by issuing RESTORE and discarding bytes with fread() (record-oriented; not a random FIXED-128 map). SEEK_END is not supported and fails with EINVAL.

rewind() is fseek(stream, 0, SEEK_SET) and clears the error indicator. ftell() reports the current logical byte offset when the backend tracks it.

RETURN VALUES

fseek() returns 0 on success, nonzero on failure. ftell() returns the offset, or -1 on error.

SEE ALSO

fopen(3), fread(3)

Source: resources/man/man3/fseek.3

Docs / API Reference / Standard I/O & disk (stdio.h)

printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, vsnprintf

printf(3)

formatted output

NAME

printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, vsnprintf — formatted output

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

int
printf(const char *fmt, ...);

int
fprintf(FILE *stream, const char *fmt, ...);

int
sprintf(char *str, const char *fmt, ...);

int
snprintf(char *str, size_t size, const char *fmt, ...);

int
vprintf(const char *fmt, va_list ap);

int
vfprintf(FILE *stream, const char *fmt, va_list ap);

int
vsprintf(char *str, const char *fmt, va_list ap);

int
vsnprintf(char *str, size_t size, const char *fmt, va_list ap);

DESCRIPTION

Subset of ISO C printf() for the TI-99/4A.

printf() and vprintf() write to the VDP nametable via the console cursor (see putchar(3)). Call ti_text_mode() first to select 32, 40, or 80 columns. fprintf() / vfprintf() to stdout / stderr use the same path; disk FILE * streams format into a 128-byte stack buffer (truncating at 127 characters per call) and emit via fputc(3) (as do cprintf(and) vcprintf(in) conio(3)).

Supported conversions: %s %c %d %i %u %x %X %p %%, plus length modifier l for 32-bit long integers (%ld %li %lu %lx %lX). Field width is supported for strings and integers, and the - flag left-aligns %s fields. Precision (.digits) and flags +, space, 0, and # are parsed and ignored.

Not supported: %f %e %g, asprintf(), positional %n$, and length modifiers other than a single l.

TYPE MODEL

int and size_t are 16-bit; long is 32-bit.

RETURN VALUES

Number of characters emitted (or that would be emitted for snprintf()), not counting a trailing NUL written into string buffers.

SEE ALSO

putchar(3), puts(3), sprintf(3)

Source: resources/man/man3/printf.3

Docs / API Reference / Standard I/O & disk (stdio.h)

putchar

putchar(3)

output a character to standard output

NAME

putchar — output a character to standard output

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

int
putchar(int c);

DESCRIPTION

The putchar() function writes the character c (converted to an unsigned char) to the standard output stream.

On the TI-99/4A, standard output is the VDP display. Characters are written to the current cursor position in VRAM and the cursor advances.

RETURN VALUES

The putchar() function returns the character written. If a write error occurs, it returns EOF.

SEE ALSO

puts(3), printf(3), fputc(3)

STANDARDS

The putchar() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/putchar.3

Docs / API Reference / Standard I/O & disk (stdio.h)

puts

puts(3)

output a line to standard output

NAME

puts — output a line to standard output

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

int
puts(const char *s);

DESCRIPTION

The puts() function writes the string s, and a terminating newline character, to the standard output stream.

On the TI-99/4A, standard output is the VDP display.

RETURN VALUES

The puts() function returns a non-negative integer on success and EOF on failure.

SEE ALSO

putchar(3), printf(3), fputs(3)

STANDARDS

The puts() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/puts.3

Docs / API Reference / Standard I/O & disk (stdio.h)

snprintf

snprintf(3)

formatted output (see printf)

NAME

snprintf — formatted output (see printf)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

See printf(3).

DESCRIPTION

TI-99/4A snprintf is documented with the printf(3) family. asprintf() is not provided.

SEE ALSO

printf(3)

Source: resources/man/man3/snprintf.3

Docs / API Reference / Standard I/O & disk (stdio.h)

sprintf

sprintf(3)

formatted output (see printf)

NAME

sprintf — formatted output (see printf)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

See printf(3).

DESCRIPTION

TI-99/4A sprintf is documented with the printf(3) family. asprintf() is not provided.

SEE ALSO

printf(3)

Source: resources/man/man3/sprintf.3

Docs / API Reference / Standard I/O & disk (stdio.h)

sscanf, scanf

sscanf(3)

formatted input (minimal)

NAME

sscanf, scanf — formatted input (minimal)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

int
sscanf(const char *str, const char *fmt, ...);

int
scanf(const char *fmt, ...);

DESCRIPTION

sscanf() parses characters from str according to the minimal conversion specifiers: %d %i %u %x %X %s %c %%

  • %d and %i both parse signed base-10 integers (use %x / %X for hexadecimal).
  • A space in fmt matches literal single space characters in str.
  • %s copies non-space characters up to the next space or NUL terminator.
  • %c reads the next character without skipping spaces.

scanf() is a stub that always returns 0 without reading input; use cgetc(3) or fgets(3) followed by sscanf() instead.

Not implemented: field widths, length modifiers, positional %n$, and floating conversions (%f %e %g).

RETURN VALUES

Number of assigned input items. Empty or unmatched input in sscanf() returns 0 (not EOF). scanf() always returns 0.

SEE ALSO

cgetc(3), fgets(3), getchar(3), printf(3)

Source: resources/man/man3/sscanf.3

Docs / API Reference / Standard I/O & disk (stdio.h)

stdio_enable

stdio_enable(3)

opt-in native disk backends for fopen

NAME

stdio_enable_chip, stdio_enable_fat, stdio_enable_wds, stdio_enable_prog, stdio_enable_all_disk — opt-in native disk backends for fopen

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

void
stdio_enable_chip(void);

void
stdio_enable_fat(void);

void
stdio_enable_wds(void);

void
stdio_enable_prog(void);

void
stdio_enable_all_disk(void);

DESCRIPTION

By default, fopen(3) uses Level-3 DSR PAB I/O only (classic DSK1.NAME) paths . That keeps game carts slim: unused chip / FAT / WDS / PROGRAM-AU translation units are not pulled from libc.a into upper RAM.

Apps that need the native backends must call one or more of these enable routines before disk I/O (typically before) stdio_disk_init() or the first fopen():

stdio_enable_chip()
TIFDC / HFDC floppy DSK* via ti_fs_chip (no Level-3 PAB).
stdio_enable_fat()
FAT12 volumes on HFDC DSK* (opaque byte stream).
stdio_enable_wds()
HFDC hard WDS* via chip AU streams (also installs the optional HFDC face poke used before PAB opens).
stdio_enable_prog()
DSR PROGRAM files as AU byte streams (:pg) and untyped fall-through to PROGRAM .
stdio_enable_all_disk()
Convenience for file managers and disk tests: enables chip, FAT, WDS, and PROGRAM. Lives in its own archive member so games that never call it do not pull those backends.

Each stdio_enable_*() registers function pointers used by fopen() / fread() / fwrite() / fseek() Calling an enable pulls that backend’s .text and .bss from the archive; call only what you need.

Games that only save/load on a classic floppy DSR should call none of these (e.g. Commander Keen). Fileman and the disk suite examples call stdio_enable_all_disk().

RETURN VALUES

None.

SEE ALSO

fopen(3), stdio_set_wds_vdp_buf(3), fcopy_path(3), ti_opendir(3)

Source: resources/man/man3/stdio_enable.3

Docs / API Reference / Standard I/O & disk (stdio.h)

stdio_enable_all_disk

stdio_enable_all_disk(3)

enable every optional fopen disk backend

NAME

stdio_enable_all_disk — enable every optional fopen disk backend

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

void
stdio_enable_all_disk(void);

DESCRIPTION

Calls stdio_enable_chip(), stdio_enable_fat(), stdio_enable_wds(), and stdio_enable_prog(). Use in file managers and disk test carts. Do not call from RAM-tight games that only need Level-3 PAB fopen(); this symbol lives in its own archive member so omitting the call keeps chip / WDS .bss out of the link.

Full backend overview: stdio_enable(3).

SEE ALSO

stdio_enable(3), fopen(3)

Source: resources/man/man3/stdio_enable_all_disk.3

Docs / API Reference / Standard I/O & disk (stdio.h)

stdio_enable_chip

stdio_enable_chip(3)

enable TI chip FS stdio backend for DSK*

NAME

stdio_enable_chip — enable TI chip FS stdio backend for DSK*

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

void
stdio_enable_chip(void);

DESCRIPTION

Registers the ti_fs_chip path matcher and stream ops so fopen(3) can open TIFDC / HFDC floppy DSK* paths without Level-3 PAB. Call once at startup before disk I/O. Pulls chip FS .bss into upper RAM; omit on carts that only need classic DSR PAB.

Full backend overview: stdio_enable(3).

SEE ALSO

stdio_enable(3), stdio_enable_all_disk(3), fopen(3)

Source: resources/man/man3/stdio_enable_chip.3

Docs / API Reference / Standard I/O & disk (stdio.h)

stdio_enable_fat

stdio_enable_fat(3)

enable FAT12 HFDC stdio backend for DSK*

NAME

stdio_enable_fat — enable FAT12 HFDC stdio backend for DSK*

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

void
stdio_enable_fat(void);

DESCRIPTION

Registers the FAT12 path matcher and stream ops so fopen(3) can open HFDC DSK* volumes formatted as FAT12 (opaque byte stream). Call once at startup before disk I/O.

Full backend overview: stdio_enable(3).

SEE ALSO

stdio_enable(3), stdio_enable_all_disk(3), fopen(3)

Source: resources/man/man3/stdio_enable_fat.3

Docs / API Reference / Standard I/O & disk (stdio.h)

stdio_enable_prog

stdio_enable_prog(3)

enable DSR PROGRAM AU byte-stream backend

NAME

stdio_enable_prog — enable DSR PROGRAM AU byte-stream backend

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

void
stdio_enable_prog(void);

DESCRIPTION

Registers PROGRAM (:pg) open and stream ops so fopen(3) can treat DSR PROGRAM images as sequential AU byte streams (no app-visible LOAD/SAVE). Without this enable, untyped opens that resolve to PROGRAM fall back toward record OPEN (which) fopen() rejects for true PROGRAM FDRs .

Full backend overview: stdio_enable(3).

SEE ALSO

stdio_enable(3), fopen(3)

Source: resources/man/man3/stdio_enable_prog.3

Docs / API Reference / Standard I/O & disk (stdio.h)

stdio_enable_wds

stdio_enable_wds(3)

enable HFDC WDS* chip stdio backend

NAME

stdio_enable_wds — enable HFDC WDS* chip stdio backend

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

void
stdio_enable_wds(void);

DESCRIPTION

Registers WDS* chip AU stream ops and the optional HFDC face poke used before PAB opens on HFDC-owned units. Required for WDS1.... paths through fopen(3). Also set stdio_set_wds_vdp_buf(3) if the default Level-2 VRAM window overlaps your screen tables.

Full backend overview: stdio_enable(3).

SEE ALSO

stdio_enable(3), stdio_set_wds_vdp_buf(3), fopen(3)

Source: resources/man/man3/stdio_enable_wds.3

Docs / API Reference / Standard I/O & disk (stdio.h)

stdio_last_error

stdio_last_error(3)

last disk/DSR error code from Tidepod libc

NAME

stdio_last_error — last disk/DSR error code from Tidepod libc

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

unsigned int
stdio_last_error(void);

DESCRIPTION

Disk path APIs (fopen, remove, ti_opendir, fcopy_path, …) record a DSR-style status in an internal stdio_last_err and expose it via stdio_last_error(). This is the primary failure signal for classic Level-3 PAB I/O.

Defined codes (see stdio.h):

STDIO_ERR_NONE
0 — success / cleared
STDIO_ERR_BADDEV
1 — bad device
STDIO_ERR_PROTECT
2 — write protect
STDIO_ERR_BADOPEN
3 — bad open
STDIO_ERR_NOSPACE
4 — out of space
STDIO_ERR_EOF
5 — end of file / missing
STDIO_ERR_DEVICE
6 — device error
STDIO_ERR_FILE
7 — file error

Some helpers also use extended codes 9–12 (verify / layout / bad path). Successful opens and many helpers clear the code to 0.

errno is not set on every DSR failure. Native backends (chip / FAT / WDS / HFDC Level-2) may set errno (e.g. EINVAL, ENOSPC, ENOTSUP) in addition to stdio_last_error(). Prefer stdio_last_error() for portable disk error handling; check errno only when a backend documents it.

RETURN VALUES

The last recorded unsigned status code.

SEE ALSO

fopen(3), fcopy_path(3), errno(3), libc(3)

Source: resources/man/man3/stdio_last_error.3

Docs / API Reference / Standard I/O & disk (stdio.h)

stdio_set_vdp_base

stdio_set_vdp_base(3)

set the VDP RAM base address for Level-3 disk PABs and record buffers

NAME

stdio_set_vdp_base — set the VDP RAM base address for Level-3 disk PABs and record buffers

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

void
stdio_set_vdp_base(uint16_t pab_base);

DESCRIPTION

stdio_set_vdp_base() sets the starting VDP RAM address (stdio_vdp_base) where libc places Peripheral Access Blocks (PABs) and their associated record transfer buffers for Level-3 DSR disk operations.

If stdio_set_vdp_base() is never called, stdio_vdp_base defaults to 0x3000 (occupying >3000–>32FF). Any program whose VRAM layout overlaps >3000–>32FF should relocate the PAB arena to a free VRAM region before opening files.

VRAM Arena Layout

Up to STDIO_MAX_FILES (3) streams may be open simultaneously. Each slot idx (0 <= idx < 3) occupies 0x0100 (256) bytes at pab_base + idx * 0x0100:

  • +0x0000 .. +0x001F (32 bytes, f->vdp_pab = pab_base + idx * 0x0100): 10-byte PAB header followed by the device/file pathname (e.g. “DSK1.MYFILE”).
  • +0x0020 .. +0x00DF (192 bytes, f->vdp_buf = vdp_pab + 0x0020): VDP record buffer (up to STDIO_REC_MAX) used by DSR OPEN, READ, and WRITE calls.

In total, the three file slots reserve 3 * 0x0100 = 0x0300 (768) bytes of VRAM: pab_base .. pab_base + 0x02FF (default >3000–>32FF).

Avoiding VRAM Collisions

When choosing pab_base, ensure the 0x0300-byte arena does not overlap:

  • Screen Image / Name Table (typically >0000–>07FF), pattern generator table at >0800, and F18A Text80 attribute table at >2000 (ATTR_BASE = 0x2000).
  • Pattern Descriptor Table (>0800–>0FFF) or >1000–>17FF in text modes, or up to >1FFF / >37FF in bitmap modes .
  • Catalog PAB scratch at >1C00 (CAT_PAB = 0x1C00, CAT_BUF = 0x1C40) used by ti_opendir(3) when reading directory entries via Level-3 DSR, and delete PAB scratch at >1D00 used by remove(3).
  • Myarc HFDC Level-2 sector buffer configured by stdio_set_wds_vdp_buf(3) (default 0x3DA8); often moved to 0x3600.
  • The DSR FILES(n) reserved area at the top of 16K VRAM: for FILES(3), >8370 is 0x37D7, so VRAM from 0x37D7 through 0x3FFF is owned by the disk controller DSR and VDP stack.

Note: native chip-level floppy I/O (stdio_enable_chip(3)) and FAT12 streams (stdio_enable_fat(3)) transfer sectors directly between controller registers and CPU RAM without using the PAB arena, whereas Level-3 PAB fallback and DSR PROGRAM loads still use stdio_vdp_base.

EXAMPLES

Place the 3-slot PAB arena at 0x3200 (occupying 0x3200–0x34FF), safely below FILES(3) at 0x37D7:

#include <stdio.h>

stdio_set_vdp_base(0x3200u);
FILE *fp = fopen("DSK1.CONFIG", "r");

SEE ALSO

fopen(3), stdio_enable(3), stdio_set_wds_vdp_buf(3), ti_opendir(3), ti_text_mode(3), libc(3)

Source: resources/man/man3/stdio_set_vdp_base.3

Docs / API Reference / Standard I/O & disk (stdio.h)

stdio_set_wds_vdp_buf, stdio_get_wds_vdp_buf

stdio_set_wds_vdp_buf(3)

choose HFDC/WDS Level-2 sector buffer in VRAM

NAME

stdio_set_wds_vdp_buf, stdio_get_wds_vdp_buf — choose HFDC/WDS Level-2 sector buffer in VRAM

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

void
stdio_set_wds_vdp_buf(uint16_t vdp_addr);

uint16_t
stdio_get_wds_vdp_buf(void);

DESCRIPTION

Myarc HFDC Level-2 sector I/O (AU read/write via subprogram >10) uses a 256-byte VRAM window. The DSR programs HDC DMA to the same numeric address; on this toolchain the emulator mirrors that transfer into VDP RAM, so the window must not overlap screen nametable, F18A attribute table, bitmap color table, catalog PABs, or the stdio_set_vdp_base() PAB arena.

The libc default is 0x3DA8 (high under FILES(2)), the traditional Myarc location. Console Text80 attributes live at >2000 (ATTR_BASE = 0x2000, while the pattern generator table is at >0800) so HFDC mirrors around >221A can overlap attributes unless relocated; apps that use Text80 attributes or place their own tables high should call stdio_set_wds_vdp_buf() (e.g. fileman uses 0x3600), below its PAB arena at >3800.

Addresses that cannot fit 256 bytes below >4000 are rejected and the default is restored. stdio_get_wds_vdp_buf() returns the address currently in use.

SEE ALSO

fopen(3), stdio_enable(3), stdio_enable_wds(3), stdio_set_vdp_base(3), ti_opendir(3)

Source: resources/man/man3/stdio_set_wds_vdp_buf.3

Docs / API Reference / Standard I/O & disk (stdio.h)

ti_text_mode, ti_text_load_builtin_font

ti_text_mode(3)

select console text geometry and load a default font

NAME

ti_text_mode, ti_text_load_builtin_font — select console text geometry and load a default font

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdio.h>

void
ti_text_mode(int cols);

void
ti_text_load_builtin_font(void);

DESCRIPTION

ti_text_mode() selects 32, 40, or 80 column text, programs VDP registers for the console nametable at (>0000) and pattern table at (>1000), and resets the console cursor. If cols is 80 but ti_vdp_text80_ok() is false, the call falls back to 40 columns. On a stock TMS9918A only VR0–7 are written; F18A/Pico enhanced registers are gated behind detect so they cannot alias into VR1 and blank the display.

ti_text_mode() does not load glyph patterns. Call ti_text_load_builtin_font() afterward to upload a bundled 5x8 font into the PDT, or rom_to_vram() a project resource (as fileman does with font_5x8.dat ). ti_text_load_builtin_font() lives in its own libc object and is linked only if referenced.

SEE ALSO

ti_vdp_detect(3), rom_to_vram(3), conio(3)

Source: resources/man/man3/ti_text_mode.3

Docs / API Reference / Catalogs & devices (dirent.h)

remove, unlink, rename

remove(3)

delete or rename a disk file

NAME

remove, unlink, rename — delete or rename a disk file

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <dirent.h>

int
remove(const char *path);

int
unlink(const char *path);

int
rename(const char *oldpath, const char *newpath);

DESCRIPTION

remove() and unlink() delete a TI path such as DSK1.MYFILE (Level-3 DELETE at VDP scratch >1D00 or FS mutate, binding-dispatched).

rename() renames within the same volume when stdio_enable_chip(3) (TIFDC floppy) or HFDC WDS (stdio_enable_wds(3)) is active; otherwise it returns -1 with errno set to ENOTSUP. Cross-volume rename is not supported — use fcopy_path() then remove().

SEE ALSO

fcopy_path(3), fopen(3), stdio_enable(3), ti_opendir(3)

Source: resources/man/man3/remove.3

Docs / API Reference / Catalogs & devices (dirent.h)

ti_dsr_enum, ti_dsr_enum_ex

ti_dsr_enum(3)

list catalogable DSR unit names via CRU scan

NAME

ti_dsr_enum, ti_dsr_enum_ex — list catalogable DSR unit names via CRU scan

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <dirent.h>

int
ti_dsr_enum(char out[][TI_DSR_NAME_MAX + 1], int max);

int
ti_dsr_enum_ex(ti_dsr_unit_t *out, int max);

typedef struct {
  char name[TI_DSR_NAME_MAX + 1];
  unsigned cru;
} ti_dsr_unit_t;

DESCRIPTION

Walk PEB CRU bases (>1000) through >1F00, map each card ROM, and collect type-8 device names from the list at >4008. Only catalogable unit names are returned: DSK1 through DSK8 and WDS1 through WDS3 (bare DSK / WDS, TIME, and other names are skipped).

Names are written without a trailing period. Pass the result to ti_opendir() as DSK1. or WDS1. to catalog.

ti_dsr_enum_ex() performs the same scan as ti_dsr_enum() but also records the card CRU base address in out[i].cru for driver binding.

At most TI_DSR_MAX (16) entries are returned; max is clamped to that limit.

RETURN VALUES

Number of names written to out (zero if none found or arguments are invalid).

SEE ALSO

ti_opendir(3), libc(3)

Source: resources/man/man3/ti_dsr_enum.3

Docs / API Reference / Catalogs & devices (dirent.h)

ti_opendir, ti_readdir, ti_closedir, ti_dir_volume, opendir, readdir, closedir

ti_opendir(3)

TI disk catalog and POSIX directory wrappers

NAME

ti_opendir, ti_readdir, ti_closedir, ti_dir_volume, opendir, readdir, closedir — TI disk catalog and POSIX directory wrappers

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <dirent.h>

ti_DIR *
ti_opendir(const char *device);

int
ti_readdir(ti_DIR *dir, ti_dirent *ent);

void
ti_closedir(ti_DIR *dir);

int
ti_dir_volume(const ti_DIR *dir, ti_volume_t *out);

DIR *
opendir(const char *name);

struct dirent *
readdir(DIR *dir);

int
closedir(DIR *dir);

DESCRIPTION

Open device (e.g. DSK1. or WDS1.) as an INTERNAL/FIXED 38 catalog (OPEN passes record length 0 so the DSR fills 38; required for Myarc HFDC). The device name is copied into always-mapped storage at entry before any further catalog work (bank-safe).

ti_readdir() fills ent and returns nonzero while file entries remain (the volume record is consumed internally and is not returned as an entry).

ti_dir_volume() copies volume metadata gathered from catalog record 0 into out. Call it before ti_closedir(). It returns nonzero when volume data is available.

ti_dirent

name
NUL-terminated file name, max TI_NAME_MAX (12, accommodating FAT 8.3 names such as FDCONFIG.SYS; classic TI names are <= 10) characters.
type
1=DISPLAY/FIXED, 2=DISPLAY/VARIABLE, 3=INTERNAL/FIXED, 4=INTERNAL/VARIABLE, 5=PROGRAM; 0=empty/unknown.
sectors
Sectors allocated to the file.
reclen
Record length for DF/DV/IF/IV files, or EOF offset in the last sector for PROGRAM files.
flags
Bit 0 set if the file is write-protected.

ti_volume_t

volume
Disk volume name.
total_sectors, free_sectors
From catalog record 0.

POSIX wrappers (opendir, readdir, closedir)

opendir(), readdir(), and closedir() provide a POSIX-shaped directory stream over DIR and struct dirent (with d_name[NAME_MAX + 1], d_type DT_REG / DT_DIR / DT_UNKNOWN, and optional TI catalog fields d_ti_type, d_flags, d_sectors, d_reclen).

Numeric catalog fields use BASIC INTERNAL encoding: a length-prefixed name followed by three length-prefixed RADIX-100 floats (each numeric is 08 then 8 float bytes). Negative type means write-protected (first two float bytes are ones-complemented). Libc also accepts layouts without per-float length bytes and flat emulator catalogs (10-char name at offset 0 with floats at 10/18/26, or big-endian words at 10/12/14). The standard FIXED-38 catalog does not include timestamps.

Supported on classic floppy DSRs, Myarc HFDC hard disks (WDSn.), and emulator DSK/HD images. Discover unit names with ti_dsr_enum(3) rather than hardcoding DSKn. / WDSn..

RETURN VALUES

ti_opendir() returns a directory handle, or NULL on failure. ti_readdir() returns nonzero for a valid entry, zero at end-of-catalog or on error. ti_dir_volume() returns nonzero when out was filled.

SEE ALSO

ti_dsr_enum(3), remove(3), fopen(3), libc(3)

Source: resources/man/man3/ti_opendir.3

Docs / API Reference / Block devices & storage (block_device.h)

ti_stat, ti_protect, ti_mkdir, ti_rmdir

ti_stat(3)

file metadata and directory mutate helpers

NAME

ti_stat, ti_protect, ti_mkdir, ti_rmdir — file metadata and directory mutate helpers

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <block_device.h>

int
ti_stat(const char *path, ti_stat_t *st);

int
ti_protect(const char *path, int protect);

int
ti_mkdir(const char *path);

int
ti_rmdir(const char *path);

typedef struct {
  unsigned char type;      /* catalog type codes */
  unsigned int  sectors;
  unsigned int  reclen;
  unsigned char flags;     /* bit0 protected; bit1 directory */
} ti_stat_t;

DESCRIPTION

ti_stat() probes TIFDC Level-2 floppy FDR metadata only (DSK1...DSK3.) and fills st for an existing file.

ti_protect(), ti_mkdir(), and ti_rmdir() copy path into a local stack buffer and dispatch across the active filesystem bindings (TIFDC floppy layout, HFDC WDS, FAT12, …). ti_protect() sets (protect=1) or clears (protect=0) the FDR protect bit where the volume supports it. ti_mkdir() and ti_rmdir() create or remove a subdirectory (HFDC WDS paths such as WDS1.NEWDIR); TIFDC floppies have no subdirectories and return ENOTSUP.

RETURN VALUES

0 on success, -1 on failure (see stdio_last_error(3) and errno).

SEE ALSO

ti_opendir(3), remove(3), stdio_enable(3), stdio_last_error(3)

Source: resources/man/man3/ti_stat.3

Docs / API Reference / VDP detection (vdpinfo.h)

ti_vdp_detect, ti_vdp_text80_ok, ti_vdp_has_attrs, ti_vdp_has_gpu, console_gpu_invalidate, ti_load_ega_palette, ti_load_tms9918_palette

ti_vdp_detect(3)

detect F18A / Pico9918 capabilities and manage VDP palette / GPU state

NAME

ti_vdp_detect, ti_vdp_text80_ok, ti_vdp_has_attrs, ti_vdp_has_gpu, console_gpu_invalidate, ti_load_ega_palette, ti_load_tms9918_palette — detect F18A / Pico9918 capabilities and manage VDP palette / GPU state

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <vdpinfo.h>

int
ti_vdp_detect(void);

int
ti_vdp_text80_ok(void);

int
ti_vdp_has_attrs(void);

int
ti_vdp_has_gpu(void);

void
console_gpu_invalidate(void);

void
ti_load_ega_palette(void);

void
ti_load_tms9918_palette(void);

DESCRIPTION

ti_vdp_detect() unlocks an F18A-compatible VDP (VR57 twice) and reads status register 14. It returns TI_VDP_STOCK, TI_VDP_F18A, or TI_VDP_PICO9918 (currently reported as F18A-compatible; TI_VDP_V9990 is also defined for Yamaha V9990/V999x but not probed yet). Results are cached.

ti_vdp_text80_ok() is nonzero when 80-column text mode is safe (enhanced VDP with firmware >= 1.6).

ti_vdp_has_attrs() returns nonzero when per-cell foreground/background attributes are available in F18A/Pico9918 Text40 or Text80 modes.

ti_vdp_has_gpu() returns nonzero when the F18A/Pico9918 GPU DMA blit engine is available. console_gpu_invalidate() drops libc's cached GPU scroll blob upload (e.g. after an application overwrites VRAM around 0x3000).

ti_load_ega_palette() and ti_load_tms9918_palette() program the F18A 16-entry palette registers to the classic EGA 16-color palette or restore the stock TMS9918A colors (no-op on stock TMS9918A).

SEE ALSO

conio(3), ti_text_mode(3)

Source: resources/man/man3/ti_vdp_detect.3

Docs / API Reference / ROM resources & banking (resource_copy.h)

resource_copy, unwrap, rom_to_vram, rom_to_ram, rom_to_vram_ex, rom_to_ram_ex

resource_copy(3)

banked cartridge asset pipeline and copy API

NAME

resource_copy, unwrap, rom_to_vram, rom_to_ram, rom_to_vram_ex, rom_to_ram_ex — banked cartridge asset pipeline and copy API

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <resource_copy.h>
#include <resource_defs.h>

#define unwrap(x) x##_bank, x##_offset, x##_length

typedef void
(*resource_copy_hook_t)(unsigned int bytes_copied, unsigned int total_bytes);

void
rom_to_vram(unsigned int srcbank, unsigned int srcoffset, unsigned int length, unsigned int dst);

void
rom_to_ram(unsigned int srcbank, unsigned int srcoffset, unsigned int length, unsigned char *dst);

void
rom_to_vram_ex(unsigned int srcbank, unsigned int srcoffset, unsigned int length, unsigned int dst, unsigned int chunk_size, resource_copy_hook_t hook);

void
rom_to_ram_ex(unsigned int srcbank, unsigned int srcoffset, unsigned int length, unsigned char *dst, unsigned int chunk_size, resource_copy_hook_t hook);

DESCRIPTION

The <resource_copy.h> header declares the runtime interface for copying binary resources (tilesets, sprite sheets, fonts, audio streams, and F18A GPU blobs) from banked cartridge ROM into VDP RAM or 32K CPU expansion RAM.

In a Tidepod banked cartridge project, binary files added with tidepod add are packed contiguously into cartridge ROM banks starting at linker symbols _binary_start_bank and _binary_start_offset. During the build, a packer pre-pass generates include/resource_defs.h with three preprocessor constants per resource (<name>_bank, <name>_offset, <name>_length), where <name> is the file stem with non-identifier characters converted to underscores.

Pass unwrap(name) as the first three arguments to rom_to_vram(3), rom_to_ram(), rom_to_vram_ex(), or rom_to_ram_ex() to transfer the asset across one or more 8 KB cartridge banks without manual bank calculations.

For complete parameter descriptions, bank-wrapping behavior, and progress-hook examples, see rom_to_vram(3).

SEE ALSO

rom_to_vram(3), f18a_gpu_host(3), ti_text_mode(3), libc(3)

Source: resources/man/man3/resource_copy.3

Docs / API Reference / ROM resources & banking (resource_copy.h)

rom_to_vram, rom_to_ram, rom_to_vram_ex, rom_to_ram_ex, unwrap

rom_to_vram(3)

copy banked cartridge ROM resources into VRAM or CPU RAM

NAME

rom_to_vram, rom_to_ram, rom_to_vram_ex, rom_to_ram_ex, unwrap — copy banked cartridge ROM resources into VRAM or CPU RAM

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <resource_copy.h>
#include <resource_defs.h>

#define unwrap(x) x##_bank, x##_offset, x##_length

typedef void
(*resource_copy_hook_t)(unsigned int bytes_copied, unsigned int total_bytes);

void
rom_to_vram(unsigned int srcbank, unsigned int srcoffset, unsigned int length, unsigned int dst);

void
rom_to_ram(unsigned int srcbank, unsigned int srcoffset, unsigned int length, unsigned char *dst);

void
rom_to_vram_ex(unsigned int srcbank, unsigned int srcoffset, unsigned int length, unsigned int dst, unsigned int chunk_size, resource_copy_hook_t hook);

void
rom_to_ram_ex(unsigned int srcbank, unsigned int srcoffset, unsigned int length, unsigned char *dst, unsigned int chunk_size, resource_copy_hook_t hook);

DESCRIPTION

The <resource_copy.h> routines stream binary assets packed into banked cartridge ROM (>6000–>7FFF) into VDP RAM or CPU RAM, automatically stepping across 8 KB (0x2000) cartridge bank boundaries and restoring the caller's active bank before returning.

When a binary asset (e.g. resources/font_5x8.dat) is registered with a Tidepod project via tidepod add, the build converts it into a linkable .binary section object and tms9900-packer emits three constants into the generated header <resource_defs.h>:

#define font_5x8_bank    ...
#define font_5x8_offset  ...
#define font_5x8_length  ...

The convenience macro unwrap(sym) expands to the comma-separated triple sym_bank, sym_offset, sym_length expected as the first three arguments of all four copy routines.

All four routines reside in .persistent memory (upper 32K RAM) so they can safely switch cartridge banks at >6000 without unmapping their own code:

rom_to_vram()
Copies length bytes starting at (srcbank, srcoffset) relative to the linker's _binary_start_bank and _binary_start_offset symbols into VDP RAM beginning at byte address dst (0x0000–0x3FFF) on stock TMS9918A, or higher when F18A extended VRAM is unlocked. Writes use an inlined VDP burst loop (port >8C02) address setup followed by streaming writes to >8C00 rather than calling a banked helper, so the active source bank at >6000 is never clobbered mid-transfer.
rom_to_ram()
Copies length bytes from banked cartridge ROM into CPU RAM at dst using memcpy(3) across bank boundaries. The destination buffer must be in persistent RAM (32K expansion or scratchpad), never inside the >6000–>7FFF cartridge window.
rom_to_vram_ex()
Chunked variant of rom_to_vram() for keeping music, sound effects, or loading bars alive during large asset uploads. Transfers at most chunk_size bytes per step (or the remainder of the current 8 KB bank if smaller); when chunk_size is 0, each bank slice is transferred in one chunk. After each chunk, if hook is non-null, calls hook(bytes_copied, total_bytes) while the resource bank is still latched. If the hook itself switches banks, it must restore currentbank or reside in persistent memory.
rom_to_ram_ex()
Chunked variant of rom_to_ram() with the same chunk_size and hook progress callback semantics.

Bank Arithmetic and Preservation

Before switching banks, each function reads the global currentbank variable, adds the linker symbols _binary_start_bank and _binary_start_offset to srcbank and srcoffset, and normalizes srcoffset modulo 0x2000. Whenever a copy spans the end of an 8 KB bank (srcoffset + length > 0x2000), the routine copies the tail of the current bank, increments srcbank, resets srcoffset to 0, and continues until length bytes have been transferred. Finally, switchtobank(saved) restores the caller's original bank.

EXAMPLES

Upload a packed 2 KB font resource into the Pattern Descriptor Table at VRAM >1000:

#include <resource_copy.h>
#include "resource_defs.h"

rom_to_vram(unwrap(font_5x8), 0x1000u);

Stream a large pattern table in 256-byte chunks while servicing a VSync audio player:

static void vsync_audio_hook(unsigned int done, unsigned int total) {
    (void)done;
    (void)total;
    sfx_tick();
}

rom_to_vram_ex(unwrap(title_patterns), 0x0000u, 256u, vsync_audio_hook);

Load an F18A GPU program image from banked ROM into VRAM and start it:

#include <resource_copy.h>
#include <f18a_gpu_host.h>
#include "resource_defs.h"
#include "gpu_fx_map.h"

rom_to_vram(unwrap(gpu_fx), gpu_fx_base);
f18a_gpu_start(gpu_fx_entry);

SEE ALSO

resource_copy(3), f18a_gpu_host(3), ti_text_mode(3), memcpy(3), libc(3)

Source: resources/man/man3/rom_to_vram.3

Docs / API Reference / SAMS memory expansion (sams.h)

sams

sams(3)

SuperAMS mapper helpers, fat pointers, fat heap, and __sams address space

NAME

sams_init, sams_present, sams_page_count, sams_map, sams_get, sams_ptr, sams_page_of, sams_offset_of, sams_add, sams_lock, sams_unlock, sams_read8, sams_write8, sams_read16, sams_write16, sams_memcpy_from, sams_memcpy_to, sams_memset, sams_malloc, sams_free, sams_calloc, sams_realloc, sams_get_free_heap, __sams_load_qi, __sams_store_qi, __sams_load_hi, __sams_store_hi — SuperAMS mapper helpers, fat pointers, fat heap, and __sams address space

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <sams.h>
#include <sams_far.h> (optional sugar)
int
sams_present(void);

unsigned
sams_page_count(void);

int
sams_init(void);

void
sams_map(unsigned window_nibble, unsigned page);

unsigned
sams_get(unsigned window_nibble);

sams_ptr_t
sams_ptr(unsigned page, unsigned offset);

unsigned
sams_page_of(sams_ptr_t p);

unsigned
sams_offset_of(sams_ptr_t p);

sams_ptr_t
sams_add(sams_ptr_t p, int delta);

void *
sams_lock(sams_ptr_t p);

void
sams_unlock(sams_ptr_t p);

unsigned char
sams_read8(sams_ptr_t p);

void
sams_write8(sams_ptr_t p, unsigned char v);

unsigned
sams_read16(sams_ptr_t p);

void
sams_write16(sams_ptr_t p, unsigned v);

void
sams_memcpy_from(void *dst, sams_ptr_t src, unsigned n);

void
sams_memcpy_to(sams_ptr_t dst, const void *src, unsigned n);

void
sams_memset(sams_ptr_t dst, unsigned char v, unsigned n);

sams_ptr_t
sams_malloc(unsigned size);

void
sams_free(sams_ptr_t p);

sams_ptr_t
sams_calloc(unsigned count, unsigned size);

sams_ptr_t
sams_realloc(sams_ptr_t p, unsigned size);

unsigned
sams_get_free_heap(void);

typedef unsigned long sams_ptr_t;  /* page << 16 | offset */

DESCRIPTION

SuperAMS (74LS612) does not enlarge the TMS9900 address space. Native char * pointers remain 16-bit and can see at most the classic ~32K expansion windows at once. Extra SRAM is reached by rewriting 4K mapper pages through CRU base >1E00 (bit 0 = mapper registers at >4000, bit 1 = MAP mode).

Tidepod exposes that card with sams_ptr_t fat pointers (page + offset) and helpers that either lock a page into a reserved CPU window (yielding a temporary near) void *, or access bytes through a scratch window without a long-lived near pointer.

Ordinary .data / .bss / .persistent and the C stack stay near forever (identity-mapped windows). Do not remap >F000 while C code is running: the default linker places the stack there.

With a toolchain that defines __TMS9900_SAMS_AS__, GCC accepts the named address space qualifier __sams (GNU C:) -std=gnu99 or -std=gnu11, not plain -std=c99. Tidepod project Makefiles default to -std=gnu99. A pointer such as unsigned char __sams * is an SI fat pointer with the same page:offset encoding as sams_ptr_t (under gnu99,) sams_malloc() returns void __sams * so no cast is needed . Loads and stores expand to __sams_load_qi(/, __sams_store_qi) and __sams_load_hi(/, __sams_store_hi) (thin wrappers over the accessors; HI touches map the accessor window once when both bytes share a page). Static objects (static unsigned char __sams buf[N]) land in .sams_bss (or) .sams_data if initialized at fat VMA 0x00100000 (page 0x10 onward); sams_static_init() in crt0 zeroes BSS via the packer bookkeeping symbols. Pointer arithmetic within a page-local object is ordinary SI add (matching) sams_malloc() chunks . Cast through sams_ptr_t to convert between the integer API and __sams pointers; use sams_lock() for a temporary near void *. See resources/examples/sams_as_test/.

Call sams_init() once before other helpers (except) sams_present() / sams_page_count(), which may probe . Without a SAMS card (or with emulator) --mem 32k|none, sams_init() returns -1 and lock/accessors fail closed.

Detection and mapper

sams_present()
Nonzero if a SuperAMS-compatible mapper responds to a page-swap probe.
sams_page_count()
Number of 4K pages (currently 256 for the 1MB configuration, or 0 if absent).
sams_init()
Probes the card, writes the classic identity map for windows >2000, >3000, >A000–>F000, and enables MAP mode. Returns 0 on success, -1 if no SAMS.
sams_map()
Maps page into the 4K CPU window whose high address nibble is window_nibble (0x2, 0x3, or 0xA–0xF).
sams_get()
Returns the page currently mapped at window_nibble.

Fat pointers

sams_ptr()
Builds a fat pointer from page and offset (offset masked to 12 bits).
sams_page_of(/) sams_offset_of()
Unpack a fat pointer.
sams_add()
Adds a signed byte delta, carrying across 4K page boundaries. Returns SAMS_PTR_NULL if underflow would wrap below page 0.

Lock windows

Two reserved windows (>C000 and >D000) hold locked pages. >E000 is reserved for accessor scratch; >F000 is left for the stack.

sams_lock()
Maps p's page into a free lock window (or reuses an existing mapping of that page) and returns a near void * into that window at p's offset. Nested locks on the same page refcount. Returns NULL if both slots are busy or SAMS is absent.
sams_unlock()
Drops one ref on p's page. When the refcount hits zero the window is restored to its identity page. Using the near pointer after unlock is undefined (use-after-free).

Accessors

These map through >E000 (last-page cache) and do not consume a lock slot. Prefer them for bulk or one-shot traffic; prefer sams_lock() when many near-pointer operations on the same object are needed.

RETURN VALUES

sams_init() returns 0 or -1. sams_lock() returns a near pointer or NULL. Accessors that cannot map (no SAMS) read as 0xFF / ignore writes.

Fat heap

sams_malloc() allocates from non-reserved SAMS pages (reserved identity pages are 2, 3, A, B, F); pages behind windows C/D/E are eligible . Chunks never cross a 4K page boundary in this phase (max payload just under 4K). The allocator does not leave the object mapped; use sams_lock() or the accessors to touch payload. sams_get_free_heap() sums free-chunk bytes on the fat freelist (including headers). Without a SAMS card these calls fail closed (NULL / 0).

When a SAMS card is present, near malloc(3) is clipped under >C000 so lock windows never overlay the near arena.

The packer also enforces that layout: any undefined sams_* reference (or explicit) --sams sets the SAMS near map so .persistent_high / .data / .bss / heap fit in >A000–BFFF (8K). Spilling into >C000–EFFF is a pack FATAL, not a silent hang under sams_lock(). The ceiling is fixed ABI (matches libc lock/accessor windows); it is not a project knob.

EXAMPLES

#include <sams.h>

if (sams_init() != 0)
  /* plain 32K — no fat heap path */
  ;

unsigned char __sams *p = sams_malloc(64);
if (p) {
  p[0] = 0xBE;
  sams_free(p);
}

Optional sugar (SAMS_FAR, sams_new(), SAMS_WITH_NEAR()) lives in <sams_far.h>. Tutorial and porting notes: docs/sams_tutorial.md and docs/sams_porting.md.

SEE ALSO

libc(3), malloc(3)

Example carts: resources/examples/sams_tutorial/, resources/examples/sams_as_test/, resources/examples/sams_malloc_test/, resources/examples/sams_chunk_demo/, resources/examples/sams_march/.

BUGS

Chunks do not span pages yet. Only single-page locks are supported (two simultaneous locked pages max).

Source: resources/man/man3/sams.3

Docs / API Reference / GDB debugging & logging (debug.h)

debug, __dbg_printf, BRK

debug(3)

zero-cost host-evaluated debug logpoints, ANSI trace styling, and soft breakpoints

NAME

debug, __dbg_printf, BRK — zero-cost host-evaluated debug logpoints, ANSI trace styling, and soft breakpoints

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <debug.h>

void
__dbg_printf(const char *fmt, ...);

void
BRK(void);

DESCRIPTION

<debug.h> provides host-assisted debugging and formatted trace output for TI-99/4A C programs running in the Tidepod IDE debugger, with minimal impact in debug builds and strictly zero code or data overhead in release builds.

Host-Evaluated Logpoints (__dbg_printf)

Traditional printf(3) on the TMS9900 consumes hundreds of bytes of stack/RAM, thousands of CPU cycles per call, and VDP bandwidth. By contrast, __dbg_printf() performs no formatting or I/O on the TI-99/4A CPU:

  • <debug> builds (without NDEBUG): each __dbg_printf() invocation emits a single 2-byte NOP instruction in .text to anchor the program counter, and records the format string and up to 8 argument variable/expression names into a non-allocatable ELF section named .tms9900.logpoints. That metadata exists only in the .debug ELF sidecar; tms9900-elf-objcopy strips it out of the final cartridge .bin. When the Tidepod debugger executes the NOP, the host intercepts the PC, resolves each named argument via DWARF debug symbols (registers, stack locals, globals, or banked variables), formats the message on the host machine, and writes it to the IDE's Debug Log panel.
  • <release> builds (NDEBUG defined, which Tidepod sets automatically in release CCFLAGS): __dbg_printf() and BRK() expand to ((void)0). No NOP, no strings, and no metadata are emitted.

__dbg_printf() accepts 0 to 8 arguments after fmt. Standard printf() format specifiers (%d, %u, %x, %04X, %s, %c, etc.) are supported directly without doubling percent signs. Because arguments are evaluated by the host DWARF reader by name rather than passed at runtime in registers, pass simple variable names or expressions that correspond to inspectable symbols in the current scope, and never rely on side effects (such as i++) inside a __dbg_printf() argument list.

Soft Breakpoints (BRK)

BRK() emits a special zero-argument logpoint marker (“__BRK__”) in debug builds. When the Tidepod debugger hits a BRK() anchor during a Debug session, it immediately pauses CPU execution and syncs the source editor and register/watch views to that line. When running outside the debugger or on real hardware, the anchor is a harmless 2-byte NOP; in release builds (NDEBUG), it compiles to nothing.

ANSI Terminal Formatting Macros

The Tidepod Debug Log panel emulates an ANSI color terminal. <debug.h> defines string-literal macros that can be concatenated directly into __dbg_printf() format strings:

Screen & Cursor Control
DBG_RESET (reset attributes), DBG_CLEAR (clear screen), DBG_HOME (cursor to 1,1), DBG_CLREOL (clear to end of line), DBG_CLRLN (clear entire line), DBG_GOTO(row, col) (1-based cursor position), DBG_UP(n), DBG_DOWN(n), DBG_RIGHT(n), DBG_LEFT(n), DBG_COL(n).
Text Weight
DBG_BOLD, DBG_NOBOLD.
Foreground Colors
DBG_BLACK, DBG_RED, DBG_GREEN, DBG_YELLOW, DBG_BLUE, DBG_MAGENTA, DBG_CYAN, DBG_WHITE.
Bright Foreground Colors
DBG_BRIGHT_RED, DBG_BRIGHT_GREEN, DBG_BRIGHT_YELLOW, DBG_BRIGHT_BLUE, DBG_BRIGHT_MAGENTA, DBG_BRIGHT_CYAN, DBG_BRIGHT_WHITE.
Background Colors
DBG_BG_BLACK, DBG_BG_RED, DBG_BG_GREEN, DBG_BG_YELLOW, DBG_BG_BLUE, DBG_BG_MAGENTA, DBG_BG_CYAN, DBG_BG_WHITE.

EXAMPLES

Log player coordinates in color and build a live HUD in the Debug Log panel:

#include <debug.h>

void update_player(int px, int py, int hp) {
    __dbg_printf(DBG_GOTO(1, 1) DBG_CLREOL
                 "Pos: (" DBG_CYAN "%d" DBG_RESET ", "
                 DBG_CYAN "%d" DBG_RESET ") HP=" DBG_GREEN "%d" DBG_RESET,
                 px, py, hp);

    if (hp < 0) {
        __dbg_printf(DBG_RED "Warning: negative HP %d" DBG_RESET, hp);
        BRK(); /* Pause debugger to inspect state */
    }
}

SEE ALSO

profiler(3), printf(3), libc(3)

Source: resources/man/man3/debug.3

Docs / API Reference / Execution profiling (profiler.h)

profiler, PROF_FRAME_END, PROF_BEGIN, PROF_END

profiler(3)

zero-cost cycle profiler annotations for the Tidepod IDE

NAME

profiler, PROF_FRAME_END, PROF_BEGIN, PROF_END — zero-cost cycle profiler annotations for the Tidepod IDE

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <profiler.h>

void
PROF_FRAME_END(void);

void
PROF_BEGIN(color, id);

void
PROF_END(color, id);

DESCRIPTION

<profiler.h> provides zero-overhead source annotations that feed the Tidepod IDE's real-time Frame Profiler (the PRF) tab in the right-hand Debugger panel . Including <profiler.h> also includes debug(3) (providing __dbg_printf(and) BRK()).

Unlike instrumentation that reads hardware timers or writes to memory, these macros emit zero instructions and occupy zero bytes of ROM or RAM. Instead, each macro emits a unique global assembler label at the current program counter (PC):

  • __prof_frame_end_<n>
  • __prof_block_<RRGGBB>_<id>_start_<n>
  • __prof_block_<RRGGBB>_<id>_end_<n>

When a debug build is loaded in Tidepod, the DWARF/ELF reader extracts these symbol addresses from the .debug sidecar. As the emulator runs, it measures exact TMS9900 clock cycles elapsed between each PROF_BEGIN() and PROF_END() pair, counts VDP vertical blanking interrupts between PROF_FRAME_END() markers to determine effective frame rate (60 Hz, 30 Hz, 20 Hz, etc.), and plots a 120-frame stacked cycle history against the project's target FPS cycle budget (50,065 cycles per 60 Hz NTSC frame). Clicking a block legend in the PRF tab jumps the editor directly to the corresponding PROF_BEGIN() line in source.

Macros

PROF_FRAME_END()
Marks the boundary of one logical game frame. Place this macro exactly once per main-loop iteration, typically at the very top of the loop before waiting for VBlank.
PROF_BEGIN(color, id)
Marks the start of a timed code region named id rendered in the IDE profiler with hex color color.
PROF_END(color, id)
Marks the end of the timed code region started by the matching PROF_BEGIN(color, id).

Annotation Rules

  1. color must be a bare 6-digit hexadecimal RGB token (RRGGBB) with no leading 0x or # (e.g. 4FC3F7, not 0x4FC3F7).
  2. id must be a bare C identifier (letters, digits, underscores — no quotation marks or spaces).
  3. Every PROF_BEGIN(color, id) must be paired with a matching PROF_END(color, id) using the exact same color and id tokens. The same (color, id) pair may appear multiple times in a frame; each expansion receives a unique assembler suffix via %=.
  4. Blocks may nest (e.g. a physics block inside an outer update block), but must not partially overlap.
  5. Wrap your VBlank wait (e.g. vdpwaitvint()) in its own block (conventionally grey, 808080) so idle wait time is distinguished from active CPU work.

Recommended Palette

Hex Color Hex Color
4FC3F7 Light blue 81C784 Green
FFB74D Orange E57373 Red
BA68C8 Purple FFD54F Yellow
4DB6AC Teal F06292 Pink
808080 Grey (idle)

EXAMPLES

Annotate a 60 Hz game loop with idle, input, physics, and render phases:

#include <profiler.h>

for (;;) {
    PROF_FRAME_END();

    PROF_BEGIN(808080, vblank_wait);
    vdpwaitvint();
    PROF_END(808080, vblank_wait);

    PROF_BEGIN(4FC3F7, input);
    read_joysticks();
    PROF_END(4FC3F7, input);

    PROF_BEGIN(FFB74D, physics);
    step_entities();
    PROF_END(FFB74D, physics);

    PROF_BEGIN(81C784, render);
    upload_sprites();
    PROF_END(81C784, render);
}

SEE ALSO

debug(3), libc(3)

Source: resources/man/man3/profiler.3

Docs / API Reference / F18A GPU coprocessor (f18a_gpu.h)

f18a_gpu, F18A_GPU_IDLE, F18A_GPU_MMIO8, F18A_GPU_MMIO16

f18a_gpu(3)

GPU-side freestanding definitions for F18A / Pico9918 coprocessor programs

NAME

f18a_gpu, F18A_GPU_IDLE, F18A_GPU_MMIO8, F18A_GPU_MMIO16 — GPU-side freestanding definitions for F18A / Pico9918 coprocessor programs

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <f18a_gpu.h>

#define F18A_GPU_IDLE() __asm__ volatile(2idle2)
#define F18A_GPU_VRAM_BASE 0x0000u
#define F18A_GPU_GRAM_BASE 0x4000u
#define F18A_GPU_WS_BASE 0x4800u
#define F18A_GPU_SCANLINE 0x7000u
#define F18A_GPU_BLANKING 0x7001u
#define F18A_ECM3_P0 0x0000u
#define F18A_ECM3_P1 0x0800u
#define F18A_ECM3_P2 0x1000u
#define F18A_GPU_MMIO8(addr) (*(volatile unsigned char *)(unsigned)(addr))
#define F18A_GPU_MMIO16(addr) (*(volatile unsigned int *)(unsigned)(addr))

DESCRIPTION

<f18a_gpu.h> provides freestanding macros and memory-map constants for C translation units compiled to run on the F18A or Pico9918 internal 100 MHz TMS9900-compatible GPU coprocessor.

In Tidepod, a source file registered with:

tidepod add src/gpu_fx.c --gpu --gpu-base 0x1F00 --gpu-stack 0x1FAE

is compiled as an independent freestanding binary linked at VDP address gpuBase with its own startup routine (crt0_gpu.o) and packed into the cartridge as a binary resource alongside a generated map header (include/gpu_<stem>_map.h). The host CPU uploads and starts the image via rom_to_vram(3) and f18a_gpu_host(3).

GPU Memory Map Constants

The F18A GPU sees a flat 64 KB byte-addressed space completely separate from the host TI-99/4A CPU bus:

F18A_GPU_VRAM_BASE (0x0000u)
Start of the 16 KB VDP RAM window (0x0000–0x3FFF) shared with the host VDP ports. Host-loaded GPU code, stacks, and shared parameter mailboxes must reside in this region.
F18A_GPU_GRAM_BASE (0x4000u)
Start of the 2 KB GPU-private RAM (0x4000–0x47FF) on classic F18A. Note: standard host VDP address writes wrap at 16 KB (0x3FFF), so the host cannot upload directly into 0x4000+ with rom_to_vram(); only the GPU itself can read and write this region directly.
F18A_GPU_WS_BASE (0x4800u)
Hardware-fixed GPU workspace register file (R0–R15).
F18A_GPU_SCANLINE (0x7000u)
Read-only byte MMIO reporting the current raster scanline (0–255).
F18A_GPU_BLANKING (0x7001u)
Read-only byte MMIO whose LSB indicates horizontal/vertical blanking. Use with care: in some emulators (e.g. JS99er) the blanking bit can be sticky across frames; prefer F18A_GPU_IDLE() with a VR50 trigger for deterministic synchronization.
F18A_ECM3_P0, F18A_ECM3_P1, F18A_ECM3_P2
Byte offsets (0x0000, 0x0800, 0x1000) for the three bitplanes of an Enhanced Color Mode 3 (8-color) pattern table when VR29 tile plane size is set to 00 (2 KB per plane).

Macros

F18A_GPU_IDLE()
Emits the TMS9900 IDLE instruction, suspending GPU execution until the next GPU trigger configured in VDP Register 50 (HSYNC or VSYNC) or until the host writes VR55.
F18A_GPU_MMIO8(addr)
Dereferences addr as a volatile unsigned char in the GPU address space (VRAM, GPU RAM, palette RAM at 0x5000, VDP registers at 0x6000, or status MMIO at 0x7000).
F18A_GPU_MMIO16(addr)
Dereferences even byte address addr as a 16-bit big-endian volatile unsigned int.

Critical GPU Coding Constraints

  1. Never execute LWPI: The F18A GPU workspace pointer is hardwired to F18A_GPU_WS_BASE (0x4800). Executing LWPI has no effect or undefined behavior on F18A derivatives.
  2. Register R15 is the hardware call stack pointer: The F18A replaces standard TMS9900 BLWP with hardware CALL and RET instructions that push and pop return addresses through R15. Tidepod automatically compiles GPU translation units with -ffixed-r15 and initializes R15 to gpuStack in crt0_gpu.o. Never clobber R15 in inline assembly.
  3. “not call host libc functions: Host libc routines access host memory-mapped ports (>8800 / >8C00) and cartridge banks (>6000) that do not exist in the GPU address space. GPU TUs must be self-contained.”

EXAMPLES

A minimal GPU routine that increments a palette entry on every VSync trigger:

#include <f18a_gpu.h>

void main(void) {
    for (;;) {
        F18A_GPU_MMIO16(0x5000u) += 0x0011u; /* Palette 0 */
        F18A_GPU_IDLE();                     /* Wait for next VR50 trigger */
    }
}

SEE ALSO

f18a_gpu_host(3), rom_to_vram(3), ti_vdp_detect(3), libc(3)

Source: resources/man/man3/f18a_gpu.3

Docs / API Reference / F18A GPU host controls (f18a_gpu_host.h)

f18a_gpu_host

f18a_gpu_host(3)

host-side control and VRAM loader for the F18A / Pico9918 GPU coprocessor

NAME

f18a_gpu_load_at, f18a_gpu_start, f18a_gpu_stop, f18a_gpu_load_and_start — host-side control and VRAM loader for the F18A / Pico9918 GPU coprocessor

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <f18a_gpu_host.h>

void
f18a_gpu_load_at(unsigned int vram_addr, const unsigned char *src, unsigned int len);

void
f18a_gpu_start(unsigned int entry_pc);

void
f18a_gpu_stop(void);

void
f18a_gpu_load_and_start(unsigned int vram_addr, const unsigned char *src, unsigned int len, unsigned int entry_pc);

DESCRIPTION

The <f18a_gpu_host.h> functions run on the host TI-99/4A TMS9900 CPU to upload machine code into VDP RAM and start or stop the F18A (or Pico9918) internal GPU coprocessor via extended VDP registers VR54, VR55, and VR56.

Before calling any of these routines, the F18A must be unlocked (writing 0x1C twice to VR57), which ti_vdp_detect(3) performs automatically when probing for an enhanced VDP.

All four routines are marked #pragma bank persistent so they remain mapped in upper 32K RAM regardless of which cartridge bank is selected at >6000.

f18a_gpu_stop()
Writes 0x00 to VDP Register 56, immediately halting the GPU coprocessor if it is running and clearing any pending GPU state.
f18a_gpu_start()
Writes the high byte of entry_pc to VDP Register 54 and the low byte to VDP Register 55. On the F18A, the write to VR55 latches the 16-bit program counter (VR54:VR55) and immediately starts GPU execution at entry_pc.
f18a_gpu_load_at()
Copies len bytes from the CPU buffer src into VDP RAM starting at byte address vram_addr (0x0000–0x3FFF) via vdpmemcpy(). Use this when the GPU machine-code blob already resides in persistent CPU RAM or the currently active ROM bank. When the GPU image is a Tidepod banked resource (added with tidepod add ... --gpu), prefer rom_to_vram(3) with unwrap(), which handles multi-bank offset normalization automatically.
f18a_gpu_load_and_start()
Convenience wrapper that calls f18a_gpu_stop(), uploads len bytes from src to vram_addr via f18a_gpu_load_at(), and starts the GPU at entry_pc via f18a_gpu_start().

Generated GPU Map Headers

When a C file src/gpu_fx.c is added to a Tidepod project with tidepod add src/gpu_fx.c --gpu --gpu-base 0x3800 --gpu-stack 0x3FFE, the build generates include/gpu_gpu_fx_map.h containing:

  • gpu_gpu_fx_base: VRAM load address (e.g. 0x3800u).
  • gpu_gpu_fx_entry: Entry PC symbol (_gpu_start, typically equal to gpu_gpu_fx_base).
  • gpu_gpu_fx_end and gpu_gpu_fx_size: End address and byte length of the linked GPU image, plus addresses of any global mailbox variables exported by the GPU translation unit.

EXAMPLES

Unlock the F18A via ti_vdp_detect(3), upload a packed GPU image from cartridge ROM into VRAM, and start it:

#include <vdpinfo.h>
#include <resource_copy.h>
#include <f18a_gpu_host.h>
#include "resource_defs.h"
#include "gpu_fx_map.h"

if (ti_vdp_detect() != TI_VDP_STOCK) {
    f18a_gpu_stop();
    rom_to_vram(unwrap(gpu_fx), gpu_fx_base);
    f18a_gpu_start(gpu_fx_entry);
}

Upload a small inline GPU snippet from a array in CPU memory and launch it at VRAM 0x3F00:

f18a_gpu_load_and_start(0x3F00u, my_gpu_blob, sizeof(my_gpu_blob), 0x3F00u);

SEE ALSO

f18a_gpu(3), rom_to_vram(3), ti_vdp_detect(3), libc(3)

Source: resources/man/man3/f18a_gpu_host.3

Docs / API Reference / Strings & memory (string.h)

memchr

memchr(3)

locate byte in byte string

NAME

memchr — locate byte in byte string

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

void *
memchr(const void *s, int c, size_t n);

DESCRIPTION

Locates the first occurrence of c (converted to an unsigned char) in the initial n bytes of s.

RETURN VALUES

A pointer to the byte, or NULL if not found within n bytes.

SEE ALSO

memcpy(3), memmove(3), memset(3)

Source: resources/man/man3/memchr.3

Docs / API Reference / Strings & memory (string.h)

memcmp

memcmp(3)

compare byte strings

NAME

memcmp — compare byte strings

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

int
memcmp(const void *s1, const void *s2, size_t n);

DESCRIPTION

Compares the first n bytes of s1 and s2 as unsigned chars.

RETURN VALUES

Less than, equal to, or greater than zero if the first n bytes of s1 are lexicographically less than, equal to, or greater than those of s2.

SEE ALSO

memcpy(3), memchr(3), strcmp(3)

Source: resources/man/man3/memcmp.3

Docs / API Reference / Strings & memory (string.h)

memcpy

memcpy(3)

copy memory

NAME

memcpy — copy memory

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

void *
memcpy(void *dst, const void *src, size_t n);

DESCRIPTION

Copies n bytes from src to dst. The regions must not overlap; use memmove(3) if they might.

RETURN VALUES

Returns dst.

SEE ALSO

memmove(3), memset(3), memchr(3)

Source: resources/man/man3/memcpy.3

Docs / API Reference / Strings & memory (string.h)

memmove

memmove(3)

copy memory (overlap-safe)

NAME

memmove — copy memory (overlap-safe)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

void *
memmove(void *dst, const void *src, size_t n);

DESCRIPTION

Copies n bytes from src to dst. Unlike memcpy(3), overlapping regions are handled correctly.

RETURN VALUES

Returns dst.

SEE ALSO

memcpy(3), memset(3)

Source: resources/man/man3/memmove.3

Docs / API Reference / Strings & memory (string.h)

memset

memset(3)

fill memory with a byte

NAME

memset — fill memory with a byte

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

void *
memset(void *dst, int c, size_t n);

DESCRIPTION

Writes the low 8 bits of c into each of the first n bytes of dst.

RETURN VALUES

Returns dst.

SEE ALSO

memcpy(3), memmove(3), memchr(3)

Source: resources/man/man3/memset.3

Docs / API Reference / Strings & memory (string.h)

strcat

strcat(3)

concatenate strings

NAME

strcat — concatenate strings

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

char *
strcat(char *dst, const char *src);

DESCRIPTION

Appends src onto the end of dst, overwriting the terminating NUL of dst and adding a new one. dst must be large enough.

There is no strlcat(). For a bounded append see strncat(3).

RETURN VALUES

Returns dst.

SEE ALSO

strncat(3), strcpy(3), strlen(3)

Source: resources/man/man3/strcat.3

Docs / API Reference / Strings & memory (string.h)

strcmp

strcmp(3)

compare strings

NAME

strcmp — compare strings

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

int
strcmp(const char *s1, const char *s2);

DESCRIPTION

Compares the NUL-terminated strings s1 and s2 lexicographically as unsigned bytes.

RETURN VALUES

Less than, equal to, or greater than zero if s1 is lexicographically less than, equal to, or greater than s2.

SEE ALSO

strncmp(3), strlen(3)

Source: resources/man/man3/strcmp.3

Docs / API Reference / Strings & memory (string.h)

strcpy

strcpy(3)

copy a string

NAME

strcpy — copy a string

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

char *
strcpy(char *dst, const char *src);

DESCRIPTION

Copies the NUL-terminated string src into dst, including the terminating NUL. dst must be large enough.

Tidepod libc does not provide stpcpy(), stpncpy(), or strlcpy(). For a bounded copy see strncpy(3).

RETURN VALUES

Returns dst.

SEE ALSO

strncpy(3), strcat(3), strlen(3)

Source: resources/man/man3/strcpy.3

Docs / API Reference / Strings & memory (string.h)

strlen

strlen(3)

string length

NAME

strlen — string length

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

size_t
strlen(const char *s);

DESCRIPTION

Returns the number of characters before the first NUL in s. size_t is 16-bit on this platform.

For a bounded length see strnlen(3).

RETURN VALUES

Length of s, not counting the terminating NUL.

SEE ALSO

strnlen(3), strcpy(3)

Source: resources/man/man3/strlen.3

Docs / API Reference / Strings & memory (string.h)

strncat

strncat(3)

concatenate strings with length limit

NAME

strncat — concatenate strings with length limit

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

char *
strncat(char *dst, const char *src, size_t n);

DESCRIPTION

Appends at most n characters from src onto dst, then writes a terminating NUL. dst must have room for the existing string, up to n new characters, and the NUL.

There is no strlcat().

RETURN VALUES

Returns dst.

SEE ALSO

strcat(3), strncpy(3), strlen(3)

Source: resources/man/man3/strncat.3

Docs / API Reference / Strings & memory (string.h)

strncmp

strncmp(3)

compare strings with length limit

NAME

strncmp — compare strings with length limit

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

int
strncmp(const char *s1, const char *s2, size_t n);

DESCRIPTION

Compares at most n bytes of s1 and s2 as unsigned bytes. Comparison stops at a NUL in either string.

RETURN VALUES

Less than, equal to, or greater than zero according to the first differing byte, or zero if the compared prefixes are equal.

SEE ALSO

strcmp(3), strlen(3)

Source: resources/man/man3/strncmp.3

Docs / API Reference / Strings & memory (string.h)

strncpy

strncpy(3)

copy a string with length limit

NAME

strncpy — copy a string with length limit

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

char *
strncpy(char *dst, const char *src, size_t n);

DESCRIPTION

Copies at most n bytes from src to dst. If src is shorter than n, the remainder of dst is filled with NULs. If src is n bytes or longer, dst is not NUL-terminated.

There is no stpncpy() or strlcpy().

RETURN VALUES

Returns dst.

SEE ALSO

strcpy(3), strncat(3), strlen(3)

Source: resources/man/man3/strncpy.3

Docs / API Reference / Strings & memory (string.h)

strnlen

strnlen(3)

bounded string length

NAME

strnlen — bounded string length

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

size_t
strnlen(const char *s, size_t maxlen);

DESCRIPTION

Like strlen(3) but never scans past maxlen bytes.

SEE ALSO

strlen(3)

Source: resources/man/man3/strnlen.3

Docs / API Reference / Strings & memory (string.h)

strstr

strstr(3)

locate a substring in a string

NAME

strstr — locate a substring in a string

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

char *
strstr(const char *haystack, const char *needle);

DESCRIPTION

The strstr() function locates the first occurrence of the null-terminated string needle in the null-terminated string haystack.

RETURN VALUES

If needle is an empty string, haystack is returned; if needle occurs nowhere in haystack, NULL is returned; otherwise a pointer to the first character of the first occurrence of needle is returned.

SEE ALSO

strcmp(3), strncmp(3), strlen(3)

Source: resources/man/man3/strstr.3

Docs / API Reference / Strings & memory (string.h)

strtok

strtok(3)

string tokens

NAME

strtok — string tokens

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <string.h>

char *
strtok(char *str, const char *sep);

DESCRIPTION

The strtok() function is used to isolate sequential tokens in a null-terminated string, str. These tokens are separated in the string by at least one of the characters in sep. The first time that strtok() is called, str should be specified; subsequent calls, wishing to obtain further tokens from the same string, should pass a null pointer instead. The separator string, sep, must be supplied each time, and may change between calls.

The strtok() function modifies its first argument by replacing delimiter characters with null bytes.

RETURN VALUES

The strtok() function returns a pointer to the beginning of each subsequent token in the string, after replacing the separator character following it with a null byte. When no more tokens remain, a null pointer is returned.

SEE ALSO

strstr(3), strcmp(3)

BUGS

The strtok() function uses a static variable to maintain state between calls, so it is not reentrant.

Source: resources/man/man3/strtok.3

Docs / API Reference / Character classes (ctype.h)

ctype, isalnum, isalpha, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit, tolower, toupper

ctype(3)

character classification and case conversion functions

NAME

ctype, isalnum, isalpha, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit, tolower, toupper — character classification and case conversion functions

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
isalnum(int c);

int
isalpha(int c);

int
iscntrl(int c);

int
isdigit(int c);

int
isgraph(int c);

int
islower(int c);

int
isprint(int c);

int
ispunct(int c);

int
isspace(int c);

int
isupper(int c);

int
isxdigit(int c);

int
tolower(int c);

int
toupper(int c);

DESCRIPTION

The <ctype.h> functions classify and convert ASCII character values in the C locale.

isalnum()
Alphanumeric character (isalpha(or) isdigit()).
isalpha()
Alphabetic character (‘A–‘Z or ‘a–‘z’’’’).
iscntrl()
Control character (0x00–0x1F or 0x7F).
isdigit()
Decimal digit (‘0–‘9’’).
isgraph()
Printing character except space (0x21–0x7E).
islower()
Lowercase letter (‘a–‘z’’).
isprint()
Printing character including space (0x20–0x7E).
ispunct()
Printing character that is neither space nor alphanumeric.
isspace()
White-space character (space, form-feed, newline, carriage return, horizontal tab, vertical tab).
isupper()
Uppercase letter (‘A–‘Z’’).
isxdigit()
Hexadecimal digit (‘0–‘9, ‘A–‘F, or ‘a–‘f’’’’’’).
tolower()
Converts an uppercase letter to lowercase; returns c unchanged otherwise.
toupper()
Converts a lowercase letter to uppercase; returns c unchanged otherwise.

RETURN VALUES

The classification functions return non-zero if the character tests true and zero if it tests false. tolower() and toupper() return the converted character or c if no conversion applies.

SEE ALSO

isalnum(3), isalpha(3), iscntrl(3), isdigit(3), isgraph(3), islower(3), isprint(3), ispunct(3), isspace(3), isupper(3), isxdigit(3), libc(3), tolower(3), toupper(3)

STANDARDS

These functions conform to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/ctype.3

Docs / API Reference / Character classes (ctype.h)

isalnum

isalnum(3)

alphanumeric character test

NAME

isalnum — alphanumeric character test

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
isalnum(int c);

DESCRIPTION

The isalnum() function tests for any character for which isalpha(3) or isdigit(3) is true.

RETURN VALUES

The isalnum() function returns zero if the character tests false and returns non-zero if the character tests true.

SEE ALSO

isalpha(3), isdigit(3), ctype(3)

STANDARDS

The isalnum() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/isalnum.3

Docs / API Reference / Character classes (ctype.h)

isalpha

isalpha(3)

alphabetic character test

NAME

isalpha — alphabetic character test

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
isalpha(int c);

DESCRIPTION

The isalpha() function tests for any character for which isupper(3) or islower(3) is true. In the ASCII character set, this includes the following characters (listed in their numeric order):

A-Z a-z

RETURN VALUES

The isalpha() function returns zero if the character tests false and returns non-zero if the character tests true.

SEE ALSO

isalnum(3), isdigit(3), islower(3), isupper(3), ctype(3)

STANDARDS

The isalpha() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/isalpha.3

Docs / API Reference / Character classes (ctype.h)

iscntrl

iscntrl(3)

control character test

NAME

iscntrl — control character test

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
iscntrl(int c);

DESCRIPTION

The iscntrl() function tests for any control character. Control characters are those with ASCII values 0x00 through 0x1F and 0x7F (DEL).

RETURN VALUES

The iscntrl() function returns zero if the character tests false and returns non-zero if the character tests true.

SEE ALSO

isprint(3), isspace(3), ctype(3)

STANDARDS

The iscntrl() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/iscntrl.3

Docs / API Reference / Character classes (ctype.h)

isdigit

isdigit(3)

decimal-digit character test

NAME

isdigit — decimal-digit character test

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
isdigit(int c);

DESCRIPTION

The isdigit() function tests for a decimal digit character (0-9).

RETURN VALUES

The isdigit() function returns zero if the character tests false and returns non-zero if the character tests true.

SEE ALSO

isalnum(3), isalpha(3), isxdigit(3), ctype(3)

STANDARDS

The isdigit() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/isdigit.3

Docs / API Reference / Character classes (ctype.h)

isgraph

isgraph(3)

printing character test (excluding space)

NAME

isgraph — printing character test (excluding space)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
isgraph(int c);

DESCRIPTION

The isgraph() function tests for any printing character except space. The graphical characters are those with ASCII values 0x21 (‘!’) through 0x7E (‘~’).

RETURN VALUES

The isgraph() function returns zero if the character tests false and returns non-zero if the character tests true.

SEE ALSO

ctype(3), isalnum(3), iscntrl(3), isprint(3), ispunct(3), isspace(3)

STANDARDS

The isgraph() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/isgraph.3

Docs / API Reference / Character classes (ctype.h)

islower

islower(3)

lower-case character test

NAME

islower — lower-case character test

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
islower(int c);

DESCRIPTION

The islower() function tests for any lower-case letter (a-z).

RETURN VALUES

The islower() function returns zero if the character tests false and returns non-zero if the character tests true.

SEE ALSO

isupper(3), isalpha(3), tolower(3), ctype(3)

STANDARDS

The islower() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/islower.3

Docs / API Reference / Character classes (ctype.h)

isprint

isprint(3)

printing character test (including space)

NAME

isprint — printing character test (including space)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
isprint(int c);

DESCRIPTION

The isprint() function tests for any printing character, including space. This is any character for which iscntrl(3) is false. The printable characters are those with ASCII values 0x20 (space) through 0x7E (~).

RETURN VALUES

The isprint() function returns zero if the character tests false and returns non-zero if the character tests true.

SEE ALSO

iscntrl(3), isalnum(3), ispunct(3), ctype(3)

STANDARDS

The isprint() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/isprint.3

Docs / API Reference / Character classes (ctype.h)

ispunct

ispunct(3)

punctuation character test

NAME

ispunct — punctuation character test

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
ispunct(int c);

DESCRIPTION

The ispunct() function tests for any printing character that is not a space or a character for which isalnum(3) is true.

RETURN VALUES

The ispunct() function returns zero if the character tests false and returns non-zero if the character tests true.

SEE ALSO

isalnum(3), isprint(3), isspace(3), ctype(3)

STANDARDS

The ispunct() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/ispunct.3

Docs / API Reference / Character classes (ctype.h)

isspace

isspace(3)

white-space character test

NAME

isspace — white-space character test

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
isspace(int c);

DESCRIPTION

The isspace() function tests for the standard white-space characters. These are:

horizontal tab
newline
vertical tab
form feed
carriage return
“ ”
space

RETURN VALUES

The isspace() function returns zero if the character tests false and returns non-zero if the character tests true.

SEE ALSO

isalnum(3), isalpha(3), isprint(3), ctype(3)

STANDARDS

The isspace() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/isspace.3

Docs / API Reference / Character classes (ctype.h)

isupper

isupper(3)

upper-case character test

NAME

isupper — upper-case character test

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
isupper(int c);

DESCRIPTION

The isupper() function tests for any upper-case letter (A-Z).

RETURN VALUES

The isupper() function returns zero if the character tests false and returns non-zero if the character tests true.

SEE ALSO

islower(3), isalpha(3), toupper(3), ctype(3)

STANDARDS

The isupper() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/isupper.3

Docs / API Reference / Character classes (ctype.h)

isxdigit

isxdigit(3)

hexadecimal-digit character test

NAME

isxdigit — hexadecimal-digit character test

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
isxdigit(int c);

DESCRIPTION

The isxdigit() function tests for any hexadecimal-digit character. These are: 0-9, A-F, and a-f.

RETURN VALUES

The isxdigit() function returns zero if the character tests false and returns non-zero if the character tests true.

SEE ALSO

isdigit(3), isalnum(3), ctype(3)

STANDARDS

The isxdigit() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/isxdigit.3

Docs / API Reference / Character classes (ctype.h)

tolower

tolower(3)

upper case to lower case letter conversion

NAME

tolower — upper case to lower case letter conversion

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
tolower(int c);

DESCRIPTION

The tolower() function converts an upper-case letter to the corresponding lower-case letter. The argument must be representable as an unsigned char or the value of EOF.

RETURN VALUES

If the argument is an upper-case letter, the tolower() function returns the corresponding lower-case letter if there is one; otherwise, the argument is returned unchanged.

SEE ALSO

toupper(3), isupper(3), islower(3), ctype(3)

STANDARDS

The tolower() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/tolower.3

Docs / API Reference / Character classes (ctype.h)

toupper

toupper(3)

lower case to upper case letter conversion

NAME

toupper — lower case to upper case letter conversion

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <ctype.h>

int
toupper(int c);

DESCRIPTION

The toupper() function converts a lower-case letter to the corresponding upper-case letter. The argument must be representable as an unsigned char or the value of EOF.

RETURN VALUES

If the argument is a lower-case letter, the toupper() function returns the corresponding upper-case letter if there is one; otherwise, the argument is returned unchanged.

SEE ALSO

tolower(3), isupper(3), islower(3), ctype(3)

STANDARDS

The toupper() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Source: resources/man/man3/toupper.3

Docs / API Reference / Utilities (stdlib.h)

abort

abort(3)

abnormal program termination

NAME

abort — abnormal program termination

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

void
abort(void);

DESCRIPTION

Enters an infinite loop. There is no host OS to deliver a signal or dump core on the TI-99/4A.

RETURN VALUES

Does not return.

SEE ALSO

exit(3)

Source: resources/man/man3/abort.3

Docs / API Reference / Utilities (stdlib.h)

abs

abs(3)

integer absolute value

NAME

abs — integer absolute value

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

int
abs(int i);

DESCRIPTION

Returns the absolute value of i. int is 16-bit on this platform; the absolute value of INT_MIN is undefined in the usual C sense.

RETURN VALUES

The absolute value of i.

SEE ALSO

atoi(3)

Source: resources/man/man3/abs.3

Docs / API Reference / Utilities (stdlib.h)

atoi, atol

atoi(3)

convert string to integer

NAME

atoi, atol — convert string to integer

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

int
atoi(const char *str);

long
atol(const char *str);

DESCRIPTION

See strtol(3).

SEE ALSO

strtol(3)

Source: resources/man/man3/atoi.3

Docs / API Reference / Utilities (stdlib.h)

atol

atol(3)

convert string to long

NAME

atol — convert string to long

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

long
atol(const char *str);

DESCRIPTION

See strtol(3).

SEE ALSO

strtol(3)

Source: resources/man/man3/atol.3

Docs / API Reference / Utilities (stdlib.h)

calloc

calloc(3)

allocate zero-initialized near-heap memory in high 32K expansion

NAME

calloc — allocate zero-initialized near-heap memory in high 32K expansion

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

void *
calloc(size_t count, size_t size);

DESCRIPTION

calloc() allocates space from the near heap for an array of count objects, each of size bytes, and initializes all allocated bytes to zero.

The near heap resides in high expansion RAM after .bss when the project heapSize (or linker --defsym=__heap_size=N / packer --heap-size) is greater than zero; see malloc(3) for arena layout and configuration. For SuperAMS fat-pointer allocations, use sams_calloc() (see sams(3)).

RETURN VALUES

calloc() returns a word-aligned pointer to the zeroed allocation, or NULL on failure, overflow, or when __heap_size is 0.

SEE ALSO

free(3), malloc(3), realloc(3), sams(3)

Source: resources/man/man3/calloc.3

Docs / API Reference / Utilities (stdlib.h)

exit, _Exit

exit(3)

halt the program

NAME

exit, _Exit — halt the program

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

void
exit(int status);

void
_Exit(int status);

DESCRIPTION

Both functions ignore status and enter an infinite loop. There is no process model, no atexit() registry, and no stream flush on exit. Cartridge programs should normally end main() with an endless loop instead of calling exit().

_Exit() is identical to exit() in Tidepod libc.

RETURN VALUES

Do not return.

SEE ALSO

abort(3)

Source: resources/man/man3/exit.3

Docs / API Reference / Utilities (stdlib.h)

free

free(3)

free near-heap memory in high 32K expansion

NAME

free — free near-heap memory in high 32K expansion

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

void
free(void *ptr);

DESCRIPTION

free() releases a block previously allocated from the near heap by malloc(3), calloc(3), or realloc(3) and coalesces adjacent free chunks in constant time. If ptr is NULL, no action is performed.

The near heap resides in high expansion RAM after .bss when the project heapSize (or linker --defsym=__heap_size=N / packer --heap-size) is greater than zero; see malloc(3) for arena layout and configuration. For SuperAMS fat-pointer allocations, use sams_free() (see sams(3)).

RETURN VALUES

free() returns no value.

SEE ALSO

calloc(3), malloc(3), realloc(3), sams(3)

Source: resources/man/man3/free.3

Docs / API Reference / Utilities (stdlib.h)

malloc, free, calloc, realloc, mallinfo, get_free_heap, malloc_walk

malloc(3)

near-heap allocator in high 32K expansion

NAME

malloc, free, calloc, realloc, mallinfo, get_free_heap, malloc_walk — near-heap allocator in high 32K expansion

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

void *
malloc(size_t size);

void
free(void *ptr);

void *
calloc(size_t count, size_t size);

void *
realloc(void *ptr, size_t size);

struct mallinfo
mallinfo(void);

unsigned
get_free_heap(void);

void
malloc_walk(void (*fn)(void *addr, unsigned size, int is_free, void *ctx), void *ctx);

DESCRIPTION

These functions manage a near heap in high expansion RAM after .bss. Native pointers remain 16-bit.

The arena is [_bss_end, _bss_end + N) where N is the absolute linker symbol __heap_size (C reads it as (unsigned)&__heap_size), not a load from memory . crt0 writes one free-chunk header when N is non-zero (linker PROVIDE(__heap_size = 0)), overridden by --defsym=__heap_size=N.

Project reservation

Set heapSize in the .project file (bytes). Tidepod passes --heap-size to tms9900-packer (so auto-promoted .persistent_high) does not consume the arena and --defsym=__heap_size to the linker. Default 0 means no heap (promotion stays aggressive; malloc()) returns NULL.

Each allocated block has a 2-byte header (size in words, free bit, prev_free bit). Free blocks also store a size footer so free() coalesces adjacent free chunks in constant time. malloc() searches a LIFO free list only (first fit with split).

Querying free space

There is no POSIX API for “free heap bytes”. This libc provides the glibc/BSD-shaped mallinfo() (not in POSIX.1). fordblks is free bytes in the arena (including free-chunk headers). get_free_heap() returns the same value. malloc_walk() visits every chunk for debugging.

On a machine with SuperAMS present, the near arena is clipped under >C000 so SAMS lock windows never overlay malloc() blocks. Large allocations use sams_malloc() (see) sams(3).

heapSize should stay modest on SAMS carts; the fat heap is the large store.

RETURN VALUES

malloc(), calloc(), and realloc() return a word-aligned pointer, or NULL on failure or when __heap_size is 0. free() of NULL is a no-op.

SEE ALSO

abs(3), qsort(3), sams(3)

Source: resources/man/man3/malloc.3

Docs / API Reference / Utilities (stdlib.h)

qsort

qsort(3)

sort an array

NAME

qsort — sort an array

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

void
qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *));

DESCRIPTION

Sorts nel elements of width bytes each. Stability is not guaranteed. Uses a small in-place algorithm suitable for 16-bit size_t.

SEE ALSO

abs(3)

Source: resources/man/man3/qsort.3

Docs / API Reference / Utilities (stdlib.h)

rand, srand

rand(3)

simple pseudo-random number generator

NAME

rand, srand — simple pseudo-random number generator

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

int
rand(void);

void
srand(unsigned seed);

DESCRIPTION

rand() returns the next value in a linear congruential sequence. srand() sets the seed.

Only these two functions are provided. There is no rand_r(), sranddev(), or arc4random().

RETURN VALUES

rand() returns a non-negative int (16-bit range on this platform).

SEE ALSO

abs(3)

Source: resources/man/man3/rand.3

Docs / API Reference / Utilities (stdlib.h)

realloc

realloc(3)

resize near-heap allocation in high 32K expansion

NAME

realloc — resize near-heap allocation in high 32K expansion

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

void *
realloc(void *ptr, size_t size);

DESCRIPTION

realloc() changes the size of the near-heap block pointed to by ptr to size bytes, copying existing contents up to the lesser of the old and new sizes when moving the block. If ptr is NULL, realloc() behaves like malloc(size). If size is 0, ptr is freed and NULL is returned.

The near heap resides in high expansion RAM after .bss when the project heapSize (or linker --defsym=__heap_size=N / packer --heap-size) is greater than zero; see malloc(3) for arena layout and configuration. For SuperAMS fat-pointer allocations, use sams_realloc() (see sams(3)).

RETURN VALUES

realloc() returns a word-aligned pointer to the resized block, or NULL on failure or when __heap_size is 0 (leaving the original block unchanged on allocation failure).

SEE ALSO

calloc(3), free(3), malloc(3), sams(3)

Source: resources/man/man3/realloc.3

Docs / API Reference / Utilities (stdlib.h)

strtol, strtoul, atoi, atol

strtol(3)

convert string to integer

NAME

strtol, strtoul, atoi, atol — convert string to integer

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

long
strtol(const char *str, char **endptr, int base);

unsigned long
strtoul(const char *str, char **endptr, int base);

int
atoi(const char *str);

long
atol(const char *str);

DESCRIPTION

long is 32-bit on this target. base 0 means auto-detect (0x) hex, leading 0 octal, else decimal. No errno is set; overflow wraps modulo 2^32. atoi() is (int)strtol(str, NULL, 10).

SEE ALSO

abs(3)

Source: resources/man/man3/strtol.3

Docs / API Reference / Utilities (stdlib.h)

strtoul

strtoul(3)

convert string to unsigned long

NAME

strtoul — convert string to unsigned long

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <stdlib.h>

unsigned long
strtoul(const char *str, char **endptr, int base);

DESCRIPTION

See strtol(3).

SEE ALSO

strtol(3)

Source: resources/man/man3/strtoul.3

Docs / API Reference / Error codes (errno.h)

errno

errno(3)

system and library error numbers

NAME

errno — system and library error numbers

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <errno.h>

extern int errno;

DESCRIPTION

The header <errno.h> declares the modifiable global integer errno and defines standard POSIX-shaped error constants for Tidepod libc.

Defined error constants:

EPERM
1 — Operation not permitted
ENOENT
2 — No such file or directory
EIO
5 — Input/output error
ENXIO
6 — No such device or address
EBADF
9 — Bad file descriptor
ENOMEM
12 — Cannot allocate memory
EACCES
13 — Permission denied
EEXIST
17 — File exists
EXDEV
18 — Cross-device link
ENODEV
19 — Operation not supported by device
ENOTDIR
20 — Not a directory
EISDIR
21 — Is a directory
EINVAL
22 — Invalid argument
ENFILE
23 — Too many open files in system
EMFILE
24 — Too many open files
ENOSPC
28 — No space left on device
EROFS
30 — Read-only file system
ENOTSUP
95 — Operation not supported
ETIMEDOUT
110 — Operation timed out

Native filesystem backends (chip floppy, FAT12, HFDC WDS) set errno on failure in addition to recording a DSR status code. Classic Level-3 PAB disk operations record their primary status via stdio_last_error(3) and do not always update errno.

SEE ALSO

fopen(3), libc(3), remove(3), stdio_last_error(3), ti_stat(3)

Source: resources/man/man3/errno.3

Docs / API Reference / Soft-float math (math.h)

atanf

atanf(3)

inverse tangent (float)

NAME

atanf — inverse tangent (float)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
atanf(float x);

DESCRIPTION

The atanf() function computes the principal value of the arc tangent of x.

RETURN VALUES

The arc tangent of x in the range [-π/2, +π/2] radians.

SEE ALSO

sinf(3), tanf(3)

Source: resources/man/man3/atanf.3

Docs / API Reference / Soft-float math (math.h)

ceilf, floorf

ceilf(3)

floor and ceiling functions (float)

NAME

floorf, ceilf — floor and ceiling functions (float)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
floorf(float x);

float
ceilf(float x);

DESCRIPTION

The floorf() function returns the largest integer value not greater than x.

The ceilf() function returns the smallest integer value not less than x.

RETURN VALUES

floorf() returns floor(x); ceilf() returns ceil(x). Both return float values.

EXAMPLES

floorf(3.7f) /* returns 3.0f */
floorf(-3.7f) /* returns -4.0f */
ceilf(3.2f) /* returns 4.0f */
ceilf(-3.2f) /* returns -3.0f */

SEE ALSO

fabsf(3), fmodf(3)

Source: resources/man/man3/ceilf.3

Docs / API Reference / Soft-float math (math.h)

cosf, sinf, tanf

cosf(3)

trigonometric functions (float)

NAME

sinf, cosf, tanf — trigonometric functions (float)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
sinf(float x);

float
cosf(float x);

float
tanf(float x);

DESCRIPTION

IEEE 754 binary32 soft-float implementations. x is in radians. Accuracy is modest; prefer fixed-point for hot loops.

SEE ALSO

atanf(3), sqrtf(3)

Source: resources/man/man3/cosf.3

Docs / API Reference / Soft-float math (math.h)

expf

expf(3)

exponential function (float)

NAME

expf — exponential function (float)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
expf(float x);

DESCRIPTION

The expf() function computes the base-e exponential of x.

RETURN VALUES

The value e^x.

SEE ALSO

logf(3), powf(3)

Source: resources/man/man3/expf.3

Docs / API Reference / Soft-float math (math.h)

fabsf

fabsf(3)

absolute value (float)

NAME

fabsf — absolute value (float)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
fabsf(float x);

DESCRIPTION

The fabsf() function computes the absolute value of the floating-point number x.

RETURN VALUES

The absolute value of x.

SEE ALSO

abs(3), fmodf(3)

Source: resources/man/man3/fabsf.3

Docs / API Reference / Soft-float math (math.h)

floorf, ceilf

floorf(3)

floor and ceiling functions (float)

NAME

floorf, ceilf — floor and ceiling functions (float)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
floorf(float x);

float
ceilf(float x);

DESCRIPTION

The floorf() function returns the largest integer value not greater than x.

The ceilf() function returns the smallest integer value not less than x.

RETURN VALUES

floorf() returns floor(x); ceilf() returns ceil(x). Both return float values.

EXAMPLES

floorf(3.7f) /* returns 3.0f */
floorf(-3.7f) /* returns -4.0f */
ceilf(3.2f) /* returns 4.0f */
ceilf(-3.2f) /* returns -3.0f */

SEE ALSO

fabsf(3), fmodf(3)

Source: resources/man/man3/floorf.3

Docs / API Reference / Soft-float math (math.h)

fmodf

fmodf(3)

floating-point remainder

NAME

fmodf — floating-point remainder

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
fmodf(float x, float y);

DESCRIPTION

The fmodf() function computes the floating-point remainder of x divided by y. The result has the same sign as x.

RETURN VALUES

The remainder x - n*y, where n is the quotient x/y truncated toward zero. If y is 0.0f, fmodf() returns 0.0f.

SEE ALSO

fabsf(3)

Source: resources/man/man3/fmodf.3

Docs / API Reference / Soft-float math (math.h)

logf

logf(3)

natural logarithm (float)

NAME

logf — natural logarithm (float)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
logf(float x);

DESCRIPTION

The logf() function computes the natural (base-e) logarithm of x.

RETURN VALUES

The natural logarithm of x. If x is less than or equal to 0.0f, logf() returns 0.0f.

SEE ALSO

expf(3), powf(3)

Source: resources/man/man3/logf.3

Docs / API Reference / Soft-float math (math.h)

powf

powf(3)

power function (float)

NAME

powf — power function (float)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
powf(float x, float y);

DESCRIPTION

The powf() function computes x raised to the power y. Implemented as expf(y * logf(fabsf(x))) (returning 0.0f when x == 0.0f).

RETURN VALUES

The value x^y.

SEE ALSO

expf(3), logf(3), sqrtf(3)

Source: resources/man/man3/powf.3

Docs / API Reference / Soft-float math (math.h)

sinf, cosf, tanf

sinf(3)

trigonometric functions (float)

NAME

sinf, cosf, tanf — trigonometric functions (float)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
sinf(float x);

float
cosf(float x);

float
tanf(float x);

DESCRIPTION

IEEE 754 binary32 soft-float implementations. x is in radians. Accuracy is modest; prefer fixed-point for hot loops.

SEE ALSO

atanf(3), sqrtf(3)

Source: resources/man/man3/sinf.3

Docs / API Reference / Soft-float math (math.h)

sqrtf

sqrtf(3)

square root (float)

NAME

sqrtf — square root (float)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
sqrtf(float x);

DESCRIPTION

IEEE soft-float square root. Negative inputs return 0.0f.

SEE ALSO

powf(3), fabsf(3)

Source: resources/man/man3/sqrtf.3

Docs / API Reference / Soft-float math (math.h)

tanf, sinf, cosf

tanf(3)

trigonometric functions (float)

NAME

sinf, cosf, tanf — trigonometric functions (float)

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <math.h>

float
sinf(float x);

float
cosf(float x);

float
tanf(float x);

DESCRIPTION

IEEE 754 binary32 soft-float implementations. x is in radians. Accuracy is modest; prefer fixed-point for hot loops.

SEE ALSO

atanf(3), sqrtf(3)

Source: resources/man/man3/tanf.3

Docs / API Reference / Other libc pages

libc

libc(3)

TI-99/4A C library overview

NAME

libc — TI-99/4A C library overview

DESCRIPTION

Tidepod/tms9900-gcc libc is a freestanding-friendly C library built as tiny translation units so the packer can bank unused symbols away.

Provided: string and ctype; stdlib including near-heap allocation when heapSize / --heap-size is configured (atoi, strtol, rand, qsort, exit, malloc, free, calloc, realloc); console printf / putchar and conio(3) cursor I/O on the VDP; keyboard (cgetc, kbhit); ti_vdp_detect(3) and ti_text_mode(3) for F18A/Pico9918 and 32/40/80-column text; banked ROM resource streaming via resource_copy(3) / rom_to_vram(3); F18A GPU host loader and coprocessor macros via f18a_gpu_host(3) and f18a_gpu(3); zero-cost host logpoints, soft breakpoints, and cycle profiling via debug(3) and profiler(3); SuperAMS mapper helpers and fat pointers via sams(3) (detect, map, lock, accessors, sams_malloc); mathf via soft-float; disk fopen(3) family (mode grammar with :df|:dv|:if|:iv|:pg), FDR probe on existing files, PROGRAM as AU byte streams, fcopy_path; catalog ti_opendir(3), DSR unit discovery ti_dsr_enum(3), metadata (ti_stat, ti_protect, ti_mkdir, ti_rmdir), and remove(3) / rename. Default fopen() is Level-3 PAB only; native chip / FAT / WDS / PROGRAM-AU backends are opt-in via stdio_enable(3). Disk path APIs copy path/mode into stack scratch at entry so banked callers remain safe across trampolines (packer also hoists string literals for trampoline TUs). Level-3 PAB VRAM placement uses stdio_set_vdp_base(3) (default 0x3000); HFDC Level-2 sector DMA uses stdio_set_wds_vdp_buf(3) (default 0x3DA8).

Disk errors: after a failed fopen / fcopy_path / remove / ti_opendir, read stdio_last_error(3) (DSR status). errno is secondary and not always updated for Level-3 PAB failures.

Not provided: asprintf.

Type model: int / size_t are 16-bit; long is 32-bit; float is IEEE binary32 soft-float.

SEE ALSO

conio(3), debug(3), f18a_gpu(3), f18a_gpu_host(3), fopen(3), malloc(3), printf(3), profiler(3), resource_copy(3), rom_to_vram(3), sams(3), stdio_enable(3), stdio_last_error(3), stdio_set_vdp_base(3), stdio_set_wds_vdp_buf(3), ti_dsr_enum(3), ti_opendir(3), ti_text_mode(3), ti_vdp_detect(3)

Source: resources/man/man3/libc.3

Docs / API Reference / Other libc pages

SAMS_FAR, SAMS_FAR_PTR, SAMS_FAR_OBJ, sams_new, sams_new_bytes, sams_delete, SAMS_WITH_NEAR

sams_far(3)

optional syntactic sugar for SuperAMS __sams pointers

NAME

SAMS_FAR, SAMS_FAR_PTR, SAMS_FAR_OBJ, sams_new, sams_new_bytes, sams_delete, SAMS_WITH_NEAR — optional syntactic sugar for SuperAMS __sams pointers

LIBRARY

Standard C Library (libc, -lc)

SYNOPSIS

#include <sams_far.h>

#define SAMS_FAR              __sams
#define SAMS_FAR_PTR(type)    type __sams *
#define SAMS_FAR_OBJ(type, name)  type __sams name

#define sams_new(type, count)     /* typed sams_calloc */
#define sams_new_bytes(n)         /* sams_malloc as uchar __sams * */
#define sams_delete(p)            sams_free((sams_ptr_t)(p))

#define SAMS_WITH_NEAR(far_p, type, near_name, block)  /* lock…unlock */

DESCRIPTION

<sams_far.h> is an optional convenience layer over <sams.h>. It does not add a second ABI; every macro expands to the named address space qualifier __sams or to existing sams_malloc(/) sams_calloc(/) sams_lock() helpers.

Use it when application code wants shorter names or typed allocs. Raw __sams is equally supported. Requires -std=gnu99 (Tidepod default).

See docs/sams_tutorial.md and resources/examples/sams_tutorial/.

SEE ALSO

sams(3), malloc(3)

Source: resources/man/man3/sams_far.3

Docs / API Reference / Extended BASIC runtime (CALL …)

ASC

asc(3xb)

return ASCII code of a string's first character (not implemented yet)

NAME

ASC — return ASCII code of a string's first character (not implemented yet)

SYNOPSIS

ASC(string$);

DESCRIPTION

UNIMPLEMENTED — not available in the current XB compiler or libxb.

The classic XB ASC() function would return the ASCII code (0–255) of the first character of string$. It is not recognized by the frontend today: a call such as ‘ASC(S$)’ is parsed as an array reference and will not compile as a builtin.

EXAMPLES

100 C = ASC("HELLO")   ! does not work yet

SEE ALSO

chr(3xb), xb-string(7)

Source: resources/man/man3/asc.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

CHAR

char(3xb)

redefine a character's graphical pattern

NAME

CHAR — redefine a character's graphical pattern

SYNOPSIS

CALL CHAR(char_code, pattern$);

DESCRIPTION

The CALL CHAR() statement redefines the visual representation of one or more characters. char_code is the starting ASCII character code to redefine (typically 32–143). pattern$ must be a compile-time hexadecimal string literal where each 16 hex digits (8 bytes) define one 8×8 pixel grid, MSB-left from top row to bottom row.

Multi-character definitions up to 512 hex digits (32 consecutive characters starting at char_code) are supported; partial 8-byte blocks are zero-padded. In ‘libxb’, patterns are written to both the VDP Pattern Descriptor Table (‘0x0800’) and the Sprite Pattern Table (‘0x1800’).

EXAMPLES

100 CALL CHAR(33, "FFFFFFFFFFFFFFFF")

SEE ALSO

charset(3xb)

Source: resources/man/man3/char.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

CHARSET

charset(3xb)

restore standard character patterns

NAME

CHARSET — restore standard character patterns

SYNOPSIS

CALL CHARSET();

DESCRIPTION

The CALL CHARSET() statement restores the default TI-99/4A font patterns for ASCII characters 32 through 127 (character sets 1 through 12, including uppercase and lowercase letters) in the VDP Pattern Descriptor Table (‘0x0800’), erasing any custom definitions created by CALL CHAR() for those characters.

EXAMPLES

100 CALL CHARSET

SEE ALSO

char(3xb)

Source: resources/man/man3/charset.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

chr

chr(3xb)

return character corresponding to ASCII code (not implemented yet)

NAME

CHR$ — return character corresponding to ASCII code (not implemented yet)

SYNOPSIS

CHR$(ascii_code);

DESCRIPTION

UNIMPLEMENTED — not available in the current XB compiler or libxb.

The classic XB CHR$() function would return a one-character string for ascii_code (0–255). It is not recognized by the frontend today.

EXAMPLES

100 A$ = CHR$(65)   ! does not work yet

SEE ALSO

asc(3xb), xb-string(7)

Source: resources/man/man3/chr.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

CLEAR

clear(3xb)

clear the screen and reset the VDP cursor

NAME

CLEAR — clear the screen and reset the VDP cursor

SYNOPSIS

CALL CLEAR();

DESCRIPTION

The CALL CLEAR() statement clears the 32×24 screen by filling the 768-byte VDP Name Table with the space character (ASCII 32) and resets the cursor to the top-left corner. In ‘libxb’, CALL CLEAR() also clears all hardware sprites (writes ‘0xD0’ to the Sprite Attribute List at ‘0x0380’ and resets sprite motion state).

EXAMPLES

100 CALL CLEAR
110 DISPLAY AT(1,1):"SCREEN CLEARED"

SEE ALSO

display_at(3xb), screen(3xb)

Source: resources/man/man3/clear.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

COINC

coinc(3xb)

detect collisions between sprites or dots

NAME

COINC — detect collisions between sprites or dots

SYNOPSIS

CALL COINC(#sp1, #sp2, tol, var);

CALL COINC(ALL, var);

DESCRIPTION

The CALL COINC() statement checks for sprite collisions and stores the result in var (-1 for true, 0 for false).

Two forms are supported:

  • CALL COINC(#sp1, #sp2, tol, var) checks whether Both (abs(dy) <= tol) and (abs(dx) <= tol) between sprites #sp1 and #sp2.
  • CALL COINC(ALL, var) checks the hardware VDP status register coincidence bit (or falls back to a bounding-box pair scan across active sprites).

Note: The 5-argument pixel-coordinate form ‘CALL COINC(#sp1, row, col, tol, var)’ is not yet implemented.

EXAMPLES

100 CALL COINC(#1, #2, 8, HIT)
110 IF HIT THEN 500

SEE ALSO

distance(3xb)

Source: resources/man/man3/coinc.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

COLOR

color(3xb)

define foreground and background colors for a character set

NAME

COLOR — define foreground and background colors for a character set

SYNOPSIS

CALL COLOR(character_set, foreground, background);

DESCRIPTION

The CALL COLOR() statement assigns a foreground and background color to a specific character set. The TI-99/4A divides its 256 characters into 32 sets of 8 characters each.

character_set must be between 1 and 14 (or up to 32, depending on graphics mode). foreground and background must be colors from 1 to 16.

The available colors are:

1 Transparent
2 Black
3 Medium Green
4 Light Green
5 Dark Blue
6 Light Blue
7 Dark Red
8 Cyan
9 Medium Red
10 Light Red
11 Dark Yellow
12 Light Yellow
13 Dark Green
14 Magenta
15 Gray
16 White

EXAMPLES

100 CALL COLOR(1, 16, 2)

SEE ALSO

screen(3xb)

Source: resources/man/man3/color.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

DELSPRITE

delsprite(3xb)

delete a specific sprite or all active sprites

NAME

DELSPRITE — delete a specific sprite or all active sprites

SYNOPSIS

CALL DELSPRITE((#no | ALL));

DESCRIPTION

The CALL DELSPRITE() statement removes sprites from the screen. Passing a sprite number removes only that sprite. Passing ALL removes all currently active sprites.

EXAMPLES

100 CALL DELSPRITE(#1)
110 CALL DELSPRITE(ALL)

SEE ALSO

sprite(3xb)

Source: resources/man/man3/delsprite.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

DISPLAY AT

display_at(3xb)

print text at a specific screen location

NAME

DISPLAY AT — print text at a specific screen location

SYNOPSIS

DISPLAY AT(row, col) [SIZE(n)]: expr

CALL DISPLAY_AT(row, col, text$);

DESCRIPTION

The DISPLAY AT() statement positions the text cursor at row (1–24) and col (1–28) and prints the expression following the colon (‘:’). In matching classic TI Extended BASIC's 28-column text window, col is offset by +2 columns on the 32-column hardware screen (so column 1 maps to screen column 3).

If the optional SIZE(n) clause is given, the output field is padded or truncated to n characters; without SIZE, the remainder of the 28-column row is cleared before printing.

Numeric expressions are formatted via xb_itoa(); floating-point values are truncated to integers when formatted by DISPLAY AT(). The subroutine form CALL DISPLAY_AT(row, col, text$) is also supported.

EXAMPLES

100 DISPLAY AT(12, 10):"HELLO WORLD"
110 DISPLAY AT(1, 1) SIZE(6):SCORE%

SEE ALSO

clear(3xb), xb-io(7)

Source: resources/man/man3/display_at.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

DISTANCE

distance(3xb)

compute the squared distance between two sprites

NAME

DISTANCE — compute the squared distance between two sprites

SYNOPSIS

CALL DISTANCE(#sp1, #sp2, var);

DESCRIPTION

The CALL DISTANCE() statement calculates the squared Euclidean pixel distance (dy*dy + dx*dx) between sprite #sp1 and sprite #sp2, clamped to ‘32767’ on 16-bit signed overflow, and stores the result in var.

Note: The 4-argument pixel-coordinate form ‘CALL DISTANCE(#sp1, row, col, var)’ is not yet implemented.

EXAMPLES

100 CALL DISTANCE(#1, #2, DIST)

SEE ALSO

coinc(3xb)

Source: resources/man/man3/distance.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

GCHAR

gchar(3xb)

read the character code at a screen position

NAME

GCHAR — read the character code at a screen position

SYNOPSIS

CALL GCHAR(row, col, return_var);

DESCRIPTION

The CALL GCHAR() statement reads the ASCII code of the character currently displayed at the specified row and col, and stores it in return_var.

EXAMPLES

100 CALL GCHAR(12, 16, CH)
110 IF CH=32 THEN 200

SEE ALSO

hchar(3xb), vchar(3xb)

Source: resources/man/man3/gchar.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

HCHAR

hchar(3xb)

draw a horizontal line of characters

NAME

HCHAR — draw a horizontal line of characters

SYNOPSIS

CALL HCHAR(row, col, char_code, [count]);

DESCRIPTION

The CALL HCHAR() statement places character char_code at row (1–24) and col (1–32). If the optional count is provided (default 1), it repeats the character horizontally to the right count times, wrapping at column 32 to column 1 of the next row (and wrapping from row 24, column 32 back to row 1, column 1).

EXAMPLES

100 CALL HCHAR(12, 16, 33, 10)

SEE ALSO

vchar(3xb), gchar(3xb)

Source: resources/man/man3/hchar.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

INIT

init(3xb)

initialize Extended BASIC expansion state

NAME

INIT — initialize Extended BASIC expansion state

SYNOPSIS

CALL INIT();

DESCRIPTION

In classic TI Extended BASIC, CALL INIT() initializes the 32K memory expansion for assembly language subprograms loaded via CALL LOAD(). In compiled ‘libxb’ programs, CALL INIT() is accepted for source compatibility and performs runtime state initialization (no-op when hardware and VDP state are already initialized by the startup code).

EXAMPLES

100 CALL INIT

SEE ALSO

clear(3xb), load(3xb)

Source: resources/man/man3/init.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

JOYST

joyst(3xb)

read joystick directional input

NAME

JOYST — read joystick directional input

SYNOPSIS

CALL JOYST(unit, return_x, return_y);

DESCRIPTION

The CALL JOYST() statement reads the directional status of joystick unit (1 or 2). return_x and return_y are populated with -4, 0, or 4 depending on the joystick's deflection.

EXAMPLES

100 CALL JOYST(1, X, Y)

SEE ALSO

key(3xb)

Source: resources/man/man3/joyst.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

KEY

key(3xb)

scan the keyboard or joysticks for input

NAME

KEY — scan the keyboard or joysticks for input

SYNOPSIS

CALL KEY(unit, return_key, return_status);

DESCRIPTION

The CALL KEY() statement reads the keyboard or joystick inputs without halting the program. unit defines which hardware to scan:

0 Console keyboard
1 Joystick 1
2 Joystick 2
3 Left side of split keyboard
4 Right side of split keyboard
5 Pascal keyboard mode

return_key is populated with the ASCII keycode of the pressed key (or 255 if none). return_status is populated with 1 if a new key was pressed, -1 if the same key was held, or 0 if no key is pressed.

EXAMPLES

100 CALL KEY(0, K, S)
110 IF S=0 THEN 100

SEE ALSO

joyst(3xb)

Source: resources/man/man3/key.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

LEN

len(3xb)

return the length of a string (not implemented yet)

NAME

LEN — return the length of a string (not implemented yet)

SYNOPSIS

LEN(string$);

DESCRIPTION

UNIMPLEMENTED — not available in the current XB compiler or libxb.

The classic XB LEN() function would return the number of characters in string$. It is not recognized by the frontend today.

EXAMPLES

100 L = LEN("HELLO")   ! does not work yet

SEE ALSO

seg(3xb), xb-string(7)

Source: resources/man/man3/len.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

LOAD

load(3xb)

write bytes into CPU RAM (not implemented yet)

NAME

LOAD — write bytes into CPU RAM (not implemented yet)

SYNOPSIS

CALL LOAD(address, val1, [val2...]);

DESCRIPTION

UNIMPLEMENTED — not available in the current XB compiler or libxb.

Classic TI BASIC CALL LOAD() is not recognized as a builtin. There is no ‘LOAD’ alias for CALL POKE().

Use poke(3xb) to write a 16-bit word, or pokeb(3xb) to write a single byte.

EXAMPLES

100 CALL LOAD(8192, 255, 0)   ! does not work; use CALL POKE / POKEB

SEE ALSO

poke(3xb), pokeb(3xb), peek(3xb)

Source: resources/man/man3/load.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

LOCATE

locate(3xb)

move an existing sprite to a new row and column

NAME

LOCATE — move an existing sprite to a new row and column

SYNOPSIS

CALL LOCATE((#no, r, c));

DESCRIPTION

The CALL LOCATE() statement immediately changes the screen position of an existing sprite. r and c are the pixel coordinates on screen (1-256).

EXAMPLES

100 CALL LOCATE(#1, 50, 50)

SEE ALSO

sprite(3xb), position(3xb)

Source: resources/man/man3/locate.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

MAGNIFY

magnify(3xb)

set the global sprite magnification factor

NAME

MAGNIFY — set the global sprite magnification factor

SYNOPSIS

CALL MAGNIFY(factor);

DESCRIPTION

The CALL MAGNIFY() statement sets the global magnification factor for all hardware sprites on screen:

1
Unmagnified single-size sprites (8×8 pixels, 1 character pattern)
2
Magnified single-size sprites (8×8 pattern magnified to 16×16 screen pixels, 1 character pattern)
3
Unmagnified double-size sprites (16×16 pixels, 4 consecutive character patterns)
4
Magnified double-size sprites (16×16 pattern magnified to 32×32 screen pixels, 4 consecutive character patterns)

EXAMPLES

100 CALL MAGNIFY(4)

SEE ALSO

sprite(3xb)

Source: resources/man/man3/magnify.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

MOTION

motion(3xb)

update the row and column velocities of a sprite

NAME

MOTION — update the row and column velocities of a sprite

SYNOPSIS

CALL MOTION((#no, rv, cv));

DESCRIPTION

The CALL MOTION() statement changes the vertical and horizontal velocities of sprite #no (1–32). rv is the signed row velocity and cv is the signed column velocity (-128 to 127).

In ‘libxb’, sprite positions are tracked in 12.4 fixed-point and advanced on each vsync(3xb) call: a velocity of ‘16’ moves the sprite 1 pixel per frame at 60 Hz (a velocity of ‘1’ moves 1/16 pixel per frame).

EXAMPLES

100 CALL MOTION(#1, 16, -16)

SEE ALSO

sprite(3xb), vsync(3xb)

Source: resources/man/man3/motion.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

PATTERN

pattern(3xb)

change the character pattern used by a sprite

NAME

PATTERN — change the character pattern used by a sprite

SYNOPSIS

CALL PATTERN((#no, char));

DESCRIPTION

The CALL PATTERN() statement changes the visual graphics of an existing sprite by assigning it a new ASCII char code.

EXAMPLES

100 CALL PATTERN(#1, 43)

SEE ALSO

sprite(3xb)

Source: resources/man/man3/pattern.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

PEEK

peek(3xb)

read a 16-bit word from CPU memory

NAME

PEEK — read a 16-bit word from CPU memory

SYNOPSIS

CALL PEEK(address, var);

DESCRIPTION

The CALL PEEK() statement reads one 16-bit word from CPU address address into var.

This is not the classic multi-byte XB form. Only a single word is read; additional variables are not filled sequentially.

For a single byte, use peekb(3xb).

EXAMPLES

100 CALL PEEK(8192, A%)

SEE ALSO

peekb(3xb), poke(3xb), peekv(3xb)

Source: resources/man/man3/peek.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

PEEKB

peekb(3xb)

read a single unsigned byte from CPU memory

NAME

PEEKB — read a single unsigned byte from CPU memory

SYNOPSIS

CALL PEEKB(address, var);

DESCRIPTION

The CALL PEEKB() statement reads a single unsigned byte (0–255) from the 16-bit CPU memory address address and stores it in var.

To read a 16-bit word from CPU memory, use peek(3xb). To read a byte from VDP RAM, use peekv(3xb) or vdpread(3xb).

EXAMPLES

100 CALL PEEKB(>8375, KEYCODE%)

SEE ALSO

pokeb(3xb), peek(3xb), peekv(3xb), xb-vdp(7)

Source: resources/man/man3/peekb.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

PEEKV

peekv(3xb)

read a byte from VDP (Video) RAM

NAME

PEEKV — read a byte from VDP (Video) RAM

SYNOPSIS

CALL PEEKV(address, var);

DESCRIPTION

The CALL PEEKV() statement reads a single unsigned byte (0–255) from the 14-bit VDP memory address address and stores it in var.

Note: Only the 2-argument single-byte form is implemented; multi-variable sequential reads are not supported.

EXAMPLES

100 CALL PEEKV(0, A%)

SEE ALSO

pokev(3xb), vdpread(3xb), peek(3xb), peekb(3xb)

Source: resources/man/man3/peekv.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

POKE

poke(3xb)

write a 16-bit word to CPU memory

NAME

POKE — write a 16-bit word to CPU memory

SYNOPSIS

CALL POKE(address, val);

DESCRIPTION

The CALL POKE() statement writes one 16-bit word val to CPU address address.

This is not the classic multi-byte XB form. Only a single word is written; extra values are not stored sequentially. CALL LOAD() is not an alias and is unimplemented; see load(3xb).

For a single byte, use pokeb(3xb).

EXAMPLES

100 CALL POKE(8192, >FF00)

SEE ALSO

pokeb(3xb), peek(3xb), pokev(3xb), load(3xb)

Source: resources/man/man3/poke.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

POKEB

pokeb(3xb)

write a single byte to CPU memory

NAME

POKEB — write a single byte to CPU memory

SYNOPSIS

CALL POKEB(address, val);

DESCRIPTION

The CALL POKEB() statement writes the low 8 bits of val (0–255) to the 16-bit CPU memory address address.

To write a 16-bit word to CPU memory, use poke(3xb). To write a byte to VDP RAM, use pokev(3xb).

EXAMPLES

100 CALL POKEB(>8300, >FF)

SEE ALSO

peekb(3xb), poke(3xb), pokev(3xb), xb-vdp(7)

Source: resources/man/man3/pokeb.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

POKEV

pokev(3xb)

write a byte directly into VDP (Video) RAM

NAME

POKEV — write a byte directly into VDP (Video) RAM

SYNOPSIS

CALL POKEV(address, val);

DESCRIPTION

The CALL POKEV() statement writes a single byte value val (0–255) into the 14-bit VDP memory address address.

Note: Only the 2-argument single-byte form is implemented; multi-byte sequential writes are not supported.

EXAMPLES

100 CALL POKEV(0, 255)

SEE ALSO

peekv(3xb), vdpmemset(3xb), vdpmemcpy(3xb), poke(3xb), pokeb(3xb)

Source: resources/man/man3/pokev.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

POSITION

position(3xb)

read the current screen coordinates of a sprite

NAME

POSITION — read the current screen coordinates of a sprite

SYNOPSIS

CALL POSITION((#no, r, c));

DESCRIPTION

The CALL POSITION() statement reads the current row and column pixel coordinates of sprite #no into variables r and c.

EXAMPLES

100 CALL POSITION(#1, R, C)

SEE ALSO

sprite(3xb), locate(3xb)

Source: resources/man/man3/position.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

RND

rnd(3xb)

generate a pseudo-random float via CALL RND

NAME

RND — generate a pseudo-random float via CALL RND

SYNOPSIS

CALL RND(var);

DESCRIPTION

CALL RND() stores a pseudo-random floating-point value in var in the half-open range [0.0, 1.0] (matching classic TI Extended BASIC RND). The target variable var must be a floating-point variable (an identifier without a ‘%’ or ‘$’ suffix).

The expression form ‘RND’ uses the same generator and returns that value directly: ‘X = RND * 10’. It does not take arguments. ‘RANDOMIZE’ is unimplemented.

‘INT(expr)’ is a numeric builtin that truncates toward zero (the C cast to int). Classic TI ‘INT’ floors negative values; positive results match.

Requires float mode (-mfloat-ieee) or -mfloat-fixed.

EXAMPLES

100 CALL RND(R)
110 N% = INT(R * 100) + 1
120 DISPLAY AT(1,1):N%

SEE ALSO

xb-math(7)

Source: resources/man/man3/rnd.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

SCREEN

screen(3xb)

set the background screen color

NAME

SCREEN — set the background screen color

SYNOPSIS

CALL SCREEN(color);

DESCRIPTION

The CALL SCREEN() statement sets the background color of the screen. The color parameter must be an integer from 1 to 16.

The available colors are:

1 Transparent
2 Black
3 Medium Green
4 Light Green
5 Dark Blue
6 Light Blue
7 Dark Red
8 Cyan
9 Medium Red
10 Light Red
11 Dark Yellow
12 Light Yellow
13 Dark Green
14 Magenta
15 Gray
16 White

EXAMPLES

100 CALL SCREEN(2)

SEE ALSO

color(3xb)

Source: resources/man/man3/screen.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

seg

seg(3xb)

extract a substring from a string (not implemented yet)

NAME

SEG$ — extract a substring from a string (not implemented yet)

SYNOPSIS

SEG$(string$, position, length);

DESCRIPTION

UNIMPLEMENTED — not available in the current XB compiler or libxb.

The classic XB SEG$() function would extract a substring from string$ starting at 1-indexed position for up to length characters. It is not recognized by the frontend today.

EXAMPLES

100 S$ = SEG$("HELLO", 2, 3)   ! does not work yet

SEE ALSO

len(3xb), xb-string(7)

Source: resources/man/man3/seg.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

SOUND

sound(3xb)

play sounds/noise through the SN76489 sound chip

NAME

SOUND — play sounds/noise through the SN76489 sound chip

SYNOPSIS

CALL SOUND(duration, freq1, vol1, [freq2, vol2, [freq3, vol3, [freq4, vol4]]]);

DESCRIPTION

The CALL SOUND() statement plays up to four simultaneous sound channels (up to three tone channels and one noise channel) on the SN76489 sound chip.

duration is the playback time in milliseconds. A negative duration starts asynchronous playback in the background without halting the program; asynchronous sound duration is advanced on each vsync(3xb) tick.

freq1 .. freq4 specify frequencies in Hertz (110–44733) for tone channels. Values from -1 to -8 in any frequency slot configure the SN76489 noise generator instead of a tone channel.

vol1 .. vol4 specify volume attenuation from 0 (loudest) to 30 (silent).

EXAMPLES

100 CALL SOUND(100, 440, 2)
110 CALL SOUND(-500, 262, 2, 330, 4, 392, 6, -5, 10)

SEE ALSO

sound_list(3xb), sound_stop(3xb), vsync(3xb), xb-sound(7)

Source: resources/man/man3/sound.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

SOUND_LIST

sound_list(3xb)

play an asynchronous VDP/ROM sound list

NAME

SOUND_LIST — play an asynchronous VDP/ROM sound list

SYNOPSIS

CALL SOUND_LIST(@label);

DESCRIPTION

The CALL SOUND_LIST() statement starts asynchronous playback of a standard TI-99/4A byte-stream sound list located at @label (defined with the ‘BYTES’ directive).

Each entry in a sound list consists of a byte count N, followed by N bytes written to the SN76489 sound generator port (‘0x8400’), followed by a duration byte in 1/60-second ticks (a byte count of ‘0’ terminates the sound list). The sound list is advanced automatically on each vsync(3xb) tick until completion or until stopped with sound_stop(3xb).

EXAMPLES

@BEEP_LIST:
BYTES 2, >8E, >01, >92, 10
BYTES 1, >9F, 0

CALL SOUND_LIST(@BEEP_LIST)

SEE ALSO

sound(3xb), sound_stop(3xb), vsync(3xb), xb-sound(7)

Source: resources/man/man3/sound_list.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

SOUND_STOP

sound_stop(3xb)

stop active asynchronous sound or sound list playback

NAME

SOUND_STOP — stop active asynchronous sound or sound list playback

SYNOPSIS

CALL SOUND_STOP();

DESCRIPTION

The CALL SOUND_STOP() statement immediately halts any active asynchronous sound(3xb) or sound_list(3xb) playback and mutes all four SN76489 sound channels (writing attenuation ‘0x9F’, ‘0xBF’, ‘0xDF’, and ‘0xFF’ to the sound chip).

EXAMPLES

100 CALL SOUND_STOP

SEE ALSO

sound(3xb), sound_list(3xb), xb-sound(7)

Source: resources/man/man3/sound_stop.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

SPRITE

sprite(3xb)

define and display a sprite

NAME

SPRITE — define and display a sprite

SYNOPSIS

CALL SPRITE((#no, char, color, r, c, [rv, cv]));

DESCRIPTION

The CALL SPRITE() statement creates a hardware sprite. #no is the sprite number (1-32). char is the ASCII character code to use for its graphics. color is the sprite's color (1-16). r and c are the pixel coordinates on screen (1-256). rv and cv are optional row and column velocities for automotion (-128 to 127). In ‘libxb’, sprite positions are tracked in 12.4 fixed-point and advanced on each vsync(3xb) call, so a velocity of ‘16’ moves 1 pixel per frame at 60 Hz (‘1 = 1/16 pixel/frame’).

EXAMPLES

100 CALL SPRITE(#1, 42, 16, 128, 128, 16, 0)

SEE ALSO

delsprite(3xb), locate(3xb), motion(3xb), vsync(3xb)

Source: resources/man/man3/sprite.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

str

str(3xb)

convert numeric value to string (not implemented yet)

NAME

STR$ — convert numeric value to string (not implemented yet)

SYNOPSIS

STR$(number);

DESCRIPTION

UNIMPLEMENTED — not available in the current XB compiler or libxb.

The classic XB STR$() function would convert a numeric value to its string representation. It is not recognized by the frontend today. (Numeric values can be shown with DISPLAY AT, which uses xb_itoa internally).

EXAMPLES

100 A$ = STR$(123.45)   ! does not work yet

SEE ALSO

val(3xb), xb-string(7)

Source: resources/man/man3/str.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

VAL

val(3xb)

convert string to numeric value (not implemented yet)

NAME

VAL — convert string to numeric value (not implemented yet)

SYNOPSIS

VAL(string$);

DESCRIPTION

UNIMPLEMENTED — not available in the current XB compiler or libxb.

The classic XB VAL() function would convert a numeric string to a number. It is not recognized by the frontend today.

EXAMPLES

100 A = VAL("123.45")   ! does not work yet

SEE ALSO

str(3xb), xb-string(7)

Source: resources/man/man3/val.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

VCHAR

vchar(3xb)

draw a vertical line of characters

NAME

VCHAR — draw a vertical line of characters

SYNOPSIS

CALL VCHAR(row, col, char_code, [count]);

DESCRIPTION

The CALL VCHAR() statement places character char_code at row (1–24) and col (1–32). If the optional count is provided (default 1), it repeats the character vertically downward count times, wrapping from row 24 to the top (row 1) of the next column (and from column 32 back to column 1).

EXAMPLES

100 CALL VCHAR(12, 16, 33, 10)

SEE ALSO

hchar(3xb), gchar(3xb)

Source: resources/man/man3/vchar.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

VDPMEMCPY

vdpmemcpy(3xb)

bulk copy ROM/CPU data to VDP RAM

NAME

VDPMEMCPY — bulk copy ROM/CPU data to VDP RAM

SYNOPSIS

CALL VDPMEMCPY(vdp_addr, @label, count);

DESCRIPTION

The CALL VDPMEMCPY() statement copies count bytes from the ROM or CPU data block at @label (defined with the ‘BYTES’ directive) into VDP memory starting at the 14-bit address vdp_addr.

This is a ‘libxb’ extension for fast bulk transfers of pattern tables, tile maps, and sprite graphics without per-byte BASIC loop overhead.

EXAMPLES

@PATTERNS:
BYTES >3C,>7E,>FF,>FF,>FF,>FF,>7E,>3C

CALL VDPMEMCPY(>0800 + 42*8, @PATTERNS, 8)

SEE ALSO

vdpmemset(3xb), vdpread(3xb), pokev(3xb), xb-vdp(7), xb-data(7)

Source: resources/man/man3/vdpmemcpy.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

VDPMEMSET

vdpmemset(3xb)

fill a block of VDP RAM with a byte value

NAME

VDPMEMSET — fill a block of VDP RAM with a byte value

SYNOPSIS

CALL VDPMEMSET(vdp_addr, byte_val, count);

DESCRIPTION

The CALL VDPMEMSET() statement fills count consecutive bytes of VDP memory starting at the 14-bit address vdp_addr with the 8-bit value byte_val (0–255).

EXAMPLES

100 CALL VDPMEMSET(>0000, 32, 768)

SEE ALSO

vdpmemcpy(3xb), vdpread(3xb), pokev(3xb), xb-vdp(7)

Source: resources/man/man3/vdpmemset.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

VDPREAD

vdpread(3xb)

read a single byte from VDP RAM

NAME

VDPREAD — read a single byte from VDP RAM

SYNOPSIS

CALL VDPREAD(vdp_addr, var);

DESCRIPTION

The CALL VDPREAD() statement reads a single unsigned byte (0–255) from the 14-bit VDP memory address vdp_addr and stores it in var.

EXAMPLES

100 CALL VDPREAD(>0000, CH%)

SEE ALSO

peekv(3xb), pokev(3xb), vdpmemcpy(3xb), vdpmemset(3xb), xb-vdp(7)

Source: resources/man/man3/vdpread.3xb

Docs / API Reference / Extended BASIC runtime (CALL …)

VSYNC

vsync(3xb)

halt execution until the next VDP vertical blanking interrupt

NAME

VSYNC — halt execution until the next VDP vertical blanking interrupt

SYNOPSIS

CALL VSYNC();

DESCRIPTION

The CALL VSYNC() statement synchronizes program execution with the screen refresh rate (60Hz NTSC / 50Hz PAL).

This statement is new to this Extended Basic compiler and libxb. In compiled programs, you must call CALL VSYNC() inside your main game loops. It is responsible for processing background tasks, including:

  • Sprite automotion (CALL MOTION)
  • Asynchronous sound updates (CALL SOUND with negative durations)

EXAMPLES

100 CALL VSYNC
110 GOTO 100

Source: resources/man/man3/vsync.3xb

Docs / API Reference / Extended BASIC language guide

xb-control

xb-control(7)

XB BASIC control flow statements (partial)

NAME

xb-control — XB BASIC control flow statements (partial)

DESCRIPTION

PARTIAL — ‘IF’, ‘FOR’, ‘WHILE’, ‘GOTO’, and ‘GOSUB’ work. ‘REPEAT / UNTIL’ and ‘ON ... GOTO / GOSUB’ are not implemented.

IF / THEN / ELSE / ELSEIF / ENDIF

Implemented. Conditional execution. Single-line form:

IF condition THEN statement :: statement

Multi-line (structured) form:

IF condition THEN
  statements
ELSEIF condition THEN
  statements
ELSE
  statements
ENDIF

FOR / TO / STEP / NEXT

Implemented. Counted loop. STEP defaults to 1 if omitted.

FOR I%=1 TO 10 STEP 2
  CALL HCHAR(I%,1,42)
NEXT I%

WHILE / WEND (or ENDWHILE)

Implemented. Pre-tested loop. Both ‘WEND’ and ‘ENDWHILE’ are accepted as the loop terminator.

WHILE RUNNING%
  ! game loop
WEND

REPEAT / UNTIL

Unimplemented (tokens exist; not parsed). Use ‘WHILE / WEND’ instead.

REPEAT
  CALL KEY(0,K%,S%)
UNTIL S%<>0   ! does not work yet

GOTO label

Implemented. Transfer control to a line number or @label.

GOTO 100
GOTO @MAIN_LOOP

GOSUB label / RETURN

Implemented. Call a subroutine at a line number or @label. ‘RETURN’ transfers back to the statement after the GOSUB.

GOSUB @DRAW_SCREEN
! ...
@DRAW_SCREEN:
  CALL CLEAR
  RETURN

ON expr GOTO label1, label2, ...

ON expr GOSUB label1, label2, ...

Unimplemented. Computed branch is not parsed.

ON CHOICE% GOTO @OPT1,@OPT2,@OPT3! does not work yet

SEE ALSO

xb-sub(7), xb-variables(7), xb-misc(7)

Source: resources/man/man7/xb-control.7

Docs / API Reference / Extended BASIC language guide

xb-data

xb-data(7)

XB BASIC DATA, READ, RESTORE, and BYTES directives

NAME

xb-data — XB BASIC DATA, READ, RESTORE, and BYTES directives

DESCRIPTION

Inline data storage and retrieval.

DATA val1, val2, ...

Store constant values in a program-wide data pool.

DATA 10,20,30,"HELLO",42

READ var1, var2, ...

Read the next value(s) from the DATA pool into variables. ‘READ’ supports integer (‘%’) and string (‘$’) variables (reading into floating-point variables is not yet supported).

READ X%,Y%,Z%,MSG$,N%

RESTORE [@label | line]

Reset the DATA read pointer to the beginning of the data pool, or to the first ‘DATA’ statement at or after the specified @label or line number.

RESTORE
RESTORE @LEVEL2_DATA

BYTES val, val, ...

(Extension) Define raw binary data bytes under a label. Values are 8-bit (0–255 or >00–>FF). Used with CALL VDPMEMCPY for bulk VDP transfers.

@PADDLE_PATTERN:
BYTES >18,>18,>18,>18,>18,>18,>18,>18

Multiple BYTES lines under the same label are concatenated.

DATA ENCODING

The compiler emits all ‘DATA’ items as an array of C string literals (__xb_data_pool[]) indexed by a runtime read cursor (__xb_data_ptr). String variables receive the literal pointer directly; integer (‘%’) variables parse the string entry at runtime via xb_atoi().

SEE ALSO

xb-variables(7), xb-vdp(7), xb-misc(7)

Source: resources/man/man7/xb-data.7

Docs / API Reference / Extended BASIC language guide

xb-input

xb-input(7)

XB BASIC joystick, keyboard, and timing commands

NAME

xb-input — XB BASIC joystick, keyboard, and timing commands

DESCRIPTION

Hardware input and timing via the TMS9900 CRU and VDP interrupt.

CALL JOYST(unit, x, y)

Implemented. Read joystick unit (1 or 2). x receives -4 (left), 0 (center), or 4 (right). y receives -4 (down), 0 (center), or 4 (up).

CALL JOYST(1,JX%,JY%)

CALL KEY(unit, key, status)

Implemented. Scan the keyboard. unit selects the input source:

Unit Source
0 Console keyboard (full scan)
1 Left side of split keyboard / joystick 1 fire
2 Right side of split keyboard / joystick 2 fire
3 Standard uppercase-only keyboard mode
4 Pascal keyboard mode
5 Basic (mixed-case) keyboard mode

key receives the ASCII code of the pressed key (255 if no key is pressed). status receives:

  • 1 — new key pressed
  • -1 — same key still held
  • 0 — no key pressed

CALL KEY(0,K%,S%)

CALL VSYNC

Implemented (also documented as vsync(3xb) ). Wait for the next vertical blank interrupt (frame sync). Use this for consistent ~60Hz game timing.

There is no ‘CALL VBLANK’ builtin; the name is ‘VSYNC’.

CALL VSYNC

EXAMPLES

! Simple input loop
@LOOP:
  CALL KEY(0,K%,S%)
  IF K%=13 THEN GOTO @DONE
  CALL JOYST(1,JX%,JY%)
  CALL VSYNC
  GOTO @LOOP
@DONE:

SEE ALSO

key(3xb), joyst(3xb), vsync(3xb), xb-sprites(7), xb-sound(7), xb-control(7)

Source: resources/man/man7/xb-input.7

Docs / API Reference / Extended BASIC language guide

xb-io

xb-io(7)

XB BASIC print, display, and input statements (partial)

NAME

xb-io — XB BASIC print, display, and input statements (partial)

DESCRIPTION

PARTIAL — only ‘DISPLAY AT’ is implemented. ‘PRINT’, ‘INPUT’, ‘LINPUT’, ‘ACCEPT’, ‘PRINT USING’, and ‘IMAGE’ are not parsed by the current compiler.

PRINT expr [; expr] [, expr]

Unimplemented.

PRINT SCORE: ;S1%! does not work yet

DISPLAY AT(row, col): expr

Implemented. Write text at a specific screen position. Numeric values are converted via ‘xb_itoa’.

DISPLAY AT(1,10):"PLAYER 1"
DISPLAY AT(24,1):S1%

PRINT USING fmt: expr

Unimplemented.

IMAGE format

Unimplemented.

INPUT prompt: var

Unimplemented.

LINPUT prompt: var$

Unimplemented.

ACCEPT AT(row, col) [SIZE(n)] [VALIDATE(...)] [BEEP]: var

Unimplemented.

SEE ALSO

display_at(3xb), xb-control(7), xb-string(7), xb-variables(7)

Source: resources/man/man7/xb-io.7

Docs / API Reference / Extended BASIC language guide

xb-math

xb-math(7)

XB BASIC built-in numeric functions (partial)

NAME

xb-math — XB BASIC built-in numeric functions (partial)

DESCRIPTION

PARTIAL — named math functions (ABS, SGN, SQR, SIN, ...), ‘PI’, and ‘RANDOMIZE’ are not implemented. ‘INT(expr)’ truncates toward zero. Expression ‘RND’ returns the same value as rnd(3xb). Operators, comparisons, and ‘AND / OR’ work; unary ‘NOT’ does not. For random floats use expression ‘RND’ or rnd(3xb) (CALL RND).

Float arithmetic requires float mode (-mfloat-ieee) or -mfloat-fixed.

ABS(x), SGN(x), SQR(x)

Unimplemented. Would return absolute value, sign (-1/0/1), and square root.

INT(x)

Truncates x toward zero and returns an integer. Positive values match classic TI ‘INT’; negative values differ (classic INT floors).

RND

Expression form returns a float in [0.0, 1.0] using the same generator as ‘CALL RND(var)’ (rnd(3xb)). ‘RANDOMIZE’ is unimplemented.

PI, SIN(x), COS(x), TAN(x), ATN(x), EXP(x), LOG(x)

Unimplemented. No named builtins; softfloat helpers exist only for compiler-lowered ‘float’ operations, not these XB names.

OPERATORS

Implemented (integer and float, subject to float mode).

+ Addition
- Subtraction / negation
* Multiplication
/ Division
MOD Modulo (integer remainder)

Not Yet Implemented:

^ Power (exponentiation)

COMPARISON

Implemented.

= Equal
<> Not equal
< Less than
> Greater than
<= Less or equal
>= Greater or equal

LOGICAL

AND Logical AND — implemented
OR Logical OR — implemented
NOT Logical NOT — unimplemented

SEE ALSO

xb-string(7), xb-variables(7), rnd(3xb)

Source: resources/man/man7/xb-math.7

Docs / API Reference / Extended BASIC language guide

xb-misc

xb-misc(7)

XB BASIC miscellaneous statements and directives (partial)

NAME

xb-misc — XB BASIC miscellaneous statements and directives (partial)

DESCRIPTION

PARTIAL — ‘LET’, ‘END’, and ‘REM’ work. ‘STOP’, ‘RANDOMIZE’, ‘DEF’, ‘ON ERROR’, and ‘RESUME’ are not implemented.

LET var = expr

Implemented. Explicit assignment (the ‘LET’ keyword is optional; bare assignment also works).

LET X%=42
X%=42

END

Implemented. Terminate program execution.

END

STOP

Unimplemented (token exists; only ‘END’ is handled).

STOP

REM text

! text

Implemented. Comment. Everything after REM or ! is ignored until the end of the line.

REM This is a comment
! This is also a comment

RANDOMIZE [seed]

Unimplemented (not even a keyword). Seed the random number generator.

RANDOMIZE 42! does not work yet

DEF name(param) = expr

Unimplemented. Define a single-expression function.

DEF DOUBLE(X)=X*2! does not work yet

ON ERROR label

Unimplemented.

RESUME

Unimplemented.

SEE ALSO

xb-control(7), xb-variables(7), xb-sub(7), rnd(3xb)

Source: resources/man/man7/xb-misc.7

Docs / API Reference / Extended BASIC language guide

xb-screen

xb-screen(7)

XB BASIC screen, color, and character definition commands

NAME

xb-screen — XB BASIC screen, color, and character definition commands

DESCRIPTION

Screen initialization, color table manipulation, and character pattern definition for the TI-99/4A VDP in Graphics I mode.

CALL CLEAR

Clear the screen (fill name table with spaces), reset the cursor position, and clear all hardware sprites (writes ‘0xD0’ to the Sprite Attribute List at ‘0x0380’ and resets sprite motion state).

CALL CLEAR

CALL SCREEN(color)

Set the screen background color. color is a VDP color code (1–16):

1 Transparent 5 Dark Blue 9 Medium Red 13 Dark Green
2 Black 6 Light Blue 10 Light Red 14 Magenta
3 Medium Green 7 Dark Red 11 Dark Yellow 15 Gray
4 Light Green 8 Cyan 12 Light Yellow 16 White

CALL SCREEN(2)

CALL COLOR(set, fg, bg)

Set the foreground and background colors for a character set. Each set controls 8 consecutive character codes:

Set Characters (ASCII)
1 32–39
2 40–47
... ...
14 136–143

fg and bg are VDP color codes (1–16).

CALL COLOR(2,16,2)

CALL CHAR(code, pattern)

Redefine the pixel pattern starting at character code (32–143). pattern is a compile-time hexadecimal string literal where each 16 hex digits represent 8 bytes (8×8 pixels). Multi-character definitions up to 512 hex digits (32 consecutive characters) are supported; partial 8-byte blocks are zero-padded.

CALL CHAR(42,"007E424242427E00")

Each hex pair represents one row, MSB–left. Patterns are written to both the Pattern Descriptor Table (‘0x0800’) and the Sprite Pattern Table (‘0x1800’).

TI-99/4A NOTES

  • The TI-99/4A VDP operates in Graphics I mode with 32 character sets.
  • CALL CLEAR writes 0x20 (space) to the entire 768-byte name table.
  • Color table is 32 bytes: one byte per set (high nybble = fg, low = bg).
  • Pattern table is 2048 bytes: 8 bytes per character × 256 characters.

SEE ALSO

xb-tiles(7), xb-sprites(7), xb-vdp(7)

Source: resources/man/man7/xb-screen.7

Docs / API Reference / Extended BASIC language guide

xb-sound

xb-sound(7)

XB BASIC sound generation commands (partial)

NAME

xb-sound — XB BASIC sound generation commands (partial)

DESCRIPTION

PARTIAL — ‘CALL SOUND’ supports multiple channels. ‘CALL SAY’ is not supported. ‘CALL SOUND_LIST’ and ‘CALL SOUND_STOP’ are also implemented in ‘libxb’ (see sound_list(3xb) and sound_stop(3xb) ).

Sound output via the TI-99/4A SN76489 sound chip.

CALL SOUND(duration, freq, vol [, freq2, vol2 ...])

Implemented. Play tones on up to three tone channels plus noise. Additional freq / vol pairs select further channels (up to four total).

duration is in milliseconds (converted to ~60Hz frames; minimum 1 frame). Negative duration starts asynchronous playback.

freq is the frequency in Hz. If freq is 0, only the duration timer is set (silence). Negative freq selects noise types on the noise channel.

vol is the volume using TI Extended BASIC convention: 0 = loudest, 30 = silent (mapped to SN76489 attenuation by dividing by 2).

CALL SOUND(200,440,2)
CALL SOUND(500,262,2,330,4,392,6)

CALL SAY(word)

Unimplemented. Speech synthesis is not supported in the current runtime or emulator.

CALL SAY("HELLO")! does not work

TIMER

Sound duration is managed by the VBlank / sound tick path. The tick counter decrements each frame (~60Hz); when it reaches zero, channels are silenced. One tick ∼ 17ms (1/60s).

EXAMPLES

! Play a simple tone
CALL SOUND(500,262,2)   ! Middle C for ~500ms

! Play descending tones
FOR I%=1 TO 5
  CALL SOUND(200,440-I%*50,0)
NEXT I%

SEE ALSO

sound(3xb), xb-input(7), xb-screen(7)

Source: resources/man/man7/xb-sound.7

Docs / API Reference / Extended BASIC language guide

xb-sprites

xb-sprites(7)

XB BASIC sprite creation, movement, and collision commands

NAME

xb-sprites — XB BASIC sprite creation, movement, and collision commands

DESCRIPTION

Hardware sprite management via the TMS9918A VDP. Up to 32 sprites are supported, numbered #1 through #32.

CALL SPRITE(#id, pat, color, y, x [, vy, vx])

Create or update sprite #id with pattern pat, VDP color color, at pixel position (y, x), and optional initial velocity (vy, vx).

CALL SPRITE(#1,33,7,96,128)

Pattern numbers refer to character codes. In 8×8 magnify mode, each sprite uses one character pattern; in 16×16 mode, four consecutive character patterns are used.

CALL DELSPRITE(#id)

Delete sprite #id from the sprite table (writes ‘0xC0’ / Y=192 to move it off-screen and clears its velocity).

CALL DELSPRITE(#1)

Use ‘CALL DELSPRITE(ALL)’ to delete all sprites.

CALL MOTION(#id, vy, vx)

Set the velocity of sprite #id. vy is vertical speed (positive = down), and vx is horizontal speed (positive = right). Values range from -128 to 127 in 12.4 fixed-point units (‘16 = 1 pixel/frame at 60 Hz’). The sprite position is updated on each ‘CALL VSYNC’.

CALL MOTION(#1,0,64)

CALL MAGNIFY(n)

Set the sprite magnification mode for all sprites:

Value Size Patterns
1 8×8 1 char each
2 8×8 doubled 1 char each
3 16×16 4 chars each
4 16×16 doubled 4 chars each

CALL MAGNIFY(3)

CALL PATTERN(#id, pat)

Change the pattern of sprite #id to pat without affecting position or color.

CALL PATTERN(#1,37)

CALL LOCATE(#id, y, x)

Move sprite #id to absolute pixel position (y, x).

CALL LOCATE(#1,0,0)

CALL POSITION(#id, y, x)

Read the current position of sprite #id into variables y and x.

CALL POSITION(#1,SY%,SX%)

CALL COINC(#id1, #id2, tol, flag)

Check if two sprites overlap within tol pixels. flag is set to -1 (true) if they coincide, 0 otherwise.

CALL COINC(#1,#2,8,HIT%)

Use ‘CALL COINC(ALL,flag)’ to check if any two active sprites overlap.

CALL DISTANCE(#id1, #id2, dist)

Calculate the squared distance between two sprites. dist receives (dy*dy + dx*dx).

CALL DISTANCE(#1,#2,D%)

SPRITE LIMITS

  • The TMS9918A supports up to 32 sprites, but only 4 per scanline.
  • Sprites with lower IDs have higher display priority.
  • Y position 208 (0xD0) terminates sprite processing for all subsequent sprites.
  • Sprite coordinates are in pixels: Y 0–191, X 0–255.

EXAMPLES

! Create a 16x16 bouncing ball
CALL MAGNIFY(3)
CALL CHAR(96,"3C7EFFFFFFFF7E3C")
CALL CHAR(97,"0000000000000000")
CALL CHAR(98,"0000000000000000")
CALL CHAR(99,"0000000000000000")
CALL SPRITE(#1,96,7,96,128)
CALL MOTION(#1,2,3)

SEE ALSO

xb-screen(7), xb-tiles(7), xb-vdp(7)

Source: resources/man/man7/xb-sprites.7

Docs / API Reference / Extended BASIC language guide

xb-string

xb-string(7)

XB BASIC built-in string functions (partial)

NAME

xb-string — XB BASIC built-in string functions (partial)

DESCRIPTION

PARTIAL — most classic string functions below are unimplemented. Only concatenation with ‘&’ works in the current compiler/libxb.

String variables use the ‘$’ suffix.

LEN(s$)

Unimplemented. Return the length of string s$.

L%=LEN("HELLO")! does not work yet

SEG$(s$, pos, len)

Unimplemented. Extract a substring starting at position pos (1-based) with length len.

X$=SEG$("HELLO",2,3)! does not work yet

CHR$(n)

Unimplemented. Return the character with ASCII code n.

A$=CHR$(65)! does not work yet

ASC(s$)

Unimplemented. Return the ASCII code of the first character of s$.

N%=ASC("A")! does not work yet

STR$(n)

Unimplemented. Convert number n to its string representation.

S$=STR$(42)! does not work yet

VAL(s$)

Unimplemented. Convert string s$ to a number.

N%=VAL("42")! does not work yet

POS(haystack$, needle$, start)

Unimplemented. Find the position of needle$ within haystack$ starting at position start (1-based).

P%=POS("HELLO","LL",1)! does not work yet

RPT$(s$, n)

Unimplemented. Repeat string s$ n times.

BAR$=RPT$("=",20)! does not work yet

Concatenation (&)

Implemented. Join two strings via ‘&’ (lowered to xb_str_concat).

FULL$=FIRST$ & & LAST$

SEE ALSO

xb-math(7), xb-io(7), xb-variables(7), asc(3xb), chr(3xb), len(3xb)

Source: resources/man/man7/xb-string.7

Docs / API Reference / Extended BASIC language guide

xb-sub

xb-sub(7)

XB BASIC subroutine definition and invocation

NAME

xb-sub — XB BASIC subroutine definition and invocation

DESCRIPTION

User-defined subroutines with parameters and shared variables.

SUB name(params) / SUBEND

Define a subroutine. Parameters are passed by reference.

SUB MOVE_BALL(BX%,BY%,DX%,DY%)
  BX%=BX%+DX%
  BY%=BY%+DY%
SUBEND

CALL name(args)

Invoke a subroutine. Arguments are matched by position to the SUB's parameter list.

CALL MOVE_BALL(BALLX%,BALLY%,BDX%,BDY%)

SHARED var1, var2, ...

Declare variables as shared between the main program and all SUBs. Must appear inside a SUB body.

SUB UPDATE_SCORE(PLAYER%,POINTS%)
  SHARED SCORE1%,SCORE2%
  IF PLAYER%=1 THEN SCORE1%=SCORE1%+POINTS%
  IF PLAYER%=2 THEN SCORE2%=SCORE2%+POINTS%
SUBEND

NOTES

  • SUBs are compiled as separate functions with their own stack frame.
  • All SUB parameters — integer (%), float (no suffix), and string ($) — are passed by reference as 16-bit pointers.
  • SUBs may call other SUBs and use recursion.

SEE ALSO

xb-control(7), xb-variables(7)

Source: resources/man/man7/xb-sub.7

Docs / API Reference / Extended BASIC language guide

xb-tiles

xb-tiles(7)

XB BASIC tile placement and reading commands

NAME

xb-tiles — XB BASIC tile placement and reading commands

DESCRIPTION

Place or read characters on the 32×24 screen grid. Row values are 1–24, column values are 1–32.

CALL HCHAR(row, col, char [, count])

Place character char at position (row, col) horizontally. If count is specified, repeat the character count times, wrapping to the next row at column 32.

CALL HCHAR(1,1,42,32)

CALL VCHAR(row, col, char [, count])

Place character char at position (row, col) vertically. If count is specified, repeat downward, wrapping to the next column at row 24.

CALL VCHAR(1,1,42,24)

CALL GCHAR(row, col, var)

Read the character code at position (row, col) into integer variable var.

CALL GCHAR(12,16,C%)

ADDRESSING

Screen positions map to VDP Name Table addresses:

addr = (row - 1) * 32 + (col - 1)

Row 1 is the top row, column 1 is the leftmost column. The name table starts at VDP address 0x0000 by default.

EXAMPLES

! Draw a border around the screen
CALL HCHAR(1,1,42,32)    ! Top row
CALL HCHAR(24,1,42,32)   ! Bottom row
CALL VCHAR(2,1,42,22)    ! Left column
CALL VCHAR(2,32,42,22)   ! Right column

SEE ALSO

xb-screen(7), xb-sprites(7), xb-vdp(7)

Source: resources/man/man7/xb-tiles.7

Docs / API Reference / Extended BASIC language guide

xb-variables

xb-variables(7)

XB BASIC variable types, arrays, and declarations

NAME

xb-variables — XB BASIC variable types, arrays, and declarations

DESCRIPTION

Variable naming conventions, data types, and array dimensions.

VARIABLE TYPES

Variable type is determined by its suffix:

Suffix Type Size Range
% Integer 16-bit -32768 to 32767
$ String pointer up to 255 chars
(none) Float 32-bit IEEE 754 single

X%=42
NAME$="PONG"
PI=3.14159

DIM var(size [, size2])

Declare an array. By default, indices start at 0 (see ‘OPTION BASE’).

DIM BOARD%(24,32)    ! 2D array
DIM NAMES$(10)       ! 1D string array

The actual number of elements is size + 1 (indices 0 through size).

OPTION BASE n

Set the minimum array index. n must be 0 or 1. Default is 0.

OPTION BASE 1

VARIABLE SCOPE

  • All variables in the main program are global.
  • Variables inside a SUB are local unless declared SHARED.
  • Arrays declared with ‘DIM’ are allocated statically in global ‘.bss’ memory even when declared inside a ‘SUB’.

TYPE COERCION

  • Assigning a float to an integer variable truncates the value.
  • Integer expressions in float context are promoted automatically.
  • String and numeric types cannot be mixed.

SEE ALSO

xb-sub(7), xb-control(7), xb-data(7)

Source: resources/man/man7/xb-variables.7

Docs / API Reference / Extended BASIC language guide

xb-vdp

xb-vdp(7)

XB BASIC VDP memory access and bulk transfer commands

NAME

xb-vdp — XB BASIC VDP memory access and bulk transfer commands

DESCRIPTION

Direct VDP (Video Display Processor) memory access for bulk data transfers, pattern loading, and low-level hardware control. These are extensions to standard TI Extended BASIC.

‘CALL PEEK’ and ‘CALL POKE’ below read/write a 16-bit CPU word, not a single byte. Use ‘CALL PEEKB / POKEB’ for bytes.

CALL VDPMEMCPY(addr, label, len)

Copy len bytes from a BYTES data block labeled label to VDP memory starting at address addr.

CALL VDPMEMCPY(>0800,@PATTERN_DATA,64)

addr can be specified in decimal or hex with the ‘>’ prefix. label must reference a ‘BYTES’ data block defined in the source.

CALL VDPMEMSET(addr, byte, len)

Fill len bytes of VDP memory starting at addr with the value byte.

CALL VDPMEMSET(>0000,32,768)

CALL VDPREAD(addr, var)

Read a single unsigned byte from VDP memory address addr into variable var. See vdpread(3xb) and peekv(3xb).

CALL VDPREAD(>0000,CH%)

CALL PEEKB(addr, var)

Read a single unsigned byte (0–255) from CPU memory address addr into variable var. See peekb(3xb).

CALL PEEKB(>8375,K%)

CALL POKEB(addr, val)

Write a single byte val (0–255) to CPU memory address addr. See pokeb(3xb).

CALL POKEB(>8300,>FF)

CALL PEEK(addr, var)

Read one 16-bit word from CPU memory address addr into variable var. See peek(3xb).

CALL PEEK(>8300,V%)

CALL POKE(addr, val)

Write 16-bit word val to CPU memory address addr. See poke(3xb).

CALL POKE(>8300,>1234)

VDP MEMORY MAP

The default VDP memory layout for Graphics I mode:

Address Size Contents
>0000 768 Name Table (32×24 screen)
>0300 32 Color Table (1 byte per set)
>0380 128 Sprite Attribute Table (32 × 4 bytes)
>0800 2048 Pattern Table (8 bytes per char)
>1800 2048 Sprite Pattern Table

BYTES DIRECTIVE

The ‘BYTES’ directive defines raw binary data blocks in ROM:

@PATTERN_DATA:
BYTES >3C,>7E,>FF,>FF,>FF,>FF,>7E,>3C

Each value is a single byte (0–255 or >00–>FF). Labels referenced by VDPMEMCPY must use the ‘@’ prefix.

EXAMPLES

! Load custom character patterns from ROM
@MY_CHARS:
BYTES >00,>7E,>42,>42,>42,>42,>7E,>00
BYTES >18,>3C,>7E,>FF,>FF,>7E,>3C,>18

CALL VDPMEMCPY(>0800+42*8,@MY_CHARS,16)

SEE ALSO

xb-screen(7), xb-tiles(7), xb-sprites(7)

Source: resources/man/man7/xb-vdp.7

Chapter 7

AI Agent Skill

Docs / AI Agent Skill

The ti99-tidepod-gamedev agent skill

AI agents

Tidepod ships an agent skill: a set of Markdown files that tells AI coding assistants how to work on a Tidepod project. Without it, assistants tend to edit the generated Makefile, invent compiler or packer flags, and call library functions that don't exist. With it they use the CLI, the real build and the real emulator options.

Where it is

tidepod new copies the skill into every new project, in the two locations most assistants look for project skills:

Project layout
mygame/
├── .agents/skills/ti99-tidepod-gamedev/
│   ├── SKILL.md
│   ├── reference.md
│   └── examples.md
└── .cursor/skills/ti99-tidepod-gamedev/
    └── (same three files)

The master copy is in the Tidepod install under resources/agent-skills/ti99-tidepod-gamedev/. For existing projects, copy that directory into the project yourself. If your assistant uses another location, copy or link it there; the files are plain Markdown with a YAML header.

Contents

FileWhat it covers
SKILL.mdWhen to use the skill, the hard rules, the canonical new/add/build/run loop, CLI table, emulator and GDB usage, PEB/disk configuration, hang forensics with --dump-regs, headless verification, banking and F18A essentials, a pitfall checklist, and pointers to the example projects.
reference.mdMemory map, project-file details (disk mounts, PEB cards), packer outputs and options, VDP and F18A notes, current emulator flags, tool paths, debug/profiler helpers.
examples.mdShort recipes: new banked cartridge, persistent code plus a resource, F18A GPU image, headless GDB session, disk/EA5, and which example project to open for what.

When an assistant uses it

The skill's description makes assistants load it for anything involving Tidepod projects: building banked cartridges, EA5 disks or XB projects, VDP/F18A graphics, packer or banking problems, code placement, emulator debugging, and adding or removing sources and resources.

Keeping it current

The skill is versioned with Tidepod. After updating Tidepod, refresh the copies in your projects from resources/agent-skills/ so assistants see the current CLI and emulator options. If you have project rules of your own, put them in a separate file rather than editing the skill, so they survive the refresh.

Docs / AI Agent Skill

Rules the skill enforces

AI agents

These are the rules the skill gives to assistants. They are good rules for humans too; if an assistant breaks one, point it at the skill.

Hard rules

  1. Never edit the generated Makefile. It starts with # [GENERATED BY TI-99 IDE - DO NOT EDIT MANUALLY] and is overwritten by the next sync. Extra rules go in Makefile.custom.
  2. Change the build list only with the CLI: tidepod add, tidepod remove, or edit srcFiles in the .project file and run tidepod sync. In particular, never add a resource by editing RESOURCE_OBJS.
  3. Build with make / make debug. There is no tidepod build.
  4. Don't edit generated files: Makefile, autobank.ld, the trampolines, autobank_mapping.h, include/resource_defs.h, include/*_map.h, bank_report.json.
  5. Prefer the Tidepod CLI over hand-made packer or linker flags.
  6. tidepod run starts the stand-alone emulator, not the IDE. It uses the layered configuration (Preferences, project "emu" block, disk mounts). For headless runs, call ti994a-emu directly.
  7. No large local variables. The stack is small. Buffers of about 64 bytes or more (sector buffers, file records, tables) must be static or global, never locals.

Canonical loop

Terminal
tidepod new mygame --type banked --path ./mygame
cd mygame
# edit main.c, tidepod add new files / resources
tidepod sync && make debug
tidepod run --debug                      # emulator + GDB on :3333

# verify boot the way a user sees it (no --autorun)
ti994a-emu --cart mygame.rpk --f18a --headless \
  --keys "WAIT:300 SPACE WAIT:120" --screenshot-at 450 --frames 480

Pitfall checklist

Before handing over a build, the skill has the assistant check:

  • VR30 set after unlocking the F18A.
  • Interrupt / vsync strategy is intentional.
  • Programs using disk files: scratchpad area starts at 0x8380 or higher.
  • No source file larger than one bank.
  • Makefile and RESOURCE_OBJS never edited by hand.
  • No edits to generated packer, resource or GPU map files.
  • make debug + --gdb used for debugging rather than a home-made debug protocol.
  • Boot verified without --autorun, using --keys and --screenshot-at.
  • bank_report.json headroom, trampolines and stack depth compared with the last good build.

The background for each item is in this documentation: Banking, Code placement, F18A GPU code, bank_report.json and Headless testing.