Files
isaac-port/src/game_restore.cpp
T

752 lines
35 KiB
C++

#include "entity_familiar.h"
#include "entity_npc.h"
#include "game.h"
#include "game_state_player.h"
#include "log.h"
#include "manager.h"
#include "room.h"
#include "texture_cache.h"
#include <algorithm>
#include <array>
#include <ranges>
#include <utility>
#include <vector>
constexpr uint32_t ROOM_REF_MERGED = 0x80000000;
constexpr uint32_t ROOM_REF_MIRRORED = 0x40000000;
constexpr uint32_t ROOM_REF_STAGE_MASK = 0xffff;
constexpr uint32_t ROOM_REF_HALF_MASK = 0xffff;
constexpr int ROOM_REF_MODE_SHIFT = 16;
constexpr int ROOM_REF_HALF_SHIFT = 16;
constexpr uint32_t ROOM_REF_MODE_MASK = 0xff;
constexpr uint32_t PLAYER_RNG_SHIFT = 34;
constexpr uint32_t FORTUNE_RNG_SHIFT = 35;
constexpr uint32_t ITEM_RNG_SHIFT = 35;
constexpr uint32_t GLITCH_BABY_SHIFT = 35;
constexpr uint32_t ITEM_POOL_SHIFT = 3;
constexpr uint32_t DEVIL_ANGEL_SHIFT = 2;
constexpr uint8_t HOLY_MANTLE_SAVED = 2;
constexpr const char* ITEM_POOLS_XML = "itempools.xml";
constexpr uint32_t STAGE_CAVES_I = 3;
constexpr uint32_t STAGE_CAVES_II = 4;
constexpr uint32_t STAGE_DEPTHS_II = 6;
constexpr int DIMENSION_ALTERNATE = 1;
constexpr int MINI_MUSH_STACKS_SECOND = 4;
constexpr int MINI_MUSH_STACKS_THIRD = 7;
constexpr int NULLITEM_WAVY_CAP_2 = 72;
constexpr int NULLITEM_WAVY_CAP_3 = 73;
constexpr double WAVY_CAP_STACKS_PER_DIZZINESS = 10;
constexpr float WAVY_CAP_DIZZINESS_SPEED = 0.001f;
constexpr uint32_t ALL_CACHE_FLAGS = 0xffff;
constexpr std::array<std::pair<int, int>, 4> TWIN_PLAYER_TYPES = {
{{PLAYER_JACOB, PLAYER_ESAU},
{PLAYER_LAZARUS_B, PLAYER_LAZARUS2_B},
{PLAYER_THEFORGOTTEN_B, PLAYER_THESOUL_B},
{PLAYER_LAZARUS2_B, PLAYER_LAZARUS_B}}};
// 007474a0 The room config a saved run names: a stage's room by type and variant (a generated mirror of it when
// mirrored), or for a merged room its two halves joined again from the merged configs (second half first).
// A merged room without the list, or a config of type 0, is none. A room the configs lack is none, where the original
// mirrors it anyway.
RoomConfig_Room* room_config_ref_load(const RoomConfigRef& ref, const std::vector<RoomConfigRef>* mergedConfigs)
{
RoomConfig& configs = g_game->roomConfig;
if (ref.packed == ROOM_REF_MERGED)
{
if (!mergedConfigs) return nullptr;
// The half at an index of the merged configs.
auto half_load = [&](uint32_t index)
{
const std::vector<RoomConfigRef>& halves = *mergedConfigs;
return index < halves.size() ? room_config_ref_load(halves[index], mergedConfigs) : nullptr;
};
RoomConfig_Room* second = half_load(ref.variant >> ROOM_REF_HALF_SHIFT & ROOM_REF_HALF_MASK);
RoomConfig_Room* first = half_load(ref.variant & ROOM_REF_HALF_MASK);
return first && second ? configs.MergeRoomsIntoGenerated(*first, *second, (RoomShape)ref.type) : nullptr;
}
if (ref.type == 0) return nullptr;
RoomMode mode = (RoomMode)(ref.packed >> ROOM_REF_MODE_SHIFT & ROOM_REF_MODE_MASK);
RoomConfig_Room* room = configs.GetRoomByStageTypeAndVariant(ref.packed & ROOM_REF_STAGE_MASK, (int)ref.type,
(int)ref.variant, mode);
if (!room || !(ref.packed & ROOM_REF_MIRRORED)) return room;
return configs.mirrored_room_make(*room);
}
// 006f8140 Rebuilds the run from a game state: its rules, counters and histories, then (continuing a saved run rather
// than rewinding) the first player, the pools, the fortune generator and whether achievements may unlock. The
// generators, pools, TMTRAINER items, the Ascent's stages, the versus rules, the players, the floor with the room the
// players are in, the nightmare stage bar, the ambush, the score and each player's Wavy Cap costume follow.
// Netplay is offline. The versus rules keep no players offline.
void Game::restore_game_state(GameState& state, GameRestore restore)
{
Manager& manager = *g_manager;
uint64_t savedFlagsMask = (1ull << SAVED_GAME_STATE_FLAG_COUNT) - 1;
seedEffects = state.seeds;
challenge = (uint32_t)state.challenge;
isConsoleUsedThisRun = state.isConsoleUsedThisRun || manager.isConsoleEnabled;
difficulty = (Difficulty)state.difficulty;
gameStateFlags = (gameStateFlags & ~savedFlagsMask) | state.gameStateFlags.to_ullong();
lastDevilRoomStage = state.lastDevilRoomStage;
treasureRoomsVisited = state.treasureRoomsVisited;
planetariumsVisited = state.planetariumsVisited;
stagesWithoutHeartsPicked = state.stagesWithoutHeartsPicked;
stagesWithoutDamage = state.stagesWithoutDamage;
devilRoomDeals = state.devilRoomDeals;
shopVisits = state.shopVisits;
donationModGreed = state.donationModGreed;
donationModAngel = state.donationModAngel;
reviveMachineCoinsLeft = state.reviveMachineCoinsLeft;
reviveMachineUses = state.reviveMachineUses;
bossRushParTime = state.bossRushParTime;
blueWombParTime = state.blueWombParTime;
frameCount = state.frameCount;
timeCounter = state.timeCounter;
stageNameNumeral = state.stageNameNumeral;
victoryLap = state.victoryLap;
lastLevelWithoutHalfHp = state.lastLevelWithoutHalfHp;
isRerun = state.isRerun;
lastLevelWithDamage = state.lastLevelWithDamage;
encounteredBosses = state.encounteredBosses;
magicSkinUses = state.magicSkinUses;
erasedEntities = state.erasedEntities;
pixelationTimer = state.pixelationTimer;
pixelationDuration = state.pixelationDuration;
if (restore == RESTORE_CONTINUE)
{
proceduralItemManager.Init();
int playerType = state.players.empty() ? state.playerType : state.players[0].playerType;
seedEffects.GetStartSeed();
playerManager.init_main_player(playerType, seedEffects.playerInitSeed);
itemPool.Init(state.itemPool.seed, manager.modManager.TryRedirectPath(ITEM_POOLS_XML));
bossPool.init(seedEffects.GetStartSeed());
fortuneRNG.SetSeed(state.fortuneSeed, FORTUNE_RNG_SHIFT);
uint32_t startSeed = seedEffects.GetStartSeed();
std::string seedText = Seeds::Seed2String(seedEffects.GetStartSeed());
log_printf(LOG_INFO, "RNG Start Seed: %s (%u) [Continue, %d]\n", seedText.c_str(), startSeed,
manager.currentSaveSlot);
bool isReadOnly = seedEffects.isCustomRun || seedEffects.AchievementUnlocksDisallowed() ||
Manager::AchievementUnlocksDisallowed() || isRerun || victoryLap > 0;
if (!manager.isNetworkPlay) manager.persistentGameData.SetReadOnly(isReadOnly);
}
playerManager.rng.SetSeed(state.playerManagerSeed, PLAYER_RNG_SHIFT);
fortuneRNG.SetSeed(state.fortuneSeed, FORTUNE_RNG_SHIFT);
itemPool.RestoreGameState(state.itemPool);
bossPool.restore_game_state(state.bossPool);
proceduralItemManager.items_restore(state.proceduralItemSeeds);
ascentTimer = state.isAscent ? 1 : 0;
backwardsStages = state.backwardsStages;
deathCertificateExitTimer = (int16_t)state.deathCertificateExitTimer;
deathmatchManager.state = DEATHMATCH_OFF;
deathmatchManager.timer = 0;
deathmatchManager.set_type((DeathmatchRules)state.versusRules);
playerManager.RestoreGameState(state);
Level::RestoreGameState(state);
playerManager.RestoreGameState_PostLevelInit(state);
manager.nightmareScene.stageIcons = state.nightmareStageIcons;
ambush._isActive = state.isAmbushActive;
ambush._currentWave = state.ambushWave;
if (ambush._isActive) reconstruction_missing("Game::restore_game_state 006f8140: an ambush in progress (Ambush)");
scoreSheet.restore_state(state.scoreSheet);
for (Entity_Player* player : playerManager.playerList) player->update_mini_mush_costume();
}
// 00736530 Restores the pools from a save: each pool's weights in draw order (as many as both have) and its Bible
// chance, the seeds, the collectibles removed and the trinkets still in the pool (counting those available), the
// pill colors' effects and which are identified, and the Genesis counts.
void ItemPool::RestoreGameState(const GameStateItemPool& state)
{
for (size_t i = 0; i < pools.size(); i++)
{
std::vector<PoolItem>& items = pools[i].poolList;
const std::vector<float>& weights = state.poolsItemWeights[i];
for (size_t j = 0; j < std::min(items.size(), weights.size()); j++) items[j].weight = weights[j];
pools[i].bibleUpgrade = state.bibleUpgrades[i];
}
seed = state.seed;
lastPool = state.lastPool;
itemPoolRNG.SetSeed(state.itemPoolRNGseed, ITEM_POOL_SHIFT);
trinketPoolRNG.SetSeed(state.trinketPoolRNGseed, TRINKET_POOL_SHIFT);
unkFloat674 = state.unkFloat674;
unkFloat678 = state.unkFloat678;
for (size_t i = 0; i < std::min(removedCollectibles.size(), state.removedCollectibles.size()); i++)
removedCollectibles[i] = state.removedCollectibles[i];
for (size_t i = 0; i < std::min(trinketPoolItems.size(), state.trinketPoolItems.size()); i++)
trinketPoolItems[i].isInPool = state.trinketPoolItems[i];
auto isDrawable = [](TrinketPoolItem& slot) { return slot.isInPool && slot.isAvailable; };
numAvailableTrinkets = (int)std::ranges::count_if(trinketPoolItems, isDrawable);
pillEffects = state.pillEffects;
identifiedPillEffects = state.identifiedPillEffects;
remainingGenesisItems = state.remainingGenesisItems;
}
// 007475b0 Restores the floor from a save and enters its room: the stage, curses, flags, Greed waves and seeds, the
// maps and every room descriptor with its config named again, the rooms the players are in and came from, and the
// Ventricle Razor portals. Backasswards resumed in the uncleared boss room starts over in the first room and walks back
// in. A new stage starts for the players, the camera catches up, and the room's watch speed and slowdown come back.
// The Death Certificate's return room is not kept by the curated game state, and the mineshaft escape's Mother's shadow
// waits for its takeover.
void Level::RestoreGameState(GameState& state)
{
Game& game = *g_game;
bool isNewLevel = false;
if (stage != state.stage)
{
isNewLevel = !game.isRestoringGlowingHourglassState;
stage = state.stage;
}
stageType = state.stageType;
startingRoomIdx = state.startingRoomIdx;
lastBossRoomListIdx = state.lastBossRoomListIdx;
curses = state.curses;
dungeonPlacementSeed = state.dungeonPlacementSeed;
devilAngelRoomRNG.SetSeed(state.devilAngelRoomSeed, DEVIL_ANGEL_SHIFT);
angelRoomChance = state.angelRoomChance;
bombPickupsSpawned = state.bombPickupsSpawned;
isHeartPicked = state.isHeartPicked;
isDevilRoomDisabled = state.isDevilRoomDisabled;
isCanSeeEverything = state.isCanSeeEverything;
isBossChallenge = state.isBossChallenge;
uint32_t savedFlagsMask = (1u << LEVEL_STATE_FLAG_COUNT) - 1;
levelStateFlags = (levelStateFlags & ~savedFlagsMask) | (uint32_t)state.levelStateFlags.to_ulong();
greedWaveSeeds = state.greedWaveSeeds;
greedModeTreasureRoomIdx = state.greedModeTreasureRoomIdx;
greedLastBeatenWave = state.greedLastBeatenWave;
greedModeWave = (int)std::min((uint32_t)state.greedModeWave, (uint32_t)greedLastBeatenWave);
greedLastPaidWave = state.greedLastPaidWave;
game.seedEffects.GetStartSeed();
generationRNG.Next();
if (game.challenge == CHALLENGE_RED_REDEMPTION) InitStageSeeds();
reset_room_list(false);
roomMap = state.roomMap;
game.roomConfig.ClearGeneratedRooms();
nbRooms = state.roomCount;
for (size_t i = 0; i < std::min(roomList.size(), state.rooms.size()); i++)
{
roomList[i] = state.rooms[i].desc;
roomList[i].data = room_config_ref_load(state.rooms[i].config, &state.mergedRoomConfigs);
}
currentRoomIdx = state.currentRoomIdx;
currentDimensionIdx = state.currentDimensionIdx;
currentRoomMap = roomMap.data() + currentDimensionIdx * LEVEL_GRID_CELLS;
lastRoomDimensionIdx = state.lastRoomDimensionIdx;
lastRoomIdx = state.lastRoomIdx;
dungeonReturnPosition = state.dungeonReturnPosition;
dungeonReturnRoomIndex = state.dungeonReturnRoomIndex;
enterDoor = state.enterDoor;
ventricleRazorPortals = state.ventricleRazorPortals;
int bossCell = game.roomList[game.lastBossRoomListIdx].gridIndex;
bool isBackasswardsBoss = game.challenge == CHALLENGE_BACKASSWARDS && stage != STAGE_DARK_ROOM &&
currentRoomIdx == bossCell &&
!(GetRoomByIdx(currentRoomIdx)->flags & ROOM_DESCRIPTOR_FLAG_CLEAR);
if (isBackasswardsBoss)
{
for (Entity_Player* player : game.playerManager.playerList)
{
player->isPlayingExtraAnimation = false;
player->isPlayingItemAnimation = false;
}
lastRoomIdx = currentRoomIdx = startingRoomIdx;
leaveDoor = -1;
load_room();
game.roomTransition.start({.animation = TRANSITION_BOSS_FORCED, .roomIndex = bossCell});
game.roomTransition.Update();
GetRoomByIdx(startingRoomIdx)->flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR;
UpdateVisibility();
}
else
{
load_room();
room->PlayMusic();
for (MinimapConfig& map : game.minimap.configs) map.refresh();
if (game.hud.hudRefreshType != HUD_REFRESH_FULL)
{
game.hud.hudRefreshType = HUD_REFRESH_PLAYER;
game.hud.hudRefreshCountdown = 2;
}
}
if (isNewLevel) game.playerManager.trigger_level_start();
bool isBackwards = stage >= 1 && stage <= STAGE_DEPTHS_II && game.GetStateFlag(GAME_STATE_BACKWARDS_PATH);
bool isMinesFloor = stage == STAGE_CAVES_II || (stage == STAGE_CAVES_I && (GetCurses() & CURSE_OF_LABYRINTH));
bool isMineshaftEscape = currentDimensionIdx == DIMENSION_ALTERNATE && !game.IsGreedMode() && !isBackwards &&
(stageType == STAGETYPE_REPENTANCE || stageType == STAGETYPE_REPENTANCE_B) &&
isMinesFloor && (levelStateFlags & 1u << LEVEL_STATE_MINESHAFT_ESCAPE);
if (isMineshaftEscape)
reconstruction_missing("Level::RestoreGameState 007475b0: the mineshaft escape's Mother's shadow");
room->camera->DoUpdate(false);
room->brokenWatchState = (BrokenWatchState)(int8_t)state.brokenWatchState;
g_manager->musicManager.targetPitch = room->time_scale_update();
room->slowdownDuration = std::max(room->slowdownDuration, state.slowdownDuration);
TextureCache::Purge();
}
// 009bc790 The players a save's players are restored into, by save index: each saved main player matched to the first
// room player of its controller. Spawning, the room players left unmatched are removed (the last first) and each saved
// main player still without one gets a new co-op player of its character. A backup player matches none.
std::vector<Entity_Player*> PlayerManager::match_saved_players(GameState& state, PlayerMatch match)
{
std::vector<Entity_Player*> matched(state.players.size(), nullptr);
std::vector<Entity_Player*> unmatched;
for (Entity_Player* player : playerList)
if (player->variant == PLAYER_VARIANT_PLAYER) unmatched.push_back(player);
for (size_t i = 0; i < state.players.size(); i++)
{
if (state.players[i].isBackupPlayer) continue;
auto found = std::ranges::find(unmatched, state.players[i].controllerIndex, &Entity_Player::controllerIndex);
if (found == unmatched.end()) continue;
matched[i] = *found;
unmatched.erase(found);
}
if (match == MATCH_FIND) return matched;
for (Entity_Player* player : std::views::reverse(unmatched)) RemoveCoPlayer(player);
for (size_t i = 0; i < state.players.size(); i++)
if (!state.players[i].isBackupPlayer && !matched[i]) matched[i] = SpawnCoPlayer2(state.players[i].playerType);
return matched;
}
// Ties a restored player to the later saved players of its twin character on its controller, both ways.
static void twins_link(std::vector<Entity_Player*>& matched, size_t index)
{
Entity_Player& player = *matched[index];
auto twin = std::ranges::find(TWIN_PLAYER_TYPES, player.playerType, &std::pair<int, int>::first);
if (twin == TWIN_PLAYER_TYPES.end()) return;
for (size_t i = index + 1; i < matched.size(); i++)
{
Entity_Player* other = matched[i];
if (!other || other->playerType != twin->second) continue;
if (other->controllerIndex != player.controllerIndex || other->twinPlayer.get()) continue;
player.twinPlayer = other;
other->twinPlayer = &player;
}
}
// 009bcaa0 Restores the saved players: each matched player from its save (its twin forgotten first), then the twins,
// the parents, the backup players and the Esau Jr. players, the glitched baby generator and random babies from the
// first saved player, the join seats and the HUDs.
void PlayerManager::RestoreGameState(GameState& state)
{
std::vector<Entity_Player*> matched = match_saved_players(state, MATCH_SPAWN);
for (size_t i = 0; i < matched.size(); i++)
{
if (!matched[i]) continue;
matched[i]->twinPlayer = nullptr;
matched[i]->RestoreGameState(state.players[i]);
}
for (size_t i = 0; i < matched.size(); i++)
{
GameStatePlayer& saved = state.players[i];
int parentIndex = saved.parentIndex;
if (saved.isBackupPlayer && i > 0 && matched[i - 1])
reconstruction_missing("PlayerManager::RestoreGameState 009bcaa0: a backup player (Tainted Lazarus)");
else if (saved.isBackupPlayer || !matched[i]) continue;
else if (parentIndex < 0) twins_link(matched, i);
else if ((size_t)parentIndex < matched.size() && matched[parentIndex])
matched[i]->parent = matched[parentIndex];
}
for (size_t i = 0; i < esauJrState.size(); i++)
{
delete esauJrState[i];
esauJrState[i] = nullptr;
if (i < state.esauJrStates.size() && state.esauJrStates[i].playerType != -1)
reconstruction_missing("PlayerManager::RestoreGameState 009bcaa0: an Esau Jr. player");
}
if (!state.players.empty())
{
GameStatePlayer& first = state.players.front();
glitchBabyRng.SetSeed((uint32_t)first.glitchBabySeed, GLITCH_BABY_SHIFT);
randomBabyCount = first.randomBabyCount;
randomBabies = first.randomBabies;
}
coop_slots_reset();
g_game->hud.AssignPlayerHUDs();
}
// 009bd010 Finishes the saved players once their floor is entered (their familiars, charmed enemies, effects and
// stats), then clears the join seats and refreshes the HUDs and the crafting bag's item.
void PlayerManager::RestoreGameState_PostLevelInit(GameState& state)
{
std::vector<Entity_Player*> matched = match_saved_players(state, MATCH_FIND);
HUD& hud = g_game->hud;
for (size_t i = 0; i < matched.size(); i++)
if (matched[i]) matched[i]->RestoreGameState_PostLevelInit(state.players[i]);
coop_slots_reset();
hud.AssignPlayerHUDs();
hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS);
hud.InvalidateCraftingItem(nullptr);
}
// 009bf530 Hands the controllers out again after a continue: every player lets go of its own, then the players without
// one take, in order, the menu's controller and every other connected device.
void PlayerManager::restore_controller_assignment()
{
std::vector<int> controllers = {g_manager->activeControllerIndex};
for (Entity_Player* player : playerList) player->SetControllerIndex(-1, true);
for (int i = 0; i < KAGE::Input::manager.get_device_count(); i++)
{
std::shared_ptr<KAGE::Input::InputDevice> device = KAGE::Input::manager.get_device(i);
if (device && device->id != g_manager->activeControllerIndex && device->isConnected)
controllers.push_back(device->id);
}
auto next = controllers.begin();
for (Entity_Player* player : playerList)
{
if (next == controllers.end()) break;
if (player->controllerIndex == -1) player->SetControllerIndex(*next++, true);
}
coop_slots_reset();
g_game->hud.AssignPlayerHUDs();
}
// An item by its kind as a save names it: a null item, a trinket (its golden flag ignored) or a collectible.
static ItemConfig_Item* item_by_kind(int type, int id)
{
ItemConfig& items = g_manager->itemConfig;
if (type == ITEM_NULL) return items.GetNullItem(id);
if (type == ITEM_TRINKET) return items.GetTrinket((uint32_t)id);
return items.GetCollectible(id);
}
// 007ae430 Gives a sub player or co-op baby its saved character (unless it holds a player index) and hearts.
static void co_player_restore(Entity_Player& player, const CoPlayerState& saved)
{
if (player.playerIndex < 0) player.playerType = saved.playerType;
player.redHearts = saved.redHearts;
player.maxHearts = saved.maxHearts;
player.soulHearts = saved.soulHearts;
player.blackHearts = saved.blackHearts;
player.eternalHearts = saved.eternalHearts;
player.goldenHearts = saved.goldenHearts;
player.brokenHearts = saved.brokenHearts;
player.rottenHearts = saved.rottenHearts;
player.boneHearts = saved.boneHearts;
player.boneHeartsMask = saved.boneHeartsMask;
}
// Seeds as many of a player's item RNGs as the save and the item configs have.
static void rng_seeds_restore(std::vector<RNG>& rngs, const std::vector<uint32_t>& seeds, size_t configCount)
{
for (size_t i = 0; i < std::min({rngs.size(), seeds.size(), configCount}); i++)
rngs[i].SetSeed(seeds[i], ITEM_RNG_SHIFT);
}
// 007ae4b0 Restores a player from its save: its controller (and character, rewinding), its name, collectible counts,
// trinkets (an unknown first one dropped for the second), voided items, Moving Box, forms, costumes and item RNGs,
// its health (hearts added again), sub player, history and inventory with the smelted trinkets counted from the
// history, its consumables, counters and stats, actives (unknown ones kept as they were), pockets (an unknown card
// dropped, the later slots moving up) and the rest of what it keeps. It is alive again and may start Astral Projection.
// A replaced player keeps its state. The Moving Box's saved entities take their spawner type as their 64-bit storage,
// as the original's copy does. The fields the curated player lacks are left out, as Entity_Player::StoreGameState
// leaves them out.
void Entity_Player::RestoreGameState(GameStatePlayer& saved)
{
Game& game = *g_game;
ItemConfig& items = g_manager->itemConfig;
std::vector<EntityConfig_Player>& configs = g_manager->entityConfig.players;
if (replacedPlayer) return;
SetControllerIndex(saved.controllerIndex, true);
if (playerType >= (int)configs.size()) playerType = PLAYER_ISAAC;
if (game.isRestoringGlowingHourglassState)
{
if (playerType != saved.playerType)
{
RemoveSkinCostume();
stop_costume_item_anims();
playerType = saved.playerType;
update_player_skin();
ResetColor();
}
if (isCoopGhost && !saved.isCoopGhost) RevivePlayerGhost();
}
if (playerType < 0 || playerType >= (int)configs.size())
log_printf(LOG_ERROR, "Could not load config for player type %d\n", playerType);
else name = configs[playerType].GetDisplayName();
size_t countCount = std::min({collectibleCounts.size(), saved.collectibleCounts.size(), items.collectibles.size()});
std::copy_n(saved.collectibleCounts.begin(), countCount, collectibleCounts.begin());
trinkets = saved.trinkets;
for (size_t i = 0; i < trinkets.size(); i++)
{
if ((trinkets[i] & TRINKET_ID_MASK) < items.trinkets.size()) continue;
if (i == 0) trinkets[0] = trinkets[1];
trinkets[1] = 0;
}
voidedCollectibles.clear();
for (int id : saved.voidedCollectibles)
if (id < (int)items.collectibles.size()) voidedCollectibles.push_back(id);
voidedPassives.clear();
for (VoidedPassive passive : saved.voidedPassives)
if (passive.id < (int)items.collectibles.size()) voidedPassives.push_back(passive.id);
movingBoxContents = saved.movingBoxContents;
for (EntitySaveState& box : movingBoxContents) box.int64Storage = box.spawnerType;
playerForms = saved.playerForms;
playerFormsRewarded = saved.playerFormsRewarded;
ClearCostumes();
for (CostumeItem costume : saved.costumes)
if ((uint32_t)costume.id < items.collectibles.size() && (uint32_t)costume.type <= ITEM_FAMILIAR)
if (ItemConfig_Item* item = item_by_kind(costume.type, costume.id)) AddCostume(item, false);
for (size_t i = 0; i < std::min(pillEffectUses.size(), saved.pillEffectUses.size()); i++)
pillEffectUses[i] = saved.pillEffectUses[i];
rng_seeds_restore(collectibleRNGs, saved.collectibleRngSeeds, items.collectibles.size());
rng_seeds_restore(trinketRNGs, saved.trinketRngSeeds, items.trinkets.size());
rng_seeds_restore(pillRNGs, saved.pillRngSeeds, items.pillEffects.size());
rng_seeds_restore(cardRNGs, saved.cardRngSeeds, items.cards.size());
goldenHearts = 0;
eternalHearts = 0;
boneHearts = 0;
blackHearts = 0;
soulHearts = 0;
maxHearts = 0;
redHearts = 0;
brokenHearts = 0;
rottenHearts = 0;
AddMaxHearts(saved.maxHearts, true);
blackHearts = saved.blackHearts;
AddSoulHearts(saved.soulHearts, false);
eternalHearts = saved.eternalHearts;
boneHearts = saved.boneHearts;
boneHeartsMask = saved.boneHeartsMask;
AddHearts(saved.redHearts, true, false);
if (saved.subPlayer && subPlayer) co_player_restore(*subPlayer, *saved.subPlayer);
if (!saved.coopBabies.empty()) reconstruction_missing("Entity_Player::RestoreGameState 007ae4b0: the co-op babies");
history.historyItems = saved.history;
inventory = saved.inventory;
game.hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS);
std::ranges::fill(smeltedTrinkets, SmeltedTrinket{});
for (HistoryItem& item : history.historyItems)
{
uint32_t id = (uint32_t)item.id & TRINKET_ID_MASK;
if (!item.isTrinket || id >= smeltedTrinkets.size()) continue;
if (item.id & TRINKET_GOLDEN_FLAG) smeltedTrinkets[id].goldenCount++;
else smeltedTrinkets[id].count++;
}
jarHearts = saved.jarHearts;
jarFlies = saved.jarFlies;
numCoins = saved.numCoins;
numKeys = saved.numKeys;
numBombs = saved.numBombs;
hasGoldenKey = saved.hasGoldenKey;
hasGoldenBomb = saved.hasGoldenBomb;
monkeyPawCounter = (uint16_t)saved.monkeyPawCounter;
totalDamageTaken = (uint16_t)saved.totalDamageTaken;
holyMantleState = saved.isHolyMantle ? HOLY_MANTLE_SAVED : 0;
tonsilCounter = saved.tonsilCounter;
tonsilCount = saved.tonsilCount;
numLeprosy = saved.numLeprosy;
speedModifier = saved.speedModifier;
fireDelayModifier = saved.fireDelayModifier;
damageModifier = saved.damageModifier;
tearRangeModifier = saved.tearRangeModifier;
shotSpeedModifier = saved.shotSpeedModifier;
luckModifier = saved.luckModifier;
donateLuck = saved.donateLuck;
potatoPeelerCounter = saved.potatoPeelerCounter;
potatoPeelerBandageCounter = saved.potatoPeelerBandageCounter;
brittleBonesUpgrades = saved.brittleBonesUpgrades;
redStewBonusDuration = saved.redStewBonusDuration;
brokenHearts = saved.brokenHearts;
rottenHearts = saved.rottenHearts;
effectiveSoulCharge = saved.effectiveSoulCharge;
urnSouls = saved.urnSouls;
numGigaBombs = saved.numGigaBombs;
rockBottomDamage = saved.rockBottomDamage;
rockBottomMaxFireDelay = saved.rockBottomMaxFireDelay;
rockBottomLuck = saved.rockBottomLuck;
rockBottomTearRange = saved.rockBottomTearRange;
rockBottomMoveSpeed = saved.rockBottomMoveSpeed;
rockBottomShotSpeed = saved.rockBottomShotSpeed;
reverseEmpressMaxHearts = saved.reverseEmpressMaxHearts;
reverseSunBoneHearts = saved.reverseSunBoneHearts;
forgottenBodyRoomIdx = saved.forgottenBodyRoomIdx;
forgottenBodyPos = saved.forgottenBodyPos;
maggyHealthDrainCooldown = saved.maggyHealthDrainCooldown;
echoChamberItems.clear();
for (PocketItem item : saved.echoChamberItems) echoChamberItems.push_back(item.id);
std::ranges::copy(saved.bagOfCraftingContent | std::views::take(bagOfCraftingContent.size()),
bagOfCraftingContent.begin());
std::ranges::copy(saved.poopSpellQueue | std::views::take(poopSpellQueue.size()), poopSpellQueue.begin());
poopMana = saved.poopMana;
effectiveBloodCharge = saved.effectiveBloodCharge;
itemCards = saved.itemCards;
modelingClayEffect = saved.modelingClayEffect;
keepersSackBonus = saved.keepersSackBonus;
isLevelStartPending = saved.isLevelStartPending;
hasCurseMistEffect = saved.hasCurseMistEffect;
consumablesBackup = saved.consumablesBackup;
if (!saved.curseMistFamiliars.empty())
reconstruction_missing("Entity_Player::RestoreGameState 007ae4b0: Curse of the Mist's familiars");
curseMistRedHearts = saved.curseMistRedHearts;
curseMistPocketItems = saved.curseMistPocketItems;
curseMistTrinkets = saved.curseMistTrinkets;
isCoopGhost = saved.isCoopGhost;
ghostPocketItems = saved.ghostPocketItems;
ghostTrinkets = saved.ghostTrinkets;
wildCardItemType = saved.wildCardItemType;
wildCardItem = saved.wildCardItem;
wildCardVarData = saved.wildCardVarData;
samsonBerserkCharge = saved.samsonBerserkCharge;
ibsCharge = saved.ibsCharge;
proceduralItems = saved.proceduralItems;
if (!proceduralItems.empty()) reconstruction_missing("GlitchedItemSet::recalculate 009e0500 (TMTRAINER items)");
edenSpeed = saved.edenSpeed;
edenFireDelay = saved.edenFireDelay;
edenDamage = saved.edenDamage;
edenTearRange = saved.edenTearRange;
edenShotSpeed = saved.edenShotSpeed;
edenLuck = saved.edenLuck;
vampireCharmKills = saved.vampireCharmKills;
for (size_t i = 0; i < activeItems.size(); i++)
{
const ActiveItemDesc& active = saved.activeItems[i];
if (active.item >= (int)items.collectibles.size()) continue;
activeItems[i].item = active.item;
activeItems[i].unknown = active.unknown;
activeItems[i].charge = active.charge;
activeItems[i].batteryCharge = active.batteryCharge;
activeItems[i].partialCharge = active.partialCharge;
activeItems[i].varData = active.varData;
}
playerSpriteScale = saved.playerSpriteScale;
if (variant == PLAYER_VARIANT_PLAYER && !isCoopGhost)
{
headScale = saved.headScale;
bodyScale = saved.bodyScale;
}
pocketItems = saved.pocketItems;
for (size_t i = 0; i < pocketItems.size(); i++)
{
PocketItem& pocket = pocketItems[i];
if (pocket.type != POCKET_CARD || pocket.id == 0 || pocket.id < (int)items.cards.size()) continue;
std::shift_left(pocketItems.begin() + (long)i, pocketItems.end(), 1);
pocketItems.back().id = 0;
}
rUaWizardTimer = saved.rUaWizardTimer;
bloodLustCounter = saved.bloodLustCounter;
deadCatLives = saved.deadCatLives;
friendBallEnemy = saved.friendBallEnemy;
purityState = saved.purityState;
immaculateConceptionState = saved.immaculateConceptionState;
cambionConceptionState = saved.cambionConceptionState;
conceptionFamiliarFlags = saved.conceptionFamiliarFlags;
d8DamageModifier = saved.d8DamageModifier;
d8SpeedModifier = saved.d8SpeedModifier;
d8RangeModifier = saved.d8RangeModifier;
d8FireDelayModifier = saved.d8FireDelayModifier;
goldenHearts = saved.goldenHearts;
planCKillCountdown = saved.planCKillCountdown;
imExcitedSpeedupCountdown = saved.imExcitedSpeedupCountdown;
holyMantleStacks = saved.holyMantleStacks;
ductTapeMode = saved.ductTapeMode;
isDead = false;
try_trigger_astral_projection();
}
// 007b0070 Finishes a saved player once its floor is entered: its familiars around it, then (unless it was replaced)
// the Forgotten's body for the Soul, its charmed enemies, the items whose effect lasts the floor, its bleeding, Greed's
// Gullet, the item it held up, its temporary effects (rebuilt from the persistent ones when it saved none), Dark Esau,
// the co-op ghost's entrance and a sub player the Soul of the Forgotten no longer needs. Its stats are evaluated again.
// The familiars, charmed enemies, Dark Esau and the co-op ghost wait for their takeovers.
void Entity_Player::RestoreGameState_PostLevelInit(GameStatePlayer& saved)
{
if (!saved.familiars.empty())
reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: the familiars (00630560)");
if (replacedPlayer) return;
if (playerType == PLAYER_THESOUL) spawn_forgotten_body();
if (!saved.charmedEnemies.empty())
reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: the charmed enemies");
levelEffectItems = saved.levelEffectItems;
bleedOutHealth = saved.bleedOutHealth;
if (bleedOutHealth > 0)
{
flags |= FLAG_BLEED_OUT;
bleedSource = EntityRef(this);
}
greedsGulletHearts = (short)saved.greedsGulletHearts;
greedsGulletOverflow = saved.greedsGulletOverflow;
queuedItem.item = saved.queuedItem.item;
queuedItem.charge = saved.queuedItem.charge;
queuedItem.flags = (uint8_t)saved.queuedItem.flags;
temporaryEffects.effects = saved.temporaryEffects;
strengthMaxHearts = saved.strengthMaxHearts;
if (temporaryEffects.effects.empty())
for (PersistentEffect& effect : saved.persistentEffects)
{
TemporaryEffect& restored = temporaryEffects.effects.emplace_back();
restored.item = item_by_kind(effect.type, effect.id);
restored.count = effect.count;
restored.cooldown = effect.cooldown;
}
if (saved.darkEsauHealth > 0)
reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: Dark Esau");
if (isCoopGhost) reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: the co-op ghost");
if (temporaryEffects.HasNullEffect(NULLITEM_SOUL_FORGOTTEN) && parent.get() && subPlayer)
reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: removing the sub player");
UpdateCanShoot();
cacheFlags |= ALL_CACHE_FLAGS;
EvaluateItems();
g_game->RemoveCompassEffect();
isPostLevelInitFinished = true;
}
// 005cb480 Dresses the player in the Wavy Cap costume its stacks of the effect call for: none, the first from one
// stack, the second from four and the third from seven, and sets the screen's dizziness to a tenth of the stacks.
// The original's co-op pass compares the player's stacks with its own, which changes nothing, so it is left out.
void Entity_Player::update_mini_mush_costume()
{
ItemConfig& items = g_manager->itemConfig;
std::array<ItemConfig_Item*, 3> costumes = {items.GetNullItem(NULLITEM_WAVY_CAP_1),
items.GetNullItem(NULLITEM_WAVY_CAP_2),
items.GetNullItem(NULLITEM_WAVY_CAP_3)};
int stacks = temporaryEffects.isDisabled ? 0
: temporaryEffects.GetNullEffectNum(NULLITEM_WAVY_CAP_1) +
temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_WAVY_CAP);
bool isRemoved = std::erase_if(costumeSpriteDescs, [&](CostumeSpriteDesc& worn)
{ return std::ranges::find(costumes, worn.item) != costumes.end(); }) > 0;
if (stacks >= MINI_MUSH_STACKS_THIRD) AddCostume(costumes[2], false);
else if (stacks >= MINI_MUSH_STACKS_SECOND) AddCostume(costumes[1], false);
else if (stacks >= 1) AddCostume(costumes[0], false);
else if (isRemoved) UpdateCostumes();
g_game->dizzyTargetIntensity = (float)(stacks / WAVY_CAP_STACKS_PER_DIZZINESS);
g_game->dizzyIntensityChangeSpeed = WAVY_CAP_DIZZINESS_SPEED;
}