diff --git a/generated-src/classes.h b/generated-src/classes.h index 0a452b5..7a49eaf 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -134,6 +134,7 @@ struct AnimationState; struct AnmCache; struct AnmFileData; struct Attraction; +struct AxisWalkAnims; struct Backdrop; struct BackdropConfig; struct BackwardsStageDesc; @@ -216,6 +217,7 @@ struct DebugRenderer; struct DeliriousBoss; struct DestinationQuad; struct Devolve; +struct DreamCatcherPage; struct EffectBehaviour; struct EmoteWheel; struct Entity; @@ -385,6 +387,7 @@ struct KAGE_ReferenceCount_ImageBase; struct KColor; struct KerningPair; struct KeyConfigs; +struct KilledNpc; struct KnifeHit; struct KnifeShot; struct KnifeThrow; @@ -557,6 +560,7 @@ struct RevivePlayerMenu; struct RichText; struct RichTextIcon; struct RichTextSpan; +struct RockDrop; struct Room; struct RoomClear; struct RoomConfig; @@ -677,6 +681,8 @@ struct WeightedOutcomePicker; struct WheelPortrait; struct Window; struct WispEntry; +struct WispShot; +struct WispTear; struct WispTears; struct XY; struct _CONTEXT; @@ -935,13 +941,6 @@ typedef void * _onexit_t; typedef int errno_t; typedef size_t rsize_t; -struct AbyssLocustData { - virtual ~AbyssLocustData(); // 0060d5e0 slot 0 ::FUN_0060d5e0 - - uint8_t _pad_0x4[0x54]; -}; -LAYOUT32(sizeof(AbyssLocustData) == 0x58); - struct std_string { char _buf[16]; uint32_t _size; @@ -3323,13 +3322,6 @@ struct Menu_OnlineMode { }; -struct MrMeData { - virtual ~MrMeData(); // 005cd8c0 slot 0 ::FUN_005cd8c0 - - uint8_t _pad_0x4[0x128]; -}; -LAYOUT32(sizeof(MrMeData) == 0x12c); - struct Multiplayer { static void set_service_provider(int providerType); // 00a29370 static void flush_channel(int *param_1); // 00a29bb0 @@ -5724,7 +5716,6 @@ int FUN_00436120(int param_1); // 00436120 void FUN_00436190(); // 00436190 void FUN_00436200(uint32_t param_1); // 00436200 void FUN_00436210(uint32_t param_1); // 00436210 -void FUN_00436260(); // 00436260 void FUN_00436fb0(); // 00436fb0 void FUN_0043e990(RNG *param_1); // 0043e990 void FUN_0043e9f0(); // 0043e9f0 @@ -5831,7 +5822,6 @@ void FUN_004d7450(void *param_1, int param_2); // 004d7450 void Catch_All_004d7683(); // 004d7683 void FUN_004d76c0(); // 004d76c0 bool FUN_004d7760(); // 004d7760 -Entity * spawn_small_maggot(Vector *position, float height, Vector *velocity, float heightVelocity); // 004d8b50 void FUN_004e46b0(); // 004e46b0 void FUN_004e46c0(); // 004e46c0 bool FUN_004e47b0(); // 004e47b0 @@ -5940,7 +5930,6 @@ void FUN_005c7ef0(int param_1); // 005c7ef0 void FUN_005c7f20(int param_1); // 005c7f20 void everything_jar_crack_the_sky_timer(int param_1); // 005c8020 void everything_jar_shopkeeper_rain_timer(int param_1); // 005c83f0 -int FUN_005c92f0(); // 005c92f0 void FUN_005ca566(uint32_t param_1, uint32_t param_2, int param_3); // 005ca566 void FUN_005ca880(); // 005ca880 void FUN_005cba20(); // 005cba20 @@ -6006,7 +5995,6 @@ Vector * FUN_005cd7e0(Vector *param_1); // 005cd7e0 void FUN_005cd800(); // 005cd800 AchievementOverlay * FUN_005cd810(); // 005cd810 void FUN_005cd840(uint32_t param_1); // 005cd840 -void FUN_005cd850(); // 005cd850 void FUN_005cd8c0(uint8_t param_1); // 005cd8c0 void FUN_005cda90(); // 005cda90 void FUN_00607540(); // 00607540 @@ -6069,18 +6057,15 @@ bool FUN_0060d1c0(uint32_t param_1); // 0060d1c0 uint32_t FUN_0060d1e0(); // 0060d1e0 void FUN_0060d1f0(uint32_t param_1); // 0060d1f0 void FUN_0060d400(); // 0060d400 -void FUN_0060d5e0(uint8_t param_1); // 0060d5e0 uint32_t FUN_0060dae0(); // 0060dae0 void FUN_0062e0e0(int param_1); // 0062e0e0 void FUN_00631a00(float *param_1, uint32_t param_2, float *param_3); // 00631a00 -void familiar_wisp_pick_tear_color(RNG *rng, int *outVariant, BitSet128 *outFlags); // 00633990 void FUN_00638e20(); // 00638e20 void FUN_006395e0(Vector *param_1, int *param_2, int param_3, int param_4, int param_5, float param_6, int param_7, int param_8, Entity *param_9, int param_10); // 006395e0 void FUN_0063b240(); // 0063b240 void FUN_0063c060(int param_1); // 0063c060 void FUN_0063e180(); // 0063e180 void FUN_006431b0(); // 006431b0 -void anm2_apply_gfx_overrides(std_string *gfxSpec, std_string *unusedString, ANM2 *anm2); // 0064aab0 void FUN_0064b6a0(); // 0064b6a0 int FUN_0064ccf0(); // 0064ccf0 int level_get_room_neighbors(uint32_t roomIndex, uint32_t *outNeighbors); // 0064cd30 @@ -6314,7 +6299,6 @@ uint8_t FUN_006b8440(); // 006b8440 uint8_t FUN_006b8490(); // 006b8490 void FUN_006b84c0(); // 006b84c0 void FUN_006b8580(); // 006b8580 -Entity * spawn_gfuel_explosion(); // 006b9450 int FUN_006c4a90(); // 006c4a90 void FUN_006d6650(); // 006d6650 uint8_t is_local_player_owned(void *self); // 006d8e10 @@ -6412,7 +6396,6 @@ uint32_t FUN_00710f70(int param_1); // 00710f70 void FUN_00711530(int param_1); // 00711530 uint32_t FUN_00711740(); // 00711740 void FUN_00718ed0(uint32_t param_1); // 00718ed0 -uint32_t FUN_00718ee0(); // 00718ee0 void FUN_0071df70(uint8_t param_1); // 0071df70 void FUN_00721e60(int param_1, int param_2, int param_3, int param_4, int param_5, int param_6); // 00721e60 void FUN_00722020(int param_1); // 00722020 @@ -6675,7 +6658,6 @@ uint32_t FUN_00813420(int param_1, int param_2); // 00813420 uint32_t FUN_0081e220(); // 0081e220 void FUN_0081fae0(uint32_t *param_1); // 0081fae0 void FUN_00821940(); // 00821940 -uint32_t FUN_00827180(float *param_1); // 00827180 void FUN_00827f30(); // 00827f30 void FUN_00828010(uint32_t *param_1); // 00828010 void FUN_00828050(short *param_1); // 00828050 @@ -20771,16 +20753,12 @@ void lil_haunt(Entity_Familiar *familiar, int unused); // 0061d030 void bumbo(Entity_Familiar *familiar); // 0062f7f0 void lil_spewer(Entity_Familiar *familiar); // 006384a0 Entity_Knife * sprinkler_spawn_knife(Entity_Familiar *familiar); // 0063b070 -void tinytoma(Entity_Familiar *familiar); // 00642cb0 void variant_204(Entity_Familiar *familiar); // 00644780 -void lil_dumpy(Entity_Familiar *familiar); // 006468a0 -void apollyons_best_friend(Entity_Familiar *familiar); // 00647320 int worm_friend(Entity_Familiar *familiar); // 0064bfa0 void star_of_bethlehem(Entity_Familiar *familiar); // 0064d5f0 void vanishing_twin(Entity_Familiar *familiar); // 00650610 } namespace FamiliarHelper { -void wisp_mine_crafter_update(Entity_Familiar *wisp); // 0043d850 Entity_Laser * sprinkler_fire_laser(Entity_Familiar *familiar, float angle, float distance); // 0063acf0 void fly_head_pathfind_move(Entity_Familiar *familiar); // 0063d570 } @@ -20859,37 +20837,17 @@ void ENTITY_GUTTED_FATTY(Entity_NPC *npc); // 004e0dd0 uint32_t ENTITY_GAPER_L2(Entity_NPC *npc); // 004e2b40 void ENTITY_CHARGER_L2(Entity_NPC *npc); // 004e38c0 void ENTITY_CANDLER(Entity_NPC *npc); // 004e4970 -void ENTITY_WHIPPER(Entity_NPC *npc); // 004e5170 -void ENTITY_GRUDGE(Entity_NPC *npc); // 004e6570 uint32_t ENTITY_BISHOP(Entity_NPC *npc); // 004e7ea0 -uint8_t * ENTITY_BABY_BEGOTTEN(Entity_NPC *npc); // 004e8380 -void ENTITY_REVENANT(Entity_NPC *npc); // 004ecc10 -void ENTITY_CULTIST(Entity_NPC *npc); // 004ed840 -void ENTITY_CLICKETY_CLACK(Entity_NPC *npc); // 004efb90 -void ENTITY_MAZE_ROAMER(Entity_NPC *npc); // 004f1ec0 -void ENTITY_GOAT(Entity_NPC *npc); // 004f2c20 void ENTITY_BALL_AND_CHAIN(Entity_NPC *npc); // 004f4730 -void ENTITY_POOFER(Entity_NPC *npc); // 004f64e0 -void ENTITY_MOCKULUS(Entity_NPC *npc); // 004f76f0 -void ENTITY_MORNINGSTAR(Entity_NPC *npc); // 004f7e60 -void ENTITY_DANNY(Entity_NPC *npc); // 004fbd10 void ENTITY_GYRO(Entity_NPC *npc); // 004ff620 void ENTITY_BOUNCER(Entity_NPC *npc); // 00501f30 -void ENTITY_FLESH_MAIDEN(Entity_NPC *npc); // 00502980 -void ENTITY_BOMBGAGGER(Entity_NPC *npc); // 00503300 -void ENTITY_DUST(Entity_NPC *npc); // 00503af0 -void ENTITY_BIG_BONY(Entity_NPC *npc); // 005041d0 -void ENTITY_DUSTY_DEATHS_HEAD(Entity_NPC *npc); // 00504a40 -void ENTITY_NECRO(Entity_NPC *npc); // 005052a0 void ENTITY_STONE_EYE(Entity_NPC *npc); // 00505d00 -void ENTITY_HEART(Entity_NPC *npc); // 0051f2f0 void ENTITY_DOPLE(Entity_NPC *npc); // 00525650 void ENTITY_BLACK_MAW(Entity_NPC *npc); // 0053b2f0 float ENTITY_TARBOY(Entity_NPC *npc); // 005442a0 void ENTITY_FISTULOID(Entity_NPC *npc); // 00545f70 void ENTITY_MR_MINE(Entity_NPC *npc); // 005492c0 void ENTITY_BUTT_SLICKER(Entity_NPC *npc); // 0054d250 -void ENTITY_SWARM_SPIDER(Entity_NPC *npc); // 005505c0 void ENTITY_COHORT(Entity_NPC *npc); // 005513a0 void ENTITY_GENERIC_PROP(Entity_NPC *npc); // 00551d30 void ENTITY_SHADY(Entity_NPC *npc); // 005522d0 @@ -20897,17 +20855,9 @@ void ENTITY_BLOOD_PUPPY(Entity_NPC *npc); // 00552d30 void ENTITY_PEEPER_FATTY(Entity_NPC *npc); // 005562b0 int ENTITY_WILLO_L2_find_target(Entity_NPC *npc); // 005591c0 void ENTITY_WILLO_L2(Entity_NPC *npc); // 005593c0 -Entity_Projectile * ENTITY_BUBBLES(Entity_NPC *npc); // 0055ad20 -void ENTITY_SMALL_LEECH(Entity_NPC *npc); // 0055b740 uint32_t ENTITY_POLTY(Entity_NPC *npc); // 0055d230 -void ENTITY_FLY_TRAP(Entity_NPC *npc); // 00560ca0 -void ENTITY_FLY_orbit_parent(Entity_NPC *npc); // 00561580 -void ENTITY_FARTIGAN(Entity_NPC *npc); // 00561a20 -void ENTITY_POOT_MINE(Entity_NPC *npc); // 00562290 -void ENTITY_DUMP(Entity_NPC *npc); // 00562f00 void ENTITY_BLOATY(Entity_NPC *npc); // 00563da0 void ENTITY_FISSURE(Entity_NPC *npc); // 00564f30 -void ENTITY_HENRY(Entity_NPC *npc); // 00565bc0 void ENTITY_MOTHER_worm(Entity_NPC *npc); // 00565e00 void ENTITY_MOTHER_ball(Entity_NPC *npc); // 00566810 void ENTITY_MOTHER_ball_burst(Entity_NPC *npc); // 00567d50 diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index 64fb976..e31210a 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -2844,63 +2844,6 @@ uint8_t NpcHelper::candler_is_free_cell(Vector *position) return 0; } -// 004e50d0 -uint8_t NpcHelper::whipper_is_target(Entity_NPC *npc, Entity *entity) -{ - int iVar1; - uint8_t bVar2; - bool isHostile; - - isHostile = (npc->_flags & 0x20000100) == 0; - if (GHIDRA_CAST(entity) != npc) { - iVar1 = entity->_type; - if (iVar1 == 4) { - if (isHostile) { - return 1; - } - } - else if (isHostile) { - if (iVar1 == 1) { - return 1; - } - if (iVar1 != 3) { - return 0; - } - iVar1 = entity->_variant; - if (iVar1 == 0x3e) { - return 1; - } - if (iVar1 == 0x43) { - return 1; - } - if (iVar1 == 0xc9) { - return 1; - } - if (iVar1 == 0xe4) { - return 1; - } - if (iVar1 == 0xee) { - return 1; - } - if (iVar1 == 0xce) { - return 1; - } - if (iVar1 == 0xed) { - return 1; - } - if (iVar1 == 0xd3) { - return 1; - } - return 0; - } - bVar2 = Entity::IsVulnerableEnemy(entity,GHIDRA_CAST(0x0)); - if (bVar2 != 0) { - return 1; - } - } - return 0; -} - // 00501e10 void NpcHelper::bouncer_death_gib(Entity_Effect *timer) { @@ -3506,122 +3449,6 @@ uint8_t NpcHelper::tarboy_is_creep_near(Entity_NPC *npc, Vector *position) return 0; } -// 0055a850 -void NpcHelper::bubbles_death_geyser_tick(Entity *owner) -{ - uint32_t projVariant; - uint32_t rngResult; - uint32_t rngFactor; - Entity_Projectile *projectile; - float originX; - float cosAngle; - float randScale; - int highShotsLeft; - int lowShotsLeft; - Vector local_18; - Vector local_10; - float originX; - float originY; - - originX = (owner->_pos).x; - originY = (owner->_pos).y; - projVariant = Level::GetStageID(); - if (projVariant == 0x1b) { - projVariant = 4; - } - else if (projVariant == 0x1c) { - projVariant = 3; - } - else { - projVariant = 0; - } - lowShotsLeft = 2; - do { - rngResult = Random(); - originX = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - originX = originX + originX; - cosAngle = cos(originX); - originX = sin(originX); - rngResult = Random(); - rngFactor = Random(); - randScale = (float)((double)GHIDRA_INT(rngFactor) + __uint_to_double_fixup[-(GHIDRA_INT(rngFactor) >> 0x1f)]) - * 2.3283064e-10; - local_18.y = randScale * originX * 2.8; - local_18.x = randScale * cosAngle * 2.8; - rngFactor = Random(); - randScale = (float)((double)GHIDRA_INT(rngFactor) + __uint_to_double_fixup[-(GHIDRA_INT(rngFactor) >> 0x1f)]) - * 2.3283064e-10; - local_10.x = cosAngle * 5.0 * randScale + originX; - local_10.y = originX * 5.0 * randScale + originY; - projectile = (Entity_Projectile *) - Game::SpawnEx(g_game,9,projVariant,&local_10,&local_18,GHIDRA_CAST(0x0),0,rngResult,0) - ; - projectile->_spawnerType = 0x326; - rngResult = Random(); - projectile->_fallingAccel = 2.0; - projectile->_scale = - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 1.4; - rngResult = Random(); - projectile->_fallingSpeed = - -15.0 - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) - * 2.3283064e-10 * 60.0; - rngResult = Random(); - projectile->_height = - -23.0 - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) - * 2.3283064e-10 * 15.0; - Entity_Projectile::apply_spawn_flags - (projectile,*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(owner[1])) + 0x40)))), - *GHIDRA_CAST((owner[1]._sprite._animDefaultName._buf + 8)),owner->_flags,GHIDRA_CAST(0x0)); - (**(code **)(*GHIDRA_CAST(projectile) + 0xc))(); - lowShotsLeft = lowShotsLeft + -1; - } while (lowShotsLeft != 0); - highShotsLeft = 2; - do { - rngResult = Random(); - originX = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - originX = originX + originX; - cosAngle = cos(originX); - originX = sin(originX); - rngResult = Random(); - rngFactor = Random(); - randScale = (float)((double)GHIDRA_INT(rngFactor) + __uint_to_double_fixup[-(GHIDRA_INT(rngFactor) >> 0x1f)]) - * 2.3283064e-10; - local_10.y = randScale * originX * 2.8; - local_10.x = randScale * cosAngle * 2.8; - rngFactor = Random(); - randScale = (float)((double)GHIDRA_INT(rngFactor) + __uint_to_double_fixup[-(GHIDRA_INT(rngFactor) >> 0x1f)]) - * 2.3283064e-10; - local_18.x = cosAngle * 5.0 * randScale + originX; - local_18.y = originX * 5.0 * randScale + originY; - projectile = (Entity_Projectile *) - Game::SpawnEx(g_game,9,projVariant,&local_18,&local_10,GHIDRA_CAST(0x0),0,rngResult,0) - ; - projectile->_spawnerType = 0x326; - rngResult = Random(); - projectile->_fallingAccel = 2.0; - projectile->_scale = - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 1.4; - rngResult = Random(); - projectile->_fallingSpeed = - -15.0 - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) - * 2.3283064e-10 * 60.0; - rngResult = Random(); - projectile->_height = - -23.0 - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) - * 2.3283064e-10 * 1000.0; - Entity_Projectile::apply_spawn_flags - (projectile,*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(owner[1])) + 0x40)))), - *GHIDRA_CAST((owner[1]._sprite._animDefaultName._buf + 8)),owner->_flags,GHIDRA_CAST(0x0)); - (**(code **)(*GHIDRA_CAST(projectile) + 0xc))(); - highShotsLeft = highShotsLeft + -1; - } while (highShotsLeft != 0); - return; -} - // 0055d070 uint8_t NpcHelper::polty_target_set(int gridIndex) { @@ -7210,32 +7037,6 @@ LAB_005adfbb: return 1; } -// 006be7e0 -uint8_t NpcHelper::is_target_valid(Entity *target) -{ - uint8_t bVar1; - bool isTargetable; - - if ((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x168)) & 0x100) == 0) { - if (target->_type != 1) { - return 0; - } - bVar1 = Entity_Player::IsInvisible(GHIDRA_CAST(target)); - isTargetable = bVar1 == 0; - } - else { - bVar1 = Entity::IsVulnerableEnemy(target,GHIDRA_CAST(0x0)); - if (bVar1 == 0) { - return 0; - } - isTargetable = (target->_flags & 0x20000000) == 0; - } - if (isTargetable) { - return 1; - } - return 0; -} - // 006d0ec0 void NpcHelper::fireplace_moveable_update(Entity_NPC *npc) { diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index b18ce2e..b5e7c60 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -8220,7 +8220,6 @@ uint32_t _DAT_e76476a4{}; uint32_t register0x00000010{}; uint32_t register0x0000001e{}; -AbyssLocustData::~AbyssLocustData() { generated_stub("AbyssLocustData::~AbyssLocustData 0060d5e0"); } uint8_t AfterbirthPersistentGameData::check_header(void *stream) { generated_stub("AfterbirthPersistentGameData::check_header 0041d670"); } BitSet128 * BitSet128::operator_and(BitSet128 *outResult, BitSet128 *a, BitSet128 *b) { generated_stub("BitSet128::operator_and 00417170"); } uint8_t BitSet128::IsNonZero() { generated_stub("BitSet128::IsNonZero 004171b0"); } @@ -9174,7 +9173,6 @@ void Menu_OnlineMode::play_idle_animation() { generated_stub("Menu_OnlineMode::p void Menu_OnlineMode::update_mode_select() { generated_stub("Menu_OnlineMode::update_mode_select 008ccc70"); } void Menu_OnlineMode::update_seed_input() { generated_stub("Menu_OnlineMode::update_seed_input 008cd3f0"); } void Menu_OnlineMode::apply_lobby_seed() { generated_stub("Menu_OnlineMode::apply_lobby_seed 008cddf0"); } -MrMeData::~MrMeData() { generated_stub("MrMeData::~MrMeData 005cd8c0"); } void Multiplayer::set_service_provider(int providerType) { generated_stub("Multiplayer::set_service_provider 00a29370"); } void Multiplayer::flush_channel(int *param_1) { generated_stub("Multiplayer::flush_channel 00a29bb0"); } void Multiplayer::leave_lobby(void *callback, void *userData) { generated_stub("Multiplayer::leave_lobby 00a29d00"); } @@ -9239,11 +9237,9 @@ Vector * NpcHelper::adult_leech_heading(Vector *outHeading, Entity *target, Vect void NpcHelper::twitchy_jump_target(Vector *outTarget, Entity_NPC *npc) { generated_stub("NpcHelper::twitchy_jump_target 004db3c0"); } void NpcHelper::gutted_fatty_burst_projectiles(Entity *timer) { generated_stub("NpcHelper::gutted_fatty_burst_projectiles 004e0930"); } uint8_t NpcHelper::candler_is_free_cell(Vector *position) { generated_stub("NpcHelper::candler_is_free_cell 004e4870"); } -uint8_t NpcHelper::whipper_is_target(Entity_NPC *npc, Entity *entity) { generated_stub("NpcHelper::whipper_is_target 004e50d0"); } void NpcHelper::bouncer_death_gib(Entity_Effect *timer) { generated_stub("NpcHelper::bouncer_death_gib 00501e10"); } void NpcHelper::migraine_timer_spawn(Entity *timer) { generated_stub("NpcHelper::migraine_timer_spawn 00528ec0"); } uint8_t NpcHelper::tarboy_is_creep_near(Entity_NPC *npc, Vector *position) { generated_stub("NpcHelper::tarboy_is_creep_near 005441e0"); } -void NpcHelper::bubbles_death_geyser_tick(Entity *owner) { generated_stub("NpcHelper::bubbles_death_geyser_tick 0055a850"); } uint8_t NpcHelper::polty_target_set(int gridIndex) { generated_stub("NpcHelper::polty_target_set 0055d070"); } uint8_t NpcHelper::polty_is_target_liftable(Entity_NPC *npc) { generated_stub("NpcHelper::polty_is_target_liftable 0055d0b0"); } uint8_t NpcHelper::polty_is_pot_cell(Entity_NPC *npc, int gridIndex) { generated_stub("NpcHelper::polty_is_pot_cell 0055d180"); } @@ -9276,7 +9272,6 @@ void NpcHelper::visage_pick_target_position(Entity_NPC *npc) { generated_stub("N void NpcHelper::visage_start_charge(Entity_NPC *npc) { generated_stub("NpcHelper::visage_start_charge 005ab180"); } void NpcHelper::visage_chain_solve(Entity_NPC *npc, uint8_t isInterpolate) { generated_stub("NpcHelper::visage_chain_solve 005acd30"); } uint8_t NpcHelper::visage_handle_collision(Entity_NPC *npc, Entity *collider, int unused) { generated_stub("NpcHelper::visage_handle_collision 005add40"); } -uint8_t NpcHelper::is_target_valid(Entity *target) { generated_stub("NpcHelper::is_target_valid 006be7e0"); } void NpcHelper::fireplace_moveable_update(Entity_NPC *npc) { generated_stub("NpcHelper::fireplace_moveable_update 006d0ec0"); } void OnlineChat::render(Vector *position, uint8_t isInputLine, uint8_t isCursorVisible, float alpha) { generated_stub("OnlineChat::render 0091d2b0"); } void OnlineChat::destructor() { generated_stub("OnlineChat::destructor 0091db20"); } @@ -9818,9 +9813,7 @@ int FUN_00436120(int param_1) { generated_stub("FUN_00436120 00436120"); } void FUN_00436190() { generated_stub("FUN_00436190 00436190"); } void FUN_00436200(uint32_t param_1) { generated_stub("FUN_00436200 00436200"); } void FUN_00436210(uint32_t param_1) { generated_stub("FUN_00436210 00436210"); } -void FUN_00436260() { generated_stub("FUN_00436260 00436260"); } void FUN_00436fb0() { generated_stub("FUN_00436fb0 00436fb0"); } -void FamiliarHelper::wisp_mine_crafter_update(Entity_Familiar *wisp) { generated_stub("FamiliarHelper::wisp_mine_crafter_update 0043d850"); } void FUN_0043e990(RNG *param_1) { generated_stub("FUN_0043e990 0043e990"); } void FUN_0043e9f0() { generated_stub("FUN_0043e9f0 0043e9f0"); } void FUN_0043ed20(uint32_t *param_1, int *param_2) { generated_stub("FUN_0043ed20 0043ed20"); } @@ -9958,7 +9951,6 @@ void Catch_All_004d7683() { generated_stub("Catch_All_004d7683 004d7683"); } void FUN_004d76c0() { generated_stub("FUN_004d76c0 004d76c0"); } bool FUN_004d7760() { generated_stub("FUN_004d7760 004d7760"); } void NpcAI::ENTITY_SMALL_MAGGOT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SMALL_MAGGOT 004d77b0"); } -Entity * spawn_small_maggot(Vector *position, float height, Vector *velocity, float heightVelocity) { generated_stub("spawn_small_maggot 004d8b50"); } void NpcAI::ENTITY_ADULT_LEECH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ADULT_LEECH 004d9000"); } void NpcAI::ENTITY_ROTTEN_GAPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ROTTEN_GAPER 004da590"); } Entity_Effect * NpcAI::ENTITY_TWITCHY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TWITCHY 004db6a0"); } @@ -9974,41 +9966,22 @@ void FUN_004e46c0() { generated_stub("FUN_004e46c0 004e46c0"); } bool FUN_004e47b0() { generated_stub("FUN_004e47b0 004e47b0"); } int FUN_004e4840() { generated_stub("FUN_004e4840 004e4840"); } void NpcAI::ENTITY_CANDLER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CANDLER 004e4970"); } -void NpcAI::ENTITY_WHIPPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WHIPPER 004e5170"); } -void NpcAI::ENTITY_GRUDGE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GRUDGE 004e6570"); } uint32_t NpcAI::ENTITY_BISHOP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BISHOP 004e7ea0"); } -uint8_t * NpcAI::ENTITY_BABY_BEGOTTEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BABY_BEGOTTEN 004e8380"); } -void NpcAI::ENTITY_REVENANT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_REVENANT 004ecc10"); } -void NpcAI::ENTITY_CULTIST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CULTIST 004ed840"); } -void NpcAI::ENTITY_CLICKETY_CLACK(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CLICKETY_CLACK 004efb90"); } -void NpcAI::ENTITY_MAZE_ROAMER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MAZE_ROAMER 004f1ec0"); } -void NpcAI::ENTITY_GOAT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GOAT 004f2c20"); } void NpcAI::ENTITY_BALL_AND_CHAIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BALL_AND_CHAIN 004f4730"); } -void NpcAI::ENTITY_POOFER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_POOFER 004f64e0"); } -void NpcAI::ENTITY_MOCKULUS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOCKULUS 004f76f0"); } -void NpcAI::ENTITY_MORNINGSTAR(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MORNINGSTAR 004f7e60"); } void FUN_004f8390() { generated_stub("FUN_004f8390 004f8390"); } void FUN_004f8460(int *param_1, int *param_2) { generated_stub("FUN_004f8460 004f8460"); } uint8_t str_ne(std_string *a, uint8_t *b) { generated_stub("str_ne 004f84a0"); } void rng_pair_init(void *self) { generated_stub("rng_pair_init 004f88a0"); } uint32_t FUN_004f88e0() { generated_stub("FUN_004f88e0 004f88e0"); } uint32_t FUN_004f8930() { generated_stub("FUN_004f8930 004f8930"); } -void NpcAI::ENTITY_DANNY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DANNY 004fbd10"); } void NpcAI::ENTITY_GYRO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GYRO 004ff620"); } void NpcAI::ENTITY_BOUNCER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BOUNCER 00501f30"); } -void NpcAI::ENTITY_FLESH_MAIDEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FLESH_MAIDEN 00502980"); } -void NpcAI::ENTITY_BOMBGAGGER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BOMBGAGGER 00503300"); } -void NpcAI::ENTITY_DUST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DUST 00503af0"); } -void NpcAI::ENTITY_BIG_BONY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BIG_BONY 005041d0"); } -void NpcAI::ENTITY_DUSTY_DEATHS_HEAD(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DUSTY_DEATHS_HEAD 00504a40"); } -void NpcAI::ENTITY_NECRO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_NECRO 005052a0"); } void pow_wrapper() { generated_stub("pow_wrapper 00505b40"); } void set_byte_0x101(void *self, uint8_t value) { generated_stub("set_byte_0x101 00505b50"); } int FUN_00505ca0() { generated_stub("FUN_00505ca0 00505ca0"); } uint32_t * FUN_00505ce0() { generated_stub("FUN_00505ce0 00505ce0"); } void NpcAI::ENTITY_STONE_EYE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_STONE_EYE 00505d00"); } long double FUN_00515290(Vector *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00515290 00515290"); } -void NpcAI::ENTITY_HEART(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HEART 0051f2f0"); } void NpcAI::ENTITY_DOPLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOPLE 00525650"); } void NpcAI::ENTITY_BLACK_MAW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLACK_MAW 0053b2f0"); } float NpcAI::ENTITY_TARBOY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TARBOY 005442a0"); } @@ -10017,7 +9990,6 @@ void npc_distribute_orbit_angles(Entity_NPC *npc) { generated_stub("npc_distribu void NpcAI::ENTITY_MR_MINE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MR_MINE 005492c0"); } int FUN_0054d1b0(int param_1) { generated_stub("FUN_0054d1b0 0054d1b0"); } void NpcAI::ENTITY_BUTT_SLICKER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BUTT_SLICKER 0054d250"); } -void NpcAI::ENTITY_SWARM_SPIDER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SWARM_SPIDER 005505c0"); } void NpcAI::ENTITY_COHORT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_COHORT 005513a0"); } void NpcAI::ENTITY_GENERIC_PROP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GENERIC_PROP 00551d30"); } void NpcAI::ENTITY_SHADY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SHADY 005522d0"); } @@ -10028,17 +10000,9 @@ void FUN_00557b70(uint8_t *param_1) { generated_stub("FUN_00557b70 00557b70"); } bool FUN_00557bb0(int *param_1) { generated_stub("FUN_00557bb0 00557bb0"); } int NpcAI::ENTITY_WILLO_L2_find_target(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WILLO_L2_find_target 005591c0"); } void NpcAI::ENTITY_WILLO_L2(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WILLO_L2 005593c0"); } -Entity_Projectile * NpcAI::ENTITY_BUBBLES(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BUBBLES 0055ad20"); } -void NpcAI::ENTITY_SMALL_LEECH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SMALL_LEECH 0055b740"); } uint32_t NpcAI::ENTITY_POLTY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_POLTY 0055d230"); } -void NpcAI::ENTITY_FLY_TRAP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FLY_TRAP 00560ca0"); } -void NpcAI::ENTITY_FLY_orbit_parent(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FLY_orbit_parent 00561580"); } -void NpcAI::ENTITY_FARTIGAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FARTIGAN 00561a20"); } -void NpcAI::ENTITY_POOT_MINE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_POOT_MINE 00562290"); } -void NpcAI::ENTITY_DUMP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DUMP 00562f00"); } void NpcAI::ENTITY_BLOATY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLOATY 00563da0"); } void NpcAI::ENTITY_FISSURE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FISSURE 00564f30"); } -void NpcAI::ENTITY_HENRY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HENRY 00565bc0"); } void FUN_00565dd0(uint32_t param_1) { generated_stub("FUN_00565dd0 00565dd0"); } void FUN_00565de0(uint32_t param_1) { generated_stub("FUN_00565de0 00565de0"); } void NpcAI::ENTITY_MOTHER_worm(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOTHER_worm 00565e00"); } @@ -10165,7 +10129,6 @@ void FUN_005c7ef0(int param_1) { generated_stub("FUN_005c7ef0 005c7ef0"); } void FUN_005c7f20(int param_1) { generated_stub("FUN_005c7f20 005c7f20"); } void everything_jar_crack_the_sky_timer(int param_1) { generated_stub("everything_jar_crack_the_sky_timer 005c8020"); } void everything_jar_shopkeeper_rain_timer(int param_1) { generated_stub("everything_jar_shopkeeper_rain_timer 005c83f0"); } -int FUN_005c92f0() { generated_stub("FUN_005c92f0 005c92f0"); } void FUN_005ca566(uint32_t param_1, uint32_t param_2, int param_3) { generated_stub("FUN_005ca566 005ca566"); } void FUN_005ca880() { generated_stub("FUN_005ca880 005ca880"); } void FUN_005cba20() { generated_stub("FUN_005cba20 005cba20"); } @@ -10231,7 +10194,6 @@ Vector * FUN_005cd7e0(Vector *param_1) { generated_stub("FUN_005cd7e0 005cd7e0") void FUN_005cd800() { generated_stub("FUN_005cd800 005cd800"); } AchievementOverlay * FUN_005cd810() { generated_stub("FUN_005cd810 005cd810"); } void FUN_005cd840(uint32_t param_1) { generated_stub("FUN_005cd840 005cd840"); } -void FUN_005cd850() { generated_stub("FUN_005cd850 005cd850"); } void FUN_005cd8c0(uint8_t param_1) { generated_stub("FUN_005cd8c0 005cd8c0"); } void FUN_005cda90() { generated_stub("FUN_005cda90 005cda90"); } void FUN_00607540() { generated_stub("FUN_00607540 00607540"); } @@ -10294,7 +10256,6 @@ bool FUN_0060d1c0(uint32_t param_1) { generated_stub("FUN_0060d1c0 0060d1c0"); } uint32_t FUN_0060d1e0() { generated_stub("FUN_0060d1e0 0060d1e0"); } void FUN_0060d1f0(uint32_t param_1) { generated_stub("FUN_0060d1f0 0060d1f0"); } void FUN_0060d400() { generated_stub("FUN_0060d400 0060d400"); } -void FUN_0060d5e0(uint8_t param_1) { generated_stub("FUN_0060d5e0 0060d5e0"); } uint32_t FUN_0060dae0() { generated_stub("FUN_0060dae0 0060dae0"); } void FamiliarAI::gb_bug(Entity_Familiar *familiar) { generated_stub("FamiliarAI::gb_bug 00618b00"); } void FamiliarAI::variant_53(Entity_Familiar *familiar) { generated_stub("FamiliarAI::variant_53 006196e0"); } @@ -10303,7 +10264,6 @@ void FamiliarAI::lil_haunt(Entity_Familiar *familiar, int unused) { generated_st void FUN_0062e0e0(int param_1) { generated_stub("FUN_0062e0e0 0062e0e0"); } void FamiliarAI::bumbo(Entity_Familiar *familiar) { generated_stub("FamiliarAI::bumbo 0062f7f0"); } void FUN_00631a00(float *param_1, uint32_t param_2, float *param_3) { generated_stub("FUN_00631a00 00631a00"); } -void familiar_wisp_pick_tear_color(RNG *rng, int *outVariant, BitSet128 *outFlags) { generated_stub("familiar_wisp_pick_tear_color 00633990"); } void FamiliarAI::lil_spewer(Entity_Familiar *familiar) { generated_stub("FamiliarAI::lil_spewer 006384a0"); } void FUN_00638e20() { generated_stub("FUN_00638e20 00638e20"); } void FUN_006395e0(Vector *param_1, int *param_2, int param_3, int param_4, int param_5, float param_6, int param_7, int param_8, Entity *param_9, int param_10) { generated_stub("FUN_006395e0 006395e0"); } @@ -10313,12 +10273,8 @@ void FUN_0063b240() { generated_stub("FUN_0063b240 0063b240"); } void FUN_0063c060(int param_1) { generated_stub("FUN_0063c060 0063c060"); } void FamiliarHelper::fly_head_pathfind_move(Entity_Familiar *familiar) { generated_stub("FamiliarHelper::fly_head_pathfind_move 0063d570"); } void FUN_0063e180() { generated_stub("FUN_0063e180 0063e180"); } -void FamiliarAI::tinytoma(Entity_Familiar *familiar) { generated_stub("FamiliarAI::tinytoma 00642cb0"); } void FUN_006431b0() { generated_stub("FUN_006431b0 006431b0"); } void FamiliarAI::variant_204(Entity_Familiar *familiar) { generated_stub("FamiliarAI::variant_204 00644780"); } -void FamiliarAI::lil_dumpy(Entity_Familiar *familiar) { generated_stub("FamiliarAI::lil_dumpy 006468a0"); } -void FamiliarAI::apollyons_best_friend(Entity_Familiar *familiar) { generated_stub("FamiliarAI::apollyons_best_friend 00647320"); } -void anm2_apply_gfx_overrides(std_string *gfxSpec, std_string *unusedString, ANM2 *anm2) { generated_stub("anm2_apply_gfx_overrides 0064aab0"); } void FUN_0064b6a0() { generated_stub("FUN_0064b6a0 0064b6a0"); } int FamiliarAI::worm_friend(Entity_Familiar *familiar) { generated_stub("FamiliarAI::worm_friend 0064bfa0"); } int FUN_0064ccf0() { generated_stub("FUN_0064ccf0 0064ccf0"); } @@ -10558,7 +10514,6 @@ uint8_t FUN_006b8440() { generated_stub("FUN_006b8440 006b8440"); } uint8_t FUN_006b8490() { generated_stub("FUN_006b8490 006b8490"); } void FUN_006b84c0() { generated_stub("FUN_006b84c0 006b84c0"); } void FUN_006b8580() { generated_stub("FUN_006b8580 006b8580"); } -Entity * spawn_gfuel_explosion() { generated_stub("spawn_gfuel_explosion 006b9450"); } uint32_t _NpcHelper::spider_load_graphics(uint8_t *param_1) { generated_stub("_NpcHelper::spider_load_graphics 006baa70"); } int FUN_006c4a90() { generated_stub("FUN_006c4a90 006c4a90"); } void FUN_006d6650() { generated_stub("FUN_006d6650 006d6650"); } @@ -10658,7 +10613,6 @@ uint32_t FUN_00710f70(int param_1) { generated_stub("FUN_00710f70 00710f70"); } void FUN_00711530(int param_1) { generated_stub("FUN_00711530 00711530"); } uint32_t FUN_00711740() { generated_stub("FUN_00711740 00711740"); } void FUN_00718ed0(uint32_t param_1) { generated_stub("FUN_00718ed0 00718ed0"); } -uint32_t FUN_00718ee0() { generated_stub("FUN_00718ee0 00718ee0"); } void FUN_0071df70(uint8_t param_1) { generated_stub("FUN_0071df70 0071df70"); } void FUN_00721e60(int param_1, int param_2, int param_3, int param_4, int param_5, int param_6) { generated_stub("FUN_00721e60 00721e60"); } void FUN_00722020(int param_1) { generated_stub("FUN_00722020 00722020"); } @@ -10921,7 +10875,6 @@ uint32_t FUN_00813420(int param_1, int param_2) { generated_stub("FUN_00813420 0 uint32_t FUN_0081e220() { generated_stub("FUN_0081e220 0081e220"); } void FUN_0081fae0(uint32_t *param_1) { generated_stub("FUN_0081fae0 0081fae0"); } void FUN_00821940() { generated_stub("FUN_00821940 00821940"); } -uint32_t FUN_00827180(float *param_1) { generated_stub("FUN_00827180 00827180"); } void FUN_00827f30() { generated_stub("FUN_00827f30 00827f30"); } void FUN_00828010(uint32_t *param_1) { generated_stub("FUN_00828010 00828010"); } void FUN_00828050(short *param_1) { generated_stub("FUN_00828050 00828050"); } diff --git a/src/active_items.h b/src/active_items.h index 392f4d5..638cdc8 100644 --- a/src/active_items.h +++ b/src/active_items.h @@ -124,6 +124,8 @@ bool input_is_action_pressed(ButtonAction action, int controllerIndex, Entity* e bool input_is_action_triggered(ButtonAction action, int controllerIndex, Entity* entity); float input_action_value_get(ButtonAction action, int controllerIndex, Entity* entity); bool is_active_usable(Entity_Player& player, int item, int slot); +int red_door_outline_slot(const Vector& position); +Entity_Familiar* stitches_get(Entity_Player& player); ChargeType active_charge_type(Entity_Player& player, int slot); bool is_active_slot_kept(Entity_Player& player, int slot); void active_collectible_add(Entity_Player& player, ItemConfig_Item& item, const ActiveGain& gain); diff --git a/src/ambush.cpp b/src/ambush.cpp index 9bc37cc..214799e 100644 --- a/src/ambush.cpp +++ b/src/ambush.cpp @@ -1,6 +1,8 @@ #include "ambush.h" #include "entity_effect.h" #include "entity_factory.h" +#include "npc_ai.h" +#include "entity_npc.h" #include "entity_player.h" #include "game.h" #include "grid_entity_door.h" @@ -17,6 +19,7 @@ #include "sfx_manager.h" #include #include +#include #include // A wave's difficulty by wave (one later on Hard), the room subtypes of normal and boss waves, how often a wave is @@ -37,6 +40,19 @@ constexpr int WAVE_COUNTDOWN = 30; constexpr int DOOR_STOP_BOSSRUSH = 2; constexpr int DOOR_STOP_CHALLENGE = 3; +// The Boss Rush's bosses rise round an ellipse 200 by 180 about the room's centre, Gurdy 80 and Mega Maw 160 below the +// top, at least 40 from a player (stepping 60 away), the segments of a boss 20 apart. Gurdy clears three cells round. +constexpr float BOSS_RUSH_FULL_TURN = 6.2831855f; +constexpr float BOSS_RUSH_RING_X = 200; +constexpr float BOSS_RUSH_RING_Y = 180; +constexpr float BOSS_RUSH_GURDY_DROP = 80; +constexpr float BOSS_RUSH_MEGA_MAW_DROP = 160; +constexpr float BOSS_RUSH_PLAYER_CLEAR = 40; +constexpr float BOSS_RUSH_PLAYER_STEP = 60; +constexpr float BOSS_RUSH_SEGMENT_SPACING = 20; +constexpr float BOSS_RUSH_GURDY_REACH = 3; +constexpr float HALF_ROOM = 0.5f; + // 008332e0 Copies the Boss Rush's waves and shuffles them by the room's spawn seed, drawing from the back. // The original stops the game on a zero seed. Here the waves stay unshuffled. void Ambush::shuffle_waves() @@ -142,6 +158,15 @@ static std::vector> wave_entries_pick(Ambush& ambush) return entries; } +// A wave's end: the summon sounds and every player's locusts come out. +static void wave_summoned() +{ + int sound = SOUND_SUMMON_PENTA; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); + for (Entity_Player* player : g_game->playerManager.playerList) player->spawn_locusts(); +} + // 00833600 Calls a challenge wave: its enemies rise from pentagrams on free cells near where the layout places them // (anything else appears at once), with the summon's sound, and every player's locusts come out. // The original crashes when the fallback stage has no wave either. Here it draws again. @@ -169,16 +194,91 @@ void Ambush::SpawnWave() if (spawned->type == ENTITY_EFFECT) spawned->Update(); spawned->spawnGridIndex = cell; } - int sound = SOUND_SUMMON_PENTA; - seed_fart_sound_override(&sound); - g_manager->sfxManager.Play(sound); - for (Entity_Player* player : game.playerManager.playerList) player->spawn_locusts(); + wave_summoned(); } -// 00833c40 Calls a Boss Rush wave. +// A boss's pentagram where it is to rise, from the next seed. +static void boss_pentagram_spawn(int type, int variant, const Vector& position) +{ + pentagram_spawn({.position = position, .type = type, .variant = variant, .seed = Random()}, -1); +} + +// Where a Boss Rush boss rises: on an ellipse about the room's centre at its angle, Gurdy and Mega Maw at the top +// middle, moved a bit away from a player too near, onto a free spot. +static Vector boss_rush_spot_find(int type, float angle) +{ + Room& room = *g_game->room; + Vector center = vector_scale(vector_add(room.bottomRightPos, room.topLeftPos), HALF_ROOM); + Vector spot = + vector_make(std::cos(angle) * BOSS_RUSH_RING_X + center.x, std::sin(angle) * BOSS_RUSH_RING_Y + center.y); + if (type == ENTITY_GURDY) spot = vector_make(center.x, room.topLeftPos.y + BOSS_RUSH_GURDY_DROP); + else if (type == ENTITY_MEGA_MAW) spot = vector_make(center.x, room.topLeftPos.y + BOSS_RUSH_MEGA_MAW_DROP); + + Entity_Player* player = game_nearest_player(spot); + if (player && vector_length_squared(vector_sub(spot, player->pos)) < BOSS_RUSH_PLAYER_CLEAR * BOSS_RUSH_PLAYER_CLEAR) + { + float away = random_unit() * RANDOM_HALF_TURN * 2; + spot = vector_add(spot, vector_scale(vector_make(std::cos(away), std::sin(away)), BOSS_RUSH_PLAYER_STEP)); + } + return room_free_pickup_position_find({.position = spot}); +} + +// Breaks the grid entities in the cells about a risen boss, three cells out around Gurdy (who lands lower). +static void boss_rush_ground_clear(int type, Vector spot) +{ + Room& room = *g_game->room; + float reach = GRID_CELL_SIZE; + if (type == ENTITY_GURDY) + { + spot.y += BOSS_RUSH_GURDY_DROP; + reach *= BOSS_RUSH_GURDY_REACH; + } + for (float dx = -reach; dx <= reach; dx += GRID_CELL_SIZE) + for (float dy = -reach; dy <= reach; dy += GRID_CELL_SIZE) + { + int column = (int)((spot.x + dx - GRID_ORIGIN_X) / GRID_CELL_SIZE + HALF_ROOM); + int row = (int)((dy + spot.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + HALF_ROOM); + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + int cell = isInside ? row * room.gridWidth + column : -1; + GridEntity* grid = (uint32_t)cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; + if (grid) grid->Destroy(false, {}); + } +} + +// 00833c40 Calls a Boss Rush wave: the slots it takes from the shuffled ones give its bosses, each rising from a +// pentagram round the room (the Headless Horseman with his head below him, a boss of several segments spread in a +// row), the ground about each broken. Then the summon sounds and every player's locusts come out. void Ambush::SpawnBossrushWave() { - reconstruction_missing("Ambush::SpawnBossrushWave 00833c40"); + BossRushWave bosses; + for (int slot = 0; slot < bossesPerWave && !wavesLeft.empty(); slot++) + { + bosses.insert(bosses.end(), wavesLeft.back().begin(), wavesLeft.back().end()); + wavesLeft.pop_back(); + } + if (bosses.empty()) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Wave has no entries!"); + + float angle = 0; + float angleStep = BOSS_RUSH_FULL_TURN / (float)bosses.size(); + for (const BossRushEntry& boss : bosses) + { + Vector spot = boss_rush_spot_find(boss.type, angle); + boss_pentagram_spawn(boss.type, boss.variant, spot); + Vector below = vector_make(spot.x + 0, spot.y + BOSS_RUSH_SEGMENT_SPACING); + if (boss.type == ENTITY_HEADLESS_HORSEMAN) boss_pentagram_spawn(ENTITY_HORSEMAN_HEAD, 0, below); + else if (boss.type == ENTITY_HORSEMAN_HEAD) boss_pentagram_spawn(ENTITY_HEADLESS_HORSEMAN, 0, below); + + int left = (boss.chunks - 1) / 2; + for (int i = 1; boss.chunks > 1 && i <= boss.chunks - left - 1; i++) + boss_pentagram_spawn(boss.type, boss.variant, + vector_make((float)i * BOSS_RUSH_SEGMENT_SPACING + spot.x, spot.y + 0)); + for (int i = 1; boss.chunks > 1 && i <= left; i++) + boss_pentagram_spawn(boss.type, boss.variant, + vector_make(spot.x - (float)i * BOSS_RUSH_SEGMENT_SPACING, spot.y + 0)); + angle += angleStep; + boss_rush_ground_clear(boss.type, spot); + } + wave_summoned(); } // 00834350 Runs the fight: 30 frames after a wave's enemies (the Boss Rush's bosses) are gone the next is called, the diff --git a/src/ambush.h b/src/ambush.h index 9a3f8af..e938419 100644 --- a/src/ambush.h +++ b/src/ambush.h @@ -11,7 +11,7 @@ struct BossRushEntry int variant = 0; }; -// A spawn slot's bosses, one of which a wave draws. +// A spawn slot's bosses, all of which rise together when a wave takes the slot. using BossRushWave = std::vector; // The original's copies, assignment and destruction are the defaults. diff --git a/src/anm2.cpp b/src/anm2.cpp index 13af098..da488cd 100644 --- a/src/anm2.cpp +++ b/src/anm2.cpp @@ -35,7 +35,6 @@ constexpr int FRAME_INDEX_UNSET = -1; constexpr uint32_t EVENT_BIT_MASK = 31; constexpr float CHANNEL = 255; constexpr float PERCENT = 100; -constexpr float HALF = 0.5f; constexpr float DEGREES_HALF_TURN = 180; constexpr float DEGREES_TURN = 360; constexpr float RADIANS_PER_DEGREE = 0.017453292f; @@ -1030,8 +1029,8 @@ static void quad_scale(DestinationQuad& quad, Vector pivot, Vector scale) *corner = vector_make((corner->x - pivot.x) * scale.x + pivot.x, (corner->y - pivot.y) * scale.y + pivot.y); } -// Turns a quad about a pivot by radians, as Quad::rotate does. -static void quad_rotate(DestinationQuad& quad, Vector pivot, float angle) +// Quad::rotate: turns a quad about a pivot by radians. +void quad_rotate(DestinationQuad& quad, Vector pivot, float angle) { if (angle == 0) return; diff --git a/src/anm2.h b/src/anm2.h index 22eac20..caee496 100644 --- a/src/anm2.h +++ b/src/anm2.h @@ -18,6 +18,15 @@ constexpr int NO_SHADOW_LAYER = -1; constexpr ColorMod COLOR_DEFAULT = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod CHAMPION_COLOR_DEFAULT = {{1, 1, 1, 0}, {0, 0, 0, 0}, {0, 0, 0}}; +// A color with only its tint, colorize and offset set, as the Color constructors build it. +constexpr ColorMod color_make(std::array tint, std::array colorize = {}, + std::array offset = {}) +{ + return {{tint[0], tint[1], tint[2], tint[3]}, + {colorize[0], colorize[1], colorize[2], colorize[3]}, + {offset[0], offset[1], offset[2]}}; +} + // ANM2::bitflags and LayerState::bitflags, ORed together when a layer renders. // REPENTOGON's AnimRenderFlags, with names for the bits it leaves out. enum AnimRenderFlag : unsigned int @@ -105,6 +114,12 @@ inline Vector vector_make(float x, float y) constexpr float PI_F = 3.1415927f; constexpr float DEGREES_TO_RADIANS = 0.017453292f; constexpr float RADIANS_TO_DEGREES = 57.295776f; +constexpr float TAU = 2 * PI_F; +constexpr float FULL_TURN_DEGREES = 360; +constexpr float HALF_TURN_DEGREES = 180; +constexpr float RIGHT_ANGLE_DEGREES = 90; +constexpr float DIAGONAL = 0.70710677f; +constexpr float HALF = 0.5f; inline Vector vector_add(Vector a, Vector b) { @@ -136,6 +151,12 @@ inline float vector_length(Vector v) return std::sqrt(v.x * v.x + v.y * v.y); } +// Vector::Distance: how far apart two points are. +inline float vector_distance(Vector a, Vector b) +{ + return vector_length(vector_sub(a, b)); +} + inline bool vector_is_zero(Vector v) { return v.x == 0 && v.y == 0; @@ -184,6 +205,7 @@ struct LerpRange }; float lerp_range(float value, const LerpRange& range); +void quad_rotate(DestinationQuad& quad, Vector pivot, float angle); // Vector::Rotated: v turned by an angle in degrees. inline Vector vector_rotated(Vector v, float degrees) diff --git a/src/backdrop.cpp b/src/backdrop.cpp index 5a53f7c..583b4f0 100644 --- a/src/backdrop.cpp +++ b/src/backdrop.cpp @@ -1,4 +1,5 @@ #include "backdrop.h" +#include "boss_pool.h" #include "data.h" #include "entity.h" #include "entity_config.h" @@ -12,6 +13,7 @@ #include "log.h" #include "manager.h" #include "menu_manager.h" +#include "npc_ai.h" #include "platform.h" #include "render_passes.h" #include "room.h" @@ -48,7 +50,6 @@ constexpr float WALL_SIZE = WALL_CELLS * GRID_SIZE; constexpr uint32_t FLOOR_SECOND = 1; constexpr uint32_t HOME_CLOSET_FIRST_SUBTYPE = 10; -constexpr int BOSS_MOM_MAUSOLEUM = 89; // Where Mega Satan's floor sprite draws past the room's corner, and the half cell its surface reaches past the walls. constexpr float MEGA_SATAN_FLOOR_X = 0; @@ -196,7 +197,6 @@ constexpr float TAR_OUT_RANGE = 40; constexpr float TAR_SHIFT_RANGE = 10; constexpr float TAR_SCALE_RANGE = 4; constexpr float HALF_TURN = 1.5707964f; -constexpr float SPLAT_SCALE_STEP = 2.3283064e-10f; constexpr int DROSS_LIGHT_FIRST = 3; constexpr int DROSS_LIGHT_ODDS = 40; constexpr float DROSS_LIGHT_SCALE = 0.5f; @@ -207,7 +207,6 @@ constexpr GridEntityType DROSS_PIPE_BLOCKERS[] = {GRID_ROCK, GRID_ROCKB, GRI constexpr float DROSS_LEAK_SIDE[2] = {6, 28}; constexpr float DROSS_LEAK_TOP[2] = {10, 24}; constexpr float DROSS_LEAK_RANGE = 0.4f; -constexpr ColorMod DROSS_LEAK_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0}}; constexpr int DOOR_SIDE_SLOT = 2; constexpr int MINES_LANTERN_ODDS = 4; constexpr int MAUSOLEUM_TORCH_ODDS = 3; @@ -223,7 +222,6 @@ constexpr float NARROW_BORDER_X = 104; constexpr float NARROW_BORDER_Y = 52; constexpr float L_BORDER_WIDTH = 364; constexpr float L_BORDER_HEIGHT = 208; -constexpr KColor WHITE = kcolor_rgba(1, 1, 1, 1); constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset"; @@ -1571,7 +1569,7 @@ static Entity* hanging_decoration_spawn(const WallSlot& slot, Vector position, s // A blood splat colored as asked, a random size from the global generator, its seed from the backdrop's. static void colored_splat_spawn(Backdrop& backdrop, Vector position, const ColorMod& color, float range) { - float scale = (float)Random() * SPLAT_SCALE_STEP * range + 1; + float scale = random_unit() * range + 1; Entity* splat = g_game->Spawn( {.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = backdrop.rng.Next()}); @@ -1663,7 +1661,7 @@ static void dross_details_spawn(Backdrop& backdrop, const WallSlot& slot, bool i const float (&leak)[2] = slot.slotX == 0 ? DROSS_LEAK_SIDE : DROSS_LEAK_TOP; Vector drip = vector_make(normal.y * leak[0] + normal.x * leak[1] + position.x, -normal.x * leak[0] + normal.y * leak[1] + position.y); - colored_splat_spawn(backdrop, drip, DROSS_LEAK_COLOR, DROSS_LEAK_RANGE); + colored_splat_spawn(backdrop, drip, LIGHT_POOP_SPLAT_COLOR, DROSS_LEAK_RANGE); } // The Mines: the background details on the second and third rows' first corner (the second's with their lights), and diff --git a/src/boss_brownie.cpp b/src/boss_brownie.cpp index afb2f34..14e83d2 100644 --- a/src/boss_brownie.cpp +++ b/src/boss_brownie.cpp @@ -3,6 +3,7 @@ #include "entity_projectile.h" #include "entity_tear.h" #include "grid_entity.h" +#include "npc_ai.h" #include "npc_basement.h" #include "npc_caves.h" #include "room_grid.h" @@ -21,7 +22,6 @@ constexpr int BROWNIE_DYING = NPC_STATE_SPECIAL; constexpr int BROWNIE_BLACK = 1; constexpr uint8_t BROWNIE_NO_SHOT = 0xff; -constexpr ColorMod BROWNIE_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0}}; constexpr int BROWNIE_DEPTH = 2000; constexpr int BROWNIE_DASH_DEPTH = 1700; constexpr float BROWNIE_FRICTION = 0.7f; @@ -606,7 +606,7 @@ void boss_brownie_update(Entity_NPC& npc) if (npc.state == NPC_STATE_INIT) { npc.state = NPC_STATE_IDLE; - npc.splatColor = BROWNIE_SPLAT_COLOR; + npc.splatColor = LIGHT_POOP_SPLAT_COLOR; npc.i2 = std::bit_cast(BrownieShots{.shot = BROWNIE_NO_SHOT, .lastAttack = NPC_STATE_IDLE}); npc.renderZOffset = BROWNIE_DEPTH; return; diff --git a/src/boss_death.cpp b/src/boss_death.cpp index 566482d..5455234 100644 --- a/src/boss_death.cpp +++ b/src/boss_death.cpp @@ -48,7 +48,6 @@ constexpr int MINIBOSS_ID_LIMIT = 16; constexpr int EFFECT_POOF04 = 17; constexpr int EFFECT_BLOOD_GUSH = 42; -constexpr int COLLECTIBLE_QUARTER = 74; constexpr int COLLECTIBLE_FOREVER_ALONE = 128; constexpr int NULL_ITEM_SOL = 56; constexpr int GIANTBOOK_SOL = 5; @@ -623,8 +622,8 @@ void Room::TriggerBossDeath(Entity_NPC& boss) // 006d7520 A death animation's blood guide between its BloodStart and BloodStop (or Explosion) events: a huge boss // (and Mother's second phase) shakes the screen and throws gibs and blood about the guide, the rest puff blood poofs -// there. Satan's guide starts four gushes that follow him, which BloodStop and Explosion end. G-Fuel's poofs are not -// reconstructed yet. +// there. Satan's guide starts four gushes that follow him, which BloodStop and Explosion end. G-Fuel makes the poofs +// small explosions. void Entity_NPC::update_blood_guide_gibs(const NullFrame& guide) { bool isBleeding = sprite.WasEventTriggered("BloodStart") && !sprite.WasEventTriggered("BloodStop") && @@ -655,20 +654,25 @@ void Entity_NPC::update_blood_guide_gibs(const NullFrame& guide) } else if (isBleeding && (Random() & 1) == 0) { - if (g_game->playerManager.GetGFuelCount() > 0) - reconstruction_missing("Entity_NPC::update_blood_guide_gibs 006d7520: G-Fuel's explosions"); - - auto* poof = static_cast(g_game->Spawn( - {.position = pos, .spawner = this, .type = ENTITY_EFFECT, .variant = EFFECT_POOF04, .seed = Random()})); + bool isGfuel = g_game->playerManager.GetGFuelCount() > 0; + Entity* poof = isGfuel ? gfuel_explosion_spawn(pos, 1) + : g_game->Spawn({.position = pos, + .spawner = this, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF04, + .seed = Random()}); poof->renderDepthOffset = GUIDE_POOF_DEPTH; poof->sprite.offset = guideSpot(GUIDE_REACH); - poof->sprite.rotation = (float)(Random() & GUIDE_POOF_TURNS) * GUIDE_POOF_TURN; - float flipY = (Random() & 1) == 0 ? 1.0f : -1.0f; + if (!isGfuel) poof->sprite.rotation = (float)(Random() & GUIDE_POOF_TURNS) * GUIDE_POOF_TURN; + float flipY = isGfuel || (Random() & 1) == 0 ? 1.0f : -1.0f; float flipX = (Random() & 1) == 0 ? 1.0f : -1.0f; float shrink = 1 - random_unit() * GUIDE_POOF_SHRINK; poof->sprite.scale = vector_make(shrink * flipX, shrink * flipY); - poof->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); - PlaySound(SOUND_DEATH_BURST_GUIDED, random_unit() * GUIDE_VOLUME_SPAN + GUIDE_VOLUME, 2, false, 1); + if (!isGfuel) + { + poof->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + PlaySound(SOUND_DEATH_BURST_GUIDED, random_unit() * GUIDE_VOLUME_SPAN + GUIDE_VOLUME, 2, false, 1); + } } if (type == ENTITY_SATAN && sprite.IsEventTriggered("BloodStart")) diff --git a/src/boss_dingle.cpp b/src/boss_dingle.cpp index 887d262..d3df57f 100644 --- a/src/boss_dingle.cpp +++ b/src/boss_dingle.cpp @@ -1,5 +1,6 @@ #include "boss_ai.h" #include "entity_projectile.h" +#include "npc_ai.h" #include "room_grid.h" #include "sfx_manager.h" #include @@ -16,8 +17,6 @@ constexpr int DINGLE_DANCE = NPC_STATE_ATTACK3; constexpr int DINGLE_BEFORE_SLIDE = NPC_STATE_ATTACK4; constexpr int DINGLE_TIRED = NPC_STATE_SPECIAL; -constexpr ColorMod DINGLE_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.25490198f, 0.16078432f, 0.13725491f}}; -constexpr ColorMod DANGLE_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0}}; constexpr int DINGLE_IDLE_WAIT = 15; constexpr int DANGLE_IDLE_WAIT = 30; @@ -189,7 +188,7 @@ static void dingle_slide(Entity_NPC& npc) if (npc.variant == DANGLE) dangle_trail(npc); } npc.sprite.isFlipX = npc.velocity.x > 0; - if (npc.IsFrame(DINGLE_SPLAT_FRAMES, (int)npc.index)) dingle_splat(npc, DINGLE_SPLAT_COLOR); + if (npc.IsFrame(DINGLE_SPLAT_FRAMES, (int)npc.index)) dingle_splat(npc, POOP_SPLAT_COLOR); if (!npc.sprite.IsPlaying() || npc.HasEntityFlags(STUNNED)) { @@ -371,7 +370,7 @@ void boss_dingle_update(Entity_NPC& npc) { npc.state = NPC_STATE_IDLE; npc.stateFrame = 0; - npc.splatColor = npc.variant == DANGLE ? DANGLE_SPLAT_COLOR : DINGLE_SPLAT_COLOR; + npc.splatColor = npc.variant == DANGLE ? LIGHT_POOP_SPLAT_COLOR : POOP_SPLAT_COLOR; npc.i1 = 0; npc.i2 = 0; return; diff --git a/src/boss_intro.cpp b/src/boss_intro.cpp index 82824fe..6431d50 100644 --- a/src/boss_intro.cpp +++ b/src/boss_intro.cpp @@ -1,4 +1,5 @@ #include "data.h" +#include "boss_pool.h" #include "entity_config.h" #include "entity_player.h" #include "game.h" @@ -46,15 +47,7 @@ struct PlayerLayers constexpr PlayerLayers MAIN_PLAYER_LAYERS = {LAYER_PLAYER_PORTRAIT, LAYER_PLAYER_PORTRAIT_ALT, LAYER_PLAYER_SPOT}; constexpr std::array COOP_PLAYER_LAYERS = {{{18, 21, 15}, {19, 22, 16}, {20, 23, 17}}}; -// The characters whose portrait goes on the alternate layer: ???, Keeper, The Forgotten and The Soul, and the tainted -// ???, Keeper and Forgotten. -constexpr std::array ALT_PORTRAIT_PLAYERS = {4, 16, 17, 14, 25, 35, 33}; - constexpr int MUSIC_JINGLE_BOSS = 81; -constexpr uint32_t BOSS_BLUE_BABY = 40; -constexpr uint32_t BOSS_MEGA_SATAN = 55; -constexpr uint32_t BOSS_MOTHER = 88; -constexpr uint32_t BOSS_DOGMA = 99; constexpr int BOSS_ROOM_DELIRIUM = 90; constexpr int DELIRIUM_STAGE = 8; constexpr int DOUBLE_TROUBLE_FIRST = 3700; diff --git a/src/boss_min_min.cpp b/src/boss_min_min.cpp index 98339c9..c8c97e6 100644 --- a/src/boss_min_min.cpp +++ b/src/boss_min_min.cpp @@ -5,6 +5,7 @@ #include "entity_familiar.h" #include "entity_player.h" #include "manager.h" +#include #include // The Willo, a will-o'-wisp orbiting its Min-Min (its parent) or the players. Its slot on the ring turns with the game's diff --git a/src/boss_pool.cpp b/src/boss_pool.cpp index 0e1263d..acf80dc 100644 --- a/src/boss_pool.cpp +++ b/src/boss_pool.cpp @@ -26,22 +26,15 @@ constexpr uint32_t DOUBLE_TROUBLE_ODDS_CHAPTER_3 = 25; constexpr uint32_t DOUBLE_TROUBLE_ODDS_CHAPTER_4 = 40; constexpr int BOSS_MONSTRO = 1; -constexpr int BOSS_MOM = 6; constexpr int BOSS_MOMS_HEART = 8; constexpr int BOSS_DEATH = 12; constexpr int BOSS_HEADLESS_HORSEMAN = 22; -constexpr int BOSS_THE_FALLEN = 23; -constexpr int BOSS_SATAN = 24; constexpr int BOSS_IT_LIVES = 25; constexpr int BOSS_THE_BLOAT = 30; constexpr int BOSS_CONQUEST = 38; -constexpr int BOSS_ISAAC = 39; -constexpr int BOSS_BLUE_BABY = 40; constexpr int BOSS_THE_LAMB = 54; constexpr int BOSS_DELIRIUM = 70; constexpr int BOSS_REAP_CREEP = 74; -constexpr int BOSS_MOTHER = 88; -constexpr int BOSS_MOM_MAUSOLEUM = 89; // The Horsemen of the first floor of chapters 1 to 4, by chapter. constexpr std::array HORSEMEN = {9, 10, 11, BOSS_DEATH}; diff --git a/src/boss_pool.h b/src/boss_pool.h index b1b581a..a57f91a 100644 --- a/src/boss_pool.h +++ b/src/boss_pool.h @@ -11,6 +11,17 @@ constexpr int BOSS_POOL_COUNT = 37; constexpr int BOSS_ID_COUNT = 104; +// The bosses the game checks by id (bossportraits.xml's ids). +constexpr int BOSS_MOM = 6; +constexpr int BOSS_THE_FALLEN = 23; +constexpr int BOSS_SATAN = 24; +constexpr int BOSS_ISAAC = 39; +constexpr int BOSS_BLUE_BABY = 40; +constexpr int BOSS_MEGA_SATAN = 55; +constexpr int BOSS_MOTHER = 88; +constexpr int BOSS_MOM_MAUSOLEUM = 89; +constexpr int BOSS_DOGMA = 99; + // Whose bosspools.xml load_xml reads: the game's, or a mod's, which the original ignores. enum BossPoolSource { diff --git a/src/console_commands.cpp b/src/console_commands.cpp index 8f3045c..2d90c7e 100644 --- a/src/console_commands.cpp +++ b/src/console_commands.cpp @@ -818,9 +818,7 @@ static void curse_run(ConsoleCommand& command) // reseed: builds the floor anew on a new seed. static void reseed_run(ConsoleCommand& command) { - bool isAltPath = g_game->stageType == STAGETYPE_REPENTANCE || g_game->stageType == STAGETYPE_REPENTANCE_B; - - g_game->seedEffects.ForgetStageSeed(g_game->stage + isAltPath); + g_game->seedEffects.ForgetStageSeed(g_game->stage_depth_get()); g_game->Init(true); g_game->Level::Update(); g_game->playerManager.trigger_new_room_effects(); diff --git a/src/cutscene.cpp b/src/cutscene.cpp index 1808b42..c45bda1 100644 --- a/src/cutscene.cpp +++ b/src/cutscene.cpp @@ -31,8 +31,6 @@ constexpr int CREDITS_CUTSCENE = 2; constexpr int MUSIC_CREDITS = 60; constexpr int MUSIC_CREDITS_ALT = 70; constexpr int MUSIC_CREDITS_ALT_FINAL = 71; -constexpr int ACHIEVEMENT_BLUE_BABY = 32; -constexpr int ACHIEVEMENT_DEAD_GOD = 637; constexpr float CUTSCENE_FADE_STEP = 0.05f; constexpr float VIDEO_VOLUME_SCALE = 3; diff --git a/src/entity.cpp b/src/entity.cpp index e3b9ad6..d2f6662 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -6,6 +6,7 @@ #include "entity_npc.h" #include "entity_player.h" #include "entity_tear.h" +#include "fx_layers.h" #include "game.h" #include "log.h" #include "lua_engine.h" @@ -26,14 +27,6 @@ extern "C" } #undef luaL_newstate -// The room's play area on screen: world units from its corner shrink by ROOM_SCREEN_SCALE into a centered view. -constexpr float ROOM_ORIGIN_X = 60; -constexpr float ROOM_ORIGIN_Y = 140; -constexpr float ROOM_SCREEN_SCALE = 0.65f; -constexpr float ROOM_VIEW_HEIGHT = 182; -constexpr float ROOM_VIEW_WIDTH = 338; -constexpr float HALF = 0.5f; - // GetRenderZ's bands: the background layer, the door layer and the normal layer sorted by depth. constexpr int RENDER_INDEX_MASK = 0x3ff; constexpr int RENDER_Z_BACKGROUND_BASE = 100; @@ -806,6 +799,20 @@ void Entity::Update() subtype); } +// A knockback that hurts on impact, hitting a wall: it bounces back along its motion at four fifths of its push and +// takes 10 plus twice the floor's depth (one deeper on the alternate path) once. +constexpr float WALL_IMPACT_BOUNCE = 0.8f; +constexpr float WALL_IMPACT_DAMAGE = 10; +constexpr int WALL_IMPACT_COUNTDOWN = 30; + +void Entity::wall_impact_apply() +{ + float push = vector_length(knockbackDirection); + knockbackDirection = vector_scale(vector_normalized(velocity), push * WALL_IMPACT_BOUNCE); + TakeDamage((float)(g_game->stage_depth_get() - 1) * 2 + WALL_IMPACT_DAMAGE, 0, EntityRef(), WALL_IMPACT_COUNTDOWN); + ClearEntityFlags(FLAG_APPLY_IMPACT_DAMAGE); +} + // A heavy knockback's push: it keeps the entity moving, slowing, until it is spent or something stops it. void Entity::knockback_update() { @@ -826,8 +833,7 @@ void Entity::knockback_update() } if (isCollidesWithGrid) { - if (HasEntityFlags(FLAG_APPLY_IMPACT_DAMAGE)) - reconstruction_missing("Entity::Update 006ae820: the damage a knocked back entity takes hitting a wall"); + if (HasEntityFlags(FLAG_APPLY_IMPACT_DAMAGE)) wall_impact_apply(); knockbackCountdown = knockbackCountdown / 2; } velocity = knockbackDirection; diff --git a/src/entity.h b/src/entity.h index e9b6d71..e4305bc 100644 --- a/src/entity.h +++ b/src/entity.h @@ -113,6 +113,9 @@ enum EntityType : int ENTITY_MOBILE_HOST = 204, ENTITY_BABY_LONG_LEGS = 206, ENTITY_CRAZY_LONG_LEGS = 207, + ENTITY_FLY_L2 = 214, + ENTITY_SPIDER_L2 = 215, + ENTITY_FULL_FLY = 249, ENTITY_FATTY = 208, ENTITY_BLUBBER = 210, ENTITY_DEATHS_HEAD = 212, @@ -129,6 +132,7 @@ enum EntityType : int ENTITY_TUMOR = 229, ENTITY_CAMILLO_JR = 230, ENTITY_NERVE_ENDING = 231, + ENTITY_ONE_TOOTH = 234, ENTITY_GAPING_MAW = 235, ENTITY_BROKEN_GAPING_MAW = 236, ENTITY_GURGLING = 237, @@ -147,6 +151,7 @@ enum EntityType : int ENTITY_FLOATING_KNIGHT = 254, ENTITY_NIGHT_CRAWLER = 255, ENTITY_DART_FLY = 256, + ENTITY_FAT_BAT = 258, ENTITY_IMP = 259, ENTITY_THE_HAUNT = 260, ENTITY_DINGLE = 261, @@ -201,6 +206,7 @@ enum EntityType : int ENTITY_MATRIARCH = 413, ENTITY_BLOOD_PUPPY = 802, ENTITY_BISHOP = 805, + ENTITY_BUBBLES = 806, ENTITY_WRAITH = 807, ENTITY_WILLO = 808, ENTITY_BOMB_GRIMACE = 809, @@ -222,27 +228,42 @@ enum EntityType : int ENTITY_FIRE_WORM = 825, ENTITY_HARDY = 826, ENTITY_FACELESS = 827, + ENTITY_NECRO = 828, ENTITY_MOLE = 829, ENTITY_BIG_BONY = 830, ENTITY_GUTTED_FATTY = 831, ENTITY_EXORCIST = 832, ENTITY_PEEPER_FATTY = 835, + ENTITY_WHIPPER = 834, + ENTITY_REVENANT = 841, ENTITY_PON = 840, ENTITY_SMALL_MAGGOT = 853, ENTITY_PUSTULE = 861, ENTITY_CYST = 862, + ENTITY_MORNINGSTAR = 863, + ENTITY_MOCKULUS = 864, ENTITY_EVIS = 865, ENTITY_DARK_ESAU = 866, + ENTITY_SIREN_HELPER = 966, ENTITY_DRIP = 870, ENTITY_SPLURT = 871, ENTITY_CLOGGY = 872, ENTITY_CLOG = 914, - ENTITY_ORBIT_SPAWNER = 873, + ENTITY_FLY_TRAP = 873, + ENTITY_FARTIGAN = 874, + ENTITY_POOT_MINE = 875, + ENTITY_DUMP = 876, ENTITY_GRUDGE = 877, ENTITY_NEEDLE = 881, + ENTITY_DUST = 882, ENTITY_CULTIST = 885, ENTITY_VIS_FATTY = 886, + ENTITY_BABY_BEGOTTEN = 883, + ENTITY_SWARM_SPIDER = 884, ENTITY_CLICKETY_CLACK = 889, + ENTITY_MAZE_ROAMER = 890, + ENTITY_GOAT = 891, + ENTITY_POOFER = 892, ENTITY_BALL_AND_CHAIN = 893, ENTITY_REAP_CREEP = 900, ENTITY_VISAGE = 903, @@ -856,6 +877,7 @@ struct Entity private: void data_release(); void knockback_update(); + void wall_impact_apply(); void color_params_update(); void status_effects_update(); void damage_events_update(); diff --git a/src/entity_bomb.cpp b/src/entity_bomb.cpp index 9970a57..5efc91c 100644 --- a/src/entity_bomb.cpp +++ b/src/entity_bomb.cpp @@ -114,7 +114,6 @@ constexpr float BOUNCE_VOLUME = 0.5f; // Dr. Fetus' bombs in flight: Wiggle Worm's sway, Tractor Beam's pull toward its line, the boomerang's pull back, and // a rocket's wiggle, thrust and steering, and the smoke it trails. -constexpr float RIGHT_ANGLE = 90; constexpr float HALF_TURN = 180; constexpr float FETUS_WIGGLE_RATE = 0.7f; constexpr float TRACTOR_PULL = 0.01f; @@ -551,7 +550,7 @@ float Entity_Bomb::fetus_flight_update() if (tearFlags[TEAR_WIGGLE]) { float wave = (updateTime - 1) * ROCKET_WIGGLE_RATE; - Vector push = vector_scale(vector_from_angle(rocketAngle + RIGHT_ANGLE), ROCKET_WIGGLE_PUSH * std::sin(wave)); + Vector push = vector_scale(vector_from_angle(rocketAngle + RIGHT_ANGLE_DEGREES), ROCKET_WIGGLE_PUSH * std::sin(wave)); velocity = vector_add(velocity, vector_scale(push, speedMultiplier)); shownAngle = std::sin(wave - ROCKET_WIGGLE_LAG) * ROCKET_WIGGLE_TURN + rocketAngle; } @@ -610,7 +609,7 @@ void Entity_Bomb::rocket_sprite_update(float shownAngle) float angle = angle_wrap(shownAngle); sprite.isFlipX = false; if (HasEntityFlags(FLAG_HELD)) angle = 0; - else if (angle > RIGHT_ANGLE || angle < -RIGHT_ANGLE) + else if (angle > RIGHT_ANGLE_DEGREES || angle < -RIGHT_ANGLE_DEGREES) { angle = HALF_TURN - angle; sprite.isFlipX = true; diff --git a/src/entity_collision.cpp b/src/entity_collision.cpp index 795742e..4a9eed0 100644 --- a/src/entity_collision.cpp +++ b/src/entity_collision.cpp @@ -1,4 +1,5 @@ #include "capsule.h" +#include "boss_pool.h" #include "entity_collision.h" #include "entity_familiar.h" #include "entity_npc.h" @@ -6,6 +7,7 @@ #include "entity_projectile.h" #include "game.h" #include "grid_entity_door.h" +#include "level.h" #include "log.h" #include "manager.h" #include "room.h" @@ -31,7 +33,6 @@ constexpr std::array POOP_GIGA_CENTER_Y = {POOP_GIGA_QUARTER, POOP_GIG -POOP_GIGA_QUARTER}; // The Lost passes the mirror door in the mirror world. -constexpr int MIRROR_DIMENSION = 1; // The Beast's dungeon keeps players this far above its floor's center line. constexpr float BEAST_DUNGEON_OFFSET_Y = 20; @@ -62,7 +63,6 @@ constexpr int FAMILIAR_SAMSONS_CHAINS = 75; constexpr float CHAINS_CRUSH_SPEED_SQUARED = 25; // Mega Satan's room lets shots leave through its walls. -constexpr int BOSS_MEGA_SATAN = 55; // The room types whose doors Notched Axe hacks open. constexpr int ROOM_TYPE_SECRET = 7; @@ -192,7 +192,7 @@ uint32_t Entity_Player::get_grid_collision_at(Vector position) GridEntity_Door& door = static_cast(*grid); if (!(door.doorFlags & DOOR_FLAG_MIRROR) || door.state == DOOR_STATE_OPEN) return COLLISION_WALL; bool isSpirit = GetHealthType() == HEALTH_NO_HEALTH || HasInstantDeathCurse(); - if (!isSpirit && g_game->currentDimensionIdx != MIRROR_DIMENSION) return COLLISION_WALL; + if (!isSpirit && g_game->currentDimensionIdx != DIMENSION_MIRROR) return COLLISION_WALL; collision = COLLISION_WALL_EXCEPT_PLAYER; } else if (collision != COLLISION_WALL_EXCEPT_PLAYER) return collision; diff --git a/src/entity_combat.cpp b/src/entity_combat.cpp index d48c0d6..9c14d4d 100644 --- a/src/entity_combat.cpp +++ b/src/entity_combat.cpp @@ -41,7 +41,6 @@ constexpr int ENTITY_SCOURGE_TYPE = 830; constexpr int SCOURGE_BONE_VARIANT = 10; constexpr int CHARGER_MY_SHADOW = 3; constexpr int FACING_SHIELD_VARIANT = 1; -constexpr float DIAGONAL = 0.70710677f; constexpr int FIREPLACE_NORMAL = 0; constexpr int FIREPLACE_RED = 1; constexpr int FIREPLACE_MOVEABLE = 10; @@ -82,8 +81,6 @@ constexpr float FROZEN_SHARD_SPEED = 5; // The sounds the combat code plays (Lua's SoundEffect). constexpr int SOUND_DEATH_BURST_BONE = 27; -constexpr int SOUND_GOODEATH = 207; -constexpr int SOUND_BONE_BREAK = 500; constexpr int SOUND_BISHOP_HIT = 501; constexpr int SOUND_CHAIN_BREAK = 504; constexpr int BISHOP_HIT_DELAY = 10; @@ -270,17 +267,25 @@ static bool bishop_shield(Entity& entity, Entity& bishop) return false; } -// Part of 006ace60: the boss parts whose own shield may take the hit, none written yet. -static void shielded_part_check(Entity& entity) +// Part of 006ace60: the boss part whose own shield takes the hit, none for others. Dogma's body is shielded by its +// parent, the Heretic's Exorcists while they wake or summon, and Clutch's orbitals by Clutch (the one it holds only +// while Clutch is solid). +static Entity* part_shield_get(Entity& entity) { + constexpr int SHIELD_EXORCIST_WAKING = NPC_STATE_SUICIDE; + constexpr int SHIELD_EXORCIST_SUMMONING = NPC_STATE_SPECIAL; + Entity* spawner = entity.spawnerEntity; Entity* parent = entity.parent; - bool isShieldedSpawn = entity.type == ENTITY_SHIELDED_SPAWN && entity.variant == 1 && spawner && - spawner->type == ENTITY_SHIELD_SPAWNER; - bool isShieldedPart = entity.type == ENTITY_SHIELDED_PART && parent && parent->type == ENTITY_SHIELD_PARENT; - bool isDogmaPart = entity.type == ENTITY_DOGMA && entity.variant == 0 && parent; - if (isShieldedSpawn || isShieldedPart || isDogmaPart) - reconstruction_missing("Entity::TakeDamage 006ace60: a boss part's own shield"); + if (entity.type == ENTITY_DOGMA) return entity.variant == 0 ? parent : nullptr; + if (entity.type == ENTITY_SHIELDED_SPAWN) + { + int state = static_cast(entity).state; + bool isGuarded = entity.variant == 1 && spawner && spawner->type == ENTITY_SHIELD_SPAWNER; + return isGuarded && (state == SHIELD_EXORCIST_SUMMONING || state == SHIELD_EXORCIST_WAKING) ? spawner : nullptr; + } + if (entity.type != ENTITY_SHIELDED_PART || !parent || parent->type != ENTITY_SHIELD_PARENT) return nullptr; + return parent->child.get() != &entity || parent->entityCollisionClass != ENTCOLL_NONE ? parent : nullptr; } // The players a co-op boss fight counts: one for each pair of twins and none for a player's attachments. @@ -307,7 +312,8 @@ bool Entity::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& sou if (damage > 0) { bool isVulnerable = IsVulnerableEnemy(nullptr); - if (isVulnerable || type == ENTITY_DOGMA) shielded_part_check(*this); + Entity* shield = isVulnerable || type == ENTITY_DOGMA ? part_shield_get(*this) : nullptr; + if (shield) return bishop_shield(*this, *shield); if ((isVulnerable && type != ENTITY_BISHOP) || (!isVulnerable && type == ENTITY_DOGMA)) { Entity* bishop = bishop_nearest_find(pos, IsFriendly()); @@ -1106,6 +1112,25 @@ static void player_contact_missing_check(Entity_Player& player, Entity& collider if (player.suplexState == 1) reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: the suplex grab"); } +// Part of 0078e1f0: The Virus and Serpent's Kiss poison an enemy touched for 60 frames at 2 plus a twentieth of the +// square of the player's red hearts (a tenth of an eighth of them, at least 1, in a deathmatch). Serpent's Kiss marks +// it to drop a black heart. The poison is handed down the enemy's chain before it is added. +constexpr int VIRUS_POISON_FRAMES = 60; +constexpr float VIRUS_POISON_BASE = 2; +constexpr float VIRUS_POISON_SCALE = 0.05f; +constexpr float VIRUS_DEATHMATCH_SCALE = 0.125f * 0.1f; + +static void virus_poison_apply(Entity_Player& player, Entity& collider) +{ + if (player.HasCollectible(COLLECTIBLE_SERPENTS_KISS)) collider.AddEntityFlags(FLAG_SPAWN_BLACK_HP); + float hearts = (float)player.redHearts; + if (g_game->deathmatchManager.state >= DEATHMATCH_INTRO) hearts = std::max(1.0f, hearts * VIRUS_DEATHMATCH_SCALE); + collider.bossStatusEffectCooldown = 0; + collider.CopyStatusEffects(); + collider.AddPoison(EntityRef(&player), VIRUS_POISON_FRAMES, hearts * VIRUS_POISON_SCALE * hearts + VIRUS_POISON_BASE, + false); +} + // 0078e1f0 Touches another entity, after a mod's MC_PRE_PLAYER_COLLISION: mid-suplex it passes enemies and shots, // it hurts a vulnerable enemy by its items' contact damage, poisons with The Virus or Serpent's Kiss, and a thrown // Tainted Forgotten slows on enemies. Tainted Forgotten's soul picks the body up. Whether the collision is ignored, which a pony's dash makes it. @@ -1140,7 +1165,7 @@ bool Entity_Player::HandleCollision(Entity* collider, bool isLow) HasCollectible(COLLECTIBLE_SERPENTS_KISS); if (collider->IsActiveEnemy(DEAD_EXCLUDED) && isPoisoning && !collider->HasEntityFlags(FLAG_NO_STATUS_EFFECTS) && !collider->IsFriendly()) - reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: The Virus' poison (Entity::AddPoison)"); + virus_poison_apply(*this, *collider); if (playerType == PLAYER_THEFORGOTTEN_B && !isIgnored && collider->IsEnemy() && HasEntityFlags(FLAG_THROWN) && !collider->IsFriendly()) velocity = vector_scale(velocity, SLOW_ON_CONTACT); diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index 07fd0f9..4537fee 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -40,8 +40,10 @@ constexpr float HOURGLASS_SLOWEST = 0.5f; constexpr float PAUSE_VELOCITY_DECAY = 0.6f; constexpr int SOUND_CHAIN_LOOP = 503; -// The variants the behaviour tables can index, up to the last vanilla one. +// The variants the behaviour tables can index. Past the last vanilla one (the gun) Init and Update run only their +// shared parts, as the original's switches do for a mod's variants. constexpr int EFFECT_VARIANT_LIMIT = 256; +constexpr int EFFECT_VANILLA_LAST = EFFECT_GUN; template static bool is_listed(const std::array& list, int value) @@ -94,11 +96,12 @@ static const EffectBehaviour* behaviour_find(int variant) std::array table{}; for (auto group : {item_effect_behaviours(), portal_effect_behaviours(), blast_effect_behaviours(), soul_effect_behaviours(), - mother_effect_behaviours(), shot_effect_behaviours(), ambient_effect_behaviours(), + mother_effect_behaviours(), shot_effect_behaviours(), vortex_effect_behaviours(), + helper_effect_behaviours(), dogma_effect_behaviours(), ambient_effect_behaviours(), hazard_effect_behaviours(), floor_effect_behaviours(), beam_effect_behaviours(), player_effect_behaviours(), mines_effect_behaviours(), trail_effect_behaviours(), - spike_effect_behaviours(), boss_effect_behaviours(), weapon_effect_behaviours(), - passive_effect_behaviours(), alt_effect_behaviours(), std::span(TIMER_BEHAVIOURS)}) + spike_effect_behaviours(), boss_effect_behaviours(), weapon_effect_behaviours(), passive_effect_behaviours(), + alt_effect_behaviours(), std::span(TIMER_BEHAVIOURS)}) for (const EffectBehaviour& behaviour : group) table[behaviour.variant] = behaviour; return table; }(); @@ -258,7 +261,7 @@ void Entity_Effect::Init(int entityType, int entityVariant, int entitySubType, u if (behaviour->init) behaviour->init(*this); } else if (is_combat_effect(variant)) combat_effect_init(*this); - else if (variant < EFFECT_VARIANT_LIMIT) reconstruction_missing("Entity_Effect::Init 005cdb20: this effect variant"); + else if (variant <= EFFECT_VANILLA_LAST) reconstruction_missing("Entity_Effect::Init 005cdb20: this effect variant"); if (!isExists) return; sprite.LoadGraphics(); @@ -315,7 +318,7 @@ void Entity_Effect::Update() if (behaviour->update) end = behaviour->update(*this); } else if (is_combat_effect(variant)) end = combat_effect_update(*this); - else if (variant < EFFECT_VARIANT_LIMIT) reconstruction_missing("Entity_Effect::Update 005d4380: this effect variant"); + else if (variant <= EFFECT_VANILLA_LAST) reconstruction_missing("Entity_Effect::Update 005d4380: this effect variant"); if (end == EFFECT_UPDATE_RETURN) return; if (timeout > 0 && --timeout < 1) isDead = true; @@ -402,12 +405,6 @@ void Entity_Effect::FollowParent(Entity* newParent) // The rest of Entity_Effect is not reconstructed yet. -// 005d2a70 -void Entity_Effect::update_mr_me() -{ - reconstruction_missing("Entity_Effect::update_mr_me 005d2a70"); -} - // 005d4010 void Entity_Effect::update_wave_chain() { diff --git a/src/entity_effect.h b/src/entity_effect.h index ce3d8c4..a678224 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -259,8 +259,8 @@ enum EffectVariant : int // An effect (Lua's EntityEffect): a visual or a hazard such as creep, a poof or a light beam, with its timeout, its // fall, the per-variant data it keeps and the extra data some variants share. // Init, Update and Render run the shared parts here and hand each variant to its group's behaviour table (the ambient, -// hazard, floor, beam, item, portal, blast, soul, Mother and shot files, and a few the player's and weapons' files -// hold) or to entity_effect_combat.h (blood, gibs, poofs, explosions). Any other variant stops. +// hazard, floor, beam, item, portal, blast, soul, Mother, shot, vortex, helper and Dogma files, and a few the player's +// and weapons' files hold) or to entity_effect_combat.h (blood, gibs, poofs, explosions). Any other variant stops. struct Entity_Effect : Entity { @@ -274,6 +274,8 @@ struct Entity_Effect : Entity std::array varData{}; std::vector hitList; Vector parentOffset{}; + float baseDamage = 0; + float baseScale = 0; float fallingAcceleration = 0; float fallingSpeed = 0; float height = 0; @@ -325,6 +327,19 @@ struct PickupGhostData : Entity_Effect::ExtraData int count = 0; }; +// Construction (005cd850) and destruction are the defaults. +// What Mr. ME! is doing: its job, the cell it works on, the pickup it carries (drawn on it) with the collision it +// took from it, its frames of work, and whether a Glitched Crown pedestal is about. +struct MrMeData : Entity_Effect::ExtraData +{ + ANM2 carried; + int frames = 0; + int gridIndex = -1; + int job = 0; + int savedCollisionClass = 0; + bool isGlitchedCrown = false; +}; + // The groups of variants Entity_Effect hands out by table (entity_effect_.cpp). std::span ambient_effect_behaviours(); std::span hazard_effect_behaviours(); @@ -339,6 +354,9 @@ std::span blast_effect_behaviours(); std::span soul_effect_behaviours(); std::span mother_effect_behaviours(); std::span shot_effect_behaviours(); +std::span vortex_effect_behaviours(); +std::span helper_effect_behaviours(); +std::span dogma_effect_behaviours(); // The frame the plain poofs share: the sprite turned by the effect's rotation (mirrored unless flipped), the effect // gone once its animation ends. diff --git a/src/entity_effect_ambient.cpp b/src/entity_effect_ambient.cpp index 60a681b..20e101c 100644 --- a/src/entity_effect_ambient.cpp +++ b/src/entity_effect_ambient.cpp @@ -11,6 +11,7 @@ #include "grid_entity_door.h" #include "kage_graphics.h" #include "npc_ai.h" +#include "pocket_items.h" #include "room.h" #include "room_grid.h" #include "room_config.h" @@ -31,9 +32,7 @@ constexpr int SOUND_SPAWNER_SUMMON = 265; constexpr int DOOR_STATE_KEEPS_DECORATIONS = 7; constexpr int RENDER_Z_DECORATION_LIMIT = 0x40000000; constexpr float NEAR_PLAYER_RANGE_SQUARED = 10000; -constexpr float FULL_TURN = 360; constexpr float HALF_TURN = 180; -constexpr float RIGHT_ANGLE = 90; // The tiny fly: white in the Cathedral, how it wanders, flees the nearest player within range, dies to tears, // knives and fires, and drops down in circles when dead. @@ -160,9 +159,9 @@ static bool is_listed(const std::array& list, int value) // normalize_angle_degrees 00682740: an angle brought into -180 to 180. static float angle_normalized(float angle) { - if (std::abs(angle) > FULL_TURN) angle = std::fmod(angle, FULL_TURN); - if (angle > HALF_TURN) return angle - FULL_TURN; - if (angle < -HALF_TURN) angle += FULL_TURN; + if (std::abs(angle) > FULL_TURN_DEGREES) angle = std::fmod(angle, FULL_TURN_DEGREES); + if (angle > HALF_TURN) return angle - FULL_TURN_DEGREES; + if (angle < -HALF_TURN) angle += FULL_TURN_DEGREES; return angle; } @@ -289,7 +288,7 @@ static void tiny_bug_update(Entity_Effect& bug) if (grid && grid->type == GRID_PIT && grid_collision_at(bug.pos) != COLLISION_NONE) { bug.pos = bug.targetPosition; - bug.rotation = angle_normalized(random_unit() * FULL_TURN); + bug.rotation = angle_normalized(random_unit() * FULL_TURN_DEGREES); if (grid_collision_at(bug.pos) == COLLISION_PIT) bug.pos = vector_add(bug.pos, random_direction()); } } @@ -375,13 +374,13 @@ static void wall_bug_update(Entity_Effect& bug) bug.pos = wall_position_get(bug.targetPosition); if (depth != bug.targetPosition.x) { - float turn = (depth <= 0) == (bug.rotation <= 0) ? RIGHT_ANGLE : -RIGHT_ANGLE; + float turn = (depth <= 0) == (bug.rotation <= 0) ? RIGHT_ANGLE_DEGREES : -RIGHT_ANGLE_DEGREES; bug.rotation = angle_lerp(bug.rotation, bug.rotation + turn, WALL_BUG_TURN_RATE); } if (grid_collision_at(bug.pos) == COLLISION_WALL_EXCEPT_PLAYER) { - bool isTurnLeft = bug.targetPosition.y <= previous.y ? bug.rotation >= -RIGHT_ANGLE : bug.rotation <= RIGHT_ANGLE; - float turn = isTurnLeft ? -RIGHT_ANGLE : RIGHT_ANGLE; + bool isTurnLeft = bug.targetPosition.y <= previous.y ? bug.rotation >= -RIGHT_ANGLE_DEGREES : bug.rotation <= RIGHT_ANGLE_DEGREES; + float turn = isTurnLeft ? -RIGHT_ANGLE_DEGREES : RIGHT_ANGLE_DEGREES; bug.rotation = angle_lerp(bug.rotation, bug.rotation + turn, WALL_BUG_TURN_RATE); bug.targetPosition = previous; bug.pos = wall_position_get(bug.targetPosition); @@ -738,18 +737,22 @@ static void dice_floor_init(Entity_Effect& floor) floor.sortingLayer = SORTING_BACKGROUND; } -// The dice floor's frame: once armed, the first player standing on it rolls its face's dice, once per room. +// 005d4380 (case 76) The dice floor's frame: once armed, the first player standing on it rolls its face's dice (a +// Tainted Soul through its Forgotten), once per room. static void dice_floor_update(Entity_Effect& floor) { - if (g_game->room->IsSacrificeDone() || floor.FrameCount() <= DICE_ARM_FRAMES) return; + Room& room = *g_game->room; + if (room.IsSacrificeDone() || floor.FrameCount() <= DICE_ARM_FRAMES) return; for (Entity_Player* player : g_game->playerManager.playerList) { if (player->variant != 0 || player->isCoopGhost || player->entityCollisionClass == ENTCOLL_NONE) continue; Vector offset = vector_sub(player->pos, floor.pos); if (std::abs(offset.x) >= DICE_REACH || std::abs(offset.y) >= DICE_REACH) continue; - reconstruction_missing("Entity_Effect::Update 005d4380: the dice floor's roll (Game::Darken, ShakeScreen, " - "the D4, D6, D20 and D100)"); + + room.SetSacrificeDone(true); + dice_room_roll(*player->resolve_tainted_soul(), floor.subtype, floor.initSeed); + return; } } @@ -943,6 +946,35 @@ constexpr int TEAR_FLAG_HOMING = 2; constexpr float LASTING_GROW_FRAMES = 15; constexpr float LASTING_SHRINK_FRAMES = 65; constexpr int PLAYER_CREEP_COUNTDOWN = 10; + +// Liquid poop (T. ???'s spell): subtype 1 trails it behind its parent every 3 frames, puddles of 0.8 to 1.2 lasting +// 450 frames hurting with the parent's poison damage, with a poop splash on each. A puddle takes the kind of the +// poop piles it touches (and of the puddles it touches every other frame) for at least 30 frames, its color easing +// toward that kind's by 2.5 percent a frame. +constexpr int LIQUID_POOP_TRAIL = 1; +constexpr float LIQUID_POOP_TRAIL_PERIOD = 3; +constexpr int LIQUID_POOP_PUDDLE_FRAMES = 450; +constexpr float LIQUID_POOP_SCALE_MIN = 0.8f; +constexpr float LIQUID_POOP_SCALE_SPAN = 0.4f; +constexpr int LIQUID_POOP_SHARE_PERIOD = 2; +constexpr float LIQUID_POOP_KIND_FRAMES = 30; +constexpr float LIQUID_POOP_COLOR_EASE = 0.025f; +constexpr float LIQUID_POOP_PILE_REACH = 40; +constexpr int POOP_PILE_FIRST_KIND = 10; +constexpr ColorMod LIQUID_POOP_COLOR = color_make({0, 0, 0, 1}, {}, {0.6f, 0.4f, 0}); + +// The kinds a puddle takes, as bits by the poop pile variant from 10: burning burns, stinky poisons and puffs gas +// every 15 frames, black slows and holy hallows the players on it. +constexpr int LIQUID_POOP_BURNING = 1 << 3; +constexpr int LIQUID_POOP_STINKY = 1 << 4; +constexpr int LIQUID_POOP_BLACK = 1 << 5; +constexpr int LIQUID_POOP_HOLY = 1 << 6; +constexpr int LIQUID_POOP_KIND_FRAMES_STATUS = 90; +constexpr float LIQUID_POOP_GAS_PERIOD = 15; +constexpr float LIQUID_POOP_GAS_SPEED = 2; +constexpr int LIQUID_POOP_GAS_FRAMES = 30; +constexpr int LIQUID_POOP_SLOW_FRAMES = 4; +constexpr int LIQUID_POOP_HALLOW_FRAMES = 4; constexpr int HOLY_WATER_FREEZE_PERIOD = 10; constexpr int HOLY_WATER_VERSUS_FREEZE_PERIOD = 60; constexpr int HOLY_WATER_FREEZE = 10; @@ -956,12 +988,6 @@ constexpr float PENTAGRAM_VERSUS_DAMAGE = 5; constexpr float PENTAGRAM_FADE = 0.8f; constexpr int PENTAGRAM_FADE_FRAMES = 10; -// A color with its tint and offset, as the Color constructors build it. -static ColorMod color_make(std::array tint, std::array offset) -{ - return {{tint[0], tint[1], tint[2], tint[3]}, {0, 0, 0, 0}, {offset[0], offset[1], offset[2]}}; -} - // Lost Cork's multiplier for a creep's owner, 1 to 3, or 0 for none. static int lost_cork_get(Entity* owner) { @@ -986,19 +1012,16 @@ static void creep_init(Entity_Effect& creep) if (creep.variant == EFFECT_CREEP_RED && g_game->room->backdropType == BACKDROP_WOMB) creep.sprite.color = tint_color_make(0.5f, 0.5f, 0.5f, 1); if (creep.variant == EFFECT_CREEP_STATIC) creep.sprite.bitflags |= CREEP_STATIC_RENDER_FLAG; + if (creep.variant == EFFECT_CREEP_LIQUID_POOP) creep.sprite.color = LIQUID_POOP_COLOR; if (creep.variant == EFFECT_PLAYER_CREEP_GREEN) creep.timeout = GREEN_CREEP_FRAMES; if (creep.variant == EFFECT_PLAYER_CREEP_LEMON_MISHAP && creep.spawnerEntity && creep.spawnerEntity->is_player()) creep.scale = LEMON_MISHAP_PLAYER_SCALE; } -// Settles creep on its first frame: its art and radius by the scale it was spawned at (Lost Cork's growth added), -// drawn at its own scale on the game's frame of a random puddle. The players' white, red, green and holy water creep -// and the yellow hold their first frame, the black and Black Powder their third, and the holy water, brown, yellow and -// slippery creep take their colors. Its alpha now is what it fades from. -// The original divides by zero for an animation without frames. This takes the first frame. -static void creep_settle(Entity_Effect& creep) +// Sizes creep by the scale it was spawned at (Lost Cork's growth added) and plays a random puddle of that size, drawn +// at its own scale. +static void creep_size_set(Entity_Effect& creep) { - creep.state++; float spawnScale = creep.sprite.scale.x; if (int cork = creep.spawnerEntity ? lost_cork_get(creep.spawnerEntity->GetLastSpawner()) : 0) { @@ -1015,6 +1038,16 @@ static void creep_settle(Entity_Effect& creep) creep.size = spawnScale * CREEP_RADIUS_PER_SCALE * creep.scale; creep.sprite.scale = vector_make(creep.scale, creep.scale); creep.sprite.Play(animation); +} + +// Settles creep on its first frame: sized, on the game's frame of its puddle. The players' white, red, green and holy +// water creep and the yellow hold their first frame, the black and Black Powder their third, and the holy water, +// brown, yellow and slippery creep take their colors. Its alpha now is what it fades from. +// The original divides by zero for an animation without frames. This takes the first frame. +static void creep_settle(Entity_Effect& creep) +{ + creep.state++; + creep_size_set(creep); int length = creep.sprite.animState.GetAnimationLength(); creep.sprite.SetFrame(length > 0 ? (float)(g_game->frameCount % length) : 0.0f); @@ -1032,15 +1065,15 @@ static void creep_settle(Entity_Effect& creep) { ColorMod& color = creep.sprite.color; KColor water = kcolor_rgba(135 / 255.0f, 165 / 255.0f, 201 / 255.0f, 1); - creep.sprite.color = color_make({0, 0, 0, 1}, {color._tint[0] * water._red + color._offset[0], + creep.sprite.color = color_make({0, 0, 0, 1}, {}, {color._tint[0] * water._red + color._offset[0], color._tint[1] * water._green + color._offset[1], color._tint[2] * water._blue + color._offset[2]}); creep.timeout /= 2; } else if (creep.variant == EFFECT_CREEP_BROWN) - creep.sprite.color = color_make({0, 0, 0, 1}, {166 / 255.0f, 104 / 255.0f, 41 / 255.0f}); + creep.sprite.color = color_make({0, 0, 0, 1}, {}, {166 / 255.0f, 104 / 255.0f, 41 / 255.0f}); else if (creep.variant == EFFECT_PLAYER_CREEP_YELLOW) - creep.sprite.color = color_make({0, 0, 0, 1}, {146 / 255.0f, 146 / 255.0f, 10 / 255.0f}); + creep.sprite.color = color_make({0, 0, 0, 1}, {}, {146 / 255.0f, 146 / 255.0f, 10 / 255.0f}); break; case EFFECT_PLAYER_CREEP_BLACK: case EFFECT_PLAYER_CREEP_BLACKPOWDER: @@ -1048,7 +1081,7 @@ static void creep_settle(Entity_Effect& creep) creep.sprite.Stop(); break; case EFFECT_CREEP_SLIPPERY_BROWN: - creep.sprite.color = color_make({0, 0, 0, 1}, {0.6f, 0.4f, 0}); + creep.sprite.color = color_make({0, 0, 0, 1}, {}, {0.6f, 0.4f, 0}); break; } creep.minRadius = creep.sprite.color._tint[3]; @@ -1279,6 +1312,134 @@ static void creep_update(Entity_Effect& creep) if (++creep.state > CREEP_FADE_FRAMES) creep.Remove(); } +// A liquid poop trail spawns its puddles behind its living parent, and goes with it. +static void liquid_poop_trail_update(Entity_Effect& trail) +{ + if (!trail.parent || trail.isDead) return trail.Remove(); + if (!trail.GetIntervalTicks(LIQUID_POOP_TRAIL_PERIOD, 0)) return; + + Entity* parent = trail.parent; + uint32_t seed = Random(); + Entity* puddle = g_game->Spawn({.position = parent->pos, .spawner = parent, .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_LIQUID_POOP, .seed = seed}); + if (parent->is_player()) puddle->SetCollisionDamage(static_cast(parent)->meleeDamage); + float scale = random_unit() * LIQUID_POOP_SCALE_SPAN + LIQUID_POOP_SCALE_MIN; + puddle->sprite.scale = vector_make(scale, scale); + static_cast(puddle)->SetTimeout(LIQUID_POOP_PUDDLE_FRAMES); + puddle->Update(); + seed = Random(); + g_game->Spawn({.position = parent->pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOP_EXPLOSION, .seed = seed})->Update(); +} + +// The color a liquid poop puddle eases toward: its kind's, holy over black over stinky over burning, or brown. +static ColorMod liquid_poop_color(int kinds) +{ + std::array offset = {0.6f, 0.4f, 0}; + if (kinds & LIQUID_POOP_HOLY) offset = {0.98f, 1, 1}; + else if (kinds & LIQUID_POOP_BLACK) offset = {0.02f, 0.02f, 0.02f}; + else if (kinds & LIQUID_POOP_STINKY) offset = {0.3f, 0.6f, 0.2f}; + else if (kinds & LIQUID_POOP_BURNING) offset = {0.8f, 0.2f, 0.1f}; + return color_make({0, 0, 0, 1}, {}, offset); +} + +// A liquid poop puddle hurts an enemy on the ground over it every third frame as acid and by its kinds, and slows it +// while black. The statuses name the enemy's own spawner as their source. +static void liquid_poop_hurt(Entity_Effect& puddle, Entity& enemy) +{ + int kinds = puddle.state; + EntityRef spawner(enemy.spawnerEntity); + if (g_game->frameCount % CREEP_DAMAGE_PERIOD == 0) + { + creep_acid_burn(puddle, enemy); + if (kinds & LIQUID_POOP_BURNING && !enemy.HasEntityFlags(FLAG_BURN)) + enemy.AddBurn(spawner, LIQUID_POOP_KIND_FRAMES_STATUS, puddle.collisionDamage, false); + if (kinds & LIQUID_POOP_STINKY && !enemy.HasEntityFlags(FLAG_POISON)) + enemy.AddPoison(spawner, LIQUID_POOP_KIND_FRAMES_STATUS, puddle.collisionDamage, false); + } + if (kinds & LIQUID_POOP_BLACK && !enemy.HasEntityFlags(FLAG_SLOW)) + enemy.AddSlowing(spawner, LIQUID_POOP_SLOW_FRAMES, PLAYER_CREEP_SLOW, CREEP_SLOW_COLOR, false); +} + +// A liquid poop puddle sizes itself on its first frame and loses its kinds once they wear off. It eases toward its +// kinds' color, puffs friendly gas while stinky, shares kinds with the puddles it touches every other frame and takes +// them from the poop piles near it. It hurts enemies over it, and marks the players standing in its opaque part (and +// stains their feet). +static void liquid_poop_puddle_update(Entity_Effect& puddle) +{ + if (puddle.maxRadius == 0) + { + creep_size_set(puddle); + puddle.maxRadius = puddle.sprite.color._tint[3]; + } + float radius = puddle.size * puddle.sprite.scale.x; + puddle.minRadius = std::max(puddle.minRadius - puddle.speedMultiplier, 0.0f); + if (puddle.minRadius <= 0) puddle.state = 0; + puddle.sprite.color = color_lerp(puddle.sprite.color, liquid_poop_color(puddle.state), LIQUID_POOP_COLOR_EASE); + + if (puddle.state & LIQUID_POOP_STINKY && puddle.GetIntervalTicks(LIQUID_POOP_GAS_PERIOD, 0)) + { + uint32_t seed = Random(); + int subtype = random_below(2); + Vector drift = vector_scale(vector_scale(random_direction(), random_unit()), LIQUID_POOP_GAS_SPEED); + auto* gas = static_cast(g_game->Spawn({.position = puddle.pos, + .velocity = vector_add(puddle.velocity, drift), + .subType = subtype, + .type = ENTITY_EFFECT, + .variant = EFFECT_SMOKE_CLOUD, + .seed = seed})); + gas->spawnerType = ENTITY_PLAYER; + gas->SetTimeout(LIQUID_POOP_GAS_FRAMES); + gas->Update(); + } + + if (g_game->frameCount % LIQUID_POOP_SHARE_PERIOD == 0) + for (Entity* other : entity_query(ENTITY_EFFECT, puddle.variant)) + { + auto& near = *static_cast(other); + if (&near == &puddle || near.subtype != 0) continue; + if (vector_length(vector_sub(near.pos, puddle.pos)) > near.size + radius) continue; + puddle.state |= near.state; + puddle.minRadius = std::max(puddle.minRadius, near.minRadius); + } + + for (Entity* entity : entity_query_radius(puddle.pos, radius + LIQUID_POOP_PILE_REACH, QUERY_ENEMIES)) + { + if (entity->type == ENTITY_POOP) + { + if (entity->variant < POOP_PILE_FIRST_KIND) continue; + puddle.state |= 1 << (entity->variant - POOP_PILE_FIRST_KIND); + puddle.minRadius = std::max(puddle.minRadius, LIQUID_POOP_KIND_FRAMES); + continue; + } + if (!entity->IsVulnerableEnemy(nullptr) || entity->IsFlying()) continue; + if (vector_length(vector_sub(entity->pos, puddle.pos)) > entity->size + radius) continue; + Vector offset = vector_sub(entity->pos, puddle.pos); + offset.y *= CREEP_ELLIPSE_SQUASH; + float reach = radius + entity->size; + if (vector_length_squared(offset) < reach * reach) liquid_poop_hurt(puddle, *entity); + } + + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->isDead || player->entityCollisionClass == ENTCOLL_NONE) continue; + if (vector_length(vector_sub(player->pos, puddle.pos)) >= radius + player->size) continue; + KColor texel = puddle.sprite.GetTexel({.renderPos = vector_scale(puddle.pos, SCREEN_SCALE), + .sample = vector_scale(player->pos, SCREEN_SCALE), + .alphaThreshold = CREEP_TEXEL_OPAQUE}); + if (texel._alpha <= CREEP_TEXEL_OPAQUE) continue; + player->creep_contact_add(puddle.state, LIQUID_POOP_HALLOW_FRAMES); + if (puddle.state & LIQUID_POOP_HOLY) player->hallowed_ground_add(LIQUID_POOP_HALLOW_FRAMES); + if (player->entityGridCollisionClass == GRIDCOLL_GROUND) player->SetFootprintColor(texel, false); + } +} + +// 005e7d5c (Update's case 195) Liquid poop: the trail (subtype 1) or a puddle. +static void liquid_poop_update(Entity_Effect& creep) +{ + if (creep.subtype == LIQUID_POOP_TRAIL) liquid_poop_trail_update(creep); + else liquid_poop_puddle_update(creep); +} + // The players' lasting creep (Lemon Mishap, holy water, Lemon Party, milk): Lost Cork grows it on its first frame. It // grows in and shrinks out with its timeout (a player's Lemon Mishap holds full size), and all but the milk burn the // enemies over it, holy water freezing them now and then. @@ -1411,7 +1572,7 @@ constexpr float MOONLIGHT_DEPTH = 10; static void tadpole_init(Entity_Effect& tadpole) { tadpole.sprite.Play("Idle"); - tadpole.rotation = angle_normalized(random_unit() * FULL_TURN); + tadpole.rotation = angle_normalized(random_unit() * FULL_TURN_DEGREES); tadpole.sprite.GetLayer(0)->rotation = tadpole.rotation + HALF_TURN; tadpole.height = 0; tadpole.isUnknown176 = true; @@ -1486,7 +1647,7 @@ static void tadpole_update(Entity_Effect& tadpole) static void lil_ghost_init(Entity_Effect& ghost) { ghost.targetPosition = ghost.pos; - ghost.rotation = angle_normalized(random_unit() * FULL_TURN); + ghost.rotation = angle_normalized(random_unit() * FULL_TURN_DEGREES); ghost.sprite.Play("Idle"); float size = ghost.dropRNG.RandomFloat() * GHOST_SCALE_SPAN + 1; ghost.sprite.scale = vector_make(size, size); @@ -1647,8 +1808,7 @@ static void heaven_door_travel(Entity_Effect& door, Entity_Player& player) game.gameStateFlags |= 1ull << GAME_STATE_HEAVEN_PATH; if (game.stage < STAGE_DARK_ROOM) return; - bool isAltPath = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; - game.seedEffects.ForgetStageSeed((int)game.stage + (isAltPath ? 1 : 0)); + game.seedEffects.ForgetStageSeed(game.stage_depth_get()); } // The heaven door: open while the room is clear (in Backasswards only in the starting room or Genesis's), it takes a @@ -1731,7 +1891,7 @@ constexpr int BEETLE_SHADOW_LAYER = 1; static void beetle_init(Entity_Effect& beetle) { beetle.sprite.Play("WalkHori"); - beetle.rotation = angle_normalized(random_unit() * FULL_TURN); + beetle.rotation = angle_normalized(random_unit() * FULL_TURN_DEGREES); beetle.sprite.GetLayer(0)->rotation = beetle.rotation; beetle.height = 0; beetle.isUnknown176 = true; @@ -1812,7 +1972,7 @@ static void beetle_crawl(Entity_Effect& beetle) if (grid && grid->type == GRID_PIT && grid_collision_at(beetle.pos) != COLLISION_NONE) { beetle.pos = beetle.targetPosition; - beetle.rotation = angle_normalized(random_unit() * FULL_TURN); + beetle.rotation = angle_normalized(random_unit() * FULL_TURN_DEGREES); if (grid_collision_at(beetle.pos) == COLLISION_PIT) beetle.pos = vector_add(beetle.pos, random_direction()); } } @@ -1943,7 +2103,7 @@ static void butterfly_init(Entity_Effect& butterfly) { butterfly.sprite.Play("Idle"); butterfly.sprite.SetFrame((float)random_below(butterfly.sprite.animState.GetAnimationLength())); - butterfly.rotation = normalize_angle_degrees(random_unit() * FULL_TURN); + butterfly.rotation = normalize_angle_degrees(random_unit() * FULL_TURN_DEGREES); butterfly.sprite.rotation = butterfly.rotation; float height = random_unit() * BUTTERFLY_FLIGHT_SPAN + BUTTERFLY_FLIGHT_LOW; butterfly.posOffset.y = height; @@ -2128,6 +2288,7 @@ constexpr auto AMBIENT_BEHAVIOURS = std::to_array({ {EFFECT_CREEP_SLIPPERY_BROWN, creep_init, effect_finishing, nullptr}, {EFFECT_CREEP_STATIC, creep_init, effect_finishing, nullptr}, {EFFECT_PLAYER_CREEP_YELLOW, creep_init, effect_finishing, nullptr}, + {EFFECT_CREEP_LIQUID_POOP, creep_init, effect_finishing, nullptr}, {EFFECT_PLAYER_CREEP_LEMON_MISHAP, creep_init, effect_finishing, nullptr}, {EFFECT_PLAYER_CREEP_HOLYWATER, creep_init, effect_finishing, nullptr}, {EFFECT_PLAYER_CREEP_LEMON_PARTY, creep_init, effect_finishing, nullptr}, diff --git a/src/entity_effect_combat.cpp b/src/entity_effect_combat.cpp index bcacb26..d2657ad 100644 --- a/src/entity_effect_combat.cpp +++ b/src/entity_effect_combat.cpp @@ -184,10 +184,8 @@ constexpr float COLOR_CHANNEL_MAX = 255; // One world unit is 0.65 screen pixels. A glowing stain sits on whole pixels. constexpr float WORLD_PER_PIXEL = 1.5384616f; -constexpr float HALF = 0.5f; // The tear poofs' quarter turns, the ripple's small sizes and the poofs' layers. -constexpr float RIGHT_ANGLE = 90; constexpr float RIPPLE_TINY_SCALE = 0.5f; constexpr float RIPPLE_SMALL_SCALE = 0.75f; constexpr float RIPPLE_TINY_GROWTH = 2; @@ -311,7 +309,6 @@ constexpr float WORM_TEAR_RANGE = 5; constexpr float WORM_STILL_SPEED_SQUARED = 1; constexpr float HALF_TURN = 180; -constexpr float FULL_TURN = 360; constexpr float SPRITE_UP = 90; static CombatEffect variant_get(const Entity_Effect& effect) @@ -333,9 +330,9 @@ bool is_combat_effect(int variant) // normalize_angle_degrees 00682740: an angle wrapped into -180 to 180. static float angle_wrap(float angle) { - if (std::fabs(angle) > FULL_TURN) angle = std::fmod(angle, FULL_TURN); - if (angle > HALF_TURN) return angle - FULL_TURN; - if (angle < -HALF_TURN) return angle + FULL_TURN; + if (std::fabs(angle) > FULL_TURN_DEGREES) angle = std::fmod(angle, FULL_TURN_DEGREES); + if (angle > HALF_TURN) return angle - FULL_TURN_DEGREES; + if (angle < -HALF_TURN) return angle + FULL_TURN_DEGREES; return angle; } @@ -439,7 +436,7 @@ static void poop_particle_init(Entity_Effect& effect) { effect.fallingAcceleration = PARTICLE_GRAVITY; effect.height = PARTICLE_START_HEIGHT; - effect.sprite.GetLayer(0)->rotation = random_unit() * FULL_TURN; + effect.sprite.GetLayer(0)->rotation = random_unit() * FULL_TURN_DEGREES; effect.sprite.Play(GIB_ANIMATIONS[Random() % GIB_ANIMATIONS.size()]); effect.fallingSpeed = GIB_FALL - random_unit() * GIB_RISE_RANGE; } @@ -485,7 +482,7 @@ static void dust_cloud_init(Entity_Effect& effect) int frame = clouds->length == 0 ? 0 : (int)(Random() % (uint32_t)clouds->length); effect.sprite.SetFrame(clouds->name, frame); effect.sprite.isFlipX = !(Random() & 1); - effect.sprite.rotation = random_unit() * FULL_TURN - HALF_TURN; + effect.sprite.rotation = random_unit() * FULL_TURN_DEGREES - HALF_TURN; effect.sprite.scale = vector_make(DUST_SCALE, DUST_SCALE); effect.renderZOffset = POOF_RENDER_Z; if (effect.subtype == DUST_DARK) effect.sprite.color = {{1, 1, 1, 1}, {}, {DUST_DARKEN, DUST_DARKEN, DUST_DARKEN}}; @@ -519,7 +516,7 @@ static void worm_init(Entity_Effect& effect) if (effect.subtype >= 0 && effect.subtype < (int)WORM_ANIMATIONS.size()) effect.sprite.Play(WORM_ANIMATIONS[effect.subtype]); - effect.rotation = angle_wrap(random_unit() * FULL_TURN); + effect.rotation = angle_wrap(random_unit() * FULL_TURN_DEGREES); effect.sprite.rotation = effect.rotation; effect.sortingLayer = SORTING_DOOR; effect.fallingAcceleration = PARTICLE_GRAVITY; @@ -552,11 +549,11 @@ void combat_effect_init(Entity_Effect& effect) case CombatEffect::TEAR_POOF_B: case CombatEffect::TEAR_POOF_SMALL: case CombatEffect::TEAR_POOF_VERYSMALL: - effect.rotation = (float)(Random() & 3) * RIGHT_ANGLE; + effect.rotation = (float)(Random() & 3) * RIGHT_ANGLE_DEGREES; effect.isUnknown176 = true; break; case CombatEffect::IMPACT: - effect.rotation = (float)(Random() & 3) * RIGHT_ANGLE; + effect.rotation = (float)(Random() & 3) * RIGHT_ANGLE_DEGREES; effect.isUnknown176 = true; sprite.isFlipX = !(Random() & 1); break; @@ -845,7 +842,7 @@ static void blood_particle_start(Entity_Effect& effect) } else { - effect.sprite.GetLayer(0)->rotation = random_unit() * FULL_TURN; + effect.sprite.GetLayer(0)->rotation = random_unit() * FULL_TURN_DEGREES; if (const char* animation = blood_particle_animation(effect)) effect.sprite.Play(animation); effect.fallingSpeed = GIB_FALL - random_unit() * GIB_RISE_RANGE; } @@ -1151,7 +1148,7 @@ static void worm_grid_push(Entity_Effect& effect) if (grid->type != GRID_PIT || room_grid_collision_at(effect.pos) == COLLISION_NONE) return; effect.pos = effect.targetPosition; - effect.rotation = angle_wrap(random_unit() * FULL_TURN); + effect.rotation = angle_wrap(random_unit() * FULL_TURN_DEGREES); if (room_grid_collision_at(effect.pos) == COLLISION_PIT) effect.pos = vector_add(effect.pos, random_direction()); } diff --git a/src/entity_effect_dogma.cpp b/src/entity_effect_dogma.cpp new file mode 100644 index 0000000..b1e4045 --- /dev/null +++ b/src/entity_effect_dogma.cpp @@ -0,0 +1,724 @@ +#include "beam_renderer.h" +#include "entity_effect.h" +#include "entity_laser.h" +#include "entity_list.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "game.h" +#include "manager.h" +#include "boss_ai.h" +#include "entity_npc.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "room.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include +#include + +// Dogma's effects: the orb that rains light beams and the black hole of its last phase. + +// The orb (subtype 0) holds on its parent, puffs a swirl every 8 ticks and hurts the other side within its size (a +// target again every 5 frames). With volleys left (its min radius) and its animation looping, it counts up through a +// volley, spawning its beam spots (subtype 1) on the steps of its table, charging at step 6 and firing at step 75. +// Let go of, it slows, rises to 27.5 up and fans 8 spots once, then dies with a shot on its animation's event. +// A spot sits on the orb, aiming out 21 and turning, slowing over its last 20 frames, and fires a thin laser where it +// aims when it dies. A swirl (subtype 2) grows and spins away as it fades. +constexpr int DOGMA_SPOT = 1; +constexpr int DOGMA_SWIRL = 2; +constexpr float SWIRL_GROWTH = 0.1f; +constexpr float SWIRL_FADE = 0.07f; +constexpr float SWIRL_SPIN = 30; +constexpr float SWIRL_DEPTH = 20; +constexpr float SWIRL_SCALE = 0.7f; +constexpr float SPOT_DEPTH = 60; +constexpr float ORB_DEPTH = 40; +constexpr float SPOT_SCREEN_SCALE = 0.65f; +constexpr int SPOT_SLOWING_FRAMES = 21; +constexpr float SPOT_SPIN_DRAG = 0.9f; +constexpr float SPOT_LASER_HEIGHT = -15; +constexpr int SPOT_LASER_VARIANT = 5; +constexpr int SPOT_LASER_TIMEOUT = 12; +constexpr float SPOT_LASER_SCALE = 0.5f; +constexpr int SPOT_PRIORITY = 255; +constexpr ColorMod SPOT_LASER_COLOR = color_make({1, 1, 1, 1}, {1, 1, 1, 1}); + +// The spot frames by how far out it aims: past 19, 17 and 12. +constexpr std::array SPOT_REACHES = {19, 17, 12}; + +constexpr float ORB_SWIRL_PERIOD = 8; +constexpr int ORB_RNG_SHIFT = 35; +constexpr int ORB_CHARGE_STEP = 6; +constexpr int ORB_FIRE_STEP = 75; +constexpr float ORB_CHARGE_VOLUME = 0.2f; +constexpr float ORB_CHARGE_PITCH = 1.05946f; +constexpr float ORB_FIRE_VOLUME = 0.7f; +constexpr float ORB_SPOT_TURN = 110; +constexpr float ORB_SPOT_LEAD = 30; +constexpr float ORB_SPOT_SPREAD = 60; +constexpr float ORB_SPOT_REACH = 21; +constexpr int ORB_SPIN_FRAMES = 20; +constexpr float ORB_SPIN_SPAN = 4; +constexpr float ORB_SPIN_LEAD = 8.33731f; +constexpr int ORB_SHOT_DELAY = 2; + +// The steps between a volley's spots: 6, 5, 4, 3, 3, 2, 2 and then one a step. +constexpr std::array ORB_SPOT_STEPS = {6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + +constexpr int ORB_LOOSE = -1; +constexpr int ORB_DYING = -2; +constexpr int ORB_FANNED = -3; +constexpr int ORB_HOLD_FRAMES = 45; +constexpr float ORB_DRAG_FRAMES = 20; +constexpr float ORB_DRAG = 0.8f; +constexpr float ORB_MIN_SPEED = 2; +constexpr float ORB_RISE = 2; +constexpr float ORB_TOP = -27.5f; +constexpr int ORB_FAN_SPOTS = 8; +constexpr float ORB_FAN_TURN = 45; +constexpr int ORB_FAN_EXTRA_FRAMES = 12; +constexpr float ORB_FAN_SCALE = 2; +constexpr int ORB_HIT_PERIOD = 5; +constexpr int ORB_HIT_COUNTDOWN = 30; + +// The beam guide a spot draws: a line out from it, fading in over its first 15 frames and out over its life, and in +// its last 5 frames thickening as it fades. It turns half a frame ahead on even frames. +constexpr int SPOT_GUIDE_LAST_FRAMES = 5; +constexpr float SPOT_GUIDE_FADE_MIN = 0.2f; +constexpr float SPOT_GUIDE_FADE_IN = 15; +constexpr float SPOT_GUIDE_REACH = 250; +constexpr float SPOT_GUIDE_REACH_MIN = 40; +constexpr float SPOT_GUIDE_ALPHA = 0.5f; + +// The Dogma orb part of 005cdb20 (Init): a swirl spins in at random, a spot shows its spot frame (its second layer +// hidden, both additive), the orb opens with its glow additive. +static void dogma_orb_init(Entity_Effect& orb) +{ + if (orb.subtype == DOGMA_SWIRL) + { + orb.sprite.Play("Swirl"); + orb.sprite.scale = vector_make(SWIRL_SCALE, SWIRL_SCALE); + orb.sprite.rotation = random_unit() * DEGREES_PER_TURN; + orb.sprite.color._tint[3] = 1; + return; + } + if (orb.subtype == DOGMA_SPOT) + { + orb.sprite.SetFrame("Spot", 0); + orb.sprite.GetLayer(1)->isVisible = false; + layer_additive_set(*orb.sprite.GetLayer(0)); + layer_additive_set(*orb.sprite.GetLayer(1)); + return; + } + orb.AddEntityFlags(FLAG_DONT_OVERWRITE); + orb.sprite.bitflags |= ANIM_RENDER_STATIC; + layer_additive_set(*orb.sprite.GetLayer(2)); + orb.sprite.Play("Open"); + orb.minRadius = 0; +} + +// A swirl grows, spins and fades, gone the moment it would be clear. +static EffectUpdateEnd dogma_swirl_update(Entity_Effect& swirl) +{ + swirl.renderDepthOffset = SWIRL_DEPTH; + float scale = swirl.speedMultiplier * SWIRL_GROWTH + swirl.sprite.scale.x; + float alpha = swirl.sprite.color._tint[3] - swirl.speedMultiplier * SWIRL_FADE; + if (alpha <= 0) + { + swirl.Remove(); + return EFFECT_UPDATE_RETURN; + } + swirl.sprite.rotation = angle_wrapped(swirl.sprite.rotation - swirl.speedMultiplier * SWIRL_SPIN); + swirl.sprite.scale = vector_make(scale, scale); + swirl.sprite.color._tint[3] = alpha; + return EFFECT_UPDATE_FINISH; +} + +// Points a spot's sprite along its aim. +static void dogma_spot_aim(Entity_Effect& spot) +{ + spot.sprite.rotation = vector_angle(spot.targetPosition); + spot.sprite.offset = vector_scale(spot.targetPosition, SPOT_SCREEN_SCALE); +} + +// A spot rides its orb and turns its aim, firing its laser as it dies. Without an orb it goes. +static void dogma_spot_update(Entity_Effect& spot) +{ + if (spot.parent) + { + spot.pos = spot.parent->pos; + spot.velocity = spot.parent->velocity; + spot.posOffset = spot.parent->posOffset; + } + if (spot.state == 0) + { + spot.renderDepthOffset = SPOT_DEPTH; + float reach = vector_length(spot.targetPosition); + int frame = 3; + for (float step : SPOT_REACHES) + if (reach <= step) frame--; + spot.sprite.SetFrame((float)frame); + dogma_spot_aim(spot); + spot.state = 1; + } + if (spot.timeout < SPOT_SLOWING_FRAMES) spot.rotation *= timescale_factor(SPOT_SPIN_DRAG, spot.speedMultiplier); + spot.targetPosition = vector_rotated(spot.targetPosition, spot.rotation * spot.speedMultiplier); + dogma_spot_aim(spot); + + if (spot.isDead) + { + Vector height = vector_make(0, SPOT_LASER_HEIGHT); + Vector from = vector_sub(vector_add(vector_add(spot.pos, spot.targetPosition), spot.posOffset), height); + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = from, + .posOffset = height, + .source = &spot, + .angleDegrees = vector_angle(spot.targetPosition), + .timeout = SPOT_LASER_TIMEOUT, + .variant = SPOT_LASER_VARIANT}); + laser->spawnerEntity = spot.spawnerEntity; + laser->set_scale(spot.sprite.scale.x * SPOT_LASER_SCALE); + laser->SetColor(SPOT_LASER_COLOR, -1, SPOT_PRIORITY, false, true); + laser->isDisableInitSound = true; + spot.Remove(); + } + if (!spot.parent) spot.Remove(); +} + +// The spin a spot turns at, -4 to 4, and the angle it starts at so that it ends at the one given. +static std::pair dogma_spot_spin(float angle, int life) +{ + float spin = (random_unit() + random_unit()) * ORB_SPIN_SPAN - ORB_SPIN_SPAN; + return {spin, angle - (float)(life - ORB_SPIN_FRAMES) * spin - spin * ORB_SPIN_LEAD}; +} + +// Sets a new spot's life, spin, aim and size, and starts it on its orb. +static void dogma_spot_start(Entity_Effect& orb, Entity_Effect& spot, int life, float spin, Vector aim, float scale) +{ + spot.SetTimeout(life); + spot.rotation = spin; + spot.targetPosition = aim; + spot.parent = &orb; + spot.posOffset = orb.posOffset; + spot.sprite.scale = vector_make(scale, scale); + spot.Update(); +} + +// The orb's volley: a step per tick, a spot on each step its table names, charging at 6 and firing at 75. +static void dogma_orb_volley(Entity_Effect& orb) +{ + if (!orb.sprite.animState.IsLoopingAnimation()) return; + RNG rng = rng_make(orb.initSeed, ORB_RNG_SHIFT); + float base = rng.RandomFloat() * DEGREES_PER_TURN; + int ticks = (int)orb.updateTime - (int)orb.prevUpdateTime; + for (int tick = 0; tick < ticks; tick++) + { + orb.state++; + if (orb.state == ORB_CHARGE_STEP) + npc_sound_play(SOUND_DOGMA_LIGHT_RAY_CHARGE, ORB_CHARGE_VOLUME, ORB_SHOT_DELAY, ORB_CHARGE_PITCH); + int step = 0; + size_t index = 0; + for (; index < ORB_SPOT_STEPS.size(); index++) + { + step += ORB_SPOT_STEPS[index]; + if (orb.state == step) break; + } + if (orb.state == step) + { + uint32_t seed = Random(); + auto* spot = static_cast(g_game->Spawn({.position = orb.pos, + .spawner = orb.spawnerEntity, + .subType = DOGMA_SPOT, + .type = ENTITY_EFFECT, + .variant = EFFECT_DOGMA_ORB, + .seed = seed})); + float lead = (float)index * ORB_SPOT_TURN + base - ORB_SPOT_LEAD; + float spread = random_unit(); + float angle = lead + spread * random_unit() * ORB_SPOT_SPREAD; + int life = ORB_FIRE_STEP - orb.state; + auto [spin, start] = dogma_spot_spin(angle, life); + Vector aim = vector_scale(vector_from_angle(start), ORB_SPOT_REACH); + aim = vector_scale(aim, std::sin((random_unit() * 0.5f + 0.5f) * PI_F * 0.5f)); + dogma_spot_start(orb, *spot, life, spin, aim, random_unit() + 1); + } + else if (orb.state == ORB_FIRE_STEP) + { + g_manager->sfxManager.Stop(SOUND_DOGMA_LIGHT_RAY_CHARGE); + npc_sound_play(SOUND_DOGMA_LIGHT_RAY_FIRE, ORB_FIRE_VOLUME, ORB_SHOT_DELAY, 1); + orb.sprite.Play("Attack"); + orb.state = 0; + orb.minRadius--; + break; + } + } +} + +// The orb let go of slows, rises and fans its last spots once. Held, it stays 45 more frames. Dead, it fires on its +// animation's shot and goes when it ends. +static void dogma_orb_loose_update(Entity_Effect& orb) +{ + if (orb.state >= 0) orb.state = ORB_LOOSE; + if (!orb.parent) + { + float slowing = std::min((float)(orb.lifespan - orb.timeout) / ORB_DRAG_FRAMES, 1.0f); + orb.velocity = vector_scale(orb.velocity, std::lerp(1.0f, ORB_DRAG, slowing)); + if (vector_length(orb.velocity) < ORB_MIN_SPEED) orb.velocity = vector_resized(orb.velocity, ORB_MIN_SPEED); + orb.posOffset.y = std::min(orb.posOffset.y + ORB_RISE, ORB_TOP); + if (!orb.isDead && orb.state != ORB_FANNED) + { + orb.state = ORB_FANNED; + for (int i = 0; i < ORB_FAN_SPOTS; i++) + { + uint32_t seed = Random(); + auto* spot = static_cast(g_game->Spawn({.position = orb.pos, + .spawner = orb.spawnerEntity, + .subType = DOGMA_SPOT, + .type = ENTITY_EFFECT, + .variant = EFFECT_DOGMA_ORB, + .seed = seed})); + int life = orb.timeout + ORB_FAN_EXTRA_FRAMES; + auto [spin, start] = dogma_spot_spin((float)i * ORB_FAN_TURN, life); + dogma_spot_start(orb, *spot, life, spin, vector_scale(vector_from_angle(start), ORB_SPOT_REACH), + ORB_FAN_SCALE); + } + } + } + else orb.SetTimeout(ORB_HOLD_FRAMES); + + if (!orb.isDead) return; + if (orb.state != ORB_DYING) + { + orb.state = ORB_DYING; + orb.sprite.Play("Death"); + } + if (orb.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_DOGMA_LIGHT_RAY_FIRE, 1, ORB_SHOT_DELAY, 1); + orb.velocity = {}; + } + if (orb.sprite.IsFinished()) orb.Remove(); +} + +// The orb hurts what is on the other side from it within its size, each once until its hits clear: enemies by its +// damage, players and familiars by 1. +static void dogma_orb_hits_update(Entity_Effect& orb) +{ + bool isFriendly = orb.HasEntityFlags(FLAG_FRIENDLY); + if (orb.IsFrame(ORB_HIT_PERIOD, orb.index)) orb.hitList.clear(); + for (Entity* entity : entity_query_radius(orb.pos, orb.size, QUERY_FAMILIARS | QUERY_ENEMIES | QUERY_PLAYERS)) + { + bool isAlly = entity->HasEntityFlags(FLAG_FRIENDLY) || entity->is_player() || entity->IsFamiliar(); + if (entity->isDead || isFriendly == isAlly) continue; + if (EntityList::HitListContains(orb.hitList, *entity)) continue; + hit_list_insert(orb.hitList, *entity); + float damage = entity->IsEnemy() ? orb.collisionDamage : 1; + entity->TakeDamage(damage, 0, EntityRef(&orb), ORB_HIT_COUNTDOWN); + } +} + +// The orb rides its parent, idles, puffs swirls, fires its volleys or drifts loose, and hurts while alive. +static void dogma_orb_body_update(Entity_Effect& orb) +{ + if (orb.parent) + { + orb.pos = orb.parent->pos; + orb.velocity = orb.parent->velocity; + } + orb.renderDepthOffset = ORB_DEPTH; + if (!orb.isDead && orb.sprite.IsFinished()) orb.sprite.Play("Idle"); + if (orb.GetIntervalTicks(ORB_SWIRL_PERIOD, 0) && !orb.isDead) + { + uint32_t seed = Random(); + Entity* swirl = g_game->Spawn({.position = orb.pos, + .spawner = &orb, + .subType = DOGMA_SWIRL, + .type = ENTITY_EFFECT, + .variant = EFFECT_DOGMA_ORB, + .seed = seed}); + swirl->posOffset = orb.posOffset; + swirl->Update(); + } + if (orb.minRadius > 0) dogma_orb_volley(orb); + else dogma_orb_loose_update(orb); + if (!orb.isDead) dogma_orb_hits_update(orb); +} + +// 005de1a6 (Update's case 172) The swirl, the spot or the orb. +static EffectUpdateEnd dogma_orb_update(Entity_Effect& orb) +{ + if (orb.subtype == DOGMA_SWIRL) return dogma_swirl_update(orb); + if (orb.subtype == DOGMA_SPOT) dogma_spot_update(orb); + else dogma_orb_body_update(orb); + return EFFECT_UPDATE_FINISH; +} + +// The Dogma orb part of 00607620 (Render): the sprite, and a spot's beam guide. +static void dogma_orb_render(Entity_Effect& spot, const Vector& offset) +{ + spot.sprite.Render(SpriteDraw{spot.renderPosition, {}, {}}); + if (spot.subtype != DOGMA_SPOT || vector_is_zero(spot.targetPosition)) return; + + Vector aim = spot.targetPosition; + if ((g_manager->framecount & 1) == 0) aim = vector_rotated(aim, spot.rotation * spot.speedMultiplier * 0.5f); + float widthScale = 1; + float reach = 0; + if (spot.timeout <= SPOT_GUIDE_LAST_FRAMES) + { + float fade = std::clamp((float)spot.timeout / SPOT_GUIDE_LAST_FRAMES, 0.0f, 1.0f) * (1 - SPOT_GUIDE_FADE_MIN) + SPOT_GUIDE_FADE_MIN; + widthScale = 2 - fade; + reach = fade * fade; + } + else + { + float spent = std::clamp(((float)spot.timeout - SPOT_GUIDE_LAST_FRAMES) / ((float)spot.lifespan - SPOT_GUIDE_LAST_FRAMES), + 0.0f, 1.0f); + float fade = std::sqrt(1 - spent); + float fadeIn = std::min((float)(spot.lifespan - spot.timeout) / SPOT_GUIDE_FADE_IN, 1.0f); + reach = fadeIn * fade * fade; + } + float width = spot.sprite.scale.x * widthScale; + Vector start = vector_add(spot.pos, spot.posOffset); + g_beamRenderer.Begin(spot.sprite, 1, BEAM_FRAME_MAIN, BEAM_COORDINATE_HEIGHTS); + g_beamRenderer.Add({.color = color_make({1, 1, 1, SPOT_GUIDE_ALPHA}), + .pos = vector_add(render_position_get(vector_add(start, aim), RENDER_SNAPPED), offset), + .width = width}); + Vector far = vector_resized(aim, (reach * SPOT_GUIDE_REACH + SPOT_GUIDE_REACH_MIN) * spot.sprite.scale.x); + g_beamRenderer.Add({.color = color_make({1, 1, 1, 0}), + .pos = vector_add(render_position_get(vector_add(start, far), RENDER_SNAPPED), offset), + .width = width}); + g_beamRenderer.End(); +} + +// The black hole of Dogma's last phase (subtype 0) drifts to a stop away from the walls, kept off Dogma's +// television, and trails dark haemo while it falls to the floor. Dying the first time, it opens for 120 frames: it +// shakes the room, throws a ring spark every 6 ticks with a slow shot 560 out along it, a swirl every 14, and pulls +// (harder as it grows) everything but Dogma, eating what comes within 48. Then it closes: on its shot it farts, +// bursts into 22 shots and pops the ring's shots, and goes when its animation ends. A spark (subtype 1) turns and +// goes when its animation ends, a swirl (subtype 2) shrinks, spins and shows until it is a tenth. +constexpr int BLACKHOLE_SPARK = 1; +constexpr int BLACKHOLE_SWIRL = 2; +constexpr int BLACKHOLE_CLOSED = 0; +constexpr int BLACKHOLE_OPEN = 1; +constexpr int BLACKHOLE_CLOSING = 2; +constexpr float BLACKHOLE_DEPTH = -10; +constexpr float BLACKHOLE_SWIRL_SHRINK = 0.1f; +constexpr float BLACKHOLE_SWIRL_SHOW = 0.07f; +constexpr float BLACKHOLE_SWIRL_SPIN = 30; +constexpr float BLACKHOLE_SWIRL_SMALLEST = 0.1f; +constexpr float BLACKHOLE_SWIRL_SCALE = 3; +constexpr float BLACKHOLE_CLOSED_FRAMES = 45; +constexpr float BLACKHOLE_DRAG_FRAMES = 20; +constexpr float BLACKHOLE_DRAG = 0.8f; +constexpr float BLACKHOLE_WALL_MARGIN = 80; +constexpr float BLACKHOLE_WALL_PUSH = 0.02f; +constexpr float BLACKHOLE_MAX_PUSH = 12; +constexpr float BLACKHOLE_TV_REACH = 100; +constexpr int DOGMA_TV = 1; +constexpr float BLACKHOLE_TRAIL_PERIOD = 2; +constexpr float BLACKHOLE_TRAIL_DRAG = 0.5f; +constexpr int BLACKHOLE_PRIORITY = 255; +constexpr float BLACKHOLE_OPEN_STRENGTH = 4; +constexpr int BLACKHOLE_OPEN_FRAMES = 120; +constexpr int BLACKHOLE_CLOSE_SOUND_FRAMES = 30; +constexpr float BLACKHOLE_SHAKE_PERIOD = 3; +constexpr int BLACKHOLE_SHAKE = 2; +constexpr float BLACKHOLE_SPARK_PERIOD = 6; +constexpr float BLACKHOLE_SWIRL_PERIOD = 14; +constexpr float BLACKHOLE_RING_REACH = 560; +constexpr float BLACKHOLE_STRENGTH_GROWTH = 0.25f; +constexpr int BLACKHOLE_RING_SHOT = 2; +constexpr float BLACKHOLE_RING_HEIGHT = -27; +constexpr float BLACKHOLE_RING_FALL = -0.095f; +constexpr float BLACKHOLE_RING_ACCELERATION = 0.6f; +constexpr int BLACKHOLE_RING_FADE_FRAMES = 10; +constexpr uint64_t BLACKHOLE_RING_FLAGS = PROJECTILE_NO_WALL_COLLIDE | PROJECTILE_ACCELERATE; +constexpr float BLACKHOLE_SHOT_SCALE_MIN = 0.6f; +constexpr float BLACKHOLE_SHOT_SCALE_MAX = 1.8f; +constexpr ColorMod BLACKHOLE_TRAIL_COLOR = color_make({0, 0, 0, 1}); +constexpr ColorMod BLACKHOLE_RING_COLOR = color_make({1, 1, 1, 0}); + +// How hard the open hole pulls: enemies, tears and bombs 6, the rest 4, times its strength, nearer harder within 8 +// (or less), shots and tears weaker for their first 30 frames, players weaker nearer than 480. What comes within 48 +// is eaten: shots and tears burst (unless just fired, low or Ludovico), bombs and rerollable pickups go, players hurt. +constexpr float BLACKHOLE_PULL = 4; +constexpr float BLACKHOLE_STRONG_PULL = 6; +constexpr float BLACKHOLE_NEAR = 8; +constexpr float BLACKHOLE_NEAR_SHARE = 4096; +constexpr float BLACKHOLE_FALLOFF = 0.05f; +constexpr float BLACKHOLE_SHOT_WARMUP = 30; +constexpr float BLACKHOLE_PLAYER_FALLOFF = 230400; +constexpr float BLACKHOLE_SHOT_DRAG = 2; +constexpr float BLACKHOLE_SHOT_DRAG_MIN = 0.5f; +constexpr float BLACKHOLE_EAT_REACH_SQUARED = 2304; +constexpr int BLACKHOLE_SHOT_SAFE_FRAMES = 15; +constexpr float BLACKHOLE_SHOT_LOWEST = -50; +constexpr int BLACKHOLE_HURT_COUNTDOWN = 30; + +// The closing burst. +constexpr int BLACKHOLE_BURST_SHAKE = 10; +constexpr float BLACKHOLE_BURST_FART = 120; +constexpr int BLACKHOLE_BURST_SHOTS = 22; +constexpr float BLACKHOLE_BURST_SPEED = 15; +constexpr float BLACKHOLE_BURST_SPOT = 5; +constexpr float BLACKHOLE_BURST_HEIGHT_MIN = -22; +constexpr float BLACKHOLE_BURST_HEIGHT_MAX = -30; +constexpr float BLACKHOLE_BURST_FALL_MIN = -0.06f; +constexpr float BLACKHOLE_BURST_FALL_MAX = -0.09f; +constexpr float BLACKHOLE_BURST_ACCELERATION = 0.95f; + +// The Dogma black hole part of 005cdb20 (Init): a swirl shows from clear, a spark trails at a random size and turn, +// the hole idles closed for 45 frames. +static void dogma_hole_init(Entity_Effect& hole) +{ + if (hole.subtype == BLACKHOLE_SWIRL) + { + hole.sprite.Play("Swirl"); + hole.sprite.scale = vector_make(BLACKHOLE_SWIRL_SCALE, BLACKHOLE_SWIRL_SCALE); + hole.sprite.rotation = random_unit() * DEGREES_PER_TURN; + hole.sprite.color._tint[3] = 0; + return; + } + if (hole.subtype == BLACKHOLE_SPARK) + { + hole.sprite.Play("Trail"); + float height = random_unit() * 0.5f + 0.5f; + hole.sprite.scale = vector_make(random_unit() + 1, height); + hole.sprite.rotation = random_unit() * DEGREES_PER_TURN; + return; + } + hole.AddEntityFlags(FLAG_DONT_OVERWRITE); + hole.sprite.bitflags |= ANIM_RENDER_STATIC; + hole.sprite.Play("IdleClosed"); + hole.timeout = BLACKHOLE_CLOSED_FRAMES; +} + +// A shot the hole throws for its spawner, as its spawner's kind. +static Entity_Projectile* dogma_hole_shot_spawn(Entity_Effect& hole, Vector position, Vector velocity, uint32_t seed) +{ + auto* shot = static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = hole.spawnerEntity, + .type = ENTITY_PROJECTILE, + .seed = seed})); + shot->spawnerType = hole.spawnerType; + shot->spawnerVariant = hole.spawnerVariant; + return shot; +} + +// Whether the open hole pulls an entity: an enemy, shot, tear, bomb or player, or a free pickup but an open chest. +static bool is_hole_pulled(Entity& entity) +{ + if (entity.IsVulnerableEnemy(nullptr) || entity.IsProjectile() || entity.IsTear() || entity.is_bomb() || + entity.is_player()) + return true; + if (!entity.is_pickup()) return false; + auto& pickup = static_cast(entity); + return pickup.price == 0 && !(Entity_Pickup::IsChest(pickup.variant) && pickup.subtype == 0); +} + +// Eats what the open hole drew within 48: a shot or tear bursts unless just fired or low (or Ludovico's), a bomb or +// a rerollable pickup goes, a player is hurt. +static void dogma_hole_eat(Entity_Effect& hole, Entity& entity) +{ + if (entity.is_bomb() || (entity.is_pickup() && static_cast(entity).CanReroll())) + return entity.Remove(); + if (entity.is_player()) return (void)entity.TakeDamage(1, 0, EntityRef(&hole), BLACKHOLE_HURT_COUNTDOWN); + if (entity.isDead || entity.FrameCount() <= BLACKHOLE_SHOT_SAFE_FRAMES) return; + if (entity.IsTear()) + { + auto& tear = static_cast(entity); + if (!tear.tearFlags[TEAR_LUDOVICO] && tear.height > BLACKHOLE_SHOT_LOWEST) tear.Remove(); + } + else if (entity.IsProjectile() && static_cast(entity).height > BLACKHOLE_SHOT_LOWEST) + entity.Remove(); +} + +// Pulls one entity into the open hole. +static void dogma_hole_pull(Entity_Effect& hole, Entity& entity) +{ + float distanceSquared = vector_length_squared(vector_sub(entity.pos, hole.pos)); + float distance = std::sqrt(distanceSquared); + Vector toward = vector_normalized(vector_sub(hole.pos, entity.pos)); + float pull = entity.IsEnemy() || entity.IsTear() || entity.is_bomb() ? BLACKHOLE_STRONG_PULL : BLACKHOLE_PULL; + pull *= hole.scale; + float nearness = distance >= BLACKHOLE_NEAR ? std::min(1 / (distance * BLACKHOLE_FALLOFF), 1.0f) : distance / BLACKHOLE_NEAR_SHARE; + if (entity.IsProjectile() || entity.IsTear()) + nearness *= std::min((float)entity.FrameCount() / BLACKHOLE_SHOT_WARMUP, 1.0f); + if (entity.is_player()) nearness *= std::min(distanceSquared / BLACKHOLE_PLAYER_FALLOFF, 1.0f); + pull = pull * nearness / entity.friction; + + if (entity.IsTear() || entity.IsProjectile()) + { + float drag = std::max(1 - nearness * BLACKHOLE_SHOT_DRAG, BLACKHOLE_SHOT_DRAG_MIN); + entity.velocity = vector_scale(entity.velocity, timescale_factor(drag, entity.speedMultiplier)); + if (entity.IsTear()) + { + auto& tear = static_cast(entity); + if (tear.tearFlags[TEAR_ORBIT] && vector_length_squared(tear.velocity) < 1) tear.tearFlags.reset(TEAR_ORBIT); + } + } + if (distanceSquared < BLACKHOLE_EAT_REACH_SQUARED) dogma_hole_eat(hole, entity); + entity.AddVelocity(vector_scale(toward, pull), false); +} + +// The open hole: shakes, throws its ring sparks and shots, swirls, grows and pulls, its closing heard 30 frames ahead. +static void dogma_hole_open_update(Entity_Effect& hole) +{ + if (hole.sprite.IsFinished()) hole.sprite.Play("Idle"); + if (hole.sprite.animState.IsLoopingAnimation() && hole.GetIntervalTicks(BLACKHOLE_SHAKE_PERIOD, 0)) + game_shake_screen(BLACKHOLE_SHAKE); + if (hole.GetIntervalTicks(BLACKHOLE_SPARK_PERIOD, 0)) + { + uint32_t seed = Random(); + Entity* spark = g_game->Spawn({.position = hole.pos, + .spawner = &hole, + .subType = BLACKHOLE_SPARK, + .type = ENTITY_EFFECT, + .variant = EFFECT_DOGMA_BLACKHOLE, + .seed = seed}); + spark->Update(); + Vector at = vector_add(hole.pos, vector_scale(vector_from_angle(spark->sprite.rotation), BLACKHOLE_RING_REACH)); + Entity_Projectile* shot = dogma_hole_shot_spawn(hole, at, {}, Random()); + shot->height = BLACKHOLE_RING_HEIGHT; + shot->fallingSpeed = 0; + shot->fallingAccel = BLACKHOLE_RING_FALL; + shot->acceleration = BLACKHOLE_RING_ACCELERATION; + shot->scale = std::lerp(BLACKHOLE_SHOT_SCALE_MIN, BLACKHOLE_SHOT_SCALE_MAX, random_unit()); + shot->projectileFlags = BLACKHOLE_RING_FLAGS; + shot->SetColor(BLACKHOLE_RING_COLOR, BLACKHOLE_RING_FADE_FRAMES, BLACKHOLE_PRIORITY, true, true); + shot->subtype = BLACKHOLE_RING_SHOT; + } + if (hole.GetIntervalTicks(BLACKHOLE_SWIRL_PERIOD, 0)) + { + uint32_t seed = Random(); + g_game->Spawn({.position = hole.pos, .spawner = &hole, .subType = BLACKHOLE_SWIRL, .type = ENTITY_EFFECT, + .variant = EFFECT_DOGMA_BLACKHOLE, .seed = seed})->Update(); + } + + hole.scale += hole.speedMultiplier * BLACKHOLE_STRENGTH_GROWTH; + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity->type == ENTITY_DOGMA || hole.GetStatusEffectTarget() == entity->GetStatusEffectTarget()) continue; + if (!is_hole_pulled(*entity) || entity == &hole || entity->friction == 0) continue; + if (entity->pos.x == hole.pos.x && entity->pos.y == hole.pos.y) continue; + dogma_hole_pull(hole, *entity); + } + if (hole.timeout == BLACKHOLE_CLOSE_SOUND_FRAMES) + effect_sound_play(SOUND_DOGMA_BLACKHOLE_CLOSE, {.frameDelay = BLACKHOLE_CLOSE_SOUND_FRAMES}); + if (!hole.isDead) return; + hole.state = BLACKHOLE_CLOSING; + hole.sprite.Play("Death"); +} + +// The closing hole bursts on its shot: a fart, a spray of shots, and its ring's shots popped. +static void dogma_hole_close_update(Entity_Effect& hole) +{ + if (hole.sprite.IsEventTriggered("Shoot")) + { + game_shake_screen(BLACKHOLE_BURST_SHAKE); + game_butter_bean_fart({.position = hole.pos, .source = &hole, .radius = BLACKHOLE_BURST_FART, .isShowEffect = false}); + for (int i = 0; i < BLACKHOLE_BURST_SHOTS; i++) + { + Vector direction = random_direction(); + Vector velocity = vector_scale(vector_scale(direction, BLACKHOLE_BURST_SPEED), random_unit()); + Vector at = vector_add(hole.pos, vector_scale(direction, BLACKHOLE_BURST_SPOT)); + Entity_Projectile* shot = dogma_hole_shot_spawn(hole, at, velocity, Random()); + shot->height = std::lerp(BLACKHOLE_BURST_HEIGHT_MIN, BLACKHOLE_BURST_HEIGHT_MAX, random_unit()); + shot->fallingSpeed = 0; + shot->fallingAccel = std::lerp(BLACKHOLE_BURST_FALL_MIN, BLACKHOLE_BURST_FALL_MAX, random_unit()); + shot->scale = std::lerp(BLACKHOLE_SHOT_SCALE_MIN, BLACKHOLE_SHOT_SCALE_MAX, random_unit()); + shot->acceleration = BLACKHOLE_BURST_ACCELERATION; + shot->projectileFlags = PROJECTILE_ACCELERATE_EX; + shot->Update(); + } + for (Entity* shot : entity_query(ENTITY_PROJECTILE, 0)) + if (shot->spawnerType == hole.spawnerType && shot->subtype == BLACKHOLE_RING_SHOT) shot->isDead = true; + } + if (hole.sprite.IsFinished()) hole.Remove(); +} + +// The hole drifts to a stop off the walls and Dogma's television, then falls (trailing dark haemo) until it first +// dies and opens, pulls until it dies again and closes. +static void dogma_hole_body_update(Entity_Effect& hole) +{ + float slowing = std::min((float)hole.FrameCount() / BLACKHOLE_DRAG_FRAMES, 1.0f); + hole.velocity = vector_scale(hole.velocity, std::lerp(1.0f, BLACKHOLE_DRAG, slowing)); + Vector push = vector_scale(vector_sub(g_game->room->GetClampedPosition(hole.pos, BLACKHOLE_WALL_MARGIN), hole.pos), BLACKHOLE_WALL_PUSH); + if (vector_length(push) > BLACKHOLE_MAX_PUSH) push = vector_resized(push, BLACKHOLE_MAX_PUSH); + hole.AddVelocity(push, false); + for (Entity* entity : entity_query_radius(hole.pos, BLACKHOLE_TV_REACH, QUERY_ALL)) + { + if (entity->type != ENTITY_DOGMA || entity->variant != DOGMA_TV) continue; + Vector away = vector_sub(hole.pos, entity->pos); + away = vector_scale(vector_scale(away, BLACKHOLE_MAX_PUSH), 1 / vector_length_squared(away)); + if (vector_length(away) > BLACKHOLE_MAX_PUSH) away = vector_resized(away, BLACKHOLE_MAX_PUSH); + hole.AddVelocity(away, false); + } + + if (hole.state == BLACKHOLE_CLOSED) + { + hole.posOffset.y = std::min(hole.posOffset.y + hole.speedMultiplier, 0.0f); + if (hole.GetIntervalTicks(BLACKHOLE_TRAIL_PERIOD, 0)) + { + uint32_t seed = Random(); + auto* trail = static_cast(g_game->Spawn({.position = hole.pos, + .velocity = vector_scale(hole.velocity, BLACKHOLE_TRAIL_DRAG), + .spawner = &hole, + .type = ENTITY_EFFECT, + .variant = EFFECT_HAEMO_TRAIL, + .seed = seed})); + trail->posOffset = hole.posOffset; + trail->SetColor(BLACKHOLE_TRAIL_COLOR, -1, BLACKHOLE_PRIORITY, false, true); + trail->renderDepthOffset = BLACKHOLE_DEPTH; + trail->Update(); + } + if (!hole.isDead) return; + hole.state = BLACKHOLE_OPEN; + hole.scale = BLACKHOLE_OPEN_STRENGTH; + hole.sprite.Play("Open"); + hole.isDead = false; + hole.SetTimeout(BLACKHOLE_OPEN_FRAMES); + effect_sound_play(SOUND_DOGMA_BLACKHOLE_OPEN); + } + else if (hole.state == BLACKHOLE_OPEN) dogma_hole_open_update(hole); + else dogma_hole_close_update(hole); +} + +// 005dc811 (Update's case 171) The swirl, the spark or the hole. +static EffectUpdateEnd dogma_hole_update(Entity_Effect& hole) +{ + if (hole.subtype == BLACKHOLE_SWIRL) + { + hole.renderDepthOffset = BLACKHOLE_DEPTH; + float scale = hole.sprite.scale.x - hole.speedMultiplier * BLACKHOLE_SWIRL_SHRINK; + float alpha = hole.sprite.color._tint[3] + hole.speedMultiplier * BLACKHOLE_SWIRL_SHOW; + if (scale <= BLACKHOLE_SWIRL_SMALLEST) + { + hole.Remove(); + return EFFECT_UPDATE_RETURN; + } + hole.sprite.rotation = angle_wrapped(hole.sprite.rotation + hole.speedMultiplier * BLACKHOLE_SWIRL_SPIN); + hole.sprite.scale = vector_make(scale, scale); + hole.sprite.color._tint[3] = alpha; + } + else if (hole.subtype == BLACKHOLE_SPARK) + { + hole.renderDepthOffset = BLACKHOLE_DEPTH; + hole.sprite.rotation = angle_wrapped(hole.sprite.rotation + hole.rotation * hole.speedMultiplier); + if (hole.sprite.IsFinished()) hole.Remove(); + } + else dogma_hole_body_update(hole); + return EFFECT_UPDATE_FINISH; +} + +constexpr auto DOGMA_BEHAVIOURS = std::to_array({ + {EFFECT_DOGMA_BLACKHOLE, dogma_hole_init, dogma_hole_update, nullptr}, + {EFFECT_DOGMA_ORB, dogma_orb_init, dogma_orb_update, dogma_orb_render}, +}); + +std::span dogma_effect_behaviours() +{ + return DOGMA_BEHAVIOURS; +} diff --git a/src/entity_effect_hazard.cpp b/src/entity_effect_hazard.cpp index 6c5345b..a4381f8 100644 --- a/src/entity_effect_hazard.cpp +++ b/src/entity_effect_hazard.cpp @@ -490,6 +490,171 @@ static EffectUpdateEnd fissure_spawner_update(Entity_Effect& spawner) return EFFECT_UPDATE_FINISH; } +// A smoke cloud: green poison gas, or (subtype 1) a poop spell's flammable gas, pulsing purple, that a fire or an +// explosion sets off. It fades in and out by a thirtieth a frame, its last 30 frames fading. An enemy's cloud lasts +// 60 more frames once its room is clear (or it dies), and while its parent lives it never runs out. +constexpr int SMOKE_FLAMMABLE = 1; +constexpr int SMOKE_FADE_FRAMES = 30; +constexpr int SMOKE_LINGER_FRAMES = 60; +constexpr int SMOKE_ENEMY_SPAWNERS = 10; +constexpr float SMOKE_SCALE_MIN = 1; +constexpr float SMOKE_SCALE_SPAN = 0.4f; +constexpr float SMOKE_HEIGHT = -20; +constexpr float SMOKE_BEAST_LAYER_ALPHA = 0.5f; + +// The flammable gas pulses every 6 frames, catches within 60 of its scale from a fire every other frame while +// thicker than a quarter, and goes up in a 15 damage explosion. +constexpr int SMOKE_PULSE_FRAMES = 6; +constexpr float SMOKE_PULSE_RED = 1.6f; +constexpr float SMOKE_PULSE_GREEN = 0.3f; +constexpr float SMOKE_PULSE_BLUE = 1.8f; +constexpr float SMOKE_CATCH_ALPHA = 0.25f; +constexpr int SMOKE_CATCH_PERIOD = 2; +constexpr float SMOKE_CATCH_REACH = 60; +constexpr float SMOKE_BLAST_DAMAGE = 15; +constexpr ColorMod SMOKE_BLAST_COLOR = color_make({1, 1, 1, 1}, {1, 1, 0, 0.5f}); + +// The poison gas hurts within 40 of its scale while thicker than a half (a friendly cloud a fifth): an enemy's +// cloud the players, a friendly one (a player's) the enemies every 10 frames, poisoning them for 60 frames at 3.5. +// An enemy already hit by a cloud this frame only takes the stronger of the two hits. +constexpr float SMOKE_HURT_REACH = 40; +constexpr float SMOKE_HURT_ALPHA = 0.5f; +constexpr float SMOKE_FRIENDLY_HURT_ALPHA = 0.2f; +constexpr float SMOKE_HURT_PERIOD = 10; +constexpr int SMOKE_HURT_COUNTDOWN = 30; +constexpr int SMOKE_POISON_FRAMES = 60; +constexpr float SMOKE_POISON_DAMAGE = 3.5f; +constexpr float SMOKE_FRICTION_START = 0.8f; +constexpr float SMOKE_FRICTION_GROWTH = 0.01f; +constexpr float SMOKE_FRICTION_MAX = 0.9f; + +// The fires that set the flammable gas off: an explosion, a hot bomb's, a blue or a red candle's flame. +constexpr std::array SMOKE_IGNITING_EFFECTS = {EFFECT_BOMB_EXPLOSION, EFFECT_HOT_BOMB_FIRE, EFFECT_BLUE_FLAME, + EFFECT_RED_CANDLE_FLAME}; + +// The smoke cloud part of 005cdb20 (Init): the gas tinted by its kind (deeper in the Beast's dungeon), invisible, +// raised 20 and sized 1 to 1.4, mirrored and started on a frame at random. +static void smoke_cloud_init(Entity_Effect& cloud) +{ + if (cloud.subtype == SMOKE_FLAMMABLE) cloud.sprite.color = color_make({1, 0.6f, 0.5f, 1}, {}, {0.2f, 0.2f, 0}); + else if (g_game->room->IsBeastDungeon()) + { + cloud.sprite.color = color_make({0.9f, 1.8f, 0.5f, 1}, {}, {0, 0.3f, 0}); + cloud.sprite.GetLayer(0)->color._tint[3] = SMOKE_BEAST_LAYER_ALPHA; + } + else cloud.sprite.color = color_make({0.6f, 1, 0.5f, 1}, {}, {0, 0.2f, 0}); + cloud.sprite.color._tint[3] = 0; + + float scale = cloud.dropRNG.RandomFloat() * SMOKE_SCALE_SPAN + SMOKE_SCALE_MIN; + cloud.sprite.scale = vector_make(scale, scale); + cloud.sprite.offset = vector_make(0, SMOKE_HEIGHT); + cloud.sprite.isFlipX = cloud.dropRNG.RandomInt(2) != 0; + cloud.sprite.Play("Idle"); + cloud.sprite.SetFrame((float)cloud.dropRNG.RandomInt(cloud.sprite.animState.GetAnimationLength())); +} + +// Whether an entity sets the flammable gas off: a fire effect not yet spent, a burning fireplace or a fire shot. +static bool is_smoke_igniter(Entity& entity) +{ + if (entity.type == ENTITY_EFFECT && std::ranges::count(SMOKE_IGNITING_EFFECTS, entity.variant) && + !entity.HasEntityFlags(FLAG_NO_BLOOD_SPLASH)) + return true; + if (entity.type == ENTITY_FIREPLACE && entity.entityCollisionClass != ENTCOLL_NONE) return true; + return entity.type == ENTITY_PROJECTILE && entity.variant == PROJECTILE_FIRE; +} + +// The flammable gas pulses, and blows up the frame after a fire (an explosion by its blast's scale) touches it. +static EffectUpdateEnd smoke_flammable_update(Entity_Effect& cloud) +{ + float pulse = std::sin((float)(g_game->frameCount % SMOKE_PULSE_FRAMES) * 2 * PI_F / SMOKE_PULSE_FRAMES) * 0.5f + 0.5f; + ColorMod& color = cloud.sprite.color; + color._colorize[0] = SMOKE_PULSE_RED; + color._colorize[1] = SMOKE_PULSE_GREEN; + color._colorize[2] = SMOKE_PULSE_BLUE; + color._colorize[3] = pulse * 0.5f; + if (cloud.state == 1) + { + explosion_effects({.color = SMOKE_BLAST_COLOR, .position = cloud.pos, .source = &cloud, .damage = SMOKE_BLAST_DAMAGE}); + cloud.Remove(); + return EFFECT_UPDATE_RETURN; + } + if (color._tint[3] <= SMOKE_CATCH_ALPHA || !cloud.IsFrame(SMOKE_CATCH_PERIOD, 0)) return EFFECT_UPDATE_FINISH; + + float reach = cloud.sprite.scale.x * SMOKE_CATCH_REACH; + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (!is_smoke_igniter(*entity)) continue; + float fire = entity->size; + if (entity->type == ENTITY_EFFECT && entity->variant == EFFECT_BOMB_EXPLOSION) + fire = entity->sprite.scale.x * SMOKE_CATCH_REACH; + Vector offset = vector_sub(entity->pos, cloud.pos); + if (offset.x * offset.x + offset.y * offset.y >= (reach + fire) * (reach + fire)) continue; + cloud.state = 1; + break; + } + return EFFECT_UPDATE_FINISH; +} + +// Raises an enemy's pending hit from another smoke cloud to this cloud's damage, or says there is none. +static bool is_smoke_hit_raised(Entity& enemy, float damage, int variant) +{ + for (DamageEvent& event : enemy.damageEvents) + { + if (event.source.type != ENTITY_EFFECT || event.source.variant != variant) continue; + event.damage = std::max(event.damage, damage); + return true; + } + return false; +} + +// The poison gas hurts the players (an enemy's) or the enemies but its spawner (a friendly one) inside it. +static void smoke_poison_update(Entity_Effect& cloud) +{ + bool isFriendly = cloud.HasEntityFlags(FLAG_FRIENDLY) || cloud.spawnerType == ENTITY_PLAYER; + float alpha = cloud.sprite.color._tint[3]; + if (alpha <= SMOKE_HURT_ALPHA && (!isFriendly || alpha <= SMOKE_FRIENDLY_HURT_ALPHA)) return; + + float reach = cloud.sprite.scale.x * SMOKE_HURT_REACH; + for (Entity* entity : entity_query_radius(cloud.pos, reach, QUERY_ENEMIES | QUERY_PLAYERS)) + { + if (entity->is_player() && !isFriendly) + { + Vector offset = vector_sub(entity->pos, cloud.pos); + if (offset.x * offset.x + offset.y * offset.y < reach * reach && entity->entityCollisionClass != ENTCOLL_NONE) + entity->TakeDamage(0, DAMAGE_POISON_BURN, EntityRef(&cloud), SMOKE_HURT_COUNTDOWN); + continue; + } + if (!entity->IsVulnerableEnemy(nullptr) || !isFriendly || entity == cloud.spawnerEntity) continue; + if (!entity->GetIntervalTicks(SMOKE_HURT_PERIOD, 0)) continue; + if (is_smoke_hit_raised(*entity, cloud.collisionDamage, cloud.variant)) continue; + entity->TakeDamage(cloud.collisionDamage, 0, EntityRef(&cloud), SMOKE_HURT_COUNTDOWN); + entity->AddPoison(EntityRef(&cloud), SMOKE_POISON_FRAMES, SMOKE_POISON_DAMAGE, false); + } +} + +// 005d6910 (Update's case 141) Lingers, fades, then sets off (flammable) or hurts (poison), slowing as it ages. +static EffectUpdateEnd smoke_cloud_update(Entity_Effect& cloud) +{ + Room& room = *g_game->room; + if ((cloud.timeout > SMOKE_LINGER_FRAMES || cloud.timeout < 0) && cloud.spawnerType >= SMOKE_ENEMY_SPAWNERS && + ((room.IsClear() && room.GetAliveEnemiesCount() <= 0) || cloud.isDead)) + cloud.timeout = SMOKE_LINGER_FRAMES; + if (cloud.timeout < SMOKE_LINGER_FRAMES && cloud.parent && !cloud.parent->isDead) cloud.timeout = SMOKE_LINGER_FRAMES; + if (cloud.timeout == 0 && cloud.isDead) cloud.Remove(); + + float& alpha = cloud.sprite.color._tint[3]; + if (cloud.timeout >= 0 && cloud.timeout < SMOKE_FADE_FRAMES) alpha = std::max(alpha - 1.0f / SMOKE_FADE_FRAMES, 0.0f); + else alpha = std::min(alpha + 1.0f / SMOKE_FADE_FRAMES, 1.0f); + + if (cloud.subtype == SMOKE_FLAMMABLE) + { + if (smoke_flammable_update(cloud) == EFFECT_UPDATE_RETURN) return EFFECT_UPDATE_RETURN; + } + else smoke_poison_update(cloud); + cloud.friction *= std::min((float)cloud.FrameCount() * SMOKE_FRICTION_GROWTH + SMOKE_FRICTION_START, SMOKE_FRICTION_MAX); + return EFFECT_UPDATE_FINISH; +} + constexpr auto HAZARD_BEHAVIOURS = std::to_array({ {EFFECT_DEVIL, nullptr, effect_finishing, nullptr}, {EFFECT_ANGEL, nullptr, effect_finishing, nullptr}, @@ -500,6 +665,7 @@ constexpr auto HAZARD_BEHAVIOURS = std::to_array({ {EFFECT_SHOCKWAVE_RANDOM, shockwave_random_init, effect_finishing, nullptr}, {EFFECT_HALLOWED_GROUND, hallowed_ground_init, hallowed_ground_update, nullptr}, {EFFECT_FISSURE_SPAWNER, fissure_spawner_init, fissure_spawner_update, nullptr}, + {EFFECT_SMOKE_CLOUD, smoke_cloud_init, smoke_cloud_update, nullptr}, }); std::span hazard_effect_behaviours() diff --git a/src/entity_effect_helpers.cpp b/src/entity_effect_helpers.cpp new file mode 100644 index 0000000..798b1c5 --- /dev/null +++ b/src/entity_effect_helpers.cpp @@ -0,0 +1,612 @@ +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "item_config.h" +#include "manager.h" +#include "npc_basement.h" +#include "npc_fireplace.h" +#include "room.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include + +// The helpers items send out: Friendly Ball's ball and Mr. ME!. + +// Friendly Ball's ball falls from 60 up, slowing as it bounces off, and lands where it stops: an empty one (subtype +// 0) catches the first enemy within 10 that is no boss and not yet a friend, and then (subtype 3) lies until its +// player picks it up for a full charge. A thrown full one (subtype 1) lets its enemy out as a friend where it dies. +constexpr int FRIEND_BALL_EMPTY = 0; +constexpr int FRIEND_BALL_FULL = 1; +constexpr int FRIEND_BALL_CAUGHT = 3; +constexpr float FRIEND_BALL_HEIGHT = -60; +constexpr float FRIEND_BALL_GRAVITY = 0.3f; +constexpr float FRIEND_BALL_DRAG = 0.98f; +constexpr int FRIEND_BALL_REST_FRAMES = 30; +constexpr float FRIEND_BALL_CATCH_REACH = 10; +constexpr float FRIEND_BALL_CATCH_DRAG = 0.3f; + +// In Pokey Mans an empty thrown ball lets out a random ground enemy at half its health. +constexpr float POKEY_MANS_HEALTH = 0.5f; + +// The Friendly Ball part of 005cdb20 (Init): it starts 60 up, over pits. +static void friend_ball_init(Entity_Effect& ball) +{ + ball.fallingSpeed = 0; + ball.height = FRIEND_BALL_HEIGHT; + ball.posOffset.y = FRIEND_BALL_HEIGHT; + ball.entityGridCollisionClass = GRIDCOLL_NOPITS; +} + +// The empty ball catches an enemy within reach: Friendly Ball keeps it, the game counts it killed, and the ball +// turns full. +static void friend_ball_catch(Entity_Effect& ball) +{ + Entity_Player* player = ball.parent ? ball.parent->ToPlayer() : nullptr; + if (!player) return; + + for (Entity* enemy : entity_query_radius(ball.pos, FRIEND_BALL_CATCH_REACH, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || enemy->IsBoss() || enemy->HasEntityFlags(FLAG_FRIENDLY)) continue; + if (Entity::is_enemy_type(enemy->type)) + { + auto& npc = static_cast(*enemy); + player->friendBallEnemy = charmed_enemy_save(npc); + g_game->scoreSheet.AddKilledEnemy(npc); + } + effect_sound_play(SOUND_FRIENDLYBALL_CAPTURE); + enemy->Remove(); + ball.velocity = vector_scale(ball.velocity, FRIEND_BALL_CATCH_DRAG); + ball.subtype = FRIEND_BALL_CAUGHT; + return; + } +} + +// Pokey Mans' enemy for an empty ball: a random ground enemy from the reroll pool, redirected to what it becomes. +static EntityDesc pokey_mans_enemy_pick(Entity_Player& player, EntityDesc desc) +{ + std::vector& pool = g_manager->entityConfig.groundRerolls; + if (pool.empty()) return desc; + + RerollEntry entry = pool[player.GetCollectibleRNG(COLLECTIBLE_FRIEND_BALL).RandomInt((uint32_t)pool.size())]; + int type = entry.id; + int variant = entry.variant; + if (Entity_NPC::Redirect(&type, &variant)) + if (EntityConfig_Entity* config = g_manager->entityConfig.GetEntity(type, variant, 0)) + entry = {.baseHP = config->baseHP, .id = config->id, .subtype = config->subtype, .variant = config->variant}; + desc.type = (uint32_t)entry.id; + desc.variant = (uint32_t)entry.variant; + desc.subtype = (uint32_t)entry.subtype; + desc.maxHealth = entry.baseHP; + desc.health = entry.baseHP * POKEY_MANS_HEALTH; + return desc; +} + +// A full ball's enemy comes out a friend for good at the nearest free spot, and Friendly Ball empties. +static void friend_ball_release(Entity_Effect& ball) +{ + if (ball.subtype != FRIEND_BALL_FULL || !ball.parent || !ball.parent->is_player()) return; + + auto& player = static_cast(*ball.parent.get()); + EntityDesc desc = player.friendBallEnemy; + if (g_game->challenge == CHALLENGE_POKEY_MANS && desc.type == 0) desc = pokey_mans_enemy_pick(player, desc); + if (desc.type != 0) + { + Vector spot = room_free_pickup_position_find({.position = ball.pos}); + if (Entity_NPC* npc = entity_desc_spawn(desc, spot, &player)) + { + npc->AddCharmed(EntityRef(), -1, false, true); + npc->AddEntityFlags(FLAG_FRIENDLY_BALL); + npc->Update(); + npc->isCanShutDoors = false; + effect_sound_play(SOUND_FRIENDLYBALL_RELEASE); + } + } + player.friendBallEnemy = EntityDesc{}; +} + +// 005fd3b4 (Update's case 81) Falls until it lands (with a bounce sound), then rests 30 frames unless caught full. +// Alive, an empty ball catches and a caught one waits for its player. Dead, a full one releases its enemy. +static void friend_ball_update(Entity_Effect& ball) +{ + if (ball.height >= 0 || ball.timeout >= 0) + { + ball.posOffset.y = 0; + ball.height = 0; + ball.fallingSpeed = 0; + ball.velocity = {}; + if (ball.subtype != FRIEND_BALL_CAUGHT && ball.timeout < 0) ball.timeout = FRIEND_BALL_REST_FRAMES; + ball.sprite.Stop(); + } + else + { + ball.fallingSpeed = (ball.fallingSpeed + FRIEND_BALL_GRAVITY) * FRIEND_BALL_DRAG; + ball.height += ball.fallingSpeed; + ball.posOffset.y = ball.height; + ball.velocity = vector_scale(ball.velocity, FRIEND_BALL_DRAG); + if (ball.height >= 0) effect_sound_play(SOUND_FRIENDLYBALL_LAND); + } + + if (ball.isDead) + { + friend_ball_release(ball); + return ball.Remove(); + } + if (ball.subtype == FRIEND_BALL_EMPTY) return friend_ball_catch(ball); + if (ball.subtype != FRIEND_BALL_CAUGHT) return; + + Entity_Player* player = ball.parent ? ball.parent->ToPlayer() : nullptr; + if (!player || vector_length(vector_sub(player->pos, ball.pos)) >= player->size + ball.size) return; + effect_sound_play(SOUND_FRIENDLYBALL_PICKUP); + ball.Remove(); + int slot = player->GetActiveItemSlot(COLLECTIBLE_FRIEND_BALL); + if (slot >= 0) player->FullCharge(slot, false, false); +} + +// Mr. ME! floats after its player while its target lives, the target flashing faster as it runs out and steering +// where the player aims (or onto their marked target). Then it picks the job nearest the target: a rock, fire, slot, +// shopkeeper or secret door to blow up (1), a door to open (2), an enemy to hit (3), or a pickup, chest or pressure +// plate to take (4). It flies there at 8, does it and leaves in a poof. A pickup it carries back to its player (a +// shop item only 1 in 3 times, else it buzzes and leaves). +constexpr int MR_ME_SEEK = 0; +constexpr int MR_ME_WORK = 1; +constexpr int MR_ME_CARRY = 2; +constexpr int MR_ME_LEAVE = 3; +constexpr int JOB_NONE = 0; +constexpr int JOB_BOMB = 1; +constexpr int JOB_DOOR = 2; +constexpr int JOB_HIT = 3; +constexpr int JOB_TAKE = 4; +constexpr float MR_ME_FOLLOW_REACH = 70; +constexpr float MR_ME_FOLLOW_SPEED = 6; +constexpr float MR_ME_FLIGHT_SPEED = 8; +constexpr float MR_ME_DRAG = 0.9f; +constexpr float MR_ME_STEER = 0.1f; +constexpr float MR_ME_AIM_REACH = 20; +constexpr int MR_ME_TARGET_DEPTH = 100; +constexpr float MR_ME_TAKE_REACH = 16; +constexpr float MR_ME_DOOR_REACH = 40; +constexpr float MR_ME_BOMB_REACH = 20; +constexpr float MR_ME_CARRY_REACH = 32; +constexpr float MR_ME_DROP_STEP = 40; +constexpr float MR_ME_HELPER_BLAST = 20; +constexpr float MR_ME_DOOR_STAND = 20; +constexpr int MR_ME_STEAL_ODDS = 3; +constexpr float MR_ME_HIT_DAMAGE = 3; +constexpr int MR_ME_HIT_PERIOD = 10; +constexpr int MR_ME_VERSUS_HIT_PERIOD = 16; +constexpr int MR_ME_VERSUS_FRAMES = 600; +constexpr int MR_ME_HIT_COUNTDOWN = 30; +constexpr int MR_ME_FLASH_FRAMES = 5; +constexpr int MR_ME_FLASH_PRIORITY = 200; +constexpr int MR_ME_TARGET_PRIORITY = 255; +constexpr float MR_ME_SHOP_SCALE = 0.8f; +constexpr ColorMod MR_ME_FLASH_COLOR = color_make({0.6f, 0.6f, 1, 1}); +constexpr ColorMod MR_ME_TARGET_DIM = color_make({0, 0, 0, 0.5f}, {}, {-0.902f, 0.392f, 0.843f}); +constexpr ColorMod MR_ME_TARGET_BRIGHT = color_make({0, 0, 0, 0.8f}, {}, {-0.784f, 0.588f, 1}); +constexpr int GRID_TNT_BROKEN = 4; +constexpr int GRID_BROKEN_STATE = 2; +constexpr int DOOR_MINESHAFT_LOCKED = 4; +constexpr int SECRET_EXIT_SEALED = 4; + +// The target flashes every 10 frames of its life, then 8, 6, 4 and 2 past 40, 55, 65 and 70. +constexpr std::array, 4> MR_ME_FLASH_PERIODS = {{{70, 2}, {65, 4}, {55, 6}, {40, 8}}}; +constexpr int MR_ME_FLASH_SLOWEST = 10; + +// The pickups Mr. ME! takes outright: cards, pills, trinkets, grab bags, coins, hearts, bombs, keys and batteries. +constexpr std::array MR_ME_TAKEN = {PICKUP_TAROTCARD, PICKUP_PILL, PICKUP_TRINKET, PICKUP_GRAB_BAG, + PICKUP_COIN, PICKUP_HEART, PICKUP_BOMB, PICKUP_KEY, PICKUP_LIL_BATTERY}; + +// A job Mr. ME! may take: what, where, on which cell or entity. +struct MrMeJob +{ + Vector position{}; + Entity* entity = nullptr; + int gridIndex = -1; + int job = JOB_NONE; +}; + +// The Mr. ME! part of 005cdb20 (Init): it starts seeking with no job. +static void mr_me_init(Entity_Effect& helper) +{ + helper.extraData = std::make_shared(); + helper.state = MR_ME_SEEK; +} + +// FUN_00710370 Whether Mr. ME! may open a door: not a mirror or photo door, not the mineshaft's locked one, and not a +// sealed secret exit. +static bool is_door_openable(GridEntity_Door& door) +{ + if (door.doorFlags & (DOOR_FLAG_MIRROR | DOOR_FLAG_PHOTO)) return false; + if (door.doorFlags & DOOR_FLAG_MINESHAFT && door.variant == DOOR_MINESHAFT_LOCKED) return false; + return door.get_secret_exit_kind() != SECRET_EXIT_SEALED; +} + +// The job a grid cell offers: special rocks and unbroken TNT to blow up, openable doors to open (a secret room's to +// blow open), and raised pressure plates to press. A broken cell offers none. +static MrMeJob mr_me_grid_job(Room& room, int index, GridEntity& grid) +{ + MrMeJob job{.position = room.GetGridPosition(index), .gridIndex = index}; + if (grid.state == GRID_BROKEN_STATE) return {}; + switch (grid.type) + { + case GRID_ROCKT: + case GRID_ROCK_SS: + case GRID_ROCK_ALT: + case GRID_ROCK_ALT2: + job.job = JOB_BOMB; + break; + case GRID_TNT: + if (grid.state < GRID_TNT_BROKEN) job.job = JOB_BOMB; + break; + case GRID_PRESSURE_PLATE: + if (grid.state == 0) job.job = JOB_TAKE; + break; + case GRID_DOOR: + { + if (g_game->deathmatchManager.is_active() || g_game->currentRoomIdx == ROOM_LIL_PORTAL_IDX) break; + auto& door = static_cast(grid); + if (!is_door_openable(door)) break; + job.position = vector_sub(job.position, vector_scale(vector_from_direction(door.direction), MR_ME_DOOR_STAND)); + bool isSecret = door.IsRoomType(ROOM_SECRET) || door.IsRoomType(ROOM_SUPERSECRET); + job.job = isSecret ? JOB_BOMB : JOB_DOOR; + break; + } + default: + break; + } + return job.job ? job : MrMeJob{}; +} + +// Whether an enemy (a player in versus mode) is one Mr. ME! may hit: solid, mortal, alive, targetable (or one of the +// two spared kinds) and not its own ancestor. +static bool is_mr_me_foe(Entity_Effect& helper, Entity& entity) +{ + if (!Entity::is_enemy_type(entity.type) || entity.entityCollisionClass == ENTCOLL_NONE || entity.entityCollisionClass == ENTCOLL_PLAYERONLY) + return false; + if (entity.isInvincible || entity.isDead) return false; + if (entity.HasEntityFlags(FLAG_NO_TARGET) && entity.type != ENTITY_BLOOD_PUPPY && entity.type != ENTITY_DARK_ESAU) + return false; + return !helper.IsDescendantOf(&entity); +} + +// The job an entity offers: blue fires, shopkeepers, TNT and slots (not broken) to blow up, enemies to hit, and +// pickups (pedestals with an item, unopened chests and the plain pickups) to take. A Glitched Crown pedestal marks it. +static MrMeJob mr_me_entity_job(Entity_Effect& helper, Entity& entity, MrMeData& data) +{ + MrMeJob job{.position = entity.pos, .entity = &entity}; + bool isBlownUp = (entity.type == ENTITY_FIREPLACE && entity.health > 1 && entity.variant >= FIRE_BLUE) || + entity.type == ENTITY_SHOPKEEPER || (entity.type == ENTITY_MOVABLE_TNT && entity.health > 1); + if (isBlownUp) job.job = JOB_BOMB; + else if (is_mr_me_foe(helper, entity)) job.job = JOB_HIT; + else if (entity.is_pickup() && entity.isExists && entity.isVisible) + { + auto& pickup = static_cast(entity); + bool isPedestal = pickup.variant == PICKUP_COLLECTIBLE && pickup.subtype != 0; + if (isPedestal || std::ranges::count(MR_ME_TAKEN, pickup.variant) || + (Entity_Pickup::IsChest(pickup.variant) && pickup.subtype != 0)) + job.job = JOB_TAKE; + if (isPedestal && g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_GLITCHED_CROWN, LAZARUS_SHARE_CHECK)) + data.isGlitchedCrown = true; + } + else if (entity.type == ENTITY_SLOT && entity.sprite.GetAnimation() != "Broken") job.job = JOB_BOMB; + return job.job ? job : MrMeJob{}; +} + +// Steers the target where the player aims (or onto their marked target), flashing faster as it runs out. +static void mr_me_target_steer(Entity_Effect& target, Entity_Player& player) +{ + if (player.markedTarget) + { + target.velocity = vector_sub(player.markedTarget->pos, target.pos); + target.renderZOffset = MR_ME_TARGET_DEPTH; + } + else target.velocity = vector_scale(player.aimDirection, MR_ME_AIM_REACH); + + int age = g_game->frameCount - target.spawnFrame; + int period = MR_ME_FLASH_SLOWEST; + for (auto [after, frames] : MR_ME_FLASH_PERIODS) + if (age > after) + { + period = frames; + break; + } + bool isDim = age % period < period / 2; + target.SetColor(isDim ? MR_ME_TARGET_DIM : MR_ME_TARGET_BRIGHT, -1, MR_ME_TARGET_PRIORITY, false, true); +} + +// Mr. ME! seeks: it follows its player and steers its target. Once the target is gone it hides the item and picks the +// job nearest where the target was (a quirk keeps the last one found compared again on every cell), or leaves. +static Vector mr_me_seek(Entity_Effect& helper, MrMeData& data) +{ + Vector move{}; + if (!helper.parent) return move; + helper.sprite.Play("Float"); + Vector toward = vector_sub(helper.parent->pos, helper.pos); + float distanceSquared = vector_length_squared(toward); + if (distanceSquared > MR_ME_FOLLOW_REACH * MR_ME_FOLLOW_REACH) + move = vector_scale(toward, MR_ME_FOLLOW_SPEED / std::sqrt(distanceSquared)); + else helper.velocity = vector_scale(helper.velocity, MR_ME_DRAG); + + if (!helper.target || !helper.parent->is_player()) + { + helper.state = MR_ME_LEAVE; + data.frames++; + return move; + } + auto& player = static_cast(*helper.parent.get()); + auto& target = static_cast(*helper.target.get()); + mr_me_target_steer(target, player); + helper.targetPosition = target.pos; + if (target.isExists && !target.isDead) + { + data.frames++; + return move; + } + + player.AnimateCollectible(COLLECTIBLE_MR_ME, "HideItem", "PlayerPickupSparkle"); + player.Update(); + data.job = JOB_NONE; + data.gridIndex = -1; + data.isGlitchedCrown = false; + Room& room = *g_game->room; + float best = 0; + auto consider = [&](const MrMeJob& job) + { + float distanceSquared = vector_length_squared(vector_sub(helper.target->pos, job.position)); + if (data.job != JOB_NONE && distanceSquared >= best) return false; + data.job = job.job; + helper.targetPosition = job.position; + best = distanceSquared; + return true; + }; + MrMeJob candidate{}; + for (int index = 0; index < room.GetGridSize(); index++) + { + GridEntity* grid = room.GetGridEntity(index); + if (grid) + if (MrMeJob job = mr_me_grid_job(room, index, *grid); job.job) candidate = job; + if (consider(candidate)) data.gridIndex = candidate.gridIndex; + } + candidate = {}; + for (Entity* entity : room.entityList.updateEL) + { + if (MrMeJob job = mr_me_entity_job(helper, *entity, data); job.job) candidate = job; + if (!consider(candidate)) continue; + helper.child = candidate.entity; + data.gridIndex = -1; + } + helper.state = data.job != JOB_NONE ? MR_ME_WORK : MR_ME_LEAVE; + data.frames = data.job != JOB_NONE ? 1 : data.frames + 1; + return move; +} + +// Takes the job's pickup: a shop item it may only steal 1 time in 3 (else it buzzes and leaves), a chest it opens, a +// bomb chest it blows up, a sticky nickel it leaves. Anything else it hides and carries, a pedestal shown as in a shop. +static void mr_me_take(Entity_Effect& helper, MrMeData& data, Entity_Pickup& pickup) +{ + if (pickup.price != 0) + { + if (helper.dropRNG.RandomInt(MR_ME_STEAL_ODDS) == 0) + { + effect_sound_play(SOUND_ERROR_BUZZ); + helper.state = MR_ME_LEAVE; + } + else pickup.update_price_sprite(0); + } + if (helper.state == MR_ME_LEAVE) return; + + int variant = pickup.variant; + if (variant == PICKUP_LOCKEDCHEST || variant == PICKUP_ETERNALCHEST || variant == PICKUP_OLDCHEST) + pickup.TryOpenChest(nullptr); + else if (variant == PICKUP_BOMBCHEST) + explosion_effects({.position = helper.pos, .source = helper.parent, .damage = MR_ME_HELPER_BLAST}); + else if (variant != PICKUP_COIN || pickup.subtype != COIN_STICKYNICKEL) + { + if (data.isGlitchedCrown) pickup.cycleCollectibleCount = 0; + data.carried = pickup.sprite; + if (variant == PICKUP_COLLECTIBLE) + { + data.carried.Play("ShopIdle", PLAY_FORCED); + data.carried.RemoveOverlay(); + data.carried.scale = vector_make(MR_ME_SHOP_SCALE, MR_ME_SHOP_SCALE); + } + pickup.isVisible = false; + data.savedCollisionClass = pickup.entityCollisionClass; + pickup.entityCollisionClass = ENTCOLL_NONE; + helper.state = MR_ME_CARRY; + return; + } + helper.state = MR_ME_LEAVE; +} + +// Presses the job's plate as if its player stood on it. +static void mr_me_plate_press(Entity_Effect& helper, MrMeData& data) +{ + GridEntity* plate = (uint32_t)data.gridIndex < ROOM_GRID_CELLS ? g_game->room->GetGridEntity(data.gridIndex) : nullptr; + if (!plate || plate->type != GRID_PRESSURE_PLATE || !helper.parent || !helper.parent->is_player()) return; + auto& player = static_cast(*helper.parent.get()); + player.damageCooldown = std::max(player.damageCooldown, 1); + Vector standing = player.pos; + player.pos = plate->Position(); + plate->Update(); + player.pos = standing; +} + +// Mr. ME! works its job: it flies to it at 8 and takes, opens, blows up or hits there, then leaves (giving up on a +// pickup that vanished). Returns where it heads. +static Vector mr_me_work(Entity_Effect& helper, MrMeData& data) +{ + Room& room = *g_game->room; + Vector move{}; + if (data.isGlitchedCrown) + for (Entity* entity : room.entityList.updateEL) + if (entity->is_pickup() && static_cast(entity)->cycleCollectibleCount > 1) + { + helper.child = entity; + break; + } + Entity* child = helper.child; + ItemConfig_Item* item = child ? g_manager->itemConfig.GetCollectible(child->subtype) : nullptr; + + if (data.job == JOB_TAKE) + { + if (data.gridIndex == -1 && (!child || (child->variant == PICKUP_COLLECTIBLE && !item))) + { + helper.state = MR_ME_LEAVE; + return move; + } + Vector goal = child ? child->pos : helper.targetPosition; + move = vector_resized(vector_sub(goal, helper.pos), MR_ME_FLIGHT_SPEED); + if (vector_length_squared(vector_sub(helper.pos, goal)) >= MR_ME_TAKE_REACH * MR_ME_TAKE_REACH) + { + if (!child || child->isVisible) return move; + } + else if (data.gridIndex >= 0) mr_me_plate_press(helper, data); + else if (child) + { + if (!child->is_pickup()) return move; + mr_me_take(helper, data, static_cast(*child)); + if (helper.state != MR_ME_WORK) return move; + } + } + else if (data.job == JOB_DOOR || data.job == JOB_BOMB) + { + Vector toward = vector_sub(helper.targetPosition, helper.pos); + float length = vector_length(toward); + move = length > 0 ? vector_scale(toward, MR_ME_FLIGHT_SPEED / length) : toward; + float reach = data.job == JOB_DOOR ? MR_ME_DOOR_REACH : MR_ME_BOMB_REACH; + if (vector_length_squared(vector_sub(helper.pos, helper.targetPosition)) >= reach * reach) return move; + if (data.job == JOB_BOMB) + explosion_effects({.position = helper.pos, .source = helper.parent, .damage = MR_ME_HELPER_BLAST}); + else + { + GridEntity* grid = (uint32_t)data.gridIndex < ROOM_GRID_CELLS ? room.GetGridEntity(data.gridIndex) : nullptr; + if (grid && grid->type == GRID_DOOR && grid->state != GRID_BROKEN_STATE && helper.parent && + helper.parent->is_player()) + { + auto& door = static_cast(*grid); + if (is_door_openable(door) && !door.TryUnlock(static_cast(*helper.parent.get()), true)) + door.Open(); + } + } + } + else if (data.job == JOB_HIT) + { + if (child && !child->isDead) + { + Vector toward = vector_sub(child->pos, helper.pos); + move = vector_resized(toward, std::min(vector_length(toward), MR_ME_FLIGHT_SPEED)); + int period = MR_ME_HIT_PERIOD; + if (g_game->deathmatchManager.is_active()) + { + period = MR_ME_VERSUS_HIT_PERIOD; + if (data.frames > MR_ME_VERSUS_FRAMES) helper.state = MR_ME_LEAVE; + } + if (helper.IsFrame(period, 0) && + vector_length_squared(vector_sub(helper.pos, child->pos)) < helper.size * helper.size) + { + child->TakeDamage(MR_ME_HIT_DAMAGE, 0, EntityRef(helper.parent), MR_ME_HIT_COUNTDOWN); + helper.SetColor(MR_ME_FLASH_COLOR, MR_ME_FLASH_FRAMES, MR_ME_FLASH_PRIORITY, true, true); + } + return move; + } + } + else return move; + helper.state = MR_ME_LEAVE; + return move; +} + +// Mr. ME! carries its pickup back and drops it at the nearest free spot by its player, then leaves. +static Vector mr_me_carry(Entity_Effect& helper, MrMeData& data) +{ + helper.sprite.Play("Carry"); + Entity* player = helper.parent; + Entity* child = helper.child; + if (!player || !child || !child->isExists) + { + helper.state = MR_ME_LEAVE; + return {}; + } + Vector move = vector_resized(vector_sub(player->pos, helper.pos), MR_ME_FLIGHT_SPEED); + if (vector_length_squared(vector_sub(helper.pos, player->pos)) >= MR_ME_CARRY_REACH * MR_ME_CARRY_REACH) return move; + + Vector spot = room_free_pickup_position_find({.position = player->pos, .step = MR_ME_DROP_STEP}); + child->pos = spot; + if (!vector_is_zero(child->targetPosition)) child->targetPosition = spot; + child->isVisible = true; + child->entityCollisionClass = (EntityCollisionClass)data.savedCollisionClass; + helper.sprite.Play("Float"); + helper.state = MR_ME_LEAVE; + return move; +} + +// 005d2a70 (Entity_Effect::update_mr_me, Update's case 108) Seeks, works, carries or leaves in a poof, its carried +// pickup animating, and eases a tenth toward where it heads. +void Entity_Effect::update_mr_me() +{ + auto* data = dynamic_cast(extraData.get()); + if (!data) return; + + Vector move{}; + if (state == MR_ME_SEEK) move = mr_me_seek(*this, *data); + else if (state == MR_ME_WORK) move = mr_me_work(*this, *data); + else if (state == MR_ME_CARRY) move = mr_me_carry(*this, *data); + else if (state == MR_ME_LEAVE) + { + uint32_t seed = Random(); + g_game->Spawn({.position = pos, .spawner = this, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + Remove(); + } + data->carried.Update(); + velocity = vector_add(vector_scale(velocity, MR_ME_DRAG), vector_scale(move, MR_ME_STEER)); +} + +// The Mr. ME! part of 00607620 (Render): the helper, and the pickup it carries at its carry point. +static void mr_me_render(Entity_Effect& helper, const Vector&) +{ + helper.sprite.Render(SpriteDraw{helper.renderPosition, {}, {}}); + auto* data = dynamic_cast(helper.extraData.get()); + if (helper.state != MR_ME_CARRY || !helper.child || !data || !data->carried.isLoaded) return; + if (const NullFrame* carry = helper.sprite.GetNullFrame("CarryPos")) + data->carried.Render(SpriteDraw{vector_add(carry->pos, helper.renderPosition), {}, {}}); +} + +// Mr. ME!'s frame (Update's case 108). +static void mr_me_update(Entity_Effect& helper) +{ + helper.update_mr_me(); +} + +// 006fece0 (Game::SpawnEntityDesc) Spawns an enemy as a description keeps it: its kind, health and champion. +Entity_NPC* entity_desc_spawn(const EntityDesc& desc, const Vector& position, Entity* spawner) +{ + uint32_t seed = Random(); + Entity* spawned = g_game->Spawn({.position = position, + .spawner = spawner, + .subType = (int)desc.subtype, + .type = (int)desc.type, + .variant = (int)desc.variant, + .seed = seed}); + if (!spawned || !Entity::is_enemy_type(spawned->type)) return nullptr; + auto* npc = static_cast(spawned); + npc->health = desc.health; + npc->maxHitPoints = desc.maxHealth; + npc->Morph((int)desc.type, (int)desc.variant, (int)desc.subtype, desc.championId); + return npc; +} + +constexpr auto HELPER_BEHAVIOURS = std::to_array({ + {EFFECT_FRIEND_BALL, friend_ball_init, effect_finishing, nullptr}, + {EFFECT_MR_ME, mr_me_init, effect_finishing, mr_me_render}, +}); + +std::span helper_effect_behaviours() +{ + return HELPER_BEHAVIOURS; +} diff --git a/src/entity_effect_mother.cpp b/src/entity_effect_mother.cpp index 54a1a8c..c70653c 100644 --- a/src/entity_effect_mother.cpp +++ b/src/entity_effect_mother.cpp @@ -1,9 +1,12 @@ #include "beam_renderer.h" +#include "boss_ai.h" #include "entity_effect.h" +#include "entity_npc.h" #include "entity_player.h" #include "entity_projectile.h" #include "game.h" #include "npc_ai.h" +#include "npc_basement.h" #include "room.h" #include "room_grid.h" #include @@ -288,10 +291,245 @@ static void lava_spawner_update(Entity_Effect& lava) if (is_lava_past_target(lava)) lava_erupt(lava); } +// Mother's big knife: it ploughs a trail every 15 units of its path inside the room, each step throwing up dirt (and +// now and then a splat), green gibs and blood, and every other frame two sick shots out to the sides (faster where +// the trail swings) and a 30 damage hurt within 50. It shakes the room and speeds up as it goes. Hitting a wall it +// bursts into rubble, gore and nine fans of eight shots back the way it came, then fades out. +constexpr float KNIFE_STEP = 15; +constexpr float KNIFE_ROOM_MARGIN = 8; +constexpr float KNIFE_TRAIL_SWAY = 8; +constexpr int KNIFE_DIRT_RENDER_Z = 1000; +constexpr float KNIFE_DIRT_DEPTH = -160; +constexpr float KNIFE_DIRT_SCALE_SPAN = 0.4f; +constexpr int KNIFE_DIRT_FRAMES = 90; +constexpr int KNIFE_SPLAT_ODDS = 5; +constexpr float KNIFE_SPLAT_SCALE = 1.5f; +constexpr float KNIFE_GIB_SPREAD = 30; +constexpr float KNIFE_GIB_SPEED = 10; +constexpr float KNIFE_GIB_DROP = 90; +constexpr int KNIFE_GIB_SUBTYPE = 3; +constexpr float KNIFE_GIB_HEIGHT = -5; +constexpr float KNIFE_GIB_HEIGHT_SPAN = 10; +constexpr float KNIFE_BLOOD_SPEED = 5; +constexpr float KNIFE_SHOT_WAVE = 0.06f; +constexpr float KNIFE_SHOT_SPEED = 8; +constexpr float KNIFE_SHOT_SPEED_SWAY = 4; +constexpr float KNIFE_SHOT_ACCELERATION = 0.97f; +constexpr int KNIFE_SHOT_CHANGE_FRAMES = 20; +constexpr float KNIFE_SHOT_FALL = -0.09f; +constexpr float KNIFE_SHOT_SCALE_SPAN = 0.5f; +constexpr float KNIFE_HURT_DAMAGE = 30; +constexpr float KNIFE_HURT_REACH = 50; +constexpr int KNIFE_SHAKE = 4; +constexpr float KNIFE_SPEEDUP = 1.12f; +constexpr int KNIFE_PRIORITY = 255; +constexpr uint64_t KNIFE_SHOT_FLAGS = PROJECTILE_HIT_ENEMIES | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT | + PROJECTILE_ACCELERATE_EX; +constexpr uint64_t KNIFE_SHOT_CHANGED_FLAGS = PROJECTILE_HIT_ENEMIES | PROJECTILE_DECELERATE; +constexpr ColorMod KNIFE_SHOT_COLOR = color_make({1, 1, 1, 1}, {1.5f, 2, 1, 1}); + +// The wall burst: rubble and gore within 5 thrown back within 45 degrees, then nine fans of shots across 160. +constexpr float KNIFE_WALL_PROBE = 30; +constexpr int KNIFE_WALL_SHAKE = 16; +constexpr int KNIFE_BURST_SUBTYPE = 4; +constexpr float KNIFE_BURST_HEIGHT = -10; +constexpr float KNIFE_BURST_HEIGHT_SPAN = 20; +constexpr int KNIFE_DEBRIS = 12; +constexpr float KNIFE_DEBRIS_SPREAD = 90; +constexpr float KNIFE_DEBRIS_SPOT = 5; +constexpr float KNIFE_ROCK_SPEED_MIN = 20; +constexpr float KNIFE_GORE_SPEED_MIN = 5; +constexpr float KNIFE_DEBRIS_SPEED_MAX = 30; +constexpr int KNIFE_GORE_PLAIN_ODDS = 5; +constexpr int KNIFE_FANS = 9; +constexpr int KNIFE_FAN_SHOTS = 8; +constexpr float KNIFE_FAN_ARC = 160; +constexpr float KNIFE_FAN_SPEED_MIN = 5; +constexpr float KNIFE_FAN_SPEED_MAX = 20; +constexpr float KNIFE_FAN_FALL = -0.08f; +constexpr float KNIFE_FADE = 0.1f; +constexpr ColorMod KNIFE_FAN_COLOR = color_make({1, 1, 1, 1}, {2.7f, 3, 2, 1}); + +// A shot the knife throws for its spawner. +static Entity_Projectile* knife_shot_spawn(Entity_Effect& knife, Vector position, Vector velocity, uint32_t seed) +{ + auto* shot = static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = knife.spawnerEntity, + .type = ENTITY_PROJECTILE, + .seed = seed})); + shot->parent = knife.spawnerEntity; + return shot; +} + +// Sets a knife shot's fall, its size (1 to 1.5) and its tint. +static void knife_shot_finish(Entity_Projectile& shot, float fall, const ColorMod& color) +{ + shot.fallingAccel = fall; + shot.scale = random_unit() * KNIFE_SHOT_SCALE_SPAN + 1; + shot.SetColor(color, -1, KNIFE_PRIORITY, false, true); +} + +// A green gore effect turned at random, raised (by up to a random span more), tinted green and started. +static void knife_gore_finish(Entity& gore, float height, float heightSpan) +{ + gore.sprite.rotation = random_unit() * DEGREES_PER_TURN; + gore.posOffset = vector_make(0, heightSpan > 0 ? height - random_unit() * heightSpan : height); + gore.SetColor(COLOR_GREEN_SPLAT, -1, KNIFE_PRIORITY, false, true); + gore.Update(); +} + +// One step of the knife's trail. +static void knife_trail_step(Entity_Effect& knife, Vector at, Vector direction) +{ + Vector side = vector_scale(vector_rotated(direction, 90), std::lerp(-KNIFE_TRAIL_SWAY, KNIFE_TRAIL_SWAY, random_unit())); + Vector spot = vector_add(at, side); + uint32_t seed = Random(); + auto* dirt = static_cast( + g_game->Spawn({.position = spot, .type = ENTITY_EFFECT, .variant = EFFECT_DIRT_PILE, .seed = seed})); + dirt->renderZOffset = KNIFE_DIRT_RENDER_Z; + dirt->renderDepthOffset = KNIFE_DIRT_DEPTH; + float scale = random_unit() * KNIFE_DIRT_SCALE_SPAN + 1; + dirt->sprite.scale = vector_make(scale, scale); + dirt->SetTimeout(KNIFE_DIRT_FRAMES); + dirt->Update(); + if (random_below(KNIFE_SPLAT_ODDS) == 0) + { + seed = Random(); + Entity* splat = g_game->Spawn({.position = spot, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = seed}); + float size = (random_unit() * 0.5f + 0.5f) * KNIFE_SPLAT_SCALE; + splat->sprite.scale = vector_make(size, size); + splat->SetColor(COLOR_GREEN_SPLAT, -1, KNIFE_PRIORITY, false, true); + splat->Update(); + } + + seed = Random(); + Vector fling = vector_rotated(vector_make(0, -1), std::lerp(-KNIFE_GIB_SPREAD, KNIFE_GIB_SPREAD, random_unit())); + fling = vector_scale(vector_scale(fling, random_unit()), KNIFE_GIB_SPEED); + Entity* gib = g_game->Spawn({.position = vector_add(at, vector_make(0, KNIFE_GIB_DROP)), + .velocity = fling, + .subType = KNIFE_GIB_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = seed}); + knife_gore_finish(*gib, KNIFE_GIB_HEIGHT, KNIFE_GIB_HEIGHT_SPAN); + + Vector spray = random_direction(); + random_unit(); + seed = Random(); + Entity* blood = g_game->Spawn({.position = at, + .velocity = vector_scale(spray, KNIFE_BLOOD_SPEED), + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_PARTICLE, + .seed = seed}); + blood->sprite.color = COLOR_GREEN_SPLAT; + blood->splatColor = COLOR_GREEN_SPLAT; + blood->Update(); + + if (!knife.IsFrame(2, 0)) return; + float speed = std::sin(vector_distance(knife.targetPosition, at) * KNIFE_SHOT_WAVE) * KNIFE_SHOT_SPEED_SWAY + KNIFE_SHOT_SPEED; + for (float way : {1.0f, -1.0f}) + { + Entity_Projectile* shot = knife_shot_spawn(knife, at, vector_make(way * speed, 0), Random()); + shot->projectileFlags = KNIFE_SHOT_FLAGS; + shot->acceleration = KNIFE_SHOT_ACCELERATION; + shot->changeFlags = KNIFE_SHOT_CHANGED_FLAGS; + shot->changeTimeout = KNIFE_SHOT_CHANGE_FRAMES; + knife_shot_finish(*shot, KNIFE_SHOT_FALL, KNIFE_SHOT_COLOR); + } + damage_radius({.position = knife.pos, + .source = knife.spawnerEntity, + .damage = KNIFE_HURT_DAMAGE, + .playerDamageThreshold = KNIFE_HURT_REACH, + .radius = KNIFE_HURT_REACH, + .isHitAll = true}); +} + +// The knife bursts on the wall it hit: rubble, gore and fans of shots back the way it came. +static void knife_wall_burst(Entity_Effect& knife, Room& room) +{ + knife.state = 1; + game_shake_screen(KNIFE_WALL_SHAKE); + effect_sound_play(SOUND_MEATY_DEATHS); + effect_sound_play(SOUND_MAGGOT_ENTER_GROUND); + Vector spot = room.GetClampedPositionImpl(knife.pos, 1, 1, 1, 1); + uint32_t seed = Random(); + Entity* burst = g_game->Spawn( + {.position = spot, .subType = KNIFE_BURST_SUBTYPE, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = seed}); + knife_gore_finish(*burst, KNIFE_BURST_HEIGHT, KNIFE_BURST_HEIGHT_SPAN); + + Vector back = vector_scale(vector_normalized(knife.velocity), -1); + auto debris = [&](float speedMin) + { + Vector direction = vector_rotated(back, (random_unit() - 0.5f) * KNIFE_DEBRIS_SPREAD); + float speed = std::lerp(speedMin, KNIFE_DEBRIS_SPEED_MAX, random_unit()); + Vector at = vector_add(spot, vector_scale(vector_scale(direction, random_unit()), KNIFE_DEBRIS_SPOT)); + return std::pair{at, vector_scale(direction, speed)}; + }; + for (int i = 0; i < KNIFE_DEBRIS; i++) + { + auto [at, velocity] = debris(KNIFE_ROCK_SPEED_MIN); + seed = Random(); + g_game->Spawn({.position = at, .velocity = velocity, .type = ENTITY_EFFECT, .variant = EFFECT_ROCK_PARTICLE, .seed = seed})->Update(); + } + for (int i = 0; i < KNIFE_DEBRIS; i++) + { + auto [at, velocity] = debris(KNIFE_GORE_SPEED_MIN); + seed = Random(); + int subtype = random_below(KNIFE_GORE_PLAIN_ODDS) == 0 ? 0 : random_below(2) ? KNIFE_GIB_SUBTYPE : KNIFE_BURST_SUBTYPE; + Entity* gore = g_game->Spawn( + {.position = at, .velocity = velocity, .subType = subtype, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = seed}); + knife_gore_finish(*gore, KNIFE_BURST_HEIGHT, 0); + } + for (int fan = 0; fan < KNIFE_FANS; fan++) + { + Vector direction = vector_rotated(back, (float)fan / (KNIFE_FANS - 1) * KNIFE_FAN_ARC - KNIFE_FAN_ARC / 2); + Vector at = vector_add(spot, vector_scale(direction, KNIFE_DEBRIS_SPOT)); + for (int i = 0; i < KNIFE_FAN_SHOTS; i++) + { + uint32_t shotSeed = Random(); + float speed = std::lerp(KNIFE_FAN_SPEED_MIN, KNIFE_FAN_SPEED_MAX, random_unit()); + Entity_Projectile* shot = knife_shot_spawn(knife, at, vector_scale(direction, speed), shotSeed); + shot->projectileFlags = PROJECTILE_HIT_ENEMIES; + knife_shot_finish(*shot, KNIFE_FAN_FALL, KNIFE_FAN_COLOR); + } + } +} + +// 005e26d9 (Update's case 182) Ploughs its trail from where it was to where it is, bursts on the first wall below +// it, then fades by a tenth a tick. +static void big_knife_update(Entity_Effect& knife) +{ + Room& room = *g_game->room; + if (vector_is_zero(knife.targetPosition)) knife.targetPosition = knife.prevPosition; + if (knife.FrameCount() > 0) + { + Vector path = vector_sub(knife.pos, knife.prevPosition); + float length = vector_length(path); + Vector direction = vector_normalized(path); + int steps = std::max((int)std::floor(length / KNIFE_STEP + 0.5f), 1); + for (int step = 0; step < steps; step++) + { + Vector at = vector_add(knife.prevPosition, vector_scale(direction, length * ((float)step / steps))); + if (room.IsPositionInRoom(at, KNIFE_ROOM_MARGIN)) knife_trail_step(knife, at, direction); + } + game_shake_screen(KNIFE_SHAKE); + knife.friction *= KNIFE_SPEEDUP; + } + if (knife.state == 0 && room_grid_collision_at(vector_add(knife.pos, vector_make(0, KNIFE_WALL_PROBE))) == GRIDCOLL_WALLS) + knife_wall_burst(knife, room); + if (knife.state <= 0) return; + + float& alpha = knife.sprite.color._tint[3]; + alpha = std::max(alpha - knife.speedMultiplier * KNIFE_FADE, 0.0f); + if (alpha <= 0) knife.Remove(); +} + constexpr auto MOTHER_EFFECT_BEHAVIOURS = std::to_array({ {EFFECT_MOTHER_TRACER, tracer_init, mother_tracer_update, mother_tracer_render}, {EFFECT_GENERIC_TRACER, tracer_init, effect_finishing, generic_tracer_render}, {EFFECT_LAVA_SPAWNER, lava_spawner_init, effect_finishing, nullptr}, + {EFFECT_BIG_KNIFE, nullptr, effect_finishing, nullptr}, }); std::span mother_effect_behaviours() diff --git a/src/entity_effect_portal.cpp b/src/entity_effect_portal.cpp index 7f088f9..a0707e7 100644 --- a/src/entity_effect_portal.cpp +++ b/src/entity_effect_portal.cpp @@ -30,8 +30,7 @@ constexpr int PORTAL_SWIRL_LAYERS = 3; constexpr float PORTAL_SWIRL_SPAN = 30; constexpr float PORTAL_SWIRL_MAX = 1.5f; -// A portal's room: its kind by subtype (treasure, boss, secret, shop, else a normal room), or one room past 1000. -constexpr std::array PORTAL_ROOM_TYPES = {ROOM_TREASURE, ROOM_BOSS, ROOM_SECRET, ROOM_SHOP}; +// A portal's room: its kind by subtype (PORTAL_ROOM_TYPES, else a normal room), or one room past 1000. constexpr int PORTAL_ROOM_INDEX_BASE = 1000; constexpr int PORTAL_GIVEN_ROOM = 900; diff --git a/src/entity_effect_shots.cpp b/src/entity_effect_shots.cpp index a72e2f2..4206549 100644 --- a/src/entity_effect_shots.cpp +++ b/src/entity_effect_shots.cpp @@ -521,12 +521,149 @@ static void shield_update(Entity_Effect& shield) shield_block(shield); } +// Jacob's Ladder's chain lightning: an invisible spark that jumps from enemy to enemy. It lives a frame at a time, +// starting from its target with 130 of reach, and each time it would die it jumps once more (its jumps counted down +// in its max radius) to the best unhit enemy within reach: the nearest give or take 25, one already hit (when it may +// rehit) 100 farther. In water, enemies on the ground are 200 farther in reach and count as much nearer. Each jump +// fires a thin spectral laser along it carrying its status tear flags, and its first one fires even with no enemy. +constexpr float CHAIN_LIGHTNING_REACH = 130; +constexpr float CHAIN_BASE_DAMAGE = 3.5f; +constexpr float CHAIN_WET = 0.1f; +constexpr float CHAIN_WET_REACH = 200; +constexpr float CHAIN_WET_SHARE = 0.15f; +constexpr float CHAIN_REHIT_PENALTY = 100; +constexpr float CHAIN_JITTER = 50; +constexpr float CHAIN_NEAREST = 0.01f; +constexpr float CHAIN_FARTHEST = 1e10f; +constexpr int CHAIN_LASER_VARIANT = 10; +constexpr int CHAIN_LASER_TIMEOUT = 3; +constexpr float CHAIN_LASER_HEIGHT = -18; + +// The tear flags a chain lightning's laser keeps: the status effects and drops. +constexpr std::array CHAIN_KEPT_FLAGS = { + TEAR_SLOW, TEAR_POISON, TEAR_FREEZE, TEAR_MULLIGAN, TEAR_CHARM, TEAR_CONFUSION, TEAR_HP_DROP, TEAR_FEAR, + TEAR_SHRINK, TEAR_BURN, TEAR_KNOCKBACK, TEAR_GISH, TEAR_MYSTERIOUS_LIQUID_CREEP, TEAR_LIGHT_FROM_HEAVEN, + TEAR_COIN_DROP, TEAR_BLACK_HP_DROP, TEAR_GODS_FLESH_FLAG, TEAR_GREED_COIN, TEAR_PERMANENT_CONFUSION, + TEAR_BOOGER_FLAG, TEAR_EGG_FLAG, TEAR_ACID, TEAR_MIDAS, TEAR_NEEDLE_FLAG, TEAR_HORN, TEAR_PUNCH, TEAR_ICE_FLAG, + TEAR_MAGNETIZE, TEAR_BAIT, TEAR_ECOLI, TEAR_COIN_DROP_DEATH}; + +// The chain lightning part of 005cdb20 (Init): unseen, a frame long, with its reach and no tear flags. +static void chain_lightning_init(Entity_Effect& chain) +{ + chain.SetTimeout(1); + chain.maxRadius = CHAIN_LIGHTNING_REACH; + chain.minRadius = CHAIN_LIGHTNING_REACH; + chain.baseDamage = CHAIN_BASE_DAMAGE; + chain.baseScale = 1; + chain.varData = {}; + chain.isVisible = false; +} + +// Whether an entity stands in the water a chain lightning runs through. +static bool is_chain_grounded(Entity& entity) +{ + return entity.entityGridCollisionClass == GRIDCOLL_GROUND || entity.entityGridCollisionClass == GRIDCOLL_NOPITS; +} + +// The enemy a chain lightning jumps to next from where it is, or none. +static Entity* chain_next_find(Entity_Effect& chain) +{ + bool isWet = g_game->room->waterAmount > CHAIN_WET; + float reach = chain.minRadius; + if (isWet && (!chain.target || is_chain_grounded(*chain.target))) reach += CHAIN_WET_REACH; + + Entity* best = nullptr; + float bestScore = CHAIN_FARTHEST; + for (Entity* enemy : entity_query_radius(chain.pos, reach, QUERY_ENEMIES)) + { + bool isGrounded = is_chain_grounded(*enemy); + float ownReach = isWet && isGrounded ? reach : chain.minRadius; + if (!enemy->IsVulnerableEnemy(nullptr) || enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) continue; + if (enemy == chain.target) continue; + float distanceSquared = vector_length_squared(vector_sub(enemy->pos, chain.pos)); + if (ownReach != reach && distanceSquared >= (enemy->size + ownReach) * (enemy->size + ownReach)) continue; + bool isHit = EntityList::HitListContains(chain.hitList, *enemy); + if (isHit && !chain.HasEntityFlags(FLAG_SPAWN_STICKY_SPIDERS)) continue; + + float distance = vector_length(vector_sub(enemy->pos, chain.pos)); + float score = distance + (isHit ? CHAIN_REHIT_PENALTY : 0); + score += (random_unit() - 0.5f) * CHAIN_JITTER; + if (isWet && isGrounded) score *= CHAIN_WET_SHARE; + if (distance <= CHAIN_NEAREST || score >= bestScore) continue; + best = enemy; + bestScore = score; + } + return best; +} + +// Fires the chain's thin spectral laser along a jump, which passes the enemies it already hit. Without one it goes. +static void chain_laser_fire(Entity_Effect& chain, Entity* next, Vector jump) +{ + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = chain.pos, + .posOffset = vector_make(0, CHAIN_LASER_HEIGHT), + .source = chain.spawnerEntity, + .angleDegrees = vector_angle(jump), + .timeout = CHAIN_LASER_TIMEOUT, + .variant = CHAIN_LASER_VARIANT, + .isPoolKept = true}); + if (!laser) return chain.Remove(); + + laser->isMultidimensionalTouched = true; + laser->isPrismTouched = true; + laser->maxDistance = vector_length(jump); + laser->SetCollisionDamage(chain.collisionDamage); + TearFlags flags = effect_tear_flags(chain); + TearFlags kept; + for (int flag : CHAIN_KEPT_FLAGS) kept[flag] = flags[flag]; + kept[TEAR_SPECTRAL] = true; + laser->tearFlags = kept; + for (uint32_t hit : chain.hitList) + if (!next || next->index != hit) laser->hitList.push_back(hit); + laser->mass = 0; + laser->isOneHit = true; + laser->isDisableFollowParent = true; + laser->Update(); + chain.state++; +} + +// 005e038f (Update's case 167) Marks its first target hit. Each time it would die it lives on a frame, jumps to the +// next enemy (firing its laser) and stands on it, or goes once out of jumps or enemies. +static void chain_lightning_update(Entity_Effect& chain) +{ + if (chain.state == 0) + { + if (chain.target) hit_list_insert(chain.hitList, *chain.target); + chain.state++; + } + if (!chain.isDead) return; + + chain.SetTimeout(1); + chain.isDead = false; + chain.maxRadius--; + Entity* next = chain_next_find(chain); + if (next || chain.state == 1) + { + Vector jump = next ? vector_sub(next->pos, chain.pos) + : vector_scale(vector_scale(random_direction(), random_unit()), chain.minRadius); + chain_laser_fire(chain, next, jump); + } + if (next) + { + chain.target = next; + hit_list_insert(chain.hitList, *next); + chain.pos = next->pos; + } + else chain.maxRadius = 0; + if (chain.maxRadius <= 0) chain.Remove(); +} + constexpr auto SHOT_EFFECT_BEHAVIOURS = std::to_array({ {EFFECT_EVIL_EYE, nullptr, effect_finishing, nullptr}, {EFFECT_BRIMSTONE_SWIRL, swirl_init, effect_finishing, nullptr}, {EFFECT_TECH_DOT, tech_dot_init, effect_finishing, tech_dot_render}, {EFFECT_DARK_SNARE, dark_snare_init, effect_finishing, nullptr}, {EFFECT_DIVINE_INTERVENTION, shield_init, effect_finishing, nullptr}, + {EFFECT_CHAIN_LIGHTNING, chain_lightning_init, effect_finishing, nullptr}, }); std::span shot_effect_behaviours() diff --git a/src/entity_effect_vortex.cpp b/src/entity_effect_vortex.cpp new file mode 100644 index 0000000..cb0929f --- /dev/null +++ b/src/entity_effect_vortex.cpp @@ -0,0 +1,578 @@ +#include "entity_combat.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_effect_combat.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "game.h" +#include "grid_entity.h" +#include "npc_ai.h" +#include "room.h" +#include "room_grid.h" +#include +#include +#include + +// The effects that pull the room in or grind through it: the Black Hole, the tears' rifts and brimstone balls. + +// The critters a rift or a brimstone ball eats: tiny bugs and flies, worms, beetles and lil ghosts. +constexpr std::array EATEN_CRITTERS = {EFFECT_TINY_BUG, EFFECT_TINY_FLY, EFFECT_WORM, EFFECT_BEETLE, + EFFECT_LIL_GHOST}; + +// Kills a critter effect a rift or brimstone ball touches, or says the entity is not one. +static bool is_critter_eaten(Entity& entity) +{ + if (entity.type != ENTITY_EFFECT || !std::ranges::count(EATEN_CRITTERS, entity.variant)) return false; + entity.isDead = true; + return true; +} + +// Brings its player's laser effects (when it has one) on what a rift or brimstone ball hits, and gives the laser +// damage flags with the ones those effects add. +static uint64_t laser_effects_apply(Entity_Effect& effect, Entity& entity, Entity_Player* player) +{ + if (!player) return DAMAGE_LASER; + TearParams params = player->GetTearHitParams(WEAPON_LASER, 1, 0, effect.spawnerEntity); + uint64_t damageFlags = DAMAGE_LASER | tear_damage_flags_get(params.tearFlags, &effect); + Entity_Tear::ApplyTearFlagEffects(&entity, effect.pos, params.tearFlags, &effect, effect.collisionDamage); + return damageFlags; +} + +// Whether a rift or brimstone ball hurts an entity it touches: a vulnerable enemy, or a solid fireplace, movable TNT +// or poop. +static bool is_laser_target(Entity& entity) +{ + if (entity.IsVulnerableEnemy(nullptr)) return true; + if (entity.entityCollisionClass == ENTCOLL_NONE) return false; + return entity.type == ENTITY_FIREPLACE || entity.type == ENTITY_MOVABLE_TNT || entity.type == ENTITY_POOP; +} + +// The player behind a rift or brimstone ball: its spawner, or its spawner's last spawner. +static Entity_Player* effect_player_get(Entity_Effect& effect) +{ + Entity* spawner = effect.spawnerEntity; + Entity_Player* player = spawner ? spawner->ToPlayer() : nullptr; + if (!player && spawner) player = spawner->GetLastSpawner()->ToPlayer(); + return player; +} + +// The Black Hole is thrown in an arc 32 high, slowing, and lands on the floor to pull for 180 frames. Its swirl +// pieces (subtype 1) spin off it, hold their place and go once their animation ends. +constexpr int BLACK_HOLE_PIECE = 1; +constexpr float BLACK_HOLE_THROW_HEIGHT = -32; +constexpr float BLACK_HOLE_FALL = 1; +constexpr float BLACK_HOLE_LANDING_HEIGHT = -11; +constexpr float BLACK_HOLE_THROW_DRAG = 0.84f; +constexpr float BLACK_HOLE_HOLD_DRAG = 0.1f; +constexpr int BLACK_HOLE_FRAMES = 180; +constexpr float BLACK_HOLE_PITCH = 0.186f; +constexpr float BLACK_HOLE_PULSE_SPEED = 0.4f; +constexpr float BLACK_HOLE_PULSE = 0.15f; +constexpr float BLACK_HOLE_SCALE = 1.8f; +constexpr float BLACK_HOLE_WALL_MARGIN = 20; +constexpr float BLACK_HOLE_WALL_PUSH = 0.3f; + +// While it pulls (past its first 4 and before its last 11 frames) it spins a piece off within 20 by 9, squashed by +// how upright its offset is, and throws dark smoke (every 6 frames) and embers within 44 by 22. +constexpr int BLACK_HOLE_SPIN_START = 176; +constexpr int BLACK_HOLE_SPIN_END = 11; +constexpr float BLACK_HOLE_SPIN_REACH_X = 20; +constexpr float BLACK_HOLE_SPIN_REACH_Y = 9; +constexpr float BLACK_HOLE_PIECE_WIDTH = 0.72f; +constexpr float BLACK_HOLE_PIECE_HEIGHT = 0.79f; +constexpr float BLACK_HOLE_PIECE_SQUASH = 0.45f; +constexpr float BLACK_HOLE_PIECE_TURN = 90; +constexpr float BLACK_HOLE_DUST_REACH = 11; +constexpr int BLACK_HOLE_SMOKE_PERIOD = 6; +constexpr float BLACK_HOLE_SMOKE_SPEED = 5; +constexpr float BLACK_HOLE_EMBER_SPEED = -3; +constexpr float BLACK_HOLE_DUST_HEIGHT = 5; +constexpr ColorMod BLACK_HOLE_DUST_COLOR = color_make({0, 0, 0, 1}); + +// It pulls the players (but a heavy one) a quarter, bombs 0.85, and the enemies, shots and rerollable pickups +// harder the nearer within 280 (a pickup 0.3 as hard, a shot 0.7), stopping all but the heavy ones dead. It hurts +// the enemies within 50 for 0.4 every other frame, and in versus mode the players for 1 but its own thrower. +constexpr float BLACK_HOLE_PLAYER_PULL = 0.25f; +constexpr float BLACK_HOLE_BOMB_PULL = 0.85f; +constexpr float BLACK_HOLE_HEAVY = 1000; +constexpr float BLACK_HOLE_PICKUP_PULL = 0.3f; +constexpr float BLACK_HOLE_SHOT_PULL = 0.7f; +constexpr float BLACK_HOLE_HELD_MASS = 60; +constexpr float BLACK_HOLE_STOP = 1e-05f; +constexpr float BLACK_HOLE_LEFT_SPEED = 4; +constexpr float BLACK_HOLE_REACH = 280; +constexpr float BLACK_HOLE_REACH_MIN = 8; +constexpr float BLACK_HOLE_PULL = 0.6f; +constexpr float BLACK_HOLE_SWIRL = 8; +constexpr float BLACK_HOLE_HURT_REACH = 50; +constexpr float BLACK_HOLE_DAMAGE = 0.4f; +constexpr int BLACK_HOLE_HURT_PERIOD = 2; +constexpr int BLACK_HOLE_HURT_COUNTDOWN = 100; + +// Its pull breaks the rocks in a ring that grows 32 every 22 frames, dusting them every other frame between. +constexpr int BLACK_HOLE_RING_FRAMES = 22; +constexpr float BLACK_HOLE_RING_WIDTH = 32; +constexpr int GRID_ROCK_BROKEN = 2; +constexpr float BLACK_HOLE_RUBBLE_REACH = 3; +constexpr float BLACK_HOLE_RUBBLE_SPEED = 3; +constexpr float BLACK_HOLE_RUBBLE_HEIGHT = 1; +constexpr ColorMod BLACK_HOLE_RUBBLE_COLOR = color_make({0.8f, 0.8f, 0.8f, 1}); + +// The Black Hole part of 005cdb20 (Init): the hole is thrown from 32 up, a piece idles. +static void black_hole_init(Entity_Effect& hole) +{ + if (hole.subtype != 0) return hole.sprite.Play("Idle"); + hole.posOffset.y = BLACK_HOLE_THROW_HEIGHT; + hole.sprite.Play("Throw"); +} + +// A swirl piece and two puffs of dust thrown off the pulling hole. +static void black_hole_spin(Entity_Effect& hole) +{ + Vector offset = random_direction(); + offset = vector_make(offset.x * BLACK_HOLE_SPIN_REACH_X, offset.y * BLACK_HOLE_SPIN_REACH_Y); + if (hole.timeout > BLACK_HOLE_SPIN_END && hole.timeout < BLACK_HOLE_SPIN_START) + { + uint32_t seed = Random(); + Entity* piece = g_game->Spawn({.position = vector_add(hole.pos, offset), + .spawner = &hole, + .subType = BLACK_HOLE_PIECE, + .type = hole.type, + .variant = hole.variant, + .seed = seed}); + float upright = std::abs(vector_dot(vector_normalized(offset), vector_make(0, -1))); + piece->sprite.scale = + vector_make(BLACK_HOLE_PIECE_WIDTH, BLACK_HOLE_PIECE_HEIGHT - upright * BLACK_HOLE_PIECE_SQUASH); + piece->sprite.rotation = vector_angle(offset) + BLACK_HOLE_PIECE_TURN; + + auto dust = [&](int variant, float speed) + { + float y = random_unit() * BLACK_HOLE_DUST_REACH * 4 - BLACK_HOLE_DUST_REACH * 2; + float x = random_unit() * BLACK_HOLE_DUST_REACH * 8 - BLACK_HOLE_DUST_REACH * 4; + game_particles_spawn({.color = BLACK_HOLE_DUST_COLOR, + .position = vector_add(hole.pos, vector_make(x, y)), + .height = BLACK_HOLE_DUST_HEIGHT, + .speed = speed, + .count = 1, + .variant = variant}); + }; + if (g_game->frameCount % BLACK_HOLE_SMOKE_PERIOD == 0) dust(EFFECT_DARK_BALL_SMOKE_PARTICLE, BLACK_HOLE_SMOKE_SPEED); + dust(EFFECT_EMBER_PARTICLE, BLACK_HOLE_EMBER_SPEED); + } +} + +// Pulls one entity toward the hole, and hurts it when it is a vulnerable enemy close by. +static void black_hole_pull(Entity_Effect& hole, Entity& entity) +{ + bool isRerollable = false; + if (entity.is_pickup()) + { + auto& pickup = static_cast(entity); + isRerollable = !pickup.IsShopItem() && pickup.variant != PICKUP_COLLECTIBLE && pickup.CanReroll(); + } + + Vector toward = vector_sub(hole.pos, entity.pos); + if (entity.is_player() && entity.mass != BLACK_HOLE_HEAVY) + entity.AddVelocity_divided(vector_resized(toward, BLACK_HOLE_PLAYER_PULL), false); + else if (entity.is_bomb()) entity.AddVelocity_divided(vector_resized(toward, BLACK_HOLE_BOMB_PULL), false); + else if ((isRerollable || entity.IsVulnerableEnemy(nullptr) || entity.IsProjectile()) && + entity.mass < BLACK_HOLE_HELD_MASS) + { + float share = isRerollable ? BLACK_HOLE_PICKUP_PULL : entity.IsProjectile() ? BLACK_HOLE_SHOT_PULL : 1; + Vector left = vector_scale(entity.velocity, BLACK_HOLE_STOP); + if (vector_length_squared(left) > BLACK_HOLE_LEFT_SPEED * BLACK_HOLE_LEFT_SPEED) + left = vector_resized(left, BLACK_HOLE_LEFT_SPEED); + entity.velocity = left; + float nearness = std::clamp(BLACK_HOLE_REACH - vector_length(toward), BLACK_HOLE_REACH_MIN, BLACK_HOLE_REACH); + Vector pull = vector_scale(toward, nearness / BLACK_HOLE_REACH * BLACK_HOLE_PULL); + entity.AddVelocity_divided(vector_scale(vector_rotated(pull, BLACK_HOLE_SWIRL), share), false); + } + + if (!entity.IsVulnerableEnemy(nullptr)) return; + if (vector_length_squared(vector_sub(entity.pos, hole.pos)) >= BLACK_HOLE_HURT_REACH * BLACK_HOLE_HURT_REACH) return; + if (g_game->frameCount % BLACK_HOLE_HURT_PERIOD != 0) return; + float damage = BLACK_HOLE_DAMAGE; + if (g_game->deathmatchManager.is_active() && entity.is_player()) + damage = hole.spawnerEntity && hole.spawnerEntity->IsDescendantOf(&entity) ? 0 : 1; + entity.TakeDamage(damage, 0, EntityRef(&hole), BLACK_HOLE_HURT_COUNTDOWN); +} + +// The ring of rocks the hole's pull breaks now, or dusts every other frame. +static void black_hole_rocks_break(Entity_Effect& hole) +{ + Room& room = *g_game->room; + float ring = std::floor((float)(BLACK_HOLE_FRAMES - hole.timeout) / BLACK_HOLE_RING_FRAMES) * BLACK_HOLE_RING_WIDTH; + for (int index = 0; index < room.GetGridSize(); index++) + { + GridEntity* rock = room.GetGridEntity(index); + if (!rock || !rock->IsBreakableRock() || rock->state == GRID_ROCK_BROKEN) continue; + float distance = vector_length(vector_sub(rock->Position(), hole.pos)); + if (distance <= ring || distance >= ring + BLACK_HOLE_RING_WIDTH) continue; + if (hole.timeout % BLACK_HOLE_RING_FRAMES == 0) rock->Destroy(false, EntityRef(&hole)); + else if (g_game->frameCount % 2 == 0) + game_particles_spawn( + {.color = BLACK_HOLE_RUBBLE_COLOR, + .position = vector_add(rock->Position(), vector_scale(random_direction(), BLACK_HOLE_RUBBLE_REACH)), + .height = BLACK_HOLE_RUBBLE_HEIGHT, + .speed = BLACK_HOLE_RUBBLE_SPEED, + .count = 1, + .variant = EFFECT_DARK_BALL_SMOKE_PARTICLE}); + } +} + +// 00601806 (Update's case 107) The thrown hole falls to the floor and starts its pull with a deep rumble. Pulling, it +// holds its place, flickers in random colors and pulses, spins pieces off, pulls and breaks. It goes after its death +// animation, kept off the walls. A piece holds its place until its animation ends. +static void black_hole_update(Entity_Effect& hole) +{ + if (hole.subtype != 0) + { + if (hole.sprite.IsFinished()) hole.Remove(); + hole.velocity = vector_scale(hole.velocity, BLACK_HOLE_HOLD_DRAG); + if (vector_is_zero(hole.targetPosition)) hole.targetPosition = hole.pos; + hole.pos = hole.targetPosition; + return; + } + + if (hole.state == 0) + { + hole.posOffset.y += BLACK_HOLE_FALL; + hole.velocity = vector_scale(hole.velocity, BLACK_HOLE_THROW_DRAG); + if (hole.posOffset.y > BLACK_HOLE_LANDING_HEIGHT) + { + hole.state++; + hole.posOffset.y = 0; + hole.sprite.Play("Init"); + hole.sortingLayer = SORTING_BACKGROUND; + hole.timeout = BLACK_HOLE_FRAMES; + hole.targetPosition = hole.pos; + effect_sound_play(SOUND_BLOOD_LASER, {.pitch = BLACK_HOLE_PITCH}); + } + } + else + { + hole.velocity = vector_scale(hole.velocity, BLACK_HOLE_HOLD_DRAG); + hole.pos = hole.targetPosition; + if (hole.sprite.IsFinished() && !hole.isDead) hole.sprite.Play("Idle"); + float blue = random_unit(); + float green = random_unit(); + float red = random_unit(); + hole.sprite.color = color_make({red, green, blue, 1}); + float scale = std::sin((float)g_game->frameCount * BLACK_HOLE_PULSE_SPEED) * BLACK_HOLE_PULSE + BLACK_HOLE_SCALE; + hole.sprite.scale = vector_make(scale, scale); + black_hole_spin(hole); + for (Entity* entity : g_game->room->entityList.updateEL) black_hole_pull(hole, *entity); + black_hole_rocks_break(hole); + } + + if (hole.isDead) + { + hole.sprite.Play("Death"); + if (hole.sprite.IsFinished()) hole.Remove(); + } + Vector clamped = g_game->room->GetClampedPosition(hole.pos, BLACK_HOLE_WALL_MARGIN); + if (clamped.x != hole.pos.x || clamped.y != hole.pos.y) + hole.velocity = vector_scale(vector_sub(clamped, hole.pos), BLACK_HOLE_WALL_PUSH); + hole.pos = clamped; +} + +// A rift opens with its vortex drawn under it, its four swirl layers following its first null's alpha and scale. It +// pulls the vulnerable enemies (but its player), shots, bombs and free pickups within 256 of its scale, harder the +// nearer, against their friction. Shots slow and stop falling once near, and burst inside it. Every 10 frames it +// hurts the enemies touching it and eats the tiny critters. Dead, it closes and goes. +constexpr float RIFT_REACH = 256; +constexpr int RIFT_SWIRL_LAYERS = 5; +constexpr float RIFT_PULL = 8; +constexpr float RIFT_STRONG_PULL = 20; +constexpr float RIFT_NEAR = 8; +constexpr float RIFT_NEAR_SHARE = 64; +constexpr float RIFT_SHOT_DRAG = 2; +constexpr float RIFT_SHOT_DRAG_MIN = 0.5f; +constexpr float RIFT_SHOT_HOVER = 0.3f; +constexpr int RIFT_SHOT_SAFE_FRAMES = 15; +constexpr float RIFT_SHOT_LOWEST = -50; +constexpr int RIFT_HIT_PERIOD = 10; +constexpr int RIFT_HIT_COUNTDOWN = 30; +constexpr float RIFT_ATTRACT_STRENGTH = 20; +constexpr float RIFT_ATTRACT_RADIUS = 250; + +// The rift part of 005cdb20 (Init): it sorts under what stands on it. +static void rift_init(Entity_Effect& rift) +{ + rift.renderDepthOffset = -100; +} + +// Whether a rift pulls an entity: a vulnerable enemy but its player, a shot, a bomb, or a free pickup (but an open +// chest). +static bool is_rift_pulled(Entity& entity, Entity_Player* player) +{ + if (entity.IsVulnerableEnemy(nullptr) && &entity != player) return true; + if (entity.IsProjectile() || entity.is_bomb()) return true; + if (!entity.is_pickup()) return false; + auto& pickup = static_cast(entity); + return pickup.price == 0 && !(Entity_Pickup::IsChest(pickup.variant) && pickup.subtype == 0); +} + +// Pulls one entity toward the rift, hurting it on the hit frames when it is an enemy touching it. +static void rift_pull(Entity_Effect& rift, Entity& entity, float strength) +{ + float distance = std::sqrt(vector_length_squared(vector_sub(entity.pos, rift.pos))); + Vector toward = vector_normalized(vector_sub(rift.pos, entity.pos)); + float pull = entity.IsEnemy() || entity.IsTear() || entity.is_bomb() ? RIFT_STRONG_PULL : RIFT_PULL; + pull *= strength; + + if (rift.IsFrame(RIFT_HIT_PERIOD, 0) && entity.IsEnemy() && distance < entity.size + rift.size && is_laser_target(entity)) + entity.TakeDamage(rift.collisionDamage, DAMAGE_LASER, EntityRef(rift.parent), RIFT_HIT_COUNTDOWN); + + float nearness = distance < RIFT_NEAR ? distance / RIFT_NEAR_SHARE : 1 / distance; + pull = pull * nearness / entity.friction; + if (entity.IsProjectile()) + { + auto& shot = static_cast(entity); + shot.velocity = vector_scale(shot.velocity, std::max(RIFT_SHOT_DRAG_MIN, 1 - nearness * RIFT_SHOT_DRAG)); + if (nearness > RIFT_SHOT_HOVER && shot.fallingAccel < 0) shot.fallingAccel = 0; + if (!shot.isDead && distance * distance < rift.size * rift.size && shot.FrameCount() > RIFT_SHOT_SAFE_FRAMES && + shot.height > RIFT_SHOT_LOWEST) + shot.isDead = true; + } + entity.AddVelocity(vector_scale(toward, pull), false); +} + +// Every 10 frames the rift eats the critters on it and hurts what it touches but its player. +static void rift_hits_update(Entity_Effect& rift, Entity_Player* player) +{ + for (Entity* entity : entity_query_radius(rift.pos, rift.size, QUERY_ALL)) + { + if (entity == player || is_critter_eaten(*entity) || !is_laser_target(*entity)) continue; + uint64_t damageFlags = laser_effects_apply(rift, *entity, player); + entity->TakeDamage(rift.collisionDamage, damageFlags, EntityRef(rift.parent), RIFT_HIT_COUNTDOWN); + } +} + +// 005e1225 (Update's case 180) Opens on its first frame, follows its null with its swirl, then pulls, attracts and +// hurts while alive, sized by its config's radius and its scale. Dead, it closes and goes. +static void rift_update(Entity_Effect& rift) +{ + if (rift.state == 0) + { + rift.state++; + rift.sprite.Play("Open"); + rift.sprite.PlayOverlay("Vortex"); + rift.sprite.isOverlayRenderFirst = true; + } + if (const NullFrame* null = rift.sprite.GetNullFrameById(0)) + for (int layerId = 1; layerId < RIFT_SWIRL_LAYERS; layerId++) + if (LayerState* layer = rift.sprite.GetLayer(layerId)) + { + layer->color._tint[3] = null->color._tint[3]; + layer->size = null->scale; + } + + if (rift.isDead) + { + rift.sprite.Play("Close"); + if (rift.sprite.IsFinished()) rift.Remove(); + return; + } + + if (rift.sprite.IsFinished()) rift.sprite.Play("Idle"); + Entity_Player* player = effect_player_get(rift); + + float reach = rift.sprite.scale.x * RIFT_REACH; + float strength = std::min(rift.sprite.scale.x, 1.0f); + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (!is_rift_pulled(*entity, player) || entity == &rift) continue; + if (vector_is_zero(vector_sub(entity->pos, rift.pos)) || entity->friction == 0) continue; + if (vector_length_squared(vector_sub(entity->pos, rift.pos)) < reach * reach) rift_pull(rift, *entity, strength); + } + entities_attract({.position = rift.pos, .spared = player, .radius = RIFT_ATTRACT_RADIUS, .strength = RIFT_ATTRACT_STRENGTH}); + rift.size = rift.config->collisionRadius * rift.sprite.scale.x; + if (rift.IsFrame(RIFT_HIT_PERIOD, 0)) rift_hits_update(rift, player); +} + +// A brimstone ball (Brimstone with Tech X or Anti-Gravity): it remembers its damage and size from its first frame +// (half again with Shrink), appears, and fades by a fifth a frame while it disappears. It carries its tears' flags: +// Strange Attractor pulls, Eye of the Occult steers it 3 times its player's shot speed toward the aim, homing picks +// an enemy within 100 of where it heads, Grow and Shrink change it (it dies as Shrink leaves it at a tenth). Every +// other frame it hurts the rocks within 15 (with its spawner's touch), eats critters, burns its way through what it +// touches (blessed Shield tears reflect a fifth of the shots) and splatters Brimstone-marked enemies once, for double +// damage and 3. +constexpr float BALL_SHRINK_SCALE = 1.5f; +constexpr float BALL_FADE = 0.8f; +constexpr float BALL_OCCULT_SPEED = 3; +constexpr float BALL_OCCULT_FRICTION = 0.8f; +constexpr float BALL_HOMING_LOOKAHEAD = 5; +constexpr float BALL_HOMING_RANGE = 100; +constexpr int BALL_HOMING_PERIOD = 5; +constexpr float BALL_HOMING_TURN = 0.5f; +constexpr float BALL_GROW_DAMAGE = 0.014f; +constexpr float BALL_GROW_SCALE = 0.01f; +constexpr float BALL_SHRINK_STEP = 0.035f; +constexpr float BALL_SHRINK_DAMAGE = 0.08f; +constexpr float BALL_SMALLEST = 0.1f; +constexpr float BALL_MOVING_DRAG = 0.9f; +constexpr int BALL_HIT_PERIOD = 2; +constexpr float BALL_ROCK_REACH = 15; +constexpr int BALL_DEFLECT_ODDS = 5; +constexpr float BALL_MARK_DAMAGE_SCALE = 2; +constexpr float BALL_MARK_DAMAGE_BONUS = 3; +constexpr float BALL_SPLAT_SPEED_MIN = 2; +constexpr float BALL_SPLAT_SPEED_SPAN = 2; +constexpr int BALL_SPLAT_SUBTYPE = 2; +constexpr int BALL_SPLAT_PRIORITY = 255; +constexpr float BALL_SPLAT_VOLUME = 0.7f; +constexpr int BALL_SPLAT_DELAY = 8; +constexpr int BALL_HIT_COUNTDOWN = 30; +constexpr ColorMod BALL_SPLAT_TINT = color_make({2, 1, 1, 1}); + +// The brimstone ball part of 005cdb20 (Init): it appears. +static void brimstone_ball_init(Entity_Effect& ball) +{ + ball.sprite.Play("Appear"); +} + +// The homing ball picks a target among the enemies near where it heads (a coin flip each, on its period), or turns +// half a step toward the one it has, keeping its speed. +static void brimstone_ball_home(Entity_Effect& ball) +{ + if (ball.target) + { + Vector turned = vector_add(ball.velocity, vector_scale(vector_normalized(vector_sub(ball.target->pos, ball.pos)), BALL_HOMING_TURN)); + ball.velocity = vector_resized(turned, vector_length(ball.velocity)); + return; + } + for (Entity* enemy : g_game->room->entityList.updateEL) + { + if (!enemy->IsVulnerableEnemy(nullptr) || enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) continue; + Vector gap = vector_sub(vector_add(ball.pos, vector_scale(ball.velocity, BALL_HOMING_LOOKAHEAD)), enemy->pos); + if (random_below(2) && ball.IsFrame(BALL_HOMING_PERIOD, ball.index) && + vector_length_squared(gap) < BALL_HOMING_RANGE * BALL_HOMING_RANGE) + ball.target = enemy; + } +} + +// Splatters a Brimstone-marked enemy under the ball once: a blood splash flying out from the ball's edge in its color. +static void brimstone_ball_splatter(Entity_Effect& ball, Entity& enemy) +{ + ColorMod tint = BALL_SPLAT_TINT; + color_multiply(tint, ball.sprite.color); + Vector edge = vector_sub(enemy.pos, ball.pos); + if (vector_length_squared(edge) > ball.size) edge = vector_resized(edge, ball.size); + uint32_t seed = Random(); + Vector velocity = vector_scale(vector_normalized(edge), random_unit() * BALL_SPLAT_SPEED_SPAN + BALL_SPLAT_SPEED_MIN); + auto* splat = static_cast(g_game->Spawn({.position = vector_add(ball.pos, edge), + .velocity = vector_add(velocity, random_direction()), + .subType = BALL_SPLAT_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = seed})); + splat->SetColor(tint, -1, BALL_SPLAT_PRIORITY, false, true); + splat->posOffset = ball.posOffset; + splat->rotation = random_unit() * DEGREES_PER_TURN; + splat->Update(); + effect_sound_play(SOUND_MEATY_DEATHS, {.volume = BALL_SPLAT_VOLUME, .frameDelay = BALL_SPLAT_DELAY}); + enemy.AddEntityFlags(FLAG_EXTRA_GORE); +} + +// Every other frame the ball hurts the rocks in its reach and what it touches. +static void brimstone_ball_hits_update(Entity_Effect& ball, Entity_Player* player) +{ + Room& room = *g_game->room; + bool isShielded = effect_tear_flags(ball)[TEAR_SHIELDED]; + for (int index = 0; index < room.GetGridSize(); index++) + { + GridEntity* grid = room.GetGridEntity(index); + if (!grid || vector_length(vector_sub(ball.pos, room.GetGridPosition(index))) >= ball.size + BALL_ROCK_REACH) continue; + grid->Hurt(1, ball.spawnerEntity ? EntityRef(ball.spawnerEntity) : EntityRef()); + } + + for (Entity* entity : entity_query_radius(ball.pos, ball.size, QUERY_ALL)) + { + if (is_critter_eaten(*entity)) continue; + if (isShielded && entity->IsProjectile()) + { + auto& shot = static_cast(*entity); + if (!(shot.projectileFlags & PROJECTILE_CANT_HIT_PLAYER) && random_below(BALL_DEFLECT_ODDS) == 0) + { + shot.projectileFlags = 0; + shot.isDead = true; + continue; + } + } + if (!is_laser_target(*entity)) continue; + + float damage = ball.collisionDamage; + uint64_t damageFlags = laser_effects_apply(ball, *entity, player); + if (entity->HasEntityFlags(FLAG_BRIMSTONE_MARKED)) + { + brimstone_ball_splatter(ball, *entity); + damage = damage * BALL_MARK_DAMAGE_SCALE + BALL_MARK_DAMAGE_BONUS; + } + entity->TakeDamage(damage, damageFlags, EntityRef(ball.parent), BALL_HIT_COUNTDOWN); + } +} + +// 0060300b (Update's case 113) Remembers its damage and size, idles (or disappears and goes), then follows its +// flags, sizes itself, slows while it moves and hits on its period. +static void brimstone_ball_update(Entity_Effect& ball) +{ + TearFlags flags = effect_tear_flags(ball); + float radius = ball.config->collisionRadius; + if (ball.state == 0) + { + ball.state = 1; + ball.baseDamage = ball.collisionDamage; + ball.baseScale = ball.size / radius; + if (flags[TEAR_SHRINK]) ball.baseScale *= BALL_SHRINK_SCALE; + } + if (ball.isDead) + { + ball.sprite.Play("Disappear"); + ball.sprite.color._tint[3] *= BALL_FADE; + if (ball.sprite.IsFinished()) ball.Remove(); + } + else if (ball.sprite.IsFinished()) ball.sprite.Play("Idle"); + + Entity_Player* player = effect_player_get(ball); + if (flags[TEAR_ATTRACTOR]) + entities_attract({.position = ball.pos, .radius = RIFT_ATTRACT_RADIUS, .strength = RIFT_ATTRACT_STRENGTH}); + if (flags[TEAR_OCCULT] && player) + { + Vector aim = player->GetShootingJoystick(); + player->GetMouseAimTarget(aim, false); + if (!vector_is_zero(aim)) + ball.velocity = vector_add(ball.velocity, vector_scale(vector_normalized(aim), player->shotSpeed * BALL_OCCULT_SPEED)); + ball.friction = BALL_OCCULT_FRICTION; + } + if (flags[TEAR_HOMING]) brimstone_ball_home(ball); + if (flags[TEAR_GROW]) + { + ball.collisionDamage += BALL_GROW_DAMAGE; + ball.baseScale += BALL_GROW_SCALE; + } + if (flags[TEAR_SHRINK]) + { + ball.baseScale = std::max(ball.baseScale - BALL_SHRINK_STEP, BALL_SMALLEST); + ball.collisionDamage = std::max(ball.collisionDamage - BALL_SHRINK_DAMAGE, BALL_SMALLEST); + if (ball.baseScale == BALL_SMALLEST) ball.isDead = true; + } + + ball.size = radius * ball.baseScale; + ball.sprite.scale = vector_make(ball.baseScale, ball.baseScale); + if (vector_length(ball.velocity) > 1) ball.friction *= BALL_MOVING_DRAG; + if (ball.IsFrame(BALL_HIT_PERIOD, 0)) brimstone_ball_hits_update(ball, player); +} + +constexpr auto VORTEX_BEHAVIOURS = std::to_array({ + {EFFECT_BLACK_HOLE, black_hole_init, effect_finishing, nullptr}, + {EFFECT_BRIMSTONE_BALL, brimstone_ball_init, effect_finishing, nullptr}, + {EFFECT_RIFT, rift_init, effect_finishing, nullptr}, +}); + +std::span vortex_effect_behaviours() +{ + return VORTEX_BEHAVIOURS; +} diff --git a/src/entity_factory.cpp b/src/entity_factory.cpp index b761bf6..ed1202e 100644 --- a/src/entity_factory.cpp +++ b/src/entity_factory.cpp @@ -1,4 +1,5 @@ #include "entity_factory.h" +#include "boss_pool.h" #include "entity_bomb.h" #include "entity_effect.h" #include "entity_familiar.h" @@ -14,8 +15,10 @@ #include "game.h" #include "grid_entity.h" #include "grid_entity_poop.h" +#include "level.h" #include "lua_engine.h" #include "manager.h" +#include "persistent_game_data.h" #include "platform.h" #include "room.h" #include @@ -37,7 +40,6 @@ constexpr int ENTITY_GREED_GAPER = 299; constexpr int ENTITY_MUSHROOM = 300; constexpr int ENTITY_SUB_HORF = 812; constexpr int EFFECT_CRAWLSPACE_LADDER = 192; -constexpr int BOSS_SATAN = 24; constexpr int CARD_SPECIAL_CHANCE = 25; constexpr int CARD_RUNE_CHANCE = 10; @@ -123,14 +125,12 @@ enum EntryAchievement : int ACHIEVEMENT_HEART_BONE = 391, ACHIEVEMENT_HEART_ROTTEN = 411, ACHIEVEMENT_TAINTED_CLOSET = 434, - ACHIEVEMENT_WOODEN_CHEST = 601, + ACHIEVEMENT_MEGA_CHEST = 601, ACHIEVEMENT_GRAB_BAG_BLACK = 604, ACHIEVEMENT_POOP_CHARMING = 605, ACHIEVEMENT_CRANE_GAME = 607, ACHIEVEMENT_HELL_GAME = 608, - ACHIEVEMENT_MIMIC_CHEST = 609, - ACHIEVEMENT_HAUNTED_CHEST = 611, - ACHIEVEMENT_ROCK_VARIANTS = 612, + ACHIEVEMENT_ROCK_VARIANTS = 612, ACHIEVEMENT_COIN_GOLDEN = 613, ACHIEVEMENT_ROTTEN_BEGGAR = 614, ACHIEVEMENT_LIL_BATTERY_GOLDEN = 615, @@ -157,7 +157,6 @@ constexpr float ELLIPSE_SPREAD_X = 1.25f; constexpr float ELLIPSE_SPREAD_Y = 0.3f; constexpr float ELLIPSE_MINES_SPREAD_X = 1.8f; constexpr float ELLIPSE_MINES_SPREAD_Y = 0.5f; -constexpr float FULL_TURN = 360; // The odds layouts roll with (one in n). constexpr int ROCK_ROLLS = 1001; @@ -177,7 +176,6 @@ constexpr int SHOPKEEPER_ODDS_MASK = 3; constexpr int PIT_MARKED_VARIANT = 128; constexpr int ROCK_MARKED_VARIANT = 10000; constexpr int TELEPORTER_STATE_ACTIVE = 2; -constexpr int MIRROR_DIMENSION = 1; constexpr int TREASURE_SUBTYPE_MIRROR = 34; constexpr int BOSS_SUBTYPE_MOTHER = 88; constexpr int TREASURE_SUBTYPE_CHOICE = 1; @@ -473,9 +471,9 @@ constexpr std::array LOCKED_ENTRIES = {{ {ENTITY_PICKUP, PICKUP_KEY, 4, ACHIEVEMENT_KEY_CHARGED, -1, 0}, {ENTITY_PICKUP, PICKUP_GRAB_BAG, 2, ACHIEVEMENT_GRAB_BAG_BLACK, -1, 0}, {ENTITY_PICKUP, PICKUP_LIL_BATTERY, 4, ACHIEVEMENT_LIL_BATTERY_GOLDEN, -1, 0}, - {ENTITY_PICKUP, PICKUP_WOODENCHEST, -1, ACHIEVEMENT_MIMIC_CHEST, PICKUP_CHEST, -1}, + {ENTITY_PICKUP, PICKUP_WOODENCHEST, -1, ACHIEVEMENT_WOODEN_CHEST, PICKUP_CHEST, -1}, {ENTITY_PICKUP, PICKUP_HAUNTEDCHEST, -1, ACHIEVEMENT_HAUNTED_CHEST, PICKUP_CHEST, -1}, - {ENTITY_PICKUP, PICKUP_MEGACHEST, -1, ACHIEVEMENT_WOODEN_CHEST, PICKUP_LOCKEDCHEST, -1}, + {ENTITY_PICKUP, PICKUP_MEGACHEST, -1, ACHIEVEMENT_MEGA_CHEST, PICKUP_LOCKEDCHEST, -1}, {ENTITY_SLOT, SLOT_HELL_GAME, -1, ACHIEVEMENT_HELL_GAME, SLOT_DEVIL_BEGGAR, -1}, {ENTITY_SLOT, SLOT_ROTTEN_BEGGAR, -1, ACHIEVEMENT_ROTTEN_BEGGAR, SLOT_KEY_MASTER, -1}, {ENTITY_SLOT, SLOT_CRANE_GAME, -1, ACHIEVEMENT_CRANE_GAME, SLOT_MACHINE, -1}, @@ -814,7 +812,7 @@ static bool rock_ellipse_contains(Room& room, int gridIndex) float spreadY = isMines ? ELLIPSE_MINES_SPREAD_Y : ELLIPSE_SPREAD_Y; float radiusY = (rng.RandomFloat() + rng.RandomFloat()) * spreadY + ELLIPSE_RADIUS_Y; float radiusX = (rng.RandomFloat() + rng.RandomFloat()) * spreadX + ELLIPSE_RADIUS_X; - float angle = -(rng.RandomFloat() * FULL_TURN) * DEGREES_TO_RADIANS; + float angle = -(rng.RandomFloat() * FULL_TURN_DEGREES) * DEGREES_TO_RADIANS; float cosine = (float)std::cos((double)angle); float sine = (float)std::sin((double)angle); @@ -1053,7 +1051,7 @@ bool room_entry_spawn(Room& room, RoomEntry entry, const RoomEntrySpawn& spawn) bool isPickup = entry.type == ENTITY_PICKUP; if (game.currentRoomIdx == ROOM_GENESIS_IDX && isPickup && entry.variant == PICKUP_COLLECTIBLE) return false; RoomConfig_Room* data = room.descriptor->data; - if (game.HasMirrorDimension() && spawn.mode == ENTRY_SPAWN && game.currentDimensionIdx == MIRROR_DIMENSION && + if (game.HasMirrorDimension() && spawn.mode == ENTRY_SPAWN && game.currentDimensionIdx == DIMENSION_MIRROR && isPickup && !(data->type == ROOM_TREASURE && data->subtype == TREASURE_SUBTYPE_MIRROR)) return false; @@ -1091,7 +1089,7 @@ bool room_entry_spawn(Room& room, RoomEntry entry, const RoomEntrySpawn& spawn) game.currentRoomIdx != ROOM_GENESIS_IDX && !(room.roomType == ROOM_BOSS && data->subtype == BOSS_SUBTYPE_MOTHER); if (!game.IsNextStageAvailable() && isDeadEnd) replace(ENTRY_COBWEB); - else if (game.HasMirrorDimension() && game.currentDimensionIdx == MIRROR_DIMENSION) replace(0); + else if (game.HasMirrorDimension() && game.currentDimensionIdx == DIMENSION_MIRROR) replace(0); } if (entry.type == ENTITY_SHOPKEEPER) { diff --git a/src/entity_familiar.cpp b/src/entity_familiar.cpp index fecc55b..1abcef5 100644 --- a/src/entity_familiar.cpp +++ b/src/entity_familiar.cpp @@ -8,6 +8,8 @@ #include "familiar_gello.h" #include "familiar_variants.h" #include "game_state_player.h" +#include "entity_tear.h" +#include "item_config.h" #include "log.h" #include "lua_engine.h" #include "manager.h" @@ -37,8 +39,7 @@ constexpr std::pair ORBIT_LAYERS[] = { {121, 5}, {128, 5}, {84, 4}, {123, 4}, {204, 6}, {216, 6}, {217, 6}, {229, 10}, {237, 8}}; // The familiars whose setup, drawing and links wait for their takeovers. -constexpr int UNWRITTEN_INIT_VARIANTS[] = {62, 122, 228, 231, 233, 236, 238}; -constexpr int UNWRITTEN_RENDER_VARIANTS[] = {231}; +constexpr int UNWRITTEN_INIT_VARIANTS[] = {62, 122, 228, 233, 236, 238}; // The familiars that walk, Init's grid collision for them, and the ones whose hit list survives the reset. constexpr int GROUND_VARIANTS[] = {46, 47, 71, 72, 48, 56, 73}; @@ -409,7 +410,8 @@ void Entity_Familiar::Init(int initType, int initVariant, int initSubtype, uint3 if (familiar_versus()) reconstruction_missing("Entity_Familiar::Init 0060de70 (a versus match's familiar)"); if (variant == BUM_FRIEND || variant == DARK_BUM || variant == KEY_BUM || variant == SUPER_BUM) sprite.Play("FloatDown"); - if (variant == SAMSONS_CHAINS) entityCollisionClass = ENTCOLL_ALL; + if (variant == ISAACS_HEART) player->isaacsHeart = this; + if (variant == ISAACS_HEART || variant == SAMSONS_CHAINS) entityCollisionClass = ENTCOLL_ALL; if (player->temporaryEffects.HasNullEffect(NULLITEM_SPIN_TO_WIN_EFFECT)) { flags |= FLAG_SPIN; @@ -445,6 +447,7 @@ void Entity_Familiar::variant_init(int initSubtype) switch (variant) { case FORGOTTEN_BODY: forgotten_body_init(*this); break; + case ABYSS_LOCUST: locust_init(*this); break; case ISAACS_BODY: if (player) isaacs_body_init(*this); break; @@ -555,8 +558,8 @@ void Entity_Familiar::Update() { if (variant != FORGOTTEN_BODY) { - if (variant == ABYSS_LOCUST) reconstruction_missing("Entity_Familiar::Update 0061da10 (a locust's size)"); - sprite.scale = vector_make(1, 1); + float scale = variant == ABYSS_LOCUST ? locust_scale_get(*this) : 1; + sprite.scale = vector_make(scale, scale); } if (g_game->frameCount - spawnFrame < 2) @@ -928,6 +931,13 @@ void Entity_Familiar::variant_update() return cube_baby_update(*this); case BLOOD_PUPPY: return blood_puppy_update(*this); + case INTRUDER: return intruder_update(*this); + case ABYSS_LOCUST: return locust_update(*this); + case TINYTOMA: + case TINYTOMA_2: return tinytoma_update(*this); + case BOT_FLY: return bot_fly_update(*this); + case LIL_DUMPY: return lil_dumpy_update(*this); + case BOILED_BABY: return boiled_baby_update(*this); case FRUITY_PLUM: return fruity_plum_update(*this); default: reconstruction_missing("Entity_Familiar::Update 0061da10 (this familiar's behaviour)"); @@ -1019,8 +1029,8 @@ void Entity_Familiar::Interpolate() } // 00624e10 Draws a familiar with its charge bar. Isaac's body draws its parts, a detached head its player's head, Gello -// its cord first, Samson's Chains and Gemini hang their links, and an item wisp shows its item's icon. The familiars -// drawn their own way (the locusts, the co-op babies) and Tainted Lazarus's hologram stop the game. +// its cord first, Samson's Chains and Gemini hang their links, a locust its shot sprites and an item wisp its item's +// icon. Tainted Lazarus's hologram stops the game. void Entity_Familiar::Render(const Vector& offset) { if (IsLilithBirthrightIncubus()) @@ -1030,13 +1040,12 @@ void Entity_Familiar::Render(const Vector& offset) } if (player && player->IsHologram()) return reconstruction_missing("Entity_Familiar::Render 00624e10 (Tainted Lazarus's hologram)"); - if (familiar_listed(UNWRITTEN_RENDER_VARIANTS, variant)) - return reconstruction_missing("Entity_Familiar::Render 00624e10 (this familiar's drawing)"); if (variant == SAMSONS_CHAINS) samsons_chains_links_place(*this); else if (variant == GEMINI) gemini_cord_place(*this); ColorMod saved = sprite.color; if (variant == UMBILICAL_BABY) umbilical_baby_render(*this, offset); + else if (variant == ABYSS_LOCUST) locust_render(*this, offset); else if (variant == GUILLOTINE || variant == SCISSORS || variant == DECAP_ATTACK) detached_head_render(*this, offset); else if (variant != ISAACS_BODY || !isaacs_body_render(*this, offset)) Entity::Render(offset); @@ -1217,8 +1226,7 @@ bool Entity_Familiar::CanBlockProjectiles() case BIG_CHUBBY: case LIL_PORTAL: return fireCooldown < 0; case WISP: return subtype != WISP_UNBLOCKING; - case ABYSS_LOCUST: - reconstruction_missing("Entity_Familiar::CanBlockProjectiles 0060d8e0 (a locust's shield)"); + case ABYSS_LOCUST: return familiar_locust_config(*this).effects[0].tearFlags[TEAR_SHIELDED]; return false; default: return familiar_listed(BLOCKING_VARIANTS, variant); } @@ -1250,8 +1258,6 @@ bool Entity_Familiar::TryThrow(const EntityRef&, const Vector& direction, float // (a wisp's orbit layer in place of its clears, Blood Puppy's health, the Star of Bethlehem's speed). void Entity_Familiar::store_backup(FamiliarData* backup) { - if (variant == ABYSS_LOCUST) reconstruction_missing("Entity_Familiar::store_backup 00630450 (a locust)"); - backup->initSeed = initSeed; backup->dropSeed = dropRNG._seed; backup->variant = variant; @@ -1267,6 +1273,7 @@ void Entity_Familiar::store_backup(FamiliarData* backup) if (variant == STAR_OF_BETHLEHEM) backup->health = orbitSpeed; backup->isNotCountedAsFollower = isNotCountedAsFollower; backup->isSubtype55555 = isSubtype55555; + if (variant == ABYSS_LOCUST) backup->roomClearCount = static_cast(*extraData).hunger; } // 00630560 Takes back what store_backup kept: drop seed, counters, formation spot and health, then what the variant @@ -1315,7 +1322,13 @@ void Entity_Familiar::RestoreState(const FamiliarData& saved) health = config->baseHP; orbitSpeed = saved.health; } - if (variant == ABYSS_LOCUST) reconstruction_missing("Entity_Familiar::RestoreState 00630560 (a locust)"); + if (variant == ABYSS_LOCUST) + { + set_locust_config_index(coins); + item = g_manager->itemConfig.GetCollectible(subtype); + static_cast(*extraData).hunger = saved.roomClearCount; + load_config_graphics(); + } Update(); } diff --git a/src/entity_familiar.h b/src/entity_familiar.h index 237be46..81ac4a1 100644 --- a/src/entity_familiar.h +++ b/src/entity_familiar.h @@ -9,6 +9,7 @@ #include #include #include +#include #include struct FamiliarData; @@ -135,6 +136,7 @@ struct Entity_Familiar : Entity ISAACS_HEART = 62, LIL_HAUNT = 63, DARK_BUM = 64, + BIG_FAN = 65, SISSY_LONGLEGS = 66, PUNCHING_BAG = 67, GUILLOTINE = 68, @@ -327,7 +329,7 @@ struct Entity_Familiar : Entity bool wisp_kill(); void wisp_death(const EntityRef& source); Entity_Tear* fire_wisp_projectile(Vector velocity); - bool wisp_take_damage(const EntityRef& source, uint64_t damageFlags); + bool wisp_take_damage(float& damage, uint64_t damageFlags, const EntityRef& source); void ai_wisp(); void ai_mr_me_wisp(); void ai_mega_blast_wisp(); @@ -338,7 +340,7 @@ struct Entity_Familiar : Entity float GetMultiplier(); int overwrite_limit(); int hit_list_interval(); - void set_locust_config_index(int); + void set_locust_config_index(int index); Entity* get_orbit_parent(); void RecalculateOrbitOffset(int layer, OrbitChange change); void AddToOrbit(int layer); @@ -427,18 +429,15 @@ struct Entity_Familiar : Entity static void minisaac_find_target(); void ai_blood_oath(); void paschal_candle_sync_effects(); - void ai_boiled_baby(); void zhl_misfit_006414c0(); void ai_bird_cage(); - void ai_bot_fly(); void ai_stitches(); Entity* aim_reflected_projectile(); void ai_shadow_intruder_damocles(bool isInterpolating); - void* get_item_config_entry(); - uint8_t abyss_locust_eat(); - uint8_t break_grid_ahead(); + bool abyss_locust_eat(); + bool break_grid_ahead(); void load_config_graphics(); - void render_abyss_locust_sprite(ANM2*, float*); + void render_abyss_locust_sprite(ANM2& shot, const Vector& offset); void siren_charm(Entity* siren, Entity_Player* player); void RemoveFromPlayer(); void UpdateDirtColor(); @@ -468,6 +467,23 @@ struct IsaacsBodyData : Entity_Familiar::ExtraData std::array partLayers{-1, -1, -1, -1}; }; +// Destruction (0060d5e0) is the default. +// An Abyss locust's extra data: the flags it flies with (its first effect's and those that proced at launch), the shot +// sprites drawn behind and in front of it, the shots it already tried to block, the enemies its devolving made, the +// grid cell it last broke, Mom's Knife's blade and the pickups it ate. +struct AbyssLocustData : Entity_Familiar::ExtraData +{ + TearFlags tearFlags; + std::vector backSprites; + std::vector frontSprites; + std::set checkedShots; + std::vector devolvedHitList; + EntityPtr knife; + uint32_t locustFlags = 0; + int lastGridIndex = 0; + int hunger = 0; +}; + // How many of a familiar a player should have (Entity_Player::CheckFamiliar's arguments): the item behind them and the // generator their spawns draw from, a subtype of -1 counting every subtype. struct FamiliarCount @@ -521,8 +537,29 @@ void sissy_longlegs_update(Entity_Familiar& sissy); void punching_bag_update(Entity_Familiar& bag); void censer_update(Entity_Familiar& censer); +// The Repentance familiars written as their own functions (familiar_repentance.cpp). +void intruder_update(Entity_Familiar& intruder); +void intruder_player_hurt(Entity_Familiar& intruder, const DamageEvent& hit); +void boiled_baby_update(Entity_Familiar& baby); +void tinytoma_update(Entity_Familiar& tinytoma); +bool tinytoma_touch(Entity_Familiar& tinytoma, Entity& enemy, float damageMultiplier); +bool tinytoma_death(Entity_Familiar& tinytoma); +void bot_fly_update(Entity_Familiar& fly); +void lil_dumpy_update(Entity_Familiar& dumpy); + +// The Abyss locusts (familiar_locust.cpp). +struct LocustConfig; +LocustConfig& familiar_locust_config(Entity_Familiar& familiar); +void anm2_gfx_overrides_apply(std::string_view gfx, std::string_view color, ANM2& sprite); +void locust_init(Entity_Familiar& locust); +float locust_scale_get(Entity_Familiar& locust); +void locust_update(Entity_Familiar& locust); +void locust_render(Entity_Familiar& locust, const Vector& offset); +void locust_touch(Entity_Familiar& locust, Entity& enemy); +bool locust_block(Entity_Familiar& locust, Entity& shot, bool isIgnored); + // The wisps' shared parts of the familiar's animations, hits, touches and death (familiar_wisp.cpp). -void wisp_anim_play(Entity_Familiar& wisp, std::string_view name); +void wisp_anim_play(Entity_Familiar& wisp, std::string_view name, AnimationSwitch mode = SWITCH_KEEP_FRAME); int wisp_hit_countdown(int damageCountdown); void wisp_countdown_share(Entity_Familiar& hurt); bool wisp_touch(Entity_Familiar& wisp, Entity& enemy); diff --git a/src/entity_knife.cpp b/src/entity_knife.cpp index ab06fb2..124bb39 100644 --- a/src/entity_knife.cpp +++ b/src/entity_knife.cpp @@ -18,6 +18,7 @@ #include "room_grid.h" #include "sfx_manager.h" #include "weapon.h" +#include #include #include @@ -186,6 +187,13 @@ constexpr std::array MULTIDIMENSIONAL_COLORS = {{ }}; constexpr int MULTIDIMENSIONAL_FRAMES = 2; +// Strange Attractor on a knife pulls within 250: a held item hard, a thrown knife harder the further it flew (up to +// 30 times at 100 out), else gently. +constexpr float KNIFE_ATTRACT_RADIUS = 250; +constexpr float KNIFE_ATTRACT_HELD_ITEM = 20; +constexpr float KNIFE_ATTRACT_FULL_DISTANCE = 100; +constexpr float KNIFE_ATTRACT_THROWN_RANGE = 29; + // The sword's idle animations by facing, plain and charged. constexpr std::array SWORD_IDLE_ANIMATIONS = {"IdleLeft", "IdleUp", "IdleRight", "IdleDown"}; constexpr std::array SWORD_CHARGED_ANIMATIONS = {"ChargedLeft", "ChargedUp", "ChargedRight", @@ -893,7 +901,13 @@ void Entity_Knife::Update() sprite.color = flicker; } if (tearFlags[TEAR_ATTRACTOR] && !isInterpolating) - reconstruction_missing("Entity_Knife::Update 00961b00 (Strange Attractor, Game::AttractEntities 00705b90)"); + { + float reach = std::clamp(knifeDistance / KNIFE_ATTRACT_FULL_DISTANCE, 0.0f, 1.0f); + float strength = subtype == KNIFE_SUBTYPE_HELD_ITEM ? KNIFE_ATTRACT_HELD_ITEM + : isFlying ? reach * KNIFE_ATTRACT_THROWN_RANGE + 1 + : 1; + entities_attract({.position = pos, .radius = KNIFE_ATTRACT_RADIUS, .strength = strength}); + } KnifeKind kind = knife_kind(variant); if (kind != KNIFE_KIND_THROWN && isFlying && config) size = config->collisionRadius * sprite.scale.x; diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index 1e538b1..e697bcf 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -42,8 +42,24 @@ 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_DEATH_SPARK_TYPE = 882; constexpr int ENTITY_DAMAGE_NUMBERS_TYPE = 964; + +// 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 GFUEL_EXPLOSION_ANM2S = {"gfx/promo/gfuel/effects/explosion.anm2", + "gfx/promo/gfuel/effects/explosion2.anm2"}; +constexpr float GFUEL_BLAST_PITCH = 0.9f; +constexpr float GFUEL_BLAST_PITCH_RANGE = 0.2f; +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 APPEAR_EVENT_TYPES = {404, 912, 913, 917}; @@ -118,8 +134,6 @@ struct LineCorner float y; }; constexpr std::array LINE_CORNERS = {{{-5, -5}, {-5, 5}, {5, 5}, {5, -5}}}; -constexpr int GRID_PATH_PIT = 3000; -constexpr uint32_t GRID_PATH_BAND = 1000; constexpr float SHIELD_SECOND = 30; constexpr float SHIELD_BASE = 0.09f; constexpr float SHIELD_FALLOFF = 0.18f; @@ -162,7 +176,6 @@ enum DeathBurst : int EFFECT_BURST_818 = 145 }; -constexpr int ENTITY_SIREN_HELPER = 966; constexpr int ENTITY_SHADOW_CHARGER = 23; constexpr int ENTITY_ULTRA_GREED_DOOR = 889; constexpr int SUCKER_VARIANT_BULB = 5; @@ -199,7 +212,6 @@ constexpr int ACHIEVEMENT_REDIRECTS = 348; constexpr uint32_t ROOM_CONFIG_FLAG_NO_CHAMPIONS = 1 << 2; constexpr int GRID_CELL = 40; constexpr float GRID_TOP = 120; -constexpr float HALF = 0.5f; constexpr int SHIELD_FRAMES_DEFAULT = 120; constexpr uint32_t DEBUG_QUICK_KILL = 1 << 9; constexpr int BOSS_ID_NONE_EXCLUDED_FIRST = 46; @@ -1986,12 +1998,46 @@ void Entity_NPC::ResetColor() 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. +// sprite's middle, or a G-Fuel explosion. The Dust also flashes. void Entity_NPC::PlayDeathEffects() { if (g_game->playerManager.GetGFuelCount() > 0) - reconstruction_missing("Entity_NPC::PlayDeathEffects 006d4e00: G-Fuel's explosion"); + { + gfuel_explosion_spawn(pos, 1); + return; + } Vector offset{}; const AnimationFrame* frame = sprite.animState.animData && (type != ENTITY_SCOURGE || variant != 10) @@ -2016,8 +2062,7 @@ void Entity_NPC::PlayDeathEffects() 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_DEATH_SPARK_TYPE) - reconstruction_missing("Entity_NPC::PlayDeathEffects 006d4e00: the electric enemy's sparks"); + 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 @@ -2216,7 +2261,6 @@ 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 DIAGONAL = 0.70710677f; constexpr float PROJECTILE_DEFAULT_FALL_SPEED = -3; constexpr float PROJECTILE_DEFAULT_FALL_ACCEL = 0.1f; constexpr float PROJECTILE_HEIGHT_LOW = -50; @@ -2603,7 +2647,7 @@ void Entity_NPC::trigger_kill_item_effects() kill_items_trigger(); g_game->room->isFirstEnemyDead = true; - // Room::record_killed_npc 00820d30 waits for Room to hold the list of killed enemies, which nothing reads yet. + room_killed_npc_record(*g_game->room, *this); entityRef = nullptr; aimTargetEffect = nullptr; if (HasEntityFlags(FLAG_BRIMSTONE_MARKED) && HasEntityFlags(FLAG_EXTRA_GORE)) marked_status_spread(); @@ -2873,10 +2917,15 @@ bool Entity_NPC::CanReroll() return !IsBoss() && !config->isBoss; } -// 006d88b0 -void Entity_NPC::TransferControl(Entity_NPC*) +// 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) { - reconstruction_missing("Entity_NPC::TransferControl 006d88b0"); + 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 The aim target a controlled NPC steers. Without a controller and none shown yet, there is nothing to do. diff --git a/src/entity_npc.h b/src/entity_npc.h index 0b07654..7469453 100644 --- a/src/entity_npc.h +++ b/src/entity_npc.h @@ -406,6 +406,7 @@ Entity* game_nearest_target_player(const Vector& position, Entity* source, bool float maxDistance); void game_shake_screen(int timeout); Entity* spawn_at(int type, int variant, int subType, const Vector& position, Entity* spawner); +Entity* gfuel_explosion_spawn(const Vector& position, float scale); int poof_size_get(Entity& entity, bool isHugeAllowed); void game_encountered_boss_add(int bossType, int bossVariant); bool game_is_hard_mode(); diff --git a/src/entity_npc_render.cpp b/src/entity_npc_render.cpp index 4620e7c..cd78541 100644 --- a/src/entity_npc_render.cpp +++ b/src/entity_npc_render.cpp @@ -329,8 +329,7 @@ static void health_bar_render(Entity_NPC& npc, const Vector& position) KColor white = kcolor_rgba(1, 1, 1, 1); KAGE::Graphics::manager.blend_set(KAGE::Graphics::BLEND_NORMAL); - bool isAltStage = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; - float stage = (float)(game.stage + (isAltStage ? 1 : 0)); + float stage = (float)game.stage_depth_get(); float toughness = npc.maxHitPoints / (stage + stage + HEALTH_BAR_STAGE_BASE); float width = std::floor((std::log10(toughness) + 1) * HEALTH_BAR_WIDTH_PER_DECADE + 0.5f); width = std::clamp(width, HEALTH_BAR_WIDTH_MIN, HEALTH_BAR_WIDTH_MAX); diff --git a/src/entity_npc_rewards.cpp b/src/entity_npc_rewards.cpp index 7056a89..da2923d 100644 --- a/src/entity_npc_rewards.cpp +++ b/src/entity_npc_rewards.cpp @@ -100,14 +100,6 @@ constexpr int KEEPER_REVISIT_LIMIT = 9; constexpr float KEEPER_BOSS_HEALTH_BASE = 38; constexpr float KEEPER_BOSS_HEALTH_STEP = 10; -// The floor a boss's coins count by: one more on an alt floor. -static int reward_stage_get() -{ - Game& game = *g_game; - bool isAlt = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; - return (int)game.stage + (isAlt ? 1 : 0); -} - // A pickup thrown out of the dead enemy in a random direction at two to five, gone after a while. static void reward_pickup_throw(Entity_NPC& npc, const EntitySpawn& spawn, int timeout) { @@ -277,7 +269,7 @@ static void vasculitis_tears_fire(Entity_NPC& npc) static void vade_retro_ghost_spawn(Entity_NPC& npc) { float scale = random_unit() * VADE_RETRO_SCALE_RANGE + VADE_RETRO_SCALE_MIN; - float damage = (float)reward_stage_get() * VADE_RETRO_DAMAGE_STEP + VADE_RETRO_DAMAGE_BASE + + float damage = (float)g_game->stage_depth_get() * VADE_RETRO_DAMAGE_STEP + VADE_RETRO_DAMAGE_BASE + npc.maxHitPoints * VADE_RETRO_HEALTH_SHARE; if (npc.IsBoss()) scale *= VADE_RETRO_BOSS_SCALE; else if (npc.isChampion) scale *= VADE_RETRO_CHAMPION_SCALE; @@ -344,7 +336,7 @@ static void urn_souls_spawn(Entity_NPC& npc) int count = npc.championColorIdx >= 0 ? 2 : 1; if (npc.IsBoss()) { - float health = (float)reward_stage_get() * KEEPER_BOSS_HEALTH_STEP + KEEPER_BOSS_HEALTH_BASE; + float health = (float)g_game->stage_depth_get() * KEEPER_BOSS_HEALTH_STEP + KEEPER_BOSS_HEALTH_BASE; count = std::min((int)std::ceil(npc.maxHitPoints / health), URN_BOSS_SOULS); } for (int i = 0; i < count; i++) @@ -551,7 +543,7 @@ static void keeper_coins_drop(Entity_NPC& npc) int count = npc.championColorIdx >= 0 ? 2 : 1; if (npc.IsBoss()) { - float health = (float)reward_stage_get() * KEEPER_BOSS_HEALTH_STEP + KEEPER_BOSS_HEALTH_BASE; + float health = (float)g_game->stage_depth_get() * KEEPER_BOSS_HEALTH_STEP + KEEPER_BOSS_HEALTH_BASE; count = std::max(1, (int)std::ceil(npc.maxHitPoints / health)); timeout = BOSS_COIN_TIMEOUT; } diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index 23de8d3..164ef73 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -7,14 +7,17 @@ #include "entity_player_trinkets.h" #include "game.h" #include "grid_entity.h" +#include "level.h" #include "log.h" #include "lua_engine.h" #include "manager.h" #include "menu_options.h" +#include "persistent_game_data.h" #include "platform.h" #include "room.h" #include "room_grid.h" #include "room_render.h" +#include "seeds.h" #include #include #include @@ -63,6 +66,15 @@ constexpr int TRINKET_APPLE_OF_SODOM = 140; constexpr int TRINKET_NUH_UH = 165; constexpr int COLLECTIBLE_MITRE = 173; constexpr int SPECIAL_DAILY_NICKELS = 7; + +// A bed of subtype 10 is held like the ending pickups, a while untouchable. The barren room's bed is torn, and Pay To +// Play's chests show a coin slot. +constexpr int BED_HELD_SUBTYPE = 10; +constexpr int BED_HELD_COOLDOWN = 10; +constexpr const char* BED_BARREN_SHEET = "gfx/Items/Pick Ups/IsaacBed_Barren.png"; +constexpr const char* CHEST_COIN_SLOT_SHEET = "gfx/Items/Pick Ups/Pickup_005_Chests_coinslot.png"; +constexpr const char* OLD_CHEST_COIN_SLOT_SHEET = "gfx/Items/Pick Ups/dirty_chest_coinslot.png"; +constexpr const char* MEGA_CHEST_COIN_SLOT_SHEET = "gfx/Items/Pick Ups/mega_chest_coinslot.png"; // Achievement 33 unlocks both the half soul heart and the micro battery. constexpr int ACHIEVEMENT_HALF_SOUL_HEART = 33; constexpr int ACHIEVEMENT_GOLDEN_HEART = 224; @@ -75,8 +87,6 @@ constexpr int ACHIEVEMENT_BONE_HEART = 391; constexpr int ACHIEVEMENT_ROTTEN_HEART = 411; constexpr int ACHIEVEMENT_MEGA_CHEST = 601; constexpr int ACHIEVEMENT_BLACK_SACK = 604; -constexpr int ACHIEVEMENT_WOODEN_CHEST = 609; -constexpr int ACHIEVEMENT_HAUNTED_CHEST = 611; constexpr int ACHIEVEMENT_GOLDEN_PENNY = 613; constexpr int ACHIEVEMENT_GOLDEN_BATTERY = 615; @@ -131,7 +141,6 @@ constexpr float POOP_PITCH_MIN = 0.9f; constexpr float POOP_PITCH_RANGE = 0.3f; constexpr int PILL_GOLD = 14; constexpr int CARD_PLAYING_FLAG = 0x8000; -constexpr float RANDOM_UNIT = 2.3283064e-10f; // The card pickup subtypes that sound like objects, not paper, when collected. constexpr std::initializer_list CARD_OBJECT_SUBTYPES = {3, 4, 6, 7, 13, 15}; constexpr uint32_t GOLDEN_TRINKET_SPRITE_FLAG = 0x80; @@ -230,6 +239,7 @@ constexpr int ROOM_DUNGEON_BEAST_STAGE = STAGE_ID_HOME; constexpr int ETERNAL_CHEST_CLOSE_WAIT = 30; constexpr float HAUNTED_CHEST_RANGE = 100; constexpr float MIMIC_CHEST_RANGE = 50; +constexpr float MIMIC_REVEAL_FRAME = 14; constexpr float THROW_GRAVITY = 1.2f; constexpr float THROW_LOW = -50; constexpr float CHEST_DRAG = 0.8f; @@ -242,10 +252,8 @@ constexpr float DUNGEON_FLOOR_PROBE = 0.5f; constexpr float DUNGEON_LAVA_MARGIN = 30; constexpr uint32_t DUNGEON_PIT_COLLISION = 4; constexpr int DUNGEON_SETTLE_FRAMES = 2; -constexpr float HALF = 0.5f; constexpr float PEDESTAL_MASS = 8; constexpr float PEDESTAL_FRICTION = 0.8f; -constexpr int DIMENSION_DEATH_CERTIFICATE = 2; // How deep pickup_variant_pick is in itself, which Nuh Uh! only rerolls at the top of. static int pickDepth = 0; @@ -829,8 +837,8 @@ bool entity_type_is_saved(int type, int variant, uint32_t subType, int spawnerTy } // 006e02f0 Starts a pickup: clears what a previous life left, chooses its kind (the pick seeded from its seed), loads -// its sprite, makes it appear, and gives Pay To Play's chests a coin slot. -// The big chest, trophy and bed are not reconstructed yet. +// its sprite, makes it appear (a bed lies idle), and gives Pay To Play's chests a coin slot. The Broken Shovel's +// handle starts at its charge. void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) { isUnknown176 = true; @@ -870,9 +878,12 @@ void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, u return; } if (choice.variant == PICKUP_SHOPITEM) shop_ware_choose(choice, seed); - if (is_listed({PICKUP_BROKEN_SHOVEL, PICKUP_BED, PICKUP_MOMSCHEST}, choice.variant)) - reconstruction_missing("Entity_Pickup::Init 006e02f0: the big pickups"); if (choice.variant == PICKUP_COLLECTIBLE) collectible_choose(choice.subType, seed); + if (choice.variant == PICKUP_BROKEN_SHOVEL) + { + choice.subType = COLLECTIBLE_BROKEN_SHOVEL_1; + charge = g_manager->itemConfig.GetCollectible(COLLECTIBLE_BROKEN_SHOVEL_1)->maxCharges; + } lua_engine_get().PostPickupSelection(this, choice.variant, choice.subType); bool isPoopBomb = choice.variant == PICKUP_BOMB && g_game->playerManager.are_all_players_tainted_blue_baby() && @@ -896,11 +907,22 @@ void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, u UpdateSprite(false); } if (variant == PICKUP_BIGCHEST || variant == PICKUP_TROPHY) ending_pickup_init(*this); + if (variant == PICKUP_BED || variant == PICKUP_MOMSCHEST) AddEntityFlags(FLAG_NO_KNOCKBACK); + if (variant == PICKUP_BED && subtype == BED_HELD_SUBTYPE) + { + AddEntityFlags(FLAG_DONT_OVERWRITE); + collisionCooldown = BED_HELD_COOLDOWN; + } if (variant == PICKUP_COLLECTIBLE) { AddEntityFlags(FLAG_NO_KNOCKBACK); pedestal_start(); } + else if (variant == PICKUP_BED) + { + sprite.Play("Idle"); + AddEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK); + } else appear_start(); optionsPickupIndex = 0; @@ -947,8 +969,8 @@ void Entity_Pickup::appear_start() if (g_game->playerManager.GetGFuelCount() > 1) reconstruction_missing("Entity_Pickup::Init 006e02f0: the G FUEL!"); } -// 006e21f0 Swaps in the spritesheets a variant shows: a trinket's own and its golden flag, a collectible's image, and -// Pay To Play's coin slot chests, then loads them. +// 006e21f0 Swaps in the spritesheets a variant shows: a trinket's own and its golden flag, a collectible's image, the +// barren room's torn bed and Pay To Play's coin slot chests, then loads them. void Entity_Pickup::UpdateSprite(bool isIgnoreBlind) { if (variant == PICKUP_TRINKET) @@ -964,8 +986,14 @@ void Entity_Pickup::UpdateSprite(bool isIgnoreBlind) ((g_game->GetCurses() & CURSE_OF_BLIND) || isForceBlind); load_collectible_gfx(sprite, 1, subtype, initSeed, isBlind); } - else if (variant == PICKUP_BED || isPayToPlay) - reconstruction_missing("Entity_Pickup::UpdateSprite 006e21f0: the bed and the coin slot chests"); + else if (variant == PICKUP_BED && g_game->room->roomType == ROOM_BARREN) + sprite.ReplaceSpritesheet(0, BED_BARREN_SHEET); + else if (isPayToPlay && (variant == PICKUP_ETERNALCHEST || variant == PICKUP_LOCKEDCHEST)) + sprite.ReplaceSpritesheet(0, CHEST_COIN_SLOT_SHEET); + else if (isPayToPlay && variant == PICKUP_OLDCHEST) + sprite.ReplaceSpritesheet(0, OLD_CHEST_COIN_SLOT_SHEET); + else if (isPayToPlay && variant == PICKUP_MEGACHEST) + sprite.ReplaceSpritesheet(0, MEGA_CHEST_COIN_SLOT_SHEET); sprite.LoadGraphics(); } @@ -998,7 +1026,7 @@ void Entity_Pickup::Render(const Vector& offset) // 006e3940 Runs the pickup for a frame: a thrown chest's flight, Keeper's hearts turning into flies, Sack Head's // sacks, troll bombs going off, holding its place where it must, its motion and friction, its appear animation and -// drop sound, its timeouts and the crawl space's gravity. +// drop sound, its timeouts and the crawl space's gravity. A mimic chest turns into a spiked one as a player comes near. // Items, the glitched pickups and the rarer kinds' behaviours are not reconstructed yet. void Entity_Pickup::Update() { @@ -1101,11 +1129,9 @@ void Entity_Pickup::Update() bool isAwake = collisionCooldown < 1 && entityCollisionClass != ENTCOLL_NONE; bool isHaunting = variant == PICKUP_HAUNTEDCHEST && isClosedChest && (HasEntityFlags(FLAG_HELD) || (isAwake && is_player_near(pos, HAUNTED_CHEST_RANGE))); - bool isMimicking = variant == PICKUP_MIMICCHEST && isClosedChest && isAwake && - !anyone_has_trinket(TRINKET_FLAT_FILE) && is_player_near(pos, MIMIC_CHEST_RANGE); bool isMegaOpening = variant == PICKUP_MEGACHEST && isClosedChest && sprite.IsEventTriggered("Open"); - if (isHaunting || isMimicking || isMegaOpening || (variant == PICKUP_HEART && subtype == HEART_ROTTEN)) - reconstruction_missing("Entity_Pickup::Update 006e3940: haunted, mega and mimic chests and rotten hearts"); + if (isHaunting || isMegaOpening || (variant == PICKUP_HEART && subtype == HEART_ROTTEN)) + reconstruction_missing("Entity_Pickup::Update 006e3940: haunted and mega chests and rotten hearts"); if (timeout > 0 && --timeout == 0) Remove(); if (wait > 0) wait--; if (chestReCloseTimer > 0 && --chestReCloseTimer == 0 && variant == PICKUP_ETERNALCHEST) @@ -1166,6 +1192,17 @@ void Entity_Pickup::Update() if (collisionCooldown > 0 && !isAppearing) collisionCooldown--; if (variant == PICKUP_BIGCHEST && big_chest_update(*this) == PICKUP_UPDATE_RETURN) return; if (variant == PICKUP_TROPHY) trophy_update(*this); + + bool isMimicAwake = variant == PICKUP_MIMICCHEST && subtype != 0 && collisionCooldown < 1 && + entityCollisionClass != ENTCOLL_NONE && !anyone_has_trinket(TRINKET_FLAT_FILE); + if (isMimicAwake && is_player_near(pos, MIMIC_CHEST_RANGE)) + { + Morph(type, PICKUP_SPIKEDCHEST, subtype, false, false, false); + sprite.Play("Appear"); + if (sprite.animState.animData) sprite.animState.SetFrameFloat(MIMIC_REVEAL_FRAME); + entityCollisionClass = ENTCOLL_ALL; + pickup_sound_play(SOUND_GOOATTACH0); + } lua_engine_get().PostPickupUpdate(this); } @@ -1545,7 +1582,12 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) variant); bool isGreed = (collider->type == ENTITY_ULTRA_GREED || collider->type == ENTITY_BUMBINO) && variant == PICKUP_COIN; - if (isBum && bum_pickup_collect(*static_cast(collider), *this)) + auto* eater = static_cast(collider); + bool isEaten = + (isBum && bum_pickup_collect(*eater, *this)) || + (isEater && !eater->is_following() && + (familiar == Entity_Familiar::LIL_PORTAL ? (eater->AddCoins(1), true) : eater->abyss_locust_eat())); + if (isEaten) { RemoveOtherOptions(); g_game->scoreSheet.add_pickup_points(variant, subtype, pos); @@ -1553,8 +1595,8 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) collect_finish(nullptr); return true; } - if (isEater || isGreed) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a familiar or enemy collecting it"); + if (isGreed) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Ultra Greed or Bumbino collecting it"); return g_game->room->roomType == ROOM_DUNGEON || collider->type == ENTITY_BOMB || price != 0; } @@ -2016,7 +2058,7 @@ void Entity_Pickup::PlayPickupSound() break; case PICKUP_POOP: { - float pitch = (float)Random() * RANDOM_UNIT * POOP_PITCH_RANGE + POOP_PITCH_MIN; + float pitch = random_unit() * POOP_PITCH_RANGE + POOP_PITCH_MIN; return pickup_sound_play(SOUND_PING_PONG, {1, 2, SOUND_ONCE, pitch}); } } diff --git a/src/entity_player.cpp b/src/entity_player.cpp index 5386918..0828e09 100644 --- a/src/entity_player.cpp +++ b/src/entity_player.cpp @@ -9,6 +9,7 @@ #include "active_items.h" #include "hud.h" #include "pocket_items.h" +#include "seeds.h" #include "sfx_manager.h" #include "game.h" #include "log.h" @@ -77,7 +78,6 @@ constexpr int PICKUP_GRAB_BAG = 69; constexpr int PICKUP_HEART = 10; constexpr float PICKUP_SPAWN_RADIUS = 40; constexpr int POCKET_ACTIVE_SLOT = 2; -constexpr float RANDOM_FLOAT_SCALE = 2.3283064e-10f; // A removed player lets go of what it holds at a tenth of its speed. constexpr float HELD_RELEASE_SPEED = 0.1f; constexpr int RED_REDEMPTION_KEY_CHARGES = 20; @@ -935,8 +935,7 @@ void Entity_Player::start_position_set() if (game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER) startY = GREED_START_SPOT_Y; else { - bool isAltStage = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; - if (game.stage + (isAltStage ? 1 : 0) != 1 || game.IsAscent()) + if (game.stage_depth_get() != 1 || game.IsAscent()) { pos = PlayerManager::get_player_start_position(this, {}); if (game.challenge == CHALLENGE_BACKASSWARDS && game.stage == STAGE_DARK_ROOM) @@ -1267,7 +1266,7 @@ void Entity_Player::spawn_low_health_blood_splat() Entity* splat = g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); - float scale = (float)Random() * RANDOM_FLOAT_SCALE * 0.5f + 0.3f; + float scale = random_unit() * 0.5f + 0.3f; splat->sprite.scale = vector_make(scale, scale); splat->sprite.rotation = (float)(Random() & 3) * 90; splat->sprite.isFlipX = !(Random() & 1); @@ -1521,7 +1520,9 @@ void Entity_Player::release_weapons_and_effects(bool isRemoveEntities) weapon.reset(); } link_release(azazelsRageLaser, isRemoveEntities); + link_release(dadsRingAura, isRemoveEntities); link_release(breathOfLifeEffect, isRemoveEntities); + link_release(isaacsHeart, isRemoveEntities); link_release(trinityShield, isRemoveEntities); link_release(deadToothRing, isRemoveEntities); link_release(redemptionEffect, isRemoveEntities); @@ -1529,11 +1530,13 @@ void Entity_Player::release_weapons_and_effects(bool isRemoveEntities) link_release(megaBlastLaser, isRemoveEntities); link_release(markedTarget, isRemoveEntities); link_release(forgottenBody, isRemoveEntities); + link_release(monstranceAura, isRemoveEntities); link_release(babyFamiliar, isRemoveEntities); link_release(salvationEffect, isRemoveEntities); link_release(tetheredEffect, isRemoveEntities); link_release(astralProjectionBody, isRemoveEntities); link_release(montezumaLaser, isRemoveEntities); + link_release(divineShield, isRemoveEntities); link_release(darkArtsLastSnare, isRemoveEntities); link_release(darkEsau, isRemoveEntities); moveToTarget = {}; diff --git a/src/entity_player.h b/src/entity_player.h index e8d9a7f..fe9c236 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -89,6 +89,11 @@ enum PlayerType : int PLAYER_THESOUL_B }; +// The characters whose portrait goes on the alternate layer: ???, Keeper, The Forgotten and The Soul, and the tainted +// ???, Keeper and Forgotten. +constexpr std::array ALT_PORTRAIT_PLAYERS = {PLAYER_BLUEBABY, PLAYER_KEEPER, PLAYER_THEFORGOTTEN, PLAYER_THESOUL, + PLAYER_BLUEBABY_B, PLAYER_KEEPER_B, PLAYER_THEFORGOTTEN_B}; + // What an Entity_Player is: a character, a co-op baby, or an extra player kept out of the room. enum PlayerVariant : int { @@ -313,6 +318,7 @@ enum PlayerItemId : int COLLECTIBLE_WAFER = 108, COLLECTIBLE_MONEY_EQUALS_POWER = 109, COLLECTIBLE_GUARDIAN_ANGEL = 112, + COLLECTIBLE_BIG_FAN = 279, COLLECTIBLE_DEMON_BABY = 113, COLLECTIBLE_MOMS_KNIFE = 114, COLLECTIBLE_DEAD_BIRD = 117, @@ -480,10 +486,12 @@ enum PlayerItemId : int COLLECTIBLE_BOZO = 513, COLLECTIBLE_BROKEN_MODEM = 514, COLLECTIBLE_MYSTERY_GIFT = 515, + COLLECTIBLE_SPRINKLER = 516, COLLECTIBLE_JUMPER_CABLES = 520, COLLECTIBLE_COUPON = 521, COLLECTIBLE_MOVING_BOX = 523, COLLECTIBLE_LEPROSY = 525, + COLLECTIBLE_7_SEALS = 526, COLLECTIBLE_DEATHS_LIST = 530, COLLECTIBLE_HAEMOLACRIA = 531, COLLECTIBLE_SCHOOLBAG = 534, @@ -528,6 +536,11 @@ enum PlayerItemId : int COLLECTIBLE_EVIL_CHARM = 632, COLLECTIBLE_LADDER = 60, COLLECTIBLE_MAW_OF_THE_VOID = 399, + COLLECTIBLE_REVELATION = 643, + COLLECTIBLE_GB_BUG = 405, + COLLECTIBLE_DIVINE_INTERVENTION = 568, + COLLECTIBLE_LIL_PORTAL = 681, + COLLECTIBLE_HEMOPTYSIS = 726, COLLECTIBLE_INTRUDER = 575, COLLECTIBLE_AKELDAMA = 641, COLLECTIBLE_DOGMA = 633, @@ -578,6 +591,19 @@ enum PlayerItemId : int COLLECTIBLE_MY_SHADOW = 433, COLLECTIBLE_CAMO_UNDIES = 497, COLLECTIBLE_MARS = 593, + COLLECTIBLE_HALO_OF_FLIES = 10, + COLLECTIBLE_DADS_RING = 546, + COLLECTIBLE_2SPOOKY = 554, + COLLECTIBLE_120_VOLT = 559, + COLLECTIBLE_MONSTRANCE = 574, + COLLECTIBLE_VENUS = 591, + COLLECTIBLE_PURGATORY = 634, + COLLECTIBLE_TOOTH_AND_NAIL = 663, + COLLECTIBLE_IBS = 725, + COLLECTIBLE_LINGER_BEAN = 447, + COLLECTIBLE_SMB_SUPER_FAN = 189, + COLLECTIBLE_ROTTEN_TOMATO = 618, + COLLECTIBLE_POUND_OF_FLESH = 672, COLLECTIBLE_JUPITER = 594, COLLECTIBLE_ADRENALINE = 493, COLLECTIBLE_PLUTO = 598, @@ -646,6 +672,7 @@ enum PlayerItemId : int TRINKET_ACE_OF_SPADES = 45, TRINKET_POKER_CHIP = 76, TRINKET_CRICKET_LEG = 185, + TRINKET_APOLLYONS_BEST_FRIEND = 186, TRINKET_AAA_BATTERY = 3, TRINKET_FISH_HEAD = 29, TRINKET_BOBS_BLADDER = 71, @@ -692,6 +719,7 @@ enum PlayerItemId : int TRINKET_DOOR_STOP = 124, TRINKET_BABY_BENDER = 127, TRINKET_GIGANTE_BEAN = 134, + TRINKET_EXTENSION_CORD = 125, TRINKET_BROKEN_PADLOCK = 136, TRINKET_FORGOTTEN_LULLABY = 141, TRINKET_BETHS_FAITH = 142, @@ -767,12 +795,14 @@ enum PlayerItemId : int NULLITEM_PURITY_GLOW = 17, NULLITEM_HEMOPTYSIS = 117, NULLITEM_EMPTY_VESSEL = 18, + NULLITEM_MAW_MARK = 19, NULLITEM_HOLY_CARD = 46, NULLITEM_LAZARUS_BOOST = 49, NULLITEM_SPIN_TO_WIN = 50, NULLITEM_INTRUDER = 55, NULLITEM_IT_HURTS = 57, NULLITEM_TOOTH_AND_NAIL_STATUE = 59, + NULLITEM_MARS = 58, NULLITEM_REVERSE_CHARIOT = 63, NULLITEM_JUPITER_BODY = 75, NULLITEM_JUPITER_BODY_ANGEL = 76, @@ -923,7 +953,12 @@ enum PlayerItemId : int COLLECTIBLE_MR_ME = 527, COLLECTIBLE_HALLOWED_GROUND = 543, COLLECTIBLE_SHARP_KEY = 623, - COLLECTIBLE_STITCHES = 635 + COLLECTIBLE_STITCHES = 635, + COLLECTIBLE_MINI_MUSH = 71, + COLLECTIBLE_QUARTER = 74, + COLLECTIBLE_GHOST_BABY = 163, + COLLECTIBLE_DRY_BABY = 265, + COLLECTIBLE_ROTTEN_BABY = 268 }; // The unlocks the player's code checks or grants (Lua's Achievement). @@ -952,18 +987,23 @@ enum PlayerAchievement : int // The challenges the player's code tells apart (Lua's Challenge). enum PlayerChallenge : int { + CHALLENGE_SPEED = 22, + CHALLENGE_PAY_TO_PLAY = 24, CHALLENGE_HAVE_A_HEART = 25, CHALLENGE_PRIDE_DAY = 28, + CHALLENGE_ONANS_STREAK = 29, CHALLENGE_GUARDIAN = 30, CHALLENGE_BACKASSWARDS = 31, CHALLENGE_APRILS_FOOL = 32, + CHALLENGE_POKEY_MANS = 33, CHALLENGE_ULTRA_HARD = 34, CHALLENGE_BLOODY_MARY = 37, CHALLENGE_BAPTISM_BY_FIRE = 38, CHALLENGE_PICA_RUN = 41, CHALLENGE_HOT_POTATO = 42, CHALLENGE_CANTRIPPED = 43, - CHALLENGE_RED_REDEMPTION = 44 + CHALLENGE_RED_REDEMPTION = 44, + CHALLENGE_DELETE_THIS = 45 }; // How far a held item's sprite rises over the head. @@ -1147,6 +1187,10 @@ struct EntityDesc bool isPlayerControlled = false; }; +struct Entity_NPC; +EntityDesc charmed_enemy_save(Entity_NPC& npc); +Entity_NPC* entity_desc_spawn(const EntityDesc& desc, const Vector& position, Entity* spawner); + // What the shoot actions ask for this frame: a direction, whether any is held, and whether opposite ones cancel. struct ShootInput { @@ -1355,6 +1399,8 @@ public: int bombPlaceDelay = 0; int controllerIndex = -1; int controlsCooldown = 0; + int divineInterventionCooldown = 0; + int doubleTapDirection = 0; int doubleTapFrames = 0; int fireBlockCooldown = 0; int glowingHourglassIndex = -1; @@ -1399,8 +1445,13 @@ public: EntityPtr babyFamiliar; EntityPtr bestFriend; EntityPtr breathOfLifeEffect; + EntityPtr dadsRingAura; + EntityPtr divineShield; EntityPtr darkEsau; EntityPtr deadToothRing; + EntityPtr isaacsHeart; + EntityPtr ladder; + EntityPtr monstranceAura; EntityPtr redemptionEffect; EntityPtr salvationEffect; EntityPtr tetheredEffect; @@ -1460,6 +1511,8 @@ public: int delayedSfxId = 0; int ductTapeMode = 0; int epiphoraCharge = 0; + int epiphoraDirection = -1; + int epiphoraGrace = 0; int eveSumptoriumCharge = 0; int forgottenSwapFormCooldown = 0; int firstVisitRooms = 0; @@ -1497,7 +1550,9 @@ public: int reverseEmpressMaxHearts = 0; int reverseSunBoneHearts = 0; int samsonBerserkCharge = 0; + int numberTwoFrames = 0; int strengthMaxHearts = 0; + int toothAndNailFrames = 0; int edenBirthrightFrame = -1; int poopSpellBagCount = 0; int itemHeartsOverflow = 0; @@ -1927,7 +1982,7 @@ public: float GetGreedDonationBreakChance(); float GetGreedDonationJamChance(PersistentGameData& data); void hallowed_ground_add(int count); - void resolve_tainted_soul(); + Entity_Player* resolve_tainted_soul(); void init_forgotten_twin(); Entity* spawn_forgotten_body(); bool SwapForgottenForm(bool isForce, bool isNoEffects); diff --git a/src/entity_player_actives.cpp b/src/entity_player_actives.cpp index c882a09..0593b85 100644 --- a/src/entity_player_actives.cpp +++ b/src/entity_player_actives.cpp @@ -7,6 +7,7 @@ #include "npc_ai.h" #include "room_grid.h" #include "active_items.h" +#include "boss_ai.h" #include "entity_bomb.h" #include "entity_pickup.h" #include "entity_tear.h" @@ -228,6 +229,29 @@ bool input_is_action_triggered(ButtonAction action, int controllerIndex, Entity* return is_action_met(action, controllerIndex, ACTION_TRIGGERED); } +// 00827180 The first door slot whose Red Key outline lies within 120 of a position, or -1. +constexpr float RED_DOOR_OUTLINE_REACH = 120; + +int red_door_outline_slot(const Vector& position) +{ + std::array& outlines = g_game->room->redDoorOutlines; + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) + { + Entity* outline = outlines[slot].get(); + if (outline && vector_length_squared(vector_sub(position, outline->pos)) < RED_DOOR_OUTLINE_REACH * RED_DOOR_OUTLINE_REACH) + return slot; + } + return -1; +} + +// 005c92f0 The player's Stitches, or none. +Entity_Familiar* stitches_get(Entity_Player& player) +{ + for (Entity* entity : entity_query(ENTITY_FAMILIAR, Entity_Familiar::STITCHES)) + if (static_cast(entity)->player == &player) return static_cast(entity); + return nullptr; +} + // 005ca5a0 Whether the player can use an item now: charged enough in its slot (none for -1), and able to pay or move // as the item needs. bool is_active_usable(Entity_Player& player, int item, int slot) @@ -256,9 +280,16 @@ bool is_active_usable(Entity_Player& player, int item, int slot) case COLLECTIBLE_BOOK_OF_VIRTUES: return !player.queuedItem.item || player.queuedItem.item->type != ITEM_ACTIVE; case COLLECTIBLE_RED_KEY: + return red_door_outline_slot(player.pos) >= 0; case COLLECTIBLE_STITCHES: + { + Entity_Familiar* stitches = stitches_get(player); + uint32_t collision = stitches ? room_grid_collision_at(stitches->pos) : COLLISION_WALL; + if (player.canFly) return stitches && collision != COLLISION_WALL; + return collision == COLLISION_NONE || collision == COLLISION_WALL_EXCEPT_PLAYER; + } case COLLECTIBLE_RECALL: - reconstruction_missing("is_active_usable 005ca5a0 (Red Key, Stitches and Recall)"); + return !player.HasEntityFlags(FLAG_HELD | FLAG_THROWN) && player.posOffset.y == 0; } return true; } @@ -1507,8 +1538,8 @@ UseResult Entity_Player::UseActiveItem(const ActiveUse& request) } // The first slot's frame for every slot: recharge cooldowns count down, a timed item fills a charge a frame and beeps -// when full, 9 Volt refills an empty one-charge item after a while in a room with enemies, 4.5 Volt's partial charge -// settles. +// when full, 9 Volt refills an empty one-charge item after a while in a room with enemies, and 4.5 Volt turns a whole +// partial charge into a charge (the original's partial charge is a float, which only 4.5 Volt's damage fills). static void timed_items_recharge(Entity_Player& player) { for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) @@ -1557,9 +1588,13 @@ static void timed_items_recharge(Entity_Player& player) bool isBatteryUnfilled = player.HasCollectible(COLLECTIBLE_BATTERY) && active.batteryCharge < maxCharge; bool isPartlyCharged = active.charge < maxCharge || isBatteryUnfilled; - if (player.HasCollectible(COLLECTIBLE_4_5_VOLT) && chargeType == CHARGE_NORMAL && isPartlyCharged) - reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (4.5 Volt's partial charge)"); - active.partialCharge = 0; + if (!player.HasCollectible(COLLECTIBLE_4_5_VOLT) || chargeType != CHARGE_NORMAL || !isPartlyCharged) + active.partialCharge = 0; + else if (active.partialCharge >= 1) + { + active.partialCharge--; + player.AddActiveCharge(1, slot, false, false, false); + } } } @@ -1591,6 +1626,58 @@ static void use_overlay_show(Entity_Player& player, int item, int slot) g_game->itemOverlay.Show(overlay->overlay, item == COLLECTIBLE_FLUSH ? 0 : OVERLAY_DELAY, nullptr); } +// Sharp Plug: an item short of charge takes it out of the player's health, a hit (8 in a deathmatch) per charge +// missing (one fills a bar item) while more than half a heart is left (a heart for coin health). A coin health +// player gets two charges a hit. Tainted Magdalene's hits on soul or temporary hearts count every other time. +constexpr uint64_t SHARP_PLUG_DAMAGE_FLAGS = + DAMAGE_NOKILL | DAMAGE_RED_HEARTS | DAMAGE_ISAAC_HURT | DAMAGE_INVINCIBLE | DAMAGE_IV_BAG | DAMAGE_NO_MODIFIERS; +constexpr float SHARP_PLUG_DAMAGE = 1; +constexpr float SHARP_PLUG_DEATHMATCH_DAMAGE = 8; +constexpr int SHARP_PLUG_COUNTDOWN = 30; +constexpr int T_MAGDALENE_TEMPORARY_HEARTS = 4; +constexpr int T_MAGDALENE_BIRTHRIGHT_HEARTS = 6; + +static void sharp_plug_pay(Entity_Player& player, int slot, ItemConfig_Item& config) +{ + bool isBar = config.discharge_get() == DISCHARGE_BAR; + bool isCoinHealth = player.GetHealthType() == HEALTH_COIN; + int missing = isBar ? 1 : player.GetActiveMinUsableCharge(slot) - player.GetTotalActiveCharge(slot); + int kept = isCoinHealth ? 2 : 1; + auto health = [&player] { return player.soulHearts + player.redHearts + player.boneHearts; }; + if (missing <= 0 || health() <= kept) return; + + grid_sound_play(SOUND_SHARP_PLUG, {.volume = player.local_volume_get()}); + bool isHalfPaid = false; + for (int i = 0; i < missing; i++) + { + int soulBefore = player.soulHearts; + int redBefore = player.redHearts; + if (health() <= kept) break; + + player.damageCooldown = 0; + float damage = g_game->deathmatchManager.state >= DEATHMATCH_INTRO ? SHARP_PLUG_DEATHMATCH_DAMAGE : SHARP_PLUG_DAMAGE; + if (!player.TakeDamage(damage, SHARP_PLUG_DAMAGE_FLAGS, EntityRef(&player), SHARP_PLUG_COUNTDOWN)) break; + if (isBar) return (void)player.FullCharge(slot, false, false); + + int temporary = player.HasCollectible(COLLECTIBLE_BIRTHRIGHT) ? T_MAGDALENE_BIRTHRIGHT_HEARTS : T_MAGDALENE_TEMPORARY_HEARTS; + bool isSoftHit = player.soulHearts < soulBefore || (player.redHearts < redBefore && player.redHearts >= temporary); + if (player.playerType == PLAYER_MAGDALENE_B && isSoftHit) + { + isHalfPaid = !isHalfPaid; + if (isHalfPaid) + { + i--; + continue; + } + } + player.AddActiveCharge(1, slot, false, false, false); + if (!isCoinHealth) continue; + i++; + if (player.GetTotalActiveCharge(slot) < player.GetActiveMinUsableCharge(slot)) + player.AddActiveCharge(1, slot, false, false, false); + } +} + // Uses a slot's item from the item button: only when charged and payable, else Sharp Plug may pay health for it. A // zero-charge item waits out its room effect. The use discharges the slot or removes the item as it asks, and Car // Battery uses it again. @@ -1607,7 +1694,7 @@ static void active_slot_use(Entity_Player& player, int slot, int itemStateBefore reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Mine Crafter's barrels)"); if (player.HasCollectible(COLLECTIBLE_SHARP_PLUG) && player.itemState == 0 && config && config->discharge_get() != DISCHARGE_HELD) - reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Sharp Plug)"); + sharp_plug_pay(player, slot, *config); return; } if (maxCharge == 0 && player.temporaryEffects.GetCollectibleEffect(item) && config->maxCooldown != 0) return; diff --git a/src/entity_player_actives_rebirth.cpp b/src/entity_player_actives_rebirth.cpp index dfd2c04..d4ffef4 100644 --- a/src/entity_player_actives_rebirth.cpp +++ b/src/entity_player_actives_rebirth.cpp @@ -375,10 +375,9 @@ static void forget_me_now_restart(Entity_Effect* timer) if (!parent || parent->type != ENTITY_PLAYER) return; Entity_Player* player = static_cast(parent); - bool isAltPath = g_game->stageType == STAGETYPE_REPENTANCE || g_game->stageType == STAGETYPE_REPENTANCE_B; sound_play(SOUND_FORGET_ME_NOW); player->PlayExtraAnimation("Appear"); - g_game->seedEffects.ForgetStageSeed(g_game->stage + isAltPath); + g_game->seedEffects.ForgetStageSeed(g_game->stage_depth_get()); g_game->stageTransition.start({.player = player, .type = STAGE_TRANSITION_FORGET_ME_NOW, .isSameStage = true}); } diff --git a/src/entity_player_actives_repentance.cpp b/src/entity_player_actives_repentance.cpp index d192698..fcc5213 100644 --- a/src/entity_player_actives_repentance.cpp +++ b/src/entity_player_actives_repentance.cpp @@ -149,7 +149,6 @@ constexpr int MEGA_MUSH_VERSUS_FRAMES = 300; constexpr ColorMod MR_ME_TARGET_COLOR = {{0, 0.5882353f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr uint64_t DULL_RAZOR_DAMAGE_FLAGS = DAMAGE_RED_HEARTS | DAMAGE_FAKE; constexpr float CHARM_FART_RADIUS = 120; -constexpr float RED_KEY_REACH = 120; constexpr float D8_MIN_MULTIPLIER = 0.5f; constexpr float D8_STAT_AVERAGE = 0.5f; constexpr float DULL_RAZOR_DAMAGE = 2; @@ -400,14 +399,8 @@ static void free_lemonade_use(ItemUse& use) // 005b2360 Red Key: the red room behind the nearest door outline within reach (the first slot's), when there is one. void Entity_Player::UseRedKey() { - std::array& outlines = g_game->room->redDoorOutlines; - - for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) - { - Entity* outline = outlines[slot].get(); - if (outline && vector_length_squared(vector_sub(pos, outline->pos)) < RED_KEY_REACH * RED_KEY_REACH) - return (void)g_game->MakeRedRoomDoor(g_game->currentRoomIdx, slot); - } + int slot = red_door_outline_slot(pos); + if (slot >= 0) g_game->MakeRedRoomDoor(g_game->currentRoomIdx, slot); } // Red Key: a red room opened, the item raised. In Red Redemption a slot's use carries Jacob's curse. @@ -1281,14 +1274,7 @@ static void d7_use(ItemUse& use) static void stitches_use(ItemUse& use) { Entity_Player& player = use.player; - Entity_Familiar* stitches = nullptr; - - for (Entity* entity : entity_query(ENTITY_FAMILIAR, Entity_Familiar::STITCHES)) - if (static_cast(entity)->player == &player) - { - stitches = static_cast(entity); - break; - } + Entity_Familiar* stitches = stitches_get(player); if (!stitches) return; uint32_t collision = room_grid_collision_at(stitches->pos); bool isReachable = player.canFly ? collision != COLLISION_WALL : collision == COLLISION_NONE || collision == COLLISION_WALL_EXCEPT_PLAYER; @@ -1357,11 +1343,9 @@ static void r_key_restart(Entity_Effect*) game.ResetState(); for (int stage = 0; stage < STAGE_SEED_COUNT; stage++) game.seedEffects.ForgetStageSeed(stage); int stage = (int)game.stage; - if (stage > 0 && (stage > STAGE_WOMB_II || !(game.gameStateFlags & 1ull << GAME_STATE_BACKWARDS_PATH))) - { - if (game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B) stage++; - if (stage < STAGE_LAST_SAVED) Game::SaveBackwardsStage(stage); - } + if (stage > 0 && (stage > STAGE_WOMB_II || !(game.gameStateFlags & 1ull << GAME_STATE_BACKWARDS_PATH)) && + game.stage_depth_get() < STAGE_LAST_SAVED) + Game::SaveBackwardsStage(game.stage_depth_get()); game.stage = 0; game.stageType = STAGETYPE_ORIGINAL; g_manager->nightmareScene.isDogma = false; diff --git a/src/entity_player_bombs.cpp b/src/entity_player_bombs.cpp index a9d261f..83cae8d 100644 --- a/src/entity_player_bombs.cpp +++ b/src/entity_player_bombs.cpp @@ -41,6 +41,9 @@ constexpr float BOMB_INHERIT = 0.1f; constexpr float BOMB_SCALE_BIG = 1.5f; constexpr float BOMB_DAMAGE_BIG = 85; constexpr float EXTRA_BOMB_SPREAD = 8; +constexpr float ROCKET_GIGA_RECOIL = 5; +constexpr float ROCKET_FAN_STEP = 3; +constexpr float ROCKET_FAN_REACH = 80; constexpr int SHORT_FUSE = 22; constexpr std::array SHORT_FUSE_DAMAGE = {15.000001f, 30.000002f, 50}; constexpr int BOMBS_MAX = 99; @@ -104,6 +107,35 @@ static bool is_rolled(const Entity_Player& player, const BombItem& item, bool is return (int)(Random() % 100) <= item.chance - (int)((double)player.luck * -item.luckChance); } +// Nancy Bombs' picks: one to four bomb effects drawn from sixteen (Sticky Bombs' two at once), more the luckier (out of 15 less the luck, cast +// unsigned as the original does). +static void nancy_bomb_flags_add(Entity_Player& player, TearFlags& flags) +{ + constexpr std::array, 16> NANCY_FLAGS = {{{TEAR_HOMING, -1}, + {TEAR_POISON, -1}, + {TEAR_BUTT_BOMB, -1}, + {TEAR_BURN, -1}, + {TEAR_SAD_BOMB, -1}, + {TEAR_SCATTER_BOMB, -1}, + {TEAR_STICKY, TEAR_EGG_FLAG}, + {TEAR_GLITTER_BOMB, -1}, + {TEAR_ATTRACTOR, -1}, + {TEAR_CROSS_BOMB, -1}, + {TEAR_CREEP_TRAIL, -1}, + {TEAR_GOLDEN_BOMB, -1}, + {TEAR_FAST_BOMB, -1}, + {TEAR_BLOOD_BOMB, -1}, + {TEAR_BRIMSTONE_BOMB, -1}, + {TEAR_GHOST_BOMB, -1}}}; + constexpr float NANCY_LUCK_BASE = 15; + auto range = (uint32_t)(int64_t)(NANCY_LUCK_BASE - player.luck); + uint32_t roll = range == 0 ? 0 : Random() % range; + int picks = roll == 0 ? 4 : roll < 3 ? 3 : roll < 5 ? 2 : 1; + for (int i = 0; i < picks; i++) + for (int flag : NANCY_FLAGS[Random() & 15]) + if (flag >= 0) flags.set(flag); +} + // 00780560 The tear effects the player's bombs carry from its items, those with chances rolled when asked (Lua's // GetBombFlags): Bobby-Bomb to Bomber Boy, Bob's Bladder, a golden bomb and Fast Bombs (unrolled only), Blood, // Brimstone and Ghost Bombs, and Nancy Bombs' random picks. @@ -122,7 +154,7 @@ TearFlags Entity_Player::GetBombFlags(bool isRollChances) if (HasCollectible(COLLECTIBLE_GHOST_BOMBS) && is_rolled(*this, {0, 0, 33, 8}, isRollChances)) flags.set(TEAR_GHOST_BOMB); if (HasCollectible(COLLECTIBLE_NANCY_BOMBS) && is_rolled(*this, {0, 0, 50, 8}, isRollChances)) - reconstruction_missing("Entity_Player::GetBombFlags 00780560: Nancy Bombs' random effects"); + nancy_bomb_flags_add(*this, flags); if (flags[TEAR_GHOST_BOMB]) flags.set(TEAR_SPECTRAL); return flags; } @@ -175,6 +207,46 @@ static void placed_bomb_setup(Entity_Player& player, Entity_Bomb& bomb, const Te if (flags[TEAR_FAST_BOMB]) bomb.AddEntityFlags(FLAG_NO_KNOCKBACK); } +// Blood Bombs' price for a bomb without bombs: Tainted Bethany's blood charge, or else a heart of the player's own. +// Whether it was paid. +static bool blood_bomb_pay(Entity_Player& player) +{ + constexpr uint64_t BLOOD_BOMB_FLAGS = DAMAGE_RED_HEARTS | DAMAGE_ISAAC_HURT | DAMAGE_INVINCIBLE | DAMAGE_IV_BAG; + constexpr int BLOOD_BOMB_COUNTDOWN = 30; + if (player.playerType == PLAYER_BETHANY_B && player.effectiveBloodCharge > 0) + { + player.AddBloodCharge(-1); + return true; + } + player.damageCooldown = 0; + return player.TakeDamage(1, BLOOD_BOMB_FLAGS, EntityRef(), BLOOD_BOMB_COUNTDOWN); +} + +// Rocket in a Jar's aim for a placed bomb: along the fire direction held, launched at 10 with the player's motion, +// its angle in degrees. Without the item or an aim the bomb is placed. +struct RocketAim +{ + Vector direction{}; + Vector velocity{}; + float angle = 0; + bool isRocket = false; +}; + +static RocketAim rocket_aim(Entity_Player& player) +{ + constexpr float ROCKET_SPEED = 10; + if (!player.HasCollectible(COLLECTIBLE_ROCKET_IN_A_JAR) || player.fireDirection == DIRECTION_NONE || + vector_is_zero(player.aimDirection)) + return {}; + + Vector direction = vector_normalized(player.aimDirection); + Vector inherited = player.GetTearMovementInheritance(direction, INHERIT_CHECKED); + return {.direction = direction, + .velocity = vector_add(vector_scale(direction, ROCKET_SPEED), inherited), + .angle = std::atan2(direction.y, direction.x) * RADIANS_TO_DEGREES, + .isRocket = true}; +} + // Takes the first placed bomb from the player's count, a giga bomb from its giga bombs, unless it was free. static void bomb_count_take(Entity_Player& player, bool isFree) { @@ -189,8 +261,10 @@ static void bomb_count_take(Entity_Player& player, bool isFree) } // 00780f40 Places a bomb when the bomb action is pressed and the last one was long enough ago: one from the player's -// count, a golden bomb's for free, a giga bomb while it has them, and more spread around with Ring Cap. Tainted ??? -// casts poop spells instead, and Tainted Forgotten's soul places none. +// count, a golden bomb's for free (or a twin's whose partner just placed one), a giga bomb while it has them, and +// more spread around with Ring Cap, or launched as rockets with Rocket in a Jar. Tainted ??? casts poop spells +// instead, and Tainted Forgotten's soul places none. The original's partner giga flag is never set, so it is left +// out. void Entity_Player::update_bomb_input() { if (isCoopGhost || IsHologram() || playerType == PLAYER_THESOUL_B) return; @@ -211,16 +285,15 @@ void Entity_Player::update_bomb_input() return; lastActionTriggers |= ACTION_TRIGGER_BOMB; + bool isFree = hasGoldenBomb; for (Entity* partner : {twinPlayer.get(), parent && parent->is_player() ? parent.get() : nullptr}) { Entity_Player* other = partner ? partner->ToPlayer() : nullptr; if (other && other->bombPlaceDelay == (other->HasCollectible(COLLECTIBLE_FAST_BOMBS) ? BOMB_DELAY_FAST : BOMB_DELAY)) - reconstruction_missing("Entity_Player::update_bomb_input 00780f40: the bomb a twin places with its partner"); + isFree = true; } - bool isFree = hasGoldenBomb; bool isGiga = numGigaBombs > 0; - if (numBombs < 1 && !isFree && HasCollectible(COLLECTIBLE_BLOOD_BOMBS)) - reconstruction_missing("Entity_Player::update_bomb_input 00780f40: Blood Bombs' bomb for health"); + if (numBombs < 1 && !isFree && HasCollectible(COLLECTIBLE_BLOOD_BOMBS)) isFree = blood_bomb_pay(*this); if (numBombs < 1 && !isFree) return; bombPlaceDelay = HasCollectible(COLLECTIBLE_FAST_BOMBS) ? BOMB_DELAY_FAST : BOMB_DELAY; @@ -230,21 +303,31 @@ void Entity_Player::update_bomb_input() for (int i = 0; i < bombCount; i++) { TearFlags flags = GetBombFlags(false); - Vector bombVelocity = vector_scale(velocity, BOMB_INHERIT); - bool isAiming = fireDirection != DIRECTION_NONE && !vector_is_zero(aimDirection); - if (HasCollectible(COLLECTIBLE_ROCKET_IN_A_JAR) && isAiming) - reconstruction_missing("Entity_Player::update_bomb_input 00780f40: Rocket in a Jar's rockets"); + RocketAim rocket = rocket_aim(*this); + Vector bombVelocity = rocket.isRocket ? rocket.velocity : vector_scale(velocity, BOMB_INHERIT); + int bombVariant = rocket.isRocket ? BOMB_ROCKET : BOMB_NORMAL; + if (rocket.isRocket && isGiga) velocity = vector_sub(velocity, vector_scale(rocket.direction, ROCKET_GIGA_RECOIL)); + if (isGiga) bombVariant = rocket.isRocket ? BOMB_ROCKET_GIGA : BOMB_GIGA; Entity* spawned = g_game->Spawn({.position = pos, .velocity = bombVelocity, .spawner = this, .type = ENTITY_BOMB, - .variant = isGiga ? BOMB_GIGA : BOMB_NORMAL, .seed = Random()}); + .variant = bombVariant, .seed = Random()}); Entity_Bomb& bomb = *static_cast(spawned); - if (bombCount > 1) + if (bombCount > 1 && rocket.isRocket) + { + Vector back = vector_normalized(bombVelocity); + float spread = (float)bombCount * ROCKET_FAN_STEP; + float turn = lerp_range((float)i, {.inMin = 0, .inMax = (float)(bombCount - 1), .outMin = -spread, .outMax = spread}); + Vector start = vector_sub(pos, vector_scale(back, ROCKET_FAN_REACH)); + bomb.pos = vector_add(start, vector_scale(vector_rotated(back, turn), ROCKET_FAN_REACH)); + } + else if (bombCount > 1) { float angle = random_unit() * RANDOM_HALF_TURN; angle += angle; bomb.pos = vector_make(std::cos(angle) * EXTRA_BOMB_SPREAD + pos.x, std::sin(angle) * EXTRA_BOMB_SPREAD + pos.y); } placed_bomb_setup(*this, bomb, flags, isGiga); + bomb.rocketAngle = rocket.angle; if (i == 0) { bomb_count_take(*this, isFree); diff --git a/src/entity_player_cards.cpp b/src/entity_player_cards.cpp index e633a91..370b532 100644 --- a/src/entity_player_cards.cpp +++ b/src/entity_player_cards.cpp @@ -1,5 +1,6 @@ #include "entity_player.h" #include "active_items.h" +#include "boss_pool.h" #include "entity_effect.h" #include "entity_npc.h" #include "entity_pickup.h" @@ -37,7 +38,6 @@ constexpr int WHEEL_CRANE_GAME_ACHIEVEMENT = 607; constexpr int JUDGEMENT_ROTTEN_BEGGAR_ACHIEVEMENT = 614; constexpr int BERKANO_LOCUSTS = 3; constexpr int BERKANO_LOCUST_SUBTYPE = 25; -constexpr int BOSS_MOM = 6; constexpr int DAEMONS_TAIL_HEART_ODDS = 5; constexpr int DAGAZ_EVIL_CHARM_FRAMES = 600; constexpr int DEATH_EVENT_COUNTER = 7; @@ -1362,46 +1362,47 @@ void game_level_pickups_reroll(Game& game, uint32_t seed) } } -// X - Wheel of Fortune?: the screen darkens and shakes, and one of six rolls: the D4 (which also takes the item away), -// the D20, the D20 with the floor's pickups, the D6 with the floor's items, a new floor, or all of the dice for everyone. -static PocketUseEnd reverse_wheel_use(PocketUse& use) +// The dice room's roll by its face, also Wheel of Fortune?'s: the screen darkens and shakes, then the D4 (which also +// takes the item away), the D20, the D20 with the floor's pickups, the D6 with the floor's items, a new floor, or all of +// the dice for everyone. +void dice_room_roll(Entity_Player& player, int face, uint32_t seed) { - Entity_Player& player = use.player; Game& game = *g_game; - game.darknessStrength = 1; game.darknessTimeout = REVERSE_WHEEL_DARK_FRAMES; game_shake_screen(REVERSE_WHEEL_SHAKE); - int roll = (int)use.rng.RandomInt(6); - uint32_t seed = use.rng.Next(); - if (roll == 0) - { - player.UseActiveItem({.item = COLLECTIBLE_D4, .flags = USE_NOANIM | USE_REMOVEACTIVE}); - return POCKET_END_ANIMATE; - } - if (roll == 1 || roll == 2 || roll == 5) + if (face == 0) player.UseActiveItem({.item = COLLECTIBLE_D4, .flags = USE_NOANIM | USE_REMOVEACTIVE}); + if (face == 1 || face == 2 || face == 5) { player.UseActiveItem({.item = COLLECTIBLE_D20, .flags = USE_NOANIM}); - if (roll != 1) game_level_pickups_reroll(game, seed); + if (face != 1) game_level_pickups_reroll(game, seed); } - if (roll == 3 || roll == 5) + if (face == 3 || face == 5) { game_level_collectibles_reroll(game); player.UseActiveItem({.item = COLLECTIBLE_D6, .flags = USE_NOANIM}); } - if (roll == 4) + if (face == 4) { - game.seedEffects.ForgetStageSeed((int)game.stage + (game.IsAltPath() ? 1 : 0)); + game.seedEffects.ForgetStageSeed(game.stage_depth_get()); game.stageTransition.start({.isSameStage = true}); } - else if (roll == 5) - for (int i = 0; i < (int)game.playerManager.playerList.size(); i++) - { - Entity_Player* each = game.GetPlayer(i); - if (each->variant == PLAYER_VARIANT_PLAYER) - each->UseActiveItem({.item = COLLECTIBLE_D4, .flags = USE_NOANIM | USE_REMOVEACTIVE}); - } + if (face != 5) return; + for (int i = 0; i < (int)game.playerManager.playerList.size(); i++) + { + Entity_Player* each = game.GetPlayer(i); + if (each->variant == PLAYER_VARIANT_PLAYER) + each->UseActiveItem({.item = COLLECTIBLE_D4, .flags = USE_NOANIM | USE_REMOVEACTIVE}); + } +} + +// X - Wheel of Fortune?: one of the dice room's six rolls. +static PocketUseEnd reverse_wheel_use(PocketUse& use) +{ + int roll = (int)use.rng.RandomInt(6); + uint32_t seed = use.rng.Next(); + dice_room_roll(use.player, roll, seed); return POCKET_END_ANIMATE; } diff --git a/src/entity_player_characters.cpp b/src/entity_player_characters.cpp index 08b3c19..26653e3 100644 --- a/src/entity_player_characters.cpp +++ b/src/entity_player_characters.cpp @@ -1130,8 +1130,7 @@ float damage_charge_scale() { Game& game = *g_game; if (game.deathmatchManager.is_active()) return DEATHMATCH_DAMAGE_CHARGE_SCALE; - bool isDeeper = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; - return 1 / ((float)(game.stage + (isDeeper ? 1 : 0)) * DAMAGE_CHARGE_PER_STAGE + DAMAGE_CHARGE_BASE); + return 1 / ((float)game.stage_depth_get() * DAMAGE_CHARGE_PER_STAGE + DAMAGE_CHARGE_BASE); } // The Berserk! charge part of 00794e50: out of Berserk!, the damage enemies took this frame charges Tainted Samson's diff --git a/src/entity_player_collectibles.cpp b/src/entity_player_collectibles.cpp index c807dc1..c6d2e38 100644 --- a/src/entity_player_collectibles.cpp +++ b/src/entity_player_collectibles.cpp @@ -2,6 +2,7 @@ #include "entity_player_passives.h" #include "active_items.h" #include "entity_config.h" +#include "entity_effect.h" #include "entity_pickup.h" #include "game.h" #include "hud.h" @@ -38,9 +39,13 @@ enum RemovalItem : int NULLITEM_DOUBLED_B = 126 }; -// The collectibles whose effect ends with more than its costume that are not written yet: Camo Undies, Wavy Cap, -// Mega Mush, Berserk and Dark Arts. -constexpr int EFFECT_END_ITEMS[] = {497, 582, 625, 704, 705}; +// The collectible whose effect ends with more than its costume that is not written yet: Mega Mush. +constexpr int EFFECT_END_ITEMS[] = {625}; + +// The suplex aiming when Berserk ends leaps at once. +constexpr int SUPLEX_STATE_AIMING = 2; +constexpr int SUPLEX_STATE_LEAP = 5; + constexpr int PURITY_STATE_COUNT = 4; constexpr float REMOVED_DROP_STEP = 40; @@ -210,8 +215,10 @@ static void doubled_costume_remove(Entity_Player& player, int collectibleId) } // What the end of a collectible's effect does after its costume comes off: the invincible items give the music its -// pitch back (Unicorn Stump its volume too), Taurus's colour fades, Dead Bird keeps its costume, and How to Jump and -// Empty Vessel land the player. +// pitch back (Unicorn Stump its volume too), Taurus's colour fades, Dead Bird keeps its costume, How to Jump and +// Empty Vessel land the player, Camo Undies gives the player its colour back, the Wavy Cap redresses its stacks, +// Berserk's end sounds, may kill a player left without hearts, resets the music's layers and lets an aimed suplex +// leap, and Dark Arts ends its last snare at once and sets its blast off. static void collectible_effect_end(Entity_Player& player, int collectibleId) { MusicManager& music = g_manager->musicManager; @@ -235,6 +242,30 @@ static void collectible_effect_end(Entity_Player& player, int collectibleId) case COLLECTIBLE_BIRD_CAGE: player.AddCostume(g_manager->itemConfig.GetCollectible(collectibleId), false); return; + case COLLECTIBLE_CAMO_UNDIES: + player.ResetColor(); + return; + case COLLECTIBLE_BERSERK: + grid_sound_play(SOUND_BERSERK_END); + player.try_trigger_astral_projection(); + g_game->UpdateBackwardsPathStages(); + if (player.suplexState == SUPLEX_STATE_AIMING && player.suplexAimCountdown > 0) + player.suplexState = SUPLEX_STATE_LEAP; + return; + case COLLECTIBLE_DARK_ARTS: + { + Entity* snare = player.darkArtsLastSnare ? player.darkArtsLastSnare->GetLastParent() : nullptr; + if (snare && snare->type == ENTITY_EFFECT) + { + static_cast(snare)->timeout = 1; + static_cast(snare)->lifespan = 1; + } + player.isDarkArtsBlastPending = true; + return; + } + case COLLECTIBLE_WAVY_CAP: + player.update_mini_mush_costume(); + return; case COLLECTIBLE_HOW_TO_JUMP: case COLLECTIBLE_EMPTY_VESSEL: if (player.variant != PLAYER_VARIANT_PLAYER) return; diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp index b68e336..969b4b5 100644 --- a/src/entity_player_damage.cpp +++ b/src/entity_player_damage.cpp @@ -1,5 +1,7 @@ +#include "entity_bomb.h" #include "entity_effect_combat.h" #include "entity_familiar.h" +#include "entity_pickup.h" #include "entity_npc.h" #include "entity_player.h" #include "entity_player_characters.h" @@ -12,7 +14,9 @@ #include "lua_engine.h" #include "manager.h" #include "npc_ai.h" +#include "npc_basement.h" #include "room.h" +#include "room_grid.h" #include #include @@ -32,13 +36,8 @@ constexpr int NULLITEM_SHACKLES_GHOST = 101; constexpr int SAMSON_B_HIT_CHARGE = 10000; constexpr int BLEED_OUT_HEALTH = 600; -// Zodiac's sign a landed hit may set off, until the zodiac's hits are written. -constexpr int ZODIAC = 392; - -constexpr int ENTITY_SEGMENTED_WORM = 903; -constexpr int ENTITY_DAMAGE_RELAY = 966; constexpr int SIREN_CHARM_SPARE_FRAMES = 29; -constexpr int SEGMENTED_WORM_VARIANT = 10; +constexpr int VISAGE_CHAIN = 10; constexpr int WHITE_FIRE_VARIANT = 4; constexpr int EFFECT_SELF_DAMAGE = 19; constexpr int EFFECT_POISON_CLOUD = 123; @@ -57,7 +56,6 @@ constexpr int COIN_THIEF_TYPES[] = {50, 86, 90, 294, 299, 406}; constexpr int COIN_SHOOTER_TYPES[] = {50, 86, 90}; constexpr int ULTRA_GREED = 406; constexpr int ULTRA_GREED_DOOR = 294; -constexpr uint32_t CHALLENGE_PAY_TO_PLAY = 24; constexpr int SOUND_NAIL_HURT_1 = 104; constexpr int SOUND_NAIL_HURT_2 = 106; @@ -158,8 +156,8 @@ static bool is_damage_ignored(Entity_Player& player, const EntityRef& source, ui bool isAppearing = player.sprite.IsPlaying("Appear") || player.sprite.IsPlaying("Glitch"); if ((player.variant == PLAYER_VARIANT_COOP_BABY || player.isCoopGhost) && isAppearing) return true; - if (source.type == ENTITY_SEGMENTED_WORM && source.variant == SEGMENTED_WORM_VARIANT && entity) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a worm segment of the player's own)"); + if (source.type == ENTITY_VISAGE && source.variant == VISAGE_CHAIN && entity) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a Visage chain)"); return false; } @@ -181,30 +179,185 @@ static bool is_wisp_shield_present(Entity_Player& player) }); } -// The items that answer a hit before it lands, each stopping or turning it, none written yet. -static void damage_reactions_check(Entity_Player& player, uint64_t damageFlags) +// Plays one of the player's sounds at a volume and pitch, unless the seeds swap it for a fart. +static void voice_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 answers' strengths and odds: Pyromaniac's heart icon, Host Hat's guard and return volley, Metal Plate's and +// Cone Head's chances, and Jelly Belly's bounce. +constexpr float HEART_ICON_RISE = -24; +constexpr int HOST_HAT_VOLLEY_ODDS = 5; +constexpr float RETURN_SHOT_SPEED = 10; +constexpr float HOST_HAT_SPREAD = 15; +constexpr uint32_t RETURN_SHOT_FLAGS = 7; +constexpr int METAL_PLATE_ODDS = 4; +constexpr int CONE_HEAD_ODDS = 5; +constexpr int CONE_HEAD_FLASH_FRAMES = 10; +constexpr int JELLY_BELLY_ODDS = 2; +constexpr float JELLY_BELLY_REACH = 10; +constexpr float JELLY_BELLY_SHOT_SPEED = 10; +constexpr float JELLY_BELLY_PUSH = 20; +constexpr int JELLY_BELLY_PUSH_FRAMES = 15; +constexpr float JELLY_BELLY_SPEED_UNIT = 25; +constexpr float JELLY_BELLY_PLAYER_PUSH = 40; +constexpr float JELLY_BELLY_BOUNCE = 20; +constexpr float JELLY_BELLY_SHOT_BOUNCE = 14; +constexpr int JELLY_BELLY_COOLDOWN = 8; +constexpr float JELLY_SHOT_VOLUME = 0.8f; +constexpr float JELLY_SHOT_PITCH = 1.25f; +constexpr ColorMod METAL_PLATE_TEAR_COLOR = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod CONE_HEAD_FLASH = {{0.7f, 0.7f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The four looks of a Host Hat animation, picked by the way a vector leans. +static std::string host_hat_anim(std::string_view base, Vector direction) +{ + constexpr std::string_view SIDES[] = {"Left", "Up", "Right", "Down"}; + return std::string(base) + std::string(SIDES[vector_to_direction(direction)]); +} + +// The shot a hat or plate sends back: the way the hitting shot came, at 10. +static Vector return_shot_velocity(const EntityRef& source) +{ + return vector_scale(vector_resized(source.velocity, RETURN_SHOT_SPEED), -1); +} + +// Jelly Belly's bounce, half the time against a living source (an enemy, a shot or a player) that reaches it: an +// enemy is knocked away, a shot turned back, another player pushed by their speeds. Whether it bounced the hit. +static bool jelly_belly_bounce(Entity_Player& player, const EntityRef& source, uint64_t damageFlags) +{ + if (!player.HasCollectible(COLLECTIBLE_JELLY_BELLY) || (damageFlags & (DAMAGE_NO_MODIFIERS | DAMAGE_FAKE))) return false; + Entity* hitter = source.entity; + bool isLiving = hitter && ((source.type >= ENTITY_FIRST_ENEMY && source.type <= ENEMY_TYPE_LAST) || + source.type == ENTITY_PROJECTILE || source.type == ENTITY_PLAYER); + if (random_below(JELLY_BELLY_ODDS) != 0 || !isLiving) return false; + + float reach = hitter->size * std::max(hitter->sizeMulti.x, hitter->sizeMulti.y) + player.size + JELLY_BELLY_REACH; + bool isTouching = vector_distance(hitter->pos, player.pos) <= reach; + if (hitter->is_player()) + { + if (hitter->HasEntityFlags(FLAG_KNOCKED_BACK) || !isTouching) return false; + float combined = vector_length_squared(hitter->velocity) + vector_length_squared(player.velocity); + float push = std::clamp(combined / JELLY_BELLY_SPEED_UNIT, 0.0f, 1.0f) * JELLY_BELLY_PLAYER_PUSH; + float strength = vector_length_squared(player.velocity) / combined * push; + Vector away = vector_scale(vector_normalized(vector_sub(hitter->pos, player.pos)), strength); + hitter->AddKnockback(EntityRef(&player), away, 1, true); + player.jellyBellyBounceTimer = JELLY_BELLY_BOUNCE; + voice_play(SOUND_JELLY_BOUNCE, 1, SOUND_FRAME_DELAY, 1); + } + else if (hitter->IsEnemy()) + { + if (!isTouching) return false; + Vector away = vector_resized(vector_sub(hitter->pos, player.pos), JELLY_BELLY_PUSH); + hitter->AddKnockback(EntityRef(&player), away, JELLY_BELLY_PUSH_FRAMES, true); + player.jellyBellyBounceTimer = JELLY_BELLY_BOUNCE; + voice_play(SOUND_JELLY_BOUNCE, 1, SOUND_FRAME_DELAY, 1); + } + else if (hitter->type == ENTITY_PROJECTILE || hitter->type == ENTITY_TEAR) + { + Vector away = vector_resized(vector_sub(hitter->pos, player.pos), JELLY_BELLY_SHOT_SPEED); + if (hitter->type == ENTITY_PROJECTILE) static_cast(hitter)->Reflect(away); + else static_cast(hitter)->Deflect(&player, away); + player.jellyBellyBounceTimer = JELLY_BELLY_SHOT_BOUNCE; + voice_play(SOUND_BLOBBY_WIGGLE, JELLY_SHOT_VOLUME, SOUND_FRAME_DELAY, JELLY_SHOT_PITCH); + } + else return false; + player.SetMinDamageCooldown(JELLY_BELLY_COOLDOWN); + player.AddEntityFlags(FLAG_NO_DAMAGE_BLINK); + return true; +} + +// Walnut cracks open on an explosion a third of the time: a trinket, a heart, a key and a coin (times its multiplier) +// near the player, and it is gone. +static void walnut_crack(Entity_Player& player) +{ + constexpr int WALNUT_CHANCE = 33; + constexpr int WALNUT_PICKUPS[] = {PICKUP_TRINKET, PICKUP_HEART, PICKUP_KEY, PICKUP_COIN}; + RNG& rng = player.GetTrinketRNG(TRINKET_WALNUT); + if (rng.Next() % 100 >= WALNUT_CHANCE) return; + + int count = player.GetTrinketMultiplier(TRINKET_WALNUT); + for (int variant : WALNUT_PICKUPS) + for (int i = 0; i < count; i++) + { + uint32_t seed = rng.Next(); + Vector spot = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_SPOT_STEP}); + g_game->Spawn({.position = spot, .spawner = &player, .type = ENTITY_PICKUP, .variant = variant, .seed = seed}); + } + player.TryRemoveTrinket(TRINKET_WALNUT); +} + +// The items that answer a hit before it lands, in the original's order: Pyromaniac heals from explosions and shrugs +// off fire, Host Hat guards explosions and sometimes fires back at shots, Dr. Fetus and the bone with Ipecac ignore +// their own blasts, Hot Bombs fire, the bomb baby explosions, Jelly Belly bounces, Metal Plate returns shots and Cone +// Head shrugs off a fifth of the hits, after Walnut cracks. Whether the hit is stopped. A charmed Bishop's shield +// stops the game. +static bool damage_reactions_check(Entity_Player& player, const EntityRef& source, uint64_t damageFlags) { bool isExplosion = damageFlags & DAMAGE_EXPLOSION; bool isFire = damageFlags & DAMAGE_FIRE; if (is_bishop_present()) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a charmed Bishop's shield)"); - if (player.HasTrinket(TRINKET_WALNUT) && isExplosion) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Walnut)"); - if (player.HasCollectible(COLLECTIBLE_PYROMANIAC) && (isFire || isExplosion)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Pyromaniac)"); - if (player.HasCollectible(COLLECTIBLE_HOST_HAT)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Host Hat)"); - bool isFetus = player.HasWeaponType(WEAPON_BOMBS) || player.HasWeaponType(WEAPON_BONE); - if (isFetus && player.HasCollectible(COLLECTIBLE_IPECAC) && isExplosion) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Ipecac with Dr. Fetus)"); - if (player.HasCollectible(COLLECTIBLE_HOT_BOMBS) && isFire) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Hot Bombs)"); - if (player.variant == PLAYER_VARIANT_COOP_BABY && player.babySkin == BABY_BOMB && isExplosion) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the bomb baby)"); - if (player.HasCollectible(COLLECTIBLE_JELLY_BELLY) && !(damageFlags & (DAMAGE_NO_MODIFIERS | DAMAGE_FAKE))) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Jelly Belly)"); - if (player.HasCollectible(COLLECTIBLE_METAL_PLATE) || player.HasCollectible(COLLECTIBLE_CONE_HEAD)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Metal Plate and Cone Head)"); + if (player.HasTrinket(TRINKET_WALNUT) && isExplosion) walnut_crack(player); + if (player.HasCollectible(COLLECTIBLE_PYROMANIAC) && isFire) return true; + if (player.HasCollectible(COLLECTIBLE_PYROMANIAC) && isExplosion) + { + if (player.redHearts >= player.GetEffectiveMaxHearts()) return true; + Entity* icon = g_game->Spawn({.position = player.pos, .type = ENTITY_EFFECT, .variant = EFFECT_HEART, .seed = Random()}); + icon->sprite.offset = vector_make(0, HEART_ICON_RISE); + icon->renderDepthOffset = 1; + player.AddHearts(1, false, false); + return true; + } + if (player.HasCollectible(COLLECTIBLE_HOST_HAT) && isExplosion) + { + player.PlayCollectibleAnim(COLLECTIBLE_HOST_HAT, false, host_hat_anim("Guard", vector_from_direction(player.headDirection)), -1); + return true; + } + + bool isFetusBomb = source.spawnerType == ENTITY_PLAYER || source.spawnerType == ENTITY_FAMILIAR; + isFetusBomb = isFetusBomb && source.entity && source.entity->type == ENTITY_BOMB && + static_cast(source.entity)->isFetus; + bool isFetus = player.HasWeaponType(WEAPON_BOMBS) || + (player.HasWeaponType(WEAPON_BONE) && player.HasCollectible(COLLECTIBLE_DR_FETUS)); + if (isFetus && player.HasCollectible(COLLECTIBLE_IPECAC) && isExplosion && isFetusBomb) return true; + bool isBoneIpecac = player.HasWeaponType(WEAPON_BONE) && player.HasCollectible(COLLECTIBLE_IPECAC); + if (isBoneIpecac && isExplosion && source.type == ENTITY_KNIFE) return true; + if (player.HasCollectible(COLLECTIBLE_HOT_BOMBS) && isFire) return true; + if (player.variant == PLAYER_VARIANT_COOP_BABY && player.babySkin == BABY_BOMB && isExplosion) return true; + if (jelly_belly_bounce(player, source, damageFlags)) return true; + + if (player.HasCollectible(COLLECTIBLE_HOST_HAT) && random_below(HOST_HAT_VOLLEY_ODDS) == 0 && + source.type == ENTITY_PROJECTILE) + { + Vector back = return_shot_velocity(source); + for (float turn : {-HOST_HAT_SPREAD, 0.0f, HOST_HAT_SPREAD}) + player.FireTear({player.pos, vector_rotated(back, turn)}, RETURN_SHOT_FLAGS, nullptr, 1); + player.PlayCollectibleAnim(COLLECTIBLE_HOST_HAT, false, host_hat_anim("Shooting", back), -1); + return true; + } + bool isShot = source.type == ENTITY_PROJECTILE || source.type == ENTITY_TEAR; + if (player.HasCollectible(COLLECTIBLE_METAL_PLATE) && + player.GetCollectibleRNG(COLLECTIBLE_METAL_PLATE).RandomInt(METAL_PLATE_ODDS) == 0 && isShot) + { + Entity_Tear* tear = player.FireTear({player.pos, return_shot_velocity(source)}, RETURN_SHOT_FLAGS, nullptr, 1); + TearFlags flags = tear->tearFlags; + flags.set(TEAR_HOMING); + flags.set(TEAR_CONFUSION); + tear->SetTearFlags(flags); + tear->SetColor(METAL_PLATE_TEAR_COLOR, -1, 255, false, true); + tear->Update(); + return true; + } + if (player.HasCollectible(COLLECTIBLE_CONE_HEAD) && !(damageFlags & (DAMAGE_NO_MODIFIERS | DAMAGE_FAKE)) && + player.GetCollectibleRNG(COLLECTIBLE_CONE_HEAD).RandomInt(CONE_HEAD_ODDS) == 0) + { + player.SetColor(CONE_HEAD_FLASH, CONE_HEAD_FLASH_FRAMES, 1, true, true); + return true; + } + return false; } // Whether a list of ids has one. @@ -241,13 +394,6 @@ static void bestiary_count_add(std::map& counts, int type, int variant if (entity && entity->isBestiary) counts[entity->id << 20 | entity->variant << 8]++; } -// Plays one of the player's sounds at a volume and pitch, unless the seeds swap it for a fart. -static void voice_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 damage a hit deals in half hearts: rounded, two from the Womb on or on a victory lap, halved by the Wafer and // its likes, doubled by the double damage effect, and set by the seeds that hurt more. static int damage_amount_get(Entity_Player& player, float damage, uint64_t damageFlags, const EntityRef& source) @@ -478,7 +624,6 @@ static bool holy_mantle_block(Entity_Player& player) static bool hit_items_check(Entity_Player& player, int amount, const ItemsHit& hit) { passives_hit_trigger(player, amount); - if (player.HasCollectible(ZODIAC)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Zodiac's sign)"); bool isHurtShown = late_items_hit_trigger(player, hit); character_items_hit(player); if (player.playerType == PLAYER_SAMSON_B && (player.redHearts > 0 || player.soulHearts > 0 || player.boneHearts > 0)) @@ -491,10 +636,46 @@ static bool hit_items_check(Entity_Player& player, int amount, const ItemsHit& h return isHurtShown; } +// Glass Cannon held in a slot shatters on a penalized hit: it becomes the Broken Glass Cannon with a crash, an impact +// and shards, the player bleeds (Anemic, and Judas' Birthright's timed boost with Book of Belial), and takes two more +// full heart hits of its own. +static void glass_cannon_break(Entity_Player& player) +{ + constexpr int GLASS_SHARD_COUNT = 8; + constexpr float GLASS_SHARD_SPEED_RANGE = 3; + constexpr float GLASS_SHARD_SPEED_MIN = 2; + constexpr int BELIAL_BOOST_FRAMES = 4; + constexpr float SHATTER_DAMAGE = 2; + constexpr uint64_t SHATTER_FLAGS = DAMAGE_NOKILL | DAMAGE_ISAAC_HURT | DAMAGE_INVINCIBLE | DAMAGE_NO_MODIFIERS; + constexpr int SHATTER_COUNTDOWN = 30; + int slot = player.GetActiveItemSlot(COLLECTIBLE_GLASS_CANNON); + if (slot < 0) return; + + player.RemoveCollectible(player.activeItems[slot].item, false, slot, true); + player.AddCollectible(COLLECTIBLE_BROKEN_GLASS_CANNON, 0, false, slot, 0); + voice_play(SOUND_GLASS_BREAK, 1, SOUND_FRAME_DELAY, 1); + g_game->Spawn({.position = player.pos, .type = ENTITY_EFFECT, .variant = EFFECT_IMPACT, .seed = Random()})->Update(); + game_particles_spawn({.position = player.pos, + .height = player.posOffset.y, + .speed = random_unit() * GLASS_SHARD_SPEED_RANGE + GLASS_SHARD_SPEED_MIN, + .count = GLASS_SHARD_COUNT, + .variant = EFFECT_TOOTH_PARTICLE}); + TemporaryEffects& effects = player.temporaryEffects; + if (!effects.HasCollectibleEffect(COLLECTIBLE_ANEMIC)) + effects.AddEffect(TemporaryEffect(g_manager->itemConfig.GetCollectible(COLLECTIBLE_ANEMIC)), true, 1); + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) + effects.AddNullEffect(NULLITEM_JUDAS_BIRTHRIGHT, true, BELIAL_BOOST_FRAMES); + for (int hit = 0; hit < 2; hit++) + { + player.ResetDamageCooldown(); + player.TakeDamage(SHATTER_DAMAGE, SHATTER_FLAGS, EntityRef(&player), SHATTER_COUNTDOWN); + } +} + // Whether the hit comes from a familiar the Siren charmed under 30 frames ago, or from a relay of its hits. static bool is_siren_charm_fresh(const EntityRef& source) { - Entity* hitter = source.type == ENTITY_DAMAGE_RELAY && source.entity ? source.entity->parent.get() : nullptr; + Entity* hitter = source.type == ENTITY_SIREN_HELPER && source.entity ? source.entity->parent.get() : nullptr; if (source.type == ENTITY_FAMILIAR) hitter = source.entity; if (!hitter || hitter->type != ENTITY_FAMILIAR) return false; @@ -523,7 +704,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR reconstruction_missing("Entity_Player::TakeDamage 007729d0 (white fire's lost curse)"); } if (IsHologram() || is_damage_ignored(*this, source, damageFlags)) return false; - damage_reactions_check(*this, damageFlags); + if (damage_reactions_check(*this, source, damageFlags)) return false; if (!(damageFlags & DAMAGE_NO_HURT_EFFECTS)) play_hurt_effects(); bool isSeedProtected = game.seedEffects.HasSeedEffect(SEED_INVINCIBLE) || @@ -560,8 +741,17 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR if (temporaryEffects.HasCollectibleEffect(COLLECTIBLE_HOLY_MANTLE) && !(damageFlags & DAMAGE_RED_HEARTS)) return holy_mantle_block(*this); - if (hallowedGroundCountdown > 0 && !(damageFlags & DAMAGE_NO_MODIFIERS)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Hallowed Ground)"); + if (hallowedGroundCountdown > 0 && !(damageFlags & DAMAGE_NO_MODIFIERS) && + GetCollectibleRNG(COLLECTIBLE_HALLOWED_GROUND).RandomInt(2) == 0) + { + constexpr ColorMod HALLOWED_FLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {64 / 255.0f, 64 / 255.0f, 128 / 255.0f}}; + constexpr int HALLOWED_FLASH_FRAMES = 15; + constexpr int HALLOWED_COOLDOWN = 8; + SetColor(HALLOWED_FLASH, HALLOWED_FLASH_FRAMES, 255, true, true); + damageCooldown = damage_cooldown_scale(HALLOWED_COOLDOWN); + AddEntityFlags(FLAG_NO_DAMAGE_BLINK); + return false; + } if (!lua_engine_get().EntityTakeDamage(this, (float)amount, damageFlags, source, damageCountdown)) return false; if (try_end_astral_projection()) return false; if (playerType == PLAYER_JACOB_B && source.type == ENTITY_DARK_ESAU) @@ -683,7 +873,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR flags &= ~FLAG_NO_DAMAGE_BLINK; if (isAstral) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Astral Projection)"); blind_rage_finger_bone_hit(*this); - if (isPenalized && HasCollectible(COLLECTIBLE_GLASS_CANNON)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Glass Cannon)"); + if (isPenalized && HasCollectible(COLLECTIBLE_GLASS_CANNON)) glass_cannon_break(*this); if (isHitAnimated) { @@ -720,6 +910,12 @@ void Entity_Player::death_count(const EntityRef& source, uint64_t damageFlags) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the achievement for dying to Ipecac)"); } +// 0060d090 Ends the invincibility frames. +void Entity_Player::ResetDamageCooldown() +{ + damageCooldown = 0; +} + // 007db6b0 Whether a hit kills at once: the Lost's curse, or Tainted Jacob's ghost. bool Entity_Player::HasInstantDeathCurse() { diff --git a/src/entity_player_effects.cpp b/src/entity_player_effects.cpp new file mode 100644 index 0000000..aea00df --- /dev/null +++ b/src/entity_player_effects.cpp @@ -0,0 +1,681 @@ +#include "entity_player_effects.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_pickup.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "entity_player_characters.h" +#include "entity_projectile.h" +#include "entity_slot.h" +#include "game.h" +#include "manager.h" +#include "grid_entity_pit.h" +#include "npc_ai.h" +#include "room.h" +#include "room_grid.h" +#include "temporary_effects.h" +#include "sfx_manager.h" +#include +#include + +// The Ladder's reach: how near a player must stand to a laid ladder to keep it, and the turn of a ladder laid across. +constexpr float LADDER_KEEP_DISTANCE_SQUARED = 3249; +constexpr float LADDER_ACROSS_ROTATION = 90; + +// The pit at a cell, or null off the grid or on any other grid entity. +static GridEntity_Pit* pit_at(Room& room, int gridIndex) +{ + if (gridIndex < 0 || gridIndex >= ROOM_GRID_CELLS) return nullptr; + GridEntity* grid = room.gridEntities[gridIndex]; + return grid && grid->type == GRID_PIT ? static_cast(grid) : nullptr; +} + +// Whether a cell is one a ladder may lean on: inside the room's first width squared cells and not a pit. The +// original bounds the cells by the width twice, not by the width and the height. +static bool is_ladder_side(Room& room, int gridIndex) +{ + return gridIndex >= 0 && gridIndex < room.gridWidth * room.gridWidth && !pit_at(room, gridIndex); +} + +// A laid ladder taken up: its pit is a pit again and it hides. +static void ladder_lift(Room& room, Entity_Effect& ladder) +{ + if (GridEntity_Pit* pit = pit_at(room, ladder.state)) + { + pit->hasLadder = false; + pit->UpdateCollision(); + } + ladder.state = -1; + ladder.isVisible = false; +} + +// 0079f3c0 The Ladder: its hidden ladder effect is spawned once. A laid ladder stays while a player (or a flying +// one) stands near it, else it is taken up. Walking from solid ground towards an open pit lays it over that pit, +// across when the walk is sideways with no pits beside, along when it is upright with no pits above and below. +// Without the item the ladder goes once it is taken up. +void Entity_Player::update_ladder() +{ + Room& room = *g_game->room; + bool isOwner = HasCollectible(COLLECTIBLE_LADDER) && variant == PLAYER_VARIANT_PLAYER; + if (!isOwner && !ladder) return; + + if (!ladder) + { + Entity* spawned = g_game->Spawn({.type = ENTITY_EFFECT, .variant = EFFECT_LADDER, .seed = Random()}); + spawned->isVisible = false; + static_cast(spawned)->state = -1; + ladder = spawned; + } + auto& effect = *static_cast(ladder.get()); + Vector start = pos; + Vector walk = velocity; + + if (effect.isVisible) + { + Vector center = room.GetGridPosition(effect.state); + bool isStoodOn = std::ranges::any_of(g_game->playerManager.playerList, [&](Entity_Player* player) + { + bool isCounted = player == this || player->entityGridCollisionClass == GRIDCOLL_NOPITS; + return isCounted && vector_length_squared(vector_sub(player->pos, center)) <= LADDER_KEEP_DISTANCE_SQUARED; + }); + if (!isStoodOn) ladder_lift(room, effect); + } + if (!isOwner) + { + if (effect.isVisible) return; + effect.Remove(); + ladder = nullptr; + return; + } + + int here = room.GetGridIndex(start); + if (here < 0) return; + Vector step = vector_length(walk) > 0 ? vector_normalized(walk) : walk; + int ahead = room.GetGridIndex(vector_add(start, vector_scale(step, GRID_CELL_SIZE))); + if (effect.state == ahead) return; + + GridEntity_Pit* standing = pit_at(room, here); + GridEntity_Pit* pit = pit_at(room, ahead); + if ((standing && standing->state <= 1) || !pit || pit->state != 0) return; + + bool isSideways = std::fabs(walk.x) > std::fabs(walk.y); + bool isUpright = std::fabs(walk.y) > std::fabs(walk.x); + bool isAcross = isSideways && is_ladder_side(room, ahead - 1) && is_ladder_side(room, ahead + 1); + if (!isAcross && + !(isUpright && is_ladder_side(room, ahead - room.gridWidth) && is_ladder_side(room, ahead + room.gridWidth))) + return; + + ladder_lift(room, effect); + pit->hasLadder = true; + pit->UpdateCollision(); + effect.state = ahead; + effect.pos = room.GetGridPosition(ahead); + effect.isVisible = true; + effect.sprite.rotation = isAcross ? LADDER_ACROSS_ROTATION : 0; + npc_sound_play(SOUND_LADDER, 1, 2, 1); +} + +// The items' frame pieces' reach, timings and strengths, with the exe's values. +constexpr float DADS_RING_RADIUS = 40; +constexpr int DADS_RING_FREEZE = -4; +constexpr int DADS_RING_BOSS_FREEZE = -50; +constexpr float SPOOKY_RADIUS = 80; +constexpr float VENUS_RADIUS = 120; +constexpr int VENUS_CHARM_FRAMES = 60; +constexpr float SPOOKY_FEAR_REACH = 80; +constexpr int SPOOKY_FEAR_FRAMES = -20; +constexpr int SPOOKY_BOSS_FEAR_FRAMES = -60; +constexpr float MONSTRANCE_RADIUS = 90; +constexpr float MONSTRANCE_PERIOD = 4; +constexpr LerpRange MONSTRANCE_FALLOFF = {.inMin = 30, .inMax = 90, .outMin = 0, .outMax = 0.4f}; +constexpr float MONSTRANCE_STAGE_DAMAGE = 0.32f; +constexpr float MONSTRANCE_BASE_DAMAGE = 3.6f; +constexpr int MONSTRANCE_HIT_COUNTDOWN = 30; +constexpr int HALO_DADS_RING = 0; +constexpr int HALO_MONSTRANCE = 2; +constexpr int MARS_READY_PONY_STEP = 2; +constexpr int MARS_READY_DAMAGE_COOLDOWN = 30; +constexpr float MARS_READY_PITCH = 0.8f; +constexpr int MARS_READY_FLASH_FRAMES = 3; +constexpr int TOOTH_AND_NAIL_WARNINGS[] = {105, 120, 135}; +constexpr int TOOTH_AND_NAIL_STATUE_FRAME = 150; +constexpr int TOOTH_AND_NAIL_END_FRAME = 180; +constexpr int TOOTH_AND_NAIL_WARNING_STEP = 15; +constexpr int TOOTH_AND_NAIL_WARNING_LAST = 9; +constexpr int FLASH_FRAMES = 2; +constexpr int FLASH_PRIORITY = 255; +constexpr int IBS_DRAIN_FRAMES = 60; +constexpr float IBS_CHARGE_PER_DAMAGE = 1.5f; +constexpr float KEEPER_COIN_PULL_RADIUS = 80; +constexpr float KEEPER_COIN_PULL_MIN_SQUARED = 16; +constexpr float KEEPER_COIN_PULL_SPEED = 10; +constexpr int PURGATORY_PERIOD = 30; +constexpr int LINGER_BEAN_PERIOD = 240; +constexpr float GIGANTE_CLOUD_SCALE = 2; +constexpr int SPLAT_PERIOD = 3; +constexpr float PLAYER_SPLAT_SIZE_RANGE = 0.5f; +constexpr float PLAYER_SPLAT_SIZE_MIN = 0.2f; +constexpr int SPIN_TO_WIN_DRAIN = -1; +constexpr int FADED_POLAROID_FADE_FRAMES = 30; +constexpr float FADED_POLAROID_PULSE = 0.1f; +constexpr float CAMO_SETTLE = 0.1f; +constexpr float CAMO_TINT = 0.01f; +constexpr float SIZE_SCALE_MIN = 0.3f; +constexpr float MINI_MUSH_SIZE = 0.75f; +constexpr float SMALL_SIZE = 0.5f; +constexpr int SMALL_COLLISION_POINTS = 12; +constexpr float MEGA_MUSH_SIZE_MAX = 2; +constexpr float MEGA_MUSH_SHADOW = 3; +constexpr float GHOST_SHADOW = 0.5f; +constexpr float HEART_PUSH_MARGIN = 8; +constexpr float HEART_BLOCK_MARGIN = 20; +constexpr float HEART_BLOCK_HEIGHT = -90; +constexpr float WARNING_VOLUME = 0.8f; +constexpr float WARNING_VOLUME_STEP = 0.2f; +constexpr float WARNING_FADE_STEP = 0.3f; +constexpr float WARNING_OFFSET = 0.3f; +constexpr float WARNING_OFFSET_STEP = 0.06f; +constexpr uint32_t FRAME_STAT_CACHE = CACHE_DAMAGE | CACHE_FIREDELAY | CACHE_TEARFLAG | CACHE_TEARCOLOR; + +// The flashes the frame lays on the player: Tooth and Nail's statue turning, and Mars' dash being ready. +constexpr ColorMod GREY_FLASH = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0.8f, 0.8f, 0.8f}}; +constexpr ColorMod MARS_READY_COLOR = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {1, 0.2f, 0.2f}}; + +// The splats some items leave every third frame: Dirty Mind's brown, Rotten Tomato's red and Neptunus' faint black. +constexpr ColorMod DIRTY_MIND_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.255f, 0.161f, 0.137f}}; +constexpr ColorMod ROTTEN_TOMATO_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.45f, 0.1f, 0.09f}}; +constexpr ColorMod NEPTUNUS_SPLAT = {{0, 0, 0, 0.08f}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The Anarchist Cookbook's effect drops a troll bomb with the player's bomb effects every fifth frame it has left. +static void anarchist_cookbook_update(Entity_Player& player) +{ + constexpr int TROLL_BOMB_PERIOD = 5; + TemporaryEffect* cookbook = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_ANARCHIST_COOKBOOK); + if (!cookbook || cookbook->cooldown % TROLL_BOMB_PERIOD != 0) return; + + Vector spot = room_pickup_position_random(false, false); + Entity* spawned = g_game->Spawn({.position = spot, .spawner = &player, .type = ENTITY_BOMB, .variant = BOMB_TROLL, + .seed = Random()}); + if (spawned->type != ENTITY_BOMB) return; + auto& bomb = *static_cast(spawned); + bomb.isLoadCostumes = true; + bomb.tearFlags = player.GetBombFlags(false); +} + +// Faded Polaroid every 300 frames, one time in five, fades the player for 3 to 7 seconds (times its multiplier). +static void faded_polaroid_update(Entity_Player& player) +{ + constexpr int POLAROID_PERIOD = 300; + constexpr int POLAROID_ODDS = 5; + constexpr int POLAROID_SECONDS_MIN = 3; + constexpr int POLAROID_SECONDS_RANGE = 5; + constexpr int POLAROID_FRAMES_PER_SECOND = 30; + TemporaryEffects& effects = player.temporaryEffects; + if (effects.HasTrinketEffect(TRINKET_FADED_POLAROID) || !player.HasTrinket(TRINKET_FADED_POLAROID)) return; + if (!player.IsFrame(POLAROID_PERIOD, 0) || random_below(POLAROID_ODDS) != 0) return; + + TemporaryEffect fade(g_manager->itemConfig.GetTrinket(TRINKET_FADED_POLAROID)); + int multiplier = player.GetTrinketMultiplier(TRINKET_FADED_POLAROID); + fade.cooldown = multiplier * (random_below(POLAROID_SECONDS_RANGE) + POLAROID_SECONDS_MIN) * POLAROID_FRAMES_PER_SECOND; + effects.AddEffect(fade, true, 1); +} + +// A link the player keeps to an aura riding on it: spawned once while it is wanted, else removed. +static void aura_keep(Entity_Player& player, EntityPtr& aura, bool isWanted, int subType) +{ + if (!isWanted) + { + if (aura) aura->Remove(); + aura = nullptr; + return; + } + if (aura) return; + Entity* halo = g_game->Spawn({.position = player.pos, .spawner = &player, .subType = subType, + .type = ENTITY_EFFECT, .variant = EFFECT_HALO, .seed = Random()}); + halo->parent = &player; + aura = halo; +} + +// Dad's Ring freezes the vulnerable enemies touching the player under its halo. +static void dads_ring_update(Entity_Player& player) +{ + bool isWorn = player.HasCollectible(COLLECTIBLE_DADS_RING); + if (isWorn) + for (Entity* enemy : entity_query_radius(player.pos, DADS_RING_RADIUS, QUERY_ENEMIES)) + if (enemy->IsVulnerableEnemy(nullptr)) + enemy->AddFreeze(EntityRef(&player), enemy->IsBoss() ? DADS_RING_BOSS_FREEZE : DADS_RING_FREEZE, false); + aura_keep(player, player.dadsRingAura, isWorn, HALO_DADS_RING); +} + +// Berserk!'s ending ticks: the tick starts with 45 frames left and stops before it, or when the effect is gone. +static void berserk_tick_update(Entity_Player& player) +{ + constexpr int BERSERK_TICK_FRAMES = 45; + constexpr int BERSERK_TICK_DELAY = 60; + SFXManager& sfx = g_manager->sfxManager; + bool isStopped = sfx.IsPlaying(SOUND_BERSERK_TICK); + + if (TemporaryEffect* berserk = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_BERSERK)) + { + if (berserk->cooldown == BERSERK_TICK_FRAMES) + sfx.Play(SOUND_BERSERK_TICK, {.frameDelay = BERSERK_TICK_DELAY}); + isStopped = berserk->cooldown > BERSERK_TICK_FRAMES; + } + if (isStopped) sfx.Stop(SOUND_BERSERK_TICK); +} + +// Venus charms the vulnerable enemies around the player and 2Spooky frightens them. With both, the original weighs +// the squared distance against the enemy's size plus 80, so the fright only reaches the nearest. +static void spooky_venus_update(Entity_Player& player) +{ + bool isSpooky = player.HasCollectible(COLLECTIBLE_2SPOOKY); + bool isVenus = player.HasCollectible(COLLECTIBLE_VENUS); + if (!isSpooky && !isVenus) return; + + for (Entity* enemy : entity_query_radius(player.pos, isVenus ? VENUS_RADIUS : SPOOKY_RADIUS, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || enemy == &player) continue; + bool isBoss = enemy->IsBoss(); + int charm = isBoss ? VENUS_CHARM_FRAMES : VENUS_CHARM_FRAMES - enemy->charmedCountdown; + if (isVenus && charm >= 1) enemy->AddCharmed(EntityRef(&player), charm, false, false); + if (!isSpooky) continue; + float distanceSquared = vector_length_squared(vector_sub(enemy->pos, player.pos)); + if (isVenus && enemy->size + SPOOKY_FEAR_REACH < distanceSquared) continue; + enemy->AddFear(EntityRef(&player), isBoss ? SPOOKY_BOSS_FEAR_FRAMES : SPOOKY_FEAR_FRAMES, false); + } +} + +// Monstrance burns the vulnerable enemies around the player every fourth tick, harder the deeper the floor and the +// nearer the enemy's edge, under its halo. A pacifist room has neither. +static void monstrance_update(Entity_Player& player) +{ + bool isWorn = player.HasCollectible(COLLECTIBLE_MONSTRANCE) && !g_game->room->isPacifist; + if (isWorn && player.GetIntervalTicks(MONSTRANCE_PERIOD, 0) != 0) + { + LerpRange falloff = MONSTRANCE_FALLOFF; + falloff.outMin = (float)g_game->stage * MONSTRANCE_STAGE_DAMAGE + MONSTRANCE_BASE_DAMAGE; + for (Entity* enemy : entity_query_radius(player.pos, MONSTRANCE_RADIUS, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || enemy == &player) continue; + float edge = vector_distance(player.pos, enemy->pos) - enemy->size; + enemy->TakeDamage(lerp_range(edge, falloff), 0, EntityRef(&player), MONSTRANCE_HIT_COUNTDOWN); + } + } + aura_keep(player, player.monstranceAura, isWorn, HALO_MONSTRANCE); +} + +// Mars' dash recharges outside its dash, twice as fast with a pony. When the dash ends the player may dash again, +// briefly unhurt. A full charge beeps, flashes red and shows Mars' ready costume. +static void mars_recharge_update(Entity_Player& player) +{ + if (!player.HasCollectible(COLLECTIBLE_MARS) || player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || + player.marsCooldown < 0) + return; + + if (!player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MARS)) + { + if (!player.isMarsDashReady) + { + player.isMarsDashReady = true; + player.ClearEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK); + player.SetMinDamageCooldown(MARS_READY_DAMAGE_COOLDOWN); + } + player.marsDashDirection = -1; + } + bool isPony = player.HasCollectible(COLLECTIBLE_PONY) || player.HasCollectible(COLLECTIBLE_WHITE_PONY); + player.marsCooldown = std::max(player.marsCooldown - (isPony ? MARS_READY_PONY_STEP : 1), -1); + if (player.marsCooldown != -1) return; + + npc_sound_play(SOUND_BEEP, 1, 2, MARS_READY_PITCH); + player.SetColor(MARS_READY_COLOR, MARS_READY_FLASH_FRAMES, FLASH_PRIORITY, true, true); + player.AddCostume(g_manager->itemConfig.GetNullItem(NULLITEM_MARS), false); +} + +// Divine Intervention's shield recharges outside interpolation, beeping and flashing gold when ready. +static void divine_intervention_recharge(Entity_Player& player) +{ + constexpr ColorMod DIVINE_READY_COLOR = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {1, 0.9f, 0.6f}}; + if (!player.HasCollectible(COLLECTIBLE_DIVINE_INTERVENTION) || player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || + player.divineInterventionCooldown < 0) + return; + player.divineInterventionCooldown = std::max(player.divineInterventionCooldown - 1, -1); + if (player.divineInterventionCooldown != -1) return; + npc_sound_play(SOUND_BEEP, 1, 2, MARS_READY_PITCH); + player.SetColor(DIVINE_READY_COLOR, MARS_READY_FLASH_FRAMES, FLASH_PRIORITY, true, true); +} + +// Tooth and Nail counts the frames: three fading warnings, then the player turns to a statue for half a second. Losing +// the item ends it. +static void tooth_and_nail_update(Entity_Player& player) +{ + if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; + TemporaryEffects& effects = player.temporaryEffects; + int& frames = player.toothAndNailFrames; + + if (!player.HasCollectible(COLLECTIBLE_TOOTH_AND_NAIL)) + { + if (frames <= 0) return; + frames = 0; + if (!effects.HasNullEffect(NULLITEM_TOOTH_AND_NAIL_STATUE)) return; + effects.RemoveNullEffect(NULLITEM_TOOTH_AND_NAIL_STATUE, 1); + player.SetColor(GREY_FLASH, FLASH_FRAMES, FLASH_PRIORITY, false, true); + return; + } + frames++; + if (std::ranges::find(TOOTH_AND_NAIL_WARNINGS, frames) != std::end(TOOTH_AND_NAIL_WARNINGS)) + { + int left = TOOTH_AND_NAIL_WARNING_LAST - frames / TOOTH_AND_NAIL_WARNING_STEP; + constexpr float WARNING_PITCH_EVEN = 1.7f; + constexpr float WARNING_PITCH_ODD = 1.4f; + float volume = WARNING_VOLUME - (float)left * WARNING_VOLUME_STEP; + npc_sound_play(SOUND_BUTTON_PRESS, volume, 1, left % 2 == 0 ? WARNING_PITCH_EVEN : WARNING_PITCH_ODD); + float offset = WARNING_OFFSET - (float)left * WARNING_OFFSET_STEP; + ColorMod warning = {{1, 1, 1, 1}, {1, 1, 1, 1 - (float)left * WARNING_FADE_STEP}, {offset, offset, offset}}; + player.SetColor(warning, FLASH_FRAMES, FLASH_PRIORITY, false, true); + } + else if (frames == TOOTH_AND_NAIL_STATUE_FRAME) + { + if (effects.HasNullEffect(NULLITEM_TOOTH_AND_NAIL_STATUE)) return; + effects.AddNullEffect(NULLITEM_TOOTH_AND_NAIL_STATUE, true, 1); + player.SetColor(GREY_FLASH, FLASH_FRAMES, FLASH_PRIORITY, false, true); + npc_sound_play(SOUND_GOOATTACH0, 1, 2, 1); + } + else if (frames >= TOOTH_AND_NAIL_END_FRAME) + { + effects.RemoveNullEffect(NULLITEM_TOOTH_AND_NAIL_STATUE, 1); + player.SetColor(GREY_FLASH, FLASH_FRAMES, FLASH_PRIORITY, false, true); + frames = 0; + } +} + +// Reverse Empress' last 90 frames blink its costume, faster at first (every 4 frames, then every 8 under 32 left). +static void reverse_empress_blink_update(Entity_Player& player) +{ + constexpr int EMPRESS_BLINK_FRAMES = 90; + constexpr int EMPRESS_FAST_BLINK_FRAMES = 32; + TemporaryEffect* empress = player.temporaryEffects.GetNullEffect(NULLITEM_REVERSE_EMPRESS); + if (!empress || empress->cooldown >= EMPRESS_BLINK_FRAMES) return; + + int phase = empress->cooldown < EMPRESS_FAST_BLINK_FRAMES ? empress->cooldown % 8 : empress->cooldown % 16 / 2; + bool isShown = player.IsNullItemCostumeVisible(NULLITEM_REVERSE_EMPRESS, -1); + ItemConfig_Item* costume = g_manager->itemConfig.GetNullItem(NULLITEM_REVERSE_EMPRESS); + if (phase < 4 && isShown) player.RemoveCostume(costume); + else if (phase >= 4 && !isShown) player.AddCostume(costume, false); +} + +// IBS charges with the damage enemies took this frame, up to full. A spent charge (negative) drains back to zero +// over a second. +static void ibs_charge_update(Entity_Player& player) +{ + if (player.HasCollectible(COLLECTIBLE_IBS)) + { + float dealt = g_game->room->entityList.enemyDamageInflicted; + if (dealt > 0 && player.ibsCharge >= 0) + player.ibsCharge = std::min(player.ibsCharge + damage_charge_scale() * dealt * IBS_CHARGE_PER_DAMAGE, 1.0f); + } + if (player.ibsCharge < 0) player.ibsCharge = std::min(player.ibsCharge + 1.0f / IBS_DRAIN_FRAMES, 0.0f); +} + +// The Birthright's frame: Eve's Dead Bird always flies (its costume hidden), and Tainted Keeper pulls the coins near +// it that are about to vanish. The Lost's Dead Bird always flies too. +static void birthright_dead_bird_update(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + bool isDeadBirdIdle = player.HasCollectible(COLLECTIBLE_DEAD_BIRD) && !player.isCoopGhost && + !effects.HasCollectibleEffect(COLLECTIBLE_DEAD_BIRD); + + if (player.HasCollectible(COLLECTIBLE_BIRTHRIGHT) && player.playerType == PLAYER_EVE && isDeadBirdIdle) + { + effects.AddCollectibleEffect(COLLECTIBLE_DEAD_BIRD, true, 1); + player.RemoveCostume(g_manager->itemConfig.GetCollectible(COLLECTIBLE_DEAD_BIRD)); + } + else if (player.HasCollectible(COLLECTIBLE_BIRTHRIGHT) && player.playerType == PLAYER_KEEPER_B) + for (Entity* entity : entity_query_radius(player.pos, KEEPER_COIN_PULL_RADIUS, QUERY_PICKUPS)) + { + if (entity->type != ENTITY_PICKUP || entity->variant != PICKUP_COIN || entity->isDead) continue; + if (static_cast(entity)->timeout <= 0) continue; + Vector pull = vector_sub(player.pos, entity->pos); + if (vector_length_squared(pull) <= KEEPER_COIN_PULL_MIN_SQUARED) continue; + entity->velocity = vector_resized(pull, KEEPER_COIN_PULL_SPEED); + entity->entityGridCollisionClass = GRIDCOLL_WALLS; + } + + bool isLost = player.playerType == PLAYER_THELOST || player.playerType == PLAYER_THELOST_B; + isDeadBirdIdle = player.HasCollectible(COLLECTIBLE_DEAD_BIRD) && !player.isCoopGhost && + !effects.HasCollectibleEffect(COLLECTIBLE_DEAD_BIRD); + if (isLost && isDeadBirdIdle) effects.AddCollectibleEffect(COLLECTIBLE_DEAD_BIRD, true, 1); +} + +// Purgatory keeps one of its rifts in a room still fighting (or under an ambush), checked every 30 frames. +static void purgatory_update(Entity_Player& player) +{ + if (!player.HasCollectible(COLLECTIBLE_PURGATORY) || !player.IsFrame(PURGATORY_PERIOD, 0)) return; + if (g_game->room->IsClear() && !g_game->ambush.isActive) return; + for (Entity* rift : entity_query(ENTITY_EFFECT, EFFECT_PURGATORY)) + if (rift->subtype == 0 && rift->spawnerEntity.get() == &player) return; + + Vector spot = room_pickup_position_random(true, false); + uint32_t seed = player.GetCollectibleRNG(COLLECTIBLE_PURGATORY).Next(); + g_game->Spawn({.position = spot, .spawner = &player, .type = ENTITY_EFFECT, .variant = EFFECT_PURGATORY, .seed = seed}) + ->Update(); +} + +// Plan C's countdown kills the player when it runs out, forgetting what hurt it. Judas with his Birthright gets Plan +// C's effect first. +static void plan_c_update(Entity_Player& player) +{ + if (player.planCKillCountdown <= 0 || --player.planCKillCountdown != 0) return; + TemporaryEffects& effects = player.temporaryEffects; + if (player.playerType == PLAYER_JUDAS && player.HasCollectible(COLLECTIBLE_BIRTHRIGHT) && + !effects.HasCollectibleEffect(COLLECTIBLE_PLAN_C)) + effects.AddCollectibleEffect(COLLECTIBLE_PLAN_C, false, 1); + player.Kill(EntityRef()); + player.lastDamageFlags = 0; + player.lastDamageSource.type = 0; + player.lastDamageSource.variant = 0; +} + +// Isaac's Heart keeps the player apart: other enemies and co-op players touching it are pushed back, and enemy shots +// that reach it pop. +static void isaacs_heart_update(Entity_Player& player) +{ + if (!player.HasCollectible(COLLECTIBLE_ISAACS_HEART)) return; + EntityList_EL entities = g_game->room->entityList.updateEL; + + for (Entity* entity : entities) + { + if (entity->type == ENTITY_PROJECTILE) + { + float reach = entity->size + player.size + HEART_BLOCK_MARGIN; + Vector offset = vector_sub(entity->pos, player.pos); + bool isNear = std::fabs(offset.x) < reach && std::fabs(offset.y) < reach && vector_length(offset) < reach; + if (static_cast(entity)->height > HEART_BLOCK_HEIGHT && isNear) entity->isDead = true; + continue; + } + Entity* pushed = entity->to_npc_or_coop_player(); + if (!pushed || pushed->entityCollisionClass == ENTCOLL_NONE) continue; + float reach = pushed->size + player.size + HEART_PUSH_MARGIN; + Vector away = vector_sub(pushed->pos, player.pos); + if (std::fabs(away.x) >= reach || std::fabs(away.y) >= reach) continue; + float distance = vector_length(away); + if (distance >= reach || distance <= 0) continue; + away = vector_scale(away, 1 / reach); + float closing = vector_dot(pushed->velocity, away); + if (closing < 0) pushed->AddVelocity_divided(vector_scale(away, -closing), false); + } +} + +// Linger Bean leaves a lingering cloud each time the fire button has been held another 240 frames (twice, the frame +// it is reached and the next), larger with Gigante Bean. +static void linger_bean_update(Entity_Player& player) +{ + if (!player.HasCollectible(COLLECTIBLE_LINGER_BEAN) || g_game->stageTransition.state != 0) return; + int held = player.shootHeldFrames; + if (!player.AreControlsEnabled() || player.fireBlockCooldown >= 1 || held % LINGER_BEAN_PERIOD >= 2 || held <= 1) + return; + + Entity* cloud = g_game->Spawn({.position = player.pos, .spawner = &player, .type = ENTITY_EFFECT, + .variant = EFFECT_BROWN_CLOUD, .seed = Random()}); + if (player.HasTrinket(TRINKET_GIGANTE_BEAN)) cloud->sprite.scale = vector_scale(cloud->sprite.scale, GIGANTE_CLOUD_SCALE); + cloud->Update(); + npc_sound_play(SOUND_LINGER_BEAN, 1, 2, 1); +} + +// A blood splat under the player (Entity_NPC::MakeSplat's), optionally tinted. +static Entity* splat_make(Entity_Player& player, const ColorMod* color) +{ + Entity* splat = spawn_at(ENTITY_EFFECT, EFFECT_BLOOD_SPLAT, 0, player.pos, &player); + float size = random_unit() * PLAYER_SPLAT_SIZE_RANGE + PLAYER_SPLAT_SIZE_MIN; + splat->sprite.scale = vector_make(size, size); + splat->Update(); + if (color) splat->SetColor(*color, -1, FLASH_PRIORITY, false, true); + return splat; +} + +// Every third frame the player may leave a splat: half the time when bleeding (the SMB Super Fan, headless, Anemic, +// Akeldama, the dead Tainted Lazarus, and a quarter of Tainted Eve's and Tainted Lazarus' frames), else from Dirty +// Mind, Rotten Tomato, a Pound of Flesh or Neptunus, the first one held. +static void splats_update(Entity_Player& player) +{ + if (!player.IsFrame(SPLAT_PERIOD, 0) || player.IsHologram()) return; + int type = player.playerType; + bool isOftenBleeding = player.HasCollectible(COLLECTIBLE_SMB_SUPER_FAN) || player.IsHeadless() || + player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_ANEMIC) || + player.HasCollectible(COLLECTIBLE_AKELDAMA) || type == PLAYER_LAZARUS2_B; + bool isBleeding = isOftenBleeding || ((type == PLAYER_LAZARUS_B || type == PLAYER_EVE_B) && random_below(4) == 0); + constexpr int BLEEDING_ODDS = 2; + constexpr int DIRTY_MIND_ODDS = 4; + constexpr int ROTTEN_TOMATO_ODDS = 8; + constexpr int POUND_OF_FLESH_ODDS = 6; + constexpr int NEPTUNUS_ODDS = 2; + + if (isBleeding) + { + if (random_below(BLEEDING_ODDS) == 0) splat_make(player, nullptr); + } + else if (player.HasCollectible(COLLECTIBLE_DIRTY_MIND)) + { + if (random_below(DIRTY_MIND_ODDS) == 0) splat_make(player, &DIRTY_MIND_SPLAT); + } + else if (player.HasCollectible(COLLECTIBLE_ROTTEN_TOMATO)) + { + if (random_below(ROTTEN_TOMATO_ODDS) == 0) splat_make(player, &ROTTEN_TOMATO_SPLAT); + } + else if (player.HasCollectible(COLLECTIBLE_POUND_OF_FLESH)) + { + if (random_below(POUND_OF_FLESH_ODDS) == 0) splat_make(player, nullptr); + } + else if (player.HasCollectible(COLLECTIBLE_NEPTUNUS) && random_below(NEPTUNUS_ODDS) == 0) + splat_make(player, &NEPTUNUS_SPLAT); +} + +// The fading looks: under the camo seeds, Camo Undies' cloak or Faded Polaroid's flicker, the player's color slides +// toward a near black tinted like its footprints, settling at once on a room's first frames. +static void camo_fade_update(Entity_Player& player) +{ + Game& game = *g_game; + float fade = 1; + bool isCamo = game.seedEffects.HasSeedEffect(SEED_CAMO_ISAAC) || game.seedEffects.HasSeedEffect(SEED_CAMO_EVERYTHING) || + player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_CAMO_UNDIES); + if (!isCamo) + { + TemporaryEffect* polaroid = player.temporaryEffects.GetTrinketEffect(TRINKET_FADED_POLAROID); + if (!polaroid) return; + if (polaroid->cooldown < FADED_POLAROID_FADE_FRAMES) + { + fade = std::sin((float)polaroid->cooldown * FADED_POLAROID_PULSE); + if (fade <= 0) return; + } + } + + float settle = game.room->GetFrameCount() > 1 ? CAMO_SETTLE : 1; + ColorMod footprints = color_lerp(player.footprintColor2, player.footprintColor1, 0.5f); + ColorMod camo = color_lerp(player.colorOverride, footprints, settle); + camo._tint[0] = camo._tint[1] = camo._tint[2] = CAMO_TINT; + camo._tint[3] = 1; + player.colorOverride = camo; + player.sprite.color = color_lerp(player.color, camo, fade); +} + +// The player's size and shadow follow its sprite's layer scale (with the original's extra 1 in the sum), held between +// 0.3 and 1: smaller with Mini Mush, halved by Pluto or Inner Child's shrink (with fewer collision points), doubled +// up to 2 by Mega Mush with a triple shadow. A co-op ghost's shadow is halved and the invisible seed hides it. +static void size_update(Entity_Player& player) +{ + ANM2& sprite = player.sprite; + float scale = 1; + for (LayerState& layer : sprite.layerStates) scale += layer.size.x; + scale = std::clamp(scale / (float)sprite.layerStates.size() * player.playerSpriteScale.x, SIZE_SCALE_MIN, 1.0f); + int points = player.config->gridCollisionPoints; + float shadow = 1; + + if (player.HasCollectible(COLLECTIBLE_MINI_MUSH)) scale *= MINI_MUSH_SIZE; + if (player.HasCollectible(COLLECTIBLE_PLUTO) || player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_INNER_CHILD)) + { + scale *= SMALL_SIZE; + points = std::min(points, SMALL_COLLISION_POINTS); + } + if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) + { + scale = std::min(scale + scale, MEGA_MUSH_SIZE_MAX); + shadow = MEGA_MUSH_SHADOW; + } + if (player.isCoopGhost) shadow *= GHOST_SHADOW; + if (g_game->seedEffects.HasSeedEffect(SEED_INVISIBLE_ISAAC)) shadow = 0; + + EntityConfig_Entity* entry = g_manager->entityConfig.GetEntity(player.type, player.variant, 0); + player.SetSize(scale * entry->collisionRadius, player.sizeMulti, points); + player.shadowSize = shadow * player.config->shadowSize; +} + +// The written pieces of the items' frame (update_effects 00794e50) the plain path runs after its others, in their +// order there. +void items_frame_update(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + + anarchist_cookbook_update(player); + faded_polaroid_update(player); + dads_ring_update(player); + if (effects.HasCollectibleEffect(COLLECTIBLE_NOTCHED_AXE) && !player.HasCollectible(COLLECTIBLE_NOTCHED_AXE)) + effects.RemoveCollectibleEffect(COLLECTIBLE_NOTCHED_AXE, -1); + if (effects.GetNullEffect(NULLITEM_CAMO_BOOST)) effects.RemoveNullEffect(NULLITEM_CAMO_BOOST, 1); + berserk_tick_update(player); + if (effects.HasCollectibleEffect(COLLECTIBLE_URN_OF_SOULS) && !player.HasCollectible(COLLECTIBLE_URN_OF_SOULS)) + effects.RemoveCollectibleEffect(COLLECTIBLE_URN_OF_SOULS, -1); + spooky_venus_update(player); + monstrance_update(player); + mars_recharge_update(player); + divine_intervention_recharge(player); + tooth_and_nail_update(player); + reverse_empress_blink_update(player); + if (effects.HasNullEffect(NULLITEM_REVERSE_STARS) && player.IsExtraAnimationFinished()) + effects.RemoveNullEffect(NULLITEM_REVERSE_STARS, 1); + ibs_charge_update(player); + birthright_dead_bird_update(player); + purgatory_update(player); + isaacs_heart_update(player); + plan_c_update(player); + linger_bean_update(player); + if (player.hallowedGroundCountdown > 0 && --player.hallowedGroundCountdown < 1) + { + player.AddCacheFlags(FRAME_STAT_CACHE); + player.EvaluateItems(); + } + splats_update(player); + if (effects.HasNullEffect(NULLITEM_SPIN_TO_WIN)) + { + if (player.activeItems[ACTIVE_SLOT_PRIMARY].item == COLLECTIBLE_SPIN_TO_WIN) + player.AddActiveCharge(SPIN_TO_WIN_DRAIN, ACTIVE_SLOT_PRIMARY, false, false, false); + else effects.RemoveNullEffect(NULLITEM_SPIN_TO_WIN, 1); + } + if (player.grantedCollectibleCountdown > 0 && --player.grantedCollectibleCountdown < 1) + { + player.grantedCollectibleFlags = 0; + player.AddCacheFlags(FRAME_STAT_CACHE); + player.EvaluateItems(); + } + camo_fade_update(player); + size_update(player); +} diff --git a/src/entity_player_effects.h b/src/entity_player_effects.h new file mode 100644 index 0000000..46a82a1 --- /dev/null +++ b/src/entity_player_effects.h @@ -0,0 +1,5 @@ +#pragma once + +struct Entity_Player; + +void items_frame_update(Entity_Player& player); diff --git a/src/entity_player_evaluate.cpp b/src/entity_player_evaluate.cpp index e120d65..9e52d1c 100644 --- a/src/entity_player_evaluate.cpp +++ b/src/entity_player_evaluate.cpp @@ -42,7 +42,6 @@ constexpr uint32_t DEBUG_HIGH_DAMAGE = 1 << 3; constexpr uint32_t DEBUG_HIGH_LUCK = 1 << 8; constexpr float DEBUG_DAMAGE_BONUS = 40; constexpr float DEBUG_LUCK_BONUS = 50; -constexpr int PILL_TEARS_DOWN = 15; constexpr int PILL_RANGE_DOWN = 11; constexpr int PILL_RANGE_UP = 12; constexpr int PILL_SPEED_DOWN = 13; @@ -61,13 +60,11 @@ constexpr int COOP_BUFF_LUCK = 4; // The constants of the other sections: the collectibles, trinkets, null items and characters they ask about. -constexpr int PILL_TEARS_UP = 16; constexpr int PILL_LARGER = 32; constexpr int PILL_SMALLER = 33; constexpr int COOP_BUFF_SMALLER = 5; constexpr int COOP_BUFF_LARGER = 6; constexpr int NULLITEM_SPIRIT_SHACKLES_SOUL = 101; -constexpr int COLLECTIBLE_2SPOOKY = 554; constexpr int SPRITE_SCALE_UNLOCK = 3; constexpr int ACHIEVEMENT_HUGE = 361; constexpr float SIZE_STEP = 0.322f; @@ -154,22 +151,21 @@ static void bulbs_apply(Entity_Player& p, float& stat, float dimScale, float vib } // The temporary effects the items' frame (update_effects 00794e50) and the shooting part (0077b020) ask about by id -// but do not run yet: collectible effects, null effects and Faded Polaroid's. An effect the frame never asks about -// only counts down there. The frame's own part (00782af0) runs or stops on its own. -constexpr int FRAME_COLLECTIBLE_EFFECTS[] = {28, 65, 130, 147, 160, 181, 325, 326, 409, 475, 497, 522, 543, - 550, 593, 625, 640, 673, 688, 699, 704, 705, 713, 714, 726, 729}; -constexpr int FRAME_NULL_EFFECTS[] = {48, 50, 59, 60, 61, 62, 66, 69, 70, 111, 114, 116, 122, 128}; -constexpr int FRAME_TRINKET_EFFECTS[] = {TRINKET_FADED_POLAROID}; +// but do not run yet: collectible effects and null effects. An effect the frame never asks about only counts down +// there. The frame's own part (00782af0) runs or stops on its own. +constexpr int FRAME_COLLECTIBLE_EFFECTS[] = {28, 130, 160, 181, 325, 326, 409, 522, 543, + 550, 593, 673, 699, 705, 713, 714, 726, 729}; +constexpr int FRAME_NULL_EFFECTS[] = {60, 61, 66, 69, 111, 114, 116, 122, 128}; // Whether the frame runs a temporary effect: the effects written for it, and those it never asks about. static bool is_frame_effect_known(const TemporaryEffect& effect) { - if (is_temporary_effect_plain(effect) || is_passive_effect_plain(effect) || is_trinket_effect_plain(effect)) + if (is_temporary_effect_plain(effect) || is_passive_effect_plain(effect) || is_trinket_effect_plain(effect) || + effect.item->type == ITEM_TRINKET) return true; - std::span unwritten = effect.item->type == ITEM_NULL ? std::span(FRAME_NULL_EFFECTS) - : effect.item->type == ITEM_TRINKET ? std::span(FRAME_TRINKET_EFFECTS) - : std::span(FRAME_COLLECTIBLE_EFFECTS); + std::span unwritten = effect.item->type == ITEM_NULL ? std::span(FRAME_NULL_EFFECTS) + : std::span(FRAME_COLLECTIBLE_EFFECTS); return std::ranges::find(unwritten, effect.item->id) == unwritten.end(); } @@ -300,7 +296,7 @@ static void fire_delay_evaluate(Entity_Player& p, const StatBonuses& bonus) TemporaryEffects& effects = p.temporaryEffects; float crownScale = bonus.crownScale; - float tears = pills_weigh(p, bonus, PILL_TEARS_UP, 0.5f, PILL_TEARS_DOWN, 0.4f); + float tears = pills_weigh(p, bonus, PILLEFFECT_TEARS_UP, 0.5f, PILLEFFECT_TEARS_DOWN, 0.4f); for (int id : {32, 80, 381, 1}) tears = n(id) + tears; tears = e(1) + tears; for (int id : {370, 341, 342}) tears = n(id) + tears; @@ -1043,15 +1039,6 @@ static void tear_flags_evaluate(Entity_Player& p) static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_TEARFLAG); } -// A colour with only its tint, colorize and offset set. -static constexpr ColorMod color_make(std::array tint, std::array colorize = {}, - std::array offset = {}) -{ - return {{tint[0], tint[1], tint[2], tint[3]}, - {colorize[0], colorize[1], colorize[2], colorize[3]}, - {offset[0], offset[1], offset[2]}}; -} - // A colorized white colour, offset alike on every channel. static constexpr ColorMod colorized(float r, float g, float b, float offset = 0) { @@ -1497,13 +1484,11 @@ void Entity_Player::EvaluateItems() } // The collectibles the items' part of the frame (update_effects 00794e50) looks at, which the plain path does not -// cover yet: Analog Stick's aim, Camo Undies, Mars, the Birthright, Akeldama, Judas's kept Book of Belial, Berserk!, -// and the auras and timers of Linger Bean, Dad's Ring, 2Spooky, 120 Volt, Monstrance, Venus, Purgatory, Tooth and Nail -// and IBS. The weapon items are not: the frame never asks for them, their weapons do. -constexpr int FRAME_ITEMS[] = {465, 497, 593, 619, 641, 59, 704, 447, 546, 554, 559, 574, 591, 634, 663, 725}; +// cover yet: Judas's kept Book of Belial and 120 Volt's sparks. +constexpr int FRAME_ITEMS[] = {59, 559}; -// The trinkets the items' frame (00794e50) looks at that it does not run yet: Faded Polaroid and Extension Cord. -constexpr std::array FRAME_TRINKETS = {69, 125}; +// The trinkets the items' frame (00794e50) looks at that it does not run yet: Extension Cord. +constexpr std::array FRAME_TRINKETS = {TRINKET_EXTENSION_CORD}; // What the player's frame does not run yet, empty when it runs its plain path: a character or run it is not // reconstructed for, a temporary effect it asks about but does not run, or an item or trinket it handles. diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index 118ad25..1884c70 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -4,6 +4,8 @@ #include "entity_player_crafting.h" #include "entity_player_passives.h" #include "tainted_characters.h" +#include "boss_ai.h" +#include "entity_bomb.h" #include "entity_effect.h" #include "sfx_manager.h" #include "pocket_items.h" @@ -32,7 +34,6 @@ constexpr int DUCT_TAPE_MODES = 4; constexpr float BODY_TURN_RATE = 0.3f; -constexpr float DEGREES_PER_RADIAN = 57.295776f; constexpr float FLYING_OFFSET_Y = -4; constexpr float HELD_OFFSET_SCALE = 0.65f; constexpr float MOVE_SPEED_BASE = 0.75f; @@ -136,10 +137,8 @@ constexpr int COLLECTIBLE_POINTY_RIB = 544; constexpr int TRINKET_TEARDROP_CHARM = 139; // The effects that stop the player shooting while on: Gamekid, My Little Unicorn and Unicorn Stump. constexpr int NO_SHOOT_EFFECTS[] = {93, 77, 298}; -// The items whose shooting update_shooting does not write yet: No. 2, Maw of the Void, Revelation, Montezuma's -// Revenge, the double tap items (GB Bug, Divine Intervention, Hemoptysis, Lil Portal), Spear of -// Destiny and Bone Spurs. -constexpr int SHOOTING_ITEMS[] = {378, 399, 643, 680, 405, 568, 726, 681, 400, 683}; +// The items whose shooting update_shooting does not write yet: Montezuma's Revenge, Spear of Destiny and Bone Spurs. +constexpr int SHOOTING_ITEMS[] = {680, 400, 683}; // The room render passes the player draws its overlays in: the room itself and the water's surface. static bool is_overlay_pass() @@ -175,13 +174,6 @@ static bool is_zero(Vector v) return v.x == 0 && v.y == 0; } -// The axis a vector mostly points along, as a unit vector (Vector::ToCardinal). -static Vector vector_cardinal(Vector v) -{ - if (std::fabs(v.x) <= std::fabs(v.y)) return vector_make(0, v.y < 0 ? -1 : 1); - return vector_make(v.x < 0 ? -1 : 1, 0); -} - // Flips horizontal input in the mirrored Downpour and Dross rooms. static bool is_mirror_world() { @@ -475,7 +467,7 @@ Vector Entity_Player::walk_direction_update(Vector input) else moveDirection = scaled.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; if (suplexState == 1) moveDirection = (Direction)get_velocity_direction(); if (moveDirection != DIRECTION_NONE) - bodyAngle = angle_lerp(bodyAngle, std::atan2(scaled.y, scaled.x) * DEGREES_PER_RADIAN, BODY_TURN_RATE); + bodyAngle = angle_lerp(bodyAngle, std::atan2(scaled.y, scaled.x) * RADIANS_TO_DEGREES, BODY_TURN_RATE); return scaled; } @@ -1090,6 +1082,319 @@ static WeaponType weapon_override_get(Entity_Player& player) return player.playerType == PLAYER_LILITH_B ? WEAPON_UMBILICAL_WHIP : WEAPON_NULL; } +// What the charged items of 0077b020 read: whether fire is held, whether a forced shot (Marked) releases a full +// charge at once, and the aim. +struct ChargeShot +{ + Vector direction{}; + bool isForced = false; + bool isShootHeld = false; +}; + +// The charged shots' timings: a full charge, the room's first frames that only reset it, and the shot's block. +constexpr uint32_t CHARGE_FULL = 150; +constexpr int CHARGE_ROOM_FRAMES = 5; +constexpr int CHARGE_FIRE_BLOCK = 30; +constexpr int NO_2_FRAMES = 150; +constexpr int MAW_TIMEOUT = 60; +constexpr int REVELATION_TIMEOUT = 30; +constexpr int EVE_CLOT_FRAMES = 59; +constexpr ColorMod NO_2_FART_COLOR = {{1.8f, 0.7f, 1.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// No. 2: fire held for 150 frames drops a butt bomb with the player's bomb effects, with a fart and the candles. +static void number_two_update(Entity_Player& player, bool isShootHeld) +{ + if (!isShootHeld) + { + player.numberTwoFrames = 0; + return; + } + if (++player.numberTwoFrames != NO_2_FRAMES) return; + + TearFlags flags = player.GetBombFlags(false); + flags.set(TEAR_BUTT_BOMB); + auto* bomb = static_cast(g_game->Spawn({.position = player.pos, + .velocity = vector_scale(player.velocity, 0.1f), + .spawner = &player, + .type = ENTITY_BOMB, + .variant = BOMB_BUTT, + .seed = Random()})); + bomb->isLoadCostumes = true; + bomb->tearFlags = flags; + npc_sound_play(SOUND_FART, 1, 2, 1); + Entity* fart = g_game->Spawn({.position = player.pos, .type = ENTITY_EFFECT, .variant = EFFECT_FART, .seed = Random()}); + fart->SetColor(NO_2_FART_COLOR, -1, 255, false, true); + fart->Update(); + player.ShootCandle({}); +} + +// 007c8dc0 Maw of the Void's ring: a black brimstone ring following the player, lifted to its mouth and drawn in +// front, pulsing with the player's tear effects (never growing or shrinking) and its damage, for a timeout. +Entity_Laser* Entity_Player::SpawnMawOfVoid(int timeout) +{ + constexpr float MAW_LIFT = -20; + npc_sound_play(SOUND_MAW_OF_VOID, 1, 2, 1); + auto* laser = static_cast(g_game->Spawn({.position = pos, .spawner = this, + .subType = LASER_SUBTYPE_RING_FOLLOW_PARENT, + .type = ENTITY_LASER, .variant = LASER_THICK_RED, + .seed = Random()})); + laser->posOffset = vector_make(0, MAW_LIFT); + laser->parent = this; + laser->renderDepthOffset = TECH_LASER_FRONT_DEPTH; + laser->tearFlags = tearFlags; + laser->tearFlags.reset(TEAR_GROW); + laser->tearFlags.reset(TEAR_SHRINK); + laser->tearFlags.set(TEAR_PULSE); + laser->SetCollisionDamage(damage); + laser->timeout = timeout; + laser->spawnerEntity = this; + return laser; +} + +// A charged item's timer: it counts while fire is held, and is let go (firing past a full charge, after a room's +// first frames) when fire is released or a forced shot comes in. Whether it fired. +static bool charge_release(uint32_t& timer, const ChargeShot& shot) +{ + if (shot.isShootHeld && !(shot.isForced && timer > CHARGE_FULL)) + { + timer++; + return false; + } + if (g_game->room->GetFrameCount() <= CHARGE_ROOM_FRAMES) return false; + bool isFired = timer > CHARGE_FULL; + timer = 0; + return isFired; +} + +// A released charged shot blocks fire for a second unless forced, and leaves no fire direction. +static void charge_fired(Entity_Player& player, const ChargeShot& shot) +{ + if (!shot.isForced) player.fireBlockCooldown = std::max(player.fireBlockCooldown, CHARGE_FIRE_BLOCK); + player.fireDirection = DIRECTION_NONE; +} + +// Maw of the Void: a full charge (shown by its costume) lets out a ring of black brimstone, opening the costume's +// mouth along the last aim. Revelation: a full charge fires its holy beam along the delayed aim with the player's +// tear effects, drawn behind the player when aiming up. +static void charged_items_update(Entity_Player& player, const ChargeShot& shot) +{ + if (player.HasCollectible(COLLECTIBLE_MAW_OF_THE_VOID)) + { + uint32_t before = player.mawOfTheVoidChargeTimer; + if (charge_release(player.mawOfTheVoidChargeTimer, shot)) + { + player.SpawnMawOfVoid(MAW_TIMEOUT)->Update(); + charge_fired(player, shot); + player.RemoveCostume(g_manager->itemConfig.GetNullItem(NULLITEM_MAW_MARK)); + constexpr std::string_view HEAD_SHOOT[] = {"HeadLeftShoot", "HeadUpShoot", "HeadRightShoot", "HeadDownShoot"}; + player.PlayCollectibleAnim(COLLECTIBLE_MAW_OF_THE_VOID, false, + HEAD_SHOOT[vector_to_direction(vector_cardinal(player.lastDirection))], -1); + } + else if (player.mawOfTheVoidChargeTimer == before + 1 && player.mawOfTheVoidChargeTimer == CHARGE_FULL) + player.AddCostume(g_manager->itemConfig.GetNullItem(NULLITEM_MAW_MARK), false); + } + if (player.HasCollectible(COLLECTIBLE_REVELATION) && charge_release(player.revelationChargeTimer, shot)) + { + Vector aim = player.delayed_shoot_direction(); + Entity_Laser* beam = Entity_Laser::ShootAngle({.position = player.pos, + .posOffset = player.GetLaserOffset(LASER_OFFSET_BRIMSTONE, aim), + .source = &player, + .angleDegrees = vector_angle(aim), + .timeout = REVELATION_TIMEOUT, + .variant = LASER_LIGHT_BEAM}); + beam->SetCollisionDamage(player.meleeDamage); + beam->tearFlags = player.tearFlags; + beam->renderDepthOffset = shot.direction.y <= -TECH_LASER_FACING ? TECH_LASER_BACK_DEPTH : TECH_LASER_FRONT_DEPTH; + charge_fired(player, shot); + } +} + +// Whether Tainted Eve has health to spend on a clot: a golden or eternal heart, red hearts beyond the rotten ones +// or with soul and bone hearts beside them, or two soul and bone hearts. +static bool is_clot_affordable(Entity_Player& player) +{ + int soulAndBone = player.boneHearts + player.soulHearts; + if (player.goldenHearts >= 1 || player.eternalHearts >= 1) return true; + if (player.redHearts >= 1 && soulAndBone >= 1) return true; + return player.redHearts - player.rottenHearts >= 2 || soulAndBone >= 2; +} + +// Tainted Eve's Sumptorium: fire held for a second (with health to spend) forms a clot. +static void eve_clot_update(Entity_Player& player, bool isShootHeld) +{ + if (!isShootHeld || !is_clot_affordable(player)) + { + player.eveSumptoriumCharge = 0; + return; + } + if (++player.eveSumptoriumCharge <= EVE_CLOT_FRAMES) return; + player.eveSumptoriumCharge = 0; + player.SpawnClot(player.pos, false); +} + +// Epiphora: fire held one way speeds the tears up frame by frame (to 180), and turning away or letting go resets it, +// though the bone keeps it 10 frames past each swing. A reset on an interpolated frame still sets off the fire +// items. Nothing resets while fire is blocked. +static void epiphora_update(Entity_Player& player, const ChargeShot& shot) +{ + constexpr int EPIPHORA_GRACE = 10; + constexpr int EPIPHORA_CHARGE_MAX = 180; + int& grace = player.epiphoraGrace; + int& faced = player.epiphoraDirection; + int direction = vector_to_direction(shot.direction); + + if (grace > 0) grace--; + if (!player.HasWeaponType(WEAPON_BONE)) grace = 0; + else if (!shot.isShootHeld || faced == DIRECTION_NONE || direction == faced) + { + Weapon* weapon = player.weapons[1].get(); + if (weapon && (int)weapon->fireDelay > 0) grace = EPIPHORA_GRACE; + if (shot.isShootHeld) faced = direction; + } + else + { + grace = -1; + faced = direction; + } + + bool isTurned = vector_to_direction(player.aimDirection) != direction && !vector_is_zero(player.aimDirection); + bool isInterpolation = player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE); + if (grace < 0 || (grace == 0 && (!shot.isShootHeld || isTurned))) + { + if (player.fireBlockCooldown != 0) return; + player.cacheFlags |= CACHE_FIREDELAY; + player.epiphoraCharge = 0; + faced = DIRECTION_NONE; + player.EvaluateItems(); + bool isFiring = player.isCoopGhost || player.canShoot; + if (!isInterpolation || !isFiring || !player.IsExtraAnimationFinished() || g_game->stageTransition.state != 0) + return; + player.ClearEntityFlags(FLAG_INTERPOLATION_UPDATE); + player.trigger_fire_item_effects(shot.direction, shot.isShootHeld); + player.AddEntityFlags(FLAG_INTERPOLATION_UPDATE); + } + else if (!isInterpolation && player.epiphoraCharge < EPIPHORA_CHARGE_MAX) + { + player.cacheFlags |= CACHE_FIREDELAY; + player.epiphoraCharge++; + player.EvaluateItems(); + } +} + +// The double tap items' reach and timings: the window between taps, the familiars' staggered shots, Divine +// Intervention's shield and its recharge, and the flash it gives. +constexpr int DOUBLE_TAP_WINDOW = 11; +constexpr int DOUBLE_TAP_FAMILIAR_STAGGER = 12; +constexpr int DIVINE_COOLDOWN = 90; +constexpr float DIVINE_SHIELD_SPEED = 10; +constexpr int DIVINE_SHIELD_TIMEOUT = 30; +constexpr int DIVINE_FLASH_FRAMES = 8; +constexpr int DIVINE_FLASH_PRIORITY = 2; +constexpr ColorMod DIVINE_FLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1.2f, 1.2f, 1}}; + +// What a double tap sends: GB Bug's and Lil Portal's familiars fire one after another along it, Divine Intervention +// throws its shield when recharged, and Hemoptysis sneezes blood once. +static void double_tap_fire(Entity_Player& player, Vector direction) +{ + constexpr std::array, 2> TAP_FAMILIARS = {{{COLLECTIBLE_LIL_PORTAL, Entity_Familiar::LIL_PORTAL}, + {COLLECTIBLE_GB_BUG, Entity_Familiar::GB_BUG}}}; + if (Room::IsMirrorWorld()) direction.x = -direction.x; + int stagger = 0; + for (const auto& [item, familiarVariant] : TAP_FAMILIARS) + { + if (!player.HasCollectible(item)) continue; + for (Entity* entity : entity_query(ENTITY_FAMILIAR, familiarVariant)) + { + auto* familiar = static_cast(entity); + if (familiar->player != &player || familiar->fireCooldown < 0 || familiar->fireCooldown > stagger) continue; + familiar->fireCooldown = stagger; + familiar->targetPosition = direction; + stagger += DOUBLE_TAP_FAMILIAR_STAGGER; + } + } + + if (player.HasCollectible(COLLECTIBLE_DIVINE_INTERVENTION) && player.divineInterventionCooldown < 1) + { + player.divineInterventionCooldown = DIVINE_COOLDOWN; + npc_sound_play(SOUND_DIVINE_INTERVENTION, 1, 2, 1); + if (player.divineShield) player.divineShield->Remove(); + auto* shield = static_cast(g_game->Spawn({.position = player.pos, .type = ENTITY_EFFECT, + .variant = EFFECT_DIVINE_INTERVENTION, + .seed = Random()})); + player.divineShield = shield; + shield->parent = &player; + shield->rotation = vector_angle(direction); + Vector heading = vector_from_angle(shield->rotation); + shield->pos = vector_sub(player.pos, vector_scale(heading, DIVINE_SHIELD_SPEED)); + shield->velocity = vector_scale(heading, DIVINE_SHIELD_SPEED); + shield->SetTimeout(DIVINE_SHIELD_TIMEOUT); + shield->Update(); + player.SetColor(DIVINE_FLASH, DIVINE_FLASH_FRAMES, DIVINE_FLASH_PRIORITY, true, true); + } + if (player.HasCollectible(COLLECTIBLE_HEMOPTYSIS) && !player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_HEMOPTYSIS)) + reconstruction_missing("Entity_Player::update_shooting 0077b020 (Hemoptysis' sneeze, Weapon_Brimstone::fire 00a02890)"); +} + +// The double tap of 0077b020: with GB Bug, Divine Intervention, Hemoptysis or Lil Portal and the controls on, a +// shoot direction pressed twice within 11 frames fires them. +static void double_tap_update(Entity_Player& player) +{ + constexpr ButtonAction TAP_ACTIONS[] = {ACTION_SHOOT_LEFT, ACTION_SHOOT_UP, ACTION_SHOOT_RIGHT, ACTION_SHOOT_DOWN}; + bool isTapping = player.HasCollectible(COLLECTIBLE_GB_BUG) || player.HasCollectible(COLLECTIBLE_DIVINE_INTERVENTION) || + player.HasCollectible(COLLECTIBLE_HEMOPTYSIS) || player.HasCollectible(COLLECTIBLE_LIL_PORTAL); + if (!isTapping || !player.isControlsEnabled) return; + + for (int side = 0; side < (int)std::size(TAP_ACTIONS); side++) + { + if (!input_is_action_triggered(TAP_ACTIONS[side], player.controllerIndex, &player)) continue; + if (player.doubleTapDirection == side && player.doubleTapFrames < DOUBLE_TAP_WINDOW) + double_tap_fire(player, vector_from_direction(side)); + player.doubleTapDirection = side; + player.doubleTapFrames = 0; + } +} + +// The headless spray of 0077b020: bleeding from Scissors or one's own bleed out, every second frame one time in two, +// the player (unless drawn whole) spits a blood tear sized and hurting by three quarters of its melee damage, thrown +// along the aim when aiming, scattered and carried by its motion, falling fast. +static void headless_blood_spray(Entity_Player& player, const PassiveShot& shot) +{ + constexpr float BLOOD_SPRAY_DAMAGE_SCALE = 0.75f; + constexpr float BLOOD_SPRAY_AIM_SPEED = 8; + constexpr float BLOOD_SPRAY_SCATTER = 2; + constexpr float BLOOD_SPRAY_HEIGHT = -12; + constexpr float BLOOD_SPRAY_FALL_ACCEL = 0.5f; + constexpr float BLOOD_SPRAY_FALL_RANGE = 10; + constexpr float BLOOD_SPRAY_FALL_MIN = 4; + bool isBleeding = player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_SCISSORS) || + (player.HasEntityFlags(FLAG_BLEED_OUT) && player.bleedSource.entity == &player); + if (!isBleeding || player.IsFullSpriteRendering() || random_below(2) != 0) return; + + float damage = player.meleeDamage * BLOOD_SPRAY_DAMAGE_SCALE; + constexpr float SIZE_ROOT = 0.15f; + constexpr float SIZE_LINEAR = 0.04f; + constexpr float SIZE_BASE = 0.6f; + constexpr float SIZE_SCALE = 0.9f; + constexpr float SCALE_STEP = 0.4f; + constexpr float SCALE_JITTER = 0.05f; + float size = (std::sqrt(damage) * SIZE_ROOT + damage * SIZE_LINEAR + SIZE_BASE) * SIZE_SCALE; + float scale = (float)random_below(2) * SCALE_STEP + SIZE_SCALE; + scale = random_unit() * SCALE_JITTER + scale; + Vector aim = vector_normalized(shot.direction); + Vector velocity = shot.isAiming ? vector_scale(aim, BLOOD_SPRAY_AIM_SPEED) : Vector{}; + velocity = vector_add(velocity, vector_scale(vector_scale(random_direction(), random_unit()), BLOOD_SPRAY_SCATTER)); + velocity = vector_add(velocity, player.GetTearMovementInheritance(aim, INHERIT_ALWAYS)); + + auto* tear = static_cast(g_game->Spawn({.position = player.pos, .velocity = velocity, .spawner = &player, + .type = ENTITY_TEAR, .variant = TEAR_BLOOD, .seed = Random()})); + tear->SetScale(scale * size); + tear->height = BLOOD_SPRAY_HEIGHT; + tear->fallingAccel += BLOOD_SPRAY_FALL_ACCEL; + tear->fallingSpeed = tear->fallingSpeed - random_unit() * BLOOD_SPRAY_FALL_RANGE - BLOOD_SPRAY_FALL_MIN; + tear->SetCollisionDamage(scale * damage); + tear->Update(); +} + // 0077b020 Shooting, each frame: reads the shoot input, turns the head to the shot (or to the walk when idle), counts // the weapons' delays down and fires them, blinks the eyes while shooting and keeps the recent shot directions. The // items, item states and characters that change shooting stop the game until reached. @@ -1151,7 +1456,10 @@ void Entity_Player::update_shooting() bool canFire = isCoopGhost || canShoot; Vector headAim = shootDirection; - if (marked_target_update(*this, {markedAim, isInterpolation, isShootHeld})) isShootHeld = true; + bool isForcedShot = marked_target_update(*this, {markedAim, isInterpolation, isShootHeld}); + if (isForcedShot) isShootHeld = true; + if (HasCollectible(COLLECTIBLE_NO_2) && game.stageTransition.state == 0 && isInputAllowed && fireBlockCooldown < 1) + number_two_update(*this, isShootHeld); if (game.dailyChallenge._specialDailyId == SPECIAL_DAILY_BUTTER_BEAN) reconstruction_missing("Entity_Player::update_shooting 0077b020 (the Butter Bean daily)"); @@ -1194,8 +1502,8 @@ void Entity_Player::update_shooting() for (int item : SHOOTING_ITEMS) if (HasCollectible(item)) reconstruction_missing("Entity_Player::update_shooting 0077b020 (shooting items)"); bool isFireReady = IsExtraAnimationFinished() && game.stageTransition.state == 0 && isInputAllowed; - if (isFireReady && playerType == PLAYER_EVE_B && !isInterpolation) - reconstruction_missing("Entity_Player::update_shooting 0077b020 (Tainted Eve's clots)"); + if (isFireReady) charged_items_update(*this, {shootDirection, isForcedShot, isShootHeld}); + if (isFireReady && playerType == PLAYER_EVE_B && !isInterpolation) eve_clot_update(*this, isShootHeld); uint32_t modifiers = (uint32_t)GetWeaponModifiers(); WeaponType overriding = weapon_override_get(*this); @@ -1235,10 +1543,9 @@ void Entity_Player::update_shooting() blinkTime = std::max(blinkTime, POINTY_RIB_BLINK); PassiveShot shot{shootDirection, isAiming, isShootHeld}; trinity_shield_update(*this, shot); + double_tap_update(*this); doubleTapFrames++; - if (!isInterpolation && IsFrame(2, 0) && - (temporaryEffects.HasCollectibleEffect(COLLECTIBLE_SCISSORS) || HasEntityFlags(FLAG_BLEED_OUT))) - reconstruction_missing("Entity_Player::update_shooting 0077b020 (the headless blood spray)"); + if (!isInterpolation && IsFrame(2, 0)) headless_blood_spray(*this, shot); float savedLuck = luck; if (HasTrinket(TRINKET_TEARDROP_CHARM)) { @@ -1268,8 +1575,7 @@ void Entity_Player::update_shooting() sprite.SetOverlayFrame(headAnim, blinkFrame); costume_heads_update(blinkFrame); } - if (isFireReady && HasCollectible(COLLECTIBLE_EPIPHORA)) - reconstruction_missing("Entity_Player::update_shooting 0077b020 (Epiphora)"); + if (isFireReady && HasCollectible(COLLECTIBLE_EPIPHORA)) epiphora_update(*this, {shootDirection, false, isShootHeld}); if (fireBlockCooldown > 0) return; aimDirection = shootDirection; diff --git a/src/entity_player_items.cpp b/src/entity_player_items.cpp index a64cf8a..4014d06 100644 --- a/src/entity_player_items.cpp +++ b/src/entity_player_items.cpp @@ -571,7 +571,6 @@ constexpr int COLLECTIBLE_COUNT_UNLOCK = 50; constexpr int ACHIEVEMENT_MANY_COLLECTIBLES = 330; constexpr int EVENT_BLOOD_CLOT = 200; constexpr int EVENT_RUBBER_CEMENT = 201; -constexpr int PILL_TEARS_UP = 16; constexpr int BINGE_EATER_STEW_FRAMES = 900; constexpr int T_BETHANY_HEART_CAP = 12; @@ -783,7 +782,7 @@ void Entity_Player::collectible_unlocks_check(int collectibleId, ItemConfig_Item if (collectibleId == COLLECTIBLE_BLOOD_CLOT) save.IncreaseEventCounter(EVENT_BLOOD_CLOT, 1); else if (collectibleId == COLLECTIBLE_RUBBER_CEMENT) save.IncreaseEventCounter(EVENT_RUBBER_CEMENT, 1); - int tearsUps = PILL_TEARS_UP < (int)pillEffectUses.size() ? pillEffectUses[PILL_TEARS_UP] : 0; + int tearsUps = PILLEFFECT_TEARS_UP < (int)pillEffectUses.size() ? pillEffectUses[PILLEFFECT_TEARS_UP] : 0; for (ItemConfig_Item* tagged : g_manager->itemConfig.GetTaggedItems(TAG_TEARS_UP)) if (tagged->IsCollectible()) tearsUps += collectibleCounts[tagged->id]; if (tearsUps >= TEARS_UP_UNLOCK_COUNT) save.TryUnlock(ACHIEVEMENT_TEARS_UP_ITEMS); @@ -793,7 +792,7 @@ void Entity_Player::collectible_unlocks_check(int collectibleId, ItemConfig_Item } // The pickups, coins, keys, bombs and hearts a collectible gives the first time it is taken. Tainted Bethany takes -// at most six red hearts. +// at most six red hearts. Containers past the cap are counted for a reroll to take back first. void Entity_Player::collectible_pickups_add(ItemConfig_Item& item) { if (g_game->deathmatchManager.is_active()) @@ -810,9 +809,8 @@ void Entity_Player::collectible_pickups_add(ItemConfig_Item& item) AddBlackHearts(item.addBlackHearts); HealthType health = GetHealthType(); - bool isCapped = (health == HEALTH_COIN || health == HEALTH_DEFAULT) && - item.addMaxHearts - maxHearts + maxHeartsBefore > 0; - if (isCapped) reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (heart containers over the cap)"); + int overflow = item.addMaxHearts - maxHearts + maxHeartsBefore; + if ((health == HEALTH_COIN || health == HEALTH_DEFAULT) && overflow > 0) itemHeartsOverflow += overflow; } // What taking a collectible passes its own pickup effect: the item, the charge (Dead Cat's lives), the active slot and @@ -1099,6 +1097,84 @@ static void dogma_gain(Entity_Player& p) p.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_HOLY_MANTLE, true, 1); } +// Consolation Prize's first pickup: a step up of the weakest of speed, tears, damage and range (a little noise breaks +// ties), then the pickups the player has least of: three coins, a key, a bomb (Tainted ???'s poop counted instead), +// a soul heart for Bethany's soul charges or two red hearts for Tainted Bethany's blood charges. Each spot is found +// after its seed is drawn and the pickups drop one after another. +constexpr float CONSOLATION_NONE = 1e10f; +constexpr float CONSOLATION_NOISE_UNIT = 2.3283061e-10f; +constexpr float CONSOLATION_NOISE = 0.02f; +constexpr float CONSOLATION_NOISE_BIAS = 0.01f; +constexpr float CONSOLATION_SPOT_STEP = 48; +constexpr float CONSOLATION_PICKUP_WEIGHT = 3; + +struct ConsolationDrop +{ + int variant = 0; + int subType = 0; + int count = 0; +}; + +constexpr std::array CONSOLATION_DROPS = {{{PICKUP_COIN, 0, 3}, + {PICKUP_KEY, 0, 1}, + {PICKUP_BOMB, 0, 1}, + {PICKUP_HEART, HEART_SOUL, 1}, + {PICKUP_HEART, HEART_FULL, 2}}}; + +// Pow as the original's wrapper takes it, through doubles. +static float pow_float(float base, float exponent) +{ + return (float)std::pow((double)base, (double)exponent); +} + +static void consolation_prize_gain(Entity_Player& p, RNG& rng) +{ + std::array stats = {p.moveSpeed * 4.5f - 2, pow_float(30 / (p.maxFireDelay + 1), 0.75f), + pow_float(p.damage, 0.56f) * 2.231179f - 2, (p.tearRange - 230) / 60 + 2}; + std::array modifiers = {&p.speedModifier, &p.fireDelayModifier, &p.damageModifier, &p.tearRangeModifier}; + constexpr std::array CACHES = {CACHE_SPEED, CACHE_FIREDELAY, CACHE_DAMAGE, CACHE_RANGE}; + float lowest = CONSOLATION_NONE; + int weakest = -1; + for (int i = 0; i < (int)stats.size(); i++) + { + rng.Next(); + float score = stats[i] - CONSOLATION_NOISE_BIAS + (float)rng._seed * CONSOLATION_NOISE_UNIT * CONSOLATION_NOISE; + if (score < lowest) weakest = i; + lowest = std::min(lowest, score); + } + if (weakest >= 0) + { + (*modifiers[weakest])++; + p.cacheFlags |= CACHES[weakest]; + } + p.EvaluateItems(); + + bool isPoopPlayer = p.playerType == PLAYER_BLUEBABY_B; + std::array counts = {(float)p.numCoins, (float)p.numKeys * CONSOLATION_PICKUP_WEIGHT, + (float)(isPoopPlayer ? p.poopMana : p.numBombs) * CONSOLATION_PICKUP_WEIGHT, + CONSOLATION_NONE, CONSOLATION_NONE}; + if (p.playerType == PLAYER_BETHANY) counts[3] = (float)p.effectiveSoulCharge * 2 - 1; + if (p.playerType == PLAYER_BETHANY_B) counts[4] = (float)p.effectiveBloodCharge * 2 - 1; + float least = CONSOLATION_NONE; + int pick = -1; + for (int i = 0; i < (int)counts.size(); i++) + { + rng.Next(); + if (counts[i] >= least && (counts[i] != least || !(rng._seed & 1))) continue; + least = counts[i]; + pick = i; + } + if (pick < 0) return; + + const ConsolationDrop& drop = CONSOLATION_DROPS[pick]; + for (int i = 0; i < drop.count; i++) + { + uint32_t seed = rng.Next(); + Vector position = room_free_pickup_position_find({p.pos, CONSOLATION_SPOT_STEP}); + pickup_drop(position, {drop.variant, drop.subType, seed, nullptr}, i); + } +} + // The first pickup's drops of the items that drop a fixed set of pickups. Whether the item is one of them. static bool collectible_drops_apply(Entity_Player& p, const CollectibleGain& gain, RNG& rng) { @@ -1374,9 +1450,11 @@ static void collectible_effect_apply(Entity_Player& p, const CollectibleGain& ga late_collectible_gain(p, gain.type, isFirst); return; case 619: return birthright_gain(p, isFirst); + case 644: + if (isFirst) consolation_prize_gain(p, rng); + return; case 588: case 593: - case 644: case 732: reconstruction_missing( (std::string("Entity_Player::AddCollectible 0075f0e0 (the pickup effect of ") + diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp index ec46ddf..2de9348 100644 --- a/src/entity_player_missing.cpp +++ b/src/entity_player_missing.cpp @@ -1,18 +1,46 @@ #include "entity_player.h" +#include "entity_familiar.h" +#include "game.h" #include "log.h" +#include -void Entity_Player::StopExtraAnimation() { reconstruction_missing("Entity_Player::StopExtraAnimation 0058e230"); } +// 0058e230 Ends the extra and item animations. +void Entity_Player::StopExtraAnimation() +{ + isPlayingExtraAnimation = false; + isPlayingItemAnimation = false; +} void Entity_Player::moms_bracelet_grab() { reconstruction_missing("Entity_Player::moms_bracelet_grab 005b1a20"); } -void Entity_Player::ResetDamageCooldown() { reconstruction_missing("Entity_Player::ResetDamageCooldown 0060d090"); } -Vector Entity_Player::SpriteScale() { reconstruction_missing("Entity_Player::SpriteScale 0060d0a0"); } +// 0060d0a0 The player's own sprite scale. +Vector Entity_Player::SpriteScale() +{ + return playerSpriteScale; +} void Entity_Player::QueueExtraAnimation(std::string_view) { reconstruction_missing("Entity_Player::QueueExtraAnimation 007539c0"); } void Entity_Player::cycle_spectate_target() { reconstruction_missing("Entity_Player::cycle_spectate_target 007585b0"); } -void Entity_Player::RemoveBlueFly() { reconstruction_missing("Entity_Player::RemoveBlueFly 00759b80"); } -void Entity_Player::AddLeprosy() { reconstruction_missing("Entity_Player::AddLeprosy 00759b90"); } -Entity* Entity_Player::AddBoneOrbital(Vector) { reconstruction_missing("Entity_Player::AddBoneOrbital 00759bc0"); } +// 00759b80 Counts a blue fly gone. +void Entity_Player::RemoveBlueFly() +{ + numBlueFlies--; +} +// 00759b90 Adds a Leprosy orbital, up to three. +void Entity_Player::AddLeprosy() +{ + constexpr int LEPROSY_MAX = 3; + if (numLeprosy >= LEPROSY_MAX) return; + cacheFlags |= CACHE_FAMILIARS; + numLeprosy++; + EvaluateItems(); +} +// 00759bc0 Spawns a bone orbital at a position. +Entity* Entity_Player::AddBoneOrbital(Vector position) +{ + return g_game->Spawn({.position = position, .spawner = this, .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::BONE_ORBITAL, .seed = Random()}); +} Entity* Entity_Player::AddSwarmFlyOrbital(Vector) { reconstruction_missing("Entity_Player::AddSwarmFlyOrbital 00759bf0"); @@ -22,7 +50,6 @@ void Entity_Player::GetNPCTarget() { reconstruction_missing("Entity_Player::GetN bool Entity_Player::VoidHasCollectible(int) { reconstruction_missing("Entity_Player::VoidHasCollectible 007711a0"); } bool Entity_Player::replace_trinket() { reconstruction_missing("Entity_Player::replace_trinket 00772530"); } void Entity_Player::update_effects() { reconstruction_missing("Entity_Player::update_effects 00794e50"); } -void Entity_Player::update_ladder() { reconstruction_missing("Entity_Player::update_ladder 0079f3c0"); } void Entity_Player::ReviveFromTrinket(uint32_t) { reconstruction_missing("Entity_Player::ReviveFromTrinket 007a3430"); } void Entity_Player::remove_twin() { reconstruction_missing("Entity_Player::remove_twin 007a37c0"); } void Entity_Player::AnimateTrinket(int, std::string_view, std::string_view) @@ -33,7 +60,14 @@ void Entity_Player::AnimateTrapdoor() { reconstruction_missing("Entity_Player::A // 007abc10 Plays the rise up a beam of light. void Entity_Player::AnimateLightTravel() { PlayExtraAnimation("LightTravel"); } void Entity_Player::AnimateAppear() { reconstruction_missing("Entity_Player::AnimateAppear 007abcb0"); } -void Entity_Player::AddPrettyFly() { reconstruction_missing("Entity_Player::AddPrettyFly 007abdf0"); } +// 007abdf0 Adds a Pretty Fly, happily. +void Entity_Player::AddPrettyFly() +{ + pillEffectUses[PILLEFFECT_PRETTY_FLY]++; + cacheFlags |= CACHE_FAMILIARS; + EvaluateItems(); + AnimateHappy(); +} void Entity_Player::TryRemoveNullCostume(int) { reconstruction_missing("Entity_Player::TryRemoveNullCostume 007ad400"); @@ -60,10 +94,13 @@ uint32_t Entity_Player::GetGlitchBabySubType() { reconstruction_missing("Entity_Player::GetGlitchBabySubType 007c2e90"); } -void Entity_Player::SetShootingCooldown(int) { reconstruction_missing("Entity_Player::SetShootingCooldown 007c37f0"); } +// 007c37f0 Blocks fire for at least this many frames. +void Entity_Player::SetShootingCooldown(int cooldown) +{ + fireBlockCooldown = std::max(fireBlockCooldown, cooldown); +} void Entity_Player::add_random_stat_up(RNG*) { reconstruction_missing("Entity_Player::add_random_stat_up 007c3980"); } void Entity_Player::dash_impact() { reconstruction_missing("Entity_Player::dash_impact 007c8240"); } -Entity_Laser* Entity_Player::SpawnMawOfVoid(int) { reconstruction_missing("Entity_Player::SpawnMawOfVoid 007c8dc0"); } Entity* Entity_Player::ShootRedCandle(Vector) { reconstruction_missing("Entity_Player::ShootRedCandle 007c9130"); } Entity* Entity_Player::ShootBlueCandle(Vector) { reconstruction_missing("Entity_Player::ShootBlueCandle 007c9350"); } void Entity_Player::apply_victory_lap_penalty(uint32_t) @@ -86,7 +123,14 @@ float Entity_Player::GetGreedDonationJamChance(PersistentGameData&) reconstruction_missing("Entity_Player::GetGreedDonationJamChance 007cbb90"); } void Entity_Player::hallowed_ground_add(int) { reconstruction_missing("Entity_Player::hallowed_ground_add 007cbc60"); } -void Entity_Player::resolve_tainted_soul() { reconstruction_missing("Entity_Player::resolve_tainted_soul 007cbcb0"); } + +// 007cbcb0 The player a Tainted Soul acts through: the Tainted Forgotten it is twinned with, else the player itself. +Entity_Player* Entity_Player::resolve_tainted_soul() +{ + Entity_Player* twin = twin_get(); + return playerType == PLAYER_THESOUL_B && twin ? twin : this; +} + void Entity_Player::GetGlyphOfBalanceDrop(int*, int*) { reconstruction_missing("Entity_Player::GetGlyphOfBalanceDrop 007d12c0"); @@ -122,12 +166,21 @@ void Entity_Player::twins_duplicate_familiars(int) } const std::string& Entity_Player::GetName() { reconstruction_missing("Entity_Player::GetName 007e9280"); } void Entity_Player::TriggerRoomExit() { reconstruction_missing("Entity_Player::TriggerRoomExit 00832850"); } +// 0085e200 Whether red and soul hearts fill the containers. bool Entity_Player::HasFullHeartsAndSoulHearts() { - reconstruction_missing("Entity_Player::HasFullHeartsAndSoulHearts 0085e200"); + return maxHearts <= soulHearts + redHearts; +} +// 0085e260 Lengthens the frames the controls stay off. +void Entity_Player::AddControlsCooldown(int frames) +{ + controlsCooldown += frames; +} +// 0085e280 The last hit's damage flags. +uint64_t Entity_Player::GetLastDamageFlags() +{ + return lastDamageFlags; } -void Entity_Player::AddControlsCooldown(int) { reconstruction_missing("Entity_Player::AddControlsCooldown 0085e260"); } -uint64_t Entity_Player::GetLastDamageFlags() { reconstruction_missing("Entity_Player::GetLastDamageFlags 0085e280"); } void Entity_Player::CheckPoopSpellQueue(Vector) { reconstruction_missing("Entity_Player::CheckPoopSpellQueue 0095ffb0"); diff --git a/src/entity_player_room.cpp b/src/entity_player_room.cpp index 4d02210..11aeaaf 100644 --- a/src/entity_player_room.cpp +++ b/src/entity_player_room.cpp @@ -7,6 +7,7 @@ #include "grid_entity_door.h" #include "log.h" #include "manager.h" +#include "npc_basement.h" #include "room.h" #include @@ -34,6 +35,7 @@ constexpr int DOG_TOOTH_SECRET_DELAY = 30; constexpr int DOG_TOOTH_ROCK_DELAY = 60; constexpr int DELAYED_SOUND_FRAMES = 2; constexpr int POKE_GO_CHANCE = 5; +constexpr size_t POKE_GO_MESSAGE_SIZE = 256; constexpr int GREED_WAVE_MAX = 12; constexpr int DOOR_STOP_UNLOCK_COPIES = 3; constexpr int DOOR_STOP_BOSS_RUSH_COPIES = 2; @@ -170,6 +172,28 @@ static void dog_tooth_apply(Entity_Player& player) constexpr int BROKEN_WATCH_PERIOD = 4; constexpr uint32_t BROKEN_WATCH_FAST_ODDS = 10; +// Poke Go's catch: one of six enemies, charmed for good by the player, stepped once and kept from shutting the doors, +// with its name in the fortune line. +constexpr std::array POKE_GO_ENEMIES = {ENTITY_ATTACKFLY, ENTITY_POOTER, ENTITY_ONE_TOOTH, + ENTITY_FAT_BAT, ENTITY_GAPER, ENTITY_VIS}; + +static void poke_go_spawn(Entity_Player& player) +{ + int type = POKE_GO_ENEMIES[player.collectibleRNGs[COLLECTIBLE_POKE_GO].Next() % POKE_GO_ENEMIES.size()]; + Entity* spawned = g_game->Spawn({.position = player.pos, .spawner = &player, .type = type, .seed = Random()}); + auto* npc = dynamic_cast(spawned); + npc->AddCharmed(EntityRef(&player), -1, false, false); + npc->Update(); + npc->isCanShutDoors = false; + + EntityConfig_Entity* config = g_manager->entityConfig.GetEntity(type, 0, 0); + std::string name = config ? config->GetName(NAME_LANGUAGE_CURRENT) : ""; + std::string format(string_table_translate(g_manager->stringTable, "#POKE_GO_APPEAR_NOTIFY")); + std::array message{}; + std::snprintf(message.data(), message.size(), format.c_str(), name.c_str()); + g_game->hud.show_fortune_line(message.data()); +} + // What the player's items do on entering a room after it is placed: Toxic Shock's clouds, Poke Go's charmed enemy, // Dog Tooth's sounds, the locusts, a co-op baby's shield, the Broken Watch, the weapons' new room reset and the // poop under the player. @@ -183,8 +207,7 @@ static void room_items_apply(Entity_Player& player) if (player.HasCollectible(COLLECTIBLE_TOXIC_SHOCK) && !room.IsClear()) room.fxLayers.AddPoopFx(TOXIC_SHOCK_COLOR); if (player.HasCollectible(COLLECTIBLE_POKE_GO) && isFresh && player.collectibleRNGs[COLLECTIBLE_POKE_GO].RandomInt(POKE_GO_CHANCE) == 0) - reconstruction_missing("Entity_Player::room_enter 007a6c50: Poke Go's charmed enemy (Entity::SetVisibleFlag, " - "HUD::show_fortune_line with #POKE_GO_APPEAR_NOTIFY)"); + poke_go_spawn(player); if (player.HasCollectible(COLLECTIBLE_DOG_TOOTH)) dog_tooth_apply(player); if (isFresh) player.spawn_locusts(); @@ -223,6 +246,55 @@ static void room_items_apply(Entity_Player& player) reconstruction_missing("Entity_Player::room_enter 007a6c50: the red poop flown over drops to its last state"); } +// Friendly enemies following the player in stand within 10 of it (Gurdy, Mega Maw and the Gate at their size), up to +// 45 degrees off the way into the room from the door entered (any way after a teleport). Their target moves with them +// and their path starts over. The original rounds pi to 3.14 for the random way. The Glowing Hourglass removes the +// Blood Puppy. +constexpr float FOLLOWER_PI = 3.14f; +constexpr float FOLLOWER_DISTANCE = 10; +constexpr float FOLLOWER_TARGET_SET_SQUARED = 3600; +constexpr uint32_t FOLLOWER_SPREAD = 90; +constexpr int FOLLOWER_SPREAD_HALF = 45; + +static void friendly_followers_place(Entity_Player& player) +{ + Game& game = *g_game; + Room& room = *game.room; + uint32_t slot = (uint32_t)game.enterDoor; + GridEntity_Door* door = slot < DOOR_SLOT_COUNT ? room.doors[slot] : nullptr; + float randomAngle = random_unit() * FOLLOWER_PI * 2; + Vector way = vector_make(std::cos(randomAngle), std::sin(randomAngle)); + if (door && door->direction >= DIRECTION_LEFT && door->direction <= DIRECTION_DOWN) + way = vector_scale(vector_from_direction(door->direction), -1); + + for (Entity* entity : room.entityList.updateEL) + { + if (game.isRestoringGlowingHourglassState && entity->type == ENTITY_BLOOD_PUPPY) + { + entity->Remove(); + continue; + } + bool isFollower = (game.deathmatchManager.state >= DEATHMATCH_INTRO && entity->type == ENTITY_PLAYER) || + (entity->type >= ENTITY_FIRST_ENEMY && entity->type < ENTITY_EFFECT); + auto* npc = dynamic_cast(entity); + // A deathmatch player is no NPC and would crash the original here. It is left where it is. + if (!(entity->flags & FLAG_FRIENDLY) || !isFollower || !npc) continue; + + Vector offset = vector_rotated(way, (float)((int)(Random() % FOLLOWER_SPREAD) - FOLLOWER_SPREAD_HALF)); + float distance = random_unit() * FOLLOWER_DISTANCE; + if (npc->type == ENTITY_GURDY || npc->type == ENTITY_MEGA_MAW || npc->type == ENTITY_GATE) distance = npc->size; + Vector spot = vector_add(player.pos, vector_scale(offset, distance)); + if (vector_length_squared(npc->targetPosition) > FOLLOWER_TARGET_SET_SQUARED) + npc->targetPosition = vector_add(vector_sub(npc->targetPosition, npc->pos), spot); + npc->pos = spot; + npc->pathfinder.movementTarget = {}; + npc->pathfinder.moveDirection = {}; + if (npc->type != ENTITY_BOIL) continue; + npc->Update(); + npc->targetPosition = npc->pos; + } +} + // 007a6c50 Sets the player up in the room just entered (after the floor's start): the cursed mist, Beth's Essence, // Dogma in the living room, the Twins and Judas's Belial, then the player stands at its entry with its motion, held // throw and pit fall reset, and its items react to the room. Friendly enemies follow it in, and Used Diaper, Lil Clot, @@ -316,20 +388,7 @@ void Entity_Player::room_enter() if (door && door->targetRoomType == ROOM_DEFAULT) door->Open(); if (HasTrinket(TRINKET_DOOR_STOP)) door_stop_apply(*this); room_items_apply(*this); - - for (Entity* entity : room.entityList.updateEL) - { - if (game.isRestoringGlowingHourglassState && entity->type == ENTITY_BLOOD_PUPPY) - { - entity->Remove(); - continue; - } - bool isFollower = (game.deathmatchManager.state >= DEATHMATCH_INTRO && entity->type == ENTITY_PLAYER) || - (entity->type >= ENTITY_FIRST_ENEMY && entity->type < ENTITY_EFFECT); - if ((entity->flags & FLAG_FRIENDLY) && isFollower) - reconstruction_missing("Entity_Player::room_enter 007a6c50: a friendly enemy following the player in " - "(Entity_NPC +0x418, +0x420)"); - } + friendly_followers_place(*this); if (HasTrinket(TRINKET_USED_DIAPER) && room.isFirstVisit && !room.IsClear() && room.GetAliveEnemiesCount() > 0 && !game.isRestoringGlowingHourglassState) for (int i = GetTrinketMultiplier(TRINKET_USED_DIAPER); i > 0; i--) AddBlueFlies(1, pos, nullptr); diff --git a/src/entity_player_tears.cpp b/src/entity_player_tears.cpp index 85899ac..0877f80 100644 --- a/src/entity_player_tears.cpp +++ b/src/entity_player_tears.cpp @@ -147,7 +147,6 @@ constexpr int COLLECTIBLE_MUCORMYCOSIS = 553; constexpr int COLLECTIBLE_TERRA = 592; constexpr int COLLECTIBLE_OCULAR_RIFT = 606; constexpr int COLLECTIBLE_LODESTONE = 617; -constexpr int COLLECTIBLE_ROTTEN_TOMATO = 618; constexpr int COLLECTIBLE_KNOCKOUT_DROPS = 637; constexpr int COLLECTIBLE_TROPICAMIDE = 659; constexpr int TRINKET_PINKY_EYE = 30; diff --git a/src/entity_player_update.cpp b/src/entity_player_update.cpp index 63c47e4..b5e59fc 100644 --- a/src/entity_player_update.cpp +++ b/src/entity_player_update.cpp @@ -1,5 +1,6 @@ #include "entity_player.h" #include "entity_player_characters.h" +#include "entity_player_effects.h" #include "entity_player_passives.h" #include "entity_player_trinkets.h" #include "tainted_characters.h" @@ -183,16 +184,26 @@ static void curse_mist_update(Entity_Player& player) else player.RemoveCurseMistEffect(); } -// The entities that ride on the player: Breath of Life's glow above it, Salvation's halo, and the Dark Esau chasing -// it with its speed. +// The entities that ride on the player: Dad's Ring's halo, Breath of Life's glow above it, Monstrance's and +// Salvation's halos, and the Dark Esau chasing it with its speed. static void riders_update(Entity_Player& player) { + if (Entity* aura = player.dadsRingAura) + { + aura->pos = player.pos; + aura->velocity = {}; + } if (Entity* breath = player.breathOfLifeEffect) { breath->posOffset = vector_make(0, BREATH_OF_LIFE_RISE); breath->pos = player.pos; breath->velocity = {}; } + if (Entity* aura = player.monstranceAura) + { + aura->pos = player.pos; + aura->velocity = {}; + } if (Entity* halo = player.salvationEffect) { halo->pos = player.pos; @@ -726,6 +737,7 @@ static void temporary_effects_update(Entity_Player& player) character_frame_update(player); passives_frame_update(player); trinkets_frame_update(player); + items_frame_update(player); lua_engine_get().PostPEffectUpdate(&player); } diff --git a/src/entity_player_weapons.cpp b/src/entity_player_weapons.cpp index bfab369..ce0d03f 100644 --- a/src/entity_player_weapons.cpp +++ b/src/entity_player_weapons.cpp @@ -1,6 +1,7 @@ #include "entity_effect.h" #include "entity_familiar.h" #include "entity_knife.h" +#include "seeds.h" #include "weapon_knives.h" #include "entity_laser.h" #include "entity_player.h" @@ -14,6 +15,10 @@ #include #include +// Stye's right eye tears float longer. +constexpr float STYE_FALLING_ACCEL_SCALE = 0.5f; +constexpr float STYE_FALLING_SPEED_DROP = 4; + constexpr int TECH5_FLAG_CHANCE = 5; constexpr int TECH5_FLAG_ROLL = 100; constexpr int TECH5_FLAG_COUNT = 84; @@ -22,14 +27,12 @@ constexpr int PLAYER_HEAD_LAYER = 4; constexpr const char* NULL_OFFSET_NAMES[] = {"LeftEye", "RightEye", "Forehead", "Mouth", "Mouth", "MomsEye", "Tractor"}; constexpr float CROSS_EYED_ANGLE = 0.7853982f; -constexpr float DEGREES_PER_RADIAN = 57.295776f; constexpr float DUNGEON_TEAR_HEIGHT_MAX = -5.1f; constexpr float DUNGEON_TEAR_OFFSET_Y = -18; constexpr float INHERIT_SCALE = 0.6f; constexpr float LANE_HALF_ARC = 90; constexpr float LANE_SPREAD_X = 1.15f; constexpr float LANE_SPREAD_Y = 0.8f; -constexpr float RANDOM_UNIT = 2.3283064e-10f; constexpr float SPREAD_CLAMP = 90; constexpr float WIZ_EYE_ANGLE = 45; // How much each extra tear widens a volley's tears and lasers, by what adds it, and how the other weapons follow. @@ -210,7 +213,7 @@ void Entity_Player::DoZitEffect(Vector direction) for (uint32_t puddles = Random() % ZIT_CREEP_MAX + 1; puddles > 0; puddles--) { uint32_t seed = Random(); - float reach = (float)Random() * RANDOM_UNIT * ZIT_CREEP_REACH + ZIT_CREEP_MIN; + float reach = random_unit() * ZIT_CREEP_REACH + ZIT_CREEP_MIN; float length = std::sqrt(direction.x * direction.x + direction.y * direction.y); Vector offset = length > 0 ? vector_scale(direction, reach / length) : direction; game.Spawn({.position = vector_add(pos, offset), @@ -338,8 +341,8 @@ Weapon_MultiShotParams Entity_Player::GetMultiShotParams(WeaponType weaponType) params.isShootingBackwards = isMomsEye || isLokisHorns; params.isShootingSideways = isLokisHorns; } - else if ((isMomsEye && (float)Random() * RANDOM_UNIT < luck * MOMS_EYE_LUCK + MOMS_EYE_CHANCE) || - (isLokisHorns && (float)Random() * RANDOM_UNIT < luck * LOKIS_HORNS_LUCK + LOKIS_HORNS_CHANCE)) + else if ((isMomsEye && random_unit() < luck * MOMS_EYE_LUCK + MOMS_EYE_CHANCE) || + (isLokisHorns && random_unit() < luck * LOKIS_HORNS_LUCK + LOKIS_HORNS_CHANCE)) { params.isShootingBackwards = true; params.isShootingSideways = isLokisHorns; @@ -395,7 +398,7 @@ PosVel Entity_Player::GetMultiShotPositionVelocity(int loopIndex, WeaponType wea float arc = (lane * (LANE_HALF_ARC + LANE_HALF_ARC) - LANE_HALF_ARC) * DEGREES_TO_RADIANS; float length = std::sqrt(aimed.y * aimed.y + aimed.x * aimed.x); Vector offset = vector_make(std::cos(arc) * LANE_SPREAD_X * length, std::sin(arc) * LANE_SPREAD_Y * length); - shot.position = vector_rotate(offset, std::atan2(aimed.y, aimed.x) * DEGREES_PER_RADIAN * DEGREES_TO_RADIANS); + shot.position = vector_rotate(offset, std::atan2(aimed.y, aimed.x) * RADIANS_TO_DEGREES * DEGREES_TO_RADIANS); } shot.velocity = vector_rotate(shot.velocity, ((spreadAngle + spreadAngle) * lane - spreadAngle) * DEGREES_TO_RADIANS); @@ -403,10 +406,10 @@ PosVel Entity_Player::GetMultiShotPositionVelocity(int loopIndex, WeaponType wea } // 00790af0 Fires a tear with the player's hit params from a shot (from the player's tear offset when it shoots it -// itself): its height, fall, scale, color, range, Dead Eye's (or Dark Arts') glow and an index, updated once and moved -// back a frame. +// itself): its height, fall, scale, color, range, Stye's slower fall, Dead Eye's (or Dark Arts') glow and an index, +// updated once and moved back a frame. // The Marked target holds no tear back, and extra shots drop the Tractor Beam and end no streak. The co-op baby's -// lasers, Stye, Evil Eye and the Lua callback are not written yet. +// lasers, Evil Eye and the Lua callback are not written yet. Entity_Tear* Entity_Player::FireTear(const PosVel& shot, uint32_t fireFlags, Entity* source, float damageMultiplier) { if (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_TECHNOLOGY) @@ -433,7 +436,7 @@ Entity_Tear* Entity_Player::FireTear(const PosVel& shot, uint32_t fireFlags, Ent tear->posOffset.y = DUNGEON_TEAR_OFFSET_Y; if (params.tearHeight > DUNGEON_TEAR_HEIGHT_MAX) tear->height = DUNGEON_TEAR_HEIGHT_MAX; } - float fallSpread = params.tearFlags.test(TEAR_POP) ? 0 : (float)Random() * RANDOM_UNIT * TEAR_FALL_SPREAD; + float fallSpread = params.tearFlags.test(TEAR_POP) ? 0 : random_unit() * TEAR_FALL_SPREAD; tear->fallingSpeed = fallSpread - tearFallingSpeed; tear->SetCollisionDamage(params.tearDamage); tear->SetTearFlags(params.tearFlags); @@ -447,7 +450,11 @@ Entity_Tear* Entity_Player::FireTear(const PosVel& shot, uint32_t fireFlags, Ent if (fireFlags & TEAR_FIRE_NO_STREAK_END) tear->isCanTriggerStreakEnd = false; float intensity = dead_eye_glow_get(*this); - if (HasCollectible(COLLECTIBLE_STYE)) reconstruction_missing("Entity_Player::FireTear 00790af0 (Stye)"); + if (HasCollectible(COLLECTIBLE_STYE) && params.tearDisplacement > 0) + { + tear->fallingAccel *= STYE_FALLING_ACCEL_SCALE; + tear->fallingSpeed -= STYE_FALLING_SPEED_DROP; + } if (intensity > 0) tear->SetDeadEyeIntensity(intensity); tear->mass *= params.massMultiplier; tear->knockbackMultiplier = params.knockbackMultiplier; @@ -536,7 +543,7 @@ Entity_Laser* Entity_Player::FireTechLaser(const TechLaserShot& shot) Entity_Laser* laser = Entity_Laser::ShootAngle({.position = vector_make(shot.position.x + offset.x, shot.position.y), .posOffset = vector_make(0, offset.y), .source = shot.source ? shot.source : this, - .angleDegrees = std::atan2(shot.direction.y, shot.direction.x) * DEGREES_PER_RADIAN, + .angleDegrees = std::atan2(shot.direction.y, shot.direction.x) * RADIANS_TO_DEGREES, .timeout = TECH_LASER_TIMEOUT, .variant = LASER_THIN_RED}); laser->parentOffset = vector_make(offset.x, 0); diff --git a/src/entity_projectile.cpp b/src/entity_projectile.cpp index eac46ed..f313c8e 100644 --- a/src/entity_projectile.cpp +++ b/src/entity_projectile.cpp @@ -23,7 +23,6 @@ // The shot a fresh projectile is: its height, slight random fall, homing, curving and change defaults. constexpr float HEIGHT_START = -23; constexpr float FALL_SPREAD = 0.2f; -constexpr float HALF = 0.5f; constexpr float CURVING_DEFAULT = 0.015f; constexpr float ACCELERATION_DEFAULT = 1.01f; constexpr int CHANGE_TIMEOUT_DEFAULT = 30; @@ -245,7 +244,6 @@ constexpr float POOF_SCALE_SHARE = 0.8f; constexpr float TEAR_POOF_SMALL = 0.4f; constexpr float TEAR_POOF_LARGE = 0.8f; constexpr float POOF_SOUND_MARGIN = -80; -constexpr float RIGHT_ANGLE = 90; constexpr float CORN_PARTICLE_SPEED = 2; constexpr int CORN_PARTICLES = 4; constexpr int BONE_PARTICLES = 8; @@ -335,7 +333,6 @@ constexpr std::array, CONTINUUM_COLORS> CONTINUUM_COLORIZES {1, 0, 1}}}; constexpr int ENTITY_TARBOY = 307; -constexpr int ENTITY_NECRO = 828; constexpr int ENTITY_SHADY = 888; constexpr int MOTHER_BALL = 10; constexpr int BEAST_FIRE_BALL = 20; @@ -1083,7 +1080,7 @@ void Entity_Projectile::death_poof_spawn() { poof->posOffset = posOffset; poof->sprite.scale = vector_make(poofScale, poofScale); - poof->sprite.rotation = (float)random_below(4) * RIGHT_ANGLE; + poof->sprite.rotation = (float)random_below(4) * RIGHT_ANGLE_DEGREES; } if (g_game->room->IsPositionInRoom(pos, POOF_SOUND_MARGIN)) sound_play(sound, 1, volume); } @@ -1479,7 +1476,7 @@ bool Entity_Projectile::wiggles_update() Vector direction = vector_scale(targetPosition, 1 / length); float along = vector_dot(velocity, direction); Vector forward = vector_scale(direction, along); - Vector wiggle = vector_scale(vector_rotated(direction, RIGHT_ANGLE), strength * std::sin(phase * 2 * PI_F)); + Vector wiggle = vector_scale(vector_rotated(direction, RIGHT_ANGLE_DEGREES), strength * std::sin(phase * 2 * PI_F)); if (along < length) forward = vector_add(forward, vector_scale(direction, length * ROTGUT_WIGGLE_PUSH)); velocity = vector_add(forward, wiggle); } diff --git a/src/entity_rock_drop.cpp b/src/entity_rock_drop.cpp index 09da71f..83e7c70 100644 --- a/src/entity_rock_drop.cpp +++ b/src/entity_rock_drop.cpp @@ -80,7 +80,13 @@ void Entity::DestroyRockGridAt(const Vector& position, GridEntityDesc* desc, Ent } rubble_spawn(position, type, subType, source, isNormal); if (isNormal) - GridEntity_Rock::SpawnDrops(position, (GridEntityType)type, variant, desc->_spawnSeed, backdropType, source); + GridEntity_Rock::SpawnDrops({.position = position, + .source = source, + .type = (GridEntityType)type, + .origin = ROCK_DROP_LANDED, + .backdropType = backdropType, + .variant = variant, + .seed = desc->_spawnSeed}); return; } if (type != GRID_POOP) return; diff --git a/src/entity_slot.cpp b/src/entity_slot.cpp index e71b06c..f3dc602 100644 --- a/src/entity_slot.cpp +++ b/src/entity_slot.cpp @@ -2,6 +2,7 @@ #include "boss_ai.h" #include "entity_config.h" #include "entity_bomb.h" +#include "entity_combat.h" #include "entity_effect_combat.h" #include "entity_pickup.h" #include "entity_player.h" @@ -41,6 +42,12 @@ constexpr std::array HELL_GAME_PRIZES = {PICKUP_HEART, PICKUP_COIN, constexpr std::array KEY_MASTER_CHESTS = {PICKUP_CHEST, PICKUP_LOCKEDCHEST, PICKUP_REDCHEST}; constexpr std::array ROTTEN_BEGGAR_TRINKETS = {TRINKET_FISH_HEAD, TRINKET_FISH_TAIL, TRINKET_BOBS_BLADDER, TRINKET_ROTTEN_PENNY}; +constexpr int ROTTEN_BEGGAR_MAGGOTS = 2; +constexpr float ROTTEN_BEGGAR_MAGGOT_HEIGHT = -10; +constexpr float ROTTEN_BEGGAR_MAGGOT_RISE = -8; +constexpr int ROTTEN_BEGGAR_GIBS = 5; +constexpr float ROTTEN_BEGGAR_GIB_SPREAD = 40; +constexpr int ROTTEN_BEGGAR_HEART_ODDS = 3; constexpr std::array BATTERY_BUM_CHARGES = {1, 1, 1, 2, 2, 3}; constexpr int BEGGAR_FOOD_FIRST = 22; constexpr int BEGGAR_FOOD_COUNT = 5; @@ -2059,8 +2066,20 @@ void Entity_Slot::spawn_break_drops() Entity_NPC::ThrowSpider(pos, this, {}, false, SLOT_SPIDER_HEIGHT); return; case SLOT_ROTTEN_BEGGAR: - reconstruction_missing( - "Entity_Slot::spawn_break_drops 00663aa0: the Rotten Beggar's maggots (spawn_small_maggot)"); + for (int i = 0; i < ROTTEN_BEGGAR_MAGGOTS; i++) + small_maggot_spawn(pos, ROTTEN_BEGGAR_MAGGOT_HEIGHT, + Entity_Pickup::GetRandomPickupVelocity(pos, &velocityRng, 1), + ROTTEN_BEGGAR_MAGGOT_RISE); + gibs_spawn({.position = pos, + .spread = ROTTEN_BEGGAR_GIB_SPREAD, + .amount = ROTTEN_BEGGAR_GIBS, + .gibFlags = GIB_FLAG_BONE | GIB_FLAG_GUT | GIB_FLAG_WORM}); + if (dropRNG.RandomInt(ROTTEN_BEGGAR_HEART_ODDS) == 0) + { + uint32_t seed = dropRNG.Next(); + drop(PICKUP_HEART, HEART_ROTTEN, seed, 1); + } + return; case SLOT_SHOP_RESTOCK_MACHINE: for (int i = (int)dropRNG.RandomInt(4); i > 0; i--) { diff --git a/src/entity_status.cpp b/src/entity_status.cpp index c6db75a..d0a11aa 100644 --- a/src/entity_status.cpp +++ b/src/entity_status.cpp @@ -538,8 +538,7 @@ void Entity::bleed_update() float moved = std::sqrt((pos.y - prevPosition.y) * (pos.y - prevPosition.y) + (pos.x - prevPosition.x) * (pos.x - prevPosition.x)); float accumulated = moved * speedMultiplier * BLEED_PER_DISTANCE + bleedDamageAccumulator; - bool isAltPath = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; - float perPoint = (float)(isAltPath ? game.stage + 1 : game.stage) * BLEED_DAMAGE_PER_STAGE + BLEED_DAMAGE_BASE; + float perPoint = (float)game.stage_depth_get() * BLEED_DAMAGE_PER_STAGE + BLEED_DAMAGE_BASE; float points = std::floor(accumulated); if (game.deathmatchManager.is_active()) perPoint = 1; bleedDamageAccumulator = accumulated - points; diff --git a/src/entity_tear.cpp b/src/entity_tear.cpp index 7410f3b..4812c29 100644 --- a/src/entity_tear.cpp +++ b/src/entity_tear.cpp @@ -271,7 +271,6 @@ constexpr float BOOMERANG_FALL_SCALE = 0.5f; constexpr float BOOMERANG_ACCEL_OFFSET = 0.08f; constexpr float BOOMERANG_ACCEL_SCALE = 0.25f; -constexpr uint32_t CHALLENGE_ONANS_STREAK = 29; constexpr int TRINKET_PULSE_WORM = 9; constexpr int TRINKET_FLAT_WORM = 12; @@ -1874,9 +1873,17 @@ static void backstab(Entity& entity, const TearHit& hit) blood.Update(); } +// Knockout Drops' punch: a sound, a strong push along the hit and a second of confusion. +constexpr int PUNCH_SOUND_DELAY = 8; +constexpr float PUNCH_PITCH_SPREAD = 0.1f; +constexpr float PUNCH_PITCH_MIN = 0.95f; +constexpr float PUNCH_PUSH = 26; +constexpr int PUNCH_PUSH_FRAMES = 14; +constexpr int PUNCH_CONFUSION = 60; + // The status effects of a hit on a vulnerable enemy: Spider Bite's slowing (Ball of Tar's darker), poison, freezing, -// charm, confusion (Glaucoma's lasting), fear, burning, Midas' gold, magnetism, bait, ice, black hearts and God's -// Flesh's shrinking. +// charm, confusion (Glaucoma's lasting), fear, burning, Midas' gold, magnetism, bait, ice, Knockout Drops' punch, +// black hearts and God's Flesh's shrinking. static void status_effects_apply(Entity& entity, const TearFlags& flags, const TearHit& hit) { Entity* source = hit.source; @@ -1908,7 +1915,12 @@ static void status_effects_apply(Entity& entity, const TearFlags& flags, const T if (flags[TEAR_MAGNETIZE]) entity.AddMagnetized(ref, MAGNETIZE_DURATION); if (flags[TEAR_BAIT]) entity.AddBaited(ref, BAIT_DURATION); if (flags[TEAR_ICE_FLAG]) entity.AddIce(ref, ICE_DURATION); - if (flags[TEAR_PUNCH]) reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Knockout Drops' punch"); + if (flags[TEAR_PUNCH]) + { + npc_sound_play(SOUND_PUNCH, 1, PUNCH_SOUND_DELAY, random_unit() * PUNCH_PITCH_SPREAD + PUNCH_PITCH_MIN); + entity.AddKnockback(ref, vector_scale(direction, PUNCH_PUSH), PUNCH_PUSH_FRAMES, true); + entity.AddConfusion(ref, PUNCH_CONFUSION, false); + } if (flags[TEAR_BLACK_HP_DROP]) entity.AddEntityFlags(FLAG_SPAWN_BLACK_HP); if (flags[TEAR_GODS_FLESH_FLAG]) entity.AddShrink(ref, SHRINK_DURATION, false); if (flags[TEAR_COIN_DROP] || (flags[TEAR_GREED_COIN] && Random() % GREED_COIN_CHANCE == 0)) @@ -1982,6 +1994,27 @@ static void parasitoid_egg_hatch(Entity& entity, Vector position, Entity* source } } +// The knockback flag's push: a tear pushes along its flight by its mass and knockback multiplier, a knife along its +// blade and a brimstone ball along its motion (or away from it), both by 51. The pushed entity's mass divides it. +static void knockback_apply(Entity& entity, Entity& source) +{ + constexpr float BLADE_PUSH = 51; + if (source.type == ENTITY_TEAR) + { + Vector push = vector_scale(vector_normalized(source.velocity), source.mass); + if (entity.mass > 0) push = vector_scale(push, 1 / entity.mass); + entity.AddVelocity_divided(vector_scale(push, static_cast(source).knockbackMultiplier), false); + return; + } + Vector direction{}; + if (source.type == ENTITY_KNIFE) direction = vector_rotated(vector_make(1, 0), source.sprite.rotation + 90); + else if (source.type == ENTITY_EFFECT && source.variant == EFFECT_BRIMSTONE_BALL) + direction = vector_normalized(vector_is_zero(source.velocity) ? vector_sub(entity.pos, source.pos) : source.velocity); + else return; + if (entity.mass > 0) direction = vector_scale(direction, 1 / entity.mass); + entity.AddVelocity_divided(vector_scale(direction, BLADE_PUSH), false); +} + // 0067af60 What a hit's tear flags do to what it hits: the status effects on vulnerable enemies, the knockback a // tear's mass and push give, and the gore. An explosive tear leaves the effects to its explosion, and a friendly // target is spared. The original reads a missing target's position. This does nothing for one. @@ -2006,14 +2039,7 @@ void Entity_Tear::ApplyTearFlagEffects(Entity* entity, const Vector& position, c if (flags[drop.flag] && (drop.flag != TEAR_HP_DROP || Random() % HP_DROP_CHANCE == 0)) entity->TakeDamage(0, drop.damageFlag, EntityRef(source), HIT_DROP_COUNTDOWN); if (flags[TEAR_KNOCKBACK] && !entity->HasEntityFlags(FLAG_NO_KNOCKBACK) && source) - { - if (source->type != ENTITY_TEAR) - reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: a knife's or effect's knockback"); - Vector push = vector_scale(vector_normalized(source->velocity), source->mass); - if (entity->mass > 0) push = vector_scale(push, 1 / entity->mass); - float multiplier = static_cast(source)->knockbackMultiplier; - entity->AddVelocity_divided(vector_scale(push, multiplier), false); - } + knockback_apply(*entity, *source); } if (!isExplosiveTear) rerollable_flags_apply(*entity, flags, source); if (flags[TEAR_LIGHT_FROM_HEAVEN] && isActiveEnemy) holy_light_strike(*entity, source, damage); diff --git a/src/entity_tear_flags.cpp b/src/entity_tear_flags.cpp index ab9a3a5..c6356be 100644 --- a/src/entity_tear_flags.cpp +++ b/src/entity_tear_flags.cpp @@ -251,7 +251,7 @@ static bool is_chained(Entity* entity) } // 00705b90 Pulls the vulnerable enemies (four times as hard) and the free pickups and closed chests within a reach -// toward a point, harder the nearer, by their speed over their mass. Within 10 they drag and are pulled gently. +// toward a point, harder the nearer, by their speed over their friction. Within 10 they drag and are pulled gently. // The original passes a filter callback. Its one user, Entity_Effect::rift_attract_filter, spares one entity. void entities_attract(const Attraction& attraction) { @@ -288,8 +288,9 @@ void entities_attract(const Attraction& attraction) vector_scale(entity->velocity, timescale_factor(ATTRACT_NEAR_DRAG, entity->speedMultiplier)); pull = reach / ATTRACT_NEAR_SHARE; } - if (entity->mass != 0) - entity->velocity = vector_add(entity->velocity, vector_scale(toward, entity->speedMultiplier * pull / entity->mass)); + if (entity->friction != 0) + entity->velocity = + vector_add(entity->velocity, vector_scale(toward, entity->speedMultiplier * pull / entity->friction)); } } diff --git a/src/familiar_ai.cpp b/src/familiar_ai.cpp index c0d1148..be1e135 100644 --- a/src/familiar_ai.cpp +++ b/src/familiar_ai.cpp @@ -576,12 +576,11 @@ void Entity_Familiar::TriggerRoomClear() if (variant == WISP && !isDead && g_game->frameCount - spawnFrame > 1) wisp_room_clear(*this); } -// 0062b750 Its player was hurt: Smart Fly turns aggressive, the Mystery Egg cracks, Damocles falls on a real hit. -// Hallowed Ground's hop, Intruder's revenge and the Paschal Candle's dimming stop the game. +// 0062b750 Its player was hurt: Smart Fly turns aggressive, the Mystery Egg cracks, Damocles falls on a real hit, +// Intruder marks the culprit, Hallowed Ground hops and the Paschal Candle dims. void Entity_Familiar::trigger_player_damage(const DamageEvent& hit) { - if (variant == INTRUDER) - reconstruction_missing("Entity_Familiar::trigger_player_damage 0062b750 (this familiar's reaction)"); + if (variant == INTRUDER) intruder_player_hurt(*this, hit); if (variant == HALLOWED_GROUND) hallowed_ground_player_hurt(*this); if (variant == PASCHAL_CANDLE) paschal_candle_player_hurt(*this, hit.damageFlags); diff --git a/src/familiar_collision.cpp b/src/familiar_collision.cpp index 9cbcd85..f20b161 100644 --- a/src/familiar_collision.cpp +++ b/src/familiar_collision.cpp @@ -26,10 +26,12 @@ constexpr int CONTACT_VARIANTS[] = {33, 60, 15, 14, 79, 77, 3, 104, 44, 4 32, 83, 121, 126, 226, 224, 210, 218, 206, 237, 229, 204}; // The familiars whose touch, block or hit has an effect of its own not reconstructed yet. -constexpr int UNWRITTEN_TOUCH_VARIANTS[] = {87, 243, 200, 204, 231, 93}; -constexpr int UNWRITTEN_BLOCK_VARIANTS[] = {228, 238, 201, 216, 217, 231}; -constexpr int UNWRITTEN_ENEMY_TOUCH_VARIANTS[] = {228, 238, 201, 216, 217}; -constexpr int UNWRITTEN_DEATH_VARIANTS[] = {128, 216, 217, 229, 234, 201, 238}; +constexpr int UNWRITTEN_TOUCH_VARIANTS[] = {87, 243, 204, 93}; +constexpr int UNWRITTEN_BLOCK_VARIANTS[] = {228, 238, 201}; +constexpr int UNWRITTEN_ENEMY_TOUCH_VARIANTS[] = {228, 238, 201}; +// The hit Tinytoma takes from each shot it stops. +constexpr float TINYTOMA_SHOT_HURT = 3.5f; +constexpr int UNWRITTEN_DEATH_VARIANTS[] = {128, 229, 234, 201, 238}; // The familiars whose contact damage stays off until their dash or throw (a cooldown of -1), or while they rest. constexpr int DASHING_VARIANTS[] = {130, 232, 223}; @@ -356,6 +358,7 @@ bool Entity_Familiar::collision_block(Entity& collider, bool isIgnored) if (collider.type == ENTITY_PROJECTILE && (static_cast(collider).projectileFlags & PROJECTILE_CANT_HIT_PLAYER)) return true; + if (variant == ABYSS_LOCUST) return locust_block(*this, collider, isIgnored); if (!CanBlockProjectiles()) { if (variant != SLIPPED_RIB) return true; @@ -397,6 +400,7 @@ bool Entity_Familiar::collision_block(Entity& collider, bool isIgnored) else if (variant == BONE_ORBITAL || variant == SWARM_FLY_ORBITAL || (variant == BONE_SPUR && (state += BONE_WEAR) > BONE_WEAR_LIMIT)) Kill(EntityRef()); + if (variant == TINYTOMA || variant == TINYTOMA_2) TakeDamage(TINYTOMA_SHOT_HURT, 0, EntityRef(&collider), 1); collider.isDead = true; return isIgnored; } @@ -557,6 +561,7 @@ bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) if (isOwnersFoe && collider->IsActiveEnemy(DEAD_EXCLUDED) && (collider->IsVulnerableEnemy(nullptr) || collider->CanShutDoors())) { + if (variant == TINYTOMA || variant == TINYTOMA_2) return tinytoma_touch(*this, *collider, damageMultiplier); if (familiar_listed(UNWRITTEN_ENEMY_TOUCH_VARIANTS, variant)) reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (this familiar's enemy touch)"); if ((variant == WISP || variant == ITEM_WISP) && wisp_touch(*this, *collider)) return true; @@ -572,6 +577,7 @@ bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) if (isFlyLord && (variant == BLUE_FLY || variant == BLUE_SPIDER || variant == ABYSS_LOCUST)) return true; if (isSpiderLord && (variant == BLUE_SPIDER || variant == SPIDER_BABY)) return true; } + if (variant == ABYSS_LOCUST) locust_touch(*this, *collider); float damage = collisionDamage; if (damage == 0) @@ -612,7 +618,7 @@ bool Entity_Familiar::TakeDamage(float damage, uint64_t damageFlags, const Entit if ((damageFlags & (DAMAGE_SPIKES | DAMAGE_POOP)) && variant != ISAACS_HEART) return false; if (variant == MILK) reconstruction_missing("Entity_Familiar::TakeDamage 0062cdc0 (this familiar's hit)"); bool isWisp = variant == WISP || variant == ITEM_WISP; - if (isWisp && !wisp_take_damage(source, damageFlags)) return false; + if (isWisp && !wisp_take_damage(damage, damageFlags, source)) return false; if (isWisp) damageCountdown = wisp_hit_countdown(damageCountdown); if (variant == BLOOD_BABY && counter > 0) return false; @@ -640,7 +646,11 @@ bool Entity_Familiar::TakeDamage(float damage, uint64_t damageFlags, const Entit // familiars that die their own way (the bone orbitals, the swarm flies, the Dips, the clots) stop the game. void Entity_Familiar::Kill(const EntityRef& source) { - if (!isDead) + if (!isDead && (variant == TINYTOMA || variant == TINYTOMA_2)) + { + if (!tinytoma_death(*this)) return; + } + else if (!isDead) { if (familiar_listed(UNWRITTEN_DEATH_VARIANTS, variant)) reconstruction_missing("Entity_Familiar::Kill 00610540 (this familiar's death)"); diff --git a/src/familiar_evaluate.cpp b/src/familiar_evaluate.cpp index e73cbbf..cdc45ea 100644 --- a/src/familiar_evaluate.cpp +++ b/src/familiar_evaluate.cpp @@ -57,15 +57,12 @@ constexpr FamiliarSource FAMILIAR_SOURCES[] = { constexpr FamiliarSource LATE_FAMILIAR_SOURCES[] = {{565, 241}, {697, 242}}; // The familiars granted another way: items whose effect alone counts, the trinkets, and the counters. -constexpr int TRINKET_APOLLYONS_BEST_FRIEND = 186; constexpr int NULLITEM_SPIN_TO_WIN_FAMILIAR = 131; constexpr int FAMILIAR_SPIN_TO_WIN = 244; -constexpr int COLLECTIBLE_HALO_OF_FLIES = 10; constexpr int NULLITEM_HALO_FLY_LOSS = 107; constexpr int HALO_FLY_CAP = 10; constexpr int ACHIEVEMENT_CUBE_OF_MEAT_FULL = 144; constexpr int ACHIEVEMENT_BALL_OF_BANDAGES_FULL = 19; -constexpr int COLLECTIBLE_SPRINKLER = 516; constexpr int COLLECTIBLE_KEY_BUM = 388; constexpr int COLLECTIBLE_BUM_FRIEND = 144; constexpr int COLLECTIBLE_LIL_DELIRIUM = 519; diff --git a/src/familiar_follow.cpp b/src/familiar_follow.cpp index 0a66c65..b5b72cc 100644 --- a/src/familiar_follow.cpp +++ b/src/familiar_follow.cpp @@ -14,7 +14,6 @@ #include // The items, trinkets, challenge and boss the following line answers to. -constexpr int COLLECTIBLE_BIG_FAN = 279; constexpr int SIREN_TYPE = 904; // How far behind its leader a follower keeps, closer for Milk and on Child's Leash, and how hard it catches up. diff --git a/src/familiar_locust.cpp b/src/familiar_locust.cpp new file mode 100644 index 0000000..e126c0f --- /dev/null +++ b/src/familiar_locust.cpp @@ -0,0 +1,887 @@ +#include "boss_ai.h" +#include "console.h" +#include "entity_bomb.h" +#include "entity_combat.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_knife.h" +#include "entity_laser.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "item_config.h" +#include "manager.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "room.h" +#include "room_grid.h" +#include "seeds.h" +#include "weapon.h" +#include +#include + +// The locust a familiar of another variant reads (Breakfast's), and the separators of a locust's gfx and color specs. +constexpr int LOCUST_FALLBACK_ITEM = 25; +constexpr char OVERRIDE_SEPARATOR = '&'; +constexpr char LAYER_SEPARATOR = '-'; +constexpr std::string_view ANM2_KEY = "anm2="; +constexpr std::string_view SPRITESHEET_KEY = "spritesheet="; +constexpr std::string_view ANIMATION_KEY = "animation="; + +// A hungry locust's looks: one sheet per five pickups eaten, up to 25, each eaten pickup adding a quarter damage. +constexpr uint32_t LOCUST_FLAG_HUNGRY = 1 << 18; +constexpr int HUNGER_MAX = 25; +constexpr int HUNGER_PER_LOOK = 5; +constexpr float HUNGER_DAMAGE = 0.25f; +constexpr const char* HUNGRY_SHEET = "hungry_%d.png"; + +// The locust flags (locusts.xml's locustFlags): what a hit sets off, and what a flying locust does. +constexpr uint32_t LOCUST_FLAG_EXPLODE = 1 << 0; +constexpr uint32_t LOCUST_FLAG_RANDOM = 1 << 1; +constexpr uint32_t LOCUST_FLAG_SWARM = 1 << 2; +constexpr uint32_t LOCUST_FLAG_DEVOLVE = 1 << 3; +constexpr uint32_t LOCUST_FLAG_NECRONOMICON = 1 << 4; +constexpr uint32_t LOCUST_FLAG_ERASE = 1 << 5; +constexpr uint32_t LOCUST_FLAG_KNIFE = 1 << 6; +constexpr uint32_t LOCUST_FLAG_SHOCKWAVE = 1 << 7; +constexpr uint32_t LOCUST_FLAG_MAW = 1 << 8; +constexpr uint32_t LOCUST_FLAG_REPEL = 1 << 9; +constexpr uint32_t LOCUST_FLAG_FART = 1 << 10; +constexpr uint32_t LOCUST_FLAG_BUTTER_BEAN = 1 << 11; +constexpr uint32_t LOCUST_FLAG_BRIMSTONE = 1 << 12; +constexpr uint32_t LOCUST_FLAG_GREEN_CREEP = 1 << 13; +constexpr uint32_t LOCUST_FLAG_LEMON_CREEP = 1 << 14; +constexpr uint32_t LOCUST_FLAG_BLOOD_CREEP = 1 << 15; +constexpr uint32_t LOCUST_FLAG_HOLY_CREEP = 1 << 16; +constexpr uint32_t LOCUST_FLAG_BLACK_POWDER = 1 << 17; +constexpr uint32_t LOCUST_FLAGS_CREEP = + LOCUST_FLAG_GREEN_CREEP | LOCUST_FLAG_LEMON_CREEP | LOCUST_FLAG_BLOOD_CREEP | LOCUST_FLAG_HOLY_CREEP; +constexpr uint32_t LOCUST_CREEPS[] = {LOCUST_FLAG_GREEN_CREEP, LOCUST_FLAG_LEMON_CREEP, LOCUST_FLAG_BLOOD_CREEP, + LOCUST_FLAG_HOLY_CREEP}; + +// A random locust's (Chaos, 3 Dollar Bill) pick: one of these tear flags, else (past them) explode, fart, Butter Bean, +// a creep or Black Powder. +constexpr int RANDOM_TEAR_FLAGS[] = {4, 3, 34, 20, 22, 13, 66, 64, 5, 14, 43, 55, 39, 2, 51, 73, 53}; +constexpr int RANDOM_LOCUST_PICKS = 22; +constexpr int RANDOM_PICK_EXPLODE = 17; +constexpr int RANDOM_PICK_FART = 18; +constexpr int RANDOM_PICK_BUTTER_BEAN = 19; +constexpr int RANDOM_PICK_CREEP = 20; + +// A locust's hit: its damage by its item's quality, how much its other effects and BFFS! add, its push and the frames +// it keeps the enemy from being hit again. +constexpr float QUALITY_DAMAGE[] = {0.5f, 0.75f, 1, 1.5f, 2}; +constexpr int APOLLYONS_BEST_FRIEND_QUALITY = 3; +constexpr float MULTIPLIER_DAMAGE_STEP = 0.25f; +constexpr float MULTIPLIER_DAMAGE_BASE = 0.75f; +constexpr float LOCUST_PUSH = 1.8f; +constexpr int LOCUST_HIT_COUNTDOWN = 30; + +// The flight: its speed per config speed, the margin it launches inside the room, how the player's motion carries it, +// how it bends toward a homing target (every four frames, within 128, odds and noise), how it returns and slows, +// when a returning locust rejoins the swarm, and how long it rests after. +constexpr float LAUNCH_SPEED = 10; +constexpr float LAUNCH_MARGIN = 5; +constexpr float LAUNCH_INHERIT = 0.6f; +constexpr int HOMING_INTERVAL = 4; +constexpr float LOCUST_HOMING_LOOKAHEAD = 5; +constexpr float LOCUST_HOMING_RANGE = 128; +constexpr float HOMING_FAR = 1e9f; +constexpr float HOMING_NOISE = 128; +constexpr float HOMING_DRAG = 0.8f; +constexpr float HOMING_TURN = 2; +constexpr float WALL_FACING = 0.3f; +constexpr int BONE_SUBTYPE = 6; +constexpr float BONE_REACH = 100; +constexpr float RETURN_DRAG = 0.8f; +constexpr int RETURN_FRAMES = 10; +constexpr int LAUNCH_REST = 30; +constexpr int CHASE_LIMIT = -15; +constexpr float CHASE_DRAG = 0.86f; +constexpr float LOCUST_CHASE_RANGE = 50; +constexpr float CHASE_PULL = 0.02f; +constexpr float SWARM_SPEED_MIN = 0.5f; +constexpr float SWARM_SPEED_RANGE = 1.5f; +constexpr float SWARM_REJOIN = 100; +constexpr float LOCUST_SWARM_PULL = 0.02f; +constexpr float RETURN_PULL = 0.15f; +constexpr float RETURN_SPEED = 6; +constexpr float RETURN_STOP = 0.1f; +constexpr float RETURN_FRICTION = 0.8f; +constexpr float SPAWN_FRICTION = 0.96f; +constexpr int SWARM_DELAY_MAX = 10; +constexpr int SWARM_DELAY_MIN = 3; + +// What the flying locusts' flags do as they fly: a glowing locust's aura (2 damage once a second between its size and +// four times it), a repelling one's push on shots within 40, a hungry one's reach for pickups, and Mom's Knife's blade +// at half damage, half size, spinning above it. +constexpr float AURA_RANGE_SCALE = 3; +constexpr float AURA_RANGE_BASE = 100; +constexpr float AURA_OUTER_SCALE = 4; +constexpr float AURA_DAMAGE = 2; +constexpr int AURA_COUNTDOWN = 30; +constexpr float REPEL_RANGE = 40; +constexpr float REPEL_FALLOFF = 80; +constexpr float REPEL_STEP = 0.1f; +constexpr float REPEL_BASE = 0.05f; +constexpr int EATEN_PICKUPS[] = {PICKUP_HEART, PICKUP_COIN, PICKUP_LIL_BATTERY, PICKUP_BOMB, + PICKUP_KEY, PICKUP_PILL, PICKUP_TAROTCARD, PICKUP_TRINKET, + PICKUP_GRAB_BAG, PICKUP_THROWABLEBOMB, PICKUP_POOP}; +constexpr float KNIFE_SCALE = 0.5f; +constexpr float KNIFE_HEIGHT = 24; +constexpr float KNIFE_SPIN = 2; + +// The hit effects: the bone shards, the explosion, the creeps (a quarter of the locust's size, inside 15 of the +// walls) and their looks, Black Powder's circle, the Necronomicon, the Maw of the Void's ring, the brimstone, the +// farts and the rift. +constexpr int LOCUST_BONE_SHARDS = 2; +constexpr float BONE_SHARD_SPEED = 10; +constexpr float BONE_SHARD_DAMAGE = 0.25f; +constexpr float LOCUST_BLAST_DAMAGE = 20; +constexpr float LOCUST_BLAST_RADIUS = 0.6f; +constexpr float LOCUST_CREEP_MARGIN = 15; +constexpr float LOCUST_CREEP_SCALE = 0.4f; +constexpr ColorMod LOCUST_GREEN_COLOR = COLOR_DEFAULT; +constexpr ColorMod LOCUST_LEMON_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {2.2f, 2.2f, 0}}; +constexpr ColorMod LOCUST_BLOOD_COLOR = {{1, 0, 0, 1}, {0, 0, 0, 0}, {0.8f, -1, -1}}; +constexpr ColorMod LOCUST_HOLY_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.6f, 2.2f}}; +constexpr int PENTAGRAM_FRAMES = 45; +constexpr float PENTAGRAM_SCALE = 32; +constexpr int LOCUST_MAW_TIMEOUT = 60; +constexpr float MAW_SCALE = 0.5f; +constexpr float MAW_RADIUS_SCALE = 0.1f; +constexpr float LOCUST_BRIMSTONE_SCALE = 1.5f; +constexpr float LOCUST_FART_RADIUS = 15; +constexpr float FART_SCALE = 0.4f; +constexpr float LOCUST_BUTTER_BEAN_RADIUS = 40; +constexpr float RIFT_DAMAGE = 0.25f; +constexpr float RIFT_SCALE = 0.4f; + +// How the shot sprites fade in while it flies and out after, and where they draw (a locust's sprite sits 25 up), at +// a share of its config scale. +constexpr float SHOT_FADE_STEP = 0.04f; +constexpr float SHOT_SPRITE_SCALE = 0.45f; +constexpr float SHOT_SPRITE_RAISE = 25; + +// 006470c0 The locust config a familiar reads: a locust's own, Breakfast's for anything else. +LocustConfig& familiar_locust_config(Entity_Familiar& familiar) +{ + bool isLocust = familiar.variant == Entity_Familiar::ABYSS_LOCUST; + return *ItemConfig::locust_config_get(isLocust ? familiar.subtype : LOCUST_FALLBACK_ITEM, + isLocust ? familiar.coins : 0); +} + +static AbyssLocustData& locust_data(Entity_Familiar& locust) +{ + return static_cast(*locust.extraData); +} + +// The extra effects of a locust config that proc, each passed to apply. An effect is skipped while an earlier proc's +// mutex flags cover its place in the list. +template static void locust_effects_roll(LocustConfig& config, Apply apply) +{ + uint32_t mutex = 0; + for (size_t i = 1; i < config.effects.size(); i++) + { + LocustEffect& effect = config.effects[i]; + if ((mutex & (1u << ((i - 1) % 32))) || effect.procChance <= 0 || random_unit() >= effect.procChance) continue; + + apply(effect); + mutex |= effect.mutexFlags; + } +} + +// 0064aab0 Applies a locust's gfx and color specs to a sprite: "anm2=" loads an anm2 under the locusts' gfx root, +// "spritesheet=N-file" replaces layer N's sheet, "animation=" picks the animation (else the default), and each +// "N-preset" of the color spec tints layer N in a locust color preset. +void anm2_gfx_overrides_apply(std::string_view gfx, std::string_view color, ANM2& sprite) +{ + ItemConfig& config = g_manager->itemConfig; + std::map sheets; + std::string anm2Path; + std::string animation; + + for (const std::string& part : text_split(gfx, OVERRIDE_SEPARATOR)) + { + if (part.starts_with(ANM2_KEY)) anm2Path = config.locustGfxRoot + std::string(part.substr(ANM2_KEY.size())); + else if (part.starts_with(SPRITESHEET_KEY)) + { + std::string_view sheet = std::string_view(part).substr(SPRITESHEET_KEY.size()); + size_t dash = sheet.find(LAYER_SEPARATOR); + if (dash != std::string_view::npos) + sheets[std::atoi(std::string(sheet.substr(0, dash)).c_str())] = + config.locustGfxRoot + std::string(sheet.substr(dash + 1)); + } + else if (part.starts_with(ANIMATION_KEY)) animation = part.substr(ANIMATION_KEY.size()); + } + + if (!anm2Path.empty()) sprite.Load(anm2Path, GRAPHICS_LOAD); + if (!sprite.isLoaded) return; + for (auto& [layer, path] : sheets) sprite.ReplaceSpritesheet(layer, g_manager->modManager.TryRedirectPath(path)); + if (!sheets.empty()) sprite.LoadGraphics(); + if (sprite.SetAnimation(animation.empty() ? sprite.GetDefaultAnimationName() : animation)) + { + sprite.animState.Rewind(); + sprite.animState.isPlaying = true; + } + + for (const std::string& part : text_split(color, OVERRIDE_SEPARATOR)) + { + size_t dash = part.find(LAYER_SEPARATOR); + if (dash == std::string::npos) continue; + int layer = std::atoi(part.substr(0, dash).c_str()); + if (LayerState* state = layer >= 0 && layer < (int)sprite.layerStates.size() ? sprite.GetLayer(layer) : nullptr) + state->color = color_preset_find(config.locustColors, std::string_view(part).substr(dash + 1)); + } +} + +// A hungry locust's sheet for its hunger. +static void hungry_sheet_load(Entity_Familiar& locust, int hunger) +{ + char sheet[32]; + std::snprintf(sheet, sizeof(sheet), HUNGRY_SHEET, hunger / HUNGER_PER_LOOK); + locust.sprite.ReplaceSpritesheet(0, g_manager->itemConfig.locustGfxRoot + sheet); + locust.sprite.LoadGraphics(); +} + +// 0064a830 Loads a locust's looks: its entity's anm2 on its default animation, the hungry sheet for a hungry one, then +// its config's gfx and colors. +void Entity_Familiar::load_config_graphics() +{ + LocustConfig& locust = familiar_locust_config(*this); + if (config) + { + sprite.Load(config->anm2Path, GRAPHICS_LOAD); + sprite.Play(sprite.GetDefaultAnimationName()); + AbyssLocustData& data = locust_data(*this); + if ((data.locustFlags | locust.effects[0].locustFlags) & LOCUST_FLAG_HUNGRY) + hungry_sheet_load(*this, data.hunger); + } + anm2_gfx_overrides_apply(locust.gfx, locust.color, sprite); +} + +// 0060ddd0 Picks which of its item's locust configs a locust uses (stored in coins), applying its looks and size. +void Entity_Familiar::set_locust_config_index(int index) +{ + if (variant != ABYSS_LOCUST) + KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Trying to set locust config index on something that isn't a locust\n"); + coins = index; + LocustConfig& locust = familiar_locust_config(*this); + anm2_gfx_overrides_apply(locust.gfx, locust.color, sprite); + size = config->collisionRadius * locust.scale; + sprite.scale = vector_make(locust.scale, locust.scale); +} + +// 00647170 A hungry locust eats a pickup: up to 25, its sheet growing every fifth. False once full. +bool Entity_Familiar::abyss_locust_eat() +{ + if (variant != ABYSS_LOCUST) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"This should only be called on a locust\n"); + AbyssLocustData& data = locust_data(*this); + if (data.hunger >= HUNGER_MAX) return false; + + data.hunger++; + if (data.hunger % HUNGER_PER_LOOK == 1) hungry_sheet_load(*this, data.hunger); + return true; +} + +// Part of 0060de70: a locust's extra data and looks, the first hungry sheet for a hungry one. +void locust_init(Entity_Familiar& locust) +{ + LocustConfig& config = familiar_locust_config(locust); + locust.extraData = std::make_unique(); + locust.load_config_graphics(); + if (!(config.effects[0].locustFlags & LOCUST_FLAG_HUNGRY)) return; + + locust.sprite.ReplaceSpritesheet(0, g_manager->itemConfig.locustGfxRoot + "hungry_0.png"); + locust.sprite.LoadGraphics(); +} + +// Part of 0061da10: a locust's size, its config's scale, or for an unscaled config the scale of its item's quality. +float locust_scale_get(Entity_Familiar& locust) +{ + float scale = familiar_locust_config(locust).scale; + if (scale != 1 || !locust.item) return scale; + + bool isBestFriend = locust.item->IsTrinket() && locust.item->id == TRINKET_APOLLYONS_BEST_FRIEND; + int quality = isBestFriend ? APOLLYONS_BEST_FRIEND_QUALITY : locust.item->quality; + return quality >= 0 && quality < LOCUST_QUALITY_COUNT ? g_manager->itemConfig.locustQualityScales[quality] : 1; +} + +// A shot sprite for a launch: the gfx applied to a fresh sprite, invisible until it fades in. +static void shot_sprite_add(std::vector& sprites, const std::string& gfx) +{ + ANM2& sprite = sprites.emplace_back(); + anm2_gfx_overrides_apply(gfx, {}, sprite); + sprite.color._tint[3] = 0; +} + +// 006489a0 A locust takes off: it carries its first effect's flags and the extra effects that proc, with their shot +// sprites behind and in front of it and their looks on it. Mom's Knife's locust carries a blade. +static void locust_launch_roll(Entity_Familiar& locust) +{ + LocustConfig& config = familiar_locust_config(locust); + AbyssLocustData& data = locust_data(locust); + LocustEffect& first = config.effects[0]; + + data.tearFlags = first.tearFlags; + data.locustFlags = first.locustFlags; + shot_sprite_add(data.backSprites, first.shootBackGfx); + shot_sprite_add(data.frontSprites, first.shootOverlayGfx); + locust_effects_roll(config, [&](LocustEffect& effect) { + data.tearFlags |= effect.tearFlags; + data.locustFlags |= effect.locustFlags; + anm2_gfx_overrides_apply(effect.shootGfx, {}, locust.sprite); + shot_sprite_add(data.backSprites, effect.shootBackGfx); + shot_sprite_add(data.frontSprites, effect.shootOverlayGfx); + }); + + if (data.locustFlags & LOCUST_FLAG_KNIFE) + { + auto* knife = static_cast( + g_game->Spawn({.position = locust.pos, .spawner = &locust, .type = ENTITY_KNIFE, .seed = Random()})); + knife->parent = &locust; + knife->SetColor(locust.sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + knife->tearFlags = data.tearFlags & ~(TearFlags().set(TEAR_GROW).set(TEAR_SHRINK)); + knife->SetCollisionDamage(locust.collisionDamage * KNIFE_SCALE); + knife->rotationOffset = 0; + knife->sprite.scale = vector_scale(locust.sprite.scale, KNIFE_SCALE); + data.knife = knife; + knife->Update(); + } + anm2_gfx_overrides_apply(first.shootGfx, {}, locust.sprite); +} + +// 0064a2d0 A flying locust breaks the grid two frames ahead, once a cell: an acid or rock locust destroys what tear +// effects can (bridging a pit behind it), anything else takes a hit. Whether a grid was destroyed or hurt. +bool Entity_Familiar::break_grid_ahead() +{ + Room& room = *g_game->room; + int index = room.GetGridIndex(vector_add(pos, vector_scale(velocity, 2))); + AbyssLocustData& data = locust_data(*this); + if (index < 0 || data.lastGridIndex == index) return false; + + data.lastGridIndex = index; + GridEntity* grid = room.GetGridEntity((uint32_t)index); + if (!grid || grid->collisionClass == COLLISION_NONE || grid->collisionClass == COLLISION_PIT) return false; + + LocustConfig& config = familiar_locust_config(*this); + TearFlags flags = config.effects[0].tearFlags; + locust_effects_roll(config, [&](LocustEffect& effect) { flags |= effect.tearFlags; }); + if (grid->CanTakeDamageFromTearEffects() && (flags[TEAR_ACID] || flags[TEAR_ROCK]) && + grid->Destroy(false, EntityRef(this))) + { + Vector step = vector_cardinal(velocity); + if (vector_is_zero(step)) return true; + + int behind = room.GetGridIndex(vector_add(grid->Position(), vector_scale(step, GRID_CELL_SIZE))); + if (behind >= 0) room_bridge_make(room.GetGridEntity((uint32_t)behind), grid); + return true; + } + return grid->Hurt(collisionDamage > 10 ? 2 : 1, EntityRef(this)); +} + +// Part of 00647320: a homing locust bends toward the enemy ahead of it, picking one every four frames. +static void locust_home(Entity_Familiar& locust) +{ + Vector ahead = vector_add(locust.pos, vector_scale(locust.velocity, LOCUST_HOMING_LOOKAHEAD)); + if (!locust.target && locust.IsFrame(HOMING_INTERVAL, (int)locust.index)) + { + Entity* chosen = nullptr; + float best = HOMING_FAR; + for (Entity* enemy : entity_query_radius(ahead, LOCUST_HOMING_RANGE, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET) || + EntityList::HitListContains(locust.hitList, *enemy) || !(Random() & 1)) + continue; + if (locust.entityGridCollisionClass == GRIDCOLL_BULLET && + !room_check_line(locust.pos, enemy->pos, LINE_MODE_PROJECTILE, 0)) + continue; + + float score = vector_distance(enemy->pos, ahead) + random_unit() * HOMING_NOISE; + if (score < best) + { + best = score; + chosen = enemy; + } + } + locust.target = chosen; + } + if (!locust.target) return; + + float speed = vector_length(locust.velocity); + Vector away = vector_normalized(vector_sub(locust.pos, locust.target->pos)); + Vector bent = vector_sub(vector_scale(locust.velocity, HOMING_DRAG), + vector_scale(away, locust.speedMultiplier * HOMING_TURN)); + locust.velocity = vector_resized(bent, speed); +} + +// Part of 00647320: the aura of a glowing locust (its first effect's, or a rolled one's) hurts enemies about it. +static void locust_aura(Entity_Familiar& locust, LocustConfig& config) +{ + bool isGlowing = config.effects[0].tearFlags[TEAR_GLOW]; + for (size_t i = 1; i < config.effects.size() && !isGlowing; i++) + { + LocustEffect& effect = config.effects[i]; + isGlowing = effect.tearFlags[TEAR_GLOW] && effect.procChance != 0 && random_unit() < effect.procChance; + } + if (!isGlowing) return; + + for (Entity* enemy : entity_query_radius(locust.pos, locust.size * AURA_RANGE_SCALE + AURA_RANGE_BASE, QUERY_ALL)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || (locust.spawnerEntity && locust.spawnerEntity->IsDescendantOf(enemy))) + continue; + + float inner = enemy->size + locust.size; + float outer = locust.size * AURA_OUTER_SCALE + enemy->size; + float distance = vector_length_squared(vector_sub(locust.pos, enemy->pos)); + if (inner * inner < distance && distance < outer * outer) + enemy->TakeDamage(AURA_DAMAGE, 0, EntityRef(&locust), AURA_COUNTDOWN); + } +} + +// Part of 00647320: a flying locust. It homes, eats pickups when hungry, and turns back on hitting a wall it faces, on +// straying too far (the bone locust), or once its hit used it up, breaking the grid under it. A returning one chases +// its target while the player still shoots, else slows and rests. Its aura burns and its repelling pushes shots away. +static void locust_fly(Entity_Familiar& locust, LocustConfig& config) +{ + AbyssLocustData& data = locust_data(locust); + Entity_Player& player = *locust.player; + + locust.state = -1; + locust.break_grid_ahead(); + if (locust.fireCooldown == -1) + { + if (config.effects[0].tearFlags[TEAR_HOMING]) locust_home(locust); + if (data.locustFlags & LOCUST_FLAG_HUNGRY) + { + for (Entity* pickup : entity_query_radius(locust.pos, locust.size, QUERY_PICKUPS)) + if (pickup && pickup->is_pickup() && familiar_listed(EATEN_PICKUPS, pickup->variant) && + static_cast(pickup)->price == 0) + Entity::ForceCollide(&locust, pickup, true); + } + } + + bool isWallHit = false; + if (locust.isCollidesWithGrid) + isWallHit = + vector_dot(vector_normalized(locust.gridCollisionVelocity), locust.gridCollisionNormal) > WALL_FACING; + bool isTooFar = locust.subtype == BONE_SUBTYPE && vector_distance(player.pos, locust.pos) > BONE_REACH; + if (isWallHit || isTooFar || locust.fireCooldown < -1) + { + locust.entityGridCollisionClass = GRIDCOLL_NONE; + Room& room = *g_game->room; + int index = room.GetGridIndex(locust.pos); + if (GridEntity* grid = index >= 0 ? room.GetGridEntity((uint32_t)index) : nullptr) + grid->Hurt(1, EntityRef(&player)); + + if (vector_is_zero(locust.targetPosition)) + { + if (data.knife) + { + data.knife->Remove(); + data.knife = nullptr; + } + locust.velocity = vector_scale(locust.velocity, RETURN_DRAG); + if (--locust.fireCooldown < -RETURN_FRAMES) + { + locust.fireCooldown = LAUNCH_REST; + locust.targetPosition = {}; + locust.load_config_graphics(); + } + } + else + { + if (locust.target) locust.targetPosition = locust.target->pos; + if (player.fireDirection == DIRECTION_NONE || locust.fireCooldown < CHASE_LIMIT) locust.targetPosition = {}; + else + { + locust.velocity = vector_scale(locust.velocity, CHASE_DRAG); + if (locust.fireCooldown > CHASE_LIMIT - 1) locust.fireCooldown--; + if (locust.target && locust.target->isDead) locust.target = nullptr; + if (!locust.target && !(Random() & 1)) + { + Entity* chosen = nullptr; + float best = HOMING_FAR; + for (Entity* enemy : entity_query_radius(locust.pos, LOCUST_CHASE_RANGE, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) + continue; + float score = vector_distance(enemy->pos, locust.pos) + random_unit() * HOMING_NOISE; + if (score < best) + { + best = score; + chosen = enemy; + } + } + if (chosen) locust.target = chosen; + } + if (locust.target) locust.fireCooldown = -2; + + Vector pull = vector_scale(vector_sub(locust.targetPosition, locust.pos), CHASE_PULL); + Vector heading = vector_normalized(vector_add(pull, random_direction())); + float speed = random_unit() * SWARM_SPEED_RANGE + SWARM_SPEED_MIN; + locust.velocity = vector_add(locust.velocity, vector_scale(heading, speed * locust.speedMultiplier)); + } + } + } + + if (data.tearFlags[TEAR_GLOW]) locust_aura(locust, config); + if (data.locustFlags & LOCUST_FLAG_REPEL) + { + for (Entity* shot : entity_query_radius(locust.pos, REPEL_RANGE, QUERY_PROJECTILES)) + { + Vector away = vector_sub(shot->pos, locust.pos); + float push = random_unit() * (REPEL_FALLOFF - vector_length(away)) * REPEL_STEP + REPEL_BASE; + shot->velocity = vector_add(shot->velocity, vector_resized(away, push)); + } + } + locust.entityGridCollisionClass = GRIDCOLL_WALLS; + locust.entityCollisionClass = ENTCOLL_ALL; +} + +// Part of 00647320: a resting locust takes off along the player's shot (or at a marked target), carrying the player's +// motion when unaimed, and the other locusts of its player wait a little so they leave one by one (Inner Eye's and +// the like leave together). +static void locust_launch(Entity_Familiar& locust, LocustConfig& config) +{ + Entity_Player& player = *locust.player; + Vector aim = direction_unit(player.fireDirection); + int direction = player.fireDirection; + bool isMarked = locust.TryAimAtMarkedTarget(aim, direction, nullptr); + + locust.pos = + g_game->room->GetClampedPositionImpl(locust.pos, LAUNCH_MARGIN, LAUNCH_MARGIN, LAUNCH_MARGIN, LAUNCH_MARGIN); + locust.friction = 1; + locust.velocity = vector_scale(aim, config.speed * LAUNCH_SPEED); + locust_data(locust).lastGridIndex = -1; + if (!isMarked) + { + Vector inherited = vector_scale(player.velocity, LAUNCH_INHERIT * 2); + Vector along = vector_normalized(aim); + Vector forward = vector_scale(along, vector_dot(inherited, along)); + if (vector_dot(forward, aim) < 0) inherited = vector_sub(inherited, forward); + locust.velocity = vector_add(locust.velocity, inherited); + } + locust.state = -1; + locust.fireCooldown = -1; + + std::vector swarm; + bool isTogether = config.effects[0].locustFlags & LOCUST_FLAG_SWARM; + for (Entity_Familiar* other : familiar_query(locust.variant)) + { + bool isOtherTogether = familiar_locust_config(*other).effects[0].locustFlags & LOCUST_FLAG_SWARM; + if (other->player == locust.player && (!isTogether || !isOtherTogether)) swarm.push_back(other); + } + int delay = std::max(SWARM_DELAY_MAX - (int)swarm.size() / 2, SWARM_DELAY_MIN); + for (Entity_Familiar* other : swarm) + if (other != &locust && other->fireCooldown >= 0 && other->fireCooldown < delay) other->fireCooldown = delay; + locust_launch_roll(locust); +} + +// 00647320 An Abyss locust's frame. Fresh ones fly out, then the swarm buzzes about the player, each locust launching +// along the player's shots once rested, flying until its hit or a wall turns it back, then returning. Mom's Knife's +// blade follows it. +void locust_update(Entity_Familiar& locust) +{ + LocustConfig& config = familiar_locust_config(locust); + AbyssLocustData& data = locust_data(locust); + Entity_Player& player = *locust.player; + + locust.AddEntityFlags(FLAG_NO_KNOCKBACK | FLAG_NO_PHYSICS_KNOCKBACK); + if (locust.state >= 1) + { + locust.state--; + locust.entityCollisionClass = ENTCOLL_NONE; + locust.friction *= SPAWN_FRICTION; + if (locust.state == 0) locust.entityCollisionClass = locust.CanBlockProjectiles() ? ENTCOLL_ALL : ENTCOLL_NONE; + } + else if (locust.fireCooldown < 0) locust_fly(locust, config); + else + { + if (locust.state == -1 && vector_distance(locust.pos, player.pos) < SWARM_REJOIN) locust.state = 0; + if (locust.state == 0) + { + locust.velocity = vector_scale(locust.velocity, CHASE_DRAG); + float angle = random_unit() * RANDOM_HALF_TURN * 2; + Vector pull = vector_scale(vector_sub(player.pos, locust.pos), LOCUST_SWARM_PULL); + Vector heading = vector_normalized(vector_add(vector_make(std::cos(angle), std::sin(angle)), pull)); + float speed = random_unit() * SWARM_SPEED_RANGE + SWARM_SPEED_MIN; + locust.velocity = vector_add(locust.velocity, vector_scale(heading, speed * locust.speedMultiplier)); + } + else + { + Vector toPlayer = vector_sub(player.pos, locust.pos); + float distance = vector_length(toPlayer); + float pull = distance < RETURN_STOP ? 0 : std::min(distance * RETURN_PULL, RETURN_SPEED) / distance; + locust.velocity = vector_add(locust.velocity, vector_scale(toPlayer, pull)); + locust.friction *= RETURN_FRICTION; + } + + if (locust.fireCooldown > 0 && locust.state == 0) locust.fireCooldown--; + if (locust.fireCooldown == 0 && player.fireDirection != DIRECTION_NONE) locust_launch(locust, config); + locust.entityGridCollisionClass = GRIDCOLL_NONE; + locust.entityCollisionClass = locust.CanBlockProjectiles() ? ENTCOLL_ALL : ENTCOLL_NONE; + } + + auto* knife = static_cast(data.knife.get()); + if (!knife) return; + knife->SetCollisionDamage(locust.collisionDamage * KNIFE_SCALE); + knife->sprite.scale = vector_scale(locust.sprite.scale, KNIFE_SCALE); + knife->posOffset = vector_make(locust.posOffset.x, locust.posOffset.y - locust.sprite.scale.y * KNIFE_HEIGHT); + knife->rotation = + (float)((uint32_t)(vector_distance(player.pos, locust.pos) * KNIFE_SPIN) % (uint32_t)FULL_TURN_DEGREES); +} + +// 0064b6c0 Draws one of a locust's shot sprites: fading in while it flies and out after (dropped once gone), at a +// share of its config scale. +void Entity_Familiar::render_abyss_locust_sprite(ANM2& shot, const Vector& offset) +{ + if (!shot.isLoaded) return; + + float alpha = shot.color._tint[3] + (state == -1 ? SHOT_FADE_STEP : -SHOT_FADE_STEP); + alpha = std::clamp(alpha, 0.0f, 1.0f); + if (alpha == 0 && state != -1) return shot.Reset(); + + shot.color._tint[3] = alpha; + if (alpha <= 0) return; + float scale = familiar_locust_config(*this).scale * SHOT_SPRITE_SCALE; + shot.scale = vector_make(scale * sizeMulti.x, scale * sizeMulti.y); + shot.Update(); + Vector screen = render_position_get(vector_make(pos.x, pos.y - SHOT_SPRITE_RAISE), RENDER_SNAPPED); + shot.Render({.position = vector_add(screen, offset)}); +} + +// Part of 00624e10: a locust between its back and front shot sprites. Faded sprites are dropped, which the original +// keeps until the locust goes. +void locust_render(Entity_Familiar& locust, const Vector& offset) +{ + AbyssLocustData& data = locust_data(locust); + auto faded = [](ANM2& sprite) { + return !sprite.isLoaded; + }; + + for (ANM2& shot : data.backSprites) locust.render_abyss_locust_sprite(shot, offset); + locust.Entity::Render(offset); + for (ANM2& shot : data.frontSprites) locust.render_abyss_locust_sprite(shot, offset); + std::erase_if(data.backSprites, faded); + std::erase_if(data.frontSprites, faded); +} + +// Part of 00649290: the creep a locust's creep flag leaves, in its color. +static void locust_creep(Entity_Familiar& locust, uint32_t locustFlags) +{ + ColorMod color = LOCUST_GREEN_COLOR; + if (locustFlags & LOCUST_FLAG_LEMON_CREEP) color = LOCUST_LEMON_COLOR; + if (locustFlags & LOCUST_FLAG_BLOOD_CREEP) color = LOCUST_BLOOD_COLOR; + if (locustFlags & LOCUST_FLAG_HOLY_CREEP) color = LOCUST_HOLY_COLOR; + if (locustFlags & LOCUST_FLAG_GREEN_CREEP) color = LOCUST_GREEN_COLOR; + + Vector spot = g_game->room->GetClampedPositionImpl(locust.pos, LOCUST_CREEP_MARGIN, LOCUST_CREEP_MARGIN, + LOCUST_CREEP_MARGIN, LOCUST_CREEP_MARGIN); + Entity* creep = g_game->Spawn({.position = spot, + .spawner = locust.spawnerEntity, + .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_GREEN, + .seed = Random()}); + creep->sprite.scale = vector_scale(locust.sprite.scale, LOCUST_CREEP_SCALE); + creep->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + creep->Update(); +} + +// Part of 00649290: a rift where the locust hit, holding enemies at a quarter of the player's damage. +static void locust_rift(Entity_Familiar& locust, float scale) +{ + Room& room = *g_game->room; + if (!room.IsPositionInRoom(locust.pos, RIFT_MARGIN)) return; + + auto* rift = + static_cast(g_game->Spawn({.position = room.GetClampedPositionImpl(locust.pos, 0, 0, 0, 0), + .spawner = locust.player, + .type = ENTITY_EFFECT, + .variant = EFFECT_RIFT, + .seed = Random()})); + rift->sprite.scale = vector_make(scale, scale); + rift->SetCollisionDamage(locust.player->damage * RIFT_DAMAGE); + rift->timeout = rift->lifespan = familiar_versus() ? RIFT_VERSUS_FRAMES : RIFT_FRAMES; + rift->Update(); + familiar_sound_play(SOUND_OCCULAR_RIFT_PORTAL); +} + +// 00649290 What a locust's hit sets off besides the tear effects: bone shards, a rift, an explosion, Black Powder's +// circle, creep, the Necronomicon, the Maw of the Void's ring, farts and a brimstone beam. Jacob's Ladder, devolving, +// erasing and the shockwave stop the game. +static void locust_hit_effects(Entity_Familiar& locust, const TearFlags& flags, uint32_t locustFlags, Entity& target) +{ + Entity_Player& player = *locust.player; + if (flags[TEAR_BONE_FLAG]) + { + TearFlags shardFlags = flags; + shardFlags.reset(TEAR_BONE_FLAG).reset(TEAR_LUDOVICO); + for (int i = 0; i < LOCUST_BONE_SHARDS; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + Vector velocity = vector_make(std::cos(angle) * BONE_SHARD_SPEED, std::sin(angle) * BONE_SHARD_SPEED); + auto* shard = static_cast(g_game->Spawn({.position = vector_sub(locust.pos, locust.velocity), + .velocity = velocity, + .spawner = &player, + .type = ENTITY_TEAR, + .variant = TEAR_BONE, + .seed = Random()})); + shard->SetCollisionDamage(player.damage * BONE_SHARD_DAMAGE); + shard->SetTearFlags(shardFlags); + shard->SetColor(locust.sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + shard->parent = locust.parent; + shard->Update(); + } + } + if (flags[TEAR_JACOBS]) + reconstruction_missing("Entity_Familiar::apply_tear_flag_effects 00649290 (Jacob's Ladder)"); + if (flags[TEAR_RIFT]) locust_rift(locust, locust.sprite.scale.x); + + if (locustFlags & LOCUST_FLAG_EXPLODE) + explosion_effects({.color = locust.sprite.color, + .position = locust.pos, + .source = &locust, + .damage = LOCUST_BLAST_DAMAGE, + .radiusMultiplier = LOCUST_BLAST_RADIUS}); + if (locustFlags & LOCUST_FLAG_BLACK_POWDER) + { + auto* circle = static_cast(g_game->Spawn({.position = locust.pos, + .spawner = &locust, + .type = ENTITY_EFFECT, + .variant = EFFECT_PENTAGRAM_BLACKPOWDER, + .seed = Random()})); + circle->timeout = PENTAGRAM_FRAMES; + circle->lifespan = PENTAGRAM_FRAMES; + circle->scale = locust.sprite.scale.x * PENTAGRAM_SCALE; + circle->Update(); + } + if (locustFlags & LOCUST_FLAGS_CREEP) locust_creep(locust, locustFlags); + if ((locustFlags & LOCUST_FLAG_DEVOLVE) && target.CanDevolve()) + reconstruction_missing("Entity_Familiar::apply_tear_flag_effects 00649290 (devolving, Game::DevolveEnemy)"); + if (locustFlags & LOCUST_FLAG_NECRONOMICON) + player.UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM}); + if ((locustFlags & LOCUST_FLAG_ERASE) && target.IsVulnerableEnemy(nullptr)) + reconstruction_missing("Entity_Familiar::apply_tear_flag_effects 00649290 (Eraser, Game::AddErasedEnemy)"); + if (locustFlags & LOCUST_FLAG_SHOCKWAVE) + reconstruction_missing("Entity_Familiar::apply_tear_flag_effects 00649290 (Larynx's shockwave)"); + if (locustFlags & LOCUST_FLAG_MAW) + { + Entity_Laser* ring = player.SpawnMawOfVoid(LOCUST_MAW_TIMEOUT); + ring->pos = locust.pos; + ring->isDisableFollowParent = true; + ring->damageMultiplier = MAW_SCALE; + ring->scale = MAW_SCALE; + ring->ResetSpriteScale(); + ring->radius *= MAW_RADIUS_SCALE; + ring->Update(); + } + if (locustFlags & LOCUST_FLAG_FART) + game_fart({.position = locust.pos, .source = &locust, .radius = LOCUST_FART_RADIUS, .scale = FART_SCALE}); + if (locustFlags & LOCUST_FLAG_BUTTER_BEAN) + game_butter_bean_fart( + {.position = locust.pos, .source = &player, .radius = LOCUST_BUTTER_BEAN_RADIUS, .isSuperKnockback = true}); + if (locustFlags & LOCUST_FLAG_BRIMSTONE) + { + Entity_Laser* beam = Weapon::FireBrimstone( + {.direction = vector_cardinal(locust.velocity), .position = locust.pos, .entity = &locust}); + beam->tearFlags.set(TEAR_WAIT); + beam->scale *= LOCUST_BRIMSTONE_SCALE; + beam->ResetSpriteScale(); + } + if (flags[TEAR_RIFT]) locust_rift(locust, RIFT_SCALE); +} + +// Part of 006261f0: a flying locust hits an enemy once a hit list. Its damage comes from its item's quality and the +// extra effects that proc (a random locust picks one more), the player's damage and its hunger. The hit's tear and +// locust effects follow, it turns back unless piercing, Tainted Apollyon's Birthright marks the enemy, and the enemy is +// pushed away unless it holds still. +void locust_touch(Entity_Familiar& locust, Entity& enemy) +{ + if (locust.state != -1 || !enemy.IsEnemy() || locust.IsDescendantOf(&enemy)) return; + bool isHittable = enemy.IsVulnerableEnemy(nullptr) || enemy.type == ENTITY_FIREPLACE || + enemy.type == ENTITY_MOVABLE_TNT || enemy.type == ENTITY_POOP; + if (!isHittable || EntityList::HitListContains(locust.hitList, enemy)) return; + + hit_list_insert(locust.hitList, enemy); + LocustConfig& config = familiar_locust_config(locust); + AbyssLocustData& data = locust_data(locust); + TearFlags flags = config.effects[0].tearFlags; + uint32_t locustFlags = config.effects[0].locustFlags; + float damage = 1; + if (locust.item) + { + bool isBestFriend = locust.item->IsTrinket() && locust.item->id == TRINKET_APOLLYONS_BEST_FRIEND; + int quality = isBestFriend ? APOLLYONS_BEST_FRIEND_QUALITY : locust.item->quality; + if (quality >= 0 && quality < LOCUST_QUALITY_COUNT) damage = QUALITY_DAMAGE[quality]; + } + float qualityDamage = damage; + bool isProcced = false; + locust_effects_roll(config, [&](LocustEffect& effect) { + flags |= effect.tearFlags; + locustFlags |= effect.locustFlags; + damage *= effect.damageMultiplier; + isProcced = true; + }); + if (!isProcced) damage = qualityDamage * config.effects[0].damageMultiplier; + damage *= locust.GetMultiplier() * MULTIPLIER_DAMAGE_STEP + MULTIPLIER_DAMAGE_BASE; + + if (locustFlags & LOCUST_FLAG_RANDOM) + { + int pick = (int)(Random() % RANDOM_LOCUST_PICKS); + if (pick < RANDOM_PICK_EXPLODE) flags.set(RANDOM_TEAR_FLAGS[pick]); + else if (pick == RANDOM_PICK_EXPLODE) locustFlags |= LOCUST_FLAG_EXPLODE; + else if (pick == RANDOM_PICK_FART) locustFlags |= LOCUST_FLAG_FART; + else if (pick == RANDOM_PICK_BUTTER_BEAN) locustFlags |= LOCUST_FLAG_BUTTER_BEAN; + else if (pick == RANDOM_PICK_CREEP) locustFlags |= LOCUST_CREEPS[Random() & 3]; + else locustFlags |= LOCUST_FLAG_BLACK_POWDER; + } + damage = damage * locust.player->damage + (float)data.hunger * HUNGER_DAMAGE; + + uint64_t damageFlags = tear_damage_flags_get(flags, &locust); + enemy.TakeDamage(damage, damageFlags, EntityRef(&locust), LOCUST_HIT_COUNTDOWN); + Entity_Tear::ApplyTearFlagEffects(&enemy, locust.pos, flags, &locust, damage); + locust_hit_effects(locust, flags, locustFlags, enemy); + if (locust.fireCooldown == -1 && !flags[TEAR_PIERCING]) locust.fireCooldown = -2; + + Entity_Player& player = *locust.player; + if (player.playerType == PLAYER_APOLLYON_B && player.HasCollectible(COLLECTIBLE_BIRTHRIGHT) && + enemy.IsVulnerableEnemy(nullptr) && (vector_is_zero(locust.targetPosition) || !locust.target)) + { + locust.target = &enemy; + locust.targetPosition = locust.pos; + } + if (enemy.HasEntityFlags(FLAG_NO_KNOCKBACK)) return; + + Vector push = vector_normalized(locust.velocity); + float mass = enemy.collision_mass_get(&locust); + if (mass > 0) push = vector_scale(push, 1 / mass); + enemy.AddVelocity_divided(vector_scale(push, locust.mass * LOCUST_PUSH), false); +} + +// Part of 006261f0: a shielding locust stops the shots it touches. Another rolls its extra shielding effects once per +// shot, stopping it on a proc. +bool locust_block(Entity_Familiar& locust, Entity& shot, bool isIgnored) +{ + LocustConfig& config = familiar_locust_config(locust); + AbyssLocustData& data = locust_data(locust); + if (!config.effects[0].tearFlags[TEAR_SHIELDED]) + { + if (data.checkedShots.contains(shot.index)) return isIgnored; + bool isStopped = false; + for (size_t i = 1; i < config.effects.size() && !isStopped; i++) + { + LocustEffect& effect = config.effects[i]; + isStopped = effect.tearFlags[TEAR_SHIELDED] && effect.procChance > 0 && random_unit() < effect.procChance; + } + if (!isStopped) + { + data.checkedShots.insert(shot.index); + return isIgnored; + } + } + shot.isDead = true; + return isIgnored; +} diff --git a/src/familiar_missing.cpp b/src/familiar_missing.cpp index f139759..64f1581 100644 --- a/src/familiar_missing.cpp +++ b/src/familiar_missing.cpp @@ -3,42 +3,12 @@ // The rest of Entity_Familiar, which the familiars this round does not reach call: each stops the game with its name. -// 00436330 - -// 00436fd0 - -// 004386f0 - -// 0043a5e0 - -// 0043aa90 - -// 0043db20 -void Entity_Familiar::ai_mr_me_wisp() -{ - reconstruction_missing("Entity_Familiar::ai_mr_me_wisp 0043db20"); -} - -// 0043e4a0 -void Entity_Familiar::ai_mega_blast_wisp() -{ - reconstruction_missing("Entity_Familiar::ai_mega_blast_wisp 0043e4a0"); -} - -// 0043eb10 - // 0060d180 KColor* Entity_Familiar::GetPlayerSlot(KColor*, Entity_Player*) { reconstruction_missing("Entity_Familiar::GetPlayerSlot 0060d180"); } -// 0060ddd0 -void Entity_Familiar::set_locust_config_index(int) -{ - reconstruction_missing("Entity_Familiar::set_locust_config_index 0060ddd0"); -} - // 0062c8d0 A pill's effect on the player's familiars: only Acid Baby and Lil Spewer react, which is not written yet. void Entity_Familiar::farting_baby_fart() { @@ -124,24 +94,12 @@ void Entity_Familiar::minisaac_find_target() reconstruction_missing("Entity_Familiar::minisaac_find_target 0063dd60"); } -// 00640ca0 -void Entity_Familiar::ai_boiled_baby() -{ - reconstruction_missing("Entity_Familiar::ai_boiled_baby 00640ca0"); -} - // 006424d0 void Entity_Familiar::ai_bird_cage() { reconstruction_missing("Entity_Familiar::ai_bird_cage 006424d0"); } -// 006431d0 -void Entity_Familiar::ai_bot_fly() -{ - reconstruction_missing("Entity_Familiar::ai_bot_fly 006431d0"); -} - // 006444d0 Entity* Entity_Familiar::aim_reflected_projectile() { @@ -154,42 +112,6 @@ void Entity_Familiar::ai_shadow_intruder_damocles(bool) reconstruction_missing("Entity_Familiar::ai_shadow_intruder_damocles 00644e80"); } -// 006470c0 -void* Entity_Familiar::get_item_config_entry() -{ - reconstruction_missing("Entity_Familiar::get_item_config_entry 006470c0"); -} - -// 00647170 -uint8_t Entity_Familiar::abyss_locust_eat() -{ - reconstruction_missing("Entity_Familiar::abyss_locust_eat 00647170"); -} - -// 0064a2d0 -uint8_t Entity_Familiar::break_grid_ahead() -{ - reconstruction_missing("Entity_Familiar::break_grid_ahead 0064a2d0"); -} - -// 0064a830 -void Entity_Familiar::load_config_graphics() -{ - reconstruction_missing("Entity_Familiar::load_config_graphics 0064a830"); -} - -// 0064b6c0 -void Entity_Familiar::render_abyss_locust_sprite(ANM2*, float*) -{ - reconstruction_missing("Entity_Familiar::render_abyss_locust_sprite 0064b6c0"); -} - -// 0064b920 -void Entity_Familiar::siren_charm(Entity*, Entity_Player*) -{ - reconstruction_missing("Entity_Familiar::siren_charm 0064b920"); -} - // 0064bab0 void Entity_Familiar::RemoveFromPlayer() { diff --git a/src/familiar_repentance.cpp b/src/familiar_repentance.cpp new file mode 100644 index 0000000..a1b277e --- /dev/null +++ b/src/familiar_repentance.cpp @@ -0,0 +1,747 @@ +#include "entity_familiar.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "capsule.h" +#include "game.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "room.h" +#include "room_grid.h" +#include "seeds.h" +#include +#include + +// Intruder: how often it shoots from the player's head, its drag, how far ahead it leads a target with its spit and +// with its hops, how far past the target it lands, its hops' reach, pace and landing spots, and its spits. +constexpr int INTRUDER_HEAD_FIRE_DELAY = 45; +constexpr float INTRUDER_FRICTION = 0.7f; +constexpr float INTRUDER_SPIT_LEAD = 0.075f; +constexpr float INTRUDER_HOP_LEAD = 0.08f; +constexpr float INTRUDER_HOP_PAST = 60; +constexpr float INTRUDER_HOP_REACH = 180; +constexpr float INTRUDER_HOP_STEP = 0.02f; +constexpr float INTRUDER_HOP_SPOT_STEP = 10; +constexpr float INTRUDER_IDLE_SPOT_STEP = 80; +constexpr float INTRUDER_SPIT_RANGE = 180; +constexpr int INTRUDER_SPIT_COOLDOWN = 15; +constexpr int INTRUDER_SPIT_REST = 20; +constexpr int INTRUDER_HOP_REST = 5; +constexpr int INTRUDER_SPITS_MIN = 2; +constexpr uint32_t INTRUDER_SPITS_MASK = 3; +constexpr TargetSearch INTRUDER_SEARCH = { + .coneAngle = 15, .range = 1000, .frameInterval = 1, .flags = TARGET_RETARGET | TARGET_PREFER_WEAK}; +constexpr int REVENGE_SPAWNER_DEPTH = 10; + +// Tinytoma: how it chases its orbit spot (half the gap, at most 4 a frame) ahead of the player, its orbit, its +// pieces' growth back to size, the explosions it takes at most 3.5 from, its regrowth after shedding, its touch's push +// and the hits it takes, and its death's splats and gibs. +constexpr float TINYTOMA_PULL = 0.5f; +constexpr float TINYTOMA_SPEED = 4; +constexpr float TINYTOMA_SNAP = 5; +constexpr int TINYTOMA_ORBIT = 6; +constexpr int TINYTOMA_PIECES = 2; +constexpr int TINYTOMA_PIECE_LIMIT = 2; +constexpr float TINYTOMA_SPAWN_SIZE = 0.01f; +constexpr float TINYTOMA_GROWTH = 0.03f; +constexpr float TINYTOMA_SOLID_SIZE = 0.8f; +constexpr float TINYTOMA_BLAST_CAP = 3.5f; +constexpr int TINYTOMA_SHED_FRAMES = 450; +constexpr int TINYTOMA_REGROW_FRAMES = 150; +constexpr int TINYTOMA_REST_FRAMES = 30; +constexpr float TINYTOMA_PUSH = 2; +constexpr float TINYTOMA_HURT = 3.5f; +constexpr int TINYTOMA_TOUCH_COUNTDOWN = 30; +constexpr float TINYTOMA_PIECE_SPREAD = 10; +constexpr ColorMod TINYTOMA_SPLAT = {{0.2f, 0.2f, 0.2f, 1}, {1, 1, 1, 1}, {0, 0, 0}}; +constexpr int TINYTOMA_GIBS_MIN = 3; +constexpr uint32_t TINYTOMA_GIBS_RANGE = 5; +constexpr float TINYTOMA_GIB_SPEED_MIN = 2; +constexpr float TINYTOMA_GIB_SPEED_RANGE = 4; +constexpr int TINYTOMA_SPIDERS_MIN = 2; +constexpr float TINYTOMA_SPIDER_STEP = 40; +constexpr float TINYTOMA_SPIDER_LIFT = -30; +constexpr int BLAST_SPLAT_SUBTYPE = 3; + +// Bot Fly: how far it looks for shots, how it scores them (nearness to the player, speed, heading at the player), its +// shield shot (with no target it fires sideways with the player's motion) and how often it fires in versus. +constexpr float BOT_FLY_RANGE = 128; +constexpr float THREAT_LEAD = 0.05f; +constexpr float THREAT_NEAR = 200; +constexpr float THREAT_NEAR_SCALE = 3; +constexpr float THREAT_BASE = 100; +constexpr float THREAT_HEADING_SCALE = 1200; +constexpr float THREAT_HEADING_MIN = 0.5f; +constexpr float THREAT_SPEED_SCALE = 100; +constexpr float THREAT_SPEED_CAP = 600; +constexpr float THREAT_HEIGHT_MIN = -50; +constexpr float THREAT_SPEED_MIN = 1e-5f; +constexpr float THREAT_NONE = -1e10f; +constexpr float BOT_FLY_SHOT_SPEED = 15; +constexpr float BOT_FLY_SHOT_LEAD = 0.05f; +constexpr float BOT_FLY_SHOT_INHERIT = 0.6f; +constexpr float BOT_FLY_SHOT_DAMAGE = 3; +constexpr float BOT_FLY_SHOT_SCALE = 0.8f; +constexpr float BOT_FLY_SHOT_FALL = 0.2f; +constexpr uint32_t BOT_FLY_VERSUS_ODDS = 3; +constexpr int PROJECTILE_ENEMY_SHOT_EXCLUDED = 14; + +// target_threatening_projectile's flags: whether its pick replaces the target even when none is found, and whether +// it leaves out the shots' heading at the player. +enum ThreatSearch : uint32_t +{ + THREAT_KEEP = 0, + THREAT_ALWAYS_ASSIGN = 1 << 0, + THREAT_NO_HEADING = 1 << 1 +}; + +// Lil Dumpy: how it trails 10 behind the player (looks by distance), how near the player it watches for danger, how +// far ahead it looks and how much wider than the player, its fart and the launch off the danger, its rest, how near it +// must land to wake, and its damage while flying. +constexpr float DUMPY_TRAIL = 10; +constexpr float DUMPY_FAST = 40; +constexpr float DUMPY_FASTER = 80; +constexpr float DUMPY_PULL = 0.2f; +constexpr float DUMPY_DRAG = 0.8f; +constexpr float DUMPY_GUARD_RANGE = 100; +constexpr float DUMPY_SEARCH_RANGE = 150; +constexpr float DUMPY_MARGIN_MIN = 10; +constexpr float DUMPY_MARGIN_RANGE = 10; +constexpr float DUMPY_FART_RADIUS = 120; +constexpr float DUMPY_GIGANTE_SCALE = 2; +constexpr float DUMPY_LAUNCH_SPEED = 20; +constexpr int DUMPY_REST_FRAMES = 45; +constexpr float DUMPY_WAKE_DISTANCE_SQUARED = 2500; +constexpr float DUMPY_SLEEP_FRICTION = 0.95f; +constexpr float DUMPY_HIT_SPEED_MIN = 10; +constexpr float DUMPY_HIT_SPEED_RANGE = 30; +constexpr float DUMPY_HIT_DAMAGE = 25; +constexpr int WHITE_FIREPLACE = 4; + +// How long a familiar the Siren charms rests before acting. +constexpr int SIREN_CHARM_REST = 45; + +// Intruder's states: in the player's head, then out as a spider idling or hopping (while the Intruder effect lasts). +enum IntruderState +{ + INTRUDER_IN_HEAD, + INTRUDER_IDLE, + INTRUDER_HOPPING +}; + +// Boiled Baby: how often it may burst while enemies are near, the odds of a burst (lower with none in range), the +// range (a charmed one's wider), the burst's tears, their arc, sizes and damage. +constexpr int BOILED_CHECK_INTERVAL = 4; +constexpr float BOILED_RANGE = 80; +constexpr float BOILED_CHARMED_RANGE = 180; +constexpr int BOILED_NEAR_ODDS = 5; +constexpr int BOILED_FAR_ODDS = 20; +constexpr int BOILED_TEARS_MIN = 4; +constexpr int BOILED_TEARS_RANGE = 3; +constexpr float BOILED_SPEED = 10; +constexpr float BOILED_SPEED_MIN = 0.7f; +constexpr float BOILED_SPEED_RANGE = 0.2f; +constexpr float BOILED_FALL_ACCEL = 0.8f; +constexpr float BOILED_LIFT = 25; +constexpr float BOILED_SIZE_JITTER = 0.05f; +constexpr float BOILED_SMALL_SIZE = 0.9f; +constexpr float BOILED_BIG_SIZE = 1.3f; +constexpr float BOILED_SIZE_SCALE = 0.8f; +constexpr float BOILED_DAMAGE = 3.5f; +constexpr float BOILED_BIG_DAMAGE = 1.5f; +constexpr float BOILED_DELIRIUM_COLORIZE[] = {2.4f, 2.4f, 2.4f, 1}; + +// Part of 0061da10 (00640ca0): Intruder hops toward enemies and spits cobwebs at them while the Intruder effect is on. +// Otherwise it sits in the player's head, unseen, shooting the way the player shoots. +void intruder_update(Entity_Familiar& intruder) +{ + Entity_Player& player = *intruder.player; + ANM2& sprite = intruder.sprite; + + bool isOut = player.temporaryEffects.HasNullEffect(NULLITEM_INTRUDER); + intruder.friction *= INTRUDER_FRICTION; + if (!isOut) + { + intruder.isVisible = false; + intruder.pos = player.pos; + if (player.isDead) return; + if (intruder.fireCooldown > 0) intruder.fireCooldown--; + if (player.fireDirection != DIRECTION_NONE && intruder.fireCooldown < 1) + { + intruder.FireProjectile(direction_unit(player.fireDirection), FIRE_INHERIT_MOTION); + intruder.fireCooldown = INTRUDER_HEAD_FIRE_DELAY; + } + if (intruder.state == INTRUDER_IN_HEAD) return; + } + else if (intruder.state == INTRUDER_IN_HEAD) + { + intruder.isVisible = true; + intruder.state = INTRUDER_IDLE; + intruder.velocity = {}; + intruder.coins = 0; + intruder.keys = 1; + intruder.hearts = (int)(Random() & INTRUDER_SPITS_MASK) + INTRUDER_SPITS_MIN; + } + + if (intruder.state == INTRUDER_HOPPING && isOut) + { + sprite.Play("Hop"); + if (sprite.IsFinished("Hop")) + { + intruder.state = INTRUDER_IDLE; + intruder.coins = INTRUDER_HOP_REST; + intruder.hearts = (int)(Random() & INTRUDER_SPITS_MASK) + INTRUDER_SPITS_MIN; + } + } + else if (intruder.state == INTRUDER_IDLE && isOut) + { + if (!sprite.IsPlaying("Shoot")) sprite.Play("Idle"); + else if (sprite.IsEventTriggered("Shoot") && intruder.target) + { + Entity& target = *intruder.target; + float lead = vector_distance(intruder.pos, target.pos) * INTRUDER_SPIT_LEAD; + Vector aim = vector_sub(vector_add(target.pos, vector_scale(target.velocity, lead)), intruder.pos); + intruder.FireProjectile(vector_normalized(aim), FIRE_EXACT); + } + + if (intruder.keys < 1 && !intruder.target) intruder.PickEnemyTarget(INTRUDER_SEARCH); + Entity* target = intruder.target; + bool isSpitting = target && (target->IsVulnerableEnemy(nullptr) || target->is_player()) && + intruder.hearts >= 1 && vector_distance(intruder.pos, target->pos) < INTRUDER_SPIT_RANGE && + room_check_line(intruder.pos, target->pos, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD); + if (intruder.keys < 1 && isSpitting) + { + sprite.Play("Shoot"); + intruder.hearts--; + intruder.keys = INTRUDER_SPIT_COOLDOWN; + intruder.coins = INTRUDER_SPIT_REST; + } + else if (intruder.coins < 1) + { + intruder.PickEnemyTarget(INTRUDER_SEARCH); + FreeSpotSearch spot = { + .position = player.pos, .step = INTRUDER_IDLE_SPOT_STEP, .isAvoidActiveEntities = true}; + if (Entity* chased = intruder.target) + { + float lead = vector_distance(intruder.pos, chased->pos) * INTRUDER_HOP_LEAD; + Vector ahead = vector_add(chased->pos, vector_scale(chased->velocity, lead)); + Vector past = vector_scale(vector_normalized(vector_sub(ahead, intruder.pos)), INTRUDER_HOP_PAST); + spot = { + .position = vector_add(ahead, past), .step = INTRUDER_HOP_SPOT_STEP, .isAvoidActiveEntities = true}; + } + if (vector_distance(intruder.pos, spot.position) > INTRUDER_HOP_REACH) + { + Vector reach = + vector_scale(vector_normalized(vector_sub(spot.position, intruder.pos)), INTRUDER_HOP_REACH); + spot.position = vector_add(intruder.pos, reach); + } + intruder.targetPosition = room_free_pickup_position_find(spot); + intruder.orbitSpeed = 0; + intruder.state = INTRUDER_HOPPING; + } + else + { + if (intruder.keys > 0) intruder.keys--; + intruder.coins--; + } + } + + bool isHopping = + intruder.state == INTRUDER_IDLE || (intruder.state == INTRUDER_HOPPING && sprite.WasEventTriggered("Jump")); + if (intruder.state == INTRUDER_IN_HEAD || vector_is_zero(intruder.targetPosition) || !isHopping) return; + + intruder.orbitSpeed += INTRUDER_HOP_STEP; + Vector step = vector_scale(vector_sub(intruder.targetPosition, intruder.pos), intruder.orbitSpeed); + intruder.velocity = vector_scale(step, 1 / intruder.friction); + if (intruder.orbitSpeed >= 1) intruder.targetPosition = {}; +} + +// Part of 0062b750: Intruder in the player's head marks what hurt the player, followed back through its spawners to an +// enemy (or a versus player). Friendly enemies are spared, except Blood Puppy and Dark Esau. +void intruder_player_hurt(Entity_Familiar& intruder, const DamageEvent& hit) +{ + Entity* source = hit.source.entity; + if (intruder.state != INTRUDER_IN_HEAD || !source) return; + + bool isVersus = familiar_versus(); + for (int depth = 1; !(isVersus && source->is_player()) && !Entity::is_enemy_type(source->type); depth++) + { + if (!source->spawnerEntity || depth >= REVENGE_SPAWNER_DEPTH) return; + source = source->spawnerEntity; + } + if (isVersus && source->is_player() && !Entity::is_enemy_type(source->type)) return; + + bool isTargetable = source->entityCollisionClass != ENTCOLL_NONE && + source->entityCollisionClass != ENTCOLL_PLAYERONLY && !source->isInvincible && !source->isDead; + bool isFoe = !source->HasEntityFlags(FLAG_FRIENDLY) || source->type == ENTITY_BLOOD_PUPPY || + source->type == ENTITY_DARK_ESAU; + if (isTargetable && isFoe) intruder.target = source; +} + +// One of Boiled Baby's burst: a blood tear (an enemy shot for a charmed one) arcing up, small or big. +static void boiled_shot_fire(Entity_Familiar& baby, float damage) +{ + Vector velocity = + vector_scale(random_direction(), BOILED_SPEED * (random_unit() * BOILED_SPEED_RANGE + BOILED_SPEED_MIN)); + bool isCharmed = baby.HasEntityFlags(FLAG_CHARM); + ColorMod color = COLOR_DEFAULT; + if (!isCharmed && baby.isLilDelirium) std::ranges::copy(BOILED_DELIRIUM_COLORIZE, color._colorize); + + Entity* shot = g_game->Spawn({.position = baby.pos, + .velocity = velocity, + .spawner = &baby, + .type = isCharmed ? ENTITY_PROJECTILE : ENTITY_TEAR, + .variant = isCharmed ? 0 : TEAR_BLOOD, + .seed = Random()}); + float lift = -(random_unit() * BOILED_LIFT); + bool isBig = random_below(2) != 0; + float size = + (random_unit() * BOILED_SIZE_JITTER + (isBig ? BOILED_BIG_SIZE : BOILED_SMALL_SIZE)) * BOILED_SIZE_SCALE; + if (isCharmed) + { + auto* projectile = static_cast(shot); + projectile->fallingAccel = BOILED_FALL_ACCEL; + projectile->fallingSpeed = lift; + projectile->scale = size; + } + else + { + auto* tear = static_cast(shot); + tear->fallingAccel = BOILED_FALL_ACCEL; + tear->fallingSpeed = lift; + tear->SetTearFlags({}); + tear->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + tear->SetScale(size); + tear->SetCollisionDamage(isBig ? damage * BOILED_BIG_DAMAGE : damage); + baby.TryFireTear(tear); + } + shot->Update(); +} + +// Part of 0061da10: Boiled Baby follows and, every few frames with enemies in the room, may burst (more likely with +// enemies near), spraying four to six tears on its Spawn animation's Shoot event. +void boiled_baby_update(Entity_Familiar& baby) +{ + ANM2& sprite = baby.sprite; + + baby.FollowParent(); + if (baby.FrameCount() == 0) return sprite.Play("FloatDown"); + if (!sprite.IsPlaying("FloatDown") && !sprite.IsFinished()) + { + if (!sprite.IsPlaying("Spawn") || !sprite.IsEventTriggered("Shoot")) return; + + familiar_sound_play(SOUND_BLOODSHOOT); + int count = random_below(BOILED_TEARS_RANGE) + BOILED_TEARS_MIN; + float damage = baby.GetMultiplier() * BOILED_DAMAGE; + for (int i = 0; i < count; i++) boiled_shot_fire(baby, damage); + return; + } + + sprite.Play("FloatDown"); + if (!baby.IsFrame(familiar_lullaby_delay(baby, BOILED_CHECK_INTERVAL), 0)) return; + if (g_game->room->GetAliveEnemiesCount() < 1) return; + + bool isCharmed = baby.HasEntityFlags(FLAG_CHARM); + int near = 0; + for (Entity* entity : entity_query_radius(baby.pos, isCharmed ? BOILED_CHARMED_RANGE : BOILED_RANGE, QUERY_ENEMIES)) + { + if (!entity) continue; + if (isCharmed) near += !entity->is_player() && (!entity->IsFamiliar() || entity->HasEntityFlags(FLAG_CHARM)); + else near += entity->IsVulnerableEnemy(nullptr); + } + if (random_below(near < 1 ? BOILED_FAR_ODDS : BOILED_NEAR_ODDS) == 0) sprite.Play("Spawn", PLAY_FORCED); +} + +// 0064b920 The Siren charms it away from its player: it serves the given player (its first one remembered), rests 45 +// frames, and a Siren helper bound to it and to the Siren keeps the charm. Big Fan and Guardian Angel count as the +// new player's items. +void Entity_Familiar::siren_charm(Entity* siren, Entity_Player* newPlayer) +{ + if (!sirenOriginalPlayer) sirenOriginalPlayer = player; + if (player != newPlayer) set_player(newPlayer); + fireCooldown = SIREN_CHARM_REST; + target = nullptr; + + Entity* helper = g_game->Spawn({.position = pos, .type = ENTITY_SIREN_HELPER, .seed = Random()}); + helper->parent = siren; + helper->target = this; + helper->ClearEntityFlags(FLAG_APPEAR); + helper->health = helper->maxHitPoints; + helper->Update(); + + if (variant == BIG_FAN) newPlayer->collectibleCounts[COLLECTIBLE_BIG_FAN]++; + else if (variant == GUARDIAN_ANGEL) newPlayer->collectibleCounts[COLLECTIBLE_GUARDIAN_ANGEL]++; + sirenCharmFrames = 1; + sirenHelper = helper; +} + +// The big Tinytoma a fresh piece belongs to: the first shed one of its player with fewer than two pieces. +static Entity* tinytoma_parent_find(Entity_Familiar& piece) +{ + std::map> shed; + for (Entity_Familiar* other : familiar_query(-1)) + { + if (other->player != piece.player) continue; + if (other->variant == Entity_Familiar::TINYTOMA && other->state > 0) shed.try_emplace(other->index, other, 0); + else if (other->variant == Entity_Familiar::TINYTOMA_2 && other->parent && + other->parent->type == ENTITY_FAMILIAR && other->parent->variant == Entity_Familiar::TINYTOMA && + static_cast(other->parent.get())->state > 0) + shed.try_emplace(other->parent->index, other->parent.get(), 0).first->second.second++; + } + for (auto& [index, entry] : shed) + if (entry.second < TINYTOMA_PIECE_LIMIT) return entry.first; + return nullptr; +} + +// 00642cb0 (FamiliarAI::tinytoma) Tinytoma and its pieces chase their orbit spot. A fresh piece picks the big one it +// came from, which rests while its pieces live. A shed Tinytoma regrows (after 150 frames, or 30 without pieces) from +// nothing back into its orbit, turning solid near full size. Explosions hurt it 3.5 at most. +void tinytoma_update(Entity_Familiar& tinytoma) +{ + Entity_Player& player = *tinytoma.player; + Vector spot = tinytoma.GetOrbitPosition(player.pos); + Vector lead = vector_scale(vector_scale(player.velocity, 2), 1 / player.friction); + Vector step = vector_scale(vector_sub(spot, vector_add(lead, tinytoma.pos)), TINYTOMA_PULL); + if (vector_length(step) > TINYTOMA_SNAP && !tinytoma.HasEntityFlags(FLAG_SPIN)) + step = vector_scale(vector_normalized(step), TINYTOMA_SPEED); + tinytoma.velocity = vector_scale(vector_add(step, lead), 1 / tinytoma.friction); + + if (tinytoma.variant == Entity_Familiar::TINYTOMA_2 && !tinytoma.parent && + g_game->frameCount - tinytoma.spawnFrame < 2) + tinytoma.parent = tinytoma_parent_find(tinytoma); + if (tinytoma.parent && tinytoma.parent->type == ENTITY_FAMILIAR) + static_cast(tinytoma.parent.get())->fireCooldown = 0; + if (tinytoma.fireCooldown < TINYTOMA_REST_FRAMES) tinytoma.fireCooldown++; + + LayerState* shell = tinytoma.sprite.GetLayer(0); + bool isRegrowing = tinytoma.state > TINYTOMA_REGROW_FRAMES || tinytoma.fireCooldown >= TINYTOMA_REST_FRAMES; + if (tinytoma.state > 0 && isRegrowing && --tinytoma.state < 1) + { + tinytoma.health = tinytoma.maxHitPoints; + shell->size = vector_make(TINYTOMA_SPAWN_SIZE, TINYTOMA_SPAWN_SIZE); + tinytoma.AddToOrbit(TINYTOMA_ORBIT); + } + if (shell->size.x > 0 && shell->size.x < 1) + { + float size = std::min(shell->size.x + TINYTOMA_GROWTH, 1.0f); + shell->size = vector_make(size, size); + if (size > TINYTOMA_SOLID_SIZE) + { + tinytoma.entityCollisionClass = ENTCOLL_ALL; + tinytoma.shadowSize = tinytoma.config->shadowSize; + } + } + + if (tinytoma.pendingDamage <= 0) return; + tinytoma.pendingDamage = 0; + for (DamageEvent& hit : tinytoma.damageEvents) + { + if (hit.damageFlags & DAMAGE_EXPLOSION) hit.damage = std::min(hit.damage, TINYTOMA_BLAST_CAP); + tinytoma.pendingDamage += hit.damage; + } +} + +// Part of 006261f0: Tinytoma hurts the enemy it touches and pushes it off, taking 3.5 itself from a harmful one. +bool tinytoma_touch(Entity_Familiar& tinytoma, Entity& enemy, float damageMultiplier) +{ + if (tinytoma.damageCountdown < 1) + enemy.TakeDamage(tinytoma.collisionDamage * damageMultiplier, 0, EntityRef(&tinytoma), + TINYTOMA_TOUCH_COUNTDOWN); + enemy.AddVelocity(vector_scale(vector_normalized(vector_sub(enemy.pos, tinytoma.pos)), TINYTOMA_PUSH), true); + if (enemy.collisionDamage > 0 && tinytoma.damageCountdown < 1) + tinytoma.TakeDamage(TINYTOMA_HURT, 0, EntityRef(&enemy), TINYTOMA_TOUCH_COUNTDOWN); + return true; +} + +// Part of 00610540: Tinytoma bursts in grey splats and gibs. The big one sheds into two pieces and lives on unseen to +// regrow, a piece leaves two or three blue spiders (enemy spiders when charmed). False while the big one lives on. +bool tinytoma_death(Entity_Familiar& tinytoma) +{ + familiar_sound_play(SOUND_DEATH_BURST_SMALL); + Entity* blast = g_game->Spawn({.position = tinytoma.pos, + .subType = BLAST_SPLAT_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blast->SetColor(TINYTOMA_SPLAT, -1, COLOR_PRIORITY_DEFAULT, false, true); + Entity* splat = g_game->Spawn( + {.position = tinytoma.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + splat->SetColor(TINYTOMA_SPLAT, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + for (uint32_t i = Random() % TINYTOMA_GIBS_RANGE + TINYTOMA_GIBS_MIN; i > 0; i--) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + Vector spot = + vector_add(tinytoma.pos, vector_scale(vector_make(std::cos(angle), std::sin(angle)), tinytoma.size / 2)); + float heading = random_unit() * RANDOM_HALF_TURN * 2; + float speed = random_unit() * TINYTOMA_GIB_SPEED_RANGE + TINYTOMA_GIB_SPEED_MIN; + Entity* gib = g_game->Spawn({.position = spot, + .velocity = vector_make(std::cos(heading) * speed, std::sin(heading) * speed), + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_PARTICLE, + .seed = Random()}); + gib->SetColor(TINYTOMA_SPLAT, -1, COLOR_PRIORITY_DEFAULT, false, true); + gib->splatColor = TINYTOMA_SPLAT; + gib->Update(); + } + + if (tinytoma.variant == Entity_Familiar::TINYTOMA) + { + if (LayerState* shell = tinytoma.sprite.GetLayer(0)) shell->size = {}; + tinytoma.state = TINYTOMA_SHED_FRAMES; + tinytoma.entityCollisionClass = ENTCOLL_NONE; + tinytoma.shadowSize = 0; + if (tinytoma.orbitLayer >= 0) + { + tinytoma.RecalculateOrbitOffset(tinytoma.orbitLayer, ORBIT_LEAVE); + tinytoma.orbitLayer = -1; + } + for (int i = 0; i < TINYTOMA_PIECES; i++) + { + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN * 2; + Vector spot = vector_add( + tinytoma.pos, vector_scale(vector_make(std::cos(angle), std::sin(angle)), TINYTOMA_PIECE_SPREAD)); + Entity* piece = g_game->Spawn({.position = spot, + .spawner = tinytoma.player, + .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::TINYTOMA_2, + .seed = seed}); + piece->Update(); + piece->parent = &tinytoma; + } + tinytoma.Entity::Kill(EntityRef()); + tinytoma.isDead = false; + return false; + } + + for (int i = (int)(Random() & 1) + TINYTOMA_SPIDERS_MIN; i > 0; i--) + if (!tinytoma.HasEntityFlags(FLAG_CHARM)) + { + tinytoma.player->numBlueSpiders++; + spawn_blue_spider(tinytoma.pos, tinytoma.player, {}); + } + else + Entity_NPC::ThrowSpider( + tinytoma.pos, nullptr, + room_free_pickup_position_find({.position = tinytoma.pos, .step = TINYTOMA_SPIDER_STEP}), false, + TINYTOMA_SPIDER_LIFT); + return true; +} + +// Whether a shot is one a shot-catching familiar goes for: an enemy shot in flight (a charmed one or one in versus goes +// for the player's tears and the shots turned against enemies instead). +static bool is_threatening_shot(Entity_Familiar& familiar, Entity& shot) +{ + if (vector_length_squared(shot.velocity) <= THREAT_SPEED_MIN) return false; + if (shot.type == ENTITY_TEAR) + { + auto& tear = static_cast(shot); + bool isHostile = familiar.HasEntityFlags(FLAG_CHARM) || familiar_versus(); + return isHostile && tear.height > THREAT_HEIGHT_MIN && !tear.tearFlags[TEAR_EXPLOSIVE] && + !tear.tearFlags[TEAR_LUDOVICO]; + } + if (shot.type != ENTITY_PROJECTILE) return false; + + auto& projectile = static_cast(shot); + bool isTurned = projectile.projectileFlags & PROJECTILE_CANT_HIT_PLAYER; + bool isHostile = familiar.HasEntityFlags(FLAG_CHARM) || familiar_versus(); + if (projectile.height <= THREAT_HEIGHT_MIN) return false; + return isHostile ? isTurned : !isTurned && projectile.variant != PROJECTILE_ENEMY_SHOT_EXCLUDED; +} + +// 00615870 (Entity_Familiar::target_threatening_projectile) Targets the most threatening shot within range of the +// player's spot it is heading for: nearer the player, faster, and heading at the player (unless left out) score higher. +static void threatening_shot_target(Entity_Familiar& familiar, float maxDistance, uint32_t search) +{ + Entity_Player& player = *familiar.player; + Entity* best = nullptr; + float bestScore = THREAT_NONE; + for (Entity* shot : g_game->room->entityList.updateEL) + { + if (familiar_versus() && shot->IsDescendantOf(familiar.spawnerEntity)) continue; + + float lead = vector_distance(familiar.pos, shot->pos) * THREAT_LEAD; + Vector predicted = vector_add(shot->pos, vector_scale(shot->velocity, lead)); + float distance = vector_distance(predicted, player.pos); + if (shot->isDead || shot->HasEntityFlags(FLAG_NO_TARGET) || distance > maxDistance) continue; + if (!is_threatening_shot(familiar, *shot)) continue; + + float score = std::max(THREAT_NEAR - distance, 0.0f) * THREAT_NEAR_SCALE + THREAT_BASE; + if (!(search & THREAT_NO_HEADING)) + { + Vector toPlayer = vector_normalized(vector_sub(player.pos, predicted)); + float heading = vector_dot(vector_normalized(shot->velocity), toPlayer) * THREAT_HEADING_SCALE; + score += heading >= THREAT_HEADING_MIN ? heading : -THREAT_HEADING_SCALE; + } + score += std::min(vector_length(shot->velocity) * THREAT_SPEED_SCALE, THREAT_SPEED_CAP); + if (score > bestScore) + { + best = shot; + bestScore = score; + } + } + if (best || (search & THREAT_ALWAYS_ASSIGN)) familiar.target = best; +} + +// 006431d0 (Entity_Familiar::ai_bot_fly) Bot Fly orbits the player, picking the shot most threatening it. While it +// attacks it faces the shot and, on its Shoot event, fires a shielding homing tear at where the shot will be (sideways +// with no target), marking that shot taken. +void bot_fly_update(Entity_Familiar& fly) +{ + ANM2& sprite = fly.sprite; + Entity_Player& player = *fly.player; + fly.velocity = vector_sub(fly.GetOrbitPosition(player.pos), fly.pos); + if (!sprite.IsPlaying("Attack")) + { + threatening_shot_target(fly, BOT_FLY_RANGE, THREAT_KEEP); + sprite.Play("Fly"); + if (fly.target) sprite.Play("Attack"); + return; + } + + threatening_shot_target(fly, BOT_FLY_RANGE, THREAT_ALWAYS_ASSIGN); + Entity* target = fly.target; + if (target) sprite.isFlipX = target->pos.x < fly.pos.x; + if (!sprite.IsEventTriggered("Shoot") || (familiar_versus() && Random() % BOT_FLY_VERSUS_ODDS != 0)) return; + + Vector aim; + if (target) + { + float lead = vector_distance(fly.pos, target->pos) * BOT_FLY_SHOT_LEAD; + aim = vector_resized(vector_sub(vector_add(target->pos, vector_scale(target->velocity, lead)), fly.pos), + BOT_FLY_SHOT_SPEED); + } + else + { + Vector side = vector_make(sprite.isFlipX ? -BOT_FLY_SHOT_SPEED : BOT_FLY_SHOT_SPEED, 0); + Vector inherited = vector_scale(player.velocity, BOT_FLY_SHOT_INHERIT * 2); + Vector along = vector_normalized(side); + Vector forward = vector_scale(along, vector_dot(inherited, along)); + if (vector_dot(forward, side) < 0) inherited = vector_sub(inherited, forward); + aim = vector_add(side, inherited); + } + if (fly.HasEntityFlags(FLAG_CHARM)) + reconstruction_missing("Entity_Familiar::ai_bot_fly 006431d0 (a charmed Bot Fly's shot)"); + + auto* tear = static_cast(g_game->Spawn({.position = fly.pos, + .velocity = aim, + .spawner = &fly, + .type = ENTITY_TEAR, + .variant = TEAR_LOST_CONTACT, + .seed = Random()})); + tear->SetCollisionDamage(BOT_FLY_SHOT_DAMAGE); + tear->SetTearFlags(TearFlags().set(TEAR_SHIELDED).set(TEAR_SPECTRAL).set(TEAR_HOMING)); + tear->baseScale = BOT_FLY_SHOT_SCALE; + tear->fScale = BOT_FLY_SHOT_SCALE; + tear->ResetSpriteScale(); + tear->fallingAccel = BOT_FLY_SHOT_FALL; + if (target) tear->target = target; + tear->Update(); + fly.shot_owner_convert(tear); + if (!target) return; + + target->AddEntityFlags(FLAG_NO_TARGET); + fly.target = nullptr; +} + +// Whether Lil Dumpy fears what is about to hit its player: a harmful enemy (a player in versus) or an enemy shot +// whose path meets the player's, not the player's own. +static bool is_dumpy_danger(Entity_Familiar& dumpy, Entity& entity, const Capsule& playerPath) +{ + if (entity.IsDescendantOf(dumpy.GetPlayerAncestor()) || entity.isDead || + entity.entityCollisionClass == ENTCOLL_NONE) + return false; + bool isVersusFoe = familiar_versus() && (entity.type == ENTITY_PLAYER || entity.type == ENTITY_TEAR); + bool isFoe = Entity::is_enemy_type(entity.type) || entity.type == ENTITY_PROJECTILE || isVersusFoe; + if (!isFoe || (entity.type == ENTITY_FIREPLACE && entity.variant == WHITE_FIREPLACE) || + entity.HasEntityFlags(FLAG_FRIENDLY)) + return false; + if (entity.type == ENTITY_PROJECTILE + ? (static_cast(entity).projectileFlags & PROJECTILE_CANT_HIT_PLAYER) + : entity.collisionDamage <= 0) + return false; + + Vector motion = vector_scale(entity.velocity, entity.friction * entity.speedMultiplier); + return Capsule::Collide(playerPath, entity.GetCollisionCapsule(motion)); +} + +// 006468a0 (FamiliarAI::lil_dumpy) Lil Dumpy trails the player, faster the further behind. When something harmful is +// about to hit its player it farts (a Butter Bean blast about the player) and shoots off the danger, sleeping until it +// rests near the player again. It hurts what it flies into, harder the faster. +void lil_dumpy_update(Entity_Familiar& dumpy) +{ + ANM2& sprite = dumpy.sprite; + Entity_Player& player = *dumpy.player; + bool isLooping = !sprite.animState.animData || sprite.animState.animData->isLooping || !sprite.animState.isPlaying; + if (dumpy.state == 0) + { + Vector spot = vector_add(player.pos, vector_resized(vector_sub(dumpy.pos, player.pos), DUMPY_TRAIL)); + float distance = vector_distance(player.pos, dumpy.pos); + if (isLooping) + sprite.Play(distance > DUMPY_FASTER ? "IdleFaster" : distance > DUMPY_FAST ? "IdleFast" : "Idle"); + if (distance > DUMPY_TRAIL) + { + float pull = (distance - DUMPY_TRAIL) / distance * DUMPY_PULL; + float speed = dumpy.speedMultiplier; + float drag = speed == 1 ? DUMPY_DRAG : DUMPY_DRAG / (speed + DUMPY_DRAG - speed * DUMPY_DRAG); + Vector wanted = vector_scale(vector_sub(spot, dumpy.pos), pull); + dumpy.velocity = vector_add(dumpy.velocity, vector_scale(vector_sub(wanted, dumpy.velocity), 1 - drag)); + } + + if (player.entityCollisionClass != ENTCOLL_NONE && player.damageCooldown < 2 && + !player.HasInvincibility(0, EntityRef()) && distance <= DUMPY_GUARD_RANGE) + { + Vector motion = vector_scale(player.velocity, player.friction * player.speedMultiplier); + uint32_t partitions = QUERY_ENEMIES | QUERY_PROJECTILES | (familiar_versus() ? QUERY_TEARS : 0); + EntityList_EL near = + entity_query_radius(vector_add(player.pos, motion), player.size + DUMPY_SEARCH_RANGE, partitions); + Capsule playerPath = player.GetCollisionCapsule(motion); + playerPath.radius += random_unit() * DUMPY_MARGIN_RANGE + DUMPY_MARGIN_MIN; + for (Entity* entity : near) + { + if (!is_dumpy_danger(dumpy, *entity, playerPath)) continue; + + sprite.Play("Fart"); + game_butter_bean_fart({.position = player.pos, + .source = &player, + .radius = DUMPY_FART_RADIUS, + .isShowEffect = false, + .isSuperKnockback = true}); + float scale = player.HasTrinket(TRINKET_GIGANTE_BEAN) ? DUMPY_GIGANTE_SCALE : 1; + Entity* cloud = g_game->Spawn( + {.position = dumpy.pos, .type = ENTITY_EFFECT, .variant = EFFECT_FART, .seed = Random()}); + cloud->SetColor(COLOR_DEFAULT, -1, COLOR_PRIORITY_DEFAULT, false, true); + cloud->sprite.scale = vector_make(scale, scale); + dumpy.velocity = vector_resized(vector_sub(dumpy.pos, entity->pos), DUMPY_LAUNCH_SPEED); + dumpy.state = 1; + dumpy.fireCooldown = DUMPY_REST_FRAMES; + break; + } + } + if (dumpy.state == 0) dumpy.friction *= DUMPY_DRAG; + } + else + { + if (!sprite.IsPlaying()) sprite.Play("Sleep"); + if (sprite.animState.animData && sprite.animState.animData->isLooping) + { + dumpy.friction *= DUMPY_DRAG; + int elapsed = (int)dumpy.updateTime - (int)dumpy.prevUpdateTime; + bool isRested = dumpy.fireCooldown < 1 || (dumpy.fireCooldown -= elapsed) < 1; + if (isRested && vector_length_squared(vector_sub(dumpy.pos, player.pos)) <= DUMPY_WAKE_DISTANCE_SQUARED) + { + sprite.Play("Wake"); + dumpy.state = 0; + } + } + else dumpy.friction *= DUMPY_SLEEP_FRICTION; + } + + sprite.isFlipX = dumpy.velocity.x < 0; + float pace = std::clamp((vector_length(dumpy.velocity) - DUMPY_HIT_SPEED_MIN) / DUMPY_HIT_SPEED_RANGE, 0.0f, 1.0f); + dumpy.collisionDamage = dumpy.GetMultiplier() * pace * DUMPY_HIT_DAMAGE; +} diff --git a/src/familiar_shoot.cpp b/src/familiar_shoot.cpp index 2a554b0..6c69eb3 100644 --- a/src/familiar_shoot.cpp +++ b/src/familiar_shoot.cpp @@ -97,6 +97,16 @@ constexpr ColorMod HUSHY_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0.2f, 0.4f}}; constexpr float DELIRIUM_COLORIZE[] = {2.4f, 2.4f, 2.4f, 1}; constexpr float HOLOGRAM_ALPHA = 0.25f; +// Intruder's spread of four slowing cobweb tears (one in ten plain): their damage, look, the fan's spread and how far +// beside the familiar they start. +constexpr float INTRUDER_SHOT_DAMAGE = 1.5f; +constexpr ColorMod INTRUDER_COLOR = {{1, 1, 1, 1}, {1.2f, 1.2f, 1.2f, 1}, {0.4f, 0.4f, 0.38f}}; +constexpr int INTRUDER_SHOTS = 4; +constexpr float INTRUDER_FAN = 10; +constexpr float INTRUDER_SPREAD = 180; +constexpr float INTRUDER_SPREAD_DISTANCE = 10; +constexpr uint32_t INTRUDER_PLAIN_ODDS = 10; + // Baby-Bender's homing look for tears and lasers. constexpr ColorMod BENDER_TEAR_COLOR = { {0.4f, 0.15f, 0.38f, 1}, {0, 0, 0, 0}, {0.21568628f, 0.019607844f, 0.37254903f}}; @@ -110,6 +120,7 @@ struct FamiliarShot { TearFlags flags; ColorMod color = COLOR_DEFAULT; + Vector offset{}; Vector velocity{}; float damage = SHOT_DAMAGE; float fallingAccel = 0; @@ -466,7 +477,11 @@ static bool shot_variant_apply(Entity_Familiar& familiar, FamiliarShot& shot, in shot.tearVariant = TEAR_BLOOD; shot.damage = 7.5f; } - else if (variant == Entity_Familiar::INTRUDER) return false; + else if (variant == Entity_Familiar::INTRUDER) + { + shot.damage = INTRUDER_SHOT_DAMAGE; + shot.color = INTRUDER_COLOR; + } else if (variant == Entity_Familiar::FRUITY_PLUM) { shot.damage = FRUITY_PLUM_SHOT_DAMAGE; @@ -488,7 +503,7 @@ static bool shot_variant_apply(Entity_Familiar& familiar, FamiliarShot& shot, in // Baby-Bender, and an owner's charm (part of 00639750). static Entity_Tear* shot_spawn(Entity_Familiar& familiar, const FamiliarShot& shot, Vector velocity) { - auto* tear = static_cast(g_game->Spawn({.position = familiar.pos, + auto* tear = static_cast(g_game->Spawn({.position = vector_add(familiar.pos, shot.offset), .velocity = velocity, .spawner = &familiar, .type = ENTITY_TEAR, @@ -509,14 +524,31 @@ static Entity_Tear* shot_spawn(Entity_Familiar& familiar, const FamiliarShot& sh return tear; } +// Part of 00639750: Intruder's fan of four tears, spread across its aim, mostly slowing. +static Entity_Tear* intruder_shots_fire(Entity_Familiar& intruder, FamiliarShot& shot, Vector aimDirection) +{ + Entity_Tear* tear = nullptr; + TearFlags flags = shot.flags; + for (int i = 0; i < INTRUDER_SHOTS; i++) + { + float step = (float)i / (INTRUDER_SHOTS - 1); + Vector side = vector_rotated(aimDirection, step * INTRUDER_SPREAD - INTRUDER_SPREAD / 2); + shot.offset = vector_scale(side, INTRUDER_SPREAD_DISTANCE); + shot.flags = flags; + if (Random() % INTRUDER_PLAIN_ODDS != 0) shot.flags.set(TEAR_SLOW); + tear = shot_spawn(intruder, shot, vector_rotated(shot.velocity, step * INTRUDER_FAN - INTRUDER_FAN / 2)); + } + return tear; +} + // 00639750 Fires a familiar's tear: at ten speed, with the player's motion unless aimed at a mark, its damage and size -// scaled by BFFS!, and the variant's flags and look. Harlequin Baby fires two, the wisps and Intruder their own way. +// scaled by BFFS!, and the variant's flags and look. Harlequin Baby fires two, Intruder four and the wisps their own +// way. Intruder works out the player's motion too but fires from its bare aim. Entity_Tear* Entity_Familiar::FireProjectile(const Vector& aimDirection, FireMode mode) { FamiliarShot shot; shot.velocity = vector_scale(aimDirection, SHOT_SPEED); - if (variant == INTRUDER) reconstruction_missing("Entity_Familiar::FireProjectile 00639750 (Intruder)"); - if (mode == FIRE_INHERIT_MOTION) + if (mode == FIRE_INHERIT_MOTION && variant != INTRUDER) { Vector inherited = vector_scale(player->velocity, SHOT_INHERIT * 2); shot.velocity = variant == ABEL || variant == FAMILIAR_ABEL_TWIN ? vector_sub(shot.velocity, inherited) @@ -548,6 +580,7 @@ Entity_Tear* Entity_Familiar::FireProjectile(const Vector& aimDirection, FireMod shot.damage *= multiplier; shot.scale = std::max(shot.scale, SHOT_SCALE_MIN); + if (variant == INTRUDER) return intruder_shots_fire(*this, shot, aimDirection); if (variant != HARLEQUIN_BABY && rainbow != 9 && mimic != 7) return shot_spawn(*this, shot, shot.velocity); Vector v = shot.velocity; diff --git a/src/familiar_wisp.cpp b/src/familiar_wisp.cpp index 10145fe..0765acc 100644 --- a/src/familiar_wisp.cpp +++ b/src/familiar_wisp.cpp @@ -1,6 +1,6 @@ +#include "familiar_wisp.h" #include "boss_ai.h" #include "entity_effect.h" -#include "entity_familiar.h" #include "entity_player.h" #include "entity_tear.h" #include "game.h" @@ -39,38 +39,18 @@ constexpr float WISP_TEAR_SCALE = 0.8f; constexpr float WISP_TEAR_FALL_JITTER = 0.2f; constexpr float WISP_POOF_HEIGHT = -6; constexpr float GELLO_PARENT_SLOWDOWN = 0.5f; +constexpr float LEMONADE_WISP_GROWTH = 1.5f; +constexpr float LARYNX_WISP_GROWTH = 0.05f; +constexpr float DIPLOPIA_TURN = 90; +constexpr float DIPLOPIA_SPACING = 5; constexpr ColorMod ITEM_WISP_ICON_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0.8f}}; constexpr ColorMod ITEM_WISP_POOF_COLOR = {{1.4f, 0.7f, 1.6f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; -// The subtypes whose wisps act, shoot, die or take hits their own way (ai_wisp 0043aa90, WispInit 00436330, -// wisp_kill 00436fd0, fire_wisp_projectile 004386f0, wisp_take_damage 0043a5e0). Plain wisps share one behaviour. -constexpr std::array WISP_UNWRITTEN_SUBTYPES = { - 35, 37, 38, 40, 42, 44, 47, 49, 56, 58, 65, 66, 77, 78, 85, 93, 102, 111, 123, 127, 130, 145, - 158, 160, 164, 175, 181, 263, 282, 287, 288, 289, 290, 293, 294, 295, 298, 323, 324, 325, 338, 347, 348, 349, - 351, 352, 383, 396, 406, 419, 421, 427, 437, 441, 478, 479, 483, 484, 485, 487, 504, 516, 521, 523, 527, 545, - 556, 578, 580, 582, 604, 609, 611, 635, 638, 639, 640, 650, 702, 703, 705, 709, 722, 729, 65536, 65537, - 65538, 65539, 65540, 65541, 65542, 65543, 65544, 65545, 65546, 65547, 65548, 65549, 65550, 65551, 65552, 65553, - 65554, 65555, 65556, 65557, 65558, 65559, 65560, 65561, 65562, 65563, 65564, 65565, 65566, 65567, 65568, 65569, - 65570, 65571, 65572, 65573, 65574, 65575, 65576, 65577, 65578, 65579}; - -// The item a wisp takes its wisps.xml entry from: an item wisp's source, a wisp's subtype, else Book of Virtues. -static int wisp_item_get(Entity_Familiar& wisp) +// 00436260 The wisps.xml entry a wisp takes: an item wisp's source, a wisp's subtype, else Book of Virtues'. +WispEntry* wisp_config(Entity_Familiar& wisp) { - if (wisp.variant == Entity_Familiar::ITEM_WISP) return wisp.wispCollectibleType; - return wisp.variant == Entity_Familiar::WISP ? wisp.subtype : COLLECTIBLE_BOOK_OF_VIRTUES; -} - -// Whether a wisp is one with its own behaviour, which stops the game until reconstructed. -static bool is_wisp_unwritten(Entity_Familiar& wisp) -{ - if (wisp.variant != Entity_Familiar::WISP) return false; - return std::ranges::find(WISP_UNWRITTEN_SUBTYPES, wisp.subtype) != WISP_UNWRITTEN_SUBTYPES.end(); -} - -// Stops the game in a special wisp's own code. -static void wisp_unwritten_stop(Entity_Familiar& wisp, std::string_view function) -{ - reconstruction_missing((std::string(function) + " (wisp " + std::to_string(wisp.subtype) + ")").c_str()); + if (wisp.variant == Entity_Familiar::ITEM_WISP) return ItemConfig::wisp_config_get(wisp.wispCollectibleType); + return ItemConfig::wisp_config_get(wisp.variant == Entity_Familiar::WISP ? wisp.subtype : COLLECTIBLE_BOOK_OF_VIRTUES); } // 005c93b0 Adds a Book of Virtues wisp of a collectible: Wavy Cap keeps one, a full ring passes it on to the next unless @@ -93,7 +73,7 @@ Entity_Familiar* Entity_Player::AddWisp(int collectible, Vector position, bool i if (!wisp->isExists || wisp->player != this) continue; if (collectible == COLLECTIBLE_WAVY_CAP && wisp->subtype == COLLECTIBLE_WAVY_CAP) return nullptr; - WispEntry* other = ItemConfig::wisp_config_get(wisp_item_get(*wisp)); + WispEntry* other = wisp_config(*wisp); int layer = wisp->orbitLayer - WISP_RING_FIRST_LAYER; if (wisp->subtype == collectible && wisp->health < weakestHealth) { @@ -203,9 +183,9 @@ int Entity_Familiar::GetRandomWisp(RNG* rng) return wispItems[rng->Next() % wispItems.size()]; } -// 00436330 Sets a wisp up from its wisps.xml entry: health, sheets and colours. An item wisp takes Lemegeton's (or -// Book of Virtues' Lemegeton) entry and reveals the map when its item is a map, Eden's Soul and Mystery Gift wisps -// become a random wisp, and the item wisps are counted as held. +// 00436330 Sets a wisp up: an item wisp takes Lemegeton's (or Book of Virtues' Lemegeton) entry, Eden's Soul and +// Mystery Gift wisps become a random wisp, the wisps with their own behaviour get ready, then its entry's health, +// sheets and colours. The item wisps are counted as held. void Entity_Familiar::WispInit() { int item = subtype; @@ -218,20 +198,11 @@ void Entity_Familiar::WispInit() if (variant == WISP && (item == COLLECTIBLE_MYSTERY_GIFT || item == COLLECTIBLE_EDENS_SOUL)) { wispCollectibleType = item; - subtype = GetRandomWisp(&dropRNG); + item = subtype = GetRandomWisp(&dropRNG); } - if (is_wisp_unwritten(*this)) wisp_unwritten_stop(*this, "Entity_Familiar::WispInit 00436330"); - if (variant == WISP && subtype == COLLECTIBLE_FORTUNE_COOKIE) player->cacheFlags |= CACHE_LUCK; + wisp_kind_init(*this, item); - if (variant == ITEM_WISP) - { - Level& level = *g_game; - if (subtype == COLLECTIBLE_BLUE_MAP || subtype == COLLECTIBLE_MIND) level.ApplyBlueMapEffect(); - if (subtype == COLLECTIBLE_TREASURE_MAP || subtype == COLLECTIBLE_MIND) level.ApplyMapEffect(); - if (subtype == COLLECTIBLE_COMPASS || subtype == COLLECTIBLE_MIND) level.ApplyCompassEffect(true); - } - - WispEntry* config = ItemConfig::wisp_config_get(wisp_item_get(*this)); + WispEntry* config = wisp_config(*this); maxHitPoints = config->hp; health = config->hp; if (!config->coreGfx.empty()) sprite.ReplaceSpritesheet(0, config->coreGfx); @@ -239,6 +210,7 @@ void Entity_Familiar::WispInit() if (!config->coreGfx.empty() || !config->flameGfx.empty()) sprite.LoadGraphics(); sprite.GetLayer(0)->color = config->coreColor; sprite.GetLayer(1)->color = config->flameColor; + if (variant == WISP) wisp_kind_colors(*this); if (variant == ITEM_WISP) player->RecomputeWispCollectibles(this); g_game->UpdateVisibility(); @@ -267,17 +239,19 @@ void wisp_room_clear(Entity_Familiar& wisp) wisp.health = wisp.maxHitPoints; } -// Part of 00614500, 00613df0 and 00614b10: a wisp's animation, the wide one for a sheet wider than 128 pixels. -void wisp_anim_play(Entity_Familiar& wisp, std::string_view name) +// Part of 00614500, 00613df0, 00614b10 and 0043aa90: a wisp's animation, the wide one for a sheet wider than 128 +// pixels. +void wisp_anim_play(Entity_Familiar& wisp, std::string_view name, AnimationSwitch mode) { LayerState* core = wisp.sprite.GetLayer(0); bool isWide = core && core->spriteSheet && core->spriteSheet->width > WISP_SHEET_WIDE; - wisp.sprite.SetAnimation(isWide ? std::string(name) + "2" : std::string(name), SWITCH_KEEP_FRAME); + wisp.sprite.SetAnimation(isWide ? std::string(name) + "2" : std::string(name), mode); } // The orbit part of ai_wisp: an orbiting wisp is pulled back toward its parent when far from its ring and steered -// onto its spot on the ring, at most four a frame, carried along by the parent's own motion. One off the orbits holds -// the spot its formation offset names. +// onto its spot on the ring, at most four a frame, carried along by the parent's own motion. A Suplex! or Mom's +// Bracelet wisp holding a spot orbits that instead, the bracelet's kept inside the room. One off the orbits holds the +// spot its formation offset names. static void wisp_orbit_move(Entity_Familiar& wisp) { if (wisp.orbitLayer < 0) @@ -289,12 +263,20 @@ static void wisp_orbit_move(Entity_Familiar& wisp) } Entity* parent = wisp.get_orbit_parent(); + Vector anchor = parent->pos; Vector parentVelocity = parent->velocity; + bool isHolding = wisp.subtype == COLLECTIBLE_SUPLEX || wisp.subtype == COLLECTIBLE_MOMS_BRACELET; + if (isHolding && !vector_is_zero(wisp.targetPosition)) + { + anchor = wisp.targetPosition; + parentVelocity = {}; + } if (parent->type == ENTITY_FAMILIAR && parent->variant == Entity_Familiar::UMBILICAL_BABY) parentVelocity = vector_scale(parentVelocity, GELLO_PARENT_SLOWDOWN); - Vector spot = wisp.GetOrbitPosition(parent->pos); + Vector spot = wisp.GetOrbitPosition(anchor); + if (wisp.subtype == COLLECTIBLE_MOMS_BRACELET) spot = g_game->room->GetClampedPositionImpl(spot, 0, 0, 0, 0); - Vector toParent = vector_sub(parent->pos, wisp.pos); + Vector toParent = vector_sub(anchor, wisp.pos); float distance = vector_length(toParent); Vector pull = vector_scale(toParent, WISP_PULL); float pullLength = vector_length(pull); @@ -312,96 +294,143 @@ static void wisp_orbit_move(Entity_Familiar& wisp) wisp.velocity = vector_add(vector_scale(vector_sub(vector_add(pull, wisp.velocity), settled), pullShare), settled); } -// 0043aa90 A wisp's frame: it keeps to its ring, grows and shrinks with its health, hits as hard as twice its player's -// melee damage (twice again with BFFS!), and fires along its player's aim at the rate its entry sets. The wisps with -// their own behaviour stop the game. -void Entity_Familiar::ai_wisp() +// The aimed part of ai_wisp: a wisp with an aim of its own or a player shooting fires its shots along it (turned and +// spread), at its fire delay, with its head following. Otherwise the head settles facing down. +static void wisp_shoot(Entity_Familiar& wisp, WispShot& shot) { - if (is_wisp_unwritten(*this)) wisp_unwritten_stop(*this, "Entity_Familiar::ai_wisp 0043aa90"); - - WispEntry* config = ItemConfig::wisp_config_get(wisp_item_get(*this)); - if (state == 0) wisp_orbit_move(*this); - - float size = health / maxHitPoints * WISP_SIZE_HEALTH_SCALE + WISP_SIZE_BASE; - float coreSize = std::sqrt(size); - sprite.GetLayer(0)->size = vector_make(coreSize, coreSize); - sprite.GetLayer(1)->size = vector_make(size, size); - collisionDamage = player->meleeDamage + player->meleeDamage; - int fireDelay = (int)config->fireDelay; - - if (player->HasCollectible(COLLECTIBLE_BFFS)) collisionDamage += collisionDamage; - if (counter > 0) counter--; - if (state != 0 || !config->isCanShoot) return; - if (fireCooldown > 0) fireCooldown--; - - int direction = player->fireDirection; - if (direction == DIRECTION_NONE || fireDelay <= 0) + if (wisp.fireCooldown > 0) wisp.fireCooldown--; + int direction = wisp.player->fireDirection; + if ((direction == DIRECTION_NONE && vector_is_zero(shot.aim)) || shot.fireDelay <= 0) { - if (headFrameDelay >= 0 && --headFrameDelay < 0) PlayFloatAnim(DIRECTION_DOWN); + if (wisp.headFrameDelay >= 0 && --wisp.headFrameDelay < 0) wisp.PlayFloatAnim(DIRECTION_DOWN); return; } Vector aim = direction_unit(direction); - TryAimAtMarkedTarget(aim, direction, nullptr); - if (fireCooldown < 1) + wisp.TryAimAtMarkedTarget(aim, direction, nullptr); + if (!vector_is_zero(shot.aim)) aim = shot.aim; + aim = vector_rotated(aim, shot.turnDegrees); + bool isFired = wisp.fireCooldown < 1; + if (isFired) { - FireProjectile(aim, FIRE_INHERIT_MOTION); - fireCooldown = fireDelay; - headFrameDelay = WISP_HEAD_FRAMES; + for (int i = 0; i < shot.count; i++) + { + wisp.FireProjectile(aim, FIRE_INHERIT_MOTION); + aim = vector_rotated(aim, shot.spreadDegrees); + } + wisp.fireCooldown = shot.fireDelay; + wisp.headFrameDelay = WISP_HEAD_FRAMES; } - else if (headFrameDelay < WISP_HEAD_FLOAT) + if (!isFired && wisp.headFrameDelay < WISP_HEAD_FLOAT) { - PlayFloatAnim(direction); - headFrameDelay = WISP_HEAD_FLOAT - 1; - return; + wisp.PlayFloatAnim(direction); + wisp.headFrameDelay = WISP_HEAD_FLOAT - 1; } - PlayShootAnim(direction); - headFrameDelay--; + else + { + wisp.PlayShootAnim(direction); + wisp.headFrameDelay--; + } + if (wisp.subtype == COLLECTIBLE_SHOOP_DA_WHOOP) wisp.targetPosition = aim; } -// 004386f0 A wisp's tear: its entry's damage (rising each floor, an alternate floor counting one deeper), size and -// look, the second kind of tear by its chance, spectral, at its entry's shot speed. BFFS! doubles the damage and keeps -// the size whole. The wisps that shoot their own way stop the game. -Entity_Tear* Entity_Familiar::fire_wisp_projectile(Vector velocity) +// 0043aa90 A wisp's frame: it keeps to its ring, grows and shrinks with its health (Free Lemonade's and Larynx's +// grow more), hits as hard as twice its player's melee damage (twice again with BFFS!), does what its item's wisp +// does, and fires along its player's aim at the rate its entry sets. +void Entity_Familiar::ai_wisp() { - if (is_wisp_unwritten(*this)) wisp_unwritten_stop(*this, "Entity_Familiar::fire_wisp_projectile 004386f0"); + WispEntry* config = wisp_config(*this); + WispShot shot{.fireDelay = (int)config->fireDelay, .isFiring = config->isCanShoot}; + int updateSteps = (int)updateTime - (int)prevUpdateTime; + if (variant == WISP && subtype == COLLECTIBLE_PLUM_FLUTE) plum_flute_wisp_target(*this); + if (state == 0) wisp_orbit_move(*this); - WispEntry* config = ItemConfig::wisp_config_get(wisp_item_get(*this)); - bool isBffs = player->HasCollectible(COLLECTIBLE_BFFS); - Level& level = *g_game; - int stage = (int)level.stage + (level.IsAltPath() ? 1 : 0); - float baseDamage = (float)(stage - 1) * config->stageDamage + config->damage; - WispTears& tears = random_unit() < config->procChance ? config->tears2 : config->tears; + float size = health / maxHitPoints * WISP_SIZE_HEALTH_SCALE + WISP_SIZE_BASE; + if (variant == WISP && subtype == COLLECTIBLE_FREE_LEMONADE) size *= LEMONADE_WISP_GROWTH; + else if (variant == WISP && subtype == COLLECTIBLE_LARYNX) size *= (float)keys * LARYNX_WISP_GROWTH + 1; + float coreSize = std::sqrt(size); + sprite.GetLayer(0)->size = vector_make(coreSize, coreSize); + sprite.GetLayer(1)->size = vector_make(size, size); + collisionDamage = player->meleeDamage + player->meleeDamage; + if (variant == WISP) wisp_kind_update(*this, shot); - TearFlags flags = tears.flags; - flags.set(TEAR_SPECTRAL); - velocity = vector_scale(velocity, config->shotSpeed); - auto* tear = static_cast(g_game->Spawn({.position = pos, - .velocity = velocity, - .spawner = this, + if (player->HasCollectible(COLLECTIBLE_BFFS)) collisionDamage += collisionDamage; + if (counter > 0) counter--; + if (state == 1 && variant == WISP && subtype == COLLECTIBLE_PLUM_FLUTE) plum_flute_wisp_spray(*this, updateSteps); + if (state == 0 && shot.isFiring) wisp_shoot(*this, shot); +} + +// The end of 004386f0: the tear itself, beside the wisp by an offset, falling a little, its parent the wisp. Baby-Bender +// bends it. +static Entity_Tear* wisp_tear_spawn(Entity_Familiar& wisp, const WispTear& shot, Vector offset) +{ + auto* tear = static_cast(g_game->Spawn({.position = vector_add(wisp.pos, offset), + .velocity = shot.velocity, + .spawner = &wisp, .type = ENTITY_TEAR, - .variant = tears.variant, + .variant = shot.variant, .seed = Random()})); - tear->fallingSpeed = random_unit() * WISP_TEAR_FALL_JITTER; - tear->fallingAccel = 0; - tear->SetCollisionDamage(wispDamageMultiplier * tears.damageMultiplier * wispScale * baseDamage * (isBffs ? 2 : 1)); - tear->SetTearFlags(flags); - tear->SetScale(std::sqrt(wispDamageMultiplier) * tears.scale * (isBffs ? 1 : WISP_TEAR_SCALE)); - tear->parent = this; - tear->SetColor(tears.color, -1, 255, false, true); + tear->fallingSpeed = random_unit() * WISP_TEAR_FALL_JITTER + shot.fallingSpeed; + tear->fallingAccel = shot.fallingAccel; + tear->SetCollisionDamage(shot.damage * shot.damageMultiplier); + tear->SetTearFlags(shot.flags); + tear->SetScale(shot.scale); + tear->parent = &wisp; + tear->SetColor(shot.color, -1, 255, false, true); tear->tearIdx = (int)(Random() & 1); - if (player->HasTrinket(TRINKET_BABY_BENDER)) TryFireTear(tear); + if (wisp.player->HasTrinket(TRINKET_BABY_BENDER)) wisp.TryFireTear(tear); return tear; } -// 0043a5e0 Whether a hit reaches a wisp: none while its player is invincible, nor its own side's crushing blows. The -// wisps that answer hits their own way stop the game. -bool Entity_Familiar::wisp_take_damage(const EntityRef& source, uint64_t damageFlags) +// The strength of a wisp's tears on this floor: its entry's damage, rising each floor, an alternate floor counting one +// deeper (part of 004386f0 and 00436fd0). +float wisp_base_damage(WispEntry& config) +{ + Level& level = *g_game; + int stage = (int)level.stage + (level.IsAltPath() ? 1 : 0); + return (float)(stage - 1) * config.stageDamage + config.damage; +} + +// 004386f0 A wisp's tear: its entry's damage (rising each floor, an alternate floor counting one deeper), size and +// look, the second kind of tear by its chance, spectral, at its entry's shot speed, then changed as its item's wisp +// changes it. BFFS! doubles the damage and keeps the size whole. Some wisps fire something else, or nothing. +Entity_Tear* Entity_Familiar::fire_wisp_projectile(Vector velocity) +{ + if (wisp_kind_fire(*this, velocity)) return nullptr; + + WispEntry* config = wisp_config(*this); + bool isBffs = player->HasCollectible(COLLECTIBLE_BFFS); + float baseDamage = wisp_base_damage(*config); + WispTears& tears = random_unit() < config->procChance ? config->tears2 : config->tears; + + WispTear tear{.color = tears.color, + .flags = tears.flags, + .velocity = vector_scale(velocity, config->shotSpeed), + .damage = wispDamageMultiplier * tears.damageMultiplier * wispScale * baseDamage, + .damageMultiplier = isBffs ? 2.0f : 1.0f, + .scale = std::sqrt(wispDamageMultiplier) * tears.scale * (isBffs ? 1 : WISP_TEAR_SCALE), + .variant = tears.variant}; + tear.flags.set(TEAR_SPECTRAL); + wisp_kind_tear(*this, tear); + + Vector offset{}; + if (subtype == COLLECTIBLE_DIPLOPIA) + { + offset = vector_scale(vector_rotated(vector_normalized(tear.velocity), DIPLOPIA_TURN), DIPLOPIA_SPACING); + wisp_tear_spawn(*this, tear, offset); + offset = vector_scale(offset, -1); + } + return wisp_tear_spawn(*this, tear, offset); +} + +// 0043a5e0 Whether a hit reaches a wisp: none while its player is invincible, nor its own side's crushing blows, then +// as its item's wisp answers it. +bool Entity_Familiar::wisp_take_damage(float& damage, uint64_t damageFlags, const EntityRef& source) { if (player->HasInvincibility(0, EntityRef())) return false; if ((source.type == ENTITY_PLAYER || source.type == ENTITY_FAMILIAR) && (damageFlags & DAMAGE_CRUSH)) return false; - if (is_wisp_unwritten(*this)) wisp_unwritten_stop(*this, "Entity_Familiar::wisp_take_damage 0043a5e0"); - return true; + if (variant != WISP) return true; + return wisp_kind_hit(*this, damage, damageFlags, source) != WISP_HIT_BLOCKED; } // The countdown a wisp's hit lasts, a third of the hit's and at most ten frames (part of 0062cdc0). @@ -476,14 +505,15 @@ static void wisp_death_poofs(Entity_Familiar& wisp, WispEntry& config) sound_play(SOUND_STEAM_HALFSEC); } -// 00436fd0 A wisp's death: an Eden's Soul or Mystery Gift wisp comes back after the next clear, then the flame goes -// out. The wisps that die their own way stop the game. True when it dies. +// 00436fd0 A wisp's death: what its item's wisp leaves behind (a few come back as another wisp instead), an Eden's +// Soul or Mystery Gift wisp coming back after the next clear, then the flame going out. True when it dies. bool Entity_Familiar::wisp_kill() { - if (is_wisp_unwritten(*this)) wisp_unwritten_stop(*this, "Entity_Familiar::wisp_kill 00436fd0"); + WispEntry* config = wisp_config(*this); + if (!wisp_kind_death(*this)) return false; if (wispCollectibleType == COLLECTIBLE_EDENS_SOUL || wispCollectibleType == COLLECTIBLE_MYSTERY_GIFT) player->pendingWisps.push_back(wispCollectibleType); - wisp_death_poofs(*this, *ItemConfig::wisp_config_get(wisp_item_get(*this))); + wisp_death_poofs(*this, *config); return true; } diff --git a/src/familiar_wisp.h b/src/familiar_wisp.h new file mode 100644 index 0000000..ad4d393 --- /dev/null +++ b/src/familiar_wisp.h @@ -0,0 +1,54 @@ +#pragma once + +#include "entity_familiar.h" + +struct WispEntry; + +// What a wisp fires this frame (ai_wisp's locals): whether it may, its delay, how many shots, the turn of the first +// and the spread between them in degrees, and an aim of its own that stands in for its player's. +struct WispShot +{ + Vector aim{}; + float spreadDegrees = 0; + float turnDegrees = 0; + int count = 1; + int fireDelay = 0; + bool isFiring = false; +}; + +// What a wisp's tear becomes before it is spawned (fire_wisp_projectile's locals). +struct WispTear +{ + ColorMod color = COLOR_DEFAULT; + TearFlags flags; + Vector velocity{}; + float damage = 0; + float damageMultiplier = 1; + float fallingAccel = 0; + float fallingSpeed = 0; + float scale = 0; + int variant = 0; +}; + +// What a wisp does when hit: its own answer, or the shared one. +enum WispHit +{ + WISP_HIT_SHARED, + WISP_HIT_BLOCKED, + WISP_HIT_TAKEN +}; + +WispEntry* wisp_config(Entity_Familiar& wisp); +float wisp_base_damage(WispEntry& config); +void erased_enemy_add(Entity& enemy); + +// The wisps of the actives with their own behaviour (familiar_wisp_kinds.cpp). +void wisp_kind_init(Entity_Familiar& wisp, int item); +void wisp_kind_colors(Entity_Familiar& wisp); +void wisp_kind_update(Entity_Familiar& wisp, WispShot& shot); +void plum_flute_wisp_target(Entity_Familiar& wisp); +void plum_flute_wisp_spray(Entity_Familiar& wisp, int updateSteps); +bool wisp_kind_fire(Entity_Familiar& wisp, Vector velocity); +void wisp_kind_tear(Entity_Familiar& wisp, WispTear& tear); +WispHit wisp_kind_hit(Entity_Familiar& wisp, float& damage, uint64_t damageFlags, const EntityRef& source); +bool wisp_kind_death(Entity_Familiar& wisp); diff --git a/src/familiar_wisp_kinds.cpp b/src/familiar_wisp_kinds.cpp new file mode 100644 index 0000000..051ca19 --- /dev/null +++ b/src/familiar_wisp_kinds.cpp @@ -0,0 +1,1938 @@ +#include "familiar_wisp.h" +#include "active_items.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_factory.h" +#include "entity_laser.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_slot.h" +#include "entity_tear.h" +#include "game.h" +#include "grid_entity_door.h" +#include "grid_entity_lock.h" +#include "grid_entity_rock.h" +#include "item_config.h" +#include "item_pool.h" +#include "level.h" +#include "lua_engine.h" +#include "manager.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "pocket_items.h" +#include "room.h" +#include "room_grid.h" +#include "room_render.h" +#include "weapon_rockets.h" +#include +#include +#include +#include + +// The wisps of the actives with their own behaviour, item by item: what they set up, do each frame, fire, take and +// leave behind. Book of Virtues' extra wisps (wisps.xml's "s" ids) count from WISP_EXTRA. +constexpr int WISP_EXTRA = 0x10000; +constexpr int WISP_ROBO_BABY = WISP_EXTRA + 4; +constexpr int WISP_FLY_SMALLEST = WISP_EXTRA + 5; +constexpr int WISP_FLY_LARGEST = WISP_EXTRA + 9; +constexpr int WISP_EXTRA_BRIMSTONE_SOUL = WISP_EXTRA + 13; +constexpr int WISP_DELIRIOUS_MONSTRO = WISP_EXTRA + 14; +constexpr int WISP_DELIRIOUS_DUKE = WISP_EXTRA + 15; +constexpr int WISP_DELIRIOUS_LOKI = WISP_EXTRA + 16; +constexpr int WISP_DELIRIOUS_HAUNT = WISP_EXTRA + 17; + +constexpr int WISP_RING_OFFSET = 7; +constexpr int WISP_BUSY_STATE = 1; +constexpr int WISP_MAX_JUMPERS = 5; +constexpr int WISP_TIMED_FRAMES = 90; +constexpr int WISP_SHOT_HEAD_FRAMES = 30; +constexpr int WISP_FADE_SPAWN_FRAMES = 60; +constexpr float WISP_BEAM_MOUTH_X = 7; +constexpr float WISP_BEAM_MOUTH_Y = 5; +constexpr float WISP_BEAM_MOUTH_DROP = 18; +constexpr ColorMod WISP_FLAME_SHADE = {{1.25f, 1.25f, 1.25f, 1}, {0, 0, 0, 0}, {0.25f, 0.25f, 0.25f}}; + +// Kamikaze's blast: at least this far from its player, its damage and reach. +constexpr float KAMIKAZE_MIN_DISTANCE = 70; +constexpr float KAMIKAZE_WISP_DAMAGE = 30; +constexpr float KAMIKAZE_RADIUS = 0.75f; +constexpr float KAMIKAZE_HIT_MULTIPLIER = 3; + +// Teleport!'s fade out and in: the step, and the frames it waits shown and hidden. +constexpr float TELEPORT_FADE_STEP = 0.1f; +constexpr int TELEPORT_HIDDEN_MIN = 30; +constexpr int TELEPORT_SHOWN_MIN = 60; +constexpr uint32_t TELEPORT_WAIT_SPREAD = 30; +enum TeleportPhase +{ + TELEPORT_SHOWN, + TELEPORT_FADING_OUT, + TELEPORT_FADING_IN, + TELEPORT_HIDDEN +}; + +// Doctor's Remote's rockets and the remote's target. +constexpr int REMOTE_TARGET_SETTLE_FRAMES = 15; +constexpr float REMOTE_SCATTER = 120; +constexpr float REMOTE_FLIGHT_FRAMES = 20; +constexpr float REMOTE_MAX_SPEED = 15; +constexpr float REMOTE_DAMAGE_SCALE = 4; +constexpr float REMOTE_DAMAGE_BONUS = 8; +constexpr float REMOTE_TEAR_SCALE = 1.5f; +constexpr float REMOTE_FALLING_ACCEL = 1.2f; +constexpr float REMOTE_FALL_DRAG = 0.9f; +constexpr float REMOTE_FALL_SPAN = -9.491221f; +constexpr float REMOTE_FALL_MIN = 0.01f; +constexpr float REMOTE_LAUNCH_HEIGHT = 18; +constexpr float REMOTE_LAUNCH_SLOPE = 13; + +// Shoop da Whoop!'s beam. +constexpr int SHOOP_CHARGE_FRAMES = 30; +constexpr int SHOOP_BEAM_FRAMES = 15; +constexpr int SHOOP_COOLDOWN = 8; +constexpr float SHOOP_MOUTH_Y = -18; +constexpr float SHOOP_DAMAGE = 3.5f; +constexpr float SHOOP_SCALE_STEP = 0.15f; +constexpr float SHOOP_SCALE_BASE = 0.35f; +constexpr float SHOOP_BEHIND_Y = -0.5f; +constexpr float SHOOP_WISP_DEPTH_BEHIND = -50; +constexpr float SHOOP_WISP_DEPTH_FRONT = 3000; + +// Lemon Mishap's and Free Lemonade's creep and splats. +constexpr int LEMON_FRAME_INTERVAL = 4; +constexpr uint32_t LEMON_CHANCE = 6; +constexpr int LEMON_CREEP_FRAMES = 90; +constexpr float LEMON_CREEP_SCALE = 0.65f; +constexpr float LEMON_CREEP_DAMAGE = 7; +constexpr float LEMON_SPLAT_SIZE = 0.5f; +constexpr float LEMON_SPLAT_SIZE_MIN = 0.2f; +constexpr float LEMON_SPLAT_SPREAD = 2; +constexpr float LEMON_SPLAT_DROP = 8; +constexpr float LEMON_TEAR_FALL = 0.6f; +constexpr ColorMod LEMON_CREEP_COLOR = {{1, 1, 1, 1}, {6.0714f, 5.7857f, 0, 1}, {0, 0, 0}}; +constexpr ColorMod LEMON_SPLAT_COLOR = {{0, 0, 0, 0.7f}, {0, 0, 0, 0}, {200 / 255.0f, 200 / 255.0f, 0}}; + +// My Little Unicorn's and Unicorn Stump's rainbow, slow and pale unless the player is charging. +constexpr float UNICORN_DAMAGE_BONUS = 8; +constexpr float UNICORN_STUMP_DAMAGE_BONUS = -5; +constexpr uint32_t RAINBOW_SLOW_FRAMES = 60; +constexpr uint32_t RAINBOW_FAST_FRAMES = 30; +constexpr float RAINBOW_PALE_SATURATION = 0.3f; +constexpr float RAINBOW_PALE_VALUE = 0.7f; +constexpr float RAINBOW_SECOND_HUE = 0.2f; +constexpr float HUE_DEGREES = 360; + +// Gamekid's scare. +constexpr int GAMEKID_FEAR = -2; +constexpr int GAMEKID_HIT_FEAR = 2; +constexpr int GAMEKID_TARGET_FRAMES = 150; +constexpr int GAMEKID_TINT_FRAMES = 2; +constexpr uint32_t GAMEKID_HEART_CHANCE = 4; +constexpr int GAMEKID_HIT_COUNTDOWN = 30; +constexpr ColorMod GAMEKID_TINT = {{0.3f, 0.5f, 1.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Mom's Bottle of Pills: the pill each wisp shows (one to six) and the colours of the six pills, shuffled per run. +constexpr int PILL_WISP_COLORS = 6; +constexpr float PILL_CORE_BRIGHTNESS = 2; +constexpr float PILL_FLAME_BRIGHTNESS = 1.7f; +constexpr float PILL_FLAME_LIFT = 0.3f; +constexpr float PILL_EFFECT_CHANCE = 0.15f; +constexpr int PILL_SPIDER_WISP = 6; +constexpr float PILL_SPIDER_HEIGHT = -30; +constexpr std::array, PILL_WISP_COLORS> PILL_WISP_RGB = { + {{1, 0.2f, 0.2f}, {0.2f, 0.35f, 1}, {0.1f, 0.1f, 0.8f}, {1, 0.8f, 0.2f}, {1, 1, 1}, {0.2f, 0.2f, 0.2f}}}; + +// Monster Manual's random looks and shots: its colour, fire delay and tear kinds (the exe's tables at 00b647b0, +// 00c7fd20 and 00c7fe98). +constexpr float MONSTER_SATURATION_SPREAD = 0.2f; +constexpr float MONSTER_SATURATION_BASE = 0.8f; +constexpr float MONSTER_VALUE = 0.8f; +constexpr float MONSTER_BRIGHTNESS = 2; +constexpr uint32_t MONSTER_DELAY_SPREAD = 14; +constexpr int MONSTER_DELAY_MIN = 16; +constexpr float MONSTER_BONUS_BASE = 0.3f; +constexpr float MONSTER_BONUS_SCALE = 0.37f; +constexpr std::array MONSTER_TEAR_VARIANTS = {0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 13, 14, 15, + 16, 18, 19, 20, 22, 23, 24, 26, 27, 29, 30, 31, 32}; +constexpr std::array MONSTER_TEAR_SHAPES = { + -1, TEAR_SPECTRAL, TEAR_PIERCING, TEAR_HOMING, TEAR_GROW, TEAR_SPLIT, + TEAR_BOOMERANG, TEAR_WIGGLE, TEAR_ORBIT, TEAR_WAIT, TEAR_QUADSPLIT, TEAR_BOUNCE, + TEAR_SHRINK, TEAR_ATTRACTOR, TEAR_PULSE, TEAR_SPIRAL, TEAR_FLAT, TEAR_SQUARE, + TEAR_CONTINUUM, TEAR_MYSTERIOUS_LIQUID_CREEP, TEAR_BIG_SPIRAL, TEAR_BONE_FLAG, TEAR_JACOBS}; +constexpr std::array MONSTER_TEAR_STATUSES = { + -1, TEAR_SLOW, TEAR_POISON, TEAR_FREEZE, TEAR_PERSISTENT, TEAR_CHARM, + TEAR_CONFUSION, TEAR_HP_DROP, TEAR_FEAR, TEAR_BURN, TEAR_GLOW, TEAR_STICKY, + TEAR_LIGHT_FROM_HEAVEN, TEAR_COIN_DROP, TEAR_GODS_FLESH_FLAG, TEAR_PERMANENT_CONFUSION, TEAR_BOOGER_FLAG, + TEAR_EGG_FLAG, TEAR_BELIAL_FLAG, TEAR_MIDAS, TEAR_NEEDLE_FLAG, TEAR_HORN}; + +// The Pony's and White Pony's dash. +constexpr float PONY_WISP_DASH_SPEED = 10; +constexpr float PONY_HOME_DISTANCE_SQUARED = 50; +constexpr float PONY_ROOM_MARGIN = -100; +constexpr float PONY_BOUNCE_DRAG = 0.5f; +constexpr int PONY_DASH_END = -10; +constexpr int PONY_REST_FRAMES = 60; +constexpr float PONY_DASH_DAMAGE = 0.2f; + +// Dad's Key. +constexpr float DADS_KEY_REACH = 24; + +// Crystal Ball's aim: the cone it looks in and how it ranks the enemies there. +constexpr float CRYSTAL_CONE = 0.8f; +constexpr float CRYSTAL_ALIGN_WEIGHT = 2000; +constexpr float CRYSTAL_NEAR = 800; +constexpr float CRYSTAL_WEAK = 400; +constexpr float CRYSTAL_LEAD = 0.05f; + +// Tammy's Head, Kamikaze, Bob's Rotten Head: the tear's turn, rise and drop. +constexpr float TAMMY_SPREAD = 40; +constexpr float KAMIKAZE_FALL_MIN = 1; +constexpr float BOB_FALLING_ACCEL = 0.6f; +constexpr float BOB_RISE_MIN = 5; + +// Scissors', Undefined's and the Delirious Monstro's sprays. +constexpr float SPRAY_JITTER = 2; +constexpr float SPRAY_WISP_FALLING_ACCEL = 0.5f; +constexpr float SPRAY_SPEED_SPREAD = 0.5f; +constexpr float SPRAY_SPEED_MIN = 0.25f; +constexpr float SPRAY_SCALE_JITTER = 0.05f; +constexpr float SPRAY_SCALE_BIG = 0.4f; +constexpr float SPRAY_WISP_SCALE_MIN = 0.9f; +constexpr float SPRAY_RISE_SPREAD = 15; +constexpr float SPRAY_RISE_MIN = 5; +constexpr uint32_t UNDEFINED_EFFECTS = 9; + +// Monster Manual's tear changes, D8's damage spread, Wavy Cap's size and Larynx's keys. +constexpr float MONSTER_DAMAGE_SPREAD = 0.4f; +constexpr float MONSTER_DAMAGE_MIN = 0.8f; +constexpr float MONSTER_FALL_SPREAD = 0.4f; +constexpr float MONSTER_FALL_MIN = -0.2f; +constexpr float MONSTER_SPEED_SPREAD = 0.6f; +constexpr float MONSTER_SPEED_MIN = 0.7f; +constexpr uint32_t D8_DELAY_SPREAD = 5; +constexpr int D8_DELAY_SHIFT = -2; +constexpr int D8_SHIFT_INDEX = 13; +constexpr float WAVY_CAP_STACK = 0.75f; +constexpr float WAVY_CAP_NULL_STACK = 0.3f; +constexpr float WAVY_CAP_ROOT = 0.23f; +constexpr float WAVY_CAP_LINEAR = 0.01f; +constexpr float WAVY_CAP_BASE = 0.55f; +constexpr float LARYNX_DAMAGE = 0.5f; +constexpr float LARYNX_CONTACT = 0.15f; +constexpr float LARYNX_SCALE = 0.1f; + +// The shot patterns: Scissors' two or three, Coupon's fan, the Delirious Monstro's burst and Loki's cross. +constexpr int COUPON_SHOTS = 3; +constexpr float COUPON_SPREAD = 15; +constexpr int MONSTRO_BURST_MIN = 5; +constexpr int LOKI_SHOTS = 4; +constexpr float LOKI_SPREAD = 90; +constexpr float LOKI_TURN = 45; +constexpr float SPRINKLER_TURN = 45; + +// The Potato Peeler's chase, Brown Nugget's aim and Mine Crafter's drift. +constexpr float PEELER_DRIFT_FRICTION = 0.9f; +constexpr float PEELER_CHASE_FRICTION = 0.8f; +constexpr float PEELER_RETURN_SPEED = 0.5f; +constexpr float PEELER_REACH = 100; +constexpr float PEELER_CLOSE_SQUARED = 10000; +constexpr float PEELER_LEAD = 0.02f; +constexpr float NUGGET_REACH = 150; +constexpr int NUGGET_LINE_MODE = 3; +constexpr int NUGGET_LINE_THRESHOLD = 900; +constexpr float CRAFTER_FRICTION = 0.9f; +constexpr float CRAFTER_SPEED = 2; +constexpr float CRAFTER_BUMP = 0.1f; +constexpr float CRAFTER_TURN = 3.14f; +constexpr float CRAFTER_DAMAGE = 100; +constexpr float CRAFTER_RADIUS = 75; + +// The How to Jump and Stitches wisps' contact, and Vengeful Spirit's. +constexpr float JUMPER_CONTACT = 0.5f; +constexpr float VENGEFUL_MASS = 0.1f; +constexpr float VENGEFUL_CONTACT = 0.25f; + +// The Plum Flute wisp's spray as Baby Plum sprays. +constexpr int BABY_PLUM_SPRAY_STATE = 6; +constexpr float PLUM_WISP_FRICTION = 0.98f; +constexpr int PLUM_TEAR_INTERVAL = 4; +constexpr float PLUM_DIAGONAL = 45; +constexpr float PLUM_TEAR_SPEED = 5; +constexpr float PLUM_SPEED_SPREAD = 0.2f; +constexpr float PLUM_SPEED_MIN = 0.9f; +constexpr float PLUM_TEAR_SPREAD = 60; +constexpr float PLUM_TEAR_FALL = 0.05f; +constexpr float PLUM_TEAR_HEIGHT = 10; +constexpr float PLUM_TEAR_DAMAGE = 3; +constexpr float PLUM_THRUST = 0.4f; +constexpr std::array PLUM_TEAR_SCALES = {0.5f, 0.625f}; +constexpr float PLUM_TEAR_SCALE_MIN = 0.01f; + +// Red Candle's and Urn of Souls' flames, Sulfur's beam and the Delirious Haunt's. +constexpr float CANDLE_FLAME_SPEED = 5; +constexpr float WISP_FLAME_DAMAGE = 10; +constexpr int RED_CANDLE_FLAME_FRAMES = 150; +constexpr int URN_FLAME_FRAMES = 90; +constexpr uint32_t URN_FLAME_CHANCE = 7; +constexpr float CANDLE_FLAME_SCALE = 0.5f; +constexpr float SULFUR_LENGTH = 180; +constexpr float SULFUR_DAMAGE = 3.5f; +constexpr float SULFUR_DEPTH = 5; +constexpr int DUKE_FLY_LIMIT = 5; +constexpr uint32_t YUCK_FLY_CHANCE = 10; + +// What dying wisps leave: Crack the Sky's beam, the Jar's heart, Krampus' cross, Book of the Dead's bony, the bombs. +constexpr float CRACK_THE_SKY_DAMAGE = 12; +constexpr float CRACK_THE_SKY_SIZE = 80; +constexpr float JAR_HEART_CHANCE = 0.25f; +constexpr int JAR_HEART_WAIT = 20; +constexpr int KRAMPUS_BEAMS = 4; +constexpr float KRAMPUS_TURN = 90; +constexpr int KRAMPUS_WISP_TIMEOUT = 20; +constexpr float KRAMPUS_SCALE = 0.5f; +constexpr uint32_t MAGIC_FINGERS_COIN_CHANCE = 10; +constexpr uint32_t BLACK_BONY_CHANCE = 3; +constexpr float SPIDER_THROW_RANGE = 80; +constexpr float SPIDER_THROW_MIN = 40; +constexpr float MEGA_BEAN_WISP_FART_RADIUS = 160; +constexpr float MEGA_BEAN_WISP_FART_SCALE = 0.5f; +constexpr float MEGA_BEAN_WISP_PUSH_RADIUS = 200; +constexpr float MEGA_BEAN_FREEZE_RADIUS = 180; +constexpr int MEGA_BEAN_FREEZE = -50; +constexpr float BEAN_WISP_FART_RADIUS = 85; +constexpr float BEAN_WISP_PUSH_RADIUS = 120; +constexpr float BUTTER_BEAN_RADIUS = 80; +constexpr float KIDNEY_BEAN_RADIUS = 80; +constexpr float DETONATOR_WISP_STEP = 60; +constexpr float DETONATOR_WISP_SPEED = 10; +constexpr float WISP_FULL_TURN = 360; +constexpr int PAUSE_WISP_FRAMES = 90; +constexpr uint32_t SMELTER_TRINKET_CHANCE = 4; +constexpr float WAIT_WHAT_WISP_RADIUS = 90; +constexpr int WAIT_WHAT_FRAMES = 10; +constexpr int HOURGLASS_SLOW_FRAMES = 90; +constexpr int GUPPY_FLY_STATE = 15; +constexpr float GUPPY_FLY_SPEED = 5; +constexpr float WISP_BOMB_THROW_SPEED = 2; +constexpr float MR_BOOM_WISP_SCALE = 0.65f; +constexpr float MR_BOOM_RADIUS = 0.75f; +constexpr float MR_BOOM_HEIGHT = -3; +constexpr float MR_BOOM_FALL = -3; +constexpr float MR_BOOM_FALL_SPREAD = 5; +constexpr int DECK_SPECIAL_CHANCE = 25; +constexpr int DECK_SUIT_CHANCE = 10; +constexpr int MOVING_BOX_PICKUP = 4; +constexpr uint32_t GAME_SEED_SHIFT_A = 2; +constexpr uint32_t GAME_SEED_SHIFT_B = 9; +constexpr uint32_t GAME_SEED_SHIFT_C = 15; + +// Mr. Me!'s errands: a tinted rock to blow up, a locked chest, a secret door to bomb open, a door to unlock. +enum MrMeErrand +{ + MR_ME_IDLE, + MR_ME_ROCK, + MR_ME_CHEST, + MR_ME_SECRET_DOOR, + MR_ME_DOOR +}; +constexpr int MR_ME_SEARCH_INTERVAL = 15; +constexpr float MR_ME_FRICTION = 0.7f; +constexpr float MR_ME_SPEED = 2; +constexpr float MR_ME_REACH_SQUARED = 225; +constexpr float MR_ME_SAFE_DISTANCE = 100; +constexpr float MR_ME_BLAST_DAMAGE = 40; +constexpr float MR_ME_BLAST_RADIUS = 80; +constexpr int DOOR_RETURN_FRAMES = 30; + +// Mega Blast's beam. +constexpr float MEGA_BLAST_AIM_DEADZONE = 0.5f; +constexpr float MEGA_BLAST_TURN_SPEED = 8; +constexpr int MEGA_BLAST_CHARGE_FRAMES = 30; +constexpr int MEGA_BLAST_HEAD_FLOAT = 8; +constexpr float MEGA_BLAST_BEHIND_Y = -0.5f; +constexpr float MEGA_BLAST_DEPTH_BEHIND = -10; +constexpr float MEGA_BLAST_DEPTH_FRONT = 3000; + +// The wisp it is, by item. +static bool is_wisp(Entity_Familiar& wisp, int item) +{ + return wisp.variant == Entity_Familiar::WISP && wisp.subtype == item; +} + +// Kills an entity with a blank source, as the wisps' own kills do. +static void wisp_die(Entity& entity) +{ + entity.Kill(EntityRef()); +} + +// The free spot nearest a position for a pickup, the first ring this far out. +static Vector pickup_spot(const Vector& position, float step) +{ + return room_free_pickup_position_find({.position = position, .step = step}); +} + +// A pickup at a free spot by the wisp, the seed drawn first. +static Entity* wisp_pickup_spawn(Entity_Familiar& wisp, int variant, int subType, float step) +{ + uint32_t seed = wisp.dropRNG.Next(); + return g_game->Spawn({.position = pickup_spot(wisp.pos, step), + .spawner = &wisp, + .subType = subType, + .type = ENTITY_PICKUP, + .variant = variant, + .seed = seed}); +} + +// An effect from the wisp. +static Entity_Effect* wisp_effect_spawn(Entity_Familiar& wisp, int effect, Vector velocity, Entity* spawner) +{ + return static_cast(g_game->Spawn({.position = wisp.pos, + .velocity = velocity, + .spawner = spawner, + .type = ENTITY_EFFECT, + .variant = effect, + .seed = Random()})); +} + +// A colour from a hue, saturation and value, doubled for a core or flame. +static ColorMod wisp_hsv_color(float hue, float saturation, float value, float brightness) +{ + KColor rgb = hsv_to_rgb(hue, saturation, value, 1); + return {{rgb._red * brightness, rgb._green * brightness, rgb._blue * brightness, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +} + +// A tear's colour from the wisp's flame: half of it brightened, a quarter of it added. +static ColorMod wisp_flame_tear_color(Entity_Familiar& wisp) +{ + const float* tint = wisp.sprite.GetLayer(1)->color._tint; + ColorMod color = WISP_FLAME_SHADE; + for (int i = 0; i < 3; i++) + { + color._tint[i] *= tint[i] * 0.5f; + color._offset[i] *= tint[i] * 0.5f; + } + return color; +} + +// Kamikaze's blast at the wisp, pushed out to stay clear of its player. +static void kamikaze_blast(Entity_Familiar& wisp) +{ + Vector away = vector_sub(wisp.pos, wisp.player->pos); + float distance = vector_length(away); + if (distance < KAMIKAZE_MIN_DISTANCE) away = vector_scale(away, KAMIKAZE_MIN_DISTANCE / distance); + explosion_effects({.position = vector_add(wisp.player->pos, away), + .source = &wisp, + .damage = KAMIKAZE_WISP_DAMAGE, + .radiusMultiplier = KAMIKAZE_RADIUS}); +} + +// The creep a lemon wisp leaves: red creep turned yellow, small for Lemon Mishap's. +static Entity_Effect* lemon_creep_spawn(Entity_Familiar& wisp, float damage) +{ + Entity_Effect* creep = wisp_effect_spawn(wisp, EFFECT_PLAYER_CREEP_RED, {}, &wisp); + creep->timeout = LEMON_CREEP_FRAMES; + creep->lifespan = LEMON_CREEP_FRAMES; + creep->SetCollisionDamage(damage); + return creep; +} + +// A lemon wisp's splat on the floor near it, yellow. +static void lemon_splat_spawn(Entity_Familiar& wisp) +{ + float size = random_unit() * LEMON_SPLAT_SIZE + LEMON_SPLAT_SIZE_MIN; + Entity* splat = wisp_effect_spawn(wisp, EFFECT_BLOOD_SPLAT, {}, &wisp); + splat->sprite.scale = vector_make(size, size); + splat->Update(); + Vector spread = vector_scale(random_direction(), LEMON_SPLAT_SPREAD); + splat->pos = vector_add(vector_add(wisp.pos, spread), vector_make(0, LEMON_SPLAT_DROP)); + splat->SetColor(LEMON_SPLAT_COLOR, -1, 255, false, true); +} + +// 00436330's Mom's Bottle of Pills part: the pill the wisp is (one to six) dealt the run's shuffled pill colours (the +// exe's statics at 00c7e820, dealt again for a new start seed). +static const std::array& pill_wisp_rgb(int pill) +{ + static uint32_t dealtSeed = 0; + static std::array order{}; + + uint32_t startSeed = g_game->seedEffects.GetStartSeed(); + if (startSeed != dealtSeed) + { + RNG rng{startSeed, GAME_SEED_SHIFT_A, GAME_SEED_SHIFT_B, GAME_SEED_SHIFT_C}; + for (int i = 0; i < PILL_WISP_COLORS; i++) order[i] = i; + for (int i = 0; i < PILL_WISP_COLORS - 1; i++) + std::swap(order[i], order[i + rng.Next() % (uint32_t)(PILL_WISP_COLORS - i)]); + dealtSeed = startSeed; + } + return PILL_WISP_RGB[order[pill - 1]]; +} + +// The jumping wisps (How to Jump, Stitches): no more than five of a kind and player, the oldest going first. +static void jumper_wisps_limit(Entity_Familiar& wisp) +{ + std::map byAge; + for (Entity* entity : g_game->room->entityList.updateEL) + { + auto* other = entity && entity->type == ENTITY_FAMILIAR && entity->variant == Entity_Familiar::WISP + ? static_cast(entity) + : nullptr; + if (other && other->player == wisp.player && other->subtype == wisp.subtype) + byAge.emplace(other->spawnFrame - g_game->frameCount, other); + } + while (byAge.size() > WISP_MAX_JUMPERS) + { + wisp_die(*byAge.begin()->second); + byAge.erase(byAge.begin()); + } +} + +// The part of 00436330 for the wisps with their own setup, by the item it is. +void wisp_kind_init(Entity_Familiar& wisp, int item) +{ + switch (item) + { + case COLLECTIBLE_MOMS_BOTTLE_OF_PILLS: + if (wisp.coins == 0) wisp.coins = (int)wisp.dropRNG.RandomInt(PILL_WISP_COLORS) + 1; + break; + case COLLECTIBLE_BEAN: case COLLECTIBLE_CANDLE: case COLLECTIBLE_RED_CANDLE: case COLLECTIBLE_BUTTER_BEAN: + case COLLECTIBLE_BOOMERANG: case COLLECTIBLE_KIDNEY_BEAN: case COLLECTIBLE_WAIT_WHAT: + case COLLECTIBLE_BROWN_NUGGET: case COLLECTIBLE_MOMS_BRACELET: case COLLECTIBLE_DARK_ARTS: + case COLLECTIBLE_SUPLEX: case COLLECTIBLE_ANIMA_SOLA: case COLLECTIBLE_DECAP_ATTACK: + wisp.isNotCountedAsFollower = true; + break; + case COLLECTIBLE_MINE_CRAFTER: + wisp.entityCollisionClass = ENTCOLL_NONE; + wisp.entityGridCollisionClass = GRIDCOLL_WALLS; + wisp.isInvincible = true; + wisp.isNotCountedAsFollower = true; + wisp.velocity = random_direction(); + break; + case COLLECTIBLE_STITCHES: + wisp.pos.y += 1; + [[fallthrough]]; + case COLLECTIBLE_HOW_TO_JUMP: + wisp.targetPosition = wisp.pos; + wisp.isNotCountedAsFollower = true; + jumper_wisps_limit(wisp); + break; + case COLLECTIBLE_POTATO_PEELER: + wisp.entityCollisionClass = ENTCOLL_NONE; + wisp.isInvincible = true; + wisp.target = nullptr; + break; + case COLLECTIBLE_FORTUNE_COOKIE: + wisp.player->cacheFlags |= CACHE_LUCK; + wisp.player->temporaryEffects.isEvaluateCachePending = true; + break; + case COLLECTIBLE_ETERNAL_D6: + wisp.isInvincible = true; + break; + case COLLECTIBLE_LEMEGETON: + { + Level& level = *g_game; + if (wisp.subtype == COLLECTIBLE_BLUE_MAP || wisp.subtype == COLLECTIBLE_MIND) level.ApplyBlueMapEffect(); + if (wisp.subtype == COLLECTIBLE_TREASURE_MAP || wisp.subtype == COLLECTIBLE_MIND) level.ApplyMapEffect(); + if (wisp.subtype == COLLECTIBLE_COMPASS || wisp.subtype == COLLECTIBLE_MIND) level.ApplyCompassEffect(true); + break; + } + } +} + +// The end of 00436330: Esau Jr.'s wisp turns dark while its player is Esau, and Monster Manual's takes two random +// colours of its own. +void wisp_kind_colors(Entity_Familiar& wisp) +{ + constexpr ColorMod ESAU_CORE = {{710 / 255.0f, 710 / 255.0f, 710 / 255.0f, 1}, {0, 0, 0, 0}, + {-512 / 255.0f, -512 / 255.0f, -512 / 255.0f}}; + constexpr ColorMod ESAU_FLAME = {{20 / 255.0f, 20 / 255.0f, 20 / 255.0f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + + TemporaryEffects& effects = wisp.player->temporaryEffects; + if (wisp.subtype == COLLECTIBLE_ESAU_JR && !effects.isDisabled && effects.HasNullEffect(NULLITEM_ESAU_JR)) + { + wisp.coins = 1; + wisp.sprite.GetLayer(0)->color = ESAU_CORE; + wisp.sprite.GetLayer(1)->color = ESAU_FLAME; + } + if (wisp.subtype != COLLECTIBLE_MONSTER_MANUAL) return; + + RNG rng{wisp.initSeed, 9, 11, 19}; + for (int layer = 0; layer < 2; layer++) + { + float first = rng.RandomFloat(); + float saturation = (first + rng.RandomFloat() - 1) * MONSTER_SATURATION_SPREAD + MONSTER_SATURATION_BASE; + float hue = rng.RandomFloat() * HUE_DEGREES; + wisp.sprite.GetLayer(layer)->color = wisp_hsv_color(hue, saturation, MONSTER_VALUE, MONSTER_BRIGHTNESS); + } +} + +// Teleport!'s and Teleport 2.0's wisps fade out, wait hidden and harmless, and fade back in, over and over. +static void teleport_wisp_update(Entity_Familiar& wisp, WispShot& shot) +{ + switch (wisp.wispState) + { + case TELEPORT_SHOWN: + if (wisp.wispTimer-- < 0) wisp.wispState = TELEPORT_FADING_OUT; + break; + case TELEPORT_FADING_OUT: + shot.isFiring = false; + wisp.collisionDamage = 0; + if (wisp.wispCharge > 0) wisp.wispCharge -= TELEPORT_FADE_STEP; + else + { + wisp.wispState = TELEPORT_HIDDEN; + wisp.wispTimer = (int)(Random() % TELEPORT_WAIT_SPREAD) + TELEPORT_HIDDEN_MIN; + } + break; + case TELEPORT_FADING_IN: + if (wisp.wispCharge < 1) wisp.wispCharge += TELEPORT_FADE_STEP; + else + { + wisp.wispState = TELEPORT_SHOWN; + wisp.wispTimer = (int)(Random() % TELEPORT_WAIT_SPREAD) + TELEPORT_SHOWN_MIN; + } + break; + case TELEPORT_HIDDEN: + shot.isFiring = false; + wisp.isVisible = false; + wisp.collisionDamage = 0; + if (wisp.wispTimer-- < 0) + { + wisp.isVisible = true; + wisp.wispState = TELEPORT_FADING_IN; + } + break; + } + ColorMod faded = wisp.sprite.color; + faded._tint[3] = wisp.wispCharge; + wisp.sprite.color = faded; +} + +// Whether the player holds Doctor's Remote up with its target settled. +static Entity* remote_target(Entity_Player& player) +{ + Weapon* weapon = player.weapons[0].get(); + if (player.itemState != COLLECTIBLE_DOCTORS_REMOTE || !weapon || weapon->weaponType != WEAPON_ROCKETS) return nullptr; + Entity* target = static_cast(weapon)->target; + if (!target || g_game->frameCount - target->spawnFrame <= REMOTE_TARGET_SETTLE_FRAMES) return nullptr; + return target; +} + +// Shoop da Whoop!'s wisp lets out a small beam of its own as its player's mouth opens, along the player's aim (or +// its last one). +static void shoop_wisp_update(Entity_Familiar& wisp) +{ + Entity_Player& player = *wisp.player; + if (player.itemState != COLLECTIBLE_SHOOP_DA_WHOOP || player.itemStateCooldown != SHOOP_CHARGE_FRAMES || + wisp.counter >= 1) + return; + + Vector aim = vector_is_zero(player.aimDirection) ? wisp.targetPosition : player.aimDirection; + aim = vector_normalized(aim); + float size = player.HasCollectible(COLLECTIBLE_BFFS) ? 1.0f : 2.0f; + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = wisp.pos, + .posOffset = vector_make(0, SHOOP_MOUTH_Y), + .source = &wisp, + .angleDegrees = vector_angle(aim), + .timeout = SHOOP_BEAM_FRAMES, + .variant = LASER_SHOOP}); + laser->SetCollisionDamage(size * SHOOP_DAMAGE); + laser->scale = size * SHOOP_SCALE_STEP + SHOOP_SCALE_BASE; + laser->ResetSpriteScale(); + laser->renderDepthOffset = aim.y <= SHOOP_BEHIND_Y ? SHOOP_WISP_DEPTH_BEHIND : SHOOP_WISP_DEPTH_FRONT; + laser->Update(); + wisp.counter = SHOOP_COOLDOWN; +} + +// Lemon Mishap's wisp drips small yellow creep now and then, and both lemon wisps leave yellow splats. +static void lemon_wisp_update(Entity_Familiar& wisp) +{ + if (!wisp.IsFrame(LEMON_FRAME_INTERVAL, 0)) return; + if (is_wisp(wisp, COLLECTIBLE_LEMON_MISHAP) && Random() % LEMON_CHANCE == 0) + { + Entity_Effect* creep = lemon_creep_spawn(wisp, LEMON_CREEP_DAMAGE); + creep->sprite.scale = vector_make(LEMON_CREEP_SCALE, LEMON_CREEP_SCALE); + creep->Update(); + creep->sprite.color = LEMON_CREEP_COLOR; + } + if (Random() % LEMON_CHANCE == 0) lemon_splat_spawn(wisp); +} + +// My Little Unicorn's and Unicorn Stump's wisps cycle through the rainbow, faster and brighter while the player +// charges, and hit hard only then (My Little Unicorn's always). +static void unicorn_wisp_update(Entity_Familiar& wisp, float contact) +{ + TemporaryEffects& effects = wisp.player->temporaryEffects; + bool isCharging = effects.HasCollectibleEffect(COLLECTIBLE_UNICORN_STUMP) || + effects.HasCollectibleEffect(COLLECTIBLE_MY_LITTLE_UNICORN); + if (wisp.subtype == COLLECTIBLE_MY_LITTLE_UNICORN) wisp.collisionDamage = contact + UNICORN_DAMAGE_BONUS; + else wisp.collisionDamage = isCharging ? contact + UNICORN_STUMP_DAMAGE_BONUS : 0; + + uint32_t age = (uint32_t)(g_game->frameCount - wisp.spawnFrame) + wisp.initSeed; + uint32_t period = isCharging ? RAINBOW_FAST_FRAMES : RAINBOW_SLOW_FRAMES; + float hue = (float)(age % period) / (float)period; + float saturation = isCharging ? 1 : RAINBOW_PALE_SATURATION; + float value = isCharging ? 1 : RAINBOW_PALE_VALUE; + wisp.sprite.GetLayer(0)->color = wisp_hsv_color(hue * HUE_DEGREES, saturation, value, 1); + float second = hue + RAINBOW_SECOND_HUE; + if (second > 1) second -= 1; + wisp.sprite.GetLayer(1)->color = wisp_hsv_color(second * HUE_DEGREES, saturation, value, 1); +} + +// Gamekid's wisp keeps the enemy that hurt it scared and tinted for a while, now and then hurting it for a heart. +static void gamekid_wisp_update(Entity_Familiar& wisp) +{ + Entity* target = wisp.target; + if (!target) return; + if (wisp.counter < 1 || target->isDead) + { + wisp.target = nullptr; + return; + } + target->SetColor(GAMEKID_TINT, GAMEKID_TINT_FRAMES, 0, false, true); + target->AddFear(EntityRef(&wisp), GAMEKID_FEAR, false); + if (Random() % GAMEKID_HEART_CHANCE == 0) + target->TakeDamage(0, DAMAGE_SPAWN_RED_HEART, EntityRef(&wisp), GAMEKID_HIT_COUNTDOWN); +} + +// Mom's Bottle of Pills' wisp shows its pill's colours on its first frame. +static void pills_wisp_update(Entity_Familiar& wisp) +{ + if (g_game->frameCount != wisp.spawnFrame || wisp.coins <= 0 || wisp.coins > PILL_WISP_COLORS) return; + + const std::array& rgb = pill_wisp_rgb(wisp.coins); + ColorMod core = COLOR_DEFAULT; + ColorMod flame = COLOR_DEFAULT; + for (int i = 0; i < 3; i++) + { + core._tint[i] = rgb[i] * PILL_CORE_BRIGHTNESS; + flame._tint[i] = rgb[i] * PILL_FLAME_BRIGHTNESS + PILL_FLAME_LIFT; + } + wisp.sprite.GetLayer(0)->color = core; + wisp.sprite.GetLayer(1)->color = flame; +} + +// The Pony's wisp dashes along its player's aim, breaking what it hits and bouncing off walls before it rests and +// floats home. It hits softly while dashing. +static void pony_wisp_update(Entity_Familiar& wisp) +{ + int direction = wisp.player->fireDirection; + Vector aim = direction_unit(direction); + if (wisp.fireCooldown > 0) wisp.fireCooldown--; + if (wisp.fireCooldown >= 0 && wisp.isInvincible && + vector_length_squared(vector_sub(wisp.pos, wisp.GetOrbitPosition(wisp.player->pos))) < PONY_HOME_DISTANCE_SQUARED) + { + wisp.isInvincible = false; + wisp.PlayFloatAnim(DIRECTION_NONE); + } + + Room& room = *g_game->room; + if (wisp.fireCooldown >= 0) + { + wisp.sprite.isFlipX = aim.x < 0; + if (direction != DIRECTION_NONE && wisp.fireCooldown <= 0) + { + wisp.state = WISP_BUSY_STATE; + wisp.isInvincible = true; + wisp.fireCooldown = -1; + wisp.entityGridCollisionClass = GRIDCOLL_BULLET; + wisp.velocity = vector_scale(aim, PONY_WISP_DASH_SPEED); + wisp.PlayShootAnim(DIRECTION_NONE); + } + } + else if (wisp.isCollidesWithGrid || wisp.fireCooldown < -1 || !room.IsPositionInRoom(wisp.pos, PONY_ROOM_MARGIN)) + { + wisp.entityGridCollisionClass = GRIDCOLL_NONE; + GridEntity* grid = room.GetGridEntity(room.GetGridIndex(wisp.pos)); + if (grid) grid->Hurt(1, EntityRef(wisp.player)); + wisp.velocity = vector_scale(wisp.velocity, PONY_BOUNCE_DRAG); + if (--wisp.fireCooldown < PONY_DASH_END) + { + wisp.fireCooldown = PONY_REST_FRAMES; + wisp.state = 0; + } + } + if (wisp.isInvincible) wisp.collisionDamage *= PONY_DASH_DAMAGE; +} + +// Dad's Key's wisp opens the locked door or key block it floats over and the chests and Key Master it touches, dying +// in the doing. +static void dads_key_wisp_update(Entity_Familiar& wisp) +{ + Room& room = *g_game->room; + Entity_Player& player = *wisp.player; + int index = room.GetGridIndex(wisp.pos); + GridEntity* grid = index >= 0 && index < ROOM_GRID_CELLS ? room.gridEntities[index] : nullptr; + if (grid && grid->type == GRID_DOOR) + { + auto* door = static_cast(grid); + if (room.GetGridCollision(index) == COLLISION_WALL && door->IsLocked() && + !(door->doorFlags & DOOR_FLAG_COIN_LOCK) && door->TryUnlock(player, true)) + wisp_die(wisp); + } + else if (grid && grid->type == GRID_LOCK && grid->state == 0) + { + static_cast(grid)->try_unlock(player, true); + wisp_die(wisp); + } + if (wisp.isDead || !wisp.IsFrame(2, 0)) return; + + for (Entity* entity : entity_query_radius(wisp.pos, DADS_KEY_REACH, QUERY_PICKUPS)) + { + if (!entity) continue; + bool isChest = entity->type == ENTITY_PICKUP && (entity->variant == PICKUP_LOCKEDCHEST || + entity->variant == PICKUP_ETERNALCHEST || + entity->variant == PICKUP_OLDCHEST); + if (isChest && static_cast(entity)->TryOpenChest(&player)) + { + wisp_die(wisp); + return; + } + const AnimationState& anim = entity->sprite.animState; + bool isKeyMasterIdle = entity->type == ENTITY_SLOT && entity->variant == SLOT_KEY_MASTER && + (!anim.animData || anim.animData->isLooping || !anim.isPlaying); + if (isKeyMasterIdle) + { + Entity::ForceCollide(&player, entity, true); + wisp_die(wisp); + return; + } + } +} + +// Ventricle Razor's wisp stands on its portal: placed there on its first frame, gone with it. +static void ventricle_wisp_update(Entity_Familiar& wisp) +{ + Entity* portal = wisp.parent; + if (g_game->frameCount == wisp.spawnFrame) + { + if (portal) wisp.pos = wisp.GetOrbitPosition(portal->pos); + } + else if (!portal) wisp.Remove(); + else if (portal->isDead) wisp_die(wisp); +} + +// The Potato Peeler's wisp drifts back to its ring until an enemy comes near, then chases it, firing as it closes. +static void peeler_wisp_update(Entity_Familiar& wisp, WispShot& shot) +{ + int ring = wisp_config(wisp)->layer + WISP_RING_OFFSET; + shot.isFiring = false; + Entity* target = wisp.target; + if (!target) + { + if (wisp.orbitLayer >= 0) wisp.friction = 1; + else + { + wisp.friction = PEELER_DRIFT_FRICTION; + Vector home = Entity_Familiar::GetOrbitDistance(ring); + if (vector_length(vector_sub(wisp.pos, wisp.player->pos)) < home.x) wisp.AddToOrbit(ring); + else wisp.AddVelocity_divided(vector_resized(vector_sub(wisp.player->pos, wisp.pos), PEELER_RETURN_SPEED), false); + } + for (Entity* enemy : entity_query_radius(wisp.pos, PEELER_REACH, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr)) continue; + wisp.target = enemy; + wisp.RemoveFromOrbit(); + break; + } + return; + } + + wisp.friction = PEELER_CHASE_FRICTION; + Vector toTarget = vector_sub(target->pos, wisp.pos); + float distanceSquared = vector_length_squared(toTarget); + if (distanceSquared > PEELER_CLOSE_SQUARED) wisp.AddVelocity_divided(vector_resized(toTarget, 1), false); + float lead = std::sqrt(distanceSquared) * PEELER_LEAD; + shot.aim = vector_normalized(vector_sub(vector_add(target->pos, vector_scale(target->velocity, lead)), wisp.pos)); + if (wisp.fireCooldown < 1) shot.isFiring = true; + else wisp.fireCooldown--; + if (!target->IsVulnerableEnemy(nullptr)) wisp.target = nullptr; +} + +// Brown Nugget's wisp fires on its own at the last enemy it can see nearby. +static void nugget_wisp_update(Entity_Familiar& wisp, WispShot& shot) +{ + shot.isFiring = false; + if (wisp.fireCooldown > 0) wisp.fireCooldown--; + + Vector aim{}; + for (Entity* enemy : entity_query_radius(wisp.pos, NUGGET_REACH, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) continue; + if (room_check_line(wisp.pos, enemy->pos, NUGGET_LINE_MODE, NUGGET_LINE_THRESHOLD)) + aim = vector_normalized(vector_sub(enemy->pos, wisp.pos)); + } + if (vector_is_zero(aim) || shot.fireDelay <= 0) + { + if (wisp.headFrameDelay >= 0 && --wisp.headFrameDelay < 0) wisp.PlayFloatAnim(DIRECTION_DOWN); + return; + } + + int direction = vector_to_direction(aim); + if (wisp.fireCooldown < 1) + { + wisp.FireProjectile(aim, FIRE_INHERIT_MOTION); + wisp.fireCooldown = shot.fireDelay; + wisp.headFrameDelay = 12; + } + else if (wisp.headFrameDelay < 9) + { + wisp.PlayFloatAnim(direction); + wisp.headFrameDelay = 8; + return; + } + wisp.PlayShootAnim(direction); + wisp.headFrameDelay--; +} + +// 0043d850 Mine Crafter's wisp drifts about the room, bouncing off walls, and blows up at the first tear that touches +// it (a Chaos Card's excepted). +static void mine_crafter_wisp_update(Entity_Familiar& wisp) +{ + wisp.friction = CRAFTER_FRICTION; + wisp.velocity = vector_resized(wisp.velocity, CRAFTER_SPEED); + if (wisp.isCollidesWithGrid) + { + float angle = random_unit() * CRAFTER_TURN * 2; + wisp.velocity = vector_add(wisp.velocity, vector_make(std::cos(angle) * CRAFTER_BUMP, std::sin(angle) * CRAFTER_BUMP)); + } + for (Entity* entity : entity_query_radius(wisp.pos, wisp.size, QUERY_TEARS)) + { + if (entity->type != ENTITY_TEAR || entity->variant == TEAR_CHAOS_CARD) continue; + wisp_effect_spawn(wisp, EFFECT_BOMB_EXPLOSION, {}, nullptr); + bomb_crater_spawn(wisp.pos, nullptr, 1); + explosion_damage({.position = wisp.pos, + .damageFlags = DAMAGE_EXPLOSION | DAMAGE_TNT, + .damage = CRAFTER_DAMAGE, + .radius = CRAFTER_RADIUS, + .isLineCheck = false}); + wisp_die(wisp); + break; + } +} + +// The part of 0043aa90 for the wisps that do something of their own each frame, or shoot their own way. +void wisp_kind_update(Entity_Familiar& wisp, WispShot& shot) +{ + float contact = wisp.collisionDamage; + Entity_Player& player = *wisp.player; + switch (wisp.subtype) + { + case COLLECTIBLE_KAMIKAZE: + { + TemporaryEffect* effect = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_KAMIKAZE); + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_KAMIKAZE); + if (!player.isDead && effect && item && effect->cooldown == item->maxCooldown - 1) kamikaze_blast(wisp); + break; + } + case COLLECTIBLE_TELEPORT: case COLLECTIBLE_TELEPORT_2: teleport_wisp_update(wisp, shot); break; + case COLLECTIBLE_DOCTORS_REMOTE: + if (!remote_target(player)) break; + if (wisp.fireCooldown > 0) wisp.fireCooldown--; + shot.aim = vector_make(0, 1); + break; + case COLLECTIBLE_SHOOP_DA_WHOOP: shoop_wisp_update(wisp); break; + case COLLECTIBLE_LEMON_MISHAP: case COLLECTIBLE_FREE_LEMONADE: lemon_wisp_update(wisp); break; + case COLLECTIBLE_MY_LITTLE_UNICORN: case COLLECTIBLE_UNICORN_STUMP: unicorn_wisp_update(wisp, contact); break; + case COLLECTIBLE_GAMEKID: gamekid_wisp_update(wisp); break; + case COLLECTIBLE_MOMS_BOTTLE_OF_PILLS: pills_wisp_update(wisp); break; + case COLLECTIBLE_MONSTER_MANUAL: + { + RNG rng{wisp.initSeed, 1, 11, 16}; + shot.fireDelay = (int)rng.RandomInt(MONSTER_DELAY_SPREAD) + MONSTER_DELAY_MIN; + break; + } + case COLLECTIBLE_PONY: pony_wisp_update(wisp); break; + case COLLECTIBLE_DADS_KEY: dads_key_wisp_update(wisp); break; + case COLLECTIBLE_WHITE_PONY: wisp.sprite.isFlipX = direction_unit(player.fireDirection).x < 0; break; + case COLLECTIBLE_HOW_TO_JUMP: case COLLECTIBLE_STITCHES: wisp.collisionDamage = contact * JUMPER_CONTACT; break; + case COLLECTIBLE_ISAACS_TEARS: + if (g_game->frameCount - wisp.spawnFrame > WISP_TIMED_FRAMES) wisp_die(wisp); + break; + case COLLECTIBLE_SCISSORS: shot.count = (int)(Random() & 1) + 2; break; + case COLLECTIBLE_VENTRICLE_RAZOR: ventricle_wisp_update(wisp); break; + case COLLECTIBLE_D8: + { + RNG rng; + rng.game_constructor(wisp.dropRNG._seed, D8_SHIFT_INDEX); + shot.fireDelay += (int)rng.RandomInt(D8_DELAY_SPREAD) + D8_DELAY_SHIFT; + break; + } + case COLLECTIBLE_MINE_CRAFTER: mine_crafter_wisp_update(wisp); break; + case COLLECTIBLE_MEGA_BLAST: wisp.ai_mega_blast_wisp(); break; + case COLLECTIBLE_POTATO_PEELER: peeler_wisp_update(wisp, shot); break; + case COLLECTIBLE_BROWN_NUGGET: nugget_wisp_update(wisp, shot); break; + case COLLECTIBLE_SPRINKLER: shot.turnDegrees = (float)wisp.coins * SPRINKLER_TURN; break; + case COLLECTIBLE_COUPON: + shot.count = COUPON_SHOTS; + shot.spreadDegrees = COUPON_SPREAD; + shot.turnDegrees = -COUPON_SPREAD; + break; + case COLLECTIBLE_MR_ME: wisp.ai_mr_me_wisp(); break; + case COLLECTIBLE_LARYNX: wisp.collisionDamage = (float)wisp.keys * LARYNX_CONTACT * contact; break; + case COLLECTIBLE_VENGEFUL_SPIRIT: + wisp.mass = VENGEFUL_MASS; + wisp.collisionDamage = contact * VENGEFUL_CONTACT; + break; + case COLLECTIBLE_ESAU_JR: + { + bool isEsau = player.temporaryEffects.HasNullEffect(NULLITEM_ESAU_JR); + if ((isEsau && wisp.coins == 0) || (!isEsau && wisp.coins == 1)) wisp_die(wisp); + break; + } + case COLLECTIBLE_ANIMA_SOLA: + if (Entity* chain = wisp.parent) shot.aim = vector_normalized(vector_sub(chain->pos, wisp.pos)); + else wisp_die(wisp); + break; + case COLLECTIBLE_GELLO: wisp.isInvincible = g_game->frameCount - wisp.spawnFrame < WISP_FADE_SPAWN_FRAMES; break; + case WISP_DELIRIOUS_MONSTRO: shot.count = (int)(Random() & 3) + MONSTRO_BURST_MIN; break; + case WISP_DELIRIOUS_LOKI: + shot.count = LOKI_SHOTS; + shot.spreadDegrees = LOKI_SPREAD; + if ((wisp.coins & 1) == 0) shot.turnDegrees = LOKI_TURN; + if (wisp.fireCooldown == shot.fireDelay) wisp.coins++; + break; + } +} + +// The start of 0043aa90 for the Plum Flute's wisp: it joins Baby Plum's spray while its Baby Plum sprays, and comes +// back to its ring and idles after. +void plum_flute_wisp_target(Entity_Familiar& wisp) +{ + auto* plum = static_cast(wisp.target.get()); + bool isSpraying = plum && plum->type == ENTITY_FAMILIAR && plum->state == BABY_PLUM_SPRAY_STATE && + plum->fireCooldown >= 1; + if (!isSpraying && wisp.state == WISP_BUSY_STATE) + { + wisp.state = 0; + wisp.fireCooldown = 0; + wisp.entityGridCollisionClass = GRIDCOLL_NONE; + wisp_anim_play(wisp, "Idle", SWITCH_RESET); + } + else if (isSpraying && wisp.state == 0) + { + wisp.state = WISP_BUSY_STATE; + wisp.fireCooldown = 0; + wisp.entityGridCollisionClass = GRIDCOLL_WALLS; + } +} + +// The end of 0043aa90 for the Plum Flute's wisp spraying: it flies along a diagonal, spraying blood tears behind it +// every fourth update with a fart, its animation facing up or down. +void plum_flute_wisp_spray(Entity_Familiar& wisp, int updateSteps) +{ + Vector heading = vector_rotated(vector_cardinal(vector_rotated(wisp.velocity, PLUM_DIAGONAL)), -PLUM_DIAGONAL); + wisp.friction = PLUM_WISP_FRICTION; + for (; updateSteps > 0; updateSteps--) + { + if (++wisp.fireCooldown % PLUM_TEAR_INTERVAL != 0) continue; + + familiar_sound_play(SOUND_BOSS2_BUBBLES); + float speed = random_unit() * PLUM_SPEED_SPREAD + PLUM_SPEED_MIN; + Vector back = vector_scale(heading, -PLUM_TEAR_SPEED * speed); + Vector velocity = vector_rotated(back, random_unit() * PLUM_TEAR_SPREAD - PLUM_TEAR_SPREAD / 2); + float damageJitter = random_unit(); + auto* tear = static_cast(g_game->Spawn({.position = wisp.pos, + .velocity = velocity, + .spawner = &wisp, + .type = ENTITY_TEAR, + .variant = TEAR_BLOOD, + .seed = Random()})); + tear->fallingAccel -= PLUM_TEAR_FALL; + float scale = std::max(PLUM_TEAR_SCALES[Random() & 1], PLUM_TEAR_SCALE_MIN); + tear->baseScale = scale; + tear->fScale = scale; + tear->ResetSpriteScale(); + tear->SetHeight(tear->height - PLUM_TEAR_HEIGHT); + tear->SetCollisionDamage(damageJitter + PLUM_TEAR_DAMAGE); + } + wisp.sprite.Play(heading.y > 0 ? "SpecialUp" : "SpecialDown", PLAY_UNFORCED); + wisp.velocity = vector_add(wisp.velocity, vector_scale(heading, PLUM_THRUST * wisp.speedMultiplier)); +} + +// The way a wisp's head turns for a shot along an aim. +static int wisp_aim_direction(Vector aim) +{ + if (std::fabs(aim.y) < std::fabs(aim.x)) return aim.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; + return aim.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP; +} + +// A Brimstone soul wisp's or the Delirious Haunt's beam from its mouth along the nearest axis, its head turned. +static void wisp_beam_fire(Entity_Familiar& wisp, Vector velocity) +{ + Vector aim = vector_normalized(velocity); + Entity_Laser* laser = wisp.FireBrimstone(vector_cardinal(aim), BRIMSTONE_OWN); + if (!laser) return; + + if (wisp.subtype == WISP_DELIRIOUS_HAUNT) laser->SetCollisionDamage(wisp_config(wisp)->damage * wisp.wispScale); + laser->posOffset = vector_make(aim.x * WISP_BEAM_MOUTH_X, aim.y * WISP_BEAM_MOUTH_Y - WISP_BEAM_MOUTH_DROP); + laser->Update(); + wisp.headFrameDelay = WISP_SHOT_HEAD_FRAMES; + wisp.PlayShootAnim(wisp_aim_direction(aim)); +} + +// Sulfur's wisp fires a short Brimstone beam of its own. +static void sulfur_wisp_fire(Entity_Familiar& wisp, Vector velocity) +{ + Vector aim = vector_normalized(velocity); + Entity_Laser* laser = wisp.FireBrimstone(vector_cardinal(aim), BRIMSTONE_BARE); + if (!laser) return; + + laser->maxDistance = SULFUR_LENGTH; + laser->posOffset = vector_make(aim.x * WISP_BEAM_MOUTH_X, aim.y * WISP_BEAM_MOUTH_Y - WISP_BEAM_MOUTH_DROP); + laser->SetCollisionDamage(wisp.GetMultiplier() * SULFUR_DAMAGE); + wisp.apply_baby_bender(*laser); + wisp.shot_owner_convert(laser); + laser->Update(); + laser->renderDepthOffset = std::copysign(SULFUR_DEPTH, laser->renderDepthOffset); + wisp.headFrameDelay = WISP_SHOT_HEAD_FRAMES; + wisp.PlayShootAnim(vector_to_direction(aim)); +} + +// Red Candle's and Urn of Souls' wisps throw a flame along their shot. +static void wisp_flame_throw(Entity_Familiar& wisp, Vector velocity, int effect, int frames) +{ + Vector throwVelocity = vector_add(vector_scale(vector_cardinal(velocity), CANDLE_FLAME_SPEED), velocity); + Entity_Effect* fire = wisp_effect_spawn(wisp, effect, throwVelocity, &wisp); + fire->SetCollisionDamage(wisp.wispScale * WISP_FLAME_DAMAGE); + fire->scale = CANDLE_FLAME_SCALE; + fire->timeout = frames; + fire->lifespan = frames; + fire->Update(); +} + +// The start of 004386f0 for the wisps that fire something other than a tear, or nothing: true when no tear follows. +// Free Lemonade's leaves creep with every other tear. +bool wisp_kind_fire(Entity_Familiar& wisp, Vector velocity) +{ + Entity_Player& player = *wisp.player; + switch (wisp.subtype) + { + case WISP_ROBO_BABY: wisp.fire_robo_baby_laser(velocity); return true; + case WISP_EXTRA_BRIMSTONE_SOUL: case WISP_DELIRIOUS_HAUNT: wisp_beam_fire(wisp, velocity); return true; + case WISP_DELIRIOUS_DUKE: + if (player.numBlueFlies < DUKE_FLY_LIMIT) player.AddBlueFlies(1, wisp.pos, nullptr); + return true; + case COLLECTIBLE_SULFUR: sulfur_wisp_fire(wisp, velocity); return true; + case COLLECTIBLE_RED_CANDLE: + wisp_flame_throw(wisp, velocity, EFFECT_RED_CANDLE_FLAME, RED_CANDLE_FLAME_FRAMES); + return true; + case COLLECTIBLE_URN_OF_SOULS: + if (Random() % URN_FLAME_CHANCE != 0) return false; + wisp_flame_throw(wisp, velocity, EFFECT_BLUE_FLAME, URN_FLAME_FRAMES); + return true; + case COLLECTIBLE_FREE_LEMONADE: + { + if ((++wisp.coins & 1) != 0) return false; + Entity_Effect* creep = lemon_creep_spawn(wisp, wisp.wispScale * LEMON_CREEP_DAMAGE); + creep->Update(); + creep->sprite.color = LEMON_CREEP_COLOR; + return false; + } + case COLLECTIBLE_YUCK_HEART: + if (Random() % YUCK_FLY_CHANCE != 0 || wisp.linkedEntity) return true; + if (Entity* fly = player.AddBlueFlies(1, wisp.pos, nullptr)) wisp.linkedEntity = fly; + return true; + } + return false; +} + +// Crystal Ball's wisp aims at the enemy ahead that is closest, weakest and most in line, leading it. +static void crystal_ball_aim(Entity_Familiar& wisp, WispTear& tear) +{ + float speed = vector_length(tear.velocity); + Vector ahead = vector_scale(tear.velocity, 1 / speed); + Entity* best = nullptr; + float bestScore = 0; + for (Entity* enemy : g_game->room->entityList.updateEL) + { + float distance = vector_length(vector_sub(enemy->pos, wisp.pos)); + if (!enemy->IsVulnerableEnemy(nullptr) || enemy->HasEntityFlags(FLAG_FRIENDLY) || enemy->isDead) continue; + + float alignment = vector_dot(ahead, vector_normalized(vector_sub(enemy->pos, wisp.pos))); + if (alignment < CRYSTAL_CONE) continue; + float score = alignment * CRYSTAL_ALIGN_WEIGHT + std::max(CRYSTAL_NEAR - distance, 0.0f) + + std::max(CRYSTAL_WEAK - enemy->health, 0.0f); + if (score <= bestScore) continue; + bestScore = score; + best = enemy; + } + if (!best) return; + + float lead = vector_length(vector_sub(wisp.pos, best->pos)) * CRYSTAL_LEAD; + Vector aimed = vector_sub(vector_add(best->pos, vector_scale(best->velocity, lead)), wisp.pos); + tear.velocity = vector_resized(aimed, speed); +} + +// Doctor's Remote's wisp lobs an explosive tear onto a spot near the remote's target, arcing to land there. +static void remote_wisp_lob(Entity_Familiar& wisp, WispTear& tear) +{ + Entity* target = remote_target(*wisp.player); + if (!target) return; + + Vector scatter = random_direction(); + Vector landing = vector_add(target->pos, vector_scale(scatter, random_unit() * REMOTE_SCATTER)); + tear.fallingAccel = REMOTE_FALLING_ACCEL; + tear.velocity = vector_scale(vector_sub(landing, wisp.pos), 1 / REMOTE_FLIGHT_FRAMES); + if (vector_length_squared(tear.velocity) > REMOTE_MAX_SPEED * REMOTE_MAX_SPEED) + tear.velocity = vector_resized(tear.velocity, REMOTE_MAX_SPEED); + tear.flags.set(TEAR_EXPLOSIVE); + tear.damage = tear.damage * REMOTE_DAMAGE_SCALE + REMOTE_DAMAGE_BONUS; + tear.scale *= REMOTE_TEAR_SCALE; + + float frames = vector_length(vector_sub(wisp.pos, landing)) / vector_length(tear.velocity); + float fall = std::max((std::pow(REMOTE_FALL_DRAG, frames) - 1) * REMOTE_FALL_SPAN, REMOTE_FALL_MIN); + tear.fallingSpeed = (REMOTE_LAUNCH_HEIGHT - (frames - fall) * REMOTE_LAUNCH_SLOPE) / fall; +} + +// Mom's Bottle of Pills' wisp sometimes fires its pill's effect: poison, ice, confusion, fire or a troll bomb. +static void pills_wisp_tear(Entity_Familiar& wisp, WispTear& tear) +{ + if (random_unit() >= PILL_EFFECT_CHANCE) return; + switch (wisp.coins) + { + case 1: tear.flags.set(TEAR_POISON); break; + case 2: tear.flags.set(TEAR_FREEZE); break; + case 3: tear.flags.set(TEAR_CONFUSION); break; + case 4: tear.flags.set(TEAR_BURN); break; + case 5: + { + uint32_t seed = wisp.dropRNG.Next(); + Vector direction = RandomVector(wisp.dropRNG.Next()); + float speed = wisp.dropRNG.RandomFloat() * WISP_BOMB_THROW_SPEED + WISP_BOMB_THROW_SPEED; + g_game->Spawn({.position = wisp.pos, + .velocity = vector_scale(direction, speed), + .type = ENTITY_BOMB, + .variant = BOMB_TROLL, + .seed = seed}) + ->Update(); + break; + } + } +} + +// 00633990 Monster Manual's random tear: half the time a tear kind and shape of its own, the shape sometimes with an +// effect, the likelier the higher its first draw. +static void monster_tear_pick(RNG& rng, WispTear& tear) +{ + float chance = rng.RandomFloat(); + uint32_t variant = rng.Next() % MONSTER_TEAR_VARIANTS.size(); + uint32_t shape = rng.Next() % MONSTER_TEAR_SHAPES.size(); + uint32_t status = rng.Next() % MONSTER_TEAR_STATUSES.size(); + if ((rng.Next() & 1) != 0) return; + + tear.variant = MONSTER_TEAR_VARIANTS[variant]; + tear.flags.reset(); + if (MONSTER_TEAR_SHAPES[shape] >= 0) tear.flags.set(MONSTER_TEAR_SHAPES[shape]); + bool isStatus = random_unit() < (chance + MONSTER_BONUS_BASE) * MONSTER_BONUS_SCALE; + if (isStatus && MONSTER_TEAR_STATUSES[status] >= 0) tear.flags.set(MONSTER_TEAR_STATUSES[status]); +} + +// Monster Manual's wisp fires its own random tears at a random speed, rise and strength. +static void monster_wisp_tear(Entity_Familiar& wisp, WispTear& tear) +{ + RNG rng{wisp.initSeed, 2, 21, 9}; + monster_tear_pick(rng, tear); + tear.flags.set(TEAR_SPECTRAL); + tear.damage *= rng.RandomFloat() * MONSTER_DAMAGE_SPREAD + MONSTER_DAMAGE_MIN; + tear.fallingAccel = 0; + tear.fallingSpeed = rng.RandomFloat() * MONSTER_FALL_SPREAD + MONSTER_FALL_MIN; + tear.color = wisp_flame_tear_color(wisp); + tear.velocity = vector_scale(tear.velocity, rng.RandomFloat() * MONSTER_SPEED_SPREAD + MONSTER_SPEED_MIN); +} + +// The spray of Scissors' and the Delirious Monstro's wisps: jittered, slowed, rising and of mixed sizes. +static void spray_wisp_tear(WispTear& tear) +{ + Vector jitter = random_direction(); + tear.velocity = vector_add(tear.velocity, vector_scale(jitter, random_unit() * SPRAY_JITTER)); + tear.fallingAccel = SPRAY_WISP_FALLING_ACCEL; + tear.velocity = vector_scale(tear.velocity, random_unit() * SPRAY_SPEED_SPREAD + SPRAY_SPEED_MIN); + float big = (float)(Random() & 1); + tear.scale *= random_unit() * SPRAY_SCALE_JITTER + big * SPRAY_SCALE_BIG + SPRAY_WISP_SCALE_MIN; + tear.fallingSpeed = -(random_unit() * SPRAY_RISE_SPREAD + SPRAY_RISE_MIN); +} + +// A tear colour's tint, and its offset unless kept. +static void tear_tint_set(ColorMod& color, const ColorMod& tint, bool isOffsetKept) +{ + std::copy(std::begin(tint._tint), std::end(tint._tint), color._tint); + if (!isOffsetKept) std::copy(std::begin(tint._offset), std::end(tint._offset), color._offset); +} + +// Undefined's wisp fires a random status tear, coloured to match, or a plain one. +static void undefined_wisp_tear(WispTear& tear) +{ + constexpr ColorMod CHARM_TINT = {{1, 0, 1, 1}, {0, 0, 0, 0}, {50 / 255.0f, 0, 0}}; + constexpr ColorMod CONFUSION_TINT = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + constexpr ColorMod FEAR_TINT = {{1, 1, 0.455f, 1}, {0, 0, 0, 0}, {0.169f, 0.145f, 0}}; + constexpr ColorMod FREEZE_TINT = {{1.25f, 0.05f, 0.15f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + constexpr ColorMod UNDEFINED_POISON_TINT = {{0.4f, 0.97f, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + constexpr ColorMod SLOW_TINT = {{2, 2, 2, 1}, {0, 0, 0, 0}, {50 / 255.0f, 50 / 255.0f, 50 / 255.0f}}; + constexpr float SHRINK_COLORIZE[4] = {0.3f, 0.4f, 1, 1.5f}; + + switch (Random() % UNDEFINED_EFFECTS) + { + case 1: + tear.flags.set(TEAR_BURN); + tear.variant = TEAR_FIRE_MIND; + break; + case 2: + tear.flags.set(TEAR_CHARM); + tear_tint_set(tear.color, CHARM_TINT, false); + break; + case 3: + tear.flags.set(TEAR_CONFUSION); + tear_tint_set(tear.color, CONFUSION_TINT, true); + break; + case 4: + tear.flags.set(TEAR_FEAR); + tear_tint_set(tear.color, FEAR_TINT, false); + break; + case 5: + tear.flags.set(TEAR_FREEZE); + tear_tint_set(tear.color, FREEZE_TINT, false); + break; + case 6: + tear.flags.set(TEAR_POISON); + tear_tint_set(tear.color, UNDEFINED_POISON_TINT, false); + break; + case 7: + tear.flags.set(TEAR_SLOW); + tear_tint_set(tear.color, SLOW_TINT, false); + break; + case 8: + tear.flags.set(TEAR_SHRINK); + std::copy(std::begin(SHRINK_COLORIZE), std::end(SHRINK_COLORIZE), tear.color._colorize); + break; + } +} + +// The middle of 004386f0: the wisps whose tears fly, look or hit their own way. +void wisp_kind_tear(Entity_Familiar& wisp, WispTear& tear) +{ + switch (wisp.subtype) + { + case COLLECTIBLE_CRYSTAL_BALL: crystal_ball_aim(wisp, tear); break; + case COLLECTIBLE_TAMMYS_HEAD: + tear.velocity = vector_rotated(tear.velocity, random_unit() * TAMMY_SPREAD - TAMMY_SPREAD / 2); + break; + case COLLECTIBLE_KAMIKAZE: tear.fallingSpeed = random_unit() + KAMIKAZE_FALL_MIN; break; + case COLLECTIBLE_BOBS_ROTTEN_HEAD: + tear.fallingAccel = BOB_FALLING_ACCEL; + tear.fallingSpeed = -(random_unit() + BOB_RISE_MIN); + break; + case COLLECTIBLE_DOCTORS_REMOTE: remote_wisp_lob(wisp, tear); break; + case COLLECTIBLE_LEMON_MISHAP: tear.fallingSpeed = LEMON_TEAR_FALL; break; + case COLLECTIBLE_MY_LITTLE_UNICORN: case COLLECTIBLE_UNICORN_STUMP: tear.color = wisp_flame_tear_color(wisp); break; + case COLLECTIBLE_MOMS_BOTTLE_OF_PILLS: + tear.color = wisp_flame_tear_color(wisp); + pills_wisp_tear(wisp, tear); + break; + case COLLECTIBLE_MONSTER_MANUAL: monster_wisp_tear(wisp, tear); break; + case COLLECTIBLE_SPRINKLER: wisp.coins++; break; + case COLLECTIBLE_WAVY_CAP: + { + TemporaryEffects& effects = wisp.player->temporaryEffects; + tear.damageMultiplier += (float)effects.GetCollectibleEffectNum(COLLECTIBLE_WAVY_CAP) * WAVY_CAP_STACK + + (float)effects.GetNullEffectNum(NULLITEM_WAVY_CAP_1) * WAVY_CAP_NULL_STACK; + tear.scale = std::sqrt(tear.damageMultiplier) * WAVY_CAP_ROOT + tear.damageMultiplier * WAVY_CAP_LINEAR + + WAVY_CAP_BASE; + break; + } + case COLLECTIBLE_LARYNX: + tear.damage *= (float)wisp.keys * LARYNX_DAMAGE; + tear.scale *= (float)wisp.keys * LARYNX_SCALE + 1; + break; + case COLLECTIBLE_SCISSORS: + tear.variant = TEAR_BLOOD; + spray_wisp_tear(tear); + break; + case WISP_DELIRIOUS_MONSTRO: spray_wisp_tear(tear); break; + case COLLECTIBLE_UNDEFINED: undefined_wisp_tear(tear); break; + case COLLECTIBLE_D8: + { + RNG rng{wisp.dropRNG._seed, 2, 7, 7}; + tear.damage += rng.RandomFloat() * 2 - 1; + break; + } + } +} + +// 00707840 Game::AddErasedEnemy: the Eraser erases an enemy's kind for the rest of the run, once. Dogma never is. +void erased_enemy_add(Entity& enemy) +{ + if (enemy.type == ENTITY_DOGMA) return; + + ErasedEnemy erased{.type = enemy.type, .subtype = enemy.subtype, .variant = enemy.variant}; + erased_enemy_id_fix(erased.type, erased.variant, erased.subtype); + std::vector& list = g_game->erasedEntities; + bool isKnown = std::ranges::any_of(list, [&](const ErasedEnemy& other) { + return other.type == erased.type && other.variant == erased.variant && other.subtype == erased.subtype; + }); + if (!isKnown) list.push_back(erased); +} + +// The Gamekid wisp's answer to a hit: the enemy behind it is scared and marked for its frames. +static void gamekid_wisp_hit(Entity_Familiar& wisp, const EntityRef& source) +{ + bool isShot = source.type < ENTITY_FIRST_ENEMY || source.type == ENTITY_EFFECT; + if (wisp.target || !isShot || !source.entity) return; + + Entity* shooter = source.entity->GetLastSpawner(); + if (!shooter->IsVulnerableEnemy(nullptr)) return; + shooter->AddFear(EntityRef(&wisp), GAMEKID_HIT_FEAR, false); + if (!shooter->HasEntityFlags(FLAG_FEAR)) return; + wisp.target = shooter; + wisp.counter = GAMEKID_TARGET_FRAMES; +} + +// The Eraser's wisp erases the kind of the enemy that hits it, every one in the room vanishing, then goes out. A +// boss is erased only once the hit would finish it. +static void eraser_wisp_hit(Entity_Familiar& wisp, const EntityRef& source) +{ + Entity* enemy = source.entity; + if (!enemy || !enemy->IsVulnerableEnemy(nullptr)) return; + if (enemy->IsBoss() && enemy->pendingDamage < enemy->health) return; + + erased_enemy_add(*enemy); + bool isErased = false; + for (Entity* entity : std::vector(g_game->room->entityList.updateEL.begin(), + g_game->room->entityList.updateEL.end())) + { + if (!entity_is_erased(*entity)) continue; + Entity::RemoveWithPoof(entity); + isErased = true; + } + if (isErased) familiar_sound_play(SOUND_PLOP); + wisp_die(wisp); +} + +// 0043a5e0's answers of the wisps that take hits their own way. +WispHit wisp_kind_hit(Entity_Familiar& wisp, float& damage, uint64_t damageFlags, const EntityRef& source) +{ + bool isEnemySource = source.type >= ENTITY_FIRST_ENEMY && source.type < ENTITY_EFFECT; + switch (wisp.subtype) + { + case COLLECTIBLE_CRACK_THE_SKY: + { + if (!isEnemySource) return WISP_HIT_TAKEN; + Entity_Effect* beam = wisp_effect_spawn(wisp, EFFECT_CRACK_THE_SKY, {}, &wisp); + beam->parent = wisp.player; + beam->SetCollisionDamage(CRACK_THE_SKY_DAMAGE); + beam->SetSize(CRACK_THE_SKY_SIZE, vector_make(-1, -1), -1); + beam->subtype = 1; + return WISP_HIT_TAKEN; + } + case COLLECTIBLE_KAMIKAZE: + if (damageFlags & DAMAGE_EXPLOSION) return WISP_HIT_BLOCKED; + if (source.entity && source.entity->IsEnemy()) damage *= KAMIKAZE_HIT_MULTIPLIER; + return WISP_HIT_TAKEN; + case COLLECTIBLE_BOOK_OF_SHADOWS: + return source.type < ENTITY_FIRST_ENEMY || source.type == ENTITY_EFFECT ? WISP_HIT_BLOCKED : WISP_HIT_TAKEN; + case COLLECTIBLE_GAMEKID: gamekid_wisp_hit(wisp, source); return WISP_HIT_TAKEN; + case COLLECTIBLE_FORGET_ME_NOW: case COLLECTIBLE_VENGEFUL_SPIRIT: return WISP_HIT_BLOCKED; + case COLLECTIBLE_ERASER: eraser_wisp_hit(wisp, source); return WISP_HIT_BLOCKED; + case COLLECTIBLE_PLUM_FLUTE: return wisp.state == WISP_BUSY_STATE ? WISP_HIT_BLOCKED : WISP_HIT_TAKEN; + } + return WISP_HIT_SHARED; +} + +// An active used for its effect alone, as a dying wisp uses its item. +static void wisp_item_use(Entity_Player& player, int item) +{ + player.UseActiveItem({.item = item, .flags = USE_NOANIM | USE_ALLOWNONMAIN, .slot = ACTIVE_SLOT_NONE}); +} + +// Mr. Boom's and the Anarchist Cookbook's wisps leave a lit bomb thrown a little way (a troll bomb for the cookbook), +// Mr. Boom's small and homing. +static void bomb_wisp_death(Entity_Familiar& wisp) +{ + uint32_t seed = wisp.dropRNG.Next(); + Vector direction = RandomVector(wisp.dropRNG.Next()); + float speed = wisp.dropRNG.RandomFloat() * WISP_BOMB_THROW_SPEED + WISP_BOMB_THROW_SPEED; + bool isBoom = wisp.subtype == COLLECTIBLE_MR_BOOM; + auto* bomb = static_cast(g_game->Spawn({.position = wisp.pos, + .velocity = vector_scale(direction, speed), + .spawner = wisp.player, + .type = ENTITY_BOMB, + .variant = isBoom ? BOMB_NORMAL : BOMB_TROLL, + .seed = seed})); + TearFlags flags = wisp.player->GetBombFlags(false); + if (isBoom) flags.set(TEAR_HOMING); + bomb->isLoadCostumes = true; + bomb->tearFlags = flags; + if (isBoom) + { + bomb->scale = MR_BOOM_WISP_SCALE; + bomb->radiusMultiplier = MR_BOOM_RADIUS; + bomb->posOffset = vector_make(0, MR_BOOM_HEIGHT); + bomb->fallSpeed = MR_BOOM_FALL - random_unit() * MR_BOOM_FALL_SPREAD; + } + bomb->flags |= FLAG_NO_KNOCKBACK; + bomb->Update(); +} + +// Deck of Cards' and the Clear Rune's wisps leave a card or a rune. +static void card_wisp_death(Entity_Familiar& wisp, bool isRune) +{ + uint32_t seed = wisp.dropRNG.Next(); + int card = isRune ? ItemPool::GetCardEx((int)seed, 0, 1, 0, true) + : ItemPool::GetCardEx((int)seed, DECK_SPECIAL_CHANCE, 0, DECK_SUIT_CHANCE, true); + RNG cardRng{seed, 5, 9, 7}; + card = lua_engine_get().GetCard( + {.rng = &cardRng, .card = card, .isOnlyRunes = isRune, .isPlaying = !isRune, .isRunes = isRune}); + wisp_pickup_spawn(wisp, PICKUP_TAROTCARD, card, PICKUP_SPOT_STEP); +} + +// The Head of Krampus' wisp lets out a cross of short beams, as strong as its tears. +static void krampus_wisp_death(Entity_Familiar& wisp) +{ + WispEntry& config = *wisp_config(wisp); + float damage = wisp_base_damage(config); + for (int i = 0; i < KRAMPUS_BEAMS; i++) + { + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = wisp.pos, + .posOffset = wisp.posOffset, + .source = &wisp, + .angleDegrees = (float)i * KRAMPUS_TURN, + .timeout = KRAMPUS_WISP_TIMEOUT, + .variant = LASER_THICK_RED}); + laser->isDisableFollowParent = true; + laser->SetCollisionDamage(damage * config.tears.damageMultiplier); + laser->scale = KRAMPUS_SCALE; + laser->ResetSpriteScale(); + laser->Update(); + } +} + +// Book of the Dead's wisp raises a charmed bony (black one time in three) twice as tough, which keeps no door shut. +static void dead_wisp_death(Entity_Familiar& wisp) +{ + uint32_t seed = Random(); + Vector spot = pickup_spot(wisp.pos, 0); + int type = wisp.dropRNG.Next() % BLACK_BONY_CHANCE == 0 ? ENTITY_BLACK_BONY : ENTITY_BONY; + auto* bony = dynamic_cast( + g_game->Spawn({.position = spot, .spawner = wisp.player, .type = type, .seed = seed})); + if (!bony) return; + + bony->AddCharmed(EntityRef(), -1, false, false); + bony->Update(); + bony->isCanShutDoors = false; + bony->maxHitPoints += bony->maxHitPoints; + bony->health = bony->maxHitPoints; + familiar_sound_play(SOUND_SUMMONSOUND); +} + +// Mega Bean's wisp lets out a big fart that freezes the enemies around it. +static void mega_bean_wisp_death(Entity_Familiar& wisp) +{ + Entity_Player* player = wisp.player; + game_fart({.position = wisp.pos, .source = player, .radius = MEGA_BEAN_WISP_FART_RADIUS, .scale = MEGA_BEAN_WISP_FART_SCALE}); + game_butter_bean_fart( + {.position = wisp.pos, .source = player, .radius = MEGA_BEAN_WISP_PUSH_RADIUS, .isShowEffect = false}); + for (Entity* enemy : entity_query_radius(wisp.pos, MEGA_BEAN_FREEZE_RADIUS, QUERY_ENEMIES)) + if (enemy->IsVulnerableEnemy(nullptr)) enemy->AddFreeze(EntityRef(player), MEGA_BEAN_FREEZE, false); +} + +// Crooked Penny's wisp doubles every wisp half the time and puts every wisp out the other half. +static void crooked_penny_wisp_death(Entity_Familiar& wisp) +{ + static bool isRunning = false; + if (isRunning) return; + + isRunning = true; + bool isDoubled = wisp.dropRNG.RandomInt(2) == 0; + for (Entity* other : entity_query(ENTITY_FAMILIAR, Entity_Familiar::WISP)) + { + if (!isDoubled) wisp_die(*other); + else if (!other->isDead) wisp.player->AddWisp(other->subtype, wisp.player->pos, false, false); + } + isRunning = false; +} + +// Glass Cannon's wisp shatters every other Glass Cannon wisp with it. +static void glass_cannon_wisp_death() +{ + static bool isRunning = false; + if (isRunning) return; + + isRunning = true; + for (Entity* other : entity_query(ENTITY_FAMILIAR, Entity_Familiar::WISP)) + if (other->subtype == COLLECTIBLE_GLASS_CANNON && !other->isDead) wisp_die(*other); + isRunning = false; +} + +// The part of 00436fd0 for the wisps that leave something behind as they go out. False when the wisp comes back as +// another instead (D7's and the fly wisps, one size smaller). +bool wisp_kind_death(Entity_Familiar& wisp) +{ + Entity_Player& player = *wisp.player; + switch (wisp.subtype) + { + case COLLECTIBLE_NECRONOMICON: wisp_item_use(player, COLLECTIBLE_NECRONOMICON); break; + case COLLECTIBLE_MR_BOOM: case COLLECTIBLE_ANARCHIST_COOKBOOK: bomb_wisp_death(wisp); break; + case COLLECTIBLE_KAMIKAZE: kamikaze_blast(wisp); break; + case COLLECTIBLE_HOURGLASS: + { + Room& room = *g_game->room; + TemporaryEffect slowdown; + slowdown.item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_HOURGLASS); + slowdown.cooldown = HOURGLASS_SLOW_FRAMES; + room.temporaryEffects.AddEffect(slowdown, true, 1); + g_manager->musicManager.targetPitch = room.time_scale_update(); + break; + } + case COLLECTIBLE_BOOK_OF_REVELATIONS: + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_7_SEALS, true, 1); + g_game->Spawn({.position = wisp.pos, + .spawner = &player, + .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::LIL_HARBINGERS, + .seed = Random()}) + ->Update(); + player.EvaluateItems(); + familiar_sound_play(SOUND_SUMMONSOUND); + break; + case COLLECTIBLE_DECK_OF_CARDS: card_wisp_death(wisp, false); break; + case COLLECTIBLE_CLEAR_RUNE: card_wisp_death(wisp, true); break; + case COLLECTIBLE_MOMS_BOTTLE_OF_PILLS: + wisp_pickup_spawn(wisp, PICKUP_PILL, 0, PICKUP_SPOT_STEP); + if (wisp.coins == PILL_SPIDER_WISP) Entity_NPC::ThrowSpider(wisp.pos, nullptr, {}, false, PILL_SPIDER_HEIGHT); + break; + case COLLECTIBLE_BEAN: + game_fart({.position = wisp.pos, .source = &wisp, .radius = BEAN_WISP_FART_RADIUS}); + game_butter_bean_fart({.position = wisp.pos, .source = &player, .radius = BEAN_WISP_PUSH_RADIUS, .isShowEffect = false}); + break; + case COLLECTIBLE_GUPPYS_HEAD: + if (auto* fly = static_cast(player.AddBlueFlies(1, wisp.pos, nullptr))) + { + fly->state = GUPPY_FLY_STATE; + Vector direction = random_direction(); + fly->entityCollisionClass = ENTCOLL_NONE; + fly->velocity = vector_scale(direction, random_unit() * GUPPY_FLY_SPEED); + } + break; + case COLLECTIBLE_BOOK_OF_SECRETS: player.trigger_cracked_orb(wisp.pos); break; + case COLLECTIBLE_BOX_OF_SPIDERS: + { + Vector direction = random_direction(); + float reach = random_unit() * SPIDER_THROW_RANGE + SPIDER_THROW_MIN; + Vector aim = vector_add(wisp.pos, vector_scale(direction, reach)); + player.ThrowBlueSpider(wisp.pos, pickup_spot(aim, SPIDER_THROW_MIN)); + break; + } + case COLLECTIBLE_THE_JAR: + if (wisp.dropRNG.RandomFloat() >= JAR_HEART_CHANCE) break; + KAGE_LogMessage(LOG_INFO, (uint8_t*)"Spawn heart!"); + static_cast(wisp_pickup_spawn(wisp, PICKUP_HEART, HEART_HALF, 0))->wait = JAR_HEART_WAIT; + break; + case COLLECTIBLE_HEAD_OF_KRAMPUS: krampus_wisp_death(wisp); break; + case COLLECTIBLE_MAGIC_FINGERS: + if (wisp.dropRNG.RandomInt(MAGIC_FINGERS_COIN_CHANCE) == 0) wisp_pickup_spawn(wisp, PICKUP_COIN, 0, 0); + break; + case COLLECTIBLE_PLACEBO: + // Only Acid Baby and Lil Spewer answer the Placebo, so only they are asked. + for (Entity* entity : entity_query(ENTITY_FAMILIAR, -1)) + { + auto* familiar = static_cast(entity); + bool isAnswering = familiar->variant == Entity_Familiar::ACID_BABY || + familiar->variant == Entity_Familiar::LIL_SPEWER; + if (familiar->player == &player && isAnswering) familiar->farting_baby_fart(); + } + wisp_pickup_spawn(wisp, PICKUP_PILL, 0, 0); + break; + case COLLECTIBLE_WOODEN_NICKEL: + if (wisp.dropRNG.RandomInt(2) == 0) wisp_pickup_spawn(wisp, PICKUP_COIN, 0, PICKUP_SPOT_STEP); + break; + case COLLECTIBLE_MEGA_BEAN: mega_bean_wisp_death(wisp); break; + case COLLECTIBLE_GLASS_CANNON: glass_cannon_wisp_death(); break; + case COLLECTIBLE_TEAR_DETONATOR: + { + wisp_item_use(player, COLLECTIBLE_TEAR_DETONATOR); + float turn = random_unit() * WISP_FULL_TURN - WISP_FULL_TURN / 2; + for (float angle = 0; angle < WISP_FULL_TURN; angle += DETONATOR_WISP_STEP) + { + Vector velocity = vector_scale(vector_from_angle(angle + turn), player.shotSpeed * DETONATOR_WISP_SPEED); + player.FireTear({wisp.pos, velocity}, TEAR_FIRE_EXTRA_SHOT, nullptr, 1)->targetPosition = wisp.pos; + } + break; + } + case COLLECTIBLE_VENTRICLE_RAZOR: + if (Entity* portal = wisp.parent) + { + VentricleRazorPortal& kept = g_game->ventricleRazorPortals[std::clamp(portal->subtype, 0, 1)]; + kept.roomIndex = g_game->currentRoomIdx; + kept.isMarked = false; + } + break; + case COLLECTIBLE_KIDNEY_BEAN: game_charm_fart(wisp.pos, KIDNEY_BEAN_RADIUS, &wisp); break; + case COLLECTIBLE_D7: + wisp_item_use(player, COLLECTIBLE_D7); + wisp_morph(wisp, wisp.subtype - 1); + wisp.health = wisp.maxHitPoints; + return false; + case COLLECTIBLE_PAUSE: g_game->room->SetPauseTimer(PAUSE_WISP_FRAMES); break; + case COLLECTIBLE_SMELTER: + if ((Random() & (SMELTER_TRINKET_CHANCE - 1)) == 0) wisp_pickup_spawn(wisp, PICKUP_TRINKET, 0, 0); + break; + case COLLECTIBLE_MAMA_MEGA: + { + uint32_t seed = Random(); + g_game->Spawn({.position = pickup_spot(wisp.pos, 0), + .spawner = &wisp, + .type = ENTITY_BOMB, + .variant = BOMB_GOLDENTROLL, + .seed = seed}); + break; + } + case COLLECTIBLE_WAIT_WHAT: + { + Entity_Effect* wave = wisp_effect_spawn(wisp, EFFECT_SHOCKWAVE, {}, &player); + wave->parent = &player; + wave->minRadius = wisp.size; + wave->maxRadius = WAIT_WHAT_WISP_RADIUS; + wave->timeout = WAIT_WHAT_FRAMES; + wave->lifespan = WAIT_WHAT_FRAMES; + [[fallthrough]]; + } + case COLLECTIBLE_BUTTER_BEAN: + game_butter_bean_fart( + {.position = wisp.pos, .source = &player, .radius = BUTTER_BEAN_RADIUS, .isSuperKnockback = true}); + break; + case COLLECTIBLE_CROOKED_PENNY: crooked_penny_wisp_death(wisp); break; + case COLLECTIBLE_MOVING_BOX: wisp_pickup_spawn(wisp, PICKUP_NULL, MOVING_BOX_PICKUP, 0); break; + case COLLECTIBLE_BOOK_OF_THE_DEAD: dead_wisp_death(wisp); break; + case WISP_FLY_SMALLEST + 1: case WISP_FLY_SMALLEST + 2: case WISP_FLY_SMALLEST + 3: case WISP_FLY_LARGEST: + wisp_morph(wisp, wisp.subtype - 1); + wisp.health = wisp.maxHitPoints; + return false; + } + return true; +} + +// Whether Mr. Me!'s wisp's rock still stands. +static bool mr_me_rock_standing(Entity_Familiar& wisp) +{ + Room& room = *g_game->room; + GridEntity* rock = (uint32_t)wisp.coins < ROOM_GRID_CELLS ? room.gridEntities[wisp.coins] : nullptr; + return rock && rock->state != ROCK_STATE_BROKEN; +} + +// Part of 0043db20: the first errand the room offers, in order: its tinted rock, the last closed locked chest, the +// last hidden secret door, the last other locked door (in co-op online not the one just come through). +static void mr_me_errand_find(Entity_Familiar& wisp) +{ + Room& room = *g_game->room; + int rockIndex = room.tintedRockIdx; + GridEntity* rock = rockIndex >= 0 && rockIndex < ROOM_GRID_CELLS ? room.gridEntities[rockIndex] : nullptr; + if (rock && (rock->type == GRID_ROCKT || rock->type == GRID_ROCK_SS) && rock->state != ROCK_STATE_BROKEN) + { + wisp.keys = MR_ME_ROCK; + wisp.coins = rockIndex; + wisp.targetPosition = room.GetGridPosition(rockIndex); + } + if (wisp.keys == MR_ME_IDLE) + { + for (Entity* chest : entity_query(ENTITY_PICKUP, PICKUP_LOCKEDCHEST)) + { + if (chest->subtype == 0) continue; + wisp.target = chest; + wisp.keys = MR_ME_CHEST; + wisp.targetPosition = chest->pos; + } + } + for (int errand : {MR_ME_SECRET_DOOR, MR_ME_DOOR}) + { + for (int slot = 0; wisp.keys == MR_ME_IDLE && slot < DOOR_SLOT_COUNT; slot++) + { + GridEntity_Door* door = room.doors[slot]; + if (!door || (door->doorFlags & (DOOR_FLAG_MIRROR | DOOR_FLAG_PHOTO))) continue; + if ((door->doorFlags & DOOR_FLAG_MINESHAFT) && door->variant == DOOR_LOCKED_BARRED) continue; + if (door->get_secret_exit_kind() == SECRET_EXIT_MOMS_HEART || door->state == DOOR_STATE_OPEN) continue; + bool isSecret = door->targetRoomType == ROOM_SECRET || door->targetRoomType == ROOM_SUPERSECRET; + if (isSecret != (errand == MR_ME_SECRET_DOOR)) continue; + bool isJustLeft = door->targetRoomIdx == g_game->lastRoomIdx && g_manager->netplayManager.is_online() && + door->updateCount <= DOOR_RETURN_FRAMES; + if (errand == MR_ME_DOOR && isJustLeft) continue; + wisp.keys = errand; + wisp.coins = slot; + wisp.targetPosition = room.GetGridPosition(door->gridIndex); + } + } +} + +// Part of 0043db20: an errand whose rock is gone, chest opened, door opened or target dead is dropped, and the +// wisp stops when it has none. +static void mr_me_errand_check(Entity_Familiar& wisp) +{ + Entity* target = wisp.target; + if (wisp.keys == MR_ME_ROCK && !mr_me_rock_standing(wisp)) wisp.keys = MR_ME_IDLE; + else if (wisp.keys != MR_ME_ROCK) + { + bool isDone = false; + if (wisp.keys == MR_ME_CHEST) isDone = !target || target->type != ENTITY_PICKUP || target->subtype != 1; + if (wisp.keys == MR_ME_SECRET_DOOR || wisp.keys == MR_ME_DOOR) + isDone = g_game->room->doors[wisp.coins]->state == DOOR_STATE_OPEN; + if (isDone || (target && (!target->isExists || target->isDead))) wisp.keys = MR_ME_IDLE; + } + if (wisp.keys == MR_ME_IDLE) wisp.velocity = {}; +} + +// Part of 0043db20: Mr. Me!'s wisp at its errand. It blows up its rock once no player stands near, opens its +// chest, bombs its secret door open or unlocks its door, going out, then rests. +static void mr_me_errand_run(Entity_Familiar& wisp) +{ + switch (wisp.keys) + { + case MR_ME_CHEST: + { + Entity* chest = wisp.target; + if (chest && chest->type == ENTITY_PICKUP && chest->subtype != 0 && + static_cast(chest)->TryOpenChest(nullptr)) + wisp_die(wisp); + break; + } + case MR_ME_ROCK: + { + if (!mr_me_rock_standing(wisp)) break; + Entity_Player* nearest = game_nearest_player(wisp.pos); + if (vector_length(vector_sub(wisp.pos, nearest->pos)) > MR_ME_SAFE_DISTANCE) + { + explosion_damage( + {.position = wisp.pos, .source = &wisp, .damage = MR_ME_BLAST_DAMAGE, .radius = MR_ME_BLAST_RADIUS}); + wisp_effect_spawn(wisp, EFFECT_BOMB_EXPLOSION, {}, nullptr)->Update(); + wisp_die(wisp); + } + return mr_me_errand_check(wisp); + } + case MR_ME_SECRET_DOOR: case MR_ME_DOOR: + { + GridEntity_Door* door = g_game->room->doors[wisp.coins]; + if (door->state == DOOR_STATE_OPEN) break; + if (wisp.keys == MR_ME_SECRET_DOOR) door->TryBlowOpen(false, nullptr); + else if (!door->TryUnlock(*wisp.player, true)) door->Open(); + wisp_die(wisp); + break; + } + default: return mr_me_errand_check(wisp); + } + wisp.keys = MR_ME_IDLE; + wisp.velocity = {}; +} + +// 0043db20 Mr. Me!'s wisp, once the room is clear, looks every fifteen frames for an errand: a tinted rock, a locked +// chest, a hidden secret door, then any other locked door. It flies there and blows up the rock (away from the +// players), opens the chest, bombs the door open or unlocks it, going out each time. Idle, it drifts back to its ring. +void Entity_Familiar::ai_mr_me_wisp() +{ + if (keys == MR_ME_IDLE) + { + if (!IsFrame(MR_ME_SEARCH_INTERVAL, (int)index) || !room_is_clear()) return; + mr_me_errand_find(*this); + if (keys != MR_ME_IDLE) + { + if (orbitLayer < 0) return; + RecalculateOrbitOffset(orbitLayer, ORBIT_LEAVE); + orbitLayer = -1; + return; + } + if (orbitLayer >= 0) + { + friction = 1; + return; + } + + int ring = wisp_config(*this)->layer + WISP_RING_OFFSET; + friction = MR_ME_FRICTION; + Vector home = GetOrbitDistance(ring); + Vector toPlayer = vector_sub(player->pos, pos); + if (vector_length(toPlayer) < home.x) return AddToOrbit(ring); + velocity = vector_add(velocity, vector_scale(vector_resized(toPlayer, MR_ME_SPEED), speedMultiplier / MR_ME_FRICTION)); + return; + } + + friction = MR_ME_FRICTION; + Vector goal = target ? target->pos : targetPosition; + Vector toGoal = vector_sub(goal, pos); + if (vector_length_squared(toGoal) > MR_ME_REACH_SQUARED) + { + velocity = vector_add(velocity, vector_scale(vector_resized(toGoal, MR_ME_SPEED), speedMultiplier / MR_ME_FRICTION)); + mr_me_errand_check(*this); + } + else mr_me_errand_run(*this); +} + +// 0043e4a0 Mega Blast's wisp charges while its player shoots and lets out a beam of its own on release, and joins its +// player's Mega Blast with a beam pointing away from them, turning with it. A mark aims its own beam. +void Entity_Familiar::ai_mega_blast_wisp() +{ + int direction = player->fireDirection; + if (vector_length(player->aimDirection) < MEGA_BLAST_AIM_DEADZONE && !player->areOpposingShootDirectionsPressed) + direction = DIRECTION_NONE; + Vector aim = direction_unit(lastDirection); + if (TryAimAtMarkedTarget(aim, lastDirection, nullptr)) + { + if (fireCooldown < 0) direction = DIRECTION_NONE; + Entity* beam = linkedEntity; + bool isTurnable = beam && beam->type == ENTITY_LASER && beam->variant != LASER_THICK_RED && + beam->variant != LASER_THIN_RED && beam->variant != LASER_SHOOP; + if (isTurnable) static_cast(beam)->RotateToAngle(vector_angle(aim), MEGA_BLAST_TURN_SPEED); + } + + if (CanPlayerFire()) + { + if (direction == DIRECTION_NONE) + { + Entity_Laser* laser = fireCooldown < 0 && !vector_is_zero(aim) && !linkedEntity + ? FireBrimstone(aim, BRIMSTONE_BARE) + : nullptr; + if (laser) + { + laser->posOffset = vector_make(aim.x * WISP_BEAM_MOUTH_X, aim.y * WISP_BEAM_MOUTH_Y - WISP_BEAM_MOUTH_DROP); + laser->Update(); + headFrameDelay = WISP_SHOT_HEAD_FRAMES; + PlayShootAnim(vector_to_direction(aim)); + } + fireCooldown = MEGA_BLAST_CHARGE_FRAMES; + } + else + { + if (headFrameDelay <= MEGA_BLAST_HEAD_FLOAT) fireCooldown--; + lastDirection = direction; + } + if (headFrameDelay > MEGA_BLAST_HEAD_FLOAT) headFrameDelay--; + else + { + if (direction == DIRECTION_NONE) PlayFloatAnim(player->headDirection); + else PlayChargeAnim(lastDirection); + headFrameDelay = MEGA_BLAST_HEAD_FLOAT; + } + } + + Vector away = vector_normalized(vector_sub(pos, player->pos)); + Vector mouth = vector_make(away.x * WISP_BEAM_MOUTH_X, away.y * WISP_BEAM_MOUTH_Y - WISP_BEAM_MOUTH_DROP); + if (player->megaBlastDuration > 0 && !linkedEntity) + { + if (Entity_Laser* laser = FireBrimstone(away, BRIMSTONE_OWN)) + { + laser->posOffset = mouth; + laser->timeout = player->megaBlastDuration; + laser->Update(); + linkedEntity = laser; + headFrameDelay = WISP_SHOT_HEAD_FRAMES; + PlayShootAnim(direction); + } + } + auto* laser = static_cast(linkedEntity.get()); + if (!laser) return; + + float angle = vector_angle(away); + laser->isActiveRotating = true; + laser->rotationDelay = 0; + laser->rotationDegrees = angle_difference(laser->angleDegrees, angle); + laser->rotationSpd = laser->rotationDegrees < 0 ? -std::fabs(angle) : std::fabs(angle); + laser->renderDepthOffset = away.y < MEGA_BLAST_BEHIND_Y ? MEGA_BLAST_DEPTH_BEHIND : MEGA_BLAST_DEPTH_FRONT; + laser->posOffset = mouth; +} diff --git a/src/fx_layers.cpp b/src/fx_layers.cpp index aee45bd..3a383e2 100644 --- a/src/fx_layers.cpp +++ b/src/fx_layers.cpp @@ -1,6 +1,7 @@ #include "fx_layers.h" #include "data.h" #include "entity_effect.h" +#include "entity_player.h" #include "game.h" #include "log.h" #include "manager.h" @@ -31,14 +32,6 @@ constexpr uint32_t ROOM_RNG_SHIFT = 35; constexpr uint32_t FX_RNG_SHIFT = 13; constexpr uint32_t DELETE_THIS_RNG_SHIFT = 14; -// The room's play area on screen: world units from its corner shrink by ROOM_SCREEN_SCALE into a centered view. -constexpr float ROOM_ORIGIN_X = 60; -constexpr float ROOM_ORIGIN_Y = 140; -constexpr float ROOM_SCREEN_SCALE = 0.65f; -constexpr float ROOM_VIEW_HEIGHT = 182; -constexpr float ROOM_VIEW_WIDTH = 338; -constexpr float HALF = 0.5f; -constexpr KColor WHITE = kcolor_rgba(1, 1, 1, 1); // The color an image draw takes to keep its quad's own colors. constexpr KColor COLOR_UNSET = kcolor_rgba(-1, -1, -1, -1); @@ -56,7 +49,6 @@ constexpr int GREED_STAGE_SHEOL = 5; constexpr int DELETE_THIS_STAGES = 11; constexpr int STAGE_TYPE_COUNT = 5; constexpr uint32_t CURSE_DARKNESS = 1; -constexpr uint32_t CHALLENGE_DELETE_THIS = 45; // A normal room shows its floor's light rays one time in RAY_ODDS (in RAY_ODDS_CHAPTER_ONE on the first chapter). constexpr uint32_t RAY_ODDS = 2; @@ -105,7 +97,6 @@ constexpr float VEIN_ALPHA_MIN = 0.3f; constexpr float VEIN_ALPHA_RANGE = 0.7f; constexpr int VEIN_DEPTH_MAX = 4; -constexpr float FULL_TURN = 360; constexpr float HALF_TURN = 180; constexpr float QUARTER_TURN = 90; @@ -263,9 +254,9 @@ static Vector room_center_get(const FXLayers& fx) // An angle in degrees brought into -180 to 180, the game's way: past a full turn it is taken modulo one first. static float angle_wrap(float angle) { - if (std::abs(angle) > FULL_TURN) angle = std::fmod(angle, FULL_TURN); - if (angle > HALF_TURN) return angle - FULL_TURN; - return angle < -HALF_TURN ? angle + FULL_TURN : angle; + if (std::abs(angle) > FULL_TURN_DEGREES) angle = std::fmod(angle, FULL_TURN_DEGREES); + if (angle > HALF_TURN) return angle - FULL_TURN_DEGREES; + return angle < -HALF_TURN ? angle + FULL_TURN_DEGREES : angle; } // Whether something turned by angle at position points to target's side of it. diff --git a/src/fx_layers.h b/src/fx_layers.h index 1a9a81c..79cb757 100644 --- a/src/fx_layers.h +++ b/src/fx_layers.h @@ -50,6 +50,20 @@ constexpr KColor kcolor_rgba(float red, float green, float blue, float alpha) return color; } +// The room's screen frame: the top-left of its floor, the scale its view is drawn at, and the view's size. +constexpr float ROOM_ORIGIN_X = 60; +constexpr float ROOM_ORIGIN_Y = 140; +constexpr float ROOM_SCREEN_SCALE = 0.65f; +constexpr float ROOM_VIEW_HEIGHT = 182; +constexpr float ROOM_VIEW_WIDTH = 338; + +constexpr KColor WHITE = kcolor_rgba(1, 1, 1, 1); +constexpr KColor BLACK = kcolor_rgba(0, 0, 0, 1); +constexpr uint32_t WHITE_ARGB = 0xffffffff; +constexpr uint32_t BLACK_ARGB = 0xff000000; +constexpr uint32_t CLEAR_ARGB = 0; +constexpr uint32_t TEXT_ARGB = 0xff362f2d; + // Construction (0098f720), assignment (009937b0) and destruction are the defaults. // How a stage's rooms look (REPENTOGON's FXParams), from fxlayers.xml's fxParams: the color grading, water and shadows. // Without one a room is ungraded, with dark see-through water, dark blue shadows and a soft white light. diff --git a/src/game.cpp b/src/game.cpp index 746bcb7..678f734 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -1,6 +1,7 @@ #include "game.h" #include "data.h" #include "entity_player.h" +#include "level.h" #include "log.h" #include "manager.h" #include "lua_engine.h" @@ -39,13 +40,11 @@ constexpr int FILTER_LINEAR = 1; constexpr int BLOOM_DURATION_DEFAULT = 30; constexpr int REVIVE_MACHINE_COINS = 10; constexpr float DIZZY_CHANGE_SPEED_DEFAULT = 0.001f; -constexpr int BOSS_RUSH_PAR_TIME = 36000; constexpr int BLUE_WOMB_PAR_TIME = 54000; constexpr float COLOR_CHANNEL_MAX = 255; // The attributes of a giant book layer's tint channels. constexpr std::array TINT_ATTRIBUTES = {"r", "g", "b", "a"}; -constexpr int DIMENSION_DEATH_CERTIFICATE = 2; // The fortune generator's xorshift (shift index 35), the start's fade in speed, and the cover an instant fade starts on. constexpr uint32_t FORTUNE_RNG_SHIFT = 35; constexpr float START_FADE_SPEED = 0.04f; @@ -865,7 +864,7 @@ bool Game::IsGreedMode() int Game::GetStageID() { if (g_game->challenge == CHALLENGE_RED_REDEMPTION) - reconstruction_missing("Game::GetStageID 00738470: Level::GetRoomStageType 0074f690 on Game's room list"); + return RoomConfig::GetStageID(stage, GetRoomStageType(currentRoomIdx), ROOM_MODE_CURRENT); if (currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE) return STAGE_ID_HOME; return RoomConfig::GetStageID(stage, stageType, ROOM_MODE_CURRENT); } diff --git a/src/game_restore.cpp b/src/game_restore.cpp index 6837bf4..a79a4be 100644 --- a/src/game_restore.cpp +++ b/src/game_restore.cpp @@ -14,12 +14,8 @@ #include #include -constexpr uint32_t ROOM_REF_MERGED = 0x80000000; -constexpr uint32_t ROOM_REF_MIRRORED = 0x40000000; constexpr uint32_t ROOM_REF_STAGE_MASK = 0xffff; constexpr uint32_t ROOM_REF_HALF_MASK = 0xffff; -constexpr int ROOM_REF_MODE_SHIFT = 16; -constexpr int ROOM_REF_HALF_SHIFT = 16; constexpr uint32_t ROOM_REF_MODE_MASK = 0xff; constexpr uint32_t PLAYER_RNG_SHIFT = 34; diff --git a/src/game_save.cpp b/src/game_save.cpp index e58b1d6..0a8d7af 100644 --- a/src/game_save.cpp +++ b/src/game_save.cpp @@ -1,4 +1,5 @@ #include "game.h" +#include "entity_player.h" #include "game_state_player.h" #include "entity_familiar.h" #include "entity_npc.h" @@ -8,16 +9,10 @@ #include "room.h" #include -constexpr int CHALLENGE_SPEED = 22; constexpr int CHARGER_MY_SHADOW = 1; constexpr int FAMILIAR_UMBILICAL_BABY = 240; constexpr int REWIND_DOOR_FRAMES = 15; -constexpr int ROOM_REF_MODE_SHIFT = 16; -constexpr int ROOM_REF_HALF_SHIFT = 16; constexpr uint32_t ROOM_FLAG_SAVED = 0x40; -constexpr uint32_t ROOM_REF_FLAGGED = 0x20000000; -constexpr uint32_t ROOM_REF_MIRRORED = 0x40000000; -constexpr uint32_t ROOM_REF_MERGED = 0x80000000; // The versus rules each kind of match plays, as its slot 1 answers. static const std::array, DEATHMATCH_VENOM> DEATHMATCH_TYPE_RULES = {{ @@ -303,7 +298,7 @@ static CoPlayerState co_player_save(Entity_Player& player) } // 006d0370 A charmed enemy as a player keeps it: its kind, champion and health, and whether a player controls it. -static EntityDesc charmed_enemy_save(Entity_NPC& npc) +EntityDesc charmed_enemy_save(Entity_NPC& npc) { return {.health = npc.health, .maxHealth = npc.maxHitPoints, diff --git a/src/game_state.h b/src/game_state.h index 165aec3..4fbede9 100644 --- a/src/game_state.h +++ b/src/game_state.h @@ -36,6 +36,13 @@ struct ErasedEnemy int variant = 0; }; +// A saved room config's packed first word: the stage in its low half, the mode above it, and the flags at the top. +constexpr uint32_t ROOM_REF_FLAGGED = 0x20000000; +constexpr uint32_t ROOM_REF_MIRRORED = 0x40000000; +constexpr uint32_t ROOM_REF_MERGED = 0x80000000; +constexpr int ROOM_REF_MODE_SHIFT = 16; +constexpr int ROOM_REF_HALF_SHIFT = 16; + // A room config as a saved run names it (GameStateRoomConfig): its stage and mode packed with two of its flags, then // its type and variant. A merged room is a flag with its shape, and its halves' indices among the merged configs packed // in the last word. diff --git a/src/game_transition.cpp b/src/game_transition.cpp index f2b493e..41490dc 100644 --- a/src/game_transition.cpp +++ b/src/game_transition.cpp @@ -3,6 +3,7 @@ #include "entity_projectile.h" #include "game.h" #include "grid_entity_door.h" +#include "level.h" #include "log.h" #include "manager.h" #include "platform.h" @@ -16,8 +17,6 @@ constexpr int ROOM_INDEX_MIN = -20; constexpr int ROOM_INDEX_MAX = LEVEL_GRID_CELLS - 1; constexpr int DIMENSION_MAX = 2; -constexpr int DEATH_CERTIFICATE_DIMENSION = 2; -constexpr int MIRROR_DIMENSION = 1; constexpr int DOOR_SIDES = 4; constexpr int SIDE_ACROSS = 2; constexpr int MINESHAFT_ENTRANCE_SUBTYPE = 10; @@ -393,7 +392,7 @@ void Level::ChangeRoom(int targetRoomIdx, int dimension) persistent.Save(); } if (dimension < 0) dimension = currentDimensionIdx; - if (currentDimensionIdx == DEATH_CERTIFICATE_DIMENSION && dimension != DEATH_CERTIFICATE_DIMENSION) + if (currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE && dimension != DIMENSION_DEATH_CERTIFICATE) reconstruction_missing("Level::ChangeRoom 0073fc80: the way back from the Death Certificate floor (Game " "+0x18900..+0x18914 hold the room, dimension and door left)"); @@ -422,7 +421,7 @@ void Level::ChangeRoom(int targetRoomIdx, int dimension) bool isMazeMoved = false; int enterSide = DIRECTION_NONE; - bool isMazeFloor = currentDimensionIdx != MIRROR_DIMENSION || !HasAbandonedMineshaft(); + bool isMazeFloor = currentDimensionIdx != DIMENSION_MIRROR || !HasAbandonedMineshaft(); if ((GetCurses() & CURSE_OF_MAZE) && currentRoomIdx >= 0 && lastRoomIdx >= 0 && currentDimensionIdx == lastRoomDimensionIdx && isMazeFloor) isMazeMoved = maze_move(*this, newRoomIdx, enterSide); @@ -461,7 +460,7 @@ void Level::ChangeRoom(int targetRoomIdx, int dimension) RoomConfig_Room* leftData = room->descriptor->data; bool isEntrance = leftData && room->roomType == ROOM_DEFAULT && leftData->subtype == MINESHAFT_ENTRANCE_SUBTYPE; if (!game.IsGreedMode() && !isBackwards && isAltStage && isMineshaftFloor && lastRoomDimensionIdx == 0 && - currentDimensionIdx == MIRROR_DIMENSION && isEntrance) + currentDimensionIdx == DIMENSION_MIRROR && isEntrance) room->descriptor->flags |= ROOM_DESCRIPTOR_FLAG_SACRIFICE_DONE; load_room(); diff --git a/src/game_update.cpp b/src/game_update.cpp index 3951f88..ee0b596 100644 --- a/src/game_update.cpp +++ b/src/game_update.cpp @@ -1,18 +1,19 @@ #include "entity_player.h" +#include "boss_pool.h" #include "game.h" #include "grid_entity_door.h" +#include "level.h" #include "log.h" #include "lua_engine.h" #include "manager.h" #include "menu_manager.h" +#include "persistent_game_data.h" #include "room.h" #include "room_render.h" #include #include #include -constexpr int BOSS_MEGA_SATAN = 55; -constexpr int BOSS_MOTHER = 88; constexpr int SOUND_TRAPDOOR_LOOP = 1008; constexpr float TRAPDOOR_LOOP_FADE = 0.05f; constexpr float TRAPDOOR_HEARING_DISTANCE = 200; @@ -32,13 +33,10 @@ constexpr int DEATH_CERTIFICATE_SHAKE = 10; constexpr int HUD_REFRESH_INTERVAL = 30; constexpr uint64_t FADE_IN_ICON_MS = 3000; constexpr uint64_t NS_PER_MS = 1000000; -constexpr int DIMENSION_DEATH_CERTIFICATE = 2; // The room's render surface, its size and margin, centered on the screen. constexpr float ROOM_SURFACE_WIDTH = 338; constexpr float ROOM_SURFACE_HEIGHT = 182; constexpr float ROOM_SURFACE_MARGIN = 52; -constexpr int EVENT_EDEN_TOKENS = 21; -constexpr int EVENT_STREAK_COUNTER = 22; // The menu each menu fade out returns to. @@ -177,19 +175,19 @@ static void fadeout_finish(Game& game) menu_queue(FADEOUT_MENUS[target]); break; case FADEOUT_RESTART: - if (is_eden() && data.eventCounters[EVENT_EDEN_TOKENS] == 0) + if (is_eden() && data.eventCounters[EVENT_COUNTER_EDEN_TOKENS] == 0) { menu_queue(MENU_GAME); break; } - if (is_eden()) data.IncreaseEventCounter(EVENT_EDEN_TOKENS, -1); + if (is_eden()) data.IncreaseEventCounter(EVENT_COUNTER_EDEN_TOKENS, -1); Manager::RestartGame(); break; case FADEOUT_RESTART_HELD: { bool isEden = is_eden(); - data.IncreaseEventCounter(EVENT_STREAK_COUNTER, -data.eventCounters[EVENT_STREAK_COUNTER]); - if (isEden && data.eventCounters[EVENT_EDEN_TOKENS] != 0) data.IncreaseEventCounter(EVENT_EDEN_TOKENS, -1); + data.IncreaseEventCounter(EVENT_COUNTER_STREAK, -data.eventCounters[EVENT_COUNTER_STREAK]); + if (isEden && data.eventCounters[EVENT_COUNTER_EDEN_TOKENS] != 0) data.IncreaseEventCounter(EVENT_COUNTER_EDEN_TOKENS, -1); Manager::RestartGame(); break; } diff --git a/src/grid_entity.h b/src/grid_entity.h index 7cfd4a3..c5e2ce1 100644 --- a/src/grid_entity.h +++ b/src/grid_entity.h @@ -55,6 +55,10 @@ enum GridCollision : int constexpr int GRID_PATH_FREED = 900; constexpr int GRID_PATH_SOLID = 1000; +// A path cost's thousands band, and a pit's band. +constexpr int GRID_PATH_BAND = 1000; +constexpr int GRID_PATH_PIT = 3000; + // The seeds and RNG a grid entity holds before Init seeds it. constexpr uint32_t GRID_SEED_DEFAULT = 0x16a9de81; constexpr RNG GRID_RNG_DEFAULT = {0xaa17414f, 5, 9, 7}; diff --git a/src/grid_entity_door.cpp b/src/grid_entity_door.cpp index 68162e9..0b9cd11 100644 --- a/src/grid_entity_door.cpp +++ b/src/grid_entity_door.cpp @@ -1,7 +1,9 @@ #include "grid_entity_door.h" #include "entity_familiar.h" #include "entity_npc.h" +#include "entity_player.h" #include "game.h" +#include "level.h" #include "log.h" #include "manager.h" #include "room.h" @@ -13,7 +15,6 @@ constexpr int DOOR_TARGET_MIRROR = -100; constexpr int DOOR_TARGET_MINESHAFT = -101; // The stage of the Blue Womb, the dimension of Downpour's mirror world and of Home's dark closet, and Home's stage. -constexpr int DIMENSION_DEATH_CERTIFICATE = 2; // The secret exits get_secret_exit_kind tells apart, by the exit room's subtype, and the boss subtype of Mom's Heart's // exit. @@ -35,14 +36,12 @@ constexpr int GREED_EXIT_WAVE = 10; constexpr uint64_t GAME_STATE_HEART_EXIT_OPENED = 1ull << 52; // The items, trinkets and challenge doors answer to. -constexpr uint32_t CHALLENGE_PAY_TO_PLAY = 24; constexpr int FAMILIAR_KEY_FULL = 28; constexpr int FAMILIAR_STATE_KEY_DOOR = 1; // How far a door's sprite stands out from the wall, and the angles its sprites turn to by direction. constexpr float DOOR_SPRITE_OFFSET = 15; constexpr float DOOR_ANGLES[4] = {-90, 0, 90, 180}; -constexpr float RIGHT_ANGLE = 90; constexpr float DEG_TO_RAD = 0.017453292f; // The frame a closing or opening door plays its sound on, and the sounds. @@ -78,7 +77,6 @@ constexpr int SPARKLE_STRONG_MULTIPLIER = 3; constexpr ColorMod BLUE_REDIRECT_COLOR = {{1, 1, 1, 1}, {0.8f, 1.1f, 1.8f, 0.8f}, {0, 0, 0}}; constexpr float CLOSET_LIGHT_BASE = 0.5f; constexpr float CLOSET_LIGHT_RANGE = 0.2f; -constexpr float UINT_TO_UNIT = 2.3283064e-10f; // Whether a room type is one of the secret rooms walls hide. static bool is_secret_room_type(int roomType) @@ -681,7 +679,7 @@ void GridEntity_Door::LoadSprite() doorFlags |= DOOR_FLAG_COIN_LOCK; } - float angle = (sprite.rotation + RIGHT_ANGLE) * DEG_TO_RAD; + float angle = (sprite.rotation + RIGHT_ANGLE_DEGREES) * DEG_TO_RAD; sprite.offset = vector_make(std::cos(angle) * offsetLength, std::sin(angle) * offsetLength); extraSprite.offset = sprite.offset; if (!extraSprite.isLoaded && isExtraAllowed) @@ -976,7 +974,7 @@ void GridEntity_Door::Update() data && data->stageId == STAGE_ID_HOME && room_subtype_get(target, ROOM_DEFAULT) == HOME_SUBTYPE_CLOSET; if (isCloset && g_game->stageType == 1) { - float alpha = (float)Random() * UINT_TO_UNIT * CLOSET_LIGHT_RANGE + CLOSET_LIGHT_BASE; + float alpha = random_unit() * CLOSET_LIGHT_RANGE + CLOSET_LIGHT_BASE; layer_show(sprite, HOME_LAYER_LIGHT_FIRST, true); if (LayerState* light = sprite.GetLayer(HOME_LAYER_LIGHT_FIRST)) light->color = {{0.9f, 0.93f, 1, alpha}, {0, 0, 0, 0}, {0, 0, 0}}; diff --git a/src/grid_entity_pit.cpp b/src/grid_entity_pit.cpp index de2b831..c23d92e 100644 --- a/src/grid_entity_pit.cpp +++ b/src/grid_entity_pit.cpp @@ -2,15 +2,16 @@ #include "entity_effect.h" #include "entity_player.h" #include "game.h" +#include "grid_entity.h" #include "grid_entity_rock.h" #include "log.h" #include "room.h" #include "room_config.h" +#include "seeds.h" #include #include // The grid path a pit claims, and a spiked bridge's. -constexpr int GRID_PATH_PIT = 3000; constexpr int GRID_PATH_SPIKED_BRIDGE = 999; // A layout pit's variant: its frame in the low byte, the event flag, and the rails above it. @@ -42,7 +43,6 @@ constexpr int BRIDGE_SPIKES_PLAYER_DAMAGE = 2; // The pits' life: the mineshaft's dust (one in 40 frames, its tint, spin, life and size), the Mines' embers (one in // 20 frames over hot lava), and the Dank Depths' tar bubbles (checked every 10 frames, one in 6). -constexpr float PIT_RANDOM_UNIT = 2.3283064e-10f; constexpr uint32_t MINESHAFT_DUST_ODDS = 40; constexpr int MINESHAFT_DUST_SUBTYPE = 2; constexpr float MINESHAFT_DUST_ALPHA_MIN = 0.1f; @@ -193,22 +193,22 @@ static void bridge_layer_update(GridEntity_Pit& pit) // A pit's floating dust in the escaping mineshaft: red, additive, slowly turning and rising, gone in 20 to 49 frames. static void mineshaft_dust_spawn(const Vector& position) { - float rise = (float)Random() * PIT_RANDOM_UNIT; + float rise = random_unit(); Vector velocity = vector_make(0, -1 - (rise + rise)); uint32_t seed = Random(); Entity* dust = g_game->Spawn({.position = position, .velocity = velocity, .subType = MINESHAFT_DUST_SUBTYPE, .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = seed}); LayerState* layer = dust->sprite.GetLayer(0); - layer->color = {{1, 0, 0, (float)Random() * PIT_RANDOM_UNIT * MINESHAFT_DUST_ALPHA_RANGE + MINESHAFT_DUST_ALPHA_MIN}, {0, 0, 0, 0}, {0, 0, 0}}; + layer->color = {{1, 0, 0, random_unit() * MINESHAFT_DUST_ALPHA_RANGE + MINESHAFT_DUST_ALPHA_MIN}, {0, 0, 0, 0}, {0, 0, 0}}; KAGE::Graphics::BlendMode mode; mode.SetMode(KAGE::Graphics::BLEND_ADDITIVE); layer->blendMode = {mode.equation, mode.rgbSource, mode.rgbDest, mode.alphaSource, mode.alphaDest}; Entity_Effect& effect = static_cast(*dust); - effect.rotation = (float)Random() * PIT_RANDOM_UNIT * MINESHAFT_DUST_SPIN_RANGE + MINESHAFT_DUST_SPIN_MIN; + effect.rotation = random_unit() * MINESHAFT_DUST_SPIN_RANGE + MINESHAFT_DUST_SPIN_MIN; effect.timeout = (int)(Random() % MINESHAFT_DUST_LIFE_RANGE) + MINESHAFT_DUST_LIFE_MIN; effect.lifespan = effect.timeout; - float scale = (float)Random() * PIT_RANDOM_UNIT * MINESHAFT_DUST_SCALE_RANGE + MINESHAFT_DUST_SCALE_MIN; + float scale = random_unit() * MINESHAFT_DUST_SCALE_RANGE + MINESHAFT_DUST_SCALE_MIN; dust->sprite.scale = vector_make(scale, scale); dust->Update(); } @@ -216,10 +216,10 @@ static void mineshaft_dust_spawn(const Vector& position) // A lava pit's ember in the Mines, drifting up from somewhere on the cell. static void lava_ember_spawn(const Vector& position) { - float rise = (float)Random() * PIT_RANDOM_UNIT * LAVA_EMBER_RISE; - float drift = ((float)Random() * PIT_RANDOM_UNIT - 0.5f) * LAVA_EMBER_DRIFT; - float x = position.x + ((float)Random() * PIT_RANDOM_UNIT - 0.5f) * LAVA_EMBER_SPREAD; - float y = position.y + ((float)Random() * PIT_RANDOM_UNIT - 0.5f) * LAVA_EMBER_SPREAD; + float rise = random_unit() * LAVA_EMBER_RISE; + float drift = (random_unit() - 0.5f) * LAVA_EMBER_DRIFT; + float x = position.x + (random_unit() - 0.5f) * LAVA_EMBER_SPREAD; + float y = position.y + (random_unit() - 0.5f) * LAVA_EMBER_SPREAD; uint32_t seed = Random(); g_game->Spawn({.position = vector_make(x, y), .velocity = vector_make(drift, rise), .type = ENTITY_EFFECT, .variant = EFFECT_EMBER_PARTICLE, .seed = seed}); @@ -281,8 +281,8 @@ void GridEntity_Pit::Update() state != PIT_STATE_EMPTY || Random() % TAR_BUBBLE_ODDS != 0) return; Vector position = Position(); - position.x += ((float)Random() * PIT_RANDOM_UNIT - 0.5f) * TAR_SPREAD; - position.y += ((float)Random() * PIT_RANDOM_UNIT - 0.5f) * TAR_SPREAD; + position.x += (random_unit() - 0.5f) * TAR_SPREAD; + position.y += (random_unit() - 0.5f) * TAR_SPREAD; uint32_t seed = Random(); game.Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_TAR_BUBBLE, .seed = seed}); } diff --git a/src/grid_entity_poop.cpp b/src/grid_entity_poop.cpp index 6ac2827..3fcb349 100644 --- a/src/grid_entity_poop.cpp +++ b/src/grid_entity_poop.cpp @@ -105,7 +105,6 @@ constexpr int OH_CRAP_FORM_COUNT = 3; // The gibs: a third more of them per hit with Extra Blood, how fast they fly, and a rainbow gib's flatter throw. constexpr int POOP_EXTRA_BLOOD_GIBS = 3; constexpr float POOP_GIB_SPEED_MIN = 2; -constexpr float POOP_RANDOM_UNIT = 2.3283064e-10f; constexpr float POOP_HALF_TURN = 3.14f; constexpr float RAINBOW_GIB_FLATTEN = 0.5f; constexpr float STONE_BREAK_SPEED = 4; @@ -585,9 +584,9 @@ void GridEntity_Poop::spawn_hit_gibs(const Vector& position, int poopVariant, in color._colorize[3] = 1; uint32_t seed = Random(); - float angle = (float)Random() * POOP_RANDOM_UNIT * POOP_HALF_TURN; + float angle = random_unit() * POOP_HALF_TURN; angle += angle; - float speed = (float)Random() * POOP_RANDOM_UNIT + POOP_GIB_SPEED_MIN; + float speed = random_unit() + POOP_GIB_SPEED_MIN; Vector velocity = vector_make(std::cos(angle) * speed, std::sin(angle) * RAINBOW_GIB_FLATTEN * speed); Entity* gib = g_game->Spawn({.position = position, .velocity = velocity, .type = ENTITY_EFFECT, .variant = EFFECT_POOP_PARTICLE, .seed = seed}); @@ -625,7 +624,7 @@ void GridEntity_Poop::spawn_hit_gibs(const Vector& position, int poopVariant, in default: break; } - float speed = (float)Random() * POOP_RANDOM_UNIT + POOP_GIB_SPEED_MIN; + float speed = random_unit() + POOP_GIB_SPEED_MIN; game_particles_spawn({.color = color, .position = position, .speed = speed, .count = count, .variant = variant}); } @@ -790,7 +789,7 @@ static void golden_drops_spawn(const Vector& position, RNG& rng) Vector velocity{}; for (int attempt = 0; attempt < COIN_THROW_ATTEMPTS; attempt++) { - float angle = (float)Random() * POOP_RANDOM_UNIT * POOP_HALF_TURN; + float angle = random_unit() * POOP_HALF_TURN; angle += angle; velocity = vector_make(std::cos(angle) * COIN_THROW_SPEED, std::sin(angle) * COIN_THROW_SPEED); if (room_check_line(position, vector_add(position, vector_scale(velocity, COIN_THROW_CHECK)), LINE_MODE_CELL, diff --git a/src/grid_entity_pressure_plate.cpp b/src/grid_entity_pressure_plate.cpp index 67af36b..3db043b 100644 --- a/src/grid_entity_pressure_plate.cpp +++ b/src/grid_entity_pressure_plate.cpp @@ -13,9 +13,6 @@ #include #include -// The sounds a plate plays: pressed, and a reward plate's reward and ambush. -constexpr int SOUND_BUTTON_PRESS = 469; - // Who presses a plate, and how close: the entities a query finds around it, within reach of its center. constexpr float PLATE_QUERY_RADIUS = 60; constexpr float PLATE_PRESS_RADIUS = 30; @@ -484,5 +481,5 @@ void GridEntity_PressurePlate::Reward() reconstruction_missing("GridEntity_PressurePlate::Reward 00984550: the kill button (Game::ShakeScreen, " "pressure_plate_kill_enemies_timer_callback 00983f30)"); else if (variant >= PLATE_OUTPUT_FIRST && variant <= PLATE_OUTPUT_LAST) - reconstruction_missing("GridEntity_PressurePlate::Reward 00984550: Room::TriggerOutput 00823080"); + g_game->room->TriggerOutput(variant - PLATE_OUTPUT_FIRST); } diff --git a/src/grid_entity_rock.cpp b/src/grid_entity_rock.cpp index 0e5039e..fc5230c 100644 --- a/src/grid_entity_rock.cpp +++ b/src/grid_entity_rock.cpp @@ -1,11 +1,17 @@ #include "grid_entity_rock.h" +#include "backdrop.h" +#include "boss_ai.h" #include "entity_bomb.h" #include "entity_effect_combat.h" #include "entity_familiar.h" +#include "entity_knife.h" #include "entity_pickup.h" #include "entity_player.h" +#include "entity_projectile.h" #include "npc_ai.h" #include "npc_alt.h" +#include "npc_basement.h" +#include "persistent_game_data.h" #include "game.h" #include "log.h" #include "manager.h" @@ -43,7 +49,6 @@ constexpr float RUBBLE_SPREAD_HALF = 8; constexpr float RUBBLE_UNIT = 2.3283062e-10f; // The challenge whose rocks come from every backdrop, and how often a rock picks from its own seed. -constexpr uint32_t CHALLENGE_DELETE_THIS = 45; constexpr uint32_t MIXED_BACKDROP_ODDS = 10; // The Shiny Rock's glint: its period, faster for a stronger rock, the frames it lasts, peaking halfway, and how bright. @@ -100,7 +105,81 @@ constexpr float TINTED_CHEST_CHANCE = 0.71f; constexpr float TINTED_LOCKED_CHEST_CHANCE = 0.9f; constexpr float TINTED_SPIDER_HEIGHT = -10; constexpr uint32_t KEEPERS_KIN_SPIDERS = 3; -constexpr int DIMENSION_DEATH_CERTIFICATE_ROCKS = 2; + +// The alternate rocks' drops: one in 200 holds an item and one in 40 a trinket, Wavy Cap one in 100 in a secret room, +// else one roll in ten (five on an axe's extra rolls) brings creatures (on 1 and 3) or pickups (on 2). +constexpr uint32_t ALT_ITEM_ODDS = 200; +constexpr uint32_t ALT_TRINKET_ODDS = 40; +constexpr uint32_t WAVY_CAP_ODDS = 100; +constexpr uint32_t ALT_REWARD_ODDS = 10; +constexpr uint32_t ALT_REWARD_ODDS_AXE = 5; +constexpr uint32_t ALT_REWARD_CREATURES = 1; +constexpr uint32_t ALT_REWARD_PICKUPS = 2; +constexpr uint32_t ALT_REWARD_CREATURES_TOO = 3; + +// The pickups' speed after the first, and the coins' scatter. The creatures are thrown from a height to free spots +// 70 out. +constexpr float ALT_PICKUP_SPEED = 2; +constexpr float ALT_COIN_SPREAD = 5; +constexpr float ALT_COIN_SPREAD_RANGE = 10; +constexpr float CREATURE_SPOT_STEP = 70; +constexpr float ALT_THROW_HEIGHT = -30; + +// The mushroom's spores: the fart's and the push's reach, and the hurt to players within 100. +constexpr float MUSHROOM_FART_RADIUS = 85; +constexpr float SPORE_PUSH_RADIUS = 120; +constexpr float SPORE_HURT_RADIUS = 100; +constexpr int SPORE_HURT_COUNTDOWN = 30; +constexpr int SPORE_SOURCE_VARIANT = 10000; + +// The polyp's burst: a ring of six shots, or in the Corpse six maggots leaping within 20 degrees of each spoke. +constexpr int POLYP_SHOTS = 6; +constexpr int POLYP_SPAWNER_VARIANT = 10001; +constexpr float POLYP_SPOKE_DEGREES = 60; +constexpr float POLYP_SHOT_SPEED = 10; +constexpr float POLYP_SHOT_RISE = -3; +constexpr float POLYP_SHOT_FALLING_ACCEL = 0.1f; +constexpr float POLYP_MAGGOT_SPREAD = 40; +constexpr float POLYP_MAGGOT_SPREAD_HALF = 20; +constexpr float POLYP_MAGGOT_SPEED = 2; +constexpr float POLYP_MAGGOT_SPEED_RANGE = 9; +constexpr float POLYP_MAGGOT_HEIGHT = -30; +constexpr float POLYP_MAGGOT_HEIGHT_RANGE = 15; +constexpr float POLYP_MAGGOT_RISE = -8; + +// A full bucket's spill: six shots of up to 6 speed from up to 8 out, falling from high, some bigger, and its splash +// (blue water, or the Dross's sludge particles). +constexpr int BUCKET_VARIANT_FULL = 1; +constexpr int BUCKET_SHOTS = 6; +constexpr int BUCKET_SPAWNER_VARIANT = 10002; +constexpr float BUCKET_SHOT_SPEED = 6; +constexpr float BUCKET_SHOT_SPREAD = 8; +constexpr float BUCKET_SHOT_SCALE = 0.9f; +constexpr float BUCKET_SHOT_SCALE_BIG = 0.4f; +constexpr float BUCKET_SHOT_SCALE_JITTER = 0.05f; +constexpr float BUCKET_SHOT_HEIGHT = -32; +constexpr float BUCKET_SHOT_FALLING_ACCEL = 0.9f; +constexpr float BUCKET_SHOT_RISE = -5; +constexpr float BUCKET_SHOT_RISE_RANGE = 24; +constexpr int BUCKET_SPLASH_SUBTYPE = 2; +constexpr ColorMod BUCKET_SPLASH_COLOR = {{1, 1, 1, 1}, {5.5f, 7, 7, 1}, {0, 0, 0}}; +constexpr float BUCKET_SLUDGE_SPEED = 4; +constexpr float BUCKET_SLUDGE_SPEED_RANGE = 5; +constexpr int BUCKET_SLUDGE_MIN = 4; +constexpr uint32_t BUCKET_SLUDGE_RANGE = 5; + +// Notched Axe's rolls with Book of Belial, and its Book of Virtues rock wisps: one roll in five, by chance below each. +constexpr int AXE_ROLLS = 3; +constexpr uint32_t AXE_WISP_ODDS = 5; +constexpr int ROCK_WISP_COMMON = 0x10000; +constexpr int ROCK_WISP_UNCOMMON = 0x10001; +constexpr int ROCK_WISP_GOLD = 0x10002; +constexpr int ROCK_WISP_RAREST = 0x10003; +constexpr int ROCK_WISP_RARE = 0x10004; +constexpr float ROCK_WISP_RAREST_CHANCE = 0.01f; +constexpr float ROCK_WISP_GOLD_CHANCE = 0.04f; +constexpr float ROCK_WISP_RARE_CHANCE = 0.08f; +constexpr float ROCK_WISP_UNCOMMON_CHANCE = 0.33f; // Stud Finder's chance of a crawlspace, Lucky Rock's of a coin, the most Lucky Rocks that count, and the countdown an // event rock or pit beside a broken rock starts. @@ -120,9 +199,21 @@ constexpr int EVENT_SS_ROCKS_DESTROYED = 4; constexpr int ALT_ROCK_SOUNDS[] = {0, 78, 79, 137, 77, 138}; constexpr int FLESHY_BACKDROPS[] = {10, 11, 12, 13, 34, 43, 44, 48}; -// Which alternate rock (urn, mushroom, skull, polyp, bucket) a backdrop shows: -// the room's for none given. -static int alt_rock_type_get(int backdropType) +// The alternate rock a backdrop shows, also the index of its break sound. +enum AltRock +{ + ALT_ROCK_URN = 1, + ALT_ROCK_MUSHROOM, + ALT_ROCK_SKULL, + ALT_ROCK_POLYP, + ALT_ROCK_BUCKET +}; + +// The Corpse's backdrops, whose polyps hold rotten things. +constexpr int CORPSE_BACKDROPS[] = {BACKDROP_CORPSE, BACKDROP_CORPSE2, BACKDROP_CORPSE3, BACKDROP_MORTIS}; + +// 00718ee0 Which alternate rock a backdrop shows (the room's for none given). +static AltRock alt_rock_type_get(int backdropType) { if (backdropType == 0) backdropType = g_game->room->backdropType; @@ -137,7 +228,7 @@ static int alt_rock_type_get(int backdropType) case 46: case 58: case 59: - return 2; + return ALT_ROCK_MUSHROOM; case 7: case 8: case 9: @@ -151,7 +242,7 @@ static int alt_rock_type_get(int backdropType) case 41: case 42: case 47: - return 3; + return ALT_ROCK_SKULL; case 10: case 11: case 12: @@ -160,13 +251,13 @@ static int alt_rock_type_get(int backdropType) case 43: case 44: case 48: - return 4; + return ALT_ROCK_POLYP; case 31: case 36: case 45: - return 5; + return ALT_ROCK_BUCKET; default: - return 1; + return ALT_ROCK_URN; } } @@ -569,7 +660,7 @@ bool GridEntity_Rock::Destroy(bool isImmediate, const EntityRef& source) .variant = EFFECT_ROCK_PARTICLE}); UpdateNeighbors(); int cell = gridIndex; - SpawnDrops(position, type, variant, spawnSeed, 0, source.entity); + SpawnDrops({.position = position, .source = source.entity, .type = type, .variant = variant, .seed = spawnSeed}); TrySpawnLadder(); grid_mark_neighbors_dirty(cell); return true; @@ -771,27 +862,58 @@ bool GridEntity_Rock::TrySpawnLadder() return true; } -// The gold rock's two to four pennies, thrown at random. -static void gold_coins_spawn(const Vector& position, RNG& dropRng, RNG& velocityRng) +// The rolls a broken rock's drops share: the drop and its backdrop, its generators, the velocity a rolled pill, card or +// heart leaves the next roll's, the rolls left (three with Notched Axe and Book of Belial), and the alternate rock. +struct RockRoll { - uint32_t first = dropRng.Next() & 1; - uint32_t second = dropRng.Next() & 1; + const RockDrop& drop; + RNG dropRng; + RNG ownerRng; + RNG velocityRng; + Vector pickupVelocity{}; + AltRock altRock = ALT_ROCK_URN; + int backdropType = 0; + int rolls = 1; + bool isCorpse = false; +}; + +// Whether a roll goes on to the next one or ends the drops. +enum RollEnd +{ + ROLL_NEXT, + ROLL_STOP +}; + +// A pickup or other drop spawned and run for its first frame. +static Entity* drop_spawn(const EntitySpawn& spawn) +{ + Entity* entity = g_game->Spawn(spawn); + entity->Update(); + return entity; +} + +// The gold rock's two to four pennies, thrown at random. +static void gold_coins_spawn(RockRoll& roll) +{ + uint32_t first = roll.dropRng.Next() & 1; + uint32_t second = roll.dropRng.Next() & 1; for (int coins = (int)(first + second) + GOLD_COINS_MIN; coins > 0; coins--) { - uint32_t coinSeed = dropRng.Next(); - Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, &velocityRng, 0); - g_game->Spawn({.position = position, .velocity = velocity, .subType = COIN_PENNY, .type = ENTITY_PICKUP, - .variant = PICKUP_COIN, .seed = coinSeed}) - ->Update(); + uint32_t coinSeed = roll.dropRng.Next(); + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(roll.drop.position, &roll.velocityRng, 0); + drop_spawn({.position = roll.drop.position, .velocity = velocity, .subType = COIN_PENNY, .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, .seed = coinSeed}); } } // Lucky Rock's coins, a third of the time each (the breaker's own Lucky Rocks in versus). -static void lucky_rock_coins_spawn(const Vector& position, Entity* source, RNG& dropRng, RNG& velocityRng) +static void lucky_rock_coins_spawn(RockRoll& roll) { int luckyRocks = 0; - if (!g_game->deathmatchManager.is_active()) luckyRocks = g_game->playerManager.GetTrinketMultiplier(TRINKET_LUCKY_ROCK); - for (Entity* ancestor = source; ancestor && g_game->deathmatchManager.is_active(); ancestor = ancestor->spawnerEntity) + if (!g_game->deathmatchManager.is_active()) + luckyRocks = g_game->playerManager.GetTrinketMultiplier(TRINKET_LUCKY_ROCK); + for (Entity* ancestor = roll.drop.source; ancestor && g_game->deathmatchManager.is_active(); + ancestor = ancestor->spawnerEntity) { if (!ancestor->is_player()) continue; luckyRocks = ancestor->ToPlayer()->GetTrinketMultiplier(TRINKET_LUCKY_ROCK); @@ -799,13 +921,12 @@ static void lucky_rock_coins_spawn(const Vector& position, Entity* source, RNG& } for (int i = 0; i < std::min(luckyRocks, LUCKY_ROCK_MAX); i++) { - if (dropRng.Next() % LUCKY_ROCK_ODDS != 0) continue; + if (roll.dropRng.Next() % LUCKY_ROCK_ODDS != 0) continue; - uint32_t coinSeed = dropRng.Next(); - Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, &velocityRng, 0); - g_game->Spawn({.position = position, .velocity = velocity, .subType = COIN_PENNY, .type = ENTITY_PICKUP, - .variant = PICKUP_COIN, .seed = coinSeed}) - ->Update(); + uint32_t coinSeed = roll.dropRng.Next(); + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(roll.drop.position, &roll.velocityRng, 0); + drop_spawn({.position = roll.drop.position, .velocity = velocity, .subType = COIN_PENNY, .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, .seed = coinSeed}); } } @@ -857,64 +978,353 @@ static void trinket_drop_spawn(const Vector& position, RNG& ownerRng, RNG& veloc // Whether the floor is the Mines or the Ashpit, whose tinted rocks may hold rock spiders. static bool is_mines_stage() { - Game& game = *g_game; - int stageType = 0; - if (game.challenge == CHALLENGE_RED_REDEMPTION) stageType = game.GetRoomStageType(game.currentRoomIdx); - else if (game.currentDimensionIdx != DIMENSION_DEATH_CERTIFICATE_ROCKS) stageType = (int)game.stageType; - else return false; - - int stageId = RoomConfig::GetStageID((int)game.stage, stageType, ROOM_MODE_CURRENT); + int stageId = g_game->GetStageID(); return stageId == STAGE_ID_MINES || stageId == STAGE_ID_ASHPIT; } + // The tinted and super secret rocks' drops: one time in ten Small Rock while in the pool (and nothing else), else two -// (four for a super secret rock, one more with Lucky Toe two times in three) rolls after the trinkets pay out: soul -// hearts (rock spiders in the Mines, half of them free), keys, bombs, and on the first roll a chest that ends them. -static void tinted_drops_spawn(const Vector& position, GridEntityType type, RNG& dropRng, RNG& velocityRng, - RNG& ownerRng) +// (four for a super secret rock, none or one on an axe's extra rolls, one more with Lucky Toe two times in three) rolls +// after the trinkets pay out: soul hearts (rock spiders in the Mines, half of them free), keys, bombs, and on the first +// roll a chest that ends them. +static RollEnd tinted_drops_spawn(RockRoll& roll) { + const Vector& position = roll.drop.position; + RNG& dropRng = roll.dropRng; if (dropRng.Next() % SMALL_ROCK_ODDS == 0 && g_game->itemPool.RemoveCollectible(SMALL_ROCK_ITEM, REMOVE_AVAILABLE, REMOVE_APPLY)) { - g_game->Spawn({.position = position, .subType = SMALL_ROCK_ITEM, .type = ENTITY_PICKUP, - .variant = PICKUP_COLLECTIBLE, .seed = dropRng.Next()}) - ->Update(); - return; + drop_spawn({.position = position, .subType = SMALL_ROCK_ITEM, .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, .seed = dropRng.Next()}); + return ROLL_STOP; } PlayerManager& players = g_game->playerManager; - int drops = type == GRID_ROCK_SS ? SS_ROCK_DROPS : TINTED_ROCK_DROPS; - if (dropRng.Next() % LUCKY_TOE_ODDS != 0 && players.FirstTrinketOwner(TRINKET_LUCKY_TOE, nullptr, LAZARUS_SHARE_CHECK)) - drops++; - trinket_drop_spawn(position, ownerRng, velocityRng); + int drops = roll.drop.type == GRID_ROCK_SS ? SS_ROCK_DROPS : TINTED_ROCK_DROPS; + if (roll.rolls > 1) drops = (int)(dropRng.Next() & 1); + bool isLuckyToe = dropRng.Next() % LUCKY_TOE_ODDS != 0; + if (isLuckyToe && players.FirstTrinketOwner(TRINKET_LUCKY_TOE, nullptr, LAZARUS_SHARE_CHECK)) drops++; + trinket_drop_spawn(position, roll.ownerRng, roll.velocityRng); RNG* tail = nullptr; - players.RandomTrinketOwner(TRINKET_DAEMONS_TAIL, ownerRng.Next(), &tail); + players.RandomTrinketOwner(TRINKET_DAEMONS_TAIL, roll.ownerRng.Next(), &tail); for (int i = 0; i < drops; i++) { - float roll = dropRng.RandomFloat(); - Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, &velocityRng, 0); - if (roll < TINTED_SOUL_CHANCE && (!tail || tail->Next() % DAEMONS_TAIL_ODDS == 0)) + float chance = dropRng.RandomFloat(); + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, &roll.velocityRng, 0); + if (chance < TINTED_SOUL_CHANCE && (!tail || tail->Next() % DAEMONS_TAIL_ODDS == 0)) { if (is_mines_stage() && (dropRng._seed & 1) == 0) rock_spider_throw(position, velocity, nullptr, SPIDER_THROW_TINTED, TINTED_SPIDER_HEIGHT); else - g_game->Spawn({.position = position, .velocity = velocity, .subType = HEART_SOUL, .type = ENTITY_PICKUP, - .variant = PICKUP_HEART, .seed = dropRng.Next()}) - ->Update(); + drop_spawn({.position = position, .velocity = velocity, .subType = HEART_SOUL, .type = ENTITY_PICKUP, + .variant = PICKUP_HEART, .seed = dropRng.Next()}); if ((dropRng.Next() & 1) == 0) drops--; continue; } int variant = PICKUP_BOMB; - if (roll < TINTED_KEY_CHANCE) variant = PICKUP_KEY; - else if (roll < TINTED_CHEST_CHANCE && i == 0) variant = PICKUP_CHEST; - else if (roll < TINTED_LOCKED_CHEST_CHANCE && i == 0) variant = PICKUP_LOCKEDCHEST; - g_game->Spawn({.position = position, .velocity = velocity, .type = ENTITY_PICKUP, .variant = variant, - .seed = dropRng.Next()}) - ->Update(); + if (chance < TINTED_KEY_CHANCE) variant = PICKUP_KEY; + else if (chance < TINTED_CHEST_CHANCE && i == 0) variant = PICKUP_CHEST; + else if (chance < TINTED_LOCKED_CHEST_CHANCE && i == 0) variant = PICKUP_LOCKEDCHEST; + drop_spawn({.position = position, .velocity = velocity, .type = ENTITY_PICKUP, .variant = variant, + .seed = dropRng.Next()}); if (variant == PICKUP_CHEST || variant == PICKUP_LOCKEDCHEST) break; } + return ROLL_NEXT; +} + +// A bucket of the layout's variant spills six shots of its water (the Dross's sludge) about with a splash. +static void bucket_spill(const RockRoll& roll) +{ + bool isDross = roll.backdropType == BACKDROP_DROSS; + const Vector& position = roll.drop.position; + for (int i = 0; i < BUCKET_SHOTS; i++) + { + Vector direction = random_direction(); + float speed = random_unit() * BUCKET_SHOT_SPEED; + uint32_t seed = Random(); + float spread = random_unit() * BUCKET_SHOT_SPREAD; + auto* shot = static_cast( + g_game->Spawn({.position = vector_add(vector_scale(direction, spread), position), + .velocity = vector_scale(direction, speed), + .type = ENTITY_PROJECTILE, + .variant = isDross ? PROJECTILE_PUKE : PROJECTILE_TEAR, + .seed = seed})); + shot->spawnerType = ENTITY_NULL; + shot->spawnerVariant = BUCKET_SPAWNER_VARIANT; + + float big = (float)(Random() & 1); + shot->scale = random_unit() * BUCKET_SHOT_SCALE_JITTER + big * BUCKET_SHOT_SCALE_BIG + BUCKET_SHOT_SCALE; + shot->height = BUCKET_SHOT_HEIGHT; + shot->fallingAccel = BUCKET_SHOT_FALLING_ACCEL; + shot->fallingSpeed = BUCKET_SHOT_RISE - random_unit() * BUCKET_SHOT_RISE_RANGE; + } + + if (!isDross) + { + Entity* splash = g_game->Spawn({.position = position, .subType = BUCKET_SPLASH_SUBTYPE, .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + splash->sprite.color = BUCKET_SPLASH_COLOR; + return; + } + float speed = random_unit() * BUCKET_SLUDGE_SPEED_RANGE + BUCKET_SLUDGE_SPEED; + int count = (int)(Random() % BUCKET_SLUDGE_RANGE) + BUCKET_SLUDGE_MIN; + game_particles_spawn({.position = position, .speed = speed, .count = count, .variant = EFFECT_POOP_PARTICLE}); + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_POOP_EXPLOSION, .seed = Random()}); +} + +// The second alternate rock's Fool card, or a known Telepills with Little Baggy but no Starter Deck. +static void alt2_card_spawn(const Vector& position) +{ + PlayerManager& players = g_game->playerManager; + Entity_Player* deck = players.FirstCollectibleOwner(COLLECTIBLE_STARTER_DECK, LAZARUS_SHARE_CHECK); + Entity_Player* baggy = players.FirstCollectibleOwner(COLLECTIBLE_LITTLE_BAGGY, LAZARUS_SHARE_CHECK); + EntitySpawn spawn = { + .position = position, .subType = CARD_FOOL, .type = ENTITY_PICKUP, .variant = PICKUP_TAROTCARD}; + if (baggy && !deck) + { + spawn.subType = g_game->itemPool.ForceAddPillEffect(PILLEFFECT_TELEPILLS); + g_game->itemPool.IdentifyPill((uint32_t)spawn.subType); + spawn.variant = PICKUP_PILL; + } + spawn.seed = Random(); + Entity* pickup = g_game->Spawn(spawn); + pickup->spawnerType = ENTITY_PICKUP; + pickup->spawnerVariant = PICKUP_GRAB_BAG; + pickup->Update(); +} + +// The item one alternate rock in 200 holds while the pool has it, or 0: The Quarter in an urn, Wavy Cap (one time in +// a hundred in a secret room), Mini Mush or Magic Mushroom in a mushroom, Dry Baby or Ghost Baby in a skull, Placenta +// or Blood Clot in a polyp (Rotten Meat or Rotten Baby in the Corpse), and The Poop in the Dross's bucket, else Leech. +static int alt_item_roll(RockRoll& roll) +{ + ItemPool& pool = g_game->itemPool; + auto take = [&](int item) { return pool.RemoveCollectible(item, REMOVE_ANY, REMOVE_APPLY) ? item : 0; }; + auto either = [&](int first, int second) + { + if ((roll.dropRng.Next() & 1) == 0 && take(first)) return first; + return take(second); + }; + + switch (roll.altRock) + { + case ALT_ROCK_URN: + return take(COLLECTIBLE_QUARTER); + case ALT_ROCK_MUSHROOM: + if (g_game->room->roomType == ROOM_SECRET && roll.dropRng.Next() % WAVY_CAP_ODDS == 0 && + take(COLLECTIBLE_WAVY_CAP)) + return COLLECTIBLE_WAVY_CAP; + return either(COLLECTIBLE_MINI_MUSH, COLLECTIBLE_MAGIC_MUSHROOM); + case ALT_ROCK_SKULL: + return either(COLLECTIBLE_DRY_BABY, COLLECTIBLE_GHOST_BABY); + case ALT_ROCK_POLYP: + if (roll.isCorpse) return either(COLLECTIBLE_ROTTEN_MEAT, COLLECTIBLE_ROTTEN_BABY); + return either(COLLECTIBLE_PLACENTA, COLLECTIBLE_BLOOD_CLOT); + default: + if (roll.backdropType == BACKDROP_DROSS && take(COLLECTIBLE_POOP)) return COLLECTIBLE_POOP; + return take(COLLECTIBLE_LEECH); + } +} + +// The trinket one alternate rock in 40 holds while the pool has it: Swallowed Penny in an urn or bucket (Butt Penny +// first in the Dross), Liberty Cap in a mushroom, and Umbilical Cord in a polyp (Lil Larva in the Corpse). A skull +// holds a black heart instead. Either ends the drops. +static RollEnd alt_trinket_spawn(RockRoll& roll) +{ + ItemPool& pool = g_game->itemPool; + EntitySpawn spawn = {.position = roll.drop.position, .type = ENTITY_PICKUP, .variant = PICKUP_TRINKET}; + auto take = [&](int trinket) { return pool.RemoveTrinket(trinket) ? trinket : 0; }; + switch (roll.altRock) + { + case ALT_ROCK_MUSHROOM: + spawn.subType = take(TRINKET_LIBERTY_CAP); + break; + case ALT_ROCK_POLYP: + spawn.subType = take(roll.isCorpse ? TRINKET_LIL_LARVA : TRINKET_UMBILICAL_CORD); + break; + case ALT_ROCK_SKULL: + spawn.subType = HEART_BLACK; + spawn.variant = PICKUP_HEART; + break; + default: + if (roll.backdropType == BACKDROP_DROSS) spawn.subType = take(TRINKET_BUTT_PENNY); + if (!spawn.subType) spawn.subType = take(TRINKET_SWALLOWED_PENNY); + } + if (!spawn.subType) return ROLL_NEXT; + + spawn.seed = Random(); + drop_spawn(spawn); + return ROLL_STOP; +} + +// The spots a few creatures are thrown to: free ones about the rock. +static Vector creature_spot_find(const Vector& position) +{ + return room_free_pickup_position_find({.position = position, .step = CREATURE_SPOT_STEP}); +} + +// The mushroom's spores: a fart and a Butter Bean push, and a hurt to each player near enough not immune to poison. +static void mushroom_spores_release(const Vector& position) +{ + game_fart({.position = position, .radius = MUSHROOM_FART_RADIUS}); + game_butter_bean_fart({.position = position, .radius = SPORE_PUSH_RADIUS, .isShowEffect = false}); + EntityRef spores; + spores.variant = SPORE_SOURCE_VARIANT; + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->HasPoisonImmunity() || player->is_evil_charm_immune(spores)) continue; + if (vector_length_squared(vector_sub(position, player->pos)) < SPORE_HURT_RADIUS * SPORE_HURT_RADIUS) + player->TakeDamage(1, 0, spores, SPORE_HURT_COUNTDOWN); + } +} + +// The polyp's burst: creep with a ring of six shots, or in the Corpse green creep with six small maggots leaping out. +static void polyp_burst(const RockRoll& roll) +{ + const Vector& position = roll.drop.position; + uint32_t seed = Random(); + Entity* creep = g_game->Spawn({.position = position, .type = ENTITY_EFFECT, + .variant = roll.isCorpse ? EFFECT_CREEP_GREEN : EFFECT_CREEP_RED, .seed = seed}); + creep->spawnerType = ENTITY_NULL; + creep->spawnerVariant = POLYP_SPAWNER_VARIANT; + creep->Update(); + + for (int i = 0; i < POLYP_SHOTS; i++) + { + float spoke = (float)i * POLYP_SPOKE_DEGREES; + if (roll.isCorpse) + { + float angle = random_unit() * POLYP_MAGGOT_SPREAD + (spoke - POLYP_MAGGOT_SPREAD_HALF); + float speed = random_unit() * POLYP_MAGGOT_SPEED_RANGE + POLYP_MAGGOT_SPEED; + Vector velocity = vector_scale(vector_from_angle(angle), speed); + small_maggot_spawn(position, random_unit() * POLYP_MAGGOT_HEIGHT_RANGE + POLYP_MAGGOT_HEIGHT, velocity, + POLYP_MAGGOT_RISE); + continue; + } + + Vector velocity = vector_scale(vector_from_angle(spoke), POLYP_SHOT_SPEED); + auto* shot = static_cast(g_game->Spawn( + {.position = position, .velocity = velocity, .type = ENTITY_PROJECTILE, .seed = Random()})); + shot->fallingSpeed = POLYP_SHOT_RISE; + shot->fallingAccel = POLYP_SHOT_FALLING_ACCEL; + shot->spawnerType = ENTITY_NULL; + shot->spawnerVariant = POLYP_SPAWNER_VARIANT; + shot->Update(); + } +} + +// The bucket's creatures in a flooded room: Drips spilled about in the Dross, else Striders, or Leeches. +static void bucket_creatures_spawn(RockRoll& roll, int count) +{ + const Vector& position = roll.drop.position; + bool isLeech = roll.dropRng.RandomInt(2) != 0; + for (int i = 0; i < count; i++) + { + if (isLeech) + { + leech_throw({.position = position, .target = creature_spot_find(position), .height = ALT_THROW_HEIGHT}); + continue; + } + if (roll.backdropType != BACKDROP_DROSS) + { + Entity_NPC::ThrowStrider(position, nullptr, creature_spot_find(position)); + continue; + } + + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, nullptr, 0); + uint32_t seed = Random(); + auto* drip = static_cast(g_game->Spawn( + {.position = vector_add(position, velocity), .velocity = velocity, .type = ENTITY_DRIP, .seed = seed})); + if (drip->friction != 0) + drip->velocity = vector_add(vector_scale(velocity, drip->speedMultiplier / drip->friction), drip->velocity); + drip->ClearEntityFlags(FLAG_APPEAR); + drip->state = NPC_STATE_MOVE; + drip->Update(); + } +} + +// The creatures an alternate rock lets out: one or two spiders from an urn (or a dry room's bucket), the mushroom's +// spores, a Host from a skull, the polyp's burst, and a flooded room's bucket creatures. +static void alt_creatures_spawn(RockRoll& roll) +{ + const Vector& position = roll.drop.position; + if (roll.altRock == ALT_ROCK_MUSHROOM) return mushroom_spores_release(position); + if (roll.altRock == ALT_ROCK_SKULL) + { + drop_spawn({.position = position, .type = ENTITY_HOST, .seed = Random()}); + return; + } + if (roll.altRock == ALT_ROCK_POLYP) return polyp_burst(roll); + + int count = (int)roll.dropRng.RandomInt(2) + 1; + if (roll.altRock == ALT_ROCK_BUCKET && g_game->room->waterAmount > 0) return bucket_creatures_spawn(roll, count); + for (int i = 0; i < count; i++) + Entity_NPC::ThrowSpider(position, nullptr, creature_spot_find(position), false, ALT_THROW_HEIGHT); +} + +// The pickups an alternate rock drops: a pill from a mushroom, a card from a skull, a heart from a polyp (a rotten one +// in the Corpse once unlocked), each at the velocity the last one left, else one or two coins scattered about. +static void alt_pickups_spawn(RockRoll& roll) +{ + const Vector& position = roll.drop.position; + if (roll.altRock == ALT_ROCK_URN || roll.altRock == ALT_ROCK_BUCKET) + { + for (int coins = (int)roll.dropRng.RandomInt(2) + 1; coins > 0; coins--) + { + Vector velocity = vector_scale(random_direction(), ALT_PICKUP_SPEED); + uint32_t seed = roll.dropRng.Next(); + Vector direction = random_direction(); + float distance = random_unit() * ALT_COIN_SPREAD_RANGE + ALT_COIN_SPREAD; + drop_spawn({.position = vector_add(vector_scale(direction, distance), position), .velocity = velocity, + .type = ENTITY_PICKUP, .variant = PICKUP_COIN, .seed = seed}); + } + return; + } + + EntitySpawn spawn = {.position = position, .velocity = roll.pickupVelocity, .type = ENTITY_PICKUP}; + spawn.variant = roll.altRock == ALT_ROCK_MUSHROOM ? PICKUP_PILL + : roll.altRock == ALT_ROCK_SKULL ? PICKUP_TAROTCARD + : PICKUP_HEART; + if (roll.isCorpse && spawn.variant == PICKUP_HEART) spawn.subType = HEART_ROTTEN; + if (spawn.subType != HEART_ROTTEN || is_run_unlocked(ACHIEVEMENT_ROTTEN_HEARTS)) + { + spawn.seed = roll.dropRng.Next(); + drop_spawn(spawn); + } + roll.pickupVelocity = vector_scale(random_direction(), ALT_PICKUP_SPEED); +} + +// The alternate rocks' drops: a bucket of the layout's variant spills on the last roll, and the second alternate rock +// gives only its card there. Else one rock in 200 holds its item, one in 40 its trinket, both ending the drops, and +// the rest roll one in ten (five on an axe's extra rolls) for pickups or creatures (these only on the last roll). +static RollEnd alt_drops_spawn(RockRoll& roll) +{ + const RockDrop& drop = roll.drop; + if (roll.altRock == ALT_ROCK_BUCKET && drop.variant == BUCKET_VARIANT_FULL && roll.rolls == 1) + bucket_spill(roll); + if (drop.type == GRID_ROCK_ALT2 && roll.rolls == 1) + { + alt2_card_spawn(drop.position); + return ROLL_STOP; + } + + if (roll.dropRng.Next() % ALT_ITEM_ODDS == 0) + if (int item = alt_item_roll(roll)) + { + drop_spawn({.position = drop.position, .subType = item, .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, .seed = Random()}); + return ROLL_STOP; + } + if (roll.dropRng.Next() % ALT_TRINKET_ODDS == 0 && alt_trinket_spawn(roll) == ROLL_STOP) return ROLL_STOP; + + uint32_t reward = roll.dropRng.RandomInt(roll.rolls > 1 ? ALT_REWARD_ODDS_AXE : ALT_REWARD_ODDS); + if ((reward == ALT_REWARD_CREATURES || reward == ALT_REWARD_CREATURES_TOO) && roll.rolls < 2) + alt_creatures_spawn(roll); + else if (reward == ALT_REWARD_PICKUPS) + alt_pickups_spawn(roll); + return ROLL_NEXT; } // Keeper's Kin's blue spiders from a broken rock: none to three for a random owner (the breaker in versus). @@ -946,21 +1356,59 @@ static void keepers_kin_spiders_spawn(const Vector& position, uint32_t seed, Ent } } -// 0071b410 Spawns what a broken rock of a type drops: a gold rock's pennies, Lucky Rock's coins for any rock, a tinted -// or super secret rock's pickups, and Keeper's Kin's spiders. -// The knife swing that breaks rocks (Entity_Knife::UpdateSwingHits) is not curated, so no swinging player rolls again -// or makes wisps here. -void GridEntity_Rock::SpawnDrops(const Vector& position, GridEntityType type, int, uint32_t seed, int, Entity* source) +// Book of Virtues on a Notched Axe swinger: a rock wisp one roll in five (three rolls with Book of Belial), a gold +// one from a gold rock, else the rarer kinds less often. +static void axe_wisps_spawn(Entity_Player& player, const RockDrop& drop) { - RNG dropRng = {seed, 5, 9, 7}; - RNG velocityRng = {seed, 1, 9, 29}; - RNG ownerRng = {seed, 2, 7, 7}; - if (type == GRID_ROCK_GOLD) gold_coins_spawn(position, dropRng, velocityRng); - lucky_rock_coins_spawn(position, source, dropRng, velocityRng); - if (type == GRID_ROCKT || type == GRID_ROCK_SS) tinted_drops_spawn(position, type, dropRng, velocityRng, ownerRng); - else if (type == GRID_ROCK_ALT || type == GRID_ROCK_ALT2) - reconstruction_missing("GridEntity_Rock::SpawnDrops 0071b410: the alternate rocks' drops"); - keepers_kin_spiders_spawn(position, seed, source); + if (!player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) return; + + RNG wispRng = {drop.seed, 7, 17, 21}; + for (int rolls = player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) ? AXE_ROLLS : 1; rolls > 0; rolls--) + { + if (wispRng.Next() % AXE_WISP_ODDS != 0) continue; + + int wisp = ROCK_WISP_GOLD; + if (drop.type != GRID_ROCK_GOLD) + { + float chance = wispRng.RandomFloat(); + wisp = chance < ROCK_WISP_RAREST_CHANCE ? ROCK_WISP_RAREST + : chance < ROCK_WISP_GOLD_CHANCE ? ROCK_WISP_GOLD + : chance < ROCK_WISP_RARE_CHANCE ? ROCK_WISP_RARE + : chance < ROCK_WISP_UNCOMMON_CHANCE ? ROCK_WISP_UNCOMMON + : ROCK_WISP_COMMON; + } + player.AddWisp(wisp, drop.position, false, false); + } +} + +// 0071b410 Spawns what a broken rock drops, roll by roll (three for a Notched Axe swinger with Book of Belial): a gold +// rock's pennies, Lucky Rock's coins for any rock, then a tinted or super secret rock's or an alternate rock's own. +// After them the axe's wisps (only for a rock's own break) and Keeper's Kin's spiders. +void GridEntity_Rock::SpawnDrops(const RockDrop& drop) +{ + RockRoll roll = {.drop = drop, + .dropRng = {drop.seed, 5, 9, 7}, + .ownerRng = {drop.seed, 2, 7, 7}, + .velocityRng = {drop.seed, 1, 9, 29}, + .backdropType = drop.backdropType ? drop.backdropType : g_game->room->backdropType}; + roll.altRock = alt_rock_type_get(roll.backdropType); + roll.isCorpse = std::find(std::begin(CORPSE_BACKDROPS), std::end(CORPSE_BACKDROPS), roll.backdropType) != + std::end(CORPSE_BACKDROPS); + Entity_Player* axe = g_notchedAxePlayer; + if (axe && axe->HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) roll.rolls = AXE_ROLLS; + + for (; roll.rolls > 0; roll.rolls--) + { + if (drop.type == GRID_ROCK_GOLD) gold_coins_spawn(roll); + lucky_rock_coins_spawn(roll); + RollEnd end = ROLL_NEXT; + if (drop.type == GRID_ROCKT || drop.type == GRID_ROCK_SS) end = tinted_drops_spawn(roll); + else if (drop.type == GRID_ROCK_ALT || drop.type == GRID_ROCK_ALT2) end = alt_drops_spawn(roll); + if (end == ROLL_STOP) break; + } + + if (drop.origin == ROCK_DROP_BROKEN && axe) axe_wisps_spawn(*axe, drop); + keepers_kin_spiders_spawn(drop.position, drop.seed, drop.source); } // 0071dee0 Sets the countdown on the event rocks and empty event pits beside a cell, so they break or fill in turn. diff --git a/src/grid_entity_rock.h b/src/grid_entity_rock.h index e4dc1c4..5e2a4ff 100644 --- a/src/grid_entity_rock.h +++ b/src/grid_entity_rock.h @@ -14,6 +14,27 @@ enum RockState : int ROCK_STATE_CRACKED }; +// Which break a rock's drops come from: the rock's own Destroy (a Notched Axe swing's wisps roll there) or one landed +// elsewhere (a thrown rock, a Siren). +enum RockDropOrigin +{ + ROCK_DROP_BROKEN, + ROCK_DROP_LANDED +}; + +// What GridEntity_Rock::SpawnDrops drops for: a rock of a type and layout variant at a position, from a seed, on a +// backdrop (the room's for 0), broken by a source. +struct RockDrop +{ + Vector position{}; + Entity* source = nullptr; + GridEntityType type = GRID_ROCK; + RockDropOrigin origin = ROCK_DROP_BROKEN; + int backdropType = 0; + int variant = 0; + uint32_t seed = 0; +}; + // Destruction (0070b950) is the default. The rubble animation's getter (005cd820) is the public field. A rock of any // kind (Lua's GridEntityRock): // plain, tinted, bomb, super secret, spiked, gold, metal blocks and pillars. A big rock spans four cells. Broken, it @@ -43,8 +64,7 @@ struct GridEntity_Rock : GridEntity void TrySpawnWorms(); static void PlayBreakSound(GridEntityType type, int backdropType); bool TrySpawnLadder(); - static void SpawnDrops(const Vector& position, GridEntityType type, int variant, uint32_t seed, int backdropType, - Entity* source); + static void SpawnDrops(const RockDrop& drop); }; void grid_mark_neighbors_dirty(int gridIndex); diff --git a/src/grid_entity_statue.cpp b/src/grid_entity_statue.cpp index 6207317..237fab9 100644 --- a/src/grid_entity_statue.cpp +++ b/src/grid_entity_statue.cpp @@ -52,8 +52,8 @@ static bool is_angel_unlocked() (manager.state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge._id != 0 || g_game->isDebug)); } -// Picks the angel a statue breaks into: the one not met yet, or the one whose key piece is still missing, else a -// coin flip from the statue's rng. +// Picks the angel a statue breaks into: the one not met yet (alive or killed in the room), or the one whose key piece is +// still missing, else a coin flip from the statue's rng. static int angel_pick(RNG& rng) { Game& game = *g_game; @@ -73,6 +73,11 @@ static int angel_pick(RNG& rng) isUrielPresent |= entity->type == ENTITY_URIEL; isGabrielPresent |= entity->type == ENTITY_GABRIEL; } + for (const KilledNpc& fallen : game.room->killedNpcs) + { + isUrielPresent |= fallen.type == ENTITY_URIEL; + isGabrielPresent |= fallen.type == ENTITY_GABRIEL; + } bool isUrielSpawned = game.gameStateFlags & 1ull << GAME_STATE_URIEL_SPAWNED; bool isGabrielSpawned = game.gameStateFlags & 1ull << GAME_STATE_GABRIEL_SPAWNED; @@ -85,7 +90,6 @@ static int angel_pick(RNG& rng) // 00838560 Breaks a standing angel statue into Uriel or Gabriel (once angels are unlocked), with the boss music, the // doors shut and the room no longer clear. Devil statues do not break. -// The room keeps no records of the NPCs killed in it (Room::record_killed_npc), so a dead angel is not counted. bool GridEntity_Statue::Destroy(bool, const EntityRef&) { if (state != STATUE_STATE_STANDING || variant != STATUE_ANGEL) return false; diff --git a/src/grid_entity_teleporter.cpp b/src/grid_entity_teleporter.cpp index da95d54..1cfb90c 100644 --- a/src/grid_entity_teleporter.cpp +++ b/src/grid_entity_teleporter.cpp @@ -1,16 +1,104 @@ #include "grid_entity_teleporter.h" -#include "log.h" +#include "boss_ai.h" +#include "entity_player.h" +#include "game.h" +#include "room.h" +#include "room_config.h" +#include +#include -// 00838eb0 Loads the pad. +// The pads' looks: seven variants, Gehenna's own. +constexpr int TELEPORTER_VARIANT_LAST = 6; + +// A player within 21 of the pad's centre stands on it. Arriving, the player's landing hurts what is within 30. +constexpr float TELEPORTER_REACH = 21; +constexpr float TELEPORTER_LANDING_DAMAGE = 40; +constexpr float TELEPORTER_LANDING_RADIUS = 30; +constexpr float TELEPORTER_LANDING_PLAYER_THRESHOLD = 50; + +// The grid path a pad keeps on its cell, so walkers go around it. +constexpr int TELEPORTER_PATH = 999; + +// 00838eb0 Loads the pad of its variant (Gehenna's on that floor) and shows it on. void GridEntity_Teleporter::subclass_init() { - reconstruction_missing("GridEntity_Teleporter::subclass_init 00838eb0"); + int look = std::clamp(variant, 0, TELEPORTER_VARIANT_LAST); + std::string path = "gfx/grid/grid_teleporter" + (look ? std::to_string(look + 1) : std::string()) + + (g_game->GetStageID() == STAGE_ID_GEHENNA ? "_gehenna" : "") + ".anm2"; + sprite.Load(path, GRAPHICS_LOAD); + sprite.Play("IdleOn"); + g_game->room->isUnknown11f5 = false; } -// 00838c30 Teleports a player standing on the pad. +// The first player standing on the pad that collides with anything. +static Entity_Player* teleporter_player_find(GridEntity_Teleporter& pad) +{ + Vector center = pad.Position(); + for (Entity_Player* player : g_game->playerManager.playerList) + { + bool isSolid = player->entityGridCollisionClass > 0 || player->entityCollisionClass > 0; + bool isNear = vector_length(vector_sub(center, player->pos)) < TELEPORTER_REACH; + if (player->variant == 0 && isSolid && isNear) return player; + } + return nullptr; +} + +// Sends a player on the pad to the next pad of its variant along the grid, hurting what is around where it lands. A +// pad without a partner in a teleporter room leads to the floor's other teleporter room, else it switches off. +static void teleporter_use(GridEntity_Teleporter& pad, Entity_Player& player) +{ + Room& room = *g_game->room; + int cells = room.gridWidth * room.gridHeight; + int cell = pad.gridIndex; + for (int scanned = 0; scanned < cells - 2; scanned++) + { + cell = (cell + 1) % cells; + GridEntity* other = (uint32_t)cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; + if (!other || other->type != GRID_TELEPORTER || other->variant != pad.variant) continue; + + player.Teleport(other->Position(), true, true); + damage_radius({.position = other->Position(), + .source = &player, + .damageFlags = DAMAGE_EXPLOSION, + .damage = TELEPORTER_LANDING_DAMAGE, + .playerDamageThreshold = TELEPORTER_LANDING_PLAYER_THRESHOLD, + .radius = TELEPORTER_LANDING_RADIUS}); + if (other->state == 0) other->state = TELEPORTER_STATE_ON; + return; + } + + if (room.roomType != ROOM_TELEPORTER && room.roomType != ROOM_TELEPORTER_EXIT) + { + pad.state = TELEPORTER_STATE_OFF; + return; + } + int target = room.roomType == ROOM_TELEPORTER ? ROOM_TELEPORTER_EXIT : ROOM_TELEPORTER; + int roomIndex = g_game->QueryRoomTypeIndex(target, false, pad.rng, true); + if (roomIndex < 0) return; + + g_game->StartRoomTransition({.player = &player, .animation = TRANSITION_TELEPORT, .roomIndex = roomIndex}); + g_game->roomTransition.teleporterTarget = pad.variant + 1; +} + +// 00838c30 A pad a player just arrived on waits for the player to step off. A switched off pad shows off once it has +// turned off. Else it shows on and sends a player standing on it away. The pad's cell stays out of the walkers' paths. void GridEntity_Teleporter::Update() { - reconstruction_missing("GridEntity_Teleporter::Update 00838c30"); + if (state == TELEPORTER_STATE_ON) + { + if (!teleporter_player_find(*this)) state = 0; + } + else if (state == TELEPORTER_STATE_OFF) + { + if (!sprite.IsPlaying("TurnOff")) sprite.Play("IdleOff"); + } + else + { + if (!sprite.IsPlaying("TurnOn")) sprite.Play("IdleOn"); + if (Entity_Player* player = teleporter_player_find(*this)) teleporter_use(*this, *player); + } + path_set(TELEPORTER_PATH); + sprite.Update(); } // 00711f30 Draws the sprite on its cell. diff --git a/src/grid_entity_teleporter.h b/src/grid_entity_teleporter.h index 64f74f8..107b09d 100644 --- a/src/grid_entity_teleporter.h +++ b/src/grid_entity_teleporter.h @@ -2,7 +2,7 @@ #include "grid_entity.h" -// A teleporter pad switched on, and off. +// A teleporter pad a player just arrived on (waiting for the player to step off), and one switched off. constexpr int TELEPORTER_STATE_ON = 1; constexpr int TELEPORTER_STATE_OFF = 2; diff --git a/src/grid_entity_trap_door.cpp b/src/grid_entity_trap_door.cpp index 4b446b4..e209148 100644 --- a/src/grid_entity_trap_door.cpp +++ b/src/grid_entity_trap_door.cpp @@ -1,4 +1,5 @@ #include "grid_entity_trap_door.h" +#include "boss_pool.h" #include "entity_effect.h" #include "entity_familiar.h" #include "entity_list.h" @@ -37,7 +38,6 @@ constexpr int STAGE_LAST_CHAPTER = 10; constexpr int GAME_STATE_BACKWARDS_PATH_INIT = 47; // Mother's boss room in the special rooms. -constexpr int BOSS_MOTHER = 88; constexpr int MINES_LAYER_HIDDEN = 1; constexpr float PLAYER_FAR = 1e9f; @@ -268,7 +268,7 @@ static void trapdoor_enter(GridEntity_TrapDoor& trapDoor, Entity_Player& player, else { if ((int)game.stage > STAGE_LAST_CHAPTER) - game.seedEffects.ForgetStageSeed((int)game.stage + (game.IsAltPath() ? 1 : 0)); + game.seedEffects.ForgetStageSeed(game.stage_depth_get()); if (trapDoor.varData == TRAPDOOR_VOID_PORTAL) game.stageTransition.start({.type = STAGE_TRANSITION_VOID}); else if (!isRepentancePath || !is_knife_piece_missing()) game.stageTransition.start({.type = STAGE_TRANSITION_NEXT}); diff --git a/src/hud.cpp b/src/hud.cpp index 9fe0db2..8480c4b 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -1,4 +1,6 @@ #include "hud.h" +#include "boss_pool.h" +#include "fx_layers.h" #include "item_pickup.h" #include "entity_player.h" #include "game.h" @@ -63,8 +65,6 @@ constexpr float TITLE_Y_LOCALIZED = 2; constexpr float SUBTITLE_Y = 18; constexpr float SUBTITLE_Y_CURSE = 26; constexpr float STREAK_TEXT_RISE = 9; -constexpr KColor WHITE = kcolor_rgba(1, 1, 1, 1); -constexpr KColor BLACK = kcolor_rgba(0, 0, 0, 1); constexpr KAGE::Graphics::BlendMode BLEND_MODE_PREMULTIPLIED = { KAGE::Graphics::EQUATION_ADD, KAGE::Graphics::FACTOR_ONE, KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA, KAGE::Graphics::FACTOR_ONE, KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA}; @@ -86,9 +86,7 @@ constexpr float STATS_ALPHA = 0.5f; constexpr int COLOR_INDEX_NONE = 5; constexpr int STB_HOME = 35; -constexpr int BOSS_MEGA_SATAN = 55; constexpr int BOSS_GREAT_GIDEON = 83; -constexpr int BOSS_MOTHER = 88; constexpr uint32_t ROOM_FLAG_CLEAR = 1; constexpr int ONLINE_HUD_COMPACT = 1; constexpr int ONLINE_HUD_HIDDEN = 2; diff --git a/src/item_config.cpp b/src/item_config.cpp index 2b765fa..f9ffff1 100644 --- a/src/item_config.cpp +++ b/src/item_config.cpp @@ -42,7 +42,6 @@ constexpr int SPECIAL_CHARGE_SEGMENTS_LAST = 12; // Ids and values the availability and charge rules name. constexpr int COLLECTIBLE_SACRED_ORB = 691; constexpr int COLLECTIBLE_VANISHING_TWIN = 697; -constexpr unsigned int CHALLENGE_ONANS_STREAK = 29; constexpr unsigned int SPECIAL_DAILY_BANNED_SET = 52; constexpr uint32_t STAGE_VANISHING_TWIN_LAST = 6; constexpr int QUALITY_LOW_LAST = 1; diff --git a/src/item_info_hud.cpp b/src/item_info_hud.cpp index cc1c9ac..84d5962 100644 --- a/src/item_info_hud.cpp +++ b/src/item_info_hud.cpp @@ -3,6 +3,7 @@ #include "game.h" #include "log.h" #include "manager.h" +#include "persistent_game_data.h" #include "room.h" constexpr const char* ITEM_INFO_FONT = "font/TeamMeatEx/TeamMeatEx12.fnt"; @@ -11,7 +12,6 @@ constexpr const char* MINIMAP_ICONS_ANM2 = "gfx/ui/minimap_icons.anm2"; constexpr const char* ANIMATION_CHARGE_ICON = "ChargeIcon"; constexpr float ITEM_INFO_LINE_SPACING = 0.9f; constexpr float ITEM_INFO_ICON_SCALE = 4; -constexpr int ACHIEVEMENT_ITEM_INFO = 641; // 0083c5f0 Loads the panel's font (without redirection), charge icon and map icons. void ItemInfoHUD::load_graphics() diff --git a/src/item_pickup.cpp b/src/item_pickup.cpp index f638368..1bd53b2 100644 --- a/src/item_pickup.cpp +++ b/src/item_pickup.cpp @@ -9,6 +9,7 @@ #include "game.h" #include "grid_entity.h" #include "item_pool.h" +#include "level.h" #include "log.h" #include "manager.h" #include "room.h" @@ -35,7 +36,6 @@ constexpr int COLLECTIBLE_KNIFE_PIECE_A = 626; constexpr int COLLECTIBLE_KNIFE_PIECE_B = 627; constexpr int COLLECTIBLE_GLITCHED_GFUEL = -1; constexpr int ACHIEVEMENT_GLITCHED_ITEMS = 593; -constexpr int DIMENSION_DEATH_CERTIFICATE = 2; constexpr int EVENT_ANGEL_ITEMS_TAKEN = 15; constexpr uint32_t MONSTER_MANUEL_ODDS = 3; @@ -84,7 +84,6 @@ constexpr int SOUND_BAND_AID_PICK_UP = 169; constexpr int ONE_UP_FRAME_DELAY = 30; constexpr float ITEM_SOUND_HALF_VOLUME = 0.5f; constexpr int COLLECTIBLE_SUPER_BANDAGE = 92; -constexpr int COLLECTIBLE_MINI_MUSH = 71; // The sprite named for its file's question mark, which Curse of the Blind shows on every pedestal. constexpr std::string_view QUESTION_MARK_GFX = "gfx/Items/Collectibles/questionmark.png"; diff --git a/src/item_pool.cpp b/src/item_pool.cpp index b8cd47b..8a77e82 100644 --- a/src/item_pool.cpp +++ b/src/item_pool.cpp @@ -1,4 +1,5 @@ #include "item_pool.h" +#include "boss_pool.h" #include "data.h" #include "entity_config.h" #include "entity_player.h" @@ -89,11 +90,9 @@ constexpr uint32_t DEBUG_GOLDEN_TRINKETS = 0x8; constexpr uint32_t TRINKET_GOLDEN = 0x8000; constexpr uint32_t STATE_SATANIC_BIBLE_USED = 0x20000; constexpr uint32_t DESCRIPTOR_DEVIL_TREASURE = 0x800; -constexpr int BOSS_THE_FALLEN = 23; constexpr int HOME_CHEST_SUBTYPE = 2; constexpr int COLLECTIBLE_ROSARY = 72; -constexpr uint32_t CHALLENGE_ONANS_STREAK = 29; constexpr int ACHIEVEMENT_GOLDEN_TRINKETS = 617; constexpr int ACHIEVEMENT_GOLD_PILLS = 603; constexpr int ACHIEVEMENT_HORSE_PILLS = 606; diff --git a/src/leaderboard.cpp b/src/leaderboard.cpp index f265bb1..86163ce 100644 --- a/src/leaderboard.cpp +++ b/src/leaderboard.cpp @@ -1,4 +1,5 @@ #include "leaderboard.h" +#include "fx_layers.h" #include "game.h" #include "log.h" #include "manager.h" @@ -18,7 +19,6 @@ constexpr int ROWS_PER_PAGE = 10; constexpr int GAME_FADE_TARGET_MENU = 2; constexpr float GAME_FADE_SPEED = 0.08f; constexpr float BUTTON_HIDDEN = 96; -constexpr uint32_t BLACK_ARGB = 0xff000000; constexpr float DIM_SHADE = 0.3f; constexpr float DIM_ALPHA = 0.5f; diff --git a/src/level.cpp b/src/level.cpp index 43885c1..a3d9748 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -12,6 +12,7 @@ #include "music_manager.h" #include "manager.h" #include "npc_ai.h" +#include "persistent_game_data.h" #include "platform.h" #include "room.h" #include "room_config.h" @@ -85,8 +86,6 @@ constexpr uint32_t SPECIAL_DAILY_DEALS = 17; constexpr uint32_t SPECIAL_DAILY_CURSED = 37; constexpr uint32_t SPECIAL_DAILY_CURSES = CURSE_OF_THE_LOST | CURSE_OF_THE_UNKNOWN | CURSE_OF_BLIND; -constexpr int ACHIEVEMENT_EVERYTHING_IS_TERRIBLE = 33; -constexpr int ACHIEVEMENT_STRANGE_DOOR = 635; constexpr int ACHIEVEMENT_SOMETHING_FROM_THE_FUTURE = 16; constexpr int ACHIEVEMENT_SOMETHING_CUTE = 17; constexpr int ACHIEVEMENT_SOMETHING_STICKY = 18; @@ -113,11 +112,9 @@ constexpr int TREASURE_SUBTYPE_KNIFE_PIECE = 34; constexpr int LIL_PORTAL_ROOM_VARIANT = 2; constexpr int GRID_SPAWN_PIT_FIRST = 3000; constexpr int GRID_SPAWN_PIT_END = 3010; -constexpr int ROOM_INDEX_OTHER_DIMENSION = -100; constexpr int ROOM_INDEX_MIRRORED_START = -101; constexpr int MIRROR_START_GRID_INDEX = 162; constexpr int MIRROR_START_SUBTYPE = 10; -constexpr int BOSS_RUSH_PAR_TIME = 36000; constexpr int BOSS_RUSH_PAR_TIME_ALT = 45000; constexpr uint32_t BACKWARDS_STAGE_END = 8; constexpr size_t BACKWARDS_ROOMS_KEPT = 2; @@ -130,13 +127,10 @@ constexpr int STATE_SUPER_GREED_SPAWNED = 16; constexpr int STATE_DONATION_SLOT_BLOWN = 30; constexpr int STATE_SHOPKEEPER_KILLED = 31; constexpr int STATE_ULTRA_PRIDE_SPAWNED = 32; -constexpr int DEATH_CERTIFICATE_DIMENSION = 2; constexpr int ROOM_SCREEN_WIDTH = 13; constexpr int ROOM_SCREEN_HEIGHT = 7; constexpr int START_ROOM_VARIANT = 2; constexpr int ULTRA_SECRET_GROUP = 99; -constexpr int BOSS_MEGA_SATAN = 55; -constexpr int BOSS_MOTHER = 88; constexpr int BOSS_MOTHER_HEART = 89; constexpr int BOSS_MOMS_HEART_MAUSOLEUM = 90; constexpr int BOSS_ROOM_RETRIES = 50; @@ -1027,6 +1021,12 @@ bool Level::IsAltPath() return stageType == STAGETYPE_REPENTANCE || stageType == STAGETYPE_REPENTANCE_B; } +// The floor's depth, one deeper on the alternate path, as 004360f0 counts it. +int Level::stage_depth_get() +{ + return (int)stage + (IsAltPath() ? 1 : 0); +} + // 0074f090 Whether the floor is one of the Ascent's. bool Level::IsAscent() { @@ -2186,7 +2186,7 @@ bool Level::IsNextStageAvailable() int type = isRedRedemption ? GetRoomStageType(currentRoomIdx) : (int)stageType; ChallengeParam& params = game.GetChallengeParams(); - if ((isRedRedemption || currentDimensionIdx != DEATH_CERTIFICATE_DIMENSION) && + if ((isRedRedemption || currentDimensionIdx != DIMENSION_DEATH_CERTIFICATE) && RoomConfig::GetStageID(nextStage, type, ROOM_MODE_CURRENT) == STAGE_ID_BACKWARDS) return false; if (IsPreAscent() || nextStage >= (int)STAGE_DARK_ROOM || @@ -2474,8 +2474,9 @@ static void corpse_door_splats_spawn(Level& level) Vector direction = direction_unit(door->direction); int gridIndex = (int)door->gridIndex; - Vector out = {-direction.x, -direction.y}; - Vector across = {out.x * rotationCos - out.y * rotationSin, out.x * rotationSin + out.y * rotationCos}; + Vector out = vector_make(-direction.x, -direction.y); + Vector across = + vector_make(out.x * rotationCos - out.y * rotationSin, out.x * rotationSin + out.y * rotationCos); float baseX = out.x * SPLAT_DOOR_OFFSET + (float)(gridIndex % room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_X; float baseY = out.y * SPLAT_DOOR_OFFSET + (float)(gridIndex / room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_Y; @@ -2486,7 +2487,7 @@ static void corpse_door_splats_spawn(Level& level) float rowY = baseY + out.y * along * SPLAT_LENGTH; float rowX = baseX + along * SPLAT_LENGTH * out.x; float spread = (rng.RandomFloat() - 0.5f) * along * SPLAT_SPREAD; - EntitySpawn spawn = {.position = {across.x * spread + rowX, rowY + spread * across.y}, + EntitySpawn spawn = {.position = vector_make(across.x * spread + rowX, rowY + spread * across.y), .type = ENTITY_EFFECT, .variant = EFFECT_VARIANT_BLOOD_SPLAT, .seed = seed}; @@ -2604,7 +2605,7 @@ void Level::load_room() int roomStageType = game.challenge == CHALLENGE_RED_REDEMPTION ? GetRoomStageType(currentRoomIdx) : (int)stageType; bool isCorpse = RoomConfig::GetStageID((int)stage, roomStageType, ROOM_MODE_CURRENT) == STAGE_ID_CORPSE; - if ((game.challenge == CHALLENGE_RED_REDEMPTION || currentDimensionIdx != DEATH_CERTIFICATE_DIMENSION) && + if ((game.challenge == CHALLENGE_RED_REDEMPTION || currentDimensionIdx != DIMENSION_DEATH_CERTIFICATE) && isCorpse && room->backdropType != BACKDROP_CORPSE3) corpse_door_splats_spawn(*this); if (currentRoomIdx == ROOM_GENESIS_IDX && room->descriptor->visitedCount == 1) diff --git a/src/level.h b/src/level.h index be23bde..9039149 100644 --- a/src/level.h +++ b/src/level.h @@ -25,8 +25,13 @@ constexpr int PORTAL_ROOM_NONE = -99999; // The xorshift a level's RNGs start on before Level::Init seeds them (shift index 35). constexpr RNG LEVEL_RNG_DEFAULT = {RNG_SEED_DEFAULT, 5, 9, 7}; -// The mirror world's dimension, the mineshaft's on a Mines floor. +// The mirror world's dimension (the mineshaft's on a Mines floor) and Death Certificate's. constexpr int DIMENSION_MIRROR = 1; +constexpr int DIMENSION_DEATH_CERTIFICATE = 2; + +// The room index of a room in another dimension, and the Boss Rush's par time in frames. +constexpr int ROOM_INDEX_OTHER_DIMENSION = -100; +constexpr int BOSS_RUSH_PAR_TIME = 36000; // The secret exit a floor's door leads to, also the exit room's layout subtype. Mom's Heart's leads to the Corpse // and the Ascent. @@ -334,6 +339,7 @@ public: int GetAbsoluteStage(); bool IsAltStage(); bool IsAltPath(); + int stage_depth_get(); bool IsAscent(); bool IsPreAscent(); bool IsMausoleumHeartStage(); diff --git a/src/manager_input.cpp b/src/manager_input.cpp index d090443..ecc9e18 100644 --- a/src/manager_input.cpp +++ b/src/manager_input.cpp @@ -2,18 +2,17 @@ #include "game.h" #include "manager.h" #include "menu_manager.h" +#include "persistent_game_data.h" constexpr int KEYBOARD_ID = 0; // The keyboard button that asks for the render surfaces to be remade. No key sends it on this platform. constexpr int KEY_RESIZE_REQUEST = 12; -constexpr int EVENT_EDEN_TOKENS = 21; constexpr uint8_t RESTART_HOLD_FRAMES = 16; constexpr float RESTART_FADE_SPEED = 1.0f / 30; constexpr float RESTART_CANCEL_FADE_SPEED = 2.0f / 15; constexpr float GAME_OVER_FADE_SPEED = 0.08f; constexpr float POPUP_BUTTON_HIDDEN = 96; // The achievement that unlocks the item info toggle, and the toggle's action past Lua's ButtonAction. -constexpr int ACHIEVEMENT_ITEM_INFO = 641; constexpr ButtonAction ACTION_ITEM_INFO = (ButtonAction)31; // Whether a main player holds restart: the keyboard's player with the keyboard's restart, any other player with the @@ -43,7 +42,7 @@ static bool is_restart_held(PlayerManager& players) // a token), and fades back if let go before the restart. static void restart_update(Game& game) { - int edenTokens = g_manager->persistentGameData.eventCounters[EVENT_EDEN_TOKENS]; + int edenTokens = g_manager->persistentGameData.eventCounters[EVENT_COUNTER_EDEN_TOKENS]; Entity_Player* first = game.GetPlayer(0); bool isEden = first && (first->playerType == PLAYER_EDEN || first->playerType == PLAYER_EDEN_B); bool isHeld = is_restart_held(game.playerManager); diff --git a/src/menu_challenge.cpp b/src/menu_challenge.cpp index 452c038..d39c74e 100644 --- a/src/menu_challenge.cpp +++ b/src/menu_challenge.cpp @@ -1,4 +1,5 @@ #include "menu_challenge.h" +#include "fx_layers.h" #include "log.h" #include "manager.h" #include "menu_manager.h" @@ -18,7 +19,6 @@ constexpr int LAST_CHALLENGE = CHALLENGE_COUNT - 1; constexpr int KEYBOARD_DEVICE = 0; constexpr int LOBBY_MODE_NONE = 0; constexpr int LOBBY_MODE_CHALLENGE = 4; -constexpr uint32_t BLACK_ARGB = 0xff000000; // The view scrolls with the cursor past the fourth challenge, a row at a time, up to the last rows. constexpr int SCROLL_FIRST_ROW = 5; diff --git a/src/menu_character.cpp b/src/menu_character.cpp index f9f1a05..2dee77e 100644 --- a/src/menu_character.cpp +++ b/src/menu_character.cpp @@ -1,9 +1,11 @@ #include "menu_character.h" +#include "fx_layers.h" #include "game.h" #include "kage_input.h" #include "log.h" #include "manager.h" #include "menu_manager.h" +#include "persistent_game_data.h" #include "texture_cache.h" #include #include @@ -118,8 +120,6 @@ constexpr int PLAYER_EDEN = 9; constexpr int PLAYER_TAINTED_EDEN = 30; constexpr int MENU_ID_RANDOM = 0; constexpr int MENU_ID_EDEN = 10; -constexpr int EVENT_EDEN_TOKENS = 21; -constexpr int EVENT_STREAK_COUNTER = 22; constexpr int EVENT_NEGATIVE_STREAK_COUNTER = 113; constexpr int ACHIEVEMENT_GREEDIER = 341; constexpr int SOUND_CHARACTER_SELECT_LEFT = 194; @@ -158,10 +158,8 @@ constexpr float WHEEL_DEPTH_GROWTH = 0.01f; constexpr int WHEEL_CROWD = 10; constexpr float WHEEL_WIDTH_SCALE = 1.3f; constexpr float WHEEL_SPEED_SCALE = 50; -constexpr float FULL_TURN = 360; constexpr float HALF_TURN = 180; constexpr float QUARTER_TURN = 90; -constexpr float TAU = 6.2831855f; constexpr float SPIN_EASE_START = 60; constexpr float SPIN_EASE_LENGTH = -60; constexpr float SPIN_SLOWDOWN = 6; @@ -205,8 +203,6 @@ constexpr MenuOffset EDEN_TOKENS_OFFSET = {240, 215}; constexpr float UNLOCK_TITLE_Y = -26; constexpr uint32_t INK_ARGB = 0xff362f2d; constexpr uint32_t EGG_COUNT_ARGB = 0xff3d3234; -constexpr uint32_t BLACK_ARGB = 0xff000000; -constexpr uint32_t CLEAR_ARGB = 0; // The GLFW keys the seed entry reads. enum SeedKey : int @@ -286,7 +282,7 @@ static bool is_player_available(int playerType) if (!player || player->achievement < 0) return true; bool isEden = playerType == PLAYER_EDEN || playerType == PLAYER_TAINTED_EDEN; - bool isTokenMissing = isEden && manager.persistentGameData.eventCounters[EVENT_EDEN_TOKENS] == 0; + bool isTokenMissing = isEden && manager.persistentGameData.eventCounters[EVENT_COUNTER_EDEN_TOKENS] == 0; return manager.persistentGameData.Unlocked(player->achievement) && !isTokenMissing; } @@ -507,7 +503,7 @@ void Menu_Character::Reset() float farScale = halfDepth + 1; float ratio = halfDepth / farScale; characterWheelWidth = (farScale - ratio * halfDepth) * WHEEL_WIDTH_SCALE / std::sqrt(1 - ratio * ratio); - scrollSpeed = FULL_TURN / (float)numCharacters / (characterWheelWidth * WHEEL_SPEED_SCALE); + scrollSpeed = FULL_TURN_DEGREES / (float)numCharacters / (characterWheelWidth * WHEEL_SPEED_SCALE); portraitPositions.assign(numCharacters, vector_make(WHEEL_X, WHEEL_Y)); portraitScales.assign(numCharacters, 1.0f); @@ -517,7 +513,7 @@ void Menu_Character::Reset() chosenRandomCharacter = 0; numCharactersMinusSelectedEntry = numCharacters - 1; randomRotationVelocity = 0; - horizontalScrollPosition = (float)numCharactersMinusSelectedEntry * FULL_TURN / (float)numCharacters; + horizontalScrollPosition = (float)numCharactersMinusSelectedEntry * FULL_TURN_DEGREES / (float)numCharacters; difficulty = (Difficulty)data.lastDifficulty; seedText.clear(); menus.seedsObject.set_start_seed(Seeds::String2Seed("")); @@ -639,7 +635,7 @@ void Menu_Character::Update() eastereggPageSprite.Play(g_menuManager->seedsObject.CountSeedEffects() == 0 ? ANIMATION_NO_EGGS : ANIMATION_EGGS); if (data.eventCounters[EVENT_NEGATIVE_STREAK_COUNTER] != 0) winStreakPageSprite.Play(ANIMATION_STREAK_BAD); - else if (data.eventCounters[EVENT_STREAK_COUNTER] != 0) winStreakPageSprite.Play(ANIMATION_STREAK_GOOD); + else if (data.eventCounters[EVENT_COUNTER_STREAK] != 0) winStreakPageSprite.Play(ANIMATION_STREAK_GOOD); } // Starts the run on the selected character, difficulty and seeds, spending an Eden token on Eden and ending the win @@ -649,9 +645,9 @@ void Menu_Character::run_start() Manager& manager = *g_manager; PersistentGameData& data = manager.persistentGameData; - if (selectedCharacterID == MENU_ID_EDEN) data.IncreaseEventCounter(EVENT_EDEN_TOKENS, -1); + if (selectedCharacterID == MENU_ID_EDEN) data.IncreaseEventCounter(EVENT_COUNTER_EDEN_TOKENS, -1); if (manager.gamestate.isSaveAvailable) - data.IncreaseEventCounter(EVENT_STREAK_COUNTER, -data.eventCounters[EVENT_STREAK_COUNTER]); + data.IncreaseEventCounter(EVENT_COUNTER_STREAK, -data.eventCounters[EVENT_COUNTER_STREAK]); progress_save(); int playerType = GetPlayerTypeFromMenuID(selectedCharacterID, characterMenuShown); manager.StartNewGame(playerType, 0, g_menuManager->seedsObject, difficulty); @@ -711,7 +707,7 @@ void Menu_Character::page_layers_update() void Menu_Character::wheel_rotate(int portrait) { float angle = -((float)portrait * TAU / (float)numCharacters); - float target = FULL_TURN / (float)numCharacters * (float)numCharactersMinusSelectedEntry; + float target = FULL_TURN_DEGREES / (float)numCharacters * (float)numCharactersMinusSelectedEntry; float speed = scrollSpeed; if (status == CHARACTER_STATUS_RANDOM_SPIN) { @@ -732,8 +728,8 @@ void Menu_Character::wheel_rotate(int portrait) } else if (status == CHARACTER_STATUS_RANDOM_SPIN) random_spin_step(); else isInputPossible = true; - if (scroll < 0) scroll = FULL_TURN; - else if (scroll > FULL_TURN) scroll = 0; + if (scroll < 0) scroll = FULL_TURN_DEGREES; + else if (scroll > FULL_TURN_DEGREES) scroll = 0; float angleCos = (float)std::cos((double)angle); float angleSin = (float)std::sin((double)angle); @@ -787,7 +783,7 @@ void Menu_Character::SelectRandomChar() chosenRandomCharacter = chosen; randomRotationAmount = chosen + numCharacters * SPIN_TURNS; - randomRotationVelocity = FULL_TURN / (float)numCharacters / SPIN_FRAMES; + randomRotationVelocity = FULL_TURN_DEGREES / (float)numCharacters / SPIN_FRAMES; for (int i = 0; i < std::min(chosen, CHARACTER_ENTRY_COUNT); i++) randomRotationAmount -= !is_on_wheel(i); EntityConfig_Player* player = @@ -1095,7 +1091,7 @@ void Menu_Character::Render() render_seed_page(origin); winStreakPageSprite.Render({offset_add(origin, WIN_STREAK_OFFSET)}); - int streak = data.eventCounters[EVENT_STREAK_COUNTER]; + int streak = data.eventCounters[EVENT_COUNTER_STREAK]; int negativeStreak = data.eventCounters[EVENT_NEGATIVE_STREAK_COUNTER]; std::string streakText = streak == 0 && negativeStreak != 0 ? "-" + std::to_string((unsigned int)negativeStreak) : std::to_string((unsigned int)streak); @@ -1181,7 +1177,7 @@ void Menu_Character::render_wheel(Vector wheelPosition, WheelPortraits portraits std::string_view format = string_table_translate(g_manager->stringTable, EDEN_TOKENS_KEY); std::array text{}; std::snprintf(text.data(), text.size(), std::string(format).c_str(), - g_manager->persistentGameData.eventCounters[EVENT_EDEN_TOKENS]); + g_manager->persistentGameData.eventCounters[EVENT_COUNTER_EDEN_TOKENS]); text_draw_centered(g_manager->font2_TeamMeatEx12, text.data(), offset_add(wheelPosition, EDEN_TOKENS_OFFSET)); } bool isHard = difficulty == DIFFICULTY_HARD || difficulty == DIFFICULTY_GREEDIER; diff --git a/src/menu_collection.cpp b/src/menu_collection.cpp index f5dd3d1..77637b2 100644 --- a/src/menu_collection.cpp +++ b/src/menu_collection.cpp @@ -1,5 +1,6 @@ #include "menu_collection.h" #include "entity_player.h" +#include "fx_layers.h" #include "manager.h" #include "menu_manager.h" #include "render_passes.h" @@ -39,7 +40,6 @@ constexpr float BULLET_SPAN = 100; constexpr int BULLET_GAPS = 3; constexpr uint32_t OUTLINE_ARGB = 0xff362f2d; constexpr uint32_t DETAIL_ARGB = 0xff787261; -constexpr uint32_t WHITE_ARGB = 0xffffffff; // The keyframes of one layer's track in an animation of a sprite, none when it has no such track. static std::span layer_frames_get(const ANM2& sprite, std::string_view animation, int layer) diff --git a/src/menu_controller_select.cpp b/src/menu_controller_select.cpp index 711c0f4..c104b92 100644 --- a/src/menu_controller_select.cpp +++ b/src/menu_controller_select.cpp @@ -1,4 +1,5 @@ #include "menu_controller_select.h" +#include "fx_layers.h" #include "kage_input.h" #include "manager.h" #include "menu_manager.h" @@ -14,7 +15,6 @@ constexpr float LIST_X = 265; constexpr float LIST_Y = 60; constexpr float ROW_HEIGHT = 20; constexpr float ROW_SLANT = 4; -constexpr uint32_t TEXT_ARGB = 0xff362f2d; // Loads the menu, playing, and resets it, at its place on the menu sheet. Inlined in MenuManager::Init. void Menu_ControllerSelect::Init(Vector menuPosition) diff --git a/src/menu_custom_challenge.cpp b/src/menu_custom_challenge.cpp index 404990a..e023692 100644 --- a/src/menu_custom_challenge.cpp +++ b/src/menu_custom_challenge.cpp @@ -1,4 +1,5 @@ #include "menu_custom_challenge.h" +#include "fx_layers.h" #include "manager.h" #include "menu_challenge.h" #include "menu_manager.h" @@ -10,7 +11,6 @@ constexpr const char* ANIMATION_BOTTOM = "Bottom"; constexpr const char* ANIMATION_CURSOR = "Cursor"; constexpr const char* ENTRY_FORMAT = "{}.{}"; constexpr const char* PIECE_FORMAT = "Piece{}"; -constexpr uint32_t BLACK_ARGB = 0xff000000; constexpr int SOUND_DELAY = 2; constexpr int FIRST_MOD_CHALLENGE = CHALLENGE_COUNT; constexpr float CHALLENGE_VIEW_Y = -216; diff --git a/src/menu_daily_challenge.cpp b/src/menu_daily_challenge.cpp index 6c25f19..2dcaa19 100644 --- a/src/menu_daily_challenge.cpp +++ b/src/menu_daily_challenge.cpp @@ -1,4 +1,5 @@ #include "menu_daily_challenge.h" +#include "fx_layers.h" #include "log.h" #include "manager.h" #include "menu_manager.h" @@ -22,8 +23,6 @@ constexpr const char* COUNTDOWN_FORMAT = "{:02}:{:02}:{:02}"; constexpr int CURSOR_LAYER = 5; constexpr int SKETCH_PAPER_LAYER = 11; constexpr int POPUP_PICTURE_LAYER = 2; -constexpr uint32_t TEXT_ARGB = 0xff362f2d; -constexpr uint32_t BLACK_ARGB = 0xff000000; constexpr float BUTTON_HIDDEN = 96; constexpr int LANGUAGE_ENGLISH = 0; diff --git a/src/menu_game.cpp b/src/menu_game.cpp index 98629f9..66ecb3d 100644 --- a/src/menu_game.cpp +++ b/src/menu_game.cpp @@ -1,4 +1,5 @@ #include "menu_game.h" +#include "fx_layers.h" #include "game.h" #include "game_state_player.h" #include "log.h" @@ -29,9 +30,6 @@ constexpr int KEYBOARD_DEVICE = 0; constexpr float CONTINUE_IMAGE_X = 72; constexpr float CONTINUE_IMAGE_Y = 124; constexpr ColorMod CONTINUE_IMAGE_COLOR = {{1, 0.5f, 0.5f, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; -constexpr uint32_t BLACK_ARGB = 0xff000000; -constexpr uint32_t WHITE_ARGB = 0xffffffff; -constexpr uint32_t CLEAR_ARGB = 0; constexpr const char* ANIMATION_CHARACTER = "Character"; constexpr const char* TIME_NULL = "Time"; diff --git a/src/menu_key_config.cpp b/src/menu_key_config.cpp index 5adaeb1..a170e31 100644 --- a/src/menu_key_config.cpp +++ b/src/menu_key_config.cpp @@ -1,4 +1,5 @@ #include "menu_key_config.h" +#include "fx_layers.h" #include "manager.h" #include "menu_manager.h" #include @@ -6,7 +7,6 @@ constexpr const char* KEY_CONFIG_ANM2 = "gfx/ui/main menu/KeyConfigMenu.anm2"; constexpr ColorMod BINDING_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.6862745f, 0, 0}}; -constexpr uint32_t TEXT_ARGB = 0xff362f2d; constexpr int ACTION_TOGGLE_DESCRIPTIONS = 31; constexpr int CURSOR_LAYER = 6; constexpr int KEYBOARD_ID = 0; diff --git a/src/menu_manager.cpp b/src/menu_manager.cpp index 32d5ed4..3f23915 100644 --- a/src/menu_manager.cpp +++ b/src/menu_manager.cpp @@ -1,4 +1,5 @@ #include "menu_manager.h" +#include "fx_layers.h" #include "game.h" #include "kage_input.h" #include "log.h" @@ -37,7 +38,6 @@ constexpr float FLY_Y = 176; constexpr int FLY_FLAP_FRAMES = 80; constexpr float FLY_HEIGHT = 8; constexpr float FLY_SHADOW_SCALE = 0.4f; -constexpr float TAU = 6.2831855f; constexpr int FLY_LAYER = 0; constexpr int FLY_SHADOW_LAYER = 1; @@ -52,8 +52,6 @@ constexpr float VIGNETTE_HARD = 0.5f; constexpr float SHADOW_HEIGHT = 148; constexpr float OVERLAY_BLEED = 0.5f; constexpr uint32_t MENU_BACKGROUND_ARGB = 0xffccbebb; -constexpr uint32_t WHITE_ARGB = 0xffffffff; -constexpr uint32_t BLACK_ARGB = 0xff000000; constexpr float CHANNEL_MAX = 255; constexpr int CLAMP_TO_EDGE = 1; constexpr int FILTER_LINEAR = 1; diff --git a/src/menu_options.cpp b/src/menu_options.cpp index 0344047..b7aba39 100644 --- a/src/menu_options.cpp +++ b/src/menu_options.cpp @@ -7,6 +7,7 @@ #include "manager.h" #include "pause_screen.h" #include "menu_manager.h" +#include "persistent_game_data.h" #include "render_passes.h" #include "texture_cache.h" #include @@ -67,7 +68,6 @@ constexpr int ONLINE_COLOR_SET_COUNT = 4; constexpr int ONLINE_LEVEL_MAX = 10; constexpr int INPUT_DELAY_MIN = 1; constexpr int INPUT_DELAY_MAX = 5; -constexpr int ACHIEVEMENT_ITEM_INFO = 641; constexpr int CONTROLLER_UNSET = -1; // How a row draws: its animation, and the layer its value picks the frame of (none when it shows its value otherwise). diff --git a/src/menu_save.cpp b/src/menu_save.cpp index 8755e37..11e4886 100644 --- a/src/menu_save.cpp +++ b/src/menu_save.cpp @@ -2,6 +2,7 @@ #include "log.h" #include "manager.h" #include "menu_manager.h" +#include "persistent_game_data.h" #include #include #include @@ -42,18 +43,12 @@ constexpr const char* SHARED_SAVE_FILE = "sharedsave"; constexpr const char* SAVE_FILE_EXTENSION = ".dat"; constexpr const char* BACKUP_FOLDER = "save_backups/"; -constexpr int ACHIEVEMENT_DEAD_GOD = 637; -constexpr int ACHIEVEMENT_STRANGE_DOOR = 635; constexpr int ACHIEVEMENT_JUST_STOP = 339; constexpr int ACHIEVEMENT_1001_PERCENT = 235; constexpr int ACHIEVEMENT_REAL_PLATINUM_GOD = 84; constexpr int ACHIEVEMENT_PLATINUM_GOD = 69; constexpr int ACHIEVEMENT_GOLDEN_GOD = 41; -constexpr int ACHIEVEMENT_ANGELS = 155; -constexpr int ACHIEVEMENT_BLUE_BABY = 32; constexpr int ACHIEVEMENT_FETUS = 11; -constexpr int ACHIEVEMENT_EVERYTHING_IS_TERRIBLE = 33; -constexpr int ACHIEVEMENT_WOMB = 4; constexpr int EVENT_MOM_KILLS = 1; constexpr int EVENT_ISAAC_KILLS = 11; constexpr int EVENT_SATAN_KILLS = 13; @@ -531,7 +526,7 @@ void Menu_Save::replace_slot_graphics(ANM2& sprite) drawing = "03_Heart.png"; heartPieces = std::min((unsigned int)data.eventCounters[EVENT_MOM_KILLS], HEART_PIECES); } - else drawing = is_unlocked(ACHIEVEMENT_WOMB) ? "02_MomKill.png" : "01_Basement.png"; + else drawing = is_unlocked(ACHIEVEMENT_THE_WOMB) ? "02_MomKill.png" : "01_Basement.png"; sprite.ReplaceSpritesheet(DRAWING_LAYER, std::string(DRAWING_FOLDER) + drawing); sprite.GetLayer(DRAWING_LAYER)->isVisible = true; diff --git a/src/menu_special_seeds.cpp b/src/menu_special_seeds.cpp index a602e25..21ece7a 100644 --- a/src/menu_special_seeds.cpp +++ b/src/menu_special_seeds.cpp @@ -1,5 +1,6 @@ #include "menu_special_seeds.h" #include "data.h" +#include "fx_layers.h" #include "log.h" #include "manager.h" #include "menu_manager.h" @@ -54,7 +55,6 @@ constexpr float SPACER_HEIGHT = 6; // The text colors: buttons and effects that stay on, effects the selected line would turn off, effects off, and // effects off that cannot join the ones on. -constexpr uint32_t TEXT_ARGB = 0xff362f2d; constexpr uint32_t TEXT_DROPPED_ARGB = 0xff962c2c; constexpr uint32_t TEXT_OFF_ARGB = 0xff8f8988; constexpr uint32_t TEXT_BLOCKED_ARGB = 0xffbdb5b3; diff --git a/src/minimap.cpp b/src/minimap.cpp index a0d1959..e10bfb6 100644 --- a/src/minimap.cpp +++ b/src/minimap.cpp @@ -1,6 +1,7 @@ #include "minimap.h" #include "entity_pickup.h" #include "entity_player.h" +#include "fx_layers.h" #include "game.h" #include "hud.h" #include "level.h" @@ -9,6 +10,7 @@ #include "menu_manager.h" #include "menu_options.h" #include "room.h" +#include "seeds.h" #include #include #include @@ -57,7 +59,6 @@ constexpr int TAP_FRAMES = 9; constexpr int SHOW_NAME_FRAMES = 10; constexpr float SHAKE_DIVISOR = 10; constexpr float SHAKE_KEEP = 0.5f; -constexpr float RANDOM_SCALE = 2.3283064e-10f; constexpr float HALF_TURN = 3.14f; constexpr float HUD_INSET_X = 24; @@ -74,7 +75,6 @@ constexpr float LARGE_ICONS_Y = 16 + 8; constexpr float DEFAULT_DISPLAYED_SIZE = 47; constexpr float SCORE_HISTORY_ALPHA = 0.5f; constexpr int HISTORY_HUD_ON = 1; -constexpr uint32_t WHITE_ARGB = 0xffffffff; constexpr int ICON_LIMIT = 7; constexpr int ICON_STACK_START = 4; @@ -86,7 +86,6 @@ constexpr int ICON_TREASURE_MAP = 2; constexpr int ICON_RESTOCK = 4; constexpr int ICON_MIND = 5; -constexpr int CHALLENGE_SPEED = 22; constexpr int SPEED_TIME_LIMIT = 28800; constexpr int FRAMES_PER_SECOND = 30; constexpr int FRAMES_PER_MINUTE = FRAMES_PER_SECOND * 60; @@ -106,7 +105,6 @@ constexpr float TIME_Y = 30; constexpr float SCORE_Y = 46; constexpr RNG APRILS_FOOL_RNG = {0, 1, 5, 16}; -constexpr int DIMENSION_DEATH_CERTIFICATE = 2; constexpr int SUBTYPE_MINESHAFT_ENTRANCE = 10; constexpr int SUBTYPE_MIRROR_ROOM = 34; constexpr int SUBTYPE_BOSS_AMBUSH = 1; @@ -772,7 +770,7 @@ void Minimap::Update() if (shakeDuration > 0) { shakeDuration--; - float angle = (float)Random() * RANDOM_SCALE * HALF_TURN * 2; + float angle = random_unit() * HALF_TURN * 2; float magnitude = (float)shakeDuration / SHAKE_DIVISOR; shakeOffset = vector_make(std::cos(angle) * magnitude + shakeOffset.x * SHAKE_KEEP, std::sin(angle) * magnitude + shakeOffset.y * SHAKE_KEEP); diff --git a/src/nightmare_scene.cpp b/src/nightmare_scene.cpp index 484d327..8d4216e 100644 --- a/src/nightmare_scene.cpp +++ b/src/nightmare_scene.cpp @@ -8,6 +8,14 @@ #include "manager.h" #include "entity_config.h" #include "entity_player.h" +#include "entity_factory.h" +#include "entity_pickup.h" +#include "item_config.h" +#include "kage_graphics.h" +#include "level.h" +#include "mod_manager.h" +#include "room.h" +#include "room_config.h" #include "render_passes.h" #include "menu_manager.h" #include "seeds.h" @@ -83,9 +91,6 @@ void NightmareScene::order_shuffle() std::swap(nightmareOrder[i], nightmareOrder[Random() % (uint32_t)(i + 1)]); } -// The characters whose portrait floats on the background's alternate layer: ???, Keeper, The Forgotten and The Soul, -// and the tainted ???, Keeper and Forgotten. -constexpr std::array ALT_PORTRAIT_PLAYERS = {4, 16, 17, 14, 25, 35, 33}; constexpr int PORTRAIT_LAYER = 2; constexpr int PORTRAIT_ALT_LAYER = 6; constexpr int BOSS_SPOT_LAYER = 3; @@ -115,11 +120,164 @@ constexpr int STAGE_BAR_LAST = 6; constexpr int STAGE_BAR_LAST_WOMB = 8; constexpr int STAGE_BAR_LAST_GREED = 7; constexpr int STAGE_HOME_SLOT = 13; -constexpr int ACHIEVEMENT_WOMB = 4; constexpr int CLOCK_LAST_STAGE = 6; +// Dream Catcher's diary: the death screen's diary page, tinted, its delay before the pages turn, and where on the +// bubble its item and boss pictures go (the exe's table at 00c5d250). +constexpr std::string_view DIARY_ANM2 = "gfx/ui/Death Screen.anm2"; +constexpr ColorMod DIARY_COLOR = {{1.1616f, 1.3218f, 1.5972f, 1}, {0, 0, 0, 0}, {-0.1283f, -0.126f, -0.1642f}}; +constexpr int SCENE_DELAY = 40; +constexpr int DREAM_CATCHER_SCENE_DELAY = 10; +constexpr int DREAM_CATCHER_ITEM_LAYER = 6; +constexpr int DREAM_CATCHER_BOSS_LAYER = 3; +constexpr int DREAM_CATCHER_DOUBLE_TROUBLE_FIRST = 3700; +constexpr int DREAM_CATCHER_DOUBLE_TROUBLE_COUNT = 150; +constexpr uint32_t ROOM_SPAWN_SHIFT_1 = 2; +constexpr uint32_t ROOM_SPAWN_SHIFT_2 = 7; +constexpr uint32_t ROOM_SPAWN_SHIFT_3 = 7; +constexpr float ROOM_SPAWN_PICK_SCALE = 2.3283062e-10f; + +// A picture on a diary page: the bubble's null it follows, the diary layer drawing it, its offset, and which of the +// page's two items or bosses it shows. +struct DiaryPicture +{ + std::string_view nullName; + Vector offset; + int layerId = 0; + int slot = 0; +}; + +// The item and boss pictures of a diary page. +static std::array diary_pictures() +{ + return {{{"Item", vector_make(84, -20), DREAM_CATCHER_ITEM_LAYER, 0}, + {"Item2", vector_make(84, -20), DREAM_CATCHER_ITEM_LAYER, 1}, + {"Boss", vector_make(-21, 30), DREAM_CATCHER_BOSS_LAYER, 0}, + {"Boss2", vector_make(-21, 30), DREAM_CATCHER_BOSS_LAYER, 1}}}; +} + +// The entry a room spawn picks with the room's spawn RNG, turned into what the room would make of it. +static RoomEntry room_spawn_pick(RoomConfig_Room& data, RoomSpawn& spawn, uint32_t seed) +{ + RoomEntry entry = *spawn.PickEntry((float)seed * ROOM_SPAWN_PICK_SCALE); + int gridIndex = spawn.x + 1 + (spawn.y + 1) * data.width; + room_entry_transform(*g_game->room, entry, gridIndex, seed); + return entry; +} + +// The treasure room More Options swaps in: a room of the same shape and doors from the floor's own set on an +// alternate floor, with the options' subtype. +static RoomConfig_Room* more_options_room(RoomDescriptor& room) +{ + Game& game = *g_game; + RoomConfig_Room& data = *room.data; + if (data.subtype != 0 && data.subtype != 2) return &data; + + int stageId = STAGE_ID_SPECIAL_ROOMS; + if (game.IsAltPath() && game.stage <= STAGE_DEPTHS_II) + stageId = STAGE_ID_DOWNPOUR + (int)((game.stage - 1) / 2) * 2 + (game.stageType != STAGETYPE_REPENTANCE ? 1 : 0); + RNG rng{room.spawnSeed, 1, 5, 16}; + RoomQuery query{.requiredDoors = data.doors, + .mode = ROOM_MODE_CURRENT, + .shape = data.shape, + .maxDifficulty = 10, + .minDifficulty = 1, + .stageId = stageId, + .subtype = data.subtype == 0 ? 1 : 3, + .type = ROOM_TREASURE}; + RoomConfig_Room* other = game.roomConfig.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); + return other ? other : &data; +} + +// Part of 00921ce0: a treasure room's diary page, the room's first two collectibles as its spawns would roll them, a +// poop page for none. +static DreamCatcherPage treasure_page_get(RoomDescriptor& room) +{ + Game& game = *g_game; + RoomConfig_Room* data = room.data; + if (game.playerManager.FirstCollectibleOwner(COLLECTIBLE_MORE_OPTIONS, LAZARUS_SHARE_CHECK)) data = more_options_room(room); + + DreamCatcherPage page; + RNG rng{room.spawnSeed, ROOM_SPAWN_SHIFT_1, ROOM_SPAWN_SHIFT_2, ROOM_SPAWN_SHIFT_3}; + int count = 0; + for (RoomSpawn& spawn : data->spawns) + { + if (count > 1) break; + uint32_t seed = rng.Next(); + if (spawn.entries.empty()) continue; + + RoomEntry entry = room_spawn_pick(*data, spawn, seed); + RNG entryRng{seed, 5, 9, 7}; + entryRng.Next(); + if (entry.type != ENTITY_PICKUP || entry.variant != PICKUP_COLLECTIBLE) continue; + int id = entry.subtype != 0 ? entry.subtype : game.itemPool.GetSeededCollectible(entryRng.Next(), 1, room); + page.items[count++] = g_manager->itemConfig.GetCollectible(id); + } + page.anim = count == 0 ? "TreasureRoomPoop" : count == 1 ? "TreasureRoom" : "TreasureRoomDouble"; + return page; +} + +// Part of 00921ce0: a boss room's diary page, its bosses as its spawns would roll them (Mom after Mom's Heart fell in +// the Mausoleum, her room spawning none), both on a Double Trouble page. +static DreamCatcherPage boss_page_get(RoomDescriptor& room) +{ + Game& game = *g_game; + RoomConfig_Room& data = *room.data; + EntityConfig& configs = g_manager->entityConfig; + std::array bosses{}; + std::array bossIds{}; + + RNG rng{room.spawnSeed, ROOM_SPAWN_SHIFT_1, ROOM_SPAWN_SHIFT_2, ROOM_SPAWN_SHIFT_3}; + for (auto spawn = data.spawns.rbegin(); spawn != data.spawns.rend(); spawn++) + { + uint32_t seed = rng.Next(); + if (spawn->entries.empty()) continue; + + RoomEntry entry = room_spawn_pick(data, *spawn, seed); + EntityConfig_Entity* config = configs.GetEntity((int)entry.type, entry.variant, entry.subtype); + if (!config || !config->bossID) continue; + if (bossIds[0] == 0) + { + bossIds[0] = config->bossID; + bosses[0] = config; + } + else if (config->bossID != bossIds[0]) + { + bossIds[1] = config->bossID; + bosses[1] = config; + } + } + bool isMomsAgain = (game.gameStateFlags & (1ull << LEVEL_GAME_STATE_MAUSOLEUM_HEART_KILLED)) && game.stage == STAGE_DEPTHS_II; + if (data.spawns.empty() && isMomsAgain) bosses[0] = configs.GetEntity(ENTITY_MOM, 0, 0); + + bool isDoubleTrouble = data.type == ROOM_BOSS && data.variant >= DREAM_CATCHER_DOUBLE_TROUBLE_FIRST && + data.variant < DREAM_CATCHER_DOUBLE_TROUBLE_FIRST + DREAM_CATCHER_DOUBLE_TROUBLE_COUNT; + if (!isDoubleTrouble) return {.anim = "Boss", .bosses = {bosses[0], nullptr}}; + return {.anim = "BossDoubleTrouble", .bosses = {bosses[0], bossIds[1] ? bosses[1] : bosses[0]}}; +} + +// Part of 00921ce0: Dream Catcher's diary of the floor ahead, a page for each treasure room then for each boss room +// (Greed's last only) on the main map. +static void dream_catcher_pages_get(NightmareScene& scene) +{ + Game& game = *g_game; + for (int i = 0; i < game.nbRooms; i++) + { + RoomDescriptor& room = game.roomList[i]; + if (room.dimension == 0 && room.data && room.data->type == ROOM_TREASURE && room.group == -1) + scene.dreamCatcherPages.push_back(treasure_page_get(room)); + } + for (int i = 0; i < game.nbRooms; i++) + { + RoomDescriptor& room = game.roomList[i]; + if (room.dimension != 0 || !room.data || room.data->type != ROOM_BOSS || room.group != -1) continue; + if (game.IsGreedMode() && game.lastBossRoomListIdx != room.listIndex) continue; + scene.dreamCatcherPages.push_back(boss_page_get(room)); + } +} + // 00921ce0 Starts the nightmare: the next one in the order (G FUEL's own with its seed, Dogma's at Home, Dream -// Catcher's showing the next floor), the player's portrait (an animated one too) on the floor's boss spot, the stage +// Catcher's diary of the floor's treasure and boss rooms), the player's portrait (an animated one too) on the floor's boss spot, the stage // bar's position before the new floor, and the nightmare jingle. Netplay's input sync is left out, as the game is // offline. void NightmareScene::Show(bool isSameStageShown) @@ -136,12 +294,22 @@ void NightmareScene::Show(bool isSameStageShown) promo.Load(promoPath, GRAPHICS_LOAD); if (promo.isLoaded) scenePath = promoPath; } - dreamCatcherAnims.clear(); + sceneDelay = SCENE_DELAY; + isDreamCatcher = false; + dreamCatcherPages.clear(); if (isDogma) scenePath = DOGMA_ANM2; else if (game.playerManager.FirstCollectibleOwner(COLLECTIBLE_DREAM_CATCHER, LAZARUS_SHARE_CHECK) && game.stage != STAGE_HOME) { - reconstruction_missing("NightmareScene::Show 00921ce0: Dream Catcher's diary of the next floor's items and bosses"); + if (!diarySprite.isLoaded) + { + diarySprite.Load(DIARY_ANM2, GRAPHICS_LOAD); + diarySprite.Play("Diary"); + diarySprite.color = DIARY_COLOR; + } + isDreamCatcher = true; + sceneDelay = DREAM_CATCHER_SCENE_DELAY; + dream_catcher_pages_get(*this); scenePath = DREAM_CATCHER_ANM2; } @@ -237,7 +405,7 @@ static StageBar stage_bar_get(NightmareScene& scene) else { bool isDailyOrDebug = manager.state == MANAGER_STATE_GAME && (game.dailyChallenge._id != 0 || game.isDebug); - if (manager.persistentGameData.achievements[ACHIEVEMENT_WOMB] || isDailyOrDebug || + if (manager.persistentGameData.achievements[ACHIEVEMENT_THE_WOMB] || isDailyOrDebug || scene.stageIndex > STAGE_BAR_LAST_GREED || (scene.stageIndex == STAGE_BAR_LAST && !scene.isSameStage)) last = STAGE_BAR_LAST_WOMB; ChallengeParam& challenge = game.GetChallengeParams(); @@ -324,6 +492,73 @@ static void stage_bar_render(NightmareScene& scene) bar_render_at(sprite, slotX(bar.playerSlot) - walked * (float)bar.walk * BAR_SLOT); } +// One item or boss of a diary page, its layer of the diary set from the bubble's null and showing its frame. +static void diary_picture_render(ANM2& diary, DreamCatcherPage& page, const DiaryPicture& picture, const NullFrame& null) +{ + Vector position = vector_add(diary.offset, null.pos); + int frame = 0; + if (picture.layerId == DREAM_CATCHER_ITEM_LAYER) + { + ItemConfig_Item* item = page.items[picture.slot]; + if (!item) return; + if (item->id >= COLLECTIBLE_VANILLA_COUNT) + { + bool isPremultiplied = KAGE::Graphics::manager.isPremultipliedAlpha; + ModSpriteDraw draw{.blendMode = {BLEND_EQUATION_ADD, isPremultiplied ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA, + BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, BLEND_FACTOR_ONE, + BLEND_FACTOR_ONE_MINUS_SRC_ALPHA}, + .color = null.color, + .position = position, + .scale = null.scale}; + return g_manager->modManager.RenderCustomCollectionItem(item->id, draw); + } + frame = item->id - 1; + } + else + { + EntityConfig_Entity* boss = page.bosses[picture.slot]; + if (!boss) return; + if (boss->modEntry && boss->isPortraitModded) + { + ANM2& portrait = boss->modEntry->contentSprites[MOD_SPRITE_DEATH_ENEMIES]; + if (!portrait.isLoaded) return; + portrait.SetFrame(portrait.GetDefaultAnimationName(), boss->portrait); + portrait.color = null.color; + portrait.scale = null.scale; + return portrait.Render({.position = position}); + } + frame = boss->portrait; + } + + LayerState* layer = diary.GetLayer(picture.layerId); + layer->pos = vector_add(picture.offset, null.pos); + layer->rotation = null.rotation; + layer->size = null.scale; + layer->color = null.color; + diary.SetLayerFrame(picture.layerId, frame); + diary.RenderLayer(picture.layerId, {}); +} + +// Part of 00920940: Dream Catcher's bubble with the diary page turning in it, the page's items and bosses drawn on +// the diary where the bubble's nulls put them, a modded one from its mod's sheet. +static void diary_render(NightmareScene& scene) +{ + ANM2& bubble = scene.bubbleSprite; + ANM2& diary = scene.diarySprite; + bubble.animState.Render({}, bubble); + if (diary.isLoaded && !scene.dreamCatcherPages.empty() && bubble.overlayAnimState.animData) + { + DreamCatcherPage& page = scene.dreamCatcherPages.front(); + diary.offset = bubble.offset; + for (const DiaryPicture& picture : diary_pictures()) + { + const NullFrame* null = bubble.overlayAnimState.GetNullFrame(picture.nullName); + if (null && null->isVisible) diary_picture_render(diary, page, picture, *null); + } + } + bubble.overlayAnimState.Render({}, bubble); +} + // 00920940 Draws the nightmare over a cleared screen: the background with the portrait, the bubble (Dream Catcher's // diary of the next floor), the stage bar but at Dogma's, and the fade. void NightmareScene::Render() @@ -334,7 +569,7 @@ void NightmareScene::Render() if (!isActive) return; background_render(*this); - if (isDreamCatcher) reconstruction_missing("NightmareScene::Render 00920940: Dream Catcher's diary"); + if (isDreamCatcher) diary_render(*this); else if (bubbleSprite.isLoaded) bubbleSprite.Render({}); if (!isDogma) stage_bar_render(*this); if (fadeAlpha <= 0) return; @@ -348,7 +583,7 @@ void NightmareScene::Render() static bool is_scene_finished(NightmareScene& scene) { AnimationState& state = scene.bubbleSprite.animState; - return scene.isDreamCatcher ? scene.dreamCatcherAnims.empty() : !state.animData || !state.isPlaying; + return scene.isDreamCatcher ? scene.dreamCatcherPages.empty() : !state.animData || !state.isPlaying; } // Plays the next of Dream Catcher's animations on the bubble's overlay, once the one before ended. @@ -359,10 +594,10 @@ static void dream_catcher_update(NightmareScene& scene) if (overlay.animData && overlay.isPlaying) return; if (overlay.animData) { - scene.dreamCatcherAnims.pop_front(); - if (scene.dreamCatcherAnims.empty()) return; + scene.dreamCatcherPages.pop_front(); + if (scene.dreamCatcherPages.empty()) return; } - scene.bubbleSprite.PlayOverlay(scene.dreamCatcherAnims.front(), PLAY_FORCED); + scene.bubbleSprite.PlayOverlay(scene.dreamCatcherPages.front().anim, PLAY_FORCED); if (scene.bubbleSprite.layerStates.size() > BUBBLE_STATIC_LAYER) scene.bubbleSprite.GetLayer(BUBBLE_STATIC_LAYER)->bitflags |= STATIC_LAYER_FLAGS; } @@ -378,7 +613,7 @@ static float fade_alpha_get(NightmareScene& scene) if (!bubble.isLoaded) return 0; if (!scene.isDreamCatcher) framesLeft = (bubble.animState.animData ? bubble.animState.animData->length : 0) - bubble.GetFrame(); - else if (scene.dreamCatcherAnims.size() > 1 || !overlay.isPlaying) return 0; + else if (scene.dreamCatcherPages.size() > 1 || !overlay.isPlaying) return 0; else framesLeft = overlay.animData ? overlay.animData->length - (int)overlay.animFrame : 1; return 1 - std::clamp((float)framesLeft / FADE_FRAMES, 0.0f, 1.0f); } @@ -409,7 +644,7 @@ void NightmareScene::Update() { bubbleSprite.Update(); if (frame == sceneFrame) bubbleSprite.Play(SCENE_ANIM, PLAY_FORCED); - if (isDreamCatcher && !dreamCatcherAnims.empty() && frame > sceneFrame && + if (isDreamCatcher && !dreamCatcherPages.empty() && frame > sceneFrame && (!bubbleSprite.animState.animData || !bubbleSprite.animState.isPlaying)) dream_catcher_update(*this); if (isDogma && bubbleSprite.animState.animData && bubbleSprite.animState.IsEventTriggered(INTERRUPT_EVENT)) diff --git a/src/nightmare_scene.h b/src/nightmare_scene.h index fa75480..ef2244d 100644 --- a/src/nightmare_scene.h +++ b/src/nightmare_scene.h @@ -14,6 +14,17 @@ constexpr int STAGE_ICON_COUNT = 14; // Home's icon on the nightmare's stage strip. constexpr int STAGE_ICON_HOME = 27; +struct EntityConfig_Entity; +struct ItemConfig_Item; + +// A page of Dream Catcher's diary: the animation that turns to it and the items (a treasure room's) or bosses on it. +struct DreamCatcherPage +{ + std::string anim; + std::array items{}; + std::array bosses{}; +}; + // Destruction (00950f10) is the default. // The nightmare between floors (g_manager->nightmareScene): a nightmare of nightmares.xml in its bubble over the // background (the player's portrait on the floor's spot), the stage bar of the floors so far with Isaac walking to the @@ -22,7 +33,7 @@ constexpr int STAGE_ICON_HOME = 27; struct NightmareScene { std::array stageIcons{}; - std::deque dreamCatcherAnims; + std::deque dreamCatcherPages; std::vector nightmarePaths; std::vector nightmareOrder; ANM2 backgroundSprite; diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index 6e554ab..5c58ddb 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -4,6 +4,7 @@ #include "game.h" #include "manager.h" #include "npc_fireplace.h" +#include "npc_gehenna.h" #include "room_grid.h" #include "room_special.h" #include "sfx_manager.h" @@ -331,7 +332,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 253: return npc_swarmer_update(npc); case 92: - return (void)NpcAI::ENTITY_HEART(&npc); + return npc_heart_update(npc); case 93: if (npc.state == NPC_STATE_INIT) return mask_heart_pair(npc); return boss_mask_of_infamy_update(npc); @@ -340,7 +341,8 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 97: return boss_mask_of_infamy_update(npc); case 98: - if (npc.state == NPC_STATE_INIT) npc.state = NPC_STATE_MOVE; + if (npc.state != NPC_STATE_INIT) return npc_heart_update(npc); + npc.state = NPC_STATE_MOVE; return; case 99: return boss_gurdy_jr_update(npc); @@ -519,13 +521,13 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 805: return (void)NpcAI::ENTITY_BISHOP(&npc); case 806: - return (void)NpcAI::ENTITY_BUBBLES(&npc); + return npc_bubbles_update(npc); case 808: return npc_willo_update(npc); case 809: return npc_bomb_grimace_update(npc); case 810: - return (void)NpcAI::ENTITY_SMALL_LEECH(&npc); + return npc_small_leech_update(npc); case 811: return npc_deep_gaper_update(npc); case 812: @@ -541,7 +543,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 818: return npc_rock_spider_update(npc); case 820: - return (void)NpcAI::ENTITY_DANNY(&npc); + return npc_danny_update(npc); case 821: return npc_blaster_update(npc); case 822: @@ -557,11 +559,11 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 827: return npc_faceless_update(npc); case 828: - return (void)NpcAI::ENTITY_NECRO(&npc); + return npc_necro_update(npc); case 829: return npc_mole_update(npc); case 830: - return (void)NpcAI::ENTITY_BIG_BONY(&npc); + return npc_big_bony_update(npc); case 831: return (void)NpcAI::ENTITY_GUTTED_FATTY(&npc); case 832: @@ -569,17 +571,17 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 833: return (void)NpcAI::ENTITY_CANDLER(&npc); case 834: - return (void)NpcAI::ENTITY_WHIPPER(&npc); + return npc_whipper_update(npc); case 835: return (void)NpcAI::ENTITY_PEEPER_FATTY(&npc); case 837: - return (void)NpcAI::ENTITY_HENRY(&npc); + return npc_henry_update(npc); case 838: return (void)NpcAI::ENTITY_WILLO_L2(&npc); case 841: - return (void)NpcAI::ENTITY_REVENANT(&npc); + return npc_revenant_update(npc); case 844: - return (void)NpcAI::ENTITY_BOMBGAGGER(&npc); + return npc_bomb_gagger_update(npc); case 850: return (void)NpcAI::ENTITY_GAPER_L2(&npc); case 851: @@ -601,9 +603,9 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 861: return npc_pustule_update(npc); case 863: - return (void)NpcAI::ENTITY_MORNINGSTAR(&npc); + return npc_morningstar_update(npc); case 864: - return (void)NpcAI::ENTITY_MOCKULUS(&npc); + return npc_mockulus_update(npc); case 865: return (void)NpcAI::ENTITY_EVIS(&npc); case 866: @@ -613,45 +615,45 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 868: return npc_army_fly_update(npc); case 873: - return (void)NpcAI::ENTITY_FLY_TRAP(&npc); + return npc_fly_trap_update(npc); case 874: - return (void)NpcAI::ENTITY_FARTIGAN(&npc); + return npc_fartigan_update(npc); case 875: - return (void)NpcAI::ENTITY_POOT_MINE(&npc); + return npc_poot_mine_update(npc); case 876: - return (void)NpcAI::ENTITY_DUMP(&npc); + return npc_dump_update(npc); case 877: - return (void)NpcAI::ENTITY_GRUDGE(&npc); + return npc_grudge_update(npc); case 878: return (void)NpcAI::ENTITY_BUTT_SLICKER(&npc); case 879: return (void)NpcAI::ENTITY_BLOATY(&npc); case 880: - return (void)NpcAI::ENTITY_FLESH_MAIDEN(&npc); + return npc_flesh_maiden_update(npc); case 881: return npc_needle_update(npc); case 882: - return (void)NpcAI::ENTITY_DUST(&npc); + return npc_dust_update(npc); case 883: - return (void)NpcAI::ENTITY_BABY_BEGOTTEN(&npc); + return npc_baby_begotten_update(npc); case 884: - return (void)NpcAI::ENTITY_SWARM_SPIDER(&npc); + return npc_swarm_spider_update(npc); case 885: - return (void)NpcAI::ENTITY_CULTIST(&npc); + return npc_cultist_update(npc); case 886: return npc_vis_fatty_update(npc); case 887: - return (void)NpcAI::ENTITY_DUSTY_DEATHS_HEAD(&npc); + return npc_dusty_deaths_head_update(npc); case 888: return (void)NpcAI::ENTITY_SHADY(&npc); case 889: - return (void)NpcAI::ENTITY_CLICKETY_CLACK(&npc); + return npc_clickety_clack_update(npc); case 890: - return (void)NpcAI::ENTITY_MAZE_ROAMER(&npc); + return npc_maze_roamer_update(npc); case 891: - return (void)NpcAI::ENTITY_GOAT(&npc); + return npc_goat_update(npc); case 892: - return (void)NpcAI::ENTITY_POOFER(&npc); + return npc_poofer_update(npc); case 893: return (void)NpcAI::ENTITY_BALL_AND_CHAIN(&npc); case 900: diff --git a/src/npc_ai.h b/src/npc_ai.h index af7794a..fe66265 100644 --- a/src/npc_ai.h +++ b/src/npc_ai.h @@ -9,10 +9,7 @@ #include constexpr float RANDOM_HALF_TURN = 3.14f; -constexpr float FULL_TURN_DEGREES = 360; constexpr int GURGLING_TURDLING = 2; -constexpr float HALF_TURN_DEGREES = 180; -constexpr float RIGHT_ANGLE_DEGREES = 90; // Isaac::Random: a random number below max, or 0 for none. inline int random_below(int max) @@ -64,3 +61,7 @@ constexpr int SQUIRT_DANK = 1; constexpr int RAGLING_RAG_MAN = 1; constexpr int KNIGHT_BLACK = 4; constexpr int DANGLE = 1; + +// The splats poop enemies leave: the plain brown, and the lighter one of corn, Brownie's dips and the Dross. +constexpr ColorMod POOP_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.25490198f, 0.16078432f, 0.13725491f}}; +constexpr ColorMod LIGHT_POOP_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0}}; diff --git a/src/npc_alt.h b/src/npc_alt.h index e9b12dc..b6b2a18 100644 --- a/src/npc_alt.h +++ b/src/npc_alt.h @@ -10,6 +10,22 @@ constexpr ColorMod ROCK_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {30 / 255.0f, void npc_blaster_update(Entity_NPC& npc); void npc_quakey_update(Entity_NPC& npc); void npc_hardy_update(Entity_NPC& npc); +void npc_bubbles_update(Entity_NPC& npc); +void npc_small_leech_update(Entity_NPC& npc); +void npc_fly_trap_update(Entity_NPC& npc); +void fly_trap_fly_update(Entity_NPC& npc); +void npc_fartigan_update(Entity_NPC& npc); +void npc_dump_update(Entity_NPC& npc); +void npc_necro_update(Entity_NPC& npc); +void npc_dust_update(Entity_NPC& npc); +void npc_big_bony_update(Entity_NPC& npc); +void npc_danny_update(Entity_NPC& npc); +void npc_dusty_deaths_head_update(Entity_NPC& npc); +void npc_flesh_maiden_update(Entity_NPC& npc); +void npc_poot_mine_update(Entity_NPC& npc); +void npc_clickety_clack_update(Entity_NPC& npc); +void npc_henry_update(Entity_NPC& npc); +void npc_bomb_gagger_update(Entity_NPC& npc); // What rock_spider_throw throws: a rock, tinted or coal rock spider (their variants), or a coal fire (a fireplace). enum RockSpiderKind diff --git a/src/npc_baby_begotten.cpp b/src/npc_baby_begotten.cpp new file mode 100644 index 0000000..763c06a --- /dev/null +++ b/src/npc_baby_begotten.cpp @@ -0,0 +1,198 @@ +#include "npc_gehenna.h" +#include "boss_ai.h" +#include "entity_laser.h" +#include "entity_player.h" + +// The Baby Begotten floats toward its target, sidestepping out of the way a player aims, and keeps out of other +// Begottens' lines of attack. Close to its target it charges along the axis it lies on, then stops, recoils and +// fires a short beam that way. +constexpr int BEGOTTEN_CHARGE = NPC_STATE_ATTACK; +constexpr int BEGOTTEN_PATH_MARKER = 900; +constexpr int BEGOTTEN_FIRST_WAIT_MIN = 10; +constexpr int BEGOTTEN_WAIT_RANGE = 50; +constexpr int BEGOTTEN_WAIT_MIN = 30; +constexpr int BEGOTTEN_REST_RANGE = 60; +constexpr int BEGOTTEN_REST_MIN = 30; + +// Drifting: it heads for its target from 40 away, off to the side of a player's aim, and starts a charge one frame in +// eight once within 100. +constexpr float BEGOTTEN_DRIFT_FRICTION = 0.8f; +constexpr float BEGOTTEN_AIM_DODGE = -0.5f; +constexpr float BEGOTTEN_AIM_DODGE_BACK = 0.5f; +constexpr float BEGOTTEN_ROOM_MARGIN = 20; +constexpr float BEGOTTEN_KEEP_AWAY = 1600; +constexpr float BEGOTTEN_DRIFT_SCALE = 0.01f; +constexpr float BEGOTTEN_CHARGE_REACH = 100; +constexpr int BEGOTTEN_CHARGE_ODDS = 8; +constexpr int BEGOTTEN_CHARGE_FRAMES = 20; + +// Charging: it chases a spot 100 behind where its target heads, at 3% of the way (16 at most), until it stops. +constexpr float BEGOTTEN_CHARGE_FRICTION = 0.7f; +constexpr float BEGOTTEN_LEAD_FRAMES = 10; +constexpr float BEGOTTEN_CHARGE_BEHIND = 100; +constexpr float BEGOTTEN_CHASE_SHARE = 0.03f; +constexpr float BEGOTTEN_CHASE_MAX = 16; +constexpr float BEGOTTEN_RECOIL_FRICTION = 0.9f; +constexpr float BEGOTTEN_CRY_VOLUME = 0.8f; +constexpr float BEGOTTEN_CRY_PITCH = 1.15f; + +// The beam: short and thin, from 18 ahead of it at mouth height, drawn behind it when it shoots up. +static const Vector BEGOTTEN_BEAM_OFFSET = vector_make(0, -35); +constexpr float BEGOTTEN_BEAM_AHEAD = 18; +constexpr int BEGOTTEN_BEAM_TIMEOUT = 14; +constexpr float BEGOTTEN_BEAM_SCALE = 0.6f; +constexpr float BEGOTTEN_BEAM_REACH = 160; +constexpr float BEGOTTEN_BEAM_UP = -0.5f; +constexpr float BEGOTTEN_BEAM_FRONT_DEPTH = 1000; +constexpr float BEGOTTEN_BEAM_BACK_DEPTH = -10; + +// Plays one of a set of animations by an axis: the right one (flipped to face left) or the up or down one. +static void axis_play(Entity_NPC& npc, Vector axis, std::string_view right, std::string_view up, std::string_view down) +{ + bool isHorizontal = std::abs(axis.y) <= std::abs(axis.x); + npc.sprite.Play(isHorizontal ? right : axis.y >= 0 ? down : up); + npc.sprite.isFlipX = isHorizontal && axis.x < 0; +} + +// 006be7e0 (NpcHelper::is_target_valid) Whether it may attack a target: a visible player, or a vulnerable enemy not +// friendly when charmed. +static bool is_target_valid(Entity_NPC& npc, Entity& target) +{ + if (npc.HasEntityFlags(FLAG_CHARM)) return target.IsVulnerableEnemy(nullptr) && !target.HasEntityFlags(FLAG_FRIENDLY); + return target.type == ENTITY_PLAYER && !static_cast(target).IsInvisible(); +} + +// Whether another Begotten already charges the target from the same side. +static bool is_side_taken(Entity_NPC& npc, Entity& target, Vector axis) +{ + for (Entity* other : entity_query(ENTITY_BABY_BEGOTTEN, -1)) + { + auto* baby = static_cast(other); + bool isKin = baby != &npc && baby->to_npc_or_coop_player() && baby->IsFriendly() == npc.IsFriendly(); + if (!isKin || baby->state != BEGOTTEN_CHARGE || baby->target.get() != &target) continue; + if (axis_direction_get(vector_sub(target.pos, baby->pos)) == axis_direction_get(axis)) return true; + } + return false; +} + +// Drifting near its target and picking its moment and side to charge. +static void drift_update(Entity_NPC& npc, Entity& target, Vector goal, Vector toGoal) +{ + axis_play(npc, toGoal, "IdleRight", "IdleUp", "IdleDown"); + int ticks = npc_ticks_get(npc); + npc.i1 -= ticks; + npc.projectileDelay -= ticks; + npc.friction *= BEGOTTEN_DRIFT_FRICTION; + + Vector destination = goal; + if (target.type == ENTITY_PLAYER && !npc.HasEntityFlags(FLAG_DISTRACTED)) + { + Vector aim = static_cast(target).aimDirection; + float dodge = std::max(vector_dot(aim, toGoal) * BEGOTTEN_AIM_DODGE, 0.0f); + if (!vector_is_zero(aim) && dodge > 0) + { + Vector side = vector_rotated(vector_normalized(aim), RIGHT_ANGLE_DEGREES); + if (vector_dot(side, toGoal) > 0) side = vector_scale(side, -1); + Vector dodgeSpot = vector_add(vector_scale(side, dodge), vector_sub(goal, vector_scale(toGoal, BEGOTTEN_AIM_DODGE_BACK))); + destination = g_game->room->GetClampedPositionImpl(dodgeSpot, BEGOTTEN_ROOM_MARGIN, BEGOTTEN_ROOM_MARGIN, + BEGOTTEN_ROOM_MARGIN, BEGOTTEN_ROOM_MARGIN); + } + } + if (vector_length_squared(vector_sub(target.pos, npc.pos)) > BEGOTTEN_KEEP_AWAY) + npc_push(npc, vector_normalized(vector_scale(vector_sub(destination, npc.pos), BEGOTTEN_DRIFT_SCALE))); + + if (npc.HasEntityFlags(FLAG_DISTRACTED) || !is_target_valid(npc, target)) return; + if (vector_length(toGoal) >= BEGOTTEN_CHARGE_REACH || (Random() & (BEGOTTEN_CHARGE_ODDS - 1)) != 0) return; + + Vector axis = vector_cardinal(vector_sub(target.pos, npc.pos)); + if (is_side_taken(npc, target, axis)) return; + + npc.state = BEGOTTEN_CHARGE; + npc.targetPosition = axis; + npc.i1 = BEGOTTEN_CHARGE_FRAMES; + npc.target = ⌖ + axis_play(npc, axis, "ChaseRight", "ChaseUp", "ChaseDown"); +} + +// Its beam along its charge, from just ahead of it. +static void beam_fire(Entity_NPC& npc) +{ + Vector axis = npc.targetPosition; + Vector from = vector_make(axis.x * BEGOTTEN_BEAM_AHEAD + npc.pos.x, npc.pos.y); + Entity_Laser* beam = Entity_Laser::ShootAngle({.position = from, + .posOffset = BEGOTTEN_BEAM_OFFSET, + .source = &npc, + .angleDegrees = std::atan2(axis.y, axis.x) * RADIANS_TO_DEGREES, + .timeout = BEGOTTEN_BEAM_TIMEOUT, + .variant = LASER_THICK_RED}); + beam->scale = BEGOTTEN_BEAM_SCALE; + beam->ResetSpriteScale(); + beam->maxDistance = BEGOTTEN_BEAM_REACH; + beam->renderDepthOffset = axis.y >= BEGOTTEN_BEAM_UP ? BEGOTTEN_BEAM_FRONT_DEPTH : BEGOTTEN_BEAM_BACK_DEPTH; + beam->Update(); +} + +// Charging: it chases behind its target along its axis until its charge frames run out, then cries and attacks, +// recoiling and firing its beam. +static void charge_update(Entity_NPC& npc, Entity* target) +{ + if (npc.sprite.animState.animData && npc.sprite.WasEventTriggered("Shoot")) + { + npc.friction *= BEGOTTEN_RECOIL_FRICTION; + npc_push(npc, vector_scale(npc.targetPosition, -1)); + } + else + { + npc.friction *= BEGOTTEN_CHARGE_FRICTION; + if ((npc.i1 > 0 || !npc.sprite.WasEventTriggered("Stop")) && target) + { + Vector lead = vector_add(vector_scale(target->velocity, BEGOTTEN_LEAD_FRAMES), target->pos); + Vector spot = vector_sub(lead, vector_scale(npc.targetPosition, BEGOTTEN_CHARGE_BEHIND)); + spot = g_game->room->GetClampedPositionImpl(spot, 0, 0, 0, 0); + Vector chase = vector_scale(vector_sub(spot, npc.pos), BEGOTTEN_CHASE_SHARE); + if (vector_length(chase) > BEGOTTEN_CHASE_MAX) chase = vector_resized(chase, BEGOTTEN_CHASE_MAX); + npc_push(npc, chase); + } + } + + if (npc.i1 > 0) + { + npc.i1 -= npc_ticks_get(npc); + if (npc.i1 > 0) return; + + axis_play(npc, npc.targetPosition, "AttackRight", "AttackUp", "AttackDown"); + npc.PlaySound(SOUND_ANGRY_GURGLE, BEGOTTEN_CRY_VOLUME, 2, false, BEGOTTEN_CRY_PITCH); + return; + } + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) beam_fire(npc); + if (!npc_anim_is_done(npc)) return; + + npc.state = NPC_STATE_MOVE; + npc.projectileDelay = (int)(Random() % BEGOTTEN_WAIT_RANGE) + BEGOTTEN_WAIT_MIN; + npc.i1 = (int)(Random() % BEGOTTEN_REST_RANGE) + BEGOTTEN_REST_MIN; + npc.target = nullptr; +} + +// 004e8380 The Baby Begotten's AI: it drifts about its target out of its aim and charges it along an axis to fire a +// short beam. +void npc_baby_begotten_update(Entity_NPC& npc) +{ + room_path_raise_at(npc.pos, BEGOTTEN_PATH_MARKER); + Entity* target = npc.GetPlayerTarget(); + Vector goal = npc.CalcTargetPosition(0); + Vector toGoal = vector_sub(goal, npc.pos); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_MOVE; + npc.projectileDelay = (int)(Random() % BEGOTTEN_WAIT_RANGE) + BEGOTTEN_FIRST_WAIT_MIN; + return; + case NPC_STATE_MOVE: + return drift_update(npc, *target, goal, toGoal); + case BEGOTTEN_CHARGE: + return charge_update(npc, target); + default: + return; + } +} diff --git a/src/npc_basement.h b/src/npc_basement.h index ee351fe..44b2325 100644 --- a/src/npc_basement.h +++ b/src/npc_basement.h @@ -39,6 +39,9 @@ void bulb_player_collision(Entity_NPC& npc, Entity& collider); // spawn_small_maggot_jump: a small maggot leaping from a position, a height up, onto a spot it keeps clear. Entity_NPC* small_maggot_jump_spawn(const Vector& position, float height, const Vector& spot); +// spawn_small_maggot: a small maggot thrown from a position, a height up, at a velocity and rise. +Entity_NPC* small_maggot_spawn(const Vector& position, float height, const Vector& velocity, float rise); + // Lord of the Flies takes a fly as a blue fly of its own. Whether it did. bool npc_fly_beelzebub_take(Entity_NPC& npc); diff --git a/src/npc_big_bony.cpp b/src/npc_big_bony.cpp new file mode 100644 index 0000000..0ccb5a4 --- /dev/null +++ b/src/npc_big_bony.cpp @@ -0,0 +1,158 @@ +#include "npc_alt.h" +#include "grid_entity.h" +#include "path_finder.h" + +// Big Bony and its bouncing bones (variant 10) leave bone colored splats. +constexpr int BONY_BONE_VARIANT = 10; +constexpr ColorMod BONE_SPLAT_COLOR = {{1, 1, 1, 1}, {0.8f, 0.78f, 0.74f, 1}, {0, 0, 0}}; + +// Big Bony walks at 0.3 and, 120 frames apart, throws a bone at 8: one time in 15 a frame within 120 of its target, +// else one time in 120. +constexpr float BIG_BONY_SPEED = 0.3f; +constexpr float BIG_BONY_WALK_THRESHOLD = 0.1f; +constexpr float BIG_BONY_FLEE_FRICTION = 0.8f; +constexpr float BIG_BONY_THROW_FRICTION = 0.6f; +constexpr float BIG_BONY_NEAR = 120; +constexpr uint32_t BIG_BONY_NEAR_ODDS = 15; +constexpr uint32_t BIG_BONY_FAR_ODDS = 120; +constexpr int BIG_BONY_COOLDOWN = 120; +constexpr float BIG_BONY_AIM = 12; +constexpr float BIG_BONY_BONE_SPEED = 8; +constexpr float BIG_BONY_THROW_PITCH = 0.8f; +constexpr int BIG_BONY_THROW_DELAY = 10; +constexpr uint32_t BIG_BONY_GROAN_ODDS = 3; +constexpr int BIG_BONY_GROAN_DELAY = 60; + +// A bone bounces about at 8, 15 up, unseen by status effects and targeting, and breaks on its eighth wall or once +// hits (1, one time in three 2, a blast 4) bring it to 1 health. +constexpr uint64_t BONE_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | FLAG_NO_DEATH_TRIGGER | + FLAG_NO_SPIKE_DAMAGE | FLAG_NO_FLASH_ON_DAMAGE | FLAG_NO_REWARD; +constexpr float BONE_SPEED = 8; +constexpr int BONE_BOUNCES = 8; +constexpr float BONE_LIFT = -15; +constexpr uint32_t BONE_HARD_HIT_ODDS = 3; +constexpr float BONE_HIT = 1; +constexpr float BONE_HARD_HIT = 2; +constexpr float BONE_BLAST_HIT = 4; +constexpr float BONE_LAST_HEALTH = 1; +constexpr float BONE_BOUNCE_VOLUME = 0.5f; +constexpr float BONE_BOUNCE_PITCH = 1.5f; +constexpr float BONE_SPIN_SPAN = 10; +constexpr float BONE_SPIN_MIN = 0.1f; +constexpr float BONE_SPIN_MAX = 2; + +// Big Bony's states: walking and throwing. +constexpr int BIG_BONY_WALK = NPC_STATE_MOVE; +constexpr int BIG_BONY_THROW = NPC_STATE_ATTACK; + +// Walking at its target (or away from what it fears), winding up a throw when its cooldown allows, and groaning. +static void big_bony_walk_update(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", BIG_BONY_WALK_THRESHOLD); + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= BIG_BONY_FLEE_FRICTION; + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= BIG_BONY_FLEE_FRICTION; + } + else + { + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), BIG_BONY_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); + if (npc.projectileCooldown > 0) npc.projectileCooldown--; + Vector target = npc.GetPlayerTarget()->pos; + bool isNear = vector_length(vector_sub(npc.pos, target)) < BIG_BONY_NEAR; + bool isThrowing = npc.projectileCooldown < 1 && ((isNear && Random() % BIG_BONY_NEAR_ODDS == 0) || + Random() % BIG_BONY_FAR_ODDS == 0); + if (isThrowing) + { + bool isSideways = npc.sprite.animState.animData && npc.sprite.animState.animData->name == "WalkHori"; + npc.sprite.Play(isSideways ? "AttackHori" : "AttackVert"); + npc.state = BIG_BONY_THROW; + npc.projectileCooldown = BIG_BONY_COOLDOWN; + npc.targetPosition = vector_scale(vector_normalized(vector_sub(target, npc.pos)), BIG_BONY_AIM); + } + } + if (npc.pathfinder.hasDirectPath && Random() % BIG_BONY_GROAN_ODDS == 0) + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, BIG_BONY_GROAN_DELAY, false, 1); +} + +// Throwing: a bone at its target on Shoot, walking again once done. +static void big_bony_throw_update(Entity_NPC& npc) +{ + npc.friction *= BIG_BONY_THROW_FRICTION; + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_SCAMPER, 1, BIG_BONY_THROW_DELAY, false, BIG_BONY_THROW_PITCH); + Vector aim = vector_scale(vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)), + BIG_BONY_BONE_SPEED); + g_game->Spawn({.position = npc.pos, .velocity = aim, .spawner = &npc, .type = ENTITY_BIG_BONY, + .variant = BONY_BONE_VARIANT, .seed = Random()})->Update(); + } + if (!npc.sprite.IsPlaying()) npc.state = BIG_BONY_WALK; +} + +// A bone's hits wear it down to its last health, which breaks it. Whether it still holds. +static bool bone_hits_take(Entity_NPC& npc) +{ + if (npc.pendingDamage <= 0) return true; + float hit = Random() % BONE_HARD_HIT_ODDS == 0 ? BONE_HARD_HIT : BONE_HIT; + if (npc.pendingDamageFlags & DAMAGE_EXPLOSION) hit = BONE_BLAST_HIT; + npc.health = std::max(npc.health - hit, BONE_LAST_HEALTH); + npc.damageEvents.clear(); + npc.pendingDamage = 0; + npc.pendingDamageFlags = 0; + if (npc.health > BONE_LAST_HEALTH) return true; + npc.Kill(EntityRef()); + return false; +} + +// A bone bouncing at its speed, clattering off walls until its last bounce, spinning with its speed. +static void bone_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.AddEntityFlags(BONE_FLAGS); + npc.ClearEntityFlags(FLAG_APPEAR); + npc.state = BIG_BONY_WALK; + npc.sprite.Play("Move"); + if (npc.sprite.animState.animData) + npc.sprite.animState.SetFrameFloat((float)(npc.dropRNG._seed % (uint32_t)npc.sprite.animState.animData->length)); + npc.splatColor = BONE_SPLAT_COLOR; + npc.aiFloat = BONE_SPEED; + npc.i1 = BONE_BOUNCES; + npc.isKillOnTouch = true; + return; + } + if (!bone_hits_take(npc)) return; + + npc.posOffset.y = BONE_LIFT; + npc.entityGridCollisionClass = GRIDCOLL_NOPITS; + if (npc.isCollidesWithGrid) + { + npc_sound_play(SOUND_BONE_BOUNCE, BONE_BOUNCE_VOLUME, 2, BONE_BOUNCE_PITCH); + if (--npc.i1 < 1) npc.Kill(EntityRef()); + } + if (vector_is_zero(npc.velocity)) npc.velocity = random_direction(); + if (vector_length(npc.velocity) > 0) npc.velocity = vector_resized(npc.velocity, npc.aiFloat); + float spin = std::sqrt(vector_length_squared(npc.velocity) + npc.v1.y * npc.v1.y) / BONE_SPIN_SPAN; + npc.sprite.playbackSpeed = std::min(std::max(spin, BONE_SPIN_MIN), BONE_SPIN_MAX); +} + +// 005041d0 Big Bony's AI: it walks at its target throwing bones, which bounce about the room until they break. +void npc_big_bony_update(Entity_NPC& npc) +{ + if (npc.variant == BONY_BONE_VARIANT) return bone_update(npc); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = BIG_BONY_WALK; + npc.sprite.Play("WalkVert"); + npc.splatColor = BONE_SPLAT_COLOR; + return; + case BIG_BONY_WALK: + return big_bony_walk_update(npc); + case BIG_BONY_THROW: + return big_bony_throw_update(npc); + } +} diff --git a/src/npc_bomb_gagger.cpp b/src/npc_bomb_gagger.cpp new file mode 100644 index 0000000..57149e4 --- /dev/null +++ b/src/npc_bomb_gagger.cpp @@ -0,0 +1,140 @@ +#include "npc_alt.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "path_finder.h" +#include + +// The Bomb Gagger wanders, or runs from the bomb it threw. Without one out, one time in five once ready, it coughs up +// a giga bomb at a target within 300 in a line a blast reaches (75 frames apart, 3 or 7 after a failed try). Friendly +// it throws five at most, and only at enemies. +constexpr float GAGGER_WALK_THRESHOLD = 0.1f; +constexpr float GAGGER_FRICTION = 0.8f; +constexpr float GAGGER_ATTACK_FRICTION = 0.7f; +constexpr uint32_t GAGGER_ATTACK_ODDS = 5; +constexpr float GAGGER_REACH = 300; +constexpr int GAGGER_FAR_WAIT = 3; +constexpr int GAGGER_BLOCKED_WAIT = 7; +constexpr int GAGGER_COOLDOWN = 75; +constexpr int GAGGER_FRIENDLY_BOMBS = 4; +constexpr std::array GAGGER_ATTACKS = {"AttackLeft", "AttackUp", "AttackRight", "AttackDown"}; + +// The bomb leaves at 10 from 10 out, with six brown droplets spraying ahead within 20 degrees at 0.6 to 2.6 of its +// speed. +constexpr float GAGGER_BOMB_SPEED = 10; +constexpr int GAGGER_DROPLETS = 6; +constexpr float GAGGER_DROPLET_OUT = 0.4f; +constexpr float GAGGER_DROPLET_SPREAD = 40; +constexpr float GAGGER_DROPLET_TURN = -20; +constexpr float GAGGER_DROPLET_SPEED = 0.6f; +constexpr float GAGGER_DROPLET_SPEED_RANGE = 2; +constexpr int GAGGER_DROPLET_SUBTYPE = 1; +constexpr float GAGGER_DROPLET_SCALE = 1; +constexpr float GAGGER_DROPLET_SCALE_RANGE = 1.5f; +constexpr ColorMod GAGGER_DROPLET_COLOR = {{0.4f, 0.42f, 0.25f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The Bomb Gagger's states: wandering and throwing. +constexpr int GAGGER_WANDER = NPC_STATE_MOVE; +constexpr int GAGGER_THROW = NPC_STATE_ATTACK; + +// A giga bomb of the Bomb Gagger's. +static Entity* gagger_bomb_spawn(Entity_NPC& npc, Vector position, Vector velocity) +{ + return g_game->Spawn({.position = position, .velocity = velocity, .spawner = &npc, .type = ENTITY_BOMB, + .variant = BOMB_GIGA, .seed = Random()}); +} + +// Wandering or running from its bomb, and winding up a throw when it can. +static void gagger_wander_update(Entity_NPC& npc) +{ + if (npc.child) npc.pathfinder.EvadeTarget(npc.child->pos, STATUS_IGNORED); + else npc.pathfinder.MoveRandomly(STATUS_OBEYED); + npc.AnimWalkFrame("WalkHori", "WalkVert", GAGGER_WALK_THRESHOLD); + npc.friction *= GAGGER_FRICTION; + if (npc.child) return; + bool isFriendly = npc.HasEntityFlags(FLAG_FRIENDLY); + if (isFriendly && (!npc.GetPlayerTarget()->IsEnemy() || npc.i2 > GAGGER_FRIENDLY_BOMBS)) return; + + if (npc.projectileCooldown >= 1 || Random() % GAGGER_ATTACK_ODDS != 0) + { + npc.projectileCooldown -= npc_ticks_get(npc); + return; + } + Vector target = npc.GetPlayerTarget()->pos; + if (vector_length(vector_sub(target, npc.pos)) >= GAGGER_REACH || + npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) + npc.projectileCooldown = GAGGER_FAR_WAIT; + else if (!room_check_line(target, npc.pos, LINE_MODE_EXPLOSION, 0)) npc.projectileCooldown = GAGGER_BLOCKED_WAIT; + else + { + npc.projectileCooldown = GAGGER_COOLDOWN; + npc.sprite.Play("AttackStart", PLAY_FORCED); + npc.state = GAGGER_THROW; + npc.sprite.isFlipX = false; + npc.stateFrame = 0; + } +} + +// The throw on Shoot: the bomb along its facing and the droplets. +static void gagger_bomb_throw(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_BOSS_GURGLE_ROAR + (int)(Random() & 1), 1, 2, false, 1); + Vector velocity = vector_scale(direction_unit(npc.i1), GAGGER_BOMB_SPEED); + npc.child = gagger_bomb_spawn(npc, vector_add(npc.pos, velocity), velocity); + Vector spray = vector_add(npc.pos, vector_scale(velocity, GAGGER_DROPLET_OUT)); + for (int droplet = 0; droplet < GAGGER_DROPLETS; droplet++) + { + uint32_t seed = Random(); + Vector direction = vector_rotated(velocity, random_unit() * GAGGER_DROPLET_SPREAD + GAGGER_DROPLET_TURN); + float speed = random_unit() * GAGGER_DROPLET_SPEED_RANGE + GAGGER_DROPLET_SPEED; + Entity* drop = g_game->Spawn({.position = spray, .velocity = vector_scale(direction, speed), + .subType = GAGGER_DROPLET_SUBTYPE, .type = ENTITY_EFFECT, .variant = EFFECT_WATER_SPLASH, .seed = seed}); + drop->sprite.scale = vector_scale(drop->sprite.scale, random_unit() * GAGGER_DROPLET_SCALE_RANGE + + GAGGER_DROPLET_SCALE); + drop->sprite.color = GAGGER_DROPLET_COLOR; + drop->Update(); + } + npc.i2++; +} + +// Throwing: the wind up (gagging), then the throw along the way to its target, then wandering again. +static void gagger_throw_update(Entity_NPC& npc) +{ + npc.friction *= GAGGER_ATTACK_FRICTION; + AnimationState& anim = npc.sprite.animState; + if (npc.stateFrame == 0) + { + if (anim.animData && anim.IsEventTriggered("Sound1")) npc.PlaySound(SOUND_WORM_SPIT, 1, 2, false, 1); + if (anim.animData && anim.IsEventTriggered("Sound2")) + { + npc.PlaySound(SOUND_WORM_SPIT, 1, 2, false, 1); + npc.PlaySound(SOUND_SKIN_PULL, 1, 2, false, 1); + } + if (npc.sprite.IsPlaying()) return; + npc.stateFrame = 1; + Direction facing = vector_to_direction(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + npc.sprite.Play(GAGGER_ATTACKS[facing]); + npc.i1 = facing; + return; + } + if (anim.animData && anim.IsEventTriggered("Shoot")) gagger_bomb_throw(npc); + if (!npc.sprite.IsPlaying()) npc.state = GAGGER_WANDER; +} + +// 00503300 The Bomb Gagger's AI: it wanders and coughs up giga bombs at its target, running from them, and drops the +// one it holds as it dies. +void npc_bomb_gagger_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = GAGGER_WANDER; + npc.i2 = 0; + } + else if (npc.state == GAGGER_WANDER) gagger_wander_update(npc); + else if (npc.state == GAGGER_THROW) gagger_throw_update(npc); + + if (!npc.isDead || !npc.sprite.animState.animData) return; + const NullFrame* held = npc.sprite.animState.GetNullFrame("Bomb"); + if (held && held->isVisible) gagger_bomb_spawn(npc, npc.pos, {}); +} diff --git a/src/npc_bubbles.cpp b/src/npc_bubbles.cpp new file mode 100644 index 0000000..9bd3e69 --- /dev/null +++ b/src/npc_bubbles.cpp @@ -0,0 +1,245 @@ +#include "npc_alt.h" +#include "entity_effect.h" +#include "entity_projectile.h" +#include "grid_entity.h" +#include "menu_manager.h" +#include "npc_basement.h" +#include "path_finder.h" + +// Bubbles walks toward its target and charges a bubble burst over 100 frames: then, one time in 120 a frame within +// 200 of its target, it farts (a 120 wide cloud) and blows 12 bubbles over 12 frames. +constexpr int BUBBLES_CHARGE = 100; +constexpr float BUBBLES_REACH_SQUARED = 40000; +constexpr uint32_t BUBBLES_ATTACK_ODDS = 120; +constexpr float BUBBLES_CONTROLLED_REACH = 1000; +constexpr float BUBBLES_FART_RADIUS = 120; +constexpr int BUBBLES_BURST_SHOTS = 12; +constexpr float BUBBLES_ATTACK_FRICTION = 0.4f; +constexpr float BUBBLES_SPEED = 0.3f; +constexpr float BUBBLES_FLEE_FRICTION = 0.8f; +constexpr float BUBBLES_WALK_THRESHOLD = 0.1f; +constexpr uint32_t BUBBLES_GURGLE_ODDS = 3; +constexpr int BUBBLES_GURGLE_DELAY = 60; +constexpr int BUBBLES_ATTACK_SOUND_DELAY = 5; + +// Hit, it answers 20 to 39 frames apart with a small bubble lobbed 40 to 120 toward the hit, and its burst bubbles +// are as small. Dross bubbles are puke, Downpour bubbles tears. +constexpr float BUBBLE_SCALE = 0.6f; +constexpr float BUBBLE_HIT_MIN = 40; +constexpr float BUBBLE_HIT_RANGE = 80; +constexpr float BUBBLE_HIT_NEAR_SQUARED = 0.01f; +constexpr uint32_t BUBBLE_HIT_GAP_RANGE = 20; +constexpr int BUBBLE_HIT_GAP = 20; +constexpr float BUBBLE_BURST_TRAJECTORY = 3; + +// Dying, it leaves a splash (tinted brown in the Dross), four blood bursts thrown 40 out at 7 between -45 and -135 +// degrees, and a geyser of bubbles over 15 frames. +constexpr ColorMod BUBBLES_DROSS_SPLASH = {{0.5f, 0.4f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod BUBBLES_GEYSER_WATER = {{1, 1, 1, 1}, {5.5f, 7, 7, 1}, {0, 0, 0}}; +constexpr ColorMod BUBBLES_GEYSER_DROSS = {{1, 1, 1, 1}, {7, 6, 5.5f, 1}, {0, 0, 0}}; +constexpr int BUBBLES_GEYSER_BURSTS = 4; +constexpr float BUBBLES_GEYSER_ANGLE = -45; +constexpr float BUBBLES_GEYSER_SPREAD = 90; +constexpr float BUBBLES_GEYSER_SPEED = 7; +constexpr float BUBBLES_GEYSER_REACH = 40; +constexpr int BUBBLES_GEYSER_BLOOD_SIZE = 2; +constexpr float BUBBLES_GEYSER_LIFT = -28; +constexpr float BUBBLES_GEYSER_DEPTH = 10; +constexpr int BUBBLES_GEYSER_Z = 500; +constexpr int BUBBLES_GEYSER_TICKS = 15; +constexpr uint64_t BUBBLES_GEYSER_FLAGS = FLAG_CHARM | FLAG_FRIENDLY | FLAG_WEAKNESS; + +// Each geyser tick throws two bubbles 5 out at up to 2.8, up to 1.4 big, rising at 15 to 75 from 23 to 38 high, +// then two more from 23 to 1023 high. +constexpr int GEYSER_SHOTS = 2; +constexpr float GEYSER_SPREAD = 5; +constexpr float GEYSER_SPEED = 2.8f; +constexpr float GEYSER_SCALE = 1.4f; +constexpr float GEYSER_FALLING_ACCEL = 2; +constexpr float GEYSER_RISE = -15; +constexpr float GEYSER_RISE_RANGE = 60; +constexpr float GEYSER_HEIGHT = -23; +constexpr float GEYSER_LOW_RANGE = 15; +constexpr float GEYSER_HIGH_RANGE = 1000; + +// The bubble shots of the stage: puke in the Dross, tears in the Downpour, plain elsewhere. +static int bubble_variant_get() +{ + uint32_t stage = g_game->GetStageID(); + if (stage == STAGE_ID_DOWNPOUR) return PROJECTILE_TEAR; + return stage == STAGE_ID_DROSS ? PROJECTILE_PUKE : PROJECTILE_NORMAL; +} + +// A small bubble shot of the stage. +static ProjectileParams bubble_params_get() +{ + ProjectileParams params; + params.variant = bubble_variant_get(); + params.scale = BUBBLE_SCALE; + return params; +} + +// Two bubbles of the geyser, thrown from heightRange over its first height. +static void geyser_shots_fire(Entity_Effect& timer, float heightRange) +{ + for (int shot = 0; shot < GEYSER_SHOTS; shot++) + { + Vector direction = random_direction(); + uint32_t seed = Random(); + Vector velocity = vector_scale(direction, random_unit() * GEYSER_SPEED); + Vector position = vector_add(timer.pos, vector_scale(direction, GEYSER_SPREAD * random_unit())); + auto* projectile = static_cast(g_game->Spawn({.position = position, .velocity = velocity, + .type = ENTITY_PROJECTILE, .variant = bubble_variant_get(), .seed = seed})); + projectile->spawnerType = ENTITY_BUBBLES; + projectile->fallingAccel = GEYSER_FALLING_ACCEL; + projectile->scale = random_unit() * GEYSER_SCALE; + projectile->fallingSpeed = GEYSER_RISE - random_unit() * GEYSER_RISE_RANGE; + projectile->height = GEYSER_HEIGHT - random_unit() * heightRange; + projectile->apply_spawn_flags({.flags = timer.flags, .scale = timer.scale, .championColor = timer.state}); + projectile->Update(); + } +} + +// 0055a850 A tick of Bubbles' death geyser: two low bubbles and two high ones. +static void bubbles_death_geyser_tick(Entity_Effect* timer) +{ + geyser_shots_fire(*timer, GEYSER_LOW_RANGE); + geyser_shots_fire(*timer, GEYSER_HIGH_RANGE); +} + +// Its death: the splash, the four blood bursts and the geyser timer, which shoots with its champion color and scale. +static void bubbles_death_spawn(Entity_NPC& npc) +{ + bool isDross = g_game->GetStageID() == STAGE_ID_DROSS; + Entity* splash = spawn_at(ENTITY_EFFECT, EFFECT_BIG_SPLASH, 0, npc.pos, nullptr); + if (isDross) splash->SetColor(BUBBLES_DROSS_SPLASH, -1, COLOR_PRIORITY_DEFAULT, false, true); + splash->Update(); + if (npc.HasEntityFlags(FLAG_SHRINK | FLAG_KILLSWITCH)) return; + + for (int burst = 0; burst < BUBBLES_GEYSER_BURSTS; burst++) + { + float angle = (BUBBLES_GEYSER_ANGLE - random_unit() * BUBBLES_GEYSER_SPREAD) * DEGREES_TO_RADIANS; + Vector direction = vector_make(std::cos(angle), std::sin(angle)); + Entity* blood = g_game->Spawn({.position = vector_add(npc.pos, vector_scale(direction, BUBBLES_GEYSER_REACH)), + .velocity = vector_scale(direction, BUBBLES_GEYSER_SPEED), .subType = BUBBLES_GEYSER_BLOOD_SIZE, + .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + blood->sprite.offset = vector_make(0, BUBBLES_GEYSER_LIFT); + blood->renderDepthOffset = BUBBLES_GEYSER_DEPTH; + blood->renderZOffset = BUBBLES_GEYSER_Z; + blood->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + blood->SetColor(isDross ? BUBBLES_GEYSER_DROSS : BUBBLES_GEYSER_WATER, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + + Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(&bubbles_death_geyser_tick), 1, + BUBBLES_GEYSER_TICKS, false); + timer->pos = npc.pos; + timer->state = npc.isChampion ? npc.championColorIdx : -1; + timer->flags |= npc.flags & BUBBLES_GEYSER_FLAGS; + timer->scale = npc.scale; + timer->Update(); +} + +// Walking: charging its burst, attacking once charged and near (or at its controller's bomb), pathing to its target +// or away from what it fears, gurgling now and then. +static void bubbles_walk_update(Entity_NPC& npc) +{ + if (npc.stateFrame < BUBBLES_CHARGE) npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame >= BUBBLES_CHARGE) + { + bool isAttacking = false; + if (npc.controllerID == -1) + { + Vector toTarget = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + isAttacking = vector_length_squared(toTarget) < BUBBLES_REACH_SQUARED && Random() % BUBBLES_ATTACK_ODDS == 0; + } + else + isAttacking = npc.IsTargetInAttackRange(BUBBLES_CONTROLLED_REACH, 0, true) || + npc.IsControllerActionPressed(ACTION_BOMB); + if (isAttacking) + { + npc.PlaySound(SOUND_ANGRY_GURGLE, 1, BUBBLES_ATTACK_SOUND_DELAY, false, 1); + npc.state = NPC_STATE_ATTACK; + npc.stateFrame = 0; + bool isHorizontal = std::abs(npc.velocity.x) > std::abs(npc.velocity.y); + npc.sprite.Play(isHorizontal ? "AttackHori" : "AttackVert"); + if (isHorizontal) npc.sprite.isFlipX = npc.velocity.x < 0; + return; + } + } + + npc.AnimWalkFrame("WalkHori", "WalkVert", BUBBLES_WALK_THRESHOLD); + npc.aiFloat = BUBBLES_SPEED; + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.controllerID != -1) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), BUBBLES_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= BUBBLES_FLEE_FRICTION; + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= BUBBLES_FLEE_FRICTION; + } + if (npc.IsHostileTo(npc.GetPlayerTarget()) && npc.pathfinder.hasDirectPath && Random() % BUBBLES_GURGLE_ODDS == 0) + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, BUBBLES_GURGLE_DELAY, false, 1); +} + +// A bubble lobbed toward the last hit, at most every 20 to 39 frames. +static void bubbles_hit_shoot(Entity_NPC& npc) +{ + if (npc.i2 > 0) + { + npc.i2--; + return; + } + if (npc.damageEvents.empty()) return; + + Vector toHit = vector_sub(npc.damageEvents.back().source.position, npc.pos); + Vector direction = vector_length_squared(toHit) < BUBBLE_HIT_NEAR_SQUARED ? random_direction() + : vector_normalized(toHit); + Vector target = vector_add(npc.pos, vector_scale(direction, random_unit() * BUBBLE_HIT_RANGE + BUBBLE_HIT_MIN)); + npc.FireBossProjectiles(1, target, 1, bubble_params_get()); + npc.i2 = (int)(Random() % BUBBLE_HIT_GAP_RANGE) + BUBBLE_HIT_GAP; +} + +// 0055ad20 Bubbles' AI: it walks charging up, farts out a stream of bubbles, answers hits with bubbles and bursts +// into a geyser of them. +void npc_bubbles_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + npc.i1 = 0; + npc.i2 = 0; + if (npc.sprite.SetAnimation("WalkVert", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } + return; + } + + if (npc.state == NPC_STATE_MOVE) bubbles_walk_update(npc); + else if (npc.state == NPC_STATE_ATTACK) + { + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Shoot")) + { + game_butter_bean_fart({.position = npc.pos, .source = &npc, .radius = BUBBLES_FART_RADIUS}); + npc.i1 = BUBBLES_BURST_SHOTS; + } + if (!npc.sprite.IsPlaying()) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + } + npc.friction *= BUBBLES_ATTACK_FRICTION; + } + + npc.UpdateChargeBar(0, BUBBLES_CHARGE, (float)npc.stateFrame, true); + bubbles_hit_shoot(npc); + if (npc.i1 > 0) + { + npc_sound_play(SOUND_BOSS2_BUBBLES, 1, 2, 1); + npc.FireBossProjectiles(1, {}, BUBBLE_BURST_TRAJECTORY, bubble_params_get()); + npc.i1--; + } + if (npc.isDead) bubbles_death_spawn(npc); +} diff --git a/src/npc_clickety_clack.cpp b/src/npc_clickety_clack.cpp new file mode 100644 index 0000000..e949f91 --- /dev/null +++ b/src/npc_clickety_clack.cpp @@ -0,0 +1,303 @@ +#include "npc_alt.h" +#include "entity_config.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "grid_entity.h" +#include "path_finder.h" +#include "room.h" +#include "room_grid.h" +#include +#include + +// The Clickety Clack walks at 0.75, keeping off the enemies near it (it picks one within 60 to keep off for 30 to 44 +// frames once more than 80 from its target), its head glowing. Clutch's Clickety Clacks are its orbitals. +constexpr float CLACK_SPEED = 0.75f; +constexpr float CLACK_FRICTION = 0.97f; +constexpr float CLACK_FLEE_FRICTION = 0.8f; +constexpr float CLACK_LONELY_SQUARED = 6400; +constexpr float CLACK_SPACING = 60; +constexpr uint32_t CLACK_SPACING_TIME_RANGE = 15; +constexpr int CLACK_SPACING_TIME = 30; +constexpr float CLACK_STILL = 0.1f; +constexpr std::array CLACK_WALKS = {"WalkLeft", "WalkUp", "WalkRight", "WalkDown"}; +constexpr int CLACK_HEAD_LAYER = 2; +constexpr ColorMod CLACK_HEAD_COLOR = {{1, 1, 1, 1}, {1.3f, 1, 2, 1}, {0, 0, 0}}; +constexpr int CLACK_FIRST_DELAY = -30; + +// Killed, it collapses into a pile of bones for 150 frames (or burns with Clutch) and gets up again with 10 health +// (9 after its first time). When the last one standing collapses they all fall for good. +constexpr float CLACK_REVIVE_HEALTH = 10; +constexpr float CLACK_PILE_MASS = 200; +constexpr int CLACK_PILE_FRAMES = 150; +constexpr int CLACK_PILE_COOLDOWN = 30; +constexpr int CLACK_PILE_DELAY = -60; +constexpr int CLACK_FLAME = 99; +constexpr uint64_t CLACK_PILE_FLAGS = FLAG_HIDE_HP_BAR | FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET; +constexpr float CLACK_PILE_FRICTION = 0.5f; +constexpr float CLACK_FLAME_REACH_SQUARED = 14400; +constexpr float CLACK_FLAME_EVERY = 2; +constexpr int CLACK_FLAME_COOLDOWN = 45; + +// Clutch's commands: the stomp (a ring of eight bones at 10), the stun and the quick revert. +constexpr float CLACK_STOMP_FRICTION = 0.5f; +constexpr float CLACK_STOMP_SPEED = 10; +constexpr float CLACK_STUN_FRICTION = 0.3f; +constexpr int CLUTCH_ORBITING = 6; +constexpr int CLUTCH_REVERT_WAIT = -1000; +constexpr int CLUTCH_DOWN = NPC_STATE_STOMP; + +// The Clickety Clack's states: Clutch's orbiting, walking, the stomp, the stun, getting up, the quick revert and the +// pile of bones. +constexpr int CLACK_ORBITING = NPC_STATE_IDLE; +constexpr int CLACK_WALK = NPC_STATE_MOVE; +constexpr int CLACK_STOMP = NPC_STATE_SUICIDE; +constexpr int CLACK_STUNNED = NPC_STATE_STOMP; +constexpr int CLACK_REGEN = NPC_STATE_SUMMON; +constexpr int CLACK_REVERT = NPC_STATE_SUMMON2; +constexpr int CLACK_PILE = NPC_STATE_SPECIAL; + +// Standing again: hurt, targeted and moved as usual. +static void clack_stand(Entity_NPC& npc) +{ + npc.ClearEntityFlags(CLACK_PILE_FLAGS); + npc.isInvincible = false; + npc.mass = npc.config->mass; +} + +// The enemy it keeps off: kept while its time lasts and it stays an enemy, else the first near one of its side once +// it is far from its target. +static Entity* clack_shy_get(Entity_NPC& npc, Vector target) +{ + Entity* shy = npc.entityRef.get(); + if (shy && shy->IsEnemy()) return shy; + npc.entityRef = nullptr; + if (vector_length_squared(vector_sub(target, npc.pos)) <= CLACK_LONELY_SQUARED) return nullptr; + + bool isFriendly = npc.HasEntityFlags(FLAG_FRIENDLY); + for (Entity* other : entity_query_radius(npc.pos, CLACK_SPACING, QUERY_ENEMIES)) + { + bool isNpc = other->type >= 10 && other->type <= 999; + bool isVersusPlayer = g_game->deathmatchManager.is_active() && other->type == ENTITY_PLAYER; + if ((!isNpc && !isVersusPlayer) || other == &npc) continue; + if (other->HasEntityFlags(FLAG_FRIENDLY) != isFriendly || other->HasEntityFlags(FLAG_NO_TARGET)) continue; + npc.entityRef = other; + npc.i1 = (int)(Random() % CLACK_SPACING_TIME_RANGE) + CLACK_SPACING_TIME; + return other; + } + return nullptr; +} + +// Walking at its target, keeping off its neighbor, or away from what it fears (or from Clutch's target). +static void clack_walk_update(Entity_NPC& npc) +{ + PathFinder& path = npc.pathfinder; + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && npc.controllerID == -1) + { + path.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= CLACK_FLEE_FRICTION; + } + else + { + Vector target = npc.CalcTargetPosition(0); + if (npc.i1 < 1 || (npc.i1 -= npc_ticks_get(npc)) < 1) npc.entityRef = nullptr; + Entity_NPC* clutch = npc.ParentNPC(); + Entity* shy = nullptr; + if (clutch && npc.i2 == 1) reconstruction_missing("npc_clickety_clack_update 004efb90: holding Clutch's line"); + else if (clutch && npc.i2 == 2) shy = npc.GetPlayerTarget(); + else shy = clack_shy_get(npc, target); + if (shy) + { + path.EvadeTarget(shy->pos, STATUS_OBEYED); + npc.friction *= CLACK_FLEE_FRICTION; + } + else path.FindGridPath(npc.CalcTargetPosition(0), CLACK_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); + } + + npc.friction *= CLACK_FRICTION; + if (vector_length(npc.velocity) < CLACK_STILL) npc.sprite.SetFrame(CLACK_WALKS[DIRECTION_DOWN], 0); + else npc.sprite.Play(CLACK_WALKS[vector_to_direction(npc.velocity)]); +} + +// Whether any Clickety Clack of its side (not friendly) still stands. +static bool clack_any_standing() +{ + for (Entity* other : g_game->room->entityList.updateEL) + { + if (other->type != ENTITY_CLICKETY_CLACK) continue; + if (!other->HasEntityFlags(FLAG_FRIENDLY) && !other->HasEntityFlags(FLAG_NO_TARGET)) return true; + } + return false; +} + +// A pile of bones: burning with Clutch, or, alone, ending them all when it was the last standing, then getting up. +// Whether the update goes on. +static bool clack_pile_update(Entity_NPC& npc) +{ + npc.friction *= CLACK_PILE_FRICTION; + if (npc.i2 == CLACK_FLAME) + { + if (!npc.sprite.IsPlaying()) npc.sprite.Play("FlameIdle"); + Entity_NPC* clutch = npc.ParentNPC(); + bool isAiming = npc.i2 == CLACK_FLAME && npc.sprite.animState.IsLoopingAnimation() && + npc.projectileCooldown < 1 && npc.GetIntervalTicks(CLACK_FLAME_EVERY, 0) && clutch && + clutch->state == CLUTCH_ORBITING && + vector_length_squared(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)) < CLACK_FLAME_REACH_SQUARED; + if (isAiming) + { + npc.sprite.Play("FlameShoot"); + npc.projectileCooldown = CLACK_FLAME_COOLDOWN; + } + } + if (npc.projectileCooldown > 0) npc.projectileCooldown = std::max(npc.projectileCooldown - npc_ticks_get(npc), 0); + + if (npc.parent) + { + reconstruction_missing("npc_clickety_clack_update 004efb90: Clutch's burning bones"); + return true; + } + if (npc.sprite.IsEventTriggered("Shoot") && !npc.IsFriendly() && !clack_any_standing()) + { + for (Entity* other : g_game->room->entityList.updateEL) + if (other->type == ENTITY_CLICKETY_CLACK && !other->HasEntityFlags(FLAG_FRIENDLY)) other->Kill(EntityRef()); + return false; + } + npc.stateFrame -= npc_ticks_get(npc); + if (npc.stateFrame > 0) return true; + npc.sprite.Play("Regen"); + npc.state = CLACK_REGEN; + return true; +} + +// Clutch's commands: the stomp's ring of bones, the stun and the quick revert, back to orbiting or walking. +static void clack_command_update(Entity_NPC& npc) +{ + if (npc.state == CLACK_STOMP) + { + npc.friction *= CLACK_STOMP_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_MONSTER_ROAR_0, 1, 2, 1); + npc_sound_play(SOUND_BLACK_POOF, 1, 2, 1); + npc.MakeGroundPoofAtSelf(COLOR_DEFAULT, 1); + ProjectileParams params; + params.variant = PROJECTILE_BONE; + npc.FireProjectiles(npc.pos, vector_make(CLACK_STOMP_SPEED, 0), PROJECTILES_EIGHT, params); + npc.projectileDelay = CLACK_FIRST_DELAY; + npc.projectileCooldown = 0; + } + if (npc.sprite.IsPlaying()) return; + clack_stand(npc); + npc.state = CLACK_ORBITING; + npc.entityRef = nullptr; + npc.i1 = 0; + return; + } + if (npc.state == CLACK_STUNNED) + { + npc.friction *= CLACK_STUN_FRICTION; + if (!npc.sprite.IsPlaying()) npc.sprite.Play("StunnedLoop"); + return; + } + + if (npc.state == CLACK_REGEN) + { + npc.friction *= CLACK_PILE_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) clack_stand(npc); + } + else + { + npc.friction *= CLACK_STUN_FRICTION; + Entity_NPC* clutch = npc.ParentNPC(); + if (npc.sprite.IsEventTriggered("Shoot") && clutch && clutch->type == ENTITY_CLUTCH && + clutch->state == CLUTCH_ORBITING) + { + clutch->state = NPC_STATE_IDLE; + clutch->stateFrame = CLUTCH_REVERT_WAIT; + } + } + if (npc.sprite.IsPlaying()) return; + clack_stand(npc); + npc.state = CLACK_WALK; + npc.targetPosition = {}; +} + +// Its head layer: placed by the HeadOffset null while orbiting, else straight, its overlay dropped. +static void clack_head_update(Entity_NPC& npc) +{ + LayerState& head = *npc.sprite.GetLayer(1); + const NullFrame* guide = npc.state == CLACK_ORBITING && npc.sprite.animState.animData + ? npc.sprite.animState.GetNullFrame("HeadOffset") + : nullptr; + if (npc.state != CLACK_ORBITING && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetAnimationData(nullptr); + else if (npc.state != CLACK_ORBITING) return; + head.pos = guide ? guide->pos : Vector{}; + head.size = guide ? guide->scale : vector_make(1, 1); + head.rotation = guide ? guide->rotation : 0; +} + +// Killed: it collapses into its pile of bones (burning with Clutch), unless it was a pile already. +static void clack_collapse(Entity_NPC& npc) +{ + Entity_NPC* clutch = npc.ParentNPC(); + // The original converts subtype - 1 unsigned, so a first collapse (subtype 0) also gets up with 9. + float firsts = std::min(std::max((float)(uint32_t)(npc.subtype - 1) * 2, 0.0f), 1.0f); + npc.health = clutch ? npc.config->baseHP : CLACK_REVIVE_HEALTH - firsts; + npc.AddEntityFlags(CLACK_PILE_FLAGS); + npc.isDead = false; + npc.RemoveStatusEffects(); + npc.mass = CLACK_PILE_MASS; + npc.targetPosition = npc.pos; + npc.isInvincible = true; + npc.state = CLACK_PILE; + npc.projectileCooldown = CLACK_PILE_COOLDOWN; + npc.projectileDelay = CLACK_PILE_DELAY; + if (clutch && clutch->child.get() == &npc) + { + npc.sprite.Play("FlameCollapse"); + npc.i2 = CLACK_FLAME; + } + else npc.sprite.Play("Collapse"); + npc.stateFrame = CLACK_PILE_FRAMES; + if (!clutch) npc.subtype++; +} + +// 004efb90 The Clickety Clack's AI: a skeleton walking at its target that collapses when killed and gets up again +// until the last one falls. Clutch drives its orbitals' stomps, stuns and reverts. +void npc_clickety_clack_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + npc.AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + npc.state = CLACK_WALK; + npc.projectileDelay = CLACK_FIRST_DELAY; + npc.i2 = 0; + if (npc.sprite.layerStates.size() > CLACK_HEAD_LAYER) npc.sprite.GetLayer(CLACK_HEAD_LAYER)->color = CLACK_HEAD_COLOR; + break; + case CLACK_ORBITING: + reconstruction_missing("npc_clickety_clack_update 004efb90: orbiting Clutch"); + break; + case CLACK_WALK: + clack_walk_update(npc); + break; + case CLACK_PILE: + if (!clack_pile_update(npc)) return; + break; + case CLACK_STOMP: + case CLACK_STUNNED: + case CLACK_REGEN: + case CLACK_REVERT: + clack_command_update(npc); + break; + } + + clack_head_update(npc); + room_path_raise_at(npc.pos, GRID_PATH_FREED); + if (!vector_is_zero(npc.targetPosition)) npc.velocity = vector_sub(npc.targetPosition, npc.pos); + Entity_NPC* clutch = npc.ParentNPC(); + bool isBoneLoose = npc.isDead || npc.state != CLACK_PILE || !clutch || clutch->state == CLUTCH_DOWN; + Entity* bone = npc.entityRef.get(); + if (isBoneLoose && bone && bone->type == ENTITY_PROJECTILE) bone->isDead = true; + if (npc.isDead && !npc.HasEntityFlags(FLAG_NO_TARGET)) clack_collapse(npc); +} diff --git a/src/npc_clotty.cpp b/src/npc_clotty.cpp index 634d3a0..16ae5ba 100644 --- a/src/npc_clotty.cpp +++ b/src/npc_clotty.cpp @@ -2,6 +2,7 @@ #include "boss_ai.h" #include "entity_effect.h" #include "entity_player.h" +#include "npc_ai.h" #include "room_grid.h" #include @@ -66,7 +67,6 @@ constexpr float MEGA_SPLIT_SPREAD = 20; constexpr float GRILL_WATER_MAX = 0.2f; constexpr uint64_t DAMAGE_FIRE_CLOTTY = 1ull << 1; -constexpr ColorMod CLOGGY_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.25490198f, 0.16078432f, 0.13725491f}}; constexpr ColorMod CLOT_SPLAT_COLOR = {{0.02f, 0.05f, 0.05f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod GRILLED_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.14117648f, 0.12156863f, 0.10980392f}}; constexpr ColorMod CLOT_SHOT_COLOR = {{1, 1, 1, 1}, {0.5f, 0.5f, 0.5f, 1}, {0, 0, 0}}; @@ -93,7 +93,7 @@ static void clotty_init(Entity_NPC& npc) { if (npc.type == ENTITY_CLOGGY) { - npc.splatColor = CLOGGY_SPLAT_COLOR; + npc.splatColor = POOP_SPLAT_COLOR; npc.i1 = (int)(npc.dropRNG.Next() & 1); } else if (npc.variant == CLOT) npc.splatColor = CLOT_SPLAT_COLOR; diff --git a/src/npc_collision.cpp b/src/npc_collision.cpp index 4ef5a3f..a84d99c 100644 --- a/src/npc_collision.cpp +++ b/src/npc_collision.cpp @@ -389,7 +389,7 @@ static Verdict contact_passes(Contact& contact) Entity& collider = contact.collider; int npcType = contact.npcType; int colliderType = contact.colliderType; - if (npc.spawnerType == ENTITY_ORBIT_SPAWNER && npc.parent && collider.IsEnemy()) return contact.isIgnored; + if (npc.spawnerType == ENTITY_FLY_TRAP && npc.parent && collider.IsEnemy()) return contact.isIgnored; if (collider.type == ENTITY_PLAYER && (npcType == ENTITY_MOVABLE_TNT || npcType == ENTITY_POOP) && collider.ToPlayer()->CanCrushRocks()) { diff --git a/src/npc_cultist.cpp b/src/npc_cultist.cpp new file mode 100644 index 0000000..fae147e --- /dev/null +++ b/src/npc_cultist.cpp @@ -0,0 +1,654 @@ +#include "npc_gehenna.h" +#include "boss_ai.h" +#include "entity_config.h" + +// The Cultist (variant 0) drifts about near the enemies by its target, raising the enemies killed in the room (up to +// 100 health of them) at the spot where most fell, and casts a purple ball. The Blood Cultist (variant 1) lunges at a +// spot ahead of its target and either sends a wall of blood and fire along the floor or raises a grasping pool of +// blood (variant 10) by its target. Hits shorten the Blood Cultist's wait. +constexpr int CULTIST_BLOOD = 1; +constexpr int CULTIST_POOL = 10; +constexpr int CULTIST_CAST = NPC_STATE_ATTACK; +constexpr int CULTIST_RAISE = NPC_STATE_SUMMON; +constexpr int CULTIST_GONE = NPC_STATE_SUICIDE; + +// Its plans (i1): none, an attack once at its spot, or (the Cultist's) a raising at the fallen. +enum CultistPlan +{ + PLAN_NONE, + PLAN_ATTACK, + PLAN_RAISE +}; + +constexpr ColorMod CULTIST_SPLAT = {{1, 1, 1, 1}, {0.84f, 0.4f, 0.68f, 1}, {0, 0, 0}}; +constexpr std::array CULTIST_HIDDEN_LAYERS = {2, 3, 4}; +constexpr int CULTIST_FIRST_WAIT_MIN = 30; +constexpr int CULTIST_FIRST_WAIT_RANGE = 30; +constexpr float CULTIST_FRICTION = 0.75f; +constexpr float CULTIST_CAST_FRICTION = 0.7f; + +// Drifting to its spot: it turns 3 to 23 degrees a frame toward it and pushes 0.7 to 2.4 along its heading, arriving +// within 10 (24 for the Blood Cultist), and gives up after 60 frames. +constexpr float CULTIST_TURN_MIN = 3; +constexpr float CULTIST_TURN_RANGE = 20; +constexpr float CULTIST_PUSH_MIN = 0.7f; +constexpr float CULTIST_PUSH_RANGE = 1.7f; +constexpr float CULTIST_ARRIVE = 100; +constexpr float BLOOD_CULTIST_ARRIVE = 576; +constexpr float CULTIST_GIVE_UP = 60; +constexpr int CULTIST_GIVE_UP_ODDS = 10; +constexpr float CULTIST_ROOM_MARGIN = 60; +constexpr float CULTIST_ROW = 30; +constexpr int CULTIST_CAST_ODDS = 3; +constexpr float CULTIST_RAISE_REACH = 10000; +constexpr int CULTIST_RAISE_ODDS = 4; +constexpr float CULTIST_FALLEN_GROUP = 25600; +constexpr float BLOOD_CULTIST_LEAD = 15; +constexpr int BLOOD_CULTIST_PLAN_ODDS = 8; + +// Its new spot: by the enemy nearest its target (by its nearest player when friendly), 50 out and up to 40 off, else +// 50 to 90 from its target within 120 degrees of where it stands. +constexpr float CULTIST_ALLY_GAP = 50; +constexpr float CULTIST_SPOT_SPREAD = 40; +constexpr float CULTIST_SPOT_MIN = 50; +constexpr float CULTIST_SIDE_ARC = 240; +constexpr float CULTIST_NO_ENEMY = 1e8f; + +// Casting: a recoil of 5 fading by 0.1, the Cultist's purple ball, and the Blood Cultist's wall of blood running 40 a +// frame from 20. +constexpr float CULTIST_RECOIL = 5; +constexpr float CULTIST_RECOIL_FADE = 0.1f; +constexpr float CULTIST_BALL_SPEED = 8; +constexpr float CULTIST_BALL_SPREAD = 40; +static const Vector CULTIST_BALL_OFFSET = vector_make(0, 5); +constexpr float CULTIST_BALL_ORBIT = 210; +constexpr int CULTIST_BALL_VARIANT = 1; +constexpr float BLOOD_WALL_START = 20; +constexpr float BLOOD_WALL_STEP = 40; +constexpr int BLOOD_WALL_CREEP_TIME = 30; +constexpr float BLOOD_WALL_CREEP_MIN = 0.9f; +constexpr float BLOOD_WALL_CREEP_GROWTH = 0.07f; +constexpr float BLOOD_WALL_SPLASH_SPEED = 2; +constexpr float BLOOD_WALL_SPLASH_BACK = 5; +constexpr float BLOOD_WALL_SPLASH_HEIGHT = -16; +constexpr float BLOOD_WALL_SPLASH_DEPTH = 10; +constexpr int BLOOD_WALL_SPLASH_PRIORITY = 255; +constexpr int BLOOD_WALL_SPLASH_SIZE = 2; +constexpr float BLOOD_WALL_SHOT_REACH = 100; +constexpr float BLOOD_WALL_SHOT_ARC = 5; +constexpr float BLOOD_WALL_SHOT_BACK = 12; + +// Raising: the fallen within 80 rise until 100 health of them stand. The Blood Cultist's pool rises 50 to 90 from +// its target, ahead of where it moves (within 80 degrees), at least 40 from every player, ten tries. +constexpr float RAISE_REACH = 6400; +constexpr float RAISE_HEALTH = 100; +constexpr float BLOOD_POOL_DELAY = 5; +constexpr float BLOOD_POOL_RETRY = 8; +constexpr int BLOOD_POOL_TRIES = 10; +constexpr float BLOOD_POOL_AHEAD_ARC = 160; +constexpr float BLOOD_POOL_MOVING = 0.001f; +constexpr float BLOOD_POOL_PLAYER_GAP = 1600; +constexpr int CULTIST_REST = 90; +constexpr int BLOOD_CULTIST_REST_MIN = 60; +constexpr int BLOOD_CULTIST_REST_RANGE = 60; +constexpr float BLOOD_CULTIST_HIT_HASTE = 5; + +// The pool: it lasts 90 frames, grabs the first hostile thing within it for 30 (a friendly one freezes it for 90), +// and pulls it in while within twice its size. +constexpr int POOL_LIFE = 90; +constexpr int POOL_HOLD = 30; +constexpr float POOL_GRAB_MARGIN = 10; +constexpr float POOL_PULL = 0.2f; +constexpr float POOL_PULL_DRAG = 0.8f; +constexpr float POOL_REACH_SCALE = 4; +constexpr float POOL_DEPTH = 20; +constexpr float POOL_FRICTION = 0.7f; +constexpr int POOL_PATH_MARKER = 900; + +// The room's killed list keeps the newest 32. +constexpr int KILLED_LIST_LIMIT = 32; +constexpr float KILLED_SPOT_SEARCH = 40; + +// 00820d30 (Room::record_killed_npc) Notes a killed enemy for the Cultists, newest first and 32 at most, moved off a +// blocked cell. Some bosses and segmented or swinging +// enemies are never noted. +void room_killed_npc_record(Room& room, Entity& npc) +{ + int type = npc.type; + switch (type) + { + case ENTITY_LARRYJR: + case ENTITY_CHUB: + case ENTITY_MRMAW: + case ENTITY_PIN: + case ENTITY_BUTTLICKER: + case ENTITY_SWINGER: + case ENTITY_GRUB: + case ENTITY_SCOURGE: + case ENTITY_MOTHER: + case ENTITY_TURDLET: + return; + default: + break; + } + if (type == ENTITY_ROUND_WORM && npc.variant == 2) return; + if ((type == ENTITY_LITTLE_HORN || type == ENTITY_RAG_MEGA) && npc.variant == 1) return; + + Vector position = npc.pos; + if (room_grid_collision_at(position) != COLLISION_NONE) + position = room_free_tile_position_find(position, KILLED_SPOT_SEARCH); + while ((int)room.killedNpcs.size() >= KILLED_LIST_LIMIT) room.killedNpcs.pop_back(); + room.killedNpcs.push_front({.position = position, + .type = type, + .variant = (int16_t)npc.variant, + .subtype = (int16_t)npc.subtype, + .championColor = static_cast(npc).championColorIdx, + .isFriendly = npc.IsFriendly()}); +} + +// Whether a killed entry is a Cultist itself, which no Cultist raises. +static bool is_cultist_fallen(const KilledNpc& fallen) +{ + return fallen.type == ENTITY_CULTIST && fallen.variant == 0; +} + +// Where the fallen lie thickest: the middle of those within 160 of the one nearest it. Nothing without any. +static Vector fallen_spot_get(Entity_NPC& npc) +{ + const KilledNpc* nearest = nullptr; + float nearestDistance = CULTIST_NO_ENEMY; + std::vector spots; + for (const KilledNpc& fallen : g_game->room->killedNpcs) + { + if (is_cultist_fallen(fallen)) continue; + float distance = vector_length_squared(vector_sub(npc.pos, fallen.position)); + if (distance < nearestDistance) + { + nearest = &fallen; + nearestDistance = distance; + } + spots.push_back(fallen.position); + } + if (!nearest || vector_is_zero(nearest->position)) return Vector{}; + + Vector sum{}; + int count = 0; + for (const Vector& spot : spots) + { + if (vector_length_squared(vector_sub(nearest->position, spot)) > CULTIST_FALLEN_GROUP) continue; + sum = vector_add(sum, spot); + count++; + } + return count ? vector_scale(sum, 1.0f / count) : nearest->position; +} + +// The enemy nearest a target the Cultist hides by: any hostile one standing, or a friendly Cultist's nearest player. +static Entity* ally_find(Entity_NPC& npc, Entity& target) +{ + if (npc.IsFriendly()) return game_nearest_player(npc.pos); + + Entity* nearest = nullptr; + float nearestDistance = CULTIST_NO_ENEMY; + for (Entity* other : g_game->room->entityList.updateEL) + { + if (!other->to_npc_or_coop_player() || other->IsFriendly() || other->entityCollisionClass == ENTCOLL_NONE) + continue; + float distance = vector_length_squared(vector_sub(target.pos, other->pos)); + if (distance >= nearestDistance) continue; + nearest = other; + nearestDistance = distance; + } + return nearest; +} + +// Picks its next spot and plan once its wait is over: the Blood Cultist lunges ahead of its target, the Cultist may +// go raise the fallen, else it drifts near the enemies by its target. +static void plan_pick(Entity_NPC& npc) +{ + Room& room = *g_game->room; + if (npc.projectileCooldown < 1 && npc.variant == CULTIST_BLOOD) + { + Entity& target = *npc.GetPlayerTarget(); + npc.i1 = PLAN_ATTACK; + Vector lead = vector_add(target.pos, vector_scale(target.velocity, BLOOD_CULTIST_LEAD)); + npc.targetPosition = room.GetClampedPositionImpl(lead, CULTIST_ROOM_MARGIN, CULTIST_ROOM_MARGIN, + CULTIST_ROOM_MARGIN, CULTIST_ROOM_MARGIN); + } + else if (npc.projectileCooldown < 1 && (Random() & (CULTIST_RAISE_ODDS - 1)) == 0 && !room.killedNpcs.empty()) + { + Vector spot = fallen_spot_get(npc); + if (!vector_is_zero(spot)) + { + npc.i1 = PLAN_RAISE; + npc.targetPosition = room.GetClampedPositionImpl(spot, CULTIST_ROOM_MARGIN, CULTIST_ROOM_MARGIN, + CULTIST_ROOM_MARGIN, CULTIST_ROOM_MARGIN); + } + } + if (npc.i1 != PLAN_NONE) + { + npc.v1.x = 0; + return; + } + + Entity& target = *npc.GetPlayerTarget(); + Entity* ally = ally_find(npc, target); + Vector spot{}; + if (ally) + { + Vector away = vector_resized(vector_sub(ally->pos, target.pos), CULTIST_ALLY_GAP); + Vector drift = random_direction(); + float spread = random_unit(); + spot = vector_add(vector_add(ally->pos, away), vector_scale(drift, spread * CULTIST_SPOT_SPREAD)); + } + else + { + float angle = random_unit() * CULTIST_SIDE_ARC - CULTIST_SIDE_ARC / 2; + Vector side = vector_rotated(vector_sub(npc.pos, target.pos), angle); + spot = vector_add(target.pos, vector_resized(side, random_unit() * CULTIST_SPOT_SPREAD + CULTIST_SPOT_MIN)); + } + npc.targetPosition = room.GetClampedPositionImpl(spot, CULTIST_ROOM_MARGIN, CULTIST_ROOM_MARGIN, + CULTIST_ROOM_MARGIN, CULTIST_ROOM_MARGIN); + if (npc.variant == CULTIST_BLOOD) + npc.i1 = (Random() & (BLOOD_CULTIST_PLAN_ODDS - 1)) == 0 ? PLAN_ATTACK : PLAN_NONE; + else + npc.i1 = PLAN_ATTACK; + npc.v1.x = 0; +} + +// Arriving at its spot: the Blood Cultist casts when its target lies in its row and in sight (else raises its pool +// when near), the Cultist raises the fallen or casts its ball. +static void arrive(Entity_NPC& npc) +{ + if (npc.variant == CULTIST_BLOOD) + { + if (npc.i1 != PLAN_ATTACK) return; + Entity* target = npc.GetPlayerTarget(); + if (!npc.IsHostileTo(target)) return; + bool isRowShot = g_game->room->camera->IsPosVisible(npc.pos) && std::abs(target->pos.y - npc.pos.y) < CULTIST_ROW && + Random() % CULTIST_CAST_ODDS == 0; + if (isRowShot) + { + npc.sprite.Play("Attack"); + npc.state = CULTIST_CAST; + npc.targetPosition = npc.pos; + npc.v1.x = 0; + npc.sprite.isFlipX = target->pos.x < npc.pos.x; + npc.v2.x = 0; + } + else if (vector_length_squared(vector_sub(npc.pos, target->pos)) < CULTIST_RAISE_REACH) + { + npc.sprite.Play("Respawn"); + npc.state = CULTIST_RAISE; + npc.targetPosition = npc.pos; + npc.v1.x = 0; + npc.v2.x = 0; + } + return; + } + + Entity* target = npc.GetPlayerTarget(); + if (npc.i1 == PLAN_RAISE) + { + npc.sprite.Play("Respawn"); + npc.state = CULTIST_RAISE; + } + else if (npc.i1 == PLAN_ATTACK && !npc.child && npc.IsHostileTo(target)) + { + npc.sprite.Play("Attack"); + npc.state = CULTIST_CAST; + } + else + return; + npc.targetPosition = npc.pos; + npc.v1.x = 0; +} + +// Drifting toward its spot, turning after it, until it arrives or gives up; then planning anew. +static void drift_update(Entity_NPC& npc) +{ + npc.friction *= CULTIST_FRICTION; + npc_anim_loop(npc.sprite, "Idle"); + if (npc.HasEntityFlags(FLAG_DISTRACTED)) + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + else if (!vector_is_zero(npc.targetPosition)) + { + npc.v1.x += npc.speedMultiplier; + float angle = vector_angle(vector_sub(npc.targetPosition, npc.pos)); + Random(); + float turn = (random_unit() * CULTIST_TURN_RANGE + CULTIST_TURN_MIN) * npc.speedMultiplier; + npc.v1.y = angle_approach(npc.v1.y, angle, turn); + float heading = npc.v1.y * DEGREES_TO_RADIANS; + float sine = std::sin(heading); + float push = random_unit() * CULTIST_PUSH_RANGE + CULTIST_PUSH_MIN; + npc.velocity.x = std::cos(heading) * push * npc.speedMultiplier + npc.velocity.x; + npc.velocity.y = sine * push * npc.speedMultiplier + npc.velocity.y; + + float arrival = npc.variant == CULTIST_BLOOD ? BLOOD_CULTIST_ARRIVE : CULTIST_ARRIVE; + if (vector_length_squared(vector_sub(npc.targetPosition, npc.pos)) < arrival) arrive(npc); + + bool isStale = npc.state == NPC_STATE_IDLE && npc.v1.x > CULTIST_GIVE_UP; + if (npc.state == NPC_STATE_IDLE && !isStale && npc.variant == 0 && npc.i1 == PLAN_ATTACK && npc.child) + isStale = Random() % CULTIST_GIVE_UP_ODDS == 0; + if (npc.state == NPC_STATE_IDLE && !isStale && npc.variant == CULTIST_BLOOD && npc.i1 == PLAN_ATTACK && + npc.projectileCooldown > 0) + isStale = Random() % CULTIST_GIVE_UP_ODDS == 0; + if (isStale) + { + npc.i1 = PLAN_NONE; + npc.v1.x = 0; + } + } + if (npc.i1 == PLAN_NONE && !npc.HasEntityFlags(FLAG_DISTRACTED)) plan_pick(npc); +} + +// The Cultist's purple ball, tossed down and circling it. +static void ball_cast(Entity_NPC& npc) +{ + uint32_t seed = Random(); + float angle = random_unit() * CULTIST_BALL_SPREAD - CULTIST_BALL_SPREAD / 2; + Entity* ball = g_game->Spawn({.position = vector_add(npc.pos, CULTIST_BALL_OFFSET), + .velocity = vector_rotated(vector_make(0, CULTIST_BALL_SPEED), angle), + .spawner = &npc, + .type = ENTITY_RAG_MEGA, + .variant = CULTIST_BALL_VARIANT, + .seed = seed}); + ball->parent = &npc; + ball->flags &= ~FLAG_APPEAR; + ball->isInvincible = true; + static_cast(ball)->v2.y = CULTIST_BALL_ORBIT; + ball->entityGridCollisionClass = GRIDCOLL_WALLS; + ball->entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + ball->Update(); + static_cast(ball)->state = NPC_STATE_MOVE; + npc.child = ball; +} + +// One stretch of the Blood Cultist's wall: creep growing with the cast, a splash of blood, a burst and a fire shot +// falling back from it. False once it leaves the room. +static bool blood_wall_step(Entity_NPC& npc, float side) +{ + Room& room = *g_game->room; + Vector spot = vector_make(side * npc.v2.x + npc.pos.x, npc.pos.y); + if (!room.IsPositionInRoom(spot, 0)) return false; + + auto* creep = static_cast(g_game->Spawn( + {.position = spot, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = Random()})); + creep->timeout = BLOOD_WALL_CREEP_TIME; + creep->lifespan = BLOOD_WALL_CREEP_TIME; + float scale = npc.stateFrame * BLOOD_WALL_CREEP_GROWTH + BLOOD_WALL_CREEP_MIN; + creep->sprite.scale = vector_make(scale, scale); + creep->Update(); + if (!room.IsPositionInRoom(spot, 0)) return true; + + float speed = random_unit(); + float height = random_unit() * BLOOD_WALL_SPLASH_HEIGHT; + Entity* splash = g_game->Spawn({.position = vector_make(spot.x - side * BLOOD_WALL_SPLASH_BACK, spot.y), + .velocity = vector_make(side * speed * BLOOD_WALL_SPLASH_SPEED, 0), + .subType = BLOOD_WALL_SPLASH_SIZE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + splash->SetColor(COLOR_DEFAULT, -1, BLOOD_WALL_SPLASH_PRIORITY, false, true); + splash->sprite.offset = vector_make(0, height); + splash->renderDepthOffset = BLOOD_WALL_SPLASH_DEPTH; + splash->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + Entity* burst = g_game->Spawn( + {.position = spot, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + burst->sizeMulti = vector_make(scale, scale); + burst->Update(); + + ProjectileParams params; + Vector aim = vector_make(side * BLOOD_WALL_SHOT_REACH + npc.pos.x, npc.pos.y); + Entity_Projectile* shot = npc.FireBossProjectiles(1, aim, BLOOD_WALL_SHOT_ARC, params); + float back = random_unit(); + shot->pos = vector_make(spot.x - side * BLOOD_WALL_SHOT_BACK * back, spot.y); + return true; +} + +// Casting: at its shot it hisses and recoils, the Cultist tossing its ball, the Blood Cultist starting its wall, +// which runs on 40 a frame. +static void cast_update(Entity_NPC& npc, int ticks) +{ + npc.friction *= CULTIST_CAST_FRICTION; + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_BOSS_LITE_HISS, 1, 2, false, 1); + npc.v1.x = 1; + if (npc.variant == 0) + ball_cast(npc); + else + { + npc.PlaySound(SOUND_HEARTOUT, 1, 2, false, 1); + npc.v2.x = BLOOD_WALL_START; + } + } + if (npc.variant == CULTIST_BLOOD && npc.v2.x > 0) + for (int tick = 0; tick < ticks; tick++) + { + if (!blood_wall_step(npc, npc.sprite.isFlipX ? -1.0f : 1.0f)) + { + npc.v2.x = 0; + continue; + } + npc.v2.x += BLOOD_WALL_STEP; + } + + if (npc.v1.x > 0) + { + if (npc.variant == CULTIST_BLOOD) + npc.velocity.x += (npc.sprite.isFlipX ? CULTIST_RECOIL : -CULTIST_RECOIL) * npc.v1.x * npc.speedMultiplier; + else + npc.velocity.y -= npc.v1.x * CULTIST_RECOIL * npc.speedMultiplier; + npc.v1.x -= npc.speedMultiplier * CULTIST_RECOIL_FADE; + } +} + +// The Cultist raises the fallen within 80 of it, up to 100 health of them, on its side. +static void fallen_raise(Entity_NPC& npc) +{ + Room& room = *g_game->room; + float raised = 0; + bool isAnyRaised = false; + for (auto fallen = room.killedNpcs.begin(); fallen != room.killedNpcs.end();) + { + if (is_cultist_fallen(*fallen) || vector_length_squared(vector_sub(npc.pos, fallen->position)) > RAISE_REACH) + { + ++fallen; + continue; + } + + Entity* risen = g_game->Spawn({.position = fallen->position, + .subType = fallen->subtype, + .type = fallen->type, + .variant = fallen->variant, + .seed = (uint32_t)fallen->championColor}); + if (npc.IsFriendly()) risen->AddCharmed(EntityRef(), -1, false, false); + risen->Update(); + raised += risen->maxHitPoints; + fallen = room.killedNpcs.erase(fallen); + isAnyRaised = true; + if (raised >= RAISE_HEALTH) break; + } + if (isAnyRaised) npc_sound_play(SOUND_SUMMONSOUND, 1, 2, 1); +} + +// The Blood Cultist's pool rises ahead of its target's way, away from the players, ten tries. +static void pool_raise(Entity_NPC& npc) +{ + Entity& target = *npc.GetPlayerTarget(); + for (int tries = 0; tries < BLOOD_POOL_TRIES; tries++) + { + Vector way = target.velocity; + float speed = vector_length(way); + if (speed >= BLOOD_POOL_MOVING) + { + float angle = random_unit() * BLOOD_POOL_AHEAD_ARC - BLOOD_POOL_AHEAD_ARC / 2; + way = vector_rotated(vector_normalized(way), angle); + } + else + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + way = vector_make(std::cos(angle), std::sin(angle)); + } + float reach = random_unit() * CULTIST_SPOT_SPREAD + CULTIST_SPOT_MIN; + Vector spot = room_free_pickup_position_find( + {.position = vector_add(target.pos, vector_scale(way, reach)), .isAvoidActiveEntities = true}); + bool isClear = npc.IsFriendly() || + vector_length_squared(vector_sub(spot, game_nearest_player(spot)->pos)) > BLOOD_POOL_PLAYER_GAP; + if (!isClear) continue; + + Entity* pool = g_game->Spawn( + {.position = spot, .spawner = &npc, .type = ENTITY_CULTIST, .variant = CULTIST_POOL, .seed = Random()}); + pool->parent = &npc; + pool->Update(); + break; + } + npc.v2.x = BLOOD_POOL_RETRY; +} + +// Raising: held in place, the Cultist raises the fallen at its shot, the Blood Cultist its pool a moment later. +static void raise_update(Entity_NPC& npc) +{ + npc.friction *= CULTIST_CAST_FRICTION; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_BOSS_LITE_HISS, 1, 2, 1); + if (npc.variant == CULTIST_BLOOD) + npc.v2.x = BLOOD_POOL_DELAY; + else + fallen_raise(npc); + } + if (npc.variant != CULTIST_BLOOD || npc.v2.x <= 0) return; + + npc.v2.x -= npc.speedMultiplier; + if (npc.v2.x <= 0) pool_raise(npc); +} + +// The Blood Cultist's pool: it appears untouchable, grabs what comes into it and fades after its time, pulling its +// catch in while near. +static void pool_update(Entity_NPC& npc, int ticks) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + npc.UpdateDirtColor(true); + npc_anim_restart(npc.sprite, "Appear"); + npc.isInvincible = true; + npc.flags = (npc.flags & ~FLAG_APPEAR) | FLAG_HIDE_HP_BAR | FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET; + npc.targetPosition = npc.pos; + npc.stateFrame = POOL_LIFE; + npc.state = NPC_STATE_IDLE; + npc.entityCollisionClass = ENTCOLL_NONE; + return; + case NPC_STATE_IDLE: + for (Entity* other : entity_query_radius(npc.pos, npc.size, QUERY_ALL)) + { + bool isTarget = other->type == ENTITY_PLAYER || Entity::is_enemy_type(other->type); + if (!isTarget || !npc.IsHostileTo(other)) continue; + npc.state = NPC_STATE_ATTACK; + npc_anim_loop(npc.sprite, "Grab"); + break; + } + break; + case CULTIST_GONE: + if (npc_anim_is_done(npc)) npc.Remove(); + break; + case NPC_STATE_ATTACK: + { + if (!npc.sprite.animState.animData || !npc.sprite.IsEventTriggered("Hit")) break; + npc.PlaySound(SOUND_BONE_BREAK, 1, 2, false, 1); + Entity* caught = nullptr; + float caughtDistance = CULTIST_NO_ENEMY; + for (Entity* other : entity_query_radius(npc.pos, npc.size + POOL_GRAB_MARGIN, QUERY_ENEMIES | QUERY_PLAYERS)) + { + float distance = vector_length_squared(vector_sub(npc.pos, other->pos)); + if (!npc.IsHostileTo(other) || distance >= caughtDistance) continue; + caught = other; + caughtDistance = distance; + } + if (caught) npc.entityRef = caught; + npc.stateFrame = npc.IsFriendly() ? POOL_LIFE : POOL_HOLD; + if (npc.IsFriendly() && caught) caught->AddFreeze(EntityRef(&npc), POOL_LIFE, false); + break; + } + default: + break; + } + + npc.stateFrame -= npc.state == CULTIST_GONE ? 0 : ticks; + if (npc.state != CULTIST_GONE && npc.stateFrame <= 0) + { + npc.entityRef = nullptr; + npc_anim_loop(npc.sprite, "Disappear"); + npc.state = CULTIST_GONE; + } + npc.friction *= POOL_FRICTION; + Vector hold = vector_sub(npc.targetPosition, npc.pos); + npc.velocity = vector_make(hold.x / npc.friction, hold.y / npc.friction); + room_path_raise_at(npc.targetPosition, POOL_PATH_MARKER); + + Entity* caught = npc.entityRef; + if (!caught) return; + Vector pull = vector_sub(npc.pos, caught->pos); + if (vector_length_squared(pull) > npc.size * npc.size * POOL_REACH_SCALE) + { + npc.entityRef = nullptr; + return; + } + float speed = npc.speedMultiplier; + npc.renderDepthOffset = POOL_DEPTH; + float drag = timescale_factor(POOL_PULL_DRAG, speed); + pull = vector_scale(pull, POOL_PULL); + caught->velocity = vector_add(vector_scale(pull, speed), vector_scale(caught->velocity, drag)); + npc.velocity = vector_sub(vector_scale(npc.velocity, drag), vector_scale(pull, speed)); +} + +// 004ed840 The Cultist's, Blood Cultist's and blood pool's AI: drifting about its target's side, raising the fallen, +// casting balls and walls of blood, and the pool that grabs. +void npc_cultist_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + if (npc.variant == CULTIST_POOL) return pool_update(npc, ticks); + + switch (npc.state) + { + case NPC_STATE_INIT: + if (npc.variant == 0) + { + npc.splatColor = CULTIST_SPLAT; + for (int layer : CULTIST_HIDDEN_LAYERS) npc.sprite.GetLayer(layer)->bitflags |= ANIM_RENDER_UNTINTED; + } + npc.state = NPC_STATE_IDLE; + npc.targetPosition = npc.pos; + npc.projectileCooldown = (int)(Random() % CULTIST_FIRST_WAIT_RANGE) + CULTIST_FIRST_WAIT_MIN; + npc.v1.x = 0; + npc.v1.y = random_unit() * FULL_TURN_DEGREES; + break; + case NPC_STATE_IDLE: + drift_update(npc); + break; + case CULTIST_CAST: + case CULTIST_RAISE: + { + bool isRaising = npc.state == CULTIST_RAISE; + if (isRaising) raise_update(npc); + else cast_update(npc, ticks); + if (!npc_anim_is_done(npc)) break; + npc.state = NPC_STATE_IDLE; + npc.i1 = PLAN_NONE; + if (npc.variant == CULTIST_BLOOD) + npc.projectileCooldown = (int)(Random() % BLOOD_CULTIST_REST_RANGE) + BLOOD_CULTIST_REST_MIN; + else if (isRaising) + npc.projectileCooldown = CULTIST_REST; + break; + } + default: + break; + } + + if (npc.projectileCooldown > 0) npc.projectileCooldown = std::max(npc.projectileCooldown - ticks, 0); + if (npc.variant == CULTIST_BLOOD) + npc.projectileCooldown = + std::max((int)((float)npc.projectileCooldown - npc.pendingDamage * BLOOD_CULTIST_HIT_HASTE), 0); +} diff --git a/src/npc_danny.cpp b/src/npc_danny.cpp new file mode 100644 index 0000000..5b11b24 --- /dev/null +++ b/src/npc_danny.cpp @@ -0,0 +1,216 @@ +#include "npc_alt.h" +#include "entity_effect.h" +#include "npc_fireplace.h" +#include "path_finder.h" +#include "room.h" +#include + +// Danny (variant 0) throws rocks and rock spiders, Coal Boy (variant 1) coal spiders and coal fires. Their splats are +// pale grey and glowing orange. +constexpr int DANNY_COAL_BOY = 1; +constexpr ColorMod DANNY_SPLAT_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 0.1f}, {0, 0, 0}}; +constexpr ColorMod COAL_BOY_SPLAT_COLOR = {{0, 0, 0, 1.1f}, {0, 0, 0, 0}, {1, 0.514f, 0.004f}}; + +// They walk at 0.6 and recharge over 150 frames (10 to 19 at first, twice as fast while hurt hard), then throw one +// time in 60 a frame (one in 20 more while hurt hard): always within 200 of the target, one time in ten within 400. +// Not with nine spiders (or coal fires) about, nor when Hornfel spawned them. +constexpr float DANNY_SPEED = 0.6f; +constexpr int DANNY_PATH_MARKER = 0; +constexpr float DANNY_WALK_THRESHOLD = 0.1f; +constexpr float DANNY_FLEE_FRICTION = 0.8f; +constexpr float DANNY_THROW_FRICTION = 0.7f; +constexpr int DANNY_RECHARGE = 150; +constexpr int DANNY_FIRST_WAIT = 10; +constexpr uint32_t DANNY_FIRST_WAIT_RANGE = 10; +constexpr float DANNY_HURT_HARD = 6; +constexpr float DANNY_HURT_RECOVERY = 0.11f; +constexpr uint32_t DANNY_THROW_ODDS = 60; +constexpr uint32_t DANNY_HURT_THROW_ODDS = 20; +constexpr float DANNY_NEAR = 200; +constexpr float DANNY_FAR = 400; +constexpr uint32_t DANNY_FAR_ODDS = 10; +constexpr int DANNY_CROWD = 9; +constexpr float DANNY_CONTROLLED_REACH = 1000; +constexpr float DANNY_STEER_AIM = 100; +constexpr uint32_t DANNY_GRUMBLE_ODDS = 3; +constexpr float DANNY_GRUMBLE_VOLUME = 0.8f; +constexpr int DANNY_GRUMBLE_DELAY = 120; + +// The throw: up to 30 degrees off its aim, from 4 out, 15 up. Danny throws six rocks, or rock spiders for those of +// its two it lost. Coal Boy throws four, coal spiders for the one it lost and coal fires for the rest. Both leave a +// spray of grit. +constexpr float THROW_SPREAD = 30; +constexpr float THROW_SPREAD_CENTER = 0.5f; +constexpr float THROW_OUT = 4; +constexpr float DANNY_THROW_HEIGHT = -15; +constexpr int DANNY_ROCKS = 6; +constexpr int DANNY_SPIDERS = 2; +constexpr float DANNY_SPIDER_SPEED = 1; +constexpr float DANNY_SPIDER_SPEED_RANGE = 3; +constexpr int COAL_BOY_THROWS = 4; +constexpr int COAL_BOY_SPIDERS = 1; +constexpr float COAL_BOY_THROW_SPEED = 1; +constexpr float COAL_BOY_THROW_SPEED_RANGE = 9; +constexpr int DANNY_GRIT = 5; +constexpr int COAL_BOY_EMBERS = 6; +constexpr int DANNY_GRIT_SUBTYPE = 99; +constexpr float GRIT_SPEED = 2; +constexpr float GRIT_SPEED_RANGE = 4; +constexpr float GRIT_LIFT = 14; +constexpr ColorMod DANNY_GRIT_COLOR = {{0.54901963f, 0.48235294f, 0.48235294f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float DANNY_THROW_PITCH = 1.1f; +constexpr int DANNY_THROW_DELAY = 10; + +// Danny's states: walking and throwing. +constexpr int DANNY_WALK = NPC_STATE_MOVE; +constexpr int DANNY_THROW = NPC_STATE_ATTACK; + +// A direction up to 15 degrees either side of the aim. +static Vector throw_direction(Vector aim) +{ + return vector_rotated(aim, (random_unit() - THROW_SPREAD_CENTER) * THROW_SPREAD); +} + +// A spray of grit (embers for Coal Boy) from within its size along the aim. +static void throw_grit_spray(Entity_NPC& npc, Vector aim) +{ + bool isCoal = npc.variant == DANNY_COAL_BOY; + for (int bit = 0; bit < (isCoal ? COAL_BOY_EMBERS : DANNY_GRIT); bit++) + { + Vector direction = throw_direction(aim); + float speed = random_unit() * GRIT_SPEED_RANGE + GRIT_SPEED; + Vector position = vector_add(npc.pos, vector_scale(direction, npc.size * random_unit())); + Entity* grit = g_game->Spawn({.position = position, .velocity = vector_scale(direction, speed), + .subType = isCoal ? 0 : DANNY_GRIT_SUBTYPE, .type = ENTITY_EFFECT, + .variant = isCoal ? EFFECT_EMBER_PARTICLE : EFFECT_TOOTH_PARTICLE, .seed = Random()}); + grit->posOffset.y -= GRIT_LIFT; + if (!isCoal) grit->SetColor(DANNY_GRIT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + grit->Update(); + } +} + +// The throw on Shoot: rocks or coal along the aim (its controller's way when steered), spiders for those lost. +static void danny_throw(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_MONSTER_GRUNT_2, 1, DANNY_THROW_DELAY, false, DANNY_THROW_PITCH); + Vector target = npc.GetPlayerTarget()->pos; + npc.UpdateControllerMovement(false); + if (npc.controllerID != -1) target = vector_add(npc.pos, vector_scale(npc.controllerMovement, DANNY_STEER_AIM)); + Vector aim = vector_normalized(vector_sub(target, npc.pos)); + int kept = (int)Entity_NPC::QueryNPCsGroup(npc.index).size(); + + if (npc.variant == DANNY_COAL_BOY) + { + int lost = std::max(COAL_BOY_SPIDERS - kept, 0); + for (int thrown = 0; thrown < COAL_BOY_THROWS; thrown++) + { + Vector direction = throw_direction(aim); + Vector from = vector_add(npc.pos, vector_scale(direction, THROW_OUT)); + Vector velocity = vector_scale(direction, random_unit() * COAL_BOY_THROW_SPEED_RANGE + COAL_BOY_THROW_SPEED); + RockSpiderKind kind = thrown < lost ? SPIDER_THROW_COAL : SPIDER_THROW_COAL_FIRE; + Entity_NPC* spider = rock_spider_throw(from, velocity, &npc, kind, DANNY_THROW_HEIGHT); + if (thrown < lost) spider->groupIdx = npc.index; + } + return throw_grit_spray(npc, aim); + } + + int lost = std::max(DANNY_SPIDERS - kept, 0); + ProjectileParams params; + params.variant = PROJECTILE_ROCK; + npc.FireBossProjectiles(DANNY_ROCKS - lost, target, 1, params); + for (int thrown = 0; thrown < lost; thrown++) + { + Vector direction = throw_direction(aim); + Vector from = vector_add(npc.pos, vector_scale(direction, THROW_OUT)); + Vector velocity = vector_scale(direction, random_unit() * DANNY_SPIDER_SPEED_RANGE + DANNY_SPIDER_SPEED); + rock_spider_throw(from, velocity, &npc, SPIDER_THROW_ROCK, DANNY_THROW_HEIGHT)->groupIdx = npc.index; + } + throw_grit_spray(npc, aim); +} + +// The spiders (Danny) or fires (Coal Boy) already in the room. Coal Boy counts blue fires (33.2), as the original +// does, not the coal fires (33.11) it throws. +static int danny_crowd_count(Entity_NPC& npc) +{ + int crowd = 0; + for (Entity* entity : g_game->room->entityList.updateEL) + { + bool isCrowd = npc.variant == DANNY_COAL_BOY + ? entity->type == ENTITY_FIREPLACE && entity->variant == FIRE_BLUE + : (entity->type == ENTITY_SPIDER && entity->variant == 0) || entity->type == ENTITY_ROCK_SPIDER; + if (isCrowd) crowd++; + } + return crowd; +} + +// Whether it winds up a throw now: recharged, by chance (more when hurt hard), near enough and not crowded. +static bool danny_is_throwing(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + if (npc.stateFrame > 0) npc.stateFrame -= ticks; + if (npc.v1.x > DANNY_HURT_HARD && npc.stateFrame > 0) npc.stateFrame -= ticks; + if (npc.stateFrame > 0) return false; + + bool isControlled = npc.controllerID != -1; + if (isControlled && !npc.IsTargetInAttackRange(DANNY_CONTROLLED_REACH, 0, true)) return false; + if (!isControlled && Random() % DANNY_THROW_ODDS != 0 && + (npc.v1.x <= DANNY_HURT_HARD || Random() % DANNY_HURT_THROW_ODDS != 0)) + return false; + if (npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK) || npc.spawnerType == ENTITY_HORNFEL) return false; + + float distance = vector_length(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)); + bool isInReach = distance < DANNY_NEAR || (distance < DANNY_FAR && Random() % DANNY_FAR_ODDS == 0) || isControlled; + return isInReach && danny_crowd_count(npc) < DANNY_CROWD; +} + +// Walking at its target, steered away only when controlled and afraid, then maybe winding up a throw. +static void danny_walk_update(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", DANNY_WALK_THRESHOLD); + // The original evades only a controlled Danny that is afraid, so a frightened wild one still walks at its target. + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && npc.controllerID != -1) + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= DANNY_FLEE_FRICTION; + } + else npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), DANNY_SPEED, DANNY_PATH_MARKER, DIRECT_PATH_FAR); + if (npc.pathfinder.hasDirectPath && Random() % DANNY_GRUMBLE_ODDS == 0) + npc.PlaySound(SOUND_ANGRY_GURGLE, DANNY_GRUMBLE_VOLUME, DANNY_GRUMBLE_DELAY, false, 1); + npc.UpdateChargeBar(DANNY_RECHARGE, 0, (float)npc.stateFrame, true); + if (!danny_is_throwing(npc)) return; + + Vector target = npc.GetPlayerTarget()->pos; + npc.UpdateControllerMovement(true); + float aimX = npc.controllerID == -1 ? target.x : npc.controllerMovement.x * DANNY_STEER_AIM + npc.pos.x; + npc.sprite.isFlipX = aimX < npc.pos.x; + npc.state = DANNY_THROW; + npc.sprite.Play("Attack"); + npc.stateFrame = DANNY_RECHARGE; +} + +// 004fbd10 Danny's and Coal Boy's AI: they walk at their target and throw rocks or coal, and spiders to replace the +// ones they lost. +void npc_danny_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = DANNY_WALK; + npc.sprite.Play("WalkVert"); + npc.splatColor = npc.variant == DANNY_COAL_BOY ? COAL_BOY_SPLAT_COLOR : DANNY_SPLAT_COLOR; + npc.stateFrame = npc.controllerID == -1 ? (int)(Random() % DANNY_FIRST_WAIT_RANGE) + DANNY_FIRST_WAIT + : DANNY_FIRST_WAIT; + break; + case DANNY_WALK: + danny_walk_update(npc); + break; + case DANNY_THROW: + npc.friction *= DANNY_THROW_FRICTION; + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Shoot")) danny_throw(npc); + if (!npc.sprite.IsPlaying()) npc.state = DANNY_WALK; + break; + } + + if (npc.pendingDamage > 0) npc.v1.x += npc.pendingDamage; + if (npc.v1.x > 0) npc.v1.x = std::max(npc.v1.x - npc.speedMultiplier * DANNY_HURT_RECOVERY, 0.0f); +} diff --git a/src/npc_dip.cpp b/src/npc_dip.cpp index 5f14786..71114e6 100644 --- a/src/npc_dip.cpp +++ b/src/npc_dip.cpp @@ -1,8 +1,10 @@ #include "npc_ai.h" +#include "active_items.h" #include "entity_effect.h" #include "entity_familiar.h" #include "entity_player.h" #include "game.h" +#include "menu_manager.h" #include "room.h" constexpr int DIP_BIG_CORN = 3; @@ -25,26 +27,38 @@ constexpr float HURT_VOLUME = 0.8f; constexpr int HURT_SOUND_DELAY = 15; constexpr float CORN_AIM_LEAD = 0.1f; constexpr float CORN_SHOT_SPEED = 10; -constexpr float CONTROLLER_DEADZONE = 0.1f; -constexpr ColorMod DIP_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.25490198f, 0.16078432f, 0.13725491f}}; -constexpr ColorMod BROWNIE_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0}}; -// A hop: a random way (away from its target while it fears it), faster for the corn dips. +// The Drip hops slower (5 to 8), one time in three at its target, pushed back by the room's current, slides with +// less friction and may hop again from frame 10 of its hop, one time in three. +constexpr float DRIP_HOP_SPEED_RANGE = 3; +constexpr int DRIP_AIM_ODDS = 3; +constexpr float DRIP_CURRENT_PUSH = 8; +constexpr float DRIP_FRICTION = 0.9f; +constexpr int DRIP_REHOP_FRAME = 10; +constexpr int DRIP_REHOP_ODDS = 3; +constexpr float CONTROLLER_DEADZONE = 0.1f; + +// A hop: a random way (away from its target while it fears it), faster for the corn dips. The Drip hops at its +// target one time in three and against the room's current. static void dip_hop(Entity_NPC& npc) { npc.state = NPC_STATE_MOVE; + bool isDrip = npc.type == ENTITY_DRIP; bool isFleeing = npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && npc.controllerID == -1; Vector direction; if (isFleeing) direction = vector_normalized(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)); else { - direction = random_direction(); + bool isAimed = isDrip && Random() % DRIP_AIM_ODDS == 0; + direction = isAimed ? vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)) : random_direction(); if (npc.controllerID != -1) direction = npc.GetControllerInput(0); } - float speed = random_unit() * HOP_SPEED_RANGE + HOP_SPEED_MIN; - bool isDoubled = npc.variant == DIP_CORN || (isFleeing && npc.variant == DIP_BROWNIE); + float speed = random_unit() * (isDrip ? DRIP_HOP_SPEED_RANGE : HOP_SPEED_RANGE) + HOP_SPEED_MIN; + bool isDoubled = !isDrip && (npc.variant == DIP_CORN || (isFleeing && npc.variant == DIP_BROWNIE)); Vector hop = vector_scale(direction, isDoubled ? speed * 2 : speed); + Vector current = g_game->room->waterCurrent; + if (isDrip && !isFleeing && !vector_is_zero(current)) hop = vector_sub(hop, vector_scale(current, DRIP_CURRENT_PUSH)); if (npc.friction != 0) npc.velocity = vector_add(npc.velocity, vector_scale(hop, npc.speedMultiplier / npc.friction)); } @@ -61,12 +75,11 @@ static void dip_corn_shoot(Entity_NPC& npc) PROJECTILES_SINGLE, params); } -// 00534860 The Dip's AI: it rests, hops about (fleeing what it fears), slides to a stop and leaves poop splats. Dirty -// Mind and the Dipping trinket turn it into the players' own dip. +// 00534860 The Dip's and the Drip's AI: it rests, hops about (fleeing what it fears), slides to a stop and leaves +// poop splats. Dirty Mind and the Dipping trinket turn it into the players' own dip. void npc_dip_update(Entity_NPC& npc) { - if (npc.type != ENTITY_DIP) reconstruction_missing("npc_dip_update 00534860: the other dip kin"); - + bool isDrip = npc.type == ENTITY_DRIP; PlayerManager& players = g_game->playerManager; bool isTamed = players.FirstCollectibleOwner(COLLECTIBLE_DIRTY_MIND_ID, LAZARUS_SHARE_CHECK) || players.AnyoneHasTrinket(TRINKET_DIPPING_TRINKET_ID); @@ -78,8 +91,8 @@ void npc_dip_update(Entity_NPC& npc) { npc.entityCollisionClass = ENTCOLL_NONE; npc.Remove(); - bool isCorn = npc.variant == DIP_CORN || npc.variant == DIP_BIG_CORN; - int dip = npc.variant == DIP_BROWNIE ? FAMILIAR_DIP_BROWNIE : isCorn ? FAMILIAR_DIP_CORN : 0; + bool isCorn = !isDrip && (npc.variant == DIP_CORN || npc.variant == DIP_BIG_CORN); + int dip = !isDrip && npc.variant == DIP_BROWNIE ? FAMILIAR_DIP_BROWNIE : isCorn ? FAMILIAR_DIP_CORN : 0; Entity_Familiar::ThrowDip(dip, npc.pos, owner); return; } @@ -88,10 +101,11 @@ void npc_dip_update(Entity_NPC& npc) if (npc.state == NPC_STATE_INIT) { npc.state = NPC_STATE_IDLE; - npc.splatColor = npc.variant == DIP_BROWNIE ? BROWNIE_SPLAT : DIP_SPLAT; + npc.splatColor = npc.variant == DIP_BROWNIE ? LIGHT_POOP_SPLAT_COLOR : POOP_SPLAT_COLOR; return; } - bool isFloating = npc.variant == DIP_BIG_CORN && g_game->room->waterAmount > 0; + bool isBigCorn = npc.type == ENTITY_DIP && npc.variant == DIP_BIG_CORN; + bool isFloating = (isDrip || isBigCorn) && g_game->room->waterAmount > 0; npc.entityGridCollisionClass = isFloating ? GRIDCOLL_NOPITS : GRIDCOLL_GROUND; if (npc.state == NPC_STATE_IDLE || npc.state == NPC_STATE_SPECIAL) @@ -101,13 +115,17 @@ void npc_dip_update(Entity_NPC& npc) (npc.controllerID == -1 ? Random() % HOP_ODDS == 0 : !vector_is_zero(npc.GetControllerInput(CONTROLLER_DEADZONE))); if (isHopping) dip_hop(npc); - npc.friction *= HOP_FRICTION; + npc.friction *= isDrip ? DRIP_FRICTION : HOP_FRICTION; } else if (npc.state == NPC_STATE_MOVE) { npc.sprite.Play("Move"); npc.friction *= SLIDE_FRICTION; - if (vector_length_squared(npc.velocity) < 1) npc.state = NPC_STATE_IDLE; + bool isRehop = isDrip && npc.sprite.GetFrame() == DRIP_REHOP_FRAME && + (Random() % DRIP_REHOP_ODDS == 0 || npc.controllerID != -1); + if (isRehop) npc.state = NPC_STATE_SPECIAL; + else if (isDrip ? !npc.sprite.IsPlaying() : vector_length_squared(npc.velocity) < 1) + npc.state = NPC_STATE_IDLE; } npc.sprite.isFlipX = npc.velocity.x < 0; @@ -116,7 +134,7 @@ void npc_dip_update(Entity_NPC& npc) ->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); if (npc.pendingDamage > 0 && (Random() & 1) == 0) npc.PlaySound(SOUND_DIP_HURT, HURT_VOLUME, HURT_SOUND_DELAY, false, 1); - if (npc.variant == DIP_BIG_CORN && npc.controllerID != -1) - reconstruction_missing("npc_dip_update 00534860: a controlled corn dip bursting"); - if (npc.isDead && npc.variant == DIP_BIG_CORN && !npc.HasEntityFlags(FLAG_SHRINK)) dip_corn_shoot(npc); + if (isBigCorn && npc.controllerID != -1 && input_is_action_pressed(ACTION_BOMB, npc.controllerID, &npc)) + npc.Kill(EntityRef()); + if (npc.isDead && isBigCorn && !npc.HasEntityFlags(FLAG_SHRINK)) dip_corn_shoot(npc); } diff --git a/src/npc_dirt.cpp b/src/npc_dirt.cpp index 77358fa..90b0b39 100644 --- a/src/npc_dirt.cpp +++ b/src/npc_dirt.cpp @@ -1,4 +1,5 @@ #include "npc_basement.h" +#include "fx_layers.h" #include "gl.h" #include "kage_graphics.h" #include "room.h" @@ -6,7 +7,6 @@ #include #include -constexpr KColor WHITE = kcolor_rgba(1, 1, 1, 1); constexpr float CHANNEL_MAX = 255; // The five points a sized sample reads (the middle, left, right, above and below), in radii, and the floor's scale diff --git a/src/npc_dump.cpp b/src/npc_dump.cpp new file mode 100644 index 0000000..c689729 --- /dev/null +++ b/src/npc_dump.cpp @@ -0,0 +1,293 @@ +#include "npc_alt.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_projectile.h" +#include "grid_entity.h" +#include "path_finder.h" +#include +#include + +// The Dump (variant 0) walks at 0.4 trailing slippery creep. Killed, it stays as a spouting poop pile and its head +// (variant 1) flies off the way it was last hit at 14, then rolls after its target at 0.78. +constexpr int DUMP_HEAD = 1; +constexpr float DUMP_SPEED = 0.4f; +constexpr float DUMP_HEAD_SPEED = 0.78f; +constexpr float DUMP_FLEE_FRICTION = 0.8f; +constexpr uint32_t DUMP_GROWL_ODDS = 6; +constexpr int DUMP_GROWL_DELAY = 90; +constexpr std::array DUMP_HEAD_WALKS = {"HeadWalk0", "HeadWalk1", "HeadWalk2"}; +constexpr float DUMP_KNOCK_SPEED = 14; +constexpr float DUMP_KNOCK_NEAR_SQUARED = 0.0001f; + +// The flying head eases toward its speed, bounces off walls at 1.8 of its push, slows by 0.8 to 0.995 a frame (more +// when slower), spins with its speed and rolls again below 0.25. Its roll shows the 12 frames of a turn. +constexpr float HEAD_EASE = 0.5f; +constexpr float HEAD_BOUNCE = 1.8f; +constexpr float HEAD_DRAG_SPEED = 1; +constexpr float HEAD_DRAG_SPAN = 10; +constexpr float HEAD_DRAG_RANGE = 0.195f; +constexpr float HEAD_DRAG_MIN = 0.8f; +constexpr float HEAD_ROLL_SPEED = 0.25f; +constexpr float HEAD_ROLL_TURN = -90; +constexpr int HEAD_ROLL_FRAMES = 12; + +// The pile spouts (Spout0 to Spout5 as it drains) losing a 150th of its health a frame, spitting puke shots faster +// the fuller it is (every 2 to 15 frames), and takes a tenth of its damage. Past Spout1 it no longer shuts the doors, +// past Spout4 it has no shadow. +constexpr std::array DUMP_SPOUTS = {"Spout0", "Spout1", "Spout2", "Spout3", "Spout4", "Spout5"}; +constexpr float DUMP_DRAIN = 150; +constexpr float DUMP_CREEP_SCALE = 1 / DUMP_DRAIN; +constexpr int DUMP_SPOUT_LAST = 5; +constexpr int DUMP_SPOUT_DOORS = 1; +constexpr int DUMP_SPOUT_SHADOW = 4; +constexpr float DUMP_SPIT_GAP = 30; +constexpr float DUMP_SPIT_FULL = 13; +constexpr float DUMP_SPIT_EMPTY = 2; +constexpr float DUMP_SPIT_TRAJECTORY = 10; +constexpr float DUMP_SPIT_SLOWDOWN = 0.5f; +constexpr float DUMP_DAMAGE_TAKEN = 0.1f; +constexpr float DUMP_LAST_HEALTH = 0.001f; +constexpr float DUMP_PILE_SIZE = 0.5f; +constexpr uint64_t DUMP_FADE_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH; +constexpr int CHAMPION_DUMP_HIGH = 18; +constexpr int CHAMPION_DUMP_LOW = 19; +constexpr float DUMP_HIGH_PITCH = 1.5f; +constexpr float DUMP_LOW_PITCH = 0.5f; + +// It leaves creep every 8 frames (3 while flying), one time in three with a light splat. +constexpr int DUMP_CREEP_EVERY = 8; +constexpr int DUMP_FLYING_CREEP_EVERY = 3; +constexpr float DUMP_CREEP_SIZE = 0.75f; +constexpr float DUMP_CREEP_SIZE_RANGE = 0.25f; +constexpr uint32_t DUMP_SPLAT_ODDS = 3; +constexpr float DUMP_SPLAT_SIZE = 0.3f; +constexpr float DUMP_SPLAT_SIZE_RANGE = 0.6f; + +// The Dump's states: walking or rolling, the head flying, and the spouting pile. +constexpr int DUMP_WALK = NPC_STATE_MOVE; +constexpr int DUMP_FLYING = NPC_STATE_ATTACK; +constexpr int DUMP_SPOUTING = NPC_STATE_SPECIAL; + +// Walking at its target (or away from what it fears). The head turns its roll along its push. +static void dump_walk_update(Entity_NPC& npc, std::string_view headWalk) +{ + bool isHead = npc.variant == DUMP_HEAD; + if (isHead) npc.sprite.PlayOverlay("WalkOverlay"); + else + { + npc.sprite.Play("Walk"); + npc.sprite.PlayOverlay(headWalk); + npc.sprite.isFlipX = npc.velocity.x < 0; + if (npc.pathfinder.hasDirectPath && Random() % DUMP_GROWL_ODDS == 0) + npc.PlaySound(SOUND_ANGRY_GURGLE, 1, DUMP_GROWL_DELAY, false, 1); + } + + Vector previous = npc.velocity; + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), isHead ? DUMP_HEAD_SPEED : DUMP_SPEED, GRID_PATH_FREED, + DIRECT_PATH_FAR); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= DUMP_FLEE_FRICTION; + } + Vector push = vector_sub(npc.velocity, previous); + if (isHead && !vector_is_zero(push)) npc.v1.x = vector_angle(push) + HEAD_ROLL_TURN; +} + +// The head flying from the body: easing to its speed, bouncing off walls, slowing and spinning. +static void dump_flying_update(Entity_NPC& npc) +{ + float speed = npc.speedMultiplier; + float keep = speed == 1 ? HEAD_EASE : HEAD_EASE / ((speed + HEAD_EASE) - speed * HEAD_EASE); + npc.velocity = vector_add(npc.velocity, vector_scale(vector_sub(npc.v2, npc.velocity), 1 - keep)); + if (npc.isCollidesWithGrid) + { + npc_sound_play(SOUND_MEAT_JUMPS, 1, 2, 1); + Vector hit = npc.gridCollisionVelocity; + Vector normal = npc.gridCollisionNormal; + npc.velocity = vector_sub(hit, vector_scale(normal, HEAD_BOUNCE * vector_dot(hit, normal))); + npc.v2 = vector_scale(vector_normalized(npc.velocity), vector_length(npc.v2)); + } + + float drag = std::clamp((vector_length(npc.v2) - HEAD_DRAG_SPEED) / HEAD_DRAG_SPAN, 0.0f, 1.0f) * HEAD_DRAG_RANGE + + HEAD_DRAG_MIN; + if (speed != 1) drag = drag / ((drag + speed) - drag * speed); + npc.v2 = vector_scale(npc.v2, drag); + npc.v1.x = normalize_angle_degrees(vector_length(npc.velocity) + npc.v1.x); + if (vector_length(npc.v2) < HEAD_ROLL_SPEED) npc.state = DUMP_WALK; +} + +// The pile spouting: its creep, its spout stage, draining to its fade and spitting as it goes. Whether it is still +// there. +static bool dump_spout_update(Entity_NPC& npc) +{ + if (npc.sprite.overlayAnimState.animData) npc.sprite.overlayAnimState.SetAnimationData(nullptr); + if (!npc.child) + { + auto* creep = static_cast(g_game->Spawn({.position = npc.pos, .spawner = &npc, + .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_SLIPPERY_BROWN_GROWING, .seed = Random()})); + creep->scale = DUMP_CREEP_SCALE; + creep->parent = &npc; + creep->Update(); + npc.child = creep; + } + + if (npc.entityCollisionClass == ENTCOLL_NONE && !npc.sprite.IsPlaying()) + { + npc.Remove(); + return false; + } + if (npc.entityCollisionClass != ENTCOLL_NONE) + { + int spout = std::clamp((int)((npc.maxHitPoints - npc.health) * DUMP_SPOUTS.size() / npc.maxHitPoints), 0, + DUMP_SPOUT_LAST); + if (spout > DUMP_SPOUT_DOORS) npc.isCanShutDoors = false; + if (spout > DUMP_SPOUT_SHADOW) npc.shadowSize = 0; + npc.sprite.Play(DUMP_SPOUTS[spout]); + npc.health = std::max(npc.health - npc.maxHitPoints / DUMP_DRAIN, 0.0f); + if (npc.health <= 0 || npc.isDead) + { + npc.health = DUMP_LAST_HEALTH; + npc.isDead = false; + npc.sprite.Play("Fade"); + npc.AddEntityFlags(DUMP_FADE_FLAGS); + npc.entityCollisionClass = ENTCOLL_NONE; + } + + npc.v1.y += npc.speedMultiplier; + float gap = DUMP_SPIT_GAP / (std::clamp(npc.health / npc.maxHitPoints, 0.0f, 1.0f) * DUMP_SPIT_FULL + + DUMP_SPIT_EMPTY); + while (npc.v1.y >= gap) + { + npc.v1.y -= gap; + ProjectileParams params; + params.variant = PROJECTILE_PUKE; + Entity_Projectile* shot = npc.FireBossProjectiles(1, {}, DUMP_SPIT_TRAJECTORY, params); + shot->velocity = vector_scale(shot->velocity, DUMP_SPIT_SLOWDOWN); + float pitch = npc.championColorIdx == CHAMPION_DUMP_HIGH ? DUMP_HIGH_PITCH + : npc.championColorIdx == CHAMPION_DUMP_LOW ? DUMP_LOW_PITCH + : 1; + npc_sound_play(SOUND_TEARS_FIRE, 1, 2, pitch); + } + } + + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (npc.pendingDamage <= 0) return true; + npc.pendingDamage = 0; + for (DamageEvent& event : npc.damageEvents) + { + event.damage *= DUMP_DAMAGE_TAKEN; + npc.pendingDamage += event.damage; + } + return true; +} + +// The creep trail and its light splats. +static void dump_creep_update(Entity_NPC& npc) +{ + int every = npc.state == DUMP_FLYING ? DUMP_FLYING_CREEP_EVERY : DUMP_CREEP_EVERY; + if (npc.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused() || + (g_game->frameCount + npc.index) % every != 0) + return; + + Entity* creep = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_SLIPPERY_BROWN, .seed = Random()}); + float size = random_unit() * DUMP_CREEP_SIZE_RANGE + DUMP_CREEP_SIZE; + creep->sprite.scale = vector_make(size, size); + creep->Update(); + if (Random() % DUMP_SPLAT_ODDS == 0) + npc.MakeSplat(random_unit() * DUMP_SPLAT_SIZE_RANGE + DUMP_SPLAT_SIZE) + ->SetColor(LIGHT_POOP_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// The head's look: its roll layer placed by the overlay's null, and the roll frame of its spin. +static void dump_head_render_update(Entity_NPC& npc) +{ + const NullFrame* guide = npc.sprite.overlayAnimState.GetNullFrameById(1); + if (!guide) return; + LayerState& roll = *npc.sprite.GetLayer(0); + roll.pos = guide->pos; + roll.size = guide->scale; + roll.rotation = guide->rotation; + float spin = npc.v1.x < 0 ? npc.v1.x + FULL_TURN_DEGREES : npc.v1.x; + if (npc.sprite.animState.animData) + npc.sprite.animState.SetFrameFloat((float)(uint32_t)(spin * HEAD_ROLL_FRAMES / FULL_TURN_DEGREES)); +} + +// Killed, the body turns into the spouting pile and its head flies off, taking any control with it. +static void dump_split(Entity_NPC& npc) +{ + npc.health = npc.maxHitPoints; + npc.state = DUMP_SPOUTING; + npc.isDead = false; + npc.targetPosition = npc.pos; + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.size = npc.config->collisionRadius * DUMP_PILE_SIZE; + + auto* head = static_cast(g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = npc.type, + .variant = npc.variant + 1, .seed = npc.dropRNG.Next()})); + if (npc.isChampion) head->Morph(head->type, head->variant, head->subtype, npc.championColorIdx); + head->ClearEntityFlags(FLAG_APPEAR); + head->Update(); + head->state = DUMP_FLYING; + head->v2 = npc.v2; + head->velocity = npc.v2; + head->sprite.PlayOverlay("FallOverlay"); + npc.TransferControl(head); +} + +// 00562f00 The Dump's AI: the body walks trailing creep until killed, then spouts as a draining pile while its head +// flies off the way it was hit and rolls after its target. +void npc_dump_update(Entity_NPC& npc) +{ + std::string_view headWalk = DUMP_HEAD_WALKS[npc.initSeed % DUMP_HEAD_WALKS.size()]; + bool isHead = npc.variant == DUMP_HEAD; + if (isHead && !npc.sprite.overlayAnimState.animData) + { + if (npc.sprite.SetAnimation("Reference", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } + npc.sprite.PlayOverlay("WalkOverlay"); + } + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = DUMP_WALK; + npc.stateFrame = 0; + npc.splatColor = POOP_SPLAT_COLOR; + if (isHead) + { + npc.sprite.SetFrame("Reference", 0); + npc.sprite.PlayOverlay("WalkOverlay"); + npc.v1.x = 0; + break; + } + if (npc.sprite.SetOverlayAnimation(headWalk, SWITCH_KEEP_FRAME) && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); + npc.sprite.SetFrame("Walk", 0); + break; + case DUMP_WALK: + dump_walk_update(npc, headWalk); + break; + case DUMP_FLYING: + dump_flying_update(npc); + break; + case DUMP_SPOUTING: + if (!dump_spout_update(npc)) return; + break; + } + + dump_creep_update(npc); + if (npc.variant == 0 && npc.pendingDamage > 0 && !npc.damageEvents.empty()) + { + Vector knock = vector_sub(npc.pos, npc.damageEvents.back().source.position); + if (vector_length_squared(knock) > DUMP_KNOCK_NEAR_SQUARED) + npc.v2 = vector_scale(vector_normalized(knock), DUMP_KNOCK_SPEED); + } + else if (isHead) dump_head_render_update(npc); + if (npc.isDead && npc.variant == 0 && npc.state != DUMP_SPOUTING) dump_split(npc); +} diff --git a/src/npc_dust.cpp b/src/npc_dust.cpp new file mode 100644 index 0000000..f962993 --- /dev/null +++ b/src/npc_dust.cpp @@ -0,0 +1,157 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_player.h" +#include "grid_entity.h" +#include "path_finder.h" +#include "room.h" +#include "room_grid.h" +#include + +// The Dust is unseen away from players: fully seen within 80 of the nearest, faded out by 200, and only touchable +// while seen at all. Friendly it always shows. +constexpr float DUST_SEEN_REACH = 80; +constexpr float DUST_FADE_SPAN = 120; +constexpr float DUST_TOUCH_ALPHA = 0.02f; + +// It drifts at its target at 0.35 to 1.35 (by how well it is seen), slower close to it (0.6 of that within 80). +// Every third of its health lost it vanishes in a puff and comes back where the players are farthest after 90 +// frames (at once when that is more than 200 off). +constexpr float DUST_SPLIT_FIRST = 0.66f; +constexpr float DUST_SPLIT_STEP = 0.33f; +constexpr float DUST_APPEAR_FRICTION = 0.6f; +constexpr float DUST_DRIFT_FRICTION = 0.8f; +constexpr float DUST_SPEED = 1.35f; +constexpr float DUST_SPEED_MIN = 0.35f; +constexpr float DUST_SLOW_REACH = 80; +constexpr float DUST_SLOW = 0.6f; +constexpr float DUST_SLOW_RANGE = 0.39999998f; +constexpr int DUST_PATH_MARKER = 0; +constexpr int DUST_GONE_FRAMES = 90; +constexpr int DUST_RETURN_TRIES = 4; +constexpr float DUST_RETURN_FAR_SQUARED = 40000; +constexpr float DUST_VANISH_VOLUME = 0.7f; +constexpr float DUST_POOF_PITCH = 1.5f; + +// It leaves pale splats every 6 frames, as faint as it is seen. +constexpr ColorMod DUST_SPLAT_COLOR = {{0, 0, 0, 0.3f}, {0, 0, 0, 0}, {0.82f, 0.82f, 0.8f}}; +constexpr float DUST_SPLAT_EVERY = 6; +constexpr float DUST_SPLAT_SIZE = 0.5f; +constexpr float DUST_SPLAT_ALPHA = 0.5f; + +// The Dust's states: appearing, drifting, and gone. +constexpr int DUST_APPEARING = NPC_STATE_APPEAR_CUSTOM; +constexpr int DUST_DRIFTING = NPC_STATE_IDLE; +constexpr int DUST_GONE = NPC_STATE_SPECIAL; + +// Sets every layer's alpha. +static void dust_alpha_set(Entity_NPC& npc, float alpha) +{ + for (LayerState& layer : npc.sprite.layerStates) layer.color._tint[3] = alpha; +} + +// Before its update: how well it is seen, shown on its layers, and whether it can be touched. +static void dust_visibility_update(Entity_NPC& npc) +{ + float seen = 1; + if (!npc.HasEntityFlags(FLAG_FRIENDLY) && npc.state != DUST_GONE) + { + Entity_Player* player = game_nearest_player(npc.pos); + seen = player ? std::clamp(1 - (vector_length(vector_sub(npc.pos, player->pos)) - DUST_SEEN_REACH) / + DUST_FADE_SPAN, + 0.0f, 1.0f) + : 0; + } + npc.v1.x = seen; + dust_alpha_set(npc, seen); + if (npc.state != DUST_GONE) npc.entityCollisionClass = seen > DUST_TOUCH_ALPHA ? ENTCOLL_ALL : ENTCOLL_NONE; +} + +// Drifting at its target, vanishing past each third of its health lost, and leaving its splats. +static void dust_drift_update(Entity_NPC& npc) +{ + npc.friction *= DUST_DRIFT_FRICTION; + float speed = std::max(npc.v1.x * DUST_SPEED, DUST_SPEED_MIN); + float near = std::clamp(vector_length(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)) / DUST_SLOW_REACH, 0.0f, 1.0f); + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), (near * DUST_SLOW_RANGE + DUST_SLOW) * speed, + DUST_PATH_MARKER, DIRECT_PATH_FAR); + if (npc.health >= npc.v1.y) + { + Vector velocity = npc.velocity; + bool isSideways = std::abs(velocity.y) < std::abs(velocity.x); + npc.sprite.Play(isSideways ? "WalkHori" : velocity.y < 0 ? "WalkUp" : "WalkDown"); + npc.sprite.isFlipX = isSideways && velocity.x < 0; + } + else + { + do npc.v1.y -= npc.maxHitPoints * DUST_SPLIT_STEP; + while (npc.health < npc.v1.y); + npc.state = DUST_GONE; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.sprite.Play("Poof"); + npc.sprite.isFlipX = false; + npc.velocity = {}; + npc.i1 = DUST_GONE_FRAMES; + } + + npc.forwardVector = vector_cardinal(npc.velocity); + if (!npc.GetIntervalTicks(DUST_SPLAT_EVERY, 0) || npc.v1.x <= 0) return; + ColorMod color = npc.splatColor; + color_multiply(color, {{1, 1, 1, npc.v1.x * DUST_SPLAT_ALPHA}, {0, 0, 0, 0}, {0, 0, 0}}); + npc.MakeSplat(DUST_SPLAT_SIZE)->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// Gone: its puff, then coming back where the players are farthest, once far enough or after its wait. +static void dust_gone_update(Entity_NPC& npc) +{ + npc.friction *= DUST_APPEAR_FRICTION; + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Poof")) + npc.PlaySound(SOUND_BLACK_POOF, DUST_VANISH_VOLUME, 2, false, DUST_POOF_PITCH); + if (npc.sprite.IsPlaying()) return; + if (npc.i1 > 0) npc.i1 -= npc_ticks_get(npc); + + Room& room = *g_game->room; + Vector best{}; + float bestDistance = 0; + for (int tries = 0; tries < DUST_RETURN_TRIES; tries++) + { + Vector spot = room_free_pickup_position_find({.position = room.GetRandomPosition(0)}); + Entity_Player* player = main_player_nearest(spot); + if (!player) continue; + float distance = vector_length_squared(vector_sub(spot, player->pos)); + if (distance <= bestDistance) continue; + best = spot; + bestDistance = distance; + } + if (bestDistance <= DUST_RETURN_FAR_SQUARED && npc.i1 > 0) return; + npc.pos = best; + npc.sprite.Play("Appear"); + npc.state = DUST_APPEARING; +} + +// 00503af0 The Dust's AI: a ghost of dust seen only near players, drifting at its target and vanishing to come back +// far off each third of its health. +void npc_dust_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return dust_visibility_update(npc); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + npc.state = DUST_APPEARING; + npc.v1 = vector_make(0, npc.maxHitPoints * DUST_SPLIT_FIRST); + npc.splatColor = DUST_SPLAT_COLOR; + dust_alpha_set(npc, 0); + npc.sprite.Play("Appear"); + npc.ClearEntityFlags(FLAG_APPEAR); + return; + case DUST_APPEARING: + npc.friction *= DUST_APPEAR_FRICTION; + if (!npc.sprite.IsPlaying()) npc.state = DUST_DRIFTING; + return; + case DUST_DRIFTING: + return dust_drift_update(npc); + case DUST_GONE: + return dust_gone_update(npc); + } +} diff --git a/src/npc_dusty_deaths_head.cpp b/src/npc_dusty_deaths_head.cpp new file mode 100644 index 0000000..f5ae476 --- /dev/null +++ b/src/npc_dusty_deaths_head.cpp @@ -0,0 +1,132 @@ +#include "npc_alt.h" +#include "entity_effect.h" +#include "room.h" +#include + +// A Dusty Death's Head drifts across the room from a room's width off one side (subtype 0 heads left, 1 right) at +// 1.6, bobbing on a wave of its own (3 to 8 high, a 60 frame period), fading in and out past the walls. 150 frames +// in it sends the next one from where it started, and it leaves 120 past the far wall. +constexpr float DUSTY_SPEED = 1.6f; +constexpr float DUSTY_FRICTION = 0.6f; +constexpr float DUSTY_WAVE_MIN = 5; +constexpr float DUSTY_WAVE_RANGE = 3; +constexpr float DUSTY_WAVE_FRAMES = 30; +constexpr float DUSTY_WAVE_LIFT = 9.549296f; +constexpr float DUSTY_OFFSCREEN = 120; +constexpr float DUSTY_FADE_SPAN = 100; +constexpr float DUSTY_NEXT_FRAMES = 150; +constexpr float DUSTY_CELL = 40; +constexpr ColorMod DUSTY_SPLAT_COLOR = {{1, 1, 1, 1}, {0.7f, 0.7f, 0.7f, 1}, {0, 0, 0}}; + +// Once the room is clear it crumbles, in a few puffs of dust if inside the room. +constexpr uint32_t DUSTY_PUFF_RANGE = 3; +constexpr uint32_t DUSTY_PUFFS = 2; +constexpr float DUSTY_PUFF_SPEED = 5; +constexpr float DUSTY_PUFF_SPREAD = 20; +constexpr float DUSTY_PUFF_LIFT = -20; +constexpr float DUSTY_PUFF_SPIN = 2; +constexpr float DUSTY_PUFF_SPIN_RANGE = 10; +constexpr uint32_t DUSTY_PUFF_TIME_RANGE = 15; +constexpr int DUSTY_PUFF_TIME = 15; +constexpr float DUSTY_PUFF_ALPHA = 0.2f; +constexpr float DUSTY_PUFF_ALPHA_RANGE = 0.5f; +constexpr int DUSTY_CRUMBLE_DELAY = 60; +constexpr int DUSTY_GRACE_FRAMES = 1; +constexpr int DUSTY_CLEAR_DELAY_HOLD = 8; + +// Its wave from its seed: the phase and the height. +struct DustyWave +{ + float phase = 0; + float height = 0; +}; + +// The wave its seed gives it, the same every frame. +static DustyWave dusty_wave_get(Entity_NPC& npc) +{ + RNG rng = {npc.initSeed, 5, 27, 25}; + float phase = rng.RandomFloat() * PI_F; + return {phase + phase, rng.RandomFloat() * DUSTY_WAVE_RANGE + DUSTY_WAVE_MIN}; +} + +// A puff of dust about it, turning the way it drifts off. +static void dusty_puff_spawn(Entity_NPC& npc) +{ + Vector velocity = vector_scale(random_direction(), random_unit() * DUSTY_PUFF_SPEED); + uint32_t seed = Random(); + Vector spot = vector_add(npc.pos, vector_scale(random_direction(), random_unit() * DUSTY_PUFF_SPREAD)); + auto* puff = static_cast(g_game->Spawn({.position = spot, .velocity = velocity, .spawner = &npc, + .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = seed})); + Vector out = vector_sub(puff->pos, npc.pos); + float turn = out.y * -velocity.x + out.x * velocity.y < 0 ? -1.0f : 1.0f; + puff->sprite.offset = vector_make(0, DUSTY_PUFF_LIFT); + puff->rotation = (random_unit() * DUSTY_PUFF_SPIN_RANGE + DUSTY_PUFF_SPIN) * turn; + puff->timeout = (int)(Random() % DUSTY_PUFF_TIME_RANGE) + DUSTY_PUFF_TIME; + puff->lifespan = puff->timeout; + ColorMod color = COLOR_DEFAULT; + color._tint[3] = random_unit() * DUSTY_PUFF_ALPHA_RANGE + DUSTY_PUFF_ALPHA; + puff->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + puff->Update(); +} + +// Setting out: a room's width off its side, harmless to touch but for its contact, invincible, on its wave. +static void dusty_init(Entity_NPC& npc, float side, const DustyWave& wave) +{ + npc.state = NPC_STATE_MOVE; + npc.sprite.Play("Idle"); + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.sprite.isFlipX = npc.subtype != 0; + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.targetPosition = npc.pos; + npc.AddEntityFlags(FLAG_HIDE_HP_BAR | FLAG_NO_STATUS_EFFECTS); + npc.isInvincible = true; + npc.pos.x -= side * (float)g_game->room->gridWidth * DUSTY_CELL; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.splatColor = DUSTY_SPLAT_COLOR; + npc.pos.y -= std::cos(wave.phase) * wave.height * DUSTY_WAVE_LIFT; +} + +// 00504a40 The Dusty Death's Head's AI: skulls drifting across the room in a wave, one after another, that crumble +// once the room is clear. +void npc_dusty_deaths_head_update(Entity_NPC& npc) +{ + float side = npc.subtype == 0 ? -1.0f : 1.0f; + DustyWave wave = dusty_wave_get(npc); + Room& room = *g_game->room; + float inside = std::min(room.bottomRightPos.x + DUSTY_OFFSCREEN - npc.pos.x, + npc.pos.x - room.topLeftPos.x + DUSTY_OFFSCREEN); + npc.sprite.color._tint[3] = std::clamp(inside / DUSTY_FADE_SPAN, 0.0f, 1.0f); + if (npc.state == NPC_STATE_INIT) return dusty_init(npc, side, wave); + + if (npc.state == NPC_STATE_MOVE) + { + npc.friction *= DUSTY_FRICTION; + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, + vector_make(side * DUSTY_SPEED * npc.speedMultiplier / npc.friction, 0)); + npc.velocity.y = std::sin(npc.updateTime * PI_F / DUSTY_WAVE_FRAMES + wave.phase) * wave.height; + if (npc.i1 == 0 && npc.updateTime >= DUSTY_NEXT_FRAMES) + { + npc.i1 = 1; + g_game->Spawn({.position = npc.targetPosition, .spawner = &npc, .subType = npc.subtype, .type = npc.type, + .variant = npc.variant, .seed = npc.dropRNG.Next()})->Update(); + } + } + + bool isGone = npc.subtype == 0 ? npc.pos.x < room.topLeftPos.x - DUSTY_OFFSCREEN + : npc.pos.x > room.bottomRightPos.x + DUSTY_OFFSCREEN; + if (isGone) return npc.Remove(); + + bool isHeldOpen = room.isTriggerPressurePlates && room.roomClearDelay > DUSTY_CLEAR_DELAY_HOLD; + if (g_game->frameCount - npc.spawnFrame <= DUSTY_GRACE_FRAMES || npc.GetAliveEnemyCount() > 0 || isHeldOpen || + npc.isDead) + return; + + npc.state = NPC_STATE_DEATH; + npc.stateFrame = 0; + npc.PlaySound(SOUND_DEVILROOM_DEAL, 1, DUSTY_CRUMBLE_DELAY, false, 1); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.shadowSize = 0; + if (!room.IsPositionInRoom(npc.pos, 0)) return; + for (uint32_t puffs = Random() % DUSTY_PUFF_RANGE + DUSTY_PUFFS; puffs > 0; puffs--) dusty_puff_spawn(npc); +} diff --git a/src/npc_fartigan.cpp b/src/npc_fartigan.cpp new file mode 100644 index 0000000..0a3c4b5 --- /dev/null +++ b/src/npc_fartigan.cpp @@ -0,0 +1,131 @@ +#include "npc_alt.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_projectile.h" +#include "grid_entity.h" +#include "path_finder.h" + +// The Fartigan walks at 1.2 (1 while farting) and blows itself up within 40 of its target, checked every 5 frames. +constexpr float FARTIGAN_SPEED = 1.2f; +constexpr float FARTIGAN_FART_SPEED = 1; +constexpr int FARTIGAN_PATH_MARKER = 0; +constexpr int FARTIGAN_REACH_EVERY = 5; +constexpr float FARTIGAN_REACH_SQUARED = 1600; +constexpr float FARTIGAN_FRICTION = 0.9f; +constexpr float FARTIGAN_SUICIDE_FRICTION = 0.8f; +constexpr float FARTIGAN_WALK_THRESHOLD = 0.1f; +constexpr float FARTIGAN_CONTROLLED_REACH = 1000; + +// Seeing its target, one time in 16 a frame it farts a gas cloud ahead (within 30 degrees, at 10 to 20) that lasts +// 180 frames, with a green puff of gas 25 up. +constexpr uint32_t FARTIGAN_FART_MASK = 0xf; +constexpr float FARTIGAN_FART_SPREAD = 60; +constexpr float FARTIGAN_FART_TURN = -30; +constexpr float FARTIGAN_CLOUD_SPEED = 10; +constexpr float FARTIGAN_CLOUD_SPEED_RANGE = 10; +constexpr int FARTIGAN_CLOUD_SUBTYPE = 1; +constexpr int FARTIGAN_CLOUD_FRAMES = 180; +constexpr int FARTIGAN_PUFF_SIZE = 1; +constexpr float FARTIGAN_PUFF_LIFT = -25; +constexpr int FARTIGAN_PUFF_Z = 500; +constexpr ColorMod FARTIGAN_PUFF_COLOR = {{1, 1, 1, 1}, {1.2f, 1.4f, 0.6f, 1}, {0, 0, 0}}; + +// Dying, it bursts into a 40 damage green explosion if it blew itself up, else it leaves an exploding gas shot at +// 0.3 of its speed (no faster than 4). +constexpr float FARTIGAN_BLAST_DAMAGE = 40; +constexpr ColorMod FARTIGAN_BLAST_COLOR = {{0.9f, 1, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float FARTIGAN_SHOT_SLOWDOWN = 0.3f; +constexpr float FARTIGAN_SHOT_SPEED_LIMIT = 4; +constexpr ColorMod FARTIGAN_SHOT_COLOR = {{1, 1, 1, 1}, {1.5f, 2, 0.5f, 1}, {0, 0, 0}}; +constexpr float FARTIGAN_SHOT_FALLING_ACCEL = 0.3f; +constexpr float FARTIGAN_SHOT_FALLING_SPEED = -5; + +// The fart: the gas cloud ahead of it and the puff about it. +static void fartigan_fart(Entity_NPC& npc) +{ + npc.state = NPC_STATE_ATTACK; + npc.PlaySound(SOUND_WHEEZY_COUGH, 1, 2, false, 1); + Vector ahead = vector_make(npc.sprite.isFlipX ? -1.0f : 1.0f, 0); + Vector direction = vector_rotated(ahead, random_unit() * FARTIGAN_FART_SPREAD + FARTIGAN_FART_TURN); + Vector velocity = vector_scale(direction, random_unit() * FARTIGAN_CLOUD_SPEED_RANGE + FARTIGAN_CLOUD_SPEED); + auto* cloud = static_cast(g_game->Spawn({.position = npc.pos, .velocity = velocity, + .spawner = &npc, .subType = FARTIGAN_CLOUD_SUBTYPE, .type = ENTITY_EFFECT, .variant = EFFECT_SMOKE_CLOUD, + .seed = Random()})); + cloud->timeout = FARTIGAN_CLOUD_FRAMES; + cloud->lifespan = FARTIGAN_CLOUD_FRAMES; + cloud->Update(); + + Entity* puff = g_game->Spawn({.position = npc.pos, .velocity = npc.velocity, .subType = FARTIGAN_PUFF_SIZE, + .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + puff->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + puff->sprite.Play("Poof"); + puff->posOffset = vector_make(0, FARTIGAN_PUFF_LIFT); + puff->renderZOffset = FARTIGAN_PUFF_Z; + puff->sprite.color = FARTIGAN_PUFF_COLOR; +} + +// Walking at its target with its head bobbing, blowing up when close and farting when it sees its target. Whether +// it blew itself up. +static bool fartigan_walk_update(Entity_NPC& npc, Vector target) +{ + npc.pathfinder.FindGridPath(target, FARTIGAN_SPEED, FARTIGAN_PATH_MARKER, DIRECT_PATH_FAR); + bool isDetonated = false; + if (npc.IsFrame(FARTIGAN_REACH_EVERY, 0) && + vector_length_squared(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)) < FARTIGAN_REACH_SQUARED) + { + npc.Kill(EntityRef()); + isDetonated = true; + } + npc.friction *= FARTIGAN_FRICTION; + npc.AnimWalkFrame("WalkHori", "WalkVert", FARTIGAN_WALK_THRESHOLD); + if (npc.sprite.IsPlaying()) npc.sprite.PlayOverlay("HeadWalk"); + else if (npc.sprite.SetOverlayAnimation("HeadWalk", SWITCH_KEEP_FRAME) && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); + if (npc.i1 > 0) return isDetonated; + + bool isFarting = npc.controllerID != -1 ? npc.IsTargetInAttackRange(FARTIGAN_CONTROLLED_REACH, 0, true) + : npc.pathfinder.hasDirectPath && (Random() & FARTIGAN_FART_MASK) == 0; + if (isFarting) fartigan_fart(npc); + return isDetonated; +} + +// Its death: the green explosion when it blew itself up, else its gas shot. +static void fartigan_death_spawn(Entity_NPC& npc, bool isDetonated) +{ + if (isDetonated) + return explosion_effects({.color = FARTIGAN_BLAST_COLOR, .position = npc.pos, .source = &npc, + .damage = FARTIGAN_BLAST_DAMAGE}); + + ProjectileParams params; + params.bulletFlags |= PROJECTILE_EXPLODE; + params.color = FARTIGAN_SHOT_COLOR; + params.fallingAccelModifier = FARTIGAN_SHOT_FALLING_ACCEL; + params.fallingSpeedModifier = FARTIGAN_SHOT_FALLING_SPEED; + Vector velocity = vector_scale(npc.velocity, FARTIGAN_SHOT_SLOWDOWN); + if (vector_length(velocity) > FARTIGAN_SHOT_SPEED_LIMIT) velocity = vector_resized(velocity, FARTIGAN_SHOT_SPEED_LIMIT); + npc.FireProjectiles(npc.pos, velocity, PROJECTILES_SINGLE, params); +} + +// 00561a20 The Fartigan's AI: it walks at its target farting gas clouds and blows itself up next to it. +void npc_fartigan_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) npc.state = NPC_STATE_MOVE; + Vector target = npc.CalcTargetPosition(0); + bool isDetonated = false; + if (npc.state == NPC_STATE_MOVE) isDetonated = fartigan_walk_update(npc, target); + else if (npc.state == NPC_STATE_ATTACK) + { + npc.pathfinder.FindGridPath(target, FARTIGAN_FART_SPEED, FARTIGAN_PATH_MARKER, DIRECT_PATH_FAR); + npc.friction *= FARTIGAN_FRICTION; + npc.AnimWalkFrame("WalkHori", "WalkVert", FARTIGAN_WALK_THRESHOLD); + npc.sprite.PlayOverlay("HeadAttack"); + AnimationState& head = npc.sprite.overlayAnimState; + if (!head.animData || !head.isPlaying) npc.state = NPC_STATE_MOVE; + } + else if (npc.state == NPC_STATE_SUICIDE) + { + npc.friction *= FARTIGAN_SUICIDE_FRICTION; + if (!npc.sprite.IsPlaying()) npc.Kill(EntityRef()); + } + if (npc.isDead && !npc.HasEntityFlags(FLAG_SHRINK)) fartigan_death_spawn(npc, isDetonated); +} diff --git a/src/npc_flesh_maiden.cpp b/src/npc_flesh_maiden.cpp new file mode 100644 index 0000000..1de8e49 --- /dev/null +++ b/src/npc_flesh_maiden.cpp @@ -0,0 +1,144 @@ +#include "npc_alt.h" +#include "entity_laser.h" +#include + +// The Flesh Maiden swings along arcs at its target (where it is heading, or anywhere while confused): 110 to 130 +// ahead and 110 to 130 to one side (the sides take turns), straight out when the target is near, over 29 frames, +// lifted 9 at the arc's middle. It hurts only by contact, but charmed or friendly. +constexpr float MAIDEN_FRICTION = 0.7f; +constexpr float MAIDEN_REACH = 110; +constexpr float MAIDEN_REACH_RANGE = 20; +constexpr float MAIDEN_NEAR_SCALE = 1.33f; +constexpr float MAIDEN_LEAD = 0.1f; +constexpr float MAIDEN_ARC_SHARE = 0.75f; +constexpr float MAIDEN_SWING_STEP = 0.035f; +constexpr float HALF_SWING = 0.5f; +constexpr float MAIDEN_LIFT = 9; +constexpr float MAIDEN_LIFT_CURVE = 4; +constexpr float MAIDEN_LANDING = 0.8f; +constexpr int MAIDEN_LANDING_FRAMES = 10; +constexpr int MAIDEN_SWING_REPEAT_FRAME = 8; +constexpr ColorMod MAIDEN_SPLAT_COLOR = {{0.9f, 0.9f, 0.9f, 1}, {0.9f, 0.9f, 1, 0.3f}, {0, 0, 0}}; + +// Its head looks at its target: down within about 22 degrees of straight down, else to the side, or up. +constexpr float MAIDEN_LOOK_DOWN = 0.924f; +constexpr int MAIDEN_HEAD_LAYER = 1; +constexpr float MAIDEN_LOOK_LEFT_FRAME = 0; +constexpr float MAIDEN_LOOK_DOWN_FRAME = 1; +constexpr float MAIDEN_LOOK_RIGHT_FRAME = 2; +constexpr float MAIDEN_LOOK_UP_FRAME = 3; + +// The Flesh Maiden's states: picking its next swing, and swinging. +constexpr int MAIDEN_PICKING = NPC_STATE_IDLE; +constexpr int MAIDEN_SWINGING = NPC_STATE_MOVE; + +// Picking the next swing: its end, its arc's middle (v1) and start (v2), its animation, and the side after it. +static void maiden_swing_pick(Entity_NPC& npc) +{ + float reach = random_unit() * MAIDEN_REACH_RANGE + MAIDEN_REACH; + float side = random_unit() * MAIDEN_REACH_RANGE + MAIDEN_REACH; + Vector aim; + if (npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) aim = npc.CalcTargetPosition(0); + else + { + Entity* target = npc.GetPlayerTarget(); + float distance = vector_length(vector_sub(npc.pos, target->pos)); + aim = vector_add(target->pos, vector_scale(target->velocity, MAIDEN_LEAD * distance)); + } + Vector toAim = vector_sub(aim, npc.pos); + float distance = vector_length(toAim); + Vector direction = vector_scale(toAim, 1 / distance); + if (distance >= reach * MAIDEN_NEAR_SCALE) + npc.targetPosition = vector_add(npc.pos, vector_add(vector_scale(direction, reach), + vector_scale(vector_rotated(direction, (float)npc.i1 * RIGHT_ANGLE_DEGREES), side))); + else npc.targetPosition = vector_add(npc.pos, vector_scale(direction, std::sqrt(side * side + reach * reach))); + + npc.v2 = npc.pos; + Vector swing = vector_sub(npc.targetPosition, npc.pos); + Vector across = vector_rotated(swing, RIGHT_ANGLE_DEGREES); + Vector middle = vector_add(npc.pos, vector_scale(swing, MAIDEN_ARC_SHARE)); + npc.v1 = vector_dot(vector_sub(aim, npc.pos), across) <= 0 ? vector_add(middle, across) : vector_sub(middle, across); + + const AnimationData* shown = npc.sprite.animState.animData; + bool isSwinging = shown && shown->name.starts_with("Swing"); + npc.sprite.Play(npc.pos.x <= npc.targetPosition.x ? "SwingRight" : "SwingLeft", PLAY_FORCED); + if (npc.sprite.SetOverlayAnimation("HeadLook", SWITCH_KEEP_FRAME) && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); + if (isSwinging && npc.sprite.animState.animData) npc.sprite.animState.SetFrameFloat(MAIDEN_SWING_REPEAT_FRAME); + npc.state = MAIDEN_SWINGING; + npc.i1 = -npc.i1; + npc.aiFloat = 0; +} + +// Swinging round its arc, easing in and out, lifted at the middle. A wall cuts the swing short. Whether it landed. +static bool maiden_swing_update(Entity_NPC& npc) +{ + npc.aiFloat += npc.speedMultiplier * MAIDEN_SWING_STEP; + float half = npc.aiFloat - HALF_SWING; + npc.posOffset.y = MAIDEN_LIFT - half * MAIDEN_LIFT * half * MAIDEN_LIFT_CURVE; + if (!vector_is_zero(npc.targetPosition)) + { + float ease = (1 - std::cos(npc.aiFloat * PI_F)) * HALF_SWING; + float startAngle = vector_angle(vector_sub(npc.v2, npc.v1)); + float startRadius = vector_length(vector_sub(npc.v1, npc.v2)); + float endRadius = vector_length(vector_sub(npc.v1, npc.targetPosition)); + float turn = angle_difference(startAngle, vector_angle(vector_sub(npc.targetPosition, npc.v1))); + float radius = (endRadius - startRadius) * ease + startRadius; + Vector spot = vector_add(npc.v1, vector_scale(vector_from_angle(turn * ease + startAngle), radius)); + npc.velocity = vector_sub(spot, npc.pos); + if (npc.isCollidesWithGrid) + { + npc.targetPosition = {}; + npc.aiFloat = std::max(npc.aiFloat, MAIDEN_LANDING); + } + } + + if (npc.aiFloat > MAIDEN_LANDING) + { + const AnimationData* shown = npc.sprite.animState.animData; + int landing = (shown ? shown->length : 0) - MAIDEN_LANDING_FRAMES; + if (npc.sprite.GetFrame() < landing && shown) npc.sprite.animState.SetFrameFloat((float)landing); + } + if (npc.aiFloat <= 1) return false; + npc.posOffset.y = 0; + return true; +} + +// Its head placed by the body's HeadPos null, looking at its target. +static void maiden_head_update(Entity_NPC& npc) +{ + if (!npc.sprite.animState.animData) return; + const NullFrame* guide = npc.sprite.animState.GetNullFrame("HeadPos"); + if (!guide) return; + LayerState& head = *npc.sprite.GetLayer(MAIDEN_HEAD_LAYER); + head.pos = guide->pos; + head.size = guide->scale; + head.rotation = guide->rotation; + + Vector look = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (vector_length(look) > 0) look = vector_normalized(look); + if (!npc.sprite.overlayAnimState.animData) return; + float frame = look.y >= MAIDEN_LOOK_DOWN ? MAIDEN_LOOK_DOWN_FRAME + : look.y < 0 ? MAIDEN_LOOK_UP_FRAME + : look.x < 0 ? MAIDEN_LOOK_LEFT_FRAME + : MAIDEN_LOOK_RIGHT_FRAME; + npc.sprite.overlayAnimState.SetFrameFloat(frame); +} + +// 00502980 The Flesh Maiden's AI: it swings along arcs at its target, alternating sides, its head watching. +void npc_flesh_maiden_update(Entity_NPC& npc) +{ + npc.friction *= MAIDEN_FRICTION; + npc.entityCollisionClass = npc.HasEntityFlags(FLAG_CHARM | FLAG_FRIENDLY) ? ENTCOLL_ALL : ENTCOLL_PLAYEROBJECTS; + if (npc.state == NPC_STATE_INIT) + { + npc.splatColor = MAIDEN_SPLAT_COLOR; + npc.i1 = (int)(npc.initSeed & 1) * 2 - 1; + npc.state = MAIDEN_PICKING; + } + else if (npc.state == MAIDEN_PICKING) maiden_swing_pick(npc); + else if (npc.state == MAIDEN_SWINGING && maiden_swing_update(npc)) npc.state = MAIDEN_PICKING; + + if (npc.i2 > 0) npc.i2--; + maiden_head_update(npc); +} diff --git a/src/npc_fly.cpp b/src/npc_fly.cpp index e556cd5..c8aeb3a 100644 --- a/src/npc_fly.cpp +++ b/src/npc_fly.cpp @@ -4,15 +4,15 @@ #include "entity_config.h" #include "entity_player.h" #include "game.h" +#include "manager.h" #include "grid_entity.h" +#include "npc_alt.h" #include "room.h" #include "score_sheet.h" #include // The fly kin this AI runs: the fly, Pooter, attack fly, the Sucker's family, Moter, the level 2 fly, the full fly and // the fly bomb. -constexpr int ENTITY_FLY_L2 = 214; -constexpr int ENTITY_FULL_FLY = 249; constexpr int SPAWNER_UNBOUNDED = 67; // The Sucker's variants: the Sucker, Spit, Soul Sucker, Ink, Mama Fly, the Bulbs and the Bloodfly. @@ -44,6 +44,13 @@ constexpr float SPIT_SHOT_RISE_SCALE = 0.7f; constexpr float SPIT_SHOT_RISE = 13; constexpr int SPIT_SHOT_COLOR_PRIORITY = 255; constexpr ColorMod SPIT_SHOT_COLOR = {{1, 1, 1, 1}, {0.4f, 2, 0.5f, 1}, {0, 0, 0}}; +static const Vector SOUL_SWIRL_OFFSET = vector_make(0, -15); +constexpr ColorMod SOUL_TRACER_COLOR = {{0.6f, 0.05f, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float SOUL_TRACER_SCALE = 4; +constexpr int SOUL_TRACER_TIME = 24; +constexpr ColorMod INK_SHOT_COLOR = {{1, 1, 1, 1}, {0.5f, 0.5f, 0.5f, 1}, {0, 0, 0}}; +constexpr float INK_CREEP_SCALE = 4; +constexpr int INK_CREEP_TIME = 450; constexpr float MOTER_SPLIT_SPEED = 10; constexpr float MOTER_OVERKILL = -20; @@ -166,7 +173,29 @@ static void fly_init(Entity_NPC& npc) npc.i1 = 0; } -// A dying Sucker bursts by its variant: a plus of shots, the Spit's arcing puddle shot, or the Bloodfly's ring. +// 0060b9d0 (NpcHelper::spawn_tracer_effect198) A warning line along a direction from a spot, as the following tracers +// show: only in an online session and outside the 1x1 and narrow rooms. +static Entity_Effect* tracer_spawn(const Vector& position, const Vector& direction) +{ + int shape = g_game->room->GetRoomShape(); + if (!g_manager->netplayManager.is_online() || !g_game->room->descriptor || !g_game->room->descriptor->data || + shape == ROOMSHAPE_1x1 || shape == ROOMSHAPE_IH || shape == ROOMSHAPE_IV) + return nullptr; + + auto* tracer = static_cast(g_game->Spawn( + {.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_GENERIC_TRACER, .seed = Random()})); + if (!tracer) return nullptr; + tracer->sprite.color = SOUL_TRACER_COLOR; + tracer->sprite.scale = vector_make(SOUL_TRACER_SCALE, SOUL_TRACER_SCALE); + tracer->targetPosition = direction; + tracer->timeout = SOUL_TRACER_TIME; + tracer->lifespan = SOUL_TRACER_TIME; + tracer->Update(); + return tracer; +} + +// A dying Sucker bursts by its variant: a plus of shots, the Spit's arcing puddle shot, the Soul Sucker's brimstone +// swirl (with warning lines online), the Ink's cross of inky shots over a pool of black creep, or the Bloodfly's ring. static void sucker_death(Entity_NPC& npc) { if (npc.HasEntityFlags(FLAG_SHRINK)) return; @@ -192,9 +221,32 @@ static void sucker_death(Entity_NPC& npc) break; } case SUCKER_SOUL: - reconstruction_missing("npc_fly_update 00506bd0: a Soul Sucker's death (spawn_tracer_effect198)"); + { + Entity* swirl = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_ENEMY_BRIMSTONE_SWIRL, + .seed = Random()}); + swirl->posOffset = SOUL_SWIRL_OFFSET; + swirl->Update(); + for (int direction : {DIRECTION_RIGHT, DIRECTION_DOWN, DIRECTION_LEFT, DIRECTION_UP}) + tracer_spawn(npc.pos, vector_from_direction(direction)); + break; + } case SUCKER_INK: - reconstruction_missing("npc_fly_update 00506bd0: an Ink's death splash"); + { + ProjectileParams params; + params.color = INK_SHOT_COLOR; + float speed = game_is_hard_mode() ? SUCKER_HARD_SHOT_SPEED : SUCKER_SHOT_SPEED; + npc.FireProjectiles(npc.pos, vector_make(speed, 0), PROJECTILES_CROSS, params); + auto* creep = static_cast(g_game->Spawn( + {.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_BLACK, .seed = Random()})); + creep->sprite.scale = vector_make(INK_CREEP_SCALE, INK_CREEP_SCALE); + creep->timeout = INK_CREEP_TIME; + creep->lifespan = INK_CREEP_TIME; + creep->Update(); + break; + } case SUCKER_BLOODFLY: { ProjectileParams params; @@ -591,7 +643,7 @@ void npc_fly_update(Entity_NPC& npc) bool isIsaacsFly = npc.spawnerType == ENTITY_ISAAC_BOSS && npc.subtype != 0; if (isIsaacsFly) npc_isaac_fly_update(npc); - else if (npc.spawnerType == ENTITY_ORBIT_SPAWNER) return NpcAI::ENTITY_FLY_orbit_parent(&npc); + else if (npc.spawnerType == ENTITY_FLY_TRAP) return fly_trap_fly_update(npc); else { if (npc.type == ENTITY_FLY_BOMB && fly_bomb_update(npc)) return; diff --git a/src/npc_fly_trap.cpp b/src/npc_fly_trap.cpp new file mode 100644 index 0000000..8090cee --- /dev/null +++ b/src/npc_fly_trap.cpp @@ -0,0 +1,229 @@ +#include "npc_alt.h" +#include "active_items.h" +#include "boss_ai.h" +#include "deathmatch_manager.h" +#include "entity_effect.h" +#include "menu_manager.h" +#include "npc_basement.h" +#include "path_finder.h" +#include + +// The Fly Trap walks at 0.25 with three attack flies about it, 20 out and 120 degrees apart. +constexpr int FLY_TRAP_START_FLIES = 3; +constexpr float FLY_TRAP_FLY_SPACING = 120; +constexpr float FLY_TRAP_FLY_REACH = 20; +constexpr float FLY_TRAP_SPEED = 0.25f; +constexpr int FLY_TRAP_PATH_MARKER = 0; + +// With three flies or more it farts them away one time in 40 a frame. With fewer than three it spits one one time +// in 20, with fewer than six one time in 80. After a fart it waits 80 frames. +constexpr size_t FLY_TRAP_FART_FLIES = 3; +constexpr uint32_t FLY_TRAP_FART_ODDS = 40; +constexpr size_t FLY_TRAP_FEW_FLIES = 3; +constexpr uint32_t FLY_TRAP_FEW_ODDS = 20; +constexpr size_t FLY_TRAP_MOST_FLIES = 6; +constexpr uint32_t FLY_TRAP_SPIT_ODDS = 80; +constexpr float FLY_TRAP_CONTROLLED_REACH = 1000; +constexpr int FLY_TRAP_FART_WAIT = 80; + +// A spat fly leaves 2 out at 10, with a cough (higher for the champion that spawns more, lower for the one with +// fewer) and a dust cloud. The fart pushes its flies away at 10 and reaches 120. +constexpr float FLY_TRAP_SPIT_OUT = 2; +constexpr float FLY_TRAP_SPIT_SPEED = 10; +constexpr int CHAMPION_FLY_TRAP_HIGH = 18; +constexpr int CHAMPION_FLY_TRAP_LOW = 19; +constexpr float FLY_TRAP_HIGH_PITCH = 1.5f; +constexpr float FLY_TRAP_LOW_PITCH = 0.5f; +constexpr float FLY_TRAP_DUST_SPREAD = 2; +constexpr float FLY_TRAP_DUST_SPREAD_RANGE = 10; +constexpr uint32_t FLY_TRAP_DUST_TIME_RANGE = 15; +constexpr int FLY_TRAP_DUST_TIME = 15; +constexpr float FLY_TRAP_DUST_ALPHA = 0.2f; +constexpr float FLY_TRAP_DUST_ALPHA_RANGE = 0.5f; +constexpr float FLY_TRAP_PUSH = 10; +constexpr float FLY_TRAP_FART_RADIUS = 120; +constexpr float FLY_TRAP_FART_FRICTION = 0.8f; + +// The Fly Trap's states: walking, spitting a fly and farting its flies away. +constexpr int FLY_TRAP_WALK = NPC_STATE_MOVE; +constexpr int FLY_TRAP_SPIT = NPC_STATE_ATTACK; +constexpr int FLY_TRAP_FART = NPC_STATE_ATTACK2; + +// An attack fly of the Fly Trap's at a position and speed. The seed is drawn before the place. +static Entity* fly_trap_fly_spawn(Entity_NPC& npc, uint32_t seed, Vector position, Vector velocity) +{ + Entity* fly = g_game->Spawn({.position = position, .velocity = velocity, .spawner = &npc, + .type = ENTITY_ATTACKFLY, .seed = seed}); + fly->parent = &npc; + return fly; +} + +// Spitting a fly on Shoot, with its cough and dust, and walking again once done. +static void fly_trap_spit_update(Entity_NPC& npc) +{ + npc.sprite.Play("Attack01"); + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), FLY_TRAP_SPEED, FLY_TRAP_PATH_MARKER, DIRECT_PATH_FAR); + if (!npc.sprite.animState.animData) + { + npc.state = FLY_TRAP_WALK; + return; + } + if (npc.sprite.animState.IsEventTriggered("Shoot")) + { + Vector direction = random_direction(); + Entity* fly = fly_trap_fly_spawn(npc, Random(), vector_add(npc.pos, vector_scale(direction, FLY_TRAP_SPIT_OUT)), + vector_scale(direction, FLY_TRAP_SPIT_SPEED)); + fly->ClearEntityFlags(FLAG_APPEAR); + float pitch = npc.championColorIdx == CHAMPION_FLY_TRAP_HIGH ? FLY_TRAP_HIGH_PITCH + : npc.championColorIdx == CHAMPION_FLY_TRAP_LOW ? FLY_TRAP_LOW_PITCH + : 1; + npc_sound_play(SOUND_WHEEZY_COUGH, 1, 2, pitch); + + auto* dust = static_cast(spawn_at(ENTITY_EFFECT, EFFECT_DUST_CLOUD, 0, npc.pos, nullptr)); + dust->rotation = random_unit() * FLY_TRAP_DUST_SPREAD_RANGE + FLY_TRAP_DUST_SPREAD; + dust->timeout = (int)(Random() % FLY_TRAP_DUST_TIME_RANGE) + FLY_TRAP_DUST_TIME; + dust->lifespan = dust->timeout; + ColorMod color = COLOR_DEFAULT; + color._tint[3] = random_unit() * FLY_TRAP_DUST_ALPHA_RANGE + FLY_TRAP_DUST_ALPHA; + dust->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + dust->Update(); + } + if (!npc.sprite.IsPlaying()) npc.state = FLY_TRAP_WALK; +} + +// Farting its flies away on Shoot, then walking again once done. +static void fly_trap_fart_update(Entity_NPC& npc, const std::vector& flies) +{ + npc.sprite.Play("Attack02"); + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Shoot")) + { + npc.i1 = FLY_TRAP_FART_WAIT; + for (Entity* fly : flies) + { + if (fly->parent.get() != &npc) continue; + Vector away = vector_sub(fly->pos, npc.pos); + if (vector_length(away) > 0) away = vector_normalized(away); + if (fly->friction != 0) + fly->velocity = vector_add(fly->velocity, + vector_scale(away, FLY_TRAP_PUSH * fly->speedMultiplier / fly->friction)); + } + game_butter_bean_fart({.position = npc.pos, .source = &npc, .radius = FLY_TRAP_FART_RADIUS}); + } + if (!npc.sprite.IsPlaying()) npc.state = FLY_TRAP_WALK; + npc.friction *= FLY_TRAP_FART_FRICTION; +} + +// Walking at its target, and after the wait choosing to fart or spit by how many flies it has. +static void fly_trap_walk_update(Entity_NPC& npc, size_t flyCount) +{ + npc.sprite.Play("Walk"); + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), FLY_TRAP_SPEED, FLY_TRAP_PATH_MARKER, DIRECT_PATH_FAR); + if (npc.i1 > 0) return; + + bool isControlled = npc.controllerID != -1; + bool isFarting = isControlled ? input_is_action_pressed(ACTION_BOMB, npc.controllerID, &npc) + : flyCount >= FLY_TRAP_FART_FLIES && Random() % FLY_TRAP_FART_ODDS == 0; + if (isFarting) + { + npc.state = FLY_TRAP_FART; + return; + } + + bool isSpitting = false; + if (isControlled) + isSpitting = npc.IsTargetInAttackRange(FLY_TRAP_CONTROLLED_REACH, 0, true) && flyCount < FLY_TRAP_MOST_FLIES; + else + isSpitting = (flyCount < FLY_TRAP_FEW_FLIES && Random() % FLY_TRAP_FEW_ODDS == 0) || + (flyCount < FLY_TRAP_MOST_FLIES && Random() % FLY_TRAP_SPIT_ODDS == 0); + if (isSpitting) npc.state = FLY_TRAP_SPIT; +} + +// 00560ca0 The Fly Trap's AI: it walks with a ring of attack flies, spits out more and farts them at its target. +void npc_fly_trap_update(Entity_NPC& npc) +{ + std::vector flies = npc_query_spawner_type(npc.type, 0, SPAWNER_QUERY_ENEMIES); + size_t flyCount = std::count_if(flies.begin(), flies.end(), [&npc](Entity* fly) { return fly->parent.get() == &npc; }); + + switch (npc.state) + { + case NPC_STATE_INIT: + { + float start = random_unit() * FULL_TURN_DEGREES; + for (int fly = 0; fly < FLY_TRAP_START_FLIES; fly++) + { + Vector direction = vector_from_angle((float)fly * FLY_TRAP_FLY_SPACING + start); + fly_trap_fly_spawn(npc, Random(), vector_add(npc.pos, vector_scale(direction, FLY_TRAP_FLY_REACH)), {}); + } + npc.state = FLY_TRAP_WALK; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + break; + } + case FLY_TRAP_WALK: + fly_trap_walk_update(npc, flyCount); + break; + case FLY_TRAP_SPIT: + fly_trap_spit_update(npc); + break; + case FLY_TRAP_FART: + fly_trap_fart_update(npc, flies); + break; + } + if (npc.i1 > 0) npc.i1 -= npc_ticks_get(npc); +} + +// A Fly Trap's fly circles 40 out (600 while it farts), at most 6 a frame (slower and slower out of the fart), and +// keeps off its fellow flies. +constexpr float TRAP_FLY_ORBIT = 40; +constexpr float TRAP_FLY_FARTED_ORBIT = 600; +constexpr float TRAP_FLY_SPEED = 6; +constexpr float TRAP_FLY_FARTED_SPEED = 10; +constexpr float TRAP_FLY_FARTED_SLOWDOWN = 30; +constexpr float TRAP_FLY_LEAD = 45; +constexpr float TRAP_FLY_EASE = 0.39999998f; +constexpr float TRAP_FLY_SPACING = 0.1f; +constexpr int TRAP_FLY_KEEPER_FIRST = 10; +constexpr int TRAP_FLY_KEEPER_LAST = 999; + +// 00561580 A fly kept by a Fly Trap (or a versus player): it circles its keeper ahead of the way round, blown far out +// by its fart, and keeps off its fellows. Without a keeper it is a plain fly again. +void fly_trap_fly_update(Entity_NPC& npc) +{ + Entity* keeper = npc.parent.get(); + bool isVersusKeeper = keeper && g_game->deathmatchManager.is_active() && keeper->type == ENTITY_PLAYER; + bool isNpcKeeper = keeper && keeper->type >= TRAP_FLY_KEEPER_FIRST && keeper->type <= TRAP_FLY_KEEPER_LAST; + if (!isVersusKeeper && !isNpcKeeper) + { + npc.spawnerType = 0; + return; + } + + // A versus player keeper has no fart, so its flies keep the plain circle. + auto* trap = dynamic_cast(keeper); + int farted = trap ? trap->i1 : 0; + float orbit = farted > FLY_TRAP_FART_WAIT / 2 ? TRAP_FLY_FARTED_ORBIT : TRAP_FLY_ORBIT; + float speed = farted > 0 ? std::abs((float)(farted - FLY_TRAP_FART_WAIT / 2)) * TRAP_FLY_FARTED_SPEED / + TRAP_FLY_FARTED_SLOWDOWN + : TRAP_FLY_SPEED; + Vector away = vector_sub(npc.pos, keeper->pos); + if (vector_length(away) > 0) away = vector_normalized(away); + Vector ahead = vector_rotated(away, TRAP_FLY_LEAD); + npc.targetPosition = vector_add(keeper->pos, vector_length(ahead) > 0 ? vector_resized(ahead, orbit) : ahead); + Vector step = vector_sub(npc.targetPosition, npc.pos); + if (vector_length(step) > speed) step = vector_resized(step, speed); + float multiplier = npc.speedMultiplier; + float keep = multiplier == 1 ? TRAP_FLY_EASE + : TRAP_FLY_EASE / ((multiplier + TRAP_FLY_EASE) - multiplier * TRAP_FLY_EASE); + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.velocity = vector_add(npc.velocity, vector_scale(vector_sub(step, npc.velocity), 1 - keep)); + + for (Entity* fellow : npc_query_spawner_type(keeper->type, 0, SPAWNER_QUERY_ENEMIES)) + { + if (fellow == &npc || fellow->parent.get() != keeper) continue; + Vector toFellow = vector_sub(fellow->pos, npc.pos); + float distance = vector_length(toFellow); + float push = 1 / (distance * TRAP_FLY_SPACING + 1); + if (distance > 0) toFellow = vector_normalized(toFellow); + if (npc.friction != 0) + npc.velocity = vector_sub(npc.velocity, vector_scale(toFellow, push * npc.speedMultiplier / npc.friction)); + } +} diff --git a/src/npc_gehenna.h b/src/npc_gehenna.h new file mode 100644 index 0000000..7e8f03f --- /dev/null +++ b/src/npc_gehenna.h @@ -0,0 +1,47 @@ +#pragma once + +#include "npc_caves.h" +#include "entity_player.h" +#include "game.h" +#include "room.h" +#include "room_grid.h" + +// The axis direction a vector leans along most: left, up, right or down (vertical on a tie). +inline int axis_direction_get(Vector v) +{ + if (std::abs(v.x) <= std::abs(v.y)) return v.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP; + return v.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; +} + +// Whether the room's pressure plates were all pressed, which ends the Mockulus and lays the Grudges to sleep. +inline bool room_plates_is_triggered() +{ + return g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_PRESSURE_PLATES_TRIGGERED; +} + +// The body animations npc_axis_walk_animate walks by (NpcHelper::charger_update_move_anim's arguments): sideways, up +// and down, and the speed below which it stands. +struct AxisWalkAnims +{ + std::string_view side; + std::string_view up; + std::string_view down; + float threshold = 0; +}; + +void npc_axis_walk_animate(Entity_NPC& npc, const AxisWalkAnims& anims); +bool room_path_mark(Room& room, int gridIndex, int value); + +// The Gehenna enemies' AIs the dispatcher (npc_ai_update) runs by type. +void npc_maze_roamer_update(Entity_NPC& npc); +void npc_goat_update(Entity_NPC& npc); +void npc_whipper_update(Entity_NPC& npc); +void npc_mockulus_update(Entity_NPC& npc); +void npc_morningstar_update(Entity_NPC& npc); +void npc_baby_begotten_update(Entity_NPC& npc); +void npc_revenant_update(Entity_NPC& npc); +void npc_grudge_update(Entity_NPC& npc); +void npc_poofer_update(Entity_NPC& npc); +void npc_heart_update(Entity_NPC& npc); +void npc_cultist_update(Entity_NPC& npc); +void npc_swarm_spider_update(Entity_NPC& npc); diff --git a/src/npc_goat.cpp b/src/npc_goat.cpp new file mode 100644 index 0000000..9951c9f --- /dev/null +++ b/src/npc_goat.cpp @@ -0,0 +1,364 @@ +#include "npc_gehenna.h" +#include "boss_ai.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "game.h" +#include "room.h" +#include + +// The Goats run as a herd led by one of them (entityRef). Every 300 frames the leader ranks its herd by how close +// each is to its target, the healthier counting closer: the first becomes the herd's charger, the second its shooter, +// the rest keep away. The Black Goats (variant 1) may cue the leader to make every seen Black Goat cast a cross of +// beams. +constexpr int GOAT_BLACK = 1; +constexpr int GOAT_DASH = NPC_STATE_JUMP; +constexpr int GOAT_SHOOT = NPC_STATE_ATTACK; +constexpr int GOAT_BEAMS = NPC_STATE_ATTACK2; + +// The roles the leader hands out (i1). +enum GoatRole +{ + GOAT_ROLE_KEEP_AWAY, + GOAT_ROLE_SHOOTER, + GOAT_ROLE_CHARGER +}; + +constexpr int GOAT_RANK_EVERY = 300; +constexpr int GOAT_RANK_RETRY = 4; +constexpr float GOAT_RANK_HEALTH_WEIGHT = 20; +constexpr int GOAT_ROLE_COOLDOWN = 30; +constexpr int GOAT_ROLE_COOLDOWN_LOW = 4; +constexpr int GOAT_DEATH_RERANK = 15; + +constexpr int GOAT_PATH_MARKER = 900; +constexpr float GOAT_WALK_THRESHOLD = 0.1f; +constexpr float GOAT_EVADE_FRICTION = 0.8f; +constexpr float GOAT_WALK_FRICTION = 0.97f; +constexpr float GOAT_SHOOTER_SPEED = 0.68f; +constexpr float GOAT_SPEED = 0.8f; +constexpr float GOAT_LEAD_SCALE = 0.15f; + +// The charger dashes along its row at its target when within 24 of it (one try in four), the shooter shoots within +// 120. A Black Goat within 20 of its target's row or column cues the beams one frame in twelve. +constexpr int GOAT_DASH_ODDS = 4; +constexpr float GOAT_DASH_ROW = 24; +constexpr float GOAT_DASH_PUSH = 10; +constexpr float GOAT_DASH_FRICTION = 0.7f; +constexpr float GOAT_DASH_ROW_PULL = 0.8f; +constexpr float GOAT_SHOOT_RANGE = 120; +constexpr float GOAT_SHOT_SPEED = 10; +constexpr float GOAT_SHOOT_FRICTION = 0.6f; +constexpr int GOAT_ATTACK_DELAY = 45; +constexpr int GOAT_BEAM_DELAY = 60; +constexpr int GOAT_BEAM_ODDS = 12; +constexpr float GOAT_BEAM_ALIGN = 20; +constexpr int GOAT_BEAM_CUE = 8; + +// The beams: a warning cross of tracers, then four short thick beams scaled down. +constexpr int GOAT_BEAM_REST = -90; +static const Vector GOAT_BEAM_OFFSET = vector_make(0, -18); +constexpr ColorMod GOAT_WARNING_COLOR = {{0.6f, 0.05f, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int GOAT_WARNING_TIMEOUT = 32; +constexpr float GOAT_WARNING_SCALE = 2; +constexpr int GOAT_BEAM_TIMEOUT = 15; +constexpr float GOAT_BEAM_SCALE = 0.75f; +constexpr int GOAT_BEAM_COUNT = 4; +constexpr float GOAT_BEAM_TURN = 90; + +// Whether another entity can lead or follow this one: an NPC on its side. +static bool is_herd_kin(Entity_NPC& npc, Entity* other) +{ + return other && other->to_npc_or_coop_player() && other->IsFriendly() == npc.IsFriendly(); +} + +// The herd's leader: its own while that one lives, else the leader of another goat of the room, else itself. +static Entity_NPC* leader_find(Entity_NPC& npc) +{ + if (is_herd_kin(npc, npc.entityRef)) return static_cast(npc.entityRef.get()); + + Entity_NPC* leader = &npc; + for (Entity* other : entity_query(npc.type, -1)) + { + Entity* otherLeader = static_cast(other)->entityRef; + if (other != &npc && is_herd_kin(npc, other) && otherLeader && otherLeader->to_npc_or_coop_player()) + { + leader = static_cast(otherLeader); + break; + } + } + npc.entityRef = leader; + npc.projectileCooldown = 1; + return leader; +} + +// The leader ranks its walking herd by distance to their targets: charger, shooter, then the rest keeping away. It +// tries again shortly while one of them is busy. +static void herd_rank(Entity_NPC& npc) +{ + std::multimap ranked; + for (Entity* other : entity_query(npc.type, -1)) + { + auto* goat = static_cast(other); + if (!is_herd_kin(npc, goat) || goat->entityRef.get() != &npc) continue; + if (goat->state != NPC_STATE_MOVE) + { + npc.projectileCooldown = GOAT_RANK_RETRY; + return; + } + + float distance = vector_length(vector_sub(goat->GetPlayerTarget()->pos, goat->pos)); + ranked.emplace(distance - goat->health * GOAT_RANK_HEALTH_WEIGHT, goat); + } + + int rank = 0; + for (auto& [score, goat] : ranked) + { + goat->i1 = rank == 0 ? GOAT_ROLE_CHARGER : rank == 1 ? GOAT_ROLE_SHOOTER : GOAT_ROLE_KEEP_AWAY; + if (goat->projectileDelay < GOAT_ROLE_COOLDOWN_LOW) goat->projectileDelay = GOAT_ROLE_COOLDOWN; + rank++; + } + npc.projectileCooldown = GOAT_RANK_EVERY; +} + +// The leader's beam cue: every Black Goat of the herd in sight starts its beams behind a warning cross, while none is +// busy (the scan stops at the first busy one). +static void beams_cue(Entity_NPC& npc) +{ + std::vector casters; + for (Entity* other : entity_query(npc.type, GOAT_BLACK)) + { + auto* goat = static_cast(other); + if (!is_herd_kin(npc, goat) || goat->entityRef.get() != &npc) continue; + if (!g_game->room->camera->IsPosVisible(goat->pos)) continue; + if (goat->state != NPC_STATE_MOVE) break; + casters.push_back(goat); + } + + for (Entity_NPC* goat : casters) + { + goat->state = GOAT_BEAMS; + npc_anim_restart(goat->sprite, "Attack2"); + goat->i2 = GOAT_BEAM_REST; + for (int direction : {DIRECTION_RIGHT, DIRECTION_DOWN, DIRECTION_LEFT, DIRECTION_UP}) + following_effect_spawn(*goat, {.offset = GOAT_BEAM_OFFSET, + .targetPosition = vector_from_direction(direction), + .color = GOAT_WARNING_COLOR, + .scale = GOAT_WARNING_SCALE, + .timeout = GOAT_WARNING_TIMEOUT}); + } + npc.i2 = GOAT_BEAM_REST; +} + +// Counts the timers down by the ticks moved: the cooldowns to zero, the beam rest (i2) toward zero from either side. +static void timers_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + if (npc.projectileCooldown > 0) npc.projectileCooldown -= ticks; + if (npc.projectileDelay > 0) npc.projectileDelay -= ticks; + if (npc.i2 < 0) npc.i2 = std::min(npc.i2 + ticks, 0); + else if (npc.i2 > 0) npc.i2 = std::max(npc.i2 - ticks, 0); +} + +// A cry at the goat's pitch. +static void goat_cry(Entity_NPC& npc, int sound) +{ + npc_sound_play(sound, 1, 2, champion_pitch_get(npc)); +} + +// Where its shots go at 10: its controller's aim or toward its target. +static Vector shot_aim(Entity_NPC& npc) +{ + bool isSteered = npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement); + Vector aim = isSteered ? npc.controllerMovement : vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + return vector_resized(aim, GOAT_SHOT_SPEED); +} + +// The charger's and shooter's attacks, or a Black Goat's beam cue. +static void attack_try(Entity_NPC& npc, Entity_NPC& leader, Entity& target) +{ + Vector offset = vector_sub(target.pos, npc.pos); + bool isAligned = std::abs(offset.x) < GOAT_BEAM_ALIGN || std::abs(offset.y) < GOAT_BEAM_ALIGN; + if (npc.variant == GOAT_BLACK && Random() % GOAT_BEAM_ODDS == 0 && npc.i2 >= 0 && isAligned) + { + if (leader.i2 >= 0 && !leader.child) leader.i2 = GOAT_BEAM_CUE; + return; + } + + if (npc.i1 == GOAT_ROLE_CHARGER && (Random() & (GOAT_DASH_ODDS - 1)) == 0 && npc.projectileDelay < 1 && + std::abs(offset.y) < GOAT_DASH_ROW && room_check_line(npc.pos, target.pos, LINE_MODE_CELL, GOAT_PATH_MARKER)) + { + npc.state = GOAT_DASH; + npc.sprite.Play("DashBegin"); + npc.sprite.isFlipX = target.pos.x < npc.pos.x; + npc.targetPosition = vector_make(npc.pos.x <= target.pos.x ? 1 : -1, 0); + npc.stateFrame = 0; + npc.PlaySound(npc.variant == GOAT_BLACK ? SOUND_MONSTER_GRUNT_4 : SOUND_ANGRY_GURGLE, 1, 2, false, 1); + return; + } + if (npc.i1 == GOAT_ROLE_SHOOTER && npc.projectileDelay < 1 && + npc.IsTargetInAttackRange(GOAT_SHOOT_RANGE, 1, true)) + { + npc.state = GOAT_SHOOT; + bool isHorizontal = std::abs(npc.velocity.x) > std::abs(npc.velocity.y); + npc.sprite.Play(isHorizontal ? "AttackHori" : "AttackVert"); + npc.stateFrame = 0; + } +} + +// Walking its role: the charger and shooter chase the leader's target (the shooter leading it), the rest keep away +// from it. A feared or shrunk goat flees its own target, a controlled one goes where it is steered. +static void walk_update(Entity_NPC& npc, Entity_NPC& leader) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", GOAT_WALK_THRESHOLD); + if (npc.controllerID != -1) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), GOAT_SPEED, GOAT_PATH_MARKER, DIRECT_PATH_FAR); + else if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= GOAT_EVADE_FRICTION; + } + else if (npc.i1 == GOAT_ROLE_KEEP_AWAY) + { + npc.pathfinder.EvadeTarget(leader.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= GOAT_EVADE_FRICTION; + } + else + { + Entity& target = *leader.GetPlayerTarget(); + bool isShooter = npc.i1 == GOAT_ROLE_SHOOTER; + float lead = vector_length(vector_sub(npc.pos, target.pos)) * GOAT_LEAD_SCALE; + Vector goal = isShooter ? vector_add(target.pos, vector_scale(target.velocity, lead)) : target.pos; + npc.pathfinder.FindGridPath(goal, isShooter ? GOAT_SHOOTER_SPEED : GOAT_SPEED, GOAT_PATH_MARKER, + DIRECT_PATH_FAR); + attack_try(npc, leader, target); + } + npc.friction *= GOAT_WALK_FRICTION; +} + +// Dashing along its row: it charges once the begin animation's shot event passed, held to its row, and stops at a +// wall or block ahead (or when distracted). +static void dash_update(Entity_NPC& npc, Entity_NPC& leader) +{ + npc.friction *= GOAT_DASH_FRICTION; + if (npc.stateFrame != 0) + { + npc.entityCollisionClass = ENTCOLL_ALL; + if (!npc_anim_is_done(npc)) return; + + npc.state = NPC_STATE_MOVE; + npc.projectileDelay = GOAT_ATTACK_DELAY; + leader.projectileCooldown = 1; + return; + } + + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) + goat_cry(npc, npc.variant == GOAT_BLACK ? SOUND_MONSTER_YELL_A : SOUND_CHILD_ANGRY_ROAR); + if (npc_anim_is_done(npc)) npc.sprite.Play("DashLoop"); + const AnimationData* anim = npc.sprite.animState.animData; + if (!anim || (!npc.sprite.WasEventTriggered("Shoot") && !anim->isLooping)) return; + + Room& room = *g_game->room; + npc.entityCollisionClass = ENTCOLL_ENEMIES; + float rowY = room.GetGridPosition(room.GetGridIndex(npc.pos)).y; + Vector push = vector_scale(vector_scale(npc.targetPosition, GOAT_DASH_PUSH), npc.speedMultiplier); + npc.velocity = vector_add(npc.velocity, push); + float pull = 1 - timescale_factor(GOAT_DASH_ROW_PULL, npc.speedMultiplier); + npc.velocity.y += (rowY - npc.pos.y - npc.velocity.y) * pull; + + Vector ahead = vector_add(npc.pos, vector_scale(npc.targetPosition, GRID_CELL_SIZE)); + if (room_grid_collision_at(ahead) != COLLISION_NONE || npc.HasEntityFlags(FLAG_DISTRACTED)) + { + npc.sprite.Play("DashEnd"); + npc.stateFrame = 1; + } +} + +// Shooting: a fan at each of its two shot events, wider for a Black Goat. +static void shoot_update(Entity_NPC& npc, Entity_NPC& leader) +{ + bool isBlack = npc.variant == GOAT_BLACK; + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) + { + ProjectileParams params; + goat_cry(npc, isBlack ? SOUND_MONSTER_GRUNT_1 : SOUND_SHAKEY_KID_ROAR); + npc.FireProjectiles(npc.pos, shot_aim(npc), isBlack ? PROJECTILES_THREE_WIDE : PROJECTILES_TWO, params); + } + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot2")) + { + ProjectileParams params; + goat_cry(npc, isBlack ? SOUND_MONSTER_GRUNT_2 : SOUND_SHAKEY_KID_ROAR); + npc.FireProjectiles(npc.pos, shot_aim(npc), isBlack ? PROJECTILES_FOUR : PROJECTILES_THREE_WIDE, params); + } + if (npc_anim_is_done(npc)) + { + npc.projectileDelay = GOAT_ATTACK_DELAY; + npc.state = NPC_STATE_MOVE; + leader.projectileCooldown = 1; + } + npc.friction *= GOAT_SHOOT_FRICTION; +} + +// A Black Goat's beams: a cry, then a short beam each way. +static void beams_update(Entity_NPC& npc, Entity_NPC& leader) +{ + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) goat_cry(npc, SOUND_MONSTER_YELL_B); + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot2")) + for (int i = 0; i < GOAT_BEAM_COUNT; i++) + { + Entity_Laser* beam = Entity_Laser::ShootAngle({.position = npc.pos, + .posOffset = GOAT_BEAM_OFFSET, + .source = &npc, + .angleDegrees = i * GOAT_BEAM_TURN, + .timeout = GOAT_BEAM_TIMEOUT, + .variant = LASER_THICK_RED}); + beam->scale = GOAT_BEAM_SCALE; + beam->ResetSpriteScale(); + } + if (npc_anim_is_done(npc)) + { + npc.projectileDelay = GOAT_BEAM_DELAY; + npc.i2 = GOAT_BEAM_REST; + npc.state = NPC_STATE_MOVE; + leader.projectileCooldown = 1; + } + npc.friction *= GOAT_SHOOT_FRICTION; +} + +// 004f2c20 The Goat's and Black Goat's AI: a herd whose leader hands out the charger and shooter roles and cues the +// Black Goats' beam crosses. +void npc_goat_update(Entity_NPC& npc) +{ + Entity_NPC& leader = *leader_find(npc); + if (&leader == &npc) + { + if (npc.i2 >= 1) beams_cue(npc); + else if (npc.projectileCooldown < 1) herd_rank(npc); + } + timers_update(npc); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_MOVE; + npc.i1 = GOAT_ROLE_KEEP_AWAY; + break; + case NPC_STATE_MOVE: + walk_update(npc, leader); + break; + case GOAT_DASH: + dash_update(npc, leader); + break; + case GOAT_SHOOT: + shoot_update(npc, leader); + break; + case GOAT_BEAMS: + beams_update(npc, leader); + break; + default: + break; + } + + room_path_raise_at(npc.pos, GOAT_PATH_MARKER); + bool isHerded = npc.i1 == GOAT_ROLE_SHOOTER || npc.i1 == GOAT_ROLE_CHARGER; + if (npc.isDead && &leader != &npc && isHerded) leader.projectileCooldown = GOAT_DEATH_RERANK; +} diff --git a/src/npc_grudge.cpp b/src/npc_grudge.cpp new file mode 100644 index 0000000..d224204 --- /dev/null +++ b/src/npc_grudge.cpp @@ -0,0 +1,393 @@ +#include "npc_gehenna.h" +#include +#include "boss_ai.h" +#include "capsule.h" +#include "entity_bomb.h" +#include "entity_combat.h" +#include "entity_config.h" +#include "manager.h" +#include "npc_fireplace.h" + +// The Grudge is an invulnerable spiked block that sits in its cell, its eye following its target. A player lined up +// with it in a clear row or column sets it charging that way, faster and faster up to 4, until it slams into a wall or +// another Grudge. What it runs into is shoved ahead of it, and crushed against a wall, block, pit or Grudge: enemies +// die, bombs go off, a dead player bursts. It sleeps once the room's plates are pressed, and Flat File (doubled) blunts its +// spikes. +constexpr int GRUDGE_WAKING = NPC_STATE_IDLE; +constexpr int GRUDGE_WAITING = NPC_STATE_MOVE; +constexpr int GRUDGE_CHARGING = NPC_STATE_ATTACK; +constexpr int GRUDGE_ASLEEP = NPC_STATE_SPECIAL; + +constexpr int GRUDGE_PATH_MARKER = 900; +constexpr int GRUDGE_WAKE_DELAY = 5; +constexpr int GRUDGE_WAIT = 4; +constexpr int GRUDGE_SLAM_WAIT = 15; +constexpr float GRUDGE_FRICTION = 0.8f; +constexpr float GRUDGE_CONTACT_DAMAGE = 1; +constexpr float GRUDGE_CHARGE_DAMAGE = 2; +constexpr int GRUDGE_SHAKE = 6; +constexpr int GRUDGE_LOOK_FRAMES = 8; +constexpr float GRUDGE_LOOK_STEP = 45; +constexpr float GRUDGE_LOOK_ROUNDING = 8.5f; + +// A player within 24 of its row or column, farther than that along it and in a clear line starts the charge. +constexpr float GRUDGE_LANE = 24; +constexpr float GRUDGE_CHARGE_MAX = 4; +constexpr float GRUDGE_WALL_REACH = 2; + +// Running something over: a shove toward just ahead of it (stronger on a dead player), within 80 of its size. +constexpr float GRUDGE_SHOVE = 0.6f; +constexpr float GRUDGE_DEAD_SHOVE = 0.8f; +constexpr float GRUDGE_QUERY_MARGIN = 80; +constexpr float GRUDGE_FIRE_DAMAGE = 1000; +constexpr int GRUDGE_FIRE_COUNTDOWN = 30; +constexpr int GRUDGE_DEAD_PLAYER_LAYER = 12; +constexpr int GRUDGE_GIBS = 10; +constexpr float GRUDGE_GIB_SPREAD = 40; +constexpr uint32_t GRUDGE_GIB_DEFAULT = GIB_FLAG_POOP | GIB_FLAG_WORM; +constexpr int GRUDGE_BURST_SIZE = 3; + +// The blood it trails after crushing something: a splat every frame for 30 to 59 frames, fading, and grey dust every +// other frame while it charges. +constexpr float GRUDGE_BLOOD_MIN = 30; +constexpr float GRUDGE_BLOOD_RANGE = 30; +constexpr float GRUDGE_BLOOD_FADE = 30; +constexpr float GRUDGE_SPLAT_MIN = 0.2f; +constexpr float GRUDGE_SPLAT_RANGE = 0.2f; +constexpr float GRUDGE_SPLAT_FRESH = 0.2f; +constexpr int GRUDGE_SPLAT_PRIORITY = 255; +constexpr float GRUDGE_DUST_EVERY = 2; +constexpr float GRUDGE_DUST_DRAG = 0.2f; +constexpr float GRUDGE_DUST_SPIN_MIN = 2; +constexpr float GRUDGE_DUST_SPIN_RANGE = 10; +constexpr int GRUDGE_DUST_LIFE_MIN = 15; +constexpr int GRUDGE_DUST_LIFE_RANGE = 15; +constexpr float GRUDGE_DUST_SCALE_MIN = 0.3f; +constexpr float GRUDGE_DUST_SCALE_RANGE = 0.3f; +constexpr ColorMod GRUDGE_DUST_COLOR = {{0.45f, 0.45f, 0.45f, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int FLAT_FILE_BLUNTING = 2; +constexpr ColorMod GRUDGE_SPLAT_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; +constexpr int PATH_MARK_CEILING = 950; + +// 004565e0 (Room::SetGridPath's guarded copy) Marks a cell's path cost unless something costlier already holds it. +bool room_path_mark(Room& room, int gridIndex, int value) +{ + if ((uint32_t)gridIndex >= ROOM_GRID_CELLS || room.gridPaths[gridIndex] > PATH_MARK_CEILING) return false; + + room.gridPaths[gridIndex] = value; + return true; +} + +// Its contact damage: none while blunted, more while charging fast. +static float grudge_damage(Entity_NPC& npc, float damage) +{ + return npc.i2 == 0 ? damage : 0; +} + +// Settles into the cell it stands in, waiting there. +static void grudge_settle(Entity_NPC& npc, int wait) +{ + Room& room = *g_game->room; + npc.state = GRUDGE_WAITING; + npc.collisionDamage = grudge_damage(npc, GRUDGE_CONTACT_DAMAGE); + npc.pathfinder.gridIndex = room.GetGridIndex(npc.pos); + npc.targetPosition = room.GetGridPosition(npc.pathfinder.gridIndex); + room_path_mark(room, npc.pathfinder.gridIndex, GRUDGE_PATH_MARKER); + npc.stateFrame = wait; +} + +// Waiting: asleep once the room's plates are all pressed and no enemy is left, else after its wait it charges at a player lined up with it. +static void wait_update(Entity_NPC& npc, int ticks, bool isPlatesTriggered) +{ + if (g_game->room->isTriggerPressurePlates && isPlatesTriggered && npc.GetAliveEnemyCount() < 1) + { + npc.sprite.Play("Sleep"); + npc.flags &= ~FLAG_NO_PHYSICS_KNOCKBACK; + npc.state = GRUDGE_ASLEEP; + npc.collisionDamage = 0; + npc.friction *= GRUDGE_FRICTION; + return; + } + + npc.stateFrame = std::max(npc.stateFrame - ticks, 0); + if (npc.stateFrame >= 1) return; + + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->isDead || player->entityCollisionClass == ENTCOLL_NONE) continue; + + Vector offset = vector_sub(player->pos, npc.pos); + float across = std::min(std::abs(offset.x), std::abs(offset.y)); + float along = std::max(std::abs(offset.x), std::abs(offset.y)); + if (across > GRUDGE_LANE || along <= GRUDGE_LANE) continue; + if (!room_check_line(npc.pos, player->pos, LINE_MODE_CELL, LINE_CHECK_THRESHOLD)) continue; + + npc.v1 = vector_cardinal(offset); + npc.state = GRUDGE_CHARGING; + npc.v2.x = 0; + } +} + +// The trail it leaves while charging: fading blood after a crush, and grey dust. +static void trail_spawn(Entity_NPC& npc) +{ + if (npc.v2.y > 0) + { + if (npc.GetIntervalTicks(1, 0) != 0) + { + float freshness = std::clamp(npc.v2.y / GRUDGE_BLOOD_FADE, 0.0f, 1.0f); + Entity_Effect* splat = + npc.MakeSplat(random_unit() * GRUDGE_SPLAT_RANGE + GRUDGE_SPLAT_MIN + freshness * GRUDGE_SPLAT_FRESH); + ColorMod color = npc.splatColor; + color._tint[3] *= freshness; + splat->SetColor(color, -1, GRUDGE_SPLAT_PRIORITY, false, true); + } + npc.v2.y = std::max(npc.v2.y - npc.speedMultiplier, 0.0f); + } + if (npc.GetIntervalTicks(GRUDGE_DUST_EVERY, 0) == 0) return; + + uint32_t seed = Random(); + Vector drift = vector_add(random_direction(), vector_scale(npc.velocity, GRUDGE_DUST_DRAG)); + auto* dust = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = drift, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = seed})); + dust->rotation = random_unit() * GRUDGE_DUST_SPIN_RANGE + GRUDGE_DUST_SPIN_MIN; + int life = (int)(Random() % GRUDGE_DUST_LIFE_RANGE) + GRUDGE_DUST_LIFE_MIN; + dust->timeout = life; + dust->lifespan = life; + dust->SetColor(GRUDGE_DUST_COLOR, -1, GRUDGE_SPLAT_PRIORITY, false, true); + float scale = random_unit() * GRUDGE_DUST_SCALE_RANGE + GRUDGE_DUST_SCALE_MIN; + dust->sprite.scale = vector_make(scale, scale); +} + +// Whether a point is held fast: in a wall, inside another Grudge, over a pit (for a walker) or in a block (for what +// does not fly over them). +static bool is_point_blocked(Entity& other, Vector point, const std::vector& grudges) +{ + uint32_t collision = g_game->room->GetGridCollision(g_game->room->GetGridIndex(point)); + if (collision == COLLISION_WALL) return true; + for (Entity* grudge : grudges) + if (vector_length_squared(vector_sub(grudge->pos, point)) <= grudge->size * grudge->size) return true; + if (collision == COLLISION_PIT) return other.entityGridCollisionClass == GRIDCOLL_GROUND; + return (collision == COLLISION_OBJECT || collision == COLLISION_SOLID) && + other.entityGridCollisionClass != GRIDCOLL_WALLS; +} + +// Crushes what it pinned: a bomb goes off, a player in its death bursts into gibs, anything else dies. The blood +// trails after it. +static void crush(Entity_NPC& npc, Entity& other) +{ + if (other.type == ENTITY_BOMB) return static_cast(other).SetExplosionCountdown(0); + if (other.type == ENTITY_PLAYER) + { + if (!other.sprite.IsPlaying("Death")) return; + LayerState& body = *other.sprite.GetLayer(GRUDGE_DEAD_PLAYER_LAYER); + if (!body.isVisible) return; + + body.isVisible = false; + g_game->Spawn({.position = npc.pos, + .subType = GRUDGE_BURST_SIZE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + npc_sound_play(SOUND_DEATH_BURST_SMALL, 1, 2, 1); + auto& entities = g_manager->entityConfig.entities; + auto gaper = entities.find(entity_key(ENTITY_GAPER, 0, 0)); + gibs_spawn({.color = COLOR_DEFAULT, + .position = other.pos, + .spread = GRUDGE_GIB_SPREAD, + .amount = GRUDGE_GIBS, + .gibFlags = gaper != entities.end() ? gaper->second.gibFlags : GRUDGE_GIB_DEFAULT}); + npc.v2.y = random_unit() * GRUDGE_BLOOD_RANGE + GRUDGE_BLOOD_MIN; + npc.splatColor = COLOR_DEFAULT; + return; + } + + other.Kill(EntityRef{}); + if (!(other.config->gibFlags & GIB_FLAG_BLOOD)) return; + npc.v2.y = random_unit() * GRUDGE_BLOOD_RANGE + GRUDGE_BLOOD_MIN; + npc.splatColor = other.splatColor; +} + +// What its charge runs into: another Grudge stops it, fireplaces (but blue and purple ones) are snuffed, the rest are +// carried along, and an enemy, bomb or dead player carried into something solid is crushed. +static void run_over(Entity_NPC& npc, Entity& other, const Capsule& body, const std::vector& grudges) +{ + if (other.type == ENTITY_GRUDGE) + { + game_shake_screen(GRUDGE_SHAKE); + npc_sound_play(SOUND_STONE_IMPACT, 1, 2, champion_pitch_get(npc)); + return grudge_settle(npc, GRUDGE_SLAM_WAIT); + } + + bool isSnuffed = other.type == ENTITY_FIREPLACE && other.variant != FIRE_COAL; + if (isSnuffed && other.variant != FIRE_BLUE && other.variant != FIRE_PURPLE) + { + other.health = 1; + other.TakeDamage(GRUDGE_FIRE_DAMAGE, 0, EntityRef(&npc), GRUDGE_FIRE_COUNTDOWN); + } + if (isSnuffed) return; + + bool isDeadPlayer = other.type == ENTITY_PLAYER && other.isDead; + float shove = isDeadPlayer ? GRUDGE_DEAD_SHOVE : GRUDGE_SHOVE; + float carry = timescale_factor(shove, npc.speedMultiplier); + other.velocity = vector_add(other.velocity, vector_scale(vector_sub(npc.velocity, other.velocity), carry)); + if (!other.to_npc_or_coop_player() && other.type != ENTITY_BOMB && !isDeadPlayer) return; + + if (other.friction != 0) + { + Vector ahead = vector_sub(vector_add(body.center, vector_scale(npc.v1, other.size)), other.pos); + other.velocity = vector_add(other.velocity, vector_scale(ahead, shove * other.speedMultiplier / other.friction)); + } + if (other.entityGridCollisionClass == GRIDCOLL_NONE) return; + + Vector next = vector_add(other.pos, vector_scale(other.velocity, other.speedMultiplier * other.friction)); + for (const Vector& point : other.collisionPoints) + if (is_point_blocked(other, vector_add(next, point), grudges)) return crush(npc, other); +} + +// Charging: it speeds up along its lane, held to its cell's line, trailing blood and dust. It stops at a wall, and +// runs over the players and enemies ahead of it. The original shifts the others' capsules by their velocity only at +// their centers, which the collision ignores, so they are tested where they stand. +static void charge_update(Entity_NPC& npc) +{ + float speed = npc.speedMultiplier; + npc.v2.x = std::min(speed + npc.v2.x, GRUDGE_CHARGE_MAX); + npc.friction *= GRUDGE_FRICTION; + if (npc.friction != 0) + { + npc.velocity.y += speed * npc.v2.x * npc.v1.y / npc.friction; + npc.velocity.x += speed * npc.v1.x * npc.v2.x / npc.friction; + } + if (std::abs(npc.v1.x) <= std::abs(npc.v1.y)) + npc.velocity.x = npc.targetPosition.x - npc.pos.x; + else + npc.velocity.y = npc.targetPosition.y - npc.pos.y; + if (npc.v2.x >= GRUDGE_CHARGE_MAX) npc.collisionDamage = grudge_damage(npc, GRUDGE_CHARGE_DAMAGE); + trail_spawn(npc); + + Room& room = *g_game->room; + Vector ahead = vector_add(npc.pos, vector_scale(npc.v1, npc.size + GRUDGE_WALL_REACH)); + if (npc.isCollidesWithGrid && room_grid_collision_at(ahead) != COLLISION_NONE) + { + game_shake_screen(GRUDGE_SHAKE); + npc.PlaySound(SOUND_STONE_IMPACT, 1, 2, false, 1); + npc.state = GRUDGE_WAITING; + npc.collisionDamage = grudge_damage(npc, GRUDGE_CONTACT_DAMAGE); + npc.pathfinder.UpdateGridIndex(); + npc.targetPosition = room.GetGridPosition(npc.pathfinder.gridIndex); + room_path_mark(room, npc.pathfinder.gridIndex, GRUDGE_PATH_MARKER); + npc.stateFrame = GRUDGE_SLAM_WAIT; + } + + Capsule body(vector_add(npc.pos, vector_scale(npc.velocity, npc.speedMultiplier)), npc.sizeMulti, 0, npc.size); + EntityList_EL nearby = entity_query_radius(body.center, npc.size + GRUDGE_QUERY_MARGIN, QUERY_ENEMIES | QUERY_PLAYERS); + std::vector grudges; + for (Entity* other : nearby) + if (other->type == ENTITY_GRUDGE && other != &npc) grudges.push_back(other); + + for (Entity* other : nearby) + { + bool isSolid = other->entityCollisionClass == ENTCOLL_ALL || other->entityCollisionClass == ENTCOLL_ENEMIES; + if (other == &npc || !isSolid || vector_dot(vector_sub(other->pos, npc.pos), npc.v1) <= 0) continue; + if (Capsule::Collide(body, other->GetCollisionCapsule({}))) run_over(npc, *other, body, grudges); + } +} + +// Wakes, sleeps or charges, then shows its eye toward its target and keeps to its cell when not charging. Flat File +// (doubled) swaps its spikes for the retracted look. +static void look_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + if (npc.state == GRUDGE_WAITING || npc.state == GRUDGE_CHARGING) + { + float angle = vector_angle(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + int frame = (int)(angle / GRUDGE_LOOK_STEP + GRUDGE_LOOK_ROUNDING) % GRUDGE_LOOK_FRAMES; + if (npc.sprite.SetAnimation("Look", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat((float)frame); + npc.sprite.animState.isPlaying = false; + } + } + if (npc.state != GRUDGE_CHARGING) + { + room_path_mark(room, npc.pathfinder.gridIndex, GRUDGE_PATH_MARKER); + npc.friction *= GRUDGE_FRICTION; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + } + + Entity_Player* owner = g_game->playerManager.FirstTrinketOwner(TRINKET_FLAT_FILE); + bool isBlunted = owner && owner->GetTrinketMultiplier(TRINKET_FLAT_FILE) >= FLAT_FILE_BLUNTING; + if ((npc.i2 != 0) == isBlunted) return; + + npc.i2 = 1 - npc.i2; + npc.collisionDamage = grudge_damage(npc, GRUDGE_CHARGE_DAMAGE); + npc.sprite.ReplaceSpritesheet(0, npc.i2 ? "gfx/Monsters/repentance/grudge_retracted.png" + : "gfx/Monsters/repentance/grudge.png"); + npc.sprite.LoadGraphics(); +} + +// 004e6570 The Grudge's AI: a spiked block that charges along rows and columns at players and crushes what it carries +// into walls. +void npc_grudge_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + int ticks = npc_ticks_get(npc); + npc.GetPlayerTarget(); + bool isPlatesTriggered = room_plates_is_triggered(); + switch (npc.state) + { + case NPC_STATE_INIT: + npc.sprite.Play("No-Spikes"); + npc.stateFrame = GRUDGE_WAKE_DELAY; + npc.state = GRUDGE_WAKING; + npc.pathfinder.UpdateGridIndex(); + npc.targetPosition = room.GetGridPosition(npc.pathfinder.gridIndex); + room_path_mark(room, npc.pathfinder.gridIndex, GRUDGE_PATH_MARKER); + npc.flags |= FLAG_HIDE_HP_BAR; + npc.isInvincible = true; + npc.flags = (npc.flags & ~FLAG_APPEAR) | FLAG_NO_PHYSICS_KNOCKBACK | FLAG_NO_BLOOD_SPLASH | + FLAG_NO_STATUS_EFFECTS; + npc.splatColor = GRUDGE_SPLAT_COLOR; + if (room.isInitialized && g_game->frameCount == room.enterFrame && isPlatesTriggered) npc.Remove(); + npc.collisionDamage = 0; + npc.i1 = 0; + npc.i2 = 0; + break; + case GRUDGE_WAKING: + if (npc.stateFrame >= 1) + { + npc.stateFrame -= ticks; + break; + } + npc.sprite.Play("Wake"); + if (npc.sprite.IsEventTriggered("Sound")) + { + npc.PlaySound(SOUND_GOOATTACH0, 1, 2, false, 1); + npc.collisionDamage = grudge_damage(npc, GRUDGE_CONTACT_DAMAGE); + } + if (npc_anim_is_done(npc)) + { + npc.state = GRUDGE_WAITING; + npc.stateFrame = GRUDGE_WAIT; + } + break; + case GRUDGE_WAITING: + wait_update(npc, ticks, isPlatesTriggered); + if (npc.state == GRUDGE_ASLEEP) return; + break; + case GRUDGE_CHARGING: + charge_update(npc); + break; + case GRUDGE_ASLEEP: + npc.collisionDamage = 0; + npc.friction *= GRUDGE_FRICTION; + return; + default: + break; + } + look_update(npc); +} diff --git a/src/npc_heart.cpp b/src/npc_heart.cpp new file mode 100644 index 0000000..831842e --- /dev/null +++ b/src/npc_heart.cpp @@ -0,0 +1,415 @@ +#include "npc_gehenna.h" +#include "boss_ai.h" +#include "active_items.h" +#include + +// The Heart (92) and the Heart of Infamy (98) beat away from their target and burst into shots when close. A linked +// Heart (variant 1) pairs with the nearest free one of the other side (subtype): the two keep their target between +// them, each on its own side, firing small shots at each other through it. A Carrion Queen's heart hurts the Queen as +// it dies. +constexpr int HEART_LINKED = 1; +constexpr int HEART_ATTACK = NPC_STATE_ATTACK; +constexpr int HEART_RIGHT_SIDE = 1; +constexpr float HEART_PAIR_SCORE = 1000; +constexpr float HEART_FRICTION = 0.8f; +constexpr float HEART_ATTACK_FRICTION = 0.7f; +constexpr float HEART_CHASE_SPEED = 1; +constexpr int HEART_PATH_MARKER = 900; +constexpr int HEART_ATTACK_EVERY = 3; +constexpr float HEART_ATTACK_REACH = 10000; +constexpr int HEART_ATTACK_COOLDOWN = 10; +constexpr float HEART_CONTROLLED_SPEED = 0.2f; +constexpr int CONTROLLER_ACTION_HOLD = 11; +constexpr int CONTROLLER_ACTION_ATTACK = 8; +constexpr ColorMod HEART_INFAMY_BURST_COLOR = {{1, 1, 1, 1}, {0.84f, 0.4f, 0.68f, 1}, {0, 0, 0}}; + +// The bursts: a cross or plus of fast shots (the Heart of Infamy's eight, or its smart plus for subtype 1), a blood +// burst at its top, and the Heart of Infamy's two splats. +constexpr float HEART_SHOT_SPEED = 12; +constexpr float HEART_INFAMY_SMART_SPEED = 8; +static const Vector HEART_BLOOD_OFFSET = vector_make(0, -20); +constexpr int HEART_BLOOD_SIZE = 2; +constexpr int HEART_INFAMY_BLOOD_SIZE = 4; +constexpr int HEART_COLOR_PRIORITY = 255; +constexpr float HEART_SPLAT_MIN = 0.6f; +constexpr float HEART_SPLAT_SECOND_RANGE = 0.5f; +constexpr float HEART_SPLAT_SPREAD = 10; +constexpr float HEART_SPLAT_DROP = 12; + +// A linked pair's shots at each other, every 12 frames: small, slow falling, at 7. +constexpr float LINK_SHOT_EVERY = 12; +constexpr float LINK_SHOT_SPEED = 7; +constexpr float LINK_SHOT_SCALE = 0.6f; +constexpr float LINK_SHOT_FALL = -0.09f; + +// A linked heart's dodging: it holds while its target stays 170 off (within 340 when charmed) and its partner 60 to +// 180 away in a clear line on its side, else steps aside: up to 7 spots 30 to 480 out are scored for being far from the +// target (near it when charmed), 170 from the partner, across the target from it and in sight of the partner. +constexpr int LINK_CHECK_EVERY = 14; +constexpr int LINK_FORGET_EVERY = 30; +constexpr int LINK_RECHECK_EVERY = 10; +constexpr float LINK_TARGET_RANGE = 170; +constexpr float LINK_CHARMED_RANGE = 340; +constexpr float LINK_PARTNER_MIN = 60; +constexpr float LINK_PARTNER_MAX = 180; +constexpr int LINK_PARTNER_FAR_ODDS = 4; +constexpr float LINK_SIDE_SLACK = 4; +constexpr int LINK_EVADE_FRAMES = 3; +constexpr float LINK_EVADE_MAX = 20; +constexpr float LINK_EVADE_DECAY = 0.9f; +constexpr float LINK_TARGET_NEAR = 250; +constexpr float LINK_TIE = 0.25f; +constexpr float LINK_STEP_PUSH = 1.5f; +constexpr float LINK_SEARCH_AHEAD = 30; +constexpr float LINK_SEARCH_TRIES = 7; +constexpr float LINK_SEARCH_TRY_COST = 0.3f; +constexpr float LINK_SEARCH_REVISIT = 0.7f; +constexpr float LINK_SEARCH_MIN = 30; +constexpr float LINK_SEARCH_RANGE = 450; +constexpr float LINK_SEARCH_FLAT = 0.5f; +constexpr float LINK_SCORE_START = -1000000; +constexpr float LINK_SCORE_TARGET = 0.25f; +constexpr float LINK_SCORE_BLOCKED = 90000; +constexpr float LINK_SCORE_HIDDEN = 40000; +constexpr float LINK_SPOT_FAR = 40000; +constexpr float LINK_SPOT_PARTNER_FAR = 3600; +constexpr float LINK_STEP_SPEED = 1.079f; + +// A Carrion Queen's heart hurts her by 40 as it dies. +constexpr float QUEEN_HEART_DAMAGE = 40; +constexpr int QUEEN_HEART_COUNTDOWN = 30; +constexpr float QUEEN_HEART_VOLUME = 0.5f; + +// The first frame: a linked heart without a partner takes the nearest free one of the other side. +static void heart_link(Entity_NPC& npc) +{ + if (npc.type != ENTITY_HEART || npc.variant != HEART_LINKED || npc.entityRef) return; + + Entity_NPC* partner = nullptr; + float bestScore = 0; + for (Entity* other : entity_query(ENTITY_HEART, HEART_LINKED)) + { + auto* heart = static_cast(other); + if (!heart->to_npc_or_coop_player() || heart->subtype != 1 - npc.subtype || heart->child || heart->entityRef) + continue; + float score = HEART_PAIR_SCORE - vector_length(vector_sub(npc.pos, heart->pos)); + if (partner && bestScore >= score) continue; + partner = heart; + bestScore = score; + } + if (!partner) return; + + partner->entityRef = &npc; + npc.entityRef = partner; + partner->child = &npc; + npc.parent = partner; + if (npc.child && npc.child->IsEnemy()) static_cast(npc.child.get())->entityRef = partner; +} + +// The spot a heart heads for while dodging, else where it stands. +static Vector dodge_spot_get(Entity_NPC& heart) +{ + PathFinder& path = heart.pathfinder; + return path.evadeMovementCountdown >= 1 && !vector_is_zero(path.movementTarget) ? path.movementTarget : heart.pos; +} + +// Which way its side lies from its partner: left for subtype 0, right for subtype 1. +static float side_get(Entity_NPC& npc) +{ + return npc.subtype == HEART_RIGHT_SIDE ? -1.0f : 1.0f; +} + +// The context a linked heart scores its dodges in. +struct LinkDodge +{ + Vector targetPos{}; + Vector partnerSpot{}; + int pathThreshold = 0; + bool isCharmed = false; +}; + +// Scores a free spot to dodge to: far from the target (near it when charmed), 170 from the partner, across the target +// from it, in sight of the partner, and hidden from the target. Nothing for a spot on the wrong side of the partner. +static bool spot_score(Entity_NPC& npc, const LinkDodge& dodge, Vector spot, float& score) +{ + if ((spot.x - dodge.partnerSpot.x) * side_get(npc) > LINK_SIDE_SLACK) return false; + + bool isSeenByTarget = room_check_line(dodge.targetPos, spot, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD); + bool isSeenByPartner = room_check_line(dodge.partnerSpot, spot, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD); + Vector fromTarget = vector_sub(spot, dodge.targetPos); + float targetScore = vector_length_squared(fromTarget) * (dodge.isCharmed ? -1.0f : 1.0f) * LINK_SCORE_TARGET; + float partnerGap = vector_length(vector_sub(spot, dodge.partnerSpot)) - LINK_TARGET_RANGE; + float across = vector_dot(vector_sub(dodge.partnerSpot, dodge.targetPos), fromTarget); + float blocked = isSeenByPartner ? 0 : LINK_SCORE_BLOCKED; + float hidden = !dodge.isCharmed && !isSeenByTarget ? LINK_SCORE_HIDDEN : 0; + score = targetScore - partnerGap * partnerGap - across - blocked + hidden; + return true; +} + +// Picks a new spot to dodge to: a step away from its partner (or its near target), then the best of a few random +// cells ahead, each tried once until it forgets them. +static void dodge_pick(Entity_NPC& npc, Entity_NPC& partner, const LinkDodge& dodge) +{ + PathFinder& path = npc.pathfinder; + float partnerDistance = vector_length(vector_sub(partner.pos, npc.pos)); + float targetDistance = vector_length(vector_sub(dodge.targetPos, npc.pos)); + Vector step = vector_make(1, 0); + if (side_get(npc) * (npc.pos.x - partner.pos.x) <= 0) + { + bool isTargetNear = targetDistance < partnerDistance && targetDistance < LINK_TARGET_NEAR; + step = vector_normalized(vector_sub(npc.pos, isTargetNear ? dodge.targetPos : partner.pos)); + } + else if (npc.subtype != HEART_RIGHT_SIDE) + step.x = -1; + if (std::abs(std::abs(step.x) - std::abs(step.y)) < LINK_TIE) + { + if ((Random() & 1) == 0) step.x *= 0.5f; + else step.y *= 0.5f; + } + npc_push(npc, vector_scale(step, LINK_STEP_PUSH)); + + Room& room = *g_game->room; + Vector ahead = vector_add(npc.pos, vector_scale(step, LINK_SEARCH_AHEAD)); + float bestScore = LINK_SCORE_START; + Vector best{}; + for (float tries = 0; tries < LINK_SEARCH_TRIES - path.evadeDistance * LINK_SEARCH_TRY_COST; tries++) + { + float reach = random_unit() * LINK_SEARCH_RANGE + LINK_SEARCH_MIN; + float angle = random_unit() * RANDOM_HALF_TURN * 2; + Vector candidate = vector_make(std::cos(angle) * reach + ahead.x, std::sin(angle) * LINK_SEARCH_FLAT * reach + ahead.y); + int cell = room.GetGridIndex(candidate); + if (path.visitedGridIndices.contains(cell)) + { + tries -= LINK_SEARCH_REVISIT; + continue; + } + + path.visitedGridIndices.insert(cell); + Vector spot = room.GetGridPosition(cell); + float score = 0; + bool isOpen = room.GetGridCollision(room.GetGridIndex(spot)) == COLLISION_NONE && + room_check_line(npc.pos, spot, LINE_MODE_CELL, dodge.pathThreshold); + if (isOpen && spot_score(npc, dodge, spot, score) && bestScore < score) + { + best = spot; + bestScore = score; + } + if (vector_is_zero(best)) continue; + + path.movementTarget = best; + if (path.evadeDistance < LINK_EVADE_MAX) path.evadeDistance *= 0.5f; + } +} + +// Whether a linked heart's dodge spot is still worth going for: hidden from its target (or after a long dodge), well +// away from target and partner, and on its side. +static bool is_dodge_kept(Entity_NPC& npc, const LinkDodge& dodge) +{ + PathFinder& path = npc.pathfinder; + Vector spot = path.movementTarget; + bool isSeen = room_check_line(dodge.targetPos, spot, LINE_MODE_CELL, dodge.pathThreshold); + if (isSeen && path.evadeDistance < LINK_EVADE_MAX) return false; + if (vector_length_squared(vector_sub(dodge.targetPos, spot)) < LINK_SPOT_FAR) return false; + if (vector_length_squared(vector_sub(dodge.partnerSpot, spot)) < LINK_SPOT_PARTNER_FAR) return false; + return (spot.x - dodge.partnerSpot.x) * side_get(npc) <= 0; +} + +// A linked heart keeping its target between itself and its partner: it holds while placed well, else picks and +// heads for spots to dodge to. +static void pair_dodge(Entity_NPC& npc, Entity_NPC& partner, const Vector& targetPos) +{ + PathFinder& path = npc.pathfinder; + LinkDodge dodge = {.targetPos = targetPos, .partnerSpot = dodge_spot_get(partner), + .isCharmed = npc.HasEntityFlags(FLAG_CHARM)}; + float targetDistance = vector_length(vector_sub(targetPos, npc.pos)); + Vector start = dodge_spot_get(npc); + path.evadeDistance = std::min(path.evadeDistance, LINK_EVADE_MAX); + if (dodge.isCharmed || npc.forcedTarget) dodge.pathThreshold = HEART_PATH_MARKER; + + if (npc.IsFrame(LINK_CHECK_EVERY, (int)npc.index)) + { + bool isTargetAway = dodge.isCharmed ? targetDistance <= LINK_CHARMED_RANGE : targetDistance >= LINK_TARGET_RANGE; + float partnerGap = vector_length(vector_sub(dodge.partnerSpot, start)); + bool isPlaced = isTargetAway && partnerGap >= LINK_PARTNER_MIN && + (partnerGap <= LINK_PARTNER_MAX || (Random() & (LINK_PARTNER_FAR_ODDS - 1)) != 0) && + room_check_line(start, dodge.partnerSpot, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD) && + (npc.pos.x - partner.pos.x) * side_get(npc) <= LINK_SIDE_SLACK; + if (isPlaced) + path.evadeMovementCountdown -= npc_ticks_get(npc); + else + { + if (path.evadeMovementCountdown < 1) path.movementTarget = Vector{}; + path.evadeMovementCountdown = LINK_EVADE_FRAMES; + } + } + if (npc.IsFrame(LINK_FORGET_EVERY, (int)npc.index)) path.visitedGridIndices.clear(); + + if (path.evadeMovementCountdown < 1) + { + path.evadeBar = 0; + path.evadeDistance *= LINK_EVADE_DECAY; + path.MoveRandomly(STATUS_IGNORED); + npc.friction *= LINK_EVADE_DECAY; + return; + } + if (vector_is_zero(path.movementTarget) || path.evadeDistance > LINK_EVADE_MAX) dodge_pick(npc, partner, dodge); + if (vector_is_zero(path.movementTarget)) return; + + if (npc.IsFrame(LINK_RECHECK_EVERY, (int)npc.index) && !is_dodge_kept(npc, dodge)) path.movementTarget = Vector{}; + if (!vector_is_zero(path.movementTarget)) + path.FindGridPath(path.movementTarget, LINK_STEP_SPEED, 0, DIRECT_PATH_FAR); +} + +// A linked heart's beat: with a living partner it dodges about the target (or follows the partner's controller) and +// fires at its partner, else it chases the target. +static void linked_update(Entity_NPC& npc, const Vector& targetPos) +{ + Entity* partnerEntity = npc.entityRef; + if (!partnerEntity || !partnerEntity->IsEnemy()) + return npc.pathfinder.FindGridPath(targetPos, HEART_CHASE_SPEED, HEART_PATH_MARKER, DIRECT_PATH_FAR); + + auto& partner = static_cast(*partnerEntity); + if (npc.controllerID != -1) + npc.pathfinder.EvadeTarget(targetPos, STATUS_OBEYED); + else if (partner.controllerID == -1) + pair_dodge(npc, partner, targetPos); + else if (partner.IsControllerActionPressed(CONTROLLER_ACTION_HOLD)) + npc.friction *= 0.5f; + else + { + npc.controllerID = partner.controllerID; + npc.pathfinder.EvadeTarget(targetPos, STATUS_OBEYED); + npc.controllerID = -1; + } + if (npc.GetIntervalTicks(LINK_SHOT_EVERY, 0) == 0) return; + + ProjectileParams params; + params.bulletFlags = PROJECTILE_TRACTOR_BEAM; + params.scale = LINK_SHOT_SCALE; + params.fallingAccelModifier = LINK_SHOT_FALL; + Vector aim = vector_scale(vector_normalized(vector_sub(partner.pos, npc.pos)), LINK_SHOT_SPEED); + npc.FireProjectiles(npc.pos, aim, PROJECTILES_SINGLE, params); +} + +// Beating: it moves by its kind, then attacks every third frame within 100 of its target (a controlled one when its +// player shoots), a linked one only once its partner is gone. A Delirium form holds off once the room is clear. +static void beat_update(Entity_NPC& npc) +{ + npc.sprite.Play(npc.type == ENTITY_HEART ? "Heart" : "HeartBeat"); + Vector targetPos = npc.GetPlayerTarget()->pos; + bool isLinked = npc.type == ENTITY_HEART && npc.variant == HEART_LINKED; + if (isLinked) + linked_update(npc, targetPos); + else + npc.pathfinder.EvadeTarget(targetPos, STATUS_OBEYED); + npc.friction *= HEART_FRICTION; + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); + + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return; + bool isAttacking = npc.controllerID == -1 ? npc.IsFrame(HEART_ATTACK_EVERY, 0) + : input_is_action_pressed((ButtonAction)CONTROLLER_ACTION_ATTACK, + npc.controllerID, &npc); + if (!isAttacking || npc.HasEntityFlags(FLAG_DISTRACTED)) return; + if (isLinked && npc.entityRef) return; + if (isLinked && npc.projectileCooldown <= 0) + { + npc.state = HEART_ATTACK; + npc.stateFrame = 0; + npc.projectileCooldown = HEART_ATTACK_COOLDOWN; + return; + } + if (npc.controllerID != -1 || vector_length_squared(vector_sub(targetPos, npc.pos)) < HEART_ATTACK_REACH) + { + npc.state = HEART_ATTACK; + npc.stateFrame = 0; + } +} + +// Its burst: the Heart's cross (a plus for the linked one), the Heart of Infamy's eight or smart plus with two splats. +static void burst_fire(Entity_NPC& npc) +{ + if (npc.type != ENTITY_HEART_OF_INFAMY) + { + blood_explosion_spawn(HEART_BLOOD_SIZE, npc.pos, HEART_BLOOD_OFFSET, npc.splatColor, {}); + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + ProjectileParams params; + npc.FireProjectiles(npc.pos, vector_make(HEART_SHOT_SPEED, 0), + npc.variant == HEART_LINKED ? PROJECTILES_CROSS : PROJECTILES_PLUS, params); + return; + } + + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + if (npc.subtype == 1) + { + ProjectileParams params; + params.bulletFlags |= PROJECTILE_SMART; + Entity* blood = blood_explosion_spawn(HEART_INFAMY_BLOOD_SIZE, npc.pos, HEART_BLOOD_OFFSET, npc.splatColor, {}); + blood->SetColor(HEART_INFAMY_BURST_COLOR, -1, HEART_COLOR_PRIORITY, false, true); + npc.FireProjectiles(npc.pos, vector_make(HEART_INFAMY_SMART_SPEED, 0), PROJECTILES_PLUS, params); + } + else + { + blood_explosion_spawn(HEART_INFAMY_BLOOD_SIZE, npc.pos, HEART_BLOOD_OFFSET, npc.splatColor, {}); + ProjectileParams params; + npc.FireProjectiles(npc.pos, vector_make(HEART_SHOT_SPEED, 0), PROJECTILES_EIGHT, params); + } + npc.MakeSplat(random_unit() + HEART_SPLAT_MIN); + Entity_Effect* splat = npc.MakeSplat(random_unit() * HEART_SPLAT_SECOND_RANGE + HEART_SPLAT_MIN); + float yTurn = random_unit() * PI_F; + float xTurn = random_unit() * PI_F; + splat->pos = vector_make(std::cos(xTurn + xTurn) * HEART_SPLAT_SPREAD + npc.pos.x, + std::sin(yTurn + yTurn) * HEART_SPLAT_SPREAD + HEART_SPLAT_DROP + npc.pos.y); +} + +// Passes a dying controlled heart's player on to its partner (or the Mask it keeps), the player's NPC target +// following. +static void control_pass(Entity_NPC& npc) +{ + auto* partner = static_cast(npc.entityRef.get()); + bool isPartnerFree = partner && partner->IsEnemy() && !partner->isDead && partner->controllerID == -1; + Entity_NPC* heir = isPartnerFree ? partner : nullptr; + if (!heir) + { + auto* mask = static_cast(npc.child.get()); + bool isMaskFree = mask && mask->type == ENTITY_MASK_OF_INFAMY && !mask->isDead && mask->controllerID == -1; + heir = isMaskFree ? mask : nullptr; + } + if (!heir || heir == &npc) return; + + for (Entity_Player* player : g_game->playerManager.extraPlayers) + if (player->controllerIndex == npc.controllerID && player->target.get() == &npc) player->target = heir; + heir->controllerID = npc.controllerID; + npc.controllerID = -1; +} + +// 0051f2f0 The Heart's and Heart of Infamy's AI: beating away from its target and bursting near it, the linked Hearts +// dodging in pairs about their target. +void npc_heart_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + heart_link(npc); + npc.state = NPC_STATE_MOVE; + return; + } + if (npc.state == NPC_STATE_MOVE) + beat_update(npc); + else + { + npc.friction *= HEART_ATTACK_FRICTION; + npc.sprite.Play("HeartAttack"); + if (npc.controllerID != -1) + npc.pathfinder.FindGridPath(Vector{}, HEART_CONTROLLED_SPEED, 0, DIRECT_PATH_FAR); + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) burst_fire(npc); + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; + npc.stateFrame++; + } + if (!npc.isDead) return; + + if (npc.controllerID != -1) control_pass(npc); + if (npc.spawnerType == ENTITY_CHUB && npc.parent) + { + npc.PlaySound(SOUND_MONSTER_ROAR_2, QUEEN_HEART_VOLUME, 2, false, 1); + npc.parent->TakeDamage(QUEEN_HEART_DAMAGE, 0, EntityRef(&npc), QUEEN_HEART_COUNTDOWN); + } +} diff --git a/src/npc_henry.cpp b/src/npc_henry.cpp new file mode 100644 index 0000000..0541d68 --- /dev/null +++ b/src/npc_henry.cpp @@ -0,0 +1,51 @@ +#include "npc_alt.h" +#include "entity_effect.h" +#include "room.h" + +// Henry peeks out of the nearest pit for 30 frames, claiming it, then flushes away, rippling every 4 frames. +constexpr int HENRY_PIT_CLAIM = 5; +constexpr int HENRY_PEEK_FRAMES = 30; +constexpr float HENRY_RIPPLE_EVERY = 4; +constexpr float HENRY_CELL = 40; +constexpr float HENRY_LEFT = 40; +constexpr float HENRY_TOP = 120; + +// Henry's states: peeking and leaving. +constexpr int HENRY_PEEKING = NPC_STATE_IDLE; +constexpr int HENRY_LEAVING = NPC_STATE_ATTACK; + +// 00565bc0 Henry's AI: a face that pops out of a pit, looks about and flushes away. +void npc_henry_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + int pit = Entity_NPC::FindTargetPit(npc.pos, npc.pos, UINT32_MAX); + // The original goes on placing a Henry without a pit after removing it, which changes nothing. + if (pit < 0) return npc.Remove(); + Room& room = *g_game->room; + if (pit < ROOM_GRID_CELLS) room.gridPaths[pit] = HENRY_PIT_CLAIM; + npc.pos = vector_make((float)(pit % room.gridWidth) * HENRY_CELL + HENRY_LEFT, + (float)(pit / room.gridWidth) * HENRY_CELL + HENRY_TOP); + npc.targetPosition = npc.pos; + npc.state = HENRY_PEEKING; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + } + else if (npc.state == HENRY_PEEKING) + { + npc.sprite.Play("Idle"); + npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame > HENRY_PEEK_FRAMES) + { + npc_sound_play(SOUND_FLUSH, 1, 2, 1); + npc.sprite.Play("Leave"); + npc.state = HENRY_LEAVING; + } + } + else if (npc.state == HENRY_LEAVING) + { + if (npc.GetIntervalTicks(HENRY_RIPPLE_EVERY, 0)) + spawn_at(ENTITY_EFFECT, EFFECT_WATER_RIPPLE, 0, npc.pos, nullptr)->Update(); + if (!npc.sprite.IsPlaying()) npc.Remove(); + } + npc.velocity = vector_sub(npc.targetPosition, npc.pos); +} diff --git a/src/npc_maggot.cpp b/src/npc_maggot.cpp index bfd2dff..499aae6 100644 --- a/src/npc_maggot.cpp +++ b/src/npc_maggot.cpp @@ -79,6 +79,13 @@ constexpr float DROWNED_CHARGE_SCALE = 0.9f; constexpr float DANK_CHARGE_SCALE = 14; constexpr int MAGGOT_CHARGE_SOUND_DELAY = 20; +// The Carrion Princess charges along a diagonal: at a target within 20 of one of its cell's diagonal lanes (20 to +// either side of its cell's middle) in a clear line to 10 short of it, kept on that lane. +constexpr float CARRION_TURN = 45; +constexpr float CARRION_LANE_WIDTH = 20; +constexpr float CARRION_LANE_SIDE = 20; +constexpr float CARRION_END_SHORT = 10; + // A charge stops at the grid or a status, when it stalls for five frames (moving less than its speed's root of two), // or when it slows to a crawl while slowed. constexpr float CHARGE_STALL_SQUARED = 2; @@ -417,6 +424,52 @@ static void maggot_rest_update(Entity_NPC& npc) // Starts a charge at its target (or its controller's push): in line with one of its axes, close and in a clear line // from its cell, it screams and dashes along that axis. The dank one shows its alert first. +// The nearer of the two diagonal lanes through a cell, 20 to either side of its middle, across a charge. +static Vector carrion_lane_get(Vector position, Vector cell, Vector across) +{ + Vector left = vector_make(cell.x - CARRION_LANE_SIDE, cell.y); + Vector right = vector_make(cell.x + CARRION_LANE_SIDE, cell.y); + float leftOffset = vector_dot(vector_sub(position, left), across); + float rightOffset = vector_dot(vector_sub(position, right), across); + return std::abs(rightOffset) <= std::abs(leftOffset) ? right : left; +} + +// The Carrion Princess's charge along the diagonal its target lies on, from its lane in a clear line to the target. +static void carrion_charge_try(Entity_NPC& npc, Vector cell, Vector spot, Vector delta) +{ + Vector turned = vector_rotated(delta, CARRION_TURN); + bool isOnDiagonal = std::abs(turned.x) < CARRION_LANE_WIDTH || std::abs(turned.y) < CARRION_LANE_WIDTH; + if (!isOnDiagonal || npc.HasEntityFlags(FLAG_DISTRACTED)) return; + + Vector direction = vector_rotated(vector_cardinal(turned), -CARRION_TURN); + Vector across = vector_rotated(direction, RIGHT_ANGLE_DEGREES); + Vector lane = carrion_lane_get(npc.pos, cell, across); + Vector start = vector_sub(npc.pos, vector_scale(across, vector_dot(vector_sub(npc.pos, lane), across))); + Vector end = vector_sub(vector_sub(spot, vector_scale(across, vector_dot(vector_sub(spot, lane), across))), + vector_scale(direction, CARRION_END_SHORT)); + if (npc.controllerID == -1 && !room_check_line(start, end, LINE_MODE_CELL, 0)) return; + + npc.PlaySound(SOUND_MAGGOTCHARGE, 1, MAGGOT_CHARGE_SOUND_DELAY, false, 1); + npc.v1 = vector_scale(direction, MAGGOT_CHARGE_SPEED); + npc.state = NPC_STATE_ATTACK; + npc.stateFrame = 0; + npc.v2 = npc.pos; + npc.pathfinder.gridPathTarget = npc.pos; + npc.pathfinder.moveCountdown = 0; +} + +// The Carrion Princess's charge: facing up or down its diagonal, kept on its lane. +static void carrion_charge_steer(Entity_NPC& npc, Vector cell) +{ + npc.sprite.Play(npc.v1.y >= 0 ? "Attack Down" : "Attack Up"); + npc.sprite.isFlipX = npc.v1.x < 0; + Vector across = vector_normalized(vector_rotated(npc.v1, RIGHT_ANGLE_DEGREES)); + float offset = vector_dot(vector_sub(npc.pos, carrion_lane_get(npc.pos, cell, across)), across); + float drift = vector_dot(npc.velocity, across); + float keep = 1 - timescale_factor(CHARGE_ALIGN_FRICTION, npc.speedMultiplier); + npc.velocity = vector_sub(npc.velocity, vector_scale(across, (offset + drift) * keep)); +} + static void maggot_charge_try(Entity_NPC& npc, MaggotFrame& frame) { Room& room = *g_game->room; @@ -431,6 +484,7 @@ static void maggot_charge_try(Entity_NPC& npc, MaggotFrame& frame) bool isControlled = npc.controllerID != -1; Vector delta = vector_sub(spot, cell); if (isControlled) delta = vector_scale(npc.GetControllerInput(0), CHARGE_INPUT_SCALE); + if (npc.type == ENTITY_CHARGER && npc.variant == CHARGER_CARRION) return carrion_charge_try(npc, cell, spot, delta); if (npc.HasEntityFlags(FLAG_DISTRACTED) || frame.isClimbing) return; if (!isControlled) { @@ -602,6 +656,7 @@ static void maggot_charge_update(Entity_NPC& npc, MaggotFrame& frame) npc.AddVelocity_divided(npc.v1, false); Vector cell = g_game->room->GetGridPosition(frame.cell); if (npc.controllerID != -1) cell = npc.v2; + if (npc.type == ENTITY_CHARGER && npc.variant == CHARGER_CARRION) return carrion_charge_steer(npc, cell); if (npc.type != ENTITY_GURGLING) { float keep = 1 - timescale_factor(CHARGE_ALIGN_FRICTION, npc.speedMultiplier); @@ -784,7 +839,8 @@ static void shadow_spread(Entity_NPC& npc) npc.velocity.y += npc.speedMultiplier * total.y; } -// The forward vector other code reads: the Gurgling's down, the others' facing. +// The forward vector other code reads: the Gurgling's down, a charging Carrion Princess's diagonal, the others' +// facing. static void maggot_forward_set(Entity_NPC& npc, int facing) { if (npc.type == ENTITY_GURGLING) @@ -792,6 +848,11 @@ static void maggot_forward_set(Entity_NPC& npc, int facing) npc.forwardVector = vector_make(0, 1); return; } + if (npc.type == ENTITY_CHARGER && npc.variant == CHARGER_CARRION && npc.state == NPC_STATE_ATTACK) + { + npc.forwardVector = vector_normalized(npc.v1); + return; + } int direction = facing == FACING_UP ? DIRECTION_UP : facing == FACING_DOWN ? DIRECTION_DOWN : (npc.sprite.isFlipX ? DIRECTION_LEFT : DIRECTION_RIGHT); @@ -803,8 +864,6 @@ static void maggot_forward_set(Entity_NPC& npc, int facing) // the drowned one and the Leeches burst as they die, and the Gurglings leave trails and summon. void npc_maggot_update(Entity_NPC& npc) { - if (npc.type == ENTITY_CHARGER && npc.variant == CHARGER_CARRION) - reconstruction_missing("NpcAI::ENTITY_MAGGOT 0052db50: the Carrion Princess's diagonal charge"); bool isShadow = npc.type == ENTITY_CHARGER && npc.variant == 0 && npc.subtype == MY_SHADOW_SUBTYPE; if (npc.type == ENTITY_LEECH && npc.variant != 0 && npc.IsControllerActionPressed(CONTROLLER_ACTION_BURST)) npc.Kill(EntityRef()); diff --git a/src/npc_mama_fly.cpp b/src/npc_mama_fly.cpp index 6deaf84..aa6c4e5 100644 --- a/src/npc_mama_fly.cpp +++ b/src/npc_mama_fly.cpp @@ -36,6 +36,15 @@ constexpr float MAGGOT_JUMP_SHARE = 0.04f; constexpr uint32_t MAGGOT_CRAWL_FRAMES = 30; constexpr int MAGGOT_CRAWL_MIN = 10; +// A small maggot's crawl after it lands: along its leap, for 10 to 39 frames of its own seed. +static Entity_NPC* small_maggot_crawl_set(Entity_NPC& maggot) +{ + maggot.pathfinder.movementTarget = vector_normalized(maggot.velocity); + RNG crawl = {maggot.initSeed, 5, 9, 7}; + maggot.pathfinder.moveCountdown = (int)crawl.RandomInt(MAGGOT_CRAWL_FRAMES) + MAGGOT_CRAWL_MIN; + return &maggot; +} + // 004d8910 spawn_small_maggot_jump: a small maggot leaping from a position, a height up, onto a spot it keeps clear. Entity_NPC* small_maggot_jump_spawn(const Vector& position, float height, const Vector& spot) { @@ -52,11 +61,30 @@ Entity_NPC* small_maggot_jump_spawn(const Vector& position, float height, const maggot->velocity = maggot->targetPosition; maggot->posOffset.y = height; maggot->Update(); + return small_maggot_crawl_set(*maggot); +} - maggot->pathfinder.movementTarget = vector_normalized(maggot->velocity); - RNG crawl = {maggot->initSeed, 5, 9, 7}; - maggot->pathfinder.moveCountdown = (int)crawl.RandomInt(MAGGOT_CRAWL_FRAMES) + MAGGOT_CRAWL_MIN; - return maggot; +// 004d8b50 spawn_small_maggot: a small maggot thrown from a position, a height up, at a velocity and rise. In a +// crawlspace the height and rise move it instead. +Entity_NPC* small_maggot_spawn(const Vector& position, float height, const Vector& velocity, float rise) +{ + auto* maggot = + static_cast(g_game->Spawn({.position = position, .type = ENTITY_SMALL_MAGGOT, .seed = Random()})); + maggot->ClearEntityFlags(FLAG_APPEAR); + maggot->v1.x = rise; + maggot->targetPosition = velocity; + maggot->velocity = velocity; + maggot->state = NPC_STATE_SPECIAL; + maggot->i1 = 1; + if (g_game->room->roomType == ROOM_DUNGEON) + { + maggot->pos.y += height; + maggot->velocity.y += rise; + } + else + maggot->posOffset.y = height; + maggot->Update(); + return small_maggot_crawl_set(*maggot); } // A new spot to lay on: the free cell farthest from its target among 10 tries 80 to 200 away, kept off landing kin. diff --git a/src/npc_maze_roamer.cpp b/src/npc_maze_roamer.cpp new file mode 100644 index 0000000..7db2929 --- /dev/null +++ b/src/npc_maze_roamer.cpp @@ -0,0 +1,227 @@ +#include "npc_gehenna.h" +#include "entity_player.h" +#include "game.h" +#include "room.h" +#include + +// The Maze Roamer walks the room's grid axis aligned with a twin spawned mirrored through the room's center, which +// walks opposite it. Either one seeing its target down a row or column within 200 shoots it an eye, and the twin +// shoots back the other way. Once one twin dies the other turns red and chases its target alone. +constexpr int MAZE_ROAMER_TWIN = 1; +constexpr int MAZE_ROAMER_ALONE = NPC_STATE_IDLE; +constexpr int MAZE_ROAMER_PAIRED = NPC_STATE_MOVE; +constexpr int MAZE_ROAMER_SHOOT = NPC_STATE_ATTACK; +constexpr int MAZE_ROAMER_ALONE_SHOOT = NPC_STATE_ATTACK2; +constexpr int MAZE_ROAMER_TURNING = NPC_STATE_SPECIAL; + +constexpr std::array MAZE_WALK_ANIMS = {"WalkLeft", "WalkUp", "WalkRight", "WalkDown"}; +constexpr std::array MAZE_ATTACK_ANIMS = {"AttackLeft", "AttackUp", "AttackRight", "AttackDown"}; +constexpr std::array MAZE_WALK_ALONE_ANIMS = {"WalkLeft2", "WalkUp2", "WalkRight2", "WalkDown2"}; +constexpr std::array MAZE_ATTACK_ALONE_ANIMS = {"AttackLeft2", "AttackUp2", "AttackRight2", + "AttackDown2"}; + +constexpr int MAZE_ROAMER_PATH_MARKER = 900; +constexpr float MAZE_ROAMER_SPEED = 1.25f; +constexpr float MAZE_ROAMER_CHASE_SPEED = 1; +constexpr float MAZE_ROAMER_WALK_FRICTION = 0.8f; +constexpr float MAZE_ROAMER_SHOOT_FRICTION = 0.3f; +constexpr int MAZE_ROAMER_ROAR_EVERY = 30; +constexpr int MAZE_ROAMER_ROAR_ODDS = 3; +constexpr float MAZE_ROAMER_ROAR_VOLUME = 0.8f; +constexpr int MAZE_ROAMER_ROAR_DELAY = 120; + +// It looks for its target every third frame, aiming a little ahead of it, within 200 and less than half a cell off +// its row or column. +constexpr int MAZE_ROAMER_LOOK_EVERY = 3; +constexpr float MAZE_ROAMER_LEAD_FRAMES = 16; +constexpr float MAZE_ROAMER_ROOM_MARGIN = 20; +constexpr float MAZE_ROAMER_ALIGN = 20; +constexpr float MAZE_ROAMER_SIGHT = 200; +constexpr float MAZE_ROAMER_SHOT_SPEED = 10; + +// A twin faces the way opposite its partner's. +static int direction_opposite(int direction) +{ + return (direction + 2) % 4; +} + +// Faces its walk: the direction it moves in, or still facing down when it barely moves. +static void walk_face(Entity_NPC& npc, const std::array& anims) +{ + if (vector_length_squared(npc.velocity) < 1) + { + npc.i1 = -1; + npc.sprite.SetFrame(anims[3], 0); + return; + } + npc.i1 = vector_to_direction(npc.velocity); + npc.sprite.Play(anims[npc.i1]); +} + +// Where its target will be in a moment, kept inside the room, when that lines up with its own cell and lies in clear +// sight within 200. Nothing when it cannot attack or there is no such spot. +static bool is_target_spotted(Entity_NPC& npc, Vector& spot) +{ + if (!npc.IsFrame(MAZE_ROAMER_LOOK_EVERY, (int)npc.index) || npc.HasEntityFlags(FLAG_DISTRACTED)) return false; + if (npc.HasEntityFlags(FLAG_FRIENDLY) && npc.GetPlayerTarget()->type == ENTITY_PLAYER) return false; + + Room& room = *g_game->room; + Entity* target = npc.GetPlayerTarget(); + Vector lead = vector_add(target->pos, vector_scale(target->velocity, random_unit() * MAZE_ROAMER_LEAD_FRAMES)); + spot = room.GetClampedPositionImpl(lead, MAZE_ROAMER_ROOM_MARGIN, MAZE_ROAMER_ROOM_MARGIN, MAZE_ROAMER_ROOM_MARGIN, + MAZE_ROAMER_ROOM_MARGIN); + Vector cell = room.GetGridPosition(npc.pathfinder.gridIndex); + Vector offset = vector_sub(cell, spot); + bool isAligned = std::abs(offset.x) < MAZE_ROAMER_ALIGN || std::abs(offset.y) < MAZE_ROAMER_ALIGN; + return isAligned && vector_length(offset) < MAZE_ROAMER_SIGHT && + room_check_line(cell, spot, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD); +} + +// Its eye shot at 10 along an aim: its controller's, or toward its target. +static Vector shot_aim(Entity_NPC& npc) +{ + bool isSteered = npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement); + Vector aim = isSteered ? npc.controllerMovement : vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + return vector_resized(aim, MAZE_ROAMER_SHOT_SPEED); +} + +static void eye_shoot(Entity_NPC& npc, const Vector& velocity) +{ + ProjectileParams params; + params.variant = PROJECTILE_PEEP; + npc.PlaySound(SOUND_PING_PONG, 1, 2, false, 1); + npc.FireProjectiles(npc.pos, velocity, PROJECTILES_SINGLE, params); +} + +// The first frame: a Maze Roamer placed in the room (or by an ambush) brings its twin, mirrored through the room's +// center. +static void twin_spawn(Entity_NPC& npc) +{ + npc.flags |= FLAG_NO_BLOOD_SPLASH; + npc.state = MAZE_ROAMER_PAIRED; + bool isPlaced = npc.spawnGridIndex >= 0 || npc.HasEntityFlags(FLAG_AMBUSH); + if (!isPlaced || npc.subtype != 0) return; + + Vector center = Room::GetCenterPos(); + Vector mirrored = vector_sub(vector_scale(center, 2), npc.pos); + auto* twin = static_cast(g_game->Spawn({.position = mirrored, + .spawner = &npc, + .subType = MAZE_ROAMER_TWIN, + .type = ENTITY_MAZE_ROAMER, + .seed = npc.initSeed})); + twin->Morph(npc.type, npc.variant, MAZE_ROAMER_TWIN, npc.championColorIdx); + if (npc.HasEntityFlags(FLAG_AMBUSH)) twin->flags |= FLAG_AMBUSH; + twin->Update(); + npc.child = twin; + twin->parent = &npc; +} + +// Walking with its twin: the first wanders the grid, the twin mirrors it through the room's center. Spotting the +// target makes both shoot, the twin back the other way. +static void paired_walk(Entity_NPC& npc) +{ + if (!npc.child && !npc.parent) + { + npc.sprite.Play("Transition"); + npc.state = MAZE_ROAMER_TURNING; + return; + } + + Room& room = *g_game->room; + if (npc.subtype == 0) + { + if (npc.IsFrame(MAZE_ROAMER_ROAR_EVERY, (int)npc.index) && Random() % MAZE_ROAMER_ROAR_ODDS == 0) + npc.PlaySound(SOUND_MONSTER_ROAR_1, MAZE_ROAMER_ROAR_VOLUME, MAZE_ROAMER_ROAR_DELAY, false, 1); + room_path_mark(room, room.GetGridIndex(npc.pos), MAZE_ROAMER_PATH_MARKER); + npc.pathfinder.UpdateGridIndex(); + npc.pathfinder.MoveRandomlyAxisAligned(MAZE_ROAMER_SPEED, STATUS_OBEYED); + npc.friction *= MAZE_ROAMER_WALK_FRICTION; + walk_face(npc, MAZE_WALK_ANIMS); + } + else + { + Vector center = Room::GetCenterPos(); + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.velocity = vector_sub(vector_sub(vector_scale(center, 2), npc.parent->pos), npc.pos); + room_path_mark(room, room.GetGridIndex(npc.pos), MAZE_ROAMER_PATH_MARKER); + npc.pathfinder.UpdateGridIndex(); + npc.i1 = npc.ParentNPC()->i1; + if (npc.i1 == -1) + npc.sprite.SetFrame("WalkDown", 0); + else + npc.sprite.Play(MAZE_WALK_ANIMS[direction_opposite(npc.i1)]); + } + + Vector spot; + if (!is_target_spotted(npc, spot)) return; + + npc.state = MAZE_ROAMER_SHOOT; + npc.stateFrame = 0; + npc.i1 = vector_to_direction(vector_sub(spot, npc.pos)); + npc.sprite.Play(MAZE_ATTACK_ANIMS[npc.i1]); + npc.i2 = 0; + Entity_NPC* partner = npc.ChildNPC() ? npc.ChildNPC() : npc.ParentNPC(); + if (!partner) return; + + partner->state = MAZE_ROAMER_SHOOT; + partner->stateFrame = 0; + partner->i1 = npc.i1; + partner->i2 = 1; + partner->sprite.Play(MAZE_ATTACK_ANIMS[direction_opposite(npc.i1)]); +} + +// Chasing alone: it marks its way through the grid toward its target, and shoots it when spotted. +static void alone_walk(Entity_NPC& npc) +{ + room_path_raise_at(npc.pos, MAZE_ROAMER_PATH_MARKER); + npc.pathfinder.FindGridPath(npc.GetPlayerTarget()->pos, MAZE_ROAMER_CHASE_SPEED, MAZE_ROAMER_PATH_MARKER, + DIRECT_PATH_FAR); + walk_face(npc, MAZE_WALK_ALONE_ANIMS); + + Vector spot; + if (!is_target_spotted(npc, spot)) return; + + npc.state = MAZE_ROAMER_ALONE_SHOOT; + npc.stateFrame = 0; + npc.i1 = vector_to_direction(vector_sub(spot, npc.pos)); + npc.sprite.Play(MAZE_ATTACK_ALONE_ANIMS[npc.i1]); +} + +// Shooting: the one that spotted the target shoots at it, its twin (i2 set) the opposite way of its partner's aim. +static void shoot_update(Entity_NPC& npc, int nextState) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + Entity_NPC* partner = npc.ParentNPC() ? npc.ParentNPC() : npc.ChildNPC(); + bool isMirrored = nextState == MAZE_ROAMER_PAIRED && npc.i2 != 0 && partner; + eye_shoot(npc, isMirrored ? vector_scale(shot_aim(*partner), -1) : shot_aim(npc)); + } + if (npc_anim_is_done(npc)) npc.state = nextState; + npc.friction *= MAZE_ROAMER_SHOOT_FRICTION; +} + +// 004f1ec0 The Maze Roamer's AI: a pair walking the grid mirrored through the room's center and shooting eyes along +// rows and columns, then the survivor chasing alone. +void npc_maze_roamer_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + return twin_spawn(npc); + case MAZE_ROAMER_ALONE: + return alone_walk(npc); + case MAZE_ROAMER_PAIRED: + return paired_walk(npc); + case MAZE_ROAMER_SHOOT: + return shoot_update(npc, MAZE_ROAMER_PAIRED); + case MAZE_ROAMER_ALONE_SHOOT: + return shoot_update(npc, MAZE_ROAMER_ALONE); + case MAZE_ROAMER_TURNING: + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.friction *= MAZE_ROAMER_WALK_FRICTION; + if (npc_anim_is_done(npc)) npc.state = MAZE_ROAMER_ALONE; + return; + default: + return; + } +} diff --git a/src/npc_membrain.cpp b/src/npc_membrain.cpp index 0ebf831..785940f 100644 --- a/src/npc_membrain.cpp +++ b/src/npc_membrain.cpp @@ -1,10 +1,10 @@ #include "npc_depths.h" #include "boss_ai.h" +#include "npc_ai.h" #include "sfx_manager.h" // The Membrain, Mama Guts and Dead Meat (which splits into Cysts), and the Dinga, which splits into Squirts. constexpr int MEMBRAIN_DEAD_MEAT = 2; -constexpr ColorMod DINGA_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.25490198f, 0.16078432f, 0.13725491f}}; // They wander, and one time in 30 (with under 8 enemies about) stop to burst: a ring of 8 shots at 10 (Dead Meat's // ring of 8 bouncing, wall crossing ones at 8), the Dinga 2 Dips 30 apart instead (with under 6 enemies about, six @@ -147,7 +147,7 @@ void npc_membrain_update(Entity_NPC& npc) if (npc.state == NPC_STATE_INIT) { npc.state = NPC_STATE_MOVE; - if (npc.type == ENTITY_DINGA) npc.splatColor = DINGA_SPLAT; + if (npc.type == ENTITY_DINGA) npc.splatColor = POOP_SPLAT_COLOR; else if (npc.type == ENTITY_MEMBRAIN && npc.variant == MEMBRAIN_DEAD_MEAT) npc.splatColor = COLOR_GREEN_SPLAT; return; } diff --git a/src/npc_mockulus.cpp b/src/npc_mockulus.cpp new file mode 100644 index 0000000..8ce40fa --- /dev/null +++ b/src/npc_mockulus.cpp @@ -0,0 +1,113 @@ +#include "npc_gehenna.h" +#include "boss_ai.h" +#include "entity_player.h" + +// The Mockulus is an invulnerable eye that keeps shut while no player shoots. Once one does it opens and slides +// diagonally, bouncing off the walls, until the shooting stops and it shuts again. Its pupil (layer 2) watches the +// nearest player. It dies once the room's plates are pressed or the rest are dead. +constexpr int MOCKULUS_SHUT = NPC_STATE_IDLE; +constexpr int MOCKULUS_OPEN = NPC_STATE_MOVE; +constexpr int MOCKULUS_PUPIL_LAYER = 2; +constexpr float MOCKULUS_PUPIL_REACH = 4; +constexpr float MOCKULUS_PUPIL_SPEED = 3; +constexpr int MOCKULUS_TOGGLE_HOLD = 10; +constexpr float MOCKULUS_SHUT_FRICTION = 0.8f; +constexpr float MOCKULUS_OPEN_FRICTION = 0.9f; +constexpr int MOCKULUS_SPLAT_ODDS = 4; +constexpr float MOCKULUS_SPLAT_MIN = 0.3f; +constexpr float MOCKULUS_SPLAT_RANGE = 0.3f; +constexpr int MOCKULUS_CLEAR_DELAY = 8; +constexpr float MOCKULUS_NO_PLAYER = 100000; + +// Eases its pupil toward the nearest player (to the middle with none), 3 a frame at most. +static void pupil_update(Entity_NPC& npc, Entity_Player* nearest) +{ + Vector goal{}; + if (nearest) goal = vector_scale(vector_normalized(vector_sub(nearest->pos, npc.pos)), MOCKULUS_PUPIL_REACH); + LayerState& pupil = *npc.sprite.GetLayer(MOCKULUS_PUPIL_LAYER); + if (pupil.pos.x == goal.x && pupil.pos.y == goal.y) return; + + float maxStep = npc.speedMultiplier * MOCKULUS_PUPIL_SPEED; + Vector step = vector_sub(goal, pupil.pos); + float length = vector_length(step); + if (maxStep < length) step = vector_scale(step, maxStep / length); + pupil.pos = vector_add(step, pupil.pos); +} + +// Open: it bleeds a little and pushes on diagonally, shutting once no one shoots and its hold ran out. +static void open_update(Entity_NPC& npc, bool isAnyShooting) +{ + npc.friction *= MOCKULUS_OPEN_FRICTION; + if (npc_anim_is_done(npc)) npc_anim_loop(npc.sprite, "Idle"); + if ((Random() & (MOCKULUS_SPLAT_ODDS - 1)) == 0) npc.MakeSplat(random_unit() * MOCKULUS_SPLAT_RANGE + MOCKULUS_SPLAT_MIN); + + Vector sign = vector_make(npc.velocity.x < 0 ? -1 : 1, npc.velocity.y < 0 ? -1 : 1); + if (npc.friction != 0) + { + npc.velocity.y += npc.speedMultiplier * sign.y / npc.friction; + npc.velocity.x += npc.speedMultiplier * sign.x / npc.friction; + } + npc.v2 = sign; + if (npc.i1 > 0 || isAnyShooting) return; + + npc_anim_loop(npc.sprite, "Close"); + npc.state = MOCKULUS_SHUT; + npc.i1 = MOCKULUS_TOGGLE_HOLD; +} + +// Shut: it waits, opening when a player shoots and setting off the way it last went. +static void shut_update(Entity_NPC& npc, bool isAnyShooting) +{ + npc.friction *= MOCKULUS_SHUT_FRICTION; + if (npc_anim_is_done(npc)) npc_anim_loop(npc.sprite, "CloseIdle"); + if (!isAnyShooting) return; + + npc_anim_loop(npc.sprite, "Open"); + npc.state = MOCKULUS_OPEN; + npc.i1 = MOCKULUS_TOGGLE_HOLD; + npc.velocity = vector_add(npc.velocity, npc.v2); +} + +// 004f76f0 The Mockulus' AI: a shut eye that opens and slides about while a player shoots, watching the nearest one, +// and dies once the room is cleared. +void npc_mockulus_update(Entity_NPC& npc) +{ + bool isCleared = room_plates_is_triggered() || + (npc.GetAliveEnemyCount() <= 0 && g_game->room->roomClearDelay <= MOCKULUS_CLEAR_DELAY); + bool isAnyShooting = false; + float nearestDistance = MOCKULUS_NO_PLAYER; + Entity_Player* nearest = nullptr; + for (Entity_Player* player : g_game->playerManager.playerList) + { + float distance = vector_length_squared(vector_sub(npc.pos, player->pos)); + if (player->fireDirection != DIRECTION_NONE) isAnyShooting = true; + if (distance < nearestDistance) + { + nearestDistance = distance; + nearest = player; + } + } + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.flags |= FLAG_NO_STATUS_EFFECTS | FLAG_HIDE_HP_BAR; + npc.isInvincible = true; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.state = MOCKULUS_SHUT; + npc_anim_loop(npc.sprite, "CloseIdle"); + break; + case MOCKULUS_SHUT: + shut_update(npc, isAnyShooting); + break; + case MOCKULUS_OPEN: + open_update(npc, isAnyShooting); + break; + default: + break; + } + + pupil_update(npc, nearest); + if (npc.i1 > 0) npc.i1 -= npc_ticks_get(npc); + if (isCleared) npc.Kill(EntityRef{}); +} diff --git a/src/npc_morningstar.cpp b/src/npc_morningstar.cpp new file mode 100644 index 0000000..749262e --- /dev/null +++ b/src/npc_morningstar.cpp @@ -0,0 +1,84 @@ +#include "npc_gehenna.h" +#include "boss_ai.h" +#include "entity_player.h" + +// The Morningstar sleeps while no player walks. Woken by one moving, it creeps toward its target and, once its swing +// gets going, speeds up to 2 by 0.01 a frame, groaning now and then when it has a straight line at its target. +constexpr int MORNINGSTAR_SLEEPING = NPC_STATE_IDLE; +constexpr int MORNINGSTAR_AWAKE = NPC_STATE_MOVE; +constexpr int MORNINGSTAR_KINDS = 2; +constexpr int MORNINGSTAR_TOGGLE_HOLD = 10; +constexpr float MORNINGSTAR_FRICTION = 0.8f; +constexpr int MORNINGSTAR_PATH_MARKER = 900; +constexpr float MORNINGSTAR_CREEP_SPEED = 0.3f; +constexpr float MORNINGSTAR_WAKE_SPEED = 0.7f; +constexpr float MORNINGSTAR_SPEED_GAIN = 0.01f; +constexpr float MORNINGSTAR_SPEED_MAX = 2; +constexpr int MORNINGSTAR_GROAN_ODDS = 3; +constexpr int MORNINGSTAR_GROAN_DELAY = 60; + +// Awake: it paths at its target, slowly until its swing starts, then faster each frame. It groans, and falls back +// asleep once no one walks and its hold ran out. +static void awake_update(Entity_NPC& npc, bool isAnyMoving) +{ + if (npc_anim_is_done(npc)) npc_anim_loop(npc.sprite, "Move"); + + const AnimationData* anim = npc.sprite.animState.animData; + bool isSwinging = anim && (npc.sprite.WasEventTriggered("Shoot") || anim->isLooping); + if (!isSwinging) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), MORNINGSTAR_CREEP_SPEED, MORNINGSTAR_PATH_MARKER, + DIRECT_PATH_FAR); + else + { + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), npc.v1.x, MORNINGSTAR_PATH_MARKER, DIRECT_PATH_FAR); + npc.v1.x = std::min(npc.speedMultiplier * MORNINGSTAR_SPEED_GAIN + npc.v1.x, MORNINGSTAR_SPEED_MAX); + } + + bool isGroaning = npc.controllerID == -1 + ? npc.IsHostileTo(npc.GetPlayerTarget()) && npc.pathfinder.hasDirectPath && + Random() % MORNINGSTAR_GROAN_ODDS == 0 + : npc.IsControllerActionTriggered(CONTROLLER_ACTION_GROAN); + if (isGroaning) npc_sound_play(SOUND_MONSTER_ROAR_1, 1, MORNINGSTAR_GROAN_DELAY, champion_pitch_get(npc)); + if (npc.i1 > 0 || isAnyMoving) return; + + npc_anim_loop(npc.sprite, "Sleep"); + npc.i1 = MORNINGSTAR_TOGGLE_HOLD; + npc.state = MORNINGSTAR_SLEEPING; +} + +// 004f7e60 The Morningstar's AI: one of two looks drawn from its seed, asleep until a player walks, then a +// quickening swing toward its target. +void npc_morningstar_update(Entity_NPC& npc) +{ + bool isAnyMoving = false; + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->moveDirection != DIRECTION_NONE) isAnyMoving = true; + + switch (npc.state) + { + case NPC_STATE_INIT: + if (npc.subtype == 0) + { + RNG rng = {npc.initSeed, 1, 5, 16}; + npc.Morph(npc.type, npc.variant, (int)rng.RandomInt(MORNINGSTAR_KINDS) + 1, -1); + } + npc.state = MORNINGSTAR_SLEEPING; + break; + case MORNINGSTAR_SLEEPING: + npc.friction *= MORNINGSTAR_FRICTION; + if (npc_anim_is_done(npc)) npc_anim_loop(npc.sprite, "Idle"); + if (!isAnyMoving) break; + + npc_anim_loop(npc.sprite, "Wake"); + npc.state = MORNINGSTAR_AWAKE; + npc.i1 = MORNINGSTAR_TOGGLE_HOLD; + npc.v1.x = MORNINGSTAR_WAKE_SPEED; + break; + case MORNINGSTAR_AWAKE: + awake_update(npc, isAnyMoving); + break; + default: + break; + } + if (npc.i1 > 0) npc.i1 -= npc_ticks_get(npc); +} diff --git a/src/npc_necro.cpp b/src/npc_necro.cpp new file mode 100644 index 0000000..554f96d --- /dev/null +++ b/src/npc_necro.cpp @@ -0,0 +1,143 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_projectile.h" +#include "kage_graphics.h" +#include "room.h" +#include "room_grid.h" + +// The Necro shakes in place, raising a bone every 0 to 29 frames (at once when steered) somewhere 60 to 180 away +// from it, opposite its target within 135 degrees, in the room, off the grid's blocks, more than 150 from any player +// and in sight of its target. It tries ten spots a frame. +constexpr float NECRO_FRICTION = 0.7f; +constexpr uint32_t NECRO_WAIT_RANGE = 30; +constexpr int NECRO_SPOT_TRIES = 10; +constexpr float NECRO_SPOT_SPREAD = 270; +constexpr float NECRO_SPOT_TURN = -135; +constexpr float NECRO_SPOT_MIN = 60; +constexpr float NECRO_SPOT_RANGE = 120; +constexpr float NECRO_SPOT_STEP = 10; +constexpr float NECRO_SPOT_PLAYER_REACH = 150; + +// The bone rises 6 high, hovering until thrown at 10, out of the dark over 6 frames with a purple glow beneath. +constexpr float NECRO_BONE_HEIGHT = -6; +constexpr int NECRO_BONE_FADE_FRAMES = 6; +constexpr int NECRO_BONE_FADE_PRIORITY = 1; +constexpr ColorMod NECRO_BONE_FADE = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod NECRO_GLOW_COLOR = {{1, 1, 1, 1}, {0.8f, 0.6f, 1.4f, 1}, {0, 0, 0}}; +constexpr float NECRO_SUMMON_VOLUME = 0.5f; +constexpr float NECRO_THROW_SPEED = 10; + +// The throw leaves a glowing purple burst on the bone, flipped, its glow layer drawn added. +constexpr int NECRO_BURST_SIZE = 5; +constexpr float NECRO_BURST_LIFT = 0.65f; +constexpr ColorMod NECRO_BURST_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.4f, 0.3f, 0.7f}}; +constexpr float NECRO_BURST_DEPTH = 1; +constexpr size_t NECRO_BURST_GLOW_LAYER = 4; + +// The Necro's states: shaking, and raising and throwing a bone. +constexpr int NECRO_SHAKING = NPC_STATE_IDLE; +constexpr int NECRO_CASTING = NPC_STATE_ATTACK; + +// A spot for the bone away from the target, or none (zero) after ten tries. +static Vector necro_spot_find(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Vector target = npc.GetPlayerTarget()->pos; + Vector away = vector_sub(npc.pos, target); + if (vector_length(away) > 0) away = vector_normalized(away); + if (vector_is_zero(away)) return {}; + + for (int tries = 0; tries < NECRO_SPOT_TRIES; tries++) + { + float turn = random_unit() * NECRO_SPOT_SPREAD + NECRO_SPOT_TURN; + float reach = random_unit() * NECRO_SPOT_RANGE + NECRO_SPOT_MIN; + Vector spot = vector_add(npc.pos, vector_scale(vector_rotated(away, turn), reach)); + if (!room.IsPositionInRoom(spot, 0)) continue; + if (room.GetGridCollision(room.GetGridIndex(spot)) != GRIDCOLL_NONE) + spot = room_free_pickup_position_find({.position = spot, .step = NECRO_SPOT_STEP, + .isAvoidActiveEntities = true}); + if (!npc.IsPlayerInRadius(spot, NECRO_SPOT_PLAYER_REACH) && + room_check_line(spot, target, LINE_MODE_PROJECTILE, 0)) + return spot; + } + return {}; +} + +// Raising the bone at its spot: hovering, fading in from the dark, with its glow and sound. It becomes the child. +static void necro_bone_raise(Entity_NPC& npc) +{ + auto* bone = static_cast(g_game->Spawn({.position = npc.targetPosition, .spawner = &npc, + .type = ENTITY_PROJECTILE, .variant = PROJECTILE_BONE, .seed = Random()})); + bone->height = NECRO_BONE_HEIGHT; + bone->fallingSpeed = 0; + bone->scale = 1; + bone->projectileFlags = PROJECTILE_ANTI_GRAVITY; + bone->parent = &npc; + npc.fire_projectile_from_params(bone); + bone->SetColor(NECRO_BONE_FADE, NECRO_BONE_FADE_FRAMES, NECRO_BONE_FADE_PRIORITY, true, true); + bone->Update(); + + Entity* glow = spawn_at(ENTITY_EFFECT, EFFECT_WATER_RIPPLE, 0, npc.targetPosition, nullptr); + glow->SetColor(NECRO_GLOW_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + npc_sound_play(SOUND_PORTAL_SPAWN, NECRO_SUMMON_VOLUME, 2, 1); + npc.child = bone; +} + +// Throwing the bone at the target, with its burst. +static void necro_bone_throw(Entity_NPC& npc) +{ + auto* bone = dynamic_cast(npc.child.get()); + if (!bone) return; + + bone->velocity = vector_resized(vector_sub(npc.GetPlayerTarget()->pos, bone->pos), NECRO_THROW_SPEED); + bone->projectileFlags &= ~PROJECTILE_ANTI_GRAVITY; + Entity* burst = blood_explosion_spawn(NECRO_BURST_SIZE, bone->pos, vector_scale(bone->posOffset, NECRO_BURST_LIFT), + COLOR_DEFAULT, {}); + burst->sprite.isFlipX = true; + burst->renderDepthOffset = NECRO_BURST_DEPTH; + burst->SetColor(NECRO_BURST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (burst->sprite.layerStates.size() > NECRO_BURST_GLOW_LAYER) + { + int source = KAGE::Graphics::manager.isPremultipliedAlpha ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA; + burst->sprite.GetLayer(NECRO_BURST_GLOW_LAYER)->blendMode = {BLEND_EQUATION_ADD, source, BLEND_FACTOR_ONE, + BLEND_FACTOR_ONE, BLEND_FACTOR_ONE}; + } + burst->Update(); + npc.PlaySound(SOUND_SCAMPER, 1, 2, false, 1); + npc.child = nullptr; +} + +// Back to shaking, waiting 0 to 29 frames (none when steered). +static void necro_rest(Entity_NPC& npc) +{ + npc.state = NECRO_SHAKING; + npc.projectileDelay = npc.controllerID == -1 ? (int)(Random() % NECRO_WAIT_RANGE) : 0; +} + +// 005052a0 The Necro's AI: it shakes in place and raises bones behind itself, throwing them at its target. +void npc_necro_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + npc.friction *= NECRO_FRICTION; + if (npc.state == NECRO_SHAKING) + { + npc.sprite.Play("Shake"); + Vector spot = npc.projectileDelay < 1 ? necro_spot_find(npc) : Vector{}; + if (!vector_is_zero(spot)) + { + npc.targetPosition = spot; + npc.state = NECRO_CASTING; + npc.sprite.Play("Attack"); + } + } + else if (npc.state == NECRO_CASTING) + { + AnimationState& anim = npc.sprite.animState; + if (anim.animData && anim.IsEventTriggered("Summon")) necro_bone_raise(npc); + if (anim.animData && anim.IsEventTriggered("Shoot")) necro_bone_throw(npc); + if (!npc.sprite.IsPlaying()) necro_rest(npc); + } + else if (npc.state == NPC_STATE_INIT) necro_rest(npc); + if (npc.projectileDelay > 0) npc.projectileDelay -= ticks; +} diff --git a/src/npc_poofer.cpp b/src/npc_poofer.cpp new file mode 100644 index 0000000..82f0432 --- /dev/null +++ b/src/npc_poofer.cpp @@ -0,0 +1,307 @@ +#include "npc_gehenna.h" +#include +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_config.h" + +// The Poofer drifts after the spot its target aims at. Hits barely hurt it but swell it through five sizes, each +// bigger, and every so often (sooner the more swollen) it puffs a ring of shots. Killed, it bursts: a fart, rays of +// blood and creep, a dust cloud and a red blast, healing its kind nearby (and its players, when friendly). +constexpr int POOFER_SWELLING = NPC_STATE_ATTACK; +constexpr int POOFER_SIZES = 5; +constexpr std::array IDLE_ANIMS = {"Idle0", "Idle1", "Idle2", "Idle3", "Idle4"}; +constexpr std::array PUFF_ANIMS = {"Attack0", "Attack1", "Attack2", "Attack3", + "Attack4"}; + +// Swelling: a hit keeps a hundredth of its damage and adds a tenth of it to the swell (v2.y) while not at its largest, +// which it grows toward by a twelfth a frame, each size 20% wider. Its puff gauge (v1.y) fills with hits and with its +// swell, puffing past 20. +constexpr float POOFER_SWELL_MAX = 4; +constexpr float POOFER_HIT_KEPT = 0.01f; +constexpr float POOFER_HIT_SWELL = 10; +constexpr float POOFER_SWELL_SPEED = 12; +constexpr float POOFER_SIZE_STEP = 0.2f; +constexpr float POOFER_HIT_GAUGE = 0.5f; +constexpr float POOFER_GAUGE_SWELL = 0.2f; +constexpr float POOFER_GAUGE_FULL = 20; +constexpr float POOFER_COOL_FRAMES = 60; +constexpr float POOFER_FRICTION = 0.8f; +constexpr float POOFER_SPEED = 0.4f; +constexpr float POOFER_AIM_LEAD = 80; +static const Vector POOFER_RING = vector_make(10, 6); + +// Its burst: rays of blood and creep six ways, a dust cloud, a red blast and a heal within 160. +constexpr float BURST_PITCH = 1.5f; +constexpr float BURST_FART_RADIUS = 120; +constexpr int POOFER_SHAKE = 8; +constexpr ColorMod BURST_CLOUD_COLOR = {{1, 1, 1, 0.4f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int BURST_CREEP_TIME = 90; +constexpr float BURST_CREEP_SCALE = 2.6f; +constexpr int BURST_RAYS = 6; +constexpr float BURST_RAY_TURN = 60; +constexpr float BURST_RAY_SPEED = 18; +constexpr int BURST_RAY_SIZE = 3; +static const Vector BURST_RAY_OFFSET = vector_make(0, -15); +constexpr float BURST_RAY_DEPTH = 10; +constexpr int BURST_RAY_CREEPS = 2; +constexpr float BURST_RAY_CREEP_STEP = 50; +constexpr float BURST_RAY_CREEP_SCALE = 2; +constexpr float BURST_RAY_CREEP_SHRINK = 0.5f; +constexpr int BURST_COLOR_PRIORITY = 255; +constexpr ColorMod BURST_BLAST_COLOR = {{1, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float BURST_BLAST_DAMAGE = 4; + +// The burst's dust: 5 to 9 puffs in its blood's color, spinning away. +constexpr int BURST_DUST_MIN = 5; +constexpr int BURST_DUST_RANGE = 5; +constexpr float BURST_DUST_SPEED = 10; +constexpr float BURST_DUST_SPREAD = 20; +constexpr float BURST_DUST_SPIN_MIN = 2; +constexpr float BURST_DUST_SPIN_RANGE = 10; +constexpr int BURST_DUST_LIFE_MIN = 15; +constexpr int BURST_DUST_LIFE_RANGE = 15; +constexpr float BURST_DUST_ALPHA_MIN = 0.1f; +constexpr float BURST_DUST_ALPHA_RANGE = 0.25f; +constexpr float BLOOD_RED = 158 / 255.0f; +constexpr float BLOOD_GREEN = 11 / 255.0f; +constexpr float BLOOD_BLUE = 15 / 255.0f; +constexpr float POOFER_LUMA_RED = 0.212671f; +constexpr float POOFER_LUMA_GREEN = 0.71516f; +constexpr float POOFER_LUMA_BLUE = 0.072169f; + +// The heal: 15 health (to twice its most) for an enemy of its side, a heart for its players when friendly. +constexpr float BURST_HEAL_RADIUS = 160; +constexpr float BURST_HEAL = 15; +constexpr int BURST_HEAL_HEARTS = 2; +constexpr ColorMod BURST_HEAL_FLASH = {{1, 0, 0, 1}, {0, 0, 0, 0}, {1, 0, 0}}; +constexpr int BURST_HEAL_FLASH_FRAMES = 8; +static const Vector BURST_HEART_OFFSET = vector_make(0, -24); +constexpr float BURST_HEART_DEPTH = 1; +constexpr int POOFER_CULTIST_POOL = 10; + +// Takes in a hit: a hundredth of it hurts, a tenth of it swells, and it fills the puff gauge. +static void hit_soak(Entity_NPC& npc) +{ + float swell = npc.v2.x; + float damage = npc.pendingDamage; + npc.v1.y = (swell * POOFER_HIT_GAUGE + 1) * damage + npc.v1.y; + if (damage <= 0 || swell >= POOFER_SWELL_MAX) return; + + npc.pendingDamage = damage * POOFER_HIT_KEPT; + npc.v2.y = damage / POOFER_HIT_SWELL + npc.v2.y; + for (DamageEvent& event : npc.damageEvents) event.damage *= POOFER_HIT_KEPT; +} + +// Grows toward its swell, widening at each new size. Returns its size. +static int swell_update(Entity_NPC& npc) +{ + float swell = npc.v2.x; + float target = npc.v2.y; + int previous = (int)std::clamp(swell, 0.0f, POOFER_SWELL_MAX); + if (swell < target) + { + float step = npc.speedMultiplier / POOFER_SWELL_SPEED; + if (step < std::abs(swell - target)) target = swell + step; + npc.v2.x = std::clamp(target, 0.0f, POOFER_SWELL_MAX); + swell = npc.v2.x; + } + int size = (int)std::clamp(swell, 0.0f, POOFER_SWELL_MAX); + if (previous >= size) return size; + + const AnimationData* anim = npc.sprite.animState.animData; + if (npc.state == POOFER_SWELLING && (!anim || !anim->isLooping)) npc.sprite.SetAnimation(PUFF_ANIMS[size]); + npc.SetSize((size * POOFER_SIZE_STEP + 1) * npc.config->collisionRadius, vector_make(-1, -1), -1); + return size; +} + +// The color of its burst's dust: its blood's red through its splat color. +static ColorMod dust_color_get(Entity_NPC& npc) +{ + const ColorMod& splat = npc.splatColor; + float red = splat._tint[0] * BLOOD_RED; + float green = splat._tint[1] * BLOOD_GREEN; + float blue = splat._tint[2] * BLOOD_BLUE; + float strength = splat._colorize[3]; + if (strength != 0) + { + float luma = green * POOFER_LUMA_GREEN + red * POOFER_LUMA_RED + blue * POOFER_LUMA_BLUE; + red += (luma * splat._colorize[0] - red) * strength; + green += (luma * splat._colorize[1] - green) * strength; + blue += (luma * splat._colorize[2] - blue) * strength; + } + return {{red + splat._offset[0], green + splat._offset[1], blue + splat._offset[2], splat._tint[3]}, + {0, 0, 0, 0}, + {0, 0, 0}}; +} + +// A pool of red creep it leaves, lasting 90 frames. +static Entity_Effect* creep_spawn(Entity_NPC& npc, const Vector& position, float scale) +{ + auto* creep = static_cast(g_game->Spawn( + {.position = position, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = Random()})); + creep->timeout = BURST_CREEP_TIME; + creep->lifespan = BURST_CREEP_TIME; + creep->sprite.scale = vector_make(scale, scale); + return creep; +} + +// The burst's rays: blood thrown six ways, each leaving two shrinking pools of creep. +static void rays_spawn(Entity_NPC& npc) +{ + creep_spawn(npc, npc.pos, BURST_CREEP_SCALE); + float angle = random_unit() * FULL_TURN_DEGREES; + for (int ray = 0; ray < BURST_RAYS; ray++) + { + float radians = angle * DEGREES_TO_RADIANS; + Vector direction = vector_make(std::cos(radians), std::sin(radians)); + Entity* blood = g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(direction, BURST_RAY_SPEED), + .subType = BURST_RAY_SIZE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->SetColor(npc.splatColor, -1, BURST_COLOR_PRIORITY, false, true); + blood->sprite.offset = BURST_RAY_OFFSET; + blood->renderDepthOffset = BURST_RAY_DEPTH; + for (int i = 0; i < BURST_RAY_CREEPS; i++) + { + float distance = i * BURST_RAY_CREEP_STEP + BURST_RAY_CREEP_STEP; + creep_spawn(npc, vector_add(npc.pos, vector_scale(direction, distance)), + BURST_RAY_CREEP_SCALE - i * BURST_RAY_CREEP_SHRINK); + } + angle += BURST_RAY_TURN; + } +} + +// The burst's dust: puffs in its blood's color thrown about it, spinning away from their throw. +static void dust_spawn(Entity_NPC& npc) +{ + int count = (int)(Random() % BURST_DUST_RANGE) + BURST_DUST_MIN; + ColorMod color = dust_color_get(npc); + float alpha = color._tint[3]; + for (int i = 0; i < count; i++) + { + float throwAngle = random_unit() * RANDOM_HALF_TURN * 2; + float speed = random_unit() * BURST_DUST_SPEED; + Vector velocity = vector_make(std::cos(throwAngle) * speed, speed * std::sin(throwAngle)); + uint32_t seed = Random(); + float placeAngle = random_unit() * RANDOM_HALF_TURN * 2; + float reach = random_unit() * BURST_DUST_SPREAD; + Vector place = vector_add(npc.pos, vector_make(std::cos(placeAngle) * reach, std::sin(placeAngle) * reach)); + auto* dust = static_cast(g_game->Spawn({.position = place, + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = seed})); + Vector out = vector_sub(dust->pos, npc.pos); + float spin = -velocity.x * out.y + out.x * velocity.y < 0 ? -1 : 1; + dust->rotation = (random_unit() * BURST_DUST_SPIN_RANGE + BURST_DUST_SPIN_MIN) * spin; + int life = (int)(Random() % BURST_DUST_LIFE_RANGE) + BURST_DUST_LIFE_MIN; + dust->timeout = life; + dust->lifespan = life; + color._tint[3] = (random_unit() * BURST_DUST_ALPHA_RANGE + BURST_DUST_ALPHA_MIN) * alpha; + dust->SetColor(color, -1, BURST_COLOR_PRIORITY, false, true); + dust->Update(); + } +} + +// A heart rising over what it heals. +static Entity* heart_spawn(Entity_NPC& npc) +{ + return g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_HEART, .seed = Random()}); +} + +// Heals what its burst reaches: enemies of its side (not fires, shopkeepers, poop, props or a Cultist's blood) and, +// when friendly, its players. Whether it healed any. +static bool burst_heal(Entity_NPC& npc) +{ + bool isHealed = false; + for (Entity* other : entity_query_radius(npc.pos, BURST_HEAL_RADIUS, QUERY_ENEMIES | QUERY_PLAYERS)) + { + int type = other->type; + bool isEnemy = other->to_npc_or_coop_player() && type != ENTITY_FIREPLACE && type != ENTITY_SHOPKEEPER && + type != ENTITY_MOVABLE_TNT && type != ENTITY_GENERIC_PROP && type != ENTITY_MINECART && + type != ENTITY_POOP && !(type == ENTITY_CULTIST && other->variant == POOFER_CULTIST_POOL); + if (isEnemy && !other->isDead && other->IsFriendly() == npc.IsFriendly()) + { + other->SetColor(BURST_HEAL_FLASH, BURST_HEAL_FLASH_FRAMES, BURST_COLOR_PRIORITY, true, true); + other->health = std::min(other->health + BURST_HEAL, other->maxHitPoints + other->maxHitPoints); + Entity* heart = heart_spawn(npc); + Vector overlay = npc.GetNullOffset("OverlayEffect"); + heart->posOffset = vector_is_zero(overlay) ? BURST_HEART_OFFSET : overlay; + heart->renderDepthOffset = BURST_HEART_DEPTH; + heart->Update(); + isHealed = true; + continue; + } + if (type != ENTITY_PLAYER || !npc.IsFriendly()) continue; + + other->SetColor(BURST_HEAL_FLASH, BURST_HEAL_FLASH_FRAMES, BURST_COLOR_PRIORITY, true, true); + static_cast(other)->AddHearts(BURST_HEAL_HEARTS, false, false); + Entity* heart = heart_spawn(npc); + heart->sprite.offset = BURST_HEART_OFFSET; + heart->Update(); + isHealed = true; + } + return isHealed; +} + +// Its burst on death (not when shrunk away). +static void burst(Entity_NPC& npc) +{ + npc_sound_play(SOUND_ROCKET_BLAST_DEATH, 1, 2, BURST_PITCH); + game_butter_bean_fart({.position = npc.pos, .source = &npc, .radius = BURST_FART_RADIUS, .isShowEffect = false}); + game_shake_screen(POOFER_SHAKE); + npc.MakeBloodPoof(npc.pos, COLOR_DEFAULT, 1); + npc.MakeBloodCloud(npc.pos, BURST_CLOUD_COLOR, 1); + rays_spawn(npc); + dust_spawn(npc); + explosion_effects({.color = BURST_BLAST_COLOR, .position = npc.pos, .source = &npc, .damage = BURST_BLAST_DAMAGE}); + if (burst_heal(npc)) npc_sound_play(SOUND_VAMP_GULP, 1, 2, champion_pitch_get(npc)); +} + +// 004f64e0 The Poofer's AI: a floating sac that swells as it is hit, puffs rings of shots, and bursts healing its +// kind. +void npc_poofer_update(Entity_NPC& npc) +{ + hit_soak(npc); + int size = swell_update(npc); + if (npc.v1.x > 0) npc.v1.x = std::max(npc.v1.x - npc.speedMultiplier / POOFER_COOL_FRAMES, 0.0f); + if (npc.v1.y > 0) npc.v1.y = npc.v2.x * POOFER_GAUGE_SWELL * npc.speedMultiplier + npc.v1.y; + + if (npc.state == NPC_STATE_IDLE) + { + npc_anim_loop(npc.sprite, IDLE_ANIMS[size]); + if (npc.v1.y > POOFER_GAUGE_FULL) + { + npc.v1.y = 0; + npc.state = POOFER_SWELLING; + } + } + else if (npc.state == POOFER_SWELLING) + { + npc_anim_loop(npc.sprite, PUFF_ANIMS[size]); + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_WHEEZY_COUGH, 1, 2, false, 1); + ProjectileParams params; + params.circleAngle = 0; + npc.FireProjectiles(npc.pos, POOFER_RING, PROJECTILES_RING, params); + } + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_IDLE; + } + else if (npc.state == NPC_STATE_INIT) + npc.state = NPC_STATE_IDLE; + + npc.friction = POOFER_FRICTION; + Vector goal = npc.CalcTargetPosition(0); + Entity* target = npc.GetPlayerTarget(); + if (target && target->type == ENTITY_PLAYER) + { + Vector aim = vector_scale(static_cast(target)->aimDirection, POOFER_AIM_LEAD); + goal = g_game->room->GetClampedPositionImpl(vector_add(aim, goal), 0, 0, 0, 0); + npc.pathfinder.FindGridPath(goal, POOFER_SPEED, 0, DIRECT_PATH_FAR); + } + if (npc.isDead && !npc.HasEntityFlags(FLAG_SHRINK)) burst(npc); +} diff --git a/src/npc_poot_mine.cpp b/src/npc_poot_mine.cpp new file mode 100644 index 0000000..b70c391 --- /dev/null +++ b/src/npc_poot_mine.cpp @@ -0,0 +1,173 @@ +#include "npc_alt.h" +#include "active_items.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "menu_manager.h" +#include "room_grid.h" + +// The Poot Mine sits until hit, then farts itself away from the hit (its controller's way when steered) at 4, +// slowing by 0.8 a frame. The fart leaves a gas cloud behind, blows away what is 40 behind it within 60 at 10 and +// sprays six brown droplets back within 20 degrees at 6 to 26. Steered, it hurts itself 2 to move. +constexpr float POOT_FRICTION = 0.7f; +constexpr float POOT_STEER_DEADZONE = 0.1f; +constexpr float POOT_STEER_DAMAGE = 2; +constexpr int POOT_STEER_DAMAGE_COUNTDOWN = 30; +constexpr float POOT_HIT_NEAR_SQUARED = 1e-06f; +constexpr float POOT_SPEED = 4; +constexpr float POOT_SLOWDOWN = 0.8f; +constexpr float POOT_BOUNCE = 1.8f; +constexpr float POOT_CLOUD_SPEED = 2; +constexpr int POOT_CLOUD_SUBTYPE = 1; +constexpr int POOT_CLOUD_FOREVER = -1; +constexpr float POOT_BLOW_BEHIND = 40; +constexpr float POOT_BLOW_RADIUS = 60; +constexpr float POOT_BLOW_PUSH = 10; +constexpr int POOT_DROPLETS = 6; +constexpr float POOT_DROPLET_SPREAD = 40; +constexpr float POOT_DROPLET_TURN = -20; +constexpr float POOT_DROPLET_SPEED = 6; +constexpr float POOT_DROPLET_SPEED_RANGE = 20; +constexpr float POOT_DROPLET_BEHIND = 4; +constexpr int POOT_DROPLET_SUBTYPE = 1; +constexpr float POOT_DROPLET_SCALE = 1; +constexpr float POOT_DROPLET_SCALE_RANGE = 1.5f; +constexpr ColorMod POOT_DROPLET_COLOR = {{0.4f, 0.42f, 0.25f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Its body layer follows the overlay's null, its frame the null's tint and its spin. Dying it bursts in a 25 damage +// green blast. +constexpr int POOT_BODY_FRAMES = 8; +constexpr uint32_t POOT_SPIN_MASK = 7; +constexpr float POOT_BLAST_DAMAGE = 25; +constexpr ColorMod POOT_BLAST_COLOR = {{1, 1, 1, 1}, {1, 1, 0, 0.5f}, {0, 0, 0}}; + +// The Poot Mine's states: sitting and farting away. +constexpr int POOT_SITTING = NPC_STATE_IDLE; +constexpr int POOT_FARTING = NPC_STATE_ATTACK; + +// The way the last hit pushes it (a random way for a hit on the spot), none without a hit. +static Vector poot_knock_get(Entity_NPC& npc) +{ + if (npc.pendingDamage <= 0) return {}; + Vector knock{}; + if (!npc.damageEvents.empty()) knock = vector_sub(npc.pos, npc.damageEvents.back().source.position); + if (vector_length_squared(knock) < POOT_HIT_NEAR_SQUARED) knock = random_direction(); + return vector_length(knock) > 0 ? vector_normalized(knock) : knock; +} + +// The fart on Shoot: the gas cloud, the blast pushing what is behind and the droplets. +static void poot_fart(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_FART, 1, 2, false, 1); + Vector away = npc.targetPosition; + auto* cloud = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(away, -POOT_CLOUD_SPEED), .spawner = &npc, .subType = POOT_CLOUD_SUBTYPE, + .type = ENTITY_EFFECT, .variant = EFFECT_SMOKE_CLOUD, .seed = Random()})); + cloud->timeout = POOT_CLOUD_FOREVER; + cloud->lifespan = POOT_CLOUD_FOREVER; + cloud->Update(); + + Vector behind = vector_sub(npc.pos, vector_scale(away, POOT_BLOW_BEHIND)); + for (Entity* entity : entity_query_radius(behind, POOT_BLOW_RADIUS, QUERY_ALL)) + if (entity != &npc) entity->velocity = vector_sub(entity->velocity, vector_scale(away, POOT_BLOW_PUSH)); + + for (int droplet = 0; droplet < POOT_DROPLETS; droplet++) + { + uint32_t seed = Random(); + Vector direction = vector_scale(vector_rotated(away, random_unit() * POOT_DROPLET_SPREAD + POOT_DROPLET_TURN), -1); + Vector velocity = vector_scale(direction, random_unit() * POOT_DROPLET_SPEED_RANGE + POOT_DROPLET_SPEED); + Entity* drop = g_game->Spawn({.position = vector_sub(npc.pos, vector_scale(away, POOT_DROPLET_BEHIND)), + .velocity = velocity, .subType = POOT_DROPLET_SUBTYPE, .type = ENTITY_EFFECT, + .variant = EFFECT_WATER_SPLASH, .seed = seed}); + drop->sprite.scale = vector_scale(drop->sprite.scale, random_unit() * POOT_DROPLET_SCALE_RANGE + POOT_DROPLET_SCALE); + drop->sprite.color = POOT_DROPLET_COLOR; + drop->Update(); + } +} + +// Farting away: steered, then its fart, then the push (bouncing off walls), and sitting again once done. +static void poot_farting_update(Entity_NPC& npc) +{ + if (npc.controllerID != -1) + { + Vector steer = npc.GetControllerInput(POOT_STEER_DEADZONE); + if (!vector_is_zero(steer)) npc.targetPosition = vector_normalized(steer); + } + AnimationState& overlay = npc.sprite.overlayAnimState; + if (overlay.IsEventTriggered("Shoot")) poot_fart(npc); + if (overlay.WasEventTriggered("Shoot")) + { + if (npc.isCollidesWithGrid) + { + Vector hit = npc.gridCollisionVelocity; + Vector normal = npc.gridCollisionNormal; + npc.velocity = vector_sub(hit, vector_scale(normal, POOT_BOUNCE * vector_dot(hit, normal))); + npc.targetPosition = vector_length(npc.velocity) > 0 ? vector_normalized(npc.velocity) : npc.velocity; + } + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, + vector_scale(npc.targetPosition, npc.speedMultiplier * npc.v1.y / npc.friction)); + float speed = npc.speedMultiplier; + float keep = speed == 1 ? POOT_SLOWDOWN : POOT_SLOWDOWN / ((speed + POOT_SLOWDOWN) - speed * POOT_SLOWDOWN); + npc.v1.y *= keep; + } + if (!overlay.animData || !overlay.isPlaying) npc.state = POOT_SITTING; +} + +// Sitting: hit, it starts farting away. +static void poot_sitting_update(Entity_NPC& npc, Vector knock) +{ + npc.sprite.PlayOverlay("IdleOverlay"); + if (vector_is_zero(knock)) return; + npc.state = POOT_FARTING; + npc.sprite.PlayOverlay("PootOverlay"); + Vector steer = npc.controllerID != -1 ? npc.GetControllerInput(POOT_STEER_DEADZONE) : Vector{}; + npc.targetPosition = vector_is_zero(steer) ? knock : vector_normalized(steer); + npc.v1.y = POOT_SPEED; + npc.sprite.isFlipX = npc.targetPosition.x < 0; +} + +// Its body layer placed by the overlay's null, and the body frame its tint and spin pick. +static void poot_body_update(Entity_NPC& npc) +{ + const NullFrame* guide = npc.sprite.overlayAnimState.GetNullFrameById(1); + if (!guide) return; + LayerState& body = *npc.sprite.GetLayer(0); + body.pos = guide->pos; + body.size = guide->scale; + body.rotation = guide->rotation; + uint32_t spin = (uint32_t)((npc.v1.x + 1) * POOT_BODY_FRAMES) & POOT_SPIN_MASK; + if (npc.sprite.animState.animData) + npc.sprite.animState.SetFrameFloat((float)((guide->color._tint[0] > 0 ? 1 : 0) + spin * 2)); +} + +// 00562290 The Poot Mine's AI: it sits until hit, then farts itself away in a cloud of gas, and bursts as it dies. +void npc_poot_mine_update(Entity_NPC& npc) +{ + if (npc.controllerID != -1) + { + if (input_is_action_pressed(ACTION_BOMB, npc.controllerID, &npc)) npc.Kill(EntityRef()); + bool isSteered = !vector_is_zero(npc.GetControllerInput(POOT_STEER_DEADZONE)); + if (isSteered && npc.pendingDamage <= 0 && npc.state == POOT_SITTING) + npc.TakeDamage(POOT_STEER_DAMAGE, 0, EntityRef(), POOT_STEER_DAMAGE_COUNTDOWN); + } + Vector knock = poot_knock_get(npc); + npc.friction *= POOT_FRICTION; + + if (npc.state == NPC_STATE_INIT) + { + npc.state = POOT_SITTING; + if (npc.sprite.SetAnimation("Reference", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } + npc.sprite.PlayOverlay("IdleOverlay"); + npc.entityGridCollisionClass = GRIDCOLL_NOPITS; + } + else if (npc.state == POOT_SITTING) poot_sitting_update(npc, knock); + else if (npc.state == POOT_FARTING) poot_farting_update(npc); + + poot_body_update(npc); + if (npc.isDead && !npc.HasEntityFlags(FLAG_SHRINK)) + explosion_effects({.color = POOT_BLAST_COLOR, .position = npc.pos, .source = &npc, .damage = POOT_BLAST_DAMAGE}); +} diff --git a/src/npc_portal.cpp b/src/npc_portal.cpp index 3708fb9..0735434 100644 --- a/src/npc_portal.cpp +++ b/src/npc_portal.cpp @@ -29,6 +29,35 @@ constexpr int PORTAL_RIPPLE_FRAMES = 10; constexpr ColorMod PORTAL_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6117647f, 0.27450982f, 0.73333335f}}; constexpr ColorMod PORTAL_SUMMON_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +// The Lil Portal summons one of its eleven every 60 to 89 frames while fewer than four of its own live (only the first +// six for a subtype), tossing it out down the screen. It never closes. Its eye (layers 2 to 4) looks from the screen's +// middle, at most 1.5 a layer. +constexpr int LIL_PORTAL_KIN_CAP = 4; +constexpr int LIL_PORTAL_CHOICES = 11; +constexpr int LIL_PORTAL_SUBTYPE_CHOICES = 6; +constexpr std::array, LIL_PORTAL_CHOICES> LIL_PORTAL_ENEMIES = { + {{ENTITY_ATTACKFLY, 0}, + {ENTITY_MOTER, 0}, + {ENTITY_FLY_L2, 0}, + {ENTITY_FULL_FLY, 0}, + {ENTITY_SUCKER, 0}, + {ENTITY_SUCKER, 3}, + {ENTITY_SPIDER, 0}, + {ENTITY_BIG_SPIDER, 0}, + {ENTITY_SPIDER_L2, 0}, + {ENTITY_CRAZY_LONG_LEGS, 1}, + {ENTITY_SWARM_SPIDER, 0}}}; +constexpr uint32_t LIL_PORTAL_WAIT = 30; +constexpr int LIL_PORTAL_WAIT_MIN = 60; +constexpr float LIL_PORTAL_TOSS = 4; +constexpr float LIL_PORTAL_TOSS_SPREAD = 40; +constexpr int LIL_PORTAL_COLOR_FRAMES = 30; +constexpr ColorMod LIL_PORTAL_SUMMON_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6313726f, 0.38431373f, 0.9372549f}}; +constexpr int LIL_PORTAL_EYE_LAYER = 2; +constexpr int LIL_PORTAL_EYE_LAYERS = 3; +constexpr float LIL_PORTAL_EYE_SCALE = 30; +constexpr float LIL_PORTAL_EYE_REACH = 1.5f; + // The enemies a Portal summons, seven per chapter: the Basement, Caves, Depths, Womb, Cathedral (and anything past it), // Sheol, Downpour and Dross. constexpr int PORTAL_CHOICES = 7; @@ -110,9 +139,15 @@ static int portal_kin_count(Entity_NPC& npc) return count; } -// A summoned enemy from the chapter's seven, a few in their own variant, sharing the Portal's champion color and charm. -static void portal_summon(Entity_NPC& npc) +// The kind a Portal summons: one of the chapter's seven (a few in their own variant), or one of the Lil Portal's. +static std::pair summon_kind_get(Entity_NPC& npc) { + if (npc.variant == PORTAL_LIL) + { + int choices = npc.subtype == 0 ? LIL_PORTAL_CHOICES : LIL_PORTAL_SUBTYPE_CHOICES; + return LIL_PORTAL_ENEMIES[npc.dropRNG.RandomInt(choices)]; + } + int group = portal_group_get(); int type = PORTAL_ENEMIES[npc.dropRNG.RandomInt(PORTAL_CHOICES) + group * PORTAL_CHOICES]; int variant = 0; @@ -121,7 +156,14 @@ static void portal_summon(Entity_NPC& npc) else if (type == ENTITY_FATTY) variant = 1; else if (type == ENTITY_THE_HAUNT) variant = SWARMER_PORTAL_VARIANT; else if (type == ENTITY_DEATHS_HEAD) variant = npc.HasEntityFlags(FLAG_CHARM) ? 1 : 0; + return {type, variant}; +} +// A summoned enemy sharing the Portal's champion color and charm. The Portal ripples and counts down its summons, the +// Lil Portal tosses its summon out without a reward. +static void portal_summon(Entity_NPC& npc) +{ + auto [type, variant] = summon_kind_get(npc); auto* enemy = static_cast(g_game->Spawn( {.position = npc.pos, .spawner = &npc, .type = type, .variant = variant, .seed = npc.dropRNG.Next()})); EntityConfig_Entity* config = g_manager->entityConfig.GetEntity(type, variant, 0); @@ -133,8 +175,17 @@ static void portal_summon(Entity_NPC& npc) enemy->LoadEntityConfig(); enemy->health = std::min(enemy->health, enemy->maxHitPoints); if (npc.HasEntityFlags(FLAG_CHARM)) enemy->AddCharmed(EntityRef(), -1, false, false); - enemy->SetColor(PORTAL_SUMMON_COLOR, PORTAL_SUMMON_COLOR_FRAMES, PORTAL_SUMMON_COLOR_PRIORITY, true, true); + if (npc.variant == PORTAL_LIL) + { + enemy->flags = (enemy->flags & ~FLAG_APPEAR) | FLAG_NO_REWARD; + float angle = random_unit() * LIL_PORTAL_TOSS_SPREAD - LIL_PORTAL_TOSS_SPREAD / 2; + enemy->velocity = vector_rotated(vector_make(0, LIL_PORTAL_TOSS), angle); + enemy->SetColor(LIL_PORTAL_SUMMON_COLOR, LIL_PORTAL_COLOR_FRAMES, PORTAL_SUMMON_COLOR_PRIORITY, true, true); + } + else + enemy->SetColor(PORTAL_SUMMON_COLOR, PORTAL_SUMMON_COLOR_FRAMES, PORTAL_SUMMON_COLOR_PRIORITY, true, true); enemy->Update(); + if (npc.variant == PORTAL_LIL) return; npc.PlaySound(SOUND_DEATH_BURST_LARGE, 1, 2, false, 1); npc.i1--; @@ -142,42 +193,77 @@ static void portal_summon(Entity_NPC& npc) PORTAL_RIPPLE_FRAMES); } -// 00543720 The Portal's AI: it hovers in place, summoning an enemy of the floor's chapter while fewer than three of its -// summons live, and closes after its last. The Lil Portal is not written yet. +// The Lil Portal's eye looks from where it shows on screen toward the screen's middle, its layers stepping out. +static void lil_portal_eye_update(Entity_NPC& npc) +{ + Vector screen = render_position_get(npc.pos, RENDER_SNAPPED); + Vector scroll = vector_add(g_game->room->renderScrollOffset, g_game->screenShakeOffset); + float scale = g_screenPointScale * LIL_PORTAL_EYE_SCALE; + Vector look = vector_make((g_screenWidth * 0.5f - (screen.x + scroll.x)) / scale, + (g_screenHeight * 0.5f - (screen.y + scroll.y)) / scale); + float length = vector_length(look); + if (length > LIL_PORTAL_EYE_REACH && length > 0) look = vector_scale(look, LIL_PORTAL_EYE_REACH / length); + for (int i = 0; i < LIL_PORTAL_EYE_LAYERS; i++) + npc.sprite.GetLayer(LIL_PORTAL_EYE_LAYER + i)->pos = vector_scale(look, (float)(i + 1)); +} + +// Waiting: once its wait ran out it summons while it has room for more, else waits again. The Lil Portal opens its +// spawn overlay with a cry first. +static void portal_wait(Entity_NPC& npc) +{ + npc.sprite.Play("Idle"); + if (npc.i2 >= 1) return; + + bool isLil = npc.variant == PORTAL_LIL; + if (portal_kin_count(npc) >= (isLil ? LIL_PORTAL_KIN_CAP : PORTAL_KIN_CAP)) + { + npc.i2 = (int)(Random() % PORTAL_CROWDED_WAIT) + PORTAL_CROWDED_WAIT_MIN; + return; + } + npc.state = NPC_STATE_ATTACK; + if (!isLil) + { + npc.i2 = (int)(Random() % PORTAL_SUMMON_WAIT) + PORTAL_SUMMON_WAIT_MIN; + return; + } + npc.i2 = (int)(Random() % LIL_PORTAL_WAIT) + LIL_PORTAL_WAIT_MIN; + if (npc.sprite.SetOverlayAnimation("SpawnOverlay", SWITCH_KEEP_FRAME)) + { + npc.sprite.overlayAnimState.Rewind(); + npc.sprite.overlayAnimState.isPlaying = true; + } + npc.PlaySound(SOUND_PORTAL_SPAWN, 1, 2, false, 1); +} + +// 00543720 The Portal's and Lil Portal's AI: hovering in place, summoning while few of its summons live. The Portal +// summons its chapter's enemies and closes after its last (at once outside the chapters but the Void), the Lil Portal +// summons flies and spiders at its overlay's shot without end. void npc_portal_update(Entity_NPC& npc) { - if (npc.variant == PORTAL_LIL) return reconstruction_missing("NpcAI::ENTITY_PORTAL 00543720: the Lil Portal"); - + bool isLil = npc.variant == PORTAL_LIL; if (npc.state == NPC_STATE_INIT) { npc.state = NPC_STATE_IDLE; npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; npc.targetPosition = npc.pos; npc.AddEntityFlags(FLAG_NO_PLAYER_CONTROL); - npc.posOffset = vector_make(0, PORTAL_HEIGHT); + if (!isLil) npc.posOffset = vector_make(0, PORTAL_HEIGHT); npc.renderZOffset = PORTAL_DEPTH; npc.splatColor = PORTAL_SPLAT; npc.i2 = PORTAL_FIRST_WAIT; npc.i1 = (int)(npc.dropRNG.Next() % PORTAL_SUMMONS) + 1; + return; } int stage = g_game->stage; - if (stage == STAGE_BLUE_WOMB || (stage >= STAGE_DARK_ROOM && stage != STAGE_VOID)) npc.Remove(); + if (!isLil && (stage == STAGE_BLUE_WOMB || (stage >= STAGE_DARK_ROOM && stage != STAGE_VOID))) npc.Remove(); + if (isLil) lil_portal_eye_update(npc); - if (npc.state == NPC_STATE_IDLE) + if (npc.state == NPC_STATE_IDLE) portal_wait(npc); + else if (npc.state == NPC_STATE_ATTACK) { - npc.sprite.Play("Idle"); - if (npc.i2 < 1) - { - bool isRoomy = portal_kin_count(npc) < PORTAL_KIN_CAP; - if (isRoomy) npc.state = NPC_STATE_ATTACK; - npc.i2 = isRoomy ? (int)(Random() % PORTAL_SUMMON_WAIT) + PORTAL_SUMMON_WAIT_MIN - : (int)(Random() % PORTAL_CROWDED_WAIT) + PORTAL_CROWDED_WAIT_MIN; - } - } - if (npc.state == NPC_STATE_ATTACK) - { - portal_summon(npc); - npc.state = NPC_STATE_IDLE; + AnimationState& overlay = npc.sprite.overlayAnimState; + if (!isLil || overlay.IsEventTriggered("Shoot")) portal_summon(npc); + if (!isLil || !overlay.animData || !overlay.isPlaying) npc.state = NPC_STATE_IDLE; } if (npc.i2 > 0) npc.i2 -= npc_ticks_get(npc); diff --git a/src/npc_revenant.cpp b/src/npc_revenant.cpp new file mode 100644 index 0000000..5cce7ee --- /dev/null +++ b/src/npc_revenant.cpp @@ -0,0 +1,279 @@ +#include "npc_gehenna.h" +#include "boss_ai.h" +#include "game.h" +#include "level.h" + +// The Revenant (and its four headed variant 1) wanders the grid axis aligned. Seeing its target ahead within 256 it +// stops and breathes a stream of fire at it for 60 frames, turning after it (variant 1 spins, breathing four ways). +// Its head is an overlay: its walking look follows where it last went, its breath shows one of twelve angles. +constexpr int REVENANT_SPINNER = 1; +constexpr int REVENANT_BREATH = NPC_STATE_ATTACK; + +// Its head's looks (down, up, sideways, and the spinner's one) and the breath's twelve angles, 30 degrees apart from +// straight down. +constexpr std::array HEAD_WALK_ANIMS = {"HeadWalkDown", "HeadWalkUp", "HeadWalkHori", "HeadWalk"}; +constexpr std::array HEAD_START_ANIMS = {"AttackStartDown", "AttackStartUp", "AttackStartHori", + "AttackStart"}; +constexpr std::array HEAD_END_ANIMS = {"AttackEndDown", "AttackEndUp", "AttackEndHori", + "AttackEnd"}; +constexpr std::array HEAD_BREATH_ANIMS = {"Attack00", "Attack01", "Attack02", "Attack03", + "Attack04", "Attack05", "Attack06", "Attack07", + "Attack08", "Attack09", "Attack10", "Attack11"}; +constexpr int SPINNER_BREATH_ANIMS = 3; +constexpr int HEAD_SPINNER_LOOK = 3; +constexpr int HEAD_SIDE_LAYER = 1; +constexpr int HEAD_LAYER = 2; +constexpr float BREATH_ANIM_TOP = 90; +constexpr float BREATH_ANIM_STEP = 30; +constexpr float HEAD_WALK_FRAME = 5; + +constexpr float REVENANT_FRICTION = 0.8f; +constexpr float REVENANT_SPEED = 0.8f; +constexpr float REVENANT_MOVING = 0.01f; +constexpr float REVENANT_WALK_THRESHOLD = 0.1f; +constexpr float REVENANT_MOAN_EVERY = 30; +constexpr int REVENANT_MOAN_ODDS = 3; +constexpr float REVENANT_MOAN_VOLUME = 0.8f; +constexpr int REVENANT_MOAN_DELAY = 120; +constexpr float REVENANT_SIGHT = 256; +constexpr float REVENANT_SIGHT_CONE = 0.9f; +constexpr int REVENANT_PATH_MARKER = 900; + +// The breath: 60 frames of fire, a shot every other frame (four at right angles for the spinner) at 8 within 5 +// degrees of its aim, which turns 5 degrees a frame after where its target will be. Then a rest of 60 to 89 frames. +constexpr int BREATH_FRAMES = 60; +constexpr int BREATH_ROAR_DELAY = 90; +constexpr int BREATH_RUSH_DELAY = 15; +constexpr float BREATH_SPREAD = 10; +constexpr float BREATH_SPEED = 8; +constexpr int SPINNER_SHOTS = 4; +constexpr float BREATH_FALL_SCALE = 0.4f; +constexpr float BREATH_LEAD = 0.1f; +constexpr float SPINNER_TURN = 3; +constexpr float BREATH_TURN = 5; +constexpr int REVENANT_REST_MIN = 60; +constexpr int REVENANT_REST_RANGE = 30; +constexpr int SHOT_COLOR_PRIORITY = 255; + +// The breath's fire: red in Gehenna, violet elsewhere. +constexpr ColorMod BREATH_GEHENNA_COLOR = {{2, 1.8f, 1.8f, 1}, {0, 0, 0, 0}, {0, -1, -1}}; +constexpr ColorMod BREATH_COLOR = {{1, 1, 1, 1}, {1.3f, 1, 2, 1}, {0, 0, 0}}; + +// Which look its head shows this frame. +enum RevenantHead +{ + HEAD_WALKING, + HEAD_BREATH_START, + HEAD_BREATHING, + HEAD_BREATH_END +}; + +// 006c15c0 (NpcHelper::charger_update_move_anim) Walks its body along the axis it moves on most, flipped to face +// left, or stands facing down while slower than the threshold (half for a slow champion), and faces that way. +void npc_axis_walk_animate(Entity_NPC& npc, const AxisWalkAnims& anims) +{ + float threshold = npc.isChampion && npc.championSpeed < 1 ? anims.threshold * 0.5f : anims.threshold; + Vector velocity = npc.velocity; + if (vector_length_squared(velocity) < threshold * threshold) + { + if (npc.sprite.SetAnimation(anims.down, SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } + npc.forwardVector = vector_make(0, 1); + return; + } + + bool isVertical = std::abs(velocity.x) <= std::abs(velocity.y); + npc_anim_loop(npc.sprite, isVertical ? (velocity.y < 0 ? anims.up : anims.down) : anims.side); + npc.sprite.isFlipX = !isVertical && velocity.x < 0; + if (isVertical) + npc.forwardVector = vector_make(0, velocity.y >= 0 ? 1 : -1); + else + npc.forwardVector = vector_make(velocity.x >= 0 ? 1 : -1, 0); +} + +// One puff of its breath: a fire shot (four at right angles for the spinner) near its aim. +static void breath_puff(Entity_NPC& npc) +{ + float angle = ((random_unit() - 0.5f) * BREATH_SPREAD + npc.v1.x) * DEGREES_TO_RADIANS; + Vector velocity = vector_make(std::cos(angle) * BREATH_SPEED, std::sin(angle) * BREATH_SPEED); + int shots = npc.variant == REVENANT_SPINNER ? SPINNER_SHOTS : 1; + const ColorMod& color = g_game->GetStageID() == STAGE_ID_GEHENNA ? BREATH_GEHENNA_COLOR : BREATH_COLOR; + for (int i = 0; i < shots; i++) + { + auto* shot = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = velocity, + .spawner = &npc, + .subType = 1, + .type = ENTITY_PROJECTILE, + .variant = PROJECTILE_FIRE, + .seed = Random()})); + shot->SetColor(color, -1, SHOT_COLOR_PRIORITY, false, false); + shot->fallingSpeed *= BREATH_FALL_SCALE; + shot->parent = &npc; + npc.fire_projectile_from_params(shot); + shot->Update(); + velocity = vector_rotated(velocity, RIGHT_ANGLE_DEGREES); + } +} + +// Breathing for the ticks moved: a puff every other frame, its aim turning after where its target will be (the +// spinner just keeps turning). +static void breath_update(Entity_NPC& npc, int ticks) +{ + if (ticks <= 0) return; + + for (int tick = 0; tick < ticks; tick++) + { + npc.stateFrame--; + if ((npc.stateFrame & 1) == 0) breath_puff(npc); + + Entity& target = *npc.GetPlayerTarget(); + float lead = vector_length(vector_sub(npc.pos, target.pos)) * BREATH_LEAD; + Vector aim = vector_add(target.pos, vector_scale(target.velocity, lead)); + float angle = npc.variant == REVENANT_SPINNER ? npc.v1.x + SPINNER_TURN : vector_angle(vector_sub(aim, npc.pos)); + npc.v1.x = angle_approach(npc.v1.x, angle, BREATH_TURN); + } + if (npc.stateFrame < 1) npc.stateFrame = -1; +} + +// The breath: its head opens until its shot event roars and starts 60 frames of fire, then closes and rests. +static RevenantHead attack_update(Entity_NPC& npc, int ticks) +{ + AnimationState& head = npc.sprite.overlayAnimState; + if (npc.stateFrame < 0) + { + if (head.animData && head.isPlaying) return HEAD_BREATH_END; + npc.state = NPC_STATE_MOVE; + npc.stateFrame = -REVENANT_REST_MIN - (int)(Random() % REVENANT_REST_RANGE); + return HEAD_BREATH_END; + } + + RevenantHead look = HEAD_BREATHING; + bool isHeadLooping = head.animData && head.animData->isLooping; + if (npc.stateFrame == 0 || !isHeadLooping) + { + look = HEAD_BREATH_START; + if (head.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_GHOST_ROAR, 1, BREATH_ROAR_DELAY, false, 1); + npc.PlaySound(SOUND_FIRE_RUSH, 1, BREATH_RUSH_DELAY, false, 1); + npc.stateFrame = BREATH_FRAMES; + } + if (!head.animData || !head.isPlaying) look = HEAD_BREATHING; + if (npc.stateFrame < 1) return look; + } + breath_update(npc, ticks); + return look; +} + +// Wandering: it moans now and then, faces the axis it moves on and stops to breathe at a target it sees ahead. +static void walk_update(Entity_NPC& npc, int ticks) +{ + if (vector_length_squared(npc.velocity) > REVENANT_MOVING) npc.v1.x = vector_angle(vector_cardinal(npc.velocity)); + if (npc.GetIntervalTicks(REVENANT_MOAN_EVERY, 0) != 0 && Random() % REVENANT_MOAN_ODDS == 0) + npc.PlaySound(SOUND_MONSTER_ROAR_1, REVENANT_MOAN_VOLUME, REVENANT_MOAN_DELAY, false, 1); + npc.pathfinder.UpdateGridIndex(); + npc.pathfinder.MoveRandomlyAxisAligned(REVENANT_SPEED, STATUS_OBEYED); + if (npc.stateFrame < 0) + { + npc.stateFrame += ticks; + return; + } + + Vector targetPos = npc.GetPlayerTarget()->pos; + Vector toTarget = vector_normalized(vector_sub(targetPos, npc.pos)); + Vector axis = vector_cardinal(toTarget); + bool isSeen = vector_length(vector_sub(targetPos, npc.pos)) < REVENANT_SIGHT && + vector_dot(toTarget, axis) > REVENANT_SIGHT_CONE && + room_check_line(npc.pos, targetPos, LINE_MODE_PROJECTILE, REVENANT_PATH_MARKER); + if (!isSeen) return; + + npc.v1.x = vector_angle(axis); + npc.state = REVENANT_BREATH; + npc.stateFrame = 0; +} + +// Its head overlay: the walking, opening and closing looks face the axis of its aim (the side one flipped to face +// left), the breath shows the angle nearest its aim. +static void head_animate(Entity_NPC& npc, RevenantHead look) +{ + ANM2& sprite = npc.sprite; + if (look == HEAD_BREATHING) + { + int count = npc.variant == REVENANT_SPINNER ? SPINNER_BREATH_ANIMS : (int)HEAD_BREATH_ANIMS.size(); + int step = (int)std::floor((BREATH_ANIM_TOP - npc.v1.x) / BREATH_ANIM_STEP + 0.5f); + int index = (step + (int)HEAD_BREATH_ANIMS.size()) % count; + npc_overlay_loop(sprite, HEAD_BREATH_ANIMS[index < 0 ? index + count : index]); + sprite.GetLayer(HEAD_SIDE_LAYER)->isFlipX = false; + sprite.GetLayer(HEAD_LAYER)->isFlipX = false; + return; + } + + const auto& anims = look == HEAD_WALKING ? HEAD_WALK_ANIMS : look == HEAD_BREATH_START ? HEAD_START_ANIMS + : HEAD_END_ANIMS; + int facing = axis_direction_get(vector_from_angle(npc.v1.x)); + std::string_view name = anims[2]; + if (npc.variant == REVENANT_SPINNER) + { + name = anims[HEAD_SPINNER_LOOK]; + sprite.GetLayer(HEAD_SIDE_LAYER)->isFlipX = false; + } + else if (facing == DIRECTION_DOWN) + name = anims[0]; + else if (facing == DIRECTION_UP) + name = anims[1]; + else + { + sprite.GetLayer(HEAD_LAYER)->isFlipX = facing == DIRECTION_LEFT; + sprite.GetLayer(HEAD_SIDE_LAYER)->isFlipX = facing == DIRECTION_LEFT; + } + + bool isBodyIdle = !sprite.animState.animData || !sprite.animState.isPlaying; + if (look == HEAD_WALKING && isBodyIdle) + { + if (sprite.SetOverlayAnimation(name, SWITCH_KEEP_FRAME) && sprite.overlayAnimState.animData) + sprite.overlayAnimState.SetFrameFloat(HEAD_WALK_FRAME); + return; + } + npc_overlay_loop(sprite, name); +} + +// 004ecc10 The Revenant's AI: an axis aligned wanderer that breathes a turning stream of fire at a target it sees +// ahead. +void npc_revenant_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + npc.friction *= REVENANT_FRICTION; + RevenantHead look = HEAD_WALKING; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_MOVE; + npc.v1.x = 0; + npc.flags |= FLAG_NO_BLOOD_SPLASH; + npc.stateFrame = 0; + npc_overlay_loop(npc.sprite, "HeadAppear"); + if (npc.sprite.SetAnimation("WalkVert", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } + return; + case NPC_STATE_MOVE: + walk_update(npc, ticks); + break; + case REVENANT_BREATH: + look = attack_update(npc, ticks); + break; + default: + break; + } + + npc_axis_walk_animate(npc, {.side = "WalkHori", .up = "WalkUp", .down = "WalkDown", .threshold = REVENANT_WALK_THRESHOLD}); + npc.sprite.GetLayer(0)->isFlipX = npc.sprite.isFlipX; + npc.sprite.isFlipX = false; + head_animate(npc, look); +} diff --git a/src/npc_small_leech.cpp b/src/npc_small_leech.cpp new file mode 100644 index 0000000..b305467 --- /dev/null +++ b/src/npc_small_leech.cpp @@ -0,0 +1,251 @@ +#include "npc_alt.h" +#include "manager.h" +#include "room.h" +#include + +// The big leech Wormwood throws (subtype 1) swims at three quarters of the speed. +constexpr int SMALL_LEECH_BIG = 1; +constexpr float BIG_LEECH_SLOWDOWN = 0.75f; + +// Thrown, it rises and falls at 0.7 a frame faster until it lands back on the ground. +constexpr float LEECH_GRAVITY = 0.7f; + +// Out of water it hops at its target (a random way when on it) every other frame at rest, at 2 to 4 (4 steered), +// braking by 0.7 at rest and on landing. +constexpr float LEECH_HOP_FRICTION = 0.7f; +constexpr float LEECH_HOP_SPEED = 2; +constexpr float LEECH_HOP_SPEED_RANGE = 2; +constexpr float LEECH_STEERED_HOP_SPEED = 4; +constexpr float LEECH_STEER_DEADZONE = 0.1f; + +// In water it swims at its target, gaining 0.016 a frame up to 0.35, or circles the leech that spawned it 20 to 60 +// out, turning 4 to 5 degrees a frame either way, and swims back once more than 30 beyond that. +constexpr float LEECH_SWIM_GAIN = 0.016f; +constexpr float LEECH_SWIM_SPEED = 0.35f; +constexpr float LEECH_SWIM_FRICTION = 0.96f; +constexpr float LEECH_RETURN_SPEED = 0.5f; +constexpr float LEECH_PACE_SCALE = 0.5f; +constexpr float LEECH_ORBIT_MIN = 20; +constexpr float LEECH_ORBIT_RANGE = 40; +constexpr float LEECH_ORBIT_SLACK = 30; +constexpr float LEECH_TURN_MIN = 4; +constexpr float LEECH_ORBIT_PULL = 20; +constexpr float LEECH_ORBIT_FRICTION = 0.85f; +constexpr int LEECH_CONFUSION_SCALE = 1023; +constexpr int LEECH_CONFUSION_DIVISOR = 4; + +// It bounces off the room's edges (10 in at the sides, 20 at the top, 4 at the bottom) and never goes faster than 10. +constexpr float LEECH_WALL_SIDE = 10; +constexpr float LEECH_WALL_TOP = 20; +constexpr float LEECH_WALL_BOTTOM = 4; +constexpr float LEECH_BOUNCE = -0.6f; +constexpr float LEECH_SPEED_LIMIT = 10; + +// Near the water's surface it shows pale (paler in the Dross), and it squeaks when hurt. +constexpr float LEECH_SURFACE = -3; +constexpr float LEECH_DROSS_TINT = 1.4f; +constexpr float LEECH_WATER_TINT = 5; +constexpr float LEECH_WATER_COLORIZE = 1; +constexpr float LEECH_WATER_COLORIZE_ALPHA = 0.6f; +constexpr float LEECH_HURT_VOLUME = 0.8f; +constexpr int LEECH_HURT_DELAY = 10; +constexpr float LEECH_HURT_PITCH = 1.3f; +constexpr float LEECH_HURT_PITCH_RANGE = 0.2f; + +// The leech's states: hopping in the air, and flying from a throw. +constexpr int LEECH_HOPPING = NPC_STATE_STOMP; +constexpr int LEECH_THROWN = NPC_STATE_JUMP; + +// The swim and hop animations by facing: right, left, down and up. +constexpr std::array LEECH_SWIM_ANIMS = {"SwimRight", "SwimLeft", "SwimDown", "SwimUp"}; +constexpr std::array LEECH_HOP_ANIMS = {"HopRight", "HopLeft", "HopDown", "HopUp"}; + +// The animation of the way a direction mostly points, none for no direction. +static std::string_view leech_anim_get(Vector direction, const std::array& anims) +{ + if (std::abs(direction.x) > std::abs(direction.y)) + return direction.x > 0 ? anims[0] : direction.x < 0 ? anims[1] : std::string_view(); + return direction.y > 0 ? anims[2] : direction.y < 0 ? anims[3] : std::string_view(); +} + +// Plays the swim animation along a direction. +static void leech_face(Entity_NPC& npc, Vector direction) +{ + std::string_view anim = leech_anim_get(direction, LEECH_SWIM_ANIMS); + if (!anim.empty()) npc.sprite.Play(anim); +} + +// Its pale water look near the surface, else its own colors. +static void leech_tint_update(Entity_NPC& npc, bool isWater) +{ + ColorMod& color = npc.sprite.GetLayer(0)->color; + bool isSurfaced = g_manager->optionsConfig.render.isWaterSurfaceEnabled && isWater && npc.posOffset.y > LEECH_SURFACE; + if (!isSurfaced) + { + std::fill_n(color._tint, 4, 1.0f); + return; + } + if (g_game->GetStageID() == STAGE_ID_DROSS) + { + std::fill_n(color._tint, 3, LEECH_DROSS_TINT); + color._tint[3] = 1; + return; + } + std::fill_n(color._tint, 3, LEECH_WATER_TINT); + color._tint[3] = 1; + std::fill_n(color._colorize, 3, LEECH_WATER_COLORIZE); + color._colorize[3] = LEECH_WATER_COLORIZE_ALPHA; +} + +// Out of water: one hop in two at rest, at its target or its controller's way. +static void leech_hop(Entity_NPC& npc) +{ + npc.friction *= LEECH_HOP_FRICTION; + bool isControlled = npc.controllerID != -1; + bool isHopping = isControlled ? !vector_is_zero(npc.GetControllerInput(LEECH_STEER_DEADZONE)) : (~Random() & 1); + if (!isHopping) return; + + Vector toTarget = vector_sub(npc.CalcTargetPosition(0), npc.pos); + Vector direction = vector_is_zero(toTarget) ? random_direction() : vector_normalized(toTarget); + if (isControlled) direction = npc.GetControllerInput(LEECH_STEER_DEADZONE); + if (vector_is_zero(direction)) return; + + float speed = isControlled ? LEECH_STEERED_HOP_SPEED : random_unit() * LEECH_HOP_SPEED_RANGE + LEECH_HOP_SPEED; + Vector hop = vector_scale(direction, speed); + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(hop, npc.speedMultiplier / npc.friction)); + std::string_view anim = leech_anim_get(direction, LEECH_HOP_ANIMS); + if (!anim.empty() && npc.sprite.SetAnimation(anim, SWITCH_KEEP_FRAME)) + { + npc.sprite.animState.Rewind(); + npc.sprite.animState.isPlaying = true; + } + npc.state = LEECH_HOPPING; +} + +// Swimming at a target: away when afraid, anywhere when confused, steered when controlled. +static void leech_swim_to(Entity_NPC& npc, Entity& target) +{ + Vector direction = vector_normalized(vector_sub(target.pos, npc.pos)); + if (npc.HasEntityFlags(FLAG_CONFUSION)) + { + int age = (g_game->frameCount - npc.spawnFrame) * LEECH_CONFUSION_SCALE / LEECH_CONFUSION_DIVISOR; + RNG rng = {npc.initSeed + (uint32_t)age, 1, 9, 29}; + rng.Next(); + direction = vector_from_angle(rng.RandomFloat() * FULL_TURN_DEGREES); + } + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) direction = vector_scale(direction, -1); + if (npc.controllerID != -1) direction = npc.GetControllerInput(0); + if (npc.subtype == SMALL_LEECH_BIG) direction = vector_scale(direction, BIG_LEECH_SLOWDOWN); + + npc.v1.x = std::min(npc.speedMultiplier * LEECH_SWIM_GAIN + npc.v1.x, LEECH_SWIM_SPEED); + npc.velocity = vector_add(npc.velocity, vector_scale(direction, npc.v1.x * npc.speedMultiplier)); + npc.friction *= LEECH_SWIM_FRICTION; + leech_face(npc, direction); + if (npc.controllerID == -1) return; + + float pace = vector_length(direction); + if (npc.subtype == SMALL_LEECH_BIG) pace /= BIG_LEECH_SLOWDOWN; + npc.sprite.playbackSpeed = pace * LEECH_PACE_SCALE + LEECH_PACE_SCALE; +} + +// Circling its parent at its distance, turning its way, unless it strayed too far and swims back. +static void leech_orbit(Entity_NPC& npc, Entity& parent) +{ + npc.v2.x = normalize_angle_degrees(npc.v2.y + npc.v2.x); + if (vector_length(vector_sub(parent.pos, npc.pos)) > npc.v1.y + LEECH_ORBIT_SLACK) + { + npc.v1.x = LEECH_RETURN_SPEED; + return leech_swim_to(npc, parent); + } + + Vector spot = vector_add(parent.pos, vector_scale(vector_from_angle(npc.v2.x), npc.v1.y)); + Vector pull = vector_sub(spot, npc.pos); + if (vector_length(pull) > LEECH_ORBIT_PULL) pull = vector_resized(pull, LEECH_ORBIT_PULL); + float keep = LEECH_SWIM_SPEED; + float speed = npc.speedMultiplier; + if (speed != 1) keep = LEECH_SWIM_SPEED / ((speed + LEECH_SWIM_SPEED) - speed * LEECH_SWIM_SPEED); + npc.velocity = vector_add(npc.velocity, + vector_scale(vector_sub(vector_add(pull, parent.velocity), npc.velocity), 1 - keep)); + npc.friction *= LEECH_ORBIT_FRICTION; + float heading = npc.v2.x + (npc.v2.y > 0 ? RIGHT_ANGLE_DEGREES : -RIGHT_ANGLE_DEGREES); + leech_face(npc, vector_from_angle(heading)); +} + +// In water: dropping a lost parent when controlled, picking its circle once, squeaking when hurt, swimming, then +// bouncing off the room's edges at no more than its top speed. +static void leech_swim(Entity_NPC& npc) +{ + if (npc.controllerID != -1 && npc.parent) npc.parent = nullptr; + Entity* parent = npc.parent.get(); + if (npc.v1.y == 0 && parent) + { + npc.v1.y = parent->size + LEECH_ORBIT_MIN + random_unit() * LEECH_ORBIT_RANGE; + npc.v2.x = vector_angle(vector_sub(npc.pos, parent->pos)); + float turn = Random() & 1 ? -1.0f : 1.0f; + npc.v2.y = (random_unit() + LEECH_TURN_MIN) * turn; + } + if (npc.pendingDamage > 0 && (Random() & 1) == 0) + npc.PlaySound(SOUND_LEECH, LEECH_HURT_VOLUME, LEECH_HURT_DELAY, false, + random_unit() * LEECH_HURT_PITCH_RANGE + LEECH_HURT_PITCH); + if (parent) leech_orbit(npc, *parent); + else leech_swim_to(npc, *npc.GetPlayerTarget()); + + Room& room = *g_game->room; + Vector next = vector_add(npc.pos, vector_scale(npc.velocity, npc.friction)); + if ((npc.velocity.x < 0 && next.x < room.topLeftPos.x + LEECH_WALL_SIDE) || + (npc.velocity.x > 0 && next.x > room.bottomRightPos.x - LEECH_WALL_SIDE)) + npc.velocity.x *= LEECH_BOUNCE; + if ((npc.velocity.y < 0 && next.y < room.topLeftPos.y + LEECH_WALL_TOP) || + (npc.velocity.y > 0 && next.y > room.bottomRightPos.y - LEECH_WALL_BOTTOM)) + npc.velocity.y *= LEECH_BOUNCE; + float limit = LEECH_SPEED_LIMIT / npc.friction; + if (vector_length(npc.velocity) > limit) npc.velocity = vector_resized(npc.velocity, limit); +} + +// Thrown: flying at its throw's speed, rising then falling, and back to swimming or hopping once landed. +static void leech_thrown_update(Entity_NPC& npc) +{ + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.velocity = npc.v2; + float speed = npc.speedMultiplier; + npc.v1.x += speed * LEECH_GRAVITY; + npc.posOffset.y += npc.v1.x * speed; + if (npc.posOffset.y <= -npc.v1.x * speed) return npc.sprite.Play(npc.v2.x < 0 ? "SwimLeft" : "SwimRight"); + + npc.posOffset.y = 0; + npc.v1.x = 0; + npc.v2 = {}; + npc.targetPosition = {}; + npc.entityGridCollisionClass = GRIDCOLL_NOPITS; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.state = NPC_STATE_IDLE; +} + +// 0055b740 The Small Leech's AI: in water it swims at its target (or circles its parent), out of water it hops, and +// thrown it flies to where it lands. +void npc_small_leech_update(Entity_NPC& npc) +{ + bool isWater = g_game->room->waterAmount > 0; + if (npc.state != LEECH_THROWN) npc.entityGridCollisionClass = isWater ? GRIDCOLL_NOPITS : GRIDCOLL_GROUND; + leech_tint_update(npc, isWater); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.entityGridCollisionClass = GRIDCOLL_NOPITS; + npc.state = NPC_STATE_IDLE; + npc.v1 = {}; + return npc.sprite.Play("SwimRight"); + case NPC_STATE_IDLE: + return isWater ? leech_swim(npc) : leech_hop(npc); + case LEECH_THROWN: + return leech_thrown_update(npc); + case LEECH_HOPPING: + if (npc.sprite.animState.animData && npc.sprite.animState.WasEventTriggered("Land")) + npc.friction *= LEECH_HOP_FRICTION; + if (!npc.sprite.IsPlaying()) npc.state = NPC_STATE_IDLE; + return; + } +} diff --git a/src/npc_spider.cpp b/src/npc_spider.cpp index efe78cd..fbe3b56 100644 --- a/src/npc_spider.cpp +++ b/src/npc_spider.cpp @@ -7,7 +7,6 @@ // The spiders this AI runs: the spider, the big spider, and the jumping kinds (the level 2 spider, the ticking // spider and the Migraine spider). -constexpr int ENTITY_SPIDER_L2 = 215; constexpr int ENTITY_TICKING_SPIDER = 250; constexpr int ENTITY_MIGRAINE_SPIDER = 869; diff --git a/src/npc_swarm_spider.cpp b/src/npc_swarm_spider.cpp new file mode 100644 index 0000000..5fdc160 --- /dev/null +++ b/src/npc_swarm_spider.cpp @@ -0,0 +1,159 @@ +#include "npc_gehenna.h" +#include "boss_ai.h" +#include "loot_list.h" + +// The Swarm Spider comes in clutches (its subtype counts the extra ones, scattered within 20) and hops about its +// target: short, plain or long hops, mostly away or sideways once within 100, and rarely so from afar. Bursting Sack +// makes them flee its owner's way, toward the farthest of their kind. +constexpr int SWARM_SPIDER_HOP = NPC_STATE_JUMP; +constexpr float SWARM_SPIDER_SCATTER = 40; +constexpr float SWARM_SPIDER_FRICTION = 0.7f; +constexpr float SWARM_SPIDER_NEAR = 100; +constexpr float SWARM_SPIDER_FAR = 200; +constexpr uint32_t SWARM_SPIDER_TURN_ODDS = 4; +constexpr uint32_t SWARM_SPIDER_FAR_TURN_ODDS = 20; +constexpr int SWARM_SPIDER_REST_ODDS = 4; +constexpr float SWARM_SPIDER_HOP_VOLUME = 0.4f; +constexpr float SWARM_SPIDER_HOP_PITCH_MIN = 1.8f; +constexpr float SWARM_SPIDER_HOP_PITCH_RANGE = 0.2f; + +// The hops: short (5 to 6, within 45 degrees), plain (8 to 10, within 20) and long (10 to 13, within 10), weighted by +// how far the target is. +enum SwarmHop +{ + HOP_SHORT, + HOP_PLAIN, + HOP_LONG +}; + +// A hop's look, its push and how far its aim may stray. +struct SwarmHopKind +{ + std::string_view anim; + float speedMin = 0; + float speedRange = 0; + float spread = 0; +}; + +constexpr std::array SWARM_HOPS = {{{"HopShort", 5, 1, 90}, {"Hop", 8, 2, 40}, {"HopLong", 10, 3, 20}}}; +constexpr int HOP_SHORT_WEIGHT = 2; +constexpr int HOP_SHORT_NEAR_WEIGHT = 5; +constexpr int HOP_PLAIN_WEIGHT = 3; +constexpr int HOP_LONG_WEIGHT = 2; +constexpr int HOP_LONG_FAR_WEIGHT = 9; + +// The first frame: it brings the rest of its clutch, each drawing its seed from its own, and scatters itself. +static void clutch_spawn(Entity_NPC& npc) +{ + npc_anim_loop(npc.sprite, "Idle"); + npc.state = NPC_STATE_IDLE; + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + if (npc.subtype == 0) return; + + for (int i = 0; i < npc.subtype; i++) + { + uint32_t seed = npc.dropRNG.Next(); + float y = random_unit() * SWARM_SPIDER_SCATTER - SWARM_SPIDER_SCATTER / 2; + float x = random_unit() * SWARM_SPIDER_SCATTER - SWARM_SPIDER_SCATTER / 2; + g_game->Spawn({.position = vector_add(npc.pos, vector_make(x, y)), + .spawner = npc.spawnerEntity, + .type = npc.type, + .variant = npc.variant, + .seed = seed}); + } + float y = random_unit() * SWARM_SPIDER_SCATTER - SWARM_SPIDER_SCATTER / 2; + float x = random_unit() * SWARM_SPIDER_SCATTER - SWARM_SPIDER_SCATTER / 2; + npc.subtype = 0; + npc.pos = vector_add(npc.pos, vector_make(x, y)); +} + +// Where it hops toward: its target, or with Bursting Sack the farthest of its kind (the world origin without one, as +// the original's fallback to a random spot is never reached). +static Vector goal_get(Entity_NPC& npc, bool isSackActive) +{ + Vector goal = npc.CalcTargetPosition(0); + if (!isSackActive) return goal; + + float farthest = 0; + Vector spot{}; + for (Entity* other : entity_query(npc.type, -1)) + { + if (other == &npc || other->IsFriendly()) continue; + float distance = vector_length(vector_sub(npc.pos, other->pos)); + if (distance <= farthest) continue; + farthest = distance; + spot = other->pos; + } + return spot; +} + +// Resting: it picks its next hop toward its goal (turned aside or back now and then) and leaps. +static void hop_pick(Entity_NPC& npc, bool isSackActive) +{ + npc.friction *= SWARM_SPIDER_FRICTION; + Vector way = vector_sub(goal_get(npc, isSackActive), npc.pos); + float distance = vector_length(way); + if (distance <= 0) return; + + uint32_t odds = distance > SWARM_SPIDER_FAR ? SWARM_SPIDER_FAR_TURN_ODDS : SWARM_SPIDER_TURN_ODDS; + if (Random() % odds == 0 || distance < SWARM_SPIDER_NEAR) + { + if ((Random() & 1) == 0) + way = vector_rotated(way, (Random() & 1) == 0 ? RIGHT_ANGLE_DEGREES : -RIGHT_ANGLE_DEGREES); + else + way = vector_scale(way, -1); + } + way = vector_make(way.x / distance, way.y / distance); + + WeightedOutcomePicker picker; + picker.AddOutcomeWeight(HOP_SHORT, distance < SWARM_SPIDER_NEAR ? HOP_SHORT_NEAR_WEIGHT : HOP_SHORT_WEIGHT); + picker.AddOutcomeWeight(HOP_PLAIN, HOP_PLAIN_WEIGHT); + if (distance > SWARM_SPIDER_NEAR) + picker.AddOutcomeWeight(HOP_LONG, distance > SWARM_SPIDER_FAR ? HOP_LONG_FAR_WEIGHT : HOP_LONG_WEIGHT); + int hop = picker.PickOutcome({Random() | 1, 5, 9, 7}); + if (hop >= HOP_SHORT && hop <= HOP_LONG) + { + const SwarmHopKind& kind = SWARM_HOPS[hop]; + npc_anim_loop(npc.sprite, kind.anim); + float speed = random_unit() * kind.speedRange + kind.speedMin; + float angle = random_unit() * kind.spread - kind.spread / 2; + way = vector_rotated(vector_scale(way, speed), angle); + } + npc.targetPosition = way; + npc.state = SWARM_SPIDER_HOP; +} + +// Hopping: it leaps at its jump event (flying over things until it lands) and rests once the hop ends, now and then. +static void hop_update(Entity_NPC& npc) +{ + if (!npc.HasEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK)) npc.friction *= SWARM_SPIDER_FRICTION; + if (npc.sprite.animState.animData) + { + if (npc.sprite.IsEventTriggered("Jump")) + { + npc.flags |= FLAG_NO_PHYSICS_KNOCKBACK; + npc.velocity = npc.targetPosition; + float pitch = random_unit() * SWARM_SPIDER_HOP_PITCH_RANGE + SWARM_SPIDER_HOP_PITCH_MIN; + npc.PlaySound(SOUND_SPLATTER, SWARM_SPIDER_HOP_VOLUME, 2, false, pitch); + } + else if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Land")) + npc.flags &= ~FLAG_NO_PHYSICS_KNOCKBACK; + if (!npc_anim_is_done(npc) || (Random() & (SWARM_SPIDER_REST_ODDS - 1)) != 0) return; + } + npc_anim_loop(npc.sprite, "Idle"); + npc.state = NPC_STATE_IDLE; +} + +// 005505c0 The Swarm Spider's AI: a clutch of small spiders hopping about their target. +void npc_swarm_spider_update(Entity_NPC& npc) +{ + Entity_Player* sackOwner = g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_BURSTING_SACK, LAZARUS_SHARE_CHECK); + bool isSackActive = sackOwner && !npc.IsFriendly(); + bool isFresh = npc.state == NPC_STATE_INIT || g_game->frameCount - npc.spawnFrame == 1; + if (isSackActive && isFresh) + reconstruction_missing("NpcAI::ENTITY_SWARM_SPIDER 005505c0: Bursting Sack's spider look (spider_load_graphics)"); + + if (npc.state == NPC_STATE_INIT) return clutch_spawn(npc); + if (npc.state == NPC_STATE_IDLE) return hop_pick(npc, isSackActive); + if (npc.state == SWARM_SPIDER_HOP) hop_update(npc); +} diff --git a/src/npc_whipper.cpp b/src/npc_whipper.cpp new file mode 100644 index 0000000..ed7f8bf --- /dev/null +++ b/src/npc_whipper.cpp @@ -0,0 +1,370 @@ +#include "npc_gehenna.h" +#include "boss_ai.h" +#include "capsule.h" +#include "entity_config.h" +#include "entity_familiar.h" +#include "npc_fireplace.h" +#include + +// The Whipper (variant 0), the Snapper (1) and the Flagellant (2) walk the grid axis aligned, lunge along their facing +// at a target they see ahead and lash at anything in reach. Their whip's Hitbox null hurts and knocks back what it +// touches (the Snapper's pulls in), breaks grid entities and turns tears away. The Flagellant dashes along its path +// instead, leaving blood, and its whip hits as it goes. +constexpr int WHIPPER_SNAPPER = 1; +constexpr int WHIPPER_FLAGELLANT = 2; +constexpr int WHIPPER_LASH = NPC_STATE_ATTACK; + +constexpr std::array WHIPPER_LAUGH_ANIMS = {"HeadLaughRight", "HeadLaughUp", "HeadLaughRight", + "HeadLaughDown"}; +constexpr std::array WHIPPER_HEAD_ANIMS = {"HeadRight", "HeadUp", "HeadRight", "HeadDown"}; +constexpr std::array WHIPPER_LASH_ANIMS = {"AttackHori", "AttackUp", "AttackHori", "AttackDown"}; + +constexpr float WHIPPER_FRICTION = 0.8f; +constexpr float WHIPPER_LASH_FRICTION = 0.9f; +constexpr float WHIPPER_FAST_LASH_FRICTION = 0.6f; +constexpr int WHIPPER_TURN_DELAY = 10; +constexpr float WHIPPER_WALK_THRESHOLD = 0.1f; +constexpr float WHIPPER_SLOW_WALK_THRESHOLD = 0.05f; +constexpr float WHIPPER_WANDER_SPEED = 1.25f; +constexpr float WHIPPER_LUNGE_MASS = 100; +constexpr float WHIPPER_CHARGE_MASS = 80; + +// Seeing its target within a narrow cone ahead in a clear line, it charges that way at 1.75 a frame (the Flagellant +// paths at 1.9 along its axis) until it stalls for 20 frames (60 for the Flagellant), bumps the grid or is distracted. +constexpr float WHIPPER_SIGHT_CONE = 0.9f; +constexpr float WHIPPER_CHARGE_PUSH = 1.75f; +constexpr float FLAGELLANT_SPEED = 1.9f; +constexpr float WHIPPER_MOVING = 0.5f; +constexpr int WHIPPER_STALL = 20; +constexpr int FLAGELLANT_STALL = 60; + +// It lashes at a target within 90 in a cone ahead (the Snapper within 180 in a narrower one), lunging 5. +constexpr float WHIPPER_REACH = 90; +constexpr float SNAPPER_REACH = 180; +constexpr float WHIPPER_LASH_CONE = 0.6f; +constexpr float SNAPPER_LASH_CONE = 0.92f; +constexpr float WHIPPER_LUNGE = 5; + +// The whip: grid entities within two cells of it take a hit, bombs and those it misses are knocked 15, its targets +// take its contact damage (ten times for an enemy) with a 30 frame countdown. +constexpr int WHIP_GRID_REACH = 2; +constexpr float WHIP_GRID_SIZE = 20; +constexpr float WHIP_KNOCKBACK = 15; +constexpr float WHIP_ENEMY_DAMAGE_SCALE = 10; +constexpr float WHIP_FIREPLACE_DAMAGE = 1000; +constexpr int WHIP_COUNTDOWN = 30; +constexpr int FLAGELLANT_SPLAT_ODDS = 8; +constexpr float FLAGELLANT_SPLAT_MIN = 0.3f; +constexpr float FLAGELLANT_SPLAT_RANGE = 0.4f; + +// 004e50d0 (NpcHelper::whipper_is_target) Whether the whip goes after an entity: a hostile one's bombs, players and +// the familiars that stand in for them, a friendly or charmed one's vulnerable enemies. +static bool is_whip_target(Entity_NPC& npc, Entity& other) +{ + bool isHostile = !npc.HasEntityFlags(FLAG_FRIENDLY | FLAG_CHARM); + if (&other == &npc) return false; + if (isHostile && (other.type == ENTITY_BOMB || other.type == ENTITY_PLAYER)) return true; + if (isHostile && other.type != ENTITY_BOMB) + { + if (other.type != ENTITY_FAMILIAR) return false; + switch (other.variant) + { + case Entity_Familiar::ISAACS_HEART: + case Entity_Familiar::PUNCHING_BAG: + case Entity_Familiar::DIP: + case Entity_Familiar::MINISAAC: + case Entity_Familiar::BLOOD_BABY: + case Entity_Familiar::WISP: + case Entity_Familiar::ITEM_WISP: + case Entity_Familiar::LOST_SOUL: + return true; + default: + return false; + } + } + return other.IsVulnerableEnemy(nullptr); +} + +// The axis it moves along most: left, up, right or down (vertical on a tie). A turn holds off its lash a moment. +static void facing_update(Entity_NPC& npc) +{ + int facing = axis_direction_get(npc.velocity); + if (npc.i1 != facing) npc.projectileDelay = WHIPPER_TURN_DELAY; + npc.i1 = facing; +} + +// Restarts a head overlay from its first frame. +static void head_restart(Entity_NPC& npc, std::string_view name) +{ + if (!npc.sprite.SetOverlayAnimation(name, SWITCH_KEEP_FRAME)) return; + + npc.sprite.overlayAnimState.Rewind(); + npc.sprite.overlayAnimState.isPlaying = true; +} + +// Shows the body still, facing down. +static void body_stand(Entity_NPC& npc) +{ + if (npc.sprite.SetAnimation("WalkDown", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } +} + +// The Flagellant's dash: its body whips as it goes, its head laughing along its way. +static void flagellant_dash_animate(Entity_NPC& npc, float threshold) +{ + const AnimationData* body = npc.sprite.animState.animData; + bool isWhipping = body && body->name.starts_with("WalkAttack"); + Vector velocity = npc.velocity; + bool isHorizontal = std::abs(velocity.y) < std::abs(velocity.x); + std::string_view bodyAnim = isHorizontal ? "WalkAttackHori" : velocity.y >= 0 ? "WalkAttackDown" : "WalkAttackUp"; + npc.sprite.isFlipX = isHorizontal && velocity.x < 0; + if (isWhipping) + npc.sprite.SetAnimation(bodyAnim); + else + npc.sprite.Play(bodyAnim); + + const AnimationData* head = npc.sprite.overlayAnimState.animData; + bool isHeadIdle = !head || !npc.sprite.overlayAnimState.isPlaying; + bool isLaughing = !isHeadIdle && head->name.starts_with("HeadLaugh"); + std::string_view headAnim = "HeadLaughDown"; + if (vector_length(velocity) >= threshold && isHorizontal) headAnim = "HeadLaughRight"; + else if (vector_length(velocity) >= threshold && velocity.y < 0) headAnim = "HeadLaughUp"; + if (isLaughing) + npc.sprite.SetOverlayAnimation(headAnim); + else + npc.sprite.PlayOverlay(headAnim, isHeadIdle ? PLAY_FORCED : PLAY_UNFORCED); + npc.mass = WHIPPER_LUNGE_MASS; +} + +// Walking: the body along its axis, its head looking that way once its laugh is over. +static void walk_animate(Entity_NPC& npc, float threshold) +{ + bool isFlipped = false; + if (vector_length(npc.velocity) < threshold) + body_stand(npc); + else if (std::abs(npc.velocity.x) <= std::abs(npc.velocity.y)) + npc.sprite.Play(npc.velocity.y >= 0 ? "WalkDown" : "WalkUp"); + else + { + npc.sprite.Play("WalkHori"); + isFlipped = npc.velocity.x < 0; + } + npc.sprite.isFlipX = isFlipped; + + bool isHeadIdle = !npc.sprite.overlayAnimState.animData || !npc.sprite.overlayAnimState.isPlaying; + if (!isHeadIdle) return; + if (npc.i1 == 1) + npc_overlay_loop(npc.sprite, "HeadUp"); + else + npc.sprite.PlayOverlay(WHIPPER_HEAD_ANIMS[npc.i1]); +} + +// Wandering until it sees its target ahead, then charging along its facing until it stalls. +static void charge_update(Entity_NPC& npc) +{ + if (vector_is_zero(npc.targetPosition)) + { + npc.pathfinder.UpdateGridIndex(); + npc.pathfinder.MoveRandomlyAxisAligned(WHIPPER_WANDER_SPEED, STATUS_OBEYED); + Vector targetPos = npc.GetPlayerTarget()->pos; + Vector facing = vector_from_direction(npc.i1); + Vector toTarget = vector_normalized(vector_sub(targetPos, npc.pos)); + if (vector_dot(facing, toTarget) <= WHIPPER_SIGHT_CONE || + !room_check_line(npc.pos, targetPos, LINE_MODE_GROUND, 0)) + return; + + npc.targetPosition = facing; + npc.projectileCooldown = 0; + head_restart(npc, WHIPPER_LAUGH_ANIMS[npc.i1]); + return; + } + + if (vector_length(npc.velocity) >= WHIPPER_MOVING) + npc.projectileCooldown = 0; + else + npc.projectileCooldown++; + if (npc.variant == WHIPPER_FLAGELLANT) + { + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), FLAGELLANT_SPEED, 0, DIRECT_PATH_FAR); + npc.velocity = vector_scale(vector_cardinal(npc.velocity), vector_length(npc.velocity)); + } + else + { + npc.velocity.x += npc.targetPosition.x * WHIPPER_CHARGE_PUSH / npc.friction; + npc.velocity.y += npc.targetPosition.y * WHIPPER_CHARGE_PUSH / npc.friction; + } + + int stall = npc.variant == WHIPPER_FLAGELLANT ? FLAGELLANT_STALL : WHIPPER_STALL; + if (npc.projectileCooldown > stall || npc.isCollidesWithGrid || npc.HasEntityFlags(FLAG_DISTRACTED)) + { + npc.pathfinder.movementTarget = Vector{}; + npc.pathfinder.moveDirection = Vector{}; + npc.targetPosition = Vector{}; + } + npc.mass = WHIPPER_CHARGE_MASS; +} + +// Its lash: a target in reach within its cone ahead starts the attack with a lunge. +static void lash_try(Entity_NPC& npc) +{ + Vector facing = vector_from_direction(npc.i1); + bool isSnapper = npc.variant == WHIPPER_SNAPPER; + float cone = isSnapper ? SNAPPER_LASH_CONE : WHIPPER_LASH_CONE; + for (Entity* other : entity_query_radius(npc.pos, isSnapper ? SNAPPER_REACH : WHIPPER_REACH, QUERY_ALL)) + { + if (!is_whip_target(npc, *other)) continue; + if (vector_dot(facing, vector_normalized(vector_sub(other->pos, npc.pos))) <= cone) continue; + + npc.secondaryHitList.clear(); + npc.state = WHIPPER_LASH; + npc.sprite.Play(WHIPPER_LASH_ANIMS[npc.i1]); + npc.sprite.isFlipX = npc.i1 == 0; + head_restart(npc, WHIPPER_LAUGH_ANIMS[npc.i1]); + npc.stateFrame = 0; + npc.targetPosition = Vector{}; + npc.projectileDelay = WHIPPER_TURN_DELAY; + if (npc.friction != 0) npc.velocity = vector_add(npc.velocity, vector_scale(facing, WHIPPER_LUNGE / npc.friction)); + return; + } +} + +static void move_update(Entity_NPC& npc) +{ + facing_update(npc); + npc.mass = std::min(npc.mass, npc.config->mass); + bool isSlowChampion = npc.isChampion && npc.championSpeed < 1; + float threshold = isSlowChampion ? WHIPPER_SLOW_WALK_THRESHOLD : WHIPPER_WALK_THRESHOLD; + if (npc.variant == WHIPPER_FLAGELLANT && !vector_is_zero(npc.targetPosition)) + flagellant_dash_animate(npc, threshold); + else + walk_animate(npc, threshold); + charge_update(npc); + + if (npc.variant == WHIPPER_FLAGELLANT) + { + bool isDashing = !vector_is_zero(npc.targetPosition); + if (isDashing && npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Sound")) + npc.PlaySound(SOUND_WHIP, 1, 2, false, 1); + } + else if (npc.projectileDelay < 1) + lash_try(npc); + else + npc.projectileDelay--; +} + +// Pushes an entity along a direction by a strength against its friction. +static void whip_push(Entity& other, Vector direction, float strength) +{ + if (other.friction != 0) other.velocity = vector_add(other.velocity, vector_scale(direction, strength / other.friction)); +} + +// What the whip touches the first time this lash: bombs knocked away, tears turned along it, its targets (and poop, +// every frame) hurt and knocked back, fireplaces snuffed and other enemies pushed by the Flagellant. +static void whip_hit(Entity_NPC& npc, Entity& other) +{ + Vector away = vector_normalized(vector_sub(other.pos, npc.pos)); + bool isPoop = other.type == ENTITY_POOP || other.type == ENTITY_MOVABLE_TNT; + bool isCharmed = npc.HasEntityFlags(FLAG_CHARM); + if (other.type == ENTITY_BOMB && !isCharmed) + { + whip_push(other, away, WHIP_KNOCKBACK); + return hit_list_insert(npc.secondaryHitList, other); + } + if (other.type == ENTITY_TEAR && !isCharmed) + { + other.velocity = vector_scale(away, vector_length(other.velocity)); + return hit_list_insert(npc.secondaryHitList, other); + } + + if (!isPoop && !is_whip_target(npc, other)) + { + if (!other.to_npc_or_coop_player()) return; + if (other.type == ENTITY_FIREPLACE && other.variant != FIRE_COAL) + other.TakeDamage(WHIP_FIREPLACE_DAMAGE, 0, EntityRef(&npc), WHIP_COUNTDOWN); + if (npc.variant == WHIPPER_FLAGELLANT) whip_push(other, away, WHIP_KNOCKBACK); + return; + } + + whip_push(other, away, npc.variant == WHIPPER_SNAPPER ? -WHIP_KNOCKBACK : WHIP_KNOCKBACK); + float damage = npc.collisionDamage; + if (other.to_npc_or_coop_player()) damage *= WHIP_ENEMY_DAMAGE_SCALE; + other.TakeDamage(damage, 0, EntityRef(&npc), WHIP_COUNTDOWN); + npc_sound_play(SOUND_WHIP_HIT, 1, 2, 1); + npc.projectileDelay = 0; + if (!isPoop) hit_list_insert(npc.secondaryHitList, other); +} + +// The whip's Hitbox null: the grid entities about it take a hit, then each entity it touches is struck once a lash. +static void whip_update(Entity_NPC& npc) +{ + Capsule whip; + npc.GetNullCapsule(whip, "Hitbox"); + if (whip.radius <= 0) + { + if (npc.variant == WHIPPER_FLAGELLANT) npc.secondaryHitList.clear(); + return; + } + + Room& room = *g_game->room; + int column = (int)((whip.center.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((whip.center.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + for (int x = column - WHIP_GRID_REACH; x <= column + WHIP_GRID_REACH; x++) + for (int y = row - WHIP_GRID_REACH; y <= row + WHIP_GRID_REACH; y++) + { + int index = room.GetGridIndexByTile(x, y); + GridEntity* grid = index >= 0 && index < ROOM_GRID_CELLS ? room.gridEntities[index] : nullptr; + if (!grid) continue; + + Capsule cell(room.GetGridPosition(grid->gridIndex), vector_make(1, 1), 0, WHIP_GRID_SIZE); + if (Capsule::Collide(whip, cell)) grid->Hurt(1, EntityRef(&npc)); + } + + for (Entity* other : entity_query_radius(whip.center, whip.radius + whip.halfLength, QUERY_ALL)) + { + if (other->size == 0 || other->entityCollisionClass == ENTCOLL_NONE) continue; + if (!Capsule::Collide(whip, other->GetCollisionCapsule({}))) continue; + if (std::binary_search(npc.secondaryHitList.begin(), npc.secondaryHitList.end(), other->GetHitListIndex())) + continue; + whip_hit(npc, *other); + } +} + +// 004e5170 The Whipper's, Snapper's and Flagellant's AI: an axis aligned wanderer that charges at a target it sees +// ahead and lashes what comes in reach with its whip. +void npc_whipper_update(Entity_NPC& npc) +{ + npc.friction *= WHIPPER_FRICTION; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + npc.i1 = 0; + npc.projectileCooldown = 0; + npc.projectileDelay = 0; + npc.v1 = Vector{}; + npc.targetPosition = Vector{}; + npc_overlay_loop(npc.sprite, "HeadDown"); + body_stand(npc); + break; + case NPC_STATE_MOVE: + move_update(npc); + break; + case WHIPPER_LASH: + npc.friction *= npc.variant == 0 ? WHIPPER_LASH_FRICTION : WHIPPER_FAST_LASH_FRICTION; + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Sound")) + npc.PlaySound(SOUND_WHIP, 1, 2, false, 1); + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; + npc.stateFrame++; + break; + default: + break; + } + + if (npc.variant == WHIPPER_FLAGELLANT && (Random() & (FLAGELLANT_SPLAT_ODDS - 1)) == 0) + npc.MakeSplat(random_unit() * FLAGELLANT_SPLAT_RANGE + FLAGELLANT_SPLAT_MIN); + whip_update(npc); +} diff --git a/src/online_emotes.cpp b/src/online_emotes.cpp index 714461c..adfa42f 100644 --- a/src/online_emotes.cpp +++ b/src/online_emotes.cpp @@ -21,7 +21,6 @@ constexpr float TYPING_OFFSET_X = -12; constexpr uint32_t TYPING_ARGB = 0xffffffff; constexpr int WHEEL_SET_COUNT = 2; -constexpr float FULL_TURN = 360; // The animation an emote plays, none while typing. static std::string_view emote_animation(Emote emote) @@ -148,7 +147,7 @@ void EmoteWheel::SetEmoteSet(int index) void EmoteWheel::angle_step_update() { float previousStep = angleStep; - angleStep = FULL_TURN / (float)emoteSets[emoteSetIndex].size(); + angleStep = FULL_TURN_DEGREES / (float)emoteSets[emoteSetIndex].size(); selection = (int)((float)selection * previousStep / angleStep + 0.5f); } diff --git a/src/path_finder.cpp b/src/path_finder.cpp index 7d97c7e..99c7134 100644 --- a/src/path_finder.cpp +++ b/src/path_finder.cpp @@ -1,6 +1,7 @@ #include "path_finder.h" #include "boss_ai.h" #include "game.h" +#include "grid_entity.h" #include "npc_ai.h" #include "npc_basement.h" #include "room.h" @@ -74,8 +75,6 @@ constexpr float EVADE_PATH_SPEED = 1.079f; // The grid paths a cell's cost means: a pit band and a blocked band some grid collisions ignore, the highest cost a // path still crosses, and what a rock crusher pays to walk through rocks and through hazards. -constexpr uint32_t GRID_PATH_BAND = 1000; -constexpr uint32_t GRID_PATH_PIT = 3000; constexpr int GRID_PATH_IMPASSABLE = 950; constexpr int GRID_PATH_SOLID_CELL = 1000; constexpr int GRID_PATH_POOP_CELL = 1500; diff --git a/src/pause_screen.cpp b/src/pause_screen.cpp index 216b522..df7f4fe 100644 --- a/src/pause_screen.cpp +++ b/src/pause_screen.cpp @@ -1,6 +1,7 @@ #include "pause_screen.h" #include "entity_pickup.h" #include "entity_player.h" +#include "fx_layers.h" #include "game.h" #include "hud.h" #include "kage_input.h" @@ -47,7 +48,6 @@ constexpr float SEED_LINE_HEIGHT = 15; constexpr size_t SEED_HALF_LENGTH = 4; constexpr size_t SEED_SECOND_HALF = 5; constexpr uint32_t PAPER_TEXT_ARGB = 0xff362f2d; -constexpr uint32_t BLACK_ARGB = 0xff000000; constexpr float SOUND_VOLUME = 0.7f; constexpr int SOUND_PAPER_IN = 17; constexpr int SOUND_PAPER_OUT = 18; diff --git a/src/persistent_game_data.h b/src/persistent_game_data.h index 690daa9..1da0b27 100644 --- a/src/persistent_game_data.h +++ b/src/persistent_game_data.h @@ -21,6 +21,14 @@ constexpr int ACHIEVEMENT_THE_NEGATIVE = 78; constexpr int ACHIEVEMENT_KRAMPUS = 142; constexpr int ACHIEVEMENT_THE_VOID = 320; constexpr int ACHIEVEMENT_RERUN = 337; +constexpr int ACHIEVEMENT_BLUE_BABY = 32; +constexpr int ACHIEVEMENT_EVERYTHING_IS_TERRIBLE = 33; +constexpr int ACHIEVEMENT_ANGELS = 155; +constexpr int ACHIEVEMENT_WOODEN_CHEST = 609; +constexpr int ACHIEVEMENT_HAUNTED_CHEST = 611; +constexpr int ACHIEVEMENT_STRANGE_DOOR = 635; +constexpr int ACHIEVEMENT_DEAD_GOD = 637; +constexpr int ACHIEVEMENT_ITEM_INFO = 641; constexpr int BOSS_COUNT = 104; constexpr int CHALLENGE_COUNT = 46; constexpr int COLLECTIBLE_SEEN_COUNT = 733; @@ -42,6 +50,7 @@ enum EventCounter : int EVENT_COUNTER_BLOOD_DONATIONS = 17, EVENT_COUNTER_SLOT_MACHINES_BROKEN = 18, EVENT_COUNTER_DONATIONS = 20, + EVENT_COUNTER_EDEN_TOKENS = 21, EVENT_COUNTER_STREAK = 22, EVENT_COUNTER_BEST_STREAK = 23, EVENT_COUNTER_BLUE_BABY_KILLS = 24, diff --git a/src/player_manager.cpp b/src/player_manager.cpp index 93d8527..0c0c597 100644 --- a/src/player_manager.cpp +++ b/src/player_manager.cpp @@ -13,6 +13,7 @@ #include "log.h" #include "manager.h" #include "menu_manager.h" +#include "persistent_game_data.h" #include "platform.h" #include "popups.h" #include "preload_manager.h" @@ -60,7 +61,6 @@ constexpr float START_DEPTH_STEP = 0.01f; // How far enter_level moves the other players toward where they stood from the lead player. constexpr float ENTER_SPREAD = 3; -constexpr float RANDOM_SCALE = 2.3283064e-10f; constexpr float HALF_TURN = 3.14f; constexpr const char* PLAYER_TEARS_GROUP = "player tears"; @@ -68,7 +68,6 @@ constexpr const char* PLAYER_TEARS_GROUP = "player tears"; constexpr int BABY_COUNT = 71; constexpr uint32_t BABY_RANDOM_PICK_MASK = 3; -constexpr int EVENT_EDEN_TOKENS = 21; constexpr int PLAYERFORM_LORD_OF_THE_FLIES = 1; constexpr int TRANSFORMATION_ITEMS = 3; constexpr uint64_t GAME_STATE_COOP_BABIES_ONLY = 0x10; @@ -219,7 +218,7 @@ void PlayerManager::init_random_unlocks(uint32_t seed) if (!config) continue; bool isEden = type == PLAYER_EDEN || type == PLAYER_EDEN_B; - bool isEdenPlayable = !isEden || data.eventCounters[EVENT_EDEN_TOKENS] != 0; + bool isEdenPlayable = !isEden || data.eventCounters[EVENT_COUNTER_EDEN_TOKENS] != 0; if (config->achievement < 0 || (data.Unlocked(config->achievement) && isEdenPlayable)) coopPlayerTypes.push_back(type); } @@ -678,7 +677,7 @@ void PlayerManager::enter_level() Vector offset = vector_make(player->pos.x - lead->pos.x, player->pos.y - lead->pos.y); if (offset.x == 0 && offset.y == 0 && player != lead) { - float angle = (float)Random() * RANDOM_SCALE * HALF_TURN; + float angle = random_unit() * HALF_TURN; angle += angle; offset = vector_make(std::cos(angle), std::sin(angle)); } @@ -1086,7 +1085,7 @@ static void coop_seat_update(PlayerManager& players, CoopJoinSlot& seat) Entity_Player* player = game.playerManager.SpawnCoPlayer2(playerType); player->SetControllerIndex(seat.controllerIndex, true); Vector first = game.playerManager.GetPlayer(0)->pos; - float angle = (float)Random() * RANDOM_SCALE * HALF_TURN; + float angle = random_unit() * HALF_TURN; angle += angle; player->pos = vector_make(std::cos(angle) * JOIN_SPAWN_DISTANCE + first.x, std::sin(angle) * JOIN_SPAWN_DISTANCE + first.y); game.hud.AssignPlayerHUDs(); diff --git a/src/pocket_items.h b/src/pocket_items.h index 128e465..d14e8f7 100644 --- a/src/pocket_items.h +++ b/src/pocket_items.h @@ -41,4 +41,5 @@ void game_level_collectibles_reroll(Game& game); void game_charm_fart(const Vector& position, float radius, Entity* source); bool game_enemy_devolve(Entity& entity, Entity** outEntity); void game_level_pickups_reroll(Game& game, uint32_t seed); +void dice_room_roll(Entity_Player& player, int face, uint32_t seed); bool teleport_random_room_of_types(Entity_Player& player, std::span roomTypes, bool isPreferUnvisited); diff --git a/src/room.cpp b/src/room.cpp index 9f821fe..3ea0195 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -1,4 +1,5 @@ #include "room.h" +#include "boss_pool.h" #include "entity_pickup.h" #include "entity_player.h" #include "entity_effect.h" @@ -6,14 +7,17 @@ #include "entity_familiar.h" #include "entity_npc.h" #include "game.h" +#include "grid_entity.h" #include "grid_entity_door.h" #include "grid_entity_stairs.h" +#include "level.h" #include "log.h" #include "lua_engine.h" #include "manager.h" #include "menu_options.h" #include "mines.h" #include "npc_fireplace.h" +#include "persistent_game_data.h" #include "room_grid.h" #include "room_path.h" #include "room_render.h" @@ -92,7 +96,6 @@ constexpr ColorMod GREY_COLOR = {{1, 1, 1, 1}, {1, 1, 1, -1}, {0, 0, 0}}; // The entity types, variants and subtypes Room checks. // The Stairway's ladder stands in the second row's eleventh cell of a room at least 11 wide. -constexpr int STAIRWAY_MIN_WIDTH = 11; constexpr int STAIRWAY_COLUMN = 10; // The room layout spawns Init reads before spawning anything (entities2.xml types 825 to 970). @@ -115,8 +118,6 @@ constexpr int WATER_SUBTYPE_DUMP = 10; // The grid path values: what an entity walking has left, and what blocks spawning. constexpr int GRID_PATH_RESET = 900; -constexpr int GRID_PATH_UNIT = 1000; -constexpr int GRID_PATH_PIT = 3000; constexpr int GRID_PATH_PIT_LAST = 3999; // Lua's GridCollisionClass values GetGridCollision returns. @@ -130,18 +131,12 @@ constexpr int DUNGEON_GIDEON = 1; constexpr int DUNGEON_ROTGUT = 2; constexpr int DUNGEON_ROTGUT_HEART = 3; constexpr int DUNGEON_BEAST = 4; -constexpr int BOSS_MOM = 6; -constexpr int BOSS_ISAAC = 39; -constexpr int BOSS_SATAN = 24; -constexpr int BOSS_MEGA_SATAN = 55; constexpr int BOSS_ULTRA_GREED = 62; constexpr int BOSS_ROTGUT = 87; -constexpr int BOSS_MOM_MAUSOLEUM = 89; // The backdrops LoadBackdropGraphics picks beyond the stage's own (backdrops.xml ids), and what picks them: rooms off // the map, Home's rooms by subtype, the bosses and stages with their own, and the Void's random ones. constexpr int ROOM_DEATHMATCH_IDX = -19; -constexpr int DIMENSION_DEATH_CERTIFICATE = 2; constexpr int DARK_CLOSET_B_SUBTYPE = 33; constexpr int HOME_ISAACS_BEDROOM = 0; constexpr int HOME_MOMS_BEDROOM = 2; @@ -189,7 +184,6 @@ constexpr int COLLECTIBLE_GOAT_HEAD = 215; // door's jingles and Greed's deal door slot, Mom's parts the Boss Rush door clears, and the run flags they set. constexpr int ACHIEVEMENT_BLUE_WOMB = 234; constexpr int ACHIEVEMENT_SECRET_EXIT = 407; -constexpr int ACHIEVEMENT_STRANGE_DOOR = 635; constexpr int SOUND_ANGEL_DOOR_APPEAR = 23; constexpr int SOUND_DEVIL_DOOR_APPEAR = 320; constexpr int GREED_DEAL_DOOR_SLOT = 4; @@ -256,8 +250,6 @@ constexpr int COLLECTIBLE_CARD_READING = 660; constexpr int SEED_EFFECT_PRE_ITEMS = 79; constexpr int SEED_EFFECT_NO_LAST_BOSS_DOORS = 71; constexpr int SPECIAL_DAILY_SURPRISE_MINIBOSS = 17; -constexpr int CHALLENGE_SPEED = 22; -constexpr int CHALLENGE_DELETE_THIS = 45; constexpr int ACHIEVEMENT_SHOP_LEVEL_2 = 151; constexpr int ACHIEVEMENT_SHOP_LEVEL_3 = 152; constexpr int ACHIEVEMENT_SHOP_LEVEL_4 = 153; @@ -267,6 +259,10 @@ constexpr int EVENT_ARCADES_VISITED = 9; constexpr int SHOP_VISITS_FOR_ACHIEVEMENT = 5; constexpr int SHOP_LEVEL_MAX = 5; +// Card Reading's portals: one to each of four room types, the two of them two cells either side of the centre. +constexpr int CARD_READING_PORTALS = (int)PORTAL_ROOM_TYPES.size(); +constexpr int CARD_READING_PORTAL_SPREAD = 2; + // The run state and floor state bits Init and Update read. constexpr uint64_t GAME_STATE_SURPRISE_MINIBOSS_SEEN = 1ull << 29; @@ -421,6 +417,7 @@ static void boss_fireplaces_bind(Room& room, bool isHeretic) void Room::Init(RoomConfig_Room& config, RoomDescriptor& roomDescriptor) { temporaryEffects.ClearEffects(false); + killedNpcs.clear(); for (int group = 0; group < OUTPUT_GROUP_COUNT; group++) { outputGroupGridIndices[group].clear(); @@ -1074,21 +1071,61 @@ void Room::init_decorations(RoomConfig_Room& config) if (is_greed() && config.type == ROOM_DEFAULT) greed_decorations_make(); } +// The spot a cell shows, for a cell off the grid the one before it as the original's -1 index. +static Vector room_cell_position(Room& room, int column, int row) +{ + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + int cell = isInside ? row * room.gridWidth + column : -1; + return vector_make((float)(cell % room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_X, + (float)(cell / room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_Y); +} + // The Stairway's ladder in the starting room's top right, with a path carved to it from the entrance. A ladder off // the grid carves nothing, where the original searched from a cell before the grid. static void stairway_place(Room& room) { uint32_t seed = Random(); - int cell = room.gridWidth >= STAIRWAY_MIN_WIDTH && room.gridHeight >= 2 ? room.gridWidth + STAIRWAY_COLUMN : -1; - Vector position = vector_make((float)(cell % room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_X, - (float)(cell / room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_Y); - Entity* ladder = entity_spawn(ENTITY_EFFECT, EFFECT_TALL_LADDER, position, 1, seed); + Entity* ladder = + entity_spawn(ENTITY_EFFECT, EFFECT_TALL_LADDER, room_cell_position(room, STAIRWAY_COLUMN, 1), 1, seed); int start = room.GetGridIndex(g_game->GetPlayer(0)->GetEnterPosition()); int goal = room.GetGridIndex(ladder->pos); if (start >= 0 && goal >= 0) is_grid_path_valid(room, {start, goal, GRID_PATH_PLAYER_WALLS | GRID_PATH_TELEPORTERS | GRID_PATH_CARVE}); } +// Card Reading's portals in the starting room, to the floor's treasure room, boss room, secret room and shop (by the +// portal's subtype, in that order, shuffled by the room's decoration seed). Up to two such rooms get one portal above +// the centre, more get two portals either side of it. +static void card_reading_portals_place(Room& room) +{ + uint32_t roomTypes = 0; + for (int i = 0; i < g_game->nbRooms; i++) + { + RoomDescriptor& desc = g_game->roomList[i]; + if (desc.data && desc.group < 0) roomTypes |= 1u << desc.data->type; + } + std::array portals{}; + int count = 0; + for (int subType = 0; subType < CARD_READING_PORTALS; subType++) + if (roomTypes & 1u << PORTAL_ROOM_TYPES[subType]) portals[count++] = subType; + if (count == 0) return; + + RNG rng = {room.descriptor->decorationSeed, 9, 5, 25}; + for (int i = 0; i < count - 1; i++) std::swap(portals[i], portals[(int)rng.RandomInt((uint32_t)(count - i)) + i]); + + int column = room.gridWidth / 2; + int row = room.gridHeight / 2 - 1; + auto portal_spawn = [&](int portal, int columnOffset, int rowOffset) + { + g_game->Spawn({.position = room_cell_position(room, column + columnOffset, row + rowOffset), + .subType = portal, .type = ENTITY_EFFECT, .variant = EFFECT_PORTAL_TELEPORT, + .seed = rng.Next()}); + }; + if (count <= 2) return portal_spawn(portals[0], 0, -1); + portal_spawn(portals[0], -CARD_READING_PORTAL_SPREAD, 0); + portal_spawn(portals[1], CARD_READING_PORTAL_SPREAD, 0); +} + // The first visit's items in the starting room: Isaac's Tomb's old chest, the pre-items seed's collectibles (two // under the Curse of the Labyrinth), and Luna's light in secret rooms. void Room::init_first_visit_items() @@ -1098,7 +1135,7 @@ void Room::init_first_visit_items() if (g_game->currentRoomIdx == g_game->startingRoomIdx && g_game->stage != STAGE_HOME) { if (players.FirstCollectibleOwner(COLLECTIBLE_CARD_READING, LAZARUS_SHARE_CHECK) && !is_greed()) - reconstruction_missing("Room::Init 007f2800: the starting room's portals (FUN_00737c10)"); + card_reading_portals_place(*this); if (players.FirstCollectibleOwner(COLLECTIBLE_THE_STAIRWAY, LAZARUS_SHARE_CHECK)) stairway_place(*this); if (players.FirstCollectibleOwner(COLLECTIBLE_ISAACS_TOMB, LAZARUS_SHARE_CHECK)) { @@ -1335,7 +1372,7 @@ void Room::init_colors() floorColor = GREY_COLOR; wallColor = GREY_COLOR; } - if (is_ashpit_rays()) reconstruction_missing("Room::Init 007f2800: Ashpit's light ray textures"); + if (is_ashpit_rays()) room_rays_load(*this); } // 008242f0 Whether the floor is the Ashpit, whose rooms load light ray textures. The mirror world never is. @@ -1649,7 +1686,7 @@ uint32_t Room::GetGridCollision(int gridIndex) if (gridEntities[gridIndex]) return (uint32_t)gridEntities[gridIndex]->collisionClass; int path = gridPaths[gridIndex]; - if (path < GRID_PATH_UNIT) return GRID_COLLISION_NONE; + if (path < GRID_PATH_BAND) return GRID_COLLISION_NONE; if (path >= GRID_PATH_PIT && path <= GRID_PATH_PIT_LAST) return GRID_COLLISION_PIT; return GRID_COLLISION_SOLID; } diff --git a/src/room.h b/src/room.h index 51ed25f..09ca4d8 100644 --- a/src/room.h +++ b/src/room.h @@ -11,6 +11,7 @@ #include "temporary_effects.h" #include #include +#include #include #include #include @@ -20,6 +21,20 @@ constexpr float GRID_CELL_SIZE = 40; constexpr float GRID_ORIGIN_X = 40; constexpr float GRID_ORIGIN_Y = 120; +// An enemy killed in the room, as a Cultist raises it again: its kind, where it fell (moved off a blocked cell), its +// champion color and side. +struct KilledNpc +{ + Vector position{}; + int type = 0; + int16_t variant = 0; + int16_t subtype = 0; + int championColor = -1; + bool isFriendly = false; +}; + +void room_killed_npc_record(Room& room, Entity& npc); + // The trigger output groups a room's pressure plates fire (Room::TriggerOutput). constexpr int OUTPUT_GROUP_COUNT = 10; @@ -68,6 +83,9 @@ enum RoomType : int ROOM_ULTRASECRET }; +// The rooms a teleport portal leads to by its subtype (Card Reading's portals): treasure, boss, secret and shop. +constexpr std::array PORTAL_ROOM_TYPES = {ROOM_TREASURE, ROOM_BOSS, ROOM_SECRET, ROOM_SHOP}; + // What the Broken Watch does to the room: nothing, slows it, or speeds it up. enum BrokenWatchState : int { @@ -164,6 +182,7 @@ public: std::set litGridIndices; std::set pendingGridRemovals; std::deque shopRestocks; + std::list killedNpcs; EntityList entityList; FXLayers fxLayers; Backdrop backdrop; @@ -352,6 +371,7 @@ public: void MamaMegaExplosion(Vector position, Entity_Player* player); void RestoreState(); void hold_trigger_output_entities(); + void TriggerOutput(int group); Entity* hold_entity_in_spawner(Entity& entity, int group); bool TrySpawnMegaSatanRoomDoor(bool isForce); bool TrySpawnSpecialQuestDoor(); diff --git a/src/room_clear.cpp b/src/room_clear.cpp index fa5a7ea..b99de48 100644 --- a/src/room_clear.cpp +++ b/src/room_clear.cpp @@ -81,7 +81,6 @@ constexpr int ACHIEVEMENT_LIL_CHUBBY = 14; constexpr int ACHIEVEMENT_STEVEN = 16; constexpr int ACHIEVEMENT_CHAD = 17; constexpr int ACHIEVEMENT_GISH = 18; -constexpr int ACHIEVEMENT_ANGELS = 155; // The endings' unlocks: Judas for Satan; the Lamb's run under 20 minutes (ZIP!), without a heart, bomb or coin picked // up (It's the key), the gate to the Void, and the first three victory laps (Once more with feeling!, Butter, RERUN). diff --git a/src/room_render.cpp b/src/room_render.cpp index a6ce7f8..48100ee 100644 --- a/src/room_render.cpp +++ b/src/room_render.cpp @@ -1,12 +1,15 @@ #include "room_render.h" +#include "boss_pool.h" #include "entity_npc.h" #include "entity_player.h" #include "entity_tear.h" +#include "fx_layers.h" #include "game.h" #include "gl.h" #include "grid_entity_door.h" #include "grid_entity_pit.h" #include "grid_entity_rock.h" +#include "level.h" #include "log.h" #include "manager.h" #include "rail_manager.h" @@ -28,6 +31,35 @@ constexpr int TEXEL_KEEP = -1; constexpr int WRAP_REPEAT = 0; constexpr int FILTER_LINEAR = 1; constexpr int ROOM_SURFACE_WIDTH = 780; + +// The Ashpit's dust: three cloud layers drifting with the room's frames (half a frame more on odd frames), up to 4 a +// frame across and 1 either way down, 2 to 6 opaque, lit by the room's light (greyed and darkened) and a faint glow. +constexpr int DUST_CLOUD_LAYERS = 3; +constexpr float DUST_DRIFT_HALF = 0.5f; +constexpr float DUST_DRIFT_X_RANGE = 3; +constexpr float DUST_CLOUD_ALPHA = 2; +constexpr float DUST_CLOUD_ALPHA_RANGE = 4; +constexpr float DUST_GLOW = 0.05f; +constexpr ColorMod DUST_LIGHT_COLOR = {{1, 1, 1, 1}, {0.5f, 0.5f, 0.5f, -1}, {-0.8f, -0.8f, -0.8f}}; +constexpr KAGE::Graphics::BlendMode DUST_MULTIPLY_BLEND = { + KAGE::Graphics::EQUATION_ADD, KAGE::Graphics::FACTOR_DST_COLOR, KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA, + KAGE::Graphics::FACTOR_DST_COLOR, KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA}; + +// The Ashpit's light rays: their two images, the cells they shine from, slanted 45 degrees from 60% of their height +// above, flickering between 0.1 and 9.1 strong, warmer and down to a twentieth as the room darkens. +constexpr std::array ASHPIT_RAY_PNGS = {"gfx/backdrop/fx_ray_3.png", "gfx/backdrop/fx_ray_4.png"}; +constexpr std::array, 2> DUST_RAY_CELLS = {{{7, 4}, {20, 4}}}; +constexpr float DUST_RAY_ABOVE = 0.6f; +constexpr float DUST_RAY_BELOW = 0.4f; +constexpr float DUST_RAY_ANGLE = -0.7853982f; +constexpr float DUST_RAY_FLICKER = 0.1f; +constexpr float DUST_RAY_FLICKER_RANGE = 9; +constexpr float DUST_RAY_DIM = 0.05f; +constexpr float DUST_RAY_GREEN = 0.9f; +constexpr float DUST_RAY_GREEN_DARK = 0.19999999f; +constexpr float DUST_RAY_BLUE = 0.8f; +constexpr float DUST_RAY_BLUE_DARK = 0.15000004f; +constexpr float DUST_RAY_HALF_WIDTH = 0.5f; constexpr int ROOM_SURFACE_HEIGHT = 468; // The game shader Render's shadows and lighting overlay draw with (the original's shader table entry 0). @@ -89,8 +121,6 @@ constexpr float DEPTH_ROW_BOTTOM = 20; constexpr float DEPTH_ROW_SCALE = 100; constexpr float DEPTH_ROW_BASE = 10030; -constexpr KColor WHITE = kcolor_rgba(1, 1, 1, 1); -constexpr KColor BLACK = kcolor_rgba(0, 0, 0, 1); constexpr KColor GREED_FLOOR_COLOR = kcolor_rgba(0.2784314f, 0.18039216f, 0.101960786f, 1); constexpr KColor SHADOW_TINT = kcolor_rgba(1, 1, 1, 0.24f); constexpr KColor LIGHTNING_TINT = kcolor_rgba(0.85f, 0.9f, 1, 1); @@ -199,8 +229,6 @@ constexpr int GRID_STATE_POOP_DESTROYED = 1000; constexpr int PLATE_VARIANT_REWARD = 9; constexpr int PLATE_VARIANT_ROOM_CLEAR = 3; constexpr int ROOM_IDX_BLUE_WOMB_LIGHT = -9; -constexpr int BOSS_MOM_MAUSOLEUM = 89; -constexpr int DIMENSION_DEATH_CERTIFICATE = 2; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_LIT_DOOR = 1u << 18; constexpr uint32_t DEBUG_FLAG_GRID_VALUES = 1 << 1; constexpr uint32_t DEBUG_FLAG_ROOM_INFO = 1 << 4; @@ -736,10 +764,111 @@ static void water_overlay_render(Room& room, Vector surfaceOffset) graphics.shader_default_set(); } -// 00825de0 Draws the Ashpit's drifting dust into the dust surface. Not reconstructed yet past the Ashpit check. +// Room::Init's part of 007f2800 for the Ashpit: one of its two light ray images, by the room's decoration seed, +// smoothed. +void room_rays_load(Room& room) +{ + RNG rng = {room.descriptor->decorationSeed, 1, 27, 27}; + roomSurfaces.rays.reset(); + image_create(roomSurfaces.rays, ASHPIT_RAY_PNGS[rng.RandomInt(ASHPIT_RAY_PNGS.size())], TEXEL_KEEP, FILTER_LINEAR); +} + +// The Ashpit's clouds: three layers of the cloud image, each from a random spot of it drifting at its own pace with +// the room's frames, over black. +static void dust_clouds_render(Room& room, RNG& rng) +{ + KAGE::Graphics::ImageBase& clouds = *roomSurfaces.clouds; + KAGE::Graphics::ImageBase& dust = *roomSurfaces.dust; + float drift = g_game->IsPaused() ? 0 : (float)((g_manager->framecount + 1) % 2) * DUST_DRIFT_HALF; + float time = (float)room.GetFrameCount() + drift; + Vector corner = vector_scale(vector_add(room.renderScrollOffset, g_game->screenShakeOffset), -1); + SourceQuad view = KAGE::Graphics::source_quad_rect(corner, vector_make((float)dust.width, (float)dust.height)); + + for (int layer = 0; layer < DUST_CLOUD_LAYERS; layer++) + { + uint32_t row = rng.Next(); + row = clouds.height ? row % (uint32_t)clouds.height : 0; + float shiftY = (rng.RandomFloat() * 2 - 1) * time + (float)row; + uint32_t column = rng.Next(); + column = clouds.width ? column % (uint32_t)clouds.width : 0; + float shiftX = (rng.RandomFloat() * DUST_DRIFT_X_RANGE + 1) * time + (float)column; + SourceQuad source = view; + for (Vector* point : {&source._topLeft, &source._topRight, &source._bottomLeft, &source._bottomRight}) + *point = vector_add(*point, vector_make(shiftX, shiftY)); + float alpha = rng.RandomFloat() * DUST_CLOUD_ALPHA_RANGE + DUST_CLOUD_ALPHA; + KColor tint = kcolor_rgba(1, 1, 1, alpha); + clouds.Render(source, screen_quad(tint), tint); + } +} + +// The Ashpit's two light rays through the room's windows (one gone in an L room missing its corner), slanted, warmer +// and dimmer as the room darkens, flickering. +static void dust_rays_render(Room& room, RNG& rng) +{ + KAGE::Graphics::ImageBase& rays = *roomSurfaces.rays; + float flicker = rng.RandomFloat() * DUST_RAY_FLICKER_RANGE + DUST_RAY_FLICKER; + float darkness = is_curse_of_darkness() ? 1 : g_game->darknessStrength * g_game->darknessModifier; + float dim = std::min(flicker * DUST_RAY_DIM, DUST_RAY_DIM); + float green = DUST_RAY_GREEN - darkness * DUST_RAY_GREEN_DARK; + float blue = DUST_RAY_BLUE - darkness * DUST_RAY_BLUE_DARK; + KColor color = kcolor_rgba(1, green, blue, (dim - flicker) * darkness + flicker); + int shape = room.descriptor && room.descriptor->data ? room.descriptor->data->shape : ROOMSHAPE_1x1; + + for (int i = 0; i < (int)DUST_RAY_CELLS.size(); i++) + { + auto [column, row] = DUST_RAY_CELLS[i]; + if (column >= room.gridWidth || row >= room.gridHeight) continue; + if ((i == 0 && shape == ROOMSHAPE_LTL) || (i == 1 && shape == ROOMSHAPE_LTR)) continue; + + Vector world = vector_make((float)column * GRID_CELL_SIZE + GRID_ORIGIN_X, + (float)row * GRID_CELL_SIZE + GRID_ORIGIN_Y); + Vector position = vector_add(vector_add(render_position_get(world, RENDER_SNAPPED), room.renderScrollOffset), + g_game->screenShakeOffset); + float halfWidth = (float)rays.width * DUST_RAY_HALF_WIDTH; + Vector topLeft = vector_make(position.x - halfWidth, position.y - (float)rays.height * DUST_RAY_ABOVE); + Vector bottomRight = vector_make(halfWidth + position.x, (float)rays.height * DUST_RAY_BELOW + position.y); + KAGE::Graphics::ColorQuad quad = + KAGE::Graphics::color_quad_rect(topLeft, vector_sub(bottomRight, topLeft), color); + quad_rotate(quad, position, DUST_RAY_ANGLE); + rays.Render(quad, color); + } +} + +// 00825de0 Draws the Ashpit's drifting dust into the dust surface: the cloud layers in their own surface, then lit by +// the room's light (dimmed), a faint glow and the light rays (with lighting, not in a pitch black room), the clouds +// multiplied over them. static void darkness_overlay_render(Room& room) { - if (room.is_ashpit_rays()) reconstruction_missing("Room::render_darkness_overlay 00825de0"); + if (!room.is_ashpit_rays()) return; + + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + bool isLighting = g_manager->optionsConfig.render.isLightingEnabled; + RNG rng = {room.descriptor->decorationSeed, 1, 11, 6}; + surface_begin(roomSurfaces.dustTemp, KAGE::Graphics::TARGET_SCREEN_SIZE); + render_color_shader_pass(screen_quad(BLACK)); + graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); + dust_clouds_render(room, rng); + surface_end(); + + surface_begin(roomSurfaces.dust, KAGE::Graphics::TARGET_SCREEN_SIZE); + graphics.isCullOffscreen = false; + if (isLighting) + { + graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); + shader_select(COLOR_OFFSET_SHADER); + apply_sprite_shader_params(DUST_LIGHT_COLOR, SPRITE_SHADER_COLOR_APPLY, *roomSurfaces.lightOverlay); + roomSurfaces.lightOverlay->Render(screen_quad(WHITE), WHITE); + graphics.shader_default_set(); + } + graphics.blend_set(KAGE::Graphics::BLEND_ADDITIVE); + render_color_shader_pass(screen_quad(kcolor_rgba(DUST_GLOW, DUST_GLOW, DUST_GLOW, 1))); + bool isPitchBlack = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_PITCH_BLACK; + if (isLighting && !isPitchBlack && roomSurfaces.rays) dust_rays_render(room, rng); + + graphics.blendMode = DUST_MULTIPLY_BLEND; + roomSurfaces.dustTemp->Render(screen_quad(WHITE), WHITE); + graphics.isCullOffscreen = true; + surface_end(); } // 00826ae0 Fills a flooded Mines room's textured pit surface: each pit's shape cut from the pit mask, painted with lava diff --git a/src/room_render.h b/src/room_render.h index 9bf6bde..6bbcdb6 100644 --- a/src/room_render.h +++ b/src/room_render.h @@ -29,6 +29,7 @@ struct RoomSurfaces KAGE::Graphics::ImagePtr lightOverlay; KAGE::Graphics::ImagePtr mirror; KAGE::Graphics::ImagePtr pitMask; + KAGE::Graphics::ImagePtr rays; KAGE::Graphics::ImagePtr shading; KAGE::Graphics::ImagePtr shadingSurface; KAGE::Graphics::ImagePtr shadow; @@ -55,6 +56,7 @@ extern RoomSurfaces roomSurfaces; extern std::array roomShockwaves; void room_surfaces_init(); +void room_rays_load(Room& room); Vector RandomVector(uint32_t seed); KColor kcolor_apply(const ColorMod& color, const KColor& input); KColor image_texel_get(KAGE::Graphics::ImageBase& image, uint32_t x, uint32_t y); diff --git a/src/room_special.cpp b/src/room_special.cpp index 7c046d5..ff92e05 100644 --- a/src/room_special.cpp +++ b/src/room_special.cpp @@ -16,7 +16,6 @@ #include #include -constexpr int COLLECTIBLE_POUND_OF_FLESH = 672; constexpr int TRINKET_STORE_CREDIT = 13; constexpr int TRINKET_KEEPERS_BARGAIN = 171; constexpr int TRINKET_ADOPTION_PAPERS = 184; diff --git a/src/room_transition.cpp b/src/room_transition.cpp index 6b42564..c687cac 100644 --- a/src/room_transition.cpp +++ b/src/room_transition.cpp @@ -1,4 +1,5 @@ #include "room_transition.h" +#include "boss_pool.h" #include "entity_familiar.h" #include "entity_npc.h" #include "entity_player.h" @@ -11,6 +12,7 @@ #include "platform.h" #include "render_passes.h" #include "room.h" +#include "seeds.h" #include #include #include @@ -19,13 +21,11 @@ constexpr const char* VERSUS_SCREEN_ANM2 = "gfx/ui/boss/versusscreen.anm2"; constexpr const char* OLD_ROOM_SURFACE = "Old Room Surface"; constexpr const char* NEW_ROOM_SURFACE = "New Room Surface"; constexpr const char* ANIMATION_DEATH_TELEPORT = "DeathTeleport"; -constexpr KColor WHITE = kcolor_rgba(1, 1, 1, 1); constexpr int PIXELATION_DURATION = 30; constexpr int WALK_DURATION = 7; constexpr int UNDIRECTED_DURATION = 3; constexpr int SOUND_MIRROR_ENTER = 608; constexpr int SOUND_MIRROR_EXIT = 609; -constexpr int MIRROR_DIMENSION = 1; constexpr std::string_view ANIMATION_DEATH_SUFFIX = "Death"; constexpr const char* ANIMATION_TELEPORT_DOWN = "TeleportDown"; constexpr const char* ANIMATION_PICKUP = "Pickup"; @@ -33,7 +33,6 @@ constexpr const char* ANIMATION_PICKUP_SPARKLE = "PlayerPickupSparkle"; constexpr const char* EVENT_POOF = "Poof"; constexpr int SLOWEST_FRAME_UNSET = 1000; constexpr int FOLLOW_MIN_FRAME = 6; -constexpr float RANDOM_UNIT = 2.3283064e-10f; constexpr float RANDOM_PI = 3.14f; constexpr float MINECART_JITTER = 8; constexpr int VERSUS_FIRE_BLOCK_FRAMES = 10; @@ -49,10 +48,8 @@ constexpr float APPEAR_FRAME = 2; constexpr float SCREEN_CELL_SIZE = 26; constexpr int ROOM_CELLS_ACROSS = 13; constexpr int ROOM_CELLS_DOWN = 7; -constexpr int DEATH_CERTIFICATE_DIMENSION = 2; constexpr float TELEPORTER_SCATTER = 10; constexpr int DOGMA_ROOM_VARIANT = 1000; -constexpr uint32_t BOSS_DOGMA = 99; // The items whose pickup animation an extra life plays once the player is back, from the Ankh to Lazarus' Rags: Ankh, // Dead Cat, 1up!, Guppy's Collar, Judas' Shadow and Lazarus' Rags. @@ -127,7 +124,7 @@ void RoomTransition::start(const RoomTransitionRequest& request) duration = direction != DIRECTION_NONE ? WALK_DURATION : UNDIRECTED_DURATION; if (animation != TRANSITION_FADE_MIRROR) return; - int sound = request.dimension != MIRROR_DIMENSION ? SOUND_MIRROR_EXIT : SOUND_MIRROR_ENTER; + int sound = request.dimension != DIMENSION_MIRROR ? SOUND_MIRROR_EXIT : SOUND_MIRROR_ENTER; seed_fart_sound_override(&sound); g_manager->sfxManager.Play(sound); } @@ -210,7 +207,7 @@ static void teleporter_arrival_place(Room& room, int target) for (Entity_Player* player : players.playerList) { if (player == traveller) continue; - float angle = (float)Random() * RANDOM_UNIT * RANDOM_PI; + float angle = random_unit() * RANDOM_PI; angle += angle; float x = std::cos(angle) * TELEPORTER_SCATTER + at.x; float y = std::sin(angle) * TELEPORTER_SCATTER + at.y; @@ -246,7 +243,7 @@ void RoomTransition::arrival_place() Entity_Player& player = *game.playerManager.roomTransitionPlayer; player.Teleport(player.forgottenBodyPos, false, false); } - else if (animation == TRANSITION_DEATH_CERTIFICATE && game.currentDimensionIdx == DEATH_CERTIFICATE_DIMENSION) + else if (animation == TRANSITION_DEATH_CERTIFICATE && game.currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE) reconstruction_missing("RoomTransition::ChangeRoom 00830950: the players placed on the Death Certificate floor"); else if (animation == TRANSITION_DEATH_CERTIFICATE) for (Entity_Player* player : game.playerManager.playerList) @@ -380,8 +377,8 @@ void RoomTransition::start_update(Entity_NPC* minecartNpc) idlePlayer->moveToTarget = slowestPlayer->moveToTarget; if (animation == TRANSITION_MINECART && minecartNpc) { - float angle = (float)Random() * RANDOM_UNIT * RANDOM_PI * 2; - float reach = (float)Random() * RANDOM_UNIT * MINECART_JITTER; + float angle = random_unit() * RANDOM_PI * 2; + float reach = random_unit() * MINECART_JITTER; idlePlayer->moveToTarget = vector_make(reach * std::cos(angle) + minecartNpc->targetPosition.x, reach * std::sin(angle) + minecartNpc->targetPosition.y); } diff --git a/src/room_update.cpp b/src/room_update.cpp index c07fd11..8c14d7b 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -4,8 +4,10 @@ #include "entity_pickup.h" #include "entity_player.h" #include "game.h" +#include "grid_entity.h" #include "grid_entity_door.h" #include "grid_entity_pit.h" +#include "level.h" #include "log.h" #include "manager.h" #include "room.h" @@ -24,7 +26,6 @@ constexpr int GRID_PATH_DECAY_FRAMES = 3; constexpr int GRID_PATH_PERMANENT = 3999; constexpr int GRID_PATH_RESET = 900; constexpr int GRID_PATH_DECAY_MAX = 100; -constexpr int GRID_PATH_UNIT = 1000; constexpr int GRID_TIMER_MAX = 99; // The frames a room waits once its enemies are gone before it counts as cleared (a crawlspace's exit room longer). @@ -52,7 +53,6 @@ constexpr float DUNGEON_LADDER_RIGHT = 140; constexpr uint32_t DUNGEON_BLACK_MARKET_DOOR = 1u << DIRECTION_RIGHT; constexpr int ROOM_PASSAGE_IDX = -14; constexpr int ROOM_PASSAGE_EXIT_IDX = -15; -constexpr int ROOM_INDEX_OTHER_DIMENSION = -100; constexpr uint64_t GAME_STATE_ANGEL_ROOM_SPAWNED = 1ull << 0; constexpr uint64_t GAME_STATE_DEVIL_ROOM_SPAWNED = 1ull << 5; @@ -152,7 +152,6 @@ constexpr int SOUND_BOSS_ROAR = 190; constexpr int SOUND_THUNDER = 472; constexpr int SOUND_ALARM = 460; constexpr int PLAYER_THE_FORGOTTEN_B = 35; -constexpr int DIMENSION_DEATH_CERTIFICATE = 2; constexpr int BOSS_MIN_MIN = 91; constexpr int ROOM_IDX_DUNGEON_BEAST = -16; constexpr int GREED_LAST_STAGE = 5; @@ -286,7 +285,7 @@ void Room::grid_paths_decay() for (int i = 0; i < gridWidth * gridHeight; i++) { int path = gridPaths[i]; - int fade = path % GRID_PATH_UNIT; + int fade = path % GRID_PATH_BAND; if (path == GRID_PATH_PERMANENT) gridPaths[i] = GRID_PATH_RESET; else if (fade < GRID_PATH_RESET) gridPaths[i] = path - std::min(fade, GRID_PATH_DECAY_MAX); @@ -372,18 +371,18 @@ static void deaths_list_update(Room& room) // 00823080 Fires an output group: the grid entities on its cells, its 1000.120 effects (which then die) and its // callbacks. // The callbacks are not reconstructed yet. -static void output_trigger(Room& room, int group) +void Room::TriggerOutput(int group) { - for (int gridIndex : room.outputGroupGridIndices[group]) - if (room.gridEntities[gridIndex]) room.gridEntities[gridIndex]->trigger_output(); - for (Entity* entity : room.entityList.updateEL) + for (int gridIndex : outputGroupGridIndices[group]) + if (gridEntities[gridIndex]) gridEntities[gridIndex]->trigger_output(); + for (Entity* entity : entityList.updateEL) { if (entity->type != ENTITY_EFFECT || entity->variant != 120 || entity->subtype != group) continue; entity->isDead = true; entity->Update(); } - if (!room.outputGroupCallbacks[group].empty()) reconstruction_missing("Room::TriggerOutput 00823080: callbacks"); + if (!outputGroupCallbacks[group].empty()) reconstruction_missing("Room::TriggerOutput 00823080: callbacks"); } // The clear check: while enemies or Greed's wave are left (or an ambush runs) the room holds off clearing; once the @@ -396,7 +395,7 @@ static void clear_update(Room& room) int dungeonKind = isDungeon ? room.descriptor->data->subtype : 0; if (!room.IsClear() && !game.ambush.isActive && !isEnemyLeft && room.roomClearDelay < 1) - output_trigger(room, OUTPUT_GROUP_ROOM_CLEAR); + room.TriggerOutput(OUTPUT_GROUP_ROOM_CLEAR); if (game.ambush.isActive || isEnemyLeft) { room.roomClearDelay = isDungeon && dungeonKind == DUNGEON_ROTGUT_HEART ? ROOM_CLEAR_DELAY_DUNGEON_EXIT diff --git a/src/sfx_manager.h b/src/sfx_manager.h index f64879c..d6fe82f 100644 --- a/src/sfx_manager.h +++ b/src/sfx_manager.h @@ -147,6 +147,11 @@ enum SoundId : int SOUND_ERROR_BUZZ = 187, SOUND_GOLDENKEY = 204, SOUND_GOOATTACH0 = 205, + SOUND_MAW_OF_VOID = 426, + SOUND_BUTTON_PRESS = 469, + SOUND_PUNCH = 478, + SOUND_LINGER_BEAN = 860, + SOUND_GOODEATH = 207, SOUND_SATAN_HAND_LASER = 211, SOUND_HEARTIN = 212, SOUND_HEARTOUT = 213, @@ -216,6 +221,7 @@ enum SoundId : int SOUND_THE_STAIN_BURST = 419, SOUND_BONE_SNAP = 462, SOUND_BONE_DROP = 467, + SOUND_BONE_BREAK = 500, SOUND_BONE_BOUNCE = 499, SOUND_TOOTH_AND_NAIL = 506, SOUND_SHOVEL_DIG = 464, @@ -231,6 +237,7 @@ enum SoundId : int SOUND_FREEZE = 496, SOUND_FREEZE_SHATTER = 498, SOUND_RECALL_FINISH = 584, + SOUND_JELLY_BOUNCE = 588, SOUND_POOP_LASER = 589, SOUND_EDEN_GLITCH = 595, SOUND_RAILROAD_TRACK_RAISE = 596, @@ -361,6 +368,7 @@ enum SoundId : int SOUND_POISON_HURT = 591, SOUND_POISON_MIND_HURT = 1081, SOUND_BUTTLICKER_GROWL = 1085, + SOUND_LADDER = 1086, SOUND_POT_BREAK = 138, SOUND_SWORD_SPIN = 538, SOUND_CUBE_BABY_KICK = 852, @@ -396,6 +404,10 @@ enum SoundId : int SOUND_LAZARUS_FLIP_DEAD = 582, SOUND_LAZARUS_FLIP_ALIVE = 583, SOUND_BERSERK_START = 592, + SOUND_DIVINE_INTERVENTION = 568, + SOUND_BERSERK_TICK = 593, + SOUND_BERSERK_END = 594, + SOUND_SHARP_PLUG = 906, SOUND_ISAAC_ROAR = 650, SOUND_ANIMA_TRAP = 611, SOUND_ANIMA_BREAK = 613, @@ -446,7 +458,11 @@ enum SoundId : int SOUND_BOOMERANG_LOOP = 837, SOUND_BOOMERANG_CATCH = 838, SOUND_BOOMERANG_HIT = 839, + SOUND_FRIENDLYBALL_CAPTURE = 1019, + SOUND_FRIENDLYBALL_LAND = 1020, + SOUND_FRIENDLYBALL_PICKUP = 1021, SOUND_FRIENDLYBALL_RAISE = 1022, + SOUND_FRIENDLYBALL_RELEASE = 1023, SOUND_FRIENDLYBALL_THROW = 1024, SOUND_DECAP_THROW = 1047, SOUND_BLACK_HOLE_THROW = 1068, @@ -498,7 +514,11 @@ enum SoundId : int SOUND_REVERSE_EXPLOSION = 511, SOUND_BEAST_LAVABALL_RISE = 814, SOUND_DOGMA_JACOBS_ZAP = 551, - SOUND_DOGMA_JACOBS_DOT = 557 + SOUND_DOGMA_JACOBS_DOT = 557, + SOUND_DOGMA_BLACKHOLE_OPEN = 545, + SOUND_DOGMA_BLACKHOLE_CLOSE = 546, + SOUND_DOGMA_LIGHT_RAY_CHARGE = 563, + SOUND_DOGMA_LIGHT_RAY_FIRE = 564 }; // Construction, copies and destruction (00a2a990, 00a2aa60, 00a2ab40, 00a2ac90) are the defaults. diff --git a/src/stage_transition.cpp b/src/stage_transition.cpp index 88a8ec2..e6fddca 100644 --- a/src/stage_transition.cpp +++ b/src/stage_transition.cpp @@ -45,7 +45,6 @@ constexpr float SPLASH_SPEED = 8; constexpr float SPLASH_FALL = 1; constexpr float SPLASH_LIFT = -8; constexpr float SPLASH_LIFT_SPREAD = 4; -constexpr float RANDOM_UNIT = 2.3283064e-10f; constexpr float RANDOM_PI = 3.14f; constexpr float LIGHT_SCALE_LIMIT = 2; @@ -201,9 +200,9 @@ static void trapdoor_splash(GridEntity& trapDoor) for (int i = 0; i < drops; i++) { uint32_t seed = Random(); - float angle = (float)Random() * RANDOM_UNIT * RANDOM_PI; + float angle = random_unit() * RANDOM_PI; angle += angle; - float speed = (float)Random() * RANDOM_UNIT * SPLASH_SPEED; + float speed = random_unit() * SPLASH_SPEED; auto* drop = static_cast( exit_effect_spawn({.position = room.GetGridPosition(trapDoor.gridIndex), .velocity = vector_make(std::cos(angle) * speed, speed * std::sin(angle)), @@ -213,7 +212,7 @@ static void trapdoor_splash(GridEntity& trapDoor) .seed = seed})); drop->fallingAcceleration = SPLASH_FALL; drop->sprite.scale = vector_scale(drop->sprite.scale, 2); - drop->fallingSpeed = SPLASH_LIFT - (float)Random() * RANDOM_UNIT * SPLASH_LIFT_SPREAD; + drop->fallingSpeed = SPLASH_LIFT - random_unit() * SPLASH_LIFT_SPREAD; drop->Update(); } } diff --git a/src/tainted_characters.cpp b/src/tainted_characters.cpp index 1f79a87..b5dbc16 100644 --- a/src/tainted_characters.cpp +++ b/src/tainted_characters.cpp @@ -161,7 +161,7 @@ void abyss_use(ItemUse& use) } PlayerManager& players = g_game->playerManager; - for (Entity* entity : g_game->room->GetEntities()->updateEL) + for (Entity* entity : std::vector(g_game->room->GetEntities()->updateEL)) { if (entity->type != ENTITY_PICKUP || entity->isDead) continue; auto& pickup = static_cast(*entity); diff --git a/src/weapon.cpp b/src/weapon.cpp index 0ee601c..05ba27f 100644 --- a/src/weapon.cpp +++ b/src/weapon.cpp @@ -37,7 +37,6 @@ constexpr float INHERIT_SCALE = 0.6f; constexpr float IPECAC_SPEED_MIN = 0.9f; constexpr float IPECAC_SPEED_RANGE = 0.2f; constexpr float PEE_SPREAD = 24; -constexpr float FULL_TURN = 360; constexpr float CHOCOLATE_MILK_CHARGE = 2.5f; constexpr float CHOCOLATE_MILK_DAMAGE_MIN = 0.1f; constexpr float CHOCOLATE_MILK_DAMAGE_MAX = 4; @@ -1056,7 +1055,7 @@ void Weapon_Tears::Fire(const Vector& shootDirection, bool isShooting, bool isIn extra_fire(vector_make(base.y, -base.x)); } for (int i = 0; i < params.numRandomDirTears; i++) - extra_fire(vector_rotated(base, random_unit() * FULL_TURN)); + extra_fire(vector_rotated(base, random_unit() * FULL_TURN_DEGREES)); if (eyeSide != 0) { diff --git a/src/weapon_urn_of_souls.cpp b/src/weapon_urn_of_souls.cpp index fb0a7f7..6e8e36d 100644 --- a/src/weapon_urn_of_souls.cpp +++ b/src/weapon_urn_of_souls.cpp @@ -86,13 +86,6 @@ void Weapon_UrnOfSouls::ClearReferences() g_manager->sfxManager.Stop(SOUND_FLAMETHROWER_LOOP); } -// The stage the flames grow with: one more on the alternate path, as 004360f0 counts it. -static int flame_stage() -{ - bool isAltPath = g_game->stageType == STAGETYPE_REPENTANCE || g_game->stageType == STAGETYPE_REPENTANCE_B; - return g_game->stage + (isAltPath ? 1 : 0); -} - // Where the urn points: the shot, the last aim, else the player's head (a familiar's shot direction). Without an owner // the original reads nothing safe: it keeps the zero aim. Vector Weapon_UrnOfSouls::aim_get(const Vector& shootDirection) @@ -194,7 +187,7 @@ void Weapon_UrnOfSouls::flame_fire(const Vector& aim) shielded.set(TEAR_SHIELDED); if (urn->subtype == 1) { - float damage = ((float)flame_stage() * FLAME_DAMAGE_PER_STAGE + FLAME_LASER_DAMAGE_BASE) * + float damage = ((float)g_game->stage_depth_get() * FLAME_DAMAGE_PER_STAGE + FLAME_LASER_DAMAGE_BASE) * FLAME_LASER_DAMAGE_SCALE * growth; if (!flameLaser) { @@ -237,7 +230,7 @@ void Weapon_UrnOfSouls::flame_fire(const Vector& aim) flame.tearRange = FLAME_RANGE; if (flame.dropRNG.RandomInt(FLAME_SHIELDED_CHANCE) == 0) flame.SetTearFlags(flame.tearFlags | shielded); flame.mass = 0; - float damage = ((float)flame_stage() * FLAME_DAMAGE_PER_STAGE + FLAME_DAMAGE_BASE) * growth; + float damage = ((float)g_game->stage_depth_get() * FLAME_DAMAGE_PER_STAGE + FLAME_DAMAGE_BASE) * growth; float scale = std::max(intensity * FLAME_RAMP_SCALE + FLAME_SCALE_MIN, TEAR_SCALE_MIN); flame.baseScale = scale; flame.fScale = scale;