Files
isaac-port/src/game.cpp
T

916 lines
39 KiB
C++

#include "game.h"
#include "data.h"
#include "entity_player.h"
#include "log.h"
#include "manager.h"
#include "lua_engine.h"
#include "menu_manager.h"
#include "render_passes.h"
#include "room.h"
#include "room_transition.h"
#include "victory_run_prompt.h"
#include <algorithm>
#include <cmath>
#include <numbers>
#include <optional>
constexpr const char* STAGES_XML = "stages.xml";
constexpr const char* CURSES_XML = "curses.xml";
constexpr const char* MINIBOSSES_XML = "minibosses.xml";
constexpr const char* GIANTBOOK_XML = "giantbook.xml";
constexpr const char* BOSS_OVERLAYS_XML = "bossoverlays.xml";
constexpr const char* AMBUSH_XML = "ambush.xml";
constexpr const char* ITEM_POOLS_XML = "itempools.xml";
constexpr const char* PRELOAD_XML = "preload.xml";
constexpr std::array<std::string_view, 4> PRELOAD_GROUPS = {"common", "enemy", "pickups", "icons"};
constexpr const char* COMPLETION_WIDGET_ANM2 = "gfx/ui/completion_widget.anm2";
constexpr const char* COMPLETION_WIDGET_ANIMATION = "Idle";
constexpr const char* GIANTBOOK_CLICKER_PNG = "gfx/ui/giantbook/GiantBook_Clicker.png";
constexpr const char* PIXELATION_SURFACE = "Pixelation Surface";
constexpr const char* BLOOM_SURFACE = "Bloom Surface";
constexpr const char* OLD_TV_SURFACE = "Old TV Surface";
constexpr const char* HALLUCINATION_SURFACE = "Hallucination Surface";
constexpr const char* HALLUCINATION_SNAPSHOT = "Hallucination Snapshot";
constexpr const char* COLORMOD_SURFACE = "Colormod Surface";
constexpr int FILTER_NEAREST = 0;
constexpr int FILTER_LINEAR = 1;
constexpr int BLOOM_DURATION_DEFAULT = 30;
constexpr int REVIVE_MACHINE_COINS = 10;
constexpr float DIZZY_CHANGE_SPEED_DEFAULT = 0.001f;
constexpr int BOSS_RUSH_PAR_TIME = 36000;
constexpr int BLUE_WOMB_PAR_TIME = 54000;
constexpr float COLOR_CHANNEL_MAX = 255;
// The attributes of a giant book layer's tint channels.
constexpr std::array<std::string_view, 4> TINT_ATTRIBUTES = {"r", "g", "b", "a"};
constexpr int DIMENSION_DEATH_CERTIFICATE = 2;
// The fortune generator's xorshift (shift index 35), the start's fade in speed, and the cover an instant fade starts on.
constexpr uint32_t FORTUNE_RNG_SHIFT = 35;
constexpr float START_FADE_SPEED = 0.04f;
constexpr float FADE_IN_ALPHA_INSTANT = 1e-05f;
constexpr int STAGE_ID_DEATH_CERTIFICATE = 35;
// How a co-op award is decided, beside its name.
struct CoopAwardRule
{
float threshold = 1;
int minimumFirstStat = 0;
int statId = COOP_STAT_NONE;
bool isTieShared = true;
bool isMostWins = true;
};
// The co-op awards' rules, in the order of COOP_AWARD_KEYS.
constexpr std::array<CoopAwardRule, COOP_AWARD_COUNT> COOP_AWARD_RULES = {{{1, 0, 21},
{1, 2, 7, true, false},
{1, 0, 4},
{2, 0, 10},
{12, 2, 2, false, false},
{3, 0, 12},
{20, 0, 15},
{5, 0, 20},
{5, 0, 19},
{10, 0, 8},
{3, 0, 18},
{3, 0, 16},
{2, 0, 9},
{20, 0, 11},
{3, 0, 1},
{5, 0, 5},
{5, 0, 6},
{31, 0, 13},
{10, 0, 14},
{1, 1, 3},
{1000, 1, 17, true, false}}};
// 00425b70 Names the co-op awards in the current language and sets how each is decided.
void coop_awards_load(std::array<CoopAward, COOP_AWARD_COUNT>& awards)
{
for (int i = 0; i < COOP_AWARD_COUNT; i++)
{
const CoopAwardRule& rule = COOP_AWARD_RULES[i];
CoopAward& award = awards[i];
award.name = g_manager->stringTable.translate(COOP_AWARD_KEYS[i]);
award.statId = rule.statId;
award.isTieShared = rule.isTieShared;
award.isMostWins = rule.isMostWins;
award.threshold = rule.threshold;
award.minimumFirstStat = rule.minimumFirstStat;
}
}
// 006f1020 Starts the floor with an empty room, names the co-op awards, draws the versus rules, and creates the run's
// render surfaces and the loaded mods' shader targets.
Game::Game()
{
fadeInColor = kcolor_make(1, 1, 1, 1);
fadeOutColor = kcolor_make(1, 1, 1, 1);
level_reset();
coop_awards_load(coopAwards);
deathmatchManager.Reset();
// ChallengeParam::Reset on dailyChallenge's params waits for DailyChallenge's takeover (classes.h has bytes).
create_render_surfaces();
g_manager->modManager.create_shader_render_targets();
}
Game::~Game()
{
reconstruction_missing("Game::~Game 006f3060");
}
// 006f4740 Resets the run, then loads the run's configs through the mods' redirection: stages, curses with the mods',
// minibosses, the giant books and boss overlays, the run's UI, the Boss Rush waves, the preloads and their groups, the
// procedural item surfaces, par times and prompts, then empties the online stats and the console.
void Game::LoadConfigXmls()
{
Game& game = *g_game;
ModManager& mods = g_manager->modManager;
game.reset_run_state();
game.challenge = 0;
game.isRerun = false;
game.screenShakeOffset = {};
game.isPocketItemRewindSaved = false;
game.trapdoorLoopVolume = 0;
game.roomConfig.LoadStages(mods.TryRedirectPath(STAGES_XML));
game.roomConfig.LoadCurses(mods.TryRedirectPath(CURSES_XML), CURSES_REPLACE);
mods.LoadModCurses();
game.roomConfig.LoadMinibosses(mods.TryRedirectPath(MINIBOSSES_XML));
game.load_giantbook_xml(mods.TryRedirectPath(GIANTBOOK_XML));
game.load_bossoverlays_xml(mods.TryRedirectPath(BOSS_OVERLAYS_XML));
// The original also zeroes GameOver's second int and the ints at Game+0x1d63c and Game+0x1d64c, not modeled yet.
game.gameOver.state = GAME_OVER_HIDDEN;
game.gameOver.isStopSoundsPending = false;
game.leaderboard.LoadAnm2();
game.emoteWheel.Init();
game.onlineStatsScreen.Load();
game.hud.graphics_reload();
game.pauseScreen.Init();
game.revivePlayerMenu.Init();
game.minimap.Init();
LoadBossRushXml(mods.TryRedirectPath(AMBUSH_XML));
game.preloadManager.xml_load(mods.TryRedirectPath(PRELOAD_XML));
for (std::string_view group : PRELOAD_GROUPS) game.preloadManager.group_load(group);
game.proceduralItemManager.Init();
game.bossRushParTime = BOSS_RUSH_PAR_TIME;
game.blueWombParTime = BLUE_WOMB_PAR_TIME;
game.genericPrompt.Initialize(PROMPT_LARGE);
victory_run_prompt_load(game.genericPrompt);
game.completionWidgetSprite.Load(COMPLETION_WIDGET_ANM2, GRAPHICS_LOAD);
game.completionWidgetSprite.SetFrame(COMPLETION_WIDGET_ANIMATION, 0);
if (!game.giantBookClickerImage)
{
game.giantBookClickerImage = Manager::LoadImage(GIANTBOOK_CLICKER_PNG);
KAGE::Graphics::ImageBase& clicker = *game.giantBookClickerImage;
if (clicker.minFilter != FILTER_NEAREST || clicker.magFilter != FILTER_NEAREST)
clicker.filter_set(FILTER_NEAREST, FILTER_NEAREST);
}
game.onlinePlayerStats._end = game.onlinePlayerStats._begin;
for (CoopAward& award : game.coopAwards) award.userIds.clear();
game.isOnlineStatsFinalized = false;
game.console.reset();
}
// An attribute when the element has it, empty or not.
static std::optional<std::string_view> attr_find(DataNode node, std::string_view name)
{
std::string_view value;
if (node["attrs"][name].get(value) != simdjson::SUCCESS) return std::nullopt;
return value;
}
// An attribute as the game reads booleans: "true", "True" or a nonzero number.
static bool attr_bool(std::string_view value)
{
return value == "true" || value == "True" || std::atoi(value.data()) != 0;
}
// The first element of a document with a tag, as rapidxml's first_node finds it.
static std::optional<DataNode> root_find(const Data& data, std::string_view tag)
{
if (node_tag(data.root) == tag) return data.root;
for (DataNode node : node_children(data.root))
if (node_tag(node) == tag) return node;
return std::nullopt;
}
// 009abe70 Reads giantbook.xml into the giant book table, after stopping the item overlay. Each entry's paths are under
// the root's anm2root, and its layers are recolored by 0 to 255 channels. An entry without an id takes the one before
// it, and ids from 48 on are skipped. False when the file is missing.
// The original crashes on a file without its root element or anm2root. Here those read as empty.
bool Game::load_giantbook_xml(std::string_view path)
{
Data data;
int id = GIANTBOOK_ENTRY_COUNT;
itemOverlay.state = ITEM_OVERLAY_INACTIVE;
itemOverlay.delay = 0;
data_load(data, path);
if (!data.isLoaded) return false;
std::optional<DataNode> root = root_find(data, "giantbook");
if (!root) return true;
std::string anm2Root(node_attr(*root, "anm2root"));
for (DataNode node : node_children(*root))
{
if (node_tag(node) != "entry") continue;
GiantbookEntry entry;
if (auto text = attr_find(node, "id")) id = std::atoi(text->data());
if (auto text = attr_find(node, "anm2")) entry.anm2Path = anm2Root + std::string(*text);
if (auto text = attr_find(node, "anim")) entry.animation = *text;
if (auto text = attr_find(node, "gfx")) entry.gfxPath = anm2Root + std::string(*text);
for (DataNode layerNode : node_children(node))
{
if (node_tag(layerNode) != "layer") continue;
GiantbookLayer layer;
float* tint = layer.color._tint;
std::fill(tint, tint + TINT_ATTRIBUTES.size(), 1.0f);
layer.name = node_attr(layerNode, "name");
for (size_t channel = 0; channel < TINT_ATTRIBUTES.size(); channel++)
if (auto text = attr_find(layerNode, TINT_ATTRIBUTES[channel]))
tint[channel] = (float)std::atoi(text->data()) / COLOR_CHANNEL_MAX;
if (!layer.name.empty()) entry.layers.push_back(layer);
}
entry.id = id;
if ((unsigned)id < GIANTBOOK_ENTRY_COUNT) giantbookEntries[id] = std::move(entry);
}
return true;
}
// 00420ba0 Reads bossoverlays.xml into the boss overlay table, after stopping the boss overlay. Each entry's .anm2 is
// under the root's anm2root, and ids past 4 are skipped. False when the file is missing.
// The original crashes on a file without its root element or anm2root. Here those read as empty.
bool Game::load_bossoverlays_xml(std::string_view path)
{
Data data;
bossOverlay._state = 0;
data_load(data, path);
if (!data.isLoaded) return false;
std::optional<DataNode> root = root_find(data, "bossoverlay");
if (!root) return true;
std::string anm2Root(node_attr(*root, "anm2root"));
for (DataNode node : node_children(*root))
{
if (node_tag(node) != "entry") continue;
BossOverlayEntry entry;
if (auto text = attr_find(node, "id")) entry.id = std::atoi(text->data());
if (auto text = attr_find(node, "anm2")) entry.anm2Path = anm2Root + std::string(*text);
if (auto text = attr_find(node, "anim")) entry.animation = *text;
if (auto text = attr_find(node, "persist")) entry.isPersistent = attr_bool(*text);
if ((unsigned)entry.id < BOSS_OVERLAY_COUNT) bossOverlayEntries[entry.id] = std::move(entry);
}
return true;
}
// A boss a Boss Rush spawn slot holds: its type and variant, and the segments of a segmented boss.
struct BossRushSpawn
{
int chunks = 1;
int type = 0;
int variant = 0;
};
// ambush.xml's Boss Rush: the bosses of each spawn slot, how many waves it lasts and how many slots each wave draws.
// The original keeps them in Ambush, which classes.h holds as bytes. They move there with its takeover.
struct BossRushConfig
{
std::vector<std::vector<BossRushSpawn>> slots;
int numWaves = 0;
int spawnsPerWave = 0;
};
static BossRushConfig bossRushConfig;
// 00834680 Reads ambush.xml's <bossrush> into the Boss Rush: its wave counts, then from its first <spawn> on, a slot
// for each element, holding from its first <enemy> on each element's boss count times. A missing file changes nothing.
// The original crashes on a file without <bossrush>. Here that leaves the Boss Rush empty.
void Game::LoadBossRushXml(std::string_view path)
{
Data data;
data_load(data, path);
if (!data.isLoaded) return;
bossRushConfig = {};
std::optional<DataNode> root = root_find(data, "bossrush");
if (!root) return;
bossRushConfig.numWaves = std::atoi(node_attr(*root, "numWaves").data());
bossRushConfig.spawnsPerWave = std::atoi(node_attr(*root, "spawnsPerWave").data());
bool isSlotStarted = false;
for (DataNode slotNode : node_children(*root))
{
isSlotStarted = isSlotStarted || node_tag(slotNode) == "spawn";
if (!isSlotStarted) continue;
std::vector<BossRushSpawn>& slot = bossRushConfig.slots.emplace_back();
bool isEnemyStarted = false;
for (DataNode enemyNode : node_children(slotNode))
{
isEnemyStarted = isEnemyStarted || node_tag(enemyNode) == "enemy";
if (!isEnemyStarted) continue;
BossRushSpawn spawn;
int count = 1;
spawn.type = std::atoi(node_attr(enemyNode, "type").data());
spawn.variant = std::atoi(node_attr(enemyNode, "variant").data());
if (auto text = attr_find(enemyNode, "chunks")) spawn.chunks = std::atoi(text->data());
if (auto text = attr_find(enemyNode, "count")) count = std::atoi(text->data());
slot.insert(slot.end(), std::max(count, 0), spawn);
}
}
}
// 006f43b0 Clears the run back to a fresh one: counters, fades, debug flags, the daily, score sheet and screen effects.
void Game::reset_run_state()
{
isRerun = false;
isDebug = false;
frameCount = 0;
timeCounter = 0;
screenShakeTimer = 0;
ResetState();
freezeFrames = 0;
fadeInColor = {};
fadeOutColor = {};
debugFlags = 0;
debugCurses = 0;
fadeOutTarget = 0;
restartHoldFrames = 0;
framesSinceRoomTransition = 0;
dailyChallenge._id = 0;
dailyChallenge._seed = 0;
dailyChallenge._specialDailyId = 0;
dailyChallenge._isPractice = false;
// ChallengeParam::Reset on dailyChallenge's params waits for DailyChallenge's takeover (classes.h has bytes).
scoreSheet.Reset();
currentColorModifier = COLOR_MOD_NEUTRAL;
pixelationDuration = 0;
pixelationTimer = 0;
isStartingFromState = false;
isColorModifierLerped = false;
lightningIntensity = 0;
dizzyIntensity = 0;
dizzyTargetIntensity = 0;
dizzyIntensityChangeSpeed = DIZZY_CHANGE_SPEED_DEFAULT;
isRoomRespawned = false;
magicSkinUses = 0;
erasedEntities.clear();
isPocketItemRewindSaved = false;
}
// 006f4520 Clears what a run counts across floors: deals, visits, donations, effects, bosses met, the backwards path's
// saved rooms and the Glowing Hourglass states.
void Game::ResetState()
{
lastDevilRoomStage = 0;
treasureRoomsVisited = 0;
planetariumsVisited = 0;
stagesWithoutHeartsPicked = 0;
stagesWithoutDamage = 0;
devilRoomDeals = 0;
donationModGreed = 0;
donationModAngel = 0;
lastLevelWithoutHalfHp = 0;
isRoomSnapshotTaken = false;
shopVisits = 0;
bloomTimer = 0;
bloomDuration = BLOOM_DURATION_DEFAULT;
bloomStrength = 1;
hallucinationDuration = 0;
hallucinationTimer = 0;
framesSinceRoomTransition = 0;
gameStateFlags = 0;
ascentTimer = 0;
for (BackwardsStageDesc& backwards : backwardsStages)
{
backwards.isXL = false;
backwards.bossRooms.clear();
backwards.treasureRooms.clear();
}
deathCertificateExitTimer = 0;
darknessTimeout = 0;
darknessModifier = 0;
darknessStrength = 0;
stageNameNumeral = 1;
victoryLap = 0;
lastLevelWithDamage = 0;
encounteredBosses.clear();
isStoringGlowingHourglassState = false;
isRestoringGlowingHourglassState = false;
currentGlowingHourglassSlot = -1;
rewindsThisFloor = 0;
for (GlowingHourglassState& state : glowingHourglassStates) state.isUsable = false;
isPocketItemRewindSaved = false;
reviveMachineUses = 0;
reviveMachineCoinsLeft = REVIVE_MACHINE_COINS;
}
// 007384d0 Replaces the current room with a new one and clears the floor: no rooms, stage, curses or Greed waves.
void Game::level_reset()
{
room.reset();
room = std::make_unique<Room>();
startingRoomIdx = -1;
nbRooms = 0;
stage = 0;
stageType = 0;
curses = 0;
greedModeWave = 0;
greedWaveSeeds = {};
greedLastBeatenWave = 0;
greedLastPaidWave = 0;
}
// Creates a surface of the framebuffer's size with linear filtering, unless it exists.
static void surface_create(KAGE::Graphics::ImagePtr& surface, const char* name)
{
if (surface) return;
surface = KAGE::Graphics::manager.render_target_create({kcolor_make(0, 0, 0, 0), name, (int)DAT_00c79114,
g_framebufferWidth});
if (surface->minFilter != FILTER_LINEAR || surface->magFilter != FILTER_LINEAR)
surface->filter_set(FILTER_LINEAR, FILTER_LINEAR);
}
// 006f37e0 Creates the run's effect surfaces that do not exist yet: pixelation, bloom (when enabled), old TV,
// hallucination and its snapshot, and the color modifier's.
void Game::create_render_surfaces()
{
surface_create(pixelationSurface, PIXELATION_SURFACE);
if (g_manager->optionsConfig.render.isBloomEnabled) surface_create(bloomSurface, BLOOM_SURFACE);
surface_create(oldTvSurface, OLD_TV_SURFACE);
surface_create(hallucinationSurface, HALLUCINATION_SURFACE);
surface_create(hallucinationSnapshot, HALLUCINATION_SNAPSHOT);
surface_create(colormodSurface, COLORMOD_SURFACE);
}
// 006f5320 Starts a new run on a character, challenge, seeds and difficulty: the run's seeds (a challenge's own
// effects), whether progress is frozen, the item and boss pools, the player, the first floor (Backasswards' Dark Room),
// then saves it, fades in from black and runs the first room's update and the mods' game start.
void Game::Start(int playerType, uint32_t startChallenge, const Seeds& seeds, Difficulty startDifficulty)
{
Manager& manager = *g_manager;
isStarted = true;
onlinePlayerStats._end = onlinePlayerStats._begin;
for (CoopAward& award : coopAwards) award.userIds.clear();
isOnlineStatsFinalized = false;
difficulty = startDifficulty;
challenge = startChallenge;
trapdoorLoopVolume = 0;
victoryLap = 0;
isConsoleUsedThisRun = manager.isConsoleEnabled;
hud.LoadGraphics();
if (seeds.gameStartSeed == 0) log_printf(LOG_ASSERT, "Start seed is not initialized");
seedEffects = seeds;
if (challenge != 0)
{
seedEffects.ClearSeedEffects();
for (int effect : GetChallengeParams().seedEffects) seedEffects.AddSeedEffect(effect);
}
fortuneRNG.SetSeed(seedEffects.GetNextSeed(), FORTUNE_RNG_SHIFT);
bool isReadOnly = seedEffects.isCustomRun || seedEffects.AchievementUnlocksDisallowed() ||
Manager::AchievementUnlocksDisallowed() || isRerun || challenge != 0;
manager.persistentGameData.SetReadOnly(isReadOnly);
uint32_t startSeed = seedEffects.GetStartSeed();
std::string seedText = Seeds::Seed2String(seedEffects.GetStartSeed());
log_printf(LOG_INFO, "RNG Start Seed: %s (%u) [New, %d]\n", seedText.c_str(), startSeed, manager.currentSaveSlot);
proceduralItemManager.Init();
std::string itemPoolsPath = manager.modManager.TryRedirectPath(ITEM_POOLS_XML);
itemPool.Init(seedEffects.GetNextSeed(), itemPoolsPath);
bossPool.init(seedEffects.GetStartSeed());
playerManager.init_main_player(playerType, seedEffects.GetPlayerInitSeed());
SetNextStage();
if (challenge == CHALLENGE_BACKASSWARDS) SetStage(STAGE_DARK_ROOM, STAGETYPE_ORIGINAL);
Init(true);
std::vector<Entity_Player*> players = playerManager.playerList;
for (Entity_Player* player : players)
if (player->variant == PLAYER_VARIANT_PLAYER) player->InitPostLevelInitStats();
Manager::save_game_state();
playerManager.trigger_new_room_effects();
Fadein(START_FADE_SPEED, FADE_ICON_SHOW, kcolor_rgba(0, 0, 0, 1));
pause_screen_reset(pauseScreen);
encounteredBosses.clear();
room->Update();
framesSinceRoomTransition = 0;
lua_engine_get().PostGameStart(false);
}
// 006f5210 Fades the screen in from a color at a speed, from full (or nearly no) cover as the instant fade asks, with
// or without the loading icon. The players cannot move until it ends.
void Game::Fadein(float speed, FadeIcon icon, KColor color)
{
fadeInColor = color;
fadeInColor._alpha = isInstantFadeIn ? FADE_IN_ALPHA_INSTANT : 1;
fadeSpeed = speed;
isFadeInIconShown = icon == FADE_ICON_SHOW;
for (Entity_Player* player : playerManager.playerList) player->isControlsEnabled = false;
}
// 009b5cb0 Closes the pause screen for a new run on Resume, with its paper's animation stopped, the options listed
// again, My Stuff closed and the quit prompt reset.
// The original also stops the full-size paper and resets fields of it, which pause_screen.h leaves out.
void pause_screen_reset(PauseScreen& pauseScreen)
{
pauseScreen.state = PAUSE_HIDDEN;
pauseScreen.selectedElement = PAUSE_ITEM_RESUME;
pauseScreen.menuSprite.animState.SetAnimationData(nullptr);
pauseScreen.menuOptions.load_graphics();
pauseScreen.myStuff.reset();
pauseScreen.genericPrompt.Initialize(PROMPT_SMALL);
}
void Game::Exit(bool)
{
reconstruction_missing("Game::Exit 006fa0c0");
}
constexpr const char* BLOOM_SHADER = "Bloom";
constexpr const char* COLOR_MOD_SHADER = "ColorMod";
constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset";
constexpr const char* HALLUCINATION_SHADER = "Hallucination";
constexpr const char* OLD_TV_SHADER = "OldTV";
constexpr const char* PIXELATION_SHADER = "Pixelation";
constexpr const char* SCREEN_SIZE_UNIFORM = "ScreenSize";
constexpr KColor SCREEN_WHITE = kcolor_rgba(1, 1, 1, 1);
constexpr RNG ROOM_SNAPSHOT_RNG = {0, 9, 5, 25};
constexpr int ROOM_SNAPSHOT_FRAME = 30;
constexpr uint32_t ROOM_SNAPSHOT_CHANCE = 3;
constexpr int HALLUCINATION_FLASH_FRAMES = 20;
constexpr float HALLUCINATION_FLASH_ALPHA = 0.5f;
constexpr int HALLUCINATION_FADE_FRAMES = 10;
constexpr float HALLUCINATION_CLEAR = 0.999f;
constexpr uint32_t CLICKER_FLIPS = 4;
constexpr float PIXELATION_SCALE = 0.3f;
constexpr float PIXELATION_MIN = 0.0001f;
constexpr float BLOOM_RATIO = 2;
constexpr float OLD_TV_TIME_SCALE = 0.05f;
constexpr float ASCENT_FADE_FRAMES = 90;
constexpr uint32_t DEBUG_FLAG_PLAYER_INFO = 1 << 11;
constexpr uint32_t DEBUG_FLAG_LUA_MEMORY = 1 << 13;
constexpr float PI = std::numbers::pi_v<float>;
// Draws a whole surface over the screen in a color.
static void screen_surface_draw(KAGE::Graphics::ImageBase& surface, KColor color)
{
SourceQuad whole = KAGE::Graphics::source_quad_rect({}, vector_make(1, 1));
whole._coordinateSpace = KAGE::Graphics::COORDINATES_NORMALIZED;
surface.Render(whole, KAGE::Graphics::color_quad_rect({}, vector_make(g_screenWidth, g_screenHeight), SCREEN_WHITE),
color);
}
// Draws into an effect surface until effect_pass_end.
static void effect_pass_begin(KAGE::Graphics::ImagePtr& surface)
{
KAGE::Graphics::manager.render_target_push(surface.get(), KAGE::Graphics::TARGET_SCREEN_SIZE,
KAGE::Graphics::PRESENT_FLUSH);
}
// Finishes an effect surface and goes back to the target before it, cleared.
static void effect_pass_end()
{
KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager;
graphics.Present(KAGE::Graphics::PRESENT_FINISH);
graphics.render_target_pop(KAGE::Graphics::PRESENT_FLUSH);
graphics.Clear();
}
// Makes an effect's shader current when it loaded, and sets one of its floats.
static void effect_shader_set(std::string_view shaderName, std::string_view uniformName, float value)
{
shader_select(shaderName);
KAGE::Graphics::Shader* shader = KAGE::Graphics::manager.currentShader;
if (shader) shader->set_uniform(uniformName, KAGE::Graphics::UNIFORM_FLOAT, &value);
}
// Gives the current shader a surface's size and its texture's as ScreenSize.
static void screen_size_set(const KAGE::Graphics::ImageBase& surface)
{
std::array<float, 4> size = {(float)surface.width, (float)surface.height, (float)surface.textureWidth,
(float)surface.textureHeight};
KAGE::Graphics::Shader* shader = KAGE::Graphics::manager.currentShader;
if (shader) shader->set_uniform(SCREEN_SIZE_UNIFORM, KAGE::Graphics::UNIFORM_VEC4, size.data());
}
// Whether the screen pixelates: a pixelation room transition going out or coming in.
// A stage transition decides with StageTransition's own check (009301d0), which waits for its takeover.
static bool is_pixelating(Game& game)
{
int stageState = game.stageTransition.state;
if (stageState == STAGE_TRANSITION_OUT || stageState == STAGE_TRANSITION_IN) return game.stageTransition.is_pixelated();
return game.roomTransition.get_fade_progress() >= 0 && game.roomTransition.animation == TRANSITION_PIXELATION;
}
// Whether this frame captures the room for a hallucination to flash back to: 30 frames into a room, the first room
// of a run always, then one room in three by its spawn seed.
// The original also captured while the flag held 0xff, which Game's bool no longer holds.
static bool is_room_snapshot(Game& game)
{
if (game.room->GetFrameCount() != ROOM_SNAPSHOT_FRAME) return false;
RNG rng = ROOM_SNAPSHOT_RNG;
rng._seed = game.room->descriptor->spawnSeed;
return rng.Next() % ROOM_SNAPSHOT_CHANCE == 0 || !game.isRoomSnapshotTaken;
}
// Draws the color modifier's surface back through its shader, in the modifier's color.
static void color_modifier_resolve(Game& game)
{
KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager;
ColorModState& modifier = game.currentColorModifier;
effect_pass_end();
shader_select(COLOR_MOD_SHADER);
graphics.blendMode = KAGE::Graphics::BLEND_MODE_OPAQUE;
if (KAGE::Graphics::Shader* shader = graphics.currentShader)
{
shader->set_uniform("Amount", KAGE::Graphics::UNIFORM_FLOAT, &modifier._amount);
shader->set_uniform("Brightness", KAGE::Graphics::UNIFORM_FLOAT, &modifier._brightness);
shader->set_uniform("Contrast", KAGE::Graphics::UNIFORM_FLOAT, &modifier._contrast);
}
screen_surface_draw(*game.colormodSurface, kcolor_rgba(modifier._red, modifier._green, modifier._blue, 1));
graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL);
graphics.shader_default_set();
}
// Draws the bloom surface back, glowing most halfway through the bloom.
static void bloom_resolve(Game& game)
{
KAGE::Graphics::ImageBase& surface = *game.bloomSurface;
float half = (float)game.bloomDuration * 0.5f;
float amount = std::sin((1 - std::abs((float)game.bloomTimer - half) / half) * PI * 0.5f) * game.bloomStrength;
std::array<float, 2> ratio = {BLOOM_RATIO / (float)surface.textureWidth,
BLOOM_RATIO / (float)surface.textureHeight};
effect_pass_end();
KAGE::Graphics::manager.blendMode = KAGE::Graphics::BLEND_MODE_OPAQUE;
effect_shader_set(BLOOM_SHADER, "BloomAmount", amount);
if (KAGE::Graphics::Shader* shader = KAGE::Graphics::manager.currentShader)
shader->set_uniform("Ratio", KAGE::Graphics::UNIFORM_VEC2, ratio.data());
screen_surface_draw(surface, SCREEN_WHITE);
}
// Flashes the giant book clicker over a hallucination fading in or out, flipped another way each frame.
static void clicker_render(Game& game, float amount)
{
KAGE::Graphics::ImageBase& clicker = *game.giantBookClickerImage;
uint32_t flip = g_manager->framecount % CLICKER_FLIPS;
bool isFlipX = flip == 1 || flip == 3;
bool isFlipY = flip == 2 || flip == 3;
float width = (float)clicker.width;
float height = (float)clicker.height;
Vector corner = vector_make(isFlipX ? width : 0, isFlipY ? height : 0);
Vector size = vector_make(isFlipX ? -width : width, isFlipY ? -height : height);
shader_select(COLOR_OFFSET_SHADER);
apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, clicker);
clicker.Render(KAGE::Graphics::source_quad_rect(corner, size),
KAGE::Graphics::color_quad_rect({}, vector_make(g_screenWidth, g_screenHeight), SCREEN_WHITE),
kcolor_rgba(1, 1, 1, 1 - amount));
}
// Draws the hallucination surface back through its shader, fading over its first and last 10 frames with the clicker.
static void hallucination_resolve(Game& game)
{
int fadeOutStart = game.hallucinationDuration - HALLUCINATION_FADE_FRAMES;
float amount = 1;
if (game.hallucinationTimer > fadeOutStart)
amount = 1 - (float)(game.hallucinationTimer - fadeOutStart) / HALLUCINATION_FADE_FRAMES;
else if (game.hallucinationTimer < HALLUCINATION_FADE_FRAMES)
amount = (float)game.hallucinationTimer / HALLUCINATION_FADE_FRAMES;
effect_pass_end();
KAGE::Graphics::manager.blendMode = KAGE::Graphics::BLEND_MODE_OPAQUE;
effect_shader_set(HALLUCINATION_SHADER, "Amount", amount);
screen_size_set(*game.hallucinationSurface);
screen_surface_draw(*game.hallucinationSurface, SCREEN_WHITE);
if (amount < HALLUCINATION_CLEAR) clicker_render(game, amount);
}
// Draws what a run shows over its room: the debug shapes, the HUD, the transitions and overlays, then the prompts and
// menus of a run between the popup layers, and the mods' shaders.
// The debug shapes stay empty until DebugRenderer's takeover, and the online stats screen never shows offline.
static void overlays_render(Game& game)
{
KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager;
PopupQueue& popups = g_manager->popupQueue;
bool isFighting = game.deathmatchManager.state == DEATHMATCH_FIGHT;
int stageState = game.stageTransition.state;
popups.render_layer(0);
game.hud.Render();
if (isFighting) game.deathmatchManager.type->FUN_0042aca0();
if (stageState == STAGE_TRANSITION_OUT || stageState == STAGE_TRANSITION_IN) game.stageTransition.Render();
else graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL);
game.itemOverlay.Render();
if (game.bossOverlay._state != 0) reconstruction_missing("Game::Render 006fbc10: BossOverlay's render 00421400");
popups.render_layer(1);
const AnimationState& prompt = game.genericPrompt.sprite.animState;
if (prompt.animData && prompt.isPlaying)
{
game.genericPrompt.Render();
if (game.genericPrompt.isOnlineVote)
reconstruction_missing("Game::Render 006fbc10: the online vote count under the prompt");
}
if (game.pauseScreen.state != PAUSE_HIDDEN) game.pauseScreen.Render();
game.emoteWheel.Render();
game.revivePlayerMenu.Render();
game.gameOver.Render();
game.leaderboard.Render();
popups.render_layer(2);
g_manager->modManager.shaders_render();
}
// Resolves the effect surfaces in turn (the room snapshot, bloom, pixelation, hallucination, old TV), then draws the
// Ascent's white, the fade in (with the loading icon) or out, and the debug displays.
static void effects_resolve(Game& game, bool isRoomSnapshot, bool isOldTv)
{
KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager;
OptionsConfig& options = g_manager->optionsConfig;
Vector screen = vector_make(g_screenWidth, g_screenHeight);
if (isRoomSnapshot)
{
effect_pass_end();
graphics.blendMode = KAGE::Graphics::BLEND_MODE_OPAQUE;
screen_surface_draw(*game.hallucinationSnapshot, SCREEN_WHITE);
}
if (game.bloomTimer > 0 && options.render.isBloomEnabled) bloom_resolve(game);
if (options.render.isPixelationEnabled && is_pixelating(game))
{
effect_pass_end();
float amount = std::max(game.roomTransition.get_fade_progress() * PIXELATION_SCALE, PIXELATION_MIN);
effect_shader_set(PIXELATION_SHADER, "PixelationAmount", amount);
screen_size_set(*game.pixelationSurface);
screen_surface_draw(*game.pixelationSurface, SCREEN_WHITE);
}
if (game.hallucinationTimer > 0) hallucination_resolve(game);
if (isOldTv)
{
effect_pass_end();
graphics.blendMode = KAGE::Graphics::BLEND_MODE_OPAQUE;
effect_shader_set(OLD_TV_SHADER, "Time", (float)game.frameCount * OLD_TV_TIME_SCALE);
screen_size_set(*game.oldTvSurface);
screen_surface_draw(*game.oldTvSurface, SCREEN_WHITE);
}
graphics.shader_default_set();
if (game.ascentTimer > 0)
{
float alpha = std::clamp((float)game.ascentTimer / ASCENT_FADE_FRAMES, 0.0f, 1.0f);
graphics.blendMode.SetMode(KAGE::Graphics::BLEND_ADDITIVE);
render_color_shader_pass(KAGE::Graphics::color_quad_rect({}, screen, kcolor_rgba(1, 1, 1, alpha)));
graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL);
}
if (game.fadeInColor._alpha > 0)
{
graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL);
render_color_shader_pass(KAGE::Graphics::color_quad_rect({}, screen, game.fadeInColor));
if (game.isFadeInIconShown) Manager::render_loading_icon(game.fadeInColor._alpha);
}
else if (game.fadeOutColor._alpha > 0)
render_color_shader_pass(KAGE::Graphics::color_quad_rect({}, screen, game.fadeOutColor));
if (game.debugFlags & DEBUG_FLAG_PLAYER_INFO && !game.playerManager.playerList.empty())
reconstruction_missing("Game::Render 006fbc10: the player debug info");
if (game.debugFlags & DEBUG_FLAG_LUA_MEMORY) reconstruction_missing("render_debug_lua_memory 00872090");
}
// 006fbc10 Draws the run's frame. The room, or the room transition, draws through the effect surfaces that are on (old
// TV, hallucination, pixelation, bloom, the room snapshot and the color modifier) with Lua's post render and a
// hallucination's flash back to the snapshot. The overlays of a run come over it, then the effects resolve, and the
// console comes last. A versus screen shows without the color modifier.
// The online parts (the vote count, the stats screen, the desync warning) never show offline.
void Game::Render()
{
KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager;
OptionsConfig& options = g_manager->optionsConfig;
bool isFighting = deathmatchManager.state == DEATHMATCH_FIGHT;
bool isOldTv = seedEffects.HasSeedEffect(SEED_OLD_TV);
bool isTransitionShown = roomTransition.mode == TRANSITION_OUT || roomTransition.mode == TRANSITION_IN;
if (isWindowResizePending)
{
recreate_render_targets();
isWindowResizePending = false;
}
room->render_lighting();
if (isFighting) deathmatchManager.type->vfunc_5();
if (isOldTv) effect_pass_begin(oldTvSurface);
if (hallucinationTimer > 0) effect_pass_begin(hallucinationSurface);
if (options.render.isPixelationEnabled && is_pixelating(*this)) effect_pass_begin(pixelationSurface);
if (bloomTimer > 0 && options.render.isBloomEnabled)
{
graphics.Clear();
effect_pass_begin(bloomSurface);
}
bool isRoomSnapshot = is_room_snapshot(*this);
if (isRoomSnapshot)
{
effect_pass_begin(hallucinationSnapshot);
isRoomSnapshotTaken = true;
}
g_manager->modManager.shader_render_targets_push();
bool isVersusScreen = roomTransition.mode == TRANSITION_OUT && roomTransition.bossIntroBossId != 0;
bool isColorModified = !isVersusScreen && options.render.isColorModifierEnabled;
if (isColorModified) effect_pass_begin(colormodSurface);
graphics.Clear();
graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL);
if (isTransitionShown) roomTransition.Render();
else room->Render();
lua_engine_get().PostRender();
bool isFlashing = hallucinationTimer > std::max(hallucinationDuration - HALLUCINATION_FLASH_FRAMES, 0);
if (isFlashing && !isRoomSnapshot && hallucinationSnapshot)
{
int flashFrame = hallucinationTimer - hallucinationDuration + HALLUCINATION_FLASH_FRAMES;
float alpha = std::sin((float)flashFrame * PI / HALLUCINATION_FLASH_FRAMES) * HALLUCINATION_FLASH_ALPHA;
screen_surface_draw(*hallucinationSnapshot, kcolor_rgba(1, 1, 1, alpha));
}
if (isColorModified) color_modifier_resolve(*this);
overlays_render(*this);
effects_resolve(*this, isRoomSnapshot, isOldTv);
console.Render();
}
// 006fd350 Whether the run's frame stands still: an open console or pause menu while offline, a freeze, the death or
// leaderboard screen, a stage or room transition, an item overlay playing, any state but the game, a prompt animating,
// or the online stats screen. The original's netplay player-list checks are is_online, as the game is offline.
bool Game::IsPaused()
{
bool isOffline = !g_manager->netplayManager.is_online();
if (console.state != CONSOLE_CLOSED && isOffline) return true;
return freezeFrames > 0 || gameOver.state != GAME_OVER_HIDDEN || leaderboard.displayState != LEADERBOARD_HIDDEN ||
stageTransition.state != 0 || roomTransition.mode != 0 || itemOverlay.state == ITEM_OVERLAY_ACTIVE ||
(pauseScreen.is_pausing() && isOffline) || g_manager->state != MANAGER_STATE_GAME ||
genericPrompt.IsActive() || onlineStatsScreen.isActive;
}
// 006f8120 Whether the run plays Greed mode.
bool Game::IsGreedMode()
{
return difficulty == DIFFICULTY_GREED || difficulty == DIFFICULTY_GREEDIER;
}
// 00738470 The stage id the floor's rooms come from: the current room's own stage in Backasswards, the Death
// Certificate floor in its dimension, else the floor's stage and type. It never used its argument.
int Game::GetStageID()
{
if (g_game->challenge == CHALLENGE_RED_REDEMPTION)
reconstruction_missing("Game::GetStageID 00738470: Level::GetRoomStageType 0074f690 on Game's room list");
if (currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE) return STAGE_ID_DEATH_CERTIFICATE;
return RoomConfig::GetStageID(stage, stageType, ROOM_MODE_CURRENT);
}
// 004217a0 Whether one of the run's state flags is set.
bool Game::GetStateFlag(GameStateFlag flag)
{
return gameStateFlags >> flag & 1;
}
// 00417870 A player by index, the first for an index past the end.
Entity_Player* Game::GetPlayer(int index)
{
return playerManager.GetPlayer(index);
}
// 00706940 The rules the run is played by: the daily's, else its challenge's (a plain run's for none).
ChallengeParam& Game::GetChallengeParams()
{
if (dailyChallenge._id != 0)
reconstruction_missing("Game::GetChallengeParams 00706940: the daily's params, which classes.h holds as bytes");
return g_manager->GetChallengeParams((int)challenge);
}