Robot: play the window program from a script, for regression tests

A test hook for src/app/main.cpp, which the headless tools bypass. With
OPENBMH_ROBOT=<script> and OPENBMH_ROBOT_LOG=<file> (usually with the SDL
dummy video and audio drivers) the game reads clicks and keys from the script
instead of the mouse, waits after each command until the picture has settled
and writes its fingerprint; OPENBMH_ROBOT_SHOTS=<dir> also saves the pictures.
The events go through SDL's queue, so they take the path of real input.

Hooks: app::present() replaces the 31 SDL_RenderPresent calls of main.cpp,
QuitConfirmation::poll() lets the robot queue its next command when no input
is waiting, and a robot run answers the quit question itself. Without the
environment variables nothing changes.

Verified: a script of 234 commands (title, new career, season start
presentations, every desk icon, two matchdays with the live match) gives the
same file in three runs; 211 of 211 tests; careers and UI walk identical.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude committed 2026-11-10 15:36:08 +01:00
1 parent b7f748688c
commit ff32ef1dbc
3 files changed
+300 -32

No files matched your search

+36 -32
View File
@@ -296,7 +296,11 @@ int main(int argc, char** argv) {
pitch_pointer.set_default(bitmap);
pitch_pointer.show({}, renderer);
}
app::QuitConfirmation quit_confirmation(window, english_game);
// A robot run (app/robot.hpp: OPENBMH_ROBOT, a test hook) plays a script and answers the quit question itself.
app::Robot::instance().start(window);
app::QuitConfirmation quit_confirmation(window, english_game,
app::Robot::instance().active() ? app::QuitConfirmation::Presenter(app::Robot::confirm_quit)
: app::QuitConfirmation::Presenter(SDL_ShowMessageBox));
try {
if (!playback.initialize_original(app::original_audio_assets(data, season_exe), audio_error))
std::fprintf(stderr, "audio: %s\n", audio_error.c_str());
@@ -349,7 +353,7 @@ int main(int argc, char** argv) {
if (present) {
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer,texture,nullptr,nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
}
}
return sample && sample->expired;
@@ -419,7 +423,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
};
// Plays the highscore point animation of the desk, one rendered frame per step, if active.
const auto present_desk_record_points = [&] {
@@ -1549,7 +1553,7 @@ int main(int argc, char** argv) {
if(SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4)!=0 ||
SDL_RenderClear(renderer)!=0 || SDL_RenderCopy(renderer,texture,nullptr,nullptr)!=0)
throw FormatError(std::string("poach renderer: ")+SDL_GetError());
SDL_RenderPresent(renderer);
app::present(renderer);
};
std::unique_ptr<ui::LeagueTableScreen> table;
// Rebuilds the league table screen from the current engine page.
@@ -2049,7 +2053,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
SDL_Event modal;
bool redrawn = false;
while (quit_confirmation.poll(&modal)) {
@@ -2206,7 +2210,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
if (pairings_screen)
pairings_screen->mark_presented_source_seconds(overview_source_seconds());
};
@@ -2233,7 +2237,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
outcome = dialog.after_present();
clock_anchor = SDL_GetTicks();
};
@@ -2435,7 +2439,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
live_frame_shown = true;
}
}
@@ -2470,7 +2474,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
offer_dirty = false;
}
SDL_Event event;
@@ -2544,7 +2548,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
rendered_phase = phase;
}
SDL_Event event;
@@ -2583,7 +2587,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
bool dismissed = false;
while (running && !dismissed) {
SDL_Event event;
@@ -2765,7 +2769,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
SDL_Event modal;
bool redrawn = false;
while (quit_confirmation.poll(&modal)) {
@@ -2833,7 +2837,7 @@ int main(int argc, char** argv) {
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_SetWindowTitle(window, "OpenBMH - live_paused");
SDL_RenderPresent(renderer);
app::present(renderer);
bool resumed = false;
while (running && !resumed) {
@@ -2863,7 +2867,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
};
// Opens the overview selected by key_slot through the session and runs it via
// present_running_overview. The sequence counter numbers the overviews opened in this
@@ -2934,7 +2938,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
};
render_settings();
// Modal save/load screen for settings files opened from the settings screen; the result is
@@ -2958,7 +2962,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
};
render_file();
// Give the filename field the native text input focus.
@@ -3270,7 +3274,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
};
const int count = ui::LiveMatchdayScreen::ball_frame_count(event.displacement);
// Converts the saved pause number at the given row into milliseconds.
@@ -3330,7 +3334,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
SDL_PumpEvents();
SDL_Event quit_event;
if (quit_confirmation.peep(&quit_event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
@@ -3365,7 +3369,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
SDL_PumpEvents();
SDL_Event input;
if (quit_confirmation.peep(&input, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
@@ -3424,7 +3428,7 @@ int main(int argc, char** argv) {
SDL_SetWindowTitle(window,title.c_str());
for (size_t i=0;i<pixels.size();++i) pixels[i]=colors.argb[images[index].pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);app::present(renderer);
SDL_PumpEvents();SDL_Event input;
if (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
// FirstThen holds the first frame for 40 retraces; later frames
@@ -3447,7 +3451,7 @@ int main(int argc, char** argv) {
const auto present=[&](const Image& image) {
for (size_t i=0;i<pixels.size();++i) pixels[i]=palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);app::present(renderer);
};
SDL_SetWindowTitle(window,title.c_str());present(live_screen.render_booking(frame,booking));
if (event.kind != 2 && app::match_sound_enabled(state))
@@ -3477,7 +3481,7 @@ int main(int argc, char** argv) {
const auto image=live_screen.render_shootout(frame,projection);
for (size_t i=0;i<pixels.size();++i) pixels[i]=palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);app::present(renderer);
SDL_PumpEvents();SDL_Event input;
if (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
const int repeats=event.stage==LiveShootoutStage::preview?4:2;
@@ -3495,7 +3499,7 @@ int main(int argc, char** argv) {
SDL_SetWindowTitle(window,title.c_str());
for (size_t i=0;i<pixels.size();++i) pixels[i]=colors.argb[image.pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);app::present(renderer);
};
const auto delay = [&](uint32_t address) {
const int saved=state.memory.has(address)?state.memory.u8(address):0;
@@ -3615,7 +3619,7 @@ int main(int argc, char** argv) {
if (SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4) != 0 ||
SDL_RenderClear(renderer) != 0 || SDL_RenderCopy(renderer, texture, nullptr, nullptr) != 0)
throw std::runtime_error(std::string("Formation save renderer: ") + SDL_GetError());
SDL_RenderPresent(renderer);
app::present(renderer);
if (!restored) SDL_Delay(ui::PitchScreen::formation_save_flash_ms);
}
};
@@ -3672,7 +3676,7 @@ int main(int argc, char** argv) {
if (SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4) != 0 ||
SDL_RenderClear(renderer) != 0 || SDL_RenderCopy(renderer, texture, nullptr, nullptr) != 0)
throw std::runtime_error(std::string("Table renderer: ") + SDL_GetError());
SDL_RenderPresent(renderer);
app::present(renderer);
dirty = false;
mark_family_table_presented();
};
@@ -3746,7 +3750,7 @@ int main(int argc, char** argv) {
const auto image=process_timer_image(flow.render());
for(size_t i=0;i<pixels.size();++i)pixels[i]=palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);app::present(renderer);
flow.mark_balance_presented_source_milliseconds(balance_source_milliseconds());
presented_balance=identity;presented_balance_notice=notice;dirty=false;
};
@@ -3869,7 +3873,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
flow.mark_league_pairings_presented_source_seconds(pairings_source_seconds());
presented_pairings = identity;
dirty = false;
@@ -4200,7 +4204,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
dirty = false;
if (flow.in_pitch()) SDL_Delay(90);
}
@@ -4224,7 +4228,7 @@ int main(int argc, char** argv) {
if (SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4)!=0 ||
SDL_RenderClear(renderer)!=0 || SDL_RenderCopy(renderer,texture,nullptr,nullptr)!=0)
throw std::runtime_error(std::string("Held controls renderer: ")+SDL_GetError());
SDL_RenderPresent(renderer);
app::present(renderer);
mark_stadium_question_presented();
mark_national_picker_presented();
mark_friendly_picker_presented();
@@ -4241,7 +4245,7 @@ int main(int argc, char** argv) {
for(size_t i=0;i<pixels.size();++i)pixels[i]=palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
dirty=false;
}
}
@@ -4254,7 +4258,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
app::present(renderer);
dirty = false;
}
// Mouse release. Order: an expired question that owns this release, then right-button
@@ -4412,7 +4416,7 @@ int main(int argc, char** argv) {
const int copied = SDL_RenderCopy(renderer, texture, nullptr, nullptr);
if (source_modal_redraw && (cleared != 0 || copied != 0))
throw std::runtime_error(std::string("Source modal renderer: ") + SDL_GetError());
SDL_RenderPresent(renderer);
app::present(renderer);
if(flow.timed_notice_open()&&!timed_notice_presented_at)
timed_notice_presented_at=SDL_GetTicks64();
if (stadium_redraw) mark_stadium_question_presented();
+11
View File
@@ -10,6 +10,8 @@
#include <functional>
#include <utility>
#include "app/robot.hpp"
namespace bmh::app {
// OpenBMH deviates from the original: confirms application exit with a localized native dialog, with cancellation selected by default.
@@ -47,6 +49,15 @@ public:
while (SDL_PollEvent(event)) {
if (event->type != SDL_QUIT || confirm()) return 1;
}
// No input waiting: a robot run (app/robot.hpp, inactive in normal play) may queue the
// events of its next script command now.
Robot& robot = Robot::instance();
if (robot.active()) {
robot.idle();
while (SDL_PollEvent(event)) {
if (event->type != SDL_QUIT || confirm()) return 1;
}
}
return 0;
}
+253
View File
@@ -0,0 +1,253 @@
// SPDX-License-Identifier: GPL-3.0-only
// The robot: a test hook that plays the real game program from an input script, without a person.
//
// Purpose. The window program (src/app/main.cpp) owns the SDL loop, the modal presentation loops
// and the timers; the headless tools (ui_walk, season_sim) bypass all of that. The robot covers it:
// started with
//
// OPENBMH_ROBOT=<script file> OPENBMH_ROBOT_LOG=<output file>
//
// (usually together with SDL_VIDEODRIVER=dummy and SDL_AUDIODRIVER=dummy, so that no window and no
// sound device are needed), the program reads the script instead of waiting for the mouse. After
// every command the robot waits until the picture has stopped changing and writes one line
//
// <number> <command> -> <fingerprint of the settled picture> [unsettled]
//
// A refactoring of the window program must reproduce that file. Without the two environment
// variables the robot is inactive and costs one branch per frame and per empty event poll.
//
// How it hooks in (both hooks are called on the UI thread only):
// - present(renderer) replaces SDL_RenderPresent in main.cpp: the robot reads the rendered
// picture back and remembers its fingerprint;
// - QuitConfirmation::poll calls idle() when SDL has no event: once the picture is settled the
// robot pushes the events of the next command into SDL's queue (so they take exactly the path
// of real input, including SDL's conversion to the 320x240 logical coordinates).
//
// Script: one command per line, '#' starts a comment. Coordinates are the game's 320x240 units.
// left X Y | right X Y a click (press, 120 ms, release)
// key NAME RETURN, ESCAPE, BACKSPACE, SPACE or one letter/digit
// text T typed text
// wait MS nothing for MS milliseconds (then the settled picture is logged)
// quit closes the program (the quit question is answered with yes)
// OPENBMH_ROBOT_SHOTS=<directory> additionally saves the settled picture of every command as a BMP.
// The time a command may take to settle is limited (OPENBMH_ROBOT_TIMEOUT_MS, default 15000); a
// screen that keeps animating is logged as "unsettled" with the picture shown at that moment.
#pragma once
#include <SDL.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
namespace bmh::app {
class Robot {
public:
static Robot& instance() {
static Robot robot;
return robot;
}
bool active() const { return active_; }
// Reads the environment; called once the window exists.
void start(SDL_Window* window) {
const char* script = std::getenv("OPENBMH_ROBOT");
const char* log = std::getenv("OPENBMH_ROBOT_LOG");
if (!script || !log) return;
std::ifstream in(script);
if (!in) { std::fprintf(stderr, "robot: cannot read %s\n", script); return; }
std::string line;
while (std::getline(in, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
const auto first = line.find_first_not_of(" \t");
if (first == std::string::npos || line[first] == '#') continue;
commands_.push_back(line.substr(first));
}
log_ = std::fopen(log, "wb");
if (!log_) { std::fprintf(stderr, "robot: cannot write %s\n", log); return; }
if (const char* settle = std::getenv("OPENBMH_ROBOT_SETTLE_MS")) settle_ms_ = Uint32(std::atoi(settle));
if (const char* timeout = std::getenv("OPENBMH_ROBOT_TIMEOUT_MS")) timeout_ms_ = Uint32(std::atoi(timeout));
if (const char* shots = std::getenv("OPENBMH_ROBOT_SHOTS")) shots_ = shots;
window_ = window;
active_ = true;
last_change_ = command_time_ = SDL_GetTicks();
}
// A picture is about to be shown: fingerprint it (FNV-1a over the rendered ARGB pixels).
void frame(SDL_Renderer* renderer) {
if (!active_) return;
int w = 0, h = 0;
if (SDL_GetRendererOutputSize(renderer, &w, &h) != 0 || w <= 0 || h <= 0) return;
pixels_.resize(size_t(w) * size_t(h) * 4);
width_ = w, height_ = h;
if (SDL_RenderReadPixels(renderer, nullptr, SDL_PIXELFORMAT_ARGB8888, pixels_.data(), w * 4) != 0) return;
uint64_t hash = 0xcbf29ce484222325ull;
for (uint8_t byte : pixels_) hash = (hash ^ byte) * 0x100000001b3ull;
if (hash != picture_) {
picture_ = hash;
++pictures_;
last_change_ = SDL_GetTicks();
}
}
// SDL has no event: issue the release of a click, or the next command once the picture is settled.
void idle() {
if (!active_) return;
const Uint32 now = SDL_GetTicks();
if (release_pending_) {
if (now - command_time_ < 120) return;
push_button(SDL_MOUSEBUTTONUP, release_button_);
release_pending_ = false;
last_change_ = now; // (the release may change the picture: settle again from here)
return;
}
if (now < wait_until_) return;
const bool settled = now - last_change_ >= settle_ms_ && now - command_time_ >= settle_ms_;
const bool timed_out = now - command_time_ >= timeout_ms_;
if (!settled && !timed_out) return;
// the previous command is done: log it with the picture now on screen
if (issued_ > 0 && !logged_) {
// (the number of pictures in between depends on the clock and is not written)
// A picture that was still changing at the time limit (a running live match, an animation) depends
// on the clock: only the fact is written, not its fingerprint.
if (settled) std::fprintf(log_, "%zu %s -> %016llx\n", issued_, commands_[issued_ - 1].c_str(), static_cast<unsigned long long>(picture_));
else std::fprintf(log_, "%zu %s -> unsettled\n", issued_, commands_[issued_ - 1].c_str());
std::fflush(log_);
save_shot();
logged_ = true;
}
if (issued_ >= commands_.size()) {
if (!finished_) { finished_ = true; std::fclose(log_); log_ = nullptr; }
return;
}
issue(commands_[issued_++]);
logged_ = false;
pictures_ = 0;
command_time_ = last_change_ = SDL_GetTicks();
}
// The quit question of a robot run is answered with "quit".
static int confirm_quit(const SDL_MessageBoxData*, int* selected) {
if (selected) *selected = 1;
return 0;
}
private:
// OPENBMH_ROBOT_SHOTS=<directory>: the settled picture of every command as <number>.bmp (for
// writing scripts and for looking at a run; not needed for the comparison).
void save_shot() {
if (shots_.empty() || pixels_.empty()) return;
SDL_Surface* surface = SDL_CreateRGBSurfaceWithFormatFrom(pixels_.data(), width_, height_, 32, width_ * 4,
SDL_PIXELFORMAT_ARGB8888);
if (!surface) return;
char name[32];
std::snprintf(name, sizeof name, "/%04zu.bmp", issued_);
SDL_SaveBMP(surface, (shots_ + name).c_str());
SDL_FreeSurface(surface);
}
void push_button(Uint32 type, Uint8 button) {
SDL_Event e{};
e.type = type;
e.button.windowID = SDL_GetWindowID(window_);
e.button.button = button;
e.button.state = type == SDL_MOUSEBUTTONDOWN ? SDL_PRESSED : SDL_RELEASED;
e.button.clicks = 1;
e.button.x = window_x_;
e.button.y = window_y_;
SDL_PushEvent(&e);
}
void push_motion() {
SDL_Event e{};
e.type = SDL_MOUSEMOTION;
e.motion.windowID = SDL_GetWindowID(window_);
e.motion.x = window_x_;
e.motion.y = window_y_;
SDL_PushEvent(&e);
}
void push_key(SDL_Keycode key) {
for (const Uint32 type : {Uint32(SDL_KEYDOWN), Uint32(SDL_KEYUP)}) {
SDL_Event e{};
e.type = type;
e.key.windowID = SDL_GetWindowID(window_);
e.key.state = type == SDL_KEYDOWN ? SDL_PRESSED : SDL_RELEASED;
e.key.keysym.sym = key;
e.key.keysym.scancode = SDL_GetScancodeFromKey(key);
SDL_PushEvent(&e);
}
}
void issue(const std::string& command) {
std::istringstream row(command);
std::string name;
row >> name;
if (name == "left" || name == "right") {
int x = 0, y = 0;
row >> x >> y;
// the middle of the logical pixel in window coordinates (SDL converts back)
int w = 960, h = 720;
SDL_GetWindowSize(window_, &w, &h);
window_x_ = x * w / 320 + w / 640;
window_y_ = y * h / 240 + h / 480;
// (the warp moves SDL's own pointer state too, which the program reads in a few places, and
// queues the motion event)
SDL_WarpMouseInWindow(window_, window_x_, window_y_);
release_button_ = name == "left" ? SDL_BUTTON_LEFT : SDL_BUTTON_RIGHT;
push_button(SDL_MOUSEBUTTONDOWN, release_button_);
release_pending_ = true;
} else if (name == "key") {
std::string key;
row >> key;
SDL_Keycode code = SDLK_UNKNOWN;
if (key == "RETURN" || key == "ENTER") code = SDLK_RETURN;
else if (key == "ESCAPE" || key == "ESC") code = SDLK_ESCAPE;
else if (key == "BACKSPACE") code = SDLK_BACKSPACE;
else if (key == "SPACE") code = SDLK_SPACE;
else if (key.size() == 1) code = SDL_Keycode(key[0] >= 'A' && key[0] <= 'Z' ? key[0] - 'A' + 'a' : key[0]);
if (code != SDLK_UNKNOWN) push_key(code);
} else if (name == "text") {
std::string text;
std::getline(row, text);
if (!text.empty() && text[0] == ' ') text.erase(0, 1);
SDL_Event e{};
e.type = SDL_TEXTINPUT;
e.text.windowID = SDL_GetWindowID(window_);
SDL_strlcpy(e.text.text, text.c_str(), sizeof(e.text.text));
SDL_PushEvent(&e);
} else if (name == "wait") {
int ms = 0;
row >> ms;
wait_until_ = SDL_GetTicks() + Uint32(ms > 0 ? ms : 0);
} else if (name == "quit") {
SDL_Event e{};
e.type = SDL_QUIT;
SDL_PushEvent(&e);
}
}
bool active_ = false, release_pending_ = false, logged_ = true, finished_ = false;
SDL_Window* window_ = nullptr;
std::FILE* log_ = nullptr;
std::vector<std::string> commands_;
std::vector<uint8_t> pixels_;
size_t issued_ = 0;
uint64_t picture_ = 0;
unsigned pictures_ = 0;
Uint32 last_change_ = 0, command_time_ = 0, wait_until_ = 0;
Uint32 settle_ms_ = 400, timeout_ms_ = 15000;
int window_x_ = 0, window_y_ = 0, width_ = 0, height_ = 0;
std::string shots_;
Uint8 release_button_ = SDL_BUTTON_LEFT;
};
// Shows the rendered picture (SDL_RenderPresent), letting the robot see it first.
inline void present(SDL_Renderer* renderer) {
Robot& robot = Robot::instance();
if (robot.active()) robot.frame(renderer);
SDL_RenderPresent(renderer);
}
} // namespace bmh::app