Curation round 2, wave A: anm2 (Anm2Ed JSON), text, config as idiomatic classes; SDL3 platform opens a window
- anm2.h/.cpp take over ANM2, AnimationState, LayerState, AnmCache and the frame data. They read Anm2Ed's JSON documents with simdjson and play them as the game does (interpolation baked at load). src/anm2/ and msvc.h are retired. - font, formatted_text, string_table and rich_text take over the text classes. FormattedText::parse is still bit-exact against its assembly. - options_config and challenge_params take over OptionsConfig, ChallengeParams and the .ini helpers. The tests include Save's exact bytes. - platform.h/.cpp and main.cpp run IsaacMain on SDL3: the window and GL context open, and the run stops at the first built-in shader (FUN_00a13fa0). - source_tree.py: a taken-over parent stays bytes, taken-over methods are not re-emitted as a namespace, and every address in a (a, b, c to d) list on a comment counts as taken over. - log.h: reconstruction_missing() for a taken-over class's methods that are not written yet. 206 functions taken over, boot path 89/615. The full build waits for wave B: item_config, entity_config and mod_manager still use the old APIs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d6e1ca7c6c
commit
780767f5e1
161 files changed
+8646
-21919
No files matched your search
@@ -0,0 +1,655 @@
|
||||
#include "platform.h"
|
||||
#include "classes.h"
|
||||
#include "data.h"
|
||||
#include "gl.h"
|
||||
#include "options_config.h"
|
||||
#include <SDL3/SDL_events.h>
|
||||
#include <SDL3/SDL_filesystem.h>
|
||||
#include <SDL3/SDL_hints.h>
|
||||
#include <SDL3/SDL_init.h>
|
||||
#include <SDL3/SDL_messagebox.h>
|
||||
#include <SDL3/SDL_mouse.h>
|
||||
#include <SDL3/SDL_timer.h>
|
||||
#include <SDL3/SDL_video.h>
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
#include <cmath>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <mutex>
|
||||
#include <span>
|
||||
#include <utility>
|
||||
|
||||
constexpr const char* SAVE_FOLDER = "Binding of Isaac Repentance+";
|
||||
constexpr const char* SAVE_FOLDER_ERROR = "Failed to obtain writable save data directory!";
|
||||
constexpr const char* SAVE_PATHS_NOTICE =
|
||||
"This file is purely informational. Changing it will have no effect on saving or loading data.\n\n";
|
||||
constexpr const char* WINDOW_TITLE = "Binding of Isaac: Repentance+ v1.9.7.17";
|
||||
constexpr int WINDOW_HEIGHT = 540;
|
||||
constexpr int WINDOW_WIDTH = 960;
|
||||
constexpr SDL_WindowFlags WINDOW_FLAGS = SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN | SDL_WINDOW_RESIZABLE;
|
||||
// The context versions GLFW was asked for, the second only when the first fails.
|
||||
constexpr int GL_MAJOR_VERSIONS[] = {2, 1};
|
||||
constexpr int DEPTH_BITS = 24;
|
||||
constexpr int STENCIL_BITS = 8;
|
||||
constexpr double CLEAR_DEPTH = -1000;
|
||||
constexpr int RENDERBUFFER_MIN_SIZE = 8;
|
||||
constexpr int ACTION_COUNT = 32;
|
||||
constexpr int CONTROLLER_COUNT = 4;
|
||||
constexpr ActionBinding EMPTY_BINDING = {-1, -1, -1, -1};
|
||||
// A frame shorter than this share of FRAME_TIME is short, and this many in a row switch the pacing over.
|
||||
constexpr double SHORT_FRAME_RATIO = 1.1;
|
||||
constexpr int PACING_SWITCH_FRAMES = 30;
|
||||
constexpr int MESSAGE_LENGTH = 1024;
|
||||
constexpr int MS_PER_SECOND = 1000;
|
||||
constexpr int TARGET_HZ = 60;
|
||||
constexpr float REFRESH_TOLERANCE = 0.04f;
|
||||
|
||||
// One default binding: an input action and its button or key.
|
||||
struct DefaultBinding
|
||||
{
|
||||
int action;
|
||||
int input;
|
||||
};
|
||||
|
||||
// The engine's own controller defaults, in its standard button numbers.
|
||||
constexpr DefaultBinding CONTROLLER_DEFAULTS[] = {
|
||||
{0, 0}, {0, 43947}, {1, 1}, {1, 43948}, {2, 2}, {2, 43949}, {3, 3}, {3, 43950}, {4, 4},
|
||||
{4, 43951}, {5, 5}, {5, 43952}, {6, 6}, {6, 43953}, {7, 7}, {7, 43954}, {8, 8}, {9, 9},
|
||||
{10, 11}, {11, 12}, {12, 15}, {13, 14}, {14, 17}, {15, 18}, {19, 15}, {20, 0}, {20, 43947},
|
||||
{21, 1}, {21, 43948}, {22, 2}, {22, 43949}, {23, 3}, {23, 43950}, {24, 8}, {25, 11}, {26, 9},
|
||||
{27, 12}, {28, 6}, {29, 4}, {30, 13}, {31, 10},
|
||||
};
|
||||
|
||||
// The engine's keyboard defaults, in GLFW key numbers.
|
||||
constexpr DefaultBinding KEYBOARD_DEFAULTS[] = {
|
||||
{0, 65}, {1, 68}, {2, 87}, {3, 83}, {4, 263}, {5, 262}, {6, 265}, {7, 264}, {8, 69},
|
||||
{9, 32}, {10, 81}, {11, 341}, {12, 80}, {13, 258}, {14, 32}, {14, 257}, {15, 256}, {19, 257},
|
||||
{20, 263}, {21, 262}, {22, 265}, {23, 264}, {24, 81}, {25, 69}, {26, 88}, {27, 67}, {28, 258},
|
||||
{29, 341}, {30, 342}, {31, 340}, {18, 82}, {16, 70}, {17, 77},
|
||||
};
|
||||
|
||||
// The standard buttons whose GLFW gamepad number differs.
|
||||
constexpr DefaultBinding PLATFORM_BUTTONS[] = {{17, 7}, {18, 5}};
|
||||
|
||||
// A vertex attribute a built-in shader binds by name, and the slot of KAGE's vertex format it reads.
|
||||
struct ShaderAttribute
|
||||
{
|
||||
const char* name;
|
||||
int slot;
|
||||
};
|
||||
|
||||
constexpr ShaderAttribute COLOR_ATTRIBUTES[] = {{"Position", 5}, {"Color", 6}, {"", 0}};
|
||||
constexpr ShaderAttribute TEXTURE_ATTRIBUTES[] = {{"Position", 5}, {"Color", 6}, {"TexCoord", 7}, {"", 0}};
|
||||
|
||||
constexpr const char* COLOR_VERTEX = R"(
|
||||
attribute vec3 Position;
|
||||
attribute vec4 Color;
|
||||
varying vec4 Color0;
|
||||
uniform mat4 Transform;
|
||||
|
||||
void main( void )
|
||||
{
|
||||
Color0 = Color;
|
||||
gl_Position = Transform * vec4( Position.xyz, 1.0 );
|
||||
}
|
||||
)";
|
||||
|
||||
constexpr const char* COLOR_FRAGMENT = R"(
|
||||
#ifndef GL_ES
|
||||
#define lowp
|
||||
#endif
|
||||
varying lowp vec4 Color0;
|
||||
|
||||
void main( void )
|
||||
{
|
||||
gl_FragColor = Color0;
|
||||
if( gl_FragColor.a == 0.0 ) discard;
|
||||
}
|
||||
)";
|
||||
|
||||
constexpr const char* TEXTURE_VERTEX = R"(
|
||||
attribute vec3 Position;
|
||||
attribute vec4 Color;
|
||||
attribute vec2 TexCoord;
|
||||
varying vec4 Color0;
|
||||
varying vec2 TexCoord0;
|
||||
uniform mat4 Transform;
|
||||
|
||||
void main( void )
|
||||
{
|
||||
gl_Position = Transform * vec4( Position.xyz, 1.0 );
|
||||
Color0 = Color;
|
||||
TexCoord0 = TexCoord;
|
||||
}
|
||||
)";
|
||||
|
||||
constexpr const char* TEXTURE_FRAGMENT = R"(
|
||||
#ifndef GL_ES
|
||||
#define lowp
|
||||
#define highp
|
||||
#endif
|
||||
varying lowp vec4 Color0;
|
||||
varying highp vec2 TexCoord0;
|
||||
uniform sampler2D Texture0;
|
||||
|
||||
void main( void )
|
||||
{
|
||||
gl_FragColor = texture2D( Texture0, TexCoord0 ) * Color0;
|
||||
if( gl_FragColor.a == 0.0 ) discard;
|
||||
}
|
||||
)";
|
||||
|
||||
constexpr const char* INDEXED_TEXTURE_FRAGMENT = R"(
|
||||
#ifndef GL_ES
|
||||
#define lowp
|
||||
#define highp
|
||||
#endif
|
||||
varying lowp vec4 Color0;
|
||||
varying highp vec2 TexCoord0;
|
||||
uniform sampler2D Texture0;
|
||||
uniform sampler2D Texture1;
|
||||
|
||||
void main( void )
|
||||
{
|
||||
vec4 PaletteIndex = texture2D( Texture0, TexCoord0 );
|
||||
vec4 OutputColor = texture2D( Texture1, PaletteIndex.xy ) * Color0;
|
||||
if( OutputColor.w == 0.0 ) discard;
|
||||
gl_FragColor = OutputColor;
|
||||
}
|
||||
)";
|
||||
|
||||
// One of the engine's built-in shaders.
|
||||
struct ShaderSource
|
||||
{
|
||||
const char* name;
|
||||
const ShaderAttribute* attributes;
|
||||
const char* vertex;
|
||||
const char* fragment;
|
||||
};
|
||||
|
||||
constexpr ShaderSource SHADERS[] = {
|
||||
{"KAGE_ColorShader", COLOR_ATTRIBUTES, COLOR_VERTEX, COLOR_FRAGMENT},
|
||||
{"KAGE_ColorTextureShader", TEXTURE_ATTRIBUTES, TEXTURE_VERTEX, TEXTURE_FRAGMENT},
|
||||
{"KAGE_IndexedTextureShader", TEXTURE_ATTRIBUTES, TEXTURE_VERTEX, INDEXED_TEXTURE_FRAGMENT},
|
||||
};
|
||||
|
||||
Platform platform;
|
||||
|
||||
// The log file, which levels reach it, and whether the next message starts a line.
|
||||
static std::mutex logMutex;
|
||||
static FILE* logFile = nullptr;
|
||||
static unsigned int logMask = 0;
|
||||
static bool isLogLineStart = true;
|
||||
|
||||
// 00a5f3a0 Opens the log file, replacing any open one, with every level written to it.
|
||||
void log_open(const std::string& path)
|
||||
{
|
||||
if (logFile) std::fclose(logFile);
|
||||
logFile = std::fopen(path.c_str(), "wb");
|
||||
logMask = UINT8_MAX;
|
||||
}
|
||||
|
||||
// What a level's lines start with.
|
||||
static const char* log_prefix(unsigned int flags)
|
||||
{
|
||||
switch (flags)
|
||||
{
|
||||
case LOG_INFO: return "[INFO] - ";
|
||||
case LOG_NET: return "[NET] - ";
|
||||
case LOG_WARN: return "[WARN] - ";
|
||||
case LOG_ERROR: return "[ERROR] - ";
|
||||
case LOG_ASSERT: return "[ASSERT] - ";
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
|
||||
// Prints a message to stdout, and to the log file when its level is in the mask, the level's prefix at a line start.
|
||||
void log_printf(LogLevel level, const char* format, ...)
|
||||
{
|
||||
std::lock_guard lock(logMutex);
|
||||
bool isFileLogged = logFile && (logMask & level);
|
||||
if ((level & UINT8_MAX) == 0 && !isFileLogged) return;
|
||||
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
va_list sizing;
|
||||
va_copy(sizing, args);
|
||||
std::string text = isLogLineStart ? log_prefix(level) : "";
|
||||
size_t start = text.size();
|
||||
text.resize(start + std::vsnprintf(nullptr, 0, format, sizing));
|
||||
va_end(sizing);
|
||||
std::vsnprintf(text.data() + start, text.size() - start + 1, format, args);
|
||||
va_end(args);
|
||||
|
||||
if (level & UINT8_MAX)
|
||||
{
|
||||
std::fputs(text.c_str(), stdout);
|
||||
std::fflush(stdout);
|
||||
}
|
||||
if (isFileLogged)
|
||||
{
|
||||
std::fputs(text.c_str(), logFile);
|
||||
std::fflush(logFile);
|
||||
}
|
||||
if (!text.empty()) isLogLineStart = text.back() == '\n';
|
||||
}
|
||||
|
||||
// 00a112c0 Logs finished text at a level. The game's prototype has no format arguments, so callers format first.
|
||||
void KAGE_LogMessage(uint32_t flags, uint8_t* format)
|
||||
{
|
||||
log_printf((LogLevel)flags, "%s", (const char*)format);
|
||||
}
|
||||
|
||||
// 00a68490 The monotonic clock in nanoseconds.
|
||||
uint64_t GetTimeNs()
|
||||
{
|
||||
return (uint64_t)((double)SDL_GetPerformanceCounter() / SDL_GetPerformanceFrequency() * SDL_NS_PER_SECOND);
|
||||
}
|
||||
|
||||
// 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)
|
||||
{
|
||||
std::error_code result;
|
||||
char message[MESSAGE_LENGTH];
|
||||
|
||||
std::filesystem::create_directory(path, result);
|
||||
if (std::filesystem::is_directory(path, result)) return;
|
||||
std::snprintf(message, sizeof(message), error, path.c_str());
|
||||
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", message, nullptr);
|
||||
}
|
||||
|
||||
// 009a9510 Finds the save folder (SDL's per-user folder for the game) and the mods and mod data folders, removes the
|
||||
// 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.
|
||||
void Platform::directories_load()
|
||||
{
|
||||
char* prefPath = SDL_GetPrefPath("", SAVE_FOLDER);
|
||||
userDataDirectory = prefPath ? prefPath : "";
|
||||
SDL_free(prefPath);
|
||||
if (userDataDirectory.empty()) SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", SAVE_FOLDER_ERROR, nullptr);
|
||||
|
||||
modsDirectory = dataDirectory + "mods/";
|
||||
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!");
|
||||
|
||||
std::error_code result;
|
||||
std::filesystem::remove_all(userDataDirectory + "mods/", result);
|
||||
|
||||
std::string onlineLogs = userDataDirectory + "online_logs/";
|
||||
std::string desyncs = onlineLogs + "desyncs/";
|
||||
if (!std::filesystem::exists(desyncs, result))
|
||||
{
|
||||
std::filesystem::create_directory(desyncs, result);
|
||||
for (const auto& entry : std::filesystem::directory_iterator(onlineLogs, result))
|
||||
std::filesystem::rename(entry.path(), std::filesystem::path(desyncs) / entry.path().filename(), result);
|
||||
}
|
||||
|
||||
FILE* info = std::fopen((dataDirectory + "savedatapath.txt").c_str(), "w");
|
||||
if (!info) return;
|
||||
std::fputs(SAVE_PATHS_NOTICE, info);
|
||||
std::fprintf(info, "Save Data Path: %s\n", userDataDirectory.c_str());
|
||||
std::fprintf(info, "Modding Data Path: %s\n", modsDirectory.c_str());
|
||||
std::fclose(info);
|
||||
}
|
||||
|
||||
// The bindings a table of defaults gives each action, in table order, up to BINDING_SLOTS each.
|
||||
static std::vector<ActionBinding> bindings_build(std::span<const DefaultBinding> defaults)
|
||||
{
|
||||
std::vector<ActionBinding> bindings(ACTION_COUNT, EMPTY_BINDING);
|
||||
|
||||
for (DefaultBinding binding : defaults)
|
||||
{
|
||||
int* slot = std::ranges::find(bindings[binding.action], -1);
|
||||
if (slot == bindings[binding.action].end()) log_printf(LOG_ASSERT, "Mapping slot overflow\n");
|
||||
else *slot = binding.input;
|
||||
}
|
||||
return bindings;
|
||||
}
|
||||
|
||||
// 004307c0 Sets the engine's default input bindings, the controller's in GLFW's button numbers, before KAGE starts.
|
||||
// Its window parameters are this file's constants. Its Epic Online Services keys and options.ini's EnableEpicOverlay
|
||||
// are online, and its heap size has no heap to size, so they are left out.
|
||||
void Platform::bindings_load()
|
||||
{
|
||||
if (isEngineInitialized)
|
||||
return log_printf(LOG_ASSERT, "SetEngineParameters must be called before calling KAGE::Initialize\n");
|
||||
|
||||
std::vector<DefaultBinding> controller(std::begin(CONTROLLER_DEFAULTS), std::end(CONTROLLER_DEFAULTS));
|
||||
for (DefaultBinding& binding : controller)
|
||||
for (DefaultBinding button : PLATFORM_BUTTONS)
|
||||
if (binding.input == button.action) binding.input = button.input;
|
||||
|
||||
bindings = {bindings_build(controller), bindings_build(KEYBOARD_DEFAULTS), CONTROLLER_COUNT};
|
||||
}
|
||||
|
||||
// 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).
|
||||
// 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.
|
||||
void Platform::engine_init()
|
||||
{
|
||||
std::srand((unsigned int)(GetTimeNs() / SDL_NS_PER_MS));
|
||||
if (isEngineInitialized) log_printf(LOG_ASSERT, "KAGE has already been initialized\n");
|
||||
if (!graphics_init()) return;
|
||||
|
||||
// The sound manager was a global object. The OpenAL Soft device hooks after it have no place on SDL audio.
|
||||
(new KAGE::Sound::ManagerOpenAL())->FUN_00a649b0();
|
||||
if (!FUN_00a21980() || !FUN_00a8c430()) return;
|
||||
|
||||
isEngineInitialized = true;
|
||||
}
|
||||
|
||||
// Opens the window, shows it, then builds the renderer's built-in shaders and starting state.
|
||||
// This is Graphics::Manager::Init at 00a18e90, whose stub stays for the generated vtable.
|
||||
bool Platform::graphics_init()
|
||||
{
|
||||
if (!SDL_Init(SDL_INIT_VIDEO)) log_printf(LOG_ASSERT, "SDL failed to initialize: %s\n", SDL_GetError());
|
||||
|
||||
window_size_set({WINDOW_WIDTH, WINDOW_HEIGHT});
|
||||
viewportSize = windowSize;
|
||||
if (!window_create()) return false;
|
||||
SDL_ShowWindow(window);
|
||||
SDL_RaiseWindow(window);
|
||||
|
||||
for (const ShaderSource& shader : SHADERS)
|
||||
FUN_00a13fa0((uint8_t*)shader.name, (void*)shader.attributes, (void*)&shader);
|
||||
state_reset();
|
||||
KAGE_Graphics().SetRenderTarget(nullptr, 1);
|
||||
// The renderer's vertex buffer (a GraphicsBufferObject the original keeps at DAT_00c7367c) and its black clear
|
||||
// color come next, with the renderer.
|
||||
new KAGE::Graphics::GraphicsBufferObject();
|
||||
FUN_00a18460(0, 0, 0);
|
||||
g_imageReleaseFn = (void*)&FUN_00a12240;
|
||||
g_renderTargetReleaseFn = (void*)&FUN_00a12240;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 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.
|
||||
// The Win32 icon and the maximize box it removes have no SDL counterpart.
|
||||
bool Platform::window_create()
|
||||
{
|
||||
SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
|
||||
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, DEPTH_BITS);
|
||||
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, STENCIL_BITS);
|
||||
window = SDL_CreateWindow(WINDOW_TITLE, windowSize.width, windowSize.height, WINDOW_FLAGS);
|
||||
for (int major : GL_MAJOR_VERSIONS)
|
||||
{
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
|
||||
if (window && (context = SDL_GL_CreateContext(window))) break;
|
||||
}
|
||||
// The original carries on without a context and crashes in its first GL call. This stops instead.
|
||||
if (!context)
|
||||
{
|
||||
log_printf(LOG_ASSERT, "Failed to create OpenGL window / context: %s\n", SDL_GetError());
|
||||
return false;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// Puts back the GL state the renderer expects: the vsync setting, blending, depth testing toward the viewer from a
|
||||
// cleared depth of -1000, and back faces culled (Graphics::Manager slot 30, 00a19b60).
|
||||
void Platform::state_reset()
|
||||
{
|
||||
vsync_apply();
|
||||
gl.Enable(GL_BLEND);
|
||||
gl.Enable(GL_DEPTH_TEST);
|
||||
gl.Enable(GL_CULL_FACE);
|
||||
gl.ClearDepth(CLEAR_DEPTH);
|
||||
gl.DepthFunc(GL_GREATER);
|
||||
gl.CullFace(GL_BACK);
|
||||
}
|
||||
|
||||
// 00a1a470 Swaps on the display's refresh when vsync is on.
|
||||
void Platform::vsync_apply()
|
||||
{
|
||||
SDL_GL_SetSwapInterval(isVsync ? 1 : 0);
|
||||
}
|
||||
|
||||
// The window's drawable size in pixels (Graphics::Manager slots 12 and 13, 00a19340 and 00a193c0).
|
||||
Size Platform::framebuffer_size_get()
|
||||
{
|
||||
Size size;
|
||||
SDL_GetWindowSizeInPixels(window, &size.width, &size.height);
|
||||
return size;
|
||||
}
|
||||
|
||||
// 00a18750 Gives the framebuffer a depth renderbuffer at the powers of two at or above the drawing size, 8 at least,
|
||||
// keeping the one it has while that is big enough.
|
||||
// The drawing size falls back to the window's. A bound render target's would come first, once render targets exist.
|
||||
void Platform::depth_renderbuffer_update(RenderbufferMode mode)
|
||||
{
|
||||
Size drawable = framebuffer_size_get();
|
||||
int width = drawingSize.width > 0 ? drawingSize.width : drawable.width;
|
||||
int height = drawingSize.height > 0 ? drawingSize.height : drawable.height;
|
||||
|
||||
if (mode == RENDERBUFFER_KEEP && depthRenderbuffer != 0)
|
||||
{
|
||||
int currentHeight = 0;
|
||||
int currentWidth = 0;
|
||||
|
||||
gl.BindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer);
|
||||
gl.GetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, ¤tWidth);
|
||||
gl.GetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, ¤tHeight);
|
||||
if (width <= currentWidth && height <= currentHeight) return;
|
||||
}
|
||||
if (depthRenderbuffer != 0) gl.DeleteRenderbuffers(1, &depthRenderbuffer);
|
||||
width = (int)std::bit_ceil((unsigned int)std::max(width, RENDERBUFFER_MIN_SIZE));
|
||||
height = (int)std::bit_ceil((unsigned int)std::max(height, RENDERBUFFER_MIN_SIZE));
|
||||
|
||||
int previous = 0;
|
||||
gl.GetIntegerv(GL_FRAMEBUFFER_BINDING, &previous);
|
||||
gl.BindFramebuffer(GL_FRAMEBUFFER, framebuffer);
|
||||
gl.GenRenderbuffers(1, &depthRenderbuffer);
|
||||
log_printf(LOG_INFO, "Renderbuffer ID: %d size %dx%d\n", depthRenderbuffer, width, height);
|
||||
gl.BindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer);
|
||||
gl.RenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
|
||||
gl.FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer);
|
||||
gl.BindFramebuffer(GL_FRAMEBUFFER, previous);
|
||||
}
|
||||
|
||||
// Sets the GL viewport to the game's viewport, at its offset when it has one.
|
||||
void Platform::viewport_reset()
|
||||
{
|
||||
SDL_FPoint offset = isViewportOffset ? viewportOffset : SDL_FPoint{};
|
||||
gl.Viewport((int)offset.x, (int)offset.y, viewportSize.width, viewportSize.height);
|
||||
}
|
||||
|
||||
// 00a19450 Resizes the window unless it has that size already. In fullscreen it keeps the size for later and warns.
|
||||
void Platform::window_size_set(Size size)
|
||||
{
|
||||
if (size == windowSize) return;
|
||||
|
||||
windowSize = size;
|
||||
if (isFullscreen) log_printf(LOG_WARN, "Setting size of window while in fullscreen, is this intended?\n");
|
||||
else if (window) SDL_SetWindowSize(window, size.width, size.height);
|
||||
}
|
||||
|
||||
// Moves the window, as GLFW's glfwSetWindowPos.
|
||||
void Platform::window_position_set(SDL_Point position)
|
||||
{
|
||||
SDL_SetWindowPosition(window, position.x, position.y);
|
||||
}
|
||||
|
||||
// 00a196b0 Switches between the window and fullscreen, at the display's own mode when exclusive, then tells the size
|
||||
// listeners and resets the viewport, projection and depth buffer. The cursor hides in fullscreen.
|
||||
// The original fakes borderless fullscreen with a topmost window a pixel wider than the display. SDL's desktop
|
||||
// fullscreen does that job.
|
||||
void Platform::fullscreen_set(FullscreenMode mode)
|
||||
{
|
||||
bool isWanted = mode != FULLSCREEN_OFF;
|
||||
if (isWanted == isFullscreen) return;
|
||||
|
||||
const SDL_DisplayMode* displayMode = SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(window));
|
||||
isFullscreen = isWanted;
|
||||
SDL_SetWindowFullscreenMode(window, mode == FULLSCREEN_EXCLUSIVE ? displayMode : nullptr);
|
||||
SDL_SetWindowFullscreen(window, isFullscreen);
|
||||
if (!isFullscreen)
|
||||
{
|
||||
SDL_SetWindowSize(window, viewportSize.width, viewportSize.height);
|
||||
window_position_set(windowPosition);
|
||||
}
|
||||
SDL_ShowWindow(window);
|
||||
SDL_RaiseWindow(window);
|
||||
SDL_SyncWindow(window);
|
||||
|
||||
Size size;
|
||||
SDL_GetWindowSize(window, &size.width, &size.height);
|
||||
for (auto& listener : sizeListeners) listener(size);
|
||||
viewport_reset();
|
||||
KAGE_Graphics().update_projection();
|
||||
depth_renderbuffer_update(RENDERBUFFER_KEEP);
|
||||
isFullscreen ? SDL_HideCursor() : SDL_ShowCursor();
|
||||
}
|
||||
|
||||
// Takes the window's events as GLFW's callbacks did: closing asks the game to quit, and a new size (00a19bf0),
|
||||
// position or focus goes to its listeners and resets what depends on it.
|
||||
// Win32's topmost-while-focused fullscreen window has no SDL counterpart.
|
||||
void Platform::events_poll()
|
||||
{
|
||||
SDL_Event event;
|
||||
|
||||
while (SDL_PollEvent(&event))
|
||||
{
|
||||
switch (event.type)
|
||||
{
|
||||
case SDL_EVENT_QUIT:
|
||||
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
|
||||
isQuitRequested = true;
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_RESIZED:
|
||||
if (event.window.data1 == 0 || event.window.data2 == 0) break;
|
||||
windowSize = {event.window.data1, event.window.data2};
|
||||
for (auto& listener : sizeListeners) listener(windowSize);
|
||||
viewport_reset();
|
||||
depth_renderbuffer_update(RENDERBUFFER_KEEP);
|
||||
KAGE_Graphics().update_projection();
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_MOVED:
|
||||
for (auto& listener : positionListeners) listener({event.window.data1, event.window.data2});
|
||||
if (isFullscreen) break;
|
||||
windowPosition = {event.window.data1, event.window.data2};
|
||||
viewport_reset();
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_FOCUS_GAINED:
|
||||
case SDL_EVENT_WINDOW_FOCUS_LOST:
|
||||
for (auto& listener : focusListeners) listener(event.type == SDL_EVENT_WINDOW_FOCUS_GAINED);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 00a266a0 Seconds since the platform started, as glfwGetTime.
|
||||
double Platform::time_get()
|
||||
{
|
||||
return (double)SDL_GetTicksNS() / SDL_NS_PER_SECOND;
|
||||
}
|
||||
|
||||
// Starts a frame and returns the frame rate the time since the last one makes, rounded. A long run of short frames
|
||||
// (vsync on a faster display) forces the 60 Hz pacing on.
|
||||
int Platform::frame_begin()
|
||||
{
|
||||
double now = time_get();
|
||||
double frameTime = now - frameStart;
|
||||
|
||||
frameStart = now;
|
||||
if (FRAME_TIME / frameTime <= SHORT_FRAME_RATIO) shortFrameCount = 0;
|
||||
else if (++shortFrameCount > PACING_SWITCH_FRAMES)
|
||||
{
|
||||
isPacingForced = true;
|
||||
fullFrameCount = 0;
|
||||
}
|
||||
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.
|
||||
// The original spins without sleeping while a cutscene video is behind (0095dee0). No video plays yet.
|
||||
void Platform::frame_wait()
|
||||
{
|
||||
if (!isPacingForced && isVsync) return;
|
||||
|
||||
int sleepMs = std::max((int)((FRAME_TIME - (time_get() - frameStart)) * MS_PER_SECOND) - 1, 0);
|
||||
if (sleepMs > 0)
|
||||
{
|
||||
fullFrameCount = 0;
|
||||
SDL_DelayNS(sleepMs * SDL_NS_PER_MS);
|
||||
}
|
||||
else if (++fullFrameCount > PACING_SWITCH_FRAMES)
|
||||
{
|
||||
isPacingForced = false;
|
||||
shortFrameCount = 0;
|
||||
}
|
||||
while (time_get() - frameStart < FRAME_TIME) {}
|
||||
}
|
||||
|
||||
// Applies one window option, as the OptionsConfig setters did: windowed again, the window takes back its saved size,
|
||||
// position and cursor. Vsync stays off for the session on a display not running at a multiple of 60 Hz.
|
||||
void window_apply(OptionsConfig& options, WindowSetting setting)
|
||||
{
|
||||
switch (setting)
|
||||
{
|
||||
case WINDOW_CURSOR:
|
||||
options.isMouseControlEnabled ? SDL_HideCursor() : SDL_ShowCursor();
|
||||
break;
|
||||
case WINDOW_FULLSCREEN:
|
||||
if (!options.isFullscreen) platform.fullscreen_set(FULLSCREEN_OFF);
|
||||
else platform.fullscreen_set(options.isExclusiveFullscreen ? FULLSCREEN_EXCLUSIVE : FULLSCREEN_BORDERLESS);
|
||||
if (options.isFullscreen) break;
|
||||
platform.window_size_set({options.windowWidth, options.windowHeight});
|
||||
platform.window_position_set({options.windowPosX, options.windowPosY});
|
||||
window_apply(options, WINDOW_CURSOR);
|
||||
break;
|
||||
case WINDOW_POSITION:
|
||||
platform.window_position_set({options.windowPosX, options.windowPosY});
|
||||
break;
|
||||
case WINDOW_VSYNC:
|
||||
{
|
||||
const SDL_DisplayMode* display = SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(platform.window));
|
||||
int hz = display ? (int)display->refresh_rate : 0;
|
||||
float cycles = 0;
|
||||
float fraction = std::modf((float)hz / TARGET_HZ, &cycles);
|
||||
bool isVsync = options.isVsyncEnabled;
|
||||
|
||||
if (isVsync && std::min(fraction, 1 - fraction) > REFRESH_TOLERANCE)
|
||||
{
|
||||
log_printf(LOG_INFO, "Display Hz: %d, Target: 60.. disabling vsync for this session.\n", hz);
|
||||
isVsync = false;
|
||||
}
|
||||
if (isVsync == platform.isVsync) break;
|
||||
platform.isVsync = isVsync;
|
||||
platform.vsync_apply();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
Reference in new issue
Block a user