Files
isaac-port/src/entity_player.cpp
T

1602 lines
64 KiB
C++

#include "entity_player.h"
#include "entity_player_characters.h"
#include "data.h"
#include "entity_effect.h"
#include "entity_familiar.h"
#include "entity_laser.h"
#include "entity_npc.h"
#include "entity_slot.h"
#include "active_items.h"
#include "hud.h"
#include "pocket_items.h"
#include "seeds.h"
#include "sfx_manager.h"
#include "game.h"
#include "log.h"
#include "lua_engine.h"
#include "manager.h"
#include "platform.h"
#include "room.h"
#include "room_grid.h"
#include <algorithm>
#include <filesystem>
constexpr float PLAYER_START_TEAR_HEIGHT = -23.75f;
constexpr float PLAYER_START_TEAR_FALLING_SPEED = 0.2f;
constexpr float PLAYER_START_TEAR_RANGE = 260;
constexpr float ROCK_BOTTOM_LUCK_UNSET = -9999;
constexpr int COSTUME_RESERVE = 32;
constexpr int MAX_PEE_BURST_COOLDOWN = 30;
constexpr int MONKEY_PAW_USES = 3;
constexpr int PLAYER_RENDER_Z_OFFSET = 5;
constexpr int TONSIL_COUNTER_MIN = 6;
constexpr int TONSIL_COUNTER_RANGE = 7;
constexpr int EDEN_COIN_RANGE = 5;
constexpr int TAINTED_EDEN_PLAYER_ID = 30;
constexpr int ITEMS_COST_MONEY_COINS = 69;
constexpr float START_SPOT_X = 320;
constexpr float START_SPOT_Y = 380;
constexpr float GREED_START_SPOT_Y = 280;
constexpr float BACKASSWARDS_START_OFFSET_Y = 100;
constexpr int BETHANY_START_CHARGE = 4;
constexpr int MAGDALENE_B_START_RED_HEARTS = 4;
constexpr int DEATHMATCH_HEART_SCALE = 8;
// The shift triples Init seeds the player's generators with: one stepping the init seed, one for each list of
// generators, and the one every item generator keeps.
constexpr uint32_t INIT_RNG_SHIFT = 5;
constexpr uint32_t COLLECTIBLE_RNG_SHIFT = 6;
constexpr uint32_t TRINKET_RNG_SHIFT = 7;
constexpr uint32_t PILL_RNG_SHIFT = 8;
constexpr uint32_t CARD_RNG_SHIFT = 9;
constexpr uint32_t ITEM_RNG_SHIFT = 35;
constexpr uint32_t PRE_LEVEL_RNG_SHIFT = 2;
constexpr uint32_t FLOOR_RNG_SHIFT = 12;
constexpr uint32_t JACOBS_CURSE_RNG_SHIFT = 66;
constexpr int JACOBS_CURSE_STEPS = 20;
constexpr int REDEMPTION_LIGHT_FADE = 2;
constexpr int NECROMANCER_OVERLAY_DELAY = 3;
// The step from a door slot (left, up, right, down) into the room.
constexpr float ASCENT_DOOR_STEPS[][2] = {{40, 0}, {0, 40}, {-40, 0}, {0, -40}};
constexpr int JACOBS_CURSE_STEP_FRAMES = 30;
constexpr int JACOBS_CURSE_MIN_FRAMES = 610;
constexpr int ASCENT_HOME_STAGE = 6;
constexpr int CAINS_EYE_CHANCE = 25;
constexpr int CANTRIPPED_CARDS = 3;
constexpr int CARD_SPECIAL_CHANCE = 25;
constexpr int CARD_START_RUNE_CHANCE = 10;
constexpr int COLOR_PRIORITY_TOP = 255;
constexpr int DAILY_CHRISTMAS = 19;
constexpr int EMPTY_HEART_RED_HEARTS = 3;
constexpr int EVENT_BONUS_ITEMS = 114;
constexpr int GIANTBOOK_EMPTY_HEART = 41;
constexpr int LOCUST_SUBTYPE_START = 25;
constexpr int PEE_ALPHA = 180;
constexpr int PEE_OFFSET = 244;
constexpr int PICKUP_GRAB_BAG = 69;
constexpr int PICKUP_HEART = 10;
constexpr float PICKUP_SPAWN_RADIUS = 40;
constexpr int POCKET_ACTIVE_SLOT = 2;
// A removed player lets go of what it holds at a tenth of its speed.
constexpr float HELD_RELEASE_SPEED = 0.1f;
constexpr int RED_REDEMPTION_KEY_CHARGES = 20;
constexpr uint8_t WOODEN_CROSS_STACK = 0x10;
constexpr std::string_view COSTUMES_DIR = "costumes";
constexpr std::array<std::string_view, 6> SKIN_COLOR_SUFFIXES = {"_white", "_black", "_blue",
"_red", "_green", "_grey"};
constexpr const char* CHARGE_BAR_PATHS[CHARGE_BAR_COUNT] = {
"gfx/chargebar.anm2", "gfx/chargebar.anm2",
"gfx/chargebar_maw.anm2", "gfx/chargebar_revelation.anm2",
"gfx/chargebar_poop.anm2", "gfx/chargebar_berserk.anm2",
"gfx/chargebar_sumptorium.anm2"};
// Whether a resource file exists, after the mods redirected it.
static bool is_file_found(const std::string& path)
{
std::error_code error;
return std::filesystem::exists(resource_path(path), error);
}
// A color from bytes as ColorParams::set_from_bytes builds it: a tint and an offset over 255, no colorize.
static ColorMod color_from_bytes(int tintRed, int tintGreen, int tintBlue, int tintAlpha, int offsetRed,
int offsetGreen, int offsetBlue)
{
constexpr float BYTE = 1.0f / 255;
return {{tintRed * BYTE, tintGreen * BYTE, tintBlue * BYTE, tintAlpha * BYTE},
{0, 0, 0, 0},
{offsetRed * BYTE, offsetGreen * BYTE, offsetBlue * BYTE}};
}
// A random card as the run hands one out: drawn from a seed, then offered to the mods' card callback.
static int card_roll(uint32_t seed, int runeChance, bool isPlaying)
{
int card = ItemPool::GetCardEx((int)seed, CARD_SPECIAL_CHANCE, runeChance, runeChance, true);
RNG rng = rng_make(seed, ITEM_RNG_SHIFT);
return lua_engine_get().GetCard({.rng = &rng, .card = card, .isPlaying = isPlaying, .isRunes = isPlaying});
}
// A generator with a seed and the shift triple at an index of RNG's table.
RNG rng_make(uint32_t seed, uint32_t shiftIndex)
{
RNG rng{};
rng.SetSeed(seed, shiftIndex);
return rng;
}
// Whether an unlock counts for this run: earned, or given to every daily and debug run.
bool is_run_unlocked(int achievement)
{
Game* game = g_game;
if (g_manager->persistentGameData.achievements[achievement]) return true;
return g_manager->state == MANAGER_STATE_GAME && game && (game->dailyChallenge._id != 0 || game->isDebug);
}
// Fills a list of item generators, one per id, each seeded by the next step of a generator of its own.
static void item_rngs_fill(std::vector<RNG>& rngs, size_t count, uint32_t seed, uint32_t shiftIndex)
{
RNG stepper = rng_make(seed, shiftIndex);
for (size_t i = 0; i < count; i++) rngs.push_back(rng_make(stepper.Next(), ITEM_RNG_SHIFT));
}
// 00753da0 Makes an empty player, its members at their defaults.
Entity_Player::Entity_Player()
{
temporaryEffects.player = this;
history.player = this;
inventory.fill(-1);
pocketItems.fill({0, POCKET_CARD});
curseMistPocketItems.fill({0, POCKET_CARD});
ghostPocketItems.fill({0, POCKET_CARD});
}
// 00754ed0, 00754d60 Unlinks the twin and frees a sub player the room does not hold, then forgets being a transition's.
Entity_Player::~Entity_Player()
{
if (Entity* twin = twinPlayer)
{
twin->ClearReferences();
twinPlayer = nullptr;
}
if (subPlayer && !subPlayer->isValid)
{
subPlayer->ClearReferences();
delete subPlayer;
}
if (!g_game) return;
PlayerManager& players = g_game->playerManager;
if (players.stageTransitionPlayer == this) players.stageTransitionPlayer = nullptr;
if (players.roomTransitionPlayer == this) players.roomTransitionPlayer = nullptr;
}
// 00755470 Starts a player of a variant: a character (subtype is the player type), a co-op baby (subtype is the skin)
// or an extra player. Seeds one generator per collectible, trinket, pill effect and card, resets every stat and
// counter, loads the sprites, picks the controller, puts on the skin, and gives a character its starting health and
// pickups. Every player starts with the tears weapon.
void Entity_Player::Init(int entityType, int entityVariant, int subType, uint32_t seed)
{
Manager& manager = *g_manager;
ItemConfig& items = manager.itemConfig;
if (seed == 0) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"RNG Seed is zero!\n");
RNG initRng = rng_make(seed, INIT_RNG_SHIFT);
item_rngs_fill(collectibleRNGs, items.collectibles.size(), initRng.Next(), COLLECTIBLE_RNG_SHIFT);
item_rngs_fill(trinketRNGs, items.trinkets.size(), initRng.Next(), TRINKET_RNG_SHIFT);
item_rngs_fill(pillRNGs, items.pillEffects.size(), initRng.Next(), PILL_RNG_SHIFT);
item_rngs_fill(cardRNGs, items.cards.size(), initRng.Next(), CARD_RNG_SHIFT);
if (!history.isLocked)
{
history.historyItems.clear();
inventory.fill(-1);
}
int entitySubType = subType;
if (entityVariant == PLAYER_VARIANT_COOP_BABY)
{
playerType = PLAYER_ISAAC;
isGlitchBaby = subType == BABY_GLITCH;
if (isGlitchBaby) entitySubType = (int)GetGlitchBabySubType();
babySkin = std::min(entitySubType, (int)BABY_BASIC);
}
else
{
babySkin = -1;
if ((size_t)subType >= manager.entityConfig.players.size())
log_printf(LOG_ASSERT, "Got non existing player type %d in Player::Init!", subType);
playerType = subType;
}
name.clear();
uint32_t entitySeed = initRng.Next();
Entity::Init(entityType, entityVariant, entitySubType, entitySeed);
renderZOffset = PLAYER_RENDER_Z_OFFSET;
log_printf(LOG_INFO, "[Frame: %d] Initialized player with Variant %d and Subtype %d\n", manager.framecount,
entityVariant, entitySubType);
temporaryEffects.ClearEffects(true);
stats_reset();
tonsilCounter = (short)(trinketRNGs[TRINKET_TONSIL].Next() % TONSIL_COUNTER_RANGE + TONSIL_COUNTER_MIN);
tonsilCount = 0;
numLeprosy = 0;
UpdateCanShoot();
lastVelocity = velocity;
isPostLevelInitFinished = variant == PLAYER_VARIANT_COOP_BABY;
collectibleCounts.assign(items.collectibles.size(), 0);
playerForms.fill(0);
playerFormsRewarded = 0;
trinkets.fill(0);
smeltedTrinkets.assign(items.trinkets.size(), {});
pillEffectUses.assign(items.pillEffects.size(), 0);
colorOverride = COLOR_DEFAULT;
pocketItems.fill({0, POCKET_CARD});
queuedItem.charge = 0;
queuedItem.item = nullptr;
isHeldItemVisible = false;
tear_stats_reset();
sprites_load();
delayedSfxId = 0;
delayedSfxDelay = 0;
bool isOwnController = variant == PLAYER_VARIANT_PLAYER && subType != PLAYER_ESAU && subType != PLAYER_THESOUL_B;
SetControllerIndex(isOwnController ? manager.activeControllerIndex : -1, false);
if (!config) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Player Config invalid!\n");
else sprite.Load(config->anm2Path, GRAPHICS_DEFER);
if (variant == PLAYER_VARIANT_PLAYER)
{
sprite.SetFrame("WalkDown", 0);
sprite.SetOverlayFrame("HeadDown", 0);
}
isControlsEnabled = true;
controlsCooldown = 0;
fireBlockCooldown = 0;
costumeSpriteDescs.reserve(COSTUME_RESERVE);
ClearCostumes();
playerSpriteScale = vector_make(1, 1);
bodyScale = vector_make(1, 1);
headScale = vector_make(1, 1);
if (variant == PLAYER_VARIANT_PLAYER) update_player_skin();
else if (variant == PLAYER_VARIANT_COOP_BABY)
{
int skin = babySkin;
if (isGlitchBaby) babySkin = BABY_GLITCH;
InitBabySkin();
babySkin = skin;
}
cacheFlags = CACHE_ALL;
footprintColor1 = {};
footprintColor2 = {};
pitfallState = 0;
pitfallTimer = 0;
babyFamiliar = nullptr;
if (variant == PLAYER_VARIANT_COOP_BABY)
{
if (babySkin == BABY_BLOAT || babySkin == BABY_YBAB || babySkin == BABY_APOLLYON)
reconstruction_missing("Entity_Player::Init 00755470 (the co-op babies that come with a familiar)");
hasBabyRoomShield = true;
}
links_reset();
if (variant == PLAYER_VARIANT_PLAYER) InitPreLevelInitStats();
shadowImage = Manager::LoadImage("gfx/shadow.png");
emotes.Load();
if (Entity* tether = tetheredEffect)
{
tether->Remove();
tetheredEffect = nullptr;
}
if (playerType == PLAYER_BETHANY && g_game->challenge != CHALLENGE_BLOODY_MARY &&
g_game->challenge != CHALLENGE_BAPTISM_BY_FIRE)
{
EvaluateItems();
AddActiveCharge(BETHANY_START_CHARGE, 0, false, false, false);
}
static_cast<LuaEngine*>(g_luaEngine)->PostPlayerInit(this);
}
// Resets the counters and stats Init starts every player with.
void Entity_Player::stats_reset()
{
subPlayer = nullptr;
isCoopGhost = false;
hasGoldenKey = false;
hasGoldenBomb = false;
goldenHearts = 0;
health = 1;
maxHitPoints = 1;
boneHeartsMask = 0;
boneHearts = 0;
eternalHearts = 0;
blackHearts = 0;
numKeys = 0;
numCoins = 0;
numBombs = 0;
soulHearts = 0;
maxHearts = 0;
redHearts = 0;
edenLuck = 0;
edenShotSpeed = 0;
edenTearRange = 0;
edenFireDelay = 0;
edenSpeed = 0;
edenDamage = 0;
jarHearts = 0;
jarFlies = 0;
firstVisitRooms = 0;
techFiveDelay = 0;
trinityShieldAngle = 0;
gnawedLeafTimer = 0;
lastActionTriggers = 0;
bloodLustCounter = 0;
deadCatLives = 0;
damageCooldown = 0;
weaponTypes.fill(false);
weaponTypes[WEAPON_TEARS] = true;
for (WeaponPtr& weapon : weapons) weapon.reset();
weapons[1] = weapon_create(WEAPON_TEARS, this);
markedTarget = nullptr;
heldEntity = nullptr;
tractorBeam = 0;
shootHeldFrames = 0;
azazelsRageLaser = nullptr;
shootDirectionHistory.clear();
lastShootTime = 0;
doubleTapFrames = 0;
ibsChargeBar = 0;
isIbsChargeSoundPending = true;
megaBlastLaser = nullptr;
breathOfLifeEffect = nullptr;
itemState = 0;
numBlueFlies = 0;
numBlueSpiders = 0;
itemHoldCooldown = 0;
purityState = 0;
immaculateConceptionState = 0;
cambionConceptionState = 0;
conceptionFamiliarFlags = 0;
speedModifier = 0;
fireDelayModifier = 0;
damageModifier = 0;
tearRangeModifier = 0;
shotSpeedModifier = 0;
luckModifier = 0;
donateLuck = 0;
coopBabyBuffTimers.fill(0);
imExcitedSpeedupCountdown = 0;
potatoPeelerCounter = 0;
potatoPeelerBandageCounter = 0;
greedsGulletHearts = 0;
greedsGulletOverflow = 0;
greedsGulletRedHearts = 0;
isUpdatingGreedsGullet = false;
megaBlastDuration = 0;
recentMovementVector = {};
slipperyTimer = 0;
deadEyeCharges = 0;
deadEyeMisses = 0;
epiphoraCharge = 0;
peeBurstCooldown = 0;
maxPeeBurstCooldown = MAX_PEE_BURST_COOLDOWN;
bladderCharge = 0;
maxBladderCharge = 0;
isUrethraBlocked = false;
nextUrethraBlockFrame = 0;
mawOfTheVoidChargeTimer = 0;
taurusSpeedBonus = 0;
monkeyPawCounter = MONKEY_PAW_USES;
rUaWizardTimer = 0;
holyMantleState = 0;
isBrokenRemotePending = false;
cursedPennyPending = 0;
vampireCharmKills = 0;
jumperCablesKills = 0;
isActiveUsed = false;
isPlayingExtraAnimation = false;
isHurtPending = false;
isPlayingItemAnimation = false;
strengthMaxHearts = 0;
friendBallEnemy.type = 0;
d8DamageModifier = 1;
d8FireDelayModifier = 1;
d8RangeModifier = 1;
d8SpeedModifier = 1;
ponyCharge = 0;
flashCountdown = 0;
planCKillCountdown = 0;
metronomeCollectibleId = 0;
brittleBonesUpgrades = 0;
bleedOutHealth = 0;
holyMantleStacks = 0;
ductTapeMode = 0;
threeDollarBillItem = 0;
}
// Resets the tear stats, the active items and where the player moves, looks and shoots.
void Entity_Player::tear_stats_reset()
{
maxFireDelay = 10;
shotSpeed = 1;
damage = 3.5f;
tearHeight = PLAYER_START_TEAR_HEIGHT;
tearFallingSpeed = PLAYER_START_TEAR_FALLING_SPEED;
tearFallingAcceleration = 0;
tearFlags.reset();
luck = 0;
moveSpeed = 1;
cacheFlags = 0;
canFly = false;
firedTearCount = 0;
meleeDamage = 3.5f;
tearRange = PLAYER_START_TEAR_RANGE;
itemStateCooldown = 0;
activeItems.fill({});
tearDisplacement = 1;
bombPlaceDelay = 0;
forgottenSwapFormCooldown = 0;
headAnim = "HeadDown";
blinkTime = 0;
headDirectionTime = 0;
moveDirection = DIRECTION_NONE;
headDirection = DIRECTION_DOWN;
fireDirection = DIRECTION_NONE;
aimDirection = {};
areOpposingShootDirectionsPressed = false;
lastDirection = {};
movementVector = {};
bodyAngle = 0;
tearsOffset = {};
lastDamageFlags = 0;
roomDamageTaken = 0;
totalDamageTaken = 0;
}
// Loads the blood gush, crown and charge bar sprites a player has not loaded yet, the crowns drawn additively.
void Entity_Player::sprites_load()
{
if (!bloodGushSprite.isLoaded)
{
bloodGushSprite.Load("gfx/characters/blood gush.anm2", GRAPHICS_LOAD);
bloodGushSprite.Play("Idle");
}
int sourceFactor =
KAGE::Graphics::manager.isPremultipliedAlpha ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA;
for (auto [crown, path] : {std::pair{&crownOfLightSprite, "gfx/CrownOfLight.anm2"},
std::pair{&darkPrincesCrownSprite, "gfx/DarkPrincesCrown.anm2"}})
{
if (crown->isLoaded) continue;
crown->Load(path, GRAPHICS_LOAD);
crown->GetLayer(1)->blendMode = {BLEND_EQUATION_ADD, sourceFactor, BLEND_FACTOR_ONE, BLEND_FACTOR_ONE,
BLEND_FACTOR_ONE};
crown->scale = vector_make(1, 1);
}
for (int i = 0; i < CHARGE_BAR_COUNT; i++)
{
if (chargeBarSprites[i].isLoaded) continue;
chargeBarSprites[i].Load(CHARGE_BAR_PATHS[i], GRAPHICS_LOAD);
chargeBarSprites[i].scale = vector_make(1, 1);
}
}
// Forgets the entities, item lists and character state a player linked to, as Init does before the starting stats.
void Entity_Player::links_reset()
{
moveToTarget = {};
voidedCollectibles.clear();
voidedPassives.clear();
movingBoxContents.clear();
extensionCordIndex = -1;
hallowedGroundCountdown = 0;
damageMultiplierStacks = 0;
lastDamageMultiplierStacks = 0;
forgottenBody = nullptr;
playerHUD.reset();
heightVelocity = 0;
redStewBonusDuration = 0;
salvationEffect = nullptr;
astralProjectionBody = nullptr;
brokenHearts = 0;
rottenHearts = 0;
effectiveSoulCharge = 0;
marsCooldown = 0;
isMarsDashReady = true;
marsDashDirection = -1;
marsLastTapDirection = 0;
marsTapFrames = 0;
poisonDamageFrames = 0;
urnSouls = 0;
numGigaBombs = 0;
rockBottomMoveSpeed = 0;
rockBottomMaxFireDelay = 0;
rockBottomDamage = 0;
rockBottomTearRange = 0;
rockBottomShotSpeed = 0;
rockBottomLuck = ROCK_BOTTOM_LUCK_UNSET;
reverseEmpressMaxHearts = 0;
reverseChariotMoveCooldown = 0;
reverseSunBoneHearts = 0;
revelationChargeTimer = 0;
montezumaChargeTimer = 0;
jupiterCharge = 0;
maggyHealthDrainCooldown = 0;
maggySwingCooldown = 0;
jellyBellyBounceTimer = 0;
montezumaLaser = nullptr;
forgottenBodyRoomIdx = FORGOTTEN_BODY_ROOM_NONE;
backupPlayer = nullptr;
echoChamberItems.clear();
suplexState = 0;
suplexAimCountdown = 0;
suplexTargetPos = {};
suplexLandPos = {};
bagOfCraftingContent.fill(0);
bagOfCraftingOutput = 0;
bagOfCraftingPool = -1;
bagOfCraftingHoldFrames = 0;
poopSpellQueue.fill(0);
poopMana = 0;
eveSumptoriumCharge = 0;
effectiveBloodCharge = 0;
forgottenBHeight = 0;
forgottenBHeightVelocity = 0;
darkArtsLastSnare = nullptr;
isDarkArtsBlastPending = false;
modelingClayEffect = 0;
keepersSackBonus = 0;
darkEsau = nullptr;
isLevelStartPending = false;
proceduralItems.clear();
extraCollectibleCounts.assign(g_manager->itemConfig.collectibles.size(), 0);
extraTrinketCounts.assign(g_manager->itemConfig.trinkets.size(), 0);
grantedCollectibleCountdown = 0;
grantedCollectibleFlags = 0;
hasCurseMistEffect = false;
curseMistPocketItems.fill({0, POCKET_CARD});
curseMistTrinkets.fill(0);
ghostPocketItems.fill({0, POCKET_CARD});
ghostTrinkets.fill(0);
wildCardItemType = WILD_CARD_NONE;
wildCardItem = 0;
wildCardVarData = 0;
samsonBerserkCharge = 0;
ibsCharge = 0;
}
// 007bbbd0 Gives a character the name, health and pickups its players.xml entry starts with, then what its type, Eden's
// rolls, the challenge and the seeds add. Eden rolls its health, a pickup and its stat offsets from the init seed.
void Entity_Player::InitPreLevelInitStats()
{
Game& game = *g_game;
EntityConfig_Player* playerConfig = g_manager->entityConfig.GetPlayer(playerType);
RNG rng = rng_make(initSeed, PRE_LEVEL_RNG_SHIFT);
if (!playerConfig)
{
log_printf(LOG_ASSERT, "Could not load config for player type %d\n", playerType);
return;
}
name = playerConfig->GetDisplayName();
if (playerType == PLAYER_THELOST || playerType == PLAYER_THELOST_B) AddEntityFlags(FLAG_NO_SPIKE_DAMAGE);
maxHearts = game.deathmatchManager.is_active() ? playerConfig->heart * DEATHMATCH_HEART_SCALE : playerConfig->heart;
redHearts = maxHearts;
soulHearts = playerConfig->armor;
switch (playerType)
{
case PLAYER_THEFORGOTTEN:
soulHearts = 0;
redHearts = 0;
maxHearts = 0;
AddBoneHearts(playerConfig->heart / 2);
AddHearts(playerConfig->heart, false, false);
AddEntityFlags(FLAG_NO_SPIKE_DAMAGE);
init_forgotten_twin();
break;
case PLAYER_THESOUL:
init_forgotten_twin();
break;
case PLAYER_KEEPER:
if (is_run_unlocked(ACHIEVEMENT_KEEPER_HOLDS_A_PENNY))
{
maxHearts += 2;
redHearts += 2;
}
break;
case PLAYER_LAZARUS_B:
if (!backupPlayer && playerIndex >= 0 && !game.isStartingFromState &&
!game.isRestoringGlowingHourglassState)
{
backupPlayer = new Entity_Player();
backupPlayer->Init(type, variant, PLAYER_LAZARUS2_B, initSeed);
backupPlayer->backupPlayer = this;
backupPlayer->isExists = false;
}
break;
case PLAYER_BETHANY:
if (HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) IncrementPlayerFormCounter(PLAYER_FORM_BOOKWORM, 1);
break;
case PLAYER_BETHANY_B:
AddBloodCharge(redHearts);
maxHearts = 0;
redHearts = 0;
break;
case PLAYER_JACOB_B:
init_forgotten_twin();
break;
default:
break;
}
AddBlackHearts(playerConfig->blackHeart);
AddBrokenHearts(playerConfig->brokenHeart);
if (playerType == PLAYER_MAGDALENE_B) redHearts = std::min(maxHearts, MAGDALENE_B_START_RED_HEARTS);
if (!game.playerManager.playerList.empty()) game.GetPlayer(0)->ConsumableCountChanged(-1);
if (!isSpawningHelperPlayers)
{
if (playerType == PLAYER_BLUEBABY_B)
{
AddPoopMana(playerConfig->bombs);
poop_spell_roll();
}
else AddBombs(playerConfig->bombs);
AddKeys(playerConfig->keys);
AddCoins(playerConfig->coins);
}
if (playerType == PLAYER_KEEPER && is_run_unlocked(ACHIEVEMENT_KEEPER_HOLDS_A_PENNY)) numCoins++;
else if (playerType == PLAYER_BETHANY && soulHearts > 0)
{
AddSoulCharge(soulHearts);
soulHearts = 0;
if (!game.deathmatchManager.is_active()) blackHearts = 0;
}
if (playerConfig->id == PLAYER_EDEN || playerConfig->id == TAINTED_EDEN_PLAYER_ID) eden_stats_roll(rng);
if (game.challenge != 0)
{
ChallengeParam& challenge = g_manager->GetChallengeParams((int)game.challenge);
if (challenge.maxHearts != 0) AddMaxHearts(challenge.maxHearts, false);
if (challenge.hearts != 0) AddHearts(challenge.hearts, false, false);
if (challenge.soulHearts > 0) AddSoulHearts(challenge.soulHearts, false);
if (challenge.blackHearts > 0) AddBlackHearts(challenge.blackHearts);
if (challenge.coins != 0) AddCoins(challenge.coins);
UpdateBlackHeartMask();
}
if (game.seedEffects.HasSeedEffect(SEED_ITEMS_COST_MONEY)) AddCoins(ITEMS_COST_MONEY_COINS);
if (game.seedEffects.HasSeedEffect(SEED_NO_FACE))
AddCostume(g_manager->itemConfig.GetNullItem(NULLITEM_BLANKFACE), false);
}
// Rolls Eden's health, a starting pickup and its stat offsets, in the original's order of draws.
void Entity_Player::eden_stats_roll(RNG& rng)
{
uint32_t heartRoll = rng.Next() & 3;
maxHearts = (int)heartRoll * 2;
redHearts = maxHearts;
soulHearts = (int)rng.RandomInt(4 - heartRoll) * 2;
if (redHearts == 0 && soulHearts < 3) soulHearts = 4;
uint32_t pickupRoll = rng.Next();
if (pickupRoll % 3 != 0 && (rng.Next() & 1))
{
uint32_t kind = rng.Next() % 3;
if (kind == 0) numCoins = (int)(rng.Next() % EDEN_COIN_RANGE) + 1;
else if (kind == 1) numKeys = 1;
else numBombs = (int)rng.RandomInt(2) + 1;
}
eden_offsets_roll(*this, rng);
}
// The part of 007bc740 that rolls Eden's starting pickups and items: a trinket on a third of the rolls, else maybe a
// card or a pill, then the first active and the first passive among 100 random collectibles Eden may start with.
void Entity_Player::eden_items_roll(RNG& rng)
{
constexpr int EDEN_ITEM_ROLLS = 100;
constexpr std::array<int, 3> REMOVED_COLLECTIBLES = {235, 43, 61};
ItemConfig& items = g_manager->itemConfig;
ItemPool& pool = g_game->itemPool;
if (rng.Next() % 3 == 0) AddTrinket((int)pool.GetTrinket(TRINKET_DRAW_TAKE), true);
else if ((rng.Next() & 1) == 0)
{
if ((rng.Next() & 1) == 0) AddPocketItem(card_roll(rng.Next(), 0, false), POCKET_CARD);
else AddPocketItem(ItemPool::GetPill(rng.Next()), POCKET_PILL);
}
int active = 0;
int passive = 0;
uint32_t range = (uint32_t)items.collectibles.size() - 1;
for (int roll = 0; roll < EDEN_ITEM_ROLLS; roll++)
{
uint32_t next = rng.Next();
int id = (int)(range == 0 ? 0 : next % range) + 1;
ItemConfig_Item* item = items.GetCollectible(id);
if (std::ranges::find(REMOVED_COLLECTIBLES, id) != REMOVED_COLLECTIBLES.end() || !item || item->HasTags(TAG_NO_EDEN) ||
!item->IsAvailableEx(AVAILABLE_ALL))
continue;
int& kept = item->type == ITEM_ACTIVE ? active : passive;
if (kept == 0) kept = id;
}
for (int id : {active, passive})
if (id != 0)
{
AddCollectible(id, -1, true, 0, 0);
pool.RemoveCollectible(id, REMOVE_ANY, REMOVE_APPLY);
}
}
// Gives the player a starting collectible, as the run's start does: added as picked up, out of the pools, and its
// temporary effect gone.
void Entity_Player::starting_collectible_add(int id)
{
AddCollectible(id, -1, true, 0, 0);
g_game->itemPool.RemoveCollectible(id, REMOVE_ANY, REMOVE_APPLY);
if (ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(id)) temporaryEffects.RemoveEffect(item, 1);
}
// Gives the player a starting trinket and takes it out of the trinket pool.
void Entity_Player::starting_trinket_add(int id)
{
AddTrinket(id, true);
std::vector<TrinketPoolItem>& pool = g_game->itemPool.trinketPoolItems;
if (id <= 0 || id >= (int)pool.size() || !pool[id].isAvailable || !pool[id].isInPool) return;
pool[id].isAvailable = false;
g_game->itemPool.numAvailableTrinkets--;
}
// 007bc740 Gives a character the items the level start leaves it: its card or pill, its config's collectibles and the
// unlocked ones (D6, Wooden Nickel, Razor Blade), the daily's, its innate items and pocket active, its trinket, Eden's
// rolled items, the Mega Satan key pieces and the challenge's lists. Then it evaluates the stats, shares the pickups
// and starts the twins and companions. Straw Man's player only evaluates. Netplay's per-player save data is offline.
// The original's daily specials and its Backasswards and Cantripped extras stop here until reached.
void Entity_Player::InitPostLevelInitStats()
{
Game& game = *g_game;
EntityConfig_Player* playerConfig = g_manager->entityConfig.GetPlayer(playerType);
RNG rng = rng_make(initSeed, PRE_LEVEL_RNG_SHIFT);
ChallengeParam& challenge = game.GetChallengeParams();
int startFrame = game.frameCount;
if (!playerConfig) log_printf(LOG_ASSERT, "Could not load config for player type %d\n", playerType);
if (temporaryEffects.HasCollectibleEffect(COLLECTIBLE_STRAW_MAN))
{
EvaluateItems();
game.GetPlayer(0)->ConsumableCountChanged(-1);
isPostLevelInitFinished = true;
return;
}
if (game.dailyChallenge._specialDailyId != 0)
reconstruction_missing("Entity_Player::InitPostLevelInitStats 007bc740 (a daily's special start)");
if (playerConfig->card > 0) AddPocketItem(playerConfig->card, POCKET_CARD);
else if (playerConfig->card < 0) AddPocketItem(card_roll(initSeed, CARD_START_RUNE_CHANCE, true), POCKET_CARD);
else if (playerConfig->pill > 0) AddPocketItem(playerConfig->pill, POCKET_PILL);
else if (playerConfig->pill < 0) AddPocketItem(ItemPool::GetPill(initSeed), POCKET_PILL);
else if (playerType == PLAYER_MAGDALENE && is_run_unlocked(ACHIEVEMENT_MAGDALENE_HOLDS_A_PILL))
magdalene_pill_add();
std::vector<int> items = playerConfig->collectibles;
if (game.challenge == 0)
{
if (playerType == PLAYER_ISAAC && is_run_unlocked(ACHIEVEMENT_ISAAC_HOLDS_THE_D6))
items.push_back(COLLECTIBLE_D6);
if (playerType == PLAYER_KEEPER && is_run_unlocked(ACHIEVEMENT_KEEPER_HOLDS_WOODEN_NICKEL))
items.push_back(COLLECTIBLE_WOODEN_NICKEL);
if (playerType == PLAYER_EVE && is_run_unlocked(ACHIEVEMENT_EVE_HOLDS_RAZOR_BLADE))
items.push_back(COLLECTIBLE_RAZOR_BLADE);
}
if (!game.deathmatchManager.is_active())
for (int id : items) starting_collectible_add(id);
apply_innate_collectibles();
if (game.challenge == CHALLENGE_RED_REDEMPTION)
{
SetPocketActiveItem(COLLECTIBLE_RED_KEY, POCKET_ACTIVE_SLOT, false);
activeItems[POCKET_ACTIVE_SLOT].varData = RED_REDEMPTION_KEY_CHARGES;
}
else if (playerConfig->pocketActiveID != 0)
SetPocketActiveItem(playerConfig->pocketActiveID, POCKET_ACTIVE_SLOT, false);
int trinket = playerConfig->trinket;
if (trinket == 0 && game.challenge == 0)
{
if (playerType == PLAYER_KEEPER && is_run_unlocked(ACHIEVEMENT_KEEPER_HOLDS_STORE_KEY))
trinket = TRINKET_STORE_KEY;
else if (playerType == PLAYER_CAIN && is_run_unlocked(ACHIEVEMENT_CAIN_HOLDS_PAPERCLIP))
trinket = TRINKET_PAPER_CLIP;
else if (playerType == PLAYER_SAMSON && is_run_unlocked(ACHIEVEMENT_SAMSON_HOLDS_CHILDS_HEART))
trinket = TRINKET_CHILDS_HEART;
}
if (trinket != 0 && !game.deathmatchManager.is_active()) starting_trinket_add(trinket);
if ((playerConfig->id == PLAYER_EDEN || playerConfig->id == TAINTED_EDEN_PLAYER_ID) &&
!game.deathmatchManager.is_active())
eden_items_roll(rng);
if (challenge.isMegaSatan)
{
starting_collectible_add(COLLECTIBLE_KEY_PIECE_1);
starting_collectible_add(COLLECTIBLE_KEY_PIECE_2);
}
if (game.challenge == 0 && game.dailyChallenge._id == 0)
{
if (startFrame == 0 && (g_manager->persistentGameData.eventCounters[EVENT_BONUS_ITEMS] & 0xffff) != 0)
reconstruction_missing("Entity_Player::InitPostLevelInitStats 007bc740 (the bonus starting items)");
}
else if (twin_get() && twin_get()->playerIndex != -1 && playerIndex > twin_get()->playerIndex && twin_get() != this)
{
for (int id : challenge.collectibleTwinList)
if (id < 0) RemoveCollectible(-id, false, 0, true);
else starting_collectible_add(id);
}
else
{
for (int id : challenge.collectibleList)
if (id < 0) RemoveCollectible(-id, false, 0, true);
else starting_collectible_add(id);
for (int id : challenge.trinketList) starting_trinket_add(id);
if (challenge.startingPill != PILLEFFECT_NULL)
reconstruction_missing("Entity_Player::InitPostLevelInitStats 007bc740 (a challenge's starting pill)");
if (challenge.startingCard > 0) AddPocketItem(challenge.startingCard, POCKET_CARD);
else if (challenge.startingCard < 0) AddPocketItem(card_roll(rng.Next(), 0, false), POCKET_CARD);
}
EvaluateItems();
game.GetPlayer(0)->ConsumableCountChanged(-1);
if (!replacedPlayer) companions_init();
if (game.challenge == CHALLENGE_BACKASSWARDS)
reconstruction_missing("Entity_Player::InitPostLevelInitStats 007bc740 (Backasswards' ten items)");
if (game.challenge == CHALLENGE_CANTRIPPED)
for (int i = 0; i < CANTRIPPED_CARDS; i++) AddItemCard(0);
isPostLevelInitFinished = true;
}
// Starts the companions some characters begin with: Jacob's Esau, Tainted Forgotten's soul, Tainted Apollyon's locust
// and Tainted Jacob's Dark Esau curse.
void Entity_Player::companions_init()
{
Game& game = *g_game;
switch (playerType)
{
case PLAYER_JACOB:
InitTwin(PLAYER_ESAU)->InitPostLevelInitStats();
break;
case PLAYER_THEFORGOTTEN_B:
if (!isCoopGhost) InitTwin(PLAYER_THESOUL_B)->InitPostLevelInitStats();
break;
case PLAYER_APOLLYON_B:
game.Spawn({.position = pos,
.spawner = this,
.subType = LOCUST_SUBTYPE_START,
.type = ENTITY_FAMILIAR,
.variant = Entity_Familiar::ABYSS_LOCUST,
.seed = Random()})
->Update();
break;
case PLAYER_JACOB_B:
if (game.challenge != CHALLENGE_RED_REDEMPTION) jacobs_curse_add();
break;
default:
break;
}
}
// Starts the countdown to Dark Esau's next charge on Tainted Jacob: 20 to 600 seconds after 610 frames, drawn from the
// devil room generator.
void Entity_Player::jacobs_curse_add()
{
temporaryEffects.RemoveNullEffect(NULLITEM_JACOBS_CURSE, -1);
ItemConfig_Item* item = g_manager->itemConfig.GetNullItem(NULLITEM_JACOBS_CURSE);
if (!item) return;
RNG rng = rng_make(g_game->devilAngelRoomRNG._seed, JACOBS_CURSE_RNG_SHIFT);
TemporaryEffect effect(item);
effect.cooldown = (int)(rng.Next() % JACOBS_CURSE_STEPS) * JACOBS_CURSE_STEP_FRAMES + JACOBS_CURSE_MIN_FRAMES;
temporaryEffects.AddEffect(effect, true, 1);
}
// 007a4ba0 Readies the player for a new floor: places it at the start (unless forced), and once its run has started,
// spills blood at low health, ends the floor's effects, restores what the floor gives back and evaluates its stats.
void Entity_Player::level_start(bool isForced)
{
delayedSfxId = 0;
delayedSfxDelay = 0;
moveToTarget = {};
if (variant == PLAYER_VARIANT_PLAYER && !isForced) start_position_set();
if (!isPostLevelInitFinished) return;
spawn_low_health_blood_splat();
ventricleRazorPortal = 0;
if (variant == PLAYER_VARIANT_COOP_BABY)
{
if (isGlitchBaby) reconstruction_missing("Entity_Player::level_start 007a4ba0 (the glitched co-op baby)");
if (parent) pos = parent->pos;
}
isLevelStartPending = false;
level_items_apply(isForced);
}
// Places a character at the floor's start: the greed mode spot, the first floor's spot below the middle, or where the
// player manager puts the players, lower in Backasswards' Blue Womb. The Ascent starts at a door.
void Entity_Player::start_position_set()
{
Game& game = *g_game;
float startY = START_SPOT_Y;
if (game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER) startY = GREED_START_SPOT_Y;
else
{
if (game.stage_depth_get() != 1 || game.IsAscent())
{
pos = PlayerManager::get_player_start_position(this, {});
if (game.challenge == CHALLENGE_BACKASSWARDS && game.stage == STAGE_DARK_ROOM)
pos.y += BACKASSWARDS_START_OFFSET_Y;
uint32_t curses =
(Seeds::GetForcedCurses() | game.debugCurses | game.curses) & ~Seeds::GetPreventedCurses();
int stage = (int)game.stage + (curses & CURSE_OF_LABYRINTH ? 1 : 0);
if (game.IsAscent() && !(stage == ASCENT_HOME_STAGE && game.IsAltPath())) ascent_start_set();
return;
}
}
pos = PlayerManager::get_player_start_position(this, vector_make(START_SPOT_X, startY));
}
// The Ascent starts the player a cell inside a door: the room's first, or from a random slot the next one its shape
// allows. A trapdoor reachable from there takes the start instead.
void Entity_Player::ascent_start_set()
{
Room& room = *g_game->room;
auto door = std::ranges::find_if(room.doors, [](GridEntity_Door* slot) { return slot != nullptr; });
int slot = (int)(door - room.doors.begin());
if (door == room.doors.end())
{
slot = (int)(Random() & (DOOR_SLOT_COUNT - 1));
uint32_t allowed = room.descriptor->data->doors;
for (int tries = 0; tries < DOOR_SLOT_COUNT && !(allowed & (1u << slot)); tries++)
slot = (slot + 1) % DOOR_SLOT_COUNT;
}
Vector start = room.GetGridPosition(room.doorGridPositions[slot]);
start = vector_make(start.x + ASCENT_DOOR_STEPS[slot % 4][0], start.y + ASCENT_DOOR_STEPS[slot % 4][1]);
pos = start;
for (int cell = 0; cell < room.gridHeight * room.gridWidth && cell < ROOM_GRID_CELLS; cell++)
{
GridEntity* grid = room.gridEntities[cell];
if (!grid || grid->type != GRID_TRAPDOOR) continue;
Vector trapdoor = room.GetGridPosition(grid->gridIndex);
if (!pathfinder_can_reach_pos(&trapdoor, &start, &room)) continue;
pos = trapdoor;
return;
}
}
// Ends the floor-long effects and restores what each floor gives back: Holy Mantle from Wooden Cross, the floor's
// health, map and compass effects, items that recharge, pickups some trinkets spawn, the Backasswards penalty and the
// per-floor generators, then evaluates. A forced start also restarts the player's familiars.
void Entity_Player::level_items_apply(bool isForced)
{
Game& game = *g_game;
ItemConfig& items = g_manager->itemConfig;
wooden_cross_mantles_add();
temporaryEffects.RemoveNullEffect(NULLITEM_REVERSE_SUN, -1);
temporaryEffects.RemoveNullEffect(NULLITEM_LUNA, -1);
if (ItemConfig_Item* salvation = items.GetCollectible(COLLECTIBLE_SALVATION))
temporaryEffects.RemoveEffect(salvation, -1);
if (ItemConfig_Item* foundSoul = items.GetTrinket(TRINKET_FOUND_SOUL)) temporaryEffects.RemoveEffect(foundSoul, -1);
temporaryEffects.RemoveNullEffect(NULLITEM_JACOBS_CURSE, -1);
for (Entity* entity : std::vector<Entity*>(game.room->entityList.mainEL))
if (entity->type == ENTITY_DARK_ESAU && entity->target.get() == this) entity->Remove();
temporaryEffects.RemoveNullEffect(NULLITEM_JUDAS_BIRTHRIGHT_STAGE, 1);
if (playerType == PLAYER_JACOB2_B) ChangePlayerType(PLAYER_JACOB_B, false);
else if (playerType == PLAYER_LAZARUS2) ChangePlayerType(PLAYER_LAZARUS, false);
if (playerType == PLAYER_JACOB_B && game.challenge != CHALLENGE_RED_REDEMPTION) jacobs_curse_add();
if (HasCollectible(COLLECTIBLE_EMPTY_HEART))
for (Entity_Player* player : {this, subPlayer})
if (player && player->GetHealthType() == HEALTH_DEFAULT &&
player->GetHeartLimit(false) > player->maxHearts && player->redHearts < EMPTY_HEART_RED_HEARTS)
{
player->AddMaxHearts(2, false);
game.itemOverlay.Show(GIANTBOOK_EMPTY_HEART, 0, nullptr);
}
if (TemporaryEffect* redemption = temporaryEffects.GetCollectibleEffect(COLLECTIBLE_REDEMPTION);
redemption && redemption->count > 0)
{
if (Entity* light = redemptionEffect; light && light->type == ENTITY_EFFECT && redemption->count == 1)
static_cast<Entity_Effect*>(light)->state = REDEMPTION_LIGHT_FADE;
if (ItemConfig_Item* item = items.GetCollectible(COLLECTIBLE_REDEMPTION))
temporaryEffects.RemoveEffect(item, -1);
}
forgottenBodyRoomIdx = FORGOTTEN_BODY_ROOM_NONE;
for (int i = HasTrinket(TRINKET_LUCKY_SACK) ? GetTrinketMultiplier(TRINKET_LUCKY_SACK) : 0; i > 0; i--)
{
uint32_t seed = GetTrinketRNG(TRINKET_LUCKY_SACK).Next();
Vector spot = room_free_pickup_position_find({pos, PICKUP_SPAWN_RADIUS});
game.Spawn(
{.position = spot, .spawner = this, .type = ENTITY_PICKUP, .variant = PICKUP_GRAB_BAG, .seed = seed});
}
if (!isForced && backupPlayer) backupPlayer->isLevelStartPending = true;
for (Entity_Player* player : {this, subPlayer})
if (player && player->eternalHearts > 0)
{
player->eternalHearts = 0;
player->eternal_heart_overlay_show();
player->AddMaxHearts(2, false);
player->AddHearts(2, false, false);
}
if (!isCoopGhost)
for (Entity* entity : game.room->entityList.mainEL)
if (Entity_Familiar* familiar = dynamic_cast<Entity_Familiar*>(entity);
familiar && familiar->IsType(ENTITY_FAMILIAR, Entity_Familiar::LIL_PORTAL, 1) && familiar->player == this)
familiar->subtype = 0;
floor_maps_apply();
floor_items_recharge();
if (HasTrinket(TRINKET_HOLLOW_HEART)) AddBoneHearts(GetTrinketMultiplier(TRINKET_HOLLOW_HEART));
if (HasCollectible(COLLECTIBLE_MISSING_NO)) missing_no_reroll();
if (HasCollectible(COLLECTIBLE_ZODIAC))
{
if (!HasCollectible(COLLECTIBLE_TAURUS) && !temporaryEffects.HasCollectibleEffect(COLLECTIBLE_TAURUS))
RemoveCostume(items.GetCollectible(COLLECTIBLE_TAURUS));
cacheFlags |= CACHE_ALL;
}
if (HasTrinket(TRINKET_STEM_CELL)) stem_cell_heal();
if (game.challenge == CHALLENGE_BACKASSWARDS) backasswards_penalty();
floor_rngs_reseed();
if (!isForced)
{
hasGoldenKey = false;
hasGoldenBomb = false;
}
levelEffectItems.clear();
bloodLustCounter = 0;
for (int id : {COLLECTIBLE_BLOODY_LUST, COLLECTIBLE_BLOODY_GUST})
cacheFlags |= items.GetCollectible(id) ? items.GetCollectible(id)->cacheFlags : 0;
EvaluateItems();
if (!isForced) return;
for (Entity* entity : std::vector<Entity*>(game.room->entityList.mainEL))
if (Entity_Familiar* familiar = dynamic_cast<Entity_Familiar*>(entity); familiar && familiar->player == this)
familiar->level_start();
}
// Applies the floor's map, Blue Map and compass items, Cain's Eye's chance at a compass, Maggy's Faith's eternal
// hearts, Sol's boss room icon, Luna's secret room and Missing Poster's chance at the super secret room, and Dream
// Catcher's soul heart.
void Entity_Player::floor_maps_apply()
{
Game& game = *g_game;
bool isMind = HasCollectible(COLLECTIBLE_MIND);
if (HasCollectible(COLLECTIBLE_TREASURE_MAP) || isMind) game.ApplyMapEffect();
if (HasCollectible(COLLECTIBLE_BLUE_MAP) || isMind) game.ApplyBlueMapEffect();
bool isCainsEye = HasTrinket(TRINKET_CAINS_EYE) &&
Random() % 100 < (uint32_t)(GetTrinketMultiplier(TRINKET_CAINS_EYE) * CAINS_EYE_CHANCE);
if (HasCollectible(COLLECTIBLE_COMPASS) || isMind || isCainsEye) game.ApplyCompassEffect(true);
if (HasTrinket(TRINKET_MAGGYS_FAITH)) AddEternalHearts(GetTrinketMultiplier(TRINKET_MAGGYS_FAITH));
if (HasCollectible(COLLECTIBLE_SOL))
{
if (game.lastBossRoomListIdx >= 0) game.roomList[game.lastBossRoomListIdx].displayFlags |= ROOM_DISPLAY_ICON;
game.minimap.Refresh();
game.levelStateFlags |= 1u << LEVEL_STATE_SOL;
}
if (HasCollectible(COLLECTIBLE_LUNA)) game.reveal_secret_room();
if (HasTrinket(TRINKET_MISSING_POSTER))
{
int multiplier = GetTrinketMultiplier(TRINKET_MISSING_POSTER);
uint32_t chance = multiplier == 2 ? 66 : multiplier > 2 ? 100 : 33;
if (GetTrinketRNG(TRINKET_MISSING_POSTER).Next() % 100 < chance)
{
for (int i = 0; i < game.nbRooms; i++)
{
if (!game.roomList[i].data) log_printf(LOG_ASSERT, "[error] Room %d is not initialized\n", i);
if (game.roomList[i].data->type != ROOM_SUPERSECRET) continue;
game.roomList[i].displayFlags |= ROOM_DISPLAY_ICON;
break;
}
game.minimap.Refresh();
}
}
if (HasCollectible(COLLECTIBLE_DREAM_CATCHER)) AddSoulHearts(1, false);
}
// Recharges Notched Axe and Eraser and empties the Glowing Hour Glass for the new floor, then lets the Necronomicon
// transformation recharge its book. Beth's Faith gives wisps.
void Entity_Player::floor_items_recharge()
{
Game& game = *g_game;
for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++)
{
ActiveItemDesc& active = activeItems[slot];
if (active.item == COLLECTIBLE_NOTCHED_AXE)
{
bool isEmpty = slot == POCKET_ACTIVE_SLOT + 1 ||
(slot == POCKET_ACTIVE_SLOT && activeItems[POCKET_ACTIVE_SLOT].item == COLLECTIBLE_RED_KEY &&
game.challenge == CHALLENGE_RED_REDEMPTION);
AddActiveCharge(isEmpty ? 0 : GetCollectibleMaxCharge(COLLECTIBLE_NOTCHED_AXE, active.varData), slot, false,
false, true);
}
else if (active.item == COLLECTIBLE_GLOWING_HOUR_GLASS)
{
active.varData = 0;
SetActiveCharge(0, slot);
}
else if (active.item == COLLECTIBLE_ERASER) AddActiveCharge(1, slot, false, false, true);
}
if (!hasCurseMistEffect && !isCoopGhost && playerForms[PLAYER_FORM_NECROMANCER] > 2) necromancer_recharge();
for (int i = HasTrinket(TRINKET_BETHS_FAITH) ? GetTrinketMultiplier(TRINKET_BETHS_FAITH) * 4 : 0; i > 0; i--)
AddWisp(COLLECTIBLE_BOOK_OF_VIRTUES, pos, false, false);
}
// Missing No. rerolls the player's items for the new floor with the D4 (no animation, from no slot), and the player
// glitches into it.
void Entity_Player::missing_no_reroll()
{
UseActiveItem({.item = COLLECTIBLE_D4, .flags = USE_NOANIM, .slot = ACTIVE_SLOT_NONE});
isPlayingItemAnimation = false;
bodySprite.Reset();
sprite.playbackSpeed = 1;
sprite.overlayAnimState.SetAnimationData(nullptr);
if (sprite.SetAnimation("Glitch", SWITCH_KEEP_FRAME))
{
sprite.animState.Rewind();
sprite.animState.isPlaying = true;
}
isPlayingExtraAnimation = true;
isPlayingItemAnimation = false;
}
// The Necromancer transformation recharges the first Necronomicon a slot holds with its form's charge (none in the
// pocket's book slot), the others losing theirs, with the giant book and its sound. Without one marked the main active
// becomes the transformation's book, fully charged.
void Entity_Player::necromancer_recharge()
{
Game& game = *g_game;
bool isRecharged = false;
for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++)
{
ActiveItemDesc& active = activeItems[slot];
if (active.item != COLLECTIBLE_NECRONOMICON) continue;
if (isRecharged) active.varData = 0;
else if (active.varData == 1)
{
int charge = slot == POCKET_ACTIVE_SLOT + 1 ? 0 : GetCollectibleMaxCharge(COLLECTIBLE_NECRONOMICON, 1);
AddActiveCharge(charge, slot, false, false, true);
game.itemOverlay.Show(GIANTBOOK_NECROMANCER, NECROMANCER_OVERLAY_DELAY, nullptr);
sound_fart_play(SOUND_NECROMANCER);
isRecharged = true;
}
game.hud.InvalidateActiveItem(this, slot);
}
if (isRecharged) return;
activeItems[ACTIVE_SLOT_PRIMARY].varData = 1;
AddActiveCharge(GetCollectibleMaxCharge(activeItems[ACTIVE_SLOT_PRIMARY].item, 1), ACTIVE_SLOT_PRIMARY, false,
false, true);
game.itemOverlay.Show(GIANTBOOK_NECROMANCER, NECROMANCER_OVERLAY_DELAY, nullptr);
}
// Stem Cell heals half the missing red hearts, all of them at two, and all of them with two heart drops at three.
void Entity_Player::stem_cell_heal()
{
int multiplier = GetTrinketMultiplier(TRINKET_STEM_CELL);
HealthType health = GetHealthType();
int containers = health == HEALTH_SOUL || health == HEALTH_NO_HEALTH ? maxHearts : maxHearts + boneHearts * 2;
int missing = containers - redHearts;
if (multiplier == 1) AddHearts(std::max(1, missing / 2), false, false);
else if (multiplier == 2) AddHearts(std::max(1, missing), false, false);
else if (multiplier == 3)
{
AddHearts(std::max(1, missing), false, false);
for (int i = 0; i < 2; i++)
{
uint32_t seed = Random();
g_game->Spawn({.position = room_pickup_position_random(false, false),
.type = ENTITY_PICKUP,
.variant = PICKUP_HEART,
.seed = seed});
}
}
}
// Backasswards takes the first collectible picked up and a heart container each floor, leaving a soul heart if nothing
// else is left.
void Entity_Player::backasswards_penalty()
{
for (HistoryItem& item : history.historyItems)
if (!item.isTrinket && HasCollectible(item.id))
{
RemoveCollectible(item.id, false, 0, true);
break;
}
AddMaxHearts(-2, false);
if (redHearts < 1 && soulHearts < 1 && boneHearts < 1) AddSoulHearts(1, false);
}
// Reseeds the generators of the items that pick a room for the floor (Teleport!, Undefined, Cursed Eye, Cursed Skull,
// Telepills) from the floor's dungeon placement seed, so every player draws the same rooms.
void Entity_Player::floor_rngs_reseed()
{
RNG stepper = rng_make(g_game->dungeonPlacementSeed, PRE_LEVEL_RNG_SHIFT);
collectibleRNGs[COLLECTIBLE_TELEPORT] = rng_make(stepper.Next(), FLOOR_RNG_SHIFT);
collectibleRNGs[COLLECTIBLE_UNDEFINED] = rng_make(stepper.Next(), FLOOR_RNG_SHIFT);
collectibleRNGs[COLLECTIBLE_CURSED_EYE] = rng_make(stepper.Next(), FLOOR_RNG_SHIFT);
trinketRNGs[TRINKET_CURSED_SKULL] = rng_make(stepper.Next(), FLOOR_RNG_SHIFT);
pillRNGs[PILLEFFECT_TELEPILLS] = rng_make(stepper.Next(), FLOOR_RNG_SHIFT);
}
// 007daff0 Wooden Cross shields the player with Holy Mantle once per floor, twice when golden or doubled.
void Entity_Player::wooden_cross_mantles_add()
{
int multiplier = GetTrinketMultiplier(TRINKET_WOODEN_CROSS);
if (multiplier == 0)
{
holyMantleStacks = 0;
return;
}
int count = multiplier == 1 ? 1 : 2;
holyMantleStacks = multiplier == 1 ? WOODEN_CROSS_STACK : WOODEN_CROSS_STACK * 2;
for (int i = 0; i < count; i++) temporaryEffects.AddCollectibleEffect(COLLECTIBLE_HOLY_MANTLE, true, 1);
}
// 007a49e0 Leaves a blood splat where a player with health is down to its last heart, red unless its blood is
// white (Kidney Stone, Eve and Tainted Eve keep the effect's own color).
void Entity_Player::spawn_low_health_blood_splat()
{
if (variant != PLAYER_VARIANT_PLAYER || boneHearts + soulHearts + redHearts >= 2 || isCoopGhost) return;
for (int type : {PLAYER_THELOST, PLAYER_THEFORGOTTEN, PLAYER_THESOUL, PLAYER_THELOST_B, PLAYER_THEFORGOTTEN_B,
PLAYER_THESOUL_B, PLAYER_JACOB2_B})
if (playerType == type) return;
Entity* splat =
g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()});
float scale = random_unit() * 0.5f + 0.3f;
splat->sprite.scale = vector_make(scale, scale);
splat->sprite.rotation = (float)(Random() & 3) * 90;
splat->sprite.isFlipX = !(Random() & 1);
if (!HasCollectible(COLLECTIBLE_KIDNEY_STONE) && playerType != PLAYER_EVE && playerType != PLAYER_EVE_B)
splat->SetColor(color_from_bytes(0, 0, 0, PEE_ALPHA, PEE_OFFSET, PEE_OFFSET, 0), -1, COLOR_PRIORITY_TOP, false,
true);
splat->Update();
}
// 007a6450 Gives the player a controller, moving its player color over, and the NPCs it controls with it. With
// isIncludePlayerOwned its sub player, Lazarus twin, twin and the players it owns follow.
void Entity_Player::SetControllerIndex(int index, bool isIncludePlayerOwned)
{
PlayerManager& players = g_game->playerManager;
log_printf(LOG_INFO, "Entity_Player::SetControllerId() Setting controller ID to %d, (Prev: %d) \n", index,
controllerIndex);
if (index != -1 && controllerIndex != index)
{
if (controllerIndex == -1) players.AssignPlayerColor(index);
else if (players.isColorAssignEnabled) player_color_reassign(index);
}
if (controllerIndex != -1)
for (Entity* entity : g_game->room->entityList.mainEL)
if (Entity_NPC* npc = dynamic_cast<Entity_NPC*>(entity); npc && npc->controllerID == controllerIndex)
npc->controllerID = index;
controllerIndex = index;
if (!isIncludePlayerOwned) return;
for (Entity_Player* owned : {subPlayer, backupPlayer, twin_get()})
if (owned) owned->SetControllerIndex(controllerIndex, false);
if (parent) return;
for (size_t i = 0; i < players.playerList.size(); i++)
{
Entity_Player* player = players.GetPlayer((int)i);
if (player->parent.get() == this) player->SetControllerIndex(controllerIndex, true);
}
}
// Moves the player color of the current controller to a new one.
void Entity_Player::player_color_reassign(int index)
{
std::array<int, COOP_SLOT_COUNT>& colors = g_game->playerManager.colorControllers;
for (size_t i = 0; i < colors.size(); i++)
if (colors[i] == controllerIndex)
{
log_printf(LOG_INFO, "Reassigning Player Color (%d) Prev(%d) New(%d) \n", (int)i, controllerIndex, index);
colors[i] = index;
return;
}
log_printf(
LOG_ERROR,
"PlayerManager::ReassignPlayerColor(%d, %d) cannot reassign the color, because there is no color assigned "
"to the original controller ID \n",
controllerIndex, index);
}
// 007cba30 Whether the player can shoot: a character as its config and the challenge allow, a co-op baby unless it is
// the magnet baby, and in the deathmatch as its rules allow.
void Entity_Player::UpdateCanShoot()
{
Game& game = *g_game;
canShoot = true;
if (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_MAGNET) canShoot = false;
else if (variant == PLAYER_VARIANT_PLAYER)
{
bool isChallengeShooting = game.GetChallengeParams().isCanShoot;
EntityConfig_Player* playerConfig = g_manager->entityConfig.GetPlayer(playerType);
if (!playerConfig) log_printf(LOG_ASSERT, "Could not load config for player type %d\n", playerType);
canShoot = isChallengeShooting && playerConfig && playerConfig->isCanShoot;
}
if (game.deathmatchManager.is_active())
reconstruction_missing("Entity_Player::UpdateCanShoot 007cba30 (deathmatch rules)");
}
// 0075dfe0 Takes off every costume, leaving each layer to the player's own sprite.
void Entity_Player::ClearCostumes()
{
costumeSpriteDescs.clear();
costume_map_reset(0);
}
// Gives every layer back to the player's own sprite, the body layers marked as such.
void Entity_Player::costume_map_reset(int priority)
{
for (int layer = 0; layer < COSTUME_LAYER_COUNT; layer++)
playerCostumeMap[layer] = {-1, -1, priority, is_body_layer(layer)};
}
// Whether a layer of the player's sprite is part of the body rather than the head.
bool Entity_Player::is_body_layer(int layer)
{
return (layer >= PLAYER_LAYER_BODY && layer <= PLAYER_LAYER_BODY1) || layer == PLAYER_LAYER_TOP0;
}
// 0075d850 Takes off an item's costume, from its Lazarus twin too when the item is shared, and redoes the costumes.
// Co-op babies wear none.
void Entity_Player::RemoveCostume(ItemConfig_Item* item)
{
if (!item || variant == PLAYER_VARIANT_COOP_BABY || item->costume.anm2Path.empty()) return;
if (isValid && item->HasTags(TAG_LAZ_SHARED) && backupPlayer) backupPlayer->RemoveCostume(item);
if (std::erase_if(costumeSpriteDescs, [item](CostumeSpriteDesc& costume) { return costume.item == item; }) > 0)
UpdateCostumes();
}
// 007bebb0 Dresses the player in its character's skin: the challenge's or the config's spritesheet on every layer and
// the matching ghost layer, then the character's costume, the blindfold of characters that cannot shoot, the seeds'
// and dailies' costumes and the Hot Potato bomb. Co-op ghosts only get the ghost body. The name follows the character.
void Entity_Player::update_player_skin()
{
Game& game = *g_game;
ItemConfig& items = g_manager->itemConfig;
if (isCoopGhost)
{
reset_body_sprite();
return;
}
EntityConfig_Player* playerConfig = g_manager->entityConfig.GetPlayer(playerType);
bodyColor = -1;
headColor = -1;
if (game.challenge == CHALLENGE_GUARDIAN)
{
for (int layer = 0; layer < COSTUME_LAYER_COUNT; layer++)
sprite.ReplaceSpritesheet(layer, "gfx/characters/costumes/NiceLilith.png");
sprite.LoadGraphics();
}
else if (!playerConfig->skinPath.empty())
{
for (int layer = 0; layer < COSTUME_LAYER_COUNT; layer++)
sprite.ReplaceSpritesheet(layer, playerConfig->skinPath);
if (LayerState* ghost = sprite.GetLayer("ghost"))
sprite.ReplaceSpritesheet(
ghost->layerData ? ghost->layerData->id : -1,
costume_path_apply_skin_color(ghost->layerData ? ghost->layerData->spriteSheetPath : "", -1, playerType,
nullptr, nullptr));
sprite.LoadGraphics();
}
if (playerConfig->costumeID == -1) UpdateCostumes();
else AddCostume(items.GetNullItem(playerConfig->costumeID), false);
bool isBombForm = playerType == PLAYER_THEFORGOTTEN_B || playerType == PLAYER_THESOUL_B;
if (variant == PLAYER_VARIANT_PLAYER && !game.GetChallengeParams().isCanShoot && !isBombForm)
AddCostume(items.GetNullItem(NULLITEM_BLINDFOLD), false);
if (game.seedEffects.HasSeedEffect(SEED_CHRISTMAS) || game.dailyChallenge._specialDailyId == DAILY_CHRISTMAS)
AddCostume(items.GetNullItem(NULLITEM_CHRISTMAS), false);
if (game.challenge == CHALLENGE_HOT_POTATO && playerType == PLAYER_THEFORGOTTEN_B)
AddCostume(items.GetNullItem(NULLITEM_FORGOTTEN_BOMB), false);
name = playerConfig->GetDisplayName();
}
// 0075b540 A costume spritesheet's path for a character and skin color: the character's own costume folder
// (costumes_<suffix>) when the file is there, then the skin color's _black, _blue, _red, _green, _grey or _white file
// when there. isSkinColorFound and isCharacterFound tell which were used.
std::string costume_path_apply_skin_color(const std::string& path, int skinColor, int playerType,
bool* isSkinColorFound, bool* isCharacterFound)
{
std::string result = path;
bool isPlayerFound = false;
bool isSkinFound = false;
EntityConfig_Player* playerConfig = playerType == -1 ? nullptr : g_manager->entityConfig.GetPlayer(playerType);
if (playerConfig && !playerConfig->costumeSuffixName.empty())
{
size_t slash = path.find_last_of("/\\");
while (slash != std::string::npos && slash >= COSTUMES_DIR.size() &&
path.compare(slash - COSTUMES_DIR.size(), COSTUMES_DIR.size(), COSTUMES_DIR) != 0)
slash = slash == 0 ? std::string::npos : path.find_last_of("/\\", slash - 1);
if (slash != std::string::npos && slash >= COSTUMES_DIR.size())
{
std::string candidate = path.substr(0, slash) + "_" + playerConfig->costumeSuffixName + path.substr(slash);
std::string redirected = g_manager->modManager.TryRedirectPath(candidate);
if (is_file_found(redirected))
{
result = redirected;
isPlayerFound = true;
}
}
}
if (skinColor >= 0)
{
size_t dot = result.find_last_of('.');
if (dot != std::string::npos)
{
std::string_view suffix = SKIN_COLOR_SUFFIXES[skinColor < (int)SKIN_COLOR_SUFFIXES.size() ? skinColor : 0];
std::string candidate = result.substr(0, dot) + std::string(suffix) + result.substr(dot);
std::string redirected = g_manager->modManager.TryRedirectPath(candidate);
if (is_file_found(redirected))
{
result = redirected;
isSkinFound = true;
}
}
}
if (isSkinColorFound) *isSkinColorFound = isSkinFound;
if (isCharacterFound) *isCharacterFound = isPlayerFound;
return result;
}
// Plays a sound effect at full volume, unless the seeds swap it for a fart.
void sound_play(int sound)
{
int id = sound;
seed_fart_sound_override(&id);
g_manager->sfxManager.Play(id);
}
// 00417800 The twin that leads the pair (Jacob over Esau), or the player itself.
Entity_Player* Entity_Player::GetMainTwin()
{
Entity_Player* twin = twin_get();
return !twin || twin->playerIndex == -1 || playerIndex <= twin->playerIndex ? this : twin;
}
// Whether Dead Bird's effect stays when the effects are cleared: while the player is down to its last heart, or two for
// Eve.
bool Entity_Player::is_dead_bird_kept()
{
if (isCoopGhost) return false;
int red = maxHearts > 0 ? redHearts : 0;
return boneHearts + soulHearts + red <= (playerType == PLAYER_EVE ? 2 : 1);
}
// 00757a40 Drops the entity links, then lets go of the weapons and the effects the player spawned.
void Entity_Player::ClearReferences()
{
Entity::ClearReferences();
release_weapons_and_effects(false);
}
// Forgets an entity the player spawned, removing it first when asked.
template <typename Link> static void link_release(Link& link, bool isRemoveEntities)
{
if (isRemoveEntities && link) static_cast<Entity*>(link)->Remove();
link = nullptr;
}
// 00757ac0 Lets go of the weapons, then of the effects the player spawned (removed when asked), the held entity (thrown
// on removal) and, unless it is being replaced, its stored helper players and its twin, removing its co-op players.
void Entity_Player::release_weapons_and_effects(bool isRemoveEntities)
{
for (size_t slot = 1; slot <= weapons.size(); slot++)
{
WeaponPtr& weapon = weapons[slot % weapons.size()];
if (weapon) weapon->ClearReferences();
weapon.reset();
}
link_release(azazelsRageLaser, isRemoveEntities);
link_release(dadsRingAura, isRemoveEntities);
link_release(breathOfLifeEffect, isRemoveEntities);
link_release(isaacsHeart, isRemoveEntities);
link_release(trinityShield, isRemoveEntities);
link_release(deadToothRing, isRemoveEntities);
link_release(redemptionEffect, isRemoveEntities);
link_release(bestFriend, isRemoveEntities);
link_release(megaBlastLaser, isRemoveEntities);
link_release(markedTarget, isRemoveEntities);
link_release(forgottenBody, isRemoveEntities);
link_release(monstranceAura, isRemoveEntities);
link_release(babyFamiliar, isRemoveEntities);
link_release(salvationEffect, isRemoveEntities);
link_release(tetheredEffect, isRemoveEntities);
link_release(astralProjectionBody, isRemoveEntities);
link_release(montezumaLaser, isRemoveEntities);
link_release(divineShield, isRemoveEntities);
link_release(darkArtsLastSnare, isRemoveEntities);
link_release(darkEsau, isRemoveEntities);
moveToTarget = {};
if (isRemoveEntities) ThrowHeldEntity(vector_make(velocity.x * HELD_RELEASE_SPEED, velocity.y * HELD_RELEASE_SPEED));
heldEntity = nullptr;
if (replacedPlayer) return;
for (Entity_Player** helper : {&subPlayer, &backupPlayer})
{
if (!*helper || (*helper)->isValid || (helper == &subPlayer && !isValid)) continue;
(*helper)->ClearReferences();
delete std::exchange(*helper, nullptr);
}
PlayerManager& players = g_game->playerManager;
Entity_Player* twin = twin_get();
if (isRemoveEntities && twin && (twin->playerIndex == -1 || playerIndex <= twin->playerIndex || twin == this))
players.RemoveCoPlayer(twin);
twinPlayer = nullptr;
if (!isRemoveEntities) return;
for (size_t i = 0; i < players.playerList.size(); i++)
{
Entity_Player* each = players.playerList[i];
Entity* owner = each->parent && each->parent->type == ENTITY_PLAYER ? (Entity*)each->parent
: each->variant == PLAYER_VARIANT_COOP_BABY ? players.playerList[0]
: nullptr;
if (owner == this && each->parent) players.RemoveCoPlayer(each);
}
}
// 0065cf60 Whether the player is a co-op baby still blinking in after joining.
bool Entity_Player::IsP2Appearing()
{
return variant == PLAYER_VARIANT_COOP_BABY && damageCooldown > 0;
}
// 00782a60 Whether the head is free to turn, its last turn having run out.
uint32_t Entity_Player::CanTurnHead()
{
return headDirectionTime < 0;
}
// 00757ab0 Whether the player shuts the room's doors, as players do only in the deathmatch.
bool Entity_Player::CanShutDoors()
{
return g_game->deathmatchManager.is_active();
}
// 00757a60 Whether the player may target an entity: not itself, its own segments, a Ring of Flies' other flies, Dark
// Esau or a Blood Puppy.
bool Entity_Player::IsValidTarget(Entity* other)
{
if (other == this || is_same_segmented_body(other)) return false;
if (type == ENTITY_RING_OF_FLIES && other->type == ENTITY_RING_OF_FLIES) return false;
return other->type != ENTITY_DARK_ESAU && other->type != ENTITY_BLOOD_PUPPY;
}
// 007579c0 Gives the sprite back the entity's own color.
void Entity_Player::ResetColor()
{
sprite.color = color;
}