3688 lines
160 KiB
C++
3688 lines
160 KiB
C++
#include "entity_npc.h"
|
|
#include "boss_repentance.h"
|
|
#include "active_items.h"
|
|
#include "boss_ai.h"
|
|
#include "boss_death.h"
|
|
#include "boss_final.h"
|
|
#include "entity_bomb.h"
|
|
#include "entity_config.h"
|
|
#include "entity_effect.h"
|
|
#include "entity_factory.h"
|
|
#include "entity_familiar.h"
|
|
#include "entity_laser.h"
|
|
#include "entity_pickup.h"
|
|
#include "entity_player.h"
|
|
#include "entity_projectile.h"
|
|
#include "entity_text.h"
|
|
#include "data.h"
|
|
#include "game.h"
|
|
#include "grid_entity.h"
|
|
#include "log.h"
|
|
#include "lua_engine.h"
|
|
#include "manager.h"
|
|
#include "npc_ai.h"
|
|
#include "npc_basement.h"
|
|
#include "persistent_game_data.h"
|
|
#include "platform.h"
|
|
#include "room.h"
|
|
#include "room_config.h"
|
|
#include "room_descriptor.h"
|
|
#include "room_grid.h"
|
|
#include "room_render.h"
|
|
#include "sfx_manager.h"
|
|
#include "menu_manager.h"
|
|
#include "mines.h"
|
|
#include "npc_alt.h"
|
|
#include <algorithm>
|
|
#include <cmath>
|
|
#include <filesystem>
|
|
|
|
// The frames of a controlled NPC's charge bar, empty to full.
|
|
constexpr int CHARGE_BAR_FRAMES = 100;
|
|
constexpr float POOP_THROW_HEIGHT = -20;
|
|
constexpr float POOP_THROW_LOUD_SPEED = 5;
|
|
|
|
constexpr int ENTITY_FEAR_IMMUNE = 205;
|
|
constexpr int ENTITY_NO_DECOY_TYPE = 213;
|
|
constexpr uint32_t DOPLE_PICK_SHIFT = 11;
|
|
constexpr int ENTITY_UNREACHABLE_EXEMPT = 886;
|
|
constexpr int ENTITY_DAMAGE_NUMBERS_TYPE = 964;
|
|
constexpr float DAMAGE_NUMBER_MAX = 9999;
|
|
constexpr float DAMAGE_NUMBER_MIN = 0.1f;
|
|
constexpr float DAMAGE_NUMBER_PRECISION = 10;
|
|
constexpr float DAMAGE_NUMBER_RISE = 20;
|
|
constexpr float DAMAGE_NUMBER_SPEED = -3;
|
|
|
|
// G-Fuel's explosions: past 1.5 the big one, which shakes the screen for 40 frames, else one of two small ones for
|
|
// 20, their sound pitched 0.9 to 1.1.
|
|
constexpr float GFUEL_BIG_SCALE = 1.5f;
|
|
constexpr std::string_view GFUEL_BIG_EXPLOSION_ANM2 = "gfx/promo/gfuel/effects/explosion_big.anm2";
|
|
constexpr std::array<std::string_view, 2> GFUEL_EXPLOSION_ANM2S = {"gfx/promo/gfuel/effects/explosion.anm2",
|
|
"gfx/promo/gfuel/effects/explosion2.anm2"};
|
|
constexpr int GFUEL_BIG_BLAST_SHAKE = 40;
|
|
constexpr int GFUEL_BLAST_SHAKE = 20;
|
|
|
|
// The Dust's death flash, colored bright, and its puff, small and dark.
|
|
constexpr float DUST_FLASH_COLORIZE = 5;
|
|
constexpr int DUST_PUFF_SUBTYPE = 1;
|
|
constexpr float DUST_PUFF_SCALE = 0.6f;
|
|
constexpr float DUST_DEATH_VOLUME = 0.8f;
|
|
constexpr int APPEAR_OVERLAY_KEPT_TYPE = 266;
|
|
constexpr float BIG_HORN_APPEAR_VOLUME = 2;
|
|
constexpr std::array<int, 4> APPEAR_EVENT_TYPES = {404, 912, 913, 917};
|
|
constexpr std::array<int, 9> FLUSH_TYPES = {217, 220, 223, 261, 402, 870, 871, 872, 914};
|
|
constexpr int FLUSH_PROP_TYPE = 237;
|
|
constexpr int FLUSH_PROP_VARIANT = 2;
|
|
constexpr int FLUSH_RENDER_Z = 5000;
|
|
constexpr int HUSH_ASH_SHAKE = 30;
|
|
|
|
// The bosses' death events: Isaac's cry, Baby Plum's last ring, Singe's blast, Mother's slam and Clutch's explosions.
|
|
constexpr int ISAAC_DEATH_CRY_FRAME = 17;
|
|
constexpr float ISAAC_DEATH_CRY_VOLUME = 2;
|
|
constexpr float PLUM_RING_FALL = 0.099f;
|
|
constexpr float PLUM_RING_SPEED = 6;
|
|
constexpr float PLUM_RING_SHOTS = 10;
|
|
constexpr float SINGE_BLAST_DAMAGE = 80;
|
|
constexpr float SINGE_BLAST_REACH = 1.5f;
|
|
constexpr int MOTHER_SLAM_VARIANT = 10;
|
|
constexpr int MOTHER_SLAM_SHAKE = 20;
|
|
constexpr float MOTHER_SLAM_PITCH = 0.5f;
|
|
constexpr int CLUTCH_BLAST_SUBTYPE = 3;
|
|
constexpr float CLUTCH_BLAST_RAISE = -20;
|
|
constexpr float CLUTCH_BLAST_SCALE = 1.5f;
|
|
constexpr float CLUTCH_BLAST_DAMAGE = 80;
|
|
constexpr float CLUTCH_BLAST_VOLUME = 1.25f;
|
|
constexpr float CLUTCH_PITCH = 0.9f;
|
|
constexpr float CLUTCH_PITCH_SPREAD = 0.2f;
|
|
constexpr int CLUTCH_BLAST_SHAKE = 14;
|
|
constexpr float CLUTCH_BLAST_SPIN = 360;
|
|
constexpr int ENTITY_FORWARD_NONE = 45;
|
|
constexpr int ENTITY_FORWARD_DOWN_A = 262;
|
|
constexpr int ENTITY_FORWARD_DOWN_B = 263;
|
|
constexpr int DEATH_NO_BURST_FIRST = 74;
|
|
constexpr int DEATH_NO_BURST_LAST = 76;
|
|
constexpr std::string_view BIG_HORN_SPLASH_EVENT = "Poof";
|
|
constexpr std::string_view DIRT_LAYER = "dirt";
|
|
constexpr std::string_view HOLE_LAYER = "Hole";
|
|
constexpr std::string_view HOLE2_LAYER = "Hole2";
|
|
constexpr std::string_view GFUEL_ISAAC_ANM2 = "gfx/promo/gfuel/102.001_g baby (true final boss).anm2";
|
|
constexpr int DIRT_SAMPLE_FRAMES = 15;
|
|
constexpr float DIRT_GREEN = 0.9f;
|
|
constexpr float DIRT_LERP = 0.1f;
|
|
constexpr int MORPH_COLOR_PRIORITY = -1000;
|
|
constexpr ColorMod COLOR_INVISIBLE = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0}};
|
|
constexpr int UNREACHABLE_CHECK_FRAMES = 60;
|
|
constexpr int UNREACHABLE_GRACE_FRAMES = 900;
|
|
constexpr float MIDAS_COIN_SPEED = 3;
|
|
constexpr float TOXIC_CREEP_SCALE = 0.05f;
|
|
constexpr int TOXIC_SHOCK_POISON = -40;
|
|
constexpr int MODEM_FRAMES = 50;
|
|
constexpr int MODEM_ODDS = 55;
|
|
constexpr int MODEM_MIN_ODDS = 38;
|
|
constexpr int SLOWED_TIME_COLOR_PRIORITY = 250;
|
|
constexpr ColorMod GAME_KID_COLOR = {{0.3f, 0.5f, 1.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}};
|
|
constexpr ColorMod SLOWED_TIME_COLOR = {
|
|
{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 * COLOR_OFFSET_UNIT, 40 * COLOR_OFFSET_UNIT, 40 * COLOR_OFFSET_UNIT}};
|
|
constexpr int PUPPY_HIT_FRAMES = 3;
|
|
constexpr int FORCED_TARGET_BOSS_COOLDOWN = 150;
|
|
constexpr int CONFUSION_RETARGET_FRAMES = 15;
|
|
constexpr float CONFUSION_WANDER = 240;
|
|
constexpr float FEAR_WANDER = 100;
|
|
constexpr int FEAR_RETARGET_RANGE = 15;
|
|
constexpr int FEAR_RETARGET_MIN = 5;
|
|
constexpr float ATTACK_PREDICT_FRAMES = 5;
|
|
constexpr int LINE_BLOCKED_MAX = 8;
|
|
// The corners of the band a line check samples around each step.
|
|
struct LineCorner
|
|
{
|
|
float x;
|
|
float y;
|
|
};
|
|
constexpr std::array<LineCorner, 4> LINE_CORNERS = {{{-5, -5}, {-5, 5}, {5, 5}, {5, -5}}};
|
|
constexpr float SHIELD_SECOND = 30;
|
|
constexpr float SHIELD_BASE = 0.09f;
|
|
constexpr float SHIELD_FALLOFF = 0.18f;
|
|
constexpr uint32_t BLACK_HEART_CHANCE = 5;
|
|
constexpr uint32_t STICKY_SPIDERS_RANGE = 3;
|
|
constexpr uint32_t STICKY_SPIDERS_BLAST_RANGE = 5;
|
|
constexpr int JAR_OF_FLIES_MAX = 20;
|
|
constexpr float HALF_SPEED = 0.5f;
|
|
constexpr float LADDER_FOOT_MARGIN = 0.5f;
|
|
constexpr float LADDER_DROP_SPEED = 3.5f;
|
|
|
|
// The kill items: Contagion's cloud, Athame's ring at a quarter plus a fortieth of the luck, and the soul wisps
|
|
// Book of Virtues takes from a captured enemy by its soul tag.
|
|
constexpr float CONTAGION_RADIUS = 85;
|
|
constexpr uint32_t ATHAME_RNG_SHIFT_INDEX = 66;
|
|
constexpr float ATHAME_BASE_CHANCE = 0.25f;
|
|
constexpr float ATHAME_LUCK_CHANCE = 0.025f;
|
|
constexpr int ATHAME_RING_TIMEOUT = 60;
|
|
constexpr int WISP_SOUL = 0x1000a;
|
|
constexpr int WISP_SOUL_EXPLOSIVE = 0x1000b;
|
|
constexpr int WISP_SOUL_HOMING = 0x1000c;
|
|
constexpr int WISP_SOUL_BRIMSTONE = 0x1000d;
|
|
|
|
// A Brimstone marked enemy's burst: its mark and statuses spread within 120 with a hit of 10.
|
|
constexpr float MARK_SPREAD_RADIUS = 120;
|
|
constexpr int MARK_SPREAD_FRAMES = 150;
|
|
constexpr int STATUS_SPREAD_FRAMES = 90;
|
|
constexpr float MARK_SPREAD_DAMAGE = 10;
|
|
constexpr int MARK_SPREAD_COUNTDOWN = 30;
|
|
constexpr ColorMod SPREAD_SLOW_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 / 255.0f, 40 / 255.0f, 40 / 255.0f}};
|
|
constexpr int SOUND_POOP_DEATH = 237;
|
|
constexpr float POOP_DEATH_VOLUME = 0.9f;
|
|
|
|
// The burst effects a dead NPC leaves besides blood (Lua's EffectVariant).
|
|
enum DeathBurst : int
|
|
{
|
|
EFFECT_BURST_810 = 130,
|
|
EFFECT_BURST_853 = 131,
|
|
EFFECT_BURST_818 = 145
|
|
};
|
|
|
|
constexpr int ENTITY_SHADOW_CHARGER = 23;
|
|
constexpr int ENTITY_ULTRA_GREED_DOOR = 889;
|
|
constexpr int SUCKER_VARIANT_BULB = 5;
|
|
constexpr int SHADOW_CHARGER_SUBTYPE = 1;
|
|
constexpr int TYPE_NO_TICK_A = 274;
|
|
constexpr int TYPE_NO_TICK_B = 275;
|
|
|
|
// The items and seeds whose effects the NPC update reads, by Lua id.
|
|
constexpr int COLLECTIBLE_HOURGLASS_ID = 66;
|
|
constexpr int COLLECTIBLE_GAMEKID_ID = 93;
|
|
constexpr int COLLECTIBLE_CHAMPION_BELT_ID = 208;
|
|
constexpr int COLLECTIBLE_STOP_WATCH_ID = 232;
|
|
constexpr int COLLECTIBLE_SOUL_ID = 335;
|
|
constexpr int COLLECTIBLE_TOXIC_SHOCK_ID = 350;
|
|
constexpr int COLLECTIBLE_BETRAYAL_ID = 391;
|
|
constexpr int COLLECTIBLE_SPIDER_MOD_ID = 403;
|
|
constexpr int COLLECTIBLE_BROKEN_MODEM_ID = 514;
|
|
constexpr int COLLECTIBLE_GUPPYS_EYE_ID = 665;
|
|
constexpr int COLLECTIBLE_SALVATION_ID = 696;
|
|
constexpr int TRINKET_PURPLE_HEART_ID = 5;
|
|
constexpr int TRINKET_TICK_ID = 53;
|
|
constexpr int TRINKET_SUPER_MAGNET_ID = 68;
|
|
constexpr int TRINKET_LIGHTER_ID = 135;
|
|
constexpr int TRINKET_ICE_CUBE_ID = 188;
|
|
constexpr int ROOM_TRINKET_STATUS_FRAMES = -90;
|
|
constexpr int NULLITEM_DAMOCLES_WEAKNESS = 64;
|
|
|
|
constexpr int ACHIEVEMENT_BOSS_COLORS = 3;
|
|
constexpr int ACHIEVEMENT_MORE_BOSS_COLORS = 33;
|
|
constexpr int ACHIEVEMENT_REDIRECTS = 348;
|
|
constexpr uint32_t ROOM_CONFIG_FLAG_NO_CHAMPIONS = 1 << 2;
|
|
constexpr int SHIELD_FRAMES_DEFAULT = 120;
|
|
constexpr int BOSS_ID_NONE_EXCLUDED_FIRST = 46;
|
|
constexpr int BOSS_ID_NONE_EXCLUDED_LAST = 52;
|
|
constexpr int BOSS_ID_EXCLUDED = 38;
|
|
constexpr int BOSS_ID_EXCLUDED_PAIR = 260;
|
|
constexpr int BOSS_ID_EXCLUDED_PAIR_VARIANT = 10;
|
|
|
|
// The champion chances: any enemy, with Champion Belt, on the Void, and a boss's color.
|
|
constexpr float CHAMPION_CHANCE = 0.05f;
|
|
constexpr float CHAMPION_CHANCE_BELT = 0.2f;
|
|
constexpr float CHAMPION_CHANCE_VOID = 0.75f;
|
|
constexpr float CHAMPION_CHANCE_LATE_SPAWN = 0.2f;
|
|
constexpr float CHAMPION_CHANCE_VICTORY_LAP = 0.25f;
|
|
constexpr float CHAMPION_CHANCE_PURPLE_HEART = 3;
|
|
|
|
constexpr unsigned int STATUS_SHARED = 1u << 31;
|
|
constexpr std::string_view STATUS_EFFECTS_ANM2 = "gfx/StatusEffects.anm2";
|
|
|
|
// The target search: how far enemies look for players, and what pushes a player back or pulls a twin forward.
|
|
constexpr float TARGET_RANGE = 5000;
|
|
constexpr float TARGET_INVINCIBLE_PENALTY = 400;
|
|
constexpr float TARGET_UNCONTROLLED_PENALTY = 800;
|
|
constexpr float TWIN_NEAR_SQUARED = 10000;
|
|
constexpr float BULB_CHARGE_BASE = 10000;
|
|
constexpr float BULB_CHARGE_STEP = 2000;
|
|
constexpr float BULB_DISTANCE_SCALE = 0.001f;
|
|
constexpr float BAIT_REACH = 500;
|
|
constexpr float BAITED_DISTANCE_SCALE = 1e-05f;
|
|
constexpr float PUPPY_SMALL_PREY_SCALE = 0.5f;
|
|
constexpr float PUPPY_BISHOP_SCALE = 0.01f;
|
|
constexpr float PUPPY_KIN_PENALTY = 250000;
|
|
constexpr int TARGET_REFRESH_FRAMES = 15;
|
|
constexpr int DECOY_TIMER_MAX = 180;
|
|
|
|
// The appear poof and the sizes of poofs and blood bursts by the NPC's size.
|
|
constexpr int APPEAR_POOF_FRAME = 1;
|
|
constexpr int APPEAR_SHOW_FRAME = 4;
|
|
constexpr int APPEAR_MIN_FRAMES = 20;
|
|
constexpr float APPEAR_FRICTION = 0.01f;
|
|
constexpr float TICK_HEALTH_MIN = 60;
|
|
constexpr float TICK_HEALTH_SCALE = 0.85f;
|
|
constexpr float POOF_SMALL_SIZE = 13;
|
|
constexpr float POOF_LARGE_SIZE = 18;
|
|
constexpr float POOF_LARGE_SHADOW = 30;
|
|
constexpr float POOF_HUGE_SIZE = 40;
|
|
constexpr float POOF_HUGE_SHADOW = 50;
|
|
constexpr float BLOOD_DEPTH_OFFSET = 10;
|
|
constexpr float PAUSE_SLOWDOWN = 0.6f;
|
|
constexpr float RIPPLE_SCALE = 0.05f;
|
|
constexpr float RIPPLE_DEPTH = -10;
|
|
constexpr float RIPPLE_SPEED = 0.5f;
|
|
constexpr int RIPPLE_FRAMES = 7;
|
|
constexpr float POOF02_SCALE = 0.3f;
|
|
constexpr float POOF02_DEPTH = 10;
|
|
constexpr ColorMod POOF02_COLOR = {{1, 1, 1, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}};
|
|
constexpr float SLOW_FRICTION = 0.92f;
|
|
constexpr int WEAKNESS_FRAMES = 2;
|
|
constexpr int STATUS_REFRESH = -2;
|
|
constexpr int SLOW_TIMESCALE_EFFECT_FRAMES = 30;
|
|
|
|
// The speed an NPC moves at: slowed by the stopwatch, the hourglass, its own slowing and Betrayal's charm.
|
|
constexpr float SPEED_HALF = 0.5f;
|
|
constexpr float SPEED_WEAKENED = 0.65f;
|
|
constexpr float SPEED_VANISHING_TWIN = 0.75f;
|
|
|
|
// 0043ef30 Shoots one plain shot at a random circle angle.
|
|
ProjectileParams::ProjectileParams() : circleAngle(random_unit() * PI_F) {}
|
|
|
|
// Plays a sound through the fart seeds.
|
|
void npc_sound_play(int sound, float volume, int frameDelay, float pitch)
|
|
{
|
|
seed_fart_sound_override(&sound);
|
|
g_manager->sfxManager.Play(sound, {.volume = volume, .frameDelay = frameDelay, .pitch = pitch});
|
|
}
|
|
|
|
// The size class of the poofs and blood bursts an NPC leaves: 1 small to 4 huge, the last only when isHugeAllowed.
|
|
int poof_size_get(Entity& entity, bool isHugeAllowed)
|
|
{
|
|
int poof = entity.size < POOF_SMALL_SIZE ? 1 : 2;
|
|
if (entity.size >= POOF_LARGE_SIZE || entity.shadowSize > POOF_LARGE_SHADOW) poof = 3;
|
|
if (isHugeAllowed && (entity.size >= POOF_HUGE_SIZE || entity.shadowSize > POOF_HUGE_SHADOW)) poof = 4;
|
|
return poof;
|
|
}
|
|
|
|
// Spawns an entity where an NPC stands.
|
|
Entity* spawn_at(int type, int variant, int subType, const Vector& position, Entity* spawner)
|
|
{
|
|
return g_game->Spawn({.position = position,
|
|
.spawner = spawner,
|
|
.subType = subType,
|
|
.type = type,
|
|
.variant = variant,
|
|
.seed = Random()});
|
|
}
|
|
|
|
// Whether an entity may be the nearest enemy (Game::GetNearestEnemy): a living, targetable, collidable enemy past its
|
|
// first frame that is not friendly, nor a fireplace, shopkeeper, TNT, poop, prop, minecart or the blood cultist's
|
|
// spawn. In a versus match the other players count too.
|
|
static bool is_nearest_enemy_candidate(Entity& entity, bool isVersusPlayer)
|
|
{
|
|
int type = entity.type;
|
|
|
|
if (g_game->frameCount - entity.spawnFrame <= 1) return false;
|
|
if (!isVersusPlayer && (type < ENTITY_FIRST_ENEMY || type > ENTITY_LAST_ENEMY)) return false;
|
|
if (entity.entityCollisionClass == ENTCOLL_NONE || entity.entityCollisionClass == ENTCOLL_PLAYERONLY) return false;
|
|
if (entity.isInvincible || entity.isDead || entity.HasEntityFlags(FLAG_NO_TARGET | FLAG_FRIENDLY)) return false;
|
|
if (isVersusPlayer) return true;
|
|
if (type == ENTITY_CULTIST) return entity.variant != CULTIST_BLOOD_SPAWN;
|
|
return type != ENTITY_FIREPLACE && type != ENTITY_SHOPKEEPER && type != ENTITY_MOVABLE_TNT && type != ENTITY_POOP &&
|
|
type != ENTITY_GENERIC_PROP && type != ENTITY_MINECART;
|
|
}
|
|
|
|
// A candidate's measure in a nearest search: the search's own, or its squared distance from the position.
|
|
static float target_distance_get(TargetDistance distance, const Vector& position, Entity* source, Entity& candidate)
|
|
{
|
|
if (distance) return distance(position, source, candidate);
|
|
return vector_length_squared(vector_sub(candidate.pos, position));
|
|
}
|
|
|
|
// 00707370 Game::GetNearestEnemy: the enemy nearest a position (by the search's measure) within a radius that a
|
|
// source may target, a charmed one counted 400 farther. A friendly source passes over the players it may not hurt,
|
|
// and in a versus match over its own ancestors.
|
|
Entity* game_nearest_enemy(const Vector& position, Entity* source, float radius, TargetDistance measure)
|
|
{
|
|
constexpr float CHARMED_DISTANCE_SQUARED = 160000;
|
|
bool isVersus = g_game->deathmatchManager.is_active();
|
|
Entity* nearest = nullptr;
|
|
float best = radius * radius;
|
|
|
|
for (Entity* entity : g_game->room->entityList.updateEL)
|
|
{
|
|
bool isPlayer = entity->type == ENTITY_PLAYER;
|
|
if (isPlayer && source && source->HasEntityFlags(FLAG_FRIENDLY) &&
|
|
source->IsDamageSourceFriendly(EntityRef(entity)))
|
|
continue;
|
|
if (source && ((isVersus && source->IsDescendantOf(entity)) || !source->IsValidTarget(entity))) continue;
|
|
if (!is_nearest_enemy_candidate(*entity, isVersus && isPlayer)) continue;
|
|
|
|
float distance = target_distance_get(measure, position, source, *entity);
|
|
if (entity->HasEntityFlags(FLAG_CHARM)) distance += CHARMED_DISTANCE_SQUARED;
|
|
if (distance >= best) continue;
|
|
best = distance;
|
|
nearest = entity;
|
|
}
|
|
return nearest;
|
|
}
|
|
|
|
// 00703950 The player nearest a position, the first on ties.
|
|
Entity_Player* game_nearest_player(const Vector& position)
|
|
{
|
|
std::vector<Entity_Player*>& players = g_game->playerManager.playerList;
|
|
Entity_Player* nearest = g_game->GetPlayer(0);
|
|
float best = vector_length_squared(vector_sub(position, nearest->pos));
|
|
|
|
for (size_t i = 1; i < players.size(); i++)
|
|
{
|
|
float distance = vector_length_squared(vector_sub(position, players[i]->pos));
|
|
if (distance >= best) continue;
|
|
best = distance;
|
|
nearest = players[i];
|
|
}
|
|
return nearest;
|
|
}
|
|
|
|
// (00703ab0) Game::GetNearestPlayerEx for the main players only: the nearest player itself (not a co-op ghost, baby,
|
|
// twin's hold or hologram) that collides with entities.
|
|
Entity_Player* main_player_nearest(const Vector& position)
|
|
{
|
|
Entity_Player* nearest = nullptr;
|
|
float best = 1e10f;
|
|
|
|
for (Entity_Player* player : g_game->playerManager.playerList)
|
|
{
|
|
float distance = vector_length_squared(vector_sub(position, player->pos));
|
|
if (distance >= best) continue;
|
|
if (player->variant != 0 || player->isCoopGhost || player->parent || player->IsHologram()) continue;
|
|
if (player->entityCollisionClass == ENTCOLL_NONE) continue;
|
|
|
|
nearest = player;
|
|
best = distance;
|
|
}
|
|
return nearest;
|
|
}
|
|
|
|
// The charge Bulb drains a player for: one per full active, else its charges.
|
|
static int active_charges_get(Entity_Player& player)
|
|
{
|
|
int charges = 0;
|
|
for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++)
|
|
{
|
|
if (!g_manager->itemConfig.GetCollectible(player.activeItems[slot].item)) continue;
|
|
int maxCharge = player.GetActiveMaxCharge(slot);
|
|
if (maxCharge > 0) charges += maxCharge == 1 ? 1 : player.activeItems[slot].charge;
|
|
}
|
|
return charges;
|
|
}
|
|
|
|
// What a target counts as from a position: its squared distance, pushed back while its player is invincible or (for
|
|
// the Blood Puppy) without control, pulled to a twin walking into the other, and for Bulb led by the active charge it holds.
|
|
static float target_score_get(const Vector& position, Entity* source, Entity& target, Entity_Player* player,
|
|
bool isBulb, TargetDistance measure)
|
|
{
|
|
float distance = target_distance_get(measure, position, source, target);
|
|
if (!player) return distance;
|
|
|
|
Entity_Player* twin = player->twin_get();
|
|
if (player->HasInvincibility(0, EntityRef())) distance += TARGET_INVINCIBLE_PENALTY;
|
|
else if ((!player->isControlsEnabled || player->controlsCooldown > 0) && source && source->type == ENTITY_BLOOD_PUPPY)
|
|
distance += TARGET_UNCONTROLLED_PENALTY;
|
|
else if (twin)
|
|
{
|
|
Vector between = vector_sub(twin->pos, player->pos);
|
|
bool isMeeting = vector_dot(vector_add(player->velocity, twin->velocity), between) < 0 &&
|
|
vector_length_squared(between) < TWIN_NEAR_SQUARED;
|
|
if (isMeeting) distance = target_distance_get(measure, position, source, *twin) + 1;
|
|
}
|
|
if (!isBulb) return distance;
|
|
|
|
float priority = std::max(BULB_CHARGE_BASE - (float)active_charges_get(*player) * BULB_CHARGE_STEP, 0.0f);
|
|
return distance * BULB_DISTANCE_SCALE + priority;
|
|
}
|
|
|
|
// Whether a player found among the enemies is one a friendly source spares. The original reads the source's flags
|
|
// even without one, which this skips.
|
|
static bool prey_is_friendly(Entity* candidate, Entity* source)
|
|
{
|
|
return candidate->type == ENTITY_PLAYER && source && source->HasEntityFlags(FLAG_FRIENDLY) &&
|
|
source->IsDamageSourceFriendly(EntityRef(candidate));
|
|
}
|
|
|
|
// Whether the hunting enemies (the Blood Puppy, the level 2 Willo) may hunt it: a player in deathmatch, or an enemy
|
|
// that is not a fire, shopkeeper, TNT, prop, minecart, poop or the Cultist's blood pool.
|
|
bool entity_is_prey(Entity& prey)
|
|
{
|
|
if (prey.type == ENTITY_PLAYER) return g_game->deathmatchManager.is_active();
|
|
if (!Entity::is_enemy_type(prey.type) || prey.type == ENTITY_FIREPLACE || prey.type == ENTITY_SHOPKEEPER || prey.type == ENTITY_MOVABLE_TNT)
|
|
return false;
|
|
if (prey.type == ENTITY_CULTIST) return prey.variant != CULTIST_POOL;
|
|
return prey.type != ENTITY_GENERIC_PROP && prey.type != ENTITY_MINECART && prey.type != ENTITY_POOP;
|
|
}
|
|
|
|
// 007069a0 What an enemy at a position goes after: the nearest visible player within reach (Dark Esau only Jacob),
|
|
// else a Punching Bag, then a baited enemy, or for the Blood Puppy its nearest prey. An enemy forced onto a target keeps
|
|
// it. Isaac's Heart stands in for its player.
|
|
// The stand-in target a player keeps at Entity_Player 0x144c waits for Entity_Player to name it.
|
|
Entity* game_nearest_target_player(const Vector& position, Entity* source, bool isPlayersOnly, bool isTargetDecoys,
|
|
float maxDistance, TargetDistance measure)
|
|
{
|
|
if (!isPlayersOnly && isTargetDecoys && source && source->IsEnemy())
|
|
{
|
|
Entity* forced = static_cast<Entity_NPC*>(source)->forcedTarget;
|
|
if (forced) return forced;
|
|
}
|
|
|
|
bool isBulb = source && source->type == ENTITY_SUCKER && source->variant == SUCKER_VARIANT_BULB;
|
|
isPlayersOnly = isPlayersOnly || isBulb;
|
|
isTargetDecoys = isTargetDecoys && !isBulb;
|
|
Entity* nearest = nullptr;
|
|
float best = maxDistance * maxDistance;
|
|
|
|
for (Entity_Player* candidate : g_game->playerManager.playerList)
|
|
{
|
|
Entity_Player* twin = candidate->twin_get();
|
|
bool isTwinLed = (candidate->playerType == PLAYER_LAZARUS_B || candidate->playerType == PLAYER_LAZARUS2_B) &&
|
|
twin && twin->playerIndex != -1 && twin->playerIndex < candidate->playerIndex;
|
|
if (candidate->isCoopGhost || (candidate->isExists && isTwinLed && twin != candidate)) continue;
|
|
if (source && source->IsFriendly() && source->IsDamageSourceFriendly(EntityRef(candidate))) continue;
|
|
|
|
Entity* target = candidate;
|
|
if (!isPlayersOnly && candidate->bestFriend) target = candidate->bestFriend.get();
|
|
else if (!isPlayersOnly && candidate->darkArtsLastSnare) target = candidate->darkArtsLastSnare->GetLastParent();
|
|
Entity_Player* player = target && target->type == ENTITY_PLAYER ? static_cast<Entity_Player*>(target) : nullptr;
|
|
if (!target) continue;
|
|
|
|
bool isJacob = candidate->playerType == PLAYER_JACOB || candidate->playerType == PLAYER_JACOB_B ||
|
|
candidate->playerType == PLAYER_JACOB2_B;
|
|
if (source && source->type == ENTITY_DARK_ESAU && !isJacob) continue;
|
|
if (target->type == ENTITY_FAMILIAR && target->variant == Entity_Familiar::ISAACS_HEART)
|
|
player = static_cast<Entity_Familiar*>(target)->player;
|
|
if (player && player->IsInvisible()) continue;
|
|
|
|
float score = target_score_get(position, source, *target, player, isBulb, measure);
|
|
if (score >= best) continue;
|
|
best = score;
|
|
nearest = target;
|
|
}
|
|
if (!isPlayersOnly && isTargetDecoys)
|
|
{
|
|
for (Entity* decoy : g_game->room->entityList.mainEL)
|
|
{
|
|
if (decoy->type != ENTITY_FAMILIAR || decoy->variant != Entity_Familiar::PUNCHING_BAG) continue;
|
|
float distance = target_distance_get(measure, position, source, *decoy);
|
|
if (distance >= best) continue;
|
|
best = distance;
|
|
nearest = decoy;
|
|
}
|
|
}
|
|
if (!isPlayersOnly && g_game->room->entityList.isAnyBaited)
|
|
{
|
|
for (Entity* baited : entity_query_radius(position, std::min(maxDistance, BAIT_REACH), QUERY_ENEMIES))
|
|
{
|
|
if (prey_is_friendly(baited, source) || baited->isDead || !baited->HasEntityFlags(FLAG_BAITED)) continue;
|
|
if (!source || !source->IsValidTarget(baited)) continue;
|
|
float distance = target_distance_get(measure, position, source, *baited) * BAITED_DISTANCE_SCALE;
|
|
if (distance >= best) continue;
|
|
best = distance;
|
|
nearest = baited;
|
|
}
|
|
return nearest;
|
|
}
|
|
if (!source || source->type != ENTITY_BLOOD_PUPPY) return nearest;
|
|
|
|
float preyScale = source->variant == 0 ? PUPPY_SMALL_PREY_SCALE : 1;
|
|
for (Entity* prey : entity_query_radius(position, std::min(maxDistance, BAIT_REACH), QUERY_ENEMIES))
|
|
{
|
|
if (prey_is_friendly(prey, source) || prey->isDead || prey == source) continue;
|
|
if (g_game->frameCount - prey->spawnFrame <= 1 || !prey->IsVulnerableEnemy(nullptr) || !entity_is_prey(*prey))
|
|
continue;
|
|
if (prey->HasEntityFlags(FLAG_NO_TARGET)) continue;
|
|
|
|
float distance = target_distance_get(measure, position, source, *prey);
|
|
bool isFriendly = prey->HasEntityFlags(FLAG_FRIENDLY);
|
|
if (prey->type == ENTITY_BISHOP && !isFriendly) distance *= PUPPY_BISHOP_SCALE;
|
|
if (prey->type == ENTITY_BLOOD_PUPPY) distance += PUPPY_KIN_PENALTY;
|
|
if (!isFriendly) distance *= preyScale;
|
|
if (distance >= best) continue;
|
|
best = distance;
|
|
nearest = prey;
|
|
}
|
|
return nearest;
|
|
}
|
|
|
|
// 00703670 Shakes the screen for a time. The controllers' rumble is not wired here.
|
|
void game_shake_screen(int timeout)
|
|
{
|
|
g_game->screenShakeTimer = timeout;
|
|
}
|
|
|
|
// 006d8240 Whether the run is on Hard or Greedier.
|
|
bool game_is_hard_mode()
|
|
{
|
|
return g_game->difficulty == DIFFICULTY_HARD || g_game->difficulty == DIFFICULTY_GREEDIER;
|
|
}
|
|
|
|
// 00703470 Remembers a boss as met this run, but for the ones the boss list leaves out.
|
|
void game_encountered_boss_add(int bossType, int bossVariant)
|
|
{
|
|
std::vector<BossId>& bosses = g_game->encounteredBosses;
|
|
auto isSame = [&](const BossId& boss) {
|
|
return boss.type == bossType && boss.variant == bossVariant;
|
|
};
|
|
if (std::ranges::any_of(bosses, isSame)) return;
|
|
|
|
bool isListed = (bossType < BOSS_ID_NONE_EXCLUDED_FIRST || bossType > BOSS_ID_NONE_EXCLUDED_LAST) &&
|
|
bossType != BOSS_ID_EXCLUDED &&
|
|
(bossType != BOSS_ID_EXCLUDED_PAIR || bossVariant != BOSS_ID_EXCLUDED_PAIR_VARIANT);
|
|
if (isListed) bosses.push_back({bossType, bossVariant});
|
|
}
|
|
|
|
// 007f0780 The grid collision of the cell under a position, or of no cell outside the grid.
|
|
uint32_t room_grid_collision_at(const Vector& position)
|
|
{
|
|
Room& room = *g_game->room;
|
|
int column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + HALF);
|
|
int row = (int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + HALF);
|
|
bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight;
|
|
return room.GetGridCollision(isInside ? room.gridWidth * row + column : -1);
|
|
}
|
|
|
|
// What a line check meets in a cell: an outside cell is a wall, an empty one by its grid path (3000 to 3999 a pit,
|
|
// 1000 up blocked), else its grid entity's collision. The Beast's crawlspace blocks nothing.
|
|
static int line_cell_collision(Room& room, int column, int row)
|
|
{
|
|
RoomConfig_Room* config = room.descriptor ? room.descriptor->data : nullptr;
|
|
if (config && config->type == ROOM_DUNGEON && config->stageId == STAGE_ID_HOME) return COLLISION_NONE;
|
|
if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return COLLISION_WALL;
|
|
|
|
int gridIndex = row * room.gridWidth + column;
|
|
if (GridEntity* grid = room.GetGridEntity(gridIndex)) return grid->collisionClass;
|
|
int path = room.GetGridPath(gridIndex);
|
|
if ((uint32_t)(path - GRID_PATH_PIT) < GRID_PATH_BAND) return COLLISION_PIT;
|
|
return path >= GRID_PATH_SOLID ? COLLISION_SOLID : COLLISION_NONE;
|
|
}
|
|
|
|
// Whether a blast stops at a cell: walls (but an unlocked lock, a door, or a wall when walls are ignored) and solid
|
|
// blocks. With crushables ignored, a grid entity that can be crushed or walked stops it too.
|
|
static bool line_cell_is_blast_wall(Room& room, int cellIndex, const LineQuery& check)
|
|
{
|
|
uint32_t collision = room.GetGridCollision(cellIndex);
|
|
bool isKnown = cellIndex >= 0 && cellIndex < ROOM_GRID_CELLS;
|
|
GridEntity* grid = isKnown ? room.gridEntities[cellIndex] : nullptr;
|
|
if (!grid) return collision == COLLISION_WALL;
|
|
if (collision != COLLISION_NONE && grid->type == GRID_ROCKB) return true;
|
|
if (grid->type == GRID_LOCK && g_game->playerManager.AnyoneHasTrinket(TRINKET_BROKEN_PADLOCK)) return false;
|
|
|
|
bool isPassable = grid->type == GRID_DOOR || (grid->type == GRID_WALL && check.isIgnoreWalls);
|
|
if (!isPassable && collision == COLLISION_WALL) return true;
|
|
return check.isIgnoreCrushable && (grid->IsEasyCrushableOrWalkable() || grid->IsDangerousCrushableOrWalkable());
|
|
}
|
|
|
|
// Whether a band corner's collision lets a line through: with crushables ignored, a grid entity in the grid that can
|
|
// be crushed or walked does.
|
|
static bool line_corner_is_crushable(Room& room, int column, int row, const LineQuery& check)
|
|
{
|
|
bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight;
|
|
int gridIndex = isInside ? row * room.gridWidth + column : -1;
|
|
if (!check.isIgnoreCrushable || gridIndex < 0 || gridIndex >= ROOM_GRID_CELLS) return false;
|
|
|
|
GridEntity* grid = room.gridEntities[gridIndex];
|
|
return grid && (grid->IsEasyCrushableOrWalkable() || grid->IsDangerousCrushableOrWalkable());
|
|
}
|
|
|
|
// 007f0df0 Whether a line from start to end is clear, walked in steps of 10: mode 0 checks a 10 wide band for grid
|
|
// collision and for more than 8 cells walked past their grid path threshold, mode 1 the same on the line's own cells,
|
|
// mode 2 the line's own cells for what stops a blast, mode 3 the band for shots (which fly over pits), and any other
|
|
// mode nothing. The stop position, when asked, gets the step before the line was blocked, or the end.
|
|
bool room_check_line(const LineQuery& check)
|
|
{
|
|
Room& room = *g_game->room;
|
|
auto stop = [&](const Vector& position, bool isClear) {
|
|
if (check.stopPosition) *check.stopPosition = position;
|
|
return isClear;
|
|
};
|
|
Vector step = vector_sub(check.start, check.end);
|
|
float length = vector_length(step);
|
|
if (length <= 0) return stop(check.end, true);
|
|
|
|
step = vector_scale(step, LINE_STEP / length);
|
|
auto cellOf = [](float value, float origin) {
|
|
return (int)((value - origin) / GRID_CELL_SIZE + HALF);
|
|
};
|
|
int startColumn = cellOf(check.start.x, GRID_ORIGIN_X);
|
|
int startRow = cellOf(check.start.y, GRID_ORIGIN_Y);
|
|
bool isStartInside =
|
|
startColumn >= 0 && startColumn < room.gridWidth && startRow >= 0 && startRow < room.gridHeight;
|
|
int startIndex = isStartInside ? room.gridWidth * startRow + startColumn : -1;
|
|
|
|
int blocked = 0;
|
|
Vector at = check.start;
|
|
for (float walked = 0; walked < length; walked += LINE_STEP)
|
|
{
|
|
at = vector_sub(at, step);
|
|
Vector before = vector_add(at, step);
|
|
if (check.mode != LINE_MODE_GROUND && check.mode != LINE_MODE_PROJECTILE)
|
|
{
|
|
int column = cellOf(at.x, GRID_ORIGIN_X);
|
|
int row = cellOf(at.y, GRID_ORIGIN_Y);
|
|
bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight;
|
|
int cellIndex = isInside ? row * room.gridWidth + column : -1;
|
|
if (check.mode == LINE_MODE_EXPLOSION && line_cell_is_blast_wall(room, cellIndex, check))
|
|
return stop(before, false);
|
|
if (check.mode != LINE_MODE_CELL) continue;
|
|
|
|
if (room.GetGridCollision(cellIndex) != COLLISION_NONE) return stop(before, false);
|
|
if (cellIndex != startIndex && cellIndex >= 0 && room.GetGridPath(cellIndex) > check.gridPathThreshold)
|
|
blocked++;
|
|
continue;
|
|
}
|
|
for (const LineCorner& corner : LINE_CORNERS)
|
|
{
|
|
int column = cellOf(at.x + corner.x, GRID_ORIGIN_X);
|
|
int row = cellOf(at.y + corner.y, GRID_ORIGIN_Y);
|
|
int collision = line_cell_collision(room, column, row);
|
|
if (check.mode == LINE_MODE_PROJECTILE && collision == COLLISION_PIT) continue;
|
|
if (collision != COLLISION_NONE)
|
|
{
|
|
if (line_corner_is_crushable(room, column, row, check)) continue;
|
|
return stop(before, false);
|
|
}
|
|
|
|
bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight;
|
|
int cornerIndex = isInside ? row * room.gridWidth + column : -1;
|
|
if (cornerIndex == startIndex) continue;
|
|
int path = cornerIndex >= 0 ? room.GetGridPath(cornerIndex) : 0;
|
|
if (check.mode == LINE_MODE_GROUND && path > check.gridPathThreshold) blocked++;
|
|
}
|
|
}
|
|
if (blocked > LINE_BLOCKED_MAX) return stop(vector_add(at, step), false);
|
|
return stop(check.end, true);
|
|
}
|
|
|
|
// The suppression the console sets so its next spawned NPC is not rolled a champion (the original's 00c71670).
|
|
bool g_isChampionRollSkipped = false;
|
|
|
|
// 006b8b20 Starts it appearing: every counter and link back to its defaults, its config loaded (Entity::Init), and
|
|
// a boss counted by the room.
|
|
void Entity_NPC::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed)
|
|
{
|
|
isChampion = false;
|
|
championColorIdx = CHAMPION_NONE;
|
|
flickerTimer = 0;
|
|
flickerState = 0;
|
|
flickerAlpha = 1;
|
|
championSpeed = 1;
|
|
bosscoloridx = -1;
|
|
isUnreachableOnce = false;
|
|
scale = 1;
|
|
shieldStrength = 0;
|
|
shieldFrames = SHIELD_FRAMES_DEFAULT;
|
|
deliriumBossType = 0;
|
|
deliriumBossVariant = 0;
|
|
deliriumTransformationTimer = 0;
|
|
deliriumRemainingAttacks = 0;
|
|
deliriumState = 0;
|
|
deliriumEntity = nullptr;
|
|
isBestiaryEncountered = false;
|
|
isDeathSoundAlt = false;
|
|
aiCallFlags = 0;
|
|
controllerID = -1;
|
|
isControlSwapped = false;
|
|
controllerMovement = {};
|
|
aimTargetEffect = nullptr;
|
|
forwardVector = {};
|
|
forcedTarget = nullptr;
|
|
forcedTargetTimer = 0;
|
|
sirenPlayerEntity = nullptr;
|
|
hitPointsMulti = 1;
|
|
scaleMulti = 1;
|
|
lastGridIndex = -1;
|
|
if (pickupGhostsEntity) pickupGhostsEntity->Remove();
|
|
pickupGhostsEntity = nullptr;
|
|
if (salvationTarget) salvationTarget->Remove();
|
|
salvationTarget = nullptr;
|
|
unknownF54 = nullptr;
|
|
killDamageEvents.clear();
|
|
killDamage = 0;
|
|
killDamageFlags = 0;
|
|
|
|
Entity::Init(entityType, entityVariant, entitySubType, seed);
|
|
AddEntityFlags(FLAG_APPEAR);
|
|
state = NPC_STATE_APPEAR;
|
|
savedState = NPC_STATE_INIT;
|
|
aiCallPhase = AI_PHASE_UPDATE;
|
|
stateFrame = 0;
|
|
aiCounter = 0;
|
|
appearFrames = 0;
|
|
decoyTargetTimer = 0;
|
|
groupIdx = -1;
|
|
targetPosition = {};
|
|
confusionTargetPos = {};
|
|
aiFloat = 1;
|
|
v1 = {};
|
|
v2 = {};
|
|
championRegenTimer = 0;
|
|
championRegenCount = 0;
|
|
holdCountdown = 0;
|
|
i1 = 0;
|
|
i2 = 0;
|
|
entityRef = nullptr;
|
|
projectileCooldown = 0;
|
|
projectileDelay = -1;
|
|
championTimer = 0;
|
|
holdPosition = {};
|
|
isUnknownC61 = false;
|
|
isUnknownC62 = false;
|
|
floorColor = {};
|
|
hitList.clear();
|
|
secondaryHitList.clear();
|
|
pathfinder.Reset();
|
|
if (isBoss) g_game->room->bossesRemaining++;
|
|
totalDamageTaken = 0;
|
|
lua_engine_get().PostNPCInit(this);
|
|
}
|
|
|
|
// The odds a boss spawns in one of its alternate colors.
|
|
static float boss_color_chance_get()
|
|
{
|
|
Game& game = *g_game;
|
|
float chance = g_manager->persistentGameData.Unlocked(ACHIEVEMENT_MORE_BOSS_COLORS) ? 0.3f : 0.1f;
|
|
if (game.difficulty == DIFFICULTY_GREEDIER) chance = 0.6f;
|
|
if (game.playerManager.AnyoneHasTrinket(TRINKET_PURPLE_HEART_ID))
|
|
chance *= (float)game.playerManager.GetTrinketMultiplier(TRINKET_PURPLE_HEART_ID) * 2;
|
|
if (game.challenge == CHALLENGE_ULTRA_HARD || game.victoryLap > 0) chance = 1;
|
|
return chance;
|
|
}
|
|
|
|
// Part of 006bb790: a boss rolls one of its alternate colors from the room's spawn seed (its subtype, 1 up), the
|
|
// Repentance stages fix Monstro's and Gurdy Jr's, and a color that loads swaps in its sheet, scale and health.
|
|
void Entity_NPC::boss_color_roll()
|
|
{
|
|
Game& game = *g_game;
|
|
int colors = (int)config->bossColors.size();
|
|
if (spawnerEntity && spawnerEntity->type == ENTITY_BIG_HORN) colors = 0;
|
|
|
|
if (g_isChampionRollSkipped)
|
|
{
|
|
colors = 0;
|
|
g_isChampionRollSkipped = false;
|
|
}
|
|
else if (colors > 0 && subtype == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_BOSS_COLORS))
|
|
{
|
|
RoomDescriptor* descriptor = game.room->descriptor;
|
|
RNG rng = {descriptor ? descriptor->spawnSeed : 0, 1, 11, 16};
|
|
if (rng.RandomFloat() < boss_color_chance_get()) subtype = (int)rng.RandomInt(colors) + 1;
|
|
if (config->id == ENTITY_MOM && subtype == 2 && game.challenge == CHALLENGE_GUARDIAN) subtype = 0;
|
|
}
|
|
if (game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B)
|
|
{
|
|
if (config->id == ENTITY_MOM) subtype = 3;
|
|
else if (config->id == ENTITY_MOMS_HEART) subtype = 1;
|
|
}
|
|
if (subtype == 0 || (uint32_t)subtype > (uint32_t)colors) return;
|
|
|
|
EntityConfig_BossColor color = config->bossColors[subtype - 1];
|
|
bosscoloridx = subtype - 1;
|
|
sprite.scale = vector_scale(sprite.scale, color.scale);
|
|
scale = color.scale;
|
|
maxHitPoints *= color.hpMultiplier;
|
|
ResetColor();
|
|
load_graphics(true);
|
|
sprite.SetFrame(sprite.GetDefaultAnimationName(), 0);
|
|
}
|
|
|
|
// 006bb790 Loads its config and sprite, then rolls whether it spawns a champion, or a boss's alternate color.
|
|
void Entity_NPC::LoadEntityConfig()
|
|
{
|
|
RNG rng = {initSeed, 1, 5, 16};
|
|
isBoss = false;
|
|
Entity::LoadEntityConfig();
|
|
if (!config)
|
|
{
|
|
log_printf(LOG_INFO, "[warn] No entity config for NPC %d.%d\n", type, variant);
|
|
return;
|
|
}
|
|
|
|
load_graphics(true);
|
|
sprite.scale = vector_make(1, 1);
|
|
if (sprite.SetAnimation(sprite.GetDefaultAnimationName(), SWITCH_KEEP_FRAME) && sprite.animState.animData)
|
|
{
|
|
sprite.animState.SetFrameFloat(0);
|
|
sprite.animState.isPlaying = false;
|
|
}
|
|
isCanShutDoors = config->isShutDoors;
|
|
isBoss = config->isBoss;
|
|
shieldStrength = config->shieldStrength;
|
|
shieldFrames = config->shieldFrames;
|
|
|
|
Game& game = *g_game;
|
|
Room& room = *game.room;
|
|
float chance = game.playerManager.FirstCollectibleOwner(COLLECTIBLE_CHAMPION_BELT_ID, LAZARUS_SHARE_CHECK)
|
|
? CHAMPION_CHANCE_BELT
|
|
: CHAMPION_CHANCE;
|
|
if (game.stage == STAGE_VOID) chance = CHAMPION_CHANCE_VOID;
|
|
if (game.playerManager.AnyoneHasTrinket(TRINKET_PURPLE_HEART_ID))
|
|
chance *=
|
|
(float)game.playerManager.GetTrinketMultiplier(TRINKET_PURPLE_HEART_ID) * CHAMPION_CHANCE_PURPLE_HEART;
|
|
if (room.isInitialized) chance *= CHAMPION_CHANCE_LATE_SPAWN;
|
|
if (game.seedEffects.HasSeedEffect(SEED_ALL_CHAMPIONS)) chance = 1;
|
|
|
|
if (isBoss) boss_color_roll();
|
|
else
|
|
{
|
|
bool isAllowed = config->isCanBeChampion && !isChampion && !room.isInitialized &&
|
|
!room.has_room_config_flag(ROOM_CONFIG_FLAG_NO_CHAMPIONS) &&
|
|
(room.roomType != ROOM_BOSS || type != ENTITY_ULTRA_GREED_DOOR);
|
|
if (isAllowed && (rng.RandomFloat() < chance || game.challenge == CHALLENGE_ULTRA_HARD ||
|
|
(game.victoryLap > 0 && rng.RandomFloat() < CHAMPION_CHANCE_VICTORY_LAP)))
|
|
isChampion = true;
|
|
}
|
|
|
|
if (g_isChampionRollSkipped)
|
|
{
|
|
isChampion = false;
|
|
g_isChampionRollSkipped = false;
|
|
}
|
|
else if (isChampion) MakeChampion(rng.Next(), championColorIdx, true);
|
|
}
|
|
|
|
// 006b9c10 A layer's sheet with the champion suffix and the stage's floor suffix put before its extension, the first
|
|
// of (both, champion only, floor only) a mod or the resources hold, else the sheet itself. isChampionSheet says
|
|
// whether the one found has the champion suffix.
|
|
std::string sheet_path_resolve(const std::string& path, std::string_view floorSuffix, std::string_view championSuffix,
|
|
bool& isChampionSheet)
|
|
{
|
|
isChampionSheet = false;
|
|
if (path.size() < SHEET_EXTENSION_SIZE || (floorSuffix.empty() && championSuffix.empty())) return path;
|
|
|
|
std::string stem = path.substr(0, path.size() - SHEET_EXTENSION_SIZE);
|
|
std::string extension = path.substr(path.size() - SHEET_EXTENSION_SIZE);
|
|
auto isFound = [&](const std::string& candidate) {
|
|
return std::filesystem::exists(resource_path(g_manager->modManager.TryRedirectPath(candidate)));
|
|
};
|
|
|
|
std::string both = stem + std::string(championSuffix) + std::string(floorSuffix) + extension;
|
|
if (!championSuffix.empty() && !floorSuffix.empty() && isFound(both))
|
|
{
|
|
isChampionSheet = true;
|
|
return both;
|
|
}
|
|
std::string champion = stem + std::string(championSuffix) + extension;
|
|
if (!championSuffix.empty() && isFound(champion))
|
|
{
|
|
isChampionSheet = true;
|
|
return champion;
|
|
}
|
|
std::string floor = stem + std::string(floorSuffix) + extension;
|
|
return !floorSuffix.empty() && isFound(floor) ? floor : path;
|
|
}
|
|
|
|
// 006baf40 Reloads its sprite (with isReloadAnm2, from the config or its boss color's .anm2) and swaps each layer's
|
|
// sheet for its champion and floor versions, marking the layers drawn in the floor's dirt color.
|
|
void Entity_NPC::load_graphics(bool isReloadAnm2)
|
|
{
|
|
bool isBossColor = bosscoloridx >= 0 && bosscoloridx < (int)config->bossColors.size();
|
|
if (isReloadAnm2)
|
|
{
|
|
bool isColorAnm2 = isBossColor && !config->bossColors[bosscoloridx].anm2Path.empty();
|
|
sprite.Load(isColorAnm2 ? config->bossColors[bosscoloridx].anm2Path : config->anm2Path, GRAPHICS_DEFER);
|
|
if (g_game->seedEffects.HasSeedEffect(SEED_G_FUEL) && type == ENTITY_ISAAC_BOSS && variant == 1)
|
|
sprite.Load(GFUEL_ISAAC_ANM2, GRAPHICS_LOAD);
|
|
}
|
|
|
|
std::string floorSuffix;
|
|
if (isBossColor) floorSuffix = config->bossColors[bosscoloridx].suffix;
|
|
else if (config->isHasFloorAlts) floorSuffix = g_game->roomConfig.stages[Level::GetStageID()].suffix;
|
|
const ColorMod* championLook = isChampion ? champion_color_get(championColorIdx) : nullptr;
|
|
std::string_view championSuffix = championLook ? CHAMPION_SUFFIX : "";
|
|
bool isChampionSheetUsed = false;
|
|
bool isDirtUsed = false;
|
|
|
|
for (int i = 0; i < (int)sprite.layerStates.size(); i++)
|
|
{
|
|
LayerState& layer = sprite.layerStates[i];
|
|
std::string name = layer.layerData ? layer.layerData->name : "";
|
|
if (name == DIRT_LAYER || name == HOLE_LAYER)
|
|
{
|
|
layer.bitflags |= ANIM_RENDER_UNTINTED;
|
|
isDirtUsed = true;
|
|
}
|
|
if (name == HOLE2_LAYER) layer.bitflags |= ANIM_RENDER_UNTINTED;
|
|
|
|
bool isChampionSheet = false;
|
|
std::string sheet = layer.layerData ? layer.layerData->spriteSheetPath : "";
|
|
sprite.ReplaceSpritesheet(i, sheet_path_resolve(sheet, floorSuffix, championSuffix, isChampionSheet));
|
|
LayerState& replaced = sprite.layerStates[i];
|
|
replaced.bitflags &= ~ANIM_RENDER_COLOROFFSET_CHAMPION;
|
|
if (isChampionSheet) replaced.bitflags |= ANIM_RENDER_COLOROFFSET_CHAMPION;
|
|
isChampionSheetUsed = isChampionSheetUsed || isChampionSheet;
|
|
}
|
|
sprite.championColor = isChampionSheetUsed && championLook ? *championLook : ColorMod{};
|
|
|
|
bool isStatic = type == ENTITY_DOGMA || (type == ENTITY_GENERIC_PROP && variant == PROP_TV);
|
|
sprite.bitflags &= ~ANIM_RENDER_STATIC;
|
|
if (isStatic) sprite.bitflags |= ANIM_RENDER_STATIC;
|
|
sprite.LoadGraphics();
|
|
if (isDirtUsed) UpdateDirtColor(true);
|
|
}
|
|
|
|
// 006c04b0 Lerps its dirt layers toward the floor color under it (Room::GetFloorColorAt doubled), sampled every 15
|
|
// frames unless isImmediate. A green champion's dirt is green.
|
|
void Entity_NPC::UpdateDirtColor(bool isImmediate)
|
|
{
|
|
if (isImmediate || IsFrame(DIRT_SAMPLE_FRAMES, (int)index))
|
|
{
|
|
KColor floor = kcolor_rgba(0, DIRT_GREEN / 2, 0, 1);
|
|
if (!isChampion || championColorIdx != CHAMPION_GREEN) floor = room_floor_color_get(*g_game->room, pos, size);
|
|
dirtColor._tint[0] = floor._red * 2;
|
|
dirtColor._tint[1] = floor._green * 2;
|
|
dirtColor._tint[2] = floor._blue * 2;
|
|
dirtColor._tint[3] = 1;
|
|
}
|
|
|
|
for (int i = 0; i < (int)sprite.layerStates.size(); i++)
|
|
{
|
|
LayerState& layer = sprite.layerStates[i];
|
|
std::string name = layer.layerData ? layer.layerData->name : "";
|
|
if (name == DIRT_LAYER || name == HOLE_LAYER)
|
|
layer.color = color_lerp(layer.color, dirtColor, isImmediate ? 1 : DIRT_LERP);
|
|
}
|
|
}
|
|
|
|
// 006d0300 Switches to another of its boss colors, reloading its sprite on its default animation's first frame.
|
|
void Entity_NPC::SetBossColorIdx(int bossColorIdx, int)
|
|
{
|
|
if (bosscoloridx != bossColorIdx)
|
|
{
|
|
bosscoloridx = bossColorIdx;
|
|
load_graphics(true);
|
|
if (sprite.SetAnimation(sprite.GetDefaultAnimationName(), SWITCH_KEEP_FRAME) && sprite.animState.animData)
|
|
{
|
|
sprite.animState.SetFrameFloat(0);
|
|
sprite.animState.isPlaying = false;
|
|
}
|
|
}
|
|
ResetColor();
|
|
}
|
|
|
|
constexpr ColorMod FRIENDLY_COLOR = {{0.8f, 0.8f, 0.8f, 1}, {1, 1, 1, -0.5f}, {0.1f, 0.1f, 0.1f}};
|
|
constexpr ColorMod FROZEN_COLOR = {{0.8f, 0.8f, 0.8f, 1}, {1, 1, 1, 0.5f}, {0.3f, 0.5f, 0.8f}};
|
|
|
|
// An iced enemy's frozen statue: its weight, health and grid collision points, the cold flash it appears with, the
|
|
// mist it trails when shoved (and the creep it leaves now and then), the wall margin it breaks at, and its ten shards.
|
|
constexpr float STATUE_HEALTH = 10;
|
|
constexpr int STATUE_GRID_POINTS = 8;
|
|
constexpr ColorMod STATUE_FLASH = {{0.8f, 0.8f, 0.8f, 1}, {1, 1, 1, 0.5f}, {0.8f, 1, 1.2f}};
|
|
constexpr int STATUE_FLASH_FRAMES = 6;
|
|
constexpr float STATUE_TRAIL_SCALE_MIN = 0.2f;
|
|
constexpr float STATUE_MIST_DRAG = 0.14f;
|
|
constexpr float STATUE_MIST_SPIN_MIN = 2;
|
|
constexpr float STATUE_MIST_SPIN_RANGE = 10;
|
|
constexpr uint32_t STATUE_MIST_FRAMES = 15;
|
|
constexpr ColorMod STATUE_MIST_COLOR = {{1, 1, 1, 0.4f}, {0, 0, 0, 0}, {0.8f, 0.9f, 1}};
|
|
constexpr float STATUE_WALL_MARGIN = 4;
|
|
constexpr int STATUE_SHARDS = 10;
|
|
constexpr float STATUE_SHARD_SPEED = 16;
|
|
constexpr float STATUE_SHARD_DAMAGE = 7;
|
|
constexpr float STATUE_SHARD_FALL = 0.2f;
|
|
|
|
// The enemy a "random enemy" spawn (type 306) turns into on each stage, on Normal and on Hard.
|
|
struct StageEnemy
|
|
{
|
|
int normalType;
|
|
int normalVariant;
|
|
int hardType;
|
|
int hardVariant;
|
|
};
|
|
|
|
constexpr int REDIRECT_RANDOM_ENEMY = 306;
|
|
constexpr std::array<StageEnemy, 18> STAGE_RANDOM_ENEMIES = {{
|
|
{85, 0, 94, 0},
|
|
{10, 0, 284, 0},
|
|
{85, 0, 94, 0},
|
|
{10, 0, 284, 0},
|
|
{21, 0, 23, 0},
|
|
{26, 0, 26, 1},
|
|
{23, 0, 23, 1},
|
|
{209, 0, 227, 0},
|
|
{227, 0, 24, 1},
|
|
{24, 0, 277, 0},
|
|
{15, 0, 58, 0},
|
|
{58, 0, 39, 0},
|
|
{39, 0, 39, 1},
|
|
{297, 0, 297, 0},
|
|
{87, 0, 252, 0},
|
|
{26, 2, 55, 2},
|
|
{48, 1, 50, 1},
|
|
{267, 0, 410, 0},
|
|
}};
|
|
constexpr std::array<StageEnemy, 6> GREED_RANDOM_ENEMIES = {{
|
|
{10, 0, 284, 0},
|
|
{21, 0, 23, 0},
|
|
{209, 0, 227, 0},
|
|
{15, 0, 58, 0},
|
|
{87, 0, 252, 0},
|
|
{50, 0, 50, 1},
|
|
}};
|
|
constexpr int GREED_RANDOM_ENEMY_DEFAULT = 299;
|
|
constexpr int STAGE_RANDOM_ENEMY_BLUE_WOMB = 26;
|
|
constexpr StageEnemy BLUE_WOMB_RANDOM_ENEMY = {412, 0, 412, 0};
|
|
|
|
// Normal or Greed (the easy ones) against Hard or Greedier.
|
|
static bool is_easy_difficulty()
|
|
{
|
|
return g_game->difficulty == DIFFICULTY_NORMAL || g_game->difficulty == DIFFICULTY_GREED;
|
|
}
|
|
|
|
// 006c07e0 Swaps an enemy about to spawn for what it stands for: Bulbs (61.5) for flies until they are unlocked, the
|
|
// placeholder types (299 to 306) for their difficulty's or stage's enemy until the redirects are unlocked, and with
|
|
// G-Fuel a few enemies for their variants. True when it picked a placeholder's enemy.
|
|
bool Entity_NPC::Redirect(int* entityType, int* entityVariant)
|
|
{
|
|
PersistentGameData& data = g_manager->persistentGameData;
|
|
if (!data.Unlocked(ACHIEVEMENT_MORE_BOSS_COLORS) && *entityType == ENTITY_SUCKER &&
|
|
*entityVariant == SUCKER_VARIANT_BULB)
|
|
{
|
|
*entityType = ENTITY_FLY;
|
|
*entityVariant = 0;
|
|
}
|
|
|
|
bool isEasy = is_easy_difficulty();
|
|
auto redirect = [&](int newType, int newVariant) {
|
|
*entityType = newType;
|
|
*entityVariant = newVariant;
|
|
return true;
|
|
};
|
|
auto byDifficulty = [&](const StageEnemy& enemy) {
|
|
return isEasy ? redirect(enemy.normalType, enemy.normalVariant) : redirect(enemy.hardType, enemy.hardVariant);
|
|
};
|
|
|
|
if (!data.Unlocked(ACHIEVEMENT_REDIRECTS))
|
|
{
|
|
switch (*entityType)
|
|
{
|
|
case 303:
|
|
return isEasy ? redirect(29, 1) : redirect(250, 0);
|
|
case 300:
|
|
return redirect(27, 0);
|
|
case 305:
|
|
return redirect(29, 0);
|
|
case 231:
|
|
*entityVariant = 0;
|
|
return true;
|
|
case 301:
|
|
return redirect(32, 0);
|
|
case 302:
|
|
return redirect(isEasy ? 208 : 257, 0);
|
|
case 304:
|
|
return redirect(isEasy ? 240 : 242, 0);
|
|
case REDIRECT_RANDOM_ENEMY:
|
|
if (g_game->IsGreedMode())
|
|
{
|
|
int stage = (int)g_game->stage;
|
|
bool isListed = stage >= 1 && stage <= (int)GREED_RANDOM_ENEMIES.size();
|
|
return isListed ? byDifficulty(GREED_RANDOM_ENEMIES[stage - 1])
|
|
: redirect(GREED_RANDOM_ENEMY_DEFAULT, 0);
|
|
}
|
|
{
|
|
int stage = g_game->room->GetRoomConfigStage();
|
|
if (stage == STAGE_RANDOM_ENEMY_BLUE_WOMB) return byDifficulty(BLUE_WOMB_RANDOM_ENEMY);
|
|
if (stage >= 0 && stage < (int)STAGE_RANDOM_ENEMIES.size())
|
|
return byDifficulty(STAGE_RANDOM_ENEMIES[stage]);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (!g_game->seedEffects.HasSeedEffect(SEED_G_FUEL)) return false;
|
|
switch (*entityType)
|
|
{
|
|
case 27:
|
|
*entityVariant = 1;
|
|
break;
|
|
case 204:
|
|
*entityType = 247;
|
|
break;
|
|
case 859:
|
|
*entityType = 25;
|
|
*entityVariant = 1;
|
|
break;
|
|
case 221:
|
|
*entityType = 58;
|
|
break;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// 006c0f30 Turns it into another entity in place: its config and color reloaded, its health refilled, its champion
|
|
// kept only where the new one can be one. An enemy the run erased leaves in a poof.
|
|
void Entity_NPC::Morph(int entityType, int entityVariant, int entitySubType, int championId)
|
|
{
|
|
bool isSame = entityType == type && entityVariant == variant && entitySubType == subtype &&
|
|
(championId < 0 || championId == championColorIdx);
|
|
if (isSame) return;
|
|
|
|
type = entityType;
|
|
variant = entityVariant;
|
|
subtype = entitySubType;
|
|
if (championId >= 0)
|
|
{
|
|
championColorIdx = championId;
|
|
isChampion = true;
|
|
}
|
|
EntityConfig_Entity* found = g_manager->entityConfig.GetEntity(entityType, entityVariant, entitySubType);
|
|
if (found && !found->isCanBeChampion)
|
|
{
|
|
championColorIdx = CHAMPION_NONE;
|
|
isChampion = false;
|
|
}
|
|
|
|
flickerTimer = 0;
|
|
championRegenTimer = 0;
|
|
flickerState = 0;
|
|
flickerAlpha = 1;
|
|
championSpeed = 1;
|
|
championTimer = 0;
|
|
ResetColor();
|
|
scale = 1;
|
|
sprite.scale = vector_make(shrinkStatus1, shrinkStatus1);
|
|
LoadEntityConfig();
|
|
totalDamageTaken = 0;
|
|
health = hitPointsMulti * maxHitPoints;
|
|
if (!colorParams.empty()) SetColor(COLOR_DEFAULT, 1, MORPH_COLOR_PRIORITY, false, true);
|
|
pathfinder.Reset();
|
|
g_manager->persistentGameData.TryAddBestiaryEncounter(type, variant);
|
|
isBestiaryEncountered = true;
|
|
if (entity_is_erased(*this)) Entity::RemoveWithPoof(this);
|
|
}
|
|
|
|
// 006c4ac0 Remembers where it was, and keeps the Exorcist's room in its state while it lives.
|
|
void Entity_NPC::PreUpdate()
|
|
{
|
|
prevPosition = pos;
|
|
prevVelocity = velocity;
|
|
if (type == ENTITY_EXORCIST && variant == 0 && !isDead) g_game->room->isExorcistActive = true;
|
|
}
|
|
|
|
// 006b8f00 Removes it, and the Dark Esau with it if it is the one that holds him.
|
|
void Entity_NPC::Remove()
|
|
{
|
|
if (type == ENTITY_DARK_ESAU && variant == 0 && child) child->Remove();
|
|
Entity::Remove();
|
|
}
|
|
|
|
// 006b8450 Whether it holds the doors shut: one that can, unless it became friendly.
|
|
bool Entity_NPC::CanShutDoors()
|
|
{
|
|
return isCanShutDoors && !IsFriendly();
|
|
}
|
|
|
|
// 006b8470
|
|
bool Entity_NPC::IsBoss()
|
|
{
|
|
return isBoss;
|
|
}
|
|
|
|
// 006a8240 Forgets where its pathfinder was taking it.
|
|
void Entity_NPC::ResetPathFinderTarget()
|
|
{
|
|
pathfinder.movementTarget = {};
|
|
pathfinder.moveDirection = {};
|
|
}
|
|
|
|
// 006d6610 Scales it, shrinking included.
|
|
void Entity_NPC::SetScale(float newScale)
|
|
{
|
|
scale = newScale;
|
|
sprite.scale = vector_make(newScale * shrinkStatus1, newScale * shrinkStatus1);
|
|
}
|
|
|
|
// 006b9910 Sends it after a target for a time, unless forced targets are on cooldown or the one it has is nearer.
|
|
bool Entity_NPC::TryForceTarget(Entity* newTarget, int duration)
|
|
{
|
|
if (forcedTargetTimer < 0) return false;
|
|
|
|
Entity* current = forcedTarget;
|
|
bool isKept = current == newTarget;
|
|
if (!isKept && current)
|
|
{
|
|
float currentDistance = vector_length_squared(vector_sub(pos, current->pos));
|
|
if (currentDistance <= vector_length_squared(vector_sub(pos, newTarget->pos))) return false;
|
|
}
|
|
if (!isKept) forcedTarget = newTarget;
|
|
forcedTargetTimer = duration;
|
|
return true;
|
|
}
|
|
|
|
// 006d6ba0 Plays a sound, higher for a tiny champion and lower for a giant one.
|
|
void Entity_NPC::PlaySound(int id, float volume, int frameDelay, bool isLoop, float pitch)
|
|
{
|
|
if (championColorIdx == CHAMPION_TINY) pitch += 0.5f;
|
|
else if (championColorIdx == CHAMPION_GIANT) pitch *= 0.5f;
|
|
seed_fart_sound_override(&id);
|
|
g_manager->sfxManager.Play(
|
|
id, {.volume = volume, .frameDelay = frameDelay, .loop = isLoop ? SOUND_LOOP : SOUND_ONCE, .pitch = pitch});
|
|
}
|
|
|
|
// 006b64d0 Leaves a blood splat of a size where it stands.
|
|
Entity_Effect* Entity_NPC::MakeSplat(float size)
|
|
{
|
|
Entity* splat = spawn_at(ENTITY_EFFECT, EFFECT_BLOOD_SPLAT, 0, pos, this);
|
|
splat->sprite.scale = vector_make(size, size);
|
|
splat->Update();
|
|
return static_cast<Entity_Effect*>(splat);
|
|
}
|
|
|
|
// 006d6c20 The enemies its side still faces: the room's living enemies, or for a friendly one the friendly enemies.
|
|
int Entity_NPC::GetAliveEnemyCount()
|
|
{
|
|
if (!IsFriendly()) return g_game->room->GetAliveEnemiesCount();
|
|
|
|
int count = 0;
|
|
for (Entity* entity : g_game->room->entityList.mainEL)
|
|
if (Entity::is_enemy_type(entity->type) && !entity->isDead && entity->IsFriendly()) count++;
|
|
return count;
|
|
}
|
|
|
|
// 006d48a0 The way it faces: the forward vector an AI set, else down for a few, else along its motion.
|
|
Vector Entity_NPC::GetForwardVector()
|
|
{
|
|
if (!vector_is_zero(forwardVector)) return forwardVector;
|
|
if (type == ENTITY_FORWARD_NONE) return {};
|
|
if (type == ENTITY_FORWARD_DOWN_A || type == ENTITY_FORWARD_DOWN_B) return vector_make(0, 1);
|
|
return Entity::GetForwardVector();
|
|
}
|
|
|
|
// Part of 006c4b30: shows the status effect it suffers on its OverlayEffect null, most important first. The
|
|
// shadow champion charger is never charmed, and Crown and Skull mark the king and death champions.
|
|
void Entity_NPC::status_overlay_update()
|
|
{
|
|
bool isShadowCharger = type == ENTITY_SHADOW_CHARGER && variant == 0 && subtype == SHADOW_CHARGER_SUBTYPE;
|
|
TemporaryEffects& roomEffects = g_game->room->temporaryEffects;
|
|
bool isTimeSlowed = roomEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH_ID) ||
|
|
roomEffects.HasCollectibleEffect(COLLECTIBLE_HOURGLASS_ID) ||
|
|
(g_game->challenge != CHALLENGE_SPEED && g_game->room->brokenWatchState == BROKEN_WATCH_SLOW);
|
|
bool isTimeImmune = (flags & (FLAG_FRIENDLY | FLAG_NO_STATUS_EFFECTS)) && type != ENTITY_DEATHS_HEAD;
|
|
|
|
std::string_view animation;
|
|
bool isShared = false;
|
|
if (championColorIdx == CHAMPION_KING) animation = "Crown";
|
|
else if (championColorIdx == CHAMPION_DEATH) animation = "Skull";
|
|
isShared = !animation.empty();
|
|
|
|
if (HasEntityFlags(FLAG_CHARM) && !isShadowCharger) animation = "Charm", isShared = true;
|
|
else if (HasEntityFlags(FLAG_BRIMSTONE_MARKED)) animation = "BrimstoneCurse", isShared = true;
|
|
else if (HasEntityFlags(FLAG_MAGNETIZED)) animation = "Magnetize", isShared = true;
|
|
else if (HasEntityFlags(FLAG_BAITED)) animation = "Bait", isShared = false;
|
|
else if (HasEntityFlags(FLAG_CONFUSION)) animation = "Confuse", isShared = true;
|
|
else if (HasEntityFlags(FLAG_BURN)) animation = "Burning", isShared = false;
|
|
else if (HasEntityFlags(FLAG_POISON)) animation = "Poison", isShared = true;
|
|
else if (HasEntityFlags(FLAG_FEAR)) animation = "Fear", isShared = true;
|
|
else if (HasEntityFlags(FLAG_BLEED_OUT)) animation = "BleedingOut", isShared = true;
|
|
else if (HasEntityFlags(FLAG_SLOW) || (isTimeSlowed && !isTimeImmune)) animation = "Slow", isShared = true;
|
|
else if (HasEntityFlags(FLAG_WEAKNESS)) animation = "Weakness", isShared = true;
|
|
else if (type == ENTITY_SIREN_HELPER) animation = "EnemyCharm", isShared = true;
|
|
else if (animation.empty())
|
|
{
|
|
if (statusEffectSprite.animState.animData) statusEffectSprite.animState.isPlaying = false;
|
|
return;
|
|
}
|
|
|
|
if (!statusEffectSprite.isLoaded) statusEffectSprite.Load(STATUS_EFFECTS_ANM2, GRAPHICS_LOAD);
|
|
if (statusEffectSprite.IsPlaying() && statusEffectSprite.isLoaded)
|
|
{
|
|
statusEffectSprite.animState.Update(statusEffectSprite.playbackSpeed);
|
|
statusEffectSprite.overlayAnimState.Update(statusEffectSprite.playbackSpeed);
|
|
}
|
|
statusEffectSprite.Play(animation);
|
|
statusEffectSprite.bitflags = isShared ? STATUS_SHARED : 0;
|
|
}
|
|
|
|
// Part of 006c4b30: stopped by a pause or held (Lil Abaddon, a hook), it stays put and slows, its AI's pre-update
|
|
// call and the base update still run (without its sprite), and it goes on with the update only if that killed it.
|
|
// False when the update stops here.
|
|
bool Entity_NPC::paused_update()
|
|
{
|
|
if (vector_is_zero(pausePosition)) pausePosition = pos;
|
|
if (pauseTimer > 0 && --pauseTimer > 0) pos = pausePosition;
|
|
velocity = vector_scale(velocity, PAUSE_SLOWDOWN);
|
|
|
|
bool wasDead = isDead;
|
|
spawn_damage_numbers();
|
|
update_damage_history();
|
|
if (aiCallFlags & AI_CALL_PRE_UPDATE) ai_call(AI_PHASE_PRE_UPDATE);
|
|
|
|
float healthBefore = health;
|
|
bool isSpriteFrozen = HasEntityFlags(FLAG_NO_SPRITE_UPDATE);
|
|
AddEntityFlags(FLAG_NO_SPRITE_UPDATE);
|
|
Entity::Update();
|
|
if (!isSpriteFrozen) ClearEntityFlags(FLAG_NO_SPRITE_UPDATE);
|
|
totalDamageTaken += std::max(healthBefore - health, 0.0f);
|
|
return wasDead != isDead;
|
|
}
|
|
|
|
// Runs the AI in a phase other than the update's own.
|
|
void Entity_NPC::ai_call(AiPhase phase)
|
|
{
|
|
aiCallPhase = phase;
|
|
npc_ai_update(*this);
|
|
aiCallPhase = AI_PHASE_UPDATE;
|
|
}
|
|
|
|
// Part of 006c4b30: the first appear frame runs the AI's init (a champion's or Tick's changes with it), the second
|
|
// poofs it in, the fourth shows it playing Appear, and once that ends (20 frames at least) its AI takes over.
|
|
void Entity_NPC::appear_update()
|
|
{
|
|
if (appearFrames == 0) appear_init();
|
|
else if (appearFrames == APPEAR_POOF_FRAME)
|
|
{
|
|
Entity* poof = spawn_at(ENTITY_EFFECT, EFFECT_POOF01, poof_size_get(*this, false), pos, this);
|
|
poof->posOffset = posOffset;
|
|
poof->renderDepthOffset = posOffset.y + 1;
|
|
if (isChampion && championColorIdx < CHAMPION_COUNT)
|
|
poof->SetColor(champion_sprite_color_get(championColorIdx), -1, COLOR_PRIORITY_DEFAULT, false, true);
|
|
|
|
int sound = isDeathSoundAlt ? SOUND_SUMMON_WAVE : SOUND_SUMMON_POOF;
|
|
g_manager->sfxManager.Stop(sound);
|
|
PlaySound(sound, 1, 2, false, 1);
|
|
if (type == ENTITY_STAIN)
|
|
{
|
|
npc_sound_play(SOUND_MAGGOT_BURST_OUT, 1, 2, 1);
|
|
PlaySound(SOUND_THE_STAIN_BURST, 1, 2, false, 1);
|
|
}
|
|
else if (type == ENTITY_FORSAKEN) PlaySound(SOUND_FORSAKEN_LAUGH, 1, 2, false, 1);
|
|
else if (type == ENTITY_BIG_HORN && variant == 0) PlaySound(SOUND_BOSS_LITE_ROAR, BIG_HORN_APPEAR_VOLUME, 2, false, 1);
|
|
}
|
|
else if (appearFrames == APPEAR_SHOW_FRAME)
|
|
{
|
|
if (type != ENTITY_PIN) isVisible = true;
|
|
if (sprite.GetAnimationData("Appear"))
|
|
{
|
|
if (type != APPEAR_OVERLAY_KEPT_TYPE) sprite.RemoveOverlay();
|
|
sprite.Play("Appear", PLAY_FORCED);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
bool isAppearing =
|
|
sprite.GetAnimationData("Appear") && !sprite.IsFinished("Appear") && sprite.GetAnimation() == "Appear";
|
|
if (appearFrames >= APPEAR_MIN_FRAMES && !isAppearing)
|
|
{
|
|
state = savedState;
|
|
friction = baseFriction;
|
|
}
|
|
}
|
|
|
|
if (std::ranges::find(APPEAR_EVENT_TYPES, type) != APPEAR_EVENT_TYPES.end())
|
|
boss_appear_events(*this);
|
|
if (state == NPC_STATE_APPEAR) friction *= APPEAR_FRICTION;
|
|
appearFrames++;
|
|
}
|
|
|
|
// Part of 006c4b30: the AI's init call on the first appear frame, with what spawning does to it.
|
|
void Entity_NPC::appear_init()
|
|
{
|
|
state = NPC_STATE_INIT;
|
|
if (championColorIdx == CHAMPION_WHITE)
|
|
{
|
|
isInvincible = true;
|
|
AddEntityFlags(FLAG_NO_STATUS_EFFECTS);
|
|
}
|
|
npc_ai_update(*this);
|
|
if (championColorIdx == CHAMPION_FLY_PROTECTED || championColorIdx == CHAMPION_RAINBOW)
|
|
spawn_at(ENTITY_ETERNALFLY, 0, 0, pos, this)->parent = this;
|
|
if (HasEntityFlags(FLAG_APPEAR))
|
|
{
|
|
isVisible = false;
|
|
savedState = state;
|
|
state = NPC_STATE_APPEAR;
|
|
}
|
|
|
|
PlayerManager& players = g_game->playerManager;
|
|
if (players.AnyoneHasTrinket(TRINKET_TICK_ID) && type != TYPE_NO_TICK_A && type != TYPE_NO_TICK_B &&
|
|
health > TICK_HEALTH_MIN)
|
|
for (int i = 0; i < players.GetTrinketMultiplier(TRINKET_TICK_ID); i++) health *= TICK_HEALTH_SCALE;
|
|
|
|
auto isDirt = [](const LayerState& layer) {
|
|
return layer.layerData && (layer.layerData->name == DIRT_LAYER || layer.layerData->name == HOLE_LAYER);
|
|
};
|
|
if (std::ranges::any_of(sprite.layerStates, isDirt)) UpdateDirtColor(true);
|
|
if (IsBoss() && !parent) game_encountered_boss_add(type, variant);
|
|
}
|
|
|
|
// Rag Man keeps its head through its death only if the head shows on the frame it died on.
|
|
static void death_head_layer_keep(ANM2& sprite)
|
|
{
|
|
LayerState* head = sprite.GetLayer("Head");
|
|
if (!head) return;
|
|
const AnimationFrame* frame = sprite.animState.GetLayerFrame(head->layerData ? head->layerData->id : -1);
|
|
head->isVisible = frame && frame->isVisible;
|
|
}
|
|
|
|
// Part of 006c4b30: what the bosses with death events do as they die: Isaac's cry, Baby Plum's spit and last ring,
|
|
// Reap Creep losing its overlay, Singe's blast, Mother's slam, Clutch's explosions and Gideon's own.
|
|
static void death_events_update(Entity_NPC& npc)
|
|
{
|
|
switch (npc.type)
|
|
{
|
|
case ENTITY_ISAAC:
|
|
if (npc.variant != ISAAC_FORM_HUSH && npc.stateFrame == ISAAC_DEATH_CRY_FRAME)
|
|
npc.PlaySound(SOUND_SUPERHOLY, ISAAC_DEATH_CRY_VOLUME, 2, false, 1);
|
|
return;
|
|
case ENTITY_BABY_PLUM:
|
|
{
|
|
if (npc.sprite.IsEventTriggered("Shoot")) npc_sound_play(SOUND_MEAT_JUMPS, 1, 2, 1);
|
|
if (!npc.sprite.IsFinished() || !npc.isDead) return;
|
|
ProjectileParams params;
|
|
params.fallingAccelModifier -= PLUM_RING_FALL;
|
|
return npc.FireProjectiles(npc.pos, vector_make(PLUM_RING_SPEED, PLUM_RING_SHOTS), PROJECTILES_RING, params);
|
|
}
|
|
case ENTITY_GIDEON:
|
|
return gideon_death_update(npc);
|
|
case ENTITY_REAP_CREEP:
|
|
if (npc.sprite.overlayAnimState.animData) npc.sprite.RemoveOverlay();
|
|
return;
|
|
case ENTITY_SINGE:
|
|
if (npc.sprite.IsFinished() && npc.isDead)
|
|
explosion_effects({.position = npc.pos, .source = &npc, .damage = SINGE_BLAST_DAMAGE,
|
|
.radiusMultiplier = SINGE_BLAST_REACH});
|
|
return;
|
|
case ENTITY_MIN_MIN:
|
|
return min_min_death_update(npc);
|
|
case ENTITY_MOTHER:
|
|
if (npc.variant != MOTHER_SLAM_VARIANT || !npc.sprite.IsEventTriggered("Shoot")) return;
|
|
game_shake_screen(MOTHER_SLAM_SHAKE);
|
|
return npc.PlaySound(SOUND_DEATH_REVERSE, 1, 2, false, MOTHER_SLAM_PITCH);
|
|
case ENTITY_CLUTCH:
|
|
{
|
|
if (!npc.sprite.IsEventTriggered("Explosion")) return;
|
|
Entity* blast = spawn_at(ENTITY_EFFECT, EFFECT_ENEMY_GHOST, CLUTCH_BLAST_SUBTYPE, npc.pos, nullptr);
|
|
blast->posOffset = vector_make(0, CLUTCH_BLAST_RAISE);
|
|
blast->sprite.rotation = random_unit() * CLUTCH_BLAST_SPIN;
|
|
blast->sprite.scale = vector_make(CLUTCH_BLAST_SCALE, CLUTCH_BLAST_SCALE);
|
|
blast->SetCollisionDamage(CLUTCH_BLAST_DAMAGE);
|
|
blast->Update();
|
|
npc_sound_play(SOUND_DEMON_HIT, CLUTCH_BLAST_VOLUME, 2, random_unit() * CLUTCH_PITCH_SPREAD + CLUTCH_PITCH);
|
|
return game_shake_screen(CLUTCH_BLAST_SHAKE);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Part of 006c4b30: a boss or Chub dying through its death animations, which ends it (trigger_kill_item_effects).
|
|
void Entity_NPC::death_animation_update()
|
|
{
|
|
if (state != NPC_STATE_DEATH && state != NPC_STATE_UNIQUE_DEATH) return;
|
|
|
|
friction *= APPEAR_FRICTION;
|
|
if (stateFrame == 0) death_animation_start();
|
|
stateFrame++;
|
|
death_events_update(*this);
|
|
|
|
if (const NullFrame* bloodGuide = sprite.GetNullFrame("BloodGuide")) npc_blood_guide_update(*this, *bloodGuide);
|
|
if (type == ENTITY_HUSH && sprite.IsEventTriggered("ash") && !HasEntityFlags(FLAG_DELIRIUM_FORM))
|
|
{
|
|
if (Entity* ashes = spawn_at(ENTITY_EFFECT, EFFECT_HUSH_ASHES, 0, pos, this)) ashes->Update();
|
|
game_shake_screen(HUSH_ASH_SHAKE);
|
|
npc_sound_play(SOUND_SUPERHOLY, 1, 2, 1);
|
|
}
|
|
if (sprite.IsFinished() && isExists) trigger_kill_item_effects();
|
|
}
|
|
|
|
// Part of 006c4b30: the first frame of the death states: a flushed boss plays Flush, the rest Death, or bursts
|
|
// where it has none.
|
|
void Entity_NPC::death_animation_start()
|
|
{
|
|
bool isFlushable = std::ranges::find(FLUSH_TYPES, type) != FLUSH_TYPES.end() ||
|
|
(type == FLUSH_PROP_TYPE && variant == FLUSH_PROP_VARIANT);
|
|
if (state == NPC_STATE_UNIQUE_DEATH)
|
|
{
|
|
if (!isFlushable) return;
|
|
if (sprite.GetAnimationData("Flush"))
|
|
{
|
|
sprite.Play("Flush");
|
|
renderZOffset = FLUSH_RENDER_Z;
|
|
return;
|
|
}
|
|
state = NPC_STATE_DEATH;
|
|
}
|
|
|
|
if (sprite.GetAnimationData("Death"))
|
|
{
|
|
if (type == ENTITY_BIG_HORN) return big_horn_death_play(*this);
|
|
if (type == ENTITY_RAG_MAN) death_head_layer_keep(sprite);
|
|
sprite.Play("Death");
|
|
return;
|
|
}
|
|
if (type == ENTITY_CHUB || type == ENTITY_LARRYJR || type == ENTITY_PIN || type == ENTITY_TURDLET)
|
|
return segment_death_animation_play(*this);
|
|
if (type >= DEATH_NO_BURST_FIRST && type <= DEATH_NO_BURST_LAST) return;
|
|
BloodExplode();
|
|
trigger_kill_item_effects();
|
|
}
|
|
|
|
// Part of 006c4b30: a charmed enemy's attention drifts to a Punching Bag it targets for up to 180 frames, then away
|
|
// for as long, before the bag can draw it again.
|
|
void Entity_NPC::decoy_update()
|
|
{
|
|
if (decoyTargetTimer > DECOY_TIMER_MAX) decoyTargetTimer = -1;
|
|
else if (decoyTargetTimer < -DECOY_TIMER_MAX) decoyTargetTimer = 0;
|
|
|
|
Entity* playerTarget = GetPlayerTarget();
|
|
if (playerTarget->type == ENTITY_FAMILIAR && playerTarget->variant == Entity_Familiar::PUNCHING_BAG) decoyTargetTimer++;
|
|
else if (decoyTargetTimer != 0) decoyTargetTimer--;
|
|
}
|
|
|
|
// Part of 006c4b30: in a room that checks it, an enemy no grounded player has a path to stops holding the doors
|
|
// after its second miss, checked every 60 frames once 900 frames passed.
|
|
void Entity_NPC::unreachable_update()
|
|
{
|
|
Room& room = *g_game->room;
|
|
if (!room.isUnknown11f5) return;
|
|
|
|
bool isGrounded = !isDead && !isBoss && !IsFlying() && entityGridCollisionClass != GRIDCOLL_NOPITS &&
|
|
type != ENTITY_UNREACHABLE_EXEMPT;
|
|
int frames = room.GetFrameCount();
|
|
if ((uint32_t)(frames + (int)index) % UNREACHABLE_CHECK_FRAMES != 0 || frames <= UNREACHABLE_GRACE_FRAMES ||
|
|
!isGrounded)
|
|
return;
|
|
if (room.roomType != ROOM_DEFAULT || room.IsClear() || any_player_flying()) return;
|
|
|
|
for (Entity_Player* player : g_game->playerManager.playerList)
|
|
if (!player->IsFlying() && pathfinder.HasPathToPos(player->pos, true)) return;
|
|
if (!isUnreachableOnce) isUnreachableOnce = true;
|
|
else isCanShutDoors = false;
|
|
}
|
|
|
|
// 009be9c0 Whether a living player moves over pits (its grid collision ignores them).
|
|
bool any_player_flying()
|
|
{
|
|
for (Entity_Player* player : g_game->playerManager.playerList)
|
|
if (!player->isCoopGhost && player->entityGridCollisionClass <= GRIDCOLL_WALLS) return true;
|
|
return false;
|
|
}
|
|
|
|
// Part of 006c4b30: the frame it dies: its burst, Midas' coins, its death triggers (rewards and the players' on-kill
|
|
// items), Toxic Shock's creep, then its removal, or a boss's death animation. In a crawlspace it drops off a ladder.
|
|
void Entity_NPC::dead_update()
|
|
{
|
|
PlayDeathEffects();
|
|
if (HasEntityFlags(FLAG_MIDAS_FREEZE) && !HasEntityFlags(FLAG_NO_REWARD)) midas_coins_spawn();
|
|
if (!HasEntityFlags(FLAG_NO_DEATH_TRIGGER))
|
|
{
|
|
trigger_death_rewards();
|
|
for (Entity_Player* player : g_game->playerManager.playerList) player->trigger_npc_death(this);
|
|
}
|
|
toxic_shock_creep_spawn();
|
|
if (!isBoss && type != ENTITY_CHUB) trigger_kill_item_effects();
|
|
else
|
|
{
|
|
state = NPC_STATE_DEATH;
|
|
stateFrame = 0;
|
|
}
|
|
if (g_game->room->roomType == ROOM_DUNGEON && !IsFlying()) ladder_drop();
|
|
}
|
|
|
|
// Part of 006c4b30: an enemy dying on a crawlspace ladder keeps its speed sideways and drops off it, unless a wall
|
|
// is right under it.
|
|
void Entity_NPC::ladder_drop()
|
|
{
|
|
GridEntity* cell = room_grid_entity_at(pos);
|
|
if (!cell || cell->type != GRID_GRAVITY) return;
|
|
|
|
velocity.y *= HALF_SPEED;
|
|
if (velocity.x > 0) velocity.x = vector_length(velocity);
|
|
else if (velocity.x < 0) velocity.x = -vector_length(velocity);
|
|
velocity.y = 0;
|
|
Vector below = vector_add(pos, vector_make(0, sizeMulti.y * size + LADDER_FOOT_MARGIN));
|
|
if (room_grid_collision_at(below) != COLLISION_WALL) AddVelocity_divided(vector_make(0, LADDER_DROP_SPEED), false);
|
|
}
|
|
|
|
// Part of 006c4b30: a gold enemy's coins, one to three (none to two for a coin hearted player).
|
|
void Entity_NPC::midas_coins_spawn()
|
|
{
|
|
Entity_Player* player = game_nearest_player(pos);
|
|
int coins = player && player->GetHealthType() == HEALTH_COIN ? random_below(3) : random_below(3) + 1;
|
|
for (int i = 0; i < coins; i++)
|
|
{
|
|
uint32_t seed = Random();
|
|
Vector speed = vector_scale(random_direction(), random_unit() * MIDAS_COIN_SPEED);
|
|
g_game->Spawn({.position = pos,
|
|
.velocity = speed,
|
|
.subType = COIN_PENNY,
|
|
.type = ENTITY_PICKUP,
|
|
.variant = PICKUP_COIN,
|
|
.seed = seed});
|
|
}
|
|
}
|
|
|
|
// 006d5350 Toxic Shock leaves its green creep where the enemy died, sized to it.
|
|
void Entity_NPC::toxic_shock_creep_spawn()
|
|
{
|
|
Entity_Player* owner = g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_TOXIC_SHOCK_ID, LAZARUS_SHARE_CHECK);
|
|
if (!owner) return;
|
|
|
|
Entity* creep = spawn_at(ENTITY_EFFECT, EFFECT_PLAYER_CREEP_GREEN, 0, pos, owner);
|
|
float creepScale = size * TOXIC_CREEP_SCALE;
|
|
creep->sprite.scale = vector_make(creepScale, creepScale);
|
|
creep->Update();
|
|
}
|
|
|
|
// Part of 006c4b30: the items whose aura works on enemies near a player, each from its nearest holder. The Soul pushes
|
|
// the enemy off within 80 one frame in three. Super Magnet pulls it in one frame in three. Salvation's beam locks
|
|
// onto it within reach of its halo.
|
|
void Entity_NPC::player_aura_update()
|
|
{
|
|
constexpr float SOUL_PUSH_REACH = 80;
|
|
constexpr float SOUL_PUSH_SHARE = 0.1f;
|
|
constexpr float SOUL_SPEED_SHARE = 0.2f;
|
|
constexpr float SOUL_PUSH_BASE = 0.05f;
|
|
constexpr float AURA_REACH_SQUARED = 1e9f;
|
|
constexpr float SUPER_MAGNET_PULL = 0.5f;
|
|
constexpr int AURA_ODDS = 3;
|
|
constexpr float SALVATION_HALO_RADIUS = 70;
|
|
constexpr int SALVATION_BEAM_SUBTYPE = 3;
|
|
constexpr float SALVATION_BEAM_DAMAGE = 3.5f;
|
|
if (state == NPC_STATE_DEATH || state == NPC_STATE_UNIQUE_DEATH || IsFriendly() || !IsVulnerableEnemy(nullptr))
|
|
return;
|
|
|
|
Entity_Player* soul = nullptr;
|
|
Entity_Player* magnet = nullptr;
|
|
Entity_Player* salvation = nullptr;
|
|
float soulDistance = SOUL_PUSH_REACH * SOUL_PUSH_REACH;
|
|
float magnetDistance = AURA_REACH_SQUARED;
|
|
float salvationDistance = AURA_REACH_SQUARED;
|
|
for (Entity_Player* player : g_game->playerManager.playerList)
|
|
{
|
|
bool isSoul = player->HasCollectible(COLLECTIBLE_SOUL_ID);
|
|
bool isMagnet = player->HasTrinket(TRINKET_SUPER_MAGNET_ID);
|
|
bool isSalvation = player->HasCollectible(COLLECTIBLE_SALVATION_ID);
|
|
if (!isSoul && !isMagnet && !isSalvation) continue;
|
|
|
|
float distance = vector_length_squared(vector_sub(player->pos, pos));
|
|
if (isSoul && distance < soulDistance)
|
|
{
|
|
soul = player;
|
|
soulDistance = distance;
|
|
}
|
|
if (isMagnet && distance < magnetDistance)
|
|
{
|
|
magnet = player;
|
|
magnetDistance = distance;
|
|
}
|
|
if (!isSalvation || distance >= salvationDistance) continue;
|
|
float haloReach = player->get_salvation_scale() * SALVATION_HALO_RADIUS + size;
|
|
if (distance >= haloReach * haloReach) continue;
|
|
salvation = player;
|
|
salvationDistance = distance;
|
|
}
|
|
|
|
if (soul && random_below(AURA_ODDS) == 0)
|
|
{
|
|
float push = random_unit() * (SOUL_PUSH_REACH - std::sqrt(soulDistance)) * SOUL_PUSH_SHARE;
|
|
float strength = vector_length(velocity) * push * SOUL_SPEED_SHARE + SOUL_PUSH_BASE;
|
|
velocity = vector_add(velocity, vector_resized(vector_sub(pos, soul->pos), strength));
|
|
}
|
|
if (magnet && random_below(AURA_ODDS) == 0) velocity = vector_add(velocity, vector_resized(vector_sub(magnet->pos, pos), SUPER_MAGNET_PULL));
|
|
if (!salvation) return;
|
|
|
|
if (!salvationTarget)
|
|
{
|
|
Entity* beam = g_game->Spawn({.position = pos,
|
|
.spawner = salvation,
|
|
.subType = SALVATION_BEAM_SUBTYPE,
|
|
.type = ENTITY_EFFECT,
|
|
.variant = EFFECT_CRACK_THE_SKY,
|
|
.seed = Random()});
|
|
beam->target = this;
|
|
beam->parent = salvation;
|
|
beam->SetCollisionDamage(SALVATION_BEAM_DAMAGE);
|
|
beam->Update();
|
|
salvationTarget = beam;
|
|
}
|
|
if (salvationTarget) static_cast<Entity_Effect*>(salvationTarget.get())->state = 1;
|
|
}
|
|
|
|
// Whether Lighter or Ice Cube catches an enemy entering the room: a fifth, a third or a half by strength, more with
|
|
// the owner's luck, rolled on the enemy's seed.
|
|
static bool is_room_trinket_struck(Entity_NPC& npc, Entity_Player& owner, int trinket)
|
|
{
|
|
constexpr float CHANCES[] = {0.2f, 0.33f, 0.5f};
|
|
constexpr float LUCK_CHANCE = 0.02f;
|
|
constexpr uint32_t STATUS_SHIFT_INDEX = 5;
|
|
int multiplier = owner.GetTrinketMultiplier(trinket);
|
|
float chance = CHANCES[multiplier == 2 ? 1 : multiplier == 3 ? 2 : 0];
|
|
RNG rng;
|
|
rng.SetSeed(npc.initSeed, STATUS_SHIFT_INDEX);
|
|
return rng.RandomFloat() < owner.luck * LUCK_CHANCE + chance;
|
|
}
|
|
|
|
// Part of 006c4b30: what the players' items do to enemies each frame: Toxic Shock's poison, Lighter's burn and Ice
|
|
// Cube's freeze on the room's first frame, confusion while its target is invisible, Broken Modem's stalls, Game
|
|
// Kid's fear and the time stopping items' tint.
|
|
void Entity_NPC::item_effects_update()
|
|
{
|
|
PlayerManager& players = g_game->playerManager;
|
|
if (g_game->room->GetFrameCount() == 0 && IsVulnerableEnemy(nullptr))
|
|
{
|
|
if (Entity_Player* owner = players.FirstCollectibleOwner(COLLECTIBLE_TOXIC_SHOCK_ID, LAZARUS_SHARE_IGNORE))
|
|
AddPoison(EntityRef(owner), TOXIC_SHOCK_POISON, 0, false);
|
|
Entity_Player* toxicOwner = players.FirstCollectibleOwner(COLLECTIBLE_TOXIC_SHOCK_ID, LAZARUS_SHARE_IGNORE);
|
|
if (Entity_Player* lighter = players.FirstTrinketOwner(TRINKET_LIGHTER_ID); lighter && is_room_trinket_struck(*this, *lighter, TRINKET_LIGHTER_ID))
|
|
AddBurn(EntityRef(lighter), ROOM_TRINKET_STATUS_FRAMES, 0, false);
|
|
// The original freezes from the Toxic Shock owner's reference, usually none.
|
|
if (Entity_Player* ice = players.FirstTrinketOwner(TRINKET_ICE_CUBE_ID); ice && is_room_trinket_struck(*this, *ice, TRINKET_ICE_CUBE_ID))
|
|
{
|
|
AddFreeze(EntityRef(toxicOwner), ROOM_TRINKET_STATUS_FRAMES, false);
|
|
AddIce(EntityRef(toxicOwner), ROOM_TRINKET_STATUS_FRAMES);
|
|
}
|
|
}
|
|
|
|
Entity_Player* targetPlayer = GetPlayerTarget()->ToPlayer();
|
|
if (targetPlayer && targetPlayer->IsInvisible()) AddConfusion(EntityRef(this), STATUS_REFRESH, false);
|
|
if (players.FirstCollectibleOwner(COLLECTIBLE_BROKEN_MODEM_ID, LAZARUS_SHARE_IGNORE))
|
|
{
|
|
int odds = std::max(MODEM_MIN_ODDS, MODEM_ODDS - (int)players.get_total_luck());
|
|
odds *= IsBoss() ? 3 : 2;
|
|
if (IsVulnerableEnemy(nullptr) && random_below(odds) == 0 && !isDead)
|
|
{
|
|
Entity& head = *GetStatusEffectTarget();
|
|
head.AddEntityFlags(FLAG_FREEZE);
|
|
head.CopyStatusEffects();
|
|
}
|
|
}
|
|
if (IsActiveEnemy(DEAD_EXCLUDED) && HasEntityFlags(FLAG_FREEZE) && freezeCountdown < 1 && IsFrame(MODEM_FRAMES, 0))
|
|
modem_release();
|
|
|
|
if (!HasEntityFlags(FLAG_NO_TARGET) && std::ranges::any_of(players.playerList, [](Entity_Player* player) {
|
|
return player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_GAMEKID_ID);
|
|
}))
|
|
{
|
|
SetColor(GAME_KID_COLOR, 2, 0, false, true);
|
|
AddFear(EntityRef(this), STATUS_REFRESH, false);
|
|
}
|
|
|
|
TemporaryEffects& roomEffects = g_game->room->temporaryEffects;
|
|
bool isTimeSlowed = roomEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH_ID) ||
|
|
roomEffects.HasCollectibleEffect(COLLECTIBLE_HOURGLASS_ID) ||
|
|
g_game->room->GetBrokenWatchState() == BROKEN_WATCH_SLOW;
|
|
bool isTimeImmune = HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_STATUS_EFFECTS) && type != ENTITY_DEATHS_HEAD;
|
|
if (isTimeSlowed && !isTimeImmune) SetColor(SLOWED_TIME_COLOR, 2, SLOWED_TIME_COLOR_PRIORITY, false, true);
|
|
}
|
|
|
|
// Part of 006c4b30: Broken Modem lets a stalled enemy go, and a moving one skips seven units each way at random, kept
|
|
// in the room when it was in it.
|
|
void Entity_NPC::modem_release()
|
|
{
|
|
constexpr float MODEM_SKIP_STEP = 14;
|
|
constexpr float MODEM_SKIP_OFFSET = 21;
|
|
Entity& head = *GetStatusEffectTarget();
|
|
head.ClearEntityFlags(FLAG_FREEZE);
|
|
head.CopyStatusEffects();
|
|
if (vector_is_zero(velocity)) return;
|
|
|
|
float skipX = (float)(Random() % 2 + 1) * MODEM_SKIP_STEP - MODEM_SKIP_OFFSET;
|
|
float skipY = (float)(Random() % 2 + 1) * MODEM_SKIP_STEP - MODEM_SKIP_OFFSET;
|
|
Room& room = *g_game->room;
|
|
Vector clamped = room.GetClampedPosition(pos, 0);
|
|
bool isInRoom = clamped.x == pos.x && clamped.y == pos.y;
|
|
pos = vector_add(pos, vector_make(skipX, skipY));
|
|
if (isInRoom) pos = room.GetClampedPosition(pos, 0);
|
|
}
|
|
|
|
// Part of 006c4b30: a poof02 event puffs half-faded smoke at the NPC, placed and sized (a third) by the null of that
|
|
// name. The original reads the null unchecked. Here a sprite without one puffs nothing.
|
|
void Entity_NPC::poof02_spawn()
|
|
{
|
|
const NullFrame* null = sprite.GetNullFrame("poof02");
|
|
if (!null) return;
|
|
|
|
Entity* poof = g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF02, .seed = Random()});
|
|
poof->sprite.offset = null->pos;
|
|
poof->sprite.scale = vector_scale(null->scale, POOF02_SCALE);
|
|
poof->renderDepthOffset = POOF02_DEPTH;
|
|
poof->SetColor(POOF02_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true);
|
|
}
|
|
|
|
// Part of 006c4b30: a grounded enemy walking through water leaves a ripple every 7 frames.
|
|
void Entity_NPC::ripple_spawn()
|
|
{
|
|
if (IsFlying() || !isVisible || !IsActiveEnemy(DEAD_EXCLUDED) || vector_length_squared(velocity) <= 1) return;
|
|
if (!g_game->room->HasWater() || !IsFrame(RIPPLE_FRAMES, (int)index) || entityCollisionClass == ENTCOLL_NONE)
|
|
return;
|
|
|
|
Entity* ripple = spawn_at(ENTITY_EFFECT, EFFECT_WATER_SPLASH, 0, vector_add(pos, velocity), this);
|
|
float rippleScale = size * RIPPLE_SCALE * scale;
|
|
ripple->sprite.scale = vector_make(rippleScale, rippleScale);
|
|
ripple->renderDepthOffset = RIPPLE_DEPTH;
|
|
ripple->velocity = vector_scale(velocity, RIPPLE_SPEED);
|
|
ripple->Update();
|
|
}
|
|
|
|
// 006c4b30 One frame of an enemy: its speed, status overlay and pause, appearing, its AI, champion and item
|
|
// effects, dying, the base update (movement), then the seeds and debug modes that change it, and its forced target.
|
|
void Entity_NPC::Update()
|
|
{
|
|
if (!isExists) return;
|
|
|
|
speedMultiplier = compute_speed_multiplier();
|
|
UpdateChildEffectPosition(false);
|
|
if (controllerID == -1)
|
|
{
|
|
controllerMovement = {};
|
|
if (aimTargetEffect) aimTargetEffect->Remove();
|
|
aimTargetEffect = nullptr;
|
|
}
|
|
if (HasEntityFlags(FLAG_ICE_FROZEN)) return update_frozen();
|
|
|
|
bool isWeakened = g_game->room->temporaryEffects.HasNullEffect(NULLITEM_DAMOCLES_WEAKNESS);
|
|
if (IsFrame(WEAKNESS_FRAMES, 0) && !IsFriendly() && IsActiveEnemy(DEAD_EXCLUDED) && isWeakened)
|
|
AddWeakness(EntityRef(nullptr), -3);
|
|
if (salvationTarget && salvationTarget->target.get() == this)
|
|
{
|
|
salvationTarget->pos = pos;
|
|
salvationTarget->velocity = velocity;
|
|
}
|
|
status_overlay_update();
|
|
|
|
bool isDeadBefore = isDead;
|
|
if ((pauseTimer != 0 || HasEntityFlags(FLAG_HELD)))
|
|
{
|
|
if (!paused_update()) return;
|
|
isDeadBefore = isDead;
|
|
}
|
|
|
|
bool isAppearing = HasEntityFlags(FLAG_APPEAR);
|
|
if (!isAppearing && state == NPC_STATE_APPEAR) state = savedState;
|
|
else if (isAppearing && state == NPC_STATE_APPEAR) appear_update();
|
|
else death_animation_update();
|
|
|
|
bool isHeld = HasEntityFlags(FLAG_FREEZE) || HasEntityFlags(FLAG_HELD) || holdCountdown > 0;
|
|
bool isDying = state == NPC_STATE_DEATH || state == NPC_STATE_UNIQUE_DEATH;
|
|
if (isDying || ((isHeld || state == NPC_STATE_APPEAR) && !isDead))
|
|
{
|
|
if (HasEntityFlags(FLAG_FREEZE) || holdCountdown > 0)
|
|
{
|
|
friction *= APPEAR_FRICTION;
|
|
if (holdCountdown > 0 && !vector_is_zero(holdPosition)) pos = holdPosition;
|
|
}
|
|
if (!isDead) player_aura_update();
|
|
}
|
|
else
|
|
{
|
|
if (!HasEntityFlags(FLAG_CHARM)) decoy_update();
|
|
if (isDead && state == NPC_STATE_APPEAR)
|
|
{
|
|
friction = baseFriction;
|
|
state = savedState;
|
|
isVisible = true;
|
|
}
|
|
if (championRegenTimer == 0) npc_ai_update(*this);
|
|
|
|
champion_update();
|
|
unreachable_update();
|
|
if (isDead && isExists) dead_update();
|
|
if (!isDead) player_aura_update();
|
|
}
|
|
item_effects_update();
|
|
if (HasEntityFlags(FLAG_BAITED)) friction *= timescale_factor(SLOW_FRICTION, speedMultiplier);
|
|
if (isChampion)
|
|
velocity = vector_scale(velocity, timescale_factor(1 - (1 - championSpeed) * (1 - friction), speedMultiplier));
|
|
if (sprite.IsEventTriggered("poof02")) poof02_spawn();
|
|
spawn_damage_numbers();
|
|
update_damage_history();
|
|
if (aiCallFlags & AI_CALL_PRE_UPDATE) ai_call(AI_PHASE_PRE_UPDATE);
|
|
if (HasEntityFlags(FLAG_PERSISTENT | FLAG_DELIRIUM_FORM)) captured_update();
|
|
|
|
float healthBefore = health;
|
|
if (type == ENTITY_MINECART) update_physics();
|
|
else Entity::Update();
|
|
totalDamageTaken += std::max(healthBefore - health, 0.0f);
|
|
if (aiCallFlags & AI_CALL_POST_UPDATE) ai_call(AI_PHASE_POST_UPDATE);
|
|
|
|
seed_effects_update();
|
|
sprite.scale = vector_make(scale * shrinkStatus1, scale * shrinkStatus1);
|
|
ripple_spawn();
|
|
pausePosition = pos;
|
|
if (!isBestiaryEncountered)
|
|
{
|
|
g_manager->persistentGameData.TryAddBestiaryEncounter(type, variant);
|
|
isBestiaryEncountered = true;
|
|
}
|
|
if (IsFrame(config->collisionInterval * 2, (int)index)) hitList.clear();
|
|
else if (type == ENTITY_BLOOD_PUPPY && state == NPC_STATE_ATTACK && sprite.animState.IsLoopingAnimation() &&
|
|
IsFrame(PUPPY_HIT_FRAMES, (int)index))
|
|
hitList.clear();
|
|
type_update();
|
|
|
|
if (isDead && !isDeadBefore && !IsBoss() && !config->isBoss && HasEntityFlags(FLAG_ICE)) ice_statue_make();
|
|
if (!isDead && state != NPC_STATE_DEATH)
|
|
{
|
|
ClearEntityFlags(FLAG_EXTRA_GORE);
|
|
ClearEntityFlags(FLAG_SPAWN_STICKY_SPIDERS);
|
|
}
|
|
forced_target_update();
|
|
}
|
|
|
|
// Part of 006c4b30: a persistent enemy or a Delirium form (Delirious's friendly boss) wastes a quarter of health every
|
|
// 15 frames down to 1, greying and shrinking with it. A hit this frame that is not fire, spikes or poop passes on as 1
|
|
// damage from its biggest hit, or as 5 from an explosion.
|
|
// The shrink is lost at once, as the frame's scale reset (FUN_006d6650) overwrites it.
|
|
void Entity_NPC::captured_update()
|
|
{
|
|
constexpr int WASTE_FRAMES = 15;
|
|
constexpr float WASTE_STEP = 0.25f;
|
|
constexpr float WASTE_LEAST_TINT = 0.6f;
|
|
constexpr float WASTE_LEAST_SCALE = 0.6f;
|
|
constexpr float WASTE_MOST_SCALE = 1.1f;
|
|
constexpr float CAPTURED_HIT_DAMAGE = 1;
|
|
constexpr float CAPTURED_BLAST_DAMAGE = 5;
|
|
constexpr uint64_t UNFELT_DAMAGE = DAMAGE_FIRE | DAMAGE_SPIKES | DAMAGE_POOP;
|
|
if (IsFrame(WASTE_FRAMES, 0) && health > 1) health = std::max(health - WASTE_STEP, 1.0f);
|
|
|
|
float tint = std::lerp(WASTE_LEAST_TINT, 1.0f, std::clamp(health * health / (maxHitPoints * maxHitPoints), 0.0f, 1.0f));
|
|
std::fill_n(sprite.color._tint, 3, tint);
|
|
sprite.color._tint[3] = 1;
|
|
float shrink = std::lerp(WASTE_LEAST_SCALE, WASTE_MOST_SCALE, std::clamp(health / maxHitPoints, 0.0f, 1.0f));
|
|
sprite.scale = vector_make(shrink, shrink);
|
|
|
|
const DamageEvent* felt = nullptr;
|
|
float feltDamage = 0;
|
|
float biggest = 0;
|
|
for (const DamageEvent& event : damageEvents)
|
|
{
|
|
if (event.damageFlags & UNFELT_DAMAGE) continue;
|
|
if (event.damageFlags & DAMAGE_EXPLOSION)
|
|
{
|
|
felt = &event;
|
|
feltDamage = CAPTURED_BLAST_DAMAGE;
|
|
break;
|
|
}
|
|
if (event.damage <= biggest) continue;
|
|
felt = &event;
|
|
feltDamage = CAPTURED_HIT_DAMAGE;
|
|
biggest = event.damage;
|
|
}
|
|
if (felt) TakeDamage(feltDamage, felt->damageFlags, felt->source, 0);
|
|
}
|
|
|
|
// The camouflage seeds: an enemy takes on the floor under it, sampled on its first frames and every 30 after, and
|
|
// blends a tenth of the way toward it each frame, nearly black underneath.
|
|
void Entity_NPC::camouflage_update()
|
|
{
|
|
constexpr float CAMO_DARKNESS = 0.02f;
|
|
camouflage_blend(*this, floorColor, CAMO_DARKNESS);
|
|
}
|
|
|
|
// The camouflage of an entity on the camo seeds: a color sampled from the floor under it on its first frames and
|
|
// every 30 after, which its sprite blends a tenth of the way toward each frame, tinted to a darkness underneath.
|
|
void camouflage_blend(Entity& entity, ColorMod& floorColor, float darkness)
|
|
{
|
|
constexpr float CAMO_ALPHA = 0.7f;
|
|
constexpr float CAMO_FLOOR_TONE = 0.9f;
|
|
constexpr float CAMO_ALPHA_BLEND = 0.3f;
|
|
constexpr float CAMO_FLOOR_BLEND = 0.5f;
|
|
constexpr float CAMO_SPRITE_BLEND = 0.1f;
|
|
constexpr int CAMO_RESAMPLE_FRAMES = 30;
|
|
constexpr int CAMO_SAMPLE_WINDOW = 2;
|
|
Room& room = *g_game->room;
|
|
ANM2& sprite = entity.sprite;
|
|
if (entity.FrameCount() < CAMO_SAMPLE_WINDOW)
|
|
{
|
|
KColor floor = room_floor_texel_get(room, entity.pos);
|
|
const float shares[] = {floor._red, floor._green, floor._blue};
|
|
std::fill_n(floorColor._tint, 3, 0.0f);
|
|
floorColor._tint[3] = CAMO_ALPHA;
|
|
for (int i = 0; i < 3; i++) floorColor._offset[i] = shares[i] * CAMO_FLOOR_TONE;
|
|
sprite.color = floorColor;
|
|
}
|
|
if ((uint32_t)(g_game->frameCount + entity.index) % CAMO_RESAMPLE_FRAMES < CAMO_SAMPLE_WINDOW)
|
|
{
|
|
KColor floor = room_floor_texel_get(room, entity.pos);
|
|
floorColor._tint[3] = std::lerp(floorColor._tint[3], CAMO_ALPHA, CAMO_ALPHA_BLEND);
|
|
const float shares[] = {floor._red, floor._green, floor._blue};
|
|
for (int i = 0; i < 3; i++)
|
|
floorColor._offset[i] = std::lerp(floorColor._offset[i], shares[i] * CAMO_FLOOR_TONE, CAMO_FLOOR_BLEND);
|
|
}
|
|
ColorMod blended = color_lerp(sprite.color, floorColor, CAMO_SPRITE_BLEND);
|
|
std::fill_n(blended._tint, 3, darkness);
|
|
blended._tint[3] = 1;
|
|
sprite.color = blended;
|
|
}
|
|
|
|
// The pacifist seed and the quick kill debug mode drain every enemy by 1/900 of its health a frame, faster for the
|
|
// split bosses, Satan, Mega Satan's fight and outside boss rooms, and a hundred times faster in quick kill. The pacifist
|
|
// seed makes them invincible. Outside quick kill only bosses drain, and the doors open once no boss is left. A drained
|
|
// boss dies with a hit, except those whose death waits on their partners, which give up holding the doors instead.
|
|
void Entity_NPC::quick_kill_update()
|
|
{
|
|
constexpr float DRAIN_SECONDS = 30;
|
|
constexpr float SPLIT_DRAIN_SCALE = 3;
|
|
constexpr float MEGA_SATAN_ROOM_DRAIN_SCALE = 4;
|
|
constexpr float MEGA_SATAN_DRAIN_SCALE = 0.33333f;
|
|
constexpr float BOSS_RUSH_DRAIN_SCALE = 2;
|
|
constexpr float MINIBOSS_DRAIN_SCALE = 3;
|
|
constexpr float ROOM_DRAIN_SCALE = 6;
|
|
constexpr float QUICK_KILL_DRAIN_SCALE = 100;
|
|
constexpr int QUICK_KILL_COUNTDOWN = 30;
|
|
Room& room = *g_game->room;
|
|
bool isQuickKill = g_game->debugFlags & DEBUG_QUICK_KILL;
|
|
bool isBlastocyst = type == ENTITY_BLASTOCYST_BIG || type == ENTITY_BLASTOCYST_MEDIUM || type == ENTITY_BLASTOCYST_SMALL;
|
|
bool isSplitBoss = type == ENTITY_FISTULA_BIG || type == ENTITY_FISTULA_MEDIUM || type == ENTITY_FISTULA_SMALL ||
|
|
isBlastocyst || (type == ENTITY_THE_HAUNT && variant == HAUNT_LIL_VARIANT);
|
|
bool isSatanFight = type == ENTITY_FALLEN && room.bossId == BOSS_SATAN;
|
|
bool isMegaSatan = type == ENTITY_MEGA_SATAN || type == ENTITY_MEGA_SATAN_2;
|
|
float drain = maxHitPoints / DRAIN_SECONDS / DRAIN_SECONDS;
|
|
if (g_game->seedEffects.HasSeedEffect(SEED_PACIFIST)) isInvincible = true;
|
|
|
|
if (isSplitBoss || isSatanFight) drain *= SPLIT_DRAIN_SCALE;
|
|
else if (isMegaSatan) drain = isInvincible ? 0 : drain * MEGA_SATAN_DRAIN_SCALE;
|
|
else if (room.bossId == BOSS_MEGA_SATAN) drain *= MEGA_SATAN_ROOM_DRAIN_SCALE;
|
|
if (room.roomType == ROOM_BOSSRUSH) drain *= BOSS_RUSH_DRAIN_SCALE;
|
|
else if (room.roomType == ROOM_MINIBOSS) drain *= MINIBOSS_DRAIN_SCALE;
|
|
else if (room.roomType != ROOM_BOSS) drain *= ROOM_DRAIN_SCALE;
|
|
if (isQuickKill) drain *= QUICK_KILL_DRAIN_SCALE;
|
|
|
|
if (!IsBoss() && !isQuickKill)
|
|
{
|
|
if (room.GetAliveBossesCount() < 1) isCanShutDoors = false;
|
|
return;
|
|
}
|
|
if (isBlastocyst)
|
|
{
|
|
if (health > 0 || entityCollisionClass == ENTCOLL_NONE) health -= drain;
|
|
else
|
|
{
|
|
isInvincible = false;
|
|
health = 1;
|
|
isDead = true;
|
|
}
|
|
return;
|
|
}
|
|
if (health > 0)
|
|
{
|
|
health -= drain;
|
|
return;
|
|
}
|
|
|
|
bool isHeldOn = type == ENTITY_GURDY || type == ENTITY_MEGA_MAW || type == ENTITY_GATE || type == ENTITY_MOMS_HEART ||
|
|
type == ENTITY_FISTULA_BIG || type == ENTITY_FISTULA_MEDIUM || type == ENTITY_FISTULA_SMALL ||
|
|
(type == ENTITY_THE_HAUNT && variant == HAUNT_LIL_VARIANT);
|
|
bool isKilled = isQuickKill || isHeldOn || room.roomType == ROOM_BOSSRUSH || room.bossId == BOSS_MEGA_SATAN || isSatanFight;
|
|
if (!isKilled)
|
|
{
|
|
isCanShutDoors = false;
|
|
return;
|
|
}
|
|
isInvincible = false;
|
|
TakeDamage(1, 0, EntityRef(), QUICK_KILL_COUNTDOWN);
|
|
isDead = true;
|
|
}
|
|
|
|
// Part of 006c4b30: the seeds and the debug mode that change every enemy: invisible enemies, camouflage, and the
|
|
// pacifist seed and quick kill that make them waste away.
|
|
void Entity_NPC::seed_effects_update()
|
|
{
|
|
Seeds& seeds = g_game->seedEffects;
|
|
if (seeds.HasSeedEffect(SEED_INVISIBLE_ENEMIES))
|
|
{
|
|
SetColor(COLOR_INVISIBLE, -1, COLOR_PRIORITY_DEFAULT, false, true);
|
|
sprite.color = COLOR_INVISIBLE;
|
|
shadowSize = 0;
|
|
}
|
|
if (seeds.HasSeedEffect(SEED_CAMO_ENEMIES) || seeds.HasSeedEffect(SEED_CAMO_EVERYTHING)) camouflage_update();
|
|
bool isQuickKill = seeds.HasSeedEffect(SEED_PACIFIST) || (g_game->debugFlags & DEBUG_QUICK_KILL);
|
|
if (isQuickKill && IsActiveEnemy(DEAD_EXCLUDED)) quick_kill_update();
|
|
}
|
|
|
|
// Part of 006c4b30: the few enemies with their own per-frame step: Hornfel, Gideon's camera, the Heart's partner and
|
|
// Big Horn's splash.
|
|
void Entity_NPC::type_update()
|
|
{
|
|
if (type == ENTITY_HORNFEL) Hornfel_UpdateFrame();
|
|
if (type == ENTITY_GIDEON && state == NPC_STATE_APPEAR) g_game->room->camera->SetFocusPosition(pos);
|
|
if (type == ENTITY_HEART)
|
|
{
|
|
targetPosition = {};
|
|
if (variant == 1 && entityRef && entityRef->IsEnemy())
|
|
{
|
|
Entity* partner = entityRef;
|
|
targetPosition = vector_sub(partner->pos, pos);
|
|
partner->targetPosition = vector_scale(targetPosition, -1);
|
|
}
|
|
}
|
|
if (type == ENTITY_BIG_HORN && sprite.IsEventTriggered(BIG_HORN_SPLASH_EVENT)) big_horn_splash(*this);
|
|
}
|
|
|
|
// Part of 006c4b30: a forced target runs out, and a boss then waits 150 frames before taking another.
|
|
void Entity_NPC::forced_target_update()
|
|
{
|
|
if (forcedTargetTimer < 0)
|
|
{
|
|
forcedTargetTimer++;
|
|
return;
|
|
}
|
|
if (forcedTargetTimer == 0 || --forcedTargetTimer != 0) return;
|
|
if (IsBoss()) forcedTargetTimer = -FORCED_TARGET_BOSS_COOLDOWN;
|
|
forcedTarget = nullptr;
|
|
}
|
|
|
|
// 006b99e0 Its speed this frame: the room's time scale for it, halved under a stopwatch or the hourglass (or, for a
|
|
// friendly enemy, the room's slowdown), slowed and weakened enemies slower, and Vanishing Twin's boss slower still.
|
|
float Entity_NPC::compute_speed_multiplier()
|
|
{
|
|
Room& room = *g_game->room;
|
|
float speed = room.GetTimeScale(this);
|
|
if (!IsFriendly())
|
|
{
|
|
if (room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH_ID) ||
|
|
(g_game->challenge != CHALLENGE_SPEED && room.brokenWatchState == BROKEN_WATCH_SLOW))
|
|
speed *= SPEED_HALF;
|
|
else if (TemporaryEffect* hourglass = room.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_HOURGLASS_ID))
|
|
speed *= 1 - std::clamp((float)hourglass->cooldown / SLOW_TIMESCALE_EFFECT_FRAMES, 0.0f, 1.0f) * SPEED_HALF;
|
|
}
|
|
else if (room.slowdownDuration > 0) speed *= SPEED_HALF;
|
|
|
|
if (HasEntityFlags(FLAG_SLOW) && state != NPC_STATE_DEATH) speed *= SPEED_HALF;
|
|
if (HasEntityFlags(FLAG_WEAKNESS)) speed *= SPEED_WEAKENED;
|
|
if (IsBoss() && !IsFriendly() && room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_VANISHING_TWIN))
|
|
speed *= SPEED_VANISHING_TWIN;
|
|
return speed;
|
|
}
|
|
|
|
// Part of 006d60a0: Betrayal turns an enemy on the nearest enemy up its attacker's parent line, for 150 frames, unless
|
|
// it is the same body, newborn or not vulnerable. One already set on another target switches only one hit in four. A
|
|
// switch it survives shows an angry heart over it.
|
|
void Entity_NPC::betrayal_turn(Entity* attacker)
|
|
{
|
|
constexpr int BETRAYAL_FRAMES = 150;
|
|
constexpr uint32_t BETRAYAL_SWITCH_MASK = 3;
|
|
constexpr int BETRAYAL_HEART_SUBTYPE = 2;
|
|
constexpr float BETRAYAL_HEART_LIFT = -24;
|
|
for (; attacker; attacker = attacker->parent)
|
|
{
|
|
if (!Entity::is_enemy_type(attacker->type)) continue;
|
|
if (attacker == this || attacker->GetStatusEffectTarget() == GetStatusEffectTarget()) return;
|
|
if (g_game->frameCount - attacker->spawnFrame <= 0 || !attacker->IsVulnerableEnemy(nullptr)) return;
|
|
Entity* previous = forcedTarget;
|
|
if (previous && previous != attacker && (Random() & BETRAYAL_SWITCH_MASK) != 0) return;
|
|
if (!TryForceTarget(attacker, BETRAYAL_FRAMES) || previous == attacker || pendingDamage >= health) return;
|
|
|
|
Entity* heart = g_game->Spawn({.position = pos, .subType = BETRAYAL_HEART_SUBTYPE, .type = ENTITY_EFFECT,
|
|
.variant = EFFECT_HEART, .seed = Random()});
|
|
heart->sprite.offset = vector_make(0, BETRAYAL_HEART_LIFT);
|
|
heart->renderDepthOffset = 1;
|
|
return;
|
|
}
|
|
}
|
|
|
|
// 006d60a0 Takes a hit as any entity (Entity::TakeDamage) and lets the items that react to it act: a player's hit
|
|
// ends Pacifist, Betrayal turns it on its attacker, the pulsing champion spawns its flies, and a hit taken spawns
|
|
// a blue fly for a hit that spawns one, marks a player's kill for Jar of Flies, and triggers the attacker's
|
|
// on-hit procedural items.
|
|
bool Entity_NPC::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& source, int damageCountdown)
|
|
{
|
|
bool isHurt = Entity::TakeDamage(damage, damageFlags, source, damageCountdown);
|
|
bool isPlayerSource = source.type == ENTITY_PLAYER || source.type == ENTITY_FAMILIAR ||
|
|
source.spawnerType == ENTITY_PLAYER || source.spawnerType == ENTITY_FAMILIAR;
|
|
if (!IsFriendly() && isPlayerSource) g_game->room->isPacifist = false;
|
|
|
|
PlayerManager& players = g_game->playerManager;
|
|
if (source.entity && players.FirstCollectibleOwner(COLLECTIBLE_BETRAYAL_ID, LAZARUS_SHARE_CHECK)) betrayal_turn(source.entity);
|
|
if (players.FirstCollectibleOwner(COLLECTIBLE_JAR_OF_FLIES, LAZARUS_SHARE_CHECK))
|
|
{
|
|
bool isBlueFly = source.type == ENTITY_FAMILIAR && source.variant == Entity_Familiar::BLUE_FLY;
|
|
bool isPlayerKill = source.type == ENTITY_PLAYER || (source.spawnerType == ENTITY_PLAYER && !isBlueFly) ||
|
|
(damageFlags & ((uint64_t)DAMAGE_ACID | DAMAGE_POISON_BURN)) ||
|
|
source.type == ENTITY_EFFECT;
|
|
if (isPlayerKill) AddEntityFlags(FLAG_ADD_JAR_FLY);
|
|
else ClearEntityFlags(FLAG_ADD_JAR_FLY);
|
|
}
|
|
bool isPlayerHit = source.type == ENTITY_PLAYER ||
|
|
(source.spawnerType == ENTITY_PLAYER &&
|
|
(source.type != ENTITY_FAMILIAR || source.variant != Entity_Familiar::BLUE_FLY));
|
|
bool isFlyDue = !isDead && pendingDamage < health && championTimer < 1 && !(damageFlags & DAMAGE_ACID);
|
|
if (championColorIdx == CHAMPION_SIZE_PULSE && isFlyDue && isPlayerHit) champion_fly_spawn();
|
|
if (!isHurt || HasEntityFlags(FLAG_NO_STATUS_EFFECTS)) return isHurt;
|
|
|
|
Entity* attacker = source.entity;
|
|
if (attacker && attacker->type != ENTITY_PLAYER) attacker = attacker->spawnerEntity;
|
|
Entity_Player* player =
|
|
attacker && attacker->type == ENTITY_PLAYER ? static_cast<Entity_Player*>(attacker) : game_nearest_player(pos);
|
|
if (damageFlags & DAMAGE_SPAWN_FLY) player->AddBlueFlies(1, player->pos, this);
|
|
glitched_items_hit_trigger(*player, *this, CONDITION_ENEMY_HIT);
|
|
return isHurt;
|
|
}
|
|
|
|
// 006be6f0 Keeps what killed it (the damage and its events) for the death triggers, then dies as any entity.
|
|
void Entity_NPC::Kill(const EntityRef& source)
|
|
{
|
|
killDamage = pendingDamage;
|
|
killDamageFlags = pendingDamageFlags;
|
|
killDamageEvents = damageEvents;
|
|
Entity::Kill(source);
|
|
}
|
|
|
|
// 006b8f30 Lets go of everything it points at, Gideon's chain and Mother's sounds included.
|
|
void Entity_NPC::ClearReferences()
|
|
{
|
|
auto* charmed = dynamic_cast<Entity_Familiar*>(target.get());
|
|
if (type == ENTITY_SIREN_HELPER && charmed && charmed->HasEntityFlags(FLAG_CHARM)) charmed->RemoveFromPlayer();
|
|
if (type == ENTITY_GIDEON) gideon_chain_unlink(*this);
|
|
if (type == ENTITY_MOTHER && (variant == 0 || variant == 10))
|
|
{
|
|
g_manager->sfxManager.Stop(SOUND_MOTHER_SUCTION);
|
|
g_manager->sfxManager.Stop(SOUND_ULTRA_GREED_SPINNING);
|
|
}
|
|
pickupGhostsEntity = nullptr;
|
|
unknownF54 = nullptr;
|
|
salvationTarget = nullptr;
|
|
entityRef = nullptr;
|
|
if (aimTargetEffect) aimTargetEffect->Remove();
|
|
aimTargetEffect = nullptr;
|
|
ClearDequeRefs();
|
|
forcedTarget = nullptr;
|
|
Entity::ClearReferences();
|
|
entityDeque.clear();
|
|
vectorDeque1.clear();
|
|
vectorDeque2.clear();
|
|
statusEffectSprite.Reset();
|
|
chargeBarSprite.Reset();
|
|
hitList.clear();
|
|
hitList.shrink_to_fit();
|
|
secondaryHitList.clear();
|
|
secondaryHitList.shrink_to_fit();
|
|
}
|
|
|
|
// 006d81c0 Lets go of the entities its deque holds, and the deque.
|
|
void Entity_NPC::ClearDequeRefs()
|
|
{
|
|
entityDeque.clear();
|
|
}
|
|
|
|
// 006c1100 Shows its own color again: a champion its sprite color (on its _champion sheets) or its color laid over
|
|
// it, a boss its alternate color, else its own. A friendly enemy is washed out and a frozen one iced.
|
|
void Entity_NPC::ResetColor()
|
|
{
|
|
if (isChampion)
|
|
{
|
|
bool isChampionSheet = std::ranges::any_of(sprite.layerStates, [](const LayerState& layer) {
|
|
return layer.bitflags & ANIM_RENDER_COLOROFFSET_CHAMPION;
|
|
});
|
|
if (championColorIdx >= 0 && championColorIdx < CHAMPION_COUNT)
|
|
sprite.color = isChampionSheet ? champion_look_get(championColorIdx).spriteColor
|
|
: champion_sprite_color_get(championColorIdx);
|
|
}
|
|
else if (bosscoloridx < 0) sprite.color = color;
|
|
else if (bosscoloridx < (int)config->bossColors.size()) sprite.color = config->bossColors[bosscoloridx].color;
|
|
|
|
bool isShadowCharger = type == ENTITY_SHADOW_CHARGER && variant == 0 && subtype == SHADOW_CHARGER_SUBTYPE;
|
|
if (IsFriendly() && !isShadowCharger) sprite.color = FRIENDLY_COLOR;
|
|
if (type == ENTITY_FROZEN_ENEMY) sprite.color = FROZEN_COLOR;
|
|
}
|
|
|
|
// 006b9450 A G-Fuel explosion at a position: a big one (past 1.5) or one of the two small ones, with its sound and a
|
|
// screen shake.
|
|
Entity* gfuel_explosion_spawn(const Vector& position, float scale)
|
|
{
|
|
Entity* explosion = spawn_at(ENTITY_EFFECT, EFFECT_POOF01, 0, position, nullptr);
|
|
bool isBig = scale > GFUEL_BIG_SCALE;
|
|
uint32_t pick = Random();
|
|
explosion->sprite.Load(isBig ? GFUEL_BIG_EXPLOSION_ANM2 : GFUEL_EXPLOSION_ANM2S[pick & 1], GRAPHICS_LOAD);
|
|
npc_sound_play(isBig ? SOUND_GFUEL_EXPLOSION_BIG : SOUND_GFUEL_EXPLOSION, 1, 2,
|
|
random_unit() * GFUEL_BLAST_PITCH_RANGE + GFUEL_BLAST_PITCH);
|
|
game_shake_screen(isBig ? GFUEL_BIG_BLAST_SHAKE : GFUEL_BLAST_SHAKE);
|
|
explosion->sprite.Play(explosion->sprite.GetDefaultAnimationName(), PLAY_FORCED);
|
|
explosion->Update();
|
|
return explosion;
|
|
}
|
|
|
|
// The Dust's death: a bright crater flash, a small dark puff and its sounds.
|
|
static void dust_death_spawn(Entity_NPC& npc)
|
|
{
|
|
Entity* flash = spawn_at(ENTITY_EFFECT, EFFECT_BOMB_CRATER, 0, npc.pos, nullptr);
|
|
std::fill_n(flash->sprite.color._colorize, 3, DUST_FLASH_COLORIZE);
|
|
flash->sprite.color._colorize[3] = 1;
|
|
flash->Update();
|
|
Entity* puff = spawn_at(ENTITY_EFFECT, EFFECT_POOF02, DUST_PUFF_SUBTYPE, npc.pos, &npc);
|
|
puff->sprite.scale = vector_make(DUST_PUFF_SCALE, DUST_PUFF_SCALE);
|
|
puff->sprite.isFlipX = (Random() & 1) == 0;
|
|
puff->Update();
|
|
npc.PlaySound(SOUND_GOODEATH, 1, 2, false, 1);
|
|
npc.PlaySound(SOUND_BLACK_POOF, DUST_DEATH_VOLUME, 2, false, 1);
|
|
}
|
|
|
|
// 006d4e00 Bursts it: a blood explosion its size (or a fly's, a spider's, a poop's), in its splat color, from its
|
|
// sprite's middle, or a G-Fuel explosion. The Dust also flashes.
|
|
void Entity_NPC::PlayDeathEffects()
|
|
{
|
|
if (g_game->playerManager.GetGFuelCount() > 0)
|
|
{
|
|
gfuel_explosion_spawn(pos, 1);
|
|
return;
|
|
}
|
|
|
|
Vector offset{};
|
|
const AnimationFrame* frame = sprite.animState.animData && (type != ENTITY_SCOURGE || variant != 10)
|
|
? sprite.animState.GetLayerFrame(0)
|
|
: nullptr;
|
|
if (frame)
|
|
offset = vector_make(frame->width * HALF - frame->pivot.x + frame->pos.x,
|
|
frame->height * HALF - frame->pivot.y + frame->pos.y);
|
|
if (HasEntityFlags(FLAG_NO_BLOOD_SPLASH)) return;
|
|
|
|
int burst = death_burst_get();
|
|
if (burst == EFFECT_BLOOD_EXPLOSION)
|
|
{
|
|
Entity* blood = spawn_at(ENTITY_EFFECT, EFFECT_BLOOD_EXPLOSION, poof_size_get(*this, true), pos, nullptr);
|
|
blood->sprite.offset = offset;
|
|
blood->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true);
|
|
blood->renderDepthOffset = BLOOD_DEPTH_OFFSET;
|
|
}
|
|
else
|
|
{
|
|
if (config->gibFlags & GIB_FLAG_POOP) npc_sound_play(SOUND_POOP_DEATH, POOP_DEATH_VOLUME, 2, 1);
|
|
Entity* burstEffect = spawn_at(ENTITY_EFFECT, burst, 0, vector_add(pos, offset), nullptr);
|
|
burstEffect->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true);
|
|
}
|
|
if (type == ENTITY_DUST) dust_death_spawn(*this);
|
|
}
|
|
|
|
// Part of 006d4e00: the burst effect a dead NPC leaves: a poop's, a fly's, a spider's, a few special ones, else
|
|
// blood.
|
|
int Entity_NPC::death_burst_get()
|
|
{
|
|
if (config->gibFlags & GIB_FLAG_POOP) return EFFECT_POOP_EXPLOSION;
|
|
switch (type)
|
|
{
|
|
case ENTITY_FLY:
|
|
case ENTITY_POOTER:
|
|
case ENTITY_ATTACKFLY:
|
|
case 214:
|
|
case 222:
|
|
case 249:
|
|
case 256:
|
|
case 281:
|
|
case 296:
|
|
case 808:
|
|
case 838:
|
|
case 868:
|
|
return EFFECT_FLY_EXPLOSION;
|
|
case ENTITY_SPIDER:
|
|
case 94:
|
|
case 215:
|
|
case 250:
|
|
case 869:
|
|
case 884:
|
|
return EFFECT_SPIDER_EXPLOSION;
|
|
case 810:
|
|
return EFFECT_BURST_810;
|
|
case 818:
|
|
return EFFECT_BURST_818;
|
|
case 853:
|
|
return EFFECT_BURST_853;
|
|
default:
|
|
return EFFECT_BLOOD_EXPLOSION;
|
|
}
|
|
}
|
|
|
|
// Part of 006be840: a Dople keeps its player, else picks one by its seed among the players no other Dople copies (a
|
|
// controlled one, its controller's). With none left it dies, mimicking the first player.
|
|
static Entity* dople_player_pick(Entity_NPC& npc)
|
|
{
|
|
if (npc.target) return npc.target.get();
|
|
|
|
std::vector<Entity*> doples = entity_query(ENTITY_DOPLE, -1);
|
|
std::vector<Entity_Player*> candidates;
|
|
for (Entity_Player* player : g_game->playerManager.playerList)
|
|
{
|
|
bool isFree = npc.controllerID != -1 ? player->controllerIndex == npc.controllerID
|
|
: std::ranges::none_of(doples, [&](Entity* dople) {
|
|
return dople != &npc && static_cast<Entity_NPC*>(dople)->target.get() == player;
|
|
});
|
|
if (isFree) candidates.push_back(player);
|
|
}
|
|
|
|
Entity* picked = nullptr;
|
|
if (!candidates.empty())
|
|
{
|
|
RNG pick = rng_make(npc.initSeed, DOPLE_PICK_SHIFT);
|
|
picked = candidates[pick.RandomInt((int)candidates.size())];
|
|
}
|
|
else
|
|
{
|
|
npc.Kill(EntityRef());
|
|
picked = g_game->GetPlayer(0);
|
|
}
|
|
npc.target = picked;
|
|
return npc.target.get();
|
|
}
|
|
|
|
// 006be840 What it goes after: a charmed enemy picks the nearest enemy, a Dople (type 53) its own player,
|
|
// the rest the nearest target player (Game::GetNearestTargetPlayer), else the first player.
|
|
Entity* Entity_NPC::GetPlayerTarget()
|
|
{
|
|
if (type == ENTITY_DOPLE) return dople_player_pick(*this);
|
|
|
|
bool isRetargeting = IsFrame(TARGET_REFRESH_FRAMES, (int)index) || !target;
|
|
if (HasEntityFlags(FLAG_CHARM) && !g_game->room->isPacifist && isRetargeting)
|
|
target = game_nearest_enemy(pos, this, TARGET_RANGE);
|
|
if (target) return target;
|
|
|
|
bool isTargetDecoys = type != ENTITY_NO_DECOY_TYPE && decoyTargetTimer >= 0;
|
|
Entity* found = game_nearest_target_player(pos, this, IsFriendly(), isTargetDecoys, TARGET_RANGE);
|
|
if (!found) return g_game->GetPlayer(0);
|
|
if (found->IsEnemy() && found->HasEntityFlags(FLAG_BAITED)) target = found;
|
|
return found;
|
|
}
|
|
|
|
// 006bec40 Where it heads for its target: a confused enemy wanders to a random spot (a new one every 15 frames),
|
|
// a feared or shrunk one runs from its target (a rare few stay put), the rest go straight for it.
|
|
Vector Entity_NPC::CalcTargetPosition(float distanceLimit)
|
|
{
|
|
Room& room = *g_game->room;
|
|
if (HasEntityFlags(FLAG_CONFUSION))
|
|
{
|
|
bool isKept =
|
|
!vector_is_zero(confusionTargetPos) && (HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused() ||
|
|
g_game->frameCount % CONFUSION_RETARGET_FRAMES != 0);
|
|
if (!isKept)
|
|
{
|
|
float angle = random_unit() * PI_ROUGH;
|
|
angle += angle;
|
|
float scaleFirst = random_unit();
|
|
float distance = random_unit() * scaleFirst * CONFUSION_WANDER;
|
|
Vector spot = vector_make(std::cos(angle) * distance + pos.x, std::sin(angle) * distance + pos.y);
|
|
confusionTargetPos = room.GetClampedPositionImpl(spot, size, size, size, size);
|
|
}
|
|
return confusionTargetPos;
|
|
}
|
|
|
|
bool isFleeingKind = type == ENTITY_MULLIGAN ? variant == MULLIGAN_VARIANT_FLEEING
|
|
: type != ENTITY_HIVE && type != ENTITY_FEAR_IMMUNE;
|
|
bool isFleeing = HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && isFleeingKind;
|
|
if (!isFleeing) return GetPlayerTarget()->pos;
|
|
|
|
Vector away = vector_sub(GetPlayerTarget()->pos, pos);
|
|
if (distanceLimit != 0 && vector_length_squared(away) != 0) away = vector_resized(away, distanceLimit);
|
|
Vector flee = vector_sub(pos, away);
|
|
Vector clamped = room.GetClampedPositionImpl(flee, size, size, size, size);
|
|
if (clamped.x == flee.x && clamped.y == flee.y)
|
|
{
|
|
confusionTargetPos = {};
|
|
return clamped;
|
|
}
|
|
if (!vector_is_zero(confusionTargetPos) && !IsFrame((int)(Random() % FEAR_RETARGET_RANGE) + FEAR_RETARGET_MIN, 0))
|
|
return confusionTargetPos;
|
|
|
|
Vector direction = random_direction();
|
|
float distance = random_unit() * FEAR_WANDER;
|
|
Vector spot = vector_sub(pos, vector_scale(direction, distance));
|
|
confusionTargetPos = room.GetClampedPositionImpl(spot, size, size, size, size);
|
|
return confusionTargetPos;
|
|
}
|
|
|
|
// 006cae60 Whether its target is in range to attack (predicting its motion, checked every frameInterval frames)
|
|
// in a clear line, or the controlling player steers it. Confused, feared and shrunk enemies never attack.
|
|
bool Entity_NPC::IsTargetInAttackRange(float range, int frameInterval, bool isPredictVelocity)
|
|
{
|
|
if (HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) return false;
|
|
if (controllerID != -1) return !vector_is_zero(GetControllerMovementInput(MOVEMENT_DEADZONE));
|
|
|
|
Entity* other = GetPlayerTarget();
|
|
if (!IsHostileTo(other)) return false;
|
|
Vector aim =
|
|
isPredictVelocity ? vector_add(other->pos, vector_scale(other->velocity, ATTACK_PREDICT_FRAMES)) : other->pos;
|
|
if (frameInterval != 0 && !IsFrame(frameInterval, (int)index)) return false;
|
|
if (vector_length_squared(vector_sub(aim, pos)) >= range * range) return false;
|
|
return room_check_line(pos, other->pos, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD) ||
|
|
championColorIdx == CHAMPION_TRANSPARENT;
|
|
}
|
|
|
|
// 006c1330 Walks its main animation: the vertical one stopped while slower than the threshold (half for a slow
|
|
// champion), else the one of the axis it moves most along, flipped to face left, and faces that way.
|
|
void Entity_NPC::AnimWalkFrame(std::string_view horizontalAnim, std::string_view verticalAnim, float speedThreshold)
|
|
{
|
|
if (isChampion && championSpeed < 1) speedThreshold *= HALF;
|
|
if (vector_length_squared(velocity) < speedThreshold * speedThreshold)
|
|
{
|
|
if (sprite.SetAnimation(verticalAnim, SWITCH_KEEP_FRAME) && sprite.animState.animData)
|
|
{
|
|
sprite.animState.SetFrameFloat(0);
|
|
sprite.animState.isPlaying = false;
|
|
}
|
|
forwardVector = vector_make(0, 1);
|
|
return;
|
|
}
|
|
|
|
bool isHorizontal = std::abs(velocity.x) > std::abs(velocity.y);
|
|
std::string_view walk = isHorizontal ? horizontalAnim : verticalAnim;
|
|
const AnimationData* current = sprite.animState.animData;
|
|
bool isWalking = current && current->name == walk && (!current->isLooping || sprite.animState.isPlaying);
|
|
if (!isWalking && sprite.SetAnimation(walk, SWITCH_KEEP_FRAME))
|
|
{
|
|
sprite.animState.Rewind();
|
|
sprite.animState.isPlaying = true;
|
|
}
|
|
if (isHorizontal) sprite.isFlipX = velocity.x < 0;
|
|
|
|
if (isHorizontal) forwardVector = vector_make(velocity.x >= 0 ? 1.0f : -1.0f, 0);
|
|
else forwardVector = vector_make(0, velocity.y >= 0 ? 1.0f : -1.0f);
|
|
}
|
|
|
|
// The rotation of each fan FireProjectiles shoots, as the cosine and sine the exe keeps and a speed scale.
|
|
struct ShotTurn
|
|
{
|
|
float cosine;
|
|
float sine;
|
|
float speed;
|
|
};
|
|
|
|
constexpr ShotTurn SHOT_8 = {0.99f, 0.139f, 1};
|
|
constexpr ShotTurn SHOT_12 = {0.978f, 0.208f, 1};
|
|
constexpr ShotTurn SHOT_16 = {0.961f, 0.276f, 1};
|
|
constexpr ShotTurn SHOT_16_SLOW = {0.961f, 0.276f, 0.9f};
|
|
constexpr ShotTurn SHOT_24 = {0.914f, 0.407f, 1};
|
|
constexpr ShotTurn SHOT_24_SLOW = {0.914f, 0.407f, 0.9f};
|
|
constexpr float PROJECTILE_DEFAULT_FALL_SPEED = -3;
|
|
constexpr float PROJECTILE_DEFAULT_FALL_ACCEL = 0.1f;
|
|
constexpr float PROJECTILE_HEIGHT_LOW = -50;
|
|
constexpr float PROJECTILE_DAMAGE_LARGE_SCALE = 1.15f;
|
|
constexpr float SHOOTER_VELOCITY_SHARE = 0.4f;
|
|
constexpr float SHOT_VELOCITY_BOOST = 1.2f;
|
|
|
|
// The shots of a fan: each turn spreads to both sides (a straight one once).
|
|
static void fan_velocities_add(std::vector<Vector>& shots, Vector velocity, float spread, const ShotTurn& turn)
|
|
{
|
|
float cosine = turn.cosine * turn.speed;
|
|
float sine = turn.sine * turn.speed * spread;
|
|
if (turn.sine == 0)
|
|
{
|
|
shots.push_back(velocity);
|
|
return;
|
|
}
|
|
shots.push_back(vector_make(velocity.x * cosine - velocity.y * sine, velocity.x * sine + velocity.y * cosine));
|
|
shots.push_back(vector_make(velocity.y * sine + velocity.x * cosine, velocity.y * cosine - velocity.x * sine));
|
|
}
|
|
|
|
// 006cb2e0 Shoots projectiles of params' variant from a position in a mode's spread, then applies params to each:
|
|
// the fans also fall at once and take on part of its motion unless params keeps their fall. The first shot, if any.
|
|
Entity_Projectile* Entity_NPC::fire_projectiles(const Vector& position, const Vector& velocity, ProjectilesMode mode,
|
|
const ProjectileParams& params)
|
|
{
|
|
std::vector<Vector> shots;
|
|
float speed = velocity.x;
|
|
switch (mode)
|
|
{
|
|
case PROJECTILES_SINGLE:
|
|
shots.push_back(velocity);
|
|
break;
|
|
case PROJECTILES_TWO:
|
|
fan_velocities_add(shots, velocity, params.spread, SHOT_16);
|
|
break;
|
|
case PROJECTILES_THREE:
|
|
shots.push_back(velocity);
|
|
fan_velocities_add(shots, velocity, params.spread, SHOT_16_SLOW);
|
|
break;
|
|
case PROJECTILES_THREE_WIDE:
|
|
shots.push_back(velocity);
|
|
fan_velocities_add(shots, velocity, params.spread, SHOT_24);
|
|
break;
|
|
case PROJECTILES_FOUR:
|
|
fan_velocities_add(shots, velocity, params.spread, SHOT_8);
|
|
fan_velocities_add(shots, velocity, params.spread, SHOT_24_SLOW);
|
|
break;
|
|
case PROJECTILES_FIVE:
|
|
shots.push_back(velocity);
|
|
fan_velocities_add(shots, velocity, params.spread, SHOT_12);
|
|
fan_velocities_add(shots, velocity, params.spread, SHOT_24);
|
|
break;
|
|
case PROJECTILES_PLUS:
|
|
shots.insert(shots.end(), {vector_make(speed, 0), vector_make(-speed, 0), vector_make(0, speed),
|
|
vector_make(0, -speed)});
|
|
break;
|
|
case PROJECTILES_CROSS:
|
|
case PROJECTILES_EIGHT:
|
|
{
|
|
float diagonal = speed * DIAGONAL;
|
|
if (mode == PROJECTILES_EIGHT)
|
|
shots.insert(shots.end(), {vector_make(speed, 0), vector_make(-speed, 0), vector_make(0, speed),
|
|
vector_make(0, -speed)});
|
|
shots.insert(shots.end(), {vector_make(diagonal, diagonal), vector_make(-diagonal, diagonal),
|
|
vector_make(diagonal, -diagonal), vector_make(-diagonal, -diagonal)});
|
|
break;
|
|
}
|
|
case PROJECTILES_RING:
|
|
{
|
|
float angle = params.circleAngle;
|
|
int count = (int)(velocity.y + HALF);
|
|
float step = 2 * PI_F / (float)count;
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
angle += step;
|
|
Vector shot = vector_make(std::cos(angle) * speed, std::sin(angle) * speed);
|
|
bool isLimited = !vector_is_zero(params.fireDirectionLimit);
|
|
if (!isLimited ||
|
|
vector_dot(vector_normalized(shot), params.fireDirectionLimit) > params.dotProductLimit)
|
|
shots.push_back(shot);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
std::vector<Entity_Projectile*> projectiles;
|
|
Vector origin = vector_add(position, params.positionOffset);
|
|
for (const Vector& shot : shots)
|
|
{
|
|
Entity* spawned = g_game->Spawn({.position = origin,
|
|
.velocity = shot,
|
|
.spawner = this,
|
|
.type = ENTITY_PROJECTILE,
|
|
.variant = params.variant,
|
|
.seed = Random()});
|
|
if (!spawned) log_printf(LOG_ASSERT, "Failed to spawn Projectile");
|
|
projectiles.push_back(static_cast<Entity_Projectile*>(spawned));
|
|
}
|
|
|
|
bool isFan = mode < PROJECTILES_PLUS;
|
|
for (Entity_Projectile* projectile : projectiles)
|
|
{
|
|
if (!isFan || params.isFallingKept) break;
|
|
projectile->fallingSpeed = PROJECTILE_DEFAULT_FALL_SPEED;
|
|
projectile->fallingAccel = PROJECTILE_DEFAULT_FALL_ACCEL;
|
|
if (mode != PROJECTILES_THREE && mode != PROJECTILES_FOUR && mode != PROJECTILES_FIVE) continue;
|
|
projectile->fallingSpeed -= 1;
|
|
projectile->velocity = vector_add(vector_scale(this->velocity, SHOOTER_VELOCITY_SHARE),
|
|
vector_scale(projectile->velocity, SHOT_VELOCITY_BOOST));
|
|
}
|
|
for (Entity_Projectile* projectile : projectiles) projectile_params_apply(*projectile, params);
|
|
for (Entity_Projectile* projectile : projectiles) fire_projectile_from_params(projectile);
|
|
return projectiles.empty() ? nullptr : projectiles.front();
|
|
}
|
|
|
|
// FireProjectiles as the AIs call it, the shot left unused.
|
|
void Entity_NPC::FireProjectiles(const Vector& position, const Vector& velocity, ProjectilesMode mode,
|
|
const ProjectileParams& params)
|
|
{
|
|
fire_projectiles(position, velocity, mode, params);
|
|
}
|
|
|
|
// Part of 006cb2e0: what params set on a shot fired.
|
|
void Entity_NPC::projectile_params_apply(Entity_Projectile& projectile, const ProjectileParams& params)
|
|
{
|
|
projectile.height += params.heightModifier;
|
|
projectile.fallingSpeed += params.fallingSpeedModifier;
|
|
projectile.fallingAccel += params.fallingAccelModifier;
|
|
projectile.scale = params.scale;
|
|
float damage = params.damage >= 0 ? params.damage : params.scale > PROJECTILE_DAMAGE_LARGE_SCALE ? 2.0f : 1.0f;
|
|
projectile.SetCollisionDamage(damage);
|
|
projectile.velocity = vector_scale(projectile.velocity, params.velocityMulti);
|
|
projectile.projectileFlags |= params.bulletFlags;
|
|
projectile.SetColor(params.color, -1, COLOR_PRIORITY_DEFAULT, false, true);
|
|
projectile.targetPosition = params.targetPosition;
|
|
projectile.homingStrength = params.homingStrength;
|
|
projectile.curvingStrength = params.curvingStrength;
|
|
projectile.acceleration = params.acceleration;
|
|
projectile.wiggleFrameOffset = params.wiggleFrameOffset;
|
|
projectile.changeFlags |= params.changeFlags;
|
|
projectile.changeVelocity = params.changeVelocity;
|
|
projectile.changeTimeout = params.changeTimeout;
|
|
projectile.isRenderedAtGround = params.isRenderedAtGround;
|
|
projectile.renderDepthOffset = params.depthOffset - params.positionOffset.y;
|
|
if (projectile.height < PROJECTILE_HEIGHT_LOW && !(projectile.projectileFlags & PROJECTILE_ANY_HEIGHT_ENTITY_HIT))
|
|
projectile.entityCollisionClass = ENTCOLL_NONE;
|
|
projectile.motionHook = params.motionHook;
|
|
}
|
|
|
|
// 006cb2a0 Hands a fired shot its shooter's champion color, scale and flags (Entity_Projectile::apply_spawn_flags).
|
|
void Entity_NPC::fire_projectile_from_params(Entity_Projectile* projectile)
|
|
{
|
|
projectile->apply_spawn_flags({this, flags, scale, isChampion ? championColorIdx : -1});
|
|
}
|
|
|
|
// Part of 006d2e50: the status effect sprite drawn on the OverlayEffect null, once on a shared body.
|
|
void Entity_NPC::status_overlay_render(const Vector& offset)
|
|
{
|
|
bool isShown =
|
|
statusEffectSprite.isLoaded && statusEffectSprite.animState.animData && statusEffectSprite.animState.isPlaying;
|
|
if (!isShown) return;
|
|
|
|
int nullIndex = sprite.null_index_get("OverlayEffect");
|
|
if (nullIndex < 0)
|
|
{
|
|
if (!config) log_printf(LOG_INFO, "[warn] No OverlayEffect Null found for Entity (%d)\n", type);
|
|
else
|
|
log_printf(LOG_INFO, "[warn] No OverlayEffect Null found for Entity %s with sprite %s\n",
|
|
config->GetName(NAME_LANGUAGE_CURRENT).c_str(), sprite.filename.c_str());
|
|
return;
|
|
}
|
|
const NullFrame* frame = sprite.GetNullFrameById(nullIndex);
|
|
bool isShared = statusEffectSprite.bitflags & STATUS_SHARED;
|
|
if (!frame || !frame->isVisible || (isShared && parent && is_same_segmented_body(nullptr))) return;
|
|
|
|
statusEffectSprite.scale = frame->scale;
|
|
Vector at =
|
|
vector_add(vector_add(render_position_get(vector_add(pos, posOffset), RENDER_SNAPPED), offset), frame->pos);
|
|
statusEffectSprite.Render(SpriteDraw{at, {}, {}});
|
|
}
|
|
|
|
// 006d90e0 Moves the effect a controlled enemy aims with along the controller's input and keeps it in reach. A target
|
|
// effect in mode 2 sits on the enemy (half a step ahead when predicting), one in another mode follows the aim input,
|
|
// and anything else the movement input. A target effect with a reach (its rotation) is pulled back within 40 of it.
|
|
void Entity_NPC::UpdateChildEffectPosition(bool isPredictMovement)
|
|
{
|
|
constexpr int AIM_MODE_SELF = 2;
|
|
constexpr float AIM_SPEED = 8;
|
|
constexpr float AIM_REACH_MARGIN = 40;
|
|
constexpr float AIM_REACH_PULL = 0.1f;
|
|
if (controllerID == -1 || !aimTargetEffect) return;
|
|
|
|
Entity* aim = aimTargetEffect;
|
|
int mode = aim->type == ENTITY_EFFECT ? (int)static_cast<Entity_Effect*>(aim)->varData[2] : 0;
|
|
if (aim->type == ENTITY_EFFECT && mode == AIM_MODE_SELF)
|
|
{
|
|
aim->pos = isPredictMovement ? vector_add(prevPosition, vector_scale(prevVelocity, HALF * speedMultiplier)) : prevPosition;
|
|
aim->velocity = {};
|
|
return;
|
|
}
|
|
|
|
Vector input = aim->type == ENTITY_EFFECT && mode != 0 ? GetControllerInput(0) : GetControllerMovementInput(0);
|
|
if (!vector_is_zero(input)) aim->velocity = vector_add(aim->velocity, vector_scale(input, AIM_SPEED));
|
|
float reach = aim->type == ENTITY_EFFECT ? static_cast<Entity_Effect*>(aim)->rotation : 0;
|
|
if (reach <= 0) return;
|
|
|
|
float limit = std::max(reach - AIM_REACH_MARGIN, 0.0f);
|
|
Vector back = vector_sub(pos, aim->pos);
|
|
float distance = vector_length(back);
|
|
if (distance > limit) aim->velocity = vector_add(aim->velocity, vector_scale(back, (distance - limit) / distance * AIM_REACH_PULL));
|
|
}
|
|
|
|
// 006d7010 With Spider Mod, shows the damage each hit of this frame dealt it as a rising number.
|
|
void Entity_NPC::spawn_damage_numbers()
|
|
{
|
|
bool isShown = type == ENTITY_DAMAGE_NUMBERS_TYPE ||
|
|
(g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SPIDER_MOD_ID, LAZARUS_SHARE_CHECK) &&
|
|
IsActiveEnemy(DEAD_EXCLUDED));
|
|
if (!isShown || !isVisible || sprite.color._tint[3] <= 0 || health <= 0) return;
|
|
if (GetStatusEffectTarget() != this || isInvincible) return;
|
|
|
|
for (DamageEvent& event : damageEvents)
|
|
{
|
|
if (event.damage <= 0) continue;
|
|
|
|
EntitySpawn spawn;
|
|
spawn.seed = Random();
|
|
spawn.velocity = vector_make(0, DAMAGE_NUMBER_SPEED - random_unit() * 2);
|
|
spawn.position = vector_make(pos.x, pos.y - DAMAGE_NUMBER_RISE);
|
|
spawn.type = ENTITY_TEXT;
|
|
spawn.variant = TEXT_DAMAGE;
|
|
|
|
Entity* number = g_game->Spawn(spawn);
|
|
float shown = std::min(std::floor(event.damage * DAMAGE_NUMBER_PRECISION + HALF) / DAMAGE_NUMBER_PRECISION,
|
|
DAMAGE_NUMBER_MAX);
|
|
number->targetPosition = vector_make(shown > 0 ? shown : DAMAGE_NUMBER_MIN, maxHitPoints);
|
|
number->parent = this;
|
|
number->Update();
|
|
}
|
|
}
|
|
|
|
// 006d7230 A shielded boss's shield: the damage of its last frames (shieldFrames) averaged per second, and past
|
|
// maxHitPoints / shieldStrength of it this frame's hits shrink.
|
|
void Entity_NPC::update_damage_history()
|
|
{
|
|
Entity* root = this;
|
|
if (DoesEntityShareStatus())
|
|
while (root->parent) root = root->parent;
|
|
if (!Entity::is_enemy_type(root->type)) root = this;
|
|
Entity_NPC& owner = static_cast<Entity_NPC&>(*root);
|
|
if (owner.shieldStrength <= 0) return;
|
|
|
|
float frameDamage = 0;
|
|
for (const DamageEvent& event : damageEvents)
|
|
if (!(event.damageFlags & DAMAGE_INVINCIBLE)) frameDamage += event.damage;
|
|
if ((int)owner.damageHistory.size() >= owner.shieldFrames) owner.damageHistory.pop_front();
|
|
owner.damageHistory.push_back(frameDamage);
|
|
|
|
float total = 0;
|
|
for (float damage : owner.damageHistory) total += damage;
|
|
float perSecond = total / (float)owner.damageHistory.size() * SHIELD_SECOND;
|
|
float threshold = maxHitPoints / owner.shieldStrength;
|
|
float multiplier = 1;
|
|
if (threshold < perSecond)
|
|
{
|
|
float share = threshold / perSecond;
|
|
multiplier = std::max(SHIELD_BASE - share * SHIELD_FALLOFF, 0.0f) + share;
|
|
}
|
|
|
|
pendingDamage = 0;
|
|
for (DamageEvent& event : damageEvents)
|
|
{
|
|
if (!(event.damageFlags & (DAMAGE_INVINCIBLE | DAMAGE_IGNORE_ARMOR))) event.damage *= multiplier;
|
|
pendingDamage += event.damage;
|
|
}
|
|
}
|
|
|
|
// Part of 006d5400: a sticky enemy bursts into blue spiders for the nearest player, one to three (two to six when
|
|
// an explosion killed it).
|
|
void Entity_NPC::sticky_spiders_spawn()
|
|
{
|
|
int spiders = killDamageFlags & DAMAGE_EXPLOSION ? (int)(Random() % STICKY_SPIDERS_BLAST_RANGE) + 2
|
|
: (int)(Random() % STICKY_SPIDERS_RANGE) + 1;
|
|
for (int i = 0; i < spiders; i++)
|
|
{
|
|
Entity_Player* player = game_nearest_player(pos);
|
|
player->numBlueSpiders++;
|
|
spawn_blue_spider(pos, player, {});
|
|
}
|
|
}
|
|
|
|
// Part of 006d5400: the rewards of a dead enemy that gives any: one in five a black heart for Black Lipstick's
|
|
// sticky kind, and Jar of Flies' count for a fly a player killed, froze or iced.
|
|
void Entity_NPC::kill_rewards_spawn()
|
|
{
|
|
if (HasEntityFlags(FLAG_SPAWN_BLACK_HP) && dropRNG.Next() % BLACK_HEART_CHANCE == 0)
|
|
{
|
|
uint32_t seed = Random();
|
|
g_game->Spawn({.position = room_free_tile_position_find(pos, 0),
|
|
.subType = HEART_BLACK,
|
|
.type = ENTITY_PICKUP,
|
|
.variant = PICKUP_HEART,
|
|
.seed = seed});
|
|
}
|
|
|
|
PlayerManager& players = g_game->playerManager;
|
|
Entity_Player* jarOwner = players.RandomCollectibleOwner(COLLECTIBLE_JAR_OF_FLIES, dropRNG.Next(), nullptr);
|
|
if (!jarOwner || !(HasEntityFlags(FLAG_ADD_JAR_FLY | FLAG_FREEZE) || HasEntityFlags(FLAG_ICE_FROZEN))) return;
|
|
jarOwner->jarFlies = std::min(jarOwner->jarFlies + 1, JAR_OF_FLIES_MAX);
|
|
g_game->hud.refresh_request(HUD_REFRESH_PLAYER);
|
|
}
|
|
|
|
// Part of 006d5400: the items a kill wakes: Contagion's cloud on the first kill of a room or a contagious enemy's,
|
|
// spreading the contagion, Athame's ring by the players' luck, a friendly enemy's recharge of the Friendly Ball in
|
|
// challenge 33, and a captured enemy's soul wisp for Book of Virtues.
|
|
void Entity_NPC::kill_items_trigger()
|
|
{
|
|
PlayerManager& players = g_game->playerManager;
|
|
Entity_Player* contagion = players.FirstCollectibleOwner(COLLECTIBLE_CONTAGION, LAZARUS_SHARE_IGNORE);
|
|
if (contagion && (HasEntityFlags(FLAG_CONTAGIOUS) || !g_game->room->isFirstEnemyDead))
|
|
{
|
|
game_fart({.position = pos, .source = contagion, .radius = CONTAGION_RADIUS, .subType = 1});
|
|
for (Entity* enemy : entity_query_radius(pos, CONTAGION_RADIUS, QUERY_ENEMIES))
|
|
if (enemy != this && enemy->IsVulnerableEnemy(nullptr)) enemy->AddEntityFlags(FLAG_CONTAGIOUS);
|
|
}
|
|
|
|
if (Entity_Player* athame = players.FirstCollectibleOwner(COLLECTIBLE_ATHAME, LAZARUS_SHARE_IGNORE))
|
|
{
|
|
RNG rng;
|
|
rng.SetSeed(initSeed, ATHAME_RNG_SHIFT_INDEX);
|
|
float luck = 0;
|
|
for (Entity_Player* player : players.playerList)
|
|
if (player->variant == PLAYER_VARIANT_PLAYER && !player->isCoopGhost) luck += player->luck;
|
|
if (rng.RandomFloat() < luck * ATHAME_LUCK_CHANCE + ATHAME_BASE_CHANCE)
|
|
{
|
|
Entity_Laser* ring = athame->SpawnMawOfVoid(ATHAME_RING_TIMEOUT);
|
|
ring->pos = pos;
|
|
ring->isDisableFollowParent = true;
|
|
ring->Update();
|
|
}
|
|
}
|
|
|
|
bool isFriendlyKill = IsFriendly() && g_game->challenge == CHALLENGE_POKEY_MANS &&
|
|
players.FirstCollectibleOwner(COLLECTIBLE_FRIEND_BALL, LAZARUS_SHARE_CHECK) &&
|
|
(spawnerType == ENTITY_PLAYER || spawnerType == ENTITY_FAMILIAR) && spawnerEntity &&
|
|
spawnerEntity->type == ENTITY_PLAYER;
|
|
if (isFriendlyKill)
|
|
{
|
|
auto* owner = static_cast<Entity_Player*>(spawnerEntity.get());
|
|
for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++)
|
|
{
|
|
if (owner->activeItems[slot].item != COLLECTIBLE_FRIEND_BALL) continue;
|
|
owner->FullCharge(slot, false, false);
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (!HasEntityFlags(FLAG_FRIENDLY_BALL)) return;
|
|
Entity_Player* virtues = players.RandomCollectibleOwner(COLLECTIBLE_BOOK_OF_VIRTUES, dropRNG.Next(), nullptr);
|
|
EntityConfig_Entity* entry = g_manager->entityConfig.GetEntity(type, variant, 0);
|
|
if (!virtues || virtues->type != ENTITY_PLAYER || !entry) return;
|
|
|
|
int wisp = WISP_SOUL;
|
|
if (entry->tags & ENTITY_TAG_HOMING_SOUL) wisp = WISP_SOUL_HOMING;
|
|
else if (entry->tags & ENTITY_TAG_EXPLOSIVE_SOUL) wisp = WISP_SOUL_EXPLOSIVE;
|
|
else if (entry->tags & ENTITY_TAG_BRIMSTONE_SOUL) wisp = WISP_SOUL_BRIMSTONE;
|
|
virtues->AddWisp(wisp, pos, false, false);
|
|
}
|
|
|
|
// Part of 006d5400: a Brimstone marked enemy's burst marks the vulnerable enemies within 120 for 150 frames, hands
|
|
// them its statuses for 90, hits them for 10, and recharges the Hemoptysis of the players with Brimstone.
|
|
void Entity_NPC::marked_status_spread()
|
|
{
|
|
EntityRef none(nullptr);
|
|
for (Entity* enemy : entity_query_radius(pos, MARK_SPREAD_RADIUS, QUERY_ENEMIES))
|
|
{
|
|
if (enemy == this || !enemy->IsVulnerableEnemy(nullptr)) continue;
|
|
|
|
enemy->AddBrimstoneMark(none, MARK_SPREAD_FRAMES);
|
|
if (HasEntityFlags(FLAG_SLOW))
|
|
enemy->AddSlowing(none, STATUS_SPREAD_FRAMES, slowingAmount, SPREAD_SLOW_COLOR, false);
|
|
if (HasEntityFlags(FLAG_POISON)) enemy->AddPoison(none, STATUS_SPREAD_FRAMES, poisonTickDamage, false);
|
|
if (HasEntityFlags(FLAG_MIDAS_FREEZE)) enemy->AddMidasFreeze(none, STATUS_SPREAD_FRAMES, false);
|
|
else if (HasEntityFlags(FLAG_FREEZE)) enemy->AddFreeze(none, STATUS_SPREAD_FRAMES, false);
|
|
if (HasEntityFlags(FLAG_SHRINK)) enemy->AddShrink(none, STATUS_SPREAD_FRAMES, false, false);
|
|
else if (HasEntityFlags(FLAG_FEAR)) enemy->AddFear(none, STATUS_SPREAD_FRAMES, false);
|
|
if (HasEntityFlags(FLAG_CHARM)) enemy->AddCharmed(none, STATUS_SPREAD_FRAMES, false, false);
|
|
if (HasEntityFlags(FLAG_CONFUSION)) enemy->AddConfusion(none, STATUS_SPREAD_FRAMES, false);
|
|
if (HasEntityFlags(FLAG_BURN)) enemy->AddBurn(none, STATUS_SPREAD_FRAMES, 0, false);
|
|
if (HasEntityFlags(FLAG_MAGNETIZED)) enemy->AddMagnetized(none, STATUS_SPREAD_FRAMES);
|
|
if (HasEntityFlags(FLAG_ICE)) enemy->AddIce(none, STATUS_SPREAD_FRAMES);
|
|
if (HasEntityFlags(FLAG_BAITED)) enemy->AddBaited(none, STATUS_SPREAD_FRAMES);
|
|
enemy->TakeDamage(MARK_SPREAD_DAMAGE, 0, none, MARK_SPREAD_COUNTDOWN);
|
|
}
|
|
MakeBloodPoof(pos, COLOR_DEFAULT, 1);
|
|
|
|
for (Entity_Player* player : g_game->playerManager.playerList)
|
|
{
|
|
Weapon* weapon = player->weapons[0] ? player->weapons[0].get() : player->weapons[1].get();
|
|
if (!weapon || weapon->weaponType != WEAPON_BRIMSTONE) continue;
|
|
player->temporaryEffects.RemoveNullEffect(NULLITEM_HEMOPTYSIS_BOOST, -1);
|
|
player->temporaryEffects.AddNullEffect(NULLITEM_HEMOPTYSIS_BOOST, true, 1);
|
|
}
|
|
}
|
|
|
|
// 006d5400 What happens as it leaves for good: a champion's drop or a boss's death, Rotgut's death, the sticky
|
|
// spiders, its rewards, its removal (Hush stays, drawn on the floor), the items a kill wakes, its record and a
|
|
// marked enemy's spreading statuses.
|
|
void Entity_NPC::trigger_kill_item_effects()
|
|
{
|
|
if (isBoss) g_game->room->TriggerBossDeath(*this);
|
|
else if (isChampion) champion_drop();
|
|
if (type == ENTITY_ROTGUT && variant == ROTGUT_MAGGOT) rotgut_death_spawn_effects(*this);
|
|
if (HasEntityFlags(FLAG_SPAWN_STICKY_SPIDERS)) sticky_spiders_spawn();
|
|
if (!HasEntityFlags(FLAG_NO_REWARD)) kill_rewards_spawn();
|
|
|
|
if (type == ENTITY_HUSH) AddEntityFlags(FLAG_RENDER_FLOOR);
|
|
else Remove();
|
|
kill_items_trigger();
|
|
|
|
g_game->room->isFirstEnemyDead = true;
|
|
room_killed_npc_record(*g_game->room, *this);
|
|
entityRef = nullptr;
|
|
aimTargetEffect = nullptr;
|
|
if (HasEntityFlags(FLAG_BRIMSTONE_MARKED) && HasEntityFlags(FLAG_EXTRA_GORE)) marked_status_spread();
|
|
lua_engine_get().PostNPCDeath(this);
|
|
}
|
|
|
|
// 00447770 Its parent, which only NPCs are.
|
|
Entity_NPC* Entity_NPC::ParentNPC()
|
|
{
|
|
if (parent && !dynamic_cast<Entity_NPC*>(parent.get())) log_printf(LOG_ASSERT, "m_Parent invalid downcast\n");
|
|
return static_cast<Entity_NPC*>(parent.get());
|
|
}
|
|
|
|
// 004567e0 Its child, which only NPCs are.
|
|
Entity_NPC* Entity_NPC::ChildNPC()
|
|
{
|
|
if (child && !dynamic_cast<Entity_NPC*>(child.get())) log_printf(LOG_ASSERT, "m_Child invalid downcast\n");
|
|
return static_cast<Entity_NPC*>(child.get());
|
|
}
|
|
|
|
// 006d8cf0 Removes the effect a controlled enemy aims with.
|
|
void Entity_NPC::ClearChild()
|
|
{
|
|
if (!aimTargetEffect) return;
|
|
aimTargetEffect->Remove();
|
|
aimTargetEffect = nullptr;
|
|
}
|
|
|
|
// 006d0c20
|
|
void Entity_NPC::SetRef_bec(Entity* entity)
|
|
{
|
|
entityRef = entity;
|
|
}
|
|
|
|
// 0060d140
|
|
void Entity_NPC::set_entity_ptr_f54(Entity* entity)
|
|
{
|
|
unknownF54 = entity;
|
|
}
|
|
|
|
// 006b5e20 Holds it at a position for the longer of the countdowns.
|
|
void Entity_NPC::hold_set(int countdown, const Vector& position)
|
|
{
|
|
holdCountdown = std::max(countdown, holdCountdown);
|
|
holdPosition = position;
|
|
}
|
|
|
|
// 009562d0 How far an action is pushed on a controller, or on the first device pushing it for -1, through the key
|
|
// configs. In a run a mod may answer first through MC_INPUT_ACTION. Netplay's remote devices are offline.
|
|
float input_action_value_get(ButtonAction action, int controllerIndex, Entity* entity)
|
|
{
|
|
if (g_manager->state == MANAGER_STATE_GAME && g_luaEngine)
|
|
if (std::optional<float> modValue = lua_engine_get().InputActionValue(entity, action)) return *modValue;
|
|
|
|
KAGE::Input::Manager& input = KAGE::Input::manager;
|
|
for (int i = 0; i < input.get_device_count(); i++)
|
|
{
|
|
std::shared_ptr<KAGE::Input::InputDevice> device = input.get_device(i);
|
|
if (!device || !device->isConnected || (controllerIndex != -1 && device->id != controllerIndex)) continue;
|
|
|
|
float value = 0;
|
|
for (int button : g_manager->keyConfigs.binding_get(*device, action))
|
|
if (button != KAGE::Input::BUTTON_NONE) value = std::max(value, device->button_value(button));
|
|
if (value != 0) return value;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
// The controlling player's movement actions (or its shooting ones) as a vector, read left, right, up, then down.
|
|
static Vector controller_axes_get(Entity_NPC& npc, ButtonAction leftAction)
|
|
{
|
|
float left = input_action_value_get(leftAction, npc.controllerID, &npc);
|
|
float right = input_action_value_get((ButtonAction)(leftAction + 1), npc.controllerID, &npc);
|
|
float up = input_action_value_get((ButtonAction)(leftAction + 2), npc.controllerID, &npc);
|
|
float down = input_action_value_get((ButtonAction)(leftAction + 3), npc.controllerID, &npc);
|
|
return vector_make(right - left, down - up);
|
|
}
|
|
|
|
// Finishes a controlling player's input: snapped to its main axis under the axis aligned seed, none below the
|
|
// deadzone, at most 1 long, and mirrored in the mirror world.
|
|
static Vector controller_input_finish(Vector input, float deadzone)
|
|
{
|
|
Game& game = *g_game;
|
|
if (game.seedEffects.HasSeedEffect(SEED_AXIS_ALIGNED_CONTROLS))
|
|
input = vector_scale(vector_cardinal(input), vector_length(input));
|
|
|
|
float length = vector_length(input);
|
|
if (deadzone > 0 && length < deadzone) return {};
|
|
if (length > 1) input = vector_make(input.x / length, input.y / length);
|
|
|
|
bool isAltStage = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B;
|
|
bool isMirrored = game.stage == 2 || (game.stage == 1 && (game.GetCurses() & CURSE_OF_LABYRINTH));
|
|
if (game.currentDimensionIdx == 1 && isAltStage && isMirrored) input.x = -input.x;
|
|
return input;
|
|
}
|
|
|
|
// 006d8260 Whether the controlling player holds an action, never without one.
|
|
bool Entity_NPC::IsControllerActionPressed(int action)
|
|
{
|
|
return controllerID != -1 && input_is_action_pressed((ButtonAction)action, controllerID, this);
|
|
}
|
|
|
|
// 006d8290 Whether the controlling player pressed an action this frame, never without one.
|
|
bool Entity_NPC::IsControllerActionTriggered(int buttonAction)
|
|
{
|
|
return controllerID != -1 && input_is_action_triggered((ButtonAction)buttonAction, controllerID, this);
|
|
}
|
|
|
|
// 006d82d0 The controlling player's walking input (its shooting one when the controls are swapped), reversed by the
|
|
// reversed controls seed. None without a player or below the deadzone.
|
|
Vector Entity_NPC::GetControllerInput(float deadzone)
|
|
{
|
|
if (controllerID == -1) return {};
|
|
|
|
Vector input = controller_axes_get(*this, isControlSwapped ? ACTION_SHOOT_LEFT : ACTION_LEFT);
|
|
if (g_game->seedEffects.HasSeedEffect(SEED_CONTROLS_REVERSED)) input = vector_make(-input.x, -input.y);
|
|
return controller_input_finish(input, deadzone);
|
|
}
|
|
|
|
// 006d85a0 The controlling player's shooting input (its walking one when the controls are swapped), or its walking
|
|
// input under the seeds that shoot with movement, reversed by the reversed controls seed. None without a player or
|
|
// below the deadzone.
|
|
Vector Entity_NPC::GetControllerMovementInput(float deadzone)
|
|
{
|
|
if (controllerID == -1) return {};
|
|
|
|
Seeds& seeds = g_game->seedEffects;
|
|
Vector input{};
|
|
if (seeds.HasSeedEffect(SEED_SHOOT_IN_MOVEMENT_DIRECTION)) input = GetControllerInput(0);
|
|
else if (seeds.HasSeedEffect(SEED_SHOOT_OPPOSITE_MOVEMENT_DIRECTION))
|
|
input = vector_scale(GetControllerInput(0), -1);
|
|
else
|
|
{
|
|
input = controller_axes_get(*this, isControlSwapped ? ACTION_LEFT : ACTION_SHOOT_LEFT);
|
|
if (seeds.HasSeedEffect(SEED_CONTROLS_REVERSED)) input = vector_make(-input.x, -input.y);
|
|
}
|
|
return controller_input_finish(input, deadzone);
|
|
}
|
|
|
|
// 006d9050 Keeps the controlling player's shooting input as its movement, the last one held unless forced to take
|
|
// any (none included), or none without a player.
|
|
void Entity_NPC::UpdateControllerMovement(bool isForceUpdate)
|
|
{
|
|
if (controllerID == -1)
|
|
{
|
|
controllerMovement = {};
|
|
return;
|
|
}
|
|
|
|
Vector input = GetControllerMovementInput(MOVEMENT_DEADZONE);
|
|
if (isForceUpdate || !vector_is_zero(input)) controllerMovement = input;
|
|
}
|
|
|
|
// 006d9320 Steers it by the controlling player's walking input: the input times the acceleration and its speed
|
|
// multiplier added to its velocity under a friction its multiplier eases, capped at a top speed.
|
|
void Entity_NPC::apply_controller_movement(float acceleration, float drag, float maxSpeed)
|
|
{
|
|
float scaledDrag = drag;
|
|
if (speedMultiplier != 1) scaledDrag = drag / (speedMultiplier + drag - speedMultiplier * drag);
|
|
|
|
Vector input = GetControllerInput(0);
|
|
velocity = vector_add(vector_scale(input, acceleration * speedMultiplier), vector_scale(velocity, scaledDrag));
|
|
float speed = vector_length(velocity);
|
|
if (speed > maxSpeed && speed > 0) velocity = vector_scale(velocity, maxSpeed / speed);
|
|
}
|
|
|
|
// 006d9440 Thrown: a poop pile flies at the throw's velocity from 20 pixels up at the throw's height, stops being kept
|
|
// across rooms, gets the thrown flag (colliding with everything when a player threw it) and splats when fast. Other
|
|
// NPCs are thrown only while held.
|
|
bool Entity_NPC::TryThrow(const EntityRef& source, const Vector& throwVelocity, float height)
|
|
{
|
|
if (type != ENTITY_POOP) return HasEntityFlags(FLAG_HELD);
|
|
|
|
v1 = vector_make(POOP_THROW_HEIGHT, -height);
|
|
velocity = throwVelocity;
|
|
flags = (flags & ~FLAG_PERSISTENT) | FLAG_THROWN;
|
|
if (source.type == ENTITY_PLAYER) entityCollisionClass = ENTCOLL_ALL;
|
|
if (vector_length_squared(throwVelocity) > POOP_THROW_LOUD_SPEED * POOP_THROW_LOUD_SPEED)
|
|
{
|
|
int sound = SOUND_POOPITEM_THROW;
|
|
seed_fart_sound_override(&sound);
|
|
g_manager->sfxManager.Play(sound);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// 006be760 Kills it with no source into its own death animation (Flush! and Lua's KillUnique).
|
|
void Entity_NPC::KillUnique()
|
|
{
|
|
Kill(EntityRef());
|
|
state = NPC_STATE_UNIQUE_DEATH;
|
|
stateFrame = 0;
|
|
}
|
|
|
|
// A thrown spider: a free landing spot within 100 when none is given, a Strider instead over Downpour's and Dross's
|
|
// water, the path cost its landing cell is kept clear with, its first hop's rise and its step toward the spot.
|
|
constexpr float SPIDER_LANDING_SEARCH = 100;
|
|
constexpr float SPIDER_STRIDER_WATER = 0.1f;
|
|
constexpr int SPIDER_LANDING_PATH = 900;
|
|
constexpr int SPIDER_LANDING_PATH_LIMIT = 950;
|
|
constexpr float SPIDER_THROW_RISE = -8;
|
|
constexpr float SPIDER_THROW_STEP = 0.04f;
|
|
|
|
// 006c2750 Throws a spider (or a big one) from position to land at targetPos, marking its landing cell in the room's
|
|
// paths so others steer clear.
|
|
Entity_NPC* Entity_NPC::ThrowSpider(const Vector& position, Entity* spawner, Vector targetPos, bool isBig,
|
|
float yOffset)
|
|
{
|
|
if (vector_is_zero(targetPos))
|
|
targetPos = room_free_pickup_position_find({.position = position, .step = SPIDER_LANDING_SEARCH});
|
|
|
|
int stageId = g_game->GetStageID();
|
|
Room& room = *g_game->room;
|
|
if ((stageId == STAGE_ID_DOWNPOUR || stageId == STAGE_ID_DROSS) && room.waterAmount > SPIDER_STRIDER_WATER)
|
|
return ThrowStrider(position, spawner, targetPos);
|
|
|
|
int gridIndex = room.GetGridIndex(targetPos);
|
|
if (gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS && room.gridPaths[gridIndex] <= SPIDER_LANDING_PATH_LIMIT)
|
|
room.gridPaths[gridIndex] = SPIDER_LANDING_PATH;
|
|
|
|
auto* spider = static_cast<Entity_NPC*>(g_game->Spawn({.position = position,
|
|
.spawner = spawner,
|
|
.type = isBig ? ENTITY_BIG_SPIDER : ENTITY_SPIDER,
|
|
.seed = Random()}));
|
|
spider->state = NPC_STATE_JUMP;
|
|
spider->targetPosition = targetPos;
|
|
spider->v2.y = SPIDER_THROW_RISE;
|
|
spider->entityCollisionClass = ENTCOLL_NONE;
|
|
spider->velocity = vector_scale(vector_sub(targetPos, spider->pos), SPIDER_THROW_STEP);
|
|
spider->v1 = spider->velocity;
|
|
spider->posOffset.y = yOffset;
|
|
return spider;
|
|
}
|
|
|
|
// Part of 006c4b30: an enemy killed while iced does not die. Its killers are rewarded as for a death, then it stands
|
|
// as a frozen statue (ENTITY_FROZEN_ENEMY, keeping its type in its state frame): inside the room, heavy, harmless,
|
|
// untargetable and alone (every pointer to it dropped), flashing cold. A Blood Puppy's familiar holds on to it.
|
|
void Entity_NPC::ice_statue_make()
|
|
{
|
|
trigger_death_rewards();
|
|
for (Entity_Player* player : g_game->playerManager.playerList) player->trigger_npc_death(this);
|
|
toxic_shock_creep_spawn();
|
|
for (EntityPtr* referrer : referrers) referrer->forget();
|
|
referrers.clear();
|
|
|
|
sprite.Stop();
|
|
sprite.StopOverlay();
|
|
RemoveStatusEffects();
|
|
statusEffectSprite.Reset();
|
|
SetCollisionDamage(0);
|
|
entityCollisionClass = ENTCOLL_ALL;
|
|
if (entityGridCollisionClass < GRIDCOLL_WALLS || entityGridCollisionClass == GRIDCOLL_PITSONLY)
|
|
entityGridCollisionClass = GRIDCOLL_WALLS;
|
|
pos = g_game->room->GetClampedPosition(pos, 0);
|
|
if (config->gridCollisionPoints < 1) SetSize(size, sizeMulti, STATUE_GRID_POINTS);
|
|
|
|
mass = STATUE_MASS;
|
|
isDead = false;
|
|
isCanShutDoors = false;
|
|
isBoss = false;
|
|
isInvincible = true;
|
|
AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | FLAG_ICE_FROZEN);
|
|
health = STATUE_HEALTH;
|
|
maxHitPoints = STATUE_HEALTH;
|
|
if (type == ENTITY_BLOOD_PUPPY && parent && parent->IsFamiliar()) static_cast<Entity_Familiar*>(parent.get())->linkedEntity = this;
|
|
spawnerType = 0;
|
|
spawnerVariant = 0;
|
|
spawnerEntity = nullptr;
|
|
parent = nullptr;
|
|
child = nullptr;
|
|
target = nullptr;
|
|
|
|
stateFrame = type;
|
|
type = ENTITY_FROZEN_ENEMY;
|
|
ResetColor();
|
|
SetColor(STATUE_FLASH, STATUE_FLASH_FRAMES, 1, true, true);
|
|
}
|
|
|
|
// 006ca930 A frozen statue's frame: it slows, and each hit it took chips one of its ten points (an explosion or a
|
|
// crush breaks it at once). Shoved, it slides with a trail of cold mist and breaks on the first wall. Broken, it gives
|
|
// its kill's item effects and bursts into ten ice shards that slow, stronger the deeper the floor.
|
|
void Entity_NPC::update_frozen()
|
|
{
|
|
friction *= HALF;
|
|
for (const DamageEvent& hit : damageEvents)
|
|
{
|
|
if (isDead) break;
|
|
if (hit.damageFlags & (DAMAGE_EXPLOSION | DAMAGE_CRUSH) || --health <= 0) Kill(EntityRef());
|
|
}
|
|
damageEvents.clear();
|
|
pendingDamage = 0;
|
|
pendingDamageFlags = 0;
|
|
Entity::Update();
|
|
|
|
if (HasEntityFlags(FLAG_KNOCKED_BACK))
|
|
{
|
|
if ((Random() & 1) == 0)
|
|
{
|
|
Entity* creep = g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL,
|
|
.seed = Random()});
|
|
float scale = random_unit() * HALF + STATUE_TRAIL_SCALE_MIN;
|
|
creep->sprite.scale = vector_make(scale, scale);
|
|
creep->Update();
|
|
}
|
|
auto* mist = static_cast<Entity_Effect*>(g_game->Spawn({.position = pos, .velocity = vector_scale(velocity, STATUE_MIST_DRAG),
|
|
.type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = Random()}));
|
|
mist->rotation = random_unit() * STATUE_MIST_SPIN_RANGE + STATUE_MIST_SPIN_MIN;
|
|
mist->SetTimeout((int)(Random() % STATUE_MIST_FRAMES) + STATUE_MIST_FRAMES);
|
|
mist->posOffset = posOffset;
|
|
mist->sprite.GetLayer(0)->color = STATUE_MIST_COLOR;
|
|
if (isCollidesWithGrid)
|
|
{
|
|
pos = g_game->room->GetClampedPositionImpl(vector_sub(pos, gridCollisionVelocity), STATUE_WALL_MARGIN, STATUE_WALL_MARGIN,
|
|
STATUE_WALL_MARGIN, STATUE_WALL_MARGIN);
|
|
Kill(EntityRef());
|
|
}
|
|
}
|
|
if (!isDead) return;
|
|
|
|
trigger_kill_item_effects();
|
|
float damage = (float)g_game->stage + STATUE_SHARD_DAMAGE;
|
|
float turn = random_unit() * FULL_TURN_DEGREES;
|
|
TearFlags flags;
|
|
flags.set(TEAR_ICE_FLAG);
|
|
flags.set(TEAR_SLOW);
|
|
for (int i = 0; i < STATUE_SHARDS; i++)
|
|
{
|
|
Vector velocity = vector_scale(vector_from_angle(i * FULL_TURN_DEGREES / STATUE_SHARDS + turn), STATUE_SHARD_SPEED);
|
|
auto* shard = static_cast<Entity_Tear*>(g_game->Spawn({.position = pos, .velocity = velocity, .type = ENTITY_TEAR,
|
|
.variant = TEAR_ICE, .seed = Random()}));
|
|
shard->SetCollisionDamage(damage);
|
|
shard->SetTearFlags(flags);
|
|
shard->fallingAccel = STATUE_SHARD_FALL;
|
|
shard->spawnerType = ENTITY_PLAYER;
|
|
shard->Update();
|
|
}
|
|
}
|
|
|
|
// 006d0c60 The room's entities of a type, and of a variant unless -1.
|
|
std::vector<Entity*> Entity_NPC::QueryNPCsType(int type, int variant)
|
|
{
|
|
return entity_query(type, variant);
|
|
}
|
|
|
|
// 006d4db0 Whether a reroll may turn it into another enemy: not when its tags forbid it, for a Lil Haunt still tied
|
|
// to the Haunt, or for a boss.
|
|
bool Entity_NPC::CanReroll()
|
|
{
|
|
if ((config->tags & ENTITY_TAG_NOREROLL) || (type == ENTITY_THE_HAUNT && variant == HAUNT_LIL_VARIANT && parent))
|
|
return false;
|
|
return !IsBoss() && !config->isBoss;
|
|
}
|
|
|
|
// 006d88b0 Hands its controller to another NPC (none to drop it): the players steering it steer that one instead.
|
|
void Entity_NPC::TransferControl(Entity_NPC* target)
|
|
{
|
|
if (target == this) return;
|
|
if (controllerID != -1)
|
|
for (Entity_Player* player : g_game->playerManager.extraPlayers)
|
|
if (player->controllerIndex == controllerID && player->target.get() == this) player->target = target;
|
|
if (target) target->controllerID = controllerID;
|
|
controllerID = -1;
|
|
}
|
|
|
|
// 006d8b20 Shows the aim target a controlled NPC steers, turned by rotation, for two frames more: an aim target that
|
|
// is no effect goes first. A new one (1000.30, never timing out, tinted red) appears only on the input its mode
|
|
// watches (shooting, walking or none).
|
|
void Entity_NPC::SpawnControlTarget(int inputMode, float rotation)
|
|
{
|
|
Entity* target = aimTargetEffect;
|
|
if (target && target->type != ENTITY_EFFECT)
|
|
{
|
|
target->Remove();
|
|
aimTargetEffect = nullptr;
|
|
target = nullptr;
|
|
}
|
|
|
|
if (!target)
|
|
{
|
|
if (inputMode == CONTROL_INPUT_SHOOT && vector_is_zero(GetControllerMovementInput(0))) return;
|
|
if (inputMode == CONTROL_INPUT_WALK && vector_is_zero(GetControllerInput(0))) return;
|
|
|
|
auto* spawned = static_cast<Entity_Effect*>(g_game->Spawn(
|
|
{.position = pos, .spawner = this, .type = ENTITY_EFFECT, .variant = EFFECT_TARGET, .seed = Random()}));
|
|
spawned->timeout = 0;
|
|
spawned->lifespan = 0;
|
|
spawned->Update();
|
|
spawned->sprite.color = CONTROL_TARGET_COLOR;
|
|
aimTargetEffect = spawned;
|
|
target = spawned;
|
|
}
|
|
|
|
auto& effect = static_cast<Entity_Effect&>(*target);
|
|
effect.rotation = rotation;
|
|
effect.varData[1] = CONTROL_TARGET_FRAMES;
|
|
effect.varData[2] = (uint32_t)inputMode;
|
|
}
|
|
|
|
// 006d8d30 Where its aim target stands, or its own position without one.
|
|
Vector Entity_NPC::GetAimTargetPosition()
|
|
{
|
|
return aimTargetEffect ? aimTargetEffect->pos : pos;
|
|
}
|
|
|
|
// 006d8d80 Whether the controlling player lets its aim target be: no input on the one its mode watches (always for
|
|
// the mode watching none, the shooting input for an aim target that is no effect). Never without an aim target.
|
|
bool Entity_NPC::is_controller_input_idle()
|
|
{
|
|
Entity* target = aimTargetEffect;
|
|
if (!target) return false;
|
|
|
|
int mode = target->type == ENTITY_EFFECT ? (int)static_cast<Entity_Effect*>(target)->varData[2] : CONTROL_INPUT_SHOOT;
|
|
if (mode == CONTROL_INPUT_SHOOT) return vector_is_zero(GetControllerMovementInput(MOVEMENT_DEADZONE));
|
|
if (mode == CONTROL_INPUT_WALK) return vector_is_zero(GetControllerInput(MOVEMENT_DEADZONE));
|
|
return mode == CONTROL_INPUT_NONE;
|
|
}
|
|
|
|
// 006d8e40 A controlled NPC's charge bar at value between start and end, hidden when full if asked.
|
|
void Entity_NPC::UpdateChargeBar(float start, float end, float value, bool isHideWhenFull)
|
|
{
|
|
if (controllerID == -1 && !chargeBarSprite.isLoaded) return;
|
|
if (controllerID != -1)
|
|
{
|
|
if (!chargeBarSprite.isLoaded) chargeBarSprite.Load("gfx/chargebar.anm2", GRAPHICS_LOAD);
|
|
chargeBarSprite.GetLayer(2)->isVisible = false;
|
|
if (start == end) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Start and End parameters cannot be the same!");
|
|
|
|
int frame = (int)(std::clamp((value - start) / (end - start), 0.0f, 1.0f) * CHARGE_BAR_FRAMES);
|
|
if (!isHideWhenFull || frame < CHARGE_BAR_FRAMES)
|
|
{
|
|
if (chargeBarSprite.SetAnimation("Charging", SWITCH_KEEP_FRAME) && chargeBarSprite.animState.animData)
|
|
{
|
|
chargeBarSprite.animState.SetFrameFloat((float)frame);
|
|
chargeBarSprite.animState.isPlaying = false;
|
|
}
|
|
chargeBarSprite.color._tint[3] = 1;
|
|
return;
|
|
}
|
|
}
|
|
chargeBarSprite.color._tint[3] = 0;
|
|
}
|
|
|
|
// The bosses a split would kill outright instead, and the ones it only hurts.
|
|
static bool split_is_killed(Entity_NPC& npc)
|
|
{
|
|
switch (npc.type)
|
|
{
|
|
case ENTITY_DINGA:
|
|
case ENTITY_SQUIRT:
|
|
case ENTITY_MEMBRAIN:
|
|
case ENTITY_MOTER:
|
|
case ENTITY_BIG_SPIDER:
|
|
case ENTITY_FISTULA_BIG:
|
|
case ENTITY_FISTULA_MEDIUM:
|
|
case ENTITY_FISTULA_SMALL:
|
|
case ENTITY_BLASTOCYST_BIG:
|
|
case ENTITY_BLASTOCYST_MEDIUM:
|
|
case ENTITY_BLASTOCYST_SMALL:
|
|
case ENTITY_ENVY:
|
|
return true;
|
|
default:
|
|
return npc.championColorIdx == CHAMPION_PULSE_GREEN;
|
|
}
|
|
}
|
|
|
|
static bool split_is_unsplittable(Entity_NPC& npc)
|
|
{
|
|
switch (npc.type)
|
|
{
|
|
case ENTITY_MOM:
|
|
return npc.variant != MOM_STOMP;
|
|
case ENTITY_VISAGE:
|
|
return npc.variant == 0 || npc.variant == 1;
|
|
case ENTITY_MOMS_HEART:
|
|
case ENTITY_SATAN:
|
|
case ENTITY_MEGA_SATAN:
|
|
case ENTITY_MEGA_SATAN_2:
|
|
case ENTITY_ISAAC:
|
|
case ENTITY_THE_LAMB:
|
|
case ENTITY_MAMA_GURDY:
|
|
case ENTITY_DADDYLONGLEGS:
|
|
case ENTITY_PIN:
|
|
case ENTITY_ROTGUT:
|
|
case ENTITY_MOTHER:
|
|
case ENTITY_HUSH:
|
|
case ENTITY_ULTRA_GREED:
|
|
case ENTITY_DOGMA:
|
|
case ENTITY_BEAST:
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Whether a split's halves stand side by side (left and right) rather than at random about it.
|
|
static bool split_is_side_by_side(Entity_NPC& npc)
|
|
{
|
|
if (npc.type == ENTITY_THE_HAUNT || npc.type == ENTITY_LOKI) return npc.variant == 0;
|
|
return npc.type == ENTITY_GURDY || npc.type == ENTITY_MEGA_MAW || npc.type == ENTITY_GATE;
|
|
}
|
|
|
|
// Hands the children of the split boss over to a half: the Lil Haunts, Peep's eyes, Gemini's twins (whose cords go)
|
|
// and Mom's parts, which heal.
|
|
static void split_half_link(Entity_NPC& npc, Entity_NPC& half, int halfIndex, Entity_NPC* first)
|
|
{
|
|
auto adopt = [&](int type, int variant, auto&& isChild) {
|
|
for (Entity* child : entity_query(type, variant))
|
|
if (child->parent.get() == &npc && isChild(*child)) child->parent = ½
|
|
};
|
|
constexpr float SPLIT_HAUNT_DRIFT = 0.3f;
|
|
switch (npc.type)
|
|
{
|
|
case ENTITY_THE_HAUNT:
|
|
if (npc.variant == 0)
|
|
{
|
|
half.state = NPC_STATE_IDLE;
|
|
half.entityCollisionClass = ENTCOLL_ALL;
|
|
half.targetPosition = vector_make(SPLIT_HAUNT_DRIFT, 0);
|
|
}
|
|
else if (npc.variant == HAUNT_LIL_VARIANT && npc.parent)
|
|
{
|
|
half.parent = npc.parent;
|
|
if (halfIndex != 0) static_cast<Entity_NPC*>(half.parent.get())->i1++;
|
|
half.spawnFrame = npc.spawnFrame;
|
|
half.state = npc.state;
|
|
}
|
|
return;
|
|
case ENTITY_PEEP:
|
|
half.i1 = npc.i1;
|
|
half.sprite.ReplaceSpritesheet(0, npc.sprite.GetLayer(0)->spriteSheetPath);
|
|
half.sprite.LoadGraphics();
|
|
adopt(ENTITY_PEEP, -1, [](Entity& eye) { return eye.variant >= PEEP_EYE_FIRST; });
|
|
return;
|
|
case ENTITY_GEMINI:
|
|
if (npc.variant != 0 && npc.variant != GEMINI_STEVEN && npc.variant != GEMINI_BLIGHTED_OVUM) return;
|
|
half.state = NPC_STATE_MOVE;
|
|
for (Entity* cord : entity_query(ENTITY_GEMINI, GEMINI_CORD))
|
|
if (cord->parent.get() == &npc) cord->Remove();
|
|
if (npc.variant == GEMINI_BLIGHTED_OVUM) adopt(ENTITY_GEMINI, GEMINI_BLIGHTED_OVUM_BABY, [](Entity&) { return true; });
|
|
return;
|
|
case ENTITY_MASK_OF_INFAMY:
|
|
half.state = NPC_STATE_ATTACK2;
|
|
return;
|
|
case ENTITY_WAR:
|
|
if (npc.variant != 1) return;
|
|
half.spawnerType = 0;
|
|
half.spawnerVariant = 0;
|
|
return;
|
|
case ENTITY_PESTILENCE:
|
|
if (npc.i1 == 0) return;
|
|
half.i1 = 1;
|
|
half.sprite.GetLayer(1)->isVisible = false;
|
|
return;
|
|
case ENTITY_FAMINE:
|
|
if (npc.state == NPC_STATE_ATTACK2) half.state = NPC_STATE_ATTACK2;
|
|
return;
|
|
case ENTITY_REAP_CREEP:
|
|
half.state = npc.state;
|
|
half.entityGridCollisionClass = GRIDCOLL_WALLS;
|
|
half.sprite.isOverlayRenderFirst = true;
|
|
return;
|
|
case ENTITY_MOM:
|
|
if (halfIndex != 0)
|
|
{
|
|
half.parent = first;
|
|
return;
|
|
}
|
|
for (Entity* part : entity_query(ENTITY_MOM, -1))
|
|
{
|
|
if (part == &npc || part->parent.get() != &npc) continue;
|
|
part->health = part->maxHitPoints;
|
|
part->parent = ½
|
|
}
|
|
return;
|
|
default:
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Spawns one half of a split boss beside it, a champion like it, with 40 percent of its health and two thirds of its
|
|
// size. Horny Boys split into Hornfel and Loki, Loki into Lokii. Hornfel out of doors to run to turns sad.
|
|
static Entity_NPC* split_half_spawn(Entity_NPC& npc, RNG& rng, int halfIndex, Entity_NPC* first)
|
|
{
|
|
constexpr float SPLIT_SPREAD = 0.5f;
|
|
constexpr float SPLIT_HALF_SCALE = 0.66f;
|
|
constexpr float SPLIT_HALF_HEALTH = 0.4f;
|
|
constexpr float SPLIT_SCORE = 0.5f;
|
|
float spread = npc.size * SPLIT_SPREAD;
|
|
Vector offset = split_is_side_by_side(npc) ? vector_make(halfIndex == 0 ? -spread : spread, 0)
|
|
: vector_scale(RandomVector(rng.Next()), spread);
|
|
int type = npc.type;
|
|
int variant = npc.variant;
|
|
if (type == ENTITY_LOKI && variant == 0) variant = LOKII;
|
|
else if (type == ENTITY_HORNY_BOYS)
|
|
{
|
|
type = halfIndex == 0 ? ENTITY_HORNFEL : ENTITY_LOKI;
|
|
variant = 0;
|
|
}
|
|
|
|
auto* half = static_cast<Entity_NPC*>(g_game->Spawn(
|
|
{.position = vector_add(npc.pos, offset), .spawner = &npc, .subType = npc.subtype, .type = type, .variant = variant, .seed = rng.Next()}));
|
|
if (npc.isChampion) half->Morph(type, variant, npc.subtype, npc.championColorIdx);
|
|
half->scoreMultiplier = npc.scoreMultiplier * SPLIT_SCORE;
|
|
if (half->type == ENTITY_BLOOD_PUPPY)
|
|
{
|
|
half->parent = npc.parent;
|
|
// The original reads the parent's type even without one, which this skips.
|
|
if (halfIndex == 0 && npc.parent && npc.parent->type == ENTITY_FAMILIAR)
|
|
static_cast<Entity_Familiar*>(npc.parent.get())->linkedEntity = half;
|
|
g_game->room->entityList.AddPersistentEntity(half);
|
|
}
|
|
if (npc.type == ENTITY_LOKI && npc.variant == 0) half->sprite.isFlipX = halfIndex != 0;
|
|
else if (npc.type != ENTITY_HORNY_BOYS)
|
|
{
|
|
half->SetScale(npc.scale * SPLIT_HALF_SCALE);
|
|
half->scaleMulti = npc.scaleMulti * SPLIT_HALF_SCALE;
|
|
}
|
|
if (half->type == ENTITY_HORNFEL && entity_query(ENTITY_HORNFEL_DOOR, -1).empty())
|
|
{
|
|
if (half->minecart) half->minecart->Remove();
|
|
half->state = NPC_STATE_SUMMON;
|
|
npc_anim_loop(half->sprite, "Sad");
|
|
half->entityGridCollisionClass = GRIDCOLL_GROUND;
|
|
}
|
|
half->maxHitPoints = npc.maxHitPoints * SPLIT_HALF_HEALTH;
|
|
half->health = npc.health * SPLIT_HALF_HEALTH;
|
|
half->hitPointsMulti = npc.hitPointsMulti * SPLIT_HALF_HEALTH;
|
|
split_half_link(npc, *half, halfIndex, first);
|
|
|
|
half->spawnGridIndex = npc.spawnGridIndex;
|
|
if (npc.HasEntityFlags(FLAG_AMBUSH)) half->AddEntityFlags(FLAG_AMBUSH);
|
|
return half;
|
|
}
|
|
|
|
// 006d97e0 Meat Cleaver's cut: splits the enemy into two halves (split_half_spawn) and removes it in a burst of blood.
|
|
// The Fallen (outside Satan's fight) only drops to 40 percent, some bosses die outright and the ones too small or
|
|
// too big to split are only hurt, the split worm bodies and Visage's and the Scourge's chains for twice their health.
|
|
// Conquest dies unless it is a boss. With a sound it shakes the screen. A dead enemy does nothing.
|
|
bool Entity_NPC::split(float damage, const EntityRef& source, bool isPlaySound)
|
|
{
|
|
constexpr float SPLIT_LEAST_SCALE = 0.5f;
|
|
constexpr float FALLEN_SPLIT_HEALTH = 0.4f;
|
|
constexpr int SPLIT_HURT_COUNTDOWN = 30;
|
|
constexpr int SPLIT_SHAKE = 15;
|
|
constexpr uint32_t SPLIT_SHIFT_INDEX = 22;
|
|
if (isDead || !isExists) return false;
|
|
|
|
if (isPlaySound) npc_sound_play(SOUND_MEATY_DEATHS, 1, 2, 1);
|
|
bool isHurtOnly = scale < SPLIT_LEAST_SCALE || split_is_unsplittable(*this);
|
|
bool isChain = (type == ENTITY_VISAGE && variant == VISAGE_CHAIN) || (type == ENTITY_SCOURGE && variant == SCOURGE_CHAIN);
|
|
if (isHurtOnly) TakeDamage(damage, 0, source, SPLIT_HURT_COUNTDOWN);
|
|
else if (type == ENTITY_FALLEN && variant == 0 && spawnerType != ENTITY_FALLEN)
|
|
health = std::min(health, maxHitPoints * FALLEN_SPLIT_HEALTH);
|
|
else if (is_same_segmented_body(nullptr) || isChain) TakeDamage(health + health, 0, source, SPLIT_HURT_COUNTDOWN);
|
|
else if (split_is_killed(*this) || (type == ENTITY_WAR && variant == 1 && !IsBoss())) Kill(EntityRef());
|
|
else
|
|
{
|
|
RNG rng;
|
|
rng.SetSeed(initSeed, SPLIT_SHIFT_INDEX);
|
|
Entity_NPC* first = split_half_spawn(*this, rng, 0, nullptr);
|
|
split_half_spawn(*this, rng, 1, first);
|
|
BloodExplode();
|
|
Remove();
|
|
}
|
|
if (isPlaySound) game_shake_screen(SPLIT_SHAKE);
|
|
return true;
|
|
}
|
|
|
|
// 006da530 While a player holds Guppy's Eye, a lit fireplace or a living shopkeeper shows the loot it would drop as
|
|
// ghosts. Otherwise, or with nothing to drop, the ghosts shown before go.
|
|
void Entity_NPC::UpdatePickupGhosts()
|
|
{
|
|
bool isLootHolder = (type == ENTITY_FIREPLACE && health > 1) || (type == ENTITY_SHOPKEEPER && !isDead);
|
|
if (isLootHolder && g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_GUPPYS_EYE_ID, LAZARUS_SHARE_CHECK))
|
|
{
|
|
LootList loot = type == ENTITY_FIREPLACE ? fireplace_get_loot(false) : LootList{shopkeeper_loot_get(*this, false)};
|
|
if (!loot.entries.empty())
|
|
{
|
|
pickupGhostsEntity = Entity_Effect::CreateLootPreview(
|
|
&loot, pos, this, static_cast<Entity_Effect*>(pickupGhostsEntity.get()));
|
|
return;
|
|
}
|
|
}
|
|
if (pickupGhostsEntity) pickupGhostsEntity->Remove();
|
|
}
|
|
|