Files
lilygo-t-deck/emulator/src/main.cpp
T
Dejvino 1dcc87d8d4 Fix trackball click: I2S MCLK was claiming GPIO0; emulator pin-ownership parity
Root cause (on device): sound_engine zero-initialized i2s_pin_config_t,
leaving mck_io_num == 0. i2s_set_pin() then claimed GPIO0 — an
MCLK-capable pin on the S3 and the trackball centre / BOOT line — as
its MCLK output. Verified on device with a diagnostic build: pin0 read
LOW at idle, exactly one latched FALLING edge, clicks never registered.

- sound_engine: set pins.mck_io_num = I2S_PIN_NO_CHANGE explicitly.
- NetDeck: register the trackball click on release with contact-bounce
  collapse (the proven CrtTerminal pattern); pollTouch re-arms when
  isPressed() stays true but getPoint() reports no points (stuck GT911
  IRQ on some units).
- Emulator parity (so this class of bug dies before flashing):
  GPIO-matrix pin-ownership model in the shim — i2s_set_pin() claims
  its pins, claimed pins are dead inputs (digitalRead LOW, no edges,
  loud WARNING on claim/ISR collisions); host pin writes go through
  emu::setPin/togglePin with an edge-accurate ISR latch (a full
  press+release pulse between dispatches no longer gets swallowed);
  E2E inits SDL_INIT_AUDIO so the I2S path actually runs there.
  Regression coverage: e2e/trackball_click (fails on the old engine),
  unit/shim_claimed_pin_is_dead_input,
  unit/shim_edge_survives_same_dispatch_pulse.
- Makefile: firmware step follows the sketch move (root platformio.ini,
  src_dir = src/netdeck).
- HW.md: new notes file for emulator-vs-hardware quirks and the
  on-device debugging recipe.

On-device verified: clicks register in both views (beacon drops, node
routing). Fast layer 23 unit + 7 integration green. Note: e2e
boot_and_controls + network_journey failures are pre-existing at HEAD
(reproduced on a clean stash before this change).
2026-11-15 10:24:30 +01:00

387 lines
15 KiB
C++

