diff --git a/tron-room-demo/.gitignore b/tron-room-demo/.gitignore new file mode 100644 index 0000000..c255df2 --- /dev/null +++ b/tron-room-demo/.gitignore @@ -0,0 +1,5 @@ +# Build artifacts +*-emu + +# Captured frames +*.bmp diff --git a/tron-room-demo/Makefile b/tron-room-demo/Makefile new file mode 100644 index 0000000..8c00ba2 --- /dev/null +++ b/tron-room-demo/Makefile @@ -0,0 +1,63 @@ +# Minimal Makefile for the T-Deck emulator-only template. +# 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 ?= RoomView +APP_DIR := examples/$(APP) + +# NetDeck firmware headers (nd_layout.h / nd_mapsource.h / nd_demomap.h) — +# the demo renders the REAL demo map, no local copy to drift out of sync. +NETDECK := ../src/netdeck + +# SDL3 flags via pkg-config +SDLFLAGS := $(shell pkg-config --cflags sdl3 sdl3-ttf) +LIBS := $(shell pkg-config --libs sdl3 sdl3-ttf) + +CXX ?= g++ +CXXFLAGS ?= -std=gnu++17 -O2 -Wall -Wextra + +# Include current directory for shim.h, and the sketch directory +INC := -I . -I $(APP_DIR) -I $(NETDECK) + +# 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/$(APP)/$(APP).cpp forming one TU. +EMU_MAIN := src/main.cpp + +EMU := $(APP)-emu + +all: $(EMU) + +# Compile + link: main.cpp includes the sketch .cpp, forming one TU. +# -DAPP_INO makes the sketch's .ino filename available to #ifdef EMULATOR. +# Depend on the sketch too, or sketch edits won't trigger a rebuild. +SKETCH := $(APP_DIR)/$(APP).cpp +$(EMU): $(EMU_MAIN) $(SHIMS) $(SKETCH) + $(CXX) $(CXXFLAGS) $(SDLFLAGS) $(INC) $(DEFS) \ + $(EMU_MAIN) -o $@ $(LIBS) + +run: $(EMU) + ./$(EMU) + +smoke: $(EMU) + ./$(EMU) --frames 240 --dump smoke_frame.bmp + +clean: + rm -f $(EMU) + +.PHONY: all run smoke clean \ No newline at end of file diff --git a/tron-room-demo/README.md b/tron-room-demo/README.md new file mode 100644 index 0000000..24407b2 --- /dev/null +++ b/tron-room-demo/README.md @@ -0,0 +1,73 @@ +# tron-room-demo — RoomView + +A top-down "3D" flythrough of **NetDeck's demo map**, built on the same +emulator-only template as `tron-demo` (SDL3 host, 320x240 ABGR8888 +framebuffer, `setup()`/`loop()` sketch contract — see the original +template README below). + +What makes this one different: the sketch renders the **real** Breach & +Board demo floorplan from the firmware tree (`src/netdeck/nd_demomap.h`, +consumed through the generic `MapSource` interface). There is no local +copy of the map — edit the demo map in `src/netdeck` and this view +follows it. + +## What you see + +- A true 3D orbiting camera (position + look-at basis, perspective + divide) drifting over the deck on a slow orbit with breathing + radius/height. +- `#` walls, `o` cover crates, the `+` blast door and the `T` terminal + as solid shaded boxes: backface culling, painter's-algorithm depth + sort, lambert lighting from above, distance fog, bright top rims. +- Floor tiles as lit quads with a subtle checker. +- The demo map's **network graph** as glowing pylons with teal link + lines and cyan packets traveling along the edges. +- Every entity from the demo spawn list walking its patrol route + (marines cyan, droids orange, heavy red, turrets magenta), plus a + pulsing halo over the airlock. + +## Keys + +| Key | Action | +|-----|--------| +| `a` / `d` | orbit faster / slower (or reverse) | +| `w` / `s` | zoom in / out | +| `r` / `f` | raise / lower the camera | +| `space` | pause the camera drift + patrols | +| `q` / ESC | quit | + +## Build & Run + +```bash +make run # build + open a window +make smoke # headless: 240 frames -> smoke_frame.bmp +make clean +``` + +The Makefile is the template's, with two changes: `APP ?= RoomView` +and `-I ../../src/netdeck` on the include path. + +## Safety hatch / CLI options + +Same as the template: `--user-run` (run indefinitely), `--timeout MS`, +`--frames N`, `--dump PATH`. By default the emulator exits after 10 s; +use `./RoomView-emu --user-run` for interactive viewing. + +--- + +# T-Deck Emulator-Only Template (original README) + +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. + +**Do not** edit `src/main.cpp` or `shim.h` — they are the host and are +app-agnostic. The sketch lives in `examples/$(APP)/$(APP).cpp` and is +compiled as a single translation unit with the host via `-DAPP_SRC=…`. + +| 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 instead | +| `--dump PATH` | Save the last frame to PATH (BMP) | diff --git a/tron-room-demo/examples/RoomView/RoomView.cpp b/tron-room-demo/examples/RoomView/RoomView.cpp new file mode 100644 index 0000000..3a550c4 --- /dev/null +++ b/tron-room-demo/examples/RoomView/RoomView.cpp @@ -0,0 +1,509 @@ +/** + * RoomView — top-down "3D" flythrough of NetDeck's demo map. + * + * Target: T-Deck emulator (320x240, ABGR8888 framebuffer). + * + * Contract with the emulator host (src/main.cpp): + * - implement setup() — called once at launch + * - implement loop() — called once per frame (host paces at ~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) + * + * The world is NetDeck's real demo floorplan: the hardcoded 3-room + * 40x24-tile Breach & Board map from src/netdeck/nd_demomap.h, consumed + * through the generic MapSource interface (tiles, rooms, doors, network + * graph, entity spawn list). Nothing about the map is duplicated here — + * edit the demo map in the firmware tree and this view follows it. + * + * Rendering (all software, no GPU): + * - a true 3D orbiting camera: position + look-at basis, full + * perspective divide, looking down at the deck from above + * - walls / crates / doors / terminals as solid shaded boxes with + * backface culling, painter's-algorithm depth sorting, lambert + * lighting from above and distance fog + * - floor tiles as flat lit quads with a subtle checker + * - the network graph drawn as glowing pylons with link lines and + * data packets traveling along the edges + * - entities from the demo spawn list walking their patrol routes + * + * The camera drifts on its own (slow orbit + breathing radius/height); + * keys adjust: a/d orbit speed, w/s zoom, r/f altitude, space pause, + * q/ESC quit. + */ + +#include "shim.h" +#include "nd_layout.h" +#include "nd_mapsource.h" +#include "nd_demomap.h" + +extern uint32_t emuGfx::fb[320 * 240]; +extern bool emuGfx::dirty; +extern std::deque emu::keyboard; + +static constexpr int W = 320; +static constexpr int H = 240; +static constexpr float TILEF = 1.0f; // one map tile = one world unit + +// --- Palette (ABGR8888: 0xAABBGGRR) ----------------------------------------- +static const uint32_t COL_FLOOR_A = 0xFF2E1F15; // near-black blue floor +static const uint32_t COL_FLOOR_B = 0xFF3A2A1C; // checker variant +static const uint32_t COL_WALL = 0xFFD8B090; // steel blue-gray hull +static const uint32_t COL_CRATE = 0xFF4A5A66; // industrial brown-gray +static const uint32_t COL_DOOR = 0xFF00A0FF; // amber blast door +static const uint32_t COL_TERMINAL = 0xFF40E060; // green terminal glow +static const uint32_t COL_AIRLOCK = 0xFFFFFF00; // cyan airlock ring +static const uint32_t COL_MARINE = 0xFFFFFF00; // cyan squad +static const uint32_t COL_DROID = 0xFF00A0FF; // orange droid +static const uint32_t COL_HEAVY = 0xFF0000FF; // red heavy +static const uint32_t COL_TURRET = 0xFFFF00FF; // magenta turret +static const uint32_t COL_LINK = 0xFFCF8B2B; // teal net link (dim) +static const uint32_t COL_PACKET = 0xFFBF0707; // cyan packet + +// --- Drawing helpers (from the template sketch toolbox) ---------------------- +static inline void putPixel(int x, int y, uint32_t c) { + if (x < 0 || x >= W || y < 0 || y >= H) return; + emuGfx::fb[y * W + x] = c; +} + +static void drawLine(int x0, int y0, int x1, int y1, uint32_t color) { + int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1; + int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1; + int err = dx + dy, e2; + for (;;) { + putPixel(x0, y0, color); + if (x0 == x1 && y0 == y1) break; + e2 = 2 * err; + if (e2 >= dy) { err += dy; x0 += sx; } + if (e2 <= dx) { err += dx; y0 += sy; } + } +} + +static void fillCircle(int cx, int cy, int r, uint32_t color) { + for (int y = -r; y <= r; y++) + for (int x = -r; x <= r; x++) + if (x * x + y * y <= r * r) putPixel(cx + x, cy + y, color); +} + +// Scale an ABGR color's RGB channels by f (fog / shading). +static inline uint32_t dimColor(uint32_t c, float f) { + if (f < 0) f = 0; + if (f > 1) f = 1; + uint32_t r = (uint32_t)((c & 0xFF) * f); + uint32_t g = (uint32_t)(((c >> 8) & 0xFF) * f); + uint32_t b = (uint32_t)(((c >> 16) & 0xFF) * f); + return 0xFF000000u | (b << 16) | (g << 8) | r; +} + +// Horizontal span with clipping. +static inline void hline(int y, int xa, int xb, uint32_t c) { + if (y < 0 || y >= H) return; + if (xa > xb) { int t = xa; xa = xb; xb = t; } + if (xb < 0 || xa >= W) return; + if (xa < 0) xa = 0; + if (xb >= W) xb = W - 1; + for (int x = xa; x <= xb; x++) emuGfx::fb[y * W + x] = c; +} + +// Scanline triangle fill (float vertices, clips to screen). +static void fillTri(float x0, float y0, float x1, float y1, float x2, float y2, uint32_t c) { + if (y1 < y0) { float t; t = x0; x0 = x1; x1 = t; t = y0; y0 = y1; y1 = t; } + if (y2 < y0) { float t; t = x0; x0 = x2; x2 = t; t = y0; y0 = y2; y2 = t; } + if (y2 < y1) { float t; t = x1; x1 = x2; x2 = t; t = y1; y1 = y2; y2 = t; } + if (y2 - y0 < 0.5f) return; + int yA = (int)ceilf(y0), yB = (int)y2; + if (yA < 0) yA = 0; + if (yB > H - 1) yB = H - 1; + for (int y = yA; y <= yB; y++) { + float yc = (float)y + 0.5f; + float t = (yc - y0) / (y2 - y0); + if (t < 0) t = 0; + if (t > 1) t = 1; + float xa = x0 + (x2 - x0) * t; + float xb; + if (yc < y1) { + float t2 = (y1 - y0 < 0.5f) ? 1.0f : (yc - y0) / (y1 - y0); + if (t2 < 0) t2 = 0; + if (t2 > 1) t2 = 1; + xb = x0 + (x1 - x0) * t2; + } else { + float t2 = (y2 - y1 < 0.5f) ? 0.0f : (yc - y1) / (y2 - y1); + if (t2 < 0) t2 = 0; + if (t2 > 1) t2 = 1; + xb = x1 + (x2 - x1) * t2; + } + hline(y, (int)floorf(xa), (int)ceilf(xb), c); + } +} + +static void fillQuad(float x0, float y0, float x1, float y1, + float x2, float y2, float x3, float y3, uint32_t c) { + fillTri(x0, y0, x1, y1, x2, y2, c); + fillTri(x0, y0, x2, y2, x3, y3, c); +} + +// --- Camera ------------------------------------------------------------------ +// Orbiting camera: position camPos, looking at lookAt, up = world +Z. +// Basis vectors are rebuilt each frame; project() does the perspective divide. +static float camPos[3] = { 20, -6, 30 }; +static float lookAt[3] = { 20, 12, 0 }; +static float camF[3], camR[3], camU[3]; +static float FX = 235.0f; // focal length (zoom) +static const float FAR_D = 44.0f; // fog distance (camera units) + +static void updateBasis() { + // forward = normalize(lookAt - camPos) + float f[3] = { lookAt[0] - camPos[0], lookAt[1] - camPos[1], lookAt[2] - camPos[2] }; + float fl = sqrtf(f[0] * f[0] + f[1] * f[1] + f[2] * f[2]); + for (int i = 0; i < 3; i++) f[i] /= fl; + // right = normalize(cross(f, worldUp)); up = cross(right, f) + float r[3] = { f[1] * 1.0f - f[2] * 0.0f, f[2] * 0.0f - f[0] * 1.0f, f[0] * 0.0f - f[1] * 0.0f }; + // cross(f, (0,0,1)) = (f.y*1 - f.z*0, f.z*0 - f.x*1, f.x*0 - f.y*0) + r[0] = f[1]; r[1] = -f[0]; r[2] = 0; + float rl = sqrtf(r[0] * r[0] + r[1] * r[1]); + if (rl < 1e-4f) { r[0] = 1; r[1] = 0; r[2] = 0; } else { r[0] /= rl; r[1] /= rl; } + float u[3] = { + r[1] * f[2] - r[2] * f[1], + r[2] * f[0] - r[0] * f[2], + r[0] * f[1] - r[1] * f[0] + }; + for (int i = 0; i < 3; i++) { camF[i] = f[i]; camR[i] = r[i]; camU[i] = u[i]; } +} + +// Project a world point (X = west-east, Y = south-north, Z = up). +// Returns false if behind the near plane. +static inline bool project(float X, float Y, float Z, int &sx, int &sy, float &depth) { + float d[3] = { X - camPos[0], Y - camPos[1], Z - camPos[2] }; + float rz = d[0] * camF[0] + d[1] * camF[1] + d[2] * camF[2]; + if (rz < 0.6f) return false; + float rx = d[0] * camR[0] + d[1] * camR[1] + d[2] * camR[2]; + float ry = d[0] * camU[0] + d[1] * camU[1] + d[2] * camU[2]; + sx = (int)(160.0f + rx * FX / rz); + sy = (int)(120.0f - ry * FX / rz); + depth = rz; + return true; +} + +// Depth fog factor for a camera-space distance. +static inline float fogFor(float d) { + float f = 1.0f - d / FAR_D; + if (f < 0.60f) f = 0.60f; + if (f > 1.0f) f = 1.0f; + return f; +} + +// --- Solid shaded box (painter's algorithm, backface culled) ----------------- +struct Box { + float x, y; // center on the floor + float hx, hy; // half extents + float z0, z1; // base / top height + uint32_t col; +}; + +// Face corner indices into an 8-corner box, and world normals. +static const int FACES[6][4] = { + {0,1,2,3}, // top (+Z) + {4,5,6,7}, // bottom (-Z, rarely seen) + {0,1,5,4}, // -Y side + {2,3,7,6}, // +Y side + {1,2,6,5}, // +X side + {0,3,7,4}, // -X side +}; +static const float NORMALS[6][3] = { + {0,0,1}, {0,0,-1}, {0,-1,0}, {0,1,0}, {1,0,0}, {-1,0,0}, +}; +static const float LIGHT[3] = { -0.35f, -0.25f, 0.90f }; // from above, slight SW + +static void drawBox(const Box &b, float dist) { + // 8 corners: bottom 0-3 (CCW seen from above), top 4-7 + static const float SIGN[8][3] = { + {-1,-1,0},{1,-1,0},{1,1,0},{-1,1,0}, + {-1,-1,1},{1,-1,1},{1,1,1},{-1,1,1}, + }; + int px[8], py[8]; + bool vis[8]; + float fog = fogFor(dist); + int minX = W, maxX = -1, minY = H, maxY = -1; + for (int i = 0; i < 8; i++) { + float X = b.x + SIGN[i][0] * b.hx; + float Y = b.y + SIGN[i][1] * b.hy; + float Z = SIGN[i][2] ? b.z1 : b.z0; + float d; + vis[i] = project(X, Y, Z, px[i], py[i], d); + if (vis[i]) { + if (px[i] < minX) minX = px[i]; + if (px[i] > maxX) maxX = px[i]; + if (py[i] < minY) minY = py[i]; + if (py[i] > maxY) maxY = py[i]; + } + } + if (maxX < 0 || minX >= W || maxY < 0 || minY >= H) return; // offscreen + + for (int f = 0; f < 6; f++) { + const int *q = FACES[f]; + bool ok = true; + for (int k = 0; k < 4; k++) if (!vis[q[k]]) { ok = false; break; } + if (!ok) continue; + // backface cull: skip faces pointing away from the camera + float fcx = b.x + NORMALS[f][0] * b.hx; + float fcy = b.y + NORMALS[f][1] * b.hy; + float fcz = (NORMALS[f][2] > 0) ? b.z1 : (NORMALS[f][2] < 0 ? b.z0 : (b.z0 + b.z1) * 0.5f); + float toCam[3] = { camPos[0] - fcx, camPos[1] - fcy, camPos[2] - fcz }; + float nd = NORMALS[f][0] * toCam[0] + NORMALS[f][1] * toCam[1] + NORMALS[f][2] * toCam[2]; + if (nd <= 0.001f) continue; + float ndl = NORMALS[f][0] * LIGHT[0] + NORMALS[f][1] * LIGHT[1] + NORMALS[f][2] * LIGHT[2]; + if (ndl < 0.55f) ndl = 0.55f; + uint32_t col = dimColor(b.col, ndl * fog); + fillQuad((float)px[q[0]], (float)py[q[0]], + (float)px[q[1]], (float)py[q[1]], + (float)px[q[2]], (float)py[q[2]], + (float)px[q[3]], (float)py[q[3]], col); + // bright rim on the top edges (f == 0 is the top face) + if (f == 0) { + uint32_t rim = dimColor(b.col, (0.55f + 0.45f * ndl) * fog); + drawLine(px[q[0]], py[q[0]], px[q[1]], py[q[1]], rim); + drawLine(px[q[1]], py[q[1]], px[q[2]], py[q[2]], rim); + drawLine(px[q[2]], py[q[2]], px[q[3]], py[q[3]], rim); + drawLine(px[q[3]], py[q[3]], px[q[0]], py[q[0]], rim); + } + } +} + +// Distance from the camera to a box center (for fog + depth sort). +static inline float boxDist(const Box &b) { + float dx = b.x - camPos[0], dy = b.y - camPos[1]; + float dz = (b.z0 + b.z1) * 0.5f - camPos[2]; + return sqrtf(dx * dx + dy * dy + dz * dz); +} + +// --- World state -------------------------------------------------------------- +static nd::DemoMapSource mapSource; + +struct Walker { + float ax, ay, bx, by; // patrol endpoints (world units, tile centers) + float t; // 0..1 along the route + float dir; // +1 or -1 + float speed; // tiles per second + uint8_t kind; +}; + +static const int MAX_WALKERS = nd::MAX_UNITS > 20 ? nd::MAX_UNITS : 20; +static Walker walkers[MAX_WALKERS]; +static int walkerCount = 0; + +static void buildWalkers() { + walkerCount = 0; + for (int i = 0; i < mapSource.spawnCount() && walkerCount < MAX_WALKERS; i++) { + const nd::UnitSpawn &s = mapSource.spawn(i); + Walker &w = walkers[walkerCount]; + w.ax = (s.tx % nd::TILE_COLS) + 0.5f; + w.ay = (s.tx / nd::TILE_COLS) + 0.5f; + if (s.patA >= 0 && s.patB >= 0) { + w.bx = (s.patA % nd::TILE_COLS) + 0.5f; + w.by = (s.patA / nd::TILE_COLS) + 0.5f; + } else { + w.bx = w.ax; w.by = w.ay; // stationary + } + w.t = 0; + w.dir = 1; + w.speed = (s.kind == 2) ? 0.0f : (s.kind == 3 ? 0.0f : 1.1f + (i % 3) * 0.15f); + w.kind = s.kind; + walkerCount++; + } +} + +static inline float lerp(float a, float b, float t) { return a + (b - a) * t; } + +// --- Setup -------------------------------------------------------------------- +void setup() { + buildWalkers(); + // initial camera pose: south of the map, looking north at the deck + camPos[0] = 20.0f; camPos[1] = 12.0f - 22.0f; camPos[2] = 30.0f; +} + +// --- Loop ---------------------------------------------------------------------- +void loop() { + // --- input --- + static float orbitSpeed = 0.10f; // rad/s + static bool paused = false; + while (!emu::keyboard.empty()) { + uint8_t k = emu::keyboard.front(); + emu::keyboard.pop_front(); + if (k == 'q' || k == 0x1b) { emu::quitRequested = true; } + if (k == 'a') { orbitSpeed += 0.03f; if (orbitSpeed > 0.60f) orbitSpeed = 0.60f; } + if (k == 'd') { orbitSpeed -= 0.03f; if (orbitSpeed < -0.60f) orbitSpeed = -0.60f; } + if (k == 'w') { FX += 18.0f; if (FX > 320.0f) FX = 320.0f; } + if (k == 's') { FX -= 18.0f; if (FX < 90.0f) FX = 90.0f; } + if (k == 'r') { camPos[2] += 2.0f; if (camPos[2] > 60.0f) camPos[2] = 60.0f; } + if (k == 'f') { camPos[2] -= 2.0f; if (camPos[2] < 14.0f) camPos[2] = 14.0f; } + if (k == ' ') paused = !paused; + } + + // --- delta time --- + static unsigned long lastMs = 0; + unsigned long now = millis(); + float dt = lastMs ? (now - lastMs) / 1000.0f : 1.0f / 60.0f; + lastMs = now; + if (dt > 0.1f) dt = 0.1f; + + // --- camera drift: slow orbit + breathing radius/height --- + static float orbit = 0.0f; // angle around the map center + static float breathe = 0.0f; + if (!paused) { + orbit += orbitSpeed * dt; + breathe += dt * 0.35f; + } + float radius = 15.0f + 3.0f * sinf(breathe * 0.7f); + float height = 21.0f + 3.5f * sinf(breathe * 0.45f + 1.3f); + lookAt[0] = 20.0f + 1.5f * sinf(breathe * 0.5f); + lookAt[1] = 12.0f + 1.0f * cosf(breathe * 0.33f); + camPos[0] = lookAt[0] + cosf(orbit) * radius; + camPos[1] = lookAt[1] + sinf(orbit) * radius; + camPos[2] = height; + updateBasis(); + + // --- entities walk their patrol routes --- + if (!paused) { + for (int i = 0; i < walkerCount; i++) { + Walker &w = walkers[i]; + if (w.speed <= 0) continue; + float len = sqrtf((w.bx - w.ax) * (w.bx - w.ax) + (w.by - w.ay) * (w.by - w.ay)); + if (len < 0.01f) continue; + w.t += w.dir * w.speed * dt / len; + if (w.t > 1) { w.t = 1; w.dir = -1; } + if (w.t < 0) { w.t = 0; w.dir = 1; } + } + } + + // --- clear framebuffer --- + for (int i = 0; i < W * H; i++) emuGfx::fb[i] = 0xFF080014; + + // --- floor: flat lit quads for every non-wall tile, checker shaded --- + for (int ty = 0; ty < nd::TILE_ROWS; ty++) { + for (int tx = 0; tx < nd::TILE_COLS; tx++) { + char ch = mapSource.tileAt(tx, ty); + if (ch == '#') continue; + uint32_t base = ((tx + ty) & 1) ? COL_FLOOR_B : COL_FLOOR_A; + int px[4], py[4]; + float d; + bool ok = true; + const float OFF[4][2] = { {0,0},{1,0},{1,1},{0,1} }; + for (int k = 0; k < 4; k++) + if (!project((float)(tx + OFF[k][0]), (float)(ty + OFF[k][1]), 0.0f, px[k], py[k], d)) { ok = false; break; } + if (!ok) continue; + if (px[0] < -8 && px[1] < -8 && px[2] < -8 && px[3] < -8) continue; + if (px[0] > W + 8 && px[1] > W + 8 && px[2] > W + 8 && px[3] > W + 8) continue; + float cx = tx + 0.5f, cy = ty + 0.5f; + fillQuad((float)px[0], (float)py[0], (float)px[1], (float)py[1], + (float)px[2], (float)py[2], (float)px[3], (float)py[3], + dimColor(base, fogFor(sqrtf((cx - camPos[0]) * (cx - camPos[0]) + + (cy - camPos[1]) * (cy - camPos[1]) + + camPos[2] * camPos[2])))); + } + } + + // --- collect solid geometry: walls, crates, door, terminal, node pylons --- + struct Solid { Box b; }; + static Solid solids[1024]; + int nSolids = 0; + + for (int ty = 0; ty < nd::TILE_ROWS; ty++) { + for (int tx = 0; tx < nd::TILE_COLS; tx++) { + char ch = mapSource.tileAt(tx, ty); + if (ch == '.') continue; + Box b; + b.x = tx + 0.5f; b.y = ty + 0.5f; + b.z0 = 0.0f; + b.hx = b.hy = 0.5f; + switch (ch) { + case '#': b.z1 = 1.6f; b.col = COL_WALL; break; + case 'o': b.z1 = 0.9f; b.col = COL_CRATE; break; + case '+': b.z1 = 1.3f; b.col = COL_DOOR; break; + case 'T': b.z1 = 0.7f; b.col = COL_TERMINAL; break; + case 'A': b.z1 = 0.15f; b.col = COL_AIRLOCK; break; + default: continue; + } + solids[nSolids++].b = b; + } + } + + // network nodes: glowing pylons at their pinned tiles + static Box nodeBoxes[nd::MAX_NODES]; + for (int i = 0; i < mapSource.nodeCount(); i++) { + const nd::NetNodeDef &n = mapSource.node(i); + Box &b = nodeBoxes[i]; + b.x = n.tx + 0.5f; b.y = n.ty + 0.5f; + b.hx = b.hy = 0.28f; + b.z0 = 0.0f; + b.z1 = 1.9f; + // RGB565 -> ABGR8888 + uint32_t r5 = ((n.color >> 11) & 31) * 8; + uint32_t g6 = ((n.color >> 5) & 63) * 4; + uint32_t b5 = (n.color & 31) * 8; + b.col = 0xFF000000u | (b5 << 16) | (g6 << 8) | r5; + solids[nSolids++].b = b; + } + + // --- entities as small glowing boxes --- + static Box entBoxes[MAX_WALKERS]; + for (int i = 0; i < walkerCount; i++) { + const Walker &w = walkers[i]; + Box &b = entBoxes[i]; + b.x = lerp(w.ax, w.bx, w.t); + b.y = lerp(w.ay, w.by, w.t); + b.hx = b.hy = 0.30f; + b.z0 = 0.0f; + b.z1 = (w.kind == 3) ? 0.45f : (w.kind == 2 ? 0.85f : 0.65f); + b.col = (w.kind == 0) ? COL_MARINE : (w.kind == 1) ? COL_DROID + : (w.kind == 2) ? COL_HEAVY : COL_TURRET; + solids[nSolids++].b = b; + } + + // --- depth sort far -> near (painter's algorithm) --- + static float dists[1024 + nd::MAX_NODES + MAX_WALKERS]; + static int order[1024 + nd::MAX_NODES + MAX_WALKERS]; + for (int i = 0; i < nSolids; i++) { dists[i] = boxDist(solids[i].b); order[i] = i; } + for (int a = 1; a < nSolids; a++) { + int v = order[a], j = a - 1; + while (j >= 0 && dists[order[j]] < dists[v]) { order[j + 1] = order[j]; j--; } + order[j + 1] = v; + } + for (int i = 0; i < nSolids; i++) drawBox(solids[order[i]].b, dists[order[i]]); + + // --- network links + traveling packets (overhead lines between pylon tops) + for (int e = 0; e < mapSource.edgeCount(); e++) { + const nd::NetEdgeDef &ed = mapSource.edge(e); + const nd::NetNodeDef &na = mapSource.node(ed.a); + const nd::NetNodeDef &nb = mapSource.node(ed.b); + float ax = na.tx + 0.5f, ay = na.ty + 0.5f; + float bx = nb.tx + 0.5f, by = nb.ty + 0.5f; + int x0, y0, x1, y1; + float d0, d1; + if (!project(ax, ay, 1.9f, x0, y0, d0)) continue; + if (!project(bx, by, 1.9f, x1, y1, d1)) continue; + drawLine(x0, y0, x1, y1, dimColor(COL_LINK, fogFor((d0 + d1) * 0.5f))); + // packet: a small bright dot sweeping the edge + float ph = fmodf(now / 1000.0f * 0.35f + e * 0.37f, 1.0f); + int pkx, pky; + float pdd; + if (project(lerp(ax, bx, ph), lerp(ay, by, ph), 1.9f + 0.15f, pkx, pky, pdd)) { + int r = (int)(0.14f * FX / pdd); + if (r < 1) r = 1; + if (r > 4) r = 4; + fillCircle(pkx, pky, r, dimColor(COL_PACKET, fogFor(pdd))); + } + } + + // --- pulsing halo over the airlock tile (squad entry marker) --- + { + int ax_, ay_; + float dd; + const nd::NetNodeDef &root = mapSource.node(mapSource.rootNode()); + if (project(root.tx + 0.5f, root.ty + 0.5f, 0.2f, ax_, ay_, dd)) { + int r = (int)(0.55f * FX / dd) + (int)(2.0f * sinf(now / 1000.0f * 3.0f)); + if (r > 2) fillCircle(ax_, ay_, r, (dimColor(COL_AIRLOCK, 0.35f) & 0x00FFFFFF) | 0x50000000); + } + } + + emuGfx::dirty = true; +} diff --git a/tron-room-demo/shim.h b/tron-room-demo/shim.h new file mode 100644 index 0000000..a6542ab --- /dev/null +++ b/tron-room-demo/shim.h @@ -0,0 +1,153 @@ +/** + * Minimal emulator shim — provides only the subset of Arduino API needed + * for graphics/engine prototypes running on the SDL3 emulator. + * + * Include this single header in your sketch: + * #include "shim.h" + * + * The template's main.cpp includes this file and sets up the emulated state. + * This header defines: millis(), random(), randomSeed(), String, and basic + * type definitions. No GPIO, no interrupts, no peripheral dependencies. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // for std::this_thread::sleep_for +#include // for std::chrono::milliseconds, microseconds + +// --------------------------------------------------------------------------- +// Platform marker: the sketch can #ifdef EMULATOR for emulator-only code +// --------------------------------------------------------------------------- +#define EMULATOR 1 + +// --------------------------------------------------------------------------- +// Flash-resident data macros (no-op on emulator; flash-mapped memory) +// --------------------------------------------------------------------------- +#define PROGMEM +#define pgm_read_byte(addr) (*(const unsigned char *)(addr)) +#define pgm_read_word(addr) (*(const unsigned short *)(addr)) +#define pgm_read_dword(addr) (*(const unsigned long *)(addr)) + +// --------------------------------------------------------------------------- +// Time +// --------------------------------------------------------------------------- +inline unsigned long millis() +{ + using namespace std::chrono; + static const auto start = steady_clock::now(); + return (unsigned long)duration_cast(steady_clock::now() - start).count(); +} + +inline unsigned long micros() +{ + using namespace std::chrono; + static const auto start = steady_clock::now(); + return (unsigned long)duration_cast(steady_clock::now() - start).count(); +} + +inline void delay(unsigned long ms) +{ + std::this_thread::sleep_for(std::chrono::milliseconds(ms)); +} + +inline void delayMicroseconds(unsigned int us) +{ + std::this_thread::sleep_for(std::chrono::microseconds(us)); +} + +// --------------------------------------------------------------------------- +// Random (Arduino-style) +// --------------------------------------------------------------------------- +inline long random(long maxv) { return maxv > 0 ? std::rand() % maxv : 0; } +inline long random(long lo, long hi) { return hi > lo ? lo + std::rand() % (hi - lo) : lo; } +inline void randomSeed(unsigned long seed) { std::srand((unsigned)seed); } + +// Emulated esp_random (used by some sketches) +inline uint32_t esp_random() +{ + return ((uint32_t)std::rand() << 17) ^ (uint32_t)std::rand() ^ millis(); +} + +// --------------------------------------------------------------------------- +// Minimal String class (Arduino-style) +// --------------------------------------------------------------------------- +class String { +public: + std::string s; + String() {} + String(const char *c) : s(c) {} + String(const std::string &x) : s(x) {} + String(char c) : s(1, c) {} + String(int v) : s(std::to_string(v)) {} + String(long v) : s(std::to_string(v)) {} + String(unsigned v) : s(std::to_string(v)) {} + String(unsigned long v) : s(std::to_string(v)) {} + String(float v) : s(std::to_string(v)) {} + const char *c_str() const { return s.c_str(); } + unsigned length() const { return (unsigned)s.length(); } +}; + +inline String operator+(const String &a, const String &b) { return String(a.s + b.s); } +inline String operator+(const String &a, const char *b) { return String(a.s + b); } +inline String operator+(const char *a, const String &b) { return String(std::string(a) + b.s); } + +// -------------------------------------------------------------------------// +// Minimal GPIO — emulated pin levels (idle HIGH). Access via +// emu::pinLevels in the main.cpp; this shim provides a safe read API. +// For the template's purposes, users should use the emu::keyboard queue +// for input instead of raw GPIO reads. +// -------------------------------------------------------------------------// +#define INPUT 0 +#define OUTPUT 1 +#define INPUT_PULLUP 2 +#define HIGH 1 +#define LOW 0 + +inline void pinMode(int, int) {} // no-op in emulator + +inline int digitalRead(int pin) +{ + (void)pin; + return 1; // idle HIGH +} + +inline void digitalWrite(int, int) {} + +// Pin edge structure — used by the emulator's ISR dispatch logic. +struct PinEdge { int pin, from, to; }; + +// -------------------------------------------------------------------------// +// Serial simulation (minimal) +// -------------------------------------------------------------------------// +struct SerialSim { + std::deque *sink = nullptr; + void capture(const char *s) + { + if (!sink) return; + sink->push_back(s); + while (sink->size() > 512) sink->pop_front(); + } + template void printf(const char *fmt, A... a) + { + char buf[512]; + std::snprintf(buf, sizeof(buf), fmt, a...); + std::fputs(buf, stdout); + capture(buf); + } + void println() { std::printf("\n"); capture("\n"); } + void println(const char *s) { std::printf("%s\n", s); capture(s); capture("\n"); } + void println(const String &s) { std::printf("%s\n", s.c_str()); capture(s.c_str()); capture("\n"); } + void println(int v) { std::printf("%d\n", v); capture(std::to_string(v).c_str()); capture("\n"); } +}; + +// External instance — the emulator main.cpp defines this. +extern SerialSim Serial; \ No newline at end of file diff --git a/tron-room-demo/src/main.cpp b/tron-room-demo/src/main.cpp new file mode 100644 index 0000000..27ba6a9 --- /dev/null +++ b/tron-room-demo/src/main.cpp @@ -0,0 +1,240 @@ +/** + * Minimal SDL3 host for the T-Deck emulator-only template. + * + * Sets up an SDL3 window/renderer, presents the user's framebuffer, + * and calls the user's sketch setup() / loop() each frame. + * + * This file is deliberately hardware-free: no TFT_eSPI, no SPI, + * no I2S, no GPIO matrix. It only depends on SDL3 and the shim. + */ + +#include +#if __has_include() +#include +#else +#include +#endif +#include +#include +#include +#include + +// --- Include the template's minimal shim (provides millis(), random, +// randomSeed(), String, pinMode/digitalRead, etc.) --- +#include "shim.h" + +// --- Emulator shared state (defined in main.cpp below) --- +// The sketch writes to emuGfx::fb; this file presents it each frame. +// --------------------------------------------------------------------------- +namespace emu { + uint8_t pinLevels[64]; + const char *pinDrivenBy[64]; + std::deque pinEdges; + bool touchDown = false; + int touchX = 0, touchY = 0; + std::deque keyboard; + bool quitRequested = false; +} // namespace emu + +namespace emuGfx { + uint32_t fb[320 * 240]; // ABGR8888 pixels, 320x240 + SDL_Texture *tex = nullptr; + bool dirty = true; +} // namespace emuGfx + +// --- Forward declarations of the user's sketch functions --- +// These will be defined in the sketch .cpp file included below. +extern "C" void setup(); +extern "C" void loop(); + +// --- Include the user's sketch .cpp file --- +// 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; // --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 + if (!SDL_Init(SDL_INIT_VIDEO)) { + std::printf("SDL_Init failed: %s\n", SDL_GetError()); + return 1; + } + TTF_Init(); + + // Create window matching the 320x240 canvas + 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()); + TTF_Quit(); + SDL_Quit(); + return 1; + } + + SDL_Renderer *ren = SDL_CreateRenderer(win, NULL); + if (!ren) ren = SDL_CreateRenderer(win, "software"); + SDL_SetRenderLogicalPresentation(ren, 320, 240, + SDL_LOGICAL_PRESENTATION_LETTERBOX); + emuGfx::tex = SDL_CreateTexture(ren, SDL_PIXELFORMAT_ABGR8888, + SDL_TEXTUREACCESS_STREAMING, 320, 240); + if (!emuGfx::tex) { + std::printf("SDL_CreateTexture failed: %s\n", SDL_GetError()); + SDL_DestroyRenderer(ren); + SDL_DestroyWindow(win); + TTF_Quit(); + SDL_Quit(); + return 1; + } + + // --- User sketch initialization --- + setup(); + + // --- Main loop --- + bool running = true; + // Frame pacing: the sketch contract is "loop() called once per frame + // (~60 fps)". Without pacing this loop busy-spins at hundreds/thousands + // of fps on a desktop and every frame-based animation runs too fast, + // so we delay until the next 60 Hz tick before starting the next frame. + const Uint64 FRAME_MS = 1000 / 60; // ~16.7 ms per frame + Uint64 nextFrame = SDL_GetTicks() + FRAME_MS; + while (running && !emu::quitRequested) { + // --- Event pump --- + SDL_Event e; + while (SDL_PollEvent(&e)) { + if (e.type == SDL_EVENT_QUIT) { + running = false; + break; + } + // Forward key presses to the emulated I2C keyboard device + if (e.type == SDL_EVENT_KEY_DOWN) { + if (e.key.repeat) break; + SDL_Keycode k = e.key.key; + if (k == SDLK_RETURN || k == SDLK_KP_ENTER) { + emu::keyboard.push_back(' '); + } + else if (k == SDLK_SPACE) { + emu::keyboard.push_back(' '); + } + else if (k == SDLK_BACKSPACE) { + emu::keyboard.push_back(0x08); + } + else if (k == SDLK_DELETE) { + emu::keyboard.push_back(0x7F); + } + else if (k == SDLK_ESCAPE) { + running = false; + } + else { + const char *name = SDL_GetKeyName(k); + if (name && strlen(name) == 1) { + emu::keyboard.push_back((uint8_t)tolower((unsigned char)name[0])); + } + } + } + } + + // --- 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(); + + // --- Present frame if dirty --- + if (emuGfx::dirty) { + SDL_UpdateTexture(emuGfx::tex, nullptr, emuGfx::fb, + 320 * sizeof(uint32_t)); + emuGfx::dirty = false; + } + + // Render: clear -> texture -> present + SDL_RenderClear(ren); + SDL_RenderTexture(ren, emuGfx::tex, nullptr, nullptr); + SDL_RenderPresent(ren); + + // --- Frame counting / dump --- + if (maxFrames > 0 && --maxFrames == 0) { + running = false; + if (dumpPath) { + // Create a surface from the texture and save as BMP + SDL_Surface *s = SDL_CreateSurface(320, 240, SDL_PIXELFORMAT_ABGR8888); + if (s) { + // Read pixels from the texture + void *pixels; + int pitch; + SDL_LockTexture(emuGfx::tex, nullptr, &pixels, &pitch); + // Copy the framebuffer directly to the surface + Uint32 *sp = (Uint32 *)s->pixels; + for (int y = 0; y < 240; y++) { + memcpy(sp + y * s->w, emuGfx::fb + y * 320, 320 * sizeof(Uint32)); + } + SDL_UnlockTexture(emuGfx::tex); + + SDL_SaveBMP(s, dumpPath); + SDL_DestroySurface(s); + std::printf("[emu] frame dumped to %s\n", dumpPath); + } + } + } + + // --- Frame pacing: sleep until the next 60 Hz tick --- + Uint64 nowMs = SDL_GetTicks(); + if (nowMs >= nextFrame) { + // Behind schedule (a slow frame or a stall): resync instead of + // burst-catching-up, so animation never runs fast to "make up" + // lost frames. + nextFrame = nowMs; + } else { + SDL_Delay((Uint32)(nextFrame - nowMs)); + } + nextFrame += FRAME_MS; + } + + // --- Save last frame as BMP for AI inspection --- + { + SDL_Surface *s = SDL_CreateSurface(320, 240, SDL_PIXELFORMAT_ABGR8888); + if (s) { + void *pixels; + int pitch; + SDL_LockTexture(emuGfx::tex, nullptr, &pixels, &pitch); + Uint32 *sp = (Uint32 *)s->pixels; + for (int y = 0; y < 240; y++) { + memcpy(sp + y * s->w, emuGfx::fb + y * 320, 320 * sizeof(Uint32)); + } + SDL_UnlockTexture(emuGfx::tex); + SDL_SaveBMP(s, "frame.bmp"); + SDL_DestroySurface(s); + std::printf("[emu] last frame saved to frame.bmp\n"); + } + } + + // --- Cleanup --- + TTF_Quit(); + SDL_DestroyTexture(emuGfx::tex); + SDL_DestroyRenderer(ren); + SDL_DestroyWindow(win); + SDL_Quit(); + return 0; +} \ No newline at end of file