emulator-template: Neutralize demo slot, add 10s auto-exit safety hatch

Make the template foolproof to copy-and-fill for a new demo:

- examples/Conway/ replaced by a neutral examples/Demo/Demo.cpp sample
  (bouncing box) documenting the full sketch contract (setup/loop,
  emuGfx::fb, emuGfx::dirty, emu::keyboard)
- Makefile passes the sketch path as -DAPP_SRC; main.cpp now includes
  APP_SRC instead of hardcoding Conway.cpp, window title uses APP_NAME
- Safety hatch: emulator auto-exits after 10 seconds by default so a
  runaway demo can't hang and eat resources; --user-run disables the
  cap, --timeout MS adjusts it (default 10000)
- README rewritten as a step-by-step recipe: replace the Demo sketch,
  run 'make run'; documents all CLI flags, drops the unimplemented
  --dump-interval flag

Verified: fresh copy + sketch swap builds and renders; hatch fires at
10s (and at --timeout 2000); --user-run runs until --frames cap.
This commit is contained in:
Dejvino
2026-11-16 20:25:41 +01:00
parent c331b55d82
commit a243f303f6
6 changed files with 152 additions and 393 deletions
+10 -5
View File
@@ -1,12 +1,15 @@
# Minimal Makefile for the T-Deck emulator-only template.
# Build & run: make run (from this directory)
# Build & run: make run (from this directory)
# Smoke test: make smoke
#
# This Makefile is self-contained: all sources (shim, main, sketch)
# are relative to this Makefile's directory. Copy the whole folder
# for a new project — no path adjustments needed.
#
# The sketch lives in examples/$(APP)/$(APP).cpp and provides setup()/loop().
# Default is the bundled sample demo; replace it to make your own.
APP ?= Conway
APP ?= Demo
APP_DIR := examples/$(APP)
# SDL3 flags via pkg-config
@@ -19,15 +22,17 @@ CXXFLAGS ?= -std=gnu++17 -O2 -Wall -Wextra
# Include current directory for shim.h, and the sketch directory
INC := -I . -I $(APP_DIR)
# Preprocessor definitions: the .ino filename and app name
DEFS += -DAPP_INO='"$(APP).ino"' -DAPP_NAME='"$(APP)"'
# Preprocessor definitions: app name, .ino filename, and the sketch source
# path. main.cpp does `#include APP_SRC`, so switching APP is enough.
DEFS += -DAPP_INO='"$(APP).ino"' -DAPP_NAME='"$(APP)"' \
-DAPP_SRC='"$(APP_DIR)/$(APP).cpp"'
# Source files — the sketch .cpp is included by main.cpp via #include,
# so they compile as a single translation unit.
SHIMS := $(wildcard *.h) # picks up shim.h at template root
# Main entry point for this template (standalone, no HW deps)
# main.cpp includes examples/Conway/Conway.cpp forming one TU.
# main.cpp includes examples/$(APP)/$(APP).cpp forming one TU.
EMU_MAIN := src/main.cpp
EMU := $(APP)-emu
+60 -76
View File
@@ -1,102 +1,86 @@
# T-Deck Emulator-Only Concept Exploration Template
# T-Deck Emulator-Only Template
A minimal, copy-paste template for prototyping graphics and engine experiments
using the SDL3 emulator (no hardware required).
A minimal, self-contained SDL3 emulator template for prototyping 320x240
graphics/engine experiments without any hardware. No TFT_eSPI, no SPI,
no I2S, no GPIO — just SDL3 and a framebuffer.
## Quick Start
## Creating a new demo (the only thing you need to do)
```bash
# From the template directory, build and run:
make run
1. Copy this whole folder and give it your demo's name.
2. Replace `examples/Demo/Demo.cpp` with your own sketch (keep the file
and folder name `Demo`, or rename both and pass `APP=YourName` to make).
3. Your sketch must provide `setup()` and `loop()` and may use:
- `millis()`, `delay()`, `random()`, `randomSeed()` — timing/randomness
- `emuGfx::fb[320*240]` — 320x240 ABGR8888 framebuffer (`uint32_t` pixels)
- `emuGfx::dirty = true` — set this every frame you want presented
- `emu::keyboard` — ASCII key queue (`' '`, `'a'`…, `0x08` backspace)
- `pinMode()`/`digitalRead()` — stubs, idle HIGH
# Or from the main emulator directory:
make -C /var/home/dejvino/workspace/T-Deck/emulator APP=Conway run
```
That is the whole contract. The bundled `Demo.cpp` shows it with a
bouncing box — use it as a starting skeleton or delete everything in it.
## 📸 Screenshot / Frame Capture
Capture the current frame as a BMP file:
```bash
make smoke # captures 240 frames to smoke_frame.bmp
./Conway-emu --dump screenshot.bmp # capture single frame
./Conway-emu --dump-interval 60 # capture every 60th frame
```
The emulator supports these command-line options:
| Flag | Description |
|------|-------------|
| `--frames N` | Run for N frames then exit |
| `--dump PATH` | Save the current frame to PATH (BMP format) |
| `--dump-interval N` | Save every Nth frame to sequential BMP files |
## Smoke Test (frame capture)
```bash
make smoke
```
This runs the emulator for 240 frames and saves the last frame to `smoke_frame.bmp`.
**Do not** edit `src/main.cpp`, `shim.h`, or the Makefile — they are the
host and are app-agnostic. Do not leave references to the bundled demo
in your sketch.
## Build & Run
```bash
make run
make run # builds examples/$(APP)/$(APP).cpp and opens a window
make run APP=MyDemo # build a differently-named sketch in examples/MyDemo/
make smoke # headless: 240 frames, dumps smoke_frame.bmp
make clean # removes the built binary
```
This will:
1. Compile the sketch (`examples/Conway/Conway.cpp`) alongside the emulator host
2. Build `Conway-emu` binary
3. Run the SDL3 emulator window showing a Game of Life simulation
## Safety hatch
By default the emulator **exits automatically after 10 seconds** so a
runaway demo can never hang around and eat resources. Flags:
```bash
./Demo-emu --user-run # run indefinitely (interactive play)
./Demo-emu --timeout 30000 # different auto-exit time (ms)
./Demo-emu --frames 600 # exit after N frames instead
```
## Frame capture
```bash
make smoke # 240 frames -> smoke_frame.bmp
./Demo-emu --dump shot.bmp # dump the last frame to a BMP
```
## CLI options
| Flag | Description |
|------|-------------|
| `--user-run` | Disable the 10 s auto-exit (interactive use) |
| `--timeout MS` | Auto-exit after MS milliseconds (default 10000) |
| `--frames N` | Exit after N frames (overrides the timeout) |
| `--dump PATH` | Save the last frame to PATH (BMP) |
## Folder Structure
```
emulator-template/
├── README.md # This file
├── shim.h # Minimal Arduino API emplementation (millis, random, etc.)
├── README.md # This file
├── shim.h # Minimal Arduino API shim (millis, random, String…)
├── src/
│ └── main.cpp # SDL3 host loop — sets up window, presents framebuffer,
# and calls setup() / loop() from the sketch
│ └── main.cpp # SDL3 host loop — window, framebuffer, setup()/loop()
├── examples/
│ └── Conway/ # Your experiment sketch lives here
│ ├── Conway.cpp # The main sketch (compiled jointly with main.cpp)
│ └── Conway.ino # .ino file kept as reference (not compiled)
├── Makefile # Self-contained build — just type `make run`
└── Conway-emu # Built binary (removed by `make clean`)
│ └── Demo/
│ └── Demo.cpp # ← your sketch goes here
├── Makefile # Self-contained build — just `make run`
└── .gitignore # ignores built binaries and captured frames
```
## How It Works
The Makefile's single rule compiles `src/main.cpp` together with
`examples/Conway/Conway.cpp` as **one translation unit**. This means:
- The sketch's `setup()` and `loop()` functions are available directly
- The emulator shim (`shim.h`) provides `millis()`, `random()`, `randomSeed()`
- The sketch writes to `emuGfx::fb[]` (ABGR8888 framebuffer), which the host
presents each frame via SDL3
- Input comes through `emu::keyboard` (populated by SDL key events)
- No hardware dependencies: no TFT_eSPI, no SPI, no I2S, no GPIO matrix
## Adding Your Own Experiment
1. **Replace** `examples/Conway/Conway.cpp` with your own sketch
2. **Ensure** your sketch provides `setup()` and `loop()` functions
3. **Use** these emulator APIs from `shim.h`:
- `millis()`, `random()`, `randomSeed()` — timing and randomness
- `emu::keyboard` — ASCII key queue (populated by SDL key events)
- `emuGfx::fb[320*240]` — 320x240 ABGR8888 framebuffer
- `emuGfx::dirty` — mark framebuffer as changed
- `pinMode()`, `digitalRead()` — minimal GPIO (idle HIGH)
## Controls (emulator)
| Key | Action |
|-----|--------|
| `Space` | Toggle pause |
| `P` / `Tab` | Switch view mode (both render same grid in this template) |
| `Esc` | Quit |
`examples/$(APP)/$(APP).cpp` as **one translation unit** (the Makefile
passes the path as `-DAPP_SRC=…`, which main.cpp `#include`s). The sketch's
`setup()`/`loop()` are called directly; each frame it writes pixels into
`emuGfx::fb[]`, and the host presents the framebuffer via SDL3.
## License
@@ -1,141 +0,0 @@
/**
* @file Conway.cpp
* @brief Game of Life — minimal SDL3 emulator prototype
*
* A minimal Game of Life implementation using the T-Deck emulator canvas.
* Press Space to toggle pause. No hardware dependencies.
*
* Build: make -C /var/home/dejvino/workspace/T-Deck/emulator-template run
* or: make -C /var/home/dejvino/workspace/T-Deck/emulator APP=Conway run
* Smoke test: make smoke -C /var/home/dejvino/workspace/T-Deck/emulator-template APP=Conway
*/
// ---------------------------------------------------------------------------
// Minimal emulator shim — provides millis(), random(), randomSeed(), etc.
// ---------------------------------------------------------------------------
#include "shim.h"
// Declare emulated state provided by the emulator main.cpp
extern std::deque<uint8_t> emu::keyboard;
extern uint32_t emuGfx::fb[320 * 240];
extern bool emuGfx::dirty;
// ---------------------------------------------------------------------------
// Canvas configuration (320x240, same as T-Deck display)
// ---------------------------------------------------------------------------
static constexpr int W = 320;
static constexpr int H = 240;
static constexpr int SCALE = 8; // 40 × 30 tile grid
using Grid = uint8_t[W / SCALE][H / SCALE];
// ---------------------------------------------------------------------------
// Game of Life state
// ---------------------------------------------------------------------------
static Grid grid{};
static Grid next{};
static bool paused = true;
static int tick = 0;
// ---------------------------------------------------------------------------
// Input tracking — read from the emu::keyboard queue (populated by the
// emulator main.cpp from SDL key events).
// ---------------------------------------------------------------------------
static bool justPressedSpace = false;
static bool justPressedP = false;
// ---------------------------------------------------------------------------
// setup() — run once at launch
// ---------------------------------------------------------------------------
void setup()
{
randomSeed(millis());
for (int y = 0; y < H / SCALE; y++) {
for (int x = 0; x < W / SCALE; x++) {
grid[x][y] = random(2);
}
}
tick = 0;
paused = false;
}
// ---------------------------------------------------------------------------
// tickOnce() — advance the simulation by one logic tick
// ---------------------------------------------------------------------------
void tickOnce()
{
for (int y = 0; y < H / SCALE; y++) {
for (int x = 0; x < W / SCALE; x++) {
int neighbors = 0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
if (dx == 0 && dy == 0) continue;
int nx = (x + dx + W / SCALE) % (W / SCALE);
int ny = (y + dy + H / SCALE) % (H / SCALE);
neighbors += grid[nx][ny];
}
}
if (grid[x][y]) {
next[x][y] = (neighbors == 2 || neighbors == 3) ? 1 : 0;
} else {
next[x][y] = (neighbors == 3) ? 1 : 0;
}
}
}
for (int i = 0; i < (W / SCALE) * (H / SCALE); i++) {
int ix = i / (W / SCALE);
int iy = i % (W / SCALE);
grid[ix][iy] = next[ix][iy];
}
tick++;
}
// ---------------------------------------------------------------------------
// render() — draw the current grid to the emulator framebuffer
// ---------------------------------------------------------------------------
void render()
{
for (int y = 0; y < H / SCALE; y++) {
for (int x = 0; x < W / SCALE; x++) {
uint32_t c = grid[x][y] ? 0xFFFFFFFF : 0xFF000000;
emuGfx::fb[y * W + x] = c;
}
}
emuGfx::dirty = true;
}
// ---------------------------------------------------------------------------
// Main loop — called once per frame by the emulator main.cpp
// ---------------------------------------------------------------------------
void loop()
{
while (!emu::keyboard.empty()) {
char k = (char)emu::keyboard.front();
emu::keyboard.pop_front();
if (k == ' ') {
justPressedSpace = true;
}
if (k == 'p' || k == '\t') {
justPressedP = true;
}
}
if (justPressedSpace) {
paused = !paused;
justPressedSpace = false;
}
if (justPressedP) {
justPressedP = false;
}
static uint32_t lastStep = 0;
uint32_t now = millis();
if (!paused && (now - lastStep > 150)) {
tickOnce();
render();
lastStep = now;
}
}
@@ -1,165 +0,0 @@
/**
* @file Conway.ino
* @brief Game of Life — minimal SDL3 emulator prototype
*
* A minimal Game of Life implementation using the T-Deck emulator canvas.
* Press Space to toggle pause. No hardware dependencies.
*
* Build: make -C /var/home/dejvino/workspace/T-Deck/emulator-template run
* or: make -C /var/home/dejvino/workspace/T-Deck/emulator APP=Conway run
* Smoke test: make smoke -C /var/home/dejvino/workspace/T-Deck/emulator-template APP=Conway
*/
// ---------------------------------------------------------------------------
// Minimal emulator shim — provides millis(), random(), randomSeed(), etc.
// Pull in the definitions that the emulator main.cpp provides.
// ---------------------------------------------------------------------------
#include "shim.h"
// Emulated state provided by the emulator main.cpp
extern uint32_t emuGfx::fb[320 * 240];
extern bool emuGfx::dirty;
extern std::deque<uint8_t> emu::keyboard;
// ---------------------------------------------------------------------------
// Canvas configuration (320x240, same as T-Deck display)
// ---------------------------------------------------------------------------
static constexpr int W = 320;
static constexpr int H = 240;
static constexpr int SCALE = 8; // 40 × 30 tile grid
using Grid = uint8_t[W / SCALE][H / SCALE];
// ---------------------------------------------------------------------------
// Game of Life state
// ---------------------------------------------------------------------------
static Grid grid{};
static Grid next{};
static bool paused = true;
static int tick = 0;
// ---------------------------------------------------------------------------
// Input tracking — read from the emu::keyboard queue (populated by the
// emulator main.cpp from SDL key events). Each keypress becomes an ASCII
// byte queued at I2C address 0x55.
// ---------------------------------------------------------------------------
static bool justPressedSpace = false;
static bool justPressedP = false;
// ---------------------------------------------------------------------------
// setup() — run once at launch
// ---------------------------------------------------------------------------
void setup()
{
// Fast random seed
randomSeed(millis());
// Populate a random initial state
for (int y = 0; y < H / SCALE; y++) {
for (int x = 0; x < W / SCALE; x++) {
grid[x][y] = random(2);
}
}
tick = 0;
paused = true;
}
// ---------------------------------------------------------------------------
// tickOnce() — advance the simulation by one logic tick
// ---------------------------------------------------------------------------
void tickOnce()
{
for (int y = 0; y < H / SCALE; y++) {
for (int x = 0; x < W / SCALE; x++) {
int neighbors = 0;
// wrap-around torus (simplest: no edges)
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
if (dx == 0 && dy == 0) continue;
int nx = (x + dx + W / SCALE) % (W / SCALE);
int ny = (y + dy + H / SCALE) % (H / SCALE);
neighbors += grid[nx][ny];
}
}
// Conway's rules
if (grid[x][y]) {
next[x][y] = (neighbors == 2 || neighbors == 3) ? 1 : 0;
} else {
next[x][y] = (neighbors == 3) ? 1 : 0;
}
}
}
// Swap buffers
for (int i = 0; i < (W / SCALE) * (H / SCALE); i++) {
int ix = i / (W / SCALE);
int iy = i % (W / SCALE);
grid[ix][iy] = next[ix][iy];
}
tick++;
}
// ---------------------------------------------------------------------------
// render() — draw the current grid to the emulator framebuffer
// The emulator main.cpp maps emuGfx::fb[y * W + x] to an SDL texture
// each frame. ABGR8888 pixel format.
// ---------------------------------------------------------------------------
void render()
{
for (int y = 0; y < H / SCALE; y++) {
for (int x = 0; x < W / SCALE; x++) {
// White living cell / black dead cell
uint32_t c = grid[x][y] ? 0xFFFFFFFF : 0xFF000000;
emuGfx::fb[y * W + x] = c;
}
}
emuGfx::dirty = true;
}
// ---------------------------------------------------------------------------
// Main loop — called once per frame by the emulator main.cpp.
// Handles input and advances simulation when unpaused.
// ---------------------------------------------------------------------------
void loop()
{
// Poll keyboard queue (filled by emulator main.cpp from SDL events)
while (!emu::keyboard.empty()) {
char k = (char)emu::keyboard.front();
emu::keyboard.pop_front();
if (k == ' ') {
justPressedSpace = true;
}
if (k == 'p' || k == '\t') {
justPressedP = true;
}
}
// Toggle pause with Space
if (justPressedSpace) {
paused = !paused;
justPressedSpace = false;
}
// Switch view mode with P / Tab (in this simple template both modes
// render the same grid; the flag is available for future expansion)
if (justPressedP) {
justPressedP = false;
}
// Simulation step (paced ~6.6 Hz when unpaused)
static uint32_t lastStep = 0;
uint32_t now = millis();
if (!paused && (now - lastStep > 150)) {
tickOnce();
render();
lastStep = now;
}
}
// ---------------------------------------------------------------------------
// The emulator main.cpp provides the full SDL3 loop, event pump, and
// frame presentation. This sketch only supplies setup(), loop(), tickOnce(),
// render(), and the framebuffer writes above. No hardware dependencies,
// no TFT_eSPI, no SPI, no I2S — pure emulator-side C++ for rapid
// graphics/engine prototyping.
// ---------------------------------------------------------------------------
+61
View File
@@ -0,0 +1,61 @@
/**
* Demo sketch — replace this file with your own experiment.
*
* Contract with the emulator host (src/main.cpp):
* - implement setup() — called once at launch
* - implement loop() — called once per frame (~60 fps)
* - write pixels into emuGfx::fb[] (320x240, ABGR8888 uint32)
* - set emuGfx::dirty = true each frame you want presented
* - read keys from emu::keyboard (ASCII queue, filled from SDL events)
*
* This sample just bounces a colored box around — enough to prove the
* pipeline works. Delete everything and start from the structure below.
*/
#include "shim.h"
// Emulator state provided by the host (src/main.cpp)
extern uint32_t emuGfx::fb[320 * 240];
extern bool emuGfx::dirty;
extern std::deque<uint8_t> emu::keyboard;
static constexpr int W = 320;
static constexpr int H = 240;
// --- Demo state -----------------------------------------------------------
static float boxX = 40, boxY = 30;
static float velX = 1.7f, velY = 1.1f;
static constexpr float BOX = 24.0f;
void setup()
{
randomSeed(millis());
velX = 1.0f + random(100) / 50.0f;
velY = 1.0f + random(100) / 50.0f;
}
void loop()
{
// Move and bounce
boxX += velX;
boxY += velY;
if (boxX < 0 || boxX + BOX > W) { velX = -velX; boxX += velX; }
if (boxY < 0 || boxY + BOX > H) { velY = -velY; boxY += velY; }
// Clear the framebuffer (opaque black, alpha = 0xFF)
for (int i = 0; i < W * H; i++) emuGfx::fb[i] = 0xFF000000;
// Draw a filled box with a color that drifts over time
uint8_t r = (uint8_t)(128 + 127 * sinf(millis() / 900.0f));
uint32_t color = 0xFF000000u | ((uint32_t)r << 16) | 0x0000CC66u;
for (int y = (int)boxY; y < (int)(boxY + BOX); y++) {
if (y < 0 || y >= H) continue;
for (int x = (int)boxX; x < (int)(boxX + BOX); x++) {
if (x < 0 || x >= W) continue;
emuGfx::fb[y * W + x] = color;
}
}
// Present the frame
emuGfx::dirty = true;
}
+20 -5
View File
@@ -48,21 +48,28 @@ extern "C" void setup();
extern "C" void loop();
// --- Include the user's sketch .cpp file ---
// This is listed on the Makefile's g++ command line so it compiles
// as part of the same translation unit as main.cpp.
#include "examples/Conway/Conway.cpp"
// The path comes from the Makefile: -DAPP_SRC='"examples/$(APP)/$(APP).cpp"'.
// Change APP (or replace examples/Demo/Demo.cpp) to run your own sketch.
#ifndef APP_SRC
#define APP_SRC "examples/Demo/Demo.cpp"
#endif
#include APP_SRC
// ---------------------------------------------------------------------------
// --- Main entry point ---
int main(int argc, char **argv)
{
// Parse simple command-line options
long maxFrames = -1;
long maxFrames = -1; // --frames N: run exactly N frames then exit
const char *dumpPath = nullptr;
bool userRun = false; // --user-run: disable the safety-hatch timeout
long timeoutMs = 10000; // safety hatch: auto-exit after 10 s by default
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--frames") && i + 1 < argc) maxFrames = atol(argv[++i]);
else if (!strcmp(argv[i], "--dump") && i + 1 < argc) dumpPath = argv[++i];
else if (!strcmp(argv[i], "--user-run")) userRun = true;
else if (!strcmp(argv[i], "--timeout") && i + 1 < argc) timeoutMs = atol(argv[++i]);
}
// SDL3 initialization
@@ -73,7 +80,7 @@ int main(int argc, char **argv)
TTF_Init();
// Create window matching the 320x240 canvas
SDL_Window *win = SDL_CreateWindow("T-Deck Template",
SDL_Window *win = SDL_CreateWindow("T-Deck: " APP_NAME,
320, 240, SDL_WINDOW_RESIZABLE);
if (!win) {
std::printf("SDL_CreateWindow failed: %s\n", SDL_GetError());
@@ -138,6 +145,14 @@ int main(int argc, char **argv)
}
}
// --- Safety hatch: auto-exit unless the user asked to play ---
if (!userRun && timeoutMs > 0 && millis() >= (unsigned long)timeoutMs) {
std::printf("[emu] safety hatch: exiting after %ld ms "
"(pass --user-run to run indefinitely)\n", timeoutMs);
running = false;
break;
}
// --- Call the user's simulation step ---
loop();