/**
* SDL3 host for T-Deck example sketches — run the app on your PC.
* The sketch is selected with -DAPP_INO (see the Makefile, APP=...).
*
* Input mapping:
* Arrow keys trackball roll (hold to keep rolling)
* Mouse wheel trackball roll (each notch = a ball pulse burst)
* Enter / right-click trackball press
* Left-click screen tap
* Letters/digits keyboard device @ I2C 0x55
* Backspace/Delete keyboard device (0x08 / 0x7F)
* --type "text" queue keys programmatically (for smoke tests)
*/
#include <SDL3/SDL.h>
#if __has_include(<SDL3/SDL_ttf.h>) // upstream install layout
#include <SDL3/SDL_ttf.h>
#else // Debian/Ubuntu package layout
#include <SDL3_ttf/SDL_ttf.h>
#endif
#include <cstdio>
#include <cctype>
#include <cstring>
#include "emu_gfx.h"
#include "emu_input.h"
#ifndef APP_INO
#define APP_INO "MissileCommand.ino"
#endif
// emulator-side autoplay request (consumed by sketches that support it)
bool emuAutoplay = false;
#ifndef APP_NAME
#define APP_NAME "T-Deck app"
#endif
// pull in the whole sketch as a single translation unit
#include APP_INO
// ---------------------------------------------------------------------------
// Global instances declared extern in the shims
// ---------------------------------------------------------------------------
namespace emu {
uint8_t pinLevels[64];
const char *pinDrivenBy[64];
std::deque<PinEdge> pinEdges;
bool touchDown = false;
int touchX = 0, touchY = 0;
std::deque<uint8_t> keyboard;
bool quitRequested = false;
} // namespace emu
namespace emuGfx {
uint32_t fb[W * H];
SDL_Texture *tex = nullptr;
bool dirty = true;
} // namespace emuGfx
SerialSim Serial;
TwoWire Wire;
SPIClass SPI;
const FreeFontStub FreeSansBold24pt7b {0};
const FreeFontStub FreeSansBold18pt7b {0};
const FreeFontStub FreeSansOblique12pt7b {0};
const FreeFontStub FreeSans12pt7b {0};
static void saveBmp(const char *path)
{
SDL_Surface *s = SDL_CreateSurfaceFrom(
emuGfx::W, emuGfx::H, SDL_PIXELFORMAT_ABGR8888,
emuGfx::fb, emuGfx::W * 4);
if (s) {
SDL_IOStream *dst = SDL_IOFromFile(path, "wb");
if (dst) {
SDL_SaveBMP_IO(s, dst, true); // true = close the stream for us
std::printf("[emu] frame dumped to %s\n", path);
}
SDL_DestroySurface(s);
}
}
int main(int argc, char **argv)
{
long maxFrames = -1;
const char *dumpPath = nullptr;
int typeFromFrame = 30;
int dumpEvery = 0;
// scheduled screen taps: --tap "x,y[@frame]" (repeatable)
struct Tap { int x, y, at, hold; bool fired; };
static Tap taps[32];
int nTaps = 0;
// scheduled typing: --type "text[@frame]" (repeatable, chars ~40 ms apart)
struct TypeEvt { const char *s; int at; };
static TypeEvt typeEvts[16];
int nType = 0;
#ifdef EMU_APP_MISSILECOMMAND
bool autoplay = false;
#endif
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], "--dump-interval") && i + 1 < argc) dumpEvery = atoi(argv[++i]);
else if (!strcmp(argv[i], "--type") && i + 1 < argc && nType < 16) {
// "text[@frame]": queue another typing event (chars ~40 ms apart)
const char *s = argv[++i];
int at = typeFromFrame; // legacy default via --type-at
const char *atp = strchr(s, '@');
char *copy = strdup(s);
if (atp) {
at = atoi(atp + 1);
copy[atp - s] = '\0';
}
typeEvts[nType++] = { copy, at };
}
else if (!strcmp(argv[i], "--type-at") && i + 1 < argc) typeFromFrame = atoi(argv[++i]);
else if (!strcmp(argv[i], "--tap") && i + 1 < argc && nTaps < 32) {
Tap &t = taps[nTaps++];
t.x = t.y = t.at = 0; t.hold = 0; t.fired = false;
const char *s = argv[++i];
sscanf(s, "%d,%d@%d", &t.x, &t.y, &t.at);
if (t.at <= 0) t.at = 30; // "@frame" part optional
t.hold = t.at + 120; // hold long enough that a frame-paced
// pollTick (~34 ms apart) sees it
}
else if (!strcmp(argv[i], "--autoplay")) { emuAutoplay = true; }
#ifdef EMU_APP_MISSILECOMMAND
else if (!strcmp(argv[i], "--wave") && i + 1 < argc) emuStartWaveRequest = atoi(argv[++i]);
else if (!strcmp(argv[i], "--autoplay")) autoplay = true;
#endif
}
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) {
std::printf("SDL_Init failed: %s\n", SDL_GetError());
return 1;
}
TTF_Init();
SDL_Window *win = SDL_CreateWindow("T-Deck emulator — " APP_NAME,
960, 720, SDL_WINDOW_RESIZABLE);
SDL_Renderer *ren = SDL_CreateRenderer(win, NULL);
if (!ren) ren = SDL_CreateRenderer(win, "software"); // fallback (headless)
SDL_SetRenderLogicalPresentation(ren, emuGfx::W, emuGfx::H,
SDL_LOGICAL_PRESENTATION_LETTERBOX);
emuGfx::tex = SDL_CreateTexture(ren, SDL_PIXELFORMAT_ABGR8888,
SDL_TEXTUREACCESS_STREAMING, emuGfx::W, emuGfx::H);
for (auto &p : emu::pinLevels) p = 1; // everything pulled up
setup();
const uint8_t dirPin[4] = { BOARD_TBOX_G02, BOARD_TBOX_G01, BOARD_TBOX_G04, BOARD_TBOX_G03 };
bool held[4] = { false, false, false, false };
// mouse wheel -> simulated ball pulses: pending pin toggles per direction
int wheelPulse[4] = { 0, 0, 0, 0 };
uint32_t frame = 0;
bool running = true;
while (running && !emu::quitRequested) {
SDL_Event e;
while (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_EVENT_QUIT:
running = false;
break;
case SDL_EVENT_KEY_DOWN: {
if (e.key.repeat) break;
SDL_Keycode k = e.key.key;
switch (k) {
case SDLK_RIGHT: held[0] = true; emu::setPin(dirPin[0], 0); break;
case SDLK_UP: held[1] = true; emu::setPin(dirPin[1], 0); break;
case SDLK_LEFT: held[2] = true; emu::setPin(dirPin[2], 0); break;
case SDLK_DOWN: held[3] = true; emu::setPin(dirPin[3], 0); break;
case SDLK_RETURN:
case SDLK_KP_ENTER:
emu::setPin(BOARD_BOOT_PIN, 0); // trackball press
break;
case SDLK_SPACE:
emu::keyboard.push_back(' ');
break;
case SDLK_TAB:
emu::keyboard.push_back('\t');
break;
case SDLK_BACKSPACE:
emu::keyboard.push_back(0x08);
break;
case SDLK_DELETE:
emu::keyboard.push_back(0x7F);
break;
case SDLK_ESCAPE:
running = false;
break;
default: {
const char *name = SDL_GetKeyName(k);
if (name && strlen(name) == 1) {
emu::keyboard.push_back((uint8_t)tolower((unsigned char)name[0]));
}
break;
}
}
break;
}
case SDL_EVENT_KEY_UP: {
SDL_Keycode k = e.key.key;
switch (k) {
case SDLK_RIGHT: held[0] = false; emu::setPin(dirPin[0], 1); break;
case SDLK_UP: held[1] = false; emu::setPin(dirPin[1], 1); break;
case SDLK_LEFT: held[2] = false; emu::setPin(dirPin[2], 1); break;
case SDLK_DOWN: held[3] = false; emu::setPin(dirPin[3], 1); break;
case SDLK_RETURN:
case SDLK_KP_ENTER:
emu::setPin(BOARD_BOOT_PIN, 1);
break;
default: break;
}
break;
}
case SDL_EVENT_MOUSE_WHEEL: {
// Each wheel notch = a burst of ball edges on the matching
// direction pin (emitted over the next few iterations).
const int perNotch = 6;
if (e.wheel.y > 0) wheelPulse[1] += perNotch * (int)e.wheel.y; // up
if (e.wheel.y < 0) wheelPulse[3] += perNotch * (int)-e.wheel.y; // down
if (e.wheel.x > 0) wheelPulse[0] += perNotch * (int)e.wheel.x; // right
if (e.wheel.x < 0) wheelPulse[2] += perNotch * (int)-e.wheel.x; // left
break;
}
case SDL_EVENT_MOUSE_BUTTON_DOWN:
case SDL_EVENT_MOUSE_BUTTON_UP: {
// SDL3 converts window-relative event coords into the
// renderer's logical (320x240) space, handling HiDPI and
// the letterboxed viewport officially.
SDL_ConvertEventToRenderCoordinates(ren, &e);
// Caveat kept from the SDL2 era (commit 260a2b3): under
// Xwayland the X server may deliver pointer event coords in
// a scaled space (observed: exactly half the true position),
// so cross-check against the cursor position reconstructed
// from the global state minus the window position (raw root
// coords on X11, unaffected by event scaling) and prefer it
// when it lands inside the window.
int ww, wh;
SDL_GetWindowSize(win, &ww, &wh);
if (ww > 0 && wh > 0) {
float gx, gy;
int wpx, wpy;
Uint32 gbtn = SDL_GetGlobalMouseState(&gx, &gy);
SDL_GetWindowPosition(win, &wpx, &wpy);
int relX = (int)(gx - wpx), relY = (int)(gy - wpy);
if (gbtn && relX >= 0 && relX < ww && relY >= 0 && relY < wh) {
float lx, ly;
if (SDL_RenderCoordinatesFromWindow(ren, (float)relX, (float)relY, &lx, &ly)) {
e.button.x = lx;
e.button.y = ly;
}
}
}
int wx = (int)e.button.x, wy = (int)e.button.y;
if (wx < 0) wx = 0;
if (wx > emuGfx::W - 1) wx = emuGfx::W - 1;
if (wy < 0) wy = 0;
if (wy > emuGfx::H - 1) wy = emuGfx::H - 1;
if (e.button.button == SDL_BUTTON_LEFT) {
bool down = (e.type == SDL_EVENT_MOUSE_BUTTON_DOWN);
emu::touchDown = down;
emu::touchX = wx;
emu::touchY = wy;
} else if (e.button.button == SDL_BUTTON_RIGHT) {
emu::setPin(BOARD_BOOT_PIN,
(e.type == SDL_EVENT_MOUSE_BUTTON_DOWN) ? 0 : 1);
}
break;
}
}
}
// Simulate a rolling trackball: toggle the held quadrant pin so the
// game keeps seeing edges while the arrow key is down, and drain the
// mouse-wheel pulse queues (one toggle per iteration = one ball edge).
for (int d = 0; d < 4; d++) {
if (wheelPulse[d] > 0) {
emu::togglePin(dirPin[d]);
wheelPulse[d]--;
}
}
if (++frame % 3 == 0) {
for (int d = 0; d < 4; d++) {
if (held[d]) emu::togglePin(dirPin[d]);
}
}
// --type: queue the strings on the keyboard device like a human typing
// (chars ~40 ms apart in millis time, so the sketch processes each key
// before the next arrives; each event starts at its "@frame").
// '\n' emulates Enter: press the trackball pin for one iteration.
static const char *typeNext = nullptr;
static int typePressPin = -1;
static unsigned long lastTypeMs = 0;
static int curType = 0;
if (curType < nType) {
const TypeEvt &te = typeEvts[curType];
if (frame >= (uint32_t)te.at) {
if (typePressPin >= 0) {
emu::setPin(typePressPin, 1); // release the Enter press
typePressPin = -1;
}
const char *typeEnd = te.s + strlen(te.s);
if (!typeNext) { typeNext = te.s; lastTypeMs = 0; }
if (typeNext >= typeEnd) {
curType++; // event finished
typeNext = nullptr;
} else if (millis() - lastTypeMs >= 40) {
lastTypeMs = millis();
if (*typeNext == '\n' || *typeNext == '\r') {
typeNext++; // consume the Enter char
emu::setPin(BOARD_BOOT_PIN, 0);
typePressPin = BOARD_BOOT_PIN;
} else {
emu::keyboard.push_back((uint8_t)*typeNext++);
}
}
}
}
// Headless test mode: start the game, wander the crosshair, keep firing.
#ifdef EMU_APP_MISSILECOMMAND
if (autoplay) {
static bool started = false;
if (!started && frame >= 5) {
emu::keyboard.push_back('a');
started = true;
}
static int dir = 0;
if (frame % 45 == 0) dir = (dir + 1) & 3;
if (frame % 4 == 0) emu::togglePin(dirPin[dir]);
if (frame % 75 == 0) emu::keyboard.push_back('s');
}
#endif
// --tap: scheduled screen taps (left-button touch at x,y from frame N,
// held ~40 iterations so the sketch's frame-paced poll sees it)
for (int i = 0; i < nTaps; i++) {
Tap &t = taps[i];
if (!t.fired && frame >= (uint32_t)t.at) {
emu::touchX = t.x;
emu::touchY = t.y;
emu::touchDown = true;
t.fired = true;
std::printf("[emu] tap %d,%d at frame %u\n", t.x, t.y, frame);
} else if (t.fired && frame >= (uint32_t)t.hold) {
emu::touchDown = false;
t.hold = -1; // released; don't re-release
}
}
// fire any emulated interrupts triggered by the pin changes above
emu::dispatchIsrs();
loop();
if (emuGfx::dirty) {
SDL_UpdateTexture(emuGfx::tex, nullptr, emuGfx::fb,
emuGfx::W * sizeof(uint32_t));
emuGfx::dirty = false;
}
SDL_RenderClear(ren);
SDL_RenderTexture(ren, emuGfx::tex, nullptr, nullptr);
SDL_RenderPresent(ren);
if (maxFrames > 0 && --maxFrames == 0) {
running = false;
if (dumpPath) saveBmp(dumpPath);
} else if (dumpEvery > 0 && frame % dumpEvery == 0) {
char path[256];
snprintf(path, sizeof(path), "seq%05d.bmp", frame / dumpEvery);
saveBmp(path);
}
}
TTF_Quit();
SDL_Quit();
return 0;
}