Test harness: --headless (no-op GL table with a CPU texel store, no window, audio or pacing), a virtual clock for every time read, --record/--replay of per-frame input, --frames, --trace state hashes and details, --mods for a private mods folder
This commit is contained in:
1 parent
7d3cf33c20
commit
ff2c61a63a
16 files changed
+743
-50
No files matched your search
+6
-1
@@ -1,5 +1,6 @@
|
||||
#include "engine/data.h"
|
||||
#include "game/manager.h"
|
||||
#include "engine/platform.h"
|
||||
#include <cctype>
|
||||
#include <filesystem>
|
||||
|
||||
@@ -12,6 +13,7 @@ constexpr std::string_view LANGUAGE_FOLDER = "lang/";
|
||||
// Mods reach their own files from resources/ through "../mods/", and here the mods live in resources/mods/.
|
||||
constexpr std::string_view MODS_FROM_RESOURCES = "../mods/";
|
||||
constexpr std::string_view PARENT_FOLDER = "../";
|
||||
constexpr std::string_view MODS_FOLDER = "mods/";
|
||||
|
||||
std::string dataDirectory = "resources/";
|
||||
std::string languageDirectory;
|
||||
@@ -27,13 +29,16 @@ static std::string path_normalize(std::string_view path)
|
||||
return normalized;
|
||||
}
|
||||
|
||||
// A normalized path under the language's folder when that holds it, under the data directory otherwise.
|
||||
// A normalized path under the language's folder when that holds it, a mod's under the mods folder, under the data
|
||||
// directory otherwise.
|
||||
static std::string mount_resolve(const std::string& normalized)
|
||||
{
|
||||
std::error_code error;
|
||||
std::string localized = languageDirectory + normalized;
|
||||
|
||||
if (!languageDirectory.empty() && std::filesystem::exists(localized, error)) return localized;
|
||||
if (normalized.starts_with(MODS_FOLDER) && !platform.modsDirectory.empty())
|
||||
return platform.modsDirectory + normalized.substr(MODS_FOLDER.size());
|
||||
return dataDirectory + normalized;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,39 @@
|
||||
#include "engine/gl.h"
|
||||
#include <SDL3/SDL_video.h>
|
||||
#include <algorithm>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
// The largest texture a headless run reports, as a desktop GL does.
|
||||
constexpr GLint HEADLESS_MAX_TEXTURE_SIZE = 16384;
|
||||
constexpr const char* HEADLESS_VERSION = "2.1 headless";
|
||||
// GL's default row alignment for texel uploads, and the channels of a texel read back.
|
||||
constexpr int UNPACK_ALIGNMENT = 4;
|
||||
constexpr int RGBA_CHANNELS = 4;
|
||||
constexpr uint8_t OPAQUE_ALPHA = 255;
|
||||
|
||||
// A texture's texels as a headless run keeps them, tightly packed, for the texels the game's logic reads back.
|
||||
struct HeadlessTexture
|
||||
{
|
||||
std::vector<uint8_t> texels;
|
||||
int channels = 0;
|
||||
int height = 0;
|
||||
int width = 0;
|
||||
};
|
||||
|
||||
// What a headless run's GL remembers: the textures by id, the bound texture, the texture the bound framebuffer draws
|
||||
// into, and the last id handed out.
|
||||
struct HeadlessGl
|
||||
{
|
||||
std::unordered_map<GLuint, HeadlessTexture> textures;
|
||||
GLuint boundTexture = 0;
|
||||
GLuint lastId = 0;
|
||||
GLuint targetTexture = 0;
|
||||
bool isFramebufferBound = false;
|
||||
};
|
||||
|
||||
Gl gl;
|
||||
static HeadlessGl headless;
|
||||
|
||||
// Fills the table from the current context, leaving isLoaded false if any entry point is missing.
|
||||
void gl_load()
|
||||
@@ -13,3 +45,108 @@ void gl_load()
|
||||
GL_FUNCTIONS(GL_FUNCTION_LOAD)
|
||||
#undef GL_FUNCTION_LOAD
|
||||
}
|
||||
|
||||
// An entry point that does nothing and returns zero.
|
||||
template <typename Function>
|
||||
struct GlStub;
|
||||
|
||||
template <typename Result, typename... Arguments>
|
||||
struct GlStub<Result (*)(Arguments...)>
|
||||
{
|
||||
static Result call(Arguments...) { return Result(); }
|
||||
};
|
||||
|
||||
// Hands out fresh ids.
|
||||
static void ids_generate(GLsizei count, GLuint* ids)
|
||||
{
|
||||
for (GLsizei i = 0; i < count; i++) ids[i] = ++headless.lastId;
|
||||
}
|
||||
|
||||
// The channels of an upload's pixel format.
|
||||
static int format_channels(GLenum format)
|
||||
{
|
||||
return format == GL_RGBA ? RGBA_CHANNELS : format == GL_RGB ? RGBA_CHANNELS - 1 : 1;
|
||||
}
|
||||
|
||||
// Copies uploaded rows (GL's 4-byte row alignment) into a part of the bound texture.
|
||||
static void texels_store(GLint x, GLint y, GLsizei width, GLsizei height, const void* data)
|
||||
{
|
||||
HeadlessTexture& texture = headless.textures[headless.boundTexture];
|
||||
if (!data || x < 0 || y < 0 || x + width > texture.width || y + height > texture.height) return;
|
||||
|
||||
int rowSize = width * texture.channels;
|
||||
int stride = (rowSize + UNPACK_ALIGNMENT - 1) / UNPACK_ALIGNMENT * UNPACK_ALIGNMENT;
|
||||
texture.texels.resize((size_t)texture.width * texture.height * texture.channels);
|
||||
for (int row = 0; row < height; row++)
|
||||
std::copy_n((const uint8_t*)data + (size_t)row * stride, rowSize,
|
||||
texture.texels.begin() + ((size_t)(y + row) * texture.width + x) * texture.channels);
|
||||
}
|
||||
|
||||
// Reads RGBA texels back from the texture the bound framebuffer draws into, transparent black from anything else.
|
||||
static void texels_read(GLint x, GLint y, GLsizei width, GLsizei height, GLenum, GLenum, void* pixels)
|
||||
{
|
||||
auto found = headless.textures.find(headless.targetTexture);
|
||||
bool isTextureBound = headless.isFramebufferBound && found != headless.textures.end();
|
||||
HeadlessTexture* texture = isTextureBound ? &found->second : nullptr;
|
||||
auto* out = (uint8_t*)pixels;
|
||||
|
||||
for (int row = y; row < y + height; row++)
|
||||
{
|
||||
for (int column = x; column < x + width; column++, out += RGBA_CHANNELS)
|
||||
{
|
||||
std::fill_n(out, RGBA_CHANNELS, 0);
|
||||
bool isInside = texture && !texture->texels.empty() && column >= 0 && row >= 0 &&
|
||||
column < texture->width && row < texture->height;
|
||||
if (!isInside) continue;
|
||||
|
||||
uint8_t* texel = &texture->texels[((size_t)row * texture->width + column) * texture->channels];
|
||||
std::copy_n(texel, texture->channels, out);
|
||||
if (texture->channels < RGBA_CHANNELS) out[RGBA_CHANNELS - 1] = OPAQUE_ALPHA;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fills the table for a run without a context: every call does nothing, objects get fresh ids, compiles, links and
|
||||
// framebuffers succeed, renderbuffers are as big as textures get, and the version reads as 2.1. Uploaded texels are
|
||||
// kept, so the texels the game's logic reads back (creep and puddle contact, sprite colors) are the ones a GPU gives.
|
||||
void gl_stub_load()
|
||||
{
|
||||
#define GL_FUNCTION_STUB(name) gl.name = GlStub<decltype(gl.name)>::call;
|
||||
GL_FUNCTIONS(GL_FUNCTION_STUB)
|
||||
#undef GL_FUNCTION_STUB
|
||||
gl.GenFramebuffers = ids_generate;
|
||||
gl.GenRenderbuffers = ids_generate;
|
||||
gl.GenTextures = ids_generate;
|
||||
gl.CreateProgram = []() { return ++headless.lastId; };
|
||||
gl.CreateShader = [](GLenum) { return ++headless.lastId; };
|
||||
gl.GetShaderiv = [](GLuint, GLenum name, GLint* value) { *value = name == GL_COMPILE_STATUS; };
|
||||
gl.GetProgramiv = [](GLuint, GLenum name, GLint* value) { *value = name == GL_LINK_STATUS; };
|
||||
gl.GetIntegerv = [](GLenum name, GLint* value)
|
||||
{ *value = name == GL_MAX_TEXTURE_SIZE ? HEADLESS_MAX_TEXTURE_SIZE : 0; };
|
||||
gl.GetRenderbufferParameteriv = [](GLenum, GLenum, GLint* value) { *value = HEADLESS_MAX_TEXTURE_SIZE; };
|
||||
gl.CheckFramebufferStatus = [](GLenum) -> GLenum { return GL_FRAMEBUFFER_COMPLETE; };
|
||||
gl.GetString = [](GLenum) { return (const GLubyte*)HEADLESS_VERSION; };
|
||||
|
||||
gl.BindTexture = [](GLenum, GLuint texture) { headless.boundTexture = texture; };
|
||||
gl.DeleteTextures = [](GLsizei count, const GLuint* textures)
|
||||
{
|
||||
for (GLsizei i = 0; i < count; i++) headless.textures.erase(textures[i]);
|
||||
};
|
||||
gl.TexImage2D = [](GLenum, GLint level, GLint, GLsizei width, GLsizei height, GLint, GLenum format, GLenum,
|
||||
const void* data)
|
||||
{
|
||||
if (level != 0) return;
|
||||
HeadlessTexture& texture = headless.textures[headless.boundTexture];
|
||||
texture = {.channels = format_channels(format), .height = height, .width = width};
|
||||
texels_store(0, 0, width, height, data);
|
||||
};
|
||||
gl.TexSubImage2D = [](GLenum, GLint level, GLint x, GLint y, GLsizei width, GLsizei height, GLenum, GLenum,
|
||||
const void* data)
|
||||
{
|
||||
if (level == 0) texels_store(x, y, width, height, data);
|
||||
};
|
||||
gl.BindFramebuffer = [](GLenum, GLuint framebuffer) { headless.isFramebufferBound = framebuffer != 0; };
|
||||
gl.FramebufferTexture2D = [](GLenum, GLenum, GLenum, GLuint texture, GLint) { headless.targetTexture = texture; };
|
||||
gl.ReadPixels = texels_read;
|
||||
gl.isLoaded = true;
|
||||
}
|
||||
@@ -91,3 +91,4 @@ struct Gl
|
||||
extern Gl gl;
|
||||
|
||||
void gl_load();
|
||||
void gl_stub_load();
|
||||
@@ -0,0 +1,395 @@
|
||||
#include "engine/harness.h"
|
||||
#include "classes.h"
|
||||
#include "engine/kage_input.h"
|
||||
#include "engine/kage_sound.h"
|
||||
#include "engine/platform.h"
|
||||
#include "engine/seeds.h"
|
||||
#include "entity/effect/effect.h"
|
||||
#include "entity/familiar/familiar.h"
|
||||
#include "entity/npc/npc.h"
|
||||
#include "entity/pickup/pickup.h"
|
||||
#include "entity/player/player.h"
|
||||
#include "game/game.h"
|
||||
#include "game/manager.h"
|
||||
#include "level/room.h"
|
||||
#include <algorithm>
|
||||
#include <cinttypes>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <type_traits>
|
||||
|
||||
constexpr const char* REPLAY_MAGIC = "isaac-input 1";
|
||||
constexpr const char* EXECUTABLE_PATH = "/proc/self/exe";
|
||||
constexpr uint64_t FNV_OFFSET = 0xcbf29ce484222325;
|
||||
constexpr uint64_t FNV_PRIME = 0x100000001b3;
|
||||
constexpr std::string_view OPTIONS_PREFIX = "options ";
|
||||
// The letter a recording writes for each DeltaKind.
|
||||
constexpr const char* DELTA_KINDS = "kmt";
|
||||
// A delta line's frame, kind and code, before its values.
|
||||
constexpr int DELTA_MIN_FIELDS = 3;
|
||||
|
||||
// A command line flag and whether a value follows it.
|
||||
struct HarnessFlag
|
||||
{
|
||||
const char* name;
|
||||
bool isValued;
|
||||
};
|
||||
|
||||
// The flags the harness reads, and --mute. The rest of the command line is kept in a recording as the options that
|
||||
// matter.
|
||||
constexpr HarnessFlag HARNESS_FLAGS[] = {
|
||||
{"--headless", false}, {"--record", true}, {"--replay", true}, {"--frames", true}, {"--trace", true},
|
||||
{"--trace-every", true}, {"--trace-detail", false}, {"--mods", true}, {"--mute", false},
|
||||
};
|
||||
|
||||
Harness harness;
|
||||
|
||||
// FNV-1a over bytes, continuing from a hash.
|
||||
static uint64_t hash_add(uint64_t hash, void* data, size_t size)
|
||||
{
|
||||
for (size_t i = 0; i < size; i++) hash = (hash ^ ((uint8_t*)data)[i]) * FNV_PRIME;
|
||||
return hash;
|
||||
}
|
||||
|
||||
// The executable's hash, which tells two builds apart, read once.
|
||||
static uint64_t build_hash()
|
||||
{
|
||||
static uint64_t hash = 0;
|
||||
if (hash) return hash;
|
||||
|
||||
std::ifstream file(EXECUTABLE_PATH, std::ios::binary);
|
||||
std::string bytes((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
|
||||
hash = hash_add(FNV_OFFSET, bytes.data(), bytes.size());
|
||||
return hash;
|
||||
}
|
||||
|
||||
// The flag a command line argument is, or null.
|
||||
static const HarnessFlag* flag_find(const char* argument)
|
||||
{
|
||||
for (const HarnessFlag& flag : HARNESS_FLAGS)
|
||||
if (std::strcmp(argument, flag.name) == 0) return &flag;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Reads the harness flags. --mods is a private mods folder. A recording's options are the other arguments and the
|
||||
// mods that folder holds.
|
||||
void Harness::arguments_load(int argc, char** argv)
|
||||
{
|
||||
std::string options;
|
||||
const char* recordPath = nullptr;
|
||||
const char* replayPath = nullptr;
|
||||
const char* tracePath = nullptr;
|
||||
|
||||
for (int i = 1; i < argc; i++)
|
||||
{
|
||||
std::string_view argument = argv[i];
|
||||
const HarnessFlag* flag = flag_find(argv[i]);
|
||||
const char* value = flag && flag->isValued && i + 1 < argc ? argv[++i] : "";
|
||||
|
||||
if (!flag) options += std::string(argument) + ' ';
|
||||
else if (argument == "--headless") isHeadless = true;
|
||||
else if (argument == "--record") recordPath = value;
|
||||
else if (argument == "--replay") replayPath = value;
|
||||
else if (argument == "--frames") frameLimit = std::strtoull(value, nullptr, DIGIT_BASE);
|
||||
else if (argument == "--trace") tracePath = value;
|
||||
else if (argument == "--trace-every") traceEvery = std::max(std::atoi(value), 1);
|
||||
else if (argument == "--trace-detail") traceMode = TRACE_DETAIL;
|
||||
else if (argument == "--mods") modsDirectory = std::string(value) + '/';
|
||||
}
|
||||
|
||||
std::vector<std::string> mods;
|
||||
std::error_code error;
|
||||
if (!modsDirectory.empty())
|
||||
for (auto& entry : std::filesystem::directory_iterator(modsDirectory, error))
|
||||
mods.push_back(entry.path().filename());
|
||||
std::ranges::sort(mods);
|
||||
for (std::string& mod : mods) options += "mod=" + mod + ' ';
|
||||
|
||||
isActive = isHeadless || recordPath || replayPath;
|
||||
if (isHeadless) KAGE::Sound::manager.isMuted = true;
|
||||
if (replayPath) isReplaying = replay_load(replayPath, options);
|
||||
if (recordPath) record_open(recordPath, options);
|
||||
if (tracePath) traceFile = std::fopen(tracePath, "w");
|
||||
}
|
||||
|
||||
// Reads a recording's header and deltas, warning when it came from another build or other options. It ends at its end
|
||||
// line's frame count, or after its last delta.
|
||||
bool Harness::replay_load(const char* path, std::string& options)
|
||||
{
|
||||
FILE* file = std::fopen(path, "r");
|
||||
if (!file)
|
||||
{
|
||||
log_printf(LOG_ERROR, "Harness: cannot open replay %s\n", path);
|
||||
return false;
|
||||
}
|
||||
|
||||
char line[MESSAGE_LENGTH];
|
||||
while (std::fgets(line, sizeof(line), file))
|
||||
{
|
||||
line[std::strcspn(line, "\n")] = 0;
|
||||
std::string_view text = line;
|
||||
InputDelta delta;
|
||||
char kind = 0;
|
||||
uint64_t hash = 0;
|
||||
int fieldCount = std::sscanf(line, "%" SCNu64 " %c %u %f %f", &delta.frame, &kind, &delta.code, &delta.x,
|
||||
&delta.y);
|
||||
const char* found = kind ? std::strchr(DELTA_KINDS, kind) : nullptr;
|
||||
|
||||
if (std::sscanf(line, "build %" SCNx64, &hash) == 1 && hash != build_hash())
|
||||
log_printf(LOG_WARN, "Harness: the replay was recorded by another build\n");
|
||||
else if (text.starts_with(OPTIONS_PREFIX) && text.substr(OPTIONS_PREFIX.size()) != options)
|
||||
log_printf(LOG_WARN, "Harness: the replay was recorded with other options: %s\n", line);
|
||||
else if (std::sscanf(line, "end %" SCNu64, &replayEnd) == 1) continue;
|
||||
else if (fieldCount >= DELTA_MIN_FIELDS && found)
|
||||
{
|
||||
delta.kind = (DeltaKind)(found - DELTA_KINDS);
|
||||
replay.push_back(delta);
|
||||
}
|
||||
}
|
||||
std::fclose(file);
|
||||
if (replayEnd == 0 && !replay.empty()) replayEnd = replay.back().frame + 1;
|
||||
keys.assign(KAGE::Input::KEY_COUNT, 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Starts a recording: the game's version, the build, and the options that matter.
|
||||
void Harness::record_open(const char* path, std::string& options)
|
||||
{
|
||||
recordFile = std::fopen(path, "w");
|
||||
if (!recordFile) return log_printf(LOG_ERROR, "Harness: cannot write %s\n", path);
|
||||
|
||||
std::fprintf(recordFile, "%s\nversion %s\nbuild %016" PRIx64 "\noptions %s\n", REPLAY_MAGIC, GAME_VERSION_CODE,
|
||||
build_hash(), options.c_str());
|
||||
recordedKeys.assign(KAGE::Input::KEY_COUNT, 0);
|
||||
}
|
||||
|
||||
// Takes a typed character in, to reach the game at the next input poll.
|
||||
void Harness::text_add(uint32_t character)
|
||||
{
|
||||
if (!isReplaying) text.push_back(character);
|
||||
}
|
||||
|
||||
// The mouse as the game reads it: SDL's, or the harness's while it owns the input.
|
||||
SDL_MouseButtonFlags Harness::mouse_get(float* x, float* y)
|
||||
{
|
||||
if (!isActive) return SDL_GetMouseState(x, y);
|
||||
if (x) *x = mouse.x;
|
||||
if (y) *y = mouse.y;
|
||||
return mouseButtons;
|
||||
}
|
||||
|
||||
// Runs after each input poll: a replay sets the keyboard, mouse and text of its frame, the mouse is read otherwise,
|
||||
// a recording takes what changed, and the typed text goes to the game.
|
||||
void Harness::input_update(KAGE::Input::Manager& input)
|
||||
{
|
||||
if (!isActive) return;
|
||||
|
||||
if (isReplaying)
|
||||
{
|
||||
for (; replayNext < replay.size() && replay[replayNext].frame <= frame; replayNext++)
|
||||
{
|
||||
InputDelta& delta = replay[replayNext];
|
||||
if (delta.kind == DELTA_KEY && delta.code < keys.size()) keys[delta.code] = delta.x;
|
||||
else if (delta.kind == DELTA_TEXT) text.push_back(delta.code);
|
||||
else if (delta.kind == DELTA_MOUSE)
|
||||
{
|
||||
mouse = {delta.x, delta.y};
|
||||
mouseButtons = delta.code;
|
||||
}
|
||||
}
|
||||
input.devices[0]->current = keys;
|
||||
}
|
||||
else mouseButtons = SDL_GetMouseState(&mouse.x, &mouse.y);
|
||||
|
||||
if (recordFile) record_write(input.devices[0]->current);
|
||||
for (uint32_t character : text)
|
||||
for (auto& listener : platform.textListeners) listener(character);
|
||||
text.clear();
|
||||
}
|
||||
|
||||
// Writes what changed in the keyboard, mouse and text since the last poll.
|
||||
void Harness::record_write(std::vector<float>& current)
|
||||
{
|
||||
for (size_t key = 0; key < current.size() && key < recordedKeys.size(); key++)
|
||||
{
|
||||
if (current[key] == recordedKeys[key]) continue;
|
||||
std::fprintf(recordFile, "%" PRIu64 " %c %zu %g\n", frame, DELTA_KINDS[DELTA_KEY], key, current[key]);
|
||||
recordedKeys[key] = current[key];
|
||||
}
|
||||
if (mouse.x != recordedMouse.x || mouse.y != recordedMouse.y || mouseButtons != recordedButtons)
|
||||
{
|
||||
std::fprintf(recordFile, "%" PRIu64 " %c %u %.9g %.9g\n", frame, DELTA_KINDS[DELTA_MOUSE], mouseButtons,
|
||||
mouse.x, mouse.y);
|
||||
recordedMouse = mouse;
|
||||
recordedButtons = mouseButtons;
|
||||
}
|
||||
for (uint32_t character : text)
|
||||
std::fprintf(recordFile, "%" PRIu64 " %c %u\n", frame, DELTA_KINDS[DELTA_TEXT], character);
|
||||
}
|
||||
|
||||
// Ends a frame: traces it and counts it. At a replay's end the input is the devices' again, and the game quits there
|
||||
// without a frame limit, at the limit with one.
|
||||
void Harness::frame_end()
|
||||
{
|
||||
if (traceFile) trace_write();
|
||||
frame++;
|
||||
|
||||
bool isReplayOver = isReplaying && frame >= replayEnd;
|
||||
if (isReplayOver) isReplaying = false;
|
||||
if (frameLimit ? frame >= frameLimit : isReplayOver) platform.isQuitRequested = true;
|
||||
}
|
||||
|
||||
// Closes the recording with the frame it ended on, and the trace.
|
||||
void Harness::shutdown()
|
||||
{
|
||||
if (recordFile) std::fprintf(recordFile, "end %" PRIu64 "\n", frame);
|
||||
for (FILE** file : {&recordFile, &traceFile})
|
||||
{
|
||||
if (*file) std::fclose(*file);
|
||||
*file = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
// Adds " key=value" to a trace record, floats with every digit they need.
|
||||
template <typename T>
|
||||
static void field_add(std::string& record, const char* key, T value)
|
||||
{
|
||||
char text[MESSAGE_LENGTH];
|
||||
if constexpr (std::is_floating_point_v<T>) std::snprintf(text, sizeof(text), " %s=%.9g", key, (double)value);
|
||||
else std::snprintf(text, sizeof(text), " %s=%lld", key, (long long)value);
|
||||
record += text;
|
||||
}
|
||||
|
||||
static void field_add(std::string& record, const char* key, Vector value)
|
||||
{
|
||||
char text[MESSAGE_LENGTH];
|
||||
std::snprintf(text, sizeof(text), " %s=%.9g,%.9g", key, value.x, value.y);
|
||||
record += text;
|
||||
}
|
||||
|
||||
static void field_add(std::string& record, const char* key, RNG& rng)
|
||||
{
|
||||
char text[MESSAGE_LENGTH];
|
||||
std::snprintf(text, sizeof(text), " %s=%08x:%u.%u.%u", key, rng._seed, rng._shift1, rng._shift2, rng._shift3);
|
||||
record += text;
|
||||
}
|
||||
|
||||
// The random generators of the game and the run: the global one, the run's seeds, the floor's, the item pools'.
|
||||
static std::string trace_rng_get()
|
||||
{
|
||||
std::string record;
|
||||
std::string state = random_state_get();
|
||||
|
||||
field_add(record, "global", hash_add(FNV_OFFSET, state.data(), state.size()));
|
||||
if (!g_game) return record;
|
||||
|
||||
Seeds& seeds = g_game->seedEffects;
|
||||
field_add(record, "start", seeds.gameStartSeed);
|
||||
field_add(record, "playerinit", seeds.playerInitSeed);
|
||||
field_add(record, "stageseeds", hash_add(FNV_OFFSET, seeds.stageSeeds.data(), sizeof(seeds.stageSeeds)));
|
||||
field_add(record, "seeds", seeds.rng);
|
||||
field_add(record, "devilangel", g_game->devilAngelRoomRNG);
|
||||
field_add(record, "generation", g_game->generationRNG);
|
||||
field_add(record, "fortune", g_game->fortuneRNG);
|
||||
field_add(record, "itempool", g_game->itemPool.itemPoolRNG);
|
||||
field_add(record, "trinketpool", g_game->itemPool.trinketPoolRNG);
|
||||
field_add(record, "gameframe", g_game->frameCount);
|
||||
return record;
|
||||
}
|
||||
|
||||
// One player: where it is, its hearts and pickups, its stats and its items.
|
||||
static std::string trace_player_get(Entity_Player& player)
|
||||
{
|
||||
std::string record;
|
||||
std::vector<int>& items = player.collectibleCounts;
|
||||
|
||||
field_add(record, "type", player.playerType);
|
||||
field_add(record, "pos", player.pos);
|
||||
field_add(record, "vel", player.velocity);
|
||||
for (auto [key, value] : {std::pair{"red", player.redHearts}, {"max", player.maxHearts},
|
||||
{"soul", player.soulHearts}, {"black", player.blackHearts}, {"bone", player.boneHearts},
|
||||
{"golden", player.goldenHearts}, {"eternal", player.eternalHearts},
|
||||
{"rotten", player.rottenHearts}, {"broken", player.brokenHearts},
|
||||
{"coins", player.numCoins}, {"bombs", player.numBombs}, {"keys", player.numKeys}})
|
||||
field_add(record, key, value);
|
||||
for (auto [key, value] : {std::pair{"damage", player.damage}, {"firedelay", player.maxFireDelay},
|
||||
{"shotspeed", player.shotSpeed}, {"range", player.tearRange},
|
||||
{"speed", player.moveSpeed}, {"luck", player.luck}})
|
||||
field_add(record, key, value);
|
||||
record += " items=";
|
||||
for (size_t item = 0; item < items.size(); item++)
|
||||
if (items[item]) record += std::to_string(item) + 'x' + std::to_string(items[item]) + ',';
|
||||
return record;
|
||||
}
|
||||
|
||||
// The state of an entity of a kind that keeps one, 0 otherwise.
|
||||
static int entity_state_get(Entity& entity)
|
||||
{
|
||||
if (auto* npc = dynamic_cast<Entity_NPC*>(&entity)) return npc->state;
|
||||
if (auto* pickup = dynamic_cast<Entity_Pickup*>(&entity)) return (int)pickup->state;
|
||||
if (auto* familiar = dynamic_cast<Entity_Familiar*>(&entity)) return familiar->state;
|
||||
if (auto* effect = dynamic_cast<Entity_Effect*>(&entity)) return effect->state;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// One entity: what it is, where, its hit points, state and flags.
|
||||
static std::string trace_entity_get(Entity& entity)
|
||||
{
|
||||
std::string record = ' ' + std::to_string(entity.type) + '.' + std::to_string(entity.variant) + '.' +
|
||||
std::to_string(entity.subtype);
|
||||
|
||||
field_add(record, "index", entity.index);
|
||||
field_add(record, "seed", entity.initSeed);
|
||||
field_add(record, "pos", entity.pos);
|
||||
field_add(record, "vel", entity.velocity);
|
||||
field_add(record, "hp", entity.health);
|
||||
field_add(record, "state", entity_state_get(entity));
|
||||
record += " flags=" + std::to_string(entity.flags);
|
||||
return record;
|
||||
}
|
||||
|
||||
// Writes the frame's trace line on every traceEvery-th frame and on a new room: the frame, the manager's state, the
|
||||
// stage and room, then a hash of each category, or (detailed) one line for each random generator set, player and
|
||||
// entity in list order.
|
||||
void Harness::trace_write()
|
||||
{
|
||||
int stage = g_game ? g_game->stage : -1;
|
||||
int stageType = g_game ? g_game->stageType : -1;
|
||||
int room = g_game ? g_game->currentRoomIdx : -1;
|
||||
bool isRoomChanged = stage != traceStage || stageType != traceStageType || room != traceRoom;
|
||||
|
||||
traceStage = stage;
|
||||
traceStageType = stageType;
|
||||
traceRoom = room;
|
||||
if (frame % traceEvery != 0 && !isRoomChanged) return;
|
||||
|
||||
std::vector<std::pair<std::string, std::string>> records = {{"rng", trace_rng_get()}};
|
||||
if (g_game)
|
||||
{
|
||||
for (Entity_Player* player : g_game->playerManager.playerList)
|
||||
records.push_back({"player", trace_player_get(*player)});
|
||||
for (Entity* entity : g_game->room->entityList.updateEL)
|
||||
records.push_back({"entity", trace_entity_get(*entity)});
|
||||
}
|
||||
|
||||
std::fprintf(traceFile, "%" PRIu64 " state=%d stage=%d.%d room=%d", frame, (int)g_manager->state, stage, stageType,
|
||||
room);
|
||||
if (traceMode == TRACE_DETAIL)
|
||||
{
|
||||
std::fputc('\n', traceFile);
|
||||
for (auto& [category, record] : records)
|
||||
std::fprintf(traceFile, "%" PRIu64 " %s%s\n", frame, category.c_str(), record.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
for (const char* category : {"rng", "player", "entity"})
|
||||
{
|
||||
uint64_t hash = FNV_OFFSET;
|
||||
for (auto& [name, record] : records)
|
||||
if (name == category) hash = hash_add(hash, record.data(), record.size() + 1);
|
||||
std::fprintf(traceFile, " %s=%016" PRIx64, category, hash);
|
||||
}
|
||||
std::fputc('\n', traceFile);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL_mouse.h>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace KAGE::Input
|
||||
{
|
||||
class Manager;
|
||||
}
|
||||
|
||||
// What a trace line holds about the game: one hash per category, or every field written out.
|
||||
enum TraceMode
|
||||
{
|
||||
TRACE_HASH,
|
||||
TRACE_DETAIL
|
||||
};
|
||||
|
||||
// What one recorded input change sets: a keyboard key, the mouse, or a typed character.
|
||||
enum DeltaKind
|
||||
{
|
||||
DELTA_KEY,
|
||||
DELTA_MOUSE,
|
||||
DELTA_TEXT
|
||||
};
|
||||
|
||||
// One input change on a frame: a key (code) and its value (x), the mouse's buttons (code) and position, or the
|
||||
// character (code) typed.
|
||||
struct InputDelta
|
||||
{
|
||||
float x = 0;
|
||||
float y = 0;
|
||||
uint64_t frame = 0;
|
||||
uint32_t code = 0;
|
||||
DeltaKind kind = DELTA_KEY;
|
||||
};
|
||||
|
||||
// The test harness the command line turns on: no window (--headless), the input recorded (--record) or played back
|
||||
// (--replay) frame for frame, a frame limit (--frames) and a trace of the game state (--trace). While any of the first
|
||||
// three is on, the clock counts frames, gamepads and focus changes are left out, and typed text comes through here.
|
||||
class Harness
|
||||
{
|
||||
public:
|
||||
std::string modsDirectory;
|
||||
std::vector<InputDelta> replay;
|
||||
std::vector<float> keys;
|
||||
std::vector<uint32_t> text;
|
||||
SDL_FPoint mouse = {};
|
||||
FILE* recordFile = nullptr;
|
||||
FILE* traceFile = nullptr;
|
||||
uint64_t frame = 0;
|
||||
uint64_t frameLimit = 0;
|
||||
uint64_t replayEnd = 0;
|
||||
size_t replayNext = 0;
|
||||
SDL_MouseButtonFlags mouseButtons = 0;
|
||||
TraceMode traceMode = TRACE_HASH;
|
||||
int traceEvery = 30;
|
||||
int traceRoom = -1;
|
||||
int traceStage = -1;
|
||||
int traceStageType = -1;
|
||||
bool isActive = false;
|
||||
bool isHeadless = false;
|
||||
bool isReplaying = false;
|
||||
|
||||
void arguments_load(int argc, char** argv);
|
||||
void input_update(KAGE::Input::Manager& input);
|
||||
void text_add(uint32_t character);
|
||||
SDL_MouseButtonFlags mouse_get(float* x, float* y);
|
||||
void frame_end();
|
||||
void shutdown();
|
||||
|
||||
private:
|
||||
std::vector<float> recordedKeys;
|
||||
SDL_FPoint recordedMouse = {};
|
||||
SDL_MouseButtonFlags recordedButtons = 0;
|
||||
|
||||
bool replay_load(const char* path, std::string& options);
|
||||
void record_open(const char* path, std::string& options);
|
||||
void record_write(std::vector<float>& current);
|
||||
void trace_write();
|
||||
};
|
||||
|
||||
extern Harness harness;
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "engine/kage_input.h"
|
||||
#include "engine/harness.h"
|
||||
#include "engine/platform.h"
|
||||
#include <SDL3/SDL_init.h>
|
||||
#include <algorithm>
|
||||
@@ -236,9 +237,11 @@ std::string_view InputDevice::button_name(int button) const
|
||||
|
||||
// 00a21980 (00a1fa20) Starts the input manager with the keyboard as device 0, opening gamepads as they connect.
|
||||
// The XInput and DirectInput loading (00a6cf80) and the gamepad polling thread (00a220c0) are SDL's work here.
|
||||
// Under the harness there are no gamepads.
|
||||
bool Manager::Init()
|
||||
{
|
||||
if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) log_printf(LOG_ERROR, "Gamepad init failed: %s\n", SDL_GetError());
|
||||
if (!harness.isActive && !SDL_InitSubSystem(SDL_INIT_GAMEPAD))
|
||||
log_printf(LOG_ERROR, "Gamepad init failed: %s\n", SDL_GetError());
|
||||
devices.clear();
|
||||
devices.push_back(std::make_shared<InputDevice>(DEVICE_KEYBOARD));
|
||||
isInitialized = true;
|
||||
@@ -253,11 +256,13 @@ void Manager::Shutdown()
|
||||
SDL_QuitSubSystem(SDL_INIT_GAMEPAD);
|
||||
}
|
||||
|
||||
// (00a21cb0, 00a1fc00) Takes the window's events, then starts every device's frame.
|
||||
// (00a21cb0, 00a1fc00) Takes the window's events, then starts every device's frame, which the harness may replay or
|
||||
// record.
|
||||
void Manager::update_devices()
|
||||
{
|
||||
platform.events_poll();
|
||||
for (auto& device : devices) device->update();
|
||||
harness.input_update(*this);
|
||||
}
|
||||
|
||||
// 00a20020 The number of devices.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "engine/kage_sound.h"
|
||||
#include "engine/data.h"
|
||||
#include "engine/harness.h"
|
||||
#include "engine/platform.h"
|
||||
#include <SDL3/SDL_init.h>
|
||||
#include <algorithm>
|
||||
@@ -188,13 +189,14 @@ static bool source_open(SoundSource& source, const std::string& file, bool isOgg
|
||||
}
|
||||
|
||||
// 00a2b1e0 A sound by its game path: a decoded sample is shared with earlier loads of the same path, a stream is
|
||||
// always new. The extension picks the decoder. Null when the manager is not running or the file fails.
|
||||
// always new. The extension picks the decoder. Null when the manager is not running (quietly in a headless run) or the
|
||||
// file fails.
|
||||
// ".org" (Organya, SampleSourceOrg) is not decoded here.
|
||||
std::shared_ptr<SoundSource> Manager::load_sound(std::string_view soundPath, SourceType type)
|
||||
{
|
||||
if (!isInitialized)
|
||||
{
|
||||
log_printf(LOG_ASSERT, "Sound manager has not been initialized\n");
|
||||
if (!harness.isHeadless) log_printf(LOG_ASSERT, "Sound manager has not been initialized\n");
|
||||
return nullptr;
|
||||
}
|
||||
if (type == SOURCE_SAMPLE)
|
||||
|
||||
+74
-32
@@ -1,6 +1,7 @@
|
||||
#include "engine/platform.h"
|
||||
#include "engine/data.h"
|
||||
#include "engine/gl.h"
|
||||
#include "engine/harness.h"
|
||||
#include "engine/kage_graphics.h"
|
||||
#include "engine/kage_input.h"
|
||||
#include "engine/kage_sound.h"
|
||||
@@ -46,6 +47,10 @@ constexpr double SHORT_FRAME_RATIO = 1.1;
|
||||
constexpr int PACING_SWITCH_FRAMES = 30;
|
||||
constexpr int TARGET_HZ = 60;
|
||||
constexpr float REFRESH_TOLERANCE = 0.04f;
|
||||
// The harness clock's frame in nanoseconds, and its wall clock at frame 0: 2025-01-01 at noon UTC, the same date in
|
||||
// every time zone.
|
||||
constexpr uint64_t HARNESS_FRAME_NS = (uint64_t)(FRAME_TIME * SDL_NS_PER_SECOND);
|
||||
constexpr std::time_t HARNESS_EPOCH = 1735732800;
|
||||
|
||||
// One default binding: an input action and its button or key.
|
||||
struct DefaultBinding
|
||||
@@ -141,12 +146,20 @@ void KAGE_LogMessage(uint32_t flags, uint8_t* format)
|
||||
log_printf((LogLevel)flags, "%s", (const char*)format);
|
||||
}
|
||||
|
||||
// 00a68490 The monotonic clock in nanoseconds.
|
||||
// 00a68490 The monotonic clock in nanoseconds. Under the harness it counts frames.
|
||||
uint64_t GetTimeNs()
|
||||
{
|
||||
if (harness.isActive) return harness.frame * HARNESS_FRAME_NS;
|
||||
return (uint64_t)((double)SDL_GetPerformanceCounter() / SDL_GetPerformanceFrequency() * SDL_NS_PER_SECOND);
|
||||
}
|
||||
|
||||
// The wall clock in seconds since 1970, under the harness its epoch and the frames since.
|
||||
std::time_t wall_time_get()
|
||||
{
|
||||
if (harness.isActive) return HARNESS_EPOCH + (std::time_t)(GetTimeNs() / SDL_NS_PER_SECOND);
|
||||
return std::time(nullptr);
|
||||
}
|
||||
|
||||
// Creates a folder, showing the game's error box when it is not there afterwards.
|
||||
static void folder_create(const std::string& path, const char* error)
|
||||
{
|
||||
@@ -163,6 +176,7 @@ static void folder_create(const std::string& path, const char* error)
|
||||
// mods folder older versions kept with the saves, moves loose online logs into online_logs/desyncs/ and notes the
|
||||
// folders in savedatapath.txt.
|
||||
// The game's own folder, where it kept mods/, data/ and savedatapath.txt, is resources/ here. Mod data goes with saves.
|
||||
// The harness's --mods replaces the mods folder.
|
||||
void Platform::directories_load()
|
||||
{
|
||||
char* prefPath = SDL_GetPrefPath("", SAVE_FOLDER.data());
|
||||
@@ -170,7 +184,7 @@ void Platform::directories_load()
|
||||
SDL_free(prefPath);
|
||||
if (userDataDirectory.empty()) SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", SAVE_FOLDER_ERROR, nullptr);
|
||||
|
||||
modsDirectory = dataDirectory + "mods/";
|
||||
modsDirectory = harness.modsDirectory.empty() ? dataDirectory + "mods/" : harness.modsDirectory;
|
||||
modsSaveDirectory = userDataDirectory + "data/";
|
||||
folder_create(modsDirectory, "Modding data path %s is not a writable directory!");
|
||||
folder_create(modsSaveDirectory, "Modding save data path %s is not a writable directory!");
|
||||
@@ -226,7 +240,7 @@ void Platform::bindings_load()
|
||||
}
|
||||
|
||||
// 00a5f0e0 Seeds rand from the clock in milliseconds, then starts KAGE: graphics, sound, input and video in turn,
|
||||
// stopping at the first that fails (the game carries on either way).
|
||||
// stopping at the first that fails (the game carries on either way). A headless run has no sound.
|
||||
// 00a710a0 (merged) Steam, EOS, the custom heap, the packed archives' mount points (resources/ is read directly), the
|
||||
// multiplayer threads and the Windows timer and power settings are left out: SDL keeps the display awake itself.
|
||||
// The OpenAL Soft device hooks after the sound manager have no place on SDL audio.
|
||||
@@ -238,7 +252,7 @@ void Platform::engine_init()
|
||||
if (isEngineInitialized) log_printf(LOG_ASSERT, "KAGE has already been initialized\n");
|
||||
if (!KAGE::Graphics::manager.Init()) return;
|
||||
|
||||
KAGE::Sound::manager.Init();
|
||||
if (!harness.isHeadless) KAGE::Sound::manager.Init();
|
||||
if (!KAGE::Input::manager.Init()) return;
|
||||
|
||||
isEngineInitialized = true;
|
||||
@@ -263,10 +277,12 @@ void Platform::engine_shutdown()
|
||||
SDL_Quit();
|
||||
}
|
||||
|
||||
// Opens the window at its default size with its GL context and shows it, as Graphics::Manager::Init began.
|
||||
// Opens the window at its default size with its GL context and shows it, as Graphics::Manager::Init began. A headless
|
||||
// run has only SDL's events.
|
||||
bool Platform::window_open()
|
||||
{
|
||||
if (!SDL_Init(SDL_INIT_VIDEO)) log_printf(LOG_ASSERT, "SDL failed to initialize: %s\n", SDL_GetError());
|
||||
if (!SDL_Init(harness.isHeadless ? SDL_INIT_EVENTS : SDL_INIT_VIDEO))
|
||||
log_printf(LOG_ASSERT, "SDL failed to initialize: %s\n", SDL_GetError());
|
||||
|
||||
window_size_set({WINDOW_WIDTH, WINDOW_HEIGHT});
|
||||
viewportSize = windowSize;
|
||||
@@ -283,9 +299,34 @@ void Platform::window_swap()
|
||||
}
|
||||
|
||||
// 00a19df0 Creates the window hidden, with an OpenGL 2.0 compatibility context (1.0 if that fails), and the
|
||||
// framebuffer the renderer draws the game into.
|
||||
// framebuffer the renderer draws the game into. A headless run has neither window nor context, only GL stubs.
|
||||
// The Win32 icon and the maximize box it removes have no SDL counterpart.
|
||||
bool Platform::window_create()
|
||||
{
|
||||
if (harness.isHeadless) gl_stub_load();
|
||||
else if (!context_create()) return false;
|
||||
|
||||
log_printf(LOG_INFO, "OpenGL version %s\n", (const char*)gl.GetString(GL_VERSION));
|
||||
log_printf(LOG_INFO, "GLSL version %s\n", (const char*)gl.GetString(GL_SHADING_LANGUAGE_VERSION));
|
||||
if (!gl.GenFramebuffers)
|
||||
{
|
||||
log_printf(LOG_ERROR, "glGenFramebuffers is NULL!\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
gl.GenFramebuffers(1, &framebuffer);
|
||||
log_printf(LOG_INFO, "Framebuffer ID: %d\n", framebuffer);
|
||||
gl.BindFramebuffer(GL_FRAMEBUFFER, framebuffer);
|
||||
depth_renderbuffer_update(RENDERBUFFER_REBUILD);
|
||||
gl.BindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
|
||||
SDL_GetWindowPosition(window, &windowPosition.x, &windowPosition.y);
|
||||
state_reset();
|
||||
return true;
|
||||
}
|
||||
|
||||
// The window and its GL context, with the table loaded from it.
|
||||
bool Platform::context_create()
|
||||
{
|
||||
SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
|
||||
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, DEPTH_BITS);
|
||||
@@ -305,22 +346,6 @@ bool Platform::window_create()
|
||||
}
|
||||
|
||||
gl_load();
|
||||
log_printf(LOG_INFO, "OpenGL version %s\n", (const char*)gl.GetString(GL_VERSION));
|
||||
log_printf(LOG_INFO, "GLSL version %s\n", (const char*)gl.GetString(GL_SHADING_LANGUAGE_VERSION));
|
||||
if (!gl.GenFramebuffers)
|
||||
{
|
||||
log_printf(LOG_ERROR, "glGenFramebuffers is NULL!\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
gl.GenFramebuffers(1, &framebuffer);
|
||||
log_printf(LOG_INFO, "Framebuffer ID: %d\n", framebuffer);
|
||||
gl.BindFramebuffer(GL_FRAMEBUFFER, framebuffer);
|
||||
depth_renderbuffer_update(RENDERBUFFER_REBUILD);
|
||||
gl.BindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
|
||||
SDL_GetWindowPosition(window, &windowPosition.x, &windowPosition.y);
|
||||
state_reset();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -343,9 +368,10 @@ void Platform::vsync_apply()
|
||||
SDL_GL_SetSwapInterval(isVsync ? 1 : 0);
|
||||
}
|
||||
|
||||
// (00a19340, 00a193c0) The window's drawable size in pixels.
|
||||
// (00a19340, 00a193c0) The window's drawable size in pixels, its size without a window.
|
||||
Size Platform::framebuffer_size_get()
|
||||
{
|
||||
if (!window) return windowSize;
|
||||
Size size;
|
||||
SDL_GetWindowSizeInPixels(window, &size.width, &size.height);
|
||||
return size;
|
||||
@@ -392,9 +418,10 @@ void Platform::viewport_reset()
|
||||
}
|
||||
|
||||
// 00a19450 Resizes the window unless it has that size already. In fullscreen it keeps the size for later and warns.
|
||||
// A headless run keeps the default size it opened with.
|
||||
void Platform::window_size_set(Size size)
|
||||
{
|
||||
if (size == windowSize) return;
|
||||
if (size == windowSize || (harness.isHeadless && isEngineInitialized)) return;
|
||||
|
||||
windowSize = size;
|
||||
if (isFullscreen) log_printf(LOG_WARN, "Setting size of window while in fullscreen, is this intended?\n");
|
||||
@@ -429,8 +456,7 @@ void Platform::fullscreen_set(FullscreenMode mode)
|
||||
SDL_RaiseWindow(window);
|
||||
SDL_SyncWindow(window);
|
||||
|
||||
Size size;
|
||||
SDL_GetWindowSize(window, &size.width, &size.height);
|
||||
Size size = window_size_get();
|
||||
for (auto& listener : sizeListeners) listener(size);
|
||||
viewport_reset();
|
||||
KAGE::Graphics::manager.update_projection();
|
||||
@@ -441,6 +467,7 @@ void Platform::fullscreen_set(FullscreenMode mode)
|
||||
// Takes the window's events as GLFW's callbacks did: closing asks the game to quit, a new size (00a19bf0), position
|
||||
// (00a19ca0) or focus (00a19d40) goes to its listeners and resets what depends on it, each typed character goes to
|
||||
// the text listeners, keys and gamepads go to input.
|
||||
// Under the harness focus changes are left out and typed characters reach the game through it.
|
||||
// Win32's topmost-while-focused fullscreen window has no SDL counterpart.
|
||||
void Platform::events_poll()
|
||||
{
|
||||
@@ -470,13 +497,17 @@ void Platform::events_poll()
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_FOCUS_GAINED:
|
||||
case SDL_EVENT_WINDOW_FOCUS_LOST:
|
||||
if (harness.isActive) break;
|
||||
for (auto& listener : focusListeners) listener(event.type == SDL_EVENT_WINDOW_FOCUS_GAINED);
|
||||
break;
|
||||
case SDL_EVENT_TEXT_INPUT:
|
||||
{
|
||||
const char* text = event.text.text;
|
||||
while (uint32_t character = SDL_StepUTF8(&text, nullptr))
|
||||
for (auto& listener : textListeners) listener(character);
|
||||
{
|
||||
if (harness.isActive) harness.text_add(character);
|
||||
else for (auto& listener : textListeners) listener(character);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SDL_EVENT_KEY_DOWN:
|
||||
@@ -516,12 +547,12 @@ int Platform::frame_begin()
|
||||
return (int)std::floor(1 / frameTime + 0.5);
|
||||
}
|
||||
|
||||
// Holds the frame to 60 Hz unless vsync paces it: sleeps the whole milliseconds left but one, then spins. A long run
|
||||
// of frames with nothing left to sleep turns the forced pacing back off.
|
||||
// Holds the frame to 60 Hz unless vsync paces it or the run is headless: sleeps the whole milliseconds left but one,
|
||||
// then spins. A long run of frames with nothing left to sleep turns the forced pacing back off.
|
||||
// The original spins without sleeping while a cutscene video plays (0095dee0).
|
||||
void Platform::frame_wait()
|
||||
{
|
||||
if (!isPacingForced && isVsync) return;
|
||||
if (harness.isHeadless || (!isPacingForced && isVsync)) return;
|
||||
|
||||
int sleepMs = std::max((int)((FRAME_TIME - (time_get() - frameStart)) * MS_PER_SECOND) - 1, 0);
|
||||
if (sleepMs > 0)
|
||||
@@ -581,5 +612,16 @@ void window_apply(OptionsConfig& options, WindowSetting setting)
|
||||
// The window's current size, which reset options take as theirs.
|
||||
void window_size_load(OptionsConfig& options)
|
||||
{
|
||||
SDL_GetWindowSize(platform.window, &options.windowWidth, &options.windowHeight);
|
||||
Size size = platform.window_size_get();
|
||||
options.windowWidth = size.width;
|
||||
options.windowHeight = size.height;
|
||||
}
|
||||
|
||||
// The window's size, its last set size without a window.
|
||||
Size Platform::window_size_get()
|
||||
{
|
||||
if (!window) return windowSize;
|
||||
Size size;
|
||||
SDL_GetWindowSize(window, &size.width, &size.height);
|
||||
return size;
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <SDL3/SDL_rect.h>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <ctime>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -15,6 +16,7 @@ constexpr int SECONDS_PER_MINUTE = 60;
|
||||
constexpr int SECONDS_PER_HOUR = 3600;
|
||||
constexpr int DIGIT_BASE = 10;
|
||||
constexpr std::string_view SAVE_FOLDER = "Binding of Isaac Repentance+";
|
||||
constexpr const char* GAME_VERSION_CODE = "J460";
|
||||
|
||||
struct SDL_GLContextState;
|
||||
struct SDL_Window;
|
||||
@@ -104,6 +106,7 @@ public:
|
||||
void vsync_apply();
|
||||
void depth_renderbuffer_update(RenderbufferMode mode);
|
||||
Size framebuffer_size_get();
|
||||
Size window_size_get();
|
||||
void state_reset();
|
||||
void viewport_reset();
|
||||
|
||||
@@ -114,10 +117,12 @@ private:
|
||||
bool isPacingForced = false;
|
||||
|
||||
bool window_create();
|
||||
bool context_create();
|
||||
};
|
||||
|
||||
extern Platform platform;
|
||||
|
||||
uint64_t GetTimeNs();
|
||||
std::time_t wall_time_get();
|
||||
void log_open(const std::string& path);
|
||||
void log_printf(LogLevel level, const char* format, ...) __attribute__((format(printf, 2, 3)));
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
#include <random>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
|
||||
constexpr uint32_t START_SHIFT_INDEX = 27;
|
||||
@@ -220,6 +221,14 @@ uint32_t Random()
|
||||
return mersenneTwister();
|
||||
}
|
||||
|
||||
// The global Mersenne Twister's state as text, for the harness's trace.
|
||||
std::string random_state_get()
|
||||
{
|
||||
std::ostringstream state;
|
||||
state << mersenneTwister;
|
||||
return state.str();
|
||||
}
|
||||
|
||||
// 006eef20 Seeds the global Mersenne Twister.
|
||||
void random_seed(uint32_t seed)
|
||||
{
|
||||
|
||||
@@ -178,3 +178,4 @@ inline float random_between(float least, float range)
|
||||
}
|
||||
|
||||
void random_seed(uint32_t seed);
|
||||
std::string random_state_get();
|
||||
@@ -21,6 +21,7 @@
|
||||
#include "game/manager.h"
|
||||
#include "ui/menu/manager.h"
|
||||
#include "engine/fx_layers.h"
|
||||
#include "engine/harness.h"
|
||||
#include "entity/effect/combat.h"
|
||||
#include "entity/npc/ai.h"
|
||||
#include "entity/npc/basement.h"
|
||||
@@ -686,7 +687,7 @@ bool Entity_Player::GetMouseAimTarget(Vector& target, bool)
|
||||
{
|
||||
if (!g_manager->optionsConfig.isMouseControlEnabled || controllerIndex != 0) return false;
|
||||
Vector cursor = {};
|
||||
if (!(SDL_GetMouseState(&cursor.x, &cursor.y) & SDL_BUTTON_LMASK)) return false;
|
||||
if (!(harness.mouse_get(&cursor.x, &cursor.y) & SDL_BUTTON_LMASK)) return false;
|
||||
|
||||
Room& room = *g_game->room;
|
||||
if (Room::IsMirrorWorld()) cursor.x = (float)platform.windowSize.width - cursor.x;
|
||||
|
||||
+7
-4
@@ -1,6 +1,7 @@
|
||||
#include "classes.h"
|
||||
#include "engine/data.h"
|
||||
#include "engine/gl.h"
|
||||
#include "engine/harness.h"
|
||||
#include "engine/kage_sound.h"
|
||||
#include "lua/engine.h"
|
||||
#include "game/manager.h"
|
||||
@@ -11,7 +12,6 @@
|
||||
#include <ctime>
|
||||
#include <string>
|
||||
|
||||
constexpr const char* GAME_VERSION = "J460";
|
||||
constexpr const char* LOCALHOST_FLAG = "--localhost_match";
|
||||
constexpr const char* RESOURCES_FLAG = "--resources";
|
||||
constexpr const char* MUTE_FLAG = "--mute";
|
||||
@@ -54,7 +54,7 @@ int IsaacMain(int argc, uint8_t** argv)
|
||||
|
||||
log_printf(LOG_INFO, "Command Line: \n");
|
||||
for (int i = 0; i < argc; i++) log_printf(LOG_INFO, "\t%s\n", (const char*)argv[i]);
|
||||
log_printf(LOG_INFO, "Game Version: %s \n", GAME_VERSION);
|
||||
log_printf(LOG_INFO, "Game Version: %s \n", GAME_VERSION_CODE);
|
||||
if (gl.ClampColor && (SDL_GL_ExtensionSupported(CLAMP_COLOR_EXTENSION) || gl_version_get() >= CLAMP_COLOR_VERSION))
|
||||
gl.ClampColor(GL_CLAMP_VERTEX_COLOR, GL_FALSE);
|
||||
|
||||
@@ -67,19 +67,22 @@ int IsaacMain(int argc, uint8_t** argv)
|
||||
Manager::Update();
|
||||
g_manager->Render();
|
||||
if (g_game) lua_engine_get().gc_update();
|
||||
harness.frame_end();
|
||||
if (platform.isQuitRequested) break;
|
||||
platform.frame_wait();
|
||||
}
|
||||
|
||||
harness.shutdown();
|
||||
isaac_shutdown();
|
||||
platform.engine_shutdown();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The Linux entry point: "--resources <dir>" says where the imported game files are, "--mute" plays nothing, then the
|
||||
// game's own main runs.
|
||||
// The Linux entry point: "--resources <dir>" says where the imported game files are, "--mute" plays nothing, the
|
||||
// harness takes its flags, then the game's own main runs.
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
harness.arguments_load(argc, argv);
|
||||
for (int i = 1; i < argc; i++)
|
||||
{
|
||||
if (std::strcmp(argv[i], MUTE_FLAG) == 0) KAGE::Sound::manager.isMuted = true;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "engine/screenshot.h"
|
||||
#include "level/backdrop.h"
|
||||
#include "engine/data.h"
|
||||
#include "engine/harness.h"
|
||||
#include "entity/player/player.h"
|
||||
#include "game/game.h"
|
||||
#include "lua/engine.h"
|
||||
@@ -546,7 +547,7 @@ void IsaacStartup(int argc, uint8_t** argv)
|
||||
resizedWindowSize = {};
|
||||
reload_resource_paths();
|
||||
log_printf(LOG_INFO, "Binding of Isaac: Repentance+ v1.9.7.17.J460\n");
|
||||
random_seed((uint32_t)(std::time(nullptr) + GetTimeNs() / NS_PER_MS));
|
||||
random_seed((uint32_t)(wall_time_get() + GetTimeNs() / NS_PER_MS));
|
||||
|
||||
platform.sizeListeners.push_back(Manager::ResizeWindowCallback);
|
||||
platform.positionListeners.push_back(window_position_changed);
|
||||
@@ -1404,7 +1405,7 @@ static void scene_end(Manager& manager)
|
||||
static void cursor_update(Manager& manager)
|
||||
{
|
||||
Vector position = {};
|
||||
SDL_MouseButtonFlags buttons = SDL_GetMouseState(&position.x, &position.y);
|
||||
SDL_MouseButtonFlags buttons = harness.mouse_get(&position.x, &position.y);
|
||||
|
||||
manager.cursorSprite.Play(buttons & SDL_BUTTON_LMASK ? CURSOR_CLICKED_ANIMATION : CURSOR_ANIMATION);
|
||||
bool isMoved = position.x != manager.lastMousePosition.x || position.y != manager.lastMousePosition.y;
|
||||
@@ -1576,8 +1577,7 @@ static void cursor_render(Manager& manager)
|
||||
bool isShown = manager.state == MANAGER_STATE_GAME || manager.state == MANAGER_STATE_MENU;
|
||||
if (!manager.optionsConfig.isMouseControlEnabled || !isShown || manager.cursorVisibleTimer <= 0) return;
|
||||
|
||||
Size window;
|
||||
SDL_GetWindowSize(platform.window, &window.width, &window.height);
|
||||
Size window = platform.window_size_get();
|
||||
SpriteDraw draw;
|
||||
draw.position.x = KAGE::Graphics::manager.orthographicWidth / (float)(unsigned int)window.width *
|
||||
manager.lastMousePosition.x;
|
||||
@@ -1605,7 +1605,7 @@ void Manager::Render()
|
||||
colorCorrectionSurface = nullptr;
|
||||
create_render_surfaces();
|
||||
if (!platform.isFullscreen && !(SDL_GetWindowFlags(platform.window) & SDL_WINDOW_BORDERLESS))
|
||||
SDL_GetWindowSize(platform.window, &optionsConfig.windowWidth, &optionsConfig.windowHeight);
|
||||
window_size_load(optionsConfig);
|
||||
isRenderSurfaceResetPending = false;
|
||||
}
|
||||
|
||||
|
||||
@@ -969,7 +969,7 @@ void PersistentGameData::BackupSaveFile()
|
||||
{
|
||||
if (g_manager->netplayManager.is_online()) return;
|
||||
|
||||
std::time_t now = std::time(nullptr);
|
||||
std::time_t now = wall_time_get();
|
||||
std::tm* date = std::localtime(&now);
|
||||
int stamp = ((date->tm_year + BACKUP_YEAR_BASE) * BACKUP_DIGITS + date->tm_mon + 1) * BACKUP_DIGITS + date->tm_mday;
|
||||
write_file(platform.userDataDirectory + "save_backups/" + std::to_string(stamp) + "." + get_save_file_name());
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include "entity/player/player.h"
|
||||
#include "engine/font.h"
|
||||
#include "engine/fx_layers.h"
|
||||
#include "engine/harness.h"
|
||||
#include "game/game.h"
|
||||
#include "level/grid/grid_entity.h"
|
||||
#include "engine/kage_input.h"
|
||||
@@ -402,14 +403,15 @@ static Vector mouse_position_get(bool isGameCoords)
|
||||
{
|
||||
Vector position = {};
|
||||
|
||||
SDL_GetMouseState(&position.x, &position.y);
|
||||
harness.mouse_get(&position.x, &position.y);
|
||||
return isGameCoords ? screen_to_world(position) : position;
|
||||
}
|
||||
|
||||
// 0086fdb0 Whether a mouse button (0 left, 1 right, 2 middle, up to 7) is held.
|
||||
static bool is_mouse_button_pressed(int button)
|
||||
{
|
||||
return button >= 0 && button <= MOUSE_BUTTON_LAST && SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON_MASK(button + 1);
|
||||
return button >= 0 && button <= MOUSE_BUTTON_LAST &&
|
||||
harness.mouse_get(nullptr, nullptr) & SDL_BUTTON_MASK(button + 1);
|
||||
}
|
||||
|
||||
// Text drawn with the console font, as RenderText and RenderScaledText draw it.
|
||||
|
||||
Reference in new issue
Block a user