diff --git a/generated-src/classes.h b/generated-src/classes.h index baee98e..dea32b6 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -120,6 +120,7 @@ struct AbyssLocustData; struct AchievementEntry; struct AchievementOverlay; struct AchievementOverlay_Entry; +struct ActionGlyph; struct ActiveGain; struct ActiveItemDesc; struct ActiveUse; @@ -140,11 +141,13 @@ struct BackdropConfig; struct BackwardsStageDesc; struct BeamPoint; struct BeamRenderer; +struct BeamVolley; struct BeastArena; struct BezierPoint; struct BitSet128; struct BlendMode; struct BombCostumeRule; +struct BoomerangLoop; struct BossId; struct BossOverlay; struct BossOverlayEntry; @@ -218,6 +221,7 @@ struct DebugRenderer; struct DeliriousBoss; struct DestinationQuad; struct Devolve; +struct DimensionReturn; struct DreamCatcherPage; struct EffectBehaviour; struct EmoteWheel; @@ -395,6 +399,7 @@ struct KnifeShot; struct KnifeThrow; struct LRoomAreaDesc; struct LRoomTileDesc; +struct LaserCarry; struct LaserShot; struct LaserVolley; struct LayerAnimation; @@ -519,11 +524,13 @@ struct PlayerHUDTrinket; struct PlayerManager; struct PlayerProceduralItems; struct PlayerTrail; +struct PlayerTypeIcon; struct PngWriter; struct PocketItem; struct PocketItemConfig; struct PocketUse; struct Point; +struct PoisonSplash; struct PoolDesc; struct PoolItem; struct PoopHit; @@ -592,6 +599,7 @@ struct SavedRoom; struct ScoreRecord; struct ScoreSheet; struct Seeds; +struct SegmentPair; struct SegmentProjection; struct Shader; struct Shape; @@ -662,6 +670,8 @@ struct WalkAnims; struct WallDetail; struct WallSlot; struct WaterClipInfo; +struct WaveChain; +struct WaveChainData; struct Weapon; struct WeaponDelete; struct Weapon_Bombs; @@ -3257,12 +3267,6 @@ struct Menu_ModChallenges { }; -struct Menu_Mods { - void Update(); // 008e3830 - void reset(); // 008e4970 -}; - - struct Menu_Online { static void render_mode_select(); // 008cc1a0 void Update(); // 008e4b10 @@ -5647,7 +5651,6 @@ uint32_t FUN_0042cef0(); // 0042cef0 long double FUN_0042cf00(); // 0042cf00 void FUN_0042cf10(Entity_Player *param_1, uint32_t param_2); // 0042cf10 int FUN_0042d040(); // 0042d040 -void get_netplay_player_color(void *self, ColorMod *outColor, Entity_Player *player); // 0042d060 uint32_t FUN_0042d1b0(); // 0042d1b0 void FUN_0042d5f0(Entity_Player *param_1, uint32_t param_2); // 0042d5f0 uint32_t FUN_0042d660(); // 0042d660 @@ -5721,7 +5724,6 @@ void FUN_00436200(uint32_t param_1); // 00436200 void FUN_00436210(uint32_t param_1); // 00436210 void FUN_00436fb0(); // 00436fb0 void FUN_0043e990(RNG *param_1); // 0043e990 -void FUN_0043e9f0(); // 0043e9f0 void FUN_0043ed20(uint32_t *param_1, int *param_2); // 0043ed20 void FUN_0043edf0(uint32_t param_1, uint32_t param_2, uint32_t *param_3); // 0043edf0 void FUN_0043eea0(uint32_t param_1); // 0043eea0 @@ -5800,7 +5802,6 @@ void FUN_004b6fc0(uint32_t *param_1); // 004b6fc0 void FUN_004b7020(uint32_t *param_1); // 004b7020 void FUN_004b7070(uint32_t param_1); // 004b7070 uint32_t FUN_004b7090(); // 004b7090 -Entity * FUN_004bb230(); // 004bb230 uint32_t FUN_004bc660(); // 004bc660 void FUN_004bfd20(); // 004bfd20 void FUN_004c5850(uint8_t *param_1); // 004c5850 @@ -5854,7 +5855,6 @@ void FUN_00571230(void *param_1, int param_2); // 00571230 void FUN_005729a0(int *param_1); // 005729a0 void FUN_00572c10(int param_1); // 00572c10 uint32_t * FUN_00575fe0(int *param_1, uint32_t param_2, uint32_t param_3, uint32_t param_4, uint32_t param_5, uint32_t param_6, int *param_7, uint32_t param_8, uint32_t param_9); // 00575fe0 -void FUN_005784e0(); // 005784e0 void FUN_00579700(); // 00579700 uint32_t FUN_00579760(); // 00579760 void FUN_0057be30(uint32_t param_1); // 0057be30 @@ -5872,22 +5872,11 @@ void FUN_00586b50(float *param_1, float param_2); // 00586b50 uint32_t FUN_0058ab60(); // 0058ab60 uint8_t FUN_0058e210(); // 0058e210 void FUN_0058e240(uint32_t param_1); // 0058e240 -void FUN_00598260(Vector *param_1); // 00598260 uint32_t * FUN_00598290(uint32_t *param_1, uint32_t *param_2); // 00598290 void FUN_005a6fb0(); // 005a6fb0 -uint8_t FUN_005a7570(); // 005a7570 -void FUN_005aae10(); // 005aae10 uint8_t * FUN_005aaf60(uint8_t *param_1); // 005aaf60 -void FUN_005aafd0(float *param_1); // 005aafd0 -void FUN_005ab0b0(int param_1); // 005ab0b0 -void FUN_005ab3e0(); // 005ab3e0 -void FUN_005acb70(int param_1); // 005acb70 void FUN_005acbf0(int param_1); // 005acbf0 -int FUN_005acc70(); // 005acc70 -int FUN_005accb0(); // 005accb0 -int FUN_005accf0(); // 005accf0 int FUN_005acd10(); // 005acd10 -void FUN_005ad1c0(); // 005ad1c0 void FUN_005b1490(uint32_t param_1, uint32_t param_2); // 005b1490 void FUN_005b1560(); // 005b1560 void FUN_005b15a0(uint32_t param_1); // 005b15a0 @@ -6056,17 +6045,11 @@ void FUN_0060d1f0(uint32_t param_1); // 0060d1f0 void FUN_0060d400(); // 0060d400 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 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 FUN_0064b6a0(); // 0064b6a0 -int FUN_0064ccf0(); // 0064ccf0 -int level_get_room_neighbors(uint32_t roomIndex, uint32_t *outNeighbors); // 0064cd30 -int star_of_bethlehem_get_target_room(); // 0064d370 void FUN_0064d570(uint32_t param_1); // 0064d570 int apply_forgotten_lullaby(void *self, int fireDelay); // 00651810 int FUN_006518d0(uint32_t param_1); // 006518d0 @@ -6536,8 +6519,6 @@ int FUN_007919c0(); // 007919c0 Entity_Player * FUN_007a0fe0(); // 007a0fe0 Entity_Player * FUN_007a1020(); // 007a1020 uint32_t FUN_007ab0e0(); // 007ab0e0 -void FUN_007ad610(); // 007ad610 -uint32_t FUN_007ad720(uint32_t param_1, uint8_t *param_2); // 007ad720 void FUN_007b8c00(int param_1); // 007b8c00 void FUN_007c2e80(); // 007c2e80 void FUN_007cb4f0(); // 007cb4f0 @@ -6545,7 +6526,6 @@ void FUN_007cf940(); // 007cf940 long double FUN_007cf9a0(float *param_1, KColor *param_2, uint32_t param_3); // 007cf9a0 uint8_t * FUN_007cfa90(); // 007cfa90 void FUN_007d3330(int param_1); // 007d3330 -void FUN_007d3e00(); // 007d3e00 void FUN_007d9360(); // 007d9360 uint32_t FUN_007d9ca0(); // 007d9ca0 uint32_t FUN_007da770(); // 007da770 @@ -6713,7 +6693,6 @@ void FUN_00839b40(); // 00839b40 void render_beast_arena_background(void *self, int pass); // 0083a3d0 void FUN_0083aae0(uint8_t param_1, int *param_2, uint32_t *param_3); // 0083aae0 void FUN_0083b830(); // 0083b830 -int FUN_0083bbc0(int param_1); // 0083bbc0 void FUN_0083bf50(); // 0083bf50 void FUN_0083bf90(uint32_t *param_1); // 0083bf90 void Catch_All_0083c241(); // 0083c241 @@ -6731,7 +6710,6 @@ void Catch_All_0084be32(); // 0084be32 uint32_t * FUN_0084be60(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3); // 0084be60 void FUN_0084bef0(uint32_t *param_1, void *param_2); // 0084bef0 void FUN_0084bf20(); // 0084bf20 -uint8_t segment_intersect(float *outX, float *outY, float p1x, float p1y, float p2x, float p2y, float q1x, float q1y, float q2x, float q2y); // 0084d8b0 void FUN_0084db90(); // 0084db90 void FUN_00856280(void *param_1); // 00856280 void FUN_00856330(); // 00856330 @@ -8920,7 +8898,6 @@ void ** vector_LaserSample_erase(void *self, void **outIter, void *where); // 0 void FUN_009a1770(uint32_t *param_1); // 009a1770 void * vector_LaserSample_emplace_reallocate(void *self, void *where, void *value); // 009a17b0 void FUN_009a1940(uint32_t *param_1, uint32_t *param_2, int param_3); // 009a1940 -void FUN_009a3560(); // 009a3560 float * FUN_009a6320(float *param_1, int param_2, int param_3); // 009a6320 void FUN_009a8a40(); // 009a8a40 void _player_hud_set_heart_anim_state(int param_1); // 009a90b0 @@ -8941,8 +8918,6 @@ void Catch_All_009b1d88(); // 009b1d88 int FUN_009b1dc0(int param_1, int param_2, int param_3); // 009b1dc0 int FUN_009b5800(); // 009b5800 uint32_t FUN_009b9450(int param_1); // 009b9450 -void FUN_009b9f60(Entity *param_1); // 009b9f60 -void FUN_009b9fc0(int param_1); // 009b9fc0 void FUN_009ba9a0(); // 009ba9a0 void FUN_009baa10(char param_1); // 009baa10 int FUN_009bac00(int param_1); // 009bac00 @@ -9011,7 +8986,6 @@ void FUN_009e24f0(uint32_t *param_1, uint32_t param_2); // 009e24f0 void FUN_009e2520(void *param_1); // 009e2520 void FUN_009e2580(int *param_1, uint32_t *param_2); // 009e2580 int * FUN_009e2760(int *param_1, uint32_t *param_2); // 009e2760 -uint8_t room_grid_flood_fill(void *self, uint32_t startIndex, uint32_t targetIndex); // 009e3560 int FUN_009e3d30(); // 009e3d30 void FUN_009e3d60(); // 009e3d60 int get_rich_presence_room_status(); // 009e5000 @@ -9088,7 +9062,6 @@ uint32_t * FUN_009f2410(uint32_t *param_1); // 009f2410 void FUN_009f2480(); // 009f2480 void * map_int_ImagePtr_subscript(void *self, int *key); // 009f2e20 void FUN_009f3c10(); // 009f3c10 -void FUN_009f3c40(); // 009f3c40 void FUN_009f4130(); // 009f4130 void FUN_009f5810(uint8_t param_1); // 009f5810 uint32_t * FUN_009f93d0(); // 009f93d0 @@ -20738,17 +20711,6 @@ void FUN_00d2bae0(); // 00d2bae0 namespace AudioPacketQueue { void destroyAllAudioPackets(); // 00aadc80 } -namespace FamiliarAI { -void variant_66(Entity_Familiar *familiar); // 0061c3f0 -void lil_haunt(Entity_Familiar *familiar, int unused); // 0061d030 -void lil_spewer(Entity_Familiar *familiar); // 006384a0 -Entity_Knife * sprinkler_spawn_knife(Entity_Familiar *familiar); // 0063b070 -void star_of_bethlehem(Entity_Familiar *familiar); // 0064d5f0 -} -namespace FamiliarHelper { -Entity_Laser * sprinkler_fire_laser(Entity_Familiar *familiar, float angle, float distance); // 0063acf0 -void fly_head_pathfind_move(Entity_Familiar *familiar); // 0063d570 -} namespace Isaac { void SwapANM2(ANM2 *left, ANM2 *right); // 00407ae0 ItemConfig * GetItemConfig(); // 0042ca00 @@ -20801,29 +20763,10 @@ void ENTITY_BUMBINO(Entity_NPC *npc); // 00499de0 void ENTITY_CHIMERA_head_update(Entity_NPC *npc); // 0049cd90 void ENTITY_CHIMERA_body(Entity_NPC *npc); // 0049d130 uint32_t ENTITY_CHIMERA(Entity_NPC *npc); // 0049fa10 -void ENTITY_CLOG(Entity_NPC *npc); // 004a12f0 -void ENTITY_DOGMA_update_distortion(Entity_NPC *npc); // 004aaef0 -void ENTITY_DOGMA(Entity_NPC *npc); // 004aafa0 -void ENTITY_DOGMA_angel(Entity_NPC *npc); // 004ae4d0 -Vector * ENTITY_DOGMA_angel_baby(Entity_NPC *npc); // 004b0200 -void ENTITY_DOGMA_tv(Entity_NPC *npc); // 004b0a30 -void ENTITY_HORNFEL_DOOR(Entity_NPC *npc); // 004bb9b0 void ENTITY_MATRIARCH(Entity_NPC *npc); // 004c59d0 -void ENTITY_MOMS_HEART_mausoleum_death(Entity_NPC *npc); // 004d64f0 -void ENTITY_UNBORN(Entity_NPC *npc); // 004dca90 -void ENTITY_CHARGER_L2(Entity_NPC *npc); // 004e38c0 -void ENTITY_BALL_AND_CHAIN(Entity_NPC *npc); // 004f4730 void ENTITY_BUTT_SLICKER(Entity_NPC *npc); // 0054d250 -void ENTITY_COHORT(Entity_NPC *npc); // 005513a0 -void ENTITY_BLOOD_PUPPY(Entity_NPC *npc); // 00552d30 -int ENTITY_WILLO_L2_find_target(Entity_NPC *npc); // 005591c0 -void ENTITY_WILLO_L2(Entity_NPC *npc); // 005593c0 uint32_t ENTITY_POLTY(Entity_NPC *npc); // 0055d230 -void ENTITY_FISSURE(Entity_NPC *npc); // 00564f30 -void ENTITY_MOTHERS_SHADOW(Entity_NPC *npc); // 0056ffa0 void ENTITY_CLUTCH(Entity_NPC *npc); // 00573030 -void ENTITY_RAGLICH(Entity_NPC *npc); // 005769b0 -void ENTITY_RAINMAKER(Entity_NPC *npc); // 00578a70 void ENTITY_SCOURGE_chain(Entity_NPC *npc); // 00584140 void ENTITY_SCOURGE_main(Entity_NPC *npc); // 005864b0 void ENTITY_SCOURGE_projectile_attack(Entity_NPC *npc); // 00586c40 @@ -20834,15 +20777,6 @@ void ENTITY_SIREN_main(Entity_NPC *npc); // 0058ec70 void siren_release_stolen_items(Entity_NPC *npc); // 005911b0 void ENTITY_SIREN(Entity_NPC *npc); // 00591460 void ENTITY_SIREN_HELPER(Entity_NPC *npc); // 00591cc0 -void ENTITY_BEAST_spawn_background(Entity_NPC *npc); // 00592280 -void ENTITY_BEAST(Entity_NPC *npc); // 00592460 -void ENTITY_BEAST_stalactite(Entity_NPC *npc); // 00596120 -void ENTITY_BEAST_rock_projectile(Entity_NPC *npc); // 00596c60 -void ENTITY_BEAST_soul(Entity_NPC *npc); // 005971e0 -void ENTITY_VISAGE(Entity_NPC *npc); // 005a7b20 -void ENTITY_VISAGE_mask(Entity_NPC *npc); // 005ab4d0 -void ENTITY_VISAGE_chain(Entity_NPC *npc); // 005ad250 -void ENTITY_VISAGE_plasma(Entity_NPC *npc); // 005ad8a0 } namespace OnlinePlayerInfo { void render_items(float *param_1); // 008d4940 @@ -20868,9 +20802,6 @@ uint32_t _seekPage(int param_1, char param_2); // 00a8e1b0 namespace _Entity { int GetAncestorField(uint32_t param_1); // 006b7d20 } -namespace _NpcHelper { -uint32_t spider_load_graphics(uint8_t *param_1); // 006baa70 -} namespace luabridge::CFunc { uint32_t readOnlyError(uint32_t param_1); // 0085cad0 } diff --git a/generated-src/menu_mods.cpp b/generated-src/menu_mods.cpp deleted file mode 100644 index b6f3077..0000000 --- a/generated-src/menu_mods.cpp +++ /dev/null @@ -1,304 +0,0 @@ -#include "classes.h" - -// 008e3830 -void Menu_Mods::Update() -{ - char isActionTriggered; - uint8_t isDisableFileExists; - char *modPath; - uint32_t *puVar1; - uint8_t ****ppppbVar2; - LayerState *widgetTabLayer; - uint8_t *modsDirEnd; - void *freeBlock; - int lastModIndex; - uint32_t freeSize; - uint32_t heldUpAction; - uint32_t menuUpAction; - uint32_t confirmAction; - uint32_t local_78; - int local_74; - uint8_t isWidgetTabVisible; - void *local_6c; - uint32_t local_5c; - uint32_t local_58; - void *modsDir [4]; - uint32_t local_44; - uint32_t local_40; - uint8_t ****disableFilePath; - uint32_t uStack_38; - uint32_t uStack_34; - uint32_t uStack_30; - uint64_t local_2c; - uint32_t local_24; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - void *local_14; - Manager *manager; - uint32_t modEntry; - uint8_t *modsDirNext; - int selectedMod; - - manager = g_manager; - puStack_20 = GHIDRA_CAST((modsDir + 0x14)); - local_14 = (void *)0xffffffff; - puStack_18 = &LAB_00b0691d; - local_1c = ExceptionList; - local_24 = __security_cookie ^ GHIDRA_UINT((modsDir + 0x11)); - ExceptionList = &local_1c; - confirmAction = 0xe; - isActionTriggered = - (**(code **)(PTR_vftable_00c57b18 + 0x74)) - (0xffffffff,FUN_00a209e0,&confirmAction,0,0,local_24); - if (isActionTriggered == '\0') { - menuUpAction = 0x16; - isActionTriggered = - (**(code **)(PTR_vftable_00c57b18 + 0x74))(0xffffffff,FUN_00a20940,&menuUpAction,0,0); - if (isActionTriggered == '\0') { - local_78 = 0x17; - isActionTriggered = - (**(code **)(PTR_vftable_00c57b18 + 0x74))(0xffffffff,FUN_00a20940,&local_78,0,0); - if (isActionTriggered == '\0') { - local_74 = 0xf; - isActionTriggered = - (**(code **)(PTR_vftable_00c57b18 + 0x74))(0xffffffff,FUN_00a209e0,&local_74,0,0); - if (isActionTriggered == '\0') { - local_74 = 0x1c; - isActionTriggered = - (**(code **)(PTR_vftable_00c57b18 + 0x74))(0xffffffff,FUN_00a209e0,&local_74,0,0); - if (isActionTriggered != '\0') { - (g_manager->_optionsConfig)._enableMods = (g_manager->_optionsConfig)._enableMods == 0; - (*GHIDRA_CAST((GHIDRA_CAST(&(this[0x61])) + 0x1))) = 1; - } - } - else { - FUN_0098aec0(); - } - } - else if (((g_manager->_optionsConfig)._enableMods != 0) && - ((selectedMod = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))), selectedMod == 0 || - ((0x31 < selectedMod && (selectedMod % 10 == 0)))))) { - selectedMod = *GHIDRA_CAST(this); - *GHIDRA_CAST(this) = selectedMod + 1; - if (selectedMod + 1 < *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((manager)) + 0x2a6c4)))) - manager->_modManager >> 2) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))) + 4; - } - else { - *GHIDRA_CAST(this) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))) = manager->_modManager; - } - } - } - else if (((g_manager->_optionsConfig)._enableMods != 0) && - ((selectedMod = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))), selectedMod == 0 || - ((0x31 < selectedMod && (selectedMod % 10 == 0)))))) { - *GHIDRA_CAST(this) = *GHIDRA_CAST(this) + -1; - if (*GHIDRA_CAST(this) < 0) { - lastModIndex = (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((manager)) + 0x2a6c4)))) - manager->_modManager >> 2) + -1; - selectedMod = 0; - if (0 < lastModIndex) { - selectedMod = lastModIndex; - } - *GHIDRA_CAST(this) = selectedMod; - selectedMod = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((manager)) + 0x2a6c4)))); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))) = selectedMod; - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((manager)) + 0x2a6c4)))) - manager->_modManager >> 2 != 0) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))) = selectedMod + -4; - } - } - else { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))) + -4; - } - } - } - else { - if (((g_manager->_optionsConfig)._enableMods == 0) || - (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))) == *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((manager)) + 0x2a6c4)))))) goto LAB_008e3c85; - selectedMod = **GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))); - *GHIDRA_CAST((selectedMod + 0xfc)) = *GHIDRA_CAST((selectedMod + 0xfc)) == '\0'; - modEntry = **GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))); - local_44 = 0; - local_40 = 0xf; - modsDir[0] = (void *)0x0; - modsDirNext = g_modsDirectory; - do { - modsDirEnd = modsDirNext; - modsDirNext = modsDirEnd + 1; - } while (*modsDirEnd != 0); - (GHIDRA_CAST((GHIDRA_CAST(modsDir))))->msvc::string::assign(g_modsDirectory,GHIDRA_UINT((modsDirEnd + -0xc72e28))); - local_14 = (void *)0x0; - modPath = GHIDRA_CAST(FUN_00651d50(modEntry)); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 1; - puVar1 = (GHIDRA_CAST((modPath)))->msvc::string::append(GHIDRA_CAST("/disable.it"),0xb); - disableFilePath = GHIDRA_CAST(*puVar1); - uStack_38 = puVar1[1]; - uStack_34 = puVar1[2]; - uStack_30 = puVar1[3]; - local_2c = *GHIDRA_CAST((puVar1 + 4)); - puVar1[4] = 0; - puVar1[5] = 0xf; - *GHIDRA_CAST(puVar1) = 0; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 3; - if (0xf < local_58) { - freeSize = local_58 + 1; - freeBlock = local_6c; - if (0xfff < freeSize) { - freeBlock = *(void **)(GHIDRA_CAST(local_6c) + -4); - freeSize = local_58 + 0x24; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(local_6c) + (-4 - GHIDRA_INT(freeBlock))))) goto LAB_008e39e8; - } - operator_delete(freeBlock,freeSize); - } - local_5c = 0; - local_58 = 0xf; - local_6c = (void *)(GHIDRA_UINT(local_6c) & 0xffffff00); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x0))) = 4; - if (0xf < local_40) { - freeSize = local_40 + 1; - freeBlock = modsDir[0]; - if (0xfff < freeSize) { - freeBlock = *(void **)(GHIDRA_INT(modsDir[0]) + -4); - freeSize = local_40 + 0x24; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(modsDir[0]) + (-4 - GHIDRA_INT(freeBlock))))) { -LAB_008e39e8: - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(freeBlock,freeSize); - } - local_44 = 0; - local_40 = 0xf; - modsDir[0] = (void *)(GHIDRA_UINT(modsDir[0]) & 0xffffff00); - if (*GHIDRA_CAST((**GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))) + 0xfc)) == '\0') { - ppppbVar2 = GHIDRA_CAST(&disableFilePath); - if (0xf < (*GHIDRA_CAST((GHIDRA_CAST(&(local_2c)) + 0x4)))) { - ppppbVar2 = disableFilePath; - } - puVar1 = (GHIDRA_CAST((&PTR_vftable_00c5aa80)))->SaveDataManager::open_file_write(GHIDRA_CAST(ppppbVar2),0); - if (puVar1 != GHIDRA_CAST(0x0)) { - (**(code **)*puVar1)(1); - } - } - else { - ppppbVar2 = GHIDRA_CAST(&disableFilePath); - if (0xf < (*GHIDRA_CAST((GHIDRA_CAST(&(local_2c)) + 0x4)))) { - ppppbVar2 = disableFilePath; - } - isDisableFileExists = file_exists(GHIDRA_CAST(ppppbVar2)); - if (isDisableFileExists != 0) { - ppppbVar2 = GHIDRA_CAST(&disableFilePath); - if (0xf < (*GHIDRA_CAST((GHIDRA_CAST(&(local_2c)) + 0x4)))) { - ppppbVar2 = disableFilePath; - } - remove(GHIDRA_CAST(ppppbVar2)); - } - } - local_14 = (void *)0xffffffff; - (*GHIDRA_CAST((GHIDRA_CAST(&(this[0x61])) + 0x1))) = 1; - if (0xf < (*GHIDRA_CAST((GHIDRA_CAST(&(local_2c)) + 0x4)))) { - freeSize = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2c)) + 0x4))) + 1; - ppppbVar2 = disableFilePath; - if (0xfff < freeSize) { - ppppbVar2 = GHIDRA_CAST(disableFilePath[-1]); - freeSize = (*GHIDRA_CAST((GHIDRA_CAST(&(local_2c)) + 0x4))) + 0x24; - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST((GHIDRA_INT(disableFilePath) + (-4 - GHIDRA_INT(ppppbVar2))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(ppppbVar2,freeSize); - } - local_2c = 0xf00000000; - disableFilePath = GHIDRA_CAST((GHIDRA_UINT(disableFilePath) & 0xffffff00)); - } -LAB_008e3c85: - local_78 = GHIDRA_UINT(((g_manager->_optionsConfig)._enableMods == 0)); - if ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x16])) + 0x2)))) != 0) && - ((0xc < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x15])) + 0x1)))) + 0x80)) || - (KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")), - 0xc < *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x15])) + 0x1)))) + 0x80)))))) { - selectedMod = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x16])) + 0x2)))); - local_74 = *GHIDRA_CAST((selectedMod + 0x68)); - if ((selectedMod == 0) || ((local_74 < 0 || (*GHIDRA_CAST((selectedMod + 0x1c)) <= local_74)))) { - KAGE_LogMessage(0x10,GHIDRA_CAST("id out of bounds\n")); - } - *GHIDRA_CAST((*GHIDRA_CAST((this + 0x18)) + local_74 * 4)) = 0; - AnimationState::AdvanceLayerPosition - (GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x15])) + 0x1)))),local_74,(float)GHIDRA_INT(local_78)); - } - isWidgetTabVisible = g_menuControllerIndex == 0; - widgetTabLayer = ANM2::GetLayer(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[5])) + 0x1)))),GHIDRA_CAST("WidgetTab")); - widgetTabLayer->_visible = isWidgetTabVisible; - local_74 = 0x17; - isActionTriggered = - (**(code **)(PTR_vftable_00c57b18 + 0x74))(0xffffffff,FUN_00a20940,&local_74,0,0); - if (isActionTriggered == '\0') { - heldUpAction = 0x16; - isActionTriggered = - (**(code **)(PTR_vftable_00c57b18 + 0x74))(0xffffffff,FUN_00a20940,&heldUpAction,0,0); - if (isActionTriggered == '\0') { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))) = 0; - ExceptionList = local_1c; - return; - } - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))) + 1; - ExceptionList = local_1c; - return; -} - -// 008e4970 -void Menu_Mods::reset() -{ - uint8_t bVar1; - uint8_t *currentName; - uint32_t compareResult; - uint8_t *defaultName; - bool isLess; - uint8_t *animData; - MenuManager *menuManager; - - animData = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x16])) + 0x2)))); - if (animData != GHIDRA_CAST(0x0)) { - currentName = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - currentName = *GHIDRA_CAST(animData); - } - defaultName = &DAT_00b6767c; - do { - bVar1 = *currentName; - isLess = bVar1 < *defaultName; - if (bVar1 != *defaultName) { -LAB_008e49b0: - compareResult = -GHIDRA_UINT(isLess) | 1; - goto LAB_008e49b5; - } - if (bVar1 == 0) break; - bVar1 = currentName[1]; - isLess = bVar1 < defaultName[1]; - if (bVar1 != defaultName[1]) goto LAB_008e49b0; - currentName = currentName + 2; - defaultName = defaultName + 2; - } while (bVar1 != 0); - compareResult = 0; -LAB_008e49b5: - if ((compareResult == 0) && ((animData[0x34] == 0 || (*GHIDRA_CAST((this + 0x1c)) != '\0')))) - goto LAB_008e49e2; - } - bVar1 = ANM2::SetAnimation(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[5])) + 0x1)))),&DAT_00b6767c,1); - if (bVar1 != 0) { - AnimationState::Rewind(GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x15])) + 0x1))))); - *GHIDRA_CAST((this + 0x1c)) = 1; - } -LAB_008e49e2: - menuManager = g_menuManager; - *GHIDRA_CAST(this) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))) = 0; - menuManager->_viewPositionSet[7].y = -216.0; - menuManager->_state = 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x62])) + 0x2)))) = g_manager->_modManager; - (*GHIDRA_CAST((GHIDRA_CAST(&(this[0x61])) + 0x1))) = 0; - return; -} diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index d4e6b4f..2c7602c 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -177,2280 +177,6 @@ LAB_0049f8ee: return; } -// 004b70c0 -void NpcHelper::hornfel_spawn_doors() -{ - RailManager *this; - Entity *pEVar1; - uint8_t isCanStep; - uint32_t uVar2; - int iVar3; - int iVar4; - uint32_t seed; - uint32_t startIndex; - Room *toIndex; - Room *room; - int iVar5; - Room *pRVar6; - int *piVar7; - float fVar8; - float fVar9; - int *doors; - int *doorsEnd; - Vector spawnPos; - Vector leftSpawnPos; - Room *local_2c; - Entity *local_28; - Entity *local_24; - Room *local_20; - int local_1c; - Entity *local_18; - int *doorsCapacity; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - - puStack_c = &LAB_00af336d; - local_10 = ExceptionList; - uVar2 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 4U; - ExceptionList = &local_10; - doors = GHIDRA_CAST(0x0); - doorsEnd = GHIDRA_CAST(0x0); - doorsCapacity = GHIDRA_CAST(0x0); - room = g_game->_room; - local_20 = GHIDRA_CAST(room->_gridWidth); - local_1c = room->_gridHeight; - local_8 = 0; - iVar5 = 1; - local_2c = room; - if (1 < local_1c + -1) { - local_28 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(local_20[-1])) + 0x7896)))); - do { - fVar9 = 120.0; - fVar8 = 40.0; - iVar4 = room->_gridWidth; - if ((iVar4 < 1) || (room->_gridHeight <= iVar5)) { - iVar3 = -1; - } - else { - iVar3 = iVar4 * iVar5; - } - local_18 = GHIDRA_CAST((iVar4 * iVar5)); - if ((iVar4 < 2) || (room->_gridHeight <= iVar5)) { - iVar4 = -1; - } - else { - iVar4 = GHIDRA_INT(local_18) + 1; - } - isCanStep = (GHIDRA_CAST((&room->_railManager)))->RoomGridPath::can_step(iVar4,iVar3); - if (isCanStep != 0) { - if ((room->_gridWidth < 1) || (room->_gridHeight <= iVar5)) { - local_18 = GHIDRA_CAST(0xffffffff); - } - iVar4 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0xc)); - leftSpawnPos.x = (float)(GHIDRA_INT(local_18) % iVar4) * fVar8 + fVar8; - leftSpawnPos.y = (float)(GHIDRA_INT(local_18) / iVar4) * fVar8 + fVar9; - seed = Random(); - local_24 = Game::Spawn(g_game,0x3c7,0,&leftSpawnPos,&g_vectorZero,GHIDRA_CAST(0x0),0,seed); - (local_24->_sprite)._rotation = -90.0; - local_18 = GHIDRA_CAST(cos(-1.5707964)); - fVar8 = sin(-1.5707964); - (local_24->_sprite)._offset.x = (float)local_18 * 0.0 - fVar8 * 15.0; - (local_24->_sprite)._offset.y = fVar8 * 0.0 + (float)local_18 * 15.0; - if (doorsEnd == doorsCapacity) { - msvc::vector::_Emplace_reallocate(doorsEnd,&local_24); - doorsCapacity = GHIDRA_CAST(0x0); - } - else { - *doorsEnd = GHIDRA_INT(local_24); - doorsEnd = doorsEnd + 1; - } - fVar9 = 120.0; - fVar8 = 40.0; - } - if (((GHIDRA_INT(&(*GHIDRA_CAST((GHIDRA_CAST(&(local_20[-1])) + 0x7897)))) < 0) || - (room->_gridWidth <= GHIDRA_INT(&(*GHIDRA_CAST((GHIDRA_CAST(&(local_20[-1])) + 0x7897)))))) || (room->_gridHeight <= iVar5)) { - iVar4 = -1; - } - else { - iVar4 = GHIDRA_INT(local_20->_gridEntities) + room->_gridWidth * iVar5 + -0x25; - } - if (((GHIDRA_INT(&(*GHIDRA_CAST((GHIDRA_CAST(&(local_20[-1])) + 0x7896)))) < 0) || (room->_gridWidth <= GHIDRA_INT(local_28))) || - (room->_gridHeight <= iVar5)) { - iVar3 = -1; - } - else { - iVar3 = GHIDRA_INT(local_20->_gridEntities) + room->_gridWidth * iVar5 + -0x26; - } - isCanStep = (GHIDRA_CAST((&room->_railManager)))->RoomGridPath::can_step(iVar3,iVar4); - if (isCanStep != 0) { - if (((GHIDRA_INT(&(*GHIDRA_CAST((GHIDRA_CAST(&(local_20[-1])) + 0x7897)))) < 0) || - (room->_gridWidth <= GHIDRA_INT(&(*GHIDRA_CAST((GHIDRA_CAST(&(local_20[-1])) + 0x7897)))))) || (room->_gridHeight <= iVar5)) - { - local_18 = GHIDRA_CAST(0xffffffff); - } - else { - local_18 = GHIDRA_CAST((GHIDRA_INT(local_20->_gridEntities) + room->_gridWidth * iVar5 + -0x25)); - } - iVar4 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0xc)); - spawnPos.x = (float)(GHIDRA_INT(local_18) % iVar4) * fVar8 + fVar8; - spawnPos.y = (float)(GHIDRA_INT(local_18) / iVar4) * fVar8 + fVar9; - seed = Random(); - local_18 = Game::Spawn(g_game,0x3c7,0,&spawnPos,&g_vectorZero,GHIDRA_CAST(0x0),0,seed); - (local_18->_sprite)._rotation = 90.0; - local_24 = GHIDRA_CAST(cos(1.5707964)); - fVar8 = sin(1.5707964); - pEVar1 = local_24; - local_24 = local_18; - (local_18->_sprite)._offset.x = (float)pEVar1 * 0.0 - fVar8 * 15.0; - (local_18->_sprite)._offset.y = fVar8 * 0.0 + (float)pEVar1 * 15.0; - if (doorsEnd == doorsCapacity) { - msvc::vector::_Emplace_reallocate(doorsEnd,&local_24); - doorsCapacity = GHIDRA_CAST(0x0); - } - else { - *doorsEnd = GHIDRA_INT(local_18); - doorsEnd = doorsEnd + 1; - } - } - iVar5 = iVar5 + 1; - } while (iVar5 < local_1c + -1); - } - local_18 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(local_20[-1])) + 0x7897)))); - pRVar6 = GHIDRA_CAST(0x1); - if (1 < GHIDRA_INT(local_18)) { - do { - fVar9 = 120.0; - fVar8 = 40.0; - if ((GHIDRA_INT(pRVar6) < room->_gridWidth) && (0 < room->_gridHeight)) { - iVar5 = room->_gridWidth; - toIndex = pRVar6; -LAB_004b747c: - if (room->_gridHeight < 2) goto LAB_004b7486; - iVar5 = GHIDRA_INT(pRVar6->_gridEntities) + iVar5 + -0x24; - } - else { - iVar5 = room->_gridWidth; - toIndex = GHIDRA_CAST(0xffffffff); - if (GHIDRA_INT(pRVar6) < iVar5) goto LAB_004b747c; -LAB_004b7486: - iVar5 = -1; - } - isCanStep = (GHIDRA_CAST((&room->_railManager)))->RoomGridPath::can_step(iVar5,GHIDRA_INT(toIndex)); - if (isCanStep != 0) { - if ((GHIDRA_INT(pRVar6) < room->_gridWidth) && (0 < room->_gridHeight)) { - local_20 = pRVar6; - } - else { - local_20 = GHIDRA_CAST(0xffffffff); - } - iVar5 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0xc)); - spawnPos.x = (float)(GHIDRA_INT(local_20) % iVar5) * fVar8 + fVar8; - spawnPos.y = (float)(GHIDRA_INT(local_20) / iVar5) * fVar8 + fVar9; - seed = Random(); - local_24 = Game::Spawn(g_game,0x3c7,0,&spawnPos,&g_vectorZero,GHIDRA_CAST(0x0),0,seed); - (local_24->_sprite)._rotation = 0.0; - local_28 = GHIDRA_CAST(cos(0.0)); - fVar8 = sin(0.0); - pEVar1 = local_28; - local_28 = local_24; - (local_24->_sprite)._offset.x = (float)pEVar1 * 0.0 - fVar8 * 15.0; - (local_24->_sprite)._offset.y = fVar8 * 0.0 + (float)pEVar1 * 15.0; - if (doorsEnd == doorsCapacity) { - msvc::vector::_Emplace_reallocate(doorsEnd,&local_28); - doorsCapacity = GHIDRA_CAST(0x0); - } - else { - *doorsEnd = GHIDRA_INT(local_24); - doorsEnd = doorsEnd + 1; - } - } - iVar5 = room->_gridWidth; - this = &room->_railManager; - if (((GHIDRA_INT(pRVar6) < iVar5) && (iVar4 = local_1c + -1, -1 < iVar4)) && - (iVar4 < room->_gridHeight)) { - iVar4 = GHIDRA_INT(pRVar6->_gridEntities) + iVar4 * iVar5 + -0x24; -LAB_004b75cf: - iVar3 = local_1c + -2; - room = local_2c; - if ((iVar3 < 0) || (local_2c->_gridHeight <= iVar3)) goto LAB_004b75e6; - iVar5 = GHIDRA_INT(pRVar6->_gridEntities) + iVar3 * iVar5 + -0x24; - } - else { - iVar4 = -1; - if (GHIDRA_INT(pRVar6) < iVar5) goto LAB_004b75cf; -LAB_004b75e6: - iVar5 = -1; - } - isCanStep = this->RoomGridPath::can_step(iVar5,iVar4); - if (isCanStep != 0) { - local_28 = GHIDRA_CAST(FUN_004bb230()); - if (doorsEnd == doorsCapacity) { - msvc::vector::_Emplace_reallocate(doorsEnd,&local_28); - doorsCapacity = GHIDRA_CAST(0x0); - } - else { - *doorsEnd = GHIDRA_INT(local_28); - doorsEnd = doorsEnd + 1; - } - } - pRVar6 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((pRVar6)) + 0x1)))); - } while (GHIDRA_INT(pRVar6) < GHIDRA_INT(local_18)); - } - local_18 = GHIDRA_CAST(0x0); - piVar7 = doors; - if (doorsEnd != GHIDRA_CAST(0x0)) { - do { - local_18 = GHIDRA_CAST(piVar7); - local_1c = *GHIDRA_CAST(local_18); - pRVar6 = GHIDRA_CAST((local_1c + 0x3bc)); - local_2c = pRVar6; - if ((*GHIDRA_CAST((local_1c + 0x3bc)) == 0) && - (piVar7 = GHIDRA_CAST((GHIDRA_INT(local_18) + 4)), piVar7 < doorsEnd)) { - do { - local_28 = GHIDRA_CAST(*piVar7); - local_20 = GHIDRA_CAST(&local_28->_parent); - if (local_28->_parent == 0) { - iVar5 = GHIDRA_INT((((local_28->_pos).x - 40.0) / 40.0 + 0.5)); - iVar4 = GHIDRA_INT((((local_28->_pos).y - 120.0) / 40.0 + 0.5)); - if ((((iVar5 < 0) || (room->_gridWidth <= iVar5)) || (iVar4 < 0)) || - (room->_gridHeight <= iVar4)) { - seed = 0xffffffff; - } - else { - seed = iVar4 * room->_gridWidth + iVar5; - } - iVar4 = GHIDRA_INT(((*GHIDRA_CAST((local_1c + 0x33c)) - 40.0) / 40.0 + 0.5)); - iVar5 = GHIDRA_INT(((*GHIDRA_CAST((local_1c + 0x340)) - 120.0) / 40.0 + 0.5)); - if (((iVar4 < 0) || (room->_gridWidth <= iVar4)) || - ((iVar5 < 0 || (room->_gridHeight <= iVar5)))) { - startIndex = 0xffffffff; - } - else { - startIndex = iVar5 * room->_gridWidth + iVar4; - } - isCanStep = room_grid_flood_fill(&room->_railManager,startIndex,seed); - if (isCanStep != 0) { - if (*GHIDRA_CAST(pRVar6) != 0) { - local_2c = pRVar6; - msvc::multiset::erase(&local_2c); - } - *GHIDRA_CAST(pRVar6) = local_28; - msvc::multiset::insert(pRVar6); - if (*GHIDRA_CAST(local_20) != 0) { - local_2c = local_20; - msvc::multiset::erase(&local_2c); - } - *GHIDRA_CAST(local_20) = local_1c; - msvc::multiset::insert(local_20); - } - } - piVar7 = piVar7 + 1; - } while (piVar7 < doorsEnd); - } - local_18 = GHIDRA_CAST((GHIDRA_INT(local_18) + 4)); - piVar7 = GHIDRA_CAST(local_18); - } while (local_18 < doorsEnd); - } - if (doorsEnd != GHIDRA_CAST(0x0)) { - do { - (**(code **)(*GHIDRA_CAST(*doors) + 0xc))(uVar2); - doors = doors + 1; - } while (doors < doorsEnd); - } - if (room->_doors[0] != (void *)0x0) { - *GHIDRA_CAST((GHIDRA_INT(room->_doors[0]) + 0xf4)) = 0; - } - if (room->_doors[1] != (void *)0x0) { - *GHIDRA_CAST((GHIDRA_INT(room->_doors[1]) + 0xf4)) = 0; - } - if (room->_doors[2] != (void *)0x0) { - *GHIDRA_CAST((GHIDRA_INT(room->_doors[2]) + 0xf4)) = 0; - } - if (room->_doors[3] != (void *)0x0) { - *GHIDRA_CAST((GHIDRA_INT(room->_doors[3]) + 0xf4)) = 0; - } - if (room->_doors[4] != (void *)0x0) { - *GHIDRA_CAST((GHIDRA_INT(room->_doors[4]) + 0xf4)) = 0; - } - if (room->_doors[5] != (void *)0x0) { - *GHIDRA_CAST((GHIDRA_INT(room->_doors[5]) + 0xf4)) = 0; - } - if (room->_doors[6] != (void *)0x0) { - *GHIDRA_CAST((GHIDRA_INT(room->_doors[6]) + 0xf4)) = 0; - } - if (room->_doors[7] != (void *)0x0) { - *GHIDRA_CAST((GHIDRA_INT(room->_doors[7]) + 0xf4)) = 0; - } - ExceptionList = local_10; - return; -} - -// 004b78f0 -void NpcHelper::hornfel_remove_doors() -{ - void *pvVar1; - int *hornfelDoorIter; - uint32_t uVar3; - int *linkedIter; - uint32_t seed; - Entity *pEVar4; - int *linkedIter; - int *piVar6; - int *local_70; - int *local_64; - Vector scratchVec; - int *local_44; - uint32_t local_40; - uint32_t uStack_3c; - uint32_t uStack_38; - uint32_t uStack_34; - uint32_t local_30; - uint32_t uStack_2c; - uint32_t uStack_28; - uint32_t uStack_24; - uint32_t local_20; - uint32_t local_1c; - uint32_t local_18; - uint32_t local_14; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - int *hornfelDoorIter; - - puStack_c = &LAB_00af33a5; - local_10 = ExceptionList; - uVar3 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 4U; - ExceptionList = &local_10; - linkedIter = GHIDRA_CAST(0x0); - local_64 = GHIDRA_CAST(0x0); - pvVar1 = g_game->_room; - piVar6 = GHIDRA_CAST(0x0); - local_70 = GHIDRA_CAST(0x0); - local_8 = 1; - scratchVec.y = 0.0; - local_14 = uVar3; - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x1264)) != 0) { - do { - local_44 = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x125c)) + GHIDRA_INT(scratchVec.y) * 4)); - if (local_44[10] == 0x3c7) { - if (linkedIter == GHIDRA_CAST(0x0)) { - msvc::vector::_Emplace_reallocate(0,&local_44); - linkedIter = local_64; - } - else { - *linkedIter = GHIDRA_INT(local_44); - local_64 = linkedIter + 1; - linkedIter = local_64; - } - } - if (local_44[0xf5] != 0) { - if (piVar6 == GHIDRA_CAST(0x0)) { - msvc::vector::_Emplace_reallocate(0,&local_44); - piVar6 = local_70; - } - else { - *piVar6 = GHIDRA_INT(local_44); - local_70 = piVar6 + 1; - piVar6 = local_70; - } - } - scratchVec.y = (float)(GHIDRA_INT(scratchVec.y) + 1); - } while (GHIDRA_UINT(scratchVec.y) < GHIDRA_UINT(*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x1264)))); - } - local_44 = GHIDRA_CAST(0x0); - linkedIter = GHIDRA_CAST(0x0); - hornfelDoorIter = local_44; - hornfelDoorIter = local_44; - if (piVar6 != GHIDRA_CAST(0x0)) { - do { - seed = Random(); - scratchVec.x = *GHIDRA_CAST((*linkedIter + 0x33c)); - scratchVec.y = *GHIDRA_CAST((*linkedIter + 0x340)); - Game::Spawn(g_game,1000,0xf,&scratchVec,&g_vectorZero,GHIDRA_CAST(0x0),0,seed); - (**(code **)(*GHIDRA_CAST(*linkedIter) + 0x28))(uVar3); - (**(code **)(**GHIDRA_CAST((*linkedIter + 0x3d4)) + 0x28))(); - linkedIter = linkedIter + 1; - hornfelDoorIter = local_44; - hornfelDoorIter = local_44; - } while (linkedIter != piVar6); - } - for (; piVar6 = local_44, hornfelDoorIter != linkedIter; hornfelDoorIter = hornfelDoorIter + 1) { - local_40 = 0x3ecccccd; - uStack_3c = 0x3ecccccd; - uStack_38 = 0x3ecccccd; - uStack_34 = 0x3f800000; - local_20 = 0; - local_30 = 0x3f800000; - uStack_2c = 0x3f800000; - uStack_28 = 0x3f800000; - uStack_24 = 0x3f800000; - local_1c = 0; - local_18 = 0; - local_44 = hornfelDoorIter; - uVar3 = Random(); - scratchVec.x = *GHIDRA_CAST((*hornfelDoorIter + 0x33c)); - scratchVec.y = *GHIDRA_CAST((*hornfelDoorIter + 0x340)); - pEVar4 = Game::Spawn(g_game,1000,0xf,&scratchVec,&g_vectorZero,GHIDRA_CAST(0x0),0,uVar3); - (**(code **)(*GHIDRA_CAST(pEVar4) + 0x3c))(&local_40,0xffffffff,0xff,0,1); - (**(code **)(*GHIDRA_CAST(*hornfelDoorIter) + 0x28))(); - hornfelDoorIter = local_44; - local_44 = piVar6; - } - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x724)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x724)) + 0xf4)) = 0x3f800000; - } - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x728)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x728)) + 0xf4)) = 0x3f800000; - } - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x72c)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x72c)) + 0xf4)) = 0x3f800000; - } - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x730)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x730)) + 0xf4)) = 0x3f800000; - } - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x734)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x734)) + 0xf4)) = 0x3f800000; - } - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x738)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x738)) + 0xf4)) = 0x3f800000; - } - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x73c)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x73c)) + 0xf4)) = 0x3f800000; - } - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x740)) != 0) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x740)) + 0xf4)) = 0x3f800000; - } - if (local_44 != GHIDRA_CAST(0x0)) { - uVar3 = -GHIDRA_INT(local_44) & 0xfffffffc; - linkedIter = local_44; - if (0xfff < uVar3) { - linkedIter = GHIDRA_CAST(local_44[-1]); - uVar3 = uVar3 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(local_44) + (-4 - GHIDRA_INT(linkedIter))))) { - local_44 = hornfelDoorIter; - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - local_44 = hornfelDoorIter; - operator_delete(linkedIter,uVar3); - } - ExceptionList = local_10; - return; -} - -// 004b7e30 -void NpcHelper::hornfel_charge(Entity_NPC *npc) -{ - char *animName; - float cartVelocityX; - float cartVelocityY; - ANM2 *sprite; - - sprite = &npc->_sprite; - cartVelocityX = *GHIDRA_CAST((npc->_minecart + 0x360)); - cartVelocityY = *GHIDRA_CAST((npc->_minecart + 0x364)); - if (npc->_state != 10) { - if (ABS(cartVelocityY) < ABS(cartVelocityX)) { - animName = "IdleLeft"; - if (0.0 <= cartVelocityX) { - animName = "IdleRight"; - } - ANM2::Play(sprite,GHIDRA_CAST(animName),0); - return; - } - animName = "IdleUp"; - if (0.0 <= cartVelocityY) { - animName = "IdleDown"; - } - ANM2::Play(sprite,GHIDRA_CAST(animName),0); - return; - } - if (ABS(cartVelocityY) < ABS(cartVelocityX)) { - animName = "ChargeLeft"; - if (0.0 <= cartVelocityX) { - animName = "ChargeRight"; - } - ANM2::Play(sprite,GHIDRA_CAST(animName),0); - return; - } - animName = "ChargeUp"; - if (0.0 <= cartVelocityY) { - animName = "ChargeDown"; - } - ANM2::Play(sprite,GHIDRA_CAST(animName),0); - return; -} - -// 004b7ee0 -Entity * NpcHelper::hornfel_pick_spawn() -{ - int *piVar1; - uint32_t uVar2; - RNG rng; - uint32_t uVar3; - Entity *spawned; - Entity *in_ECX; - void *freeBlock; - uint32_t uVar4; - BitSet128 BVar5; - uint32_t *local_44; - uint32_t rngSeed; - uint64_t uStack_3c; - uint32_t uStack_34; - void *outcomes; - uint32_t *outcomesEnd; - uint32_t *outcomesCapacity; - uint32_t securityCookie; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - int oldParent; - uint32_t *parentRef; - - puStack_20 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)); - puStack_18 = &LAB_00af332d; - local_1c = ExceptionList; - securityCookie = __security_cookie ^ GHIDRA_INT(register0x00000010) - 0x10U; - ExceptionList = &local_1c; - outcomes = (void *)0x0; - outcomesEnd = GHIDRA_CAST(0x0); - outcomesCapacity = GHIDRA_CAST(0x0); - local_14 = 0; - uStack_3c = (uint64_t)GHIDRA_UINT(uStack_3c); - uStack_34 = 6; - msvc::vector<8byte>::_Emplace_reallocate(0,GHIDRA_INT(&uStack_3c) + 4); - uVar3 = 0; - uVar4 = GHIDRA_INT(outcomesEnd) - GHIDRA_INT(outcomes) >> 3; - if (uVar4 != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(outcomes) + uVar3 * 8)) == 8) { - piVar1 = GHIDRA_CAST((GHIDRA_INT(outcomes) + uVar3 * 8 + 4)); - *piVar1 = *piVar1 + 3; - if (*piVar1 < 0) { - *GHIDRA_CAST((GHIDRA_CAST(outcomes) + uVar3 * 8 + 4)) = 0; - } - goto LAB_004b7fc7; - } - uVar3 = uVar3 + 1; - } while (uVar3 < uVar4); - } - uStack_3c = CONCAT44(8,GHIDRA_UINT(uStack_3c)); - uStack_34 = 3; - if (outcomesEnd == outcomesCapacity) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesEnd,GHIDRA_INT(&uStack_3c) + 4); - } - else { - *outcomesEnd = 8; - outcomesEnd[1] = 3; - outcomesEnd = outcomesEnd + 2; - } -LAB_004b7fc7: - uVar3 = 0; - uVar4 = GHIDRA_INT(outcomesEnd) - GHIDRA_INT(outcomes) >> 3; - if (uVar4 != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(outcomes) + uVar3 * 8)) == 0x10) { - piVar1 = GHIDRA_CAST((GHIDRA_INT(outcomes) + uVar3 * 8 + 4)); - *piVar1 = *piVar1 + 1; - if (*piVar1 < 0) { - *GHIDRA_CAST((GHIDRA_CAST(outcomes) + uVar3 * 8 + 4)) = 0; - } - goto LAB_004b8025; - } - uVar3 = uVar3 + 1; - } while (uVar3 < uVar4); - } - uStack_3c = CONCAT44(0x10,GHIDRA_UINT(uStack_3c)); - uStack_34 = 1; - if (outcomesEnd == outcomesCapacity) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesEnd,GHIDRA_INT(&uStack_3c) + 4); - } - else { - *outcomesEnd = 0x10; - outcomesEnd[1] = 1; - outcomesEnd = outcomesEnd + 2; - } -LAB_004b8025: - rngSeed = Random(); - rngSeed = rngSeed | 1; - uStack_3c = 0x900000005; - uStack_34 = 7; - rng._shift1 = 5; - rng._seed = rngSeed; - rng._shift2 = 9; - rng._shift3 = 7; - uVar3 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&outcomes),rng); - local_14 = 0xffffffff; - uStack_34 = uVar3; - if (outcomes != (void *)0x0) { - uVar4 = GHIDRA_INT(outcomesCapacity) - GHIDRA_INT(outcomes) & 0xfffffff8; - freeBlock = outcomes; - if (0xfff < uVar4) { - freeBlock = *(void **)(GHIDRA_CAST(outcomes) + -4); - uVar4 = uVar4 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(outcomes) + (-4 - GHIDRA_INT(freeBlock))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(freeBlock,uVar4); - } - uVar4 = Random(); - spawned = Game::Spawn(g_game,4,uVar3,&in_ECX->_pos,&g_vectorZero,in_ECX,0,uVar4); - oldParent = spawned->_parent; - parentRef = &spawned->_parent; - spawned->_visible = 0; - spawned->_entityCollisionClass = 0; - spawned->_entityGridCollisionClass = 0; - *GHIDRA_CAST((spawned + 1)) = 0x23; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(spawned[1])) + 0x4)))) = 0x23; - if (oldParent != 0) { - local_44 = parentRef; - msvc::multiset::erase(&local_44); - } - *parentRef = in_ECX; - if (in_ECX != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(parentRef); - } - if (uStack_34 == 8) { - BVar5 = g_tearFlagBurn; - } - else { - if (uStack_34 != 0x10) goto LAB_004b814e; - BVar5 = g_tearFlagSadBomb; - } - spawned[1]._sprite._filename._buf[0xb] = '\x01'; - *GHIDRA_CAST(&spawned[1]._type) = BVar5; -LAB_004b814e: - uVar2 = *GHIDRA_CAST((GHIDRA_INT(&spawned->_flags) + 4)); - *GHIDRA_CAST(&spawned->_flags) = GHIDRA_UINT(spawned->_flags) | 0x20; - *GHIDRA_CAST((GHIDRA_INT(&spawned->_flags) + 4)) = uVar2; - ExceptionList = local_1c; - return spawned; -} - -// 004b8190 -void NpcHelper::hornfel_minecart(Entity_NPC *npc) -{ - uint32_t uVar1; - uint32_t uVar2; - int iVar3; - int iVar4; - Entity_NPC *pEVar5; - Vector *velocity; - int *piVar6; - Entity_Player *player; - uint32_t rngResult; - Entity *spawned; - char *ptr; - int iVar7; - int *remaining; - float fVar8; - uint32_t *puVar9; - float deltaX; - Vector railDirOut; - Vector local_60; - Vector local_58; - Vector local_50; - Entity_NPC *local_48; - int *local_44; - uint32_t *local_40; - std_string anm2Path; - uint32_t local_24; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - ANM2 *minecartSprite; - void *room; - - puStack_20 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)); - local_14 = 0xffffffff; - puStack_18 = &LAB_00af33dd; - local_1c = ExceptionList; - local_24 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 0x10U; - ExceptionList = &local_1c; - local_48 = npc; - if (npc->_state == 7) { - pEVar5 = GHIDRA_CAST(npc->_entityRef); - local_60.y = (float)pEVar5; - if (pEVar5 != GHIDRA_CAST(0x0)) { - local_40 = &npc->_entityRef; - puStack_20 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)); - msvc::multiset::erase(&local_40); - npc->_entityRef = 0; - goto LAB_004b8213; - } - } - local_60.y = (float)hornfel_free_door(); - local_50.y = (float)g_game->_room; - local_58.y = 0.0; - if ((GHIDRA_CAST((GHIDRA_INT(local_50.y) + 0xf60)))->_brimstoneMarkCountdown != 0) { - do { - iVar7 = *GHIDRA_CAST(((GHIDRA_CAST((GHIDRA_INT(local_50.y) + 0xf60)))->_weaknessCountdown + - GHIDRA_INT(local_58.y) * 4)); - if (*GHIDRA_CAST((iVar7 + 0x28)) == 0x3c7) { - if (*GHIDRA_CAST((iVar7 + 0x3c4)) == npc) { - if (*GHIDRA_CAST((iVar7 + 0x3c4)) == GHIDRA_CAST(0x0)) { - if ((*GHIDRA_CAST((iVar7 + 0x3bc)) == 0) || (*GHIDRA_CAST((*GHIDRA_CAST((iVar7 + 0x3bc)) + 0x3c4)) == 0)) - goto LAB_004b8675; - } - else { - local_40 = GHIDRA_CAST((iVar7 + 0x3c4)); - msvc::multiset::erase(&local_40); - } - iVar3 = *GHIDRA_CAST((iVar7 + 0x3bc)); - *GHIDRA_CAST((iVar7 + 0x3c4)) = 0; - if (iVar3 != 0) { - if (*GHIDRA_CAST((iVar3 + 0x3c4)) != 0) { - local_40 = GHIDRA_CAST((iVar3 + 0x3c4)); - msvc::multiset::erase(&local_40); - } - *GHIDRA_CAST((iVar3 + 0x3c4)) = 0; - } - } - } -LAB_004b8675: - local_58.y = (float)(GHIDRA_INT(local_58.y) + 1); - } while (GHIDRA_UINT(local_58.y) < - GHIDRA_UINT((GHIDRA_CAST((GHIDRA_INT(local_50.y) + 0xf60)))->_brimstoneMarkCountdown)); - } - pEVar5 = GHIDRA_CAST(local_60.y); - if (GHIDRA_CAST(local_60.y) == GHIDRA_CAST(0x0)) { - KAGE_LogMessage(4,GHIDRA_CAST("no doors to enter from!\n")); - *GHIDRA_CAST(&npc->_stateFrame) = 0xf; - ExceptionList = local_1c; - return; - } -LAB_004b8213: - hornfel_get_rail_direction(pEVar5,&local_50); - if ((local_50.x == g_vectorZero.x) && (local_50.y == g_vectorZero.y)) { - KAGE_LogMessage(0x10,GHIDRA_CAST("exit velocity is zero\n")); - } - if ((local_50.x != g_vectorZero.x) || (local_50.y != g_vectorZero.y)) { - npc->_visible = 1; - npc->_entityCollisionClass = 4; - npc->_shadowSize = *GHIDRA_CAST((GHIDRA_CAST(npc->_config) + 0x24)); - local_58.y = (float)npc->_minecart; - if (GHIDRA_CAST(local_58.y) != GHIDRA_CAST(0x0)) { - FUN_004cf0f0(1); - Entity_NPC::SetMinecartPosVel(GHIDRA_CAST(local_58.y),&pEVar5->_targetPosition,&local_50); - fVar8 = (GHIDRA_CAST((GHIDRA_INT(local_58.y) + 0x33c)))->y; - (npc->_pos).x = (GHIDRA_CAST((GHIDRA_INT(local_58.y) + 0x33c)))->x; - (npc->_pos).y = fVar8; - hornfel_claim_target(pEVar5,GHIDRA_CAST(npc)); - local_40 = GHIDRA_CAST(npc->_parent); - if (npc->_state == 6) { - if (*GHIDRA_CAST((GHIDRA_INT(&npc->_projectileCooldown) + 1)) == '\0') { - uVar2 = Random(); - if (((uVar2 & 7) == 0) && ((local_40 == GHIDRA_CAST(0x0) || (4 < GHIDRA_INT(local_40[0x117]))))) - { - room = g_game->_room; - iVar3 = *GHIDRA_CAST((GHIDRA_CAST(room) + 0x12c0)) + *GHIDRA_CAST((GHIDRA_CAST(room) + 0x12c4)); - iVar7 = 0; - if (0 < iVar3) { - iVar7 = iVar3; - } - iVar4 = *GHIDRA_CAST((GHIDRA_CAST(room) + 0x12c8)) + *GHIDRA_CAST((GHIDRA_CAST(room) + 0x12cc)); - iVar3 = 0; - if (0 < iVar4) { - iVar3 = iVar4; - } - if ((iVar7 - iVar3 < 2) && (spawned = hornfel_free_door(), spawned != GHIDRA_CAST(0x0))) { - local_58.y = 0.0; - local_44 = GHIDRA_CAST(((0x87 < *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x10)) * - *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0xc))) + 2)); - do { - local_60.y = (float)hornfel_free_door(); - if (GHIDRA_CAST(local_60.y) == GHIDRA_CAST(0x0)) break; - uVar2 = Random(); - pEVar5 = (Entity_NPC *) - Game::Spawn(g_game,0x38a,1,&g_vectorZero,&g_vectorZero,GHIDRA_CAST(npc),0, - uVar2); - uVar1 = *GHIDRA_CAST((GHIDRA_INT(&pEVar5->_flags) + 4)); - iVar7 = *GHIDRA_CAST(pEVar5); - *GHIDRA_CAST(&pEVar5->_flags) = GHIDRA_UINT(pEVar5->_flags) & 0xfffffffb; - *GHIDRA_CAST((GHIDRA_INT(&pEVar5->_flags) + 4)) = uVar1; - local_48 = pEVar5; - (**(code **)(iVar7 + 0xc))(); - velocity = hornfel_get_rail_direction(GHIDRA_CAST(local_60.y),&railDirOut); - local_50.y = (float)Entity::GiveMinecart - (GHIDRA_CAST(pEVar5),GHIDRA_CAST((GHIDRA_INT(local_60.y) + 0x334)), - velocity); - anm2Path._size = 0; - minecartSprite = &(GHIDRA_CAST(local_50.y))->_sprite; - anm2Path._capacity = 0xf; - anm2Path._buf[0] = '\0'; - anm2Path._buf[1] = '\0'; - anm2Path._buf[2] = '\0'; - anm2Path._buf[3] = '\0'; - (*GHIDRA_CAST((GHIDRA_CAST(&(anm2Path._buf)) + 0x0))) = msvc::_Allocate(0x30); - anm2Path._size = 0x21; - anm2Path._capacity = 0x2f; - builtin_strncpy((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(anm2Path._buf))) + 0x0))),"gfx/965.001_hornfel minecart.anm2",0x22 - ); - local_14 = 0; - ANM2::Load(minecartSprite,&anm2Path,1); - local_14 = 0xffffffff; - if (0xf < anm2Path._capacity) { - uVar2 = anm2Path._capacity + 1; - ptr = (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(anm2Path._buf))) + 0x0))); - if (0xfff < uVar2) { - ptr = *GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(anm2Path._buf)) + 0x0))) + -4)); - uVar2 = anm2Path._capacity + 0x24; - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(anm2Path._buf)) + 0x0))) + (-4 - GHIDRA_INT(ptr))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(ptr,uVar2); - } - (**(code **)(*GHIDRA_CAST(local_50.y) + 0xc))(); - pEVar5 = local_48; - if ((*GHIDRA_CAST((GHIDRA_CAST(local_60.y) + 0x3c4)) == 0) && - ((*GHIDRA_CAST((GHIDRA_CAST(local_60.y) + 0x3bc)) == 0 || - (*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(local_60.y) + 0x3bc)) + 0x3c4)) == 0)))) { - *GHIDRA_CAST((GHIDRA_CAST(local_60.y) + 0x3c4)) = local_48; - msvc::multiset::insert(GHIDRA_CAST((GHIDRA_INT(local_60.y) + 0x3c4))); - iVar7 = *GHIDRA_CAST((GHIDRA_CAST(local_60.y) + 0x3bc)); - if (iVar7 != 0) { - local_50.y = (float)(iVar7 + 0x3c4); - if (*GHIDRA_CAST((iVar7 + 0x3c4)) != 0) { - local_48 = GHIDRA_CAST(local_50.y); - msvc::multiset::erase(&local_48); - } - *GHIDRA_CAST(local_50.y) = pEVar5; - msvc::multiset::insert(local_50.y); - } - } - local_58.y = (float)(GHIDRA_INT(local_58.y) + 1); - } while (GHIDRA_INT(local_58.y) < GHIDRA_INT(local_44)); - npc->_state = 0xe; - uVar2 = Random(); - *GHIDRA_CAST((GHIDRA_INT(&npc->_projectileCooldown) + 1)) = 100; - *GHIDRA_CAST(&npc->_projectileDelay) = (short)(uVar2 % 0x1e) + 0x1e; - if (local_40 == GHIDRA_CAST(0x0)) { - ExceptionList = local_1c; - return; - } - if (GHIDRA_INT(local_40[0x117]) < 0x96) { - local_40[0x117] = 0x96; - local_40[0x118] = 0x96; - ExceptionList = local_1c; - return; - } - ExceptionList = local_1c; - return; - } - pEVar5 = GHIDRA_CAST(local_60.y); - } - } - if ((((npc->_state == 6) && (*GHIDRA_CAST((GHIDRA_INT(&npc->_projectileCooldown) + 2)) == '\0')) && - (uVar2 = Random(), (uVar2 & 7) == 0)) && - ((GHIDRA_CAST(pEVar5->_parent) != GHIDRA_CAST(0x0) && - (GHIDRA_CAST(pEVar5->_parent) != pEVar5)))) { - npc->_state = 10; - (GHIDRA_CAST((GHIDRA_INT(local_58.y) + 3000)))->x = 0.1; - if (npc->_entityRef != 0) { - local_44 = &npc->_entityRef; - msvc::multiset::erase(&local_44); - } - npc->_entityRef = pEVar5; - msvc::multiset::insert(&npc->_entityRef); - *GHIDRA_CAST((GHIDRA_INT(&npc->_projectileCooldown) + 2)) = 100; - uVar2 = Random(); - *GHIDRA_CAST((GHIDRA_INT(&npc->_projectileDelay) + 2)) = (char)(uVar2 % 3) + '\x06'; - ExceptionList = local_1c; - return; - } - } - if (npc->_state == 7) { - npc->_state = 0xb; - } - else { - npc->_state = 3; - uVar2 = Random(); - *GHIDRA_CAST(&npc->_projectileDelay) = (short)(uVar2 % 0xf) + 0xf; - uVar2 = Random(); - if (uVar2 % 3 == 0) { - local_44 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x1264)); - if (local_44 != GHIDRA_CAST(0x0)) { - piVar6 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x125c)); - uVar2 = 0; - remaining = local_44; - do { - iVar7 = *GHIDRA_CAST((*piVar6 + 0x28)); - if ((iVar7 == 0x333) || ((iVar7 == 4 && (*GHIDRA_CAST((*piVar6 + 0x2c)) == 0xe)))) { - uVar2 = uVar2 + 1; - } - piVar6 = piVar6 + 1; - remaining = GHIDRA_CAST((GHIDRA_INT(remaining) + -1)); - } while (remaining != GHIDRA_CAST(0x0)); - npc = local_48; - if (3 < uVar2) { - ExceptionList = local_1c; - return; - } - } - uVar2 = 0; - local_40 = GHIDRA_CAST(0x7149f2ca); - if (GHIDRA_INT((g_game->_playerManager)._playerList._end) - - GHIDRA_INT((g_game->_playerManager)._playerList._begin) >> 2 != 0) { - do { - player = Game::GetPlayer(g_game,uVar2); - uVar2 = uVar2 + 1; - fVar8 = (npc->_pos).y - (player->_pos).y; - deltaX = (npc->_pos).x - (player->_pos).x; - puVar9 = GHIDRA_CAST((fVar8 * fVar8 + deltaX * deltaX)); - if ((float)local_40 <= (float)puVar9) { - puVar9 = local_40; - } - local_40 = puVar9; - } while (uVar2 < GHIDRA_UINT((GHIDRA_INT((g_game->_playerManager)._playerList._end) - - GHIDRA_INT((g_game->_playerManager)._playerList._begin) >> 2))); - if ((float)puVar9 <= 57600.0) { - ExceptionList = local_1c; - return; - } - } - local_40 = GHIDRA_CAST(0x2); - do { - uVar2 = Random(); - rngResult = Random(); - local_44 = GHIDRA_CAST((((float)((double)GHIDRA_INT(rngResult) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 40.0 - 20.0) * 0.017453292)); - local_48 = GHIDRA_CAST(cos((float)local_44)); - fVar8 = sin((float)local_44); - local_58.x = local_50.x * (float)local_48 - local_50.y * fVar8; - local_58.y = local_50.y * (float)local_48 + local_50.x * fVar8; - rngResult = Random(); - fVar8 = (float)((double)GHIDRA_INT(rngResult) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * 2.3283064e-10 * 3.14 - ; - local_44 = GHIDRA_CAST((fVar8 + fVar8)); - fVar8 = cos((float)local_44); - local_60.x = fVar8 * 6.0 + (npc->_pos).x; - fVar8 = sin((float)local_44); - local_60.y = fVar8 * 6.0 + (npc->_pos).y; - spawned = Game::Spawn(g_game,0x333,0,&local_60,&local_58,GHIDRA_CAST(npc),0,uVar2); - if (spawned->_parent != 0) { - local_44 = &spawned->_parent; - msvc::multiset::erase(&local_44); - } - spawned->_parent = npc; - msvc::multiset::insert(&spawned->_parent); - *GHIDRA_CAST(&spawned->_flags) = GHIDRA_UINT(spawned->_flags) & 0xfffffffb; - local_40 = GHIDRA_CAST((GHIDRA_INT(local_40) + -1)); - *GHIDRA_CAST((GHIDRA_INT(&spawned->_flags) + 4)) = *GHIDRA_CAST((GHIDRA_INT(&spawned->_flags) + 4)); - } while (local_40 != GHIDRA_CAST(0x0)); - } - } - } - } - ExceptionList = local_1c; - return; -} - -// 004b8a30 -void NpcHelper::hornfel_ride_minecart(Entity_NPC *linkedNpc) -{ - char *pcVar1; - uint64_t qVar2; - float *pfVar3; - int flyBombData; - float fVar4; - uint64_t *allocatedBytes; - uint32_t uVar5; - float fVar6; - EntityList_EL flyBombs; - Vector scratchVec; - uint32_t *local_14; - void *local_10; - uint8_t *puStack_c; - uint32_t uStack_8; - Game *game; - Entity_NPC *linkedNpc; - Entity_NPC *minecart; - uint32_t *parentRef; - - uStack_8 = 0xffffffff; - puStack_c = &LAB_00af341d; - local_10 = ExceptionList; - minecart = GHIDRA_CAST(linkedNpc->_minecart); - if ((linkedNpc->_state == 10) && - (linkedNpc = GHIDRA_CAST(linkedNpc->_entityRef), linkedNpc != GHIDRA_CAST(0x0))) { - if ('\0' < *GHIDRA_CAST((GHIDRA_INT(&linkedNpc->_projectileDelay) + 2))) { - ExceptionList = &local_10; - hornfel_get_rail_direction(linkedNpc,&scratchVec); - Entity_NPC::SetMinecartPosVel(minecart,&linkedNpc->_targetPosition,&scratchVec); - fVar4 = (minecart->_pos).x; - fVar6 = (minecart->_pos).y; - pcVar1 = GHIDRA_CAST((GHIDRA_INT(&linkedNpc->_projectileDelay) + 2)); - *pcVar1 = *pcVar1 + -1; - (linkedNpc->_pos).x = fVar4; - (linkedNpc->_pos).y = fVar6; - ExceptionList = local_10; - return; - } - linkedNpc->_state = 7; - linkedNpc->_visible = 0; - linkedNpc->_entityCollisionClass = 0; - *GHIDRA_CAST(&linkedNpc->_stateFrame) = 1; - (linkedNpc->_targetPosition).x = (linkedNpc->_pos).x; - (linkedNpc->_targetPosition).y = (linkedNpc->_pos).y; - linkedNpc->_shadowSize = 0.0; - fVar4 = (minecart->_v2).x; - fVar6 = 6.0; - if (fVar4 <= 6.0) { - fVar6 = fVar4; - } - minecart->_shadowSize = 0.0; - (minecart->_v2).x = fVar6; - return; - } - ExceptionList = &local_10; - linkedNpc->_state = 6; - *GHIDRA_CAST(&linkedNpc->_stateFrame) = 0x2d; - linkedNpc->_visible = 0; - linkedNpc->_entityCollisionClass = 0; - (linkedNpc->_targetPosition).x = (linkedNpc->_pos).x; - (linkedNpc->_targetPosition).y = (linkedNpc->_pos).y; - game = g_game; - linkedNpc->_shadowSize = 0.0; - minecart->_shadowSize = 0.0; - EntityList::QuerySublist(GHIDRA_CAST((GHIDRA_INT(game->_room) + 0x1218)),&flyBombs,0x333,-1,-1,0,0); - uVar5 = 0; - if (flyBombs._size != 0) { - flyBombData = (*GHIDRA_CAST((GHIDRA_CAST(&(flyBombs)) + 0x4))); - do { - scratchVec.y = *GHIDRA_CAST((flyBombData + uVar5 * 4)); - parentRef = GHIDRA_CAST((GHIDRA_INT(scratchVec.y) + 0x3bc)); - if (*GHIDRA_CAST((GHIDRA_CAST(scratchVec.y) + 0x3bc)) == linkedNpc) { - fVar4 = scratchVec.y; - if (*GHIDRA_CAST((GHIDRA_CAST(scratchVec.y) + 0x3bc)) != GHIDRA_CAST(0x0)) { - local_14 = parentRef; - msvc::multiset::erase(&local_14); - fVar4 = scratchVec.y; - } - local_14 = *GHIDRA_CAST((GHIDRA_CAST(fVar4) + 0x380)); - scratchVec.y = 3.5; - *parentRef = 0; - pfVar3 = &scratchVec.y; - if ((float)local_14 <= 3.5) { - pfVar3 = GHIDRA_CAST(&local_14); - } - *GHIDRA_CAST((GHIDRA_CAST(fVar4) + 0x380)) = *pfVar3; - flyBombData = (*GHIDRA_CAST((GHIDRA_CAST(&(flyBombs)) + 0x4))); - } - uVar5 = uVar5 + 1; - } while (uVar5 < GHIDRA_UINT(flyBombs._size)); - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(flyBombs)) + 0x0))) == '\0') { - if (g_mainHeap == (void *)0x0) { - allocatedBytes = &g_allocatedBytesNoHeap; - } - else { - allocatedBytes = GHIDRA_CAST((GHIDRA_INT(g_mainHeap) + 0x30)); - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(flyBombs)) + 0x4))) != 0) { - uVar5 = *GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(flyBombs)) + 0x4))) + -4)); - qVar2 = *allocatedBytes; - *GHIDRA_CAST(allocatedBytes) = GHIDRA_UINT(*allocatedBytes) - uVar5; - *GHIDRA_CAST((GHIDRA_CAST(allocatedBytes) + 4)) = - *GHIDRA_CAST((GHIDRA_CAST(allocatedBytes) + 4)) - GHIDRA_UINT((GHIDRA_UINT(qVar2) < uVar5)); - free(GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(flyBombs)) + 0x4))) + -4))); - } - } - ExceptionList = local_10; - return; -} - -// 004b8ca0 -void NpcHelper::hornfel_attack(Entity_NPC *npc) -{ - RNG rng; - uint32_t uVar1; - Entity *target; - uint32_t extraout_ECX; - uint32_t extraout_ECX_00; - uint32_t extraout_ECX_01; - uint32_t uVar2; - void *ptr; - uint32_t uVar3; - float targetDist; - uint64_t uStack_48; - float fStack_40; - float targetDirY; - void *picker; - uint32_t *outcomesEnd; - uint32_t *outcomesCapacity; - float *local_2c; - uint32_t *local_28; - uint32_t local_24; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - char *animName; - float *childSlot; - int dequeBlock; - uint32_t *firstChildSlot; - int *outcomeWeight; - - puStack_20 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)); - puStack_18 = &LAB_00af344d; - local_1c = ExceptionList; - local_24 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 0x10U; - ExceptionList = &local_1c; - picker = (void *)0x0; - outcomesEnd = GHIDRA_CAST(0x0); - outcomesCapacity = GHIDRA_CAST(0x0); - local_14 = 0; - uStack_48 = (uint64_t)GHIDRA_UINT(uStack_48); - fStack_40 = 4.2039e-45; - msvc::vector<8byte>::_Emplace_reallocate(0,GHIDRA_INT(&uStack_48) + 4); - uVar1 = 0; - uVar3 = GHIDRA_INT(outcomesEnd) - GHIDRA_INT(picker) >> 3; - if (uVar3 != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(picker) + uVar1 * 8)) == 1) { - outcomeWeight = GHIDRA_CAST((GHIDRA_INT(picker) + uVar1 * 8 + 4)); - *outcomeWeight = *outcomeWeight + 1; - if (*outcomeWeight < 0) { - *GHIDRA_CAST((GHIDRA_CAST(picker) + uVar1 * 8 + 4)) = 0; - } - goto LAB_004b8d87; - } - uVar1 = uVar1 + 1; - } while (uVar1 < uVar3); - } - uStack_48 = CONCAT44(1,GHIDRA_UINT(uStack_48)); - fStack_40 = 1.4013e-45; - if (outcomesEnd == outcomesCapacity) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesEnd,GHIDRA_INT(&uStack_48) + 4); - } - else { - *outcomesEnd = 1; - outcomesEnd[1] = 1; - outcomesEnd = outcomesEnd + 2; - } -LAB_004b8d87: - if ((char)npc->_projectileCooldown == '\0') { - uVar1 = 0; - uVar3 = GHIDRA_INT(outcomesEnd) - GHIDRA_INT(picker) >> 3; - if (uVar3 != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(picker) + uVar1 * 8)) == 2) { - outcomeWeight = GHIDRA_CAST((GHIDRA_INT(picker) + uVar1 * 8 + 4)); - *outcomeWeight = *outcomeWeight + 1; - if (*outcomeWeight < 0) { - *GHIDRA_CAST((GHIDRA_CAST(picker) + uVar1 * 8 + 4)) = 0; - } - goto LAB_004b8df1; - } - uVar1 = uVar1 + 1; - } while (uVar1 < uVar3); - } - uStack_48 = CONCAT44(2,GHIDRA_UINT(uStack_48)); - fStack_40 = 1.4013e-45; - if (outcomesEnd == outcomesCapacity) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesEnd,GHIDRA_INT(&uStack_48) + 4); - } - else { - *outcomesEnd = 2; - outcomesEnd[1] = 1; - outcomesEnd = outcomesEnd + 2; - } - } -LAB_004b8df1: - uVar1 = Random(); - uStack_48 = 0x900000005; - fStack_40 = 9.80909e-45; - rng._shift1 = 5; - rng._seed = uVar1 | 1; - rng._shift2 = 9; - rng._shift3 = 7; - uVar1 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&picker),rng); - target = Entity_NPC::GetPlayerTarget(npc); - local_28 = GHIDRA_CAST(((target->_pos).x - (npc->_pos).x)); - targetDirY = (target->_pos).y - (npc->_pos).y; - targetDist = sqrtf((float)local_28 * (float)local_28 + targetDirY * targetDirY); - if (0.0 < targetDist) { - local_28 = GHIDRA_CAST(((float)local_28 * (1.0 / targetDist))); - targetDirY = targetDirY * (1.0 / targetDist); - } - *GHIDRA_CAST((GHIDRA_INT(&npc->_projectileDelay) + 3)) = 1; - if (uVar1 == 0) { - fStack_40 = (float)hornfel_pick_spawn(extraout_ECX); - uVar1 = (npc->_entityDeque)._offset; - uVar3 = uVar1 & 3; - dequeBlock = *GHIDRA_CAST((GHIDRA_INT((npc->_entityDeque)._map) + - ((npc->_entityDeque)._mapSize - 1 & uVar1 >> 2) * 4)); - childSlot = GHIDRA_CAST((dequeBlock + uVar3 * 4)); - if (*GHIDRA_CAST((dequeBlock + uVar3 * 4)) != 0) { - local_2c = childSlot; - msvc::multiset::erase(&local_2c); - } - *childSlot = fStack_40; - if (fStack_40 != 0.0) { - msvc::multiset::insert(childSlot); - } - if (-0.2 <= targetDirY) { - if (0.0 <= (float)local_28) { - animName = "Attack1Right"; - } - else { - animName = "Attack1Left"; - } -LAB_004b9068: - ANM2::Play(&npc->_sprite,GHIDRA_CAST(animName),0); - } - else { - animName = "Attack1Left_Back"; - if (0.0 <= (float)local_28) { - animName = "Attack1Right_Back"; - } - ANM2::Play(&npc->_sprite,GHIDRA_CAST(animName),0); - *GHIDRA_CAST((GHIDRA_INT(&npc->_projectileDelay) + 3)) = 0; - } - } - else { - if (uVar1 != 1) { - if (uVar1 == 2) { - ANM2::Play(&npc->_sprite,s_Attack2,0); - npc->_state = 9; - *GHIDRA_CAST(&npc->_projectileCooldown) = 0x96; - } - goto LAB_004b9077; - } - local_2c = GHIDRA_CAST(hornfel_pick_spawn(extraout_ECX)); - uVar1 = (npc->_entityDeque)._offset; - uVar3 = uVar1 & 3; - dequeBlock = *GHIDRA_CAST((GHIDRA_INT((npc->_entityDeque)._map) + - ((npc->_entityDeque)._mapSize - 1 & uVar1 >> 2) * 4)); - firstChildSlot = GHIDRA_CAST((dequeBlock + uVar3 * 4)); - uVar2 = 0; - if (*GHIDRA_CAST((dequeBlock + uVar3 * 4)) != 0) { - local_28 = firstChildSlot; - msvc::multiset::erase(&local_28); - uVar2 = extraout_ECX_00; - } - *firstChildSlot = local_2c; - if (local_2c != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(firstChildSlot); - uVar2 = extraout_ECX_01; - } - local_28 = GHIDRA_CAST(hornfel_pick_spawn(uVar2)); - uVar1 = (npc->_entityDeque)._offset + 1; - uVar3 = uVar1 & 3; - dequeBlock = *GHIDRA_CAST((GHIDRA_INT((npc->_entityDeque)._map) + - ((npc->_entityDeque)._mapSize - 1 & uVar1 >> 2) * 4)); - childSlot = GHIDRA_CAST((dequeBlock + uVar3 * 4)); - if (*GHIDRA_CAST((dequeBlock + uVar3 * 4)) != 0) { - local_2c = childSlot; - msvc::multiset::erase(&local_2c); - } - *childSlot = (float)local_28; - if (local_28 != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(childSlot); - } - if (-0.2 <= targetDirY) { - animName = "Attack1Double"; - goto LAB_004b9068; - } - ANM2::Play(&npc->_sprite,GHIDRA_CAST("Attack1Double_Back"),0); - *GHIDRA_CAST((GHIDRA_INT(&npc->_projectileDelay) + 3)) = 0; - } - npc->_state = 8; -LAB_004b9077: - *GHIDRA_CAST((GHIDRA_INT(&npc->_projectileDelay) + 2)) = 0; - if (picker != (void *)0x0) { - uVar1 = GHIDRA_INT(outcomesCapacity) - GHIDRA_INT(picker) & 0xfffffff8; - ptr = picker; - if (0xfff < uVar1) { - ptr = *(void **)(GHIDRA_CAST(picker) + -4); - uVar1 = uVar1 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(picker) + (-4 - GHIDRA_INT(ptr))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(ptr,uVar1); - } - ExceptionList = local_1c; - return; -} - -// 004b90e0 -void NpcHelper::hornfel_launch_toward(Entity_NPC *npc, Entity *entity, Vector *targetPos) -{ - int iVar1; - Entity *pEVar2; - float deltaX; - float fVar3; - float launchSpeed; - float npcPosY; - uint32_t *refSlot; - - fVar3 = targetPos->y; - deltaX = (npc->_pos).x - targetPos->x; - npcPosY = (npc->_pos).y - fVar3; - targetPos = GHIDRA_CAST(targetPos->x); - npcPosY = sqrtf(npcPosY * npcPosY + deltaX * deltaX); - pEVar2 = entity; - npcPosY = (npcPosY - 100.0) / 200.0; - if (npcPosY <= 0.0) { - npcPosY = 0.0; - } - if (1.0 <= npcPosY) { - npcPosY = 1.0; - } - launchSpeed = npcPosY * 18.0 + 10.0; - if (entity->_variant == 8) { - launchSpeed = launchSpeed * 0.75; - } - fVar3 = fVar3 - (npc->_pos).y; - targetPos = GHIDRA_CAST(((float)targetPos - (npc->_pos).x)); - npcPosY = sqrtf(fVar3 * fVar3 + (float)targetPos * (float)targetPos); - if (0.0 < npcPosY) { - targetPos = GHIDRA_CAST(((float)targetPos * (1.0 / npcPosY))); - fVar3 = fVar3 * (1.0 / npcPosY); - } - targetPos = GHIDRA_CAST(((float)targetPos * launchSpeed)); - refSlot = &pEVar2->_spawnerEntity; - if (*refSlot != 0) { - entity = GHIDRA_CAST(refSlot); - msvc::multiset::erase(&entity); - } - *refSlot = npc; - if (npc != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(refSlot); - } - refSlot = &pEVar2->_parent; - pEVar2->_spawnerType = npc->_type; - pEVar2->_spawnerVariant = npc->_variant; - if (*refSlot != 0) { - entity = GHIDRA_CAST(refSlot); - msvc::multiset::erase(&entity); - } - *refSlot = npc; - msvc::multiset::insert(refSlot); - pEVar2->_entityCollisionClass = 4; - pEVar2->_visible = 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(pEVar2[1])) + 0xc)))) = 0xc0800000; - (pEVar2->_posOffset).x = 0.0; - (pEVar2->_posOffset).y = -24.0; - (pEVar2->_pos).x = (npc->_pos).x; - npcPosY = (npc->_pos).y; - *GHIDRA_CAST(&pEVar2->_flags) = GHIDRA_UINT(pEVar2->_flags) & 0xffffffdf; - (pEVar2->_pos).y = npcPosY; - *GHIDRA_CAST((GHIDRA_INT(&pEVar2->_flags) + 4)) = *GHIDRA_CAST((GHIDRA_INT(&pEVar2->_flags) + 4)); - iVar1 = *GHIDRA_CAST(pEVar2); - (pEVar2->_velocity).x = (float)targetPos; - (pEVar2->_velocity).y = fVar3 * launchSpeed; - (**(code **)(iVar1 + 0xc))(); - return; -} - -// 004bb350 -Entity * NpcHelper::hornfel_free_door() -{ - uint32_t rngResult; - int *candidatesEnd; - float fVar1; - float fVar2; - int *candidatesEndCopy; - int railDoor; - uint32_t i; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - char *currentRoom; - int enterDoor; - void *room; - - puStack_c = &LAB_00af34dd; - local_10 = ExceptionList; - ExceptionList = &local_10; - candidatesEnd = GHIDRA_CAST(0x0); - candidatesEndCopy = GHIDRA_CAST(0x0); - room = g_game->_room; - local_8 = 0; - i = 0; - if (*GHIDRA_CAST((GHIDRA_CAST(room) + 0x1264)) != 0) { - do { - railDoor = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(room) + 0x125c)) + i * 4)); - if (((*GHIDRA_CAST((railDoor + 0x28)) == 0x3c7) && (*GHIDRA_CAST((railDoor + 0x3c4)) == 0)) && - ((*GHIDRA_CAST((railDoor + 0x3bc)) == 0 || (*GHIDRA_CAST((*GHIDRA_CAST((railDoor + 0x3bc)) + 0x3c4)) == 0)))) - { - currentRoom = g_game->_room; - if (((*currentRoom == '\0') || (g_game->_frameCount - *GHIDRA_CAST((currentRoom + 0x11f0)) < 0x1e) - ) && (enterDoor = g_game->_enterDoor, -1 < enterDoor)) { - if (enterDoor < 8) { - fVar1 = (float)(*GHIDRA_CAST((currentRoom + enterDoor * 4 + 0x744)) % - *GHIDRA_CAST((currentRoom + 0xc))) * 40.0 + 40.0; - fVar2 = (float)(*GHIDRA_CAST((currentRoom + enterDoor * 4 + 0x744)) / - *GHIDRA_CAST((currentRoom + 0xc))) * 40.0 + 120.0; - } - else { - fVar1 = g_vectorZero.x; - fVar2 = g_vectorZero.y; - } - fVar1 = *GHIDRA_CAST((railDoor + 0x33c)) - fVar1; - fVar2 = *GHIDRA_CAST((railDoor + 0x340)) - fVar2; - if (fVar2 * fVar2 + fVar1 * fVar1 <= 3600.0) goto LAB_004bb4af; - } - if (candidatesEnd == GHIDRA_CAST(0x0)) { - msvc::vector::_Emplace_reallocate(0,&railDoor); - candidatesEnd = candidatesEndCopy; - } - else { - *candidatesEnd = railDoor; - candidatesEndCopy = candidatesEnd + 1; - candidatesEnd = candidatesEndCopy; - } - } -LAB_004bb4af: - i = i + 1; - } while (i < *GHIDRA_CAST((GHIDRA_CAST(room) + 0x1264))); - if (candidatesEnd != GHIDRA_CAST(0x0)) { - if (GHIDRA_INT(candidatesEnd) >> 2 == 0) { - ExceptionList = local_10; - return pERam00000000; - } - rngResult = Random(); - ExceptionList = local_10; - return *GHIDRA_CAST(((rngResult % GHIDRA_UINT((GHIDRA_INT(candidatesEnd) >> 2))) * 4)); - } - } - ExceptionList = local_10; - return GHIDRA_CAST(0x0); -} - -// 004bb550 -Vector * NpcHelper::hornfel_get_rail_direction(Entity_NPC *npc, Vector *outDirection) -{ - int gridY; - uint32_t railSign; - uint32_t gridIdx; - int gridX; - uint8_t railFlags; - void *room; - float zeroY; - - zeroY = g_vectorZero.y; - room = g_game->_room; - gridX = GHIDRA_INT((((npc->_targetPosition).x - 40.0) / 40.0 + 0.5)); - if ((((-1 < gridX) && (gridX < *GHIDRA_CAST((GHIDRA_CAST(room) + 0xc)))) && - (gridY = GHIDRA_INT((((npc->_targetPosition).y - 120.0) / 40.0 + 0.5)), -1 < gridY)) && - (((gridY < *GHIDRA_CAST((GHIDRA_CAST(room) + 0x10)) && - (gridIdx = *GHIDRA_CAST((GHIDRA_CAST(room) + 0xc)) * gridY + gridX, gridIdx < 0x1c0)) && - (railFlags = *GHIDRA_CAST((gridIdx + 0x746c + GHIDRA_INT(room))), railFlags != 0xff)))) { - if ((railFlags & 0x40) == 0) { - if ((railFlags & 0x10) == 0) { - railSign = railFlags >> 5 & 1; - } - else { - railSign = 0xffffffff; - } - } - else { - railSign = 0; - } - railFlags = *GHIDRA_CAST((GHIDRA_CAST(room) + gridIdx + 0x746c)); - if (railSign != 0) { - if ((railFlags & 0xf) != 0) { - if (GHIDRA_INT(railSign) < 0) { - outDirection->x = 0.0; - outDirection->y = (float)&DAT_bf800000; - return outDirection; - } - outDirection->x = 0.0; - outDirection->y = 1.0; - return outDirection; - } - if (GHIDRA_INT(railSign) < 0) { - outDirection->x = (float)&DAT_bf800000; - outDirection->y = (float)(railFlags & 0xf); - return outDirection; - } - outDirection->x = 1.0; - outDirection->y = 0.0; - return outDirection; - } - } - outDirection->x = g_vectorZero.x; - outDirection->y = zeroY; - return outDirection; -} - -// 004bb6b0 -int NpcHelper::hornfel_next_rail_index(Entity_NPC *npc) -{ - int row; - uint32_t railDirection; - uint32_t gridIndex; - int iVar1; - uint8_t *directionSign; - Vector nextPos; - uint8_t railType; - Room *room; - - room = g_game->_room; - iVar1 = GHIDRA_INT((((npc->_targetPosition).x - 40.0) / 40.0 + 0.5)); - if ((((-1 < iVar1) && (iVar1 < room->_gridWidth)) && - (row = GHIDRA_INT((((npc->_targetPosition).y - 120.0) / 40.0 + 0.5)), -1 < row)) && - (((row < room->_gridHeight && (gridIndex = room->_gridWidth * row + iVar1, gridIndex < 0x1c0)) - && (railType = (room->_railManager)._sprite._filename._buf[gridIndex - 0x1c0], - railType != 0xff)))) { - if ((railType & 0x40) == 0) { - if ((railType & 0x10) == 0) { - railDirection = railType >> 5 & 1; - } - else { - railDirection = 0xffffffff; - } - } - else { - railDirection = 0; - } - if (railDirection != 0) { - if (((room->_railManager)._sprite._filename._buf[gridIndex - 0x1c0] & 0xfU) == 0) { - if (GHIDRA_INT(railDirection) < 0) { - directionSign = &DAT_bf800000; - } - else { - directionSign = GHIDRA_CAST(0x3f800000); - } - nextPos.x = (float)directionSign * 40.0 + (npc->_targetPosition).x; - nextPos.y = (npc->_targetPosition).y + 0.0; - iVar1 = Room::GetGridIndex(room,&nextPos); - return iVar1; - } - if (GHIDRA_INT(railDirection) < 0) { - directionSign = &DAT_bf800000; - } - else { - directionSign = GHIDRA_CAST(0x3f800000); - } - nextPos.x = (npc->_targetPosition).x + 0.0; - nextPos.y = (float)directionSign * 40.0 + (npc->_targetPosition).y; - iVar1 = Room::GetGridIndex(room,&nextPos); - return iVar1; - } - } - return -1; -} - -// 004bb830 -void NpcHelper::hornfel_set_anim(Entity_NPC *npc, int stateFrame) -{ - uint8_t bVar1; - uint8_t *curAnimChar; - uint32_t animCompare; - uint8_t *openAnimChar; - bool isLess; - int soundId; - uint8_t *animData; - Manager *manager; - - if (npc->_state != 3) goto LAB_004bb903; - animData = (npc->_sprite)._animState._animData; - if (animData == GHIDRA_CAST(0x0)) { -LAB_004bb896: - bVar1 = ANM2::SetAnimation(&npc->_sprite,s_Open,1); - if (bVar1 != 0) { - AnimationState::Rewind(&(npc->_sprite)._animState); - (npc->_sprite)._animState._isPlaying = 1; - } - } - else { - curAnimChar = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - curAnimChar = *GHIDRA_CAST(animData); - } - openAnimChar = s_Open; - do { - bVar1 = *curAnimChar; - isLess = bVar1 < *openAnimChar; - if (bVar1 != *openAnimChar) { -LAB_004bb880: - animCompare = -GHIDRA_UINT(isLess) | 1; - goto LAB_004bb885; - } - if (bVar1 == 0) break; - bVar1 = curAnimChar[1]; - isLess = bVar1 < openAnimChar[1]; - if (bVar1 != openAnimChar[1]) goto LAB_004bb880; - curAnimChar = curAnimChar + 2; - openAnimChar = openAnimChar + 2; - } while (bVar1 != 0); - animCompare = 0; -LAB_004bb885: - if ((animCompare != 0) || ((animData[0x34] != 0 && ((npc->_sprite)._animState._isPlaying == 0))) - ) goto LAB_004bb896; - } - manager = g_manager; - soundId = 0x24; - seed_fart_sound_override(&soundId); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(soundId,0.5,10,0,1.3,0.0); - npc->_state = 4; -LAB_004bb903: - npc->_stateFrame = stateFrame; - return; -} - -// 004bb920 -uint8_t NpcHelper::hornfel_claim_target(Entity_NPC *npc, Entity *target) -{ - int iVar1; - Entity *parentTargetRef; - Entity *targetLocal; - - targetLocal = target; - if ((npc->_target != 0) || ((iVar1 = npc->_parent, iVar1 != 0 && (*GHIDRA_CAST((iVar1 + 0x3c4)) != 0)))) - { - return 0; - } - npc->_target = target; - if (target != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(&npc->_target); - iVar1 = npc->_parent; - } - if (iVar1 != 0) { - parentTargetRef = GHIDRA_CAST((iVar1 + 0x3c4)); - if (*GHIDRA_CAST((iVar1 + 0x3c4)) != 0) { - target = parentTargetRef; - msvc::multiset::erase(&target); - } - *GHIDRA_CAST(parentTargetRef) = targetLocal; - if (targetLocal != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(parentTargetRef); - } - } - return 1; -} - -// 004bc460 -void NpcHelper::hornfel_room_controller(Entity_Effect *effect) -{ - uint32_t uVar1; - uint32_t uVar2; - Entity_NPC *npc; - uint32_t uVar3; - Entity *cart; - int iVar4; - Vector railDirection; - uint32_t cartTypeChoices [16]; - void *room; - int roomWidth; - - cartTypeChoices[0xe] = __security_cookie ^ GHIDRA_UINT(&railDirection); - room = g_game->_room; - if (effect->_state == 0) { - hornfel_spawn_doors(); - uVar2 = Random(); - effect->_state = 1; - iVar4 = uVar2 % 0xd2 + 0x96; - effect->_timeout = iVar4; - effect->_lifespan = iVar4; - return; - } - if ((*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(room) + 4)) + 0x44)) & 1) != 0) { - hornfel_remove_doors(); - (**(code **)(*GHIDRA_CAST(effect) + 0x28))(); - } - roomWidth = *GHIDRA_CAST((GHIDRA_CAST(room) + 0x12cc)) + *GHIDRA_CAST((GHIDRA_CAST(room) + 0x12c8)); - iVar4 = 0; - if (0 < roomWidth) { - iVar4 = roomWidth; - } - if ((0 < iVar4) && (effect->_dead != 0)) { - npc = GHIDRA_CAST(hornfel_free_door()); - if (npc != GHIDRA_CAST(0x0)) { - hornfel_get_rail_direction(npc,&railDirection); - if ((railDirection.x != g_vectorZero.x) || (railDirection.y != g_vectorZero.y)) { - cartTypeChoices[0] = 0x337; - cartTypeChoices[1] = 0; - cartTypeChoices[2] = 0x334; - cartTypeChoices[3] = 0; - cartTypeChoices[0xc] = 0x124; - cartTypeChoices[4] = 0x33b; - cartTypeChoices[5] = 0; - cartTypeChoices[6] = 0xe3; - cartTypeChoices[7] = 0; - cartTypeChoices[0xd] = 0; - cartTypeChoices[8] = 0x57; - cartTypeChoices[9] = 0; - cartTypeChoices[10] = 0x21; - cartTypeChoices[0xb] = 0; - uVar2 = Random(); - uVar3 = Random(); - cart = Game::SpawnEx(g_game,cartTypeChoices[(uVar2 % 7) * 2], - cartTypeChoices[(uVar2 % 7) * 2 + 1],&g_vectorZero,&g_vectorZero, - GHIDRA_CAST(0x0),0,uVar3,0); - uVar1 = *GHIDRA_CAST((GHIDRA_INT(&cart->_flags) + 4)); - *GHIDRA_CAST(&cart->_flags) = GHIDRA_UINT(cart->_flags) & 0xfffffffb; - *GHIDRA_CAST((GHIDRA_INT(&cart->_flags) + 4)) = uVar1; - cart->_spawnerType = 0x38a; - Entity::GiveMinecart(cart,&npc->_targetPosition,&railDirection); - hornfel_claim_target(npc,cart); - } - } - uVar2 = Random(); - uVar2 = uVar2 % 0xd2 + 0x96; - iVar4 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x10)); - roomWidth = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0xc)); - effect->_dead = 0; - uVar3 = uVar2 / 2; - if (iVar4 * roomWidth < 0x88) { - uVar3 = uVar2; - } - effect->_timeout = uVar3; - effect->_lifespan = uVar3; - } - return; -} - -// 00528ec0 -void NpcHelper::migraine_timer_spawn(Entity *timer) -{ - int *piVar1; - int64_t lVar2; - int64_t lVar3; - int64_t lVar4; - float fVar5; - uint8_t isErased; - char cVar6; - uint32_t uVar7; - uint32_t uVar8; - int *piVar9; - int iVar10; - Entity *pEVar11; - int unusedArg; - int unusedArg_00; - void *pvVar12; - uint32_t uVar13; - uint32_t uVar14; - PlayerManager *playerManager; - bool bVar15; - float fVar16; - float fVar17; - uint64_t timeNs; - float local_124; - Entity *local_120; - Game *local_11c; - void *local_118; - float local_114; - float local_110; - float local_10c; - uint32_t local_108; - uint32_t local_104; - float spawnVelX; - float fStack_fc; - Game *local_f4; - Entity *owner; - Vector spawnPos; - uint32_t local_e4; - uint32_t local_e0; - Vector local_d4; - uint32_t uStack_cc; - uint32_t spawnSeed; - void *pvStack_c4; - int *apiStack_bc [4]; - Vector particleVel; - int *local_a4; - Vector spawnVel [2]; - int iStack_8c; - uint32_t uStack_88; - int iStack_84; - uint32_t uStack_80; - Vector bloodVel [2]; - uint32_t uStack_6c; - uint32_t local_68; - uint32_t uStack_64; - uint32_t local_60 [5]; - uint8_t auStack_4c [8]; - int foundNode2; - int foundNode; - uint8_t auStack_30 [8]; - int iStack_28; - int iStack_24; - uint32_t uStack_20; - uint32_t stackCookie; - code *fnPtr; - Game *game; - uint32_t *spawnerRef; - ColorMod *spriteColor; - - stackCookie = __security_cookie ^ GHIDRA_UINT(&local_124); - spawnPos.x = (timer->_pos).x; - spawnPos.y = (timer->_pos).y; - owner = timer; - uVar7 = Random(); - fVar16 = (float)((double)GHIDRA_INT(uVar7) + __uint_to_double_fixup[-(GHIDRA_INT(uVar7) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - local_120 = GHIDRA_CAST((fVar16 + fVar16)); - uVar7 = Random(); - local_110 = (float)((double)GHIDRA_INT(uVar7) + __uint_to_double_fixup[-(GHIDRA_INT(uVar7) >> 0x1f)]) * - 2.3283064e-10 * 4.0 + 6.0; - spawnVelX = cos((float)local_120); - spawnVelX = spawnVelX * local_110; - spawnVel[0].x = spawnVelX; - fVar16 = sin((float)local_120); - local_118 = (void *)(fVar16 * local_110); - spawnVel[0].y = (float)local_118; - spawnSeed = Random(); - local_11c = g_game; - local_114 = 0.0; - local_e4 = 3; - local_f4 = GHIDRA_CAST(&DAT_00000004); - lua_callback_run_pre_entity_spawn - (GHIDRA_CAST(&local_f4),GHIDRA_CAST(&local_e4),&spawnPos,spawnVel,GHIDRA_CAST(0x0),GHIDRA_CAST(&local_114), - &spawnSeed); - uVar7 = local_e4; - if (*GHIDRA_CAST(&g_game->_deathmatchManager) < 2) { -LAB_0052926a: - local_124 = local_114; - } - else { - pEVar11 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((g_game->_deathmatchManager))) + 0xc)))); - local_120 = pEVar11; - uVar8 = Random(); - fVar16 = local_114; - local_68 = 5; - uStack_64 = 9; - local_110 = 9.80909e-45; - local_60[0] = 7; - if (local_f4 != GHIDRA_CAST(&DAT_00000005)) goto LAB_0052926a; - if (uVar7 < 0x12d) { - if (uVar7 == 300) { - while ((local_124 = local_114, local_114 == 0.0 || - (cVar6 = (**(code **)(*GHIDRA_CAST(pEVar11) + 0x24))(), cVar6 != '\0'))) { - if (uVar8 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - fnPtr = (code *)swi(3); - (*fnPtr)(); - return; - } - uVar8 = uVar8 >> ((uint8_t)local_68 & 0x1f) ^ uVar8; - uVar8 = uVar8 << ((uint8_t)uStack_64 & 0x1f) ^ uVar8; - uVar8 = uVar8 >> (SUB41(local_110,0) & 0x1f) ^ uVar8; - iVar10 = ItemPool::GetCardEx(uVar8,0x19,10,10,1); - iStack_28 = 5; - iStack_24 = 9; - uStack_20 = 7; - (*GHIDRA_CAST((GHIDRA_CAST(&(auStack_30)) + 0x4))) = uVar8; - local_114 = (float)lua_callback_run_get_card(GHIDRA_CAST((auStack_30 + 4)),iVar10,1,1,0); - } - } - else { - if (uVar7 == 0x46) { - local_d4.x = (float)(GHIDRA_UINT(local_114) >> 0xb); - do { - local_124 = local_114; - if (local_114 != 0.0) { - fnPtr = *(code **)(*GHIDRA_CAST(pEVar11) + 0x28); - ItemPool::GetPillEffect(&g_game->_itemPool,GHIDRA_UINT(local_114),GHIDRA_CAST(0x0)); - cVar6 = (*fnPtr)(); - if (cVar6 == '\0') goto LAB_00529272; - pEVar11 = local_120; - } - if (uVar8 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - fnPtr = (code *)swi(3); - (*fnPtr)(); - return; - } - uVar8 = uVar8 >> ((uint8_t)local_68 & 0x1f) ^ uVar8; - uVar8 = uVar8 << ((uint8_t)uStack_64 & 0x1f) ^ uVar8; - uVar8 = uVar8 >> (SUB41(local_110,0) & 0x1f) ^ uVar8; - uVar7 = ItemPool::GetPill(uVar8); - local_114 = (float)(uVar7 | (GHIDRA_UINT(local_d4.x) & 1) << 0xb); - } while( true ); - } - if (uVar7 != 100) goto LAB_0052926a; - local_124 = local_114; - if (local_114 == 3.50325e-44) { -LAB_005290ba: - bVar15 = false; - } - else { - local_d4.x = local_114; - msvc::set::find_node(); - if (((*GHIDRA_CAST((foundNode + 0xd)) == '\0') && (*GHIDRA_CAST((foundNode + 0x10)) <= GHIDRA_INT(fVar16))) - && (foundNode != pEVar11->_index)) goto LAB_005290ba; - bVar15 = true; - } - if ((fVar16 == 0.0) || (bVar15)) { - local_124 = (float)(**(code **)(*GHIDRA_CAST(pEVar11) + 0x84))(); - local_114 = local_124; - } - } - } - else { - if (uVar7 != 0x15e) goto LAB_0052926a; - while ((local_124 = local_114, local_114 == 0.0 || - (cVar6 = (**(code **)(*GHIDRA_CAST(pEVar11) + 0x2c))(), cVar6 != '\0'))) { - local_114 = (float)ItemPool::GetTrinket(&g_game->_itemPool,0); - } - } - } -LAB_00529272: - local_120 = EntityFactory::Create(local_11c->_entityFactory,GHIDRA_UINT(local_f4),0); - if (local_120 == GHIDRA_CAST(0x0)) goto LAB_00529568; - timeNs = GetTimeNs(); - pEVar11 = local_120; - local_108 = GHIDRA_UINT((timeNs >> 0x20)); - lVar2 = (timeNs & 0xffffffff) * 0x431bde82; - local_104 = GHIDRA_UINT(((uint64_t)lVar2 >> 0x20)); - lVar3 = (uint64_t)local_108 * 0xd7b634db + ((timeNs & 0xffffffff) * 0xd7b634db >> 0x20); - local_d4.y = (float)(lVar3 + lVar2); - lVar2 = (uint64_t)local_108 * 0x431bde82 + - (uint64_t) - CONCAT14(CARRY4(GHIDRA_UINT(((uint64_t)lVar3 >> 0x20)), - local_104 + CARRY4(GHIDRA_UINT(lVar2),GHIDRA_UINT(lVar3))), - GHIDRA_INT(((uint64_t)(lVar3 + lVar2) >> 0x20))); - local_e0 = GHIDRA_UINT(((uint64_t)lVar2 >> 0x20)); - spawnerRef = &local_120->_spawnerEntity; - local_10c = (float)(GHIDRA_UINT(lVar2) >> 0x12 | local_e0 * 0x4000); - local_e0 = local_e0 >> 0x12; - local_120->_spawnerType = 0; - local_120->_spawnerVariant = 0; - if (*spawnerRef != 0) { - local_a4 = spawnerRef; - msvc::multiset::erase(); - } - iVar10 = *GHIDRA_CAST(pEVar11); - *spawnerRef = 0; - (pEVar11->_pos).x = spawnPos.x; - (pEVar11->_pos).y = spawnPos.y; - (pEVar11->_velocity).x = spawnVelX; - (pEVar11->_velocity).y = (float)local_118; - (**(code **)(iVar10 + 4))(local_f4,local_e4); - game = local_11c; - pvVar12 = local_11c->_room; - iVar10 = *GHIDRA_CAST((GHIDRA_CAST(pvVar12) + 0x1214)); - *GHIDRA_CAST((GHIDRA_CAST(pvVar12) + 0x1214)) = iVar10 + 1; - pEVar11->_index = iVar10; - EntityList::AddEntity(GHIDRA_CAST((GHIDRA_INT(pvVar12) + 0x1218)),pEVar11); - isErased = Game::ShouldEraseEnemy(pEVar11); - if (isErased != 0) { - Entity::RemoveWithPoof(pEVar11,unusedArg); - } - if ((pEVar11->_exists != 0) && - ((game->_proceduralItemManager)._proceduralItems._begin != - (game->_proceduralItemManager)._proceduralItems._end)) { - uStack_88 = pEVar11->_variant; - iStack_8c = pEVar11->_type; - msvc::map::find(); - pvVar12 = (game->_proceduralItemManager)._spawnTriggerTargets._head; - if (pvStack_c4 == pvVar12) { - iStack_84 = pEVar11->_type; - uStack_80 = 0xffffffff; - piVar9 = GHIDRA_CAST(std)::map::find(); - pvStack_c4 = (void *)*piVar9; - if (pvStack_c4 == pvVar12) goto LAB_005294e4; - } - uVar7 = 0; - playerManager = &g_game->_playerManager; - if (GHIDRA_INT((g_game->_playerManager)._playerList._end) - GHIDRA_INT((playerManager->_playerList)._begin) >> - 2 != 0) { - do { - pvVar12 = (playerManager->_playerList)._end; - if (GHIDRA_INT(pvVar12) - GHIDRA_INT((playerManager->_playerList)._begin) >> 2 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("PlayerManager::GetPlayer() : There are no players! \n")); - pvVar12 = (playerManager->_playerList)._end; - } - piVar9 = (playerManager->_playerList)._begin; - if (uVar7 < GHIDRA_UINT((GHIDRA_INT(pvVar12) - GHIDRA_INT(piVar9) >> 2))) { - piVar9 = piVar9 + uVar7; - } - trigger_set_dispatch((void *)(*piVar9 + 0x1fc8),6,pEVar11,&spawnPos,spawnVel); - uVar7 = uVar7 + 1; - playerManager = &g_game->_playerManager; - } while (uVar7 < GHIDRA_UINT((GHIDRA_INT((g_game->_playerManager)._playerList._end) - - GHIDRA_INT((playerManager->_playerList)._begin) >> 2))); - } - } -LAB_005294e4: - timeNs = GetTimeNs(); - uVar7 = GHIDRA_UINT((timeNs >> 0x20)); - lVar2 = (timeNs & 0xffffffff) * 0x431bde82; - local_104 = GHIDRA_UINT(((uint64_t)lVar2 >> 0x20)); - lVar3 = (uint64_t)uVar7 * 0x431bde82; - local_108 = GHIDRA_UINT(lVar3); - lVar4 = (uint64_t)uVar7 * 0xd7b634db + ((timeNs & 0xffffffff) * 0xd7b634db >> 0x20); - local_d4.y = (float)(lVar4 + lVar2); - lVar3 = lVar3 + (uint64_t) - CONCAT14(CARRY4(GHIDRA_UINT(((uint64_t)lVar4 >> 0x20)), - local_104 + CARRY4(GHIDRA_UINT(lVar2),GHIDRA_UINT(lVar4))), - GHIDRA_INT(((uint64_t)(lVar4 + lVar2) >> 0x20))); - uVar8 = GHIDRA_UINT(((uint64_t)lVar3 >> 0x20)); - fVar16 = (float)(GHIDRA_UINT(lVar3) >> 0x12 | uVar8 * 0x4000); - uVar7 = GHIDRA_INT(fVar16) - GHIDRA_INT(local_10c); - bVar15 = CARRY4(GHIDRA_UINT(g_entitySpawnTimeMs),uVar7); - (*GHIDRA_CAST((GHIDRA_CAST(&(g_entitySpawnTimeMs)) + 0x0))) = GHIDRA_UINT(g_entitySpawnTimeMs) + uVar7; - (*GHIDRA_CAST((GHIDRA_CAST(&(g_entitySpawnTimeMs)) + 0x4))) = - (*GHIDRA_CAST((GHIDRA_CAST(&(g_entitySpawnTimeMs)) + 0x4))) + - (((uVar8 >> 0x12) - local_e0) - GHIDRA_UINT((GHIDRA_UINT(fVar16) < GHIDRA_UINT(local_10c)))) + GHIDRA_UINT(bVar15); -LAB_00529568: - bloodVel[0].x = spawnVelX * 0.4; - bloodVel[0].y = (float)local_118 * 0.4; - iVar10 = GHIDRA_INT(owner[1]._pendingDamageFlags) * -7 + 0x42; - *GHIDRA_CAST((local_120 + 1)) = iVar10; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(local_120[1])) + 0x4)))) = iVar10; - uVar7 = Random(); - pEVar11 = Game::Spawn(g_game,1000,2,&spawnPos,bloodVel,GHIDRA_CAST(0x0),1,uVar7); - (**(code **)(*GHIDRA_CAST(pEVar11) + 0x3c))(&DAT_00c5c800,0xffffffff,0xff); - (pEVar11->_sprite)._offset.x = 0.0; - (pEVar11->_sprite)._offset.y = -5.0; - pEVar11->_renderDepthOffset = 10.0; - uVar7 = Random(); - local_11c = GHIDRA_CAST(((uVar7 & 1) + 1)); - do { - if (local_11c == GHIDRA_CAST(0x0)) { - return; - } - uVar7 = Random(); - fVar16 = (float)((double)GHIDRA_INT(uVar7) + __uint_to_double_fixup[-(GHIDRA_INT(uVar7) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - local_f4 = GHIDRA_CAST((fVar16 + fVar16)); - fVar16 = cos((float)local_f4); - local_d4.x = fVar16 * 12.0 * 0.5 + spawnVelX; - fVar16 = sin((float)local_f4); - local_d4.y = fVar16 * 12.0 * 0.5 + fStack_fc; - uVar7 = Random(); - fVar16 = (float)((double)GHIDRA_INT(uVar7) + __uint_to_double_fixup[-(GHIDRA_INT(uVar7) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - fVar16 = fVar16 + fVar16; - uVar7 = Random(); - local_114 = (float)((double)GHIDRA_INT(uVar7) + __uint_to_double_fixup[-(GHIDRA_INT(uVar7) >> 0x1f)]) * - 2.3283064e-10 * 4.0 + 2.0; - fVar17 = cos(fVar16); - pvStack_c4 = (void *)(fVar17 * local_114); - particleVel.x = (float)pvStack_c4; - local_10c = sin(fVar16); - local_10c = local_10c * local_114; - particleVel.y = local_10c; - local_104 = Random(); - local_f4 = g_game; - piVar9 = GHIDRA_CAST(0x0); - local_124 = 7.00649e-45; - local_120 = GHIDRA_CAST(0x3e8); - lua_callback_run_pre_entity_spawn - (GHIDRA_CAST(&local_120),GHIDRA_CAST(&local_124),&local_d4,&particleVel,GHIDRA_CAST(0x0), - GHIDRA_CAST((apiStack_bc + -0x1f)),&local_104); - fVar16 = local_124; - if (1 < *GHIDRA_CAST(&g_game->_deathmatchManager)) { - piVar1 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((g_game->_deathmatchManager))) + 0xc)))); - uVar7 = Random(); - uStack_6c = 5; - local_68 = 9; - local_114 = 9.80909e-45; - uStack_64 = 7; - if (local_120 == GHIDRA_CAST(&DAT_00000005)) { - if (GHIDRA_UINT(fVar16) < 0x12d) { - if (fVar16 == 4.2039e-43) { - while ((piVar9 == GHIDRA_CAST(0x0) || - (cVar6 = (**(code **)(*piVar1 + 0x24))(piVar9), cVar6 != '\0'))) { - if (uVar7 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - fnPtr = (code *)swi(3); - (*fnPtr)(); - return; - } - uVar7 = uVar7 >> ((uint8_t)uStack_6c & 0x1f) ^ uVar7; - uVar7 = uVar7 << ((uint8_t)local_68 & 0x1f) ^ uVar7; - uVar7 = uVar7 >> (SUB41(local_114,0) & 0x1f) ^ uVar7; - iVar10 = ItemPool::GetCardEx(uVar7,0x19,10,10,1); - (*GHIDRA_CAST((GHIDRA_CAST(&(auStack_30)) + 0x4))) = 5; - iStack_28 = 9; - iStack_24 = 7; - (*GHIDRA_CAST((GHIDRA_CAST(&(auStack_30)) + 0x0))) = uVar7; - piVar9 = GHIDRA_CAST(lua_callback_run_get_card(GHIDRA_CAST(auStack_30),iVar10,1,1,0)); - } - } - else { - if (fVar16 == 9.80909e-44) { - uVar8 = GHIDRA_UINT(piVar9) >> 0xb; - do { - if (piVar9 != GHIDRA_CAST(0x0)) { - fnPtr = *(code **)(*piVar1 + 0x28); - iVar10 = ItemPool::GetPillEffect - (&g_game->_itemPool,GHIDRA_UINT(piVar9),GHIDRA_CAST(0x0)); - cVar6 = (*fnPtr)(iVar10); - if (cVar6 == '\0') goto LAB_00529a2e; - } - if (uVar7 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - fnPtr = (code *)swi(3); - (*fnPtr)(); - return; - } - uVar7 = uVar7 >> ((uint8_t)uStack_6c & 0x1f) ^ uVar7; - uVar7 = uVar7 << ((uint8_t)local_68 & 0x1f) ^ uVar7; - uVar7 = uVar7 >> (SUB41(local_114,0) & 0x1f) ^ uVar7; - uVar13 = ItemPool::GetPill(uVar7); - piVar9 = GHIDRA_CAST((uVar13 | (uVar8 & 1) << 0xb)); - } while( true ); - } - if (fVar16 == 1.4013e-43) { - if (piVar9 == GHIDRA_CAST(0x19)) { -LAB_00529876: - bVar15 = false; - } - else { - local_a4 = piVar9; - msvc::set::find_node(auStack_4c,&local_a4); - if (((*GHIDRA_CAST((foundNode2 + 0xd)) == '\0') && - (*GHIDRA_CAST((foundNode2 + 0x10)) <= GHIDRA_INT(piVar9))) && (foundNode2 != piVar1[8])) - goto LAB_00529876; - bVar15 = true; - } - if ((piVar9 == GHIDRA_CAST(0x0)) || (bVar15)) { - piVar9 = GHIDRA_CAST((**(code **)(*piVar1 + 0x84))(0)); - } - } - } - } - else if (fVar16 == 4.90454e-43) { - while ((piVar9 == GHIDRA_CAST(0x0) || - (cVar6 = (**(code **)(*piVar1 + 0x2c))(piVar9), cVar6 != '\0'))) { - piVar9 = GHIDRA_CAST(ItemPool)::GetTrinket(&g_game->_itemPool,0); - } - } - } - } -LAB_00529a2e: - pEVar11 = EntityFactory::Create(local_f4->_entityFactory,GHIDRA_UINT(local_120),0); - if (pEVar11 != GHIDRA_CAST(0x0)) { - timeNs = GetTimeNs(); - uVar7 = GHIDRA_UINT((timeNs >> 0x20)); - lVar2 = (timeNs & 0xffffffff) * 0x431bde82; - lVar3 = (uint64_t)uVar7 * 0xd7b634db + ((timeNs & 0xffffffff) * 0xd7b634db >> 0x20); - local_114 = (float)(lVar3 + lVar2); - lVar2 = (uint64_t)uVar7 * 0x431bde82 + - (uint64_t) - CONCAT14(CARRY4(GHIDRA_UINT(((uint64_t)lVar3 >> 0x20)), - GHIDRA_INT(((uint64_t)lVar2 >> 0x20)) + - GHIDRA_UINT(CARRY4(GHIDRA_UINT(lVar2),GHIDRA_UINT(lVar3)))), - GHIDRA_INT(((uint64_t)(lVar3 + lVar2) >> 0x20))); - uStack_cc = GHIDRA_UINT(((uint64_t)lVar2 >> 0x20)); - spawnerRef = &pEVar11->_spawnerEntity; - uVar7 = GHIDRA_UINT(lVar2) >> 0x12 | uStack_cc * 0x4000; - uStack_cc = uStack_cc >> 0x12; - pEVar11->_spawnerType = 0; - pEVar11->_spawnerVariant = 0; - if (*spawnerRef != 0) { - apiStack_bc[0] = spawnerRef; - msvc::multiset::erase(apiStack_bc); - } - iVar10 = *GHIDRA_CAST(pEVar11); - *spawnerRef = 0; - (pEVar11->_pos).x = local_d4.x; - (pEVar11->_pos).y = local_d4.y; - (pEVar11->_velocity).x = (float)pvStack_c4; - (pEVar11->_velocity).y = local_10c; - (**(code **)(iVar10 + 4))(local_120,local_124,piVar9,local_104); - game = local_f4; - pvVar12 = local_f4->_room; - iVar10 = *GHIDRA_CAST((GHIDRA_CAST(pvVar12) + 0x1214)); - *GHIDRA_CAST((GHIDRA_CAST(pvVar12) + 0x1214)) = iVar10 + 1; - pEVar11->_index = iVar10; - EntityList::AddEntity(GHIDRA_CAST((GHIDRA_INT(pvVar12) + 0x1218)),pEVar11); - isErased = Game::ShouldEraseEnemy(pEVar11); - if (isErased != 0) { - Entity::RemoveWithPoof(pEVar11,unusedArg_00); - } - if ((pEVar11->_exists != 0) && - ((game->_proceduralItemManager)._proceduralItems._begin != - (game->_proceduralItemManager)._proceduralItems._end)) { - iStack_84 = pEVar11->_variant; - uVar8 = pEVar11->_type; - uStack_88 = uVar8; - msvc::map::find(&local_118,&uStack_88); - if (local_118 == (game->_proceduralItemManager)._spawnTriggerTargets._head) { - local_e0 = 0xffffffff; - local_e4 = uVar8; - piVar9 = GHIDRA_CAST(std)::map::find(local_60,&local_e4); - local_118 = (void *)*piVar9; - if (local_118 == (game->_proceduralItemManager)._spawnTriggerTargets._head) - goto LAB_00529ca4; - } - uVar8 = 0; - playerManager = &g_game->_playerManager; - if (GHIDRA_INT((g_game->_playerManager)._playerList._end) - - GHIDRA_INT((playerManager->_playerList)._begin) >> 2 != 0) { - do { - pvVar12 = (playerManager->_playerList)._end; - if (GHIDRA_INT(pvVar12) - GHIDRA_INT((playerManager->_playerList)._begin) >> 2 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("PlayerManager::GetPlayer() : There are no players! \n")); - pvVar12 = (playerManager->_playerList)._end; - } - piVar9 = (playerManager->_playerList)._begin; - if (uVar8 < GHIDRA_UINT((GHIDRA_INT(pvVar12) - GHIDRA_INT(piVar9) >> 2))) { - piVar9 = piVar9 + uVar8; - } - trigger_set_dispatch((void *)(*piVar9 + 0x1fc8),6,pEVar11,&local_d4,&particleVel); - uVar8 = uVar8 + 1; - playerManager = &g_game->_playerManager; - } while (uVar8 < GHIDRA_UINT((GHIDRA_INT((g_game->_playerManager)._playerList._end) - - GHIDRA_INT((playerManager->_playerList)._begin) >> 2))); - } - } -LAB_00529ca4: - timeNs = GetTimeNs(); - uVar8 = GHIDRA_UINT((timeNs >> 0x20)); - lVar2 = (timeNs & 0xffffffff) * 0x431bde82; - pvStack_c4 = (void *)((uint64_t)lVar2 >> 0x20); - lVar3 = (uint64_t)uVar8 * 0x431bde82; - local_10c = (float)lVar3; - lVar4 = (uint64_t)uVar8 * 0xd7b634db + ((timeNs & 0xffffffff) * 0xd7b634db >> 0x20); - local_f4 = GHIDRA_CAST((lVar4 + lVar2)); - lVar3 = lVar3 + (uint64_t) - CONCAT14(CARRY4(GHIDRA_UINT(((uint64_t)lVar4 >> 0x20)), - GHIDRA_INT(pvStack_c4) + GHIDRA_UINT(CARRY4(GHIDRA_UINT(lVar2),GHIDRA_UINT(lVar4)))), - GHIDRA_INT(((uint64_t)(lVar4 + lVar2) >> 0x20))); - uVar14 = GHIDRA_UINT(((uint64_t)lVar3 >> 0x20)); - uVar8 = GHIDRA_UINT(lVar3) >> 0x12 | uVar14 * 0x4000; - uVar13 = uVar8 - uVar7; - bVar15 = CARRY4(GHIDRA_UINT(g_entitySpawnTimeMs),uVar13); - (*GHIDRA_CAST((GHIDRA_CAST(&(g_entitySpawnTimeMs)) + 0x0))) = GHIDRA_UINT(g_entitySpawnTimeMs) + uVar13; - (*GHIDRA_CAST((GHIDRA_CAST(&(g_entitySpawnTimeMs)) + 0x4))) = - (*GHIDRA_CAST((GHIDRA_CAST(&(g_entitySpawnTimeMs)) + 0x4))) + (((uVar14 >> 0x12) - uStack_cc) - GHIDRA_UINT((uVar8 < uVar7))) + - GHIDRA_UINT(bVar15); - } - (**(code **)(*GHIDRA_CAST(pEVar11) + 0x3c))(&DAT_00c5c800,0xffffffff,0xff,0,1); - spriteColor = &(pEVar11->_sprite)._color; - if (&pEVar11->_splatColor != spriteColor) { - fVar16 = (pEVar11->_sprite)._color._tint[1]; - fVar17 = (pEVar11->_sprite)._color._tint[2]; - fVar5 = (pEVar11->_sprite)._color._tint[3]; - (pEVar11->_splatColor)._tint[0] = spriteColor->_tint[0]; - (pEVar11->_splatColor)._tint[1] = fVar16; - (pEVar11->_splatColor)._tint[2] = fVar17; - (pEVar11->_splatColor)._tint[3] = fVar5; - fVar16 = (pEVar11->_sprite)._color._colorize[1]; - fVar17 = (pEVar11->_sprite)._color._colorize[2]; - fVar5 = (pEVar11->_sprite)._color._colorize[3]; - (pEVar11->_splatColor)._colorize[0] = (pEVar11->_sprite)._color._colorize[0]; - (pEVar11->_splatColor)._colorize[1] = fVar16; - (pEVar11->_splatColor)._colorize[2] = fVar17; - (pEVar11->_splatColor)._colorize[3] = fVar5; - *GHIDRA_CAST((pEVar11->_splatColor)._offset) = - *GHIDRA_CAST((pEVar11->_sprite)._color._offset); - (pEVar11->_splatColor)._offset[2] = (pEVar11->_sprite)._color._offset[2]; - } - (**(code **)(*GHIDRA_CAST(pEVar11) + 0xc))(); - local_11c = GHIDRA_CAST((GHIDRA_INT(local_11c) + -1)); - } while( true ); -} - // 0055d070 uint8_t NpcHelper::polty_target_set(int gridIndex) { @@ -3033,364 +759,6 @@ LAB_00575ed0: return; } -// 00576090 -void NpcHelper::raglich_pick_target_pos(Entity_NPC *npc, float speed) -{ - float fVar1; - float fVar2; - uint8_t isInRoom; - int gridWidth; - uint32_t direction; - int row; - int iVar3; - Vector probePos; - Vector clampedPos; - Vector local_24; - Vector local_1c; - Vector local_14; - Vector local_c; - Game *game; - Vector *minResult; - Room *room; - - direction = *GHIDRA_CAST((GHIDRA_INT(&npc->_i1) + 2)) + 4 + GHIDRA_INT((short)npc->_i1) & 0x80000003; - if (GHIDRA_INT(direction) < 0) { - direction = (direction - 1 | 0xfffffffc) + 1; - } - local_c.y = speed; - Isaac::GetAxisAlignedUnitVectorFromDir(&local_24,direction); - Isaac::GetAxisAlignedUnitVectorFromDir(&local_1c,GHIDRA_INT((short)npc->_i1)); - game = g_game; - fVar1 = (npc->_v1).y; - fVar2 = npc->_speedMultiplier; - local_14.y = ((npc->_pos).y - (npc->_targetPosition).y) * local_1c.y + - ((npc->_pos).x - (npc->_targetPosition).x) * local_1c.x; - local_14.x = local_1c.x * local_14.y; - local_14.y = local_1c.y * local_14.y; - (npc->_velocity).x = - ((local_24.x * local_c.y + 0.0) - local_14.x * 0.1) * fVar1 * fVar2 + (npc->_velocity).x; - (npc->_velocity).y = - ((local_24.y * local_c.y + 0.0) - local_14.y * 0.1) * fVar1 * fVar2 + (npc->_velocity).y; - room = game->_room; - local_14.x = (npc->_pos).x - local_14.x; - local_14.y = (npc->_pos).y - local_14.y; - Room::GetClampedPositionImpl(room,&clampedPos,&local_14,10.0,10.0,10.0,10.0); - local_14.y = local_24.x * 40.0; - local_24.y = local_24.y * 40.0; - local_c.x = clampedPos.x + local_14.y; - local_c.y = clampedPos.y + local_24.y; - isInRoom = Room::IsPositionInRoom(room,&local_c,0.0); - if (isInRoom == 0) { - direction = (GHIDRA_INT((short)npc->_i1) - GHIDRA_INT(*GHIDRA_CAST((GHIDRA_INT(&npc->_i1) + 2)))) + 4U & 0x80000003; - if (GHIDRA_INT(direction) < 0) { - direction = (direction - 1 | 0xfffffffc) + 1; - } - *GHIDRA_CAST(&npc->_i1) = (short)direction; - iVar3 = GHIDRA_INT(((clampedPos.x - 40.0) / 40.0 + 0.5)); - row = GHIDRA_INT(((clampedPos.y - 120.0) / 40.0 + 0.5)); - if ((((iVar3 < 0) || (gridWidth = room->_gridWidth, gridWidth <= iVar3)) || (row < 0)) || - (room->_gridHeight <= row)) { - gridWidth = room->_gridWidth; - iVar3 = -1; - } - else { - iVar3 = gridWidth * row + iVar3; - } - row = iVar3 / gridWidth; - iVar3 = iVar3 % gridWidth; - } - else { - if (3 < *GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((room)) + 0x4)))) + 0x10)) + 0x48)) - 9U) goto LAB_00576404; - probePos.x = clampedPos.x - local_1c.x * 40.0; - probePos.y = clampedPos.y - local_1c.y * 40.0; - local_1c.y = probePos.y; - local_c.y = probePos.x; - isInRoom = Room::IsPositionInRoom(room,&probePos,0.0); - if (isInRoom == 0) goto LAB_00576404; - probePos.x = local_c.y - local_14.y; - probePos.y = local_1c.y - local_24.y; - isInRoom = Room::IsPositionInRoom(room,&probePos,0.0); - if (isInRoom != 0) goto LAB_00576404; - direction = (short)npc->_i1 + 4 + GHIDRA_INT(*GHIDRA_CAST((GHIDRA_INT(&npc->_i1) + 2))) & 0x80000003; - if (GHIDRA_INT(direction) < 0) { - direction = (direction - 1 | 0xfffffffc) + 1; - } - *GHIDRA_CAST(&npc->_i1) = (short)direction; - iVar3 = Room::GetGridIndex(room,&clampedPos); - row = iVar3 / room->_gridWidth; - iVar3 = iVar3 % room->_gridWidth; - } - (npc->_targetPosition).y = (float)row * 40.0 + 120.0; - (npc->_targetPosition).x = (float)iVar3 * 40.0 + 40.0; -LAB_00576404: - local_1c.y = 1.0; - local_24.y = npc->_speedMultiplier * 0.1 + (npc->_v1).y; - minResult = &local_24; - if (1.0 <= local_24.y) { - minResult = &local_1c; - } - (npc->_v1).y = minResult->y; - return; -} - -// 00576450 -void NpcHelper::raglich_slam_spawn_grid(Entity_NPC *npc) -{ - uint8_t bVar1; - uint32_t uVar2; - int gridX; - GridEntity *pit; - uint8_t *animNameChar; - int gridY; - uint8_t *wantedAnimChar; - int gridIndex; - bool isLess; - Vector particlePos; - Vector rightDamagePos; - Vector local_68; - int gridYCopy; - uint32_t gridSeed; - Vector local_58; - int column; - void *room; - Vector slamOffset; - ColorMod particleColor; - uint32_t local_14; - void *local_10; - uint8_t *puStack_c; - float local_8; - uint8_t *animData; - uint64_t flags; - int *gridAtIndex; - uint32_t *oldGrid; - float posY; - float targetY; - - local_8 = -NAN; - puStack_c = &LAB_00af5157; - local_10 = ExceptionList; - uVar2 = __security_cookie ^ GHIDRA_UINT((&particleColor)[1]._colorize); - local_14 = uVar2; - if (npc->_state != 0) { - if (npc->_state != 3) { - return; - } - ExceptionList = &local_10; - npc->_friction = 0.5; - targetY = (npc->_targetPosition).y; - posY = (npc->_pos).y; - (npc->_velocity).x = (npc->_targetPosition).x - (npc->_pos).x; - (npc->_velocity).y = targetY - posY; - Entity::GetNullOffset(GHIDRA_CAST(npc),&slamOffset,&DAT_00b1d3b0); - if ((slamOffset.x != g_vectorZero.x) || (slamOffset.y != g_vectorZero.y)) { - if (npc->_i1 == 0) { - npc->_i1 = 1; - Entity_NPC::PlaySound(npc,0x34,1.0,2,0,1.0); - Game::ShakeScreen(g_game,0xe); - } - local_68.x = slamOffset.x + (npc->_pos).x; - local_68.y = slamOffset.y + (npc->_pos).y; - Game::BombDamage(g_game,&local_68,10.0,20.0,0,GHIDRA_CAST(npc),(BitSet128)ZEXT816(0),0x1000000,0) - ; - local_58.x = slamOffset.x + ((npc->_pos).x - 40.0); - local_58.y = slamOffset.y + (npc->_pos).y + 0.0; - Game::BombDamage(g_game,&local_58,10.0,20.0,0,GHIDRA_CAST(npc),(BitSet128)ZEXT816(0),0x1000000,0) - ; - rightDamagePos.x = slamOffset.x + (npc->_pos).x + 40.0; - rightDamagePos.y = slamOffset.y + (npc->_pos).y + 0.0; - Game::BombDamage(g_game,&rightDamagePos,10.0,20.0,0,GHIDRA_CAST(npc),(BitSet128)ZEXT816(0), - 0x1000000,0); - gridX = GHIDRA_INT((((slamOffset.x + (npc->_pos).x) - 40.0) / 40.0 + 0.5)); - gridY = GHIDRA_INT((((slamOffset.y + (npc->_pos).y) - 120.0) / 40.0 + 0.5)); - column = gridX + -1; - local_58.y = (float)(gridX + 1); - gridYCopy = gridY; - if (column <= GHIDRA_INT(local_58.y)) { - do { - gridX = column; - room = g_game->_room; - if ((((-1 < column) && (column < *GHIDRA_CAST((GHIDRA_CAST(room) + 0xc)))) && (-1 < gridY)) && - ((gridY < *GHIDRA_CAST((GHIDRA_CAST(room) + 0x10)) && - (gridIndex = *GHIDRA_CAST((GHIDRA_CAST(room) + 0xc)) * gridY + column, -1 < gridIndex)))) { - gridSeed = Random(); - if (gridIndex < 0x1c0) { - if (*GHIDRA_CAST((GHIDRA_CAST(room) + gridIndex * 4 + 0x76c)) < 0x385) { - pit = operator_new(0x158); - local_8 = 8.40779e-45; - local_68.y = (float)pit; - if (pit == GHIDRA_CAST(0x0)) { - pit = GHIDRA_CAST(0x0); - } - else { - GridEntity::GridEntity(pit); - *GHIDRA_CAST(pit) = IsaacRepentancePlus::GridEntity_Pit::vftable; - } - local_8 = -NAN; - if (pit != GHIDRA_CAST(0x0)) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((pit)) + 0x4)))) = 7; - pit->_gridIndex = gridIndex; - oldGrid = *GHIDRA_CAST((GHIDRA_CAST(room) + gridIndex * 4 + 0x24)); - if (oldGrid != GHIDRA_CAST(0x0)) { - (**(code **)*oldGrid)(1); - } - *GHIDRA_CAST((GHIDRA_CAST(room) + gridIndex * 4 + 0x24)) = pit; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((pit)) + 0x8)))) = 0; - pit->_varData = 0; - GridEntity::Init(pit,gridSeed); - } - gridX = column; - } - gridAtIndex = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + gridIndex * 4 + 0x24)); - if ((gridAtIndex != GHIDRA_CAST(0x0)) && (gridAtIndex[1] == 7)) { - (**(code **)(*gridAtIndex + 4))(); - } - } - else { - KAGE_LogMessage(0x10,GHIDRA_CAST("SpawnGridEntity: Grid index invalid\n")); - } - particleColor._tint[0] = 1.0; - particleColor._tint[1] = 1.0; - particleColor._tint[2] = 1.0; - particleColor._tint[3] = 1.0; - particleColor._offset[0] = 0.0; - particleColor._offset[1] = 0.0; - particleColor._colorize[0] = 0.0; - particleColor._colorize[1] = 0.0; - particleColor._colorize[2] = 0.0; - particleColor._colorize[3] = 0.0; - particlePos.x = slamOffset.x + (npc->_pos).x; - particlePos.y = slamOffset.y + (npc->_pos).y; - particleColor._offset[2] = 0.0; - Game::SpawnParticles(g_game,&particlePos,4,4,6.0,&particleColor,100000.0,0); - gridY = gridYCopy; - } - column = gridX + 1; - } while (column <= GHIDRA_INT(local_58.y)); - } - } - if (((npc->_sprite)._animState._animData == (void *)0x0) || - ((npc->_sprite)._animState._isPlaying == 0)) { - (**(code **)(*GHIDRA_CAST(npc) + 0x28))(uVar2); - ExceptionList = local_10; - return; - } - ExceptionList = local_10; - return; - } - animData = (npc->_sprite)._animState._animData; - if (animData != GHIDRA_CAST(0x0)) { - animNameChar = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - animNameChar = *GHIDRA_CAST(animData); - } - wantedAnimChar = &DAT_00b61c98; - do { - bVar1 = *animNameChar; - isLess = bVar1 < *wantedAnimChar; - if (bVar1 != *wantedAnimChar) { -LAB_00576910: - uVar2 = -GHIDRA_UINT(isLess) | 1; - goto LAB_00576915; - } - if (bVar1 == 0) break; - bVar1 = animNameChar[1]; - isLess = bVar1 < wantedAnimChar[1]; - if (bVar1 != wantedAnimChar[1]) goto LAB_00576910; - animNameChar = animNameChar + 2; - wantedAnimChar = wantedAnimChar + 2; - } while (bVar1 != 0); - uVar2 = 0; -LAB_00576915: - if ((uVar2 == 0) && ((animData[0x34] == 0 || ((npc->_sprite)._animState._isPlaying != 0)))) - goto LAB_00576948; - } - ExceptionList = &local_10; - bVar1 = ANM2::SetAnimation(&npc->_sprite,&DAT_00b61c98,1); - if (bVar1 != 0) { - AnimationState::Rewind(&(npc->_sprite)._animState); - (npc->_sprite)._animState._isPlaying = 1; - } -LAB_00576948: - flags = npc->_flags; - *GHIDRA_CAST((GHIDRA_INT(&npc->_flags) + 4)) = *GHIDRA_CAST((GHIDRA_INT(&npc->_flags) + 4)); - *GHIDRA_CAST(&npc->_flags) = GHIDRA_UINT(flags) & 0xfffffffb | 0xc4000011; - npc->_state = 3; - (npc->_targetPosition).x = (npc->_pos).x; - (npc->_targetPosition).y = (npc->_pos).y; - ExceptionList = local_10; - return; -} - -// 005785a0 -void NpcHelper::rainmaker_drop_timer_launch(Entity_Effect *timer) -{ - int iVar1; - int iVar2; - uint32_t rngResult; - float distance; - float fVar3; - float distance; - float fVar5; - float dirY; - float dirX; - - iVar1 = timer->_parent; - if (iVar1 == 0) { - return; - } - if (*GHIDRA_CAST((iVar1 + 0x28)) != 9) { - return; - } - distance = timer->_rotation; - iVar2 = timer->_target; - fVar3 = timer->_scale; - *GHIDRA_CAST((iVar1 + 0x43c)) = *GHIDRA_CAST((iVar1 + 0x43c)) & 0xfffffeff; - *GHIDRA_CAST((iVar1 + 0x438)) = *GHIDRA_CAST((iVar1 + 0x438)); - if (iVar2 == 0) { - rngResult = Random(); - fVar3 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - fVar3 = fVar3 + fVar3; - dirX = cos(fVar3); - dirY = sin(fVar3); - } - else { - dirX = *GHIDRA_CAST((iVar2 + 0x33c)); - dirY = *GHIDRA_CAST((iVar2 + 0x340)); - if (fVar3 <= 0.0) { - fVar5 = *GHIDRA_CAST((iVar1 + 0x33c)); - } - else { - fVar5 = *GHIDRA_CAST((iVar1 + 0x33c)); - distance = *GHIDRA_CAST((iVar1 + 0x340)) - dirY; - distance = sqrtf(distance * distance + (fVar5 - dirX) * (fVar5 - dirX)); - dirY = dirY + distance * *GHIDRA_CAST((iVar2 + 0x364)) * fVar3; - dirX = dirX + distance * *GHIDRA_CAST((iVar2 + 0x360)) * fVar3; - } - dirY = dirY - *GHIDRA_CAST((iVar1 + 0x340)); - dirX = dirX - fVar5; - fVar3 = sqrtf(dirX * dirX + dirY * dirY); - if (0.0 < fVar3) { - dirY = dirY * (1.0 / fVar3); - dirX = (1.0 / fVar3) * dirX; - } - } - if (0.0 < distance) { - rngResult = Random(); - fVar3 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10; - distance = ((fVar3 + fVar3) - 1.0) * distance * 0.017453292; - fVar3 = cos(distance); - distance = sin(distance); - fVar5 = distance * dirX; - dirX = fVar3 * dirX - distance * dirY; - dirY = fVar5 + fVar3 * dirY; - } - *GHIDRA_CAST((iVar1 + 0x360)) = dirX * 10.0; - *GHIDRA_CAST((iVar1 + 0x364)) = dirY * 10.0; - return; -} - // 00582f60 void NpcHelper::scourge_whip(Entity_NPC *npc) { @@ -4342,961 +1710,3 @@ LAB_0058ebbb: ExceptionList = local_1c; return; } - -// 00592050 -void NpcHelper::siren_familiar_orbit(Entity_NPC *siren, Entity_Familiar *familiar) -{ - void *pvVar1; - uint8_t isDetached; - int extraout_ECX; - int extraout_ECX_00; - int orbitSlot; - int extraout_EDX; - int extraout_EDX_00; - void *orbitCenter; - int detachedAheadCount; - float fVar2; - float fVar3; - float fVar4; - float fVar5; - float deltaY; - Entity_Familiar *chainFamiliar; - int chainType; - - pvVar1 = siren->_sirenPlayerEntity; - if (pvVar1 != (void *)0x0) { - orbitCenter = pvVar1; - if ((void *)siren->_child != (void *)0x0) { - orbitCenter = (void *)siren->_child; - } - orbitSlot = 0; - detachedAheadCount = 0; - chainFamiliar = GHIDRA_CAST(familiar->_parent); - if (chainFamiliar != GHIDRA_CAST(0x0)) { - chainType = chainFamiliar->_type; - while (chainType == 3) { - isDetached = Entity_Familiar::is_detached_from_follow(chainFamiliar); - if (isDetached != 0) { - detachedAheadCount = detachedAheadCount + 1; - } - chainFamiliar = *GHIDRA_CAST((extraout_ECX + 0x3bc)); - orbitSlot = extraout_EDX; - if (chainFamiliar == GHIDRA_CAST(0x0)) break; - chainType = chainFamiliar->_type; - } - } - chainFamiliar = GHIDRA_CAST(familiar->_child); - if (chainFamiliar != GHIDRA_CAST(0x0)) { - chainType = chainFamiliar->_type; - while (chainType == 3) { - isDetached = Entity_Familiar::is_detached_from_follow(chainFamiliar); - orbitSlot = extraout_EDX_00; - if (isDetached != 0) { - orbitSlot = extraout_EDX_00 + 1; - } - chainFamiliar = *GHIDRA_CAST((extraout_ECX_00 + 0x3c0)); - if (chainFamiliar == GHIDRA_CAST(0x0)) break; - chainType = chainFamiliar->_type; - } - } - fVar5 = (((float)orbitSlot * 360.0) / (float)(orbitSlot + 1 + detachedAheadCount) + - *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x334)) * 3.5) * 0.017453292; - fVar2 = cos(fVar5); - fVar3 = (fVar2 * 90.0 + *GHIDRA_CAST((GHIDRA_CAST(orbitCenter) + 0x33c))) - (familiar->_pos).x; - fVar2 = sin(fVar5); - deltaY = (fVar2 * 90.0 + *GHIDRA_CAST((GHIDRA_CAST(orbitCenter) + 0x340))) - (familiar->_pos).y; - fVar4 = sqrtf(deltaY * deltaY + fVar3 * fVar3); - fVar2 = g_vectorZero.y; - fVar5 = g_vectorZero.x; - if (20.0 < fVar4) { - fVar4 = ((fVar4 - 20.0) * 0.1) / fVar4; - fVar5 = g_vectorZero.x + fVar3 * fVar4; - fVar2 = g_vectorZero.y + deltaY * fVar4; - } - fVar3 = *GHIDRA_CAST((GHIDRA_CAST(orbitCenter) + 0x360)); - (familiar->_velocity).y = fVar2 + *GHIDRA_CAST((GHIDRA_CAST(orbitCenter) + 0x364)); - (familiar->_velocity).x = fVar3 + fVar5; - } - return; -} - -// 00597d00 -void NpcHelper::beast_soul_render(Entity_NPC *npc, Vector *offset) -{ - Vector *point; - int iVar1; - uint32_t dequeIndex; - uint32_t uVar2; - float fVar3; - float fVar4; - double dVar5; - float smoothedPointX; - float fStack_5c; - uint32_t uStack_58; - float fStack_54; - float firstPointX; - float fStack_4c; - float fStack_48; - float fStack_44; - float local_40; - float local_3c; - ColorMod pointColor; - uint32_t local_c; - uint8_t auStack_8 [4]; - float *screenPointsEnd; - void *trailPointsEnd; - - local_c = __security_cookie ^ GHIDRA_UINT((auStack_8 + 4)); - if (8 < (npc->_vectorDeque2)._size) { - iVar1 = *GHIDRA_CAST(ThreadLocalStoragePointer); - if ((*GHIDRA_CAST((iVar1 + 0xc)) < DAT_00c7f838) && (_Init_thread_header(), DAT_00c7f838 == -1)) { - _atexit(GHIDRA_CAST<_func_4879 *>(&LAB_00b15560)); - _Init_thread_footer(); - } - if ((*GHIDRA_CAST((iVar1 + 0xc)) < DAT_00c7f848) && (_Init_thread_header(), DAT_00c7f848 == -1)) { - _atexit(GHIDRA_CAST<_func_4879 *>(&LAB_00b15500)); - _Init_thread_footer(); - } - uVar2 = 0; - DAT_00c7f840 = DAT_00c7f83c; - g_beastTrailPointsEnd = g_beastTrailPoints; - if ((npc->_vectorDeque2)._size != 0) { - do { - screenPointsEnd = DAT_00c7f840; - fStack_54 = (float)(npc->_vectorDeque2)._offset; - local_40 = g_displayPixelRatio * g_screenPointScale; - dequeIndex = GHIDRA_INT(fStack_54) + uVar2 & 1; - iVar1 = *GHIDRA_CAST((GHIDRA_INT((npc->_vectorDeque2)._map) + - ((npc->_vectorDeque2)._mapSize - 1 & GHIDRA_INT(fStack_54) + uVar2 >> 1) * 4)); - fStack_48 = *GHIDRA_CAST((iVar1 + dequeIndex * 8)); - fStack_44 = *GHIDRA_CAST((iVar1 + 4 + dequeIndex * 8)); - local_3c = ((g_screenWidth - 338.0) * 0.5 + (fStack_48 - 60.0) * 0.65) * local_40 + 0.5; - dVar5 = floor((double)local_3c); - fStack_54 = (float)dVar5 / local_40; - local_3c = ((g_screenHeight - 182.0) * 0.5 + (fStack_44 - 140.0) * 0.65) * local_40 + 0.5; - dVar5 = floor((double)local_3c); - local_3c = (float)dVar5; - fStack_48 = fStack_54 + offset->x; - fStack_44 = local_3c / local_40 + offset->y; - if (screenPointsEnd == DAT_00c7f844) { - msvc::vector::_Emplace_reallocate(screenPointsEnd,&fStack_48); - } - else { - *screenPointsEnd = fStack_48; - DAT_00c7f840[1] = fStack_44; - DAT_00c7f840 = DAT_00c7f840 + 2; - } - uVar2 = uVar2 + 3; - } while (uVar2 < (npc->_vectorDeque2)._size); - } - trailPointsEnd = g_beastTrailPointsEnd; - firstPointX = *DAT_00c7f83c; - fStack_4c = DAT_00c7f83c[1]; - uVar2 = (npc->_vectorDeque2)._offset + 2; - local_40 = 0.0; - fStack_44 = 0.0; - fStack_48 = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_INT((npc->_vectorDeque2)._map) + - (uVar2 >> 1 & (npc->_vectorDeque2)._mapSize - 1) * 4)) + - (uVar2 & 1) * 8)); - if (g_beastTrailPointsEnd == DAT_00c7f854) { - FUN_00598290(g_beastTrailPointsEnd,&firstPointX); - } - else { - *GHIDRA_CAST(g_beastTrailPointsEnd) = firstPointX; - *GHIDRA_CAST((GHIDRA_CAST(trailPointsEnd) + 4)) = fStack_4c; - *GHIDRA_CAST((GHIDRA_CAST(trailPointsEnd) + 8)) = fStack_48; - *GHIDRA_CAST((GHIDRA_CAST(trailPointsEnd) + 0xc)) = 0; - g_beastTrailPointsEnd = (void *)(GHIDRA_INT(g_beastTrailPointsEnd) + 0x10); - } - fVar3 = 0.0; - uVar2 = 1; - if (1 < (GHIDRA_INT(DAT_00c7f840) - GHIDRA_INT(DAT_00c7f83c) >> 3) - 1U) { - local_3c = 4.2039e-45; - do { - trailPointsEnd = g_beastTrailPointsEnd; - dequeIndex = GHIDRA_INT(local_3c) + (npc->_vectorDeque2)._offset + 2; - fStack_54 = 0.0; - smoothedPointX = - DAT_00c7f83c[uVar2 * 2 + -2] * 0.3 + DAT_00c7f83c[uVar2 * 2] * 0.4 + - DAT_00c7f83c[uVar2 * 2 + 2] * 0.3; - fStack_5c = DAT_00c7f83c[uVar2 * 2 + -1] * 0.3 + DAT_00c7f83c[uVar2 * 2 + 1] * 0.4 + - DAT_00c7f83c[uVar2 * 2 + 3] * 0.3; - uStack_58 = *(uint32_t *) - (*GHIDRA_CAST((GHIDRA_INT((npc->_vectorDeque2)._map) + - ((npc->_vectorDeque2)._mapSize - 1 & dequeIndex >> 1) * 4)) + - (dequeIndex & 1) * 8); - if (g_beastTrailPointsEnd == DAT_00c7f854) { - FUN_00598290(g_beastTrailPointsEnd,&smoothedPointX); - } - else { - *GHIDRA_CAST(g_beastTrailPointsEnd) = smoothedPointX; - *GHIDRA_CAST((GHIDRA_CAST(trailPointsEnd) + 4)) = fStack_5c; - *GHIDRA_CAST((GHIDRA_CAST(trailPointsEnd) + 8)) = uStack_58; - *GHIDRA_CAST((GHIDRA_CAST(trailPointsEnd) + 0xc)) = 0; - g_beastTrailPointsEnd = (void *)(GHIDRA_INT(g_beastTrailPointsEnd) + 0x10); - } - trailPointsEnd = g_beastTrailPointsEnd; - iVar1 = GHIDRA_INT(g_beastTrailPointsEnd) - GHIDRA_INT(g_beastTrailPoints) >> 4; - fVar3 = *GHIDRA_CAST((GHIDRA_CAST(g_beastTrailPoints) + (iVar1 + -2) * 0x10 + 4)) - - *GHIDRA_CAST((GHIDRA_CAST(g_beastTrailPoints) + iVar1 * 0x10 + -0xc)); - fVar4 = *GHIDRA_CAST((GHIDRA_CAST(g_beastTrailPoints) + (iVar1 + -2) * 0x10)) - - *GHIDRA_CAST((GHIDRA_CAST(g_beastTrailPoints) + iVar1 * 0x10 + -0x10)); - fVar3 = sqrtf(fVar3 * fVar3 + fVar4 * fVar4); - fVar3 = fVar3 + local_40; - uVar2 = uVar2 + 1; - local_3c = (float)(GHIDRA_INT(local_3c) + 3); - *GHIDRA_CAST((GHIDRA_CAST(trailPointsEnd) + -4)) = fVar3; - local_40 = fVar3; - } while (uVar2 < (GHIDRA_INT(DAT_00c7f840) - GHIDRA_INT(DAT_00c7f83c) >> 3) - 1U); - } - local_3c = 1.0; - if ((128.0 < fVar3) && (local_3c = 128.0 / fVar3, local_3c <= 0.5)) { - local_3c = 0.5; - } - DAT_00c78ef0 = &npc->_sprite; - uVar2 = 0; - DAT_00c78ef4 = 0; - (*GHIDRA_CAST((GHIDRA_CAST(&(DAT_00c78ef8)) + 0x0))) = 0; - g_beamRendererPointsEnd = g_beamRendererPoints; - if (GHIDRA_INT(g_beastTrailPointsEnd) - GHIDRA_INT(g_beastTrailPoints) >> 4 != 0) { - iVar1 = 0; - do { - point = GHIDRA_CAST((iVar1 + GHIDRA_INT(g_beastTrailPoints))); - pointColor._offset[0] = 0.0; - pointColor._offset[1] = 0.0; - pointColor._offset[2] = 0.0; - pointColor._colorize[0] = 0.0; - pointColor._colorize[1] = 0.0; - pointColor._colorize[2] = 0.0; - pointColor._colorize[3] = 0.0; - pointColor._tint[3] = point[1].x; - pointColor._tint[0] = 1.0; - pointColor._tint[1] = 1.0; - pointColor._tint[2] = 1.0; - BeamRenderer::Add(point,&pointColor,local_3c,local_3c * point[1].y); - iVar1 = iVar1 + 0x10; - uVar2 = uVar2 + 1; - } while (uVar2 < GHIDRA_UINT((GHIDRA_INT(g_beastTrailPointsEnd) - GHIDRA_INT(g_beastTrailPoints) >> 4))); - } - BeamRenderer::End(); - } - return; -} - -// 005a7010 -void NpcHelper::visage_spawn_particles(Vector *position, Vector *direction) -{ - int iVar1; - uint32_t rngResult; - uint32_t rngValue; - Entity *particle; - int iVar2; - int particlesLeft; - float cosQuarterTurn; - float sinQuarterTurn; - float sideDirX; - float sideDirY; - float fVar5; - uint8_t *spinSign; - float fVar6; - Vector local_18; - Vector spawnPos; - float dirX; - float dirY; - float sideDirX; - float sideDirY; - - rngResult = Random(); - cosQuarterTurn = cos(1.5707964); - sinQuarterTurn = sin(1.5707964); - dirX = direction->x; - dirY = direction->y; - for (particlesLeft = (rngResult & 3) + 5; particlesLeft != 0; particlesLeft = particlesLeft + -1) - { - rngResult = Random(); - rngValue = Random(); - sideDirX = (float)((double)GHIDRA_INT(rngValue) + __uint_to_double_fixup[-(GHIDRA_INT(rngValue) >> 0x1f)]) * - 2.3283064e-10; - sideDirY = direction->x; - fVar5 = direction->y; - rngValue = Random(); - fVar6 = (float)((double)GHIDRA_INT(rngValue) + __uint_to_double_fixup[-(GHIDRA_INT(rngValue) >> 0x1f)]) * - 2.3283064e-10; - fVar6 = (fVar6 + fVar6) - 1.0; - local_18.y = sideDirX * fVar5 * 5.0 + fVar6 * (dirY * cosQuarterTurn + dirX * sinQuarterTurn); - local_18.x = sideDirX * sideDirY * 5.0 + fVar6 * (dirX * cosQuarterTurn - dirY * sinQuarterTurn); - rngValue = Random(); - sideDirY = (float)((double)GHIDRA_INT(rngValue) + __uint_to_double_fixup[-(GHIDRA_INT(rngValue) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - sideDirY = sideDirY + sideDirY; - rngValue = Random(); - fVar5 = (float)((double)GHIDRA_INT(rngValue) + __uint_to_double_fixup[-(GHIDRA_INT(rngValue) >> 0x1f)]) * - 2.3283064e-10; - sideDirX = cos(sideDirY); - spawnPos.x = sideDirX * fVar5 * 20.0 + position->x; - sideDirY = sin(sideDirY); - spawnPos.y = sideDirY * fVar5 * 20.0 + position->y; - particle = Game::SpawnEx(g_game,1000,0x3b,&spawnPos,&local_18,GHIDRA_CAST(0x0),0,rngResult,0); - sideDirY = (particle->_pos).x; - fVar5 = (particle->_pos).y; - sideDirX = position->x; - fVar6 = position->y; - sideDirX = direction->x; - sideDirY = direction->y; - rngResult = Random(); - if (((float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 10.0 + 2.0) * - (float)((sideDirY - sideDirX) * sideDirX + (fVar5 - fVar6) * sideDirY < 0.0) == 0.0) { - spinSign = GHIDRA_CAST(0x3f800000); - } - else { - spinSign = &DAT_bf800000; - } - *GHIDRA_CAST((particle[1]._sprite._animDefaultName._buf + 4)) = spinSign; - rngResult = Random(); - (particle->_posOffset).x = 0.0; - (particle->_posOffset).y = -16.0; - iVar1 = *GHIDRA_CAST(particle); - iVar2 = rngResult % 10 + 0x1e; - *GHIDRA_CAST((particle[1]._sprite._filename._buf + 4)) = iVar2; - *GHIDRA_CAST((particle[1]._sprite._filename._buf + 8)) = iVar2; - (**(code **)(iVar1 + 0xc))(); - } - return; -} - -// 005a7310 -void NpcHelper::visage_spawn_chain(Entity_NPC *npc) -{ - uint32_t uVar1; - int iVar2; - uint32_t subType; - uint32_t seed; - Entity_NPC *pEVar3; - uint32_t *puVar4; - uint32_t *linkIter; - uint32_t *linksEnd; - Entity_NPC *local_28; - int *local_24; - Vector *spawnPos; - uint32_t linkIndex; - uint32_t *linksCapacityEnd; - Entity_NPC *visage; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - - puStack_c = &LAB_00af597d; - local_10 = ExceptionList; - ExceptionList = &local_10; - linkIter = GHIDRA_CAST(0x0); - linksCapacityEnd = GHIDRA_CAST(0x0); - linksEnd = GHIDRA_CAST(0x0); - local_8 = 0; - spawnPos = &npc->_pos; - linkIndex = 0; - visage = npc; - do { - subType = linkIndex; - seed = Random(); - pEVar3 = (Entity_NPC *) - Game::Spawn(g_game,0x387,10,spawnPos,&g_vectorZero,GHIDRA_CAST(visage),subType,seed); - uVar1 = *GHIDRA_CAST((GHIDRA_INT(&pEVar3->_flags) + 4)); - *GHIDRA_CAST(&pEVar3->_flags) = GHIDRA_UINT(pEVar3->_flags) & 0xfffffffb; - *GHIDRA_CAST((GHIDRA_INT(&pEVar3->_flags) + 4)) = uVar1; - local_28 = pEVar3; - if (pEVar3->_parent != 0) { - local_24 = &pEVar3->_parent; - msvc::multiset::erase(&local_24); - } - pEVar3->_parent = npc; - if (npc != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(&pEVar3->_parent); - } - if (npc->_variant == 10) { - puVar4 = &npc->_child; - if (npc->_child != 0) { - local_24 = puVar4; - msvc::multiset::erase(&local_24); - } - *puVar4 = pEVar3; - msvc::multiset::insert(puVar4); - } - if (linksEnd == linksCapacityEnd) { - msvc::vector<4byte>::_Emplace_reallocate(linksEnd,&local_28); - linksCapacityEnd = GHIDRA_CAST(0x0); - } - else { - *linksEnd = pEVar3; - linksEnd = linksEnd + 1; - } - linkIndex = linkIndex + 1; - npc = pEVar3; - } while (GHIDRA_INT(linkIndex) < 0x28); - local_24 = GHIDRA_CAST(linksEnd[-1]); - puVar4 = &visage->_entityRef; - if (*puVar4 != 0) { - local_28 = GHIDRA_CAST(puVar4); - msvc::multiset::erase(&local_28); - } - *puVar4 = local_24; - if (local_24 != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(puVar4); - } - puVar4 = &pEVar3->_child; - iVar2 = visage->_child; - if (*puVar4 != 0) { - local_28 = GHIDRA_CAST(puVar4); - msvc::multiset::erase(&local_28); - } - *puVar4 = iVar2; - if (iVar2 != 0) { - msvc::multiset::insert(puVar4); - } - if (linksEnd != GHIDRA_CAST(0x0)) { - do { - (**(code **)(*GHIDRA_CAST(*linkIter) + 0xc))(); - linkIter = linkIter + 1; - } while (linkIter != linksEnd); - } - ExceptionList = local_10; - return; -} - -// 005a7510 -int NpcHelper::visage_plasma_cap() -{ - int iVar1; - - iVar1 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 4)); - if ((iVar1 != 0) && (iVar1 = *GHIDRA_CAST((iVar1 + 0x10)), iVar1 != 0)) { - switch(*GHIDRA_CAST((iVar1 + 0x48))) { - case 4: - case 6: - return 6; - case 8: - case 9: - case 10: - case 0xb: - case 0xc: - return 8; - } - } - return 4; -} - -// 005a7590 -float NpcHelper::visage_score_position(Entity_NPC *npc, Vector *position) -{ - int iVar1; - Entity *pEVar2; - float fVar3; - float fVar4; - float fVar5; - float fVar6; - float fVar7; - float targetDistSq; - float local_1c; - float local_18; - - pEVar2 = Entity_NPC::GetPlayerTarget(npc); - iVar1 = npc->_child; - if (iVar1 == 0) { - fVar3 = (pEVar2->_pos).y - position->y; - fVar5 = (pEVar2->_pos).targetDistSq - position->targetDistSq; - fVar3 = sqrtf(fVar3 * fVar3 + fVar5 * fVar5); - return 0.0 - ABS(fVar3 - 120.0); - } - if (GHIDRA_UINT(npc->_state) < 0x71) { - local_1c = *GHIDRA_CAST((iVar1 + 0x340)) - position->y; - local_18 = *GHIDRA_CAST((iVar1 + 0x33c)) - position->targetDistSq; - fVar5 = local_1c * local_1c + local_18 * local_18; - fVar3 = sqrtf(fVar5); - fVar5 = sqrtf(fVar5); - if (0.0 < fVar5) { - local_18 = local_18 * (1.0 / fVar5); - local_1c = local_1c * (1.0 / fVar5); - } - fVar5 = (pEVar2->_pos).y - position->y; - fVar7 = (pEVar2->_pos).targetDistSq - position->targetDistSq; - targetDistSq = fVar5 * fVar5 + fVar7 * fVar7; - fVar6 = sqrtf(targetDistSq); - if (0.0 < fVar6) { - fVar7 = fVar7 * (1.0 / fVar6); - fVar5 = fVar5 * (1.0 / fVar6); - } - fVar6 = (npc->_pos).targetDistSq - position->targetDistSq; - fVar4 = (npc->_pos).y - position->y; - targetDistSq = sqrtf(targetDistSq); - fVar6 = sqrtf(fVar4 * fVar4 + fVar6 * fVar6); - return fVar6 * 1.2 + - (((fVar5 * local_1c + fVar7 * local_18) * 300.0 + fVar3 * 0.5 + 0.0) - - ABS(targetDistSq - 120.0)); - } - local_18 = *GHIDRA_CAST((iVar1 + 0x340)) - position->y; - local_1c = *GHIDRA_CAST((iVar1 + 0x33c)) - position->targetDistSq; - fVar5 = local_18 * local_18 + local_1c * local_1c; - fVar3 = sqrtf(fVar5); - fVar5 = sqrtf(fVar5); - if (0.0 < fVar5) { - local_1c = local_1c * (1.0 / fVar5); - local_18 = local_18 * (1.0 / fVar5); - } - fVar7 = (pEVar2->_pos).targetDistSq - position->targetDistSq; - fVar6 = (pEVar2->_pos).y - position->y; - targetDistSq = fVar6 * fVar6 + fVar7 * fVar7; - fVar5 = sqrtf(targetDistSq); - if (0.0 < fVar5) { - fVar7 = fVar7 * (1.0 / fVar5); - fVar6 = fVar6 * (1.0 / fVar5); - } - fVar5 = sqrtf(targetDistSq); - return ((fVar6 * local_18 + fVar7 * local_1c) * 0.2 * 300.0 + fVar3 * 0.25 + 0.0) - - ABS(fVar5 - 120.0); -} - -// 005a7920 -void NpcHelper::visage_pick_target_position(Entity_NPC *npc) -{ - uint32_t rngResult; - int triesLeft; - float fVar1; - float fVar2; - float candidateX; - float bestScore; - Vector candidatePos; - Vector clampedPos; - Room *room; - - (npc->_targetPosition).x = (npc->_pos).x; - (npc->_targetPosition).y = (npc->_pos).y; - bestScore = visage_score_position(npc,&npc->_pos); - triesLeft = 0x14; - do { - rngResult = Random(); - fVar1 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - fVar1 = fVar1 + fVar1; - rngResult = Random(); - fVar2 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 100.0; - candidateX = cos(fVar1); - candidateX = candidateX * fVar2 + (npc->_pos).x; - candidatePos.x = candidateX; - fVar1 = sin(fVar1); - room = g_game->_room; - fVar1 = fVar1 * fVar2 + (npc->_pos).y; - candidatePos.y = fVar1; - if (*GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((room)) + 0x4)))) + 0x10)) + 0x48)) - 9U < 4) { - Room::GetClampedPositionImpl(room,&clampedPos,&candidatePos,10.0,10.0,10.0,10.0); - if ((clampedPos.x == candidateX) && (clampedPos.y == fVar1)) { -LAB_005a7ace: - fVar2 = visage_score_position(npc,&candidatePos); - if (bestScore < fVar2) { - (npc->_targetPosition).x = candidateX; - (npc->_targetPosition).y = fVar1; - bestScore = fVar2; - } - } - } - else if (((((room->_topLeftPos).x + 10.0 <= candidateX) && - (candidateX <= (room->_bottomRightPos).x - 10.0)) && - ((room->_topLeftPos).y + 10.0 <= fVar1)) && (fVar1 <= (room->_bottomRightPos).y - 10.0) - ) goto LAB_005a7ace; - triesLeft = triesLeft + -1; - if (triesLeft == 0) { - return; - } - } while( true ); -} - -// 005ab180 -void NpcHelper::visage_start_charge(Entity_NPC *npc) -{ - uint8_t bVar1; - Vector *pVVar2; - uint8_t *curAnimChar; - uint32_t animCompare; - Entity_Laser *laser; - uint8_t *newAnimChar; - bool isLess; - float fVar3; - int iVar4; - Entity_NPC *source; - Vector local_18; - Vector VStack_10; - uint8_t *animData; - uint32_t flagsHigh; - Manager *manager; - - if (npc->_state == 0x6d) { - flagsHigh = *GHIDRA_CAST((GHIDRA_INT(&npc->_flags) + 4)); - *GHIDRA_CAST(&npc->_flags) = GHIDRA_UINT(npc->_flags) & 0xffffffee; - iVar4 = *GHIDRA_CAST(npc); - *GHIDRA_CAST((GHIDRA_INT(&npc->_flags) + 4)) = flagsHigh; - npc->_health = npc->_maxHitPoints; - npc->_isInvicible = 0; - (**(code **)(iVar4 + 0x40))(*GHIDRA_CAST((GHIDRA_CAST(npc->_config) + 0x28))); - } - manager = g_manager; - local_18.x = 1.0; - if (npc->_championColorIdx == 0x12) { - local_18.x = 1.5; - } - else if (npc->_championColorIdx == 0x13) { - local_18.x = 0.5; - } - VStack_10.x = 1.61149e-43; - seed_fart_sound_override(GHIDRA_CAST(&VStack_10)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(VStack_10.x),1.0,2,0,local_18.x,0.0); - pVVar2 = Isaac::GetAxisAlignedUnitVectorFromDir(&VStack_10,npc->_i1); - (npc->_targetPosition).x = pVVar2->x; - (npc->_targetPosition).y = pVVar2->y; - sprintf(&DAT_00c7f858,GHIDRA_CAST("Charge2Loop%s")); - animData = (npc->_sprite)._animState._animData; - if (animData != GHIDRA_CAST(0x0)) { - curAnimChar = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - curAnimChar = *GHIDRA_CAST(animData); - } - newAnimChar = &DAT_00c7f858; - do { - bVar1 = *curAnimChar; - isLess = bVar1 < *newAnimChar; - if (bVar1 != *newAnimChar) { -LAB_005ab300: - animCompare = -GHIDRA_UINT(isLess) | 1; - goto LAB_005ab305; - } - if (bVar1 == 0) break; - bVar1 = curAnimChar[1]; - isLess = bVar1 < newAnimChar[1]; - if (bVar1 != newAnimChar[1]) goto LAB_005ab300; - curAnimChar = curAnimChar + 2; - newAnimChar = newAnimChar + 2; - } while (bVar1 != 0); - animCompare = 0; -LAB_005ab305: - if ((animCompare == 0) && ((animData[0x34] == 0 || ((npc->_sprite)._animState._isPlaying != 0))) - ) goto LAB_005ab33c; - } - bVar1 = ANM2::SetAnimation(&npc->_sprite,&DAT_00c7f858,1); - if (bVar1 != 0) { - AnimationState::Rewind(&(npc->_sprite)._animState); - (npc->_sprite)._animState._isPlaying = 1; - } -LAB_005ab33c: - npc->_state = 0x6e; - pVVar2 = &local_18; - VStack_10.x = (npc->_targetPosition).y * -1.0; - bVar1 = 0; - iVar4 = 0x14; - local_18.x = 0.0; - local_18.y = -40.0; - source = npc; - fVar3 = atan2f(VStack_10.x,(npc->_targetPosition).x * -1.0); - laser = Entity_Laser::ShootAngle - (1,&npc->_pos,fVar3 * 57.295776,iVar4,pVVar2,GHIDRA_CAST(source),bVar1); - fVar3 = 0.0; - if (0.0 <= VStack_10.x) { - fVar3 = 1000.0; - } - laser->_renderDepthOffset = fVar3; - (**(code **)(*GHIDRA_CAST(laser) + 0xc))(); - return; -} - -// 005acd30 -void NpcHelper::visage_chain_solve(Entity_NPC *npc, uint8_t isInterpolate) -{ - Vector *pVVar1; - Entity_NPC *pEVar2; - int iVar3; - Entity_NPC *pEVar4; - uint8_t isFlipX; - uint32_t uVar5; - Vector *normalized; - Entity_NPC *pEVar6; - Entity_NPC *pEVar7; - float fVar8; - float angleDeg; - Vector local_2c; - float headY; - float headX; - Vector normDir; - float dirX; - float anchorY; - float anchorX; - int *parentSlot; - int *state; - - pEVar2 = GHIDRA_CAST(npc->_child); - if (((pEVar2 == GHIDRA_CAST(0x0)) || (pEVar2->_type != 0x387)) || (pEVar2->_variant != 10)) { - parentSlot = &npc->_parent; - pEVar7 = GHIDRA_CAST(npc->_parent); - pEVar6 = npc; - while (pEVar4 = pEVar7, pEVar4 != GHIDRA_CAST(0x0)) { - pEVar6 = pEVar4; - pEVar7 = GHIDRA_CAST(pEVar4->_parent); - } - pEVar7 = npc; - if ((pEVar6->_type != 0x387) || (pEVar6->_variant != 0)) { - pEVar6 = GHIDRA_CAST(0x0); - } - while (pEVar4 = pEVar2, pEVar4 != GHIDRA_CAST(0x0)) { - pEVar7 = pEVar4; - pEVar2 = GHIDRA_CAST(pEVar4->_child); - } - if (((pEVar7 == GHIDRA_CAST(0x0)) || (pEVar7->_type != 0x387)) || (pEVar7->_variant != 1)) { - pEVar7 = GHIDRA_CAST(0x0); - } - if (pEVar6 != GHIDRA_CAST(0x0)) { - pVVar1 = &pEVar6->_pos; - headX = pVVar1->x; - state = &npc->_state; - headY = (pEVar6->_pos).y; - if (npc->_state == 3) { - if (pEVar7 == GHIDRA_CAST(0x0)) { - return; - } - normalized = &pEVar7->_pos; - anchorX = normalized->x; - anchorY = (pEVar7->_pos).y; - if (isInterpolate != 0) { - uVar5 = GHIDRA_UINT((pEVar6->_isInterpolating != 0)); - headX = (pEVar6->_velocity).x * 0.5 + - *GHIDRA_CAST((GHIDRA_CAST((&pEVar6->_splatColor + 7)) + (uVar5 * 2 + 9) * 4)); - headY = (pEVar6->_velocity).y * 0.5 + - *GHIDRA_CAST((GHIDRA_CAST((&pEVar6->_splatColor + 7)) + (uVar5 * 2 + 10) * 4)); - if (pEVar7->_isInterpolating != 0) { - anchorX = (pEVar7->_preInterpolatePos).x; - normalized = &pEVar7->_preInterpolatePos; - } - anchorX = (pEVar7->_velocity).x * 0.5 + anchorX; - anchorY = (pEVar7->_velocity).y * 0.5 + normalized->y; - } - local_2c.x = headX - anchorX; - local_2c.y = headY - anchorY; - normalized = (GHIDRA_CAST((&local_2c)))->Vector::Normalized(&normDir); - dirX = normalized->x; - normDir.y = normalized->y; - } - else { - anchorX = (npc->_pos).x; - anchorY = (npc->_pos).y; - if (isInterpolate != 0) { - if (pEVar6->_isInterpolating == 0) { - normalized = pVVar1; - } - else { - headX = (pEVar6->_preInterpolatePos).x; - normalized = &pEVar6->_preInterpolatePos; - } - headX = (pEVar6->_velocity).x * 0.5 + headX; - headY = (pEVar6->_velocity).y * 0.5 + normalized->y; - } - dirX = headX - anchorX; - normDir.y = headY - anchorY; - fVar8 = sqrtf(dirX * dirX + normDir.y * normDir.y); - if (0.0 < fVar8) { - normDir.y = normDir.y * (1.0 / fVar8); - dirX = dirX * (1.0 / fVar8); - } - anchorX = anchorX - dirX * 8.0; - anchorY = anchorY - normDir.y * 8.0; - } - iVar3 = *parentSlot; - while (iVar3 != 0) { - fVar8 = sqrtf((headY - anchorY) * (headY - anchorY) + (headX - anchorX) * (headX - anchorX)) - ; - if (8.0 < fVar8) { - if (16.0 <= fVar8) { - local_2c.y = dirX * 16.0 + anchorX; - fVar8 = normDir.y * 16.0 + anchorY; - } - else { - local_2c.y = pVVar1->x; - fVar8 = (pEVar6->_pos).y; - } - if (isInterpolate == 0) { - npc->_visible = 1; - npc->_entityCollisionClass = 4; - } - if ((*state == 3) || - (((iVar3 = npc->_child, iVar3 != 0 && (*GHIDRA_CAST((iVar3 + 0x28)) == 0x387)) && - (*GHIDRA_CAST((iVar3 + 0x2c)) == 10)))) { - (npc->_pos).x = (anchorX + local_2c.y) * 0.5; - (npc->_pos).y = (anchorY + fVar8) * 0.5; - (npc->_velocity).x = g_vectorZero.x; - (npc->_velocity).y = g_vectorZero.y; - } - (npc->_posOffset).y = -35.0; - angleDeg = atan2f(normDir.y,dirX); - angleDeg = angleDeg * 57.295776; - if ((90.0 < angleDeg) || (angleDeg < -90.0)) { - isFlipX = 1; - angleDeg = 180.0 - angleDeg; - } - else { - isFlipX = 0; - } - (npc->_sprite)._flipX = isFlipX; - (npc->_sprite)._rotation = angleDeg; - anchorX = local_2c.y; - anchorY = fVar8; - } - else if (isInterpolate == 0) { - (npc->_pos).x = pVVar1->x; - (npc->_pos).y = (pEVar6->_pos).y; - npc->_visible = 0; - npc->_entityCollisionClass = 0; - } - npc = GHIDRA_CAST(*parentSlot); - parentSlot = &npc->_parent; - iVar3 = npc->_parent; - } - } - } - return; -} - -// 005add40 -uint8_t NpcHelper::visage_handle_collision(Entity_NPC *npc, Entity *collider, int unused) -{ - Entity *targetRef; - float newHealth; - float healCap; - int iVar2; - float local_3c; - int *local_38; - uint32_t local_34; - uint32_t uStack_30; - uint32_t uStack_2c; - uint32_t uStack_28; - uint32_t local_24; - uint32_t uStack_20; - uint32_t uStack_1c; - uint32_t uStack_18; - uint32_t local_14; - uint32_t local_10; - uint32_t local_c; - uint32_t local_8; - uint32_t *targetRef; - - local_8 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 4U; - iVar2 = npc->_variant; - if (iVar2 == 0) { - if (((npc->_state != 0x76) || (collider->_type != 0x387)) || (collider->_variant != 0x14)) { - return 0xff; - } - Entity_NPC::PlaySound(npc,0xb9,1.0,2,0,(float)npc->_stateFrame * 0.15 + 1.0); - npc->_stateFrame = npc->_stateFrame + 1; - (**(code **)(*GHIDRA_CAST(collider) + 0x28))(); - local_34 = 0x3f800000; - uStack_30 = 0x3f800000; - uStack_2c = 0x3f800000; - uStack_28 = 0x3f800000; - local_14 = 0x3f800000; - local_10 = 0x3dcccccd; - local_c = 0; - local_24 = 0; - uStack_20 = 0; - uStack_1c = 0; - uStack_18 = 0; - (**(code **)(*GHIDRA_CAST(npc) + 0x3c))(&local_34,10,0xff,1,1); - healCap = npc->_maxHitPoints * 0.4; - newHealth = npc->_maxHitPoints * 0.025 + npc->_health; - if (healCap <= newHealth) { - newHealth = healCap; - } - npc->_health = newHealth; - return 0xff; - } - if (iVar2 == 1) { - if ((collider->_type == 9) && (collider->_variant == 2)) { - collider->_dead = 1; - return 0; - } - if ((collider == GHIDRA_CAST(npc->_parent)) && (npc->_state == 0x6c)) { - return 1; - } - if (collider->_type != 0x387) { - return 0xff; - } - if (collider->_variant != 0x14) { - return 0xff; - } - if (collider[2]._preInterpolatePos.x == 5.60519e-45) { - return 0xff; - } - if ((npc->_state == 0x6a) || (npc->_state == 0x6d)) { - (**(code **)(*GHIDRA_CAST(collider) + 0x28))(); - local_34 = 0x3f800000; - uStack_30 = 0x3f800000; - uStack_2c = 0x3f800000; - uStack_28 = 0x3f800000; - local_14 = 0x3f800000; - local_10 = 0x3e19999a; - local_c = 0; - local_24 = 0; - uStack_20 = 0; - uStack_1c = 0; - uStack_18 = 0; - (**(code **)(*GHIDRA_CAST(npc) + 0x3c))(&local_34,10,0xff,1,1); - visage_start_charge(npc); - return 0xff; - } - return 0xff; - } - if (iVar2 != 10) { - if (iVar2 == 0x14) { - return 0xff; - } - return 0; - } - targetRef = &npc->_target; - if (collider == GHIDRA_CAST(npc->_target)) { - return 1; - } - if (npc->_state != 5) { - return 0xff; - } - iVar2 = collider->_type; - if (iVar2 == 1) { - iVar2 = 0x4d; - } - else { - if (iVar2 == 4) { - iVar2 = *GHIDRA_CAST((collider + 1)); - *GHIDRA_CAST((collider + 1)) = iVar2 + 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(collider[1])) + 0x4)))) = iVar2 + 1; - goto LAB_005adfbb; - } - if (iVar2 != 0x387) { - return 0xff; - } - if (collider->_variant != 1) { - return 0xff; - } - iVar2 = 0x8a; - } - Entity_NPC::PlaySound(npc,iVar2,1.0,2,0,1.0); -LAB_005adfbb: - targetRef = GHIDRA_CAST(FUN_005acc70()); - if ((collider == targetRef) && (collider[2]._preInterpolatePos.x == 1.48538e-43)) { - local_3c = (collider->_pos).x - *GHIDRA_CAST((collider->_parent + 0x33c)); - local_38 = GHIDRA_CAST(((collider->_pos).y - *GHIDRA_CAST((collider->_parent + 0x340)))); - FUN_005aafd0(&local_3c); - collider[2]._preInterpolatePos.x = 1.49939e-43; - } - if (*targetRef != 0) { - local_38 = targetRef; - msvc::multiset::erase(&local_38); - } - *targetRef = collider; - msvc::multiset::insert(targetRef); - npc->_state = 7; - (npc->_velocity).x = g_vectorZero.x; - (npc->_velocity).y = g_vectorZero.y; - return 1; -} diff --git a/generated-src/room_grid_path.cpp b/generated-src/room_grid_path.cpp deleted file mode 100644 index 2ae765d..0000000 --- a/generated-src/room_grid_path.cpp +++ /dev/null @@ -1,53 +0,0 @@ -#include "classes.h" - -// 009e3450 -uint8_t RoomGridPath::can_step(int fromIndex, int toIndex) -{ - uint32_t dRow; - uint32_t cellKind; - uint32_t stepRow; - uint32_t stepCol; - uint32_t dCol; - float *stepEntry; - int iVar1; - uint8_t cellType; - - iVar1 = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0xc)); - dRow = toIndex / iVar1 - fromIndex / iVar1; - dCol = toIndex % iVar1 - fromIndex % iVar1; - if (((((dRow ^ GHIDRA_INT(dRow) >> 0x1f) - (GHIDRA_INT(dRow) >> 0x1f)) + - ((dCol ^ GHIDRA_INT(dCol) >> 0x1f) - (GHIDRA_INT(dCol) >> 0x1f)) == 1) && (GHIDRA_UINT(fromIndex) < 0x1c0)) && - (cellType = *GHIDRA_CAST((fromIndex + 4 + GHIDRA_INT(this))), cellType != 0xff)) { - iVar1 = 0; - cellKind = cellType & 0xf; - if (0 < *GHIDRA_CAST((&DAT_00c37610 + cellKind * 0x44))) { - stepEntry = GHIDRA_CAST((&DAT_00c37614 + cellKind * 0x44)); - do { - if (*stepEntry == -13.0) { - stepCol = 0xffffffff; - } - else { - stepCol = 0; - if (*stepEntry == 13.0) { - stepCol = 1; - } - } - if (stepEntry[1] == -13.0) { - stepRow = 0xffffffff; - } - else { - stepRow = 0; - if (stepEntry[1] == 13.0) { - stepRow = 1; - } - } - if ((stepCol == dCol) && (stepRow == dRow)) { - return 1; - } - iVar1 = iVar1 + 1; - stepEntry = stepEntry + 2; - } while (iVar1 < *GHIDRA_CAST((&DAT_00c37610 + cellKind * 0x44))); - } - } - return 0; -} diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index cf78851..e94b3d6 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -9132,8 +9132,6 @@ void Menu_CreateLobby::load_graphics(ANM2 *menuSprite) { generated_stub("Menu_Cr void Menu_CreateLobby::update_paper_layers() { generated_stub("Menu_CreateLobby::update_paper_layers 008cc5e0"); } void Menu_LobbyList::render_lobbies() { generated_stub("Menu_LobbyList::render_lobbies 008df9b0"); } void Menu_LobbyListFilters::constructor() { generated_stub("Menu_LobbyListFilters::constructor 008dc1a0"); } -void Menu_Mods::Update() { generated_stub("Menu_Mods::Update 008e3830"); } -void Menu_Mods::reset() { generated_stub("Menu_Mods::reset 008e4970"); } void Menu_Online::render_mode_select() { generated_stub("Menu_Online::render_mode_select 008cc1a0"); } void Menu_Online::Update() { generated_stub("Menu_Online::Update 008e4b10"); } void Menu_Online::Render() { generated_stub("Menu_Online::Render 008e4e30"); } @@ -9213,21 +9211,6 @@ void NetworkManager::receive_packet(uint64_t *sender, void *buffer, int size) { void * NetworkManager::get_peer(void *outPeer, uint64_t *userId) { generated_stub("NetworkManager::get_peer 00a790b0"); } int * NpcHelper::chub_nearest_segment(int *param_1, int param_2) { generated_stub("NpcHelper::chub_nearest_segment 00499a50"); } void NpcHelper::chimera_charge_begin(Entity_NPC *npc, Vector *target, float speed) { generated_stub("NpcHelper::chimera_charge_begin 0049f870"); } -void NpcHelper::hornfel_spawn_doors() { generated_stub("NpcHelper::hornfel_spawn_doors 004b70c0"); } -void NpcHelper::hornfel_remove_doors() { generated_stub("NpcHelper::hornfel_remove_doors 004b78f0"); } -void NpcHelper::hornfel_charge(Entity_NPC *npc) { generated_stub("NpcHelper::hornfel_charge 004b7e30"); } -Entity * NpcHelper::hornfel_pick_spawn() { generated_stub("NpcHelper::hornfel_pick_spawn 004b7ee0"); } -void NpcHelper::hornfel_minecart(Entity_NPC *npc) { generated_stub("NpcHelper::hornfel_minecart 004b8190"); } -void NpcHelper::hornfel_ride_minecart(Entity_NPC *linkedNpc) { generated_stub("NpcHelper::hornfel_ride_minecart 004b8a30"); } -void NpcHelper::hornfel_attack(Entity_NPC *npc) { generated_stub("NpcHelper::hornfel_attack 004b8ca0"); } -void NpcHelper::hornfel_launch_toward(Entity_NPC *npc, Entity *entity, Vector *targetPos) { generated_stub("NpcHelper::hornfel_launch_toward 004b90e0"); } -Entity * NpcHelper::hornfel_free_door() { generated_stub("NpcHelper::hornfel_free_door 004bb350"); } -Vector * NpcHelper::hornfel_get_rail_direction(Entity_NPC *npc, Vector *outDirection) { generated_stub("NpcHelper::hornfel_get_rail_direction 004bb550"); } -int NpcHelper::hornfel_next_rail_index(Entity_NPC *npc) { generated_stub("NpcHelper::hornfel_next_rail_index 004bb6b0"); } -void NpcHelper::hornfel_set_anim(Entity_NPC *npc, int stateFrame) { generated_stub("NpcHelper::hornfel_set_anim 004bb830"); } -uint8_t NpcHelper::hornfel_claim_target(Entity_NPC *npc, Entity *target) { generated_stub("NpcHelper::hornfel_claim_target 004bb920"); } -void NpcHelper::hornfel_room_controller(Entity_Effect *effect) { generated_stub("NpcHelper::hornfel_room_controller 004bc460"); } -void NpcHelper::migraine_timer_spawn(Entity *timer) { generated_stub("NpcHelper::migraine_timer_spawn 00528ec0"); } 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"); } @@ -9235,9 +9218,6 @@ void NpcHelper::mother_set_collision_class(Entity_NPC *npc, int collisionClass) Entity * NpcHelper::clutch_find_farthest_orbital(Entity_NPC *clutch, int unused) { generated_stub("NpcHelper::clutch_find_farthest_orbital 00572a70"); } void NpcHelper::clutch_spawn_fire(Entity_NPC *npc, Entity *target) { generated_stub("NpcHelper::clutch_spawn_fire 00572cc0"); } void NpcHelper::clutch_render(Entity_NPC *npc, Vector *offset) { generated_stub("NpcHelper::clutch_render 00575a10"); } -void NpcHelper::raglich_pick_target_pos(Entity_NPC *npc, float speed) { generated_stub("NpcHelper::raglich_pick_target_pos 00576090"); } -void NpcHelper::raglich_slam_spawn_grid(Entity_NPC *npc) { generated_stub("NpcHelper::raglich_slam_spawn_grid 00576450"); } -void NpcHelper::rainmaker_drop_timer_launch(Entity_Effect *timer) { generated_stub("NpcHelper::rainmaker_drop_timer_launch 005785a0"); } void NpcHelper::scourge_whip(Entity_NPC *npc) { generated_stub("NpcHelper::scourge_whip 00582f60"); } void NpcHelper::scourge_chain_shoot() { generated_stub("NpcHelper::scourge_chain_shoot 00587480"); } void NpcHelper::singe_explode_at(Entity_NPC *npc, Vector *position) { generated_stub("NpcHelper::singe_explode_at 0058ac10"); } @@ -9245,16 +9225,6 @@ void NpcHelper::siren_charm_familiar(Entity_NPC *npc, Entity_Familiar *familiar) void NpcHelper::siren_familiar_counts(int *outFreeCount, int *outCharmedCount, int *outTotalCount) { generated_stub("NpcHelper::siren_familiar_counts 0058e490"); } int NpcHelper::siren_charmed_count(Entity_NPC *npc) { generated_stub("NpcHelper::siren_charmed_count 0058e590"); } void NpcHelper::siren_pick(Entity_NPC *npc) { generated_stub("NpcHelper::siren_pick 0058e680"); } -void NpcHelper::siren_familiar_orbit(Entity_NPC *siren, Entity_Familiar *familiar) { generated_stub("NpcHelper::siren_familiar_orbit 00592050"); } -void NpcHelper::beast_soul_render(Entity_NPC *npc, Vector *offset) { generated_stub("NpcHelper::beast_soul_render 00597d00"); } -void NpcHelper::visage_spawn_particles(Vector *position, Vector *direction) { generated_stub("NpcHelper::visage_spawn_particles 005a7010"); } -void NpcHelper::visage_spawn_chain(Entity_NPC *npc) { generated_stub("NpcHelper::visage_spawn_chain 005a7310"); } -int NpcHelper::visage_plasma_cap() { generated_stub("NpcHelper::visage_plasma_cap 005a7510"); } -float NpcHelper::visage_score_position(Entity_NPC *npc, Vector *position) { generated_stub("NpcHelper::visage_score_position 005a7590"); } -void NpcHelper::visage_pick_target_position(Entity_NPC *npc) { generated_stub("NpcHelper::visage_pick_target_position 005a7920"); } -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"); } 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"); } void OnlineChat::render_all(Vector *pos, uint8_t isFocused) { generated_stub("OnlineChat::render_all 0091e650"); } @@ -9283,7 +9253,6 @@ void ReferenceCountBase::vfunc_5() { generated_stub("ReferenceCountBase::vfunc_5 ReferenceCountBase::ReferenceCountBase() { generated_stub("ReferenceCountBase::ReferenceCountBase 0040cc10"); } uint8_t RichTextSpan::try_merge(void *other) { generated_stub("RichTextSpan::try_merge 009ef9a0"); } void RichTextSpan::move_construct(void *dest, void *source) { generated_stub("RichTextSpan::move_construct 009f1ef0"); } -uint8_t RoomGridPath::can_step(int fromIndex, int toIndex) { generated_stub("RoomGridPath::can_step 009e3450"); } void * SaveDataManager::open_file_read(uint8_t *fileName) { generated_stub("SaveDataManager::open_file_read 00a24fd0"); } void * SaveDataManager::open_file_write(uint8_t *path, int mode) { generated_stub("SaveDataManager::open_file_write 00a25090"); } Shape::Shape(void *other) { generated_stub("Shape::Shape 0042f850"); } @@ -9722,7 +9691,6 @@ uint32_t FUN_0042cef0() { generated_stub("FUN_0042cef0 0042cef0"); } long double FUN_0042cf00() { generated_stub("FUN_0042cf00 0042cf00"); } void FUN_0042cf10(Entity_Player *param_1, uint32_t param_2) { generated_stub("FUN_0042cf10 0042cf10"); } int FUN_0042d040() { generated_stub("FUN_0042d040 0042d040"); } -void get_netplay_player_color(void *self, ColorMod *outColor, Entity_Player *player) { generated_stub("get_netplay_player_color 0042d060"); } uint32_t FUN_0042d1b0() { generated_stub("FUN_0042d1b0 0042d1b0"); } void FUN_0042d5f0(Entity_Player *param_1, uint32_t param_2) { generated_stub("FUN_0042d5f0 0042d5f0"); } uint32_t FUN_0042d660() { generated_stub("FUN_0042d660 0042d660"); } @@ -9797,7 +9765,6 @@ 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_00436fb0() { generated_stub("FUN_00436fb0 00436fb0"); } 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"); } void FUN_0043edf0(uint32_t param_1, uint32_t param_2, uint32_t *param_3) { generated_stub("FUN_0043edf0 0043edf0"); } void FUN_0043eea0(uint32_t param_1) { generated_stub("FUN_0043eea0 0043eea0"); } @@ -9866,7 +9833,6 @@ uint32_t FUN_0049d100() { generated_stub("FUN_0049d100 0049d100"); } void NpcAI::ENTITY_CHIMERA_body(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CHIMERA_body 0049d130"); } uint32_t NpcAI::ENTITY_CHIMERA(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CHIMERA 0049fa10"); } void FUN_004a11b0() { generated_stub("FUN_004a11b0 004a11b0"); } -void NpcAI::ENTITY_CLOG(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CLOG 004a12f0"); } int FUN_004a2920() { generated_stub("FUN_004a2920 004a2920"); } void FUN_004aaaa0(void *param_1, int param_2) { generated_stub("FUN_004aaaa0 004aaaa0"); } void FUN_004aaaf0(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3) { generated_stub("FUN_004aaaf0 004aaaf0"); } @@ -9884,11 +9850,6 @@ void FUN_004aadf0(uint32_t param_1, uint32_t param_2, uint32_t param_3) { genera void FUN_004aae30(char param_1) { generated_stub("FUN_004aae30 004aae30"); } void FUN_004aae50(char param_1) { generated_stub("FUN_004aae50 004aae50"); } int FUN_004aae70() { generated_stub("FUN_004aae70 004aae70"); } -void NpcAI::ENTITY_DOGMA_update_distortion(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOGMA_update_distortion 004aaef0"); } -void NpcAI::ENTITY_DOGMA(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOGMA 004aafa0"); } -void NpcAI::ENTITY_DOGMA_angel(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOGMA_angel 004ae4d0"); } -Vector * NpcAI::ENTITY_DOGMA_angel_baby(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOGMA_angel_baby 004b0200"); } -void NpcAI::ENTITY_DOGMA_tv(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOGMA_tv 004b0a30"); } void FUN_004b3950() { generated_stub("FUN_004b3950 004b3950"); } void FUN_004b6b20(int *param_1, int param_2, int param_3) { generated_stub("FUN_004b6b20 004b6b20"); } void FUN_004b6ce0(int param_1, int param_2, int param_3) { generated_stub("FUN_004b6ce0 004b6ce0"); } @@ -9901,8 +9862,6 @@ void FUN_004b6fc0(uint32_t *param_1) { generated_stub("FUN_004b6fc0 004b6fc0"); void FUN_004b7020(uint32_t *param_1) { generated_stub("FUN_004b7020 004b7020"); } void FUN_004b7070(uint32_t param_1) { generated_stub("FUN_004b7070 004b7070"); } uint32_t FUN_004b7090() { generated_stub("FUN_004b7090 004b7090"); } -Entity * FUN_004bb230() { generated_stub("FUN_004bb230 004bb230"); } -void NpcAI::ENTITY_HORNFEL_DOOR(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HORNFEL_DOOR 004bb9b0"); } uint32_t FUN_004bc660() { generated_stub("FUN_004bc660 004bc660"); } void FUN_004bfd20() { generated_stub("FUN_004bfd20 004bfd20"); } void FUN_004c5850(uint8_t *param_1) { generated_stub("FUN_004c5850 004c5850"); } @@ -9915,7 +9874,6 @@ void msvc::set::clear() { generated_stub("msvc::set::clear 004cf350"); } void FUN_004cf380(int *param_1) { generated_stub("FUN_004cf380 004cf380"); } void FUN_004d3050() { generated_stub("FUN_004d3050 004d3050"); } void FUN_004d3230(uint32_t *param_1) { generated_stub("FUN_004d3230 004d3230"); } -void NpcAI::ENTITY_MOMS_HEART_mausoleum_death(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOMS_HEART_mausoleum_death 004d64f0"); } void invoke_pending_callbacks(void *owner) { generated_stub("invoke_pending_callbacks 004d6ee0"); } void FUN_004d7100(void *param_1) { generated_stub("FUN_004d7100 004d7100"); } void FUN_004d7130() { generated_stub("FUN_004d7130 004d7130"); } @@ -9929,13 +9887,10 @@ void FUN_004d7450(void *param_1, int param_2) { generated_stub("FUN_004d7450 004 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_UNBORN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_UNBORN 004dca90"); } -void NpcAI::ENTITY_CHARGER_L2(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CHARGER_L2 004e38c0"); } void FUN_004e46b0() { generated_stub("FUN_004e46b0 004e46b0"); } 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_BALL_AND_CHAIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BALL_AND_CHAIN 004f4730"); } 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"); } @@ -9950,30 +9905,21 @@ long double FUN_00515290(Vector *param_1, uint32_t param_2, int param_3) { gener void npc_distribute_orbit_angles(Entity_NPC *npc) { generated_stub("npc_distribute_orbit_angles 00547040"); } 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_COHORT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_COHORT 005513a0"); } -void NpcAI::ENTITY_BLOOD_PUPPY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLOOD_PUPPY 00552d30"); } void FUN_00557b50(uint32_t param_1) { generated_stub("FUN_00557b50 00557b50"); } 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"); } uint32_t NpcAI::ENTITY_POLTY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_POLTY 0055d230"); } -void NpcAI::ENTITY_FISSURE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FISSURE 00564f30"); } 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 FUN_00568980(char param_1) { generated_stub("FUN_00568980 00568980"); } void FUN_0056ff00(uint32_t *param_1, uint32_t param_2, uint32_t param_3) { generated_stub("FUN_0056ff00 0056ff00"); } bool FUN_0056ff60(uint32_t param_1) { generated_stub("FUN_0056ff60 0056ff60"); } -void NpcAI::ENTITY_MOTHERS_SHADOW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOTHERS_SHADOW 0056ffa0"); } void FUN_00571170() { generated_stub("FUN_00571170 00571170"); } void FUN_00571230(void *param_1, int param_2) { generated_stub("FUN_00571230 00571230"); } void FUN_005729a0(int *param_1) { generated_stub("FUN_005729a0 005729a0"); } void FUN_00572c10(int param_1) { generated_stub("FUN_00572c10 00572c10"); } void NpcAI::ENTITY_CLUTCH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CLUTCH 00573030"); } uint32_t * FUN_00575fe0(int *param_1, uint32_t param_2, uint32_t param_3, uint32_t param_4, uint32_t param_5, uint32_t param_6, int *param_7, uint32_t param_8, uint32_t param_9) { generated_stub("FUN_00575fe0 00575fe0"); } -void NpcAI::ENTITY_RAGLICH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_RAGLICH 005769b0"); } -void FUN_005784e0() { generated_stub("FUN_005784e0 005784e0"); } -void NpcAI::ENTITY_RAINMAKER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_RAINMAKER 00578a70"); } void FUN_00579700() { generated_stub("FUN_00579700 00579700"); } uint32_t FUN_00579760() { generated_stub("FUN_00579760 00579760"); } void FUN_0057be30(uint32_t param_1) { generated_stub("FUN_0057be30 0057be30"); } @@ -10001,31 +9947,11 @@ void NpcAI::ENTITY_SIREN_main(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_S void NpcAI::siren_release_stolen_items(Entity_NPC *npc) { generated_stub("NpcAI::siren_release_stolen_items 005911b0"); } void NpcAI::ENTITY_SIREN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SIREN 00591460"); } void NpcAI::ENTITY_SIREN_HELPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SIREN_HELPER 00591cc0"); } -void NpcAI::ENTITY_BEAST_spawn_background(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BEAST_spawn_background 00592280"); } -void NpcAI::ENTITY_BEAST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BEAST 00592460"); } -void NpcAI::ENTITY_BEAST_stalactite(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BEAST_stalactite 00596120"); } -void NpcAI::ENTITY_BEAST_rock_projectile(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BEAST_rock_projectile 00596c60"); } -void NpcAI::ENTITY_BEAST_soul(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BEAST_soul 005971e0"); } -void FUN_00598260(Vector *param_1) { generated_stub("FUN_00598260 00598260"); } uint32_t * FUN_00598290(uint32_t *param_1, uint32_t *param_2) { generated_stub("FUN_00598290 00598290"); } void FUN_005a6fb0() { generated_stub("FUN_005a6fb0 005a6fb0"); } -uint8_t FUN_005a7570() { generated_stub("FUN_005a7570 005a7570"); } -void NpcAI::ENTITY_VISAGE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VISAGE 005a7b20"); } -void FUN_005aae10() { generated_stub("FUN_005aae10 005aae10"); } uint8_t * FUN_005aaf60(uint8_t *param_1) { generated_stub("FUN_005aaf60 005aaf60"); } -void FUN_005aafd0(float *param_1) { generated_stub("FUN_005aafd0 005aafd0"); } -void FUN_005ab0b0(int param_1) { generated_stub("FUN_005ab0b0 005ab0b0"); } -void FUN_005ab3e0() { generated_stub("FUN_005ab3e0 005ab3e0"); } -void NpcAI::ENTITY_VISAGE_mask(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VISAGE_mask 005ab4d0"); } -void FUN_005acb70(int param_1) { generated_stub("FUN_005acb70 005acb70"); } void FUN_005acbf0(int param_1) { generated_stub("FUN_005acbf0 005acbf0"); } -int FUN_005acc70() { generated_stub("FUN_005acc70 005acc70"); } -int FUN_005accb0() { generated_stub("FUN_005accb0 005accb0"); } -int FUN_005accf0() { generated_stub("FUN_005accf0 005accf0"); } int FUN_005acd10() { generated_stub("FUN_005acd10 005acd10"); } -void FUN_005ad1c0() { generated_stub("FUN_005ad1c0 005ad1c0"); } -void NpcAI::ENTITY_VISAGE_chain(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VISAGE_chain 005ad250"); } -void NpcAI::ENTITY_VISAGE_plasma(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VISAGE_plasma 005ad8a0"); } void FUN_005b1490(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_005b1490 005b1490"); } void FUN_005b1560() { generated_stub("FUN_005b1560 005b1560"); } void FUN_005b15a0(uint32_t param_1) { generated_stub("FUN_005b15a0 005b15a0"); } @@ -10193,26 +10119,13 @@ 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"); } uint32_t FUN_0060dae0() { generated_stub("FUN_0060dae0 0060dae0"); } -void FamiliarAI::variant_66(Entity_Familiar *familiar) { generated_stub("FamiliarAI::variant_66 0061c3f0"); } -void FamiliarAI::lil_haunt(Entity_Familiar *familiar, int unused) { generated_stub("FamiliarAI::lil_haunt 0061d030"); } void FUN_0062e0e0(int param_1) { generated_stub("FUN_0062e0e0 0062e0e0"); } -void FUN_00631a00(float *param_1, uint32_t param_2, float *param_3) { generated_stub("FUN_00631a00 00631a00"); } -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"); } -Entity_Laser * FamiliarHelper::sprinkler_fire_laser(Entity_Familiar *familiar, float angle, float distance) { generated_stub("FamiliarHelper::sprinkler_fire_laser 0063acf0"); } -Entity_Knife * FamiliarAI::sprinkler_spawn_knife(Entity_Familiar *familiar) { generated_stub("FamiliarAI::sprinkler_spawn_knife 0063b070"); } -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 FUN_006431b0() { generated_stub("FUN_006431b0 006431b0"); } void FUN_0064b6a0() { generated_stub("FUN_0064b6a0 0064b6a0"); } -int FUN_0064ccf0() { generated_stub("FUN_0064ccf0 0064ccf0"); } -int level_get_room_neighbors(uint32_t roomIndex, uint32_t *outNeighbors) { generated_stub("level_get_room_neighbors 0064cd30"); } -int star_of_bethlehem_get_target_room() { generated_stub("star_of_bethlehem_get_target_room 0064d370"); } void FUN_0064d570(uint32_t param_1) { generated_stub("FUN_0064d570 0064d570"); } -void FamiliarAI::star_of_bethlehem(Entity_Familiar *familiar) { generated_stub("FamiliarAI::star_of_bethlehem 0064d5f0"); } int apply_forgotten_lullaby(void *self, int fireDelay) { generated_stub("apply_forgotten_lullaby 00651810"); } int FUN_006518d0(uint32_t param_1) { generated_stub("FUN_006518d0 006518d0"); } void * set_iterator_post_increment(void *self, void *outIterator, int unused) { generated_stub("set_iterator_post_increment 006518f0"); } @@ -10444,7 +10357,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"); } -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"); } uint8_t is_local_player_owned(void *self) { generated_stub("is_local_player_owned 006d8e10"); } @@ -10686,8 +10598,6 @@ int FUN_007919c0() { generated_stub("FUN_007919c0 007919c0"); } Entity_Player * FUN_007a0fe0() { generated_stub("FUN_007a0fe0 007a0fe0"); } Entity_Player * FUN_007a1020() { generated_stub("FUN_007a1020 007a1020"); } uint32_t FUN_007ab0e0() { generated_stub("FUN_007ab0e0 007ab0e0"); } -void FUN_007ad610() { generated_stub("FUN_007ad610 007ad610"); } -uint32_t FUN_007ad720(uint32_t param_1, uint8_t *param_2) { generated_stub("FUN_007ad720 007ad720"); } void FUN_007b8c00(int param_1) { generated_stub("FUN_007b8c00 007b8c00"); } void FUN_007c2e80() { generated_stub("FUN_007c2e80 007c2e80"); } void FUN_007cb4f0() { generated_stub("FUN_007cb4f0 007cb4f0"); } @@ -10695,7 +10605,6 @@ void FUN_007cf940() { generated_stub("FUN_007cf940 007cf940"); } long double FUN_007cf9a0(float *param_1, KColor *param_2, uint32_t param_3) { generated_stub("FUN_007cf9a0 007cf9a0"); } uint8_t * FUN_007cfa90() { generated_stub("FUN_007cfa90 007cfa90"); } void FUN_007d3330(int param_1) { generated_stub("FUN_007d3330 007d3330"); } -void FUN_007d3e00() { generated_stub("FUN_007d3e00 007d3e00"); } void FUN_007d9360() { generated_stub("FUN_007d9360 007d9360"); } uint32_t FUN_007d9ca0() { generated_stub("FUN_007d9ca0 007d9ca0"); } uint32_t FUN_007da770() { generated_stub("FUN_007da770 007da770"); } @@ -10864,7 +10773,6 @@ void FUN_00839b40() { generated_stub("FUN_00839b40 00839b40"); } void render_beast_arena_background(void *self, int pass) { generated_stub("render_beast_arena_background 0083a3d0"); } void FUN_0083aae0(uint8_t param_1, int *param_2, uint32_t *param_3) { generated_stub("FUN_0083aae0 0083aae0"); } void FUN_0083b830() { generated_stub("FUN_0083b830 0083b830"); } -int FUN_0083bbc0(int param_1) { generated_stub("FUN_0083bbc0 0083bbc0"); } void FUN_0083bf50() { generated_stub("FUN_0083bf50 0083bf50"); } void FUN_0083bf90(uint32_t *param_1) { generated_stub("FUN_0083bf90 0083bf90"); } void Catch_All_0083c241() { generated_stub("Catch_All_0083c241 0083c241"); } @@ -10888,7 +10796,6 @@ void Catch_All_0084be32() { generated_stub("Catch_All_0084be32 0084be32"); } uint32_t * FUN_0084be60(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3) { generated_stub("FUN_0084be60 0084be60"); } void FUN_0084bef0(uint32_t *param_1, void *param_2) { generated_stub("FUN_0084bef0 0084bef0"); } void FUN_0084bf20() { generated_stub("FUN_0084bf20 0084bf20"); } -uint8_t segment_intersect(float *outX, float *outY, float p1x, float p1y, float p2x, float p2y, float q1x, float q1y, float q2x, float q2y) { generated_stub("segment_intersect 0084d8b0"); } void FUN_0084db90() { generated_stub("FUN_0084db90 0084db90"); } void FUN_00856280(void *param_1) { generated_stub("FUN_00856280 00856280"); } void FUN_00856330() { generated_stub("FUN_00856330 00856330"); } @@ -13083,7 +12990,6 @@ void ** vector_LaserSample_erase(void *self, void **outIter, void *where) { gene void FUN_009a1770(uint32_t *param_1) { generated_stub("FUN_009a1770 009a1770"); } void * vector_LaserSample_emplace_reallocate(void *self, void *where, void *value) { generated_stub("vector_LaserSample_emplace_reallocate 009a17b0"); } void FUN_009a1940(uint32_t *param_1, uint32_t *param_2, int param_3) { generated_stub("FUN_009a1940 009a1940"); } -void FUN_009a3560() { generated_stub("FUN_009a3560 009a3560"); } float * FUN_009a6320(float *param_1, int param_2, int param_3) { generated_stub("FUN_009a6320 009a6320"); } void FUN_009a8a40() { generated_stub("FUN_009a8a40 009a8a40"); } void _player_hud_set_heart_anim_state(int param_1) { generated_stub("_player_hud_set_heart_anim_state 009a90b0"); } @@ -13104,8 +13010,6 @@ void Catch_All_009b1d88() { generated_stub("Catch_All_009b1d88 009b1d88"); } int FUN_009b1dc0(int param_1, int param_2, int param_3) { generated_stub("FUN_009b1dc0 009b1dc0"); } int FUN_009b5800() { generated_stub("FUN_009b5800 009b5800"); } uint32_t FUN_009b9450(int param_1) { generated_stub("FUN_009b9450 009b9450"); } -void FUN_009b9f60(Entity *param_1) { generated_stub("FUN_009b9f60 009b9f60"); } -void FUN_009b9fc0(int param_1) { generated_stub("FUN_009b9fc0 009b9fc0"); } void FUN_009ba9a0() { generated_stub("FUN_009ba9a0 009ba9a0"); } void FUN_009baa10(char param_1) { generated_stub("FUN_009baa10 009baa10"); } int FUN_009bac00(int param_1) { generated_stub("FUN_009bac00 009bac00"); } @@ -13174,7 +13078,6 @@ void FUN_009e24f0(uint32_t *param_1, uint32_t param_2) { generated_stub("FUN_009 void FUN_009e2520(void *param_1) { generated_stub("FUN_009e2520 009e2520"); } void FUN_009e2580(int *param_1, uint32_t *param_2) { generated_stub("FUN_009e2580 009e2580"); } int * FUN_009e2760(int *param_1, uint32_t *param_2) { generated_stub("FUN_009e2760 009e2760"); } -uint8_t room_grid_flood_fill(void *self, uint32_t startIndex, uint32_t targetIndex) { generated_stub("room_grid_flood_fill 009e3560"); } int FUN_009e3d30() { generated_stub("FUN_009e3d30 009e3d30"); } void FUN_009e3d60() { generated_stub("FUN_009e3d60 009e3d60"); } int get_rich_presence_room_status() { generated_stub("get_rich_presence_room_status 009e5000"); } @@ -13251,7 +13154,6 @@ uint32_t * FUN_009f2410(uint32_t *param_1) { generated_stub("FUN_009f2410 009f24 void FUN_009f2480() { generated_stub("FUN_009f2480 009f2480"); } void * map_int_ImagePtr_subscript(void *self, int *key) { generated_stub("map_int_ImagePtr_subscript 009f2e20"); } void FUN_009f3c10() { generated_stub("FUN_009f3c10 009f3c10"); } -void FUN_009f3c40() { generated_stub("FUN_009f3c40 009f3c40"); } void FUN_009f4130() { generated_stub("FUN_009f4130 009f4130"); } void FUN_009f5810(uint8_t param_1) { generated_stub("FUN_009f5810 009f5810"); } uint32_t * FUN_009f93d0() { generated_stub("FUN_009f93d0 009f93d0"); } diff --git a/src/anm2.cpp b/src/anm2.cpp index bde5393..47bf243 100644 --- a/src/anm2.cpp +++ b/src/anm2.cpp @@ -46,8 +46,6 @@ constexpr std::string_view IDLE_ANIMATION = "Idle"; constexpr std::string_view CHAMPION_COLOR_UNIFORM = "ChampionColor"; constexpr std::string_view COLOR_OFFSET_SHADER = "ColorOffset"; constexpr std::string_view COLOR_OFFSET_CHAMPION_SHADER = "ColorOffsetChampion"; -constexpr std::string_view COLOR_OFFSET_DOGMA_SHADER = "ColorOffsetDogma"; -constexpr std::string_view COLOR_OFFSET_GOLD_SHADER = "ColorOffsetGold"; // Delirium's forms swap a boss's or monster's spritesheets for the ones under DELIRIUM_FORMS_FOLDER. constexpr int DELIRIUM_TYPE = 412; diff --git a/src/anm2.h b/src/anm2.h index caee496..ecacefd 100644 --- a/src/anm2.h +++ b/src/anm2.h @@ -136,6 +136,17 @@ inline Vector vector_scale(Vector v, float scale) return vector_make(v.x * scale, v.y * scale); } +// Vector::operator* and operator/ with another vector: each axis scaled by the other's. +inline Vector vector_mul(Vector a, Vector b) +{ + return vector_make(a.x * b.x, a.y * b.y); +} + +inline Vector vector_div(Vector a, Vector b) +{ + return vector_make(a.x / b.x, a.y / b.y); +} + inline float vector_dot(Vector a, Vector b) { return a.x * b.x + a.y * b.y; @@ -215,6 +226,12 @@ inline Vector vector_rotated(Vector v, float degrees) return vector_make(v.x * cosine - v.y * sine, v.x * sine + v.y * cosine); } +// v mirrored about a unit normal: v less twice its part along the normal. +inline Vector vector_reflected(Vector v, Vector normal) +{ + return vector_sub(v, vector_scale(vector_scale(normal, 2), vector_dot(v, normal))); +} + // The name prefix of a light pass layer. constexpr char LIGHT_LAYER_PREFIX = '*'; diff --git a/src/beast_arena.cpp b/src/beast_arena.cpp index 82e0c24..46fbfde 100644 --- a/src/beast_arena.cpp +++ b/src/beast_arena.cpp @@ -1,4 +1,5 @@ #include "beast_arena.h" +#include "fx_layers.h" #include "game.h" #include "log.h" #include "room.h" @@ -78,8 +79,47 @@ void BeastArena::update() } } -// 0083a1b0 Draws the background's light layer over the screen, following the camera. +// Part of 006fd3f0: the half step of an interpolation, the background sorting layer moving a twentieth as far, the +// players colliding with the grid again and the familiars left alone. +void BeastArena::interpolate() +{ + scrollRendered += scrollSpeed * HALF; + for (Entity* entity : entities_live(g_game->room->entityList.updateEL)) + { + if (entity->type == ENTITY_PLAYER) + { + entity->flags |= FLAG_INTERPOLATION_UPDATE; + entity->PlayerCollideWithGrid(GRID_COLLISION_APPLY); + entity->flags &= ~FLAG_INTERPOLATION_UPDATE; + continue; + } + if (entity->type == ENTITY_FAMILIAR) continue; + float shift = entity->sortingLayer == SORTING_BACKGROUND ? scrollSpeed * BACKGROUND_PARALLAX * HALF : scrollSpeed * HALF; + entity->pos.x += shift; + } +} + +// The light layer's texture (hell_overlay.png), drawn over the screen from the spot that puts its (16, 121) at the +// room floor's screen centre, offset by a 480 by 270 screen and the floor's 26 margin. +constexpr int BACKGROUND_LIGHT_LAYER = 16; +constexpr float LIGHT_SCREEN_WIDTH = 480; +constexpr float LIGHT_SCREEN_HEIGHT = 270; +constexpr float LIGHT_FLOOR_MARGIN = 26; +static const Vector LIGHT_ANCHOR = vector_make(16, 121); + +// 0083a1b0 Draws the background's light layer over the whole screen in plain alpha, following the room's floor on +// screen, its scroll and the screen shake. void BeastArena::render_light() { - reconstruction_missing("BeastArena::render_light 0083a1b0"); + KAGE::Graphics::manager.blend_set(KAGE::Graphics::BLEND_NORMAL); + Room& room = *g_game->room; + Vector floor = vector_sub(room.floorScreenBottomRight, room.floorScreenTopLeft); + Vector shift = vector_add(vector_add(room.renderSurfaceTopLeft, room.renderScrollOffset), g_game->screenShakeOffset); + Vector at = vector_make((floor.x + LIGHT_FLOOR_MARGIN * 2 - LIGHT_SCREEN_WIDTH) * HALF + shift.x + LIGHT_FLOOR_MARGIN, + (floor.y + LIGHT_FLOOR_MARGIN * 2 - LIGHT_SCREEN_HEIGHT) * HALF + shift.y + LIGHT_FLOOR_MARGIN); + std::shared_ptr texture = background.GetLayer(BACKGROUND_LIGHT_LAYER)->spriteSheet; + if (!texture) return; + Vector screen = vector_make(g_screenWidth, g_screenHeight); + texture->Render(KAGE::Graphics::source_quad_rect(vector_sub(LIGHT_ANCHOR, at), screen), + KAGE::Graphics::color_quad_rect({}, screen, WHITE), WHITE); } diff --git a/src/beast_arena.h b/src/beast_arena.h index fb88a15..fb69c78 100644 --- a/src/beast_arena.h +++ b/src/beast_arena.h @@ -15,5 +15,6 @@ struct BeastArena void init(); void update(); + void interpolate(); void render_light(); }; diff --git a/src/bomb_explosion.cpp b/src/bomb_explosion.cpp index e920a01..42bbf02 100644 --- a/src/bomb_explosion.cpp +++ b/src/bomb_explosion.cpp @@ -66,7 +66,6 @@ constexpr float PUSH_PLAYER_MAX = 10; constexpr float PLAYER_DAMAGE_STRONG = 85; constexpr float DEATHMATCH_DAMAGE_SCALE = 0.2f; constexpr float IMMOVABLE_MASS = 1000; -constexpr int HIT_COUNTDOWN = 30; constexpr int LOCK_BLAST_DAMAGE = 4; constexpr float LOCK_BLAST_FRAME = 20; constexpr float TEAR_EFFECT_DAMAGE = 3.5f; @@ -77,6 +76,14 @@ constexpr float RAY_STEP = 20; // The entities and effects an explosion treats apart. constexpr int CARPET_BLOWN = 1000; +constexpr int SHOVEL_DIG_SHAKE = 8; + +// A poison splash's green splat (sized up to twice its scale at random) and the flat cloud drawn under it. +constexpr ColorMod POISON_SPLAT_COLOR = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {0, 0.33333334f, 0}}; +constexpr ColorMod POISON_CLOUD_COLOR = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {0.039215688f, 0.3921569f, 0}}; +constexpr float POISON_CLOUD_DEPTH = -5; +constexpr float POISON_CLOUD_FLATTEN = 0.4f; +constexpr int POISON_CLOUD_SUBTYPE = 4; constexpr std::array EFFECTS_BLOWN_AWAY = {21, 33, 63, 64, 158, 159}; constexpr int BOMB_EXPLOSION_EFFECT = 1; constexpr int SPECIAL_DAILY_FIREWORKS = 12; @@ -251,7 +258,17 @@ static void explosion_entity_hurt(Explosion& explosion, Entity& entity, const Te if (entity.variant == EFFECT_ISAACS_CARPET) { if (entity.subtype != 0) return; - reconstruction_missing("Game::BombDamage 006ff2a0: the hole under Isaac's carpet (stairs or a trapdoor)"); + Room& room = *g_game->room; + if (room.roomType == ROOM_ISAACS) + { + uint32_t seed = Random(); + room.SpawnGridEntity(room.GetGridIndex(Room::GetCenterPos()), GRID_STAIRS, 0, seed, 0); + } + else if (g_game->CanSpawnTrapDoor()) + { + uint32_t seed = Random(); + room.SpawnGridEntity(room.GetGridIndex(Room::GetCenterPos()), GRID_TRAPDOOR, 0, seed, 0); + } entity.subtype = CARPET_BLOWN; return; } @@ -804,14 +821,21 @@ void explosion_tear_flag_effects(const Explosion& explosion) if (flags[TEAR_GIGA_BOMB]) giga_bomb_crater(explosion); } -// 008207a0 Digs Mom's Shovel up when a bomb goes off in the first floor's start room while its quest is on. +// 008207a0 Digs Mom's Shovel up when a bomb goes off in the first floor's start room while its quest is on: the shovel +// rises from the room's middle with a shake, and its shadows know it is out. void shovel_quest_dig() { Game& game = *g_game; bool isQuestRoom = game.stage == 1 && (game.levelStateFlags & 1u << LEVEL_STATE_SHOVEL_QUEST_TRIGGERED) && game.currentRoomIdx == game.startingRoomIdx; - if (isQuestRoom && !game.itemPool.removedCollectibles[COLLECTIBLE_BROKEN_SHOVEL]) - reconstruction_missing("Room 008207a0: Mom's Shovel dug up by a bomb"); + if (!isQuestRoom || game.itemPool.removedCollectibles[COLLECTIBLE_BROKEN_SHOVEL]) return; + + Vector center = Room::GetCenterPos(); + game.itemPool.removedCollectibles[COLLECTIBLE_BROKEN_SHOVEL] = true; + game.Spawn({.position = center, .type = ENTITY_PICKUP, .variant = PICKUP_BROKEN_SHOVEL, .seed = game.room->GetSpawnSeed()}); + game_shake_screen(SHOVEL_DIG_SHAKE); + for (Entity* shadow : entity_query(ENTITY_EFFECT, EFFECT_BROKEN_SHOVEL_SHADOW)) + static_cast(shadow)->state = 1; } // FUN_007008b0 A giga bomb's aftershock: while its bomb is there, the blast hits again with the bomb's tear effects. @@ -933,3 +957,28 @@ Entity* bomb_crater_spawn(const Vector& position, Entity* spawner, float scale) state.intStorage1 = std::bit_cast(scale); return crater; } + +// A poison splash: a green splat up to twice its scale at random, and unless left out a flat green cloud under it, +// faded by its alpha. +void poison_splash_spawn(const PoisonSplash& splash) +{ + Entity* splat = + g_game->Spawn({.position = splash.position, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + float size = (random_unit() + 1) * splash.scale; + splat->sprite.scale = vector_make(size, size); + splat->SetColor(POISON_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + if (!splash.isCloud) return; + + Entity* cloud = g_game->Spawn({.position = splash.position, + .subType = POISON_CLOUD_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + ColorMod color = POISON_CLOUD_COLOR; + color._tint[3] = splash.alpha; + cloud->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + cloud->renderDepthOffset = POISON_CLOUD_DEPTH; + cloud->sprite.scale = vector_make(splash.scale, splash.scale * POISON_CLOUD_FLATTEN); + cloud->Update(); +} diff --git a/src/boss_ai.h b/src/boss_ai.h index 5e7dc36..d147982 100644 --- a/src/boss_ai.h +++ b/src/boss_ai.h @@ -159,6 +159,11 @@ std::vector npc_query_spawner_type(int spawnerType, int entityType, Spa // The Haunt's Lil Haunts, by variant. constexpr int HAUNT_LIL_VARIANT = 10; +// Mom's stomping foot, Loki's twin Lokii, and the first of Peep's (and the Bloat's) eye variants. +constexpr int MOM_STOMP = 10; +constexpr int LOKII = 1; +constexpr int PEEP_EYE_FIRST = 10; + // Isaac's forms, by variant: Isaac in the Cathedral, ??? in the Chest, and the ??? whose death calls Hush. enum IsaacVariant { @@ -230,8 +235,14 @@ void boss_mega_satan_update(Entity_NPC& npc); void boss_mega_satan_hand_update(Entity_NPC& npc); void boss_delirium_update(Entity_NPC& npc); +void laser_sweep_set(Entity* entity, float degrees, float speed); + // The fly group Hush keeps as a ring about him. constexpr int HUSH_FLY_RING_GROUP = 1; -// Gemini's baby, the variant its twin is tied to. +// Gemini's baby, the variant its twin is tied to, Steven, Blighted Ovum and its baby, and the cord between twin and baby. constexpr int GEMINI_BABY = 10; +constexpr int GEMINI_STEVEN = 1; +constexpr int GEMINI_BLIGHTED_OVUM = 2; +constexpr int GEMINI_BLIGHTED_OVUM_BABY = 12; +constexpr int GEMINI_CORD = 20; diff --git a/src/boss_beast.cpp b/src/boss_beast.cpp new file mode 100644 index 0000000..05b16e7 --- /dev/null +++ b/src/boss_beast.cpp @@ -0,0 +1,1710 @@ +#include "boss_final.h" +#include "beam_renderer.h" +#include "boss_ai.h" +#include "camera.h" +#include "capsule.h" +#include "deathmatch_manager.h" +#include "entity_combat.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_laser.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "fx_layers.h" +#include "manager.h" +#include "music_manager.h" +#include "npc_alt.h" +#include "player_manager.h" +#include "room_grid.h" +#include +#include + +// The Beast's states: idle, crossing the screen, diving into the lava (from the background, or to switch sides), +// surfacing, its suction and blast, its double shot, switching sides, calling souls, and the background phase of +// the ultra horsemen. +constexpr int BEAST_IDLE = NPC_STATE_IDLE; +constexpr int BEAST_MOVE = NPC_STATE_MOVE; +constexpr int BEAST_DIVE_TRANSITION = NPC_STATE_SUICIDE; +constexpr int BEAST_DIVE = NPC_STATE_JUMP; +constexpr int BEAST_SURFACE = NPC_STATE_STOMP; +constexpr int BEAST_SUCK = NPC_STATE_ATTACK; +constexpr int BEAST_BLAST = NPC_STATE_ATTACK2; +constexpr int BEAST_DOUBLE_SHOT = NPC_STATE_ATTACK3; +constexpr int BEAST_SWITCH = NPC_STATE_ATTACK4; +constexpr int BEAST_SURFACE_ALT = NPC_STATE_ATTACK5; +constexpr int BEAST_SOUL_CALL = NPC_STATE_SUMMON; +constexpr int BEAST_BACKGROUND = NPC_STATE_SPECIAL; +constexpr int BEAST_DYING = NPC_STATE_DEATH; + +// Its horsemen, ten variants apart. +constexpr int BEAST_HORSEMEN = 4; +constexpr int BEAST_HORSEMAN_STEP = 10; +constexpr int BEAST_HORSEMAN_ARRIVING = 99; +constexpr int BEAST_LEAVING = NPC_STATE_MOVE; + +// Its look and hurt: the ray layer drawn untinted, the stage of hurt it shows from its health (two thirds of its +// bar, then four more in the last third), its hurt's gibs from 120 above it. +constexpr int BEAST_RAY_LAYER = 9; +constexpr float BEAST_THIRDS = 2.999f; +constexpr float BEAST_LAST_THIRD = 0.3333f; +constexpr float BEAST_LAST_STAGES = 5.999f; +constexpr float BEAST_LAST_STAGES_SPAN = 3.999f; +constexpr int BEAST_STAGE_DIVE = 2; +static const Vector BEAST_GIB_OFFSET = vector_make(0, -120); +constexpr int BEAST_GIBS = 10; +constexpr float BEAST_GIB_SPREAD = 40; +constexpr int BEAST_HURT_SHAKE = 15; +constexpr float BEAST_HURT_BLAST_DECAY = 0.8f; +constexpr std::array BEAST_HURT_ANIMATIONS = {"Damage1", "Damage2", "Damage3"}; +constexpr std::array BEAST_MOVE_HURT_ANIMATIONS = {"MoveLoopDamage1", "MoveLoopDamage2", + "MoveLoopDamage3"}; +constexpr int BEAST_MUSIC_FIGHT_LAYER = 3; +constexpr int BOSS_OVERLAY_BEAST_DEAD = 4; + +// Its moves toward its target: 6% of the way a frame, at most 8 (12 doubled after the dive, 15 switching sides), and +// half on an interpolation. +constexpr float BEAST_FOLLOW = 0.06f; +constexpr float BEAST_FOLLOW_TOP = 8; +constexpr float BEAST_FOLLOW_TOP_FAST = 12; +constexpr float BEAST_FOLLOW_TOP_SWITCH = 15; +constexpr int BEAST_STALACTITE_SHAKE = 10; +constexpr float BEAST_STALACTITE_LIFT = -8; +constexpr float BEAST_STALACTITE_BLAST_DECAY = 0.9f; +constexpr float BEAST_DEATH_BLAST_DECAY = 0.95f; + +// Idle: it blinks every 30 to 90 frames, and acts after 60. +constexpr int BEAST_IDLE_FRAMES = 61; +constexpr int BEAST_BLINK_LEAST = 30; +constexpr uint32_t BEAST_BLINK_RANGE = 60; +constexpr int BEAST_MOVE_COOLDOWN = 30; +constexpr uint32_t BEAST_MOVE_COOLDOWN_RANGE = 20; + +// Crossing the screen: its blast force grows 0.2 a frame to 7 (7.5 after the dive), and every so far a stalactite +// (or a pair) comes in from the side it moves toward. +constexpr float BEAST_BLAST_STEP = 0.2f; +constexpr float BEAST_BLAST_TOP = 7; +constexpr float BEAST_BLAST_TOP_FAST = 7.5f; +constexpr float BEAST_BLAST_FADE = 0.05f; +constexpr float BEAST_OFFSCREEN = 100; +constexpr float BEAST_STALACTITE_DEPTH = 55; +constexpr float BEAST_STALACTITE_JITTER = 60; +constexpr float BEAST_STALACTITE_EDGE = 20; +constexpr float BEAST_STALACTITE_GAP = 200; +constexpr float BEAST_STALACTITE_GAP_HURT = 150; +constexpr int BEAST_GRUMBLE_EVERY = 60; +constexpr int BEAST_MOVE_FRAMES = 239; +constexpr int STALACTITE_TOP = 0; +constexpr int STALACTITE_BOTTOM = 1; +constexpr int STALACTITE_CRACKED = 2; +constexpr int STALACTITE_CRACKED_BASE = 3; +constexpr int STALACTITE_TIP = 4; + +// The dives: a lava spawner up from the floor at a random spot (the lowest path of 20 tries while surfacing), and the +// Beast 120 from the side it surfaces at. +constexpr float BEAST_SIDE = 120; +constexpr float BEAST_LAVA_MARGIN = 20; +constexpr int LAVA_SPAWNER_RISING = 2; +constexpr int BEAST_LAVA_FRAMES = 60; +constexpr int BEAST_SURFACE_LAVA_FRAMES = 30; +constexpr int BEAST_LAVA_PATH = 900; +constexpr int BEAST_LAVA_TRIES = 20; +constexpr float BEAST_DIVE_COUNTDOWN = 60; +constexpr float BEAST_DIVE_SHAKE = 0.125f; +constexpr float BEAST_LAVA_EVERY_FIRST = 30; +constexpr float BEAST_LAVA_EVERY_LEAST = 12; +constexpr float BEAST_LAVA_WAVES = 30; +constexpr float BEAST_SURFACE_SCREAM = -2; +constexpr float BEAST_SURFACING = -1; +constexpr int BEAST_SURFACE_FRAMES = 90; +constexpr int BEAST_SURFACE_REST = 45; + +// Surfacing spits eight lava balls up and away from the side it faces, 10 and faster, from 30 above the floor. +constexpr int BEAST_LAVA_BALLS = 8; +constexpr float BEAST_LAVA_BALL_SPREAD = 50; +constexpr float BEAST_LAVA_BALL_ANGLE = -100; +constexpr float BEAST_LAVA_BALL_SPEED = 10; +constexpr float BEAST_LAVA_BALL_LEAD = 3; +constexpr float BEAST_LAVA_BALL_FLOOR = 30; +constexpr float BEAST_LAVA_BALL_SCALE = 0.8f; +constexpr float BEAST_LAVA_BALL_SCALE_RANGE = 0.2f; +constexpr int BEAST_LAVA_BALL_SUBTYPE = 1; +constexpr int BEAST_SURFACE_SHAKE = 14; + +// The suction: its loop sound fades in, the attraction swirls toward its mouth 60 out, stalactites hurt within the +// room's sides, rings of fire shots at 580 with a gap, and everything loose pulled in, eaten when close. +constexpr float BEAST_SUCK_FADE = 0.05f; +constexpr float BEAST_MOUTH = 60; +constexpr float BEAST_SWIRL_FAR = 800; +static const Vector BEAST_SWIRL_OFFSET = vector_make(0, -24); +constexpr int BIG_ATTRACT_FAR = 0; +constexpr int BIG_ATTRACT_NEAR = 1; +constexpr int BIG_ATTRACT_RAY = 10; +constexpr int BIG_ATTRACT_RAY_THIN = 11; +constexpr int BEAST_SUCK_SHAKE = 4; +constexpr int BEAST_SWIRL_EVERY = 3; +constexpr int BEAST_STALACTITE_HURT_EVERY = 6; +constexpr float BEAST_STALACTITE_HURT = 14; +constexpr float BEAST_STALACTITE_HURT_NEAR = 500; +constexpr float BEAST_STALACTITE_HURT_FALLOFF = 1500; +constexpr float BEAST_STALACTITE_HURT_FAR = 0.8f; +constexpr int BEAST_STALACTITE_HIT_COUNTDOWN = 30; +constexpr int BEAST_RING_AFTER = 20; +constexpr int BEAST_RING_EVERY = 30; +constexpr uint32_t BEAST_RING_GAPS = 20; +constexpr int BEAST_RING_FIRST = -90; +constexpr int BEAST_RING_LAST = 60; +constexpr int BEAST_RING_GAP_HALF = 9; +constexpr float BEAST_RING_RADIUS = 580; +constexpr float BEAST_RING_FALL_ACCEL = -0.1f; +constexpr float BEAST_RING_ACCEL = 0.95f; +constexpr int BEAST_RING_SLOW_DELAY = 30; +constexpr int BEAST_RING_FAST_DELAY = 60; +constexpr float BEAST_PULL_REACH_SQUARED = 1.96e+06f; +constexpr float BEAST_PULL_PLAYER = 160; +constexpr float BEAST_PULL_HEAVY = 400; +constexpr float BEAST_PULL_SHOT = 300; +constexpr float BEAST_PULL_NEAR = 8; +constexpr float BEAST_PULL_NEAR_SCALE = 0.015625f; +constexpr float BEAST_PULL_RAMP = 30; +constexpr float BEAST_PULL_DAMP = 20; +constexpr float BEAST_PULL_DAMP_LEAST = 0.4f; +constexpr float BEAST_PULL_LIFT = -16; +constexpr float BEAST_PULL_ROCK_LIFT = -60; +constexpr float BEAST_PULL_ROCK_LIFT_TOP = -36; +constexpr float BEAST_EAT_REACH = 0.6f; +constexpr float BEAST_EAT_EFFECT_REACH = 0.4f; +constexpr float BEAST_EAT_AFTER = 15; +constexpr int BEAST_SUCK_FRAMES = 360; + +// The blast: a beam from its mouth for 70 frames, clearing the shots, for 90. +static const Vector BEAST_BEAM_FROM = vector_make(0, 20); +static const Vector BEAST_BEAM_OFFSET = vector_make(0, -20); +constexpr int BEAST_BEAM_FRAMES = 70; +constexpr int BEAST_BLAST_SHAKE = 8; +constexpr float BEAST_BLAST_FRAMES = 90; + +// The double shot: three fans of nine fire shots at 20, 18 degrees apart, then from its Sound the holy fan of ten at +// 15, 9 degrees apart, with blood. +constexpr int BEAST_FAN_EVERY = 22; +constexpr int BEAST_FAN_FRAMES = 70; +constexpr int BEAST_FAN_HALF = 4; +constexpr float BEAST_FAN_STEP = 18; +constexpr float BEAST_FAN_SPEED = 20; +constexpr float BEAST_FAN_ACCEL = 0.7f; +constexpr int BEAST_FAN_CHANGE = 12; +constexpr int BEAST_HOLY_START = 1000; +constexpr int BEAST_HOLY_END = 1024; +constexpr int BEAST_HOLY_EVERY = 4; +constexpr int BEAST_HOLY_HALF = 9; +constexpr float BEAST_HOLY_STEP = 9; +constexpr float BEAST_HOLY_SPEED = 15; +constexpr float BEAST_HOLY_SCALE = 2.5f; +constexpr ColorMod BEAST_HOLY_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 0.3f, 0}}; +constexpr float BEAST_HOLY_BLOOD_SPEED = 8; +constexpr float BEAST_HOLY_BLOOD_SPEED_RANGE = 4; + +// Switching sides: it plunges past the room's side, its hitbox lowered, then returns 120 in. +constexpr float BEAST_SWITCH_SINK = 0.8f; +constexpr float BEAST_SWITCH_NEAR = 80; + +// The soul call: souls rise from the floor every 8 frames and red rays burst from it every other frame. +constexpr int BEAST_SOUL_EVERY = 8; +constexpr float BEAST_SOUL_MARGIN = 50; +constexpr float BEAST_SOUL_FLOOR = 20; +static const Vector BEAST_RAY_OFFSET = vector_make(0, -14); +constexpr ColorMod BEAST_RAY_COLOR = {{1, 0.2f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float BEAST_RAY_FRAMES = 160.0f / 9.0f; +constexpr float BEAST_RAY_INNER = 10; +constexpr float BEAST_RAY_OUTER = 150; +constexpr int BEAST_THIN_RAYS = 3; +constexpr float BEAST_THIN_RAY_SPREAD = 60; +constexpr float BEAST_THIN_RAY_TURN = 120; +constexpr float BEAST_THIN_RAY_REACH = 0.15f; +constexpr float BEAST_THIN_RAY_LENGTH = 500; +constexpr float BEAST_THIN_RAY_WIDTH = 0.6f; +constexpr float BEAST_THIN_RAY_WIDTH_RANGE = 0.4f; + +// The background phase: the horsemen come one by one, 400 right of the fourth row's twelfth cell, each after the room +// is cleared twice, then the Beast surfaces there. +constexpr int BEAST_HORSEMAN_COLUMN = 11; +constexpr int BEAST_HORSEMAN_ROW = 4; +constexpr int BEAST_HORSEMAN_MIN_WIDTH = 12; +constexpr int BEAST_HORSEMAN_MIN_HEIGHT = 5; +constexpr float BEAST_HORSEMAN_RIGHT = 400; +constexpr int BEAST_BACKGROUND_WAIT = 30; +constexpr int BEAST_BACKGROUND_DONE = 1000; + +// The background beast and horsemen behind the arena, about the room's floor 58 up. +constexpr float BEAST_BACKGROUND_RISE = 58; +static const std::array BEAST_HORSEMAN_SPOTS = { + vector_make(-150, -140), vector_make(-50, -200), vector_make(50, -200), vector_make(150, -140)}; + +// A stalactite still standing within the room's sides (100 out of them) as the Beast faces, hurt less the farther it +// is from the Beast. +static void beast_stalactites_hurt(Entity_NPC& npc, float left, float right) +{ + for (Entity* stalactite : entity_query(ENTITY_BEAST, BEAST_STALACTITE)) + { + if (stalactite->isDead) continue; + float x = stalactite->pos.x; + float edge = npc.sprite.isFlipX ? right + BEAST_OFFSCREEN : left - BEAST_OFFSCREEN; + bool isOutside = npc.sprite.isFlipX ? edge < x : x < edge; + if (isOutside || edge == x) continue; + float roll = random_unit(); + float falloff = std::clamp((vector_distance(npc.pos, stalactite->pos) - BEAST_STALACTITE_HURT_NEAR) / + BEAST_STALACTITE_HURT_FALLOFF, + 0.0f, 1.0f); + stalactite->TakeDamage((1 - falloff * BEAST_STALACTITE_HURT_FAR) * (roll * BEAST_STALACTITE_HURT + BEAST_STALACTITE_HURT), + 0, EntityRef(), BEAST_STALACTITE_HIT_COUNTDOWN); + } +} + +// Its stalactites and souls die with it, and its shots and lasers fade. +static void beast_summons_kill(Entity_NPC& npc) +{ + for (Entity* entity : std::vector(g_game->room->entityList.updateEL)) + { + if (entity->IsType(ENTITY_BEAST, BEAST_STALACTITE, -1) || entity->IsType(ENTITY_BEAST, BEAST_SOUL, -1)) + entity->Kill(EntityRef(&npc)); + else if ((entity->type == ENTITY_PROJECTILE || entity->type == ENTITY_LASER) && entity->spawnerType == ENTITY_BEAST) + entity->isDead = true; + } +} + +// A lava spawner rising from the floor, raising the path there. +static void beast_lava_spawn(Entity_NPC& npc, Vector position, int frames) +{ + auto* lava = static_cast(g_game->Spawn({.position = position, + .spawner = &npc, + .subType = LAVA_SPAWNER_RISING, + .type = ENTITY_EFFECT, + .variant = EFFECT_LAVA_SPAWNER, + .seed = Random()})); + lava->timeout = frames; + lava->lifespan = frames; + lava->Update(); + room_path_raise_at(lava->pos, BEAST_LAVA_PATH); +} + +// Switches the music to a layer alone. +static void beast_music_layer_set(int layer) +{ + MusicManager& music = g_manager->musicManager; + music.channels[music.currentChannel].enabledLayers.reset(); + music.EnableLayer(layer, LAYER_FADE); +} + +// Its hurt stage from its health: 0 and 1 over the first two thirds, 2 to 5 over the last. +static int beast_stage_get(Entity_NPC& npc) +{ + int stage = (int)(BEAST_THIRDS - std::clamp(npc.health / npc.maxHitPoints, 0.0f, 1.0f) * BEAST_THIRDS); + if (stage != BEAST_STAGE_DIVE) return stage; + float last = std::clamp(npc.health / (npc.maxHitPoints * BEAST_LAST_THIRD), 0.0f, 1.0f); + return (int)(BEAST_LAST_STAGES - last * BEAST_LAST_STAGES_SPAN); +} + +// Its hurt gibs from above it. +static void beast_gibs_spawn(Entity_NPC& npc) +{ + gibs_spawn({.position = vector_add(npc.pos, BEAST_GIB_OFFSET), + .spawner = &npc, + .spread = BEAST_GIB_SPREAD, + .amount = BEAST_GIBS, + .gibFlags = GIB_FLAG_BLOOD | GIB_FLAG_HUGE}); +} + +// A new hurt stage: the first time past a third it dives into the background-free second phase, and in the last third +// it shows each new wound. +static void beast_stage_update(Entity_NPC& npc, int stage) +{ + if (npc.projectileDelay >= stage) return; + if (stage > 1 && npc.projectileDelay < 2) + { + npc_sound_play(SOUND_ROCKET_BLAST_DEATH, 1, 2, 1); + npc_sound_play(SOUND_BEAST_GROWL, 1, 2, 1); + beast_gibs_spawn(npc); + npc.sprite.Play("TransitionDive"); + npc.state = BEAST_DIVE_TRANSITION; + beast_summons_kill(npc); + } + if (stage > 2) + { + npc.sprite.Play(BEAST_HURT_ANIMATIONS[stage - 3]); + npc_sound_play(SOUND_ROCKET_BLAST_DEATH, 1, 2, 1); + beast_gibs_spawn(npc); + game_shake_screen(BEAST_HURT_SHAKE); + g_game->room->beastArena.scrollSpeed *= BEAST_HURT_BLAST_DECAY; + } + npc.projectileDelay = stage; +} + +// Its first frame: in the room of the horsemen (variant 666) it waits hidden in the background, otherwise it fights. +static void beast_init(Entity_NPC& npc) +{ + npc.targetPosition = npc.pos; + npc.aiCallFlags = AI_CALL_PRE_UPDATE | AI_CALL_INTERPOLATE | AI_CALL_COLLISION | AI_CALL_POST_UPDATE; + uint32_t roll = Random(); + npc.i2 = 0; + npc.projectileDelay = 0; + npc.flags = (npc.flags & ~FLAG_APPEAR) | FLAG_NO_KNOCKBACK | FLAG_NO_PHYSICS_KNOCKBACK; + npc.projectileCooldown = (int)(roll % BEAST_BLINK_RANGE) + BEAST_BLINK_LEAST; + if (g_game->room->descriptor->data->variant == BEAST_ROOM_VARIANT) + { + npc.sprite.Play("BGIdle", PLAY_FORCED); + npc.flags |= FLAG_DONT_COUNT_BOSS_HP; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isVisible = false; + npc.isInvincible = true; + npc.state = BEAST_BACKGROUND; + npc.stateFrame = BEAST_BACKGROUND_WAIT; + beast_background_spawn(npc); + } + else + { + npc.sprite.Play("Idle", PLAY_FORCED); + npc.state = BEAST_IDLE; + beast_music_layer_set(BEAST_MUSIC_FIGHT_LAYER); + } + npc.sprite.GetLayer(BEAST_RAY_LAYER)->bitflags |= ANIM_RENDER_UNTINTED; +} + +// Idle: blinking, then crossing the screen, then one of its attacks, then a dive (or switching sides before its first +// wound). +static void beast_idle(Entity_NPC& npc, int stage) +{ + if (npc.projectileCooldown > 0) npc.projectileCooldown = std::max(npc.projectileCooldown - npc_ticks_get(npc), 0); + if (npc.stateFrame < BEAST_IDLE_FRAMES) + { + npc.stateFrame += npc_ticks_get(npc); + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + if (npc.projectileCooldown < 1) + { + npc.sprite.Play("Blink", PLAY_FORCED); + npc.projectileCooldown = (int)(Random() % BEAST_BLINK_RANGE) + BEAST_BLINK_LEAST; + } + else npc.sprite.Play("Idle", PLAY_FORCED); + return; + } + + switch (npc.i1) + { + case 0: + { + npc.sprite.Play("MoveStart"); + npc.state = BEAST_MOVE; + npc.stateFrame = 0; + uint32_t roll = Random(); + npc.i1++; + npc.i2 = stage; + npc.projectileCooldown = (int)(roll % BEAST_MOVE_COOLDOWN_RANGE) + BEAST_MOVE_COOLDOWN; + for (Entity* stalactite : entity_query(ENTITY_BEAST, BEAST_STALACTITE)) stalactite->Remove(); + npc.v1.x = 0; + return; + } + case 1: + switch (Random() % 3) + { + case 0: + npc.sprite.Play("SuckStart"); + npc.state = BEAST_SUCK; + break; + case 1: + npc.sprite.Play("DoubleShot"); + npc.state = BEAST_DOUBLE_SHOT; + break; + default: + npc.sprite.Play("SoulCall"); + npc.state = BEAST_SOUL_CALL; + break; + } + npc.i1++; + break; + case 2: + if (npc.i2 == 0) + { + npc.sprite.Play("MoveStart"); + npc_sound_play(SOUND_BEAST_SWITCH_SIDES, 1, 2, 1); + npc.state = BEAST_SWITCH; + } + else + { + npc.sprite.Play("Dive"); + npc.state = BEAST_DIVE; + } + npc.i1 = 0; + break; + default: + return; + } + npc.stateFrame = 0; +} + +// A stalactite (or a pair, top and bottom) brought in from the side it crosses toward. +static void beast_stalactites_spawn(Entity_NPC& npc, float x, float top, float bottom) +{ + auto spawn = [&](Vector at, int subType, uint32_t seed) { + g_game->Spawn({.position = at, .spawner = &npc, .subType = subType, .type = ENTITY_BEAST, .variant = BEAST_STALACTITE, .seed = seed}) + ->Update(); + }; + if (Random() % 3 == 0 && npc.i2 != 2) + { + float jitter = random_unit() * BEAST_STALACTITE_JITTER - BEAST_STALACTITE_JITTER * HALF; + spawn(vector_make(x, top - BEAST_STALACTITE_DEPTH + jitter), STALACTITE_TOP, Random()); + spawn(vector_make(x, bottom + BEAST_STALACTITE_DEPTH + jitter), STALACTITE_BOTTOM, Random()); + return; + } + if ((Random() & 1) == 0) + { + uint32_t seed = Random(); + spawn(vector_make(x, bottom + BEAST_STALACTITE_EDGE - random_unit() * BEAST_STALACTITE_JITTER), STALACTITE_BOTTOM, seed); + return; + } + int subType = npc.i2 == 1 && (Random() & 1) == 0 ? STALACTITE_CRACKED : STALACTITE_TOP; + uint32_t seed = Random(); + spawn(vector_make(x, random_unit() * BEAST_STALACTITE_JITTER + (top - BEAST_STALACTITE_EDGE)), subType, seed); +} + +// Crossing the screen: the background races past as its blast force builds, stalactites come in, and before its dive +// it stops after 240 frames. +static void beast_move(Entity_NPC& npc, int stage, Room& room) +{ + if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) + npc.sprite.Play(stage >= 3 ? BEAST_MOVE_HURT_ANIMATIONS[stage - 3] : "MoveLoop"); + if (npc.projectileCooldown > 0 && npc.sprite.animState.IsLoopingAnimation()) + npc.projectileCooldown = std::max(npc.projectileCooldown - npc_ticks_get(npc), 0); + if (npc.sprite.IsEventTriggered("Shoot")) npc.entityCollisionClass = ENTCOLL_ALL; + if (npc.sprite.WasEventTriggered("Shoot") || npc.sprite.animState.IsLoopingAnimation()) + { + float top = npc.i2 == 2 ? BEAST_BLAST_TOP_FAST : BEAST_BLAST_TOP; + float& force = room.beastArena.scrollSpeed; + force = npc.sprite.isFlipX ? std::max(force - BEAST_BLAST_STEP, -top) : std::min(force + BEAST_BLAST_STEP, top); + npc.v1.x -= std::abs(force); + if (npc.v1.x <= 0) + { + float x = npc.sprite.isFlipX ? room.bottomRightPos.x + BEAST_OFFSCREEN + npc.v1.x : room.topLeftPos.x - BEAST_OFFSCREEN - npc.v1.x; + beast_stalactites_spawn(npc, x, room.topLeftPos.y, room.bottomRightPos.y); + float gap = npc.i2 == 2 || npc.i2 == 1 ? BEAST_STALACTITE_GAP_HURT : BEAST_STALACTITE_GAP; + npc.v1.x += random_unit() * BEAST_STALACTITE_JITTER + gap; + } + } + if (npc.stateFrame % BEAST_GRUMBLE_EVERY == 0) npc_sound_play(SOUND_BEAST_GRUMBLE, 1, 2, 1); + if (npc.i2 != 2 && npc.stateFrame > BEAST_MOVE_FRAMES) + { + npc.state = BEAST_IDLE; + npc.sprite.Play("MoveEnd"); + npc.stateFrame = 0; + return; + } + npc.stateFrame += npc_ticks_get(npc); +} + +// Its dives: into the background for its second phase (surfacing at once, moving), or into the lava to rise from its +// other side. +static void beast_dive(Entity_NPC& npc, Room& room) +{ + if (npc.sprite.IsEventTriggered("Shoot")) npc.entityCollisionClass = ENTCOLL_NONE; + if (!npc.sprite.IsFinished()) return; + + npc.v1 = vector_make(BEAST_DIVE_COUNTDOWN, 0); + float side = npc.sprite.isFlipX ? room.bottomRightPos.x - BEAST_SIDE : room.topLeftPos.x + BEAST_SIDE; + if (npc.state != BEAST_DIVE_TRANSITION) + { + npc.state = BEAST_SURFACE; + uint32_t seed = Random(); + float left = room.topLeftPos.x + BEAST_LAVA_MARGIN; + Vector at = vector_make((room.bottomRightPos.x - BEAST_LAVA_MARGIN - left) * random_unit() + left, room.bottomRightPos.y); + auto* lava = static_cast(g_game->Spawn({.position = at, + .spawner = &npc, + .subType = LAVA_SPAWNER_RISING, + .type = ENTITY_EFFECT, + .variant = EFFECT_LAVA_SPAWNER, + .seed = seed})); + lava->timeout = BEAST_LAVA_FRAMES; + lava->lifespan = BEAST_LAVA_FRAMES; + lava->Update(); + room_path_raise_at(lava->pos, BEAST_LAVA_PATH); + npc.targetPosition.x = side; + npc.sprite.isFlipX = !npc.sprite.isFlipX; + return; + } + npc.sprite.Play("TransitionSurface"); + npc.v1.y = BEAST_SURFACING; + npc.stateFrame = 0; + npc.targetPosition.x = side; + npc.pos.x = side; + npc.state = BEAST_MOVE; + npc.sprite.isFlipX = !npc.sprite.isFlipX; + npc.i1 = 0; + npc.i2 = 2; + npc.v1.x = BEAST_SIDE; +} + +// Surfacing spits lava balls up from the floor (the surfacing out of the background only roars). +static void beast_lava_balls(Entity_NPC& npc, Room& room) +{ + if (npc.v1.y == BEAST_SURFACE_SCREAM) + { + npc_sound_play(SOUND_BEAST_SURFACE_GROWL, 1, 2, 1); + return; + } + npc_sound_play(SOUND_BEAST_FIRE_BARF, 1, 2, 1); + npc.entityCollisionClass = ENTCOLL_ALL; + ProjectileParams params; + params.variant = PROJECTILE_LAVA; + params.isFallingKept = true; + for (int ball = 0; ball < BEAST_LAVA_BALLS; ball++) + { + float angle = (random_unit() * BEAST_LAVA_BALL_SPREAD + BEAST_LAVA_BALL_ANGLE) * DEGREES_TO_RADIANS; + Vector velocity = vector_scale(vector_make(std::cos(angle), std::sin(angle)), (float)ball + BEAST_LAVA_BALL_SPEED); + if (!npc.sprite.isFlipX) velocity.x = -velocity.x; + float floor = room.bottomRightPos.y; + params.scale = random_unit() * BEAST_LAVA_BALL_SCALE_RANGE + BEAST_LAVA_BALL_SCALE; + Vector from = vector_make(velocity.x * BEAST_LAVA_BALL_LEAD + npc.pos.x, + velocity.y * BEAST_LAVA_BALL_LEAD + (floor - BEAST_LAVA_BALL_FLOOR)); + npc.fire_projectiles(from, velocity, PROJECTILES_SINGLE, params)->subtype = BEAST_LAVA_BALL_SUBTYPE; + } +} + +// A lava spawner where the floor's path is lowest of 21 random spots. +static void beast_surface_lava_spawn(Entity_NPC& npc, Room& room) +{ + auto pathAt = [&](Vector spot) { + int index = room.GetGridIndex(spot); + return index >= 0 && index < ROOM_GRID_CELLS ? room.gridPaths[index] : 0; + }; + float left = room.topLeftPos.x + BEAST_LAVA_MARGIN; + float span = room.bottomRightPos.x - BEAST_LAVA_MARGIN - left; + float floor = room.bottomRightPos.y - BEAST_LAVA_MARGIN; + Vector best = vector_make(random_unit() * span + left, floor); + int lowest = pathAt(best); + for (int tries = 0; tries < BEAST_LAVA_TRIES && lowest != 0; tries++) + { + Vector spot = vector_make(random_unit() * span + left, floor); + int path = pathAt(spot); + if (path < lowest) + { + best = spot; + lowest = path; + } + } + beast_lava_spawn(npc, best, BEAST_SURFACE_LAVA_FRAMES); +} + +// Under the lava (v1 counts down to the next wave of lava, v1.y counts the waves), then surfacing and spitting. +static void beast_surface(Entity_NPC& npc, Room& room) +{ + if (npc.v1.y < 0) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + beast_lava_balls(npc, room); + game_shake_screen(BEAST_SURFACE_SHAKE); + } + if (npc.sprite.IsFinished()) npc.sprite.Play("Idle", PLAY_FORCED); + npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame > BEAST_SURFACE_FRAMES) + { + npc.stateFrame = npc.v1.y == BEAST_SURFACE_SCREAM ? BEAST_SURFACE_REST : 0; + npc.state = BEAST_IDLE; + } + return; + } + + if (npc.v1.y == 0) game_shake_screen((int)((BEAST_DIVE_COUNTDOWN - npc.v1.x) * BEAST_DIVE_SHAKE)); + for (int tick = 0; tick < npc_ticks_get(npc); tick++) + { + npc.v1.x -= 1; + if (npc.v1.x > 0) continue; + npc.v1.y += 1; + npc.v1.x = std::max(BEAST_LAVA_EVERY_FIRST - (npc.v1.y + npc.v1.y), BEAST_LAVA_EVERY_LEAST); + if (npc.v1.y == BEAST_LAVA_WAVES) + { + npc.v1.x = BEAST_DIVE_COUNTDOWN; + continue; + } + if (npc.v1.y == BEAST_LAVA_WAVES + 1) + { + npc.sprite.Play("Surface"); + npc.v1.y = BEAST_SURFACING; + npc.stateFrame = 0; + return; + } + beast_surface_lava_spawn(npc, room); + } +} + +// A ring of fire shots about its mouth 580 out, with a gap at a random angle; those near the gap speed and fade +// sooner. +static void beast_fire_ring(Entity_NPC& npc, Vector mouth) +{ + int gap = (int)(Random() % BEAST_RING_GAPS) * 2 - (int)BEAST_RING_GAPS; + for (int angle = BEAST_RING_FIRST; angle < BEAST_RING_LAST; angle += 2) + { + int fromGap = std::abs(angle - gap); + if (fromGap <= BEAST_RING_GAP_HALF) continue; + Vector at = vector_scale(vector_from_angle((float)angle), BEAST_RING_RADIUS); + if (!npc.sprite.isFlipX) at.x = -at.x; + auto* shot = static_cast(g_game->Spawn({.position = vector_add(mouth, at), + .spawner = &npc, + .type = ENTITY_PROJECTILE, + .variant = PROJECTILE_FIRE, + .seed = Random()})); + shot->fallingSpeed = 0; + shot->fallingAccel = BEAST_RING_FALL_ACCEL; + shot->acceleration = BEAST_RING_ACCEL; + int band = ((fromGap - BEAST_RING_GAP_HALF - 1) / 2) % 4; + shot->projectileFlags = PROJECTILE_ACCELERATE; + if (band != 0) + { + shot->changeTimeout = band == 2 ? BEAST_RING_FAST_DELAY : BEAST_RING_SLOW_DELAY; + shot->changeFlags = PROJECTILE_ACCELERATE | PROJECTILE_FADEOUT; + shot->projectileFlags |= PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT; + } + shot->Update(); + } +} + +// What the suction can pull: shots, tears, bombs and players, some effects, its rocks, and pickups that are not +// for sale nor closed chests. +static bool beast_is_suckable(Entity& entity) +{ + switch (entity.type) + { + case ENTITY_PROJECTILE: + case ENTITY_TEAR: + case ENTITY_BOMB: + case ENTITY_PLAYER: + return true; + case ENTITY_EFFECT: + return entity.variant == EFFECT_EMBER_PARTICLE && entity.sortingLayer == SORTING_NORMAL; + case ENTITY_BEAST: + return entity.variant == BEAST_ROCK; + case ENTITY_PICKUP: + return static_cast(entity).price == 0 && + (!Entity_Pickup::IsChest(entity.variant) || entity.subtype != 0); + default: + return false; + } +} + +// The suction's pull on one entity: shots and tears slowed and lifted, swallowed when at its mouth, all drawn in. +static void beast_pull(Entity_NPC& npc, Entity& entity, Vector mouth) +{ + if (&entity == &npc || (entity.pos.x == mouth.x && entity.pos.y == mouth.y) || entity.friction == 0) return; + Vector toMouth = vector_sub(mouth, entity.pos); + float distanceSquared = vector_length_squared(toMouth); + if (distanceSquared >= BEAST_PULL_REACH_SQUARED) return; + float distance = std::sqrt(distanceSquared); + if (distance > 0) toMouth = vector_scale(toMouth, 1 / distance); + + float strength = BEAST_PULL_PLAYER; + bool isEnemy = entity.type >= ENTITY_FIRST_ENEMY && entity.type <= ENTITY_LAST_ENEMY; + if ((entity.type == ENTITY_PLAYER && g_game->deathmatchManager.is_active()) || isEnemy || entity.type == ENTITY_BOMB) + strength = BEAST_PULL_HEAVY; + else if (entity.type == ENTITY_TEAR || entity.type == ENTITY_PROJECTILE) strength = BEAST_PULL_SHOT; + float nearness = distance >= BEAST_PULL_NEAR ? 1 / distance : distance * BEAST_PULL_NEAR_SCALE; + if (entity.type == ENTITY_PROJECTILE || entity.type == ENTITY_TEAR) + nearness *= std::min(entity.updateTime / BEAST_PULL_RAMP, 1.0f); + float pull = strength * nearness / entity.friction; + float damp = std::max(1 - nearness * BEAST_PULL_DAMP, BEAST_PULL_DAMP_LEAST); + float eatReach = npc.size * npc.size * BEAST_EAT_REACH * BEAST_EAT_REACH; + + if (entity.type == ENTITY_TEAR) + { + auto& tear = static_cast(entity); + tear.velocity = vector_scale(tear.velocity, damp); + if (tear.tearFlags[TEAR_ORBIT] && vector_length_squared(tear.velocity) < 1) + tear.SetTearFlags(tear.tearFlags & ~TearFlags().set(TEAR_ORBIT)); + float lift = std::max(nearness * BEAST_PULL_LIFT, BEAST_PULL_LIFT); + tear.velocity.y += lift * tear.speedMultiplier; + if (!tear.isDead && distanceSquared < eatReach && tear.updateTime > BEAST_EAT_AFTER && !tear.tearFlags[TEAR_LUDOVICO]) + tear.Remove(); + } + else if (entity.type == ENTITY_PROJECTILE || entity.type == ENTITY_BEAST) + { + entity.velocity = vector_scale(entity.velocity, damp); + if (!entity.isDead && distanceSquared < eatReach && entity.updateTime > BEAST_EAT_AFTER) entity.Remove(); + if (entity.type != ENTITY_PROJECTILE) + entity.velocity.y += std::max(nearness * BEAST_PULL_ROCK_LIFT, BEAST_PULL_ROCK_LIFT_TOP) * entity.speedMultiplier; + } + else if (entity.type == ENTITY_EFFECT) + { + entity.velocity = vector_scale(entity.velocity, damp); + if (distanceSquared < npc.size * npc.size * BEAST_EAT_EFFECT_REACH * BEAST_EAT_EFFECT_REACH) entity.Remove(); + } + entity.velocity = vector_add(entity.velocity, vector_scale(toMouth, pull * entity.speedMultiplier)); +} + +// One frame of the suction while its mouth is open: swirls, hurt stalactites, rings of fire and the pull. +static void beast_suck_tick(Entity_NPC& npc, Room& room) +{ + game_shake_screen(BEAST_SUCK_SHAKE); + float side = npc.sprite.isFlipX ? 1.0f : -1.0f; + Vector mouth = vector_make(npc.pos.x + side * BEAST_MOUTH, npc.pos.y); + if (npc.stateFrame % BEAST_SWIRL_EVERY == 0) + { + Entity* swirl = g_game->Spawn({.position = vector_make(npc.pos.x + side * BEAST_SWIRL_FAR, npc.pos.y), + .subType = BIG_ATTRACT_FAR, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_ATTRACT, + .seed = Random()}); + swirl->posOffset = BEAST_SWIRL_OFFSET; + swirl->targetPosition = vector_make(npc.pos.x + side * BEAST_MOUTH, npc.pos.y); + swirl->Update(); + } + if (npc.stateFrame % BEAST_STALACTITE_HURT_EVERY == 0) beast_stalactites_hurt(npc, room.topLeftPos.x, room.bottomRightPos.x); + if (npc.stateFrame > BEAST_RING_AFTER && npc.stateFrame % BEAST_RING_EVERY == 0) beast_fire_ring(npc, mouth); + if ((npc.stateFrame & 1) == 0) + { + Entity* swirl = g_game->Spawn({.position = vector_make(npc.pos.x + side * BEAST_MOUTH, npc.pos.y), + .subType = BIG_ATTRACT_NEAR, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_ATTRACT, + .seed = Random()}); + swirl->posOffset = BEAST_SWIRL_OFFSET; + swirl->Update(); + } + for (Entity* entity : std::vector(g_game->room->entityList.updateEL)) + if (beast_is_suckable(*entity)) beast_pull(npc, *entity, mouth); +} + +// The suction: its loop rises, and for 360 frames the open mouth pulls everything in, then the blast. +static void beast_suck(Entity_NPC& npc, Room& room) +{ + SFXManager& sfx = g_manager->sfxManager; + float volume = sfx.GetAmbientSoundVolume(SOUND_BEAST_SUCTION_LOOP); + if (volume < 1 && volume > 0) sfx.SetAmbientSound(SOUND_BEAST_SUCTION_LOOP, volume + BEAST_SUCK_FADE, 1); + if (npc.sprite.IsPlaying("SuckStart") && npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_BEAST_SUCTION_START, 1, 2, 1); + sfx.SetAmbientSound(SOUND_BEAST_SUCTION_LOOP, BEAST_SUCK_FADE, 1); + } + if (npc.sprite.IsFinished()) npc.sprite.Play("SuckLoop"); + for (int tick = 0; tick < npc_ticks_get(npc); tick++) + { + AnimationState& anim = npc.sprite.animState; + if (anim.animData && (anim.WasEventTriggered("Shoot") || anim.animData->isLooping)) beast_suck_tick(npc, room); + if (npc.stateFrame > BEAST_SUCK_FRAMES) + { + npc.stateFrame = 0; + npc.sprite.Play("SuckEnd"); + npc.state = BEAST_BLAST; + npc_sound_play(SOUND_BEAST_SUCTION_END, 1, 2, 1); + sfx.SetAmbientSound(SOUND_BEAST_SUCTION_LOOP, sfx.GetAmbientSoundVolume(SOUND_BEAST_SUCTION_LOOP) - BEAST_SUCK_FADE, 1); + return; + } + npc.stateFrame++; + } +} + +// The blast after the suction: its beam, the shots it swallowed gone. +static void beast_blast(Entity_NPC& npc) +{ + SFXManager& sfx = g_manager->sfxManager; + sfx.SetAmbientSound(SOUND_BEAST_SUCTION_LOOP, sfx.GetAmbientSoundVolume(SOUND_BEAST_SUCTION_LOOP) - BEAST_SUCK_FADE, 1); + if (npc.sprite.IsFinished()) + { + npc.sprite.Play("BlastLoop"); + npc_sound_play(SOUND_BEAST_LASER, 1, 2, 1); + Entity_Laser::ShootAngle({.position = vector_add(npc.pos, BEAST_BEAM_FROM), + .posOffset = BEAST_BEAM_OFFSET, + .source = &npc, + .angleDegrees = npc.sprite.isFlipX ? 0 : HALF_TURN_DEGREES, + .timeout = BEAST_BEAM_FRAMES, + .variant = LASER_BEAST}); + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity->type == ENTITY_PROJECTILE) entity->isDead = true; + } + if (npc.sprite.WasEventTriggered("Shoot") || npc.sprite.animState.IsLoopingAnimation()) game_shake_screen(BEAST_BLAST_SHAKE); + npc.stateFrame += npc_ticks_get(npc); + if ((float)npc.stateFrame > BEAST_BLAST_FRAMES) + { + npc.stateFrame = 0; + npc.state = BEAST_IDLE; + npc.sprite.Play("BlastEnd"); + } +} + +// A fan of fire shots that hurt enemies too, then accelerate. +static void beast_fire_fan(Entity_NPC& npc, Vector mouth) +{ + ProjectileParams params; + params.variant = PROJECTILE_FIRE; + params.fallingAccelModifier = BEAST_RING_FALL_ACCEL; + params.bulletFlags = PROJECTILE_HIT_ENEMIES | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT | PROJECTILE_ACCELERATE_EX; + params.changeFlags = PROJECTILE_HIT_ENEMIES; + params.changeTimeout = BEAST_FAN_CHANGE; + params.acceleration = BEAST_FAN_ACCEL; + params.isFallingKept = true; + float side = npc.sprite.isFlipX ? 1.0f : -1.0f; + for (int shot = -BEAST_FAN_HALF; shot <= BEAST_FAN_HALF; shot++) + npc.FireProjectiles(mouth, vector_scale(vector_scale(vector_from_angle((float)shot * BEAST_FAN_STEP), side), BEAST_FAN_SPEED), + PROJECTILES_SINGLE, params); +} + +// The holy fan: ten large glowing shots, and blood beside half of them. +static void beast_holy_fan(Entity_NPC& npc, Vector mouth) +{ + ProjectileParams params; + params.fallingAccelModifier = BEAST_RING_FALL_ACCEL; + params.color = BEAST_HOLY_COLOR; + params.bulletFlags = PROJECTILE_HIT_ENEMIES; + params.scale = BEAST_HOLY_SCALE; + params.isFallingKept = true; + float side = npc.sprite.isFlipX ? 1.0f : -1.0f; + for (int shot = -BEAST_HOLY_HALF; shot < BEAST_HOLY_HALF + 1; shot += 2) + { + Vector direction = vector_scale(vector_from_angle((float)shot * BEAST_HOLY_STEP), side); + npc.FireProjectiles(mouth, vector_scale(direction, BEAST_HOLY_SPEED), PROJECTILES_SINGLE, params); + if ((Random() & 1) != 0) continue; + Vector velocity = vector_scale(direction, random_unit() * BEAST_HOLY_BLOOD_SPEED_RANGE + BEAST_HOLY_BLOOD_SPEED); + blood_explosion_spawn((int)(~Random() & 1) + BLOOD_EXPLOSION_SPLASH, mouth, {}, BEAST_HOLY_COLOR, velocity); + } +} + +// The double shot: three fans of fire, then from its Sound the holy fan. +static void beast_double_shot(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Shoot")) npc_sound_play(SOUND_BEAST_SPIT, 1, 2, 1); + if (npc.sprite.WasEventTriggered("Shoot")) + { + Vector mouth = vector_make(npc.pos.x + (npc.sprite.isFlipX ? BEAST_MOUTH : -BEAST_MOUTH), npc.pos.y); + for (int tick = npc_ticks_get(npc); tick > 0; tick--) + { + int frame = npc.stateFrame; + if (!npc.sprite.animState.animData || !npc.sprite.animState.WasEventTriggered("Sound")) + { + if (frame % BEAST_FAN_EVERY == 0 && frame < BEAST_FAN_FRAMES) beast_fire_fan(npc, mouth); + } + else if (frame % BEAST_HOLY_EVERY == 0 && frame >= BEAST_HOLY_START && frame < BEAST_HOLY_END) + beast_holy_fan(npc, mouth); + npc.stateFrame++; + } + } + if (npc.sprite.IsEventTriggered("Sound")) npc.stateFrame = BEAST_HOLY_START; + if (npc.sprite.IsFinished()) + { + npc.stateFrame = 0; + npc.state = BEAST_IDLE; + } +} + +// Switching sides: it plunges past the side it faces, lowered, then turns and rises 120 in. +static void beast_switch(Entity_NPC& npc, Room& room) +{ + if (npc.stateFrame == 0) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.targetPosition.x = npc.sprite.isFlipX ? room.bottomRightPos.x + BEAST_OFFSCREEN : room.topLeftPos.x - BEAST_OFFSCREEN; + npc.sizeMulti.y *= BEAST_SWITCH_SINK; + } + if ((npc.sprite.WasEventTriggered("Shoot") || npc.sprite.animState.IsLoopingAnimation()) && + std::abs(npc.targetPosition.x - npc.pos.x) < BEAST_SWITCH_NEAR) + { + npc.stateFrame = 1; + npc.sprite.Play("MoveEndTurn"); + } + if (npc.sprite.IsFinished()) npc.sprite.Play("MoveLoopFast"); + return; + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.sizeMulti = npc.config->collisionRadiusMulti; + npc.targetPosition.x = npc.sprite.isFlipX ? room.bottomRightPos.x - BEAST_SIDE : room.topLeftPos.x + BEAST_SIDE; + } + if (!npc.sprite.IsFinished()) return; + npc.sprite.isFlipX = !npc.sprite.isFlipX; + npc.sprite.Play("Idle"); + npc.state = BEAST_IDLE; + npc.stateFrame = 0; +} + +// Red rays burst from the Beast: a wide one and three thin ones at random turns. +static void beast_rays_spawn(Entity_NPC& npc) +{ + int frames = (int)std::ceil(BEAST_RAY_FRAMES); + auto* ray = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = BIG_ATTRACT_RAY, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_ATTRACT, + .seed = Random()})); + ray->posOffset = BEAST_RAY_OFFSET; + ray->SetColor(BEAST_RAY_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + ray->minRadius = BEAST_RAY_INNER; + ray->maxRadius = BEAST_RAY_OUTER; + ray->timeout = frames * 2; + ray->lifespan = frames * 2; + ray->Update(); + + float turn = random_unit() * FULL_TURN_DEGREES; + for (int thin = 0; thin < BEAST_THIN_RAYS; thin++) + { + auto* line = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = BIG_ATTRACT_RAY_THIN, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_ATTRACT, + .seed = Random()})); + line->posOffset = BEAST_RAY_OFFSET; + line->sprite.rotation = random_unit() * BEAST_THIN_RAY_SPREAD - BEAST_THIN_RAY_SPREAD * HALF + + (float)thin * BEAST_THIN_RAY_TURN + turn; + line->SetColor(BEAST_RAY_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + line->timeout = frames; + line->lifespan = frames; + float roll = random_unit(); + line->minRadius = BEAST_RAY_INNER; + line->maxRadius = (roll * BEAST_THIN_RAY_REACH + BEAST_THIN_RAY_REACH) * BEAST_THIN_RAY_LENGTH; + line->sprite.GetLayer(0)->size.y = random_unit() * BEAST_THIN_RAY_WIDTH_RANGE + BEAST_THIN_RAY_WIDTH; + line->Update(); + } +} + +// The soul call: a roar, then souls rising from the floor and rays bursting until its Sound. +static void beast_soul_call(Entity_NPC& npc, Room& room) +{ + if (npc.sprite.IsEventTriggered("Roar")) npc_sound_play(SOUND_BEAST_GHOST_ROAR, 1, 2, 1); + if (npc.sprite.IsEventTriggered("Shoot")) npc_sound_play(SOUND_BEAST_GHOST_RISE, 1, 2, 1); + if (npc.sprite.WasEventTriggered("Shoot") && !npc.sprite.WasEventTriggered("Sound")) + { + game_shake_screen(BEAST_SUCK_SHAKE); + for (int tick = npc_ticks_get(npc); tick > 0; tick--) + { + if ((npc.stateFrame & 1) == 0) beast_stalactites_hurt(npc, room.topLeftPos.x, room.bottomRightPos.x); + if (npc.stateFrame % BEAST_SOUL_EVERY == 0) + { + uint32_t seed = Random(); + float left = room.topLeftPos.x + BEAST_SOUL_MARGIN; + Vector at = vector_make((room.bottomRightPos.x - BEAST_SOUL_MARGIN - left) * random_unit() + left, + room.bottomRightPos.y - BEAST_SOUL_FLOOR); + g_game->Spawn({.position = at, .spawner = &npc, .type = ENTITY_BEAST, .variant = BEAST_SOUL, .seed = seed}) + ->Update(); + } + if ((npc.stateFrame & 1) == 0) beast_rays_spawn(npc); + npc.stateFrame++; + } + } + if (!npc.sprite.IsFinished()) return; + npc.state = BEAST_IDLE; + npc.stateFrame = 0; +} + +// The background phase: each horseman in turn leaves the background (the Beast itself last) and comes as an ultra +// horseman, and once the four are beaten the Beast surfaces from the lava. +static void beast_background(Entity_NPC& npc, Room& room) +{ + if (npc.stateFrame != BEAST_BACKGROUND_DONE) + { + if (npc.stateFrame >= 1) + { + if (!npc.child && room.GetAliveEnemiesCount() == 1) npc.stateFrame -= npc_ticks_get(npc); + return; + } + if (npc.i1 > 0) + { + g_game->playerManager.trigger_room_clear(); + g_game->playerManager.trigger_room_clear(); + } + size_t slot = npc.i1 < BEAST_HORSEMEN ? (size_t)npc.i1 + 1 : 0; + EntityPtr& leaving = npc.entityDeque[slot]; + if (leaving) + { + npc.child = leaving; + leaving = nullptr; + static_cast(npc.child.get())->state = BEAST_LEAVING; + npc.child->sprite.Play(npc.i1 < BEAST_HORSEMEN ? "LeaveStart" : "Leave"); + } + npc.stateFrame = BEAST_BACKGROUND_DONE; + return; + } + if (npc.child) return; + + bool isWide = room.gridWidth >= BEAST_HORSEMAN_MIN_WIDTH && room.gridHeight >= BEAST_HORSEMAN_MIN_HEIGHT; + Vector at = vector_add(room.GetGridPosition(isWide ? room.gridWidth * BEAST_HORSEMAN_ROW + BEAST_HORSEMAN_COLUMN : -1), + vector_make(BEAST_HORSEMAN_RIGHT, 0)); + room.lastAliveBossCount = 0; + Entity* horseman = nullptr; + if (npc.i1 < BEAST_HORSEMEN) + { + uint32_t seed = Random(); + horseman = g_game->Spawn({.position = at, + .type = ENTITY_BEAST, + .variant = BEAST_ULTRA_FAMINE + npc.i1 * BEAST_HORSEMAN_STEP, + .seed = seed}); + } + if (!horseman) + { + npc.flags &= ~FLAG_DONT_COUNT_BOSS_HP; + npc.isVisible = true; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isInvincible = false; + npc.i1 = 0; + beast_music_layer_set(BEAST_MUSIC_FIGHT_LAYER); + npc.pos = vector_sub(at, vector_make(BEAST_HORSEMAN_RIGHT, 0)); + npc.state = BEAST_SURFACE; + npc.sprite.Play("Surface"); + npc_sound_play(SOUND_BEAST_LAVA_RISE, 1, 2, 1); + npc.v1.y = BEAST_SURFACE_SCREAM; + npc.stateFrame = 0; + return; + } + horseman->flags &= ~FLAG_APPEAR; + horseman->Update(); + static_cast(horseman)->state = BEAST_HORSEMAN_ARRIVING; + npc.child = horseman; + npc.i1++; + npc.stateFrame = BEAST_BACKGROUND_WAIT; +} + +// Its death throes: the camera on it, its last sounds and the boss overlay. +static void beast_dying_update(Entity_NPC& npc) +{ + g_game->room->camera->SetFocusPosition(npc.pos); + g_game->room->beastArena.scrollSpeed *= BEAST_DEATH_BLAST_DECAY; + AnimationState& anim = npc.sprite.animState; + if (!anim.animData) return; + if (anim.IsEventTriggered("Sound1")) npc_sound_play(SOUND_BEAST_DEATH, 1, 2, 1); + if (anim.IsEventTriggered("Sound2")) npc_sound_play(SOUND_BEAST_DEATH_2, 1, 2, 1); + if (anim.IsEventTriggered("Sound3")) npc_sound_play(SOUND_BEAST_ANGELIC_BLAST, 1, 2, 1); + if (anim.WasEventTriggered("Sound3")) game_shake_screen(BEAST_STALACTITE_SHAKE); + if (anim.IsEventTriggered("Shoot")) g_game->bossOverlay.play(BOSS_OVERLAY_BEAST_DEAD); +} + +// Its glide toward its target (after the update, and half on an interpolation). +static void beast_follow(Entity_NPC& npc) +{ + if (vector_is_zero(npc.targetPosition)) return; + float top = BEAST_FOLLOW_TOP; + Vector step = vector_scale(vector_sub(npc.targetPosition, npc.pos), BEAST_FOLLOW); + if (npc.i2 > 0) + { + top = BEAST_FOLLOW_TOP_FAST; + step = vector_scale(step, 2); + } + if (npc.state == BEAST_SWITCH) top = BEAST_FOLLOW_TOP_SWITCH; + float length = vector_length(step); + if (top < length && length > 0) step = vector_scale(step, top / length); + if (npc.aiCallPhase == AI_PHASE_INTERPOLATE) step = vector_scale(step, HALF); + npc.pos = vector_add(npc.pos, step); + npc.velocity = {}; +} + +// 00592460 The Beast (951.0): first it waits behind the arena while the four ultra horsemen come, then it crosses the +// scrolling hell blasting the arena past, brings stalactites, sucks everything in and blasts, spits fire, calls souls +// and dives through the lava, hurting through four more stages in its last third. +static void beast_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + if (npc.aiCallPhase == AI_PHASE_COLLISION) + { + Entity& collider = *npc.collisionEntity; + if (!collider.IsType(ENTITY_BEAST, BEAST_STALACTITE, -1)) return; + if (collider.subtype != STALACTITE_CRACKED_BASE) + { + auto& stalactite = static_cast(collider); + stalactite.state = NPC_STATE_SUICIDE; + stalactite.v2 = vector_make(-room.beastArena.scrollSpeed, BEAST_STALACTITE_LIFT); + game_shake_screen(BEAST_STALACTITE_SHAKE); + g_game->room->beastArena.scrollSpeed *= BEAST_STALACTITE_BLAST_DECAY; + } + npc.collisionResult = 0; + return; + } + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) + { + if (npc.state == BEAST_DYING) beast_dying_update(npc); + return; + } + if (npc.aiCallPhase == AI_PHASE_POST_UPDATE || npc.aiCallPhase == AI_PHASE_INTERPOLATE) return beast_follow(npc); + + int stage = beast_stage_get(npc); + beast_stage_update(npc, stage); + if (npc.isDead) + { + LayerState& ray = *npc.sprite.GetLayer(BEAST_RAY_LAYER); + layer_additive_set(ray); + ray.wrapSMode = WRAP_CLAMP; + ray.wrapTMode = WRAP_CLAMP; + npc.sprite.PlayOverlay("DeathRay"); + beast_summons_kill(npc); + } + + switch (npc.state) + { + case NPC_STATE_INIT: + beast_init(npc); + break; + case BEAST_IDLE: + beast_idle(npc, stage); + break; + case BEAST_MOVE: + beast_move(npc, stage, room); + break; + case BEAST_DIVE_TRANSITION: + case BEAST_DIVE: + beast_dive(npc, room); + break; + case BEAST_SURFACE: + case BEAST_SURFACE_ALT: + beast_surface(npc, room); + break; + case BEAST_SUCK: + beast_suck(npc, room); + break; + case BEAST_BLAST: + beast_blast(npc); + break; + case BEAST_DOUBLE_SHOT: + beast_double_shot(npc); + break; + case BEAST_SWITCH: + beast_switch(npc, room); + break; + case BEAST_SOUL_CALL: + beast_soul_call(npc, room); + break; + case BEAST_BACKGROUND: + beast_background(npc, room); + break; + } + + if (npc.isDead || (npc.state != BEAST_SUCK && npc.state != BEAST_BLAST)) g_manager->sfxManager.Stop(SOUND_BEAST_SUCTION_LOOP); + if (npc.state != BEAST_MOVE && npc.state != BEAST_BACKGROUND) + room.beastArena.scrollSpeed = std::max(room.beastArena.scrollSpeed - BEAST_BLAST_FADE, 0.0f); +} + +// 00592280 The background beast and its four horsemen behind the arena, held in its entity deque (the beast first). +void beast_background_spawn(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.ClearDequeRefs(); + npc.entityDeque.resize(BEAST_HORSEMEN + 1); + Vector middle = vector_make((room.bottomRightPos.x + room.topLeftPos.x) * HALF, + room.bottomRightPos.y - BEAST_BACKGROUND_RISE); + Entity* beast = g_game->Spawn({.position = middle, + .spawner = &npc, + .type = ENTITY_BEAST, + .variant = BEAST_BACKGROUND_BEAST, + .seed = Random()}); + beast->Update(); + npc.entityDeque[0] = beast; + for (int horseman = 0; horseman < BEAST_HORSEMEN; horseman++) + { + uint32_t seed = Random(); + Entity* rider = g_game->Spawn({.position = vector_add(beast->pos, BEAST_HORSEMAN_SPOTS[horseman]), + .spawner = &npc, + .type = ENTITY_BEAST, + .variant = BEAST_BACKGROUND_BEAST + 1 + horseman, + .seed = seed}); + rider->Update(); + npc.entityDeque[horseman + 1] = rider; + } +} + +// The stalactites (951.1) by subtype: hanging from the top or rising from the bottom, cracked (breaking once the +// Beast blasts it into the room), its cracked base and the tip that falls. They break on the Beast, drift with the +// arena and burst into rocks. +constexpr std::array STALACTITE_ANIMATIONS = {"Top", "Bottom", "TopCracked", "TopCrackedBase", + "TopCrackedTip"}; +constexpr std::array STALACTITE_HEIGHTS = {-10, -10, -10, -10, -110}; +constexpr uint64_t STALACTITE_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | + FLAG_NO_DEATH_TRIGGER | FLAG_NO_KNOCKBACK | FLAG_NO_PHYSICS_KNOCKBACK | + FLAG_HIDE_HP_BAR | FLAG_NO_REWARD | FLAG_NO_PLAYER_CONTROL; +constexpr float STALACTITE_FLOOR = 30; +constexpr float STALACTITE_FLOOR_REACH = 60; +constexpr float STALACTITE_FLOOR_FRICTION = 0.5f; +constexpr float STALACTITE_WOBBLE = -0.8f; +constexpr float STALACTITE_WOBBLE_STOP = 0.3f; +constexpr float STALACTITE_HIT_WOBBLE = 3; +constexpr float STALACTITE_CRACK_REACH = 200; +constexpr float STALACTITE_BASE_HEIGHT = 0.25f; +constexpr float STALACTITE_TIP_HEIGHT = HALF; +static const Vector STALACTITE_TIP_DROP = vector_make(0, 100); +constexpr float STALACTITE_TIP_FALL = 1.5f; +constexpr float STALACTITE_GONE = 200; +constexpr int STALACTITE_SHAKE = 4; +constexpr float STALACTITE_ROCK_AREA = 3800; +constexpr int STALACTITE_DISCARDED_DRAWS = 3; +constexpr float STALACTITE_SCATTER = 5; +constexpr float STALACTITE_THROW_SPREAD = 40; +constexpr float STALACTITE_THROW_SHARE = 0.7f; +constexpr float STALACTITE_THROW_SHARE_RANGE = 0.3f; +constexpr float STALACTITE_ROCK_SCALE = 0.8f; +constexpr float STALACTITE_ROCK_GRAVITY = 0.25f; +constexpr float STALACTITE_DUST_TURN = 10; +constexpr float STALACTITE_DUST_TURN_LEAST = 2; +constexpr int STALACTITE_DUST_FRAMES = 15; + +// A stalactite cracks: its base stays (its hitbox a quarter high) and its tip comes away, falling or flung. +static Entity_NPC* stalactite_crack(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_ROCK_CRUMBLE, 1, 2, false, 1); + npc.subtype = STALACTITE_CRACKED_BASE; + npc.sprite.Play("TopCrackedBase"); + EntityConfig_Entity& config = *npc.config; + npc.SetSize(config.collisionRadius, + vector_make(config.collisionRadiusMulti.x, config.collisionRadiusMulti.y * STALACTITE_BASE_HEIGHT), -1); + auto* tip = static_cast(g_game->Spawn({.position = vector_add(npc.pos, STALACTITE_TIP_DROP), + .subType = STALACTITE_TIP, + .type = ENTITY_BEAST, + .variant = BEAST_STALACTITE, + .seed = Random()})); + tip->SetSize(config.collisionRadius, + vector_make(config.collisionRadiusMulti.x, config.collisionRadiusMulti.y * STALACTITE_TIP_HEIGHT), -1); + tip->sprite.isFlipX = npc.sprite.isFlipX; + return tip; +} + +// A stalactite bursts into rocks flung along the Beast's blow and dust, from every null's capsule by its size. +static void stalactite_burst(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_ROCK_CRUMBLE, 1, 2, false, 1); + npc.PlaySound(SOUND_STONE_IMPACT, 1, 2, false, 1); + game_shake_screen(STALACTITE_SHAKE); + if (!npc.sprite.file) return; + for (const std::string& null : npc.sprite.file->nullLayerNames) + { + Capsule capsule; + npc.GetNullCapsule(capsule, null); + if (capsule.radius <= 0) continue; + int rocks = (int)std::ceil((capsule.halfLength + capsule.radius) * capsule.radius * 4 / STALACTITE_ROCK_AREA); + for (int rock = 0; rock < rocks; rock++) + { + for (int draw = 0; draw < STALACTITE_DISCARDED_DRAWS; draw++) Random(); + uint32_t seed = Random(); + float scatterAngle = random_unit() * RANDOM_HALF_TURN; + scatterAngle += scatterAngle; + float scatter = random_unit(); + float turn = random_unit() * STALACTITE_THROW_SPREAD - STALACTITE_THROW_SPREAD * HALF; + Vector throwDirection = vector_rotated(npc.v2, turn); + float share = random_unit() * STALACTITE_THROW_SHARE_RANGE + STALACTITE_THROW_SHARE; + Vector velocity = vector_add(vector_scale(vector_make(std::cos(scatterAngle), std::sin(scatterAngle)), scatter * STALACTITE_SCATTER), + vector_scale(throwDirection, share)); + auto* piece = static_cast(g_game->Spawn({.position = capsule.center, + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_BEAST, + .variant = BEAST_ROCK, + .seed = seed})); + piece->scale = random_unit() + STALACTITE_ROCK_SCALE; + float size = piece->scale * piece->shrinkStatus1; + piece->sprite.scale = vector_make(size, size); + piece->targetPosition = vector_make(STALACTITE_ROCK_GRAVITY, 0); + piece->Update(); + + uint32_t dustSeed = Random(); + float dustAngle = random_unit() * RANDOM_HALF_TURN; + dustAngle += dustAngle; + float dustSpeed = random_unit() * STALACTITE_SCATTER; + auto* dust = static_cast(g_game->Spawn({.position = capsule.center, + .velocity = vector_scale(vector_make(std::cos(dustAngle), std::sin(dustAngle)), dustSpeed), + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = dustSeed})); + dust->posOffset = npc.posOffset; + dust->sprite.scale = vector_make(1, 1); + dust->rotation = random_unit() * STALACTITE_DUST_TURN + STALACTITE_DUST_TURN_LEAST; + int frames = (int)(Random() % STALACTITE_DUST_FRAMES) + STALACTITE_DUST_FRAMES; + dust->timeout = frames; + dust->lifespan = frames; + dust->Update(); + } + } +} + +// 00596120 A stalactite (951.1): it wobbles when hit, a cracked one breaks off its tip once the blast carries it in, +// the Beast's blow (state 5) breaks it, and it is gone 200 past the side the arena scrolls toward. +static void beast_stalactite_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) + { + if (room.bottomRightPos.y - STALACTITE_FLOOR < npc.pos.y + STALACTITE_FLOOR_REACH) npc.friction *= STALACTITE_FLOOR_FRICTION; + if (npc.subtype == STALACTITE_TIP || vector_is_zero(npc.targetPosition)) return; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + return; + } + + size_t look = (uint32_t)npc.subtype < STALACTITE_TIP ? (size_t)npc.subtype : STALACTITE_TIP; + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc.sprite.Play(STALACTITE_ANIMATIONS[look]); + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + npc.flags = (npc.flags & ~FLAG_APPEAR) | STALACTITE_FLAGS; + npc.posOffset.y = STALACTITE_HEIGHTS[look]; + npc.targetPosition = npc.pos; + } + else if (npc.state == NPC_STATE_IDLE || npc.state == NPC_STATE_SUICIDE) + { + if (npc.posOffset.x != 0) + { + npc.posOffset.x *= STALACTITE_WOBBLE; + if (std::abs(npc.posOffset.x) < STALACTITE_WOBBLE_STOP) npc.posOffset.x = 0; + } + float force = room.beastArena.scrollSpeed; + if (npc.subtype == STALACTITE_CRACKED) + { + if ((force > 0 && room.topLeftPos.x + STALACTITE_CRACK_REACH < npc.pos.x) || + (force < 0 && npc.pos.x < room.bottomRightPos.x - STALACTITE_CRACK_REACH)) + stalactite_crack(npc)->Update(); + } + else if (npc.subtype == STALACTITE_TIP) npc.velocity.y += npc.speedMultiplier * STALACTITE_TIP_FALL; + + if (npc.state == NPC_STATE_SUICIDE) + { + npc.state = NPC_STATE_IDLE; + if (npc.subtype == STALACTITE_TOP || npc.subtype == STALACTITE_CRACKED) + { + Entity_NPC* tip = stalactite_crack(npc); + tip->isVisible = false; + tip->v2 = npc.v2; + tip->Kill(EntityRef(&npc)); + tip->Update(); + } + else npc.Kill(EntityRef()); + } + } + + if (npc.pendingDamage > 0) npc.posOffset.x = npc.posOffset.x >= 0 ? -STALACTITE_HIT_WOBBLE : STALACTITE_HIT_WOBBLE; + float force = room.beastArena.scrollSpeed; + if ((force > 0 && npc.pos.x > room.bottomRightPos.x + STALACTITE_GONE) || + (force < 0 && npc.pos.x < room.topLeftPos.x - STALACTITE_GONE)) + return npc.Remove(); + if (npc.isDead) stalactite_burst(npc); +} + +// The rocks (951.2): thrown pieces of stalactite that fall, splash into the lava, and break into rubble. +constexpr uint64_t BEAST_ROCK_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | FLAG_NO_KNOCKBACK | + FLAG_NO_PHYSICS_KNOCKBACK | FLAG_HIDE_HP_BAR | FLAG_NO_REWARD | FLAG_NO_PLAYER_CONTROL; +constexpr int BEAST_ROCK_LAST_TURN = 6; +constexpr float BEAST_ROCK_HEIGHT = -22; +constexpr float BEAST_ROCK_KEPT_TOP = -600; +constexpr float BEAST_ROCK_KEPT_SIDES = -200; +constexpr int BEAST_ROCK_SPLASH_AFTER = 2; +constexpr float BEAST_ROCK_LAVA = 30; +constexpr ColorMod BEAST_ROCK_RUBBLE_TINT = {{0.54901963f, 0.48235297f, 0.48235297f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float BEAST_ROCK_SOUND_MARGIN = -20; +constexpr float BEAST_ROCK_RUBBLE = 4; +constexpr float BEAST_ROCK_RUBBLE_RANGE = HALF; +constexpr int BEAST_ROCK_RUBBLE_MOST = 16; +constexpr float BEAST_ROCK_RUBBLE_SPEED = 1; +constexpr int TOOTH_PARTICLE_ROCK = 1; + +// The rock breaks: a poof in its color and, inside the room, rubble scattered from within it. +static void rock_break(Entity_NPC& npc) +{ + ColorMod rubbleColor = BEAST_ROCK_RUBBLE_TINT; + color_multiply(rubbleColor, npc.sprite.color); + Entity* poof = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_ROCK_POOF, .seed = Random()}); + poof->posOffset = npc.posOffset; + poof->SetColor(npc.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + poof->Update(); + poof->sprite.rotation = 0; + poof->sprite.scale = vector_make(npc.scale, npc.scale); + if (!g_game->room->IsPositionInRoom(npc.pos, BEAST_ROCK_SOUND_MARGIN)) return; + + npc_sound_play(SOUND_ROCK_CRUMBLE, 1, 2, 1); + int pieces = std::clamp((int)((random_unit() * BEAST_ROCK_RUBBLE_RANGE + 1) * npc.scale * BEAST_ROCK_RUBBLE), 1, BEAST_ROCK_RUBBLE_MOST); + for (int piece = 0; piece < pieces; piece++) + { + Vector direction = vector_from_angle(random_unit() * FULL_TURN_DEGREES); + float speed = random_unit() * 2 + BEAST_ROCK_RUBBLE_SPEED; + float reach = random_unit(); + Vector at = vector_add(vector_scale(direction, reach * npc.size), npc.pos); + Entity* rubble = g_game->Spawn({.position = at, + .velocity = vector_scale(direction, speed), + .subType = TOOTH_PARTICLE_ROCK, + .type = ENTITY_EFFECT, + .variant = EFFECT_TOOTH_PARTICLE, + .seed = Random()}); + rubble->posOffset = npc.posOffset; + rubble->SetColor(rubbleColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + rubble->Update(); + } +} + +// 00596c60 A rock (951.2): it turns by its size, falls by its targetPosition's x, is gone off the room's sides, +// splashes into the Beast's lava, and breaks on a player or familiar. +static void beast_rock_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_COLLISION) + { + int type = npc.collisionEntity->type; + if (type == ENTITY_PLAYER || type == ENTITY_FAMILIAR) npc.isDead = true; + return; + } + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc.sprite.Play("Rotate" + std::to_string(std::min((int)(npc.scale + npc.scale + 1), BEAST_ROCK_LAST_TURN))); + npc.scale = 1; + npc.sprite.scale = vector_make(1, 1); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.aiCallFlags = AI_CALL_COLLISION; + npc.flags = (npc.flags & ~FLAG_APPEAR) | BEAST_ROCK_FLAGS; + return; + } + + Room& room = *g_game->room; + npc.posOffset.y = BEAST_ROCK_HEIGHT; + npc.velocity.y += npc.speedMultiplier * npc.targetPosition.x; + Vector kept = room.GetClampedPositionImpl(npc.pos, BEAST_ROCK_KEPT_TOP, BEAST_ROCK_KEPT_SIDES, BEAST_ROCK_KEPT_SIDES, BEAST_ROCK_KEPT_SIDES); + if (kept.x != npc.pos.x || kept.y != npc.pos.y) npc.Remove(); + if (room.IsBeastDungeon() && g_game->frameCount - npc.spawnFrame > BEAST_ROCK_SPLASH_AFTER && npc.velocity.y > 0 && + room.bottomRightPos.y - BEAST_ROCK_LAVA < npc.pos.y) + { + npc.Remove(); + g_game->Spawn({.position = npc.pos, .subType = POOF02_LAVA_SPLASH, .type = ENTITY_EFFECT, .variant = EFFECT_POOF02, .seed = Random()}) + ->Update(); + return; + } + if (npc.isDead) rock_break(npc); +} + +// The Beast's souls (951.3): launched up at a slight random angle, they wander on a sine slowing down, then dash at the +// player and burst. Each leaves a trail drawn as a beam. +constexpr float BEAST_SOUL_HEIGHT = -15; +constexpr float BEAST_SOUL_LAUNCH_SPREAD = 20; +constexpr float BEAST_SOUL_LAUNCH_SPEED = 10; +constexpr RNG BEAST_SOUL_FRAME_SHIFTS = {0, 1, 27, 27}; +constexpr int BEAST_SOUL_IDLE_FRAMES = 4; +constexpr uint64_t BEAST_SOUL_FLAGS = + FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_DEATH_TRIGGER | FLAG_HIDE_HP_BAR | FLAG_NO_PLAYER_CONTROL; +constexpr int BEAST_SOUL_WANDER = NPC_STATE_IDLE; +constexpr int BEAST_SOUL_BURST = NPC_STATE_SUICIDE; +constexpr int BEAST_SOUL_DASH = NPC_STATE_ATTACK; +constexpr float BEAST_SOUL_SLOWDOWN = 0.002f; +constexpr float BEAST_SOUL_WEAVE_SPEED = 0.4f; +constexpr float BEAST_SOUL_WEAVE_SPEED_RANGE = 0.1f; +constexpr float BEAST_SOUL_WEAVE = 90; +constexpr float BEAST_SOUL_DRAG_LEAST = 0.95f; +constexpr float BEAST_SOUL_DASH_AT = 0.9f; +constexpr float BEAST_SOUL_DASH_PUSH = 2; +constexpr float BEAST_SOUL_DASH_TOP = 20; +constexpr int BEAST_SOUL_STEER_FRAMES = 40; +constexpr float BEAST_SOUL_STEER_RAMP = 0.25f; +constexpr float BEAST_SOUL_STEER_TOP = 20; +constexpr int BEAST_SOUL_DASH_FRAMES = 61; +constexpr float BEAST_SOUL_TRAIL_FADE = 0.1f; +constexpr float BEAST_SOUL_TRAIL_DRAG = 0.98f; +constexpr float BEAST_SOUL_TRAIL_ALPHA = 1.4f; +constexpr float BEAST_SOUL_TRAIL_SPEED = 8; +constexpr float BEAST_SOUL_TRAIL_WAVE = 0.4f; +constexpr float BEAST_SOUL_TRAIL_WAVE_ANGLE = 30; +constexpr float BEAST_SOUL_INTERPOLATION_STEP = HALF; +constexpr float BEAST_SOUL_ANGLE_UP = 90; + +// The soul's trail (vectorDeque1 kept, vectorDeque2 drawn, three vectors a point: its place, its drift and its alpha): +// each point drifts and fades, a new one is laid at the soul behind it, the faded ones drop. +static void soul_trail_update(Entity_NPC& npc, float step) +{ + std::deque& kept = npc.vectorDeque1; + std::deque& drawn = npc.vectorDeque2; + if (drawn.size() < kept.size()) drawn.resize(kept.size()); + float drag = timescale_factor(BEAST_SOUL_TRAIL_DRAG, step); + for (size_t i = 0; i < kept.size(); i += CORD_STRIDE) + { + drawn[i] = vector_add(kept[i], vector_scale(kept[i + 1], step)); + drawn[i + 1] = vector_scale(kept[i + 1], drag); + drawn[i + 2].x = std::max(kept[i + 2].x - BEAST_SOUL_TRAIL_FADE, 0.0f); + } + + drawn.push_front(vector_make(BEAST_SOUL_TRAIL_ALPHA, 0)); + Vector back = vector_resized(npc.velocity, BEAST_SOUL_TRAIL_SPEED); + float wave = std::sin(npc.updateTime * BEAST_SOUL_TRAIL_WAVE) * BEAST_SOUL_TRAIL_WAVE_ANGLE; + drawn.push_front(vector_scale(vector_rotated(back, wave), -1)); + drawn.push_front(vector_add(npc.posOffset, npc.pos)); + while (!drawn.empty() && drawn.back().x <= 0) + for (size_t i = 0; i < CORD_STRIDE; i++) drawn.pop_back(); + + npc.sprite.rotation = vector_angle(npc.velocity) + BEAST_SOUL_ANGLE_UP; + if (npc.aiCallPhase != AI_PHASE_INTERPOLATE) kept = drawn; +} + +// The soul's dash: pushed along its heading (v2) at most 20, steering toward its target for 40 frames, bursting after +// 60 (or at once without a target). +static void soul_dash(Entity_NPC& npc) +{ + if (npc.target) + { + npc.velocity = vector_add(npc.velocity, vector_scale(npc.v2, BEAST_SOUL_DASH_PUSH * npc.speedMultiplier)); + float speed = vector_length(npc.velocity); + if (speed > BEAST_SOUL_DASH_TOP && speed > 0) npc.velocity = vector_scale(npc.velocity, BEAST_SOUL_DASH_TOP / speed); + if (npc.stateFrame < BEAST_SOUL_STEER_FRAMES) + { + Vector steer = vector_resized(vector_sub(npc.target->pos, npc.pos), + std::min((float)npc.stateFrame * BEAST_SOUL_STEER_RAMP, BEAST_SOUL_STEER_TOP)); + npc.v2 = vector_normalized(vector_add(npc.v2, vector_scale(steer, npc.speedMultiplier))); + } + npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame < BEAST_SOUL_DASH_FRAMES) return; + } + npc.state = BEAST_SOUL_BURST; +} + +// 005971e0 A soul of the Beast (951.3): launched up, it weaves while slowing, then dashes at the player and bursts +// like Dogma's babies, its trail laid after each update and interpolation. +static void beast_soul_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_POST_UPDATE) return soul_trail_update(npc, npc.speedMultiplier); + if (npc.aiCallPhase == AI_PHASE_INTERPOLATE) return soul_trail_update(npc, BEAST_SOUL_INTERPOLATION_STEP * npc.speedMultiplier); + + switch (npc.state) + { + case NPC_STATE_INIT: + { + npc.posOffset.y = BEAST_SOUL_HEIGHT; + float launch = random_unit() * BEAST_SOUL_LAUNCH_SPREAD - BEAST_SOUL_LAUNCH_SPREAD * HALF; + npc.v2 = vector_rotated(vector_make(0, -1), launch); + npc.velocity = vector_scale(npc.v2, BEAST_SOUL_LAUNCH_SPEED); + RNG rng = BEAST_SOUL_FRAME_SHIFTS; + rng._seed = npc.initSeed; + npc.sprite.SetFrame("Idle", (int)rng.RandomInt(BEAST_SOUL_IDLE_FRAMES)); + npc.isInvincible = true; + npc.v1.x = 1; + npc.flags = (npc.flags & ~FLAG_APPEAR) | BEAST_SOUL_FLAGS; + npc.state = BEAST_SOUL_WANDER; + npc.aiCallFlags = AI_CALL_INTERPOLATE | AI_CALL_POST_UPDATE; + break; + } + case BEAST_SOUL_WANDER: + { + npc.v1.x -= npc.speedMultiplier * BEAST_SOUL_SLOWDOWN; + Vector drift = vector_resized(npc.velocity, npc.v1.x * npc.v1.x); + float weave = std::sin((random_unit() * BEAST_SOUL_WEAVE_SPEED_RANGE + BEAST_SOUL_WEAVE_SPEED) * npc.updateTime) * BEAST_SOUL_WEAVE; + float speed = vector_length(npc.velocity); + Vector turned = vector_resized(vector_add(vector_rotated(drift, weave), npc.velocity), speed); + npc.velocity = vector_scale(turned, timescale_factor(std::max(npc.v1.x, BEAST_SOUL_DRAG_LEAST), npc.speedMultiplier)); + if (vector_length_squared(npc.velocity) > 1) npc.v2 = vector_normalized(npc.velocity); + if (npc.v1.x >= BEAST_SOUL_DASH_AT) break; + npc.state = BEAST_SOUL_DASH; + npc_sound_play(SOUND_BEAST_GHOST_DASH, 1, 2, 1); + npc.target = npc.GetPlayerTarget(); + npc.stateFrame = 0; + break; + } + case BEAST_SOUL_BURST: + { + Entity* burst = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = ENEMY_GHOST_BLAST, + .type = ENTITY_EFFECT, + .variant = EFFECT_ENEMY_GHOST, + .seed = Random()}); + burst->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + burst->sprite.scale = vector_make(1, 1); + burst->SetCollisionDamage(20); + burst->Update(); + damage_radius({.position = npc.pos, .source = &npc, .damage = 1, .playerDamageThreshold = 50, .radius = 60}); + npc_sound_play(SOUND_DEMON_HIT, 0.8f, 2, random_unit() * 0.2f + 1.2f); + npc.Remove(); + break; + } + case BEAST_SOUL_DASH: + soul_dash(npc); + break; + } +} + +constexpr size_t BEAST_SOUL_TRAIL_LEAST = 8; +constexpr float BEAST_SOUL_TRAIL_SMOOTH_EDGE = 0.3f; +constexpr float BEAST_SOUL_TRAIL_SMOOTH_MIDDLE = 0.4f; +constexpr float BEAST_SOUL_TRAIL_LONGEST = 128; +constexpr float BEAST_SOUL_TRAIL_THINNEST = HALF; + +// 00597d00 Draws a soul's trail through the beam renderer: its points on screen, smoothed, fading by their alpha, +// narrowed when the trail is longer than 128. +static void beast_soul_render(Entity_NPC& npc, const Vector& offset) +{ + std::deque& trail = npc.vectorDeque2; + if (trail.size() <= BEAST_SOUL_TRAIL_LEAST) return; + + std::vector screen; + for (size_t i = 0; i < trail.size(); i += CORD_STRIDE) + screen.push_back(vector_add(render_position_get(trail[i], RENDER_SNAPPED), offset)); + + struct TrailPoint + { + Vector pos{}; + float alpha = 0; + float length = 0; + }; + std::vector points = {{.pos = screen[0], .alpha = trail[2].x}}; + float length = 0; + for (size_t i = 1; i + 1 < screen.size(); i++) + { + Vector smoothed = vector_add(vector_add(vector_scale(screen[i - 1], BEAST_SOUL_TRAIL_SMOOTH_EDGE), + vector_scale(screen[i], BEAST_SOUL_TRAIL_SMOOTH_MIDDLE)), + vector_scale(screen[i + 1], BEAST_SOUL_TRAIL_SMOOTH_EDGE)); + points.push_back({.pos = smoothed, .alpha = trail[i * CORD_STRIDE + 2].x}); + length += vector_distance(points[points.size() - 2].pos, points.back().pos); + points.back().length = length; + } + float width = 1; + if (length > BEAST_SOUL_TRAIL_LONGEST) width = std::max(BEAST_SOUL_TRAIL_LONGEST / length, BEAST_SOUL_TRAIL_THINNEST); + + g_beamRenderer.Begin(npc.sprite, 0, BEAM_FRAME_MAIN, BEAM_COORDINATE_PIXELS); + for (const TrailPoint& point : points) + g_beamRenderer.Add({.color = color_make({1, 1, 1, point.alpha}), + .pos = point.pos, + .coordinate = width * point.length, + .width = width}); + g_beamRenderer.End(); +} + +// 00598260 The Beast's forms draw themselves, but for the souls' trails. +void beast_render(Entity_NPC& npc, const Vector& offset) +{ + if (npc.variant == BEAST_SOUL) return beast_soul_render(npc, offset); + npc.Entity::Render(offset); +} + +// The Beast's forms (951) by variant: its stalactites, rocks and souls, the four ultra horsemen and their summons, and +// the background beasts. +void boss_beast_update(Entity_NPC& npc) +{ + switch (npc.variant) + { + case BEAST_STALACTITE: + return beast_stalactite_update(npc); + case BEAST_ROCK: + return beast_rock_update(npc); + case BEAST_SOUL: + return beast_soul_update(npc); + case BEAST_ULTRA_FAMINE: + return NpcAI::ENTITY_BEAST_ultra_famine(&npc); + case BEAST_ULTRA_FAMINE_FLY: + return NpcAI::ENTITY_BEAST_ultra_famine_fly(&npc); + case BEAST_ULTRA_PESTILENCE: + return NpcAI::ENTITY_BEAST_ultra_pestilence(&npc); + case BEAST_ULTRA_PESTILENCE_FLY: + return NpcAI::ENTITY_BEAST_pestilence_fly(&npc); + case BEAST_ULTRA_PESTILENCE_MAGGOT: + return NpcAI::ENTITY_BEAST_ultra_pestilence_maggot(&npc); + case BEAST_ULTRA_PESTILENCE_FLY_BALL: + return NpcAI::ENTITY_BEAST_ultra_pestilence_fly_ball(&npc); + case BEAST_ULTRA_WAR: + return NpcAI::ENTITY_BEAST_ultra_war(&npc); + case BEAST_ULTRA_WAR_BOMB: + return NpcAI::ENTITY_BEAST_ultra_war_bomb(&npc); + case BEAST_ULTRA_DEATH: + return NpcAI::ENTITY_BEAST_ultra_death(&npc); + case BEAST_ULTRA_DEATH_SCYTHE: + return NpcAI::ENTITY_BEAST_ultra_death_scythe(&npc); + case BEAST_ULTRA_DEATH_HEAD: + return NpcAI::ENTITY_BEAST_ultra_death_head(&npc); + case BEAST_BACKGROUND_BEAST: + case BEAST_BACKGROUND_FAMINE: + case BEAST_BACKGROUND_PESTILENCE: + case BEAST_BACKGROUND_WAR: + case BEAST_BACKGROUND_DEATH: + return NpcAI::ENTITY_BEAST_background(&npc); + default: + return beast_update(npc); + } +} diff --git a/src/boss_clog.cpp b/src/boss_clog.cpp new file mode 100644 index 0000000..cd3fbea --- /dev/null +++ b/src/boss_clog.cpp @@ -0,0 +1,345 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "manager.h" +#include "loot_list.h" +#include "npc_ai.h" +#include + +// Clog's states: idling, spitting a drip, its whirlpool spin, its bullet hell and its fart. +constexpr int CLOG_IDLE = NPC_STATE_IDLE; +constexpr int CLOG_SPIT = NPC_STATE_ATTACK; +constexpr int CLOG_SPIN = NPC_STATE_ATTACK2; +constexpr int CLOG_BULLET_HELL = NPC_STATE_ATTACK3; +constexpr int CLOG_FART = NPC_STATE_ATTACK4; + +// Clog keeps its cooldowns packed in i2's bytes, as the original does: the spin's, the bullet hell's and the fart's, +// each 90 after its attack, counted down every other frame. +enum ClogCooldown +{ + COOLDOWN_UNUSED, + COOLDOWN_SPIN, + COOLDOWN_BULLET_HELL, + COOLDOWN_FART +}; +constexpr uint8_t CLOG_ATTACK_COOLDOWN = 90; + +static uint8_t& clog_cooldown(Entity_NPC& npc, ClogCooldown which) +{ + return reinterpret_cast(&npc.i2)[which]; +} + +// Its pick, one frame in ten: a spit (40 for each enemy missing from 5), the spin (20 per enemy from 3 enemies, +// else 1), the bullet hell and the fart (30 each, 1 while cooling down). +constexpr uint32_t CLOG_ATTACK_ODDS = 10; +constexpr int CLOG_SPIT_ENEMY_LIMIT = 5; +constexpr int CLOG_SPIT_WEIGHT = 40; +constexpr int SPIN_WEIGHT = 20; +constexpr int SPIN_WEIGHT_MIN = 60; +constexpr int CLOG_ATTACK_WEIGHT = 30; +constexpr float SPIN_SLOW = 10; +constexpr float SPIN_FAST = 25; +constexpr float CLOG_FRICTION = 0.7f; + +// The spit: a drip 10 out within 45 of down, flung at 5 to 10 with a splash 40 up. +constexpr float CLOG_SPIT_SPREAD = 90; +constexpr float CLOG_SPIT_SPREAD_HALF = 45; +constexpr float CLOG_SPIT_REACH = 10; +constexpr float CLOG_SPIT_SPEED = 5; +constexpr float CLOG_SPIT_SPEED_RANGE = 5; +constexpr float CLOG_SPIT_SPLASH_HEIGHT = -40; +constexpr int CLOG_SPIT_SPLASH_DEPTH = 500; +constexpr ColorMod CLOG_SPIT_SPLASH_COLOR = {{1, 1, 1, 1}, {3.5f, 2.5f, 2.4f, 1}, {0, 0, 0}}; +constexpr int DRIP_FLUNG = NPC_STATE_MOVE; + +// The spin: a whirlpool every 8 frames from the 5th, drawing the walkers in (at up to 1.5 after 22 frames), turning +// them 90 about it, splashing about players and enemies every 3rd frame; it ends with its animation past 90 frames. +constexpr int SPIN_WATER_SOUND_FRAME = 5; +constexpr int SPIN_WATER_DELAY = 30; +constexpr float SPIN_CENTER_SLACK = 80; +constexpr float SPIN_CENTER_PUSH = 2; +constexpr float SPIN_RAMP = 15; +constexpr float SPIN_PULL_MAX = 1.5f; +constexpr int SPIN_WHIRL_FROM = 4; +constexpr int SPIN_WHIRL_EVERY = 8; +constexpr float SPIN_WHIRL_SCALE = 1; +constexpr float SPIN_WHIRL_SCALE_RANGE = 0.5f; +constexpr float SPIN_INWARD = 0.4f; +constexpr float SPIN_AROUND = 0.8f; +constexpr uint32_t SPLASH_RANGE = 3; +constexpr int SPLASH_MIN = 2; +constexpr float CLOG_SPLASH_SPEED = 4; +constexpr float CLOG_SPLASH_SPEED_RANGE = 6; +constexpr int CLOG_ATTACK_FRAMES = 90; + +// The bullet hell: a ring of four puke shots every 6 frames, turning with its spin, at 4 (6 for the fast spin) falling +// slower for the fast one, their flags changing after 30. +constexpr int HELL_EVERY = 6; +constexpr int HELL_SOUND_DELAY = 45; +constexpr float HELL_SOUND_PITCH = 0.8f; +constexpr float HELL_FAST_TURN = 20; +constexpr float HELL_SPEED = 4; +constexpr float HELL_SPEED_FAST = 6; +constexpr float HELL_SHOTS = 4; +constexpr float HELL_FALL = -0.1f; +constexpr float HELL_FALL_FAST = -0.05f; +constexpr int HELL_CHANGE_TIMEOUT = 30; + +// The fart: three fart waves 30 out, 120 apart, two of them carrying an eternal fly while fewer than 3 are out. +constexpr int FART_WAVES = 3; +constexpr float FART_STEP = 120; +constexpr float FART_REACH = 30; +constexpr int ETERNAL_FLY_LIMIT = 3; +constexpr int FART_LAUGH_DELAY = 20; +constexpr float FART_LAUGH_PITCH = 0.9f; + +// The spit's drip and its splash. +static void clog_spit(Entity_NPC& npc) +{ + Vector heading = vector_rotated(vector_make(0, 1), random_unit() * CLOG_SPIT_SPREAD - CLOG_SPIT_SPREAD_HALF); + uint32_t seed = Random(); + auto* drip = static_cast(g_game->Spawn( + {.position = vector_add(npc.pos, vector_scale(heading, CLOG_SPIT_REACH)), .spawner = &npc, .type = ENTITY_DRIP, .seed = seed})); + npc_push(*drip, vector_scale(heading, random_unit() * CLOG_SPIT_SPEED_RANGE + CLOG_SPIT_SPEED)); + drip->ClearEntityFlags(FLAG_APPEAR); + drip->state = DRIP_FLUNG; + drip->Update(); + + seed = Random(); + Entity* splash = g_game->Spawn({.position = drip->pos, .velocity = drip->velocity, .subType = 1, + .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = seed}); + splash->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + splash->sprite.Play("Poof"); + splash->posOffset = vector_make(0, CLOG_SPIT_SPLASH_HEIGHT); + splash->renderZOffset = CLOG_SPIT_SPLASH_DEPTH; + splash->sprite.color = CLOG_SPIT_SPLASH_COLOR; + npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); +} + +// The spin's draw on everything walking: in and around it, splashing about the players and enemies it moves. +static void clog_whirl_pull(Entity_NPC& npc, float pull, float around) +{ + std::vector entities(g_game->room->entityList.updateEL.begin(), g_game->room->entityList.updateEL.end()); + for (Entity* entity : entities) + { + bool isCreature = entity->type == ENTITY_PLAYER || Entity::is_enemy_type(entity->type); + if (!isCreature && entity->type != ENTITY_PICKUP && entity->type != ENTITY_BOMB) continue; + bool isWalking = entity->entityGridCollisionClass == GRIDCOLL_GROUND || + entity->entityGridCollisionClass == GRIDCOLL_NOPITS; + if (entity->IsBoss() || !isWalking) continue; + + Vector inward = vector_normalized(vector_sub(npc.pos, entity->pos)); + Vector drift = vector_scale(vector_add(vector_scale(vector_rotated(inward, around), SPIN_AROUND), + vector_scale(inward, SPIN_INWARD)), + pull); + entity->velocity = vector_add(entity->velocity, drift); + if (!entity->IsFrame(3, 0) || !isCreature) continue; + + for (uint32_t count = Random() % SPLASH_RANGE + SPLASH_MIN; count != 0; count--) + { + Vector at = random_direction(); + Vector spot = vector_add(entity->pos, vector_scale(vector_scale(at, entity->size), random_unit())); + uint32_t seed = Random(); + float speed = random_unit() * CLOG_SPLASH_SPEED_RANGE + CLOG_SPLASH_SPEED; + Vector velocity = vector_add(vector_scale(drift, speed), random_direction()); + g_game->Spawn({.position = spot, .velocity = velocity, .spawner = entity, .subType = 1, + .type = ENTITY_EFFECT, .variant = EFFECT_WATER_SPLASH, .seed = seed})->Update(); + } + } +} + +// The spin: a whirlpool about it drawing everything in, ending once its loop finishes past 90 frames. +static void clog_spin_update(Entity_NPC& npc) +{ + npc.sprite.Play(npc.i1 == 0 ? "SpinLoop" : "SpinLoop2"); + npc.stateFrame++; + if (npc.stateFrame == SPIN_WATER_SOUND_FRAME) + g_manager->sfxManager.Play(SOUND_BOSS2_WATERTHRASHING, {.frameDelay = SPIN_WATER_DELAY}); + + Vector fromCenter = vector_sub(npc.pos, Room::GetCenterPos()); + if (vector_length(fromCenter) > SPIN_CENTER_SLACK) + npc_push(npc, vector_scale(vector_normalized(fromCenter), SPIN_CENTER_PUSH)); + float pull = std::min((float)npc.stateFrame / SPIN_RAMP, SPIN_PULL_MAX); + float around = npc.i1 == 0 ? RIGHT_ANGLE_DEGREES : -RIGHT_ANGLE_DEGREES; + if (npc.stateFrame > SPIN_WHIRL_FROM && npc.IsFrame(SPIN_WHIRL_EVERY, 0)) + { + uint32_t seed = Random(); + auto* whirl = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_WHIRLPOOL, .seed = seed})); + whirl->rotation = random_unit() * FULL_TURN_DEGREES; + whirl->sprite.isFlipX = npc.i1 == 0; + float scale = random_unit() * SPIN_WHIRL_SCALE_RANGE + SPIN_WHIRL_SCALE; + whirl->sprite.scale = vector_make(scale, scale); + whirl->Update(); + } + clog_whirl_pull(npc, pull, around); + + if (npc.stateFrame <= CLOG_ATTACK_FRAMES) return; + const AnimationData* data = npc.sprite.animState.animData; + if (npc.sprite.GetFrame() != (data ? data->length : 0) - 1) return; + npc.sprite.Play(npc.i1 == 0 ? "SpinEnd" : "SpinEnd2"); + npc.stateFrame = -1; +} + +// The bullet hell: rings of puke shots every 6 frames as it turns. +static void clog_bullet_hell_update(Entity_NPC& npc) +{ + npc.sprite.Play("BulletHellLoop"); + npc.PlaySound(SOUND_FART_GURG, 1, HELL_SOUND_DELAY, false, HELL_SOUND_PITCH); + bool isSlow = std::abs(npc.v1.y) < HELL_FAST_TURN; + int frame = npc.stateFrame; + if (frame % HELL_EVERY == 0) + { + ProjectileParams params; + params.targetPosition = npc.pos; + params.fallingAccelModifier = isSlow ? HELL_FALL : HELL_FALL_FAST; + params.variant = PROJECTILE_PUKE; + params.circleAngle = npc.v1.x * PI_F / HALF_TURN_DEGREES; + params.bulletFlags = PROJECTILE_NO_WALL_COLLIDE | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT; + params.changeTimeout = HELL_CHANGE_TIMEOUT; + params.changeFlags = 0; + npc.FireProjectiles(npc.pos, vector_make(isSlow ? HELL_SPEED : HELL_SPEED_FAST, HELL_SHOTS), PROJECTILES_RING, params); + npc.v1.x = normalize_angle_degrees(npc.v1.x + npc.v1.y); + frame = npc.stateFrame; + } + npc.stateFrame = frame + 1; + if (npc.stateFrame < CLOG_ATTACK_FRAMES + 1) return; + npc.sprite.Play("BulletHellEnd"); + npc.stateFrame = -1; +} + +// An attack of three steps: its begin (stateFrame 0), its loop (above 0) and its end (below 0), cooling down after. +static void clog_phased_update(Entity_NPC& npc, std::string_view begin, ClogCooldown cooldown, void (*loop)(Entity_NPC&)) +{ + if (npc.stateFrame == 0) + { + npc.sprite.Play(begin); + if (npc.sprite.IsFinished()) npc.stateFrame = 1; + return; + } + if (npc.stateFrame > 0) return loop(npc); + if (!npc.sprite.IsFinished()) return; + npc.state = CLOG_IDLE; + clog_cooldown(npc, cooldown) = CLOG_ATTACK_COOLDOWN; +} + +// The fart: three fart waves about it, two carrying an eternal fly while there are few. +static void clog_fart(Entity_NPC& npc) +{ + npc_sound_play(SOUND_CLOG_POOPSMOKE, 1, 2, 1); + float base = random_unit() * FULL_TURN_DEGREES; + int flies = (int)entity_query(ENTITY_ETERNALFLY, -1).size(); + for (uint32_t i = 0; i < FART_WAVES; i++) + { + float angle = (float)i * FART_STEP + base; + int carriesFly = 0; + if (i < 2 && flies < ETERNAL_FLY_LIMIT) + { + flies++; + carriesFly = 1; + } + uint32_t seed = Random(); + auto* wave = static_cast(g_game->Spawn({.position = vector_add(npc.pos, vector_scale(vector_from_angle(angle), FART_REACH)), + .spawner = &npc, + .subType = carriesFly, + .type = ENTITY_EFFECT, + .variant = EFFECT_FARTWAVE, + .seed = seed})); + wave->rotation = angle; + wave->Update(); + } +} + +// Its pick of an attack once in a while: spit when the room is empty, spin when crowded, else bullet hell or fart. +static void clog_attack_pick(Entity_NPC& npc) +{ + int enemies = std::max(g_game->room->GetAliveEnemiesCount(), 0); + WeightedOutcomePicker picker; + int spitWeight = (CLOG_SPIT_ENEMY_LIMIT - enemies) * CLOG_SPIT_WEIGHT; + if (spitWeight > 0) picker.AddOutcomeWeight(CLOG_SPIT, spitWeight); + int spinWeight = enemies * SPIN_WEIGHT; + if (spinWeight < SPIN_WEIGHT_MIN || clog_cooldown(npc, COOLDOWN_SPIN)) spinWeight = 1; + if (spinWeight > 0) picker.AddOutcomeWeight(CLOG_SPIN, spinWeight); + picker.AddOutcomeWeight(CLOG_BULLET_HELL, clog_cooldown(npc, COOLDOWN_BULLET_HELL) ? 1 : CLOG_ATTACK_WEIGHT); + picker.AddOutcomeWeight(CLOG_FART, clog_cooldown(npc, COOLDOWN_FART) ? 1 : CLOG_ATTACK_WEIGHT); + + npc.state = picker.PickOutcome({Random() | 1, 5, 9, 7}); + if (npc.state == CLOG_SPIN) npc.i1 = (int)(Random() & 1); + else if (npc.state == CLOG_BULLET_HELL) + { + npc.v1.x = random_unit() * FULL_TURN_DEGREES; + float spin = (Random() & 1) == 0 ? SPIN_SLOW : SPIN_FAST; + npc.v1.y = (Random() & 1) == 0 ? -spin : spin; + } + npc.stateFrame = 0; +} + +// 004a12f0 Clog: a toilet boss rooted in place that spits drips, spins a whirlpool, rings puke shots and farts out +// eternal flies. Its death flushes, taking its drips with it. +void boss_clog_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = CLOG_IDLE; + npc.splatColor = POOP_SPLAT_COLOR; + npc.stateFrame = 0; + npc.projectileDelay = 0; + npc.targetPosition = npc.pos; + npc.i2 = 0; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + break; + case CLOG_IDLE: + npc.sprite.Play("Idle"); + if (Random() % CLOG_ATTACK_ODDS == 0) clog_attack_pick(npc); + break; + case CLOG_SPIT: + npc.sprite.Play("Spit"); + if (npc.sprite.animState.animData) + { + if (npc.sprite.animState.IsEventTriggered("Shoot")) clog_spit(npc); + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) break; + } + npc.state = CLOG_IDLE; + break; + case CLOG_SPIN: + clog_phased_update(npc, npc.i1 == 0 ? "SpinBegin" : "SpinBegin2", COOLDOWN_SPIN, &clog_spin_update); + break; + case CLOG_BULLET_HELL: + clog_phased_update(npc, "BulletHellBegin", COOLDOWN_BULLET_HELL, &clog_bullet_hell_update); + break; + case CLOG_FART: + npc.sprite.Play("Fart"); + if (npc.sprite.animState.animData) + { + if (npc.sprite.animState.IsEventTriggered("Shoot")) clog_fart(npc); + if (npc.sprite.animState.animData) + { + if (npc.sprite.animState.IsEventTriggered("Sound")) + npc.PlaySound(SOUND_BROWNIE_LAUGH, 1, FART_LAUGH_DELAY, false, FART_LAUGH_PITCH); + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) break; + } + } + npc.state = CLOG_IDLE; + clog_cooldown(npc, COOLDOWN_FART) = CLOG_ATTACK_COOLDOWN; + break; + default: + break; + } + + if (npc.IsFrame(2, 0)) + for (int which = COOLDOWN_UNUSED; which <= COOLDOWN_FART; which++) + { + uint8_t& cooldown = clog_cooldown(npc, (ClogCooldown)which); + if (cooldown != 0) cooldown--; + } + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + npc.friction *= CLOG_FRICTION; + if (!npc.isDead) return; + + uint32_t seed = Random(); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_WHIRLPOOL, .seed = seed})->Update(); + npc_sound_play(SOUND_FLUSH, 1, 2, 1); + g_manager->sfxManager.Stop(SOUND_BOSS2_WATERTHRASHING); + for (Entity* drip : entity_query(ENTITY_DRIP, -1)) + if (drip->IsVulnerableEnemy(nullptr) && !drip->HasEntityFlags(FLAG_FRIENDLY)) static_cast(drip)->KillUnique(); +} diff --git a/src/boss_dogma.cpp b/src/boss_dogma.cpp new file mode 100644 index 0000000..79149f0 --- /dev/null +++ b/src/boss_dogma.cpp @@ -0,0 +1,1754 @@ +#include "boss_final.h" +#include "active_items.h" +#include "backdrop.h" +#include "boss_ai.h" +#include "camera.h" +#include "entity_effect.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "grid_entity_trap_door.h" +#include "manager.h" +#include "menu_manager.h" +#include "music_manager.h" +#include "npc_alt.h" +#include "npc_basement.h" +#include "player_manager.h" +#include "room_config.h" +#include "room_grid.h" +#include "room_transition.h" +#include +#include + +// Dogma's states: its appearance (skipped once it is in the bestiary), its four attacks and the scream, and the +// transition into the angel once the TV breaks. +constexpr int DOGMA_APPEAR = NPC_STATE_APPEAR_CUSTOM; +constexpr int DOGMA_IDLE = NPC_STATE_IDLE; +constexpr int DOGMA_SKIPPED = NPC_STATE_STOMP; +constexpr int DOGMA_BRIMSTONE = NPC_STATE_ATTACK; +constexpr int DOGMA_JACOB = NPC_STATE_ATTACK2; +constexpr int DOGMA_CROSS = NPC_STATE_ATTACK3; +constexpr int DOGMA_GODHEAD = NPC_STATE_ATTACK4; +constexpr int DOGMA_BLACKHOLE = NPC_STATE_ATTACK5; +constexpr int DOGMA_SCREAM = NPC_STATE_SUMMON; +constexpr int DOGMA_TRANSITION = NPC_STATE_SPECIAL; + +// Its attacks, picked at random from the first four, the cross also following Jacob's Ladder below half health. +enum DogmaAttack +{ + DOGMA_ATTACK_NONE = -1, + DOGMA_ATTACK_BRIMSTONE, + DOGMA_ATTACK_JACOB, + DOGMA_ATTACK_CROSS, + DOGMA_ATTACK_GODHEAD, + DOGMA_ATTACK_BLACKHOLE +}; + +// The directions its Brimstone fires (Isaac's Direction). +constexpr int DOGMA_FACE_LEFT = 0; +constexpr int DOGMA_FACE_UP = 1; +constexpr int DOGMA_FACE_RIGHT = 2; +constexpr int DOGMA_FACE_DOWN = 3; + +// Its look: the cord layer hidden under the overlay, the white flash it splats, the room darkened for the fight and +// lit by the static of its appearance. +constexpr int DOGMA_CORD_LAYER = 2; +constexpr int DOGMA_DISTORTION_LAYER = 0; +constexpr uint64_t DOGMA_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_DONT_COUNT_BOSS_HP | FLAG_HIDE_HP_BAR; +constexpr ColorMod DOGMA_SPLAT_COLOR = {{1, 1, 1, 1}, {3, 3, 3, 1}, {0, 0, 0}}; +constexpr ColorModState DOGMA_ROOM_DARK = {0.1f, 0.1f, 0.1f, 0.3f, 0, 1.02f}; +constexpr ColorModState DOGMA_ROOM_FLASH = {0, 0, 0, 0, 1, 1}; +constexpr float DOGMA_ROOM_DARK_RATE = 0.015f; +constexpr float DOGMA_ROOM_DARK_FAST = 0.04f; +constexpr int DOGMA_INTRO_BOSS = 99; +constexpr int DOGMA_FIRST_COOLDOWN = 20; +constexpr int DOGMA_FIGHT_COOLDOWN = 60; +constexpr int DOGMA_COOLDOWN_RANGE = 30; + +// The distortion its layers take from their Distortion null, 3 more while a hit's timer runs, and how fast its glow +// fades. +constexpr float DOGMA_DISTORTION_HIT = 3; +constexpr float DOGMA_GLOW_FADE = 0.05f; + +// Its cord to the TV: ten points laid from it to the TV with a sine sway, hung 30 below, and the pull past 190. +constexpr int DOGMA_CORD_POINTS = 10; +constexpr float DOGMA_CORD_LAST = 9; +constexpr float DOGMA_CORD_SWAY = 10; +constexpr float DOGMA_CORD_SWAY_STEP = 0.4f; +constexpr float DOGMA_CORD_TV_LEFT = 8; +constexpr float DOGMA_CORD_HANG = -30; +constexpr float DOGMA_TV_DROP = 20; +constexpr float DOGMA_LEASH = 190; +constexpr float DOGMA_LEASH_PULL = 0.1f * 0.3f; + +// The appearance: its splat and the static it leaves, its scream's shockwave, the debris ringing the room's edges +// pushed 10 to 90 out, and the players pushed 80 from it. +constexpr float DOGMA_APPEAR_FRICTION = 0.8f; +constexpr float DOGMA_STATIC_SCALE = 1.2f; +constexpr int DOGMA_STATIC_FRAMES = 300; +constexpr float DOGMA_SHOCKWAVE_AMPLITUDE = 0.04f; +constexpr float DOGMA_SHOCKWAVE_SPEED = 0.07f; +constexpr int DOGMA_SHOCKWAVE_FRAMES = 20; +constexpr int DOGMA_APPEAR_SHAKE = 6; +constexpr RNG DOGMA_DEBRIS_SHIFTS = {0, 1, 5, 19}; +constexpr int DOGMA_DEBRIS_COUNT = 30; +constexpr float DOGMA_DEBRIS_SPACING = 20; +constexpr float DOGMA_DEBRIS_PUSH = 80; +constexpr float DOGMA_DEBRIS_PUSH_LEAST = 10; +constexpr float DOGMA_PLAYER_ROOM = 80; +constexpr int DOGMA_STATIC_EVERY = 7; +constexpr int DOGMA_TRAIL_FRAMES = 60; +constexpr float DOGMA_TRAIL_SCALE_LEAST = 0.5f; + +// Its drift about the TV: toward its target at aiFloat, sliding around the TV's side, settling to 0.5 (0.9 beside the +// TV, 0.05 while it holds a blackhole). +constexpr float DOGMA_DRIFT_FRICTION = 0.8f; +constexpr float DOGMA_DRIFT = 0.5f; +constexpr float DOGMA_DRIFT_SIDE = 0.9f; +constexpr float DOGMA_DRIFT_HOLDING = 0.05f; +constexpr float DOGMA_DRIFT_SETTLE = 0.9f; + +// The Brimstone: 90 frames from its mouth 15 up, its beam held 30 higher, aimed at least 100 out and swept toward the +// player by a tenth, at most 10 degrees a frame, never closer than 60, turning to face the player after 15 frames. +constexpr int DOGMA_BRIMSTONE_FRAMES = 90; +constexpr float DOGMA_MOUTH_HEIGHT = -15; +constexpr float DOGMA_BEAM_HEIGHT = -30; +constexpr float DOGMA_BEAM_RAMP = 20; +constexpr int DOGMA_BEAM_TAIL = 15; +constexpr float DOGMA_BEAM_DEPTH_UP = -50; +constexpr float DOGMA_BEAM_DEPTH = 1000; +constexpr float DOGMA_BEAM_REACH_LEAST = 100; +constexpr int DOGMA_BEAM_SHAKE = 10; +constexpr float DOGMA_BEAM_SWEEP = 0.1f; +constexpr float DOGMA_BEAM_SPEEDUP = 0.02f; +constexpr float DOGMA_BEAM_STEP_MOST = 4; +constexpr float DOGMA_BEAM_STEP_LEAST = 2; +constexpr float DOGMA_BEAM_TURN = 10; +constexpr float DOGMA_BEAM_NEAR = 60; +constexpr int DOGMA_BEAM_TURN_AFTER = 15; +constexpr float DOGMA_BEAM_TURN_NEAR_SQUARED = 2500; +constexpr int DOGMA_BEAM_RESTART_FRAMES = 2; +constexpr int DOGMA_HIT_DISTORTION = 4; +constexpr float DOGMA_STATIC_VOLUME = 0.5f; +constexpr float DOGMA_GLOW_ATTACK = 2; +constexpr float DOGMA_GLOW_SHOT = 1; + +// Jacob's Ladder: three or four laser shots flung at 7 in random directions, three volleys before its Splat. +constexpr float DOGMA_ATTACK_FRICTION = 0.6f; +constexpr float DOGMA_JACOB_SPEED = 7; +constexpr float DOGMA_JACOB_SCALE = 1.5f; +constexpr float DOGMA_JACOB_FALL_ACCEL = -0.096f; +constexpr float DOGMA_JACOB_FALL = 3; +constexpr int DOGMA_JACOB_VOLLEYS = 3; +constexpr int DOGMA_JACOB_LOOP_FRAME = 6; +constexpr float DOGMA_CROSS_BELOW = 0.5f; + +// The cross: four arms of shots fanned 24 degrees apart, a volley every 5 frames for 25, the downward arm 1.5 faster, +// each volley slower by half; below a third of its health it may scream after. +constexpr int DOGMA_CROSS_EVERY = 5; +constexpr int DOGMA_CROSS_VOLLEYS = 5; +constexpr int DOGMA_CROSS_FRAMES = 25; +constexpr float DOGMA_CROSS_SPEED = 10; +constexpr float DOGMA_CROSS_SLOWER = 0.5f; +constexpr float DOGMA_CROSS_DOWN = 1.5f; +constexpr float DOGMA_CROSS_FAN = 24; +constexpr float DOGMA_CROSS_FALL_ACCEL = -0.098f; +constexpr float DOGMA_CROSS_FALL = -0.5f; +constexpr float DOGMA_CROSS_SHOT_VOLUME = 0.5f; +constexpr float DOGMA_SCREAM_BELOW = 0.33f; +constexpr int DOGMA_ARMS = 4; + +// Godhead: rings of eight shots at 7, offset an eighth turn every other ring, three rings (four below half health). +constexpr float DOGMA_GODHEAD_FALL_ACCEL = -0.08f; +constexpr float DOGMA_GODHEAD_SCALE = 2; +constexpr float DOGMA_GODHEAD_OFFSET = 0.3926991f; +static const Vector DOGMA_GODHEAD_RING = vector_make(7, 8); +constexpr int DOGMA_GODHEAD_RINGS = 3; +constexpr int DOGMA_GODHEAD_RINGS_HURT = 4; + +// The blackhole: thrown at 15 from 46 up, its swirls sown every 8 frames while it charges. +constexpr float DOGMA_BLACKHOLE_SPEED = 15; +static const Vector DOGMA_BLACKHOLE_OFFSET = vector_make(0, -46); +constexpr float DOGMA_BLACKHOLE_EVERY = 8; +constexpr float DOGMA_SWIRL_SCALE = 0.2f; +constexpr float DOGMA_SWIRL_WIDTH = 0.5f; +constexpr float DOGMA_BLACKHOLE_PITCH = 2; + +// The scream: for 15 frames a ring spreading 40 a frame turns its shots red and sends them curving at the player. +constexpr int DOGMA_SCREAM_FRAMES = 15; +constexpr int DOGMA_SCREAM_SHAKE = 4; +constexpr float DOGMA_SCREAM_SPREAD = 40; +constexpr ColorMod DOGMA_SCREAM_COLOR = {{1, 1, 1, 1}, {8, 0, 0, 0}, {0, 0, 0}}; +constexpr int DOGMA_SCREAM_FLASH = 12; +constexpr int DOGMA_SCREAM_SHOT = 1; +constexpr float DOGMA_SCREAM_SHOT_SPEED = 2; +constexpr float DOGMA_SCREAM_SHOT_HEIGHT = -27.5f; +constexpr float DOGMA_SCREAM_SHOT_FALL_ACCEL = -0.085f; +constexpr float DOGMA_SCREAM_SHOT_FALL = -1; +constexpr float DOGMA_SCREAM_SHOT_CURVE = -2; +constexpr int DOGMA_SCREAM_SHOT_DELAY = 20; +constexpr float DOGMA_SCREAM_SHOT_ACCEL = 0.85f; +constexpr float DOGMA_SCREAM_SHOCKWAVE = 0.02f; +constexpr uint64_t DOGMA_SCREAM_SHOT_FLAGS = PROJECTILE_CURVE_RIGHT | PROJECTILE_ACCELERATE | + PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT | + PROJECTILE_CHANGE_VELOCITY_AFTER_TIMEOUT; + +// The transition: what it fired fizzles, its cord bursts and it becomes the angel. +constexpr float DOGMA_TRANSITION_FRICTION = 0.5f; +constexpr int BIG_SPLASH_DOGMA = 1; +constexpr int BIG_SPLASH_DOGMA_ANGEL = 2; +constexpr float DOGMA_ANGEL_VOLUME = 0.6f; +constexpr int TECH_DOT_FADING = 1; +constexpr int DOGMA_LASER_END = 1; + +// 004aaef0 Sets every layer's distortion from the Distortion null, 3 more while its hit timer (i2) runs down. +static void dogma_distortion_update(Entity_NPC& npc) +{ + float distortion = 0; + AnimationState& anim = npc.sprite.overlayAnimState.isPlaying ? npc.sprite.overlayAnimState : npc.sprite.animState; + if (const NullFrame* null = anim.GetNullFrame("Distortion")) distortion = null->pos.x; + if (npc.i2 > 0) distortion += DOGMA_DISTORTION_HIT; + npc.i2 = std::max(npc.i2 - npc_ticks_get(npc), 0); + for (LayerState& layer : npc.sprite.layerStates) layer.color._colorize[0] = distortion; +} + +// Its cord: the first points follow its CordPos null, the last the TV under it, and it steps (half on an +// interpolation). It is laid out on the first frame the null shows. +static void dogma_cord_update(Entity_NPC& npc, bool isInterpolation) +{ + Vector anchor = npc.GetNullOffset("CordPos"); + std::deque& cord = npc.vectorDeque1; + if (!vector_is_zero(anchor) && cord.empty()) + { + for (int point = 0; point < DOGMA_CORD_POINTS; point++) + { + float along = (float)point / DOGMA_CORD_LAST; + float sway = std::sin((float)point * DOGMA_CORD_SWAY_STEP) * DOGMA_CORD_SWAY; + cord.push_back(vector_make(sway + (npc.targetPosition.x - DOGMA_CORD_TV_LEFT - npc.pos.x) * along + npc.pos.x, + (npc.targetPosition.y - npc.pos.y) * along + npc.pos.y)); + cord.push_back({}); + cord.push_back(vector_make(DOGMA_CORD_HANG, 0)); + } + npc.vectorDeque2 = cord; + } + + Vector tv = npc.parent ? vector_add(npc.parent->pos, vector_make(0, DOGMA_TV_DROP)) : npc.targetPosition; + if (!cord.empty()) + { + cord[0] = vector_make(anchor.x + npc.pos.x, npc.pos.y); + cord[1] = npc.velocity; + cord[2] = vector_make(anchor.y, 0); + cord[cord.size() - 3] = vector_make(tv.x - DOGMA_CORD_TV_LEFT, tv.y); + cord[cord.size() - 2] = {}; + cord[cord.size() - 1] = vector_make(DOGMA_CORD_HANG, 0); + npc.UpdateCordChain(isInterpolation); + } + + Vector toTv = vector_sub(tv, npc.pos); + float distance = vector_length(toTv); + if (distance > DOGMA_LEASH) + npc.velocity = vector_add(npc.velocity, vector_scale(toTv, (distance - DOGMA_LEASH) * DOGMA_LEASH_PULL * + npc.speedMultiplier / distance)); +} + +// Its pre-update and interpolation: a confirm skips a known Dogma's appearance, the distortion and glow fade, and the +// cord follows. +static void dogma_pre_update(Entity_NPC& npc) +{ + bool isInterpolation = npc.aiCallPhase == AI_PHASE_INTERPOLATE; + if (npc.state == DOGMA_APPEAR && input_is_action_triggered(ACTION_MENU_CONFIRM, -1, nullptr) && + g_manager->persistentGameData.GetBestiaryEncounterCount(ENTITY_DOGMA, 0) != 0) + npc.state = DOGMA_SKIPPED; + if (!isInterpolation) + { + dogma_distortion_update(npc); + float& glow = npc.sprite.GetLayer(DOGMA_DISTORTION_LAYER)->color._colorize[2]; + float step = npc.speedMultiplier * DOGMA_GLOW_FADE; + glow = std::abs(glow) <= step ? 0 : glow >= 0 ? glow - step : glow + step; + } + dogma_cord_update(npc, isInterpolation); +} + +// The room becomes Dogma's own: the doors gone, the static backdrop up, its walls down. +static void dogma_room_set(Room& room) +{ + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) room.RemoveDoor(slot); + room.descriptor->flags |= ROOM_DESCRIPTOR_FLAG_SACRIFICE_DONE; + room.descriptor->flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR; +} + +// Its first frame: spawned by the TV it appears, otherwise (from a room's layout) it fights at once under its own TV. +static void dogma_init(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.aiCallFlags = AI_CALL_PRE_UPDATE | AI_CALL_INTERPOLATE; + if (npc.spawnerType == 0) + { + Entity* tv = g_game->Spawn({.position = Room::GetCenterPos(), + .spawner = &npc, + .type = ENTITY_DOGMA, + .variant = DOGMA_TV, + .seed = npc.initSeed}); + tv->Update(); + tv->child = &npc; + npc.parent = tv; + npc.state = DOGMA_IDLE; + npc.sprite.Play("Idle"); + npc.sprite.PlayOverlay("Cord"); + npc.sprite.GetLayer(DOGMA_CORD_LAYER)->isVisible = false; + npc.flags = (npc.flags & ~FLAG_APPEAR) | DOGMA_FLAGS; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.projectileCooldown = DOGMA_FIRST_COOLDOWN; + npc.projectileDelay = -1; + dogma_room_set(room); + room.descriptor->flags |= ROOM_DESCRIPTOR_FLAG_NO_WALLS; + room.LoadBackdropGraphics(); + room.backdrop.load_details(); + g_game->SetColorModifier(DOGMA_ROOM_DARK, false, DOGMA_ROOM_DARK_RATE); + } + else + { + npc.state = DOGMA_APPEAR; + npc.sprite.Play("Appear"); + npc.sprite.PlayOverlay("Cord"); + npc.sprite.GetLayer(DOGMA_CORD_LAYER)->isVisible = false; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.flags = (npc.flags & ~FLAG_APPEAR) | DOGMA_FLAGS; + g_game->hud.isVisible = false; + } + npc.aiFloat = 0; + npc.splatColor = DOGMA_SPLAT_COLOR; +} + +// The room's edges ring with 30 pieces of debris, spread along the walls from the decoration seed and pushed out from +// the middle. +static void dogma_debris_spawn(Room& room) +{ + RNG rng = DOGMA_DEBRIS_SHIFTS; + rng._seed = room.descriptor ? room.descriptor->decorationSeed : 0; + float width = room.bottomRightPos.x - room.topLeftPos.x; + float height = room.bottomRightPos.y - room.topLeftPos.y; + float half = width + height; + float threeQuarters = width + half; + float perimeter = height + threeQuarters; + for (int piece = 0; piece < DOGMA_DEBRIS_COUNT; piece++) + { + float along = (rng.RandomFloat() + ((float)piece - HALF)) * perimeter / DOGMA_DEBRIS_SPACING; + Vector at = room.topLeftPos; + if (along <= width) at.x += along; + else if (along <= half) at = vector_make(at.x + width, along - width + at.y); + else if (along <= threeQuarters) at = vector_make(width - (along - half) + at.x, at.y + height); + else at.y = height - (along - threeQuarters) + at.y; + + Vector out = vector_sub(at, Room::GetCenterPos()); + float push = rng.RandomFloat() * DOGMA_DEBRIS_PUSH + DOGMA_DEBRIS_PUSH_LEAST; + float length = vector_length(out); + if (length > 0) out = vector_scale(out, push / length); + g_game->Spawn({.position = vector_add(at, out), .type = ENTITY_EFFECT, .variant = EFFECT_DOGMA_DEBRIS, .seed = rng.Next()}) + ->Update(); + } +} + +// Its scream on appearing: the living room is torn away (the TV and its carpet gone, the room swapped for Dogma's), +// the debris thrown, its cord, the players and itself moved by how far the TV was from the middle, and its own TV +// spawned there. +static void dogma_room_tear(Entity_NPC& npc, Room& room) +{ + Vector shift{}; + for (Entity* entity : std::vector(room.entityList.updateEL)) + { + if (entity->type == ENTITY_GENERIC_PROP) + { + if (entity->variant == PROP_TV) shift = vector_sub(Room::GetCenterPos(), entity->targetPosition); + entity->Remove(); + } + else if (entity->type == ENTITY_EFFECT && + (entity->variant == EFFECT_ISAACS_CARPET || entity->variant == EFFECT_CREEP_STATIC)) + entity->Remove(); + } + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) room.RemoveDoor(slot); + room.descriptor->data = g_game->roomConfig.GetRoomByStageTypeAndVariant(room.descriptor->data->stageId, ROOM_DEFAULT, + DOGMA_ROOM_VARIANT, ROOM_MODE_CURRENT); + dogma_debris_spawn(room); + + if (!npc.vectorDeque1.empty()) + for (size_t i = 0; i < DOGMA_CORD_POINTS * CORD_STRIDE; i += CORD_STRIDE) + { + npc.vectorDeque1[i] = vector_add(npc.vectorDeque1[i], shift); + npc.vectorDeque2[i] = vector_add(npc.vectorDeque2[i], shift); + } + + for (Entity_Player* player : g_game->playerManager.playerList) + { + Vector away = vector_sub(player->pos, npc.pos); + float distance = vector_length(away); + if (distance < DOGMA_PLAYER_ROOM) + { + if (distance > 0) away = vector_scale(away, DOGMA_PLAYER_ROOM / distance); + player->pos = vector_add(away, npc.pos); + } + player->Teleport(room.GetClampedPositionImpl(vector_add(player->pos, shift), 0, 0, 0, 0), false, false); + } + + Entity* tv = g_game->Spawn({.position = Room::GetCenterPos(), + .spawner = &npc, + .type = ENTITY_DOGMA, + .variant = DOGMA_TV, + .seed = npc.initSeed}); + tv->Update(); + tv->child = &npc; + npc.parent = tv; + npc.pos = vector_add(npc.pos, shift); +} + +// The fight begins: the players move again, the boss music and HUD return. +static void dogma_fight_begin() +{ + for (Entity_Player* player : g_game->playerManager.playerList) player->isControlsEnabled = true; + g_game->room->PlayMusic(); + g_game->hud.isVisible = true; +} + +// Its appearance out of the TV: the splat and static, its scream flashing the room, then the room torn away. Once +// the animation ends the boss intro shows; a skipped appearance does it all at once and fights at once. +static void dogma_appear(Entity_NPC& npc, Room& room) +{ + npc.friction *= DOGMA_APPEAR_FRICTION; + if (npc.sprite.IsEventTriggered("Splat")) + { + Entity_Effect* creep = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_STATIC, .seed = Random()})); + creep->AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + creep->sprite.scale = vector_make(DOGMA_STATIC_SCALE, DOGMA_STATIC_SCALE); + creep->timeout = DOGMA_STATIC_FRAMES; + creep->lifespan = DOGMA_STATIC_FRAMES; + creep->Update(); + g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = BIG_SPLASH_DOGMA, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_SPLASH, + .seed = Random()}) + ->Update(); + } + + bool isSkipped = npc.state == DOGMA_SKIPPED; + if (npc.sprite.IsEventTriggered("Sound") || isSkipped) + { + if (!isSkipped) + { + npc.PlaySound(SOUND_DOGMA_APPEAR_SCREAM, 1, 2, false, 1); + shockwave_make(npc.pos, DOGMA_SHOCKWAVE_AMPLITUDE, DOGMA_SHOCKWAVE_SPEED, DOGMA_SHOCKWAVE_FRAMES); + } + g_game->SetColorModifier(DOGMA_ROOM_FLASH, !isSkipped, isSkipped ? DOGMA_ROOM_DARK_RATE : DOGMA_ROOM_DARK_FAST); + } + if (npc.sprite.WasEventTriggered("Sound")) game_shake_screen(DOGMA_APPEAR_SHAKE); + if (npc.sprite.IsEventTriggered("Shoot") || isSkipped) + { + room.descriptor->flags |= ROOM_DESCRIPTOR_FLAG_SACRIFICE_DONE; + room.descriptor->flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR; + room.LoadBackdropGraphics(); + room.backdrop.load_details(); + dogma_room_tear(npc, room); + } + + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) + { + if (!isSkipped) + { + room.camera->SetFocusPosition(npc.pos); + return; + } + dogma_fight_begin(); + } + else if (isSkipped) dogma_fight_begin(); + else g_game->roomTransition.StartBossIntro(DOGMA_INTRO_BOSS, 0); + + npc.entityCollisionClass = ENTCOLL_ALL; + npc.state = DOGMA_IDLE; + npc.sprite.Play("Idle"); + npc.projectileCooldown = DOGMA_FIGHT_COOLDOWN; + g_game->SetColorModifier(DOGMA_ROOM_DARK, true, DOGMA_ROOM_DARK_FAST); + room.camera->SnapToPosition(g_game->playerManager.players_center_position(CENTER_FRESH)); + room.descriptor->flags |= ROOM_DESCRIPTOR_FLAG_NO_WALLS; +} + +// Starts an attack, facing the player for its Brimstone, and rolls the next cooldown. +static void dogma_attack_start(Entity_NPC& npc, int attack) +{ + Entity* player = npc.GetPlayerTarget(); + switch (attack) + { + case DOGMA_ATTACK_BRIMSTONE: + { + Vector toPlayer = vector_sub(player->pos, npc.pos); + int direction; + if (std::abs(toPlayer.x) <= std::abs(toPlayer.y)) + { + direction = toPlayer.y >= 0 ? DOGMA_FACE_DOWN : DOGMA_FACE_UP; + npc.sprite.Play(direction == DOGMA_FACE_DOWN ? "BrimstoneStartDown" : "BrimstoneStartUp"); + } + else + { + direction = toPlayer.x >= 0 ? DOGMA_FACE_RIGHT : DOGMA_FACE_LEFT; + npc.sprite.Play("BrimstoneStartRight"); + npc.sprite.isFlipX = direction == DOGMA_FACE_LEFT; + } + npc.i1 = direction; + npc.v2.x = 0; + npc.state = DOGMA_BRIMSTONE; + npc.PlaySound(SOUND_DOGMA_BRIMSTONE_CHARGE, 1, 2, false, 1); + npc.sprite.GetLayer(DOGMA_DISTORTION_LAYER)->color._colorize[2] = DOGMA_GLOW_ATTACK; + npc.projectileCooldown = 20; + break; + } + case DOGMA_ATTACK_JACOB: + npc.sprite.Play("JacobAttack"); + npc.state = DOGMA_JACOB; + npc.projectileCooldown = 40; + break; + case DOGMA_ATTACK_CROSS: + npc.sprite.Play("CrossStart"); + npc.state = DOGMA_CROSS; + npc.projectileCooldown = 5; + break; + case DOGMA_ATTACK_GODHEAD: + npc.sprite.Play("GodheadStart"); + npc.state = DOGMA_GODHEAD; + npc.projectileCooldown = 60; + break; + case DOGMA_ATTACK_BLACKHOLE: + npc.sprite.Play("BlackholeAttack"); + npc.state = DOGMA_BLACKHOLE; + npc.projectileCooldown = 150; + npc.sprite.isFlipX = player->pos.x < npc.pos.x; + npc.PlaySound(SOUND_DOGMA_BLACKHOLE_CHARGE, 1, 2, false, DOGMA_BLACKHOLE_PITCH); + break; + } + npc.v1 = npc.pos; + npc.stateFrame = 0; + npc.projectileCooldown += (int)(Random() % DOGMA_COOLDOWN_RANGE); +} + +// Idle: it drifts toward its target, sliding around the side of the TV in its way, and attacks when its cooldown +// runs out. +static void dogma_idle(Entity_NPC& npc) +{ + npc.friction *= DOGMA_DRIFT_FRICTION; + Entity& tv = *npc.parent; + Vector toTarget = vector_sub(npc.CalcTargetPosition(0), npc.pos); + Vector toTv = vector_sub(tv.pos, npc.pos); + Vector targetSide = vector_normalized(vector_rotated(toTarget, RIGHT_ANGLE_DEGREES)); + Vector tvSide = vector_normalized(vector_rotated(toTv, RIGHT_ANGLE_DEGREES)); + float tvReach = std::max(tv.sizeMulti.x, tv.sizeMulti.y) * tv.size + npc.size; + float settle = DOGMA_DRIFT; + if (vector_dot(toTv, toTarget) > 0 && std::abs(vector_dot(toTv, targetSide)) <= tvReach) + { + npc.AddVelocity_divided(vector_resized(vector_scale(tvSide, vector_dot(tvSide, toTarget)), npc.aiFloat), false); + settle = DOGMA_DRIFT_SIDE; + } + else npc.AddVelocity_divided(vector_resized(toTarget, npc.aiFloat), false); + if (npc.entityRef) settle = DOGMA_DRIFT_HOLDING; + npc.aiFloat = (npc.aiFloat - settle) * timescale_factor(DOGMA_DRIFT_SETTLE, npc.speedMultiplier) + settle; + + if (npc.projectileCooldown < 1) return; + npc.projectileCooldown -= npc_ticks_get(npc); + if (npc.projectileCooldown <= 0) dogma_attack_start(npc, (int)(Random() & 3)); +} + +// The Brimstone's beam fired along its direction (refired on a turn), aimed at least 100 out toward the player. +static void dogma_beam_fire(Entity_NPC& npc, Vector mouth, Vector playerPos) +{ + Vector direction = vector_from_direction(npc.i1); + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = mouth, + .posOffset = vector_make(0, DOGMA_BEAM_HEIGHT), + .source = &npc, + .angleDegrees = vector_angle(direction), + .timeout = std::max(DOGMA_BRIMSTONE_FRAMES - npc.stateFrame, 0) + + DOGMA_BEAM_TAIL, + .variant = LASER_THICK_RED}); + laser->renderDepthOffset = npc.i1 == DOGMA_FACE_UP ? DOGMA_BEAM_DEPTH_UP : DOGMA_BEAM_DEPTH; + float reach = std::max(vector_dot(vector_sub(playerPos, mouth), direction), DOGMA_BEAM_REACH_LEAST); + npc.targetPosition = vector_add(mouth, vector_scale(direction, reach)); + laser->isDisableInitSound = true; + if (npc.stateFrame < 1) + { + npc.PlaySound(SOUND_DOGMA_BRIMSTONE_SHOOT, 1, 2, false, 1); + game_shake_screen(DOGMA_BEAM_SHAKE); + } + else npc.targetPosition = vector_add(npc.targetPosition, vector_scale(vector_sub(playerPos, npc.targetPosition), DOGMA_BEAM_SWEEP)); + laser->targetPosition = npc.targetPosition; + laser->tearFlags = TearFlags().set(TEAR_OCCULT); + laser->Update(); + npc.child = laser; + npc.sprite.Play(npc.i1 == DOGMA_FACE_DOWN ? "BrimstoneLoopDown" : npc.i1 == DOGMA_FACE_UP ? "BrimstoneLoopUp" : "BrimstoneLoopRight"); + if (npc.stateFrame == 0) npc.stateFrame = 1; +} + +// The beam sweeps toward the player, turning at most 10 degrees a frame and never nearer than 60, and after 15 frames +// it may break off to refire toward the player's side. +static void dogma_beam_sweep(Entity_NPC& npc, Vector mouth, Vector playerPos, float ramp) +{ + if (npc.v2.x < 1) npc.v2.x = std::min(npc.v2.x + npc.speedMultiplier * DOGMA_BEAM_SPEEDUP, 1.0f); + Vector step = vector_scale(vector_sub(playerPos, npc.targetPosition), DOGMA_BEAM_SWEEP * npc.v2.x); + float length = vector_length(step); + if (length > DOGMA_BEAM_STEP_MOST) step = vector_scale(step, DOGMA_BEAM_STEP_MOST / length); + else if (length < DOGMA_BEAM_STEP_LEAST && length > 0) step = vector_scale(step, DOGMA_BEAM_STEP_LEAST / length); + Vector aim = vector_add(npc.targetPosition, vector_scale(step, ramp * npc.speedMultiplier)); + + Vector reach = vector_sub(aim, mouth); + float turn = normalize_angle_degrees(vector_angle(reach) - vector_angle(vector_sub(npc.targetPosition, mouth))); + if (std::abs(turn) > DOGMA_BEAM_TURN) aim = vector_add(vector_rotated(reach, DOGMA_BEAM_TURN - turn), mouth); + npc.targetPosition = aim; + if (vector_length_squared(vector_sub(aim, mouth)) < DOGMA_BEAM_NEAR * DOGMA_BEAM_NEAR) + npc.targetPosition = vector_add(mouth, vector_resized(vector_sub(aim, mouth), DOGMA_BEAM_NEAR)); + npc.child->targetPosition = npc.targetPosition; + if (npc.stateFrame <= DOGMA_BEAM_TURN_AFTER) return; + + int facing = (int)vector_to_direction(vector_sub(playerPos, mouth)); + if (facing == npc.i1 || + ((Random() & 3) != 0 && + vector_length_squared(vector_sub(playerPos, npc.targetPosition)) >= DOGMA_BEAM_TURN_NEAR_SQUARED)) + return; + npc.child->Remove(); + npc.i1 = facing; + if (facing == DOGMA_FACE_DOWN) npc.sprite.Play("BrimstoneStartDown"); + else if (facing == DOGMA_FACE_UP) npc.sprite.Play("BrimstoneStartUp"); + else + { + npc.sprite.Play("BrimstoneStartRight"); + npc.sprite.isFlipX = npc.i1 == DOGMA_FACE_LEFT; + } + npc.sprite.SetFrame((float)(npc.sprite.animState.GetAnimationLength() - DOGMA_BEAM_RESTART_FRAMES)); + npc.i2 = DOGMA_HIT_DISTORTION; + npc.PlaySound(SOUND_STATIC, DOGMA_STATIC_VOLUME, 2, false, 1); + npc.v2.x = 0; +} + +// The Brimstone: 90 frames of a beam from its mouth that follows the player, then its end. +static void dogma_brimstone(Entity_NPC& npc) +{ + npc.friction *= DOGMA_APPEAR_FRICTION; + if (npc.stateFrame > 0) npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame >= DOGMA_BRIMSTONE_FRAMES) + { + if (npc.sprite.animState.IsLoopingAnimation()) + npc.sprite.Play(npc.i1 == DOGMA_FACE_DOWN || npc.i1 == DOGMA_FACE_UP ? "BrimstoneEndDown" : "BrimstoneEndRight"); + if (npc.sprite.IsFinished()) + { + npc.sprite.Play("Idle"); + npc.sprite.isFlipX = false; + npc.state = DOGMA_IDLE; + } + return; + } + + Vector playerPos = npc.GetPlayerTarget()->pos; + Vector mouth = vector_add(npc.pos, vector_make(0, DOGMA_MOUTH_HEIGHT)); + float ramp = std::min((float)npc.stateFrame / DOGMA_BEAM_RAMP, 1.0f); + if (npc.sprite.IsEventTriggered("Shoot")) dogma_beam_fire(npc, mouth, playerPos); + if (npc.child && npc.child->type == ENTITY_LASER) dogma_beam_sweep(npc, mouth, playerPos, ramp); +} + +// Jacob's Ladder: volleys of laser shots flung about it. After its Splat it loops until three volleys are out, and +// below half the TV's health it may go on into the cross. +static void dogma_jacob(Entity_NPC& npc, float tvHealth) +{ + npc.friction *= DOGMA_ATTACK_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_DOGMA_JACOBS, 1, 2, false, 1); + npc.sprite.GetLayer(DOGMA_DISTORTION_LAYER)->color._colorize[2] = DOGMA_GLOW_SHOT; + for (int shot = (int)(Random() & 1) + 3; shot != 0; shot--) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector velocity = vector_make(std::cos(angle) * DOGMA_JACOB_SPEED, std::sin(angle) * DOGMA_JACOB_SPEED); + ProjectileParams params; + params.bulletFlags = PROJECTILE_LASER_SHOT; + params.scale = DOGMA_JACOB_SCALE; + params.fallingAccelModifier = DOGMA_JACOB_FALL_ACCEL; + params.fallingSpeedModifier = random_unit() * DOGMA_JACOB_FALL; + npc.FireProjectiles(npc.pos, velocity, PROJECTILES_SINGLE, params); + } + npc.stateFrame++; + } + + int next = DOGMA_ATTACK_NONE; + if (npc.sprite.IsEventTriggered("Splat")) + { + if (npc.stateFrame < DOGMA_JACOB_VOLLEYS) npc.sprite.SetFrame((float)DOGMA_JACOB_LOOP_FRAME); + else if (tvHealth < DOGMA_CROSS_BELOW && (Random() & 1) == 0) next = DOGMA_ATTACK_CROSS; + } + if (npc.sprite.IsFinished()) + { + npc.sprite.Play("Idle"); + npc.state = DOGMA_IDLE; + } + if (next != DOGMA_ATTACK_NONE) dogma_attack_start(npc, next); +} + +// One volley of the cross: four arms of shots, each wider and slower than the last. +static void dogma_cross_volley(Entity_NPC& npc, int volley) +{ + float speed = DOGMA_CROSS_SPEED - (float)volley * DOGMA_CROSS_SLOWER; + npc.PlaySound(SOUND_THUMBS_DOWN, DOGMA_CROSS_SHOT_VOLUME, 2, false, 1); + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + ProjectileParams params; + params.fallingAccelModifier = DOGMA_CROSS_FALL_ACCEL; + params.fallingSpeedModifier = DOGMA_CROSS_FALL; + for (int arm = 0; arm < DOGMA_ARMS; arm++) + { + Vector velocity = vector_scale(vector_from_direction(arm), speed); + if (arm == DOGMA_FACE_DOWN) velocity = vector_scale(velocity, DOGMA_CROSS_DOWN); + float middle = (float)(volley - 1) * HALF; + for (int shot = 0; shot < volley; shot++) + npc.FireProjectiles(npc.pos, vector_rotated(velocity, ((float)shot - middle) * DOGMA_CROSS_FAN), + PROJECTILES_SINGLE, params); + } +} + +// The cross: it holds its spot while its volleys go out every 5 frames, then ends (or screams, below a third of the +// TV's health half the time). +static void dogma_cross(Entity_NPC& npc, float tvHealth) +{ + npc.friction *= DOGMA_ATTACK_FRICTION; + npc.velocity = vector_sub(npc.v1, npc.pos); + if (npc.stateFrame > 0) + for (int tick = 0; tick < npc_ticks_get(npc); tick++) + { + int volley = (npc.stateFrame - 1) / DOGMA_CROSS_EVERY; + if ((npc.stateFrame - 1) % DOGMA_CROSS_EVERY == 0 && volley < DOGMA_CROSS_VOLLEYS) dogma_cross_volley(npc, volley); + if (++npc.stateFrame > DOGMA_CROSS_FRAMES) + { + if (tvHealth >= DOGMA_SCREAM_BELOW || (Random() & 1) != 0) npc.sprite.Play("CrossEnd"); + else + { + npc.sprite.Play("Scream"); + npc.state = DOGMA_SCREAM; + } + npc.stateFrame = -1; + break; + } + } + if (npc.sprite.IsEventTriggered("Shoot")) npc.stateFrame = 1; + if (!npc.sprite.IsFinished()) return; + if (npc.stateFrame < 1) + { + npc.sprite.Play("Idle"); + npc.state = DOGMA_IDLE; + } + else npc.sprite.Play("CrossLoop"); +} + +// Godhead: rings of homing light shots, three (four below half the TV's health). +static void dogma_godhead(Entity_NPC& npc, float tvHealth) +{ + npc.friction *= DOGMA_ATTACK_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_DOGMA_GODHEAD, 1, 2, false, 1); + npc.sprite.GetLayer(DOGMA_DISTORTION_LAYER)->color._colorize[2] = DOGMA_GLOW_SHOT; + npc.GetPlayerTarget(); + Random(); + ProjectileParams params; + params.fallingAccelModifier = DOGMA_GODHEAD_FALL_ACCEL; + params.scale = DOGMA_GODHEAD_SCALE; + params.circleAngle = (npc.stateFrame & 1) != 0 ? 0 : DOGMA_GODHEAD_OFFSET; + params.bulletFlags = PROJECTILE_GODHEAD; + npc.FireProjectiles(npc.pos, DOGMA_GODHEAD_RING, PROJECTILES_RING, params); + } + if (!npc.sprite.IsFinished()) return; + + int rings = tvHealth < DOGMA_CROSS_BELOW ? DOGMA_GODHEAD_RINGS_HURT : DOGMA_GODHEAD_RINGS; + if (npc.stateFrame == -1) + { + npc.sprite.Play("Idle"); + npc.state = DOGMA_IDLE; + } + else if (npc.stateFrame < rings) + { + npc.sprite.Play("GodheadShoot", PLAY_FORCED); + npc.stateFrame++; + } + else + { + npc.sprite.Play("GodheadEnd"); + npc.stateFrame = -1; + } +} + +// The blackhole: thrown at the player and held (entityRef) while its swirls gather. +static void dogma_blackhole(Entity_NPC& npc) +{ + npc.friction *= DOGMA_ATTACK_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_DOGMA_BLACKHOLE_SHOOT, 1, 2, false, 1); + g_manager->sfxManager.Stop(SOUND_DOGMA_BLACKHOLE_CHARGE); + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.sprite.isFlipX = aim.x < 0; + Entity* hole = g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(aim, DOGMA_BLACKHOLE_SPEED), + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_DOGMA_BLACKHOLE, + .seed = Random()}); + hole->Update(); + hole->posOffset = DOGMA_BLACKHOLE_OFFSET; + npc.SetRef_bec(hole); + } + if (npc.sprite.WasEventTriggered("Sound") && !npc.sprite.WasEventTriggered("Splat") && + npc.GetIntervalTicks(DOGMA_BLACKHOLE_EVERY, 0) != 0) + { + Entity* swirl = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = BLACKHOLE_SPARK, + .type = ENTITY_EFFECT, + .variant = EFFECT_DOGMA_BLACKHOLE, + .seed = Random()}); + swirl->Update(); + float height = random_unit() * DOGMA_SWIRL_SCALE + DOGMA_SWIRL_SCALE; + swirl->posOffset = DOGMA_BLACKHOLE_OFFSET; + swirl->sprite.scale = vector_make(random_unit() * DOGMA_SWIRL_SCALE + DOGMA_SWIRL_WIDTH, height); + } + if (npc.sprite.IsFinished()) + { + npc.sprite.Play("Idle"); + npc.state = DOGMA_IDLE; + npc.sprite.isFlipX = false; + } +} + +// A shot its scream reaches turns red and curves away, accelerating, then after 20 frames it turns on the player. +static void dogma_scream_shot_turn(Entity_NPC& npc, Entity_Projectile& shot) +{ + shot.subtype = DOGMA_SCREAM_SHOT; + shot.SetColor(DOGMA_SCREAM_COLOR, DOGMA_SCREAM_FLASH, COLOR_PRIORITY_DEFAULT, true, true); + uint64_t flags = shot.projectileFlags; + shot.changeFlags = flags & ~PROJECTILE_ACCELERATE; + shot.changeVelocity = DOGMA_SCREAM_SHOT_SPEED; + shot.height = DOGMA_SCREAM_SHOT_HEIGHT; + shot.fallingAccel = DOGMA_SCREAM_SHOT_FALL_ACCEL; + shot.fallingSpeed = DOGMA_SCREAM_SHOT_FALL; + shot.curvingStrength = DOGMA_SCREAM_SHOT_CURVE; + shot.projectileFlags = flags | DOGMA_SCREAM_SHOT_FLAGS; + shot.changeTimeout = (int)shot.updateTime + DOGMA_SCREAM_SHOT_DELAY; + shot.target = npc.GetPlayerTarget(); + shot.acceleration = DOGMA_SCREAM_SHOT_ACCEL; + npc.i1++; +} + +// The scream: from its Shoot, a ring spreading 40 a frame turns its shots for 15 frames. +static void dogma_scream(Entity_NPC& npc) +{ + if ((uint32_t)npc.stateFrame < DOGMA_SCREAM_FRAMES) + { + game_shake_screen(DOGMA_SCREAM_SHAKE); + npc.v2.x += npc.speedMultiplier * DOGMA_SCREAM_SPREAD; + npc.CalcTargetPosition(0); + for (Entity* entity : std::vector(g_game->room->entityList.updateEL)) + if (entity && entity->type == ENTITY_PROJECTILE && entity->spawnerType == ENTITY_DOGMA && entity->subtype == 0 && + vector_length_squared(vector_sub(npc.pos, entity->pos)) <= npc.v2.x * npc.v2.x) + dogma_scream_shot_turn(npc, *static_cast(entity)); + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.stateFrame = 0; + npc.v2.x = 0; + shockwave_make(npc.pos, DOGMA_SCREAM_SHOCKWAVE, DOGMA_SHOCKWAVE_SPEED, DOGMA_SHOCKWAVE_FRAMES); + npc.i1 = 0; + npc.PlaySound(SOUND_DOGMA_SCREAM, 1, 2, false, 1); + } + if (npc.sprite.IsFinished()) + { + npc.sprite.Play("Idle"); + npc.state = DOGMA_IDLE; + } +} + +// What Dogma fired fizzles out: its shots fall, its lasers end, its dots fade and its blackhole fizzles. +static void dogma_shots_fizzle(Room& room) +{ + for (Entity* entity : room.entityList.updateEL) + { + if (entity->spawnerType != ENTITY_DOGMA) continue; + if (entity->type == ENTITY_PROJECTILE) + { + static_cast(entity)->projectileFlags = 0; + entity->isDead = true; + } + else if (entity->type == ENTITY_LASER) static_cast(entity)->timeout = DOGMA_LASER_END; + else if (entity->type == ENTITY_EFFECT) + { + auto* effect = static_cast(entity); + if (effect->variant == EFFECT_TECH_DOT) effect->state = TECH_DOT_FADING; + else if (effect->variant == EFFECT_DOGMA_BLACKHOLE && effect->subtype == 0) + { + effect->state = BLACKHOLE_CLOSING; + effect->sprite.Play("Fizzle"); + } + else continue; + entity->isDead = true; + } + } +} + +// The transition once the TV breaks: what it fired fizzles and its cord bursts in poofs, it splats, and it becomes the +// angel. +static void dogma_transition(Entity_NPC& npc, Room& room) +{ + room.camera->SetFocusPosition(npc.pos); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.friction *= DOGMA_TRANSITION_FRICTION; + if (npc.sprite.IsEventTriggered("Sound")) + { + dogma_shots_fizzle(room); + for (size_t i = 0; i < npc.vectorDeque1.size(); i += CORD_STRIDE) + { + float height = npc.vectorDeque1[i + 2].x; + Entity* poof = g_game->Spawn( + {.position = npc.vectorDeque1[i], .type = ENTITY_EFFECT, .variant = EFFECT_BULLET_POOF_STATIC, .seed = Random()}); + poof->sprite.offset = vector_make(0, height); + } + npc.vectorDeque1.clear(); + npc.vectorDeque2.clear(); + npc.PlaySound(SOUND_DEATH_BURST_SMALL, 1, 2, false, 1); + } + npc.sprite.IsEventTriggered("Shoot"); + if (npc.sprite.IsEventTriggered("Splat")) + { + g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = BIG_SPLASH_DOGMA_ANGEL, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_SPLASH, + .seed = Random()}) + ->Update(); + npc.PlaySound(SOUND_MEATHEADSHOOT, 1, 2, false, 1); + } + if (npc.sprite.IsFinished()) + { + npc.Morph(ENTITY_DOGMA, DOGMA_ANGEL, 0, -1); + npc.sprite.Play("Appear"); + npc.PlaySound(SOUND_DOGMA_ANGEL_TRANSFORM, DOGMA_ANGEL_VOLUME, 2, false, 1); + } +} + +// 004aafa0 Dogma (950.0): it climbs out of the TV and tears the living room away, then fights tethered to its TV with +// Brimstone, Jacob's Ladder, the cross, Godhead, its blackhole and its scream, leaving static behind. Once the TV +// breaks it becomes the angel. +static void dogma_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE || npc.aiCallPhase == AI_PHASE_INTERPOLATE) return dogma_pre_update(npc); + + Room& room = *g_game->room; + float tvHealth = npc.parent ? npc.parent->health / npc.parent->maxHitPoints : 1; + if (!npc.parent && npc.state != NPC_STATE_INIT && npc.state != DOGMA_TRANSITION && npc.state != DOGMA_APPEAR && + npc.state != DOGMA_SKIPPED) + { + npc.state = DOGMA_TRANSITION; + npc.sprite.Play("Transition"); + } + switch (npc.state) + { + case NPC_STATE_INIT: + dogma_init(npc); + break; + case DOGMA_APPEAR: + case DOGMA_SKIPPED: + dogma_appear(npc, room); + break; + case DOGMA_IDLE: + dogma_idle(npc); + break; + case DOGMA_BRIMSTONE: + dogma_brimstone(npc); + break; + case DOGMA_JACOB: + dogma_jacob(npc, tvHealth); + break; + case DOGMA_CROSS: + dogma_cross(npc, tvHealth); + break; + case DOGMA_GODHEAD: + dogma_godhead(npc, tvHealth); + break; + case DOGMA_BLACKHOLE: + dogma_blackhole(npc); + break; + case DOGMA_SCREAM: + dogma_scream(npc); + break; + case DOGMA_TRANSITION: + dogma_transition(npc, room); + break; + } + + if (npc.state != DOGMA_APPEAR && npc.GetIntervalTicks(DOGMA_STATIC_EVERY, (float)(npc.index % DOGMA_STATIC_EVERY)) != 0) + { + auto* creep = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_STATIC, .seed = Random()})); + float scale = random_unit() + DOGMA_TRAIL_SCALE_LEAST; + creep->timeout = DOGMA_TRAIL_FRAMES; + creep->lifespan = DOGMA_TRAIL_FRAMES; + creep->sprite.scale = vector_make(scale, scale); + creep->Update(); + } +} + +// The TV's states: standing in the room's middle, and destroyed once its health runs out. +constexpr int DOGMA_TV_IDLE = NPC_STATE_IDLE; +constexpr int DOGMA_TV_DESTROYED = NPC_STATE_SPECIAL; +constexpr float DOGMA_TV_SINK = 20; +constexpr float DOGMA_TV_DEPTH = -500; +constexpr ColorMod DOGMA_TV_BLAST_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; +constexpr ColorMod DOGMA_TV_DUST_COLOR = {{0.4f, 0.4f, 0.4f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float DOGMA_TV_BLAST_DEPTH = 50; +static const Vector DOGMA_TV_DUST_RISE = vector_make(0, -2); +constexpr float DOGMA_TV_DUST_TURN = 10; +constexpr float DOGMA_TV_DUST_TURN_LEAST = 2; +constexpr int DOGMA_TV_DUST_FRAMES = 15; + +// The TV breaks: a white blast and dust, and Dogma turns into the angel. +static void dogma_tv_break(Entity_NPC& npc) +{ + Entity* blast = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + blast->SetColor(DOGMA_TV_BLAST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + blast->renderDepthOffset = DOGMA_TV_BLAST_DEPTH; + blast->Update(); + + auto* dust = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = DOGMA_TV_DUST_RISE, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = Random()})); + dust->rotation = random_unit() * DOGMA_TV_DUST_TURN + DOGMA_TV_DUST_TURN_LEAST; + int frames = (int)(Random() % DOGMA_TV_DUST_FRAMES) + DOGMA_TV_DUST_FRAMES; + dust->timeout = frames; + dust->lifespan = frames; + dust->SetColor(DOGMA_TV_DUST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + dust->renderDepthOffset = DOGMA_TV_BLAST_DEPTH; + dust->Update(); + + npc.PlaySound(SOUND_DOGMA_TV_BREAK, 1, 2, false, 1); + Entity_NPC* dogma = npc.ChildNPC(); + if (dogma && dogma->state != DOGMA_TRANSITION) + { + dogma->state = DOGMA_TRANSITION; + dogma->sprite.Play("Transition"); + } +} + +// 004b0a30 Dogma's TV (950.1): it holds its spot until its health runs out, then breaks in its Destroyed animation +// (its death kept off) and the fight's boss death triggers once Dogma is gone. +static void dogma_tv_update(Entity_NPC& npc) +{ + if (npc.isDead && npc.state != DOGMA_TV_DESTROYED) + { + npc.isDead = false; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.RemoveStatusEffects(); + npc.flags |= DOGMA_FLAGS; + npc.state = DOGMA_TV_DESTROYED; + npc.sprite.Play("Destroyed"); + } + switch (npc.state) + { + case NPC_STATE_INIT: + npc.flags = (npc.flags & ~FLAG_APPEAR) | FLAG_NO_KNOCKBACK | FLAG_NO_PHYSICS_KNOCKBACK; + npc.targetPosition = npc.pos; + npc.state = DOGMA_TV_IDLE; + npc.sprite.Play("Idle"); + npc.posOffset.y = DOGMA_TV_SINK; + npc.renderDepthOffset = DOGMA_TV_DEPTH; + break; + case DOGMA_TV_IDLE: + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + break; + case DOGMA_TV_DESTROYED: + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Shoot")) dogma_tv_break(npc); + if (npc.ChildNPC() || npc.HasEntityFlags(FLAG_BOSSDEATH_TRIGGERED)) break; + g_game->room->TriggerBossDeath(npc); + npc.isCanShutDoors = false; + break; + } +} + +// The angel's states: the transformation, drifting about the player, the feather spread (after a nuke too), the nuke +// and the ring, and its death. +constexpr int DOGMA_ANGEL_IDLE = NPC_STATE_IDLE; +constexpr int DOGMA_ANGEL_SPREAD = NPC_STATE_ATTACK; +constexpr int DOGMA_ANGEL_NUKE = NPC_STATE_ATTACK2; +constexpr int DOGMA_ANGEL_RING = NPC_STATE_ATTACK3; +constexpr int DOGMA_ANGEL_NUKE_THROW = NPC_STATE_SUMMON; +constexpr int DOGMA_ANGEL_TRANSFORM = NPC_STATE_SPECIAL; +constexpr int DOGMA_ANGEL_DYING = NPC_STATE_DEATH; + +// Its glitching below a quarter of its health: a random Glitch overlay with only its glitch layer shown, for 3 to 6 +// frames. +constexpr int DOGMA_ANGEL_GLITCH_LAYER = 5; +constexpr float DOGMA_ANGEL_GLITCH_BELOW = 0.25f; +constexpr float DOGMA_ANGEL_GLITCH_ODDS = 0.02f; +constexpr float DOGMA_ANGEL_GLITCH_ODDS_FALL = 0.06f; +constexpr int DOGMA_ANGEL_GLITCH_FRAMES = 3; +constexpr std::array DOGMA_ANGEL_GLITCHES = {"Glitch0", "Glitch1", "Glitch2", "Glitch3"}; + +// Its death: the boss overlay, the music's second layer, then the controls off and the jingle while the sounds hush. +constexpr int BOSS_OVERLAY_DOGMA_DYING = 2; +constexpr int BOSS_OVERLAY_DOGMA_DEAD = 3; +constexpr int DOGMA_MUSIC_DEATH_LAYER = 1; +constexpr float DOGMA_JINGLE_FADE = 0.5f; +constexpr float DOGMA_DEATH_HUSH = -10; +constexpr float DOGMA_DEATH_HUSH_STEP = 0.005f; + +// Its drift: a figure eight 280 by 110 about its target, pushed 1.5 toward it. +constexpr float DOGMA_ANGEL_FRICTION = 0.75f; +constexpr float DOGMA_ANGEL_EIGHT_SPEED = 0.03f; +constexpr float DOGMA_ANGEL_EIGHT_WIDTH = 280; +constexpr float DOGMA_ANGEL_EIGHT_HEIGHT = 220 * HALF; +constexpr float DOGMA_ANGEL_DRIFT = 1.5f; +constexpr float DOGMA_ANGEL_SPREAD_REACH = 240; +constexpr float DOGMA_ANGEL_ROOM_MARGIN = 80; +constexpr uint32_t DOGMA_ANGEL_SPECIAL_ODDS = 30; +constexpr int DOGMA_ANGEL_REST = 90; +constexpr int DOGMA_ANGEL_LONG_REST = 140; +constexpr int DOGMA_ANGEL_REST_RANGE = 30; + +// The spread: a cone of 14 fast feathers and a wider one of 14 slow ones toward the player, within 45 degrees of its +// facing, and a recoil of 5 decaying by 0.8. +constexpr float DOGMA_ANGEL_SPREAD_FRICTION = 0.7f; +constexpr float DOGMA_ANGEL_SPREAD_TURN = 45; +constexpr float DOGMA_ANGEL_RECOIL = 5; +constexpr float DOGMA_ANGEL_RECOIL_DECAY = 0.8f; +constexpr int DOGMA_ANGEL_FEATHERS = 14; +constexpr float DOGMA_ANGEL_FAST_CONE = 20; +constexpr float DOGMA_ANGEL_FAST_SPEED = 7; +constexpr float DOGMA_ANGEL_FAST_STEP = 0.6f; +constexpr float DOGMA_ANGEL_FAST_FALL_ACCEL = -0.15f; +constexpr float DOGMA_ANGEL_SLOW_CONE = 120; +constexpr float DOGMA_ANGEL_SLOW_SPEED = 4; +constexpr float DOGMA_ANGEL_SLOW_STEP = 0.3f; +constexpr float DOGMA_ANGEL_SLOW_FALL_ACCEL = -0.17f; +constexpr float DOGMA_ANGEL_FEATHER_SCALE = 0.8f; +constexpr float DOGMA_ANGEL_FEATHER_SCALE_RANGE = 0.4f; +constexpr float DOGMA_ANGEL_ORB_THROW = 15; + +// The nuke: an orb held 100 above it, growing from 3. +constexpr float DOGMA_ANGEL_NUKE_FRICTION = 0.5f; +static const Vector DOGMA_ANGEL_NUKE_OFFSET = vector_make(0, -100); +constexpr float DOGMA_ANGEL_NUKE_GROWTH = 3; +constexpr int DOGMA_ORB_TRAIL = 2; +constexpr int DOGMA_ORB_FADING = -2; +constexpr int DOGMA_ORB_SPARK = 1; + +// The ring: it circles the player, turning 15 degrees and pushed a quarter, at most 8, then charges through the player +// once outside the room 400 from its middle, spinning three rings of feathers as it passes, for 360 frames. +constexpr float DOGMA_ANGEL_RING_FRICTION = 0.8f; +constexpr float DOGMA_ANGEL_RING_END_FRICTION = 0.9f; +constexpr float DOGMA_ANGEL_RING_PULL = 0.25f; +constexpr float DOGMA_ANGEL_RING_TURN = 15; +constexpr float DOGMA_ANGEL_RING_TOP_SPEED = 8; +constexpr float DOGMA_ANGEL_RING_FAR_SQUARED = 160000; +constexpr float DOGMA_ANGEL_RING_SLOW = 0.8f; +constexpr float DOGMA_ANGEL_RING_FACING = 0.9f; +constexpr int DOGMA_ANGEL_RING_FRAMES = 360; +constexpr float DOGMA_ANGEL_RING_SHOT_FALL_ACCEL = -0.08f; +constexpr float DOGMA_ANGEL_RING_SHOT_TURN = 0.2617994f; +static const std::array DOGMA_ANGEL_RINGS = {vector_make(11, 12), vector_make(9, 12), vector_make(7, 12)}; +constexpr std::array DOGMA_ANGEL_RING_SCALES = {0.6f, 0.8f, 1}; +constexpr float DOGMA_ANGEL_TRAIL_EVERY = 6; +constexpr float DOGMA_ANGEL_TRAIL_DRAG = 0.5f; +constexpr float DOGMA_ANGEL_RING_REACH = 1.6f; +constexpr float DOGMA_ANGEL_RING_PLAYER_DAMAGE = 1; +constexpr float DOGMA_ANGEL_RING_DAMAGE = 100; +constexpr int DOGMA_ANGEL_RING_HIT_COUNTDOWN = 30; +constexpr float DOGMA_ANGEL_RING_PUSH = 10; +constexpr uint64_t DOGMA_ANGEL_RING_FLAGS = FLAG_NO_KNOCKBACK | FLAG_NO_PHYSICS_KNOCKBACK; + +// The transformation's flash of bloom. +constexpr int DOGMA_ANGEL_BLOOM_FRAMES = 6; +constexpr float DOGMA_ANGEL_BLOOM = 0.5f; + +// Shows every layer but the glitch layer, or only the glitch layer. +static void angel_glitch_layers_set(Entity_NPC& npc, bool isGlitching) +{ + for (size_t layer = 0; layer < npc.sprite.layerStates.size(); layer++) + npc.sprite.layerStates[layer].isVisible = (layer == DOGMA_ANGEL_GLITCH_LAYER) == isGlitching; +} + +// The glitch overlay ends: the normal layers come back. +static void angel_glitch_end(Entity_NPC& npc) +{ + angel_glitch_layers_set(npc, false); + npc.sprite.overlayAnimState.SetAnimationData(nullptr); + npc.i2 = 1; +} + +// Switches the music to a layer alone. +static void dogma_music_layer_set(int layer) +{ + MusicManager& music = g_manager->musicManager; + music.channels[music.currentChannel].enabledLayers.reset(); + music.EnableLayer(layer, LAYER_FADE); +} + +// Its death throes: the camera on it, the overlay and the music's last layer, then the controls off and its jingle. +static void angel_dying_update(Entity_NPC& npc) +{ + if (npc.sprite.overlayAnimState.isPlaying) angel_glitch_end(npc); + g_game->room->camera->SetFocusPosition(npc.pos); + AnimationState& anim = npc.sprite.animState; + if (!anim.animData) return; + if (anim.IsEventTriggered("Sound")) + { + g_game->bossOverlay.play(BOSS_OVERLAY_DOGMA_DYING); + dogma_music_layer_set(DOGMA_MUSIC_DEATH_LAYER); + } + if (!anim.animData || !anim.IsEventTriggered("Shoot")) return; + for (Entity_Player* player : g_game->playerManager.playerList) player->isControlsEnabled = false; + g_game->bossOverlay.play(BOSS_OVERLAY_DOGMA_DEAD); + g_manager->musicManager.Crossfade(MUSIC_JINGLE_DOGMA_OVER, DOGMA_JINGLE_FADE); + g_manager->sfxManager.volume_modifier_set(DOGMA_DEATH_HUSH); + g_manager->sfxManager.volumeModifierStep = DOGMA_DEATH_HUSH_STEP; +} + +// Its pre-update: Dogma's own shots do it no harm, its distortion runs, and below a quarter of its health it glitches. +static void angel_pre_update(Entity_NPC& npc, float health) +{ + if (npc.pendingDamage > 0) + { + npc.pendingDamage = 0; + for (DamageEvent& event : npc.damageEvents) + { + if (event.source.type == ENTITY_DOGMA && event.source.IsFriendly() == npc.IsFriendly()) event.damage = 0; + npc.pendingDamage += event.damage; + } + } + dogma_distortion_update(npc); + if (npc.state == DOGMA_ANGEL_DYING) return angel_dying_update(npc); + + if (npc.projectileDelay > 0) npc.projectileDelay = std::max(npc.projectileDelay - npc_ticks_get(npc), 0); + if (health < DOGMA_ANGEL_GLITCH_BELOW && random_unit() < DOGMA_ANGEL_GLITCH_ODDS - health * DOGMA_ANGEL_GLITCH_ODDS_FALL) + { + npc.sprite.PlayOverlay(DOGMA_ANGEL_GLITCHES[Random() & 3], PLAY_FORCED); + AnimationState& overlay = npc.sprite.overlayAnimState; + uint32_t frame = overlay.animData && overlay.animData->length != 0 ? Random() % (uint32_t)overlay.animData->length : 0; + if (overlay.animData) overlay.SetFrameFloat((float)(int)frame); + npc.i2 = 1; + angel_glitch_layers_set(npc, false); + npc.projectileDelay = (int)(Random() & 3) + DOGMA_ANGEL_GLITCH_FRAMES; + } + if (!npc.sprite.overlayAnimState.isPlaying) return; + if (npc.sprite.GetLayer(DOGMA_ANGEL_GLITCH_LAYER)->isVisible) + { + if (npc.projectileDelay <= 0) angel_glitch_end(npc); + return; + } + if (npc.i2 <= 0) angel_glitch_layers_set(npc, true); +} + +// Back to drifting after an attack, resting a while. +static void angel_rest(Entity_NPC& npc, int rest) +{ + npc.sprite.Play("Idle"); + npc.state = DOGMA_ANGEL_IDLE; + npc.projectileCooldown = (int)(Random() % DOGMA_ANGEL_REST_RANGE) + rest; +} + +// Starts the spread, facing the target. +static void angel_spread_start(Entity_NPC& npc, int state, Vector target) +{ + npc.sprite.Play("SpreadAttack"); + npc.sprite.isFlipX = npc.pos.x < target.x; + npc.state = state; + npc.stateFrame = 0; + npc.targetPosition = {}; +} + +// Idle: a figure eight about its target, then the spread when the target is far to a side, otherwise rarely a nuke or +// a ring while inside the room. +static void angel_idle(Entity_NPC& npc) +{ + npc.friction *= DOGMA_ANGEL_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) npc.PlaySound(SOUND_DOGMA_WING_FLAP, 1, 2, false, 1); + if (npc.projectileCooldown > 0) npc.projectileCooldown = std::max(npc.projectileCooldown - npc_ticks_get(npc), 0); + Vector target = npc.CalcTargetPosition(0); + float phase = npc.updateTime * DOGMA_ANGEL_EIGHT_SPEED; + Vector eight = vector_make(std::cos(phase) * DOGMA_ANGEL_EIGHT_WIDTH + target.x - npc.pos.x, + std::sin(phase + phase) * DOGMA_ANGEL_EIGHT_HEIGHT + target.y - npc.pos.y); + npc.velocity = vector_add(npc.velocity, vector_scale(vector_resized(eight, DOGMA_ANGEL_DRIFT), npc.speedMultiplier)); + if (npc.projectileCooldown > 0) return; + + float across = std::abs(target.x - npc.pos.x); + if (across > std::abs(target.y - npc.pos.y) && across > DOGMA_ANGEL_SPREAD_REACH && Random() % 3 == 0) + return angel_spread_start(npc, DOGMA_ANGEL_SPREAD, target); + if (!g_game->room->IsPositionInRoom(npc.pos, DOGMA_ANGEL_ROOM_MARGIN)) return; + uint32_t roll = Random() % DOGMA_ANGEL_SPECIAL_ODDS; + if (roll == 0) + { + npc.sprite.Play("NukeStart"); + npc.state = DOGMA_ANGEL_NUKE; + } + else if (roll == 1) + { + npc.sprite.Play("RingStart"); + npc.state = DOGMA_ANGEL_RING; + npc.PlaySound(SOUND_DOGMA_RING_START, 1, 2, false, 1); + } + else return; + npc.stateFrame = 0; + npc.targetPosition = npc.pos; +} + +// One cone of feathers about an angle: each faster than the last, at a random angle within it. +static void angel_feathers_fire(Entity_NPC& npc, ProjectileParams& params, float first, float cone, float speed, + float step) +{ + for (int feather = 0; feather < DOGMA_ANGEL_FEATHERS; feather++) + { + float angle = (random_unit() * cone + first) * DEGREES_TO_RADIANS; + float featherSpeed = (float)feather * step + speed; + Vector velocity = vector_make(std::cos(angle) * featherSpeed, std::sin(angle) * featherSpeed); + params.scale = random_unit() * DOGMA_ANGEL_FEATHER_SCALE_RANGE + DOGMA_ANGEL_FEATHER_SCALE; + npc.FireProjectiles(vector_add(velocity, npc.pos), velocity, PROJECTILES_SINGLE, params); + } +} + +// The spread: on its Shoot two cones of feathers toward the target (after a nuke the orb is thrown instead), and a +// recoil away. +static void angel_spread(Entity_NPC& npc) +{ + npc.friction *= DOGMA_ANGEL_SPREAD_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + Vector target = npc.CalcTargetPosition(0); + float aim = angle_approach(npc.sprite.isFlipX ? 0 : HALF_TURN_DEGREES, + vector_angle(vector_sub(target, npc.pos)), DOGMA_ANGEL_SPREAD_TURN); + npc.v2 = vector_make(aim + HALF_TURN_DEGREES, DOGMA_ANGEL_RECOIL); + if (npc.state == DOGMA_ANGEL_NUKE_THROW) + { + if (npc.entityRef) + { + npc.entityRef->velocity = vector_scale(vector_from_angle(aim), DOGMA_ANGEL_ORB_THROW); + npc.entityRef->parent = nullptr; + npc.entityRef = nullptr; + npc.PlaySound(SOUND_DOGMA_LIGHT_BALL_THROW, 1, 2, false, 1); + } + } + else + { + ProjectileParams params; + params.variant = PROJECTILE_WING; + params.fallingAccelModifier = DOGMA_ANGEL_FAST_FALL_ACCEL; + angel_feathers_fire(npc, params, aim - DOGMA_ANGEL_FAST_CONE * HALF, DOGMA_ANGEL_FAST_CONE, DOGMA_ANGEL_FAST_SPEED, DOGMA_ANGEL_FAST_STEP); + params.fallingAccelModifier = DOGMA_ANGEL_SLOW_FALL_ACCEL; + angel_feathers_fire(npc, params, aim - DOGMA_ANGEL_SLOW_CONE * HALF, DOGMA_ANGEL_SLOW_CONE, DOGMA_ANGEL_SLOW_SPEED, DOGMA_ANGEL_SLOW_STEP); + npc.PlaySound(SOUND_DOGMA_FEATHER_SPRAY, 1, 2, false, 1); + } + g_game->Spawn({.position = npc.pos, + .subType = BIG_SPLASH_DOGMA_ANGEL, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_SPLASH, + .seed = Random()}); + } + AnimationState& anim = npc.sprite.animState; + if (anim.animData && anim.WasEventTriggered("Shoot")) + { + npc.velocity = vector_add(npc.velocity, vector_scale(vector_from_angle(npc.v2.x), npc.v2.y * npc.speedMultiplier)); + npc.v2.y *= timescale_factor(DOGMA_ANGEL_RECOIL_DECAY, npc.speedMultiplier); + } + if (anim.animData && anim.isPlaying) return; + angel_rest(npc, DOGMA_ANGEL_REST); +} + +// The nuke: on its Shoot an orb gathers above it (held in entityRef). Once the orb is ready the angel throws it with +// a spread; without the orb it rests. +static void angel_nuke(Entity_NPC& npc) +{ + npc.friction *= DOGMA_ANGEL_NUKE_FRICTION; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (npc.sprite.IsEventTriggered("Sound")) npc.PlaySound(SOUND_BIRD_FLAP, 1, 2, false, 1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_DOGMA_LIGHT_APPEAR, 1, 2, false, 1); + auto* orb = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_DOGMA_ORB, .seed = Random()})); + orb->parent = &npc; + orb->posOffset = DOGMA_ANGEL_NUKE_OFFSET; + orb->minRadius = DOGMA_ANGEL_NUKE_GROWTH; + orb->maxRadius = 0; + orb->Update(); + npc.entityRef = orb; + } + AnimationState& anim = npc.sprite.animState; + if (!anim.animData || !anim.isPlaying) + { + npc.sprite.Play("NukeLoop"); + if (!anim.animData) return; + } + if (!anim.animData->isLooping) return; + Entity* orb = npc.entityRef; + if (orb && orb->type == ENTITY_EFFECT) + { + if (static_cast(orb)->state >= 0) return; + angel_spread_start(npc, DOGMA_ANGEL_NUKE_THROW, npc.CalcTargetPosition(0)); + return; + } + angel_rest(npc, DOGMA_ANGEL_LONG_REST); +} + +// The ring's feathers: three rings, each wider and larger, turned 15 degrees from the last. +static void angel_ring_fire(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_DOGMA_SPIN_ATTACK, 1, 2, false, 1); + npc.PlaySound(SOUND_THUMBS_DOWN, 1, 2, false, 1); + ProjectileParams params; + params.fallingAccelModifier = DOGMA_ANGEL_RING_SHOT_FALL_ACCEL; + params.variant = PROJECTILE_WING; + for (size_t ring = 0; ring < DOGMA_ANGEL_RINGS.size(); ring++) + { + if (ring != 0) params.circleAngle += DOGMA_ANGEL_RING_SHOT_TURN; + params.scale = DOGMA_ANGEL_RING_SCALES[ring]; + npc.FireProjectiles(npc.pos, DOGMA_ANGEL_RINGS[ring], PROJECTILES_RING, params); + } + if (npc.stateFrame <= DOGMA_ANGEL_RING_FRAMES) return; + npc.stateFrame = -1; + npc.sprite.Play("RingEnd"); +} + +// The ring's steering (targetPosition is its push): circling the player (i1 0) until outside the room, then turning +// back (1) until it faces the player, then charging (2) and firing its rings once past. +static void angel_ring_steer(Entity_NPC& npc, Vector toPlayer) +{ + Vector& push = npc.targetPosition; + float speed = npc.speedMultiplier; + if (npc.i1 == 0) + { + push = vector_sub(push, vector_scale(vector_rotated(vector_resized(toPlayer, DOGMA_ANGEL_RING_PULL), DOGMA_ANGEL_RING_TURN), speed)); + float length = vector_length_squared(push); + if (length > DOGMA_ANGEL_RING_TOP_SPEED * DOGMA_ANGEL_RING_TOP_SPEED) push = vector_scale(push, DOGMA_ANGEL_RING_TOP_SPEED / std::sqrt(length)); + if (!g_game->room->IsPositionInRoom(npc.pos, 0) && + vector_length_squared(vector_sub(Room::GetCenterPos(), npc.pos)) > DOGMA_ANGEL_RING_FAR_SQUARED) + npc.i1 = 1; + return; + } + + if (npc.i1 == 1) push = vector_scale(push, timescale_factor(DOGMA_ANGEL_RING_SLOW, speed)); + push = vector_add(push, vector_scale(vector_resized(toPlayer, DOGMA_ANGEL_RING_PULL), speed)); + float length = vector_length_squared(push); + if (length > DOGMA_ANGEL_RING_TOP_SPEED * DOGMA_ANGEL_RING_TOP_SPEED) push = vector_scale(push, DOGMA_ANGEL_RING_TOP_SPEED / std::sqrt(length)); + if (npc.i1 == 1) + { + if (vector_dot(vector_normalized(toPlayer), vector_normalized(push)) <= DOGMA_ANGEL_RING_FACING) return; + npc.i1 = 2; + } + if (npc.i1 != 2 || vector_dot(toPlayer, push) >= 0) return; + npc.i1 = 0; + angel_ring_fire(npc); +} + +// The ring's touch: what it passes through is hurt (players and familiars by 1, others by 100) and flung sideways. +static void angel_ring_touch(Entity_NPC& npc) +{ + for (Entity* entity : entity_query_radius(npc.pos, npc.size * DOGMA_ANGEL_RING_REACH, + QUERY_PLAYERS | QUERY_ENEMIES | QUERY_FAMILIARS)) + { + if (entity == &npc) continue; + bool isAlly = entity->type == ENTITY_PLAYER || entity->type == ENTITY_FAMILIAR; + entity->TakeDamage(isAlly ? DOGMA_ANGEL_RING_PLAYER_DAMAGE : DOGMA_ANGEL_RING_DAMAGE, 0, EntityRef(&npc), DOGMA_ANGEL_RING_HIT_COUNTDOWN); + Vector away = vector_resized(vector_sub(entity->pos, npc.pos), DOGMA_ANGEL_RING_PUSH); + entity->velocity = vector_add(entity->velocity, vector_scale(vector_rotated(away, RIGHT_ANGLE_DEGREES), entity->speedMultiplier)); + } +} + +// The ring: from its Shoot it charges about the room for 360 frames, unpushable, trailing orbs and spinning rings of +// feathers, then rests. +static void angel_ring(Entity_NPC& npc) +{ + if (npc.stateFrame == 0) + { + npc.friction = DOGMA_ANGEL_RING_FRICTION; + if (!npc.sprite.IsEventTriggered("Shoot")) return; + npc.stateFrame = 1; + npc.targetPosition = {}; + npc.flags |= DOGMA_ANGEL_RING_FLAGS; + npc.i1 = 0; + return; + } + if (npc.stateFrame < 1) + { + npc.friction = DOGMA_ANGEL_RING_END_FRICTION; + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + angel_rest(npc, DOGMA_ANGEL_LONG_REST); + npc.flags &= ~DOGMA_ANGEL_RING_FLAGS; + return; + } + + npc.friction = DOGMA_ANGEL_RING_FRICTION; + if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) npc.sprite.Play("RingLoop"); + npc.stateFrame += npc_ticks_get(npc); + angel_ring_steer(npc, vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, npc.speedMultiplier)); + if (npc.GetIntervalTicks(DOGMA_ANGEL_TRAIL_EVERY, 0) != 0) + { + Entity* trail = g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(npc.velocity, DOGMA_ANGEL_TRAIL_DRAG), + .spawner = &npc, + .subType = DOGMA_ORB_TRAIL, + .type = ENTITY_EFFECT, + .variant = EFFECT_DOGMA_ORB, + .seed = Random()}); + trail->posOffset = npc.posOffset; + trail->Update(); + } + angel_ring_touch(npc); +} + +// The transformation from Dogma: a flash of bloom and the music's first layer, then it fights. +static void angel_transform(Entity_NPC& npc) +{ + npc.friction *= DOGMA_ATTACK_FRICTION; + g_game->room->camera->SetFocusPosition(npc.pos); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_DOGMA_ANGEL_TRANSFORM_END, 1, 2, false, 1); + g_game->bloomDuration = DOGMA_ANGEL_BLOOM_FRAMES; + g_game->bloomTimer = DOGMA_ANGEL_BLOOM_FRAMES; + g_game->bloomStrength = DOGMA_ANGEL_BLOOM; + dogma_music_layer_set(0); + } + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying && !npc.HasEntityFlags(FLAG_NO_REWARD)) return; + npc.sprite.Play("Idle"); + npc.flags &= ~(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_DONT_COUNT_BOSS_HP | FLAG_HIDE_HP_BAR); + npc.state = DOGMA_ANGEL_IDLE; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.isInvincible = false; + npc.projectileCooldown = 0; + npc.projectileDelay = 0; + npc.stateFrame = 0; +} + +// Once the angel dies what Dogma fired goes: its shots fall, its lasers end, its orbs fizzle (their sparks vanish) +// and the other enemies it brought die. +static void angel_death_clear(Entity_NPC& npc) +{ + for (Entity* entity : std::vector(g_game->room->entityList.updateEL)) + { + if (entity->spawnerType != ENTITY_DOGMA) continue; + if (entity->type == ENTITY_PROJECTILE) + { + static_cast(entity)->projectileFlags = 0; + entity->isDead = true; + } + else if (entity->type == ENTITY_LASER) static_cast(entity)->timeout = DOGMA_LASER_END; + else if (entity->type == ENTITY_EFFECT && entity->variant == EFFECT_DOGMA_ORB) + { + if (entity->subtype == 0) + { + static_cast(entity)->state = DOGMA_ORB_FADING; + entity->sprite.Play("Fizzle"); + entity->isDead = true; + } + else if (entity->subtype == DOGMA_ORB_SPARK) entity->Remove(); + } + else if (entity->is_valid_boss_enemy() && !entity->IsBoss()) entity->Kill(EntityRef(&npc)); + } +} + +// 004ae4d0 Dogma's angel (950.2): it transforms, then drifts in figure eights about the player, spreading feathers, +// throwing a nuke of light and charging in a ring. Below a quarter of its health it glitches, and its death clears +// what Dogma fired. +static void dogma_angel_update(Entity_NPC& npc) +{ + float health = npc.health / npc.maxHitPoints; + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return angel_pre_update(npc, health); + if (npc.aiCallPhase == AI_PHASE_INTERPOLATE) return; + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = DOGMA_ANGEL_IDLE; + break; + case DOGMA_ANGEL_IDLE: + angel_idle(npc); + break; + case DOGMA_ANGEL_SPREAD: + case DOGMA_ANGEL_NUKE_THROW: + angel_spread(npc); + break; + case DOGMA_ANGEL_NUKE: + angel_nuke(npc); + break; + case DOGMA_ANGEL_RING: + angel_ring(npc); + break; + case DOGMA_ANGEL_TRANSFORM: + angel_transform(npc); + break; + } + if (npc.isDead) angel_death_clear(npc); +} + +// The angel's babies: drained from 500 to their health 3.5 a frame, circling the player until they dash past it +// 120 and burst, dealing damage about them. +constexpr int DOGMA_BABY_IDLE = NPC_STATE_IDLE; +constexpr int DOGMA_BABY_DASH = NPC_STATE_ATTACK; +constexpr float DOGMA_BABY_START_HEALTH = 500; +constexpr ColorMod DOGMA_BABY_SPLAT_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; +constexpr float DOGMA_BABY_DOGMA_DAMAGE = 10; +constexpr float DOGMA_BABY_FRICTION = 0.9f; +constexpr float DOGMA_BABY_DASH_FRICTION = 0.75f; +constexpr RNG DOGMA_BABY_ORBIT_SHIFTS = {0, 15, 1, 29}; +constexpr float DOGMA_BABY_ORBIT_RADIUS = 100; +constexpr float DOGMA_BABY_ORBIT_RADIUS_RANGE = 80; +constexpr float DOGMA_BABY_ORBIT_SPEED = 2.5f; +constexpr float DOGMA_BABY_ORBIT_PULL = 0.3f; +constexpr float DOGMA_BABY_ORBIT_PULL_RANGE = 0.4f; +constexpr float DOGMA_BABY_DRAIN = 3.5f; +constexpr float DOGMA_BABY_DASH_BELOW = 100; +constexpr uint32_t DOGMA_BABY_DASH_ODDS = 20; +constexpr float DOGMA_BABY_DASH_PAST = 120; +constexpr float DOGMA_BABY_DASH_START = 0.2f; +constexpr float DOGMA_BABY_DASH_TOP = 10; +constexpr float DOGMA_BABY_BURST_DAMAGE = 20; +constexpr float DOGMA_BABY_BURST_THRESHOLD = 50; +constexpr float DOGMA_BABY_BURST_RADIUS = 60; +constexpr float DOGMA_BABY_BURST_VOLUME = 0.8f; +constexpr float DOGMA_BABY_BURST_PITCH = 1.2f; +constexpr float DOGMA_BABY_BURST_PITCH_RANGE = 0.2f; +constexpr int DOGMA_BABY_BURST_SHAKE = 14; + +// The baby's dash: past the player 120, faster each frame up to 10, bursting once beyond its mark. +static void baby_dash(Entity_NPC& npc) +{ + npc.friction *= DOGMA_BABY_DASH_FRICTION; + AnimationState& anim = npc.sprite.animState; + if (!anim.animData || !anim.isPlaying) + { + Vector player = npc.GetPlayerTarget()->pos; + npc.targetPosition = vector_add(player, vector_resized(vector_sub(player, npc.pos), DOGMA_BABY_DASH_PAST)); + Vector dash = vector_sub(npc.targetPosition, npc.pos); + npc.v1 = vector_normalized(dash); + if (std::abs(dash.x) <= std::abs(dash.y)) npc.sprite.Play(dash.y >= 0 ? "DashDown" : "DashUp"); + else + { + npc.sprite.Play("DashRight"); + npc.sprite.isFlipX = dash.x < 0; + } + npc.aiFloat = DOGMA_BABY_DASH_START; + if (!anim.animData) return; + } + if (!anim.animData->isLooping) return; + + npc.aiFloat = std::min(npc.speedMultiplier + npc.aiFloat, DOGMA_BABY_DASH_TOP); + npc.velocity = vector_add(npc.velocity, vector_scale(vector_resized(vector_sub(npc.targetPosition, npc.pos), npc.aiFloat), + npc.speedMultiplier)); + if (vector_dot(vector_sub(npc.pos, npc.targetPosition), npc.v1) <= 0) return; + + Entity* burst = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = ENEMY_GHOST_BLAST, + .type = ENTITY_EFFECT, + .variant = EFFECT_ENEMY_GHOST, + .seed = Random()}); + burst->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + burst->sprite.scale = vector_make(1, 1); + burst->SetCollisionDamage(DOGMA_BABY_BURST_DAMAGE); + burst->Update(); + damage_radius({.position = npc.pos, + .source = &npc, + .damage = 1, + .playerDamageThreshold = DOGMA_BABY_BURST_THRESHOLD, + .radius = DOGMA_BABY_BURST_RADIUS}); + npc_sound_play(SOUND_DEMON_HIT, DOGMA_BABY_BURST_VOLUME, 2, random_unit() * DOGMA_BABY_BURST_PITCH_RANGE + DOGMA_BABY_BURST_PITCH); + game_shake_screen(DOGMA_BABY_BURST_SHAKE); + npc.Remove(); +} + +// The baby's orbit about its target, on a circle, speed and pull its seed fixes. Drained to its health, below 100 it +// may dash, unless the angel holds it for a nuke. +static void baby_orbit(Entity_NPC& npc) +{ + npc.friction *= DOGMA_BABY_FRICTION; + AnimationState& anim = npc.sprite.animState; + if (!anim.animData || !anim.isPlaying) npc.sprite.Play("Idle"); + if (!anim.animData || !anim.animData->isLooping) return; + + Vector target = npc.CalcTargetPosition(0); + RNG rng = DOGMA_BABY_ORBIT_SHIFTS; + rng._seed = npc.initSeed; + float radius = rng.RandomFloat() * DOGMA_BABY_ORBIT_RADIUS_RANGE + DOGMA_BABY_ORBIT_RADIUS; + float sign = rng.RandomInt(2) == 0 ? -1.0f : 1.0f; + float speed = (rng.RandomFloat() * DOGMA_BABY_ORBIT_SPEED + DOGMA_BABY_ORBIT_SPEED) * sign; + float pull = rng.RandomFloat() * DOGMA_BABY_ORBIT_PULL_RANGE + DOGMA_BABY_ORBIT_PULL; + Vector spot = vector_add(vector_scale(vector_from_angle(speed * npc.updateTime), radius), target); + npc.velocity = vector_add(npc.velocity, vector_scale(vector_resized(vector_sub(spot, npc.pos), pull), npc.speedMultiplier)); + + Entity* angel = npc.spawnerEntity; + if (angel && angel->IsType(ENTITY_DOGMA, DOGMA_ANGEL, -1) && static_cast(angel)->state == DOGMA_ANGEL_NUKE) return; + if (npc.health > npc.maxHitPoints) npc.health = std::max(npc.health - npc.speedMultiplier * DOGMA_BABY_DRAIN, npc.maxHitPoints); + if (npc.health < DOGMA_BABY_DASH_BELOW && Random() % DOGMA_BABY_DASH_ODDS == 0) + { + npc.sprite.Play("DashStart"); + npc.state = DOGMA_BABY_DASH; + } +} + +// 004b0200 The angel's baby (950.10): it appears with 500 health draining to its own, takes ten times Dogma's hurt, +// circles the player and dashes through it to burst. +static void dogma_angel_baby_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) + { + if (npc.pendingDamage > 0) + { + npc.pendingDamage = 0; + for (DamageEvent& event : npc.damageEvents) + { + if (event.source.type == ENTITY_DOGMA) event.damage *= DOGMA_BABY_DOGMA_DAMAGE; + npc.pendingDamage += event.damage; + } + } + return dogma_distortion_update(npc); + } + switch (npc.state) + { + case NPC_STATE_INIT: + npc.sprite.Play("Appear", PLAY_FORCED); + npc.flags &= ~FLAG_APPEAR; + npc.state = DOGMA_BABY_IDLE; + npc.health = DOGMA_BABY_START_HEALTH; + npc.splatColor = DOGMA_BABY_SPLAT_COLOR; + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + break; + case DOGMA_BABY_IDLE: + baby_orbit(npc); + break; + case DOGMA_BABY_DASH: + baby_dash(npc); + break; + } +} + +// Dogma's forms (950) by variant. +void boss_dogma_update(Entity_NPC& npc) +{ + switch (npc.variant) + { + case DOGMA_TV: + return dogma_tv_update(npc); + case DOGMA_ANGEL: + return dogma_angel_update(npc); + case DOGMA_ANGEL_BABY: + return dogma_angel_baby_update(npc); + default: + return dogma_update(npc); + } +} diff --git a/src/boss_final.h b/src/boss_final.h index 719e9d2..ae20b44 100644 --- a/src/boss_final.h +++ b/src/boss_final.h @@ -29,5 +29,52 @@ enum MotherOrbSize MOTHER_ORB_SMALL }; +// Dogma's forms (950), by variant: Dogma itself, its TV, the angel it becomes and the angel's babies. +enum DogmaVariant +{ + DOGMA_MAIN = 0, + DOGMA_TV = 1, + DOGMA_ANGEL = 2, + DOGMA_ANGEL_BABY = 10 +}; + +// The Beast's forms (951), by variant: the Beast, its stalactites, rocks and souls, the four ultra horsemen and what +// they bring, and the background beast with its four horsemen. +enum BeastVariant +{ + BEAST_MAIN = 0, + BEAST_STALACTITE = 1, + BEAST_ROCK = 2, + BEAST_SOUL = 3, + BEAST_ULTRA_FAMINE = 10, + BEAST_ULTRA_FAMINE_FLY = 11, + BEAST_ULTRA_PESTILENCE = 20, + BEAST_ULTRA_PESTILENCE_FLY = 21, + BEAST_ULTRA_PESTILENCE_MAGGOT = 22, + BEAST_ULTRA_PESTILENCE_FLY_BALL = 23, + BEAST_ULTRA_WAR = 30, + BEAST_ULTRA_WAR_BOMB = 31, + BEAST_ULTRA_DEATH = 40, + BEAST_ULTRA_DEATH_SCYTHE = 41, + BEAST_ULTRA_DEATH_HEAD = 42, + BEAST_BACKGROUND_BEAST = 100, + BEAST_BACKGROUND_FAMINE = 101, + BEAST_BACKGROUND_PESTILENCE = 102, + BEAST_BACKGROUND_WAR = 103, + BEAST_BACKGROUND_DEATH = 104 +}; + +// The Dogma fight's room (living room variant 1000) and the room of the Beast's horsemen (crawlspace variant 666). +constexpr int DOGMA_ROOM_VARIANT = 1000; +constexpr int BEAST_ROOM_VARIANT = 666; + +// Home's generic props (960) by variant: the lamp and the TV Dogma comes out of. +constexpr int PROP_LAMP = 3; +constexpr int PROP_TV = 4; + void boss_mother_update(Entity_NPC& npc); +void boss_dogma_update(Entity_NPC& npc); +void boss_beast_update(Entity_NPC& npc); +void beast_background_spawn(Entity_NPC& npc); +void beast_render(Entity_NPC& npc, const Vector& offset); void mother_render(Entity_NPC& npc, const Vector& offset); diff --git a/src/boss_gemini.cpp b/src/boss_gemini.cpp index 7523f5e..32726ca 100644 --- a/src/boss_gemini.cpp +++ b/src/boss_gemini.cpp @@ -7,11 +7,7 @@ // Gemini's parts, by variant: the big twins below 10 (Gemini, Steven, Blighted Ovum), their babies ten above, and the // umbilical cord's segments. -constexpr int GEMINI_STEVEN = 1; -constexpr int GEMINI_BLIGHTED_OVUM = 2; constexpr int GEMINI_STEVEN_BABY = 11; -constexpr int GEMINI_BLIGHTED_OVUM_BABY = 12; -constexpr int GEMINI_CORD = 20; constexpr int GEMINI_NO_CORD = 1; constexpr int CORD_SEGMENTS = 18; diff --git a/src/boss_hornfel.cpp b/src/boss_hornfel.cpp new file mode 100644 index 0000000..dac21a3 --- /dev/null +++ b/src/boss_hornfel.cpp @@ -0,0 +1,1261 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_tear.h" +#include "grid_entity_door.h" +#include "log.h" +#include "loot_list.h" +#include "manager.h" +#include "mines.h" +#include "room_grid.h" +#include +#include +#include + +// Hornfel's forms, by variant: Hornfel himself and the decoys he sends out in carts. +constexpr int HORNFEL_DECOY = 1; + +// Hornfel's states: riding his cart, running on foot, hidden off screen, gone through a door, throwing bombs, +// throwing brimstone bombs, charging and its finish, the decoy's detonation, his fall from a broken cart, waiting after +// sending decoys, and a decoy's idling. +enum HornfelState +{ + HORNFEL_RIDE = NPC_STATE_IDLE, + HORNFEL_RUN = NPC_STATE_MOVE, + HORNFEL_HIDDEN = NPC_STATE_JUMP, + HORNFEL_CHARGE_EXIT = NPC_STATE_STOMP, + HORNFEL_THROW = NPC_STATE_ATTACK, + HORNFEL_BOMB_SPREAD = NPC_STATE_ATTACK2, + HORNFEL_CHARGE = NPC_STATE_ATTACK3, + HORNFEL_CHARGE_FINISH = NPC_STATE_ATTACK4, + HORNFEL_DETONATE = NPC_STATE_ATTACK5, + HORNFEL_FALL = NPC_STATE_SUMMON, + HORNFEL_SUMMONED = NPC_STATE_SUMMON2, + HORNFEL_DECOY_IDLE = NPC_STATE_SPECIAL +}; + +// A rail door's states: shut, and open for a passing cart. +constexpr int HORNFEL_DOOR_CLOSED = NPC_STATE_IDLE; +constexpr int HORNFEL_DOOR_OPEN = NPC_STATE_MOVE; + +// Hornfel packs his timers into the NPC's counters as the original does: four byte cooldowns in projectileCooldown, +// a short move timer, the throw count and whether he faces the front in projectileDelay, and the hidden wait and the +// re-entry delay as two shorts in stateFrame. +enum HornfelCooldown +{ + COOLDOWN_BOMB_SPREAD, + COOLDOWN_SUMMON, + COOLDOWN_CHARGE, + COOLDOWN_TAUNT +}; +constexpr int DELAY_THROWS = 2; +constexpr int DELAY_FACING_FRONT = 3; + +static uint8_t& counter_byte(int& field, int index) +{ + return reinterpret_cast(&field)[index]; +} + +static int16_t counter_half_get(int field, int half) +{ + return (int16_t)((uint32_t)field >> (16 * half)); +} + +static void counter_half_set(int& field, int half, int value) +{ + uint32_t shift = 16 * (uint32_t)half; + field = (int)(((uint32_t)field & ~(0xffffu << shift)) | ((uint32_t)(uint16_t)value << shift)); +} + +// His packed counters by name. +static uint8_t& hornfel_cooldown(Entity_NPC& npc, HornfelCooldown which) +{ + return counter_byte(npc.projectileCooldown, which); +} + +static int16_t hornfel_move_timer(Entity_NPC& npc) +{ + return counter_half_get(npc.projectileDelay, 0); +} + +static void hornfel_move_timer_set(Entity_NPC& npc, int value) +{ + counter_half_set(npc.projectileDelay, 0, value); +} + +// The cart: the hornfel minecart's look, its rolling speed (its v2.x) while ridden, building to 30 on a charge, back +// to 1.2 after the charge's shot and no lower than 0.8 before it. +constexpr std::string_view HORNFEL_CART_ANM2 = "gfx/965.001_hornfel minecart.anm2"; +constexpr float CART_SPEED = 1.2f; +constexpr float CART_CHARGE_START = 0.1f; +constexpr float CART_CHARGE_GAIN = 0.08f; +constexpr float CART_CHARGE_MAX = 30; +constexpr float CART_EXIT_MAX = 6; +constexpr float CART_FINISH_SLOW = 0.75f; +constexpr float CART_FINISH_MIN = 0.8f; +constexpr float CART_FINISH_GAIN = 0.1f; + +// The doors: spawned on the room's edges where a rail meets the wall, their sprites turned to face in and set 15 +// inside, opening for a cart heading in or one on their cell, closing after 15 (5 for Hornfel on foot, 10 when +// charging). +constexpr float DOOR_SPRITE_INSET = 15; +constexpr int DOOR_OPEN_FRAMES = 15; +constexpr int DOOR_RUN_FRAMES = 5; +constexpr int DOOR_CHARGE_FRAMES = 10; +constexpr float DOOR_FACING = 0.2f; +constexpr float DOOR_SOUND_VOLUME = 0.5f; +constexpr int HORNFEL_DOOR_SOUND_DELAY = 10; +constexpr float DOOR_SOUND_PITCH = 1.3f; +constexpr float DOOR_ENTRY_CLEARANCE = 3600; +constexpr int DOOR_ENTRY_GRACE = 30; +constexpr ColorMod DOOR_POOF_COLOR = {{0.4f, 0.4f, 0.4f, 1}, {1, 1, 1, 1}, {0, 0, 0}}; + +// The room controller sends a cart through a door every 150 to 359 frames (half that in large rooms) while a boss +// lives: one of the Mines' enemies. +constexpr uint32_t CONTROLLER_WAIT_RANGE = 210; +constexpr int CONTROLLER_WAIT = 150; +constexpr int LARGE_ROOM_CELLS = 136; +constexpr std::array, 7> CART_RIDERS = {{{ENTITY_QUAKEY, 0}, + {ENTITY_DANNY, 0}, + {ENTITY_FACELESS, 0}, + {ENTITY_BONY, 0}, + {ENTITY_GURGLE, 0}, + {ENTITY_FIREPLACE, 0}, + {ENTITY_MOVABLE_TNT, 0}}}; + +// Entering: one time in eight (summon cooldown spent, the controller's wait over 4) he sends two decoys (three in +// large rooms) when at most one other enemy is out, waiting 30 to 59. One time in eight (charge cooldown spent) he +// charges through a door with a partner, passing 6 to 8 doors. Else he rides in, waiting 15 to 29 before his attack, +// and one time in three lets two fly bombs go within 6 when no player is within 240 and at most 3 bombs are out. +constexpr uint32_t ENTRY_ODDS_MASK = 7; +constexpr int HORNFEL_SUMMON_ENEMY_LIMIT = 2; +constexpr int CONTROLLER_SUMMON_WAIT = 4; +constexpr int CONTROLLER_SUMMON_HOLD = 150; +constexpr int DECOYS = 2; +constexpr uint8_t HORNFEL_SUMMON_COOLDOWN = 100; +constexpr uint32_t SUMMON_WAIT_RANGE = 30; +constexpr int HORNFEL_SUMMON_WAIT = 30; +constexpr uint8_t CHARGE_COOLDOWN = 100; +constexpr uint32_t CHARGE_DOORS_RANGE = 3; +constexpr int CHARGE_DOORS = 6; +constexpr uint32_t RIDE_WAIT_RANGE = 15; +constexpr int RIDE_WAIT = 15; +constexpr uint32_t FLY_BOMB_ODDS = 3; +constexpr size_t FLY_BOMB_LIMIT = 3; +constexpr float FLY_BOMB_PLAYER_CLEARANCE = 57600; +constexpr int FLY_BOMBS = 2; +constexpr float FLY_BOMB_SPREAD = 40; +constexpr float FLY_BOMB_SPREAD_HALF = 20; +constexpr float FLY_BOMB_OFFSET = 6; +constexpr int NO_DOOR_WAIT = 15; +constexpr uint8_t START_COOLDOWN = 30; +constexpr float FLY_BOMB_FREED_HEALTH = 3.5f; +constexpr int HIDE_FRAMES = 45; + +// His attacks: a held bomb (weight 3), two held bombs (1) or a spread of brimstone bombs (1, every 150 cooldown +// ticks). A held bomb is a normal (6), hot (3) or sad blood (1) one on a 35 fuse, thrown leading the target by 0.1 to +// 0.3 of the distance. The spread throws 3 (4 in large rooms) spaced apart by the best of 8 spots. +constexpr int ATTACK_HELD = 0; +constexpr int ATTACK_DOUBLE = 1; +constexpr int ATTACK_SPREAD = 2; +constexpr int ATTACK_HELD_WEIGHT = 3; +constexpr uint8_t SPREAD_COOLDOWN = 150; +constexpr float ATTACK_BACK_FACING = -0.2f; +constexpr int HELD_FUSE = 35; +constexpr int HELD_NORMAL_WEIGHT = 6; +constexpr int HELD_HOT_WEIGHT = 3; +constexpr int HELD_SAD_WEIGHT = 1; +constexpr float HORNFEL_THROW_LEAD = 0.1f; +constexpr float THROW_LEAD_RANGE = 0.20000002f; +constexpr int SPREAD_BOMBS = 3; +constexpr int SPREAD_TRIES = 8; +constexpr float SPREAD_MARGIN = 40; +constexpr float SPREAD_CLEARANCE = 64; +constexpr float SPREAD_SCORE_FLOOR = -1e30f; +constexpr int SPREAD_REENTRY_DELAY = 125; +constexpr uint8_t TAUNT_COOLDOWN = 150; +constexpr uint32_t TAUNT_ODDS = 10; +constexpr float TAUNT_HEALTH = 0.5f; + +// A thrown bomb: at 10 to 28 by its distance past 100 over 200 (three quarters for a hot one), from 24 up, falling +// from 4. +constexpr float LAUNCH_NEAR = 100; +constexpr float LAUNCH_SPAN = 200; +constexpr float HORNFEL_LAUNCH_SPEED = 10; +constexpr float LAUNCH_SPEED_RANGE = 18; +constexpr float LAUNCH_HOT_SHARE = 0.75f; +constexpr float LAUNCH_FALL = -4; +constexpr float LAUNCH_HEIGHT = -24; + +// The charge drops a bomb within 1 every 15 frames while 20 inside the room. Its finish fires a big burning shot +// leading the target by a tenth, raised 10, falling faster. +constexpr int CHARGE_BOMB_EVERY = 15; +constexpr float CHARGE_BOMB_MARGIN = 20; +constexpr ColorMod FINISH_SHOT_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 0.3f, 0}}; +constexpr float FINISH_SHOT_SCALE = 2; +constexpr float FINISH_SHOT_LEAD = 0.1f; +constexpr float FINISH_SHOT_CURVE = 10; +constexpr float FINISH_SHOT_FALL = 0.6f; +constexpr float FINISH_SHOT_SLOW = 0.7f; +constexpr float FINISH_SHOT_DROP = 3; + +// On foot: fleeing from the side of the target he faces most, turning 0.5 to 3.5 a frame at 1.2, making for the +// nearest door with a path, checked every 10 frames, and fading out past the room's edge over 48. +constexpr float RUN_FRICTION = 0.8f; +constexpr float HORNFEL_RUN_SPEED = 1.2f; +constexpr float RUN_TURN = 0.5f; +constexpr float RUN_TURN_RANGE = 3; +constexpr float RUN_AIM_SHARE = 0.8f; +constexpr int RUN_PATH_CHECK = 10; +constexpr float RUN_PATH_SPEED = 1.08f; +constexpr float RUN_FADE = 48; +constexpr float DOOR_SEARCH_FLOOR = 1e30f; +constexpr std::array, 4> RUN_SIDES = {{{0, 1}, {0, -1}, {-1, 0}, {1, 0}}}; +constexpr int FALL_RUN_WAIT = 90; +constexpr float FALL_FRICTION = 0.6f; + +// His fall from a broken cart: he keeps 100 health and hurts 1 on contact. The held bombs fly off within 10. +constexpr float HORNFEL_FALL_HEALTH = 100; +constexpr float FALL_CONTACT_DAMAGE = 1; +constexpr float FALL_BOMB_SCATTER = 10; + +// A decoy takes 1 to 3 from each hit (more for over 10, one time in three one more) and goes off below 1.5: a blast of +// 110 over 75 and six troll bombs at 5 to 20. +constexpr float DECOY_BIG_HIT = 10; +constexpr uint32_t DECOY_HIT_ODDS = 3; +constexpr float DECOY_DYING = 1.5f; +constexpr float DECOY_BLAST_DAMAGE = 110; +constexpr float DECOY_BLAST_RADIUS = 75; +constexpr int DECOY_TROLL_BOMBS = 6; +constexpr float DECOY_TROLL_SPEED = 5; +constexpr float DECOY_TROLL_SPEED_RANGE = 15; +constexpr uint64_t DECOY_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_DEATH_TRIGGER | FLAG_BOSSDEATH_TRIGGERED; +constexpr int HORNFEL_HIDDEN_LAYER = 3; + +// A grid cell's rail byte: a minecart riding it backward (-1), forward (1) or neither (0), none on a mineshaft piece. +static int rail_sign_get(uint8_t rail) +{ + if (rail & RAIL_MINESHAFT) return 0; + if (rail & RAIL_CART_BACKWARD) return -1; + return rail >> 5 & 1; +} + +// The rail byte under a rail door's target position, none off the grid or on no rail. +static int door_rail_get(Entity& door) +{ + Room& room = *g_game->room; + int cell = room.GetGridIndex(door.targetPosition); + if (cell < 0 || cell >= ROOM_GRID_CELLS) return RAIL_NONE; + return room.railManager.rails[cell]; +} + +// 004bb550 The way a cart leaves through a rail door: along its rail, the way its cart flag points. +static Vector hornfel_get_rail_direction(Entity& door) +{ + int rail = door_rail_get(door); + int sign = rail == RAIL_NONE ? 0 : rail_sign_get((uint8_t)rail); + if (sign == 0) return {}; + if ((rail & RAIL_PIECE_MASK) != 0) return vector_make(0, (float)sign); + return vector_make((float)sign, 0); +} + +// 004bb6b0 The grid cell a rail door's rail leads to next, -1 when it leads nowhere. +static int hornfel_next_rail_index(Entity& door) +{ + Vector direction = hornfel_get_rail_direction(door); + if (vector_is_zero(direction)) return -1; + return g_game->room->GetGridIndex(vector_add(door.targetPosition, vector_scale(direction, GRID_CELL_SIZE))); +} + +// 004bb830 Opens a shut rail door with a heavy creak, then keeps it open for some frames. +static void hornfel_set_anim(Entity_NPC& door, int frames) +{ + if (door.state == HORNFEL_DOOR_CLOSED) + { + door.sprite.Play("Open"); + npc_sound_play(SOUND_DOOR_HEAVY_OPEN, DOOR_SOUND_VOLUME, HORNFEL_DOOR_SOUND_DELAY, DOOR_SOUND_PITCH); + door.state = HORNFEL_DOOR_OPEN; + } + door.stateFrame = frames; +} + +// 004bb920 A rail door takes a rider for its pair, unless either already has one. +static bool hornfel_claim_target(Entity_NPC& door, Entity* rider) +{ + Entity* pair = door.parent.get(); + if (door.target || (pair && pair->target)) return false; + + door.target = rider; + if (pair) pair->target = rider; + return true; +} + +// 004bb230 A rail door at a cell on the room's edge, turned to face in from its side (left, top, right, bottom). +static Entity* door_spawn(int cell, int side) +{ + constexpr std::array SIDE_ANGLES = {-RIGHT_ANGLE_DEGREES, 0, RIGHT_ANGLE_DEGREES, HALF_TURN_DEGREES}; + uint32_t seed = Random(); + Entity* door = g_game->Spawn({.position = g_game->room->GetGridPosition(cell), .type = ENTITY_HORNFEL_DOOR, .seed = seed}); + door->sprite.rotation = SIDE_ANGLES[side]; + door->sprite.offset = vector_rotated(vector_make(0, DOOR_SPRITE_INSET), SIDE_ANGLES[side]); + return door; +} + +// The room's doors' sprites shown or hidden while Hornfel's rail doors stand. +static void room_doors_fade(float alpha) +{ + for (GridEntity_Door* door : g_game->room->doors) + if (door) door->sprite.color._tint[3] = alpha; +} + +// 004b70c0 Rail doors on every edge cell a rail runs into, each paired with the first others its rail reaches, and the +// room's doors hidden. +static void hornfel_spawn_doors() +{ + Room& room = *g_game->room; + RailManager* rails = &room.railManager; + int width = room.gridWidth; + int height = room.gridHeight; + std::vector doors; + + for (int row = 1; row < height - 1; row++) + { + if (rails->can_step(room.GetGridIndexByTile(1, row), room.GetGridIndexByTile(0, row))) + doors.push_back(door_spawn(room.GetGridIndexByTile(0, row), 0)); + if (rails->can_step(room.GetGridIndexByTile(width - 2, row), room.GetGridIndexByTile(width - 1, row))) + doors.push_back(door_spawn(room.GetGridIndexByTile(width - 1, row), 2)); + } + for (int column = 1; column < width - 1; column++) + { + if (rails->can_step(room.GetGridIndexByTile(column, 1), room.GetGridIndexByTile(column, 0))) + doors.push_back(door_spawn(room.GetGridIndexByTile(column, 0), 1)); + if (rails->can_step(room.GetGridIndexByTile(column, height - 2), room.GetGridIndexByTile(column, height - 1))) + doors.push_back(door_spawn(room.GetGridIndexByTile(column, height - 1), 3)); + } + + for (size_t i = 0; i < doors.size(); i++) + { + if (doors[i]->parent) continue; + for (size_t j = i + 1; j < doors.size(); j++) + { + if (doors[j]->parent) continue; + if (!room.railManager.flood_fill(room.GetGridIndex(doors[i]->pos), room.GetGridIndex(doors[j]->pos))) + continue; + doors[i]->parent = doors[j]; + doors[j]->parent = doors[i]; + } + } + for (Entity* door : doors) door->Update(); + room_doors_fade(0); +} + +// 004b78f0 Once the room is clear: every rider of a minecart goes in a poof with its cart, every rail door in a grey +// poof, and the room's doors show again. +static void hornfel_remove_doors() +{ + std::vector doors; + std::vector riders; + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity->type == ENTITY_HORNFEL_DOOR) doors.push_back(entity); + if (entity->minecart) riders.push_back(entity); + } + + for (Entity* rider : riders) + { + uint32_t seed = Random(); + g_game->Spawn({.position = rider->pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + rider->Remove(); + rider->minecart->Remove(); + } + for (Entity* door : doors) + { + uint32_t seed = Random(); + Entity* poof = g_game->Spawn({.position = door->pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + poof->SetColor(DOOR_POOF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + door->Remove(); + } + room_doors_fade(1); +} + +// 004bb350 A random rail door with no rider for it or its pair, not one by the door the players just came in by. +static Entity* hornfel_free_door() +{ + Game& game = *g_game; + Room& room = *game.room; + std::vector candidates; + for (Entity* door : room.entityList.updateEL) + { + if (door->type != ENTITY_HORNFEL_DOOR || door->target || (door->parent && door->parent->target)) continue; + + bool isJustEntered = !room.isInitialized || game.frameCount - room.enterFrame < DOOR_ENTRY_GRACE; + if (isJustEntered && game.enterDoor >= 0) + { + Vector entrance = game.enterDoor < DOOR_SLOT_COUNT ? room.GetGridPosition(room.doorGridPositions[game.enterDoor]) + : Vector{}; + if (vector_length_squared(vector_sub(door->pos, entrance)) <= DOOR_ENTRY_CLEARANCE) continue; + } + candidates.push_back(door); + } + if (candidates.empty()) return nullptr; + return candidates[Random() % (uint32_t)candidates.size()]; +} + +// 004bc460 Hornfel's room controller (effect 152): it puts up the rail doors, sends an enemy through one in a cart +// whenever its timeout runs out while a boss lives, and takes the doors down once the room is clear. +void hornfel_room_controller(Entity_Effect& controller) +{ + Room& room = *g_game->room; + if (controller.state == 0) + { + hornfel_spawn_doors(); + controller.state = 1; + int wait = (int)(Random() % CONTROLLER_WAIT_RANGE) + CONTROLLER_WAIT; + controller.timeout = wait; + controller.lifespan = wait; + return; + } + if (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR) + { + hornfel_remove_doors(); + controller.Remove(); + } + if (room.GetAliveBossesCount() <= 0 || !controller.isDead) return; + + auto* door = static_cast(hornfel_free_door()); + if (door) + { + Vector direction = hornfel_get_rail_direction(*door); + if (!vector_is_zero(direction)) + { + uint32_t pick = Random(); + uint32_t seed = Random(); + auto [type, variant] = CART_RIDERS[pick % CART_RIDERS.size()]; + Entity* rider = g_game->Spawn({.type = type, .variant = variant, .seed = seed}); + rider->ClearEntityFlags(FLAG_APPEAR); + rider->spawnerType = ENTITY_HORNFEL; + rider->GiveMinecart(door->targetPosition, direction); + hornfel_claim_target(*door, rider); + } + } + + uint32_t wait = Random() % CONTROLLER_WAIT_RANGE + CONTROLLER_WAIT; + controller.isDead = false; + int timeout = (int)(room.gridHeight * room.gridWidth < LARGE_ROOM_CELLS ? wait : wait / 2); + controller.timeout = timeout; + controller.lifespan = timeout; +} + +// 004bb9b0 A rail door: shut until a cart on its cell or on the rail into it heads its way, then open a while. +void hornfel_door_update(Entity_NPC& door) +{ + if (door.state == NPC_STATE_INIT) + { + door.state = HORNFEL_DOOR_CLOSED; + door.ClearEntityFlags(FLAG_APPEAR); + door.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + door.entityCollisionClass = ENTCOLL_NONE; + door.targetPosition = door.pos; + door.sortingLayer = SORTING_DOOR; + door.sprite.Play("Closed"); + } + else if (door.state == HORNFEL_DOOR_CLOSED) + { + if (door.sprite.IsFinished()) door.sprite.Play("Closed"); + Room& room = *g_game->room; + RailManager* rails = &room.railManager; + int doorCell = room.GetGridIndex(door.targetPosition); + std::vector carts(room.entityList.updateEL.begin(), room.entityList.updateEL.end()); + for (Entity* entity : carts) + { + if (entity->type != ENTITY_MINECART || static_cast(entity)->state != NPC_STATE_MOVE) continue; + + int cartCell = room.GetGridIndex(entity->pos); + Vector toDoor = vector_normalized(vector_sub(room.GetGridPosition(doorCell), room.GetGridPosition(cartCell))); + float facing = vector_dot(toDoor, vector_normalized(entity->velocity)); + if (cartCell == doorCell || (rails->can_step(cartCell, doorCell) && facing > DOOR_FACING)) + hornfel_set_anim(door, DOOR_OPEN_FRAMES); + } + } + else if (door.state == HORNFEL_DOOR_OPEN) + { + if (door.sprite.IsFinished()) door.sprite.Play("Opened"); + if (door.stateFrame >= 1 && --door.stateFrame == 0) + { + door.sprite.Play("Close"); + npc_sound_play(SOUND_DOOR_HEAVY_CLOSE, DOOR_SOUND_VOLUME, HORNFEL_DOOR_SOUND_DELAY, DOOR_SOUND_PITCH); + door.state = HORNFEL_DOOR_CLOSED; + door.stateFrame = 0; + } + } + door.pos = door.targetPosition; + door.velocity = {}; +} + +// 004b7e30 Hornfel in his cart faces its way: idling, or charging in his charge. +static void hornfel_charge(Entity_NPC& npc) +{ + Vector rolling = npc.minecart->velocity; + bool isCharging = npc.state == HORNFEL_CHARGE; + if (std::abs(rolling.y) < std::abs(rolling.x)) + npc.sprite.Play(rolling.x >= 0 ? (isCharging ? "ChargeRight" : "IdleRight") : (isCharging ? "ChargeLeft" : "IdleLeft")); + else npc.sprite.Play(rolling.y >= 0 ? (isCharging ? "ChargeDown" : "IdleDown") : (isCharging ? "ChargeUp" : "IdleUp")); +} + +// 004b7ee0 A bomb Hornfel holds, hidden on him: normal, hot (burning) or sad blood, on a 35 fuse, frozen until thrown. +static Entity* hornfel_pick_spawn(Entity_NPC& npc) +{ + WeightedOutcomePicker picker; + picker.AddOutcomeWeight(BOMB_NORMAL, HELD_NORMAL_WEIGHT); + picker.AddOutcomeWeight(BOMB_HOT, HELD_HOT_WEIGHT); + picker.AddOutcomeWeight(BOMB_SAD_BLOOD, HELD_SAD_WEIGHT); + int variant = picker.PickOutcome({Random() | 1, 5, 9, 7}); + + uint32_t seed = Random(); + auto* bomb = static_cast( + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_BOMB, .variant = variant, .seed = seed})); + bomb->isVisible = false; + bomb->entityCollisionClass = ENTCOLL_NONE; + bomb->entityGridCollisionClass = GRIDCOLL_NONE; + bomb->explosionCountdown = HELD_FUSE; + bomb->explosionCountdown2 = HELD_FUSE; + bomb->parent = &npc; + if (variant == BOMB_HOT || variant == BOMB_SAD_BLOOD) + { + bomb->isLoadCostumes = true; + bomb->tearFlags = TearFlags().set(variant == BOMB_HOT ? TEAR_BURN : TEAR_SAD_BOMB); + } + bomb->AddEntityFlags(FLAG_FREEZE); + return bomb; +} + +// 004b90e0 Throws a bomb from Hornfel at a spot, faster the farther it is, shown and live. +static void hornfel_launch_toward(Entity_NPC& npc, Entity& entity, const Vector& target) +{ + float reach = std::clamp((vector_distance(npc.pos, target) - LAUNCH_NEAR) / LAUNCH_SPAN, 0.0f, 1.0f); + float speed = reach * LAUNCH_SPEED_RANGE + HORNFEL_LAUNCH_SPEED; + if (entity.variant == BOMB_HOT) speed *= LAUNCH_HOT_SHARE; + Vector heading = vector_normalized(vector_sub(target, npc.pos)); + + auto& bomb = static_cast(entity); + bomb.spawnerEntity = &npc; + bomb.spawnerType = npc.type; + bomb.spawnerVariant = (uint32_t)npc.variant; + bomb.parent = &npc; + bomb.entityCollisionClass = ENTCOLL_ALL; + bomb.isVisible = true; + bomb.fallSpeed = LAUNCH_FALL; + bomb.posOffset = vector_make(0, LAUNCH_HEIGHT); + bomb.pos = npc.pos; + bomb.ClearEntityFlags(FLAG_FREEZE); + bomb.velocity = vector_scale(heading, speed); + bomb.Update(); +} + +// 004b8ca0 Picks Hornfel's attack: one or two held bombs (facing the target, from behind when it is above) or the +// brimstone spread when its cooldown is spent. +static void hornfel_attack(Entity_NPC& npc) +{ + WeightedOutcomePicker picker; + picker.AddOutcomeWeight(ATTACK_HELD, ATTACK_HELD_WEIGHT); + picker.AddOutcomeWeight(ATTACK_DOUBLE, 1); + if (hornfel_cooldown(npc, COOLDOWN_BOMB_SPREAD) == 0) picker.AddOutcomeWeight(ATTACK_SPREAD, 1); + int attack = picker.PickOutcome({Random() | 1, 5, 9, 7}); + + Vector toTarget = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + uint8_t& isFacingFront = counter_byte(npc.projectileDelay, DELAY_FACING_FRONT); + bool isBehind = toTarget.y < ATTACK_BACK_FACING; + isFacingFront = 1; + if (attack == ATTACK_HELD) + { + npc.entityDeque[0] = hornfel_pick_spawn(npc); + if (!isBehind) npc.sprite.Play(toTarget.x >= 0 ? "Attack1Right" : "Attack1Left"); + else npc.sprite.Play(toTarget.x >= 0 ? "Attack1Right_Back" : "Attack1Left_Back"); + } + else if (attack == ATTACK_DOUBLE) + { + npc.entityDeque[0] = hornfel_pick_spawn(npc); + npc.entityDeque[1] = hornfel_pick_spawn(npc); + npc.sprite.Play(isBehind ? "Attack1Double_Back" : "Attack1Double"); + } + if (attack == ATTACK_SPREAD) + { + npc.sprite.Play("Attack2"); + npc.state = HORNFEL_BOMB_SPREAD; + hornfel_cooldown(npc, COOLDOWN_BOMB_SPREAD) = SPREAD_COOLDOWN; + } + else if (attack == ATTACK_HELD || attack == ATTACK_DOUBLE) + { + if (isBehind) isFacingFront = 0; + npc.state = HORNFEL_THROW; + } + counter_byte(npc.projectileDelay, DELAY_THROWS) = 0; +} + +// The minecart its rider leaves or enters, first set going (its own AI's first frame when new), moving or still. +static void minecart_state_set(Entity_NPC& cart, bool isMoving) +{ + if (cart.state == NPC_STATE_INIT) npc_minecart_update(cart); + cart.state = isMoving ? NPC_STATE_MOVE : NPC_STATE_IDLE; +} + +// 004b8a30 Hornfel's cart reaches the room's edge: charging, it rolls on through the next door until the charge's +// doors run out, then he waits hidden for his exit. Else he hides a while and the fly bombs he let go are freed. +static void hornfel_ride_minecart(Entity_NPC& npc) +{ + auto* cart = static_cast(npc.minecart.get()); + auto* door = static_cast(npc.entityRef.get()); + if (npc.state == HORNFEL_CHARGE && door) + { + uint8_t& doorsLeft = counter_byte(npc.projectileDelay, DELAY_THROWS); + if ((int8_t)doorsLeft > 0) + { + cart->SetMinecartPosVel(door->targetPosition, hornfel_get_rail_direction(*door)); + doorsLeft--; + npc.pos = cart->pos; + return; + } + npc.state = HORNFEL_CHARGE_EXIT; + npc.isVisible = false; + npc.entityCollisionClass = ENTCOLL_NONE; + counter_half_set(npc.stateFrame, 0, 1); + npc.targetPosition = npc.pos; + npc.shadowSize = 0; + cart->v2.x = std::min(CART_EXIT_MAX, cart->v2.x); + cart->shadowSize = 0; + return; + } + + npc.state = HORNFEL_HIDDEN; + counter_half_set(npc.stateFrame, 0, HIDE_FRAMES); + npc.isVisible = false; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.targetPosition = npc.pos; + npc.shadowSize = 0; + cart->shadowSize = 0; + for (Entity* flyBomb : entity_query(ENTITY_FLY_BOMB, -1)) + { + if (flyBomb->parent.get() != &npc) continue; + flyBomb->parent = nullptr; + flyBomb->health = std::min(flyBomb->health, FLY_BOMB_FREED_HEALTH); + } +} + +// His decoys sent in from free doors, two (three in large rooms), each in a hornfel cart claiming its door. +static void hornfel_decoys_send(Entity_NPC& npc) +{ + Room& room = *g_game->room; + int count = (room.gridHeight * room.gridWidth >= LARGE_ROOM_CELLS) + DECOYS; + for (int i = 0; i < count; i++) + { + auto* door = static_cast(hornfel_free_door()); + if (!door) break; + + uint32_t seed = Random(); + Entity* decoy = g_game->Spawn({.spawner = &npc, .type = ENTITY_HORNFEL, .variant = HORNFEL_DECOY, .seed = seed}); + decoy->ClearEntityFlags(FLAG_APPEAR); + decoy->Update(); + Entity_NPC* cart = decoy->GiveMinecart(door->targetPosition, hornfel_get_rail_direction(*door)); + cart->sprite.Load(HORNFEL_CART_ANM2, GRAPHICS_LOAD); + cart->Update(); + Entity* pair = door->parent.get(); + if (!door->target && (!pair || !pair->target)) + { + door->target = decoy; + if (pair) pair->target = decoy; + } + } +} + +// Two fly bombs let go beside him, spread 20 either way of the rail, unless bombs crowd the room or a player is near. +static void hornfel_fly_bombs_release(Entity_NPC& npc, Vector direction) +{ + size_t bombs = 0; + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity->type == ENTITY_FLY_BOMB || (entity->type == ENTITY_BOMB && entity->variant == BOMB_SMALL)) bombs++; + if (bombs > FLY_BOMB_LIMIT) return; + + PlayerManager& players = g_game->playerManager; + if (!players.playerList.empty()) + { + float nearest = DOOR_SEARCH_FLOOR; + for (size_t i = 0; i < players.playerList.size(); i++) + nearest = std::min(nearest, vector_length_squared(vector_sub(npc.pos, g_game->GetPlayer((int)i)->pos))); + if (nearest <= FLY_BOMB_PLAYER_CLEARANCE) return; + } + for (int i = 0; i < FLY_BOMBS; i++) + { + uint32_t seed = Random(); + Vector velocity = vector_rotated(direction, random_unit() * FLY_BOMB_SPREAD - FLY_BOMB_SPREAD_HALF); + Vector at = random_direction(); + Entity* flyBomb = g_game->Spawn({.position = vector_add(npc.pos, vector_scale(at, FLY_BOMB_OFFSET)), + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_FLY_BOMB, + .seed = seed}); + flyBomb->parent = &npc; + flyBomb->ClearEntityFlags(FLAG_APPEAR); + } +} + +// 004b8190 Hornfel rides back in through a free door (the one his charge left by when ending a charge): sending +// decoys, setting off on a charge, or riding in to attack. +static void hornfel_minecart(Entity_NPC& npc) +{ + Entity_NPC* door = nullptr; + if (npc.state == HORNFEL_CHARGE_EXIT && npc.entityRef) + { + door = static_cast(npc.entityRef.get()); + npc.entityRef = nullptr; + } + else + { + door = static_cast(hornfel_free_door()); + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity->type != ENTITY_HORNFEL_DOOR || entity->target.get() != &npc) continue; + entity->target = nullptr; + if (entity->parent) entity->parent->target = nullptr; + } + if (!door) + { + KAGE_LogMessage(LOG_WARN, (uint8_t*)"no doors to enter from!\n"); + counter_half_set(npc.stateFrame, 0, NO_DOOR_WAIT); + return; + } + } + + Vector direction = hornfel_get_rail_direction(*door); + if (vector_is_zero(direction)) + { + KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"exit velocity is zero\n"); + return; + } + npc.isVisible = true; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.shadowSize = npc.config->shadowSize; + auto* cart = static_cast(npc.minecart.get()); + if (!cart) return; + + minecart_state_set(*cart, true); + cart->SetMinecartPosVel(door->targetPosition, direction); + npc.pos = cart->pos; + hornfel_claim_target(*door, &npc); + auto* controller = static_cast(npc.parent.get()); + if (npc.state == HORNFEL_HIDDEN) + { + if (hornfel_cooldown(npc, COOLDOWN_SUMMON) == 0 && (Random() & ENTRY_ODDS_MASK) == 0 && + (!controller || controller->timeout > CONTROLLER_SUMMON_WAIT)) + { + Room& room = *g_game->room; + if (room.GetAliveEnemiesCount() - room.GetAliveBossesCount() < HORNFEL_SUMMON_ENEMY_LIMIT && hornfel_free_door()) + { + hornfel_decoys_send(npc); + npc.state = HORNFEL_SUMMONED; + uint32_t wait = Random(); + hornfel_cooldown(npc, COOLDOWN_SUMMON) = HORNFEL_SUMMON_COOLDOWN; + hornfel_move_timer_set(npc, (int)(wait % SUMMON_WAIT_RANGE) + HORNFEL_SUMMON_WAIT); + if (controller && controller->timeout < CONTROLLER_SUMMON_HOLD) + { + controller->timeout = CONTROLLER_SUMMON_HOLD; + controller->lifespan = CONTROLLER_SUMMON_HOLD; + } + return; + } + } + Entity* pair = door->parent.get(); + if (hornfel_cooldown(npc, COOLDOWN_CHARGE) == 0 && (Random() & ENTRY_ODDS_MASK) == 0 && pair && pair != door) + { + npc.state = HORNFEL_CHARGE; + cart->v2.x = CART_CHARGE_START; + npc.entityRef = door; + hornfel_cooldown(npc, COOLDOWN_CHARGE) = CHARGE_COOLDOWN; + counter_byte(npc.projectileDelay, DELAY_THROWS) = (uint8_t)(Random() % CHARGE_DOORS_RANGE + CHARGE_DOORS); + return; + } + } + + if (npc.state == HORNFEL_CHARGE_EXIT) + { + npc.state = HORNFEL_CHARGE_FINISH; + return; + } + npc.state = HORNFEL_RIDE; + hornfel_move_timer_set(npc, (int)(Random() % RIDE_WAIT_RANGE) + RIDE_WAIT); + if (Random() % FLY_BOMB_ODDS == 0) hornfel_fly_bombs_release(npc, direction); +} + +// His start: tied to the room's controller (spawning it if missing), two empty bomb hands, and either a decoy or +// Hornfel set in his cart, hidden until he rides in. +static void hornfel_init(Entity_NPC& npc) +{ + if (npc.variant == 0) + { + std::vector controllers = entity_query(ENTITY_EFFECT, EFFECT_HORNFEL_ROOM_CONTROLLER); + Entity* controller; + if (controllers.empty()) + { + uint32_t seed = Random(); + controller = g_game->Spawn({.type = ENTITY_EFFECT, .variant = EFFECT_HORNFEL_ROOM_CONTROLLER, .seed = seed}); + controller->Update(); + } + else controller = controllers.front(); + npc.parent = controller; + } + + npc.ClearEntityFlags(FLAG_APPEAR); + npc.sprite.GetLayer(HORNFEL_HIDDEN_LAYER)->isVisible = false; + npc.sprite.GetLayer(HORNFEL_FRONT_LAYER)->isVisible = false; + npc.stateFrame = 0; + npc.projectileCooldown = 0; + hornfel_move_timer_set(npc, 0); + counter_byte(npc.projectileDelay, DELAY_THROWS) = 0; + npc.entityDeque.resize(2); + npc.entityDeque[0] = nullptr; + npc.entityDeque[1] = nullptr; + + if (npc.variant == HORNFEL_DECOY) + { + npc.AddEntityFlags(DECOY_FLAGS); + npc.state = HORNFEL_DECOY_IDLE; + npc.isInvincible = true; + return; + } + if (!npc.minecart) npc.GiveMinecart({}, {})->sprite.Load(HORNFEL_CART_ANM2, GRAPHICS_LOAD); + hornfel_ride_minecart(npc); + hornfel_cooldown(npc, COOLDOWN_SUMMON) = START_COOLDOWN; + hornfel_cooldown(npc, COOLDOWN_CHARGE) = START_COOLDOWN; +} + +// Riding: idling in the cart at its pace, then attacking (or taunting after sending decoys) when the wait runs out. +static void hornfel_ride_update(Entity_NPC& npc, Entity_NPC& cart) +{ + const AnimationData* data = npc.sprite.animState.animData; + if (npc.sprite.IsFinished() || data->isLooping) hornfel_charge(npc); + cart.v2.x = CART_SPEED; + + int timer = hornfel_move_timer(npc); + if (timer <= 0) return; + hornfel_move_timer_set(npc, --timer); + if (timer >= 1) return; + + if (npc.state != HORNFEL_SUMMONED) return hornfel_attack(npc); + if (counter_byte(npc.projectileDelay, DELAY_FACING_FRONT)) + { + npc.sprite.Play("Taunt"); + hornfel_cooldown(npc, COOLDOWN_TAUNT) = TAUNT_COOLDOWN; + } +} + +// On foot with no door: fleeing the target's side he faces most, turning toward it and bouncing off walls. +static void hornfel_flee(Entity_NPC& npc) +{ + Entity* target = npc.GetPlayerTarget(); + Vector away = vector_sub(npc.pos, target->pos); + float best = 0; + Vector side{}; + for (auto [x, y] : RUN_SIDES) + { + Vector candidate = vector_make(x, y); + float facing = vector_dot(away, candidate); + if (best < facing) + { + best = facing; + side = candidate; + } + } + Vector aim = vector_add(target->pos, vector_scale(side, best * RUN_AIM_SHARE)); + float goal = vector_angle(vector_sub(npc.pos, aim)); + Vector heading = vector_from_angle(npc.v1.x); + npc.v1.x = angle_approach(npc.v1.x, goal, random_unit() * RUN_TURN_RANGE + RUN_TURN); + npc.velocity = vector_add(npc.velocity, vector_scale(heading, HORNFEL_RUN_SPEED * npc.speedMultiplier)); + if (!npc.isCollidesWithGrid) return; + + Vector normal = npc.gridCollisionNormal; + float into = vector_dot(normal, heading); + npc.v1.x = vector_angle(vector_sub(heading, vector_scale(normal, into * 2))); +} + +// The nearest rail door (the path check is on his own spot, as the original does). +static Entity* hornfel_door_nearest(Entity_NPC& npc) +{ + float best = DOOR_SEARCH_FLOOR; + Entity* nearest = nullptr; + for (Entity* door : g_game->room->entityList.updateEL) + { + if (door->type != ENTITY_HORNFEL_DOOR) continue; + float distance = vector_length_squared(vector_sub(npc.pos, door->pos)); + if (npc.pathfinder.HasPathToPos(npc.pos, false) && distance < best) + { + best = distance; + nearest = door; + } + } + return nearest; +} + +// On foot: running for the nearest rail door and out along its rail (out of the room his fight ends), fleeing while +// there is none, fading as he leaves the room. +static void hornfel_run_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.friction *= RUN_FRICTION; + if (std::abs(npc.velocity.y) < std::abs(npc.velocity.x)) + { + npc.sprite.Play("RunHori"); + npc.sprite.isFlipX = npc.velocity.x < 0; + } + else + { + npc.sprite.Play(npc.velocity.y >= 0 ? "RunDown" : "RunUp"); + npc.sprite.isFlipX = false; + } + int timer = hornfel_move_timer(npc); + if (timer > 0) hornfel_move_timer_set(npc, timer - npc_ticks_get(npc)); + + bool hasDoor = (bool)npc.entityRef; + int next = hasDoor ? hornfel_next_rail_index(*npc.entityRef) : -1; + bool isAtRail = (hasDoor && room.GetGridIndex(npc.pos) == next) || !room.IsPositionInRoom(npc.pos, 0); + if (!isAtRail && npc.entityRef && npc.IsFrame(RUN_PATH_CHECK, 0) && + !npc.pathfinder.HasPathToPos(room.GetGridPosition(next), false)) + npc.entityRef = nullptr; + + if (!npc.entityRef && hornfel_move_timer(npc) < 1) + { + Entity* nearest = hornfel_door_nearest(npc); + if (nearest) npc.entityRef = nearest; + if (npc.entityRef) next = hornfel_next_rail_index(*npc.entityRef); + } + + auto* door = static_cast(npc.entityRef.get()); + if (!door) hornfel_flee(npc); + else if (!isAtRail) + { + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.pathfinder.FindGridPath(room.GetGridPosition(next), RUN_PATH_SPEED, 0, DIRECT_PATH_FAR); + } + else + { + npc.entityGridCollisionClass = GRIDCOLL_NONE; + Vector direction = hornfel_get_rail_direction(*door); + npc.velocity = vector_sub(npc.velocity, vector_scale(direction, npc.speedMultiplier)); + hornfel_set_anim(*door, DOOR_RUN_FRAMES); + if (room.GetGridIndex(npc.pos) < 0) + { + room.TriggerBossDeath(npc); + npc.Remove(); + } + } + + if (room.IsPositionInRoom(npc.pos, 0)) + { + npc.sprite.color._tint[3] = 1; + return; + } + float outside = std::max({room.topLeftPos.x - npc.pos.x, npc.pos.x - room.bottomRightPos.x, + room.topLeftPos.y - npc.pos.y, npc.pos.y - room.bottomRightPos.y}); + npc.sprite.color._tint[3] = 1 - std::clamp((outside - 0) / RUN_FADE, 0.0f, 1.0f); +} + +// The throw: a held bomb at the target, leading it, the second hand next; then back to riding, taunting now and then. +static void hornfel_throw_update(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Sound")) npc.PlaySound(SOUND_FETUS_FEET, 1, 2, false, 1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_CUTE_GRUNT, 1, 2, false, 1); + Entity* target = npc.GetPlayerTarget(); + float lead = random_unit() * THROW_LEAD_RANGE + HORNFEL_THROW_LEAD; + float distance = vector_distance(npc.pos, target->pos); + Vector aimed = vector_add(target->pos, vector_scale(target->velocity, lead * distance)); + aimed = room_free_pickup_position_find({.position = aimed}); + for (size_t hand = 0; hand < 2; hand++) + { + Entity* bomb = npc.entityDeque[hand].get(); + if (!bomb) continue; + hornfel_launch_toward(npc, *bomb, aimed); + npc.entityDeque[hand] = nullptr; + break; + } + counter_byte(npc.projectileDelay, DELAY_THROWS)++; + } + if (!npc.sprite.IsFinished()) return; + + npc.state = HORNFEL_RIDE; + if (counter_byte(npc.projectileDelay, DELAY_FACING_FRONT) && hornfel_cooldown(npc, COOLDOWN_TAUNT) == 0 && + Random() % TAUNT_ODDS == 0 && npc.health / npc.maxHitPoints > TAUNT_HEALTH) + { + npc.sprite.Play("Taunt"); + hornfel_cooldown(npc, COOLDOWN_TAUNT) = TAUNT_COOLDOWN; + } +} + +// The spread: brimstone bombs thrown to spots kept apart, the first anywhere, the rest the best spread of 8 tries. +static void hornfel_spread_throw(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_CUTE_GRUNT, 1, 2, false, 1); + Room& room = *g_game->room; + std::vector spots; + int count = (room.gridHeight * room.gridWidth >= LARGE_ROOM_CELLS) + SPREAD_BOMBS; + for (int i = 0; i < count; i++) + { + Vector spot{}; + if (spots.empty()) spot = room.GetRandomPosition(SPREAD_MARGIN); + else + { + float best = SPREAD_SCORE_FLOOR; + for (int tries = SPREAD_TRIES; tries != 0; tries--) + { + Vector candidate = room.GetRandomPosition(SPREAD_MARGIN); + float spread = 0; + for (const Vector& other : spots) + { + Vector apart = vector_sub(candidate, other); + Vector axes = vector_normalized(vector_make(std::abs(apart.x), std::abs(apart.y))); + spread += std::min(axes.x, axes.y) * vector_length(apart); + } + if (best < spread) + { + spot = candidate; + best = spread; + } + } + } + spot = room_free_pickup_position_find({.position = spot, .step = SPREAD_CLEARANCE}); + uint32_t seed = Random(); + Entity* bomb = g_game->Spawn({.position = npc.pos, .type = ENTITY_BOMB, .variant = BOMB_BRIMSTONE, .seed = seed}); + hornfel_launch_toward(npc, *bomb, spot); + bomb->entityCollisionClass = ENTCOLL_PLAYERONLY; + spots.push_back(spot); + } + counter_half_set(npc.stateFrame, 1, SPREAD_REENTRY_DELAY); +} + +// The charge: building speed, dropping a bomb about him every 15 frames while inside the room. +static void hornfel_charge_update(Entity_NPC& npc, Entity_NPC& cart) +{ + hornfel_charge(npc); + cart.v2.x = std::min(cart.v2.x + CART_CHARGE_GAIN, CART_CHARGE_MAX); + if (!npc.IsFrame(CHARGE_BOMB_EVERY, (int)npc.index) || !g_game->room->IsPositionInRoom(npc.pos, CHARGE_BOMB_MARGIN)) + return; + + Vector at = random_direction(); + Vector spot = vector_add(npc.pos, vector_scale(at, random_unit())); + spot = room_free_pickup_position_find({.position = spot}); + uint32_t seed = Random(); + Entity* bomb = g_game->Spawn({.position = npc.pos, .type = ENTITY_BOMB, .seed = seed}); + hornfel_launch_toward(npc, *bomb, spot); +} + +// The charge's finish: a big burning shot at the target as the cart slows, then picks up again. +static void hornfel_charge_finish_update(Entity_NPC& npc, Entity_NPC& cart) +{ + npc.sprite.Play("ChargeFinish"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + ProjectileParams params; + params.bulletFlags |= PROJECTILE_FIRE_WAVE; + params.scale = FINISH_SHOT_SCALE; + params.color = FINISH_SHOT_COLOR; + Entity* target = npc.GetPlayerTarget(); + float distance = vector_distance(npc.pos, target->pos); + Vector aimed = vector_add(target->pos, vector_scale(target->velocity, FINISH_SHOT_LEAD * distance)); + Entity_Projectile* shot = npc.FireBossProjectiles(1, aimed, FINISH_SHOT_CURVE, params); + shot->scale = FINISH_SHOT_SCALE; + shot->fallingAccel -= FINISH_SHOT_FALL; + shot->fallingSpeed = shot->fallingSpeed * FINISH_SHOT_SLOW - FINISH_SHOT_DROP; + } + if (!npc.sprite.WasEventTriggered("Shoot")) cart.v2.x = std::max(cart.v2.x - CART_FINISH_SLOW, CART_FINISH_MIN); + else cart.v2.x = std::min(cart.v2.x + CART_FINISH_GAIN, CART_SPEED); +} + +// A decoy only takes chipped hits (any explosion sets it off at once), going off below 1.5 health. +static void hornfel_decoy_update(Entity_NPC& npc) +{ + npc.sprite.Play("DecoyIdle"); + if (npc.pendingDamage <= 0) return; + + if (npc.pendingDamageFlags & DAMAGE_EXPLOSION) + { + npc.health = 1; + npc.isDead = true; + return; + } + for (DamageEvent& event : npc.damageEvents) + { + if (event.damage > DECOY_BIG_HIT) npc.health -= Random() % DECOY_HIT_ODDS == 0 ? 3 : 2; + else if (event.damage > 0) npc.health -= Random() % DECOY_HIT_ODDS == 0 ? 2 : 1; + } + if (npc.health < 1) + { + npc.health = 1; + npc.isDead = true; + } + else if (npc.health < DECOY_DYING) npc.isDead = true; +} + +// Hornfel shrugs off explosions he did not take from a player, his own lasers and fire jets not from a player. +static void hornfel_damage_filter(Entity_NPC& npc) +{ + for (DamageEvent& event : npc.damageEvents) + { + const EntityRef& source = event.source; + bool isForeignBlast = (event.damageFlags & DAMAGE_EXPLOSION) && source.spawnerType != ENTITY_PLAYER && + source.type != ENTITY_PLAYER; + bool isOwnLaser = (event.damageFlags & DAMAGE_LASER) && source.type == npc.type; + bool isForeignJet = source.type == ENTITY_EFFECT && source.variant == EFFECT_FIRE_JET && + source.spawnerType != ENTITY_PLAYER; + if (!isForeignBlast && !isOwnLaser && !isForeignJet) continue; + npc.pendingDamage -= event.damage; + event.damage = 0; + } + if (npc.pendingDamage < 0) npc.pendingDamage = 0; +} + +// His end: a decoy blows up into troll bombs. Hornfel in his cart only loses it, his held bombs flying off, and falls +// out to run for it. +static void hornfel_death_update(Entity_NPC& npc, Entity_NPC* cart) +{ + if (npc.variant == HORNFEL_DECOY) + { + uint32_t seed = Random(); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = seed}); + seed = Random(); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_CRATER, .seed = seed})->Update(); + explosion_damage({.position = npc.pos, + .damageFlags = DAMAGE_EXPLOSION | DAMAGE_TNT, + .damage = DECOY_BLAST_DAMAGE, + .radius = DECOY_BLAST_RADIUS, + .isLineCheck = false}); + for (int i = 0; i < DECOY_TROLL_BOMBS; i++) + { + Vector at = random_direction(); + float speed = random_unit() * DECOY_TROLL_SPEED_RANGE + DECOY_TROLL_SPEED; + uint32_t bombSeed = Random(); + Entity* troll = g_game->Spawn({.position = npc.pos, .velocity = vector_scale(at, speed), .spawner = &npc, + .type = ENTITY_BOMB, .variant = BOMB_TROLL, .seed = bombSeed}); + troll->entityCollisionClass = ENTCOLL_PLAYERONLY; + } + return; + } + if (!cart || !npc.isVisible) return; + + uint32_t seed = Random(); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = seed}); + if (npc.state == HORNFEL_THROW) + for (size_t hand = 0; hand < 2; hand++) + { + Entity* bomb = npc.entityDeque[hand].get(); + if (!bomb) continue; + Vector at = random_direction(); + hornfel_launch_toward(npc, *bomb, vector_add(npc.pos, vector_scale(at, random_unit() * FALL_BOMB_SCATTER))); + npc.entityDeque[hand] = nullptr; + } + minecart_break(*cart); + npc.state = HORNFEL_FALL; + npc.sprite.Play("Sad"); + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.isDead = false; + npc.health = HORNFEL_FALL_HEALTH; + npc.entityRef = nullptr; + npc.collisionDamage = FALL_CONTACT_DAMAGE; + npc.sprite.color._tint[3] = 1; +} + +// 004b92e0 Hornfel: he rides his cart in through the rail doors to throw bombs, charges through them, sends decoys, +// and hides between passes. Brought down, his cart breaks and he runs for a door to escape. +void Entity_NPC::Hornfel_UpdateAI() +{ + auto* cart = static_cast(minecart.get()); + switch (state) + { + case NPC_STATE_INIT: + hornfel_init(*this); + break; + case HORNFEL_RIDE: + case HORNFEL_SUMMONED: + hornfel_ride_update(*this, *cart); + break; + case HORNFEL_RUN: + hornfel_run_update(*this); + break; + case HORNFEL_HIDDEN: + case HORNFEL_CHARGE_EXIT: + { + isVisible = false; + entityCollisionClass = ENTCOLL_NONE; + if (child) break; + int wait = counter_half_get(stateFrame, 0); + if (wait != 0) counter_half_set(stateFrame, 0, wait - 1); + else if (counter_half_get(stateFrame, 1) < 1) hornfel_minecart(*this); + break; + } + case HORNFEL_THROW: + hornfel_throw_update(*this); + break; + case HORNFEL_BOMB_SPREAD: + if (sprite.IsEventTriggered("Shoot")) hornfel_spread_throw(*this); + break; + case HORNFEL_CHARGE: + hornfel_charge_update(*this, *cart); + break; + case HORNFEL_CHARGE_FINISH: + hornfel_charge_finish_update(*this, *cart); + break; + case HORNFEL_DETONATE: + sprite.Play("Detonate"); + if (sprite.IsEventTriggered("Sound")) PlaySound(SOUND_SHELLGAME, 1, 2, false, 1); + if (sprite.IsEventTriggered("Shoot")) PlaySound(SOUND_BUTTON_PRESS, 1, 2, false, 1); + break; + case HORNFEL_FALL: + friction *= FALL_FRICTION; + if (!sprite.IsFinished()) break; + state = HORNFEL_RUN; + hornfel_move_timer_set(*this, FALL_RUN_WAIT); + v1.x = vector_angle(vector_sub(pos, GetPlayerTarget()->pos)); + break; + case HORNFEL_DECOY_IDLE: + hornfel_decoy_update(*this); + break; + default: + break; + } + + int reentry = counter_half_get(stateFrame, 1); + if (reentry > 0) counter_half_set(stateFrame, 1, reentry - 1); + hornfel_damage_filter(*this); + if (GetIntervalTicks(3, 0)) + for (int which = COOLDOWN_BOMB_SPREAD; which <= COOLDOWN_TAUNT; which++) + { + uint8_t& cooldown = hornfel_cooldown(*this, (HornfelCooldown)which); + if (cooldown != 0) cooldown--; + } + if (isDead) hornfel_death_update(*this, cart); +} + +// 004bb0e0, 004bc450 Hornfel's per-frame step: a charge holds its door and the pair open, a hidden Hornfel parks his +// cart where he left, and a cart off the grid takes him on to his next door or into hiding. +void Entity_NPC::Hornfel_UpdateFrame() +{ + auto* cart = static_cast(minecart.get()); + if (state == HORNFEL_CHARGE && entityRef) + { + auto* door = static_cast(entityRef.get()); + hornfel_set_anim(*door, DOOR_CHARGE_FRAMES); + if (door->parent) hornfel_set_anim(*static_cast(door->parent.get()), DOOR_CHARGE_FRAMES); + } + if (!cart) return; + + if (!isVisible) + { + minecart_state_set(*cart, false); + cart->pos = targetPosition; + cart->velocity = {}; + return; + } + Room& room = *g_game->room; + int column = (int)((cart->pos.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + HALF); + int row = (int)((cart->pos.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + HALF); + if (column < 0 || column > room.gridWidth - 1 || row < 0 || row > room.gridHeight - 1) hornfel_ride_minecart(*this); +} diff --git a/src/boss_loki.cpp b/src/boss_loki.cpp index 8b987e1..17de7de 100644 --- a/src/boss_loki.cpp +++ b/src/boss_loki.cpp @@ -4,7 +4,6 @@ #include "sfx_manager.h" // Lokii, the twin Loki (its variant). The second of a pair starts hidden and mirrored (its i1 2). -constexpr int LOKII = 1; constexpr int LOKII_HIDDEN_TWIN = 2; // Loki's next move from its walk: a teleport 1 in 40 with a player within 300, a ring of eight 1 in 140, a cross of diff --git a/src/boss_mom.cpp b/src/boss_mom.cpp index 2ca61a9..3b5e9e2 100644 --- a/src/boss_mom.cpp +++ b/src/boss_mom.cpp @@ -21,7 +21,6 @@ enum MomSubtype }; // The foot stomping in the middle of the room (its variant). The parts in the doors keep variant 0. -constexpr int MOM_STOMP = 10; // Where Mom's parts look in through the doors: left, top, right and bottom, 15 into the room. static const std::array MOM_DOOR_SPOTS = {vector_make(40, 280), vector_make(320, 120), @@ -166,13 +165,6 @@ void damage_radius(const RadiusDamage& hit) } } -// The frames since the room started, or -1 before it did. -static int room_frames_get() -{ - Room& room = *g_game->room; - return room.isInitialized ? g_game->frameCount - room.enterFrame : -1; -} - // The pitch Mom's voice takes for her champion size. static float voice_pitch_get(Entity_NPC& npc) { @@ -308,7 +300,7 @@ static bool is_player_near_door(Entity_NPC& npc) // stomps for the Mausoleum's, or a laugh when the roll or a player near a door says no. static void stomp_start(Entity_NPC& npc) { - int roomFrames = room_frames_get(); + int roomFrames = g_game->room->GetFrameCount(); bool isStarting = roomFrames < ROOM_START_FRAMES; bool isWanted = Random() % 3 == 0 || npc.subtype == MOM_RED || isStarting; if (!isStarting && (!isWanted || is_player_near_door(npc))) @@ -438,7 +430,7 @@ static void mom_death(Entity_NPC& npc) // The foot: from rest it stomps when its cooldown is out, then plays out the stomp. static void foot_update(Entity_NPC& npc) { - int roomFrames = room_frames_get(); + int roomFrames = g_game->room->GetFrameCount(); int odds = npc.subtype == MOM_RED ? STOMP_ODDS_RED : STOMP_ODDS; bool isReady = npc.projectileCooldown == 0 && roomFrames > ROOM_SETTLE_FRAMES && (random_below(odds) == 0 || roomFrames < ROOM_START_FRAMES) && npc.state == NPC_STATE_IDLE; @@ -455,8 +447,8 @@ static void foot_update(Entity_NPC& npc) if (npc.isDead) mom_death(npc); } -// Sets an eye laser sweeping at once by an angle each frame at a speed, if it is still a laser. -static void eye_laser_sweep(Entity* entity, float degrees, float speed) +// Sets a laser sweeping at once by an angle each frame at a speed, if it is still a laser. +void laser_sweep_set(Entity* entity, float degrees, float speed) { if (!entity || entity->type != ENTITY_LASER) return; @@ -470,15 +462,15 @@ static void eye_laser_sweep(Entity* entity, float degrees, float speed) // 004d2f50 The eye lasers' first turn: the first sweeps back, the second on. static void eye_lasers_turn(Entity_Effect* timer) { - eye_laser_sweep(timer->child, -EYE_LASER_TURN, -EYE_LASER_SWEEP_SPEED); - eye_laser_sweep(timer->target, EYE_LASER_TURN, EYE_LASER_SWEEP_SPEED); + laser_sweep_set(timer->child, -EYE_LASER_TURN, -EYE_LASER_SWEEP_SPEED); + laser_sweep_set(timer->target, EYE_LASER_TURN, EYE_LASER_SWEEP_SPEED); } // 004d2fd0 The eye lasers' second turn, the other way. static void eye_lasers_back(Entity_Effect* timer) { - eye_laser_sweep(timer->child, EYE_LASER_TURN, EYE_LASER_SWEEP_SPEED); - eye_laser_sweep(timer->target, -EYE_LASER_TURN, -EYE_LASER_SWEEP_SPEED); + laser_sweep_set(timer->child, EYE_LASER_TURN, EYE_LASER_SWEEP_SPEED); + laser_sweep_set(timer->target, -EYE_LASER_TURN, -EYE_LASER_SWEEP_SPEED); } // Fires the Mausoleum's two eye lasers out of the door, sweeping apart, with timers to turn them. @@ -496,7 +488,7 @@ static void eye_lasers_fire(Entity_NPC& npc) .timeout = EYE_LASER_TIMEOUT, .variant = EYE_LASER_VARIANT}); lasers[i]->renderDepthOffset = depth; - eye_laser_sweep(lasers[i], side * EYE_LASER_SWEEP, side * EYE_LASER_SWEEP_SPEED); + laser_sweep_set(lasers[i], side * EYE_LASER_SWEEP, side * EYE_LASER_SWEEP_SPEED); lasers[i]->Update(); } @@ -553,7 +545,7 @@ static bool is_player_in_arm_reach(Entity_NPC& npc) static void part_choose(Entity_NPC& npc) { Entity_NPC& foot = *npc.ParentNPC(); - int roomFrames = room_frames_get(); + int roomFrames = g_game->room->GetFrameCount(); bool isSettled = roomFrames > ROOM_START_FRAMES; bool isArmReady = npc.state != NPC_STATE_ATTACK2 && npc.state != NPC_STATE_ATTACK4 && foot.state != NPC_STATE_STOMP && foot.state != NPC_STATE_JUMP && npc.subtype != MOM_MAUSOLEUM; @@ -613,7 +605,8 @@ static void part_update(Entity_NPC& npc, int prevState) if (npc.state != NPC_STATE_ATTACK2 && npc.size > npc.config->collisionRadius) npc.SetSize(npc.config->collisionRadius, npc.config->collisionRadiusMulti, npc.config->gridCollisionPoints); - if (npc.IsFrame(PART_CHECK_FRAMES, (int)npc.index) && room_frames_get() > ROOM_START_FRAMES) part_choose(npc); + if (npc.IsFrame(PART_CHECK_FRAMES, (int)npc.index) && g_game->room->GetFrameCount() > ROOM_START_FRAMES) + part_choose(npc); if (npc.state == NPC_STATE_IDLE) npc.entityCollisionClass = ENTCOLL_NONE; else @@ -624,7 +617,7 @@ static void part_update(Entity_NPC& npc, int prevState) if (npc.state == NPC_STATE_ATTACK3 && sprite.animState.animData && sprite.IsEventTriggered("Shoot")) part_summon(npc); bool isEyeShot = npc.state == NPC_STATE_ATTACK && npc.subtype == MOM_RED && - room_frames_get() >= EYE_SHOT_SETTLE_FRAMES && sprite.IsEventTriggered("Shoot"); + g_game->room->GetFrameCount() >= EYE_SHOT_SETTLE_FRAMES && sprite.IsEventTriggered("Shoot"); if (isEyeShot) { Vector velocity = vector_resized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos), EYE_SHOT_SPEED); diff --git a/src/boss_moms_heart.cpp b/src/boss_moms_heart.cpp index a85a58f..9872f70 100644 --- a/src/boss_moms_heart.cpp +++ b/src/boss_moms_heart.cpp @@ -6,6 +6,9 @@ #include "entity_projectile.h" #include "grid_entity_trap_door.h" #include "level.h" +#include "manager.h" +#include "music_manager.h" +#include "room_render.h" #include "room_grid.h" #include "sfx_manager.h" #include @@ -793,6 +796,81 @@ static void heart_animation_update(Entity_NPC& npc) return; } } +// The Mausoleum's escape: a tremor and the music cut, every other room of the floor (but the ultra secret room and the +// lil portal's) cleared and shown with its pickups gone and its fires burnt down, and the last boss room filled with +// 5 flies and 50 bugs, flies and beetles within 40 of random cells. +constexpr int ESCAPE_SHAKE = 50; +constexpr float ESCAPE_TREMOR_VOLUME = 1.8f; +constexpr float ESCAPE_TREMOR_PITCH = 0.8f; +constexpr float ESCAPE_MUSIC_FADE = 0.08f; +constexpr uint32_t ESCAPE_DISPLAY_FLAGS = ROOM_DISPLAY_BOX | ROOM_DISPLAY_ICON; +constexpr uint32_t ESCAPE_ROOM_FLAGS = ROOM_DESCRIPTOR_FLAG_CLEAR | ROOM_DESCRIPTOR_FLAG_CHALLENGE_DONE; +constexpr int ESCAPE_FLIES = 5; +constexpr int ESCAPE_CRITTERS = 50; +constexpr float ESCAPE_CRITTER_SCATTER = 40; +constexpr float ESCAPE_FLY_STORAGE = 3; +constexpr uint32_t ESCAPE_RNG_SHIFT_INDEX = 4; +constexpr std::array ESCAPE_CRITTER_VARIANTS = {EFFECT_TINY_BUG, EFFECT_TINY_FLY, EFFECT_BEETLE}; + +// A saved critter of the escape at a random cell inside the boss room, scattered within 40 of it. +static void escape_critter_save(RoomDescriptor& bossRoom, RNG& rng, EntitySaveState state) +{ + Room& room = *g_game->room; + int column = (int)rng.RandomInt((uint32_t)bossRoom.data->width - 2) + 1; + int row = (int)rng.RandomInt((uint32_t)bossRoom.data->height - 2) + 1; + if (state.type == ENTITY_EFFECT) state.variant = ESCAPE_CRITTER_VARIANTS[rng.Next() % ESCAPE_CRITTER_VARIANTS.size()]; + state.initSeed = rng.Next(); + state.dropSeed = state.initSeed; + Vector cell = room.GetGridPosition(room.GetGridIndexByTile(column, row)); + Vector heading = RandomVector(rng.Next()); + float scatter = rng.RandomFloat() * ESCAPE_CRITTER_SCATTER; + state.targetPosition = vector_add(cell, vector_scale(heading, scatter)); + bossRoom.savedEntities.push_back(state); +} + +// 004d64f0 Mom's Heart killed in the Mausoleum, once a run: the floor gives way for the escape to the Corpse. +static void heart_mausoleum_escape() +{ + Game& game = *g_game; + if (game.gameStateFlags & (1ull << GAME_STATE_MAUSOLEUM_HEART_KILLED)) return; + + game_shake_screen(ESCAPE_SHAKE); + npc_sound_play(SOUND_GROUND_TREMOR, ESCAPE_TREMOR_VOLUME, 2, ESCAPE_TREMOR_PITCH); + MusicManager& music = g_manager->musicManager; + music.channels[music.currentChannel].targetVolume = 0; + music.channels[music.currentChannel].fadeRate = ESCAPE_MUSIC_FADE; + music.queuedMusicId = 0; + game.gameStateFlags |= 1ull << GAME_STATE_MAUSOLEUM_HEART_KILLED; + + for (RoomDescriptor& descriptor : game.roomList) + { + if (!descriptor.data || &descriptor == game.room->descriptor || descriptor.data->type == ROOM_ULTRASECRET || + descriptor.gridIndex == ROOM_LIL_PORTAL_IDX) + continue; + descriptor.flags |= ESCAPE_ROOM_FLAGS; + descriptor.displayFlags |= ESCAPE_DISPLAY_FLAGS; + if (descriptor.visitedCount == 0) descriptor.visitedCount = 1; + std::erase_if(descriptor.savedEntities, [](const EntitySaveState& saved) { return saved.type == ENTITY_PICKUP; }); + for (EntitySaveState& saved : descriptor.savedEntities) + if (saved.type == ENTITY_FIREPLACE) saved.intStorage1 = 1; + } + + RoomDescriptor& bossRoom = game.roomList[game.lastBossRoomListIdx]; + if (bossRoom.data && (bossRoom.flags & ROOM_DESCRIPTOR_FLAG_CLEAR)) + { + RNG rng; + rng.SetSeed(bossRoom.spawnSeed, ESCAPE_RNG_SHIFT_INDEX); + EntitySaveState fly; + fly.type = ENTITY_FLY; + fly.floatStorage1 = ESCAPE_FLY_STORAGE; + for (int i = 0; i < ESCAPE_FLIES; i++) escape_critter_save(bossRoom, rng, fly); + EntitySaveState critter; + critter.type = ENTITY_EFFECT; + for (int i = 0; i < ESCAPE_CRITTERS; i++) escape_critter_save(bossRoom, rng, critter); + } + game.UpdateVisibility(); +} + // Whether the heart's death takes an entity with it: an enemy (or a versus player) that holds the doors, not Mother's // ball or a friendly one. @@ -819,7 +897,7 @@ static void heart_death(Entity_NPC& npc) bool isMausoleum = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; if (isMausoleum && !npc.HasEntityFlags(FLAG_FRIENDLY) && game.currentRoomIdx == ROOM_SECRET_EXIT_IDX) - reconstruction_missing("NpcAI::ENTITY_MOMS_HEART_mausoleum_death 004d64f0 (the Mausoleum's escape)"); + heart_mausoleum_escape(); } // 004d48b0 NpcAI::ENTITY_MOMS_HEART: Mom's Heart and It Lives, set in the room's flesh. Beating at a pace its health diff --git a/src/boss_mother.cpp b/src/boss_mother.cpp index d770b50..309cd2f 100644 --- a/src/boss_mother.cpp +++ b/src/boss_mother.cpp @@ -863,8 +863,8 @@ static void mother_pound_update(Entity_NPC& npc) Entity* ball = npc.entityRef; if (ball) { - Vector toFist = - vector_sub(vector_add(vector_add(npc.GetNullOffset("ShootPos"), npc.pos), {0, BALL_SWING_LINE}), ball->pos); + Vector fistLine = vector_add(vector_add(npc.GetNullOffset("ShootPos"), npc.pos), vector_make(0, BALL_SWING_LINE)); + Vector toFist = vector_sub(fistLine, ball->pos); Vector pulled = vector_add(ball->targetPosition, vector_resized(toFist, BALL_POUND_PULL)); ball->targetPosition = vector_resized(pulled, vector_length(ball->targetPosition)); } diff --git a/src/boss_mothers_shadow.cpp b/src/boss_mothers_shadow.cpp new file mode 100644 index 0000000..2fcf10d --- /dev/null +++ b/src/boss_mothers_shadow.cpp @@ -0,0 +1,348 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "entity_effect_combat.h" +#include "entity_list.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "grid_entity_door.h" +#include "level.h" +#include "manager.h" +#include "npc_fireplace.h" +#include "music_manager.h" +#include "room_config.h" +#include + +// Mother's Shadow's states: rising through the floor, chasing, gone once the players leave the mineshaft, dashing at +// its target, and waiting hidden for the item in its room to be taken. +constexpr int SHADOW_APPEAR = NPC_STATE_APPEAR_CUSTOM; +constexpr int SHADOW_CHASE = NPC_STATE_IDLE; +constexpr int SHADOW_GONE = NPC_STATE_SUICIDE; +constexpr int SHADOW_DASH = NPC_STATE_ATTACK; +constexpr int SHADOW_WAIT = NPC_STATE_SPECIAL; + +// The mineshaft's room subtypes: the escape's rooms (swapped for the next variant once she appears) and the room the +// shadow's escape ends in. +constexpr int MINESHAFT_ESCAPE_SUBTYPE = 30; +constexpr int MINESHAFT_EXIT_SUBTYPE = 10; +constexpr int MINESHAFT_DIMENSION = 1; + +// While she is out: the screen shakes and one frame in three a rock falls from 200 to 280 up somewhere in the room, +// fading in over 15. She only touches players 45 frames into a room. +constexpr int SHADOW_SHAKE = 4; +constexpr uint32_t ROCK_ODDS = 3; +constexpr float ROCK_SCALE = 0.8f; +constexpr float ROCK_SCALE_RANGE = 0.2f; +constexpr float ROCK_HEIGHT = -200; +constexpr float ROCK_HEIGHT_RANGE = 80; +constexpr ColorMod ROCK_FADE_COLOR = {{1, 1, 1, 0}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int ROCK_FADE_FRAMES = 15; +constexpr int SHADOW_TOUCH_GRACE = 44; +constexpr int SHADOW_GONE_SHAKE = 14; +constexpr int SHADOW_GONE_FRAMES = 29; + +// Her start: hidden, untouchable, out of the boss bar, until the item is taken. Then she appears after 30 frames, +// the fires turned red, and chases. +constexpr uint64_t SHADOW_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_BOSSDEATH_TRIGGERED | FLAG_NO_KNOCKBACK | + FLAG_NO_PHYSICS_KNOCKBACK | FLAG_DONT_COUNT_BOSS_HP | FLAG_HIDE_HP_BAR; +constexpr uint64_t SHADOW_PUSH_FLAGS = FLAG_NO_KNOCKBACK | FLAG_NO_PHYSICS_KNOCKBACK; +constexpr int SHADOW_APPEAR_WAIT = 30; +constexpr int SHADOW_START_COOLDOWN = 60; +constexpr float SHADOW_MUSIC_FADE = 0.08f; + +// The chase: past 80 from its target it speeds up to 6 by its distance over 600; within 200 it dashes when rested. +constexpr float SHADOW_CHASE_FRICTION = 0.8f; +constexpr float CHASE_NEAR_SQUARED = 6400; +constexpr float CHASE_SHARE = 0.01f; +constexpr float CHASE_FAR = 600; +constexpr float SHADOW_CHASE_SPEED = 6; +constexpr float DASH_REACH = 200; + +// The dash: it hovers 180 off its target while winding up, aims after 14 frames and charges at 6, trailing black dust +// every 3 frames, then rests 90. +constexpr float DASH_HOVER = 180; +constexpr int DASH_AIM_FRAME = 14; +constexpr float SHADOW_DASH_SPEED = 6; +constexpr int SHADOW_DASH_REST = 90; +constexpr ColorMod DUST_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float DUST_DRAG = 0.1f; +constexpr float DUST_RISE = -2; +constexpr float DUST_RISE_RANGE = 6; +constexpr float SHADOW_DUST_SPIN = 10; +constexpr float SHADOW_DUST_SPIN_MIN = 2; +constexpr uint32_t SHADOW_DUST_TIMEOUT_RANGE = 10; +constexpr int SHADOW_DUST_TIMEOUT = 10; +constexpr float SHADOW_DUST_SCALE = 1.5f; +constexpr float DUST_SCALE_RANGE = 0.5f; +constexpr int DUST_DEPTH = -2000; + +// The mineshaft's escape begins: its rooms are swapped for their next variant, emptied and unvisited. +static void mineshaft_escape_rooms_swap() +{ + Game& game = *g_game; + game.levelStateFlags |= 1u << LEVEL_STATE_MINESHAFT_ESCAPE; + for (int i = 0; i < game.nbRooms; i++) + { + RoomDescriptor& descriptor = game.roomList[i]; + RoomConfig_Room* data = descriptor.data; + if (descriptor.dimension != MINESHAFT_DIMENSION || !data || data->type != ROOM_DEFAULT || + data->subtype != MINESHAFT_ESCAPE_SUBTYPE) + continue; + descriptor.data = game.roomConfig.GetRoomByStageTypeAndVariant(data->stageId, ROOM_DEFAULT, data->variant + 1, + ROOM_MODE_CURRENT); + descriptor.savedEffects.clear(); + descriptor.savedEntities.clear(); + std::fill(descriptor.savedGridEntities.begin(), descriptor.savedGridEntities.end(), GRID_SAVE_EMPTY); + descriptor.restrictedGridIndexes.clear(); + descriptor.visitedCount = 0; + } +} + +// Her start in the chase: shown, pushable and harmless to the room's doors. +static void shadow_chase_start(Entity_NPC& npc) +{ + npc.sprite.Play("Idle"); + npc.ClearEntityFlags(SHADOW_PUSH_FLAGS); + npc.state = SHADOW_CHASE; + npc.i1 = SHADOW_START_COOLDOWN; + npc.entityCollisionClass = ENTCOLL_PLAYERONLY; + npc.isCanShutDoors = false; +} + +// Her pre-update while out: the rumble and falling rocks, and her end once the players leave the mineshaft (barring +// its exit room's mineshaft doors). +static void shadow_pre_update(Entity_NPC& npc) +{ + Game& game = *g_game; + Room& room = *game.room; + bool isSettled = room.GetFrameCount() > SHADOW_TOUCH_GRACE; + if (npc.state == SHADOW_CHASE || npc.state == SHADOW_DASH) + npc.entityCollisionClass = isSettled ? ENTCOLL_PLAYERONLY : ENTCOLL_NONE; + if (npc.state == SHADOW_WAIT) return; + + game_shake_screen(SHADOW_SHAKE); + if (npc.state == SHADOW_GONE) return; + if (Random() % ROCK_ODDS == 0) + { + Vector spot = room.GetRandomPosition(0); + uint32_t seed = Random(); + auto* rock = static_cast(g_game->Spawn({.position = spot, + .subType = room.backdropType | ROCK_PARTICLE_BOUNCY, + .type = ENTITY_EFFECT, + .variant = EFFECT_ROCK_PARTICLE, + .seed = seed})); + float scale = random_unit() * ROCK_SCALE_RANGE + ROCK_SCALE; + rock->sprite.scale = vector_make(scale, scale); + rock->height = ROCK_HEIGHT - random_unit() * ROCK_HEIGHT_RANGE; + rock->SetColor(ROCK_FADE_COLOR, ROCK_FADE_FRAMES, COLOR_PRIORITY_DEFAULT, true, true); + rock->Update(); + } + if (game.currentDimensionIdx != 0) return; + + npc.state = SHADOW_GONE; + npc.stateFrame = 0; + npc_sound_play(SOUND_MOTHERSHADOW_END, 1, 2, 1); + npc_sound_play(SOUND_GROUND_TREMOR, 1, 2, 1); + npc.isVisible = false; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isCanShutDoors = true; + RoomConfig_Room* data = room.descriptor->data; + if (!game.HasAbandonedMineshaft() || data->type != ROOM_DEFAULT || data->subtype != MINESHAFT_EXIT_SUBTYPE) return; + for (GridEntity_Door* door : room.doors) + if (door && (door->doorFlags & DOOR_FLAG_MINESHAFT) && door->variant != DOOR_LOCKED_BARRED) door->Bar(); +} + +// Her start: hidden and waiting for the room's item, or chasing at once where she was not placed by the room. +static void shadow_init(Entity_NPC& npc) +{ + npc.AddEntityFlags(SHADOW_FLAGS); + npc.ClearEntityFlags(FLAG_APPEAR); + npc.isInvincible = true; + npc.state = SHADOW_WAIT; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isVisible = false; + npc.sprite.SetFrame("Appear", 0); + npc.targetPosition = npc.pos; + g_game->room->entityList.AddPersistentEntity(&npc); + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + npc.i1 = 0; + if (npc.spawnGridIndex < 0) + { + shadow_chase_start(npc); + npc.stateFrame = 0; + return; + } + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity->type == ENTITY_PICKUP && entity->variant == PICKUP_COLLECTIBLE) + { + npc.entityRef = entity; + return; + } +} + +// Rising: the room's fires turn red as she comes up, and the mineshaft's escape begins. +static void shadow_appear_update(Entity_NPC& npc) +{ + if (npc.projectileDelay >= 1) + { + if (--npc.projectileDelay >= 1) return; + npc.sprite.Play("Appear", PLAY_FORCED); + npc.isVisible = true; + for (Entity* fire : entity_query(ENTITY_FIREPLACE, -1)) + { + fire->isDead = true; + fire->Update(); + } + return; + } + + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (npc.sprite.IsEventTriggered("Shoot")) + { + for (Entity* entity : entity_query(ENTITY_FIREPLACE, -1)) + { + auto* fire = static_cast(entity); + fire->Morph(ENTITY_FIREPLACE, FIRE_RED, 0, -1); + fire->state = FIRE_STATE_RELIGHT; + fire->Update(); + } + npc_sound_play(SOUND_MOTHERSHADOW_APPEAR, 1, 2, 1); + } + if (!npc.sprite.IsFinished()) return; + shadow_chase_start(npc); + mineshaft_escape_rooms_swap(); +} + +// The chase: catching up the farther she is, dashing once rested and near. +static void shadow_chase_update(Entity_NPC& npc, int ticks) +{ + npc.isVisible = true; + npc.friction *= SHADOW_CHASE_FRICTION; + Entity* target = npc.GetPlayerTarget(); + Vector toTarget = vector_sub(npc.CalcTargetPosition(0), npc.pos); + float distance = vector_length(toTarget); + if (npc.i1 > 0) npc.i1 -= ticks; + npc.friction *= SHADOW_CHASE_FRICTION; + npc.projectileDelay -= ticks; + + float apartSquared = vector_length_squared(vector_sub(target->pos, npc.pos)); + if (apartSquared > CHASE_NEAR_SQUARED) + { + float speed = std::clamp((std::sqrt(apartSquared) - 0) / CHASE_FAR, 0.0f, 1.0f) * SHADOW_CHASE_SPEED + 0; + npc_push(npc, vector_resized(vector_scale(toTarget, CHASE_SHARE), speed)); + } + if (npc.i1 >= 1 || distance >= DASH_REACH) return; + + npc.sprite.Play("Attack"); + npc.state = SHADOW_DASH; + npc.stateFrame = 0; + npc.target = target; + npc.targetPosition = {}; +} + +// A puff of black dust behind her dash. +static void shadow_dust_spawn(Entity_NPC& npc) +{ + Vector at = vector_add(vector_add(npc.pos, npc.posOffset), npc.GetNullOffset("*0")); + uint32_t seed = Random(); + Vector velocity = vector_make(npc.velocity.x * DUST_DRAG + 0, + (DUST_RISE - random_unit() * DUST_RISE_RANGE) + npc.velocity.y * DUST_DRAG); + auto* dust = static_cast(g_game->Spawn( + {.position = at, .velocity = velocity, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = seed})); + dust->sprite.GetLayer(0)->color = DUST_COLOR; + dust->rotation = random_unit() * SHADOW_DUST_SPIN + SHADOW_DUST_SPIN_MIN; + int timeout = (int)(Random() % SHADOW_DUST_TIMEOUT_RANGE) + SHADOW_DUST_TIMEOUT; + dust->timeout = timeout; + dust->lifespan = timeout; + float scale = random_unit() * DUST_SCALE_RANGE + SHADOW_DUST_SCALE; + dust->renderZOffset = DUST_DEPTH; + dust->sprite.scale = vector_make(scale, scale); +} + +// The dash: winding up hovering off the target, aiming, charging with a trail of dust, then resting. +static void shadow_dash_update(Entity_NPC& npc, int ticks) +{ + if (npc.stateFrame == 0) npc_sound_play(SOUND_MOTHERSHADOW_CHARGE_UP, 1, 2, 1); + if (npc.sprite.WasEventTriggered("ShootEnd")) + { + npc.friction *= SHADOW_CHASE_FRICTION; + if (!npc.sprite.IsFinished()) return; + npc.sprite.Play("Idle"); + npc.state = SHADOW_CHASE; + npc.i1 = SHADOW_DASH_REST; + return; + } + + if (npc.sprite.WasEventTriggered("Shoot")) + { + if (npc.sprite.IsEventTriggered("Shoot")) npc_sound_play(SOUND_MOTHERSHADOW_DASH, 1, 2, 1); + npc.friction *= SHADOW_CHASE_FRICTION; + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, SHADOW_DASH_SPEED * npc.speedMultiplier)); + if (npc.GetIntervalTicks(3, 0)) shadow_dust_spawn(npc); + npc.stateFrame += ticks; + return; + } + + npc.friction *= SHADOW_CHASE_FRICTION; + Vector aim; + if (!npc.target) aim = npc.GetPlayerTarget()->pos; + else + { + aim = npc.CalcTargetPosition(0); + Vector hover = vector_add(aim, vector_resized(vector_sub(npc.pos, aim), DASH_HOVER)); + npc_push(npc, vector_scale(vector_sub(hover, npc.pos), CHASE_SHARE)); + } + npc.stateFrame += ticks; + if (npc.stateFrame > DASH_AIM_FRAME && vector_is_zero(npc.targetPosition)) + npc.targetPosition = vector_normalized(vector_sub(aim, npc.pos)); + if (npc.sprite.IsEventTriggered("Shoot")) npc.stateFrame = 0; +} + +// Waiting for the room's item: once taken (and no player still holds it up) the music changes and she rises. +static void shadow_wait_update(Entity_NPC& npc) +{ + npc.pos = npc.targetPosition; + Entity* item = npc.entityRef.get(); + if (item && !item->isDead && item->subtype != 0) return; + + if (npc.i1 == 0) + { + npc.i1 = 1; + MusicManager& music = g_manager->musicManager; + music.Crossfade(MUSIC_MOTHERS_SHADOW_INTRO, SHADOW_MUSIC_FADE); + if (music.tracks.size() > MUSIC_MINESHAFT_ESCAPE) music.queuedMusicId = MUSIC_MINESHAFT_ESCAPE; + } + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->queuedItem.item) return; + npc.state = SHADOW_APPEAR; + npc.projectileDelay = SHADOW_APPEAR_WAIT; +} + +// 0056ffa0 Mother's Shadow: in the mineshaft, once its item is taken, she rises and chases the players through the +// escape, dashing at them, until they climb out. +void boss_mothers_shadow_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return shadow_pre_update(npc); + + switch (npc.state) + { + case NPC_STATE_INIT: + return shadow_init(npc); + case SHADOW_APPEAR: + return shadow_appear_update(npc); + case SHADOW_CHASE: + return shadow_chase_update(npc, ticks); + case SHADOW_GONE: + npc.stateFrame += ticks; + if (npc.stateFrame > SHADOW_GONE_FRAMES) npc.Remove(); + game_shake_screen(SHADOW_GONE_SHAKE); + return; + case SHADOW_DASH: + return shadow_dash_update(npc, ticks); + case SHADOW_WAIT: + return shadow_wait_update(npc); + default: + return; + } +} diff --git a/src/boss_peep.cpp b/src/boss_peep.cpp index 352e4ff..9ed4ea2 100644 --- a/src/boss_peep.cpp +++ b/src/boss_peep.cpp @@ -13,7 +13,6 @@ // Peep (variant 0) and the Bloat (variant 1), their yellow/green subtype, and their eyes (variant + 10). An eye of // subtype 99 lives on its own until the room is won. constexpr int BLOAT = 1; -constexpr int PEEP_EYE_FIRST = 10; constexpr int PEEP_YELLOW = 1; constexpr int PEEP_LONE_EYE = 99; diff --git a/src/boss_raglich.cpp b/src/boss_raglich.cpp new file mode 100644 index 0000000..8bd8d94 --- /dev/null +++ b/src/boss_raglich.cpp @@ -0,0 +1,645 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_effect_combat.h" +#include "entity_laser.h" +#include "grid_entity.h" +#include "manager.h" +#include "npc_fireplace.h" +#include "npc_basement.h" +#include +#include + +// Raglich's forms, by variant: Raglich and the arms he summons to slam the floor. +constexpr int RAGLICH_ARM = 1; + +// His states: rising, walking along the walls, dashing across and the alternate dash, his brimstone, summoning a +// creep, his first and second phase summons. +constexpr int RAGLICH_APPEAR = NPC_STATE_APPEAR; +constexpr int RAGLICH_WALK = NPC_STATE_IDLE; +constexpr int RAGLICH_DASH = NPC_STATE_JUMP; +constexpr int RAGLICH_DASH_ALT = NPC_STATE_STOMP; +constexpr int RAGLICH_BRIMSTONE = NPC_STATE_ATTACK; +constexpr int RAGLICH_SUMMON = NPC_STATE_SUMMON; +constexpr int RAGLICH_FIRES = NPC_STATE_SUMMON2; +constexpr int RAGLICH_ARMS = NPC_STATE_SUMMON3; + +// Raglich packs his heading into i1 as the original does: the direction he faces (low half), the way he turns at a +// corner (byte 2, 1 or -1) and his phase (byte 3). +constexpr int I1_TURN = 2; +constexpr int RAGLICH_I1_PHASE = 3; +constexpr int RAGLICH_START_I1 = 0xff0003; + +static int raglich_direction_get(const Entity_NPC& npc) +{ + return (int16_t)(npc.i1 & 0xffff); +} + +static void raglich_direction_set(Entity_NPC& npc, int direction) +{ + npc.i1 = (int)(((uint32_t)npc.i1 & 0xffff0000u) | (uint16_t)direction); +} + +static int8_t& raglich_byte(Entity_NPC& npc, int index) +{ + return reinterpret_cast(&npc.i1)[index]; +} + +// The direction a turn away from another, wrapped to the four. +static int direction_turn(int direction, int turn) +{ + return (direction + turn + 4) & 3; +} + +// His phases: below two thirds of his health he summons fire, below a third the arms. +constexpr std::array PHASE_HEALTH = {0.666f, 0.333f, 0}; +constexpr std::array MOVE_UP = {"MoveLeftUp", "MoveUpRight", "MoveRightDown", "MoveDownLeft"}; +constexpr std::array MOVE_DOWN = {"MoveLeftDown", "MoveUpLeft", "MoveRightUp", "MoveDownRight"}; +constexpr std::array SUMMON = {"SummonLeft", "SummonUp", "SummonRight", "SummonDown"}; +constexpr std::array SUMMON_ARM = {"SummonArmLeft", "SummonArmUp", "SummonArmRight", "SummonArmDown"}; +constexpr std::array BRIMSTONE = {"BrimstoneLeft", "BrimstoneUp", "BrimstoneRight", "BrimstoneDown"}; +constexpr std::array DASH = {"DashLeft", "DashUp", "DashRight", "DashDown"}; +constexpr std::array DASH_ALT = {"DashAltLeft", "DashAltUp", "DashAltRight", "DashAltDown"}; +constexpr std::array TURN_DOWN = {"TurnDownFromLeft", "TurnDownFromUp", "TurnDownFromRight"}; + +// His look: a purple splat, drawn 17 low, and a purple-tinted brimstone. +constexpr ColorMod RAGLICH_SPLAT_COLOR = {{1, 1, 1, 1}, {0.84f, 0.4f, 0.68f, 1}, {0, 0, 0}}; +constexpr ColorMod RAGLICH_LASER_COLOR = {{1, 1, 1, 1}, {0.8f, 0.1f, 1, 1}, {0.18f, 0, 0.22f}}; +constexpr ColorMod BLUE_FIRE_COLOR = {{1, 1, 1, 1}, {1.3f, 1, 2, 1}, {0, 0, 0}}; +constexpr float RAGLICH_DROP = 17; +constexpr float RAGLICH_FRICTION = 0.6f; + +// The walk along the walls at 3 (0.2 while firing), taking in his edge's pull at a tenth, building to 1 by 0.1. +constexpr float RAGLICH_WALK_SPEED = 3; +constexpr float WALK_FIRING_SPEED = 0.2f; +constexpr float WALK_EDGE_PULL = 0.1f; +constexpr float WALK_MARGIN = 10; +constexpr float WALK_GAIN = 0.1f; +constexpr float WALK_MAX = 1; + +// His picks while walking: a dash across when the target is within 24 of his line (leading it by a tenth) and he is +// rested, else the brimstone once ready; every 30 frames one time in five a creep while at most one of his is out. +constexpr float DASH_LINE = 24; +constexpr float TARGET_LEAD = 0.1f; +constexpr uint32_t BRIMSTONE_WAIT_RANGE = 60; +constexpr int BRIMSTONE_WAIT = 60; +constexpr int SUMMON_EVERY = 30; +constexpr uint32_t RAGLICH_SUMMON_ODDS = 5; +constexpr size_t SUMMON_CREEP_LIMIT = 1; +constexpr float SUMMON_START_FRAME = 20; +constexpr int WALL_CREEP_SUMMONED = 2; +constexpr int RAGLICH_DASH_COOLDOWN = 60; + +// The dash: from 18, slowing by 0.4 to no less than 8, cut to its end past the room's middle, then turned back +// toward the wall it heads for at 12 a frame at most (a twentieth of the way). The alternate dash slows to 2, then 1 +// while it fires crosses of blue fire with its blue fires. +constexpr float RAGLICH_DASH_SPEED = 18; +constexpr float DASH_SLOW = 0.4f; +constexpr float DASH_MIN = 8; +constexpr int DASH_LATE_FRAME = 79; +constexpr float DASH_END_FRAME = 80; +constexpr int DASH_ALT_SKIP_FRAME = 26; +constexpr float DASH_ALT_SKIP_TO = 33; +constexpr float DASH_RETURN_GAIN = 0.2f; +constexpr float DASH_RETURN_MAX = 12; +constexpr float DASH_RETURN_SHARE = 0.05f; +constexpr float DASH_TURN_MIN = 2; +constexpr float DASH_SHOOT_MIN = 1; +constexpr float DASH_RESTART_FRAME = 90; +constexpr float RAGLICH_FIRE_SHOT_SPEED = 10; + +// The brimstone: a beam 24 up for 45 frames, drawn in front unless aimed up. +constexpr float BRIMSTONE_HEIGHT = -24; +constexpr int RAGLICH_BRIMSTONE_TIMEOUT = 45; +constexpr float BEHIND_DEPTH = -10; +constexpr float RAGLICH_FRONT_DEPTH = 3000; + +// The appearance: a wall creep at 10, 20, 30 and 40 frames after its roar. The fire summon lights one of his blue +// fires every 6 frames. The arm summon flies him 120 above the room's middle and sends two arms 200 either side. +constexpr std::array APPEAR_CREEP_FRAMES = {10, 20, 30, 40}; +constexpr int FIRE_LIGHT_EVERY = 6; +constexpr float FIRE_UNLIT_HEALTH = 1; +constexpr float ARMS_HEIGHT = 120; +constexpr float ARMS_REACH = 200; +constexpr float ARMS_FOLLOW = 0.9f; +constexpr int RAGLICH_SUMMON_SHAKE = 8; + +// An arm: it slams where it hangs, crushing three cells into pits with rock bursts and small blasts of 10 over 20. +constexpr float ARM_FRICTION = 0.5f; +constexpr int ARM_SHAKE = 14; +constexpr float ARM_BLAST_DAMAGE = 10; +constexpr float ARM_BLAST_RADIUS = 20; +constexpr float ARM_PARTICLE_SPEED = 6; +constexpr int ARM_PARTICLES = 4; +constexpr uint64_t ARM_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_KNOCKBACK | FLAG_NO_PHYSICS_KNOCKBACK | + FLAG_DONT_COUNT_BOSS_HP; + +// The grid cell's center a spot falls in, as the original works it out (off the grid at the cell -1's spot). +static Vector cell_center_get(Room& room, Vector position) +{ + return room.GetGridPosition(room.GetGridIndex(position)); +} + +// The cell on the second row under a column of the room, his walk's start and his place after the arms. +static Vector top_row_position_get(Room& room, Vector position) +{ + int column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + HALF); + int cell = column < 0 || column >= room.gridWidth || room.gridHeight < 2 ? -1 : column + room.gridWidth; + return room.GetGridPosition(cell); +} + +// The last spot inside the room from his position along his facing, in steps of a cell. +static Vector wall_spot_get(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Vector step = vector_scale(vector_from_direction(raglich_direction_get(npc)), GRID_CELL_SIZE); + Vector spot = npc.pos; + while (room.IsPositionInRoom(vector_add(spot, step), 0)) spot = vector_add(spot, step); + return spot; +} + +// 00576090 His walk along the walls: sideways along his edge, pulled onto it, turning at the room's corners (and an +// L room's inner ones), his target the cell at the turn. +static void raglich_pick_target_pos(Entity_NPC& npc, float speed) +{ + Room& room = *g_game->room; + int turn = raglich_byte(npc, I1_TURN); + Vector side = vector_from_direction(direction_turn(raglich_direction_get(npc), turn)); + Vector facing = vector_from_direction(raglich_direction_get(npc)); + Vector offEdge = vector_scale(facing, vector_dot(vector_sub(npc.pos, npc.targetPosition), facing)); + npc.velocity = vector_add(npc.velocity, vector_scale(vector_sub(vector_scale(side, speed), vector_scale(offEdge, WALK_EDGE_PULL)), + npc.v1.y * npc.speedMultiplier)); + Vector clamped = room.GetClampedPositionImpl(vector_sub(npc.pos, offEdge), WALK_MARGIN, WALK_MARGIN, WALK_MARGIN, WALK_MARGIN); + Vector ahead = vector_add(clamped, vector_scale(side, GRID_CELL_SIZE)); + if (!room.IsPositionInRoom(ahead, 0)) + { + raglich_direction_set(npc, direction_turn(raglich_direction_get(npc), -turn)); + int column = (int)((clamped.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + HALF); + int row = (int)((clamped.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + HALF); + npc.targetPosition = room.GetGridPosition(room.GetGridIndexByTile(column, row)); + } + else if (room.IsLShapedRoom()) + { + Vector behind = vector_sub(clamped, vector_scale(facing, GRID_CELL_SIZE)); + if (room.IsPositionInRoom(behind, 0) && !room.IsPositionInRoom(vector_sub(behind, vector_scale(side, GRID_CELL_SIZE)), 0)) + { + raglich_direction_set(npc, direction_turn(raglich_direction_get(npc), turn)); + npc.targetPosition = cell_center_get(room, clamped); + } + } + npc.v1.y = std::min(npc.speedMultiplier * WALK_GAIN + npc.v1.y, WALK_MAX); +} + +// 00576450 A summoned arm: it slams, crushing the cells under it and beside it into pits, and goes once done. +static void raglich_slam_spawn_grid(Entity_NPC& arm) +{ + if (arm.state == NPC_STATE_INIT) + { + arm.sprite.Play("Arm"); + arm.ClearEntityFlags(FLAG_APPEAR); + arm.AddEntityFlags(ARM_FLAGS); + arm.state = NPC_STATE_IDLE; + arm.targetPosition = arm.pos; + return; + } + if (arm.state != NPC_STATE_IDLE) return; + + arm.friction = ARM_FRICTION; + arm.velocity = vector_sub(arm.targetPosition, arm.pos); + Vector hit = arm.GetNullOffset("Hit"); + if (!vector_is_zero(hit)) + { + if (arm.i1 == 0) + { + arm.i1 = 1; + arm.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, 1, 2, false, 1); + game_shake_screen(ARM_SHAKE); + } + Vector slam = vector_add(arm.pos, hit); + for (float offset : {0.0f, -GRID_CELL_SIZE, GRID_CELL_SIZE}) + explosion_damage({.position = vector_add(slam, vector_make(offset, 0)), + .source = &arm, + .damageFlags = DAMAGE_CRUSH, + .damage = ARM_BLAST_DAMAGE, + .radius = ARM_BLAST_RADIUS, + .isLineCheck = false}); + + Room& room = *g_game->room; + int column = (int)((slam.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + HALF); + int row = (int)((slam.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + HALF); + for (int x = column - 1; x <= column + 1; x++) + { + int cell = room.GetGridIndexByTile(x, row); + if (cell < 0) continue; + uint32_t seed = Random(); + if (cell < ROOM_GRID_CELLS) + { + room.SpawnGridEntity(cell, GRID_PIT, 0, seed, 0); + GridEntity* pit = room.gridEntities[cell]; + if (pit && pit->type == GRID_PIT) pit->PostInit(); + } + else KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"SpawnGridEntity: Grid index invalid\n"); + game_particles_spawn({.position = vector_add(arm.pos, hit), .speed = ARM_PARTICLE_SPEED, + .count = ARM_PARTICLES, .variant = EFFECT_ROCK_PARTICLE}); + } + } + if (arm.sprite.IsFinished()) arm.Remove(); +} + +// His appearance: his roar sets his touch, and four wall creeps crawl out as it echoes. +static void raglich_appear_pre_update(Entity_NPC& npc, int ticks) +{ + AnimationState& anim = npc.sprite.animState; + if (!anim.animData || anim.IsEventTriggered("Shoot") || !anim.isPlaying) + { + npc.entityCollisionClass = ENTCOLL_ALL; + if (!anim.animData) return; + } + if (anim.IsEventTriggered("Sound")) npc_sound_play(SOUND_GHOST_ROAR, 1, 2, champion_pitch_get(npc)); + if (!anim.WasEventTriggered("Sound")) return; + + for (; ticks > 0; ticks--) + { + npc.stateFrame++; + if (std::ranges::find(APPEAR_CREEP_FRAMES, npc.stateFrame) == APPEAR_CREEP_FRAMES.end()) continue; + Vector spot = g_game->room->GetRandomPosition(0); + uint32_t seed = Random(); + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_WALL_CREEP, .variant = WALL_CREEP_SUMMONED, .seed = seed})->Update(); + npc_sound_play(SOUND_SUMMONSOUND, 1, 2, 1); + } +} + +// Raglich is not hurt by himself or his own side's shots of his kind. +static void raglich_damage_filter(Entity_NPC& npc) +{ + for (DamageEvent& event : npc.damageEvents) + { + if (event.source.type != npc.type || event.source.IsFriendly() != npc.IsFriendly()) continue; + npc.pendingDamage -= event.damage; + event.damage = 0; + } + if (npc.pendingDamage < 0) npc.pendingDamage = 0; +} + +// Crossing a phase line: blood bursts and he summons fire (the first) or the arms (the second). +static void raglich_phase_update(Entity_NPC& npc) +{ + int8_t& phase = raglich_byte(npc, RAGLICH_I1_PHASE); + if (phase < 0 || phase >= 3 || !(npc.health < PHASE_HEALTH[(size_t)phase] * npc.maxHitPoints)) return; + + phase++; + npc.BloodExplode(); + if (phase == 1) + { + npc.sprite.Play(SUMMON[(size_t)raglich_direction_get(npc) & 3], PLAY_FORCED); + npc.state = RAGLICH_FIRES; + npc.PlaySound(SOUND_MONSTER_GRUNT_4, 1, 2, false, 1); + } + else if (phase == 2) + { + npc.sprite.Play(SUMMON_ARM[(size_t)raglich_direction_get(npc) & 3], PLAY_FORCED); + npc.PlaySound(SOUND_MONSTER_GRUNT_4, 1, 2, false, 1); + npc.state = RAGLICH_ARMS; + } + else return; + npc.stateFrame = 0; +} + +// The walk: along the walls, dashing across at a target in line, firing his brimstone, or calling a creep. +static void raglich_walk_update(Entity_NPC& npc) +{ + size_t direction = (size_t)raglich_direction_get(npc) & 3; + npc.sprite.Play(raglich_byte(npc, I1_TURN) >= 1 ? MOVE_UP[direction] : MOVE_DOWN[direction]); + npc.friction *= RAGLICH_FRICTION; + raglich_pick_target_pos(npc, RAGLICH_WALK_SPEED); + direction = (size_t)raglich_direction_get(npc) & 3; + Vector axis = vector_from_direction((int)direction); + Entity* target = npc.GetPlayerTarget(); + float distance = vector_distance(npc.pos, target->pos); + Vector toTarget = vector_sub(vector_add(target->pos, vector_scale(target->velocity, distance * TARGET_LEAD)), npc.pos); + if (std::abs(vector_dot(vector_rotated(axis, RIGHT_ANGLE_DEGREES), toTarget)) >= DASH_LINE || npc.projectileCooldown > 0) + { + if (npc.projectileDelay < 1) + { + npc.state = RAGLICH_BRIMSTONE; + npc.sprite.Play(BRIMSTONE[direction]); + npc.stateFrame = 0; + } + } + else + { + bool isAlt = raglich_byte(npc, RAGLICH_I1_PHASE) != 0; + npc.state = isAlt ? RAGLICH_DASH_ALT : RAGLICH_DASH; + npc.sprite.Play(isAlt ? DASH_ALT[direction] : DASH[direction]); + } + + if (!npc.GetIntervalTicks(SUMMON_EVERY, 0) || Random() % RAGLICH_SUMMON_ODDS != 0) return; + size_t creeps = 0; + for (Entity* creep : entity_query(ENTITY_WALL_CREEP, -1)) + if (creep->spawnerEntity.get() == &npc) creeps++; + if (creeps > SUMMON_CREEP_LIMIT) return; + npc.state = RAGLICH_SUMMON; + npc.sprite.Play(SUMMON[(size_t)raglich_direction_get(npc) & 3]); + if (npc.sprite.animState.animData) npc.sprite.SetFrame(SUMMON_START_FRAME); + npc.stateFrame = 0; +} + +// The alternate dash's shots: a cross or plus of blue fire from him and each of his blue fires that is shooting. +static void raglich_fire_shots(Entity_NPC& npc, int sound, ProjectilesMode mode) +{ + npc.PlaySound(sound, 1, 2, false, 1); + ProjectileParams params; + params.variant = PROJECTILE_FIRE; + params.color = BLUE_FIRE_COLOR; + npc.FireProjectiles(npc.pos, vector_make(RAGLICH_FIRE_SHOT_SPEED, 0), mode, params); + for (Entity* entity : entity_query(ENTITY_FIREPLACE, FIRE_PURPLE)) + { + auto* fire = static_cast(entity); + if (!Entity::is_enemy_type(fire->type) || fire->spawnerType != npc.type || fire->state != FIRE_STATE_LIT) continue; + npc.FireProjectiles(fire->pos, vector_make(RAGLICH_FIRE_SHOT_SPEED, 0), mode, params); + fire->sprite.PlayOverlay("Shoot", PLAY_FORCED); + } +} + +// The dash's end: he turns his walk around and rests from dashing. +static void raglich_dash_end(Entity_NPC& npc) +{ + raglich_byte(npc, I1_TURN) = (int8_t)-raglich_byte(npc, I1_TURN); + npc.state = RAGLICH_WALK; + npc.projectileCooldown = RAGLICH_DASH_COOLDOWN; +} + +// The dash across the room: building from 18 down to 8, heading for the far wall, then turning to walk back along it. +// The alternate dash turns down into a slide that fires blue crosses, then dashes on. +static bool raglich_dash_update(Entity_NPC& npc) +{ + npc.friction = RAGLICH_FRICTION; + AnimationState& anim = npc.sprite.animState; + bool isMoving = npc.stateFrame == 1; + if (anim.animData && anim.IsEventTriggered("DashStart")) + { + npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + npc.stateFrame = 1; + npc.v1.y = RAGLICH_DASH_SPEED; + isMoving = true; + } + if (isMoving) + { + bool isSkipped = npc.sprite.GetFrame() == DASH_ALT_SKIP_FRAME && npc.state == RAGLICH_DASH_ALT; + bool isGoing = !isSkipped; + if (isSkipped && anim.animData) + { + anim.SetFrameFloat(DASH_ALT_SKIP_TO); + isGoing = npc.stateFrame == 1; + } + if (isGoing && anim.animData && anim.IsEventTriggered("DashEnd")) + { + size_t direction = (size_t)raglich_direction_get(npc) & 3; + if (npc.state == RAGLICH_DASH_ALT) + { + if (direction >= TURN_DOWN.size()) + { + npc.sprite.Play("DashAltShoot"); + npc.v1.y *= HALF; + npc.stateFrame = 4; + } + else + { + npc.sprite.Play(TURN_DOWN[direction]); + npc.stateFrame = 3; + } + } + else + { + npc.stateFrame = 2; + npc.targetPosition = cell_center_get(*g_game->room, wall_spot_get(npc)); + raglich_direction_set(npc, direction_turn(raglich_direction_get(npc), 2)); + } + } + } + + Vector axis = vector_from_direction(raglich_direction_get(npc)); + switch (npc.stateFrame) + { + case 1: + { + npc.velocity = vector_add(npc.velocity, vector_scale(axis, npc.v1.y * npc.speedMultiplier)); + npc.v1.y = std::max(npc.v1.y - npc.speedMultiplier * DASH_SLOW, DASH_MIN); + bool isPastMiddle = npc.state == RAGLICH_DASH && npc.sprite.GetFrame() <= DASH_LATE_FRAME && + vector_dot(vector_sub(npc.pos, Room::GetCenterPos()), axis) > 0; + if (isPastMiddle) + { + if (!anim.animData) + { + raglich_dash_end(npc); + return false; + } + anim.SetFrameFloat(DASH_END_FRAME); + } + break; + } + case 2: + { + npc.v1.y = std::min(npc.speedMultiplier * DASH_RETURN_GAIN + npc.v1.y, DASH_RETURN_MAX); + Vector back = vector_scale(vector_sub(npc.targetPosition, npc.pos), DASH_RETURN_SHARE); + float length = vector_length(back); + if (npc.v1.y < length && length > 0) back = vector_scale(back, npc.v1.y / length); + npc.velocity = vector_add(npc.velocity, vector_scale(back, npc.speedMultiplier)); + break; + } + case 3: + npc.velocity = vector_add(npc.velocity, vector_scale(axis, npc.v1.y * npc.speedMultiplier)); + npc.v1.y = std::max(npc.v1.y - 2 * npc.speedMultiplier, DASH_TURN_MIN); + if (npc.sprite.IsFinished()) + { + npc.sprite.Play("DashAltShoot"); + npc.stateFrame = 4; + } + break; + case 4: + npc.velocity = vector_add(npc.velocity, vector_scale(axis, npc.v1.y * npc.speedMultiplier)); + npc.v1.y = std::max(npc.v1.y - npc.speedMultiplier, DASH_SHOOT_MIN); + if (npc.sprite.IsEventTriggered("Shoot")) raglich_fire_shots(npc, SOUND_MONSTER_GRUNT_0, PROJECTILES_CROSS); + else if (npc.sprite.IsEventTriggered("Shoot2")) raglich_fire_shots(npc, SOUND_MONSTER_GRUNT_1, PROJECTILES_PLUS); + if (npc.sprite.IsFinished()) + { + npc.sprite.Play(DASH[(size_t)raglich_direction_get(npc) & 3], PLAY_FORCED); + npc.targetPosition = cell_center_get(*g_game->room, wall_spot_get(npc)); + raglich_direction_set(npc, direction_turn(raglich_direction_get(npc), 2)); + npc.sprite.SetFrame(DASH_RESTART_FRAME); + npc.stateFrame = 2; + } + break; + default: + break; + } + if (!npc.sprite.IsFinished()) return true; + raglich_dash_end(npc); + return false; +} + +// The brimstone: a beam along his facing that turns with him as he keeps walking. +static void raglich_brimstone_update(Entity_NPC& npc) +{ + npc.friction = RAGLICH_FRICTION; + int before = raglich_direction_get(npc); + bool isFiring = npc.sprite.animState.animData && npc.sprite.animState.WasEventTriggered("Shoot"); + raglich_pick_target_pos(npc, isFiring ? WALK_FIRING_SPEED : RAGLICH_WALK_SPEED); + int direction = raglich_direction_get(npc); + float angle = (float)direction * RIGHT_ANGLE_DEGREES - HALF_TURN_DEGREES; + float depth = direction == 1 ? BEHIND_DEPTH : RAGLICH_FRONT_DEPTH; + if (direction != before) + { + npc.sprite.SetAnimation(BRIMSTONE[(size_t)direction & 3], SWITCH_KEEP_FRAME); + Entity* beam = npc.child.get(); + if (beam && beam->type == ENTITY_LASER) + { + static_cast(beam)->set_aim_angle(angle); + beam->renderDepthOffset = depth; + } + } + if (npc.sprite.animState.animData) + { + if (npc.sprite.animState.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_GHOST_ROAR, 1, 2, false, 1); + npc.stateFrame = 0; + npc.v1.x = angle; + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = npc.pos, + .posOffset = vector_make(0, BRIMSTONE_HEIGHT), + .source = &npc, + .angleDegrees = angle, + .timeout = RAGLICH_BRIMSTONE_TIMEOUT, + .variant = 1}); + laser->renderDepthOffset = depth; + laser->SetColor(RAGLICH_LASER_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + npc.child = laser; + } + if (npc.sprite.animState.isPlaying) return; + } + npc.state = RAGLICH_WALK; + npc.stateFrame = 0; + npc.projectileDelay = (int)(Random() % BRIMSTONE_WAIT_RANGE) + BRIMSTONE_WAIT; +} + +// The first phase summon lights his blue fires one by one. +static void raglich_fires_light(Entity_NPC& npc, int ticks) +{ + std::vector fires = entity_query(ENTITY_FIREPLACE, FIRE_PURPLE); + for (; ticks > 0; ticks--) + { + if (npc.stateFrame++ % FIRE_LIGHT_EVERY != 0 || fires.empty()) continue; + for (Entity* entity : fires) + { + auto* fire = static_cast(entity); + if (!Entity::is_enemy_type(fire->type) || fire->spawnerType != npc.type || fire->health > FIRE_UNLIT_HEALTH) + continue; + fire->state = FIRE_STATE_RELIGHT; + fire->Update(); + break; + } + } +} + +// The arm summon: he flies above the room's middle and sends two arms down either side. +static bool raglich_arms_update(Entity_NPC& npc) +{ + npc.friction *= RAGLICH_FRICTION; + if (npc.sprite.IsEventTriggered("DashStart")) + npc.targetPosition = vector_sub(Room::GetCenterPos(), vector_make(0, ARMS_HEIGHT)); + if (npc.sprite.WasEventTriggered("DashStart")) + { + float keep = timescale_factor(ARMS_FOLLOW, npc.speedMultiplier); + npc.velocity = vector_add(npc.velocity, + vector_scale(vector_sub(vector_sub(npc.targetPosition, npc.pos), npc.velocity), 1 - keep)); + } + if (npc.sprite.IsEventTriggered("Sound")) + for (float side : {-1.0f, 1.0f}) + { + uint32_t seed = Random(); + Entity* arm = g_game->Spawn({.position = vector_add(npc.targetPosition, vector_make(side * ARMS_REACH, 0)), + .spawner = &npc, .type = ENTITY_RAGLICH, .variant = RAGLICH_ARM, .seed = seed}); + if (side > 0) arm->sprite.isFlipX = true; + arm->Update(); + } + if (!npc.sprite.IsFinished()) return false; + + npc.targetPosition = top_row_position_get(*g_game->room, npc.pos); + raglich_direction_set(npc, 3); + raglich_byte(npc, I1_TURN) = -1; + npc.state = RAGLICH_WALK; + return true; +} + +// 005769b0 Raglich: he walks along the room's walls, dashes across at a target in line, fires brimstone and calls +// wall creeps; his phases light his blue fires and send arms that crush the floor into pits. +void boss_raglich_update(Entity_NPC& npc) +{ + if (npc.variant == RAGLICH_ARM) return raglich_slam_spawn_grid(npc); + + raglich_damage_filter(npc); + Room& room = *g_game->room; + int ticks = npc_ticks_get(npc); + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) + { + if (npc.state == RAGLICH_APPEAR) raglich_appear_pre_update(npc, ticks); + return; + } + + raglich_phase_update(npc); + if (npc.projectileDelay > 0) npc.projectileDelay -= ticks; + if (npc.projectileCooldown > 0) npc.projectileCooldown -= ticks; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.entityCollisionClass = ENTCOLL_NONE; + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + npc.splatColor = RAGLICH_SPLAT_COLOR; + npc.state = RAGLICH_WALK; + npc.posOffset = vector_make(0, RAGLICH_DROP); + npc.targetPosition = top_row_position_get(room, npc.pos); + npc.i1 = RAGLICH_START_I1; + npc.projectileDelay = (int)(Random() % BRIMSTONE_WAIT_RANGE) + BRIMSTONE_WAIT; + npc.stateFrame = 0; + return; + case RAGLICH_WALK: + return raglich_walk_update(npc); + case RAGLICH_DASH: + case RAGLICH_DASH_ALT: + if (raglich_dash_update(npc)) return; + break; + case RAGLICH_BRIMSTONE: + return raglich_brimstone_update(npc); + case RAGLICH_SUMMON: + npc.friction *= RAGLICH_FRICTION; + if (npc.sprite.IsEventTriggered("Sound")) npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + Vector spot = room.GetRandomPosition(0); + uint32_t seed = Random(); + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_WALL_CREEP, .variant = WALL_CREEP_SUMMONED, .seed = seed})->Update(); + npc_sound_play(SOUND_SUMMONSOUND, 1, 2, 1); + } + if (!npc.sprite.IsFinished()) return; + npc.state = RAGLICH_WALK; + break; + case RAGLICH_FIRES: + npc.friction *= RAGLICH_FRICTION; + if (npc.sprite.IsEventTriggered("Sound")) + { + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + game_shake_screen(RAGLICH_SUMMON_SHAKE); + } + if (npc.sprite.WasEventTriggered("Shoot")) raglich_fires_light(npc, ticks); + if (!npc.sprite.IsFinished()) return; + npc.state = RAGLICH_WALK; + break; + case RAGLICH_ARMS: + if (!raglich_arms_update(npc)) return; + break; + default: + return; + } + npc.v1.y = 0; + npc.stateFrame = 0; +} diff --git a/src/boss_rainmaker.cpp b/src/boss_rainmaker.cpp new file mode 100644 index 0000000..288fb8e --- /dev/null +++ b/src/boss_rainmaker.cpp @@ -0,0 +1,319 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "manager.h" + +// The Rainmaker's states: walking, raining a line of drops, raining drops about it while it walks, and gathering the +// rain into one burst. +constexpr int RAINMAKER_WALK = NPC_STATE_IDLE; +constexpr int RAINMAKER_RAIN_LINE = NPC_STATE_ATTACK; +constexpr int RAINMAKER_RAIN_ABOUT = NPC_STATE_ATTACK2; +constexpr int RAINMAKER_GATHER = NPC_STATE_ATTACK3; + +// It walks at its target at 0.5 (1.3 while raining about it), slowed to 0.7 a frame, and picks an attack one frame in +// 20: the line one time in three (crossways two times in three when the target is not level with it). +constexpr float RAINMAKER_FRICTION = 0.7f; +constexpr float RAINMAKER_WALK_SPEED = 0.5f; +constexpr float RAIN_WALK_SPEED = 1.3f; +constexpr uint32_t RAINMAKER_ATTACK_ODDS = 20; +constexpr uint32_t ATTACK_KINDS = 3; +constexpr float LEVEL_SLACK = 0.25f; + +// A drop: a tear shot 6 up hanging still until its timer launches it at 10 at the target, leading it and spread by +// the timer's settings. +constexpr float DROP_HEIGHT = -6; +constexpr float RAINMAKER_DROP_SPEED = 10; + +// The line: from its 12th frame every 3rd, six pairs of drops either side, 30 apart along the row (or on a half +// circle of 70 when crossways), each launched 8 frames earlier than the next. +constexpr int LINE_START = 12; +constexpr int LINE_PAIR_EVERY = 3; +constexpr int LINE_PAIRS = 6; +constexpr float LINE_GAP = 30; +constexpr float LINE_RADIUS = 70; +constexpr int LINE_LAUNCH_LAST = 9; +constexpr int LINE_LAUNCH_STEP = 8; +constexpr float LINE_LEAD = 0.05f; +constexpr float LINE_ROOM_MARGIN = 1; + +// Raining about it: a drop within 60 every 10 frames until 150, launched after 45 spread 5 and leading 0.03, then a +// ring of eight tears at 10 to end. +constexpr int ABOUT_EVERY = 10; +constexpr int ABOUT_FRAMES = 150; +constexpr float ABOUT_REACH = 60; +constexpr int ABOUT_LAUNCH = 45; +constexpr float ABOUT_SPREAD = 5; +constexpr float ABOUT_LEAD = 0.03f; +constexpr float ABOUT_RING_SPEED = 10; + +// Gathering: a drop rises within 60 every other frame from its 3rd to its 19th, drawn up to it at 4 toward 95 above +// it, each it swallows adding 2 or 3 to the burst of at least 4 tears 72 up. +constexpr int GATHER_FIRST = 2; +constexpr int GATHER_SPAN = 18; +constexpr float GATHER_PULL = 4; +constexpr float GATHER_HEIGHT = -95; +constexpr float GATHER_RISE = 0.28f; +constexpr float GATHER_REACHED = 4; +constexpr float GATHER_SWALLOW = 9; +constexpr int GATHER_SUBTYPE = 1; +constexpr int RAINMAKER_BURST_MIN = 4; +constexpr float RAINMAKER_BURST_HEIGHT = -72; +constexpr float RAINMAKER_BURST_CURVE = 2; +constexpr float BURST_POOF_SCALE = 2; + +// 005784e0 Walks at its target at a speed. +static void rainmaker_walk(Entity_NPC& npc, float speed) +{ + Vector toTarget = vector_normalized(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + npc.velocity = vector_add(npc.velocity, vector_scale(toTarget, speed * npc.speedMultiplier)); +} + +// A tear drop hanging where it formed. +static Entity_Projectile* drop_spawn(Entity_NPC& npc, const Vector& position, int subType, uint32_t seed) +{ + auto* drop = static_cast(g_game->Spawn({.position = position, .spawner = &npc, .subType = subType, + .type = ENTITY_PROJECTILE, .variant = PROJECTILE_TEAR, + .seed = seed})); + drop->height = DROP_HEIGHT; + drop->fallingSpeed = 0; + drop->scale = 1; + return drop; +} + +// 005785a0 A drop's timer: it falls again and shoots at its target (leading it by the timer's scale) or anywhere, +// turned by up to the timer's rotation either way. +static void rainmaker_drop_timer_launch(Entity_Effect* timer) +{ + Entity* drop = timer->parent.get(); + if (!drop || drop->type != ENTITY_PROJECTILE) return; + + float spread = timer->rotation; + float lead = timer->scale; + Entity* target = timer->target.get(); + static_cast(drop)->projectileFlags &= ~PROJECTILE_ANTI_GRAVITY; + Vector direction; + if (!target) direction = random_direction(); + else + { + Vector aim = target->pos; + if (lead > 0) aim = vector_add(aim, vector_scale(target->velocity, vector_distance(drop->pos, aim) * lead)); + direction = vector_normalized(vector_sub(aim, drop->pos)); + } + if (spread > 0) direction = vector_rotated(direction, (random_unit() * 2 - 1) * spread); + drop->velocity = vector_scale(direction, RAINMAKER_DROP_SPEED); +} + +// 00578820 A drop hanging in the air with a splash, launched by a timer after a delay. +static Entity* rainmaker_spawn_homing_drop(Entity_NPC& npc, const Vector& position, int delay, float spread, float lead) +{ + uint32_t seed = Random(); + Entity_Projectile* drop = drop_spawn(npc, position, 0, seed); + drop->projectileFlags = PROJECTILE_ANTI_GRAVITY; + drop->parent = &npc; + drop->Update(); + seed = Random(); + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_WATER_RIPPLE, .seed = seed}); + npc_sound_play(SOUND_TEARS_FIRE, 1, 2, 1); + + Entity_Effect* timer = + Entity_Effect::CreateTimer(reinterpret_cast(&rainmaker_drop_timer_launch), (uint32_t)delay, 0, false); + timer->parent = drop; + timer->target = npc.GetPlayerTarget(); + timer->rotation = spread; + timer->scale = lead; + return drop; +} + +// The line of drops, a pair each third frame from the 12th, then its end. +static void rainmaker_rain_line(Entity_NPC& npc) +{ + if (npc.projectileCooldown < 0) + { + if (npc.sprite.IsEventTriggered("Shoot")) npc.PlaySound(SOUND_CUTE_GRUNT, 1, 2, false, 1); + if (npc.sprite.IsFinished()) npc.state = RAINMAKER_WALK; + return; + } + npc.sprite.Play("Attack1"); + if (npc.sprite.IsFinished()) + { + npc.sprite.Play("Attack1End"); + npc.projectileCooldown = -1; + return; + } + + int step = npc.projectileCooldown - LINE_START; + if (step < 0 || step >= LINE_PAIRS * LINE_PAIR_EVERY || step % LINE_PAIR_EVERY != 0) + { + npc.projectileCooldown++; + return; + } + int pair = step / LINE_PAIR_EVERY; + for (int side = -1; side < 2; side += 2) + { + Vector at; + if (npc.i2 == 1) + at = vector_add(npc.pos, vector_scale(vector_from_angle((float)pair * HALF_TURN_DEGREES / LINE_PAIRS + + (float)side * RIGHT_ANGLE_DEGREES + RIGHT_ANGLE_DEGREES), + LINE_RADIUS)); + else at = vector_add(npc.pos, vector_make((float)(pair + 1) * (float)side * LINE_GAP, 0)); + if (!g_game->room->IsPositionInRoom(at, LINE_ROOM_MARGIN)) continue; + npc.GetPlayerTarget(); + rainmaker_spawn_homing_drop(npc, at, (LINE_LAUNCH_LAST - pair) * LINE_LAUNCH_STEP, 0, LINE_LEAD); + } + npc.projectileCooldown++; +} + +// Raining about it while walking, then a ring of tears and a clap. +static void rainmaker_rain_about(Entity_NPC& npc) +{ + if (npc.projectileCooldown == 0) + { + npc.sprite.Play("Attack2Begin"); + if (!npc.sprite.IsFinished()) return; + npc.sprite.Play("Attack2Loop"); + npc.projectileCooldown = 1; + return; + } + if (npc.projectileCooldown > 0) + { + if (npc.sprite.IsFinished()) + { + if (npc.projectileCooldown < ABOUT_FRAMES) npc.sprite.Play("Attack2Loop", PLAY_FORCED); + else + { + npc.sprite.Play("Attack2End"); + npc.projectileCooldown = -1; + } + return; + } + if (npc.projectileCooldown % ABOUT_EVERY == 0) + { + npc.GetPlayerTarget(); + Vector at = vector_add(npc.pos, vector_scale(random_direction(), ABOUT_REACH)); + rainmaker_spawn_homing_drop(npc, at, ABOUT_LAUNCH, ABOUT_SPREAD, ABOUT_LEAD); + } + npc.projectileCooldown++; + rainmaker_walk(npc, RAIN_WALK_SPEED); + return; + } + + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_CUTE_GRUNT, 1, 2, false, 1); + ProjectileParams params; + params.variant = PROJECTILE_TEAR; + npc.FireProjectiles(npc.pos, vector_make(ABOUT_RING_SPEED, 0), PROJECTILES_EIGHT, params); + } + if (npc.sprite.IsEventTriggered("Clap")) npc.PlaySound(SOUND_FETUS_FEET, 1, 2, false, 1); + if (npc.sprite.IsFinished()) npc.state = RAINMAKER_WALK; +} + +// The gathered drops rise toward the cloud above it, each swallowed one adding to the burst. +static void rainmaker_drops_gather(Entity_NPC& npc) +{ + for (Entity* entity : entity_query(ENTITY_PROJECTILE, -1)) + { + auto* drop = static_cast(entity); + if (drop->subtype != GATHER_SUBTYPE || drop->parent.get() != &npc) continue; + + drop->entityGridCollisionClass = GRIDCOLL_NONE; + Vector toCloud = vector_sub(npc.pos, drop->pos); + Vector pull = vector_length(toCloud) <= GATHER_PULL ? toCloud : vector_scale(vector_normalized(toCloud), GATHER_PULL); + drop->velocity = vector_scale(pull, 1 / drop->friction); + drop->fallingSpeed = (GATHER_HEIGHT - drop->height) * GATHER_RISE; + if (std::abs(drop->height - GATHER_HEIGHT) >= GATHER_REACHED || vector_distance(npc.pos, drop->pos) >= GATHER_SWALLOW) + continue; + npc_sound_play(SOUND_BOSS2_BUBBLES, 1, 2, 1); + drop->isDead = true; + npc.i1 += (int)(Random() & 1) + 2; + } +} + +// Gathering the rain: drops rise about it and are drawn up into one burst of tears. +static void rainmaker_gather(Entity_NPC& npc) +{ + npc.sprite.Play("Attack3"); + int rising = npc.projectileCooldown - GATHER_FIRST; + if (npc.projectileCooldown > GATHER_FIRST && rising < GATHER_SPAN && (rising & 1) == 0) + { + Vector at = vector_add(npc.pos, vector_scale(random_direction(), ABOUT_REACH)); + uint32_t seed = Random(); + Entity_Projectile* drop = drop_spawn(npc, at, GATHER_SUBTYPE, seed); + drop->parent = &npc; + drop->Update(); + seed = Random(); + g_game->Spawn({.position = at, .type = ENTITY_EFFECT, .variant = EFFECT_WATER_RIPPLE, .seed = seed}); + seed = Random(); + g_game->Spawn({.position = at, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_WATER_RIPPLE, .seed = seed}); + npc_sound_play(SOUND_TEARS_FIRE, 1, 2, 1); + } + + bool isGathering = !npc.sprite.animState.animData; + if (!isGathering) + { + if (npc.sprite.animState.IsEventTriggered("Clap")) npc.PlaySound(SOUND_CLAP, 1, 2, false, 1); + if (npc.sprite.animState.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_BOSS2INTRO_WATER_EXPLOSION, 1, 2, 1); + ProjectileParams params; + params.heightModifier = RAINMAKER_BURST_HEIGHT; + params.variant = PROJECTILE_TEAR; + npc.FireBossProjectiles(std::max(RAINMAKER_BURST_MIN, npc.i1), {}, RAINMAKER_BURST_CURVE, params); + uint32_t seed = Random(); + Entity* poof = g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_TEAR_POOF_B, .seed = seed}); + poof->posOffset = vector_make(0, GATHER_HEIGHT); + poof->sprite.scale = vector_make(BURST_POOF_SCALE, BURST_POOF_SCALE); + poof->Update(); + } + isGathering = !npc.sprite.animState.WasEventTriggered("Shoot"); + } + if (isGathering) rainmaker_drops_gather(npc); + if (npc.sprite.IsFinished()) npc.state = RAINMAKER_WALK; + npc.projectileCooldown++; +} + +// 00578a70 The Rainmaker: it walks at its target and makes rain, a line of drops, drops about it or a gathered burst. +// Its death takes its drops and stops the room's rain. +void boss_rainmaker_update(Entity_NPC& npc) +{ + npc.friction *= RAINMAKER_FRICTION; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = RAINMAKER_WALK; + break; + case RAINMAKER_WALK: + { + npc.sprite.Play("Walk"); + rainmaker_walk(npc, RAINMAKER_WALK_SPEED); + if (Random() % RAINMAKER_ATTACK_ODDS != 0) break; + npc.projectileCooldown = 0; + npc.i1 = 0; + uint32_t kind = Random() % ATTACK_KINDS; + if (kind != 0) + { + npc.state = kind == 1 ? RAINMAKER_RAIN_ABOUT : RAINMAKER_GATHER; + break; + } + npc.state = RAINMAKER_RAIN_LINE; + Vector toTarget = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.i2 = std::abs(toTarget.y) < LEVEL_SLACK || (Random() & 1) == 0 ? 0 : 1; + break; + } + case RAINMAKER_RAIN_LINE: + rainmaker_rain_line(npc); + break; + case RAINMAKER_RAIN_ABOUT: + rainmaker_rain_about(npc); + break; + case RAINMAKER_GATHER: + rainmaker_gather(npc); + break; + default: + break; + } + if (!npc.isDead) return; + + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity->type == ENTITY_PROJECTILE && entity->parent.get() == &npc) entity->isDead = true; + g_game->room->isRainStopped = true; +} diff --git a/src/boss_repentance.h b/src/boss_repentance.h index ab3d213..0798144 100644 --- a/src/boss_repentance.h +++ b/src/boss_repentance.h @@ -1,6 +1,8 @@ #pragma once #include "entity_npc.h" +#include "entity_effect.h" +#include // Rotgut's forms, by variant: the face in the wall, the maggot in its first dungeon and the heart in its second. enum RotgutVariant @@ -10,6 +12,18 @@ enum RotgutVariant ROTGUT_HEART }; +// The Visage's forms, by variant: the heart, its mask, a link of the chain between them, and a plasma ball. +enum VisageVariant +{ + VISAGE_HEART = 0, + VISAGE_MASK = 1, + VISAGE_CHAIN = 10, + VISAGE_PLASMA = 20 +}; + +// Hornfel's front layer, drawn over his cart. +constexpr int HORNFEL_FRONT_LAYER = 4; + // The Repentance enemies' and bosses' AIs the dispatcher (npc_ai_update) runs by type. void boss_colostomia_update(Entity_NPC& npc); void boss_horny_boys_update(Entity_NPC& npc); @@ -20,3 +34,13 @@ void npc_gasbag_update(Entity_NPC& npc); void npc_generic_prop_update(Entity_NPC& npc); void boss_turdlet_update(Entity_NPC& npc); void rotgut_death_spawn_effects(Entity_NPC& npc); + +// The late Repentance bosses' AIs and hooks (boss_visage.cpp and its neighbours). +void boss_visage_update(Entity_NPC& npc); +std::optional visage_handle_collision(Entity_NPC& npc, Entity& collider); +void hornfel_door_update(Entity_NPC& door); +void boss_rainmaker_update(Entity_NPC& npc); +void boss_mothers_shadow_update(Entity_NPC& npc); +void boss_clog_update(Entity_NPC& npc); +void boss_raglich_update(Entity_NPC& npc); +void hornfel_room_controller(Entity_Effect& controller); diff --git a/src/boss_rotgut.cpp b/src/boss_rotgut.cpp index 8137aac..c3aa6ba 100644 --- a/src/boss_rotgut.cpp +++ b/src/boss_rotgut.cpp @@ -137,8 +137,6 @@ constexpr float FALL_PIT_PULL = 0.5f; constexpr float FALL_HEALTH = 0.001f; constexpr int FALL_DEPTH = -500; constexpr float FALL_SPLASH_HEIGHT = -4; -constexpr int FALL_RETURN_INDEX_MIN = -20; -constexpr int FALL_RETURN_INDEX_MAX = 168; // The maggot: an attack one in 30 frames after 15, its head attacks more likely with the target below it, its suck, its // spray of 15 volleys, its 20 frames of wiggling shots and its fart. @@ -695,10 +693,11 @@ static void face_fall_update(Entity_NPC& npc, int ticks) if (npc.stateFrame > FALL_FRAMES) { Game& game = *g_game; - game.enterDoor = -1; + game.leaveDoor = -1; game.dungeonReturnPosition = npc.pos; // 0057be90 The dungeon's return room, held between -20 and 168. - game.dungeonReturnRoomIndex = std::clamp(game.currentRoomIdx, FALL_RETURN_INDEX_MIN, FALL_RETURN_INDEX_MAX); + game.dungeonReturnRoomIndex = + std::clamp(game.currentRoomIdx, DUNGEON_RETURN_INDEX_MIN, DUNGEON_RETURN_INDEX_MAX); game.StartRoomTransition({.animation = TRANSITION_PIXELATION, .roomIndex = ROOM_ROTGUT_DUNGEON1_IDX}); } } diff --git a/src/boss_visage.cpp b/src/boss_visage.cpp new file mode 100644 index 0000000..3b7ea0c --- /dev/null +++ b/src/boss_visage.cpp @@ -0,0 +1,1995 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_effect_combat.h" +#include "entity_laser.h" +#include "grid_entity.h" +#include "manager.h" +#include "npc_basement.h" +#include "npc_gehenna.h" +#include +#include +#include + +// The heart's states. Chained to the mask it idles and winds the chain in, then breaks free, swings the chain hook, +// pulls with it, holds the mask for its lasers and leaps. Below half health it breaks out again, spits plasma, rings +// shots and draws everything in. +enum VisageState +{ + VISAGE_CHAINED = 100, + VISAGE_UNWIND, + VISAGE_REWIND, + VISAGE_BREAKING, + VISAGE_BROKEN, + VISAGE_IDLE, + VISAGE_THROW, + VISAGE_PULL, + VISAGE_HOLD = 109, + VISAGE_JUMP_UP, + VISAGE_JUMP_DOWN, + VISAGE_BREAKING2, + VISAGE_BROKEN2, + VISAGE_IDLE2, + VISAGE_PLASMA_SPIT, + VISAGE_RING_LOOP, + VISAGE_RING_END, + VISAGE_DRAW +}; + +// The mask's states: hunting on the chain, its charge's start, run and wall hit, its break, walking free, pulled by +// the hook, its eye lasers, stunned, and its second charge with its hit. +enum MaskState +{ + MASK_HUNT = 100, + MASK_CHARGE_BEGIN, + MASK_CHARGE, + MASK_CHARGE_HIT, + MASK_BREAKING, + MASK_BROKEN, + MASK_WALK, + MASK_PULLED, + MASK_LASERS, + MASK_STUNNED, + MASK_CHARGE2, + MASK_CHARGE2_HIT +}; + +// A chain link's states: hanging between the heart and the mask, hidden in the heart, thrown as the hook, stuck in a +// wall and hooked into something. +enum ChainState +{ + CHAIN_HANGING = NPC_STATE_IDLE, + CHAIN_HIDDEN = NPC_STATE_MOVE, + CHAIN_THROWN = NPC_STATE_SUICIDE, + CHAIN_STUCK = NPC_STATE_JUMP, + CHAIN_HOOKED = NPC_STATE_STOMP +}; + +// A plasma ball's states: drifting, and drawn in by the heart. +constexpr int PLASMA_DRIFT = NPC_STATE_IDLE; +constexpr int PLASMA_DRAWN = NPC_STATE_MOVE; + +// Its look: the glowing layer, the dark red splat, the tooth chips of its breaks, the white flash of a swallowed ball +// and the fire it rings. +constexpr int VISAGE_GLOW_LAYER = 1; +constexpr ColorMod VISAGE_SPLAT_COLOR = {{0, 0, 0, 1.1f}, {0, 0, 0, 0}, {1, 0.1f, 0}}; +constexpr ColorMod VISAGE_CHIP_COLOR = {{0.41960785f, 0.3529412f, 0.3529412f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod VISAGE_SWALLOW_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 0.1f, 0}}; +constexpr ColorMod MASK_SWALLOW_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 0.15f, 0}}; +constexpr ColorMod VISAGE_FIRE_COLOR = {{2, 1.8f, 1.8f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod CHAIN_SPLAT_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; +constexpr ColorMod EYE_TRAIL_COLOR = {{1, 0.2f, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int VISAGE_SWALLOW_FLASH = 10; +constexpr uint64_t VISAGE_HIDDEN_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET; + +// The chain: 40 links, each 8 to 16 from the next, drawn 35 up, its hook thrown at 7 and stuck where it hits. +constexpr int CHAIN_LINKS = 40; +constexpr float CHAIN_LINK_MIN = 8; +constexpr float CHAIN_LINK_MAX = 16; +constexpr float VISAGE_CHAIN_HEIGHT = -35; +constexpr float CHAIN_THROW_PUSH = 7; +constexpr float CHAIN_THROW_FRICTION = 0.85f; +constexpr float CHAIN_DAMAGE_COUNTDOWN = 30; +constexpr float CHAIN_FRAYED_HEALTH = 0.25f; + +// The heart's leash: the mask hangs 150 out and is pulled back at up to 15, a fifth of the slack each frame. Each +// wind adds 20 and pulls 0.8 of the mask's charge. A rewind takes in 30 a frame down to 35, done below 40. +constexpr float VISAGE_LEASH_LENGTH = 150; +constexpr float LEASH_PULL_MAX = 15; +constexpr float LEASH_PULL_SHARE = 0.2f; +constexpr float LEASH_UNWIND = 20; +constexpr float LEASH_UNWIND_RECOIL = 0.8f; +constexpr float LEASH_REWIND = 30; +constexpr float LEASH_REWIND_FLOOR = 35; +constexpr float LEASH_REWOUND = 40; +constexpr float MASK_SPAWN_DROP = 26; + +// Its walks: to a spot it picks from 20 within 100 of it, scored to stand 120 from its target on the far side of the +// mask, at a tenth of the way up to 2 (3 once broken twice), repicking one frame in 20 or one in 4 when hurt. +constexpr int PICK_TRIES = 20; +constexpr float PICK_REACH = 100; +constexpr float PICK_MARGIN = 10; +constexpr float PICK_TARGET_GAP = 120; +constexpr float PICK_HEART_DISTANCE = 1.2f; +constexpr float PICK_FACING = 300; +constexpr float PICK_MASK_DISTANCE = 0.5f; +constexpr float PICK_FACING2 = 0.2f; +constexpr float PICK_MASK_DISTANCE2 = 0.25f; +constexpr uint32_t REPICK_ODDS = 20; +constexpr float WALK_SHARE = 0.1f; +constexpr float VISAGE_WALK_SPEED = 2; +constexpr float WALK_SPEED2 = 3; +constexpr float CHAINED_FRICTION = 0.8f; +constexpr float IDLE2_FRICTION = 0.75f; + +// The throw: one frame in 40 when alone, else one in 20 when the mask is over 256 away. The hook leads a player by +// 0.06 of the distance and the mask by 0.01. A pull drags the hooked at 22 (a player) or 15, slowing it to 0.5 or 0.9 +// a tick, and ends within 40 or after 60 frames, 90 when stuck in a wall. +constexpr uint32_t THROW_ODDS_ALONE = 40; +constexpr uint32_t THROW_ODDS = 20; +constexpr float THROW_MASK_DISTANCE = 256; +constexpr float THROW_LEAD_PLAYER = 0.06f; +constexpr float THROW_LEAD_MASK = 0.01f; +constexpr float THROW_FRICTION = 0.5f; +constexpr float THROW_HOOK_SLOW = 0.6f; +constexpr float PULL_STAY_DISTANCE = 80; +constexpr int PULL_PATIENCE = 91; +constexpr uint32_t PULL_PLAIN_ODDS = 7; +constexpr float PULL_FACING = 0.9f; +constexpr float PULL_SIDE_FACING = 0.4f; +constexpr float PULL_SWING = 9; +constexpr float PULL_HOLD_SPEED = 8; +constexpr float PULL_PLAYER_SPEED = 22; +constexpr float PULL_SPEED = 15; +constexpr float PULL_PLAYER_SLOW = 0.5f; +constexpr float PULL_SLOW = 0.9f; +constexpr float PULL_REACHED = 40; +constexpr int VISAGE_PULL_FRAMES = 60; +constexpr int PULL_STUCK_FRAMES = 90; +constexpr int PULL_SWING_FRAMES = 30; +constexpr float PULL_SWING_AIM = 0.85f; +constexpr float PULL_SWING_TURN = 3; +constexpr float PULL_SHOT_SPEED = -10; +constexpr float PULL_PLAYER_DAMAGE = 2; +constexpr int PULL_DAMAGE_COUNTDOWN = 30; +constexpr float PULL_SPLAT_SIZE = 0.2f; +constexpr float PULL_SPLAT_RANGE = 0.5f; +constexpr float SWING_REWIND_FRAME = 4; + +// Its stomps and slams: rock shots raised 10, five or six from a wall slam, ten to thirteen from a landing. +constexpr float SLAM_SHOT_RAISE = -10; +constexpr int VISAGE_SLAM_SHAKE = 15; +constexpr int PULL_END_SHAKE = 8; +constexpr int SLAM_DELAY = 10; +constexpr float VISAGE_LAND_VOLUME = 2; +constexpr int VISAGE_CRACKWAVES = 4; +constexpr float CRACKWAVE_OFFSET = 45; + +// Holding the mask for its lasers: 40 in front of it, slipping sideways past 10 off the target's line at 0.7 (0.015 +// once the lasers fire) and backing 0.5 toward the target. +constexpr float HOLD_REACH = 40; +constexpr float HOLD_DROP = 1; +constexpr float HOLD_SIDE_SLACK = 10; +constexpr float HOLD_SIDE_PUSH = 0.7f; +constexpr float HOLD_SIDE_PUSH_FIRING = 0.015f; +constexpr float HOLD_PUSH = 0.5f; +constexpr float HOLD_FRICTION = 0.8f; +constexpr float HOLD_FRICTION_FIRING = 0.95f; +constexpr float VISAGE_JUMP_FRICTION = 0.6f; +constexpr uint32_t IDLE_COOLDOWN_RANGE = 30; +constexpr int IDLE_COOLDOWN = 15; +constexpr int IDLE2_COOLDOWN = 30; + +// The breaks: 3 to 6 chips at 3 to 5 the first time, 8 to 15 at 4 to 7 the second, when its health reaches half. +constexpr float BREAK_FRICTION = 0.1f; +constexpr float BREAK_HEALTH = 0.5f; + +// The broken heart's attacks: plasma at 10 on a diagonal (up to 4, 6 or 8 by the room's size), a ring of 16 orbiting +// rock shots released after 60, and its draw over 600 that swallows plasma for rings of 24 fire shots at 14. +constexpr uint32_t VISAGE_ATTACK_ODDS = 15; +constexpr size_t PLASMA_RING_MIN = 3; +constexpr uint32_t VISAGE_RING_ODDS = 3; +constexpr float PLASMA_SPEED = 10; +constexpr int PLASMA_CAP_SMALL = 4; +constexpr int PLASMA_CAP_LONG = 6; +constexpr int PLASMA_CAP_LARGE = 8; +constexpr int VISAGE_RING_SHOTS = 16; +constexpr float RING_STEP = 22.5f; +constexpr float VISAGE_RING_SPEED = 10; +constexpr float VISAGE_RING_HEIGHT = -20; +constexpr int RING_HOLD = 60; +constexpr int RING_ORBITING = 1; +constexpr int RING_RELEASED = 2; +constexpr float RING_FRICTION = 0.7f; +constexpr int DRAW_START = 3; +constexpr int DRAW_MASK_STUN = 4; +constexpr float DRAW_REACH = 600; +constexpr float DRAW_PULL = 0.9f; +constexpr float DRAW_PLAYER_SHARE = 0.6f; +constexpr float DRAW_PLASMA_SHARE = 1.6f; +constexpr int DRAW_LASERS = 4; +constexpr float DRAW_LASER_HEIGHT = -20; +constexpr float DRAW_LASER_REACH = 100; +constexpr int DRAW_LASER_TIMEOUT = 20; +constexpr int FIRE_RING_SHOTS = 24; +constexpr float FIRE_RING_STEP = 15; +constexpr float FIRE_RING_TWIST = 7.5f; +constexpr float FIRE_RING_SPEED = 14; +constexpr float SWALLOW_PITCH = 0.15f; +constexpr float SWALLOW_HEAL = 0.025f; +constexpr float SWALLOW_HEAL_CAP = 0.4f; +constexpr float VISAGE_FRONT_DEPTH = 1000; + +// Its dust bursts: 5 to 8 puffs within 20 of the hit, thrown back at up to 5, spinning off the side, 16 up, for 30 to +// 39 frames. +constexpr uint32_t DUST_EXTRA_MASK = 3; +constexpr int VISAGE_DUST_MIN = 5; +constexpr float VISAGE_DUST_SPREAD = 20; +constexpr float VISAGE_DUST_SPEED = 5; +constexpr float VISAGE_DUST_SPIN = 10; +constexpr float VISAGE_DUST_SPIN_MIN = 2; +constexpr float DUST_HEIGHT = -16; +constexpr uint32_t VISAGE_DUST_TIMEOUT_RANGE = 10; +constexpr int VISAGE_DUST_TIMEOUT = 30; + +// The mask: hunting at 1.5 (1.5 to 4 on a lunge of 30 to 89 frames turning 0.05 toward its target), charging at 7 +// when lined up over 200 of open floor, its hit's chain gibs, its free walk at 1.5 (0.8 wandering), its lasers 10 or +// 15 apart and its second charge at 5. Its speeds take half again once broken free. +constexpr float MASK_FREE_SPEED = 1.5f; +constexpr int MASK_LUNGE_WAIT = -89; +constexpr uint32_t MASK_LUNGE_ODDS = 40; +constexpr uint32_t MASK_LUNGE_RANGE = 60; +constexpr int MASK_LUNGE_MIN = 30; +constexpr float MASK_HUNT_SPEED = 1.5f; +constexpr float MASK_LUNGE_SPEED = 2.5f; +constexpr float MASK_LUNGE_TURN = 0.05f; +constexpr int MASK_START_WAIT = 60; +constexpr float MASK_LINED_UP = 0.9f; +constexpr uint32_t MASK_CHARGE_ODDS = 40; +constexpr float MASK_CHARGE_ROOM = 200; +constexpr float MASK_CHARGE_MARGIN = 20; +constexpr int MASK_AIM_FRAME = 6; +constexpr float MASK_AIM_LEAD = 0.18f; +constexpr float VISAGE_MASK_CHARGE_PUSH = 7; +constexpr float MASK_HEAD_ON = 0.5f; +constexpr uint32_t MASK_REST_RANGE = 60; +constexpr int MASK_REST = 30; +constexpr uint32_t GIB_EXTRA_MASK = 3; +constexpr int GIBS_MIN = 10; +constexpr float VISAGE_GIB_SPEED_RANGE = 6; +constexpr float VISAGE_GIB_SPEED_MIN = 2; +constexpr float MASK_WANDER_SHARE = 0.8f; +constexpr int MASK_TURN_GRACE = 4; +constexpr uint32_t MASK_TURN_ODDS = 10; +constexpr float MASK_STUN_FRICTION = 0.5f; +constexpr float MASK_CHARGE2_PUSH = 5; +constexpr float MASK_RING_SPEED = 10; +constexpr float MASK_RING_SHOTS = 8; +constexpr float MASK_LASER_HEIGHT = -58; +constexpr float MASK_LASER_GAP = 10; +constexpr float MASK_LASER_GAP_VERTICAL = 15; +constexpr float MASK_LASER_TURN = 10; +constexpr float MASK_LASER_TURN_SPEED = 2; +constexpr float MASK_LASER_SWEEP = 20; +constexpr uint32_t MASK_LASER_TURN_FRAMES = 5; +constexpr uint32_t MASK_LASER_BACK_FRAMES = 15; +constexpr float MASK_BROKEN_SPEED = 1.5f; +constexpr float MASK_DYING_HEALTH = 0.1f; +constexpr float CHARGE2_LASER_HEIGHT = -40; +constexpr float ANIMATED_SPEED = 0.1f; + +// The eye trails: 0.12 wide at half size, shown from a speed of 10 over 15. +constexpr float EYE_TRAIL_RADIUS = 0.12f; +constexpr float EYE_TRAIL_SCALE = 0.5f; +constexpr float EYE_TRAIL_SPEED = 10; +constexpr float EYE_TRAIL_FADE = 15; +constexpr std::array EYE_NULLS = {"LeftEye", "RightEye"}; + +// A plasma ball drifts at 0.5 inside the room, swerving 0.2 toward a stunned mask it was sent at. +constexpr float PLASMA_DRIFT_PUSH = 0.5f; +constexpr float PLASMA_SCALE = 0.6f; +constexpr float PLASMA_SCALE_DRIFT = 0.5f; +constexpr float PLASMA_SCALE_SEEK = 1; +constexpr float PLASMA_SEEK_TURN = 0.2f; +constexpr float PLASMA_FRICTION = 0.8f; +constexpr float PLASMA_DRAWN_FRICTION = 0.9f; +constexpr float PLASMA_RISE_SPEED = 0.1f; + +// The animation names by facing (left, up, right, down). +constexpr std::array DIRECTION_NAMES = {"Left", "Up", "Right", "Down"}; +constexpr std::array MASK_MOVE = {"MoveLeft", "MoveUp", "MoveRight", "MoveDown"}; +constexpr std::array MASK_MOVE_ANGRY = {"MoveAngryLeft", "MoveAngryUp", "MoveAngryRight", + "MoveAngryDown"}; +constexpr std::array MASK_ATTACK = {"AttackLeft", "AttackUp", "AttackRight", "AttackDown"}; +constexpr std::array MASK_STUN = {"StunLeft", "StunUp", "StunRight", "StunDown"}; + +static bool is_visage(Entity* entity, int variant) +{ + return entity && entity->type == ENTITY_VISAGE && entity->variant == variant; +} + +// An animation name with the facing a vector leans along most (vertical on a tie). +static std::string direction_animation(std::string_view prefix, Vector direction) +{ + std::string_view name = std::abs(direction.x) > std::abs(direction.y) ? DIRECTION_NAMES[direction.x < 0 ? 0 : 2] + : DIRECTION_NAMES[direction.y < 0 ? 1 : 3]; + return std::string(prefix) + std::string(name); +} + +// 005a7570 How far the heart has broken out: chained, broken once, or broken twice. +static int visage_phase_get(Entity_NPC& visage) +{ + if (visage.state >= VISAGE_BROKEN2) return 2; + return visage.state >= VISAGE_BROKEN ? 1 : 0; +} + +// 005accb0 The heart at the top of a link's chain, if it is one. +static Entity_NPC* chain_visage_get(Entity_NPC& link) +{ + Entity* top = &link; + while (top->parent) top = top->parent.get(); + return is_visage(top, VISAGE_HEART) ? static_cast(top) : nullptr; +} + +// 005acc70 The mask at the end of a link's chain, if it is one. +static Entity_NPC* chain_mask_get(Entity_NPC& link) +{ + Entity* end = &link; + while (end->child) end = end->child.get(); + return is_visage(end, VISAGE_MASK) ? static_cast(end) : nullptr; +} + +// 005accf0, 005acd10 Whether a link is the chain's first (no link above) or last (no link below). +static bool chain_is_first(Entity_NPC& link) +{ + return !is_visage(link.parent.get(), VISAGE_CHAIN); +} + +static bool chain_is_last(Entity_NPC& link) +{ + return !is_visage(link.child.get(), VISAGE_CHAIN); +} + +// A blood splat under any entity (Entity_NPC::MakeSplat, which the heart calls on a player it pulls). +static void splat_make(Entity& entity, float size) +{ + Entity* splat = spawn_at(ENTITY_EFFECT, EFFECT_BLOOD_SPLAT, 0, entity.pos, &entity); + splat->sprite.scale = vector_make(size, size); + splat->Update(); +} + +// Rock shots raised 10 for a slam or a landing. +static ProjectileParams slam_params_get() +{ + ProjectileParams params; + params.heightModifier += SLAM_SHOT_RAISE; + params.variant = PROJECTILE_ROCK; + return params; +} + +// A slam's rock shots: least plus a random part under extraMask, drawn after the params. +static void slam_shots_fire(Entity_NPC& shooter, uint32_t extraMask, int least) +{ + ProjectileParams params = slam_params_get(); + shooter.FireBossProjectiles((int)(Random() & extraMask) + least, {}, 0, params); +} + +// 005ad1c0 The hook lets go and goes back to hiding in the heart, unless more chain hangs from it. +static void hook_retract(Entity_NPC& hook) +{ + if (!chain_is_last(hook)) return; + + hook.targetPosition = {}; + hook.target = nullptr; + hook.state = CHAIN_HIDDEN; + g_manager->sfxManager.Stop(SOUND_CHAIN_LOOP); +} + +// 005a7010 A burst of 5 to 8 dust puffs about a spot, thrown back along a direction, each spinning away from its side. +static void visage_spawn_particles(const Vector& position, const Vector& direction) +{ + int count = (int)(Random() & DUST_EXTRA_MASK) + VISAGE_DUST_MIN; + Vector side = vector_rotated(direction, RIGHT_ANGLE_DEGREES); + + for (; count != 0; count--) + { + uint32_t seed = Random(); + float back = random_unit(); + float sideways = random_unit() * 2 - 1; + Vector velocity = vector_add(vector_scale(direction, back * VISAGE_DUST_SPEED), vector_scale(side, sideways)); + Vector at = random_direction(); + Vector spot = vector_add(position, vector_scale(at, random_unit() * VISAGE_DUST_SPREAD)); + auto* dust = static_cast(g_game->Spawn( + {.position = spot, .velocity = velocity, .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = seed})); + + bool isBehind = vector_dot(vector_sub(dust->pos, position), direction) < 0; + dust->rotation = (random_unit() * VISAGE_DUST_SPIN + VISAGE_DUST_SPIN_MIN) * (float)isBehind == 0 ? 1.0f : -1.0f; + int timeout = (int)(Random() % VISAGE_DUST_TIMEOUT_RANGE) + VISAGE_DUST_TIMEOUT; + dust->posOffset = vector_make(0, DUST_HEIGHT); + dust->timeout = timeout; + dust->lifespan = timeout; + dust->Update(); + } +} + +// 005a7310 Spawns the 40 links from the heart to the mask, each hanging from the last, and keeps the last as the hook. +static void visage_spawn_chain(Entity_NPC& visage) +{ + std::vector links; + Entity* previous = &visage; + + for (int i = 0; i < CHAIN_LINKS; i++) + { + uint32_t seed = Random(); + Entity* link = g_game->Spawn({.position = visage.pos, .spawner = &visage, .subType = i, .type = ENTITY_VISAGE, + .variant = VISAGE_CHAIN, .seed = seed}); + link->ClearEntityFlags(FLAG_APPEAR); + link->parent = previous; + if (previous->variant == VISAGE_CHAIN) previous->child = link; + links.push_back(link); + previous = link; + } + + visage.entityRef = links.back(); + links.back()->child = visage.child.get(); + for (Entity* link : links) link->Update(); +} + +// 005a7510 The most plasma balls at once: more in long rooms, most in large ones. +static size_t visage_plasma_cap() +{ + switch (g_game->room->GetRoomShape()) + { + case ROOMSHAPE_1x2: + case ROOMSHAPE_2x1: + return PLASMA_CAP_LONG; + case ROOMSHAPE_2x2: + case ROOMSHAPE_LTL: + case ROOMSHAPE_LTR: + case ROOMSHAPE_LBL: + case ROOMSHAPE_LBR: + return PLASMA_CAP_LARGE; + default: + return PLASMA_CAP_SMALL; + } +} + +// 005a7590 How good a spot is for the heart: 120 from its target and, with the mask out, on the far side of it. +static float visage_score_position(Entity_NPC& npc, const Vector& position) +{ + Entity* target = npc.GetPlayerTarget(); + float targetGap = std::abs(vector_distance(target->pos, position) - PICK_TARGET_GAP); + Entity* mask = npc.child.get(); + if (!mask) return 0 - targetGap; + + Vector toMask = vector_sub(mask->pos, position); + float facing = vector_dot(vector_normalized(vector_sub(target->pos, position)), vector_normalized(toMask)); + float maskDistance = vector_length(toMask); + if (npc.state < VISAGE_BROKEN2) + return vector_distance(npc.pos, position) * PICK_HEART_DISTANCE + + (facing * PICK_FACING + maskDistance * PICK_MASK_DISTANCE + 0) - targetGap; + return (facing * PICK_FACING2 * PICK_FACING + maskDistance * PICK_MASK_DISTANCE2 + 0) - targetGap; +} + +// 005a7920 Picks the best of 20 spots within 100, kept 10 inside the room, as the heart's next target position. +static void visage_pick_target_position(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.targetPosition = npc.pos; + float best = visage_score_position(npc, npc.pos); + + for (int i = 0; i < PICK_TRIES; i++) + { + Vector at = random_direction(); + Vector spot = vector_add(npc.pos, vector_scale(at, random_unit() * PICK_REACH)); + bool isInside; + if (room.IsLShapedRoom()) + { + Vector clamped = room.GetClampedPositionImpl(spot, PICK_MARGIN, PICK_MARGIN, PICK_MARGIN, PICK_MARGIN); + isInside = clamped.x == spot.x && clamped.y == spot.y; + } + else + isInside = room.topLeftPos.x + PICK_MARGIN <= spot.x && spot.x <= room.bottomRightPos.x - PICK_MARGIN && + room.topLeftPos.y + PICK_MARGIN <= spot.y && spot.y <= room.bottomRightPos.y - PICK_MARGIN; + if (!isInside) continue; + + float score = visage_score_position(npc, spot); + if (best < score) + { + npc.targetPosition = spot; + best = score; + } + } +} + +// The heart's walk toward its target position at a tenth of the way, repicking now and then, the mask out. +static void visage_walk(Entity_NPC& npc, float friction, float maxSpeed, float speedScale) +{ + npc.friction *= friction; + npc.GetPlayerTarget(); + if (Random() % REPICK_ODDS == 0 || (npc.pendingDamage > 0 && (Random() & 3) == 0)) visage_pick_target_position(npc); + + Vector toTarget = vector_sub(npc.targetPosition, npc.pos); + float speed = std::min(vector_length(toTarget) * WALK_SHARE, maxSpeed); + npc.velocity = vector_add(npc.velocity, vector_scale(vector_normalized(toTarget), speed * speedScale)); +} + +// The chips of a break and its crumble. +static void visage_chips_spawn(Entity_NPC& npc, float speed, int count) +{ + game_particles_spawn( + {.color = VISAGE_CHIP_COLOR, .position = npc.pos, .speed = speed, .count = count, .variant = EFFECT_TOOTH_PARTICLE}); +} + +// 005ab0b0 The mask's walk animation for its facing (angry, firing or stunned by state) while it moves over 0.1. +static void mask_animate(Entity_NPC& mask) +{ + if (vector_length(mask.velocity) <= ANIMATED_SPEED) return; + + size_t facing = (size_t)mask.i1 & 3; + switch (mask.state) + { + case MASK_WALK: + case MASK_PULLED: + return mask.sprite.Play(MASK_MOVE_ANGRY[facing]); + case MASK_LASERS: + return mask.sprite.Play(MASK_ATTACK[facing]); + case MASK_STUNNED: + return mask.sprite.Play(MASK_STUN[facing]); + default: + return mask.sprite.Play(MASK_MOVE[facing]); + } +} + +// 005aafd0 The mask turns to face a direction (its velocity when none) moving over 0.1, keeping its aim as forward. +static void mask_face(Entity_NPC& mask, Vector direction) +{ + if (vector_is_zero(direction)) direction = mask.velocity; + if (vector_length(direction) <= ANIMATED_SPEED) return; + + if (std::abs(direction.x) <= std::abs(direction.y)) mask.i1 = direction.y >= 0 ? 3 : 1; + else mask.i1 = direction.x < 0 ? 0 : 2; + mask.forwardVector = mask.targetPosition; +} + +// 005ab3e0 The mask goes limp: healed, untouchable and harmless until a plasma ball wakes it. +static void mask_stun(Entity_NPC& mask) +{ + if (mask.state == MASK_STUNNED) return; + + mask.health = mask.maxHitPoints; + mask.state = MASK_STUNNED; + npc_sound_play(SOUND_STEAM_HALFSEC, 1, 2, champion_pitch_get(mask)); + mask.AddEntityFlags(VISAGE_HIDDEN_FLAGS); + mask.isInvincible = true; + mask.SetCollisionDamage(0); + mask_animate(mask); +} + +// 005aae10 The mask on its chain: pulled back toward the heart past the leash, while the heart is chained. +static void mask_leash(Entity_NPC& mask) +{ + mask.friction *= CHAINED_FRICTION; + auto* visage = static_cast(mask.parent.get()); + if (!visage || visage->state >= VISAGE_IDLE) return; + + Vector toHeart = vector_sub(visage->pos, mask.pos); + float pull = std::min(vector_length(toHeart) - visage->v1.y, LEASH_PULL_MAX); + if (pull > 0) npc_push(mask, vector_scale(vector_normalized(toHeart), pull)); +} + +// 005ab180 A plasma ball wakes the mask: it roars and charges along its facing behind a laser. +static void visage_start_charge(Entity_NPC& mask) +{ + if (mask.state == MASK_STUNNED) + { + mask.ClearEntityFlags(VISAGE_HIDDEN_FLAGS); + mask.health = mask.maxHitPoints; + mask.isInvincible = false; + mask.SetCollisionDamage(mask.config->collisionDamage); + } + npc_sound_play(SOUND_MONSTER_ROAR_0, 1, 2, champion_pitch_get(mask)); + mask.targetPosition = vector_from_direction(mask.i1); + mask.sprite.Play(direction_animation("Charge2Loop", mask.targetPosition)); + mask.state = MASK_CHARGE2; + + Vector back = vector_scale(mask.targetPosition, -1); + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = mask.pos, + .posOffset = vector_make(0, CHARGE2_LASER_HEIGHT), + .source = &mask, + .angleDegrees = vector_angle(back), + .timeout = DRAW_LASER_TIMEOUT, + .variant = 1}); + laser->renderDepthOffset = back.y >= 0 ? VISAGE_FRONT_DEPTH : 0; + laser->Update(); +} + +// The heart's hold on the mask's lasers: the mask hangs in front of it while it slides to keep the target in the line. +static bool visage_hold(Entity_NPC& npc) +{ + Entity* held = npc.entityDeque.empty() ? nullptr : npc.entityDeque[0].get(); + auto* mask = static_cast(held); + if (!mask || mask->state != MASK_LASERS) return false; + + Vector axis = vector_from_direction(mask->i1); + Vector side = vector_rotated(axis, RIGHT_ANGLE_DEGREES); + Entity* target = npc.GetPlayerTarget(); + bool isFiring = mask->sprite.WasEventTriggered("Break"); + Vector toTarget = vector_sub(target->pos, npc.pos); + float sideways = vector_dot(toTarget, side); + float sidePush = isFiring ? HOLD_SIDE_PUSH_FIRING : HOLD_SIDE_PUSH; + if (sideways > HOLD_SIDE_SLACK) npc.velocity = vector_add(npc.velocity, vector_scale(side, sidePush * npc.speedMultiplier)); + else if (sideways < -HOLD_SIDE_SLACK) + npc.velocity = vector_add(npc.velocity, vector_scale(side, -sidePush * npc.speedMultiplier)); + + if (!isFiring) + { + if (vector_dot(toTarget, axis) > 0) + { + npc.friction *= HOLD_FRICTION; + npc.velocity = vector_add(npc.velocity, vector_scale(axis, HOLD_PUSH * npc.speedMultiplier)); + } + } + else + { + npc.friction *= HOLD_FRICTION_FIRING; + npc.velocity = vector_sub(npc.velocity, vector_scale(axis, HOLD_PUSH * npc.speedMultiplier)); + } + + mask->pos = vector_add(vector_add(npc.pos, vector_scale(axis, HOLD_REACH)), vector_make(0, HOLD_DROP)); + mask->velocity = npc.velocity; + return true; +} + +// The heart throws its hook: at a player or a stunned mask (one time in two), else at the mask, leading it. +static void visage_hook_throw(Entity_NPC& npc) +{ + auto* mask = static_cast(npc.child.get()); + Entity* aim; + float lead; + if (!mask || (mask->state == MASK_STUNNED && (Random() & 1))) + { + aim = npc.GetPlayerTarget(); + lead = THROW_LEAD_PLAYER; + } + else + { + aim = mask; + lead = THROW_LEAD_MASK; + } + Vector aimed = vector_add(aim->pos, vector_scale(aim->velocity, vector_distance(npc.pos, aim->pos) * lead)); + + auto* hook = static_cast(npc.entityRef.get()); + if (chain_is_last(*hook) && hook->state == CHAIN_HIDDEN) + { + hook->state = CHAIN_THROWN; + hook->targetPosition = vector_normalized(vector_sub(aimed, hook->pos)); + g_manager->sfxManager.Play(SOUND_CHAIN_LOOP, {.volume = 0.8f, .loop = SOUND_LOOP}); + } + npc.stateFrame = 0; +} + +// The throw's wind-up: the hook flies, then once it sticks or hooks something the heart decides how to pull. A hooked +// mask is swung about (v1.x the swing), taken to hold for its lasers (i1 1) or leapt over (i1 2). +static void visage_throw_update(Entity_NPC& npc) +{ + npc.v1.x = 0; + npc.friction *= THROW_FRICTION; + npc.sprite.Play("Unwind2"); + if (!npc.entityRef) + { + npc.i1 = -1; + npc.state = VISAGE_PULL; + return; + } + + if (npc.sprite.IsEventTriggered("Wind")) visage_hook_throw(npc); + auto* hook = static_cast(npc.entityRef.get()); + if (hook->state != CHAIN_STUCK && hook->state != CHAIN_HOOKED) + { + auto* mask = static_cast(npc.child.get()); + if (hook->state == CHAIN_THROWN && mask) mask->friction *= THROW_HOOK_SLOW; + return; + } + + npc.v1.y = vector_distance(npc.pos, hook->pos); + auto* hooked = static_cast(hook->target.get()); + npc.state = VISAGE_PULL; + if (!is_visage(hooked, VISAGE_MASK)) return; + + Entity* target = npc.GetPlayerTarget(); + float facing = vector_dot(vector_normalized(vector_sub(target->pos, npc.pos)), + vector_normalized(vector_sub(hooked->pos, npc.pos))); + if (npc.projectileDelay >= PULL_PATIENCE || Random() % PULL_PLAIN_ODDS == 0) + { + npc.i1 = 2; + return; + } + bool isSwung = hooked->state == MASK_STUNNED || + (facing <= PULL_FACING && (facing <= PULL_SIDE_FACING || (Random() & 3) != 0)); + if (!isSwung) + { + npc.i1 = 1; + return; + } + + Vector side = vector_rotated(vector_normalized(vector_sub(hooked->pos, npc.pos)), RIGHT_ANGLE_DEGREES); + npc.v1.x = vector_dot(side, vector_sub(target->pos, hooked->pos)) <= 0 ? -PULL_SWING : PULL_SWING; + npc.i1 = 0; +} + +// The pull's end on what it hooked: a player is hurt, a bomb goes off, the mask is held, leapt over or let go. +static void visage_pull_end(Entity_NPC& npc, Entity_NPC& hook, Entity* hooked) +{ + game_shake_screen(PULL_END_SHAKE); + if (hooked && !hooked->isDead) + { + if (hooked->type == ENTITY_PLAYER) + hooked->TakeDamage(PULL_PLAYER_DAMAGE, 0, EntityRef(&npc), PULL_DAMAGE_COUNTDOWN); + else if (hooked->type == ENTITY_BOMB) + { + auto* bomb = static_cast(hooked); + bomb->explosionCountdown = 1; + bomb->explosionCountdown2 = 1; + } + else if (is_visage(hooked, VISAGE_MASK)) + { + auto* mask = static_cast(hooked); + if (npc.i1 == 1 && mask->state != MASK_STUNNED) + { + mask->state = MASK_LASERS; + npc.entityDeque[0] = mask; + npc.state = VISAGE_HOLD; + } + else if (npc.i1 == 2) + { + if (mask->state == MASK_PULLED) mask->state = MASK_WALK; + npc.targetPosition = npc.GetPlayerTarget()->pos; + npc.state = VISAGE_JUMP_UP; + } + else if (mask->state == MASK_PULLED) mask->state = MASK_WALK; + } + hooked->velocity = {}; + } + hook_retract(hook); +} + +// The pull of a swung mask: dragged at 9 while swinging sideways (shooting every other frame until it faces the +// target), it slams back off a wall with rock shots. +static void visage_swing_update(Entity_NPC& npc, Entity_NPC& mask, Vector toHeart) +{ + mask.velocity = vector_scale(mask.velocity, timescale_factor(PULL_SLOW, npc.speedMultiplier)); + Vector inward = vector_normalized(toHeart); + Vector outward = vector_normalized(vector_scale(toHeart, -1)); + Vector swing = vector_scale(vector_rotated(outward, RIGHT_ANGLE_DEGREES), npc.v1.x); + if (npc.stateFrame < VISAGE_PULL_FRAMES + 1) + { + mask.velocity = vector_add(mask.velocity, vector_scale(vector_add(swing, vector_scale(inward, PULL_SWING)), + mask.speedMultiplier)); + if (npc.GetIntervalTicks(2, 0) && mask.state != MASK_STUNNED) + { + ProjectileParams params; + params.heightModifier += SLAM_SHOT_RAISE; + mask.FireProjectiles(mask.pos, vector_scale(inward, PULL_SHOT_SPEED), PROJECTILES_SINGLE, params); + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + } + if (npc.stateFrame > PULL_SWING_FRAMES) + { + Vector heading = vector_normalized( + vector_sub(vector_scale(vector_rotated(outward, RIGHT_ANGLE_DEGREES), PULL_SWING_TURN * npc.v1.x), + vector_scale(inward, PULL_SWING))); + Vector toTarget = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + if (vector_dot(heading, toTarget) > PULL_SWING_AIM) npc.stateFrame = VISAGE_PULL_FRAMES; + } + } + else + mask.velocity = vector_add(mask.velocity, vector_scale(vector_sub(swing, vector_scale(inward, PULL_SWING)), + mask.speedMultiplier)); + if (!mask.isCollidesWithGrid) return; + + mask.velocity = vector_scale(vector_rotated(outward, RIGHT_ANGLE_DEGREES), -npc.v1.x); + npc.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, 1, SLAM_DELAY, false, 1); + game_shake_screen(VISAGE_SLAM_SHAKE); + ProjectileParams params = slam_params_get(); + int count = mask.state == MASK_STUNNED ? (int)(Random() & 1) + 6 : (int)(Random() & 3) + 10; + mask.FireBossProjectiles(count, {}, 0, params); + npc.v1.y = vector_distance(npc.pos, npc.entityRef->pos); + if (npc.sprite.SetAnimation("Rewind2")) + { + npc.sprite.animState.Rewind(); + npc.sprite.animState.isPlaying = true; + } + if (npc.sprite.animState.animData) npc.sprite.SetFrame(SWING_REWIND_FRAME); + visage_spawn_particles(mask.pos, vector_scale(mask.gridCollisionNormal, -1)); + npc.v1.x = 0; + npc.stateFrame = 0; +} + +// The heart winds the chain in on what it hooked (or itself to the wall the hook stuck in) until it arrives. +static void visage_pull_update(Entity_NPC& npc, int ticks) +{ + npc.sprite.Play("Rewind2"); + bool isRewinding = npc.sprite.WasEventTriggered("Wind") || npc.sprite.IsFinished(); + if (isRewinding) npc.stateFrame += ticks; + + auto* hook = static_cast(npc.entityRef.get()); + bool isHookPulling = hook && (hook->state == CHAIN_STUCK || hook->state == CHAIN_HOOKED); + if (!isHookPulling) + { + auto* mask = static_cast(npc.child.get()); + if (mask && mask->state == MASK_PULLED) mask->state = MASK_WALK; + npc.state = VISAGE_IDLE; + npc.projectileCooldown = (int)(Random() % IDLE_COOLDOWN_RANGE) + IDLE_COOLDOWN; + return; + } + + if (hook->state == CHAIN_STUCK) + { + Vector toHook = vector_sub(hook->pos, npc.pos); + if (npc.isCollidesWithGrid) + { + npc.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, 1, SLAM_DELAY, false, 1); + game_shake_screen(VISAGE_SLAM_SHAKE); + visage_spawn_particles(npc.pos, vector_scale(npc.gridCollisionNormal, -1)); + ProjectileParams params = slam_params_get(); + npc.FireBossProjectiles((int)(Random() & 1) + 5, {}, 0, params); + npc.FireBossProjectiles((int)(Random() & 1) + 5, {}, 0, params); + npc.velocity = {}; + hook_retract(*hook); + visage_pick_target_position(npc); + return; + } + if (isRewinding) + npc.velocity = vector_add(npc.velocity, vector_scale(vector_normalized(toHook), PULL_HOLD_SPEED * npc.speedMultiplier)); + if (npc.stateFrame > PULL_STUCK_FRAMES) hook_retract(*hook); + return; + } + + npc.friction *= THROW_FRICTION; + Entity* hooked = hook->target.get(); + if (!hooked || hooked->isDead || vector_distance(hooked->pos, npc.pos) <= PULL_REACHED) + return visage_pull_end(npc, *hook, hooked); + + Vector toHeart = vector_sub(npc.pos, hooked->pos); + if (!isRewinding) + { + hooked->velocity = vector_scale(hooked->velocity, timescale_factor(PULL_PLAYER_SLOW, npc.speedMultiplier)); + float slack = std::max(vector_length(toHeart) - npc.v1.y, 0.0f); + hooked->velocity = + vector_add(hooked->velocity, vector_scale(vector_normalized(toHeart), slack * hooked->speedMultiplier)); + return; + } + + if (hooked->type == ENTITY_PLAYER) + { + splat_make(*hooked, random_unit() * PULL_SPLAT_RANGE + PULL_SPLAT_SIZE); + float slow = timescale_factor(PULL_PLAYER_SLOW, npc.speedMultiplier); + hooked->velocity = vector_add(vector_scale(vector_normalized(toHeart), PULL_PLAYER_SPEED * npc.speedMultiplier), + vector_scale(hooked->velocity, slow)); + } + else if (is_visage(hooked, VISAGE_MASK)) + { + auto* mask = static_cast(hooked); + if (npc.v1.x != 0) + { + return visage_swing_update(npc, *mask, toHeart); + } + mask->velocity = vector_scale(mask->velocity, timescale_factor(PULL_SLOW, npc.speedMultiplier)); + mask->velocity = + vector_add(mask->velocity, vector_scale(vector_normalized(toHeart), PULL_SPEED * mask->speedMultiplier)); + if (npc.i1 == 1) npc.velocity = vector_sub(npc.velocity, vector_scale(vector_normalized(toHeart), PULL_SPEED)); + } + else + { + hooked->velocity = vector_scale(hooked->velocity, timescale_factor(PULL_SLOW, npc.speedMultiplier)); + hooked->velocity = + vector_add(hooked->velocity, vector_scale(vector_normalized(toHeart), PULL_SPEED * hooked->speedMultiplier)); + } + if (npc.stateFrame > VISAGE_PULL_FRAMES) hook_retract(*hook); +} + +// Its broken attacks' pick once its cooldown runs out: the draw with three balls out (one time in two), a shot ring, +// or a plasma ball while under the room's cap (sent at a stunned mask when it has one). +static void visage_attack_pick(Entity_NPC& npc) +{ + size_t plasmas = entity_query(ENTITY_VISAGE, VISAGE_PLASMA).size(); + bool isRingPicked = false; + if (plasmas >= PLASMA_RING_MIN) + { + if ((Random() & 1) == 0) + { + npc.state = VISAGE_DRAW; + npc.sprite.Play("Attack4"); + npc.projectileCooldown = 0; + npc.stateFrame = 0; + return; + } + isRingPicked = true; + } + else if (plasmas > 0) isRingPicked = true; + if (isRingPicked && (Random() % VISAGE_RING_ODDS == 0 || visage_plasma_cap() <= plasmas)) + { + npc.state = VISAGE_RING_LOOP; + npc.sprite.Play("Attack3"); + npc.projectileCooldown = 0; + return; + } + if (plasmas >= visage_plasma_cap()) return; + + npc.state = VISAGE_PLASMA_SPIT; + npc.i1 = 0; + auto* mask = static_cast(npc.child.get()); + if (mask && mask->state == MASK_STUNNED && (plasmas == 0 || (Random() & 1) == 0)) npc.i1 = 1; +} + +// The draw: everything within 600 but fires is pulled in (players at 0.6, its own balls at 1.6, which it then +// swallows), the mask stunned first. +static void visage_draw_in(Entity_NPC& npc) +{ + auto* mask = static_cast(npc.child.get()); + if (npc.projectileCooldown == DRAW_MASK_STUN && mask && mask->state != MASK_STUNNED) + { + mask_stun(*mask); + uint32_t seed = Random(); + Entity* plasma = g_game->Spawn({.position = npc.pos, .type = ENTITY_VISAGE, .variant = VISAGE_PLASMA, .seed = seed}); + plasma->ClearEntityFlags(FLAG_APPEAR); + plasma->parent = &npc; + npc.PlaySound(SOUND_CANDLE_LIGHT, 1, 2, false, 1); + } + + std::vector entities(g_game->room->entityList.updateEL.begin(), g_game->room->entityList.updateEL.end()); + for (Entity* other : entities) + { + if (other == &npc) continue; + int type = other->type; + if ((type < ENTITY_FIRST_ENEMY || type > ENTITY_LAST_ENEMY || type == ENTITY_FIREPLACE) && + type != ENTITY_PLAYER && type != ENTITY_TEAR && type != ENTITY_PROJECTILE && type != ENTITY_PICKUP) + continue; + + Vector toHeart = vector_sub(npc.pos, other->pos); + float distance = vector_length(toHeart); + float pull = std::clamp((DRAW_REACH - distance) * DRAW_PULL / DRAW_REACH, 0.0f, DRAW_PULL); + if (type == ENTITY_PLAYER) pull *= DRAW_PLAYER_SHARE; + else if (is_visage(other, VISAGE_PLASMA) && other->parent.get() == &npc) + { + pull *= DRAW_PLASMA_SHARE; + static_cast(other)->state = PLASMA_DRAWN; + } + npc_push(*other, vector_scale(vector_normalized(toHeart), pull)); + } +} + +// Its draw's end: back to idling, its balls drifting again. +static void visage_draw_end(Entity_NPC& npc) +{ + npc.state = VISAGE_IDLE2; + npc.projectileCooldown = (int)(Random() % IDLE_COOLDOWN_RANGE) + IDLE2_COOLDOWN; + for (Entity* entity : g_game->room->entityList.updateEL) + if (is_visage(entity, VISAGE_PLASMA) && entity->parent.get() == &npc) + static_cast(entity)->state = PLASMA_DRIFT; +} + +// The draw's attack: it stuns the mask and sends a ball in, pulls, fires four lasers and rings fire for each ball it +// swallowed. +static void visage_draw_update(Entity_NPC& npc, int ticks) +{ + npc.friction *= RING_FRICTION; + if (npc.projectileCooldown >= DRAW_START && !npc.sprite.WasEventTriggered("Break")) visage_draw_in(npc); + + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_FIRE_RUSH, 1, 2, false, 1); + for (int i = 0; i < DRAW_LASERS; i++) + { + float angle = (float)i * RIGHT_ANGLE_DEGREES + CRACKWAVE_OFFSET; + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = npc.pos, + .posOffset = vector_make(0, DRAW_LASER_HEIGHT), + .source = &npc, + .angleDegrees = angle, + .timeout = DRAW_LASER_TIMEOUT, + .variant = 1}); + laser->renderDepthOffset = std::sin(angle * DEGREES_TO_RADIANS) >= 0 ? VISAGE_FRONT_DEPTH : 0; + laser->maxDistance = DRAW_LASER_REACH; + laser->Update(); + } + } + + if (!npc.sprite.animState.animData) visage_draw_end(npc); + else + { + if (npc.sprite.animState.WasEventTriggered("Shoot") && npc.GetIntervalTicks(2, 0) && npc.stateFrame > 0) + { + npc.stateFrame--; + for (int i = 0; i < FIRE_RING_SHOTS; i++) + { + float angle = (float)i * FIRE_RING_STEP + (float)npc.stateFrame * FIRE_RING_TWIST; + Vector velocity = vector_scale(vector_from_angle(angle), FIRE_RING_SPEED); + uint32_t seed = Random(); + auto* shot = static_cast(g_game->Spawn({.position = npc.pos, .velocity = velocity, + .spawner = &npc, .type = ENTITY_PROJECTILE, + .variant = PROJECTILE_FIRE, .seed = seed})); + shot->SetColor(VISAGE_FIRE_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + shot->projectileFlags = PROJECTILE_HIT_ENEMIES | PROJECTILE_NO_WALL_COLLIDE; + shot->parent = &npc; + shot->Update(); + } + } + if (npc.sprite.IsFinished()) visage_draw_end(npc); + } + npc.projectileCooldown += ticks; +} + +// The ring: 16 rock shots orbiting it at 10, released after 60 frames. +static void visage_ring_update(Entity_NPC& npc) +{ + npc.friction *= RING_FRICTION; + if (npc.sprite.IsFinished()) npc.sprite.Play("Attack3Loop"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_THUMBS_DOWN, 0.5f, 2, false, 1); + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + for (int i = 0; i < VISAGE_RING_SHOTS; i++) + { + Vector velocity = vector_scale(vector_from_angle((float)i * RING_STEP), VISAGE_RING_SPEED); + uint32_t seed = Random(); + auto* shot = static_cast(g_game->Spawn({.position = npc.pos, .velocity = velocity, + .spawner = &npc, .subType = RING_ORBITING, + .type = ENTITY_PROJECTILE, .seed = seed})); + shot->height = VISAGE_RING_HEIGHT; + shot->fallingSpeed = 0; + shot->scale = 1; + shot->projectileFlags = PROJECTILE_NO_WALL_COLLIDE; + shot->parent = &npc; + shot->targetPosition = npc.pos; + shot->Update(); + } + } + + npc.projectileCooldown++; + if (npc.projectileCooldown <= RING_HOLD) return; + + npc.state = VISAGE_RING_END; + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity->type == ENTITY_PROJECTILE && entity->parent.get() == &npc && entity->subtype == RING_ORBITING) + entity->subtype = RING_RELEASED; +} + +// The heart's state after an attack: back to idling once the animation ends. +static void visage_attack_finish(Entity_NPC& npc) +{ + if (!npc.sprite.IsFinished()) return; + + npc.state = VISAGE_IDLE2; + npc.projectileCooldown = (int)(Random() % IDLE_COOLDOWN_RANGE) + IDLE2_COOLDOWN; +} + +// Its frame while broken free once: walking, throwing the hook now and then, and timing how long it stood near one spot. +static void visage_idle_update(Entity_NPC& npc, int ticks) +{ + npc.sprite.Play("Idle2"); + if (npc.projectileCooldown > 0) npc.projectileCooldown -= ticks; + + auto* mask = static_cast(npc.child.get()); + bool isThrowing; + if (!mask || mask->state == MASK_STUNNED) + { + npc.friction *= CHAINED_FRICTION; + npc.pathfinder.MoveRandomlyBoss(STATUS_OBEYED); + isThrowing = npc.projectileCooldown < 1 && Random() % THROW_ODDS_ALONE == 0; + } + else + { + visage_walk(npc, CHAINED_FRICTION, VISAGE_WALK_SPEED, 1); + isThrowing = npc.projectileCooldown < 1 && Random() % THROW_ODDS == 0 && + vector_distance(npc.pos, npc.child->pos) > THROW_MASK_DISTANCE; + } + if (isThrowing && npc.entityRef) npc.state = VISAGE_THROW; + + if (vector_is_zero(npc.v2) || vector_distance(npc.v2, npc.pos) > PULL_STAY_DISTANCE) + { + npc.v2 = npc.pos; + npc.projectileDelay = 0; + } + else npc.projectileDelay += ticks; +} + +// Its frame twice broken: walking and picking an attack when its cooldown runs out. +static void visage_idle2_update(Entity_NPC& npc) +{ + npc.sprite.Play("Idle3"); + auto* mask = static_cast(npc.child.get()); + if (!mask || mask->state == MASK_STUNNED) + { + npc.friction *= IDLE2_FRICTION; + npc.pathfinder.MoveRandomlyBoss(STATUS_OBEYED); + } + else visage_walk(npc, IDLE2_FRICTION, WALK_SPEED2, npc.speedMultiplier); + + if (npc.projectileCooldown > 0) npc.projectileCooldown--; + if (npc.projectileCooldown == 0 && Random() % VISAGE_ATTACK_ODDS == 0) visage_attack_pick(npc); +} + +// A break: chips fly, it crumbles and becomes vulnerable, then moves on to its next phase. +static bool visage_break_update(Entity_NPC& npc, std::string_view animation, int brokenState) +{ + npc.friction *= BREAK_FRICTION; + npc.sprite.Play(animation); + if (npc.sprite.IsEventTriggered("Break")) + { + if (brokenState == VISAGE_BROKEN) + { + float speed = random_unit() * 2 + 3; + visage_chips_spawn(npc, speed, (int)(Random() & 3) + 3); + } + else + { + float speed = random_unit() * 3 + 4; + visage_chips_spawn(npc, speed, (int)(Random() & 7) + 8); + uint32_t seed = Random(); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + } + npc.PlaySound(SOUND_ROCK_CRUMBLE, 1, 2, false, 1); + npc.ClearEntityFlags(VISAGE_HIDDEN_FLAGS); + npc.state = brokenState; + npc.isInvincible = false; + } + return npc.sprite.IsFinished(); +} + +// The heart's shared end of a frame: losing the hook ends the chained phase, half health breaks it free (damage past +// half is held back until it does), and its death takes its shots and balls with it. +static void visage_frame_end(Entity_NPC& npc) +{ + if (npc.state < VISAGE_BROKEN2) + { + if (npc.state < VISAGE_BROKEN) + { + if (!npc.entityRef && npc.state != VISAGE_BREAKING) + { + g_manager->sfxManager.Stop(SOUND_CHAIN_LOOP); + if (npc.child) static_cast(npc.child.get())->state = MASK_BREAKING; + npc.state = VISAGE_BREAKING; + } + } + else + { + float half = npc.maxHitPoints * BREAK_HEALTH; + if (npc.health - npc.pendingDamage <= half) + { + if (npc.state == VISAGE_IDLE) npc.state = VISAGE_BREAKING2; + else if (npc.pendingDamage > 0) + { + float pending = npc.pendingDamage; + float allowed = std::min(npc.health - half, pending); + npc.pendingDamage = 0; + for (DamageEvent& event : npc.damageEvents) + { + event.damage *= allowed / pending; + npc.pendingDamage += event.damage; + } + } + } + } + } + if (!npc.isDead) return; + + std::vector entities(g_game->room->entityList.updateEL.begin(), g_game->room->entityList.updateEL.end()); + for (Entity* entity : entities) + { + if (entity->type == ENTITY_PROJECTILE) + { + if (entity->parent.get() == &npc) entity->isDead = true; + } + else if (is_visage(entity, VISAGE_PLASMA)) entity->Kill(EntityRef(&npc)); + } +} + +// 005a7b20 The Visage's heart: chained to its mask it winds the chain to swing it, breaks free at the chain's loss to +// hook and pull with it, and below half health breaks again to fight with plasma, shot rings and its draw. +static void visage_heart_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + switch (npc.state) + { + case NPC_STATE_INIT: + { + layer_additive_set(*npc.sprite.GetLayer(VISAGE_GLOW_LAYER)); + npc.state = VISAGE_CHAINED; + npc.isInvincible = true; + npc.splatColor = VISAGE_SPLAT_COLOR; + npc.AddEntityFlags(VISAGE_HIDDEN_FLAGS); + npc.v1.x = 0; + npc.ClearDequeRefs(); + npc.entityDeque.push_back(EntityPtr()); + npc.v1.y = VISAGE_LEASH_LENGTH; + + uint32_t seed = Random(); + Entity* mask = g_game->Spawn({.position = vector_add(npc.pos, vector_make(0, MASK_SPAWN_DROP)), + .type = ENTITY_VISAGE, + .variant = VISAGE_MASK, + .seed = seed}); + mask->parent = &npc; + npc.child = mask; + visage_spawn_chain(npc); + break; + } + case VISAGE_CHAINED: + { + npc.sprite.Play("Idle1"); + npc.pathfinder.MoveRandomlyBoss(STATUS_OBEYED); + npc.friction *= CHAINED_FRICTION; + Room& room = *g_game->room; + room_path_mark(room, room.GetGridIndex(npc.pos), GRID_PATH_FREED); + if (!npc.child) break; + + Vector toMask = vector_sub(npc.child->pos, npc.pos); + float pull = std::min(vector_length(toMask) - npc.v1.y, LEASH_PULL_MAX); + if (pull > 0) npc_push(npc, vector_scale(vector_normalized(toMask), pull * LEASH_PULL_SHARE)); + break; + } + case VISAGE_UNWIND: + npc.sprite.Play("Unwind"); + if (npc.sprite.WasEventTriggered("Wind")) + { + npc.v1.y += LEASH_UNWIND; + if (npc.child) + npc.velocity = vector_sub(npc.velocity, vector_scale(npc.child->targetPosition, LEASH_UNWIND_RECOIL)); + } + if (npc.sprite.IsFinished()) npc.state = VISAGE_CHAINED; + break; + case VISAGE_REWIND: + { + npc.sprite.Play("Rewind"); + if (npc.sprite.IsEventTriggered("Wind")) + g_manager->sfxManager.Play(SOUND_CHAIN_LOOP, {.volume = 0.8f, .loop = SOUND_LOOP}); + if (npc.sprite.WasEventTriggered("Wind") || npc.sprite.IsFinished()) + npc.v1.y = std::max(npc.v1.y - LEASH_REWIND, LEASH_REWIND_FLOOR); + if (npc.v1.y >= LEASH_REWOUND) break; + + g_manager->sfxManager.Stop(SOUND_CHAIN_LOOP); + npc.v1.y = VISAGE_LEASH_LENGTH; + if (npc.child) static_cast(npc.child.get())->state = MASK_HUNT; + npc.state = VISAGE_CHAINED; + break; + } + case VISAGE_BREAKING: + case VISAGE_BROKEN: + if (!visage_break_update(npc, "Transition", VISAGE_BROKEN)) break; + npc.state = VISAGE_IDLE; + if (!npc.entityRef) visage_spawn_chain(npc); + break; + case VISAGE_IDLE: + visage_idle_update(npc, ticks); + break; + case VISAGE_THROW: + visage_throw_update(npc); + break; + case VISAGE_PULL: + visage_pull_update(npc, ticks); + break; + case VISAGE_HOLD: + npc.sprite.Play("Idle2"); + if (visage_hold(npc)) break; + npc.state = VISAGE_IDLE; + npc.projectileCooldown = (int)(Random() % IDLE_COOLDOWN_RANGE) + IDLE_COOLDOWN; + break; + case VISAGE_JUMP_UP: + npc.sprite.Play("JumpUp"); + npc.friction *= VISAGE_JUMP_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) npc.entityCollisionClass = ENTCOLL_NONE; + if (!npc.sprite.IsFinished()) break; + npc.pos = npc.targetPosition; + npc.state = VISAGE_JUMP_DOWN; + break; + case VISAGE_JUMP_DOWN: + npc.sprite.Play("JumpDown"); + npc.friction *= VISAGE_JUMP_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, VISAGE_LAND_VOLUME, 2, false, 1); + game_shake_screen(VISAGE_SLAM_SHAKE); + slam_shots_fire(npc, 3, 10); + for (int i = 0; i < VISAGE_CRACKWAVES; i++) + { + uint32_t seed = Random(); + auto* wave = static_cast(g_game->Spawn({.position = npc.pos, .spawner = &npc, + .subType = 1, .type = ENTITY_EFFECT, + .variant = EFFECT_CRACKWAVE, .seed = seed})); + wave->parent = &npc; + wave->rotation = (float)i * RIGHT_ANGLE_DEGREES + CRACKWAVE_OFFSET; + } + } + if (!npc.sprite.IsFinished()) break; + npc.state = VISAGE_IDLE; + npc.projectileCooldown = (int)(Random() % IDLE_COOLDOWN_RANGE) + IDLE_COOLDOWN; + break; + case VISAGE_BREAKING2: + case VISAGE_BROKEN2: + if (visage_break_update(npc, "Transition2", VISAGE_BROKEN2)) npc.state = VISAGE_IDLE2; + break; + case VISAGE_IDLE2: + visage_idle2_update(npc); + break; + case VISAGE_PLASMA_SPIT: + npc.sprite.Play("Attack"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + float angle = ((float)(Random() & 3) * RIGHT_ANGLE_DEGREES + CRACKWAVE_OFFSET); + uint32_t seed = Random(); + Entity* plasma = g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(vector_from_angle(angle), PLASMA_SPEED), + .spawner = &npc, + .type = ENTITY_VISAGE, + .variant = VISAGE_PLASMA, + .seed = seed}); + plasma->ClearEntityFlags(FLAG_APPEAR); + plasma->parent = &npc; + if (npc.i1 != 0 && npc.child) plasma->target = npc.child.get(); + npc.PlaySound(SOUND_CANDLE_LIGHT, 1, 2, false, 1); + npc.PlaySound(SOUND_HEARTOUT, 1, 2, false, 1); + } + visage_attack_finish(npc); + break; + case VISAGE_RING_LOOP: + visage_ring_update(npc); + break; + case VISAGE_RING_END: + npc.friction *= RING_FRICTION; + npc.sprite.Play("Attack3End"); + visage_attack_finish(npc); + break; + case VISAGE_DRAW: + visage_draw_update(npc, ticks); + break; + default: + break; + } + visage_frame_end(npc); +} + +// The mask's charge along its aim, bouncing off walls at a glance and stopping head on into one with a slam. +static bool mask_charge_hit(Entity_NPC& mask, std::string_view hitAnimation) +{ + if (!mask.isCollidesWithGrid) return false; + + Vector normal = mask.gridCollisionNormal; + Vector incoming = mask.gridCollisionVelocity; + if (std::abs(vector_dot(normal, vector_normalized(incoming))) < MASK_HEAD_ON) + { + mask.velocity = vector_sub(incoming, vector_scale(normal, 2 * vector_dot(incoming, normal))); + return false; + } + mask.sprite.Play(direction_animation(hitAnimation, mask.targetPosition)); + mask.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, 1, SLAM_DELAY, false, 1); + return true; +} + +// The mask hunting on its chain: drifting at its target, lunging now and then, and charging when lined up. +static void mask_hunt_update(Entity_NPC& mask, int ticks) +{ + Vector toTarget = vector_normalized(vector_sub(mask.GetPlayerTarget()->pos, mask.pos)); + if (mask.projectileCooldown < MASK_LUNGE_WAIT) + { + if (Random() % MASK_LUNGE_ODDS == 0) + { + mask.projectileCooldown = (int)(Random() % MASK_LUNGE_RANGE) + MASK_LUNGE_MIN; + mask.targetPosition = toTarget; + } + } + else mask.projectileCooldown--; + + if (mask.projectileCooldown < 1) + mask.velocity = vector_add(mask.velocity, vector_scale(toTarget, MASK_HUNT_SPEED * mask.speedMultiplier)); + else + { + float speed = random_unit() * MASK_LUNGE_SPEED + MASK_HUNT_SPEED; + mask.velocity = vector_add(mask.velocity, vector_scale(mask.targetPosition, speed * mask.speedMultiplier)); + mask.targetPosition = vector_normalized(vector_add(mask.targetPosition, vector_scale(toTarget, MASK_LUNGE_TURN))); + } + mask_face(mask, toTarget); + mask_animate(mask); + if (mask.stateFrame > 0) mask.stateFrame -= ticks; + + bool isLinedUp = vector_dot(toTarget, vector_cardinal(toTarget)) > MASK_LINED_UP; + if (isLinedUp && Random() % MASK_CHARGE_ODDS == 0 && mask.stateFrame < 1 && mask.projectileCooldown < 1) + { + Vector end = Entity_Laser::CalculateEndPoint(mask.pos, toTarget, {}, nullptr, MASK_CHARGE_MARGIN); + if (vector_distance(mask.pos, end) > MASK_CHARGE_ROOM) + { + mask.targetPosition = toTarget; + mask.state = MASK_CHARGE_BEGIN; + static_cast(mask.parent.get())->state = VISAGE_UNWIND; + mask.sprite.Play(direction_animation("ChargeBegin", mask.targetPosition)); + } + } + mask_leash(mask); +} + +// 005acb70, 005acbf0 The mask's two laser sweeps: out, then back the other way. +static void mask_lasers_out(Entity_Effect* timer) +{ + laser_sweep_set(timer->child.get(), -MASK_LASER_SWEEP, -MASK_LASER_TURN_SPEED); + laser_sweep_set(timer->target.get(), MASK_LASER_SWEEP, MASK_LASER_TURN_SPEED); +} + +static void mask_lasers_back(Entity_Effect* timer) +{ + laser_sweep_set(timer->child.get(), MASK_LASER_SWEEP, MASK_LASER_TURN_SPEED); + laser_sweep_set(timer->target.get(), -MASK_LASER_SWEEP, -MASK_LASER_TURN_SPEED); +} + +// The mask's eye lasers while the heart holds it: two beams beside each other, turning out and back. +static void mask_lasers_fire(Entity_NPC& mask) +{ + Vector axis = vector_from_direction(mask.i1); + Vector side = vector_scale(vector_rotated(axis, RIGHT_ANGLE_DEGREES), + axis.y == 0 ? MASK_LASER_GAP : MASK_LASER_GAP_VERTICAL); + float angle = vector_angle(axis); + std::array lasers; + for (int i = 0; i < 2; i++) + { + Vector origin = i == 0 ? vector_add(mask.pos, side) : vector_sub(mask.pos, side); + lasers[i] = Entity_Laser::ShootAngle({.position = origin, + .posOffset = vector_make(0, MASK_LASER_HEIGHT), + .source = &mask, + .angleDegrees = angle, + .timeout = DRAW_LASER_TIMEOUT, + .variant = 1}); + lasers[i]->renderDepthOffset = axis.y >= 0 ? VISAGE_FRONT_DEPTH : 0; + float turn = i == 0 ? 1.0f : -1.0f; + laser_sweep_set(lasers[i], turn * MASK_LASER_TURN, turn * MASK_LASER_TURN_SPEED); + lasers[i]->Update(); + } + + for (auto [callback, delay] : {std::pair{&mask_lasers_out, MASK_LASER_TURN_FRAMES}, + std::pair{&mask_lasers_back, MASK_LASER_BACK_FRAMES}}) + { + Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(callback), delay, 0, false); + timer->child = lasers[0]; + timer->target = lasers[1]; + } +} + +// The mask's chain break: its links burst into gibs as it roars free. +static void mask_break_update(Entity_NPC& mask) +{ + mask.friction *= BREAK_FRICTION; + mask.sprite.Play("Transition"); + if (mask.sprite.animState.animData) + { + if (mask.sprite.animState.IsEventTriggered("Break")) + { + float reach = mask.size * HALF; + int count = (int)(Random() & GIB_EXTRA_MASK) + GIBS_MIN; + for (; count != 0; count--) + { + uint32_t seed = Random(); + Vector heading = random_direction(); + Vector velocity = vector_scale(heading, random_unit() * VISAGE_GIB_SPEED_RANGE + VISAGE_GIB_SPEED_MIN); + Vector at = random_direction(); + g_game->Spawn({.position = vector_add(mask.pos, vector_scale(at, reach)), .velocity = velocity, + .type = ENTITY_EFFECT, .variant = EFFECT_CHAIN_GIB, .seed = seed})->Update(); + } + mask.PlaySound(SOUND_CHAIN_BREAK, 1, 2, false, 1); + mask.PlaySound(SOUND_GHOST_ROAR, 1, 2, false, 1); + mask.state = MASK_BROKEN; + } + if (mask.sprite.animState.isPlaying) return; + } + mask.ClearEntityFlags(VISAGE_HIDDEN_FLAGS); + mask.isInvincible = false; + mask.state = MASK_WALK; + mask.i2 = 0; + mask.targetPosition = {}; +} + +// The mask walking free: along its last aim (dropped after 4 frames off it) or wandering, turning to face its target +// when lined up with it. +static void mask_walk_update(Entity_NPC& mask, float speedScale, int ticks) +{ + if (!vector_is_zero(mask.targetPosition)) + { + if (vector_dot(mask.targetPosition, mask.velocity) >= speedScale) mask.i2 = 0; + else + { + mask.i2 += ticks; + if (mask.i2 > MASK_TURN_GRACE) mask.targetPosition = {}; + } + mask.velocity = vector_add(mask.velocity, vector_scale(mask.targetPosition, MASK_FREE_SPEED * speedScale)); + } + else mask.pathfinder.MoveRandomlyAxisAligned(speedScale * MASK_WANDER_SHARE, STATUS_OBEYED); + + mask_leash(mask); + mask_face(mask, {}); + mask_animate(mask); + if (Random() % MASK_TURN_ODDS != 0) return; + + Vector toTarget = vector_sub(mask.GetPlayerTarget()->pos, mask.pos); + Vector cardinal = vector_cardinal(toTarget); + if (vector_dot(cardinal, vector_normalized(toTarget)) > MASK_LINED_UP) mask.targetPosition = cardinal; +} + +// The mask's shared end of a frame: it cannot die but stuns at no health (or keeps 0.1 while not walking), stuns when +// the heart dies, and its eye trails follow its eyes, shown while it moves fast. +static void mask_frame_end(Entity_NPC& mask) +{ + if (!mask.isInvincible && mask.health - mask.pendingDamage <= 0) + { + mask.pendingDamage = 0; + mask.pendingDamageFlags = 0; + mask.damageEvents.clear(); + if (mask.state == MASK_WALK) mask_stun(mask); + else mask.health = std::min(mask.health, MASK_DYING_HEALTH); + } + if (mask.parent && mask.parent->isDead) mask_stun(mask); + + float speed = vector_length(mask.velocity) * mask.friction; + for (size_t i = 0; i < EYE_NULLS.size() && i < mask.entityDeque.size(); i++) + { + Entity* trail = mask.entityDeque[i].get(); + if (!trail) continue; + + Vector offset = mask.GetNullOffset(EYE_NULLS[i]); + trail->sprite.color._tint[3] = + vector_is_zero(offset) ? 0 : std::clamp((speed - EYE_TRAIL_SPEED) / EYE_TRAIL_FADE, 0.0f, 1.0f); + trail->pos = vector_add(mask.pos, offset); + } +} + +// 005ab4d0 The Visage's mask: chained, it hunts and charges, swung by the heart. Free of the chain it walks, fires +// its eye lasers while held and wakes to charge when struck by plasma. It never dies, only stuns. +static void visage_mask_update(Entity_NPC& mask) +{ + float speedScale = mask.state > MASK_BREAKING ? MASK_BROKEN_SPEED : 1; + int ticks = npc_ticks_get(mask); + if (!mask.parent && mask.state != MASK_STUNNED) mask_stun(mask); + + switch (mask.state) + { + case NPC_STATE_INIT: + mask.ClearDequeRefs(); + for (int i = 0; i < 2; i++) + { + uint32_t seed = Random(); + auto* trail = static_cast(g_game->Spawn( + {.position = mask.pos, .spawner = &mask, .type = ENTITY_EFFECT, .variant = EFFECT_SPRITE_TRAIL, .seed = seed})); + trail->sprite.color = EYE_TRAIL_COLOR; + trail->minRadius = EYE_TRAIL_RADIUS; + trail->maxRadius = EYE_TRAIL_RADIUS; + trail->sprite.scale = vector_make(EYE_TRAIL_SCALE, EYE_TRAIL_SCALE); + trail->parent = &mask; + mask.entityDeque.emplace_back() = trail; + } + layer_additive_set(*mask.sprite.GetLayer(VISAGE_GLOW_LAYER)); + mask.AddEntityFlags(VISAGE_HIDDEN_FLAGS); + mask.state = MASK_HUNT; + mask.stateFrame = MASK_START_WAIT; + mask.isInvincible = true; + mask_face(mask, vector_make(0, 1)); + break; + case MASK_HUNT: + mask_hunt_update(mask, ticks); + break; + case MASK_CHARGE_BEGIN: + mask_leash(mask); + if (mask.sprite.GetFrame() > MASK_AIM_FRAME && mask.stateFrame < 1) + { + Entity* target = mask.GetPlayerTarget(); + float lead = vector_distance(mask.pos, target->pos) * MASK_AIM_LEAD; + Vector aimed = vector_add(target->pos, vector_scale(target->velocity, lead)); + mask.targetPosition = vector_normalized(vector_sub(aimed, mask.pos)); + mask.stateFrame = 1; + } + if (mask.sprite.IsEventTriggered("Charge")) + { + float frame = mask.sprite.animState.animData ? mask.sprite.animState.animFrame : ANIMATION_FRAME_UNSET; + mask.sprite.Play(direction_animation("ChargeBegin", mask.targetPosition)); + if (mask.sprite.animState.animData) mask.sprite.SetFrame(frame); + mask.PlaySound(SOUND_MONSTER_ROAR_0, 1, SLAM_DELAY, false, 1); + g_manager->sfxManager.Play(SOUND_CHAIN_LOOP, {.volume = 0.8f, .loop = SOUND_LOOP}); + mask.state = MASK_CHARGE; + } + break; + case MASK_CHARGE: + mask_leash(mask); + if (mask.sprite.IsFinished()) mask.sprite.Play(direction_animation("ChargeLoop", mask.targetPosition)); + mask.velocity = vector_add(mask.velocity, vector_scale(mask.targetPosition, VISAGE_MASK_CHARGE_PUSH)); + if (!mask_charge_hit(mask, "ChargeHit")) break; + g_manager->sfxManager.Stop(SOUND_CHAIN_LOOP); + game_shake_screen(VISAGE_SLAM_SHAKE); + mask.state = MASK_CHARGE_HIT; + visage_spawn_particles(mask.pos, vector_scale(mask.gridCollisionNormal, -1)); + slam_shots_fire(mask, 3, 10); + break; + case MASK_CHARGE_HIT: + mask_leash(mask); + if (!mask.sprite.IsFinished()) break; + mask_face(mask, mask.targetPosition); + mask_animate(mask); + static_cast(mask.parent.get())->state = VISAGE_REWIND; + mask.stateFrame = (int)(Random() % MASK_REST_RANGE) + MASK_REST; + break; + case MASK_BREAKING: + case MASK_BROKEN: + mask_break_update(mask); + break; + case MASK_WALK: + mask_walk_update(mask, speedScale, ticks); + break; + case MASK_STUNNED: + { + auto* visage = static_cast(mask.parent.get()); + bool isHooked = visage && visage->entityRef && visage->entityRef->target.get() == &mask; + if (!isHooked) + { + mask.friction *= MASK_STUN_FRICTION; + mask_animate(mask); + break; + } + [[fallthrough]]; + } + case MASK_PULLED: + mask_leash(mask); + mask_face(mask, vector_sub(mask.pos, mask.parent->pos)); + mask_animate(mask); + break; + case MASK_LASERS: + mask_animate(mask); + if (mask.sprite.IsEventTriggered("Break")) mask_lasers_fire(mask); + if (mask.sprite.IsFinished()) mask.state = MASK_WALK; + break; + case MASK_CHARGE2: + mask.velocity = vector_add(mask.velocity, vector_scale(mask.targetPosition, MASK_CHARGE2_PUSH)); + if (!mask_charge_hit(mask, "Charge2Hit")) break; + { + game_shake_screen(VISAGE_SLAM_SHAKE); + mask.state = MASK_CHARGE2_HIT; + visage_spawn_particles(mask.pos, vector_scale(mask.gridCollisionNormal, -1)); + ProjectileParams params; + mask.FireProjectiles(mask.pos, vector_make(MASK_RING_SPEED, MASK_RING_SHOTS), PROJECTILES_RING, params); + params.variant = PROJECTILE_ROCK; + params.color = COLOR_DEFAULT; + params.heightModifier += SLAM_SHOT_RAISE; + mask.FireBossProjectiles((int)(Random() & 3) + 10, {}, 0, params); + } + break; + case MASK_CHARGE2_HIT: + mask.friction *= VISAGE_JUMP_FRICTION; + if (!mask.sprite.IsFinished()) break; + mask.state = MASK_WALK; + mask_face(mask, mask.targetPosition); + mask_animate(mask); + mask.stateFrame = (int)(Random() % MASK_REST_RANGE) + MASK_REST; + break; + default: + break; + } + mask_frame_end(mask); +} + +// 005acd30 Lays the chain out from its last link up to the heart: links 8 to 16 apart along the line to the heart (from +// the mask while hanging), turned along it, hidden in the heart where it bunches. In the interpolation pass it only +// turns them, from the positions they are drawn at. +static void visage_chain_solve(Entity_NPC& last, bool isInterpolate) +{ + if (!chain_is_last(last)) return; + + Entity_NPC* visage = chain_visage_get(last); + Entity* tail = &last; + while (tail->child) tail = tail->child.get(); + Entity* mask = is_visage(tail, VISAGE_MASK) ? tail : nullptr; + if (!visage) return; + + auto drawn = [](Entity& entity) + { + Vector at = entity.isInterpolating ? entity.preInterpolatePos : entity.pos; + return vector_add(at, vector_scale(entity.velocity, HALF)); + }; + Vector head = visage->pos; + Vector anchor; + Vector direction; + int state = last.state; + if (state == CHAIN_HANGING) + { + if (!mask) return; + anchor = mask->pos; + if (isInterpolate) + { + head = drawn(*visage); + anchor = drawn(*mask); + } + direction = vector_normalized(vector_sub(head, anchor)); + } + else + { + anchor = last.pos; + if (isInterpolate) head = drawn(*visage); + direction = vector_normalized(vector_sub(head, anchor)); + anchor = vector_sub(anchor, vector_scale(direction, CHAIN_LINK_MIN)); + } + + for (Entity_NPC* link = &last; link->parent; link = link->ParentNPC()) + { + float distance = vector_distance(head, anchor); + if (distance > CHAIN_LINK_MIN) + { + Vector next = distance >= CHAIN_LINK_MAX ? vector_add(anchor, vector_scale(direction, CHAIN_LINK_MAX)) : visage->pos; + if (!isInterpolate) + { + link->isVisible = true; + link->entityCollisionClass = ENTCOLL_ALL; + } + if (state == CHAIN_HANGING || !chain_is_last(*link)) + { + link->pos = vector_scale(vector_add(anchor, next), HALF); + link->velocity = {}; + } + link->posOffset.y = VISAGE_CHAIN_HEIGHT; + float angle = vector_angle(direction); + bool isFlipped = angle > RIGHT_ANGLE_DEGREES || angle < -RIGHT_ANGLE_DEGREES; + link->sprite.isFlipX = isFlipped; + link->sprite.rotation = isFlipped ? HALF_TURN_DEGREES - angle : angle; + anchor = next; + } + else if (!isInterpolate) + { + link->pos = visage->pos; + link->isVisible = false; + link->entityCollisionClass = ENTCOLL_NONE; + } + } +} + +// A hanging chain's first link shares damage down it: every link drops to the most hurt one. +static void chain_damage_share(Entity_NPC& first) +{ + float lowest = 1e10f; + for (Entity* link = &first; link && link->variant == VISAGE_CHAIN; link = link->child.get()) + lowest = std::min(lowest, link->health - link->pendingDamage); + for (Entity* link = &first; link && link->variant == VISAGE_CHAIN; link = link->child.get()) + { + float health = link->health - link->pendingDamage; + if (lowest < health) link->TakeDamage(health - lowest, 0, EntityRef(&first), CHAIN_DAMAGE_COUNTDOWN); + } +} + +// 005ad250 A link of the Visage's chain: hanging between heart and mask, it shares damage and frays below a quarter +// health. The last link is the hook the heart throws. A link goes when the heart does, or when the chain hangs from +// nothing before the heart breaks free. A link's death takes the rest of the chain. +static void visage_chain_update(Entity_NPC& link) +{ + if (link.aiCallPhase == AI_PHASE_INTERPOLATE) return visage_chain_solve(link, true); + if (link.i1 != 0) return; + + Entity_NPC* visage = chain_visage_get(link); + Entity_NPC* mask = chain_mask_get(link); + bool isOrphaned = !visage || visage->isDead || (chain_is_first(link) && !mask && visage->state < VISAGE_IDLE); + if (!link.isDead && isOrphaned) + { + if (link.entityCollisionClass == ENTCOLL_NONE) link.Remove(); + else link.Kill(EntityRef()); + } + + switch (link.state) + { + case NPC_STATE_INIT: + link.state = CHAIN_HANGING; + link.splatColor = CHAIN_SPLAT_COLOR; + link.sprite.SetFrame(link.subtype & 1 ? "Idle2" : "Idle1", 0); + if (visage && visage_phase_get(*visage) > 0) + { + link.AddEntityFlags(FLAG_NO_TARGET); + link.state = CHAIN_HIDDEN; + link.isInvincible = true; + if (chain_is_last(link)) + { + link.sprite.SetFrame("Idle3", 0); + link.pos = visage->pos; + } + } + link.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_BLOOD_SPLASH); + link.aiCallFlags |= AI_CALL_INTERPOLATE; + link.entityCollisionClass = ENTCOLL_NONE; + link.i1 = 0; + link.isVisible = false; + break; + case CHAIN_HANGING: + visage_chain_solve(link, false); + break; + case CHAIN_HIDDEN: + if (chain_is_last(link) && visage) + { + link.pos = visage->pos; + link.velocity = {}; + } + visage_chain_solve(link, false); + break; + case CHAIN_THROWN: + link.friction *= CHAIN_THROW_FRICTION; + link.velocity = vector_add(link.velocity, vector_scale(link.targetPosition, CHAIN_THROW_PUSH)); + visage_chain_solve(link, false); + if (link.isCollidesWithGrid || !g_game->room->IsPositionInRoom(link.pos, 0)) + { + link.PlaySound(SOUND_POT_BREAK, 1, 2, false, 1); + link.state = CHAIN_STUCK; + link.velocity = {}; + } + break; + case CHAIN_STUCK: + link.velocity = {}; + visage_chain_solve(link, false); + link.isVisible = false; + break; + case CHAIN_HOOKED: + visage_chain_solve(link, false); + if (!link.target) hook_retract(link); + else + { + link.pos = link.target->pos; + link.velocity = link.target->velocity; + } + if (link.target.get() == mask) link.isVisible = false; + break; + default: + break; + } + + if (link.state == CHAIN_HANGING) + { + if (chain_is_first(link)) chain_damage_share(link); + float frayed = link.maxHitPoints * CHAIN_FRAYED_HEALTH; + const AnimationData* data = link.sprite.animState.animData; + if (link.health >= frayed && link.health - link.pendingDamage < frayed) + { + if (!data) Random(); + else link.sprite.SetFrame((float)((data->length != 1 ? Random() % (uint32_t)(data->length - 1) : 0) + 1)); + } + } + if (!link.isDead) return; + + Entity_NPC* top = &link; + while (top->parent && top->parent->variant == VISAGE_CHAIN) top = top->ParentNPC(); + if (top != &link && top->isDead) return; + for (Entity_NPC* below = top->ChildNPC(); below && below->variant == VISAGE_CHAIN; below = below->ChildNPC()) + { + below->i1 = 1; + if (below->entityCollisionClass == ENTCOLL_NONE) below->Remove(); + else below->Kill(EntityRef()); + } +} + +// 005ad8a0 A plasma ball of the Visage: it drifts about the room bouncing off its sides, seeks a stunned mask it was +// sent at, and slows while the heart draws it in. +static void visage_plasma_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + layer_additive_set(*npc.sprite.GetLayer(VISAGE_GLOW_LAYER)); + npc.state = PLASMA_DRIFT; + npc.splatColor = VISAGE_SPLAT_COLOR; + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.sprite.Play("Idle"); + npc.v1.x = PLASMA_SCALE; + return; + case PLASMA_DRIFT: + { + auto* mask = static_cast(npc.target.get()); + if (mask) + { + if (is_visage(mask, VISAGE_MASK) && mask->state == MASK_STUNNED) + { + Vector heading = vector_normalized(npc.velocity); + Vector toMask = vector_normalized(vector_sub(mask->pos, npc.pos)); + Vector steer = vector_normalized(vector_add(vector_scale(toMask, PLASMA_SEEK_TURN), heading)); + npc.friction *= PLASMA_FRICTION; + npc.v1.x = PLASMA_SCALE_SEEK; + npc.velocity = vector_scale(steer, vector_length(npc.velocity) + 1 / npc.friction); + return; + } + npc.target = nullptr; + } + + Room& room = *g_game->room; + npc.v1.x = PLASMA_SCALE_DRIFT; + if (npc.pos.x < room.topLeftPos.x && npc.velocity.x < 0) npc.velocity.x = 1; + else if (npc.pos.x > room.bottomRightPos.x && npc.velocity.x > 0) npc.velocity.x = -1; + if (npc.pos.y < room.topLeftPos.y && npc.velocity.y < 0) npc.velocity.y = 1; + else if (npc.pos.y > room.bottomRightPos.y && npc.velocity.y > 0) npc.velocity.y = -1; + npc.pos.x = std::min(std::max(npc.pos.x, room.topLeftPos.x), room.bottomRightPos.x); + npc.pos.y = std::min(std::max(npc.pos.y, room.topLeftPos.y), room.bottomRightPos.y); + + Vector sign = vector_make(npc.velocity.x >= 0 ? 1.0f : -1.0f, npc.velocity.y >= PLASMA_RISE_SPEED ? 1.0f : -1.0f); + npc.friction *= PLASMA_FRICTION; + npc_push(npc, vector_scale(sign, PLASMA_DRIFT_PUSH)); + return; + } + case PLASMA_DRAWN: + npc.friction *= PLASMA_DRAWN_FRICTION; + return; + default: + return; + } +} + +// The Visage's AI by variant: the heart, the mask, a chain link or a plasma ball. +void boss_visage_update(Entity_NPC& npc) +{ + switch (npc.variant) + { + case VISAGE_HEART: + return visage_heart_update(npc); + case VISAGE_MASK: + return visage_mask_update(npc); + case VISAGE_CHAIN: + return visage_chain_update(npc); + case VISAGE_PLASMA: + return visage_plasma_update(npc); + default: + return; + } +} + +// 005add40 The Visage's contacts. The drawing heart swallows its balls (each ring of fire one more, healing it to 0.4). +// The mask burns fire shots away, passes the heart holding it and wakes to charge at a ball while free or stunned. The +// thrown hook catches a player, a bomb (held from going off) or the mask. None decides the contact for the others. +std::optional visage_handle_collision(Entity_NPC& npc, Entity& collider) +{ + switch (npc.variant) + { + case VISAGE_HEART: + if (npc.state != VISAGE_DRAW || !is_visage(&collider, VISAGE_PLASMA)) return std::nullopt; + npc.PlaySound(SOUND_BOSS2_BUBBLES, 1, 2, false, (float)npc.stateFrame * SWALLOW_PITCH + 1); + npc.stateFrame++; + collider.Remove(); + npc.SetColor(VISAGE_SWALLOW_COLOR, VISAGE_SWALLOW_FLASH, COLOR_PRIORITY_DEFAULT, true, true); + npc.health = std::min(npc.maxHitPoints * SWALLOW_HEAL + npc.health, npc.maxHitPoints * SWALLOW_HEAL_CAP); + return std::nullopt; + case VISAGE_MASK: + if (collider.type == ENTITY_PROJECTILE && collider.variant == PROJECTILE_FIRE) + { + collider.isDead = true; + return false; + } + if (&collider == npc.parent.get() && npc.state == MASK_LASERS) return true; + if (!is_visage(&collider, VISAGE_PLASMA) || static_cast(collider).state == PLASMA_DRAWN) + return std::nullopt; + if (npc.state == MASK_WALK || npc.state == MASK_STUNNED) + { + collider.Remove(); + npc.SetColor(MASK_SWALLOW_COLOR, VISAGE_SWALLOW_FLASH, COLOR_PRIORITY_DEFAULT, true, true); + visage_start_charge(npc); + } + return std::nullopt; + case VISAGE_CHAIN: + { + if (&collider == npc.target.get()) return true; + if (npc.state != CHAIN_THROWN) return std::nullopt; + if (collider.type == ENTITY_PLAYER) npc.PlaySound(SOUND_MEATY_DEATHS, 1, 2, false, 1); + else if (collider.type == ENTITY_BOMB) + { + auto& bomb = static_cast(collider); + bomb.explosionCountdown++; + bomb.explosionCountdown2 = bomb.explosionCountdown; + } + else if (is_visage(&collider, VISAGE_MASK)) npc.PlaySound(SOUND_POT_BREAK, 1, 2, false, 1); + else return std::nullopt; + + Entity_NPC* mask = chain_mask_get(npc); + if (&collider == mask && mask->state == MASK_WALK) + { + mask_face(*mask, vector_sub(mask->pos, mask->parent->pos)); + mask->state = MASK_PULLED; + } + npc.target = &collider; + npc.state = CHAIN_HOOKED; + npc.velocity = {}; + return true; + } + case VISAGE_PLASMA: + return std::nullopt; + default: + return false; + } +} diff --git a/src/cutscene.cpp b/src/cutscene.cpp index df2e6d4..6c25436 100644 --- a/src/cutscene.cpp +++ b/src/cutscene.cpp @@ -25,7 +25,6 @@ constexpr const char* BODY_FONT_PATH = "font/terminus.fnt"; constexpr uint32_t COLOR_DEBUG_PINK = 0xffffc0cb; constexpr uint32_t COLOR_WHITE = 0xffffffff; constexpr uint32_t COLOR_BLACK = 0xff000000; -constexpr float COLOR_CHANNEL_MAX = 255; constexpr int CREDITS_CUTSCENE = 2; constexpr int MUSIC_CREDITS = 60; @@ -36,7 +35,6 @@ constexpr float CUTSCENE_FADE_STEP = 0.05f; constexpr float VIDEO_VOLUME_SCALE = 3; constexpr float VIDEO_SUBTITLE_SCALE = 2; constexpr float POPUP_BUTTON_HIDDEN_OFFSET = 96; -constexpr uint32_t FRAMES_PER_SECOND = 30; constexpr int TIMING_DRIFT_LIMIT = 3; // Without a part, the screen is laid out for this canvas, as is a temporary part. diff --git a/src/data.h b/src/data.h index 55a5b28..a2e2ab2 100644 --- a/src/data.h +++ b/src/data.h @@ -4,6 +4,9 @@ #include #include +// The root node a converted XML file opens with. +constexpr std::string_view DOCUMENT_TAG = "#document"; + // A game document the import tool converted from XML (items.xml, entities2.xml ...) into resources/.json. // (.anm2 files are Anm2Ed's own JSON documents under their own names instead.) // Each element is {"tag", "attrs", "children", "text"}, with every attribute value kept as the string the XML held, diff --git a/src/entity.h b/src/entity.h index cc48209..bdad525 100644 --- a/src/entity.h +++ b/src/entity.h @@ -115,6 +115,8 @@ enum EntityType : int ENTITY_CRAZY_LONG_LEGS = 207, ENTITY_FLY_L2 = 214, ENTITY_SPIDER_L2 = 215, + ENTITY_TICKING_SPIDER = 250, + ENTITY_MIGRAINE_SPIDER = 869, ENTITY_FULL_FLY = 249, ENTITY_FATTY = 208, ENTITY_BLUBBER = 210, @@ -244,6 +246,7 @@ enum EntityType : int ENTITY_WHIPPER = 834, ENTITY_REVENANT = 841, ENTITY_PON = 840, + ENTITY_WILLO_L2 = 838, ENTITY_SPIKEBALL = 852, ENTITY_SMALL_MAGGOT = 853, ENTITY_ADULT_LEECH = 854, @@ -254,6 +257,7 @@ enum EntityType : int ENTITY_MOCKULUS = 864, ENTITY_EVIS = 865, ENTITY_DARK_ESAU = 866, + ENTITY_MOTHERS_SHADOW = 867, ENTITY_ARMYFLY = 868, ENTITY_SIREN_HELPER = 966, ENTITY_DRIP = 870, @@ -301,6 +305,7 @@ enum EntityType : int ENTITY_FROZEN_ENEMY = 963, ENTITY_DUMMY = 964, ENTITY_MINECART = 965, + ENTITY_HORNFEL_DOOR = 967, ENTITY_EFFECT = 1000, ENTITY_TEXT = 9001 }; @@ -534,6 +539,8 @@ constexpr int COLOR_PRIORITY_DEFAULT = 255; // The priority status effects' colors show at, and the damage a poison or burn ticks for without a source's. constexpr int STATUS_COLOR_PRIORITY = 255; constexpr float STATUS_TICK_DAMAGE_DEFAULT = 2; +// The frames a hit leaves its victim untouchable for, the usual 30. +constexpr int HIT_COUNTDOWN = 30; // Reading and clearing (0040c3a0, 00a0fe80) are the pointer's own. // A pointer to an entity that the entity clears when it goes away (REPENTOGON's EntityPtr). It registers itself with diff --git a/src/entity_bomb.cpp b/src/entity_bomb.cpp index 3c59459..fd5f316 100644 --- a/src/entity_bomb.cpp +++ b/src/entity_bomb.cpp @@ -105,7 +105,6 @@ constexpr float LOW_COLLIDER_SLOW = 0.2f; constexpr float LOW_BOMB_SLOW = 0.5f; constexpr float PLAYER_PUSH = 0.4f; constexpr float PUSH_MIN_DISTANCE = 0.0001f; -constexpr int HIT_COUNTDOWN = 30; // Hydrobounce's bounce: how much of the fall it keeps, its splash's reach and share of the damage, and its sound. constexpr float BOUNCE_KEEP = -0.7f; @@ -188,16 +187,21 @@ constexpr float GHOST_PITCH_MIN = 2; constexpr float GHOST_PITCH_RANGE = 0.4f; constexpr int GHOST_FRAMES = 360; constexpr int GHOST_FETUS_FRAMES = 180; +constexpr float ATTRACTOR_RADIUS = 250; +constexpr float ATTRACTOR_STRENGTH = 10; +constexpr int FETUS_PERSISTENT_FUSE = 30; +constexpr int FETUS_PERSISTENT_ROCKET_FUSE = 60; +constexpr float FETUS_SPLIT_SPEED = 5; +constexpr int FETUS_SPLIT_FUSE = 15; +constexpr float FETUS_SPLIT_DAMAGE = 0.4f; +constexpr int FETUS_QUAD_BOMBS = 4; +constexpr float FETUS_QUAD_SPEED = 6.5f; +constexpr int FETUS_QUAD_FUSE = 7; +constexpr float FETUS_QUAD_DAMAGE = 0.35f; // The running number each player bomb takes on its first frame (the original's 00c7ec64). static int g_bombIndexCounter = 0; -// Stops where a bomb's tear effect is not reconstructed yet. -static void flag_check(const Entity_Bomb& bomb, int bit, const char* what) -{ - if (bomb.tearFlags[bit]) reconstruction_missing(what); -} - // Hot Bombs burn what they touch: a player's bomb the vulnerable enemies it overlaps, anyone else's the players beside // it. static void hot_bomb_burn(Entity_Bomb& bomb) @@ -539,7 +543,7 @@ void Entity_Bomb::Update() float shownAngle = fetus_flight_update(); if (tearFlags[TEAR_BURN]) hot_bomb_burn(*this); - flag_check(*this, TEAR_OCCULT, "Entity_Bomb::Update 006a24d0: the Occult's steering"); + if (tearFlags[TEAR_OCCULT]) occult_steer(); if (IsRocket()) rocket_thrust_update(); Entity::Update(); if (IsRocket() && tearFlags[TEAR_BOOMERANG] && parent) rocket_boomerang_update(); @@ -565,7 +569,8 @@ bool Entity_Bomb::fuse_update(Entity_Player* spawner) if (explosionCountdown >= 1 && !(spawnerType == ENTITY_PLAYER && isRemoteSet)) { if (!IsRocket() || !HasEntityFlags(FLAG_HELD)) explosionCountdown--; - flag_check(*this, TEAR_ATTRACTOR, "Entity_Bomb::Update 006a24d0: Strange Attractor (Game::AttractEntities)"); + if (tearFlags[TEAR_ATTRACTOR]) + entities_attract({.position = pos, .radius = ATTRACTOR_RADIUS, .strength = ATTRACTOR_STRENGTH}); bool isTroll = variant == BOMB_TROLL || variant == BOMB_SUPERTROLL || variant == BOMB_HOT || variant == BOMB_GOLDENTROLL; @@ -613,12 +618,7 @@ void Entity_Bomb::explode(Entity_Player* spawner) isDead = true; if (pitfallState == 0) sprite.Play("Explode"); - if (isFetus) - { - flag_check(*this, TEAR_PERSISTENT, "Entity_Bomb::Update 006a24d0: a Dr. Fetus bomb that throws another"); - flag_check(*this, TEAR_SPLIT, "Entity_Bomb::Update 006a24d0: Dr. Fetus' split bombs"); - flag_check(*this, TEAR_QUADSPLIT, "Entity_Bomb::Update 006a24d0: Dr. Fetus' quad split bombs"); - } + if (isFetus) fetus_children_throw(); else if (tearFlags[TEAR_STICKY] && stickyTarget) stickyTarget->AddEntityFlags(FLAG_SPAWN_STICKY_SPIDERS); if (!isFetus && variant != BOMB_THROWABLE && spawner && spawner->HasTrinket(TRINKET_BLASTING_CAP)) { @@ -640,10 +640,110 @@ void Entity_Bomb::explode(Entity_Player* spawner) velocity = vector_make(speed * std::cos(angle), speed * std::sin(angle)); scatterTimer = GOLDEN_SCATTER_FRAMES; } - bool isVirtuesWisp = !HasEntityFlags(FLAG_NO_REWARD) && spawner && spawnerEntity.get() == spawner && + bool isVirtuesWisp = !HasEntityFlags(FLAG_NO_REWARD) && spawner && spawnerEntity.get() == spawner && !isFetus && spawner->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_REMOTE_DETONATOR) && spawner->HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES); - if (isVirtuesWisp) reconstruction_missing("Entity_Bomb::Update 006a24d0: the Remote Detonator's wisp"); + if (isVirtuesWisp) spawner->AddWisp(COLLECTIBLE_REMOTE_DETONATOR, pos, false, false); +} + +// Eye of the Occult: a bomb its player fired steers toward the player's aim (Marked's target, the mouse or the +// shooting stick) by three times the shot speed (half that with My Reflection), braking a little. Without an aim it +// glides on, longer while homing and endlessly when it comes back. +void Entity_Bomb::occult_steer() +{ + Entity_Player* player = parent && parent->type == ENTITY_PLAYER ? parent->ToPlayer() : nullptr; + if (!player) return; + + Vector aim = player->GetShootingJoystick(); + player->GetMouseAimTarget(aim, false); + if (Entity* target = player->markedTarget) + { + aim = vector_make((target->pos.x - pos.x) / OCCULT_MARKED_SHARE, (target->pos.y - pos.y) / OCCULT_MARKED_SHARE); + if (vector_length(aim) > 1) aim = vector_normalized(aim); + } + float steer = player->shotSpeed * OCCULT_STEER; + if (player->HasCollectible(COLLECTIBLE_MY_REFLECTION)) steer *= OCCULT_BOOMERANG_SCALE; + if (!vector_is_zero(aim)) + { + aim = vector_normalized(aim); + velocity = vector_make(aim.x * steer + velocity.x, aim.y * steer + velocity.y); + friction = OCCULT_FRICTION; + return; + } + friction = tearFlags[TEAR_BOOMERANG] ? 1 : tearFlags[TEAR_HOMING] ? OCCULT_HOMING_FRICTION : OCCULT_FRICTION; +} + +// A Dr. Fetus bomb going off throws its children, each a fetus bomb with its flags but the one that made it: +// another of itself with Pinky Eye's persistence, two smaller weaker bombs to the sides with The Parasite, and four +// small weak bombs around at random with Cricket's Body. +// The original reads the split and quad split bombs' variant, and the split's first side, from stack slots no path +// here sets. They take this bomb's variant, and the split goes to both sides. +void Entity_Bomb::fetus_children_throw() +{ + auto child_spawn = [this](const Vector& position, const Vector& launch, int dropped) { + Entity_Bomb& child = *static_cast(g_game->Spawn({.position = position, + .velocity = launch, + .spawner = spawnerEntity, + .type = ENTITY_BOMB, + .variant = variant, + .seed = Random()})); + child.spawnerType = spawnerType; + child.spawnerVariant = spawnerVariant; + child.isFetus = true; + child.tearFlags = tearFlags; + child.tearFlags.reset((size_t)dropped); + child.isLoadCostumes = true; + return &child; + }; + + if (tearFlags[TEAR_PERSISTENT]) + { + Entity_Bomb* child = child_spawn(pos, velocity, TEAR_PERSISTENT); + int fuse = FETUS_PERSISTENT_FUSE; + if (child->IsRocket()) + { + child->rocketAngle = rocketAngle; + fuse = FETUS_PERSISTENT_ROCKET_FUSE; + } + child->SetExplosionCountdown(fuse); + child->AddEntityFlags(FLAG_NO_KNOCKBACK | FLAG_NO_REWARD); + } + + if (tearFlags[TEAR_SPLIT]) + { + Vector side = vector_normalized(vector_make(velocity.y, -velocity.x)); + for (float way = -1; way <= 1; way += 2) + { + Vector launch = vector_make(way * side.x * FETUS_SPLIT_SPEED, way * side.y * FETUS_SPLIT_SPEED); + Vector position = vector_make(size * side.x * way + pos.x, size * side.y * way + pos.y); + Entity_Bomb* child = child_spawn(position, launch, TEAR_SPLIT); + child->AddEntityFlags(FLAG_NO_KNOCKBACK | FLAG_NO_REWARD); + child->SetExplosionCountdown(FETUS_SPLIT_FUSE); + child->explosionDamage *= FETUS_SPLIT_DAMAGE; + } + } + + if (!tearFlags[TEAR_QUADSPLIT]) return; + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector around = vector_make(std::cos(angle), std::sin(angle)); + float turnCosine = std::cos(PI_F / 2); + float turnSine = std::sin(PI_F / 2); + for (int i = 0; i < FETUS_QUAD_BOMBS; i++) + { + Vector launch = vector_make(around.x * FETUS_QUAD_SPEED, around.y * FETUS_QUAD_SPEED); + Vector position = vector_make(size * around.x + pos.x, size * around.y + pos.y); + Entity_Bomb* child = child_spawn(position, launch, TEAR_QUADSPLIT); + child->scale = scale * 0.5f; + child->explosionDamage *= FETUS_QUAD_DAMAGE; + child->radiusMultiplier = radiusMultiplier * 0.5f; + child->SetSize(child->size * 0.5f, vector_make(-1, -1), -1); + child->AddEntityFlags(FLAG_NO_KNOCKBACK | FLAG_NO_REWARD); + child->SetExplosionCountdown(FETUS_QUAD_FUSE); + float turned = turnSine * around.x; + around.x = turnCosine * around.x - turnSine * around.y; + around.y = turnCosine * around.y + turned; + } } // The rest of the frame: a super troll bomb chases the nearest player, the cooldowns run, the bomb turns solid, falls diff --git a/src/entity_bomb.h b/src/entity_bomb.h index 29bee18..7ea45c4 100644 --- a/src/entity_bomb.h +++ b/src/entity_bomb.h @@ -106,9 +106,21 @@ private: void rocket_thrust_update(); void rocket_boomerang_update(); void rocket_sprite_update(float shownAngle); + void occult_steer(); + void fetus_children_throw(); +}; + +// A poison splash (Ipecac's and the poison bombs'): where, how big, and how faded the cloud over the splat is, if any. +struct PoisonSplash +{ + Vector position{}; + float alpha = 1; + float scale = 1; + bool isCloud = true; }; void explosion_damage(Explosion explosion); +void poison_splash_spawn(const PoisonSplash& splash); void shovel_quest_dig(); bool explosion_line_clear(const Vector& start, const Vector& end, bool isIgnoreWalls); void explosion_effects(const Explosion& explosion); diff --git a/src/entity_collision.cpp b/src/entity_collision.cpp index 4a9eed0..493e116 100644 --- a/src/entity_collision.cpp +++ b/src/entity_collision.cpp @@ -51,7 +51,6 @@ constexpr float HALF_CELL = GRID_CELL_SIZE / 2; // The enemies that bounce harder off walls, with the sounds some make. constexpr float REBOUND_GURDY_JR = 1.4f; constexpr float REBOUND_BOUNCER = 1.2f; -constexpr int SOUND_BALL_AND_CHAIN_HIT = 581; constexpr float BOUNCE_VOLUME_SCALE = 0.05f; constexpr float BOUNCE_VOLUME_BASE = 0.2f; constexpr float BOUNCE_VOLUME_MAX = 1.2f; diff --git a/src/entity_combat.cpp b/src/entity_combat.cpp index 250840a..0febfc9 100644 --- a/src/entity_combat.cpp +++ b/src/entity_combat.cpp @@ -19,6 +19,8 @@ #include "platform.h" #include "room.h" #include "room_render.h" +#include "seeds.h" +#include "entity_npc.h" #include "sfx_manager.h" #include #include @@ -32,6 +34,12 @@ constexpr int ENTITY_SINS_FIRST = 46; constexpr int ENTITY_SINS_LAST = 52; constexpr int ENTITY_IGNORED_BY_TEARS = 291; constexpr int ENTITY_REFLECTING_ENEMY = 822; +constexpr uint32_t REFLECT_ODDS = 5; +constexpr uint32_t DELIRIUM_RAGE_MAX = 255; +constexpr float TOOTH_CHIP_SPEED = 2; +constexpr float TOOTH_CHIP_SPEED_RANGE = 3; +// A black tooth's chips are its colour darkened to three tenths. +constexpr ColorMod BLACK_TOOTH_SHADE = {{0.3f, 0.3f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr int ENTITY_SHIELDED_SPAWN = 832; constexpr int ENTITY_SHIELDED_PART = 889; constexpr int ENTITY_FACING_SHIELD = 903; @@ -81,8 +89,6 @@ constexpr uint32_t FROZEN_SHARD_EXTRA = 3; 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_CHAIN_BREAK = 504; constexpr int BISHOP_HIT_DELAY = 10; constexpr float SOUND_LARGE_VOLUME = 1.25f; constexpr float SOUND_BABY_VOLUME = 1.8f; @@ -175,6 +181,7 @@ constexpr float DROP_SPIN_RANGE = 10; constexpr float DROP_ALPHA_MIN = 0.1f; constexpr float DROP_ALPHA_RANGE = 0.25f; constexpr float HUGE_GIB_SCALE_MIN = 2; +constexpr float HUGE_GIB_THROW = 10; constexpr float HUGE_DROP_SCALE_RANGE = 2; constexpr float HUGE_DROP_SPEED = 4; constexpr int BURST_DROPS_MIN_GIBS = 6; @@ -641,7 +648,7 @@ void gibs_spawn(const GibSpawn& gibs) if (gibs.gibFlags & GIB_FLAG_HUGE) { if (g_game->room->IsBeastDungeon()) - reconstruction_missing("spawn_gibs 006b31b0: the Beast's huge gibs thrown up"); + gib->velocity.y += (-HUGE_GIB_THROW - random_unit() * HUGE_GIB_THROW) * gib->speedMultiplier; float scale = random_unit() + HUGE_GIB_SCALE_MIN; gib->AddEntityFlags(FLAG_EXTRA_GORE); gib->sprite.scale = vector_make(scale, scale); @@ -742,12 +749,18 @@ static TearContact tear_tear_contact(Entity_Tear& tear, Entity_Tear& other) } // Part of 00673660: a Chaos Card kills any enemy it touches outright, passing the props and Dogma's and the Beast's -// bodies. +// bodies. Delirium only flies into a long rage, the card gone. The original also clears the top bits of his form's +// age, which this reconstruction does not keep. static TearContact chaos_card_contact(Entity_Tear& tear, Entity& collider) { if (collider.type == ENTITY_GENERIC_PROP) return TEAR_CONTACT_PASS; if ((collider.type == ENTITY_DOGMA || collider.type == ENTITY_BEAST) && collider.variant == 0) return TEAR_CONTACT_PASS; - if (collider.type == ENTITY_DELIRIUM) reconstruction_missing("Entity_Tear::HandleCollision 00673660: a Chaos Card hitting Delirium"); + if (collider.type == ENTITY_DELIRIUM) + { + tear.Remove(); + static_cast(collider).deliriumRageTimer = DELIRIUM_RAGE_MAX; + return TEAR_CONTACT_PASS; + } if (!collider.IsEnemy()) return TEAR_CONTACT_HIT; collider.Kill(EntityRef(&tear)); @@ -806,8 +819,18 @@ static TearContact tear_contact_get(Entity_Tear& tear, Entity& collider, Entity* } return TEAR_CONTACT_PASS; } - if (!isExplosive && collider.type == ENTITY_REFLECTING_ENEMY) - reconstruction_missing("Entity_Tear::HandleCollision 00673660: an enemy reflecting tears"); + if (!isExplosive && collider.type == ENTITY_REFLECTING_ENEMY && + static_cast(collider).state == NPC_STATE_SPECIAL) + { + RNG rng = rng_make(collider.initSeed + tear.initSeed, DEFAULT_SHIFT_INDEX); + if (rng.RandomInt(REFLECT_ODDS) == 0) + { + Vector normal = vector_normalized(vector_sub(tear.pos, collider.pos)); + float along = vector_dot(normal, tear.velocity); + if (along < 0) tear.velocity = vector_sub(tear.velocity, vector_scale(normal, along + along)); + return TEAR_CONTACT_PASS; + } + } if (collider.type == ENTITY_PROJECTILE) { @@ -861,7 +884,7 @@ static void dead_eye_charge(Entity_Tear& tear, Entity& collider) } // Part of 00673660: what a hit does beside its damage: a burning tear may turn explosive by luck, a piercing or -// lasting tear pushes what it passes, and flies are knocked along. +// lasting tear pushes what it passes, a tooth Ludovico chips teeth off a vulnerable enemy, and flies are knocked along. static void tear_hit_push(Entity_Tear& tear, Entity& collider, Entity* owner) { if (tear.tearFlags[TEAR_BURN] && collider.type != ENTITY_FIREPLACE) @@ -873,7 +896,16 @@ static void tear_hit_push(Entity_Tear& tear, Entity& collider, Entity* owner) } if ((tear.variant == TEAR_TOOTH || tear.variant == TEAR_BLACK_TOOTH) && tear.tearFlags[TEAR_LUDOVICO] && collider.IsVulnerableEnemy(nullptr)) - reconstruction_missing("Entity_Tear::HandleCollision 00673660: a tooth Ludovico's particles"); + { + ColorMod color = tear.sprite.color; + if (tear.variant == TEAR_BLACK_TOOTH) color_multiply(color, BLACK_TOOTH_SHADE); + game_particles_spawn({.color = color, + .position = tear.pos, + .height = tear.height, + .speed = random_between(TOOTH_CHIP_SPEED, TOOTH_CHIP_SPEED_RANGE), + .count = 1, + .variant = EFFECT_TOOTH_PARTICLE}); + } bool isPassing = tear.tearFlags[TEAR_PIERCING] || tear.tearFlags[TEAR_PERSISTENT]; if ((isPassing || tear.tearFlags[TEAR_FETUS_FLAG]) && !collider.HasEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK)) diff --git a/src/entity_config.cpp b/src/entity_config.cpp index d34080b..0a24f5f 100644 --- a/src/entity_config.cpp +++ b/src/entity_config.cpp @@ -9,10 +9,8 @@ #include #include -constexpr std::string_view DOCUMENT_TAG = "#document"; constexpr std::string_view ENTITIES_VERSION = "5"; constexpr int BOSS_COLORS_VERSION_MAX = 1; -constexpr char STRING_KEY_PREFIX = '#'; constexpr float SHADOW_SIZE_SCALE = 100; // Eden, whose children list the hairstyles it rolls, and the point boss portrait pivots are measured back from. diff --git a/src/entity_config.h b/src/entity_config.h index f3fe048..66dae16 100644 --- a/src/entity_config.h +++ b/src/entity_config.h @@ -186,6 +186,9 @@ struct EntityConfig_Entity std::string GetName(int language); }; +// The characters' config file, as the game and Lua resets load it. +constexpr const char* PLAYERS_XML = "players.xml"; + // Construction (00694490), copies (0069e6c0, 0069b810), moves (006a1a40) and destruction (0069b7b0) are the defaults. // A character's config from players.xml: its sprites, starting pickups and items, and its tainted twin. struct EntityConfig_Player diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index bbdf0a5..884ef3d 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -1,20 +1,27 @@ #include "entity_effect.h" +#include "entity_config.h" #include "entity_effect_combat.h" #include "entity_effect_trail.h" +#include "entity_familiar.h" #include "entity_list.h" +#include "entity_pickup.h" #include "entity_player.h" #include "entity_player_forgotten.h" #include "entity_player_passives.h" #include "game.h" +#include "item_config.h" #include "kage_graphics.h" #include "log.h" +#include "loot_list.h" #include "lua_engine.h" #include "manager.h" -#include "room.h" -#include "sfx_manager.h" #include "mines.h" +#include "room.h" +#include "seeds.h" +#include "sfx_manager.h" #include "weapon_rockets.h" #include +#include #include #include @@ -29,6 +36,24 @@ constexpr std::array CRAWLSPACE_HIDDEN_EFFECTS = {7, 18, 22, 23, 24, 2 // The creep a familiar's wave of creep (familiar variant 125) leaves, which keeps its chain going. constexpr std::array WAVE_CHAIN_CREEPS = {53, 44, 46, 45, 32, 204}; constexpr int FAMILIAR_CREEP_WAVE = 125; +constexpr ColorMod MOONLIGHT_FLASH = {{2, 3, 4, 1}, {0, 0, 0, 0}, {0.2f, 0.2f, 0.2f}}; +constexpr int MOONLIGHT_FLASH_FRAMES = 3; + +// The pickup ghosts: their ranks, their lift and fade, the looks of cards and runes, and April's Fool's random items. +constexpr int GHOST_RANK_COLLECTIBLE = 10000; +constexpr int GHOST_RANK_TRINKET = 1000; +constexpr int GHOST_RANK_RARE = 500; +constexpr int GHOST_RANK_UNCOMMON = 200; +constexpr int GHOST_RANK_OTHER = 50; +constexpr int GHOST_RANK_COMMON = 10; +constexpr float GHOST_LIFT = -4; +constexpr float GHOST_ITEM_LIFT = 4; +constexpr float PICKUP_GHOST_ALPHA = 0.75f; +constexpr int GHOST_CANTRIPPED_LOOK = 16; +constexpr int GHOST_CARD_DEFAULT_LOOK = 2; +constexpr int GHOST_FOOL_TRIES = 15; +constexpr uint32_t GHOST_FOOL_ITEMS = 732; +constexpr std::array UNUSED_COLLECTIBLE_IDS = {235, 43, 61}; constexpr int EFFECT_BLACK_POWDER = 92; constexpr int EFFECT_TIMER = 119; @@ -38,7 +63,6 @@ constexpr float HOURGLASS_COOLDOWN_SPAN = 30; 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. 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. @@ -59,6 +83,12 @@ struct TimerData : Entity_Effect::ExtraData int times = 1; }; +// The times a timer has left to run its callback (counting the run in progress). +int timer_times_get(Entity_Effect& timer) +{ + return static_cast(*timer.extraData).times; +} + // The timer part of 005cdb20 (Init): a timer is invisible, never overwritten, and has nothing to run yet. static void timer_init(Entity_Effect& timer) { @@ -410,18 +440,25 @@ void Entity_Effect::FollowParent(Entity* newParent) parentOffset = vector_make(pos.x - newParent->pos.x, pos.y - newParent->pos.y); } -// The rest of Entity_Effect is not reconstructed yet. - -// 005d4010 +// Lil Spewer's creep wave, written as wave_chain_update in familiar_babies.cpp. void Entity_Effect::update_wave_chain() { - reconstruction_missing("Entity_Effect::update_wave_chain 005d4010"); + wave_chain_update(*this); } -// 006073f0 -void Entity_Effect::moonlight_timer_callback(int) +// 006073f0 Luna's blessing half a second after its moonlight is touched: the timer's player, still alive, flashes +// bright, gains Luna's secondary effect and a soul heart, holding the item up. +void Entity_Effect::moonlight_timer_callback(Entity_Effect* timer) { - reconstruction_missing("Entity_Effect::moonlight_timer_callback 006073f0"); + Entity* owner = timer->parent; + if (!owner || owner->type != ENTITY_PLAYER || owner->isDead) return; + + Entity_Player& player = *owner->ToPlayer(); + effect_sound_play(SOUND_POWERUP_SPEWER); + player.SetColor(MOONLIGHT_FLASH, MOONLIGHT_FLASH_FRAMES, -1, true, true); + player.temporaryEffects.AddNullEffect(NULLITEM_LUNA, true, 1); + player.AnimateCollectible(COLLECTIBLE_LUNA, "UseItem", "PlayerPickupSparkle"); + player.AddSoulHearts(1, false); } // 0060af00 Spawns a timer running a callback (taking the timer) every delay frames, times more times after the first @@ -438,14 +475,131 @@ Entity_Effect* Entity_Effect::CreateTimer(void* fn, uint32_t delay, uint32_t tim return timer; } -// 0060b7a0 -Entity_Effect* Entity_Effect::CreateLootPreview(void*, const Vector&, Entity*, Entity_Effect*) +// 0060b7a0 Shows a loot list as pickup ghosts at a position: in the ghost effect given, or a new one, following its +// owner. The effect, unless it had nothing to show. +Entity_Effect* Entity_Effect::CreateLootPreview(LootList* lootList, const Vector& pos, Entity* owner, + Entity_Effect* effect) { - reconstruction_missing("Entity_Effect::CreateLootPreview 0060b7a0"); + if (!effect || effect->type != ENTITY_EFFECT || effect->variant != EFFECT_PICKUP_GHOST) + effect = static_cast( + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_PICKUP_GHOST, .seed = Random()})); + effect->pos = pos; + effect->setup_loot_preview(lootList); + if (owner) effect->FollowParent(owner); + return effect->isExists ? effect : nullptr; } -// 0060bae0 -void Entity_Effect::setup_loot_preview(void*) +// How high a pickup ghost ranks among the loot (most first): collectibles, then trinkets, then the rarer hearts, +// coins, keys and bombs, then other pickups, then anything else. +static int loot_ghost_rank(const LootEntry& loot) { - reconstruction_missing("Entity_Effect::setup_loot_preview 0060bae0"); + if (loot.type != ENTITY_PICKUP) return 0; + + int sub = loot.subType; + switch (loot.variant) + { + case PICKUP_BOMB: return sub == 4 || sub == 6 || sub == 7 ? GHOST_RANK_RARE : GHOST_RANK_COMMON; + case PICKUP_HEART: + if (sub == 4 || sub == 7 || sub == 11) return GHOST_RANK_RARE; + return sub == 6 || sub == 10 || sub == 3 || sub == 8 ? GHOST_RANK_UNCOMMON : GHOST_RANK_COMMON; + case PICKUP_COIN: + if (sub == 3 || sub == 5) return GHOST_RANK_RARE; + return sub == 2 ? GHOST_RANK_UNCOMMON : GHOST_RANK_COMMON; + case PICKUP_KEY: return sub == 2 || sub == 4 ? GHOST_RANK_RARE : GHOST_RANK_COMMON; + case PICKUP_COLLECTIBLE: return GHOST_RANK_COLLECTIBLE; + case PICKUP_TRINKET: return GHOST_RANK_TRINKET; + default: return GHOST_RANK_OTHER; + } +} + +// A collectible ghost's look: its item (any item at random on April's Fool), a question mark under Curse of the +// Blind. +static void loot_ghost_item_set(ANM2& sprite, const LootEntry& loot) +{ + sprite.GetLayer(1)->pos = vector_make(0, GHOST_ITEM_LIFT); + if (loot.subType == 0) return; + if (g_game->GetCurses() & CURSE_OF_BLIND) + { + sprite.ReplaceSpritesheet(1, QUESTION_MARK_GFX); + return; + } + + ItemConfig& items = g_manager->itemConfig; + std::string gfx = items.GetCollectible(loot.subType)->gfxFilename; + if (g_game->challenge == CHALLENGE_APRILS_FOOL) + { + RNG rng = {loot.seed, 11, 21, 13}; + for (int i = 0; i < GHOST_FOOL_TRIES; i++) + { + int id = (int)(rng.Next() % GHOST_FOOL_ITEMS) + 1; + bool isUnused = std::ranges::find(UNUSED_COLLECTIBLE_IDS, id) != UNUSED_COLLECTIBLE_IDS.end(); + bool isShown = id < (int)items.collectibles.size() && !isUnused && items.GetCollectible(id); + if (!isShown) continue; + gfx = items.GetCollectible(id)->gfxFilename; + break; + } + } + sprite.ReplaceSpritesheet(1, gfx); +} + +// 0060bae0 Fills a pickup ghost with up to four of the loot's pickups, the highest ranked first (what a random pickup +// would turn out as, a card or rune shown as its kind's look): each as its entity's sprite on its first frame, +// shadowless and faded, a trinket or collectible with its own look. A ghost with nothing to show goes. +void Entity_Effect::setup_loot_preview(LootList* lootList) +{ + auto* ghosts = dynamic_cast(extraData.get()); + if (!ghosts) return Remove(); + + for (ANM2& sprite : ghosts->sprites) + if (sprite.isLoaded) sprite.Reset(); + ghosts->count = 0; + + std::multimap ranked; + for (LootEntry loot : lootList->entries) + { + if (loot.type == ENTITY_PICKUP) + { + PickupChoice choice = {.subType = loot.subType, .variant = loot.variant, .seed = loot.seed, .draw = POOL_DRAW_PEEK}; + if (pickup_variant_pick(choice)) + { + loot.variant = choice.variant; + loot.subType = choice.subType; + } + } + if (loot.variant == PICKUP_TAROTCARD) + { + ItemConfig_Card* card = g_manager->itemConfig.GetCard(loot.subType); + if (g_game->challenge == CHALLENGE_CANTRIPPED) loot.subType = GHOST_CANTRIPPED_LOOK; + else loot.subType = card ? card->pickupSubtype : GHOST_CARD_DEFAULT_LOOK; + } + if (!g_manager->entityConfig.GetEntity(loot.type, loot.variant, loot.subType)) continue; + ranked.emplace(loot_ghost_rank(loot), loot); + } + + for (auto it = ranked.rbegin(); it != ranked.rend() && ghosts->count < PICKUP_GHOST_SLOTS; ++it) + { + const LootEntry& loot = it->second; + EntityConfig_Entity* config = g_manager->entityConfig.GetEntity(loot.type, loot.variant, loot.subType); + if (!config) continue; + + ANM2& sprite = ghosts->sprites[ghosts->count++]; + sprite.Load(config->anm2Path, GRAPHICS_DEFER); + sprite.GetLayer(0)->pos = vector_make(0, GHOST_LIFT); + if (loot.type == ENTITY_PICKUP && loot.variant == PICKUP_TRINKET) + { + if (ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(loot.subType & TRINKET_ID_MASK)) + sprite.ReplaceSpritesheet(0, trinket->gfxFilename); + } + else if (loot.type == ENTITY_PICKUP && loot.variant == PICKUP_COLLECTIBLE) + loot_ghost_item_set(sprite, loot); + if (LayerState* shadow = sprite.GetLayer("shadow")) shadow->isVisible = false; + sprite.LoadGraphics(); + if (sprite.SetAnimation(sprite.GetDefaultAnimationName(), SWITCH_RESET) && sprite.animState.animData) + { + sprite.animState.SetFrameFloat(0); + if (sprite.animState.animData) sprite.animState.isPlaying = false; + } + sprite.color = tint_color_make(1, 1, 1, PICKUP_GHOST_ALPHA); + } + if (ghosts->count == 0) Remove(); } diff --git a/src/entity_effect.h b/src/entity_effect.h index 96f658a..7f3a068 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -55,6 +55,16 @@ constexpr int BLOOD_EXPLOSION_BURST = 2; constexpr int BLOOD_EXPLOSION_SPLASH = 3; constexpr int BLOOD_EXPLOSION_SPLASH_BIG = 4; +// Dogma's blackhole (171): its sparks (subtype 1) and swirls (2), and its states while open and closing. +constexpr int BLACKHOLE_SPARK = 1; +constexpr int BLACKHOLE_SWIRL = 2; +constexpr int BLACKHOLE_OPEN = 1; +constexpr int BLACKHOLE_CLOSING = 2; + +// The enemy ghost's bursts (144): the Beast's crackwave's, and the larger one of Dogma's babies and the Beast's souls. +constexpr int ENEMY_GHOST_BURST = 1; +constexpr int ENEMY_GHOST_BLAST = 2; + // Poof02's lava splashes, small and large. constexpr int POOF02_LAVA_SPLASH = 66; constexpr int POOF02_LAVA_SPLASH_LARGE = 67; @@ -330,12 +340,12 @@ struct Entity_Effect : Entity static bool rift_attract_filter(int first, int second); void update_mr_me(); void update_wave_chain(); - static void moonlight_timer_callback(int); + static void moonlight_timer_callback(Entity_Effect* timer); static bool IsPlayerCreep(int effectVariant); static Entity_Effect* CreateTimer(void* fn, uint32_t delay, uint32_t times, bool isPersistent); void update_variant178_shooter(bool isPositionOnly); - static Entity_Effect* CreateLootPreview(void* lootlist, const Vector& pos, Entity* owner, Entity_Effect* effect); - void setup_loot_preview(void* lootQueue); + static Entity_Effect* CreateLootPreview(LootList* lootList, const Vector& pos, Entity* owner, Entity_Effect* effect); + void setup_loot_preview(LootList* lootList); }; // The most pickups a pickup ghost shows. @@ -410,6 +420,8 @@ Entity_Effect* chain_lightning_spawn(const ChainLightning& chain); struct Entity_Familiar; bool is_familiar_charmable(Entity_Familiar& familiar); +int timer_times_get(Entity_Effect& timer); + // Sets a layer to draw additively (BlendMode::SetMode 2), or normally (1). void layer_additive_set(LayerState& layer); void layer_normal_set(LayerState& layer); diff --git a/src/entity_effect_ambient.cpp b/src/entity_effect_ambient.cpp index 20e101c..abb4507 100644 --- a/src/entity_effect_ambient.cpp +++ b/src/entity_effect_ambient.cpp @@ -1,21 +1,22 @@ #include "boss_ai.h" -#include "entity_effect.h" #include "data.h" #include "deathmatch_manager.h" -#include "entity_tear.h" +#include "entity_effect.h" #include "entity_list.h" #include "entity_player.h" +#include "entity_tear.h" #include "fx_layers.h" #include "game.h" #include "grid_entity.h" #include "grid_entity_door.h" #include "kage_graphics.h" +#include "level_generator.h" #include "npc_ai.h" #include "pocket_items.h" #include "room.h" -#include "room_grid.h" #include "room_config.h" #include "room_descriptor.h" +#include "room_grid.h" #include #include #include @@ -148,6 +149,7 @@ constexpr float DICE_REACH = 75; constexpr int SHOVEL_SHADOW_RENDER_Z = 10000; constexpr int LADDER_ARM_FRAMES = 5; constexpr float LADDER_NEAR = 50; +constexpr int LADDER_TO_ANGEL_SHOP = 1; constexpr float LADDER_CLIMB = 21; template @@ -880,15 +882,27 @@ static EffectUpdateEnd backdrop_decoration_update(Entity_Effect& decoration) return backdrop_detail_cleared(decoration) ? EFFECT_UPDATE_RETURN : EFFECT_UPDATE_FINISH; } -// A ladder's frame: it counts the frames no player stands close, and a player climbing it once it is ready leaves. +// A ladder's frame: it counts the frames no player stands close, and a player free to climb it once it is ready leaves: +// Stairway's ladder up to the angel shop (remembering where to come back to), any other down to the dungeon's return +// room. static void tall_ladder_update(Entity_Effect& ladder) { Entity_Player* player = main_player_nearest(ladder.pos); float distance = player ? vector_length(vector_sub(ladder.pos, player->pos)) : 1e9f; ladder.state = distance < LADDER_NEAR && ladder.state <= LADDER_ARM_FRAMES ? 0 : ladder.state + 1; - if (player && distance < LADDER_CLIMB && ladder.state > LADDER_ARM_FRAMES) - reconstruction_missing("Entity_Effect::Update 005d4380: climbing a ladder out of the room"); + if (!player || distance >= LADDER_CLIMB || ladder.state <= LADDER_ARM_FRAMES || !is_player_free(*player)) return; + + Game& game = *g_game; + if (ladder.subtype != LADDER_TO_ANGEL_SHOP) + return game.StartRoomTransition( + {.player = player, .animation = TRANSITION_PIXELATION, .roomIndex = game.dungeonReturnRoomIndex}); + + int roomIndex = game.currentRoomIdx; + game.leaveDoor = DOOR_UP0; + game.StartRoomTransition({.player = player, .direction = DIRECTION_UP, .roomIndex = ROOM_ANGEL_SHOP_IDX}); + game.dungeonReturnPosition = ladder.pos; + game.dungeonReturnRoomIndex = std::clamp(roomIndex, DUNGEON_RETURN_INDEX_MIN, DUNGEON_RETURN_INDEX_MAX); } // The creep: how long it lasts, where it lies, and how it fades when it dies. @@ -917,7 +931,6 @@ constexpr float CREEP_BIG = 1.3f; constexpr float CREEP_BIGGEST = 2.1f; // Lost Cork grows the players' creep by its multiplier: small creep gains size, larger creep multiplies it. -constexpr uint32_t TRINKET_LOST_CORK = 106; constexpr std::array CORK_SMALL_GROWTH = {1, 1.25f, 1.5f}; constexpr std::array CORK_GROWTH = {1.65f, 1.9f, 2.15f}; @@ -1556,6 +1569,7 @@ constexpr int HEAVEN_DOOR_BEAM = 2; constexpr int ROOM_INDEX_GENESIS = -2; constexpr float HEAVEN_DOOR_RANGE_SQUARED = 625; constexpr float MOONLIGHT_RANGE_SQUARED = 900; +constexpr uint32_t MOONLIGHT_BLESSING_DELAY = 30; constexpr int MOONLIGHT_READY = 60; constexpr int HEAVEN_DOOR_READY = 41; constexpr int HEAVEN_DOOR_EARLY = 8; @@ -1767,11 +1781,16 @@ static void moonlight_update(Entity_Effect& light) if (distance_squared(player->pos, light.pos) >= MOONLIGHT_RANGE_SQUARED || light.state <= MOONLIGHT_READY) continue; light.state = -1; npc_sound_play(SOUND_POWER_UP, 1, 2, 1); - reconstruction_missing("Entity_Effect::Update 005d4380: Luna's moonlight blessing (Entity_Effect::CreateTimer)"); + Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(&Entity_Effect::moonlight_timer_callback), + MOONLIGHT_BLESSING_DELAY, 0, false); + timer->parent = player->resolve_tainted_soul(); + timer->AddEntityFlags(FLAG_FREEZE); + return; } } -// The light beam up: it appears, waits, and once a player free to move stands in it, carries them up. +// The light beam up: it appears, waits, and once a player free to move stands in it, carries the first up its light +// (drawn over them), then fades. static void light_beam_update(Entity_Effect& beam) { if (beam.state == 0) @@ -1790,8 +1809,13 @@ static void light_beam_update(Entity_Effect& beam) for (Entity_Player* player : g_game->playerManager.playerList) { if (player->variant != 0 || player->isCoopGhost || player->entityCollisionClass == ENTCOLL_NONE) continue; - if (distance_squared(player->pos, beam.pos) < HEAVEN_DOOR_RANGE_SQUARED && is_player_free(*player)) - reconstruction_missing("Entity_Effect::Update 005d4380: the light beam's travel (AnimateLightTravel)"); + if (distance_squared(player->pos, beam.pos) >= HEAVEN_DOOR_RANGE_SQUARED || !is_player_free(*player)) continue; + + beam.renderDepthOffset = player->pos.y - beam.pos.y + 1; + player->AnimateLightTravel(); + player->moveToTarget = beam.pos; + beam.state++; + return; } } } diff --git a/src/entity_effect_boss.cpp b/src/entity_effect_boss.cpp index c77cb63..4dd2b60 100644 --- a/src/entity_effect_boss.cpp +++ b/src/entity_effect_boss.cpp @@ -1,6 +1,8 @@ #include "entity_effect.h" #include "entity_familiar.h" +#include "entity_laser.h" #include "entity_player.h" +#include "entity_tear.h" #include "game.h" #include "npc_caves.h" #include "room.h" @@ -24,6 +26,7 @@ enum CrackSubtype // a player's or a friendly one hurts enemies for its own damage, every 3 frames, 30 frames apart per victim. constexpr float CRACK_STRIKE_DAMAGE = 20; constexpr float CRACK_HOSTILE_DAMAGE = 2; +constexpr float CRACK_VERSUS_HIT_DAMAGE = 7; constexpr int CRACK_HIT_SPACING = 3; constexpr int CRACK_HIT_COUNTDOWN = 30; constexpr int CRACK_SHAKE = 5; @@ -34,6 +37,20 @@ constexpr int CRACK_BEAM_LAYER = 0; constexpr int CRACK_STRUCK = 1; constexpr int CRACK_NPC_TYPE_FIRST = 10; +// The cross beam: held at its frame while it waits, its target glowing up to the strike (frame 10 unless the "Hit" +// event says), then four white light beams lasting 30 frames 12 up. +constexpr int CRACK_CROSS_HOLD = -1; +constexpr uint32_t CRACK_HIT_EVENT = 1; +constexpr float CRACK_CROSS_STRIKE_FRAME = 10; +constexpr float CRACK_CROSS_RED = 0.8f; +constexpr float CRACK_CROSS_BLUE = 1.6f; +constexpr float CRACK_CROSS_RED_OFFSET = 0.2f; +constexpr int CRACK_CROSS_GLOW_FRAMES = 2; +constexpr int CRACK_CROSS_BEAMS = 4; +constexpr float CRACK_CROSS_LIFT = -12; +constexpr int CRACK_CROSS_TIMEOUT = 30; +constexpr ColorMod CRACK_CROSS_BEAM_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; + // Part of 005cdb20 (Init's case 19) A beam strikes for 20. static void crack_init(Entity_Effect& crack) { @@ -56,8 +73,16 @@ static void crack_hit(Entity_Effect& crack) if (entity->type == ENTITY_PLAYER && isHostile) { - if (isVersus) reconstruction_missing("Entity_Effect::Update 005d4380: a versus mode beam's hit"); - entity->TakeDamage(CRACK_HOSTILE_DAMAGE, 0, EntityRef(source), CRACK_HIT_COUNTDOWN); + uint64_t damageFlags = 0; + TearFlags flags = effect_tear_flags(crack); + if (isVersus && flags[TEAR_THROUGH_COOLDOWN]) + { + damageFlags |= DAMAGE_THROUGH_COOLDOWN; + flags.reset(TEAR_THROUGH_COOLDOWN); + effect_tear_flags_set(crack, flags); + } + float damage = isVersus ? CRACK_VERSUS_HIT_DAMAGE : CRACK_HOSTILE_DAMAGE; + entity->TakeDamage(damage, damageFlags, EntityRef(source), CRACK_HIT_COUNTDOWN); } else if (entity->type >= CRACK_NPC_TYPE_FIRST) { @@ -68,6 +93,67 @@ static void crack_hit(Entity_Effect& crack) if (crack.subtype == CRACK_PLAYER) crack.subtype = CRACK_PLAYER_STRUCK; } +// The cross beam before it strikes: it starts its animation, then holds it and runs it back at its speed, gone once +// back at the start. Its target glows brighter the nearer the strike's frame. Whether it is still there. +static bool crack_cross_wait(Entity_Effect& crack) +{ + if (crack.state == CRACK_STRUCK) + { + crack.sprite.playbackSpeed = 1; + crack.state = CRACK_CROSS_HOLD; + } + else if (crack.state == CRACK_CROSS_HOLD) + { + crack.sprite.playbackSpeed = 0; + float frame = (crack.sprite.animState.animData ? crack.sprite.animState.animFrame : -1) - crack.speedMultiplier; + if (!(0 < frame)) + { + crack.Remove(); + return false; + } + crack.sprite.SetFrame(frame); + } + + Entity* target = crack.target; + if (!target) + { + crack.velocity = {}; + return true; + } + float strikeFrame = CRACK_CROSS_STRIKE_FRAME; + if (const AnimationData* animation = crack.sprite.animState.animData) + for (const AnimationData_EventTrigger& trigger : animation->eventTriggers) + if (trigger.eventId == CRACK_HIT_EVENT) strikeFrame = (float)trigger.animationFrame; + float frame = crack.sprite.animState.animData ? crack.sprite.animState.animFrame : -1; + float glow = std::min(frame / strikeFrame, 1.0f); + ColorMod color = {{1, 1, 1, 1}, + {CRACK_CROSS_RED, CRACK_CROSS_BLUE, CRACK_CROSS_BLUE, glow}, + {glow + (0 - glow) * CRACK_CROSS_RED_OFFSET, glow + (0 - glow) * HALF, glow + (0 - glow) * HALF}}; + target->SetColor(color, CRACK_CROSS_GLOW_FRAMES, 0, false, true); + return true; +} + +// The cross beam's strike: it stops and fires four light beams along the axes for half its damage, the last drawn +// behind. +static void crack_cross_fire(Entity_Effect& crack) +{ + crack.target = nullptr; + crack.velocity = {}; + for (int i = 0; i < CRACK_CROSS_BEAMS; i++) + { + Entity_Laser* beam = Entity_Laser::ShootAngle({.position = crack.pos, + .posOffset = vector_make(0, CRACK_CROSS_LIFT), + .source = crack.parent, + .angleDegrees = (float)i * RIGHT_ANGLE_DEGREES, + .timeout = CRACK_CROSS_TIMEOUT, + .variant = LASER_LIGHT_BEAM}); + beam->SetCollisionDamage(crack.collisionDamage * 0.5f); + beam->SetColor(CRACK_CROSS_BEAM_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + beam->isDisableFollowParent = true; + beam->renderDepthOffset = i == CRACK_CROSS_BEAMS - 1 ? TECH_LASER_BACK_DEPTH : TECH_LASER_FRONT_DEPTH; + } +} + // 005e96b5 (Update's case 19) The spotlight charges, strikes with a crater and a shake, hurts every third frame its // beam shows, and goes once its animation ends. static void crack_update(Entity_Effect& crack) @@ -79,10 +165,12 @@ static void crack_update(Entity_Effect& crack) : "Spotlight"); crack.state++; } - if (crack.subtype == CRACK_DELAYED_CROSS) - reconstruction_missing("Entity_Effect::Update 005d4380: the delayed beam with a cross of lasers"); + bool isCross = crack.subtype == CRACK_DELAYED_CROSS; + if (isCross && !crack.sprite.IsEventTriggered("Hit") && !crack.sprite.WasEventTriggered("Hit") && + !crack_cross_wait(crack)) + return; - if (crack.sprite.IsEventTriggered("Sound")) npc_sound_play(SOUND_LIGHTBOLT_CHARGE, 1, 2, 1); + if (crack.sprite.IsEventTriggered("Sound") && !isCross) npc_sound_play(SOUND_LIGHTBOLT_CHARGE, 1, 2, 1); if (crack.sprite.IsEventTriggered("Hit")) { npc_sound_play(SOUND_LIGHTBOLT, 1, 2, 1); @@ -92,6 +180,7 @@ static void crack_update(Entity_Effect& crack) crater->sprite.scale = vector_make(CRACK_CRATER_SCALE, CRACK_CRATER_SCALE); crater->Update(); crack.state = CRACK_STRUCK; + if (isCross) crack_cross_fire(crack); } const AnimationFrame* beam = crack.sprite.animState.GetLayerFrame(CRACK_BEAM_LAYER); diff --git a/src/entity_effect_combat.cpp b/src/entity_effect_combat.cpp index 636d96a..7a2d094 100644 --- a/src/entity_effect_combat.cpp +++ b/src/entity_effect_combat.cpp @@ -180,7 +180,6 @@ constexpr float STAIN_LIGHT_BOOST = 1.1f; constexpr float STAIN_LIGHT_RED = 103; constexpr float STAIN_LIGHT_GREEN = 10; constexpr float STAIN_LIGHT_BLUE = 11; -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; diff --git a/src/entity_effect_dogma.cpp b/src/entity_effect_dogma.cpp index b1e4045..2c7f6f1 100644 --- a/src/entity_effect_dogma.cpp +++ b/src/entity_effect_dogma.cpp @@ -1,4 +1,5 @@ #include "beam_renderer.h" +#include "boss_final.h" #include "entity_effect.h" #include "entity_laser.h" #include "entity_list.h" @@ -397,11 +398,7 @@ static void dogma_orb_render(Entity_Effect& spot, const Vector& offset) // (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; @@ -415,7 +412,6 @@ 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; diff --git a/src/entity_effect_hazard.cpp b/src/entity_effect_hazard.cpp index a4381f8..5b9197a 100644 --- a/src/entity_effect_hazard.cpp +++ b/src/entity_effect_hazard.cpp @@ -82,7 +82,6 @@ constexpr int CRACKWAVE_BEAST_SHAKE = 6; constexpr float CRACKWAVE_BEAST_VOLUME = 0.8f; constexpr float CRACKWAVE_BEAST_PITCH_MIN = 0.9f; constexpr float CRACKWAVE_BEAST_PITCH_SPAN = 0.2f; -constexpr int ENEMY_GHOST_BURST = 1; // A crackwave from an entity with sticky spiders throws three rocks 1 time in 4, each larger and further on. constexpr int CRACKWAVE_ROCK_ODDS = 4; diff --git a/src/entity_effect_items.cpp b/src/entity_effect_items.cpp index c2b1cc0..8f12120 100644 --- a/src/entity_effect_items.cpp +++ b/src/entity_effect_items.cpp @@ -1,4 +1,5 @@ #include "boss_ai.h" +#include "boss_repentance.h" #include "entity_bomb.h" #include "entity_effect_combat.h" #include "entity_familiar.h" @@ -123,6 +124,7 @@ constexpr float BAR_FRICTION = 0.86f; constexpr int BAR_DIM_FRAMES = 10; // The cleaver's slash splits an enemy it holds from frame 3. +constexpr float CLEAVER_WISP_MIN_SCALE = 0.25f; constexpr int CLEAVER_SPLIT_FRAME = 3; constexpr float CLEAVER_DEPTH = 4; @@ -741,12 +743,6 @@ static void hidden_kept_init(Entity_Effect& effect) effect.AddEntityFlags(FLAG_DONT_OVERWRITE); } -// 005da269 (Update's case 152) Hornfel's room controller. -static void hornfel_controller_update(Entity_Effect& controller) -{ - NpcHelper::hornfel_room_controller(&controller); -} - // 005efc0b (Update's case 28) Monstro's tooth: Monstro follows his target (a player only so long), jumps back up once // down and goes once up, landing on frame 33 with a stomp and a crushing blast. static void tooth_update(Entity_Effect& tooth) @@ -807,6 +803,24 @@ static void bar_particle_update(Entity_Effect& bar) bar.friction *= BAR_FRICTION; } +// 0043e9f0 The cleaver splits a wisp in two halves of its size and strength, the new one beside its player's +// orbit. A wisp already a quarter its size dies instead. +static void wisp_cleave(Entity_Familiar& wisp) +{ + if (wisp.wispScale <= CLEAVER_WISP_MIN_SCALE) + { + wisp.Kill(EntityRef(nullptr)); + return; + } + + wisp.wispScale *= 0.5f; + wisp.sprite.scale = vector_make(wisp.sprite.scale.x * 0.5f, wisp.sprite.scale.y * 0.5f); + Entity_Familiar* half = wisp.player->AddWisp(wisp.subtype, wisp.pos, true, false); + if (!half) return; + half->wispScale = wisp.wispScale; + half->sprite.scale = wisp.sprite.scale; +} + // 005df80d (Update's case 176) The cleaver's slash holds its target from frame 3, splitting an enemy for its damage, // then lets go and goes when done. static void cleaver_slash_update(Entity_Effect& slash) @@ -824,7 +838,7 @@ static void cleaver_slash_update(Entity_Effect& slash) static_cast(target)->split(slash.collisionDamage, source, false); } if (target->type == ENTITY_FAMILIAR && target->variant == Entity_Familiar::WISP) - reconstruction_missing("Entity_Effect::Update 005d4380: the cleaver splitting a wisp (FUN_0043e9f0)"); + wisp_cleave(*static_cast(target)); slash.target = nullptr; } } @@ -1449,7 +1463,7 @@ constexpr auto ITEM_EFFECT_BEHAVIOURS = std::to_array({ {EFFECT_FARTWAVE, spreading_wave_init, effect_finishing, nullptr}, {EFFECT_FIRE_JET, nullptr, effect_finishing, nullptr}, {EFFECT_FIRE_WAVE, spreading_wave_init, effect_finishing, nullptr}, - {EFFECT_HORNFEL_ROOM_CONTROLLER, hidden_kept_init, effect_finishing, nullptr}, + {EFFECT_HORNFEL_ROOM_CONTROLLER, hidden_kept_init, effect_finishing, nullptr}, {EFFECT_BISHOP_SHIELD, nullptr, bishop_shield_update, nullptr}, {EFFECT_HERETIC_PENTAGRAM, floor_init, effect_poof_update, nullptr}, {EFFECT_SIREN_RING, siren_ring_init, effect_poof_update, nullptr}, diff --git a/src/entity_familiar.cpp b/src/entity_familiar.cpp index b1cf036..e7aa646 100644 --- a/src/entity_familiar.cpp +++ b/src/entity_familiar.cpp @@ -38,9 +38,6 @@ constexpr std::pair ORBIT_LAYERS[] = { {69, 0}, {70, 0}, {83, 0}, {126, 0}, {226, 0}, {43, 1}, {65, 5}, {68, 5}, {116, 5}, {117, 5}, {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[] = {228, 236}; - // 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}; constexpr int KEEP_HIT_LIST_VARIANTS[] = {24, 102}; @@ -440,13 +437,13 @@ static void bone_orbital_init(Entity_Familiar& bone) // Part of 0060de70: what each variant starts with. The rarer familiars stop the game. void Entity_Familiar::variant_init(int initSubtype) { - if (familiar_listed(UNWRITTEN_INIT_VARIANTS, variant)) - return reconstruction_missing("Entity_Familiar::Init 0060de70 (this familiar's setup)"); if (familiar_listed(FLOAT_DOWN_VARIANTS, variant)) return sprite.Play("FloatDown"); switch (variant) { case FORGOTTEN_BODY: forgotten_body_init(*this); break; + case MINISAAC: minisaac_init(*this); break; + case STAR_OF_BETHLEHEM: star_of_bethlehem_init(*this); break; case ABYSS_LOCUST: locust_init(*this); break; case ISAACS_BODY: if (player) isaacs_body_init(*this); @@ -956,6 +953,9 @@ void Entity_Familiar::variant_update() case SWORN_PROTECTOR: return sworn_protector_update(*this); case LIL_GURDY: return ai_lil_gurdy(); case LIL_HARBINGERS: return ai_lil_harbingers(); + case LIL_SPEWER: return lil_spewer_update(*this); + case MINISAAC: return minisaac_update(*this); + case STAR_OF_BETHLEHEM: return star_of_bethlehem_update(*this); case BUMBO: return bumbo_update(*this); case DAMOCLES: return ai_shadow_intruder_damocles(false); case VANISHING_TWIN: return vanishing_twin_update(*this); diff --git a/src/entity_familiar.h b/src/entity_familiar.h index 176f290..555db1a 100644 --- a/src/entity_familiar.h +++ b/src/entity_familiar.h @@ -2,6 +2,7 @@ #include "anm2.h" #include "entity.h" +#include "entity_effect.h" #include "path_finder.h" #include "sfx_manager.h" #include "weapon.h" @@ -72,6 +73,21 @@ enum ClotKind : int CLOT_LIL }; +// The Dips the familiar code tells apart (Lua's DipSubType). +enum DipSubtype +{ + DIP_SUBTYPE_RED = 1, + DIP_SUBTYPE_CORNY = 2, + DIP_SUBTYPE_GOLDEN = 3, + DIP_SUBTYPE_RAINBOW = 4, + DIP_SUBTYPE_BLACK = 5, + DIP_SUBTYPE_WHITE = 6, + DIP_SUBTYPE_STONE = 12, + DIP_SUBTYPE_FLAMING = 13, + DIP_SUBTYPE_STINKY = 14, + DIP_SUBTYPE_BROWNIE = 20 +}; + // How many kinds of Lil Harbinger there are. constexpr int HARBINGER_KINDS = 5; @@ -95,6 +111,7 @@ struct TargetSearch // Construction and destruction (0060d3d0, 0060d200) are the defaults, with the familiar owning its pathfinder, and // set_extra_data (004357e0) is the extra data's reset. // Field accessors (004361f0, 00505cf0, 0060d0e0, 0060d100, 0060d120, 0060d130) are the public fields. +// GetPlayerSlot (0060d180) is PlayerManager's color lookup for a versus player, which player_color_mod_get makes. // A familiar (Lua's EntityFamiliar): its player, its place in the following line or an orbit, the consumables it // collects, its weapon, and the extra data some variants keep. struct Entity_Familiar : Entity @@ -350,7 +367,6 @@ struct Entity_Familiar : Entity void ai_mr_me_wisp(); void ai_mega_blast_wisp(); static int GetRandomWisp(RNG* rng); - KColor* GetPlayerSlot(KColor* outColor, Entity_Player* player); bool CanBeDamagedByEnemy(); bool CanBlockProjectiles(); float GetMultiplier(); @@ -433,16 +449,12 @@ struct Entity_Familiar : Entity void ai_lil_monstro(); void ai_variant_111(); void update_angry_fly(); - void ai_lil_spewer(); void ai_lil_harbingers(); Entity_Laser* FireBrimstone(const Vector& aimDirection, BrimstoneLook look); static Entity* ThrowDip(int subType, const Vector& position, Entity* spawner); Entity_Laser* sprinkler_shoot_laser(float angle, float distance); void update_idle_anim_by_size(); void RemoveFromPlayer(uint8_t unusedRemoveFamiliar); - void ai_minisaac(); - void minisaac_fire(); - static void minisaac_find_target(); void ai_blood_oath(); void paschal_candle_sync_effects(); void zhl_misfit_006414c0(); @@ -459,7 +471,6 @@ struct Entity_Familiar : Entity void UpdateDirtColor(); void update_star_of_bethlehem_speed(bool isForce); void ai_blood_clot(bool isPostMove); - static uint8_t multidimensional_baby_copy_knife(Entity_Knife* knife, Entity* unused); private: void blood_puppy_restore(float bodyHealth); @@ -470,6 +481,32 @@ private: bool solid_check(Entity& collider, bool isIgnored); }; +// A wave of creep Lil Spewer spews (wave_chain_spawn's arguments): where the next puddle goes and the way the wave +// runs, the familiar spewing it, each puddle's damage and size, the step to the next and the white wave's turn each step, +// the creep, the frames between puddles, Lil Spewer's kind, the puddles left and how long each lasts. +struct WaveChain +{ + Vector direction{}; + Vector position{}; + Entity* spawner = nullptr; + float curve = 0; + float damage = 0; + float scale = 0; + float step = 0; + int creep = 0; + int delay = 0; + int kind = 0; + int puddles = 0; + int timeout = 0; +}; + +// A creep puddle's part of a Lil Spewer wave, and the familiar spewing it. +struct WaveChainData : Entity_Effect::ExtraData +{ + WaveChain wave; + EntityPtr spawner; +}; + // The body parts Isaac's body (Pinking Shears) draws: the player's body, its two body layers and the top layer. constexpr int BODY_PART_COUNT = 4; @@ -534,6 +571,16 @@ void detached_head_update(Entity_Familiar& head); void decap_head_update(Entity_Familiar& head); void detached_head_render(Entity_Familiar& head, const Vector& offset); +// Lil Spewer and its creep waves, and the other late familiars (familiar_babies.cpp). +void wave_chain_spawn(const WaveChain& wave); +void wave_chain_update(Entity_Effect& puddle); +void lil_spewer_update(Entity_Familiar& spewer); +void minisaac_init(Entity_Familiar& minisaac); +void minisaac_update(Entity_Familiar& minisaac); +void star_of_bethlehem_init(Entity_Familiar& star); +void star_of_bethlehem_update(Entity_Familiar& star); +bool multidimensional_knife_copy(Entity_Knife& knife); + // The variant behaviours of Update written as their own functions (familiar_update.cpp). void brown_nugget_update(Entity_Familiar& fly); void charged_baby_update(Entity_Familiar& baby); diff --git a/src/entity_knife.cpp b/src/entity_knife.cpp index 7716522..3b90da4 100644 --- a/src/entity_knife.cpp +++ b/src/entity_knife.cpp @@ -26,7 +26,6 @@ constexpr float KNIFE_DAMAGE_DEFAULT = 22; constexpr float KNIFE_MAX_DISTANCE_DEFAULT = 100; constexpr float KNIFE_PATH_PROGRESS_NONE = -100; constexpr float KNIFE_PATH_FOLLOW_SPEED = 0.1f; -constexpr float KNIFE_PATH_OFFSET_RANGE = 50; constexpr float KNIFE_GRAVITY = -2; constexpr float KNIFE_ORBIT_GRAVITY = -1; constexpr float KNIFE_SWING_GRAVITY_SCALE = 0.75f; diff --git a/src/entity_knife.h b/src/entity_knife.h index 781aed1..64d9843 100644 --- a/src/entity_knife.h +++ b/src/entity_knife.h @@ -46,6 +46,9 @@ struct KnifeHit bool isFlying = false; }; +// How far a path knife's homing path may start off its line, both ways. +constexpr float KNIFE_PATH_OFFSET_RANGE = 50; + // Construction and destruction (00960b50, 00960a70) are the defaults. // Field accessors (004d7790, 004d77a0, 0060cf10, 0060cfb0, 0085de90, 0085deb0, 0085dec0) are the public fields. // A knife (Lua's EntityKnife): Mom's Knife and the swung weapons (bones, clubs, swords), with the tear effects they diff --git a/src/entity_knife_hits.cpp b/src/entity_knife_hits.cpp index d806808..b80349b 100644 --- a/src/entity_knife_hits.cpp +++ b/src/entity_knife_hits.cpp @@ -1,4 +1,5 @@ #include "boss_ai.h" +#include "boss_final.h" #include "capsule.h" #include "entity_bomb.h" #include "entity_effect.h" @@ -62,7 +63,6 @@ constexpr int SWING_SHOT_FRAMES = 5; // What else a swing hits: fire it puts out, Mother's balls, projectiles and pickups it bats, and the cube baby. constexpr float FIREPLACE_SWING_DAMAGE = 1000; constexpr int FIREPLACE_HARD_VARIANT = 11; -constexpr int MOTHER_BALL_VARIANT = 100; constexpr float PROJECTILE_BAT_HEIGHT = -50; constexpr float CUBE_BABY_DRAG = 0.25f; constexpr float LUDOVICO_TEAR_BAT = 1.25f; @@ -132,11 +132,6 @@ constexpr float KNIFE_BLAST_REFERENCE_DAMAGE = 31; constexpr float KNIFE_BLAST_RADIUS_MAX = 70; constexpr int BLAST_BLUE_FLY_ODDS = 6; constexpr int BLAST_BLUE_FLY_MAX = 30; -constexpr float POISON_CLOUD_DEPTH = -5; -constexpr float POISON_CLOUD_FLATTEN = 0.4f; -constexpr int POISON_CLOUD_SUBTYPE = 4; -constexpr ColorMod POISON_SPLAT_COLOR = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {0, 0.33333334f, 0}}; -constexpr ColorMod POISON_CLOUD_COLOR = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {0.039215688f, 0.3921569f, 0}}; constexpr int BURST_MIN = 6; constexpr uint32_t BURST_SPREAD = 6; constexpr float BURST_SCALE = 1.5f; @@ -229,27 +224,6 @@ static void shard_finish(Entity_Knife& knife, Entity_Tear& shard, float scale, E shard.Update(); } -// Ipecac's poison splat and cloud around a blast. -static void poison_cloud_spawn(const Vector& position, float scale, bool isCloud) -{ - Entity* splat = g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); - float size = (random_unit() + 1) * scale; - splat->sprite.scale = vector_make(size, size); - splat->SetColor(POISON_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); - splat->Update(); - if (!isCloud) return; - - Entity* cloud = g_game->Spawn({.position = position, - .subType = POISON_CLOUD_SUBTYPE, - .type = ENTITY_EFFECT, - .variant = EFFECT_BLOOD_EXPLOSION, - .seed = Random()}); - cloud->SetColor(POISON_CLOUD_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); - cloud->sprite.scale = vector_make(scale, scale * POISON_CLOUD_FLATTEN); - cloud->renderDepthOffset = POISON_CLOUD_DEPTH; - cloud->Update(); -} - // 009680d0 Starts a swing: a sword swings toward its facing, a club alternates Swing and Swing2. Held by a player or // familiar, the weapon starts close by, pointing away. The swing hits anew. void Entity_Knife::SetAttackAnimation() @@ -480,6 +454,23 @@ static uint64_t swing_damage_flags(Entity_Knife& knife, Entity& enemy, Entity_Pl return flags; } +// Part of 009688d0: a swing bats Mother's falling ball back up at 18 toward Mother (or straight away without her), its +// reach to her a little longer and the ball a little heavier. +static void mother_ball_bat(Entity_Knife& knife, Entity_NPC& ball) +{ + constexpr float BALL_BATTED_SPEED = 18; + constexpr float BALL_BATTED_REACH = 0.1f; + + if (ball.velocity.y <= 0 || ball.pos.y >= knife.pos.y) return; + ball.state = NPC_STATE_SPECIAL; + Vector toward = vector_sub(ball.parent ? ball.parent->pos : ball.pos, knife.pos); + float distance = vector_length(toward); + ball.velocity = distance > 0 ? vector_scale(toward, BALL_BATTED_SPEED / distance) : toward; + float reach = vector_length(ball.targetPosition); + ball.targetPosition = distance > 0 ? vector_scale(toward, (reach + BALL_BATTED_REACH) / distance) : toward; + ball.mass += 1; +} + // An enemy (or fire, poop, TNT) a swing reaches: hit once per swing, pushed away and hurt, with the swing's effects, // and the swinger recoils from the first living one. False when the axe broke and the swing stops. static bool swing_enemy_hit(Entity_Knife& knife, Entity& enemy, SwingHit& hit) @@ -499,8 +490,11 @@ static bool swing_enemy_hit(Entity_Knife& knife, Entity& enemy, SwingHit& hit) if (hit.player) Entity::ForceCollide(hit.player, &enemy, true); return true; } - if (enemy.type == ENTITY_MOTHER && enemy.variant == MOTHER_BALL_VARIANT) - reconstruction_missing("Entity_Knife::UpdateSwingHits 009688d0 (batting Mother's ball)"); + if (enemy.type == ENTITY_MOTHER && enemy.variant == MOTHER_ORB) + { + mother_ball_bat(knife, static_cast(enemy)); + return true; + } if (enemy.type == ENTITY_SHOPKEEPER || enemy.isDead) return true; Vector away = vector_normalized(vector_sub(enemy.pos, hit.knockbackOrigin)); @@ -881,7 +875,7 @@ void Entity_Knife::apply_hit_effects(const KnifeHit& hit) .damageFlags = hit.damageFlags | DAMAGE_EXPLOSION, .damage = hit.damage * CLUB_BLAST_DAMAGE, .radius = CLUB_BLAST_RADIUS}); - if (tearFlags[TEAR_POISON]) poison_cloud_spawn(hitPosition, 1, false); + if (tearFlags[TEAR_POISON]) poison_splash_spawn({.position = hitPosition, .isCloud = false}); Entity* blast = g_game->Spawn({.position = hitPosition, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); blast->posOffset = posOffset; @@ -1001,7 +995,7 @@ void Entity_Knife::apply_hit_effects(const KnifeHit& hit) .damageFlags = damageFlags, .damage = damage, .radius = radius}); - if (tearFlags[TEAR_POISON]) poison_cloud_spawn(at, sizeScale, true); + if (tearFlags[TEAR_POISON]) poison_splash_spawn({.position = at, .scale = sizeScale}); Entity* blast = g_game->Spawn({.position = at, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); blast->posOffset = posOffset; diff --git a/src/entity_laser.cpp b/src/entity_laser.cpp index b11fcbc..c1608f2 100644 --- a/src/entity_laser.cpp +++ b/src/entity_laser.cpp @@ -3,6 +3,7 @@ #include "entity_effect.h" #include "entity_factory.h" #include "entity_familiar.h" +#include "entity_knife.h" #include "entity_player.h" #include "entity_tear.h" #include "fx_layers.h" @@ -14,6 +15,7 @@ #include "npc_basement.h" #include "room.h" #include "room_config.h" +#include "room_render.h" #include "sfx_manager.h" #include #include @@ -107,6 +109,59 @@ constexpr int IMPACT_SUBTYPE_RING = 5; constexpr int IMPACT_SUBTYPE_GIANT = 6; constexpr int IMPACT_SUBTYPE_BROWN = 7; constexpr int IMPACT_SUBTYPE_GIANT_END = 4; +constexpr float SEGMENT_PARALLEL = 1e-5f; +constexpr float MIRROR_REACH = 20; +constexpr float MIRROR_DAMAGE = 7; +constexpr int MIRROR_FRESH_FRAMES = 150; +constexpr int MIRROR_TIMEOUT_MIN = 30; +constexpr float BOUNCE_DEPTH = 100; +constexpr ColorMod MIRROR_COLOR = {{1, 1, 1, 1}, {5, 5, 4, 1}, {0, 0, 0}}; +constexpr float SPLIT_SIDE_OFFSET = 5; +constexpr int MULTIDIMENSIONAL_PULSE_FRAMES = 16; +constexpr float MULTIDIMENSIONAL_PULSE_STEP = 0.125f; +constexpr float MULTIDIMENSIONAL_COLORIZE_BASE = 0.3f; +constexpr float MULTIDIMENSIONAL_OFFSET_SCALE = 0.4f; +constexpr float MULTIDIMENSIONAL_OFFSET_BASE = 0.2f; +constexpr float PRISM_SPREAD[] = {-30, -10, 10, 30}; +constexpr float PRISM_LIGHT = 0.3921569f; +constexpr float PRISM_STRONG = 0.7843138f; +constexpr ColorMod PRISM_COLORS[] = { + COLOR_DEFAULT, + {{1, 2, 1, 1}, {0, 0, 0, 0}, {PRISM_LIGHT, PRISM_STRONG, 0}}, + {{1, 2, 1, 1}, {0, 0, 0, 0}, {-PRISM_STRONG, PRISM_STRONG, PRISM_LIGHT}}, + {{1, 1, 2, 1}, {0, 0, 0, 0}, {-PRISM_STRONG, PRISM_LIGHT, PRISM_STRONG}}}; +constexpr float CONTINUUM_CLAMP = -131; +constexpr float LASER_CONTINUUM_WRAP_MARGIN = -130; +constexpr int CONTINUUM_WRAPS = 4; +constexpr float CARRIED_REACH_MIN = 10; +constexpr int BOUNCE_PROBE_STEP = 6; +constexpr float BOUNCE_PROBE_REACH = 20; +constexpr float BOUNCE_KEEPER_RANGE = 250; +constexpr float LASER_CREEP_ROOM_MARGIN = 15; +constexpr float LASER_CREEP_SCALE = 0.4f; +constexpr float POP_TEAR_SPEED = 20; +constexpr float POP_TEAR_SCALE_MIN = 0.9f; +constexpr float POP_TEAR_SCALE_RANGE = 1.1f; +constexpr float POP_TEAR_SPEED_MIN = 0.8f; +constexpr float POP_TEAR_SPEED_RANGE = 0.3f; +constexpr float POP_TEAR_BACKSTEP = 0.7f; +constexpr float POP_TEAR_WIDTH_MARGIN = 6; +constexpr float SUB_LASER_EASE = 0.3f; +constexpr float SUB_LASER_TURN = 0.4f; +constexpr float SUB_LASER_BACKSTEP = 0.25f; +constexpr float SUB_LASER_SCALE = 0.8f; +constexpr float CHAIN_SPEED = 40; +constexpr float CHAIN_SCATTER = 39; +constexpr float CHAIN_HOMING_REACH = 1e8f; +constexpr float CHAIN_ZAP_VOLUME = 0.15f; +constexpr float BOOMERANG_LENGTH = 120; +constexpr float BOOMERANG_SHOT_SPEED_UNIT = 1.6f; +constexpr float WIGGLE_PATH_UNIT = 200; +constexpr float WIGGLE_ROLL_SPEED = 0.1f; +constexpr float WIGGLE_REACH = 30; +constexpr float WIGGLE_TURNS = 15; +constexpr uint32_t WIGGLE_EASE_IN = 20; +constexpr uint32_t WIGGLE_EASE_OUT = 22; constexpr const char* STATIC_LASER_ANM2 = "gfx/007.001_Static Laser.anm2"; constexpr const char* CAGE_VIS_LASER_ANM2 = "gfx/007.006_CageVisLaser.anm2"; constexpr const char* STATIC_IMPACT_ANM2 = "gfx/1000.050_brimstoneimpact_static.anm2"; @@ -150,23 +205,6 @@ static void laser_sound_play(int sound, SoundPlay play) g_manager->sfxManager.Play(sound, play); } -// A color's tint, colorize and offset applied to a KColor, as Color::apply_to_kcolor does. -static KColor color_apply(const ColorMod& color, const KColor& input) -{ - float red = color._tint[0] * input._red; - float green = color._tint[1] * input._green; - float blue = color._tint[2] * input._blue; - if (color._colorize[3] != 0) - { - float luminance = green * LUMINANCE_GREEN + red * LUMINANCE_RED + blue * LUMINANCE_BLUE; - red += (luminance * color._colorize[0] - red) * color._colorize[3]; - green += (luminance * color._colorize[1] - green) * color._colorize[3]; - blue += (luminance * color._colorize[2] - blue) * color._colorize[3]; - } - return kcolor_rgba(red + color._offset[0], green + color._offset[1], blue + color._offset[2], - color._tint[3] * input._alpha); -} - // 006827a0 The shortest signed turn from one angle to another, in degrees. float angle_difference(float from, float to) { @@ -180,6 +218,26 @@ float angle_difference(float from, float to) return to - from; } +// 0084d8b0 Whether two segments cross (not when nearly parallel), and where, measured along the one further along. +bool segment_intersect(const SegmentPair& segments, Vector& outHit) +{ + Vector along = vector_sub(segments.start, segments.end); + Vector across = vector_sub(segments.first, segments.second); + Vector apart = vector_sub(segments.start, segments.first); + float denominator = across.y * along.x - across.x * along.y; + if (!(std::abs(denominator) > SEGMENT_PARALLEL)) return false; + + float t = -(apart.y * along.x - apart.x * along.y) / denominator; + float u = (apart.x * across.y - apart.y * across.x) / denominator; + if (!(t >= 0 && t <= 1 && u >= 0 && u <= 1)) return false; + + Vector start = u > t ? segments.start : segments.first; + Vector end = u > t ? segments.end : segments.second; + float fraction = u > t ? u : t; + outHit = vector_add(start, vector_scale(vector_sub(end, start), fraction)); + return true; +} + // 0096cb60 Points the laser's path at it. Entity_Laser::Entity_Laser() { @@ -566,7 +624,7 @@ ColorMod Entity_Laser::CalculateTearColor() multiplier = kcolor_rgba(1, 0, 0, 1); else color_multiply(tinted, {{1, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}); - KColor result = color_apply(tinted, multiplier); + KColor result = kcolor_apply(tinted, multiplier); red = result._red; green = result._green; blue = result._blue; @@ -1142,10 +1200,14 @@ void Entity_Laser::update_laser() bool isCut = false; if (!isSampleLaser) straight_update(isRedirected); - else if ((homingType != LASER_HOMING_FREEZE && !isOneHit) || isFirstUpdate) + else { - isSamplesRebuilt = true; - path_update(isRedirected, isCut); + if ((homingType != LASER_HOMING_FREEZE && !isOneHit) || isFirstUpdate) + { + isSamplesRebuilt = true; + path_update(isRedirected, isCut); + } + creep_update(); } death_update(); @@ -1153,7 +1215,7 @@ void Entity_Laser::update_laser() if (isHitFrame) update_endpoint_and_hits(); if (isSampleLaser && isExists) { - ends_update(isSamplesRebuilt, isHitFrame, isRedirected, isCut); + if (isSamplesRebuilt) ends_update(isHitFrame, isRedirected, isCut); chain_fire(); } @@ -1174,7 +1236,7 @@ void Entity_Laser::update_laser() } // A straight beam's end: along its angle to the grid or the room's edge within its reach. A beam not the players' -// bounces off a mirror it meets. +// bounces off the last mirror it meets facing it. void Entity_Laser::straight_update(bool& isRedirected) { isGridHit = false; @@ -1200,9 +1262,32 @@ void Entity_Laser::straight_update(bool& isRedirected) if (spawnerType != ENTITY_PLAYER && spawnerType != ENTITY_FAMILIAR) { - if (!entity_query(ENTITY_EFFECT, EFFECT_LASER_MIRROR).empty()) - reconstruction_missing("Entity_Laser::update_laser 00973c60: a beam off a mirror"); - if (bounceLaser) bounceLaser->Remove(); + Entity* mirror = nullptr; + Vector normal{}; + for (Entity* candidate : entity_query(ENTITY_EFFECT, EFFECT_LASER_MIRROR)) + { + Vector facing = vector_from_angle(static_cast(candidate)->rotation); + if (vector_dot(facing, vector_sub(endPoint, start)) >= 0) continue; + + Vector center = vector_add(candidate->pos, vector_scale(facing, MIRROR_REACH)); + Vector across = vector_scale(vector_rotated(facing, RIGHT_ANGLE_DEGREES), candidate->size); + Vector hit{}; + if (!segment_intersect({start, endPoint, vector_sub(center, across), vector_add(center, across)}, hit)) + continue; + endPoint = hit; + normal = facing; + mirror = candidate; + } + + if (mirror) + { + Entity* owner = mirror->parent; + float angle = vector_angle(vector_reflected(vector_sub(endPoint, start), normal)); + mirror_bounce_set(vector_sub(endPoint, posOffset), angle, owner ? owner->ToPlayer() : nullptr); + isRedirected = true; + } + else if (bounceLaser) + bounceLaser->Remove(); } laserLength = vector_length(vector_sub(endPoint, start)); update_impact_effect(isRedirected); @@ -1210,7 +1295,7 @@ void Entity_Laser::straight_update(bool& isRedirected) // A path laser's samples: from the tip of its start sprite to its end, along a straight path (homing and shaped by // its tear flags), cut by the grid, then split by Multidimensional Baby and Angelic Prism, bounced by a mirror, -// wrapped by Continuum, or bounced by Rubber Cement. +// wrapped by Continuum, or bounced by Rubber Cement. A thick beam of the player's drips at a blocked end. void Entity_Laser::path_update(bool& isRedirected, bool& isCut) { isGridHit = false; @@ -1253,12 +1338,14 @@ void Entity_Laser::path_update(bool& isRedirected, bool& isCut) if (tearFlags[TEAR_ORBIT]) homingLaser.build_curl_path(HOMING_LASER_RING_REACH); if (tearFlags[TEAR_BOOMERANG]) { - homingLaser.build_wiggle_bezier(); + float loopLength = player ? player->shotSpeed / BOOMERANG_SHOT_SPEED_UNIT * BOOMERANG_LENGTH : BOOMERANG_LENGTH; + homingLaser.build_wiggle_bezier( + {.length = loopLength, .maxLength = maxDistance, .width = HOMING_LASER_RING_REACH}); if (!homingLaser.bezier.empty()) endPoint = homingLaser.bezier.back().point; } if (tearFlags[TEAR_TURN_HORIZONTAL]) { - homingLaser.trace_entities(TEAR_TURN_HORIZONTAL); + homingLaser.trace_entities(); if (!homingLaser.bezier.empty()) endPoint = homingLaser.bezier.back().point; } @@ -1301,106 +1388,397 @@ void Entity_Laser::path_update(bool& isRedirected, bool& isCut) bool isPlayersParent = parent && (parent->type == ENTITY_PLAYER || parent->type == ENTITY_FAMILIAR); if (g_game->challenge == CHALLENGE_GUARDIAN && !isPlayersParent) homingLaser.truncate_samples_at_player(); - bool isMirrored = false; - path_redirects_update(isRedirected, isCut, isMirrored); + bool isPlayers = + spawnerType == ENTITY_PLAYER || (spawnerType == ENTITY_FAMILIAR && spawnerVariant != FAMILIAR_ANGELIC_PRISM); + if (isPlayers && !isMultidimensionalTouched) multidimensional_update(isRedirected, isCut); + + bool isMirrored = false; + bool isOthers = + (spawnerType != ENTITY_PLAYER && spawnerType != ENTITY_FAMILIAR) || g_game->deathmatchManager.is_active(); + if (isOthers) isMirrored = mirror_update(isRedirected, isCut); + + bool isPrismable = spawnerType == ENTITY_PLAYER || + (spawnerType == ENTITY_FAMILIAR && spawnerVariant != Entity_Familiar::MULTIDIMENSIONAL_BABY); + if (isPrismable && !isPrismTouched) prism_update(isRedirected, isCut); + + continuum_update(isRedirected, isCut); + if (!isMirrored) rubber_cement_update(isRedirected); - if (!isMirrored) - { - if (tearFlags[TEAR_BOUNCE] && !isRedirected) - reconstruction_missing("Entity_Laser::update_laser 00973c60: Rubber Cement's bounce"); - if (bounceLaser) bounceLaser->Remove(); - spawn_impact_effect(); - } if (!isGridHit) isCut = isCut || chainedLasers > 0; else chainedLasers = 0; update_impact_effect(isCut); + blood_drop_spawn(); +} +// A thick beam of the player's at a blocked end (or with no reach) drops a blood droplet there each frame, sprayed +// back along the beam. +void Entity_Laser::blood_drop_spawn() +{ Entity* follow = child; - int endCollision = follow ? (int)g_game->room->GetGridCollision( - g_game->room->GetGridIndex(vector_add(follow->pos, follow->posOffset))) - : 0; + int endCollision = follow ? (int)room_grid_collision_at(vector_add(follow->pos, follow->posOffset)) : 0; bool isDroppingVariant = variant == LASER_THICK_RED || variant == LASER_GIANT_RED || variant == LASER_BRIM_TECH || variant == LASER_THICKER_RED || variant == LASER_THICK_BROWN || variant == LASER_THICKER_BRIM_TECH || variant == LASER_GIANT_BRIM_TECH; bool isBlockedEnd = maxDistance == 0 || (endCollision != COLLISION_NONE && endCollision != COLLISION_PIT); - if (isDroppingVariant && sprite.scale.x > 0.5f && spawnerType == ENTITY_PLAYER && isBlockedEnd && - !isInterpolating && !HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && homingLaser.samples.size() > 1) - { - std::vector& samples = homingLaser.samples; - float back = vector_angle(vector_sub(samples[samples.size() - 2], samples.back())); - float angle = angle_wrap(random_fraction() * ANGLE_HALF_TURN + back - SPRITE_ROTATION_OFFSET); - uint32_t seed = Random(); - Vector velocity = vector_scale(vector_from_angle(angle), random_fraction() * 10 + 1); - Vector position = vector_add(samples.back(), vector_scale(random_direction(), random_fraction() * 20)); - Entity* drop = g_game->Spawn({.position = position, - .velocity = velocity, - .type = ENTITY_EFFECT, - .variant = EFFECT_BLOOD_DROP, - .seed = seed}); - if (child) - { - drop->sprite = child->sprite; - drop->sprite.SetFrame("Droplets", random_below(3)); - } - drop->posOffset = posOffset; - drop->SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); - drop->Update(); - } + bool isDropping = isDroppingVariant && sprite.scale.x > 0.5f && spawnerType == ENTITY_PLAYER && isBlockedEnd && + !isInterpolating && !HasEntityFlags(FLAG_INTERPOLATION_UPDATE); + std::vector& samples = homingLaser.samples; + if (!isDropping || samples.size() < 2) return; - if (tearFlags[TEAR_MYSTERIOUS_LIQUID_CREEP] && IsFrame(5, (int)index)) - reconstruction_missing("Entity_Laser::update_laser 00973c60: Mysterious Liquid's creep at the beam's end"); + float back = vector_angle(vector_sub(samples[samples.size() - 2], samples.back())); + float angle = angle_wrap(random_fraction() * ANGLE_HALF_TURN + back - SPRITE_ROTATION_OFFSET); + uint32_t seed = Random(); + Vector velocity = vector_scale(vector_from_angle(angle), random_fraction() * 10 + 1); + Vector spray = random_direction(); + Vector position = vector_add(samples.back(), vector_scale(spray, random_fraction() * 20)); + Entity* drop = g_game->Spawn( + {.position = position, .velocity = velocity, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_DROP, .seed = seed}); + if (child) + { + drop->sprite = child->sprite; + drop->sprite.SetFrame("Droplets", random_below(3)); + } + drop->posOffset = posOffset; + drop->SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + drop->Update(); } -// The splits a path laser meets: Multidimensional Baby doubles the players' beams through it, a mirror bounces the -// others, Angelic Prism splits the players' into four, and Continuum carries a beam on from the opposite wall. Each -// one met marks the beam redirected. -void Entity_Laser::path_redirects_update(bool& isRedirected, bool& isCut, bool& isMirrored) +// Mysterious Liquid: every fifth frame a path beam leaves a small puddle of green creep at its end. +void Entity_Laser::creep_update() +{ + std::vector& samples = homingLaser.samples; + if (!tearFlags[TEAR_MYSTERIOUS_LIQUID_CREEP] || !IsFrame(5, (int)index) || samples.empty()) return; + + Vector position = g_game->room->GetClampedPosition(samples.back(), LASER_CREEP_ROOM_MARGIN); + uint32_t seed = Random(); + Entity* creep = g_game->Spawn({.position = position, + .spawner = spawnerEntity, + .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_GREEN, + .seed = seed}); + creep->sprite.scale = vector_make(LASER_CREEP_SCALE, LASER_CREEP_SCALE); + creep->Update(); +} + +// Multidimensional Baby doubles a players' beam crossing it: two beams from beside the crossing, along the beam, +// pulsing white. They are taken back when the beam misses it. +void Entity_Laser::multidimensional_update(bool& isRedirected, bool& isCut) { Vector hitPosition{}; Vector hitDirection{}; - bool isPlayers = - spawnerType == ENTITY_PLAYER || (spawnerType == ENTITY_FAMILIAR && spawnerVariant != FAMILIAR_ANGELIC_PRISM); - if (isPlayers && !isMultidimensionalTouched) + if (!homingLaser.find_targets(hitPosition, hitDirection, ENTITY_FAMILIAR, Entity_Familiar::MULTIDIMENSIONAL_BABY, + nullptr)) { - if (homingLaser.find_targets(hitPosition, hitDirection, ENTITY_FAMILIAR, Entity_Familiar::MULTIDIMENSIONAL_BABY, - nullptr)) - reconstruction_missing("Entity_Laser::update_laser 00973c60: Multidimensional Baby's beams"); for (EntityPtr& split : multidimensionalLasers) if (split) split->Remove(); impact_effect_refresh(); + return; } - bool isOthers = - (spawnerType != ENTITY_PLAYER && spawnerType != ENTITY_FAMILIAR) || g_game->deathmatchManager.is_active(); - if (isOthers) + Vector side = vector_make(hitDirection.y * SPLIT_SIDE_OFFSET, -hitDirection.x * SPLIT_SIDE_OFFSET); + float angle = vector_angle(hitDirection); + if (!multidimensionalLasers[0] || !multidimensionalLasers[1]) + { + for (EntityPtr& slot : multidimensionalLasers) + { + if (slot) continue; + Entity_Laser* split = ShootAngle({.position = vector_add(hitPosition, side), + .posOffset = posOffset, + .source = parent, + .angleDegrees = angle, + .timeout = timeout, + .variant = variant, + .isPoolKept = true}); + side = vector_scale(side, -1); + if (!split) continue; + + split->isDisableFollowParent = true; + split->copy_from_parent(*this, LASER_COPY_SPAWN); + split->tearFlags = tearFlags; + split->tearFlags.reset(TEAR_LASER); + split->isMultidimensionalTouched = true; + split->parent = this; + split->Update(); + slot = split; + } + chainedLasers = 0; + } + else + for (EntityPtr& slot : multidimensionalLasers) + { + if (slot->type != ENTITY_LASER) continue; + Entity_Laser& split = static_cast(*slot); + split.copy_from_parent(*this, LASER_COPY_STATE); + split.set_aim_angle(angle); + split.pos = vector_add(hitPosition, side); + side = vector_scale(side, -1); + } + + int phase = (g_game->frameCount - spawnFrame) % MULTIDIMENSIONAL_PULSE_FRAMES; + int pulse = phase < MULTIDIMENSIONAL_PULSE_FRAMES / 2 ? phase : MULTIDIMENSIONAL_PULSE_FRAMES - phase; + float glow = (float)pulse * MULTIDIMENSIONAL_PULSE_STEP; + float colorize = glow + glow + MULTIDIMENSIONAL_COLORIZE_BASE; + float offset = glow * MULTIDIMENSIONAL_OFFSET_SCALE - MULTIDIMENSIONAL_OFFSET_BASE; + ColorMod color = {{1, 1, 1, 1}, {colorize, colorize, colorize, 1}, {offset, offset, offset}}; + for (EntityPtr& slot : multidimensionalLasers) + { + if (!slot || slot->type != ENTITY_LASER) continue; + Entity_Laser& split = static_cast(*slot); + split.SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (split.child) split.child->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (split.tearWaitEffect) split.tearWaitEffect->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + isRedirected = true; + isCut = false; +} + +// A mirror bounces a beam crossing it off its face, keeping the mirror up a while when it is new. Without one, a +// bounce the beam had for a player is taken back. Whether a mirror bounced it. +bool Entity_Laser::mirror_update(bool& isRedirected, bool& isCut) +{ + Vector hitPosition{}; + Vector hitDirection{}; + Entity* mirror = homingLaser.find_targets(hitPosition, hitDirection, ENTITY_EFFECT, EFFECT_LASER_MIRROR, this); + if (!mirror) { - Entity* mirror = homingLaser.find_targets(hitPosition, hitDirection, ENTITY_EFFECT, EFFECT_LASER_MIRROR, this); - isMirrored = mirror != nullptr; - if (isMirrored) reconstruction_missing("Entity_Laser::update_laser 00973c60: a beam off a mirror"); Entity* bounce = bounceLaser; if (bounce && bounce->parent && bounce->parent->type == ENTITY_PLAYER) bounce->Remove(); + return false; } - bool isPrismable = spawnerType == ENTITY_PLAYER || - (spawnerType == ENTITY_FAMILIAR && spawnerVariant != Entity_Familiar::MULTIDIMENSIONAL_BABY); - if (isPrismable && !isPrismTouched) + Entity_Effect& effect = *static_cast(mirror); + Entity* owner = mirror->parent; + float angle = vector_angle(vector_reflected(hitDirection, vector_from_angle(effect.rotation))); + mirror_bounce_set(hitPosition, angle, owner && owner->type == ENTITY_PLAYER ? owner : nullptr); + if (g_game->frameCount - mirror->spawnFrame < MIRROR_FRESH_FRAMES) + effect.SetTimeout(std::max(MIRROR_TIMEOUT_MIN, effect.timeout)); + isRedirected = true; + isCut = true; + return true; +} + +// The beam a mirror turned: lit (unless a light or electric beam), dealing 7, drawn above the beam, lasting and +// fading with it. A new one is shot from where the beam met the mirror. An old one is moved and turned there. +void Entity_Laser::mirror_bounce_set(const Vector& position, float angle, Entity* source) +{ + bool isPlain = variant == LASER_LIGHT_BEAM || variant == LASER_ELECTRIC; + Entity_Laser* bounce = static_cast(bounceLaser.get()); + bool isNew = !bounce; + if (isNew) + { + bounce = ShootAngle({.position = position, + .posOffset = posOffset, + .source = source, + .angleDegrees = angle, + .timeout = timeout, + .variant = variant, + .isPoolKept = true}); + if (!bounce) return; + bounce->isDisableFollowParent = true; + bounce->isPrismTouched = true; + } + + bounce->SetColor(isPlain ? COLOR_DEFAULT : MIRROR_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + bounce->SetCollisionDamage(MIRROR_DAMAGE); + bounce->renderDepthOffset = renderDepthOffset + BOUNCE_DEPTH; + bounce->timeout = timeout; + bounce->isShrink = isShrink || isDead; + if (isNew) + { + bounce->Update(); + bounceLaser = bounce; + return; + } + bounce->set_aim_angle(angle); + bounce->pos = position; +} + +// Angelic Prism splits a players' beam crossing it into four, fanned 30 and 10 degrees either side, each but the +// first tinted. They are taken back when the beam misses it. +void Entity_Laser::prism_update(bool& isRedirected, bool& isCut) +{ + Vector hitPosition{}; + Vector hitDirection{}; + if (!homingLaser.find_targets(hitPosition, hitDirection, ENTITY_FAMILIAR, FAMILIAR_ANGELIC_PRISM, nullptr)) { - if (homingLaser.find_targets(hitPosition, hitDirection, ENTITY_FAMILIAR, FAMILIAR_ANGELIC_PRISM, nullptr)) - reconstruction_missing("Entity_Laser::update_laser 00973c60: Angelic Prism's beams"); for (EntityPtr& split : prismLasers) if (split) split->Remove(); impact_effect_refresh(); + return; } - if (!tearFlags[TEAR_CONTINUUM] || isRedirected || isGridHit) + float angle = vector_angle(hitDirection); + bool isMissing = std::any_of(prismLasers.begin(), prismLasers.end(), [](EntityPtr& split) { return !split; }); + for (size_t i = 0; i < prismLasers.size(); i++) + { + EntityPtr& slot = prismLasers[i]; + float splitAngle = angle + PRISM_SPREAD[i]; + if (isMissing) + { + if (slot) continue; + Entity_Laser* split = ShootAngle({.position = hitPosition, + .posOffset = posOffset, + .source = parent, + .angleDegrees = splitAngle, + .timeout = timeout, + .variant = variant, + .isPoolKept = true}); + if (!split) continue; + split->isDisableFollowParent = true; + split->copy_from_parent(*this, LASER_COPY_SPAWN); + split->isPrismTouched = true; + split->Update(); + slot = split; + continue; + } + + if (slot->type != ENTITY_LASER) continue; + Entity_Laser& split = static_cast(*slot); + split.copy_from_parent(*this, LASER_COPY_STATE); + split.SetColor(PRISM_COLORS[i], -1, COLOR_PRIORITY_DEFAULT, false, true); + split.set_aim_angle(splitAngle); + split.pos = hitPosition; + } + if (isMissing) chainedLasers = 0; + isRedirected = true; + isCut = false; +} + +// Continuum: a beam reaching past the room's edge goes on from the opposite wall, wrapped round the room, along the +// direction its path ends in. Without a wrap (or when redirected or stopped by the grid) the carried beam goes. +void Entity_Laser::continuum_update(bool& isRedirected, bool& isCut) +{ + std::vector& samples = homingLaser.samples; + bool isCarried = tearFlags[TEAR_CONTINUUM] && !isRedirected && !isGridHit; + if (!isCarried || samples.empty() || homingLaser.bezier.empty()) { if (continuumLaser) continuumLaser->Remove(); + return; } - else - reconstruction_missing("Entity_Laser::update_laser 00973c60: Continuum's beam from the far wall"); - (void)isCut; + + BezierPoint& last = homingLaser.bezier.back(); + float angle = vector_angle(vector_sub(last.handleOut, last.handleIn)); + Vector end = samples.back(); + float travelled = vector_distance(samples[0], end); + Room& room = *g_game->room; + Vector wrapped = room.GetClampedPositionImpl(vector_add(end, posOffset), CONTINUUM_CLAMP, CONTINUUM_CLAMP, + CONTINUUM_CLAMP, CONTINUUM_CLAMP); + for (int i = 0; i < CONTINUUM_WRAPS; i++) + { + Vector next = room_screen_wrap(wrapped, LASER_CONTINUUM_WRAP_MARGIN); + if (next.x == wrapped.x && next.y == wrapped.y) break; + wrapped = next; + } + wrapped = vector_sub(wrapped, posOffset); + if (wrapped.x == end.x && wrapped.y == end.y) + { + if (continuumLaser) continuumLaser->Remove(); + return; + } + + Entity_Laser* carried = static_cast(continuumLaser.get()); + if (!carried) + { + carried = carried_laser_spawn(wrapped, angle); + continuumLaser = carried; + if (!carried) return; + chainedLasers = 0; + } + TearFlags dropped{}; + dropped.set(TEAR_CONTINUUM); + carried_laser_update(*carried, {.droppedFlags = dropped, .position = wrapped, .angle = angle, .travelled = travelled}); + isRedirected = true; + isCut = false; +} + +// Rubber Cement: a beam bounces off the walls and blocks around its end, mirrored about the way out of them (a bit +// less for the Ring Keeper's close beams). Without it, or when redirected, the bounce goes and the impact comes back. +void Entity_Laser::rubber_cement_update(bool isRedirected) +{ + std::vector& samples = homingLaser.samples; + if (!tearFlags[TEAR_BOUNCE] || isRedirected || samples.size() < 2) + { + if (bounceLaser) bounceLaser->Remove(); + spawn_impact_effect(); + return; + } + + Room& room = *g_game->room; + Vector gridOffset = vector_scale(posOffset, GRID_HIT_OFFSET_SCALE); + Entity_Laser* bounce = static_cast(bounceLaser.get()); + Vector end = samples.back(); + float travelled = vector_distance(end, samples[0]); + Vector normal{}; + for (int degrees = 0; degrees < (int)ANGLE_FULL_TURN; degrees += BOUNCE_PROBE_STEP) + { + Vector probe = vector_scale(vector_from_angle((float)degrees), BOUNCE_PROBE_REACH); + Vector at = vector_add(vector_add(room.GetClampedPosition(samples.back(), 0), probe), gridOffset); + if (grid_collision_blocks(entityGridCollisionClass, (int)room_grid_collision_at(at))) + normal = vector_add(normal, probe); + } + + Vector direction = vector_sub(samples.back(), samples[samples.size() - 2]); + normal = vector_normalized(normal); + float factor = 2; + Entity* owner = parent; + if (owner && owner->type == SPAWNER_RING_KEEPER && owner->subtype == 2) + factor = 2 - (1 - std::clamp(vector_distance(pos, end), 0.0f, BOUNCE_KEEPER_RANGE) / BOUNCE_KEEPER_RANGE); + Vector turned = vector_sub(direction, vector_scale(vector_scale(normal, vector_dot(direction, normal)), factor)); + float angle = vector_angle(turned); + + if (!bounce) + { + if (vector_is_zero(normal)) return; + bounce = carried_laser_spawn(end, angle); + bounceLaser = bounce; + if (!bounce) return; + chainedLasers = 0; + } + TearFlags dropped{}; + dropped.set(TEAR_BOUNCE); + carried_laser_update(*bounce, {.droppedFlags = dropped, .position = end, .angle = angle, .travelled = travelled}); +} + +// A laser carrying this one on (a wrap, a bounce, a split): shot from a position at an angle, quiet, not following +// its parent, with this one's spawn data, sharing its hit list, and parented to this one (or to its parent for a +// laser that hits once). +Entity_Laser* Entity_Laser::carried_laser_spawn(const Vector& position, float angle) +{ + Entity_Laser* carried = ShootAngle({.position = position, + .posOffset = posOffset, + .source = parent, + .angleDegrees = angle, + .timeout = timeout, + .variant = variant, + .isPoolKept = true}); + if (!carried) return nullptr; + + carried->isDisableInitSound = true; + carried->isDisableFollowParent = true; + carried->copy_from_parent(*this, LASER_COPY_SPAWN); + carried->parentLaser = this; + carried->parent = isOneHit ? parent.get() : this; + return carried; +} + +// Keeps a carried laser like this one: its look and flags (but the ones it drops), its start and angle, and the reach +// this beam has left past what it travelled (never under 10). One that hits once waits hidden. A new one updates. +void Entity_Laser::carried_laser_update(Entity_Laser& carried, const LaserCarry& carry) +{ + carried.copy_from_parent(*this, LASER_COPY_STATE); + carried.tearFlags &= ~carry.droppedFlags; + carried.pos = carry.position; + carried.set_aim_angle(carry.angle); + if (carry.travelled >= 0) + carried.maxDistance = maxDistance <= 0 ? 0 : std::max(maxDistance - carry.travelled, CARRIED_REACH_MIN); + if (isOneHit) + { + carried.waitFrames = LASER_WAIT_FRAMES; + carried.isVisible = false; + } + if (carried.isFirstUpdate) carried.Update(); } // After splits that met nothing, a missing impact effect is put back, and a giant beam's renewed after a bounce. @@ -1449,34 +1827,176 @@ void Entity_Laser::death_update() Remove(); } -// After the hits: on a hit frame the beam's end (or wherever it was stopped) sets off its tear effects, and Pop and -// Absorb drop a tear there. The split beams of Cricket's Body follow the impact. -void Entity_Laser::ends_update(bool isSamplesRebuilt, bool isHitFrame, bool isRedirected, bool isCut) +// After rebuilding the path: on a hit frame the beam's end (or wherever it was stopped) sets off its tear effects, +// and Pop and Absorb drop a tear there. Cricket's Body splits an impact into two beams across it. +void Entity_Laser::ends_update(bool isHitFrame, bool isRedirected, bool isCut) { - bool isImpact = false; - if (isSamplesRebuilt) + bool isImpact = + std::isfinite(impactDistance) || isGridHit || !(isCut || (parent && parent->type == ENTITY_TEAR)); + if (isHitFrame) { - isImpact = std::isfinite(impactDistance) || isGridHit || !(isCut || (parent && parent->type == ENTITY_TEAR)); - if (isHitFrame && isImpact) impact_tear_flag_effects(impactPosition, impactDirection); + if (isImpact) impact_tear_flag_effects(impactPosition, impactDirection); bool isEnded = std::isfinite(impactDistance) || isGridHit || chainedLasers == 0; bool isPopped = tear_flags_any(activeTearFlags, {TEAR_POP, TEAR_ABSORB}) && !isRedirected && !isGridHit; - if (isHitFrame && isEnded && isPopped) - reconstruction_missing("Entity_Laser::update_laser 00973c60: Pop's and Absorb's tear at the beam's end"); + if (isEnded && isPopped) pop_tear_fire(); } + if (isImpact && activeTearFlags[TEAR_SPLIT] && sub_lasers_update()) return; - if (isImpact && activeTearFlags[TEAR_SPLIT]) - reconstruction_missing("Entity_Laser::update_laser 00973c60: the split beams of Cricket's Body"); for (EntityPtr& split : subLasers) if (split) split->Remove(); subLaserDistance = INFINITY; } -// Past its second frame a beam of a spread fires the next of its chain from its end. +// Pop and Absorb: a piercing tear of the laser's look leaves the beam's end along it, nudged within its width and +// sharing its hits. A thick beam's is a size and speed at random. +void Entity_Laser::pop_tear_fire() +{ + std::vector& samples = homingLaser.samples; + if (samples.size() < 2) return; + + Vector end = samples.back(); + Vector velocity = vector_scale(vector_normalized(vector_sub(end, samples[samples.size() - 2])), POP_TEAR_SPEED); + float tearScale = scale; + if (is_thick_variant()) + { + tearScale *= random_fraction() * POP_TEAR_SCALE_RANGE + POP_TEAR_SCALE_MIN; + velocity = vector_scale(velocity, random_fraction() * POP_TEAR_SPEED_RANGE + POP_TEAR_SPEED_MIN); + } + + TearFlags flags = activeTearFlags; + flags.set(TEAR_PIERCING); + for (int bit : {TEAR_QUADSPLIT, TEAR_SPLIT, TEAR_LUDOVICO, TEAR_BONE_FLAG, TEAR_HYDROBOUNCE, TEAR_LASERSHOT}) + flags.reset((size_t)bit); + bool isAbsorb = activeTearFlags[TEAR_ABSORB]; + uint32_t seed = Random(); + Entity* spawner = spawnerEntity; + Vector nudge = random_direction(); + nudge = vector_scale(nudge, random_fraction()); + nudge = vector_scale(nudge, std::max(size - POP_TEAR_WIDTH_MARGIN, 0.0f)); + Vector position = vector_add(vector_sub(end, vector_scale(velocity, POP_TEAR_BACKSTEP)), nudge); + + Entity_Tear* tear = static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = spawner, + .type = ENTITY_TEAR, + .variant = isAbsorb ? TEAR_HUNGRY : TEAR_EYE, + .seed = seed})); + tear->SetTearFlags(flags); + tear->SetColor(CalculateTearColor(), -1, COLOR_PRIORITY_DEFAULT, false, true); + tear->SetCollisionDamage(collisionDamage); + tear->SetScale(tearScale); + tear->AddEntityFlags(FLAG_NO_SPIKE_DAMAGE); + for (uint32_t hit : hit_list_get()) + { + auto at = std::lower_bound(tear->hitList.begin(), tear->hitList.end(), hit); + if (at == tear->hitList.end() || *at != hit) tear->hitList.insert(at, hit); + } +} + +// Cricket's Body: two beams leave across the beam a little before where it hit, easing along with the hit (or from +// the beam's end when nothing stopped it). Whether they were placed, none when the hit is at the start. +bool Entity_Laser::sub_lasers_update() +{ + Vector position{}; + Vector direction{}; + float angle = 0; + if (!std::isfinite(impactDistance)) + { + subLaserDistance = INFINITY; + get_segment_start_dir(INFINITY, position, direction); + angle = vector_angle(direction); + } + else + { + bool isEased = std::isfinite(subLaserDistance); + subLaserDistance = + isEased ? subLaserDistance + (impactDistance - subLaserDistance) * SUB_LASER_EASE : impactDistance; + if (subLaserDistance <= 0) return false; + + get_segment_start_dir(subLaserDistance, position, direction); + angle = vector_angle(direction); + if (isEased) + angle = angle_approach(subLaserAngle, angle, angle_difference(subLaserAngle, angle) * SUB_LASER_TURN); + } + + subLaserAngle = angle; + position = vector_sub(position, vector_scale(vector_scale(vector_from_angle(angle), SUB_LASER_BACKSTEP), size)); + TearFlags dropped{}; + dropped.set(TEAR_CONTINUUM); + dropped.set(TEAR_BOUNCE); + for (size_t i = 0; i < subLasers.size(); i++) + { + Entity_Laser* split = static_cast(subLasers[i].get()); + if (!split) + { + split = carried_laser_spawn(position, 0); + subLasers[i] = split; + if (!split) continue; + split->scale = scale * SUB_LASER_SCALE; + split->ResetSpriteScale(); + } + float turn = i == 0 ? -RIGHT_ANGLE_DEGREES : RIGHT_ANGLE_DEGREES; + carried_laser_update(*split, {.droppedFlags = dropped, .position = position, .angle = angle + turn}); + } + return true; +} + +// Past its second frame a beam of a spread fires the next of its chain from its end, a bit astray (toward the +// nearest enemy ahead for a homing one), quiet and short, the chain one shorter, with a zap that fades along it. void Entity_Laser::chain_fire() { if (g_game->frameCount - spawnFrame <= 1 || chainedLasers <= 0) return; - if (homingLaser.samples.size() > 1) - reconstruction_missing("Entity_Laser::update_laser 00973c60: the chained beams of a spread"); + + std::vector& samples = homingLaser.samples; + if (samples.size() > 1) + { + Vector start = samples.back(); + Vector direction = vector_normalized(vector_sub(start, samples[samples.size() - 2])); + Vector ahead = vector_scale(direction, CHAIN_SPEED); + Vector astray = random_direction(); + astray = vector_scale(astray, random_fraction() * CHAIN_SCATTER); + Vector velocity = vector_add(ahead, astray); + if (tearFlags[TEAR_HOMING]) + { + float nearest = CHAIN_HOMING_REACH; + Vector target{}; + for (Entity* entity : g_game->room->entityList.updateEL) + { + bool isTarget = entity->IsVulnerableEnemy(nullptr) && + !entity->HasEntityFlags(FLAG_NO_TARGET | FLAG_FRIENDLY) && entity != parent.get(); + if (!isTarget) continue; + + Vector toward = vector_sub(entity->pos, start); + if (vector_dot(direction, toward) <= 0 || vector_length(toward) >= nearest) continue; + nearest = vector_length(toward); + target = entity->pos; + } + if (!vector_is_zero(target)) + velocity = vector_resized(vector_sub(vector_add(velocity, target), start), vector_length(velocity)); + } + + Entity_Laser* chained = ShootAngle({.position = start, + .posOffset = posOffset, + .source = parent, + .angleDegrees = vector_angle(velocity), + .timeout = TECH_LASER_TIMEOUT, + .variant = variant, + .isPoolKept = true}); + if (chained) + { + chained->isDisableFollowParent = true; + chained->copy_from_parent(*this, LASER_COPY_SPAWN); + chained->isDisableInitSound = true; + chained->timeout = TECH_LASER_TIMEOUT; + chained->tearFlags = activeTearFlags; + for (int bit : {TEAR_ORBIT, TEAR_ORBIT_ADVANCED, TEAR_BOOMERANG}) chained->tearFlags.reset((size_t)bit); + chained->parent = parent; + chained->maxDistance = vector_length(velocity); + chained->chainedLasers = chainedLasers - 1; + chained->Update(); + laser_sound_play(SOUND_REDLIGHTNING_ZAP_WEAK, {.volume = (float)chainedLasers * CHAIN_ZAP_VOLUME}); + } + } chainedLasers = 0; } @@ -1554,8 +2074,34 @@ void Entity_Laser::Remove() if (variant == LASER_THICK_RED && spawnerType == SPAWNER_FORSAKEN) g_manager->sfxManager.Stop(SOUND_FORSAKEN_LASER); } -// 0099efc0 Big Spiral's and Ring Worm's path turns are not reconstructed yet. -void Entity_Laser::update_wiggle_path(float, float) +// 0099efc0 Hook Worm and Ring Worm: a line path's samples swing round its line in turns rolling on with the frames, +// over a stretch scaled by the path's length and shortened by the amplitude, easing in over the first 20 samples and +// out over the last 22. +void Entity_Laser::update_wiggle_path(float amplitude, float phase) { - reconstruction_missing("Entity_Laser::update_wiggle_path 0099efc0"); + std::vector& samples = homingLaser.samples; + if (homingLaser.isRing || samples.size() < 2) return; + + float pathScale = vector_distance(homingLaser.origin, homingLaser.endPoint) / WIGGLE_PATH_UNIT; + float roll = (float)g_game->frameCount * WIGGLE_ROLL_SPEED - phase; + float cosine = std::cos(PI_F / 2); + float sine = std::sin(PI_F / 2); + uint32_t count = (uint32_t)samples.size(); + float span = (float)(count - 2); + for (uint32_t i = 0; i + 1 < count; i++) + { + Vector direction = vector_normalized(vector_sub(samples[i + 1], samples[i])); + Vector across = vector_make(direction.x * cosine - sine * direction.y, direction.x * sine + cosine * direction.y); + float edge = 1; + if (i < WIGGLE_EASE_IN) + edge = (float)i / WIGGLE_EASE_IN; + else if (count - WIGGLE_EASE_OUT < i) + edge = (float)(count - i + 1) / WIGGLE_EASE_OUT; + float swing = (1 - (float)std::pow((double)(1 - edge), 2.0)) * WIGGLE_REACH * amplitude; + float angle = (float)i / span * pathScale * WIGGLE_TURNS / amplitude - roll; + float turnSine = std::sin(angle); + float turnCosine = std::cos(angle); + samples[i].x += turnCosine * across.x * swing + turnSine * direction.x * swing; + samples[i].y += turnCosine * across.y * swing + turnSine * direction.y * swing; + } } diff --git a/src/entity_laser.h b/src/entity_laser.h index 99659db..5a2aa63 100644 --- a/src/entity_laser.h +++ b/src/entity_laser.h @@ -73,6 +73,25 @@ struct LaserShot bool isPoolKept = false; }; +// Where a laser carried on from another goes (a wrap, a bounce, a split): its start and angle, the tear flags it +// drops, and how far the beam before it ran (negative to keep its reach). +struct LaserCarry +{ + TearFlags droppedFlags{}; + Vector position{}; + float angle = 0; + float travelled = -1; +}; + +// The two segments segment_intersect crosses: one from a start to an end, the other from a first to a second point. +struct SegmentPair +{ + Vector start{}; + Vector end{}; + Vector first{}; + Vector second{}; +}; + // Construction and destruction (0096cb60, 0096ccf0, 0096cd20) are the defaults. // Field accessors (00435f20, 00435f30, 00456850, 004aaed0, 005cd580, 005cd590, 0060cea0, 0060ceb0, 007e9230, // 007e9240, 0097e3b0, 0097e6e0, 008c5cf7) are the public fields. @@ -177,6 +196,8 @@ struct Entity_Laser : Entity bool damage_grid_entity(int gridIndex, const Vector& direction); void update_line_hits(float damage); void impact_tear_flag_effects(const Vector& position, const Vector& direction); + void impact_explode(const Vector& position, const Vector& direction, float alpha); + void impact_split(const Vector& position, const Vector& direction, float alpha); void update_wiggle_path(float amplitude, float phase); private: @@ -184,8 +205,19 @@ private: void color_cycle_update(); void straight_update(bool& isRedirected); void path_update(bool& isRedirected, bool& isCut); - void path_redirects_update(bool& isRedirected, bool& isCut, bool& isMirrored); - void ends_update(bool isSamplesRebuilt, bool isHitFrame, bool isRedirected, bool isCut); + void blood_drop_spawn(); + void creep_update(); + void multidimensional_update(bool& isRedirected, bool& isCut); + bool mirror_update(bool& isRedirected, bool& isCut); + void mirror_bounce_set(const Vector& position, float angle, Entity* source); + void prism_update(bool& isRedirected, bool& isCut); + void continuum_update(bool& isRedirected, bool& isCut); + void rubber_cement_update(bool isRedirected); + Entity_Laser* carried_laser_spawn(const Vector& position, float angle); + void carried_laser_update(Entity_Laser& carried, const LaserCarry& carry); + void ends_update(bool isHitFrame, bool isRedirected, bool isCut); + void pop_tear_fire(); + bool sub_lasers_update(); void chain_fire(); void death_update(); void splash_spawn(const Vector& center, const Vector& along, float from, float to, Entity& target); @@ -195,4 +227,5 @@ private: }; float angle_difference(float from, float to); +bool segment_intersect(const SegmentPair& segments, Vector& outHit); bool tear_flags_any(const TearFlags& flags, std::initializer_list bits); diff --git a/src/entity_laser_hits.cpp b/src/entity_laser_hits.cpp index dfaaddc..d5c6814 100644 --- a/src/entity_laser_hits.cpp +++ b/src/entity_laser_hits.cpp @@ -1,7 +1,9 @@ #include "boss_ai.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_pickup.h" #include "entity_player.h" @@ -15,11 +17,42 @@ #include "room.h" #include "room_grid.h" #include "sfx_manager.h" +#include "weapon.h" #include #include #include constexpr float LASER_KNOCKBACK = 1.8f; +constexpr float ATTRACTOR_NEAREST_START = 1e6f; +constexpr float ATTRACTOR_REACH_SQUARED = 40000; +constexpr float ATTRACTOR_PULL = 10; +constexpr float ATTRACTOR_ENEMY_PULL = 40; +constexpr float ATTRACTOR_SOFT_RANGE = 100; +constexpr float HIT_SHOT_INTERVAL = 4; +constexpr float HIT_CREEP_MARGIN = 15; +constexpr float HIT_CREEP_SCALE = 0.4f; +constexpr float STICKING_TEAR_SCALE_MIN = 0.01f; +constexpr int CULTIST_STUCK_VARIANT = 10; +constexpr float IMPACT_EXPLOSION_INTERVAL = 4; +constexpr float RING_CONTINUUM_WRAP_MARGIN = -200; +constexpr int RING_CONTINUUM_FRAMES = 45; +constexpr float IMPACT_SPARK_INTERVAL = 2; +constexpr float LUDOVICO_EXPLOSION_AGE = 30; +constexpr float RING_EXPLOSION_AGE = 5; +constexpr float IMPACT_EXPLOSION_RADIUS = 60; +constexpr float IMPACT_EXPLOSION_REACH = 30; +constexpr float IMPACT_EXPLOSION_GROWTH = 10; +constexpr float IMPACT_EXPLOSION_PUSH = 10; +constexpr float IMPACT_EXPLOSION_DAMAGE = 10; +constexpr float IMPACT_SPLIT_HALF_TURN = 3.14f; +constexpr float IMPACT_SPLIT_SPEED = 10; +constexpr float IMPACT_SPLIT_BACKSTEP = 4; +constexpr float IMPACT_SPLIT_HEIGHT = -11.875f; +constexpr float IMPACT_SPLIT_CRAWLSPACE_Y = -18; +constexpr float IMPACT_SPLIT_SCALE = 0.6f; +constexpr float IMPACT_PAIR_STEP = 180; +constexpr float IMPACT_QUAD_STEP = 90; +constexpr float IMPACT_HEX_STEP = 60; constexpr float OWNER_KNOCKBACK_SCALE = 0.2f; constexpr float GROW_RANGE = 1000; constexpr float GROW_GAIN = 5; @@ -334,6 +367,116 @@ void Entity_Laser::splash_spawn(const Vector& center, const Vector& along, float spray->Update(); } +// Strange Attractor: an enemy or a loose pickup (not for sale, not an opened chest) near the beam's path is pulled +// toward the first segment within 200 of it, an enemy (or a versus player) harder, everything gently when nearly on +// it, its friction and speed scaling the pull. +static void attractor_pull(Entity_Laser& laser, Entity& entity) +{ + if (entity.type == ENTITY_PICKUP) + { + Entity_Pickup& pickup = static_cast(entity); + if (pickup.price != 0 || (Entity_Pickup::IsChest(pickup.variant) && pickup.subtype == 0)) return; + } + + std::vector& samples = laser.homingLaser.samples; + float nearest = ATTRACTOR_NEAREST_START; + Vector pull{}; + for (size_t i = 0; i + 1 < samples.size(); i++) + { + SegmentProjection projection = segment_project_point(entity.pos, samples[i], samples[i + 1]); + if (projection.distanceSquared < ATTRACTOR_REACH_SQUARED && projection.distanceSquared < nearest) + { + Vector onPath = vector_add(vector_scale(vector_sub(samples[i + 1], samples[i]), projection.t), samples[i]); + pull = vector_sub(onPath, entity.pos); + nearest = projection.distanceSquared; + } + if (vector_is_zero(pull)) continue; + + float distance = vector_length(pull); + bool isStrong = (g_game->deathmatchManager.is_active() && entity.type == ENTITY_PLAYER) || + (entity.type >= ENTITY_FIRST_ENEMY && entity.type <= ENTITY_LAST_ENEMY); + Vector force = vector_scale(vector_normalized(pull), isStrong ? ATTRACTOR_ENEMY_PULL : ATTRACTOR_PULL); + force = ATTRACTOR_PULL > distance ? vector_scale(force, distance / ATTRACTOR_SOFT_RANGE) + : vector_make(force.x / distance, force.y / distance); + if (entity.friction == 0) return; + entity.velocity.x = force.x * entity.speedMultiplier / entity.friction + entity.velocity.x; + entity.velocity.y = force.y * entity.speedMultiplier / entity.friction + entity.velocity.y; + return; + } +} + +// Mysterious Liquid: a beam's hit leaves a small puddle of green creep there, kept off the walls. +static void hit_creep_spawn(Entity_Laser& laser, const Vector& hit) +{ + Vector position = g_game->room->GetClampedPositionImpl(hit, HIT_CREEP_MARGIN, HIT_CREEP_MARGIN, HIT_CREEP_MARGIN, + HIT_CREEP_MARGIN); + uint32_t seed = Random(); + Entity* creep = g_game->Spawn({.position = position, + .spawner = laser.spawnerEntity, + .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_GREEN, + .seed = seed}); + creep->sprite.scale = vector_make(HIT_CREEP_SCALE, HIT_CREEP_SCALE); + creep->Update(); +} + +// Whether a sticking tear may stick to what the beam hit: a player in a versus match, or an enemy but the fireplaces, +// shopkeepers, movable TNT, poops, props, minecarts and the cultists' tenth variant. +static bool is_stickable(Entity& entity) +{ + if (g_game->deathmatchManager.is_active() && entity.type == ENTITY_PLAYER) return true; + if (entity.type < ENTITY_FIRST_ENEMY || entity.type > ENTITY_LAST_ENEMY) return false; + + switch (entity.type) + { + case ENTITY_FIREPLACE: + case ENTITY_SHOPKEEPER: + case ENTITY_MOVABLE_TNT: + case ENTITY_POOP: + case ENTITY_GENERIC_PROP: + case ENTITY_MINECART: + return false; + case ENTITY_CULTIST: + return entity.variant != CULTIST_STUCK_VARIANT; + default: + return true; + } +} + +// Sticky Bomb's, Booger's and Spore's beams stick a tear of their look into what they hit, at its edge toward the +// hit, with the beam's flags (none that split or come back), damage and scale, touching it at once. +static void sticking_tear_fire(Entity_Laser& laser, Entity& entity, const Vector& hit) +{ + Vector offset = vector_sub(hit, entity.pos); + float distance = vector_length(offset); + if (entity.size < distance && distance > 0) offset = vector_scale(offset, entity.size / distance); + + int tearVariant = TEAR_EXPLOSIVO; + if (laser.tearFlags[TEAR_BOOGER_FLAG]) + tearVariant = TEAR_BOOGER; + else if (laser.tearFlags[TEAR_SPORE_FLAG]) + tearVariant = TEAR_SPORE; + TearFlags flags = laser.tearFlags; + for (int bit : {TEAR_QUADSPLIT, TEAR_SPLIT, TEAR_LUDOVICO, TEAR_BONE_FLAG, TEAR_ABSORB, TEAR_HYDROBOUNCE, + TEAR_LASERSHOT}) + flags.reset((size_t)bit); + + uint32_t seed = Random(); + Entity_Tear* tear = static_cast(g_game->Spawn({.position = vector_add(offset, entity.pos), + .spawner = laser.spawnerEntity, + .type = ENTITY_TEAR, + .variant = tearVariant, + .seed = seed})); + tear->Update(); + tear->SetTearFlags(flags); + tear->SetCollisionDamage(laser.collisionDamage); + float tearScale = std::max(laser.scale, STICKING_TEAR_SCALE_MIN); + tear->baseScale = tearScale; + tear->fScale = tearScale; + tear->ResetSpriteScale(); + Entity::ForceCollide(tear, &entity, true); +} + // 00971810 Hits what the beam crosses, for a damage. A straight beam hits what lies within its width along its // angle and length. A path beam takes the entities it may hurt (with the small critters it kills, the players' // bombs it pushes, and a projectile Lost Contact catches now and then), finds where each crosses its segments, and @@ -386,8 +529,7 @@ void Entity_Laser::update_line_hits(float damage) if (isCandidate) candidates.push_back(entity); bool isPulled = entity->IsVulnerableEnemy(nullptr) || entity->type == ENTITY_PICKUP; - if (tearFlags[TEAR_ATTRACTOR] && isPulled) - reconstruction_missing("Entity_Laser::update_line_hits 00971810: Strange Attractor's pull"); + if (tearFlags[TEAR_ATTRACTOR] && isPulled) attractor_pull(*this, *entity); } const std::vector& samples = homingLaser.samples; @@ -440,10 +582,12 @@ void Entity_Laser::update_line_hits(float damage) impactDirection = direction; } + Vector hit = vector_add(samples[i], vector_scale(direction, length * projection.t - depth)); + if (tearFlags[TEAR_MYSTERIOUS_LIQUID_CREEP] && (isFirstUpdate || GetIntervalTicks(HIT_SHOT_INTERVAL, 0))) + hit_creep_spawn(*this, hit); bool isSticky = tear_flags_any(tearFlags, {TEAR_STICKY, TEAR_BOOGER_FLAG, TEAR_SPORE_FLAG}); - if (tearFlags[TEAR_MYSTERIOUS_LIQUID_CREEP] || (isSticky && !entity->isDead && entity->IsEnemy())) - reconstruction_missing( - "Entity_Laser::update_line_hits 00971810: the creep and sticking tears of a hit"); + bool isStuck = isSticky && is_stickable(*entity) && !entity->isDead; + if (isStuck && (isFirstUpdate || GetIntervalTicks(HIT_SHOT_INTERVAL, 0))) sticking_tear_fire(*this, *entity, hit); float hitDamage = damage; if (!IsCircleLaser()) @@ -473,12 +617,135 @@ void Entity_Laser::update_line_hits(float damage) } } -// 0096d3f0 What the beam's tear flags do where it ends: explosions, split and quad split tears, Rift, Jacob's -// Ladder's arcs. None of them is reconstructed yet. -void Entity_Laser::impact_tear_flag_effects(const Vector&, const Vector&) +// The opacity a remote online player's lasers fade to, by the player at the root of the laser's spawners. +static float laser_shot_alpha_get(Entity_Laser& laser) { - if (tear_flags_any(tearFlags, {TEAR_EXPLOSIVE, TEAR_SPLIT, TEAR_QUADSPLIT, TEAR_RIFT, TEAR_JACOBS})) - reconstruction_missing("Entity_Laser::impact_tear_flag_effects 0096d3f0"); + Entity* root = laser.spawnerEntity ? laser.spawnerEntity->GetLastSpawner() : nullptr; + return shot_alpha_get(root ? root->ToPlayer() : nullptr); +} + +// Ipecac: every fourth tick (a ring only once old enough) the beam's end blows up 10 past it, sized to the beam, +// with its tear effects, a poison splash and a poof in the beam's color. Then it stops exploding. +void Entity_Laser::impact_explode(const Vector& position, const Vector& direction, float alpha) +{ + if (!isFirstUpdate && GetIntervalTicks(IMPACT_EXPLOSION_INTERVAL, 0) == 0) return; + if (subtype == LASER_SUBTYPE_RING_LUDOVICO && updateTime < LUDOVICO_EXPLOSION_AGE) return; + bool isFlyingRing = subtype == LASER_SUBTYPE_RING_PROJECTILE || subtype == LASER_SUBTYPE_RING_FOLLOW_PARENT; + if (isFlyingRing && updateTime < RING_EXPLOSION_AGE) return; + + float radius = scale >= 1 + ? std::max(scale * IMPACT_EXPLOSION_GROWTH + IMPACT_EXPLOSION_REACH, IMPACT_EXPLOSION_RADIUS) + : std::max(scale * IMPACT_EXPLOSION_RADIUS, IMPACT_EXPLOSION_REACH); + float radiusScale = radius / IMPACT_EXPLOSION_RADIUS; + Vector center = vector_add(vector_scale(direction, IMPACT_EXPLOSION_PUSH), position); + explosion_tear_flag_effects({.tearFlags = tearFlags, .position = center, .source = this, .radius = radius}); + explosion_damage({.tearFlags = tearFlags, + .position = center, + .source = this, + .damage = collisionDamage + collisionDamage + IMPACT_EXPLOSION_DAMAGE, + .radius = radius}); + if (tearFlags[TEAR_POISON]) poison_splash_spawn({.position = center, .alpha = alpha, .scale = radiusScale}); + + Entity* blast = + g_game->Spawn({.position = center, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + if (radiusScale != 1) blast->sprite.scale = vector_scale(blast->sprite.scale, radiusScale); + ColorMod color = sprite.color; + color._tint[3] *= alpha; + blast->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + activeTearFlags.reset(TEAR_EXPLOSIVE); +} + +// The Parasite and Cricket's Body tears every fourth tick: two, four (or six for both) piercing tears burst from the +// beam's end at a random angle, evenly round, at half its damage and 60% of its size. Then it stops quad splitting. +void Entity_Laser::impact_split(const Vector& position, const Vector& direction, float alpha) +{ + if (!isFirstUpdate && GetIntervalTicks(IMPACT_EXPLOSION_INTERVAL, 0) == 0) return; + + Vector at = g_game->room->GetClampedPositionImpl(position, 1, 1, 1, 1); + float angle = random_unit() * IMPACT_SPLIT_HALF_TURN; + angle += angle; + Vector velocity = vector_make(std::cos(angle) * IMPACT_SPLIT_SPEED, std::sin(angle) * IMPACT_SPLIT_SPEED); + TearFlags flags = tearFlags; + flags.set(TEAR_PIERCING); + for (int bit : {TEAR_FETUS_FLAG, TEAR_LASERSHOT, TEAR_HYDROBOUNCE, TEAR_ABSORB, TEAR_BONE_FLAG, TEAR_LUDOVICO, + TEAR_SPLIT, TEAR_QUADSPLIT}) + flags.reset((size_t)bit); + ColorMod color = CalculateTearColor(); + color._tint[3] *= alpha; + + int count = 4; + float step = IMPACT_QUAD_STEP; + if (tearFlags[TEAR_SPLIT] && tearFlags[TEAR_QUADSPLIT]) + { + count = 6; + step = IMPACT_HEX_STEP; + } + else if (tearFlags[TEAR_SPLIT]) + { + count = 2; + step = IMPACT_PAIR_STEP; + } + float stepCosine = std::cos(step * DEGREES_TO_RADIANS); + float stepSine = std::sin(step * DEGREES_TO_RADIANS); + for (int i = 0; i < count; i++) + { + uint32_t seed = Random(); + Entity_Tear* tear = static_cast( + g_game->Spawn({.position = vector_sub(at, vector_scale(direction, IMPACT_SPLIT_BACKSTEP)), + .velocity = velocity, + .spawner = spawnerEntity, + .type = ENTITY_TEAR, + .seed = seed})); + tear->height = IMPACT_SPLIT_HEIGHT; + tear->posOffset.y = tear->get_height_offset_y(IMPACT_SPLIT_HEIGHT); + if (g_game->room->roomType == ROOM_DUNGEON) tear->posOffset.y = IMPACT_SPLIT_CRAWLSPACE_Y; + tear->SetTearFlags(flags); + tear->SetCollisionDamage(collisionDamage * 0.5f); + float tearScale = std::max(scale * IMPACT_SPLIT_SCALE, STICKING_TEAR_SCALE_MIN); + tear->baseScale = tearScale; + tear->fScale = tearScale; + tear->ResetSpriteScale(); + tear->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + tear->Update(); + + float turned = velocity.x * stepSine; + velocity.x = velocity.x * stepCosine - velocity.y * stepSine; + velocity.y = velocity.y * stepCosine + turned; + } + activeTearFlags.reset(TEAR_QUADSPLIT); +} + +// 0096d3f0 What the beam's tear flags do where it ends: Ipecac's explosion, the split tears, Jacob's Ladder's chain +// lightning every other tick (at half damage, sharing its hits) and Ocular Rift's rift (once, inside the room). +void Entity_Laser::impact_tear_flag_effects(const Vector& position, const Vector& direction) +{ + float alpha = laser_shot_alpha_get(*this); + if (tearFlags[TEAR_EXPLOSIVE]) impact_explode(position, direction, alpha); + if (tear_flags_any(tearFlags, {TEAR_SPLIT, TEAR_QUADSPLIT})) impact_split(position, direction, alpha); + + if (tearFlags[TEAR_JACOBS] && (isFirstUpdate || GetIntervalTicks(IMPACT_SPARK_INTERVAL, 0))) + { + Entity_Effect* chain = chain_lightning_spawn( + {.tearFlags = tearFlags, .position = position, .spawner = spawnerEntity, .damage = collisionDamage * 0.5f}); + chain->hitList = hitList; + ColorMod color = chain->sprite.color; + color._tint[3] *= alpha; + chain->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + chain->Update(); + } + + bool isRiftFrame = isFirstUpdate || GetIntervalTicks(IMPACT_SPARK_INTERVAL, 0); + if (!tearFlags[TEAR_RIFT] || !isRiftFrame || !g_game->room->IsPositionInRoom(position, RIFT_MARGIN)) return; + + Vector at = g_game->room->GetClampedPositionImpl(position, 0, 0, 0, 0); + Entity_Effect& rift = *static_cast(g_game->Spawn( + {.position = at, .spawner = spawnerEntity, .type = ENTITY_EFFECT, .variant = EFFECT_RIFT, .seed = Random()})); + rift.sprite.scale = vector_make(scale, scale); + rift.SetCollisionDamage(collisionDamage * 0.5f); + rift.SetTimeout(g_game->deathmatchManager.is_active() ? RIFT_VERSUS_FRAMES : RIFT_FRAMES); + rift.Update(); + activeTearFlags.reset(TEAR_RIFT); + effect_sound_play(SOUND_OCCULAR_RIFT_PORTAL); } // How a ring's radius changes with its tear flags and age, before it is drawn: pulsing, growing or shrinking with the @@ -599,7 +866,13 @@ void Entity_Laser::UpdateHits() } } else if (!tearFlags[TEAR_CONTINUUM]) pos = g_game->room->GetClampedPosition(pos, radiusNow); - else if (!isInterpolating) reconstruction_missing("Entity_Laser::UpdateHits 0097baa0: Continuum's ring wrapping"); + else if (!isInterpolating) + { + Vector unwrapped = pos; + pos = room_screen_wrap(pos, RING_CONTINUUM_WRAP_MARGIN); + bool isWrapped = pos.x != unwrapped.x || pos.y != unwrapped.y; + if (isWrapped && subtype == LASER_SUBTYPE_RING_PROJECTILE && timeout == 0) timeout = RING_CONTINUUM_FRAMES; + } if ((variant == LASER_THIN_RED || variant == LASER_ELECTRIC) && child) { diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index 8582e8a..d11e2ee 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -3,6 +3,7 @@ #include "active_items.h" #include "boss_ai.h" #include "boss_death.h" +#include "boss_final.h" #include "entity_bomb.h" #include "entity_config.h" #include "entity_effect.h" @@ -27,6 +28,7 @@ #include "room_config.h" #include "room_descriptor.h" #include "room_grid.h" +#include "room_render.h" #include "sfx_manager.h" #include "menu_manager.h" #include "mines.h" @@ -232,8 +234,6 @@ constexpr float CHAMPION_CHANCE_VICTORY_LAP = 0.25f; constexpr float CHAMPION_CHANCE_PURPLE_HEART = 3; constexpr unsigned int STATUS_SHARED = 1u << 31; -// Dogma and the generic prop's TV (960.4) draw with the static shader. -constexpr int GENERIC_PROP_TV = 4; constexpr std::string_view STATUS_EFFECTS_ANM2 = "gfx/StatusEffects.anm2"; // The target search: how far enemies look for players, and what pushes a player back or pulls a twin forward. @@ -244,6 +244,11 @@ constexpr float TWIN_NEAR_SQUARED = 10000; constexpr float BULB_CHARGE_BASE = 10000; constexpr float BULB_CHARGE_STEP = 2000; constexpr float BULB_DISTANCE_SCALE = 0.001f; +constexpr float BAIT_REACH = 500; +constexpr float BAITED_DISTANCE_SCALE = 1e-05f; +constexpr float PUPPY_SMALL_PREY_SCALE = 0.5f; +constexpr float PUPPY_BISHOP_SCALE = 0.01f; +constexpr float PUPPY_KIN_PENALTY = 250000; constexpr int TARGET_REFRESH_FRAMES = 15; constexpr int DECOY_TIMER_MAX = 180; @@ -405,7 +410,7 @@ static int active_charges_get(Entity_Player& player) } // What a target counts as from a position: its squared distance, pushed back while its player is invincible or (for -// Baby Plum) without control, pulled to a twin walking into the other, and for Bulb led by the active charge it holds. +// the Blood Puppy) without control, pulled to a twin walking into the other, and for Bulb led by the active charge it holds. static float target_score_get(const Vector& position, Entity* source, Entity& target, Entity_Player* player, bool isBulb) { @@ -414,7 +419,7 @@ static float target_score_get(const Vector& position, Entity* source, Entity& ta Entity_Player* twin = player->twin_get(); if (player->HasInvincibility(0, EntityRef())) distance += TARGET_INVINCIBLE_PENALTY; - else if ((!player->isControlsEnabled || player->controlsCooldown > 0) && source && source->type == ENTITY_BABY_PLUM) + else if ((!player->isControlsEnabled || player->controlsCooldown > 0) && source && source->type == ENTITY_BLOOD_PUPPY) distance += TARGET_UNCONTROLLED_PENALTY; else if (twin) { @@ -429,8 +434,28 @@ static float target_score_get(const Vector& position, Entity* source, Entity& ta return distance * BULB_DISTANCE_SCALE + priority; } +// Whether a player found among the enemies is one a friendly source spares. The original reads the source's flags +// even without one, which this skips. +static bool prey_is_friendly(Entity* candidate, Entity* source) +{ + return candidate->type == ENTITY_PLAYER && source && source->HasEntityFlags(FLAG_FRIENDLY) && + source->IsDamageSourceFriendly(EntityRef(candidate)); +} + +// Whether the hunting enemies (the Blood Puppy, the level 2 Willo) may hunt it: a player in deathmatch, or an enemy +// that is not a fire, shopkeeper, TNT, prop, minecart, poop or the Cultist's blood pool. +bool entity_is_prey(Entity& prey) +{ + if (prey.type == ENTITY_PLAYER) return g_game->deathmatchManager.is_active(); + if (!Entity::is_enemy_type(prey.type) || prey.type == ENTITY_FIREPLACE || prey.type == ENTITY_SHOPKEEPER || prey.type == ENTITY_MOVABLE_TNT) + return false; + if (prey.type == ENTITY_CULTIST) return prey.variant != CULTIST_POOL; + return prey.type != ENTITY_GENERIC_PROP && prey.type != ENTITY_MINECART && prey.type != ENTITY_POOP; +} + // 007069a0 What an enemy at a position goes after: the nearest visible player within reach (Dark Esau only Jacob), -// else a Punching Bag or a baited enemy. An enemy forced onto a target keeps it. +// else a Punching Bag, then a baited enemy, or for the Blood Puppy its nearest prey. An enemy forced onto a target keeps +// it. Isaac's Heart stands in for its player. // The stand-in target a player keeps at Entity_Player 0x144c waits for Entity_Player to name it. Entity* game_nearest_target_player(const Vector& position, Entity* source, bool isPlayersOnly, bool isTargetDecoys, float maxDistance) @@ -464,8 +489,8 @@ Entity* game_nearest_target_player(const Vector& position, Entity* source, bool bool isJacob = candidate->playerType == PLAYER_JACOB || candidate->playerType == PLAYER_JACOB_B || candidate->playerType == PLAYER_JACOB2_B; if (source && source->type == ENTITY_DARK_ESAU && !isJacob) continue; - if (target->type == ENTITY_FAMILIAR) - reconstruction_missing("Game::GetNearestTargetPlayer 007069a0: a familiar standing in for its player"); + if (target->type == ENTITY_FAMILIAR && target->variant == Entity_Familiar::ISAACS_HEART) + player = static_cast(target)->player; if (player && player->IsInvisible()) continue; float score = target_score_get(position, source, *target, player, isBulb); @@ -473,9 +498,7 @@ Entity* game_nearest_target_player(const Vector& position, Entity* source, bool best = score; nearest = target; } - if (isPlayersOnly) return nearest; - - if (isTargetDecoys) + if (!isPlayersOnly && isTargetDecoys) { for (Entity* decoy : g_game->room->entityList.mainEL) { @@ -486,10 +509,38 @@ Entity* game_nearest_target_player(const Vector& position, Entity* source, bool nearest = decoy; } } - if (g_game->room->entityList.isAnyBaited) - reconstruction_missing("Game::GetNearestTargetPlayer 007069a0: the baited enemies that draw attacks"); - if (source && source->type == ENTITY_BLOOD_PUPPY) - reconstruction_missing("Game::GetNearestTargetPlayer 007069a0: the Blood Puppy's prey"); + if (!isPlayersOnly && g_game->room->entityList.isAnyBaited) + { + for (Entity* baited : entity_query_radius(position, std::min(maxDistance, BAIT_REACH), QUERY_ENEMIES)) + { + if (prey_is_friendly(baited, source) || baited->isDead || !baited->HasEntityFlags(FLAG_BAITED)) continue; + if (!source || !source->IsValidTarget(baited)) continue; + float distance = vector_length_squared(vector_sub(baited->pos, position)) * BAITED_DISTANCE_SCALE; + if (distance >= best) continue; + best = distance; + nearest = baited; + } + return nearest; + } + if (!source || source->type != ENTITY_BLOOD_PUPPY) return nearest; + + float preyScale = source->variant == 0 ? PUPPY_SMALL_PREY_SCALE : 1; + for (Entity* prey : entity_query_radius(position, std::min(maxDistance, BAIT_REACH), QUERY_ENEMIES)) + { + if (prey_is_friendly(prey, source) || prey->isDead || prey == source) continue; + if (g_game->frameCount - prey->spawnFrame <= 1 || !prey->IsVulnerableEnemy(nullptr) || !entity_is_prey(*prey)) + continue; + if (prey->HasEntityFlags(FLAG_NO_TARGET)) continue; + + float distance = vector_length_squared(vector_sub(prey->pos, position)); + bool isFriendly = prey->HasEntityFlags(FLAG_FRIENDLY); + if (prey->type == ENTITY_BISHOP && !isFriendly) distance *= PUPPY_BISHOP_SCALE; + if (prey->type == ENTITY_BLOOD_PUPPY) distance += PUPPY_KIN_PENALTY; + if (!isFriendly) distance *= preyScale; + if (distance >= best) continue; + best = distance; + nearest = prey; + } return nearest; } @@ -882,7 +933,7 @@ void Entity_NPC::load_graphics(bool isReloadAnm2) } sprite.championColor = isChampionSheetUsed && championLook ? *championLook : ColorMod{}; - bool isStatic = type == ENTITY_DOGMA || (type == ENTITY_GENERIC_PROP && variant == GENERIC_PROP_TV); + bool isStatic = type == ENTITY_DOGMA || (type == ENTITY_GENERIC_PROP && variant == PROP_TV); sprite.bitflags &= ~ANIM_RENDER_STATIC; if (isStatic) sprite.bitflags |= ANIM_RENDER_STATIC; sprite.LoadGraphics(); @@ -1590,30 +1641,79 @@ void Entity_NPC::toxic_shock_creep_spawn() creep->Update(); } -// Part of 006c4b30: the items whose aura works on enemies near a player: Super Magnet's nearest holder pulls the -// enemy in one frame in three. The Soul's push and Salvation's beam stop the game until reached. +// Part of 006c4b30: the items whose aura works on enemies near a player, each from its nearest holder. The Soul pushes +// the enemy off within 80 one frame in three. Super Magnet pulls it in one frame in three. Salvation's beam locks +// onto it within reach of its halo. void Entity_NPC::player_aura_update() { - constexpr float SUPER_MAGNET_REACH_SQUARED = 1e9f; + constexpr float SOUL_PUSH_REACH = 80; + constexpr float SOUL_PUSH_SHARE = 0.1f; + constexpr float SOUL_SPEED_SHARE = 0.2f; + constexpr float SOUL_PUSH_BASE = 0.05f; + constexpr float AURA_REACH_SQUARED = 1e9f; constexpr float SUPER_MAGNET_PULL = 0.5f; - constexpr int SUPER_MAGNET_ODDS = 3; + constexpr int AURA_ODDS = 3; + constexpr float SALVATION_HALO_RADIUS = 70; + constexpr int SALVATION_BEAM_SUBTYPE = 3; + constexpr float SALVATION_BEAM_DAMAGE = 3.5f; if (state == NPC_STATE_DEATH || state == NPC_STATE_UNIQUE_DEATH || IsFriendly() || !IsVulnerableEnemy(nullptr)) return; + Entity_Player* soul = nullptr; Entity_Player* magnet = nullptr; - float magnetDistance = SUPER_MAGNET_REACH_SQUARED; + Entity_Player* salvation = nullptr; + float soulDistance = SOUL_PUSH_REACH * SOUL_PUSH_REACH; + float magnetDistance = AURA_REACH_SQUARED; + float salvationDistance = AURA_REACH_SQUARED; for (Entity_Player* player : g_game->playerManager.playerList) { - if (player->HasCollectible(COLLECTIBLE_SOUL_ID) || player->HasCollectible(COLLECTIBLE_SALVATION_ID)) - reconstruction_missing("Entity_NPC::Update 006c4b30: The Soul's push and Salvation's beam"); - if (!player->HasTrinket(TRINKET_SUPER_MAGNET_ID)) continue; - Vector away = vector_sub(player->pos, pos); - float distance = away.x * away.x + away.y * away.y; - if (distance >= magnetDistance) continue; - magnet = player; - magnetDistance = distance; + bool isSoul = player->HasCollectible(COLLECTIBLE_SOUL_ID); + bool isMagnet = player->HasTrinket(TRINKET_SUPER_MAGNET_ID); + bool isSalvation = player->HasCollectible(COLLECTIBLE_SALVATION_ID); + if (!isSoul && !isMagnet && !isSalvation) continue; + + float distance = vector_length_squared(vector_sub(player->pos, pos)); + if (isSoul && distance < soulDistance) + { + soul = player; + soulDistance = distance; + } + if (isMagnet && distance < magnetDistance) + { + magnet = player; + magnetDistance = distance; + } + if (!isSalvation || distance >= salvationDistance) continue; + float haloReach = player->get_salvation_scale() * SALVATION_HALO_RADIUS + size; + if (distance >= haloReach * haloReach) continue; + salvation = player; + salvationDistance = distance; } - if (magnet && random_below(SUPER_MAGNET_ODDS) == 0) velocity = vector_add(velocity, vector_resized(vector_sub(magnet->pos, pos), SUPER_MAGNET_PULL)); + + if (soul && random_below(AURA_ODDS) == 0) + { + float push = random_unit() * (SOUL_PUSH_REACH - std::sqrt(soulDistance)) * SOUL_PUSH_SHARE; + float strength = vector_length(velocity) * push * SOUL_SPEED_SHARE + SOUL_PUSH_BASE; + velocity = vector_add(velocity, vector_resized(vector_sub(pos, soul->pos), strength)); + } + if (magnet && random_below(AURA_ODDS) == 0) velocity = vector_add(velocity, vector_resized(vector_sub(magnet->pos, pos), SUPER_MAGNET_PULL)); + if (!salvation) return; + + if (!salvationTarget) + { + Entity* beam = g_game->Spawn({.position = pos, + .spawner = salvation, + .subType = SALVATION_BEAM_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_CRACK_THE_SKY, + .seed = Random()}); + beam->target = this; + beam->parent = salvation; + beam->SetCollisionDamage(SALVATION_BEAM_DAMAGE); + beam->Update(); + salvationTarget = beam; + } + if (salvationTarget) static_cast(salvationTarget.get())->state = 1; } // Whether Lighter or Ice Cube catches an enemy entering the room: a fifth, a third or a half by strength, more with @@ -1805,8 +1905,7 @@ void Entity_NPC::Update() spawn_damage_numbers(); update_damage_history(); if (aiCallFlags & AI_CALL_PRE_UPDATE) ai_call(AI_PHASE_PRE_UPDATE); - if (HasEntityFlags(FLAG_PERSISTENT | FLAG_FRIENDLY_BALL_DYING)) - reconstruction_missing("Entity_NPC::Update 006c4b30: a captured enemy wasting away"); + if (HasEntityFlags(FLAG_PERSISTENT | FLAG_FRIENDLY_BALL_DYING)) captured_update(); float healthBefore = health; if (type == ENTITY_MINECART) update_physics(); @@ -1838,6 +1937,153 @@ void Entity_NPC::Update() forced_target_update(); } +// Part of 006c4b30: an enemy captured in a Friendly Ball (or dying out of one) wastes a quarter of health every 15 +// frames down to 1, greying and shrinking with it. A hit this frame that is not fire, spikes or poop passes on as 1 +// damage from its biggest hit, or as 5 from an explosion. +// The shrink is lost at once, as the frame's scale reset (FUN_006d6650) overwrites it. +void Entity_NPC::captured_update() +{ + constexpr int WASTE_FRAMES = 15; + constexpr float WASTE_STEP = 0.25f; + constexpr float WASTE_LEAST_TINT = 0.6f; + constexpr float WASTE_LEAST_SCALE = 0.6f; + constexpr float WASTE_MOST_SCALE = 1.1f; + constexpr float CAPTURED_HIT_DAMAGE = 1; + constexpr float CAPTURED_BLAST_DAMAGE = 5; + constexpr uint64_t UNFELT_DAMAGE = DAMAGE_FIRE | DAMAGE_SPIKES | DAMAGE_POOP; + if (IsFrame(WASTE_FRAMES, 0) && health > 1) health = std::max(health - WASTE_STEP, 1.0f); + + float tint = std::lerp(WASTE_LEAST_TINT, 1.0f, std::clamp(health * health / (maxHitPoints * maxHitPoints), 0.0f, 1.0f)); + std::fill_n(sprite.color._tint, 3, tint); + sprite.color._tint[3] = 1; + float shrink = std::lerp(WASTE_LEAST_SCALE, WASTE_MOST_SCALE, std::clamp(health / maxHitPoints, 0.0f, 1.0f)); + sprite.scale = vector_make(shrink, shrink); + + const DamageEvent* felt = nullptr; + float feltDamage = 0; + float biggest = 0; + for (const DamageEvent& event : damageEvents) + { + if (event.damageFlags & UNFELT_DAMAGE) continue; + if (event.damageFlags & DAMAGE_EXPLOSION) + { + felt = &event; + feltDamage = CAPTURED_BLAST_DAMAGE; + break; + } + if (event.damage <= biggest) continue; + felt = &event; + feltDamage = CAPTURED_HIT_DAMAGE; + biggest = event.damage; + } + if (felt) TakeDamage(feltDamage, felt->damageFlags, felt->source, 0); +} + +// The camouflage seeds: an enemy takes on the floor under it, sampled on its first frames and every 30 after, and +// blends a tenth of the way toward it each frame, nearly black underneath. +void Entity_NPC::camouflage_update() +{ + constexpr float CAMO_ALPHA = 0.7f; + constexpr float CAMO_FLOOR_TONE = 0.9f; + constexpr float CAMO_ALPHA_BLEND = 0.3f; + constexpr float CAMO_FLOOR_BLEND = 0.5f; + constexpr float CAMO_SPRITE_BLEND = 0.1f; + constexpr float CAMO_DARKNESS = 0.02f; + constexpr int CAMO_RESAMPLE_FRAMES = 30; + constexpr int CAMO_SAMPLE_WINDOW = 2; + Room& room = *g_game->room; + if (FrameCount() < CAMO_SAMPLE_WINDOW) + { + KColor floor = room_floor_texel_get(room, pos); + const float shares[] = {floor._red, floor._green, floor._blue}; + std::fill_n(floorColor._tint, 3, 0.0f); + floorColor._tint[3] = CAMO_ALPHA; + for (int i = 0; i < 3; i++) floorColor._offset[i] = shares[i] * CAMO_FLOOR_TONE; + sprite.color = floorColor; + } + if ((uint32_t)(g_game->frameCount + index) % CAMO_RESAMPLE_FRAMES < CAMO_SAMPLE_WINDOW) + { + KColor floor = room_floor_texel_get(room, pos); + floorColor._tint[3] = std::lerp(floorColor._tint[3], CAMO_ALPHA, CAMO_ALPHA_BLEND); + const float shares[] = {floor._red, floor._green, floor._blue}; + for (int i = 0; i < 3; i++) + floorColor._offset[i] = std::lerp(floorColor._offset[i], shares[i] * CAMO_FLOOR_TONE, CAMO_FLOOR_BLEND); + } + ColorMod blended = color_lerp(sprite.color, floorColor, CAMO_SPRITE_BLEND); + std::fill_n(blended._tint, 3, CAMO_DARKNESS); + blended._tint[3] = 1; + sprite.color = blended; +} + +// The pacifist seed and the quick kill debug mode drain every enemy by 1/900 of its health a frame, faster for the +// split bosses, Satan, Mega Satan's fight and outside boss rooms, and a hundred times faster in quick kill. The pacifist +// seed makes them invincible. Outside quick kill only bosses drain, and the doors open once no boss is left. A drained +// boss dies with a hit, except those whose death waits on their partners, which give up holding the doors instead. +void Entity_NPC::quick_kill_update() +{ + constexpr float DRAIN_SECONDS = 30; + constexpr float SPLIT_DRAIN_SCALE = 3; + constexpr float MEGA_SATAN_ROOM_DRAIN_SCALE = 4; + constexpr float MEGA_SATAN_DRAIN_SCALE = 0.33333f; + constexpr float BOSS_RUSH_DRAIN_SCALE = 2; + constexpr float MINIBOSS_DRAIN_SCALE = 3; + constexpr float ROOM_DRAIN_SCALE = 6; + constexpr float QUICK_KILL_DRAIN_SCALE = 100; + constexpr int QUICK_KILL_COUNTDOWN = 30; + Room& room = *g_game->room; + bool isQuickKill = g_game->debugFlags & DEBUG_QUICK_KILL; + bool isBlastocyst = type == ENTITY_BLASTOCYST_BIG || type == ENTITY_BLASTOCYST_MEDIUM || type == ENTITY_BLASTOCYST_SMALL; + bool isSplitBoss = type == ENTITY_FISTULA_BIG || type == ENTITY_FISTULA_MEDIUM || type == ENTITY_FISTULA_SMALL || + isBlastocyst || (type == ENTITY_THE_HAUNT && variant == HAUNT_LIL_VARIANT); + bool isSatanFight = type == ENTITY_FALLEN && room.bossId == BOSS_SATAN; + bool isMegaSatan = type == ENTITY_MEGA_SATAN || type == ENTITY_MEGA_SATAN_2; + float drain = maxHitPoints / DRAIN_SECONDS / DRAIN_SECONDS; + if (g_game->seedEffects.HasSeedEffect(SEED_PACIFIST)) isInvincible = true; + + if (isSplitBoss || isSatanFight) drain *= SPLIT_DRAIN_SCALE; + else if (isMegaSatan) drain = isInvincible ? 0 : drain * MEGA_SATAN_DRAIN_SCALE; + else if (room.bossId == BOSS_MEGA_SATAN) drain *= MEGA_SATAN_ROOM_DRAIN_SCALE; + if (room.roomType == ROOM_BOSSRUSH) drain *= BOSS_RUSH_DRAIN_SCALE; + else if (room.roomType == ROOM_MINIBOSS) drain *= MINIBOSS_DRAIN_SCALE; + else if (room.roomType != ROOM_BOSS) drain *= ROOM_DRAIN_SCALE; + if (isQuickKill) drain *= QUICK_KILL_DRAIN_SCALE; + + if (!IsBoss() && !isQuickKill) + { + if (room.GetAliveBossesCount() < 1) isCanShutDoors = false; + return; + } + if (isBlastocyst) + { + if (health > 0 || entityCollisionClass == ENTCOLL_NONE) health -= drain; + else + { + isInvincible = false; + health = 1; + isDead = true; + } + return; + } + if (health > 0) + { + health -= drain; + return; + } + + bool isHeldOn = type == ENTITY_GURDY || type == ENTITY_MEGA_MAW || type == ENTITY_GATE || type == ENTITY_MOMS_HEART || + type == ENTITY_FISTULA_BIG || type == ENTITY_FISTULA_MEDIUM || type == ENTITY_FISTULA_SMALL || + (type == ENTITY_THE_HAUNT && variant == HAUNT_LIL_VARIANT); + bool isKilled = isQuickKill || isHeldOn || room.roomType == ROOM_BOSSRUSH || room.bossId == BOSS_MEGA_SATAN || isSatanFight; + if (!isKilled) + { + isCanShutDoors = false; + return; + } + isInvincible = false; + TakeDamage(1, 0, EntityRef(), QUICK_KILL_COUNTDOWN); + isDead = true; +} + // Part of 006c4b30: the seeds and the debug mode that change every enemy: invisible enemies, camouflage, and the // pacifist seed and quick kill that make them waste away. void Entity_NPC::seed_effects_update() @@ -1849,11 +2095,9 @@ void Entity_NPC::seed_effects_update() sprite.color = COLOR_INVISIBLE; shadowSize = 0; } - if (seeds.HasSeedEffect(SEED_CAMO_ENEMIES) || seeds.HasSeedEffect(SEED_CAMO_EVERYTHING)) - reconstruction_missing("Entity_NPC::Update 006c4b30: the camouflage seeds"); + if (seeds.HasSeedEffect(SEED_CAMO_ENEMIES) || seeds.HasSeedEffect(SEED_CAMO_EVERYTHING)) camouflage_update(); bool isQuickKill = seeds.HasSeedEffect(SEED_PACIFIST) || (g_game->debugFlags & DEBUG_QUICK_KILL); - if (isQuickKill && IsActiveEnemy(DEAD_EXCLUDED)) - reconstruction_missing("Entity_NPC::Update 006c4b30: the pacifist seed and quick kill debug mode"); + if (isQuickKill && IsActiveEnemy(DEAD_EXCLUDED)) quick_kill_update(); } // Part of 006c4b30: the few enemies with their own per-frame step: Hornfel, Gideon's camera, the Heart's partner and @@ -1911,6 +2155,32 @@ float Entity_NPC::compute_speed_multiplier() return speed; } +// Part of 006d60a0: Betrayal turns an enemy on the nearest enemy up its attacker's parent line, for 150 frames, unless +// it is the same body, newborn or not vulnerable. One already set on another target switches only one hit in four. A +// switch it survives shows an angry heart over it. +void Entity_NPC::betrayal_turn(Entity* attacker) +{ + constexpr int BETRAYAL_FRAMES = 150; + constexpr uint32_t BETRAYAL_SWITCH_MASK = 3; + constexpr int BETRAYAL_HEART_SUBTYPE = 2; + constexpr float BETRAYAL_HEART_LIFT = -24; + for (; attacker; attacker = attacker->parent) + { + if (!Entity::is_enemy_type(attacker->type)) continue; + if (attacker == this || attacker->GetStatusEffectTarget() == GetStatusEffectTarget()) return; + if (g_game->frameCount - attacker->spawnFrame <= 0 || !attacker->IsVulnerableEnemy(nullptr)) return; + Entity* previous = forcedTarget; + if (previous && previous != attacker && (Random() & BETRAYAL_SWITCH_MASK) != 0) return; + if (!TryForceTarget(attacker, BETRAYAL_FRAMES) || previous == attacker || pendingDamage >= health) return; + + Entity* heart = g_game->Spawn({.position = pos, .subType = BETRAYAL_HEART_SUBTYPE, .type = ENTITY_EFFECT, + .variant = EFFECT_HEART, .seed = Random()}); + heart->sprite.offset = vector_make(0, BETRAYAL_HEART_LIFT); + heart->renderDepthOffset = 1; + return; + } +} + // 006d60a0 Takes a hit as any entity (Entity::TakeDamage) and lets the items that react to it act: a player's hit // ends Pacifist, Betrayal turns it on its attacker, the pulsing champion spawns its flies, and a hit taken spawns // a blue fly for a hit that spawns one, marks a player's kill for Jar of Flies, and triggers the attacker's @@ -1923,8 +2193,7 @@ bool Entity_NPC::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& if (!IsFriendly() && isPlayerSource) g_game->room->isPacifist = false; PlayerManager& players = g_game->playerManager; - if (source.entity && players.FirstCollectibleOwner(COLLECTIBLE_BETRAYAL_ID, LAZARUS_SHARE_CHECK)) - reconstruction_missing("Entity_NPC::TakeDamage 006d60a0: Betrayal"); + if (source.entity && players.FirstCollectibleOwner(COLLECTIBLE_BETRAYAL_ID, LAZARUS_SHARE_CHECK)) betrayal_turn(source.entity); if (players.FirstCollectibleOwner(COLLECTIBLE_JAR_OF_FLIES, LAZARUS_SHARE_CHECK)) { bool isBlueFly = source.type == ENTITY_FAMILIAR && source.variant == Entity_Familiar::BLUE_FLY; @@ -2463,11 +2732,35 @@ void Entity_NPC::status_overlay_render(const Vector& offset) statusEffectSprite.Render(SpriteDraw{at, {}, {}}); } -// 006d90e0 Moves the effect a controlled enemy aims with along the controller's input and keeps it in reach. -void Entity_NPC::UpdateChildEffectPosition(bool) +// 006d90e0 Moves the effect a controlled enemy aims with along the controller's input and keeps it in reach. A target +// effect in mode 2 sits on the enemy (half a step ahead when predicting), one in another mode follows the aim input, +// and anything else the movement input. A target effect with a reach (its rotation) is pulled back within 40 of it. +void Entity_NPC::UpdateChildEffectPosition(bool isPredictMovement) { + constexpr int AIM_MODE_SELF = 2; + constexpr float AIM_SPEED = 8; + constexpr float AIM_REACH_MARGIN = 40; + constexpr float AIM_REACH_PULL = 0.1f; if (controllerID == -1 || !aimTargetEffect) return; - reconstruction_missing("Entity_NPC::UpdateChildEffectPosition 006d90e0"); + + Entity* aim = aimTargetEffect; + int mode = aim->type == ENTITY_EFFECT ? (int)static_cast(aim)->varData[2] : 0; + if (aim->type == ENTITY_EFFECT && mode == AIM_MODE_SELF) + { + aim->pos = isPredictMovement ? vector_add(prevPosition, vector_scale(prevVelocity, HALF * speedMultiplier)) : prevPosition; + aim->velocity = {}; + return; + } + + Vector input = aim->type == ENTITY_EFFECT && mode != 0 ? GetControllerInput(0) : GetControllerMovementInput(0); + if (!vector_is_zero(input)) aim->velocity = vector_add(aim->velocity, vector_scale(input, AIM_SPEED)); + float reach = aim->type == ENTITY_EFFECT ? static_cast(aim)->rotation : 0; + if (reach <= 0) return; + + float limit = std::max(reach - AIM_REACH_MARGIN, 0.0f); + Vector back = vector_sub(pos, aim->pos); + float distance = vector_length(back); + if (distance > limit) aim->velocity = vector_add(aim->velocity, vector_scale(back, (distance - limit) / distance * AIM_REACH_PULL)); } // 006d7010 With Spider Mod, shows the damage each hit of this frame dealt it as a rising number. @@ -2852,18 +3145,6 @@ bool Entity_NPC::TryThrow(const EntityRef& source, const Vector& throwVelocity, return true; } -// 004b92e0 -void Entity_NPC::Hornfel_UpdateAI() -{ - reconstruction_missing("Entity_NPC::Hornfel_UpdateAI 004b92e0"); -} - -// 004bb0e0 -void Entity_NPC::Hornfel_UpdateFrame() -{ - reconstruction_missing("Entity_NPC::Hornfel_UpdateFrame 004bb0e0"); -} - // 006be760 Kills it with no source into its own death animation (Flush! and Lua's KillUnique). void Entity_NPC::KillUnique() { @@ -3016,16 +3297,10 @@ void Entity_NPC::update_frozen() } } -// 006d0c60 -void* Entity_NPC::QueryNPCsType(void*, int, int) +// 006d0c60 The room's entities of a type, and of a variant unless -1. +std::vector Entity_NPC::QueryNPCsType(int type, int variant) { - reconstruction_missing("Entity_NPC::QueryNPCsType 006d0c60"); -} - -// 006d1580 -void* Entity_NPC::fireplace_get_loot(void*, bool) -{ - reconstruction_missing("Entity_NPC::fireplace_get_loot 006d1580"); + return entity_query(type, variant); } // 006d4db0 Whether a reroll may turn it into another enemy: not when its tags forbid it, for a Lil Haunt still tied @@ -3092,20 +3367,247 @@ void Entity_NPC::UpdateChargeBar(float start, float end, float value, bool isHid chargeBarSprite.color._tint[3] = 0; } -// 006d97e0 -uint8_t Entity_NPC::split(float, const EntityRef&, bool) +// The bosses a split would kill outright instead, and the ones it only hurts. +static bool split_is_killed(Entity_NPC& npc) { - reconstruction_missing("Entity_NPC::split 006d97e0"); + switch (npc.type) + { + case ENTITY_DINGA: + case ENTITY_SQUIRT: + case ENTITY_MEMBRAIN: + case ENTITY_MOTER: + case ENTITY_BIG_SPIDER: + case ENTITY_FISTULA_BIG: + case ENTITY_FISTULA_MEDIUM: + case ENTITY_FISTULA_SMALL: + case ENTITY_BLASTOCYST_BIG: + case ENTITY_BLASTOCYST_MEDIUM: + case ENTITY_BLASTOCYST_SMALL: + case ENTITY_ENVY: + return true; + default: + return npc.championColorIdx == CHAMPION_PULSE_GREEN; + } +} + +static bool split_is_unsplittable(Entity_NPC& npc) +{ + switch (npc.type) + { + case ENTITY_MOM: + return npc.variant != MOM_STOMP; + case ENTITY_VISAGE: + return npc.variant == 0 || npc.variant == 1; + case ENTITY_MOMS_HEART: + case ENTITY_SATAN: + case ENTITY_MEGA_SATAN: + case ENTITY_MEGA_SATAN_2: + case ENTITY_ISAAC: + case ENTITY_THE_LAMB: + case ENTITY_MAMA_GURDY: + case ENTITY_DADDYLONGLEGS: + case ENTITY_PIN: + case ENTITY_ROTGUT: + case ENTITY_MOTHER: + case ENTITY_HUSH: + case ENTITY_ULTRA_GREED: + case ENTITY_DOGMA: + case ENTITY_BEAST: + return true; + default: + return false; + } +} + +// Whether a split's halves stand side by side (left and right) rather than at random about it. +static bool split_is_side_by_side(Entity_NPC& npc) +{ + if (npc.type == ENTITY_THE_HAUNT || npc.type == ENTITY_LOKI) return npc.variant == 0; + return npc.type == ENTITY_GURDY || npc.type == ENTITY_MEGA_MAW || npc.type == ENTITY_GATE; +} + +// Hands the children of the split boss over to a half: the Lil Haunts, Peep's eyes, Gemini's twins (whose cords go) +// and Mom's parts, which heal. +static void split_half_link(Entity_NPC& npc, Entity_NPC& half, int halfIndex, Entity_NPC* first) +{ + auto adopt = [&](int type, int variant, auto&& isChild) { + for (Entity* child : entity_query(type, variant)) + if (child->parent.get() == &npc && isChild(*child)) child->parent = ½ + }; + constexpr float SPLIT_HAUNT_DRIFT = 0.3f; + switch (npc.type) + { + case ENTITY_THE_HAUNT: + if (npc.variant == 0) + { + half.state = NPC_STATE_IDLE; + half.entityCollisionClass = ENTCOLL_ALL; + half.targetPosition = vector_make(SPLIT_HAUNT_DRIFT, 0); + } + else if (npc.variant == HAUNT_LIL_VARIANT && npc.parent) + { + half.parent = npc.parent; + if (halfIndex != 0) static_cast(half.parent.get())->i1++; + half.spawnFrame = npc.spawnFrame; + half.state = npc.state; + } + return; + case ENTITY_PEEP: + half.i1 = npc.i1; + half.sprite.ReplaceSpritesheet(0, npc.sprite.GetLayer(0)->spriteSheetPath); + half.sprite.LoadGraphics(); + adopt(ENTITY_PEEP, -1, [](Entity& eye) { return eye.variant >= PEEP_EYE_FIRST; }); + return; + case ENTITY_GEMINI: + if (npc.variant != 0 && npc.variant != GEMINI_STEVEN && npc.variant != GEMINI_BLIGHTED_OVUM) return; + half.state = NPC_STATE_MOVE; + for (Entity* cord : entity_query(ENTITY_GEMINI, GEMINI_CORD)) + if (cord->parent.get() == &npc) cord->Remove(); + if (npc.variant == GEMINI_BLIGHTED_OVUM) adopt(ENTITY_GEMINI, GEMINI_BLIGHTED_OVUM_BABY, [](Entity&) { return true; }); + return; + case ENTITY_MASK_OF_INFAMY: + half.state = NPC_STATE_ATTACK2; + return; + case ENTITY_WAR: + if (npc.variant != 1) return; + half.spawnerType = 0; + half.spawnerVariant = 0; + return; + case ENTITY_PESTILENCE: + if (npc.i1 == 0) return; + half.i1 = 1; + half.sprite.GetLayer(1)->isVisible = false; + return; + case ENTITY_FAMINE: + if (npc.state == NPC_STATE_ATTACK2) half.state = NPC_STATE_ATTACK2; + return; + case ENTITY_REAP_CREEP: + half.state = npc.state; + half.entityGridCollisionClass = GRIDCOLL_WALLS; + half.sprite.isOverlayRenderFirst = true; + return; + case ENTITY_MOM: + if (halfIndex != 0) + { + half.parent = first; + return; + } + for (Entity* part : entity_query(ENTITY_MOM, -1)) + { + if (part == &npc || part->parent.get() != &npc) continue; + part->health = part->maxHitPoints; + part->parent = ½ + } + return; + default: + return; + } +} + +// Spawns one half of a split boss beside it, a champion like it, with 40 percent of its health and two thirds of its +// size. Horny Boys split into Hornfel and Loki, Loki into Lokii. Hornfel out of doors to run to turns sad. +static Entity_NPC* split_half_spawn(Entity_NPC& npc, RNG& rng, int halfIndex, Entity_NPC* first) +{ + constexpr float SPLIT_SPREAD = 0.5f; + constexpr float SPLIT_HALF_SCALE = 0.66f; + constexpr float SPLIT_HALF_HEALTH = 0.4f; + constexpr float SPLIT_SCORE = 0.5f; + float spread = npc.size * SPLIT_SPREAD; + Vector offset = split_is_side_by_side(npc) ? vector_make(halfIndex == 0 ? -spread : spread, 0) + : vector_scale(RandomVector(rng.Next()), spread); + int type = npc.type; + int variant = npc.variant; + if (type == ENTITY_LOKI && variant == 0) variant = LOKII; + else if (type == ENTITY_HORNY_BOYS) + { + type = halfIndex == 0 ? ENTITY_HORNFEL : ENTITY_LOKI; + variant = 0; + } + + auto* half = static_cast(g_game->Spawn( + {.position = vector_add(npc.pos, offset), .spawner = &npc, .subType = npc.subtype, .type = type, .variant = variant, .seed = rng.Next()})); + if (npc.isChampion) half->Morph(type, variant, npc.subtype, npc.championColorIdx); + half->scoreMultiplier = npc.scoreMultiplier * SPLIT_SCORE; + if (half->type == ENTITY_BLOOD_PUPPY) + { + half->parent = npc.parent; + // The original reads the parent's type even without one, which this skips. + if (halfIndex == 0 && npc.parent && npc.parent->type == ENTITY_FAMILIAR) + static_cast(npc.parent.get())->linkedEntity = half; + g_game->room->entityList.AddPersistentEntity(half); + } + if (npc.type == ENTITY_LOKI && npc.variant == 0) half->sprite.isFlipX = halfIndex != 0; + else if (npc.type != ENTITY_HORNY_BOYS) + { + half->SetScale(npc.scale * SPLIT_HALF_SCALE); + half->scaleMulti = npc.scaleMulti * SPLIT_HALF_SCALE; + } + if (half->type == ENTITY_HORNFEL && entity_query(ENTITY_HORNFEL_DOOR, -1).empty()) + { + if (half->minecart) half->minecart->Remove(); + half->state = NPC_STATE_SUMMON; + npc_anim_loop(half->sprite, "Sad"); + half->entityGridCollisionClass = GRIDCOLL_GROUND; + } + half->maxHitPoints = npc.maxHitPoints * SPLIT_HALF_HEALTH; + half->health = npc.health * SPLIT_HALF_HEALTH; + half->hitPointsMulti = npc.hitPointsMulti * SPLIT_HALF_HEALTH; + split_half_link(npc, *half, halfIndex, first); + + half->spawnGridIndex = npc.spawnGridIndex; + if (npc.HasEntityFlags(FLAG_AMBUSH)) half->AddEntityFlags(FLAG_AMBUSH); + return half; +} + +// 006d97e0 Meat Cleaver's cut: splits the enemy into two halves (split_half_spawn) and removes it in a burst of blood. +// The Fallen (outside Satan's fight) only drops to 40 percent, some bosses die outright and the ones too small or +// too big to split are only hurt, the split worm bodies and Visage's and the Scourge's chains for twice their health. +// Conquest dies unless it is a boss. With a sound it shakes the screen. A dead enemy does nothing. +bool Entity_NPC::split(float damage, const EntityRef& source, bool isPlaySound) +{ + constexpr float SPLIT_LEAST_SCALE = 0.5f; + constexpr float FALLEN_SPLIT_HEALTH = 0.4f; + constexpr int SPLIT_HURT_COUNTDOWN = 30; + constexpr int SPLIT_SHAKE = 15; + constexpr uint32_t SPLIT_SHIFT_INDEX = 22; + if (isDead || !isExists) return false; + + if (isPlaySound) npc_sound_play(SOUND_MEATY_DEATHS, 1, 2, 1); + bool isHurtOnly = scale < SPLIT_LEAST_SCALE || split_is_unsplittable(*this); + bool isChain = (type == ENTITY_VISAGE && variant == VISAGE_CHAIN) || (type == ENTITY_SCOURGE && variant == SCOURGE_CHAIN); + if (isHurtOnly) TakeDamage(damage, 0, source, SPLIT_HURT_COUNTDOWN); + else if (type == ENTITY_FALLEN && variant == 0 && spawnerType != ENTITY_FALLEN) + health = std::min(health, maxHitPoints * FALLEN_SPLIT_HEALTH); + else if (is_same_segmented_body(nullptr) || isChain) TakeDamage(health + health, 0, source, SPLIT_HURT_COUNTDOWN); + else if (split_is_killed(*this) || (type == ENTITY_WAR && variant == 1 && !IsBoss())) Kill(EntityRef()); + else + { + RNG rng; + rng.SetSeed(initSeed, SPLIT_SHIFT_INDEX); + Entity_NPC* first = split_half_spawn(*this, rng, 0, nullptr); + split_half_spawn(*this, rng, 1, first); + BloodExplode(); + Remove(); + } + if (isPlaySound) game_shake_screen(SPLIT_SHAKE); + return true; } // 006da530 While a player holds Guppy's Eye, a lit fireplace or a living shopkeeper shows the loot it would drop as -// ghosts. Otherwise the ghosts shown before go. +// ghosts. Otherwise, or with nothing to drop, the ghosts shown before go. void Entity_NPC::UpdatePickupGhosts() { bool isLootHolder = (type == ENTITY_FIREPLACE && health > 1) || (type == ENTITY_SHOPKEEPER && !isDead); - if (isLootHolder && g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_GUPPYS_EYE_ID, LAZARUS_SHARE_CHECK)) - reconstruction_missing("Entity_NPC::UpdatePickupGhosts 006da530 (the loot ghosts)"); + { + LootList loot = type == ENTITY_FIREPLACE ? fireplace_get_loot(false) : LootList{shopkeeper_loot_get(*this, false)}; + if (!loot.entries.empty()) + { + pickupGhostsEntity = Entity_Effect::CreateLootPreview( + &loot, pos, this, static_cast(pickupGhostsEntity.get())); + return; + } + } if (pickupGhostsEntity) pickupGhostsEntity->Remove(); } diff --git a/src/entity_npc.h b/src/entity_npc.h index 98b3ea6..3b51a34 100644 --- a/src/entity_npc.h +++ b/src/entity_npc.h @@ -3,6 +3,7 @@ #include "entity.h" #include "anm2.h" #include "entity_projectile.h" +#include "loot_list.h" #include "path_finder.h" #include #include @@ -101,9 +102,10 @@ enum ChampionColor : int CHAMPION_COUNT = 26 }; -// Mask of Infamy's hit color, and Singe's ball variant. +// Mask of Infamy's hit color, Singe's ball variant and the Scourge's chain. constexpr ColorMod INFAMY_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {64 / 255.0f, 64 / 255.0f, 128 / 255.0f}}; constexpr int SINGE_BALL = 1; +constexpr int SCOURGE_CHAIN = 10; // How far apart a line check samples. constexpr float LINE_STEP = 10; @@ -299,6 +301,9 @@ struct Entity_NPC : Entity void poof02_spawn(); void ripple_spawn(); void seed_effects_update(); + void captured_update(); + void camouflage_update(); + void quick_kill_update(); void type_update(); void forced_target_update(); void update_frozen(); @@ -343,9 +348,10 @@ struct Entity_NPC : Entity void marked_status_spread(); void trigger_death_rewards(); void KillUnique(); + void betrayal_turn(Entity* attacker); bool CanBeDamagedFromVelocity(Vector velocity); bool CanReroll(); - uint8_t split(float damage, const EntityRef& source, bool isPlaySound); + bool split(float damage, const EntityRef& source, bool isPlaySound); Entity_NPC* ParentNPC(); Entity_NPC* ChildNPC(); @@ -376,11 +382,11 @@ struct Entity_NPC : Entity void RenderSegmentLink(const Vector& offset, bool isShadow); void CreateBling(); void CreateGoldParticles(uint32_t count); - void* fireplace_get_loot(void* outLoot, bool isShouldAdvance); + LootList fireplace_get_loot(bool isShouldAdvance); void on_player_damaged(); static int FindTargetPit(const Vector& pos1, const Vector& pos2, uint32_t pitIndex); static Entity_NPC* ThrowStrider(const Vector& pos, Entity* spawner, const Vector& targetPos); - static void* QueryNPCsType(void* outList, int type, int variant); + static std::vector QueryNPCsType(int type, int variant); static std::vector QueryNPCsGroup(int groupIdx); }; @@ -432,3 +438,5 @@ constexpr std::string_view CHAMPION_SUFFIX = "_champion"; std::string sheet_path_resolve(const std::string& path, std::string_view floorSuffix, std::string_view championSuffix, bool& isChampionSheet); bool room_check_line(const Vector& start, const Vector& end, int mode, int gridPathThreshold); +std::vector shopkeeper_loot_get(Entity_NPC& npc, bool isAdvance); +bool entity_is_prey(Entity& prey); diff --git a/src/entity_npc_boss.cpp b/src/entity_npc_boss.cpp index 89704e1..f50df76 100644 --- a/src/entity_npc_boss.cpp +++ b/src/entity_npc_boss.cpp @@ -1,4 +1,6 @@ #include "boss_ai.h" +#include "boss_final.h" +#include "entity_effect_combat.h" #include "entity_effect.h" #include "entity_player.h" #include "entity_projectile.h" @@ -313,10 +315,12 @@ void segment_death_animation_play(Entity_NPC& npc) } } -constexpr int MOTHER_SECOND_PHASE = 20; +// A Dead Isaac of Mother's rises out of the floor in five bouncing rocks flung at 6. +constexpr int MOTHER_DUST_COUNT = 5; +constexpr float MOTHER_DUST_SPEED = 6; // Part of 006c4b30: the sounds and effects some Repentance bosses' Appear animations trigger: Little Horn's hole, -// Min-Min's shot. Mother's particles and Colostomia's landing are not reconstructed yet. +// Min-Min's shot, a Dead Isaac's rocks and Colostomia's landing. void boss_appear_events(Entity_NPC& npc) { switch (npc.type) @@ -329,8 +333,12 @@ void boss_appear_events(Entity_NPC& npc) if (npc.sprite.IsEventTriggered("Shoot")) npc.PlaySound(SOUND_FLAME_BURST, 1, 2, false, 1); return; case ENTITY_MOTHER: - if (npc.variant == MOTHER_SECOND_PHASE && npc.sprite.IsEventTriggered("Shoot")) - reconstruction_missing("Entity_NPC::Update 006c4b30: Mother's appear particles (Game::SpawnParticles)"); + if (npc.variant == MOTHER_DEAD_ISAAC && npc.sprite.IsEventTriggered("Shoot")) + game_particles_spawn({.position = npc.pos, + .speed = MOTHER_DUST_SPEED, + .count = MOTHER_DUST_COUNT, + .subType = ROCK_PARTICLE_BOUNCY, + .variant = EFFECT_ROCK_PARTICLE}); return; case ENTITY_COLOSTOMIA: if (!npc.sprite.IsEventTriggered("Land")) return; diff --git a/src/entity_npc_render.cpp b/src/entity_npc_render.cpp index 95b06e0..0c4990b 100644 --- a/src/entity_npc_render.cpp +++ b/src/entity_npc_render.cpp @@ -42,7 +42,6 @@ constexpr float HEALTH_BAR_SATURATION_GREY = 0.8f; constexpr int WORMWOOD = 3; constexpr int BIG_BONY_BONE = 10; constexpr int SHELL = 3; -constexpr int SCOURGE_CHAIN = 10; constexpr int RIDDEN_MINECART = 10; constexpr int SINGE_BALL_VARIANT = 1; constexpr int HEART_PAIRED = 1; @@ -291,7 +290,7 @@ static void npc_body_render(Entity_NPC& npc, const Vector& offset) case ENTITY_CLUTCH: return reconstruction_missing("NpcHelper::clutch_render 00575a10"); case ENTITY_BEAST: - return reconstruction_missing("Entity_NPC::Render 006d2e50: the Beast's drawing (00598260)"); + return beast_render(npc, offset); case ENTITY_MINECART: if (npc.variant == RIDDEN_MINECART) return minecart_riders_render(npc, offset); return npc.Entity::Render(offset); diff --git a/src/entity_npc_room.cpp b/src/entity_npc_room.cpp index 5ab08b5..f5125f5 100644 --- a/src/entity_npc_room.cpp +++ b/src/entity_npc_room.cpp @@ -5,7 +5,6 @@ #include "level_generator.h" #include "npc_ai.h" -constexpr int ENTITY_MOTHERS_SHADOW = 867; constexpr int DARK_ESAU_SECOND = 1; constexpr ColorMod DARK_ESAU_POOF_COLOR = {{0.1f, 0.1f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index 69e8e15..53fd499 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -123,7 +123,6 @@ constexpr int SOUND_MEAT_FEET_SLOW0 = 68; constexpr int SOUND_DIMEDROP = 198; constexpr int SOUND_DIMEPICKUP = 199; constexpr int SOUND_LUCKYPICKUP = 200; -constexpr int SOUND_FETUS_FEET = 201; constexpr int SOUND_NICKELDROP = 231; constexpr int SOUND_NICKELPICKUP = 232; constexpr int SOUND_PENNYDROP = 233; @@ -2128,14 +2127,14 @@ bool Entity_Pickup::CanRerollVariant(int pickupVariant, int pickupSubType) return !(isChallenge && isPhoto && (path == PATH_TYPE_HOME || g_game->GetChallengeParams().endStage == STAGE_VOID)); } -// 006ee750 Taking one of a set of options removes the others in a poof, items after a short timeout. -// The Death Certificate floor's items are not reconstructed yet. +// 006ee750 Taking one of a set of options removes the others in a poof, items after a short timeout. Taking an item +// on the Death Certificate's floor starts its 90 frames to the way back. void Entity_Pickup::RemoveOtherOptions() { if (optionsPickupIndex == 0) return; if (optionsPickupIndex == 1 && variant == PICKUP_COLLECTIBLE && g_game->currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE && g_game->deathCertificateExitTimer < 1) - reconstruction_missing("Entity_Pickup::RemoveOtherOptions 006ee750: Death Certificate's exit"); + g_game->deathCertificateExitTimer = DEATH_CERTIFICATE_EXIT_FRAMES; std::vector pickups(g_game->room->entityList.updateEL); for (Entity* entity : pickups) diff --git a/src/entity_pickup.h b/src/entity_pickup.h index 04af4cc..105e2ca 100644 --- a/src/entity_pickup.h +++ b/src/entity_pickup.h @@ -103,6 +103,13 @@ enum HeartSubType : int HEART_SCARED = 9, HEART_BLENDED = 10 }; +// The poop pickups (Lua's PoopPickupSubType). +enum PoopPickupSubType : int +{ + POOP_SMALL, + POOP_BIG +}; + enum KeySubType : int { KEY_NORMAL = 1, @@ -111,6 +118,9 @@ enum KeySubType : int KEY_CHARGED }; +// 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"; + // The game state bit set once a heart, bomb or coin is picked, and Daemon's Tail's 1 in 5 heart chance. constexpr int GAME_STATE_HEART_BOMB_COIN_PICKED = 41; constexpr int DAEMONS_TAIL_ODDS = 5; diff --git a/src/entity_pickup_chest.cpp b/src/entity_pickup_chest.cpp index a898224..3309c16 100644 --- a/src/entity_pickup_chest.cpp +++ b/src/entity_pickup_chest.cpp @@ -174,7 +174,6 @@ constexpr int OLD_CHEST_SOUL_HEARTS = 3; constexpr int RED_CHEST_FAMILIARS = 3; constexpr int LEFT_HAND_EXTRA = 2; constexpr int LEFT_HAND_NO_SPIDERS = 3; -constexpr int ACHIEVEMENT_MOMS_CHEST_ITEMS = 415; constexpr int FAMILIAR_BLUE_FLY = 43; constexpr int FAMILIAR_BLUE_SPIDER = 73; constexpr int RED_CHEST_TELEPORT = 1; @@ -575,7 +574,7 @@ static void sack_loot_draw(ChestDraw& draw, int subtype) // Mom's chest's loot: a Mom's chest item, the Red Key until those are unlocked (outside a daily or debug run). static void moms_chest_loot_draw(ChestDraw& draw) { - bool isLocked = !g_manager->persistentGameData.achievements[ACHIEVEMENT_MOMS_CHEST_ITEMS] && + bool isLocked = !g_manager->persistentGameData.achievements[ACHIEVEMENT_RED_KEY] && (g_manager->state != MANAGER_STATE_GAME || (g_game->dailyChallenge._id == 0 && !g_game->isDebug)); if (!isLocked) return loot_item_add(draw, POOL_MOMS_CHEST); diff --git a/src/entity_player.cpp b/src/entity_player.cpp index 13bb851..00d01d7 100644 --- a/src/entity_player.cpp +++ b/src/entity_player.cpp @@ -68,12 +68,12 @@ constexpr int COLOR_PRIORITY_TOP = 255; constexpr int DAILY_CHRISTMAS = 19; constexpr int EMPTY_HEART_RED_HEARTS = 3; constexpr int EVENT_BONUS_ITEMS = 114; +constexpr int START_ITEM_ROLLS = 100; constexpr int GIANTBOOK_EMPTY_HEART = 41; constexpr int LOCUST_SUBTYPE_START = 25; constexpr int PEE_ALPHA = 180; constexpr int PEE_OFFSET = 244; constexpr float PICKUP_SPAWN_RADIUS = 40; -constexpr int POCKET_ACTIVE_SLOT = 2; // A removed player lets go of what it holds at a tenth of its speed. constexpr float HELD_RELEASE_SPEED = 0.1f; constexpr int RED_REDEMPTION_KEY_CHARGES = 20; @@ -511,12 +511,7 @@ void Entity_Player::links_reset() poisonDamageFrames = 0; urnSouls = 0; numGigaBombs = 0; - rockBottomMoveSpeed = 0; - rockBottomMaxFireDelay = 0; - rockBottomDamage = 0; - rockBottomTearRange = 0; - rockBottomShotSpeed = 0; - rockBottomLuck = ROCK_BOTTOM_LUCK_UNSET; + rock_bottom_reset(); reverseEmpressMaxHearts = 0; reverseChariotMoveCooldown = 0; reverseSunBoneHearts = 0; @@ -692,15 +687,36 @@ void Entity_Player::eden_stats_roll(RNG& rng) eden_offsets_roll(*this, rng); } +// Whether a rolled collectible may start a run: one of the config's that still exists, is not barred from Eden and +// is unlocked. +static bool is_start_collectible(int id) +{ + constexpr std::array REMOVED_COLLECTIBLES = {235, 43, 61}; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(id); + return std::ranges::find(REMOVED_COLLECTIBLES, id) == REMOVED_COLLECTIBLES.end() && item && + !item->HasTags(TAG_NO_EDEN) && item->IsAvailableEx(AVAILABLE_ALL); +} + +// A random collectible of the config, never the first. +static int start_collectible_roll(RNG& rng) +{ + uint32_t range = (uint32_t)g_manager->itemConfig.collectibles.size() - 1; + uint32_t next = rng.Next(); + return (int)(range == 0 ? 0 : next % range) + 1; +} + +// Gives the player a rolled collectible: added as picked up with a charge, and out of the pools. +void Entity_Player::rolled_collectible_add(int id, int charge) +{ + AddCollectible(id, charge, true, 0, 0); + g_game->itemPool.RemoveCollectible(id, REMOVE_ANY, REMOVE_APPLY); +} + // The part of 007bc740 that rolls Eden's starting pickups and items: a trinket on a third of the rolls, else maybe a // card or a pill, then the first active and the first passive among 100 random collectibles Eden may start with. void Entity_Player::eden_items_roll(RNG& rng) { - constexpr int EDEN_ITEM_ROLLS = 100; - constexpr std::array REMOVED_COLLECTIBLES = {235, 43, 61}; - ItemConfig& items = g_manager->itemConfig; ItemPool& pool = g_game->itemPool; - if (rng.Next() % 3 == 0) AddTrinket((int)pool.GetTrinket(TRINKET_DRAW_TAKE), true); else if ((rng.Next() & 1) == 0) { @@ -710,24 +726,58 @@ void Entity_Player::eden_items_roll(RNG& rng) int active = 0; int passive = 0; - uint32_t range = (uint32_t)items.collectibles.size() - 1; - for (int roll = 0; roll < EDEN_ITEM_ROLLS; roll++) + for (int roll = 0; roll < START_ITEM_ROLLS; roll++) { - uint32_t next = rng.Next(); - int id = (int)(range == 0 ? 0 : next % range) + 1; - ItemConfig_Item* item = items.GetCollectible(id); - if (std::ranges::find(REMOVED_COLLECTIBLES, id) != REMOVED_COLLECTIBLES.end() || !item || item->HasTags(TAG_NO_EDEN) || - !item->IsAvailableEx(AVAILABLE_ALL)) - continue; - int& kept = item->type == ITEM_ACTIVE ? active : passive; + int id = start_collectible_roll(rng); + if (!is_start_collectible(id)) continue; + int& kept = g_manager->itemConfig.GetCollectible(id)->type == ITEM_ACTIVE ? active : passive; if (kept == 0) kept = id; } for (int id : {active, passive}) - if (id != 0) + if (id != 0) rolled_collectible_add(id, -1); +} + +// The part of 007bc740 that hands out the bonus starting items the save holds (up to two): random collectibles the +// player may start with, an active only into an empty slot, each given up after 100 rolls. The save's count is spent. +// The second local player's copy of the counter is netplay's. +void Entity_Player::bonus_items_roll(RNG& rng) +{ + constexpr int BONUS_ITEMS_MAX = 2; + constexpr uint32_t BONUS_COUNT_MASK = 0xffff; + int& counter = g_manager->persistentGameData.eventCounters[EVENT_BONUS_ITEMS]; + int count = std::min((int)((uint32_t)counter & BONUS_COUNT_MASK), BONUS_ITEMS_MAX); + if (count == 0) return; + + for (int bonus = 0; bonus < count; bonus++) + for (int roll = 0; roll < START_ITEM_ROLLS; roll++) { - AddCollectible(id, -1, true, 0, 0); - pool.RemoveCollectible(id, REMOVE_ANY, REMOVE_APPLY); + int id = start_collectible_roll(rng); + if (!is_start_collectible(id)) continue; + bool isActive = g_manager->itemConfig.GetCollectible(id)->type == ITEM_ACTIVE; + if (isActive && activeItems[ACTIVE_SLOT_PRIMARY].item != 0) continue; + rolled_collectible_add(id, -1); + break; } + counter = (int)((uint32_t)counter & ~BONUS_COUNT_MASK); +} + +// The part of 007bc740 for Backasswards: ten passive collectibles drawn at random from every one the player may start +// with, uncharged. +void Entity_Player::backasswards_items_roll(RNG& rng) +{ + constexpr int BACKASSWARDS_ITEMS = 10; + std::vector candidates; + for (int id = 1; id < (int)g_manager->itemConfig.collectibles.size(); id++) + if (is_start_collectible(id) && g_manager->itemConfig.GetCollectible(id)->type != ITEM_ACTIVE) + candidates.push_back(id); + + for (int i = 0; i < BACKASSWARDS_ITEMS && !candidates.empty(); i++) + { + uint32_t pick = rng.Next() % (uint32_t)candidates.size(); + std::swap(candidates[pick], candidates.back()); + rolled_collectible_add(candidates.back(), 0); + candidates.pop_back(); + } } // Gives the player a starting collectible, as the run's start does: added as picked up, out of the pools, and its @@ -753,7 +803,7 @@ void Entity_Player::starting_trinket_add(int id) // unlocked ones (D6, Wooden Nickel, Razor Blade), the daily's, its innate items and pocket active, its trinket, Eden's // rolled items, the Mega Satan key pieces and the challenge's lists. Then it evaluates the stats, shares the pickups // and starts the twins and companions. Straw Man's player only evaluates. Netplay's per-player save data is offline. -// The original's daily specials and its Backasswards and Cantripped extras stop here until reached. +// The original's daily specials stop here until reached. void Entity_Player::InitPostLevelInitStats() { Game& game = *g_game; @@ -796,11 +846,11 @@ void Entity_Player::InitPostLevelInitStats() if (game.challenge == CHALLENGE_RED_REDEMPTION) { - SetPocketActiveItem(COLLECTIBLE_RED_KEY, POCKET_ACTIVE_SLOT, false); - activeItems[POCKET_ACTIVE_SLOT].varData = RED_REDEMPTION_KEY_CHARGES; + SetPocketActiveItem(COLLECTIBLE_RED_KEY, ACTIVE_SLOT_POCKET, false); + activeItems[ACTIVE_SLOT_POCKET].varData = RED_REDEMPTION_KEY_CHARGES; } else if (playerConfig->pocketActiveID != 0) - SetPocketActiveItem(playerConfig->pocketActiveID, POCKET_ACTIVE_SLOT, false); + SetPocketActiveItem(playerConfig->pocketActiveID, ACTIVE_SLOT_POCKET, false); int trinket = playerConfig->trinket; if (trinket == 0 && game.challenge == 0) @@ -824,8 +874,7 @@ void Entity_Player::InitPostLevelInitStats() } if (game.challenge == 0 && game.dailyChallenge._id == 0) { - if (startFrame == 0 && (g_manager->persistentGameData.eventCounters[EVENT_BONUS_ITEMS] & 0xffff) != 0) - reconstruction_missing("Entity_Player::InitPostLevelInitStats 007bc740 (the bonus starting items)"); + if (startFrame == 0) bonus_items_roll(rng); } else if (twin_get() && twin_get()->playerIndex != -1 && playerIndex > twin_get()->playerIndex && twin_get() != this) { @@ -840,7 +889,11 @@ void Entity_Player::InitPostLevelInitStats() else starting_collectible_add(id); for (int id : challenge.trinketList) starting_trinket_add(id); if (challenge.startingPill != PILLEFFECT_NULL) - reconstruction_missing("Entity_Player::InitPostLevelInitStats 007bc740 (a challenge's starting pill)"); + { + int pillColor = game.itemPool.ForceAddPillEffect(challenge.startingPill); + AddPocketItem(pillColor, POCKET_PILL); + game.itemPool.IdentifyPill((uint32_t)pillColor); + } if (challenge.startingCard > 0) AddPocketItem(challenge.startingCard, POCKET_CARD); else if (challenge.startingCard < 0) AddPocketItem(card_roll(rng.Next(), 0, false), POCKET_CARD); } @@ -848,8 +901,7 @@ void Entity_Player::InitPostLevelInitStats() EvaluateItems(); game.GetPlayer(0)->ConsumableCountChanged(-1); if (!replacedPlayer) companions_init(); - if (game.challenge == CHALLENGE_BACKASSWARDS) - reconstruction_missing("Entity_Player::InitPostLevelInitStats 007bc740 (Backasswards' ten items)"); + if (game.challenge == CHALLENGE_BACKASSWARDS) backasswards_items_roll(rng); if (game.challenge == CHALLENGE_CANTRIPPED) for (int i = 0; i < CANTRIPPED_CARDS; i++) AddItemCard(0); isPostLevelInitFinished = true; @@ -1119,8 +1171,8 @@ void Entity_Player::floor_items_recharge() ActiveItemDesc& active = activeItems[slot]; if (active.item == COLLECTIBLE_NOTCHED_AXE) { - bool isEmpty = slot == POCKET_ACTIVE_SLOT + 1 || - (slot == POCKET_ACTIVE_SLOT && activeItems[POCKET_ACTIVE_SLOT].item == COLLECTIBLE_RED_KEY && + bool isEmpty = slot == ACTIVE_SLOT_POCKET + 1 || + (slot == ACTIVE_SLOT_POCKET && activeItems[ACTIVE_SLOT_POCKET].item == COLLECTIBLE_RED_KEY && game.challenge == CHALLENGE_RED_REDEMPTION); AddActiveCharge(isEmpty ? 0 : GetCollectibleMaxCharge(COLLECTIBLE_NOTCHED_AXE, active.varData), slot, false, false, true); @@ -1170,7 +1222,7 @@ void Entity_Player::necromancer_recharge() if (isRecharged) active.varData = 0; else if (active.varData == 1) { - int charge = slot == POCKET_ACTIVE_SLOT + 1 ? 0 : GetCollectibleMaxCharge(COLLECTIBLE_NECRONOMICON, 1); + int charge = slot == ACTIVE_SLOT_POCKET + 1 ? 0 : GetCollectibleMaxCharge(COLLECTIBLE_NECRONOMICON, 1); AddActiveCharge(charge, slot, false, false, true); game.itemOverlay.Show(GIANTBOOK_NECROMANCER, NECROMANCER_OVERLAY_DELAY, nullptr); sound_fart_play(SOUND_NECROMANCER); @@ -1498,6 +1550,17 @@ void Entity_Player::ClearReferences() release_weapons_and_effects(false); } +// 007d3e00 Forgets the stats Rock Bottom holds, so the next evaluation starts it again. +void Entity_Player::rock_bottom_reset() +{ + rockBottomMoveSpeed = 0; + rockBottomMaxFireDelay = 0; + rockBottomDamage = 0; + rockBottomTearRange = 0; + rockBottomShotSpeed = 0; + rockBottomLuck = ROCK_BOTTOM_LUCK_UNSET; +} + // Forgets an entity the player spawned, removing it first when asked. template static void link_release(Link& link, bool isRemoveEntities) { @@ -1533,6 +1596,7 @@ void Entity_Player::release_weapons_and_effects(bool isRemoveEntities) link_release(tetheredEffect, isRemoveEntities); link_release(astralProjectionBody, isRemoveEntities); link_release(montezumaLaser, isRemoveEntities); + link_release(spearOfDestiny, isRemoveEntities); link_release(divineShield, isRemoveEntities); link_release(darkArtsLastSnare, isRemoveEntities); link_release(darkEsau, isRemoveEntities); @@ -1596,3 +1660,172 @@ void Entity_Player::ResetColor() { sprite.color = color; } + +constexpr int VICTORY_LAP_HEARTS = 6; +constexpr float VICTORY_LAP_SECOND_LOSS = 0.5f; +constexpr float VICTORY_LAP_LATER_LOSS = 0.75f; +constexpr int BODY_SKIN_DEFAULT = 60; +constexpr int BODY_SKIN_SOUL = 62; +constexpr int BODY_SKIN_DARK = 61; +constexpr int BODY_SKIN_BONY = 63; + +// 0060d0a0 The player's own sprite scale. +Vector Entity_Player::SpriteScale() +{ + return playerSpriteScale; +} + +// 00770610 What enemies chase instead of the player: its Best Friend, else the last parent of Dark Arts' last snare, +// else the player. +Entity* Entity_Player::GetNPCTarget() +{ + if (bestFriend) return bestFriend.get(); + return darkArtsLastSnare ? darkArtsLastSnare->GetLastParent() : this; +} + +// 007e9280 The player's name. +const std::string& Entity_Player::GetName() +{ + return name; +} + +// 007daed0 Greed's reset of a main player: its stats from the start of the floor and the collectibles Greed's reset +// gave back, then the wisps. The given collectibles are forgotten for any player. +void Entity_Player::ResetPlayer() +{ + if (variant == PLAYER_VARIANT_PLAYER && !isCoopGhost) + { + InitPostLevelInitStats(); + for (int collectible : greedResetCollectibles) AddCollectible(collectible, 0, false, 0, 0); + EvaluateItems(); + RecomputeWispCollectibles(nullptr); + } + greedResetCollectibles = {}; +} + +// The co-op baby skin a character's body takes as a ghost: ???'s, the dark one of Azazel and Lilith, the bony one of +// Keeper, Apollyon and the Forgotten (tainted or not), else the default. +static int body_skin_get(int playerType) +{ + switch (playerType) + { + case PLAYER_BLUEBABY: + case PLAYER_BLUEBABY_B: + return BODY_SKIN_SOUL; + case PLAYER_KEEPER: + case PLAYER_KEEPER_B: + case PLAYER_APOLLYON: + case PLAYER_APOLLYON_B: + case PLAYER_THEFORGOTTEN: + case PLAYER_THEFORGOTTEN_B: + return BODY_SKIN_BONY; + case PLAYER_AZAZEL: + case PLAYER_AZAZEL_B: + case PLAYER_LILITH: + case PLAYER_LILITH_B: + return BODY_SKIN_DARK; + default: + return BODY_SKIN_DEFAULT; + } +} + +// 007d9b70 Loads the player's sprite again, every layer in the body skin its character takes as a ghost. +void Entity_Player::reset_body_sprite() +{ + const std::string& skin = g_manager->entityConfig.babies[body_skin_get(playerType)].gfx; + + sprite.Load(g_manager->entityConfig.GetEntity(ENTITY_PLAYER, 0, 0)->anm2Path, GRAPHICS_DEFER); + for (size_t layer = 0; layer < sprite.layerStates.size(); layer++) sprite.ReplaceSpritesheet((int)layer, skin); + sprite.LoadGraphics(); +} + +// 007c97f0 A victory lap's toll: the second keeps three heart containers at most and loses half the collectibles, the +// third turns the player into the Lost, and later ones also lose three quarters of them. The lost collectibles are +// drawn by shuffling the history from a seed. +void Entity_Player::apply_victory_lap_penalty(uint32_t seed) +{ + int lap = g_game->victoryLap; + float loss = VICTORY_LAP_SECOND_LOSS; + + if (lap < 2) return; + if (lap == 2 && maxHearts > VICTORY_LAP_HEARTS) AddMaxHearts(VICTORY_LAP_HEARTS - maxHearts, false); + if (lap >= 3) + { + RemoveSkinCostume(); + cacheFlags |= CACHE_ALL; + maxHearts = 0; + redHearts = 0; + soulHearts = 1; + blackHearts = 0; + boneHeartsMask = 0; + boneHearts = 0; + eternalHearts = 0; + playerType = PLAYER_THELOST; + EvaluateItems(); + update_player_skin(); + UpdateCanShoot(); + if (lap == 3) return; + loss = VICTORY_LAP_LATER_LOSS; + } + + std::vector collectibles; + for (HistoryItem& item : history.historyItems) + if (!item.isTrinket) collectibles.push_back(item.id); + for (size_t i = collectibles.size(); i > 1; i--) + { + seed ^= seed >> 4; + seed ^= seed << 5; + seed ^= seed >> 15; + std::swap(collectibles[i - 1], collectibles[seed % i]); + } + size_t lost = std::min((size_t)std::floor((float)(collectibles.size() + 1) * loss), collectibles.size()); + for (size_t i = 0; i < lost; i++) RemoveCollectible(collectibles[i], false, 0, true); +} + +// 007585b0 Moves a dead co-op player's view to the next player alive. +void Entity_Player::cycle_spectate_target() +{ + reconstruction_missing("Entity_Player::cycle_spectate_target 007585b0 (co-op)"); +} + +// 007ba2b0 The effects of a co-op baby's skin each frame. +void Entity_Player::update_baby_skin_effects() +{ + reconstruction_missing("Entity_Player::update_baby_skin_effects 007ba2b0 (co-op)"); +} + +// 007bb5e0 A co-op baby's skin's effect as it dies. +void Entity_Player::coop_baby_death_effect() +{ + reconstruction_missing("Entity_Player::coop_baby_death_effect 007bb5e0 (co-op)"); +} + +// 007bf040 Dresses a co-op baby in its skin. +void Entity_Player::InitBabySkin() +{ + reconstruction_missing("Entity_Player::InitBabySkin 007bf040 (co-op)"); +} + +// 007c2e90 The skin a glitched co-op baby takes next. +uint32_t Entity_Player::GetGlitchBabySubType() +{ + reconstruction_missing("Entity_Player::GetGlitchBabySubType 007c2e90 (co-op)"); +} + +// 007cb090 What a co-op baby's skin brings as it joins. +void Entity_Player::apply_coop_baby_spawn_bonus() +{ + reconstruction_missing("Entity_Player::apply_coop_baby_spawn_bonus 007cb090 (co-op)"); +} + +// 007d93b0 Brings a co-op ghost back to life. +void Entity_Player::RevivePlayerGhost() +{ + reconstruction_missing("Entity_Player::RevivePlayerGhost 007d93b0 (co-op)"); +} + +// 007d96f0 Turns a dead co-op player into a ghost. +void Entity_Player::MorphToCoopGhost() +{ + reconstruction_missing("Entity_Player::MorphToCoopGhost 007d96f0 (co-op)"); +} diff --git a/src/entity_player.h b/src/entity_player.h index 6bce712..f0d8d6b 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -38,6 +38,8 @@ constexpr int WEAPON_SLOT_COUNT = 5; constexpr uint32_t QUEUED_TOUCHED = 0x1; constexpr uint32_t QUEUED_GOLDEN = 0x2; constexpr uint32_t TRINKET_GOLDEN_FLAG = 0x8000; +constexpr uint32_t CARD_ITEM_FLAG = 0x8000; +constexpr int DEAD_CAT_LIVES = 9; constexpr uint8_t WILD_CARD_NONE = 0xff; constexpr uint8_t WILD_CARD_PILL = 0; constexpr uint8_t WILD_CARD_CARD = 1; @@ -54,9 +56,26 @@ enum ConsumableMask : uint32_t CONSUMABLE_SOUL_CHARGE = 0x20, CONSUMABLE_GIGA_BOMBS = 0x40, CONSUMABLE_POOP_MANA = 0x80, - CONSUMABLE_BLOOD_CHARGE = 0x100 + CONSUMABLE_BLOOD_CHARGE = 0x100, + CONSUMABLE_ALL = 0xffffffff }; +// A character's skin colour (Lua's SkinColor), as headColor holds it. +enum SkinColor : int +{ + SKIN_PINK = -1, + SKIN_WHITE, + SKIN_BLACK, + SKIN_BLUE, + SKIN_RED, + SKIN_GREEN, + SKIN_GREY, + SKIN_SHADOW +}; + +// How far above its mouth Montezuma's Revenge's beam leaves, in body heights. +constexpr float MONTEZUMA_RISE = 4; + // The characters, by their ids in players.xml (Lua's PlayerType). enum PlayerType : int { @@ -124,6 +143,7 @@ enum BabySubType : int BABY_YBAB = 7, BABY_SHADOW = 13, BABY_BEGOTTEN = 21, + BABY_DEAD = 22, BABY_FIGHTING = 23, BABY_GLITCH = 25, BABY_MAGNET = 26, @@ -291,9 +311,12 @@ enum PlayerItemId : int COLLECTIBLE_TRANSCENDENCE = 20, COLLECTIBLE_INNER_EYE = 2, COLLECTIBLE_SPOON_BENDER = 3, + COLLECTIBLE_MY_REFLECTION = 5, COLLECTIBLE_NUMBER_ONE = 6, COLLECTIBLE_SKATOLE = 9, COLLECTIBLE_1UP = 11, + COLLECTIBLE_ANKH = 161, + COLLECTIBLE_JUDAS_SHADOW = 311, COLLECTIBLE_VIRUS = 13, COLLECTIBLE_COMPASS = 21, COLLECTIBLE_BREAKFAST = 25, @@ -302,6 +325,7 @@ enum PlayerItemId : int COLLECTIBLE_INFESTATION_2 = 234, COLLECTIBLE_QUINTS = 661, COLLECTIBLE_BONE_SPURS = 683, + COLLECTIBLE_SPEAR_OF_DESTINY = 400, COLLECTIBLE_HUNGRY_SOUL = 684, COLLECTIBLE_DOLLAR = 18, COLLECTIBLE_LUNCH = 22, @@ -694,6 +718,10 @@ enum PlayerItemId : int TRINKET_MYSTERIOUS_PAPER = 21, TRINKET_DAEMONS_TAIL = 22, TRINKET_MISSING_POSTER = 23, + TRINKET_STORE_CREDIT = 13, + TRINKET_BROKEN_ANKH = 28, + TRINKET_LOCUST_OF_WRATH = 113, + TRINKET_LOCUST_OF_CONQUEST = 117, TRINKET_BUTT_PENNY = 24, TRINKET_CHILDS_HEART = 34, TRINKET_RUSTED_KEY = 36, @@ -773,6 +801,7 @@ enum PlayerItemId : int TRINKET_NUMBER_MAGNET = 174, TRINKET_STRANGE_KEY = 175, TRINKET_RC_REMOTE = 179, + TRINKET_LOST_CORK = 106, TRINKET_FOUND_SOUL = 180, TRINKET_BROKEN_GLASSES = 187, TRINKET_ID_MASK = 0x7fff, @@ -819,6 +848,7 @@ enum PlayerItemId : int TRINKET_BROKEN_REMOTE = 4, TRINKET_M = 138, TRINKET_PANIC_BUTTON = 149, + TRINKET_TORN_CARD = 157, TRINKET_EXPANSION_PACK = 181, NULLITEM_EXPLOSIVE_DIARRHEA = 0, @@ -832,6 +862,7 @@ enum PlayerItemId : int NULLITEM_MAW_MARK = 19, NULLITEM_HOLY_CARD = 46, NULLITEM_LAZARUS_BOOST = 49, + NULLITEM_BATWING_WINGS = 40, NULLITEM_SPIN_TO_WIN = 50, NULLITEM_INTRUDER = 55, NULLITEM_IT_HURTS = 57, @@ -945,6 +976,8 @@ enum PlayerItemId : int PILLEFFECT_SHOT_SPEED_UP = 48, PILLEFFECT_EXPERIMENTAL = 49, COLLECTIBLE_BROTHER_BOBBY = 8, + COLLECTIBLE_SISTER_MAGGY = 67, + COLLECTIBLE_SWARM = 693, COLLECTIBLE_ABYSS = 706, COLLECTIBLE_LEMEGETON = 712, COLLECTIBLE_ANIMA_SOLA = 722, @@ -993,7 +1026,12 @@ enum PlayerItemId : int COLLECTIBLE_MINI_MUSH = 71, COLLECTIBLE_QUARTER = 74, COLLECTIBLE_GHOST_BABY = 163, + COLLECTIBLE_HIVE_MIND = 248, COLLECTIBLE_DRY_BABY = 265, + COLLECTIBLE_EYE_OF_GREED = 450, + COLLECTIBLE_GHOST_PEPPER = 495, + COLLECTIBLE_IMMACULATE_HEART = 573, + COLLECTIBLE_BIRDS_EYE = 616, COLLECTIBLE_ROTTEN_BABY = 268 }; @@ -1475,7 +1513,7 @@ public: std::vector darkArtsHitList; std::vector curseMistFamiliars; std::vector pendingWisps; - std::deque echoChamberItems; + std::deque echoChamberItems; PlayerTrail hallucinationTrail; PlayerTrail roomTrail; EntityDesc friendBallEnemy; @@ -1502,8 +1540,9 @@ public: Entity_Player* subPlayer = nullptr; Entity* darkArtsLastSnare = nullptr; Entity* heldEntity = nullptr; - Entity* montezumaLaser = nullptr; EntityPtr markedTarget; + EntityPtr montezumaLaser; + EntityPtr spearOfDestiny; Entity_Familiar* forgottenBody = nullptr; Entity_Laser* megaBlastLaser = nullptr; Vector forgottenBodyPos{}; @@ -1556,6 +1595,7 @@ public: int forgottenSwapFormCooldown = 0; int firstVisitRooms = 0; int techFiveDelay = 0; + float spearOfDestinyAngle = 0; float trinityShieldAngle = 0; int gnawedLeafTimer = 0; int momsHandTimer = 0; @@ -1643,6 +1683,7 @@ public: int get_seeded_variant(); int g_fuel_count(); void EvaluateItems(); + void rock_bottom_reset(); void AddCacheFlags(uint32_t flags); RNG& GetCollectibleRNG(int id); RNG& GetTrinketRNG(int id); @@ -1752,6 +1793,9 @@ private: void links_reset(); void eden_stats_roll(RNG& rng); void eden_items_roll(RNG& rng); + void bonus_items_roll(RNG& rng); + void backasswards_items_roll(RNG& rng); + void rolled_collectible_add(int id, int charge); void magdalene_pill_add(); std::optional collectible_lent(int collectibleType, ItemConfig_Item& item); std::optional trinket_lent(uint32_t id, int multiplier); @@ -1860,7 +1904,7 @@ public: void render_charge_bars(Vector renderPos); int GetCollectibleCount(); void RespawnFamiliars(); - void GetNPCTarget(); + Entity* GetNPCTarget(); bool VoidHasCollectible(int id); bool HasGoldenTrinket(uint32_t trinketId); bool TryHoldTrinket(int trinketId); @@ -1895,7 +1939,6 @@ public: void SetActiveVarData(int vardata, int slot); void ControlActiveItem(int slot); bool HasTimedItem(); - void update_effects(); void update_ladder(); void trigger_npc_death(Entity* npc); Entity_Bomb* FireBomb(Vector pos, Vector vel, Entity* source); @@ -1949,6 +1992,9 @@ public: void stop_costume_item_anims(); void ClearCollectibleAnim(int collectible); bool IsCollectibleAnimFinished(int collectible, std::string_view animName); + void ClearNullItemAnim(int nullItem); + void play_null_costume_anim(int nullItem, std::string_view animation, int frame); + bool IsNullItemAnimFinished(int nullItem, std::string_view animName); void TriggerTrinketAdded(uint32_t trinketId, bool isFirstTime); void TriggerTrinketRemoved(uint32_t trinketId); void RestoreGameState(GameStatePlayer& saved); @@ -1960,7 +2006,7 @@ public: void SetFootprintColor(KColor color, bool isUnknown); bool is_footstep_triggered(int foot); void update_pitfall(); - void TryDecreaseGlowingHourglassUses(int unk1, bool isUnknown2); + bool TryDecreaseGlowingHourglassUses(bool isDecrease, bool isRefill); bool GetMouseAimTarget(Vector& outTarget, bool isSkipNetCursor); void update_baby_skin_effects(); void coop_baby_death_effect(); @@ -2063,7 +2109,7 @@ public: Entity_Pickup* DropCollectibleByHistoryIndex(int index, Entity_Pickup* existing); bool CanAddCollectibleToInventory(int id); void SetPocketActiveItem(int collectible, int slot, bool keepInPools); - void get_salvation_scale(); + float get_salvation_scale(); void update_suplex(); bool bag_of_crafting_collect(Entity_Pickup* pickup); void tainted_cain_pedestal_burst(Vector position, uint32_t seed, int poolType); @@ -2097,11 +2143,9 @@ public: void ModelingClay_roll(RNG* rng); void twins_duplicate_familiars(int count); const std::string& GetName(); - void TriggerRoomExit(); int GetActiveSubCharge(int slot); int GetPoopSpell(int position); bool HasFullHeartsAndSoulHearts(); void AddControlsCooldown(int amount); uint64_t GetLastDamageFlags(); - void CheckPoopSpellQueue(Vector position); }; diff --git a/src/entity_player_actives_grid.cpp b/src/entity_player_actives_grid.cpp index a123d4f..2f4aa0f 100644 --- a/src/entity_player_actives_grid.cpp +++ b/src/entity_player_actives_grid.cpp @@ -39,6 +39,35 @@ static bool is_config_walking(const EntityConfig_Entity* config) return grid == "ground" || (grid.empty() && config->gridCollisionPoints >= 1); } +// 00823d10 Where a walking enemy can stand: the position itself when it reaches the player, else the first cell +// centre off the walls that does, spiralling out from it for 15 rings, else the position. +static Vector reachable_position_find(Room& room, Vector position) +{ + constexpr int SPIRAL_RINGS = 16; + if (is_reachable_from_player(room, {.position = position})) return position; + + int column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + int stepX = 0; + int stepY = -1; + for (int length = 1; length < SPIRAL_RINGS;) + { + for (int i = 0; i < length; i++) + { + column += stepX; + row += stepY; + if (column <= 0 || row <= 0 || column >= room.gridWidth - 1 || row >= room.gridHeight - 1) continue; + Vector cell = room.GetGridPosition(room.GetGridIndexByTile(column, row)); + if (is_reachable_from_player(room, {.position = cell})) return cell; + } + int turned = -stepY; + stepY = stepX; + stepX = turned; + if (stepX == 0) length++; + } + return position; +} + // 00705480 Turns an entity into one of its weaker forms from entities2.xml, drawn by weight on the room's decoration // seed: an enemy keeps its health share and champion and is counted with the ambush, a flying one turning into a walker // is moved where the players can reach. A grid form replaces it on its cell with a poof. A friendly entity, one a @@ -97,7 +126,7 @@ bool game_enemy_devolve(Entity& entity, Entity** outEntity) bool isWalking = is_config_walking(g_manager->entityConfig.GetEntity(type, variant, form.subtype)); if (isFlying && isWalking && !is_reachable_from_player(room, {.position = entity.pos})) { - reconstruction_missing("Game::DevolveEnemy 00705480: Room::find_reachable_position 00823d10"); + entity.pos = reachable_position_find(room, entity.pos); entity.velocity = {}; } auto* devolved = static_cast(g_game->Spawn({.position = entity.pos, diff --git a/src/entity_player_actives_rebirth.cpp b/src/entity_player_actives_rebirth.cpp index 36b5f35..bdfc931 100644 --- a/src/entity_player_actives_rebirth.cpp +++ b/src/entity_player_actives_rebirth.cpp @@ -27,6 +27,7 @@ #include constexpr float NECRONOMICON_DAMAGE = 40; +constexpr int PANDORA_COINS = 20; constexpr float NECRONOMICON_VERSUS_DAMAGE = 20; constexpr float NECRONOMICON_VERSUS_PAGE_DAMAGE = 10; constexpr int NECRONOMICON_SHAKE = 15; @@ -1423,6 +1424,174 @@ static void diplopia_use(ItemUse& use) for (Entity* wisp : entity_query(ENTITY_FAMILIAR, Entity_Familiar::WISP)) player.AddWisp(wisp->subtype, player.pos, false, false); } + +// What Pandora's Box holds: count pickups of a variant and subtype, each at a free spot near the player. +struct BoxPickups +{ + int count = 1; + int subType = 1; + int variant = PICKUP_HEART; +}; + +// Pandora's Box puts a pickup at a free spot near the player, seeded by the box. +static void box_pickup_spawn(Entity_Player& player, const BoxPickups& pickup, uint32_t seed) +{ + Vector spot = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_SPOT_STEP}); + g_game->Spawn({.position = spot, .spawner = &player, .subType = pickup.subType, .type = ENTITY_PICKUP, + .variant = pickup.variant, .seed = seed}); +} + +// Pandora's Box spills pickups. +static void box_pickups_spawn(Entity_Player& player, const BoxPickups& pickups) +{ + for (int i = 0; i < pickups.count; i++) + box_pickup_spawn(player, pickups, player.GetCollectibleRNG(COLLECTIBLE_BLUE_BOX).Next()); +} + +// Pandora's Box puts count collectibles from a pool on pedestals. +static void box_collectibles_spawn(Entity_Player& player, ItemPoolType pool, int count) +{ + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_BLUE_BOX); + for (int i = 0; i < count; i++) + { + uint32_t seed = rng.Next(); + int item = g_game->itemPool.GetCollectible(pool, rng.Next(), 0, 0, 0); + box_pickup_spawn(player, {.subType = item, .variant = PICKUP_COLLECTIBLE}, seed); + } +} + +// Pandora's Box with the Strange Key: the key goes, and a collectible comes from each of the first pools of a shuffled +// list (six, eight or ten with the key's multiplier). The original reads an unset tenth pool with a tripled key in +// Greed mode. Here the draws stop at the end of the list. +static void strange_key_open(Entity_Player& player) +{ + constexpr std::array NORMAL_POOLS = {POOL_TREASURE, POOL_BOSS, POOL_SHOP, POOL_DEVIL, POOL_ANGEL, + POOL_LIBRARY, POOL_GOLDEN_CHEST, POOL_CURSE, POOL_PLANETARIUM, + POOL_SECRET}; + constexpr std::array GREED_POOLS = {POOL_GREED_TREASURE, POOL_GREED_BOSS, POOL_GREED_SHOP, + POOL_GREED_DEVIL, POOL_GREED_ANGEL, POOL_LIBRARY, + POOL_GOLDEN_CHEST, POOL_GREED_CURSE, POOL_PLANETARIUM}; + int multiplier = player.GetTrinketMultiplier(TRINKET_STRANGE_KEY); + int count = multiplier == 2 ? 8 : multiplier == 3 ? 10 : 6; + player.TryRemoveTrinket(TRINKET_STRANGE_KEY); + std::vector pools = g_game->IsGreedMode() + ? std::vector(GREED_POOLS.begin(), GREED_POOLS.end()) + : std::vector(NORMAL_POOLS.begin(), NORMAL_POOLS.end()); + + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_BLUE_BOX); + for (size_t i = 0; i + 1 < pools.size(); i++) + if (uint32_t offset = rng.RandomInt((uint32_t)(pools.size() - i)); offset != 0) + std::swap(pools[i], pools[i + offset]); + for (int i = 0; i < std::min(count, (int)pools.size()); i++) box_collectibles_spawn(player, pools[i], 1); +} + +// What Pandora's Box gives on a Greed mode floor, by the floor. +static void greed_box_open(Entity_Player& player, int stage) +{ + switch (stage) + { + case 1: + box_pickups_spawn(player, {.count = 2, .variant = PICKUP_KEY}); + return box_pickups_spawn(player, {.count = 2, .variant = PICKUP_BOMB}); + case 2: + box_collectibles_spawn(player, POOL_BOSS, 1); + return box_pickups_spawn(player, {.count = 2, .subType = HEART_SOUL}); + case 3: + return box_pickups_spawn(player, {.count = PANDORA_COINS, .variant = PICKUP_COIN}); + case 4: + return box_collectibles_spawn(player, POOL_BOSS, 2); + case 5: + box_collectibles_spawn(player, POOL_DEVIL, 1); + return box_pickups_spawn(player, {.subType = HEART_BLACK}); + case 6: + case 7: + return box_pickups_spawn(player, {.variant = PICKUP_COIN}); + default: + log_printf(LOG_INFO, "[warn] Blue Box, can't generate a specific collectible for the current stage %d\n", stage); + } +} + +// What Pandora's Box gives, by the floor: hearts, keys and bombs, coins, boss items, the Bible, a devil or angel deal +// (by the floor's side), the Moving Box unlocked, nothing in the Chest, or the Red Key on the Home floor. +static void box_open(Entity_Player& player, int stage) +{ + switch (stage) + { + case 1: + return box_pickups_spawn(player, {.count = 2, .subType = HEART_SOUL}); + case 2: + box_pickups_spawn(player, {.count = 2, .variant = PICKUP_KEY}); + return box_pickups_spawn(player, {.count = 2, .variant = PICKUP_BOMB}); + case 3: + return box_collectibles_spawn(player, POOL_BOSS, 1); + case 4: + box_collectibles_spawn(player, POOL_BOSS, 1); + return box_pickups_spawn(player, {.count = 2, .subType = HEART_SOUL}); + case 5: + return box_pickups_spawn(player, {.count = 4, .subType = HEART_SOUL}); + case 6: + return box_pickups_spawn(player, {.count = PANDORA_COINS, .variant = PICKUP_COIN}); + case 7: + return box_collectibles_spawn(player, POOL_BOSS, 2); + case 8: + return box_pickups_spawn(player, {.subType = COLLECTIBLE_BIBLE, .variant = PICKUP_COLLECTIBLE}); + case 10: + if (!g_game->IsAltStage()) + { + box_collectibles_spawn(player, POOL_DEVIL, 1); + return box_pickups_spawn(player, {.subType = HEART_BLACK}); + } + box_collectibles_spawn(player, POOL_ANGEL, 1); + return box_pickups_spawn(player, {.subType = HEART_ETERNAL}); + case 11: + if (g_game->IsAltStage()) return box_pickups_spawn(player, {.variant = PICKUP_COIN}); + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_MOVING_BOX); + return; + case 12: + return; + case 13: + if (!g_manager->persistentGameData.Unlocked(ACHIEVEMENT_RED_KEY)) + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_RED_KEY); + return box_pickups_spawn(player, {.subType = COLLECTIBLE_RED_KEY, .variant = PICKUP_COLLECTIBLE}); + default: + log_printf(LOG_INFO, "[warn] Blue Box, can't generate a specific collectible for the current stage %d\n", stage); + } +} + +// Pandora's Box: opened by a main player, it gives what the floor holds (or the Strange Key's collectibles), one wisp +// per floor past the first with Book of Virtues and a devil familiar with Judas's kept Book of Belial. It goes once +// owned, or used through the Void. +static void pandoras_box_use(ItemUse& use) +{ + constexpr std::array BELIAL_FAMILIARS = {278, 113, 360, 275, 417, 679, 565, 698}; + Entity_Player& player = use.player; + if (player.variant != PLAYER_VARIANT_PLAYER) return use_animate(use); + + sound_play_local(player, SOUND_PANDORAS_BOX); + if (use.request.flags & (USE_OWNED | USE_VOID)) use.result.isRemove = true; + int stage = g_game->stage; + if (player.HasTrinket(TRINKET_STRANGE_KEY)) strange_key_open(player); + else if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (Pandora's Box in a versus match)"); + else if (g_game->IsGreedMode()) greed_box_open(player, stage); + else box_open(player, stage); + + if (is_wisp_use(use)) + for (int i = 0; i < stage - 1; i++) player.AddWisp(COLLECTIBLE_BLUE_BOX, player.pos, false, false); + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) + { + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_BLUE_BOX); + int familiar = g_game->itemPool.GetCollectibleFromList(BELIAL_FAMILIARS, rng.Next(), COLLECTIBLE_DEMON_BABY, + LIST_PICK_BLACKLIST); + uint32_t seed = rng.Next(); + Vector spot = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_SPOT_STEP}); + g_game->Spawn({.position = spot, .subType = familiar, .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE, + .seed = seed}) + ->Update(); + } + use_animate(use); +} + // Runs the own effect of a Rebirth or early Afterbirth active (below 400) the main dispatch does not case. The ones not // written yet stop the game. void rebirth_item_effect_run(ItemUse& use) @@ -1524,6 +1693,8 @@ void rebirth_item_effect_run(ItemUse& use) return undefined_use(use); case COLLECTIBLE_VENTRICLE_RAZOR: return ventricle_razor_use(use); + case COLLECTIBLE_BLUE_BOX: + return pandoras_box_use(use); default: return active_missing_report(use); } diff --git a/src/entity_player_actives_repentance.cpp b/src/entity_player_actives_repentance.cpp index 0a7dbf2..eb0d148 100644 --- a/src/entity_player_actives_repentance.cpp +++ b/src/entity_player_actives_repentance.cpp @@ -1726,3 +1726,58 @@ void repentance_item_effect_run(ItemUse& use) return afterbirth_item_effect_run(use); } } + +// 007711a0 Whether the Void, held in an active slot, has absorbed a collectible. +bool Entity_Player::VoidHasCollectible(int id) +{ + auto isVoid = [](ActiveItemDesc& active) { return active.item == COLLECTIBLE_VOID; }; + if (std::ranges::none_of(activeItems, isVoid)) return false; + return std::ranges::find(voidedCollectibles, id) != voidedCollectibles.end(); +} + +// 007b9e10 Spends one of Glowing Hourglass' rewinds, or with isRefill gives them all back: in the held hourglasses +// (a refill only ever reaching the first slot's), in a Void that absorbed one (emptied by a spend), and in the +// hourglasses packed in a Moving Box. One rewind at most is spent. True when it was. +bool Entity_Player::TryDecreaseGlowingHourglassUses(bool isDecrease, bool isRefill) +{ + bool isDecreased = false; + auto spend = [&](Charge& varData) + { + if (isRefill) varData = (Charge)GLOWING_HOUR_GLASS_REWINDS; + else if (isDecrease && (int)varData < GLOWING_HOUR_GLASS_REWINDS) + { + varData++; + isDecreased = true; + isDecrease = false; + } + }; + + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + { + ActiveItemDesc& active = activeItems[slot]; + if (active.item == COLLECTIBLE_GLOWING_HOUR_GLASS && active.varData < GLOWING_HOUR_GLASS_REWINDS) + spend(isRefill ? activeItems[0].varData : active.varData); + else if (active.item == COLLECTIBLE_VOID && VoidHasCollectible(COLLECTIBLE_GLOWING_HOUR_GLASS) && isDecrease) + { + SetActiveCharge(0, slot); + isDecreased = true; + isDecrease = false; + } + } + if (movingBoxContents.empty() || !HasCollectible(COLLECTIBLE_MOVING_BOX)) return isDecreased; + + for (EntitySaveState& saved : movingBoxContents) + { + bool isHourglass = saved.type == ENTITY_PICKUP && saved.variant == PICKUP_COLLECTIBLE && + saved.subtype == COLLECTIBLE_GLOWING_HOUR_GLASS; + if (isHourglass) spend(saved.intStorage8); + } + return isDecreased; +} + +// 005b1a20 Mom's Bracelet's grab: the grid entity ahead (lifted through Room::CanPickupGridEntity and +// PickupGridEntity), else an enemy, host or shot within reach, held over the head. +void Entity_Player::moms_bracelet_grab() +{ + reconstruction_missing("Entity_Player::moms_bracelet_grab 005b1a20"); +} diff --git a/src/entity_player_characters.cpp b/src/entity_player_characters.cpp index 136b039..4b3d00a 100644 --- a/src/entity_player_characters.cpp +++ b/src/entity_player_characters.cpp @@ -60,13 +60,7 @@ constexpr int NPC_TYPE_LAST = 999; constexpr int ROOM_IDX_DEBUG = -16; constexpr float FORGOTTEN_CHAIN_SCALE = 120; constexpr int MAGDALENE_PILL_TRIES = 10; -constexpr int REVIVE_DAMAGE_COOLDOWN = 90; constexpr int COOP_REVIVE_DAMAGE_COOLDOWN = 150; -constexpr int LAZARUS_RISEN_MAX_HEARTS = 2; -constexpr int LAZARUS_BIRTHRIGHT_STEW_FRAMES = 1800; -constexpr int POOF_LARGE_SUBTYPE = 3; -constexpr int COLLECTIBLE_GUPPYS_COLLAR_RNG = 212; -constexpr int TRINKET_BROKEN_ANKH_RNG = 28; constexpr int SOUL_CHARGE_HEART_CONTAINERS = 2; constexpr int KEEPER_START_COIN_HEARTS = 4; constexpr float INDICATOR_SCREEN_WIDTH = 338; @@ -77,6 +71,15 @@ constexpr float INDICATOR_SCALE = 0.65f; constexpr float INDICATOR_BOTTOM_MARGIN = 10; constexpr float INDICATOR_FADE_START = 10; constexpr float INDICATOR_FADE_LENGTH = 140; +constexpr float INDICATOR_SHRINK_START = 30; +constexpr float INDICATOR_SHRINK_LENGTH = 250; +constexpr float INDICATOR_ICON_SCALE = 2; +constexpr float INDICATOR_HUD_SHIFT_X = 28; +constexpr float INDICATOR_HUD_SHIFT_Y = 12; +constexpr float INDICATOR_MARGIN_X = 10; +constexpr float INDICATOR_MARGIN_Y = 16; +constexpr float INDICATOR_BOTTOM_REACH = 35; +constexpr float INDICATOR_RISE = -18; constexpr std::string_view FORGOTTEN_BOMB_SHEET = "gfx/characters/costumes/character_016b_theforgotten_bomb.png"; // The damage each character type adds as a share of its damage (the exe's table at 00b6bce8). @@ -612,7 +615,7 @@ bool is_twin_button_blocked(Entity_Player& player, TwinButton button) } // The Render part (0078ca00) that points at a co-op player outside the screen: its character's icon at the screen's -// edge, faded in over 140 past the edge. The icon is HUD::render_player_type_icon, which stops the game when shown. +// edge once 10 past it, shrinking from double size over 250 past 30, outlined in its player color. void Entity_Player::coop_indicator_render() { Room& room = *g_game->room; @@ -626,8 +629,20 @@ void Entity_Player::coop_indicator_render() float edgeX = std::min(std::max(x, 0.0f), g_screenWidth); float edgeY = std::min(std::max(y, 0.0f), g_screenHeight + INDICATOR_BOTTOM_MARGIN); float distance = std::sqrt((y - edgeY) * (y - edgeY) + (x - edgeX) * (x - edgeX)); - if (std::clamp((distance - INDICATOR_FADE_START) / INDICATOR_FADE_LENGTH, 0.0f, 1.0f) > 0) - reconstruction_missing("HUD::render_player_type_icon 009a6660 (the co-op player indicator)"); + if (std::clamp((distance - INDICATOR_FADE_START) / INDICATOR_FADE_LENGTH, 0.0f, 1.0f) <= 0) return; + + float hudOffset = g_manager->optionsConfig.hudOffset; + float marginX = hudOffset * INDICATOR_HUD_SHIFT_X + INDICATOR_MARGIN_X; + float marginY = hudOffset * INDICATOR_HUD_SHIFT_Y + INDICATOR_MARGIN_Y; + float shrink = std::clamp((distance - INDICATOR_SHRINK_START) / INDICATOR_SHRINK_LENGTH, 0.0f, 1.0f); + float iconScale = INDICATOR_ICON_SCALE - shrink; + x = std::min(std::max(x, marginX), g_screenWidth - marginX); + y = std::min(std::max(y, marginY + INDICATOR_BOTTOM_MARGIN), + g_screenHeight - marginY - INDICATOR_BOTTOM_MARGIN + INDICATOR_BOTTOM_REACH); + g_game->hud.render_player_type_icon({.color = g_game->playerManager.player_color_mod_get(*this), + .position = vector_make(x - iconScale * 0.5f, y + INDICATOR_RISE - 2 * shrink), + .scale = iconScale, + .playerType = playerType}); } // 007c3620 Takes off the costume the character's config dresses it in. @@ -678,92 +693,6 @@ void Entity_Player::Revive() if (LayerState* extra = sprite.GetLayer(PLAYER_LAYER_EXTRA)) extra->isVisible = true; } -// 007a23a0 Revives the player by a collectible's rule, the owner of the collectible playing its part. Only Lazarus' -// Rags (Lazarus' own rising) is reconstructed: the player is dressed as Lazarus Risen (unless already Lazarus), -// keeps a container fewer (two at least) filled with a red heart, rises as Lazarus Risen (the tainted Lazaruses stay -// themselves) with Lazarus' boost, Red Stew's effect with his Birthright, and a poof. It stays vulnerable for 90 frames -// at least. -void Entity_Player::collectible_revive(int collectible, bool isOwner) -{ - Game& game = *g_game; - ItemConfig& items = g_manager->itemConfig; - - if (playerIndex >= 0) Revive(); - if (collectible != COLLECTIBLE_LAZARUS_RAGS) - reconstruction_missing(("Entity_Player::collectible_revive 007a23a0 (collectible " + std::to_string(collectible) + - (isOwner ? ", owner)" : ")")) - .c_str()); - - if (playerType != PLAYER_LAZARUS) - { - if (playerType != PLAYER_THEFORGOTTEN_B) RemoveSkinCostume(); - AddCostume(items.GetCollectible(COLLECTIBLE_LAZARUS_RAGS), false); - } - soulHearts = 0; - blackHearts = 0; - eternalHearts = 0; - maxHearts = std::max(maxHearts - 2, LAZARUS_RISEN_MAX_HEARTS); - boneHeartsMask = 0; - boneHearts = 0; - redHearts = std::min(maxHearts, LAZARUS_RISEN_MAX_HEARTS); - rottenHearts = 0; - if (HasCollectible(COLLECTIBLE_BIRTHRIGHT) && playerType == PLAYER_LAZARUS) - redStewBonusDuration = LAZARUS_BIRTHRIGHT_STEW_FRAMES; - if (playerType != PLAYER_LAZARUS_B && playerType != PLAYER_LAZARUS2_B) playerType = PLAYER_LAZARUS2; - cacheFlags |= CACHE_ALL; - temporaryEffects.AddNullEffect(NULLITEM_LAZARUS_BOOST, true, 1); - update_player_skin(); - EvaluateItems(); - if (forgottenBody) pos = forgottenBody->pos; - Entity* poof = game.Spawn({.position = pos, - .spawner = this, - .subType = POOF_LARGE_SUBTYPE, - .type = ENTITY_EFFECT, - .variant = EFFECT_POOF01, - .seed = Random()}); - poof->renderDepthOffset = posOffset.y + 1; - - isVisible = true; - damageCooldown = std::max(damageCooldown, REVIVE_DAMAGE_COOLDOWN); - UpdateHeartDependentEffects(); - if (game.deathmatchManager.is_active() || isDead || goldenHearts <= 0) return; - int holders = (std::min(redHearts, maxHearts) + 1) / 2 + (soulHearts + 1) / 2 + boneHearts; - if (holders >= goldenHearts) return; - BreakGoldenHearts(goldenHearts - holders); - goldenHearts = holders; -} - -// The end of 007a1090 once the first of the pair lives again: Judas' Birthright makes a Judas saved by Plan C Black -// Judas, the first player's old character lets go of what it brought, and each player rolls Guppy's Collar's and Broken -// Ankh's generators, gets its Forgotten half back and settles whether it can shoot and its color. -void revived_players_settle(std::vector& players, int oldType) -{ - Entity_Player& first = *players[0]; - - if (oldType == PLAYER_JUDAS && first.playerType != PLAYER_BLACKJUDAS && first.HasCollectible(COLLECTIBLE_BIRTHRIGHT) && - first.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_PLAN_C)) - { - if (ItemConfig_Item* planC = g_manager->itemConfig.GetCollectible(COLLECTIBLE_PLAN_C)) - first.temporaryEffects.RemoveEffect(planC, -1); - first.maxHearts = 0; - first.redHearts = 0; - first.playerType = PLAYER_BLACKJUDAS; - first.cacheFlags |= CACHE_ALL; - first.update_player_skin(); - first.EvaluateItems(); - first.TryPreventDeath(); - } - first.player_type_change_prepare(oldType); - for (Entity_Player* player : players) - { - player->GetCollectibleRNG(COLLECTIBLE_GUPPYS_COLLAR_RNG).Next(); - player->GetTrinketRNG(TRINKET_BROKEN_ANKH_RNG).Next(); - player->init_forgotten_twin(); - player->UpdateCanShoot(); - player->ResetColor(); - } -} - // 007cf610 Lets go of what the old character brought once the player became another: a twin it had (Jacob's Esau, // Tainted Forgotten's soul, Tainted Lazarus' other form) unless the twin is that character, Tainted Isaac's inventory // and Tainted Jacob's curse (not reconstructed yet), Tainted Forgotten's flight, and its pocket active for the new @@ -1321,3 +1250,56 @@ void birthright_gain(Entity_Player& player, bool isFirstTime) reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (this character's Birthright)"); } } + +// 007a37c0 Lets the twin go (Jacob's Esau, Tainted Lazarus' other form, the Forgotten's other half), the stored backup +// player when there is no twin: its effects end and, unless it is Tainted Forgotten's soul, the player takes over its +// passive collectibles (dressing in their costumes), its smelted trinkets, pill uses, voided items and history. A backup +// player is deleted, a twin leaves the room. +// The original reads a missing backup player and crashes. Without either, nothing happens. +void Entity_Player::remove_twin() +{ + Entity_Player* twin = twin_get(); + bool isBackup = !twin; + + if (isBackup) twin = backupPlayer; + if (!twin) return; + twin->temporaryEffects.ClearEffects(true); + if (twin->playerType != PLAYER_THESOUL_B) + { + ItemConfig& items = g_manager->itemConfig; + for (size_t id = 0; id < collectibleCounts.size(); id++) + { + ItemConfig_Item* item = items.GetCollectible((int)id); + if (!item || item->type == ITEM_ACTIVE || twin->collectibleCounts[id] <= 0) continue; + collectibleCounts[id] += std::exchange(twin->collectibleCounts[id], 0); + if (item->isAddCostumeOnPickup) AddCostume(item, false); + } + for (size_t id = 0; id < smeltedTrinkets.size(); id++) + { + SmeltedTrinket& own = smeltedTrinkets[id]; + SmeltedTrinket& other = twin->smeltedTrinkets[id]; + bool isOtherHeld = other.count > 0 || other.goldenCount > 0; + if (isOtherHeld && own.count < 1 && own.goldenCount < 1) + AddCostume(items.GetTrinket((uint32_t)id & TRINKET_ID_MASK), false); + own.count += other.count; + own.goldenCount += other.goldenCount; + other = {}; + } + for (size_t id = 0; id < pillEffectUses.size(); id++) + if (twin->pillEffectUses[id] > 0) pillEffectUses[id] += std::exchange(twin->pillEffectUses[id], 0); + voidedCollectibles.insert(voidedCollectibles.end(), twin->voidedCollectibles.begin(), twin->voidedCollectibles.end()); + voidedPassives.insert(voidedPassives.end(), twin->voidedPassives.begin(), twin->voidedPassives.end()); + history.merge(twin->history); + cacheFlags |= CACHE_ALL; + temporaryEffects.isEvaluateCachePending = true; + } + + if (isBackup) + { + backupPlayer->ClearReferences(); + delete std::exchange(backupPlayer, nullptr); + return; + } + twinPlayer = nullptr; + g_game->playerManager.RemoveCoPlayer(twin); +} diff --git a/src/entity_player_characters.h b/src/entity_player_characters.h index 89a0d44..5ca2319 100644 --- a/src/entity_player_characters.h +++ b/src/entity_player_characters.h @@ -63,9 +63,6 @@ void birthright_gain(Entity_Player& player, bool isFirstTime); // Cambion Conception's count of hits (part of 007729d0). void cambion_conception_hit(Entity_Player& player); -// The end of a death that revived the first of the pair (007a1090). -void revived_players_settle(std::vector& players, int oldType); - // Eve's Dead Bird and Samson's Bloody Lust answering a hit (007729d0). void character_items_hit(Entity_Player& player); diff --git a/src/entity_player_collectibles.cpp b/src/entity_player_collectibles.cpp index 7884e90..6073bc7 100644 --- a/src/entity_player_collectibles.cpp +++ b/src/entity_player_collectibles.cpp @@ -173,7 +173,8 @@ static void collectible_last_removed(Entity_Player& player, int collectibleId) player.update_greeds_gullet(); return; case COLLECTIBLE_ROCK_BOTTOM: - reconstruction_missing("Entity_Player::TriggerCollectibleRemoved 0078ff90 (Rock Bottom, FUN_007d3e00)"); + player.rock_bottom_reset(); + return; case COLLECTIBLE_RED_KEY: g_game->room->UpdateRedKey(); return; @@ -399,24 +400,84 @@ void Entity_Player::RemoveCollectible(int type, bool isIgnoreModifiers, int acti UpdateBookOfVirtues(false); } -// 007ab380 Holds a collectible up over the head: the pedestal's sprite showing the item plays its animation (left -// alone when it already shows it), lifted a little, while the player plays its own. +// Shows an item over the player's head: the pedestal's sprite with the item's graphics plays its animation (left alone +// when it already shows it), lifted a little. +static void held_sprite_show(Entity_Player& player, const std::string& gfx, std::string_view spriteAnimName) +{ + ANM2& held = player.heldSprite; + + held.Reset(); + held.Load(g_manager->entityConfig.GetEntity(ENTITY_PICKUP, PICKUP_COLLECTIBLE, 0)->anm2Path, GRAPHICS_DEFER); + held.ReplaceSpritesheet(1, gfx); + held.LoadGraphics(); + held.Play(spriteAnimName); + held.offset = vector_make(0, HELD_SPRITE_RISE); +} + +// 00721c80 Merges another player's history into this one by pickup time, this one's first on a tie, unless locked. +void History::merge(History& other) +{ + if (isLocked) return; + + std::vector own = std::move(historyItems); + historyItems.clear(); + auto isEarlier = [](const HistoryItem& a, const HistoryItem& b) { return a.time < b.time; }; + std::ranges::merge(own, other.historyItems, std::back_inserter(historyItems), isEarlier); + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); +} + +// 007ab380 Holds a collectible up over the head while the player plays its own animation. void Entity_Player::AnimateCollectible(int collectibleId, std::string_view animName, std::string_view spriteAnimName) { ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); if (!item) return; - heldSprite.Reset(); - EntityConfig_Entity* pedestal = g_manager->entityConfig.GetEntity(ENTITY_PICKUP, PICKUP_COLLECTIBLE, 0); - heldSprite.Load(pedestal->anm2Path, GRAPHICS_DEFER); if (collectibleId < 0) reconstruction_missing("Entity_Player::AnimateCollectible 007ab380 (a procedural item)"); - heldSprite.ReplaceSpritesheet(1, item->gfxFilename); - heldSprite.LoadGraphics(); - heldSprite.Play(spriteAnimName); - heldSprite.offset = vector_make(0, HELD_SPRITE_RISE); + held_sprite_show(*this, item->gfxFilename, spriteAnimName); PlayExtraAnimation(animName); } +// 007ab550 Holds a trinket up over the head while the player plays its own animation. +void Entity_Player::AnimateTrinket(int trinketId, std::string_view animName, std::string_view spriteAnimName) +{ + ItemConfig_Item* item = g_manager->itemConfig.GetTrinket((uint32_t)trinketId & TRINKET_ID_MASK); + if (!item) return; + + held_sprite_show(*this, item->gfxFilename, spriteAnimName); + PlayExtraAnimation(animName); +} + +// 007abc00 Plays the jump down a trapdoor. +void Entity_Player::AnimateTrapdoor() +{ + PlayExtraAnimation("Trapdoor"); +} + +// 007abc10 Plays the rise up a beam of light. +void Entity_Player::AnimateLightTravel() +{ + PlayExtraAnimation("LightTravel"); +} + +// 007abcb0 Plays the appearance. +void Entity_Player::AnimateAppear() +{ + PlayExtraAnimation("Appear"); +} + +// 007539c0 Sets the extra animation to play once the current one ends. +void Entity_Player::QueueExtraAnimation(std::string_view animName) +{ + queuedExtraAnimation = animName; +} + +// 0058e230 Ends the extra and item animations. +void Entity_Player::StopExtraAnimation() +{ + isPlayingExtraAnimation = false; + isPlayingItemAnimation = false; +} + // 0075eff0 How many collectibles the player has, counting copies. int Entity_Player::GetCollectibleCount() { diff --git a/src/entity_player_costumes.cpp b/src/entity_player_costumes.cpp index b681aca..8c102d8 100644 --- a/src/entity_player_costumes.cpp +++ b/src/entity_player_costumes.cpp @@ -406,6 +406,55 @@ void Entity_Player::ClearCollectibleAnim(int collectible) if (map.index >= 0 && costumeSpriteDescs[map.index].item == item) costumeSpriteDescs[map.index].isItemAnimPlay = false; } +// 0075a3e0 Plays an animation on a null item's head costumes, marking them as playing its own animation: switched to +// keeping the frame when frame is below -1, played unforced otherwise. Costumes with an overlay play its _Overlay +// alike. +void Entity_Player::play_null_costume_anim(int nullItem, std::string_view animation, int frame) +{ + ItemConfig_Item* item = g_manager->itemConfig.GetNullItem(nullItem); + std::string overlay = std::string(animation) + "_Overlay"; + for (PlayerCostumeMap& map : playerCostumeMap) + { + if (map.index < 0 || map.isBodyLayer) continue; + CostumeSpriteDesc& costume = costumeSpriteDescs[map.index]; + if (costume.item != item) continue; + + ANM2& sprite = costume.sprite; + costume.isItemAnimPlay = true; + if (frame < -1) sprite.SetAnimation(animation, SWITCH_KEEP_FRAME); + else sprite.Play(animation); + if (!costume.isHasOverlay) continue; + if (frame < -1) sprite.SetOverlayAnimation(overlay, SWITCH_KEEP_FRAME); + else sprite.PlayOverlay(overlay); + } +} + +// 007ad610 Ends a null item's own animation on its costumes (Hemoptysis's), but not on a co-op ghost. +void Entity_Player::ClearNullItemAnim(int nullItem) +{ + if (isCoopGhost) return; + ItemConfig_Item* item = g_manager->itemConfig.GetNullItem(nullItem); + for (PlayerCostumeMap& map : playerCostumeMap) + if (map.index >= 0 && costumeSpriteDescs[map.index].item == item) + costumeSpriteDescs[map.index].isItemAnimPlay = false; +} + +// 007ad720 Whether a null item's own animation ended on one of its costumes with a non looping animation. Unlike a +// collectible's, it is false when none plays it. +bool Entity_Player::IsNullItemAnimFinished(int nullItem, std::string_view animName) +{ + ItemConfig_Item* item = g_manager->itemConfig.GetNullItem(nullItem); + for (PlayerCostumeMap& map : playerCostumeMap) + { + if (map.index < 0) continue; + CostumeSpriteDesc& costume = costumeSpriteDescs[map.index]; + if (!costume.isItemAnimPlay || costume.item != item || !costume.sprite.IsFinished(animName)) continue; + const AnimationData* animation = costume.sprite.animState.animData; + if (!animation || !animation->isLooping) return true; + } + return false; +} + // 007ad680 Whether a collectible's own animation ended on its costumes: true at the first one done with a non looping // animation, or when none plays it. bool Entity_Player::IsCollectibleAnimFinished(int collectible, std::string_view animName) @@ -423,3 +472,9 @@ bool Entity_Player::IsCollectibleAnimFinished(int collectible, std::string_view } return isFinished; } + +// 007ad400 Takes off a null item's costume. +void Entity_Player::TryRemoveNullCostume(int nullId) +{ + RemoveCostume(g_manager->itemConfig.GetNullItem(nullId)); +} diff --git a/src/entity_player_crafting.cpp b/src/entity_player_crafting.cpp index e83fc6b..5bfd329 100644 --- a/src/entity_player_crafting.cpp +++ b/src/entity_player_crafting.cpp @@ -159,7 +159,6 @@ constexpr int BURST_TRINKET_ODDS = 100; constexpr int BURST_TRINKET_CHANCES[] = {33, 66, 100}; constexpr int ACHIEVEMENT_BONE_HEART_UNLOCK = 391; constexpr int ACHIEVEMENT_ROTTEN_HEART_UNLOCK = 411; -constexpr int ACHIEVEMENT_RED_KEY_UNLOCK = 415; constexpr int ACHIEVEMENT_GOLD_BOMB_UNLOCK = 226; // A trinket that may add one pickup to the burst, in the order they roll, with that pickup's variant. @@ -427,7 +426,7 @@ static BurstPickup burst_pool_pickup(Entity_Player& player, RNG& rng, int poolTy case POOL_GREED_SECRET: return gated(ACHIEVEMENT_BONE_HEART_UNLOCK, {PICKUP_HEART, HEART_BONE_SUBTYPE}); case POOL_RED_CHEST: - return gated(ACHIEVEMENT_RED_KEY_UNLOCK, {PICKUP_TAROTCARD, CRACKED_KEY_CARD}); + return gated(ACHIEVEMENT_RED_KEY, {PICKUP_TAROTCARD, CRACKED_KEY_CARD}); case POOL_CURSE: case POOL_GREED_CURSE: return gated(ACHIEVEMENT_ROTTEN_HEART_UNLOCK, {PICKUP_HEART, HEART_ROTTEN_SUBTYPE}); diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp index de46953..53b9903 100644 --- a/src/entity_player_damage.cpp +++ b/src/entity_player_damage.cpp @@ -1,3 +1,4 @@ +#include "boss_repentance.h" #include "boss_ai.h" #include "entity_bomb.h" #include "entity_combat.h" @@ -42,7 +43,6 @@ constexpr int SAMSON_B_HIT_CHARGE = 10000; constexpr int BLEED_OUT_HEALTH = 600; constexpr int SIREN_CHARM_SPARE_FRAMES = 29; -constexpr int VISAGE_CHAIN = 10; constexpr int WHITE_FIRE_VARIANT = 4; constexpr int EFFECT_SELF_DAMAGE = 19; constexpr int EFFECT_POISON_CLOUD = 123; @@ -1575,3 +1575,15 @@ void Entity_Player::set_last_damage(uint64_t damageFlags, const EntityRef& sourc lastDamageFlags = damageFlags; lastDamageSource = source; } + +// 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; +} diff --git a/src/entity_player_death.cpp b/src/entity_player_death.cpp index b74b9d4..08ea516 100644 --- a/src/entity_player_death.cpp +++ b/src/entity_player_death.cpp @@ -1,31 +1,30 @@ #include "game_over.h" +#include "boss_ai.h" +#include "entity_combat.h" +#include "entity_effect.h" #include "entity_familiar.h" #include "entity_list.h" +#include "entity_npc.h" #include "entity_player.h" #include "entity_player_characters.h" #include "game.h" #include "item_config.h" +#include "level.h" #include "log.h" #include "manager.h" +#include "persistent_game_data.h" #include "platform.h" #include "player_manager.h" #include "room.h" +#include "room_config.h" +#include "room_descriptor.h" #include "sfx_manager.h" #include #include #include -constexpr int COLLECTIBLE_ANKH = 161; -constexpr int COLLECTIBLE_JUDAS_SHADOW = 311; -constexpr int TRINKET_BROKEN_ANKH = 28; -constexpr int TRINKET_LOCUST_OF_WRATH = 113; -constexpr int TRINKET_LOCUST_OF_CONQUEST = 117; -constexpr int NULLITEM_BATWING_WINGS = 40; -constexpr int ACHIEVEMENT_THE_LOST = 82; -constexpr int CLOT_SUBTYPE_UNCOUNTED = 7; constexpr int SPECIAL_DAILY_SHUFFLED_ITEMS = 7; - constexpr float DEATH_FRICTION = 0.6f; constexpr int DEATH_FRAME_TWIN_FALLS = 7; constexpr int DEATH_FRAME_BONES_BREAK = 19; @@ -41,6 +40,75 @@ constexpr int POCKET_ACTIVE_FIRST_SLOT = 2; constexpr int CONQUEST_EXTRA_ROLL = 4; constexpr int CONQUEST_EXTRA_ROLL_DOUBLE = 5; +constexpr int DEAD_CAT_HEARTS = 2; +constexpr int REVIVE_DAMAGE_COOLDOWN = 90; +constexpr int REVIVE_SHOW_COOLDOWN = 120; +constexpr int LAZARUS_RISEN_MAX_HEARTS = 2; +constexpr int LAZARUS_BIRTHRIGHT_STEW_FRAMES = 1800; +constexpr int POOF_LARGE_SUBTYPE = 3; +constexpr int LOST_BIRTHRIGHT_GHOST_DAMAGE = 200; +constexpr float LOST_BIRTHRIGHT_GHOST_SCALE = 1.5f; +constexpr int LOST_BIRTHRIGHT_SHAKE = 14; +constexpr int INNER_CHILD_SHAKE = 6; +constexpr float INNER_CHILD_BOUNCE = 6; +constexpr float INNER_CHILD_DAMAGE = 35; +constexpr float INNER_CHILD_PLAYER_THRESHOLD = 50; +constexpr float INNER_CHILD_RADIUS = 60; +constexpr int STRAWMAN_SPIDERS = 5; +constexpr int DEATH_GIBS_LARGE = 14; +constexpr int DEATH_GIBS_SMALL = 8; +constexpr float DEATH_GIB_SPREAD = 80; +constexpr float LOUD_DEATH_VOLUME = 1.25f; +constexpr uint32_t BONE_GIB_FLAGS = GIB_FLAG_BLOOD | GIB_FLAG_BONE | GIB_FLAG_GUT | GIB_FLAG_EYE; +constexpr uint32_t BLOOD_GIB_FLAGS = GIB_FLAG_BLOOD | GIB_FLAG_BONE | GIB_FLAG_GUT; +constexpr const char* ANIMATION_PICKUP = "Pickup"; +constexpr const char* ANIMATION_PICKUP_SPARKLE = "PlayerPickupSparkle"; + +// How a revival comes about: each of the dying pair revives by the collectible (its holder as owner) or the first +// alone, the item used up or kept, Dead Cat losing a life, a trinket's revival, or a Missing Poster still locked. +enum RevivalKind +{ + REVIVAL_NONE, + REVIVAL_SOUL_OF_LAZARUS, + REVIVAL_EACH, + REVIVAL_EACH_KEPT, + REVIVAL_DEAD_CAT, + REVIVAL_FIRST, + REVIVAL_FIRST_KEPT, + REVIVAL_TRINKET, + REVIVAL_POSTER_LOCKED +}; + +// The revival a death finds: how it comes about, its item (a trinket for REVIVAL_TRINKET) and who holds it. +struct Revival +{ + Entity_Player* holder = nullptr; + int id = 0; + RevivalKind kind = REVIVAL_NONE; +}; + +// How a revived owner returns: the room restart's transition and what a helper player holds up instead. +struct RevivalReturn +{ + RoomTransitionAnim animation = TRANSITION_WALK; + int collectible = 0; + uint32_t trinket = 0; +}; + +// The character a revival turns the player into, unless it already is its tainted self, with its new hearts. +struct RevivalForm +{ + int blackHearts = 0; + int soulHearts = 0; + int playerType = 0; + int taintedType = 0; +}; + +constexpr RevivalForm ANKH_FORM = {.soulHearts = 6, .playerType = PLAYER_BLUEBABY, .taintedType = PLAYER_BLUEBABY_B}; +constexpr RevivalForm JUDAS_SHADOW_FORM = { + .blackHearts = -1, .soulHearts = 4, .playerType = PLAYER_BLACKJUDAS, .taintedType = PLAYER_JUDAS_B}; +constexpr RevivalForm MISSING_POSTER_FORM = {.soulHearts = 1, .playerType = PLAYER_THELOST, .taintedType = PLAYER_THELOST_B}; + // The player and its twin, the one with the lower player index first, as a death handles them together. static std::vector death_players_get(Entity_Player& player) { @@ -67,6 +135,21 @@ static Entity_Player* trinket_holder_find(std::vector& players, return found == players.end() ? nullptr : *found; } +// The first of the players with Soul of Lazarus' revival pending, else the first with the card in a pocket slot it +// uses. +static Entity_Player* soul_of_lazarus_holder_find(std::vector& players) +{ + for (Entity_Player* player : players) + if (player->temporaryEffects.HasNullEffect(NULLITEM_LAZARUS_SOUL_REVIVE)) return player; + for (Entity_Player* player : players) + for (uint32_t slot = 0; slot < player->GetMaxPocketItems(); slot++) + { + PocketItem& pocket = player->pocketItems[std::min(slot, POCKET_SLOT_COUNT - 1)]; + if (pocket.type == POCKET_CARD && pocket.id == CARD_SOUL_LAZARUS) return player; + } + return nullptr; +} + // Whether Missing Poster revives: once the Lost is unlocked, and always in a daily or debug run. static bool is_missing_poster_unlocked() { @@ -77,51 +160,532 @@ static bool is_missing_poster_unlocked() return manager.persistentGameData.achievements[ACHIEVEMENT_THE_LOST] || isExemptRun; } -constexpr const char* LAZARUS_RISING = "Lazarus rising"; - -// What revives a dying player and its twin, in the order the game tries them, or null. Broken Ankh's roll draws from -// its RNG even when the death is only checked. A Missing Poster still locked ends the search. -static const char* revival_find(Entity_Player& player, std::vector& players) +// Whether Broken Ankh's roll saves its holder: 22 in 100, 33 doubled, 50 with more. +static bool is_broken_ankh_saving(Entity_Player& holder) { - for (Entity_Player* each : players) - if (each->temporaryEffects.HasNullEffect(NULLITEM_LAZARUS_SOUL_REVIVE)) return "Soul of Lazarus's revival"; - for (Entity_Player* each : players) - for (uint32_t slot = 0; slot < each->GetMaxPocketItems(); slot++) - { - PocketItem& pocket = each->pocketItems[std::min(slot, POCKET_SLOT_COUNT - 1)]; - if (pocket.type == POCKET_CARD && pocket.id == CARD_SOUL_LAZARUS) return "Soul of Lazarus's revival"; - } + int multiplier = holder.GetTrinketMultiplier(TRINKET_BROKEN_ANKH); + int chance = multiplier >= 1 && multiplier <= 2 ? BROKEN_ANKH_CHANCES[multiplier - 1] : BROKEN_ANKH_CHANCE_MAX; - if (collectible_holder_find(players, COLLECTIBLE_1UP)) return "1up!'s revival"; - if (player.playerType == PLAYER_LAZARUS) return LAZARUS_RISING; - if (collectible_holder_find(players, COLLECTIBLE_DEAD_CAT)) return "Dead Cat's revival"; - if (collectible_holder_find(players, COLLECTIBLE_INNER_CHILD)) return "Inner Child's revival"; - Entity_Player* collar = collectible_holder_find(players, COLLECTIBLE_GUPPYS_COLLAR); - if (collar && collar->GetCollectibleRNG(COLLECTIBLE_GUPPYS_COLLAR)._seed & 1) return "Guppy's Collar's revival"; - if (collectible_holder_find(players, COLLECTIBLE_LAZARUS_RAGS)) return "Lazarus' Rags's revival"; - if (collectible_holder_find(players, COLLECTIBLE_ANKH)) return "Ankh's revival"; + return (int)holder.GetTrinketRNG(TRINKET_BROKEN_ANKH).RandomInt(BROKEN_ANKH_ROLL) < chance; +} - if (Entity_Player* ankh = trinket_holder_find(players, TRINKET_BROKEN_ANKH)) - { - int multiplier = ankh->GetTrinketMultiplier(TRINKET_BROKEN_ANKH); - int chance = multiplier >= 1 && multiplier <= 2 ? BROKEN_ANKH_CHANCES[multiplier - 1] : BROKEN_ANKH_CHANCE_MAX; - if ((int)ankh->GetTrinketRNG(TRINKET_BROKEN_ANKH).RandomInt(BROKEN_ANKH_ROLL) < chance) - return "Broken Ankh's revival"; - } - if (collectible_holder_find(players, COLLECTIBLE_JUDAS_SHADOW)) return "Judas' Shadow's revival"; - if (trinket_holder_find(players, TRINKET_MISSING_POSTER)) - return is_missing_poster_unlocked() ? "Missing Poster's revival" : nullptr; +// The revival that saves a dying player and its twin, in the order the game tries them. Broken Ankh's roll draws from +// its RNG even when the death is only checked, and a Missing Poster still locked ends the search. +static Revival revival_find(Entity_Player& player, std::vector& players) +{ + Entity_Player* holder = nullptr; + + if ((holder = soul_of_lazarus_holder_find(players))) return {holder, CARD_SOUL_LAZARUS, REVIVAL_SOUL_OF_LAZARUS}; + if ((holder = collectible_holder_find(players, COLLECTIBLE_1UP))) return {holder, COLLECTIBLE_1UP, REVIVAL_EACH}; + if (player.playerType == PLAYER_LAZARUS) return {players[0], COLLECTIBLE_LAZARUS_RAGS, REVIVAL_FIRST_KEPT}; + if ((holder = collectible_holder_find(players, COLLECTIBLE_DEAD_CAT))) + return {holder, COLLECTIBLE_DEAD_CAT, REVIVAL_DEAD_CAT}; + if ((holder = collectible_holder_find(players, COLLECTIBLE_INNER_CHILD))) + return {holder, COLLECTIBLE_INNER_CHILD, REVIVAL_EACH}; + holder = collectible_holder_find(players, COLLECTIBLE_GUPPYS_COLLAR); + if (holder && holder->GetCollectibleRNG(COLLECTIBLE_GUPPYS_COLLAR)._seed & 1) + return {holder, COLLECTIBLE_GUPPYS_COLLAR, REVIVAL_EACH_KEPT}; + if ((holder = collectible_holder_find(players, COLLECTIBLE_LAZARUS_RAGS))) + return {holder, COLLECTIBLE_LAZARUS_RAGS, REVIVAL_EACH}; + if ((holder = collectible_holder_find(players, COLLECTIBLE_ANKH))) return {holder, COLLECTIBLE_ANKH, REVIVAL_FIRST}; + holder = trinket_holder_find(players, TRINKET_BROKEN_ANKH); + if (holder && is_broken_ankh_saving(*holder)) return {holder, TRINKET_BROKEN_ANKH, REVIVAL_TRINKET}; + if ((holder = collectible_holder_find(players, COLLECTIBLE_JUDAS_SHADOW))) + return {holder, COLLECTIBLE_JUDAS_SHADOW, REVIVAL_FIRST}; + if ((holder = trinket_holder_find(players, TRINKET_MISSING_POSTER))) + return {holder, TRINKET_MISSING_POSTER, is_missing_poster_unlocked() ? REVIVAL_TRINKET : REVIVAL_POSTER_LOCKED}; if (player.playerType == PLAYER_THELOST_B && player.HasCollectible(COLLECTIBLE_BIRTHRIGHT)) - return "Tainted Lost's Birthright revival"; - return nullptr; + return {&player, COLLECTIBLE_BIRTHRIGHT, REVIVAL_FIRST}; + return {}; +} + +// Clears the hearts a revival replaces: soul, black, eternal, bone and rotten ones. +static void revive_hearts_clear(Entity_Player& player) +{ + player.soulHearts = 0; + player.blackHearts = 0; + player.eternalHearts = 0; + player.boneHeartsMask = 0; + player.boneHearts = 0; + player.rottenHearts = 0; +} + +// The least hearts a revival leaves: half a red heart in the containers (a whole coin heart for the Keepers), else a +// bone heart, two coin containers, Bethany's container half filled, or half a soul heart. +static void revive_hearts_least(Entity_Player& player) +{ + revive_hearts_clear(player); + if (player.maxHearts > 0) player.redHearts = player.GetHealthType() == HEALTH_COIN ? 2 : 1; + else if (player.GetHealthType() == HEALTH_BONE) + { + player.redHearts = 0; + player.AddBoneHearts(1); + } + else if (player.GetHealthType() == HEALTH_COIN) + { + player.redHearts = 2; + player.maxHearts = 2; + } + else if (player.playerType == PLAYER_BETHANY) + { + player.maxHearts = 2; + player.redHearts = 1; + } + else + { + player.redHearts = 0; + player.soulHearts = 1; + } +} + +// 1up!'s hearts: the character's starting soul and black hearts for soul characters, its starting bone hearts for bone +// ones, else the least hearts when it has no containers. The containers are filled after. +static void one_up_hearts_restore(Entity_Player& player) +{ + revive_hearts_clear(player); + HealthType health = player.GetHealthType(); + EntityConfig& config = g_manager->entityConfig; + + if (health == HEALTH_SOUL) + { + player.maxHearts = 0; + player.soulHearts = config.GetPlayer(player.playerType)->armor; + player.AddBlackHearts(config.GetPlayer(player.playerType)->blackHeart); + } + else if (health == HEALTH_BONE) + { + player.redHearts = 0; + player.AddBoneHearts(config.GetPlayer(player.playerType)->heart / 2); + } + else if (player.maxHearts == 0) revive_hearts_least(player); + player.SetFullHearts(); +} + +// Dead Cat's hearts: two soul hearts for soul characters, a bone heart filled red for bone ones, half a soul heart +// without health, else a full container. Its sub player (the Forgotten's soul) revives with it. +static void dead_cat_hearts_restore(Entity_Player& player) +{ + revive_hearts_clear(player); + HealthType health = player.GetHealthType(); + + if (health == HEALTH_SOUL) + { + player.maxHearts = 0; + player.soulHearts = DEAD_CAT_HEARTS; + } + else if (health == HEALTH_NO_HEALTH) player.soulHearts = 1; + else + { + if (health == HEALTH_BONE) player.AddBoneHearts(1); + else player.maxHearts = DEAD_CAT_HEARTS; + player.redHearts = DEAD_CAT_HEARTS; + } + if (player.subPlayer) player.subPlayer->collectible_revive(COLLECTIBLE_DEAD_CAT, false); +} + +// Turns the revived player into the revival's character with its hearts, the costumes and stats following. +static void revive_form_take(Entity_Player& player, const RevivalForm& form) +{ + player.RemoveSkinCostume(); + revive_hearts_clear(player); + player.maxHearts = 0; + player.redHearts = 0; + if (player.playerType != form.taintedType) player.playerType = form.playerType; + player.soulHearts = form.soulHearts; + player.blackHearts = form.blackHearts; + if (form.blackHearts) player.UpdateBlackHeartMask(); + player.cacheFlags |= CACHE_ALL; + player.EvaluateItems(); + player.update_player_skin(); +} + +// Whether the room is the Beast's, where a revival does not restart the room. +static bool is_beast_room() +{ + RoomConfig_Room* data = g_game->room->descriptor->data; + return data && data->type == ROOM_DUNGEON && data->stageId == STAGE_ID_HOME; +} + +// The revived owner's return: a helper player holds up what saved it, any other restarts the last room through the +// revival's transition, except in the Beast's room. True when the room restarts. +static bool revive_return(Entity_Player& player, const RevivalReturn& revival) +{ + Game& game = *g_game; + + if (player.parent) + { + player.isVisible = true; + player.damageCooldown = REVIVE_SHOW_COOLDOWN; + if (revival.trinket) player.AnimateTrinket(revival.trinket, ANIMATION_PICKUP, ANIMATION_PICKUP_SPARKLE); + else player.AnimateCollectible(revival.collectible, ANIMATION_PICKUP, ANIMATION_PICKUP_SPARKLE); + return false; + } + if (is_beast_room()) return false; + + game.leaveDoor = game.enterDoor < 0 ? -1 : std::min(game.enterDoor, DOOR_SLOT_COUNT - 1); + game.StartRoomTransition({.player = &player, + .animation = revival.animation, + .direction = (Direction)(game.enterDoor % 4), + .roomIndex = game.lastRoomIdx}); + return true; +} + +// The end of every revival: seen again and safe for 90 frames at least unless the room restarts, then the effects +// that follow the hearts and the golden hearts left without a heart break. +static void revive_finish(Entity_Player& player, bool isRestarting) +{ + if (!isRestarting) + { + player.isVisible = true; + player.damageCooldown = std::max(player.damageCooldown, REVIVE_DAMAGE_COOLDOWN); + } + player.UpdateHeartDependentEffects(); + player.ClampGoldenHearts(false); +} + +// Lazarus' Rags' rising: dressed as Lazarus Risen (unless Lazarus), a container fewer (two at least) filled with up +// to two red hearts, Red Stew's effect with Lazarus' Birthright, Lazarus Risen (the tainted Lazaruses stay themselves) +// with his boost, and a large poof at the Forgotten's body or the player. +static void lazarus_rise(Entity_Player& player) +{ + ItemConfig& items = g_manager->itemConfig; + + if (player.playerType != PLAYER_LAZARUS) + { + if (player.playerType != PLAYER_THEFORGOTTEN_B) player.RemoveSkinCostume(); + player.AddCostume(items.GetCollectible(COLLECTIBLE_LAZARUS_RAGS), false); + } + revive_hearts_clear(player); + player.maxHearts = std::max(player.maxHearts - 2, LAZARUS_RISEN_MAX_HEARTS); + player.redHearts = std::min(player.maxHearts, LAZARUS_RISEN_MAX_HEARTS); + if (player.HasCollectible(COLLECTIBLE_BIRTHRIGHT) && player.playerType == PLAYER_LAZARUS) + player.redStewBonusDuration = LAZARUS_BIRTHRIGHT_STEW_FRAMES; + if (player.playerType != PLAYER_LAZARUS_B && player.playerType != PLAYER_LAZARUS2_B) + player.playerType = PLAYER_LAZARUS2; + player.cacheFlags |= CACHE_ALL; + player.temporaryEffects.AddNullEffect(NULLITEM_LAZARUS_BOOST, true, 1); + player.update_player_skin(); + player.EvaluateItems(); + + player.isVisible = true; + if (player.forgottenBody) player.pos = player.forgottenBody->pos; + Entity* poof = g_game->Spawn({.position = player.pos, + .spawner = &player, + .subType = POOF_LARGE_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF01, + .seed = Random()}); + poof->renderDepthOffset = player.posOffset.y + 1; +} + +// Tainted Lost's Birthright: half a soul heart, the Birthright held up, and an enemy ghost blast that hurts for 200, +// with a black poof's and a holy sound and a shake. +static void lost_birthright_revive(Entity_Player& player) +{ + revive_hearts_clear(player); + player.soulHearts = 1; + player.maxHearts = 0; + player.isVisible = true; + player.damageCooldown = REVIVE_DAMAGE_COOLDOWN; + player.AnimateCollectible(COLLECTIBLE_BIRTHRIGHT, ANIMATION_PICKUP, ANIMATION_PICKUP_SPARKLE); + + Entity* blast = g_game->Spawn({.position = player.pos, + .subType = ENEMY_GHOST_BLAST, + .type = ENTITY_EFFECT, + .variant = EFFECT_ENEMY_GHOST, + .seed = Random()}); + blast->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + blast->sprite.scale = vector_make(LOST_BIRTHRIGHT_GHOST_SCALE, LOST_BIRTHRIGHT_GHOST_SCALE); + blast->SetCollisionDamage(LOST_BIRTHRIGHT_GHOST_DAMAGE); + blast->Update(); + effect_sound_play(SOUND_BLACK_POOF); + effect_sound_play(SOUND_SUPERHOLY); + game_shake_screen(LOST_BIRTHRIGHT_SHAKE); +} + +// Inner Child's revival: its effect, the least hearts, safe for 90 frames at the Forgotten's body or the player, a +// burst by character (bones for the Forgottens, a black poof for the Losts, blood and gibs else) with a ground or blood +// poof, a bounce, a shake, and a blast that hurts what stands near for 35. +static void inner_child_revive(Entity_Player& player) +{ + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_INNER_CHILD, true, 1); + revive_hearts_least(player); + player.isVisible = true; + player.damageCooldown = REVIVE_DAMAGE_COOLDOWN; + if (player.forgottenBody) player.pos = player.forgottenBody->pos; + + int type = player.playerType; + bool isForgotten = type == PLAYER_THEFORGOTTEN || type == PLAYER_THEFORGOTTEN_B; + bool isLost = type == PLAYER_THELOST || type == PLAYER_THELOST_B || type == PLAYER_JACOB2_B; + GibSpawn gibs = {.position = player.pos, .spawner = &player, .spread = DEATH_GIB_SPREAD, .amount = DEATH_GIBS_LARGE}; + if (isLost) + { + effect_sound_play(SOUND_BLACK_POOF); + g_game->Spawn({.position = player.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + player.MakeGroundPoof(player.pos, COLOR_DEFAULT, 1); + } + else if (isForgotten) + { + effect_sound_play(SOUND_DEATH_BURST_BONE, {.volume = LOUD_DEATH_VOLUME}); + effect_sound_play(SOUND_BLACK_POOF); + gibs.gibFlags = BONE_GIB_FLAGS; + gibs_spawn(gibs); + player.MakeGroundPoof(player.pos, COLOR_DEFAULT, 1); + } + else + { + effect_sound_play(SOUND_DEATH_BURST_LARGE, {.volume = LOUD_DEATH_VOLUME}); + effect_sound_play(SOUND_BLACK_POOF); + g_game->Spawn({.position = player.pos, + .subType = BLOOD_EXPLOSION_SPLASH, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + gibs.gibFlags = BLOOD_GIB_FLAGS; + gibs_spawn(gibs); + player.MakeBloodPoof(player.pos, COLOR_DEFAULT, 1); + } + player.jellyBellyBounceTimer = INNER_CHILD_BOUNCE; + game_shake_screen(INNER_CHILD_SHAKE); + damage_radius({.position = player.pos, + .source = &player, + .damage = INNER_CHILD_DAMAGE, + .playerDamageThreshold = INNER_CHILD_PLAYER_THRESHOLD, + .radius = INNER_CHILD_RADIUS}); +} + +// 007a23a0 Revives the player by a collectible's rule: 1up! with its character's hearts, Dead Cat with two hearts and +// a life gone, Guppy's Collar with the least hearts, Ankh as ??? and Judas' Shadow as Black Judas with their soul +// hearts, Lazarus' Rags as Lazarus Risen, Inner Child with a blast, and Tainted Lost's Birthright with a ghost blast. +// The owner of the item holds it up as a helper player, else restarts the last room. Any other collectible is logged. +void Entity_Player::collectible_revive(int collectible, bool isOwner) +{ + if (playerIndex >= 0) Revive(); + + RevivalReturn revival = {.collectible = collectible}; + switch (collectible) + { + case COLLECTIBLE_1UP: + one_up_hearts_restore(*this); + revival.animation = TRANSITION_ONE_UP; + break; + case COLLECTIBLE_DEAD_CAT: + dead_cat_hearts_restore(*this); + revival.animation = TRANSITION_DEAD_CAT; + break; + case COLLECTIBLE_GUPPYS_COLLAR: + revive_hearts_least(*this); + revival.animation = TRANSITION_COLLAR; + break; + case COLLECTIBLE_ANKH: + revive_form_take(*this, ANKH_FORM); + revival.animation = TRANSITION_ANKH; + break; + case COLLECTIBLE_JUDAS_SHADOW: + revive_form_take(*this, JUDAS_SHADOW_FORM); + revival.animation = TRANSITION_JUDAS_SHADOW; + break; + case COLLECTIBLE_LAZARUS_RAGS: + lazarus_rise(*this); + return revive_finish(*this, false); + case COLLECTIBLE_BIRTHRIGHT: + lost_birthright_revive(*this); + return revive_finish(*this, false); + case COLLECTIBLE_INNER_CHILD: + inner_child_revive(*this); + return revive_finish(*this, false); + default: + { + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectible); + log_printf(LOG_WARN, "No revival effect associated with collectible %d (%s)\n", collectible, + item ? item->GetLocalizedName().c_str() : ""); + return revive_finish(*this, false); + } + } + revive_finish(*this, isOwner && revive_return(*this, revival)); +} + +// 007a3430 Revives the player by a trinket's rule: Missing Poster as the Lost with half a soul heart, Broken Ankh as +// ??? with three soul hearts, the owner holding up the poster or the Ankh as a helper player, else restarting the last +// room. Any other trinket is logged. +void Entity_Player::ReviveFromTrinket(uint32_t trinketId) +{ + if (playerIndex >= 0) Revive(); + + if (trinketId != TRINKET_MISSING_POSTER && trinketId != TRINKET_BROKEN_ANKH) + { + ItemConfig_Item* item = g_manager->itemConfig.GetTrinket(trinketId & TRINKET_ID_MASK); + log_printf(LOG_WARN, "No revival effect associated with trinket %d (%s)\n", trinketId, + item ? item->GetLocalizedName().c_str() : ""); + return revive_finish(*this, false); + } + bool isPoster = trinketId == TRINKET_MISSING_POSTER; + revive_form_take(*this, isPoster ? MISSING_POSTER_FORM : ANKH_FORM); + RevivalReturn revival = isPoster ? RevivalReturn{TRANSITION_MISSING_POSTER, 0, TRINKET_MISSING_POSTER} + : RevivalReturn{TRANSITION_ANKH, COLLECTIBLE_ANKH, 0}; + revive_finish(*this, revive_return(*this, revival)); +} + +// Soul of Lazarus' revival: its pending effect ends for the pair, else the card leaves the holder's pocket, and each +// comes back with the least hearts, seen and safe for 90 frames at the Forgotten's body or where it stands. +static void soul_of_lazarus_revive(Entity_Player& holder, std::vector& players) +{ + if (holder.temporaryEffects.HasNullEffect(NULLITEM_LAZARUS_SOUL_REVIVE)) + for (Entity_Player* player : players) player->temporaryEffects.RemoveNullEffect(NULLITEM_LAZARUS_SOUL_REVIVE, 1); + else + { + auto isCard = [](PocketItem& pocket) { return pocket.type == POCKET_CARD && pocket.id == CARD_SOUL_LAZARUS; }; + auto card = std::ranges::find_if(holder.pocketItems, isCard); + if (card != holder.pocketItems.end()) + { + std::shift_left(card, holder.pocketItems.end(), 1); + holder.pocketItems.back() = {0, POCKET_CARD}; + } + } + for (Entity_Player* player : players) + { + if (player->playerIndex >= 0) player->Revive(); + revive_hearts_least(*player); + player->isVisible = true; + player->damageCooldown = REVIVE_DAMAGE_COOLDOWN; + if (player->forgottenBody) player->pos = player->forgottenBody->pos; + player->UpdateHeartDependentEffects(); + player->ClampGoldenHearts(false); + } +} + +// Uses up what saves the pair and revives it: each of the pair by the collectible (its holder as owner), or the first +// alone. Dead Cat loses a life, and a cat goes once the lives left drop below the cats' share. +static void revival_apply(Revival& revival, std::vector& players) +{ + Entity_Player& holder = *revival.holder; + Entity_Player& first = *players[0]; + + if (revival.kind == REVIVAL_EACH || revival.kind == REVIVAL_FIRST) + holder.RemoveCollectible(revival.id, false, 0, true); + if (revival.kind == REVIVAL_DEAD_CAT) + { + holder.deadCatLives = (short)std::max(holder.deadCatLives - 1, 0); + while (holder.deadCatLives < (holder.collectibleCounts[COLLECTIBLE_DEAD_CAT] - 1) * DEAD_CAT_LIVES + 1) + holder.RemoveCollectible(COLLECTIBLE_DEAD_CAT, false, 0, true); + } + if (revival.id == TRINKET_MISSING_POSTER && revival.kind == REVIVAL_TRINKET) + { + holder.TryRemoveTrinket(TRINKET_MISSING_POSTER); + holder.temporaryEffects.RemoveTrinketEffect(TRINKET_MISSING_POSTER, -1); + } + + switch (revival.kind) + { + case REVIVAL_SOUL_OF_LAZARUS: + return soul_of_lazarus_revive(holder, players); + case REVIVAL_EACH: + case REVIVAL_EACH_KEPT: + case REVIVAL_DEAD_CAT: + for (Entity_Player* player : players) player->collectible_revive(revival.id, player == &holder); + return; + case REVIVAL_FIRST: + case REVIVAL_FIRST_KEPT: + return first.collectible_revive(revival.id, true); + case REVIVAL_TRINKET: + return first.ReviveFromTrinket((uint32_t)revival.id); + default: + return; + } +} + +// A helper player's burst as it dies: bones for the Forgottens, nothing for the Losts but Strawman's black poof, and +// blood and gibs for the others, louder for a helper that is not Strawman. +static void helper_burst(Entity_Player& helper, bool isStrawman) +{ + int type = helper.playerType; + bool isForgotten = type == PLAYER_THEFORGOTTEN || type == PLAYER_THEFORGOTTEN_B; + bool isLost = type == PLAYER_THELOST || type == PLAYER_THELOST_B || type == PLAYER_JACOB2_B; + GibSpawn gibs = {.position = helper.pos, .spawner = &helper, .spread = DEATH_GIB_SPREAD}; + + if (isForgotten) + { + effect_sound_play(SOUND_DEATH_BURST_BONE, {.volume = isStrawman ? 1 : LOUD_DEATH_VOLUME}); + gibs.amount = DEATH_GIBS_LARGE; + gibs.gibFlags = BONE_GIB_FLAGS; + return gibs_spawn(gibs); + } + if (isLost) + { + if (!isStrawman) return; + effect_sound_play(SOUND_BLACK_POOF); + g_game->Spawn({.position = helper.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + return; + } + effect_sound_play(SOUND_DEATH_BURST_SMALL); + g_game->Spawn({.position = helper.pos, + .subType = isStrawman ? BLOOD_EXPLOSION_SPLASH : BLOOD_EXPLOSION_BURST, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + gibs.amount = DEATH_GIBS_SMALL; + gibs.gibFlags = BLOOD_GIB_FLAGS; + gibs_spawn(gibs); +} + +// The death of a helper player of a player: Strawman leaves with its item and five blue spiders for its owner, any +// other helper with its burst. +static void helper_death(Entity_Player& helper, Entity_Player& owner) +{ + PlayerManager& playerManager = g_game->playerManager; + + if (!helper.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_STRAW_MAN)) + { + helper_burst(helper, false); + return playerManager.RemoveCoPlayer(&helper); + } + if (ItemConfig_Item* strawman = g_manager->itemConfig.GetCollectible(COLLECTIBLE_STRAW_MAN)) + helper.temporaryEffects.RemoveEffect(strawman, -1); + playerManager.RemoveCoPlayer(&helper); + owner.RemoveCollectible(COLLECTIBLE_STRAW_MAN, false, 0, true); + for (int i = 0; i < STRAWMAN_SPIDERS; i++) + { + owner.numBlueSpiders++; + spawn_blue_spider(helper.pos, &owner, Vector{}); + } + helper_burst(helper, true); +} + +// The end of 007a1090 once the first of the pair lives again: Judas' Birthright makes a Judas saved by Plan C Black +// Judas, the first player's old character lets go of what it brought, and each player rolls Guppy's Collar's and Broken +// Ankh's generators, gets its Forgotten half back and settles whether it can shoot and its color. +static void revived_players_settle(std::vector& players, int oldType) +{ + Entity_Player& first = *players[0]; + + if (oldType == PLAYER_JUDAS && first.playerType != PLAYER_BLACKJUDAS && first.HasCollectible(COLLECTIBLE_BIRTHRIGHT) && + first.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_PLAN_C)) + { + if (ItemConfig_Item* planC = g_manager->itemConfig.GetCollectible(COLLECTIBLE_PLAN_C)) + first.temporaryEffects.RemoveEffect(planC, -1); + first.maxHearts = 0; + first.redHearts = 0; + first.playerType = PLAYER_BLACKJUDAS; + first.cacheFlags |= CACHE_ALL; + first.update_player_skin(); + first.EvaluateItems(); + first.TryPreventDeath(); + } + first.player_type_change_prepare(oldType); + for (Entity_Player* player : players) + { + player->GetCollectibleRNG(COLLECTIBLE_GUPPYS_COLLAR).Next(); + player->GetTrinketRNG(TRINKET_BROKEN_ANKH).Next(); + player->init_forgotten_twin(); + player->UpdateCanShoot(); + player->ResetColor(); + } } // 007a1090 The death of a player out of health, with its twin, once its death animation ended: the first revival -// its items give, else a co-op ghost while others live, else the end of the run. A co-op baby leaves the run. -// With isCheckOnly, only whether it would revive. A locked Missing Poster says so in a Sacrifice Room, where dying -// with it unlocks the Lost. -// Lazarus rises as Lazarus Risen and the revived pair settles. The other revivals and helpers stop the game when -// reached. +// its items give (in the order revival_find tries them), else a co-op ghost while others live, a helper player's own +// death, or the end of the run. A co-op baby leaves the run. With isCheckOnly, only whether it would revive. A locked +// Missing Poster says so in a Sacrifice Room, where dying with it unlocks the Lost. bool Entity_Player::TriggerDeath(bool isCheckOnly) { Game& game = *g_game; @@ -141,10 +705,9 @@ bool Entity_Player::TriggerDeath(bool isCheckOnly) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_THE_LOST); int firstType = players[0]->playerType; - const char* revival = revival_find(*this, players); - if (isCheckOnly) return revival || (trinket_holder_find(players, TRINKET_MISSING_POSTER) && isSacrificeRoom); - if (revival == LAZARUS_RISING) players[0]->collectible_revive(COLLECTIBLE_LAZARUS_RAGS, true); - else if (revival) reconstruction_missing(revival); + Revival revival = revival_find(*this, players); + if (isCheckOnly) return revival.kind == REVIVAL_POSTER_LOCKED ? isSacrificeRoom : revival.kind != REVIVAL_NONE; + revival_apply(revival, players); for (Entity_Player* player : players) { @@ -164,13 +727,15 @@ bool Entity_Player::TriggerDeath(bool isCheckOnly) return true; } if (first.parent && first.variant == PLAYER_VARIANT_PLAYER && first.parent->is_player()) - reconstruction_missing("Entity_Player::TriggerDeath 007a1090 (a helper player's death)"); + { + helper_death(first, *first.parent->ToPlayer()); + return true; + } - playerManager.trigger_coop_baby_death(this); - isVisible = false; + playerManager.trigger_coop_baby_death(&first); + first.isVisible = false; return true; } - // 007cbb60 Whether the player would revive from its death. bool Entity_Player::WillPlayerRevive() { @@ -192,13 +757,6 @@ static bool is_run_lost(Entity_Player& dying) return true; } -// Plays a sound in the player's voice, as the fart seed may replace it. -static void voice_play(int sound, float pitch) -{ - seed_fart_sound_override(&sound); - g_manager->sfxManager.Play(sound, {.pitch = pitch}); -} - // The death part of the player's frame, Update 00782af0: outside transitions the death animation starts once (with // Mysterious Paper's chance of Missing Poster), the held entity is thrown, the ghost shows, and a run lost forgets its // save. The player slows to a halt, cries out on the animation's DeathSound, takes its twin down with it once the @@ -241,7 +799,7 @@ void Entity_Player::death_update() } else if (sprite.IsPlaying(animation) && sprite.IsEventTriggered("DeathSound")) { - if (!IsHologram()) voice_play(SOUND_ISAACDIES, get_voice_pitch()); + if (!IsHologram()) effect_sound_play(SOUND_ISAACDIES, {.pitch = get_voice_pitch()}); if (playerType == PLAYER_BLUEBABY_B) reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Blue Baby's last poops)"); } @@ -306,7 +864,7 @@ void Entity_Player::room_exit(bool isKeepHolyMantle) auto isClot = [this](Entity* entity) { bool isOwned = entity && entity->IsFamiliar() && static_cast(entity)->player == this; - return isOwned && entity->variant == Entity_Familiar::BLOOD_BABY && entity->subtype != CLOT_SUBTYPE_UNCOUNTED && + return isOwned && entity->variant == Entity_Familiar::BLOOD_BABY && entity->subtype != BLOOD_CLOT_SUBTYPE_SPENT && !entity->isDead; }; EntityList_EL& persistent = game.room->entityList.persistentEL; diff --git a/src/entity_player_effects.cpp b/src/entity_player_effects.cpp index 0c00e65..867007a 100644 --- a/src/entity_player_effects.cpp +++ b/src/entity_player_effects.cpp @@ -7,8 +7,10 @@ #include "entity_pickup.h" #include "entity_npc.h" #include "entity_player.h" +#include "entity_laser.h" #include "entity_player_characters.h" #include "entity_projectile.h" +#include "entity_tear.h" #include "entity_slot.h" #include "game.h" #include "manager.h" @@ -821,6 +823,16 @@ static void purgatory_update(Entity_Player& player) ->Update(); } +// Montezuma's Revenge's spray turns toward the back of a player in control, three tenths of the way a frame. +static void montezuma_aim_update(Entity_Player& player) +{ + constexpr float MONTEZUMA_TURN = 0.3f; + Entity* spray = player.montezumaLaser; + if (!spray || !player.AreControlsEnabled() || spray->type != ENTITY_LASER) return; + auto* laser = static_cast(spray); + laser->set_aim_angle(angle_lerp(laser->angleDegrees, player.bodyAngle + HALF_TURN_DEGREES, MONTEZUMA_TURN)); +} + // 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) @@ -1026,6 +1038,7 @@ void items_frame_update(Entity_Player& player) sumptorium_recall_update(player); purgatory_update(player); isaacs_heart_update(player); + montezuma_aim_update(player); plan_c_update(player); linger_bean_update(player); im_excited_update(player); @@ -1077,3 +1090,68 @@ void Entity_Player::creep_contact_add(int flags, int count) grantedCollectibleFlags = (uint32_t)flags; ground_contact_add(*this, grantedCollectibleCountdown, count, isChanged); } + +constexpr int DASH_IMPACT_COOLDOWN = 30; +constexpr int DASH_FLAMES = 8; +constexpr float DASH_FLAME_REACH = 40; +constexpr int DASH_FLAME_BURN = 10; +constexpr float DASH_IMPACT_RADIUS = 80; +constexpr float DASH_PUSH_MAX = 7; +constexpr float DASH_HEAVY_MASS = 20; +constexpr float DASH_HEAVY_SCALE = 0.5f; +constexpr float DASH_VELOCITY_KEPT = 0.5f; +constexpr float DASH_KNOCKBACK_SPEED = 16; +constexpr LerpRange DASH_KNOCKBACK_FRAMES = {.inMin = 10, .inMax = 80, .outMin = 20, .outMax = 1}; + +// 007c8240 A dash's crash: the player blinks no more and is safe for 30 frames at least, a ring of eight friendly fire +// jets bursts out within the room, and what stands within 80 is thrown off: shots turn back on the enemies, and bombs, +// pickups and enemies that can be moved are pushed away (less when heavier than 20), the enemies also knocked back for +// fewer frames the farther and heavier they are. +// The original's weights for masses above 30 and 50 never apply, as the check for 20 comes first. +void Entity_Player::dash_impact() +{ + ClearEntityFlags(FLAG_NO_DAMAGE_BLINK); + isMarsDashReady = true; + damageCooldown = std::max(damageCooldown, DASH_IMPACT_COOLDOWN); + + for (int i = 0; i < DASH_FLAMES; i++) + { + Vector spot = vector_add(pos, vector_scale(vector_from_angle((float)i * FULL_TURN_DEGREES / DASH_FLAMES), DASH_FLAME_REACH)); + if (!g_game->room->IsPositionInRoom(spot, 0)) continue; + Entity* flame = g_game->Spawn({.position = spot, .spawner = this, .type = ENTITY_EFFECT, .variant = EFFECT_FIRE_JET, + .seed = Random()}); + flame->AddEntityFlags(FLAG_FRIENDLY); + flame->AddBurn(EntityRef(this), DASH_FLAME_BURN, 0, false); + flame->Update(); + } + + for (Entity* target : entity_query_radius(pos, DASH_IMPACT_RADIUS, QUERY_ALL)) + { + bool isMovable = target->IsVulnerableEnemy(nullptr) || target->type == ENTITY_BOMB || target->type == ENTITY_PICKUP; + if (target->type == ENTITY_PLAYER || !isMovable || target->mass == 0 || target->HasEntityFlags(FLAG_NO_KNOCKBACK)) + continue; + Vector away = vector_sub(target->pos, pos); + float distance = vector_length(away); + if (distance <= 0) continue; + + Vector turned = vector_scale(away, vector_length(target->velocity) / distance); + if (target->type == ENTITY_PROJECTILE) static_cast(target)->Reflect(turned); + else if (Entity_Tear* tear = target->type == ENTITY_TEAR ? dynamic_cast(target) : nullptr) + tear->Deflect(this, turned); + else + { + float push = std::min(DASH_PUSH_MAX, target->size + DASH_IMPACT_RADIUS - distance) * 2; + if (target->mass > DASH_HEAVY_MASS) push *= DASH_HEAVY_SCALE; + Vector kept = vector_scale(target->velocity, DASH_VELOCITY_KEPT); + target->velocity = vector_make(away.x / distance * push + kept.x, away.y / distance * push + kept.y); + bool isKnocked = target->IsVulnerableEnemy(nullptr) && target->mass > 0 && + !target->HasEntityFlags(FLAG_NO_KNOCKBACK) && !target->HasEntityFlags(FLAG_FRIENDLY); + if (!isKnocked) continue; + Vector direction = vector_sub(target->pos, pos); + float length = vector_length(direction); + direction = vector_scale(direction, 1 / length); + float frames = lerp_range(length - (size + target->size) + target->mass, DASH_KNOCKBACK_FRAMES); + target->AddKnockback(EntityRef(this), vector_scale(direction, DASH_KNOCKBACK_SPEED), (int)std::floor(frames), true); + } + } +} diff --git a/src/entity_player_familiars.cpp b/src/entity_player_familiars.cpp new file mode 100644 index 0000000..7dc91cd --- /dev/null +++ b/src/entity_player_familiars.cpp @@ -0,0 +1,190 @@ +#include "entity_player.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_list.h" +#include "game.h" +#include "item_config.h" +#include "manager.h" +#include "room.h" +#include "sfx_manager.h" +#include +#include +#include +#include +#include + +constexpr int LEPROSY_MAX = 3; +constexpr size_t SWARM_FLIES_MAX = 15; +constexpr float MINISAAC_LAUNCH_TURN = 3.14f * 2; +constexpr float MINISAAC_LAUNCH_SPEED_RANGE = 3; +constexpr float MINISAAC_LAUNCH_SPEED_MIN = 2; +constexpr int MINISAAC_FORGOTTEN_SUBTYPE = 99; +constexpr float MINISAAC_SPLAT_PUSH = 0.4f; +constexpr float MINISAAC_SPLAT_SCALE_RANGE = 0.4f; +constexpr float MINISAAC_SPLAT_SCALE_MIN = 0.8f; +constexpr int MINISAAC_SPLAT_Z_OFFSET = 2000; +constexpr int BLOOD_EXPLOSION_SPLAT = 1; +constexpr size_t TWINS_FAMILIARS_MAX = 60; +constexpr std::array TWINS_REMOVED_IDS = {43, 61, 235}; + +// 00759b80 Counts a blue fly gone. +void Entity_Player::RemoveBlueFly() +{ + numBlueFlies--; +} + +// 00759b90 Adds a Leprosy orbital, up to three. +void Entity_Player::AddLeprosy() +{ + 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()}); +} + +// 00759bf0 Spawns a Swarm fly orbital at a position from the Swarm's RNG, first removing the player's flies past 15 +// (the last in the room's list first). +Entity* Entity_Player::AddSwarmFlyOrbital(Vector position) +{ + std::deque flies; + + for (Entity* entity : g_game->room->entityList.updateEL) + { + bool isFly = entity && entity->type == ENTITY_FAMILIAR && entity->variant == Entity_Familiar::SWARM_FLY_ORBITAL; + if (isFly && static_cast(entity)->player == this) flies.push_front(entity); + } + for (; flies.size() > SWARM_FLIES_MAX; flies.pop_front()) flies.front()->Remove(); + + Entity* fly = g_game->Spawn({.position = position, .spawner = this, .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::SWARM_FLY_ORBITAL, + .seed = GetCollectibleRNG(COLLECTIBLE_SWARM).Next()}); + fly->Update(); + return fly; +} + +// 00770600 Has the familiars spawned again for the player's items. +void Entity_Player::RespawnFamiliars() +{ + cacheFlags |= CACHE_FAMILIARS; + EvaluateItems(); +} + +// 007abdf0 Adds a Pretty Fly, happily. +void Entity_Player::AddPrettyFly() +{ + pillEffectUses[PILLEFFECT_PRETTY_FLY]++; + cacheFlags |= CACHE_FAMILIARS; + EvaluateItems(); + AnimateHappy(); +} + +// The blood a Minisaac bursts out of: a splat pushed with it, turned and sized at random, drawn above, with a pop. +static void minisaac_splat_spawn(const Vector& position, const Vector& velocity) +{ + Entity* splat = g_game->Spawn({.position = position, + .velocity = vector_scale(velocity, MINISAAC_SPLAT_PUSH), + .subType = BLOOD_EXPLOSION_SPLAT, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + splat->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + splat->sprite.Play("Poof"); + float scale = random_unit() * MINISAAC_SPLAT_SCALE_RANGE + MINISAAC_SPLAT_SCALE_MIN; + splat->sprite.scale = vector_make(scale, scale); + splat->renderZOffset = MINISAAC_SPLAT_Z_OFFSET; + effect_sound_play(SOUND_DEATH_BURST_SMALL); +} + +// 007d1860 Spawns a Minisaac in the player's skin color (the Forgotten's bones as 99) at a position. With isPlayAnim it +// bursts out flung at random, appearing in a splat of blood without colliding until it lands. It walks unless the +// player flies. +Entity_Familiar* Entity_Player::AddMinisaac(Vector position, bool isPlayAnim) +{ + Vector launch{}; + if (isPlayAnim) + { + float angle = random_unit() * MINISAAC_LAUNCH_TURN; + float speed = random_unit() * MINISAAC_LAUNCH_SPEED_RANGE + MINISAAC_LAUNCH_SPEED_MIN; + launch = vector_make(std::cos(angle) * speed, std::sin(angle) * speed); + } + int subType = headColor < 0 ? 0 : headColor + 1; + if (playerType == PLAYER_THEFORGOTTEN) subType = MINISAAC_FORGOTTEN_SUBTYPE; + + auto* minisaac = static_cast(g_game->Spawn({.position = position, + .velocity = launch, + .spawner = this, + .subType = subType, + .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::MINISAAC, + .seed = Random()})); + if (isPlayAnim) + { + minisaac->ClearEntityFlags(FLAG_APPEAR); + minisaac->sprite.Play("Appear"); + minisaac->sprite.RemoveOverlay(); + minisaac->state = 1; + minisaac->entityCollisionClass = ENTCOLL_NONE; + minisaac_splat_spawn(position, launch); + } + minisaac->entityGridCollisionClass = canFly ? GRIDCOLL_WALLS : GRIDCOLL_GROUND; + return minisaac; +} + +// 007d2a00 Spawns a friendly Dip of a subtype at a position. +void Entity_Player::AddFriendlyDip(int subType, Vector position) +{ + Entity_Familiar::ThrowDip(subType, position, this); +} + +// 007d2a20 Throws a friendly Dip of a subtype from a position to a target. +void Entity_Player::ThrowFriendlyDip(int subType, Vector position, Vector target) +{ + spawn_dip_at(subType, &position, this, &target); +} + +// The Twins' choice: the unique-less familiar items the player has, else Brother Bobby and Sister Maggy. +static std::vector twins_familiars_get(Entity_Player& player) +{ + ItemConfig& items = g_manager->itemConfig; + std::vector familiars; + + for (int id = 1; id < (int)items.collectibles.size(); id++) + { + ItemConfig_Item* item = items.GetCollectible(id); + if (!item || (item->tags & TAG_UNIQUE_FAMILIAR) || item->type != ITEM_FAMILIAR) continue; + if (player.GetCollectibleNum(id) < 1 || std::ranges::find(TWINS_REMOVED_IDS, id) != TWINS_REMOVED_IDS.end()) continue; + familiars.push_back(id); + } + return familiars; +} + +// 007dbeb0 The Twins: for a count of times, one of the player's familiar items (Brother Bobby or Sister Maggy without +// any) lends a copy for the room, drawn from the Twins' RNG while fewer than 60 familiars are about. A draw takes one +// item out of the next draws (not always the one lent), refilled once none are left. +void Entity_Player::twins_duplicate_familiars(int count) +{ + if (count < 1) return; + auto isFamiliar = [](Entity* entity) { return entity->type == ENTITY_FAMILIAR; }; + if ((size_t)std::ranges::count_if(g_game->room->entityList.updateEL, isFamiliar) >= TWINS_FAMILIARS_MAX) return; + + std::vector familiars = twins_familiars_get(*this); + RNG& rng = GetTrinketRNG(TRINKET_THE_TWINS); + for (; count > 0; count--) + { + if (familiars.empty()) familiars = {COLLECTIBLE_BROTHER_BOBBY, COLLECTIBLE_SISTER_MAGGY}; + uint32_t taken = rng.Next() % (uint32_t)familiars.size(); + int lent = familiars[rng.Next() % (uint32_t)familiars.size()]; + temporaryEffects.AddCollectibleEffect(lent, true, 1); + std::swap(familiars[taken], familiars.back()); + familiars.pop_back(); + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::twins_duplicate_familiars 007dbeb0 (the versus mode)"); + } +} diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index 69da513..684f4ff 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -20,6 +20,7 @@ #include "manager.h" #include "menu_manager.h" #include "fx_layers.h" +#include "entity_effect_combat.h" #include "npc_ai.h" #include "npc_basement.h" #include "npc_depths.h" @@ -81,6 +82,42 @@ constexpr int BLINK_CLOSED_FRAME = 2; constexpr int BLINK_CLOSED_FROM = 9; constexpr int HELD_ITEM_STATE_SUPLEX = 709; constexpr float HELD_DROP_SPEED = 0.1f; +// The head animations of a shot out of the mouth, left, up, right and down (Maw of the Void's and Hemoptysis's). +constexpr std::string_view HEAD_SHOOT_ANIMS[] = {"HeadLeftShoot", "HeadUpShoot", "HeadRightShoot", "HeadDownShoot"}; +constexpr int KIDNEY_BURST_HOLD = 5; +constexpr float REVERSE_CHARIOT_DEAD_ZONE = 0.25f; +constexpr float REVERSE_CHARIOT_LUNGE = 2; +constexpr int REVERSE_CHARIOT_FRAMES = 5; +constexpr float PONY_STEER = 0.6f; +constexpr float SPEAR_HOLD_REACH = 45; +constexpr float SPEAR_SIDE = 10; +constexpr float SPEAR_RISE = -15; +constexpr float SPEAR_REST_RATE = 0.8f; +constexpr float SPEAR_SWING_RATE = 0.5f; +constexpr int SPEAR_BLINK = 7; +constexpr float BONE_SPUR_CHIP_SPEED = 2; +constexpr float BONE_SPUR_CHIP_RANGE = 3; +constexpr int BUTTER_BEAN_DAILY_PERIOD = 30; +constexpr uint32_t BUTTER_BEAN_DAILY_ODDS_MASK = 3; +constexpr float BUTTER_BEAN_DAILY_RADIUS = 120; +constexpr int URETHRA_ROOM_FRAMES = 5; +constexpr int URETHRA_BLINK = 10; +constexpr int KIDNEY_BURST_FRAMES = 180; +constexpr uint32_t URETHRA_BLOCK_SECONDS_RANGE = 15; +constexpr int URETHRA_BLOCK_SECONDS = 15; +constexpr int URETHRA_SECOND_FRAMES = 30; +constexpr float KIDNEY_STONE_SPEED = 15; +constexpr uint32_t KIDNEY_STONE_FIRE_FLAGS = 0x45; +constexpr float KIDNEY_STONE_DAMAGE = 10; +constexpr float KIDNEY_STONE_SCALE = 1.2f; +constexpr float KIDNEY_STONE_SCALE_RANGE = 0.3f; +constexpr float KIDNEY_STONE_SCALE_MIN = 0.01f; +constexpr float KIDNEY_STONE_FALL = -3; +constexpr float KIDNEY_STONE_HEIGHT = -10; +constexpr uint32_t IBS_SPELLS = 11; +constexpr float IBS_SPENT = -1; +constexpr float IBS_BAR_STEP = 1.0f / 30; +constexpr int KIDNEY_BURST_BLINK = 8; constexpr float BODY_THROWN_DRAG = 0.97f; constexpr int ITEM_STATE_DOCTORS_REMOTE = 47; constexpr int ITEM_STATE_END_FRAMES = 5; @@ -136,8 +173,6 @@ 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: 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() @@ -241,15 +276,17 @@ Vector Entity_Player::GetShootingJoystick() return input; } -// 00779900 The direction the body walks: the weapon's aim while it fires, Montezuma's Revenge's blast, or the last -// movement. +// 00779900 The direction the body walks: the weapon's aim while it fires, against Montezuma's Revenge's spray (or its +// charging body), or the last movement. Vector Entity_Player::GetBodyMoveDirection() { Weapon* weapon = weapons[0] ? weapons[0].get() : weapons[1].get(); if (weapon && !is_zero(weapon->bodyDirection)) return weapon->bodyDirection; - if (HasCollectible(COLLECTIBLE_MONTEZUMAS_REVENGE) && (montezumaLaser || montezumaChargeTimer > 0)) - reconstruction_missing("Entity_Player::GetBodyMoveDirection 00779900 (Montezuma's Revenge)"); - return recentMovementVector; + if (!HasCollectible(COLLECTIBLE_MONTEZUMAS_REVENGE)) return recentMovementVector; + Entity* spray = montezumaLaser; + if (spray && spray->type == ENTITY_LASER) + return vector_from_angle(static_cast(spray)->angleDegrees + HALF_TURN_DEGREES); + return montezumaChargeTimer > 0 ? vector_from_angle(bodyAngle) : recentMovementVector; } // 00782630 How far a flying player floats above its shadow, except in the Beast's room. @@ -401,9 +438,24 @@ static void mars_taps_read(Entity_Player& p) } } +// The Chariot reversed: the player cannot walk, only lunge along the input every 5 frames (at least one frame after a +// lunge while the input is held). +static void reverse_chariot_step(Entity_Player& player, Vector input) +{ + int& cooldown = player.reverseChariotMoveCooldown; + if (vector_length(input) <= REVERSE_CHARIOT_DEAD_ZONE) cooldown--; + else if (cooldown < 1) + { + player.velocity = vector_add(player.velocity, + vector_scale(vector_normalized(input), REVERSE_CHARIOT_LUNGE * player.speedMultiplier)); + cooldown = REVERSE_CHARIOT_FRAMES; + } + else cooldown = std::max(cooldown - 1, 1); +} + // 00779b40 Moves the player by its input: speed and friction from its speed stat, a slippery floor's drift and the -// facing it walks in. A doubled Duct Tape's drop button turns the familiars' formation. The items that change walking -// stop the game until reached. +// facing it walks in. A suplex or Dark Arts' blast holds the input, the reversed Chariot only lunges and a charging +// pony steers to the nearest axis. A doubled Duct Tape's drop button turns the familiars' formation. void Entity_Player::update_body_animations() { if (heightVelocity < 0 || posOffset.y < 0) return; @@ -422,9 +474,7 @@ void Entity_Player::update_body_animations() float length = std::sqrt(input.x * input.x + input.y * input.y); if (length > 1) input = vector_make(input.x / length, input.y / length); } - if (playerType == PLAYER_THEFORGOTTEN_B && !isCoopGhost) input = {}; - if (suplexState != 0 || isDarkArtsBlastPending) - reconstruction_missing("Entity_Player::update_body_animations 00779b40 (suplexes and Dark Arts)"); + if ((playerType == PLAYER_THEFORGOTTEN_B && !isCoopGhost) || suplexState != 0 || isDarkArtsBlastPending) input = {}; bool isPair = playerType == PLAYER_JACOB || playerType == PLAYER_ESAU || playerType == PLAYER_LAZARUS_B || playerType == PLAYER_LAZARUS2_B; if ((isPair && twin_get()) || playerType == PLAYER_EVE_B) @@ -432,9 +482,17 @@ void Entity_Player::update_body_animations() Vector leaderInput = GetMainTwin()->GetMovementJoystick(); if (leaderInput.x != 0 || leaderInput.y != 0) actionHoldDrop = 0; } - if (temporaryEffects.HasNullEffect(NULLITEM_REVERSE_CHARIOT) || ponyCharge > 0) - reconstruction_missing("Entity_Player::update_body_animations 00779b40 (the Chariot and pony dashes)"); - reverseChariotMoveCooldown = 0; + if (temporaryEffects.HasNullEffect(NULLITEM_REVERSE_CHARIOT)) + { + reverse_chariot_step(*this, input); + input = {}; + } + else reverseChariotMoveCooldown = 0; + if (ponyCharge > 0) + { + Vector cardinal = vector_cardinal(movementVector); + input = vector_add(input, vector_scale(vector_sub(cardinal, input), PONY_STEER)); + } movementVector = input; if (input.x != 0 || input.y != 0) recentMovementVector = input; @@ -517,7 +575,8 @@ void Entity_Player::walk_velocity_update(Vector walkInput) float push = std::max(0.0f, (slippery * 0.7f - 0.2f) * (before.x * walkInput.x + before.y * walkInput.y)); float accel = (push / moveSpeed + 3) * 0.4f; if (HasEntityFlags(FLAG_THROWN)) drag = 1; - else if (suplexState < 2) drag = slippery * 0.185f + 0.775f; + else if (suplexState < 2 && !temporaryEffects.HasNullEffect(NULLITEM_REVERSE_CHARIOT)) + drag = slippery * 0.185f + 0.775f; else drag = slippery * 0.51f + 0.45f; float maxSpeed = moveSpeed * 4.41f; @@ -1112,6 +1171,8 @@ constexpr int CHARGE_FIRE_BLOCK = 30; constexpr int NO_2_FRAMES = 150; constexpr int MAW_TIMEOUT = 60; constexpr int REVELATION_TIMEOUT = 30; +constexpr int MONTEZUMA_TIMEOUT = 30; +constexpr float MONTEZUMA_REACH = 120; 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}}; @@ -1189,7 +1250,8 @@ static void charge_fired(Entity_Player& player, const ChargeShot& shot) // 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. +// tear effects, drawn behind the player when aiming up. Montezuma's Revenge: a full charge sprays a short brown beam +// out behind the player, which the frame then steers. static void charged_items_update(Entity_Player& player, const ChargeShot& shot) { if (player.HasCollectible(COLLECTIBLE_MAW_OF_THE_VOID)) @@ -1200,9 +1262,8 @@ static void charged_items_update(Entity_Player& player, const ChargeShot& 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); + HEAD_SHOOT_ANIMS[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); @@ -1221,6 +1282,25 @@ static void charged_items_update(Entity_Player& player, const ChargeShot& shot) beam->renderDepthOffset = shot.direction.y <= -TECH_LASER_FACING ? TECH_LASER_BACK_DEPTH : TECH_LASER_FRONT_DEPTH; charge_fired(player, shot); } + if (player.HasCollectible(COLLECTIBLE_MONTEZUMAS_REVENGE) && charge_release(player.montezumaChargeTimer, shot)) + { + float angle = player.bodyAngle + HALF_TURN_DEGREES; + Vector aim = vector_from_angle(angle); + Vector offset = player.GetLaserOffset(LASER_OFFSET_NONE, aim); + offset.y -= player.bodyScale.y * MONTEZUMA_RISE; + Entity_Laser* spray = Entity_Laser::ShootAngle({.position = player.pos, + .posOffset = offset, + .source = &player, + .angleDegrees = angle, + .timeout = MONTEZUMA_TIMEOUT, + .variant = LASER_THICK_BROWN}); + spray->SetCollisionDamage(player.meleeDamage); + spray->tearFlags = TearFlags(player.tearFlags).reset(TEAR_WAIT); + spray->maxDistance = MONTEZUMA_REACH; + player.montezumaLaser = spray; + spray->renderDepthOffset = aim.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 @@ -1307,7 +1387,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. +// throws its shield when recharged, and Hemoptysis sneezes blood once through a passing Brimstone weapon, its +// costume opening its mouth along the tap. static void double_tap_fire(Entity_Player& player, Vector direction) { constexpr std::array, 2> TAP_FAMILIARS = {{{COLLECTIBLE_LIL_PORTAL, Entity_Familiar::LIL_PORTAL}, @@ -1345,8 +1426,16 @@ static void double_tap_fire(Entity_Player& player, Vector direction) 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)"); + TemporaryEffects& effects = player.temporaryEffects; + if (!player.HasCollectible(COLLECTIBLE_HEMOPTYSIS) || effects.HasCollectibleEffect(COLLECTIBLE_HEMOPTYSIS)) return; + WeaponPtr sneeze = weapon_create(WEAPON_BRIMSTONE, &player); + sneeze->maxFireDelay = player.maxFireDelay; + sneeze->modifiers = (uint32_t)player.GetWeaponModifiers() | WEAPON_MOD_AZAZELS_SNEEZE; + static_cast(sneeze.get())->fire(direction, 1); + sneeze.reset(); + effects.AddCollectibleEffect(COLLECTIBLE_HEMOPTYSIS, true, 1); + effects.AddNullEffect(NULLITEM_HEMOPTYSIS, true, 1); + player.play_null_costume_anim(NULLITEM_HEMOPTYSIS, HEAD_SHOOT_ANIMS[vector_to_direction(direction)], -1); } // The double tap of 0077b020: with GB Bug, Divine Intervention, Hemoptysis or Lil Portal and the controls on, a @@ -1368,6 +1457,62 @@ static void double_tap_update(Entity_Player& player) } } +// Where the Spear of Destiny stands for an angle: 45 out from the player along it, 10 to its side. +static Vector spear_position(Entity_Player& player, float angle) +{ + Vector out = vector_from_angle(angle + RIGHT_ANGLE_DEGREES); + return vector_add(vector_add(player.pos, vector_scale(out, SPEAR_HOLD_REACH)), + vector_scale(vector_rotated(out, RIGHT_ANGLE_DEGREES), SPEAR_SIDE)); +} + +// The Spear of Destiny is held out at the player's side in its tear colour, swinging toward the shot (or back to its +// last angle when nothing is shot), and the eyes stay shut while it does. Without the item it goes. +static void spear_of_destiny_update(Entity_Player& player, const PassiveShot& shot) +{ + Entity* held = player.spearOfDestiny; + if (!player.HasCollectible(COLLECTIBLE_SPEAR_OF_DESTINY)) + { + if (held) held->Remove(); + player.spearOfDestiny = nullptr; + return; + } + if (!held) + { + uint32_t seed = Random(); + Entity* spawned = g_game->Spawn({.position = player.pos, .spawner = &player, .type = ENTITY_EFFECT, + .variant = EFFECT_SPEAR_OF_DESTINY, .seed = seed}); + + // The original goes on with a spawn that failed or was replaced. Here that spawn is dropped. + auto* spear = spawned && spawned->type == ENTITY_EFFECT ? static_cast(spawned) : nullptr; + player.spearOfDestiny = spear; + if (!spear) return; + spear->parent = &player; + spear->rotation = player.spearOfDestinyAngle; + spear->sprite.rotation = player.spearOfDestinyAngle; + spear->pos = spear_position(player, player.spearOfDestinyAngle); + spear->posOffset = vector_make(0, SPEAR_RISE); + spear->SetColor(player.tearColor, -1, TEAR_COLOR_PRIORITY, false, true); + spear->Update(); + return; + } + + auto* spear = static_cast(held); + float rate = SPEAR_REST_RATE; + if (shot.isShootHeld) + { + Vector aim = is_zero(shot.direction) ? vector_from_direction(player.headDirection) : shot.direction; + float angle = angle_wrapped(vector_angle(aim) - RIGHT_ANGLE_DEGREES); + spear->rotation = angle; + player.spearOfDestinyAngle = angle; + rate = SPEAR_SWING_RATE; + } + float angle = angle_lerp(spear->sprite.rotation, spear->rotation, rate); + spear->sprite.rotation = angle; + spear->pos = spear_position(player, angle); + spear->SetColor(player.tearColor, -1, TEAR_COLOR_PRIORITY, false, true); + player.blinkTime = std::max(player.blinkTime, SPEAR_BLINK); +} + // 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. @@ -1409,6 +1554,73 @@ static void headless_blood_spray(Entity_Player& player, const PassiveShot& shot) tear->Update(); } +// The held shot a blocked urethra (Kidney Stone) reads: whether the shot is held, and whether it is forced. +struct UrethraShot +{ + bool isShootHeld = false; + bool isForcedShot = false; +}; + +// Kidney Stone's blocked urethra: holding the shot fills the bladder. Letting go (or a forced shot on a full bladder) +// after the room's first frames empties it, and a full one passes the stone: a big piercing spectral stone tear, +// then a burst of tears for 180 frames, until it blocks again 15 to 29 seconds later. +static void urethra_update(Entity_Player& player, const UrethraShot& shot) +{ + if (shot.isShootHeld && !(shot.isForcedShot && player.maxBladderCharge <= player.bladderCharge)) + { + if (player.bladderCharge < player.maxBladderCharge) player.bladderCharge++; + return; + } + if (g_game->room->GetFrameCount() <= URETHRA_ROOM_FRAMES) return; + + if (player.maxBladderCharge <= player.bladderCharge) + { + player.TryForgottenThrow(player.lastDirection); + player.isUrethraBlocked = false; + player.blinkTime = URETHRA_BLINK; + int frame = g_game->frameCount; + player.maxPeeBurstCooldown = KIDNEY_BURST_FRAMES; + player.peeBurstCooldown = KIDNEY_BURST_FRAMES; + player.nextUrethraBlockFrame = + frame + (int)(Random() % URETHRA_BLOCK_SECONDS_RANGE + URETHRA_BLOCK_SECONDS) * URETHRA_SECOND_FRAMES; + + Vector velocity = vector_scale(player.lastDirection, KIDNEY_STONE_SPEED * player.shotSpeed); + Entity_Tear* stone = player.FireTear({.position = player.pos, .velocity = velocity}, KIDNEY_STONE_FIRE_FLAGS, + nullptr, 1); + stone->ChangeVariant(TEAR_STONE); + stone->SetCollisionDamage(stone->collisionDamage * KIDNEY_STONE_DAMAGE); + float scale = std::max((random_unit() * KIDNEY_STONE_SCALE_RANGE + KIDNEY_STONE_SCALE) * stone->fScale, + KIDNEY_STONE_SCALE_MIN); + stone->baseScale = scale; + stone->fScale = scale; + stone->ResetSpriteScale(); + stone->SetTearFlags(TearFlags(stone->tearFlags).set(TEAR_PIERCING).set(TEAR_SPECTRAL)); + stone->fallingAccel = 0; + stone->fallingSpeed = KIDNEY_STONE_FALL; + stone->SetHeight(KIDNEY_STONE_HEIGHT); + stone->SetColor(COLOR_DEFAULT, -1, TEAR_COLOR_PRIORITY, false, true); + stone->Update(); + } + player.bladderCharge = 0; +} + +// IBS: holding the shot on a full charge fills its bar over a second, gurgling as it starts. Letting go casts a random +// poop spell and spends the charge. +static void ibs_update(Entity_Player& player, bool isShootHeld) +{ + if (!isShootHeld) + { + player.UsePoopSpell(player.GetCollectibleRNG(COLLECTIBLE_IBS).RandomInt(IBS_SPELLS) + 1); + player.ibsCharge = IBS_SPENT; + player.ibsChargeBar = 0; + return; + } + player.ibsChargeBar = std::min(player.ibsChargeBar + IBS_BAR_STEP, 1.0f); + if (!player.isIbsChargeSoundPending) return; + player.isIbsChargeSoundPending = false; + npc_sound_play(SOUND_IBS_GURGLE, 1, 2, 1); +} + // 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. @@ -1436,12 +1648,29 @@ void Entity_Player::update_shooting() if (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_YBAB) reconstruction_missing("Entity_Player::update_shooting 0077b020 (the mirrored baby's aim)"); - if (peeBurstCooldown > 0) reconstruction_missing("Entity_Player::update_shooting 0077b020 (Kidney Stone's burst)"); + Vector markedAim = input.direction; + bool isKidneyBurst = false; + if (peeBurstCooldown > 0) + { + if (peeBurstCooldown < maxPeeBurstCooldown - KIDNEY_BURST_HOLD) + { + input.isPressed = true; + isKidneyBurst = true; + if (is_zero(input.direction)) input.direction = lastDirection; + if (is_zero(input.direction)) input.direction = vector_from_direction(headDirection); + } + if (!isInterpolation) + { + peeBurstCooldown--; + cacheFlags |= CACHE_FIREDELAY; + EvaluateItems(); + } + blinkTime = KIDNEY_BURST_BLINK; + } if ((isPlayingExtraAnimation || isPlayingItemAnimation) && heldEntity && itemState != COLLECTIBLE_MOMS_BRACELET && itemState != HELD_ITEM_STATE_SUPLEX) ThrowHeldEntity(vector_scale(velocity, HELD_DROP_SPEED)); - Vector markedAim = input.direction; TemporaryEffect* taurus = temporaryEffects.GetCollectibleEffect(COLLECTIBLE_TAURUS); bool isShootingBlocked = std::ranges::any_of(NO_SHOOT_EFFECTS, [&](int id) { return temporaryEffects.HasCollectibleEffect(id); }) || @@ -1450,6 +1679,7 @@ void Entity_Player::update_shooting() { input.direction = {}; input.isPressed = false; + isKidneyBurst = false; } if (itemStateCooldown > 0 && !isInterpolation && --itemStateCooldown < 1) { @@ -1470,26 +1700,31 @@ void Entity_Player::update_shooting() bool canFire = isCoopGhost || canShoot; Vector headAim = shootDirection; - bool isForcedShot = marked_target_update(*this, {markedAim, isInterpolation, isShootHeld}); + bool isForcedShot = marked_target_update(*this, {markedAim, isInterpolation, isShootHeld}) || + (isKidneyBurst && itemStateCooldown == 0); 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)"); + bool isButterBeanDaily = game.dailyChallenge._specialDailyId == SPECIAL_DAILY_BUTTER_BEAN; + if (isButterBeanDaily && game.stageTransition.state == 0 && isInputAllowed && isShootHeld && + IsFrame(BUTTER_BEAN_DAILY_PERIOD, 0) && (Random() & BUTTER_BEAN_DAILY_ODDS_MASK) == 0) + game_butter_bean_fart({.position = pos, .source = this, .radius = BUTTER_BEAN_DAILY_RADIUS}); if (game.stageTransition.state == 0 && isInputAllowed && fireBlockCooldown < 1) shootHeldFrames = isShootHeld ? shootHeldFrames + 1 : 0; if (megaBlastDuration > 0 || azazelsRageLaser) canFire = false; canFire = canFire && fireBlockCooldown < 1; if (isUrethraBlocked && fireBlockCooldown < 1 && isInputAllowed) - reconstruction_missing("Entity_Player::update_shooting 0077b020 (the blocked urethra)"); + { + urethra_update(*this, {isShootHeld, isForcedShot}); + canFire = false; + } if (ibsCharge < 1) { isIbsChargeSoundPending = true; ibsChargeBar = 0; } - else if (fireBlockCooldown < 1 && isInputAllowed && itemState == 0) - reconstruction_missing("Entity_Player::update_shooting 0077b020 (IBS)"); + else if (fireBlockCooldown < 1 && isInputAllowed && itemState == 0) ibs_update(*this, isShootHeld); if (headDirectionTime < 0) { @@ -1513,8 +1748,6 @@ void Entity_Player::update_shooting() fireDirection = vector_to_direction(shootDirection); } - 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) charged_items_update(*this, {shootDirection, isForcedShot, isShootHeld}); if (isFireReady && playerType == PLAYER_EVE_B && !isInterpolation) eve_clot_update(*this, isShootHeld); @@ -1525,13 +1758,17 @@ void Entity_Player::update_shooting() else { if (!weapons[0] || weapons[0]->weaponType != overriding) weapons[0] = weapon_create(overriding, this); - if (!weapons[0]) reconstruction_missing("Entity_Player::update_shooting 0077b020 (this overriding weapon)"); if (overriding != WEAPON_ROCKETS) canFire = true; } for (int slot = 1; slot < WEAPON_SLOT_COUNT; slot++) - if (weapons[slot]) weapons[slot]->modifiers = modifiers; + { + if (!weapons[slot]) continue; + weapons[slot]->maxFireDelay = maxFireDelay; + weapons[slot]->modifiers = modifiers; + } if (weapons[0]) { + weapons[0]->maxFireDelay = maxFireDelay; weapons[0]->modifiers = modifiers | WEAPON_MOD_OVERRIDE; weapons[0]->Update(isInterpolation); } @@ -1559,6 +1796,7 @@ void Entity_Player::update_shooting() trinity_shield_update(*this, shot); double_tap_update(*this); doubleTapFrames++; + spear_of_destiny_update(*this, shot); if (!isInterpolation && IsFrame(2, 0)) headless_blood_spray(*this, shot); float savedLuck = luck; if (HasTrinket(TRINKET_TEARDROP_CHARM)) @@ -1586,6 +1824,13 @@ void Entity_Player::update_shooting() { if (variant != PLAYER_VARIANT_PLAYER || isCoopGhost) reconstruction_missing("Entity_Player::update_shooting 0077b020 (co-op babies' and ghosts' heads)"); + if (HasCollectible(COLLECTIBLE_BONE_SPURS) && sprite.GetOverlayFrame() == 0 && blinkFrame != 0) + game_particles_spawn({.position = pos, + .height = posOffset.y, + .speed = random_between(BONE_SPUR_CHIP_SPEED, BONE_SPUR_CHIP_RANGE), + .count = 1, + .subType = 1, + .variant = EFFECT_TOOTH_PARTICLE}); sprite.SetOverlayFrame(headAnim, blinkFrame); costume_heads_update(blinkFrame); } diff --git a/src/entity_player_health.cpp b/src/entity_player_health.cpp index f078f1f..3a46c56 100644 --- a/src/entity_player_health.cpp +++ b/src/entity_player_health.cpp @@ -2,11 +2,13 @@ #include "entity_player_trinkets.h" #include "game.h" #include "entity_effect.h" +#include "entity_effect_combat.h" #include "entity_pickup.h" #include "entity_player_characters.h" #include "item_overlay.h" #include "manager.h" #include "room_grid.h" +#include "seeds.h" #include "sfx_manager.h" #include #include @@ -1198,3 +1200,117 @@ void Entity_Player::trigger_max_hearts_removed(int removed) reverseEmpressMaxHearts -= empress; strengthMaxHearts -= std::min(strengthMaxHearts, hearts - empress); } + +constexpr int JAR_FLIES_MAX = 20; +constexpr int URN_SOULS_MAX = 20; +constexpr uint32_t STAT_UP_CACHE = CACHE_DAMAGE | CACHE_FIREDELAY | CACHE_SHOTSPEED | CACHE_RANGE | CACHE_SPEED | + CACHE_LUCK; + +// 007c9bb0 Adds flies to the Jar of Flies, 20 at most. +void Entity_Player::AddJarFlies(int amount) +{ + jarFlies = std::min(jarFlies + amount, JAR_FLIES_MAX); + g_game->hud.refresh_request(HUD_REFRESH_PLAYER); +} + +// 007d3480 Adds souls to the Urn of Souls, between none and 20. +void Entity_Player::AddUrnSouls(uint32_t amount) +{ + urnSouls = (uint32_t)std::clamp((int)(amount + urnSouls), 0, URN_SOULS_MAX); + g_game->hud.refresh_request(HUD_REFRESH_PLAYER); +} + +// 007d34f0 Adds giga bombs, between none and the bombs held. +void Entity_Player::AddGigaBombs(int amount) +{ + numGigaBombs = std::max(std::min(numGigaBombs + amount, numBombs), 0); + ConsumableCountChanged(CONSUMABLE_GIGA_BOMBS); + g_game->hud.refresh_request(HUD_REFRESH_PLAYER); +} + +// 007b2200 Adds luck given away by a slot, a beggar or a mirror. +void Entity_Player::DonateLuck(int luck) +{ + donateLuck += luck; + cacheFlags |= CACHE_LUCK; + EvaluateItems(); +} + +// 007c3980 Raises one stat at random from the RNG (speed, tears, damage, range, shot speed or luck), happily unless +// falling or dead. +void Entity_Player::add_random_stat_up(RNG* rng) +{ + std::array stats = {&speedModifier, &fireDelayModifier, &damageModifier, + &tearRangeModifier, &shotSpeedModifier, &luckModifier}; + + (*stats[rng->Next() % stats.size()])++; + cacheFlags |= STAT_UP_CACHE; + EvaluateItems(); + if (pitfallState == 0 && !isDead) AnimateHappy(); +} + +// 0085e200 Whether red and soul hearts fill the containers. +bool Entity_Player::HasFullHeartsAndSoulHearts() +{ + return maxHearts <= soulHearts + redHearts; +} + +constexpr float GOLDEN_PARTICLE_SPEED_RANGE = 12; +constexpr float GOLDEN_PARTICLE_SPEED_MIN = 8; +constexpr int GOLDEN_PARTICLES = 10; +constexpr uint32_t GOLDEN_HEART_COINS_RANGE = 6; +constexpr uint32_t GOLDEN_HEART_COINS_MIN = 3; +constexpr float GOLDEN_COIN_SPEED_RANGE = 0.66f; +constexpr float GOLDEN_COIN_SPEED_MIN = 0.33f; +constexpr float GOLDEN_FREEZE_RADIUS = 80; +constexpr int GOLDEN_FREEZE_FRAMES = 180; +constexpr int GOLDEN_FREEZE_COLOR_FRAMES = 15; +constexpr ColorMod GOLDEN_CRATER_COLOR = color_make({1, 1, 1, 1}, {10, 7.5f, 0, 1}); +constexpr ColorMod GOLDEN_FREEZE_COLOR = color_make({1, 1, 1, 1}, {}, {1, 0.9f, 0}); + +// 007ca2d0 Breaks golden hearts: a crumble of Ultra Greed's coins and a golden crater, then for each heart a burst of +// gold particles and 3 to 8 pennies flung out, and Midas' touch freezes the enemies within 80 (players too in versus) +// for 180 frames, gilded while frozen. +void Entity_Player::BreakGoldenHearts(int count) +{ + if (count < 1) return; + + effect_sound_play(SOUND_ULTRA_GREED_COIN_DESTROY); + Entity* crumble = g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + crumble->sprite.Load("gfx/293.000_UltraGreedCoins.anm2", GRAPHICS_LOAD); + crumble->sprite.Play("CrumbleNoDebris"); + crumble->Update(); + Entity* crater = g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_CRATER, .seed = Random()}); + std::ranges::copy(GOLDEN_CRATER_COLOR._colorize, crater->sprite.color._colorize); + crater->Update(); + + for (; count > 0; count--) + { + game_particles_spawn({.position = pos, + .height = posOffset.y, + .speed = random_unit() * GOLDEN_PARTICLE_SPEED_RANGE + GOLDEN_PARTICLE_SPEED_MIN, + .count = GOLDEN_PARTICLES, + .variant = EFFECT_GOLD_PARTICLE}); + for (uint32_t coins = Random() % GOLDEN_HEART_COINS_RANGE + GOLDEN_HEART_COINS_MIN; coins > 0; coins--) + { + Vector push = Entity_Pickup::GetRandomPickupVelocity(pos, nullptr, 0); + Vector velocity = vector_scale(push, random_unit() * GOLDEN_COIN_SPEED_RANGE + GOLDEN_COIN_SPEED_MIN); + g_game->Spawn({.position = vector_add(pos, velocity), + .velocity = velocity, + .spawner = this, + .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, + .seed = Random()}); + } + } + + for (Entity* entity : entity_query_radius(pos, GOLDEN_FREEZE_RADIUS, QUERY_ENEMIES)) + { + if (!Entity::is_enemy_type(entity->type) || entity == this) continue; + entity->bossStatusEffectCooldown = 0; + entity->CopyStatusEffects(); + entity->AddMidasFreeze(EntityRef(this), GOLDEN_FREEZE_FRAMES, false); + if (entity->HasEntityFlags(FLAG_MIDAS_FREEZE)) + entity->SetColor(GOLDEN_FREEZE_COLOR, GOLDEN_FREEZE_COLOR_FRAMES, COLOR_PRIORITY_DEFAULT, true, true); + } +} diff --git a/src/entity_player_hits.cpp b/src/entity_player_hits.cpp index 090f4ab..97643d3 100644 --- a/src/entity_player_hits.cpp +++ b/src/entity_player_hits.cpp @@ -15,11 +15,13 @@ #include "loot_list.h" #include "manager.h" #include "npc_ai.h" +#include "pocket_items.h" #include "room.h" #include "room_grid.h" #include "room_special.h" #include "sfx_manager.h" #include +#include // The odds and amounts of the trinkets and collectibles (367 on) a hit sets off: Red Patch's chance and luck, Missing // Page's Necronomicon, Salvation's count, the stomp, the pennies, Cartridge, the dice, Purity's colours, the shards, @@ -483,6 +485,11 @@ bool late_items_hit_trigger(Entity_Player& player, const ItemsHit& hit) return isHurtShown; } +// The rooms a stronger Cursed Skull sends the player to. +constexpr std::array CURSED_SKULL_SPECIAL_ROOMS = { + ROOM_SHOP, ROOM_TREASURE, ROOM_MINIBOSS, ROOM_SECRET, ROOM_SUPERSECRET, ROOM_ARCADE, ROOM_CHALLENGE, + ROOM_LIBRARY, ROOM_SACRIFICE, ROOM_ISAACS, ROOM_BARREN, ROOM_CHEST, ROOM_DICE, ROOM_PLANETARIUM}; + // Cursed Skull's part of 007729d0: a hit leaving the player at its last red heart (two with three copies) and no soul // hearts to spare sends it to a random room. Stronger copies pick among the special rooms. void cursed_skull_teleport(Entity_Player& player) @@ -492,6 +499,6 @@ void cursed_skull_teleport(Entity_Player& player) int hearts = scale_for_hard_difficulty(multiplier >= SKULL_STRONG ? 2 : 1); bool isLow = player.redHearts <= hearts && (player.soulHearts < 1 || (player.redHearts < 1 && player.soulHearts <= hearts)); if (!isLow) return; - if (multiplier != 1) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (golden Cursed Skull's special rooms)"); - game_random_room_move(*g_game, false, player.GetTrinketRNG(TRINKET_CURSED_SKULL).Next(), &player); + if (multiplier != 1) teleport_random_room_of_types(player, CURSED_SKULL_SPECIAL_ROOMS, false); + else game_random_room_move(*g_game, false, player.GetTrinketRNG(TRINKET_CURSED_SKULL).Next(), &player); } diff --git a/src/entity_player_items.cpp b/src/entity_player_items.cpp index 7f1e095..fa4f9d5 100644 --- a/src/entity_player_items.cpp +++ b/src/entity_player_items.cpp @@ -593,7 +593,6 @@ constexpr TagUnlock STARS_UNLOCK = {TAG_STARS, 2, 406}; constexpr int COIN_LUCKY_PENNY = 5; constexpr int SOUND_KISS_LIPS = 219; constexpr int SOUND_PEEPER_POP = 237; -constexpr int DEAD_CAT_LIVES = 9; constexpr int ROSARY_BIBLE_UPGRADE = 5; constexpr int RED_STEW_FRAMES = 5400; constexpr int RED_STEW_DEATHMATCH_FRAMES = 600; diff --git a/src/entity_player_kills.cpp b/src/entity_player_kills.cpp index 18bab1d..437b874 100644 --- a/src/entity_player_kills.cpp +++ b/src/entity_player_kills.cpp @@ -14,7 +14,6 @@ constexpr int COLLECTIBLE_CHARM_OF_THE_VAMPIRE = 62; constexpr int COLLECTIBLE_BERSERK_KILLS = 704; constexpr int TRINKET_BAT_WING_KILLS = 118; constexpr int TRINKET_SIGIL_OF_BAPHOMET = 189; -constexpr int NULLITEM_BAT_WING = 40; constexpr int SOUND_BOOK_SHADOWS_SIGIL = 1028; // Charm of the Vampire heals every 13 kills, every 8 in a versus match. The heart rises 24 above the player. @@ -109,7 +108,7 @@ static void bat_wing_update(Entity_Player& player) if (player.trinketRNGs[TRINKET_BAT_WING_KILLS].RandomInt(odds) != 0) return; player.temporaryEffects.AddTrinketEffect(TRINKET_BAT_WING_KILLS, true, 1); - player.AddCostume(g_manager->itemConfig.GetNullItem(NULLITEM_BAT_WING), false); + player.AddCostume(g_manager->itemConfig.GetNullItem(NULLITEM_BATWING_WINGS), false); } // Death's List: killing the marked enemy moves the mark to where it died, killing another fails the list. diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp deleted file mode 100644 index b72fda5..0000000 --- a/src/entity_player_missing.cpp +++ /dev/null @@ -1,171 +0,0 @@ -#include "entity_player.h" -#include "entity_familiar.h" -#include "game.h" -#include "log.h" -#include - -// 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"); } -// 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"); } -// 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"); -} -void Entity_Player::RespawnFamiliars() { reconstruction_missing("Entity_Player::RespawnFamiliars 00770600"); } -void Entity_Player::GetNPCTarget() { reconstruction_missing("Entity_Player::GetNPCTarget 00770610"); } -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::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) -{ - reconstruction_missing("Entity_Player::AnimateTrinket 007ab550"); -} -void Entity_Player::AnimateTrapdoor() { reconstruction_missing("Entity_Player::AnimateTrapdoor 007abc00"); } -// 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"); } -// 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"); -} -void Entity_Player::DonateLuck(int) { reconstruction_missing("Entity_Player::DonateLuck 007b2200"); } -void Entity_Player::TryDecreaseGlowingHourglassUses(int, bool) -{ - reconstruction_missing("Entity_Player::TryDecreaseGlowingHourglassUses 007b9e10"); -} -void Entity_Player::update_baby_skin_effects() -{ - reconstruction_missing("Entity_Player::update_baby_skin_effects 007ba2b0"); -} -void Entity_Player::coop_baby_death_effect() -{ - reconstruction_missing("Entity_Player::coop_baby_death_effect 007bb5e0"); -} -void Entity_Player::InitBabySkin() { reconstruction_missing("Entity_Player::InitBabySkin 007bf040"); } -Entity_Laser* Entity_Player::FireDelayedBrimstone(float, Entity*) -{ - reconstruction_missing("Entity_Player::FireDelayedBrimstone 007bf1a0"); -} -uint32_t Entity_Player::GetGlitchBabySubType() -{ - reconstruction_missing("Entity_Player::GetGlitchBabySubType 007c2e90"); -} -// 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"); } -void Entity_Player::apply_victory_lap_penalty(uint32_t) -{ - reconstruction_missing("Entity_Player::apply_victory_lap_penalty 007c97f0"); -} -void Entity_Player::AddJarFlies(int) { reconstruction_missing("Entity_Player::AddJarFlies 007c9bb0"); } -bool Entity_Player::IsPosInSpotLight(Vector) { reconstruction_missing("Entity_Player::IsPosInSpotLight 007c9c00"); } -void Entity_Player::BreakGoldenHearts(int) { reconstruction_missing("Entity_Player::BreakGoldenHearts 007ca2d0"); } -void Entity_Player::apply_coop_baby_spawn_bonus() -{ - reconstruction_missing("Entity_Player::apply_coop_baby_spawn_bonus 007cb090"); -} - -// 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"); -} -Entity_Familiar* Entity_Player::AddMinisaac(Vector, bool) -{ - reconstruction_missing("Entity_Player::AddMinisaac 007d1860"); -} -void Entity_Player::AddFriendlyDip(int, Vector) { reconstruction_missing("Entity_Player::AddFriendlyDip 007d2a00"); } -void Entity_Player::ThrowFriendlyDip(int, Vector, Vector) -{ - reconstruction_missing("Entity_Player::ThrowFriendlyDip 007d2a20"); -} -void Entity_Player::AddUrnSouls(uint32_t) { reconstruction_missing("Entity_Player::AddUrnSouls 007d3480"); } -void Entity_Player::AddGigaBombs(int) { reconstruction_missing("Entity_Player::AddGigaBombs 007d34f0"); } -void Entity_Player::fire_saturnus_tears() { reconstruction_missing("Entity_Player::fire_saturnus_tears 007d3e40"); } -void Entity_Player::get_salvation_scale() { reconstruction_missing("Entity_Player::get_salvation_scale 007d4340"); } -uint32_t Entity_Player::AddItemCard(uint32_t) { reconstruction_missing("Entity_Player::AddItemCard 007d8240"); } -void Entity_Player::AttachMinecart(Entity_NPC*) { reconstruction_missing("Entity_Player::AttachMinecart 007d9180"); } -void Entity_Player::RevivePlayerGhost() { reconstruction_missing("Entity_Player::RevivePlayerGhost 007d93b0"); } -void Entity_Player::MorphToCoopGhost() { reconstruction_missing("Entity_Player::MorphToCoopGhost 007d96f0"); } -void Entity_Player::reset_body_sprite() { reconstruction_missing("Entity_Player::reset_body_sprite 007d9b70"); } -void Entity_Player::ResetPlayer() { reconstruction_missing("Entity_Player::ResetPlayer 007daed0"); } -void Entity_Player::twins_duplicate_familiars(int) -{ - reconstruction_missing("Entity_Player::twins_duplicate_familiars 007dbeb0"); -} -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() -{ - 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::CheckPoopSpellQueue(Vector) -{ - reconstruction_missing("Entity_Player::CheckPoopSpellQueue 0095ffb0"); -} -void History::merge(History&) { reconstruction_missing("History::merge 00721c80"); } diff --git a/src/entity_player_pills.cpp b/src/entity_player_pills.cpp index 73eb453..a38ef88 100644 --- a/src/entity_player_pills.cpp +++ b/src/entity_player_pills.cpp @@ -92,7 +92,6 @@ constexpr float SPIDER_GRID_ORIGIN_X = 40; constexpr float SPIDER_GRID_ORIGIN_Y = 120; constexpr float SPIDER_GRID_STEP = 40; constexpr float STAT_COLOR_TINT = 0.3f; -constexpr ColorMod BAD_GAS_CLOUDS = {{1, 1, 1, 1}, {0, 1, 0, 1}, {0, 0, 0}}; constexpr ColorMod HORF_COLOR = {{0.5f, 0.9f, 0.4f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod PARALYSIS_COLOR = {{0.6f, 0.6f, 0.6f, 1}, {0, 0, 0, 0}, {0.4f, 0.4f, 0.4f}}; constexpr ColorMod PHEROMONES_CLOUDS = {{1, 1, 1, 1}, {2, 0, 1, 1}, {0, 0, 0}}; diff --git a/src/entity_player_pockets.cpp b/src/entity_player_pockets.cpp index 0eb3fa6..2c4e2ac 100644 --- a/src/entity_player_pockets.cpp +++ b/src/entity_player_pockets.cpp @@ -186,11 +186,24 @@ int Entity_Player::GetTrinket(uint32_t slot) return slot < TRINKET_SLOT_COUNT ? (int)trinkets[slot] : 0; } -// 007db740 Echo Chamber repeats the last three cards and pills used. Not written yet. -void Entity_Player::TriggerEchoChamber(uint32_t, int) +// 007db740 Echo Chamber uses again the cards and pills it remembers, quietly, then remembers this one. It keeps only +// the first three: a fourth is dropped from the back as soon as it is added. +void Entity_Player::TriggerEchoChamber(uint32_t pocketItemType, int cardOrPillColor) { - if (HasCollectible(COLLECTIBLE_ECHO_CHAMBER)) - reconstruction_missing("Entity_Player::TriggerEchoChamber 007db740 (Echo Chamber)"); + constexpr uint32_t ECHO_USE_FLAGS = USE_MIMIC | USE_NOANNOUNCER | USE_NOHUD; + constexpr size_t ECHO_MEMORY = 3; + if (!HasCollectible(COLLECTIBLE_ECHO_CHAMBER)) return; + + for (size_t i = 0; i < echoChamberItems.size(); i++) + { + PocketItem echo = echoChamberItems[i]; + if (echo.type == POCKET_CARD) UseCard(echo.id, ECHO_USE_FLAGS); + else if (echo.type == POCKET_PILL) + UsePill(g_game->itemPool.GetPillEffect((uint32_t)echo.id, this), echo.id, ECHO_USE_FLAGS); + } + if (pocketItemType != POCKET_CARD && pocketItemType != POCKET_PILL) return; + echoChamberItems.push_back({.id = cardOrPillColor, .type = (PocketItemType)pocketItemType}); + while (echoChamberItems.size() > ECHO_MEMORY) echoChamberItems.pop_back(); } // 007abd30 Plays the thumbs up with its sound. @@ -507,3 +520,37 @@ void Entity_Player::pocket_use_input() reconstruction_missing("Entity_Player::pocket_use_input 007a3d30 (Endless Nameless' copy)"); game.hud.refresh_request(HUD_REFRESH_PLAYER); } + +constexpr size_t ITEM_CARDS_BASE = 3; +constexpr size_t ITEM_CARDS_MAX = 20; +constexpr int ITEM_CARD_DROP_COOLDOWN = 4; + +// How many item cards the player holds: 3, one more per Starter Deck, 20 at most. +static size_t item_cards_max(Entity_Player& player) +{ + return std::min((size_t)player.GetCollectibleNum(COLLECTIBLE_STARTER_DECK) + ITEM_CARDS_BASE, ITEM_CARDS_MAX); +} + +// 007d8240 Puts an item card in front of the others (drawn from the item card pool for none), dropping the oldest at a +// free spot when a given card finds the hand full. The card added, or none when the hand stays full. +uint32_t Entity_Player::AddItemCard(uint32_t itemId) +{ + if (itemId != 0 && itemCards.size() == item_cards_max(*this)) + { + Vector spot = room_free_pickup_position_find({.position = pos}); + Entity* card = g_game->Spawn({.position = spot, + .spawner = this, + .subType = (int)((uint32_t)itemCards.front() | CARD_ITEM_FLAG), + .type = ENTITY_PICKUP, + .variant = PICKUP_TAROTCARD, + .seed = Random()}); + if (card) static_cast(card)->collisionCooldown = ITEM_CARD_DROP_COOLDOWN; + itemCards.erase(itemCards.begin()); + } + if (itemCards.size() >= item_cards_max(*this)) return 0; + + if (itemId == 0) reconstruction_missing("ItemPool::GetCardImpl 007376c0 (the item card pool)"); + itemCards.insert(itemCards.begin(), (int)itemId); + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); + return itemId; +} diff --git a/src/entity_player_room.cpp b/src/entity_player_room.cpp index ef4fd72..407444e 100644 --- a/src/entity_player_room.cpp +++ b/src/entity_player_room.cpp @@ -360,7 +360,13 @@ void Entity_Player::room_enter() for (Entity* entity : room.entityList.updateEL) if (entity->type == ENTITY_ROTGUT && entity->variant == 0) { - reconstruction_missing("Entity_Player::room_enter 007a6c50: thrown out of Rotgut (Entity_Player::TryThrow)"); + // Rotgut spits the player back out, flung within 35 degrees of straight down at 6 from 18 high. + constexpr float ROTGUT_SPIT_SPREAD = 70; + constexpr float ROTGUT_SPIT_SPEED = 6; + constexpr float ROTGUT_SPIT_HEIGHT = 18; + pos = entity->pos; + float angle = (random_unit() - HALF) * ROTGUT_SPIT_SPREAD + RIGHT_ANGLE_DEGREES; + TryThrow(EntityRef(nullptr), vector_scale(vector_from_angle(angle), ROTGUT_SPIT_SPEED), ROTGUT_SPIT_HEIGHT); break; } if (HasCollectible(COLLECTIBLE_SATURNUS)) fire_saturnus_tears(); @@ -481,3 +487,11 @@ void Entity_Player::Teleport(const Vector& position, bool isDoEffects, bool isTe grid_sound_play(SOUND_HELL_PORTAL1, {.volume = TELEPORT_LEAVE_VOLUME, .frameDelay = TELEPORT_SOUND_DELAY}); Entity_Effect::CreateTimer(reinterpret_cast(&teleport_sound_play), TELEPORT_SOUND_TIMER, 0, false); } + +// 007d9180 Seats the player in a minecart, keeping where it sits from the cart's target. +// The original reads a missing cart's target and crashes. Without a cart only the seat is cleared. +void Entity_Player::AttachMinecart(Entity_NPC* cart) +{ + minecart = cart; + if (cart) minecartOffset = vector_sub(pos, cart->targetPosition); +} diff --git a/src/entity_player_tainted.cpp b/src/entity_player_tainted.cpp index b978f84..9319796 100644 --- a/src/entity_player_tainted.cpp +++ b/src/entity_player_tainted.cpp @@ -146,3 +146,10 @@ void tainted_isaac_inventory_trim(Entity_Player& player) history.isLocked = false; inventory_rebuild(history); } + +// 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; +} diff --git a/src/entity_player_trinkets.cpp b/src/entity_player_trinkets.cpp index c33f84d..8b6ce56 100644 --- a/src/entity_player_trinkets.cpp +++ b/src/entity_player_trinkets.cpp @@ -123,9 +123,30 @@ bool Entity_Player::TryHoldTrinket(int trinketId) return false; } +// Mom's Toenail dropped in a room still fighting: Mom stomps the cell it landed on (the top left corner when off the +// grid), once per multiplier, a second apart. +static void moms_toenail_stomp(Vector position, int stomps) +{ + constexpr int STOMP_DELAY_STEP = 30; + Room& room = *g_game->room; + Vector cell = room.GetGridPosition(room.GetGridIndex(position)); + for (int i = 0; i < stomps; i++) + { + uint32_t seed = Random(); + auto* stomp = static_cast(g_game->Spawn({.position = cell, + .subType = i * STOMP_DELAY_STEP, + .type = ENTITY_EFFECT, + .variant = EFFECT_MOM_FOOT_STOMP, + .seed = seed})); + stomp->targetPosition = cell; + stomp->Update(); + } +} + // 00771800 Drops the first trinket that may go (the Tick only to a trinket that burns it, with a sizzle), the next // slot moving up: it lands as a pickup at the position for a main player, its pickup effect undone and its costume -// off unless its effect wears it. Butter plays its sound. The stats are evaluated. The dropped pickup, if any. +// off unless its effect wears it. Butter plays its sound, and Mom's Toenail brings Mom's stomps in a fight. The stats +// are evaluated. The dropped pickup, if any. Entity_Pickup* Entity_Player::DropTrinket(Vector position, bool isReplaceTick) { FlushQueueItem(); @@ -180,8 +201,8 @@ Entity_Pickup* Entity_Player::DropTrinket(Vector position, bool isReplaceTick) if (!isEffectWorn) RemoveCostume(trinket); } if (id == TRINKET_BUTTER) sound_play(SOUND_BUTTER_DROP); - else if (id == TRINKET_MOMS_TOENAIL && !(g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR) && stomps > 0) - reconstruction_missing("Entity_Player::DropTrinket 00771800 (Mom's Toenail's stomps)"); + else if (id == TRINKET_MOMS_TOENAIL && !(g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR) && pickup) + moms_toenail_stomp(pickup->pos, stomps); if (cacheFlags) EvaluateItems(); return pickup; } @@ -1041,3 +1062,133 @@ void coin_trinkets_collect(Entity_Pickup& pickup, Entity_Player& player, int val if (player.HasTrinket(TRINKET_ROTTEN_PENNY)) player.AddBlueFlies(std::min(std::max(player.GetTrinketMultiplier(TRINKET_ROTTEN_PENNY), 1), 3), player.pos, nullptr); } + +constexpr int GLYPH_PICKUP_FEW = 1; +constexpr int GLYPH_PICKUP_MANY = 5; +constexpr int GLYPH_COINS_MANY = 15; +constexpr int GLYPH_CHARGE_MANY = 12; +constexpr int GLYPH_SOUL_HEARTS_FEW = 4; +constexpr int GLYPH_HEARTS_ENOUGH = 12; + +// Glyph of Balance's drop as a pickup variant and subtype, kept as it is when it is already of the chosen variant (a +// soul heart also keeps a black heart). +struct GlyphDrop +{ + int* variant = nullptr; + int* subType = nullptr; + + void set(int newVariant, int newSubType) + { + if (*variant == newVariant) return; + *variant = newVariant; + *subType = newSubType; + } + void soul_heart_set() + { + if (*variant == PICKUP_HEART && (*subType == HEART_SOUL || *subType == HEART_BLACK)) return; + *variant = PICKUP_HEART; + *subType = HEART_SOUL; + } +}; + +// Whether the player keeps its bombs (Tainted ???'s poop) for Glyph of Balance, at least a count of them. +static bool is_glyph_bombs_short(Entity_Player& player, int count) +{ + return player.playerType == PLAYER_BLUEBABY_B ? player.poopMana < count : player.numBombs < count; +} + +// The charge Bethany's or Tainted Bethany's heart drop needs: a soul heart or a red heart when short of it. +static bool glyph_charge_drop(Entity_Player& player, GlyphDrop& drop, int count) +{ + if (player.playerType == PLAYER_BETHANY && player.effectiveSoulCharge < count) drop.soul_heart_set(); + else if (player.playerType == PLAYER_BETHANY_B && player.effectiveBloodCharge < count) drop.set(PICKUP_HEART, HEART_FULL); + else return false; + return true; +} + +// 007d12c0 The pickup Glyph of Balance drops for the player, in order of need: a red heart when low on red health, a +// soul heart without containers, a key, a bomb (poop for Tainted ???), Bethany's charge, red hearts to fill the +// containers, coins, a trinket with enough of everything and none held or lying about, then more coins, keys, bombs +// and charge, and soul hearts until twelve hearts are held. Else the drop is left as it is. +void Entity_Player::GetGlyphOfBalanceDrop(int* variant, int* subType) +{ + GlyphDrop drop = {variant, subType}; + HealthType health = GetHealthType(); + bool isRedHealth = (health == HEALTH_DEFAULT || health == HEALTH_BONE) && playerType != PLAYER_BETHANY; + bool isBoneless = health == HEALTH_SOUL || health == HEALTH_NO_HEALTH; + int containers = isBoneless ? maxHearts : maxHearts + boneHearts * 2; + + if (redHearts < 2 && containers >= 2 && (health == HEALTH_DEFAULT || health == HEALTH_BONE)) + return drop.set(PICKUP_HEART, HEART_FULL); + if (containers == 0 && soulHearts < GLYPH_SOUL_HEARTS_FEW && isRedHealth) return drop.soul_heart_set(); + if (numKeys < GLYPH_PICKUP_FEW) return drop.set(PICKUP_KEY, 0); + if (playerType == PLAYER_BLUEBABY_B && poopMana < GLYPH_PICKUP_FEW) return drop.set(PICKUP_POOP, POOP_BIG); + if (playerType != PLAYER_BLUEBABY_B && numBombs < GLYPH_PICKUP_FEW) return drop.set(PICKUP_BOMB, 0); + if (glyph_charge_drop(*this, drop, GLYPH_PICKUP_FEW)) return; + if (redHearts < GetEffectiveMaxHearts() && GetEffectiveMaxHearts() >= 0 && GetHealthType() != HEALTH_COIN) + return drop.set(PICKUP_HEART, HEART_FULL); + if (numCoins < GLYPH_PICKUP_MANY) return drop.set(PICKUP_COIN, 0); + + bool isBombsKept = playerType == PLAYER_BLUEBABY_B ? poopMana != 0 : numBombs >= GLYPH_PICKUP_MANY; + if (isBombsKept && numKeys >= GLYPH_PICKUP_MANY && trinkets[0] == 0 && entity_query(ENTITY_PICKUP, PICKUP_TRINKET).empty()) + return drop.set(PICKUP_TRINKET, 0); + if (numCoins < GLYPH_COINS_MANY) return drop.set(PICKUP_COIN, 0); + if (numKeys < GLYPH_PICKUP_MANY) return drop.set(PICKUP_KEY, 0); + if (is_glyph_bombs_short(*this, GLYPH_PICKUP_MANY)) + return drop.set(playerType == PLAYER_BLUEBABY_B ? PICKUP_POOP : PICKUP_BOMB, playerType == PLAYER_BLUEBABY_B ? POOP_BIG : 0); + if (glyph_charge_drop(*this, drop, GLYPH_CHARGE_MANY)) return; + if (GetEffectiveMaxHearts() + soulHearts < std::min(GetHeartLimit(false), GLYPH_HEARTS_ENOUGH) && isRedHealth) + drop.soul_heart_set(); +} + +// 00772530 Turns a golden Store Credit back into a plain one: the one held over the head, else each held (its costume +// and effects swapped), else each smelted one in the history. True when the held over one was changed. +bool Entity_Player::replace_trinket() +{ + bool isMainPlayer = variant == PLAYER_VARIANT_PLAYER && !isCoopGhost; + ItemConfig_Item* storeCredit = g_manager->itemConfig.GetTrinket(TRINKET_STORE_CREDIT); + uint32_t golden = TRINKET_STORE_CREDIT | TRINKET_GOLDEN_FLAG; + + if (isMainPlayer) InvalidateCoPlayerItems(); + if (queuedItem.item && queuedItem.item == storeCredit && (queuedItem.flags & QUEUED_GOLDEN)) + { + queuedItem.flags &= ~QUEUED_GOLDEN; + return true; + } + + int slots = HasCollectible(COLLECTIBLE_MOMS_PURSE) || HasCollectible(COLLECTIBLE_BELLY_BUTTON) ? 2 : 1; + for (int slot = 0; slot < slots; slot++) + { + if (trinkets[slot] != golden) continue; + trinkets[slot] = TRINKET_STORE_CREDIT; + log_printf(LOG_INFO, "Replacing trinket %d (%s) from player %d (%s) with trinket %d (%s)\n", golden, + storeCredit->GetLocalizedName().c_str(), playerIndex, name.c_str(), TRINKET_STORE_CREDIT, + storeCredit->GetLocalizedName().c_str()); + TriggerTrinketRemoved(golden); + if (storeCredit->isAddCostumeOnPickup || !temporaryEffects.HasTrinketEffect(golden)) RemoveCostume(storeCredit); + TriggerTrinketAdded(TRINKET_STORE_CREDIT, false); + if (storeCredit->isAddCostumeOnPickup) AddCostume(storeCredit, false); + } + if (!isMainPlayer) return false; + + for (HistoryItem& item : history.historyItems) + { + if (!item.isTrinket || (uint32_t)item.id != golden) continue; + item.id = TRINKET_STORE_CREDIT; + SmeltedTrinket& smelted = smeltedTrinkets[storeCredit->id]; + if (smelted.goldenCount > 0) + { + smelted.goldenCount--; + TriggerTrinketRemoved(golden); + if (smelted.count < 1 && smelted.goldenCount < 1) TryRemoveTrinketCostume(golden); + smelted.count++; + TriggerTrinketAdded(TRINKET_STORE_CREDIT, false); + if (storeCredit->isAddCostumeOnPickup) AddCostume(storeCredit, false); + } + log_printf(LOG_INFO, "Replacing smelted trinket %d (%s) from player %d (%s) with trinket %d (%s)\n", golden, + storeCredit->GetLocalizedName().c_str(), playerIndex, name.c_str(), TRINKET_STORE_CREDIT, + storeCredit->GetLocalizedName().c_str()); + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); + } + return false; +} diff --git a/src/entity_player_update.cpp b/src/entity_player_update.cpp index 8fd6093..c45ff7b 100644 --- a/src/entity_player_update.cpp +++ b/src/entity_player_update.cpp @@ -14,6 +14,9 @@ #include "log.h" #include "lua_engine.h" #include "player_hud.h" +#include "player_manager.h" +#include "platform.h" +#include "game_state_player.h" #include "manager.h" #include "menu_manager.h" #include "npc_ai.h" @@ -22,6 +25,10 @@ #include "entity_combat.h" #include "active_items.h" #include "room.h" +#include "room_grid.h" +#include "entity_pickup.h" +#include "entity_laser.h" +#include "entity_projectile.h" #include "sfx_manager.h" #include "temporary_effects.h" #include "weapon_lasers.h" @@ -36,9 +43,11 @@ constexpr float SALVATION_HALO_RISE = -15; constexpr int SALVATION_TURN_FRAMES = 360; constexpr float SALVATION_GROWTH = 0.1f; constexpr float SALVATION_SCALE_MAX = 2; +constexpr float LAZARUS_TWIN_SPREAD = 15; constexpr float BREATH_OF_LIFE_RISE = -15; constexpr float FX_POOF_DEPTH = -10; constexpr float FX_POOF_RISE = -20; +constexpr float DISCONNECT_POOF_RISE = -10; constexpr int FX_POOF_SUBTYPE = 10; constexpr int POISON_BUILDUP_FRAMES = 30; @@ -69,7 +78,42 @@ constexpr float CAMO_DAMAGE = 15; constexpr float CAMO_RADIUS = 80; constexpr float CAMO_PLAYER_THRESHOLD = 50; constexpr int SLIPPERY_SLIDE_FRAMES = 60; +constexpr float SCHOOLBAG_DROP_STEP = 40; constexpr int HOW_TO_JUMP_SPECIAL_DAILY = 33; +constexpr float BELIAL_FLASH_INTERVAL = 4; +constexpr int BELIAL_FLASH_FRAMES = 4; +constexpr float BELIAL_BURN_INTERVAL = 2; +constexpr float BELIAL_FLAME_RISE = -10; +constexpr float BELIAL_FLAME_DRIFT = 0.1f; +constexpr float BELIAL_FLAME_LIFT = -2; +constexpr float BELIAL_FLAME_LIFT_RANGE = 6; +constexpr float BELIAL_FLAME_TURN = 2; +constexpr float BELIAL_FLAME_TURN_RANGE = 10; +constexpr uint32_t BELIAL_FLAME_FRAMES_RANGE = 10; +constexpr int BELIAL_FLAME_FRAMES = 10; +constexpr float BELIAL_FLAME_SIZE = 0.4f; +constexpr float BELIAL_FLAME_SIZE_RANGE = 0.3f; +constexpr int BELIAL_FLAME_DEPTH = -2000; +constexpr float BELIAL_DAMAGE = 2; +constexpr float BELIAL_DAMAGE_PER_STAGE = 0.2f; +constexpr float BELIAL_REACH = 40; +constexpr uint32_t BELIAL_PARTITIONS = QUERY_PROJECTILES | QUERY_ENEMIES; +constexpr int BELIAL_DAMAGE_COUNTDOWN = 30; +constexpr int BELIAL_BURN_FRAMES = 150; +constexpr float MONTEZUMA_MOUTH = 14; +constexpr float MONTEZUMA_OFFSET = 13; +constexpr float MONTEZUMA_BACK_DEPTH = -40; +constexpr float MONTEZUMA_SPREAD = 90; +constexpr float MONTEZUMA_SHOT_SPREAD = 30; +constexpr float MONTEZUMA_SPLASH_SPEED = 6; +constexpr float MONTEZUMA_SPLASH_SPEED_RANGE = 10; +constexpr float MONTEZUMA_SPLASH_SIZE_RANGE = 1.5f; +constexpr float MONTEZUMA_SPLASH_DEPTH = 20; +constexpr float MONTEZUMA_POOP_SPEED = 2; +constexpr float MONTEZUMA_POOP_SPEED_RANGE = 3; +constexpr float MONTEZUMA_SHOT_SPEED = 6; +constexpr float MONTEZUMA_SHOT_SPEED_RANGE = 5; +constexpr uint32_t MONTEZUMA_EXTRA_ODDS = 5; constexpr float HOW_TO_JUMP_WAVE_REACH = 90; constexpr int HOW_TO_JUMP_WAVE_FRAMES = 10; constexpr float DASH_GRID_REACH = 40; @@ -99,6 +143,12 @@ constexpr uint64_t BLEED_OUT_DAMAGE_FLAGS = DAMAGE_RED_HEARTS | DAMAGE_INVINCIBL // The seeds the frame reads: the slippery floor, the music following the player's speed, the tints, the grid's // footsteps and the timed deaths. constexpr int FRAME_SEEDS[] = {1, 2, 14, 24, 26, 27, 28, 37, 52, 53}; +// The kept Book of Belial's flash and flames: a red flash, orange flames, and red ones on a shadow's head. +constexpr ColorMod BELIAL_FLASH = {{1, 0.8f, 0.8f, 1}, {0, 0, 0, 0}, {0.8f, 0.4f, 0}}; +constexpr ColorMod BELIAL_FLAME_COLOR = {{5, 0.5f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod BELIAL_FLAME_BLACK = {{5, 0.2f, 0.21f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +// Montezuma's Revenge's brown splashes. +constexpr ColorMod MONTEZUMA_BROWN = {{0.6f, 0.34f, 0.26f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; // The poisonous gas's tints (green) and a static's (white), building up and flashing, with the exe's values. constexpr ColorMod POISON_FLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 1, 0}}; constexpr ColorMod STATIC_FLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 1, 0.6f}}; @@ -145,19 +195,60 @@ static void salvation_halo_update(Entity_Player& player) halo->sprite.rotation = (float)((g_game->frameCount - player.spawnFrame) % SALVATION_TURN_FRAMES) + half; } -// Tainted Lazarus's Birthright keeps both forms out at once: splitting them and joining them back stop the game until -// reached. +// Tainted Lazarus's Birthright brings the stored form out beside the player, fully evaluated and in control. Losing +// it puts the twin away again: it leaves the room with its familiars in a poof and leaves the list. static void lazarus_twins_update(Entity_Player& player) { if (player.playerType != PLAYER_LAZARUS_B && player.playerType != PLAYER_LAZARUS2_B) return; + PlayerManager& players = g_game->playerManager; Entity_Player* backup = player.backupPlayer; - bool isBirthright = player.HasCollectible(COLLECTIBLE_BIRTHRIGHT); - if (backup && !backup->isValid && (isBirthright || backup->HasCollectible(COLLECTIBLE_BIRTHRIGHT))) - reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Lazarus's Birthright split)"); + if (backup && !backup->isValid && + (player.HasCollectible(COLLECTIBLE_BIRTHRIGHT) || backup->HasCollectible(COLLECTIBLE_BIRTHRIGHT))) + { + player.twinPlayer = backup; + backup->twinPlayer = &player; + backup->backupPlayer = nullptr; + player.backupPlayer = nullptr; + if (std::shared_ptr saved = std::exchange(backup->unlistedRestoreState, nullptr)) + { + backup->RestoreGameState(*saved); + backup->RestoreGameState_PostLevelInit(*saved); + } + player.SetControllerIndex(player.controllerIndex, true); + if (!backup->isPostLevelInitFinished) backup->InitPostLevelInitStats(); + backup->isExists = true; + backup->pos = vector_add(player.pos, vector_scale(random_direction(), LAZARUS_TWIN_SPREAD)); + backup->velocity = player.velocity; + players.player_add(backup); + player.SyncConsumables(backup, CONSUMABLE_ALL); + backup->weaponTypes.fill(false); + backup->cacheFlags = CACHE_ALL; + backup->EvaluateItems(); + backup->isControlsEnabled = true; + backup->bodySprite.Reset(); + backup->isPlayingItemAnimation = false; + backup->sprite.SetLastFrame(); + backup->isPlayingExtraAnimation = false; + return; + } - Entity_Player* twin = player.twinPlayer ? player.twinPlayer->ToPlayer() : nullptr; - if (twin && !isBirthright && !twin->HasCollectible(COLLECTIBLE_BIRTHRIGHT) && !player.IsHologram()) - reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Lazarus's twins joined again)"); + Entity_Player* twin = player.twin_get(); + if (!twin || player.HasCollectible(COLLECTIBLE_BIRTHRIGHT) || twin->HasCollectible(COLLECTIBLE_BIRTHRIGHT) || + player.IsHologram()) + return; + player.backupPlayer = twin; + twin->backupPlayer = &player; + twin->twinPlayer = nullptr; + player.twinPlayer = nullptr; + twin->room_exit(false); + twin->isValid = false; + twin->isExists = false; + twin->playerIndex = -1; + for (Entity* entity : entity_query(ENTITY_FAMILIAR, -1)) + if (static_cast(entity)->player == twin) entity->Remove(); + uint32_t seed = Random(); + g_game->Spawn({.position = twin->pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + players.player_remove(twin); } // A changed damage multiplier asks for the damage, and a floor start left pending (a twin's) runs once nothing @@ -297,13 +388,27 @@ static void fx_event_update(Entity_Player& player) poof->rotation = 0; } -// A controller that went away pauses the game for its player, or lets a joined co-op player go. Offline the keyboard -// never goes, so it stops the game until reached. -static void controller_check(Entity_Player& player) +// A controller that went away pauses the game for a main or child player, and lets a joined co-op player go in a +// poof. Whether the player's frame stops there. +static bool controller_check(Entity_Player& player) { - bool isConnected = KAGE::Input::manager.is_device_connected(player.controllerIndex); - if (!isConnected && g_game->stageTransition.state == STAGE_TRANSITION_NONE) - reconstruction_missing("Entity_Player::Update 00782af0 (a disconnected controller)"); + if (KAGE::Input::manager.is_device_connected(player.controllerIndex) || + g_game->stageTransition.state != STAGE_TRANSITION_NONE) + return false; + + log_printf(LOG_INFO, "Controller %d has disconnected.\n", player.controllerIndex); + if (player.variant == PLAYER_VARIANT_PLAYER || player.parent) + { + g_game->pauseScreen.Show(); + return true; + } + g_game->playerManager.RemoveCoPlayer(&player); + uint32_t seed = Random(); + g_game->Spawn({.position = vector_add(player.pos, vector_make(0, DISCONNECT_POOF_RISE)), + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF01, + .seed = seed}); + return true; } // The Intruder: a hurt sets spiders loose from the player's head (always at a red heart or less, else one time in @@ -368,12 +473,26 @@ static void akeldama_update(Entity_Player& player) tear->Update(); } -// The second active is dropped as a pedestal without the Schoolbag, unless the player is a co-op ghost. +// The second active is dropped as a pedestal without the Schoolbag, unless the player is a co-op ghost. The pedestal +// keeps the slot's charge, but not its battery charge. static void schoolbag_drop_check(Entity_Player& player) { - if (player.activeItems[ACTIVE_SLOT_SECONDARY].item != 0 && !player.HasCollectible(COLLECTIBLE_SCHOOLBAG) && - !player.isCoopGhost) - reconstruction_missing("Entity_Player::Update 00782af0 (the second active dropped without the Schoolbag)"); + ActiveItemDesc& slot = player.activeItems[ACTIVE_SLOT_SECONDARY]; + if (slot.item == 0 || player.HasCollectible(COLLECTIBLE_SCHOOLBAG) || player.isCoopGhost) return; + + g_pickupIgnoreModifiers++; + uint32_t seed = player.GetCollectibleRNG(slot.item).Next(); + Vector spot = room_free_pickup_position_find({.position = player.pos, .step = SCHOOLBAG_DROP_STEP}); + auto* pedestal = static_cast(g_game->Spawn({.position = spot, + .spawner = &player, + .subType = slot.item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = seed})); + pedestal->itemPoolType = slot.unknown; + pedestal->charge = slot.charge; + player.RemoveCollectible(slot.item, false, ACTIVE_SLOT_SECONDARY, true); + g_pickupIgnoreModifiers--; } // The floor turns slippery under the seed or a slippery flag, the slide lasting a second after it. @@ -466,15 +585,75 @@ static void how_to_jump_update(Entity_Player& player) wave->SetTimeout(HOW_TO_JUMP_WAVE_FRAMES); } -// Judas's Birthright aura (the Book of Belial kept as a passive) burns around a leaping or reviving player (it stops -// the game until reached), and Dark Arts' dash ends at the next shot. +// The kept Book of Belial's flames: one rises off the player (or its "extra" layer), red on a shadow's head and orange +// otherwise, drifting with it. +static void belial_flame_spawn(Entity_Player& player) +{ + Vector at = vector_add(player.pos, player.posOffset); + LayerState* extra = player.sprite.GetLayer("extra"); + const AnimationFrame* frame = extra ? player.sprite.animState.GetLayerFrame( + extra->layerData ? extra->layerData->id : -1) + : nullptr; + if (frame) + { + Vector layer = vector_add(vector_scale(frame->pos, 1 / ROOM_SCREEN_SCALE), vector_make(0, BELIAL_FLAME_RISE)); + at = vector_add(at, vector_make(layer.x * player.playerSpriteScale.x, layer.y * player.playerSpriteScale.y)); + } + + uint32_t seed = Random(); + Vector velocity = vector_add(vector_scale(player.velocity, BELIAL_FLAME_DRIFT), + vector_make(0, BELIAL_FLAME_LIFT - random_unit() * BELIAL_FLAME_LIFT_RANGE)); + auto* flame = static_cast(g_game->Spawn({.position = at, + .velocity = velocity, + .spawner = &player, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = seed})); + LayerState& layer = *flame->sprite.GetLayer(0); + layer_additive_set(layer); + layer.color = player.headColor == SKIN_SHADOW ? BELIAL_FLAME_BLACK : BELIAL_FLAME_COLOR; + flame->rotation = random_unit() * BELIAL_FLAME_TURN_RANGE + BELIAL_FLAME_TURN; + flame->SetTimeout((int)(Random() % BELIAL_FLAME_FRAMES_RANGE) + BELIAL_FLAME_FRAMES); + float size = random_between(BELIAL_FLAME_SIZE, BELIAL_FLAME_SIZE_RANGE); + flame->sprite.scale = vector_scale(player.playerSpriteScale, size); + flame->renderZOffset = BELIAL_FLAME_DEPTH; +} + +// Judas's Birthright aura (the Book of Belial kept as a passive) burns around a leaping or reviving player: it flashes +// red, sheds flames and burns enemies close by. While leaping it also destroys the shots it touches. +static void belial_leap_aura_update(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + bool isReviving = effects.HasCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE); + if (!player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) || + (!effects.HasCollectibleEffect(COLLECTIBLE_HOW_TO_JUMP) && !isReviving)) + return; + + if (player.GetIntervalTicks(BELIAL_FLASH_INTERVAL, 0)) + player.SetColor(BELIAL_FLASH, BELIAL_FLASH_FRAMES, 1, true, true); + if (player.GetIntervalTicks(BELIAL_BURN_INTERVAL, 0)) belial_flame_spawn(player); + if (!player.GetIntervalTicks(BELIAL_BURN_INTERVAL, 0)) return; + + float damage = (float)g_game->stage_depth_get() * BELIAL_DAMAGE_PER_STAGE + BELIAL_DAMAGE; + for (Entity* entity : entity_query_radius(player.pos, player.size + BELIAL_REACH, BELIAL_PARTITIONS)) + { + if (entity->IsVulnerableEnemy(nullptr) && entity != &player && !entity->HasEntityFlags(FLAG_FRIENDLY)) + { + entity->TakeDamage(damage, DAMAGE_IGNORE_ARMOR, EntityRef(&player), BELIAL_DAMAGE_COUNTDOWN); + entity->AddBurn(EntityRef(&player), BELIAL_BURN_FRAMES, 0, false); + continue; + } + if (!entity->IsProjectile() || isReviving || entity->isDead) continue; + auto* shot = static_cast(entity); + if (!(shot->projectileFlags & PROJECTILE_CANT_HIT_PLAYER)) shot->die_without_flags(); + } +} + +// Judas's Birthright aura burns around a leaping or reviving player, and Dark Arts' dash ends at the next shot. static void leap_auras_update(Entity_Player& player) { TemporaryEffects& effects = player.temporaryEffects; - bool isLeaping = effects.HasCollectibleEffect(COLLECTIBLE_HOW_TO_JUMP) || - effects.HasCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE); - if (player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) && isLeaping) - reconstruction_missing("Entity_Player::Update 00782af0 (the Book of Belial's burning aura)"); + belial_leap_aura_update(player); if (!effects.HasCollectibleEffect(COLLECTIBLE_DARK_ARTS)) return; for (ButtonAction shot : {ACTION_SHOOT_LEFT, ACTION_SHOOT_UP, ACTION_SHOOT_RIGHT, ACTION_SHOOT_DOWN}) if (input_is_action_triggered(shot, player.controllerIndex, nullptr)) @@ -568,8 +747,11 @@ static void item_animations_update(Entity_Player& player) for (int collectible : {COLLECTIBLE_HOST_HAT, COLLECTIBLE_MAW_OF_THE_VOID}) if (player.HasCollectible(collectible) && player.IsCollectibleAnimFinished(collectible, "")) player.ClearCollectibleAnim(collectible); - if (player.temporaryEffects.HasNullEffect(NULLITEM_HEMOPTYSIS)) - reconstruction_missing("Entity_Player::Update 00782af0 (Hemoptysis's animation)"); + if (!player.temporaryEffects.HasNullEffect(NULLITEM_HEMOPTYSIS) || + !player.IsNullItemAnimFinished(NULLITEM_HEMOPTYSIS, "")) + return; + player.ClearNullItemAnim(NULLITEM_HEMOPTYSIS); + player.RemoveCostume(g_manager->itemConfig.GetNullItem(NULLITEM_HEMOPTYSIS)); } // A delayed sound plays once its delay runs out. @@ -746,12 +928,90 @@ static void temporary_effects_update(Entity_Player& player) lua_engine_get().PostPEffectUpdate(&player); } -// The living player's frame: it walks, uses its buttons and shoots, its effects and costumes update, its leaps, -// charges and timers run, and its body animates. +// A spray particle's flight: turned up to half a spread either way off the aim, then a random speed. +struct SprayFlight +{ + Vector aim{}; + float spread = 0; + float speed = 0; + float speedRange = 0; +}; + +// The velocity of one spray particle. +static Vector montezuma_velocity(const SprayFlight& flight) +{ + Vector turned = vector_rotated(flight.aim, random_unit() * flight.spread - flight.spread / 2); + return vector_scale(turned, random_between(flight.speed, flight.speedRange)); +} + +// Montezuma's Revenge's spray rides out behind the player along its beam, splashing brown water each frame, with now +// and then a bit of poop and a stray shot that only hurts enemies. +static void montezuma_spray_update(Entity_Player& player) +{ + Entity* laserEntity = player.montezumaLaser; + if (!laserEntity || laserEntity->type != ENTITY_LASER) return; + + auto* laser = static_cast(laserEntity); + Vector aim = vector_from_angle(laser->angleDegrees); + laser->parentOffset = vector_scale(aim, -MONTEZUMA_MOUTH); + Vector offset = vector_add(player.GetLaserOffset(LASER_OFFSET_NONE, aim), vector_scale(aim, MONTEZUMA_OFFSET)); + offset.y -= player.bodyScale.y * MONTEZUMA_RISE; + laser->posOffset = offset; + laser->renderDepthOffset = aim.y <= -TECH_LASER_FACING ? MONTEZUMA_BACK_DEPTH : TECH_LASER_FRONT_DEPTH; + if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; + + Vector mouth = vector_scale(aim, MONTEZUMA_MOUTH); + Vector from = vector_sub(vector_add(player.pos, offset), mouth); + uint32_t seed = Random(); + Vector splashVelocity = + montezuma_velocity({aim, MONTEZUMA_SPREAD, MONTEZUMA_SPLASH_SPEED, MONTEZUMA_SPLASH_SPEED_RANGE}); + Entity* splash = g_game->Spawn({.position = from, + .velocity = splashVelocity, + .subType = 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_WATER_SPLASH, + .seed = seed}); + splash->sprite.scale = vector_scale(splash->sprite.scale, random_between(1, MONTEZUMA_SPLASH_SIZE_RANGE)); + splash->sprite.color = MONTEZUMA_BROWN; + splash->renderDepthOffset = MONTEZUMA_SPLASH_DEPTH; + splash->Update(); + + if (Random() % MONTEZUMA_EXTRA_ODDS == 0) + { + seed = Random(); + Vector velocity = montezuma_velocity({aim, MONTEZUMA_SPREAD, MONTEZUMA_POOP_SPEED, MONTEZUMA_POOP_SPEED_RANGE}); + g_game->Spawn({.position = from, .velocity = velocity, .type = ENTITY_EFFECT, .variant = EFFECT_POOP_PARTICLE, + .seed = seed}) + ->Update(); + } + if (Random() % MONTEZUMA_EXTRA_ODDS != 0) return; + seed = Random(); + Vector velocity = + montezuma_velocity({aim, MONTEZUMA_SHOT_SPREAD, MONTEZUMA_SHOT_SPEED, MONTEZUMA_SHOT_SPEED_RANGE}); + Vector at = vector_sub(vector_add(player.pos, vector_make(offset.x, 0)), mouth); + auto* shot = static_cast(g_game->Spawn({.position = at, + .velocity = velocity, + .spawner = &player, + .type = ENTITY_PROJECTILE, + .variant = PROJECTILE_CORN, + .seed = seed})); + uint64_t flags = PROJECTILE_HIT_ENEMIES; + if (!g_game->deathmatchManager.is_active()) flags |= PROJECTILE_CANT_HIT_PLAYER; + shot->projectileFlags = flags; + shot->Update(); +} + +// The living player's frame: the glitched co-op baby glitches after appearing and then takes a new skin. It walks, +// uses its buttons and shoots, its effects and costumes update, its leaps, charges and timers run, and its body +// animates. static void living_frame_update(Entity_Player& player) { if (player.variant == PLAYER_VARIANT_COOP_BABY && player.isGlitchBaby && player.IsExtraAnimationFinished()) - reconstruction_missing("Entity_Player::Update 00782af0 (the glitched co-op baby's animation)"); + { + const std::string& animation = player.sprite.GetAnimation(); + if (animation == "Appear") player.PlayExtraAnimation("Glitch"); + else if (animation == "Glitch") player.InitBabySkin(); + } player.held_entity_follow(); camo_undies_update(player); player.update_body_animations(); @@ -768,7 +1028,7 @@ static void living_frame_update(Entity_Player& player) } gnawed_leaf_update(player); temporary_effects_update(player); - if (player.montezumaLaser) reconstruction_missing("Entity_Player::Update 00782af0 (Montezuma's Revenge's spray)"); + montezuma_spray_update(player); attached_sprites_update(player); player.sprite_scale_update(); @@ -827,7 +1087,7 @@ void Entity_Player::Update() bodySprite.Update(); fx_event_update(*this); } - controller_check(*this); + if (controller_check(*this)) return; if (isPlayingExtraAnimation && sprite.IsFinished()) isPlayingExtraAnimation = false; if (isHurtPending && !isPlayingExtraAnimation) { diff --git a/src/entity_player_weapons.cpp b/src/entity_player_weapons.cpp index ce0d03f..b7e37ff 100644 --- a/src/entity_player_weapons.cpp +++ b/src/entity_player_weapons.cpp @@ -17,11 +17,11 @@ // Stye's right eye tears float longer. constexpr float STYE_FALLING_ACCEL_SCALE = 0.5f; +constexpr int EVIL_EYE_ODDS = 30; +constexpr int EVIL_EYE_ODDS_MIN = 10; +constexpr float EVIL_EYE_SHOT_SCALE = 0.3f; 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; constexpr float HEAD_PIVOT_LIFT = -5; constexpr int PLAYER_HEAD_LAYER = 4; constexpr const char* NULL_OFFSET_NAMES[] = {"LeftEye", "RightEye", "Forehead", "Mouth", "Mouth", "MomsEye", "Tractor"}; @@ -29,7 +29,6 @@ constexpr const char* NULL_OFFSET_NAMES[] = {"LeftEye", "RightEye", "Forehead", constexpr float CROSS_EYED_ANGLE = 0.7853982f; 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; @@ -408,8 +407,8 @@ 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, 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, Evil Eye and the Lua callback are not written yet. +// The Marked target holds no tear back, and extra shots drop the Tractor Beam and end no streak. With Evil Eye, one +// shot in 30 less luck (one in 10 at best) becomes an eye instead. The co-op baby's lasers 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) @@ -463,8 +462,17 @@ Entity_Tear* Entity_Player::FireTear(const PosVel& shot, uint32_t fireFlags, Ent tear->pos = vector_make(tear->pos.x - tear->velocity.x, tear->pos.y - tear->velocity.y); lua_engine_get().PostFireTear(tear); - if (HasCollectible(COLLECTIBLE_EVIL_EYE) && !(fireFlags & TEAR_FIRE_NO_EVIL_EYE)) - reconstruction_missing("Entity_Player::FireTear 00790af0 (Evil Eye)"); + if (!HasCollectible(COLLECTIBLE_EVIL_EYE) || (fireFlags & TEAR_FIRE_NO_EVIL_EYE)) return tear; + uint32_t odds = (uint32_t)std::max(EVIL_EYE_ODDS - (int)luck, EVIL_EYE_ODDS_MIN); + if (Random() % odds != 0) return tear; + uint32_t seed = Random(); + Entity* eye = g_game->Spawn({.position = shot.position, + .velocity = vector_scale(shot.velocity, EVIL_EYE_SHOT_SCALE), + .type = ENTITY_EFFECT, + .variant = EFFECT_EVIL_EYE, + .seed = seed}); + eye->parent = this; + tear->Remove(); return tear; } @@ -665,3 +673,110 @@ ColorMod Entity_Player::get_laser_color_copy() { return laserColor; } + +// 007c37f0 Blocks fire for at least this many frames. +void Entity_Player::SetShootingCooldown(int cooldown) +{ + fireBlockCooldown = std::max(fireBlockCooldown, cooldown); +} + +constexpr float SALVATION_STACK_GROWTH = 0.1f; +constexpr float SALVATION_MAX_SCALE = 2; + +// 007d4340 Salvation's size: a tenth more per stack this room, from 1 to at most 2. +float Entity_Player::get_salvation_scale() +{ + TemporaryEffect* effect = temporaryEffects.isDisabled ? nullptr : temporaryEffects.GetCollectibleEffect(COLLECTIBLE_SALVATION); + return std::clamp((float)(effect ? effect->count : 0) * SALVATION_STACK_GROWTH + 1, 1.0f, SALVATION_MAX_SCALE); +} + +constexpr int DELAYED_BRIMSTONE_TIMEOUT = 10; +constexpr float DELAYED_BRIMSTONE_UP = -0.5f; +constexpr float DELAYED_BRIMSTONE_DEPTH_BEHIND = -10; +constexpr float DELAYED_BRIMSTONE_DEPTH_FRONT = 3000; +constexpr float AZAZEL_BEAM_RANGE_SCALE = 0.25f; +constexpr float AZAZEL_BEAM_RANGE_BASE = 32; +constexpr float AZAZEL_BEAM_MIN_DISTANCE = 60; +constexpr int SATURNUS_TEARS = 7; +constexpr float SATURNUS_SPREAD = 4; +constexpr float SATURNUS_SPEED = 10; +constexpr float SATURNUS_DAMAGE_BONUS = 5; +constexpr float SATURNUS_DAMAGE_SCALE = 1.5f; +constexpr float SATURNUS_HEIGHT = -20; +constexpr float SATURNUS_DUNGEON_OFFSET = -18; +constexpr float SATURNUS_FALL_ACCEL = -0.096f; +constexpr float SPOTLIGHT_REACH_SQUARED = 40000; +constexpr float SPOTLIGHT_HALF_ANGLE = 20; + +// 007bf1a0 Fires a Brimstone beam from another entity at an angle as the player's (Lua's FireDelayedBrimstone): mixed +// with Technology, thicker with two Brimstones, in the laser color, with the player's tear effects but Occult's, drawn +// behind when aimed up. Azazel's short beam (or Azazel's Stump's) reaches its range, 60 at least, without Brimstone. +Entity_Laser* Entity_Player::FireDelayedBrimstone(float angle, Entity* parent) +{ + bool isTech = HasCollectible(COLLECTIBLE_TECHNOLOGY); + int variant = isTech ? LASER_BRIM_TECH : LASER_THICK_RED; + if (GetCollectibleNum(COLLECTIBLE_BRIMSTONE) > 1) variant = isTech ? LASER_THICKER_BRIM_TECH : LASER_THICKER_RED; + + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = parent->pos, + .posOffset = parent->posOffset, + .source = this, + .angleDegrees = angle, + .timeout = DELAYED_BRIMSTONE_TIMEOUT, + .variant = variant}); + laser->SetColor(laserColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + TearParams params = GetTearHitParams(WEAPON_BRIMSTONE, 1, (int)(Random() & 1) * 2 - 1, nullptr); + laser->SetCollisionDamage(params.tearDamage); + laser->tearFlags = params.tearFlags; + laser->tearFlags.reset(TEAR_OCCULT); + laser->isPlayerParams = true; + bool isUp = std::sin(angle * DEGREES_TO_RADIANS) <= DELAYED_BRIMSTONE_UP; + laser->renderDepthOffset = isUp ? DELAYED_BRIMSTONE_DEPTH_BEHIND : DELAYED_BRIMSTONE_DEPTH_FRONT; + laser->parent = parent; + + bool isShortBeam = playerType == PLAYER_AZAZEL || temporaryEffects.HasTrinketEffect(TRINKET_AZAZELS_STUMP); + if (isShortBeam && !HasCollectible(COLLECTIBLE_BRIMSTONE)) + laser->maxDistance = std::max(tearRange * AZAZEL_BEAM_RANGE_SCALE + AZAZEL_BEAM_RANGE_BASE, AZAZEL_BEAM_MIN_DISTANCE); + return laser; +} + +// 007d3e40 Saturnus' ring: seven spectral tears that pierce no rocks set orbiting the player from a random angle, each +// a seventh of a turn further, 5 damage stronger and floating at its height (lower in a crawlspace), Homing, bouncing, +// Boomerang, Ludovico, Occult and plain orbits dropped. +void Entity_Player::fire_saturnus_tears() +{ + float start = random_unit() * FULL_TURN_DEGREES; + + for (int i = 0; i < SATURNUS_TEARS; i++) + { + float angle = start - (float)i * (FULL_TURN_DEGREES / SATURNUS_TEARS); + Vector offset = vector_from_angle(angle); + Vector velocity = vector_scale(vector_from_angle(angle + RIGHT_ANGLE_DEGREES), shotSpeed * SATURNUS_SPEED); + PosVel shot = {vector_add(pos, vector_scale(offset, SATURNUS_SPREAD)), velocity}; + Entity_Tear* tear = FireTear(shot, TEAR_FIRE_NO_EVIL_EYE | TEAR_FIRE_EXTRA_SHOT, nullptr, SATURNUS_DAMAGE_SCALE); + tear->SetCollisionDamage(tear->collisionDamage + SATURNUS_DAMAGE_BONUS); + tear->tearIdx = 1; + + TearFlags flags = tear->tearFlags; + for (int bit : {TEAR_NO_GRID_DAMAGE, TEAR_SPECTRAL, TEAR_ORBIT_ADVANCED}) flags.set(bit); + for (int bit : {TEAR_HOMING, TEAR_BOUNCE, TEAR_BOOMERANG, TEAR_ORBIT, TEAR_LUDOVICO, TEAR_OCCULT}) flags.reset(bit); + tear->SetTearFlags(flags); + tear->height = SATURNUS_HEIGHT; + tear->posOffset.y = tear->get_height_offset_y(SATURNUS_HEIGHT); + if (g_game->room->roomType == ROOM_DUNGEON) tear->posOffset.y = SATURNUS_DUNGEON_OFFSET; + tear->fallingSpeed = 0; + tear->fallingAccel = SATURNUS_FALL_ACCEL; + } +} + +// 007c9c00 Whether a position lies in the player's spotlight: within 200 of it and 20 degrees of where its body faces. +bool Entity_Player::IsPosInSpotLight(Vector position) +{ + Vector toward = vector_sub(position, pos); + Vector facing = vector_from_angle(bodyAngle); + float distanceSquared = vector_length_squared(toward); + float distance = std::sqrt(distanceSquared); + + if (distance > 0) toward = vector_scale(toward, 1 / distance); + if (distanceSquared >= SPOTLIGHT_REACH_SQUARED) return false; + return std::acos(toward.x * facing.x + facing.y * toward.y) * RADIANS_TO_DEGREES < SPOTLIGHT_HALF_ANGLE; +} diff --git a/src/entity_projectile.cpp b/src/entity_projectile.cpp index 0e8ad09..2e8aa31 100644 --- a/src/entity_projectile.cpp +++ b/src/entity_projectile.cpp @@ -301,7 +301,6 @@ constexpr int CIRCLE_PROC_MAX = 32; // Hits: a small player lets shots pass over, hats block falling ones, Infamy blocks some, the frozen flash. constexpr float PLAYER_HIT_SCALE_MIN = 0.5f; constexpr float HAT_CRAWLSPACE_SIDE = 0.8f; -constexpr int HIT_COUNTDOWN = 30; constexpr float ENEMY_HIT_BONUS = 5; constexpr float GRID_HIT_DAMAGE = 35; constexpr int FREEZE_DURATION = 90; @@ -1133,8 +1132,8 @@ static void side_wave_spawn(Entity_Projectile& shot) } } -// The trails shots leave: a blue fire spawning shot's and a Necro bone's glow, a side wave's shots, and the drops -// Mother's pound shots leave. The Beast's is not reconstructed. +// The trails shots leave: a blue fire spawning shot's and a Necro bone's glow, a side wave's shots, the Beast's fire +// trail and the drops Mother's pound shots leave. void Entity_Projectile::trails_update() { if ((projectileFlags & PROJECTILE_BLUE_FIRE_SPAWN) && GetIntervalTicks(TRAIL_TICKS, 0)) glow_trail_spawn(false); @@ -1142,9 +1141,32 @@ void Entity_Projectile::trails_update() glow_trail_spawn(true); if ((projectileFlags & PROJECTILE_SIDE_WAVE) && GetIntervalTicks(SIDE_WAVE_TICKS, 0)) side_wave_spawn(*this); + // War's fire balls in the Beast's fight leave a glowing trail of haemo every other frame, its glow random. + constexpr float FIRE_TRAIL_SPEED = 0.5f; + constexpr float FIRE_TRAIL_DROP = 0.5f; + constexpr float FIRE_TRAIL_GLOW = 0.7f; + constexpr float FIRE_TRAIL_GLOW_LEAST = 0.3f; + constexpr float FIRE_TRAIL_RED = 0.12f; + constexpr float FIRE_TRAIL_GREEN = 0.4f; + constexpr int FIRE_TRAIL_DEPTH = -500; bool isBeastFire = (projectileFlags & PROJECTILE_EXPLODE) && spawnerType == ENTITY_BEAST && spawnerVariant == BEAST_FIRE_BALL; - if (isBeastFire) reconstruction_missing("Entity_Projectile::Update 00653070: the Beast's fire trail"); + if (isBeastFire && GetIntervalTicks(2, 0)) + { + uint32_t seed = Random(); + Entity* trail = g_game->Spawn({.position = pos, + .velocity = vector_scale(velocity, FIRE_TRAIL_SPEED), + .spawner = this, + .type = ENTITY_EFFECT, + .variant = EFFECT_HAEMO_TRAIL, + .seed = seed}); + trail->posOffset = vector_add(posOffset, vector_make(0, fallingSpeed * FIRE_TRAIL_DROP)); + float glow = random_unit() * FIRE_TRAIL_GLOW + FIRE_TRAIL_GLOW_LEAST; + trail->SetColor({{1, 1, 1, 1}, {0.4f, 2, 0.5f, 1}, {glow * FIRE_TRAIL_RED, glow * FIRE_TRAIL_GREEN, 0}}, -1, + COLOR_PRIORITY_DEFAULT, false, true); + trail->renderZOffset = FIRE_TRAIL_DEPTH; + trail->Update(); + } fly_ball_update(*this); // Mother's pound shots drop a falling shot of their color every 4 frames. diff --git a/src/entity_tear.cpp b/src/entity_tear.cpp index 55a6c13..0bd0e34 100644 --- a/src/entity_tear.cpp +++ b/src/entity_tear.cpp @@ -14,6 +14,7 @@ #include "lua_engine.h" #include "manager.h" #include "npc_ai.h" +#include "pocket_items.h" #include "room.h" #include "room_grid.h" #include "sfx_manager.h" @@ -123,13 +124,6 @@ constexpr float TECH_ZERO_LIFT = -15; constexpr int TECH_ZERO_TIMEOUT = 3; constexpr float TECH_ZERO_DAMAGE = 0.3f; -// Eye of the Occult: Marked's pull share, the steering's strength (less under Ludovico or a boomerang) and drags. -constexpr float OCCULT_MARKED_SHARE = 10; -constexpr float OCCULT_STEER = 3; -constexpr float OCCULT_LUDOVICO_SCALE = 0.4f; -constexpr float OCCULT_BOOMERANG_SCALE = 0.5f; -constexpr float OCCULT_FRICTION = 0.8f; -constexpr float OCCULT_HOMING_FRICTION = 0.9f; // Ludovico's tears: the circling and Monstro's Lung's ones (and their own bit), the fast one, their drag, the reach // of their hits' refresh without a player, a fast tear's speed bonus and Spectral, the familiar's smaller tear, the @@ -323,19 +317,6 @@ constexpr std::array TEAR_EFFECTS = {{ {TEAR_DARK_MATTER_FLAG, "gfx/DarkMatterTearEffect.anm2"}, }}; -// A flag whose behaviour is not reconstructed yet, and where the game stops when a tear carries it. -struct UnhandledFlag -{ - int flag = 0; - const char* name = nullptr; -}; - -constexpr std::array HIT_UNHANDLED_FLAGS = {{ - {TEAR_ENEMY_TO_WISP, "Entity_Tear::ApplyTearFlagEffects 0067af60: an enemy turned to a wisp"}, - {TEAR_REROLL_ENEMY, "Entity_Tear::ApplyTearFlagEffects 0067af60: an enemy rerolled"}, - {TEAR_MOM_STOMP_WISP, "Entity_Tear::ApplyTearFlagEffects 0067af60: Mom's stomp"}, -}}; - // The drops a hit's flags mark its enemy to leave: a red heart one time in three, and the coin, card and rune drops // on death, each through a harmless hit carrying the drop. struct HitDrop @@ -357,14 +338,6 @@ static bool is_listed(const std::array& list, int value) return std::find(list.begin(), list.end(), value) != list.end(); } -// Stops the game at the first flag in the list a tear carries. -template -static void unhandled_check(const TearFlags& flags, const std::array& list) -{ - for (const UnhandledFlag& unhandled : list) - if (flags[unhandled.flag]) reconstruction_missing(unhandled.name); -} - // Whether the current room is a crawlspace, where tears drop under gravity. bool tear_room_is_crawlspace() { @@ -1256,7 +1229,20 @@ void Entity_Tear::fall_update() if (!tearFlags[TEAR_FETUS_FLAG] && fallingAccel >= GRAVITY_MIN_ACCEL) velocity.y += fallingAccel; else if (!tearFlags[TEAR_FETUS_FLAG] && height > CRAWLSPACE_SINK_HEIGHT) velocity.y += CRAWLSPACE_SINK_SPEED; - if (g_game->room->IsBeastDungeon()) reconstruction_missing("Entity_Tear::Update 006670f0: the Beast's lava"); + // In the Beast's arena a falling tear sinks into the lava 30 above the floor: an explosive one bursts, others + // splash. + constexpr float BEAST_LAVA_DEPTH = 30; + Room& room = *g_game->room; + if (!room.IsBeastDungeon() || FrameCount() <= 2 || velocity.y <= 0 || pos.y <= room.bottomRightPos.y - BEAST_LAVA_DEPTH) + return; + if (tearFlags[TEAR_EXPLOSIVE]) + { + isDead = true; + return; + } + Remove(); + g_game->Spawn({.position = pos, .subType = POOF02_LAVA_SPLASH, .type = ENTITY_EFFECT, .variant = EFFECT_POOF02, .seed = Random()}) + ->Update(); } // 00679400 Moves the tear half a step for the frame between updates, sways the worms' tears, and places its sprite at @@ -1928,8 +1914,17 @@ static void status_effects_apply(Entity& entity, const TearFlags& flags, const T coin_knock_out(position, direction); } -// E. Coli turns a vulnerable enemy that may be rerolled into poop (keeping its minecart). The wisps' flags are not -// written yet. +// The player a hit's wisp goes to: the player of the familiar that fired it, or the player that did. +static Entity_Player* wisp_owner_get(Entity* source) +{ + Entity* spawner = source ? source->GetLastSpawner() : nullptr; + if (spawner && spawner->type == ENTITY_FAMILIAR) return static_cast(spawner)->player; + return spawner && spawner->type == ENTITY_PLAYER ? spawner->ToPlayer() : nullptr; +} + +// What a hit does to a vulnerable enemy that may be rerolled: E. Coli turns it into poop (keeping its minecart), a +// wisp's flag turns it into a random wisp of its owner where the shot was, another devolves it, and another brings +// Mom's foot down on it. The original asks a missing source for its spawner. Here no wisp comes of it. static void rerollable_flags_apply(Entity& entity, const TearFlags& flags, Entity* source) { bool isRerollable = entity.type >= ENTITY_TYPE_NPC_FIRST && static_cast(entity).CanReroll() && @@ -1941,8 +1936,19 @@ static void rerollable_flags_apply(Entity& entity, const TearFlags& flags, Entit Entity* poop = g_game->Spawn({.position = entity.pos, .type = ENTITY_POOP, .seed = Random()}); if (entity.minecart) static_cast(entity.minecart.get())->MinecartUpdateChild(poop); } - unhandled_check(flags, HIT_UNHANDLED_FLAGS); - (void)source; + if (flags[TEAR_ENEMY_TO_WISP] && entity.IsVulnerableEnemy(nullptr)) + if (Entity_Player* owner = wisp_owner_get(source)) + { + owner->AddWisp(Entity_Familiar::GetRandomWisp(&source->dropRNG), source->pos, false, false); + entity.Remove(); + } + if (flags[TEAR_REROLL_ENEMY] && entity.IsVulnerableEnemy(nullptr)) game_enemy_devolve(entity, nullptr); + if (!flags[TEAR_MOM_STOMP_WISP] || !entity.IsVulnerableEnemy(nullptr)) return; + uint32_t seed = Random(); + Entity* stomp = g_game->Spawn( + {.position = entity.pos, .type = ENTITY_EFFECT, .variant = EFFECT_MOM_FOOT_STOMP, .seed = seed}); + stomp->target = &entity; + stomp->Update(); } // Holy Light's beam strikes the enemy for three times the hit's damage, its spawner's player (or the first player) diff --git a/src/entity_tear.h b/src/entity_tear.h index 9c16ec7..5c5d55a 100644 --- a/src/entity_tear.h +++ b/src/entity_tear.h @@ -218,6 +218,14 @@ constexpr int TEAR_COLOR_PRIORITY = 255; constexpr float TEAR_RIGHT_ANGLE = 90; constexpr float TEAR_HALF_TURN = 180; constexpr float TEAR_FULL_TURN = 360; +// Eye of the Occult (on tears and bombs): Marked's pull share, the steering's strength (less under Ludovico or a +// boomerang) and drags. +constexpr float OCCULT_MARKED_SHARE = 10; +constexpr float OCCULT_STEER = 3; +constexpr float OCCULT_LUDOVICO_SCALE = 0.4f; +constexpr float OCCULT_BOOMERANG_SCALE = 0.5f; +constexpr float OCCULT_FRICTION = 0.8f; +constexpr float OCCULT_HOMING_FRICTION = 0.9f; // Ocular Rift's rifts open inside the room, for a second (half that in versus). constexpr float RIFT_MARGIN = -10; constexpr int RIFT_FRAMES = 60; diff --git a/src/entity_tear_death.cpp b/src/entity_tear_death.cpp index a17c1a4..7ace9ae 100644 --- a/src/entity_tear_death.cpp +++ b/src/entity_tear_death.cpp @@ -80,19 +80,14 @@ constexpr std::array POOF_TINTS = {{ }}; constexpr PoofTint SPORE_TINT = {{{0.3f, 0.3f, 0.7f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, TEAR_SPORE}; -// Ipecac's and Bob's head's explosion: its reach by the tear's size, the damage in versus, the hydro bounce's halving, -// and the poison's green splat and cloud. +// Ipecac's and Bob's head's explosion: its reach by the tear's size, the damage in versus and the hydro bounce's +// halving. constexpr float EXPLOSION_FLAG_RADIUS = 60; constexpr float EXPLOSION_SIZE_FULL = 8.75f; constexpr float IPECAC_RADIUS = 60; constexpr float IPECAC_RADIUS_MIN = 30; constexpr float EXPLOSION_SIZE_REACH = 30; constexpr float EXPLOSION_VERSUS_DAMAGE = 35; -constexpr float CLOUD_HEIGHT_SHARE = 0.4f; -constexpr float CLOUD_DEPTH_OFFSET = -5; -constexpr int IPECAC_CLOUD_SUBTYPE = 4; -constexpr ColorMod IPECAC_SPLAT_COLOR = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {0, 85 / 255.0f, 0}}; -constexpr ColorMod IPECAC_CLOUD_COLOR = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {10 / 255.0f, 100 / 255.0f, 0}}; // A water bounce: the speed it leaves the floor at (harder for an explosive or splitting tear), and the splash it // hurts what is around with. @@ -364,21 +359,7 @@ float Entity_Tear::explode(bool isRising) float explosionScale = radius / IPECAC_RADIUS; explosion_damage({.tearFlags = tearFlags, .position = pos, .source = this, .damageFlags = damageFlags, .damage = damage, .radius = radius, .isDamageSource = false, .isLineCheck = true}); - if (!tearFlags[TEAR_POISON]) return explosionScale; - - Entity* splat = g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); - float splatScale = (random_unit() + 1) * explosionScale; - splat->sprite.scale = vector_make(splatScale, splatScale); - splat->SetColor(IPECAC_SPLAT_COLOR, -1, TEAR_COLOR_PRIORITY, false, true); - splat->Update(); - - uint32_t seed = Random(); - Entity* cloud = g_game->Spawn({.position = pos, .subType = IPECAC_CLOUD_SUBTYPE, .type = ENTITY_EFFECT, - .variant = EFFECT_BLOOD_EXPLOSION, .seed = seed}); - cloud->SetColor(IPECAC_CLOUD_COLOR, -1, TEAR_COLOR_PRIORITY, false, true); - cloud->sprite.scale = vector_make(explosionScale, explosionScale * CLOUD_HEIGHT_SHARE); - cloud->renderDepthOffset = CLOUD_DEPTH_OFFSET; - cloud->Update(); + if (tearFlags[TEAR_POISON]) poison_splash_spawn({.position = pos, .scale = explosionScale}); return explosionScale; } diff --git a/src/familiar_ai.cpp b/src/familiar_ai.cpp index c8e4da0..3539c36 100644 --- a/src/familiar_ai.cpp +++ b/src/familiar_ai.cpp @@ -6,7 +6,9 @@ #include "entity_tear.h" #include "familiar_gello.h" #include "familiar_variants.h" +#include "boss_ai.h" #include "game.h" +#include "level_generator.h" #include "item_pool.h" #include "log.h" #include "manager.h" @@ -29,6 +31,16 @@ constexpr int CHARGER_RESPAWN_FRAMES = 300; constexpr int CHARGER_RESPAWN_STAGES = 3; constexpr int BOBS_BRAIN_COOLDOWN = 60; +// A wanderer's wait at a new room's spot, from 70 to 129 frames. +constexpr uint32_t WANDER_WAIT_RANGE = 60; +constexpr int WANDER_WAIT_MIN = 70; + +// The bosses the Vanishing Twin does not copy. +constexpr int TWIN_UNCOPIED_BOSSES[] = {ENTITY_MOM, ENTITY_MOMS_HEART, ENTITY_SATAN, ENTITY_ISAAC, + ENTITY_THE_LAMB, ENTITY_MEGA_SATAN, ENTITY_MEGA_SATAN_2, + ENTITY_ULTRA_GREED, ENTITY_HUSH, ENTITY_DELIRIUM, + ENTITY_MOTHER, ENTITY_DARK_ESAU, ENTITY_DOGMA, ENTITY_BEAST}; + // The chargers' dash: speed, how much of the player's motion it takes, how long a stuck one keeps hitting the wall, and // the sounds. constexpr float CHARGE_SPEED = 10; @@ -460,7 +472,8 @@ void Entity_Familiar::charger_dash() if (variant == KNIFE_FULL) return knife_dash(*this); Room& room = *g_game->room; - if (isCollidesWithGrid || fireCooldown < -1 || !room.IsPositionInRoom(pos, CHARGE_ROOM_MARGIN)) + if ((isCollidesWithGrid || fireCooldown < -1 || !room.IsPositionInRoom(pos, CHARGE_ROOM_MARGIN)) && + !IsLilithBirthrightIncubus()) { entityGridCollisionClass = GRIDCOLL_NONE; if (GridEntity* grid = room.GetGridEntity((uint32_t)room.GetGridIndex(pos))) grid->Hurt(1, EntityRef(player)); @@ -493,15 +506,19 @@ void Entity_Familiar::charger_start(const Vector& aimDirection, int direction) // 006174c0 The chargers (Little Chubby, Bob's Brain and their kin): follow, and dash the way the player shoots once // recharged, Bob's Brain only while no other brain is out, Lil Portal only toward a spot it was sent to. A spent one -// (subtype set) hides and comes back after a while. Tainted Lilith's Incubus stops the game. +// (subtype set) hides and comes back after a while. Riding Gello with Tainted Lilith's Birthright, it dashes the way +// Gello shoots without stopping at walls, staying on Gello. void Entity_Familiar::ai_charger() { - if (IsLilithBirthrightIncubus()) return reconstruction_missing("Entity_Familiar::ai_charger 006174c0 (Incubus)"); - + bool isIncubus = IsLilithBirthrightIncubus(); if (subtype != 0) { entityCollisionClass = ENTCOLL_NONE; - if (variant == HOLY_WATER && sprite.animState.animData && sprite.animState.isPlaying) friction *= 0.3f; + if (variant == HOLY_WATER && sprite.animState.animData && sprite.animState.isPlaying) + { + friction *= 0.3f; + if (isIncubus) FollowParent(); + } else { isVisible = false; @@ -528,7 +545,16 @@ void Entity_Familiar::ai_charger() int direction = player->fireDirection; Vector aim = direction_unit(direction); TryAimAtMarkedTarget(aim, direction, nullptr); - if (fireCooldown < 0) return charger_dash(); + if (fireCooldown < 0) + { + auto* gello = isIncubus ? static_cast(get_incubus_umbilical_whip()) : nullptr; + if (gello && gello->shootDirection != DIRECTION_NONE) velocity = direction_unit(gello->shootDirection); + charger_dash(); + if (!isIncubus) return; + FollowParent(); + if (!get_incubus_umbilical_whip()) fireCooldown = CHARGE_RECOVER_FRAMES; + return; + } FollowParent(); bool isKnifePiece = variant == KNIFE_PIECE_1 || variant == KNIFE_PIECE_2; @@ -692,13 +718,60 @@ void Entity_Familiar::level_start() else if (variant == PASCHAL_CANDLE) paschal_candle_sync_effects(); else if (variant == LOST_SOUL && lost_soul_level_start(*this)) return; else if (variant == STAR_OF_BETHLEHEM) - reconstruction_missing("Entity_Familiar::level_start 0062b360 (this familiar's new floor)"); + { + int room = g_game->currentRoomIdx < 0 ? g_game->startingRoomIdx : g_game->currentRoomIdx; + coins = -1; + formationTargetOffset = vector_make((float)(room % LEVEL_GRID_WIDTH), (float)(room / LEVEL_GRID_WIDTH)); + formationOffset = formationTargetOffset; + } pos = GetFollowTargetPosition(FOLLOW_EXACT); if (variant == BLOOD_PUPPY) blood_puppy_level_start(*this); if (variant == VANISHING_TWIN) state = 0; } +// Part of 0062bb70: a wanderer forgets its path and picks a new spot and wait, Sissy Longlegs and the punching bag +// anywhere within the room's bounds (healed), the spiders at a random spot. +static void wanderer_room_enter(Entity_Familiar& wanderer) +{ + wanderer.subtype = 1; + wanderer.pathfinder.movementTarget = {}; + wanderer.pathfinder.moveDirection = {}; + Room& room = *g_game->room; + bool isSpider = wanderer.variant == Entity_Familiar::SPIDER_MOD || wanderer.variant == Entity_Familiar::SPIDER_BABY; + if (isSpider) wanderer.targetPosition = room.GetRandomPosition(0); + else + { + Vector span = vector_sub(room.bottomRightPos, room.topLeftPos); + float down = random_unit() * span.y; + float across = random_unit() * span.x; + wanderer.targetPosition = vector_add(room.topLeftPos, vector_make(across, down)); + } + wanderer.counter = (int)(Random() % WANDER_WAIT_RANGE) + WANDER_WAIT_MIN; + if (!isSpider) wanderer.health = wanderer.maxHitPoints; +} + +// Part of 0062bb70: the Vanishing Twin forgets its spot and, in an uncleared boss room, picks the first boss it can +// copy (not Mom, her heart, Satan, Isaac, the Lamb, Mega Satan, Ultra Greed, Hush, Delirium, Mother, Dark Esau, Dogma +// or the Beast, nor a friendly, persistent or attached one). +static void vanishing_twin_room_enter(Entity_Familiar& twin) +{ + twin.targetPosition = {}; + twin.coins = 0; + twin.keys = 0; + Room& room = *g_game->room; + if (room.roomType != ROOM_BOSS || room_is_clear()) return; + + for (Entity* boss : entities_live(room.entityList.updateEL)) + { + if (!boss->IsBoss() || boss->HasEntityFlags(FLAG_FRIENDLY | FLAG_PERSISTENT) || boss->parent) continue; + if (familiar_listed(TWIN_UNCOPIED_BOSSES, boss->type)) continue; + twin.coins = boss->type; + twin.keys = boss->variant; + return; + } +} + // 0062bb70 A new room: the chargers recharge, the walkers and rooted familiars stop, the delayed ones forget the path, // a few reset their state, and the spawned-for-a-room familiars go (unless the Glowing Hourglass rewound). void Entity_Familiar::room_enter() @@ -784,7 +857,7 @@ void Entity_Familiar::room_enter() case SISSY_LONGLEGS: case PUNCHING_BAG: case SPIDER_MOD: - case SPIDER_BABY: + case SPIDER_BABY: wanderer_room_enter(*this); break; case LOST_SOUL: lost_soul_room_enter(*this); break; @@ -792,7 +865,9 @@ void Entity_Familiar::room_enter() blood_puppy_room_enter(*this); break; case STAR_OF_BETHLEHEM: - case VANISHING_TWIN: reconstruction_missing("Entity_Familiar::room_enter 0062bb70 (this familiar's new room)"); + if (!isVisible) update_star_of_bethlehem_speed(false); + break; + case VANISHING_TWIN: vanishing_twin_room_enter(*this); break; case UMBILICAL_BABY: umbilical_baby_room_enter(*this); break; case WISP: case ITEM_WISP: pos = GetOrbitPosition(player->pos); break; diff --git a/src/familiar_babies.cpp b/src/familiar_babies.cpp new file mode 100644 index 0000000..85f387d --- /dev/null +++ b/src/familiar_babies.cpp @@ -0,0 +1,1178 @@ +#include "boss_ai.h" +#include "data.h" +#include "entity_effect.h" +#include "entity_factory.h" +#include "entity_familiar.h" +#include "entity_knife.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "fx_layers.h" +#include "game.h" +#include "grid_entity_door.h" +#include "item_config.h" +#include "level.h" +#include "manager.h" +#include "npc_basement.h" +#include "npc_ai.h" +#include "room.h" +#include "room_config.h" +#include "room_descriptor.h" +#include +#include +#include + +// Lil Spewer's five kinds (its state): normal, white, red, black and yellow, each with its sheet, creep, charge tint and +// wave (puddles, step, scale, damage, delay between puddles and how long each lasts, BFFS!'s extra puddles and time, +// and Lost Cork's growth). +constexpr int SPEWER_KINDS = 5; +constexpr int SPEWER_WHITE = 1; +constexpr int SPEWER_RED = 2; +constexpr int SPEWER_YELLOW = 4; +constexpr std::string_view SPEWER_SHEETS[SPEWER_KINDS] = { + "gfx/familiar/familiar_125_lilspewer.png", "gfx/familiar/familiar_125_lilspewer_white.png", + "gfx/familiar/familiar_125_lilspewer_red.png", "gfx/familiar/familiar_125_lilspewer_black.png", + "gfx/familiar/familiar_125_lilspewer_yellow.png"}; +constexpr int SPEWER_CREEPS[SPEWER_KINDS] = {EFFECT_PLAYER_CREEP_GREEN, EFFECT_PLAYER_CREEP_WHITE, + EFFECT_PLAYER_CREEP_RED, EFFECT_PLAYER_CREEP_BLACK, + EFFECT_PLAYER_CREEP_LEMON_MISHAP}; +constexpr ColorMod SPEWER_CHARGE_TINTS[SPEWER_KINDS] = {{{1, 0.8f, 0.8f, 1}, {0, 0, 0, 0}, {0.2f, 0, 0}}, + {{1, 0.8f, 0.8f, 1}, {0, 0, 0, 0}, {0.3f, 0, 0}}, + {{0.8f, 1, 1, 1}, {0, 0, 0, 0}, {0, 0.1f, 0.1f}}, + {{1, 0.8f, 0.8f, 1}, {0, 0, 0, 0}, {0.2f, 0, 0}}, + {{1, 0.8f, 0.8f, 1}, {0, 0, 0, 0}, {0.3f, 0, 0}}}; +constexpr int SPEWER_PUDDLES[SPEWER_KINDS] = {10, 18, 14, 14, 6}; +constexpr int SPEWER_BFFS_PUDDLES[SPEWER_KINDS] = {4, 0, 0, 6, 2}; +constexpr float SPEWER_STEPS[SPEWER_KINDS] = {20, 20, 20, 20, 21}; +constexpr int SPEWER_CORK_STEPS[SPEWER_KINDS] = {0, 0, 0, 0, 16}; +constexpr float SPEWER_SCALES[SPEWER_KINDS] = {0.8f, 0.8f, 0.85f, 0.8f, 0.27f}; +constexpr float SPEWER_CORK_SCALES[SPEWER_KINDS] = {0.3f, 0.3f, 0.3f, 0.3f, 0.2f}; +constexpr float SPEWER_CORK_GROWTH[] = {1, 1.25f, 1.5f}; +constexpr float SPEWER_DAMAGES[SPEWER_KINDS] = {0.35f, 0, 12, 0, 2}; +constexpr int SPEWER_DELAYS[SPEWER_KINDS] = {1, 1, 1, 1, 2}; +constexpr int SPEWER_TIMEOUTS[SPEWER_KINDS] = {25, 100, 4, 100, 80}; +constexpr int SPEWER_BFFS_TIMEOUTS[SPEWER_KINDS] = {25, 25, 4, 25, 30}; + +// Lil Spewer's charge and shot: the charge it needs, the cooldown after a shot, the charge tint's beat, the mouth's +// reach, how much of its motion bends the shot, the white kind's two curving waves, and the shot's pitch. +constexpr int SPEWER_CHARGE_FRAMES = 30; +constexpr int SPEWER_SHOT_COOLDOWN = -15; +constexpr int SPEWER_TINT_INTERVAL = 5; +constexpr int SPEWER_SHEET_FRAME = 4; +constexpr float SPEWER_MOUTH_REACH = 20; +constexpr float SPEWER_DRIFT_SHARE = 0.6f; +constexpr float SPEWER_DRIFT_BEND = 0.1f; +constexpr float SPEWER_WHITE_SPLIT = -90; +constexpr float SPEWER_WHITE_CURVE = 10; +constexpr float SPEWER_PITCH = 1.2f; +constexpr std::string_view SPEWER_CHARGE_ANIMS[] = {"ChargeSide", "ChargeUp", "ChargeSide", "ChargeDown"}; +constexpr std::string_view SPEWER_FLOAT_ANIMS[] = {"FloatSide", "FloatUp", "FloatSide", "FloatDown"}; +constexpr std::string_view SPEWER_SHOOT_ANIMS[] = {"FloatShootSide", "FloatShootUp", "FloatShootSide", + "FloatShootDown"}; + +// A wave's growth by kind: the yellow one's puddles grow in damage (up to 20) and size, and the red one's last puddle +// is bigger and lasts longer. +constexpr float WAVE_YELLOW_GROWTH = 1.5f; +constexpr float WAVE_YELLOW_DAMAGE_MAX = 20; +constexpr float WAVE_YELLOW_SCALE_STEP = 0.1f; +constexpr float WAVE_RED_LAST_SCALE = 1.75f; +constexpr int WAVE_RED_LAST_TIMEOUT = 60; + +// Acid Baby's answer to a pill: poison on every enemy and a green cloud. +constexpr float ACID_BABY_DAMAGE = 10; +constexpr int ACID_BABY_HIT_COUNTDOWN = 30; +constexpr int ACID_BABY_POISON_FRAMES = 150; +constexpr ColorMod ACID_BABY_POOF = {{1, 1, 1, 0.5f}, {0.6f, 1, 0.3f, 1}, {0, 0, 0}}; + +// Minisaac's states (landing from its spawn, transforming, then active), its looks by subtype, the Forgotten's look +// that swings a club, and its walking, flying and head animations by direction. +constexpr int MINISAAC_ACTIVE = 0; +constexpr int MINISAAC_LANDING = 1; +constexpr int MINISAAC_TRANSFORMING = 2; +constexpr int MINISAAC_FORGOTTEN = 99; +constexpr std::pair MINISAAC_LOOKS[] = {{1, "_white"}, {2, "_black"}, {3, "_blue"}, + {4, "_red"}, {5, "_green"}, {6, "_grey"}, + {7, "_shadow"}, {99, "_forgotten"}}; +constexpr std::string_view MINISAAC_FLY_ANIMS[] = {"FlyLeft", "FlyUp", "FlyRight", "FlyDown"}; +constexpr std::string_view MINISAAC_WALK_ANIMS[] = {"WalkLeft", "WalkUp", "WalkRight", "WalkDown"}; +constexpr std::string_view MINISAAC_HEAD_ANIMS[] = {"HeadLeft", "HeadUp", "HeadRight", "HeadDown"}; + +// Minisaac's motion: standing still, its lift in flight, its head's shooting frames, its fading health, and its land. +constexpr float MINISAAC_STILL = 0.01f; +constexpr float MINISAAC_FLY_LIFT = -4; +constexpr int MINISAAC_HEAD_SHOOT_FRAMES = 6; +constexpr int MINISAAC_FADE_INTERVAL = 15; +constexpr float MINISAAC_FADE = 0.2f; +constexpr float MINISAAC_LAND_VOLUME = 0.8f; +constexpr float MINISAAC_DEATH_PITCH = 1.8f; +constexpr float MINISAAC_DROP_SPEED_RANGE = 3; + +// Minisaac's flight to its target's side: its sides, how close and far it keeps (the club much closer), its sway, and +// how far it eases toward its wanted spot. +constexpr std::pair MINISAAC_SIDES[] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; +constexpr float MINISAAC_TEAR_NEAR = 40; +constexpr float MINISAAC_TEAR_FAR = 100; +constexpr float MINISAAC_CLUB_NEAR = 10; +constexpr float MINISAAC_CLUB_FAR = 20; +constexpr float MINISAAC_SWAY_FRAMES = 15; +constexpr float MINISAAC_SIDE_EASE = 0.2f; +constexpr float MINISAAC_SIDE_FARTHEST = 10000; + +// Minisaac's walk: its speed against its player's, its own pace and spacing from its seed (the shift triple 2, 7, 25), +// its drag and steps, how far past its spacing it stops near its player, how hard it keeps off its player, the spread +// from the others growing with its speed over the room's first second, when it gives up a target and when it shoots. +constexpr float MINISAAC_SPEED = 1.15f; +constexpr uint32_t MINISAAC_SHIFT_INDEX = 13; +constexpr float MINISAAC_UNIT = 2.3283061e-10f; +constexpr float MINISAAC_PACE_RANGE = 0.2f; +constexpr float MINISAAC_PACE_MIN = 0.9f; +constexpr float MINISAAC_SPACING = 15; +constexpr float MINISAAC_REACH = 1.5f; +constexpr float MINISAAC_STOP_SLACK = 4; +constexpr float MINISAAC_DRAG = 0.7f; +constexpr float MINISAAC_STEP_SHARE = 0.1f; +constexpr float MINISAAC_STEP_MAX = 2; +constexpr float MINISAAC_PLAYER_PUSH = 0.2f; +constexpr float MINISAAC_SPREAD_BASE = 0.4f; +constexpr float MINISAAC_SPREAD_MIN = 0.8f; +constexpr float MINISAAC_SPREAD_FRAMES = 30; +constexpr float MINISAAC_SPREAD_MIN_SHARE = 0.1f; +constexpr int MINISAAC_GIVE_UP_FRAMES = 10; +constexpr float MINISAAC_AIM_DOT = 0.86f; + +// Minisaac's targets: how often it looks, how far its player may be, how near counts, and a charmed one's reach. +constexpr int MINISAAC_TARGET_INTERVAL = 4; +constexpr float MINISAAC_LEASH = 800; +constexpr float MINISAAC_TARGET_RANGE = 100; +constexpr float MINISAAC_CHARMED_RANGE = 300; + +// Minisaac's shots: damage by depth and BFFS!, size by BFFS!, its tear's speed, height and smallest size, the club's +// hold, size and sound, and the rests after each. +constexpr float MINISAAC_DEPTH_DAMAGE = 0.15f; +constexpr float MINISAAC_BASE_DAMAGE = 1.2f; +constexpr float MINISAAC_BFFS_DAMAGE = 0.4f; +constexpr float MINISAAC_DAMAGE_SHARE = 0.6f; +constexpr float MINISAAC_BFFS_SCALE = 0.25f; +constexpr float MINISAAC_SCALE_SHARE = 0.75f; +constexpr float MINISAAC_SHOT_SPEED = 9; +constexpr float MINISAAC_WALK_SHOT_HEIGHT = -14; +constexpr float MINISAAC_FLY_SHOT_HEIGHT = -18; +constexpr float MINISAAC_SHOT_SCALE_MIN = 0.01f; +constexpr float MINISAAC_CLUB_HOLD = 8; +constexpr float MINISAAC_CLUB_SCALE = 0.7f; +constexpr float MINISAAC_CLUB_VOLUME = 0.6f; +constexpr float MINISAAC_CLUB_PITCH = 1.5f; +constexpr int MINISAAC_CLUB_COOLDOWN = 20; +constexpr int MINISAAC_TEAR_COOLDOWN = 10; + +// The Star of Bethlehem's map: the floor's 13 by 13 cells and the rooms off it past them, how far a step into another +// room counts, the special rooms it links (the alternate Womb's exit and Dark Room's Mega Satan room) and the top door +// cell of a room's layout. +constexpr int STAR_OFF_MAP_BASE = LEVEL_GRID_CELLS - 1; +constexpr int STAR_CELLS = LEVEL_GRID_CELLS + OFF_MAP_ROOM_COUNT; +constexpr uint16_t STAR_UNREACHED = 0xffff; +constexpr int STAR_ROOM_STEP = 3; +constexpr int STAR_SECRET_EXIT_CELL = STAR_OFF_MAP_BASE - ROOM_SECRET_EXIT_IDX; +constexpr int STAR_SECRET_EXIT_ROOM = ROOM_MAP_CELLS - ROOM_SECRET_EXIT_IDX - 1; +constexpr int STAR_MEGA_SATAN_ROOM = ROOM_MAP_CELLS - ROOM_MEGA_SATAN_IDX - 1; +constexpr int STAR_DOOR_ROW = 7; +constexpr int STAR_CORRIDOR_ROW = 3; + +// The Star's waypoints: a cell plus a fraction packed in 16 bits each (0x8000 the corner), the middle of a room wider +// or taller than one screen, and the spot near the top of Mega Satan's room. +constexpr uint32_t STAR_CORNER = 0x80008000; +constexpr uint32_t STAR_ROOM_CORNER = STAR_CORNER; +constexpr int STAR_OFFSET_ZERO = 0x8000; +constexpr float STAR_OFFSET_SCALE = 1.0f / 65536; +constexpr int STAR_WIDE_ROOM = 13; +constexpr int STAR_TALL_ROOM = 7; +constexpr uint32_t STAR_MEGA_SATAN_OFFSET = 0x60008000; + +// The Star's pace against its player's progress to the goal: far is more than 9 steps. +constexpr int STAR_FAR_STEPS = 9; +constexpr float STAR_PACE_FAR_AHEAD = 0.25f; +constexpr float STAR_PACE_AHEAD = 0.5f; +constexpr float STAR_PACE_BEHIND = 4; +constexpr float STAR_PACE_FAR_BEHIND = 8; + +// The Star in a room: a cell's span in the room, the room's corner and its centre cell (rooms of at least 8 by 5), +// Mega Satan's room lower, how far past the walls it still shows, its jump's step and height, its fade, its aura and +// its glow. +constexpr float STAR_ROOM_SPAN_X = 520; +constexpr float STAR_ROOM_SPAN_Y = 280; +constexpr float STAR_ROOM_LEFT = 40; +constexpr float STAR_ROOM_TOP = 120; +constexpr int STAR_SMALL_ROOM_WIDTH = 7; +constexpr int STAR_SMALL_ROOM_HEIGHT = 4; +constexpr int STAR_CENTRE_ROW = 4; +constexpr int STAR_CENTRE_COLUMN = 7; +constexpr float STAR_MEGA_SATAN_DROP = 280; +constexpr float STAR_ROOM_MARGIN = -60; +constexpr float STAR_JUMP_STEP = 0.025f; +constexpr float STAR_JUMP_HEIGHT = 26; +constexpr float STAR_FADE_SPAN = 60; +constexpr float STAR_AURA_REACH = 70; +constexpr int STAR_AURA_FRAMES = 2; +constexpr int STAR_AURA_MAX = 4; +constexpr uint32_t STAR_AURA_CACHE = CACHE_DAMAGE | CACHE_FIREDELAY | CACHE_TEARFLAG | CACHE_TEARCOLOR; +constexpr float STAR_GLOW_LIFT = -12; +constexpr int STAR_GLOW_DEPTH = 10000; + +// Multidimensional Baby's knife copies: how far to each side and how much faster the root knife flies. +constexpr float MULTIDIMENSIONAL_KNIFE_SIDE = 10; +constexpr float MULTIDIMENSIONAL_KNIFE_SPEED = 5; + +// A Lil Spewer kind from its state. +static int spewer_kind(Entity_Familiar& spewer) +{ + return std::clamp(spewer.state, 0, SPEWER_KINDS - 1); +} + +// 0063b240 Dresses Lil Spewer in its kind's sheet. +static void lil_spewer_sheet_load(Entity_Familiar& spewer) +{ + spewer.sprite.ReplaceSpritesheet(0, SPEWER_SHEETS[spewer_kind(spewer)]); + spewer.sprite.LoadGraphics(); +} + +// 006395e0 Lays the next creep puddle of a wave if any are left and it is inside the room, carrying the rest of the +// wave in its data. +void wave_chain_spawn(const WaveChain& wave) +{ + if (wave.puddles <= 0 || !g_game->room->IsPositionInRoom(wave.position, 0)) return; + + auto* puddle = static_cast(g_game->Spawn({.position = wave.position, + .spawner = wave.spawner, + .type = ENTITY_EFFECT, + .variant = wave.creep, + .seed = Random()})); + if (wave.creep == EFFECT_PLAYER_CREEP_LEMON_MISHAP) puddle->scale = wave.scale; + else puddle->sprite.scale = vector_make(wave.scale, wave.scale); + puddle->SetCollisionDamage(wave.damage); + puddle->timeout = wave.timeout; + puddle->lifespan = wave.timeout; + + auto data = std::make_shared(); + data->wave = wave; + data->wave.puddles = std::max(wave.puddles - 1, 0); + data->spawner = wave.spawner; + puddle->extraData = data; + puddle->Update(); +} + +// 005d4010 Entity_Effect::update_wave_chain: on its delay's frame a puddle of Lil Spewer's wave lays the next one a +// step on, the yellow wave growing, the red one's last puddle swelling and the white one curving. +void wave_chain_update(Entity_Effect& puddle) +{ + auto* data = dynamic_cast(puddle.extraData.get()); + if (!data || g_game->frameCount - puddle.spawnFrame != data->wave.delay) return; + + WaveChain next = data->wave; + if (next.kind == SPEWER_YELLOW) + { + next.damage = std::min(next.damage * WAVE_YELLOW_GROWTH, WAVE_YELLOW_DAMAGE_MAX); + next.scale += WAVE_YELLOW_SCALE_STEP; + } + else if (next.kind == SPEWER_RED && next.puddles == 1) + { + next.scale = WAVE_RED_LAST_SCALE; + next.timeout = WAVE_RED_LAST_TIMEOUT; + } + else if (next.kind == SPEWER_WHITE) next.direction = vector_rotated(next.direction, next.curve); + data->wave = next; + + Vector step = vector_length(next.direction) > 0 ? vector_resized(next.direction, next.step) : next.direction; + next.position = vector_add(puddle.pos, step); + next.creep = puddle.variant; + next.spawner = data->spawner; + wave_chain_spawn(next); +} + +// Part of 006384a0: the released shot, a wave of creep along the aim bent by its motion (two curving ones for the +// white kind), sized by its kind, BFFS! and Lost Cork. +static void lil_spewer_shoot(Entity_Familiar& spewer, Vector aim) +{ + Entity_Player& player = *spewer.player; + int kind = spewer_kind(spewer); + WaveChain wave = {.position = vector_add(vector_add(spewer.pos, spewer.velocity), vector_scale(aim, SPEWER_MOUTH_REACH)), + .spawner = &spewer, + .damage = SPEWER_DAMAGES[kind], + .scale = SPEWER_SCALES[kind], + .step = SPEWER_STEPS[kind], + .creep = SPEWER_CREEPS[kind], + .delay = SPEWER_DELAYS[kind], + .kind = spewer.state, + .puddles = SPEWER_PUDDLES[kind], + .timeout = SPEWER_TIMEOUTS[kind]}; + if (player.HasCollectible(COLLECTIBLE_BFFS)) + { + wave.puddles += SPEWER_BFFS_PUDDLES[kind]; + wave.timeout += SPEWER_BFFS_TIMEOUTS[kind]; + } + if (player.HasTrinket(TRINKET_LOST_CORK)) + { + int multiplier = player.GetTrinketMultiplier(TRINKET_LOST_CORK); + if (multiplier >= 1 && multiplier <= (int)std::size(SPEWER_CORK_GROWTH)) + wave.scale += SPEWER_CORK_SCALES[kind] * SPEWER_CORK_GROWTH[multiplier - 1]; + wave.step += (float)SPEWER_CORK_STEPS[kind]; + } + + Vector drift = vector_scale(spewer.velocity, SPEWER_DRIFT_SHARE); + Vector along = vector_scale(aim, vector_dot(aim, drift)); + if (vector_dot(aim, along) < 0) drift = vector_sub(drift, along); + Vector direction = vector_normalized(vector_add(aim, vector_scale(drift, SPEWER_DRIFT_BEND))); + + if (spewer.state == SPEWER_WHITE) + { + float split = SPEWER_WHITE_SPLIT; + wave.curve = SPEWER_WHITE_CURVE; + for (int side = 0; side < 2; side++) + { + WaveChain curved = wave; + curved.direction = vector_rotated(direction, split); + wave_chain_spawn(curved); + wave.curve = -wave.curve; + split = -split; + } + } + else + { + wave.direction = direction; + wave_chain_spawn(wave); + } + familiar_sound_play(SOUND_SPEWER, {.frameDelay = 0, .pitch = SPEWER_PITCH}); +} + +// 006384a0 FamiliarAI::lil_spewer: follows, charges while the player shoots (its head toward the shot, tinted in its +// kind's colour once full) and spews its wave on release, then rests. A mark aims it. Its kind's sheet shows a few +// frames after it spawns. +void lil_spewer_update(Entity_Familiar& spewer) +{ + spewer.FollowParent(); + if (g_game->frameCount - spewer.spawnFrame == SPEWER_SHEET_FRAME && spewer.state != 0) lil_spewer_sheet_load(spewer); + if (spewer.fireCooldown < 0 && ++spewer.fireCooldown == 0) + spewer.fireCooldown = familiar_lullaby_delay(spewer, SPEWER_CHARGE_FRAMES); + + Entity_Player& player = *spewer.player; + int facing = player.moveDirection == DIRECTION_NONE ? DIRECTION_DOWN : player.moveDirection; + int shot = spewer.lastDirection == DIRECTION_NONE ? DIRECTION_DOWN : std::clamp(spewer.lastDirection, 0, 3); + int direction = player.fireDirection; + if (vector_length(player.aimDirection) < 0.5f && !player.areOpposingShootDirectionsPressed) + direction = DIRECTION_NONE; + Vector aim = direction_unit(spewer.lastDirection); + if (spewer.TryAimAtMarkedTarget(aim, spewer.lastDirection, nullptr) && spewer.fireCooldown == 0) + direction = DIRECTION_NONE; + if (!spewer.CanPlayerFire()) return; + + if (direction == DIRECTION_NONE) + { + if (spewer.fireCooldown == familiar_lullaby_delay(spewer, SPEWER_CHARGE_FRAMES)) + { + spewer.sprite.isFlipX = facing == DIRECTION_LEFT; + spewer.sprite.Play(SPEWER_FLOAT_ANIMS[facing]); + } + if (spewer.fireCooldown < 0) return; + if (spewer.fireCooldown > 0) + { + spewer.fireCooldown = familiar_lullaby_delay(spewer, SPEWER_CHARGE_FRAMES); + return; + } + + spewer.fireCooldown = familiar_lullaby_delay(spewer, SPEWER_SHOT_COOLDOWN); + spewer.sprite.isFlipX = shot == DIRECTION_LEFT; + spewer.sprite.Play(SPEWER_SHOOT_ANIMS[shot]); + return lil_spewer_shoot(spewer, aim); + } + + int cooldown = spewer.fireCooldown; + if (cooldown < 0) return; + if (cooldown > 0) spewer.fireCooldown = --cooldown; + spewer.sprite.isFlipX = direction == DIRECTION_LEFT; + std::string_view charge = SPEWER_CHARGE_ANIMS[std::clamp(direction, 0, 3)]; + float progress = 1 - (float)cooldown / (float)familiar_lullaby_delay(spewer, SPEWER_CHARGE_FRAMES); + const AnimationData* chargeData = spewer.sprite.GetAnimationData(charge); + spewer.sprite.SetFrame(charge, chargeData ? (int)((float)chargeData->length * progress) : 0); + if (spewer.fireCooldown == 0 && spewer.IsFrame(SPEWER_TINT_INTERVAL, 0)) + spewer.SetColor(SPEWER_CHARGE_TINTS[spewer_kind(spewer)], SPEWER_TINT_INTERVAL, 0, true, false); + spewer.lastDirection = direction; +} + +// 0062c8d0 A pill taken: Acid Baby poisons every enemy (hitting it for 10) in a green cloud, and Lil Spewer turns into +// another kind with a poof. No other familiar reacts. +void Entity_Familiar::farting_baby_fart() +{ + if (variant == LIL_SPEWER) + { + int previous = state; + do state = (int)(dropRNG.Next() % SPEWER_KINDS); + while (state == previous); + lil_spewer_sheet_load(*this); + g_game->Spawn({.position = vector_add(pos, velocity), .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, + .seed = Random()}) + ->Update(); + familiar_sound_play(SOUND_POWERUP_SPEWER); + return; + } + if (variant != ACID_BABY) return; + + for (Entity* enemy : entities_live(g_game->room->entityList.updateEL)) + { + if (!enemy->IsActiveEnemy(DEAD_EXCLUDED) || IsDescendantOf(enemy)) continue; + enemy->TakeDamage(ACID_BABY_DAMAGE, 0, EntityRef(this), ACID_BABY_HIT_COUNTDOWN); + enemy->AddPoison(EntityRef(this), ACID_BABY_POISON_FRAMES, 0, false); + } + sprite.Play("Spawn"); + g_game->room->fxLayers.AddPoopFx(BAD_GAS_CLOUDS); + MakeGroundPoof(pos, ACID_BABY_POOF, 1); +} + +// 0063d2e0 FamiliarHelper::fly_head_pick_side_offset: the spot beside a target (left, right, above or below it) that +// Minisaac flies to, as far out as the walls let it and swaying in and out, the nearest to it. None when no side has +// room. +static Vector minisaac_side_spot(Entity_Familiar& minisaac, Entity& target) +{ + Vector toMinisaac = vector_sub(minisaac.pos, target.pos); + float sway = std::sin((float)(g_game->frameCount - minisaac.spawnFrame) * PI_F / MINISAAC_SWAY_FRAMES); + bool isForgotten = minisaac.subtype == MINISAAC_FORGOTTEN; + float near = target.size + (isForgotten ? MINISAAC_CLUB_NEAR : MINISAAC_TEAR_NEAR); + float far = near + (isForgotten ? MINISAAC_CLUB_FAR : MINISAAC_TEAR_FAR) + + sway * (isForgotten ? MINISAAC_CLUB_NEAR : MINISAAC_TEAR_NEAR); + + Vector spot{}; + float best = MINISAAC_SIDE_FARTHEST; + for (auto [sideX, sideY] : MINISAAC_SIDES) + { + Vector side = vector_make(sideX, sideY); + float along = std::max(vector_dot(toMinisaac, side), near); + Vector toWall = vector_sub(room_laser_target_get(target.pos, side), target.pos); + float room = vector_length(toWall); + if (room < near) continue; + + float wanted = (far - along) * MINISAAC_SIDE_EASE + along; + if (room > wanted && room > 0) toWall = vector_scale(toWall, wanted / room); + Vector candidate = vector_add(target.pos, toWall); + float distance = vector_length(vector_sub(minisaac.pos, candidate)); + if (distance >= best) continue; + spot = candidate; + best = distance; + } + return spot; +} + +// 0063d570 FamiliarHelper::fly_head_pathfind_move: Minisaac heads for its target's side (facing it to shoot when +// lined up), else its player, at a pace and spacing of its own from its seed: straight when the way is clear, else by +// the grid. It stops near its player, gives up a target with no side free for ten frames, and keeps apart from its +// player and the other Minisaacs. +static void minisaac_move(Entity_Familiar& minisaac) +{ + Entity_Player& player = *minisaac.player; + float speed = player.moveSpeed * MINISAAC_SPEED; + minisaac.shootDirection = DIRECTION_NONE; + Vector goal = player.pos; + if (Entity* target = minisaac.target) + { + goal = minisaac_side_spot(minisaac, *target); + if (vector_is_zero(goal)) + { + minisaac.friction *= MINISAAC_DRAG; + minisaac.targetPosition = {}; + if (++minisaac.headFrameDelay > MINISAAC_GIVE_UP_FRAMES) minisaac.target = nullptr; + return; + } + Vector toTarget = vector_sub(target->pos, minisaac.pos); + int direction = vector_to_direction(toTarget); + Vector facing = vector_length(toTarget) > 0 ? vector_normalized(toTarget) : toTarget; + if (vector_dot(direction_unit(direction), facing) > MINISAAC_AIM_DOT) minisaac.shootDirection = direction; + } + minisaac.headFrameDelay = 0; + + RNG rng; + rng.SetSeed(minisaac.initSeed, MINISAAC_SHIFT_INDEX); + float pace = ((float)rng.Next() * MINISAAC_UNIT * MINISAAC_PACE_RANGE + MINISAAC_PACE_MIN) * speed; + float spacing = (float)rng.Next() * MINISAAC_UNIT * MINISAAC_SPACING + MINISAAC_SPACING; + float reach = spacing * MINISAAC_REACH; + if (room_check_line(minisaac.pos, goal, LINE_MODE_GROUND, 0)) + { + minisaac.friction *= MINISAAC_DRAG; + Vector toGoal = vector_sub(goal, minisaac.pos); + float distance = vector_length(toGoal); + bool isMoving = true; + if (!minisaac.target && distance <= reach * 2) + isMoving = distance > reach + MINISAAC_STOP_SLACK && vector_length(minisaac.velocity) > 1; + if (!isMoving) minisaac.targetPosition = {}; + else + { + Vector direction = distance > 0 ? vector_scale(toGoal, 1 / distance) : toGoal; + float step = std::min(distance * MINISAAC_STEP_SHARE, MINISAAC_STEP_MAX); + minisaac.targetPosition = vector_scale(direction, pace * step); + minisaac.velocity = vector_add(minisaac.velocity, vector_scale(minisaac.targetPosition, 1 / minisaac.friction)); + } + } + else + { + minisaac.pathfinder.FindGridPath(goal, pace, 0, DIRECT_PATH_FAR); + minisaac.targetPosition = minisaac.velocity; + } + + Vector push{}; + Vector fromPlayer = vector_sub(minisaac.pos, player.pos); + float playerDistance = vector_length(fromPlayer); + if (playerDistance > 0 && reach > playerDistance) + push = vector_scale(fromPlayer, MINISAAC_PLAYER_PUSH * (1 - playerDistance / reach) / playerDistance); + float speedShare = std::clamp(vector_length(minisaac.velocity) + MINISAAC_SPREAD_BASE, MINISAAC_SPREAD_MIN, + MINISAAC_STEP_MAX); + Room& room = *g_game->room; + float age = room.isInitialized ? (float)(g_game->frameCount - room.enterFrame) : -1; + float spread = std::clamp(age / MINISAAC_SPREAD_FRAMES, 0.0f, 1.0f) * speedShare; + for (Entity_Familiar* other : familiar_query(minisaac.variant)) + { + if (other == &minisaac || other->player != minisaac.player) continue; + Vector away = vector_sub(minisaac.pos, other->pos); + float distance = vector_length(away); + if (distance > 0 && spacing > distance && spread > MINISAAC_SPREAD_MIN_SHARE) + push = vector_add(push, vector_scale(away, spread / distance)); + } + minisaac.velocity = vector_add(minisaac.velocity, push); +} + +// Whether Minisaac may pick an entity as its target (part of 0063dd60): an enemy (or a versus player) it can hit and see, +// with a free side to fly to. +static bool minisaac_can_target(Entity_Familiar& minisaac, Entity& enemy) +{ + bool isVersusPlayer = g_game->deathmatchManager.is_active() && enemy.type == ENTITY_PLAYER; + if (!isVersusPlayer && (enemy.type < ENTITY_FIRST_ENEMY || enemy.type > ENTITY_LAST_ENEMY)) return false; + if (enemy.entityCollisionClass == ENTCOLL_PLAYERONLY || enemy.entityCollisionClass == ENTCOLL_NONE) return false; + if (enemy.isInvincible || enemy.isDead) return false; + bool isUntargetable = enemy.HasEntityFlags(FLAG_NO_TARGET); + if (isUntargetable && enemy.type != ENTITY_BLOOD_PUPPY && enemy.type != ENTITY_DARK_ESAU) return false; + if (minisaac.IsDescendantOf(&enemy) || enemy.HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) return false; + return room_check_line(minisaac.pos, enemy.pos, LINE_MODE_PROJECTILE, 0); +} + +// 0063dd60 Every fourth frame Minisaac keeps a target that can still be hurt, else picks the nearest it can see within +// 100 (favouring its current one) that has a free side, dropping any once its player is 800 away. A charmed Minisaac +// targets its charmer's target within 300, never an invincible player. +static void minisaac_find_target(Entity_Familiar& minisaac) +{ + if (minisaac.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused()) return; + if ((g_game->frameCount + minisaac.index) % MINISAAC_TARGET_INTERVAL != 0) return; + + if (vector_length(vector_sub(minisaac.player->pos, minisaac.pos)) > MINISAAC_LEASH) + { + minisaac.target = nullptr; + return; + } + Entity* current = minisaac.target; + if (current && current->IsVulnerableEnemy(nullptr)) return; + + if (!minisaac.HasEntityFlags(FLAG_CHARM)) + { + Entity* best = nullptr; + float bestScore = 0; + for (Entity* enemy : entities_live(g_game->room->entityList.updateEL)) + { + if (!minisaac_can_target(minisaac, *enemy)) continue; + float closeness = std::max(MINISAAC_TARGET_RANGE - vector_length(vector_sub(enemy->pos, minisaac.pos)), 0.0f); + float score = (enemy == current ? MINISAAC_TARGET_RANGE : 0) + closeness; + if (score <= bestScore || vector_is_zero(minisaac_side_spot(minisaac, *enemy))) continue; + best = enemy; + bestScore = score; + } + minisaac.target = best; + return; + } + + if (current && current->type == ENTITY_PLAYER && static_cast(current)->HasInvincibility(0, EntityRef())) + minisaac.target = nullptr; + if (minisaac.target) return; + Entity* charmer = minisaac.player->parent; + if (!charmer || !charmer->IsEnemy()) return; + Entity* charmerTarget = static_cast(charmer)->GetPlayerTarget(); + if (vector_length(vector_sub(minisaac.pos, charmerTarget->pos)) > MINISAAC_CHARMED_RANGE) return; + minisaac.target = charmerTarget; +} + +// 0063ce20 Minisaac fires when facing its target and rested: a small tear carried a little by its motion (stronger and +// bigger with BFFS!, deeper floors hitting harder), or for the Forgotten's look a swing of a small bone club. +static void minisaac_fire(Entity_Familiar& minisaac) +{ + if (minisaac.shootDirection >= 0 && minisaac.fireCooldown <= 0) + { + Vector aim = direction_unit(minisaac.shootDirection); + float depthDamage = (float)g_game->stage_depth_get() * MINISAAC_DEPTH_DAMAGE + MINISAAC_BASE_DAMAGE; + float damage = (minisaac.GetMultiplier() * MINISAAC_BFFS_DAMAGE + MINISAAC_DAMAGE_SHARE) * depthDamage; + float scale = minisaac.GetMultiplier() * MINISAAC_BFFS_SCALE + MINISAAC_SCALE_SHARE; + if (minisaac.subtype == MINISAAC_FORGOTTEN) + { + auto* club = static_cast(g_game->Spawn({.position = minisaac.pos, + .spawner = &minisaac, + .subType = KNIFE_SUBTYPE_HELD_ITEM, + .type = ENTITY_KNIFE, + .variant = KNIFE_BONE_CLUB, + .seed = Random()})); + club->parent = &minisaac; + club->targetPosition = vector_make(MINISAAC_CLUB_HOLD, 0); + club->posOffset = vector_make(0, -MINISAAC_CLUB_HOLD); + club->rotation = vector_angle(vector_cardinal(aim)); + club->SetCollisionDamage(damage + damage); + club->sprite.scale = vector_make(scale * MINISAAC_CLUB_SCALE, scale * MINISAAC_CLUB_SCALE); + club->SetAttackAnimation(); + club->Update(); + minisaac.fireCooldown = MINISAAC_CLUB_COOLDOWN; + familiar_sound_play(SOUND_SHELLGAME, {.volume = MINISAAC_CLUB_VOLUME, .pitch = MINISAAC_CLUB_PITCH}); + } + else + { + Vector drift = vector_scale(minisaac.velocity, HALF); + Vector facing = vector_length(aim) > 0 ? vector_normalized(aim) : aim; + float along = vector_dot(drift, facing); + if (along < 0) drift = vector_sub(drift, vector_scale(vector_normalized(aim), along)); + Vector velocity = vector_add(vector_scale(aim, MINISAAC_SHOT_SPEED), drift); + auto* tear = static_cast(g_game->Spawn({.position = minisaac.pos, + .velocity = velocity, + .spawner = &minisaac, + .type = ENTITY_TEAR, + .seed = Random()})); + tear->SetCollisionDamage(damage); + tear->SetHeight(minisaac.entityGridCollisionClass == GRIDCOLL_GROUND ? MINISAAC_WALK_SHOT_HEIGHT + : MINISAAC_FLY_SHOT_HEIGHT); + float size = std::max(scale * HALF * tear->baseScale, MINISAAC_SHOT_SCALE_MIN); + tear->baseScale = size; + tear->fScale = size; + tear->ResetSpriteScale(); + minisaac.TryFireTear(tear); + tear->Update(); + minisaac.shot_owner_convert(tear); + minisaac.fireCooldown = MINISAAC_TEAR_COOLDOWN; + familiar_sound_play(SOUND_TEARS_FIRE); + } + } + if (minisaac.fireCooldown > 0) minisaac.fireCooldown--; +} + +// Part of 0060de70: Minisaac starts walking down with its head down, ready to shoot, in the look of its subtype (the +// recoloured sheets beside its own). +void minisaac_init(Entity_Familiar& minisaac) +{ + minisaac.sprite.SetFrame("WalkDown", 0); + minisaac.sprite.SetOverlayFrame("HeadDown", 0); + minisaac.fireCooldown = 0; + minisaac.headFrameDelay = 0; + minisaac.state = MINISAAC_ACTIVE; + minisaac.entityGridCollisionClass = GRIDCOLL_GROUND; + minisaac.shootDirection = DIRECTION_NONE; + if (minisaac.subtype == 0) return; + + std::string_view suffix; + for (auto [subtype, look] : MINISAAC_LOOKS) + if (subtype == minisaac.subtype) suffix = look; + for (int layer = 0; layer < (int)minisaac.sprite.layerStates.size(); layer++) + { + const std::string& sheet = minisaac.sprite.layerStates[layer].spriteSheetPath; + size_t dot = sheet.find_last_of('.'); + if (dot == std::string::npos) continue; + std::string path = g_manager->modManager.TryRedirectPath(sheet.substr(0, dot) + std::string(suffix) + sheet.substr(dot)); + std::error_code error; + if (std::filesystem::exists(resource_path(path), error)) minisaac.sprite.ReplaceSpritesheet(layer, path); + } + minisaac.sprite.LoadGraphics(); +} + +// Part of 0063c1c0: Minisaac's death, a small poof with a squeak and a drop or two of blood. +static void minisaac_death(Entity_Familiar& minisaac) +{ + familiar_sound_play(SOUND_ISAAC_HURT_GRUNT, {.volume = MINISAAC_LAND_VOLUME, .pitch = MINISAAC_DEATH_PITCH}); + g_game->Spawn({.position = minisaac.pos, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}) + ->sprite.Play("Poof_Small"); + for (uint32_t drops = (Random() & 1) + 1; drops > 0; drops--) + { + float turn = random_unit() * RANDOM_HALF_TURN * 2; + Vector spot = vector_add(minisaac.pos, vector_scale(vector_make(std::cos(turn), std::sin(turn)), minisaac.size * HALF)); + float fling = random_unit() * RANDOM_HALF_TURN * 2; + float speed = random_unit() * MINISAAC_DROP_SPEED_RANGE + 1; + Vector velocity = vector_scale(vector_make(std::cos(fling), std::sin(fling)), speed); + g_game->Spawn({.position = spot, .velocity = velocity, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_PARTICLE, + .seed = Random()}) + ->Update(); + } +} + +// 0063c1c0 Minisaac walks (or flies, over pits) toward its target's side or its player, its head turned to its shot, +// firing and fading a little every half second. A fresh one lands and transforms first. Its death poofs. +void minisaac_update(Entity_Familiar& minisaac) +{ + if (!minisaac.player) return; + + int gridClass = minisaac.entityGridCollisionClass; + bool isFlying = gridClass == GRIDCOLL_NONE || gridClass == GRIDCOLL_WALLS || gridClass == GRIDCOLL_WALLS_X || + gridClass == GRIDCOLL_WALLS_Y; + ANM2& sprite = minisaac.sprite; + if (minisaac.state == MINISAAC_ACTIVE) + { + float speed = vector_length(minisaac.targetPosition); + int direction = speed <= MINISAAC_STILL ? DIRECTION_DOWN : vector_to_direction(minisaac.targetPosition); + float playback = std::clamp(speed, HALF, 1.0f); + if (isFlying) + { + sprite.Play(MINISAAC_FLY_ANIMS[direction]); + sprite.playbackSpeed = playback; + } + else if (speed <= MINISAAC_STILL) sprite.SetFrame("WalkDown", 0); + else + { + sprite.Play(MINISAAC_WALK_ANIMS[direction]); + sprite.playbackSpeed = playback; + } + minisaac.posOffset.y = isFlying ? MINISAAC_FLY_LIFT : 0; + + int headDirection = minisaac.shootDirection != DIRECTION_NONE ? minisaac.shootDirection : direction; + if (sprite.SetOverlayAnimation(MINISAAC_HEAD_ANIMS[headDirection]) && sprite.overlayAnimState.animData) + sprite.overlayAnimState.SetFrameFloat(minisaac.fireCooldown > MINISAAC_HEAD_SHOOT_FRAMES ? 1 : 0); + minisaac_move(minisaac); + minisaac_find_target(minisaac); + minisaac_fire(minisaac); + if (!minisaac.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && !g_game->IsPaused() && + g_game->frameCount % MINISAAC_FADE_INTERVAL == 0 && minisaac.health > 1) + minisaac.health -= MINISAAC_FADE; + } + else if (minisaac.state == MINISAAC_LANDING || minisaac.state == MINISAAC_TRANSFORMING) + { + if (sprite.animState.animData && sprite.IsEventTriggered("Land")) + { + minisaac.velocity = {}; + familiar_sound_play(SOUND_MEAT_IMPACTS, {.volume = MINISAAC_LAND_VOLUME}); + } + bool isLanded = minisaac.state == MINISAAC_TRANSFORMING || + (sprite.animState.animData && sprite.animState.WasEventTriggered("Land")); + if (isLanded) minisaac.friction *= HALF; + if (!sprite.animState.animData || !sprite.animState.isPlaying) + { + if (minisaac.state == MINISAAC_LANDING) + { + sprite.Play(isFlying ? "TransformFlying" : "Transform"); + minisaac.state = MINISAAC_TRANSFORMING; + } + else + { + minisaac.state = MINISAAC_ACTIVE; + minisaac.entityCollisionClass = ENTCOLL_ALL; + } + } + } + if (minisaac.isDead) minisaac_death(minisaac); +} + +// 0064ccf0 A room's cell on the Star's map: the Dark Room's Mega Satan room sits above the start, the other rooms off +// the map past it. +static int star_cell(int gridIndex) +{ + Game& game = *g_game; + if (!game.IsGreedMode() && game.stage == STAGE_DARK_ROOM && gridIndex == ROOM_MEGA_SATAN_IDX) + return game.startingRoomIdx - LEVEL_GRID_WIDTH; + return gridIndex < 0 ? STAR_OFF_MAP_BASE - gridIndex : gridIndex; +} + +// The floor's depth as the Star reads it, a labyrinth counting as its second floor. +static int star_stage() +{ + int stage = (int)g_game->stage; + bool isFirstFloor = stage == STAGE_BASEMENT_I || stage == STAGE_CAVES_I || stage == STAGE_DEPTHS_I || stage == STAGE_WOMB_I; + return isFirstFloor && (g_game->GetCurses() & CURSE_OF_LABYRINTH) ? stage + 1 : stage; +} + +// The Dark Room's cell above the start, or the Mega Satan room's place off the map. +static int star_mega_satan_cell() +{ + Game& game = *g_game; + return !game.IsGreedMode() && game.stage == STAGE_DARK_ROOM ? game.startingRoomIdx - LEVEL_GRID_WIDTH + : STAR_OFF_MAP_BASE - ROOM_MEGA_SATAN_IDX; +} + +// 0064cd30 level_get_room_neighbors: the cells beside a cell holding rooms, and the links off the map: the alternate +// Womb's last boss to its exit, and the Dark Room's start to the Mega Satan room. +static std::vector star_neighbors(int cell) +{ + Game& game = *g_game; + std::vector neighbors; + if (cell < LEVEL_GRID_CELLS) + { + int column = cell % LEVEL_GRID_WIDTH; + int row = cell / LEVEL_GRID_WIDTH; + if (column > 0 && game.roomMap[cell - 1] != -1) neighbors.push_back(star_cell(cell - 1)); + if (column < LEVEL_GRID_WIDTH - 1 && game.roomMap[cell + 1] != -1) neighbors.push_back(star_cell(cell + 1)); + if (row > 0 && game.roomMap[cell - LEVEL_GRID_WIDTH] != -1) + neighbors.push_back(star_cell(cell - LEVEL_GRID_WIDTH)); + if (row < LEVEL_GRID_WIDTH - 1 && game.roomMap[cell + LEVEL_GRID_WIDTH] != -1) + neighbors.push_back(star_cell(cell + LEVEL_GRID_WIDTH)); + } + if (game.IsGreedMode()) return neighbors; + + int stage = star_stage(); + if (stage == STAGE_WOMB_II && game.IsAltPath() && game.lastBossRoomListIdx >= 0) + { + int boss = star_cell(game.roomList[game.lastBossRoomListIdx].safeGridIndex); + if (cell == boss) neighbors.push_back(STAR_SECRET_EXIT_CELL); + if (cell == STAR_SECRET_EXIT_CELL) neighbors.push_back(boss); + } + else if (stage == STAGE_DARK_ROOM) + { + int start = star_cell(game.startingRoomIdx); + int above = star_mega_satan_cell(); + if (cell == start) neighbors.push_back(above); + if (cell == above) neighbors.push_back(start); + } + return neighbors; +} + +// 0064cf20 Level::compute_room_distances: every cell's distance to a cell, a step within a room costing 1 and into +// another room 3, and the distance from another cell. Its neighbour nearest the goal is the next step there. +static uint16_t star_distance(int from, int to, int* nextStep = nullptr) +{ + std::array distances; + distances.fill(STAR_UNREACHED); + std::vector open = {to}; + distances[to] = 0; + while (!open.empty()) + { + int cell = open.back(); + open.pop_back(); + for (int neighbor : star_neighbors(cell)) + { + bool isSameRoom = cell < LEVEL_GRID_CELLS && neighbor < LEVEL_GRID_CELLS && + g_game->roomMap[neighbor] == g_game->roomMap[cell]; + int distance = distances[cell] + (isSameRoom ? 1 : STAR_ROOM_STEP); + if (distance >= distances[neighbor]) continue; + distances[neighbor] = (uint16_t)distance; + open.push_back(neighbor); + } + } + if (nextStep) + { + *nextStep = -1; + uint16_t best = STAR_UNREACHED; + for (int neighbor : star_neighbors(from)) + { + if (distances[neighbor] >= best) continue; + best = distances[neighbor]; + *nextStep = neighbor; + } + } + return distances[from]; +} + +// The cell of a room's top door, where the Dark Room's start saves its door to Mega Satan. +static int star_top_door_cell(const RoomConfig_Room& room) +{ + switch (room.shape) + { + case ROOMSHAPE_LTL: return (room.width + 1) * STAR_DOOR_ROW; + case ROOMSHAPE_IH: + case ROOMSHAPE_IIH: return room.width * STAR_CORRIDOR_ROW + STAR_DOOR_ROW; + default: return STAR_DOOR_ROW; + } +} + +// 0064d370 star_of_bethlehem_get_target_room: the cell the Star leads to, the floor's last boss room: Delirium's in +// the Void, the exit on the alternate Womb, and in the Dark Room Mega Satan's once its door above the start opens. +// None without one. +static int star_goal_cell() +{ + Game& game = *g_game; + int roomIdx = game.lastBossRoomListIdx; + int stage = star_stage(); + if (!game.IsGreedMode()) + { + if (stage == STAGE_VOID) roomIdx = game.firstBossRoomListIdx; + else if (stage == STAGE_WOMB_II && game.IsAltPath()) roomIdx = STAR_SECRET_EXIT_ROOM; + else if (stage == STAGE_DARK_ROOM) + { + RoomDescriptor* start = game.GetRoomByIdx(game.startingRoomIdx, -1); + if (start->data && start->doors[DOOR_UP0] >= 0 && + !game.GetRoomByIdx(start->doors[DOOR_UP0], -1)->data) + { + bool isOpened = false; + if (game.GetCurrentRoomDesc() == start) + { + GridEntity_Door* door = game.room->doors[DOOR_UP0]; + isOpened = door && door->targetRoomIdx == ROOM_MEGA_SATAN_IDX && door->state == DOOR_STATE_OPEN; + } + else + { + const GridEntityDesc& saved = start->savedGridEntities[star_top_door_cell(*start->data)]; + isOpened = saved._type == GRID_DOOR && saved._state == DOOR_STATE_OPEN; + } + if (isOpened) roomIdx = STAR_MEGA_SATAN_ROOM; + } + } + } + return roomIdx < 0 ? -1 : star_cell(game.roomList[roomIdx].safeGridIndex); +} + +// The room index of a cell on the Star's map: the Dark Room's cell above the start is Mega Satan's room, and the +// other negative cells fold as the map does. +static int star_room_index(int cell) +{ + Game& game = *g_game; + if (!game.IsGreedMode() && game.stage == STAGE_DARK_ROOM && cell == game.startingRoomIdx - LEVEL_GRID_WIDTH) + return ROOM_MEGA_SATAN_IDX; + return cell < 0 ? STAR_OFF_MAP_BASE - cell : cell; +} + +// A point on the Star's map: a cell with a fraction in each half of a packed offset (0x8000 the cell's corner). +static Vector star_point(int cell, uint32_t offset) +{ + return vector_make((float)(cell % LEVEL_GRID_WIDTH) + (float)((int)(offset & 0xffff) - STAR_OFFSET_ZERO) * STAR_OFFSET_SCALE, + (float)(cell / LEVEL_GRID_WIDTH) + (float)((int)(offset >> 16) - STAR_OFFSET_ZERO) * STAR_OFFSET_SCALE); +} + +// The cell under a point on the Star's map. +static int star_point_cell(Vector point) +{ + return (int)(point.y + HALF) * LEVEL_GRID_WIDTH + (int)(point.x + HALF); +} + +// 0064d1d0 The Star's pace (its orbit angle offset): a quarter in another dimension or far ahead of its player on the +// way to the goal, half when ahead, four times when behind and eight when far behind, else (or when forced) its own. +void Entity_Familiar::update_star_of_bethlehem_speed(bool isForce) +{ + orbitAngleOffset = 1; + if (isForce || vector_is_zero(formationOffset)) return; + if (g_game->currentDimensionIdx != 0) + { + orbitAngleOffset = STAR_PACE_FAR_AHEAD; + return; + } + + int from = g_game->currentRoomIdx; + int goal = star_goal_cell(); + if (from < 0) return; + auto star = (int16_t)star_distance(star_point_cell(formationOffset), goal); + auto playerDistance = (int16_t)star_distance(from, goal); + if (star + STAR_FAR_STEPS < playerDistance) orbitAngleOffset = STAR_PACE_FAR_AHEAD; + else if (star < playerDistance) orbitAngleOffset = STAR_PACE_AHEAD; + else if (star > playerDistance + STAR_FAR_STEPS) orbitAngleOffset = STAR_PACE_FAR_BEHIND; + else if (star > playerDistance) orbitAngleOffset = STAR_PACE_BEHIND; +} + +// Part of 0060de70: the Star starts in the room its player is in (the last one between rooms, the start off the main +// dimension), at the room's corner, its pace even. +void star_of_bethlehem_init(Entity_Familiar& star) +{ + Game& game = *g_game; + int room = game.currentRoomIdx < 0 ? game.lastRoomIdx : game.currentRoomIdx; + if (game.currentDimensionIdx != 0 || room < 0) room = game.startingRoomIdx; + star.coins = -1; + star.hearts = (int)STAR_CORNER; + star.keys = 0; + star.orbitSpeed = 0; + star.orbitAngleOffset = 1; + star.formationTargetOffset = star_point(room, STAR_ROOM_CORNER); + star.formationOffset = star.formationTargetOffset; +} + +// Part of 0064d5f0: the Star's next waypoint toward the goal (from where it stands, or from its waypoint when sent on), +// a room's centre (its middle for a big room, near the top for Mega Satan's) once it reached the goal's room. +static Vector star_route(Entity_Familiar& star, int cell, int goal) +{ + Vector waypoint = star_point(star.coins, (uint32_t)star.hearts); + if (star.keys == 0) + { + int here = star_room_index(cell); + int there = star_room_index(goal); + RoomDescriptor* hereRoom = g_game->GetRoomByIdx(here, 0); + RoomDescriptor* goalRoom = g_game->GetRoomByIdx(there, 0); + if (hereRoom == goalRoom && goalRoom->data) + { + uint32_t offset = STAR_CORNER; + if (goalRoom->data->width > STAR_WIDE_ROOM) offset = (offset & 0xffff0000) | 0xffff; + if (goalRoom->data->height > STAR_TALL_ROOM) offset |= 0xffff0000; + if (there == ROOM_MEGA_SATAN_IDX) offset = STAR_MEGA_SATAN_OFFSET; + star.coins = goal; + star.hearts = (int)offset; + star.keys = 1; + waypoint = star_point(goal, offset); + } + } + + Vector at = star.formationOffset; + bool isArrived = star.coins < 0 || (at.x == waypoint.x && at.y == waypoint.y); + if (((isArrived && star.orbitSpeed == 0) || star.state == 1) && goal >= 0) + { + if (star.state == 1 && star.coins >= 0) cell = star.coins; + star.state = 0; + int next = -1; + if (cell != goal) star_distance(cell, goal, &next); + if (next >= 0) + { + star.coins = next; + star.hearts = (int)STAR_CORNER; + star.keys = 0; + waypoint = star_point(next, STAR_CORNER); + star.orbitSpeed = (unsigned)cell < LEVEL_GRID_CELLS && (unsigned)next < LEVEL_GRID_CELLS ? 0 : STAR_JUMP_STEP; + } + } + return waypoint; +} + +// Part of 0064d5f0: the Star glides toward its waypoint at its pace, or between dimensions jumps over a second +// (rising, then falling back as it lands on the waypoint). +static void star_glide(Entity_Familiar& star, Vector waypoint) +{ + if (star.coins < 0) return; + if (star.orbitSpeed > 0) + { + star.orbitSpeed += STAR_JUMP_STEP; + if (star.orbitSpeed < 1) return; + star.orbitSpeed = -1; + star.formationTargetOffset = waypoint; + star.formationOffset = waypoint; + return; + } + if (star.orbitSpeed < 0) + { + star.orbitSpeed += STAR_JUMP_STEP; + if (star.orbitSpeed >= 0) star.orbitSpeed = 0; + return; + } + + Vector scale = vector_make(STAR_ROOM_SPAN_X, STAR_ROOM_SPAN_Y); + Vector at = vector_mul(star.formationOffset, scale); + Vector toward = vector_sub(vector_mul(waypoint, scale), at); + float distance = vector_length(toward); + Vector next = waypoint; + if (distance > star.orbitAngleOffset) + next = vector_div(vector_make(star.orbitAngleOffset * toward.x / distance + at.x, + star.orbitAngleOffset * toward.y / distance + at.y), + scale); + star.formationTargetOffset = next; + star.formationOffset = next; +} + +// Part of 0064d5f0: the Star's place in the room it shares with its player: its map point against the room's, +// spread over the room's centre (Mega Satan's lower down). +static Vector star_room_position(Entity_Familiar& star) +{ + Game& game = *g_game; + Room& room = *game.room; + int here = star_cell(game.GetRoomByIdx(game.currentRoomIdx, game.currentDimensionIdx)->gridIndex); + bool isBig = room.gridWidth > STAR_SMALL_ROOM_WIDTH && room.gridHeight > STAR_SMALL_ROOM_HEIGHT; + int centre = isBig ? room.gridWidth * STAR_CENTRE_ROW + STAR_CENTRE_COLUMN : -1; + Vector offset = here == star_mega_satan_cell() ? vector_make(0, STAR_MEGA_SATAN_DROP) : Vector{}; + return vector_make( + (star.formationOffset.x - (float)(here % LEVEL_GRID_WIDTH)) * STAR_ROOM_SPAN_X + offset.x + + (float)(centre % room.gridWidth) * GRID_CELL_SIZE + STAR_ROOM_LEFT, + (star.formationOffset.y - (float)(here / LEVEL_GRID_WIDTH)) * STAR_ROOM_SPAN_Y + offset.y + + (float)(centre / room.gridWidth) * GRID_CELL_SIZE + STAR_ROOM_TOP); +} + +// Part of 0064d5f0: in its player's room the Star shows, faded toward the walls and while jumping, blessing each +// player under it (Hallowed Ground's aura), with its glow beneath it. Elsewhere it hides and drops its glow, its pace +// reset. +static void star_show(Entity_Familiar& star, Vector spot) +{ + Game& game = *g_game; + Room& room = *game.room; + if (game.currentDimensionIdx != 0 || !room.IsPositionInRoom(spot, STAR_ROOM_MARGIN)) + { + if (star.isVisible) star.update_star_of_bethlehem_speed(false); + star.isVisible = false; + star.velocity = {}; + if (Entity* glow = star.child) + { + glow->parent = nullptr; + star.child = nullptr; + } + return; + } + + if (!star.isVisible) star.orbitAngleOffset = 1; + star.isVisible = true; + star.sprite.offset = vector_make(0, star.orbitSpeed * STAR_JUMP_HEIGHT); + Vector inside = room.GetClampedPositionImpl(spot, 0, 0, 0, 0); + float fade = (std::fabs(star.orbitSpeed) * STAR_FADE_SPAN + vector_length(vector_sub(spot, inside))) / STAR_FADE_SPAN; + float alpha = 1 - std::clamp(fade, 0.0f, 1.0f); + bool isFresh = !room.isInitialized || game.frameCount - room.enterFrame <= 1 || game.frameCount - star.spawnFrame <= 1; + if (isFresh) + { + star.pos = spot; + star.velocity = {}; + } + else star.velocity = vector_sub(spot, star.pos); + + for (Entity_Player* player : game.playerManager.playerList) + { + if (vector_length(vector_sub(star.pos, player->pos)) >= player->size + STAR_AURA_REACH) continue; + int before = player->hallowedGroundCountdown; + player->hallowedGroundCountdown = std::min(before + STAR_AURA_FRAMES, STAR_AURA_MAX); + if ((before > 0) == (player->hallowedGroundCountdown > 0)) continue; + player->cacheFlags |= STAR_AURA_CACHE; + player->EvaluateItems(); + } + + if (!star.child) + { + auto* glow = static_cast(game.Spawn({.position = star.pos, .type = ENTITY_EFFECT, + .variant = EFFECT_HALLOWED_GROUND, .seed = Random()})); + glow->parent = ☆ + glow->isFollowing = true; + glow->parentOffset = vector_sub(glow->pos, star.pos); + glow->sprite.offset = vector_make(0, STAR_GLOW_LIFT); + glow->renderZOffset = STAR_GLOW_DEPTH; + glow->Update(); + star.child = glow; + } + star.sprite.color._tint[3] = alpha; + if (Entity* glow = star.child) glow->sprite.color._tint[3] = alpha; +} + +// 0064d5f0 FamiliarAI::star_of_bethlehem: the Star walks the floor's map toward its last boss room a room at a time, +// at a pace that waits for its player, and shows in its player's room. +void star_of_bethlehem_update(Entity_Familiar& star) +{ + int cell = star_point_cell(star.formationOffset); + int goal = star_goal_cell(); + star_glide(star, star_route(star, cell, goal)); + star_show(star, star_room_position(star)); +} + +// 009615e0 Multidimensional Baby doubles a flying knife into two side by side, 10 apart: a held or thrown one hides and +// hands its flight on past the split, a path follower lays out fresh paths from beside itself and goes. The root +// speeds up. False for a knife already doubled, hidden, at rest or of another kind. +bool multidimensional_knife_copy(Entity_Knife& knife) +{ + if (knife.isMultidimensionalApplied || !knife.isVisible || knife.knifeVelocity <= 0 || + (knife.subtype != KNIFE_SUBTYPE_HELD && knife.subtype != KNIFE_SUBTYPE_PATH)) + return false; + + knife.isVisible = false; + knife.showDistance = knife.knifeDistance; + knife.isMultidimensionalApplied = true; + knife.GetRootParent()->knifeVelocity += MULTIDIMENSIONAL_KNIFE_SPEED; + for (int i = 0; i < 2; i++) + { + float side = i == 0 ? MULTIDIMENSIONAL_KNIFE_SIDE : -MULTIDIMENSIONAL_KNIFE_SIDE; + Entity* spawned = game_spawn({.position = knife.pos, .spawner = &knife, .type = ENTITY_KNIFE, + .variant = knife.variant, .seed = Random()}, + POOL_KEEP); + if (!spawned) break; + + Entity_Knife& copy = *static_cast(spawned); + copy.parent = &knife; + copy.copy_parent_state(knife); + if (knife.subtype == KNIFE_SUBTYPE_PATH) + { + copy.pos = vector_add(knife.pos, vector_rotated(vector_make(0, side), knife.rotation)); + float offset = random_unit() * KNIFE_PATH_OFFSET_RANGE - KNIFE_PATH_OFFSET_RANGE / 2; + copy.InitHomingPath(vector_from_angle(knife.rotation), &knife, offset); + } + else + { + copy.splitDistance = knife.knifeDistance; + copy.splitOffset = vector_make(0, side); + } + copy.Update(); + } + if (knife.subtype == KNIFE_SUBTYPE_PATH) knife.Remove(); + return true; +} diff --git a/src/familiar_collision.cpp b/src/familiar_collision.cpp index 18dd5a0..01effec 100644 --- a/src/familiar_collision.cpp +++ b/src/familiar_collision.cpp @@ -1,5 +1,6 @@ #include "entity_bomb.h" #include "entity_effect.h" +#include "entity_effect_combat.h" #include "entity_familiar.h" #include "entity_list.h" #include "entity_npc.h" @@ -26,11 +27,8 @@ 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 block or hit has an effect of its own not reconstructed yet. -constexpr int UNWRITTEN_BLOCK_VARIANTS[] = {201}; -constexpr int UNWRITTEN_ENEMY_TOUCH_VARIANTS[] = {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}; // 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}; @@ -141,6 +139,34 @@ constexpr int BBF_RESPAWN_FRAMES = 300; // The blood a dying familiar spills. constexpr float DEATH_BLOOD_HEIGHT = -10; +// A bone familiar's shatter: its shards, their speed and height, and its crack. +constexpr int BONE_SHATTER_SHARDS = 8; +constexpr float BONE_SHATTER_SPEED_MIN = 2; +constexpr float BONE_SHATTER_SPEED_RANGE = 3; +constexpr float BONE_SHATTER_HEIGHT = -12; +constexpr float BONE_CRACK_VOLUME = 0.5f; +constexpr float BONE_CRACK_PITCH_RANGE = 0.2f; + +// A Dip's death drops and their speed, its flame (damage, frames) and its gas cloud's frames. +constexpr float DIP_DROP_SPEED = 5; +constexpr float DIP_FLAME_DAMAGE = 8; +constexpr int DIP_FLAME_FRAMES = 300; +constexpr int DIP_CLOUD_FRAMES = 270; + +// A Dip's bite: the red one's hiss delay, its ailments (one in three for gold and charm, two seconds), the black +// one's slowing, the flaming one's burn, the thrown state and its extra damage, the hit countdown and the bounce. +constexpr int DIP_THROWN_STATE = 2; +constexpr int DIP_HISS_DELAY = 20; +constexpr uint32_t DIP_AILMENT_ODDS = 3; +constexpr int DIP_AILMENT_FRAMES = 120; +constexpr float DIP_SLOWING = 0.9f; +constexpr ColorMod DIP_SLOW_COLOR = {{0.2f, 0.2f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float DIP_BURN_DAMAGE = 3.5f; +constexpr float DIP_THROWN_DAMAGE = 7; +constexpr int DIP_HIT_COUNTDOWN = 30; +constexpr float DIP_BOUNCE = 10; +constexpr float DIP_RECOIL = 3; + // What a familiar's hit takes: the shielding damage of spikes and poop, and the count each hit adds. constexpr uint64_t DAMAGE_ISAACS_HEART = 1ull << 11; constexpr float PUNCHING_BAG_KNOCKBACK = 5; @@ -370,8 +396,6 @@ bool Entity_Familiar::collision_block(Entity& collider, bool isIgnored) if (variant != SLIPPED_RIB) return true; reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (Slipped Rib's reflection)"); } - if (familiar_listed(UNWRITTEN_BLOCK_VARIANTS, variant)) - reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (this familiar's block)"); if (variant == DRY_BABY) { @@ -407,7 +431,8 @@ bool Entity_Familiar::collision_block(Entity& collider, bool isIgnored) (variant == BONE_SPUR && (state += BONE_WEAR) > BONE_WEAR_LIMIT)) Kill(EntityRef()); if (variant == MINISAAC || variant == BLOOD_BABY) TakeDamage(1, 0, EntityRef(&collider), 1); - else if (variant == TINYTOMA || variant == TINYTOMA_2) TakeDamage(TINYTOMA_SHOT_HURT, 0, EntityRef(&collider), 1); + else if (variant == TINYTOMA || variant == TINYTOMA_2 || variant == DIP) + TakeDamage(TINYTOMA_SHOT_HURT, 0, EntityRef(&collider), 1); collider.isDead = true; return isIgnored; } @@ -496,6 +521,57 @@ static bool sissy_charm(Entity_Familiar& sissy, Entity& collider) return true; } +// Part of 006261f0: a Dip's bite by its kind (the red one hisses, the golden one may turn the enemy to gold, the +// rainbow one charm it, the black one slow it, the flaming one burn it), harder when thrown (marking the enemy its +// target), then both bounce apart and a harmful enemy hurts it. +static bool dip_touch(Entity_Familiar& dip, Entity& enemy, float damageMultiplier) +{ + EntityRef source(&dip); + uint64_t damageFlags = 0; + auto ail = [&enemy](uint64_t flag, uint32_t odds) { + if (enemy.HasEntityFlags(flag) || (odds > 1 && Random() % odds != 0)) return false; + enemy.bossStatusEffectCooldown = 0; + enemy.CopyStatusEffects(); + return true; + }; + switch (dip.subtype) + { + case DIP_SUBTYPE_RED: familiar_sound_play(SOUND_FIREDEATH_HISS, {.frameDelay = DIP_HISS_DELAY}); break; + case DIP_SUBTYPE_GOLDEN: + if (ail(FLAG_MIDAS_FREEZE, DIP_AILMENT_ODDS)) enemy.AddMidasFreeze(source, DIP_AILMENT_FRAMES, false); + break; + case DIP_SUBTYPE_RAINBOW: + if (ail(FLAG_CHARM, DIP_AILMENT_ODDS)) enemy.AddCharmed(source, DIP_AILMENT_FRAMES, false, false); + break; + case DIP_SUBTYPE_BLACK: + if (ail(FLAG_SLOW, 1)) enemy.AddSlowing(source, DIP_AILMENT_FRAMES, DIP_SLOWING, DIP_SLOW_COLOR, false); + break; + case DIP_SUBTYPE_FLAMING: + damageFlags = DAMAGE_FIRE; + if (ail(FLAG_BURN, 1)) enemy.AddBurn(source, DIP_AILMENT_FRAMES, DIP_BURN_DAMAGE, false); + break; + } + + float damage = dip.collisionDamage; + if (dip.state == DIP_THROWN_STATE && vector_is_zero(dip.targetPosition)) + { + damage = damage + damage + DIP_THROWN_DAMAGE; + if (dip.headFrameDelay == 0) + { + dip.target = &enemy; + dip.headFrameDelay = 1; + } + } + if (dip.damageCountdown <= 0) enemy.TakeDamage(damage * damageMultiplier, damageFlags, source, DIP_HIT_COUNTDOWN); + + Vector away = vector_normalized(vector_sub(enemy.pos, dip.pos)); + enemy.AddVelocity_divided(vector_scale(away, DIP_BOUNCE), true); + dip.AddVelocity_divided(vector_scale(away, -DIP_RECOIL), true); + if (enemy.collisionDamage > 0 && dip.damageCountdown <= 0) + dip.TakeDamage(TINYTOMA_SHOT_HURT, 0, EntityRef(&enemy), DIP_HIT_COUNTDOWN); + return true; +} + // 006261f0 What a familiar does on touching an entity, after the mods. In a versus match players and other players' // tears always count as low. Friendly and charmed ones, and all in a pacifist room, leave enemies alone. A resting Cube // Baby lets players by, the spiders curse, Sissy Longlegs charms, a dashing charger breaks fireplaces and poop, a @@ -570,8 +646,7 @@ bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) (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 == DIP) return dip_touch(*this, *collider, damageMultiplier); if ((variant == WISP || variant == ITEM_WISP) && wisp_touch(*this, *collider)) return true; } @@ -650,6 +725,95 @@ bool Entity_Familiar::TakeDamage(float damage, uint64_t damageFlags, const Entit return isDamaged; } +// Part of 00610540: a familiar's usual death, a burst of its blood (a clot's heart drop with it). +static void familiar_bleed(Entity_Familiar& familiar) +{ + Entity* blood = g_game->Spawn({.position = familiar.pos, + .subType = 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->posOffset = vector_make(0, DEATH_BLOOD_HEIGHT); + blood->SetColor(familiar.splatColor, -1, 255, false, true); + blood->Update(); + familiar.BloodExplode(); + if (familiar.variant == Entity_Familiar::BLOOD_BABY) blood_clot_death(familiar); +} + +// Part of 00610540: a bone orbital or Bone Spur shatters into tooth shards with a crack. +static void bone_shatter(Entity_Familiar& bone) +{ + game_particles_spawn({.position = bone.pos, + .height = BONE_SHATTER_HEIGHT, + .speed = random_unit() * BONE_SHATTER_SPEED_RANGE + BONE_SHATTER_SPEED_MIN, + .count = BONE_SHATTER_SHARDS, + .variant = EFFECT_TOOTH_PARTICLE}); + float pitch = random_unit() * BONE_CRACK_PITCH_RANGE + 1; + familiar_sound_play(SOUND_BOIL_HATCH, {.volume = BONE_CRACK_VOLUME, .pitch = pitch}); +} + +// Part of 00610540: a Dip bleeds (not a stone one) and leaves what its kind drops: a blue fly (corny and brownie), two +// or three pennies (golden), two to five half hearts (rainbow), a flame (flaming) or a cloud of gas (stinky). +static void dip_death(Entity_Familiar& dip) +{ + if (dip.subtype != DIP_SUBTYPE_STONE) + { + Entity* blood = g_game->Spawn({.position = dip.pos, .subType = 1, .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + blood->posOffset = vector_make(0, DEATH_BLOOD_HEIGHT); + blood->SetColor(dip.splatColor, -1, 255, false, true); + blood->Update(); + } + dip.BloodExplode(); + + auto scatter = [&dip](int variant, int subtype) { + uint32_t seed = dip.dropRNG.Next(); + float turn = random_unit() * RANDOM_HALF_TURN * 2; + g_game->Spawn({.position = dip.pos, + .velocity = vector_scale(vector_make(std::cos(turn), std::sin(turn)), DIP_DROP_SPEED), + .spawner = &dip, + .subType = subtype, + .type = ENTITY_PICKUP, + .variant = variant, + .seed = seed}); + }; + switch (dip.subtype) + { + case DIP_SUBTYPE_CORNY: + case DIP_SUBTYPE_BROWNIE: dip.player->AddBlueFlies(1, dip.pos, nullptr); break; + case DIP_SUBTYPE_GOLDEN: + for (uint32_t coins = (Random() & 1) + 2; coins > 0; coins--) scatter(PICKUP_COIN, 0); + break; + case DIP_SUBTYPE_RAINBOW: + for (uint32_t hearts = (Random() & 3) + 2; hearts > 0; hearts--) scatter(PICKUP_HEART, HEART_HALF); + break; + case DIP_SUBTYPE_FLAMING: + { + auto* flame = static_cast(g_game->Spawn({.position = dip.pos, .spawner = dip.player, + .type = ENTITY_EFFECT, + .variant = EFFECT_RED_CANDLE_FLAME, + .seed = Random()})); + flame->SetCollisionDamage(DIP_FLAME_DAMAGE); + flame->timeout = DIP_FLAME_FRAMES; + flame->lifespan = DIP_FLAME_FRAMES; + flame->Update(); + break; + } + case DIP_SUBTYPE_STINKY: + { + auto* cloud = static_cast(g_game->Spawn({.position = dip.pos, .spawner = dip.player, + .type = ENTITY_EFFECT, + .variant = EFFECT_SMOKE_CLOUD, + .seed = Random()})); + cloud->timeout = DIP_CLOUD_FRAMES; + cloud->lifespan = DIP_CLOUD_FRAMES; + cloud->SetCollisionDamage(dip.player->meleeDamage * HALF); + cloud->Update(); + break; + } + } +} + // 00610540 A familiar's death: blood, then the entity's own kill and its removal. A wisp's flame goes out instead. The // familiars that die their own way (the bone orbitals, the swarm flies, the Dips) stop the game. Tainted // Eve's clots refresh her heart effects. @@ -661,20 +825,11 @@ void Entity_Familiar::Kill(const EntityRef& source) } else if (!isDead) { - if (familiar_listed(UNWRITTEN_DEATH_VARIANTS, variant)) - reconstruction_missing("Entity_Familiar::Kill 00610540 (this familiar's death)"); - if (variant == WISP || variant == ITEM_WISP) return wisp_death(source); - - Entity* blood = g_game->Spawn({.position = pos, - .subType = 1, - .type = ENTITY_EFFECT, - .variant = EFFECT_BLOOD_EXPLOSION, - .seed = Random()}); - blood->posOffset = vector_make(0, DEATH_BLOOD_HEIGHT); - blood->SetColor(splatColor, -1, 255, false, true); - blood->Update(); - BloodExplode(); - if (variant == BLOOD_BABY) blood_clot_death(*this); + if (variant == BONE_ORBITAL || variant == BONE_SPUR) bone_shatter(*this); + else if (variant == WISP || variant == ITEM_WISP) return wisp_death(source); + else if (variant == SWARM_FLY_ORBITAL) player->AddBlueFlies(1, pos, target); + else if (variant == DIP) dip_death(*this); + else familiar_bleed(*this); } Entity::Kill(source); Remove(); diff --git a/src/familiar_dip.cpp b/src/familiar_dip.cpp index bc5ac5b..f2cc5ec 100644 --- a/src/familiar_dip.cpp +++ b/src/familiar_dip.cpp @@ -24,19 +24,6 @@ constexpr float DIP_THROW_LIFT = -8; constexpr float DIP_VERSUS_GLOW = 0.25f; constexpr int DIP_VERSUS_NO_SLOT = 5; -// The Dips the familiar AI tells apart (Lua's DipSubType). -enum DipSubtype -{ - DIP_SUBTYPE_RED = 1, - DIP_SUBTYPE_GOLDEN = 3, - DIP_SUBTYPE_RAINBOW = 4, - DIP_SUBTYPE_BLACK = 5, - DIP_SUBTYPE_WHITE = 6, - DIP_SUBTYPE_STONE = 12, - DIP_SUBTYPE_FLAMING = 13, - DIP_SUBTYPE_STINKY = 14 -}; - // A Dip's states: idling, scooting, and thrown. enum DipState { diff --git a/src/familiar_evaluate.cpp b/src/familiar_evaluate.cpp index 6a34f48..f8a7e47 100644 --- a/src/familiar_evaluate.cpp +++ b/src/familiar_evaluate.cpp @@ -1,11 +1,18 @@ +#include "data.h" +#include "entity_effect.h" #include "entity_familiar.h" #include "entity_player.h" #include "game.h" #include "log.h" #include "lua_engine.h" #include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "weapon.h" #include #include +#include +#include #include // How a collectible's familiars are counted: copies held and in effects, copies held only (at most one), copies in @@ -65,6 +72,20 @@ constexpr int ACHIEVEMENT_CUBE_OF_MEAT_FULL = 144; constexpr int ACHIEVEMENT_BALL_OF_BANDAGES_FULL = 19; constexpr int COLLECTIBLE_LIL_DELIRIUM = 519; +// Lil Delirium: where a new one spawns, the forms it takes (drawn from its seed with the shift triple 5, 3, 21, ten +// tries for a new one), the folder of the recoloured sheets after "gfx/", and its poof's size. +constexpr float LIL_DELIRIUM_SPREAD = 20; +constexpr uint32_t DELIRIUM_SHIFT_INDEX = 33; +constexpr int DELIRIUM_DRAWS = 10; +constexpr int DELIRIUM_FORMS[] = {3, 4, 47, 51, 53, 54, 55, 58, 59, 61, 63, + 80, 87, 92, 107, 108, 112, 95, 104, 12, 97, 225}; +constexpr size_t DELIRIUM_SHEET_PREFIX = 4; +constexpr std::string_view DELIRIUM_SHEET_FOLDER = "familiar/delirium/"; +constexpr float DELIRIUM_POOF_SCALE = 0.5f; + +// Found Soul's and the Strawman's companions appear this far below their player. +constexpr float COMPANION_DROP = 4; + // Super Bum's arrival: the state flag that shows its page once, the page, and the three bums it takes the place of. constexpr int GIANTBOOK_SUPER_BUM = 38; constexpr std::pair SUPER_BUM_PARTS[] = {{COLLECTIBLE_KEY_BUM, Entity_Familiar::KEY_BUM}, @@ -73,7 +94,6 @@ constexpr std::pair SUPER_BUM_PARTS[] = {{COLLECTIBLE_KEY_BUM, Entity_ constexpr int COLLECTIBLE_PEEPER_2 = 605; constexpr int TRINKET_ISAACS_HEAD = 54; constexpr int TRINKET_SOUL = 57; -constexpr int TRINKET_FOUND_SOUL_ID = 180; constexpr int SOUL_TRINKET_CAP = 3; constexpr int FORM_RNG_SHIFT = 35; constexpr int FAMILIAR_ACHIEVEMENT_COUNT = 4; @@ -269,18 +289,184 @@ static void super_bum_check(Entity_Player& p) .variant = variant}); } -// Lil Delirium's familiars, Found Soul's and the Strawman's co-op babies wait for their takeovers. -static void unwritten_familiars_check(Entity_Player& p) +// Part of 00763570: Lil Delirium's familiars, one per copy held or in effect. Extra ones are removed, and missing ones +// spawn beside the player as a Dry Baby that turns at once into its first form. +static void lil_delirium_check(Entity_Player& p) { - int delirium = p.GetCollectibleNum(COLLECTIBLE_LIL_DELIRIUM) + - p.temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_LIL_DELIRIUM); - bool isDeliriumShown = std::ranges::any_of(familiar_query(-1), [](Entity_Familiar* f) { return f->isLilDelirium; }); - if (delirium > 0 || isDeliriumShown) reconstruction_missing("Entity_Player::EvaluateItems 00763570 (Lil Delirium)"); + int count = std::max(p.GetCollectibleNum(COLLECTIBLE_LIL_DELIRIUM) + + p.temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_LIL_DELIRIUM), + 0); + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_LIL_DELIRIUM); + int kept = 0; + for (Entity_Familiar* familiar : familiar_query(-1)) + { + if (!familiar->isLilDelirium || familiar->isNotCountedAsFollower) continue; + if (kept >= count) familiar->Remove(); + else + { + kept++; + familiar->item = item; + } + } - bool isBabyKept = std::ranges::any_of(g_game->playerManager.playerList, - [&p](Entity_Player* other) { return other->parent == &p && !other->isDead; }); - if (p.HasTrinket(TRINKET_FOUND_SOUL_ID) || p.GetCollectibleNum(COLLECTIBLE_STRAW_MAN) > 0 || isBabyKept) - reconstruction_missing("Entity_Player::EvaluateItems 00763570 (Found Soul and the Strawman)"); + for (; kept < count; kept++) + { + uint32_t seed = p.GetCollectibleRNG(COLLECTIBLE_LIL_DELIRIUM).Next(); + Vector spot = g_game->room->GetClampedPosition( + vector_add(p.pos, vector_scale(random_direction(), LIL_DELIRIUM_SPREAD)), LIL_DELIRIUM_SPREAD); + auto* delirium = static_cast(g_game->Spawn({.position = spot, + .spawner = &p, + .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::DRY_BABY, + .seed = seed})); + delirium->isLilDelirium = true; + delirium->delirium_morph(); + delirium->item = item; + delirium->Update(); + } +} + +// Removes a player's newest co-op companions past a count (part of 00763570). +static void companions_trim(std::vector& companions, size_t count) +{ + while (companions.size() > count) + { + g_game->playerManager.RemoveCoPlayer(companions.back()); + companions.pop_back(); + } +} + +// Places a co-op companion of a player just below it, on the player's controller (part of 00763570). +static void companion_place(Entity_Player& p, Entity_Player& companion) +{ + companion.SetControllerIndex(p.controllerIndex, false); + companion.parent = &p; + companion.pos = vector_add(p.pos, vector_make(0, COMPANION_DROP)); +} + +// Part of 00763570: Found Soul's baby (none while the trinket's effect already used it) and a Keeper for each Strawman, +// removed or spawned to match, the Strawmen left alone while a run is restored. A companion's own evaluation does not +// come back here. +static void companions_check(Entity_Player& p) +{ + static bool isChecking = false; + if (isChecking) return; + isChecking = true; + + size_t souls = 0; + if (p.HasTrinket(TRINKET_FOUND_SOUL)) + souls = (size_t)std::max(1 - p.temporaryEffects.GetTrinketEffectNum(TRINKET_FOUND_SOUL), 0); + size_t strawmen = (size_t)p.GetCollectibleNum(COLLECTIBLE_STRAW_MAN); + std::vector babies; + std::vector keepers; + for (Entity_Player* other : g_game->playerManager.playerList) + { + if (other->parent != &p || other->isDead) continue; + if (other->variant == PLAYER_VARIANT_COOP_BABY && other->babySkin == BABY_FOUND_SOUL) babies.push_back(other); + else if (other->variant == PLAYER_VARIANT_PLAYER && other->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_STRAW_MAN)) + keepers.push_back(other); + } + + companions_trim(babies, souls); + while (babies.size() < souls) + { + Entity_Player* baby = g_game->playerManager.SpawnCoPlayerBaby(BABY_FOUND_SOUL); + companion_place(p, *baby); + baby->apply_coop_baby_spawn_bonus(); + baby->cacheFlags = CACHE_ALL; + baby->EvaluateItems(); + babies.push_back(baby); + } + + if (!g_game->isStartingFromState && !g_game->isRestoringGlowingHourglassState) + { + companions_trim(keepers, strawmen); + while (keepers.size() < strawmen) + { + Entity_Player* keeper = g_game->playerManager.SpawnCoPlayer2(PLAYER_KEEPER); + companion_place(p, *keeper); + keeper->temporaryEffects.AddCollectibleEffect(COLLECTIBLE_STRAW_MAN, true, 1); + keeper->InitPostLevelInitStats(); + keepers.push_back(keeper); + } + } + isChecking = false; +} + +// 00631b20 Lil Delirium turns into another of its familiars (ten draws from its seed for one other than its own), +// keeping its player, place in the line, position, motion, spawner and Siren charm. Each sheet with a Delirium version +// under gfx/familiar/delirium/ swaps to it, and a small poof shows the change. +void Entity_Familiar::delirium_morph() +{ + RNG rng; + rng.SetSeed(initSeed, DELIRIUM_SHIFT_INDEX); + int newVariant = variant; + for (int i = 0; i < DELIRIUM_DRAWS && newVariant == variant; i++) + newVariant = DELIRIUM_FORMS[rng.RandomInt((uint32_t)std::size(DELIRIUM_FORMS))]; + + Entity_Player* owner = player; + Entity* oldChild = child; + Entity* oldParent = parent; + Vector oldPos = pos; + Vector oldVelocity = velocity; + int oldSpawnerType = spawnerType; + int oldSpawnerVariant = spawnerVariant; + Entity* oldSirenHelper = sirenHelper; + Entity_Player* oldSirenPlayer = sirenOriginalPlayer; + if (weapon) weapon->ClearReferences(); + weapon.reset(); + if (linkedEntity) linkedEntity->Remove(); + + bool wasFollower = isFollower; + bool wasDelayed = isDelayed; + RecalculateOrbitOffset(orbitLayer, ORBIT_LEAVE); + RemoveFromFollowers(); + RemoveFromDelayed(); + ClearReferences(); + spawnerEntity = owner; + Init(type, newVariant, 0, rng.Next()); + + if ((isFollower && wasFollower) || (isDelayed && wasDelayed)) + { + RemoveFromFollowers(); + RemoveFromDelayed(); + isFollower = wasFollower; + isDelayed = wasDelayed; + parent = oldParent; + if (oldParent) oldParent->child = this; + child = oldChild; + if (oldChild) oldChild->parent = this; + } + pos = oldPos; + velocity = oldVelocity; + spawnerType = oldSpawnerType; + spawnerVariant = oldSpawnerVariant; + appearTimer = 0; + + bool isRecolored = false; + for (int layer = 0; layer < (int)sprite.layerStates.size(); layer++) + { + const LayerData* data = sprite.layerStates[layer].layerData; + // The original throws on a sheet path shorter than its "gfx/" prefix. Such a layer keeps its sheet here. + if (!data || data->spriteSheetPath.size() < DELIRIUM_SHEET_PREFIX) + continue; + std::string sheet = g_manager->modManager.TryRedirectPath( + std::string(data->spriteSheetPath).insert(DELIRIUM_SHEET_PREFIX, DELIRIUM_SHEET_FOLDER)); + std::error_code error; + if (!std::filesystem::exists(resource_path(sheet), error)) continue; + sprite.ReplaceSpritesheet(layer, sheet); + isRecolored = true; + } + if (isRecolored) sprite.LoadGraphics(); + + Entity* poof = g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->sprite.scale = vector_make(DELIRIUM_POOF_SCALE, DELIRIUM_POOF_SCALE); + poof->Update(); + + sirenHelper = oldSirenHelper; + sirenOriginalPlayer = oldSirenPlayer; + if (sirenHelper) sirenHelper->target = this; + isLilDelirium = true; } // The familiars section of 00763570: every familiar item, effect, trinket and counter checked for its familiars in a @@ -335,7 +521,7 @@ void familiars_evaluate(Entity_Player& p) effect_check(p, COLLECTIBLE_SPRINKLER, Entity_Familiar::SPRINKLER); pieces_check(); super_bum_check(p); - unwritten_familiars_check(p); + lil_delirium_check(p); familiar_check(p, {.rng = &formRng, .count = p.HasPlayerForm(PLAYER_FORM_SPIDER_BABY) ? 1 : 0, @@ -353,6 +539,7 @@ void familiars_evaluate(Entity_Player& p) .variant = Entity_Familiar::BIRD_CAGE}); effect_check(p, COLLECTIBLE_PEEPER_2, Entity_Familiar::PEEPER_2); source_check(p, {COLLECTIBLE_DAMOCLES_PASSIVE, Entity_Familiar::DAMOCLES, COUNT_OWNED_ONE}); + companions_check(p); lua_engine_get().EvaluateItems(&p, CACHE_FAMILIARS_FLAG); diff --git a/src/familiar_follow.cpp b/src/familiar_follow.cpp index b5b72cc..36e391c 100644 --- a/src/familiar_follow.cpp +++ b/src/familiar_follow.cpp @@ -1,5 +1,8 @@ +#include "active_items.h" #include "entity_familiar.h" #include "entity_effect.h" +#include "entity_npc.h" +#include "menu_manager.h" #include "familiar_gello.h" #include "familiar_variants.h" #include "weapon_umbilical_whip.h" @@ -13,9 +16,6 @@ #include "room_grid.h" #include -// The items, trinkets, challenge and boss the following line answers to. -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. constexpr float FOLLOW_DISTANCE = 20; constexpr float MILK_FOLLOW_DISTANCE = 10; @@ -24,6 +24,49 @@ constexpr float FOLLOW_PULL = 0.2f; constexpr float FOLLOW_FRICTION = 0.8f; constexpr float FOLLOW_POSITION_PULL = 0.1f; +// Duct Tape's hold on the player's offset: its fastest step and drag. +constexpr float DUCT_TAPE_STEP_MAX = 100; +constexpr float DUCT_TAPE_DRAG = 0.8f; + +// RC Remote: the push apart from the line and the player, its cap, and the push back off the walls. +constexpr float RC_SPREAD_PUSH = 0.5f; +constexpr float RC_SPREAD_MAX = 2; +constexpr float RC_WALL_PUSH_MIN = 1; +constexpr float RC_WALL_PUSH_MAX = 16; + +// The Siren's charm: the charmed line circles her (or what she holds) this far, at this speed. +constexpr float SIREN_ORBIT_RADIUS = 90; +constexpr float SIREN_ORBIT_SPEED = 3.5f; + +// Lilith's Birthright: the counted followers fan out in front of her, a few degrees more for each, up to nearly a half +// turn, just past her size, and close in fast. +constexpr float LILITH_FAN_STEP = 5; +constexpr float LILITH_FAN_BASE = 15; +constexpr float LILITH_FAN_MAX = 179; +constexpr float LILITH_FAN_REACH = 20; +constexpr float LILITH_FAN_PULL = 0.4f; + +// Friendship Necklace: the followers circle their leader in an ellipse (half as wide on Child's Leash), faster with the +// trinket tripled, closing in past their slack, harder while spinning, and keeping up with a player more than another +// familiar. +constexpr float NECKLACE_ORBIT_SPEED = 3.5f; +constexpr float NECKLACE_ORBIT_FAST = 1.5f; +constexpr int NECKLACE_FAST_MULTIPLIER = 2; +constexpr float NECKLACE_ORBIT_X = 65; +constexpr float NECKLACE_ORBIT_Y = 60; +constexpr float NECKLACE_LEASH_SCALE = 0.5f; +constexpr float NECKLACE_SLACK = 20; +constexpr float NECKLACE_PULL = 0.1f; +constexpr float NECKLACE_SPIN_PULL = 5; +constexpr float NECKLACE_PLAYER_CARRY = 1.5f; + +// A grown Blood Puppy's arrival: how many spots it tries around the room's centre, how far out and how far from the +// players. +constexpr int BLOOD_PUPPY_SPOT_TRIES = 20; +constexpr float BLOOD_PUPPY_SPOT_RADIUS = 100; +constexpr float BLOOD_PUPPY_SPOT_STEP = 60; +constexpr float BLOOD_PUPPY_SPOT_DISTANCE_SQUARED = 25600; + // How a delayed familiar steers toward its leader's old position, and how hard My Shadow snaps there. constexpr float DELAYED_PULL = 0.1f; constexpr float DELAYED_FRICTION = 0.7f; @@ -381,9 +424,122 @@ static Entity* follow_leader_find(Entity_Familiar& familiar, bool isLilithBirthr return nullptr; } +// The followers counted ahead of a familiar in its line (up to a King Baby leading it) and behind it. +struct LineCount +{ + Entity* king = nullptr; + int ahead = 0; + int behind = 0; +}; + +// Counts a familiar's line by a test, as Lilith's Birthright and Friendship Necklace do (part of 00612bb0). +template static LineCount line_count(Entity_Familiar& familiar, Test isCounted) +{ + LineCount line; + for (Entity* ahead = familiar.parent; ahead; ahead = ahead->parent) + { + if (ahead->type != ENTITY_FAMILIAR) continue; + if (ahead->variant == Entity_Familiar::KING_BABY) + { + line.king = ahead; + break; + } + if (isCounted(static_cast(*ahead))) line.ahead++; + } + for (Entity* behind = familiar.child; behind; behind = behind->child) + if (behind->type == ENTITY_FAMILIAR && isCounted(static_cast(*behind))) line.behind++; + return line; +} + +// 00592050 NpcHelper::siren_familiar_orbit: a familiar the Siren charmed circles her (or what she holds) in its place +// among the charmed line, keeping up with her. +static void siren_orbit(Entity_NPC& siren, Entity_Familiar& familiar) +{ + Entity* controller = siren.sirenPlayerEntity; + if (!controller) return; + + Entity* center = siren.child ? siren.child.get() : controller; + int ahead = 0; + int behind = 0; + for (Entity* next = familiar.parent; next && next->type == ENTITY_FAMILIAR; next = next->parent) + if (static_cast(next)->is_following()) ahead++; + for (Entity* next = familiar.child; next && next->type == ENTITY_FAMILIAR; next = next->child) + if (static_cast(next)->is_following()) behind++; + + float angle = (float)behind * 360 / (float)(behind + 1 + ahead) + controller->targetPosition.x * SIREN_ORBIT_SPEED; + Vector toward = vector_sub(vector_add(center->pos, vector_scale(vector_from_angle(angle), SIREN_ORBIT_RADIUS)), + familiar.pos); + float gap = vector_length(toward); + Vector pull = gap > NECKLACE_SLACK ? vector_scale(toward, (gap - NECKLACE_SLACK) * NECKLACE_PULL / gap) : Vector{}; + familiar.velocity = vector_add(pull, center->velocity); +} + +// Part of 00612bb0: Lilith's Birthright fans her counted followers out in front of her, where she aims (or faces), +// alternating sides from the back of the line. +static void lilith_fan_follow(Entity_Familiar& familiar) +{ + Entity_Player& lilith = *familiar.player; + LineCount line = line_count(familiar, [](Entity_Familiar& f) { return f.is_following() && f.is_counted_follower(); }); + Entity* leader = line.king ? line.king : &lilith; + int total = line.ahead + line.behind; + + Vector aim = vector_is_zero(lilith.aimDirection) ? direction_unit(lilith.headDirection) : lilith.aimDirection; + if (total + 1 > 1) + { + float spread = std::min((float)(total + 1) * LILITH_FAN_STEP + LILITH_FAN_BASE, LILITH_FAN_MAX); + if (line.behind & 1) spread = -spread; + aim = vector_rotated(aim, spread * (float)(total - (line.behind & ~1)) / (float)total); + } + if (vector_length(aim) > 0) aim = vector_resized(aim, lilith.size + LILITH_FAN_REACH); + familiar.velocity = vector_scale(vector_sub(vector_add(leader->pos, aim), familiar.pos), LILITH_FAN_PULL); +} + +// Part of 00612bb0: Friendship Necklace has the followers circle their leader (the player or a King Baby) evenly. +static void necklace_orbit(Entity_Familiar& familiar, bool isLilithBirthright) +{ + Entity_Player& player = *familiar.player; + LineCount line = line_count(familiar, [isLilithBirthright](Entity_Familiar& f) { + return f.is_following() && !(isLilithBirthright && f.is_counted_follower()); + }); + Entity* leader = line.king ? line.king : &player; + + familiar.orbitSpeed = NECKLACE_ORBIT_SPEED; + if (player.GetTrinketMultiplier(TRINKET_FRIENDSHIP_NECKLACE) > NECKLACE_FAST_MULTIPLIER) + familiar.orbitSpeed *= NECKLACE_ORBIT_FAST; + familiar.orbitDistance = vector_make(NECKLACE_ORBIT_X, NECKLACE_ORBIT_Y); + float angle = (float)line.behind * 360 / (float)(line.ahead + 1 + line.behind) + + (float)g_game->frameCount * familiar.orbitSpeed - familiar.orbitAngleOffset; + if (player.HasTrinket(TRINKET_CHILD_LEASH)) + familiar.orbitDistance = vector_scale(familiar.orbitDistance, NECKLACE_LEASH_SCALE); + + float radians = angle * DEGREES_TO_RADIANS; + Vector spot = vector_make(std::cos(radians) * familiar.orbitDistance.x + leader->pos.x, + std::sin(radians) * familiar.orbitDistance.y + leader->pos.y); + Vector toward = vector_sub(spot, familiar.pos); + float gap = vector_length(toward); + familiar.velocity = {}; + if (gap > NECKLACE_SLACK) + { + familiar.velocity = vector_scale(toward, (gap - NECKLACE_SLACK) * NECKLACE_PULL / gap); + if (familiar.HasEntityFlags(FLAG_SPIN)) familiar.velocity = vector_scale(familiar.velocity, NECKLACE_SPIN_PULL); + } + float carry = leader->type == ENTITY_PLAYER ? NECKLACE_PLAYER_CARRY : 1; + familiar.velocity = vector_add(familiar.velocity, vector_scale(leader->velocity, carry)); +} + +// The first punching bag of the Guardian challenge, which Isaac's Heart follows instead of its line (part of 00612bb0). +static Entity* guardian_bag_find(Entity_Familiar& familiar) +{ + if (g_game->challenge != CHALLENGE_GUARDIAN || familiar.variant != Entity_Familiar::ISAACS_HEART) return nullptr; + + std::vector bags = familiar_query(Entity_Familiar::PUNCHING_BAG); + return bags.empty() ? nullptr : bags.front(); +} + // 00612bb0 Trails its leader at a short distance, catching up the further it falls behind. Permanent familiars stay // put, and Tainted Lilith's Birthright puts the line on Gello. The Siren's charm, RC Remote, Duct Tape, Friendship -// Necklace and Lilith's Birthright arrange the line their own ways, which stops the game where not written. +// Necklace and Lilith's Birthright arrange the line their own ways, and Isaac's Heart follows the Guardian challenge's +// punching bag. void Entity_Familiar::FollowParent() { if (isSubtype55555) @@ -393,23 +549,31 @@ void Entity_Familiar::FollowParent() return; } if (IsLilithBirthrightIncubus()) return ride_gello(*this); - if (player->spawnerEntity && player->spawnerEntity->type == SIREN_TYPE && player->spawnerEntity->variant == 0 && - player->HasEntityFlags(FLAG_SPAWN_STICKY_SPIDERS)) - return reconstruction_missing("Entity_Familiar::FollowParent 00612bb0 (the Siren's charm)"); + + Entity* siren = player ? player->spawnerEntity.get() : nullptr; + if (siren && siren->type == ENTITY_SIREN && siren->variant == 0 && player->HasEntityFlags(FLAG_SPAWN_STICKY_SPIDERS)) + { + siren_orbit(static_cast(*siren), *this); + friction *= FOLLOW_FRICTION; + return; + } if (player->HasTrinket(TRINKET_RC_REMOTE)) return predict_player_movement(); if (player->HasTrinket(TRINKET_DUCT_TAPE)) return move_to_parent_offset(); if (!vector_is_zero(formationOffset)) reset_follow_target(); - if (g_game->challenge == CHALLENGE_GUARDIAN && variant == ISAACS_HEART) - return reconstruction_missing("Entity_Familiar::FollowParent 00612bb0 (the punching bag challenge)"); + Entity* bag = guardian_bag_find(*this); bool isLilithBirthright = player->playerType == PLAYER_LILITH && player->HasCollectible(COLLECTIBLE_BIRTHRIGHT); if (isLilithBirthright && is_counted_follower()) - return reconstruction_missing("Entity_Familiar::FollowParent 00612bb0 (Lilith's Birthright)"); + { + lilith_fan_follow(*this); + friction *= FOLLOW_FRICTION; + return; + } if (player->HasTrinket(TRINKET_FRIENDSHIP_NECKLACE) && variant != KING_BABY) - return reconstruction_missing("Entity_Familiar::FollowParent 00612bb0 (Friendship Necklace)"); + return necklace_orbit(*this, isLilithBirthright); orbitDistance = {}; - Entity* leader = follow_leader_find(*this, isLilithBirthright); + Entity* leader = bag ? bag : follow_leader_find(*this, isLilithBirthright); Vector leaderPos = leader ? leader->pos : player->pos; float distance = variant == MILK ? MILK_FOLLOW_DISTANCE : FOLLOW_DISTANCE; if (player->HasTrinket(TRINKET_CHILD_LEASH)) distance = LEASH_FOLLOW_DISTANCE; @@ -505,6 +669,74 @@ Vector Entity_Familiar::UpdateFollowPosition() cosine * formationOffset.y + sine * formationOffset.x); } +// 00631850 Duct Tape holds it at its formation offset from the player: placed there on the frame a room is entered, +// else stepping there (at most 100 a frame) with drag. +void Entity_Familiar::move_to_parent_offset() +{ + Room& room = *g_game->room; + if (room.isInitialized && g_game->frameCount == room.enterFrame) + { + velocity = {}; + pos = vector_add(player->pos, UpdateFollowPosition()); + return; + } + + velocity = vector_sub(vector_add(player->pos, UpdateFollowPosition()), pos); + if (vector_length(velocity) > DUCT_TAPE_STEP_MAX) velocity = vector_resized(velocity, DUCT_TAPE_STEP_MAX); + velocity = vector_scale(velocity, DUCT_TAPE_DRAG); +} + +// 00650220 RC Remote: it walks as the player does with the player's movement input (none while dropping), keeps apart +// from its line and the player, and is pushed back inside the room. +void Entity_Familiar::predict_player_movement() +{ + Vector input{}; + if (player->isControlsEnabled && player->controlsCooldown <= 0) + { + input = player->GetMovementJoystick(); + if (vector_length(input) > 1) input = vector_resized(input, 1); + } + if (input_is_action_pressed(ACTION_DROP, player->controllerIndex, player)) input = {}; + pathfinder.SimulatePlayerMovement(input, player->moveSpeed); + + Entity* head = this; + while (head->parent && head->parent->type == ENTITY_FAMILIAR) head = head->parent; + Vector push{}; + auto pushAway = [&](Entity& other) { + Vector away = vector_sub(pos, other.pos); + if (!vector_is_zero(away)) + push = vector_add(push, vector_scale(away, RC_SPREAD_PUSH / vector_length_squared(away))); + }; + for (Entity* next = head; next && next->type == ENTITY_FAMILIAR; next = next->child) pushAway(*next); + pushAway(*player); + if (vector_length(push) > RC_SPREAD_MAX) push = vector_resized(push, RC_SPREAD_MAX); + velocity = vector_add(velocity, vector_scale(push, speedMultiplier)); + + Vector inward = vector_sub(g_game->room->GetClampedPositionImpl(pos, 0, 0, 0, 0), pos); + if (vector_is_zero(inward)) return; + inward = vector_normalized(inward); + float strength = std::clamp(-vector_dot(inward, velocity), RC_WALL_PUSH_MIN, RC_WALL_PUSH_MAX); + velocity = vector_add(velocity, vector_scale(inward, strength * speedMultiplier)); +} + +// Part of 0063b4a0: a grown Blood Puppy arrives at a free spot near the room's centre, trying up to twenty spots around +// it for one away from every player. +static Vector blood_puppy_spot() +{ + Vector spot = room_free_pickup_position_find({.position = Room::GetCenterPos()}); + for (int i = 0; i < BLOOD_PUPPY_SPOT_TRIES; i++) + { + if (vector_length_squared(vector_sub(game_nearest_player(spot)->pos, spot)) >= BLOOD_PUPPY_SPOT_DISTANCE_SQUARED) + break; + float turn = random_unit() * RANDOM_HALF_TURN * 2; + Vector around = vector_add(Room::GetCenterPos(), vector_scale(vector_make(std::cos(turn), std::sin(turn)), + BLOOD_PUPPY_SPOT_RADIUS)); + spot = room_free_pickup_position_find( + {.position = around, .step = BLOOD_PUPPY_SPOT_STEP, .isAvoidActiveEntities = true}); + } + return spot; +} + // 0063b4a0 Where it should be when it arrives with its player: its orbit spot, a free spot for the Sprinkler, or beside // the player (scattered when it is new), kept off the walls. Vector Entity_Familiar::GetFollowTargetPosition(FollowSpot spot) @@ -521,9 +753,7 @@ Vector Entity_Familiar::GetFollowTargetPosition(FollowSpot spot) if (spot == FOLLOW_EXACT) { if (variant == BLOOD_BABY) target = vector_add(target, random_direction()); - if (variant == BLOOD_PUPPY && linkedEntity) - reconstruction_missing("Entity_Familiar::GetFollowTargetPosition " - "0063b4a0 (Blood Puppy's spot)"); + if (variant == BLOOD_PUPPY && linkedEntity) target = blood_puppy_spot(); } return g_game->room->GetClampedPositionImpl(target, 20, 20, 20, 20); } diff --git a/src/familiar_locust.cpp b/src/familiar_locust.cpp index d77935d..144d697 100644 --- a/src/familiar_locust.cpp +++ b/src/familiar_locust.cpp @@ -150,6 +150,14 @@ constexpr ColorMod LOCUST_HOLY_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.6f, constexpr int PENTAGRAM_FRAMES = 45; constexpr float PENTAGRAM_SCALE = 32; constexpr int LOCUST_MAW_TIMEOUT = 60; + +// Larynx's locust scream: its pitch, volume and shake, and the shockwave's reach and damage. +constexpr float LOCUST_LARYNX_VOLUME = 0.8f; +constexpr float LOCUST_LARYNX_PITCH = 2.5f; +constexpr int LOCUST_LARYNX_SHAKE = 8; +constexpr float LOCUST_LARYNX_MIN_RADIUS = 3.5f; +constexpr float LOCUST_LARYNX_MAX_RADIUS = 46.62f; +constexpr float LOCUST_LARYNX_DAMAGE = 30; constexpr float MAW_SCALE = 0.5f; constexpr float MAW_RADIUS_SCALE = 0.1f; constexpr float LOCUST_BRIMSTONE_SCALE = 1.5f; @@ -772,7 +780,21 @@ static void locust_hit_effects(Entity_Familiar& locust, const TearFlags& flags, 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)"); + { + familiar_sound_play(SOUND_LARYNX_SCREAM_LO, {.volume = LOCUST_LARYNX_VOLUME, .pitch = LOCUST_LARYNX_PITCH}); + game_shake_screen(LOCUST_LARYNX_SHAKE); + auto* scream = static_cast(g_game->Spawn({.position = locust.pos, + .spawner = &locust, + .subType = 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_MAMA_MEGA_EXPLOSION, + .seed = Random()})); + scream->targetPosition = locust.pos; + scream->minRadius = LOCUST_LARYNX_MIN_RADIUS; + scream->maxRadius = LOCUST_LARYNX_MAX_RADIUS; + scream->SetCollisionDamage(LOCUST_LARYNX_DAMAGE); + scream->Update(); + } if (locustFlags & LOCUST_FLAG_MAW) { Entity_Laser* ring = player.SpawnMawOfVoid(LOCUST_MAW_TIMEOUT); diff --git a/src/familiar_missing.cpp b/src/familiar_missing.cpp deleted file mode 100644 index 6c847e0..0000000 --- a/src/familiar_missing.cpp +++ /dev/null @@ -1,77 +0,0 @@ -#include "entity_familiar.h" -#include "log.h" - -// The rest of Entity_Familiar, which the familiars this round does not reach call: each stops the game with its name. - -// 0060d180 -KColor* Entity_Familiar::GetPlayerSlot(KColor*, Entity_Player*) -{ - reconstruction_missing("Entity_Familiar::GetPlayerSlot 0060d180"); -} - -// 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() -{ - if (variant != ACID_BABY && variant != LIL_SPEWER) return; - reconstruction_missing("Entity_Familiar::farting_baby_fart 0062c8d0 (Acid Baby and Lil Spewer)"); -} - -// 00631850 -void Entity_Familiar::move_to_parent_offset() -{ - reconstruction_missing("Entity_Familiar::move_to_parent_offset 00631850"); -} - -// 00650220 -void Entity_Familiar::predict_player_movement() -{ - reconstruction_missing("Entity_Familiar::predict_player_movement 00650220"); -} - -// 00631b20 -void Entity_Familiar::delirium_morph() -{ - reconstruction_missing("Entity_Familiar::delirium_morph 00631b20"); -} - -// 00634b10 -void Entity_Familiar::ai_lil_spewer() -{ - reconstruction_missing("Entity_Familiar::ai_lil_spewer 00634b10"); -} - -// 0063aef0 -Entity_Laser* Entity_Familiar::sprinkler_shoot_laser(float, float) -{ - reconstruction_missing("Entity_Familiar::sprinkler_shoot_laser 0063aef0"); -} - -// 0063c1c0 -void Entity_Familiar::ai_minisaac() -{ - reconstruction_missing("Entity_Familiar::ai_minisaac 0063c1c0"); -} - -// 0063ce20 -void Entity_Familiar::minisaac_fire() -{ - reconstruction_missing("Entity_Familiar::minisaac_fire 0063ce20"); -} - -// 0063dd60 -void Entity_Familiar::minisaac_find_target() -{ - reconstruction_missing("Entity_Familiar::minisaac_find_target 0063dd60"); -} - -// 0064d1d0 -void Entity_Familiar::update_star_of_bethlehem_speed(bool) -{ - reconstruction_missing("Entity_Familiar::update_star_of_bethlehem_speed 0064d1d0"); -} - -// 009615e0 -uint8_t Entity_Familiar::multidimensional_baby_copy_knife(Entity_Knife*, Entity*) -{ - reconstruction_missing("Entity_Familiar::multidimensional_baby_copy_knife 009615e0"); -} diff --git a/src/familiar_shoot.cpp b/src/familiar_shoot.cpp index 6c69eb3..fef3522 100644 --- a/src/familiar_shoot.cpp +++ b/src/familiar_shoot.cpp @@ -11,7 +11,6 @@ #include // The items and trinkets the familiars' shots read. -constexpr int COLLECTIBLE_HIVE_MIND = 248; constexpr int TRINKET_ISAACS_HEAD_ID = 54; // Fruity Plum's fruit tears: their damage, their two sizes (the tear scales of sizes 2 and 3), how much bigger, and @@ -77,6 +76,13 @@ constexpr float MONSTRO_SPRAY_SCALE = 0.7f; constexpr float MONSTRO_SPRAY_VOLUME = 0.7f; constexpr int MONSTRO_HEAD_FRAMES = 20; +// Lil Abaddon's released ring: its pitch, lift, scale and damage (both by the multiplier) and how long it lasts. +constexpr float ABADDON_PITCH = 1.1f; +constexpr float ABADDON_RING_LIFT = -20; +constexpr float ABADDON_RING_SCALE = 0.5f; +constexpr float ABADDON_RING_DAMAGE = 3.5f; +constexpr int ABADDON_RING_TIMEOUT = 30; + // The collectibles of the babies Mongo Baby mimics, by its subtype (Brother Bobby first, Demon Baby second). constexpr int MONGO_MIMICS[] = {8, 113, 99, 100, 95, 67, 163, 167, 174, 268, 435, 608}; @@ -875,11 +881,38 @@ void Entity_Familiar::ai_incubus_shot() whip->headFrameDelay = std::max(whip->headFrameDelay, WHIP_HEAD_FRAMES); } -// Part of 0062d300: the released shot. Lil Monstro sprays twelve tears with a splat, Lil Brimstone fires its beam. -// Lil Abaddon's ring stops the game. +// Part of 0062d300: Lil Abaddon's released ring, a pulsing Maw of the Void ring around it. +static void abaddon_ring_fire(Entity_Familiar& abaddon, Vector aim) +{ + familiar_sound_play(SOUND_MAW_OF_VOID, {.pitch = ABADDON_PITCH}); + auto* ring = static_cast(g_game->Spawn({.position = abaddon.pos, + .spawner = &abaddon, + .subType = LASER_SUBTYPE_RING_FOLLOW_PARENT, + .type = ENTITY_LASER, + .variant = LASER_THICK_RED, + .seed = Random()})); + ring->posOffset = vector_make(0, ABADDON_RING_LIFT); + ring->parent = &abaddon; + ring->renderDepthOffset = BRIMSTONE_DEPTH_FRONT; + ring->scale = abaddon.GetMultiplier() * ABADDON_RING_SCALE; + ring->ResetSpriteScale(); + ring->SetCollisionDamage(abaddon.GetMultiplier() * ABADDON_RING_DAMAGE); + ring->tearFlags = TearFlags().set(TEAR_PULSE); + ring->timeout = ABADDON_RING_TIMEOUT; + ring->Update(); + + abaddon.linkedEntity = ring; + abaddon.apply_baby_bender(*ring); + abaddon.shot_owner_convert(ring); + abaddon.headFrameDelay = ABADDON_RING_TIMEOUT; + abaddon.PlayShootAnim(vector_to_direction(aim)); +} + +// Part of 0062d300: the released shot. Lil Monstro sprays twelve tears with a splat, Lil Abaddon fires its ring and +// Lil Brimstone its beam. void Entity_Familiar::charged_shot_fire(Vector aim, FireMode mode) { - if (variant == LIL_ABADDON) return reconstruction_missing("Entity_Familiar::ai_incubus_shot 0062d300 (Lil Abaddon)"); + if (variant == LIL_ABADDON) return abaddon_ring_fire(*this, aim); if (variant != LIL_MONSTRO) { FireBrimstone(aim, BRIMSTONE_OWN); diff --git a/src/familiar_sprinkler.cpp b/src/familiar_sprinkler.cpp index 3941483..5577bdd 100644 --- a/src/familiar_sprinkler.cpp +++ b/src/familiar_sprinkler.cpp @@ -1,11 +1,16 @@ +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_knife.h" +#include "entity_laser.h" #include "entity_player.h" #include "entity_tear.h" #include "familiar_variants.h" #include "game.h" -#include "log.h" #include "npc_ai.h" #include "room.h" #include "weapon.h" +#include "weapon_fetus.h" +#include #include #include @@ -27,8 +32,41 @@ constexpr int SPRINKLER_GRID_PATH = 700; constexpr int SPRINKLER_GRID_PATH_LIMIT = 951; constexpr float SPRINKLER_FRICTION = 0.5f; constexpr float SPRINKLER_SLOW_FIRE = 3; -constexpr WeaponType SPRINKLER_UNWRITTEN_WEAPONS[] = {WEAPON_ROCKETS, WEAPON_KNIFE, WEAPON_BOMBS, - WEAPON_TECH_X, WEAPON_LASER, WEAPON_BRIMSTONE}; + +// The Sprinkler's beams and knives: they start this far out, raised to its eye, the laser lasting 3 frames and the +// Brimstone beam 5 (as long as an Azazel's, at least 60, without Brimstone), drawn in front. Its knives fly home +// slowly. +constexpr float SPRINKLER_REACH = 20; +constexpr float SPRINKLER_EYE_LIFT = -32; +constexpr int SPRINKLER_LASER_TIMEOUT = 3; +constexpr int SPRINKLER_BRIMSTONE_TIMEOUT = 5; +constexpr float SPRINKLER_BEAM_DEPTH = 3000; +constexpr float SPRINKLER_AZAZEL_RANGE = 32; +constexpr float SPRINKLER_AZAZEL_RANGE_MIN = 60; +constexpr float SPRINKLER_BRIMSTONE_RANGE = 115; +constexpr float SPRINKLER_RANGE_PER_HEIGHT = 2.5f; +constexpr int SPRINKLER_KNIFE_SUBTYPE = 1; +constexpr float SPRINKLER_KNIFE_FOLLOW_SPEED = 0.05f; +constexpr float SPRINKLER_TECH_X_RADIUS = 5; + +// Epic Fetus through the Sprinkler: a target drifting off along its turn, lasting by the volley's size, with one more +// target (Mom's Eye) or three (Loki's Horns) beside it and Monstro's Lung's scattered around it. +constexpr int TARGET_LIFE_BASE = 20; +constexpr int TARGET_LIFE_PER_TEAR = 5; +constexpr float TARGET_SPEED_BASE = 5; +constexpr float TARGET_SPEED_RANGE = 10; +constexpr int TARGET_LUNG_SUBTYPE = 4; +constexpr float TARGET_LUNG_SPREAD_MIN = 10; +constexpr float TARGET_LUNG_SPREAD_RANGE = 80; + +// Monstro's Lung's extra shots through the Sprinkler: knives (one to three), targets (two to four) and beams (three to +// five) at random angles, and Tech X rings (three to five) within 25 degrees of its turn. +constexpr uint32_t LUNG_EXTRA_RANGE = 3; +constexpr uint32_t LUNG_KNIVES_MIN = 1; +constexpr uint32_t LUNG_TARGETS_MIN = 2; +constexpr uint32_t LUNG_BEAMS_MIN = 3; +constexpr float LUNG_RING_SPREAD = 50; +constexpr float LUNG_RING_RADIUS_MIN = 0.5f; // Monstro's Lung through the Sprinkler: the tears per eye (12 and 2.4 per extra tear, spread over the eyes), their // scatter, fall, lift and size. @@ -43,12 +81,226 @@ constexpr float SPRINKLER_LUNG_SCALE_BASE = 0.9f; constexpr float SPRINKLER_LUNG_SCALE_RANGE = 0.05f; constexpr float SPRINKLER_LUNG_SCALE_MIN = 0.01f; +// A Sprinkler shot of a weapon: where it starts, how fast it goes and its angle. +struct SprinklerShot +{ + Vector position{}; + Vector velocity{}; + float angle = 0; +}; + // A shot direction of the Sprinkler's turn plus an angle. static Vector sprinkler_direction(Entity_Familiar& sprinkler, float turn) { return vector_from_angle(normalize_angle_degrees((float)sprinkler.state * SPRINKLER_STEP + turn)); } +// The extra shots of Loki's Horns (three more, a right angle apart) or Mom's Eye (one behind), then the volley of a +// weapon along the Sprinkler's turn, each handed to fire. +template +static void sprinkler_volley(Entity_Familiar& sprinkler, WeaponType type, const Weapon_MultiShotParams& params, Fire fire) +{ + Entity_Player& player = *sprinkler.player; + auto extra = [&](float turn) { + float angle = normalize_angle_degrees((float)sprinkler.state * SPRINKLER_STEP + turn); + fire(SprinklerShot{sprinkler.pos, vector_scale(vector_from_angle(angle), SPRINKLER_SHOT_SPEED), angle}); + }; + if (player.HasCollectible(COLLECTIBLE_LOKIS_HORNS)) + for (int i = 1; i < SPRINKLER_HORN_SHOTS; i++) extra((float)i * SPRINKLER_HORN_TURN); + else if (player.HasCollectible(COLLECTIBLE_MOMS_EYE)) extra(SPRINKLER_EYE_TURN); + + Vector aim = sprinkler_direction(sprinkler, 0); + for (int i = 0; i < params.numTears; i++) + { + PosVel shot = Entity_Player::GetMultiShotPositionVelocity(i, type, aim, SPRINKLER_SHOT_SPEED, params); + fire(SprinklerShot{vector_add(shot.position, sprinkler.pos), shot.velocity, vector_angle(shot.velocity)}); + } +} + +// Monstro's Lung's extra count through the Sprinkler, when held: a few more than the least. +static uint32_t sprinkler_lung_extras(Entity_Player& player, uint32_t least) +{ + return player.HasCollectible(COLLECTIBLE_MONSTROS_LUNG) ? Random() % LUNG_EXTRA_RANGE + least : 0; +} + +// The player's tear effects for one of the Sprinkler's shots of a weapon, on a random side. +static TearParams sprinkler_hit_params(Entity_Familiar& sprinkler, WeaponType type) +{ + int side = (int)(Random() & 1) * 2 - 1; + return sprinkler.player->GetTearHitParams(type, 1, side, nullptr); +} + +// A Sprinkler beam's look and hits: the player's tear flags, color and damage, drawn in front. +static void sprinkler_beam_dress(Entity_Laser& beam, const TearParams& params) +{ + beam.tearFlags = params.tearFlags; + beam.SetColor(params.tearColor, -1, 255, false, true); + beam.SetCollisionDamage(params.tearDamage); + beam.renderDepthOffset = SPRINKLER_BEAM_DEPTH; +} + +// 0063aef0 The Sprinkler's Technology laser: a short thin beam from its eye at an angle, hitting once, with the +// player's tear effects, passing over pits when spectral. +Entity_Laser* Entity_Familiar::sprinkler_shoot_laser(float angle, float distance) +{ + Vector offset = vector_add(vector_scale(vector_from_angle(angle), distance), vector_make(0, SPRINKLER_EYE_LIFT)); + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = pos, + .posOffset = offset, + .source = this, + .angleDegrees = angle, + .timeout = SPRINKLER_LASER_TIMEOUT, + .variant = LASER_THIN_RED}); + laser->isOneHit = true; + sprinkler_beam_dress(*laser, sprinkler_hit_params(*this, WEAPON_LASER)); + laser->entityGridCollisionClass = laser->tearFlags[TEAR_SPECTRAL] ? GRIDCOLL_NOPITS : GRIDCOLL_WALLS; + return laser; +} + +// 0063acf0 FamiliarHelper::sprinkler_fire_laser: the Sprinkler's Brimstone beam (Brimstone and Technology's with +// Technology), reaching as far as the player's would by its tear height. +static Entity_Laser* sprinkler_fire_brimstone(Entity_Familiar& sprinkler, float angle, float distance) +{ + Entity_Player& player = *sprinkler.player; + Vector offset = vector_add(vector_scale(vector_from_angle(angle), distance), vector_make(0, SPRINKLER_EYE_LIFT)); + Entity_Laser* beam = Entity_Laser::ShootAngle( + {.position = sprinkler.pos, + .posOffset = offset, + .source = &sprinkler, + .angleDegrees = angle, + .timeout = SPRINKLER_BRIMSTONE_TIMEOUT, + .variant = player.HasCollectible(COLLECTIBLE_TECHNOLOGY) ? LASER_BRIM_TECH : LASER_THICK_RED}); + sprinkler_beam_dress(*beam, sprinkler_hit_params(sprinkler, WEAPON_BRIMSTONE)); + + bool isAzazel = player.playerType == PLAYER_AZAZEL || player.temporaryEffects.HasTrinketEffect(TRINKET_AZAZELS_STUMP); + float drop = player.tearHeight * SPRINKLER_RANGE_PER_HEIGHT; + if (isAzazel && !player.HasCollectible(COLLECTIBLE_BRIMSTONE)) + beam->maxDistance = std::max(SPRINKLER_AZAZEL_RANGE - drop, SPRINKLER_AZAZEL_RANGE_MIN); + else beam->maxDistance = SPRINKLER_BRIMSTONE_RANGE - drop; + return beam; +} + +// 0063b070 FamiliarAI::sprinkler_spawn_knife: one of the Sprinkler's knives, set out at an angle with the player's +// knife effects, flying a homing path from it. +static Entity_Knife* sprinkler_spawn_knife(Entity_Familiar& sprinkler, float angle, float distance) +{ + TearParams params = sprinkler_hit_params(sprinkler, WEAPON_KNIFE); + Vector direction = vector_from_angle(angle); + auto* knife = static_cast(g_game->Spawn({.position = vector_add(sprinkler.pos, vector_scale(direction, distance)), + .spawner = &sprinkler, + .subType = SPRINKLER_KNIFE_SUBTYPE, + .type = ENTITY_KNIFE, + .seed = Random()})); + knife->posOffset = vector_make(0, SPRINKLER_EYE_LIFT); + knife->SetCollisionDamage(params.tearDamage); + knife->SetColor(params.tearColor, -1, 255, false, true); + knife->parent = &sprinkler; + knife->tearFlags = params.tearFlags; + knife->InitHomingPath(direction, &sprinkler, 0); + knife->pathFollowSpeed = SPRINKLER_KNIFE_FOLLOW_SPEED; + knife->Update(); + return knife; +} + +// Part of 00635390: Epic Fetus' targets, the first drifting off along the turn and the others (Mom's Eye's, Loki's +// Horns' and Monstro's Lung's) held to it. +static void sprinkler_targets(Entity_Familiar& sprinkler, const Weapon_MultiShotParams& params) +{ + Entity_Player& player = *sprinkler.player; + int life = (params.numTears * TARGET_LIFE_PER_TEAR + TARGET_LIFE_BASE) * 2; + auto spawn = [&](Vector velocity, uint32_t seed, Entity* parent, int subtype) { + auto* target = static_cast(g_game->Spawn({.position = sprinkler.pos, + .velocity = velocity, + .spawner = &sprinkler, + .type = ENTITY_EFFECT, + .variant = EFFECT_TARGET, + .seed = seed})); + target->parent = parent; + target->state = params.numTears; + target->timeout = life; + target->lifespan = life; + target->subtype = subtype; + return target; + }; + + uint32_t seed = Random(); + float speed = random_unit() * TARGET_SPEED_RANGE + TARGET_SPEED_BASE; + Entity_Effect* lead = spawn(vector_scale(sprinkler_direction(sprinkler, 0), speed), seed, &sprinkler, 0); + if (player.HasCollectible(COLLECTIBLE_MOMS_EYE) || player.HasCollectible(COLLECTIBLE_LOKIS_HORNS)) + { + spawn({}, Random(), lead, 1); + if (player.HasCollectible(COLLECTIBLE_LOKIS_HORNS)) + for (int subtype = 2; subtype < SPRINKLER_HORN_SHOTS; subtype++) spawn({}, Random(), lead, subtype); + } + for (uint32_t i = sprinkler_lung_extras(player, LUNG_TARGETS_MIN); i > 0; i--) + { + Entity_Effect* scattered = spawn({}, Random(), lead, TARGET_LUNG_SUBTYPE); + float turn = random_unit() * RANDOM_HALF_TURN * 2; + float spread = random_unit() * TARGET_LUNG_SPREAD_RANGE + TARGET_LUNG_SPREAD_MIN; + scattered->posOffset = vector_scale(vector_make(std::cos(turn), std::sin(turn)), spread); + } +} + +// Part of 00635390: the Sprinkler's knives, bombs, Tech X rings, lasers, Brimstone beams and C Section fetuses, each +// the way the player's weapon fires them, Monstro's Lung adding scattered extras to most. +static void sprinkler_weapons(Entity_Familiar& sprinkler, const Weapon_MultiShotParams& params) +{ + Entity_Player& player = *sprinkler.player; + auto randomAngle = [] { return random_unit() * 360 - 180; }; + if (player.weaponTypes[WEAPON_KNIFE]) + { + sprinkler_volley(sprinkler, WEAPON_KNIFE, params, [&](const SprinklerShot& shot) { + sprinkler_spawn_knife(sprinkler, shot.angle, SPRINKLER_REACH)->Update(); + }); + for (uint32_t i = sprinkler_lung_extras(player, LUNG_KNIVES_MIN); i > 0; i--) + sprinkler_spawn_knife(sprinkler, randomAngle(), SPRINKLER_REACH)->Update(); + } + if (player.weaponTypes[WEAPON_BOMBS]) + sprinkler_volley(sprinkler, WEAPON_BOMBS, params, [&](const SprinklerShot& shot) { + player.FireBomb(shot.position, shot.velocity, nullptr)->Update(); + }); + if (player.weaponTypes[WEAPON_TECH_X]) + { + sprinkler_volley(sprinkler, WEAPON_TECH_X, params, [&](const SprinklerShot& shot) { + player.FireTechXLaser({.position = shot.position, .velocity = shot.velocity, .radius = SPRINKLER_TECH_X_RADIUS}) + ->Update(); + }); + Vector aim = sprinkler_direction(sprinkler, 0); + for (uint32_t i = sprinkler_lung_extras(player, LUNG_BEAMS_MIN); i > 0; i--) + { + float radius = (random_unit() * HALF + LUNG_RING_RADIUS_MIN) * SPRINKLER_SHOT_SPEED; + float turn = random_unit() * LUNG_RING_SPREAD - LUNG_RING_SPREAD / 2; + player.FireTechXLaser({.position = vector_add(sprinkler.pos, vector_scale(aim, SPRINKLER_REACH)), + .velocity = vector_rotated(aim, turn), + .radius = radius}) + ->Update(); + } + } + if (player.weaponTypes[WEAPON_LASER]) + { + sprinkler_volley(sprinkler, WEAPON_LASER, params, [&](const SprinklerShot& shot) { + sprinkler.sprinkler_shoot_laser(shot.angle, SPRINKLER_REACH)->Update(); + }); + for (uint32_t i = sprinkler_lung_extras(player, LUNG_BEAMS_MIN); i > 0; i--) + sprinkler.sprinkler_shoot_laser(randomAngle(), SPRINKLER_REACH)->Update(); + } + if (player.weaponTypes[WEAPON_BRIMSTONE]) + { + sprinkler_volley(sprinkler, WEAPON_BRIMSTONE, params, [&](const SprinklerShot& shot) { + sprinkler_fire_brimstone(sprinkler, shot.angle, SPRINKLER_REACH)->Update(); + }); + for (uint32_t i = sprinkler_lung_extras(player, LUNG_BEAMS_MIN); i > 0; i--) + sprinkler_fire_brimstone(sprinkler, randomAngle(), SPRINKLER_REACH)->Update(); + } + ::Weapon* tearWeapon = player.weapons[1].get(); + if (tearWeapon && tearWeapon->weaponType == WEAPON_FETUS) + sprinkler_volley(sprinkler, WEAPON_FETUS, params, [&](const SprinklerShot& shot) { + sprinkler.TryFireTear(fire_fetus_tear(*tearWeapon, {.position = shot.position, + .velocity = shot.velocity, + .source = &sprinkler, + .fireFlags = SPRINKLER_TEAR_FLAGS})); + }); +} + // Fires one of the player's tears from the Sprinkler. static void sprinkler_tear(Entity_Familiar& sprinkler, const PosVel& shot) { @@ -138,8 +390,8 @@ static void sprinkler_face(Entity_Familiar& sprinkler) // 00635390 FamiliarAI::sprinkler: the Sprinkler stays where it landed, marking its tile for pathing. Once it appeared // (in Loki's or Mom's Eye's look) it fires the player's weapon at the player's rate (a third of it for Epic Fetus and -// C Section), turning an eighth each volley. Tears, Monstro's Lung and the bone tears are written, the other weapons -// stop the game. +// C Section), turning an eighth each volley: Epic Fetus' targets, knives, bombs, Tech X rings, lasers, Brimstone beams, +// C Section's fetuses and the tears, Monstro's Lung's and bone tears. void sprinkler_update(Entity_Familiar& sprinkler) { if (vector_is_zero(sprinkler.targetPosition)) sprinkler.targetPosition = sprinkler.pos; @@ -168,13 +420,8 @@ void sprinkler_update(Entity_Familiar& sprinkler) if (sprinkler.GetIntervalTicks(fireDelay, 0) == 0) return; Weapon_MultiShotParams params = player.GetMultiShotParams(WEAPON_TEARS); - ::Weapon* tearWeapon = player.weapons[1].get(); - for (WeaponType type : SPRINKLER_UNWRITTEN_WEAPONS) - if (player.weaponTypes[type]) - return reconstruction_missing("FamiliarAI::sprinkler 00635390 (this weapon through the Sprinkler)"); - if (tearWeapon && tearWeapon->weaponType == WEAPON_FETUS) - return reconstruction_missing("FamiliarAI::sprinkler 00635390 (C Section through the Sprinkler)"); - + if (player.weaponTypes[WEAPON_ROCKETS]) sprinkler_targets(sprinkler, params); + sprinkler_weapons(sprinkler, params); if (player.weaponTypes[WEAPON_TEARS] || player.weaponTypes[WEAPON_MONSTROS_LUNGS] || player.weaponTypes[WEAPON_BONE]) sprinkler_tears(sprinkler, params); diff --git a/src/familiar_update.cpp b/src/familiar_update.cpp index deb30d0..f7b18b0 100644 --- a/src/familiar_update.cpp +++ b/src/familiar_update.cpp @@ -982,7 +982,7 @@ static void gemini_animate(Entity_Familiar& gemini, int previousCooldown) else if (!isPlaying) gemini.sprite.Play(isRaging ? "FloatDownRage" : "FloatDown"); } -// Part of 0061da10 (0061d030, the database's lil_haunt): Gemini follows until an enemy comes within reach of its +// 0061d030 FamiliarAI::lil_haunt, which is Gemini's update: it follows until an enemy comes within reach of its // player, then charges it on its leash, dropping it once it strays out of reach. Twins keep apart. void gemini_update(Entity_Familiar& gemini) { @@ -1081,7 +1081,7 @@ static void familiar_wander(Entity_Familiar& familiar) } } -// Part of 0061da10 (0061c3f0, the database's variant_66): Sissy Longlegs wanders the room, resting between walks, +// 0061c3f0 FamiliarAI::variant_66, Sissy Longlegs' update: it wanders the room, resting between walks, // and while enemies remain lays a blue spider now and then, up to its player's limit. void sissy_longlegs_update(Entity_Familiar& sissy) { diff --git a/src/familiar_variants.cpp b/src/familiar_variants.cpp index 3eefb9b..1ff20a5 100644 --- a/src/familiar_variants.cpp +++ b/src/familiar_variants.cpp @@ -899,6 +899,7 @@ void knife_dash(Entity_Familiar& knife) return; } + if (knife.IsLilithBirthrightIncubus()) return; knife.entityCollisionClass = ENTCOLL_NONE; knife.entityGridCollisionClass = GRIDCOLL_NONE; if (vector_is_zero(knife.gridCollisionNormal)) diff --git a/src/fx_layers.cpp b/src/fx_layers.cpp index 2fc8c59..5a4fdf3 100644 --- a/src/fx_layers.cpp +++ b/src/fx_layers.cpp @@ -14,7 +14,6 @@ #include #include -constexpr std::string_view DOCUMENT_TAG = "#document"; constexpr std::string_view LAYER_TYPE_NAMES[] = {"", "foreground", "background", "behind", "lighting", "underwater", "overlay"}; constexpr std::string_view COLOR_CHANNELS[] = {"r", "g", "b", "a"}; diff --git a/src/fx_layers.h b/src/fx_layers.h index fb5ed00..24bd0b7 100644 --- a/src/fx_layers.h +++ b/src/fx_layers.h @@ -65,6 +65,8 @@ constexpr uint32_t CLEAR_ARGB = 0; constexpr uint32_t TEXT_ARGB = 0xff362f2d; // A sprite drawn solid white: its own color dropped and white added. constexpr ColorMod SOLID_WHITE = {{0, 0, 0, 1}, {0, 0, 0, 0}, {1, 1, 1}}; +// The green poop clouds of bad gas (AddPoopFx's color for poison farts). +constexpr ColorMod BAD_GAS_CLOUDS = {{1, 1, 1, 1}, {0, 1, 0, 1}, {0, 0, 0}}; // 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. diff --git a/src/game.cpp b/src/game.cpp index 93488f1..4a163ec 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -39,7 +39,6 @@ constexpr int BLOOM_DURATION_DEFAULT = 30; constexpr int REVIVE_MACHINE_COINS = 10; constexpr float DIZZY_CHANGE_SPEED_DEFAULT = 0.001f; 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"}; @@ -117,6 +116,31 @@ Game::~Game() reconstruction_missing("Game::~Game 006f3060"); } +// 006f3c00 Reloads the run's configs a Lua reset may have changed, through the mods' redirection (stages, the game's +// curses, minibosses and characters), then the run's UI: the scoreboard, HUD, pause screen, revive menu, prompt and +// completion marks. +// The original also zeroes GameOver's second int and the ints at Game+0x1d63c and Game+0x1d64c, not modeled yet. +void Game::ReloadStagesXmlOnLuaReset() +{ + Game& game = *g_game; + ModManager& mods = g_manager->modManager; + + game.roomConfig.LoadStages(mods.TryRedirectPath(STAGES_XML)); + game.roomConfig.LoadCurses(mods.TryRedirectPath(CURSES_XML), CURSES_REPLACE); + game.roomConfig.LoadMinibosses(mods.TryRedirectPath(MINIBOSSES_XML)); + g_manager->entityConfig.LoadPlayers(mods.TryRedirectPath(PLAYERS_XML), nullptr); + + game.gameOver.state = GAME_OVER_HIDDEN; + game.leaderboard.LoadAnm2(); + game.hud.LoadGraphics(); + game.pauseScreen.Init(); + game.revivePlayerMenu.Init(); + game.genericPrompt.Initialize(PROMPT_LARGE); + victory_run_prompt_load(game.genericPrompt); + game.completionWidgetSprite.Load(COMPLETION_WIDGET_ANM2, GRAPHICS_LOAD); + game.completionWidgetSprite.SetFrame(COMPLETION_WIDGET_ANIMATION, 0); +} + // 006f4740 Resets the run, then loads the run's configs through the mods' redirection: stages, curses with the mods', // minibosses, the giant books and boss overlays, the run's UI, the Boss Rush waves, the preloads and their groups, the // procedural item surfaces, par times and prompts, then empties the online stats and the console. diff --git a/src/game.h b/src/game.h index 686d2d1..a3389dc 100644 --- a/src/game.h +++ b/src/game.h @@ -93,6 +93,7 @@ enum GameStateFlag : int GAME_STATE_BLUEWOMB_DOOR_SPAWNED = 39, GAME_STATE_BLUEWOMB_DONE = 40, GAME_STATE_SECRET_PATH = 44, + GAME_STATE_MAUSOLEUM_HEART_KILLED = 46, GAME_STATE_BACKWARDS_PATH = 48, GAME_STATE_MEGA_SATAN_DOOR_OPENED = 49 }; @@ -328,6 +329,7 @@ public: ~Game(); static void LoadConfigXmls(); + static void ReloadStagesXmlOnLuaReset(); bool load_giantbook_xml(std::string_view path); bool load_bossoverlays_xml(std::string_view path); static void LoadBossRushXml(std::string_view path); diff --git a/src/game_restore.cpp b/src/game_restore.cpp index 9846b97..d0bbf8d 100644 --- a/src/game_restore.cpp +++ b/src/game_restore.cpp @@ -6,6 +6,7 @@ #include "manager.h" #include "music_manager.h" #include "npc_ai.h" +#include "npc_basement.h" #include "room.h" #include "texture_cache.h" #include @@ -18,8 +19,6 @@ constexpr uint32_t ROOM_REF_STAGE_MASK = 0xffff; constexpr uint32_t ROOM_REF_HALF_MASK = 0xffff; constexpr uint32_t ROOM_REF_MODE_MASK = 0xff; -constexpr uint32_t PLAYER_RNG_SHIFT = 34; -constexpr uint32_t ITEM_POOL_SHIFT = 3; constexpr uint32_t DEVIL_ANGEL_SHIFT = 2; constexpr uint8_t HOLY_MANTLE_SAVED = 2; constexpr const char* ITEM_POOLS_XML = "itempools.xml"; @@ -213,6 +212,35 @@ void ItemPool::RestoreGameState(const GameStateItemPool& state) remainingGenesisItems = state.remainingGenesisItems; } +// Part of 007475b0: a saved escape from the mineshaft brings Mother's shadow back 100 behind where the players came +// in, or 100 back through their door (a random one of the room's when unknown). +static void mothers_shadow_restore(Level& level) +{ + constexpr float SHADOW_BEHIND = 100; + + Room& room = *level.room; + Vector at = level.GetEnterPosition(); + if (vector_is_zero(at)) + { + int door = level.enterDoor; + if (door == -1) + { + door = (int)(Random() & 7); + for (int tries = 0; tries < DOOR_SLOT_COUNT; tries++) + { + if (door < DOOR_SLOT_COUNT && (room.descriptor->data->doors & 1u << door)) break; + door = (door + 1) % DOOR_SLOT_COUNT; + } + } + at = {}; + if ((uint32_t)door < DOOR_SLOT_COUNT) at = room.GetGridPosition(room.doorGridPositions[door]); + Vector away = vector_scale(vector_from_direction(door % 4), SHADOW_BEHIND); + at = vector_add(at, away); + } + else at.y -= SHADOW_BEHIND; + g_game->Spawn({.position = at, .type = ENTITY_MOTHERS_SHADOW, .seed = Random()})->Update(); +} + // 007475b0 Restores the floor from a save and enters its room: the stage, curses, flags, Greed waves and seeds, the // maps and every room descriptor with its config named again, the rooms the players are in and came from, and the // Ventricle Razor portals. Backasswards resumed in the uncleared boss room starts over in the first room and walks back @@ -309,8 +337,7 @@ void Level::RestoreGameState(GameState& state) bool isMineshaftEscape = currentDimensionIdx == DIMENSION_ALTERNATE && !game.IsGreedMode() && !isBackwards && (stageType == STAGETYPE_REPENTANCE || stageType == STAGETYPE_REPENTANCE_B) && isMinesFloor && (levelStateFlags & 1u << LEVEL_STATE_MINESHAFT_ESCAPE); - if (isMineshaftEscape) - reconstruction_missing("Level::RestoreGameState 007475b0: the mineshaft escape's Mother's shadow"); + if (isMineshaftEscape) mothers_shadow_restore(*this); room->camera->DoUpdate(false); room->brokenWatchState = (BrokenWatchState)(int8_t)state.brokenWatchState; @@ -617,8 +644,7 @@ void Entity_Player::RestoreGameState(GameStatePlayer& saved) forgottenBodyRoomIdx = saved.forgottenBodyRoomIdx; forgottenBodyPos = saved.forgottenBodyPos; maggyHealthDrainCooldown = saved.maggyHealthDrainCooldown; - echoChamberItems.clear(); - for (PocketItem item : saved.echoChamberItems) echoChamberItems.push_back(item.id); + echoChamberItems.assign(saved.echoChamberItems.begin(), saved.echoChamberItems.end()); std::ranges::copy(saved.bagOfCraftingContent | std::views::take(bagOfCraftingContent.size()), bagOfCraftingContent.begin()); bagOfCraftingOutput = saved.bagOfCraftingOutput; diff --git a/src/game_save.cpp b/src/game_save.cpp index 0a8d7af..d0aaead 100644 --- a/src/game_save.cpp +++ b/src/game_save.cpp @@ -399,8 +399,7 @@ void Entity_Player::StoreGameState(GameStatePlayer* saveState, bool isSaveTempor state.forgottenBodyRoomIdx = forgottenBodyRoomIdx; state.forgottenBodyPos = forgottenBodyPos; state.maggyHealthDrainCooldown = maggyHealthDrainCooldown; - state.echoChamberItems.clear(); - for (int item : echoChamberItems) state.echoChamberItems.push_back({.id = item}); + state.echoChamberItems.assign(echoChamberItems.begin(), echoChamberItems.end()); std::copy(bagOfCraftingContent.begin(), bagOfCraftingContent.end(), state.bagOfCraftingContent.begin()); state.bagOfCraftingOutput = bagOfCraftingOutput; state.bagOfCraftingPool = bagOfCraftingPool; diff --git a/src/game_transition.cpp b/src/game_transition.cpp index 01d0ea2..e56f9a6 100644 --- a/src/game_transition.cpp +++ b/src/game_transition.cpp @@ -390,8 +390,15 @@ void Level::ChangeRoom(int targetRoomIdx, int dimension) } if (dimension < 0) dimension = currentDimensionIdx; 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)"); + { + DimensionReturn& back = deathCertificateReturn; + currentRoomIdx = back.roomIdx; + lastRoomIdx = back.lastRoomIdx; + currentDimensionIdx = back.dimension; + currentRoomMap = &roomMap[back.dimension * LEVEL_GRID_CELLS]; + lastRoomDimensionIdx = back.lastRoomDimension; + leaveDoor = back.leaveDoor; + } RoomDescriptor& target = *GetRoomByIdx(newRoomIdx, dimension); bool isHomeDungeon = target.data && target.data->type == ROOM_DUNGEON && target.data->stageId == STAGE_ID_HOME; diff --git a/src/game_update.cpp b/src/game_update.cpp index 5f58b43..5248186 100644 --- a/src/game_update.cpp +++ b/src/game_update.cpp @@ -312,7 +312,9 @@ static void timers_update(Game& game) if (game.currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE) { game.leaveDoor = -1; - reconstruction_missing("Game::StartRoomTransition 006fd7c0, out of the Death Certificate floor"); + game.StartRoomTransition({.animation = TRANSITION_DEATH_CERTIFICATE, + .dimension = game.deathCertificateReturn.dimension, + .roomIndex = game.deathCertificateReturn.roomIdx}); } } } @@ -415,7 +417,8 @@ void Game::Update() // players run a full update flagged as an interpolation one and the transition's entities interpolate. Then, unless // the run is paused or the window lost focus (with pause on focus loss), the players update and collide with the grid // again while everything else interpolates half a step, and the extra players update. -// The Beast arena's scroll and the stage transition's trapdoor landing scale stop the game: neither is modelled yet. +// In the Beast's arena the background and what is not a player or familiar scroll half a step, and the players +// collide with the grid again. void Game::interpolate_update() { Manager& manager = *g_manager; @@ -465,7 +468,7 @@ void Game::interpolate_update() entity.PlayerCollideWithGrid(GRID_COLLISION_APPLY); entity.flags &= ~FLAG_INTERPOLATION_UPDATE; } - if (room->IsBeastDungeon()) reconstruction_missing("Game::interpolate_update 006fd3f0: the Beast arena's scroll"); + if (room->beastArena.isActive) room->beastArena.interpolate(); room->isUnknown7220 = true; for (size_t i = 0; i < playerManager.extraPlayers.size(); i++) player_update(*playerManager.extraPlayers[i]); diff --git a/src/grid_entity_pressure_plate.cpp b/src/grid_entity_pressure_plate.cpp index 8e193b5..360c49b 100644 --- a/src/grid_entity_pressure_plate.cpp +++ b/src/grid_entity_pressure_plate.cpp @@ -27,7 +27,6 @@ constexpr int AMBUSH_RESPAWN_FRAME = 4; // Greed's timer under the button: seconds and minutes, how far below the button it shows, and its grey blink. constexpr int TIMER_FRAMES_PER_SECOND = 30; -constexpr int SECONDS_PER_MINUTE = 60; constexpr int TIMER_TEXT_SIZE = 32; constexpr int TIMER_BLINK_FRAMES = 4; constexpr float TIMER_PLATE_DROP = 21; diff --git a/src/homing_laser.cpp b/src/homing_laser.cpp index 0bf2d45..9fdc7bb 100644 --- a/src/homing_laser.cpp +++ b/src/homing_laser.cpp @@ -19,6 +19,49 @@ constexpr float PLAYER_CUT_DISTANCE_SQUARED = 100; constexpr uint32_t PLAYER_CUT_FIRST_SAMPLE = 2; constexpr float GRID_HALF_CELL = GRID_CELL_SIZE / 2; constexpr float OBSTACLE_MARGIN = 20; +constexpr float RING_PULL_TENSION = 0.4f; + +// The worms' waves: rolling a tenth of a turn a frame, 10 out on a ring (six round it), up to 20 across a line in +// turns over each 200 of its length, eased in over 20 samples and out over 22. +constexpr float WAVE_ROLL_SPEED = 0.1f; +constexpr float WAVE_REACH = 10; +constexpr float RING_SINE_TURNS = 37.699112f; +constexpr float WAVE_STRENGTH = 20; +constexpr float WAVE_PATH_UNIT = 200; +constexpr float WAVE_TURNS = 15; +constexpr uint32_t WAVE_EASE_IN = 20; +constexpr uint32_t WAVE_EASE_OUT = 22; + +// Pulse Worm's steps: four waves round a ring rolling faster, and across a line blocks of 15 samples (4 on a path 500 +// long) stepping 20 aside, past the first two samples and short of the last three. +constexpr float SQUARE_RING_ROLL_SPEED = 0.16f; +constexpr float SQUARE_RING_TURNS = 25.132742f; +constexpr float SQUARE_FULL_LENGTH = 500; +constexpr float SQUARE_PERIOD_MAX = 15; +constexpr float SQUARE_PERIOD_RANGE = 11; +constexpr float SQUARE_STEP = 20; +constexpr uint32_t SQUARE_FIRST_SAMPLE = 2; +constexpr uint32_t SQUARE_LAST_SKIPPED = 3; + +// Tiny Planet's curl: 50 out along the aim, then six points round the start from 0.7 back, each 0.3 pi on from the last, their handles a quarter radian either side and 5% further out. +constexpr float CURL_LEAD = 50; +constexpr float CURL_START_TURN = 0.7f; +constexpr float CURL_HANDLE_SCALE = 1.05f; +constexpr float CURL_HANDLE_SPREAD = 0.25f; +constexpr uint32_t CURL_POINTS = 6; +constexpr float CURL_STEP_DIVISOR = 5; +constexpr float CURL_TURNS = 6; +constexpr float CURL_TURN_SHARE = 0.25f; + +// My Reflection's loop: its handles a fifth of its length. +constexpr float LOOP_HANDLE = 0.2f; + +// Brain Worm's turn: past 80 along, its corner 20 either side with handles 5 and 60 out, started over when 40 off. +constexpr float TRACE_MIN_ALONG = 80; +constexpr float TRACE_CORNER = 20; +constexpr float TRACE_HANDLE_NEAR = 5; +constexpr float TRACE_HANDLE_FAR = 60; +constexpr float TRACE_RESTART_DISTANCE = 40; // A hunting path: 40 long steps turned 0.3 toward the nearest target, up to 25 points, smoothed at 0.4. A path shorter // than 0.1 does not hunt. @@ -560,22 +603,114 @@ void HomingLaser::compute_bezier_handles(float tension) } } -// 0099ec00 -void HomingLaser::apply_sine_offset(float, float) +// 0099ec00 Wiggle Worm: a ring's samples swell in and out from its center in six waves rolling round it. A line's +// samples swing across it in waves along a stretch scaled by its length, rolling on with the frames, easing in over +// the first 20 and out over the last 22. +void HomingLaser::apply_sine_offset(float amplitude, float phase) { - reconstruction_missing("HomingLaser::apply_sine_offset 0099ec00"); + size_t count = samples.size(); + float roll = (float)g_game->frameCount * WAVE_ROLL_SPEED; + if (isRing) + { + for (uint32_t i = 0; i < count; i++) + { + Vector radial = vector_normalized(vector_sub(samples[i], origin)); + float wave = std::sin((float)i * RING_SINE_TURNS / (float)(uint32_t)(count - 1) - roll - phase); + wave = wave * WAVE_REACH * amplitude; + samples[i] = vector_add(vector_scale(radial, wave), samples[i]); + } + return; + } + + if (count < 2) return; + float pathScale = vector_distance(origin, endPoint) / WAVE_PATH_UNIT; + for (uint32_t i = 0; i + 1 < count; i++) + { + Vector direction = vector_normalized(vector_sub(samples[i + 1], samples[i])); + float strength = amplitude * WAVE_STRENGTH; + if (i < WAVE_EASE_IN) + strength = (float)i / WAVE_EASE_IN * strength; + else if ((uint32_t)count - WAVE_EASE_OUT < i) + strength = (float)(uint32_t)(count - i + 1) / WAVE_EASE_OUT * strength; + float wave = std::sin((float)i / (float)(uint32_t)(count - 2) * pathScale * WAVE_TURNS - roll - phase); + samples[i].x = direction.y * wave * strength + samples[i].x; + samples[i].y = -direction.x * wave * strength + samples[i].y; + } } -// 0099fa60 -void HomingLaser::build_curl_path(float) +// 0099fa60 Tiny Planet: the path leaves its start along its aim for 50, then curls round the start in six points at +// a radius (handles 5% further out), and runs out to its end. +void HomingLaser::build_curl_path(float radius) { - reconstruction_missing("HomingLaser::build_curl_path 0099fa60"); + Vector reach = vector_sub(endPoint, origin); + Vector direction = vector_normalized(reach); + bezier.push_back({origin, origin, vector_add(vector_scale(direction, CURL_LEAD), origin)}); + + float start = (float)std::atan2((double)reach.y, (double)reach.x) - CURL_START_TURN; + float handleRadius = radius * CURL_HANDLE_SCALE; + auto onCircle = [this](float angle, float distance) { + return vector_make((float)std::cos((double)angle) * distance + origin.x, + (float)std::sin((double)angle) * distance + origin.y); + }; + for (uint32_t i = 0; i < CURL_POINTS; i++) + { + float angle = start - (float)i / CURL_STEP_DIVISOR * PI_F * CURL_TURNS * CURL_TURN_SHARE; + Vector handleIn = onCircle(angle + CURL_HANDLE_SPREAD, handleRadius); + Vector point = onCircle(angle, radius); + Vector handleOut = onCircle(angle - CURL_HANDLE_SPREAD, handleRadius); + bezier.push_back({point, handleIn, handleOut}); + } + + bezier.push_back({vector_sub(endPoint, vector_scale(reach, 0.5f)), vector_sub(endPoint, vector_scale(reach, 0.75f)), + vector_sub(endPoint, vector_scale(reach, 0.25f))}); + bezier.push_back({endPoint, vector_sub(endPoint, vector_scale(reach, 0.25f)), vector_add(endPoint, reach)}); } -// 0099fed0 -void HomingLaser::build_wiggle_bezier() +// 0099fed0 My Reflection: the path loops out a length along its aim and back round a width, continuing from the last +// point of a path already laid (which it replaces), then runs back past its start to the room's edge, within a +// most length (none for 0). +void HomingLaser::build_wiggle_bezier(const BoomerangLoop& loop) { - reconstruction_missing("HomingLaser::build_wiggle_bezier 0099fed0"); + Vector direction = vector_normalized(vector_sub(endPoint, origin)); + float cosine = std::cos(PI_F / 2); + float sine = std::sin(PI_F / 2); + Vector forward = vector_scale(direction, loop.length); + Vector handle = vector_scale(forward, LOOP_HANDLE); + Vector side = vector_make((cosine * direction.x - sine * direction.y) * loop.width * 0.5f, + (sine * direction.x + cosine * direction.y) * loop.width * 0.5f); + Vector leftHalf = vector_sub(vector_scale(forward, 0.5f), side); + Vector rightHalf = vector_add(side, vector_scale(forward, 0.5f)); + + // A path of one point has nothing left to continue from once its point goes, so it starts over like an empty one. + if (!bezier.empty()) bezier.pop_back(); + Vector start = origin; + if (bezier.empty()) + bezier.push_back({origin, origin, vector_add(handle, origin)}); + else + { + start = bezier.back().point; + bezier.back().handleOut = vector_add(handle, start); + } + + Vector left = vector_add(start, leftHalf); + bezier.push_back({left, vector_sub(left, handle), vector_add(handle, left)}); + Vector tip = vector_add(start, forward); + bezier.push_back({tip, vector_sub(tip, side), vector_add(side, tip)}); + Vector right = vector_add(start, rightHalf); + bezier.push_back({right, vector_add(handle, right), vector_sub(right, handle)}); + Vector back = vector_scale(rightHalf, 0.5f); + bezier.push_back({start, vector_add(back, start), vector_sub(start, back)}); + + Vector away = vector_scale(direction, -1); + endPoint = static_cast(owner)->calc_end_point(start, away); + float length = vector_distance(endPoint, start); + if (loop.maxLength != 0 && loop.maxLength < length) + { + endPoint = vector_sub(start, vector_scale(direction, loop.maxLength)); + length = loop.maxLength; + } + Vector endHandle = vector_scale(vector_scale(direction, length), 0.5f); + bezier.push_back({endPoint, vector_add(endHandle, endPoint), vector_sub(endPoint, endHandle)}); } // 009a0c50 Cuts the path at the first segment past the first that a wall or obstacle stops, the stop taking the @@ -595,15 +730,43 @@ void HomingLaser::truncate_samples_at_obstacle(const Vector& offset) } } -// 009a0fa0 -void HomingLaser::apply_sample_wiggle(float, float) +// 009a0fa0 Pulse Worm and the like: a ring's samples swell in and out from its center in four waves rolling round +// it. A line's inner samples step across it together, in blocks that alternate sides, the blocks shorter on a longer +// path. +void HomingLaser::apply_sample_wiggle(float amplitude, float phase) { - reconstruction_missing("HomingLaser::apply_sample_wiggle 009a0fa0"); + size_t count = samples.size(); + if (count == 0) return; + + if (isRing) + { + float roll = (float)g_game->frameCount * SQUARE_RING_ROLL_SPEED; + for (uint32_t i = 0; i < count; i++) + { + Vector radial = vector_normalized(vector_sub(samples[i], origin)); + float wave = std::sin((float)i * SQUARE_RING_TURNS / (float)(uint32_t)(count - 1) - roll); + samples[i].x = radial.x * wave * WAVE_REACH * amplitude + samples[i].x; + samples[i].y = radial.y * wave * WAVE_REACH * amplitude + samples[i].y; + } + return; + } + + float lengthShare = std::clamp(totalLength / SQUARE_FULL_LENGTH, 0.0f, 1.0f); + int period = (int)(SQUARE_PERIOD_MAX - lengthShare * SQUARE_PERIOD_RANGE); + for (uint32_t i = SQUARE_FIRST_SAMPLE; i + SQUARE_LAST_SKIPPED < count; i++) + { + Vector direction = vector_normalized(vector_sub(samples[i + 1], samples[i])); + float step = std::sin((float)g_game->frameCount * WAVE_ROLL_SPEED + phase) * SQUARE_STEP * amplitude; + if ((int)i % (period * 2) < period) step = -step; + samples[i].x = direction.y * step + samples[i].x; + samples[i].y = -direction.x * step + samples[i].y; + } } // 009a0850 Lays out a ring of radius around a center: seven points (the last closing the circle) with handles along -// its tangent. Spoon Bender's ring bending toward enemies is not reconstructed yet. -void HomingLaser::build_ring_bezier(const Vector& center, bool isHoming, Entity*, float radius) +// its tangent. A homing ring (Spoon Bender) pulls each inner point onto the first enemy (or a rival's familiar in a +// versus match) near the curve after it, one point each, and smooths the ring again if any moved. +void HomingLaser::build_ring_bezier(const Vector& center, bool isHoming, Entity* ignored, float radius) { for (int i = 0; i <= RING_SEGMENTS; i++) { @@ -614,11 +777,95 @@ void HomingLaser::build_ring_bezier(const Vector& center, bool isHoming, Entity* std::sin(tangentAngle) * radius * RING_HANDLE); bezier.push_back({point, vector_sub(point, tangent), vector_add(point, tangent)}); } - if (isHoming) reconstruction_missing("HomingLaser::build_ring_bezier 009a0850 (a homing ring)"); + if (!isHoming) return; + + bool isVersus = g_game->deathmatchManager.is_active(); + std::vector targets; + for (Entity* entity : g_game->room->entityList.updateEL) + { + bool isTarget = entity->IsVulnerableEnemy(nullptr) && + !entity->HasEntityFlags(FLAG_NO_TARGET | FLAG_FRIENDLY) && entity != ignored; + bool isRival = isVersus && entity->type == ENTITY_FAMILIAR && entity->variant == Entity_Familiar::PUNCHING_BAG && + ignored && !entity->IsDescendantOf(ignored->spawnerEntity); + if (isTarget || isRival) targets.push_back(entity); + } + + bool isBent = false; + for (size_t i = 1; i + 1 < bezier.size(); i++) + { + auto pulled = std::find_if(targets.begin(), targets.end(), [&](Entity* target) { + float t = 0; + return bezier_closest_point(target->pos, bezier[i], bezier[i + 1], t) < reach * reach; + }); + if (pulled == targets.end()) continue; + + bezier[i].point = (*pulled)->pos; + targets.erase(pulled); + isBent = true; + } + if (isBent) compute_bezier_handles(RING_PULL_TENSION); } -// 0099f2c0 -void HomingLaser::trace_entities(uint32_t) +// 0099f2c0 Brain Worm: the path turns a right angle toward the nearest target it would pass beside (more than both +// sizes off its line, more than 80 along, in sight for a beam the grid stops), running from there out to the room's +// edge. A turn far from the eased path starts the path over. +void HomingLaser::trace_entities() { - reconstruction_missing("laser_sample_trace_entities 0099f2c0"); + Entity_Laser& laser = *static_cast(owner); + Vector direction = vector_normalized(vector_sub(endPoint, origin)); + float cosine = std::cos(PI_F / 2); + float sine = std::sin(PI_F / 2); + Vector across = vector_make(direction.x * cosine - direction.y * sine, direction.x * sine + direction.y * cosine); + float nearest = vector_distance(origin, endPoint); + float side = 1; + Entity* turnAt = nullptr; + Entity* spawner = laser.spawnerEntity; + bool isVersus = g_game->deathmatchManager.is_active(); + bool isSighted = laser.entityGridCollisionClass != GRIDCOLL_NONE && + laser.entityGridCollisionClass != GRIDCOLL_WALLS && !laser.tearFlags[TEAR_SPECTRAL]; + for (Entity* entity : g_game->room->entityList.updateEL) + { + bool isKind = (isVersus && entity->type == ENTITY_PLAYER) || + (entity->type >= ENTITY_FIRST_ENEMY && entity->type <= ENTITY_LAST_ENEMY); + bool isTarget = entity != spawner && isKind && entity->entityCollisionClass != ENTCOLL_NONE && + entity->entityCollisionClass != ENTCOLL_PLAYERONLY && !entity->isInvincible && + !entity->isDead && !entity->HasEntityFlags(FLAG_NO_TARGET | FLAG_FRIENDLY); + bool isRival = isVersus && entity->type == ENTITY_FAMILIAR && entity->variant == Entity_Familiar::PUNCHING_BAG && + !entity->IsDescendantOf(spawner); + if (!isTarget && !isRival) continue; + + Vector offset = vector_sub(entity->pos, origin); + float along = direction.y * offset.y + direction.x * offset.x; + float off = offset.y * across.y + offset.x * across.x; + bool isBeside = along > TRACE_MIN_ALONG && along < nearest && laser.size + entity->size < std::abs(off); + if (!isBeside) continue; + Vector foot = vector_add(vector_scale(direction, along), origin); + if (isSighted && !room_check_line(foot, entity->pos, LINE_MODE_PROJECTILE, 0)) continue; + + turnAt = entity; + nearest = along; + side = off <= 0 ? -1.0f : 1.0f; + } + if (!turnAt) return; + + Vector corner = vector_add(vector_scale(direction, nearest), origin); + Vector turn = vector_scale(across, side); + for (int i = 0; i < 2; i++) + if (bezier.size() > 1) bezier.pop_back(); + if (bezier.empty()) bezier.push_back({origin, origin, vector_add(vector_scale(direction, CURL_LEAD), origin)}); + bezier.push_back({vector_sub(corner, vector_scale(direction, TRACE_CORNER)), + vector_sub(corner, vector_scale(direction, TRACE_HANDLE_FAR)), + vector_sub(corner, vector_scale(direction, TRACE_HANDLE_NEAR))}); + bezier.push_back({vector_add(vector_scale(turn, TRACE_CORNER), corner), + vector_add(vector_scale(turn, TRACE_HANDLE_NEAR), corner), + vector_add(vector_scale(turn, TRACE_HANDLE_FAR), corner)}); + endPoint = laser.calc_end_point(corner, turn); + bezier.push_back({endPoint, vector_sub(endPoint, vector_scale(turn, CURL_LEAD)), endPoint}); + + if (!smoothedSamples.empty() && vector_distance(endPoint, smoothedSamples.back()) > TRACE_RESTART_DISTANCE) + { + samples.clear(); + smoothedSamples.clear(); + nonOptimizedSamples.clear(); + } } diff --git a/src/homing_laser.h b/src/homing_laser.h index 29bcd33..70dc4d1 100644 --- a/src/homing_laser.h +++ b/src/homing_laser.h @@ -27,6 +27,14 @@ enum BezierPathType : int BEZIER_PATH_WITH_PLAYERS = 5 }; +// My Reflection's loop: how far out it reaches, how wide it turns, and the most length its run back has (none for 0). +struct BoomerangLoop +{ + float length = 0; + float maxLength = 0; + float width = 0; +}; + // One point of a laser's path with the handles of the curves into and out of it (HomingLaser_Bezier). struct BezierPoint { @@ -66,11 +74,11 @@ struct HomingLaser void compute_bezier_handles(float tension); void apply_sine_offset(float amplitude, float phase); void build_curl_path(float radius); - void build_wiggle_bezier(); + void build_wiggle_bezier(const BoomerangLoop& loop); void truncate_samples_at_obstacle(const Vector& offset); void apply_sample_wiggle(float amplitude, float phase); void build_ring_bezier(const Vector& center, bool isHoming, Entity* ignored, float radius); - void trace_entities(uint32_t turnFlags); + void trace_entities(); }; // Where a point lands on a segment, as a fraction of it clamped to the segment, with its squared distance to there. diff --git a/src/hud.cpp b/src/hud.cpp index 7df09b8..6adbb3d 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -9,6 +9,7 @@ #include "manager.h" #include "minimap.h" #include "platform.h" +#include "procedural_item_manager.h" #include "render_passes.h" #include "room.h" #include "string_table.h" @@ -18,6 +19,8 @@ #include #include #include +#include +#include constexpr const char* MPLUS_FONT = "font/MPlus_12b.fnt"; constexpr const char* KOREAN_FONT = "font/KR_Font14.fnt"; @@ -44,7 +47,6 @@ constexpr const char* COOP_MENU_PNG = "gfx/ui/coop menu.png"; constexpr const char* MESSAGE_SURFACE = "HUD_Message Text Surface"; constexpr const char* FORTUNE_SURFACE = "Fortune Text Surface"; constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset"; -constexpr const char* COLOR_OFFSET_DOGMA_SHADER = "ColorOffsetDogma"; constexpr const char* ANIMATION_IDLE = "Idle"; constexpr const char* ANIMATION_MAIN = "Main"; @@ -83,7 +85,6 @@ constexpr float FORTUNE_SOUND_VOLUME = 0.5f; constexpr float FORTUNE_SLIDE_IN_PITCH = 1.5f; constexpr float STATS_ALPHA = 0.5f; -constexpr int COLOR_INDEX_NONE = 5; constexpr int STB_HOME = 35; constexpr int BOSS_GREAT_GIDEON = 83; constexpr uint32_t ROOM_FLAG_CLEAR = 1; @@ -92,6 +93,23 @@ constexpr int ONLINE_HUD_HIDDEN = 2; constexpr int TEXT_BUFFER_SIZE = 16; constexpr int UTF16_HIGH_HALF_SHIFT = 16; +// The recent items: icons full size two to a row or mini four to a row, half see-through, down to the screen's bottom +// (lower with the HUD offset), split in two columns with a grey line for a second player, each list a column apart. +// A trinket's icon key carries HISTORY_TRINKET_KEY, a golden one also the golden flag. +constexpr float HISTORY_ICON = 32; +constexpr float HISTORY_MINI_ICON = 16; +constexpr int HISTORY_COLUMNS = 2; +constexpr int HISTORY_MINI_COLUMNS = 4; +constexpr float HISTORY_BOTTOM_MARGIN = 64; +constexpr float HISTORY_BOTTOM_SHIFT = 14; +constexpr float HISTORY_SPLIT_SHIFT = 2; +constexpr float HISTORY_LIST_STEP = 33; +constexpr float HISTORY_ALPHA = 0.5f; +constexpr float HISTORY_ERROR_ALPHA = 128 / 255.0f; +constexpr uint32_t HISTORY_SPLIT_ARGB = 0x80808080; +constexpr int HISTORY_TRINKET_KEY = 0x80000; +constexpr int HISTORY_GOLDEN_KEY = HISTORY_TRINKET_KEY | TRINKET_GOLDEN_FLAG; + // The pickup counter rows, the run icons and the destination icon, as frames of hudpickups.anm2. enum PickupFrame : int { @@ -138,6 +156,38 @@ enum ChallengeEndStage : int END_STAGE_VOID = 12 }; +// The co-op menu sheet's character icons: their cell by player type, six 32 pixel cells to a row, drawn at half size +// (bigger in a versus match) over an outline. +constexpr std::array PLAYER_ICON_CELLS = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 8, 3, 11, + 12, 13, 14, 14, 15, 16, 16, 24, 25, 26, 27, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 32, 40, 38}; +constexpr int PLAYER_ICON_COLUMNS = 6; +constexpr float PLAYER_ICON_CELL = 32; +constexpr float PLAYER_ICON_SIZE = 16; +constexpr float PLAYER_ICON_OUTLINE = 2; +constexpr float VERSUS_ICON_SCALE = 1.8f; + +// The surfaces a glitched character's block is taken from, by the character's hash. +enum GlitchSurface +{ + GLITCH_HEARTS, + GLITCH_CHARGE_BAR, + GLITCH_PICKUPS, + GLITCH_CARDS_PILLS, + GLITCH_FLOOR, + GLITCH_WALLS, + GLITCH_STATS, + GLITCH_SCREEN, + GLITCH_SURFACE_COUNT +}; + +// A glitched character's block of its surface, which the blocks tile. +constexpr float GLITCH_BLOCK_WIDTH = 8; +constexpr float GLITCH_BLOCK_HEIGHT = 16; +constexpr int GLITCH_WIDTH_SHIFT = 3; +constexpr int GLITCH_HEIGHT_SHIFT = 4; +constexpr uint32_t GLITCH_BLOCK_MASK = 0xffff; + // A HUD position: its x and y. static Vector at_make(float x, float y) { @@ -186,8 +236,7 @@ static std::u16string utf16_from(std::string_view text) // A channel cut to the 8 bits of an ARGB color, as KColor's round trip through one cuts it. static float channel_quantize(float channel) { - constexpr float CHANNEL_MAX = 255; - return (float)(uint8_t)(uint32_t)(channel * CHANNEL_MAX) / CHANNEL_MAX; + return (float)(uint8_t)(uint32_t)(channel * COLOR_CHANNEL_MAX) / COLOR_CHANNEL_MAX; } // The text drawn the way the HUD draws text, white with default settings at its own size. @@ -347,10 +396,89 @@ void HUD_Message::Render(Vector at, float atScale) textImage->Render(KAGE::Graphics::color_quad_rect(corner, size, WHITE), WHITE); } -// 008413a0 Draws rich text, its icons from the HUD's sprites, centered at a point of the text surface. -void HUD_Message::render_text_image(Font&, std::u16string_view, Vector, KColor) +// How far a character moves the pen in a font, or 0 when the font lacks it or it moves nothing. +static int glyph_advance_get(Font& font, char16_t character) { - reconstruction_missing("HUD_Message::render_text_image 008413a0"); + int index = font.isLoaded ? font.get_glyph_index(character) : GLYPH_NONE; + return index == GLYPH_NONE ? 0 : font.glyphs[index].xAdvance; +} + +// The surface a glitched character takes its block from: a HUD sheet, the room's floor or walls, or the screen. +static KAGE::Graphics::ImagePtr glitch_surface_get(GlitchSurface surface) +{ + HUD& hud = g_game->hud; + auto sheet = [](ANM2& sprite) { LayerState* layer = sprite.GetLayer(0); return layer ? layer->spriteSheet : nullptr; }; + + switch (surface) + { + case GLITCH_HEARTS: return sheet(hud.heartsSprite); + case GLITCH_CHARGE_BAR: return sheet(hud.chargeBarSprite); + case GLITCH_PICKUPS: return sheet(hud.pickupHUDSprite); + case GLITCH_CARDS_PILLS: return sheet(hud.cardsPillsSprite); + case GLITCH_FLOOR: return g_game->room->backdrop.floorBuffer; + case GLITCH_WALLS: return g_game->room->backdrop.wallsBuffer; + case GLITCH_STATS: return sheet(hud.statsSprite); + default: return g_manager->colorCorrectionSurface; + } +} + +// Draws a glitched character: an 8 by 16 block of one of eight surfaces, the surface and the block both hashed from +// the character. Without color correction the screen's block is a white one. +// The original divides by zero on a surface too small for one block. This draws nothing then. +static void glitch_block_render(char16_t character, Vector at) +{ + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + uint32_t hash = (uint32_t)character + 1; + hash ^= hash >> 5; + GlitchSurface surface = (GlitchSurface)((hash >> 12 ^ hash) % GLITCH_SURFACE_COUNT); + int block = (int)((hash >> 8 ^ hash) & GLITCH_BLOCK_MASK); + KAGE::Graphics::ImagePtr image = glitch_surface_get(surface); + int columns = image ? (int)((unsigned int)image->width >> GLITCH_WIDTH_SHIFT) : 0; + int blocks = image ? (int)((unsigned int)image->height >> GLITCH_HEIGHT_SHIFT) * columns : 0; + if (blocks == 0) return; + + block %= blocks; + Vector size = vector_make(GLITCH_BLOCK_WIDTH, GLITCH_BLOCK_HEIGHT); + SourceQuad source = KAGE::Graphics::source_quad_rect( + vector_make((float)(block % columns) * size.x, (float)(block / columns) * size.y), size); + KAGE::Graphics::ColorQuad quad = KAGE::Graphics::color_quad_rect(at, size, WHITE); + bool isScreen = surface == GLITCH_SCREEN; + if (isScreen && !g_manager->optionsConfig.render.isColorCorrectionEnabled) return render_color_shader_pass(quad); + + bool isPushed = graphics.shader_push(isScreen ? COLOR_CORRECTION_SHADER : COLOR_OFFSET_SHADER); + if (isScreen) + { + float neutral = 1; + graphics.currentShader->set_uniform("Exposure", KAGE::Graphics::UNIFORM_FLOAT, &neutral); + graphics.currentShader->set_uniform("Gamma", KAGE::Graphics::UNIFORM_FLOAT, &neutral); + } + else apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, *image); + image->Render(source, quad, WHITE); + if (isPushed) graphics.shader_pop(); +} + +// 008413a0 Draws glitched text centered at a point of the text surface: each character the font has in it, each one +// it lacks as a block of a game surface. +// The original leaves the shaders it picks current. Here they are popped after each block. +void HUD_Message::render_text_image(Font& textFont, std::u16string_view line, Vector at, KColor textColor) +{ + unsigned int width = 0; + for (char16_t character : line) + { + int advance = glyph_advance_get(textFont, character); + width += advance ? advance : (int)GLITCH_BLOCK_WIDTH; + } + + float x = at.x - (float)(width >> 1); + for (char16_t character : line) + { + int advance = glyph_advance_get(textFont, character); + FontSettings settings; + if (advance) textFont.DrawString(std::u16string_view(&character, 1), vector_make(x, at.y), vector_make(1, 1), + textColor, settings); + else glitch_block_render(character, vector_make(x, at.y)); + x += advance ? (float)advance : GLITCH_BLOCK_WIDTH; + } } // 0083abb0 Forgets both players' recent items. @@ -360,22 +488,171 @@ void HistoryHUD::clear() isComputed = false; } -// 0083ac20 Draws the recent items at a position, full size or mini. -void HistoryHUD::Render(Vector, bool) +// 0083ac20 Draws the recent items from a position down to the bottom of the screen, half see-through, in rows of two +// (four mini), one column each (two mini) with a line between when a second player has a list. Dogma and golden +// trinkets shimmer, the error trinket shows red, Modeling Clay its copied item in clay, Monkey Paw its fingers left and +// a glitched item its own icon. +// The original leaves the shaders it picks current. Here they are popped after each icon. +void HistoryHUD::Render(Vector at, bool isMini) { - reconstruction_missing("HistoryHUD::Render 0083ac20"); + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + float iconSize = isMini ? HISTORY_MINI_ICON : HISTORY_ICON; + int columns = isMini ? HISTORY_MINI_COLUMNS : HISTORY_COLUMNS; + float rowsShown = std::ceil(((1 - g_manager->optionsConfig.hudOffset) * HISTORY_BOTTOM_SHIFT + + (g_screenHeight - HISTORY_BOTTOM_MARGIN) - at.y) / iconSize); + float bottom = rowsShown * iconSize + at.y; + if (at.y >= bottom) return; + + if (players[1].player) + { + at.x -= HISTORY_SPLIT_SHIFT; + columns /= 2; + auto rows_get = [&](const HistoryHUDPlayer& slot) { return ((int)slot.items.size() + columns - 1) / columns; }; + int rows = std::min(std::max(rows_get(players[0]), rows_get(players[1])), (int)rowsShown); + if (rows > 0) + render_color_shader_pass(KAGE::Graphics::color_quad_rect( + vector_make(at.x + HISTORY_ICON, at.y), vector_make(1, (float)rows * iconSize), + kcolor_argb(HISTORY_SPLIT_ARGB))); + } + + for (HistoryHUDPlayer& slot : players) + { + if (!slot.player) break; + + for (int i = 0; i < (int)slot.items.size(); i++) + { + HistoryHUDItem& icon = slot.items[i]; + Vector position = vector_make((float)(i % columns) * iconSize + at.x, (float)(i / columns) * iconSize + at.y); + if (position.y >= bottom) break; + + bool isGolden = icon.key > 0 && (icon.key & HISTORY_GOLDEN_KEY) == HISTORY_GOLDEN_KEY; + ColorMod color = COLOR_DEFAULT; + KColor tint = kcolor_rgba(1, 1, 1, HISTORY_ALPHA); + int pushed = graphics.shader_push(COLOR_OFFSET_SHADER) ? 1 : 0; + if (icon.key == COLLECTIBLE_DOGMA || isGolden) + { + if (graphics.shader_push(isGolden ? COLOR_OFFSET_GOLD_SHADER : COLOR_OFFSET_DOGMA_SHADER)) pushed++; + color._colorize[3] = (float)(g_manager->framecount / 2 % GOLD_SHIMMER_STEPS) / GOLD_SHIMMER_STEPS; + } + bool isMonkeyPaw = icon.isTrinket && icon.historyId == TRINKET_MONKEY_PAW; + float frameX = isMonkeyPaw ? (float)(MONKEY_PAW_FRAMES - slot.player->monkeyPawCounter) * TRINKET_SIZE : 0; + SourceQuad source = KAGE::Graphics::source_quad_rect(vector_make(frameX, 0), vector_make(TRINKET_SIZE, TRINKET_SIZE)); + Vector shake = g_game->screenShakeOffset; + KAGE::Graphics::ColorQuad quad = + KAGE::Graphics::color_quad_rect(vector_add(position, shake), vector_make(iconSize, iconSize), WHITE); + + if (!icon.image && icon.key < 0) + { + ProceduralItemManager& glitched = g_game->proceduralItemManager; + apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *glitched.renderTarget); + glitched.render_item(icon.key, source, quad, tint); + } + else if (icon.image) + { + int trinket = icon.isTrinket ? icon.historyId & TRINKET_ID_MASK : 0; + if (trinket == TRINKET_ERROR) + tint = kcolor_rgba(ERROR_TRINKET_TINT[0], ERROR_TRINKET_TINT[1], ERROR_TRINKET_TINT[2], HISTORY_ERROR_ALPHA); + else if (trinket == TRINKET_MODELING_CLAY) + for (int c = 0; c < 4; c++) color._colorize[c] = CLAY_COLORIZE[c]; + apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *icon.image); + icon.image->Render(source, quad, tint); + } + for (; pushed > 0; pushed--) graphics.shader_pop(); + } + at.x += HISTORY_LIST_STEP; + } } -// 0083b280 Recomputes one player's recent items. -void HistoryHUD::Recompute(int, bool) +// 0083bbc0 The slot showing a player, given the first free one when it has none. A baby, a player with a parent and the +// Forgotten's soul (Tainted) have none, nor would an online player of another machine. +int HistoryHUD::player_slot_get(Entity_Player* player) { - reconstruction_missing("HistoryHUD::Recompute 0083b280"); + int freeSlot = -1; + if (player->variant != PLAYER_VARIANT_PLAYER || player->parent || player->playerType == PLAYER_THESOUL_B) return -1; + + for (int i = 0; i < HISTORY_PLAYER_COUNT; i++) + { + if (players[i].player == player) return i; + if (!players[i].player && freeSlot < 0) freeSlot = i; + } + if (freeSlot >= 0) players[freeSlot].player = player; + return freeSlot; } -// 0083b850 Recomputes both players' recent items. -void HistoryHUD::RecomputeAll(bool) +// 0083b280 Marks a player's recent items for a rebuild, or rebuilds them: each item of the player's history, newest +// first, but actives. The error trinket shows the trinket it passes for and Modeling Clay its copied item. Icons are +// kept by key across the rebuild, each reused once, and loaded otherwise. A glitched item has no icon of its own. +void HistoryHUD::Recompute(int playerIndex, HistoryRebuild rebuild) { - reconstruction_missing("HistoryHUD::RecomputeAll 0083b850"); + if (playerIndex < 0 || playerIndex >= HISTORY_PLAYER_COUNT || !players[playerIndex].player) return; + + HistoryHUDPlayer& slot = players[playerIndex]; + if (rebuild == HISTORY_KEEP_ICONS) + { + slot.isDirty = true; + return; + } + + std::map kept; + ItemConfig& items = g_manager->itemConfig; + for (HistoryHUDItem& icon : slot.items) + if (icon.image) kept.emplace(icon.key, icon.image); + slot.items.clear(); + + for (const HistoryItem& entry : std::views::reverse(slot.player->history.historyItems)) + { + HistoryHUDItem icon{nullptr, entry.id, entry.id, entry.isTrinket}; + int trinket = entry.isTrinket ? entry.id : 0; + if ((trinket & TRINKET_ID_MASK) == TRINKET_ERROR) + trinket = error_trinket_disguise_get() | (entry.id & TRINKET_GOLDEN_FLAG); + else if ((trinket & TRINKET_ID_MASK) == TRINKET_MODELING_CLAY && slot.player->modelingClayEffect) + { + icon.key = slot.player->modelingClayEffect; + trinket = 0; + } + if (trinket) icon.key = trinket | HISTORY_TRINKET_KEY; + + ItemConfig_Item* config = trinket ? items.GetTrinket(trinket) : items.GetCollectible(icon.key); + if (!config || config->type == ITEM_ACTIVE) continue; + if (config->id < 0) + { + icon.key = config->id; + slot.items.push_back(icon); + continue; + } + + auto found = kept.find(icon.key); + if (found != kept.end()) + { + icon.image = found->second; + kept.erase(found); + } + else icon.image = Manager::LoadImage(config->gfxFilename); + if (icon.image) slot.items.push_back(icon); + } + slot.isDirty = false; +} + +// 0083b850 Drops the players whose slot no longer shows them, moving the next one up, then has each player's recent +// items rebuilt or marked for it. Tainted Lazarus's other form is marked too when it has a slot. +void HistoryHUD::RecomputeAll(HistoryRebuild rebuild) +{ + for (int i = HISTORY_PLAYER_COUNT - 1; i >= 0; i--) + { + if (!players[i].player || player_slot_get(players[i].player) >= 0) continue; + + players[i].player = nullptr; + std::rotate(players.begin() + i, players.begin() + i + 1, players.end()); + } + + for (Entity_Player* player : g_game->playerManager.playerList) + { + Recompute(player_slot_get(player), rebuild); + Entity_Player* other = player->backupPlayer; + bool isLazarus = player->playerType == PLAYER_LAZARUS_B || player->playerType == PLAYER_LAZARUS2_B; + int otherSlot = other && isLazarus ? player_slot_get(other) : -1; + if (otherSlot >= 0 && players[otherSlot].player) players[otherSlot].isDirty = true; + } } // 009a1970 Loads the graphics again, empties the HUD and loads the item info panel. @@ -541,10 +818,10 @@ void HUD::PostUpdate() if (!historyHUD.isComputed) { historyHUD.isComputed = true; - historyHUD.RecomputeAll(false); + historyHUD.RecomputeAll(HISTORY_KEEP_ICONS); } for (int i = 0; i < HISTORY_PLAYER_COUNT; i++) - if (historyHUD.players[i].isDirty) historyHUD.Recompute(i, true); + if (historyHUD.players[i].isDirty) historyHUD.Recompute(i, HISTORY_REBUILD_ICONS); } statHUD.Update(); } @@ -609,7 +886,7 @@ void HUD::mark_all_slots_dirty(HistoryRebuild rebuild, HistoryClear clearing) return; } if (clearing == HISTORY_CLEAR_ITEMS) historyHUD.clear(); - historyHUD.RecomputeAll(rebuild == HISTORY_REBUILD_ICONS); + historyHUD.RecomputeAll(rebuild); } // 004aaee0 Shows or hides the HUD. @@ -630,10 +907,15 @@ void HUD::ShowItemText(Entity_Player* player, ItemConfig_Item* item) item_text_show(*this, player, item); } -// 0085e750 Lua's HUD:ShowItemText, for a player and item or a title and description. -int HUD::lua_show_item_text(void*) +// 009a3560 Hides every stacked banner. +void HUD::messages_hide() { - reconstruction_missing("HUD::ShowItemText 0085e750 (Lua's HUD:ShowItemText)"); + for (HUD_Message& message : messageStack) + { + if (!message.isShowing) continue; + message.free_text_buffers(); + message.isShowing = false; + } } // 009a3410 Shows a pill's name, online on its player's banner, else on the first free stacked banner (none when all @@ -1155,7 +1437,7 @@ void HUD::render_streak_texts() at.x += i == 0 || i == 2 ? SHIFT_LEFT_CORNER : SHIFT_RIGHT_CORNER; PlayerManager& players = g_game->playerManager; - int colorIndex = COLOR_INDEX_NONE; + int colorIndex = PLAYER_COLOR_NONE; for (int j = 0; j < COOP_SLOT_COUNT; j++) if (players.colorControllers[j] == player->controllerIndex) { @@ -1410,10 +1692,46 @@ void HUD::render_boss_health_bar(Vector barPos) if (isShaderPushed) graphics.shader_pop(); } -// 008f8ee0 Draws a modded character's co-op portrait. -void HUD::render_modded_coop_portrait(int, Vector, Vector, const ColorMod&) +// 009a6660 Draws a character's icon of the co-op menu sheet (other characters show Isaac's) over an outline 2 pixels +// wider all round, both bigger in a versus match. Co-op players off screen and the online player list show these. +void HUD::render_player_type_icon(const PlayerTypeIcon& icon) { - reconstruction_missing("HUD::render_modded_coop_portrait 008f8ee0"); + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + int cell = icon.playerType >= 0 && icon.playerType < (int)PLAYER_ICON_CELLS.size() ? PLAYER_ICON_CELLS[icon.playerType] : 0; + float size = icon.scale * (g_game->deathmatchManager.is_active() ? VERSUS_ICON_SCALE : 1) * PLAYER_ICON_SIZE; + Vector half = vector_make(size * 0.5f, size * 0.5f); + SourceQuad source = KAGE::Graphics::source_quad_rect( + vector_make((float)(cell % PLAYER_ICON_COLUMNS) * PLAYER_ICON_CELL, (float)(cell / PLAYER_ICON_COLUMNS) * PLAYER_ICON_CELL), + vector_make(PLAYER_ICON_CELL, PLAYER_ICON_CELL)); + KAGE::Graphics::ImageBase& sheet = *coopMenuImage; + + if (sheet.minFilter != icon.filter || sheet.magFilter != icon.filter) sheet.filter_set(icon.filter, icon.filter); + bool isPushed = graphics.shader_push(COLOR_OFFSET_SHADER); + + Vector outline = vector_make(PLAYER_ICON_OUTLINE, PLAYER_ICON_OUTLINE); + Vector outlineSize = vector_make(size + 2 * PLAYER_ICON_OUTLINE, size + 2 * PLAYER_ICON_OUTLINE); + apply_sprite_shader_params(icon.color, SPRITE_SHADER_COLOR_APPLY, sheet); + sheet.Render(source, KAGE::Graphics::color_quad_rect(vector_sub(vector_sub(icon.position, half), outline), outlineSize, WHITE), + kcolor_rgba(icon.color._tint[0], icon.color._tint[1], icon.color._tint[2], icon.color._tint[3])); + + apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, sheet); + sheet.Render(source, KAGE::Graphics::color_quad_rect(vector_sub(icon.position, half), vector_make(size, size), WHITE), + kcolor_rgba(1, 1, 1, icon.alpha)); + if (isPushed) graphics.shader_pop(); +} + +// 008f8ee0 Draws a modded character's co-op portrait at a position, size and color, its sprite playing the animation +// named for the character, when its mod gives it one. +void HUD::render_modded_coop_portrait(int playerType, Vector at, Vector portraitScale, const ColorMod& color) +{ + EntityConfig_Player* config = g_manager->entityConfig.GetPlayer(playerType); + ANM2* portrait = config ? config->moddedSprites[PLAYER_SPRITE_COOP_MENU] : nullptr; + if (!portrait) return; + + portrait->Play(config->GetDisplayName()); + portrait->scale = portraitScale; + portrait->color = color; + portrait->Render({.position = at}); } // 009a8230 Places the HUD by the HUD offset option: the four screen corners, each player corner (negative from the diff --git a/src/hud.h b/src/hud.h index c66620c..f8d20c1 100644 --- a/src/hud.h +++ b/src/hud.h @@ -75,11 +75,14 @@ struct HUD_Message static void render_text_image(Font& textFont, std::u16string_view line, Vector at, KColor textColor); }; -// An item of the recent items list, with its icon. +// An item of the recent items list: its icon, the key the icon is kept by between rebuilds (a collectible id, a trinket +// id with HISTORY_TRINKET_KEY, or a glitched item's negative id), and the history entry's item. struct HistoryHUDItem { KAGE::Graphics::ImagePtr image; - int id = 0; + int historyId = 0; + int key = 0; + bool isTrinket = false; }; // The recent items of one player and whether they need recomputing. @@ -90,7 +93,7 @@ struct HistoryHUDPlayer bool isDirty = false; }; -// The recent items HUD (REPENTOGON's HistoryHUD) under the minimap, for up to two players. +// The recent items HUD (REPENTOGON's HistoryHUD) under the minimap, for up to two players, newest first. struct HistoryHUD { std::array players{}; @@ -98,10 +101,22 @@ struct HistoryHUD void clear(); void Render(Vector at, bool isMini); - void Recompute(int playerIndex, bool isImmediate); - void RecomputeAll(bool isImmediate); + void Recompute(int playerIndex, HistoryRebuild rebuild); + void RecomputeAll(HistoryRebuild rebuild); + int player_slot_get(Entity_Player* player); }; +// A character's icon of the co-op menu sheet, centered on a position at a scale, outlined in a color's tint (the color +// shading the outline), faded and filtered. +struct PlayerTypeIcon +{ + ColorMod color = COLOR_DEFAULT; + Vector position{}; + TextureFilter filter = FILTER_LINEAR; + float alpha = 1; + float scale = 1; + int playerType = 0; +}; // The online HUD style option in effect, ONLINE_HUD_OFFLINE offline. int online_hud_mode(); @@ -175,7 +190,7 @@ public: void ShowItemText(Entity_Player* player, ItemConfig_Item* item); void ShowStackedItemTextCustom(const char* title, const char* subtitle); - static int lua_show_item_text(void* luaState); + void messages_hide(); void show_pill_name(Entity_Player* player, const char* title, const char* subtitle); void ShowFortuneText(const std::vector& lines); void show_fortune_line(const char* text); @@ -190,6 +205,7 @@ public: void render_player_hud(int playerHudIndex, PlayerHudLayout layout); void render_player_net_status(int playerHudIndex, Vector at); void render_boss_health_bar(Vector barPos); + void render_player_type_icon(const PlayerTypeIcon& icon); static void render_modded_coop_portrait(int playerType, Vector at, Vector portraitScale, const ColorMod& color); void update_hud_offset(); diff --git a/src/info_display.cpp b/src/info_display.cpp index defb783..43e7f7f 100644 --- a/src/info_display.cpp +++ b/src/info_display.cpp @@ -8,7 +8,6 @@ #include #include -constexpr std::string_view DOCUMENT_TAG = "#document"; constexpr int RED_HEARTS_ALL = 24; // The ids load_xml lists from the item config before reading info_display.xml. diff --git a/src/item_config.cpp b/src/item_config.cpp index f9ffff1..acc2e63 100644 --- a/src/item_config.cpp +++ b/src/item_config.cpp @@ -12,10 +12,8 @@ #include constexpr int LOG_LINE_SIZE = 1024; -constexpr std::string_view DOCUMENT_TAG = "#document"; constexpr std::string_view ITEMS_VERSION = "1"; constexpr char WORD_SEPARATOR = ' '; -constexpr char LOCALIZED_KEY_PREFIX = '#'; constexpr std::string_view ITEMS_CATEGORY = "Items"; constexpr std::string_view POCKET_ITEMS_CATEGORY = "PocketItems"; constexpr const char* COLLECTIBLE_OUT_OF_BOUNDS = "Collectible ID out of bounds.\n"; @@ -35,7 +33,6 @@ constexpr int EXTRA_WISP_ID_BASE = 0x10000; // Trinket ids carry the golden flag above this mask. constexpr int TEAR_FLAG_COUNT = 128; constexpr int LOCUST_FLAG_MASK = 31; -constexpr float COLOR_CHANNEL_MAX = 255; // The most charges a special charge shows as segments. constexpr int SPECIAL_CHARGE_SEGMENTS_LAST = 12; @@ -347,7 +344,7 @@ static std::string localized_get(std::string_view category, std::string_view tex StringTable& table = g_manager->stringTable; bool isMissing = false; - if (text.empty() || text[0] != LOCALIZED_KEY_PREFIX) return std::string(text); + if (text.empty() || text[0] != STRING_KEY_PREFIX) return std::string(text); if (language == LANGUAGE_CURRENT) language = table.language; std::string_view localized = table.get_string(category, language, text.substr(1), &isMissing); return std::string(isMissing ? text : localized); diff --git a/src/item_info_hud.cpp b/src/item_info_hud.cpp index 84d5962..99e0180 100644 --- a/src/item_info_hud.cpp +++ b/src/item_info_hud.cpp @@ -5,6 +5,8 @@ #include "manager.h" #include "persistent_game_data.h" #include "room.h" +#include +#include constexpr const char* ITEM_INFO_FONT = "font/TeamMeatEx/TeamMeatEx12.fnt"; constexpr const char* CHARGE_ICONS_ANM2 = "gfx/ui/ui_charge_icons.anm2"; @@ -13,6 +15,16 @@ constexpr const char* ANIMATION_CHARGE_ICON = "ChargeIcon"; constexpr float ITEM_INFO_LINE_SPACING = 0.9f; constexpr float ITEM_INFO_ICON_SCALE = 4; +// The charge icon's frames: one per bar size, in CHARGE_BARS order, then the timed, the special and no bar. Blank Card, +// Clear Rune, Placebo, D Infinity and Notched Axe show no bar. +constexpr std::array CHARGE_BARS = {1, 2, 3, 4, 6, 12}; +constexpr int CHARGE_FRAME_FOUR = 3; +constexpr int CHARGE_FRAME_TIMED = 6; +constexpr int CHARGE_FRAME_SPECIAL = 7; +constexpr int CHARGE_FRAME_NONE = 8; +constexpr std::array CHARGE_NONE_ITEMS = {COLLECTIBLE_BLANK_CARD, COLLECTIBLE_CLEAR_RUNE, COLLECTIBLE_PLACEBO, + COLLECTIBLE_D_INFINITY, COLLECTIBLE_NOTCHED_AXE}; + // 0083c5f0 Loads the panel's font (without redirection), charge icon and map icons. void ItemInfoHUD::load_graphics() { @@ -54,3 +66,23 @@ void ItemInfoHUD::Update() if (pickup && popupId == POPUP_NONE) reconstruction_missing("ItemInfoHUD::Update 0083c8d0: the description's popup"); } + +// 00840030 Shows on the charge icon how an active charges: its bar of 1, 2, 3, 4, 6 or 12, a timed bar, a special one +// (any other count, or a special charge), or none for the cards and runes it stands in for. Tainted Lazarus's Flip +// shows a bar of 4. Anything not an active leaves the icon as it was. +void ItemInfoHUD::set_active_charge_frame(int collectibleId, const Entity_Player& player) +{ + bool isLazarusFlip = collectibleId == COLLECTIBLE_FLIP && + (player.playerType == PLAYER_LAZARUS_B || player.playerType == PLAYER_LAZARUS2_B); + if (isLazarusFlip) return chargeIconSprite.SetFrame((float)CHARGE_FRAME_FOUR); + bool isBarless = std::ranges::find(CHARGE_NONE_ITEMS, collectibleId) != CHARGE_NONE_ITEMS.end(); + if (isBarless) return chargeIconSprite.SetFrame((float)CHARGE_FRAME_NONE); + + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); + if (!item || item->type != ITEM_ACTIVE) return; + + int frame = item->chargeType == CHARGE_TIMED ? CHARGE_FRAME_TIMED : CHARGE_FRAME_SPECIAL; + auto bar = std::ranges::find(CHARGE_BARS, item->maxCharges); + if (item->chargeType == CHARGE_NORMAL && bar != CHARGE_BARS.end()) frame = (int)(bar - CHARGE_BARS.begin()); + chargeIconSprite.SetFrame((float)frame); +} diff --git a/src/item_info_hud.h b/src/item_info_hud.h index 7d23c78..78b03f2 100644 --- a/src/item_info_hud.h +++ b/src/item_info_hud.h @@ -26,4 +26,5 @@ struct ItemInfoHUD void load_graphics(); void reset(); void Update(); + void set_active_charge_frame(int collectibleId, const Entity_Player& player); }; diff --git a/src/item_overlay.cpp b/src/item_overlay.cpp index b0aaa1d..1811c53 100644 --- a/src/item_overlay.cpp +++ b/src/item_overlay.cpp @@ -9,7 +9,6 @@ #include "room.h" #include -constexpr int SOUND_STATIC = 81; constexpr int SLEEP_SOUL_HEARTS = 6; constexpr int EVENT_COUNTER_SLEEPS = 202; constexpr const char* EVENT_SOUND = "Sound"; diff --git a/src/item_pickup.cpp b/src/item_pickup.cpp index 1bd53b2..c327587 100644 --- a/src/item_pickup.cpp +++ b/src/item_pickup.cpp @@ -85,8 +85,6 @@ constexpr int ONE_UP_FRAME_DELAY = 30; constexpr float ITEM_SOUND_HALF_VOLUME = 0.5f; constexpr int COLLECTIBLE_SUPER_BANDAGE = 92; -// 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"; static bool is_anyone_owning(int collectible) { diff --git a/src/item_pool.cpp b/src/item_pool.cpp index a4617b1..213587a 100644 --- a/src/item_pool.cpp +++ b/src/item_pool.cpp @@ -50,7 +50,6 @@ constexpr std::array GREED_ROOM_POOLS = [] { }(); constexpr uint32_t POOL_SHIFT = 35; -constexpr uint32_t ITEM_POOL_SHIFT = 3; constexpr uint32_t CHAOS_SHIFT = 22; constexpr uint32_t DRAW_SHIFT = 4; constexpr uint32_t DAILY_SHIFT = 2; diff --git a/src/item_pool.h b/src/item_pool.h index 4295457..a218b4c 100644 --- a/src/item_pool.h +++ b/src/item_pool.h @@ -9,6 +9,7 @@ #include constexpr int PILL_COLOR_SLOTS = 15; +constexpr uint32_t ITEM_POOL_SHIFT = 3; // The odds GetCardEx's callers draw a special card and a rune with. constexpr int CARD_SPECIAL_CHANCE = 25; constexpr int CARD_RUNE_CHANCE = 10; diff --git a/src/kage_graphics.cpp b/src/kage_graphics.cpp index 44df651..399a758 100644 --- a/src/kage_graphics.cpp +++ b/src/kage_graphics.cpp @@ -27,7 +27,6 @@ constexpr int RGBA_HEADER_SIZE = 4; constexpr int QUAD_INDICES = 6; constexpr int QUAD_INDEX_ORDER[QUAD_INDICES] = {0, 2, 1, 1, 2, 3}; constexpr int MESSAGE_LENGTH = 1024; -constexpr float CHANNEL_MAX = 255; constexpr double SRGB_GAMMA = 2.2; // The color draw calls take to mean "the quad's own colors". constexpr float COLOR_UNSET = -1; @@ -1219,7 +1218,7 @@ ImagePtr Manager::render_target_create(const RenderTargetDesc& desc) target->format = IMAGE_RGBA; if (target->set_size(desc.width, desc.height)) { - uint8_t red = (uint8_t)(unsigned int)(color._red * CHANNEL_MAX); + uint8_t red = (uint8_t)(unsigned int)(color._red * COLOR_CHANNEL_MAX); std::vector texels((size_t)target->textureWidth * target->textureHeight * COLOR_CHANNELS, red); target->texels_load(texels); } diff --git a/src/kage_graphics.h b/src/kage_graphics.h index dad2a50..4f3a74c 100644 --- a/src/kage_graphics.h +++ b/src/kage_graphics.h @@ -23,6 +23,9 @@ enum TextureWrap : int WRAP_CLAMP }; +// A color channel at full, in bytes. +constexpr float COLOR_CHANNEL_MAX = 255; + namespace KAGE::Graphics { class ImageBase; diff --git a/src/leaderboard.cpp b/src/leaderboard.cpp index 86163ce..4b80a36 100644 --- a/src/leaderboard.cpp +++ b/src/leaderboard.cpp @@ -18,7 +18,6 @@ constexpr const char* ANIMATION_BOARD_DISAPPEAR = "Dissappear"; 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 float DIM_SHADE = 0.3f; constexpr float DIM_ALPHA = 0.5f; diff --git a/src/level.cpp b/src/level.cpp index c286f6d..9af8cba 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -1,4 +1,5 @@ #include "level.h" +#include "boss_final.h" #include "boss_pool.h" #include "entity_effect.h" #include "entity_familiar.h" @@ -409,6 +410,41 @@ void Level::myosotis_pickups_collect() } } +// Part of 00744940: the Ascent's voiceover a second in, stopping any other line first (the timer's state holds it). +static void ascent_voiceover_play(Entity_Effect* timer) +{ + SFXManager& sfx = g_manager->sfxManager; + for (int line : {SOUND_MOM_AND_DAD_1, SOUND_MOM_AND_DAD_2, SOUND_MOM_AND_DAD_3, SOUND_MOM_AND_DAD_4}) sfx.Stop(line); + sfx.Play(timer->state, {.volume = 1, .frameDelay = 0, .pitch = 1}); +} + +// Part of 00744940: the line Mom and Dad speak on the Ascent's first floor of each chapter, the last first. +static void ascent_voiceover_start(uint32_t voiceStage) +{ + constexpr int ASCENT_VOICEOVER_DELAY = 60; + int line; + switch (voiceStage) + { + case STAGE_BASEMENT_I: + line = SOUND_MOM_AND_DAD_4; + break; + case STAGE_CAVES_I: + line = SOUND_MOM_AND_DAD_3; + break; + case STAGE_DEPTHS_I: + line = SOUND_MOM_AND_DAD_2; + break; + case STAGE_WOMB_I: + line = SOUND_MOM_AND_DAD_1; + break; + default: + return; + } + Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(&ascent_voiceover_play), ASCENT_VOICEOVER_DELAY, 0, false); + timer->state = line; + timer->Update(); +} + // 00744940 Lays out the floor: seeds its RNGs from the stage seed, rolls its curse, loads the stage's rooms, generates // the layout the floor calls for, then enters the start room (or the boss room on the Ascent) and starts the floor. void Level::Init(bool isResetLilPortalRoom) @@ -594,11 +630,10 @@ void Level::Init(bool isResetLilPortalRoom) if (!game.playerManager.FirstCollectibleOwner(keyPiece, LAZARUS_SHARE_CHECK)) reconstruction_missing("Level::Init 00744940: a Mega Satan challenge's Key Pieces (AddCollectible)"); - uint32_t voiceStage = effectiveStage + ((GetCurses() & CURSE_OF_LABYRINTH) && effectiveStage % 2 == 0 ? 1 : 0); - - if (IsAscent() && g_manager->optionsConfig.isAscentVoiceover && voiceStage % 2 == 1 && - voiceStage <= STAGE_WOMB_I) - reconstruction_missing("Level::Init 00744940: the Ascent's voiceover timer (Entity_Effect::CreateTimer)"); + uint32_t voiceStage = effectiveStage; + if ((GetCurses() & CURSE_OF_LABYRINTH) && (voiceStage == STAGE_BASEMENT_II || voiceStage == STAGE_CAVES_II)) + voiceStage++; + if (IsAscent() && g_manager->optionsConfig.isAscentVoiceover) ascent_voiceover_start(voiceStage); game.playerManager.trigger_level_start(); game.itemPool.unkFloat674 = game.itemPool.unkFloat678; @@ -2626,8 +2661,10 @@ void Level::load_room() if (isHomePathBoss && GetRoomByIdx(currentRoomIdx)->listIndex == lastBossRoomListIdx && (room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR)) - reconstruction_missing("Level::load_room 0073e0a0: the Home path's Boss Rush door (Room::update_door_targets " - "00802670, TrySpawnBossRushDoor 007f9960)"); + { + room->update_door_targets(); + room->TrySpawnBossRushDoor(false, false); + } EntityList_EL& updated = room->entityList.updateEL; @@ -2837,7 +2874,6 @@ constexpr std::array HOME_ROOMS = {{ {{7, 7}, ROOMSHAPE_IH, {7, 7}, DIRECTION_RIGHT, ROOMSHAPE_IH, 10}, }}; constexpr size_t HOME_LAST_BOSS_ROOM = 2; -constexpr int BEAST_ROOM_VARIANT = 666; // 0074de30 Lays out Home by hand from its own rooms, Mom's bedroom counted the last boss room. Off the map, the error // room, black market and crawl space from the generation RNG, and the Beast's crawl space as the secret exit. diff --git a/src/level.h b/src/level.h index f8bf78e..474e455 100644 --- a/src/level.h +++ b/src/level.h @@ -30,6 +30,9 @@ constexpr RNG LEVEL_RNG_DEFAULT = {RNG_SEED_DEFAULT, 5, 9, 7}; constexpr int DIMENSION_MIRROR = 1; constexpr int DIMENSION_DEATH_CERTIFICATE = 2; +// The frames the Death Certificate's floor shakes after its item is taken, before the way back. +constexpr int DEATH_CERTIFICATE_EXIT_FRAMES = 90; + // 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; @@ -69,6 +72,10 @@ enum OffMapRoom : int ROOM_LIL_PORTAL_IDX = -20 }; +// The grid room indices a dungeon's return room is held between (Level::SetDungeonReturnRoomIndex 0057be90). +constexpr int DUNGEON_RETURN_INDEX_MIN = -20; +constexpr int DUNGEON_RETURN_INDEX_MAX = 168; + // The floor's own state flags (Lua's LevelStateFlag) the curated code reads, by bit. enum LevelStateFlag : int { @@ -207,6 +214,17 @@ struct VentricleRazorPortal bool isMarked = false; }; +// Where the players left for the Death Certificate's floor, to go back there: the room and the one before it, their +// dimensions and the door left by. +struct DimensionReturn +{ + int lastRoomIdx = 0; + int leaveDoor = -1; + int roomIdx = 0; + int8_t dimension = 0; + int8_t lastRoomDimension = 0; +}; + // The floor (Rebirth's Level, the front of Game, which Game::GetLevel hands out): its stage, curses and room // descriptors, the 13x13 maps of its three dimensions, the room the players are in, and the RNGs a floor is laid out // and its deals drawn with. Init lays a floor out from the run's stage seed. @@ -221,6 +239,7 @@ public: std::array greedWaveSeeds{}; std::array ventricleRazorPortals{}; std::vector myosotisPickups; + DimensionReturn deathCertificateReturn; std::unique_ptr room; int* currentRoomMap = nullptr; RNG devilAngelRoomRNG = LEVEL_RNG_DEFAULT; diff --git a/src/lua_api_entities.cpp b/src/lua_api_entities.cpp index 5053f41..a46bdfc 100644 --- a/src/lua_api_entities.cpp +++ b/src/lua_api_entities.cpp @@ -269,7 +269,7 @@ static void npc_pickup_register(lua_State* state) [](Entity_NPC& npc, Vector velocity) { return npc.CanBeDamagedFromVelocity(velocity); }); lua_method(state, "CanReroll", [](Entity_NPC& npc) { return npc.CanReroll(); }); lua_method(state, "QueryNPCsType", - [](Entity_NPC&, int type, int variant) { return entity_list_make(entity_query(type, variant)); }); + [](Entity_NPC&, int type, int variant) { return entity_list_make(Entity_NPC::QueryNPCsType(type, variant)); }); lua_method(state, "QueryNPCsSpawnerType", [](Entity_NPC&, int spawnerType, int type, bool isEnemiesOnly) { SpawnerQueryMode mode = isEnemiesOnly ? SPAWNER_QUERY_ENEMIES : SPAWNER_QUERY_ALL; return entity_list_make(npc_query_spawner_type(spawnerType, type, mode)); diff --git a/src/lua_api_entity_player.cpp b/src/lua_api_entity_player.cpp index 6bd31d2..4629f65 100644 --- a/src/lua_api_entity_player.cpp +++ b/src/lua_api_entity_player.cpp @@ -396,10 +396,7 @@ static void player_state_register(lua_State* state) lua_method(state, "GetTractorBeam", [](Entity_Player& player) -> Entity* { return player.tractorBeam; }); lua_method(state, "GetLastActionTriggers", [](Entity_Player& player) { return player.lastActionTriggers; }); lua_field<&Entity_Player::blinkTime>(state, "HeadFrameDelay"); - lua_method(state, "GetNPCTarget", [](Entity_Player&) -> Entity* { - reconstruction_missing("Entity_Player::GetNPCTarget 00770610"); - return nullptr; - }); + lua_method(state, "GetNPCTarget", [](Entity_Player& player) { return player.GetNPCTarget(); }); lua_method(state, "HasCurseMistEffect", [](Entity_Player& player) { return player.hasCurseMistEffect; }); lua_method(state, "AddCurseMistEffect", [](Entity_Player& player) { player.AddCurseMistEffect(); }); lua_method(state, "RemoveCurseMistEffect", [](Entity_Player& player) { player.RemoveCurseMistEffect(); }); diff --git a/src/lua_api_game.cpp b/src/lua_api_game.cpp index 4ee9cc1..23316f6 100644 --- a/src/lua_api_game.cpp +++ b/src/lua_api_game.cpp @@ -30,6 +30,11 @@ constexpr int STAGE_COUNTER_MAX = 13; // Making this many devil deals in one run unlocks Azazel. // A Greed run's waves, bosses and the devil's included (one more in Greedier). constexpr int GREED_WAVE_TOTAL = 11; +// HUD:ShowItemText's arguments: the clear flag after a player and item, the curse display and clear flags after a +// title and subtitle. +constexpr int HUD_ITEM_CLEAR_ARGUMENT = 4; +constexpr int HUD_TEXT_CURSE_ARGUMENT = 4; +constexpr int HUD_TEXT_CLEAR_ARGUMENT = 5; // The argument past the last line HUD:ShowFortuneText reads. constexpr int FORTUNE_ARGUMENT_END = 34; @@ -307,6 +312,44 @@ static int hud_fortune_text_show(lua_State* state) return 0; } +// A Lua argument as text, empty when it is nil, missing or no string or number. +static const char* lua_text_get(lua_State* state, int index) +{ + const char* text = lua_isnoneornil(state, index) ? nullptr : lua_tostring(state, index); + return text ? text : ""; +} + +// 0085e750 HUD:ShowItemText. With a string (title, subtitle, curse display, clear) it shows them on the first free +// stacked banner. Otherwise it shows a player's item as ShowItemText does (player, item, clear). Either way the stacked +// banners are hidden first unless the clear argument is false. +static int hud_item_text_show(lua_State* state) +{ + HUD& hud = *static_cast(lua_object_check(state, 1, LUA_CLASS_HUD)); + bool isText = lua_type(state, 2) == LUA_TSTRING || lua_type(state, 3) == LUA_TSTRING; + int clearIndex = isText ? HUD_TEXT_CLEAR_ARGUMENT : HUD_ITEM_CLEAR_ARGUMENT; + bool isCleared = lua_isnoneornil(state, clearIndex) || lua_toboolean(state, clearIndex); + + if (isText) + { + if (isCleared) hud.messages_hide(); + bool isCurse = lua_toboolean(state, HUD_TEXT_CURSE_ARGUMENT); + std::string subtitle = lua_text_get(state, 3); + std::string title = lua_text_get(state, 2); + auto banner = std::ranges::find(hud.messageStack, false, &HUD_Message::isShowing); + if (banner != hud.messageStack.end()) banner->Show(title.c_str(), subtitle.c_str(), true, isCurse); + return 0; + } + + auto* player = lua_isnoneornil(state, 2) ? nullptr + : static_cast(lua_object_check(state, 2, LUA_CLASS_PLAYER)); + auto* item = lua_isnoneornil(state, 3) + ? nullptr + : static_cast(lua_object_check(state, 3, LUA_CLASS_ITEM_CONFIG_ITEM)); + if (isCleared) hud.messages_hide(); + if (player && item) hud.ShowItemText(player, item); + return 0; +} + // Registers Lua's HUD, ItemPool and Seeds, the parts of a run Game hands out. static void game_parts_register(lua_State* state) { @@ -319,15 +362,14 @@ static void game_parts_register(lua_State* state) [](HUD& hud, Entity_Player* player, int slot) { hud.InvalidateActiveItem(player, slot); }); lua_method(state, "InvalidateCraftingItem", [](HUD& hud, Entity_Player* player) { hud.InvalidateCraftingItem(player); }); - lua_method(state, "ShowItemText", [](HUD& hud, Entity_Player* player, ItemConfig_Item* item) { - hud.ShowItemText(player, item); - }); lua_method(state, "AssignPlayerHUDs", [](HUD& hud) { hud.AssignPlayerHUDs(); }); lua_method(state, "Update", [](HUD& hud) { hud.Update(); }); lua_method(state, "PostUpdate", [](HUD& hud) { hud.PostUpdate(); }); lua_method(state, "Render", [](HUD& hud) { hud.Render(); }); lua_pushcfunction(state, hud_fortune_text_show); lua_table_set(state, -2, "ShowFortuneText"); + lua_pushcfunction(state, hud_item_text_show); + lua_table_set(state, -2, "ShowItemText"); lua_class_end(state); lua_class_begin(state, "ItemPool", LUA_CLASS_ITEM_POOL); diff --git a/src/manager.cpp b/src/manager.cpp index 5166ecd..1b7ff02 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -1,9 +1,11 @@ #include "manager.h" +#include "backdrop.h" #include "data.h" #include "entity_player.h" #include "game.h" #include "lua_engine.h" #include "menu_manager.h" +#include "render_passes.h" #include "room.h" #include "room_transition.h" #include "kage_input.h" @@ -39,7 +41,15 @@ constexpr const char* CURSOR_ANM2 = "gfx/ui/cursor.anm2"; constexpr const char* BUTTONS_ANM2 = "gfx/ui/Buttons.anm2"; constexpr const char* PLATFORM_ICONS_ANM2 = "gfx/ui/PlatformIcons.anm2"; constexpr const char* CURSOR_ANIMATION = "Idle"; -constexpr const char* BUTTONS_ANIMATION = "XboxOne"; + +// The button glyph sheets of Buttons.anm2, by the layout a gamepad's buttons follow. +enum PadLayout +{ + PAD_XBOX, + PAD_PLAYSTATION, + PAD_NINTENDO +}; +constexpr std::array PAD_ANIMATIONS = {"XboxOne", "PS4", "WiiU"}; // The language codes GetLanguage gives, by StringTable language id, and the one for any other id. constexpr std::array LANGUAGE_CODES = { @@ -66,7 +76,6 @@ constexpr const char* VERTEX_EXTENSION = ".vs"; constexpr const char* FRAGMENT_EXTENSION = ".fs"; constexpr const char* COLORED_TEXTURED_VERTEX = "basic_colored_textured"; constexpr const char* TEXTURED_VERTEX = "basic_textured"; -constexpr const char* COLOR_CORRECTION_SHADER = "ColorCorrection"; constexpr const char* HQ4X_SHADER = "HQ4X"; constexpr KAGE::Graphics::VertexAttribute COLORED_TEXTURED_ATTRIBUTES[] = { {"Position", KAGE::Graphics::VERTEX_POSITION}, @@ -105,7 +114,7 @@ constexpr GameShader GAME_SHADERS[] = { {"Pixelation", TEXTURED_ATTRIBUTES, TEXTURED_VERTEX, "pixelation", "Pixelation Shader"}, {"Bloom", COLORED_TEXTURED_ATTRIBUTES, COLORED_TEXTURED_VERTEX, "bloom", "Bloom Shader"}, {"ColorMod", COLORED_TEXTURED_ATTRIBUTES, COLORED_TEXTURED_VERTEX, "colormod", "Colormod Shader"}, - {COLOR_CORRECTION_SHADER, TEXTURED_ATTRIBUTES, TEXTURED_VERTEX, "colorcorrection", "Color Correction Shader"}, + {COLOR_CORRECTION_SHADER.data(), TEXTURED_ATTRIBUTES, TEXTURED_VERTEX, "colorcorrection", "Color Correction Shader"}, {HQ4X_SHADER, TEXTURED_ATTRIBUTES, TEXTURED_VERTEX, "hq4x", "HQ4X Shader"}, {"OldTV", TEXTURED_ATTRIBUTES, TEXTURED_VERTEX, "oldtv", "OldTV Shader"}, {"Shockwave", COLORED_TEXTURED_ATTRIBUTES, COLORED_TEXTURED_VERTEX, "shockwave", "Shockwave Shader"}, @@ -139,7 +148,6 @@ constexpr const char* INFO_DISPLAY_DEFAULT_NAME = "Unknown"; constexpr const char* CHALLENGES_XML = "challenges.xml"; constexpr const char* ENTITIES_XML = "entities2.xml"; constexpr const char* BOSS_COLORS_XML = "bosscolors.xml"; -constexpr const char* PLAYERS_XML = "players.xml"; constexpr const char* BABIES_XML = "babies.xml"; constexpr const char* BOSS_PORTRAITS_XML = "bossportraits.xml"; @@ -339,7 +347,7 @@ void Manager::Init() manager.buttonsSprite.Load(BUTTONS_ANM2, GRAPHICS_LOAD); manager.platformIconsSprite.Load(PLATFORM_ICONS_ANM2, GRAPHICS_LOAD); - manager.buttonsSprite.Play(BUTTONS_ANIMATION); + manager.buttonsSprite.Play(PAD_ANIMATIONS[PAD_XBOX]); input_devices_configure(manager.keyConfigs); manager.modManager.LoadModContent(); manager.netplayManager.Init(); @@ -1616,7 +1624,7 @@ void Manager::Render() float gamma = 1 / optionsConfig.gamma; surface_pop(); - KAGE::Graphics::Shader& shader = shader_select(COLOR_CORRECTION_SHADER); + KAGE::Graphics::Shader& shader = shader_select(COLOR_CORRECTION_SHADER.data()); shader.set_uniform("Exposure", KAGE::Graphics::UNIFORM_FLOAT, &exposure); shader.set_uniform("Gamma", KAGE::Graphics::UNIFORM_FLOAT, &gamma); surface_draw(colorCorrectionSurface); @@ -1694,7 +1702,58 @@ void seed_fart_sound_override(int* soundId) if (fartRng.Next() % FART_GURG_CHANCE == 0) *soundId = SOUND_FART_GURG; } +// 0095ad30 Draws a frame of the button glyph sheet at full size. +void Manager::render_button_sprite(int frame, Vector position) +{ + ANM2& sprite = g_manager->buttonsSprite; + + sprite.scale = vector_make(1, 1); + sprite.SetFrame((float)frame); + sprite.Render({.position = position}); +} + +// The glyph sheet a gamepad's buttons follow. KAGE read it from the pad's name, SDL knows the pad's family. +static PadLayout pad_layout_get(const KAGE::Input::InputDevice& device) +{ + switch (SDL_GetGamepadType(device.gamepad)) + { + case SDL_GAMEPAD_TYPE_PS3: + case SDL_GAMEPAD_TYPE_PS4: + case SDL_GAMEPAD_TYPE_PS5: return PAD_PLAYSTATION; + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO: + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT: + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT: + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR: return PAD_NINTENDO; + default: return PAD_XBOX; + } +} + +// 0095af30 Draws the glyph of the button a gamepad has an action on, on its layout's sheet, and whether it drew one. +// Only the first two bindings have glyphs. Without one the fallback draws the gamepad default's button number as the +// frame itself, unconverted, as the original does. The keyboard draws nothing. +// render_input_button_icon (0095adf0) is this at full size, the scale's default. +bool Manager::render_controller_action_glyph(const ActionGlyph& glyph) +{ + std::shared_ptr device = KAGE::Input::manager.device_find(glyph.controllerIndex); + std::vector& defaults = platform.bindings.controller; + + if (!device || device->type != KAGE::Input::DEVICE_GAMEPAD) return false; + + buttonsSprite.Play(PAD_ANIMATIONS[pad_layout_get(*device)]); + int frame = glyph.bindingIndex < CONFIG_SLOTS + ? controller_button_to_glyph_frame(keyConfigs.binding_get(*device, glyph.action)[glyph.bindingIndex]) + : KAGE::Input::BUTTON_NONE; + bool isFallback = frame == KAGE::Input::BUTTON_NONE && glyph.fallback == GLYPH_FALLBACK; + if (isFallback && glyph.action >= 0 && glyph.action < (int)defaults.size()) frame = defaults[glyph.action][0]; + if (frame == KAGE::Input::BUTTON_NONE) return false; + + buttonsSprite.scale = glyph.scale; + buttonsSprite.SetFrame((float)frame); + buttonsSprite.color = glyph.color; + buttonsSprite.Render({.position = glyph.position}); + return true; +} + // Not reconstructed yet: each stops the game where it is reached. Manager::~Manager() { reconstruction_missing("Manager::destructor 00951160"); } -void Manager::render_button_sprite(int, Vector) { reconstruction_missing("Manager::render_button_sprite 0095ad30"); } void Manager::apply_device_key_config(int) { reconstruction_missing("Manager::apply_device_key_config 0095b180"); } diff --git a/src/manager.h b/src/manager.h index ca504c3..a3fd903 100644 --- a/src/manager.h +++ b/src/manager.h @@ -66,6 +66,25 @@ enum ChallengeSource CHALLENGES_MOD }; +// Whether a controller glyph falls back to the frame of the gamepad's default button when the controller has none. +enum GlyphFallback +{ + GLYPH_NO_FALLBACK, + GLYPH_FALLBACK +}; + +// A controller's button glyph for an action: which of the action's bindings, where, how big and in what color. +struct ActionGlyph +{ + ColorMod color = COLOR_DEFAULT; + Vector position{}; + Vector scale = vector_make(1, 1); + int action = 0; + int bindingIndex = 0; + int controllerIndex = 0; + GlyphFallback fallback = GLYPH_FALLBACK; +}; + // The game's top object (g_manager): every subsystem that outlives a run, the state it shows (menus, game, cutscene, // nightmare) and the transitions queued between them, the UI sprites and fonts, and the run about to start. // Members of classes not taken over yet keep their generated types and start zeroed. @@ -182,6 +201,7 @@ public: void update_controller_popups(); static void render_loading_icon(float alpha); static void render_button_sprite(int frame, Vector position); + bool render_controller_action_glyph(const ActionGlyph& glyph); static void apply_device_key_config(int deviceId); static bool AchievementUnlocksDisallowed(); static void queue_achievement_popup(int achievementId); diff --git a/src/manager_input.cpp b/src/manager_input.cpp index ecc9e18..c7e4121 100644 --- a/src/manager_input.cpp +++ b/src/manager_input.cpp @@ -4,7 +4,6 @@ #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 uint8_t RESTART_HOLD_FRAMES = 16; @@ -29,10 +28,10 @@ static bool is_restart_held(PlayerManager& players) if (!player || !KAGE::Input::manager.device_find(player->controllerIndex)) continue; int controller = player->controllerIndex; - bool isKeyboardHeld = is_controller_action(KEYBOARD_ID, ACTION_RESTART, ACTION_PRESSED); + bool isKeyboardHeld = is_controller_action(KEYBOARD_DEVICE, ACTION_RESTART, ACTION_PRESSED); bool isComboHeld = is_controller_action(controller, ACTION_PAUSE, ACTION_PRESSED) && is_controller_action(controller, ACTION_MAP, ACTION_PRESSED); - if (controller == KEYBOARD_ID) isHeld = isKeyboardHeld; + if (controller == KEYBOARD_DEVICE) isHeld = isKeyboardHeld; else if (isKeyboardHeld || isComboHeld) isHeld = true; } return isHeld; @@ -90,7 +89,7 @@ void Manager::update_ingame_input() Game& game = *g_game; RoomTransition& transition = game.roomTransition; - std::shared_ptr keyboard = KAGE::Input::manager.device_find(KEYBOARD_ID); + std::shared_ptr keyboard = KAGE::Input::manager.device_find(KEYBOARD_DEVICE); if (keyboard && keyboard->is_button_triggered(KEY_RESIZE_REQUEST)) game.isWindowResizePending = true; restart_update(game); diff --git a/src/menu_bestiary.cpp b/src/menu_bestiary.cpp index 86c55de..c672fe0 100644 --- a/src/menu_bestiary.cpp +++ b/src/menu_bestiary.cpp @@ -1,4 +1,5 @@ #include "menu_bestiary.h" +#include "entity_npc.h" #include "log.h" #include "manager.h" #include "menu_manager.h" @@ -236,9 +237,9 @@ void Menu_Bestiary::Update() bestiaryMenuSprite.GetLayer(NEXT_PAGE_LAYER)->isVisible = currentPage < last_page_get(); } -// 008c8c70 Loads the selected entity's bestiary animation: its bestiary sprite or its own, with its overlay, scaled, -// without its shadow. Fallen angels take their black sheets, dirt and holes are brightened, and Dogma ignores the -// game's time. +// 008c8c70 Loads the selected entity's bestiary animation: its bestiary sprite or its own (its floor's sheets when it +// names one), with its overlay, scaled, without its shadow. Fallen angels take their black sheets, dirt and holes are +// brightened, and Dogma ignores the game's time. void Menu_Bestiary::LoadPreview() { enemySprite.Reset(); @@ -247,8 +248,13 @@ void Menu_Bestiary::LoadPreview() enemySprite.Load(entity->bestiaryAnm2Path.empty() ? entity->anm2Path : entity->bestiaryAnm2Path, GRAPHICS_DEFER); std::vector& layers = enemySprite.layerStates; - if (!entity->bestiaryFloorAlt.empty() && !layers.empty()) - reconstruction_missing("anm2_resolve_spritesheet_path 006b9c10, for a bestiary floor alternate sheet"); + bool isChampionSheet = false; + for (size_t layer = 0; layer < layers.size() && !entity->bestiaryFloorAlt.empty(); layer++) + { + std::string sheet = layers[layer].layerData ? layers[layer].layerData->spriteSheetPath : ""; + std::string resolved = sheet_path_resolve(sheet, entity->bestiaryFloorAlt, "", isChampionSheet); + enemySprite.ReplaceSpritesheet((int)layer, resolved); + } bool isFallenAngel = (entity->id == ENTITY_GABRIEL || entity->id == ENTITY_URIEL) && entity->variant == ANGEL_VARIANT_FALLEN; diff --git a/src/menu_challenge.cpp b/src/menu_challenge.cpp index d39c74e..3209aab 100644 --- a/src/menu_challenge.cpp +++ b/src/menu_challenge.cpp @@ -16,16 +16,13 @@ constexpr int DONE_LAYER = 15; constexpr int ENTRY_LAYERS[] = {OPEN_LAYER, DONE_LAYER, LOCKED_LAYER}; constexpr int FIRST_CHALLENGE = 1; constexpr int LAST_CHALLENGE = CHALLENGE_COUNT - 1; -constexpr int KEYBOARD_DEVICE = 0; constexpr int LOBBY_MODE_NONE = 0; constexpr int LOBBY_MODE_CHALLENGE = 4; // 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; constexpr int SCROLL_LAST_ROW = 43; -constexpr int SCROLL_ROWS_ABOVE = 4; constexpr float SCROLL_ROW_HEIGHT = 22; -constexpr float CHALLENGE_VIEW_Y = -216; constexpr float CHALLENGE_VIEW_BOTTOM_Y = -1074; // The achievement opening each challenge to play, by challenge id. None (0) is always open. @@ -194,9 +191,11 @@ void Menu_Challenge::Render() sprite.SetLayerFrame(CURSOR_LAYER, selectedChallengeId - 1); sprite.RenderLayer(CURSOR_LAYER, draw); - bool isGamepad = g_menuControllerIndex != KEYBOARD_DEVICE && g_menuControllerIndex != DEVICE_NONE; - if (isGamepad && !isFromLobby && sprite.GetNullFrame(CUSTOM_BUTTON_NULL)) - reconstruction_missing("Manager::render_controller_action_glyph 0095af30, which manager.h does not declare"); + const NullFrame* customButton = sprite.GetNullFrame(CUSTOM_BUTTON_NULL); + if (g_menuControllerIndex != KEYBOARD_DEVICE && !isFromLobby && customButton) + g_manager->render_controller_action_glyph({.position = vector_add(draw.position, customButton->pos), + .action = ACTION_MENU_TAB, + .controllerIndex = g_menuControllerIndex}); layer_show(sprite, CUSTOM_PAPER_LAYER, !isFromLobby); layer_show(sprite, CUSTOM_TEXT_LAYER, !isFromLobby); diff --git a/src/menu_character.cpp b/src/menu_character.cpp index b706c1d..f2ecf56 100644 --- a/src/menu_character.cpp +++ b/src/menu_character.cpp @@ -56,7 +56,6 @@ constexpr const char* EVENT_SOUND = "Sound"; constexpr const char* BUTTON_ICON_NULL = "ButtonIcon"; constexpr const char* EDEN_TOKENS_KEY = "#EDEN_TOKENS_COUNT"; constexpr const char* SEED_MENU_CATEGORY = "SeedMenu"; -constexpr char STRING_KEY_PREFIX = '#'; // The wheel's characters, the game's then their tainted twins, as the exe's table at 00b24140 lists them. constexpr Menu_Character_Entry CHARACTER_ENTRIES[CHARACTER_MENU_COUNT][CHARACTER_ENTRY_COUNT] = { @@ -127,8 +126,6 @@ constexpr int SOUND_CHARACTER_SELECT_RIGHT = 195; constexpr int SOUND_MENU_FLIP_LIGHT = 569; constexpr int SOUND_MENU_FLIP_DARK = 570; constexpr int SOUND_MENU_RIP = 571; -constexpr int SOUND_DELAY = 2; -constexpr int KEYBOARD_DEVICE = 0; constexpr int BACKGROUND_LAYER_BACK = 0; constexpr int BACKGROUND_LAYER_FRONT = 1; @@ -175,7 +172,6 @@ constexpr ColorModState COLOR_MOD_TAINTED = {1, 1.03f, 1.1f, 0.3f, -0.15f, 0.9f} constexpr float PORTRAIT_FADE_RED = 231; constexpr float PORTRAIT_FADE_GREEN = 221; constexpr float PORTRAIT_FADE_BLUE = 220; -constexpr float CHANNEL_MAX = 255; // Where a part of the menu sits from the menu's corner, or from another part. struct MenuOffset @@ -232,10 +228,10 @@ static bool is_key(int key, ActionTest test) // Whether the menu controller's glyph for an action was drawn at a position, which the sprites' own key art stands in // for otherwise. The keyboard has no glyphs. -static bool is_action_glyph_rendered([[maybe_unused]] ButtonAction action, [[maybe_unused]] Vector glyphPosition) +static bool is_action_glyph_rendered(ButtonAction action, Vector glyphPosition) { - if (g_menuControllerIndex == KEYBOARD_DEVICE || g_menuControllerIndex == DEVICE_NONE) return false; - reconstruction_missing("Manager::render_controller_action_glyph 0095af30, which manager.h does not declare"); + return g_manager->render_controller_action_glyph( + {.position = glyphPosition, .action = action, .controllerIndex = g_menuControllerIndex}); } // Shows or hides a layer of a sprite. The original assumes the layer is there. @@ -1227,8 +1223,8 @@ void Menu_Character::render_portraits(Vector wheelPosition, Vector offset, Vecto float fade = 1 - portrait.scale; ColorMod color = {{portrait.scale, portrait.scale, portrait.scale, 1}, {0, 0, 0, 0}, - {fade * PORTRAIT_FADE_RED / CHANNEL_MAX, fade * PORTRAIT_FADE_GREEN / CHANNEL_MAX, - fade * PORTRAIT_FADE_BLUE / CHANNEL_MAX}}; + {fade * PORTRAIT_FADE_RED / COLOR_CHANNEL_MAX, fade * PORTRAIT_FADE_GREEN / COLOR_CHANNEL_MAX, + fade * PORTRAIT_FADE_BLUE / COLOR_CHANNEL_MAX}}; float portraitY = portrait.position.y * scale.y + offset.y + wheelPosition.y; Vector portraitScale = vector_make(portrait.scale * scale.x, portrait.scale * scale.y); if (portrait.menuId >= CHARACTER_ENTRY_COUNT) diff --git a/src/menu_collection.cpp b/src/menu_collection.cpp index 77637b2..6de2297 100644 --- a/src/menu_collection.cpp +++ b/src/menu_collection.cpp @@ -13,7 +13,6 @@ constexpr const char* COLLECTION_ANM2 = "gfx/ui/main menu/CollectionMenu.anm2"; constexpr const char* DEATH_SCREEN_ANM2 = "gfx/ui/Death Screen.anm2"; constexpr const char* ANIMATION_DIARY = "Diary"; constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset"; -constexpr const char* COLOR_OFFSET_DOGMA_SHADER = "ColorOffsetDogma"; constexpr int PAGE_SIZE = 120; constexpr int PAGE_COLUMNS = 20; constexpr int REPEAT_DELAY = 19; diff --git a/src/menu_custom_challenge.cpp b/src/menu_custom_challenge.cpp index e023692..9bb6719 100644 --- a/src/menu_custom_challenge.cpp +++ b/src/menu_custom_challenge.cpp @@ -3,37 +3,10 @@ #include "manager.h" #include "menu_challenge.h" #include "menu_manager.h" -#include +#include "menu_mods.h" constexpr const char* CUSTOM_CHALLENGE_ANM2 = "gfx/ui/main menu/ChallengeMenuCustom.anm2"; -constexpr const char* ANIMATION_MAIN = "Main"; -constexpr const char* ANIMATION_BOTTOM = "Bottom"; -constexpr const char* ANIMATION_CURSOR = "Cursor"; -constexpr const char* ENTRY_FORMAT = "{}.{}"; -constexpr const char* PIECE_FORMAT = "Piece{}"; -constexpr int SOUND_DELAY = 2; constexpr int FIRST_MOD_CHALLENGE = CHALLENGE_COUNT; -constexpr float CHALLENGE_VIEW_Y = -216; - -// The paper: torn pieces down to the bottom, as many as the list needs, picked by a fixed seed so they stay put. -constexpr uint32_t PIECE_SEED = 12345; -constexpr uint32_t PIECE_SHIFT_INDEX = 35; -constexpr uint32_t PIECE_COUNT = 5; -constexpr int PIECE_ROWS_PER_ENTRY = 25; -constexpr int PIECE_ROWS_SHIFT = 5; -constexpr float PIECE_HEIGHT = 32; -constexpr float PAPER_OFFSET_X = 200; - -// The list: each entry's text, scaled down, and the cursor before the selected one. The view scrolls past the fifth. -constexpr float ENTRY_OFFSET_X = -90; -constexpr float CURSOR_OFFSET_X = -93; -constexpr float CURSOR_OFFSET_Y = -16; -constexpr float ENTRY_TEXT_SCALE_X = 0.8f; -constexpr float ENTRY_HEIGHT = 25; -constexpr int SCROLL_ROWS_ABOVE = 4; -constexpr int SCROLL_ROWS_BELOW = 3; -constexpr int SCROLL_LAST_ROWS = 7; -constexpr size_t ENTRY_TEXT_LIMIT = 63; static int challenge_count() { @@ -56,16 +29,11 @@ void Menu_CustomChallenge::LoadGraphics() } // 008ceb90 Plays the paper and puts the cursor on the first mod challenge. -// The original scrolls the game's challenges menu back to the top here, not this one. Kept. void Menu_CustomChallenge::reset() { - MenuManager& menus = *g_menuManager; - - customChallengeSprite.Play(ANIMATION_MAIN); + paper_reset(customChallengeSprite); selectedChallengeId = FIRST_MOD_CHALLENGE; holdInputTimer = 0; - menus.viewPositionSet[MENU_CHALLENGE].y = CHALLENGE_VIEW_Y; - menus.isViewMoving = true; } // 008ce080 Steps the menu: the selected challenge starts once the menus faded out. Confirm picks it (a buzz when mods @@ -103,51 +71,24 @@ void Menu_CustomChallenge::Update() holdInputTimer = isHeld ? holdInputTimer + 1 : 0; } -// 008ce430 Draws the paper (its top, the torn pieces and the bottom), each mod challenge's number and name, and the -// cursor by the selected one, then scrolls the view to keep it in sight. -// The original formats the text into 64 bytes, failing past them. Longer names are cut instead. +// 008ce430 Draws the paper, each mod challenge's number and name, and the cursor by the selected one, then scrolls the +// view to keep it in sight. void Menu_CustomChallenge::Render() { MenuManager& menus = *g_menuManager; - ANM2& sprite = customChallengeSprite; std::vector& params = g_manager->challengeParams; - Vector origin = vector_make(menus.viewPosition.x + position.x + PAPER_OFFSET_X, menus.viewPosition.y + position.y); - int count = challenge_count(); - int pieceRows = ((count - FIRST_MOD_CHALLENGE) * PIECE_ROWS_PER_ENTRY >> PIECE_ROWS_SHIFT) + 1; - RNG pieceRng{}; - - sprite.Play(ANIMATION_MAIN); - sprite.Render({.position = origin}); - pieceRng.SetSeed(PIECE_SEED, PIECE_SHIFT_INDEX); - for (int row = 1; row <= pieceRows; row++) - { - sprite.Play(std::format(PIECE_FORMAT, pieceRng.RandomInt(PIECE_COUNT) + 1)); - sprite.Render({.position = vector_make(origin.x, origin.y + (float)row * PIECE_HEIGHT)}); - } - sprite.Play(ANIMATION_BOTTOM); - sprite.Render({.position = vector_make(origin.x, origin.y + (float)pieceRows * PIECE_HEIGHT)}); - - for (int row = 1; row + FIRST_MOD_CHALLENGE - 1 < count; row++) - { - int challengeId = row + FIRST_MOD_CHALLENGE - 1; - std::string text = std::format(ENTRY_FORMAT, row, params[challengeId].name).substr(0, ENTRY_TEXT_LIMIT); - Vector textPosition = vector_make(origin.x + ENTRY_OFFSET_X, origin.y + (float)(row - 1) * ENTRY_HEIGHT); - Vector scale = vector_make(ENTRY_TEXT_SCALE_X, 1); - FontSettings settings; - - g_manager->font2_TeamMeatEx12.DrawString(text, textPosition, scale, kcolor_argb(BLACK_ARGB), settings); - if (selectedChallengeId != challengeId) continue; - - sprite.Play(ANIMATION_CURSOR); - Vector cursor = vector_make(origin.x + CURSOR_OFFSET_X, origin.y + (float)row * ENTRY_HEIGHT + CURSOR_OFFSET_Y); - sprite.Render({.position = cursor}); - } - + Vector origin = paper_origin_get(position); + int rowCount = challenge_count() - FIRST_MOD_CHALLENGE; int selectedRow = selectedChallengeId - FIRST_MOD_CHALLENGE; - int rowCount = count - FIRST_MOD_CHALLENGE; - int scrollRows = - selectedRow < rowCount - SCROLL_ROWS_BELOW ? selectedRow - SCROLL_ROWS_ABOVE : rowCount - SCROLL_LAST_ROWS; - menus.viewPositionSet[MENU_CUSTOM_CHALLENGE].y = - selectedRow > SCROLL_ROWS_ABOVE ? CHALLENGE_VIEW_Y - (float)(scrollRows * ENTRY_HEIGHT) : CHALLENGE_VIEW_Y; + + paper_top_render(customChallengeSprite, origin); + paper_render(customChallengeSprite, origin, rowCount); + for (int row = 0; row < rowCount; row++) + { + paper_row_render(paper_row_text(row, params[row + FIRST_MOD_CHALLENGE].name), origin, row, BLACK); + if (row == selectedRow) paper_cursor_render(customChallengeSprite, origin, row); + } + + menus.viewPositionSet[MENU_CUSTOM_CHALLENGE].y = paper_view_y_get(selectedRow, rowCount); menus.isViewMoving = true; } diff --git a/src/menu_cutscenes.cpp b/src/menu_cutscenes.cpp index baffaa8..f99b327 100644 --- a/src/menu_cutscenes.cpp +++ b/src/menu_cutscenes.cpp @@ -8,7 +8,6 @@ constexpr ColorMod UNSEEN_COLOR = {{1, 1, 1, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr int CURSOR_LAYER = 25; constexpr int CUTSCENE_SLOTS = 24; constexpr int CUTSCENE_ROWS = 6; -constexpr int SOUND_DELAY = 2; // A slot of the page: the sprite layer drawing it and the cutscene it plays. struct CutsceneSlot diff --git a/src/menu_daily_challenge.cpp b/src/menu_daily_challenge.cpp index e3889dc..efd0800 100644 --- a/src/menu_daily_challenge.cpp +++ b/src/menu_daily_challenge.cpp @@ -23,7 +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 float BUTTON_HIDDEN = 96; // Where the texts sit: the player's name shrunk to fit its width, the countdown, and the streaks scaled down. @@ -37,7 +36,6 @@ constexpr const char* PROFILE_NAME_NONE = "???"; // The daily clock: Steam's server time, ten hours behind UTC, and the game's fallback without Steam. constexpr time_t STEAM_OFFLINE_TIME = 1; constexpr time_t SERVER_HOUR_OFFSET = -10; -constexpr time_t SECONDS_PER_HOUR = 3600; constexpr int LAST_HOUR = 23; constexpr int LAST_MINUTE = 59; constexpr int YEAR_BASE = 1900; diff --git a/src/menu_game.cpp b/src/menu_game.cpp index 66ecb3d..0854168 100644 --- a/src/menu_game.cpp +++ b/src/menu_game.cpp @@ -17,6 +17,7 @@ constexpr const char* CONTINUE_IMAGE_NAME = "Continue Img Surface"; constexpr const char* ANIMATION_APPEAR = "Appear"; constexpr const char* ANIMATION_DISAPPEAR = "Dissapear"; constexpr const char* MODS_KEY_LAYER = "ModsKey"; +constexpr const char* MODS_BUTTON_NULL = "ModsButton"; constexpr const char* GUIDE_NULL = "Guide"; constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset"; constexpr int CONTINUE_IMAGE_SIZE = 256; @@ -25,8 +26,6 @@ constexpr int CONTINUE_LAYER = 2; constexpr int CONTINUE_SAVED = 0; constexpr int CONTINUE_EMPTY = 1; constexpr int CONTINUE_RERUN = 2; -constexpr int SOUND_DELAY = 2; -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}}; @@ -37,9 +36,6 @@ constexpr const char* STAGE_NULL = "Stage"; constexpr int CHARACTER_LAYER = 0; constexpr int DIFFICULTY_LAYER = 2; constexpr int CHARACTER_ALT_LAYER = 3; -constexpr int FRAMES_PER_SECOND = 30; -constexpr int SECONDS_PER_MINUTE = 60; -constexpr int SECONDS_PER_HOUR = 3600; constexpr int TIME_TEXT_SIZE = 9; constexpr int STAGE_LINE_WIDTH = 88; constexpr size_t SHORT_WORD_LENGTH = 2; @@ -329,8 +325,12 @@ void Menu_Game::Render() SpriteDraw draw = menus.menu_draw_get(position); gameMenuSprite.Render(draw); - if (g_menuControllerIndex != KEYBOARD_DEVICE && g_menuControllerIndex != DEVICE_NONE) - reconstruction_missing("Manager::render_controller_action_glyph 0095af30, which manager.h does not declare"); + const NullFrame* modsButton = gameMenuSprite.GetNullFrame(MODS_BUTTON_NULL); + // The original reads the null without checking it is there. + if (g_menuControllerIndex != KEYBOARD_DEVICE && g_menuControllerIndex != DEVICE_NONE && modsButton) + g_manager->render_controller_action_glyph({.position = vector_add(draw.position, modsButton->pos), + .action = ACTION_MENU_TAB, + .controllerIndex = g_menuControllerIndex}); bool isWidgetHidden = continueWidgetSprite.IsFinished(ANIMATION_DISAPPEAR); if (!isWidgetHidden && menus.selectedMenuId == MENU_GAME && continueImage) diff --git a/src/menu_key_config.cpp b/src/menu_key_config.cpp index a170e31..c95dfbe 100644 --- a/src/menu_key_config.cpp +++ b/src/menu_key_config.cpp @@ -9,17 +9,18 @@ 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 int ACTION_TOGGLE_DESCRIPTIONS = 31; constexpr int CURSOR_LAYER = 6; -constexpr int KEYBOARD_ID = 0; constexpr int RESET_ROW = 19; constexpr int SLOT_PRIMARY = 0; constexpr int SLOT_SECONDARY = 1; -constexpr int SOUND_DELAY = 2; constexpr int SCROLL_TOP_ROW = 2; constexpr float VIEW_TOP = -1890; constexpr float LABEL_X = 80; constexpr float LABEL_Y = 58; constexpr float PRIMARY_RIGHT = 400; constexpr float SECONDARY_RIGHT = 300; +constexpr float PRIMARY_GLYPH_X = 384; +constexpr float SECONDARY_GLYPH_X = 284; +constexpr float GLYPH_OFFSET_Y = 7; constexpr float CURSOR_X = 480; constexpr float CURSOR_Y = 2; constexpr float COLUMN_WIDTH = 100; @@ -87,7 +88,7 @@ static bool is_device_triggered(const KAGE::Input::InputDevice* device, int acti static bool is_menu_triggered(const KAGE::Input::InputDevice& device, int action) { return is_device_triggered(&device, action) || - is_device_triggered(KAGE::Input::manager.device_find(KEYBOARD_ID).get(), action); + is_device_triggered(KAGE::Input::manager.device_find(KEYBOARD_DEVICE).get(), action); } // The config a device's bindings are edited in, made from the defaults for its kind when it has none yet. @@ -133,7 +134,7 @@ void Menu_KeyConfig::leave() { selectedElement = 0; state = KEY_CONFIG_BROWSING; - g_menuControllerIndex = KEYBOARD_ID; + g_menuControllerIndex = KEYBOARD_DEVICE; g_manager->isHotkeysEnabled = true; g_menuManager->pop_menu(); } @@ -258,11 +259,16 @@ void Menu_KeyConfig::Render() font.DrawString(g_manager->stringTable.translate(entry.label), vector_make(origin.x + LABEL_X, y), vector_make(1, 1), rowColor, settings); - if (device->type != KAGE::Input::DEVICE_KEYBOARD) - reconstruction_missing( - "Manager::render_controller_action_glyph 0095af30, which manager.h does not declare"); - keyDraw(binding[SLOT_PRIMARY], PRIMARY_RIGHT, y, rowColor); - keyDraw(binding[SLOT_SECONDARY], SECONDARY_RIGHT, y, textColor); + auto isGlyphRendered = [&](int slot, float x) { + return g_manager->render_controller_action_glyph({.position = vector_make(origin.x + x, y + GLYPH_OFFSET_Y), + .action = entry.action, + .bindingIndex = slot, + .controllerIndex = g_menuControllerIndex, + .fallback = GLYPH_NO_FALLBACK}); + }; + if (!isGlyphRendered(SLOT_PRIMARY, PRIMARY_GLYPH_X)) keyDraw(binding[SLOT_PRIMARY], PRIMARY_RIGHT, y, rowColor); + if (!isGlyphRendered(SLOT_SECONDARY, SECONDARY_GLYPH_X)) + keyDraw(binding[SLOT_SECONDARY], SECONDARY_RIGHT, y, textColor); if (row != selectedElement) continue; SpriteDraw cursorDraw; diff --git a/src/menu_manager.cpp b/src/menu_manager.cpp index d074d2c..377ae94 100644 --- a/src/menu_manager.cpp +++ b/src/menu_manager.cpp @@ -47,12 +47,10 @@ constexpr int MUSIC_JINGLE_GAME_START = 95; constexpr float WIDGET_OFFSET_Y = 90; constexpr float BUTTON_SHOWN = 0; constexpr float BUTTON_RAISED = 25; -constexpr float BUTTON_HIDDEN = 96; 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 float CHANNEL_MAX = 255; constexpr int CLAMP_TO_EDGE = 1; constexpr int KEY_REPEAT_DELAY = 49; constexpr int KEY_REPEAT_INTERVAL = 10; @@ -76,7 +74,7 @@ KColor kcolor_make(float red, float green, float blue, float alpha) // A color from packed ARGB bytes, as KColor::SetFromARGB unpacks them. KColor kcolor_argb(uint32_t argb) { - auto channel = [argb](int shift) { return (float)((argb >> shift) & 0xff) / CHANNEL_MAX; }; + auto channel = [argb](int shift) { return (float)((argb >> shift) & 0xff) / COLOR_CHANNEL_MAX; }; return kcolor_make(channel(16), channel(8), channel(0), channel(24)); } @@ -225,7 +223,7 @@ void MenuManager::Init() } // Inits each menu at its place on the sheet, in the original order. The daily menu's record streak catches up with -// the current one. Menu_Mods is not taken over yet and starts unloaded. The key config menu's own reset of its view +// the current one. The key config menu's own reset of its view // place and the view movement is left out, as Init sets both again. void MenuManager::menus_init() { @@ -252,6 +250,7 @@ void MenuManager::menus_init() log_printf(LOG_INFO, "Menu Stats Init\n"); menuStats.Init(menu_position_get(MENU_STATS)); log_printf(LOG_INFO, "Menu Mods Init\n"); + menuMods.Init(menu_position_get(MENU_MODS)); log_printf(LOG_INFO, "Menu Options Init\n"); menuOptions.Init(menu_position_get(MENU_OPTIONS), OPTIONS_MAIN_MENU); log_printf(LOG_INFO, "Menu Controller Init\n"); @@ -266,7 +265,7 @@ void MenuManager::menus_init() menuCustomChallenge.Init(menu_position_get(MENU_CUSTOM_CHALLENGE)); } -// 00988ba0 Drops every menu's sprites, as a run starts. Menu_Mods is not taken over yet and holds none. +// 00988ba0 Drops every menu's sprites, as a run starts. The mods menu keeps its own. void MenuManager::unload_graphics() { menuTitle.titleScreenSprite.Reset(); @@ -288,8 +287,7 @@ void MenuManager::unload_graphics() menuCustomChallenge.customChallengeSprite.Reset(); } -// 00988d80 Loads every menu's sprites again, as the menus come back. Menu_Mods is not taken over yet and stays -// unloaded. +// 00988d80 Loads every menu's sprites again, as the menus come back. void MenuManager::LoadGraphics() { menuTitle.sprite_load(); @@ -308,6 +306,7 @@ void MenuManager::LoadGraphics() menuDailyChallenge.load_graphics(); menuBestiary.load_graphics(); menuCustomChallenge.LoadGraphics(); + menuMods.LoadGraphics(); } // 00989750 Fades the menus out into the run to the start jingle, loading the loading screen for the start seed. @@ -460,7 +459,7 @@ void MenuManager::color_mod_update() // 0098a040 Draws the menu sheet over its paper color: every menu at its place, the fly, then the overlay, the shadow // and the vignette, all through the color modifier when it is on, then the fades. -// Menu_Mods' page waits for its takeover, and the offline online menus draw nothing. +// The offline online menus draw nothing. void MenuManager::Render() { KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; @@ -489,6 +488,7 @@ void MenuManager::Render() menuOptions.Render(); menuCutscenes.Render(); menuCustomChallenge.Render(); + menuMods.Render(); menuSave.Render(); menuDailyChallenge.leaderboard.Render(); flySprite.Render(menu_draw_get(vector_make(scrollInterpolationX, scrollInterpolationY))); @@ -681,9 +681,8 @@ void MenuManager::SetState(MenuState state, MenuHistory history) // What leaving one menu for another does, and whether entering the special seeds resets them on this path. SeedsEntry MenuManager::transition_apply(MenuState previous, MenuState state) { - if (previous == MENU_MODS && state == MENU_GAME) + if (previous == MENU_MODS && state == MENU_GAME && menuMods.isChanged) { - reconstruction_missing("MenuManager::SetState 0098aa30: Menu_Mods' changed flag, inlined"); g_manager->modManager.Reset(); g_manager->LoadGameState(g_manager->currentSaveSlot); } diff --git a/src/menu_manager.h b/src/menu_manager.h index 3ab1e9b..cb94755 100644 --- a/src/menu_manager.h +++ b/src/menu_manager.h @@ -12,6 +12,7 @@ #include "menu_daily_challenge.h" #include "menu_game.h" #include "menu_key_config.h" +#include "menu_mods.h" #include "menu_options.h" #include "menu_save.h" #include "menu_special_seeds.h" @@ -111,6 +112,13 @@ constexpr const char* ANIMATION_IDLE = "Idle"; constexpr float MENU_HEIGHT = 270; constexpr float MENU_WIDTH = 480; constexpr int DEVICE_NONE = -1; +constexpr int KEYBOARD_DEVICE = 0; +// The challenge menu's resting view, and the rows a paper list keeps above its cursor when it scrolls. +constexpr float CHALLENGE_VIEW_Y = -216; +constexpr int SCROLL_ROWS_ABOVE = 4; +// The frames a menu waits before its sound, and the slide offset that hides a button. +constexpr int SOUND_DELAY = 2; +constexpr float BUTTON_HIDDEN = 96; constexpr int SOUND_MENU_SCROLL = 282; constexpr int SOUND_MENU_NOTE_APPEAR = 283; constexpr int SOUND_MENU_NOTE_HIDE = 284; @@ -119,7 +127,7 @@ constexpr ColorModState COLOR_MOD_NONE = {1, 1, 1, 0, 0, 1}; // Copies are never made. Destruction (00986f30) is the default. // The main menu (g_menuManager): every menu laid out on one sheet the view scrolls across, the history of menus // opened, the fades, the fly, the shadow and overlay over everything, and the color modifier it all renders through. -// The online menus are offline: they are never built, entered or drawn. Menu_Mods keeps its generated type. +// The online menus are offline: they are never built, entered or drawn. class MenuManager { public: @@ -149,7 +157,7 @@ public: Menu_Cutscenes menuCutscenes; Menu_DailyChallenge menuDailyChallenge; Menu_KeyConfig menuKeyConfig; - Menu_Mods menuMods{}; + Menu_Mods menuMods; Menu_Options menuOptions; Menu_SpecialSeeds menuSpecialSeeds; Menu_Stats menuStats; diff --git a/src/menu_mods.cpp b/src/menu_mods.cpp new file mode 100644 index 0000000..e71e10c --- /dev/null +++ b/src/menu_mods.cpp @@ -0,0 +1,217 @@ +#include "menu_mods.h" +#include "fx_layers.h" +#include "manager.h" +#include "menu_manager.h" +#include +#include + +constexpr const char* MODS_MENU_ANM2 = "gfx/ui/main menu/ModsMenu.anm2"; +constexpr const char* WIDGET_BUTTON_NULL = "WidgetButton"; +constexpr const char* WIDGET_TAB_LAYER = "WidgetTab"; +constexpr const char* OUTDATED_SUFFIX = "[Old]"; +constexpr int SWITCH_LAYER = 12; +constexpr int SWITCH_ON_FRAME = 0; +constexpr int SWITCH_OFF_FRAME = 1; +constexpr KColor OUTDATED_COLOR = kcolor_rgba(1, 0, 0, 1); +constexpr KColor OUTDATED_OFF_COLOR = kcolor_rgba(1, 0.5f, 0.5f, 1); +constexpr uint32_t DISABLED_ARGB = 0xff808080; + +// The paper: torn pieces down to the bottom, as many as the list needs, picked by a fixed seed so they stay put. +constexpr const char* ANIMATION_MAIN = "Main"; +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 PIECE_SEED = 12345; +constexpr uint32_t PIECE_SHIFT_INDEX = 35; +constexpr uint32_t PIECE_COUNT = 5; +constexpr int PIECE_ROWS_PER_ENTRY = 25; +constexpr int PIECE_ROWS_SHIFT = 5; +constexpr float PIECE_HEIGHT = 32; +constexpr float PAPER_OFFSET_X = 200; +constexpr float PAPER_VIEW_Y = -216; + +// The list: each entry's text, scaled down, and the cursor before the selected one. The view scrolls past the fifth. +constexpr float ENTRY_OFFSET_X = -90; +constexpr float CURSOR_OFFSET_X = -93; +constexpr float CURSOR_OFFSET_Y = -16; +constexpr float ENTRY_TEXT_SCALE_X = 0.8f; +constexpr float ENTRY_HEIGHT = 25; +constexpr int SCROLL_ROWS_BELOW = 3; +constexpr int SCROLL_LAST_ROWS = 7; +constexpr size_t ENTRY_TEXT_LIMIT = 63; + +// Where the paper's top draws in the current view, for a menu at its place on the menu sheet. +Vector paper_origin_get(Vector menuPosition) +{ + Vector view = g_menuManager->viewPosition; + return vector_make(view.x + menuPosition.x + PAPER_OFFSET_X, view.y + menuPosition.y); +} + +// Plays the paper's top and scrolls the game's challenges menu back to the top, as both mods' menus do on reset. +// That scroll is the original's, though neither menu is the challenges menu. Kept. +void paper_reset(ANM2& sprite) +{ + MenuManager& menus = *g_menuManager; + + sprite.Play(ANIMATION_MAIN); + menus.viewPositionSet[MENU_CHALLENGE].y = PAPER_VIEW_Y; + menus.isViewMoving = true; +} + +// Draws the paper's top. +void paper_top_render(ANM2& sprite, Vector origin) +{ + sprite.Play(ANIMATION_MAIN); + sprite.Render({.position = origin}); +} + +// Draws the torn pieces under the paper's top, as many as the rows need, then its bottom. +void paper_render(ANM2& sprite, Vector origin, int rowCount) +{ + int pieceRows = (rowCount * PIECE_ROWS_PER_ENTRY >> PIECE_ROWS_SHIFT) + 1; + RNG pieceRng{}; + + pieceRng.SetSeed(PIECE_SEED, PIECE_SHIFT_INDEX); + for (int row = 1; row <= pieceRows; row++) + { + sprite.Play(std::format(PIECE_FORMAT, pieceRng.RandomInt(PIECE_COUNT) + 1)); + sprite.Render({.position = vector_make(origin.x, origin.y + (float)row * PIECE_HEIGHT)}); + } + sprite.Play(ANIMATION_BOTTOM); + sprite.Render({.position = vector_make(origin.x, origin.y + (float)pieceRows * PIECE_HEIGHT)}); +} + +// A row's text: its number from 1 and its name, then a suffix. +// The original formats each step into 64 bytes, failing past them. Longer text is cut instead. +std::string paper_row_text(int row, std::string_view name, std::string_view suffix) +{ + std::string text = std::format(ENTRY_FORMAT, row + 1, name).substr(0, ENTRY_TEXT_LIMIT); + return (text + std::string(suffix)).substr(0, ENTRY_TEXT_LIMIT); +} + +// Draws a row's text, scaled down, at its line of the paper. +void paper_row_render(std::string_view text, Vector origin, int row, KColor color) +{ + Vector position = vector_make(origin.x + ENTRY_OFFSET_X, origin.y + (float)row * ENTRY_HEIGHT); + FontSettings settings; + + g_manager->font2_TeamMeatEx12.DrawString(text, position, vector_make(ENTRY_TEXT_SCALE_X, 1), color, settings); +} + +// Draws the cursor before a row. +void paper_cursor_render(ANM2& sprite, Vector origin, int row) +{ + sprite.Play(ANIMATION_CURSOR); + sprite.Render({.position = vector_make(origin.x + CURSOR_OFFSET_X, + origin.y + (float)(row + 1) * ENTRY_HEIGHT + CURSOR_OFFSET_Y)}); +} + +// The view's height that keeps the selected row in sight, past the fifth. +float paper_view_y_get(int selectedRow, int rowCount) +{ + if (selectedRow <= SCROLL_ROWS_ABOVE) return PAPER_VIEW_Y; + + int scrollRows = + selectedRow < rowCount - SCROLL_ROWS_BELOW ? selectedRow - SCROLL_ROWS_ABOVE : rowCount - SCROLL_LAST_ROWS; + return PAPER_VIEW_Y - (float)(scrollRows * ENTRY_HEIGHT); +} + +// Loads the menu at its place on the menu sheet, then resets it (inlined in MenuManager::Init). +void Menu_Mods::Init(Vector menuPosition) +{ + position = menuPosition; + modsMenuSprite.Load(MODS_MENU_ANM2, GRAPHICS_LOAD); + reset(); +} + +// Loads the menu again and resets it (inlined in MenuManager::LoadGraphics). +void Menu_Mods::LoadGraphics() +{ + modsMenuSprite.Load(MODS_MENU_ANM2, GRAPHICS_LOAD); + reset(); +} + +// 008e4970 Plays the paper, puts the cursor on the first mod and forgets any change. +void Menu_Mods::reset() +{ + paper_reset(modsMenuSprite); + selectedMod = 0; + holdInputTimer = 0; + isChanged = false; +} + +// 008e3830 Steps the menu. While mods are on, confirm turns the selected mod on or off (its disable.it written or +// removed) and up and down move the cursor (repeating while held, wrapping). Back leaves, and the tab turns every mod +// on or off. The switch shows whether mods are on, and the tab key art shows on the keyboard. +void Menu_Mods::Update() +{ + std::vector>& mods = g_manager->modManager.mods; + bool& isModsEnabled = g_manager->optionsConfig.isModsEnabled; + int modCount = (int)mods.size(); + + if (is_action(ACTION_MENU_CONFIRM, ACTION_TRIGGERED)) + { + if (isModsEnabled && selectedMod < modCount) + { + ModEntry& mod = *mods[selectedMod]; + mod.isEnabled = !mod.isEnabled; + mod.disable_marker_save(); + isChanged = true; + } + } + else if (is_action(ACTION_MENU_UP, ACTION_PRESSED)) + { + if (isModsEnabled && is_key_repeat(holdInputTimer) && --selectedMod < 0) selectedMod = std::max(modCount - 1, 0); + } + else if (is_action(ACTION_MENU_DOWN, ACTION_PRESSED)) + { + if (isModsEnabled && is_key_repeat(holdInputTimer) && ++selectedMod >= modCount) selectedMod = 0; + } + else if (is_action(ACTION_MENU_BACK, ACTION_TRIGGERED)) g_menuManager->pop_menu(); + else if (is_action(ACTION_MENU_TAB, ACTION_TRIGGERED)) + { + isModsEnabled = !isModsEnabled; + isChanged = true; + } + + modsMenuSprite.SetLayerFrame(SWITCH_LAYER, isModsEnabled ? SWITCH_ON_FRAME : SWITCH_OFF_FRAME); + // The original assumes the layer is there. + if (LayerState* tab = modsMenuSprite.GetLayer(WIDGET_TAB_LAYER)) tab->isVisible = g_menuControllerIndex == KEYBOARD_DEVICE; + + bool isHeld = is_action(ACTION_MENU_DOWN, ACTION_PRESSED) || is_action(ACTION_MENU_UP, ACTION_PRESSED); + holdInputTimer = isHeld ? holdInputTimer + 1 : 0; +} + +// 008e3db0 Draws the paper, the controller's tab glyph, and each mod's number and name: black when on, grey when off, +// red with [Old] when outdated, with the cursor by the selected one. While mods are off every name is grey (outdated +// ones pink) and there is no cursor. The view then scrolls to keep the cursor in sight. +// The original runs this every frame on any menu, so the view keeps moving, and outside this menu toward its place. +void Menu_Mods::Render() +{ + MenuManager& menus = *g_menuManager; + std::vector>& mods = g_manager->modManager.mods; + bool isModsEnabled = g_manager->optionsConfig.isModsEnabled; + Vector origin = paper_origin_get(position); + int modCount = (int)mods.size(); + + paper_top_render(modsMenuSprite, origin); + const NullFrame* button = modsMenuSprite.GetNullFrame(WIDGET_BUTTON_NULL); + if (g_menuControllerIndex != KEYBOARD_DEVICE && button) + g_manager->render_controller_action_glyph( + {.position = vector_add(origin, button->pos), .action = ACTION_MENU_TAB, .controllerIndex = g_menuControllerIndex}); + paper_render(modsMenuSprite, origin, modCount); + + for (int row = 0; row < modCount; row++) + { + ModEntry& mod = *mods[row]; + KColor color = isModsEnabled && mod.isEnabled ? BLACK : kcolor_argb(DISABLED_ARGB); + if (mod.isOutdated) color = isModsEnabled ? OUTDATED_COLOR : OUTDATED_OFF_COLOR; + + paper_row_render(paper_row_text(row, mod.name, mod.isOutdated ? OUTDATED_SUFFIX : ""), origin, row, color); + if (isModsEnabled && row == selectedMod) paper_cursor_render(modsMenuSprite, origin, row); + } + + menus.viewPositionSet[MENU_MODS].y = paper_view_y_get(selectedMod, modCount); + menus.isViewMoving = true; +} diff --git a/src/menu_mods.h b/src/menu_mods.h new file mode 100644 index 0000000..f2f4133 --- /dev/null +++ b/src/menu_mods.h @@ -0,0 +1,35 @@ +#pragma once + +#include "anm2.h" +#include +#include + +// The mods menu (Menu_Mods): the installed mods numbered on a torn paper, confirm turning the selected one on or off +// and the tab turning every mod on or off at once. Leaving it for the game menu after a change reloads the mods and the +// save. +class Menu_Mods +{ +public: + ANM2 modsMenuSprite; + Vector position{}; + int holdInputTimer = 0; + int selectedMod = 0; + bool isChanged = false; + + void Init(Vector menuPosition); + void LoadGraphics(); + void reset(); + void Update(); + void Render(); +}; + +// The torn paper list the mods' menus share (Menu_Mods and Menu_CustomChallenge): numbered rows on a paper as long as +// they need, a cursor by the selected row, and the view scrolled to keep it in sight. +Vector paper_origin_get(Vector menuPosition); +void paper_reset(ANM2& sprite); +void paper_top_render(ANM2& sprite, Vector origin); +void paper_render(ANM2& sprite, Vector origin, int rowCount); +std::string paper_row_text(int row, std::string_view name, std::string_view suffix = {}); +void paper_row_render(std::string_view text, Vector origin, int row, KColor color); +void paper_cursor_render(ANM2& sprite, Vector origin, int row); +float paper_view_y_get(int selectedRow, int rowCount); diff --git a/src/menu_options.cpp b/src/menu_options.cpp index b7aba39..0268158 100644 --- a/src/menu_options.cpp +++ b/src/menu_options.cpp @@ -27,7 +27,6 @@ constexpr const char* ANIMATION_PAPER_BOTTOM = "PaperBottom"; constexpr const char* ROWS_NULL = "OptionPositions"; constexpr const char* COLORS_LAYER = "OnOff2"; constexpr const char* LOADING_KEY = "#LOADING"; -constexpr char STRING_KEY_PREFIX = '#'; constexpr char CATEGORY_SEPARATOR = '/'; constexpr int LAYER_NONE = -1; @@ -517,8 +516,12 @@ void Menu_Options::language_reload() if (menus) menus->unload_graphics(); pause_screen_unload_sprites(); if (g_game) - reconstruction_missing("Menu_Options::Update 009b23a0: the run's HUD, prompt and stages.xml reload " - "(Game::ReloadStagesXmlOnLuaReset 006f3c00), which game.h does not declare"); + { + g_game->hud.unload_graphics(); + g_game->genericPrompt.sprite.Reset(); + g_game->genericPrompt.isOnlineVote = false; + g_game->completionWidgetSprite.Reset(); + } log_printf(LOG_INFO, "Lua is resetting!\n"); lua.destroy(); lua.Init(lua.mode); @@ -529,6 +532,7 @@ void Menu_Options::language_reload() g_manager->validate_language(); if (menus) menus->LoadGraphics(); graphics_reload(); + if (g_game) Game::ReloadStagesXmlOnLuaReset(); mods.LoadShaders(); Manager::unload_configs(); mods.LoadModContent(); diff --git a/src/menu_special_seeds.cpp b/src/menu_special_seeds.cpp index eccb1cd..742b29d 100644 --- a/src/menu_special_seeds.cpp +++ b/src/menu_special_seeds.cpp @@ -11,7 +11,6 @@ constexpr const char* SEEDS_MENU_ANM2 = "gfx/ui/main menu/SeedsMenu.anm2"; constexpr const char* SEED_MENU_XML = "seedmenu.xml"; constexpr const char* SEED_MENU_CATEGORY = "SeedMenu"; constexpr std::string_view NUM_SEEDS_TAG = "{numseeds}"; -constexpr char STRING_KEY_PREFIX = '#'; // seedmenu.xml: the entry dialog's texts and the list's lines. constexpr std::string_view DIALOG_TAG = "entryDialog"; @@ -61,7 +60,6 @@ constexpr uint32_t TEXT_BLOCKED_ARGB = 0xffbdb5b3; // The view follows the cursor below this height. Held directions repeat after a delay, and dyslexia scrambles the // names for a while after it is turned on. constexpr float VIEW_FOLLOW_Y = 135; -constexpr float CHALLENGE_VIEW_Y = -216; constexpr int KEY_REPEAT_DELAY = 29; constexpr int KEY_REPEAT_INTERVAL = 5; constexpr int DYSLEXIA_TIME = 30; diff --git a/src/minimap.cpp b/src/minimap.cpp index e10bfb6..61a9aba 100644 --- a/src/minimap.cpp +++ b/src/minimap.cpp @@ -87,7 +87,6 @@ constexpr int ICON_RESTOCK = 4; constexpr int ICON_MIND = 5; constexpr int SPEED_TIME_LIMIT = 28800; -constexpr int FRAMES_PER_SECOND = 30; constexpr int FRAMES_PER_MINUTE = FRAMES_PER_SECOND * 60; constexpr int FRAMES_PER_HOUR = FRAMES_PER_MINUTE * 60; constexpr int BLINK_PERIOD = 8; diff --git a/src/mod_manager.cpp b/src/mod_manager.cpp index 7503af1..f4b90fa 100644 --- a/src/mod_manager.cpp +++ b/src/mod_manager.cpp @@ -41,7 +41,6 @@ constexpr const char* STB_EXTENSION = "stb"; constexpr size_t XML_EXTENSION_LENGTH = 3; constexpr const char* DEFAULT_VERSION = "1.0"; -constexpr const char* DOCUMENT_TAG = "#document"; constexpr const char* FRAGMENT_TAG = "fragment"; constexpr const char* ID_ATTRIBUTE = "id"; constexpr const char* METADATA_TAG = "metadata"; @@ -518,6 +517,17 @@ void ModEntry::WriteMetadata() file << "{\"tag\":\"metadata\",\"children\":[" << children << "]}"; } +// Writes disable.it into the mod's folder while the mod is off, and removes it once it is on (inlined in +// Menu_Mods::Update). +void ModEntry::disable_marker_save() +{ + std::string path = resource_path(MODS_FOLDER + directory + DISABLE_MARKER); + std::error_code error; + + if (isEnabled) std::filesystem::remove(path, error); + else std::ofstream file(path); +} + // 008f9e50 Loads a content sprite slot from the mod's content folder, when the mod has that file. void ModEntry::load_content_anm2(ModContentSprite slot, std::string_view relativePath) { diff --git a/src/mod_manager.h b/src/mod_manager.h index ca0e527..3707c37 100644 --- a/src/mod_manager.h +++ b/src/mod_manager.h @@ -83,6 +83,7 @@ struct ModEntry std::string GetContentPath(std::string_view fileName); void WriteMetadata(); + void disable_marker_save(); void load_content_anm2(ModContentSprite slot, std::string_view relativePath); void load_menu_sprites(); }; diff --git a/src/music_manager.cpp b/src/music_manager.cpp index e149505..969fd37 100644 --- a/src/music_manager.cpp +++ b/src/music_manager.cpp @@ -29,7 +29,6 @@ constexpr float DIZZY_WOBBLE_DEPTH = 0.05f; constexpr double RED_ROOM_WOBBLE_SPEED = 0.009999999776482582; constexpr float RED_ROOM_WOBBLE_DEPTH = 0.002f; constexpr int32_t ROOM_FLAG_RED_ROOM = 1 << 10; -constexpr std::string_view DOCUMENT_TAG = "#document"; // A seed effect that sets the music's pitch, and the pitch. struct SeedPitch diff --git a/src/music_manager.h b/src/music_manager.h index ac8963d..27944b7 100644 --- a/src/music_manager.h +++ b/src/music_manager.h @@ -71,6 +71,10 @@ enum MusicId : int MUSIC_MOTHER_BOSS = 43, MUSIC_DOGMA_BOSS = 44, MUSIC_BEAST_BOSS = 45, + MUSIC_JINGLE_DOGMA_OVER = 48, + MUSIC_JINGLE_BEAST_OVER = 49, + MUSIC_MOTHERS_SHADOW_INTRO = 66, + MUSIC_MINESHAFT_ESCAPE = 117, MUSIC_PLANETARIUM = 50, MUSIC_SECRET_ROOM_ALT_ALT = 51, MUSIC_BOSS_OVER_TWISTED = 52, diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index 8c7291e..e493c76 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -14,51 +14,6 @@ #include "entity_player_characters.h" #include "tainted_characters.h" -// The Beast's forms, by variant: its stalactites, rocks and soul, the four ultra horsemen and their summons, and -// the background beasts. -static void beast_update(Entity_NPC& npc) -{ - switch (npc.variant) - { - case 1: - return NpcAI::ENTITY_BEAST_stalactite(&npc); - case 2: - return NpcAI::ENTITY_BEAST_rock_projectile(&npc); - case 3: - return NpcAI::ENTITY_BEAST_soul(&npc); - case 10: - return NpcAI::ENTITY_BEAST_ultra_famine(&npc); - case 11: - return NpcAI::ENTITY_BEAST_ultra_famine_fly(&npc); - case 20: - return NpcAI::ENTITY_BEAST_ultra_pestilence(&npc); - case 21: - return NpcAI::ENTITY_BEAST_pestilence_fly(&npc); - case 22: - return NpcAI::ENTITY_BEAST_ultra_pestilence_maggot(&npc); - case 23: - return NpcAI::ENTITY_BEAST_ultra_pestilence_fly_ball(&npc); - case 30: - return NpcAI::ENTITY_BEAST_ultra_war(&npc); - case 31: - return NpcAI::ENTITY_BEAST_ultra_war_bomb(&npc); - case 40: - return NpcAI::ENTITY_BEAST_ultra_death(&npc); - case 41: - return NpcAI::ENTITY_BEAST_ultra_death_scythe(&npc); - case 42: - return NpcAI::ENTITY_BEAST_ultra_death_head(&npc); - case 100: - case 101: - case 102: - case 103: - case 104: - return NpcAI::ENTITY_BEAST_background(&npc); - default: - return NpcAI::ENTITY_BEAST(&npc); - } -} - // A heart spawned for a Mask, charmed with it. static Entity* mask_heart_spawn(Entity_NPC& npc, Vector position, int subType, uint32_t seed, bool isCharmed) { @@ -128,6 +83,47 @@ static void mask_heart_pair(Entity_NPC& npc) npc.isInvincible = true; } +// Part of 006c2990: Clutch's orbitals (921, its other variants) pick an idle look and circle 50 from Clutch, +// turning 5 a frame, catching up at 0.15 of the gap up to 2. They go with Clutch. +constexpr int CLUTCH_ORBITAL_LOOKS = 8; +constexpr float CLUTCH_ORBIT_RADIUS = 50; +constexpr float CLUTCH_ORBIT_STILL = 0.1f; +constexpr float CLUTCH_ORBIT_SHARE = 0.15f; +constexpr float CLUTCH_ORBIT_SPEED = 2; +constexpr float CLUTCH_ORBIT_FRICTION = 0.8f; +constexpr float CLUTCH_ORBIT_TURN = 5; + +static void clutch_orbital_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.subtype = (int)(Random() & (CLUTCH_ORBITAL_LOOKS - 1)); + npc.sprite.Play("Idle" + std::to_string(std::min(npc.subtype, CLUTCH_ORBITAL_LOOKS - 1))); + npc.AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.state = NPC_STATE_IDLE; + return; + } + if (npc.state != NPC_STATE_IDLE) return; + + Entity* clutch = npc.parent.get(); + if (!clutch || clutch->isDead) return npc.Kill(EntityRef()); + Vector gap = vector_sub(vector_add(clutch->pos, vector_scale(vector_from_angle(npc.v1.x), CLUTCH_ORBIT_RADIUS)), npc.pos); + float distance = vector_length(gap); + float share = distance < CLUTCH_ORBIT_STILL ? 0 : std::min(distance * CLUTCH_ORBIT_SHARE, CLUTCH_ORBIT_SPEED) / distance; + npc.velocity = vector_add(npc.velocity, vector_scale(gap, share * npc.speedMultiplier)); + npc.friction *= CLUTCH_ORBIT_FRICTION; + npc.v1.x = normalize_angle_degrees(npc.speedMultiplier * CLUTCH_ORBIT_TURN + npc.v1.x); +} + +// Part of 006c2990: Cadavra (922) only takes its green splat. +static void cadavra_update(Entity_NPC& npc) +{ + if (npc.state != NPC_STATE_INIT) return; + npc.splatColor = COLOR_GREEN_SPLAT; + npc.state = NPC_STATE_IDLE; +} + // The AI routine of each NPC type. Types it does not list (the ones the game left without an AI) do nothing. static void npc_ai_routine_run(Entity_NPC& npc) { @@ -499,7 +495,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 413: return (void)NpcAI::ENTITY_MATRIARCH(&npc); case 802: - return (void)NpcAI::ENTITY_BLOOD_PUPPY(&npc); + return npc_blood_puppy_update(npc); case 804: return npc_quake_grimace_update(npc); case 805: @@ -521,7 +517,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 814: return npc_strider_update(npc); case 815: - return (void)NpcAI::ENTITY_FISSURE(&npc); + return npc_fissure_update(npc); case 816: return (void)NpcAI::ENTITY_POLTY(&npc); case 818: @@ -561,7 +557,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 837: return npc_henry_update(npc); case 838: - return (void)NpcAI::ENTITY_WILLO_L2(&npc); + return npc_willo_l2_update(npc); case 841: return npc_revenant_update(npc); case 844: @@ -577,13 +573,13 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 854: return npc_adult_leech_update(npc); case 855: - return (void)NpcAI::ENTITY_CHARGER_L2(&npc); + return npc_charger_l2_update(npc); case 856: return npc_gasbag_update(npc); case 857: - return (void)NpcAI::ENTITY_COHORT(&npc); + return npc_cohort_update(npc); case 860: - return (void)NpcAI::ENTITY_UNBORN(&npc); + return npc_unborn_update(npc); case 861: return npc_pustule_update(npc); case 863: @@ -595,7 +591,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 866: return npc_dark_esau_update(npc); case 867: - return (void)NpcAI::ENTITY_MOTHERS_SHADOW(&npc); + return boss_mothers_shadow_update(npc); case 868: return npc_army_fly_update(npc); case 873: @@ -639,19 +635,15 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 892: return npc_poofer_update(npc); case 893: - return (void)NpcAI::ENTITY_BALL_AND_CHAIN(&npc); + return npc_ball_and_chain_update(npc); case 900: return boss_reap_creep_update(npc); case 901: return (void)NpcAI::ENTITY_LIL_BLUB(&npc); case 902: - return (void)NpcAI::ENTITY_RAINMAKER(&npc); + return boss_rainmaker_update(npc); case 903: - if (npc.variant == 0) return NpcAI::ENTITY_VISAGE(&npc); - if (npc.variant == 1) return NpcAI::ENTITY_VISAGE_mask(&npc); - if (npc.variant == 10) return NpcAI::ENTITY_VISAGE_chain(&npc); - if (npc.variant == 20) return NpcAI::ENTITY_VISAGE_plasma(&npc); - return; + return boss_visage_update(npc); case 904: return (void)NpcAI::ENTITY_SIREN(&npc); case 905: @@ -673,7 +665,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 913: return boss_min_min_update(npc); case 914: - return (void)NpcAI::ENTITY_CLOG(&npc); + return boss_clog_update(npc); case 915: return npc.variant == 1 ? NpcAI::ENTITY_SINGE_ball(&npc) : NpcAI::ENTITY_SINGE_body(&npc); case 916: @@ -683,21 +675,18 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 918: return boss_turdlet_update(npc); case 919: - return (void)NpcAI::ENTITY_RAGLICH(&npc); + return boss_raglich_update(npc); case 920: return boss_horny_boys_update(npc); case 921: if (npc.variant == 0) return NpcAI::ENTITY_CLUTCH(&npc); - reconstruction_missing("npc_ai_update 006c2990: Clutch's orbitals"); + return clutch_orbital_update(npc); case 922: - reconstruction_missing("npc_ai_update 006c2990: Cadavra's green splat"); + return cadavra_update(npc); case 950: - if (npc.variant == 1) return NpcAI::ENTITY_DOGMA_tv(&npc); - if (npc.variant == 2) return NpcAI::ENTITY_DOGMA_angel(&npc); - if (npc.variant == 10) return (void)NpcAI::ENTITY_DOGMA_angel_baby(&npc); - return NpcAI::ENTITY_DOGMA(&npc); + return boss_dogma_update(npc); case 951: - return beast_update(npc); + return boss_beast_update(npc); case 960: return npc_generic_prop_update(npc); case 965: @@ -705,7 +694,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 966: return (void)NpcAI::ENTITY_SIREN_HELPER(&npc); case 967: - return NpcAI::ENTITY_HORNFEL_DOOR(&npc); + return hornfel_door_update(npc); default: return; } diff --git a/src/npc_ai.h b/src/npc_ai.h index 39ef48e..42b2c99 100644 --- a/src/npc_ai.h +++ b/src/npc_ai.h @@ -62,6 +62,9 @@ constexpr int RAGLING_RAG_MAN = 1; constexpr int KNIGHT_BLACK = 4; constexpr int DANGLE = 1; +// The Cultist's blood pool (its Bone Trap variant), which nothing hunts. +constexpr int CULTIST_POOL = 10; + // Evis' cord (its variant 10), the Peeping Fatty's eyes (its first two queued entities) and the Gutted Fatty's // Festering Guts (its variant 20). constexpr int EVIS_CORD = 10; diff --git a/src/npc_alt.h b/src/npc_alt.h index f2f03a9..477f78a 100644 --- a/src/npc_alt.h +++ b/src/npc_alt.h @@ -49,6 +49,12 @@ void npc_fatty_wander(Entity_NPC& npc); Vector npc_weave_direction_get(Entity_NPC& npc); void npc_bloaty_update(Entity_NPC& npc); void npc_rotten_gaper_update(Entity_NPC& npc); +void npc_unborn_update(Entity_NPC& npc); +void npc_charger_l2_update(Entity_NPC& npc); +void npc_willo_l2_update(Entity_NPC& npc); +void npc_fissure_update(Entity_NPC& npc); +void npc_blood_puppy_update(Entity_NPC& npc); +void npc_ball_and_chain_update(Entity_NPC& npc); // The walks Entity_NPC::anim_walk_frame_4dir picks between (its arguments): left, right, up and down, and the speed // below which it stands. diff --git a/src/npc_ball_and_chain.cpp b/src/npc_ball_and_chain.cpp new file mode 100644 index 0000000..e1c8149 --- /dev/null +++ b/src/npc_ball_and_chain.cpp @@ -0,0 +1,322 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_player.h" +#include "grid_entity.h" +#include +#include + +// The Ball and Chain: a spiked ball chained to a rock beside it, swung around it at a radius and speed its subtype +// sets ((subtype & 15) + 1 cells, (subtype >> 4 & 15) half degrees a tick, reversed by bit 8), crushing the rocks it +// passes. When its rock goes it snaps its chain and rolls free, bouncing and dropping into pits. Two Flat Files retract +// its spikes. +constexpr float CHAIN_ANCHOR_OFFSETS[4][2] = {{0, -40}, {0, 40}, {-40, 0}, {40, 0}}; +constexpr uint32_t CHAIN_LENGTH_MASK = 0xf; +constexpr uint32_t CHAIN_SPEED_SHIFT = 4; +constexpr uint32_t CHAIN_REVERSED = 0x100; +constexpr float CHAIN_SPEED_STEP = 0.5f; +constexpr int BALL_CHAIN_LAYER = 1; +constexpr int SPIKE_LAYER = 2; +constexpr unsigned int CHAIN_WRAP_REPEAT = 1; +constexpr float BALL_LIFT = -14; +constexpr float BALL_DROP_HEIGHT = -10; +constexpr float BALL_DROP_SPEED = -6; +constexpr float BALL_SPIN_SHARE = 0.0005f; +constexpr float BALL_SPIN_MAX = 0.1f; +constexpr float BALL_FACING_STEP = 45; +constexpr int BALL_FACINGS = 8; +constexpr int CHAIN_FACINGS = 4; +constexpr float BALL_DUST_INTERVAL = 2; +constexpr float BALL_DUST_ODDS_SCALE = 10; +constexpr float BALL_DUST_DRAG_SHARE = 0.2f; +constexpr float BALL_DUST_SPIN_MIN = 2; +constexpr float BALL_DUST_SPIN_RANGE = 10; +constexpr int BALL_DUST_TIMEOUT_MIN = 15; +constexpr int BALL_DUST_TIMEOUT_SPREAD = 15; +constexpr float BALL_DUST_SCALE_MIN = 0.3f; +constexpr float BALL_DUST_SCALE_RANGE = 0.3f; +constexpr ColorMod BALL_DUST_COLOR = {{0.45f, 0.45f, 0.45f, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float CHAIN_GIB_STEPS = 12; +constexpr float CHAIN_GIB_GAP = 20; +constexpr float CHAIN_GIB_SPEED_MIN = 2; +constexpr float CHAIN_GIB_SPEED_RANGE = 6; +constexpr float TINY_BALL_PITCH = 1.5f; +constexpr float GIANT_BALL_PITCH = 0.5f; +constexpr float BALL_BREAK_FLING = 3; +constexpr float BALL_HIGH = -50; +constexpr float BALL_GRAVITY = 0.8f; +constexpr float BALL_SUNK = 10; +constexpr float BALL_STOP_BOUNCE = 4; +constexpr float BALL_BOUNCE_VOLUME_SHARE = 0.1f; +constexpr float BALL_BOUNCE_VOLUME_MIN = 0.2f; +constexpr float BALL_BOUNCE_VOLUME_MAX = 1.2f; +constexpr float BALL_BOUNCE_PITCH_MIN = 0.9f; +constexpr float BALL_BOUNCE_PITCH_RANGE = 0.2f; +constexpr float BALL_BOUNCE_KEEP = -0.35f; +constexpr float BALL_ROLL_SPEED_SQUARED = 4; +constexpr float BALL_ROLL_MIN = 0.5f; +constexpr float BALL_ROLL_RANGE = 3.5f; +constexpr float BALL_ROLL_SHARE = 0.02f; +constexpr float BALL_ROLL_DRAG = 0.86f; +constexpr float BALL_ROLL_DRAG_RANGE = 0.13f; +constexpr float BALL_CRUSH_SPEED_SQUARED = 16; +constexpr float BALL_CRUSH_REACH = 1.05f; +constexpr int FLAT_FILE_RETRACT = 2; +constexpr float BALL_SPIKE_DAMAGE = 2; +constexpr std::string_view BALL_SHEET = "gfx/Monsters/repentance/ball_and_chain.png"; +constexpr std::string_view BALL_RETRACTED_SHEET = "gfx/Monsters/repentance/ball_and_chain_retracted.png"; + +// A rock or wall it may hang from: solid, or a wall that is not the room's outer wall. +static bool chain_anchor_is_valid(GridEntity* grid) +{ + return grid && (grid->collisionClass == COLLISION_SOLID || (grid->collisionClass == COLLISION_WALL && grid->type != GRID_WALL)); +} + +// Turns a fraction back into [0, 1). +static float unit_wrap(float value) +{ + while (value < 0) value += 1; + while (value >= 1) value -= 1; + return value; +} + +// Shows the frame of a facing animation ("Idle0" to "Idle7") a direction in degrees falls in, still, turned by the rest. +static void ball_facing_show(Entity_NPC& npc, float degrees, float turn) +{ + int facing = (int)std::floor(normalize_angle_degrees(degrees) / BALL_FACING_STEP + HALF); + if (facing < 0) facing += BALL_FACINGS; + std::string name = "Idle" + std::to_string(facing); + bool isShown = npc.sprite.animState.animData && npc.sprite.animState.animData->name == name; + if (!isShown && npc.sprite.SetAnimation(name, SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + if (npc.sprite.animState.animData) npc.sprite.animState.isPlaying = false; + } + npc.sprite.rotation = turn - (float)facing * BALL_FACING_STEP; +} + +// Its first frame: it hangs from the first rock beside it (above, below, left, right) at its chain's length, or drops +// free. It is untouchable and out of the players' control. +static void ball_start(Entity_NPC& npc, float radius) +{ + Room& room = *g_game->room; + npc.i1 = -1; + npc.i2 = 0; + for (const auto& offset : CHAIN_ANCHOR_OFFSETS) + { + int cell = room.GetGridIndex(vector_add(npc.pos, vector_make(offset[0], offset[1]))); + GridEntity* grid = cell >= 0 && cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; + if (!chain_anchor_is_valid(grid)) continue; + npc.targetPosition = room.GetGridPosition(grid->gridIndex); + npc.i1 = grid->gridIndex; + break; + } + + if (npc.sprite.SetOverlayAnimation("Chain", SWITCH_KEEP_FRAME) && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); + if (npc.sprite.SetAnimation("Idle0", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + if (npc.sprite.animState.animData) npc.sprite.animState.isPlaying = false; + } + LayerState* chain = npc.sprite.GetLayer(BALL_CHAIN_LAYER); + chain->isVisible = false; + chain->wrapSMode = CHAIN_WRAP_REPEAT; + chain->wrapTMode = 0; + npc.sprite.GetLayer(SPIKE_LAYER)->isVisible = false; + npc.AddEntityFlags(FLAG_HIDE_HP_BAR | FLAG_NO_PLAYER_CONTROL | FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | + FLAG_NO_BLOOD_SPLASH | FLAG_NO_DEATH_TRIGGER); + npc.ClearEntityFlags(FLAG_APPEAR); + npc.isInvincible = true; + npc.state = NPC_STATE_IDLE; + + if (vector_is_zero(npc.targetPosition)) + { + npc.v1 = vector_make(0, BALL_DROP_SPEED); + npc.v2.y = BALL_DROP_HEIGHT; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + } + else + { + float angle = vector_angle(vector_sub(npc.pos, npc.targetPosition)); + npc.v1 = vector_make(angle, 0); + npc.pos = vector_add(npc.targetPosition, vector_scale(vector_from_angle(angle), radius)); + npc.entityGridCollisionClass = GRIDCOLL_NONE; + } + npc.posOffset = vector_make(0, BALL_LIFT); +} + +// Hung from its rock: it swings around it, spinning the ball by its speed and showing the chain's quarter, and kicks +// up dust off the floor. When the rock goes it snaps the chain in gibs and drops, flung on at three times its speed, +// dying outside the room. +static void ball_swing(Entity_NPC& npc, float speed) +{ + Room& room = *g_game->room; + ball_facing_show(npc, npc.v1.x, npc.v1.x); + if (const AnimationData* data = npc.sprite.animState.animData) + npc.sprite.animState.SetFrameFloat((float)(int)((float)data->length * npc.v1.y)); + int quarter = (int)std::floor(normalize_angle_degrees(npc.v1.x) / RIGHT_ANGLE_DEGREES + HALF); + if (quarter < 0) quarter += CHAIN_FACINGS; + if (npc.sprite.overlayAnimState.animData) npc.sprite.overlayAnimState.SetFrameFloat((float)quarter); + + if (npc.GetIntervalTicks(BALL_DUST_INTERVAL, 0) != 0 && room.GetGridCollision(room.GetGridIndex(npc.pos)) == COLLISION_NONE && + random_unit() * BALL_DUST_ODDS_SCALE < std::abs(speed)) + { + uint32_t seed = Random(); + Vector drag = vector_scale(npc.velocity, BALL_DUST_DRAG_SHARE); + Vector puff = vector_add(random_direction(), drag); + auto* dust = static_cast(g_game->Spawn( + {.position = npc.pos, .velocity = puff, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = seed})); + dust->rotation = random_between(BALL_DUST_SPIN_MIN, BALL_DUST_SPIN_RANGE); + int timeout = (int)(Random() % BALL_DUST_TIMEOUT_SPREAD) + BALL_DUST_TIMEOUT_MIN; + dust->timeout = timeout; + dust->lifespan = timeout; + dust->SetColor(BALL_DUST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + float scale = random_between(BALL_DUST_SCALE_MIN, BALL_DUST_SCALE_RANGE); + dust->sprite.scale = vector_make(scale, scale); + } + + if (npc.i1 < 0) return; + if (npc.i1 < ROOM_GRID_CELLS && chain_anchor_is_valid(room.gridEntities[npc.i1])) return; + + npc.i1 = -1; + Vector along = vector_sub(npc.targetPosition, npc.pos); + float length = vector_length(along); + if (length > 0) + { + float step = std::max(length / CHAIN_GIB_STEPS, CHAIN_GIB_GAP); + Vector direction = vector_scale(along, 1 / length); + for (float at = 0; at < length; at += step) + { + uint32_t seed = Random(); + Vector heading = random_direction(); + Vector fling = vector_scale(heading, random_between(CHAIN_GIB_SPEED_MIN, CHAIN_GIB_SPEED_RANGE)); + g_game->Spawn({.position = vector_add(npc.pos, vector_scale(direction, at)), .velocity = fling, .type = ENTITY_EFFECT, + .variant = EFFECT_CHAIN_GIB, .seed = seed}) + ->Update(); + } + } + npc.targetPosition = {}; + float pitch = npc.championColorIdx == CHAMPION_TINY ? TINY_BALL_PITCH + : npc.championColorIdx == CHAMPION_GIANT ? GIANT_BALL_PITCH + : 1; + npc_sound_play(SOUND_CHAIN_BREAK, 1, 2, pitch); + if (!room.IsPositionInRoom(npc.pos, 0)) npc.Kill(EntityRef()); + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.v1 = vector_make(0, BALL_DROP_SPEED); + npc.v2.y = BALL_DROP_HEIGHT; + npc.sprite.rotation = 0; + npc.velocity = vector_scale(npc.velocity, BALL_BREAK_FLING); +} + +// Loose: it falls by gravity (untouchable high up, kept off pits while airborne), bounces off the floor with a clank, +// sinks into a pit and goes, and rolls along its way, slowing with its spin. False once it has gone. +static bool ball_roll(Entity_NPC& npc) +{ + Room& room = *g_game->room; + float height = npc.v2.y; + bool isSinking = npc.entityGridCollisionClass == GRIDCOLL_PITSONLY; + if (isSinking) npc.entityCollisionClass = ENTCOLL_NONE; + else + { + npc.entityCollisionClass = height > BALL_HIGH ? ENTCOLL_ALL : ENTCOLL_NONE; + npc.entityGridCollisionClass = height <= -1 || npc.v1.y < 0 ? GRIDCOLL_NOPITS : GRIDCOLL_GROUND; + } + + if (height < 0 || npc.v1.y < 0 || isSinking) + { + height += npc.v1.y * npc.speedMultiplier; + npc.v1.y += npc.speedMultiplier * BALL_GRAVITY; + npc.v2.y = height; + if (isSinking) + { + if (height > BALL_SUNK) + { + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + npc.Remove(); + return false; + } + } + else if (height > 0) + { + if (room.GetGridCollision(room.GetGridIndex(vector_add(npc.pos, npc.velocity))) == COLLISION_PIT) + npc.entityGridCollisionClass = GRIDCOLL_PITSONLY; + else + { + npc.v2.y = 0; + height = 0; + if (npc.v1.y > 0 && npc.v1.y <= BALL_STOP_BOUNCE) npc.v1.y = 0; + else if (npc.v1.y > 0) + { + float pitch = random_between(BALL_BOUNCE_PITCH_MIN, BALL_BOUNCE_PITCH_RANGE); + float volume = std::min(npc.v1.y * BALL_BOUNCE_VOLUME_SHARE + BALL_BOUNCE_VOLUME_MIN, BALL_BOUNCE_VOLUME_MAX); + npc_sound_play(SOUND_BALL_AND_CHAIN_HIT, volume, 2, pitch); + npc.v1.y *= BALL_BOUNCE_KEEP; + } + } + } + } + npc.posOffset.y = height + BALL_LIFT; + + float speedSquared = vector_length_squared(npc.velocity); + if (speedSquared > BALL_ROLL_SPEED_SQUARED) + { + float heading = vector_angle(npc.velocity) + RIGHT_ANGLE_DEGREES; + ball_facing_show(npc, heading, heading); + } + float roll = std::sqrt(npc.v1.y * npc.v1.y + speedSquared); + float drag = std::clamp((roll - BALL_ROLL_MIN) / BALL_ROLL_RANGE, 0.0f, 1.0f); + npc.v1.x = unit_wrap(roll * BALL_ROLL_SHARE + npc.v1.x); + npc.friction *= drag * BALL_ROLL_DRAG_RANGE + BALL_ROLL_DRAG; + const AnimationData* data = npc.sprite.animState.animData; + if (data && (int)((float)data->length * npc.v1.x) != (int)std::floor(npc.sprite.animState.animFrame)) + npc.sprite.animState.SetFrameFloat((float)(int)((float)data->length * npc.v1.x)); + return true; +} + +// Hung or rolling fast, it breaks the rocks and blocks its body meets, but its own rock. +static void ball_crush(Entity_NPC& npc) +{ + Room& room = *g_game->room; + for (const Vector& point : npc.collisionPoints) + { + int cell = room.GetGridIndex(vector_add(npc.pos, vector_scale(point, BALL_CRUSH_REACH))); + GridEntity* grid = cell >= 0 && cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; + if (!grid || grid->gridIndex == npc.i1) continue; + if (grid->collisionClass == COLLISION_SOLID || grid->collisionClass == COLLISION_OBJECT) grid->Destroy(false, EntityRef(&npc)); + } +} + +// 004f4730 The Ball and Chain's AI. +void npc_ball_and_chain_update(Entity_NPC& npc) +{ + float radius = (float)((npc.subtype & CHAIN_LENGTH_MASK) + 1) * GRID_CELL_SIZE; + float speed = (float)(((uint32_t)npc.subtype >> CHAIN_SPEED_SHIFT) & CHAIN_LENGTH_MASK) * CHAIN_SPEED_STEP; + if (npc.subtype & CHAIN_REVERSED) speed = -speed; + + if (npc.state == NPC_STATE_INIT) ball_start(npc, radius); + else if (npc.state == NPC_STATE_IDLE && !vector_is_zero(npc.targetPosition)) + { + npc.v1.x = normalize_angle_degrees(speed * npc.speedMultiplier + npc.v1.x); + float spin = std::clamp(speed * BALL_SPIN_SHARE * radius, -BALL_SPIN_MAX, BALL_SPIN_MAX); + npc.v1.y = unit_wrap(npc.v1.y - spin); + npc.velocity = vector_sub(vector_add(npc.targetPosition, vector_scale(vector_from_angle(npc.v1.x), radius)), npc.pos); + } + + if (!vector_is_zero(npc.targetPosition)) ball_swing(npc, speed); + else if (!ball_roll(npc)) return; + if (!vector_is_zero(npc.targetPosition) || vector_length_squared(npc.velocity) > BALL_CRUSH_SPEED_SQUARED) ball_crush(npc); + + Entity_Player* filer = g_game->playerManager.FirstTrinketOwner(TRINKET_FLAT_FILE); + bool isRetracted = filer && filer->GetTrinketMultiplier(TRINKET_FLAT_FILE) >= FLAT_FILE_RETRACT; + if ((npc.i2 != 0) == isRetracted) return; + + npc.i2 = 1 - npc.i2; + npc.collisionDamage = npc.i2 == 0 ? BALL_SPIKE_DAMAGE : 0; + std::string_view sheet = npc.i2 == 0 ? BALL_SHEET : BALL_RETRACTED_SHEET; + if (!npc.sprite.layerStates.empty() && npc.sprite.layerStates[0].spriteSheetPath != sheet) + { + npc.sprite.layerStates[0].spriteSheetPath = sheet; + npc.sprite.layerStates[0].isSpriteSheetLoaded = false; + } + npc.sprite.LoadGraphics(); +} diff --git a/src/npc_basement.h b/src/npc_basement.h index 9b28018..34b1c1e 100644 --- a/src/npc_basement.h +++ b/src/npc_basement.h @@ -30,6 +30,12 @@ void npc_baby_long_legs_update(Entity_NPC& npc); void npc_movable_tnt_update(Entity_NPC& npc); void npc_vis_update(Entity_NPC& npc); +// The suffix of the harmless spider sprites Bursting Sack swaps in (spider_load_graphics), and the Migraine spider's +// death timer. +constexpr std::string_view INERT_SUFFIX = "_inert"; +bool spider_load_graphics(Entity_NPC& npc, std::string_view suffix); +void migraine_timer_spawn(Entity_Effect* timer); + // The Vis' Chubber worm (its variant), which the Fistuloid also spits. constexpr int CHUBBER_WORM = 22; diff --git a/src/npc_blood_puppy.cpp b/src/npc_blood_puppy.cpp new file mode 100644 index 0000000..6906085 --- /dev/null +++ b/src/npc_blood_puppy.cpp @@ -0,0 +1,369 @@ +#include "npc_alt.h" +#include "npc_gehenna.h" +#include "entity_player.h" +#include "boss_ai.h" +#include "capsule.h" +#include "entity_familiar.h" +#include "entity_pickup.h" +#include "room_grid.h" +#include + +// The Blood Puppy (802), the familiar's pet turned enemy (variant 0 small, 1 grown), tied to the familiar it came +// from. It wanders after its target or its prey, dripping blood, and dashes at one in line with it, shoving what it +// hits aside. The grown one breaks rocks into bridges as it dashes. As its familiar gathers coins it grows, hacking up +// a heart. It shrugs off most hits that are not the players'. +constexpr int PUPPY_GROWN = 1; +constexpr int PUPPY_SPAWNING = NPC_STATE_SUMMON; +constexpr int PUPPY_RESET = NPC_STATE_SPECIAL; +constexpr int PUPPY_DASH = NPC_STATE_ATTACK; +constexpr int PUPPY_FAMILIAR_FRAMES = 5; +constexpr float PUPPY_NPC_HIT_SHARE = 0.1f; +constexpr float PUPPY_SHRUGGED_HIT_SHARE = 0.01f; +constexpr uint64_t PUPPY_IGNORED_DAMAGE = DAMAGE_FIRE | DAMAGE_EXPLOSION | DAMAGE_SPIKES | DAMAGE_CRUSH; +constexpr int PUPPY_RESET_COOLDOWN = 30; +constexpr float PUPPY_SPAWN_FRICTION = 0.88f; +constexpr uint32_t PUPPY_JITTER_ODDS = 15; +constexpr float PUPPY_JITTER = 18; +constexpr float PUPPY_BASE_SPEED = 1.2f; +constexpr float PUPPY_GROWN_SLOWDOWN = 0.15f; +constexpr float PUPPY_SPEED_SHARE = 0.83f; +constexpr int PUPPY_UNCONTROLLED_DELAY = 15; +constexpr float PUPPY_BACK_OFF = 80; +constexpr uint32_t PUPPY_SPLAT_MASK = 3; +constexpr float PUPPY_BLOOD_MIN = 0.3f; +constexpr float PUPPY_BLOOD_RANGE = 0.4f; +constexpr float PUPPY_SPLAT_GROWN = 0.3f; +constexpr float PUPPY_FRICTION = 0.9f; +constexpr float PUPPY_RUN_SPEED = 2; +constexpr int PUPPY_FIRST_GROWTH = 25; +constexpr int PUPPY_SECOND_GROWTH = 35; +constexpr int PUPPY_GROWTH_STEP = 10; +constexpr int PUPPY_LAST_GROWTH = 40; +constexpr uint32_t PUPPY_DASH_MASK = 3; +constexpr float PUPPY_LEAD = 0.1f; +constexpr float PUPPY_ALIGN_MARGIN = 18; +constexpr int PUPPY_DASH_COOLDOWN = 30; +constexpr float PUPPY_DASH_SPEED = 5; +constexpr float PUPPY_SMALL_PITCH = 1.1f; +constexpr float PUPPY_GROWN_PITCH = 0.9f; +constexpr float PUPPY_WINDUP_FRICTION = 0.7f; +constexpr float PUPPY_BUMP_SHARE = 0.5f; +constexpr float PUPPY_SHOVE_REACH = 1.2f; +constexpr float PUPPY_SHOVE_SEARCH = 80; +constexpr float PUPPY_SHOVE_PULL = 0.6f; +constexpr float PUPPY_STUCK_DISTANCE = 4; +constexpr int PUPPY_STUCK_FRAMES = 6; +constexpr float PUPPY_OVERSHOOT = -80; +constexpr uint32_t PUPPY_STOP_MASK = 7; +constexpr int PUPPY_STOP_COOLDOWN = 15; +constexpr float PUPPY_DASH_DECAY = 0.1f; +constexpr float PUPPY_DASH_MIN = 3; +constexpr float PUPPY_DASH_FRICTION = 0.85f; +constexpr float PUPPY_HEART_FRICTION = 0.8f; +constexpr float PUPPY_HEART_LIFT = -5; + +// The animation of a facing (up, down or sideways, flipped for left) under a name's prefix. +static void puppy_face_play(Entity_NPC& npc, std::string_view prefix) +{ + std::string_view side = npc.i1 == DIRECTION_UP ? "Up" : npc.i1 == DIRECTION_DOWN ? "Down" : "Hori"; + npc.sprite.Play(std::string(prefix) + " " + std::string(side)); + npc.sprite.isFlipX = npc.i1 == DIRECTION_LEFT; +} + +// Its pre update: it takes its familiar's coins in its first frames and dies without a familiar. It takes a hundredth +// of shots, lasers and other Blood Puppies' hits and a tenth of enemies', and none of the fire, blasts, spikes and +// crushing the players and familiars did not cause. +static void puppy_hits_soften(Entity_NPC& npc) +{ + if (g_game->frameCount - npc.spawnFrame < PUPPY_FAMILIAR_FRAMES && npc.parent && npc.parent->type == ENTITY_FAMILIAR) + npc.i2 = static_cast(npc.parent.get())->coins; + if (npc.type == ENTITY_BLOOD_PUPPY && !npc.isDead && !npc.parent) npc.Kill(EntityRef()); + if (npc.pendingDamage <= 0) return; + + npc.pendingDamage = 0; + for (DamageEvent& event : npc.damageEvents) + { + const EntityRef& source = event.source; + bool isOwnSide = source.IsFriendly() || source.type == ENTITY_PLAYER || source.spawnerType == ENTITY_PLAYER || + source.spawnerType == ENTITY_FAMILIAR; + bool isPuppy = source.type == ENTITY_FAMILIAR && source.variant == Entity_Familiar::BLOOD_PUPPY; + if ((event.damageFlags & PUPPY_IGNORED_DAMAGE) && !isOwnSide && !(event.damageFlags & DAMAGE_TNT)) event.damage = 0; + else if ((event.damageFlags & DAMAGE_LASER) && !source.IsFriendly() && source.type != ENTITY_PLAYER && + source.type != ENTITY_FAMILIAR) + event.damage *= PUPPY_SHRUGGED_HIT_SHARE; + else if (source.type == ENTITY_PROJECTILE || isPuppy || source.type == ENTITY_BLOOD_PUPPY) + event.damage *= PUPPY_SHRUGGED_HIT_SHARE; + else if (source.type != ENTITY_FAMILIAR && Entity::is_enemy_type(source.type) && source.type != ENTITY_PLAYER) + event.damage *= PUPPY_NPC_HIT_SHARE; + npc.pendingDamage += event.damage; + } +} + +// Growing: past 25 and 35 of its familiar's coins, then every ten up to 40, it hacks up a heart. True when it starts. +static bool puppy_grow_check(Entity_NPC& npc) +{ + if (!npc.parent || npc.parent->type != ENTITY_FAMILIAR) return false; + + int coins = static_cast(npc.parent.get())->coins; + if (npc.i2 < PUPPY_FIRST_GROWTH) + { + if (coins < PUPPY_FIRST_GROWTH) return false; + npc.i2 = PUPPY_FIRST_GROWTH; + } + else if (npc.i2 < PUPPY_SECOND_GROWTH) + { + if (coins < PUPPY_SECOND_GROWTH) return false; + npc.i2 = PUPPY_SECOND_GROWTH; + } + else + { + if (npc.i2 / PUPPY_GROWTH_STEP >= coins / PUPPY_GROWTH_STEP) return false; + npc.i2 = coins / PUPPY_GROWTH_STEP * PUPPY_GROWTH_STEP; + if (npc.i2 == PUPPY_LAST_GROWTH) return false; + } + npc_anim_restart(npc.sprite, "Spawn"); + npc.state = PUPPY_SPAWNING; + return true; +} + +// The dash's wind up: in line with its target (or where the target heads, for an enemy) and in sight, it turns to it. +static void puppy_dash_try(Entity_NPC& npc, Entity& target, Vector aim) +{ + Vector lead = aim; + if (target.IsEnemy()) + lead = vector_add(target.pos, vector_scale(target.velocity, vector_distance(npc.pos, target.pos) * PUPPY_LEAD)); + Vector delta = vector_sub(lead, npc.pos); + if (std::min(std::abs(delta.x), std::abs(delta.y)) >= target.size + PUPPY_ALIGN_MARGIN) return; + if (!room_check_line(npc.pos, lead, npc.variant != 0 ? LINE_MODE_EXPLOSION : LINE_MODE_CELL, 0)) return; + + npc.i1 = vector_to_direction(delta); + npc.state = PUPPY_DASH; + bool isQuick = target.IsEnemy() && !target.HasEntityFlags(FLAG_FRIENDLY); + puppy_face_play(npc, isQuick ? "AttackStartQuick" : "AttackStart"); + npc.target = ⌖ + npc.projectileCooldown = PUPPY_DASH_COOLDOWN; +} + +// Wandering after its target, jittering about an enemy one and backing off a player who cannot move (or while it +// waits), dripping blood. It grows when due, or tries a dash one frame in four off cooldown. +static void puppy_wander(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + npc.isVisible = true; + if (anim.animData && anim.isPlaying && !anim.animData->isLooping) + { + npc.friction *= PUPPY_SPAWN_FRICTION; + return; + } + + Vector aim = npc.CalcTargetPosition(0); + Entity* target = npc.GetPlayerTarget(); + Vector targetPos = target->pos; + Entity_Player* player = target->type == ENTITY_FAMILIAR ? static_cast(target)->player + : target->type == ENTITY_PLAYER ? static_cast(target) + : nullptr; + if (target->IsEnemy() && Random() % PUPPY_JITTER_ODDS == 0) + { + Vector direction = random_direction(); + npc.v2 = vector_scale(direction, random_unit() * PUPPY_JITTER); + } + else npc.v2 = {}; + + bool isChasing = true; + float speed = (PUPPY_BASE_SPEED - (float)npc.variant * PUPPY_GROWN_SLOWDOWN) * PUPPY_SPEED_SHARE; + bool isBackingOff = false; + if (player) + { + if (!player->AreControlsEnabled()) npc.projectileDelay = PUPPY_UNCONTROLLED_DELAY; + isBackingOff = !player->AreControlsEnabled() || npc.projectileDelay >= 1; + } + if (isBackingOff) + { + isChasing = false; + npc.pathfinder.FindGridPath(vector_add(aim, vector_resized(vector_sub(npc.pos, aim), PUPPY_BACK_OFF)), speed, 0, DIRECT_PATH_FAR); + } + else if (vector_length_squared(vector_sub(aim, npc.pos)) > 0) + npc.pathfinder.FindGridPath(vector_add(aim, npc.v2), speed, 0, DIRECT_PATH_FAR); + + if ((Random() & PUPPY_SPLAT_MASK) == 0) + npc.MakeSplat(random_unit() * PUPPY_BLOOD_RANGE + PUPPY_BLOOD_MIN + (float)npc.variant * PUPPY_SPLAT_GROWN); + bool isCooled = npc.projectileCooldown < 1 || (npc.projectileCooldown -= npc_ticks_get(npc)) < 1; + if (isCooled && npc.entityCollisionClass == ENTCOLL_NONE) npc.entityCollisionClass = ENTCOLL_ALL; + npc.friction *= PUPPY_FRICTION; + + if (vector_length(npc.velocity) >= PUPPY_RUN_SPEED) + { + npc.i1 = vector_to_direction(npc.velocity); + puppy_face_play(npc, "Move"); + } + else puppy_face_play(npc, "Idle"); + if (puppy_grow_check(npc)) return; + + bool isOnTarget = aim.x == targetPos.x && aim.y == targetPos.y; + if (!isOnTarget || npc.projectileCooldown > 0 || !isChasing || (Random() & PUPPY_DASH_MASK) != 0) return; + puppy_dash_try(npc, *target, aim); +} + +// The grown puppy's dash breaks the rocks its body hits, bridging the pit beyond each. True when one broke. +static bool puppy_rocks_break(Entity_NPC& npc) +{ + Room& room = *g_game->room; + auto gridAt = [&](int cell) { return cell >= 0 && cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; }; + bool isBroken = false; + for (const Vector& point : npc.collisionPoints) + { + int cell = room.GetGridIndex(vector_add(vector_add(npc.pos, vector_scale(npc.gridCollisionVelocity, HALF)), point)); + if (cell < 0) continue; + GridEntity* rock = gridAt(cell); + uint32_t collision = room.GetGridCollision(cell); + if ((collision != COLLISION_SOLID && collision != COLLISION_OBJECT) || !rock || rock->collisionClass != COLLISION_SOLID) + continue; + if (!rock->Destroy(false, EntityRef(&npc))) continue; + + Vector rockPos = room.GetGridPosition(rock->gridIndex); + Vector step = vector_from_direction(axis_direction_get(vector_sub(rockPos, npc.pos))); + int beyond = room.GetGridIndex(vector_add(rockPos, vector_scale(step, GRID_CELL_SIZE))); + if (beyond >= 0) room_bridge_make(gridAt(beyond), rock); + isBroken = true; + } + return isBroken; +} + +// Its dash shoves the enemies and bombs ahead that it meets along with it, toward its leading edge. +static void puppy_shove(Entity_NPC& npc, Vector direction) +{ + float reach = npc.size * PUPPY_SHOVE_REACH; + Capsule body(vector_add(npc.pos, vector_scale(npc.velocity, npc.speedMultiplier)), npc.sizeMulti, 0, reach); + for (Entity* other : entity_query_radius(body.center, reach + PUPPY_SHOVE_SEARCH, QUERY_ENEMIES)) + { + if (other == &npc || other->type == ENTITY_BLOOD_PUPPY) continue; + if (other->entityCollisionClass != ENTCOLL_ALL && other->entityCollisionClass != ENTCOLL_ENEMIES) continue; + if (vector_dot(direction, vector_sub(other->pos, npc.pos)) <= 0) continue; + + Capsule shape(other->pos, other->sizeMulti, other->sprite.rotation, other->size); + shape.center = vector_add(shape.center, vector_scale(other->velocity, other->speedMultiplier)); + Vector hit{}; + bool isShovable = Entity::is_enemy_type(other->type) || other->type == ENTITY_BOMB; + if (!Capsule::Collide(body, shape, &hit) || !isShovable) continue; + + float keep = timescale_factor(PUPPY_SHOVE_PULL, npc.speedMultiplier); + other->velocity = vector_add(other->velocity, vector_scale(vector_sub(npc.velocity, other->velocity), keep)); + if (other->friction == 0) continue; + Vector edge = vector_add(body.center, vector_scale(direction, other->size)); + float pull = PUPPY_SHOVE_PULL * other->speedMultiplier / other->friction; + other->velocity = vector_add(other->velocity, vector_scale(vector_sub(edge, other->pos), pull)); + } +} + +// The dash: once its wind up ends it charges along its facing, slowing to 3, and stops when stuck for 6 frames. The +// grown one may also pull up short of an enemy target it passed by 80. +static void puppy_dash(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + if (!anim.animData || !anim.isPlaying) + { + puppy_face_play(npc, "Attack"); + npc.targetPosition = npc.pos; + npc.stateFrame = 0; + npc.v1.x = PUPPY_DASH_SPEED; + npc_sound_play(SOUND_MONSTER_ROAR_0, 1, 2, npc.variant == 0 ? PUPPY_SMALL_PITCH : PUPPY_GROWN_PITCH); + } + if (!anim.animData || !anim.animData->isLooping) + { + npc.friction *= PUPPY_WINDUP_FRICTION; + return; + } + + Vector direction = vector_from_direction(npc.i1); + if (npc.isCollidesWithGrid && npc.variant == PUPPY_GROWN && puppy_rocks_break(npc)) + { + npc.stateFrame = 0; + npc.velocity = vector_scale(npc.gridCollisionVelocity, PUPPY_BUMP_SHARE); + } + puppy_shove(npc, direction); + + bool isDone = false; + if (vector_length_squared(vector_sub(npc.pos, npc.targetPosition)) < PUPPY_STUCK_DISTANCE * npc.speedMultiplier * npc.speedMultiplier) + { + npc.stateFrame += npc_ticks_get(npc); + isDone = npc.stateFrame > PUPPY_STUCK_FRAMES; + } + else npc.stateFrame = 0; + npc.targetPosition = npc.pos; + + Entity* target = npc.target; + if (npc.variant == PUPPY_GROWN && target && target->IsEnemy() && !target->HasEntityFlags(FLAG_FRIENDLY) && + vector_dot(vector_sub(target->pos, npc.pos), direction) < PUPPY_OVERSHOOT && (Random() & PUPPY_STOP_MASK) == 0) + { + isDone = true; + npc.projectileCooldown = PUPPY_STOP_COOLDOWN; + puppy_face_play(npc, "AttackStop"); + } + if ((Random() & 1) == 0) + npc.MakeSplat((float)npc.variant * PUPPY_SPLAT_GROWN + random_unit() * PUPPY_BLOOD_RANGE + PUPPY_BLOOD_MIN); + npc.v1.x = std::max(npc.v1.x - npc.speedMultiplier * PUPPY_DASH_DECAY, PUPPY_DASH_MIN); + npc.velocity = vector_add(npc.velocity, vector_scale(direction, npc.v1.x * npc.speedMultiplier)); + npc.friction *= PUPPY_DASH_FRICTION; + if (isDone) npc.state = NPC_STATE_IDLE; +} + +// Growing: on Shoot it hacks up a heart (a half one when small) from its drop RNG. +static void puppy_heart_spawn(Entity_NPC& npc) +{ + npc.friction *= PUPPY_HEART_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_THUMBSUP, 1, 2, 1); + uint32_t seed = npc.dropRNG.Next(); + int subType = npc.variant != PUPPY_GROWN ? HEART_HALF : HEART_FULL; + Vector toss = vector_add(random_direction(), vector_make(0, PUPPY_HEART_LIFT)); + g_game->Spawn({.position = npc.pos, .velocity = toss, .spawner = &npc, .subType = subType, .type = ENTITY_PICKUP, + .variant = PICKUP_HEART, .seed = seed}); + } + if (!npc_anim_is_done(npc)) return; + npc.state = NPC_STATE_IDLE; +} + +// 00552d30 The Blood Puppy's AI. +void npc_blood_puppy_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return puppy_hits_soften(npc); + + int stateBefore = npc.state; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.AddEntityFlags(FLAG_NO_TARGET); + npc.state = NPC_STATE_IDLE; + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + break; + case PUPPY_RESET: + npc.state = NPC_STATE_IDLE; + npc.projectileCooldown = PUPPY_RESET_COOLDOWN; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.v2 = {}; + npc.stateFrame = 0; + npc.projectileDelay = 0; + puppy_wander(npc); + break; + case NPC_STATE_IDLE: + puppy_wander(npc); + break; + case PUPPY_DASH: + puppy_dash(npc); + break; + case PUPPY_SPAWNING: + puppy_heart_spawn(npc); + break; + default: + break; + } + bool isSettled = (stateBefore == PUPPY_DASH || stateBefore == PUPPY_SPAWNING) && npc.state == NPC_STATE_IDLE; + if (isSettled) + { + npc.target = nullptr; + npc.stateFrame = 0; + npc.v2 = {}; + } + if (npc.projectileDelay > 0) npc.projectileDelay = std::max(npc.projectileDelay - npc_ticks_get(npc), 0); +} diff --git a/src/npc_charger_l2.cpp b/src/npc_charger_l2.cpp new file mode 100644 index 0000000..85d2233 --- /dev/null +++ b/src/npc_charger_l2.cpp @@ -0,0 +1,182 @@ +#include "npc_alt.h" +#include "npc_gehenna.h" +#include "entity_player.h" +#include +#include + +// The level 2 Charger wanders the grid's axes and charges at a target it sees within 20 of one of its four axes +// (or where its controller points), steering into the target a little as it goes. Its Elleech (variant 1) waits out +// a delay, then charges along its grid path at the target and turns with the path every other tick. +constexpr int ELLEECH = 1; +constexpr std::array CHARGE_ANIMS_4 = {"Attack Right", "Attack Down", "Attack Left", "Attack Up"}; +constexpr std::array CHARGE_ANIMS_8 = {"Attack Right", "Attack Right Down", "Attack Down", + "Attack Left Down", "Attack Left", "Attack Left Up", + "Attack Up", "Attack Right Up"}; +constexpr float CHARGER_L2_WANDER_SPEED = 0.65f; +constexpr float CHARGER_L2_FRICTION = 0.85f; +constexpr float CHARGER_L2_DRIFT = 0.9647058f; +constexpr float CHARGER_L2_LEAD = 16; +constexpr float CHARGER_L2_MARGIN = 20; +constexpr float CHARGER_L2_CONTROL_REACH = 100; +constexpr float CHARGER_L2_ALIGN = 20; +constexpr float CHARGER_L2_SPEED = 1.3f; +constexpr float ELLEECH_SPEED = 2; +constexpr float ELLEECH_PATH_SPEED = 2; +constexpr float ELLEECH_STEER_SPEED = 10; +constexpr float ELLEECH_STEER_INTERVAL = 2; +constexpr int CHARGER_L2_PATH_MARKER = 900; +constexpr int CHARGER_L2_CHARGE_DELAY = 4; +constexpr float CHARGE_STEER_STRENGTH = 2; +constexpr float CHARGE_STEER_DECAY = 0.033f; +constexpr float CHARGE_STEER_SHARE = 0.1f; +constexpr float CHARGE_STUCK_DISTANCE = 2; +constexpr int CHARGE_STUCK_FRAMES = 6; +constexpr int ELLEECH_TURN_STALL = 10; +constexpr float CHARGER_L2_SLOW_SPEED = 3; +constexpr float CHARGER_L2_CHARGE_FRICTION = 0.8f; +constexpr int CHARGER_L2_SOUND_DELAY = 20; +constexpr float CHARGER_L2_PITCH = 0.9f; +constexpr float QUARTER_SLOT_DEGREES = 45; + +// The aim a target is led to: its spot ahead by its velocity (scaled by the lead, random when none is given), held 20 +// inside the room. +static Vector charger_l2_aim(Entity_NPC& npc, float lead) +{ + Vector targetPos = npc.CalcTargetPosition(0); + Vector targetVelocity = npc.GetPlayerTarget()->velocity; + if (lead < 0) lead = random_unit() * CHARGER_L2_LEAD; + Vector aim = vector_add(targetPos, vector_scale(targetVelocity, lead)); + return g_game->room->GetClampedPositionImpl(aim, CHARGER_L2_MARGIN, CHARGER_L2_MARGIN, CHARGER_L2_MARGIN, CHARGER_L2_MARGIN); +} + +// Starts the charge along a direction, 4 frames before it may stop. +static void charger_l2_charge_start(Entity_NPC& npc, Vector direction) +{ + npc.sprite.isFlipX = false; + npc.v1 = direction; + npc.v2.x = CHARGE_STEER_STRENGTH; + npc.state = NPC_STATE_ATTACK; + npc.pathfinder.gridPathTarget = npc.pos; + npc.pathfinder.moveCountdown = 0; +} + +// The Elleech's lunge once its delay runs out: along the first step of its grid path at the target. +static void elleech_lunge(Entity_NPC& npc) +{ + npc.stateFrame = CHARGER_L2_CHARGE_DELAY; + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), ELLEECH_PATH_SPEED, CHARGER_L2_PATH_MARKER, DIRECT_PATH_NEAR); + int direction = vector_to_direction(npc.velocity); + npc_sound_play(SOUND_LEECH, 1, CHARGER_L2_SOUND_DELAY, 1); + npc.sprite.Play(CHARGE_ANIMS_4[(direction + 2) % 4]); + charger_l2_charge_start(npc, vector_scale(vector_from_direction(direction), ELLEECH_SPEED)); +} + +// Wandering: the Elleech counts down its delay; the Charger watches for a target in line with an axis. +static void charger_l2_wander(Entity_NPC& npc) +{ + npc_axis_walk_animate(npc, {"Move Hori", "Move Up", "Move Down", 0}); + if (npc.variant == ELLEECH && npc.stateFrame > 0) + { + npc.stateFrame -= npc_ticks_get(npc); + npc.friction *= CHARGER_L2_FRICTION; + if (npc.stateFrame <= 0) elleech_lunge(npc); + return; + } + + npc.pathfinder.MoveRandomlyAxisAligned(CHARGER_L2_WANDER_SPEED, STATUS_OBEYED); + npc.friction *= CHARGER_L2_FRICTION; + npc.velocity.y *= timescale_factor(CHARGER_L2_DRIFT, npc.speedMultiplier); + Vector start = npc.pos; + Vector aim = charger_l2_aim(npc, -1); + Vector delta = vector_sub(aim, start); + if (npc.controllerID != -1) + { + delta = vector_scale(npc.GetControllerInput(0), CHARGER_L2_CONTROL_REACH); + aim = vector_add(start, delta); + } + + int quarter = (int)((vector_angle(delta) + FULL_TURN_DEGREES + QUARTER_SLOT_DEGREES) / RIGHT_ANGLE_DEGREES) % 4; + Vector direction = vector_from_angle((float)(quarter * 2) * QUARTER_SLOT_DEGREES); + if (npc.controllerID == -1) + { + if (vector_dot(direction, delta) <= 0) return; + if (std::abs(vector_dot(vector_rotated(direction, RIGHT_ANGLE_DEGREES), delta)) >= CHARGER_L2_ALIGN) return; + if (!room_check_line(start, aim, LINE_MODE_CELL, 0)) return; + } + else if (vector_is_zero(delta)) return; + + if (npc.variant == ELLEECH) + { + npc_sound_play(SOUND_LEECH, 1, CHARGER_L2_SOUND_DELAY, 1); + npc.sprite.Play(CHARGE_ANIMS_4[quarter]); + charger_l2_charge_start(npc, vector_scale(direction, ELLEECH_SPEED)); + } + else + { + npc_sound_play(SOUND_MAGGOTCHARGE, 1, CHARGER_L2_SOUND_DELAY, CHARGER_L2_PITCH); + npc.sprite.Play(CHARGE_ANIMS_8[quarter * 2]); + charger_l2_charge_start(npc, vector_scale(direction, CHARGER_L2_SPEED)); + } + npc.stateFrame = CHARGER_L2_CHARGE_DELAY; +} + +// Charging: it stops once stuck (barely moving or against a wall) for 6 frames, or when slowed below 3, distracted +// or controlled away. The Elleech follows its grid path, stalling a turn when it bends. +static void charger_l2_charge(Entity_NPC& npc) +{ + PathFinder& path = npc.pathfinder; + float moved = vector_length_squared(vector_sub(path.gridPathTarget, npc.pos)) / (npc.speedMultiplier * npc.speedMultiplier); + path.moveCountdown = moved < CHARGE_STUCK_DISTANCE || npc.isCollidesWithGrid ? path.moveCountdown + npc_ticks_get(npc) : 0; + if (npc.variant == ELLEECH && npc.GetIntervalTicks(ELLEECH_STEER_INTERVAL, 0) != 0) + { + int countdown = path.moveCountdown; + path.Reset(); + Vector velocity = npc.velocity; + float friction = npc.friction; + path.FindGridPath(npc.CalcTargetPosition(0), ELLEECH_STEER_SPEED, CHARGER_L2_PATH_MARKER, DIRECT_PATH_NEAR); + bool isTurning = vector_to_direction(npc.v1) != vector_to_direction(npc.velocity); + npc.velocity = velocity; + npc.friction = friction; + path.moveCountdown = isTurning ? ELLEECH_TURN_STALL : countdown; + } + path.gridPathTarget = npc.pos; + + bool isSlowed = npc.HasEntityFlags(FLAG_SLOW) && vector_length(npc.velocity) < CHARGER_L2_SLOW_SPEED; + if (npc.HasEntityFlags(FLAG_DISTRACTED) || isSlowed || path.moveCountdown >= CHARGE_STUCK_FRAMES) + { + path.movementTarget = {}; + path.moveDirection = {}; + npc.state = NPC_STATE_MOVE; + return; + } + + int octant = (int)((vector_angle(npc.v1) + FULL_TURN_DEGREES + QUARTER_SLOT_DEGREES * HALF) / QUARTER_SLOT_DEGREES) % 8; + npc.sprite.Play(CHARGE_ANIMS_8[octant]); + npc.friction *= CHARGER_L2_CHARGE_FRICTION; + if (npc.friction != 0) npc.velocity = vector_add(npc.velocity, vector_scale(npc.v1, npc.speedMultiplier / npc.friction)); + if (npc.variant == ELLEECH) return; + + npc.v2.x = std::max(npc.v2.x - npc.speedMultiplier * CHARGE_STEER_DECAY, 0.0f); + Vector delta = vector_sub(charger_l2_aim(npc, CHARGER_L2_LEAD), npc.pos); + if (vector_dot(npc.v1, delta) <= 0 || npc.v2.x <= 0) return; + + Vector steer = vector_resized(delta, std::min(npc.v2.x, 1.0f) * CHARGE_STEER_SHARE); + npc.v1 = vector_resized(vector_add(npc.v1, vector_scale(steer, npc.speedMultiplier)), vector_length(npc.v1)); +} + +// 004e38c0 The level 2 Charger's and the Elleech's AI. +void npc_charger_l2_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_MOVE; + return; + case NPC_STATE_MOVE: + return charger_l2_wander(npc); + case NPC_STATE_ATTACK: + return charger_l2_charge(npc); + default: + return; + } +} diff --git a/src/npc_cohort.cpp b/src/npc_cohort.cpp new file mode 100644 index 0000000..6388db4 --- /dev/null +++ b/src/npc_cohort.cpp @@ -0,0 +1,203 @@ +#include "npc_gehenna.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include + +// The Cohort idles for 8 frames, then one time in three (two in three once it has jumped four times) attacks a target +// within 420: a fast big shot when in sight half the time, else a lobbed burst of 18 with a meat shot that grows a +// Globin. Otherwise it jumps toward its target along its grid path. It bursts into four meat shots on death. +constexpr int COHORT_IDLE_FRAMES = 8; +constexpr uint32_t COHORT_ATTACK_ODDS = 3; +constexpr int COHORT_RESTLESS_JUMPS = 4; +constexpr float COHORT_ATTACK_RANGE = 420; +constexpr float COHORT_FRICTION = 0.8f; +constexpr float COHORT_PATH_SPEED = 1; +constexpr float COHORT_PATH_LOOKAHEAD = 300; +constexpr float COHORT_JUMP_SPEED = 1.5f; +constexpr float COHORT_AIR_FRICTION = 0.9f; +constexpr float COHORT_LAND_VOLUME = 0.5f; +constexpr int COHORT_LAND_POOF_SUBTYPE = 2; +constexpr float COHORT_LAND_POOF_DROP = 15; +constexpr ColorMod COHORT_LAND_POOF_COLOR = {{0.8f, 0.8f, 0.8f, 0.7f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float COHORT_SHOT_SPEED = 10; +constexpr float COHORT_SHOT_ACCEL = 0.94f; +constexpr float COHORT_SHOT_HEIGHT = -23; +constexpr float COHORT_SHOT_SCALE = 2; +constexpr int COHORT_BURST_SHOTS = 18; +constexpr size_t COHORT_GLOBIN_LIMIT = 10; +constexpr int COHORT_OWN_GLOBIN_LIMIT = 4; +constexpr float COHORT_MEAT_ARC = 3; +constexpr float COHORT_MEAT_LIFT = -10; +constexpr int COHORT_DEATH_SHOTS = 4; +constexpr float COHORT_DEATH_SPREAD = 10; + +// The jump: toward the next step of its grid path when the way is blocked (and it is free to choose), else at its +// target, as a unit direction. +static void cohort_jump_start(Entity_NPC& npc, Vector targetPos, int ticks) +{ + Vector landing; + if (!npc.HasEntityFlags(FLAG_DISTRACTED) && !room_check_line(npc.pos, targetPos, LINE_MODE_GROUND, 0)) + { + float friction = npc.friction; + Vector velocity = npc.velocity; + npc.velocity = {}; + npc.pathfinder.Reset(); + npc.pathfinder.FindGridPath(targetPos, COHORT_PATH_SPEED, 0, DIRECT_PATH_FAR); + landing = vector_is_zero(npc.velocity) ? npc.CalcTargetPosition(0) + : vector_add(npc.pos, vector_scale(npc.velocity, COHORT_PATH_LOOKAHEAD)); + npc.velocity = velocity; + npc.friction = friction; + } + else landing = npc.CalcTargetPosition(0); + + npc.sprite.Play("Jump"); + npc.targetPosition = vector_normalized(vector_sub(landing, npc.pos)); + npc.i1 += ticks; + npc.state = NPC_STATE_JUMP; +} + +// Idling: after 8 frames it attacks a near target or jumps. +static void cohort_idle(Entity_NPC& npc, int ticks) +{ + npc.friction *= COHORT_FRICTION; + npc.sprite.Play("Idle"); + npc.stateFrame += ticks; + if (npc.stateFrame <= COHORT_IDLE_FRAMES) return; + + Vector targetPos = npc.GetPlayerTarget()->pos; + bool isInSight = room_check_line(npc.pos, targetPos, LINE_MODE_PROJECTILE, 0); + bool isAttacking = Random() % COHORT_ATTACK_ODDS == 0 || + (npc.i1 > COHORT_RESTLESS_JUMPS && Random() % COHORT_ATTACK_ODDS != 0); + if (isAttacking && vector_distance(npc.pos, targetPos) < COHORT_ATTACK_RANGE) + { + npc.sprite.isFlipX = targetPos.x - npc.pos.x > 0; + bool isShot = (Random() & 1) == 0 && isInSight; + npc.sprite.Play(isShot ? "Attack1" : "Attack2"); + npc.state = isShot ? NPC_STATE_ATTACK : NPC_STATE_ATTACK2; + npc.i1 = 0; + return; + } + cohort_jump_start(npc, targetPos, ticks); +} + +// In the air between Jump and Land it is untouchable and pushed along; on Land it thuds in a pale poof. +// True while the jump plays on. +static bool cohort_jump(Entity_NPC& npc) +{ + ANM2& sprite = npc.sprite; + bool isAirborne = sprite.animState.animData && sprite.animState.WasEventTriggered("Jump") && !sprite.WasEventTriggered("Land"); + if (isAirborne) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, COHORT_JUMP_SPEED / npc.friction)); + npc.friction *= COHORT_AIR_FRICTION; + sprite.isFlipX = npc.velocity.x > 0; + } + else + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.friction *= COHORT_FRICTION; + } + + if (sprite.animState.animData && sprite.animState.IsEventTriggered("Land")) + { + npc_sound_play(SOUND_FORESTBOSS_STOMPS, COHORT_LAND_VOLUME, 2, 1); + Entity* poof = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = COHORT_LAND_POOF_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF02, + .seed = Random()}); + poof->sprite.offset = vector_make(0, COHORT_LAND_POOF_DROP); + poof->sprite.isFlipX = (Random() & 1) == 0; + poof->SetColor(COHORT_LAND_POOF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + static_cast(poof)->FollowParent(&npc); + poof->Update(); + } + if (!npc_anim_is_done(npc)) return true; + + npc.entityCollisionClass = ENTCOLL_ALL; + return false; +} + +// The fast shot: one big shot at its target, speeding then slowing. +static void cohort_shoot(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_MONSTER_GRUNT_2, 1, 2, false, 1); + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + ProjectileParams params; + params.bulletFlags = PROJECTILE_ACCELERATE_EX | PROJECTILE_BURST8; + params.acceleration = COHORT_SHOT_ACCEL; + Entity_Projectile* shot = npc.FireBossProjectiles(1, {}, 0, params); + shot->height = COHORT_SHOT_HEIGHT; + shot->fallingAccel = 0; + shot->velocity = vector_scale(aim, COHORT_SHOT_SPEED); + shot->fallingSpeed = 0; + shot->scale = COHORT_SHOT_SCALE; +} + +// The lobbed burst of 18 at its target, and a meat shot that grows a Globin while the room holds fewer than ten and it +// has spawned fewer than four. +static void cohort_lob(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_BOSS_SPIT_BLOB_BARF, 1, 2, false, 1); + Vector targetPos = npc.GetPlayerTarget()->pos; + ProjectileParams params; + npc.FireBossProjectiles(COHORT_BURST_SHOTS, targetPos, 0, params); + + std::vector globins = Entity_NPC::QueryNPCsType(ENTITY_GLOBIN, -1); + int owned = (int)std::count_if(globins.begin(), globins.end(), [&](Entity* globin) { return globin->spawnerEntity.get() == &npc; }); + if (globins.size() >= COHORT_GLOBIN_LIMIT || owned >= COHORT_OWN_GLOBIN_LIMIT) return; + + params.variant = PROJECTILE_MEAT; + params.bulletFlags = PROJECTILE_BOUNCE; + Entity_Projectile* meat = npc.FireBossProjectiles(1, targetPos, COHORT_MEAT_ARC, params); + meat->fallingSpeed = std::min(meat->fallingSpeed, COHORT_MEAT_LIFT); +} + +// 005513a0 The Cohort's AI. +void npc_cohort_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + bool isAttackDone = false; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + npc.i1 = 0; + npc.targetPosition = npc.pos; + break; + case NPC_STATE_IDLE: + cohort_idle(npc, ticks); + break; + case NPC_STATE_JUMP: + isAttackDone = !cohort_jump(npc); + break; + case NPC_STATE_ATTACK: + case NPC_STATE_ATTACK2: + npc.friction *= COHORT_FRICTION; + if (!npc.sprite.animState.animData) + { + isAttackDone = true; + break; + } + if (npc.sprite.animState.IsEventTriggered("Shoot")) + npc.state == NPC_STATE_ATTACK ? cohort_shoot(npc) : cohort_lob(npc); + isAttackDone = !npc.sprite.animState.isPlaying; + break; + default: + break; + } + if (isAttackDone) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + } + if (!npc.isDead) return; + + ProjectileParams params; + params.variant = PROJECTILE_MEAT; + params.bulletFlags = PROJECTILE_BOUNCE; + npc.FireBossProjectiles(COHORT_DEATH_SHOTS, {}, COHORT_DEATH_SPREAD, params); +} diff --git a/src/npc_collision.cpp b/src/npc_collision.cpp index 1d8fc6a..8f026d4 100644 --- a/src/npc_collision.cpp +++ b/src/npc_collision.cpp @@ -6,7 +6,9 @@ #include "entity_familiar.h" #include "entity_player.h" #include "entity_tear.h" +#include "grid_entity_door.h" #include "boss_ai.h" +#include "boss_repentance.h" #include "game.h" #include "npc_alt.h" #include "room.h" @@ -30,10 +32,10 @@ constexpr int LARRY_SEGMENT_VARIANT = 3; constexpr int VIS_CHUBBER_VARIANT = 22; constexpr int DEATH_SCYTHE_VARIANT = 20; constexpr int PIN_SCOLEX_VARIANT = 3; +constexpr int SWALLOWED_BOMB_FUSE = 35; constexpr int SUCKER_BULB_FIRST = 5; constexpr int SUCKER_BULB_LAST = 6; constexpr int BEAST_SOUL_VARIANT = 10; -constexpr int SCOURGE_CHAIN_VARIANT = 10; constexpr int SMALL_MAGGOT_FALLING = 2; constexpr int SMALL_MAGGOT_LANDED = 1; constexpr int HAND_GRAB_STATE = NPC_STATE_STOMP; @@ -58,6 +60,9 @@ constexpr float BEAST_SOUL_DAMAGE = 200; constexpr float BEAST_SOUL_SPEED_SQUARED = 225; constexpr float SCOURGE_CHAIN_DAMAGE = 5; constexpr float SCOURGE_CHAIN_AGE = 60; +constexpr float HORNFEL_RAM_SPEED = 10; +constexpr float HORNFEL_RAM_ENEMY_DAMAGE = 25; +constexpr float HORNFEL_RAM_DAMAGE = 1; constexpr float CRUSH_DAMAGE = 10; constexpr float FRIENDLY_FIRE_DAMAGE = 10; constexpr float FIREPLACE_BURN = 16; @@ -81,6 +86,8 @@ constexpr float FRIENDLY_TARGET_MAX = 3.5f; constexpr float BAITED_SHARE = 0.5f; constexpr float KNOCKBACK_IMPACT_SPEED = 6; constexpr float ICE_SHATTER_DAMAGE = 35; +constexpr float ICE_KNOCK_SPEED = 18; +constexpr int ICE_KNOCK_FRAMES = 200; constexpr float IMPACT_DAMAGE_BASE = 10; constexpr float SPAWN_GRACE_FRAMES = 10; constexpr int DARK_ESAU_GRACE = 16; @@ -165,6 +172,35 @@ static void black_knight_reflect(Entity_NPC& npc, Entity_Tear& tear) npc.FireProjectiles(npc.pos, mirrored, PROJECTILES_SINGLE, params); } +// A player touching the exit minecart rides it out through the first door it can blow open that the rails reach from +// its spot, on the cart and without control. The room remembers the cart has gone. +static bool minecart_exit_ride(Entity_NPC& cart, Entity_Player& player) +{ + Room& room = *g_game->room; + int start = room.GetGridIndex(cart.targetPosition); + for (GridEntity_Door* door : room.doors) + { + if (!door || !door->CanBlowOpen() || !room.railManager.flood_fill(start, door->gridIndex)) continue; + + RoomTransitionRequest request = {.player = &player, .animation = TRANSITION_MINECART, .direction = door->direction, + .roomIndex = door->targetRoomIdx}; + if (door->targetRoomIdx <= ROOM_INDEX_OTHER_DIMENSION) + { + RoomDescriptor* target = g_game->GetRoomByIdx(door->targetRoomIdx, -1); + request.dimension = target->dimension; + request.roomIndex = target->gridIndex; + } + g_game->StartRoomTransition(request); + g_game->roomTransition.minecart = &cart; + room.descriptor->flags |= ROOM_DESCRIPTOR_FLAG_SACRIFICE_DONE; + player.PlayExtraAnimation("MinecartEnter"); + player.moveToTarget = cart.targetPosition; + player.isControlsEnabled = false; + return true; + } + return false; +} + // The first contacts, before the AI's collision call: Dark Esau passes shots, a white fire spares a player it cannot // hurt, a magnetized enemy collides with the enemies of another target and minecarts pass each other. static Verdict contact_early(Contact& contact) @@ -186,8 +222,9 @@ static Verdict contact_early(Contact& contact) TearFlags& flags = collider.ToTear()->tearFlags; if (!flags[TEAR_EXPLOSIVE] && !flags[TEAR_LUDOVICO]) black_knight_reflect(npc, *collider.ToTear()); } - if (collider.type == ENTITY_PLAYER && npc.type == ENTITY_MINECART && npc.variant == MINECART_EXIT) - reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a minecart leaving the room"); + if (collider.type == ENTITY_PLAYER && npc.type == ENTITY_MINECART && npc.variant == MINECART_EXIT && + minecart_exit_ride(npc, *collider.ToPlayer())) + return true; bool isVersusPlayer = g_game->deathmatchManager.is_active() && collider.type == ENTITY_PLAYER; bool isMagnetized = npc.HasEntityFlags(FLAG_MAGNETIZED) || collider.HasEntityFlags(FLAG_MAGNETIZED); @@ -273,7 +310,10 @@ static Verdict contact_pairs(Contact& contact) if (npc.type == ENTITY_HORNFEL) { if (npc.variant == 1 && collider.type == ENTITY_PLAYER) npc.Kill(EntityRef()); - if (npc.minecart) reconstruction_missing("Entity_NPC::HandleCollision 006cd410: Hornfel's minecart ramming"); + auto* cart = static_cast(npc.minecart.get()); + if (cart && cart->v2.x > HORNFEL_RAM_SPEED) + collider.TakeDamage(collider.IsEnemy() ? HORNFEL_RAM_ENEMY_DAMAGE : HORNFEL_RAM_DAMAGE, 0, EntityRef(&npc), + CONTACT_COUNTDOWN); } bool isBall = (npc.type == ENTITY_SINGE && npc.variant == 1) || npc.type == ENTITY_BALL_AND_CHAIN; @@ -283,7 +323,12 @@ static Verdict contact_pairs(Contact& contact) hit_list_insert(npc.hitList, collider); damage_deal(collider, BALL_DAMAGE, 0, &npc); } - if (npc.type == ENTITY_VISAGE) reconstruction_missing("Entity_NPC::HandleCollision 006cd410: Visage's contacts"); + if (npc.type == ENTITY_VISAGE) + { + std::optional verdict = visage_handle_collision(npc, collider); + if (verdict) return *verdict; + if (collider.type == ENTITY_VISAGE && npc.variant == 10) return true; + } if (npc.type == ENTITY_MOTHER && collider.type == ENTITY_MOTHER) return true; if (npc.type == ENTITY_BEAST && collider.type == ENTITY_BEAST) @@ -305,7 +350,7 @@ static Verdict contact_pairs(Contact& contact) if (npc.type == ENTITY_SCOURGE) { if (collider.type == ENTITY_SCOURGE) return true; - bool isChain = npc.variant == SCOURGE_CHAIN_VARIANT && npc.subtype != 0; + bool isChain = npc.variant == SCOURGE_CHAIN && npc.subtype != 0; if (isChain && collider.IsVulnerableEnemy(nullptr) && collider.updateTime > SCOURGE_CHAIN_AGE) { if (collider.type == ENTITY_SMALL_MAGGOT) collider.Kill(EntityRef(&npc)); @@ -774,9 +819,22 @@ static Verdict contact_late(Contact& contact) bool isChubEating = npcType == ENTITY_CHUB && !npc.parent && npc.state == NPC_STATE_ATTACK; bool isPinEating = npcType == ENTITY_PIN && npc.variant == PIN_SCOLEX_VARIANT && !npc.parent && (npc.state == NPC_STATE_JUMP || npc.state == NPC_STATE_MOVE) && npc.i1 == 2; - if (isChubEating || isPinEating) - reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a boss swallowing a bomb"); - return std::nullopt; + if (!isChubEating && !isPinEating) return std::nullopt; + + npc.state = isChubEating ? NPC_STATE_SPECIAL : NPC_STATE_SUICIDE; + npc.stateFrame = 0; + Entity_Bomb* bomb = dynamic_cast(&collider); + if (!bomb) return contact.isIgnored; + bomb->parent = nullptr; + bomb->isFetus = false; + bomb->explosionCountdown = SWALLOWED_BOMB_FUSE; + bomb->explosionCountdown2 = SWALLOWED_BOMB_FUSE; + bomb->entityCollisionClass = ENTCOLL_NONE; + bomb->isVisible = false; + bomb->pos = npc.pos; + bomb->velocity = {}; + npc.SetRef_bec(bomb); + return contact.isIgnored; } if (!contact.isLow && npcType == ENTITY_GURDY) { @@ -877,8 +935,15 @@ static void contact_impact(Entity_NPC& npc, Entity& other) } if (other.HasEntityFlags(FLAG_ICE_FROZEN)) - reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a frozen enemy knocking an iced one"); - damage_deal(other, ICE_SHATTER_DAMAGE, DAMAGE_ICE_SHATTER, nullptr); + { + Vector away = vector_normalized(vector_sub(other.pos, npc.pos)); + Vector push = vector_scale(vector_normalized(vector_add(away, vector_normalized(npc.velocity))), ICE_KNOCK_SPEED); + bool isStatusImmune = other.HasEntityFlags(FLAG_NO_STATUS_EFFECTS); + other.ClearEntityFlags(FLAG_NO_STATUS_EFFECTS); + other.AddKnockback(EntityRef(&npc), push, ICE_KNOCK_FRAMES, true); + if (isStatusImmune) other.AddEntityFlags(FLAG_NO_STATUS_EFFECTS); + } + else damage_deal(other, ICE_SHATTER_DAMAGE, DAMAGE_ICE_SHATTER, nullptr); npc.Kill(EntityRef()); } diff --git a/src/npc_cultist.cpp b/src/npc_cultist.cpp index fae147e..87fb0c5 100644 --- a/src/npc_cultist.cpp +++ b/src/npc_cultist.cpp @@ -7,7 +7,6 @@ // 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; diff --git a/src/npc_dirt.cpp b/src/npc_dirt.cpp index 90b0b39..23e406c 100644 --- a/src/npc_dirt.cpp +++ b/src/npc_dirt.cpp @@ -7,7 +7,6 @@ #include #include -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 // on screen. The surface's luma weights order them. @@ -27,7 +26,7 @@ static KColor image_pixel_get(KAGE::Graphics::ImageBase& image, uint32_t x, uint KAGE::Graphics::manager.render_target_push(&image, KAGE::Graphics::TARGET_OWN_SIZE, KAGE::Graphics::PRESENT_FLUSH); gl.ReadPixels((GLint)x, (GLint)y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, texel.data()); KAGE::Graphics::manager.render_target_pop(KAGE::Graphics::PRESENT_FLUSH); - return kcolor_rgba(texel[0] / CHANNEL_MAX, texel[1] / CHANNEL_MAX, texel[2] / CHANNEL_MAX, texel[3] / CHANNEL_MAX); + return kcolor_rgba(texel[0] / COLOR_CHANNEL_MAX, texel[1] / COLOR_CHANNEL_MAX, texel[2] / COLOR_CHANNEL_MAX, texel[3] / COLOR_CHANNEL_MAX); } static float luma_get(const KColor& color) diff --git a/src/npc_faceless.cpp b/src/npc_faceless.cpp index a16d51c..7a57e3a 100644 --- a/src/npc_faceless.cpp +++ b/src/npc_faceless.cpp @@ -2,6 +2,7 @@ #include "entity_player.h" #include "entity_projectile.h" #include "path_finder.h" +#include "room_grid.h" #include // The Faceless' states: asleep then walking, shooting, waking with a burst of blood, and summoning at the Heretic's @@ -341,10 +342,180 @@ void npc_faceless_update(Entity_NPC& npc) (npc.targetPosition.y - npc.pos.y) / npc.friction); } -// 004ec240 (the Faceless part) The Exorcist: the Heretic's summoned ones are Faceless. The plain Exorcist is not -// reconstructed yet. +// The plain Exorcist walks about and, now and then, turns a ghost of the room's dead into a Lil Haunt where it lies, or +// raises one beside itself, keeping clear of its target while one hangs about it. +constexpr int EXORCIST_REVIVE_SUMMON = NPC_STATE_ATTACK; +constexpr int EXORCIST_REVIVE_GHOSTS = NPC_STATE_ATTACK2; +constexpr int EXORCIST_START_WAIT_MIN = 15; +constexpr int EXORCIST_START_WAIT_RANGE = 30; +constexpr int EXORCIST_WAIT_MIN = 60; +constexpr int EXORCIST_WAIT_RANGE = 60; +constexpr int EXORCIST_IDLE_WAIT = 30; +constexpr float EXORCIST_GROAN_INTERVAL = 30; +constexpr uint32_t EXORCIST_GROAN_ODDS = 3; +constexpr float EXORCIST_GROAN_VOLUME = 0.8f; +constexpr int EXORCIST_GROAN_DELAY = 120; +constexpr float EXORCIST_GHOST_CHECK_INTERVAL = 5; +constexpr float EXORCIST_GHOST_SEARCH_INTERVAL = 10; +constexpr uint32_t EXORCIST_GHOST_SEARCH_ODDS = 3; +constexpr float EXORCIST_GHOST_SEARCH = 200; +constexpr float EXORCIST_GHOST_REACH = 80; +constexpr float EXORCIST_GHOST_ARRIVAL = 15; +constexpr float EXORCIST_WALK_SPEED = 0.85f; +constexpr float EXORCIST_GUARD_DISTANCE = 80; +constexpr float EXORCIST_GUARD_MARGIN = 5; +constexpr float EXORCIST_EVADE_FRICTION = 0.8f; +constexpr uint32_t EXORCIST_SUMMON_ODDS = 10; +constexpr float EXORCIST_REVIVE_FRICTION = 0.6f; +constexpr float EXORCIST_SUMMON_SPOT = 40; +constexpr float EXORCIST_TINY_PITCH = 1.5f; +constexpr float EXORCIST_GIANT_PITCH = 0.5f; + +// Stops the walk to raise the dead. +static void exorcist_revive_start(Entity_NPC& npc, int state) +{ + npc.sprite.RemoveOverlay(); + npc.sprite.Play("Revive"); + npc.state = state; +} + +// The ghost it walks to: a fresh look every 10 ticks, one time in three, for the nearest free spot within 200 that +// lies within 80 of a ghost and that it can walk to. +static void exorcist_ghost_find(Entity_NPC& npc) +{ + if (npc.GetIntervalTicks(EXORCIST_GHOST_SEARCH_INTERVAL, 0) == 0 || Random() % EXORCIST_GHOST_SEARCH_ODDS != 0) return; + + Entity* ghost = nullptr; + Vector ghostSpot{}; + float best = EXORCIST_GHOST_SEARCH * EXORCIST_GHOST_SEARCH; + for (Entity* candidate : entity_query(ENTITY_EFFECT, EFFECT_ENEMY_GHOST)) + { + if (candidate->subtype != 0) continue; + Vector spot = room_free_pickup_position_find({.position = candidate->pos}); + float distance = vector_length_squared(vector_sub(npc.pos, spot)); + if (distance >= best || vector_length_squared(vector_sub(candidate->pos, spot)) >= EXORCIST_GHOST_REACH * EXORCIST_GHOST_REACH) + continue; + if (!npc.pathfinder.HasPathToPos(spot, false)) continue; + ghost = candidate; + ghostSpot = spot; + best = distance; + } + if (!ghost) return; + npc.entityRef = ghost; + npc.targetPosition = ghostSpot; +} + +// Walking: it groans, drops a ghost it can no longer reach, walks to its ghost (reviving it on arrival), else guards +// its Lil Haunt from its target or keeps away from the target, and may raise a Lil Haunt itself. +static void exorcist_walk(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", FACELESS_WALK_THRESHOLD); + npc.sprite.PlayOverlay("Head"); + if (npc.GetIntervalTicks(EXORCIST_GROAN_INTERVAL, 0) != 0 && Random() % EXORCIST_GROAN_ODDS == 0) + npc.PlaySound(SOUND_MONSTER_ROAR_1, EXORCIST_GROAN_VOLUME, EXORCIST_GROAN_DELAY, false, 1); + if (npc.GetIntervalTicks(EXORCIST_GHOST_CHECK_INTERVAL, 0) != 0 && npc.entityRef) + { + bool isNear = vector_length_squared(vector_sub(npc.targetPosition, npc.entityRef->pos)) < EXORCIST_GHOST_REACH * EXORCIST_GHOST_REACH; + if (!isNear || !npc.pathfinder.HasPathToPos(npc.targetPosition, false)) npc.entityRef = nullptr; + } + + if (!npc.entityRef) exorcist_ghost_find(npc); + if (npc.entityRef) + { + npc.pathfinder.FindGridPath(npc.targetPosition, EXORCIST_WALK_SPEED, 0, DIRECT_PATH_FAR); + if (vector_length_squared(vector_sub(npc.targetPosition, npc.pos)) <= EXORCIST_GHOST_ARRIVAL * EXORCIST_GHOST_ARRIVAL) + { + npc.entityRef = nullptr; + return exorcist_revive_start(npc, EXORCIST_REVIVE_GHOSTS); + } + } + else if (Vector targetPos = npc.GetPlayerTarget()->pos; Entity* haunt = npc.child) + { + Vector guard = vector_add(haunt->pos, vector_resized(vector_sub(haunt->pos, targetPos), EXORCIST_GUARD_DISTANCE)); + guard = g_game->room->GetClampedPositionImpl(guard, EXORCIST_GUARD_MARGIN, EXORCIST_GUARD_MARGIN, EXORCIST_GUARD_MARGIN, + EXORCIST_GUARD_MARGIN); + npc.pathfinder.FindGridPath(guard, EXORCIST_WALK_SPEED, 0, DIRECT_PATH_FAR); + } + else + { + npc.pathfinder.EvadeTarget(npc.CalcTargetPosition(0), STATUS_OBEYED); + npc.friction *= EXORCIST_EVADE_FRICTION; + } + if (npc.i1 < 1 && Random() % EXORCIST_SUMMON_ODDS == 0 && !npc.child) exorcist_revive_start(npc, EXORCIST_REVIVE_SUMMON); +} + +// A Lil Haunt it raises, rewardless. +static Entity* exorcist_haunt_spawn(Entity_NPC& npc, const Vector& position) +{ + Entity* haunt = g_game->Spawn( + {.position = position, .spawner = &npc, .type = ENTITY_THE_HAUNT, .variant = HAUNT_LIL_VARIANT, .seed = Random()}); + haunt->AddEntityFlags(FLAG_NO_REWARD); + return haunt; +} + +// Reviving: on Revive it raises a Lil Haunt beside itself, or turns every ghost within 80 into one, then waits a while. +static void exorcist_revive(Entity_NPC& npc) +{ + npc.sprite.Play("Revive"); + npc.friction *= EXORCIST_REVIVE_FRICTION; + if (!npc.sprite.animState.animData) + { + npc.state = FACELESS_WALKING; + return; + } + if (npc.sprite.animState.IsEventTriggered("Revive")) + { + if (npc.state == EXORCIST_REVIVE_SUMMON) + { + Vector spot = room_free_pickup_position_find( + {.position = npc.pos, .step = EXORCIST_SUMMON_SPOT, .isAvoidActiveEntities = true, .isAllowPits = true}); + npc.PlaySound(SOUND_SUMMONSOUND, 1, 2, false, 1); + Entity* haunt = exorcist_haunt_spawn(npc, spot); + npc.child = haunt; + haunt->Update(); + } + else + { + for (Entity* ghost : entity_query(ENTITY_EFFECT, EFFECT_ENEMY_GHOST)) + { + if (ghost->subtype != 0) continue; + if (vector_length_squared(vector_sub(npc.pos, ghost->pos)) >= EXORCIST_GHOST_REACH * EXORCIST_GHOST_REACH) continue; + float pitch = npc.championColorIdx == CHAMPION_TINY ? EXORCIST_TINY_PITCH + : npc.championColorIdx == CHAMPION_GIANT ? EXORCIST_GIANT_PITCH + : 1; + npc_sound_play(SOUND_SUMMONSOUND, 1, 2, pitch); + exorcist_haunt_spawn(npc, ghost->pos)->Update(); + ghost->Remove(); + } + } + npc.i1 = (int)(Random() % EXORCIST_WAIT_RANGE) + EXORCIST_WAIT_MIN; + } + if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) npc.state = FACELESS_WALKING; +} + +// 004ec240 The Exorcist: the Heretic's summoned ones are Faceless. The plain one walks and raises Lil Haunts. Its wait +// runs down while it is long or while it has no Lil Haunt. void npc_exorcist_update(Entity_NPC& npc) { if (npc.variant == EXORCIST_FACELESS_VARIANT) return npc_faceless_update(npc); - reconstruction_missing("NpcAI::ENTITY_EXORCIST 004ec240: the plain Exorcist"); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = FACELESS_WALKING; + npc.sprite.PlayOverlay("Head"); + npc.sprite.SetFrame("WalkVert", 0); + npc.i1 = (int)(Random() % EXORCIST_START_WAIT_RANGE) + EXORCIST_START_WAIT_MIN; + break; + case FACELESS_WALKING: + exorcist_walk(npc); + break; + case EXORCIST_REVIVE_SUMMON: + case EXORCIST_REVIVE_GHOSTS: + exorcist_revive(npc); + break; + default: + break; + } + if (npc.i1 > EXORCIST_IDLE_WAIT || (!npc.child && npc.i1 > 0)) npc.i1 -= npc_ticks_get(npc); } diff --git a/src/npc_fireplace.cpp b/src/npc_fireplace.cpp index c45bb04..c7842c3 100644 --- a/src/npc_fireplace.cpp +++ b/src/npc_fireplace.cpp @@ -11,11 +11,6 @@ #include "room.h" #include -// A fire burns lit, is out, and is told to light again by others. -constexpr int FIRE_STATE_OUT = NPC_STATE_IDLE; -constexpr int FIRE_STATE_LIT = NPC_STATE_ATTACK; -constexpr int FIRE_STATE_RELIGHT = NPC_STATE_ATTACK2; - // A fire's three looks (its subtype), each with its burning, burnt out and dying animation. constexpr int FIRE_LOOKS = 3; constexpr const char* FLICKERING[FIRE_LOOKS] = {"Flickering", "Flickering2", "Flickering3"}; @@ -228,33 +223,42 @@ static Entity_Player* fire_putter_get(Entity_NPC& npc) return source ? static_cast(source->GetPlayerAncestor()) : nullptr; } -// Entity_NPC::fireplace_get_loot (006d1580, which needs a LootList), advancing the drop RNG, with each drop spawned -// and updated at once: what a fire put out drops, nothing from white, moveable or Coal fires or without rewards. -static void fire_loot_spawn(Entity_NPC& npc) +// 006d1580 What a fire put out drops, from its drop RNG, which only an advancing draw moves on: nothing from white, +// moveable or Coal fires or without rewards. +LootList Entity_NPC::fireplace_get_loot(bool isShouldAdvance) { + LootList loot; PlayerManager& players = g_game->playerManager; - RNG& rng = npc.dropRNG; - int variant = npc.variant; - bool isLootless = npc.HasEntityFlags(FLAG_NO_REWARD) || variant == FIRE_WHITE || variant >= FIRE_MOVEABLE; + RNG copy = dropRNG; + RNG& rng = isShouldAdvance ? dropRNG : copy; + bool isLootless = HasEntityFlags(FLAG_NO_REWARD) || variant == FIRE_WHITE || variant >= FIRE_MOVEABLE; auto isTailed = [&] { RNG tail = {rng._seed, 1, 11, 6}; return players.AnyoneHasTrinket(TRINKET_DAEMONS_TAIL) && tail.RandomInt(DAEMONS_TAIL_ODDS) != 0; }; - if (isLootless || rng.RandomFloat() >= (game_is_hard_mode() ? LOOT_CHANCE_HARD : LOOT_CHANCE)) return; + if (isLootless || rng.RandomFloat() >= (game_is_hard_mode() ? LOOT_CHANCE_HARD : LOOT_CHANCE)) return loot; int pickup = PICKUP_HEART; int subtype = 0; if (variant == FIRE_BLUE || variant == FIRE_PURPLE) { - if (isTailed()) return; + if (isTailed()) return loot; subtype = players.GetTrinketMultiplier(TRINKET_DAEMONS_TAIL) < 2 ? HEART_SOUL : HEART_BLACK; } else if (rng.RandomFloat() >= LOOT_HEART_CHANCE || isTailed()) pickup = PICKUP_COIN; - uint32_t seed = rng.Next(); - Entity* drop = g_game->Spawn({.position = npc.pos, .subType = subtype, .type = ENTITY_PICKUP, .variant = pickup, .seed = seed}); - drop->Update(); - g_game->room->isPickupVisionInvalid = true; + loot.entries.push_back({.subType = subtype, .type = ENTITY_PICKUP, .variant = pickup, .seed = rng.Next()}); + return loot; +} + +// A fire put out spawns its loot, advancing the drop RNG, each drop updated at once. +static void fire_loot_spawn(Entity_NPC& npc) +{ + LootList loot = npc.fireplace_get_loot(true); + for (const LootEntry& entry : loot.entries) + g_game->Spawn({.position = npc.pos, .subType = entry.subType, .type = entry.type, .variant = entry.variant, .seed = entry.seed}) + ->Update(); + if (!loot.entries.empty()) g_game->room->isPickupVisionInvalid = true; } // The fire's hits this frame. A normal or red fire loses health to each and goes out at the last of it, or at once to diff --git a/src/npc_fireplace.h b/src/npc_fireplace.h index 201229c..53a653b 100644 --- a/src/npc_fireplace.h +++ b/src/npc_fireplace.h @@ -1,6 +1,6 @@ #pragma once -struct Entity_NPC; +#include "entity_npc.h" // A fireplace's variants (entities2.xml's 33): the fires, the moveable ones and Coal. enum FireplaceVariant : int @@ -16,4 +16,9 @@ enum FireplaceVariant : int FIRE_MOVEABLE_PURPLE = 13 }; +// A fire burns lit, is out, and is told to light again by others (Mother's Shadow, Raglich). +constexpr int FIRE_STATE_OUT = NPC_STATE_IDLE; +constexpr int FIRE_STATE_LIT = NPC_STATE_ATTACK; +constexpr int FIRE_STATE_RELIGHT = NPC_STATE_ATTACK2; + void npc_fireplace_update(Entity_NPC& npc); diff --git a/src/npc_fissure.cpp b/src/npc_fissure.cpp new file mode 100644 index 0000000..6088818 --- /dev/null +++ b/src/npc_fissure.cpp @@ -0,0 +1,111 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "grid_entity.h" +#include +#include + +// The Fissure is a bouncing flame head: it skips across the room diagonally (or where its controller steers), +// fleeing a target within 120 while afraid or shrunk, and bounces on the floor in a splash of drops for 180 frames +// before it dies. Landing on a pit it sinks through it and goes. It trails its last 20 heights for its drawing. +constexpr float FISSURE_START_SPEED = 4; +constexpr float FISSURE_DIAGONAL_SPEED = 0.8f; +constexpr float FISSURE_FRICTION = 0.9f; +constexpr float FISSURE_STEER_SHARE = 0.5f; +constexpr float FISSURE_FLEE_RANGE = 120; +constexpr float FISSURE_FLEE_SCALE = 0.02f; +constexpr float FISSURE_GRAVITY = 0.36f; +constexpr float FISSURE_SINK_GRAVITY = 0.18f; +constexpr float FISSURE_BOUNCE_HEIGHT = -6; +constexpr float FISSURE_BOUNCE_LIFT = -5; +constexpr float FISSURE_SUNK_DEPTH = 30; +constexpr float FISSURE_LIFETIME = 180; +constexpr float FISSURE_SPLASH_RADIUS = 18; +constexpr float FISSURE_START_LIFT = -6; +constexpr float FISSURE_START_HEIGHT = 10; +constexpr size_t FISSURE_TRAIL_LENGTH = 20; + +// Its first frame: launched up from 10 below the floor, with two trail points. +static void fissure_start(Entity_NPC& npc) +{ + npc.v1 = vector_make(FISSURE_START_LIFT, FISSURE_START_HEIGHT); + npc.posOffset.y = FISSURE_START_HEIGHT; + npc.state = NPC_STATE_JUMP; + npc_anim_loop(npc.sprite, "Idle"); + npc.vectorDeque1.push_back(vector_make(0, npc.v1.y)); + npc.vectorDeque1.push_back(vector_make(0, npc.v1.y)); +} + +// Its skid: the first time off in a random direction at 4 with a diagonal push, after that the push follows the way +// it moves on each axis. A controller steers it by half the push, and fear sends it from a near target. +static void fissure_skid(Entity_NPC& npc) +{ + npc.friction *= FISSURE_FRICTION; + if (vector_is_zero(npc.targetPosition)) + { + npc.velocity = vector_scale(random_direction(), FISSURE_START_SPEED); + float diagonal = FISSURE_DIAGONAL_SPEED / std::sqrt(2.0f); + npc.targetPosition = vector_make(diagonal, diagonal); + } + + Vector push = npc.targetPosition; + if ((npc.velocity.x < 0) != (push.x < 0)) push.x = -push.x; + if ((npc.velocity.y < 0) != (push.y < 0)) push.y = -push.y; + if (npc.controllerID != -1) + push = vector_add(push, vector_scale(npc.GetControllerInput(0), vector_length(push) * FISSURE_STEER_SHARE)); + if (npc.friction != 0) npc.velocity = vector_add(npc.velocity, vector_scale(push, npc.speedMultiplier / npc.friction)); + + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.controllerID != -1) return; + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float distance = vector_length(away); + if (distance > 0) away = vector_scale(away, std::clamp((FISSURE_FLEE_RANGE - distance) * FISSURE_FLEE_SCALE, 0.0f, 1.0f) / distance); + if (npc.friction != 0) npc.velocity = vector_add(npc.velocity, vector_scale(away, npc.speedMultiplier / npc.friction)); +} + +// Its bounce: it falls by gravity (half under the floor) and, coming down to the floor, sinks into a pit, bounces in a +// splash, or dies once old. Sunk 30 deep it goes. +static void fissure_bounce(Entity_NPC& npc) +{ + bool isSinking = npc.entityGridCollisionClass == GRIDCOLL_PITSONLY; + npc.v1.x += npc.speedMultiplier * (isSinking ? FISSURE_SINK_GRAVITY : FISSURE_GRAVITY); + npc.v1.y += npc.v1.x * npc.speedMultiplier; + npc.posOffset.y = npc.v1.y; + if (isSinking) + { + if (npc.v1.y > FISSURE_SUNK_DEPTH) npc.Remove(); + return; + } + if (npc.v1.y <= FISSURE_BOUNCE_HEIGHT || npc.v1.x <= 0) return; + + Vector splash = vector_make(FISSURE_SPLASH_RADIUS, FISSURE_SPLASH_RADIUS); + if (room_grid_collision_at(npc.pos) == COLLISION_PIT) + { + water_drops_spawn(npc.pos, splash, 1); + npc.entityGridCollisionClass = GRIDCOLL_PITSONLY; + } + else if (npc.updateTime > FISSURE_LIFETIME) npc.Kill(EntityRef()); + else + { + npc.v1 = vector_make(FISSURE_BOUNCE_LIFT, FISSURE_BOUNCE_HEIGHT); + water_drops_spawn(npc.pos, splash, 1); + npc.PlaySound(SOUND_SPLATTER, 1, 2, false, 1); + } +} + +// 00564f30 The Fissure's AI. +void npc_fissure_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) return fissure_start(npc); + if (npc.state != NPC_STATE_JUMP) return; + + fissure_skid(npc); + float heightBefore = npc.v1.y; + fissure_bounce(npc); + + int ticks = npc_ticks_get(npc); + for (int tick = 1; tick <= ticks; tick++) + { + float height = heightBefore + (npc.v1.y - heightBefore) * ((float)tick / (float)ticks); + npc.vectorDeque1.push_front(vector_make(npc.velocity.x, height)); + while (npc.vectorDeque1.size() > FISSURE_TRAIL_LENGTH) npc.vectorDeque1.pop_back(); + } +} diff --git a/src/npc_gehenna.h b/src/npc_gehenna.h index 7e8f03f..ffa7383 100644 --- a/src/npc_gehenna.h +++ b/src/npc_gehenna.h @@ -45,3 +45,4 @@ 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); +void npc_cohort_update(Entity_NPC& npc); diff --git a/src/npc_generic_prop.cpp b/src/npc_generic_prop.cpp index 9876182..f832fff 100644 --- a/src/npc_generic_prop.cpp +++ b/src/npc_generic_prop.cpp @@ -1,3 +1,4 @@ +#include "boss_final.h" #include "boss_repentance.h" #include "game.h" #include "log.h" @@ -13,8 +14,6 @@ constexpr uint64_t PROP_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_N FLAG_DONT_OVERWRITE | FLAG_NO_KNOCKBACK | FLAG_NO_PHYSICS_KNOCKBACK | FLAG_HIDE_HP_BAR | FLAG_NO_PLAYER_CONTROL; constexpr ColorMod PROP_FADED_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 0.2f}, {0, 0, 0}}; -constexpr int PROP_LAMP = 3; -constexpr int PROP_TV = 4; constexpr int PROP_HOME_STAGE = 13; constexpr int PROP_TV_WAIT = 4; diff --git a/src/npc_poofer.cpp b/src/npc_poofer.cpp index 82f0432..744ad4b 100644 --- a/src/npc_poofer.cpp +++ b/src/npc_poofer.cpp @@ -77,7 +77,6 @@ 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) @@ -222,7 +221,7 @@ static bool burst_heal(Entity_NPC& npc) 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); + type != ENTITY_POOP && !(type == ENTITY_CULTIST && other->variant == CULTIST_POOL); if (isEnemy && !other->isDead && other->IsFriendly() == npc.IsFriendly()) { other->SetColor(BURST_HEAL_FLASH, BURST_HEAL_FLASH_FRAMES, BURST_COLOR_PRIORITY, true, true); diff --git a/src/npc_render_parts.cpp b/src/npc_render_parts.cpp index 61ab722..d0e9a4d 100644 --- a/src/npc_render_parts.cpp +++ b/src/npc_render_parts.cpp @@ -1,10 +1,10 @@ +#include "boss_repentance.h" #include "npc_depths.h" #include "beam_renderer.h" #include "game.h" // Evis' cord layer, the Scourge's chain links and the Chimera's body, as their renders know them. constexpr int EVIS_CORD_LAYER = 1; -constexpr int SCOURGE_CHAIN_LINK = 10; constexpr int SCOURGE_LINK_SHOWN = NPC_STATE_JUMP; constexpr int CHIMERA_BODY = 1; constexpr int CHIMERA_BODY_LAYER = 2; @@ -17,7 +17,6 @@ constexpr int HORNY_BOYS_LAYERS = 3; // Hornfel's segments ride its layers 5 and 6, and its cart's front (its layer 4) follows the cart's layer 1, 224 up. constexpr int HORNFEL_FIRST_SEGMENT_LAYER = 5; constexpr int HORNFEL_CART_LAYER = 1; -constexpr int HORNFEL_FRONT_LAYER = 4; constexpr float HORNFEL_CART_RAISE = 224; // The Ball and Chain's chain (layer 1) runs from 4 out of its anchor (raised 8, flattened) to 10 short of the ball. @@ -63,7 +62,7 @@ void evis_render(Entity_NPC& npc, const Vector& offset) void scourge_chain_render(Entity_NPC& npc, const Vector& offset) { Entity* parent = npc.parent.get(); - bool isFirstLink = !parent || parent->type != ENTITY_SCOURGE || parent->variant != SCOURGE_CHAIN_LINK; + bool isFirstLink = !parent || parent->type != ENTITY_SCOURGE || parent->variant != SCOURGE_CHAIN; if (isFirstLink) return reconstruction_missing("NpcHelper::scourge_chain_render 005832c0"); if (npc.state != SCOURGE_LINK_SHOWN) return; diff --git a/src/npc_spider.cpp b/src/npc_spider.cpp index fbe3b56..500f2b9 100644 --- a/src/npc_spider.cpp +++ b/src/npc_spider.cpp @@ -4,11 +4,11 @@ #include "entity_player.h" #include "game.h" #include "room.h" - -// 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_TICKING_SPIDER = 250; -constexpr int ENTITY_MIGRAINE_SPIDER = 869; +#include "boss_ai.h" +#include "data.h" +#include "entity_config.h" +#include "manager.h" +#include // A spider rests 14 frames, then runs at its target (leading it) when near and in sight, else somewhere at random // within 70 to 110, keeping out of the walls. The jumping kinds leap there one time in three. @@ -50,6 +50,21 @@ constexpr float BIG_SPIDER_OVERKILL = -20; constexpr float TICK_DAMAGE = 40; constexpr float TICK_RADIUS = 60; +// The Migraine spider's death: three troll bombs 4 frames apart, flung at 6 to 10 with fuses of 45, 52 and 59, each +// in grey blood. +constexpr uint32_t MIGRAINE_TIMER_DELAY = 4; +constexpr uint32_t MIGRAINE_TIMER_TIMES = 3; +constexpr float MIGRAINE_FLING_MIN = 6; +constexpr float MIGRAINE_FLING_RANGE = 4; +constexpr int MIGRAINE_FUSE = 66; +constexpr int MIGRAINE_FUSE_STEP = 7; +constexpr float MIGRAINE_BLOOD_SHARE = 0.4f; +constexpr float MIGRAINE_BLOOD_LIFT = -5; +constexpr float MIGRAINE_DROP_SPREAD = 12; +constexpr float MIGRAINE_DROP_SPEED_MIN = 2; +constexpr float MIGRAINE_DROP_SPEED_RANGE = 4; +constexpr ColorMod MIGRAINE_BLOOD_COLOR = {{0.8f, 0.8f, 0.8f, 1}, {1, 0.9f, 0.9f, 1}, {0, 0, 0}}; + static bool is_jumper(int type) { return type == ENTITY_SPIDER_L2 || type == ENTITY_TICKING_SPIDER || type == ENTITY_MIGRAINE_SPIDER; @@ -224,6 +239,60 @@ static void spider_jump_update(Entity_NPC& npc) if (is_jump_ended(anim)) npc.state = NPC_STATE_MOVE; } +// 006baa70 (NpcHelper::spider_load_graphics) Reloads a spider's sprite from its config's .anm2 with a suffix before the +// extension (a mod may redirect it), keeping its animation playing. False when it has no .anm2, no extension or no +// such file. +bool spider_load_graphics(Entity_NPC& npc, std::string_view suffix) +{ + const std::string& path = npc.config->anm2Path; + size_t dot = path.find_last_of('.'); + if (path.empty() || dot == std::string::npos) return false; + + std::string redirected = g_manager->modManager.TryRedirectPath(path.substr(0, dot) + std::string(suffix) + path.substr(dot)); + if (!std::filesystem::exists(resource_path(redirected))) return false; + + std::string animation = npc.sprite.GetAnimation(); + npc.sprite.Load(redirected, GRAPHICS_LOAD); + if (!animation.empty()) npc_anim_loop(npc.sprite, animation); + npc.load_graphics(false); + return true; +} + +// 00528ec0 (NpcHelper::migraine_timer_spawn) The Migraine spider's timer: each tick it flings a troll bomb from where +// the spider died, its fuse longer for the later ones, in a burst of grey blood and a drop or two of it. +void migraine_timer_spawn(Entity_Effect* timer) +{ + Vector spot = timer->pos; + Vector direction = random_direction(); + Vector fling = vector_scale(direction, random_between(MIGRAINE_FLING_MIN, MIGRAINE_FLING_RANGE)); + auto* bomb = static_cast( + g_game->Spawn({.position = spot, .velocity = fling, .type = ENTITY_BOMB, .variant = BOMB_TROLL, .seed = Random()})); + int fuse = MIGRAINE_FUSE - MIGRAINE_FUSE_STEP * timer_times_get(*timer); + bomb->explosionCountdown = fuse; + bomb->explosionCountdown2 = fuse; + + Entity* blood = g_game->Spawn({.position = spot, + .velocity = vector_scale(fling, MIGRAINE_BLOOD_SHARE), + .subType = 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->SetColor(MIGRAINE_BLOOD_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + blood->sprite.offset = vector_make(0, MIGRAINE_BLOOD_LIFT); + blood->renderDepthOffset = BOSS_BLOOD_DEPTH; + for (int drops = (int)(Random() & 1) + 1; drops > 0; drops--) + { + Vector at = vector_add(spot, vector_scale(random_direction(), MIGRAINE_DROP_SPREAD * HALF)); + Vector heading = random_direction(); + Vector velocity = vector_scale(heading, random_between(MIGRAINE_DROP_SPEED_MIN, MIGRAINE_DROP_SPEED_RANGE)); + Entity* drop = g_game->Spawn( + {.position = at, .velocity = velocity, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_PARTICLE, .seed = Random()}); + drop->SetColor(MIGRAINE_BLOOD_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + drop->splatColor = drop->sprite.color; + drop->Update(); + } +} + // A dying ticking spider blows up. static void spider_death(Entity_NPC& npc) { @@ -234,7 +303,12 @@ static void spider_death(Entity_NPC& npc) g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); } else if (npc.type == ENTITY_MIGRAINE_SPIDER) - reconstruction_missing("NpcAI::ENTITY_SPIDER 00529da0: the Migraine spider's timer (Entity_Effect::CreateTimer)"); + { + Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(&migraine_timer_spawn), MIGRAINE_TIMER_DELAY, + MIGRAINE_TIMER_TIMES, false); + timer->pos = npc.pos; + timer->Update(); + } } // 00529da0 The spiders' AI: they rest a moment, then scuttle at their target when it is near and in sight, or @@ -245,7 +319,7 @@ void npc_spider_update(Entity_NPC& npc) PlayerManager& players = g_game->playerManager; bool isPassive = players.FirstCollectibleOwner(COLLECTIBLE_BURSTING_SACK, LAZARUS_SHARE_CHECK) && !npc.IsFriendly(); if (isPassive && (npc.state == NPC_STATE_INIT || g_game->frameCount - npc.spawnFrame == 1)) - reconstruction_missing("NpcAI::ENTITY_SPIDER 00529da0: Bursting Sack's inert spider sheet"); + spider_load_graphics(npc, INERT_SUFFIX); if (npc.state == NPC_STATE_INIT) { npc.state = NPC_STATE_MOVE; diff --git a/src/npc_swarm_spider.cpp b/src/npc_swarm_spider.cpp index 5fdc160..5aa9855 100644 --- a/src/npc_swarm_spider.cpp +++ b/src/npc_swarm_spider.cpp @@ -150,8 +150,7 @@ 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 (isSackActive && isFresh) spider_load_graphics(npc, INERT_SUFFIX); if (npc.state == NPC_STATE_INIT) return clutch_spawn(npc); if (npc.state == NPC_STATE_IDLE) return hop_pick(npc, isSackActive); diff --git a/src/npc_unborn.cpp b/src/npc_unborn.cpp new file mode 100644 index 0000000..a9b00d5 --- /dev/null +++ b/src/npc_unborn.cpp @@ -0,0 +1,202 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_config.h" +#include + +// The Unborn drifts after its target, rolling with its speed and bouncing off walls, and swerves around the tear most +// likely to hit it. Kept between 100 and 500 from its target for 30 frames, it may warp beside the target (120 out +// along the way it was coming) and fade back in. +constexpr float UNBORN_FRICTION = 0.97f; +constexpr float UNBORN_WARP_FRICTION = 0.8f; +constexpr uint32_t UNBORN_GROWL_ODDS = 90; +constexpr int UNBORN_GROWL_DELAY = 60; +constexpr float UNBORN_ROLL_SCALE = 2; +constexpr int UNBORN_ROLL_FRAMES = 12; +constexpr float UNBORN_WARP_NEAR = 100; +constexpr float UNBORN_WARP_FAR = 500; +constexpr int UNBORN_WARP_FRAMES = 30; +constexpr uint32_t UNBORN_WARP_ODDS = 30; +constexpr float UNBORN_BOUNCE = 1.4f; +constexpr float UNBORN_WARP_DISTANCE = 120; +constexpr float UNBORN_WARP_CLEARANCE = 40; +constexpr int UNBORN_WARP_TRIES = 10; +constexpr int UNBORN_NARROW_TRIES = 3; +constexpr int UNBORN_WIDE_TRIES = 6; +constexpr float UNBORN_NARROW_SPREAD = 90; +constexpr float UNBORN_WIDE_SPREAD = 180; +constexpr float UNBORN_RISE_SPEED = 3; +constexpr float UNBORN_DODGE_REACH = 256; +constexpr float UNBORN_TEAR_LOOK = 0.25f; +constexpr float UNBORN_TEAR_THREAT = 3; +constexpr float UNBORN_TEAR_BIAS = 0.5f; +constexpr float UNBORN_DODGE_STRENGTH = 180; +constexpr float UNBORN_DODGE_SOFTEN = 50; +constexpr float UNBORN_DODGE_MAX = 20; +constexpr float UNBORN_DODGE_BRAKE = 0.1f; +constexpr float UNBORN_LEAD = 0.3f; +constexpr float UNBORN_ACCEL = 0.29f; +constexpr float UNBORN_MAX_SPEED = 12; + +// Drifting: it rolls by its speed (the frame of a 12 frame turn), growls now and then, and once held at a middle +// distance for 30 frames warps one frame in 30. It bounces off walls. +static void unborn_drift(Entity_NPC& npc) +{ + npc.friction *= UNBORN_FRICTION; + if (Random() % UNBORN_GROWL_ODDS == 0) npc_sound_play(SOUND_UNBORN_GROWL, 1, UNBORN_GROWL_DELAY, 1); + + float roll = vector_length(npc.velocity) * UNBORN_ROLL_SCALE; + if (npc.velocity.x < 0) roll = -roll; + npc.v1.x = normalize_angle_degrees(roll + npc.v1.x); + float turn = npc.v1.x < 0 ? npc.v1.x + FULL_TURN_DEGREES : npc.v1.x; + int frame = (int)std::floor(turn * UNBORN_ROLL_FRAMES / FULL_TURN_DEGREES); + if (npc.sprite.SetAnimation("Idle", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat((float)(frame % UNBORN_ROLL_FRAMES)); + if (npc.sprite.animState.animData) npc.sprite.animState.isPlaying = false; + } + + if (!npc.HasEntityFlags(FLAG_DISTRACTED)) + { + Entity* target = npc.GetPlayerTarget(); + float distance = vector_distance(npc.pos, target->pos); + if (distance <= UNBORN_WARP_NEAR || distance >= UNBORN_WARP_FAR) npc.i1 = 0; + else if (++npc.i1 > UNBORN_WARP_FRAMES && Random() % UNBORN_WARP_ODDS == 0) + { + npc.targetPosition = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.state = NPC_STATE_JUMP; + npc.i1 = 0; + npc_sound_play(SOUND_UNBORN_WARP, 1, 2, 1); + } + } + if (!npc.isCollidesWithGrid) return; + + float along = vector_dot(npc.gridCollisionVelocity, npc.gridCollisionNormal); + npc.velocity = vector_sub(npc.gridCollisionVelocity, vector_scale(npc.gridCollisionNormal, UNBORN_BOUNCE * along)); +} + +// Warping out: it fades on Effect and, once gone, lands 120 from its target along its approach, turned up to 45, then +// 90, then 180 degrees about the far side over ten tries until the spot is in the room and clear of players. Without +// one it tries again next frame. +static void unborn_warp_out(Entity_NPC& npc) +{ + npc.friction = UNBORN_WARP_FRICTION; + npc.v1.x = 0; + npc.sprite.Play("Teleport"); + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Effect")) + { + npc.shadowSize = 0; + npc.entityCollisionClass = ENTCOLL_NONE; + } + if (!npc_anim_is_done(npc)) return; + + npc.velocity = {}; + Room& room = *g_game->room; + Vector targetPos = npc.GetPlayerTarget()->pos; + Vector spot = vector_add(targetPos, vector_scale(npc.targetPosition, UNBORN_WARP_DISTANCE)); + auto isClear = [&] { return room.IsPositionInRoom(spot, 1) && !npc.IsPlayerInRadius(spot, UNBORN_WARP_CLEARANCE); }; + for (int i = 0; i < UNBORN_WARP_TRIES && !isClear(); i++) + { + float turn = random_unit() - HALF; + if (i < UNBORN_NARROW_TRIES) turn *= UNBORN_NARROW_SPREAD; + else + { + turn *= UNBORN_WIDE_SPREAD; + if (i > UNBORN_WIDE_TRIES) turn += HALF_TURN_DEGREES; + } + spot = vector_add(targetPos, vector_scale(vector_rotated(npc.targetPosition, turn), UNBORN_WARP_DISTANCE)); + } + if (!isClear()) return; + + npc.pos = spot; + npc.state = NPC_STATE_STOMP; +} + +// Warping in: it takes shape on Effect, rising at 3, and steers from then on. True while it steers. +static bool unborn_warp_in(Entity_NPC& npc) +{ + bool isSteering = false; + npc.sprite.Play("TeleportEnd"); + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Effect")) + { + npc.shadowSize = npc.config->shadowSize; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.friction = UNBORN_FRICTION; + npc.velocity = vector_resized(npc.velocity, UNBORN_RISE_SPEED); + isSteering = true; + } + else if (npc.sprite.animState.animData && npc.sprite.animState.WasEventTriggered("Effect")) + { + npc.friction = UNBORN_FRICTION; + isSteering = true; + } + else npc.friction = UNBORN_WARP_FRICTION; + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_IDLE; + return isSteering; +} + +// The tear it fears most: the nearest weighed by how straight it flies at it, a still one counting at 3.5 times its +// distance, within 256. +static Entity* unborn_threat_find(Entity_NPC& npc, float& threatScore) +{ + Entity* threat = nullptr; + threatScore = UNBORN_DODGE_REACH; + for (Entity* tear : entity_query(ENTITY_TEAR, -1)) + { + Vector away = vector_sub(npc.pos, tear->pos); + float distance = vector_length(away); + float aim = 0; + if (!vector_is_zero(tear->velocity)) + { + Vector look = vector_scale(tear->velocity, UNBORN_TEAR_LOOK); + if (vector_length(look) > 1) look = vector_normalized(look); + aim = vector_dot(look, vector_normalized(away)); + if (aim < 0) continue; + } + float score = (UNBORN_TEAR_THREAT - aim * UNBORN_TEAR_THREAT + UNBORN_TEAR_BIAS) * distance; + if (score <= 0 || score > threatScore) continue; + threatScore = score; + threat = tear; + } + return threat; +} + +// Steering: toward its target, sidestepping its worst tear and leading the target, capped at 12. +static void unborn_steer(Entity_NPC& npc) +{ + Vector move = vector_normalized(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + float threatScore = 0; + if (Entity* tear = unborn_threat_find(npc, threatScore)) + { + Vector flight = vector_is_zero(tear->velocity) ? vector_sub(npc.pos, tear->pos) : tear->velocity; + Vector side = vector_rotated(vector_normalized(flight), RIGHT_ANGLE_DEGREES); + if (vector_dot(vector_sub(npc.pos, tear->pos), side) < 0) side = vector_scale(side, -1); + float strength = std::min(UNBORN_DODGE_STRENGTH / (threatScore + UNBORN_DODGE_SOFTEN), UNBORN_DODGE_MAX); + Vector brake = vector_scale(vector_normalized(move), strength * UNBORN_DODGE_BRAKE); + move = vector_add(vector_scale(side, strength), vector_sub(move, brake)); + } + if (!npc.HasEntityFlags(FLAG_DISTRACTED)) move = vector_add(move, vector_scale(npc.GetPlayerTarget()->velocity, UNBORN_LEAD)); + npc.velocity = vector_add(npc.velocity, vector_scale(move, UNBORN_ACCEL * npc.speedMultiplier)); + if (vector_length(npc.velocity) > UNBORN_MAX_SPEED) npc.velocity = vector_resized(npc.velocity, UNBORN_MAX_SPEED); +} + +// 004dca90 The Unborn's AI. +void npc_unborn_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_IDLE; + npc.v1.x = 0; + return; + case NPC_STATE_IDLE: + unborn_drift(npc); + return unborn_steer(npc); + case NPC_STATE_JUMP: + return unborn_warp_out(npc); + case NPC_STATE_STOMP: + if (unborn_warp_in(npc)) unborn_steer(npc); + return; + default: + return; + } +} diff --git a/src/npc_willo_l2.cpp b/src/npc_willo_l2.cpp new file mode 100644 index 0000000..bcb7a5f --- /dev/null +++ b/src/npc_willo_l2.cpp @@ -0,0 +1,200 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "room_grid.h" +#include + +// The level 2 Willo latches onto the nearest enemy of its own side and circles it, riding along with it, spacing +// itself from the other Willos on the same host. Without a host it circles its target at half health. Now and then it +// spits a burning tear at a target within 240. It passes through the enemies of its side. +constexpr float WILLO_L2_HOST_SEARCH = 1e9f; +constexpr float WILLO_L2_LATCH_GAP = 40; +constexpr int WILLO_L2_START_DELAY = 40; +constexpr int WILLO_L2_GLOW_LAYER = 3; +constexpr int WILLO_L2_DISTRACTED_COOLDOWN = 10; +constexpr float WILLO_L2_FRICTION = 0.9f; +constexpr float WILLO_L2_ORBIT_GAP = 20; +constexpr float WILLO_L2_TOO_CLOSE = 0.1f; +constexpr float WILLO_L2_PULL = 0.05f; +constexpr float WILLO_L2_PULL_MAX = 2; +constexpr float WILLO_L2_FAR = 300; +constexpr float WILLO_L2_ORBIT_SPEED = 6; +constexpr float WILLO_L2_ORBIT_PUSH = 3; +constexpr float WILLO_L2_SNAP = 15; +constexpr float WILLO_L2_SPACING_RANGE = 120; +constexpr float WILLO_L2_SPACING = 10; +constexpr float WILLO_L2_SPACING_SOFTEN = 0.1f; +constexpr uint32_t WILLO_L2_ATTACK_ODDS = 9; +constexpr float WILLO_L2_ATTACK_RANGE = 240; +constexpr float WILLO_L2_SHOT_SPEED = 10; +constexpr int WILLO_L2_COOLDOWN = 45; +constexpr ColorMod WILLO_L2_SHOT_COLOR = {{1, 1, 1, 1}, {1, 0.8f, 0.1f, 1}, {0.3f, 0.25f, 0.05f}}; + +// 005591c0 Latches the Willo onto the nearest living enemy of its side it may hunt (not another Willo, a small leech, a +// fly, a Fissure, a Strider or a buried Deep Gaper), or onto nothing. +static Entity* willo_l2_host_find(Entity_NPC& npc) +{ + Entity* host = nullptr; + float best = WILLO_L2_HOST_SEARCH; + bool isFriendly = npc.HasEntityFlags(FLAG_FRIENDLY); + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (!entity || !entity_is_prey(*entity) || entity->isDead) continue; + int type = entity->type; + if (type == ENTITY_WILLO || type == ENTITY_WILLO_L2 || type == ENTITY_SMALL_LEECH || type == ENTITY_FLY || + type == ENTITY_FISSURE || type == ENTITY_STRIDER) + continue; + if (type == ENTITY_DEEP_GAPER && entity->entityCollisionClass == ENTCOLL_NONE) continue; + if (entity->HasEntityFlags(FLAG_FRIENDLY) != isFriendly) continue; + + float distance = vector_length_squared(vector_sub(npc.pos, entity->pos)); + if (distance >= best) continue; + host = entity; + best = distance; + } + npc.entityRef = host; + return host; +} + +// Its first frame: it latches on beside its host, glowing, unbound by the grid and out of the players' control. +static void willo_l2_start(Entity_NPC& npc) +{ + if (Entity* host = willo_l2_host_find(npc)) + { + Vector away = vector_sub(npc.pos, host->pos); + float distance = vector_length(away); + if (distance > 0) away = vector_scale(away, (host->size + WILLO_L2_LATCH_GAP) / distance); + npc.pos = vector_add(host->pos, away); + } + npc.projectileDelay = WILLO_L2_START_DELAY; + npc.state = NPC_STATE_IDLE; + npc.aiCallFlags = AI_CALL_COLLISION; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.AddEntityFlags(FLAG_NO_PLAYER_CONTROL); + npc.i1 = npc.entityRef ? 1 : 0; + layer_additive_set(*npc.sprite.GetLayer(WILLO_L2_GLOW_LAYER)); +} + +// Circling its host (or target): pulled to 20 beyond its edge, pushed around it, and while latched snapped toward its +// side and carried with it the nearer it is. +static void willo_l2_orbit(Entity_NPC& npc, Entity& host) +{ + float reach = host.size + WILLO_L2_ORBIT_GAP; + Vector toward = vector_sub(host.prevPosition, npc.pos); + if (npc.i1 != 0) npc.velocity = vector_sub(npc.velocity, npc.v1); + + float distance = vector_length(toward); + if (distance == 0) distance = WILLO_L2_TOO_CLOSE; + Vector direction = vector_scale(toward, 1 / distance); + Vector side = vector_rotated(direction, RIGHT_ANGLE_DEGREES); + Vector before = npc.velocity; + float pull = std::clamp((distance - reach) * WILLO_L2_PULL, -WILLO_L2_PULL_MAX, WILLO_L2_PULL_MAX); + Vector inward = vector_scale(direction, pull * HALF); + float distance01 = std::clamp((distance - reach) / WILLO_L2_FAR, 0.0f, 1.0f); + float push = std::clamp(WILLO_L2_ORBIT_SPEED - vector_dot(before, side), 0.0f, WILLO_L2_ORBIT_PUSH); + Vector around = vector_scale(side, push); + float share = 1 - distance01; + + if (npc.i1 != 0) + { + Vector snap = vector_sub(vector_sub(host.pos, vector_scale(direction, reach)), npc.pos); + if (vector_length(snap) > WILLO_L2_SNAP) snap = vector_resized(snap, WILLO_L2_SNAP); + float keep = timescale_factor(1 - share * HALF, npc.speedMultiplier); + npc.velocity = vector_add(before, vector_scale(vector_sub(snap, before), 1 - keep)); + } + npc.velocity = vector_add(npc.velocity, vector_scale(vector_add(inward, around), npc.speedMultiplier)); + if (npc.i1 == 0) + { + npc.v1 = {}; + return; + } + npc.v1 = vector_scale(host.velocity, share); + npc.velocity = vector_add(npc.velocity, npc.v1); +} + +// It keeps clear of the other Willos of its side on the same host within 120. +static void willo_l2_space(Entity_NPC& npc) +{ + bool isFriendly = npc.HasEntityFlags(FLAG_FRIENDLY); + for (Entity* other : entity_query_radius(npc.pos, WILLO_L2_SPACING_RANGE, QUERY_ENEMIES)) + { + if (!other || !Entity::is_enemy_type(other->type) || other == &npc || other->type != npc.type) continue; + if (other->HasEntityFlags(FLAG_FRIENDLY) != isFriendly) continue; + if (static_cast(other)->entityRef.get() != npc.entityRef.get()) continue; + + Vector away = vector_sub(npc.pos, other->pos); + float distance = vector_length(away); + if (distance <= 0) continue; + float push = WILLO_L2_SPACING * npc.speedMultiplier / (distance * WILLO_L2_SPACING_SOFTEN + WILLO_L2_SPACING); + npc.velocity = vector_add(npc.velocity, vector_scale(away, push / distance)); + } +} + +// Its attack: one frame in nine, off cooldown, at a target within 240 it warns and spits a burning tear where the +// target is heading. +static void willo_l2_attack(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_IDLE && Random() % WILLO_L2_ATTACK_ODDS == 0 && npc.projectileCooldown <= 0 && + vector_length_squared(vector_sub(npc.pos, npc.CalcTargetPosition(0))) < WILLO_L2_ATTACK_RANGE * WILLO_L2_ATTACK_RANGE) + { + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Attack"); + return; + } + if (npc.state != NPC_STATE_ATTACK) return; + + AnimationState& anim = npc.sprite.animState; + if (anim.animData) + { + if (anim.IsEventTriggered("Warn")) npc_sound_play(SOUND_CANDLE_LIGHT, 1, 2, 1); + if (anim.animData && anim.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_TEARS_FIRE, 1, 2, 1); + Entity* target = npc.GetPlayerTarget(); + ProjectileParams params; + Vector aim = vector_sub(vector_add(target->pos, target->velocity), npc.pos); + params.color = WILLO_L2_SHOT_COLOR; + params.variant = PROJECTILE_TEAR; + params.bulletFlags = PROJECTILE_NO_WALL_COLLIDE; + npc.FireProjectiles(npc.pos, vector_scale(vector_normalized(aim), WILLO_L2_SHOT_SPEED), PROJECTILES_SINGLE, params); + } + if (anim.animData && anim.isPlaying) return; + } + npc.state = NPC_STATE_IDLE; + npc.projectileCooldown = WILLO_L2_COOLDOWN; +} + +// 005593c0 The level 2 Willo's AI. In its collision call it passes through the enemies of its own side. +void npc_willo_l2_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_COLLISION) + { + Entity* other = npc.collisionEntity; + if (Entity::is_enemy_type(other->type) && other->HasEntityFlags(FLAG_FRIENDLY) == npc.HasEntityFlags(FLAG_FRIENDLY)) + npc.collisionResult = 0; + return; + } + + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); + if (npc.HasEntityFlags(FLAG_DISTRACTED)) npc.projectileCooldown = std::max(npc.projectileCooldown, WILLO_L2_DISTRACTED_COOLDOWN); + if (npc.state == NPC_STATE_INIT) return willo_l2_start(npc); + if (npc.state != NPC_STATE_IDLE && npc.state != NPC_STATE_ATTACK) return; + + npc.sprite.Play(npc.state == NPC_STATE_IDLE ? "Fly" : "Attack"); + npc.friction *= WILLO_L2_FRICTION; + if (!npc.entityRef) + { + npc.i1 = willo_l2_host_find(npc) ? 1 : 0; + if (!npc.entityRef) + { + npc.entityRef = npc.GetPlayerTarget(); + npc.health = std::min(npc.health, npc.maxHitPoints * HALF); + } + } + if (Entity* host = npc.entityRef) + { + willo_l2_orbit(npc, *host); + willo_l2_space(npc); + } + willo_l2_attack(npc); +} diff --git a/src/persistent_game_data.h b/src/persistent_game_data.h index 045e06e..2796523 100644 --- a/src/persistent_game_data.h +++ b/src/persistent_game_data.h @@ -18,7 +18,10 @@ constexpr int ACHIEVEMENT_ROTTEN_HEARTS = 411; constexpr int ACHIEVEMENT_PLANETARIUMS = 406; constexpr int ACHIEVEMENT_THE_POLAROID = 57; constexpr int ACHIEVEMENT_THE_NEGATIVE = 78; +constexpr int ACHIEVEMENT_THE_LOST = 82; constexpr int ACHIEVEMENT_KRAMPUS = 142; +constexpr int ACHIEVEMENT_MOVING_BOX = 366; +constexpr int ACHIEVEMENT_RED_KEY = 415; constexpr int ACHIEVEMENT_THE_VOID = 320; constexpr int ACHIEVEMENT_RERUN = 337; constexpr int ACHIEVEMENT_BLUE_BABY = 32; diff --git a/src/platform.h b/src/platform.h index 9b70ff3..c4eb85d 100644 --- a/src/platform.h +++ b/src/platform.h @@ -10,6 +10,9 @@ constexpr uint32_t MS_PER_SECOND = 1000; constexpr uint64_t NS_PER_MS = 1000000; +constexpr int FRAMES_PER_SECOND = 30; +constexpr int SECONDS_PER_MINUTE = 60; +constexpr int SECONDS_PER_HOUR = 3600; struct SDL_GLContextState; struct SDL_Window; diff --git a/src/player_hud.cpp b/src/player_hud.cpp index b1cec00..52f315f 100644 --- a/src/player_hud.cpp +++ b/src/player_hud.cpp @@ -23,7 +23,6 @@ constexpr const char* HEARTS_PNG = "gfx/ui/ui_hearts.png"; constexpr const char* HEARTS_SMALL_PNG = "gfx/ui/ui_hearts_small.png"; constexpr std::string_view CRAFTING_BLIND_GFX = "gfx/Items/Collectibles/questionmark.png"; constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset"; -constexpr const char* COLOR_OFFSET_GOLD_SHADER = "ColorOffsetGold"; constexpr const char* ANIMATION_CURSE_HEART = "CurseHeart"; constexpr const char* ANIMATION_GOLD_OVERLAY = "GoldHeartOverlay"; constexpr const char* ANIMATION_WHITE_OVERLAY = "WhiteHeartOverlay"; @@ -49,6 +48,17 @@ constexpr float CRAFTING_STEP = 12; constexpr float CRAFTING_SLOTS_X = 64; constexpr float CRAFTING_SLOTS_Y = 6; constexpr float CRAFTING_SLOT_REACH = 8; +constexpr const char* CRAFTING_SLOT_ANIMATION = "Idle"; + +// The Cantripped challenge's card table: three cards and one more per Starter Deck (20 at most), the first in the +// result box at full size, the rest in a row leftward at half size, an empty one as an empty slot. +constexpr int CARD_TABLE_BASE = 3; +constexpr int CARD_TABLE_MAX = 20; +constexpr float CARD_RESULT_FRAME = 1; +constexpr float CARD_ROW_X = -26; +constexpr float CARD_ROW_Y = -6; +constexpr float CARD_EMPTY_SHIFT_X = 8; +constexpr float CARD_EMPTY_Y = 2; constexpr int CRAFTING_COLUMNS = 4; // The flash colors of HeartFlash, which add to a heart's color: red, soul, black, gold and rotten. @@ -115,22 +125,15 @@ constexpr int LAST_HEART_FLASH_PERIOD = 45; constexpr int LAST_HEART_FLASH_FRAMES = 10; constexpr int LAST_HEART_FLASH_STEPS = 9; -// A trinket icon: its size, its frames across for Monkey Paw, its shadow, the tint of the error trinket, the clay -// colorize of a Modeling Clay copy and the golden shimmer's steps. -constexpr float TRINKET_SIZE = 32; -constexpr int MONKEY_PAW_FRAMES = 3; +// A trinket icon's shadow. constexpr float TRINKET_SHADOW_ALPHA = 0.3f; constexpr ColorMod TRINKET_SHADOW = {{0, 0, 0, TRINKET_SHADOW_ALPHA}, {0, 0, 0, 0}, {0, 0, 0}}; -constexpr std::array ERROR_TRINKET_TINT = {132 / 255.0f, 26 / 255.0f, 26 / 255.0f}; -constexpr std::array CLAY_COLORIZE = {0.5976471f, 0.33411765f, 0.31058824f, 1}; -constexpr int GOLD_SHIMMER_STEPS = 256; constexpr uint32_t ERROR_TRINKET_POOL = 189; // The active items whose HUD icon is not their item icon, the books Bethany and Judas show over the first slot, and // the Necronomicon's powered icon, which needs three of the form counter it reads. constexpr int NECRONOMICON_FORM = 15; constexpr int NECRONOMICON_FORM_COUNT = 3; -constexpr int POCKET_ACTIVE_SLOT = 2; // The pockets: the small ones behind the first (stacked in the normal HUD, in a row in the others), the first's card // front, its name and Tarot Cloth's glow, the pocket active's icon and the Bag of Crafting's table. @@ -422,7 +425,6 @@ void PlayerHUD::actives_update(bool& isChanged) if (item != active.id) { active.id = item; - if (item < 0) reconstruction_missing("PlayerHUD::Update 00842230: a TMTRAINER active's icon"); ItemConfig_Item* config = g_manager->itemConfig.GetCollectible(item); active.itemImage.reset(); @@ -437,7 +439,7 @@ void PlayerHUD::actives_update(bool& isChanged) if (item == COLLECTIBLE_NECRONOMICON && isNecronomiconPowered) path = NECRONOMICON_POWERED_PNG; if (item == COLLECTIBLE_URN_OF_SOULS) path = is_judas_birthright(shown) ? URN_OF_SOULS_BELIAL_PNG : URN_OF_SOULS_PNG; - if (item == COLLECTIBLE_BAG_OF_CRAFTING && slot != POCKET_ACTIVE_SLOT) path = BAG_OF_CRAFTING_PNG; + if (item == COLLECTIBLE_BAG_OF_CRAFTING && slot != ACTIVE_SLOT_POCKET) path = BAG_OF_CRAFTING_PNG; active.itemImage = Manager::LoadImage(path); } isChanged = true; @@ -462,7 +464,6 @@ static void trinket_icon_load(PlayerHUDTrinket& trinket) constexpr int TRINKET_ICON_PIXELS = 32; constexpr int RGBA = 4; ItemConfig& items = g_manager->itemConfig; - if (trinket.clayItem < 0) reconstruction_missing("PlayerHUD::Update 00842230: a glitched item's clay icon"); ItemConfig_Item* item = trinket.clayItem ? items.GetCollectible(trinket.clayItem) : items.GetTrinket(trinket.id); if (!item) return; trinket.image = Manager::LoadImage(item->gfxFilename); @@ -493,6 +494,18 @@ static void trinket_icon_load(PlayerHUDTrinket& trinket) trinket.offset = vector_make((float)((maxY - minY) / 2 + minY), (float)((maxX - minX) / 2 + minX)); } +// The trinket the error trinket passes for in the current room, picked by the room's spawn seed, or the error trinket +// itself while that seed is 0. +int error_trinket_disguise_get() +{ + uint32_t seed = g_game->GetRoomByIdx(g_game->currentRoomIdx)->spawnSeed; + if (seed == 0) return TRINKET_ERROR; + + seed ^= seed >> 2; + seed ^= seed << 7; + return (int)((seed >> 25 ^ seed) % ERROR_TRINKET_POOL + 1); +} + // The trinket slots of Update: each follows its trinket (the error trinket shows one picked by the room's spawn seed) // and, once it shows Modeling Clay, the item the clay copies, reloading the icon and the offset of its drawn pixels // when either changed. @@ -505,13 +518,7 @@ void PlayerHUD::trinkets_update(bool& isChanged) PlayerHUDTrinket& trinket = trinkets[slot]; int id = (int)(shown.trinkets[slot] & TRINKET_ID_MASK); int clayItem = trinket.id == TRINKET_MODELING_CLAY ? shown.modelingClayEffect : 0; - uint32_t seed = id == TRINKET_ERROR ? g_game->GetRoomByIdx(g_game->currentRoomIdx)->spawnSeed : 0; - if (seed != 0) - { - seed ^= seed >> 2; - seed ^= seed << 7; - id = (int)((seed >> 25 ^ seed) % ERROR_TRINKET_POOL + 1); - } + if (id == TRINKET_ERROR) id = error_trinket_disguise_get(); if (id == trinket.id && clayItem == trinket.clayItem) continue; trinket.id = id; @@ -720,12 +727,6 @@ void PlayerHUD::UpdateHearts(std::span slots, Entity_Player& sho } } -// 00840030 Sets an active slot's charge bar frame for a collectible. -void PlayerHUD::set_active_charge_frame(int) -{ - reconstruction_missing("PlayerHUD::set_active_charge_frame 00840030"); -} - // 00843df0 Draws the hearts in rows of six from at (leftward for Esau's corner of the twin layout), last first, each // tinted by its flash (or the last heart's flash), dimmed past The Forgotten's first row or under an instant death // curse, Tainted Magdalene's pulsing, with the eternal heart over its heart and the golden overlays after. The Holy @@ -1022,7 +1023,7 @@ static void active_icon_frame_set(IconLayout& icon, Entity_Player& shown, int sl break; case COLLECTIBLE_BAG_OF_CRAFTING: { - if (slot == POCKET_ACTIVE_SLOT) + if (slot == ACTIVE_SLOT_POCKET) break; int count = (int)std::ranges::count_if(shown.bagOfCraftingContent, [](char pickup) { return pickup != 0; }); icon.isOutlined = count == BAG_OF_CRAFTING_SIZE; @@ -1040,15 +1041,22 @@ static void active_icon_frame_set(IconLayout& icon, Entity_Player& shown, int sl } } +// Draws a glitched item's icon in a quad from a frame of its cell, through the procedural items' surface. +static void glitched_icon_draw(int id, const SourceQuad& source, const KAGE::Graphics::ColorQuad& quad, + const ColorMod& color) +{ + ProceduralItemManager& glitched = g_game->proceduralItemManager; + apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *glitched.renderTarget); + glitched.render_item(id, source, quad, kcolor_rgba(color._tint[0], color._tint[1], color._tint[2], color._tint[3])); +} + // (008452f0) Draws an active's item icon in a quad from a frame: a glitched item through the procedural items. static void active_item_draw(const PlayerHUDActiveItem& active, const SourceQuad& source, const KAGE::Graphics::ColorQuad& quad, const ColorMod& color) { KAGE::Graphics::manager.shader_default_set(); - if (active.id < 0) - reconstruction_missing("GlitchedCollectibleGfx::render_item 009e0240: a TMTRAINER active's icon"); - if (!active.itemImage) - return; + if (active.id < 0) return glitched_icon_draw(active.id, source, quad, color); + if (!active.itemImage) return; apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *active.itemImage); active.itemImage->Render(source, quad, kcolor_rgba(color._tint[0], color._tint[1], color._tint[2], color._tint[3])); @@ -1431,8 +1439,6 @@ void PlayerHUD::RenderPocketItems(Vector at, PlayerHudLayout layout, float alpha PocketItem& held = shown.pocketItems[0]; bool isActive = held.type == POCKET_ACTIVE; - if (isActive && held.id - 1U < ACTIVE_SLOT_COUNT && shown.activeItems[held.id - 1].item < 0) - reconstruction_missing("PlayerHUD::RenderPocketItems 008471c0: a TMTRAINER pocket active"); ItemConfig_Card* card = held.type == POCKET_CARD ? g_manager->itemConfig.GetCard(held.id) : nullptr; bool isShown = held.id != 0 && (!isActive || (held.id - 1U < ACTIVE_SLOT_COUNT && g_manager->itemConfig.GetCollectible(shown.activeItems[held.id - 1].item))); @@ -1524,12 +1530,12 @@ void PlayerHUD::RenderPocketItems(Vector at, PlayerHudLayout layout, float alpha // (00848c20) Draws an inventory or crafting icon in a quad: a glitched item through the procedural items. static void inventory_icon_draw(const PlayerHUDIcon& icon, const KAGE::Graphics::ColorQuad& quad, const ColorMod& color) { - if (icon.id < 0) reconstruction_missing("GlitchedCollectibleGfx::render_item 009e0240: a TMTRAINER item's icon"); + SourceQuad source = KAGE::Graphics::source_quad_rect({}, vector_make(INVENTORY_ICON_SIZE, INVENTORY_ICON_SIZE)); + if (icon.id < 0) return glitched_icon_draw(icon.id, source, quad, color); if (!icon.image) return; apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *icon.image); - icon.image->Render(KAGE::Graphics::source_quad_rect({}, vector_make(INVENTORY_ICON_SIZE, INVENTORY_ICON_SIZE)), quad, - kcolor_rgba(color._tint[0], color._tint[1], color._tint[2], color._tint[3])); + icon.image->Render(source, quad, kcolor_rgba(color._tint[0], color._tint[1], color._tint[2], color._tint[3])); } // 00848d20 Draws Tainted Isaac's inventory in two rows: each held item's icon at half size over its shadow, shaken @@ -1585,16 +1591,76 @@ static void crafting_frame_set(ANM2& sprite, std::string_view animation, float f sprite.animState.isPlaying = false; } +// Draws an item card's icon over its shadow (shifted by a scale) and widens the corner's bounds to the icon. +void PlayerHUD::card_icon_render(const PlayerHUDIcon& icon, Vector at, float size, float shadowShift) +{ + Vector square = vector_make(size, size); + KAGE::Graphics::manager.shader_default_set(); + inventory_icon_draw(icon, KAGE::Graphics::color_quad_rect(vector_make(at.x + shadowShift, at.y + shadowShift), square, + kcolor_rgba(1, 1, 1, 1)), + INVENTORY_SHADOW); + KAGE::Graphics::ColorQuad quad = KAGE::Graphics::color_quad_rect(at, square, kcolor_rgba(1, 1, 1, 1)); + inventory_icon_draw(icon, quad, COLOR_DEFAULT); + for (Vector corner : {quad._topLeft, quad._bottomRight}) + { + boundsMin = vector_make(std::min(boundsMin.x, corner.x), std::min(boundsMin.y, corner.y)); + boundsMax = vector_make(std::max(boundsMax.x, corner.x), std::max(boundsMax.y, corner.y)); + } +} + +// The Cantripped part of RenderCraftingTable (00849510): the cards held, last first. The first fills the result box +// (faint while empty) with its icon over a shadow the original draws in the same spot. The others line up leftward at +// half size over shadows, an empty one as an empty slot. +void PlayerHUD::render_card_table(Vector at, float tableScale) +{ + ANM2& sprite = hud->craftingTableSprite; + Vector shake = g_game->screenShakeOffset; + int cards = std::min(player->GetCollectibleNum(COLLECTIBLE_STARTER_DECK, ITEM_CHECK_MODIFIED) + CARD_TABLE_BASE, CARD_TABLE_MAX); + auto is_held = [&](int slot) { + return slot < (int)inventoryIcons.size() && (inventoryIcons[slot].image || inventoryIcons[slot].id < 0); + }; + + for (int slot = cards - 1; slot > 0; slot--) + { + float x = (CARD_ROW_X - (float)(slot - 1) * CRAFTING_STEP) * tableScale; + if (is_held(slot)) + { + Vector spot = vector_make(x + shake.x + at.x, at.y + shake.y + tableScale * CARD_ROW_Y); + card_icon_render(inventoryIcons[slot], spot, tableScale * CRAFTING_ICON_SIZE * 0.5f, tableScale); + continue; + } + crafting_frame_set(sprite, CRAFTING_SLOT_ANIMATION, 0); + sprite.Render({vector_make(x + CARD_EMPTY_SHIFT_X * tableScale + at.x, tableScale * CARD_EMPTY_Y + at.y)}); + } + if (cards <= 0) return; + + bool isResultHeld = is_held(0); + crafting_frame_set(sprite, CRAFTING_RESULT_ANIMATION, CARD_RESULT_FRAME); + if (!isResultHeld) sprite.color = CRAFTING_EMPTY_COLOR; + sprite.Render({at}); + sprite.color = COLOR_DEFAULT; + if (isResultHeld) + { + float half = CRAFTING_ICON_SIZE * 0.5f; + card_icon_render(inventoryIcons[0], vector_make(at.x + shake.x - half, at.y + shake.y - half), + tableScale * CRAFTING_ICON_SIZE, 0); + } +} + // 00849510 Draws Tainted Cain's crafting bag: the result box, faint while the bag makes nothing, else with the item's -// icon over its shadow, then the bag's eight pickups in two rows, each widening the corner's bounds. The Cantripped -// challenge's card table is not written yet. +// icon over its shadow, then the bag's eight pickups in two rows, each widening the corner's bounds. In the Cantripped +// challenge it draws the card table instead. void PlayerHUD::RenderCraftingTable(Vector at, float tableScale) { ANM2& sprite = hud->craftingTableSprite; - if (g_game->challenge == CHALLENGE_CANTRIPPED) - reconstruction_missing("PlayerHUD::RenderCraftingTable 00849510 (the Cantripped cards)"); - sprite.scale = vector_make(tableScale, tableScale); + if (g_game->challenge == CHALLENGE_CANTRIPPED) + { + render_card_table(at, tableScale); + KAGE::Graphics::manager.shader_default_set(); + return; + } + crafting_frame_set(sprite, CRAFTING_RESULT_ANIMATION, 0); if (!craftingResultImage) sprite.color = CRAFTING_EMPTY_COLOR; sprite.Render({at}); @@ -1616,7 +1682,7 @@ void PlayerHUD::RenderCraftingTable(Vector at, float tableScale) { Vector spot = vector_make(((float)(slot % CRAFTING_COLUMNS) * CRAFTING_STEP - CRAFTING_SLOTS_X) * tableScale + at.x, ((float)(slot / CRAFTING_COLUMNS) * CRAFTING_STEP - CRAFTING_SLOTS_Y) * tableScale + at.y); - crafting_frame_set(sprite, "Idle", (float)player->bagOfCraftingContent[slot]); + crafting_frame_set(sprite, CRAFTING_SLOT_ANIMATION, (float)player->bagOfCraftingContent[slot]); sprite.Render({spot}); boundsMin = vector_make(std::min(boundsMin.x, spot.x - reach), std::min(boundsMin.y, spot.y - reach)); boundsMax = vector_make(std::max(boundsMax.x, spot.x + reach), std::max(boundsMax.y, spot.y + reach)); diff --git a/src/player_hud.h b/src/player_hud.h index 492f3f1..b5fd38d 100644 --- a/src/player_hud.h +++ b/src/player_hud.h @@ -16,6 +16,14 @@ constexpr int PLAYER_HUD_TRINKET_COUNT = 2; constexpr int PLAYER_HUD_POCKET_COUNT = 4; constexpr float PLAYER_HUD_BOUNDS_FAR = 1e7f; +// A trinket icon as the corners and the recent items draw it: its size, its frames across for Monkey Paw, the tint of +// the error trinket, the clay colorize of a Modeling Clay copy and the golden shimmer's steps. +constexpr float TRINKET_SIZE = 32; +constexpr int MONKEY_PAW_FRAMES = 3; +constexpr std::array ERROR_TRINKET_TINT = {132 / 255.0f, 26 / 255.0f, 26 / 255.0f}; +constexpr std::array CLAY_COLORIZE = {0.5976471f, 0.33411765f, 0.31058824f, 1}; +constexpr int GOLD_SHIMMER_STEPS = 256; + // REPENTOGON's HUD layouts of a player, and the spot an online player's status takes. enum PlayerHudLayout : int { @@ -116,7 +124,6 @@ struct PlayerHUD void assign(Entity_Player* shown); void Update(); void UpdateHearts(std::span slots, Entity_Player& shown); - void set_active_charge_frame(int collectibleId); void RenderHearts(Vector& outExtent, ANM2& sprite, PlayerHudLayout layout, float heartScale, Vector at); void RenderActiveItem(int activeSlot, Vector at, PlayerHudLayout layout, float itemScale, float alpha); void RenderTrinket(int trinketSlot, Vector at, float trinketScale, bool isSmall); @@ -133,4 +140,8 @@ private: void pockets_update(); void inventory_update(); void trinket_draw(const PlayerHUDTrinket& trinket, Vector at, const ColorMod& color, float trinketScale); + void card_icon_render(const PlayerHUDIcon& icon, Vector at, float size, float shadowShift); + void render_card_table(Vector at, float tableScale); }; + +int error_trinket_disguise_get(); diff --git a/src/player_manager.cpp b/src/player_manager.cpp index 3ecf000..2651fae 100644 --- a/src/player_manager.cpp +++ b/src/player_manager.cpp @@ -74,7 +74,6 @@ constexpr uint64_t GAME_STATE_COOP_BABIES_ONLY = 0x10; // The xorshift triples by shift index: the player generator's, the baby shuffle's, the owner rolls' and the // glitched baby's. -constexpr uint32_t PLAYER_RNG_SHIFT = 34; constexpr uint32_t BABY_SHUFFLE_SHIFT = 27; constexpr uint32_t OWNER_ROLL_SHIFT = 22; @@ -133,6 +132,20 @@ static void room_player_add(Entity_Player* player) room.GetEntities()->AddEntity(player); } +// 009b9f60 Lists a player again at the end of the list (Tainted Lazarus's Birthright split) and adds it to the room. +void PlayerManager::player_add(Entity_Player* player) +{ + player->playerIndex = (int)playerList.size(); + playerList.push_back(player); + room_player_add(player); +} + +// 009b9fc0 Takes a player out of the list, the others keeping their indices. +void PlayerManager::player_remove(Entity_Player* player) +{ + if (auto slot = std::ranges::find(playerList, player); slot != playerList.end()) playerList.erase(slot); +} + // The player with the highest roll, one roll drawn from seed for each player picked, or null. template static Entity_Player* player_roll(std::vector& players, uint32_t seed, Picked isPicked) @@ -649,6 +662,16 @@ KColor PlayerManager::GetPlayerColorValue(int playerColor) return kcolor_argb(PLAYER_COLOR_INVALID); } +// 0042d060 The color a player is outlined in: its controller's player color as the tint and the offset, none (5) when +// no color is assigned to the controller. +ColorMod PlayerManager::player_color_mod_get(const Entity_Player& player) +{ + auto slot = std::ranges::find(colorControllers, player.controllerIndex); + int colorIndex = slot == colorControllers.end() ? PLAYER_COLOR_NONE : (int)(slot - colorControllers.begin()); + KColor color = GetPlayerColorValue(colorIndex); + return {{color._red, color._green, color._blue, 1}, {0, 0, 0, 0}, {color._red, color._green, color._blue}}; +} + // Frees every co-op seat, keeping whether its character was forced, as the original does inline. void PlayerManager::coop_slots_reset() { diff --git a/src/player_manager.h b/src/player_manager.h index 2614f0b..c5b9231 100644 --- a/src/player_manager.h +++ b/src/player_manager.h @@ -11,6 +11,7 @@ constexpr int RANDOM_BABY_COUNT = 5; // The xorshift the manager's generators start on, before a run seeds them (shift index 35). constexpr RNG PLAYER_RNG_UNSEEDED = {0xaa17414f, 5, 9, 7}; +constexpr uint32_t PLAYER_RNG_SHIFT = 34; // Whether an item query also asks the dead Lazarus kept as a backup player, for items tagged as shared globally. enum LazarusShare @@ -51,6 +52,9 @@ struct CoopJoinSlot bool isPlayerTypeForced = false; }; +// The player color index of a controller with none assigned. +constexpr int PLAYER_COLOR_NONE = 5; + // The players of a run (Game::playerManager): the room's players with their twins and co-op babies, the extra players // kept out of the room, the join seats and colors of co-op controllers, and the characters and babies co-op offers. // Players are entities of the room. The manager holds them by pointer and deletes them with itself. @@ -89,6 +93,8 @@ public: void remove_coplayers_without_device(); void players_clear(); bool replace_player(Entity_Player* oldPlayer, Entity_Player* newPlayer); + void player_add(Entity_Player* player); + void player_remove(Entity_Player* player); void ReviveCoopPlayer(uint32_t index); void revive_player_ghosts(); @@ -124,6 +130,7 @@ public: int GetPlayerSlotFromController(int controllerId); void AssignPlayerColor(int controllerId); static KColor GetPlayerColorValue(int playerColor); + ColorMod player_color_mod_get(const Entity_Player& player); void restore_controller_assignment(); void coop_slots_reset(); void handle_coop_join(); diff --git a/src/popups.cpp b/src/popups.cpp index f3b2905..e9a5fb3 100644 --- a/src/popups.cpp +++ b/src/popups.cpp @@ -43,6 +43,7 @@ constexpr float SHADOW_ALPHA = 0.4f; constexpr float SHADOW_SHIFT = 5; constexpr float FADE_MS = 1000; constexpr float SLIDE_MS = 112; +constexpr float GLYPH_SCALE = 1.5f; constexpr uint32_t SLIDE_OUT_MS = 112; constexpr float SLIDE_IN_Y = -223; constexpr float SLIDE_OUT_Y = -233; @@ -793,7 +794,7 @@ static std::string_view key_name_get(int action) // 00423cc0 Draws the buttons while the active controller is connected, each with its label frame, then the key name // of its action on the keyboard, and the callback. -// The original reads an action out of range, which this shows as None. Gamepads show glyphs, not taken over yet. +// The original reads an action out of range, which this shows as None. Gamepads show their glyph instead. void PopupButtons::Render() { std::shared_ptr device = KAGE::Input::manager.device_find(active_controller_get()); @@ -814,7 +815,13 @@ void PopupButtons::Render() if (button.buttonAction == BUTTON_ACTION_NONE || !button.isVisible) continue; if (device->type != KAGE::Input::DEVICE_KEYBOARD) - reconstruction_missing("Manager::render_controller_action_glyph 0095af30"); + { + g_manager->render_controller_action_glyph({.position = get_label_position(i), + .scale = vector_make(scale * GLYPH_SCALE, scale * GLYPH_SCALE), + .action = button.buttonAction, + .controllerIndex = device->id}); + continue; + } FontSettings settings(ALIGN_CENTER); g_manager->font1_TeamMeatEx10.DrawString(key_name_get(button.buttonAction), get_label_position(i), vector_make(scale, scale), kcolor_argb(BUTTON_LABEL_ARGB), settings); diff --git a/src/procedural_item_manager.cpp b/src/procedural_item_manager.cpp index 05bcb59..1f5e035 100644 --- a/src/procedural_item_manager.cpp +++ b/src/procedural_item_manager.cpp @@ -9,6 +9,8 @@ constexpr const char* ITEM_SURFACE = "Procedural Item Surface"; constexpr const char* COLLECTION_SURFACE = "Procedural Item Collection Surface"; constexpr int ITEM_SURFACE_SIZE = 1024; constexpr int COLLECTION_SURFACE_SIZE = 512; +constexpr int ITEM_CELLS_PER_ROW = 32; +constexpr float ITEM_CELL_SIZE = 32; // The seed of the glitched item a G FUEL! run starts with. constexpr uint32_t G_FUEL_ITEM_SEED = 1; @@ -55,6 +57,23 @@ void ProceduralItemManager::items_restore(const std::vector& seeds) for (uint32_t seed : seeds) CreateProceduralItem(seed, 0); } +// 009e0240 Draws a glitched item's icon, its 32 pixel cell of the item surface by -1 - id, and whether it had one. +// Rebirth named it GlitchedCollectibleGfx::render_item. +bool ProceduralItemManager::render_item(int itemId, const SourceQuad& source, const KAGE::Graphics::ColorQuad& quad, + const KColor& color) +{ + int index = -1 - itemId; + if (itemId >= 0 || index >= (int)proceduralItems.size() || !proceduralItems[index]->item) return false; + + Vector cell = vector_make((float)(index % ITEM_CELLS_PER_ROW) * ITEM_CELL_SIZE, + (float)(index / ITEM_CELLS_PER_ROW) * ITEM_CELL_SIZE); + SourceQuad atlas = source; + for (Vector* corner : {&atlas._topLeft, &atlas._topRight, &atlas._bottomLeft, &atlas._bottomRight}) + *corner = vector_add(*corner, cell); + renderTarget->Render(atlas, quad, color); + return true; +} + int ProceduralItemManager::CreateProceduralItem(uint32_t, uint32_t) { reconstruction_missing("ProceduralItemManager::CreateProceduralItem 009dcc70"); diff --git a/src/procedural_item_manager.h b/src/procedural_item_manager.h index 60fa48e..be350ed 100644 --- a/src/procedural_item_manager.h +++ b/src/procedural_item_manager.h @@ -22,4 +22,5 @@ public: void Init(); void items_restore(const std::vector& seeds); int CreateProceduralItem(uint32_t seed, uint32_t flags); + bool render_item(int itemId, const SourceQuad& source, const KAGE::Graphics::ColorQuad& quad, const KColor& color); }; diff --git a/src/rail_manager.cpp b/src/rail_manager.cpp index 46246d4..086a8e9 100644 --- a/src/rail_manager.cpp +++ b/src/rail_manager.cpp @@ -5,6 +5,9 @@ #include "log.h" #include "npc_ai.h" #include "room.h" +#include +#include +#include // The row and the columns where an L room's walls step in around its missing quarter. constexpr int L_ROW = 7; @@ -194,3 +197,59 @@ RailPoint RailManager::get_closest_rail_point(Vector position, Vector velocity, if (travel < 0 || (travel == 0 && !(gridIndex & 1))) closest.direction = vector_scale(closest.direction, -1); return closest; } + +// 009e3450 (RoomGridPath::can_step) Whether a minecart may step from a cell to a neighbour along the from cell's track. +bool RailManager::can_step(int fromIndex, int toIndex) +{ + int width = g_game->room->gridWidth; + int rowStep = toIndex / width - fromIndex / width; + int columnStep = toIndex % width - fromIndex % width; + if (std::abs(rowStep) + std::abs(columnStep) != 1 || fromIndex < 0 || fromIndex >= ROOM_GRID_CELLS) return false; + if (rails[fromIndex] == RAIL_NONE || (rails[fromIndex] & RAIL_PIECE_MASK) >= RAIL_TRACK_COUNT) return false; + + const RailTrack& track = RAIL_TRACKS[rails[fromIndex] & RAIL_PIECE_MASK]; + auto edge = [](float offset) { return offset == -RAIL_REACH ? -1 : offset == RAIL_REACH ? 1 : 0; }; + for (int i = 0; i < track.count; i++) + if (edge(track.points[i].x) == columnStep && edge(track.points[i].y) == rowStep) return true; + return false; +} + +// 009e3560 (room_grid_flood_fill) Whether the rails lead from one cell to another, searched depth first. A crossing +// is only passed straight on. +bool RailManager::flood_fill(int startIndex, int targetIndex) +{ + constexpr int STEPS[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; + constexpr uint8_t RAIL_CROSSING = 6; + struct Visit + { + int index = 0; + int direction = 0; + }; + Room& room = *g_game->room; + std::bitset visited; + std::vector pending = {{startIndex, -1}}; + visited.set(startIndex); + while (!pending.empty()) + { + Visit cell = pending.back(); + pending.pop_back(); + if (cell.index == targetIndex) return true; + if (cell.index >= ROOM_GRID_CELLS || rails[cell.index] == RAIL_NONE) continue; + + bool isCrossing = (rails[cell.index] & RAIL_PIECE_MASK) == RAIL_CROSSING; + int x = cell.index % room.gridWidth; + int y = cell.index / room.gridWidth; + for (int direction = 0; direction < 4; direction++) + { + if (isCrossing && direction != cell.direction) continue; + int nx = x + STEPS[direction][0]; + int ny = y + STEPS[direction][1]; + if (nx < 0 || ny < 0 || nx >= room.gridWidth || ny >= room.gridHeight) continue; + int next = ny * room.gridWidth + nx; + if (next >= ROOM_GRID_CELLS || visited[next] || rails[next] == RAIL_NONE || !can_step(cell.index, next)) continue; + pending.push_back({next, direction}); + visited.set(next); + } + } + return false; +} diff --git a/src/rail_manager.h b/src/rail_manager.h index c48eb8b..7249919 100644 --- a/src/rail_manager.h +++ b/src/rail_manager.h @@ -48,4 +48,6 @@ struct RailManager void init(); void Render(Vector offset); RailPoint get_closest_rail_point(Vector position, Vector velocity, int gridIndex, int railType); + bool can_step(int fromIndex, int toIndex); + bool flood_fill(int startIndex, int targetIndex); }; diff --git a/src/render_passes.h b/src/render_passes.h index db80518..bce6d6d 100644 --- a/src/render_passes.h +++ b/src/render_passes.h @@ -2,6 +2,12 @@ #include "kage_graphics.h" #include +#include + +// The screen's color correction shader, and the sprite shaders that animate a glitched (Dogma's static) or golden item. +constexpr std::string_view COLOR_CORRECTION_SHADER = "ColorCorrection"; +constexpr std::string_view COLOR_OFFSET_DOGMA_SHADER = "ColorOffsetDogma"; +constexpr std::string_view COLOR_OFFSET_GOLD_SHADER = "ColorOffsetGold"; // Whether apply_sprite_shader_params sets the color uniforms too, or keeps the ones the shader has. enum SpriteShaderColor diff --git a/src/room.h b/src/room.h index 9b833c8..05a8e5b 100644 --- a/src/room.h +++ b/src/room.h @@ -377,6 +377,7 @@ public: void LoadBackdropGraphics(); void reload_backdrop(); void MakeDoor(int slot); + void update_door_targets(); void make_walls(); void crawlspace_walls_make(); void crawlspace_ladders_make(); diff --git a/src/room_clear.cpp b/src/room_clear.cpp index 6d79c51..60885b4 100644 --- a/src/room_clear.cpp +++ b/src/room_clear.cpp @@ -37,7 +37,6 @@ constexpr int COLLECTIBLE_CONTRACT_FROM_BELOW = 241; constexpr int COLLECTIBLE_THERES_OPTIONS = 249; constexpr int COLLECTIBLE_DEEP_POCKETS_CLEAR = 416; constexpr int COLLECTIBLE_OPTIONS = 670; -constexpr int COLLECTIBLE_SWARM = 693; constexpr int COLLECTIBLE_LITTLE_CHAD = 96; constexpr int COLLECTIBLE_LITTLE_GISH = 99; constexpr int COLLECTIBLE_STEVEN = 50; @@ -1407,8 +1406,7 @@ void room_clear_trigger(Room& room, ClearSound sound) params.endStage == STAGE_HOME; int nextStage = (int)game.stage + (game.filter_curses(CURSE_OF_LABYRINTH) ? 1 : 0); if (isPathChallenge && Room::IsCurrentRoomLastBoss() && nextStage == STAGE_DEPTHS_II) - reconstruction_missing("Room::TriggerClear 008068f0: a path challenge's doors (Room::update_door_targets " - "00802670)"); + room.update_door_targets(); bool isGreed = game.IsGreedMode(); if (!isGreed) room.TrySpawnSecretExit(true, false); diff --git a/src/room_config.cpp b/src/room_config.cpp index 3d83a1a..d2ae3bc 100644 --- a/src/room_config.cpp +++ b/src/room_config.cpp @@ -34,7 +34,6 @@ constexpr std::string_view STAGES_CATEGORY = "Stages"; constexpr std::string_view CURSES_CATEGORY = "Curses"; constexpr std::string_view MINIBOSSES_CATEGORY = "Minibosses"; constexpr std::string_view GENERATED_ROOM_NAME = "generated"; -constexpr char LOCALIZED_KEY_PREFIX = '#'; constexpr int CURSE_SLOTS = 9; constexpr uint16_t QUEST_DOOR_VARIANT = 2; @@ -146,7 +145,7 @@ static std::string localized_get(std::string_view category, std::string_view tex StringTable& table = g_manager->stringTable; bool isMissing = false; - if (text.empty() || text[0] != LOCALIZED_KEY_PREFIX) return std::string(text); + if (text.empty() || text[0] != STRING_KEY_PREFIX) return std::string(text); if (language == LANGUAGE_CURRENT) language = table.language; std::string_view localized = table.get_string(category, language, text.substr(1), &isMissing); return std::string(isMissing ? text : localized); diff --git a/src/room_lighting.cpp b/src/room_lighting.cpp index 892085c..819d780 100644 --- a/src/room_lighting.cpp +++ b/src/room_lighting.cpp @@ -1,3 +1,4 @@ +#include "boss_repentance.h" #include "entity_bomb.h" #include "entity_effect.h" #include "entity_familiar.h" @@ -82,9 +83,6 @@ constexpr int BOOMFLY_DRAGON_FLY = 3; constexpr int LAMB_VARIANT_LIGHT = 10; constexpr int PREY_VARIANT_LIGHT = 1; constexpr int ROCK_SPIDER_VARIANT_LIGHT = 2; -constexpr int VISAGE_HEART = 0; -constexpr int VISAGE_MASK = 1; -constexpr int VISAGE_CHAIN = 20; constexpr int VISAGE_HEART_STATE_LIT = 113; constexpr int VISAGE_HEART_STATE_FLARE = 104; constexpr int VISAGE_MASK_STATE_LIT = 105; @@ -846,7 +844,7 @@ static void visage_light_render(LightPass& pass) light_draw(pass, {LIGHT_TARGET, rise}); else if (visage.variant == VISAGE_HEART && visage.state == VISAGE_HEART_STATE_FLARE) light_draw(pass, {LIGHT_TARGET, rise, uniform(1.5f)}); - else if (visage.variant == VISAGE_CHAIN) + else if (visage.variant == VISAGE_PLASMA) light_draw(pass, {LIGHT_TARGET, rise, uniform(0.6f), 0, 1}); } diff --git a/src/room_special.cpp b/src/room_special.cpp index ff92e05..ea17b01 100644 --- a/src/room_special.cpp +++ b/src/room_special.cpp @@ -16,7 +16,6 @@ #include #include -constexpr int TRINKET_STORE_CREDIT = 13; constexpr int TRINKET_KEEPERS_BARGAIN = 171; constexpr int TRINKET_ADOPTION_PAPERS = 184; constexpr int ACHIEVEMENT_HOLY_CARD = 293; @@ -618,16 +617,6 @@ void game_random_room_move(Game& game, bool isErrorRoom, uint32_t seed, Entity_P {.player = player, .animation = TRANSITION_TELEPORT, .roomIndex = game.GetRandomRoomIndex(isErrorRoom, seed)}); } -// A pickup or enemy a shopkeeper drops when it dies (the original's LootList entry): its kind, seed and the RNG -// a thrown spider uses. -struct ShopkeeperLoot -{ - int subType = 0; - int type = 0; - int variant = 0; - uint32_t seed = 0; -}; - // The secret room shopkeepers' rare trinkets. constexpr std::array SHOPKEEPER_TRINKETS = {1, 24, 49, 50, 51, 52}; constexpr int SHOPKEEPER_TRINKET_TRIES = 3; @@ -664,9 +653,9 @@ static int shopkeeper_trinket_roll(RNG& rng) // 006c1ac0 What a shopkeeper drops when it dies (Entity_NPC::shopkeeper_get_loot), from its drop RNG, which only an // advancing draw moves on: rarely Steam Sale, Head of the Keeper or Coupon, else two spiders, two coins or nothing. // A secret room's shopkeeper rarely hides Greed, else a rare trinket or a nickel. One without a reward drops nothing. -static std::vector shopkeeper_loot_get(Entity_NPC& npc, bool isAdvance) +std::vector shopkeeper_loot_get(Entity_NPC& npc, bool isAdvance) { - std::vector loot; + std::vector loot; if (npc.HasEntityFlags(FLAG_NO_REWARD)) return loot; RNG copy = npc.dropRNG; @@ -756,10 +745,10 @@ void npc_shopkeeper_update(Entity_NPC& npc) game.gameStateFlags |= 1ull << GAME_STATE_SHOPKEEPER_KILLED; game.levelStateFlags |= 1u << LEVEL_STATE_SHOPKEEPER_KILLED; - std::vector loot = shopkeeper_loot_get(npc, true); + std::vector loot = shopkeeper_loot_get(npc, true); for (size_t i = 0; i < loot.size(); i++) { - ShopkeeperLoot& drop = loot[i]; + LootEntry& drop = loot[i]; if (drop.type == ENTITY_SPIDER) { Vector target = i == 0 ? room_free_pickup_position_find({npc.pos, SHOPKEEPER_SPIDER_RANGE}) : Vector{}; diff --git a/src/room_transition.cpp b/src/room_transition.cpp index c687cac..4ba20ff 100644 --- a/src/room_transition.cpp +++ b/src/room_transition.cpp @@ -1,4 +1,5 @@ #include "room_transition.h" +#include "boss_final.h" #include "boss_pool.h" #include "entity_familiar.h" #include "entity_npc.h" @@ -49,7 +50,6 @@ constexpr float SCREEN_CELL_SIZE = 26; constexpr int ROOM_CELLS_ACROSS = 13; constexpr int ROOM_CELLS_DOWN = 7; constexpr float TELEPORTER_SCATTER = 10; -constexpr int DOGMA_ROOM_VARIANT = 1000; // 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. @@ -218,6 +218,38 @@ static void teleporter_arrival_place(Room& room, int target) } } +// Part of 00830950: the players come onto the Death Certificate's floor in the fourth row's eleventh cell, all but the +// first scattered 10 about it, appearing frozen. +static void death_certificate_players_place(Room& room) +{ + constexpr int ARRIVAL_COLUMN = 10; + constexpr int ARRIVAL_ROW = 4; + constexpr int ARRIVAL_MIN_WIDTH = 11; + constexpr int ARRIVAL_MIN_HEIGHT = 5; + constexpr float ARRIVAL_SCATTER = 10; + + int cell = room.gridWidth < ARRIVAL_MIN_WIDTH || room.gridHeight < ARRIVAL_MIN_HEIGHT ? -1 + : room.gridWidth * ARRIVAL_ROW + ARRIVAL_COLUMN; + Vector arrival = vector_make((float)(cell % room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_X, + (float)(cell / room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_Y); + Vector spot = arrival; + int placed = 0; + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (!player) continue; + if (placed++ != 0) + { + float angle = random_unit() * RANDOM_PI; + angle += angle; + spot = vector_add(arrival, vector_make(std::cos(angle) * ARRIVAL_SCATTER, std::sin(angle) * ARRIVAL_SCATTER)); + } + player->pos = spot; + player->PlayExtraAnimation(ANIMATION_APPEAR); + if (player->sprite.animState.animData) player->sprite.animState.SetFrameFloat(APPEAR_FRAME); + player->isControlsEnabled = false; + } +} + // Puts the players in the new room. A teleport keeps them hidden, else the main players not held show. The Forgotten's // body, the Death Certificate's floor, a teleporter's pad and the Ventricle Razor's portals place them. void RoomTransition::arrival_place() @@ -244,7 +276,7 @@ void RoomTransition::arrival_place() player.Teleport(player.forgottenBodyPos, false, false); } else if (animation == TRANSITION_DEATH_CERTIFICATE && game.currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE) - reconstruction_missing("RoomTransition::ChangeRoom 00830950: the players placed on the Death Certificate floor"); + death_certificate_players_place(room); else if (animation == TRANSITION_DEATH_CERTIFICATE) for (Entity_Player* player : game.playerManager.playerList) { diff --git a/src/room_update.cpp b/src/room_update.cpp index 67d4016..4d5745c 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -1,4 +1,5 @@ #include "npc_basement.h" +#include "boss_final.h" #include "entity_effect.h" #include "entity_laser.h" #include "entity_npc.h" @@ -158,10 +159,8 @@ constexpr uint32_t RNG_SHIFT_COUPON_2 = 27; // The entities with ambient loops of their own (Lua's EntityType, EffectVariant and laser variants). constexpr int AMBIENT_FLY_TYPES[] = {13, 14, 18, 25, 61, 80, 214, 222, 249, 256, 281, 296, 808, 819, 838, 868}; constexpr int BEAST_FLY_VARIANTS[] = {11, 21}; -constexpr int DOGMA_ANGEL = 2; constexpr int DOGMA_ANGEL_STATE = 10; constexpr int LASER_LOOP_VARIANTS[] = {6, 15}; -constexpr int BLACKHOLE_STATE_OPEN = 1; // How the sources sound: the reach of the enemies' loops, the flies' buzz (Hush's flies quieter, the whole buzz capped), // fire, portals and rifts, a laser, Vis Fatty's, the Urn of Souls', the black hole's and the ball and chain's reach, @@ -861,6 +860,80 @@ static void coupon_update(Room& room) descriptor.shopItemDiscountIdx = (int16_t)rng.RandomInt((uint32_t)descriptor.shopItemIdx); } +// 00802670 Makes every door the room's layout allows and points each at its neighbour, with both rooms' types, then +// updates the map. +void Room::update_door_targets() +{ + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) + { + if (!(descriptor->allowedDoors & 1u << slot)) continue; + MakeDoor(slot); + GridEntity_Door* door = doors[slot]; + int target = descriptor->doors[slot]; + if (target < 0) continue; + RoomDescriptor* neighbour = g_game->GetRoomByIdx(target); + if (!neighbour->data || !door) continue; + door->targetRoomIdx = target; + door->SetRoomTypes(descriptor->data->type, neighbour->data->type); + door->slot = slot; + } + g_game->UpdateVisibility(); +} + +// Part of 00802980: the Beast's arena burns. Every 4 frames the players in the lava 30 above the floor are slowed and +// singed, and half the frames an ember rises from the lava (two in three behind the room, fainter and smaller). +static void home_crawlspace_update(Room& room) +{ + constexpr float LAVA_DEPTH = 30; + constexpr int LAVA_BURN_EVERY = 4; + constexpr int LAVA_SLOW_FRAMES = 4; + constexpr float LAVA_SLOW = 0.6f; + constexpr ColorMod LAVA_SLOW_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {0.15686275f, 0.15686275f, 0.15686275f}}; + constexpr int LAVA_HIT_COUNTDOWN = 30; + constexpr float HOME_EMBER_RISE = -2.88f; + constexpr float HOME_EMBER_DRIFT = 0.4f; + constexpr float HOME_EMBER_TOP = 40; + constexpr int HOME_EMBER_LAVA = 10; + constexpr float HOME_EMBER_SCALE = 0.8f; + constexpr float HOME_EMBER_SCALE_RANGE = 1.2f; + constexpr uint32_t HOME_EMBER_FRONT_ODDS = 3; + constexpr float HOME_EMBER_FRONT_DEPTH = 80; + constexpr float HOME_EMBER_BACK_SHADE = 0.6f; + + Game& game = *g_game; + float lava = room.bottomRightPos.y - LAVA_DEPTH; + if (room.isInitialized && (game.frameCount - room.enterFrame) % LAVA_BURN_EVERY == 0) + for (Entity_Player* player : game.playerManager.playerList) + { + if (player->pos.y + player->size < lava || player->entityCollisionClass == ENTCOLL_NONE) continue; + player->AddSlowing(EntityRef(), LAVA_SLOW_FRAMES, LAVA_SLOW, LAVA_SLOW_COLOR, false); + player->TakeDamage(1, DAMAGE_FIRE, EntityRef(), LAVA_HIT_COUNTDOWN); + } + if ((Random() & 1) != 0) return; + + float rise = random_unit() * HOME_EMBER_RISE; + Vector drift = vector_make((random_unit() - HALF) * HOME_EMBER_DRIFT, rise); + float top = room.topLeftPos.x + HOME_EMBER_TOP; + float y = (lava - top) * random_unit() + top; + Vector at = vector_make((room.bottomRightPos.x - room.topLeftPos.x) * random_unit() + room.topLeftPos.x, y); + Entity* ember = game.Spawn({.position = at, + .velocity = drift, + .subType = HOME_EMBER_LAVA, + .type = ENTITY_EFFECT, + .variant = EFFECT_EMBER_PARTICLE, + .seed = Random()}); + float scale = random_unit() * HOME_EMBER_SCALE_RANGE + HOME_EMBER_SCALE; + ember->sprite.scale = vector_make(scale, scale); + if (Random() % HOME_EMBER_FRONT_ODDS == 0) ember->renderDepthOffset = HOME_EMBER_FRONT_DEPTH; + else + { + ember->sortingLayer = SORTING_DOOR; + ember->sprite.color._tint[3] = HOME_EMBER_BACK_SHADE; + ember->sprite.scale = vector_scale(ember->sprite.scale, HOME_EMBER_BACK_SHADE); + } + ember->Update(); +} + // 00802980 Runs the room for a frame: its first frame's extras, Genesis's timer, the exorcism and time effects, the // poop clouds, the removed and living grid entities and the grid paths, the Broken Shovel's and Ambush's challenges, // the entity list and effect layers, the floor sprite and the Beast's arena, the Dataminer's music, temporary @@ -951,8 +1024,7 @@ void Room::Update() game.darknessTimeout = HEART_DARKNESS_TIMEOUT; } RoomConfig_Room* config = descriptor->data; - if (config && config->type == ROOM_DUNGEON && config->stageId == STAGE_ID_HOME) - reconstruction_missing("Room::Update 00802980: the Home crawlspace's cold and steam"); + if (config && config->type == ROOM_DUNGEON && config->stageId == STAGE_ID_HOME) home_crawlspace_update(*this); for (Shockwave& wave : roomShockwaves) { if (wave.frame >= wave.duration) continue; @@ -1080,7 +1152,7 @@ static void ambient_effect_add(AmbientMix& mix, Entity& entity) RIFT_VOLUME * effect.sprite.scale.x; return; case EFFECT_DOGMA_BLACKHOLE: - if (effect.subtype == 0 && effect.state == BLACKHOLE_STATE_OPEN && animation && animation->isLooping) + if (effect.subtype == 0 && effect.state == BLACKHOLE_OPEN && animation && animation->isLooping) volumes[AMBIENT_BLACKHOLE] += ambient_falloff(effect.pos, mix.center, BLACKHOLE_REACH, FALLOFF_SQUARED); return; case EFFECT_ANIMA_CHAIN: diff --git a/src/sfx_manager.cpp b/src/sfx_manager.cpp index 86239a1..795b530 100644 --- a/src/sfx_manager.cpp +++ b/src/sfx_manager.cpp @@ -13,7 +13,6 @@ constexpr uint32_t SAMPLE_RNG_SHIFT_INDEX = 42; constexpr float AMBIENT_VOLUME_MIN = 0.01f; constexpr int AMBIENT_FRAME_DELAY = 2; constexpr std::string_view STREAM_EXTENSION = ".ogg"; -constexpr std::string_view DOCUMENT_TAG = "#document"; // 00a2add0 Takes a freshly loaded source, setting it back to no loop, full volume, centered and at its own pitch. void SoundInstance::assign(std::shared_ptr loaded) diff --git a/src/sfx_manager.h b/src/sfx_manager.h index 953efba..2b8cee6 100644 --- a/src/sfx_manager.h +++ b/src/sfx_manager.h @@ -42,6 +42,7 @@ enum SoundId : int SOUND_CHEST_OPEN = 22, SOUND_COIN_SLOT = 24, SOUND_CUTE_GRUNT = 25, + SOUND_DEATH_BURST_BONE = 27, SOUND_DEATH_BURST_LARGE = 28, SOUND_BOSS1_EXPLOSIONS = 28, SOUND_DEATH_REVERSE = 29, @@ -166,6 +167,7 @@ enum SoundId : int SOUND_BUTTON_PRESS = 469, SOUND_PUNCH = 478, SOUND_LINGER_BEAN = 860, + SOUND_IBS_GURGLE = 864, SOUND_GOODEATH = 207, SOUND_SATAN_HAND_LASER = 211, SOUND_HEARTIN = 212, @@ -230,6 +232,7 @@ enum SoundId : int SOUND_HEARTBEAT_FASTER = 322, SOUND_HEARTBEAT_FASTEST = 323, SOUND_WET_FEET = 398, + SOUND_FETUS_FEET = 201, SOUND_DANGLE_WHISTLE = 413, SOUND_LITTLE_HORN_COUGH = 414, SOUND_LITTLE_HORN_GRUNT_1 = 415, @@ -239,7 +242,19 @@ enum SoundId : int SOUND_BONE_DROP = 467, SOUND_BONE_BREAK = 500, SOUND_BISHOP_HIT = 501, + SOUND_CLAP = 485, + SOUND_BOSS2INTRO_WATER_EXPLOSION = 486, + SOUND_CHAIN_LOOP = 503, + SOUND_BOSS2_WATERTHRASHING = 488, + SOUND_CLOG_POOPSMOKE = 1018, + SOUND_MOTHERSHADOW_END = 717, + SOUND_MOTHERSHADOW_APPEAR = 714, + SOUND_MOTHERSHADOW_CHARGE_UP = 715, + SOUND_MOTHERSHADOW_DASH = 716, + SOUND_GROUND_TREMOR = 578, + SOUND_CHAIN_BREAK = 504, SOUND_BONE_BOUNCE = 499, + SOUND_SPEWER = 459, SOUND_TOOTH_AND_NAIL = 506, SOUND_TOOTH_AND_NAIL_TICK = 507, SOUND_THREAD_SNAP = 509, @@ -274,7 +289,13 @@ enum SoundId : int SOUND_POOPITEM_STORE = 606, SOUND_POOPITEM_HOLD = 607, SOUND_VAMP_DOUBLE = 614, + SOUND_GFUEL_GUNSHOT = 824, + SOUND_GFUEL_GUNSHOT_SMALL = 825, + SOUND_GFUEL_GUNSHOT_LARGE = 826, + SOUND_GFUEL_GUNSHOT_SPREAD = 827, SOUND_GFUEL_AIR_HORN = 828, + SOUND_GFUEL_GUNSHOT_MINI = 830, + SOUND_GFUEL_ROCKETLAUNCHER = 832, SOUND_CRACKED_ORB = 850, SOUND_DARK_BUM_PAYOUT = 853, SOUND_DRSREMOTE_WARNING = 855, @@ -579,7 +600,46 @@ enum SoundId : int SOUND_DOGMA_BLACKHOLE_OPEN = 545, SOUND_DOGMA_BLACKHOLE_CLOSE = 546, SOUND_DOGMA_LIGHT_RAY_CHARGE = 563, - SOUND_DOGMA_LIGHT_RAY_FIRE = 564 + SOUND_DOGMA_LIGHT_RAY_FIRE = 564, + SOUND_STATIC = 81, + SOUND_DOGMA_APPEAR_SCREAM = 541, + SOUND_DOGMA_DEATH = 542, + SOUND_DOGMA_BLACKHOLE_CHARGE = 543, + SOUND_DOGMA_BLACKHOLE_SHOOT = 544, + SOUND_DOGMA_BRIMSTONE_CHARGE = 547, + SOUND_DOGMA_BRIMSTONE_SHOOT = 548, + SOUND_DOGMA_GODHEAD = 549, + SOUND_DOGMA_JACOBS = 550, + SOUND_DOGMA_SCREAM = 552, + SOUND_DOGMA_RING_START = 554, + SOUND_DOGMA_FEATHER_SPRAY = 556, + SOUND_DOGMA_ANGEL_TRANSFORM = 559, + SOUND_DOGMA_ANGEL_TRANSFORM_END = 560, + SOUND_DOGMA_LIGHT_APPEAR = 561, + SOUND_DOGMA_LIGHT_BALL_THROW = 562, + SOUND_DOGMA_SPIN_ATTACK = 565, + SOUND_DOGMA_WING_FLAP = 566, + SOUND_DOGMA_TV_BREAK = 567, + SOUND_BEAST_DEATH = 697, + SOUND_BEAST_LASER = 698, + SOUND_BEAST_GHOST_DASH = 701, + SOUND_BEAST_GHOST_RISE = 702, + SOUND_BEAST_LAVA_RISE = 704, + SOUND_BEAST_SUCTION_LOOP = 705, + SOUND_BEAST_FIRE_BARF = 706, + SOUND_BEAST_GHOST_ROAR = 707, + SOUND_BEAST_SUCTION_END = 709, + SOUND_BEAST_SUCTION_START = 710, + SOUND_BEAST_SPIT = 711, + SOUND_BEAST_SURFACE_GROWL = 712, + SOUND_BEAST_SWITCH_SIDES = 713, + SOUND_BEAST_DEATH_2 = 731, + SOUND_BEAST_ANGELIC_BLAST = 732, + SOUND_BEAST_GROWL = 815, + SOUND_BEAST_GRUMBLE = 816, + SOUND_UNBORN_GROWL = 1089, + SOUND_UNBORN_WARP = 1090, + SOUND_BALL_AND_CHAIN_HIT = 581 }; // Construction, copies and destruction (00a2a990, 00a2aa60, 00a2ab40, 00a2ac90) are the defaults. diff --git a/src/string_table.h b/src/string_table.h index 5f8b41e..c5d62b2 100644 --- a/src/string_table.h +++ b/src/string_table.h @@ -6,6 +6,9 @@ #include #include +// The mark that opens a string table key in place of literal text. +constexpr char STRING_KEY_PREFIX = '#'; + // The languages the game checks by id (its language column order). enum Language : int { diff --git a/src/tainted_characters.cpp b/src/tainted_characters.cpp index 2e6f28c..4b90339 100644 --- a/src/tainted_characters.cpp +++ b/src/tainted_characters.cpp @@ -206,7 +206,7 @@ void flip_use(ItemUse& use) other->isControlsEnabled = false; g_game->playerManager.replace_player(&player, other); poof_spawn(player.pos)->Update(); - player.SyncConsumables(other, UINT32_MAX); + player.SyncConsumables(other, CONSUMABLE_ALL); other->PlayExtraAnimation("Sad"); other->isControlsEnabled = true; other->controlsCooldown = 1; diff --git a/src/weapon.cpp b/src/weapon.cpp index 05ba27f..867d827 100644 --- a/src/weapon.cpp +++ b/src/weapon.cpp @@ -1,16 +1,6 @@ #include "weapon.h" -#include "weapon_lasers.h" -#include "weapon_bombs.h" -#include "weapon_knives.h" -#include "weapon_fetus.h" -#include "weapon_ludovico.h" -#include "weapon_monstros_lung.h" -#include "weapon_rockets.h" -#include "weapon_spirit_sword.h" -#include "weapon_deathmatch.h" -#include "weapon_umbilical_whip.h" -#include "weapon_urn_of_souls.h" #include "boss_ai.h" +#include "entity_effect.h" #include "entity_familiar.h" #include "entity_laser.h" #include "entity_player.h" @@ -20,8 +10,23 @@ #include "log.h" #include "manager.h" #include "menu_manager.h" +#include "netplay_manager.h" #include "npc_ai.h" #include "npc_basement.h" +#include "room_grid.h" +#include "room_render.h" +#include "sfx_manager.h" +#include "weapon_bombs.h" +#include "weapon_deathmatch.h" +#include "weapon_fetus.h" +#include "weapon_knives.h" +#include "weapon_lasers.h" +#include "weapon_ludovico.h" +#include "weapon_monstros_lung.h" +#include "weapon_rockets.h" +#include "weapon_spirit_sword.h" +#include "weapon_umbilical_whip.h" +#include "weapon_urn_of_souls.h" #include #include @@ -33,7 +38,6 @@ constexpr float EPIPHORA_SPREAD = 16; constexpr float EPIPHORA_SPREAD_DIVISOR = 3; constexpr int EPIPHORA_FRAMES_PER_STEP = 90; constexpr float FIRE_BLINK_SCALE = -0.45f; -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; @@ -56,6 +60,73 @@ constexpr float TEAR_SPEED_SPREAD = 0.2f; constexpr float TEAR_SPEED_MIN = 0.8f; constexpr float CHARGE_BAR_FULL = 1; constexpr float WEAPON_DAMAGE_DEFAULT = 3.5f; +constexpr float LIL_DELIRIUM_COLORIZE[] = {2.4f, 2.4f, 2.4f, 1}; +constexpr float SEEDED_SPREAD_WIDE = 24; +constexpr int MOMS_WIG_ODDS = 20; +constexpr uint32_t MOMS_WIG_SPIDERS = 4; +constexpr uint32_t MOMS_WIG_HIVE_SPIDERS = 9; +constexpr float EXTRA_TEAR_SPEED = 10; +constexpr float EXTRA_TEAR_SPEED_MIN = 0.9f; +constexpr float EXTRA_TEAR_SPEED_SPREAD = 0.2f; +constexpr float EXTRA_TEAR_SCALE_MIN = 0.01f; +constexpr float EXTRA_TEAR_FALL_SPREAD = 0.2f; +constexpr float IMMACULATE_LIFT = 7; +constexpr float IMMACULATE_FALL_SCALE = 0.01f; +constexpr ColorMod IMMACULATE_TINT = {{1.5f, 2, 2, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float CRAWLSPACE_TEAR_OFFSET_Y = -18; +constexpr float CRAWLSPACE_TEAR_HEIGHT_MAX = -5.1f; +constexpr uint32_t TORN_CARD_PERIOD = 15; +constexpr uint32_t TORN_CARD_PERIOD_DOUBLE = 10; +constexpr uint32_t TORN_CARD_PERIOD_TRIPLE = 5; +constexpr float TORN_CARD_DAMAGE = 40; +constexpr float TORN_CARD_SCALE = 0.3f; +constexpr float TORN_CARD_SPEED = 16; +constexpr float TORN_CARD_DRAG = 0.9f; +constexpr float TORN_CARD_FLIGHT = 50; +constexpr float TORN_CARD_SLOPE = -9.4912214f; +constexpr float TORN_CARD_FLOOR = -5; +constexpr float TORN_CARD_ARC = 9; +constexpr float TORN_CARD_FALL_ACCEL = 0.8f; +constexpr ColorMod TORN_CARD_COLOR = {{0.5f, 0.9f, 0.4f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int CANDLE_ODDS = 8; +constexpr int GHOST_PEPPER_ODDS = 12; +constexpr int CANDLE_ODDS_MIN = 2; +constexpr float CANDLE_VERSUS_DAMAGE = 4; +constexpr int GREED_PERIOD = 20; +constexpr float GREED_DAMAGE_SCALE = 1.5f; +constexpr float GREED_DAMAGE_BONUS = 10; +constexpr int PENCIL_PERIOD = 15; +constexpr int PENCIL_TEARS = 12; +constexpr float PENCIL_HALF_TURN = 3.14f; +constexpr float PENCIL_SCATTER = 3.5f; +constexpr float PENCIL_SCALE_STEP = 0.4f; +constexpr float PENCIL_SCALE_JITTER = 0.05f; +constexpr float PENCIL_LOB_ACCEL = 0.5f; +constexpr float PENCIL_LOB_LIFT = 5; +constexpr float PENCIL_LOB_RANGE = 15; +constexpr float SEEDED_SPREAD_NARROW = 8; +constexpr float GFUEL_FLASH_REACH = 4; +constexpr int GFUEL_FLASH_FRAMES = 2; +constexpr float GFUEL_FLASH_LIFT = -20; +constexpr float GFUEL_CASING_SPREAD = 20; +constexpr float GFUEL_CASING_SPEED_MIN = 0.1f; +constexpr float GFUEL_CASING_SPEED_RANGE = 0.2f; +constexpr float GFUEL_CASING_PLAYBACK_MIN = 0.8f; +constexpr float GFUEL_CASING_PLAYBACK_RANGE = 0.6f; +constexpr float GFUEL_CASING_LIFT = -8; +constexpr float GFUEL_CASING_LIFT_RANGE = 16; +constexpr float GFUEL_RECOIL = 0.02f; +constexpr float GFUEL_RECOIL_MIN = 0.2f; +constexpr float GFUEL_SMALL_SCALE = 0.75f; +constexpr float GFUEL_LARGE_SCALE = 1.75f; +constexpr int GFUEL_SHAKE_SMALL = 3; +constexpr int GFUEL_SHAKE_PISTOL = 6; +constexpr int GFUEL_SHAKE_HEAVY = 10; +constexpr int GFUEL_SHAKE_SPREAD = 16; +constexpr const char* GFUEL_FLASH_ANM2 = "gfx/promo/gfuel/effects/muzzle_flash.anm2"; +constexpr const char* GFUEL_CASING_ANM2 = "gfx/promo/gfuel/effects/casing.anm2"; +constexpr const char* GFUEL_CASING_ANIMATION = "Gib1"; +constexpr ColorMod BABY_BENDER_TEAR_COLOR = {{0.4f, 0.15f, 0.38f, 1}, {0, 0, 0, 0}, {0.21568629f, 0.019607844f, 0.37254903f}}; constexpr int FIRE_BLINK_BASE = 7; constexpr int FIRE_BLINK_MIN = 11; constexpr int MAX_SHOTS_PER_FRAME = 8; @@ -75,7 +146,6 @@ constexpr int MOMS_EYE_LASER_CHANCE = 20; constexpr float MOMS_EYE_LASER_LUCK = 1.5f; constexpr int LOKIS_HORNS_LASER_CHANCE = 80; constexpr float LOKIS_HORNS_LASER_LUCK = 5; -constexpr int TRINKET_TORN_CARD = 157; constexpr int BABY_SPIN = 8; constexpr int MARKED_TARGET = 30; constexpr std::string_view C_SECTION_SUB_ANIM = "SubAnim"; @@ -83,7 +153,6 @@ constexpr float C_SECTION_FRAME_PLAY = -1; constexpr int MARKED_OCCULT_TARGET = 153; // The items that react to each tear fired: Mom's Wig, Immaculate Heart, Bird's Eye, Ghost Pepper, Eye of Greed and Lead // Pencil. -constexpr int TEAR_TRIGGER_ITEMS[] = {217, 573, 616, 495, 450, COLLECTIBLE_LEAD_PENCIL}; // The null costumes that count as Brimstone's: Azazel's head, Brimstone's second costume, Tainted Azazel and Azazel's // Rage. @@ -421,29 +490,264 @@ Entity_Tear* Weapon::fire_tear(const PosVel& shot, uint32_t fireFlags, float dam return tear; } -// 009f7930 What firing does beyond the shot, once per tear: Isaac's Tears charges, glitched items trigger, and the -// items that fire extras or spawn things with tears (not written yet). Counts the shots fired. -void Weapon::TriggerTearEffects(const Vector&, int count) +// The shot speed of the weapon's player (009f3c40), or one without a player. +static float weapon_shot_speed(Weapon& weapon) { - Entity_Player* player = owner_player(); + Entity_Player* player = weapon.owner_player(); + return player ? player->shotSpeed : 1; +} +// Mom's Wig: one tear in 20 (less with luck, at least one in one) spawns a blue spider by the owner, while the player +// has at most four (nine with Hive Mind). +static void moms_wig_spider(Weapon& weapon, Entity_Player& player) +{ + float luck = player.luck; + luck += luck; + int chance = std::max(MOMS_WIG_ODDS - (int)luck, 1); + if (Random() % (uint32_t)chance != 0) return; + + bool isHive = player.HasCollectible(COLLECTIBLE_HIVE_MIND) || + player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_HIVE_MIND); + uint32_t spiders = (uint32_t)player.numBlueSpiders; + if (spiders > MOMS_WIG_SPIDERS && !(isHive && spiders <= MOMS_WIG_HIVE_SPIDERS)) return; + + Vector spot = room_free_pickup_position_find({.position = weapon.get_owner_position()}); + player.numBlueSpiders++; + spawn_blue_spider(spot, &player, Vector{}); +} + +// Immaculate Heart: one tear in four sends a spectral tear the way the head faces orbiting the player, glowing white. +static void immaculate_heart_fire(Weapon& weapon, Entity_Player& player, int count) +{ + if ((Random() & 3) != 0) return; + + Vector direction = vector_scale(vector_from_direction(player.headDirection), EXTRA_TEAR_SPEED); + Vector inherited = weapon.get_tear_movement_inheritance(direction); + float speed = weapon_shot_speed(weapon); + Vector velocity = vector_make(speed * (direction.x + inherited.x), speed * (direction.y + inherited.y)); + if (count > 1) velocity = vector_scale(velocity, random_unit() * EXTRA_TEAR_SPEED_SPREAD + EXTRA_TEAR_SPEED_MIN); + + uint32_t fireFlags = TEAR_FIRE_NO_EVIL_EYE | TEAR_FIRE_EXTRA_SHOT | TEAR_FIRE_ORBITAL; + Entity_Tear* tear = weapon.fire_tear({weapon.get_owner_position(), velocity}, fireFlags, 1, 0); + if (!tear->tearFlags[TEAR_ORBIT]) + { + tear->fallingSpeed -= IMMACULATE_LIFT; + tear->fallingAccel *= IMMACULATE_FALL_SCALE; + } + TearFlags flags = tear->tearFlags; + flags.set(TEAR_ORBIT_ADVANCED); + flags.set(TEAR_SPECTRAL); + flags.reset(TEAR_BOOMERANG); + flags.reset(TEAR_OCCULT); + tear->SetTearFlags(flags); + ColorMod color = tear->sprite.color; + color_multiply(color, IMMACULATE_TINT); + tear->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// An item's tear fired along with the player's: from the owner at the player's tear offset plus its velocity, at a +// height (kept low in a crawlspace). +static Entity_Tear* extra_tear_spawn(Weapon& weapon, Entity_Player& player, const Vector& velocity, int variant, + float height) +{ + uint32_t seed = Random(); + Vector position = vector_add(vector_add(weapon.get_owner_position(), player.tearsOffset), velocity); + Entity_Tear* tear = g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = &player, + .type = ENTITY_TEAR, + .variant = variant, + .seed = seed}) + ->ToTear(); + tear->height = height; + tear->posOffset.y = tear->get_height_offset_y(height); + if (g_game->room->roomType == ROOM_DUNGEON) + { + tear->posOffset.y = CRAWLSPACE_TEAR_OFFSET_Y; + if (tear->height > CRAWLSPACE_TEAR_HEIGHT_MAX) tear->height = CRAWLSPACE_TEAR_HEIGHT_MAX; + } + return tear; +} + +// What every extra tear of an item shares once its flags are set: the player as its parent, a tear index of its +// own and no streak, then its first update and a step back so it leaves from where it was spawned. +static void extra_tear_finish(Entity_Tear& tear, Entity_Player& player, float fallingSpeed, float fallingAccel) +{ + tear.parent = &player; + tear.tearIdx = (int)Random(); + tear.isCanTriggerStreakEnd = false; + tear.fallingSpeed = fallingSpeed; + tear.fallingAccel = fallingAccel; + tear.Update(); + tear.pos = vector_sub(tear.pos, tear.velocity); +} + +// Torn Card: every 15th tear (10th, 5th with two or three) is a big poison explosive tear that comes back, lobbed the +// way the head faces in pale green. +static void torn_card_fire(Weapon& weapon, Entity_Player& player) +{ + int multiplier = player.GetTrinketMultiplier(TRINKET_TORN_CARD); + if (multiplier <= 0) return; + uint32_t period = multiplier == 2 ? TORN_CARD_PERIOD_DOUBLE : multiplier == 3 ? TORN_CARD_PERIOD_TRIPLE : TORN_CARD_PERIOD; + if ((uint32_t)weapon.numFired % period != 0) return; + + TearParams params = player.GetTearHitParams(WEAPON_TEARS, 1, -player.tearDisplacement, nullptr); + if (!player.HasCollectible(COLLECTIBLE_IPECAC)) + { + params.tearDamage += TORN_CARD_DAMAGE; + params.tearScale += TORN_CARD_SCALE; + } + for (int bit : {TEAR_EXPLOSIVE, TEAR_POISON, TEAR_BOOMERANG}) params.tearFlags.set((size_t)bit); + Vector velocity = vector_scale(vector_from_direction(player.headDirection), TORN_CARD_SPEED); + velocity = vector_add(velocity, weapon.get_tear_movement_inheritance(velocity)); + + Entity_Tear* tear = extra_tear_spawn(weapon, player, velocity, params.tearVariant, params.tearHeight); + tear->SetCollisionDamage(params.tearDamage); + tear->SetTearFlags(params.tearFlags); + tear->baseScale = std::max(params.tearScale, EXTRA_TEAR_SCALE_MIN); + tear->fScale = tear->baseScale; + tear->ResetSpriteScale(); + tear->SetColor(TORN_CARD_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + float slope = std::max(((float)std::pow(TORN_CARD_DRAG, TORN_CARD_FLIGHT) - 1) * TORN_CARD_SLOPE, EXTRA_TEAR_SCALE_MIN); + float fallingSpeed = ((TORN_CARD_FLOOR - tear->height) - (TORN_CARD_FLIGHT - slope) * TORN_CARD_ARC) / slope; + extra_tear_finish(*tear, player, fallingSpeed, TORN_CARD_FALL_ACCEL); +} + +// Bird's Eye and Ghost Pepper: one tear in 8 (12 for Ghost Pepper alone, less with luck) throws a red or blue candle +// flame along the aim, either with both. In versus a blue flame hits as hard as four tears. +static void candle_fire(Entity_Player& player, const Vector& aim) +{ + bool isBirdsEye = player.HasCollectible(COLLECTIBLE_BIRDS_EYE); + bool isGhostPepper = player.HasCollectible(COLLECTIBLE_GHOST_PEPPER); + if (!isBirdsEye && !isGhostPepper) return; + + bool isBoth = isBirdsEye && isGhostPepper; + int odds = isBirdsEye ? CANDLE_ODDS : GHOST_PEPPER_ODDS; + int least = isBoth ? 1 : CANDLE_ODDS_MIN; + int chance = odds - (int)player.luck; + if (chance < least) chance = least; + if (chance != 0 && Random() % (uint32_t)chance != 0) return; + + if (isBirdsEye && !(isGhostPepper && (Random() & 1))) + { + player.ShootRedCandle(aim); + return; + } + Entity* flame = player.ShootBlueCandle(aim); + if (g_game->deathmatchManager.is_active()) + { + int displacement = (int)(Random() & 1) * 2 - 1; + TearParams params = player.GetTearHitParams(WEAPON_TEARS, 1, displacement, nullptr); + flame->SetCollisionDamage(params.tearDamage * CANDLE_VERSUS_DAMAGE * player.meleeDamage / player.damage); + } +} + +// Eye of Greed: every 20th tear is a coin tear along the aim that freezes in gold, and with a coin to spend a +// stronger one dropping coins, with a cash register's ring. +static void greed_coin_fire(Weapon& weapon, Entity_Player& player, const Vector& aim, int count) +{ + if (weapon.numFired % GREED_PERIOD != 0) return; + + TearParams params = player.GetTearHitParams(WEAPON_TEARS, 1, -player.tearDisplacement, nullptr); + Vector direction = vector_scale(aim, EXTRA_TEAR_SPEED); + Vector inherited = weapon.get_tear_movement_inheritance(direction); + float speed = weapon_shot_speed(weapon); + Vector velocity = vector_make(speed * (direction.x + inherited.x), speed * (direction.y + inherited.y)); + if (count > 1) velocity = vector_scale(velocity, random_unit() * EXTRA_TEAR_SPEED_SPREAD + EXTRA_TEAR_SPEED_MIN); + + Entity_Tear* tear = extra_tear_spawn(weapon, player, velocity, TEAR_COIN, params.tearHeight); + TearFlags flags = params.tearFlags; + flags.set(TEAR_MIDAS); + if (player.numCoins > 0) + { + player.AddCoins(-1); + tear->SetCollisionDamage(params.tearDamage * GREED_DAMAGE_SCALE + GREED_DAMAGE_BONUS); + flags.set(TEAR_COIN_DROP); + } + else + tear->SetCollisionDamage(params.tearDamage); + tear->SetTearFlags(flags); + float fallingSpeed = random_unit() * EXTRA_TEAR_FALL_SPREAD - player.tearFallingSpeed - IMMACULATE_LIFT; + extra_tear_finish(*tear, player, fallingSpeed, player.tearFallingAcceleration * IMMACULATE_FALL_SCALE); + effect_sound_play(SOUND_CASH_REGISTER); +} + +// Lead Pencil: every 15th tear, a burst of twelve tears the way the head faces, scattered and lobbed. +static void lead_pencil_fire(Weapon& weapon, Entity_Player& player) +{ + if (weapon.numFired % PENCIL_PERIOD != 0) return; + + for (int i = 0; i < PENCIL_TEARS; i++) + { + TearParams params = player.GetTearHitParams(WEAPON_TEARS, 1, -player.tearDisplacement, nullptr); + Vector direction = vector_scale(vector_from_direction(player.headDirection), EXTRA_TEAR_SPEED); + Vector inherited = weapon.get_tear_movement_inheritance(direction); + float speed = weapon_shot_speed(weapon); + Vector velocity = vector_make((direction.x + inherited.x) * speed, (direction.y + inherited.y) * speed); + float angle = random_unit() * PENCIL_HALF_TURN; + angle += angle; + float scatter = random_unit(); + velocity.x = std::cos(angle) * scatter * PENCIL_SCATTER + velocity.x; + velocity.y = std::sin(angle) * scatter * PENCIL_SCATTER + velocity.y; + + Entity_Tear* tear = extra_tear_spawn(weapon, player, velocity, params.tearVariant, params.tearHeight); + tear->SetCollisionDamage(params.tearDamage); + tear->SetTearFlags(params.tearFlags); + float lane = (float)(Random() & 1); + float jitter = random_unit() * PENCIL_SCALE_JITTER; + tear->baseScale = + std::max((lane * PENCIL_SCALE_STEP + EXTRA_TEAR_SPEED_MIN + jitter) * params.tearScale, EXTRA_TEAR_SCALE_MIN); + tear->fScale = tear->baseScale; + tear->ResetSpriteScale(); + tear->SetColor(params.tearColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + float fallingSpeed = random_unit() * EXTRA_TEAR_FALL_SPREAD - player.tearFallingSpeed; + extra_tear_finish(*tear, player, fallingSpeed, player.tearFallingAcceleration); + if (g_game->deathmatchManager.is_active()) + { + TearFlags flags = tear->tearFlags; + flags.set(TEAR_THROUGH_COOLDOWN); + tear->SetTearFlags(flags); + } + if (player.HasCollectible(COLLECTIBLE_IPECAC)) continue; + tear->fallingAccel = player.tearFallingAcceleration + PENCIL_LOB_ACCEL; + tear->fallingSpeed = (PENCIL_LOB_LIFT - random_unit() * PENCIL_LOB_RANGE) - player.tearFallingSpeed; + } +} + +// 009f7930 What firing does beyond the shot: Isaac's Tears charges by the tears fired, and for each tear glitched +// items trigger, Mom's Wig, Immaculate Heart, Torn Card, Bird's Eye and Ghost Pepper, Eye of Greed and Lead Pencil +// add their own, counting the shots fired. Without a shot direction it aims the weapon's or the player's way. +void Weapon::TriggerTearEffects(const Vector& shootDirection, int count) +{ + if (count < 1) return; + + Entity_Player* player = owner_player(); + if (player && player->itemState == 0) + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + if (player->activeItems[slot].item == COLLECTIBLE_ISAACS_TEARS) + player->AddActiveCharge(count, slot, false, false, true); + + Vector aim = shootDirection; + if (vector_is_zero(aim)) aim = vector_is_zero(direction) && player ? player->aimDirection : direction; for (int i = 0; i < count; i++) { - if (player) + if (!player) { - if (player->itemState == 0) - for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) - if (player->activeItems[slot].item == COLLECTIBLE_ISAACS_TEARS) - player->AddActiveCharge(count, slot, false, false, true); - if (!player->proceduralItems.empty()) - reconstruction_missing("Weapon::TriggerTearEffects 009f7930 (glitched items)"); - for (int item : TEAR_TRIGGER_ITEMS) - if (player->HasCollectible(item)) - reconstruction_missing("Weapon::TriggerTearEffects 009f7930 (items fired with tears)"); - if (player->GetTrinketMultiplier(TRINKET_TORN_CARD) > 0) - reconstruction_missing("Weapon::TriggerTearEffects 009f7930 (Torn Card)"); + numFired++; + continue; } + + if (!player->proceduralItems.empty()) + reconstruction_missing("Weapon::TriggerTearEffects 009f7930 (glitched items, trigger_set_dispatch 009e0680)"); + if (player->HasCollectible(COLLECTIBLE_MOMS_WIG)) moms_wig_spider(*this, *player); + if (player->HasCollectible(COLLECTIBLE_IMMACULATE_HEART)) immaculate_heart_fire(*this, *player, count); + torn_card_fire(*this, *player); + if (player->variant == PLAYER_VARIANT_COOP_BABY && player->babySkin == BABY_DEAD) + reconstruction_missing("Weapon::TriggerTearEffects 009f7930 (a co-op baby's blue flies)"); + candle_fire(*player, aim); numFired++; + if (player->HasCollectible(COLLECTIBLE_EYE_OF_GREED)) greed_coin_fire(*this, *player, aim, count); + if (player->HasCollectible(COLLECTIBLE_LEAD_PENCIL)) lead_pencil_fire(*this, *player); } } @@ -472,14 +776,32 @@ TearFlags Weapon::get_owner_tear_flags() return flags; } -// 009f3db0 The color the weapon's tears take: its player's. A familiar's are recolored, which is not reconstructed -// yet. Online, another player's tears fade with the opacity option, which this offline build has no use for. +// The opacity a remote online player's shots fade to with the opacity option, or one for a local player's and in +// versus. +float shot_alpha_get(Entity_Player* player) +{ + NetplayManager& netplay = g_manager->netplayManager; + bool isRemote = player && netplay.is_online() && !netplay.IsIdxLocalPlayer(player->controllerIndex); + return isRemote && !g_game->deathmatchManager.is_active() ? tear_remote_opacity_get() : 1; +} + +// 009f3db0 The color the weapon's tears take: its player's, purple for a familiar under Baby-Bender and glowing for +// Lil Delirium. A remote online player's fade with the opacity option. ColorMod Weapon::get_tear_color() { Entity_Player* player = owner_player(); if (!player) return COLOR_DEFAULT; - if (owner->IsFamiliar()) reconstruction_missing("Weapon::get_tear_color 009f3db0 (a familiar's tears)"); - return player->tearColor; + + ColorMod color = player->tearColor; + if (owner->IsFamiliar()) + { + if (player->HasTrinket(TRINKET_BABY_BENDER)) + color = BABY_BENDER_TEAR_COLOR; + else if (static_cast(owner)->isLilDelirium) + std::copy(std::begin(LIL_DELIRIUM_COLORIZE), std::end(LIL_DELIRIUM_COLORIZE), color._colorize); + } + color._tint[3] *= shot_alpha_get(player); + return color; } // 0075a2b0 Whether a costume belongs to an item. Brimstone's is also Azazel's head and Rage, Brimstone's second @@ -900,13 +1222,139 @@ static void tear_charge_update(Weapon_Tears& weapon, const TearCharge& kind, con weapon.chargeAtRelease = next; } +// The volley a Technology 2 laser eye fires instead of tears: its multi-shot params, aim, start, damage, spread and +// shot speed. +struct LaserEyeVolley +{ + const Weapon_MultiShotParams& params; + Vector direction{}; + Vector position{}; + float damageMultiplier = 1; + float spreadAngle = 0; + float speed = 1; +}; + +// Part of 00a0a720: one eye with Technology 2 fires the volley as Technology 2 lasers lasting one hit, backward, +// sideways, at random and along each shot of the multi-shot, then lets them all leave the eye together. +void Weapon_Tears::laser_eye_fire(const LaserEyeVolley& volley) +{ + Vector aim = vector_normalized(volley.direction); + std::vector lasers; + auto fire = [&](Vector direction) { + lasers.push_back(fire_laser({.direction = vector_spread(direction, volley.spreadAngle), + .position = volley.position, + .damageScale = volley.damageMultiplier, + .offsetId = LASER_OFFSET_TECH2, + .isOneHit = true})); + }; + if (volley.params.isShootingBackwards) fire(vector_make(-aim.x, -aim.y)); + if (volley.params.isShootingSideways) + { + fire(vector_make(-aim.y, aim.x)); + fire(vector_make(aim.y, -aim.x)); + } + for (int i = 0; i < volley.params.numRandomDirTears; i++) fire(vector_rotated(aim, random_unit() * FULL_TURN_DEGREES)); + for (int i = 0; i < volley.params.numTears; i++) + { + PosVel shot = Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_LASER, aim, volley.speed, volley.params); + fire(vector_normalized(shot.velocity)); + } + for (Entity_Laser* laser : lasers) + { + laser->isDisableFollowParent = false; + laser->Update(); + } +} + +// Part of 00a0a720: G FUEL!'s gun look for each volley: a muzzle flash in the tear color 4 out along the shot, a +// casing flung back a bit astray, and a bang by the gun (a spread, a minigun that kicks the player back, a rocket +// launcher, or a pistol by the tear size) with a screen shake to match. +void Weapon_Tears::gfuel_shot_effects(Entity_Player& shooter, const Vector& position, const Vector& base) +{ + float length = vector_length(base); + Vector ahead = length > 0 ? vector_scale(base, GFUEL_FLASH_REACH / length) : base; + uint32_t seed = Random(); + Entity_Effect& flash = *static_cast(g_game->Spawn({.position = vector_add(position, ahead), + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF01, + .seed = seed})); + flash.SetTimeout(GFUEL_FLASH_FRAMES); + flash.sprite.Load(GFUEL_FLASH_ANM2, GRAPHICS_LOAD); + flash.posOffset = vector_make(0, GFUEL_FLASH_LIFT); + char animation[] = {(char)('0' + (Random() & 3)), 0}; + flash.sprite.Play(animation, PLAY_FORCED); + int displacement = (int)(Random() & 1) * 2 - 1; + TearParams params = shooter.GetTearHitParams(WEAPON_TEARS, 1, displacement, nullptr); + flash.sprite.scale = vector_make(params.tearScale, params.tearScale); + KColor tint = kcolor_apply(params.tearColor, kcolor_rgba(1, 1, 1, 1)); + flash.sprite.color = tint_color_make(tint._red, tint._green, tint._blue, params.tearColor._tint[3]); + LayerState& layer = *flash.sprite.GetLayer(0); + layer.rotation = std::atan2(base.y, base.x) * RADIANS_TO_DEGREES; + layer_additive_set(layer); + flash.Update(); + + uint32_t casingSeed = Random(); + Vector astray = vector_rotated(base, random_unit() * GFUEL_CASING_SPREAD - GFUEL_CASING_SPREAD / 2); + float kick = -(random_unit() * GFUEL_CASING_SPEED_RANGE + GFUEL_CASING_SPEED_MIN); + Entity_Effect& casing = *static_cast(g_game->Spawn({.position = position, + .velocity = vector_scale(astray, kick), + .type = ENTITY_EFFECT, + .variant = EFFECT_WOOD_PARTICLE, + .seed = casingSeed})); + casing.sprite.Load(GFUEL_CASING_ANM2, GRAPHICS_LOAD); + casing.sprite.Play(GFUEL_CASING_ANIMATION, PLAY_FORCED); + casing.sprite.playbackSpeed = random_unit() * GFUEL_CASING_PLAYBACK_RANGE + GFUEL_CASING_PLAYBACK_MIN; + casing.fallingSpeed = GFUEL_CASING_LIFT - random_unit() * GFUEL_CASING_LIFT_RANGE; + casing.Update(); + + int sound = SOUND_GFUEL_GUNSHOT; + int shake = GFUEL_SHAKE_PISTOL; + switch (shooter.get_seeded_variant()) + { + case SEEDED_VARIANT_MUTANT_SPIDER: + case SEEDED_VARIANT_SLOW: + sound = SOUND_GFUEL_GUNSHOT_SPREAD; + shake = GFUEL_SHAKE_SPREAD; + break; + case SEEDED_VARIANT_RAPID: + { + effect_sound_play(SOUND_GFUEL_GUNSHOT_MINI); + game_shake_screen(GFUEL_SHAKE_HEAVY); + Vector recoil = vector_scale(base, -GFUEL_RECOIL); + Vector away = vector_normalized(recoil); + float push = std::max(-(shooter.velocity.x * away.x + shooter.velocity.y * away.y), GFUEL_RECOIL_MIN); + shooter.velocity = vector_make(push * recoil.x + shooter.velocity.x, push * recoil.y + shooter.velocity.y); + return; + } + case SEEDED_VARIANT_SLOW_FAR: + sound = SOUND_GFUEL_ROCKETLAUNCHER; + shake = GFUEL_SHAKE_HEAVY; + break; + default: + if (params.tearScale < GFUEL_SMALL_SCALE) + { + sound = SOUND_GFUEL_GUNSHOT_SMALL; + shake = GFUEL_SHAKE_SMALL; + } + else if (params.tearScale > GFUEL_LARGE_SCALE) + { + sound = SOUND_GFUEL_GUNSHOT_LARGE; + shake = GFUEL_SHAKE_HEAVY; + } + break; + } + effect_sound_play(sound); + game_shake_screen(shake); +} + // 00a0a720 Fires the tears due this frame: one volley per fire delay passed (at most eight), from each eye Eye Drops // gives, alternating eyes, spread by the multi-shot items, with the extra backward, sideways and random shots. Shots // fired late in a frame start further along. Cain's one eye (and Cursed Eye's) shoots from the right, Technology 2 // leaves the right eye to its laser. A familiar (Incubus, Cain's Other Eye, Twisted Pair) fires its player's volley // from itself, with no eyes, spread or blink of a player. Chocolate Milk and Cursed Eye fire one shot on release, // stronger the longer it charged (Chocolate Milk) or as several (Cursed Eye's charges), and Neptunus fires faster and -// wider the fuller its charge. G FUEL! and the laser eye of Cain with Technology 2 are not written yet. The player +// wider the fuller its charge. One eye with Technology 2 fires a volley of Technology 2 lasers instead, and G FUEL! +// spreads its tears and fires them like a gun, with a flash, a casing, a bang and a shake. The player // field getters and the volley wrapper it calls are inlined (009f5830, 009f5850, 009f5870, 009f4230, 009f4fc0). void Weapon_Tears::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) { @@ -918,8 +1366,6 @@ void Weapon_Tears::Fire(const Vector& shootDirection, bool isShooting, bool isIn .isCursedEye = (modifiers & WEAPON_MOD_CURSED_EYE) != 0, .isNeptunus = (modifiers & WEAPON_MOD_NEPTUNUS) != 0}; kind.isChargeShot = !kind.isNeptunus && (kind.isChocolateMilk || kind.isCursedEye); - if (shooter && shooter->get_seeded_variant() != SEEDED_VARIANT_NONE) - reconstruction_missing("Weapon_Tears::Fire 00a0a720 (G FUEL!)"); bool isHolding = tear_shot_held(*this, kind, isShooting, isInterpolated); Vector aim = isShooting ? shootDirection : direction; @@ -1013,11 +1459,10 @@ void Weapon_Tears::Fire(const Vector& shootDirection, bool isShooting, bool isIn eyeSide = 0; shooter->blinkTime = std::max(shooter->blinkTime, NUMBER_ONE_BLINK); } - if (eyeSide != 0 && eyeMode == 1 && shooter->HasCollectible(COLLECTIBLE_TECHNOLOGY_2)) - reconstruction_missing("Weapon_Tears::Fire 00a0a720 (the laser eye with Technology 2)"); } Vector firePos = owner ? owner->pos : Vector{}; + Vector ownerPos = firePos; Vector base = vector_add(vector_scale(shotDirection, SHOT_SPEED_BASE), get_tear_movement_inheritance(shotDirection)); if (player && player->HasCollectible(COLLECTIBLE_IPECAC)) @@ -1039,11 +1484,23 @@ void Weapon_Tears::Fire(const Vector& shootDirection, bool isShooting, bool isIn int pee = shooter ? shooter->peeBurstCooldown : 0; int peeMax = shooter ? shooter->maxPeeBurstCooldown : 0; if (pee > 0 && peeMax > 0 && pee < peeMax - 1) spreadAngle += (float)pee * PEE_SPREAD / (float)peeMax; + int seededVariant = shooter ? shooter->get_seeded_variant() : SEEDED_VARIANT_NONE; + if (seededVariant == SEEDED_VARIANT_MUTANT_SPIDER) + spreadAngle += SEEDED_SPREAD_WIDE; + else if (seededVariant == SEEDED_VARIANT_RAPID) + spreadAngle += SEEDED_SPREAD_NARROW; if (kind.isNeptunus) spreadAngle += std::clamp(charge * NEPTUNUS_SPREAD_MAX / (maxFireDelay * NEPTUNUS_CHARGE), 0.0f, NEPTUNUS_SPREAD_MAX); float speed = player ? player->shotSpeed : 1; + if (shooter && eyeSide != 0 && eyeMode == 1 && shooter->HasCollectible(COLLECTIBLE_TECHNOLOGY_2)) + { + LaserEyeVolley volley = {params, shotDirection, firePos, damageMultiplier, spreadAngle, speed}; + laser_eye_fire(volley); + positionStep -= eyeMaxFireDelay + 1; + continue; + } auto extra_fire = [&](Vector velocity) { fire_tear({firePos, vector_spread(vector_scale(velocity, speed), spreadAngle)}, TEAR_FIRE_EXTRA_SHOT, damageMultiplier, positionStep); @@ -1070,6 +1527,7 @@ void Weapon_Tears::Fire(const Vector& shootDirection, bool isShooting, bool isIn shot.velocity = vector_spread(shot.velocity, spreadAngle); fire_tear(shot, 0, damageMultiplier, positionStep); } + if (seededVariant != SEEDED_VARIANT_NONE) gfuel_shot_effects(*shooter, ownerPos, base); positionStep -= eyeMaxFireDelay + 1; } } diff --git a/src/weapon.h b/src/weapon.h index 57b34ed..9ab97a2 100644 --- a/src/weapon.h +++ b/src/weapon.h @@ -12,6 +12,8 @@ constexpr float SHOTS_PER_SECOND = 30; constexpr float HEAD_CHARGE_FRAMES = 18; // How far R U A Wizard and the spinning co-op baby turn shots per eye side. constexpr float SHOT_ROTATION_DEGREES = 45; +// The share of the shooter's velocity a shot inherits. +constexpr float INHERIT_SCALE = 0.6f; // What a player or familiar shoots (Lua's WeaponType). Slot 16 is the deathmatch's. enum WeaponType : int @@ -62,6 +64,7 @@ enum TearFireFlag : uint32_t TEAR_FIRE_NO_EVIL_EYE = 1 << 0, TEAR_FIRE_NO_TRACTOR_BEAM = 1 << 1, TEAR_FIRE_NO_STREAK_END = 1 << 2, + TEAR_FIRE_ORBITAL = 1 << 6, TEAR_FIRE_EXTRA_SHOT = TEAR_FIRE_NO_TRACTOR_BEAM | TEAR_FIRE_NO_STREAK_END }; @@ -265,6 +268,7 @@ struct Weapon static Entity_Laser* FireBrimstone(const BrimstoneShot& shot); Entity_Laser* fire_brimstone_with_color(const Vector& shootDirection, float damageMultiplier, uint32_t fireFlags); Entity_Laser* fire_laser(const TechLaserShot& shot); + Entity_Laser* familiar_laser_fire(const TechLaserShot& shot); void technology2_extra_lasers(Entity_Player& player, const Vector& aim); Entity_Laser* fire_tech_x_laser(const TechXShot& shot); Entity_Knife* fire_knife(Entity* knifeParent, int knifeVariant, bool isCantOverwrite, float rotationOffset); @@ -282,6 +286,8 @@ using WeaponPtr = std::unique_ptr; // Destruction (009f9900) is the default. // The weapon that fires tears (and Eye Drops' second eye, Chocolate Milk, Cursed Eye and Neptunus charge them). +struct LaserEyeVolley; + struct Weapon_Tears : Weapon { float chargeAtRelease = 0; @@ -296,9 +302,19 @@ struct Weapon_Tears : Weapon bool SupportsTractorBeam() override; bool CanTriggerCursedEyeTeleport() override; bool CanTriggerKidneyStone() override; + + void laser_eye_fire(const LaserEyeVolley& volley); + void gfuel_shot_effects(Entity_Player& shooter, const Vector& position, const Vector& base); }; +// Tech.5 fires one laser in twenty with a single random flag of the first 84. +constexpr int TECH5_FLAG_CHANCE = 5; +constexpr int TECH5_FLAG_ROLL = 100; +constexpr int TECH5_FLAG_COUNT = 84; + WeaponPtr weapon_create(WeaponType type, Entity* owner); +float shot_alpha_get(Entity_Player* player); +Vector familiar_laser_offset_get(int laserOffsetId, const Vector& direction); bool laser_is_hit_frame(Entity_Laser& laser); Vector weapon_steer_aim(Entity_Player* player, Vector aim); void costume_item_anim_set(Entity_Player& player, ItemConfig_Item* item, std::string_view animName, int frame); diff --git a/src/weapon_knives.cpp b/src/weapon_knives.cpp index 3c2cd4d..0b571b2 100644 --- a/src/weapon_knives.cpp +++ b/src/weapon_knives.cpp @@ -27,6 +27,7 @@ constexpr float KNIFE_AIM_RELEASE_BASE = 5; constexpr float KNIFE_FLYING_LIFT = -15; constexpr float KNIFE_FAMILIAR_SCALE = 0.75f; constexpr float KNIFE_FAMILIAR_LIFT = -20; +constexpr float LUDOVICO_KNIFE_SPEED = 5; constexpr float KNIFE_RANDOM_TURN = 360; constexpr int KNIFE_HELD_BLINK = 7; constexpr int KNIFE_THROWN_BLINK = 15; @@ -208,9 +209,83 @@ void Weapon_Knife::knives_throw(const KnifeThrow& knifeThrow) direction = {}; } +// Part of 00a03f90: Ludovico's knife hovers by the owner, made when missing (placed on the owner in a room's first +// frame), with one more chained behind it for each extra shot of the volley. Shooting steers it by the shot speed. +// Every fire delay it sets off the player's tear effects outward from the player. +void Weapon_Knife::ludovico_update(const Vector& shootDirection, bool isShooting, bool isInterpolated) +{ + Entity_Player* player = owner_player(); + Entity_Player* shooter = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + int variant = shooter && shooter->temporaryEffects.HasNullEffect(NULLITEM_BLOODY_BABYLON) ? KNIFE_SUMPTORIUM + : KNIFE_MOMS_KNIFE; + float interval = std::max(maxFireDelay, KNIFE_CHARGE_MINIMUM); + float shotSpeed = player ? player->shotSpeed : 1; + if (!isInterpolated) + { + if (!knives[0]) + { + Entity_Knife* knife = fire_knife(owner, variant, true, 0); + knives[0] = knife; + if (player) init_knife(*knife); + knife->Update(); + } + Entity_Knife* main = static_cast(knives[0].get()); + init_knife(*main); + if (shooter && shooter->GetIntervalTicks(interval, 0)) + { + bool isApart = main->pos.x != owner->pos.x || main->pos.y != owner->pos.y; + TriggerTearEffects(isApart ? vector_normalized(vector_sub(main->pos, owner->pos)) : random_direction(), 1); + } + if (g_game->room->GetFrameCount() == 0) main->pos = get_owner_position(); + ludovico_chain_update(*main, variant); + } + + Entity* knife = knives[0]; + if (!knife || !isShooting) return; + + float speed = shotSpeed * LUDOVICO_KNIFE_SPEED; + Vector push = shootDirection; + if (vector_length_squared(push) > 1) push = vector_normalized(push); + if (knife->friction == 0) return; + knife->velocity.y = knife->speedMultiplier * speed * push.y * 0.5f / knife->friction + knife->velocity.y; + knife->velocity.x = knife->speedMultiplier * speed * push.x * 0.5f / knife->friction + knife->velocity.x; +} + +// The knives chained behind Ludovico's: one for each extra shot of the volley, the missing ones fired behind the main +// knife, the extra ones removed, the chain linked again and the new ones updated. +void Weapon_Knife::ludovico_chain_update(Entity_Knife& main, int variant) +{ + Weapon_MultiShotParams params = GetMultiShotParams(); + size_t wanted = (size_t)std::max(params.numTears - 1, 0); + std::vector chain; + for (Entity* link = main.child; link; link = link->child) chain.push_back(static_cast(link)); + if (chain.size() == wanted) return; + + if (chain.size() < wanted) + for (size_t i = chain.size(); i < wanted; i++) + { + Entity_Knife* knife = fire_knife(&main, variant, false, 0); + init_knife(*knife); + chain.push_back(knife); + } + else + { + for (size_t i = wanted; i < chain.size(); i++) chain[i]->Remove(); + chain.resize(wanted); + } + + Entity* previous = &main; + for (Entity_Knife* knife : chain) + { + previous->child = knife; + previous = knife; + if (g_game->frameCount == knife->spawnFrame) knife->Update(); + } +} + // 00a03f90 Holds, charges and throws Mom's Knife: the knives sit around the owner turned toward the aim, charge while // shooting and fly off on release (or once Marked's aim has charged enough). A thrown knife keeps the head turned. -// Ludovico's knife is not reconstructed yet. +// Ludovico steers one knife instead. void Weapon_Knife::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) { Weapon::Fire(shootDirection, isShooting, isInterpolated); @@ -222,8 +297,7 @@ void Weapon_Knife::Fire(const Vector& shootDirection, bool isShooting, bool isIn int variant = shooter && shooter->temporaryEffects.HasNullEffect(NULLITEM_BLOODY_BABYLON) ? KNIFE_SUMPTORIUM : KNIFE_MOMS_KNIFE; float range = (player ? player->tearRange : KNIFE_RANGE_DEFAULT) * KNIFE_RANGE_SHARE; - if (modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE) - reconstruction_missing("Weapon_Knife::Fire 00a03f90 (Ludovico's knife)"); + if (modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE) return ludovico_update(shootDirection, isShooting, isInterpolated); Entity* markedTarget = player ? player->markedTarget : nullptr; Vector target = markedTarget && isMarked ? markedTarget->pos : fixedDirection; diff --git a/src/weapon_knives.h b/src/weapon_knives.h index c49f8e1..8d771db 100644 --- a/src/weapon_knives.h +++ b/src/weapon_knives.h @@ -38,6 +38,7 @@ struct Weapon_Knife : Weapon void knives_aim(const Vector& aim); void knives_throw(const KnifeThrow& knifeThrow); void ludovico_update(const Vector& shootDirection, bool isShooting, bool isInterpolated); + void ludovico_chain_update(Entity_Knife& main, int variant); }; // What a swing gives each club it starts: the tear effects, color and damage of a fresh tear, and the extra swings. diff --git a/src/weapon_lasers.cpp b/src/weapon_lasers.cpp index ad055ce..d57d4eb 100644 --- a/src/weapon_lasers.cpp +++ b/src/weapon_lasers.cpp @@ -18,9 +18,18 @@ #include "room.h" #include "room_grid.h" #include "sfx_manager.h" +#include "weapon_fetus.h" #include constexpr float LASER_INHERIT_SCALE = 0.4f; +constexpr float FAMILIAR_EYE_SPREAD = 7; +constexpr float C_SECTION_FETUS_SPEED = 10; +constexpr float C_SECTION_HALF_TURN = 3.14f; +constexpr float C_SECTION_JITTER = 3; +constexpr float FAMILIAR_EYE_LIFT = 8; +constexpr uint32_t TECH5_FLAG_REACH = 64; +constexpr ColorMod BABY_BENDER_LASER_COLOR = {{0.4f, 0.15f, 0.38f, 1}, {0, 0, 0, 0}, {0.3529412f, 0, 0.7058824f}}; +constexpr ColorMod LIL_DELIRIUM_LASER_COLOR = {{0.2f, 1, 0, 1}, {0, 0, 0, 0}, {1, 1, 0}}; constexpr float LASER_AIM_SPEED = 10; constexpr float LASER_BLINK_SCALE = -0.45f; constexpr int LASER_BLINK_BASE = 7; @@ -163,25 +172,60 @@ static int marked_variant_get(Entity_Player* player) return player->HasCollectible(COLLECTIBLE_EYE_OF_THE_OCCULT) ? OCCULT_TARGET_VARIANT : MARKED_TARGET_VARIANT; } -// 009f3f60 The color the owner's lasers take: its player's laser color. A familiar's lasers are recolored by -// Baby-Bender, which is not reconstructed yet. Online, another player's lasers fade with the opacity option, which -// this offline build has no use for. +// 009f3f60 The color the owner's lasers take: its player's laser color, purple for a familiar under Baby-Bender and +// green for Lil Delirium. A remote online player's fade with the opacity option. ColorMod Weapon::get_laser_color() { Entity_Player* player = weapon_player(owner); if (!player) return COLOR_DEFAULT; + + ColorMod color = player->laserColor; if (owner->type == ENTITY_FAMILIAR) - reconstruction_missing("Weapon::get_laser_color 009f3f60 (a familiar's lasers)"); - return player->laserColor; + { + if (player->HasTrinket(TRINKET_BABY_BENDER)) + color = BABY_BENDER_LASER_COLOR; + else if (static_cast(owner)->isLilDelirium) + color = LIL_DELIRIUM_LASER_COLOR; + } + color._tint[3] *= shot_alpha_get(player); + return color; } -// 009f5a30 Where the owner's laser of an offset leaves from: its player's eye or mouth. A familiar's are not -// reconstructed yet. +// 00631a00 Where a familiar's laser of an offset leaves from, toward a direction: its eyes for Technology and +// Technology 2, its mouth for the beams, its middle otherwise, all 23 up. +Vector familiar_laser_offset_get(int laserOffsetId, const Vector& direction) +{ + Vector offset{}; + switch (laserOffsetId) + { + case LASER_OFFSET_NONE: + return {}; + case LASER_OFFSET_TECH1: + offset = vector_make(direction.y * FAMILIAR_EYE_SPREAD + (direction.x + direction.x), + direction.x + direction.x - FAMILIAR_EYE_LIFT); + break; + case LASER_OFFSET_TECH2: + offset = vector_make(direction.x + direction.x - direction.y * FAMILIAR_EYE_SPREAD, + -FAMILIAR_EYE_LIFT - (direction.x + direction.x)); + break; + case LASER_OFFSET_SHOOP: + case LASER_OFFSET_BRIMSTONE: + case LASER_OFFSET_TRACTOR_BEAM: + offset = vector_make(direction.x * FAMILIAR_BRIMSTONE_REACH, + FAMILIAR_BRIMSTONE_LIFT - std::abs(direction.x) * FAMILIAR_BRIMSTONE_LIFT); + break; + default: + break; + } + return vector_make(offset.x + 0, offset.y - FAMILIAR_BRIMSTONE_HEIGHT); +} + +// 009f5a30 Where the owner's laser of an offset leaves from: its player's eye or mouth, or its familiar's. Vector Weapon::GetOwnerLaserOffset(int laserOffsetId, const Vector& shootDirection) { if (!owner) return {}; if (owner->type == ENTITY_PLAYER) return owner->ToPlayer()->GetLaserOffset(laserOffsetId, shootDirection); - if (owner->type == ENTITY_FAMILIAR) reconstruction_missing("Weapon::GetOwnerLaserOffset 009f5a30 (00631a00)"); + if (owner->type == ENTITY_FAMILIAR) return familiar_laser_offset_get(laserOffsetId, shootDirection); return {}; } @@ -287,13 +331,14 @@ Entity_Laser* Weapon::fire_brimstone_with_color(const Vector& shootDirection, fl return laser; } -// 009f6610 Fires a Technology laser: the player's own, a familiar's (not reconstructed yet), or a plain one from the -// owner. +// 009f6610 Fires a Technology laser: the player's own, or a familiar's from its eye in the laser color with its +// player's flags (one of Tech.5's in twenty with a random flag of the first 64 only) and laser hit params (Technology +// 2's with the weapon's damage), drawn behind it when it fires up or away from the eye. Anything else fires a plain +// one from the owner. Entity_Laser* Weapon::fire_laser(const TechLaserShot& shot) { if (owner && owner->type == ENTITY_PLAYER) return owner->ToPlayer()->FireTechLaser(shot); - if (owner && owner->type == ENTITY_FAMILIAR) - reconstruction_missing("Weapon::fire_laser 009f6610 (a familiar's laser)"); + if (owner && owner->type == ENTITY_FAMILIAR) return familiar_laser_fire(shot); return Entity_Laser::ShootAngle({.position = get_owner_position(), .source = owner, @@ -302,6 +347,50 @@ Entity_Laser* Weapon::fire_laser(const TechLaserShot& shot) .variant = LASER_THIN_RED}); } +// A familiar's Technology laser (the familiar half of 009f6610). +Entity_Laser* Weapon::familiar_laser_fire(const TechLaserShot& shot) +{ + Entity_Player* player = static_cast(owner)->player; + float angle = std::atan2(shot.direction.y, shot.direction.x) * RADIANS_TO_DEGREES; + Vector offset = GetOwnerLaserOffset(shot.offsetId, shot.direction); + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = vector_make(offset.x + shot.position.x, shot.position.y + 0), + .posOffset = vector_make(0, offset.y), + .source = owner, + .angleDegrees = angle, + .timeout = TECH_LASER_TIMEOUT, + .variant = LASER_THIN_RED}); + laser->isOneHit = shot.isOneHit; + laser->isDisableFollowParent = true; + + TearFlags flags{}; + if (shot.offsetId == LASER_OFFSET_TECH5 && Random() % (uint32_t)TECH5_FLAG_ROLL < (uint32_t)TECH5_FLAG_CHANCE) + { + uint32_t bit = Random() % (uint32_t)TECH5_FLAG_COUNT; + if (bit < TECH5_FLAG_REACH) flags.set(bit); + } + else + flags = get_owner_tear_flags(); + laser->tearFlags = flags; + laser->SetColor(get_laser_color(), -1, COLOR_PRIORITY_DEFAULT, false, true); + if (player && shot.offsetId == LASER_OFFSET_TECH2) + laser->SetCollisionDamage(get_damage()); + else if (player) + { + int displacement = (int)(Random() & 1) * 2 - 1; + TearParams params = player->GetTearHitParams(WEAPON_LASER, shot.damageScale, displacement, owner); + laser->SetCollisionDamage(params.tearDamage); + laser->mass *= params.massMultiplier; + } + laser->entityGridCollisionClass = GRIDCOLL_NOPITS; + + const Vector& aim = shot.direction; + bool isBehind = shot.isLeftEye ? (aim.y < -TECH_LASER_FACING || aim.x > TECH_LASER_FACING) + : (aim.y <= -TECH_LASER_FACING || aim.x <= -TECH_LASER_FACING); + laser->renderDepthOffset = isBehind ? TECH_LASER_BACK_DEPTH : TECH_LASER_FRONT_DEPTH; + laser->isPlayerParams = true; + return laser; +} + // 00a052a0 Forgets the charges. The base's reset does not run. void Weapon_Laser::Reset() { @@ -420,6 +509,58 @@ std::vector Weapon_Laser::fire_lasers(const LaserVolley& volley) return fired; } +// Part of 00a052b0: Ludovico's Technology ring over the owner, made again when gone or of the wrong kind. Shooting +// steers it by the shot speed, and with no enemies left it drifts home from afar. Every fire delay it sets off the +// player's tear effects outward from the player. +void Weapon_Laser::ludovico_ring_update(const Vector& shootDirection, bool isShooting, bool isInterpolated) +{ + Entity_Player* player = weapon_player(owner); + float shotSpeed = player ? player->shotSpeed : 1; + Vector ownerPosition = owner ? owner->pos : Vector{}; + Entity* ring = ludovicoLaser; + if (!isInterpolated) + { + if (ring && (ring->variant != LASER_THIN_RED || ring->subtype != LASER_SUBTYPE_RING_LUDOVICO)) ring->Remove(); + if (!ring || ring->isDead) + { + Entity_Laser* laser = static_cast(g_game->Spawn({.position = ownerPosition, + .spawner = owner, + .subType = LASER_SUBTYPE_RING_LUDOVICO, + .type = ENTITY_LASER, + .variant = LASER_THIN_RED, + .seed = Random()})); + laser->posOffset = vector_make(0, LUDOVICO_RING_LIFT); + laser->parent = owner; + laser->renderDepthOffset = TECH_LASER_FRONT_DEPTH; + init_laser(*this, *laser); + laser->Update(); + ludovicoLaser = ring = laser; + } + } + if (!ring) return; + + if (isShooting) + { + Vector push = shootDirection; + if (vector_length_squared(push) > 1) push = vector_normalized(push); + ring->AddVelocity_divided(vector_scale(push, shotSpeed), false); + } + else if (g_game->room->GetAliveEnemiesCount() < 1) + { + Vector away = vector_sub(ownerPosition, ring->pos); + if (vector_length_squared(away) > LUDOVICO_RETURN_DISTANCE_SQUARED) + ring->AddVelocity_divided(vector_scale(vector_normalized(away), LUDOVICO_RETURN_PUSH), false); + } + if (isInterpolated) return; + + init_laser(*this, *static_cast(ring)); + Entity* shooter = owner && owner->is_player() ? owner : nullptr; + if (!shooter || !shooter->GetIntervalTicks(maxFireDelay, 0)) return; + + bool isApart = ring->pos.x != owner->pos.x || ring->pos.y != owner->pos.y; + TriggerTearEffects(isApart ? vector_normalized(vector_sub(ring->pos, owner->pos)) : random_direction(), 1); +} + // 00a052b0 Fires Technology's lasers: one volley per fire delay passed this frame (at most eight), from the eye with // the volley's extra backward, sideways and random lasers, carrying a share of the owner's movement unless a // Tractor Beam holds them. Ludovico's ring and the charged shots (Monstro's Lung, Chocolate Milk, Cursed Eye) are @@ -427,8 +568,7 @@ std::vector Weapon_Laser::fire_lasers(const LaserVolley& volley) void Weapon_Laser::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) { Weapon::Fire(shootDirection, isShooting, isInterpolated); - if (modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE) - reconstruction_missing("Weapon_Laser::Fire 00a052b0 (Ludovico's ring)"); + if (modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE) return ludovico_ring_update(shootDirection, isShooting, isInterpolated); if (modifiers & (WEAPON_MOD_MONSTROS_LUNG | WEAPON_MOD_CHOCOLATE_MILK | WEAPON_MOD_CURSED_EYE)) reconstruction_missing("Weapon_Laser::Fire 00a052b0 (charged lasers)"); @@ -630,28 +770,11 @@ void Weapon_Brimstone::release(const Vector& shootDirection, const BrimstoneAim& if (!aim.isHasBrimstone) damageScale *= 0.5f; } - Weapon_MultiShotParams params = GetMultiShotParams(); aimAngle = vector_angle(beamDirection); if (isCSection) update_c_section_charge_anim(HEAD_CHARGE_SHOOT, beamDirection, -1); else UpdateHeadChargeAnimation(COLLECTIBLE_BRIMSTONE, HEAD_CHARGE_SHOOT, beamDirection, -1); - Entity_Laser* first = nullptr; - for (int i = 0; i < params.numTears; i++) - { - PosVel shot = Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_BRIMSTONE, beamDirection, - aim.shotSpeed, params); - Entity_Laser* laser = fire_brimstone_with_color(shot.velocity, damageScale, fireFlags); - laser->Update(); - if (first) laser->parent = first; - else mainLaser = first = laser; - } - for (int i = 0; i < params.numRandomDirTears; i++) fire_beam(random_direction(), damageScale, fireFlags); - if (params.isShootingBackwards) fire_beam(vector_scale(beamDirection, -1), damageScale, fireFlags); - if (params.isShootingSideways) - { - fire_beam(vector_make(-beamDirection.y, beamDirection.x), damageScale, fireFlags); - fire_beam(vector_make(beamDirection.y, -beamDirection.x), damageScale, fireFlags); - } + beam_volley({beamDirection, aim.shotSpeed, damageScale, fireFlags}); if (isAntiGravity && isCSection) fire_c_section_fetuses(); } @@ -859,42 +982,82 @@ void Weapon_Brimstone::Fire(const Vector& shootDirection, bool isShooting, bool else if (isShootingNow || is_c_section_anim_finished()) bodyDirection = shootDirection; } -// 00a00d10 +// 00a00d10 C Section with Brimstone: the main beam and every beam hung on it throws a fetus from its start along it, a +// bit astray, at the owner's shot speed. void Weapon_Brimstone::fire_c_section_fetuses() { - reconstruction_missing("Weapon_Brimstone::fire_c_section_fetuses 00a00d10"); + Entity_Player* player = weapon_player(owner); + float shotSpeed = player ? player->shotSpeed : 1; + for (Entity* beam : entity_query(ENTITY_LASER, -1)) + { + if (beam != mainLaser.get() && beam->parent != mainLaser.get()) continue; + + Vector along = vector_scale(vector_from_angle(static_cast(beam)->angleDegrees), C_SECTION_FETUS_SPEED); + float angle = random_unit() * C_SECTION_HALF_TURN; + angle += angle; + Vector velocity = vector_make((std::cos(angle) * C_SECTION_JITTER + along.x) * shotSpeed, + (std::sin(angle) * C_SECTION_JITTER + along.y) * shotSpeed); + fire_fetus_tear(*this, {.position = beam->pos, .velocity = velocity, .source = owner})->Update(); + } } -// Hemoptysis' sneeze when a shot starts with nothing held: hitscan bursts of blood along the volley (its shots, Eye -// Sore's, Mom's Eye's and Loki's Horns'), the rest dropped after the first that hits. A hit, or the boost the item's -// use left, sets the next charge halfway along, and the fire delay restarts at a full charge. -void Weapon_Brimstone::sneeze(const Vector& shootDirection, const BrimstoneAim& aim) +// The beams of one volley along a direction: the volley's shots (the first made the main beam, the others hung on +// it), then the random, backward and sideways ones on the main beam. +void Weapon_Brimstone::beam_volley(const BeamVolley& volley) { - Vector aimDirection = IsAxisAligned() ? vector_cardinal(shootDirection) : vector_normalized(shootDirection); Weapon_MultiShotParams params = GetMultiShotParams(); - aimAngle = vector_angle(aimDirection); - UpdateHeadChargeAnimation(COLLECTIBLE_BRIMSTONE, HEAD_CHARGE_SHOOT_ALT, aimDirection, -1); - SetBlinkTime(SNEEZE_BLINK); + Entity_Laser* first = nullptr; + for (int i = 0; i < params.numTears; i++) + { + PosVel shot = Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_BRIMSTONE, volley.direction, + volley.shotSpeed, params); + Entity_Laser* laser = fire_brimstone_with_color(shot.velocity, volley.damageScale, volley.fireFlags); + laser->Update(); + if (first) laser->parent = first; + else mainLaser = first = laser; + } + for (int i = 0; i < params.numRandomDirTears; i++) + fire_beam(random_direction(), volley.damageScale, volley.fireFlags); + if (params.isShootingBackwards) fire_beam(vector_scale(volley.direction, -1), volley.damageScale, volley.fireFlags); + if (!params.isShootingSideways) return; + fire_beam(vector_make(-volley.direction.y, volley.direction.x), volley.damageScale, volley.fireFlags); + fire_beam(vector_make(volley.direction.y, -volley.direction.x), volley.damageScale, volley.fireFlags); +} +// The hitscan bursts of blood of one volley along a direction (its shots, then the random, backward and sideways +// ones), the rest dropped after the first that hits. A hit, or the boost Hemoptysis's use left, sets the charge +// halfway to full and spends the boost. +void Weapon_Brimstone::hitscan_volley(const BeamVolley& volley, Entity_Player* player) +{ + Weapon_MultiShotParams params = GetMultiShotParams(); + Vector aim = volley.direction; bool isHit = false; for (int i = 0; i < params.numTears; i++) { - PosVel shot = Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_BONE, aimDirection, aim.shotSpeed, params); - if (!isHit) isHit = fire_hitscan(shot.velocity, 1); + PosVel shot = Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_BONE, aim, volley.shotSpeed, params); + if (!isHit) isHit = fire_hitscan(shot.velocity, volley.damageScale); } for (int i = 0; i < params.numRandomDirTears; i++) - if (!isHit) isHit = fire_hitscan(random_direction(), 1); - if (params.isShootingBackwards && !isHit) isHit = fire_hitscan(vector_scale(aimDirection, -1), 1); + if (!isHit) isHit = fire_hitscan(random_direction(), volley.damageScale); + if (params.isShootingBackwards && !isHit) isHit = fire_hitscan(vector_scale(aim, -1), volley.damageScale); if (params.isShootingSideways && !isHit) - isHit = fire_hitscan(vector_make(-aimDirection.y, aimDirection.x), 1) || - fire_hitscan(vector_make(aimDirection.y, -aimDirection.x), 1); + isHit = fire_hitscan(vector_make(-aim.y, aim.x), volley.damageScale) || + fire_hitscan(vector_make(aim.y, -aim.x), volley.damageScale); - Entity_Player* player = aim.player; - if (isHit || (player && player->temporaryEffects.HasNullEffect(NULLITEM_HEMOPTYSIS_BOOST))) - { - charge += (GetMaxCharge() - charge) * HALF; - if (player) player->temporaryEffects.RemoveNullEffect(NULLITEM_HEMOPTYSIS_BOOST, -1); - } + if (!isHit && !(player && player->temporaryEffects.HasNullEffect(NULLITEM_HEMOPTYSIS_BOOST))) return; + charge += (GetMaxCharge() - charge) * HALF; + if (player) player->temporaryEffects.RemoveNullEffect(NULLITEM_HEMOPTYSIS_BOOST, -1); +} + +// Hemoptysis' sneeze when a shot starts with nothing held: a hitscan volley along the aim, and the fire delay +// restarts at a full charge. +void Weapon_Brimstone::sneeze(const Vector& shootDirection, const BrimstoneAim& aim) +{ + Vector aimDirection = IsAxisAligned() ? vector_cardinal(shootDirection) : vector_normalized(shootDirection); + aimAngle = vector_angle(aimDirection); + UpdateHeadChargeAnimation(COLLECTIBLE_BRIMSTONE, HEAD_CHARGE_SHOOT_ALT, aimDirection, -1); + SetBlinkTime(SNEEZE_BLINK); + hitscan_volley({aimDirection, aim.shotSpeed, 1, 0}, aim.player); fireDelay = aim.maxCharge; } @@ -1089,10 +1252,21 @@ bool Weapon_Brimstone::fire_hitscan(const Vector& direction, float damageScale) return isHit; } -// 00a02890 -void Weapon_Brimstone::fire(float, bool) +// 00a02890 Fires one volley at once along a direction, uncharged (Hemoptysis's sneeze through a passing weapon): with +// Azazel's sneeze a hitscan volley of blood, otherwise Brimstone's beams, at the owner's shot speed. +void Weapon_Brimstone::fire(const Vector& shootDirection, float damageScale) { - reconstruction_missing("Weapon_Brimstone::fire 00a02890"); + Entity_Player* player = weapon_player(owner); + BeamVolley volley{shootDirection, player ? player->shotSpeed : 1, damageScale, 0}; + if (!(modifiers & WEAPON_MOD_AZAZELS_SNEEZE)) + { + UpdateHeadChargeAnimation(COLLECTIBLE_BRIMSTONE, HEAD_CHARGE_SHOOT, shootDirection, -1); + beam_volley(volley); + return; + } + UpdateHeadChargeAnimation(COLLECTIBLE_BRIMSTONE, HEAD_CHARGE_SHOOT_ALT, shootDirection, -1); + SetBlinkTime(SNEEZE_BLINK); + hitscan_volley(volley, player); } // 00a0e260 The charge a full ring takes: three fire delays. diff --git a/src/weapon_lasers.h b/src/weapon_lasers.h index bcab2cc..262b6cd 100644 --- a/src/weapon_lasers.h +++ b/src/weapon_lasers.h @@ -34,10 +34,20 @@ struct Weapon_Laser : Weapon std::vector fire_lasers(const LaserVolley& volley); static void init_laser(Weapon& weapon, Entity_Laser& laser); + void ludovico_ring_update(const Vector& shootDirection, bool isShooting, bool isInterpolated); }; struct BrimstoneAim; +// One volley of Brimstone: along a direction at a shot speed, its damage scale and FireBrimstone's flags. +struct BeamVolley +{ + Vector direction{}; + float shotSpeed = 1; + float damageScale = 1; + uint32_t fireFlags = 0; +}; + // Destruction (009f9a20) is the default. // The weapon that charges and fires Brimstone's beams. aimAngle is where the beams point, swept toward the aim. struct Weapon_Brimstone : Weapon @@ -61,7 +71,9 @@ struct Weapon_Brimstone : Weapon void fire_c_section_fetuses(); void sneeze(const Vector& shootDirection, const BrimstoneAim& aim); bool fire_hitscan(const Vector& direction, float damageScale); - void fire(float speed, bool isStatusIgnored); + void beam_volley(const BeamVolley& volley); + void hitscan_volley(const BeamVolley& volley, Entity_Player* player); + void fire(const Vector& shootDirection, float damageScale); }; // Destruction (009f3260) is the base's.