From c58f31d02c37f17969002099a1b2e89831782887 Mon Sep 17 00:00:00 2001 From: Dejvino Date: Mon, 16 Nov 2026 22:51:40 +0100 Subject: [PATCH] emulator-template: RGB565 wire-order contract + ready-to-build HW twin Propagate the lessons from tron-room-demo's hardware bring-up back into the canonical template, so demos are hardware-testable from day one: - Contract change: the sketch renders into emuGfx::fb565 (320x240 uint16_t, RGB565 in PANEL WIRE ORDER - big-endian, the byte sequence the ST7789 receives over SPI, the same convention TFT_eSprite's primitives use). The host expands 565 to 8888 for SDL only. Native little-endian writes look right in the emulator but show byte-swapped on the panel (seen on hardware: BG 0x0002 -> green, fogged floor 0x0882 -> pink) - the new contract makes that bug impossible. - Recommended sketch structure: examples/APP/Core.h holds all rendering/logic device-agnostically (demoInit/demoInput/demoFrame); the .cpp is a thin emulator shell. Bundled sample demonstrates it. - New fw/ scaffold: standalone PlatformIO project (shared boards/lib, T-Deck pin map) with DemoHW.ino driving the same core through a TFT_eSprite frameBuffer() and reporting true fps + render/push split over USB serial every 2 s. -O2 explicitly (pio default -Os skews benchmarks). - shim.h gains rgb565()/wire565() helpers; Makefile deps now include the sketch's headers; --dump now also fires on safety-hatch exit (a long --frames run was silently losing its dump before). Verified: template builds + smoke renders correct 565 colors; DemoHW builds clean for ESP32-S3 (328 KB flash). --- emulator-template/Makefile | 5 +- emulator-template/README.md | 121 +++++++++++++++++---- emulator-template/examples/Demo/Demo.cpp | 54 ++++----- emulator-template/examples/Demo/DemoCore.h | 94 ++++++++++++++++ emulator-template/fw/DemoHW.ino | 117 ++++++++++++++++++++ emulator-template/fw/platformio.ini | 37 +++++++ emulator-template/shim.h | 16 +++ emulator-template/src/main.cpp | 92 +++++++++------- 8 files changed, 440 insertions(+), 96 deletions(-) create mode 100644 emulator-template/examples/Demo/DemoCore.h create mode 100644 emulator-template/fw/DemoHW.ino create mode 100644 emulator-template/fw/platformio.ini diff --git a/emulator-template/Makefile b/emulator-template/Makefile index ae4cf37..096adb1 100644 --- a/emulator-template/Makefile +++ b/emulator-template/Makefile @@ -41,9 +41,10 @@ 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. +# Depend on the sketch AND its headers too (e.g. the device-agnostic +# $(APP)Core.h), or core edits won't trigger a rebuild. SKETCH := $(APP_DIR)/$(APP).cpp -$(EMU): $(EMU_MAIN) $(SHIMS) $(SKETCH) +$(EMU): $(EMU_MAIN) $(SHIMS) $(SKETCH) $(wildcard $(APP_DIR)/*.h) $(CXX) $(CXXFLAGS) $(SDLFLAGS) $(INC) $(DEFS) \ $(EMU_MAIN) -o $@ $(LIBS) diff --git a/emulator-template/README.md b/emulator-template/README.md index 9f9927a..80c08f8 100644 --- a/emulator-template/README.md +++ b/emulator-template/README.md @@ -1,29 +1,74 @@ # T-Deck Emulator-Only Template 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. +graphics/engine experiments without any hardware — with a ready-made +firmware twin so the same code can be benchmarked on the real T-Deck. +No TFT_eSPI, no SPI, no I2S, no GPIO on the desktop side — just SDL3 +and a framebuffer. + +## The color contract (RGB565, panel wire order) + +The T-Deck's ST7789 panel receives 16-bit RGB565 pixels **high byte +first** over SPI, and on hardware your framebuffer is pushed raw. So +the emulator's contract matches the panel exactly: + +- render into `emuGfx::fb565[]` — 320x240 `uint16_t`, RGB565 in **panel + wire order** (big-endian: store `wire565(c)`, a byte swap) +- build colors with `rgb565(r, g, b)` (5/6/5 channels) +- set `emuGfx::dirty = true` when a frame is ready + +The host expands 565 → 8888 for the desktop window only. On the device +that step doesn't exist — the buffer goes to the panel as-is. Anything +you see in the emulator, including 5-bit color banding, is what the +panel would show. + +**Why wire order:** `TFT_eSprite`'s own primitives store colors +byte-swapped (`drawPixel`: `color = color>>8 | color<<8`) because +`pushSprite` sends the buffer raw. If your software rasterizer writes +native little-endian values into a hardware sprite buffer, colors show +up byte-swapped on the panel while the emulator looks fine. Storing in +wire order from day one makes that bug impossible. + +## Sketch structure (for hardware-testable demos) + +``` +examples/$(APP)/$(APP)Core.h <- all rendering + logic. Device-agnostic: + no shim, no SDL, no Arduino. Renders + RGB565 (wire order) into a caller- + supplied buffer. +examples/$(APP)/$(APP).cpp <- thin emulator shell: keyboard pump, + delta time, set dirty. +fw/$(APP)HW.ino <- firmware twin (copy of DemoHW.ino): + TFT_eSprite + free-running fps report. +``` + +The bundled sample implements exactly this split. Because the core is +shared 1:1, whatever fps the hardware reports is the fps of exactly +your code. ## Creating a new demo (the only thing you need to do) 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: +2. Put your rendering + logic in `examples/Demo/DemoCore.h` (keep the + file and folder name `Demo`, or rename both and pass `APP=YourName` + to make). +3. The core's API contract (mirrored by the twin in `fw/`): + - `demoInit(uint16_t *fb)` — receive the 320x240 RGB565 buffer + - `demoInput(uint8_t key)` — one ASCII key (`0x1b` = ESC) + - `demoQuitRequested()` — ask the host to exit + - `demoFrame(float dt, unsigned long nowMs)` — simulate + render +4. The shell (`examples/Demo/Demo.cpp`) may use: - `millis()`, `delay()`, `random()`, `randomSeed()` — timing/randomness - - `emuGfx::fb[320*240]` — 320x240 ABGR8888 framebuffer (`uint32_t` pixels) + - `emuGfx::fb565[320*240]` — the RGB565 buffer (wire order) - `emuGfx::dirty = true` — set this every frame you want presented - `emu::keyboard` — ASCII key queue (`' '`, `'a'`…, `0x08` backspace) - `pinMode()`/`digitalRead()` — stubs, idle HIGH -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. +**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. -**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 +## Build & Run (emulator) ```bash make run # builds examples/$(APP)/$(APP).cpp and opens a window @@ -32,6 +77,34 @@ make smoke # headless: 240 frames, dumps smoke_frame.bmp make clean # removes the built binary ``` +## On the real T-Deck (ESP32-S3) — free-running benchmark + +The `fw/` scaffold drives the same core on the hardware, drawing +straight into a `TFT_eSprite`'s `frameBuffer()` (16-bit RGB565, PSRAM — +the same full-frame pipeline as NetDeck's M1 anti-flicker pattern) and +presenting with `startWrite()/pushSprite(0,0)/endWrite()`. + +The loop is deliberately **free-running** — no pacing — and prints a +report over USB serial every 2 s: + +``` +DemoHW: 120 frames in 2001ms = 60.0 fps | render 12.3 ms, push 14.8 ms +``` + +`render` is your core's rasterizer; `push` is the SPI transfer to the +panel (at 80 MHz a full 320x240 frame costs ~15 ms — that is the +physical floor for full-frame 30 fps). + +```bash +pio run -d emulator-template/fw -t upload # flash the T-Deck +pio device monitor # 115200 baud +``` + +(`fw/platformio.ini` points at the repo's shared `boards/`, `lib/` and +the T-Deck pin map in `src/netdeck` — NetDeck's own builds are +untouched. Rename the demo: adjust `[env:DemoHW]`'s `-I` and the +`demo::` calls in the .ino.) + ## Safety hatch By default the emulator **exits automatically after 10 seconds** so a @@ -50,6 +123,11 @@ make smoke # 240 frames -> smoke_frame.bmp ./Demo-emu --dump shot.bmp # dump the last frame to a BMP ``` +Note: `--dump` fires when the run ends — via `--frames N` completing or +the safety hatch exiting. A run longer than the default 10 s hatch needs +`--timeout` raised (e.g. `--frames 900 --timeout 20000`), or the hatch +cuts it short. + ## CLI options | Flag | Description | @@ -64,12 +142,16 @@ make smoke # 240 frames -> smoke_frame.bmp ``` emulator-template/ ├── README.md # This file -├── shim.h # Minimal Arduino API shim (millis, random, String…) +├── shim.h # Minimal Arduino API shim (millis, random, rgb565…) ├── src/ -│ └── main.cpp # SDL3 host loop — window, framebuffer, setup()/loop() +│ └── main.cpp # SDL3 host loop — window, 565→8888 expand, setup()/loop() ├── examples/ │ └── Demo/ -│ └── Demo.cpp # ← your sketch goes here +│ ├── DemoCore.h # ← your rendering + logic (device-agnostic) +│ └── Demo.cpp # ← emulator shell +├── fw/ +│ ├── platformio.ini # Hardware twin project (shared boards/lib) +│ └── DemoHW.ino # T-Deck firmware with fps report ├── Makefile # Self-contained build — just `make run` └── .gitignore # ignores built binaries and captured frames ``` @@ -78,9 +160,10 @@ emulator-template/ The Makefile's single rule compiles `src/main.cpp` together with `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. +passes the path as `-DAPP_SRC=…`, which main.cpp `#include`s). The +sketch's `setup()`/`loop()` are called directly; each frame it writes +RGB565 pixels into `emuGfx::fb565[]`, the host expands them to 8888 and +presents via SDL3. ## License diff --git a/emulator-template/examples/Demo/Demo.cpp b/emulator-template/examples/Demo/Demo.cpp index 41d0ae6..74d25d0 100644 --- a/emulator-template/examples/Demo/Demo.cpp +++ b/emulator-template/examples/Demo/Demo.cpp @@ -1,10 +1,15 @@ /** * Demo sketch — replace this file with your own experiment. * + * This is the EMULATOR SHELL only. The actual demo lives in DemoCore.h + * (device-agnostic: RGB565 in panel wire order) so the same core can be + * driven by the firmware twin in fw/DemoHW.ino for hardware benchmarks. + * * 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) + * - the host provides emuGfx::fb565[] (320x240, RGB565 in panel wire + * order) — render into it, or hand your own buffer to the core * - set emuGfx::dirty = true each frame you want presented * - read keys from emu::keyboard (ASCII queue, filled from SDL events) * @@ -18,56 +23,37 @@ */ #include "shim.h" +#include "DemoCore.h" // Emulator state provided by the host (src/main.cpp) -extern uint32_t emuGfx::fb[320 * 240]; +extern uint16_t emuGfx::fb565[320 * 240]; extern bool emuGfx::dirty; extern std::deque emu::keyboard; -static constexpr int W = 320; -static constexpr int H = 240; - -// --- Demo state ----------------------------------------------------------- -static float boxX = 40, boxY = 30; -static float velX = 100.0f, velY = 70.0f; // pixels per second -static unsigned long lastMs = 0; -static constexpr float BOX = 24.0f; - void setup() { - randomSeed(millis()); - velX = 60.0f + random(100) * 1.2f; // 60..180 px/s - velY = 60.0f + random(100) * 1.2f; + demo::demoInit(emuGfx::fb565); } void loop() { + // Keyboard pump + while (!emu::keyboard.empty()) { + uint8_t k = emu::keyboard.front(); + emu::keyboard.pop_front(); + demo::demoInput(k); + } + // Delta time: seconds since the previous frame. + 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; // clamp after stalls (drag, breakpoint) - // Move and bounce - boxX += velX * dt; - boxY += velY * dt; - if (boxX < 0 || boxX + BOX > W) { velX = -velX; boxX += velX * dt; } - if (boxY < 0 || boxY + BOX > H) { velY = -velY; boxY += velY * dt; } + // Render one frame into the 565 buffer + demo::demoFrame(dt, now); - // 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 + // Present: the host expands 565 -> 8888 for the desktop window emuGfx::dirty = true; } diff --git a/emulator-template/examples/Demo/DemoCore.h b/emulator-template/examples/Demo/DemoCore.h new file mode 100644 index 0000000..6190b21 --- /dev/null +++ b/emulator-template/examples/Demo/DemoCore.h @@ -0,0 +1,94 @@ +/** + * DemoCore — the device-agnostic part of the bundled sample demo. + * + * This is the recommended structure for template sketches that will also + * run on real hardware: + * + * examples/$(APP)/$(APP)Core.h <- THIS FILE: all rendering + logic. + * Device-agnostic: no shim, no SDL, + * no Arduino. Renders RGB565 in + * panel wire order into a buffer the + * owner supplies. + * examples/$(APP)/$(APP).cpp <- thin emulator shell (keyboard, dt) + * fw/$(APP)HW.ino <- firmware twin (TFT_eSprite + fps report) + * + * Because the core is shared 1:1, whatever fps the hardware reports is + * the fps of exactly this code. + * + * COLOR CONTRACT: the buffer holds 16-bit RGB565 pixels in PANEL WIRE + * ORDER — big-endian, i.e. the byte sequence the ST7789 receives over + * SPI. On hardware the buffer IS the TFT_eSprite payload pushed raw. + * Store every pixel through wire565() or you will see byte-swapped + * colors on the panel while the emulator looks fine. + */ + +#pragma once + +#include +#include +#include + +namespace demo { + +static constexpr int W = 320; +static constexpr int H = 240; + +static uint16_t *g_fb = nullptr; + +// --- RGB565 helpers (also in shim.h for shell-side use) ---------------------- +static inline uint16_t rgb565(int r, int g, int b) { + return (uint16_t)(((r & 31) << 11) | ((g & 63) << 5) | (b & 31)); +} +// Panel wire order: the ST7789 receives the high byte first, and the +// sprite/push path sends buffer bytes raw — so store byteswapped values. +static inline uint16_t wire565(uint16_t c) { + return (uint16_t)((c << 8) | (c >> 8)); +} + +// --- Demo state -------------------------------------------------------------- +static float boxX = 40, boxY = 30; +static float velX = 100.0f, velY = 70.0f; // pixels per second +static constexpr float BOX = 24.0f; +static bool quitRequested = false; + +// --- Public API --------------------------------------------------------------- +static inline void demoInit(uint16_t *fb) { + g_fb = fb; + velX = 60.0f + (rand() % 100) * 1.2f; + velY = 60.0f + (rand() % 100) * 1.2f; +} + +static inline void demoInput(uint8_t k) { + if (k == 'q' || k == 0x1b) quitRequested = true; +} + +static inline bool demoQuitRequested() { return quitRequested; } + +static void demoFrame(float dt, unsigned long nowMs) { + // Move and bounce + boxX += velX * dt; + boxY += velY * dt; + if (boxX < 0 || boxX + BOX > W) { velX = -velX; boxX += velX * dt; } + if (boxY < 0 || boxY + BOX > H) { velY = -velY; boxY += velY * dt; } + + // Clear (dark 565 background, stored in wire order) + { + uint16_t bg = wire565(rgb565(2, 2, 6)); + for (int i = 0; i < W * H; i++) g_fb[i] = bg; + } + + // Draw a filled box with a color that drifts over time (5-bit quantized — + // the banding is what the real panel shows) + uint16_t color = rgb565((int)(16 + 15 * sinf(nowMs / 900.0f)) & 31, + 24, 12); + uint16_t wcolor = wire565(color); + 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; + g_fb[y * W + x] = wcolor; + } + } +} + +} // namespace demo diff --git a/emulator-template/fw/DemoHW.ino b/emulator-template/fw/DemoHW.ino new file mode 100644 index 0000000..e11a3e9 --- /dev/null +++ b/emulator-template/fw/DemoHW.ino @@ -0,0 +1,117 @@ +/** + * DemoHW — the template's bundled demo on the real T-Deck + * (ESP32-S3 + ST7789), with frame-time instrumentation. + * + * Firmware twin of the emulator sketch (../examples/Demo/Demo.cpp). + * Both drive the same device-agnostic DemoCore.h, which renders the + * whole scene in RGB565 (panel wire order) into a single 320x240 + * buffer. Here that buffer IS a TFT_eSprite's frameBuffer() — the core + * writes straight into the sprite, and the sprite is pushed with the + * proven NetDeck M1 anti-flicker pattern. + * + * Build & flash (from the repo root): + * pio run -d emulator-template/fw -t upload + * pio device monitor # 115200 baud + * + * The loop is deliberately free-running: the serial report every 2 s is + * the true throughput of the core + SPI push on this hardware. + */ + +#include +#include +#include +#include "utilities.h" +#include "DemoCore.h" + +TFT_eSPI tft; +static TFT_eSprite fb(&tft); // full-frame 320x240x16 buffer (PSRAM) + +// --- frame-time accounting --------------------------------------------------- +static uint32_t accRenderUs = 0; +static uint32_t accPushUs = 0; +static uint32_t accFrames = 0; +static uint32_t reportT0 = 0; + +void setup() +{ + Serial.begin(115200); + Serial.println(); + Serial.println("DemoHW — emulator-template demo on real T-Deck (RGB565)"); + Serial.println("Free-running benchmark: report every 2 s over USB serial."); + + // Proven T-Deck bring-up (same sequence as NetDeck.ino hardwareInit) + pinMode(BOARD_POWERON, OUTPUT); + digitalWrite(BOARD_POWERON, HIGH); + + pinMode(BOARD_SDCARD_CS, OUTPUT); + pinMode(RADIO_CS_PIN, OUTPUT); + pinMode(BOARD_TFT_CS, OUTPUT); + digitalWrite(BOARD_SDCARD_CS, HIGH); + digitalWrite(RADIO_CS_PIN, HIGH); + digitalWrite(BOARD_TFT_CS, HIGH); + + pinMode(BOARD_SPI_MISO, INPUT_PULLUP); + SPI.begin(BOARD_SPI_SCK, BOARD_SPI_MISO, BOARD_SPI_MOSI); + + tft.begin(); + tft.setRotation(1); // 320x240 landscape + tft.fillScreen(TFT_BLACK); + + pinMode(BOARD_BL_PIN, OUTPUT); + digitalWrite(BOARD_BL_PIN, HIGH); + + // Full-frame 16-bit sprite; the core draws directly into its buffer. + fb.setColorDepth(16); + if (!fb.createSprite(320, 240)) { + Serial.println("DemoHW: framebuffer alloc failed (stopping)"); + while (true) delay(1000); + } + uint16_t *buf = (uint16_t *)fb.frameBuffer(0); + if (!buf) { + Serial.println("DemoHW: frameBuffer() unavailable (stopping)"); + while (true) delay(1000); + } + demo::demoInit(buf); + + reportT0 = millis(); +} + +void loop() +{ + static uint32_t lastUs = 0; + uint32_t t0 = micros(); + + // Delta time from real elapsed time — motion speed stays correct no + // matter the achieved fps. + float dt = lastUs ? (t0 - lastUs) / 1e6f : 1.0f / 60.0f; + lastUs = t0; + if (dt > 0.1f) dt = 0.1f; + + demo::demoFrame(dt, millis()); + uint32_t renderUs = micros() - t0; + + // Panel push: the M1 anti-flicker pattern (NetDeck.ino present()). + uint32_t p0 = micros(); + tft.startWrite(); + fb.pushSprite(0, 0); + tft.endWrite(); + uint32_t pushUs = micros() - p0; + + // --- accounting --- + accRenderUs += renderUs; + accPushUs += pushUs; + accFrames++; + + uint32_t elapsed = millis() - reportT0; + if (elapsed >= 2000) { + float fps = accFrames * 1000.0f / elapsed; + float avgRender = accFrames ? accRenderUs / (float)accFrames / 1000.0f : 0.0f; + float avgPush = accFrames ? accPushUs / (float)accFrames / 1000.0f : 0.0f; + Serial.printf("DemoHW: %lu frames in %lu ms = %.1f fps | " + "render %.1f ms, push %.1f ms\n", + (unsigned long)accFrames, (unsigned long)elapsed, fps, + avgRender, avgPush); + reportT0 = millis(); + accRenderUs = accPushUs = accFrames = 0; + } +} diff --git a/emulator-template/fw/platformio.ini b/emulator-template/fw/platformio.ini new file mode 100644 index 0000000..53ab3d1 --- /dev/null +++ b/emulator-template/fw/platformio.ini @@ -0,0 +1,37 @@ +; PlatformIO project for running the template demo on the real T-Deck +; (ESP32-S3 + ST7789) as a free-running benchmark. +; +; Standalone on purpose (the repo's top-level platformio.ini keeps +; src_dir = src/netdeck for NetDeck): this points back at the shared +; boards/ and lib/ directories. +; +; pio run -d emulator-template/fw -t upload # flash the T-Deck +; pio device monitor # fps report every 2 s +; +; The loop free-runs (no pacing); the serial report's render/push split +; is the true throughput of the sketch core + SPI push on the hardware. + +[platformio] +default_envs = DemoHW +src_dir = . +boards_dir = ../../boards +lib_dir = ../../lib + +[env:DemoHW] +platform = espressif32@6.3.0 +board = T-Deck +framework = arduino +upload_speed = 921600 +monitor_speed = 115200 +build_flags = + -DBOARD_HAS_PSRAM=1 + -DCORE_DEBUG_LEVEL=1 + -DARDUINO_USB_CDC_ON_BOOT=1 + -DDISABLE_ALL_LIBRARY_WARNINGS + -DSPI_FREQUENCY=80000000 + ; -O2: PlatformIO's default -Os optimizes for size and can cost a + ; large fraction of frame time — benchmarks deserve the honest number. + -O2 + -I../examples/Demo + ; T-Deck pin map (BOARD_POWERON, TFT pins...) from the firmware tree + -I../../src/netdeck diff --git a/emulator-template/shim.h b/emulator-template/shim.h index a6542ab..084d080 100644 --- a/emulator-template/shim.h +++ b/emulator-template/shim.h @@ -77,6 +77,22 @@ inline uint32_t esp_random() return ((uint32_t)std::rand() << 17) ^ (uint32_t)std::rand() ^ millis(); } +// --------------------------------------------------------------------------- +// RGB565 helpers — the panel-facing color format of the T-Deck's ST7789. +// The emulator framebuffer contract is RGB565 in PANEL WIRE ORDER +// (big-endian): see README "The color contract". Use rgb565() to build +// colors and wire565() before storing a pixel into the framebuffer. +// --------------------------------------------------------------------------- +inline uint16_t rgb565(uint32_t r, uint32_t g, uint32_t b) +{ + return (uint16_t)(((r & 31) << 11) | ((g & 63) << 5) | (b & 31)); +} + +inline uint16_t wire565(uint16_t c) +{ + return (uint16_t)((c << 8) | (c >> 8)); +} + // --------------------------------------------------------------------------- // Minimal String class (Arduino-style) // --------------------------------------------------------------------------- diff --git a/emulator-template/src/main.cpp b/emulator-template/src/main.cpp index 27ba6a9..7781422 100644 --- a/emulator-template/src/main.cpp +++ b/emulator-template/src/main.cpp @@ -5,7 +5,18 @@ * 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. + * no I2S, no GPIO. It only depends on SDL3 and the shim. + * + * COLOR CONTRACT (matches the real T-Deck panel pipeline): the sketch + * renders into emuGfx::fb565 — a 320x240 buffer of 16-bit RGB565 pixels + * held in PANEL WIRE ORDER (big-endian: each pixel's high byte is what + * the ST7789 receives first over SPI; the same convention TFT_eSprite's + * own primitives use on hardware). The host expands 565 -> 8888 for the + * desktop window only. On the device the 565 buffer is pushed as-is, so + * anything you see here is exactly what the panel would show — including + * 5-bit color banding. Sketches that ignore this and write native + * little-endian values will render byte-swapped on hardware even though + * they look right in the emulator. */ #include @@ -24,7 +35,7 @@ #include "shim.h" // --- Emulator shared state (defined in main.cpp below) --- -// The sketch writes to emuGfx::fb; this file presents it each frame. +// The sketch writes to emuGfx::fb565; this file presents it each frame. // --------------------------------------------------------------------------- namespace emu { uint8_t pinLevels[64]; @@ -37,11 +48,26 @@ namespace emu { } // namespace emu namespace emuGfx { - uint32_t fb[320 * 240]; // ABGR8888 pixels, 320x240 + uint16_t fb565[320 * 240]; // RGB565, panel wire order — THE sketch target + uint32_t fb[320 * 240]; // ABGR8888 staging for SDL (host-internal) SDL_Texture *tex = nullptr; bool dirty = true; } // namespace emuGfx +// Expand the 565 wire-order buffer into the 8888 staging buffer. +// Wire order = big-endian 565: unswap, then replicate 5/6/5 -> 8/8/8 bits. +static void expand565() +{ + for (int i = 0; i < 320 * 240; i++) { + uint16_t c = (uint16_t)((emuGfx::fb565[i] << 8) | (emuGfx::fb565[i] >> 8)); + uint32_t r5 = (c >> 11) & 31, g6 = (c >> 5) & 63, b5 = c & 31; + uint32_t r = (r5 << 3) | (r5 >> 2); + uint32_t g = (g6 << 2) | (g6 >> 4); + uint32_t b = (b5 << 3) | (b5 >> 2); + emuGfx::fb[i] = 0xFF000000u | (b << 16) | (g << 8) | r; + } +} + // --- Forward declarations of the user's sketch functions --- // These will be defined in the sketch .cpp file included below. extern "C" void setup(); @@ -56,6 +82,22 @@ extern "C" void loop(); #include APP_SRC // --------------------------------------------------------------------------- +// Save the current frame (after 565 expansion) as a BMP. +static void dumpFrame(const char *path) +{ + if (!path) return; + expand565(); + SDL_Surface *s = SDL_CreateSurface(320, 240, SDL_PIXELFORMAT_ABGR8888); + if (!s) return; + 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_SaveBMP(s, path); + SDL_DestroySurface(s); + std::printf("[emu] frame dumped to %s\n", path); +} + // --- Main entry point --- int main(int argc, char **argv) { @@ -155,6 +197,7 @@ int main(int argc, char **argv) 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); + dumpFrame(dumpPath); running = false; break; } @@ -164,8 +207,9 @@ int main(int argc, char **argv) // --- Present frame if dirty --- if (emuGfx::dirty) { + expand565(); SDL_UpdateTexture(emuGfx::tex, nullptr, emuGfx::fb, - 320 * sizeof(uint32_t)); + 320 * sizeof(uint32_t)); emuGfx::dirty = false; } @@ -177,26 +221,7 @@ int main(int argc, char **argv) // --- 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); - } - } + dumpFrame(dumpPath); } // --- Frame pacing: sleep until the next 60 Hz tick --- @@ -213,22 +238,7 @@ int main(int argc, char **argv) } // --- 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"); - } - } + dumpFrame("frame.bmp"); // --- Cleanup --- TTF_Quit(); @@ -237,4 +247,4 @@ int main(int argc, char **argv) SDL_DestroyWindow(win); SDL_Quit(); return 0; -} \ No newline at end of file +}