diff --git a/db/names.tsv b/db/names.tsv index 564e89f..0a21006 100644 --- a/db/names.tsv +++ b/db/names.tsv @@ -470,7 +470,7 @@ 00684b90 hsv_to_rgb hue/60 sextant switch, chroma*value 00652a90 _has_flag_0x110 ? ? (this+0x110 & mask)!=0 00505b80 _Entity_NPC::GetColorWithFlash ? ? copies Color, multiplies when +0xc>0; NPC ResetColor/Update -004b6a90 std::deque::push_front 4-per-block deque front insertion +004b6a90 std::deque::push_back 4-per-block deque back insertion: grows when (offset+size)%4==0, writes at offset+size, offset unchanged (was push_front; the decompile proves push_back) 00452be0 _ptr_deref_or_minus1 ? ? returns *ptr or -1 00435d60 Entity::SetTargetPosition writes +0x334/+0x338 (_targetPosition) 00426980 std::vector::_Tidy frees 8-byte element vector diff --git a/dump/all.c b/dump/all.c index c4c6dde..96ac02b 100644 --- a/dump/all.c +++ b/dump/all.c @@ -115397,7 +115397,7 @@ LAB_004b5198: piVar5[0x2d9] = 9; (**(code **)(*piVar5 + 0xc))(); VStack_130.x = 0.0; - std::deque::push_front(&VStack_130); + std::deque::push_back(&VStack_130); VStack_104.x = (float)npc->_child; uVar15 = ((npc->_entityDeque)._size + (npc->_entityDeque)._offset) - 1; uVar16 = uVar15 & 3; @@ -116072,11 +116072,11 @@ LAB_004b67fd: } -//@@ 004b6a90 std::deque::push_front +//@@ 004b6a90 std::deque::push_back /* DB: 4-per-block deque front insertion */ -void std::deque::push_front(undefined4 *param_1) +void std::deque::push_back(undefined4 *param_1) { uint uVar1; @@ -171750,7 +171750,7 @@ LAB_00519d09: *(undefined4 *)(extraout_EAX_00 + 0x3bc) = npc; std::multiset::insert((undefined4 *)(extraout_EAX_00 + 0x3bc)); local_160.y = 0.0; - std::deque::push_front(&local_160.y); + std::deque::push_back(&local_160.y); local_160.y = (float)((npc->_entityDeque)._offset + (npc->_entityDeque)._size); uVar5 = (uint)&((Entity_NPC *)((int)local_160.y + -0xf60))->field_0xf5f & 3; iVar7 = *(int *)((int)(npc->_entityDeque)._map + @@ -245573,7 +245573,7 @@ void __fastcall NpcAI::ENTITY_VISAGE(Entity_NPC *npc) (npc->_v1).x = 0.0; Entity_NPC::ClearDequeRefs(npc); local_350.x = 0.0; - std::deque::push_front(&local_350); + std::deque::push_back(&local_350); (npc->_v1).y = 150.0; uVar12 = Random(); scratchVec.x = (npc->_pos).x + 0.0; @@ -247135,7 +247135,7 @@ void __fastcall NpcAI::ENTITY_VISAGE_mask(Entity_NPC *npc) tmpEntity->_parent = npc; std::multiset::insert(&tmpEntity->_parent); local_10c.x = 0.0; - std::deque::push_front(&local_10c); + std::deque::push_back(&local_10c); local_f8.y = (float)((npc->_entityDeque)._size + (npc->_entityDeque)._offset); uVar8 = (int)local_f8.y - 1U & 3; iVar4 = *(int *)((int)(npc->_entityDeque)._map + @@ -258935,7 +258935,7 @@ LAB_005b8f47: afStack_7f0[1] = (float)*puVar14; pEVar6 = (Entity_Player *)Entity_Familiar::Player(); if (pEVar6 == curPlayer) { - std::deque::push_front(); + std::deque::push_back(); } uVar24 = uVar24 + 1; uVar9 = EntityList::Size((EntityList *)boneOrbitals); @@ -259073,7 +259073,7 @@ LAB_005c1f2d: tmpVec = Vector::__mul(tmpVec,&bookOfTheDeadScaled2,&bookOfTheDeadRandomScale1); Entity::SetVelocity(boneOrbital,tmpVec); Entity::ClearEntityFlags(boneOrbital,4); - std::deque::push_front(); + std::deque::push_back(); } ::Color::Color(bookOfTheDeadColor1); fVar29 = random_float(); @@ -259198,7 +259198,7 @@ LAB_005c1f2d: tmpVec = Vector::__mul(tmpVec,&bookOfTheDeadScaled6,&bookOfTheDeadRandomScale2); Entity::SetVelocity(boneOrbital2,tmpVec); Entity::ClearEntityFlags(boneOrbital2,4); - std::deque::push_front(); + std::deque::push_back(); } ::Color::Color(bookOfTheDeadColor2); fVar29 = random_float(); @@ -312245,7 +312245,7 @@ short Level::compute_room_distances queueProxyRef[1] = 0; *queueProxyRef = (int)&queueProxyRef; local_8 = 0; - std::deque::push_front(&local_54); + std::deque::push_back(&local_54); distances[local_54] = 0; if (queueSize != 0) { do { @@ -312273,7 +312273,7 @@ short Level::compute_room_distances } if (newDistance < (ushort)distancesLocal[neighborRoom]) { distancesLocal[neighborRoom] = (short)newDistance; - std::deque::push_front(&neighborRoom); + std::deque::push_back(&neighborRoom); } iVar5 = iVar5 + 1; psVar2 = psVar3; @@ -510395,7 +510395,7 @@ Entity * __thiscall Entity_Player::AddSwarmFlyOrbital(Entity_Player *game,Vector } else if ((*(int *)(familiar + 0x2c) == 0xe5) && (*(Entity_Player **)(familiar + 0x410) == game)) { - std::deque::push_front(&familiar); + std::deque::push_back(&familiar); } entityIndex = entityIndex + 1; } while (entityIndex < *(uint *)((int)pvVar3 + 0x1264)); @@ -935274,7 +935274,7 @@ void __thiscall PlayerManager::restore_controller_assignment(PlayerManager *this local_8._0_1_ = 0; local_8._1_3_ = 0; local_14 = g_manager->_activeControllerIndex; - std::deque::push_front(&local_14); + std::deque::push_back(&local_14); uVar6 = 0; while( true ) { (**(code **)(PTR_vftable_00c57b2c + 0xc))(0xffffffff,uVar2); diff --git a/dump/functions.tsv b/dump/functions.tsv index 2af1c0b..4e8c8e0 100644 --- a/dump/functions.tsv +++ b/dump/functions.tsv @@ -1100,7 +1100,7 @@ 004b3f10 FUN_004b3f10 437 004b40d0 NpcHelper::heretic_choose_attack 740 004b43c0 NpcAI::ENTITY_HERETIC 1264 -004b6a90 std::deque::push_front 132 +004b6a90 std::deque::push_back 132 004b6b20 FUN_004b6b20 443 004b6ce0 FUN_004b6ce0 130 004b6d70 FUN_004b6d70 68 diff --git a/generated-src/boss_overlay.cpp b/generated-src/boss_overlay.cpp deleted file mode 100644 index 678afc2..0000000 --- a/generated-src/boss_overlay.cpp +++ /dev/null @@ -1,127 +0,0 @@ -#include "classes.h" - -// 004212c0 -void BossOverlay::update() -{ - uint8_t isEndTriggered; - int *in_ECX; - int *counter; - Game *game; - Manager *manager; - SoundEffects *sfxManager; - - if (*in_ECX != 0) { - if ((*in_ECX == 1) && - (((in_ECX[0xf] == 0 || ((char)in_ECX[0x13] == '\0')) && - ((char)in_ECX[(in_ECX[1] + 6) * 0xe] == '\0')))) { - *in_ECX = 0; - } - if (*GHIDRA_CAST((GHIDRA_CAST(in_ECX) + 0x111)) != '\0') { - AnimationState::Update(GHIDRA_CAST((in_ECX + 0xe))); - AnimationState::Update(GHIDRA_CAST((in_ECX + 0x16))); - } - if (in_ECX[1] == 3) { - if (in_ECX[0xf] != 0) { - isEndTriggered = - AnimationState::IsEventTriggered(GHIDRA_CAST((in_ECX + 0xe)),&DAT_00b1c00c); - manager = g_manager; - if (isEndTriggered != 0) { - sfxManager = &g_manager->_sfxManager; - counter = (g_manager->_persistentGameData)._cutsceneCounters + 0x19; - *counter = *counter + 1; - *GHIDRA_CAST(&manager->_persistentGameData) = 1; - counter = (manager->_persistentGameData)._cutsceneCounters + 2; - *counter = *counter + 1; - *GHIDRA_CAST(&manager->_persistentGameData) = 1; - (*GHIDRA_CAST((GHIDRA_CAST(&((manager->_cutsceneManager))) + 0x848))) = 1; - (manager->_cutsceneManager)._isQueuedCleanup = 0; - manager->_cutsceneNextMenuState = 1; - (manager->_cutsceneManager)._queuedCutsceneId = 0x19; - (manager->_achievementOverlay)._isPopupBlocked = 1; - if ((manager->_sfxManager)._volumeModifier != 1.0) { - (manager->_sfxManager)._volumeModifier = 1.0; - (GHIDRA_CAST((sfxManager)))->SoundEffects::ClearVolumeModifier(); - } - game = g_game; - (manager->_sfxManager)._volumeModifierStep = 0.005; - Game::StartRoomTransition(game,-10,-1,1,GHIDRA_CAST(0x0),-1); - RoomTransition::Update(&g_game->_roomTransition); - return; - } - if ((in_ECX[0xf] != 0) && ((char)in_ECX[0x13] != '\0')) { - return; - } - } - *in_ECX = 0; - in_ECX[1] = 0; - } - } - return; -} - -// 004214b0 -void BossOverlay::play(int overlayType) -{ - void *sprite = this; - uint8_t bVar1; - LayerState *layer; - uint8_t *currentName; - uint32_t compareResult; - uint8_t unk; - uint8_t *targetName; - uint8_t *anim; - bool isLess; - uint8_t *animData; - ANM2 *sprite; - - if (4 < GHIDRA_UINT(overlayType)) { - return; - } - sprite = GHIDRA_CAST((GHIDRA_INT(sprite) + 8)); - ANM2::Load(sprite,GHIDRA_CAST((GHIDRA_INT(sprite) + overlayType * 0x38 + 0x120)),1); - ANM2::LoadGraphics(sprite,unk); - *GHIDRA_CAST((GHIDRA_CAST(sprite) + 4)) = overlayType; - if ((overlayType == 2) || (overlayType == 3)) { - layer = ANM2::GetLayer(sprite,&DAT_00000004); - layer->_bitflags = layer->_bitflags | 0x20; - } - anim = GHIDRA_CAST((GHIDRA_INT(sprite) + overlayType * 0x38 + 0x138)); - if (0xf < *GHIDRA_CAST((GHIDRA_CAST(sprite) + overlayType * 0x38 + 0x14c))) { - anim = *GHIDRA_CAST(anim); - } - if (*GHIDRA_CAST((GHIDRA_CAST(sprite) + 0x3c)) != 0) { - animData = *GHIDRA_CAST((GHIDRA_CAST(sprite) + 0x3c)); - currentName = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - currentName = *GHIDRA_CAST(animData); - } - targetName = anim; - do { - bVar1 = *currentName; - isLess = bVar1 < *targetName; - if (bVar1 != *targetName) { -LAB_00421555: - compareResult = -GHIDRA_UINT(isLess) | 1; - goto LAB_0042155a; - } - if (bVar1 == 0) break; - bVar1 = currentName[1]; - isLess = bVar1 < targetName[1]; - if (bVar1 != targetName[1]) goto LAB_00421555; - currentName = currentName + 2; - targetName = targetName + 2; - } while (bVar1 != 0); - compareResult = 0; -LAB_0042155a: - if ((compareResult == 0) && ((animData[0x34] == 0 || (*GHIDRA_CAST((GHIDRA_CAST(sprite) + 0x4c)) != '\0')))) - goto LAB_00421582; - } - bVar1 = ANM2::SetAnimation(sprite,anim,1); - if (bVar1 != 0) { - AnimationState::Rewind(GHIDRA_CAST((GHIDRA_INT(sprite) + 0x38))); - *GHIDRA_CAST((GHIDRA_CAST(sprite) + 0x4c)) = 1; - } -LAB_00421582: - *GHIDRA_CAST(sprite) = 1; - return; -} diff --git a/generated-src/classes.h b/generated-src/classes.h index dea32b6..32eebe4 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -219,6 +219,7 @@ struct DeathmatchTypeSwordFight; struct DeathmatchTypeVenom; struct DebugRenderer; struct DeliriousBoss; +struct DescriptionScroll; struct DestinationQuad; struct Devolve; struct DimensionReturn; @@ -373,12 +374,14 @@ struct ItemConfig_Costume; struct ItemConfig_Item; struct ItemConfig_Pill; struct ItemConfig_PlayerForm; +struct ItemInfoBox; struct ItemInfoHUD; struct ItemOverlay; struct ItemPool; struct ItemPool_Item; struct ItemUse; struct ItemsHit; +struct JacobsCurseDelay; struct KAGE_Filesys_File; struct KAGE_Filesys_FileManager; struct KAGE_Filesys_FileStream; @@ -568,6 +571,7 @@ struct RerollEntry; struct RevivePlayerMenu; struct RichText; struct RichTextIcon; +struct RichTextLine; struct RichTextSpan; struct RockDrop; struct Room; @@ -1004,14 +1008,6 @@ struct BlendMode { }; -struct BossOverlay { - static void update(); // 004212c0 - void play(int overlayType); // 004214b0 - - int _state; -}; -LAYOUT32(offsetof(BossOverlay, _state) == 0x0); - struct BufferedStream { }; @@ -1128,22 +1124,6 @@ struct ConstLobby { }; -struct DailyChallenge { - void Init(uint32_t dailyDate); // 00426a50 - - unsigned int _id; - unsigned int _seed; - bool _isPractice; - uint8_t _pad_0x9[0x3]; - unsigned int _specialDailyId; - uint8_t _params[0x4]; // ChallengeParam -}; -LAYOUT32(offsetof(DailyChallenge, _id) == 0x0); -LAYOUT32(offsetof(DailyChallenge, _seed) == 0x4); -LAYOUT32(offsetof(DailyChallenge, _isPractice) == 0x8); -LAYOUT32(offsetof(DailyChallenge, _specialDailyId) == 0xc); -LAYOUT32(offsetof(DailyChallenge, _params) == 0x10); - struct DamageInfo { DamageInfo(); // 006a8190 }; @@ -3704,12 +3684,6 @@ struct RenderTarget { }; -struct RichTextSpan { - uint8_t try_merge(void *other); // 009ef9a0 - static void move_construct(void *dest, void *source); // 009f1ef0 -}; - - struct RoomConfigMode { void ctor(); // 00828b60 void Clear(); // 00828c00 @@ -5419,12 +5393,10 @@ void FUN_0040c610(); // 0040c610 uint32_t FUN_0040c630(); // 0040c630 void FUN_0040c690(); // 0040c690 uint32_t FUN_0040c6b0(); // 0040c6b0 -uint32_t FUN_0040c6f0(); // 0040c6f0 void FUN_0040c720(uint8_t *param_1); // 0040c720 void deallocate(void *ptr, uint32_t count); // 0040c740 void FUN_0040c790(); // 0040c790 uint32_t FUN_0040c7c0(); // 0040c7c0 -void render_color_stack_push(ColorMod *color); // 0040c890 int memcmp_eq(void *a, void *b, uint32_t size); // 0040ca70 void FUN_0040cad0(); // 0040cad0 uint8_t str_eq(uint8_t *a, uint32_t lengthA, uint8_t *b, uint32_t lengthB); // 0040cae0 @@ -5549,9 +5521,6 @@ uint32_t * FUN_00420020(int param_1, int param_2, uint32_t *param_3); // 004200 RoomTransition * FUN_00420ae0(); // 00420ae0 void FUN_00420b00(); // 00420b00 void FUN_00420b20(); // 00420b20 -void FUN_00421260(); // 00421260 -void FUN_00421400(); // 00421400 -void FUN_004215a0(char *param_1); // 004215a0 void FUN_004215e0(uint32_t *param_1); // 004215e0 void FUN_00421620(uint8_t *param_1); // 00421620 DailyChallenge * FUN_00421780(); // 00421780 @@ -5577,8 +5546,6 @@ int FUN_004253d0(); // 004253d0 void FUN_00425410(); // 00425410 void online_stats_destroy(void *self); // 00425430 void online_stats_register_players(); // 004257b0 -void FUN_00427290(); // 00427290 -int holiday_get_current(uint32_t yyyymmdd); // 00427870 void FUN_00428560(uint32_t *param_1, uint32_t param_2); // 00428560 void FUN_004286b0(int *param_1, int *param_2); // 004286b0 void FUN_00428880(); // 00428880 @@ -5771,7 +5738,6 @@ void FUN_00499950(); // 00499950 void FUN_004999b0(); // 004999b0 uint32_t FUN_004999d0(uint32_t param_1); // 004999d0 uint32_t FUN_00499db0(); // 00499db0 -uint32_t FUN_0049d100(); // 0049d100 void FUN_004a11b0(); // 004a11b0 int FUN_004a2920(); // 004a2920 void FUN_004aaaa0(void *param_1, int param_2); // 004aaaa0 @@ -5839,7 +5805,6 @@ void pow_wrapper(); // 00505b40 void set_byte_0x101(void *self, uint8_t value); // 00505b50 int FUN_00505ca0(); // 00505ca0 uint32_t * FUN_00505ce0(); // 00505ce0 -long double FUN_00515290(Vector *param_1, uint32_t param_2, int param_3); // 00515290 void npc_distribute_orbit_angles(Entity_NPC *npc); // 00547040 int FUN_0054d1b0(int param_1); // 0054d1b0 void FUN_00557b50(uint32_t param_1); // 00557b50 @@ -5852,8 +5817,6 @@ void FUN_0056ff00(uint32_t *param_1, uint32_t param_2, uint32_t param_3); // 00 bool FUN_0056ff60(uint32_t param_1); // 0056ff60 void FUN_00571170(); // 00571170 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_00579700(); // 00579700 uint32_t FUN_00579760(); // 00579760 @@ -6047,7 +6010,6 @@ uint32_t FUN_0060dae0(); // 0060dae0 void FUN_0062e0e0(int param_1); // 0062e0e0 void FUN_00638e20(); // 00638e20 void FUN_0063c060(int param_1); // 0063c060 -void FUN_0063e180(); // 0063e180 void FUN_006431b0(); // 006431b0 void FUN_0064b6a0(); // 0064b6a0 void FUN_0064d570(uint32_t param_1); // 0064d570 @@ -6079,7 +6041,6 @@ int FUN_00652a30(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint8_t p void FUN_00652a70(); // 00652a70 bool _has_flag_0x110(uint32_t param_1); // 00652a90 int FUN_00652ae0(); // 00652ae0 -void reroll_entity_to_free_tile(int param_1); // 0065ad30 bool FUN_0065cfe0(uint32_t param_1); // 0065cfe0 int FUN_0065d010(); // 0065d010 void FUN_0065d020(); // 0065d020 @@ -6092,9 +6053,6 @@ void FUN_0065d0c0(); // 0065d0c0 void FUN_0065d160(); // 0065d160 uint8_t * FUN_0065d1f0(); // 0065d1f0 Vector * FUN_006653c0(Vector *param_1); // 006653c0 -void FUN_006653e0(int param_1); // 006653e0 -void FUN_006655e0(); // 006655e0 -void FUN_00665630(); // 00665630 void FUN_00665a30(); // 00665a30 void FUN_00665a50(); // 00665a50 void FUN_00665a90(Entity *param_1); // 00665a90 @@ -6120,7 +6078,6 @@ uint32_t FUN_0067f030(); // 0067f030 void FUN_0067f2e0(); // 0067f2e0 uint8_t string_to_bool(void *self); // 0067f600 void ResolveRelativePath(uint8_t *anmPath, uint8_t *relPath, uint8_t *outPath); // 0067f670 -void ExtractAngleBracketText(); // 0067fdf0 void FUN_00680060(size_t param_1); // 00680060 void shader_stack_push(int shaderIndex); // 00682280 void FUN_00682350(); // 00682350 @@ -6428,7 +6385,6 @@ void FUN_00738390(uint32_t param_1); // 00738390 void FUN_007383b0(); // 007383b0 int FUN_00738620(uint32_t param_1, uint32_t param_2); // 00738620 void FUN_00741cc0(); // 00741cc0 -void FUN_00741cf0(); // 00741cf0 void FUN_007435c8(); // 007435c8 void FUN_0074371e(); // 0074371e void FUN_0074399a(); // 0074399a @@ -6507,8 +6463,6 @@ void FUN_00757980(uint32_t *param_1); // 00757980 void FUN_00757a10(); // 00757a10 uint32_t FUN_00758590(); // 00758590 int FUN_00759260(); // 00759260 -void FUN_0075d9f0(uint32_t param_1); // 0075d9f0 -uint32_t FUN_0075ef20(ANM2 *param_1, int param_2); // 0075ef20 void FUN_00770640(float *param_1); // 00770640 void FUN_007792f0(uint32_t param_1, uint32_t param_2); // 007792f0 uint32_t FUN_007826c0(); // 007826c0 @@ -6530,7 +6484,6 @@ void FUN_007d9360(); // 007d9360 uint32_t FUN_007d9ca0(); // 007d9ca0 uint32_t FUN_007da770(); // 007da770 uint32_t FUN_007dac30(); // 007dac30 -void FUN_007dad80(); // 007dad80 int FUN_007dafb0(); // 007dafb0 void FUN_007dc610(); // 007dc610 void FUN_007dc620(uint32_t *param_1); // 007dc620 @@ -6614,7 +6567,6 @@ uint32_t * FUN_007e3060(uint32_t *param_1); // 007e3060 void FUN_007e3190(); // 007e3190 void FUN_007e3230(); // 007e3230 void FUN_007e4890(); // 007e4890 -uint8_t pathfinder_can_reach_pos(Vector *targetPos, Vector *startPos, Room *room); // 007e7820 void FUN_007e8620(); // 007e8620 void FUN_007e86e0(int param_1, int param_2); // 007e86e0 void * vector_PathNode_emplace_reallocate_copy(void *self, void *where, void *value); // 007e8810 @@ -6690,7 +6642,6 @@ void FUN_00839840(float *param_1); // 00839840 void FUN_00839960(); // 00839960 void FUN_008399a0(int *param_1); // 008399a0 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 void FUN_0083bf50(); // 0083bf50 @@ -6699,7 +6650,6 @@ void Catch_All_0083c241(); // 0083c241 uint32_t * FUN_0083c270(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3); // 0083c270 void FUN_0083c320(int *param_1, int *param_2); // 0083c320 void FUN_0083c480(); // 0083c480 -void item_pool_icons_render(void *iconLayer, Vector *position, KColor *color); // 0083d8c0 char * FUN_00840510(); // 00840510 std_string * int_to_string(std_string *outString, int value); // 00840540 void FUN_0084abc0(uint32_t *param_1, float *param_2, uint32_t *param_3, uint32_t *param_4); // 0084abc0 @@ -8533,16 +8483,6 @@ void kick_player_menu_render(); // 008d1600 void FUN_008d2810(); // 008d2810 uint32_t * FUN_008d2880(uint32_t *param_1, int param_2); // 008d2880 void FUN_008d28c0(uint32_t param_1, uint8_t *param_2); // 008d28c0 -void FUN_008d47c0(int *param_1, uint32_t *param_2, uint32_t *param_3, uint32_t param_4, float param_5, uint32_t param_6); // 008d47c0 -void FUN_008d5440(float *param_1); // 008d5440 -void FUN_008d5640(float *param_1); // 008d5640 -void FUN_008d57f0(float *param_1); // 008d57f0 -void FUN_008d5da0(int *param_1, ANM2 *param_2, float *param_3); // 008d5da0 -void render_item_info_text(void *self, void *text, Vector *position, int width, uint32_t lineStart, uint32_t lineEnd); // 008d5f70 -int FUN_008d69d0(int param_1); // 008d69d0 -uint32_t menu_item_description_build(void *self, int *item, uint32_t startLine, int unused, float maxHeight); // 008d7cb0 -int FUN_008d8460(int *param_1); // 008d8460 -void item_info_update_charge_bar(void *self, int collectibleId, Entity_Player *player); // 008d8870 void FUN_008d8a90(); // 008d8a90 bool FUN_008dc0a0(int *param_1, int *param_2); // 008dc0a0 bool FUN_008dc0d0(uint32_t param_1, int *param_2, int *param_3, uint8_t **param_4, int *param_5, int *param_6); // 008dc0d0 @@ -8830,7 +8770,6 @@ void float_split(); // 00925f30 void FUN_00926240(); // 00926240 void FUN_00926460(uint8_t param_1); // 00926460 uint32_t FUN_009264b0(uint8_t *param_1, uint8_t *param_2); // 009264b0 -int save_backup_find_latest(PersistentGameData *gameData); // 00926510 void FUN_00929660(char param_1); // 00929660 uint8_t * FUN_00929b00(); // 00929b00 uint32_t FUN_00929b20(); // 00929b20 @@ -8880,7 +8819,6 @@ void cutscene_render_skip_vote_count(void *cutscene, void *state); // 0095eb60 uint32_t * FUN_00960880(void *param_1, uint32_t *param_2); // 00960880 void FUN_00960bc0(); // 00960bc0 void FUN_0096d120(int *param_1); // 0096d120 -void pressure_plate_kill_enemies_timer_callback(int *param_1); // 00983f30 void FUN_0098b0a0(); // 0098b0a0 void FUN_0098b130(); // 0098b130 void FUN_00993740(); // 00993740 @@ -8898,7 +8836,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 -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 void move_directory_files(); // 009a90e0 @@ -9003,7 +8940,6 @@ void FUN_009e6e10(int param_1); // 009e6e10 void FUN_009e6e50(uint8_t *param_1); // 009e6e50 void FUN_009e6e80(); // 009e6e80 void FUN_009e6e90(Weapon_Brimstone *param_1, uint32_t param_2); // 009e6e90 -void save_screenshot(); // 009e6eb0 void FUN_009e72e0(); // 009e72e0 void FUN_009e7300(); // 009e7300 void FUN_009e7310(); // 009e7310 @@ -9050,13 +8986,10 @@ void FUN_009ebbf0(); // 009ebbf0 void Catch_All_009ebf8f(); // 009ebf8f void FUN_009ebfc0(); // 009ebfc0 void FUN_009ef980(uint32_t *param_1); // 009ef980 -Vector * rich_text_render(void *self, Vector *outSize, uint8_t *text, Vector *position, KColor *color, float scale, int maxWidth); // 009efdb0 -void rich_text_layout(void *copiedSpan, uint8_t *markup, KColor *baseColor, uint32_t maxWidth, void *outLines, float scale); // 009f0290 void FUN_009f1be0(uint32_t *param_1); // 009f1be0 void FUN_009f1d20(char *param_1, char *param_2); // 009f1d20 void FUN_009f1d50(void *param_1, int param_2); // 009f1d50 void Catch_All_009f20c7(); // 009f20c7 -void FUN_009f20f0(void *param_1); // 009f20f0 void Catch_All_009f229d(); // 009f229d uint32_t * FUN_009f2410(uint32_t *param_1); // 009f2410 void FUN_009f2480(); // 009f2480 @@ -9167,7 +9100,6 @@ void FUN_00a1d4d0(uint32_t param_1, uint32_t *param_2); // 00a1d4d0 void FUN_00a1d5a0(uint32_t *param_1); // 00a1d5a0 void FUN_00a1d600(); // 00a1d600 void FUN_00a1d6b0(int param_1); // 00a1d6b0 -void render_color_quad(Vector *from, Vector *to, KColor *fromColor, KColor *toColor, float thickness); // 00a1d710 void FUN_00a1e050(); // 00a1e050 void FUN_00a1e1f0(); // 00a1e1f0 uint32_t FUN_00a1e210(); // 00a1e210 @@ -20717,14 +20649,6 @@ ItemConfig * GetItemConfig(); // 0042ca00 int Random(int Max); // 0067f010 Vector * GetRandomPickupVelocity(Vector *outVelocity, Vector *position, uint32_t pickupVelType, RNG *rng); // 006ee440 } -namespace ItemInfo { -uint8_t is_collectible_seen(int param_1); // 0083d760 -uint8_t is_pickup_known(int param_1); // 0083d7c0 -void measure(uint32_t *param_1); // 00840250 -void measure_line(uint8_t *param_1, float *param_2, int *param_3); // 008402f0 -void render_popup_callback(int param_1, uint32_t param_2); // 00840370 -void render_line(uint8_t *param_1, Vector *param_2, int param_3); // 008404a0 -} namespace KAGE_Memory { void * heap_alloc(uint32_t heapId, uint64_t *size); // 00a230b0 void heap_free(uint32_t heapId, void *ptr); // 00a23160 @@ -20758,29 +20682,18 @@ void ENTITY_BEAST_ultra_pestilence_maggot(Entity_NPC *npc); // 0044b6f0 void ENTITY_BEAST_ultra_war(Entity_NPC *npc); // 0044c070 void ENTITY_BEAST_ultra_war_fire_burst(Entity_NPC *npc); // 0044ee60 void ENTITY_BEAST_ultra_war_bomb(Entity_NPC *npc); // 0044f2b0 -void ENTITY_LIL_BLUB(Entity_NPC *npc); // 00450da0 -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_MATRIARCH(Entity_NPC *npc); // 004c59d0 void ENTITY_BUTT_SLICKER(Entity_NPC *npc); // 0054d250 uint32_t ENTITY_POLTY(Entity_NPC *npc); // 0055d230 -void ENTITY_CLUTCH(Entity_NPC *npc); // 00573030 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 void ENTITY_SCOURGE(Entity_NPC *npc); // 00587aa0 void ENTITY_SINGE_body(Entity_NPC *npc); // 0058aed0 -void ENTITY_SINGE_ball(Entity_NPC *npc); // 0058d8b0 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 } -namespace OnlinePlayerInfo { -void render_items(float *param_1); // 008d4940 -} namespace OnlineStats { void compute_awards(); // 004254b0 } diff --git a/generated-src/daily_challenge.cpp b/generated-src/daily_challenge.cpp deleted file mode 100644 index 4012954..0000000 --- a/generated-src/daily_challenge.cpp +++ /dev/null @@ -1,389 +0,0 @@ -#include "classes.h" - -// 00426a50 -void DailyChallenge::Init(uint32_t dailyDate) -{ - code *pcVar1; - int iVar2; - tm *tmResult; - uint32_t uVar3; - uint32_t rolledPlayerType; - bool isGroundhogDay; - RNG rng; - uint8_t date [8]; - __time64_t dateTime; - tm dateTm; - uint32_t local_c; - uint8_t auStack_8 [4]; - - local_c = __security_cookie ^ GHIDRA_UINT((auStack_8 + 4)); - this->_id = 0; - this->_seed = 0; - this->_specialDailyId = 0; - this->_isPractice = 0; - ChallengeParam::Reset(&this->_params); - (this->_params)._isPathTypeSet = 1; - iVar2 = holiday_get_current(dailyDate); - this->_specialDailyId = iVar2; - this->_id = dailyDate; - DateTime::set_from_yyyymmdd(date,dailyDate); - isGroundhogDay = this->_specialDailyId == 2; - rng._seed = dailyDate; - if (isGroundhogDay) { - rng._seed = dailyDate - 1; - } - rng._shift3 = 0x15; - rng._shift1 = 10; - rng._shift2 = 9; - (this->_params)._playerType = 0x29; - uVar3 = dailyDate - 1; - if (!isGroundhogDay) { - uVar3 = dailyDate; - } - do { - if (uVar3 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - rng._seed = GHIDRA_UINT(rng._seed) >> 10 ^ rng._seed; - rng._seed = rng._seed << 9 ^ rng._seed; - rng._seed = GHIDRA_UINT(rng._seed) >> 0x15 ^ rng._seed; - rolledPlayerType = GHIDRA_UINT(rng._seed) % 0x14; - (this->_params)._playerType = rolledPlayerType; - uVar3 = rng._seed; - } while ((((rolledPlayerType == 0xc) || (rolledPlayerType == 0xb)) || (rolledPlayerType == 0x11)) - || (rolledPlayerType == 0x14)); - if (rng._seed == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - rng._seed = GHIDRA_UINT(rng._seed) >> 10 ^ rng._seed; - rng._seed = rng._seed << 9 ^ rng._seed; - rng._seed = GHIDRA_UINT(rng._seed) >> 0x15 ^ rng._seed; - switch(rng._seed & 3) { - case 0: - (this->_params)._endStage = 6; - break; - case 1: - (this->_params)._endStage = 8; - break; - case 2: - (this->_params)._endStage = 10; - break; - case 3: - (this->_params)._endStage = 0xb; - } - if ((this->_params)._endStage < 10) { -LAB_00426bde: - iVar2 = 1; - } - else { - if (rng._seed == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - rng._seed = GHIDRA_UINT(rng._seed) >> 10 ^ rng._seed; - rng._seed = rng._seed << 9 ^ rng._seed; - rng._seed = GHIDRA_UINT(rng._seed) >> 0x15 ^ rng._seed; - if ((rng._seed & 1U) != 0) goto LAB_00426bde; - iVar2 = 0; - } - (this->_params)._pathType = iVar2; - (this->_params)._isMegaSatan = 0; - (this->_params)._difficulty = 0; - if ((date[0] & 2) != 0) { - dateTime = _mkgmtime64(&dateTm); - } - if ((date[0] & 3) != 0) { - tmResult = _gmtime64(&dateTime); - dateTm.tm_sec = tmResult->tm_sec; - dateTm.tm_min = tmResult->tm_min; - dateTm.tm_hour = tmResult->tm_hour; - dateTm.tm_mday = tmResult->tm_mday; - dateTm.tm_mon = tmResult->tm_mon; - dateTm.tm_year = tmResult->tm_year; - dateTm.tm_wday = tmResult->tm_wday; - dateTm.tm_yday = tmResult->tm_yday; - dateTm.tm_isdst = tmResult->tm_isdst; - } - date[0] = date[0] & 0xfc; - if ((char)dateTm.tm_wday == '\0') { - (this->_params)._endStage = 0xb; - (this->_params)._isMegaSatan = 1; - if (rng._seed == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - rng._seed = GHIDRA_UINT(rng._seed) >> ((uint8_t)rng._shift1 & 0x1f) ^ rng._seed; - rng._seed = rng._seed << ((uint8_t)rng._shift2 & 0x1f) ^ rng._seed; - rng._seed = GHIDRA_UINT(rng._seed) >> ((uint8_t)rng._shift3 & 0x1f) ^ rng._seed; - if (rng._seed != (GHIDRA_UINT(rng._seed) / 6) * 6) goto LAB_00427185; -LAB_0042717b: - (this->_params)._difficulty = 1; - goto LAB_00427185; - } - if ((char)dateTm.tm_wday == '\x01') { - (this->_params)._pathType = 2; - (this->_params)._endStage = 8; - goto LAB_00427185; - } - if ((char)dateTm.tm_wday == '\x02') { - switch((this->_params)._playerType) { - case 0: - (this->_params)._playerType = 0x15; - break; - case 1: - (this->_params)._playerType = 0x16; - break; - case 2: - (this->_params)._playerType = 0x17; - break; - case 3: - (this->_params)._playerType = 0x18; - break; - case 4: - (this->_params)._playerType = 0x19; - break; - case 5: - (this->_params)._playerType = 0x1a; - break; - case 6: - (this->_params)._playerType = 0x1b; - break; - case 7: - (this->_params)._playerType = 0x1c; - break; - case 8: - (this->_params)._playerType = 0x1d; - break; - case 9: - (this->_params)._playerType = 0x1e; - break; - case 10: - (this->_params)._playerType = 0x1f; - break; - default: - KAGE_LogMessage(8,(uint8_t *) - "GetTaintedId() could not find tainted counterpart to given ePlayerType (%d) \n" - ); - break; - case 0xd: - (this->_params)._playerType = 0x20; - break; - case 0xe: - (this->_params)._playerType = 0x21; - break; - case 0xf: - (this->_params)._playerType = 0x22; - break; - case 0x10: - (this->_params)._playerType = 0x23; - break; - case 0x12: - (this->_params)._playerType = 0x24; - break; - case 0x13: - (this->_params)._playerType = 0x25; - } - if (rng._seed == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - rng._seed = GHIDRA_UINT(rng._seed) >> ((uint8_t)rng._shift1 & 0x1f) ^ rng._seed; - rng._seed = rng._seed << ((uint8_t)rng._shift2 & 0x1f) ^ rng._seed; - rng._seed = GHIDRA_UINT(rng._seed) >> ((uint8_t)rng._shift3 & 0x1f) ^ rng._seed; - uVar3 = GHIDRA_UINT(rng._seed) % 100; - if (uVar3 < 0x14) { - (this->_params)._endStage = 6; - goto LAB_00427185; - } - if (uVar3 < 0x28) { - (this->_params)._endStage = 8; - goto LAB_00427185; - } - if (0x31 < uVar3) { - if (0x40 < uVar3) { - if (0x4f < uVar3) { - (this->_params)._endStage = 0xb; - (this->_params)._pathType = GHIDRA_UINT((0x59 < uVar3)); - goto LAB_00427185; - } - goto LAB_00426e6e; - } - goto LAB_00426e53; - } - } - else { - if ((char)dateTm.tm_wday == '\x03') { - (this->_params)._endStage = 0xc; - uVar3 = (GHIDRA_CAST((&rng)))->RNG::RandomInt(2); - (this->_params)._pathType = GHIDRA_UINT((uVar3 == 0)); - uVar3 = (GHIDRA_CAST((&rng)))->RNG::RandomInt(100); - if (GHIDRA_INT(uVar3) < 0x14) { - (this->_params)._endStage = 6; - goto LAB_00427185; - } - if (GHIDRA_INT(uVar3) < 0x28) { - (this->_params)._endStage = 8; - goto LAB_00427185; - } - } - else { - if ((char)dateTm.tm_wday == '\x04') { - (this->_params)._pathType = 3; - (this->_params)._endStage = 0xd; - goto LAB_00427185; - } - if ((char)dateTm.tm_wday != '\x05') { - if ((char)dateTm.tm_wday != '\x06') goto LAB_00427185; - uVar3 = (GHIDRA_CAST((&rng)))->RNG::RandomInt(100); - if (GHIDRA_INT(uVar3) < 0xf) { - (this->_params)._endStage = 6; - } - else if (GHIDRA_INT(uVar3) < 0x1e) { - (this->_params)._endStage = 8; - } - else if (GHIDRA_INT(uVar3) < 0x28) { - (this->_params)._endStage = 0xc; - uVar3 = (GHIDRA_CAST((&rng)))->RNG::RandomInt(2); - (this->_params)._pathType = GHIDRA_UINT((uVar3 == 0)); - } - else if (GHIDRA_INT(uVar3) < 0x32) { - (this->_params)._endStage = 10; - (this->_params)._pathType = 0; - } - else if (GHIDRA_INT(uVar3) < 0x3c) { - (this->_params)._endStage = 10; - (this->_params)._pathType = 1; - } - else if (GHIDRA_INT(uVar3) < 0x46) { - (this->_params)._endStage = 0xb; - (this->_params)._pathType = 0; - } - else if (GHIDRA_INT(uVar3) < 0x50) { - (this->_params)._endStage = 0xb; - (this->_params)._pathType = 1; - } - else if (GHIDRA_INT(uVar3) < 0x5a) { - (this->_params)._pathType = 3; - (this->_params)._endStage = 0xd; - } - uVar3 = (GHIDRA_CAST((&rng)))->RNG::RandomInt(2); - if (uVar3 != 0) { - switch((this->_params)._playerType) { - case 0: - (this->_params)._playerType = 0x15; - break; - case 1: - (this->_params)._playerType = 0x16; - break; - case 2: - (this->_params)._playerType = 0x17; - break; - case 3: - (this->_params)._playerType = 0x18; - break; - case 4: - (this->_params)._playerType = 0x19; - break; - case 5: - (this->_params)._playerType = 0x1a; - break; - case 6: - (this->_params)._playerType = 0x1b; - break; - case 7: - (this->_params)._playerType = 0x1c; - break; - case 8: - (this->_params)._playerType = 0x1d; - break; - case 9: - (this->_params)._playerType = 0x1e; - break; - case 10: - (this->_params)._playerType = 0x1f; - break; - default: - KAGE_LogMessage(8,(uint8_t *) - "GetTaintedId() could not find tainted counterpart to given ePlayerType (%d) \n" - ); - break; - case 0xd: - (this->_params)._playerType = 0x20; - break; - case 0xe: - (this->_params)._playerType = 0x21; - break; - case 0xf: - (this->_params)._playerType = 0x22; - break; - case 0x10: - (this->_params)._playerType = 0x23; - break; - case 0x12: - (this->_params)._playerType = 0x24; - break; - case 0x13: - (this->_params)._playerType = 0x25; - } - } - uVar3 = (GHIDRA_CAST((&rng)))->RNG::RandomInt(2); - if (uVar3 == 0) goto LAB_00427185; - goto LAB_0042717b; - } - (this->_params)._difficulty = 1; - uVar3 = (GHIDRA_CAST((&rng)))->RNG::RandomInt(100); - if (GHIDRA_INT(uVar3) < 0x14) { - (this->_params)._endStage = 6; - goto LAB_00427185; - } - if (GHIDRA_INT(uVar3) < 0x28) { - (this->_params)._endStage = 8; - goto LAB_00427185; - } - } - if (0x31 < GHIDRA_INT(uVar3)) { - if (0x40 < GHIDRA_INT(uVar3)) { - if (0x4f < GHIDRA_INT(uVar3)) { - (this->_params)._endStage = 0xb; - (this->_params)._pathType = GHIDRA_UINT((0x59 < GHIDRA_INT(uVar3))); - goto LAB_00427185; - } -LAB_00426e6e: - (this->_params)._endStage = 10; - (this->_params)._pathType = 1; - goto LAB_00427185; - } -LAB_00426e53: - (this->_params)._endStage = 10; - (this->_params)._pathType = 0; - goto LAB_00427185; - } - } - (this->_params)._endStage = 0xc; - uVar3 = (GHIDRA_CAST((&rng)))->RNG::RandomInt(2); - (this->_params)._pathType = GHIDRA_UINT((uVar3 == 0)); -LAB_00427185: - if (rng._seed == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - uVar3 = GHIDRA_UINT(rng._seed) >> ((uint8_t)rng._shift1 & 0x1f) ^ rng._seed; - uVar3 = uVar3 << ((uint8_t)rng._shift2 & 0x1f) ^ uVar3; - this->_seed = uVar3 >> ((uint8_t)rng._shift3 & 0x1f) ^ uVar3; - FUN_00427290(this->_specialDailyId); - return; -} diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index 2c7602c..b7b7392 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -104,79 +104,6 @@ LAB_00499c40: goto LAB_00499ba3; } -// 0049f870 -void NpcHelper::chimera_charge_begin(Entity_NPC *npc, Vector *target, float speed) -{ - uint8_t bVar1; - uint8_t *currentName; - uint32_t compareResult; - char *chargeBeginName; - bool isLess; - float length; - float dirX; - float local_c; - float local_8; - uint8_t *animData; - Manager *manager; - - animData = (npc->_sprite)._animState._animData; - if (animData != GHIDRA_CAST(0x0)) { - currentName = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - currentName = *GHIDRA_CAST(animData); - } - chargeBeginName = "ChargeBegin"; - do { - bVar1 = *currentName; - isLess = bVar1 < (uint8_t)*chargeBeginName; - if (bVar1 != *chargeBeginName) { -LAB_0049f8b6: - compareResult = -GHIDRA_UINT(isLess) | 1; - goto LAB_0049f8bb; - } - if (bVar1 == 0) break; - bVar1 = currentName[1]; - isLess = bVar1 < (uint8_t)chargeBeginName[1]; - if (bVar1 != chargeBeginName[1]) goto LAB_0049f8b6; - currentName = currentName + 2; - chargeBeginName = chargeBeginName + 2; - } while (bVar1 != 0); - compareResult = 0; -LAB_0049f8bb: - if ((compareResult == 0) && - ((animData[0x34] == 0 || ((npc->_sprite)._animState._isPlaying != 0)))) goto LAB_0049f8ee; - } - bVar1 = ANM2::SetAnimation(&npc->_sprite,GHIDRA_CAST("ChargeBegin"),1); - if (bVar1 != 0) { - AnimationState::Rewind(&(npc->_sprite)._animState); - (npc->_sprite)._animState._isPlaying = 1; - } -LAB_0049f8ee: - npc->_state = 10; - manager = g_manager; - local_8 = 1.0; - if (npc->_championColorIdx == 0x12) { - local_8 = 1.5; - } - else if (npc->_championColorIdx == 0x13) { - local_8 = 0.5; - } - local_c = 4.21791e-43; - seed_fart_sound_override(GHIDRA_CAST(&local_c)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_c),1.0,2,0,local_8,0.0); - dirX = target->x - (npc->_pos).x; - local_c = target->y - (npc->_pos).y; - length = sqrtf(dirX * dirX + local_c * local_c); - if (0.0 < length) { - dirX = dirX * (1.0 / length); - local_c = local_c * (1.0 / length); - } - *GHIDRA_CAST(&npc->_i1) = 0; - (npc->_targetPosition).x = dirX * speed; - (npc->_targetPosition).y = local_c * speed; - return; -} - // 0055d070 uint8_t NpcHelper::polty_target_set(int gridIndex) { @@ -282,483 +209,6 @@ void NpcHelper::mother_set_collision_class(Entity_NPC *npc, int collisionClass) return; } -// 00572a70 -Entity * NpcHelper::clutch_find_farthest_orbital(Entity_NPC *clutch, int unused) -{ - uint64_t qVar1; - uint8_t isClutchFriendly; - int enemiesData; - uint64_t *heapAllocatedBytes; - uint8_t extraout_DL; - Entity *tmpEntity; - uint32_t uVar2; - float fVar3; - float deltaX; - EntityList_EL local_38; - uint32_t local_24; - float maxDistance; - Entity *local_18; - void *local_10; - uint8_t *puStack_c; - uint32_t uStack_8; - - uStack_8 = 0xffffffff; - puStack_c = &LAB_00af1840; - local_10 = ExceptionList; - ExceptionList = &local_10; - local_18 = GHIDRA_CAST(0x0); - maxDistance = 0.0; - EntityList::QuerySublist(GHIDRA_CAST((GHIDRA_INT(g_game->_room) + 0x1218)),&local_38,0x379,-1,-1,0,0); - uVar2 = 0; - tmpEntity = GHIDRA_CAST(0x0); - if (local_38._size != 0) { - enemiesData = (*GHIDRA_CAST((GHIDRA_CAST(&(local_38)) + 0x4))); - do { - tmpEntity = *GHIDRA_CAST((enemiesData + uVar2 * 4)); - if (tmpEntity != GHIDRA_CAST(0x0)) { - if (((1 < *GHIDRA_CAST(&g_game->_deathmatchManager)) && (tmpEntity->_type == 1)) || - (tmpEntity->_type - 10U < 0x3de)) { - local_24 = *GHIDRA_CAST((GHIDRA_INT(&tmpEntity->_flags) + 4)); - isClutchFriendly = Entity::IsFriendly(GHIDRA_CAST(clutch)); - if (((extraout_DL == isClutchFriendly) && (GHIDRA_CAST(tmpEntity->_parent) == clutch)) && - ((tmpEntity != GHIDRA_CAST(clutch->_child) && - ((tmpEntity[2]._updateTime != 1.38729e-43 && - (fVar3 = (clutch->_pos).y - (tmpEntity->_pos).y, - deltaX = (clutch->_pos).x - (tmpEntity->_pos).x, - fVar3 = sqrtf(fVar3 * fVar3 + deltaX * deltaX), (tmpEntity->_flags & 0x10) == 0)))))) - { - enemiesData = (*GHIDRA_CAST((GHIDRA_CAST(&(local_38)) + 0x4))); - if (maxDistance < fVar3) { - maxDistance = fVar3; - local_18 = tmpEntity; - } - goto LAB_00572bab; - } - } - enemiesData = (*GHIDRA_CAST((GHIDRA_CAST(&(local_38)) + 0x4))); - } -LAB_00572bab: - uVar2 = uVar2 + 1; - tmpEntity = local_18; - } while (uVar2 < GHIDRA_UINT(local_38._size)); - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(local_38)) + 0x0))) == '\0') { - if (g_mainHeap == (void *)0x0) { - heapAllocatedBytes = &g_allocatedBytesNoHeap; - } - else { - heapAllocatedBytes = GHIDRA_CAST((GHIDRA_INT(g_mainHeap) + 0x30)); - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(local_38)) + 0x4))) != 0) { - uVar2 = *GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(local_38)) + 0x4))) + -4)); - qVar1 = *heapAllocatedBytes; - *GHIDRA_CAST(heapAllocatedBytes) = GHIDRA_UINT(*heapAllocatedBytes) - uVar2; - *GHIDRA_CAST((GHIDRA_CAST(heapAllocatedBytes) + 4)) = - *GHIDRA_CAST((GHIDRA_CAST(heapAllocatedBytes) + 4)) - GHIDRA_UINT((GHIDRA_UINT(qVar1) < uVar2)); - free(GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(local_38)) + 0x4))) + -4))); - } - } - ExceptionList = local_10; - return tmpEntity; -} - -// 00572cc0 -void NpcHelper::clutch_spawn_fire(Entity_NPC *npc, Entity *target) -{ - uint32_t uVar1; - float fVar2; - float fVar3; - uint8_t bVar4; - uint32_t uVar5; - Entity *fire; - uint8_t *pbVar6; - LayerState *layer; - uint32_t angleRoll; - char *pcVar7; - uint8_t *size; - bool bVar8; - float fVar9; - Vector spawnPos; - Vector local_64; - ANM2 *local_5c; - Entity *local_58; - Entity_NPC *local_54; - Entity *local_50; - uint8_t local_4c [32]; - int animPathSize; - uint8_t *animPathCapacity; - uint32_t local_24; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - code *addFlagsFn; - ANM2 *fireSprite; - uint32_t *parentSlot; - - puStack_20 = local_4c + 0x48; - local_14 = 0xffffffff; - puStack_18 = &LAB_00af506d; - local_1c = ExceptionList; - uVar5 = __security_cookie ^ GHIDRA_UINT((local_4c + 0x3c)); - ExceptionList = &local_1c; - local_58 = target; - uVar1 = *GHIDRA_CAST((GHIDRA_INT(&target->_flags) + 4)); - *GHIDRA_CAST(&target->_flags) = GHIDRA_UINT(target->_flags) | 0x10; - *GHIDRA_CAST((GHIDRA_INT(&target->_flags) + 4)) = uVar1; - addFlagsFn = *(code **)(*GHIDRA_CAST(target) + 0x24); - local_54 = npc; - local_24 = uVar5; - EntityRef::constructor(GHIDRA_CAST(local_4c),GHIDRA_CAST(npc)); - (*addFlagsFn)(local_4c,uVar5); - uVar5 = Random(); - local_64.x = (local_58->_pos).x; - local_64.y = (local_58->_pos).y; - fire = Game::Spawn(g_game,0x21,0xd,&local_64,&g_vectorZero,GHIDRA_CAST(npc),0,uVar5); - animPathSize = 0; - fireSprite = &fire->_sprite; - animPathCapacity = &DAT_0000000f; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_4c)) + 0x10))) = 0.0; - local_5c = fireSprite; - local_50 = fire; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_4c)) + 0x10))) = msvc::_Allocate(0x30); - animPathSize = 0x20; - animPathCapacity = &DAT_0000002f; - builtin_strncpy((*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_4c))) + 0x10))),"gfx/009.002_Fire Projectile.anm2",0x21); - local_14 = 0; - ANM2::Load(fireSprite,GHIDRA_CAST((local_4c + 0x10)),1); - local_14 = 0xffffffff; - if (&DAT_0000000f < animPathCapacity) { - size = animPathCapacity + 1; - pcVar7 = (*GHIDRA_CAST((GHIDRA_CAST(&(GHIDRA_CAST(local_4c))) + 0x10))); - if (GHIDRA_CAST(0xfff) < size) { - pcVar7 = *GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(local_4c)) + 0x10))) + -4)); - size = animPathCapacity + 0x24; - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(local_4c)) + 0x10))) + (-4 - GHIDRA_INT(pcVar7))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pcVar7,GHIDRA_UINT(size)); - } - pbVar6 = (fire->_sprite)._animState._animData; - if (pbVar6 != GHIDRA_CAST(0x0)) { - if (0xf < *GHIDRA_CAST((pbVar6 + 0x14))) { - pbVar6 = *GHIDRA_CAST(pbVar6); - } - pcVar7 = "Flickering"; - do { - bVar4 = *pbVar6; - bVar8 = bVar4 < (uint8_t)*pcVar7; - if (bVar4 != *pcVar7) { -LAB_00572e46: - uVar5 = -GHIDRA_UINT(bVar8) | 1; - goto LAB_00572e4b; - } - if (bVar4 == 0) break; - bVar4 = pbVar6[1]; - bVar8 = bVar4 < (uint8_t)pcVar7[1]; - if (bVar4 != pcVar7[1]) goto LAB_00572e46; - pbVar6 = pbVar6 + 2; - pcVar7 = pcVar7 + 2; - } while (bVar4 != 0); - uVar5 = 0; -LAB_00572e4b: - if ((uVar5 == 0) && - ((*GHIDRA_CAST((GHIDRA_INT((fire->_sprite)._animState._animData) + 0x34)) == '\0' || - ((fire->_sprite)._animState._isPlaying != 0)))) goto LAB_00572e7c; - } - bVar4 = ANM2::SetAnimation(fireSprite,GHIDRA_CAST("Flickering"),1); - if (bVar4 != 0) { - AnimationState::Rewind(&(fire->_sprite)._animState); - (fire->_sprite)._animState._isPlaying = 1; - } -LAB_00572e7c: - fireSprite = local_5c; - pbVar6 = GHIDRA_CAST(0x0); - if ((local_50->_sprite)._layerCount != 0) { - do { - layer = ANM2::GetLayer(fireSprite,pbVar6); - fVar3 = fRam00c34e34; - fVar2 = fRam00c34e30; - fVar9 = fRam00c34e2c; - if (&layer->_color != GHIDRA_CAST(&DAT_00c34e28)) { - (layer->_color)._tint[0] = _DAT_00c34e28; - (layer->_color)._tint[1] = fVar9; - (layer->_color)._tint[2] = fVar2; - (layer->_color)._tint[3] = fVar3; - fVar3 = fRam00c34e44; - fVar2 = fRam00c34e40; - fVar9 = fRam00c34e3c; - (layer->_color)._colorize[0] = _DAT_00c34e38; - (layer->_color)._colorize[1] = fVar9; - (layer->_color)._colorize[2] = fVar2; - (layer->_color)._colorize[3] = fVar3; - *GHIDRA_CAST((layer->_color)._offset) = DAT_00c34e48; - (layer->_color)._offset[2] = DAT_00c34e50; - } - pbVar6 = pbVar6 + 1; - } while (pbVar6 < GHIDRA_CAST((local_50->_sprite)._layerCount)); - npc = local_54; - } - (**(code **)(*GHIDRA_CAST(local_50) + 0xc))(); - local_50 = GHIDRA_CAST(0x2); - do { - uVar5 = Random(); - local_54 = GHIDRA_CAST((local_58->_pos).x); - local_64.y = (local_58->_pos).y; - angleRoll = Random(); - fVar9 = (float)((double)GHIDRA_INT(angleRoll) + __uint_to_double_fixup[-(GHIDRA_INT(angleRoll) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - local_5c = GHIDRA_CAST((fVar9 + fVar9)); - fVar9 = cos((float)local_5c); - spawnPos.x = fVar9 * 10.0 + (float)local_54; - fVar9 = sin((float)local_5c); - spawnPos.y = fVar9 * 10.0 + local_64.y; - local_54 = (Entity_NPC *) - Game::Spawn(g_game,0x399,1,&spawnPos,&g_vectorZero,GHIDRA_CAST(npc),0,uVar5); - parentSlot = &local_54->_parent; - if (local_54->_parent != 0) { - local_64.y = (float)parentSlot; - msvc::multiset::erase(&local_64.y); - } - *parentSlot = npc; - if (npc != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(parentSlot); - } - uVar5 = Random(); - local_50 = GHIDRA_CAST((GHIDRA_INT(local_50) + -1)); - (local_54->_v1).x = - (float)((double)GHIDRA_INT(uVar5) + __uint_to_double_fixup[-(GHIDRA_INT(uVar5) >> 0x1f)]) * 2.3283064e-10 - * 360.0; - } while (local_50 != GHIDRA_CAST(0x0)); - ExceptionList = local_1c; - return; -} - -// 00575a10 -void NpcHelper::clutch_render(Entity_NPC *npc, Vector *offset) -{ - LayerState *pLVar1; - float *pfVar2; - int iVar3; - int iVar4; - int iVar5; - void *layerFrames; - int pointSlotOffset; - int iVar6; - void *animData; - int pointIndex; - uint32_t pointBlock; - uint32_t nextPointBlock; - float *nextPoint; - float flipSign; - float deltaX; - float fVar7; - double dVar8; - double dVar9; - int layerOffset; - uint32_t nextPointIndex; - uint8_t *layerId; - float segmentStretch; - Vector segmentPos [8]; - ANM2 *animation; - int *pointDeque; - - if (npc->_variant == 0) { - pLVar1 = ANM2::GetLayer(&npc->_sprite,GHIDRA_CAST(0x1)); - if ((0.0 < (pLVar1->_color)._tint[3]) && ((npc->_vectorDeque1)._size != 0)) { - pLVar1 = ANM2::GetLayer(&npc->_sprite,GHIDRA_CAST(0x1)); - pLVar1->_visible = 1; - pLVar1 = ANM2::GetLayer(&npc->_sprite,GHIDRA_CAST(0x2)); - layerId = GHIDRA_CAST(0x1); - layerOffset = 0x3c; - pLVar1->_visible = 1; - pointBlock = (npc->_vectorDeque1)._offset; - do { - pointDeque = (npc->_vectorDeque1)._proxy; - nextPointIndex = pointBlock + 3; - pointIndex = pointBlock; - while( true ) { - pointBlock = (npc->_vectorDeque1)._offset; - if (((npc->_vectorDeque1)._size - 3) + pointBlock <= GHIDRA_UINT(pointIndex)) break; - if (pointDeque == GHIDRA_CAST(0x0)) { - iVar3 = 0; - } - else { - iVar3 = *pointDeque; - } - pointBlock = GHIDRA_UINT(pointIndex) >> 1; - pointSlotOffset = (pointIndex & 1U) * 8; - pfVar2 = GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((iVar3 + 4)) + - (*GHIDRA_CAST((iVar3 + 8)) - 1U & pointBlock) * 4)) + pointSlotOffset)) - ; - if (pointDeque == GHIDRA_CAST(0x0)) { - iVar3 = 0; - } - else { - iVar3 = *pointDeque; - } - nextPointBlock = nextPointIndex >> 1; - fVar7 = g_displayPixelRatio * g_screenPointScale; - iVar6 = (nextPointIndex & 1) * 8; - nextPoint = GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((iVar3 + 4)) + - (*GHIDRA_CAST((iVar3 + 8)) - 1U & nextPointBlock) * 4)) + iVar6)); - dVar8 = floor((double)((((*pfVar2 + *nextPoint) * 0.5 - 60.0) * 0.65 + - (g_screenWidth - 338.0) * 0.5) * fVar7 + 0.5)); - dVar9 = floor((double)((((pfVar2[1] + nextPoint[1]) * 0.5 - 140.0) * 0.65 + - (g_screenHeight - 182.0) * 0.5) * fVar7 + 0.5)); - segmentPos[0].x = (float)dVar8 / fVar7 + offset->x; - segmentPos[0].y = (float)dVar9 / fVar7 + offset->y; - if (pointDeque == GHIDRA_CAST(0x0)) { - iVar3 = 0; - } - else { - iVar3 = *pointDeque; - } - if (pointDeque == GHIDRA_CAST(0x0)) { - iVar5 = 0; - } - else { - iVar5 = *pointDeque; - } - iVar3 = GHIDRA_INT((8.0 - (*GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((iVar5 + 4)) + - (nextPointIndex + 2 >> 1 & - *GHIDRA_CAST((iVar5 + 8)) - 1U) * 4)) + - (nextPointIndex + 2 & 1) * 8)) + - *GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((iVar3 + 4)) + - (nextPointIndex - 1 >> 1 & *GHIDRA_CAST((iVar3 + 8)) - 1U - ) * 4)) + (nextPointIndex + 1 & 1) * 8))) * 0.5 * 8.0 - )); - if (iVar3 == 7) { - segmentStretch = 1.0; -LAB_00575d73: - pLVar1 = ANM2::GetLayer(&npc->_sprite,layerId); - (pLVar1->_size).x = segmentStretch; - (pLVar1->_size).y = 1.0; - if ((npc->_sprite)._flipX == 0) { - flipSign = 1.0; - } - else { - flipSign = (float)&DAT_bf800000; - } - if (pointDeque == GHIDRA_CAST(0x0)) { - iVar5 = 0; - } - else { - iVar5 = *pointDeque; - } - pfVar2 = GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((iVar5 + 4)) + - (*GHIDRA_CAST((iVar5 + 8)) - 1U & nextPointBlock) * 4)) + iVar6)); - if (pointDeque == GHIDRA_CAST(0x0)) { - iVar6 = 0; - } - else { - iVar6 = *pointDeque; - } - iVar6 = *GHIDRA_CAST((*GHIDRA_CAST((iVar6 + 4)) + (*GHIDRA_CAST((iVar6 + 8)) - 1U & pointBlock) * 4)); - fVar7 = atan2f(pfVar2[1] - *GHIDRA_CAST((iVar6 + 4 + pointSlotOffset)), - *pfVar2 - *GHIDRA_CAST((iVar6 + pointSlotOffset))); - pLVar1 = ANM2::GetLayer(&npc->_sprite,layerId); - pLVar1->_rotation = fVar7 * 57.295776 * flipSign; - if ((npc->_sprite)._overlayAnimState._animData != (void *)0x0) { - AnimationState::SetFrameFloat(&(npc->_sprite)._overlayAnimState,(float)iVar3); - } - if ((npc->_sprite)._loaded != 0) { - if ((npc->_sprite)._overlayRenderFirst == 0) { - animData = (npc->_sprite)._animState._animData; - if (((animData != (void *)0x0) && - (animation = (npc->_sprite)._animState._animation, - GHIDRA_INT(layerId) < animation->_layerCount)) && - (iVar3 = *GHIDRA_CAST((layerOffset + GHIDRA_INT(animData))), -1 < iVar3)) { - AnimationLayer::RenderFrame - (GHIDRA_CAST((iVar3 * 0x10 + *GHIDRA_CAST((GHIDRA_CAST(animData) + 0x18)))), - segmentPos, - *GHIDRA_CAST((GHIDRA_INT((npc->_sprite)._animState._layerFrames) + iVar3 * 4)), - &g_vectorZero,&g_vectorZero,animation); - } - animData = (npc->_sprite)._overlayAnimState._animData; - if (((animData != (void *)0x0) && - (animation = (npc->_sprite)._overlayAnimState._animation, - GHIDRA_INT(layerId) < animation->_layerCount)) && - (iVar3 = *GHIDRA_CAST((layerOffset + GHIDRA_INT(animData))), -1 < iVar3)) { - layerFrames = (npc->_sprite)._overlayAnimState._layerFrames; - goto LAB_00575ed0; - } - } - else { - animData = (npc->_sprite)._overlayAnimState._animData; - if (((animData != (void *)0x0) && - (animation = (npc->_sprite)._overlayAnimState._animation, - GHIDRA_INT(layerId) < animation->_layerCount)) && - (iVar3 = *GHIDRA_CAST((layerOffset + GHIDRA_INT(animData))), -1 < iVar3)) { - AnimationLayer::RenderFrame - (GHIDRA_CAST((iVar3 * 0x10 + *GHIDRA_CAST((GHIDRA_CAST(animData) + 0x18)))), - segmentPos, - *GHIDRA_CAST((GHIDRA_INT((npc->_sprite)._overlayAnimState._layerFrames) + iVar3 * 4 - )),&g_vectorZero,&g_vectorZero,animation); - } - animData = (npc->_sprite)._animState._animData; - if (((animData != (void *)0x0) && - (animation = (npc->_sprite)._animState._animation, - GHIDRA_INT(layerId) < animation->_layerCount)) && - (iVar3 = *GHIDRA_CAST((layerOffset + GHIDRA_INT(animData))), -1 < iVar3)) { - layerFrames = (npc->_sprite)._animState._layerFrames; -LAB_00575ed0: - AnimationLayer::RenderFrame - (GHIDRA_CAST((iVar3 * 0x10 + *GHIDRA_CAST((GHIDRA_CAST(animData) + 0x18)))), - segmentPos,*GHIDRA_CAST((GHIDRA_CAST(layerFrames) + iVar3 * 4)),&g_vectorZero, - &g_vectorZero,animation); - } - } - } - pointIndex = pointIndex + 3; - nextPointIndex = nextPointIndex + 3; - } - else { - if (pointDeque == GHIDRA_CAST(0x0)) { - iVar5 = 0; - } - else { - iVar5 = *pointDeque; - } - iVar5 = *GHIDRA_CAST((*GHIDRA_CAST((iVar5 + 4)) + (*GHIDRA_CAST((iVar5 + 8)) - 1U & pointBlock) * 4)); - if (pointDeque == GHIDRA_CAST(0x0)) { - iVar4 = 0; - } - else { - iVar4 = *pointDeque; - } - pfVar2 = GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((iVar4 + 4)) + - (*GHIDRA_CAST((iVar4 + 8)) - 1U & nextPointBlock) * 4)) + iVar6)); - fVar7 = pfVar2[1] - *GHIDRA_CAST((iVar5 + 4 + pointSlotOffset)); - deltaX = *pfVar2 - *GHIDRA_CAST((iVar5 + pointSlotOffset)); - fVar7 = sqrtf(fVar7 * fVar7 + deltaX * deltaX); - segmentStretch = (fVar7 * 0.5) / (float)(8 - iVar3); - if (segmentStretch <= 1.0) { - segmentStretch = 1.0; - } - if (3.0 <= segmentStretch) { - segmentStretch = 3.0; - } - if (iVar3 < 8) goto LAB_00575d73; - pointIndex = pointIndex + 3; - nextPointIndex = nextPointIndex + 3; - } - } - layerId = layerId + 1; - layerOffset = layerOffset + 4; - } while (layerOffset < 0x41); - pLVar1 = ANM2::GetLayer(&npc->_sprite,GHIDRA_CAST(0x1)); - pLVar1->_visible = 0; - pLVar1 = ANM2::GetLayer(&npc->_sprite,GHIDRA_CAST(0x2)); - pLVar1->_visible = 0; - } - } - Entity::Render(GHIDRA_CAST(npc),offset); - return; -} - // 00582f60 void NpcHelper::scourge_whip(Entity_NPC *npc) { diff --git a/generated-src/rich_text_span.cpp b/generated-src/rich_text_span.cpp deleted file mode 100644 index 40e724b..0000000 --- a/generated-src/rich_text_span.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "classes.h" - -// 009ef9a0 -uint8_t RichTextSpan::try_merge(void *other) -{ - int *ownStyle; - int *otherStyle; - uint32_t bytesLeft; - bool isMore; - uint32_t *otherLength; - - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x34)) == *GHIDRA_CAST((GHIDRA_CAST(other) + 0x34))) { - otherStyle = GHIDRA_CAST((GHIDRA_INT(other) + 0x20)); - bytesLeft = 0xc; - ownStyle = GHIDRA_CAST((GHIDRA_INT(this) + 0x20)); - do { - if (*ownStyle != *otherStyle) { - return 0; - } - ownStyle = ownStyle + 1; - otherStyle = otherStyle + 1; - isMore = 3 < bytesLeft; - bytesLeft = bytesLeft - 4; - } while (isMore); - if ((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x38)) == *GHIDRA_CAST((GHIDRA_CAST(other) + 0x38))) && - (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x3c)) == *GHIDRA_CAST((GHIDRA_CAST(other) + 0x3c)))) { - otherLength = GHIDRA_CAST((GHIDRA_INT(other) + 0x10)); - if (0xf < *GHIDRA_CAST((GHIDRA_CAST(other) + 0x14))) { - other = *(void **)other; - } - this->msvc::string::append(other,*otherLength); - return 1; - } - } - return 0; -} - -// 009f1ef0 -void RichTextSpan::move_construct(void *dest, void *source) -{ - uint32_t uVar1; - uint32_t uVar2; - uint32_t uVar3; - - *GHIDRA_CAST(dest) = 0; - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x10)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x14)) = 0; - uVar1 = *GHIDRA_CAST((GHIDRA_CAST(source) + 4)); - uVar2 = *GHIDRA_CAST((GHIDRA_CAST(source) + 8)); - uVar3 = *GHIDRA_CAST((GHIDRA_CAST(source) + 0xc)); - *GHIDRA_CAST(dest) = *GHIDRA_CAST(source); - *GHIDRA_CAST((GHIDRA_CAST(dest) + 4)) = uVar1; - *GHIDRA_CAST((GHIDRA_CAST(dest) + 8)) = uVar2; - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0xc)) = uVar3; - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x10)) = *GHIDRA_CAST((GHIDRA_CAST(source) + 0x10)); - *GHIDRA_CAST((GHIDRA_CAST(source) + 0x10)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(source) + 0x14)) = 0xf; - *GHIDRA_CAST(source) = 0; - uVar1 = *GHIDRA_CAST((GHIDRA_CAST(source) + 0x1c)); - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x18)) = *GHIDRA_CAST((GHIDRA_CAST(source) + 0x18)); - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x1c)) = uVar1; - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x20)) = *GHIDRA_CAST((GHIDRA_CAST(source) + 0x20)); - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x24)) = *GHIDRA_CAST((GHIDRA_CAST(source) + 0x24)); - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x28)) = *GHIDRA_CAST((GHIDRA_CAST(source) + 0x28)); - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x2c)) = *GHIDRA_CAST((GHIDRA_CAST(source) + 0x2c)); - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x30)) = *GHIDRA_CAST((GHIDRA_CAST(source) + 0x30)); - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x34)) = *GHIDRA_CAST((GHIDRA_CAST(source) + 0x34)); - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x38)) = *GHIDRA_CAST((GHIDRA_CAST(source) + 0x38)); - *GHIDRA_CAST((GHIDRA_CAST(dest) + 0x3c)) = *GHIDRA_CAST((GHIDRA_CAST(source) + 0x3c)); - return; -} diff --git a/generated-src/stats_panel.cpp b/generated-src/stats_panel.cpp deleted file mode 100644 index 3e81197..0000000 --- a/generated-src/stats_panel.cpp +++ /dev/null @@ -1,343 +0,0 @@ -#include "classes.h" - -// 0084dc00 -void StatsPanel::add_stat_line() -{ - char *format; - void **formattedString; - int in_ECX; - uint8_t *textEnd; - void *pvVar1; - uint32_t allocSize; - float in_XMM1_Da; - void *entry; - void *pvStack_1bc; - void *pvStack_1b8; - void *pvStack_1b4; - uint64_t local_1b0; - uint8_t local_1a8 [12]; - uint8_t local_19c [12]; - uint8_t local_190 [12]; - uint8_t local_184 [12]; - uint8_t local_178 [12]; - uint8_t local_16c [20]; - void *local_158; - uint32_t local_148; - uint32_t local_144; - void *textString [4]; - uint32_t local_130; - uint32_t local_12c; - uint8_t text [260]; - uint32_t local_24; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - uint8_t ch; - - puStack_20 = text + 0x124; - local_14 = 0xffffffff; - puStack_18 = &LAB_00b02fbb; - local_1c = ExceptionList; - local_24 = __security_cookie ^ GHIDRA_UINT((text + 0x118)); - ExceptionList = &local_1c; - if (in_XMM1_Da != 0.0) { - format = "+%.2f"; - if (in_XMM1_Da < 0.0) { - format = "%.2f"; - } - sprintf_s(text,0x100,GHIDRA_CAST(format)); - InfoDisplayText::constructor(&entry); - local_14 = 0; - textEnd = text; - local_130 = 0; - local_12c = 0xf; - textString[0] = (void *)0x0; - do { - ch = *textEnd; - textEnd = textEnd + 1; - } while (ch != 0); - (GHIDRA_CAST((GHIDRA_CAST(textString))))->msvc::string::assign(text,GHIDRA_INT(textEnd) - GHIDRA_INT((text + 1))); - local_14 = CONCAT31((*GHIDRA_CAST((GHIDRA_CAST(&(local_14)) + 0x1))),1); - formattedString = (void **)FUN_00651d50(); - if (&entry != formattedString) { - (GHIDRA_CAST((GHIDRA_CAST(&entry))))->msvc::string::_Tidy_deallocate(); - entry = *formattedString; - pvStack_1bc = formattedString[1]; - pvStack_1b8 = formattedString[2]; - pvStack_1b4 = formattedString[3]; - local_1b0 = *GHIDRA_CAST((formattedString + 4)); - formattedString[4] = (void *)0x0; - formattedString[5] = (void *)0xf; - *GHIDRA_CAST(formattedString) = '\0'; - } - if (0xf < local_144) { - allocSize = local_144 + 1; - pvVar1 = local_158; - if (0xfff < allocSize) { - pvVar1 = *(void **)(GHIDRA_CAST(local_158) + -4); - allocSize = local_144 + 0x24; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(local_158) + (-4 - GHIDRA_INT(pvVar1))))) goto LAB_0084ddc1; - } - operator_delete(pvVar1,allocSize); - } - local_14 = local_14 & 0xffffff00; - local_148 = 0; - local_144 = 0xf; - local_158 = (void *)(GHIDRA_UINT(local_158) & 0xffffff00); - if (0xf < local_12c) { - allocSize = local_12c + 1; - pvVar1 = textString[0]; - if (0xfff < allocSize) { - pvVar1 = *(void **)(GHIDRA_INT(textString[0]) + -4); - allocSize = local_12c + 0x24; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(textString[0]) + (-4 - GHIDRA_INT(pvVar1))))) { -LAB_0084ddc1: - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pvVar1,allocSize); - } - pvVar1 = *(void **)(in_ECX + 0x24); - if (pvVar1 == *(void **)(in_ECX + 0x28)) { - msvc::vector<104byte>::_Emplace_reallocate(pvVar1,&entry); - } - else { - InfoDisplayEntry::copy_constructor(pvVar1,&entry); - *GHIDRA_CAST((in_ECX + 0x24)) = *GHIDRA_CAST((in_ECX + 0x24)) + 0x68; - } - FID_conflict__Tidy(local_16c); - FID_conflict__Tidy(local_178); - FID_conflict__Tidy(local_184); - FID_conflict__Tidy(local_190); - FID_conflict__Tidy(local_19c); - FID_conflict__Tidy(local_1a8); - if (0xf < (*GHIDRA_CAST((GHIDRA_CAST(&(local_1b0)) + 0x4)))) { - allocSize = (*GHIDRA_CAST((GHIDRA_CAST(&(local_1b0)) + 0x4))) + 1; - pvVar1 = entry; - if (0xfff < allocSize) { - pvVar1 = *(void **)(GHIDRA_CAST(entry) + -4); - allocSize = (*GHIDRA_CAST((GHIDRA_CAST(&(local_1b0)) + 0x4))) + 0x24; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(entry) + (-4 - GHIDRA_INT(pvVar1))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pvVar1,allocSize); - } - } - ExceptionList = local_1c; - return; -} - -// 0084dea0 -void StatsPanel::set(Entity_Player *player, uint8_t isGoldenTrinket) -{ - uint32_t uVar1; - void *extraout_ECX; - void *extraout_ECX_00; - void *panel; - undefined3 in_stack_00000009; - std_string statName; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - - local_8 = 0xffffffff; - puStack_c = &LAB_00b03025; - local_10 = ExceptionList; - uVar1 = __security_cookie ^ GHIDRA_UINT(&(&statName)[1]._size); - ExceptionList = &local_10; - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) != 0) { - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x48)) = player; - if (*GHIDRA_CAST(this) == 0) { - preview_collectible(1); - panel = extraout_ECX; - } - else { - panel = this; - if (*GHIDRA_CAST(this) == 1) { - preview_trinket(1,_isGoldenTrinket); - panel = extraout_ECX_00; - } - } - FUN_00856840(panel,uVar1); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)) = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)); - statName._capacity = 0xf; - statName._size = 6; - builtin_strncpy(statName._buf," Speed",7); - local_8 = 0; - add_stat_line(&statName); - local_8 = 0xffffffff; - if (0xf < statName._capacity) { - uVar1 = statName._capacity + 1; - panel = (*GHIDRA_CAST((GHIDRA_CAST(&((void *)statName._buf)) + 0x0))); - if (0xfff < uVar1) { - panel = *(void **)((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) + -4); - uVar1 = statName._capacity + 0x24; - if (0x1f < ((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) - GHIDRA_INT(panel)) - 4U) goto LAB_0084e1d4; - } - operator_delete(panel,uVar1); - } - statName._capacity = 0xf; - statName._size = 6; - builtin_strncpy(statName._buf," Tears",7); - local_8 = 1; - add_stat_line(&statName); - local_8 = 0xffffffff; - if (0xf < statName._capacity) { - uVar1 = statName._capacity + 1; - panel = (*GHIDRA_CAST((GHIDRA_CAST(&((void *)statName._buf)) + 0x0))); - if (0xfff < uVar1) { - panel = *(void **)((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) + -4); - uVar1 = statName._capacity + 0x24; - if (0x1f < ((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) - GHIDRA_INT(panel)) - 4U) goto LAB_0084e1d4; - } - operator_delete(panel,uVar1); - } - statName._capacity = 0xf; - statName._size = 7; - builtin_strncpy(statName._buf," Damage",8); - local_8 = 2; - add_stat_line(&statName); - local_8 = 0xffffffff; - if (0xf < statName._capacity) { - uVar1 = statName._capacity + 1; - panel = (*GHIDRA_CAST((GHIDRA_CAST(&((void *)statName._buf)) + 0x0))); - if (0xfff < uVar1) { - panel = *(void **)((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) + -4); - uVar1 = statName._capacity + 0x24; - if (0x1f < ((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) - GHIDRA_INT(panel)) - 4U) goto LAB_0084e1d4; - } - operator_delete(panel,uVar1); - } - statName._capacity = 0xf; - statName._size = 6; - builtin_strncpy(statName._buf," Range",7); - local_8 = 3; - add_stat_line(&statName); - local_8 = 0xffffffff; - if (0xf < statName._capacity) { - uVar1 = statName._capacity + 1; - panel = (*GHIDRA_CAST((GHIDRA_CAST(&((void *)statName._buf)) + 0x0))); - if (0xfff < uVar1) { - panel = *(void **)((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) + -4); - uVar1 = statName._capacity + 0x24; - if (0x1f < ((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) - GHIDRA_INT(panel)) - 4U) goto LAB_0084e1d4; - } - operator_delete(panel,uVar1); - } - builtin_strncpy(statName._buf + 8,"eed",4); - statName._capacity = 0xf; - statName._size = 0xb; - builtin_strncpy(statName._buf," Shot Sp",8); - local_8 = 4; - add_stat_line(&statName); - local_8 = 0xffffffff; - if (0xf < statName._capacity) { - uVar1 = statName._capacity + 1; - panel = (*GHIDRA_CAST((GHIDRA_CAST(&((void *)statName._buf)) + 0x0))); - if (0xfff < uVar1) { - panel = *(void **)((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) + -4); - uVar1 = statName._capacity + 0x24; - if (0x1f < ((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) - GHIDRA_INT(panel)) - 4U) goto LAB_0084e1d4; - } - operator_delete(panel,uVar1); - } - statName._capacity = 0xf; - statName._size = 5; - builtin_strncpy(statName._buf," Luck",6); - local_8 = 5; - add_stat_line(&statName); - if (0xf < statName._capacity) { - uVar1 = statName._capacity + 1; - panel = (*GHIDRA_CAST((GHIDRA_CAST(&((void *)statName._buf)) + 0x0))); - if (0xfff < uVar1) { - panel = *(void **)((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) + -4); - uVar1 = statName._capacity + 0x24; - if (0x1f < ((*GHIDRA_CAST((GHIDRA_CAST(&(statName._buf)) + 0x0))) - GHIDRA_INT(panel)) - 4U) { -LAB_0084e1d4: - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(panel,uVar1); - } - } - ExceptionList = local_10; - return; -} - -// 0084e9d0 -void StatsPanel::snapshot_stats(uint32_t param_1) -{ - int in_ECX; - - if (*GHIDRA_CAST((in_ECX + 0x48)) != 0) { - StatTracker::set(param_1); - StatTracker::set(param_1); - StatTracker::set(param_1); - StatTracker::set(param_1); - StatTracker::set(param_1); - StatTracker::set(param_1); - } - return; -} - -// 0084ea90 -void StatsPanel::preview_collectible(uint8_t param_1) -{ - uint32_t *puVar1; - int iVar2; - int in_ECX; - - if (*GHIDRA_CAST((in_ECX + 0x48)) != 0) { - snapshot_stats(0); - iVar2 = *GHIDRA_CAST((in_ECX + 0x48)); - *GHIDRA_CAST((iVar2 + 0x2ef4)) = *GHIDRA_CAST((in_ECX + 4)); - *GHIDRA_CAST((iVar2 + 0x2ef0)) = param_1; - puVar1 = GHIDRA_CAST((*GHIDRA_CAST((in_ECX + 0x48)) + 0x1574)); - *puVar1 = *puVar1 | 0x41f; - Entity_Player::EvaluateItems(*GHIDRA_CAST((in_ECX + 0x48))); - snapshot_stats(1); - iVar2 = *GHIDRA_CAST((in_ECX + 0x48)); - *GHIDRA_CAST((iVar2 + 0x2ef4)) = 0; - *GHIDRA_CAST((iVar2 + 0x2ef0)) = 1; - puVar1 = GHIDRA_CAST((*GHIDRA_CAST((in_ECX + 0x48)) + 0x1574)); - *puVar1 = *puVar1 | 0x41f; - Entity_Player::EvaluateItems(*GHIDRA_CAST((in_ECX + 0x48))); - } - return; -} - -// 0084eb10 -void StatsPanel::preview_trinket(uint8_t param_1, int param_2) -{ - uint32_t *puVar1; - int iVar2; - uint32_t uVar3; - int in_ECX; - - if (*GHIDRA_CAST((in_ECX + 0x48)) != 0) { - snapshot_stats(0); - iVar2 = *GHIDRA_CAST((in_ECX + 0x48)); - uVar3 = *GHIDRA_CAST((in_ECX + 4)) | 0x8000; - if (param_2 != 1) { - uVar3 = *GHIDRA_CAST((in_ECX + 4)); - } - *GHIDRA_CAST((iVar2 + 0x2ef8)) = uVar3; - *GHIDRA_CAST((iVar2 + 0x2ef0)) = param_1; - puVar1 = GHIDRA_CAST((*GHIDRA_CAST((in_ECX + 0x48)) + 0x1574)); - *puVar1 = *puVar1 | 0x41f; - Entity_Player::EvaluateItems(*GHIDRA_CAST((in_ECX + 0x48))); - snapshot_stats(1); - iVar2 = *GHIDRA_CAST((in_ECX + 0x48)); - *GHIDRA_CAST((iVar2 + 0x2ef8)) = 0; - *GHIDRA_CAST((iVar2 + 0x2ef0)) = 1; - puVar1 = GHIDRA_CAST((*GHIDRA_CAST((in_ECX + 0x48)) + 0x1574)); - *puVar1 = *puVar1 | 0x41f; - Entity_Player::EvaluateItems(*GHIDRA_CAST((in_ECX + 0x48))); - } - return; -} diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index e94b3d6..88b087e 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -8226,8 +8226,6 @@ uint8_t BitSet128::IsNonZero() { generated_stub("BitSet128::IsNonZero 004171b0") BitSet128 * BitSet128::operator__(BitSet128 *other) { generated_stub("BitSet128::operator__ 00435bf0"); } BitSet128 * BitSet128::operator_or(BitSet128 *outResult, BitSet128 *a, BitSet128 *b) { generated_stub("BitSet128::operator_or 00435c20"); } uint8_t BitSet128::IsZero() { generated_stub("BitSet128::IsZero 00592230"); } -void BossOverlay::update() { generated_stub("BossOverlay::update 004212c0"); } -void BossOverlay::play(int overlayType) { generated_stub("BossOverlay::play 004214b0"); } Color::Color() { generated_stub("Color::Color 00407170"); } ColorMod * Color::operator_assign(ColorMod *other) { generated_stub("Color::operator_assign 004071c0"); } float Color::R() { generated_stub("Color::R 00407240"); } @@ -8250,7 +8248,6 @@ void Color::SetOffset(float redOffset, float greenOffset, float blueOffset) { ge void Color::__mul(ColorMod *other) { generated_stub("Color::__mul 006831c0"); } ColorMod * Color::Lerp(ColorMod *out, ColorMod *from, ColorMod *to, float t) { generated_stub("Color::Lerp 006832e0"); } void CommandThread::post_command(void *command) { generated_stub("CommandThread::post_command 00a73100"); } -void DailyChallenge::Init(uint32_t dailyDate) { generated_stub("DailyChallenge::Init 00426a50"); } DamageInfo::DamageInfo() { generated_stub("DamageInfo::DamageInfo 006a8190"); } void DateTime::set_from_yyyymmdd(void *dateTime, int yyyymmdd) { generated_stub("DateTime::set_from_yyyymmdd 0085af30"); } void DateTime::constructor(uint8_t isNow) { generated_stub("DateTime::constructor 00a24270"); } @@ -9210,14 +9207,10 @@ void * NetworkManager::receive_message(void *outMessage, uint8_t channel, uint8_ void NetworkManager::receive_packet(uint64_t *sender, void *buffer, int size) { generated_stub("NetworkManager::receive_packet 00a78a10"); } 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"); } 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"); } void NpcHelper::mother_set_collision_class(Entity_NPC *npc, int collisionClass) { generated_stub("NpcHelper::mother_set_collision_class 005688c0"); } -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::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"); } @@ -9251,8 +9244,6 @@ void ReferenceCountBase::vfunc_3() { generated_stub("ReferenceCountBase::vfunc_3 void ReferenceCountBase::vfunc_4() { generated_stub("ReferenceCountBase::vfunc_4 00af05d3"); } void ReferenceCountBase::vfunc_5() { generated_stub("ReferenceCountBase::vfunc_5 00af05d3"); } 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"); } 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"); } @@ -9290,11 +9281,6 @@ int Sprite::GetLayerCount() { generated_stub("Sprite::GetLayerCount 00440e40"); void Sprite::set_offset(Vector *offset) { generated_stub("Sprite::set_offset 00456340"); } long double Sprite::PlaybackSpeed() { generated_stub("Sprite::PlaybackSpeed 00456360"); } Vector * Sprite::Offset() { generated_stub("Sprite::Offset 0049cb40"); } -void StatsPanel::add_stat_line() { generated_stub("StatsPanel::add_stat_line 0084dc00"); } -void StatsPanel::set(Entity_Player *player, uint8_t isGoldenTrinket) { generated_stub("StatsPanel::set 0084dea0"); } -void StatsPanel::snapshot_stats(uint32_t param_1) { generated_stub("StatsPanel::snapshot_stats 0084e9d0"); } -void StatsPanel::preview_collectible(uint8_t param_1) { generated_stub("StatsPanel::preview_collectible 0084ea90"); } -void StatsPanel::preview_trinket(uint8_t param_1, int param_2) { generated_stub("StatsPanel::preview_trinket 0084eb10"); } SteamCloudFile::~SteamCloudFile() { generated_stub("SteamCloudFile::~SteamCloudFile 00683710"); } void SteamCloudFile::vfunc_1() { generated_stub("SteamCloudFile::vfunc_1 0067efb0"); } void SteamCloudFile::vfunc_2() { generated_stub("SteamCloudFile::vfunc_2 0067efc0"); } @@ -9453,12 +9439,10 @@ void FUN_0040c610() { generated_stub("FUN_0040c610 0040c610"); } uint32_t FUN_0040c630() { generated_stub("FUN_0040c630 0040c630"); } void FUN_0040c690() { generated_stub("FUN_0040c690 0040c690"); } uint32_t FUN_0040c6b0() { generated_stub("FUN_0040c6b0 0040c6b0"); } -uint32_t FUN_0040c6f0() { generated_stub("FUN_0040c6f0 0040c6f0"); } void FUN_0040c720(uint8_t *param_1) { generated_stub("FUN_0040c720 0040c720"); } void deallocate(void *ptr, uint32_t count) { generated_stub("deallocate 0040c740"); } void FUN_0040c790() { generated_stub("FUN_0040c790 0040c790"); } uint32_t FUN_0040c7c0() { generated_stub("FUN_0040c7c0 0040c7c0"); } -void render_color_stack_push(ColorMod *color) { generated_stub("render_color_stack_push 0040c890"); } int memcmp_eq(void *a, void *b, uint32_t size) { generated_stub("memcmp_eq 0040ca70"); } void FUN_0040cad0() { generated_stub("FUN_0040cad0 0040cad0"); } uint8_t str_eq(uint8_t *a, uint32_t lengthA, uint8_t *b, uint32_t lengthB) { generated_stub("str_eq 0040cae0"); } @@ -9586,9 +9570,6 @@ uint32_t * FUN_00420020(int param_1, int param_2, uint32_t *param_3) { generated RoomTransition * FUN_00420ae0() { generated_stub("FUN_00420ae0 00420ae0"); } void FUN_00420b00() { generated_stub("FUN_00420b00 00420b00"); } void FUN_00420b20() { generated_stub("FUN_00420b20 00420b20"); } -void FUN_00421260() { generated_stub("FUN_00421260 00421260"); } -void FUN_00421400() { generated_stub("FUN_00421400 00421400"); } -void FUN_004215a0(char *param_1) { generated_stub("FUN_004215a0 004215a0"); } void FUN_004215e0(uint32_t *param_1) { generated_stub("FUN_004215e0 004215e0"); } void FUN_00421620(uint8_t *param_1) { generated_stub("FUN_00421620 00421620"); } DailyChallenge * FUN_00421780() { generated_stub("FUN_00421780 00421780"); } @@ -9615,8 +9596,6 @@ void FUN_00425410() { generated_stub("FUN_00425410 00425410"); } void online_stats_destroy(void *self) { generated_stub("online_stats_destroy 00425430"); } void OnlineStats::compute_awards() { generated_stub("OnlineStats::compute_awards 004254b0"); } void online_stats_register_players() { generated_stub("online_stats_register_players 004257b0"); } -void FUN_00427290() { generated_stub("FUN_00427290 00427290"); } -int holiday_get_current(uint32_t yyyymmdd) { generated_stub("holiday_get_current 00427870"); } void FUN_00428560(uint32_t *param_1, uint32_t param_2) { generated_stub("FUN_00428560 00428560"); } void FUN_004286b0(int *param_1, int *param_2) { generated_stub("FUN_004286b0 004286b0"); } void FUN_00428880() { generated_stub("FUN_00428880 00428880"); } @@ -9799,7 +9778,6 @@ void NpcAI::ENTITY_BEAST_ultra_war_fire_burst(Entity_NPC *npc) { generated_stub( void NpcAI::ENTITY_BEAST_ultra_war_bomb(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BEAST_ultra_war_bomb 0044f2b0"); } void FUN_00450880(uint32_t param_1) { generated_stub("FUN_00450880 00450880"); } void FUN_004508a0(uint32_t param_1) { generated_stub("FUN_004508a0 004508a0"); } -void NpcAI::ENTITY_LIL_BLUB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LIL_BLUB 00450da0"); } uint32_t _ptr_deref_or_minus1() { generated_stub("_ptr_deref_or_minus1 00452be0"); } void FUN_00456170(int *param_1) { generated_stub("FUN_00456170 00456170"); } void FUN_00456190(uint32_t *param_1) { generated_stub("FUN_00456190 00456190"); } @@ -9827,11 +9805,6 @@ void FUN_00499950() { generated_stub("FUN_00499950 00499950"); } void FUN_004999b0() { generated_stub("FUN_004999b0 004999b0"); } uint32_t FUN_004999d0(uint32_t param_1) { generated_stub("FUN_004999d0 004999d0"); } uint32_t FUN_00499db0() { generated_stub("FUN_00499db0 00499db0"); } -void NpcAI::ENTITY_BUMBINO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BUMBINO 00499de0"); } -void NpcAI::ENTITY_CHIMERA_head_update(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CHIMERA_head_update 0049cd90"); } -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"); } int FUN_004a2920() { generated_stub("FUN_004a2920 004a2920"); } void FUN_004aaaa0(void *param_1, int param_2) { generated_stub("FUN_004aaaa0 004aaaa0"); } @@ -9866,7 +9839,6 @@ 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"); } void FUN_004c5980(float *param_1, Vector *param_2) { generated_stub("FUN_004c5980 004c5980"); } -void NpcAI::ENTITY_MATRIARCH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MATRIARCH 004c59d0"); } void FUN_004cdce0() { generated_stub("FUN_004cdce0 004cdce0"); } uint32_t FUN_004ce0f0() { generated_stub("FUN_004ce0f0 004ce0f0"); } void FUN_004cf0f0(uint8_t param_1) { generated_stub("FUN_004cf0f0 004cf0f0"); } @@ -9901,7 +9873,6 @@ void pow_wrapper() { generated_stub("pow_wrapper 00505b40"); } void set_byte_0x101(void *self, uint8_t value) { generated_stub("set_byte_0x101 00505b50"); } int FUN_00505ca0() { generated_stub("FUN_00505ca0 00505ca0"); } uint32_t * FUN_00505ce0() { generated_stub("FUN_00505ce0 00505ce0"); } -long double FUN_00515290(Vector *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00515290 00515290"); } 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"); } @@ -9916,9 +9887,6 @@ void FUN_0056ff00(uint32_t *param_1, uint32_t param_2, uint32_t param_3) { gener bool FUN_0056ff60(uint32_t param_1) { generated_stub("FUN_0056ff60 0056ff60"); } 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 FUN_00579700() { generated_stub("FUN_00579700 00579700"); } uint32_t FUN_00579760() { generated_stub("FUN_00579760 00579760"); } @@ -9940,7 +9908,6 @@ void NpcAI::ENTITY_SCOURGE_projectile_attack(Entity_NPC *npc) { generated_stub(" void NpcAI::ENTITY_SCOURGE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SCOURGE 00587aa0"); } uint32_t FUN_0058ab60() { generated_stub("FUN_0058ab60 0058ab60"); } void NpcAI::ENTITY_SINGE_body(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SINGE_body 0058aed0"); } -void NpcAI::ENTITY_SINGE_ball(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SINGE_ball 0058d8b0"); } uint8_t FUN_0058e210() { generated_stub("FUN_0058e210 0058e210"); } void FUN_0058e240(uint32_t param_1) { generated_stub("FUN_0058e240 0058e240"); } void NpcAI::ENTITY_SIREN_main(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SIREN_main 0058ec70"); } @@ -10122,7 +10089,6 @@ uint32_t FUN_0060dae0() { generated_stub("FUN_0060dae0 0060dae0"); } void FUN_0062e0e0(int param_1) { generated_stub("FUN_0062e0e0 0062e0e0"); } void FUN_00638e20() { generated_stub("FUN_00638e20 00638e20"); } void FUN_0063c060(int param_1) { generated_stub("FUN_0063c060 0063c060"); } -void FUN_0063e180() { generated_stub("FUN_0063e180 0063e180"); } void FUN_006431b0() { generated_stub("FUN_006431b0 006431b0"); } void FUN_0064b6a0() { generated_stub("FUN_0064b6a0 0064b6a0"); } void FUN_0064d570(uint32_t param_1) { generated_stub("FUN_0064d570 0064d570"); } @@ -10154,7 +10120,6 @@ int FUN_00652a30(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint8_t p void FUN_00652a70() { generated_stub("FUN_00652a70 00652a70"); } bool _has_flag_0x110(uint32_t param_1) { generated_stub("_has_flag_0x110 00652a90"); } int FUN_00652ae0() { generated_stub("FUN_00652ae0 00652ae0"); } -void reroll_entity_to_free_tile(int param_1) { generated_stub("reroll_entity_to_free_tile 0065ad30"); } bool FUN_0065cfe0(uint32_t param_1) { generated_stub("FUN_0065cfe0 0065cfe0"); } int FUN_0065d010() { generated_stub("FUN_0065d010 0065d010"); } void FUN_0065d020() { generated_stub("FUN_0065d020 0065d020"); } @@ -10167,9 +10132,6 @@ void FUN_0065d0c0() { generated_stub("FUN_0065d0c0 0065d0c0"); } void FUN_0065d160() { generated_stub("FUN_0065d160 0065d160"); } uint8_t * FUN_0065d1f0() { generated_stub("FUN_0065d1f0 0065d1f0"); } Vector * FUN_006653c0(Vector *param_1) { generated_stub("FUN_006653c0 006653c0"); } -void FUN_006653e0(int param_1) { generated_stub("FUN_006653e0 006653e0"); } -void FUN_006655e0() { generated_stub("FUN_006655e0 006655e0"); } -void FUN_00665630() { generated_stub("FUN_00665630 00665630"); } void FUN_00665a30() { generated_stub("FUN_00665a30 00665a30"); } void FUN_00665a50() { generated_stub("FUN_00665a50 00665a50"); } void FUN_00665a90(Entity *param_1) { generated_stub("FUN_00665a90 00665a90"); } @@ -10196,7 +10158,6 @@ uint32_t FUN_0067f030() { generated_stub("FUN_0067f030 0067f030"); } void FUN_0067f2e0() { generated_stub("FUN_0067f2e0 0067f2e0"); } uint8_t string_to_bool(void *self) { generated_stub("string_to_bool 0067f600"); } void ResolveRelativePath(uint8_t *anmPath, uint8_t *relPath, uint8_t *outPath) { generated_stub("ResolveRelativePath 0067f670"); } -void ExtractAngleBracketText() { generated_stub("ExtractAngleBracketText 0067fdf0"); } void FUN_00680060(size_t param_1) { generated_stub("FUN_00680060 00680060"); } void shader_stack_push(int shaderIndex) { generated_stub("shader_stack_push 00682280"); } void FUN_00682350() { generated_stub("FUN_00682350 00682350"); } @@ -10507,7 +10468,6 @@ void FUN_00738390(uint32_t param_1) { generated_stub("FUN_00738390 00738390"); } void FUN_007383b0() { generated_stub("FUN_007383b0 007383b0"); } int FUN_00738620(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_00738620 00738620"); } void FUN_00741cc0() { generated_stub("FUN_00741cc0 00741cc0"); } -void FUN_00741cf0() { generated_stub("FUN_00741cf0 00741cf0"); } void FUN_007435c8() { generated_stub("FUN_007435c8 007435c8"); } void FUN_0074371e() { generated_stub("FUN_0074371e 0074371e"); } void FUN_0074399a() { generated_stub("FUN_0074399a 0074399a"); } @@ -10586,8 +10546,6 @@ void FUN_00757980(uint32_t *param_1) { generated_stub("FUN_00757980 00757980"); void FUN_00757a10() { generated_stub("FUN_00757a10 00757a10"); } uint32_t FUN_00758590() { generated_stub("FUN_00758590 00758590"); } int FUN_00759260() { generated_stub("FUN_00759260 00759260"); } -void FUN_0075d9f0(uint32_t param_1) { generated_stub("FUN_0075d9f0 0075d9f0"); } -uint32_t FUN_0075ef20(ANM2 *param_1, int param_2) { generated_stub("FUN_0075ef20 0075ef20"); } void FUN_00770640(float *param_1) { generated_stub("FUN_00770640 00770640"); } void FUN_007792f0(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_007792f0 007792f0"); } uint32_t FUN_007826c0() { generated_stub("FUN_007826c0 007826c0"); } @@ -10609,7 +10567,6 @@ 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"); } uint32_t FUN_007dac30() { generated_stub("FUN_007dac30 007dac30"); } -void FUN_007dad80() { generated_stub("FUN_007dad80 007dad80"); } int FUN_007dafb0() { generated_stub("FUN_007dafb0 007dafb0"); } void FUN_007dc610() { generated_stub("FUN_007dc610 007dc610"); } void FUN_007dc620(uint32_t *param_1) { generated_stub("FUN_007dc620 007dc620"); } @@ -10693,7 +10650,6 @@ uint32_t * FUN_007e3060(uint32_t *param_1) { generated_stub("FUN_007e3060 007e30 void FUN_007e3190() { generated_stub("FUN_007e3190 007e3190"); } void FUN_007e3230() { generated_stub("FUN_007e3230 007e3230"); } void FUN_007e4890() { generated_stub("FUN_007e4890 007e4890"); } -uint8_t pathfinder_can_reach_pos(Vector *targetPos, Vector *startPos, Room *room) { generated_stub("pathfinder_can_reach_pos 007e7820"); } void FUN_007e8620() { generated_stub("FUN_007e8620 007e8620"); } void FUN_007e86e0(int param_1, int param_2) { generated_stub("FUN_007e86e0 007e86e0"); } void * vector_PathNode_emplace_reallocate_copy(void *self, void *where, void *value) { generated_stub("vector_PathNode_emplace_reallocate_copy 007e8810"); } @@ -10770,7 +10726,6 @@ void FUN_00839840(float *param_1) { generated_stub("FUN_00839840 00839840"); } void FUN_00839960() { generated_stub("FUN_00839960 00839960"); } void FUN_008399a0(int *param_1) { generated_stub("FUN_008399a0 008399a0"); } 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"); } void FUN_0083bf50() { generated_stub("FUN_0083bf50 0083bf50"); } @@ -10779,13 +10734,6 @@ void Catch_All_0083c241() { generated_stub("Catch_All_0083c241 0083c241"); } uint32_t * FUN_0083c270(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3) { generated_stub("FUN_0083c270 0083c270"); } void FUN_0083c320(int *param_1, int *param_2) { generated_stub("FUN_0083c320 0083c320"); } void FUN_0083c480() { generated_stub("FUN_0083c480 0083c480"); } -uint8_t ItemInfo::is_collectible_seen(int param_1) { generated_stub("ItemInfo::is_collectible_seen 0083d760"); } -uint8_t ItemInfo::is_pickup_known(int param_1) { generated_stub("ItemInfo::is_pickup_known 0083d7c0"); } -void item_pool_icons_render(void *iconLayer, Vector *position, KColor *color) { generated_stub("item_pool_icons_render 0083d8c0"); } -void ItemInfo::measure(uint32_t *param_1) { generated_stub("ItemInfo::measure 00840250"); } -void ItemInfo::measure_line(uint8_t *param_1, float *param_2, int *param_3) { generated_stub("ItemInfo::measure_line 008402f0"); } -void ItemInfo::render_popup_callback(int param_1, uint32_t param_2) { generated_stub("ItemInfo::render_popup_callback 00840370"); } -void ItemInfo::render_line(uint8_t *param_1, Vector *param_2, int param_3) { generated_stub("ItemInfo::render_line 008404a0"); } char * FUN_00840510() { generated_stub("FUN_00840510 00840510"); } std_string * int_to_string(std_string *outString, int value) { generated_stub("int_to_string 00840540"); } void FUN_0084abc0(uint32_t *param_1, float *param_2, uint32_t *param_3, uint32_t *param_4) { generated_stub("FUN_0084abc0 0084abc0"); } @@ -12620,17 +12568,6 @@ void kick_player_menu_render() { generated_stub("kick_player_menu_render 008d160 void FUN_008d2810() { generated_stub("FUN_008d2810 008d2810"); } uint32_t * FUN_008d2880(uint32_t *param_1, int param_2) { generated_stub("FUN_008d2880 008d2880"); } void FUN_008d28c0(uint32_t param_1, uint8_t *param_2) { generated_stub("FUN_008d28c0 008d28c0"); } -void FUN_008d47c0(int *param_1, uint32_t *param_2, uint32_t *param_3, uint32_t param_4, float param_5, uint32_t param_6) { generated_stub("FUN_008d47c0 008d47c0"); } -void OnlinePlayerInfo::render_items(float *param_1) { generated_stub("OnlinePlayerInfo::render_items 008d4940"); } -void FUN_008d5440(float *param_1) { generated_stub("FUN_008d5440 008d5440"); } -void FUN_008d5640(float *param_1) { generated_stub("FUN_008d5640 008d5640"); } -void FUN_008d57f0(float *param_1) { generated_stub("FUN_008d57f0 008d57f0"); } -void FUN_008d5da0(int *param_1, ANM2 *param_2, float *param_3) { generated_stub("FUN_008d5da0 008d5da0"); } -void render_item_info_text(void *self, void *text, Vector *position, int width, uint32_t lineStart, uint32_t lineEnd) { generated_stub("render_item_info_text 008d5f70"); } -int FUN_008d69d0(int param_1) { generated_stub("FUN_008d69d0 008d69d0"); } -uint32_t menu_item_description_build(void *self, int *item, uint32_t startLine, int unused, float maxHeight) { generated_stub("menu_item_description_build 008d7cb0"); } -int FUN_008d8460(int *param_1) { generated_stub("FUN_008d8460 008d8460"); } -void item_info_update_charge_bar(void *self, int collectibleId, Entity_Player *player) { generated_stub("item_info_update_charge_bar 008d8870"); } void FUN_008d8a90() { generated_stub("FUN_008d8a90 008d8a90"); } bool FUN_008dc0a0(int *param_1, int *param_2) { generated_stub("FUN_008dc0a0 008dc0a0"); } bool FUN_008dc0d0(uint32_t param_1, int *param_2, int *param_3, uint8_t **param_4, int *param_5, int *param_6) { generated_stub("FUN_008dc0d0 008dc0d0"); } @@ -12922,7 +12859,6 @@ void float_split() { generated_stub("float_split 00925f30"); } void FUN_00926240() { generated_stub("FUN_00926240 00926240"); } void FUN_00926460(uint8_t param_1) { generated_stub("FUN_00926460 00926460"); } uint32_t FUN_009264b0(uint8_t *param_1, uint8_t *param_2) { generated_stub("FUN_009264b0 009264b0"); } -int save_backup_find_latest(PersistentGameData *gameData) { generated_stub("save_backup_find_latest 00926510"); } void FUN_00929660(char param_1) { generated_stub("FUN_00929660 00929660"); } uint8_t * FUN_00929b00() { generated_stub("FUN_00929b00 00929b00"); } uint32_t FUN_00929b20() { generated_stub("FUN_00929b20 00929b20"); } @@ -12972,7 +12908,6 @@ void cutscene_render_skip_vote_count(void *cutscene, void *state) { generated_st uint32_t * FUN_00960880(void *param_1, uint32_t *param_2) { generated_stub("FUN_00960880 00960880"); } void FUN_00960bc0() { generated_stub("FUN_00960bc0 00960bc0"); } void FUN_0096d120(int *param_1) { generated_stub("FUN_0096d120 0096d120"); } -void pressure_plate_kill_enemies_timer_callback(int *param_1) { generated_stub("pressure_plate_kill_enemies_timer_callback 00983f30"); } void FUN_0098b0a0() { generated_stub("FUN_0098b0a0 0098b0a0"); } void FUN_0098b130() { generated_stub("FUN_0098b130 0098b130"); } void FUN_00993740() { generated_stub("FUN_00993740 00993740"); } @@ -12990,7 +12925,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"); } -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"); } void move_directory_files() { generated_stub("move_directory_files 009a90e0"); } @@ -13095,7 +13029,6 @@ void FUN_009e6e10(int param_1) { generated_stub("FUN_009e6e10 009e6e10"); } void FUN_009e6e50(uint8_t *param_1) { generated_stub("FUN_009e6e50 009e6e50"); } void FUN_009e6e80() { generated_stub("FUN_009e6e80 009e6e80"); } void FUN_009e6e90(Weapon_Brimstone *param_1, uint32_t param_2) { generated_stub("FUN_009e6e90 009e6e90"); } -void save_screenshot() { generated_stub("save_screenshot 009e6eb0"); } void FUN_009e72e0() { generated_stub("FUN_009e72e0 009e72e0"); } void FUN_009e7300() { generated_stub("FUN_009e7300 009e7300"); } void FUN_009e7310() { generated_stub("FUN_009e7310 009e7310"); } @@ -13142,13 +13075,10 @@ void FUN_009ebbf0() { generated_stub("FUN_009ebbf0 009ebbf0"); } void Catch_All_009ebf8f() { generated_stub("Catch_All_009ebf8f 009ebf8f"); } void FUN_009ebfc0() { generated_stub("FUN_009ebfc0 009ebfc0"); } void FUN_009ef980(uint32_t *param_1) { generated_stub("FUN_009ef980 009ef980"); } -Vector * rich_text_render(void *self, Vector *outSize, uint8_t *text, Vector *position, KColor *color, float scale, int maxWidth) { generated_stub("rich_text_render 009efdb0"); } -void rich_text_layout(void *copiedSpan, uint8_t *markup, KColor *baseColor, uint32_t maxWidth, void *outLines, float scale) { generated_stub("rich_text_layout 009f0290"); } void FUN_009f1be0(uint32_t *param_1) { generated_stub("FUN_009f1be0 009f1be0"); } void FUN_009f1d20(char *param_1, char *param_2) { generated_stub("FUN_009f1d20 009f1d20"); } void FUN_009f1d50(void *param_1, int param_2) { generated_stub("FUN_009f1d50 009f1d50"); } void Catch_All_009f20c7() { generated_stub("Catch_All_009f20c7 009f20c7"); } -void FUN_009f20f0(void *param_1) { generated_stub("FUN_009f20f0 009f20f0"); } void Catch_All_009f229d() { generated_stub("Catch_All_009f229d 009f229d"); } uint32_t * FUN_009f2410(uint32_t *param_1) { generated_stub("FUN_009f2410 009f2410"); } void FUN_009f2480() { generated_stub("FUN_009f2480 009f2480"); } @@ -13260,7 +13190,6 @@ void FUN_00a1d4d0(uint32_t param_1, uint32_t *param_2) { generated_stub("FUN_00a void FUN_00a1d5a0(uint32_t *param_1) { generated_stub("FUN_00a1d5a0 00a1d5a0"); } void FUN_00a1d600() { generated_stub("FUN_00a1d600 00a1d600"); } void FUN_00a1d6b0(int param_1) { generated_stub("FUN_00a1d6b0 00a1d6b0"); } -void render_color_quad(Vector *from, Vector *to, KColor *fromColor, KColor *toColor, float thickness) { generated_stub("render_color_quad 00a1d710"); } void FUN_00a1e050() { generated_stub("FUN_00a1e050 00a1e050"); } void FUN_00a1e1f0() { generated_stub("FUN_00a1e1f0 00a1e1f0"); } uint32_t FUN_00a1e210() { generated_stub("FUN_00a1e210 00a1e210"); } diff --git a/src/anm2.cpp b/src/anm2.cpp index 47bf243..953a93e 100644 --- a/src/anm2.cpp +++ b/src/anm2.cpp @@ -1,4 +1,5 @@ #include "anm2.h" +#include "color_stack.h" #include "game.h" #include "kage_graphics.h" #include "data.h" @@ -1176,7 +1177,7 @@ static ColorMod layer_color_get(const AnimationFrame& frame, const LayerState& l ColorMod color = (flags & ANIM_RENDER_UNTINTED) ? layer.color : animation.color; if (flags & ANIM_RENDER_UNTINTED) color_multiply(color, frame.color); - else if (g_colorStackSize != 0) color = *(const ColorMod*)(uintptr_t)FUN_0040c6f0(); + else if (const ColorMod* top = color_stack_top()) color = *top; else { color_multiply(color, layer.color); diff --git a/src/backdrop.cpp b/src/backdrop.cpp index 6f9201f..86ed15f 100644 --- a/src/backdrop.cpp +++ b/src/backdrop.cpp @@ -45,7 +45,6 @@ constexpr uint32_t RNG_SHIFT_CONTROLS = 39; // A room's grid cells on the surfaces, and the walls two cells thick that frame its floor. constexpr float GRID_SIZE = 26; -constexpr int WALL_CELLS = 2; constexpr float WALL_SIZE = WALL_CELLS * GRID_SIZE; constexpr uint32_t FLOOR_SECOND = 1; @@ -114,7 +113,6 @@ constexpr std::string_view KEYBOARD_ANIMATION = "Keyboard"; constexpr std::string_view GAMEPAD_ANIMATION = "XboxOne"; constexpr int KEYBOARD_CONTROLLER = 0; constexpr int ACTION_NONE = -1; -constexpr int KEY_SPACE = 32; constexpr float SPACE_KEY_PADDING = 4; constexpr float ICON_PADDING = 4; constexpr float ICON_WIDTH = 8; @@ -145,14 +143,11 @@ constexpr int WALL_EDGE_COLUMNS = 7; constexpr int WALL_EDGE_ROWS = 4; constexpr int WALL_MIDDLE_COLUMN = 7; constexpr int WALL_MIDDLE_ROW = 4; -constexpr int NARROW_COLUMN_INSET = 4; constexpr int NARROW_ROW_INSET = 2; constexpr int L_CORNER_SHEET_X = 18; // The blood splats a room may start with: on world cells 40 apart, kept 20 from the walls or 100 from the middle. constexpr float WORLD_CELL = 40; -constexpr float WORLD_ORIGIN_X = 40; -constexpr float WORLD_ORIGIN_Y = 120; constexpr float SPLAT_MARGIN = 20; constexpr float SPLAT_RADIUS = 100; constexpr float SPLAT_SQUASH = 0.6f; @@ -210,7 +205,6 @@ constexpr int DOOR_SIDE_SLOT = 2; constexpr int MINES_LANTERN_ODDS = 4; constexpr int MAUSOLEUM_TORCH_ODDS = 3; constexpr int GEHENNA_CHAIN_ODDS = 3; -constexpr int COLOR_PRIORITY_TOP = 255; // RenderFloor: the Error room's floor sprite repeats every 100 pixels. constexpr float ERROR_TILE = 100; @@ -1043,7 +1037,7 @@ static void blood_splat_spawn(Backdrop& backdrop, Vector position, bool isDarken float scale = backdrop.rng.RandomFloat() * SPLAT_SCALE_RANGE + SPLAT_SCALE_MIN; splat->sprite.scale = vector_make(scale, scale); - if (isDarkened) splat->SetColor(CORPSE_SPLAT_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + if (isDarkened) splat->SetColor(CORPSE_SPLAT_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_DEFAULT, false, true); splat->Update(); } @@ -1055,8 +1049,8 @@ static void blood_splats_spawn(Backdrop& backdrop) uint32_t id = backdrop.backdropId; int cells = room.gridHeight * room.gridWidth; auto cell_position = [&](int cell) { - return vector_make((float)(cell % room.gridWidth) * WORLD_CELL + WORLD_ORIGIN_X, - (float)(cell / room.gridWidth) * WORLD_CELL + WORLD_ORIGIN_Y); + return vector_make((float)(cell % room.gridWidth) * WORLD_CELL + GRID_ORIGIN_X, + (float)(cell / room.gridWidth) * WORLD_CELL + GRID_ORIGIN_Y); }; if (id == BACKDROP_BASEMENT && room.roomType == ROOM_BOSS) @@ -1469,7 +1463,7 @@ static Entity* null_light_spawn(Vector position, const NullFrame& frame) light->flags |= FLAG_BACKDROP_DETAIL; static_cast(light)->scale = LIGHT_SCALE; - light->SetColor(frame.color, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + light->SetColor(frame.color, COLOR_DURATION_FOREVER, COLOR_PRIORITY_DEFAULT, false, true); light->sprite.scale = frame.scale; return light; } @@ -1508,7 +1502,7 @@ static void ember_spawn(Backdrop& backdrop, const WallSlot& slot, float drawBack Entity* ember = wall_light_spawn(slot, drawBack, 0); static_cast(ember)->scale = LIGHT_SCALE; - ember->SetColor(EMBER_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + ember->SetColor(EMBER_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_DEFAULT, false, true); if (!isFlattened) { float scale = backdrop.rng.RandomFloat() * BURNING_EMBER_RANGE + BURNING_EMBER_MIN; @@ -1573,7 +1567,7 @@ static void colored_splat_spawn(Backdrop& backdrop, Vector position, const Color {.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = backdrop.rng.Next()}); splat->sprite.scale = vector_make(scale, scale); - splat->SetColor(color, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + splat->SetColor(color, COLOR_DURATION_FOREVER, COLOR_PRIORITY_DEFAULT, false, true); splat->Update(); } @@ -1590,7 +1584,7 @@ static void cathedral_light_spawn(const WallSlot& slot) g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_LIGHT, .seed = Random()}); light->flags |= FLAG_BACKDROP_DETAIL; - light->SetColor(CATHEDRAL_LIGHT_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + light->SetColor(CATHEDRAL_LIGHT_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_DEFAULT, false, true); light->sprite.scale = vector_make(CATHEDRAL_LIGHT_SCALE_X, CATHEDRAL_LIGHT_SCALE_Y); light->sprite.rotation = ySign * xSign * CATHEDRAL_LIGHT_ANGLE; } @@ -1635,7 +1629,7 @@ static void dross_details_spawn(Backdrop& backdrop, const WallSlot& slot, bool i int subType = backdrop.rng.RandomInt(DROSS_LIGHT_ODDS) == 0; Entity* light = wall_light_spawn(slot, -WALL_LIGHT_OUT, subType); - light->SetColor(DROSS_LIGHT_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + light->SetColor(DROSS_LIGHT_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_DEFAULT, false, true); light->sprite.scale = vector_make(DROSS_LIGHT_SCALE, DROSS_LIGHT_SCALE); return; } diff --git a/src/beast_arena.cpp b/src/beast_arena.cpp index 46fbfde..840a22f 100644 --- a/src/beast_arena.cpp +++ b/src/beast_arena.cpp @@ -2,7 +2,9 @@ #include "fx_layers.h" #include "game.h" #include "log.h" +#include "render_passes.h" #include "room.h" +#include constexpr int BACKGROUND_LAYER_COUNT = 15; constexpr int BACKGROUND_GLOW_LAYER = 8; @@ -99,27 +101,129 @@ void BeastArena::interpolate() } } -// 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. +// The background's art is laid out for a 480 by 270 screen around the room floor, with the floor's 26 margin. The light +// layer's texture (hell_overlay.png) puts its (16, 121) at the floor's screen centre. constexpr int BACKGROUND_LIGHT_LAYER = 16; -constexpr float LIGHT_SCREEN_WIDTH = 480; -constexpr float LIGHT_SCREEN_HEIGHT = 270; -constexpr float LIGHT_FLOOR_MARGIN = 26; +constexpr float ART_SCREEN_WIDTH = 480; +constexpr float ART_SCREEN_HEIGHT = 270; +constexpr float ART_FLOOR_MARGIN = 26; static const Vector LIGHT_ANCHOR = vector_make(16, 121); +// The background's layers each pass draws (up to the first -1), and by layer how far it scrolls and how much of the +// darkness it takes. +constexpr int PASS_LAYER_SLOTS = 6; +constexpr std::array, BEAST_PASS_COUNT> PASS_LAYERS = { + {{0, 1, 2, -1}, {3, 4, 5, 6, 7, 8}, {9, 10, -1}, {11, 12, 13, 14, 15, -1}}}; +constexpr std::array LAYER_PARALLAX = { + 0, 0.25f, 0.25f, 0, 0.33333334f, 0.33333334f, 0.5f, 0.5f, 0, 0.71428573f, 0.71428573f, 1, 1, 0, 0, 1.25f}; +constexpr std::array LAYER_DARKNESS = { + 0, 1, 1, 0, 0.8f, 0.8f, 0.6f, 0.6f, 0.4f, 0.1f, 0.1f, 0, 0, 0, 0, 0.98f}; + +// The background layers drawn from their own rows of the texture: the bands as tall as their keyframe, the ground down +// to the screen's bottom, and the hills and the low glow below their first rows. +constexpr int LAYER_HILLS_BACK = 0; +constexpr int LAYER_HILLS_FRONT = 3; +constexpr int LAYER_BAND_BACK = 9; +constexpr int LAYER_GROUND_BACK = 10; +constexpr int LAYER_BAND_FRONT = 11; +constexpr int LAYER_GROUND_FRONT = 12; +constexpr int LAYER_GLOW = 13; +constexpr float HILLS_FIRST_ROW = 69; +constexpr float GLOW_FIRST_ROW = 292; + +// Where the art's 480 by 270 screen starts on the real one: around the room floor's screen rectangle, following the +// room's scroll and the screen shake. +static Vector art_origin_get() +{ + 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); + return vector_make((floor.x + ART_FLOOR_MARGIN * 2 - ART_SCREEN_WIDTH) * HALF + shift.x + ART_FLOOR_MARGIN, + (floor.y + ART_FLOOR_MARGIN * 2 - ART_SCREEN_HEIGHT) * HALF + shift.y + ART_FLOOR_MARGIN); +} + // 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() { 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); + Vector at = art_origin_get(); 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); } + +// 0083a3d0 (render_beast_arena_background) Draws a pass of the hell background over the screen: under everything a red +// backdrop dimmed by the darkness, then each of the pass's layers in its own blending, scrolled by its parallax, tinted +// by its keyframe and dimmed by its share of the darkness, from the row its keyframe puts it at down. A layer starting +// below the screen is skipped. +// The original returns with the textured shader still pushed when a layer has no spritesheet, and reads a missing +// keyframe. Here the pass ends as usual then. +void BeastArena::render_background(BeastArenaPass pass) +{ + namespace Graphics = KAGE::Graphics; + if (!isActive) return; + + Graphics::Manager& graphics = Graphics::manager; + Vector origin = art_origin_get(); + Vector screen = vector_make(g_screenWidth, g_screenHeight); + float darkness = g_game->darknessStrength * g_game->darknessModifier; + if (pass == BEAST_PASS_BACKGROUND) + { + graphics.blend_set(Graphics::BLEND_OPAQUE); + render_color_shader_pass(Graphics::color_quad_rect({}, screen, kcolor_rgba(1 - darkness, 0, 0, 1))); + } + + graphics.shader_push(Graphics::COLOR_TEXTURE_SHADER); + for (int layerId : PASS_LAYERS[pass]) + { + if (layerId < 0) break; + LayerState& layer = *background.GetLayer(layerId); + const std::array& mode = layer.blendMode; + using Factor = Graphics::BlendFactor; + graphics.blendMode = {(Graphics::BlendEquation)mode[BLEND_EQUATION], (Factor)mode[BLEND_RGB_SOURCE], + (Factor)mode[BLEND_RGB_DEST], (Factor)mode[BLEND_ALPHA_SOURCE], + (Factor)mode[BLEND_ALPHA_DEST]}; + std::shared_ptr texture = layer.spriteSheet; + const AnimationFrame* frame = background.animState.GetLayerFrame(layerId); + if (!texture || !frame) break; + + float shade = 1 - darkness * LAYER_DARKNESS[layerId]; + ColorMod tint = frame->color; + color_multiply(tint, {{shade, shade, shade, 1}, {0, 0, 0, 0}, {0, 0, 0}}); + float top = origin.y + ART_SCREEN_HEIGHT + frame->pos.y - frame->pivot.y - ART_FLOOR_MARGIN; + if (top >= screen.y) continue; + + float destTop = 0; + float destBottom = screen.y; + float sourceTop = -top; + bool isBandLayer = layerId == LAYER_BAND_BACK || layerId == LAYER_BAND_FRONT; + if (isBandLayer) + { + destTop = top; + destBottom = top + frame->height; + sourceTop = frame->crop.y; + } + else if (layerId == LAYER_GROUND_BACK || layerId == LAYER_GROUND_FRONT) + { + destTop = top; + sourceTop = 0; + } + else if (layerId == LAYER_GLOW || layerId == LAYER_HILLS_BACK || layerId == LAYER_HILLS_FRONT) + { + sourceTop = layerId == LAYER_GLOW ? GLOW_FIRST_ROW : HILLS_FIRST_ROW; + destTop = top + sourceTop; + } + float sourceBottom = isBandLayer ? sourceTop + frame->height : screen.y - top; + float scrollX = -scrollRendered * LAYER_PARALLAX[layerId] - origin.x; + Vector sourceSize = vector_make(screen.x, sourceBottom - sourceTop); + Vector destSize = vector_make(screen.x, destBottom - destTop); + texture->Render(Graphics::source_quad_rect(vector_make(scrollX, sourceTop), sourceSize), + Graphics::color_quad_rect(vector_make(0, destTop), destSize, WHITE), + kcolor_rgba(tint._tint[0], tint._tint[1], tint._tint[2], tint._tint[3])); + } + graphics.shader_pop(); + graphics.blend_set(Graphics::BLEND_NORMAL); +} diff --git a/src/beast_arena.h b/src/beast_arena.h index fb69c78..b5f1261 100644 --- a/src/beast_arena.h +++ b/src/beast_arena.h @@ -2,6 +2,16 @@ #include "anm2.h" +// The Beast's arena draws in passes around the room's: under everything, over the floor, over the entities, last. +enum BeastArenaPass +{ + BEAST_PASS_BACKGROUND, + BEAST_PASS_FLOOR, + BEAST_PASS_ENTITIES, + BEAST_PASS_FOREGROUND, + BEAST_PASS_COUNT +}; + // Construction and destruction are the defaults. The scroll speed's getter (00592260) is the public field. // The scrolling hell of the Beast's fight (Room's beastArena): active in Home's Beast crawlspace, where its background // scrolls by scrollSpeed and carries everything but the players and familiars along. @@ -17,4 +27,5 @@ struct BeastArena void update(); void interpolate(); void render_light(); + void render_background(BeastArenaPass pass); }; diff --git a/src/bomb_explosion.cpp b/src/bomb_explosion.cpp index 42bbf02..6fe2f8f 100644 --- a/src/bomb_explosion.cpp +++ b/src/bomb_explosion.cpp @@ -926,7 +926,7 @@ void explosion_effects(const Explosion& explosion) else if (flags[TEAR_GIGA_BOMB]) blast->sprite.scale = vector_make(explosion.radiusMultiplier * 2, explosion.radiusMultiplier * 2); bool isFetusBomb = source && source->type == ENTITY_BOMB && static_cast(source)->isFetus; - if (g_game->dailyChallenge._specialDailyId == SPECIAL_DAILY_FIREWORKS && isFetusBomb) + if (g_game->dailyChallenge.specialDailyId == SPECIAL_DAILY_FIREWORKS && isFetusBomb) { Entity* fireworks = g_game->Spawn({.position = explosion.position, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_FIREWORKS, .seed = Random()}); diff --git a/src/boss_beast.cpp b/src/boss_beast.cpp index 05b16e7..5e83024 100644 --- a/src/boss_beast.cpp +++ b/src/boss_beast.cpp @@ -61,7 +61,6 @@ constexpr std::array BEAST_HURT_ANIMATIONS = {"Damage1", "D 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. diff --git a/src/boss_bumbino.cpp b/src/boss_bumbino.cpp new file mode 100644 index 0000000..4129d0c --- /dev/null +++ b/src/boss_bumbino.cpp @@ -0,0 +1,702 @@ +#include "boss_ai.h" +#include "boss_repentance.h" +#include "capsule.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_slot.h" +#include "grid_entity.h" +#include "item_pool.h" +#include "npc_basement.h" +#include "room_grid.h" +#include +#include + +// Bumbino's states: resting, walking (after coins or its target), dizzy after a wall, swiping, slamming the ground, +// ramming up or down, throwing a butt bomb, and spawning its item before it goes. +enum BumbinoState +{ + BUMBINO_REST = NPC_STATE_IDLE, + BUMBINO_WALK = NPC_STATE_MOVE, + BUMBINO_DIZZY = NPC_STATE_SUICIDE, + BUMBINO_SWIPE = NPC_STATE_ATTACK, + BUMBINO_SLAM = NPC_STATE_ATTACK2, + BUMBINO_RAM = NPC_STATE_ATTACK3, + BUMBINO_BUTT_BOMB = NPC_STATE_ATTACK4, + BUMBINO_LEAVE = NPC_STATE_SPECIAL +}; + +// Resting 30 to 59 frames (10 to 29 after an attack), then walking 60 to 119. Resting, one time in ten it throws a +// butt bomb at its target when that is down and to a side (its direction 0.31 to 0.91 down) in a clear line. +constexpr uint32_t BUMBINO_REST_RANGE = 30; +constexpr int BUMBINO_REST_FRAMES = 30; +constexpr uint32_t REST_SHORT_RANGE = 20; +constexpr int REST_SHORT_FRAMES = 10; +constexpr uint32_t WALK_RANGE = 60; +constexpr int WALK_FRAMES = 60; +constexpr float BUMBINO_LEAD = 0.1f; +constexpr float BUTT_BOMB_DOWN_MIN = 0.30710676f; +constexpr float BUTT_BOMB_DOWN_MAX = 0.90710676f; +constexpr uint32_t BUTT_BOMB_ODDS = 10; +constexpr float REST_FRICTION = 0.8f; + +// Walking: after the nearest free coin it has a path to (searched every 3 frames, one time in four while it has +// one), else at its target, kept within 80 below its target when below the room's middle. It pauses 3 frames on each +// step. Stuck against a wall 9 frames it swipes. One time in four with its target level within 40 (and 200 across) +// it swipes (cooled down, or one time in 50), and one time in six with its target within 40 across it rams. +constexpr float COIN_SEARCH_EVERY = 3; +constexpr uint32_t COIN_KEEP_MASK = 3; +constexpr float COIN_REACH_SQUARED = 100000; +constexpr int STEP_PAUSE = 3; +constexpr float STEP_FRICTION = 0.4f; +constexpr float WALK_REACH_BELOW = 80; +constexpr float BUMBINO_WALK_SPEED = 0.8f; +constexpr float WALK_COIN_SPEED = 0.95f; +constexpr int STUCK_FRAMES = 9; +constexpr uint32_t SWIPE_MASK = 3; +constexpr float SWIPE_LEVEL = 40; +constexpr float SWIPE_ACROSS = 200; +constexpr uint32_t SWIPE_HOT_ODDS = 50; +constexpr float RAM_ACROSS = 40; +constexpr uint32_t RAM_ODDS = 6; +constexpr int COIN_WALK_FRAMES = 15; +constexpr int SWIPE_STUCK = -1; +constexpr int SWIPE_AIMED = 1; + +// Its coins: twelve picked up, it leaves an item from its list. +constexpr int COINS_TO_LEAVE = 12; +constexpr std::array BUMBINO_ITEMS = { + COLLECTIBLE_YUM_HEART, COLLECTIBLE_HEART, COLLECTIBLE_COMMON_COLD, COLLECTIBLE_SINUS_INFECTION, + COLLECTIBLE_NUMBER_ONE, COLLECTIBLE_LEMON_MISHAP, COLLECTIBLE_POOP, COLLECTIBLE_BUTT_BOMBS, + COLLECTIBLE_COMPOUND_FRACTURE, COLLECTIBLE_BONE_SPURS, COLLECTIBLE_DEAD_TOOTH, COLLECTIBLE_MONSTROS_TOOTH}; + +// The swipe lunges at 12 across (4 to 12 at its target a twentieth of the gap across when aimed), up to 4 toward its +// target's height, slowing by 0.75 a frame. Its hitbox knocks things away at 10, hurting players and familiars 2 and +// the rest 35, and knocks one to three coins out of a player (at 3 plus 2 to 7). Stuck, it swipes back and forth. +constexpr float BUMBINO_SWIPE_FRICTION = 0.8f; +constexpr float SWIPE_SPEED = 12; +constexpr float SWIPE_AIM_SHARE = 20; +constexpr float SWIPE_AIM_MIN = 4; +constexpr float SWIPE_CLIMB = 4; +constexpr float SWIPE_NEAR = 0.001f; +constexpr float SWIPE_DRAG = 0.75f; +constexpr float SWIPE_STILL = 0.1f; +constexpr float SWIPE_WALL_SPEED = 10; +constexpr float SWIPE_WALL_FACING = 0.3f; +constexpr float SWIPE_KNOCK = 10; +constexpr float SWIPE_PLAYER_DAMAGE = 2; +constexpr float SWIPE_DAMAGE = 35; +constexpr int SWIPE_HIT_COUNTDOWN = 30; +constexpr uint32_t COIN_LOSS_RANGE = 3; +constexpr float COIN_KNOCK = 3; +constexpr float BUMBINO_COIN_SPEED_RANGE = 5; +constexpr float COIN_SPEED = 2; +constexpr int COIN_DROPPED_SUBTYPE = 1; +constexpr int SWIPE_AGAIN_FRAME = 7; + +// Its trail of dust while lunging, every 2 frames, at a fifth of its speed plus 2 at random. +constexpr float DUST_EVERY = 2; +constexpr float DUST_TRAIL_SHARE = 0.2f; +constexpr float BUMBINO_DUST_SPIN = 10; +constexpr float BUMBINO_DUST_SPIN_MIN = 2; +constexpr uint32_t DUST_TRAIL_RANGE = 15; +constexpr int DUST_TRAIL_FRAMES = 15; +constexpr ColorMod BUMBINO_DUST_COLOR = {{0.8f, 0.7f, 0.65f, 0.75f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float BUMBINO_DUST_DEPTH = -5; + +// The slam: 15 dust clouds at 15 to 20 and four crackwaves, a ring of eight rocks at 12, ten rock particles, and +// players within 100 thrown at 3. Then a rest and 30 to 89 frames of cooldown. +constexpr int BUMBINO_SLAM_SHAKE = 14; +constexpr int SLAM_DUST = 15; +constexpr float SLAM_DUST_SPEED = 15; +constexpr float BUMBINO_SLAM_DUST_SPEED_RANGE = 5; +constexpr float BUMBINO_DUST_SCALE = 0.9f; +constexpr float BUMBINO_DUST_SCALE_RANGE = 0.3f; +constexpr uint32_t SLAM_DUST_RANGE = 20; +constexpr int SLAM_DUST_FRAMES = 20; +constexpr int SLAM_CRACKWAVES = 4; +constexpr float BUMBINO_CRACKWAVE_FIRST = 45; +constexpr float BUMBINO_CRACKWAVE_STEP = 90; +constexpr int BUMBINO_SLAM_SOUND_DELAY = 20; +constexpr ColorMod SLAM_POOF_COLOR = {{0.9f, 0.85f, 0.84f, 0.9f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float SLAM_ROCK_SCALE = 1.25f; +constexpr float BUMBINO_SLAM_ROCK_SPEED = 12; +constexpr int BUMBINO_SLAM_PARTICLES = 10; +constexpr float PARTICLE_SPEED_MIN = 0.5f; +constexpr float PARTICLE_FLATTEN = 0.8f; +constexpr float BUMBINO_PARTICLE_SPEED = 10; +constexpr float PARTICLE_OUT = 3; +constexpr uint32_t PARTICLE_PLAIN_ODDS = 3; +constexpr int PARTICLE_DARK_SUBTYPE = 0x20000; +constexpr float SLAM_THROW_REACH = 100; +constexpr float PLAYER_THROW_SPEED = 3; +constexpr float PLAYER_THROW_HEIGHT = 9; +constexpr uint32_t BUMBINO_COOLDOWN_RANGE = 60; +constexpr int COOLDOWN_FRAMES = 30; +constexpr float SLAM_FRICTION = 0.7f; + +// The ram: down at 10 or up at 8, a doubled push at its start. +constexpr float RAM_DOWN_SPEED = 10; +constexpr float RAM_UP_SPEED = -8; + +// The butt bomb: a fart of 85 and a butt bomb at 12 within 45 degrees of its side toward its target ahead, on a 20 +// fuse. +constexpr float BUMBINO_BUTT_FART_RADIUS = 85; +constexpr float BUTT_BOMB_RIGHT = 30; +constexpr float BUTT_BOMB_LEFT = 150; +constexpr float BUTT_BOMB_TURN = 45; +constexpr float BUTT_BOMB_SPEED = 12; +constexpr int BUTT_BOMB_FUSE = 20; + +// A wall hit while lunging: dizzy for 60 frames, ten dust clouds thrown off the wall at 15 to 19, eight rocks at 100 +// off the wall, and players within 150 thrown. Dizzy it rains rocks every other frame from 400 up, on its target one +// time in five, else on a free spot. A lunge breaks rocks it hits and bridges a pit behind them. +constexpr int BUMBINO_DIZZY_FRAMES = 60; +constexpr int WALL_DUST = 10; +constexpr float WALL_DUST_SPREAD = 160; +constexpr float WALL_DUST_FIRST = 100; +constexpr float WALL_DUST_SPEED_RANGE = 4; +constexpr float WALL_DUST_SPEED = 15; +constexpr int WALL_ROCKS = 8; +constexpr float WALL_ROCK_OUT = 100; +constexpr float WALL_THROW_REACH = 150; +constexpr float DIZZY_FRICTION = 0.7f; +constexpr int DIZZY_RAIN_END = 10; +constexpr uint32_t DIZZY_TARGET_ODDS = 5; +constexpr float DIZZY_SPOT_MARGIN = 10; +constexpr float DIZZY_SPOT_STEP = 64; +constexpr float RAIN_HEIGHT = -400; +constexpr float BUMBINO_RAIN_FALL_ACCEL = 2; +constexpr float RAIN_SCALE = 1.2f; +constexpr float RAIN_SCALE_RANGE = 0.40000004f; +constexpr float RAIN_FALL_RANGE = 10; +constexpr float CHARGING_DAMAGE_MIN = 2; +constexpr float CELL_HALF_STEP = 0.5f; + +// Its leaving: an item from its list where items spawn, in a poof. +constexpr float BUMBINO_LEAVE_FRICTION = 0.5f; + +// A cloud of its trail behind it, every 2 frames. +static void bumbino_trail_spawn(Entity_NPC& npc) +{ + if (!npc.GetIntervalTicks(DUST_EVERY, 0)) return; + uint32_t seed = Random(); + Vector drift = random_direction(); + Vector velocity = vector_add(vector_scale(npc.velocity, DUST_TRAIL_SHARE), vector_add(drift, drift)); + auto* cloud = static_cast(g_game->Spawn( + {.position = npc.pos, .velocity = velocity, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = seed})); + cloud->rotation = random_unit() * BUMBINO_DUST_SPIN + BUMBINO_DUST_SPIN_MIN; + cloud->SetTimeout((int)(Random() % DUST_TRAIL_RANGE) + DUST_TRAIL_FRAMES); + cloud->SetColor(BUMBINO_DUST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + cloud->renderDepthOffset = BUMBINO_DUST_DEPTH; +} + +// A cloud thrown off a slam or a wall: spinning either way, sized 0.9 to 1.2, lasting 20 to 39 frames. +static void bumbino_burst_dust(Entity_NPC& npc, const Vector& position, const Vector& velocity) +{ + auto* cloud = static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = Random()})); + float side = Random() & 1 ? 1.0f : -1.0f; + cloud->rotation = (random_unit() * BUMBINO_DUST_SPIN + BUMBINO_DUST_SPIN_MIN) * side; + float scale = random_unit() * BUMBINO_DUST_SCALE_RANGE + BUMBINO_DUST_SCALE; + cloud->sprite.scale = vector_make(scale, scale); + cloud->SetTimeout((int)(Random() % SLAM_DUST_RANGE) + SLAM_DUST_FRAMES); + cloud->SetColor(BUMBINO_DUST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// Players within a reach of a spot are thrown away from it. +static void bumbino_players_throw(Entity_NPC& npc, const Vector& from, float reach) +{ + for (Entity_Player* player : g_game->playerManager.playerList) + { + Vector away = vector_sub(player->pos, from); + if (vector_length(away) >= reach) continue; + player->TryThrow(EntityRef(&npc), vector_scale(vector_normalized(away), PLAYER_THROW_SPEED), PLAYER_THROW_HEIGHT); + } +} + +// Its target ahead by a tenth of a second per unit of distance. +static Vector bumbino_lead(Entity_NPC& npc) +{ + Entity* target = npc.GetPlayerTarget(); + float distance = vector_distance(npc.pos, target->pos); + return vector_add(target->pos, vector_scale(target->velocity, distance * BUMBINO_LEAD)); +} + +// Back to rest for 10 to 29 frames. +static void bumbino_rest(Entity_NPC& npc) +{ + npc.state = BUMBINO_REST; + npc.i1 = (int)(Random() % REST_SHORT_RANGE) + REST_SHORT_FRAMES; +} + +// Starts a swipe (aimed or stuck): its lunge waits for the Shoot event. +static void bumbino_swipe_start(Entity_NPC& npc, int swipe) +{ + npc.stateFrame = swipe; + npc.v1 = {}; + npc.state = BUMBINO_SWIPE; + npc.sprite.Play("Swipe", PLAY_FORCED); + npc_sound_play(SOUND_BUMBINO_PUNCH, 1, 2, 1); +} + +// The nearest free coin it can walk to, kept a while once picked. +static void bumbino_coin_update(Entity_NPC& npc) +{ + Entity* coin = npc.entityRef.get(); + bool isValid = !coin || (!coin->isDead && coin->type == ENTITY_PICKUP && coin->variant == PICKUP_COIN); + if (isValid && !(npc.IsFrame(COIN_SEARCH_EVERY, 0) && (!coin || (Random() & COIN_KEEP_MASK) == 0))) return; + if (!isValid) npc.entityRef = nullptr; + + Entity* nearest = nullptr; + float nearestDistance = COIN_REACH_SQUARED; + for (Entity* candidate : entity_query(ENTITY_PICKUP, PICKUP_COIN)) + { + if (candidate->isDead || static_cast(candidate)->price != 0) continue; + if (!npc.pathfinder.HasPathToPos(candidate->pos, false)) continue; + float distance = vector_length_squared(vector_sub(npc.pos, candidate->pos)); + if (nearestDistance <= distance) continue; + nearest = candidate; + nearestDistance = distance; + } + if (nearest) npc.entityRef = nearest; +} + +// Walking after coins or its target, swiping or ramming when it lines up. +static void bumbino_walk_update(Entity_NPC& npc, int ticks) +{ + bumbino_coin_update(npc); + npc.sprite.Play("Walk"); + if (npc.sprite.IsEventTriggered("Step")) + { + npc.PlaySound(SOUND_MEAT_IMPACTS, 1, 2, false, 1); + npc.stateFrame = STEP_PAUSE - ticks; + npc.friction *= STEP_FRICTION; + } + else if (npc.stateFrame > 0) + { + npc.stateFrame -= ticks; + npc.friction *= STEP_FRICTION; + } + + Entity* coin = npc.entityRef.get(); + Vector goal = coin ? coin->pos : npc.CalcTargetPosition(0); + if (!coin && npc.pos.y > Room::GetCenterPos().y) + { + Vector up = vector_sub(room_laser_target_get(goal, vector_make(0, -1)), goal); + float length = vector_length(up); + if (length > WALK_REACH_BELOW && length > 0) up = vector_scale(up, WALK_REACH_BELOW / length); + goal = vector_add(goal, up); + } + npc.pathfinder.FindGridPath(goal, coin ? WALK_COIN_SPEED : BUMBINO_WALK_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); + npc.i1 -= ticks; + npc.sprite.isFlipX = npc.pos.x < goal.x; + + if (npc.aiCounter >= STUCK_FRAMES && npc.projectileCooldown <= 0) bumbino_swipe_start(npc, SWIPE_STUCK); + else if (coin) npc.i1 = std::max(npc.i1, COIN_WALK_FRAMES); + else + { + Vector lead = bumbino_lead(npc); + bool isSwiping = (Random() & SWIPE_MASK) == 0 && std::abs(lead.y - npc.pos.y) <= SWIPE_LEVEL && + std::abs(lead.x - npc.pos.x) <= SWIPE_ACROSS && + (npc.projectileCooldown < 1 || Random() % SWIPE_HOT_ODDS == 0); + if (isSwiping) bumbino_swipe_start(npc, SWIPE_AIMED); + else if (std::abs(lead.x - npc.pos.x) <= RAM_ACROSS && Random() % RAM_ODDS == 0) + { + npc.state = BUMBINO_RAM; + npc.v1 = vector_sub(lead, npc.pos); + npc.sprite.Play(npc.v1.y >= 0 ? "DownCharge" : "UpCharge"); + npc.stateFrame = 0; + } + } + if (npc.i1 < 1) bumbino_rest(npc); +} + +// Dizzy after a wall: it rains rocks, then shakes it off. +static void bumbino_dizzy_update(Entity_NPC& npc, int ticks) +{ + npc.friction *= DIZZY_FRICTION; + bool isFinished = npc.sprite.IsFinished(); + if (npc.stateFrame != 0) + { + if (!isFinished) return; + npc_sound_play(SOUND_BUMBINO_MISC, 1, 2, 1); + return bumbino_rest(npc); + } + if (isFinished) + { + npc.sprite.Play("Dizzy"); + npc_sound_play(SOUND_BUMBINO_DIZZY, 1, 2, 1); + } + for (int tick = 0; tick < ticks; tick++) + { + npc.i1--; + if (npc.i1 <= DIZZY_RAIN_END || (npc.i1 & 1) != 0) continue; + Room& room = *g_game->room; + Vector spot = Random() % DIZZY_TARGET_ODDS == 0 + ? npc.CalcTargetPosition(0) + : room_free_pickup_position_find({.position = room.GetRandomPosition(DIZZY_SPOT_MARGIN), .step = DIZZY_SPOT_STEP}); + ProjectileParams params; + params.heightModifier = RAIN_HEIGHT; + params.fallingAccelModifier = BUMBINO_RAIN_FALL_ACCEL; + params.scale = RAIN_SCALE - random_unit() * RAIN_SCALE_RANGE; + params.variant = PROJECTILE_ROCK; + params.fallingSpeedModifier = random_unit() * RAIN_FALL_RANGE + 0; + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float speed = random_unit(); + npc.FireProjectiles(spot, vector_make(std::cos(angle) * speed, std::sin(angle) * speed), PROJECTILES_SINGLE, params); + } + if (npc.i1 >= 0) return; + npc.sprite.Play("ShakeOff"); + npc_sound_play(SOUND_BUMBINO_SNAP_OUT, 1, 2, 1); + npc.stateFrame++; +} + +// The swipe's hitbox knocks back and hurts what it touches, and shakes coins out of players. +static void bumbino_hitbox_update(Entity_NPC& npc) +{ + Capsule hitbox; + npc.GetNullCapsule(hitbox, "Hitbox"); + if (hitbox.radius <= 0) return; + // The hitspheres debug view (debug flag 6) is left out until Entity::GetDebugShape is written. + + for (Entity* other : entity_query_radius(hitbox.center, hitbox.halfLength + hitbox.radius, QUERY_ALL)) + { + if (other->entityCollisionClass == ENTCOLL_NONE || other->entityGridCollisionClass == GRIDCOLL_BULLET || other == &npc) + continue; + if (!Capsule::Collide(hitbox, other->GetCollisionCapsule({}))) continue; + + Vector away = vector_normalized(vector_sub(other->pos, npc.pos)); + other->velocity = vector_add(other->velocity, vector_scale(away, SWIPE_KNOCK)); + bool isFriend = other->type == ENTITY_PLAYER || other->type == ENTITY_FAMILIAR; + other->TakeDamage(isFriend ? SWIPE_PLAYER_DAMAGE : SWIPE_DAMAGE, 0, EntityRef(&npc), SWIPE_HIT_COUNTDOWN); + + auto* player = other->ToPlayer(); + bool isRobbed = player && player->variant == 0 && !player->isCoopGhost && + !player->HasInvincibility(0, EntityRef()) && player->numCoins > 0; + if (!isRobbed) continue; + player->AddCoins(-1); + int dropped = std::min((int)(Random() % COIN_LOSS_RANGE) + 1, player->numCoins); + for (int i = 0; i < dropped; i++) + { + uint32_t seed = Random(); + Vector knock = vector_scale(away, COIN_KNOCK); + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float speed = random_unit() * BUMBINO_COIN_SPEED_RANGE + COIN_SPEED; + Vector velocity = vector_add(knock, vector_make(std::cos(angle) * speed, std::sin(angle) * speed)); + g_game->Spawn({.position = player->pos, + .velocity = velocity, + .subType = COIN_DROPPED_SUBTYPE, + .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, + .seed = seed}); + } + player->AddCoins(-dropped); + } +} + +// The swipe: a lunge across (and toward its target's height), its hitbox live, swiping back while stuck, ending in a +// slam. Whether it lunges, and whether it hit a wall hard. +static bool bumbino_swipe_update(Entity_NPC& npc, bool& isWallImpact) +{ + npc.friction *= BUMBINO_SWIPE_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + Entity* target = npc.GetPlayerTarget(); + float distance = vector_distance(npc.pos, target->pos); + float climb = distance <= SWIPE_NEAR ? 0 : (target->pos.y - npc.pos.y) / distance; + npc.v1 = vector_make(npc.sprite.isFlipX ? SWIPE_SPEED : -SWIPE_SPEED, std::clamp(climb * SWIPE_CLIMB, -SWIPE_CLIMB, SWIPE_CLIMB)); + if (npc.stateFrame == 0) + { + float aim = (target->pos.x - npc.pos.x) / SWIPE_AIM_SHARE; + npc.v1.x = npc.v1.x >= 0 ? std::clamp(aim, SWIPE_AIM_MIN, SWIPE_SPEED) : std::clamp(aim, -SWIPE_SPEED, -SWIPE_AIM_MIN); + } + } + + bool isLunging = false; + if (!vector_is_zero(npc.v1)) + { + bumbino_trail_spawn(npc); + npc.AddVelocity_divided(npc.v1, false); + npc.v1 = vector_scale(npc.v1, timescale_factor(SWIPE_DRAG, npc.speedMultiplier)); + if (std::abs(npc.v1.x) < SWIPE_STILL) npc.v1 = {}; + bool isHard = npc.isCollidesWithGrid && vector_length(npc.gridCollisionVelocity) > SWIPE_WALL_SPEED; + if (isHard) isWallImpact = vector_dot(vector_normalized(npc.gridCollisionVelocity), npc.gridCollisionNormal) > SWIPE_WALL_FACING; + isLunging = true; + } + bumbino_hitbox_update(npc); + + if (npc.stateFrame > 0 && npc.sprite.IsEventTriggered("Sound")) + { + npc.stateFrame--; + npc.sprite.isFlipX = !npc.sprite.isFlipX; + npc.sprite.Play("Swipe", PLAY_FORCED); + npc_sound_play(SOUND_BUMBINO_PUNCH, 1, 2, 1); + npc.sprite.SetFrame((float)SWIPE_AGAIN_FRAME); + } + if (npc.sprite.IsPlaying()) return isLunging; + if (npc.stateFrame < 0) + { + npc.state = BUMBINO_REST; + npc.i1 = 1; + npc.projectileCooldown = 1; + } + else + { + npc.sprite.isFlipX = false; + npc.sprite.Play("GroundSlam"); + npc.state = BUMBINO_SLAM; + } + return isLunging; +} + +// The slam: dust, crackwaves, a ring of rocks and rock particles, throwing players near. +static void bumbino_slam_update(Entity_NPC& npc) +{ + npc.friction *= SLAM_FRICTION; + if (npc.sprite.IsEventTriggered("Sound")) npc_sound_play(SOUND_BUMBINO_SLAM, 1, 2, 1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + Vector hit = vector_add(npc.pos, npc.GetNullOffset("Hitbox")); + game_shake_screen(BUMBINO_SLAM_SHAKE); + for (int i = 0; i < SLAM_DUST; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float speed = random_unit() * BUMBINO_SLAM_DUST_SPEED_RANGE + SLAM_DUST_SPEED; + bumbino_burst_dust(npc, hit, vector_make(std::cos(angle) * speed, std::sin(angle) * speed)); + } + for (int i = 0; i < SLAM_CRACKWAVES; i++) + { + auto* wave = static_cast(g_game->Spawn( + {.position = hit, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CRACKWAVE, .seed = Random()})); + wave->parent = &npc; + wave->rotation = (float)i * BUMBINO_CRACKWAVE_STEP + BUMBINO_CRACKWAVE_FIRST; + } + npc_sound_play(SOUND_HELLBOSS_GROUNDPOUND, 1, BUMBINO_SLAM_SOUND_DELAY, 1); + game_shake_screen(BUMBINO_SLAM_SHAKE); + npc.MakeGroundPoof(hit, SLAM_POOF_COLOR, 1); + ProjectileParams params; + params.variant = PROJECTILE_ROCK; + params.scale = SLAM_ROCK_SCALE; + npc.FireProjectiles(hit, vector_make(BUMBINO_SLAM_ROCK_SPEED, 0), PROJECTILES_EIGHT, params); + for (int i = 0; i < BUMBINO_SLAM_PARTICLES; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float speed = random_unit() + PARTICLE_SPEED_MIN; + Vector direction = vector_make(std::cos(angle) * speed, std::sin(angle) * speed * PARTICLE_FLATTEN); + uint32_t seed = Random(); + int subType = Random() % PARTICLE_PLAIN_ODDS != 0 ? PARTICLE_DARK_SUBTYPE : 0; + g_game->Spawn({.position = vector_add(hit, vector_scale(direction, PARTICLE_OUT)), + .velocity = vector_scale(direction, BUMBINO_PARTICLE_SPEED), + .subType = subType, + .type = ENTITY_EFFECT, + .variant = EFFECT_ROCK_PARTICLE, + .seed = seed}); + } + bumbino_players_throw(npc, hit, SLAM_THROW_REACH); + } + if (npc.sprite.IsPlaying()) return; + npc.state = BUMBINO_REST; + npc.i1 = (int)(Random() % REST_SHORT_RANGE) + REST_SHORT_FRAMES; + npc.projectileCooldown = (int)(Random() % BUMBINO_COOLDOWN_RANGE) + COOLDOWN_FRAMES; +} + +// The ram up or down. Whether it lunges, and whether it hit a wall. +static bool bumbino_ram_update(Entity_NPC& npc, bool& isWallImpact) +{ + npc.friction *= SLAM_FRICTION; + if (npc.stateFrame == 0) + { + if (npc.sprite.IsEventTriggered("Sound")) npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + if (!npc.sprite.IsEventTriggered("Shoot")) return false; + npc_sound_play(SOUND_BUMBINO_RAM, 1, 2, 1); + npc.stateFrame++; + float speed = npc.v1.y <= 0 ? RAM_UP_SPEED : RAM_DOWN_SPEED; + npc.v1 = vector_make(0, speed); + npc.AddVelocity_divided(vector_make(0, speed + speed), false); + return false; + } + if (npc.stateFrame != 1) return false; + bumbino_trail_spawn(npc); + npc.AddVelocity_divided(npc.v1, false); + isWallImpact = npc.isCollidesWithGrid; + return true; +} + +// The butt bomb: a fart and a butt bomb lobbed toward its target. +static void bumbino_butt_bomb_update(Entity_NPC& npc) +{ + npc.friction *= SLAM_FRICTION; + if (npc.sprite.IsEventTriggered("Sound")) npc.PlaySound(SOUND_BUMBINO_HIT_WALL, 1, 2, false, 1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + Vector origin = vector_add(npc.pos, npc.GetNullOffset("Hitbox")); + game_fart({.position = origin, .source = &npc, .radius = BUMBINO_BUTT_FART_RADIUS}); + float side = npc.sprite.isFlipX ? BUTT_BOMB_LEFT : BUTT_BOMB_RIGHT; + Vector aim = vector_sub(bumbino_lead(npc), origin); + uint32_t seed = Random(); + float angle = angle_approach(side, vector_angle(aim), BUTT_BOMB_TURN); + auto* bomb = static_cast(g_game->Spawn({.position = origin, + .velocity = vector_scale(vector_from_angle(angle), BUTT_BOMB_SPEED), + .spawner = &npc, + .type = ENTITY_BOMB, + .variant = BOMB_BUTT, + .seed = seed})); + bomb->SetExplosionCountdown(BUTT_BOMB_FUSE); + bomb->entityCollisionClass = ENTCOLL_NONE; + } + if (!npc.sprite.IsPlaying()) bumbino_rest(npc); +} + +// A lunge breaks the rocks it runs into (bridging a pit behind each). Whether any broke. +static bool bumbino_rocks_break(Entity_NPC& npc) +{ + Room& room = *g_game->room; + bool isBroken = false; + for (Vector point : npc.collisionPoints) + { + Vector at = vector_add(vector_add(vector_scale(npc.gridCollisionVelocity, CELL_HALF_STEP), npc.pos), point); + int column = (int)((at.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + CELL_HALF_STEP); + int row = (int)((at.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + CELL_HALF_STEP); + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) continue; + int index = room.gridWidth * row + column; + GridEntity* rock = room.GetGridEntity((uint32_t)index); + uint32_t collision = room.GetGridCollision(index); + bool isSolid = collision == COLLISION_SOLID || collision == COLLISION_OBJECT; + if (!isSolid || !rock || rock->collisionClass != COLLISION_SOLID) continue; + if (!rock->Destroy(false, EntityRef(&npc))) continue; + + Vector cell = vector_make((float)(rock->gridIndex % room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_X, + (float)(rock->gridIndex / room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_Y); + Vector beyond = vector_add(cell, vector_scale(vector_cardinal(vector_sub(cell, npc.pos)), GRID_CELL_SIZE)); + int beyondIndex = room.GetGridIndex(beyond); + if (beyondIndex >= 0) room_bridge_make(room.GetGridEntity((uint32_t)beyondIndex), rock); + isBroken = true; + } + return isBroken; +} + +// A lunge into a wall: a crash of dust and rocks, players thrown, and it reels dizzy. +static void bumbino_wall_impact(Entity_NPC& npc) +{ + npc_sound_play(SOUND_HELLBOSS_GROUNDPOUND, 1, BUMBINO_SLAM_SOUND_DELAY, 1); + game_shake_screen(BUMBINO_SLAM_SHAKE); + npc.sprite.Play("WallImpact"); + npc_sound_play(SOUND_BUMBINO_HIT_WALL, 1, 2, 1); + npc.state = BUMBINO_DIZZY; + npc.stateFrame = 0; + npc.i1 = BUMBINO_DIZZY_FRAMES; + npc.GetPlayerTarget(); + for (int i = 0; i < WALL_DUST; i++) + { + float angle = random_unit() * WALL_DUST_SPREAD + WALL_DUST_FIRST; + Vector off = vector_rotated(npc.gridCollisionNormal, angle); + float speed = random_unit() * WALL_DUST_SPEED_RANGE + WALL_DUST_SPEED; + bumbino_burst_dust(npc, npc.pos, vector_scale(off, speed)); + } + ProjectileParams params; + params.variant = PROJECTILE_ROCK; + npc.FireBossProjectiles(WALL_ROCKS, vector_sub(npc.pos, vector_scale(npc.gridCollisionNormal, WALL_ROCK_OUT)), 0, params); + bumbino_players_throw(npc, npc.pos, WALL_THROW_REACH); +} + +// 00499de0 Bumbino walks after coins (twelve and it leaves an item) or its target, swiping, ramming, slamming and +// throwing butt bombs. Lunging into a wall leaves it dizzy under falling rocks. +void boss_bumbino_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + npc.aiCounter = npc.isCollidesWithGrid ? npc.aiCounter + 1 : 0; + if (npc.isDead) npc_sound_play(SOUND_BUMBINO_DEATH, 1, 2, 1); + + bool isLunging = false; + bool isWallImpact = false; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = BUMBINO_REST; + npc.i2 = 0; + npc.aiCounter = 0; + npc.i1 = (int)(Random() % BUMBINO_REST_RANGE) + BUMBINO_REST_FRAMES; + npc.pathfinder.canCrushRocks = true; + break; + case BUMBINO_REST: + { + npc.friction *= REST_FRICTION; + npc.sprite.Play("Idle2"); + npc.i1 -= ticks; + if (npc.i1 < 1) + { + npc.state = BUMBINO_WALK; + npc.stateFrame = 0; + npc.i1 = (int)(Random() % WALK_RANGE) + WALK_FRAMES; + break; + } + Vector lead = bumbino_lead(npc); + Vector gap = vector_sub(lead, npc.pos); + Vector direction = vector_normalized(gap); + bool isBombing = direction.y > BUTT_BOMB_DOWN_MIN && direction.y < BUTT_BOMB_DOWN_MAX && + room_check_line(npc.pos, lead, LINE_MODE_CELL, 0) && Random() % BUTT_BOMB_ODDS == 0; + if (!isBombing) break; + npc.sprite.Play("ButtBomb"); + npc.state = BUMBINO_BUTT_BOMB; + npc.sprite.isFlipX = gap.x < 0; + break; + } + case BUMBINO_WALK: + bumbino_walk_update(npc, ticks); + break; + case BUMBINO_DIZZY: + bumbino_dizzy_update(npc, ticks); + break; + case BUMBINO_SWIPE: + isLunging = bumbino_swipe_update(npc, isWallImpact); + break; + case BUMBINO_SLAM: + bumbino_slam_update(npc); + break; + case BUMBINO_RAM: + isLunging = bumbino_ram_update(npc, isWallImpact); + break; + case BUMBINO_BUTT_BOMB: + bumbino_butt_bomb_update(npc); + break; + case BUMBINO_LEAVE: + npc.friction *= BUMBINO_LEAVE_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + int item = g_game->itemPool.GetCollectibleFromList(BUMBINO_ITEMS, npc.initSeed, COLLECTIBLE_POOP, LIST_PICK_BLACKLIST); + uint32_t seed = npc.dropRNG.Next(); + Entity* pedestal = g_game->Spawn({.position = collectible_spawn_position(npc.pos), + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = seed}); + g_game->Spawn({.position = pedestal->pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + npc_sound_play(SOUND_THUMBSUP, 1, 2, 1); + } + if (npc.sprite.IsPlaying()) break; + npc.Remove(); + return g_game->room->TriggerBossDeath(npc); + } + + npc.collisionDamage = isLunging ? std::max(npc.config->collisionDamage, CHARGING_DAMAGE_MIN) : npc.config->collisionDamage; + if (npc.isCollidesWithGrid && isLunging && bumbino_rocks_break(npc)) + npc.velocity = vector_scale(npc.gridCollisionVelocity, CELL_HALF_STEP); + else if (isWallImpact) bumbino_wall_impact(npc); + + if (npc.projectileCooldown > 0) npc.projectileCooldown -= ticks; + bool isCalm = npc.state == BUMBINO_REST || npc.state == BUMBINO_WALK; + if (!isCalm || npc.i2 < COINS_TO_LEAVE) return; + npc.i2 = 0; + npc.state = BUMBINO_LEAVE; + npc.sprite.Play("ItemSpawn"); + npc.sprite.isFlipX = false; + npc.RemoveStatusEffects(); + npc.entityCollisionClass = ENTCOLL_NONE; +} diff --git a/src/boss_chimera.cpp b/src/boss_chimera.cpp new file mode 100644 index 0000000..a3cca1d --- /dev/null +++ b/src/boss_chimera.cpp @@ -0,0 +1,1152 @@ +#include "boss_ai.h" +#include "boss_repentance.h" +#include "entity_config.h" +#include "entity_laser.h" +#include "loot_list.h" +#include "grid_entity.h" +#include "npc_basement.h" + +// The Chimera's states: walking, running (charging whole, at its head or rolling after it), leaping, tripping its head +// off, spitting a fly, falling back to spray shots, its brimstone, its roll and its head's throw. Its head's states: +// resting, leaping, falling, spitting shots, its charge's warning and its charge. +enum ChimeraState +{ + CHIMERA_WALK = NPC_STATE_IDLE, + CHIMERA_RUN = NPC_STATE_MOVE, + CHIMERA_LEAP = NPC_STATE_JUMP, + CHIMERA_TRIP = NPC_STATE_STOMP, + CHIMERA_SPIT_FLY = NPC_STATE_ATTACK, + CHIMERA_FALL_BACK = NPC_STATE_ATTACK2, + CHIMERA_BRIMSTONE = NPC_STATE_ATTACK3, + CHIMERA_ROLL = NPC_STATE_ATTACK4, + CHIMERA_THROW = NPC_STATE_SPECIAL, + CHIMERA_HEAD_REST = NPC_STATE_IDLE, + HEAD_LEAP = NPC_STATE_JUMP, + HEAD_FALL = NPC_STATE_STOMP, + CHIMERA_HEAD_SHOOT = NPC_STATE_ATTACK, + HEAD_ANNOUNCE = NPC_STATE_ATTACK2, + CHIMERA_HEAD_CHARGE = NPC_STATE_ATTACK3, + HEAD_CARRIED = NPC_STATE_SPECIAL +}; + +// The Chimera packs six byte cooldowns into v2, counted down every 10 frames, and its head two flags into i1: charging +// back to its body, and charging once thrown. +enum ChimeraCooldown +{ + COOLDOWN_LEAP, + COOLDOWN_SPIT, + COOLDOWN_FALL_BACK, + COOLDOWN_THROW, + COOLDOWN_ROLL, + COOLDOWN_BRIMSTONE, + CHIMERA_COOLDOWNS +}; +enum HeadFlag +{ + HEAD_TO_BODY, + HEAD_THROWN +}; +constexpr uint8_t CHIMERA_COOLDOWN = 15; +constexpr uint8_t BRIMSTONE_COOLDOWN = 9; +constexpr float COOLDOWN_EVERY = 10; + +// Its head's healthy fight: the overlay's spit of five small maggots fanned 22 degrees at 8 (a fifth slower each +// further out), one time in 40 a free frame, every 90 frames. +constexpr int HEAD_ANGRY = -1000; +constexpr int HEAD_ATTACK_COOLDOWN = 90; +constexpr uint32_t HEAD_ATTACK_ODDS = 40; +constexpr int MAGGOT_FAN = 2; +constexpr float MAGGOT_FAN_STEP = 22; +constexpr float CHIMERA_MAGGOT_SPEED = 8; +constexpr float MAGGOT_SLOWING = 0.2f; +constexpr float CHIMERA_MAGGOT_HEIGHT = -24; +constexpr float MAGGOT_RISE = -8; +constexpr float HEAD_SPLAT_SIDE = 6; +constexpr float HEAD_SPLAT_RAISE = -48; +constexpr int SPLAT_SUBTYPE = 3; +constexpr int SPLAT_BIG_SUBTYPE = 4; +constexpr ColorMod CHIMERA_GREEN_COLOR = {{1, 1, 1, 1}, {1.5f, 2, 1, 1}, {0, 0, 0}}; + +// Walking at 0.6 a step after its target (or its thrown head). Below half health it turns angry: hits do a tenth. +// Whole, every frame its cooldown is under 30 it draws a charge (8), a fly (10), a fall back (10) or nothing (600). +constexpr float CHIMERA_WALK_FRICTION = 0.7f; +constexpr float CHIMERA_WALK_SPEED = 0.6f; +constexpr int PICK_COOLDOWN = 30; +constexpr int PICK_NOTHING = 0; +constexpr int PICK_CHARGE = 1; +constexpr int PICK_SPIT = 2; +constexpr int PICK_FALL_BACK = 3; +constexpr int PICK_CHARGE_WEIGHT = 8; +constexpr int PICK_ATTACK_WEIGHT = 10; +constexpr int PICK_NOTHING_WEIGHT = 600; +constexpr float CHARGE_MASS = 1000; +constexpr float ANGRY_HEALTH = 0.5f; +constexpr float ANGRY_DAMAGE_SHARE = 0.1f; + +// Headless, one time in 60 it runs for its head, or casts brimstone when its target is 60 below or above it within +// 20 across (a fifth of a second ahead per unit). +constexpr uint32_t BODY_RUN_ODDS = 60; +constexpr float BODY_LEAD = 0.04f; +constexpr float BRIMSTONE_REACH = 60; +constexpr float BRIMSTONE_ALIGN = 20; + +// Running at 0.12 a step (0.16 angry), leaving green creep one time in three, at its target a fifth of a second ahead. +// Angry, past 120 frames one time in 15 (or past 60 heading its target's way within 300) it trips, its head flying +// off at 10. Else past 90 frames with a cooldown under 46 one time in 15 it leaps. Headless it rolls after 100 frames +// (30 without its head), turned to the nearest diagonal at 0.6 of its speed. +constexpr float CHIMERA_RUN_FRICTION = 0.96f; +constexpr float CHIMERA_RUN_SPEED = 0.12f; +constexpr float RUN_ANGRY_SPEED = 0.16f; +constexpr float RUN_LEAD = 0.2f; +constexpr int CREEP_SUBTYPE = 100; +constexpr uint32_t RUN_CREEP_ODDS = 3; +constexpr int RUN_CREEP_TIMEOUT = 20; +constexpr float RUN_SPLAT_SIZE = 0.25f; +constexpr int TRIP_LONG_RUN = 120; +constexpr uint32_t TRIP_ODDS = 15; +constexpr int TRIP_RUN = 60; +constexpr float TRIP_REACH = 300; +constexpr float TRIP_AIM = 0.94f; +constexpr float TRIP_PUSH = 5; +constexpr int LEAP_RUN = 90; +constexpr int LEAP_COOLDOWN_LIMIT = 46; +constexpr int ROLL_RUN = 100; +constexpr int ROLL_HEADLESS_RUN = 30; +constexpr float CHIMERA_ROLL_TURN = 45; +constexpr float ROLL_START_SHARE = 0.6f; + +// The leap at its target a tenth of a second ahead per unit (8 percent of the gap, 10 at most), landing in a ring of +// eight shots at 10 (or four crackwaves after the first). +constexpr float CHIMERA_LEAP_LEAD = 0.1f; +constexpr float LEAP_SHARE = 0.08f; +constexpr float CHIMERA_LEAP_MAX = 10; +constexpr float LEAP_FRICTION = 0.8f; +constexpr int LEAP_SHAKE = 8; +constexpr int LEAP_BIG_SHAKE = 12; +constexpr float LEAP_SHOT_SCALE = 1.4f; +constexpr float LEAP_SHOT_SPEED = 10; +constexpr int CHIMERA_CRACKWAVES = 4; +constexpr int CHIMERA_CRACKWAVE_SUBTYPE = 2; +constexpr float CHIMERA_CRACKWAVE_FIRST = -45; +constexpr float CHIMERA_CRACKWAVE_STEP = 90; + +// Its head comes off where its layer 1 shows (drawn at 0.65), at 10 times the trip's direction. +constexpr int CHIMERA_HEAD_LAYER = 1; +constexpr int HEAD_GUIDE_LAYER = 2; +constexpr float HEAD_LAYER_SCALE = 0.65f; +constexpr float HEAD_THROW_SPEED = 10; +constexpr float HEAD_TRIP_VOLUME = 0.7f; +constexpr int TRIP_SHAKE = 6; +constexpr float HEAD_PUSH_SHARE = 0.1f; + +// The fly: a half-size Dragon Fly held 10 below its mouth until it is flung at 15. +constexpr int DRAGON_FLY = 5; +constexpr float FLY_SCALE = 0.5f; +constexpr float FLY_HOLD_DROP = 10; +constexpr float FLY_HOP = -8; +constexpr float FLY_RAISE = -16; +constexpr float FLY_FLING = 15; +constexpr int FLY_FLUNG = NPC_STATE_SUICIDE; + +// The fall back sprays green shots every other tick to 18, sweeping 40 degrees across where its target will be, over +// 20 to 50 frames each, falling to land where the target mark shows. +constexpr float FALL_BACK_FRICTION = 0.7f; +constexpr int CHIMERA_SPRAY_END = 18; +constexpr float SPRAY_SPAN = 22; +constexpr float CHIMERA_SPRAY_LEAD = 0.2f; +constexpr float SPRAY_SWEEP = 40; +constexpr float SPRAY_SWEEP_HALF = 20; +constexpr float CHIMERA_SPRAY_FRAMES = 30; +constexpr float SPRAY_MIN_FRAMES = 20; +constexpr float SPRAY_MAX_SPEED = 10; +constexpr float SPRAY_DRAG = 0.9f; +constexpr float SPRAY_DRAG_SUM = -9.491221f; +constexpr float SPRAY_DRAG_MIN = 0.01f; +constexpr float SPRAY_START_HEIGHT = -5; +constexpr float SPRAY_GRAVITY = 21; +constexpr float SPRAY_ACCEL = 2; +constexpr float CHIMERA_SPRAY_SCALE = 1.4f; +constexpr ColorMod SPRAY_COLOR = {{1, 1, 1, 1}, {0.7f, 2, 0.5f, 1}, {0, 0, 0}}; +constexpr int SPRAY_MARK_SUBTYPE = 10; +constexpr ColorMod SPRAY_MARK_COLOR = {{0.4f, 1, 0.1f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float SPRAY_SPLAT_RAISE = -20; +constexpr float SPRAY_SPLAT_RISE = 100; +constexpr float SPRAY_SPLAT_RANGE = 16; + +// Its brimstone: a hop up at 5, a beam straight down from 4 below, then rising at 2 until it lands with a stomp. +constexpr int BRIMSTONE_START = -1; +constexpr int BRIMSTONE_HOP = -2; +constexpr int BRIMSTONE_END = -3; +constexpr float BRIMSTONE_HOP_SPEED = 5; +constexpr float BRIMSTONE_DROP = 4; +constexpr float BRIMSTONE_ANGLE = 90; +constexpr int CHIMERA_BRIMSTONE_TIMEOUT = 30; +constexpr float CHIMERA_BRIMSTONE_DEPTH = 1000; +constexpr float BRIMSTONE_RISE = 2; +constexpr int BRIMSTONE_LASER = 1; + +// The roll at 18 (14 with its head about), ending past 89 frames one time in 20. +constexpr float ROLL_SPEED = 18; +constexpr float ROLL_HEAD_SPEED = 14; +constexpr int ROLL_LONG = 89; +constexpr uint32_t ROLL_END_ODDS = 20; +constexpr float CHIMERA_THROW_FRICTION = 0.8f; +constexpr float THROW_PITCH = 0.8f; +constexpr float CHIMERA_THROW_LEAD = 0.3f; +constexpr float THROW_CHARGE_SPEED = 4; +constexpr float THROW_RAISE = -20; + +// The head: a charge's warning past 8 frames of rest, one time in four (more after leaps) in a clear line, at its +// target a twentieth of a second ahead per unit, at 3.7. It spits five shots three frames apart (two more with no +// cooldown) and hops 300 along its path at its target within 420 (or at its target a tenth ahead per unit). +constexpr int HEAD_REST_FRAMES = 8; +constexpr float HEAD_REST_FRICTION = 0.8f; +constexpr float HEAD_SHOOT_REACH = 420; +constexpr uint32_t CHIMERA_HEAD_SHOOT_ODDS = 10; +constexpr uint32_t HEAD_SHOOT_LEAPT_ODDS = 3; +constexpr int HEAD_SHOOT_LEAPS = 1; +constexpr int HEAD_SHOOT_MANY_LEAPS = 3; +constexpr float HEAD_PATH_LOOKAHEAD = 300; +constexpr float HEAD_LEAP_LEAD = 0.1f; +constexpr uint64_t HEAD_PATH_BLOCK_FLAGS = FLAG_FEAR | FLAG_CONFUSION | FLAG_SHRINK; +constexpr float HEAD_LEAP_PUSH = 1.5f; +constexpr float HEAD_LEAP_FRICTION = 0.9f; +constexpr float HEAD_LEAP_LANDING = 0.05f; +constexpr float HEAD_FALL_FRICTION = 0.93f; +constexpr int HEAD_SHOT_EVERY = 3; +constexpr int HEAD_SHOTS_END = 10; +constexpr int HEAD_SHOTS_FREE_END = 12; +constexpr int HEAD_SHOT_TRACKING = 2; +constexpr float HEAD_SHOT_SPREAD = 1.5f; +constexpr float HEAD_SHOT_FIRST_SCALE = 1.4f; +constexpr float HEAD_SHOT_FALL = -0.05f; +constexpr float CHIMERA_HEAD_SHOT_SPEED = 8; +constexpr float HEAD_SMOKE_RAISE = -10; +constexpr float HEAD_CHARGE_LEAD = 0.05f; +constexpr float CHIMERA_HEAD_CHARGE_SPEED = 3.7f; +constexpr int HEAD_CHARGES = 3; +constexpr int HEAD_BODY_CHARGE = 2; +constexpr float HEAD_BODY_LEAD = 0.1f; +constexpr float HEAD_CHARGE_END_FRICTION = 0.85f; +constexpr float HEAD_CHARGE_FRICTION = 0.93f; + +// The head bounces (1.1 down a frame, back at a fifth above 1.5), flashes red every 5 frames while thrown, and on a wall +// halves its charge (a burst of 20 shots and a splat while thrown). It bleeds a trail of creep one time in three. +constexpr float HEAD_GRAVITY = 1.1f; +constexpr float HEAD_BOUNCE_MIN = 1.5f; +constexpr float CHIMERA_HEAD_BOUNCE = -0.2f; +constexpr float HEAD_FLASH_EVERY = 5; +constexpr ColorMod HEAD_FLASH_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.75f, 0, 0}}; +constexpr int HEAD_FLASH_FRAMES = 4; +constexpr int HEAD_WALL_SHAKE = 10; +constexpr int HEAD_WALL_SHOTS = 20; +constexpr float HEAD_WALL_HOP = -8; +constexpr float HEAD_CHARGE_DRAG = 0.95f; +constexpr float HEAD_SLOW_CHARGE = 8; +constexpr float HEAD_STOPPED = 0.1f; +constexpr uint32_t HEAD_TRAIL_MASK = 3; +constexpr float HEAD_TRAIL_BACK = 4; +constexpr uint32_t HEAD_CREEP_ODDS = 3; +constexpr int HEAD_CREEP_TIMEOUT = 30; + +// A cooldown or flag byte packed into a counter. +static uint8_t& chimera_byte(void* field, int index) +{ + return static_cast(field)[index]; +} + +static uint8_t& chimera_cooldown(Entity_NPC& npc, ChimeraCooldown which) +{ + return chimera_byte(&npc.v2, which); +} + +static uint8_t& head_flag(Entity_NPC& npc, HeadFlag which) +{ + return chimera_byte(&npc.i1, which); +} + +// Whether the NPC's clock crossed a multiple of an interval this frame (the original's floor of the frame over minus +// the interval). +static bool chimera_interval_crossed(Entity_NPC& npc, float interval) +{ + return (int)((npc.prevUpdateTime + 0) / -interval) != (int)((npc.updateTime + 0) / -interval); +} + +// Its target ahead of itself by a share of a second per unit of distance from the NPC. +static Vector chimera_lead(Entity_NPC& npc, Entity& target, float share) +{ + float distance = vector_distance(npc.pos, target.pos); + return vector_add(target.pos, vector_scale(target.velocity, distance * share)); +} + +// A blood explosion following the NPC, tinted, beside its mouth. +static void chimera_splat_spawn(Entity_NPC& npc, int subType, const ColorMod& color, Vector offset) +{ + Entity* splat = g_game->Spawn( + {.position = npc.pos, .subType = subType, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + splat->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->sprite.offset = offset; + splat->renderDepthOffset = BOSS_BLOOD_DEPTH; + static_cast(splat)->FollowParent(&npc); +} + +// 0049f870 Starts a charge: ChargeBegin, a gurgle at its size's pitch, toward a spot at a speed. +static void chimera_charge_begin(Entity_NPC& npc, const Vector& target, float speed) +{ + npc.sprite.Play("ChargeBegin"); + npc.state = CHIMERA_HEAD_CHARGE; + npc_sound_play(SOUND_FART_GURG, 1, 2, champion_pitch_get(npc)); + head_flag(npc, HEAD_TO_BODY) = 0; + npc.targetPosition = vector_scale(vector_normalized(vector_sub(target, npc.pos)), speed); +} + +// 0049d100 Whether the body waits for its head: it has one, may throw it, and is walking or running. +static bool chimera_body_is_waiting(Entity_NPC& body) +{ + return body.child && chimera_cooldown(body, COOLDOWN_THROW) == 0 && + (body.state == CHIMERA_WALK || body.state == CHIMERA_RUN); +} + +// 0049cd90 The whole Chimera's head overlay: once in a while it spits a fan of maggots in a green splat. +static void chimera_head_overlay_update(Entity_NPC& npc) +{ + if (npc.projectileCooldown == HEAD_ANGRY) return; + + Vector target = npc.GetPlayerTarget()->pos; + if (npc.projectileCooldown > 0) + { + npc.projectileCooldown = std::max(npc.projectileCooldown - npc_ticks_get(npc), 0); + return; + } + if (npc.projectileCooldown == 0) + { + if (Random() % HEAD_ATTACK_ODDS != 0) return; + npc.projectileCooldown = -1; + npc.sprite.PlayOverlay("HeadAttack"); + npc.sprite.GetLayer(CHIMERA_HEAD_LAYER)->isFlipX = npc.pos.x < target.x; + return; + } + + if (npc.sprite.overlayAnimState.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_BOSS_GURGLE_ROAR, 1, 2, false, 1); + Vector aim = vector_normalized(vector_sub(target, npc.pos)); + for (int i = -MAGGOT_FAN; i <= MAGGOT_FAN; i++) + { + float speed = CHIMERA_MAGGOT_SPEED * (1 - (float)std::abs(i) * MAGGOT_SLOWING); + small_maggot_spawn(npc.pos, CHIMERA_MAGGOT_HEIGHT, vector_scale(vector_rotated(aim, (float)i * MAGGOT_FAN_STEP), speed), MAGGOT_RISE); + } + float side = npc.sprite.GetLayer(CHIMERA_HEAD_LAYER)->isFlipX ? HEAD_SPLAT_SIDE : -HEAD_SPLAT_SIDE; + chimera_splat_spawn(npc, SPLAT_SUBTYPE, COLOR_GREEN_SPLAT, vector_make(side, HEAD_SPLAT_RAISE)); + } + if (npc.sprite.overlayAnimState.IsEventTriggered("Jump")) npc.sprite.GetLayer(CHIMERA_HEAD_LAYER)->isFlipX = false; + if (npc.sprite.overlayAnimState.animData && npc.sprite.overlayAnimState.isPlaying) return; + + if (npc.state == CHIMERA_RUN) + { + npc.sprite.PlayOverlay("HeadCharge"); + if (const AnimationData* data = npc.sprite.overlayAnimState.animData) npc.sprite.overlayAnimState.SetFrameFloat((float)data->length); + } + else npc.sprite.PlayOverlay("HeadIdle"); + npc.projectileCooldown = HEAD_ATTACK_COOLDOWN; +} + +// Its walk or run, by the axis its push leans along. +static void chimera_walk_play(Entity_NPC& npc, Vector push, std::string_view vertical, std::string_view horizontal) +{ + bool isHorizontal = std::abs(push.x) > std::abs(push.y); + npc.sprite.Play(isHorizontal ? horizontal : vertical); + npc.sprite.GetLayer(0)->isFlipX = isHorizontal && push.x < 0; +} + +// Whole, it draws its next attack while its head cools down. +static void chimera_attack_pick(Entity_NPC& npc) +{ + WeightedOutcomePicker picker; + if (chimera_cooldown(npc, COOLDOWN_LEAP) == 0) picker.AddOutcomeWeight(PICK_CHARGE, PICK_CHARGE_WEIGHT); + if (chimera_cooldown(npc, COOLDOWN_SPIT) == 0) picker.AddOutcomeWeight(PICK_SPIT, PICK_ATTACK_WEIGHT); + if (chimera_cooldown(npc, COOLDOWN_FALL_BACK) == 0) picker.AddOutcomeWeight(PICK_FALL_BACK, PICK_ATTACK_WEIGHT); + picker.AddOutcomeWeight(PICK_NOTHING, PICK_NOTHING_WEIGHT); + switch (picker.PickOutcome({Random() | 1, 5, 9, 7})) + { + case PICK_CHARGE: + npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + npc.mass = CHARGE_MASS; + npc.state = CHIMERA_RUN; + npc.sprite.PlayOverlay("HeadCharge"); + npc.projectileCooldown = std::max(npc.projectileCooldown, PICK_COOLDOWN); + npc.velocity = {}; + break; + case PICK_SPIT: + npc.state = CHIMERA_SPIT_FLY; + npc.sprite.Play("SpitFly"); + break; + case PICK_FALL_BACK: + npc.state = CHIMERA_FALL_BACK; + npc.sprite.Play("FallBack"); + break; + default: + return; + } + npc.projectileDelay = 0; +} + +// Walking after its target (or its returning head), picking attacks. +static void chimera_walk_update(Entity_NPC& npc, bool isHeadReturning) +{ + npc.friction *= CHIMERA_WALK_FRICTION; + Vector target = isHeadReturning ? npc.child->pos : npc.GetPlayerTarget()->pos; + npc.pathfinder.FindGridPath(target, CHIMERA_WALK_SPEED, 0, DIRECT_PATH_FAR); + if (npc.variant == CHIMERA_WHOLE) chimera_head_overlay_update(npc); + bool isWhole = npc.variant == CHIMERA_WHOLE; + chimera_walk_play(npc, npc.velocity, isWhole ? "WalkVert" : "WalkVertHeadless", isWhole ? "WalkHori" : "WalkHoriHeadless"); + + if (npc.variant == CHIMERA_WHOLE) + { + if (npc.projectileCooldown == HEAD_ANGRY) + { + npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + npc.mass = CHARGE_MASS; + npc.state = CHIMERA_RUN; + npc.sprite.PlayOverlay("HeadAngry"); + npc.velocity = {}; + npc.projectileDelay = 0; + } + if ((uint32_t)npc.projectileCooldown < PICK_COOLDOWN) chimera_attack_pick(npc); + return; + } + + Vector lead = chimera_lead(npc, *npc.GetPlayerTarget(), BODY_LEAD); + Entity_NPC* head = npc.ChildNPC(); + bool isRunning = (chimera_cooldown(npc, COOLDOWN_ROLL) == 0 && (!head || head->state == CHIMERA_HEAD_REST) && + Random() % BODY_RUN_ODDS == 0) || !head; + if (isRunning) + { + npc.PlaySound(SOUND_BOSS_LITE_SLOPPY_ROAR, 1, 2, false, 1); + npc.mass = CHARGE_MASS; + npc.state = CHIMERA_RUN; + npc.velocity = {}; + npc.projectileDelay = 0; + } + else if (chimera_cooldown(npc, COOLDOWN_BRIMSTONE) == 0 && std::abs(lead.y - npc.pos.y) > BRIMSTONE_REACH && + std::abs(lead.x - npc.pos.x) < BRIMSTONE_ALIGN) + { + npc.state = CHIMERA_BRIMSTONE; + npc.sprite.Play("BrimstoneStart"); + npc.projectileDelay = BRIMSTONE_START; + } +} + +// Running: whole it trips its head off or leaps, headless it starts its roll. +static void chimera_run_update(Entity_NPC& npc, bool isHeadReturning) +{ + Entity* target = npc.GetPlayerTarget(); + Vector aim = isHeadReturning ? npc.child->pos : chimera_lead(npc, *target, RUN_LEAD); + Vector before = npc.velocity; + npc.pathfinder.FindGridPath(aim, npc.projectileCooldown == HEAD_ANGRY ? RUN_ANGRY_SPEED : CHIMERA_RUN_SPEED, 0, DIRECT_PATH_FAR); + Vector push = vector_sub(npc.velocity, before); + npc.friction = CHIMERA_RUN_FRICTION; + if (npc.variant == CHIMERA_WHOLE) chimera_head_overlay_update(npc); + bool isWhole = npc.variant == CHIMERA_WHOLE; + chimera_walk_play(npc, push, isWhole ? "RunVert" : "RunVertHeadless", isWhole ? "RunHori" : "RunHoriHeadless"); + npc.projectileDelay += npc_ticks_get(npc); + + if (npc.variant != CHIMERA_WHOLE) + { + Vector toward = vector_normalized(vector_sub(target->pos, npc.pos)); + if (npc.projectileDelay <= ROLL_RUN && (npc.projectileDelay <= ROLL_HEADLESS_RUN || npc.child)) return; + npc.mass = npc.config->mass; + npc.state = CHIMERA_ROLL; + npc.sprite.Play("RollBegin"); + Vector diagonal = vector_rotated(vector_cardinal(vector_rotated(toward, CHIMERA_ROLL_TURN)), -CHIMERA_ROLL_TURN); + float speed = vector_length(npc.velocity); + npc.velocity = vector_scale(diagonal, speed * ROLL_START_SHARE); + npc.targetPosition = diagonal; + npc.sprite.GetLayer(0)->isFlipX = false; + npc.projectileDelay = 0; + return; + } + + if (Random() % RUN_CREEP_ODDS == 0) + { + Entity* creep = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = CREEP_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_GREEN, + .seed = Random()}); + static_cast(creep)->SetTimeout(RUN_CREEP_TIMEOUT); + creep->Update(); + npc.MakeSplat((random_unit() * HALF + HALF) * RUN_SPLAT_SIZE)->SetColor(COLOR_GREEN_SPLAT, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + + if (npc.projectileCooldown == HEAD_ANGRY) + { + Vector toward = vector_normalized(vector_sub(target->pos, npc.pos)); + bool isTripping = (npc.projectileDelay > TRIP_LONG_RUN && Random() % TRIP_ODDS == 0) || + (npc.projectileDelay > TRIP_RUN && vector_distance(target->pos, npc.pos) < TRIP_REACH && + vector_dot(toward, vector_cardinal(push)) > TRIP_AIM); + if (!isTripping) return; + Vector axis = vector_cardinal(push); + npc.mass = npc.config->mass; + npc.state = CHIMERA_TRIP; + npc.sprite.PlayOverlay("HeadTrip"); + npc.targetPosition = toward; + npc.velocity = vector_add(npc.velocity, vector_scale(toward, TRIP_PUSH)); + chimera_walk_play(npc, axis, "TripVert", "TripHori"); + npc.sprite.GetLayer(HEAD_GUIDE_LAYER)->isFlipX = npc.sprite.GetLayer(0)->isFlipX; + } + else if (npc.projectileDelay > LEAP_RUN && npc.projectileCooldown >= 0 && npc.projectileCooldown < LEAP_COOLDOWN_LIMIT && + Random() % TRIP_ODDS == 0) + { + npc.mass = npc.config->mass; + npc.state = CHIMERA_LEAP; + npc.projectileDelay = 0; + npc.sprite.Play("Leap"); + } +} + +// The leap: at its target, landing in a ring of shots (crackwaves after the first). +static void chimera_leap_update(Entity_NPC& npc) +{ + if (npc.entityCollisionClass != ENTCOLL_NONE) npc.friction *= LEAP_FRICTION; + if (npc.sprite.IsEventTriggered("Jump")) + { + npc.velocity = vector_scale(vector_sub(chimera_lead(npc, *npc.GetPlayerTarget(), CHIMERA_LEAP_LEAD), npc.pos), LEAP_SHARE); + if (vector_length(npc.velocity) > CHIMERA_LEAP_MAX) npc.velocity = vector_scale(vector_normalized(npc.velocity), CHIMERA_LEAP_MAX); + npc.friction = 1; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.velocity = {}; + if (npc.projectileDelay == 0) + { + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); + game_shake_screen(LEAP_SHAKE); + ProjectileParams params; + params.scale = LEAP_SHOT_SCALE; + npc.FireProjectiles(npc.pos, vector_make(LEAP_SHOT_SPEED, 0), PROJECTILES_EIGHT, params); + } + else + { + npc.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, 1, 2, false, 1); + game_shake_screen(LEAP_BIG_SHAKE); + for (int i = 0; i < CHIMERA_CRACKWAVES; i++) + { + auto* wave = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = CHIMERA_CRACKWAVE_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_CRACKWAVE, + .seed = Random()})); + wave->parent = &npc; + wave->rotation = CHIMERA_CRACKWAVE_FIRST + (float)i * CHIMERA_CRACKWAVE_STEP; + } + } + npc.projectileDelay++; + } + if (npc.sprite.IsPlaying()) return; + npc.state = CHIMERA_WALK; + npc.sprite.PlayOverlay("HeadIdle"); + chimera_cooldown(npc, COOLDOWN_LEAP) = CHIMERA_COOLDOWN; +} + +// The trip: its head flies off at 10 where its layer shows, sharing its health. +static void chimera_trip_update(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + game_shake_screen(TRIP_SHAKE); + npc.variant = CHIMERA_BODY; + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, HEAD_TRIP_VOLUME, 2, false, 1); + npc.PlaySound(SOUND_PLOP, 1, 2, false, 1); + Vector layerPos = npc.sprite.GetLayer(CHIMERA_HEAD_LAYER)->pos; + Vector position = vector_add(vector_scale(layerPos, 1 / HEAD_LAYER_SCALE), npc.pos); + auto* head = static_cast(g_game->Spawn({.position = position, + .velocity = vector_scale(npc.targetPosition, HEAD_THROW_SPEED), + .type = ENTITY_CHIMERA, + .variant = CHIMERA_HEAD, + .seed = Random()})); + head->ClearEntityFlags(FLAG_APPEAR); + head->parent = &npc; + npc.child = head; + head->health = npc.health; + head->targetPosition = vector_scale(head->velocity, HEAD_PUSH_SHARE); + blood_explosion_spawn(SPLAT_SUBTYPE, head->pos, vector_make(0, HEAD_SPLAT_RAISE), COLOR_DEFAULT, {}); + npc.sprite.GetLayer(CHIMERA_HEAD_LAYER)->isVisible = false; + } + if (npc.sprite.WasEventTriggered("Shoot")) npc.friction *= LEAP_FRICTION; + if (npc.sprite.IsFinished()) npc.state = CHIMERA_WALK; +} + +// Spits a half-size Dragon Fly held under its mouth, then flings it at its target. +static void chimera_spit_fly_update(Entity_NPC& npc) +{ + npc.friction *= LEAP_FRICTION; + Vector holdOffset = vector_make(0, FLY_HOLD_DROP); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_LITTLE_SPIT, 1, 2, false, 1); + auto* fly = static_cast( + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_BOOMFLY, .variant = DRAGON_FLY, .seed = Random()})); + fly->ClearEntityFlags(FLAG_APPEAR); + fly->sprite.scale = vector_make(FLY_SCALE, FLY_SCALE); + fly->entityCollisionClass = ENTCOLL_NONE; + fly->state = NPC_STATE_SPECIAL; + fly->v1.x = FLY_HOP; + fly->posOffset = vector_make(0, FLY_RAISE); + fly->targetPosition = vector_add(npc.pos, holdOffset); + npc.child = fly; + Entity* splat = blood_explosion_spawn(SPLAT_SUBTYPE, npc.pos, {}, CHIMERA_GREEN_COLOR, {}); + static_cast(splat)->FollowParent(&npc); + } + if (Entity* fly = npc.child.get()) fly->targetPosition = vector_add(npc.pos, holdOffset); + if (npc.sprite.IsEventTriggered("Jump") && npc.child) + { + Vector toward = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.PlaySound(SOUND_CLAP, 1, 2, false, 1); + auto* fly = static_cast(npc.child.get()); + fly->state = FLY_FLUNG; + fly->sprite.scale = vector_make(1, 1); + fly->targetPosition = vector_scale(toward, FLY_FLING); + fly->entityCollisionClass = ENTCOLL_ALL; + fly->posOffset = {}; + npc.child = nullptr; + } + if (npc.sprite.IsPlaying()) return; + npc.state = CHIMERA_WALK; + npc.sprite.PlayOverlay("HeadIdle"); + chimera_cooldown(npc, COOLDOWN_SPIT) = CHIMERA_COOLDOWN; +} + +// One green shot of the fall back's spray, a share of the way through it, lobbed to land on a target mark. +static void chimera_spray_fire(Entity_NPC& npc, float progress) +{ + Entity* target = npc.GetPlayerTarget(); + float lead = vector_distance(npc.pos, target->pos) * (progress * CHIMERA_SPRAY_LEAD + 0); + Vector aim = vector_sub(vector_add(target->pos, vector_scale(target->velocity, lead)), npc.pos); + Vector landing = vector_add(vector_rotated(aim, progress * SPRAY_SWEEP - SPRAY_SWEEP_HALF), npc.pos); + Vector velocity = vector_scale(vector_sub(landing, npc.pos), 1 / (progress * CHIMERA_SPRAY_FRAMES + SPRAY_MIN_FRAMES)); + float speed = vector_length(velocity); + if (speed > SPRAY_MAX_SPEED && speed > 0) velocity = vector_scale(velocity, SPRAY_MAX_SPEED / speed); + + auto* shot = static_cast(g_game->Spawn( + {.position = npc.pos, .velocity = velocity, .spawner = &npc, .type = ENTITY_PROJECTILE, .seed = Random()})); + float flight = vector_distance(npc.pos, landing) / vector_length(velocity); + float drag = std::max((std::pow(SPRAY_DRAG, flight) - 1) * SPRAY_DRAG_SUM, SPRAY_DRAG_MIN); + shot->fallingAccel = SPRAY_ACCEL; + shot->scale = CHIMERA_SPRAY_SCALE; + shot->projectileFlags = PROJECTILE_EXPLODE; + shot->fallingSpeed = ((SPRAY_START_HEIGHT - shot->height) - (flight - drag) * SPRAY_GRAVITY) / drag; + shot->SetColor(SPRAY_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + + Entity* mark = g_game->Spawn( + {.position = landing, .subType = SPRAY_MARK_SUBTYPE, .type = ENTITY_EFFECT, .variant = EFFECT_OCCULT_TARGET, .seed = Random()}); + mark->parent = shot; + mark->sprite.color = SPRAY_MARK_COLOR; + mark->Update(); + float raise = SPRAY_SPLAT_RAISE - progress * SPRAY_SPLAT_RISE - random_unit() * SPRAY_SPLAT_RANGE; + blood_explosion_spawn(SPLAT_SUBTYPE, npc.pos, vector_make(0, raise), COLOR_GREEN_SPLAT, {}); +} + +// Falls back and sprays its green shots in a sweep across its target. +static void chimera_fall_back_update(Entity_NPC& npc) +{ + npc.friction = FALL_BACK_FRICTION; + if (npc.sprite.IsEventTriggered("Jump")) npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.projectileDelay = 1; + game_shake_screen(LEAP_SHAKE); + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); + npc.PlaySound(SOUND_GURG_BARF, 1, 2, false, 1); + } + for (int tick = 0; tick < npc_ticks_get(npc); tick++) + { + if (npc.projectileDelay <= 0) continue; + int step = ++npc.projectileDelay; + if (step > 0 && step % 2 == 0 && step < CHIMERA_SPRAY_END) chimera_spray_fire(npc, ((float)step - 0) / SPRAY_SPAN); + } + if (npc.sprite.IsPlaying()) return; + npc.state = CHIMERA_WALK; + npc.sprite.PlayOverlay("HeadIdle"); + chimera_cooldown(npc, COOLDOWN_FALL_BACK) = CHIMERA_COOLDOWN; +} + +// Headless, its brimstone: a hop, a beam down, then rising until it lands back. +static void chimera_brimstone_update(Entity_NPC& npc) +{ + if (npc.projectileDelay >= 0) + { + if (npc.sprite.IsFinished()) npc.sprite.Play("BrimstoneLoop"); + npc.velocity.y -= npc.speedMultiplier * BRIMSTONE_RISE; + if (!npc.isCollidesWithGrid || npc.gridCollisionVelocity.y >= 0) return; + npc.sprite.Play("BrimstoneEnd"); + Entity* laser = npc.entityRef.get(); + if (laser && laser->type == ENTITY_LASER) static_cast(laser)->timeout = 1; + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); + game_shake_screen(LEAP_SHAKE); + npc.projectileDelay = BRIMSTONE_END; + return; + } + + if (npc.projectileDelay == BRIMSTONE_START || npc.projectileDelay == BRIMSTONE_END) + { + npc.friction *= LEAP_FRICTION; + if (npc.projectileDelay == BRIMSTONE_END) + { + if (!npc.sprite.IsFinished()) return; + npc.state = CHIMERA_WALK; + chimera_cooldown(npc, COOLDOWN_BRIMSTONE) = BRIMSTONE_COOLDOWN; + return; + } + } + if (npc.sprite.IsEventTriggered("Jump")) + { + npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + npc.projectileDelay = BRIMSTONE_HOP; + npc.velocity.y += BRIMSTONE_HOP_SPEED; + } + if (!npc.sprite.IsEventTriggered("Shoot")) return; + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = vector_make(npc.pos.x, npc.pos.y + BRIMSTONE_DROP), + .source = &npc, + .angleDegrees = BRIMSTONE_ANGLE, + .timeout = CHIMERA_BRIMSTONE_TIMEOUT, + .variant = BRIMSTONE_LASER}); + laser->renderDepthOffset = CHIMERA_BRIMSTONE_DEPTH; + laser->SetColor(CHIMERA_GREEN_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + laser->Update(); + npc.SetRef_bec(laser); + npc.projectileDelay = 0; +} + +// Headless, its roll: faster without its head, ending at random after 89 frames when its head is about. +static void chimera_roll_update(Entity_NPC& npc) +{ + if (npc.projectileDelay < 0 && npc.child) + { + npc.friction *= CHIMERA_WALK_FRICTION; + if (!npc.sprite.IsFinished()) return; + npc.state = CHIMERA_WALK; + chimera_cooldown(npc, COOLDOWN_ROLL) = CHIMERA_COOLDOWN; + return; + } + npc.friction *= LEAP_FRICTION; + if (npc.sprite.IsFinished()) npc.sprite.Play("Roll"); + if (!vector_is_zero(npc.velocity)) + npc.velocity = vector_scale(vector_normalized(npc.velocity), npc.child ? ROLL_HEAD_SPEED : ROLL_SPEED); + npc.projectileDelay += npc_ticks_get(npc); + if (npc.projectileDelay <= ROLL_LONG || Random() % ROLL_END_ODDS != 0 || !npc.child) return; + npc.projectileDelay = -1; + npc.sprite.Play("RollEnd"); +} + +// Headless, the throw: it pulls its head back in and hurls it, charging, at its target. +static void chimera_throw_update(Entity_NPC& npc) +{ + npc.friction = CHIMERA_THROW_FRICTION; + if (npc.sprite.IsEventTriggered("Jump")) npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + Entity_NPC* head = npc.ChildNPC(); + bool isCarried = head && head->state == HEAD_CARRIED; + if (isCarried) head->velocity = vector_sub(npc.pos, head->pos); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_SHELLGAME, 1, 2, false, THROW_PITCH); + if (isCarried) + { + head->entityCollisionClass = ENTCOLL_ALL; + chimera_charge_begin(*head, chimera_lead(npc, *npc.GetPlayerTarget(), CHIMERA_THROW_LEAD), THROW_CHARGE_SPEED); + head_flag(*head, HEAD_THROWN) = 1; + head->posOffset.y = THROW_RAISE; + head->isVisible = true; + head->velocity = vector_scale(head->targetPosition, 2); + } + } + if (!npc.sprite.IsFinished()) return; + npc.state = CHIMERA_WALK; + chimera_cooldown(npc, COOLDOWN_THROW) = CHIMERA_COOLDOWN; +} + +// Before its update, the whole Chimera shows its head's layer where its guide layer shows. +static void chimera_head_layer_place(Entity_NPC& npc) +{ + if (npc.variant != CHIMERA_WHOLE || !npc.sprite.animState.animData || !npc.sprite.overlayAnimState.animData) return; + if (npc.state < CHIMERA_WALK) return; + + npc.sprite.GetLayer(HEAD_GUIDE_LAYER)->isVisible = false; + const AnimationFrame* frame = npc.sprite.animState.GetLayerFrame(HEAD_GUIDE_LAYER); + LayerState& head = *npc.sprite.GetLayer(CHIMERA_HEAD_LAYER); + head.isVisible = frame && frame->isVisible; + if (!head.isVisible) return; + float frameX = npc.sprite.GetLayer(HEAD_GUIDE_LAYER)->isFlipX ? -frame->pos.x : frame->pos.x; + head.pos = vector_make(frameX, frame->pos.y); + head.size = frame->scale; +} + +// Its body catches its returning head when that charges into it, to throw it. +static void chimera_head_catch(Entity_NPC& npc) +{ + Entity* collider = npc.collisionEntity; + if (!Entity::is_enemy_type(collider->type)) return; + Entity* head = npc.child.get(); + if (collider != head && collider != npc.parent.get()) return; + + auto* headNpc = static_cast(head); + bool isCaught = npc.variant == CHIMERA_BODY && collider->type == ENTITY_CHIMERA && collider->variant == CHIMERA_HEAD && + head && chimera_body_is_waiting(npc) && headNpc->state == CHIMERA_HEAD_CHARGE && head_flag(*headNpc, HEAD_TO_BODY); + if (isCaught) + { + npc.state = CHIMERA_THROW; + headNpc->state = HEAD_CARRIED; + head->isVisible = false; + npc.velocity = vector_add(npc.velocity, head->velocity); + head->velocity = {}; + head->entityCollisionClass = ENTCOLL_NONE; + npc.sprite.Play("ThrowHead"); + } + npc.collisionResult = 0; +} + +// The cooldowns count down every 10 frames. Angry below half health, hits do a tenth. No blast but a player's hurts it. +static void chimera_end_update(Entity_NPC& npc) +{ + for (int tick = 0; tick < npc.GetIntervalTicks(COOLDOWN_EVERY, 0); tick++) + for (int i = 0; i < CHIMERA_COOLDOWNS; i++) + if (chimera_cooldown(npc, (ChimeraCooldown)i) != 0) chimera_cooldown(npc, (ChimeraCooldown)i)--; + + if (npc.variant == CHIMERA_WHOLE && npc.projectileCooldown != HEAD_ANGRY && npc.health / npc.maxHitPoints < ANGRY_HEALTH) + { + npc.projectileCooldown = HEAD_ANGRY; + npc.health = npc.maxHitPoints * ANGRY_HEALTH; + } + for (DamageEvent& hit : npc.damageEvents) + if ((hit.damageFlags & DAMAGE_EXPLOSION) && hit.source.spawnerType != ENTITY_PLAYER) + { + npc.pendingDamage -= hit.damage; + hit.damage = 0; + } + if (npc.projectileCooldown != HEAD_ANGRY || npc.variant != CHIMERA_WHOLE) return; + npc.pendingDamage = 0; + for (DamageEvent& hit : npc.damageEvents) + { + hit.damage *= ANGRY_DAMAGE_SHARE; + npc.pendingDamage += hit.damage; + } +} + +// 0049d130 The Chimera walks after its target, charging, leaping, spitting a fly and falling back to spray shots. When +// angry it trips its head off. Headless it rolls, casts brimstone and throws its head when that charges back into it. +void chimera_body_update(Entity_NPC& npc) +{ + Entity* head = npc.child.get(); + bool isHeadReturning = head && chimera_body_is_waiting(npc) && head_flag(*static_cast(head), HEAD_TO_BODY); + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return chimera_head_layer_place(npc); + if (npc.aiCallPhase == AI_PHASE_COLLISION) return chimera_head_catch(npc); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = CHIMERA_WALK; + npc.sprite.PlayOverlay("HeadIdle"); + npc.aiCallFlags = AI_CALL_PRE_UPDATE | AI_CALL_COLLISION; + npc.projectileCooldown = 0; + npc.v2 = {}; + break; + case CHIMERA_WALK: + chimera_walk_update(npc, isHeadReturning); + break; + case CHIMERA_RUN: + chimera_run_update(npc, isHeadReturning); + break; + case CHIMERA_LEAP: + chimera_leap_update(npc); + break; + case CHIMERA_TRIP: + chimera_trip_update(npc); + break; + case CHIMERA_SPIT_FLY: + chimera_spit_fly_update(npc); + break; + case CHIMERA_FALL_BACK: + chimera_fall_back_update(npc); + break; + case CHIMERA_BRIMSTONE: + chimera_brimstone_update(npc); + break; + case CHIMERA_ROLL: + chimera_roll_update(npc); + break; + case CHIMERA_THROW: + chimera_throw_update(npc); + break; + } + chimera_end_update(npc); +} + +// The head at rest: its charge (at its target, or a leap and shots when its body is busy). +static void chimera_head_rest_update(Entity_NPC& npc) +{ + npc.friction *= HEAD_REST_FRICTION; + npc.sprite.Play("Idle"); + npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame <= HEAD_REST_FRAMES) return; + + Vector target = npc.GetPlayerTarget()->pos; + auto* body = static_cast(npc.parent.get()); + bool isCharging = room_check_line(npc.pos, target, LINE_MODE_PROJECTILE, 0) && (Random() & 3) == 0 && + chimera_cooldown(npc, COOLDOWN_LEAP) == 0 && (!body || body->state == CHIMERA_WALK); + if (isCharging || !body) + { + npc.sprite.isFlipX = target.x - npc.pos.x > 0; + npc.sprite.Play("ChargeAnnounce"); + npc.state = HEAD_ANNOUNCE; + npc.i2 = 0; + npc.stateFrame = -1; + return; + } + + bool isShooting = Random() % CHIMERA_HEAD_SHOOT_ODDS == 0 || (npc.i2 > HEAD_SHOOT_LEAPS && Random() % HEAD_SHOOT_LEAPT_ODDS == 0) || + (npc.i2 > HEAD_SHOOT_MANY_LEAPS && (Random() & 1) == 0); + if (isShooting && vector_distance(npc.pos, target) < HEAD_SHOOT_REACH && (!body || body->state == CHIMERA_WALK)) + { + npc.sprite.isFlipX = target.x - npc.pos.x > 0; + npc.sprite.Play("Shoot"); + npc.state = CHIMERA_HEAD_SHOOT; + npc.i2 = 0; + npc.stateFrame = -1; + npc.projectileCooldown = 0; + return; + } + + Vector landing = npc.CalcTargetPosition(0); + if (!npc.HasEntityFlags(HEAD_PATH_BLOCK_FLAGS) && !room_check_line(npc.pos, target, LINE_MODE_GROUND, 0)) + { + Vector position = npc.pos; + Vector velocity = npc.velocity; + float friction = npc.friction; + npc.pathfinder.Reset(); + npc.pathfinder.FindGridPath(target, 1, 0, DIRECT_PATH_FAR); + landing = vector_is_zero(npc.velocity) ? npc.CalcTargetPosition(0) + : vector_add(npc.pos, vector_scale(npc.velocity, HEAD_PATH_LOOKAHEAD)); + npc.pos = position; + npc.velocity = velocity; + npc.friction = friction; + } + if (landing.x == target.x && landing.y == target.y) + { + Vector lead = chimera_lead(npc, *npc.GetPlayerTarget(), HEAD_LEAP_LEAD); + if (room_grid_collision_at(lead) == COLLISION_NONE) landing = lead; + } + npc.stateFrame = -1; + npc.sprite.Play("Jump"); + npc.i2++; + npc.v1 = landing; + npc.state = HEAD_LEAP; +} + +// The head's spit: five shots three frames apart in a smoke puff each. +static void chimera_head_shoot_update(Entity_NPC& npc) +{ + npc.friction *= HEAD_REST_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_BOSS_GURGLE_ROAR, 1, 2, false, 1); + npc.stateFrame = 0; + npc.v1 = npc.GetPlayerTarget()->pos; + } + if (npc.stateFrame >= 0) + { + Vector aim = npc.projectileCooldown == HEAD_SHOT_TRACKING ? npc.GetPlayerTarget()->pos : npc.v1; + int end = npc.projectileCooldown < 1 ? HEAD_SHOTS_FREE_END : HEAD_SHOTS_END; + for (int tick = 0; tick < npc_ticks_get(npc); tick++) + { + if (npc.stateFrame % HEAD_SHOT_EVERY == 0 && npc.stateFrame < end) + { + Vector direction = vector_normalized(vector_sub(aim, npc.pos)); + if (npc.projectileCooldown == 0) + { + ProjectileParams params; + params.spread = HEAD_SHOT_SPREAD; + params.scale = npc.stateFrame != 0 ? 1 : HEAD_SHOT_FIRST_SCALE; + params.fallingAccelModifier = HEAD_SHOT_FALL; + npc.FireProjectiles(npc.pos, vector_scale(direction, CHIMERA_HEAD_SHOT_SPEED), PROJECTILES_FIVE, params); + } + float side = npc.sprite.isFlipX ? HEAD_SPLAT_SIDE : -HEAD_SPLAT_SIDE; + chimera_splat_spawn(npc, SPLAT_SUBTYPE, COLOR_DEFAULT, vector_make(side, HEAD_SMOKE_RAISE)); + } + npc.stateFrame++; + } + } + if (npc.sprite.IsPlaying()) return; + npc.state = CHIMERA_HEAD_REST; + npc.stateFrame = 0; +} + +// The head's charge: three times at its target (the second at its waiting body), then rest. +static void chimera_head_charge_update(Entity_NPC& npc) +{ + if (!vector_is_zero(npc.targetPosition)) + { + npc.sprite.isFlipX = npc.targetPosition.x > 0; + npc.friction = HEAD_CHARGE_FRICTION; + if (!npc.sprite.IsPlaying()) npc.sprite.Play("ChargeLoop"); + return; + } + + auto* body = static_cast(npc.parent.get()); + bool isChargingOn = npc.projectileDelay < HEAD_CHARGES || !body; + npc.friction = HEAD_CHARGE_END_FRICTION; + npc.sprite.Play(isChargingOn ? "ChargeEndShort" : "ChargeEnd"); + head_flag(npc, HEAD_TO_BODY) = 0; + head_flag(npc, HEAD_THROWN) = 0; + if (npc.sprite.IsPlaying()) return; + + if (!isChargingOn) + { + npc.state = CHIMERA_HEAD_REST; + npc.stateFrame = 0; + return; + } + if (body && chimera_body_is_waiting(*body) && npc.projectileDelay == HEAD_BODY_CHARGE) + { + chimera_charge_begin(npc, chimera_lead(npc, *body, HEAD_BODY_LEAD), CHIMERA_HEAD_CHARGE_SPEED); + head_flag(npc, HEAD_TO_BODY) = 1; + } + else chimera_charge_begin(npc, chimera_lead(npc, *npc.GetPlayerTarget(), HEAD_CHARGE_LEAD), CHIMERA_HEAD_CHARGE_SPEED); + npc.projectileDelay++; +} + +// The head bounces, counts its cooldowns down, and rides its charge: flashing while thrown, rebounding off walls. +static void chimera_head_motion_update(Entity_NPC& npc) +{ + float fall = npc.aiFloat; + npc.posOffset.y += fall; + if (npc.posOffset.y >= 0) + { + npc.posOffset.y = 0; + fall = fall <= HEAD_BOUNCE_MIN ? 0 : fall * CHIMERA_HEAD_BOUNCE; + } + npc.aiFloat = fall + HEAD_GRAVITY; + bool isLive = !npc.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && !g_game->IsPaused(); + if (isLive && chimera_interval_crossed(npc, COOLDOWN_EVERY)) + for (int i = 0; i < CHIMERA_COOLDOWNS; i++) + if (chimera_cooldown(npc, (ChimeraCooldown)i) != 0) chimera_cooldown(npc, (ChimeraCooldown)i)--; + if (vector_is_zero(npc.targetPosition)) return; + + npc.friction = std::max(npc.friction, HEAD_CHARGE_FRICTION); + bool isThrown = head_flag(npc, HEAD_THROWN); + if (isThrown && isLive && chimera_interval_crossed(npc, HEAD_FLASH_EVERY)) + npc.SetColor(HEAD_FLASH_COLOR, HEAD_FLASH_FRAMES, COLOR_PRIORITY_DEFAULT, true, true); + if (npc.isCollidesWithGrid) + { + if (isThrown) + { + game_shake_screen(HEAD_WALL_SHAKE); + npc.FireBossProjectiles(HEAD_WALL_SHOTS, {}, 0, ProjectileParams()); + npc_sound_play(SOUND_FORESTBOSS_STOMPS, 1, 2, champion_pitch_get(npc)); + float side = npc.sprite.isFlipX ? HEAD_SPLAT_SIDE : -HEAD_SPLAT_SIDE; + chimera_splat_spawn(npc, SPLAT_BIG_SUBTYPE, COLOR_DEFAULT, vector_make(side, HEAD_SMOKE_RAISE)); + npc.v1.x = HEAD_WALL_HOP; + } + npc_sound_play(SOUND_MEAT_JUMPS, 1, 2, champion_pitch_get(npc)); + float speed = vector_length(npc.targetPosition); + npc.targetPosition = vector_scale(vector_normalized(npc.velocity), speed * HALF); + head_flag(npc, HEAD_THROWN) = 0; + } + + npc.velocity = vector_add(npc.velocity, npc.targetPosition); + npc.targetPosition = vector_scale(npc.targetPosition, HEAD_CHARGE_DRAG); + if (npc.state == CHIMERA_HEAD_CHARGE && vector_length(npc.velocity) < HEAD_SLOW_CHARGE) + npc.targetPosition = vector_scale(npc.targetPosition, HEAD_CHARGE_DRAG); + if (vector_length(npc.targetPosition) < HEAD_STOPPED) npc.targetPosition = {}; + if (head_flag(npc, HEAD_THROWN) && (Random() & HEAD_TRAIL_MASK) == 0) + { + Vector behind = vector_sub(npc.pos, vector_scale(npc.velocity, HEAD_TRAIL_BACK)); + npc.FireBossProjectiles((int)(Random() & 1) + 1, behind, 0, ProjectileParams()); + } + if (Random() % HEAD_CREEP_ODDS != 0) return; + Entity* creep = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = Random()}); + static_cast(creep)->SetTimeout(HEAD_CREEP_TIMEOUT); + creep->Update(); +} + +// 0049fa10 The Chimera's head: it hops about, spits shots, charges at its target (and back into its body to be +// thrown), bouncing and bleeding as it goes. +void chimera_head_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + npc.v2 = {}; + npc.state = HEAD_FALL; + npc.sprite.Play("Fall", PLAY_FORCED); + break; + case CHIMERA_HEAD_REST: + chimera_head_rest_update(npc); + break; + case HEAD_LEAP: + { + bool isFlying = npc.sprite.animState.animData && npc.sprite.WasEventTriggered("Jump") && + !npc.sprite.WasEventTriggered("Shoot"); + if (!isFlying) + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.friction *= LEAP_FRICTION; + } + else + { + npc.entityCollisionClass = ENTCOLL_NONE; + Vector toward = vector_normalized(vector_sub(npc.v1, npc.pos)); + npc_push(npc, vector_scale(toward, HEAD_LEAP_PUSH)); + npc.friction *= HEAD_LEAP_FRICTION; + npc.sprite.isFlipX = npc.velocity.x > 0; + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + npc.stateFrame = 0; + npc.targetPosition = vector_scale(npc.velocity, HEAD_LEAP_LANDING); + } + if (npc.sprite.IsPlaying()) break; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.state = CHIMERA_HEAD_REST; + npc.stateFrame = 0; + break; + } + case HEAD_FALL: + npc.sprite.Play("Fall"); + npc.friction *= HEAD_FALL_FRICTION; + if (!npc.sprite.IsPlaying()) npc.state = CHIMERA_HEAD_REST; + break; + case CHIMERA_HEAD_SHOOT: + chimera_head_shoot_update(npc); + break; + case HEAD_ANNOUNCE: + if (npc.sprite.IsPlaying()) break; + npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + chimera_charge_begin(npc, chimera_lead(npc, *npc.GetPlayerTarget(), HEAD_CHARGE_LEAD), CHIMERA_HEAD_CHARGE_SPEED); + npc.projectileDelay = 1; + break; + case CHIMERA_HEAD_CHARGE: + chimera_head_charge_update(npc); + break; + case HEAD_CARRIED: + { + Entity_NPC* body = npc.ParentNPC(); + if (body && body->state == CHIMERA_THROW) break; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.state = HEAD_FALL; + npc.sprite.Play("Fall"); + npc.velocity = {}; + npc.posOffset.y = 0; + npc.isVisible = true; + break; + } + } + if (npc.state != HEAD_CARRIED) npc.isVisible = true; + chimera_head_motion_update(npc); +} diff --git a/src/boss_clutch.cpp b/src/boss_clutch.cpp new file mode 100644 index 0000000..0fdf7bd --- /dev/null +++ b/src/boss_clutch.cpp @@ -0,0 +1,740 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "grid_entity_trap_door.h" +#include "entity_config.h" +#include "npc_fireplace.h" +#include +#include + +// Clutch's forms, by variant: Clutch himself and the fireballs circling him. +constexpr int CLUTCH_FIREBALL = 1; + +// Clutch's states: resting before he picks a Clickety Clack, wandering in his last phase, inside a Clickety Clack, +// stunned once none is left, flying to the one he picked, flying at his target, his ring of flames, leaving a +// Clickety Clack, and his last phase's start. +enum ClutchState +{ + CLUTCH_IDLE = NPC_STATE_IDLE, + CLUTCH_WANDER = NPC_STATE_MOVE, + CLUTCH_POSSESS = NPC_STATE_JUMP, + CLUTCH_STUNNED = NPC_STATE_STOMP, + CLUTCH_FLY = NPC_STATE_ATTACK, + CLUTCH_CHARGE = NPC_STATE_ATTACK2, + CLUTCH_RING = NPC_STATE_ATTACK3, + CLUTCH_UNPOSSESS = NPC_STATE_ATTACK4, + CLUTCH_TRANSITION = NPC_STATE_SPECIAL +}; + +// The Clickety Clacks' states Clutch drives: its stomp, its stun, getting up and its pile of bones. + +// His last phase starts at a quarter of his health. His Clickety Clacks take 1.75 times their health. +constexpr float CLUTCH_LAST_PHASE = 0.25f; +constexpr float CLACK_HEALTH_SHARE = 1.75f; +constexpr ColorMod CLUTCH_SPLAT_COLOR = {{0.8f, 0.75f, 1, 0.5f}, {2.1f, 1.7f, 2.5f, 1}, {0, 0, 0}}; +constexpr uint32_t CLUTCH_AI_CALLS = AI_CALL_INTERPOLATE | AI_CALL_POST_UPDATE; + +// Resting 15 frames, then flying at his pick: starting 29 frames in after a quick revert, waiting 30 more. +constexpr int CLUTCH_REST = 15; +constexpr float CLUTCH_FRICTION = 0.9f; +constexpr float CLUTCH_SLOW_FRICTION = 0.8f; +constexpr float CLUTCH_MOVE_START_FRAME = 29; +constexpr int CLUTCH_REVERT_REST = 30; + +// The flight: up to 0.8 a frame faster a frame (30 at most) to his pick, entering it within 20. In his last phase he +// wanders 8 frames, then flies at half the gap to his target (1.2 a frame faster, 30 at most) and rings it with flames +// within 20: six rings of nine fire shots at 9, every other one turned 30 degrees. +constexpr float CLUTCH_FLY_GAIN = 0.8f; +constexpr float CLUTCH_FLY_MAX = 30; +constexpr float CLUTCH_REACH = 20; +constexpr int CLUTCH_WANDER_FRAMES = 8; +constexpr float CLUTCH_CHARGE_GAIN = 1.2f; +constexpr float CLUTCH_RING_SPEED = 9; +constexpr float CLUTCH_RING_SHOTS = 6; +constexpr float CLUTCH_RING_TURN = 0.5235988f; +constexpr int CLUTCH_RINGS = 5; +constexpr float CLUTCH_RING_VOLUME = 0.8f; + +// Stunned with no Clickety Clack left he takes 80 hurt (a tenth a frame at least) before rising, waking the burnt piles +// every 8 frames. Thrown out of a dead Clickety Clack at 20. In his last phase he takes a tenth of each hit. +constexpr float CLUTCH_STUN_HEALTH = 80; +constexpr float CLUTCH_STUN_DRAIN = 0.1f; +constexpr float CLUTCH_THROW_SPEED = 20; +constexpr float CLUTCH_PILE_EVERY = 8; +constexpr float CLUTCH_LAST_DAMAGE_SHARE = 0.1f; +constexpr float CLUTCH_ROAR_VOLUME = 2; +constexpr float CLUTCH_LAST_ROAR_VOLUME = 1.5f; +constexpr int CLUTCH_SHAKE = 16; +constexpr float CLUTCH_RIPPLE_AMPLITUDE = 0.035f; +constexpr float CLUTCH_RIPPLE_SPEED = 0.025f; +constexpr int CLUTCH_RIPPLE_FRAMES = 10; +constexpr float CLUTCH_COUNT_EVERY = 15; + +// The beam between Clutch and his pick fades over 10 frames, raised 12, once he enters it. +constexpr ColorMod CLUTCH_BEAM_COLOR = {{0.35f, 0.1f, 1, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int CLUTCH_BEAM_FADE = 10; +constexpr float CLUTCH_BEAM_RAISE = -12; + +// A Clickety Clack burnt for good becomes a purple fire with two fireballs 10 out at a random angle. +constexpr std::string_view CLUTCH_FIRE_ANM2 = "gfx/009.002_Fire Projectile.anm2"; +constexpr std::string_view CLUTCH_POOF_ANM2 = "gfx/033.010_Movable Fireplace.anm2"; +constexpr int CLUTCH_FIREBALLS = 2; +constexpr float CLUTCH_FIREBALL_OUT = 10; +constexpr float CLUTCH_POOF_VOLUME = 0.85f; + +// The trail of purple flames behind him: one more every time the Trail null moved 8 (squared) from the last, 0.6 to 0.8 +// of the null's size, drifting 1.5 down (or swinging across his flight), slowing by 0.9 plus 0.08 of its size, shaking +// by 0.3 of it and shrinking 0.08 a frame, kept within 40 of the null. Half a step between frames. +constexpr float TRAIL_SPACING_SQUARED = 8; +constexpr float CLUTCH_TRAIL_SIZE = 0.6f; +constexpr float TRAIL_SIZE_RANGE = 0.2f; +constexpr float TRAIL_DRIFT = 1.5f; +constexpr float TRAIL_SWAY = 6; +constexpr float TRAIL_SWAY_PERIOD = 15; +constexpr float TRAIL_SWING_RATE = 0.25f; +constexpr float TRAIL_SWING_SHARE = 0.33f; +constexpr float TRAIL_DRAG = 0.9f; +constexpr float TRAIL_SIZE_DRAG = 0.08f; +constexpr float TRAIL_SHAKE = 0.3f; +constexpr float CLUTCH_TRAIL_SHRINK = 0.08f; +constexpr float TRAIL_REACH = 40; +constexpr float TRAIL_PULL = 0.6f; +constexpr float TRAIL_INTERPOLATED_STEP = 0.5f; +constexpr ColorMod TRAIL_HIDDEN_COLOR = {{1, 1, 1, 0}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr size_t TRAIL_POINT = 3; +constexpr int TRAIL_FIRST_LAYER = 1; +constexpr int TRAIL_LAST_LAYER = 2; + +// A trail segment shows one of 8 frames by its flames' size, stretched to half its length per missing frame (1 to 3). +constexpr int TRAIL_FRAMES = 8; +constexpr float TRAIL_STRETCH_MAX = 3; + +// Whether a Clickety Clack (or other NPC) is one of Clutch's side. +static bool clutch_is_ally(Entity_NPC& npc, Entity& other) +{ + return Entity::is_enemy_type(other.type) && other.IsFriendly() == npc.IsFriendly(); +} + +// The Clickety Clacks of his side he leads. +static std::vector clutch_clacks_get(Entity_NPC& npc) +{ + std::vector clacks; + for (Entity* other : Entity_NPC::QueryNPCsType(ENTITY_CLICKETY_CLACK, -1)) + if (clutch_is_ally(npc, *other) && other->parent.get() == &npc) clacks.push_back(static_cast(other)); + return clacks; +} + +// 00572a70 The Clickety Clack of his farthest from him he may enter: not his pick, not burning, not untargetable. +static Entity_NPC* clutch_clack_farthest(Entity_NPC& npc) +{ + Entity_NPC* farthest = nullptr; + float farthestDistance = 0; + for (Entity* other : entity_query(ENTITY_CLICKETY_CLACK, -1)) + { + auto* clack = static_cast(other); + bool isPick = clutch_is_ally(npc, *clack) && clack->parent.get() == &npc && clack != npc.child.get() && + clack->i2 != CLACK_FLAME && !clack->HasEntityFlags(FLAG_NO_TARGET); + float distance = vector_distance(npc.pos, clack->pos); + if (!isPick || distance <= farthestDistance) continue; + farthestDistance = distance; + farthest = clack; + } + return farthest; +} + +// How his beam goes: left fading where his pick stands, or removed. +enum BeamRelease +{ + BEAM_RELEASE_FADE, + BEAM_RELEASE_REMOVE +}; + +// 005729a0 Lets the beam to his pick go. +static void clutch_beam_release(Entity_NPC& npc, BeamRelease release) +{ + Entity* beam = npc.entityRef.get(); + if (!beam || beam->type != ENTITY_EFFECT) return; + + if (release == BEAM_RELEASE_REMOVE) beam->Remove(); + else + { + static_cast(beam)->SetTimeout(CLUTCH_BEAM_FADE); + beam->pos = npc.child->pos; + beam->posOffset = vector_make(0, CLUTCH_BEAM_RAISE); + beam->target = nullptr; + } + npc.entityRef = nullptr; +} + +// His purple beam from a spawner to a Clickety Clack, under a parent. +Entity* clutch_beam_spawn(Entity& spawner, Entity& target, Entity* parent) +{ + Entity* beam = g_game->Spawn({.position = target.pos, + .spawner = &spawner, + .type = ENTITY_EFFECT, + .variant = EFFECT_KINETI_BEAM, + .seed = Random()}); + beam->SetColor(CLUTCH_BEAM_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + beam->target = ⌖ + beam->parent = parent; + beam->Update(); + return beam; +} + +// Clutch flies off to a Clickety Clack, his beam on it, stunning it. +static void clutch_beam_to(Entity_NPC& npc, Entity_NPC& clack) +{ + npc_sound_play(SOUND_DEVILROOM_DEAL, 1, 2, CLUTCH_SOUND_PITCH); + clutch_beam_release(npc, BEAM_RELEASE_FADE); + npc.entityRef = clutch_beam_spawn(npc, clack, &npc); +} + +// Where a Clickety Clack burnt for good goes: a purple poof of the movable fireplace. +static void clutch_fire_poof(Entity& at) +{ + npc_sound_play(SOUND_STEAM_HALFSEC, CLUTCH_POOF_VOLUME, 2, 1); + Entity* poof = g_game->Spawn({.position = at.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->sprite.Load(CLUTCH_POOF_ANM2, GRAPHICS_LOAD); + for (LayerState& layer : poof->sprite.layerStates) layer.color = CLUTCH_FLAME_COLOR; + poof->sprite.Play("Disappear"); + poof->Update(); +} + +// 00572c10 A pile of bones gets up again at full health, from its Regen's 15th frame. +static void clutch_pile_regen(Entity_NPC& clack) +{ + clack.health = clack.maxHitPoints; + clack.sprite.Play("Regen"); + if (clack.sprite.animState.animData) clack.sprite.animState.SetFrameFloat(CLACK_REGEN_FRAME); + clack.state = CLACK_REGEN; +} + +// 00572cc0 A Clickety Clack burns for good: killed as a purple fire, two fireballs circling Clutch. +static void clutch_fire_spawn(Entity_NPC& npc, Entity& clack) +{ + clack.AddEntityFlags(FLAG_NO_TARGET); + clack.Kill(EntityRef(&npc)); + Entity* fire = g_game->Spawn({.position = clack.pos, + .spawner = &npc, + .type = ENTITY_FIREPLACE, + .variant = FIRE_MOVEABLE_PURPLE, + .seed = Random()}); + fire->sprite.Load(CLUTCH_FIRE_ANM2, GRAPHICS_LOAD); + fire->sprite.Play("Flickering"); + for (LayerState& layer : fire->sprite.layerStates) layer.color = CLUTCH_FLAME_COLOR; + fire->Update(); + + for (int i = 0; i < CLUTCH_FIREBALLS; i++) + { + uint32_t seed = Random(); + Vector position = vector_add(clack.pos, vector_scale(random_direction(), CLUTCH_FIREBALL_OUT)); + auto* fireball = static_cast(g_game->Spawn( + {.position = position, .spawner = &npc, .type = ENTITY_CLUTCH, .variant = CLUTCH_FIREBALL, .seed = seed})); + fireball->parent = &npc; + fireball->v1.x = random_unit() * FULL_TURN_DEGREES; + } +} + +// Clutch's roar on a stun's end or his last phase: shaking the room with a ripple. +static void clutch_roar(Entity_NPC& npc, float volume) +{ + npc.PlaySound(SOUND_THUMBS_DOWN, 1, 2, false, 1); + npc.PlaySound(SOUND_MULTI_SCREAM, 1, 2, false, 1); + npc.PlaySound(SOUND_FORSAKEN_SCREAM, volume, 2, false, 1); + game_shake_screen(CLUTCH_SHAKE); + shockwave_make(npc.pos, CLUTCH_RIPPLE_AMPLITUDE, CLUTCH_RIPPLE_SPEED, CLUTCH_RIPPLE_FRAMES); +} + +// Which Clickety Clacks the roar picks from: the piles, or any. +enum ClackPick +{ + PICK_PILES, + PICK_ANY +}; + +// Every 8 frames after the roar one of his Clickety Clacks: a pile gets up, or one burns in his last phase. +static void clutch_roar_pick(Entity_NPC& npc, ClackPick pick, void (*picked)(Entity_NPC&, Entity_NPC&)) +{ + if (!npc.sprite.WasEventTriggered("Shoot") || !npc.GetIntervalTicks(CLUTCH_PILE_EVERY, 0)) return; + + std::vector clacks; + for (Entity_NPC* clack : clutch_clacks_get(npc)) + if (pick == PICK_ANY || clack->state == CLACK_PILE) clacks.push_back(clack); + if (!clacks.empty()) picked(npc, *clacks[random_below((int)clacks.size())]); +} + +// The rest after the roar: every pile of his gets up (or burns), and he goes back to resting (or wandering). +static void clutch_roar_finish(Entity_NPC& npc, void (*finished)(Entity_NPC&, Entity_NPC&)) +{ + for (Entity_NPC* clack : clutch_clacks_get(npc)) + if (clack->state == CLACK_PILE) finished(npc, *clack); +} + +static void clack_regen_picked(Entity_NPC&, Entity_NPC& clack) +{ + clutch_pile_regen(clack); +} + +static void clack_burn_picked(Entity_NPC& npc, Entity_NPC& clack) +{ + clutch_fire_spawn(npc, clack); +} + +// Enters his last phase: a roar, out of any Clickety Clack, his beam gone. +static void clutch_transition_start(Entity_NPC& npc) +{ + npc.sprite.Play("Transition"); + npc.state = CLUTCH_TRANSITION; + clutch_beam_release(npc, BEAM_RELEASE_REMOVE); +} + +// Resting: once rested (or after a quick revert) he flies to the Clickety Clack he left or the farthest, stunning it. +static void clutch_idle_update(Entity_NPC& npc, int ticks) +{ + npc.sprite.Play("Idle"); + npc.pathfinder.MoveRandomlyBoss(STATUS_OBEYED); + if (npc.stateFrame >= 0) npc.stateFrame += ticks; + npc.friction *= CLUTCH_FRICTION; + if (npc.stateFrame <= CLUTCH_REST && npc.stateFrame >= 0) return; + + auto* clack = static_cast(npc.parent.get()); + if (!clack || clack->type != ENTITY_CLICKETY_CLACK) clack = clutch_clack_farthest(npc); + if (!clack) clutch_transition_start(npc); + else + { + npc.state = CLUTCH_FLY; + Vector gap = vector_sub(clack->pos, npc.pos); + if (std::abs(gap.x) > std::abs(gap.y)) npc.sprite.Play("MoveStart"); + else npc.sprite.Play(npc.pos.y <= clack->pos.y ? "MoveStartDown" : "MoveStartUp"); + npc.child = clack; + if (npc.stateFrame < 0) + { + if (npc.sprite.animState.animData) npc.sprite.animState.SetFrameFloat(CLUTCH_MOVE_START_FRAME); + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.shadowSize = npc.config->shadowSize; + } + else clutch_beam_to(npc, *clack); + if (clack->state != CLACK_PILE) + { + clack->state = CLACK_STUNNED; + clack->sprite.Play("Stunned"); + clack->targetPosition = {}; + } + npc.sprite.isFlipX = npc.pos.x < clack->pos.x; + } + npc.stateFrame = npc.stateFrame < 0 ? CLUTCH_REVERT_REST : 0; +} + +// Inside a Clickety Clack, riding it until it dies: then he takes the farthest other (or falls stunned with none), +// thrown away from his target. +static void clutch_possess_update(Entity_NPC& npc) +{ + Entity* clack = npc.child.get(); + npc.friction *= CLUTCH_FRICTION; + if (clack && !clack->isDead && !clack->HasEntityFlags(FLAG_NO_TARGET)) + { + npc.velocity = vector_sub(clack->pos, npc.pos); + if (npc.sprite.IsEventTriggered("Sound")) npc_sound_play(SOUND_PORTAL_SPAWN, 1, 2, CLUTCH_SOUND_PITCH); + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + npc_sound_play(SOUND_BONE_HEART, 1, 2, CLUTCH_SOUND_PITCH); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.shadowSize = 0; + Entity_NPC* host = npc.ChildNPC(); + host->state = CLACK_STOMP; + host->sprite.Play("Transition"); + if (host == npc.ParentNPC() && host->sprite.animState.animData) + host->sprite.animState.SetFrameFloat(CLUTCH_MOVE_START_FRAME); + return; + } + + if (npc.entityCollisionClass != ENTCOLL_NONE) + { + npc.sprite.Play("Idle"); + npc.state = CLUTCH_IDLE; + npc.stateFrame = CLUTCH_REST; + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.shadowSize = npc.config->shadowSize; + return; + } + + Entity_NPC* next = clutch_clack_farthest(npc); + if (!next) + { + npc.sprite.Play("Stun"); + npc.state = CLUTCH_STUNNED; + npc.stateFrame = 0; + npc.v1.x = CLUTCH_STUN_HEALTH; + } + else + { + npc.parent = next; + npc.state = CLUTCH_UNPOSSESS; + npc_sound_play(SOUND_DEVILROOM_DEAL, 1, 2, CLUTCH_SOUND_PITCH); + clutch_beam_release(npc, BEAM_RELEASE_REMOVE); + npc.entityRef = clutch_beam_spawn(npc, *next, &npc); + npc.sprite.Play("Unpossess"); + } + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.shadowSize = npc.config->shadowSize; + Vector away = vector_normalized(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)); + npc.velocity = vector_add(npc.velocity, vector_scale(away, CLUTCH_THROW_SPEED)); +} + +// Stunned with none left: the burning piles go out first, then he takes hurt until he rises with a roar, waking them. +static void clutch_stunned_update(Entity_NPC& npc) +{ + npc.friction *= CLUTCH_SLOW_FRICTION; + if (npc.stateFrame == 0) + { + npc.stateFrame = 1; + for (Entity_NPC* clack : clutch_clacks_get(npc)) + { + if (clack->state != CLACK_PILE || clack->i2 != CLACK_FLAME) continue; + clack->i2 = 0; + clack->sprite.Play("Collapse"); + if (clack->sprite.animState.animData) clack->sprite.animState.AdvancePosition(clack->sprite.animState.animData->length - 1); + clutch_fire_poof(*clack); + } + } + + if (npc.v1.x > 0) + { + if (!npc.sprite.IsPlaying()) npc.sprite.Play("StunLoop"); + npc.v1.x -= std::max(npc.speedMultiplier * CLUTCH_STUN_DRAIN, npc.pendingDamage); + return; + } + + npc.sprite.Play("StunEnd"); + npc.parent = nullptr; + npc.child = nullptr; + if (npc.sprite.IsEventTriggered("Shoot")) clutch_roar(npc, CLUTCH_ROAR_VOLUME); + clutch_roar_pick(npc, PICK_PILES, clack_regen_picked); + if (npc.sprite.IsPlaying()) return; + clutch_roar_finish(npc, clack_regen_picked); + npc.sprite.Play("Idle"); + npc.state = CLUTCH_IDLE; + npc.stateFrame = 0; +} + +// Flying to his pick, faster each frame. Whether he entered it. +static bool clutch_fly_update(Entity_NPC& npc, int ticks) +{ + npc.friction *= CLUTCH_FRICTION; + Entity* clack = npc.child.get(); + if (!clack) + { + npc.sprite.Play("Idle"); + npc.state = CLUTCH_IDLE; + npc.stateFrame = CLUTCH_REST; + return false; + } + if (!npc.sprite.IsPlaying()) npc.sprite.Play("MoveLoop"); + npc.stateFrame += ticks; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_BEAST_GHOST_DASH, 1, 2, 1); + clutch_beam_release(npc, BEAM_RELEASE_FADE); + } + if (!npc.sprite.WasEventTriggered("Shoot") && !npc.sprite.animState.IsLoopingAnimation()) return false; + + float maxSpeed = std::min((float)npc.stateFrame * CLUTCH_FLY_GAIN, CLUTCH_FLY_MAX); + npc.velocity = vector_sub(clack->pos, npc.pos); + float distance = vector_length(npc.velocity); + if (distance >= CLUTCH_REACH) + { + if (maxSpeed < distance && distance > 0) npc.velocity = vector_scale(npc.velocity, maxSpeed / distance); + return false; + } + npc.sprite.Play("Possess"); + npc.state = CLUTCH_POSSESS; + npc.stateFrame = 0; + return true; +} + +// His last phase: he wanders, flies at his target and rings it with fire. Hits do a tenth while he roars. +static void clutch_last_phase_update(Entity_NPC& npc, int ticks) +{ + switch (npc.state) + { + case CLUTCH_WANDER: + npc.pathfinder.MoveRandomlyBoss(STATUS_OBEYED); + npc.stateFrame += ticks; + npc.friction *= CLUTCH_FRICTION; + if (npc.stateFrame > CLUTCH_WANDER_FRAMES) + { + Vector target = npc.GetPlayerTarget()->pos; + if (vector_is_zero(target)) break; + npc.state = CLUTCH_CHARGE; + npc.sprite.Play("MoveStart2"); + npc.targetPosition = target; + npc.sprite.isFlipX = npc.pos.x < target.x; + npc.stateFrame = 0; + } + break; + case CLUTCH_CHARGE: + { + if (npc.sprite.IsFinished()) npc.sprite.Play("MoveLoop2"); + npc.stateFrame += ticks; + if (!npc.sprite.WasEventTriggered("Shoot") && !npc.sprite.animState.IsLoopingAnimation()) break; + float maxSpeed = std::min((float)npc.stateFrame * CLUTCH_CHARGE_GAIN, CLUTCH_FLY_MAX); + npc.velocity = vector_scale(vector_sub(npc.targetPosition, npc.pos), HALF); + float distance = vector_length(npc.velocity); + if (distance < CLUTCH_REACH) + { + npc.sprite.Play("AttackStart"); + npc.state = CLUTCH_RING; + npc.stateFrame = 0; + } + else if (maxSpeed < distance) npc.velocity = vector_resized(npc.velocity, maxSpeed); + break; + } + case CLUTCH_RING: + npc.friction *= CLUTCH_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_BEAST_FIRE_RING, CLUTCH_RING_VOLUME, 2, false, CLUTCH_SOUND_PITCH); + ProjectileParams params; + params.circleAngle = npc.stateFrame & 1 ? 0 : CLUTCH_RING_TURN; + params.variant = PROJECTILE_FIRE; + params.color = CLUTCH_FLAME_COLOR; + npc.FireProjectiles(npc.pos, vector_make(CLUTCH_RING_SPEED, CLUTCH_RING_SHOTS), PROJECTILES_RING, params); + npc.stateFrame++; + } + if (!npc.sprite.IsFinished()) break; + if (npc.stateFrame > CLUTCH_RINGS) + { + npc.sprite.Play("Idle2"); + npc.state = CLUTCH_WANDER; + npc.stateFrame = 0; + } + else npc.sprite.Play("Attack", PLAY_FORCED); + break; + case CLUTCH_TRANSITION: + npc.friction *= CLUTCH_SLOW_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) clutch_roar(npc, CLUTCH_LAST_ROAR_VOLUME); + clutch_roar_pick(npc, PICK_ANY, clack_burn_picked); + if (npc.sprite.IsPlaying()) + { + npc.pendingDamage = 0; + for (DamageEvent& hit : npc.damageEvents) + { + hit.damage *= CLUTCH_LAST_DAMAGE_SHARE; + npc.pendingDamage += hit.damage; + } + break; + } + clutch_roar_finish(npc, clack_burn_picked); + npc.sprite.Play("Idle2"); + npc.state = CLUTCH_WANDER; + npc.stateFrame = 0; + break; + } +} + +// Numbers the Clickety Clacks he leads standing (his pick 0) for their places, keeping one more than their count. +static void clutch_clacks_count(Entity_NPC& npc) +{ + int count = 1; + for (Entity* other : entity_query(ENTITY_CLICKETY_CLACK, -1)) + { + auto* clack = static_cast(other); + if (!Entity::is_enemy_type(clack->type) || clack->parent.get() != &npc || clack->state == CLACK_PILE) continue; + clack->i2 = clack == npc.child.get() ? 0 : count++; + } + npc.i1 = count; +} + +// Dying, he takes his Clickety Clacks, purple fires and fireballs with him. His shots fall. +static void clutch_death_update(Entity_NPC& npc) +{ + for (Entity* other : entities_live(g_game->room->entityList.updateEL)) + { + if (!clutch_is_ally(npc, *other)) + { + if (other->type == ENTITY_PROJECTILE && other->parent.get() == &npc) + { + static_cast(other)->projectileFlags = 0; + other->isDead = true; + } + continue; + } + if (other->type == ENTITY_CLICKETY_CLACK) + { + if (other->parent.get() != &npc) continue; + other->AddEntityFlags(FLAG_NO_TARGET); + other->Kill(EntityRef(&npc)); + } + else if (other->type == ENTITY_FIREPLACE && other->variant == FIRE_MOVEABLE_PURPLE) + { + other->Kill(EntityRef(&npc)); + clutch_fire_poof(*other); + } + else if (other->type == ENTITY_CLUTCH && other->variant == CLUTCH_FIREBALL && other->parent.get() == &npc) + other->Kill(EntityRef(&npc)); + } +} + +// Part of 00573030 Between frames the trail steps half and keeps its last whole step. After the update it steps whole, +// grows a flame and takes the Trail null's colour onto its two layers. +static void clutch_trail_update(Entity_NPC& npc) +{ + bool isInterpolated = npc.aiCallPhase == AI_PHASE_INTERPOLATE; + if (isInterpolated) npc.vectorDeque2 = npc.vectorDeque1; + else npc.vectorDeque1 = npc.vectorDeque2; + + bool isFlying = (npc.state == CLUTCH_FLY || npc.state == CLUTCH_CHARGE) && + (npc.sprite.WasEventTriggered("Shoot") || npc.sprite.animState.IsLoopingAnimation()); + Vector anchor = vector_add(npc.pos, npc.GetNullOffset("Trail")); + Vector drift = vector_make(0, TRAIL_DRIFT); + if (!isFlying) anchor.x += std::sin(npc.updateTime * PI_F / TRAIL_SWAY_PERIOD) * TRAIL_SWAY; + else + { + Vector side = vector_rotated(npc.velocity, RIGHT_ANGLE_DEGREES); + float swing = std::sin(npc.updateTime * PI_F * TRAIL_SWING_RATE); + anchor = vector_add(anchor, vector_scale(side, swing)); + drift = vector_scale(side, TRAIL_SWING_SHARE * swing); + } + const NullFrame* null = npc.sprite.animState.animData ? npc.sprite.animState.GetNullFrame("Trail") : nullptr; + + std::deque& trail = npc.vectorDeque1; + float step = (isInterpolated ? TRAIL_INTERPOLATED_STEP : 1) * npc.speedMultiplier; + for (size_t i = 0; i < trail.size();) + { + Vector& position = trail[i]; + Vector& velocity = trail[i + 1]; + Vector& size = trail[i + 2]; + position = vector_add(position, vector_scale(velocity, step)); + velocity = vector_scale(velocity, timescale_factor(size.x * TRAIL_SIZE_DRAG + TRAIL_DRAG, step)); + Vector shake = random_direction(); + float strength = size.x * random_unit() * TRAIL_SHAKE * step; + velocity = vector_add(velocity, vector_scale(shake, strength)); + size.x = std::max(size.x - step * CLUTCH_TRAIL_SHRINK, 0.0f); + + float distance = vector_distance(anchor, position); + if (distance > TRAIL_REACH) + { + float kept = timescale_factor(TRAIL_PULL, step) * (distance - TRAIL_REACH) + TRAIL_REACH; + position = vector_add(anchor, vector_scale(vector_sub(position, anchor), kept / distance)); + } + if (size.x > 0 || isInterpolated) i += TRAIL_POINT; + else trail.erase(trail.begin() + (long)i, trail.begin() + (long)(i + TRAIL_POINT)); + } + + bool isSpaced = trail.empty() || vector_length_squared(vector_sub(anchor, trail.front())) > TRAIL_SPACING_SQUARED; + if (!isInterpolated && isSpaced) + { + float scale = null ? null->scale.x : 1; + trail.push_front(vector_make((random_unit() * TRAIL_SIZE_RANGE + CLUTCH_TRAIL_SIZE) * scale, 0)); + trail.push_front(drift); + trail.push_front(anchor); + } + + ColorMod color = null && null->isVisible ? null->color : TRAIL_HIDDEN_COLOR; + npc.sprite.GetLayer(TRAIL_LAST_LAYER)->color = color; + npc.sprite.GetLayer(TRAIL_FIRST_LAYER)->color = color; +} + +// 00573030 Clutch rides his Clickety Clacks one by one, leaving each dead one to stomp its bones and wake again, and +// falls stunned once none is left. Below a quarter of his health he burns them all and flies at his target, ringing +// it with fire. +void boss_clutch_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_POST_UPDATE || npc.aiCallPhase == AI_PHASE_INTERPOLATE) return clutch_trail_update(npc); + + int ticks = npc_ticks_get(npc); + bool isCounted = npc.GetIntervalTicks(CLUTCH_COUNT_EVERY, 0); + bool isLastPhaseDue = npc.state == CLUTCH_IDLE || npc.state == CLUTCH_FLY || + (npc.state == CLUTCH_STUNNED && !npc.sprite.WasEventTriggered("Shoot")); + if (isLastPhaseDue && npc.health <= npc.maxHitPoints * CLUTCH_LAST_PHASE) + { + clutch_transition_start(npc); + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.shadowSize = npc.config->shadowSize; + } + + switch (npc.state) + { + case NPC_STATE_INIT: + { + npc.splatColor = CLUTCH_SPLAT_COLOR; + npc.state = CLUTCH_IDLE; + npc.aiCallFlags = CLUTCH_AI_CALLS; + npc.sprite.PlayOverlay("Trail"); + npc.sprite.GetLayer(TRAIL_FIRST_LAYER)->isVisible = false; + npc.sprite.GetLayer(TRAIL_LAST_LAYER)->isVisible = false; + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + int count = 1; + for (Entity* other : Entity_NPC::QueryNPCsType(ENTITY_CLICKETY_CLACK, -1)) + { + if (!clutch_is_ally(npc, *other) || other->parent) continue; + auto* clack = static_cast(other); + clack->parent = &npc; + clack->maxHitPoints *= CLACK_HEALTH_SHARE; + clack->i2 = count++; + clack->health = clack->maxHitPoints; + } + npc.i1 = count; + break; + } + case CLUTCH_IDLE: + clutch_idle_update(npc, ticks); + break; + case CLUTCH_POSSESS: + clutch_possess_update(npc); + break; + case CLUTCH_STUNNED: + clutch_stunned_update(npc); + break; + case CLUTCH_FLY: + if (clutch_fly_update(npc, ticks)) isCounted = true; + break; + case CLUTCH_UNPOSSESS: + npc.friction *= CLUTCH_SLOW_FRICTION; + if (npc.sprite.IsPlaying()) break; + npc.state = CLUTCH_IDLE; + npc.stateFrame = CLUTCH_REVERT_WAIT; + break; + default: + clutch_last_phase_update(npc, ticks); + break; + } + + if (isCounted) clutch_clacks_count(npc); + if (npc.isDead) clutch_death_update(npc); +} + +// 00575a10 Clutch draws his trail of flames segment by segment on his two trail layers, each between two flames, +// turned along them and showing their size, then himself. The fireballs draw plainly. +void clutch_render(Entity_NPC& npc, const Vector& offset) +{ + std::deque& trail = npc.vectorDeque1; + if (npc.variant != 0 || npc.sprite.GetLayer(TRAIL_FIRST_LAYER)->color._tint[3] <= 0 || trail.empty()) + return npc.Entity::Render(offset); + + npc.sprite.GetLayer(TRAIL_FIRST_LAYER)->isVisible = true; + npc.sprite.GetLayer(TRAIL_LAST_LAYER)->isVisible = true; + for (int layerId = TRAIL_FIRST_LAYER; layerId <= TRAIL_LAST_LAYER; layerId++) + for (size_t i = 0; i + TRAIL_POINT < trail.size(); i += TRAIL_POINT) + { + Vector from = trail[i]; + Vector to = trail[i + TRAIL_POINT]; + Vector middle = render_position_get(vector_scale(vector_add(from, to), HALF), RENDER_SNAPPED); + float size = (trail[i + TRAIL_POINT + 2].x + trail[i + 2].x) * HALF; + int frame = (int)((float)TRAIL_FRAMES - size * TRAIL_FRAMES); + if (frame >= TRAIL_FRAMES) continue; + + float stretch = 1; + if (frame != TRAIL_FRAMES - 1) + stretch = std::clamp(vector_distance(from, to) * HALF / (float)(TRAIL_FRAMES - frame), 1.0f, TRAIL_STRETCH_MAX); + LayerState& layer = *npc.sprite.GetLayer(layerId); + layer.size = vector_make(stretch, 1); + Vector gap = vector_sub(to, from); + layer.rotation = std::atan2(gap.y, gap.x) * RADIANS_TO_DEGREES * (npc.sprite.isFlipX ? -1.0f : 1.0f); + if (npc.sprite.overlayAnimState.animData) npc.sprite.overlayAnimState.SetFrameFloat((float)frame); + npc.sprite.RenderLayer(layerId, SpriteDraw{vector_add(middle, offset), {}, {}}); + } + npc.sprite.GetLayer(TRAIL_FIRST_LAYER)->isVisible = false; + npc.sprite.GetLayer(TRAIL_LAST_LAYER)->isVisible = false; + npc.Entity::Render(offset); +} diff --git a/src/boss_death.cpp b/src/boss_death.cpp index c3e92ce..097312d 100644 --- a/src/boss_death.cpp +++ b/src/boss_death.cpp @@ -39,8 +39,6 @@ constexpr int VARIANT_MOTHER_PHASE_TWO = 10; constexpr int BIG_HORN_SMALL_HOLE = 1; constexpr int BIG_HORN_BIG_HOLE = 2; constexpr int ENVY_SIZES = 10; -constexpr int ROTGUT_BOSS_ROOM_SUBTYPE = 3; -constexpr int DUNGEON_BOSS_SUBTYPE_FIRST = 2; constexpr int MINIBOSS_PRIDE = 6; constexpr int MINIBOSS_ULTRA_PRIDE = 14; constexpr int MINIBOSS_ID_LIMIT = 16; @@ -425,11 +423,11 @@ static void boss_death_rewards(Room& room, Entity_NPC& boss, RNG& rng, bool isGr Game& game = *g_game; RoomType roomType = room.roomType; RoomDescriptor* descriptor = room.descriptor; - bool isDungeonBoss = roomType == ROOM_DUNGEON && descriptor->data->subtype >= DUNGEON_BOSS_SUBTYPE_FIRST && - descriptor->data->subtype <= ROTGUT_BOSS_ROOM_SUBTYPE; + bool isDungeonBoss = roomType == ROOM_DUNGEON && descriptor->data->subtype >= DUNGEON_ROTGUT && + descriptor->data->subtype <= DUNGEON_ROTGUT_HEART; if (isDungeonBoss) { - if (boss.type != ENTITY_ROTGUT || descriptor->data->subtype != ROTGUT_BOSS_ROOM_SUBTYPE) return; + if (boss.type != ENTITY_ROTGUT || descriptor->data->subtype != DUNGEON_ROTGUT_HEART) return; RoomDescriptor* returnRoom = game.GetRoomByIdx(game.dungeonReturnRoomIndex, -1); if (returnRoom->data && returnRoom->data->type == ROOM_BOSS) returnRoom->flags |= ROOM_DESCRIPTOR_FLAG_ROTGUT_CLEARED; diff --git a/src/boss_dogma.cpp b/src/boss_dogma.cpp index 79149f0..73c8f7e 100644 --- a/src/boss_dogma.cpp +++ b/src/boss_dogma.cpp @@ -1099,8 +1099,6 @@ 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; diff --git a/src/boss_gemini.cpp b/src/boss_gemini.cpp index 32726ca..d03ef71 100644 --- a/src/boss_gemini.cpp +++ b/src/boss_gemini.cpp @@ -26,7 +26,6 @@ constexpr float BABY_SPAWN_OFFSET_Y = -8; constexpr float TWIN_FRICTION = 0.8f; constexpr float NO_CORD_FRICTION = 0.92f; constexpr int CREEP_FRAMES = 7; -constexpr float WALK_THRESHOLD = 0.1f; constexpr float SPEED = 1.4f; constexpr float OVUM_SPEED = 1.6f; constexpr float PATH_SPEED_SCALE = 0.83f; @@ -188,7 +187,7 @@ static void twin_state_update(Entity_NPC& npc) return twin_head_idle(npc); case NPC_STATE_MOVE: { - npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); + npc.AnimWalkFrame("WalkHori", "WalkVert", MOVEMENT_DEADZONE); npc.aiFloat = npc.variant == GEMINI_BLIGHTED_OVUM ? OVUM_SPEED : SPEED; twin_walk(npc, npc.aiFloat); twin_head_idle(npc); @@ -205,7 +204,7 @@ static void twin_state_update(Entity_NPC& npc) case NPC_STATE_ATTACK: npc.aiFloat = (npc.aiFloat + RAGE_ACCELERATION) * RAGE_DAMPING; twin_walk(npc, npc.variant == GEMINI_BLIGHTED_OVUM ? npc.aiFloat + OVUM_RAGE_BONUS : npc.aiFloat); - npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); + npc.AnimWalkFrame("WalkHori", "WalkVert", MOVEMENT_DEADZONE); npc.sprite.PlayOverlay("RageBody"); if (++npc.stateFrame <= RAGE_FRAMES) return; diff --git a/src/boss_gideon.cpp b/src/boss_gideon.cpp index 51e5456..5f3e924 100644 --- a/src/boss_gideon.cpp +++ b/src/boss_gideon.cpp @@ -136,7 +136,6 @@ constexpr float CELL_SIZE = 40; constexpr float CELL_ORIGIN_X = 40; constexpr float CELL_ORIGIN_Y = 120; constexpr RNG CRAWLSPACE_RNG_SHIFTS = {0, 1, 27, 27}; -constexpr int CRAWLSPACE_GIDEON = 1; static int cooldown_get(const Entity_NPC& npc, int shift) { @@ -694,7 +693,7 @@ static void gideon_stairs_spawn(Entity_NPC& npc) RNG rng = CRAWLSPACE_RNG_SHIFTS; rng._seed = game.devilAngelRoomRNG._seed; crawlspace->InitSeeds(rng); - RoomQuery query = {.stageId = STAGE_ID_SPECIAL_ROOMS, .subtype = CRAWLSPACE_GIDEON, .type = ROOM_DUNGEON}; + RoomQuery query = {.stageId = STAGE_ID_SPECIAL_ROOMS, .subtype = DUNGEON_GIDEON, .type = ROOM_DUNGEON}; crawlspace->data = game.roomConfig.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); } game.room->SpawnGridEntity(npc.projectileDelay, GRID_STAIRS, STAIRS_GIDEON, Random(), 0); diff --git a/src/boss_lil_blub.cpp b/src/boss_lil_blub.cpp new file mode 100644 index 0000000..71fa200 --- /dev/null +++ b/src/boss_lil_blub.cpp @@ -0,0 +1,456 @@ +#include "boss_ai.h" +#include "boss_repentance.h" +#include "fx_layers.h" +#include "level.h" +#include "npc_basement.h" +#include "room_grid.h" +#include +#include + +// Lil Blub's states: resting, throwing small leeches, throwing a big one, spraying a ring of shots, and its jumps. +enum LilBlubState +{ + BLUB_REST = NPC_STATE_IDLE, + BLUB_LEECHES = NPC_STATE_ATTACK, + BLUB_BIG_LEECH = NPC_STATE_ATTACK2, + BLUB_SPRAY = NPC_STATE_ATTACK3, + BLUB_JUMPS = NPC_STATE_ATTACK4 +}; + +// Resting it throws leeches one time in 40 (six of its leeches at most out), a big one one time in 70 (40 when hurt +// to below 30 percent, with no big one free), sprays one time in 45 (with three of its leeches out), or jumps one time +// in 110 (with three of its leeches out, one time in ten and two to four more jumps when hurt). +constexpr uint32_t LEECHES_ODDS = 40; +constexpr int LEECHES_LIMIT = 6; +constexpr uint32_t BIG_LEECH_ODDS = 70; +constexpr uint32_t BIG_LEECH_HURT_ODDS = 40; +constexpr uint32_t SPRAY_ODDS = 45; +constexpr int SPRAY_LEECHES = 2; +constexpr uint32_t JUMPS_ODDS = 110; +constexpr uint32_t JUMPS_HURT_ODDS = 10; +constexpr int JUMPS_LEECHES = 3; +constexpr uint32_t JUMPS_HURT_RANGE = 3; +constexpr int JUMPS_HURT_EXTRA = 2; +constexpr float BLUB_HURT_HEALTH = 0.3f; + +// Leeches: one to three small ones (twice as tough) 30 out and 30 below, or a big one at its target within 90, thrown +// from 30 up, each in a splash 40 up thrown 5 down. +constexpr uint32_t LEECHES_RANGE = 3; +constexpr float LEECH_OUT = 30; +constexpr float LEECH_DROP = 30; +constexpr float LEECH_HEIGHT = -30; +constexpr float LEECH_MARGIN = 5; +constexpr float BIG_LEECH_REACH = 90; +constexpr int SPLASH_SUBTYPE = 1; +constexpr float BLUB_SPLASH_FALL = 5; +constexpr float SPLASH_RAISE = -40; +constexpr int BLUB_SPLASH_DEPTH = 500; + +// The spray: on every other frame up to 12 a ring of six shots from a random turn, each jittered 6 degrees, 30 out +// at 8 to 10, falling slightly, with a splash 40 out every fourth frame. It pushes its leeches away at 8. +constexpr int BLUB_SPRAY_SHOTS = 6; +constexpr float SPRAY_STEP = 60; +constexpr float BLUB_SPRAY_JITTER = 12; +constexpr float BLUB_SPRAY_JITTER_HALF = 6; +constexpr int BLUB_SPRAY_END = 12; +constexpr float BLUB_SPRAY_HEIGHT = -10; +constexpr float BLUB_SPRAY_FALL_RANGE = 0.049999997f; +constexpr float BLUB_SPRAY_FALL = -0.08f; +constexpr float BLUB_SPRAY_SCALE_RANGE = 0.6f; +constexpr float BLUB_SPRAY_SCALE = 0.9f; +constexpr float BLUB_SPRAY_SPEED = 10; +constexpr float SPRAY_SPEED_RANGE = 0.19999999f; +constexpr float SPRAY_SPEED_SHARE = 0.8f; +constexpr float BLUB_SPRAY_SCATTER = 3; +constexpr float SPRAY_OUT = 30; +constexpr int SPRAY_SPLASH_EVERY = 4; +constexpr float SPRAY_SPLASH_OUT = 40; +constexpr float SPRAY_SPLASH_SPEED = 7; +constexpr float SPRAY_SPLASH_RAISE = -28; +constexpr float BLUB_SPRAY_PUSH = 8; + +// The jumps: at its target a twenty-fifth of a second ahead per unit, 240 at most (160 when hurt), a sixteenth of the +// way a frame, landing with 35 hurt to enemies within 60 and, when hurt, a plus of shots at 10 and a cross at 4 (else +// 8 frames of fountain shots). Its next jump starts from frame 19. +constexpr float JUMP_LEAD = 0.04f; +constexpr float BLUB_JUMP_MARGIN = 20; +constexpr float BLUB_JUMP_REACH = 240; +constexpr float JUMP_HURT_REACH = 160; +constexpr float BLUB_JUMP_STEP = 0.0625f; +constexpr float BLUB_JUMP_PUSH = 1; +constexpr int JUMP_FOUNTAIN_FRAMES = 8; +constexpr float JUMP_PLUS_SPEED = 10; +constexpr float JUMP_CROSS_SPEED = 4; +constexpr float JUMP_CRUSH_REACH = 60; +constexpr float JUMP_CRUSH_DAMAGE = 35; +constexpr int JUMP_CRUSH_COUNTDOWN = 30; +constexpr int BLUB_JUMP_SHAKE = 8; +constexpr float JUMP_LOOP_FRAME = 19; +constexpr float JUMP_LANDED_FRICTION = 0.2f; +constexpr float BLUB_JUMP_FRICTION = 0.9f; + +// It floats 40 below the room's top, bouncing off the edges, drifting at 0.5 diagonally (fleeing within 180 when +// afraid). Its small champion slows more. +constexpr float BLUB_TOP_MARGIN = 40; +constexpr float BLUB_FRICTION = 0.8f; +constexpr float BLUB_DRIFT = 0.5f; +constexpr float BLUB_DRIFT_TURN = 0.1f; +constexpr float BLUB_FLEE_REACH = 180; +constexpr float BLUB_FLEE_SHARE = 0.02f; +constexpr int BLUB_SLOW_SUBTYPE = 2; +constexpr float BLUB_SLOW_FRICTION = 0.9f; + +// Dying it bursts in a big splash, its leeches pushed away at 4, two to four more thrown within 60, and a fountain of +// shots 15 frames running. +constexpr float DEATH_SPLASH_SCALE = 1.5f; +constexpr float DEATH_PUSH = 4; +constexpr uint32_t DEATH_TIMER_TIMES = 15; +constexpr uint32_t DEATH_LEECHES_RANGE = 3; +constexpr uint32_t DEATH_LEECHES = 2; +constexpr float DEATH_LEECH_REACH = 60; +constexpr float LEECH_HEALTH_SHARE = 0.5f; + +// The fountain: two shots at up to 4 from up to 15 high, and two at up to 2.5 from up to 1000 high, within 15. +constexpr int FOUNTAIN_SHOTS = 2; +constexpr float FOUNTAIN_SPEED = 4; +constexpr float FOUNTAIN_HIGH_SPEED = 2.5f; +constexpr float FOUNTAIN_SPREAD = 15; +constexpr float FOUNTAIN_ACCEL = 2; +constexpr float FOUNTAIN_SCALE = 1.4f; +constexpr float FOUNTAIN_FALL = -15; +constexpr float FOUNTAIN_FALL_RANGE = 60; +constexpr float FOUNTAIN_HEIGHT = -15; +constexpr float FOUNTAIN_HIGH_HEIGHT = -1000; + +// Whether the floor is the Dross, whose water is sewage: brown splashes and puke shots instead of tears. +static bool blub_is_sewage() +{ + return g_game->GetStageID() == STAGE_ID_DROSS; +} + +static int blub_shot_variant() +{ + return blub_is_sewage() ? PROJECTILE_PUKE : PROJECTILE_TEAR; +} + +// A splash of its water spinning at a random angle, raised. +static void blub_splash_spawn(const Vector& position, const Vector& velocity, float raise) +{ + Entity* splash = g_game->Spawn({.position = position, + .velocity = velocity, + .subType = SPLASH_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + splash->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + splash->sprite.Play("Poof"); + splash->posOffset = vector_make(0, raise); + splash->renderZOffset = BLUB_SPLASH_DEPTH; + splash->sprite.color = blub_is_sewage() ? SEWAGE_SPLASH_COLOR : WATER_SPLASH_COLOR; +} + +// A leech thrown up out of it toward a spot kept in the room. +static Entity_NPC* blub_leech_throw(Entity_NPC& npc, Vector target, bool isBig) +{ + Vector landing = g_game->room->GetClampedPositionImpl(target, LEECH_MARGIN, LEECH_MARGIN, LEECH_MARGIN, LEECH_MARGIN); + return leech_throw({.position = npc.pos, .target = landing, .spawner = &npc, .height = LEECH_HEIGHT, .isBig = isBig}); +} + +// 004508c0 The fountain its death leaves: four shots of its water raining about the timer. +static void blub_fountain_timer(Entity_Effect* timer) +{ + Vector origin = timer->pos; + for (auto [speed, height] : {std::pair{FOUNTAIN_SPEED, FOUNTAIN_HEIGHT}, std::pair{FOUNTAIN_HIGH_SPEED, FOUNTAIN_HIGH_HEIGHT}}) + for (int i = 0; i < FOUNTAIN_SHOTS; i++) + { + Vector direction = random_direction(); + uint32_t seed = Random(); + Vector velocity = vector_scale(direction, random_unit() * speed); + Vector position = vector_add(origin, vector_scale(direction, FOUNTAIN_SPREAD * random_unit())); + auto* shot = static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .type = ENTITY_PROJECTILE, + .variant = blub_shot_variant(), + .seed = seed})); + shot->spawnerType = ENTITY_LIL_BLUB; + shot->fallingAccel = FOUNTAIN_ACCEL; + shot->scale = random_unit() * FOUNTAIN_SCALE; + shot->fallingSpeed = FOUNTAIN_FALL - random_unit() * FOUNTAIN_FALL_RANGE; + shot->height = random_unit() * height; + shot->Update(); + } +} + +// Its leeches out: all of the room's, its own, and the big ones run free. +struct BlubLeeches +{ + int all = 0; + int bigFree = 0; + int own = 0; +}; + +static BlubLeeches blub_leeches_count(Entity_NPC& npc) +{ + BlubLeeches count; + for (Entity* leech : g_game->room->entityList.updateEL) + { + if (leech->type != ENTITY_SMALL_LEECH || leech->spawnerType != ENTITY_LIL_BLUB) continue; + count.all++; + if (leech->parent.get() == &npc) count.own++; + if (!leech->parent && leech->subtype == 1) count.bigFree++; + } + return count; +} + +// Resting, it picks its next attack. +static void blub_rest_update(Entity_NPC& npc, const BlubLeeches& leeches, bool isHurt) +{ + npc.sprite.Play("Idle"); + npc.projectileDelay = 0; + if (Random() % LEECHES_ODDS == 0 && leeches.all < LEECHES_LIMIT) npc.state = BLUB_LEECHES; + else if ((Random() % BIG_LEECH_ODDS == 0 || (isHurt && Random() % BIG_LEECH_HURT_ODDS == 0)) && leeches.bigFree < 1) + npc.state = BLUB_BIG_LEECH; + else if (Random() % SPRAY_ODDS == 0 && leeches.own > SPRAY_LEECHES) npc.state = BLUB_SPRAY; + else + { + uint32_t roll = Random(); + bool isJumping = isHurt ? roll % JUMPS_HURT_ODDS == 0 : roll % JUMPS_ODDS == 0 && leeches.own >= JUMPS_LEECHES; + if (!isJumping) return; + npc.state = BLUB_JUMPS; + npc.projectileDelay = 1; + if (isHurt) npc.projectileDelay += (int)(Random() % JUMPS_HURT_RANGE) + JUMPS_HURT_EXTRA; + } +} + +// Throws one to three small leeches of its own (twice as tough) about it. +static void blub_leeches_throw(Entity_NPC& npc) +{ + for (uint32_t i = Random() % LEECHES_RANGE + 1; i != 0; i--) + { + Vector spot = vector_add(npc.pos, vector_scale(random_direction(), LEECH_OUT)); + Entity_NPC* leech = blub_leech_throw(npc, vector_make(spot.x + 0, spot.y + LEECH_DROP), false); + leech->spawnerType = npc.type; + leech->spawnerVariant = (uint32_t)npc.variant; + leech->maxHitPoints *= 2; + leech->health = leech->maxHitPoints; + leech->parent = &npc; + } + blub_splash_spawn(npc.pos, vector_make(npc.velocity.x + 0, npc.velocity.y + BLUB_SPLASH_FALL), SPLASH_RAISE); + npc_sound_play(SOUND_MONSTER_GRUNT_2, 1, 2, champion_pitch_get(npc)); +} + +// Throws a big leech at its target within 90. +static void blub_big_leech_throw(Entity_NPC& npc) +{ + Vector gap = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + float distance = vector_length(gap); + if (distance > BIG_LEECH_REACH) gap = vector_scale(gap, BIG_LEECH_REACH / distance); + Entity_NPC* leech = blub_leech_throw(npc, vector_add(npc.pos, gap), true); + leech->spawnerType = npc.type; + leech->spawnerVariant = (uint32_t)npc.variant; + blub_splash_spawn(npc.pos, vector_make(npc.velocity.x + 0, npc.velocity.y + BLUB_SPLASH_FALL), SPLASH_RAISE); + npc.PlaySound(SOUND_MONSTER_GRUNT_1, 1, 2, false, 1); +} + +// The spray: a ring of six shots each other frame, its leeches pushed off. +static void blub_spray_update(Entity_NPC& npc, float& leechPush) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_MONSTER_GRUNT_4, 1, 2, false, 1); + leechPush = BLUB_SPRAY_PUSH; + npc.v1.x = random_unit() * FULL_TURN_DEGREES; + } + if (!npc.sprite.WasEventTriggered("Shoot")) return; + + int step = npc.projectileDelay; + if (step % 2 == 0 && step < BLUB_SPRAY_END) + for (int i = 0; i < BLUB_SPRAY_SHOTS; i++) + { + Vector ring = vector_from_angle((float)i * SPRAY_STEP + npc.v1.x); + Vector direction = vector_rotated(ring, random_unit() * BLUB_SPRAY_JITTER - BLUB_SPRAY_JITTER_HALF); + float roll = random_unit(); + ProjectileParams params; + params.heightModifier = BLUB_SPRAY_HEIGHT; + params.variant = blub_shot_variant(); + params.fallingAccelModifier = roll * BLUB_SPRAY_FALL_RANGE + BLUB_SPRAY_FALL; + params.scale = roll * BLUB_SPRAY_SCALE_RANGE + BLUB_SPRAY_SCALE; + Vector velocity = vector_scale(direction, BLUB_SPRAY_SPEED * (roll * SPRAY_SPEED_RANGE + SPRAY_SPEED_SHARE)); + Vector scatter = vector_scale(random_direction(), BLUB_SPRAY_SCATTER); + Vector position = vector_add(vector_add(scatter, vector_scale(direction, SPRAY_OUT)), npc.pos); + npc.FireProjectiles(position, velocity, PROJECTILES_SINGLE, params); + if (npc.projectileDelay % SPRAY_SPLASH_EVERY != 0) continue; + blub_splash_spawn(vector_add(npc.pos, vector_scale(direction, SPRAY_SPLASH_OUT)), + vector_scale(direction, SPRAY_SPLASH_SPEED), SPRAY_SPLASH_RAISE); + } + npc.projectileDelay = step + 1; +} + +// The jumps: a leap at its target, landing with a crush, its leeches pushed off. Whether it keeps on. +static bool blub_jumps_update(Entity_NPC& npc, float& leechPush, bool isHurt) +{ + if (npc.sprite.IsEventTriggered("Jump")) + { + npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + npc.PlaySound(SOUND_BOSS2_DIVE, 1, 2, false, 1); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BIG_SPLASH, .seed = Random()})->Update(); + Entity* target = npc.GetPlayerTarget(); + float distance = vector_distance(npc.pos, target->pos); + Vector lead = vector_add(target->pos, vector_scale(target->velocity, JUMP_LEAD * distance)); + Vector landing = g_game->room->GetClampedPositionImpl(lead, BLUB_JUMP_MARGIN, 0, 0, 0); + Vector gap = vector_sub(landing, npc.pos); + float reach = isHurt ? JUMP_HURT_REACH : BLUB_JUMP_REACH; + float length = vector_length(gap); + if (reach < length && length > 0) gap = vector_scale(gap, reach / length); + leechPush = BLUB_JUMP_PUSH; + npc.targetPosition = vector_add(gap, npc.pos); + npc.v2 = vector_scale(vector_sub(npc.targetPosition, npc.pos), BLUB_JUMP_STEP); + npc.entityCollisionClass = ENTCOLL_NONE; + } + if (npc.sprite.IsEventTriggered("Land")) + { + npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BIG_SPLASH, .seed = Random()})->Update(); + npc.targetPosition = {}; + npc.entityCollisionClass = ENTCOLL_ALL; + if (!isHurt) npc.stateFrame = JUMP_FOUNTAIN_FRAMES; + else + { + ProjectileParams params; + params.variant = blub_shot_variant(); + npc.FireProjectiles(npc.pos, vector_make(JUMP_PLUS_SPEED, 0), PROJECTILES_PLUS, params); + npc.FireProjectiles(npc.pos, vector_make(JUMP_CROSS_SPEED, 0), PROJECTILES_CROSS, params); + } + for (Entity* other : entity_query_radius(npc.pos, JUMP_CRUSH_REACH, QUERY_ENEMIES)) + if (other->IsVulnerableEnemy(nullptr)) other->TakeDamage(JUMP_CRUSH_DAMAGE, DAMAGE_EXPLOSION, EntityRef(&npc), JUMP_CRUSH_COUNTDOWN); + game_shake_screen(BLUB_JUMP_SHAKE); + npc.projectileDelay--; + } + + if (vector_is_zero(npc.targetPosition)) npc.friction *= JUMP_LANDED_FRICTION; + else + { + npc.friction *= BLUB_JUMP_FRICTION; + npc.velocity = vector_scale(npc.v2, 1 / npc.friction); + } + if (npc.stateFrame > 0) + { + npc.stateFrame--; + ProjectileParams params; + params.variant = blub_shot_variant(); + npc.FireBossProjectiles((int)(Random() & 1) + 1, {}, 0, params); + } + if (npc.projectileDelay >= 1 && npc.sprite.IsEventTriggered("Shoot")) npc.sprite.animState.SetFrameFloat(JUMP_LOOP_FRAME); + return npc.sprite.IsPlaying(); +} + +// It floats in the room, bouncing off its edges, drifting diagonally (or wandering confused). +static void blub_float_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.pos = room.GetClampedPositionImpl(npc.pos, BLUB_TOP_MARGIN, 0, 0, 0); + if (npc.pos.x == room.bottomRightPos.x) npc.velocity.x = -1; + if (npc.pos.x == room.topLeftPos.x) npc.velocity.x = 1; + if (npc.pos.y == room.bottomRightPos.y) npc.velocity.y = -1; + if (npc.pos.y == room.topLeftPos.y + BLUB_TOP_MARGIN) npc.velocity.y = 1; + + bool isSlow = npc.variant == 0 && npc.subtype == BLUB_SLOW_SUBTYPE; + if (npc.HasEntityFlags(FLAG_CONFUSION) && !npc.HasEntityFlags(FLAG_CHARM)) + { + npc.friction *= BLUB_FRICTION; + if (isSlow) npc.friction *= BLUB_SLOW_FRICTION; + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + return; + } + + Vector drift = vector_make(npc.velocity.x > 0 ? 1.0f : -1.0f, npc.velocity.y < BLUB_DRIFT_TURN ? -1.0f : 1.0f); + npc.friction *= BLUB_FRICTION; + npc_push(npc, vector_scale(drift, BLUB_DRIFT)); + if (isSlow) npc.friction *= BLUB_SLOW_FRICTION; + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) return; + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float distance = vector_length(away); + if (distance > 0) away = vector_scale(away, std::clamp((BLUB_FLEE_REACH - distance) * BLUB_FLEE_SHARE, 0.0f, 1.0f) / distance); + npc_push(npc, away); +} + +// Dying: a big splash, a fountain of shots, and two to four more leeches. +static void blub_burst(Entity_NPC& npc) +{ + Entity* splash = g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BIG_SPLASH, .seed = Random()}); + splash->sprite.scale = vector_make(DEATH_SPLASH_SCALE, DEATH_SPLASH_SCALE); + splash->Update(); + Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(&blub_fountain_timer), 1, DEATH_TIMER_TIMES, false); + timer->pos = npc.pos; + timer->Update(); + for (uint32_t i = Random() % DEATH_LEECHES_RANGE + DEATH_LEECHES; i != 0; i--) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float reach = random_unit() * DEATH_LEECH_REACH; + blub_leech_throw(npc, vector_add(npc.pos, vector_make(std::cos(angle) * reach, std::sin(angle) * reach)), false); + } +} + +// 00450da0 Lil Blub floats about its flooded room throwing leeches, spraying rings of water and jumping at its +// target, pushing its leeches off when it sprays, jumps or dies. +void boss_lil_blub_update(Entity_NPC& npc) +{ + float leechPush = -1; + BlubLeeches leeches = blub_leeches_count(npc); + bool isHurt = npc.health / npc.maxHitPoints < BLUB_HURT_HEALTH; + + bool isEnded = false; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = BLUB_REST; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.targetPosition = {}; + npc.splatColor = blub_is_sewage() ? SEWAGE_SPLASH_COLOR : WATER_SPLASH_COLOR; + npc.projectileDelay = 0; + npc.stateFrame = 0; + break; + case BLUB_REST: + blub_rest_update(npc, leeches, isHurt); + break; + case BLUB_LEECHES: + npc.sprite.Play("Attack01"); + if (npc.sprite.IsEventTriggered("Shoot")) blub_leeches_throw(npc); + isEnded = !npc.sprite.IsPlaying(); + break; + case BLUB_BIG_LEECH: + npc.sprite.Play("Attack02"); + if (npc.sprite.IsEventTriggered("Shoot")) blub_big_leech_throw(npc); + isEnded = !npc.sprite.IsPlaying(); + break; + case BLUB_SPRAY: + npc.sprite.Play("Attack03"); + blub_spray_update(npc, leechPush); + isEnded = !npc.sprite.IsPlaying(); + break; + case BLUB_JUMPS: + npc.sprite.Play("Attack04"); + isEnded = !blub_jumps_update(npc, leechPush, isHurt); + if (isEnded) npc.stateFrame = 0; + break; + } + if (isEnded) npc.state = BLUB_REST; + + blub_float_update(npc); + if (npc.isDead) + { + leechPush = DEATH_PUSH; + blub_burst(npc); + } + if (leechPush <= 0) return; + + for (Entity* leech : g_game->room->entityList.updateEL) + { + if (leech->type != ENTITY_SMALL_LEECH || leech->parent.get() != &npc) continue; + leech->parent = nullptr; + npc_push(*leech, vector_scale(vector_normalized(vector_sub(leech->pos, npc.pos)), leechPush)); + static_cast(leech)->v1.x = 0; + leech->health = std::min(leech->health, leech->maxHitPoints * LEECH_HEALTH_SHARE); + } +} diff --git a/src/boss_matriarch.cpp b/src/boss_matriarch.cpp new file mode 100644 index 0000000..6cb1cab --- /dev/null +++ b/src/boss_matriarch.cpp @@ -0,0 +1,574 @@ +#include "boss_ai.h" +#include "boss_repentance.h" +#include "entity_config.h" +#include "manager.h" +#include "npc_basement.h" +#include "npc_depths.h" +#include +#include +#include +#include + +// The Matriarch's states: resting, flinching from a lost chunk, hopping, flinching in the air, spitting a Fistuloid, +// spraying worms, spitting a big shot, her rage of Fistuloids and her death into Chub. +enum MatriarchState +{ + MATRIARCH_IDLE = NPC_STATE_IDLE, + MATRIARCH_FLINCH = NPC_STATE_SUICIDE, + MATRIARCH_HOP = NPC_STATE_JUMP, + MATRIARCH_AIR_FLINCH = NPC_STATE_STOMP, + MATRIARCH_SUMMON = NPC_STATE_ATTACK, + MATRIARCH_WORMS = NPC_STATE_ATTACK2, + MATRIARCH_SHOT = NPC_STATE_ATTACK3, + MATRIARCH_RAGE = NPC_STATE_SUMMON, + MATRIARCH_DEATH = NPC_STATE_SPECIAL +}; + +// She loses a chunk at 80, 65, 50 and 35 percent of her health: a Fistula or two (from the third) thrown back 40 out +// within 45 degrees of away from her target at 2 to 4, flinching back at 20 (6 in the air). Each chunk adds 90 to +// her anger (i1), which hits raise by 1 plus 0.6 per chunk lost, falling 1 a frame. +constexpr std::array MATRIARCH_CHUNKS = {0.8f, 0.65f, 0.5f, 0.35f}; +constexpr float CHUNK_VOLUME = 0.8f; +constexpr int CHUNK_TWO_FROM = 1; +constexpr float CHUNK_SPREAD = 90; +constexpr float CHUNK_SPREAD_HALF = 45; +constexpr float CHUNK_OUT = 40; +constexpr float CHUNK_SPEED = 2; +constexpr float CHUNK_SPEED_RANGE = 2; +constexpr int CHUNK_FISTULA_SUBTYPE = 1000; +constexpr float CHUNK_BLOOD_SHARE = 0.5f; +constexpr float CHUNK_FLINCH_SPEED = 20; +constexpr float CHUNK_AIR_FLINCH_SPEED = 6; +constexpr int CHUNK_ANGER = 90; +constexpr float ANGER_PER_CHUNK = 0.6f; +constexpr float BLOOD_RAISE = -16; +constexpr int BLOOD_SUBTYPE_FISTULA = 4; +constexpr int BLOOD_SUBTYPE_SPLASH = 3; +constexpr int BLOOD_SUBTYPE_MEDIUM = 2; +constexpr int BLOOD_SUBTYPE_SMALL = 1; + +// Resting: angered past 300 with three chunks lost she rages one time in five. Else one time in 12 she attacks: a +// Fistuloid (weight 100, 300 when angered past 150 or none is out, none with four out or when it would cost a chunk), +// worms (100) or a shot (100, 200 when cooled down). Else one time in ten she hops. +constexpr int RAGE_ANGER = 300; +constexpr int RAGE_CHUNKS = 3; +constexpr uint32_t MATRIARCH_RAGE_ODDS = 5; +constexpr int RAGE_START_ANGER = 400; +constexpr uint32_t MATRIARCH_ATTACK_ODDS = 12; +constexpr uint32_t SUMMON_WEIGHT = 100; +constexpr uint32_t SUMMON_ANGRY_WEIGHT = 300; +constexpr int SUMMON_ANGER = 150; +constexpr size_t SUMMON_LIMIT = 3; +constexpr int MATRIARCH_ATTACK_WEIGHT = 100; +constexpr int ATTACK_COOLED_WEIGHT = 200; +constexpr uint32_t MATRIARCH_HOP_ODDS = 10; +constexpr float IDLE_FRICTION = 0.5f; +constexpr float FLINCH_FRICTION = 0.8f; + +// A hop at 6 at her target or the Fistuloid she leads, swerving 45 degrees when the swerve lands 128 out in the room +// and the target is more than 100 away. +constexpr float HOP_SPEED = 6; +constexpr float HOP_SWERVE_REACH = 100; +constexpr float HOP_SWERVE = 45; +constexpr float HOP_SWERVE_OUT = 128; +constexpr float MATRIARCH_LAND_VOLUME = 0.7f; + +// A Fistuloid spat 20 ahead and 4 up at 10 (4 up), costing her its health down to a point above her next chunk. +constexpr float SUMMON_OUT = 20; +constexpr float SUMMON_RAISE = 4; +constexpr float MATRIARCH_SUMMON_SPEED = 10; +constexpr float SUMMON_BLOOD_SHARE = 0.3f; +constexpr int SUMMON_HIT_COUNTDOWN = 30; + +// Worms: eight Chubber worms on an ellipse of 16 (22.4 across), their blood thrown at 0.3, 0.5 and 0.6 of their speed. +constexpr int WORMS = 8; +constexpr float WORM_STEP = 45; +constexpr float WORM_REACH = 16; +constexpr float WORM_WIDTH = 1.4f; +constexpr int WORM_SUBTYPE = 2; +constexpr float WORM_BLOOD_SPLASH = 0.3f; +constexpr float WORM_BLOOD_MEDIUM = 0.5f; +constexpr float WORM_BLOOD_SMALL = 0.6f; +constexpr float WORM_SOUND_VOLUME = 0.8f; + +// A shot: a big red shot leaving creep at 10 from 40 ahead and 3 down, at where her target will be (a tenth of its +// speed per unit of distance, in the room), turned 45 degrees at most from straight ahead, cooling 90 to 149 frames. +constexpr float MATRIARCH_SHOT_LEAD = 0.1f; +constexpr float SHOT_MARGIN = 4; +constexpr float SHOT_OUT = 40; +constexpr float SHOT_DROP = 3; +constexpr float SHOT_TURN_MAX = 45; +constexpr float MATRIARCH_SHOT_SPEED = 10; +constexpr float MATRIARCH_SHOT_SCALE = 2; +constexpr float SHOT_SPIT_PITCH = 0.8f; +constexpr float SHOT_HEART_VOLUME = 0.8f; +constexpr float SHOT_BLOOD_RAISE = -10; +constexpr uint32_t SHOT_COOLDOWN_RANGE = 60; +constexpr int SHOT_COOLDOWN = 90; + +// Her rage: she lets her Fistuloid go and spits one every 8 frames one time in two, within 90 degrees of her target, +// 20 out at 5 to 10, with half health, that dies on touch and the player cannot steer, until her anger falls to +// nothing at 2 a frame. +constexpr int RAGE_SPIT_EVERY = 8; +constexpr float RAGE_SPREAD = 180; +constexpr float RAGE_SPREAD_HALF = 90; +constexpr float RAGE_OUT = 20; +constexpr float RAGE_SPEED = 5; +constexpr float RAGE_SPEED_RANGE = 5; +constexpr float RAGE_HEALTH_SHARE = 0.5f; +constexpr int RAGE_ANGER_DRAIN = 2; +constexpr ColorMod RAGE_LOOSE_COLOR = {{1.5f, 0.6f, 0.6f, 1}, {0, 0, 0, 0}, {0.4f, 0.08f, 0.05f}}; +constexpr ColorMod RAGE_LOOSE_FLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.8f, 0.3f, 0.2f}}; +constexpr int RAGE_LOOSE_FLASH_FRAMES = 15; + +// Every 15 frames one time in two, leading none, she takes one of her Fistuloids to lead when at most one other +// door-shutting enemy is out (or one time in 100). +constexpr int LEAD_EVERY = 15; +constexpr uint32_t LEAD_CROWD_ODDS = 100; + +// At a fifth of her health she bursts (a Fistula 40 out at 2 to 4, see below) and turns into a three-part Chub at a +// fifth of her health, her parts at her full health, in front of her. +constexpr float DEATH_HEALTH = 0.2f; +constexpr int DEATH_BURST_FISTULAS = 3; +constexpr int CHUB_SUBTYPE = 1000; +constexpr int CHUB_HEAD_DEPTH = 1500; +constexpr int CHUB_MIDDLE_DEPTH = 500; +constexpr int CHUB_TAIL_DEPTH = -500; +constexpr float CHUB_MIDDLE_SHADOW = 0.34f; +constexpr float CHUB_TAIL_SHADOW = 0.26f; +constexpr int MATRIARCH_CHUB_CHARGE = NPC_STATE_ATTACK; + +// The chunk threshold she is at, none past her last. +static float matriarch_chunk_health(Entity_NPC& npc) +{ + // The original reads past the table at her fifth chunk, a value so large no summon or cost fits under it. + return npc.i2 < (int)MATRIARCH_CHUNKS.size() ? MATRIARCH_CHUNKS[(size_t)npc.i2] * npc.maxHitPoints : INFINITY; +} + +// A blood explosion raised to her mouth (FUN_004c5980). +static void matriarch_blood_spawn(int subType, const Vector& position, const Vector& velocity, float raise) +{ + Entity* blood = g_game->Spawn({.position = position, + .velocity = velocity, + .subType = subType, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->posOffset = vector_make(0, raise); +} + +// A Fistula thrown out of her along a direction, free of the boss bar. +static void matriarch_fistula_throw(Entity_NPC& npc, int type, Vector direction) +{ + Vector position = vector_add(npc.pos, vector_scale(direction, CHUNK_OUT)); + uint32_t seed = Random(); + float speed = random_unit() * CHUNK_SPEED_RANGE + CHUNK_SPEED; + Entity* fistula = g_game->Spawn({.position = position, + .velocity = vector_scale(direction, speed), + .spawner = &npc, + .subType = CHUNK_FISTULA_SUBTYPE, + .type = type, + .seed = seed}); + fistula->ClearEntityFlags(FLAG_APPEAR); + fistula->AddEntityFlags(FLAG_DONT_COUNT_BOSS_HP); + matriarch_blood_spawn(BLOOD_SUBTYPE_FISTULA, position, vector_scale(direction, CHUNK_BLOOD_SHARE), BLOOD_RAISE); +} + +// The hits that would take her past her next chunks throw Fistulas off her and make her flinch. +static void matriarch_chunks_update(Entity_NPC& npc) +{ + float health = npc.health - npc.pendingDamage; + while (npc.i2 < (int)MATRIARCH_CHUNKS.size() && health < matriarch_chunk_health(npc)) + { + npc_sound_play(SOUND_DEATH_BURST_LARGE, CHUNK_VOLUME, 2, 1); + Vector away = vector_normalized(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)); + for (int i = 0; i < (npc.i2 > CHUNK_TWO_FROM) + 1; i++) + { + float angle = random_unit() * CHUNK_SPREAD - CHUNK_SPREAD_HALF; + matriarch_fistula_throw(npc, ENTITY_FISTULA_SMALL, vector_rotated(away, angle)); + } + + bool isAirborne = npc.state == MATRIARCH_HOP && npc.sprite.WasEventTriggered("Jump") && + !npc.sprite.WasEventTriggered("Land"); + if (isAirborne) + { + npc.sprite.Play("AirFlinch"); + npc.state = MATRIARCH_AIR_FLINCH; + npc.velocity = vector_scale(away, CHUNK_AIR_FLINCH_SPEED); + } + else if (npc.state != MATRIARCH_FLINCH && npc.state != MATRIARCH_AIR_FLINCH) + { + npc.sprite.Play("Flinch"); + npc.state = MATRIARCH_FLINCH; + npc.velocity = vector_scale(away, CHUNK_FLINCH_SPEED); + } + npc.i2++; + npc.i1 += CHUNK_ANGER; + } +} + +// A Fistuloid's health, what spitting one costs her. +static float fistuloid_health_get() +{ + // The original reads a missing config through a null pointer. Here it costs nothing. + EntityConfig_Entity* config = g_manager->entityConfig.GetEntity(ENTITY_FISTULOID, 0, 0); + return config ? config->baseHP : 0; +} + +// Resting: her rage, an attack or a hop. +static void matriarch_idle_update(Entity_NPC& npc) +{ + npc.sprite.Play("Idle"); + npc.friction *= IDLE_FRICTION; + if (npc.i1 > RAGE_ANGER && npc.i2 >= RAGE_CHUNKS && Random() % MATRIARCH_RAGE_ODDS == 0) + { + npc.sprite.Play("RageBegin"); + npc.state = MATRIARCH_RAGE; + npc.stateFrame = 0; + npc.i1 = RAGE_START_ANGER; + return; + } + + if (Random() % MATRIARCH_ATTACK_ODDS != 0) + { + if (Random() % MATRIARCH_HOP_ODDS != 0) return; + npc.state = MATRIARCH_HOP; + npc.sprite.Play(Random() & 1 ? "Jump" : "Jump2"); + return; + } + + size_t led = 0; + for (Entity* fistuloid : Entity_NPC::QueryNPCsType(ENTITY_FISTULOID, -1)) + if (fistuloid->parent.get() == &npc) led++; + uint32_t summonWeight = SUMMON_WEIGHT; + if (led > SUMMON_LIMIT || npc.health - fistuloid_health_get() < matriarch_chunk_health(npc)) summonWeight = 0; + else if (npc.i1 > SUMMON_ANGER || led == 0) summonWeight = SUMMON_ANGRY_WEIGHT; + uint32_t shotWeight = npc.projectileCooldown < 1 ? ATTACK_COOLED_WEIGHT : MATRIARCH_ATTACK_WEIGHT; + uint32_t roll = Random() % (shotWeight + summonWeight); + if (roll < summonWeight) + { + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + npc.state = MATRIARCH_SUMMON; + } + else npc.state = roll < summonWeight + MATRIARCH_ATTACK_WEIGHT ? MATRIARCH_WORMS : MATRIARCH_SHOT; +} + +// A hop at her target, or the Fistuloid she leads. +static void matriarch_hop_start(Entity_NPC& npc) +{ + Vector direction{}; + if (Entity* led = npc.child.get()) direction = vector_normalized(vector_sub(led->pos, npc.pos)); + else + { + Vector gap = vector_sub(npc.CalcTargetPosition(0), npc.pos); + direction = vector_normalized(gap); + if (vector_length(gap) > HOP_SWERVE_REACH) + { + Vector swerve = vector_rotated(direction, Random() & 1 ? -HOP_SWERVE : HOP_SWERVE); + if (g_game->room->IsPositionInRoom(vector_add(npc.pos, vector_scale(swerve, HOP_SWERVE_OUT)), 0)) direction = swerve; + } + } + npc.targetPosition = vector_scale(direction, HOP_SPEED); + npc.velocity = npc.targetPosition; +} + +// Where her shot aims: her target ahead by a tenth of its speed per unit of distance, kept in the room. +static Vector matriarch_shot_aim(Entity_NPC& npc) +{ + Entity* target = npc.GetPlayerTarget(); + float distance = vector_distance(npc.pos, target->pos); + Vector aim = vector_add(target->pos, vector_scale(target->velocity, MATRIARCH_SHOT_LEAD * distance)); + return g_game->room->GetClampedPositionImpl(aim, SHOT_MARGIN, SHOT_MARGIN, SHOT_MARGIN, SHOT_MARGIN); +} + +// Spits a Fistuloid ahead, costing her its health down to just above her next chunk. +static void matriarch_summon_spit(Entity_NPC& npc) +{ + npc_sound_play(SOUND_SUMMONSOUND, 1, 2, 1); + float side = npc.sprite.isFlipX ? -1.0f : 1.0f; + Vector position = vector_make(npc.pos.x + side * SUMMON_OUT, npc.pos.y - SUMMON_RAISE); + Vector velocity = vector_make(-side * MATRIARCH_SUMMON_SPEED, -SUMMON_RAISE); + auto* fistuloid = static_cast(g_game->Spawn( + {.position = position, .velocity = velocity, .spawner = &npc, .type = ENTITY_FISTULOID, .seed = Random()})); + fistuloid->parent = &npc; + fistuloid->ClearEntityFlags(FLAG_APPEAR); + fistuloid_orbit_spread(*fistuloid); + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + matriarch_blood_spawn(BLOOD_SUBTYPE_SPLASH, position, vector_scale(fistuloid->velocity, SUMMON_BLOOD_SHARE), BLOOD_RAISE); + + float left = std::max(npc.health - fistuloid_health_get(), matriarch_chunk_health(npc) + 1); + if (left < npc.health) npc.TakeDamage(npc.health - left, 0, EntityRef(), SUMMON_HIT_COUNTDOWN); +} + +// Sprays a ring of eight Chubber worms, each in its blood. +static void matriarch_worms_spray(Entity_NPC& npc) +{ + npc_sound_play(SOUND_HEARTOUT, WORM_SOUND_VOLUME, 2, 1); + for (int i = 0; i < WORMS; i++) + { + Vector unit = vector_from_angle((float)i * WORM_STEP); + Vector velocity = vector_make(unit.x * WORM_REACH * WORM_WIDTH, unit.y * WORM_REACH); + auto* worm = static_cast(g_game->Spawn({.position = vector_add(npc.pos, velocity), + .velocity = velocity, + .spawner = &npc, + .subType = WORM_SUBTYPE, + .type = ENTITY_VIS, + .variant = CHUBBER_WORM, + .seed = Random()})); + worm->state = NPC_STATE_INIT; + worm->parent = &npc; + worm->Update(); + matriarch_blood_spawn(BLOOD_SUBTYPE_SPLASH, worm->pos, vector_scale(worm->velocity, WORM_BLOOD_SPLASH), BLOOD_RAISE); + matriarch_blood_spawn(BLOOD_SUBTYPE_MEDIUM, worm->pos, vector_scale(worm->velocity, WORM_BLOOD_MEDIUM), BLOOD_RAISE); + matriarch_blood_spawn(BLOOD_SUBTYPE_SMALL, worm->pos, vector_scale(worm->velocity, WORM_BLOOD_SMALL), BLOOD_RAISE); + } +} + +// Spits her big shot ahead, turned 45 degrees at most toward where her target will be. +static void matriarch_shot_fire(Entity_NPC& npc) +{ + npc_sound_play(SOUND_WORM_SPIT, 1, 2, SHOT_SPIT_PITCH); + npc_sound_play(SOUND_HEARTIN, SHOT_HEART_VOLUME, 2, 1); + Vector mouth = vector_make(npc.pos.x + (npc.sprite.isFlipX ? SHOT_OUT : -SHOT_OUT), npc.pos.y + SHOT_DROP); + Vector aim = matriarch_shot_aim(npc); + float ahead = npc.sprite.isFlipX ? 0 : HALF_TURN_DEGREES; + float turn = normalize_angle_degrees(vector_angle(vector_sub(aim, mouth)) - ahead); + Vector velocity = vector_scale(vector_from_angle(ahead + std::clamp(turn, -SHOT_TURN_MAX, SHOT_TURN_MAX)), MATRIARCH_SHOT_SPEED); + ProjectileParams params; + params.bulletFlags |= PROJECTILE_ACID_RED | PROJECTILE_RED_CREEP; + params.scale = MATRIARCH_SHOT_SCALE; + npc.FireProjectiles(mouth, velocity, PROJECTILES_SINGLE, params); + matriarch_blood_spawn(BLOOD_SUBTYPE_MEDIUM, mouth, velocity, SHOT_BLOOD_RAISE); + npc.projectileCooldown = (int)(Random() % SHOT_COOLDOWN_RANGE) + SHOT_COOLDOWN; +} + +// A Fistuloid gone wild in her rage: reddened, flashing, deadly on touch and beyond a player's control. +static void matriarch_fistuloid_loose(Entity& fistuloid) +{ + fistuloid.AddEntityFlags(FLAG_NO_PLAYER_CONTROL); + fistuloid.sprite.GetLayer(0)->color = RAGE_LOOSE_COLOR; + fistuloid.SetColor(RAGE_LOOSE_FLASH, RAGE_LOOSE_FLASH_FRAMES, COLOR_PRIORITY_DEFAULT, true, true); +} + +// Her rage: she lets her Fistuloid loose on the roar, then spits wild ones until her anger is spent. +static void matriarch_rage_update(Entity_NPC& npc) +{ + npc.friction *= IDLE_FRICTION; + if (npc.stateFrame == 0) + { + if (!npc.sprite.IsEventTriggered("Shoot")) return; + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + npc.stateFrame = 1; + npc.sprite.isFlipX = npc.pos.x < npc.CalcTargetPosition(0).x; + if (Entity* led = npc.child.get()) + { + led->parent = nullptr; + led->isKillOnTouch = true; + matriarch_fistuloid_loose(*led); + npc.child = nullptr; + } + return; + } + if (npc.stateFrame < 0) + { + if (!npc.sprite.IsPlaying()) npc.state = MATRIARCH_IDLE; + return; + } + + if (!npc.sprite.IsPlaying()) npc.sprite.Play("RageLoop"); + if (npc.stateFrame % RAGE_SPIT_EVERY == 0 && (Random() & 1) == 0) + { + npc_sound_play(SOUND_SUMMONSOUND, 1, 2, 1); + Vector toward = vector_normalized(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + Vector direction = vector_rotated(toward, random_unit() * RAGE_SPREAD - RAGE_SPREAD_HALF); + Vector position = vector_add(npc.pos, vector_scale(direction, RAGE_OUT)); + uint32_t seed = Random(); + float speed = random_unit() * RAGE_SPEED_RANGE + RAGE_SPEED; + Entity* fistuloid = g_game->Spawn({.position = position, + .velocity = vector_scale(direction, speed), + .spawner = &npc, + .type = ENTITY_FISTULOID, + .seed = seed}); + float health = fistuloid->maxHitPoints * RAGE_HEALTH_SHARE; + fistuloid->ClearEntityFlags(FLAG_APPEAR); + fistuloid->isKillOnTouch = true; + fistuloid->maxHitPoints = health; + fistuloid->health = health; + matriarch_fistuloid_loose(*fistuloid); + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + matriarch_blood_spawn(BLOOD_SUBTYPE_SPLASH, position, vector_scale(fistuloid->velocity, SUMMON_BLOOD_SHARE), BLOOD_RAISE); + } + npc.stateFrame++; + npc.i1 -= RAGE_ANGER_DRAIN; + if (npc.i1 >= 1) return; + npc.i1 = 0; + npc.stateFrame = -1; + npc.sprite.Play("RageEnd"); +} + +// Her death: she bursts and turns into Chub, two more parts trailing her, charging at her target. +static void matriarch_burst(Entity_NPC& npc) +{ + npc_sound_play(SOUND_ROCKET_BLAST_DEATH, 1, 2, 1); + uint32_t burst = Random(); + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_LARGE_BLOOD_EXPLOSION, .seed = burst}); + // The original counts its Fistulas on from the burst's seed, so all but one seed in a billion throw one small Fistula. + uint32_t thrown = burst; + do matriarch_fistula_throw(npc, thrown != 0 ? ENTITY_FISTULA_SMALL : ENTITY_FISTULA_MEDIUM, random_direction()); + while (++thrown < DEATH_BURST_FISTULAS); + + if (Entity* led = npc.child.get()) + { + led->parent = nullptr; + npc.child = nullptr; + } + auto* fistuloid = static_cast( + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_FISTULOID, .seed = Random()})); + fistuloid->parent = &npc; + fistuloid->ClearEntityFlags(FLAG_APPEAR); + fistuloid_orbit_spread(*fistuloid); + + float maxHealth = npc.maxHitPoints; + npc.RemoveStatusEffects(); + npc.Morph(ENTITY_CHUB, 0, CHUB_SUBTYPE, -1); + npc.maxHitPoints = maxHealth; + npc.spawnerType = ENTITY_MATRIARCH; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.health = maxHealth * DEATH_HEALTH; + auto* middle = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .subType = npc.subtype, .type = npc.type, .variant = npc.variant, .seed = Random()})); + auto* tail = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .subType = npc.subtype, .type = npc.type, .variant = npc.variant, .seed = Random()})); + middle->ClearEntityFlags(FLAG_APPEAR); + tail->ClearEntityFlags(FLAG_APPEAR); + npc.child = middle; + middle->parent = &npc; + middle->child = tail; + tail->parent = middle; + npc.ClearEntityFlags(FLAG_NO_DEATH_TRIGGER); + npc.i1 = 0; + npc.renderZOffset = CHUB_HEAD_DEPTH; + + // Chub's parts carry their place along it in i1. + for (auto [part, depth, shadow, place] : {std::tuple{middle, CHUB_MIDDLE_DEPTH, CHUB_MIDDLE_SHADOW, 1}, + std::tuple{tail, CHUB_TAIL_DEPTH, CHUB_TAIL_SHADOW, 2}}) + { + part->renderZOffset = depth; + part->shadowSize = shadow; + part->i1 = place; + part->AddEntityFlags(FLAG_DONT_COUNT_BOSS_HP); + part->maxHitPoints = npc.maxHitPoints; + part->health = npc.maxHitPoints; + } + + Vector toward = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + npc.v1 = vector_cardinal(toward); + npc.state = MATRIARCH_CHUB_CHARGE; + npc.stateFrame = 0; + npc.pathfinder.movementTarget = {}; + npc.pathfinder.moveDirection = {}; +} + +// Every 15 frames one time in two she takes a Fistuloid to lead, unless the room is crowded. +static void matriarch_lead_update(Entity_NPC& npc) +{ + if (!npc.IsFrame(LEAD_EVERY, 0) || npc.child || (Random() & 1) != 0) return; + + int crowd = 0; + for (Entity* entity : g_game->room->entityList.updateEL) + if (Entity::is_enemy_type(entity->type) && entity->CanShutDoors() && entity->type != ENTITY_MATRIARCH && + entity->type != ENTITY_FISTULOID) + crowd++; + if (crowd > 1 && Random() % LEAD_CROWD_ODDS != 0) return; + + std::vector led; + for (Entity* fistuloid : entity_query(ENTITY_FISTULOID, -1)) + if (fistuloid->parent.get() == &npc) led.push_back(fistuloid); + if (led.empty()) return; + Entity* picked = led[random_below((int)led.size())]; + npc.child = picked; + fistuloid_orbit_spread(static_cast(*picked)); +} + +// 004c59d0 The Matriarch hops about trailed by her Fistuloids, spitting them, worms and big shots. Losing chunks of +// her health throws Fistulas off her and angers her into a rage of wild Fistuloids. At a fifth of her health she +// bursts into Chub. +void boss_matriarch_update(Entity_NPC& npc) +{ + bool isDeliriumForm = npc.deliriumBossType != 0; + if (!isDeliriumForm && npc.pendingDamage > 0 && npc.state != MATRIARCH_RAGE) matriarch_chunks_update(npc); + + bool isEnded = true; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = MATRIARCH_IDLE; + npc.i1 = 0; + npc.i2 = 0; + isEnded = false; + break; + case MATRIARCH_IDLE: + matriarch_idle_update(npc); + isEnded = false; + break; + case MATRIARCH_FLINCH: + npc.friction *= FLINCH_FRICTION; + break; + case MATRIARCH_HOP: + case MATRIARCH_AIR_FLINCH: + { + if (npc.state == MATRIARCH_HOP && npc.sprite.IsEventTriggered("Jump")) matriarch_hop_start(npc); + if (npc.sprite.IsEventTriggered("Land")) npc_sound_play(SOUND_FORESTBOSS_STOMPS, MATRIARCH_LAND_VOLUME, 2, 1); + bool isAirborne = npc.sprite.WasEventTriggered("Jump") && !npc.sprite.WasEventTriggered("Land"); + if (isAirborne && npc.state == MATRIARCH_HOP) npc.sprite.isFlipX = npc.targetPosition.x > 0; + if (!isAirborne) npc.friction *= IDLE_FRICTION; + break; + } + case MATRIARCH_SUMMON: + npc.friction *= IDLE_FRICTION; + npc.sprite.Play("Attack1"); + if (npc.sprite.IsEventTriggered("Shoot")) matriarch_summon_spit(npc); + break; + case MATRIARCH_WORMS: + npc.friction *= IDLE_FRICTION; + npc.sprite.Play("Attack2"); + if (npc.sprite.IsEventTriggered("Shoot")) matriarch_worms_spray(npc); + break; + case MATRIARCH_SHOT: + npc.friction *= IDLE_FRICTION; + npc.sprite.Play("Attack3"); + if (npc.sprite.GetFrame() == 0) npc.sprite.isFlipX = npc.pos.x < matriarch_shot_aim(npc).x; + if (npc.sprite.IsEventTriggered("Shoot")) matriarch_shot_fire(npc); + break; + case MATRIARCH_RAGE: + matriarch_rage_update(npc); + npc.friction *= FLINCH_FRICTION; + break; + case MATRIARCH_DEATH: + npc.friction *= IDLE_FRICTION; + npc.sprite.Play("Death"); + if (!npc.sprite.IsPlaying()) return matriarch_burst(npc); + isEnded = false; + break; + default: + isEnded = false; + break; + } + if (isEnded && !npc.sprite.IsPlaying()) npc.state = MATRIARCH_IDLE; + + if (npc.projectileCooldown > 0) npc.projectileCooldown--; + if (npc.state != MATRIARCH_RAGE) + { + if (npc.pendingDamage > 0) npc.i1 += (int)(((float)npc.i2 * ANGER_PER_CHUNK + 1) * npc.pendingDamage); + if (npc.i1 > 0) npc.i1--; + matriarch_lead_update(npc); + } + if (!isDeliriumForm && (npc.isDead || npc.health <= npc.maxHitPoints * DEATH_HEALTH)) + { + npc.isDead = false; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.state = MATRIARCH_DEATH; + npc.health = npc.maxHitPoints * DEATH_HEALTH; + } +} diff --git a/src/boss_monstro.cpp b/src/boss_monstro.cpp index 78b7ca0..eb11efe 100644 --- a/src/boss_monstro.cpp +++ b/src/boss_monstro.cpp @@ -62,7 +62,6 @@ constexpr float LINE_UP_RANGE = 50; constexpr float REPEAT_REROLL_ODDS = 0.9f; constexpr float CRUSH_RADIUS = 70; constexpr float MONSTRO_CRUSH_DAMAGE = 30; -constexpr int CRUSH_COUNTDOWN = 30; constexpr float MONSTRO_LASER_HEIGHT = -20; constexpr float LASER_RIGHT_DEGREES = 0; constexpr float LASER_LEFT_DEGREES = 180; @@ -296,7 +295,7 @@ static void suckers_crush(Entity_NPC& npc) for (Entity* sucker : entity_query_radius(npc.pos, CRUSH_RADIUS, QUERY_ENEMIES)) if (sucker->type == ENTITY_SUCKER && sucker->variant == 0) - sucker->TakeDamage(MONSTRO_CRUSH_DAMAGE, 0, EntityRef(&npc), CRUSH_COUNTDOWN); + sucker->TakeDamage(MONSTRO_CRUSH_DAMAGE, 0, EntityRef(&npc), HIT_COUNTDOWN); } // A hop toward its target's cell: pulled there while airborne (harder for the quick one), dust where it lands, and diff --git a/src/boss_overlay.cpp b/src/boss_overlay.cpp new file mode 100644 index 0000000..cb6f833 --- /dev/null +++ b/src/boss_overlay.cpp @@ -0,0 +1,86 @@ +#include "boss_overlay.h" +#include "cutscene.h" +#include "game.h" +#include "manager.h" +#include "menu_manager.h" +#include "sfx_manager.h" + +// The 480 by 270 screen the overlays are drawn for, Dogma's static layer that ignores the game's time, and the room +// Dogma's shutdown leads to. +constexpr float OVERLAY_SCREEN_WIDTH = 480; +constexpr float OVERLAY_SCREEN_HEIGHT = 270; +constexpr int DOGMA_STATIC_LAYER = 4; +constexpr const char* EVENT_END = "End"; + +// The sound effects back to full volume at the normal fade. +static void sound_volume_restore() +{ + SFXManager& sounds = g_manager->sfxManager; + if (sounds.volumeModifier != 1) + { + sounds.volumeModifier = 1; + sounds.ClearVolumeModifier(); + } + sounds.volumeModifierStep = VOLUME_MODIFIER_STEP; +} + +// 004214b0 Shows an overlay: its .anm2 loaded and its animation played (Dogma's static layer ignoring the game's +// time). An id past the table is ignored. +void BossOverlay::play(int overlayType) +{ + if ((unsigned)overlayType >= BOSS_OVERLAY_COUNT) return; + + BossOverlayEntry& entry = entries[overlayType]; + sprite.Load(entry.anm2Path, GRAPHICS_LOAD); + sprite.LoadGraphics(); + type = overlayType; + if (overlayType == BOSS_OVERLAY_DOGMA_DYING || overlayType == BOSS_OVERLAY_DOGMA_DEAD) + sprite.GetLayer(DOGMA_STATIC_LAYER)->bitflags |= ANIM_RENDER_STATIC; + sprite.Play(entry.animation); + state = BOSS_OVERLAY_SHOWN; +} + +// 004212c0 Plays the overlay on, hiding a finished one that does not stay. Dogma's shutdown, at its "End" event, shows +// the Dogma cutscene (keeping the run, then the title) and takes the players through the fade to the Beast's +// floor, else hides once it is over. +void BossOverlay::update() +{ + if (state == BOSS_OVERLAY_HIDDEN) return; + + bool isFinished = !sprite.animState.animData || !sprite.animState.isPlaying; + if (isFinished && !entries[type].isPersistent) state = BOSS_OVERLAY_HIDDEN; + sprite.Update(); + if (type != BOSS_OVERLAY_DOGMA_DEAD) return; + + if (sprite.animState.animData && sprite.animState.IsEventTriggered(EVENT_END)) + { + g_manager->ShowCutscene(CUTSCENE_DOGMA, CUTSCENE_KEEP_STATE, MENU_TITLE); + sound_volume_restore(); + g_game->StartRoomTransition({.animation = TRANSITION_FADE, .roomIndex = ROOM_SECRET_EXIT_IDX}); + g_game->roomTransition.Update(); + return; + } + if (sprite.animState.animData && sprite.animState.isPlaying) return; + state = BOSS_OVERLAY_HIDDEN; + type = BOSS_OVERLAY_NONE; +} + +// 00421400 Draws the overlay stretched from its 480 by 270 screen over the real one, without the screen shake. +void BossOverlay::render() +{ + if (state == BOSS_OVERLAY_HIDDEN) return; + + DAT_00c33910 = 0; + sprite.scale = vector_make(g_screenWidth / OVERLAY_SCREEN_WIDTH, g_screenHeight / OVERLAY_SCREEN_HEIGHT); + sprite.Render({}); + DAT_00c33910 = 1; +} + +// 00421260 Hides the overlay, unloading its sprite, and the sound effects come back to full volume. +void BossOverlay::stop() +{ + sprite.Reset(); + state = BOSS_OVERLAY_HIDDEN; + type = BOSS_OVERLAY_NONE; + sound_volume_restore(); +} diff --git a/src/boss_overlay.h b/src/boss_overlay.h new file mode 100644 index 0000000..b17f80a --- /dev/null +++ b/src/boss_overlay.h @@ -0,0 +1,50 @@ +#pragma once + +#include "anm2.h" +#include +#include + +constexpr int BOSS_OVERLAY_COUNT = 5; + +// The overlays bossoverlays.xml defines, by id: the whiteouts and Dogma's static as it falls and shuts down. +enum BossOverlayType : int +{ + BOSS_OVERLAY_NONE, + BOSS_OVERLAY_WHITEOUT, + BOSS_OVERLAY_DOGMA_DYING, + BOSS_OVERLAY_DOGMA_DEAD, + BOSS_OVERLAY_BEAST_DEAD +}; + +// Whether the overlay is hidden or shows its entry. +enum BossOverlayState : int +{ + BOSS_OVERLAY_HIDDEN, + BOSS_OVERLAY_SHOWN +}; + +// A boss overlay animation as bossoverlays.xml defines it: its .anm2, its animation and whether it stays once played. +struct BossOverlayEntry +{ + std::string anm2Path; + std::string animation; + int id = 0; + bool isPersistent = false; +}; + +// Construction and destruction are the defaults. +// The full screen animations of the late bosses (Game's bossOverlay): the entries bossoverlays.xml defines and the one +// shown, stretched over the screen. +class BossOverlay +{ +public: + std::array entries; + ANM2 sprite; + BossOverlayState state = BOSS_OVERLAY_HIDDEN; + int type = BOSS_OVERLAY_NONE; + + void play(int overlayType); + void update(); + void render(); + void stop(); +}; diff --git a/src/boss_pool.cpp b/src/boss_pool.cpp index acf80dc..de8e093 100644 --- a/src/boss_pool.cpp +++ b/src/boss_pool.cpp @@ -27,24 +27,21 @@ constexpr uint32_t DOUBLE_TROUBLE_ODDS_CHAPTER_4 = 40; constexpr int BOSS_MONSTRO = 1; constexpr int BOSS_MOMS_HEART = 8; -constexpr int BOSS_DEATH = 12; constexpr int BOSS_HEADLESS_HORSEMAN = 22; constexpr int BOSS_IT_LIVES = 25; constexpr int BOSS_THE_BLOAT = 30; -constexpr int BOSS_CONQUEST = 38; constexpr int BOSS_THE_LAMB = 54; constexpr int BOSS_DELIRIUM = 70; constexpr int BOSS_REAP_CREEP = 74; // The Horsemen of the first floor of chapters 1 to 4, by chapter. -constexpr std::array HORSEMEN = {9, 10, 11, BOSS_DEATH}; +constexpr std::array HORSEMEN = {BOSS_FAMINE, BOSS_PESTILENCE, BOSS_WAR, BOSS_DEATH}; // The bosses the dark bosses special daily fixes on stages 1 to 7 (none on stage 6). constexpr int SPECIAL_DAILY_DARK_BOSSES = 13; constexpr std::array SPECIAL_DAILY_BOSSES = {0, 60, 43, 50, 23, 51, 0, 15}; constexpr int ACHIEVEMENT_HARBINGERS = 5; -constexpr int ACHIEVEMENT_FORGOTTEN_HORSEMAN = 66; constexpr int STAGE_CHAPTER_1 = 1; constexpr int STAGE_CHAPTER_2 = 3; @@ -252,7 +249,7 @@ int BossPool::GetBossId(int levelStage, int stageType) if (game.challenge == CHALLENGE_APRILS_FOOL) return BOSS_THE_BLOAT; bool isDailyStage = levelStage >= 0 && levelStage < (int)SPECIAL_DAILY_BOSSES.size(); - if (game.dailyChallenge._specialDailyId == SPECIAL_DAILY_DARK_BOSSES && isDailyStage && + if (game.dailyChallenge.specialDailyId == SPECIAL_DAILY_DARK_BOSSES && isDailyStage && SPECIAL_DAILY_BOSSES[levelStage] != 0) return SPECIAL_DAILY_BOSSES[levelStage]; if (int boss = chapter_end_boss(levelStage, stageType)) return boss; diff --git a/src/boss_pool.h b/src/boss_pool.h index 8f7369a..1122bce 100644 --- a/src/boss_pool.h +++ b/src/boss_pool.h @@ -13,9 +13,14 @@ constexpr int BOSS_ID_COUNT = 104; // The bosses the game checks by id (bossportraits.xml's ids). constexpr int BOSS_MOM = 6; +constexpr int BOSS_FAMINE = 9; +constexpr int BOSS_PESTILENCE = 10; +constexpr int BOSS_WAR = 11; +constexpr int BOSS_DEATH = 12; constexpr int BOSS_THE_FALLEN = 23; constexpr int BOSS_SATAN = 24; constexpr int BOSS_ISAAC = 39; +constexpr int BOSS_CONQUEST = 38; constexpr int BOSS_BLUE_BABY = 40; constexpr int BOSS_MEGA_SATAN = 55; constexpr int BOSS_ULTRA_GREED = 62; diff --git a/src/boss_repentance.h b/src/boss_repentance.h index 0798144..0027e96 100644 --- a/src/boss_repentance.h +++ b/src/boss_repentance.h @@ -44,3 +44,37 @@ 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); + +// Clutch (boss_clutch.cpp): the purple of his flames and Clickety Clacks' glow, the burning pile's mark (a Clickety +// Clack's i2), his beam to a Clickety Clack, his AI and his trail's drawing. +constexpr ColorMod CLUTCH_FLAME_COLOR = {{1, 1, 1, 1}, {1.3f, 1, 2, 1}, {0, 0, 0}}; +constexpr int CLACK_FLAME = 99; + +// The Clickety Clack's states Clutch drives (its stomp, its stun, getting up from its Regen's 15th frame and its pile +// of bones), Clutch's wait after a quick revert, and the pitch of his sounds. +constexpr int CLACK_STOMP = NPC_STATE_SUICIDE; +constexpr int CLACK_STUNNED = NPC_STATE_STOMP; +constexpr int CLACK_REGEN = NPC_STATE_SUMMON; +constexpr int CLACK_PILE = NPC_STATE_SPECIAL; +constexpr int CLACK_REGEN_FRAME = 15; +constexpr int CLUTCH_REVERT_WAIT = -1000; +constexpr float CLUTCH_SOUND_PITCH = 1.5f; +Entity* clutch_beam_spawn(Entity& spawner, Entity& target, Entity* parent); +void boss_clutch_update(Entity_NPC& npc); + +// The Chimera's forms, by variant: whole, its body once its head is off, and its head. +enum ChimeraVariant +{ + CHIMERA_WHOLE, + CHIMERA_BODY, + CHIMERA_HEAD +}; + +// The Repentance bosses of the Mausoleum's and Gehenna's ranks (boss_matriarch.cpp and its neighbours). +void boss_matriarch_update(Entity_NPC& npc); +void chimera_body_update(Entity_NPC& npc); +void chimera_head_update(Entity_NPC& npc); +void boss_lil_blub_update(Entity_NPC& npc); +void boss_bumbino_update(Entity_NPC& npc); +void singe_ball_update(Entity_NPC& npc); +void clutch_render(Entity_NPC& npc, const Vector& offset); diff --git a/src/boss_singe.cpp b/src/boss_singe.cpp new file mode 100644 index 0000000..e4d2cb1 --- /dev/null +++ b/src/boss_singe.cpp @@ -0,0 +1,188 @@ +#include "boss_ai.h" +#include "boss_repentance.h" +#include "entity_player.h" +#include "grid_entity.h" +#include "player_manager.h" +#include "room_grid.h" +#include +#include + +// Singe's ball rolls about untouchable, bounced by blasts. Its roll frame stands for its turn (v1.x, 0 to 1), its +// height (v2.y) and fall (v1.y) lift it, and i1 tells a sideways roll from an up-and-down one. +constexpr uint64_t BALL_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | FLAG_NO_DEATH_TRIGGER; +constexpr uint32_t BALL_SHIFT_1 = 2; +constexpr uint32_t BALL_SHIFT_2 = 5; +constexpr uint32_t BALL_SHIFT_3 = 15; +constexpr int BALL_ROLL_SIDEWAYS = 1; + +// Flat File retracts its spikes: the ball's sheet changes and it does no contact damage. +constexpr std::string_view SINGE_BALL_SHEET = "gfx/Bosses/repentance/singe_ball.png"; +constexpr std::string_view SINGE_BALL_RETRACTED_SHEET = "gfx/Bosses/repentance/singe_ball_retracted.png"; + +// It goes once no enemy is left (unless pressure plates hold the room under 9 frames of clearing). Above 50 it +// passes over things, and above 1 (or rising) over the floor's obstacles. +constexpr int BALL_CLEAR_DELAY = 9; +constexpr float SINGE_BALL_HIGH = -50; +constexpr float BALL_LIFTED = -1; + +// A blast pushes it away at up to 40 (less the faster it already rolls away, from 20 against to 20 along) and pops it +// up at 6. It falls 0.8 a frame, bouncing back at 0.35 above 4 with a thud, dropping into pits it lands over (and +// gone 10 below). +constexpr float SINGE_BLAST_PUSH = 20; +constexpr float BLAST_ALONG = 20; +constexpr float BLAST_ALONG_SPAN = 40; +constexpr float BLAST_POP = -6; +constexpr float SINGE_BALL_GRAVITY = 0.8f; +constexpr float BALL_SINK = 10; +constexpr float BALL_BOUNCE_MIN = 4; +constexpr float BALL_BOUNCE = -0.35f; +constexpr float THUD_VOLUME_SHARE = 0.1f; +constexpr float THUD_VOLUME = 0.2f; +constexpr float THUD_VOLUME_MAX = 1.2f; +constexpr float THUD_PITCH_RANGE = 0.2f; +constexpr float THUD_PITCH = 0.9f; + +// Rolling faster than 2 picks its roll's axis. It turns 0.02 of its speed a frame, slowing by 0.7 to 0.99 as it rolls +// from 0.5 to 4. +constexpr float ROLL_TURN_SPEED_SQUARED = 4; +constexpr float SINGE_ROLL_TURN = 0.02f; +constexpr float ROLL_SLOW = 0.5f; +constexpr float ROLL_SLOW_SPAN = 3.5f; +constexpr float ROLL_FRICTION_RANGE = 0.29000002f; +constexpr float ROLL_FRICTION = 0.7f; + +// Sets its roll animation still at the frame its turn shows. +static void singe_ball_roll_set(Entity_NPC& npc, std::string_view animation) +{ + if (npc.sprite.SetAnimation(animation, SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + if (npc.sprite.animState.animData) npc.sprite.animState.isPlaying = false; + } + if (const AnimationData* data = npc.sprite.animState.animData) + npc.sprite.animState.SetFrameFloat((float)(int)((float)data->length * npc.v1.x)); +} + +// The blasts of the frame push it away and pop it up. +static void singe_ball_blasts_update(Entity_NPC& npc) +{ + if (!(npc.pendingDamageFlags & DAMAGE_EXPLOSION)) return; + + for (DamageEvent& hit : npc.damageEvents) + { + if (!(hit.damageFlags & DAMAGE_EXPLOSION) || vector_is_zero(hit.source.position)) continue; + Vector away = vector_normalized(vector_sub(npc.pos, hit.source.position)); + float along = std::clamp((vector_dot(away, npc.velocity) + BLAST_ALONG) / BLAST_ALONG_SPAN, 0.0f, 1.0f); + float push = 2 - (along + along); + npc.velocity = vector_add(npc.velocity, vector_scale(away, push * SINGE_BLAST_PUSH * npc.speedMultiplier)); + if (npc.v2.y >= 0 && npc.v1.y >= 0) npc.v1.y = BLAST_POP; + } +} + +// Its height: falling (and bouncing, or dropping into a pit) while up or popped. +static void singe_ball_fall_update(Entity_NPC& npc) +{ + bool isAirborne = npc.v2.y < 0 || npc.v1.y < 0 || npc.entityGridCollisionClass == GRIDCOLL_PITSONLY; + if (!isAirborne) + { + npc.posOffset.y = npc.v2.y; + return; + } + + float fall = npc.v1.y; + npc.v1.y = npc.speedMultiplier * SINGE_BALL_GRAVITY + fall; + npc.v2.y += npc.speedMultiplier * fall; + if (npc.entityGridCollisionClass == GRIDCOLL_PITSONLY) + { + if (npc.v2.y > BALL_SINK) + { + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + npc.Remove(); + } + } + else if (npc.v2.y > 0) + { + Room& room = *g_game->room; + Vector ahead = vector_add(npc.pos, npc.velocity); + int column = (int)((ahead.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + HALF); + int row = (int)((ahead.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + HALF); + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + if (room.GetGridCollision(isInside ? room.gridWidth * row + column : -1) == COLLISION_PIT) + npc.entityGridCollisionClass = GRIDCOLL_PITSONLY; + else + { + npc.v2.y = 0; + if (npc.v1.y > 0 && npc.v1.y <= BALL_BOUNCE_MIN) npc.v1.y = 0; + else if (npc.v1.y > 0) + { + float pitch = random_unit() * THUD_PITCH_RANGE + THUD_PITCH; + npc_sound_play(SOUND_STONE_IMPACT, std::min(npc.v1.y * THUD_VOLUME_SHARE + THUD_VOLUME, THUD_VOLUME_MAX), 2, pitch); + npc.v1.y *= BALL_BOUNCE; + } + } + } + npc.posOffset.y = npc.v2.y; +} + +// 0058d8b0 Singe's ball rolls about wherever it is knocked, bounced by blasts and turning with its roll, harmless +// with Flat File. It goes with the last enemy, or into a pit. +void singe_ball_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.AddEntityFlags(BALL_FLAGS); + npc.isInvincible = true; + RNG turn = {npc.initSeed, BALL_SHIFT_1, BALL_SHIFT_2, BALL_SHIFT_3}; + npc.v1.y = 0; + npc.v2.y = 0; + npc.i1 = 0; + npc.i2 = 0; + npc.v1.x = turn.RandomFloat(); + singe_ball_roll_set(npc, "RollVert"); + npc.state = NPC_STATE_IDLE; + } + + Entity_Player* flatFile = g_game->playerManager.FirstTrinketOwner(TRINKET_FLAT_FILE); + if (flatFile && (flatFile->GetTrinketMultiplier(TRINKET_FLAT_FILE) > 1) != (npc.i2 != 0)) + { + bool isRetracted = flatFile->GetTrinketMultiplier(TRINKET_FLAT_FILE) > 1; + npc.i2 = isRetracted; + npc.sprite.ReplaceSpritesheet(0, isRetracted ? SINGE_BALL_RETRACTED_SHEET : SINGE_BALL_SHEET); + npc.sprite.LoadGraphics(); + npc.collisionDamage = npc.i2 == 0 ? 1.0f : 0.0f; + } + + Room& room = *g_game->room; + bool isRoomHeld = room.isTriggerPressurePlates && room.roomClearDelay >= BALL_CLEAR_DELAY; + if (npc.subtype == 0 && npc.GetAliveEnemyCount() < 1 && !isRoomHeld && !npc.isDead) npc.Kill(EntityRef()); + + if (npc.entityGridCollisionClass == GRIDCOLL_PITSONLY) npc.entityCollisionClass = ENTCOLL_NONE; + else + { + npc.entityCollisionClass = npc.v2.y > SINGE_BALL_HIGH ? ENTCOLL_ALL : ENTCOLL_NONE; + npc.entityGridCollisionClass = npc.v2.y <= BALL_LIFTED || npc.v1.y < 0 ? GRIDCOLL_NOPITS : GRIDCOLL_GROUND; + } + singe_ball_blasts_update(npc); + singe_ball_fall_update(npc); + + float speedSquared = vector_length_squared(npc.velocity); + int axis = std::abs(npc.velocity.y) < std::abs(npc.velocity.x) ? BALL_ROLL_SIDEWAYS : 0; + if (speedSquared > ROLL_TURN_SPEED_SQUARED && axis != npc.i1) + { + npc.i1 = axis; + singe_ball_roll_set(npc, axis == BALL_ROLL_SIDEWAYS ? "RollHori" : "RollVert"); + } + + float speed = std::sqrt(npc.v1.y * npc.v1.y + speedSquared); + float heading = npc.i1 == BALL_ROLL_SIDEWAYS ? npc.velocity.x : npc.velocity.y; + npc.v1.x += heading < 0 ? -speed * SINGE_ROLL_TURN : speed * SINGE_ROLL_TURN; + float slowing = std::clamp((speed - ROLL_SLOW) / ROLL_SLOW_SPAN, 0.0f, 1.0f); + npc.friction *= slowing * ROLL_FRICTION_RANGE + ROLL_FRICTION; + while (npc.v1.x < 0) npc.v1.x += 1; + while (npc.v1.x >= 1) npc.v1.x -= 1; + + const AnimationData* data = npc.sprite.animState.animData; + if (!data) return; + int frame = (int)((float)data->length * npc.v1.x); + if (frame != (int)std::floor(npc.sprite.animState.animFrame)) npc.sprite.animState.SetFrameFloat((float)frame); +} diff --git a/src/color_stack.cpp b/src/color_stack.cpp new file mode 100644 index 0000000..e60586b --- /dev/null +++ b/src/color_stack.cpp @@ -0,0 +1,23 @@ +#include "color_stack.h" +#include + +// The pushed colours, the last on top. +static std::vector colorStack; + +// 0040c890 Pushes a colour over every layer drawn until it is popped. +void color_stack_push(const ColorMod& color) +{ + colorStack.push_back(color); +} + +// Pops the top colour, as the callers of the push do inline. +void color_stack_pop() +{ + if (!colorStack.empty()) colorStack.pop_back(); +} + +// 0040c6f0 The colour layers draw in, null while none is pushed. +const ColorMod* color_stack_top() +{ + return colorStack.empty() ? nullptr : &colorStack.back(); +} diff --git a/src/color_stack.h b/src/color_stack.h new file mode 100644 index 0000000..80bf776 --- /dev/null +++ b/src/color_stack.h @@ -0,0 +1,8 @@ +#pragma once + +#include "classes.h" + +// KAGE's render colour stack: while a colour is pushed, every sprite layer draws in the top one instead of its own. +void color_stack_push(const ColorMod& color); +void color_stack_pop(); +const ColorMod* color_stack_top(); diff --git a/src/console.cpp b/src/console.cpp index 153132a..724cec7 100644 --- a/src/console.cpp +++ b/src/console.cpp @@ -24,38 +24,12 @@ #include #include -// The GLFW keys the console reads. -enum ConsoleKey : int -{ - KEY_V = 86, - KEY_GRAVE_ACCENT = 96, - KEY_ESCAPE = 256, - KEY_ENTER = 257, - KEY_BACKSPACE = 259, - KEY_DELETE = 261, - KEY_RIGHT = 262, - KEY_LEFT = 263, - KEY_DOWN = 264, - KEY_UP = 265, - KEY_PAGE_UP = 266, - KEY_PAGE_DOWN = 267, - KEY_HOME = 268, - KEY_END = 269, - KEY_KEYPAD_SUBTRACT = 333, - KEY_KEYPAD_ADD = 334, - KEY_KEYPAD_ENTER = 335, - KEY_LEFT_CONTROL = 341, - KEY_LEFT_SUPER = 343, - KEY_RIGHT_CONTROL = 345 -}; - constexpr std::string_view GREETING = "Repentance+ Console\n"; constexpr const char* HISTORY_FILE = "cmd_history.txt"; constexpr const char* WHITESPACE = " \t\n\v\f\r"; constexpr size_t HISTORY_LINE_MAX = 1024; constexpr size_t HISTORY_LOAD_MAX = 64; -// The Lua input hook and ButtonAction a mod can open the console with. -constexpr int INPUT_HOOK_TRIGGERED = 1; +// The ButtonAction a mod can open the console with. constexpr int ACTION_CONSOLE = 33; constexpr int SLIDE_FRAMES = 14; @@ -144,7 +118,7 @@ ConsoleText console_text_get() // Whether the console may be used: enabled in the options and not in a scored daily run. Netplay is offline. static bool is_console_allowed() { - bool isDailyScored = g_game && g_game->dailyChallenge._id != 0 && !g_game->dailyChallenge._isPractice; + bool isDailyScored = g_game && g_game->dailyChallenge.id != 0 && !g_game->dailyChallenge.isPractice; return !isDailyScored && g_manager->optionsConfig.isDebugConsoleEnabled; } diff --git a/src/console_commands.cpp b/src/console_commands.cpp index 8949700..421a6f7 100644 --- a/src/console_commands.cpp +++ b/src/console_commands.cpp @@ -775,7 +775,7 @@ static void macro_run(ConsoleCommand& command) size_t count = command.words.size(); Console& console = *command.console; - if (name == "lp") reconstruction_missing("Game::ChangeRoom 006fe2f0"); + if (name == "lp") return g_game->ChangeRoom(ROOM_LIL_PORTAL_IDX, -1); for (const ConsoleMacro& macro : MACROS) { if (macro.name != name) continue; @@ -969,10 +969,18 @@ static void reloadwisps_run(ConsoleCommand&) entity->Init(entity->type, entity->variant, entity->subtype, entity->initSeed); } -// rewind: restarts the run from the state the Glowing Hourglass keeps, without fading in. +// rewind: rewinds the run to the state the Glowing Hourglass keeps, then restarts it from the save on its seeds, +// without fading in. static void rewind_run(ConsoleCommand&) { - reconstruction_missing("Game::rewind 00706020"); + Manager& manager = *g_manager; + + Game::rewind(nullptr); + Manager::RestartGame(); + manager.startSeeds = g_game->seedEffects; + manager.isSaveOnExit = true; + manager.isRerunAvailable = true; + g_game->isInstantFadeIn = true; } static void clear_run(ConsoleCommand& command) diff --git a/src/cutscene.h b/src/cutscene.h index 5b15dd9..710b54f 100644 --- a/src/cutscene.h +++ b/src/cutscene.h @@ -14,6 +14,7 @@ // The cutscenes cutscenes.xml can fill, by id. Id 0 is no cutscene. constexpr int CUTSCENE_ENTRY_COUNT = 27; constexpr int CUTSCENE_CREDITS = 2; +constexpr int CUTSCENE_DOGMA = 25; constexpr int SUBTITLE_LINE_LIMIT = 4; constexpr int NO_PART = -1; diff --git a/src/daily_challenge.cpp b/src/daily_challenge.cpp new file mode 100644 index 0000000..9b6bd72 --- /dev/null +++ b/src/daily_challenge.cpp @@ -0,0 +1,293 @@ +#include "daily_challenge.h" +#include "entity_player.h" +#include "game.h" +#include "level.h" +#include "log.h" +#include "platform.h" +#include "room.h" +#include "seeds.h" +#include +#include +#include + +constexpr uint32_t DAILY_SHIFT_INDEX = 64; +constexpr uint32_t SPECIAL_DAILY_GROUNDHOG = 2; +constexpr uint32_t SPECIAL_DAILY_EASTER = 6; +constexpr uint32_t SPECIAL_DAILY_THANKSGIVING = 16; +constexpr uint32_t SPECIAL_DAILY_G_FUEL = 52; +constexpr const char* G_FUEL_SEED = "XRA8 J6GH"; +constexpr int NOVEMBER = 11; +constexpr int EASTER_LAST_YEAR = 3100; +constexpr int DAILY_ROLL_RANGE = 100; +constexpr int SUNDAY_HARD_ODDS = 6; + +// The characters a daily may draw (by its seed modulo 20, skipping the Lost, Lazarus risen and the Soul), and the +// stages a daily ends on by two bits of the seed. +constexpr int DAILY_CHARACTER_RANGE = 20; +constexpr std::array DAILY_SKIPPED_CHARACTERS = {PLAYER_LAZARUS2, PLAYER_THELOST, PLAYER_THESOUL}; +constexpr std::array DAILY_END_STAGES = {STAGE_DEPTHS_II, STAGE_WOMB_II, STAGE_SHEOL, STAGE_DARK_ROOM}; + +// The bounds of the rolls out of 100 picking a daily's end stage: on most days, past which the Chest is picked, and +// on Saturdays. +constexpr std::array STAGE_ROLLS = {20, 40, 50, 65, 80}; +constexpr int CHEST_ROLL = 89; +constexpr std::array SATURDAY_ROLLS = {15, 30, 40, 50, 60, 70, 80, 90}; + +// The weekdays that change a daily's rules. +enum DailyWeekday : int +{ + WEEKDAY_SUNDAY, + WEEKDAY_MONDAY, + WEEKDAY_TUESDAY, + WEEKDAY_WEDNESDAY, + WEEKDAY_THURSDAY, + WEEKDAY_FRIDAY, + WEEKDAY_SATURDAY +}; + +// A date's special daily, by month and day (MMDD), besides Easter, Thanksgiving and G FUEL's. +struct HolidayDate +{ + uint32_t monthDay = 0; + uint32_t specialDailyId = 0; +}; +constexpr std::array HOLIDAY_DATES = {{ + {101, 1}, {114, 20}, {116, 21}, {127, 22}, {202, 2}, {209, 23}, {211, 24}, {214, 3}, {218, 25}, + {302, 4}, {304, 26}, {317, 5}, {320, 27}, {322, 28}, {401, 7}, {410, 29}, {415, 30}, {422, 31}, + {504, 32}, {508, 8}, {513, 33}, {517, 34}, {530, 9}, {605, 35}, {618, 36}, {619, 10}, {625, 11}, + {702, 37}, {704, 12}, {711, 38}, {713, 39}, {815, 40}, {816, 41}, {822, 42}, {905, 43}, {917, 44}, + {922, 45}, {1006, 46}, {1007, 47}, {1031, 13}, {1101, 14}, {1104, 52}, {1111, 15}, {1113, 48}, {1119, 49}, + {1205, 17}, {1206, 18}, {1223, 50}, {1225, 19}, {1231, 51}, +}}; +// The dates G FUEL's daily also fell on. +constexpr std::array G_FUEL_DATES = {20230324, 20230414}; + +// What a special daily sets: the character, end stage, path, difficulty and Mega Satan (-1 keeps the drawn one), no +// shooting, and the treasure rooms (and shops) it leaves out. +struct SpecialDailyRules +{ + uint32_t id = 0; + int playerType = -1; + int endStage = -1; + int pathType = -1; + int difficulty = -1; + int isMegaSatan = -1; + bool isCantShoot = false; + bool isTreasureFiltered = false; + bool isShopFiltered = false; +}; +constexpr std::array SPECIAL_DAILY_RULES = {{ + {1, 8, 11, 0, 0, 0, true}, {3, 1, 8, -1, 0, 0}, {4, 0, 11, -1, 0, 1}, {5, 2, 11, -1, 0, 1}, + {6, 8, 10, 1, 0, 0, false, true}, {7, 14, 11, 1, 0, 1}, {8, 0, 8, -1, 0, 0, false, true}, + {9, 10, 11, 1, 0, 0, true}, {10, 2, 8, -1, 0, 0, false, true}, {11, 10, 6, -1, 0, 0}, {12, 6, 11, -1, 0, 1}, + {13, 5, 10, 0, 0, 0}, {14, 10, 11, 0, 1, 0}, {15, 10, 11, -1, 1, 1, false, true}, + {16, 1, 11, -1, 0, 1}, {17, 0, 10, 0, 0, 0}, {18, 0, 10, 1, 0, 0}, {19, 0, 11, -1, 0, 1}, + {20, 0, -1, -1, -1, -1, false, true}, {21, 15, -1, -1, -1, -1, false, true, true}, + {22, 4, -1, -1, -1, -1, false, true, true}, {23, 2, -1, -1, -1, -1, false, true}, {24, 1}, {25, 0}, + {26, 1, -1, -1, -1, -1, false, true}, {27, 0, -1, -1, -1, -1, false, true}, {28, 0}, {29, 13}, + {30, 8, -1, -1, -1, -1, false, true}, {31, 1, -1, -1, -1, -1, false, true}, {32, 0}, + {33, 1, -1, -1, -1, -1, false, true}, {34, 0}, {35, 4}, {36, 2}, {37, 16}, + {38, 4, -1, -1, -1, -1, false, true}, {39, 8, -1, -1, -1, -1, false, true}, + {40, 1, -1, -1, -1, -1, false, true}, {41, 14}, {42, 0}, {43, 1}, {44, 2}, {45, 1}, {46, 3}, {47, 0}, + {48, 0, -1, -1, -1, -1, false, true}, {49, 4, -1, -1, -1, -1, false, true}, {50, 3}, {51, 0}, + {SPECIAL_DAILY_G_FUEL, 0, 11, 1, 0, 0}, +}}; + +// A YYYYMMDD date as a calendar date, normalized as mktime would. +static std::chrono::sys_days date_days_get(uint32_t date) +{ + using namespace std::chrono; + year_month_day day = year{(int)(date / DATE_YEAR)} / month{date % DATE_YEAR / DATE_PART} / 1; + return sys_days{day} + days{date % DATE_PART - 1}; +} + +// A calendar date as YYYYMMDD. +static uint32_t date_make(std::chrono::sys_days days) +{ + std::chrono::year_month_day day{days}; + return (uint32_t)(int)day.year() * DATE_YEAR + (uint32_t)day.month() * DATE_PART + (uint32_t)day.day(); +} + +// Easter Sunday of a year by Gauss's computus, or the epoch past the years it covers (logged). +static uint32_t easter_get(int year) +{ + using namespace std::chrono; + if (year > EASTER_LAST_YEAR) + { + log_printf(LOG_WARN, "Cannot calculate Easter date for year %d", year); + return date_make(sys_days{}); + } + + int golden = year % 19; + int century = year / 100; + int yearInCentury = year % 100; + int epact = (19 * golden + century - century / 4 - (century - (century + 8) / 25 + 1) / 3 + 15) % 30; + int weekday = (32 + 2 * (century % 4) + 2 * (yearInCentury / 4) - epact - yearInCentury % 4) % 7; + int correction = (golden + 11 * epact + 22 * weekday) / 451; + int days = epact + weekday - 7 * correction + 114; + return date_make(sys_days{std::chrono::year{year} / (days / 31) / (days % 31 + 1)}); +} + +// 00427870 The special daily a YYYYMMDD date falls on: Thanksgiving (the fourth Thursday of November), Easter, +// G FUEL's, one of the year's fixed dates, or 0 for none. +uint32_t holiday_get_current(uint32_t date) +{ + using namespace std::chrono; + int year = (int)year_month_day{date_days_get(date)}.year(); + sys_days novemberFirst{std::chrono::year{year} / NOVEMBER / 1}; + sys_days thanksgiving = novemberFirst + (Thursday - weekday{novemberFirst}) + weeks{3}; + + if (date == date_make(thanksgiving)) return SPECIAL_DAILY_THANKSGIVING; + if (date == easter_get(year)) return SPECIAL_DAILY_EASTER; + if (std::ranges::find(G_FUEL_DATES, date) != G_FUEL_DATES.end()) return SPECIAL_DAILY_G_FUEL; + auto holiday = std::ranges::find(HOLIDAY_DATES, date % DATE_YEAR, &HolidayDate::monthDay); + return holiday == HOLIDAY_DATES.end() ? 0 : holiday->specialDailyId; +} + +// A character's tainted self, or the character itself (logged) for those without one. +static int tainted_id_get(int playerType) +{ + if (playerType >= PLAYER_ISAAC && playerType <= PLAYER_THELOST) return playerType + PLAYER_ISAAC_B; + switch (playerType) + { + case PLAYER_LILITH: return PLAYER_LILITH_B; + case PLAYER_KEEPER: return PLAYER_KEEPER_B; + case PLAYER_APOLLYON: return PLAYER_APOLLYON_B; + case PLAYER_THEFORGOTTEN: return PLAYER_THEFORGOTTEN_B; + case PLAYER_BETHANY: return PLAYER_BETHANY_B; + case PLAYER_JACOB: return PLAYER_JACOB_B; + } + log_printf(LOG_ERROR, "GetTaintedId() could not find tainted counterpart to given ePlayerType (%d) \n", + playerType); + return playerType; +} + +// The end stage and path a roll out of 100 picks: the Depths, the Womb, the Void on either path, Sheol or the +// Cathedral, or the Dark Room or the Chest past 89. +static void daily_stage_roll(ChallengeParam& params, RNG& rng, int roll) +{ + + if (roll < STAGE_ROLLS[0]) params.endStage = STAGE_DEPTHS_II; + else if (roll < STAGE_ROLLS[1]) params.endStage = STAGE_WOMB_II; + else if (roll < STAGE_ROLLS[2]) + { + params.endStage = STAGE_VOID; + params.pathType = rng.RandomInt(2) == 0 ? PATH_TYPE_CATHEDRAL : PATH_TYPE_SHEOL; + } + else if (roll < STAGE_ROLLS[4]) + { + params.endStage = STAGE_SHEOL; + params.pathType = roll < STAGE_ROLLS[3] ? PATH_TYPE_SHEOL : PATH_TYPE_CATHEDRAL; + } + else + { + params.endStage = STAGE_DARK_ROOM; + params.pathType = roll > CHEST_ROLL ? PATH_TYPE_CATHEDRAL : PATH_TYPE_SHEOL; + } +} + +// Saturday's end stage and path, a roll out of 100 in tenths (the first two halves of fifteen), none past 89. +static void saturday_stage_roll(ChallengeParam& params, RNG& rng, int roll) +{ + + if (roll < SATURDAY_ROLLS[0]) params.endStage = STAGE_DEPTHS_II; + else if (roll < SATURDAY_ROLLS[1]) params.endStage = STAGE_WOMB_II; + else if (roll < SATURDAY_ROLLS[2]) + { + params.endStage = STAGE_VOID; + params.pathType = rng.RandomInt(2) == 0 ? PATH_TYPE_CATHEDRAL : PATH_TYPE_SHEOL; + } + else if (roll < SATURDAY_ROLLS[6]) + { + int band = (roll - SATURDAY_ROLLS[2]) / (SATURDAY_ROLLS[3] - SATURDAY_ROLLS[2]); + params.endStage = band < 2 ? STAGE_SHEOL : STAGE_DARK_ROOM; + params.pathType = band % 2 ? PATH_TYPE_CATHEDRAL : PATH_TYPE_SHEOL; + } + else if (roll < SATURDAY_ROLLS[7]) + { + params.pathType = PATH_TYPE_HOME; + params.endStage = STAGE_HOME; + } +} + +// 00427290 Applies a special daily's rules over the drawn ones: G FUEL's also plays with its seed and G FUEL's effect. +static void special_daily_apply(DailyChallenge& daily) +{ + ChallengeParam& params = daily.params; + auto rules = std::ranges::find(SPECIAL_DAILY_RULES, daily.specialDailyId, &SpecialDailyRules::id); + if (rules == SPECIAL_DAILY_RULES.end()) return; + + auto apply = [](int& value, int rule) { value = rule >= 0 ? rule : value; }; + apply(params.playerType, rules->playerType); + apply(params.endStage, rules->endStage); + apply(params.difficulty, rules->difficulty); + if (rules->pathType >= 0) params.pathType = (PathType)rules->pathType; + if (rules->isMegaSatan >= 0) params.isMegaSatan = rules->isMegaSatan; + if (rules->isCantShoot) params.isCanShoot = false; + if (rules->isTreasureFiltered) params.roomset.insert(ROOM_TREASURE); + if (rules->isShopFiltered) params.roomset.insert(ROOM_SHOP); + if (daily.specialDailyId != SPECIAL_DAILY_G_FUEL) return; + + params.seedEffects = {SEED_G_FUEL}; + daily.seed = Seeds::String2Seed(G_FUEL_SEED); +} + +// 00426a50 Draws a date's daily from it (Groundhog Day repeats the day before): a character (tainted on some +// Tuesdays and Saturdays), an end stage and path, then the weekday's twist (Sunday's Mega Satan, maybe hard, Monday's +// Repentance path to the Womb, Wednesday's and Friday's (hard) rolls, Thursday's Home, Saturday's anything), the run's +// seed, and the special daily's rules over them. +// The original stops in the debugger on a zero seed. Here the seed just stays zero. +void DailyChallenge::Init(uint32_t dailyDate) +{ + seed = 0; + isPractice = false; + params.Reset(); + params.isPathTypeSet = true; + specialDailyId = holiday_get_current(dailyDate); + id = dailyDate; + + RNG rng = rng_make(specialDailyId == SPECIAL_DAILY_GROUNDHOG ? dailyDate - 1 : dailyDate, DAILY_SHIFT_INDEX); + do params.playerType = (int)(rng.Next() % DAILY_CHARACTER_RANGE); + while (std::ranges::find(DAILY_SKIPPED_CHARACTERS, params.playerType) != DAILY_SKIPPED_CHARACTERS.end()); + params.endStage = DAILY_END_STAGES[rng.Next() & 3]; + params.pathType = params.endStage < STAGE_SHEOL || (rng.Next() & 1) ? PATH_TYPE_CATHEDRAL : PATH_TYPE_SHEOL; + params.isMegaSatan = false; + params.difficulty = DIFFICULTY_NORMAL; + + switch (std::chrono::weekday{date_days_get(dailyDate)}.c_encoding()) + { + case WEEKDAY_SUNDAY: + params.endStage = STAGE_DARK_ROOM; + params.isMegaSatan = true; + if (rng.Next() % SUNDAY_HARD_ODDS == 0) params.difficulty = DIFFICULTY_HARD; + break; + case WEEKDAY_MONDAY: + params.pathType = PATH_TYPE_REPENTANCE; + params.endStage = STAGE_WOMB_II; + break; + case WEEKDAY_TUESDAY: + params.playerType = tainted_id_get(params.playerType); + daily_stage_roll(params, rng, (int)(rng.Next() % DAILY_ROLL_RANGE)); + break; + case WEEKDAY_WEDNESDAY: + params.endStage = STAGE_VOID; + params.pathType = rng.RandomInt(2) == 0 ? PATH_TYPE_CATHEDRAL : PATH_TYPE_SHEOL; + daily_stage_roll(params, rng, (int)rng.RandomInt(DAILY_ROLL_RANGE)); + break; + case WEEKDAY_THURSDAY: + params.pathType = PATH_TYPE_HOME; + params.endStage = STAGE_HOME; + break; + case WEEKDAY_FRIDAY: + params.difficulty = DIFFICULTY_HARD; + daily_stage_roll(params, rng, (int)rng.RandomInt(DAILY_ROLL_RANGE)); + break; + case WEEKDAY_SATURDAY: + saturday_stage_roll(params, rng, (int)rng.RandomInt(DAILY_ROLL_RANGE)); + if (rng.RandomInt(2) != 0) params.playerType = tainted_id_get(params.playerType); + if (rng.RandomInt(2) != 0) params.difficulty = DIFFICULTY_HARD; + break; + } + seed = rng.Next(); + special_daily_apply(*this); +} diff --git a/src/daily_challenge.h b/src/daily_challenge.h new file mode 100644 index 0000000..1e73e9a --- /dev/null +++ b/src/daily_challenge.h @@ -0,0 +1,23 @@ +#pragma once + +#include "challenge_params.h" +#include + +// A YYYYMMDD date's factors: the year's, then the month's and the day's part. +constexpr uint32_t DATE_YEAR = 10000; +constexpr uint32_t DATE_PART = 100; + +// A day's daily run (DailyChallenge): its date (0 when no daily is played), seed, the special daily the date falls on +// and the rules drawn for it, and whether it is only practiced. +struct DailyChallenge +{ + ChallengeParam params; + uint32_t id = 0; + uint32_t seed = 0; + uint32_t specialDailyId = 0; + bool isPractice = false; + + void Init(uint32_t dailyDate); +}; + +uint32_t holiday_get_current(uint32_t date); diff --git a/src/entity.cpp b/src/entity.cpp index 85286bf..f9bb9bd 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -313,10 +313,16 @@ Entity* Entity::GetStatusEffectTarget() return DoesEntityShareStatus() ? GetLastParent() : this; } -// 0067a720 -float Entity::GetRootParent() +// 0067a720 (misnamed GetRootParent) How many frames a Ludovico water tear's bob lasts: the max fire delay of the +// player its spawners lead back to, plus 8, or 18 for anything else. +float Entity::hydrobounce_period_get() { - reconstruction_missing("Entity::GetRootParent 0067a720"); + constexpr float PERIOD_BASE = 8; + constexpr float PERIOD_FIRE_DELAY = 10; + + Entity* root = GetLastSpawner(); + float fireDelay = root->type == ENTITY_PLAYER ? static_cast(root)->maxFireDelay : PERIOD_FIRE_DELAY; + return fireDelay + PERIOD_BASE; } // Follows a chain of links from start, stopping at the first entity found or where the chain loops. @@ -568,10 +574,33 @@ bool Entity::is_valid_boss_enemy() return is_enemy_type(type) && CanShutDoors() && type != ENTITY_DARK_ESAU && !IsFriendly(); } -// 006d8990 +// 006d8990 Whether a player may take control of it: a living enemy that is not a fireplace, shopkeeper, TNT, poop, +// prop, minecart or the blood cultist's spawn, nobody controls yet and that has no FLAG_NO_PLAYER_CONTROL. A body of +// segments counts only at its root: a Ring of Flies or Swarm fly's parent NPC, an Army Fly's last enemy parent, or the +// head of a body sharing its status. +// The original reads a versus player's controller as an NPC's. Here a player has none. bool Entity::is_valid_target() { - reconstruction_missing("Entity::is_valid_target 006d8990"); + bool isEnemy = is_enemy_type(type) && type != ENTITY_FIREPLACE && type != ENTITY_SHOPKEEPER && + type != ENTITY_MOVABLE_TNT && type != ENTITY_GENERIC_PROP && type != ENTITY_MINECART && + type != ENTITY_POOP && !(type == ENTITY_CULTIST && variant == CULTIST_BLOOD_SPAWN); + if (!isEnemy || isDead) return false; + + Entity* root = this; + auto* npc = static_cast(this); + if (type == ENTITY_RING_OF_FLIES || (type == ENTITY_SWARM && npc->ParentNPC())) root = npc->ParentNPC(); + else if (type == ENTITY_ARMYFLY) + { + Entity* ancestor = GetLastParent(); + if (is_enemy_type(ancestor->type)) root = ancestor; + } + else if (type != ENTITY_SWARM) + { + if (DoesEntityShareStatus()) root = GetLastParent(); + if (!is_enemy_type(root->type)) root = nullptr; + } + bool isControlled = type != ENTITY_PLAYER && npc->controllerID != -1; + return root == this && !isControlled && !HasEntityFlags(FLAG_NO_PLAYER_CONTROL); } // 006a8f80 Whether its config lists anything it can devolve into. @@ -696,6 +725,17 @@ void Entity::Init(int entityType, int entityVariant, int entitySubType, uint32_t data_release(); } +// An entity's health on the current floor: its base health, plus its stage health for each stage (to the tenth, a +// fifth less from the fifth) when it has any. +float stage_health_get(float baseHealth, float stageHealth) +{ + if (stageHealth <= STAGE_HP_MIN) return baseHealth; + + float stage = std::min((float)g_game->stage, STAGE_HP_CAP); + float scale = g_game->stage < STAGE_HP_REDUCED_FROM ? 1 : STAGE_HP_REDUCED_SCALE; + return stage * scale * stageHealth + baseHealth; +} + // 006a98b0 Takes its stats from its config (preloading its resources), or defaults with a log line without one. void Entity::LoadEntityConfig() { @@ -722,13 +762,7 @@ void Entity::LoadEntityConfig() shadowSize = config->shadowSize; collisionDamage = config->collisionDamage; mass = config->mass; - maxHitPoints = config->baseHP; - if (STAGE_HP_MIN < config->stageHP) - { - float stage = std::min((float)g_game->stage, STAGE_HP_CAP); - float scale = g_game->stage < STAGE_HP_REDUCED_FROM ? 1 : STAGE_HP_REDUCED_SCALE; - maxHitPoints = stage * scale * config->stageHP + config->baseHP; - } + maxHitPoints = stage_health_get(config->baseHP, config->stageHP); size = 0; sizeMulti = {}; @@ -1223,18 +1257,6 @@ void Entity::SetSpriteOverlayFrame(std::string_view animation, int frame) // The rest of Entity is not reconstructed yet. -// 0064bb70 -void Entity::convert_shot_for_enemy_owner(Entity*) -{ - reconstruction_missing("Entity::convert_shot_for_enemy_owner 0064bb70"); -} - -// 006b5e60 -void* Entity::GetData(void*) -{ - reconstruction_missing("Entity::GetData 006b5e60"); -} - // 006b5f10 void* Entity::GetDebugShape(bool) { @@ -1281,20 +1303,19 @@ void Entity::GetNullCapsule(Capsule& outCapsule, std::string_view nullLayerName) outCapsule = Capsule(vector_add(offset, pos), size, rotation, 1); } -// 007079c0 -void Entity::RemoveWithPoof(Entity*) +// 007079c0 Removes an entity in a pink poof, a boss's death counting for the room. Dogma stays. +void Entity::RemoveWithPoof(Entity* entity) { - reconstruction_missing("Entity::RemoveWithPoof 007079c0"); + constexpr ColorMod POOF_COLOR = {{1, 0.6f, 0.9f, 1}, {0, 0, 0, 0}, {0.2f, 0.15f, 0.18f}}; + + if (entity->type == ENTITY_DOGMA) return; + + Entity* poof = + g_game->Spawn({.position = entity->pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->SetColor(POOF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + poof->Update(); + bool isBossDeath = is_enemy_type(entity->type) && entity->IsBoss(); + if (isBossDeath) g_game->room->TriggerBossDeath(*static_cast(entity)); + entity->Remove(); } -// 0085e680 -int Entity::IsVulnerableEnemy_lua(lua_State*) -{ - reconstruction_missing("Entity::IsVulnerableEnemy_lua 0085e680"); -} - -// 008c5cf2 -void Entity::KillWithSource() -{ - reconstruction_missing("Entity::KillWithSource 008c5cf2"); -} diff --git a/src/entity.h b/src/entity.h index bdad525..4735bce 100644 --- a/src/entity.h +++ b/src/entity.h @@ -3,6 +3,7 @@ #include "anm2.h" #include "classes.h" #include "seeds.h" +#include #include #include #include @@ -281,6 +282,7 @@ enum EntityType : int ENTITY_POOFER = 892, ENTITY_BALL_AND_CHAIN = 893, ENTITY_REAP_CREEP = 900, + ENTITY_LIL_BLUB = 901, ENTITY_VISAGE = 903, ENTITY_SIREN = 904, ENTITY_HERETIC = 905, @@ -313,6 +315,8 @@ enum EntityType : int // The types an enemy can have, both ends included. constexpr int ENTITY_FIRST_ENEMY = 10; constexpr int ENTITY_LAST_ENEMY = 999; +// Two entities closer than this are not pushed apart. +constexpr float PUSH_MIN_DISTANCE = 0.0001f; // An entity's fall into a pit (pitfallState): falling, at the bottom, climbing back out, or gone through to another // room. @@ -328,6 +332,20 @@ enum PitfallState : int // A color offset step: one 255th. constexpr float COLOR_OFFSET_UNIT = 0.003921569f; +// Angelic Prism's four tints of the tears, bombs and knives it splits (Color's 255th offsets), and the turns and tints +// of the lasers it fans out. +constexpr std::array PRISM_COLORS = {{ + {{1, 1, 1, 1}, {0, 0, 0, 0}, {155 * COLOR_OFFSET_UNIT, -100 * COLOR_OFFSET_UNIT, -100 * COLOR_OFFSET_UNIT}}, + {{1, 1, 1, 1}, {0, 0, 0, 0}, {138 * COLOR_OFFSET_UNIT, 155 * COLOR_OFFSET_UNIT, -100 * COLOR_OFFSET_UNIT}}, + {{1, 1, 1, 1}, {0, 0, 0, 0}, {-100 * COLOR_OFFSET_UNIT, 155 * COLOR_OFFSET_UNIT, -67 * COLOR_OFFSET_UNIT}}, + {{1, 1, 1, 1}, {0, 0, 0, 0}, {-100 * COLOR_OFFSET_UNIT, 103 * COLOR_OFFSET_UNIT, 155 * COLOR_OFFSET_UNIT}}}}; +constexpr std::array PRISM_LASER_SPREAD = {-30, -10, 10, 30}; +constexpr std::array PRISM_LASER_COLORS = {{ + {{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}, + {{1, 2, 1, 1}, {0, 0, 0, 0}, {100 * COLOR_OFFSET_UNIT, 200 * COLOR_OFFSET_UNIT, 0}}, + {{1, 2, 1, 1}, {0, 0, 0, 0}, {-200 * COLOR_OFFSET_UNIT, 200 * COLOR_OFFSET_UNIT, 100 * COLOR_OFFSET_UNIT}}, + {{1, 1, 2, 1}, {0, 0, 0, 0}, {-200 * COLOR_OFFSET_UNIT, 100 * COLOR_OFFSET_UNIT, 200 * COLOR_OFFSET_UNIT}}}}; + // Gigante Bean's push of every enemy a doubled fart hits, away from the fart. constexpr float GIGANTE_KNOCKBACK_SPEED = 8; constexpr int GIGANTE_KNOCKBACK_FRAMES = 18; @@ -355,6 +373,7 @@ enum EntityFlag : uint64_t FLAG_NO_REMOVE_ON_TEX_RENDER = 1ull << 17, FLAG_NO_DEATH_TRIGGER = 1ull << 18, FLAG_NO_SPIKE_DAMAGE = 1ull << 19, + FLAG_ITEM_SHOULD_DUPLICATE = 1ull << 19, FLAG_BOSSDEATH_TRIGGERED = 1ull << 20, FLAG_DONT_OVERWRITE = 1ull << 21, FLAG_SPAWN_STICKY_SPIDERS = 1ull << 22, @@ -822,7 +841,7 @@ struct Entity Entity* GetLastSpawner(); Entity* GetPlayerAncestor(); Entity* GetStatusEffectTarget(); - float GetRootParent(); + float hydrobounce_period_get(); bool IsDescendantOf(Entity* ancestor); bool HasCommonParentWithEntity(Entity* other); bool is_same_segmented_body(Entity* other); @@ -877,22 +896,18 @@ struct Entity Entity_Effect* MakeBloodPoof(const Vector& position, const ColorMod& poofColor, float scale); Entity_Effect* MakeBloodPoofAtPos(const ColorMod& poofColor, float scale); Entity_NPC* GiveMinecart(const Vector& position, const Vector& cartVelocity); - void convert_shot_for_enemy_owner(Entity* shot); WaterClipInfo GetWaterClipInfo(); void water_ripples_update(); void* GetDebugShape(bool isUnknown); - void* GetData(void* outRef); Vector GetNullOffset(std::string_view nullLayerName); void GetNullCapsule(Capsule& outCapsule, std::string_view nullLayerName); void SetSpriteFrame(std::string_view animation, int frame); void SetSpriteOverlayFrame(std::string_view animation, int frame); - void KillWithSource(); static void ReleaseLuaRef(Entity* entity); static void RemoveWithPoof(Entity* entity); static void DestroyRockGridAt(const Vector& position, GridEntityDesc* desc, Entity* source, int backdropType); - static int IsVulnerableEnemy_lua(lua_State* state); private: void data_release(); @@ -906,6 +921,10 @@ private: void magnet_pull_update(); }; +// The blood cultist's spawn (885.10), which nothing targets. +constexpr int CULTIST_BLOOD_SPAWN = 10; + void hit_list_insert(std::vector& hitList, Entity& entity); +float stage_health_get(float baseHealth, float stageHealth); Vector render_position_get(const Vector& world, RenderSnap snap); int render_z_get(float depth); diff --git a/src/entity_bomb.cpp b/src/entity_bomb.cpp index fd5f316..8db92bf 100644 --- a/src/entity_bomb.cpp +++ b/src/entity_bomb.cpp @@ -104,7 +104,6 @@ constexpr int VISAGE_MASK_VARIANT = 10; 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; // 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; diff --git a/src/entity_collision.cpp b/src/entity_collision.cpp index 493e116..b0c20ca 100644 --- a/src/entity_collision.cpp +++ b/src/entity_collision.cpp @@ -77,7 +77,6 @@ constexpr int NULL_TOOTH_AND_NAIL = 59; constexpr std::array SHOT_ANCHORED_TYPES = {23, 25, 41, 55, 62, 91, 254, 283, 245, 292}; // Two entities closer than this are not pushed apart. A player or the Punching Bag is not pushed into a wall. -constexpr float PUSH_MIN_DISTANCE = 0.0001f; constexpr float PLAYER_PUSH_SHARE = 0.5f; constexpr float BEAST_PUSH_DAMPING = 0.25f; diff --git a/src/entity_combat.cpp b/src/entity_combat.cpp index 0febfc9..5ce8907 100644 --- a/src/entity_combat.cpp +++ b/src/entity_combat.cpp @@ -67,7 +67,6 @@ constexpr std::array STATIC_OBSTACLE_TYPES = {292, 245, 302, 42, 201, 20 constexpr int STATIC_OBSTACLE_EXTRA = 202; // The items, trinkets and player kinds the combat code reads (Lua's ids). -constexpr int COLLECTIBLE_MOMS_HEELS = 30; constexpr int COLLECTIBLE_ARIES = 300; constexpr int NULLITEM_TOOTH_AND_NAIL = 59; constexpr int PLAYER_FORM_COUNT_NEEDED = 3; @@ -115,7 +114,6 @@ constexpr uint32_t TEAR_BOUNCE_PIERCE_MASK = 3; constexpr int INFAMY_CHANCE = 2; constexpr int INFAMY_CHANCE_VERSUS = 4; constexpr int INFAMY_FLASH_FRAMES = 15; -constexpr int COLOR_PRIORITY_TOP = 255; constexpr float MULLIGAN_FLY_CHANCE = 0.166f; constexpr float GUPPY_FLY_CHANCE = 0.66f; constexpr float LASTING_BEAM_FLY_SCALE = 0.1f; @@ -123,6 +121,17 @@ constexpr float LASTING_BEAM_FLY_SCALE = 0.1f; // Entity_Player::HandleCollision: the contact damage the items deal. constexpr int CONTACT_COUNTDOWN = 15; constexpr int SUPLEX_STATE_PASSING = 3; +// Mega Mush's stomp (weaker in versus) and the suplex grab: the fireplace it snuffs, its aim's time and its scamper's +// pitch. Breath of Life's burst: its damage, more per floor deep, and its size. +constexpr float MEGA_MUSH_STOMP = 80; +constexpr float MEGA_MUSH_STOMP_VERSUS = 10; +constexpr float SUPLEX_FIREPLACE_DAMAGE = 1000; +constexpr int SUPLEX_GRAB_AIM_FRAMES = 60; +constexpr float SUPLEX_GRAB_PITCH_MIN = 0.9f; +constexpr float SUPLEX_GRAB_PITCH_RANGE = 0.2f; +constexpr float BREATH_BURST_DAMAGE = 15; +constexpr float BREATH_BURST_DAMAGE_PER_STAGE = 2.1f; +constexpr float BREATH_BURST_SIZE = 80; constexpr float HEELS_DAMAGE = 12; constexpr float HEELS_DAMAGE_VERSUS = 2; constexpr float VIRUS_DAMAGE = 12; @@ -171,8 +180,6 @@ constexpr float GIB_SPEED_MIN = 2; constexpr float GIB_SPEED_RANGE = 4; constexpr float GIB_LIFT = 0.5f; constexpr float GIB_WORM_HEIGHT = -40; -constexpr float DUST_SPEED = 5; -constexpr float DUST_RADIUS = 20; constexpr float DUST_ALPHA_MIN = 0.2f; constexpr float DUST_ALPHA_RANGE = 0.5f; constexpr float DROP_SPEED = 10; @@ -421,7 +428,7 @@ static void burst_drops_spawn(Entity& entity, int gibsAmount) drop->rotation = (random_unit() * DROP_SPIN_RANGE + DROP_SPIN_MIN) * side; float alpha = (random_unit() * DROP_ALPHA_RANGE + DROP_ALPHA_MIN) * blood._alpha; drop->SetColor({{blood._red, blood._green, blood._blue, alpha}, {0, 0, 0, 0}, {0, 0, 0}}, -1, - COLOR_PRIORITY_TOP, false, true); + COLOR_PRIORITY_DEFAULT, false, true); if (!isHuge) drop->SetTimeout((int)(Random() % GIB_TIMEOUT_RANGE) + GIB_TIMEOUT_MIN); else { @@ -484,7 +491,7 @@ void Entity::BloodExplode() if (type == ENTITY_BOMB || type == ENTITY_PICKUP || HasEntityFlags(FLAG_NO_BLOOD_SPLASH)) return; Entity_Effect* splat = effect_spawn(EFFECT_BLOOD_SPLAT, 0, pos, {}, nullptr, Random()); - splat->SetColor(splatColor, -1, COLOR_PRIORITY_TOP, false, true); + splat->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); if (g_game->seedEffects.HasSeedEffect(SEED_EXTRA_BLOOD)) splat->sprite.scale = vector_make(EXTRA_BLOOD_SPLAT_SCALE, EXTRA_BLOOD_SPLAT_SCALE); splat->Update(); @@ -530,7 +537,7 @@ static void gib_dust_spawn(const GibSpawn& gibs, int half) dust->rotation = (random_unit() * DROP_SPIN_RANGE + DROP_SPIN_MIN) * spin_side(*dust, gibs.position, velocity); dust->SetTimeout((int)(Random() % GIB_TIMEOUT_RANGE) + GIB_TIMEOUT_MIN); float alpha = random_unit() * DUST_ALPHA_RANGE + DUST_ALPHA_MIN; - dust->SetColor({{1, 1, 1, alpha}, {0, 0, 0, 0}, {0, 0, 0}}, -1, COLOR_PRIORITY_TOP, false, true); + dust->SetColor({{1, 1, 1, alpha}, {0, 0, 0, 0}, {0, 0, 0}}, -1, COLOR_PRIORITY_DEFAULT, false, true); dust->Update(); } } @@ -570,14 +577,14 @@ static Entity_Effect* gib_blood_spawn(const GibSpawn& gibs, int kind, uint32_t s Entity_Effect* gib = gib_fling(gibs, EFFECT_BLOOD_PARTICLE, kind, seed, speed); if (!gibs.spawner || !gibs.spawner->HasEntityFlags(FLAG_POISON)) { - gib->SetColor(gibs.color, -1, COLOR_PRIORITY_TOP, false, true); + gib->SetColor(gibs.color, -1, COLOR_PRIORITY_DEFAULT, false, true); gib->splatColor = gibs.color; } else { ColorMod tinted = gibs.color; color_multiply(tinted, POISON_GIB_TINT); - gib->SetColor(kind == 0 ? tinted : gibs.color, -1, COLOR_PRIORITY_TOP, false, true); + gib->SetColor(kind == 0 ? tinted : gibs.color, -1, COLOR_PRIORITY_DEFAULT, false, true); gib->splatColor = tinted; } if (kind == GIB_KIND_BONE) gib->AddEntityFlags(FLAG_NO_BLOOD_SPLASH); @@ -618,7 +625,7 @@ static Entity_Effect* gib_spawn(const GibSpawn& gibs, int kind) if (kind == GIB_KIND_ROCK_SMALL) { Entity_Effect* tooth = gib_scatter(gibs, EFFECT_TOOTH_PARTICLE, draw); - tooth->SetColor(TOOTH_COLOR, -1, COLOR_PRIORITY_TOP, false, true); + tooth->SetColor(TOOTH_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); return tooth; } if (kind == GIB_KIND_CHAIN) return gib_scatter(gibs, EFFECT_CHAIN_GIB, draw); @@ -733,7 +740,7 @@ static TearContact tear_player_contact(Entity_Tear& tear, Entity_Player& player) int infamyChance = g_game->deathmatchManager.is_active() ? INFAMY_CHANCE_VERSUS : INFAMY_CHANCE; if (!player.HasCollectible(COLLECTIBLE_INFAMY) || random_below(infamyChance) != 0) return TEAR_CONTACT_HIT; - player.SetColor(INFAMY_COLOR, INFAMY_FLASH_FRAMES, COLOR_PRIORITY_TOP, true, true); + player.SetColor(INFAMY_COLOR, INFAMY_FLASH_FRAMES, COLOR_PRIORITY_DEFAULT, true, true); tear.Kill(EntityRef(&player)); return TEAR_CONTACT_PASS; } @@ -994,10 +1001,10 @@ bool Entity_Tear::HandleCollision(Entity* collider, bool isLow) tear_hit_push(*this, *collider, owner); } ApplyTearFlagEffects(collider, pos, tearFlags, this, collisionDamage); - if (variant == TEAR_ERASER && collider->IsVulnerableEnemy(nullptr) && (!collider->IsBoss() || collider->HasMortalDamage())) - reconstruction_missing("Entity_Tear::HandleCollision 00673660: the Eraser erasing an enemy"); + bool isErasable = collider->IsVulnerableEnemy(nullptr) && (!collider->IsBoss() || collider->HasMortalDamage()); + if (variant == TEAR_ERASER && isErasable && enemy_erase(*collider)) npc_sound_play(SOUND_ERASER_HIT, 1, 2, 1); if (tearFlags[TEAR_TELEPORT] && collider->IsVulnerableEnemy(nullptr) && !collider->IsBoss()) - reconstruction_missing("Entity_Tear::HandleCollision 00673660: a teleporting tear's reroll"); + tear_hit_teleport(*collider); if (isExplosive) { @@ -1124,9 +1131,44 @@ static float player_contact_damage(Entity_Player& player, Entity& collider, bool return damage; } -// Part of 0078e1f0: the player's ways of touching: shoving an iced enemy, Tainted Magdalene's hug, and those not -// written yet: Mega Mush's stomp, Tainted Soul grabbing her body and the suplex grab. -static void player_contact_missing_check(Entity_Player& player, Entity& collider) +// Part of 0078e1f0: Mega Mush's stomp crushes what the giant touches once each: an enemy (unless friendly), a slot or a +// pickup, the last two blown up as well. +static void mega_mush_stomp(Entity_Player& player, Entity& collider) +{ + bool isEnemy = collider.IsEnemy() && !collider.HasEntityFlags(FLAG_FRIENDLY); + if (!isEnemy && !collider.is_slot() && !collider.is_pickup()) return; + if (EntityList::HitListContains(player.contactHitList, collider)) return; + + hit_list_insert(player.contactHitList, collider); + float damage = isEnemy && g_game->deathmatchManager.is_active() ? MEGA_MUSH_STOMP_VERSUS : MEGA_MUSH_STOMP; + uint64_t flags = isEnemy ? DAMAGE_CRUSH : DAMAGE_CRUSH | DAMAGE_EXPLOSION; + collider.TakeDamage(damage, flags, EntityRef(&player), HIT_COUNTDOWN); +} + +// Part of 0078e1f0: Suplex!'s dash grabs what it runs into: shots pass, a fireplace is snuffed out, and an enemy or a +// bomb is lifted for the aim. Whether the collision is ignored for good. +static bool suplex_grab(Entity_Player& player, Entity& collider) +{ + if (collider.type == ENTITY_PROJECTILE) return true; + if (!collider.IsEnemy() && !collider.is_bomb()) return false; + if (collider.type == ENTITY_FIREPLACE) + { + collider.TakeDamage(SUPLEX_FIREPLACE_DAMAGE, 0, EntityRef(&player), HIT_COUNTDOWN); + return false; + } + if (!player.TryHoldEntity(&collider)) return false; + + player.itemState = COLLECTIBLE_SUPLEX; + player.suplexAimCountdown = SUPLEX_GRAB_AIM_FRAMES; + player.suplexState = SUPLEX_AIMING; + npc_sound_play(SOUND_SUPLEX_GRAB, 1, 2, 1); + npc_sound_play(SOUND_SCAMPER, 1, 2, random_unit() * SUPLEX_GRAB_PITCH_RANGE + SUPLEX_GRAB_PITCH_MIN); + return true; +} + +// Part of 0078e1f0: the player's ways of touching before it hurts anything: shoving an iced enemy, Tainted Magdalene's +// hug and Mega Mush's stomp. +static void player_contact_touch(Entity_Player& player, Entity& collider) { bool isEnemyLike = Entity::is_enemy_type(collider.type) || (g_game->deathmatchManager.is_active() && collider.type == ENTITY_PLAYER); @@ -1139,9 +1181,7 @@ static void player_contact_missing_check(Entity_Player& player, Entity& collider collider.AddKnockback(EntityRef(&player), vector_scale(push, ICE_SHOVE_SPEED), ICE_SHOVE_FRAMES, true); } tainted_magdalene_hug(player, collider); - if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) - reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Mega Mush's stomp"); - if (player.suplexState == 1) reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: the suplex grab"); + if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) mega_mush_stomp(player, collider); } // Part of 0078e1f0: The Virus and Serpent's Kiss poison an enemy touched for 60 frames at 2 plus a twentieth of the @@ -1163,6 +1203,25 @@ static void virus_poison_apply(Entity_Player& player, Entity& collider) false); } +// Part of 0078e1f0: Breath of Life's holy burst where the player's edge meets the enemy it hurt, stronger deeper down +// (none while the player keeps Judas' Book of Belial), and a short spell unhurt. +static void breath_of_life_burst(Entity_Player& player, Entity& collider) +{ + float damage = (float)g_game->stage_depth_get() * BREATH_BURST_DAMAGE_PER_STAGE + BREATH_BURST_DAMAGE; + Vector edge = vector_add(player.pos, vector_resized(vector_sub(collider.pos, player.pos), player.size)); + if (!player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) + { + Entity* burst = g_game->Spawn({.position = edge, .spawner = &player, .type = ENTITY_EFFECT, + .variant = EFFECT_CRACK_THE_SKY, .seed = Random()}); + burst->parent = &player; + burst->SetCollisionDamage(damage); + burst->SetSize(BREATH_BURST_SIZE, vector_make(-1, -1), -1); + burst->subtype = 1; + } + if (player.damageCooldown < 1) player.AddEntityFlags(FLAG_NO_DAMAGE_BLINK); + player.damageCooldown = std::max(player.damageCooldown, CONTACT_COUNTDOWN); +} + // 0078e1f0 Touches another entity, after a mod's MC_PRE_PLAYER_COLLISION: mid-suplex it passes enemies and shots, // it hurts a vulnerable enemy by its items' contact damage, poisons with The Virus or Serpent's Kiss, and a thrown // Tainted Forgotten slows on enemies. Tainted Forgotten's soul picks the body up. Whether the collision is ignored, which a pony's dash makes it. @@ -1172,7 +1231,7 @@ bool Entity_Player::HandleCollision(Entity* collider, bool isLow) if (lua == LUA_RESULT_TRUE) return true; if (lua == LUA_RESULT_FALSE) return false; - player_contact_missing_check(*this, *collider); + player_contact_touch(*this, *collider); if (playerType == PLAYER_THESOUL_B && collider->type == ENTITY_PLAYER && static_cast(collider)->playerType == PLAYER_THEFORGOTTEN_B) { @@ -1182,6 +1241,7 @@ bool Entity_Player::HandleCollision(Entity* collider, bool isLow) return true; TryHoldEntity(collider); } + if (suplexState == SUPLEX_DASHING && suplex_grab(*this, *collider)) return true; if (suplexState >= SUPLEX_STATE_PASSING && (collider->IsEnemy() || collider->type == ENTITY_PROJECTILE)) return true; bool isIgnored = false; @@ -1191,7 +1251,7 @@ bool Entity_Player::HandleCollision(Entity* collider, bool isLow) bool isBreath = false; float damage = player_contact_damage(*this, *collider, isBreath); if (damage > 0 && collider->TakeDamage(damage, DAMAGE_COUNTDOWN, EntityRef(this), CONTACT_COUNTDOWN) && isBreath) - reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Breath of Life's burst"); + breath_of_life_burst(*this, *collider); } bool isPoisoning = HasCollectible(COLLECTIBLE_VIRUS) || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_VIRUS) || HasCollectible(COLLECTIBLE_SERPENTS_KISS); @@ -1202,6 +1262,11 @@ bool Entity_Player::HandleCollision(Entity* collider, bool isLow) !collider->IsFriendly()) velocity = vector_scale(velocity, SLOW_ON_CONTACT); if (collider->IsEnemy() && !collider->HasEntityFlags(FLAG_CHARM) && temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MARS)) - reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Mars' dash impact"); + { + temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_MARS, -1); + velocity = vector_scale(vector_normalized(vector_sub(pos, collider->pos)), vector_length(velocity)); + marsDashDirection = -1; + dash_impact(); + } return isIgnored; } diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index 884ef3d..4358f4e 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -67,7 +67,6 @@ constexpr float PAUSE_VELOCITY_DECAY = 0.6f; // The variants the behaviour tables can index. Past the last vanilla one (the gun) Init and Update run only their // shared parts, as the original's switches do for a mod's variants. constexpr int EFFECT_VARIANT_LIMIT = 256; -constexpr int EFFECT_VANILLA_LAST = EFFECT_GUN; template static bool is_listed(const std::array& list, int value) @@ -298,7 +297,6 @@ void Entity_Effect::Init(int entityType, int entityVariant, int entitySubType, u if (behaviour->init) behaviour->init(*this); } else if (is_combat_effect(variant)) combat_effect_init(*this); - else if (variant <= EFFECT_VANILLA_LAST) reconstruction_missing("Entity_Effect::Init 005cdb20: this effect variant"); if (!isExists) return; sprite.LoadGraphics(); @@ -355,13 +353,12 @@ void Entity_Effect::Update() if (behaviour->update) end = behaviour->update(*this); } else if (is_combat_effect(variant)) end = combat_effect_update(*this); - else if (variant <= EFFECT_VANILLA_LAST) reconstruction_missing("Entity_Effect::Update 005d4380: this effect variant"); if (end == EFFECT_UPDATE_RETURN) return; if (timeout > 0 && --timeout < 1) isDead = true; pausePosition = pos; if (spawnerType == ENTITY_FAMILIAR && spawnerVariant == FAMILIAR_CREEP_WAVE && is_listed(WAVE_CHAIN_CREEPS, variant)) - update_wave_chain(); + wave_chain_update(*this); lua_engine_get().PostEffectUpdate(this); } @@ -440,12 +437,6 @@ void Entity_Effect::FollowParent(Entity* newParent) parentOffset = vector_make(pos.x - newParent->pos.x, pos.y - newParent->pos.y); } -// Lil Spewer's creep wave, written as wave_chain_update in familiar_babies.cpp. -void Entity_Effect::update_wave_chain() -{ - wave_chain_update(*this); -} - // 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) diff --git a/src/entity_effect.h b/src/entity_effect.h index 7f3a068..fa63883 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -50,10 +50,16 @@ constexpr int PULLING_PURPLE = 0; constexpr int PULLING_GREY = 1; constexpr int PULLING_RED = 2; -// A blood explosion's subtypes the shots and bosses splash with: a burst, a splash and a big splash. +// A blood explosion's subtypes the shots and bosses splash with: a burst, a splash, a big splash and a flame. constexpr int BLOOD_EXPLOSION_BURST = 2; constexpr int BLOOD_EXPLOSION_SPLASH = 3; constexpr int BLOOD_EXPLOSION_SPLASH_BIG = 4; +constexpr int BLOOD_EXPLOSION_FLAME = 5; + +// The dust clouds thrown up by doors, debris and falls: their speed, spread and least spin. +constexpr float DUST_SPEED = 5; +constexpr float DUST_RADIUS = 20; +constexpr float DUST_SPIN_MIN = 2; // Dogma's blackhole (171): its sparks (subtype 1) and swirls (2), and its states while open and closing. constexpr int BLACKHOLE_SPARK = 1; @@ -305,6 +311,7 @@ struct Entity_Effect : Entity std::shared_ptr extraData; std::array varData{}; std::vector hitList; + GridEntityDesc gridDesc{}; Vector parentOffset{}; float baseDamage = 0; float baseScale = 0; @@ -339,7 +346,6 @@ struct Entity_Effect : Entity void FollowParent(Entity* parent); static bool rift_attract_filter(int first, int second); void update_mr_me(); - void update_wave_chain(); 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); diff --git a/src/entity_effect_mother.cpp b/src/entity_effect_mother.cpp index f191348..45dd9a6 100644 --- a/src/entity_effect_mother.cpp +++ b/src/entity_effect_mother.cpp @@ -200,7 +200,6 @@ static void generic_tracer_render(Entity_Effect& tracer, const Vector& offset) // spawner's colour at its share, which lingers its state's frames after it. An eruption throws up a lava ball from // the lava's line at 20 a frame, with a blast and a shake. constexpr int LAVA_PATH_LEVEL = 900; -constexpr float LAVA_LINE_ABOVE = 30; constexpr float LAVA_BALL_SPEED = -20; constexpr float LAVA_BALL_ACCEL = 0.5f; constexpr int LAVA_SHAKE = 6; @@ -224,7 +223,7 @@ static void lava_spawner_init(Entity_Effect& lava) // An eruption at the spawner's column: a lava ball thrown up from the lava's line, a blast and a shake. static void lava_erupt(Entity_Effect& lava) { - Vector line = vector_make(lava.pos.x, g_game->room->bottomRightPos.y - LAVA_LINE_ABOVE); + Vector line = vector_make(lava.pos.x, g_game->room->get_lava_line_y()); effect_sound_play(SOUND_BEAST_LAVABALL_RISE); uint32_t seed = Random(); auto* ball = static_cast(g_game->Spawn({.position = line, diff --git a/src/entity_effect_portal.cpp b/src/entity_effect_portal.cpp index a0707e7..f14188b 100644 --- a/src/entity_effect_portal.cpp +++ b/src/entity_effect_portal.cpp @@ -30,8 +30,6 @@ constexpr int PORTAL_SWIRL_LAYERS = 3; constexpr float PORTAL_SWIRL_SPAN = 30; constexpr float PORTAL_SWIRL_MAX = 1.5f; -// A portal's room: its kind by subtype (PORTAL_ROOM_TYPES, else a normal room), or one room past 1000. -constexpr int PORTAL_ROOM_INDEX_BASE = 1000; constexpr int PORTAL_GIVEN_ROOM = 900; // The colours of the portals to a room of a kind, and of the orange womb hole and its wisp. diff --git a/src/entity_factory.cpp b/src/entity_factory.cpp index 101985a..becc7a7 100644 --- a/src/entity_factory.cpp +++ b/src/entity_factory.cpp @@ -112,7 +112,6 @@ enum EntryAchievement : int ACHIEVEMENT_SHOPKEEPER_SECRET = 243, ACHIEVEMENT_SHOPKEEPER_SPECIAL = 247, ACHIEVEMENT_DARK_ROOM_END = 320, - ACHIEVEMENT_SUPER_TINTED_ROCK = 323, ACHIEVEMENT_HEART_SCARED = 328, ACHIEVEMENT_KEY_CHARGED = 333, ACHIEVEMENT_ENEMY_VARIANTS = 348, @@ -155,7 +154,6 @@ constexpr float ELLIPSE_MINES_SPREAD_Y = 0.5f; constexpr int ROCK_ROLLS = 1001; constexpr int ROCK_BOMB_ROLLS = 10; constexpr int ROCK_ALT_ROLLS = 16; -constexpr int SUPER_TINTED_ODDS = 20; constexpr int ELLIPSE_ODDS = 10; constexpr int CORN_ODDS = 40; constexpr int FIREPLACE_RED_ODDS = 40; @@ -543,10 +541,10 @@ static void trapdoor_transform(Room& room, RoomEntry& entry, int stage, RNG& rng if (game.currentRoomIdx == ROOM_GENESIS_IDX && !game.IsNextStageAvailable()) stairs(); return; } - bool isBackwards = game.gameStateFlags & 1ull << LEVEL_GAME_STATE_BACKWARDS_PATH; + bool isBackwards = game.gameStateFlags & 1ull << GAME_STATE_BACKWARDS_PATH; if (game.stage >= 1 && game.stage <= STAGE_BACKWARDS_LAST && isBackwards) return heaven(); - bool isInChallenge = game.challenge != 0 || game.dailyChallenge._id != 0; + bool isInChallenge = game.challenge != 0 || game.dailyChallenge.id != 0; bool isCathedralAllowed = !isInChallenge || game.GetChallengeParams().pathType == PATH_TYPE_CATHEDRAL; bool isCathedralForced = isInChallenge && game.GetChallengeParams().pathType == PATH_TYPE_CATHEDRAL; if (stage == STAGE_DARK_ROOM && room.roomType == ROOM_ERROR) @@ -603,7 +601,7 @@ static bool enemy_variant_transform(Room& room, RoomEntry& entry, int stage, int switch (entry.type) { case ENTITY_STONEY: - if (game.dailyChallenge._specialDailyId == SPECIAL_DAILY_GOLDEN_FATTY || + if (game.dailyChallenge.specialDailyId == SPECIAL_DAILY_GOLDEN_FATTY || game.challenge == CHALLENGE_GOLDEN_FATTY) return roll(true, 5, 1, 10); return false; diff --git a/src/entity_familiar.cpp b/src/entity_familiar.cpp index e7aa646..1a15cb6 100644 --- a/src/entity_familiar.cpp +++ b/src/entity_familiar.cpp @@ -1,6 +1,7 @@ #include "entity_familiar.h" #include "active_items.h" #include "boss_ai.h" +#include "color_stack.h" #include "entity_effect.h" #include "entity_list.h" #include "entity_player.h" @@ -68,6 +69,11 @@ constexpr float BLUE_BABY_SOUL_DRAG = 0.8f; constexpr int DRY_BABY_GIANTBOOK = 1; constexpr int MONGO_MIMIC_DEMON_BABY = 1; +// Tainted Lazarus's hologram draws its familiars faint, their alpha drawn from a generator of their own. +constexpr RNG HOLOGRAM_FLICKER = {0x194fc4ad, 4, 3, 27}; +constexpr float HOLOGRAM_FLICKER_SPREAD = 0.15f; +constexpr float HOLOGRAM_FLICKER_MIN = 0.05f; + // The followers that shoot, and the orbitals that only circle. constexpr int SHOOTER_VARIANTS[] = {1, 4, 5, 6, 7, 9, 10, 11, 12, 54, 81, 92, 97, 209, 220}; constexpr int ORBITAL_VARIANTS[] = {30, 31, 32, 33, 35, 44, 60, 65, 69, 84, 117, 121, 126}; @@ -735,7 +741,7 @@ static void abel_update(Entity_Familiar& abel) abel.Shoot(); } -// The behaviours of 0061da10 by variant. The familiars not reconstructed yet stop the game. +// The behaviours of 0061da10 by variant. A variant the game does not know (a mod's) does nothing here. void Entity_Familiar::variant_update() { if (familiar_listed(SHOOTER_VARIANTS, variant)) @@ -956,12 +962,15 @@ void Entity_Familiar::variant_update() 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 BUDDY_IN_A_BOX: return buddy_in_a_box_update(*this); + case BABY_PLUM: return baby_plum_update(*this); + case MULTIDIMENSIONAL_BABY: return multidimensional_baby_update(*this); + case ANGELIC_PRISM: return angelic_prism_update(*this); case BUMBO: return bumbo_update(*this); case DAMOCLES: return ai_shadow_intruder_damocles(false); case VANISHING_TWIN: return vanishing_twin_update(*this); case FRUITY_PLUM: return fruity_plum_update(*this); - default: reconstruction_missing("Entity_Familiar::Update 0061da10 (this familiar's behaviour)"); } } @@ -1051,7 +1060,7 @@ void Entity_Familiar::Interpolate() // 00624e10 Draws a familiar with its charge bar. Isaac's body draws its parts, a detached head its player's head, Gello // its cord first, Samson's Chains and Gemini hang their links, a locust its shot sprites and an item wisp its item's -// icon. Tainted Lazarus's hologram stops the game. +// icon. Tainted Lazarus's hologram draws them all faint and flickering. void Entity_Familiar::Render(const Vector& offset) { if (IsLilithBirthrightIncubus()) @@ -1059,8 +1068,14 @@ void Entity_Familiar::Render(const Vector& offset) Entity* whip = get_incubus_umbilical_whip(); if (!whip || !whip->isVisible) return; } - if (player && player->IsHologram()) - return reconstruction_missing("Entity_Familiar::Render 00624e10 (Tainted Lazarus's hologram)"); + bool isHologram = player && player->IsHologram(); + if (isHologram) + { + static RNG flicker = HOLOGRAM_FLICKER; + color_stack_push({{1, 1, 1, flicker.RandomFloat() * HOLOGRAM_FLICKER_SPREAD + HOLOGRAM_FLICKER_MIN}, + {0, 0, 0, 0}, + {0, 0, 0}}); + } if (variant == SAMSONS_CHAINS) samsons_chains_links_place(*this); else if (variant == GEMINI) gemini_cord_place(*this); @@ -1073,6 +1088,7 @@ void Entity_Familiar::Render(const Vector& offset) if (variant == ITEM_WISP) item_wisp_icon_render(*this); lua_engine_get().PostFamiliarRender(this, offset); render_charge_indicator(renderPosition); + if (isHologram) color_stack_pop(); sprite.color = saved; } diff --git a/src/entity_familiar.h b/src/entity_familiar.h index 555db1a..68f5981 100644 --- a/src/entity_familiar.h +++ b/src/entity_familiar.h @@ -561,6 +561,7 @@ void familiar_sound_play(int sound, SoundPlay play = {}); bool familiar_unicorn_active(Entity_Player& owner); Entity* spawn_dip_at(int subType, const Vector* position, Entity* spawner, const Vector* targetPosition); float angle_wrap(float angle); +float orbit_layer_angle_offset(int layer); Vector direction_unit(int direction); // Isaac's body and the player's detached head (Guillotine, Scissors, Decap Attack) (familiar_body.cpp). @@ -580,6 +581,10 @@ 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); +void buddy_in_a_box_update(Entity_Familiar& buddy); +void baby_plum_update(Entity_Familiar& plum); +void multidimensional_baby_update(Entity_Familiar& baby); +void angelic_prism_update(Entity_Familiar& prism); // The variant behaviours of Update written as their own functions (familiar_update.cpp). void brown_nugget_update(Entity_Familiar& fly); diff --git a/src/entity_knife.cpp b/src/entity_knife.cpp index 3b90da4..80449d0 100644 --- a/src/entity_knife.cpp +++ b/src/entity_knife.cpp @@ -165,12 +165,6 @@ constexpr std::array AXE_GLOW_PHASES = {0.5f, 0.25f, 0}; constexpr std::array AXE_GLOW_STRENGTHS = {0.17f, 0.1f, 0.25f}; // Angelic Prism's four colored knives, split 20 degrees apart around a 30 degree turn. -constexpr std::array PRISM_COLORS = {{ - {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.607843f, -0.392157f, -0.392157f}}, - {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.541176f, 0.607843f, -0.392157f}}, - {{1, 1, 1, 1}, {0, 0, 0, 0}, {-0.392157f, 0.607843f, -0.262745f}}, - {{1, 1, 1, 1}, {0, 0, 0, 0}, {-0.392157f, 0.403922f, 0.607843f}}, -}}; constexpr float PRISM_STEP = 20; constexpr float PRISM_TURN = 30; constexpr float PRISM_SPEED_BONUS = 2; diff --git a/src/entity_laser.cpp b/src/entity_laser.cpp index c1608f2..063542b 100644 --- a/src/entity_laser.cpp +++ b/src/entity_laser.cpp @@ -122,14 +122,6 @@ 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; @@ -1614,7 +1606,7 @@ void Entity_Laser::prism_update(bool& isRedirected, bool& isCut) for (size_t i = 0; i < prismLasers.size(); i++) { EntityPtr& slot = prismLasers[i]; - float splitAngle = angle + PRISM_SPREAD[i]; + float splitAngle = angle + PRISM_LASER_SPREAD[i]; if (isMissing) { if (slot) continue; @@ -1637,7 +1629,7 @@ void Entity_Laser::prism_update(bool& isRedirected, bool& isCut) 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.SetColor(PRISM_LASER_COLORS[i], -1, COLOR_PRIORITY_DEFAULT, false, true); split.set_aim_angle(splitAngle); split.pos = hitPosition; } diff --git a/src/entity_laser_render.cpp b/src/entity_laser_render.cpp index e72b54d..8ab7879 100644 --- a/src/entity_laser_render.cpp +++ b/src/entity_laser_render.cpp @@ -1,11 +1,13 @@ #include "entity_laser.h" #include "entity_tear.h" +#include "fx_layers.h" #include "game.h" #include "kage_graphics.h" #include "log.h" #include "lua_engine.h" #include "npc_ai.h" #include "render_passes.h" +#include "room.h" #include #include @@ -20,6 +22,18 @@ constexpr float SHRINK_RENDER_RANGE = 300; constexpr float SHRINK_RENDER_LOSS = 0.5f; constexpr float RING_SCROLL_SPEED = 5; +// The hit area's debug display: a line laser's free end reaches 40 further, and a thick beam's start gets a ring 16 +// back from it, of two to twelve steps a quarter, one per ten of its circumference. +constexpr float HIT_LINE_REACH = 40; +constexpr float HIT_RING_BACK = 16; +constexpr float HIT_RING_STEP = 10; +constexpr float HIT_RING_MIN = 2; +constexpr float HIT_RING_MAX = 12; +constexpr float RIGHT_ANGLE_RADIANS = 1.5707964f; +constexpr int HIT_RING_VARIANTS[] = {LASER_THICK_RED, LASER_SHOOP, LASER_GIANT_RED, LASER_BRIM_TECH, + LASER_THICKER_RED, LASER_THICK_BROWN, LASER_BEAST, LASER_THICKER_BRIM_TECH, + LASER_GIANT_BRIM_TECH}; + // What one beam draw needs: where it lands on screen, its spritesheet and colors, and whether it is the shadow. struct BeamDraw { @@ -271,10 +285,77 @@ bool Entity_Laser::RenderShadowLayer(const Vector& offset) return true; } -// 0097eb50 The debug display of the laser's hit area (debug flag 6) is not reconstructed yet. +// A world point as the debug lines draw it: snapped to the screen and moved with the room's scroll. +static Vector debug_point(Vector world) +{ + return vector_add(render_position_get(world, RENDER_SNAPPED), g_game->room->renderScrollOffset); +} + +// A hit area's debug outline: a line on each side of a stretch of beam between two screen points, as far out as the +// laser's size, sideways to a direction. +static void hit_lines_render(Vector start, Vector end, Vector along, float size, const KColor& color) +{ + float cosine = std::cos(RIGHT_ANGLE_RADIANS); + float sine = std::sin(RIGHT_ANGLE_RADIANS); + Vector side = vector_make((cosine * along.x - sine * along.y) * size * ROOM_SCREEN_SCALE, + (sine * along.x + cosine * along.y) * size * ROOM_SCREEN_SCALE); + render_color_quad(vector_sub(start, side), vector_sub(end, side), color, color, 1); + render_color_quad(vector_add(start, side), vector_add(end, side), color, color, 1); +} + +// The debug ring at a thick beam's start: a circle of the laser's size, 16 back from its first sample, in two to +// twelve steps a quarter. +static void hit_ring_render(Entity_Laser& laser, const KColor& color) +{ + float angle = laser.angleDegrees * DEGREES_TO_RADIANS; + Vector first = laser.homingLaser.samples[0]; + Vector centre = debug_point( + vector_make(first.x - std::cos(angle) * HIT_RING_BACK, first.y - std::sin(angle) * HIT_RING_BACK)); + Vector previous = vector_make(std::cos(0.0f) * laser.size * ROOM_SCREEN_SCALE + centre.x, + std::sin(0.0f) * laser.size * ROOM_SCREEN_SCALE + centre.y); + int quarter = (int)std::clamp(laser.size * TAU / HIT_RING_STEP, HIT_RING_MIN, HIT_RING_MAX); + for (int segment = 1; segment <= quarter * 4; segment++) + { + float turn = (float)segment * HALF_TURN_DEGREES / (float)(quarter * 2) * DEGREES_TO_RADIANS; + Vector next = vector_make(std::cos(turn) * laser.size * ROOM_SCREEN_SCALE + centre.x, + std::sin(turn) * laser.size * ROOM_SCREEN_SCALE + centre.y); + render_color_quad(previous, next, color, color, 1); + previous = next; + } +} + +// 0097eb50 The debug display of the laser's hit area (debug flag 6), colored by what it collides with: lines along a +// straight beam from its position to its end, or along each stretch of a path (the last one 40 longer for a line +// laser that hit nothing), with a ring at a thick beam's start. void Entity_Laser::PostRender() { - if ((g_game->debugFlags & DEBUG_HITSPHERES) && size > 0 && entityCollisionClass != ENTCOLL_NONE && - sampleMode != SAMPLE_UNDECIDED) - reconstruction_missing("Entity_Laser::PostRender 0097eb50: the hit area's debug lines"); + if (!(g_game->debugFlags & DEBUG_HITSPHERES) || size <= 0 || entityCollisionClass == ENTCOLL_NONE || + sampleMode == SAMPLE_UNDECIDED) + return; + + static const KColor COLORS[] = {kcolor_argb(0xff000000), kcolor_argb(0xffffa500), kcolor_argb(0xffffc0cb), + kcolor_argb(0xff00ff00), kcolor_argb(0xffff0000)}; + bool isKnownClass = entityCollisionClass >= ENTCOLL_PLAYERONLY && entityCollisionClass <= ENTCOLL_ALL; + const KColor& color = COLORS[isKnownClass ? entityCollisionClass : 0]; + if (sampleMode == SAMPLE_STRAIGHT) + { + Vector along = vector_from_angle(angleDegrees); + Vector end = vector_add(pos, vector_scale(along, std::abs(posOffset.y) + laserLength)); + return hit_lines_render(debug_point(pos), debug_point(end), along, size, color); + } + + const std::vector& samples = homingLaser.samples; + bool isLine = subtype != LASER_SUBTYPE_RING_LUDOVICO && subtype != LASER_SUBTYPE_RING_PROJECTILE && + subtype != LASER_SUBTYPE_RING_FOLLOW_PARENT; + for (size_t i = 0; i + 1 < samples.size(); i++) + { + Vector next = samples[i + 1]; + if (isLine && i == samples.size() - 2 && !isGridHit && maxDistance <= 0) + next = vector_add(next, vector_resized(vector_sub(next, samples[i]), HIT_LINE_REACH)); + Vector start = debug_point(samples[i]); + Vector end = debug_point(next); + hit_lines_render(start, end, vector_normalized(vector_sub(end, start)), size, color); + if (i == 0 && std::ranges::find(HIT_RING_VARIANTS, variant) != std::end(HIT_RING_VARIANTS)) + hit_ring_render(*this, color); + } } diff --git a/src/entity_list.cpp b/src/entity_list.cpp index 6656c18..94bdf6d 100644 --- a/src/entity_list.cpp +++ b/src/entity_list.cpp @@ -1,4 +1,5 @@ #include "entity_list.h" +#include "entity_bomb.h" #include "entity_effect.h" #include "entity_familiar.h" #include "entity_npc.h" @@ -18,8 +19,6 @@ constexpr const char* SHADOW_PNG = "gfx/shadow.png"; // How much lower a walking player's reflection sits in the water. constexpr float PLAYER_REFLECTION_DROP = 4; -constexpr int BOMB_ROCKET = 19; -constexpr int BOMB_ROCKET_GIGA = 20; constexpr int KNIFE_MAIN = 0; // The boss bar flashes for this many frames when the bosses' health changes. constexpr int BOSS_BAR_FLASH_FRAMES = 8; @@ -30,10 +29,6 @@ constexpr uint32_t RENDER_Z_NORMAL_START = 10000; constexpr int RENDER_LIST_CAPACITY = 0x4000; constexpr int RENDER_SORT_SWAP_BUDGET = (RENDER_LIST_CAPACITY >> 4) + 1; -// The room's render surface, its size and margin, centered on the screen. -constexpr float ROOM_SURFACE_WIDTH = 338; -constexpr float ROOM_SURFACE_HEIGHT = 182; -constexpr float ROOM_SURFACE_MARGIN = 52; // A surface surfaces_bake draws into: the flag of the entities drawn there, the flags that keep them, and whether any // is to be drawn. diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index d11e2ee..7b148fb 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -59,8 +59,6 @@ constexpr float GFUEL_BIG_SCALE = 1.5f; constexpr std::string_view GFUEL_BIG_EXPLOSION_ANM2 = "gfx/promo/gfuel/effects/explosion_big.anm2"; constexpr std::array GFUEL_EXPLOSION_ANM2S = {"gfx/promo/gfuel/effects/explosion.anm2", "gfx/promo/gfuel/effects/explosion2.anm2"}; -constexpr float GFUEL_BLAST_PITCH = 0.9f; -constexpr float GFUEL_BLAST_PITCH_RANGE = 0.2f; constexpr int GFUEL_BIG_BLAST_SHAKE = 40; constexpr int GFUEL_BLAST_SHAKE = 20; @@ -132,7 +130,6 @@ constexpr float CONFUSION_WANDER = 240; constexpr float FEAR_WANDER = 100; constexpr int FEAR_RETARGET_RANGE = 15; constexpr int FEAR_RETARGET_MIN = 5; -constexpr float MOVEMENT_DEADZONE = 0.1f; constexpr float ATTACK_PREDICT_FRAMES = 5; constexpr int LINE_BLOCKED_MAX = 8; // The corners of the band a line check samples around each step. @@ -174,7 +171,6 @@ constexpr int MARK_SPREAD_COUNTDOWN = 30; constexpr ColorMod SPREAD_SLOW_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 / 255.0f, 40 / 255.0f, 40 / 255.0f}}; constexpr int SOUND_POOP_DEATH = 237; constexpr float POOP_DEATH_VOLUME = 0.9f; -constexpr uint64_t FLAG_FRIENDLY_BALL_DYING = 1ull << 60; // The burst effects a dead NPC leaves besides blood (Lua's EffectVariant). enum DeathBurst : int @@ -203,7 +199,6 @@ constexpr int COLLECTIBLE_SPIDER_MOD_ID = 403; constexpr int COLLECTIBLE_BROKEN_MODEM_ID = 514; constexpr int COLLECTIBLE_GUPPYS_EYE_ID = 665; constexpr int COLLECTIBLE_SALVATION_ID = 696; -constexpr int COLLECTIBLE_VANISHING_TWIN_ID = 697; constexpr int TRINKET_PURPLE_HEART_ID = 5; constexpr int TRINKET_TICK_ID = 53; constexpr int TRINKET_SUPER_MAGNET_ID = 68; @@ -216,8 +211,6 @@ constexpr int ACHIEVEMENT_BOSS_COLORS = 3; constexpr int ACHIEVEMENT_MORE_BOSS_COLORS = 33; constexpr int ACHIEVEMENT_REDIRECTS = 348; constexpr uint32_t ROOM_CONFIG_FLAG_NO_CHAMPIONS = 1 << 2; -constexpr int GRID_CELL = 40; -constexpr float GRID_TOP = 120; constexpr int SHIELD_FRAMES_DEFAULT = 120; constexpr int BOSS_ID_NONE_EXCLUDED_FIRST = 46; constexpr int BOSS_ID_NONE_EXCLUDED_LAST = 52; @@ -318,7 +311,6 @@ Entity* spawn_at(int type, int variant, int subType, const Vector& position, Ent // spawn. In a versus match the other players count too. static bool is_nearest_enemy_candidate(Entity& entity, bool isVersusPlayer) { - constexpr int CULTIST_BLOOD_SPAWN = 10; int type = entity.type; if (g_game->frameCount - entity.spawnFrame <= 1) return false; @@ -331,10 +323,17 @@ static bool is_nearest_enemy_candidate(Entity& entity, bool isVersusPlayer) type != ENTITY_GENERIC_PROP && type != ENTITY_MINECART; } -// 00707370 Game::GetNearestEnemy: the enemy nearest a position within a radius that a source may target, a charmed -// one counted 400 farther. A friendly source passes over the players it may not hurt, and in a versus match over its -// own ancestors. The original's optional distance function is left out, as no caller here passes one. -Entity* game_nearest_enemy(const Vector& position, Entity* source, float radius) +// A candidate's measure in a nearest search: the search's own, or its squared distance from the position. +static float target_distance_get(TargetDistance distance, const Vector& position, Entity* source, Entity& candidate) +{ + if (distance) return distance(position, source, candidate); + return vector_length_squared(vector_sub(candidate.pos, position)); +} + +// 00707370 Game::GetNearestEnemy: the enemy nearest a position (by the search's measure) within a radius that a +// source may target, a charmed one counted 400 farther. A friendly source passes over the players it may not hurt, +// and in a versus match over its own ancestors. +Entity* game_nearest_enemy(const Vector& position, Entity* source, float radius, TargetDistance measure) { constexpr float CHARMED_DISTANCE_SQUARED = 160000; bool isVersus = g_game->deathmatchManager.is_active(); @@ -350,7 +349,7 @@ Entity* game_nearest_enemy(const Vector& position, Entity* source, float radius) if (source && ((isVersus && source->IsDescendantOf(entity)) || !source->IsValidTarget(entity))) continue; if (!is_nearest_enemy_candidate(*entity, isVersus && isPlayer)) continue; - float distance = vector_length_squared(vector_sub(position, entity->pos)); + float distance = target_distance_get(measure, position, source, *entity); if (entity->HasEntityFlags(FLAG_CHARM)) distance += CHARMED_DISTANCE_SQUARED; if (distance >= best) continue; best = distance; @@ -412,9 +411,9 @@ 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 // 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) + bool isBulb, TargetDistance measure) { - float distance = vector_length_squared(vector_sub(target.pos, position)); + float distance = target_distance_get(measure, position, source, target); if (!player) return distance; Entity_Player* twin = player->twin_get(); @@ -426,7 +425,7 @@ static float target_score_get(const Vector& position, Entity* source, Entity& ta Vector between = vector_sub(twin->pos, player->pos); bool isMeeting = vector_dot(vector_add(player->velocity, twin->velocity), between) < 0 && vector_length_squared(between) < TWIN_NEAR_SQUARED; - if (isMeeting) distance = vector_length_squared(vector_sub(twin->pos, position)) + 1; + if (isMeeting) distance = target_distance_get(measure, position, source, *twin) + 1; } if (!isBulb) return distance; @@ -458,7 +457,7 @@ bool entity_is_prey(Entity& prey) // 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) + float maxDistance, TargetDistance measure) { if (!isPlayersOnly && isTargetDecoys && source && source->IsEnemy()) { @@ -493,7 +492,7 @@ Entity* game_nearest_target_player(const Vector& position, Entity* source, bool player = static_cast(target)->player; if (player && player->IsInvisible()) continue; - float score = target_score_get(position, source, *target, player, isBulb); + float score = target_score_get(position, source, *target, player, isBulb, measure); if (score >= best) continue; best = score; nearest = target; @@ -503,7 +502,7 @@ Entity* game_nearest_target_player(const Vector& position, Entity* source, bool for (Entity* decoy : g_game->room->entityList.mainEL) { if (decoy->type != ENTITY_FAMILIAR || decoy->variant != Entity_Familiar::PUNCHING_BAG) continue; - float distance = vector_length_squared(vector_sub(decoy->pos, position)); + float distance = target_distance_get(measure, position, source, *decoy); if (distance >= best) continue; best = distance; nearest = decoy; @@ -515,7 +514,7 @@ Entity* game_nearest_target_player(const Vector& position, Entity* source, bool { 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; + float distance = target_distance_get(measure, position, source, *baited) * BAITED_DISTANCE_SCALE; if (distance >= best) continue; best = distance; nearest = baited; @@ -532,7 +531,7 @@ Entity* game_nearest_target_player(const Vector& position, Entity* source, bool continue; if (prey->HasEntityFlags(FLAG_NO_TARGET)) continue; - float distance = vector_length_squared(vector_sub(prey->pos, position)); + float distance = target_distance_get(measure, position, source, *prey); bool isFriendly = prey->HasEntityFlags(FLAG_FRIENDLY); if (prey->type == ENTITY_BISHOP && !isFriendly) distance *= PUPPY_BISHOP_SCALE; if (prey->type == ENTITY_BLOOD_PUPPY) distance += PUPPY_KIN_PENALTY; @@ -575,8 +574,8 @@ void game_encountered_boss_add(int bossType, int bossVariant) uint32_t room_grid_collision_at(const Vector& position) { Room& room = *g_game->room; - int column = (int)((position.x - GRID_CELL) / GRID_CELL + HALF); - int row = (int)((position.y - GRID_TOP) / GRID_CELL + HALF); + int column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + HALF); + int row = (int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + HALF); bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; return room.GetGridCollision(isInside ? room.gridWidth * row + column : -1); } @@ -623,10 +622,10 @@ bool room_check_line(const Vector& start, const Vector& end, int mode, int gridP step = vector_scale(step, LINE_STEP / length); auto cellOf = [](float value, float origin) { - return (int)((value - origin) / GRID_CELL + HALF); + return (int)((value - origin) / GRID_CELL_SIZE + HALF); }; - int startColumn = cellOf(start.x, GRID_CELL); - int startRow = cellOf(start.y, GRID_TOP); + int startColumn = cellOf(start.x, GRID_ORIGIN_X); + int startRow = cellOf(start.y, GRID_ORIGIN_Y); bool isStartInside = startColumn >= 0 && startColumn < room.gridWidth && startRow >= 0 && startRow < room.gridHeight; int startIndex = isStartInside ? room.gridWidth * startRow + startColumn : -1; @@ -638,8 +637,8 @@ bool room_check_line(const Vector& start, const Vector& end, int mode, int gridP at = vector_sub(at, step); if (mode == LINE_MODE_EXPLOSION) { - int column = cellOf(at.x, GRID_CELL); - int row = cellOf(at.y, GRID_TOP); + int column = cellOf(at.x, GRID_ORIGIN_X); + int row = cellOf(at.y, GRID_ORIGIN_Y); bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; int cellIndex = isInside ? row * room.gridWidth + column : -1; if (line_cell_is_blast_wall(room, cellIndex)) return false; @@ -647,8 +646,8 @@ bool room_check_line(const Vector& start, const Vector& end, int mode, int gridP } if (mode == LINE_MODE_CELL) { - int column = cellOf(at.x, GRID_CELL); - int row = cellOf(at.y, GRID_TOP); + int column = cellOf(at.x, GRID_ORIGIN_X); + int row = cellOf(at.y, GRID_ORIGIN_Y); bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; int cellIndex = isInside ? row * room.gridWidth + column : -1; if (room.GetGridCollision(cellIndex) != COLLISION_NONE) return false; @@ -657,8 +656,8 @@ bool room_check_line(const Vector& start, const Vector& end, int mode, int gridP } for (const LineCorner& corner : LINE_CORNERS) { - int column = cellOf(at.x + corner.x, GRID_CELL); - int row = cellOf(at.y + corner.y, GRID_TOP); + int column = cellOf(at.x + corner.x, GRID_ORIGIN_X); + int row = cellOf(at.y + corner.y, GRID_ORIGIN_Y); int collision = line_cell_collision(room, column, row); if (mode == LINE_MODE_PROJECTILE && collision == COLLISION_PIT) continue; if (collision != COLLISION_NONE) return false; @@ -1905,7 +1904,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)) captured_update(); + if (HasEntityFlags(FLAG_PERSISTENT | FLAG_DELIRIUM_FORM)) captured_update(); float healthBefore = health; if (type == ENTITY_MINECART) update_physics(); @@ -1937,8 +1936,8 @@ 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 +// Part of 006c4b30: a persistent enemy or a Delirium form (Delirious's friendly boss) wastes a quarter of health every +// 15 frames down to 1, greying and shrinking with it. A hit this frame that is not fire, spikes or poop passes on as 1 // damage from its biggest hit, or as 5 from an explosion. // The shrink is lost at once, as the frame's scale reset (FUN_006d6650) overwrites it. void Entity_NPC::captured_update() @@ -1982,35 +1981,43 @@ void Entity_NPC::captured_update() // The camouflage seeds: an enemy takes on the floor under it, sampled on its first frames and every 30 after, and // blends a tenth of the way toward it each frame, nearly black underneath. void Entity_NPC::camouflage_update() +{ + constexpr float CAMO_DARKNESS = 0.02f; + camouflage_blend(*this, floorColor, CAMO_DARKNESS); +} + +// The camouflage of an entity on the camo seeds: a color sampled from the floor under it on its first frames and +// every 30 after, which its sprite blends a tenth of the way toward each frame, tinted to a darkness underneath. +void camouflage_blend(Entity& entity, ColorMod& floorColor, float darkness) { constexpr float CAMO_ALPHA = 0.7f; constexpr float CAMO_FLOOR_TONE = 0.9f; constexpr float CAMO_ALPHA_BLEND = 0.3f; constexpr float CAMO_FLOOR_BLEND = 0.5f; constexpr float CAMO_SPRITE_BLEND = 0.1f; - constexpr 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) + ANM2& sprite = entity.sprite; + if (entity.FrameCount() < CAMO_SAMPLE_WINDOW) { - KColor floor = room_floor_texel_get(room, pos); + KColor floor = room_floor_texel_get(room, entity.pos); const float shares[] = {floor._red, floor._green, floor._blue}; std::fill_n(floorColor._tint, 3, 0.0f); floorColor._tint[3] = CAMO_ALPHA; for (int i = 0; i < 3; i++) floorColor._offset[i] = shares[i] * CAMO_FLOOR_TONE; sprite.color = floorColor; } - if ((uint32_t)(g_game->frameCount + index) % CAMO_RESAMPLE_FRAMES < CAMO_SAMPLE_WINDOW) + if ((uint32_t)(g_game->frameCount + entity.index) % CAMO_RESAMPLE_FRAMES < CAMO_SAMPLE_WINDOW) { - KColor floor = room_floor_texel_get(room, pos); + KColor floor = room_floor_texel_get(room, entity.pos); floorColor._tint[3] = std::lerp(floorColor._tint[3], CAMO_ALPHA, CAMO_ALPHA_BLEND); const float shares[] = {floor._red, floor._green, floor._blue}; for (int i = 0; i < 3; i++) floorColor._offset[i] = std::lerp(floorColor._offset[i], shares[i] * CAMO_FLOOR_TONE, CAMO_FLOOR_BLEND); } ColorMod blended = color_lerp(sprite.color, floorColor, CAMO_SPRITE_BLEND); - std::fill_n(blended._tint, 3, CAMO_DARKNESS); + std::fill_n(blended._tint, 3, darkness); blended._tint[3] = 1; sprite.color = blended; } @@ -2150,7 +2157,7 @@ float Entity_NPC::compute_speed_multiplier() if (HasEntityFlags(FLAG_SLOW) && state != NPC_STATE_DEATH) speed *= SPEED_HALF; if (HasEntityFlags(FLAG_WEAKNESS)) speed *= SPEED_WEAKENED; - if (IsBoss() && !IsFriendly() && room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_VANISHING_TWIN_ID)) + if (IsBoss() && !IsFriendly() && room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_VANISHING_TWIN)) speed *= SPEED_VANISHING_TWIN; return speed; } diff --git a/src/entity_npc.h b/src/entity_npc.h index 3b51a34..1ce5bde 100644 --- a/src/entity_npc.h +++ b/src/entity_npc.h @@ -68,6 +68,8 @@ enum ProjectilesMode : int // The Mulligan that runs from the player, which a champion's health never raises. constexpr int MULLIGAN_VARIANT_FLEEING = 2; +// Movement or controller input below this length counts as standing still. +constexpr float MOVEMENT_DEADZONE = 0.1f; // Lua's ChampionColor values the NPC code tests. enum ChampionColor : int @@ -404,16 +406,24 @@ enum LineCheckMode : int }; constexpr int LINE_CHECK_THRESHOLD = 999; +// The pitch of G FUEL!'s explosions and bursts, 0.9 to 1.1. +constexpr float GFUEL_BLAST_PITCH = 0.9f; +constexpr float GFUEL_BLAST_PITCH_RANGE = 0.2f; + +// How a nearest search measures a candidate in place of its squared distance from the position (the Slog's lanes). +using TargetDistance = float (*)(const Vector& position, Entity* source, Entity& candidate); + // Game's, Room's and PlayerManager's queries the enemies need, until those classes carry them. Entity_Player* game_nearest_player(const Vector& position); Entity_Player* main_player_nearest(const Vector& position); -Entity* game_nearest_enemy(const Vector& position, Entity* source, float radius); +Entity* game_nearest_enemy(const Vector& position, Entity* source, float radius, TargetDistance distance = nullptr); bool any_player_flying(); Entity* game_nearest_target_player(const Vector& position, Entity* source, bool isPlayersOnly, bool isTargetDecoys, - float maxDistance); + float maxDistance, TargetDistance distance = nullptr); void game_shake_screen(int timeout); Entity* spawn_at(int type, int variant, int subType, const Vector& position, Entity* spawner); Entity* gfuel_explosion_spawn(const Vector& position, float scale); +void camouflage_blend(Entity& entity, ColorMod& floorColor, float darkness); int poof_size_get(Entity& entity, bool isHugeAllowed); void game_encountered_boss_add(int bossType, int bossVariant); bool game_is_hard_mode(); diff --git a/src/entity_npc_render.cpp b/src/entity_npc_render.cpp index 0c4990b..ca95afe 100644 --- a/src/entity_npc_render.cpp +++ b/src/entity_npc_render.cpp @@ -1,5 +1,6 @@ #include "entity_npc.h" #include "boss_final.h" +#include "boss_repentance.h" #include "beam_renderer.h" #include "entity_config.h" #include "entity_player.h" @@ -13,12 +14,16 @@ #include #include #include +#include #include constexpr float NPC_SCREEN_SCALE = 0.65f; constexpr int SPAWN_BAR_DELAY = 2; constexpr float HEALTH_BAR_DROP = 10; +// Part of 006d2e50 The dummy shows the damage it took (its v1.x) to two places, centred 28 above it. +constexpr float DUMMY_TEXT_RISE = 28; + // The health bar's sheet: left cap, stretched middle and right cap 8 high in the top row, the fill below the middle. // Its width grows with the log of the NPC's toughness, from 8 to 48. The fill's hue runs from red (none left) to green, // blue for the toughest, and greys a little away from green. @@ -288,7 +293,7 @@ static void npc_body_render(Entity_NPC& npc, const Vector& offset) case ENTITY_HORNY_BOYS: return horny_boys_render(npc, offset); case ENTITY_CLUTCH: - return reconstruction_missing("NpcHelper::clutch_render 00575a10"); + return clutch_render(npc, offset); case ENTITY_BEAST: return beast_render(npc, offset); case ENTITY_MINECART: @@ -440,7 +445,14 @@ void Entity_NPC::Render(const Vector& offset) bool isMainPass = renderMode == RENDER_NORMAL || renderMode == RENDER_WATER_ABOVE; if (isMainPass && !isHidden) { - if (type == ENTITY_DUMMY) reconstruction_missing("Entity_NPC::Render 006d2e50: the dummy's damage text"); + if (type == ENTITY_DUMMY) + { + FontSettings settings; + settings.alignment = ALIGN_TOP_CENTER; + g_manager->font6_PFTempestaSevenCondensed.DrawString(std::format("{:.2f}", v1.x), + vector_make(renderPosition.x, renderPosition.y - DUMMY_TEXT_RISE), + vector_make(1, 1), kcolor_rgba(1, 1, 1, 1), settings); + } status_overlay_render(base); if (npc_is_health_bar_shown(*this)) health_bar_render(*this, vector_make(renderPosition.x, renderPosition.y + HEALTH_BAR_DROP)); diff --git a/src/entity_npc_room.cpp b/src/entity_npc_room.cpp index f5125f5..d747af1 100644 --- a/src/entity_npc_room.cpp +++ b/src/entity_npc_room.cpp @@ -2,6 +2,7 @@ #include "entity_npc.h" #include "entity_player.h" #include "game.h" +#include "grid_entity_door.h" #include "level_generator.h" #include "npc_ai.h" @@ -14,10 +15,8 @@ constexpr float ROOM_STEP_Y = 280; // The door slot's side when the rooms have no place on the floor: the xorshift (1, 11, 16) of the decoration seed. constexpr uint32_t DOOR_SIDE_SHIFT_INDEX = 5; -constexpr int DOOR_SIDES = 4; -// A persistent enemy is spared contact damage for its first 20 frames in the new room. -constexpr uint64_t FLAG_FRIENDLY_BALL_DYING = 1ull << 60; +// A persistent enemy or Delirium form is spared contact damage for its first 20 frames in the new room. constexpr int ROOM_ENTER_DAMAGE_COUNTDOWN = 20; // How many rooms the players moved, by the rooms' places on the floor, else by the side of the door they came in by @@ -85,5 +84,5 @@ void Entity_NPC::room_enter() poof->SetColor(DARK_ESAU_POOF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); } } - if (HasEntityFlags(FLAG_PERSISTENT | FLAG_FRIENDLY_BALL_DYING)) damageCountdown = ROOM_ENTER_DAMAGE_COUNTDOWN; + if (HasEntityFlags(FLAG_PERSISTENT | FLAG_DELIRIUM_FORM)) damageCountdown = ROOM_ENTER_DAMAGE_COUNTDOWN; } diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index 53fd499..d6548be 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -1,17 +1,22 @@ #include "entity_pickup.h" #include "active_items.h" +#include "entity_bomb.h" #include "entity_config.h" #include "entity_effect.h" #include "entity_familiar.h" +#include "entity_npc.h" #include "entity_player.h" #include "entity_player_trinkets.h" #include "game.h" #include "grid_entity.h" +#include "grid_entity_door.h" #include "level.h" #include "log.h" #include "lua_engine.h" #include "manager.h" +#include "item_pool.h" #include "menu_options.h" +#include "npc_ai.h" #include "npc_depths.h" #include "persistent_game_data.h" #include "platform.h" @@ -35,18 +40,6 @@ constexpr std::array CHESTS = {PICKUP_CHEST, PICKUP_LOCKEDCHEST, // The coins a coin subtype is worth (penny, nickel, dime, double, lucky, sticky, golden), from subtype 1. constexpr std::array COIN_VALUES = {1, 1, 5, 10, 2, 1, 5, 1}; -// A bomb's subtypes the code tells apart, as Lua's BombSubType names them. -enum BombSubType : int -{ - BOMB_NORMAL = 1, - BOMB_DOUBLEPACK, - BOMB_TROLL, - BOMB_GOLDEN, - BOMB_SUPERTROLL, - BOMB_GOLDENTROLL, - BOMB_GIGA -}; - // The items, trinkets, characters, challenges, seeds and unlocks the pickups ask about. constexpr int BLOOD_CHARGE_CAP = 99; constexpr int COLLECTIBLE_MAGNETO = 53; @@ -99,13 +92,10 @@ constexpr int FAMILIAR_KEY_BUM = 90; constexpr int FAMILIAR_SUPER_BUM = 102; constexpr int FIREPLACE_VARIANT_COUNT = 10; constexpr int MINECART_UNSAVED_VARIANT = 10; -constexpr int BOMB_THROWABLE = 13; // A sack's loot flies out at 2 to 5, drawn by this RNG shift. constexpr int SACK_SHIFT_INDEX = 23; constexpr float SACK_SPEED_MIN = 2; constexpr float SACK_SPEED_RANGE = 3; -constexpr int BOMB_ROCKET = 19; -constexpr int BOMB_ROCKET_GIGA = 20; constexpr uint32_t PORTAL_SAVED_SUBTYPE_MIN = 899; // The effects a room keeps when it or no spawner placed them (tiny bugs and flies, wall bugs, worms, wisps, beetles, // butterflies, tadpoles, lil ghosts), and the ones it always keeps (carpet, dice floor, heaven light, dirt patch, @@ -212,6 +202,7 @@ constexpr int CARD_SUIT_CHANCE = 10; // Pickup motion and timing. constexpr int COLLISION_COOLDOWN = 10; +constexpr int THROWN_PICKUP_HIT_COUNTDOWN = 30; constexpr int SETTLE_FRAMES = 6; constexpr float PICKUP_REPOSITION_STEP = 40; constexpr int APPEAR_KICK = 15; @@ -242,6 +233,22 @@ constexpr uint32_t DUNGEON_PIT_COLLISION = 4; constexpr int DUNGEON_SETTLE_FRAMES = 2; constexpr float PEDESTAL_MASS = 8; constexpr float PEDESTAL_FRICTION = 0.8f; +constexpr float PEDESTAL_POOF_DROP = 10; +constexpr float PICKUP_MAGNET_PULL = 0.5f; +constexpr float PICKUP_MAGNET_FRICTION = 0.8f; +constexpr int PEDESTAL_VANISH_FRAMES = 4; +constexpr int BROKEN_SHOVEL_VANISH_FRAME = 4; +constexpr ColorMod BROKEN_SHOVEL_POOF_COLOR = color_make({0.7f, 0.4f, 1, 1}); +constexpr float ENDING_PICKUP_WIDTH = 2; +constexpr float SLIDE_SEED_PUSH = 2; +constexpr float CAMO_PICKUP_DARKNESS = 0.01f; + +// Whether a chest opening by itself takes the other options away. +enum OptionsTaken +{ + OPTIONS_KEEP, + OPTIONS_REMOVE +}; // How deep pickup_variant_pick is in itself, which Nuh Uh! only rerolls at the top of. static int pickDepth = 0; @@ -456,7 +463,7 @@ static void coin_subtype_pick(PickupChoice& choice, RNG& rng) return; } } - bool isNickelDaily = g_game->dailyChallenge._specialDailyId == SPECIAL_DAILY_NICKELS; + bool isNickelDaily = g_game->dailyChallenge.specialDailyId == SPECIAL_DAILY_NICKELS; if (kind == COIN_NICKEL && isNickelDaily) kind = COIN_STICKYNICKEL; } @@ -466,11 +473,11 @@ static void bomb_subtype_pick(PickupChoice& choice, RNG& rng) int& kind = choice.subType; if (kind != 0) return; - kind = BOMB_NORMAL; - if (rng_chance(rng, ODDS_DOUBLE_BOMB)) kind = BOMB_DOUBLEPACK; - if (rng_chance(rng, ODDS_GOLDEN_BOMB) && is_unlocked(ACHIEVEMENT_GOLDEN_BOMB)) kind = BOMB_GOLDEN; - if (rng_chance(rng, ODDS_SUPERTROLL)) kind = kind == BOMB_GOLDEN ? BOMB_GOLDENTROLL : BOMB_SUPERTROLL; - if (rng_chance(rng, ODDS_TROLL)) kind = kind == BOMB_GOLDEN ? BOMB_GOLDENTROLL : BOMB_TROLL; + kind = BOMB_SUBTYPE_NORMAL; + if (rng_chance(rng, ODDS_DOUBLE_BOMB)) kind = BOMB_SUBTYPE_DOUBLEPACK; + if (rng_chance(rng, ODDS_GOLDEN_BOMB) && is_unlocked(ACHIEVEMENT_GOLDEN_BOMB)) kind = BOMB_SUBTYPE_GOLDEN; + if (rng_chance(rng, ODDS_SUPERTROLL)) kind = kind == BOMB_SUBTYPE_GOLDEN ? BOMB_SUBTYPE_GOLDENTROLL : BOMB_SUBTYPE_SUPERTROLL; + if (rng_chance(rng, ODDS_TROLL)) kind = kind == BOMB_SUBTYPE_GOLDEN ? BOMB_SUBTYPE_GOLDENTROLL : BOMB_SUBTYPE_TROLL; } // A chest's kind and its contents: a plain chest may turn mimic, red, bomb, spiked, a grab bag, wooden or haunted, any @@ -601,7 +608,7 @@ static void choice_modifiers_apply(PickupChoice& choice, RNG& rng, bool isLittle if (variant == PICKUP_HEART && (kind == HEART_FULL || kind == HEART_SCARED)) kind = HEART_DOUBLEPACK; if (variant == PICKUP_COIN && kind == COIN_PENNY) kind = COIN_DOUBLEPACK; if (variant == PICKUP_KEY && kind == KEY_NORMAL) kind = KEY_DOUBLEPACK; - else if (variant == PICKUP_BOMB && kind == BOMB_NORMAL) kind = BOMB_DOUBLEPACK; + else if (variant == PICKUP_BOMB && kind == BOMB_SUBTYPE_NORMAL) kind = BOMB_SUBTYPE_DOUBLEPACK; } bool isScatHeart = is_listed({HEART_FULL, HEART_HALF, HEART_DOUBLEPACK, HEART_BLENDED, HEART_SCARED, HEART_ROTTEN}, @@ -614,7 +621,7 @@ static void choice_modifiers_apply(PickupChoice& choice, RNG& rng, bool isLittle challenge_pickups_apply(choice, rng, isLittleBaggy); bool isPoopBomb = variant == PICKUP_BOMB && g_game->playerManager.are_all_players_tainted_blue_baby() && - !is_listed({BOMB_TROLL, BOMB_SUPERTROLL, BOMB_GOLDENTROLL}, kind); + !is_listed({BOMB_SUBTYPE_TROLL, BOMB_SUBTYPE_SUPERTROLL, BOMB_SUBTYPE_GOLDENTROLL}, kind); if (isPoopBomb) { variant = PICKUP_POOP; @@ -646,7 +653,7 @@ static bool nuh_uh_reroll(PickupChoice& choice, RNG& rng) if (isDoubling && (int)owner->GetTrinketRNG(TRINKET_NUH_UH).RandomInt(NUH_UH_ROLL) < doubleChance) { if (choice.variant == PICKUP_HEART) choice.subType = HEART_DOUBLEPACK; - else if (choice.variant == PICKUP_BOMB) choice.subType = BOMB_DOUBLEPACK; + else if (choice.variant == PICKUP_BOMB) choice.subType = BOMB_SUBTYPE_DOUBLEPACK; } PickupChoice reroll = choice; @@ -865,8 +872,9 @@ void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, u entity_spawn({pos, {}, nullptr, 0, ENTITY_FLY, 0, dropRNG.Next()})->scoreMultiplier = 0; return; } - if (choice.variant == PICKUP_SHOPITEM) shop_ware_choose(choice, seed); - if (choice.variant == PICKUP_COLLECTIBLE) collectible_choose(choice.subType, seed); + RNG rng = rng_make(seed, DEFAULT_SHIFT_INDEX); + if (choice.variant == PICKUP_SHOPITEM) shop_ware_choose(choice, rng); + if (choice.variant == PICKUP_COLLECTIBLE) collectible_choose(choice.subType, rng); if (choice.variant == PICKUP_BROKEN_SHOVEL) { choice.subType = COLLECTIBLE_BROKEN_SHOVEL_1; @@ -875,11 +883,18 @@ void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, u lua_engine_get().PostPickupSelection(this, choice.variant, choice.subType); bool isPoopBomb = choice.variant == PICKUP_BOMB && g_game->playerManager.are_all_players_tainted_blue_baby() && - !is_listed({BOMB_TROLL, BOMB_SUPERTROLL, BOMB_GOLDENTROLL}, choice.subType); + !is_listed({BOMB_SUBTYPE_TROLL, BOMB_SUBTYPE_SUPERTROLL, BOMB_SUBTYPE_GOLDENTROLL}, choice.subType); if (isPoopBomb) choice = {1, PICKUP_POOP, seed}; - if (g_game->challenge == CHALLENGE_CANTRIPPED) reconstruction_missing("Entity_Pickup::Init 006e02f0: Cantripped"); - if (choice.variant == PICKUP_TAROTCARD) + bool isItemCard = g_game->challenge == CHALLENGE_CANTRIPPED && choice.variant == PICKUP_TAROTCARD; + if (isItemCard && (!(choice.subType & CARD_ITEM_FLAG) || (choice.subType & ~CARD_ITEM_FLAG) == 0)) + choice.subType = ItemPool::GetCardImpl(rng.Next()) | (int)CARD_ITEM_FLAG; + if (isItemCard) + { + Entity::Init(entityType, PICKUP_TAROTCARD, ITEM_CARD_SPRITE_SUBTYPE, seed); + subtype = choice.subType; + } + else if (choice.variant == PICKUP_TAROTCARD) { ItemConfig_Card* card = g_manager->itemConfig.GetCard(choice.subType); Entity::Init(entityType, PICKUP_TAROTCARD, card ? card->pickupSubtype : 2, seed); @@ -916,7 +931,7 @@ void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, u optionsPickupIndex = 0; bool isSaleSeed = g_game->seedEffects.HasSeedEffect(SEED_ITEMS_COST_MONEY) && variant != PICKUP_COIN && CanReroll() && !IsChest(variant); - if (isSaleSeed) reconstruction_missing("Entity_Pickup::Init 006e02f0: the seed that sells every pickup"); + if (isSaleSeed) shop_price_assign(); update_price_sprite(price); if (variant == PICKUP_HEART && g_game->challenge == CHALLENGE_ULTRA_HARD) Remove(); @@ -954,7 +969,32 @@ void Entity_Pickup::appear_start() velocity.y -= APPEAR_KICK; return; } - if (g_game->playerManager.GetGFuelCount() > 1) reconstruction_missing("Entity_Pickup::Init 006e02f0: the G FUEL!"); + if (g_game->playerManager.GetGFuelCount() > 1) gfuel_appear_spawn(pos, GFUEL_APPEAR_PICKUP); +} + +// The burst a pickup appears in while several players have G FUEL!. A pickup's shakes the screen first and plays its +// sound last, a pedestal's plays its sound and shakes the screen before its random flip and forced animation. +void gfuel_appear_spawn(const Vector& position, GfuelAppear appear) +{ + constexpr std::string_view GFUEL_APPEAR_ANM2 = "gfx/promo/gfuel/effects/explosion4.anm2"; + constexpr int GFUEL_APPEAR_SHAKE = 10; + bool isPedestal = appear == GFUEL_APPEAR_PEDESTAL; + auto soundPlay = [] + { npc_sound_play(SOUND_GFUEL_ITEM_APPEAR, 1, 2, random_between(GFUEL_BLAST_PITCH, GFUEL_BLAST_PITCH_RANGE)); }; + + if (!isPedestal) game_shake_screen(GFUEL_APPEAR_SHAKE); + Entity* burst = + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + burst->sprite.Load(GFUEL_APPEAR_ANM2, GRAPHICS_LOAD); + if (isPedestal) + { + soundPlay(); + game_shake_screen(GFUEL_APPEAR_SHAKE); + } + burst->sprite.isFlipX = (Random() & 1) == 0; + burst->sprite.Play(burst->sprite.GetDefaultAnimationName(), isPedestal ? PLAY_FORCED : PLAY_UNFORCED); + burst->Update(); + if (!isPedestal) soundPlay(); } // 006e21f0 Swaps in the spritesheets a variant shows: a trinket's own and its golden flag, a collectible's image, the @@ -985,11 +1025,18 @@ void Entity_Pickup::UpdateSprite(bool isIgnoreBlind) sprite.LoadGraphics(); } -// 006e17c0 Shows a chest's or sack's contents to a holder of Guppy's Eye, and otherwise removes the preview. +// 006e17c0 Shows a closed chest's or a sack's contents to a holder of Guppy's Eye, while it is not timing out, and +// otherwise removes the preview. void Entity_Pickup::UpdateLootPreview() { - if (anyone_has_collectible(COLLECTIBLE_GUPPYS_EYE)) - reconstruction_missing("Entity_Pickup::UpdateLootPreview 006e17c0: Guppy's Eye"); + bool isLoot = (IsChest(variant) && subtype != 0) || (variant == PICKUP_GRAB_BAG && !isDead); + if (anyone_has_collectible(COLLECTIBLE_GUPPYS_EYE) && isLoot && timeout < 1) + { + LootList loot = GetChestLoot(POOL_DRAW_PEEK, game_nearest_player(pos)); + auto* ghost = static_cast(pickupGhost.get()); + pickupGhost = Entity_Effect::CreateLootPreview(&loot, pos, this, ghost); + return; + } if (pickupGhost) pickupGhost->Remove(); } @@ -1000,22 +1047,146 @@ void Entity_Pickup::Interpolate() Entity::Interpolate(); } -// 006e69b0 Draws the pickup and its price, unless it is waiting to drop. -// An item's pedestal is not reconstructed yet. +// 006e69b0 Draws the pickup and its price, unless it is waiting to drop. The second item of a Mega Chest's pair is +// drawn by the first. void Entity_Pickup::Render(const Vector& offset) { if (!isExists || !isVisible || dropDelay >= 1) return; + if (variant == PICKUP_COLLECTIBLE && megaChestCollectible[0]) return; if (variant == PICKUP_COLLECTIBLE) pedestal_render(offset); else Entity::Render(offset); if (priceANM2.isLoaded) priceANM2.Render(SpriteDraw{renderPosition, {}, {}}); lua_engine_get().PostPickupRender(this, offset); } +// A chest opening by itself, thrown or haunted or a Mega Chest's last lock, may take the other options away. Its +// opening starts a challenge room's fight. Whether it opened. +static bool chest_open_alone(Entity_Pickup& chest, Entity_Player* player, OptionsTaken options) +{ + if (!chest.TryOpenChest(player)) return false; + if (options == OPTIONS_REMOVE) chest.RemoveOtherOptions(); + int roomType = g_game->room->roomType; + if (roomType == ROOM_CHALLENGE || roomType == ROOM_BOSSRUSH) g_game->ambush.StartChallenge(); + return true; +} + +// The poof a pedestal leaves vanishing in, a little below it. +static Entity* pedestal_poof_spawn(Entity_Pickup& pedestal) +{ + Vector below = vector_make(pedestal.pos.x, pedestal.pos.y + PEDESTAL_POOF_DROP); + return g_game->Spawn({.position = below, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); +} + +// Part of 006e3940: a scared heart flees where the nearest player or a Dark or Super Bum is about to be, inside 50, +// harder the nearer it is and turned up to 90 degrees either way by a draw that changes every ten frames. A calm, +// slow heart idles again. +static void scared_heart_flee(Entity_Pickup& heart) +{ + constexpr float SCARED_HEART_RANGE = 50; + constexpr float SCARED_HEART_PUSH = 3; + constexpr float SCARED_HEART_CALM_SPEED = 4; + constexpr int SCARED_HEART_TURN_FRAMES = 10; + auto aheadOf = [&](Entity& chaser) + { return vector_sub(vector_add(chaser.pos, vector_scale(chaser.velocity, 2)), heart.pos); }; + + Vector threat = aheadOf(*game_nearest_player(heart.pos)); + for (Entity* entity : entity_query_radius(heart.pos, SCARED_HEART_RANGE, QUERY_FAMILIARS)) + { + bool isBum = entity->type == ENTITY_FAMILIAR && + (entity->variant == FAMILIAR_DARK_BUM || entity->variant == FAMILIAR_SUPER_BUM); + Vector bum = isBum ? aheadOf(*entity) : threat; + if (vector_length_squared(bum) < vector_length_squared(threat)) threat = bum; + } + + float distanceSquared = vector_length_squared(threat); + if (distanceSquared >= SCARED_HEART_RANGE * SCARED_HEART_RANGE) + { + const AnimationData* animation = heart.sprite.animState.animData; + if (vector_length_squared(heart.velocity) <= SCARED_HEART_CALM_SPEED && animation && animation->isLooping) + heart.sprite.Play("Idle"); + return; + } + + uint32_t seed = heart.initSeed * (uint32_t)((g_game->frameCount - heart.spawnFrame) / SCARED_HEART_TURN_FRAMES); + float turn = rng_make(seed ? seed : 1, DEFAULT_SHIFT_INDEX).RandomFloat() * HALF_TURN_DEGREES - RIGHT_ANGLE_DEGREES; + float strength = distanceSquared * SCARED_HEART_PUSH / (SCARED_HEART_RANGE * SCARED_HEART_RANGE); + Vector push = vector_resized(threat, strength); + heart.AddVelocity_divided(vector_scale(vector_rotated(push, turn), -1), false); + if (heart.entityCollisionClass != ENTCOLL_NONE) heart.sprite.Play("IdlePanic"); +} + +// Part of 006e3940: a closed haunted chest a Polty dropped opens by itself. Free on the floor, it wakes as a player +// comes within 100 and a fading Polty rises out of it to carry it off. +static void haunted_chest_update(Entity_Pickup& chest) +{ + constexpr float HAUNTED_GHOST_DEPTH = 6; + constexpr int HAUNTED_GHOST_FADE_FRAMES = 5; + bool isHeld = chest.HasEntityFlags(FLAG_HELD); + bool isThrown = chest.HasEntityFlags(FLAG_THROWN); + + if (isHeld && !isThrown && !chest.child) + { + chest.isVisible = true; + chest_open_alone(chest, nullptr, OPTIONS_REMOVE); + return; + } + bool isAwake = chest.collisionCooldown < 1 && chest.entityCollisionClass != ENTCOLL_NONE && !isHeld && !isThrown; + Entity_Player* player = game_nearest_player(chest.pos); + float rangeSquared = HAUNTED_CHEST_RANGE * HAUNTED_CHEST_RANGE; + if (!isAwake || vector_length_squared(vector_sub(chest.pos, player->pos)) >= rangeSquared) return; + + Entity* ghost = + g_game->Spawn({.position = chest.pos, .spawner = &chest, .type = ENTITY_POLTY, .seed = chest.dropRNG.Next()}); + ghost->renderDepthOffset = HAUNTED_GHOST_DEPTH; + chest.AddEntityFlags(FLAG_HELD); + ghost->ClearEntityFlags(FLAG_APPEAR); + ghost->Update(); + ghost->SetColor(color_make({1, 1, 1, 0}), HAUNTED_GHOST_FADE_FRAMES, COLOR_PRIORITY_DEFAULT, true, true); + chest.child = ghost; +} + +// Part of 006e3940: a rotten heart drips a small, sickly blood splat when it lands, or one time in three while it +// slides fast, and landing it sheds one to three worms around it. +static void rotten_heart_drip(Entity_Pickup& heart) +{ + constexpr float DRIP_SPEED = 3; + constexpr uint32_t DRIP_ODDS = 3; + constexpr uint32_t WORMS_MAX = 3; + constexpr float WORM_TURN = 2 * 3.14f; + + bool isLanding = heart.sprite.animState.animData && heart.sprite.IsEventTriggered("DropSound"); + if (!isLanding && !(vector_length(heart.velocity) > DRIP_SPEED && Random() % DRIP_ODDS == 0)) return; + + Entity* splat = g_game->Spawn( + {.position = heart.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + float scale = random_between(ROTTEN_SPLAT_MIN, ROTTEN_SPLAT_RANGE); + splat->sprite.scale = vector_make(scale, scale); + splat->SetColor(ROTTEN_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + if (!isLanding) return; + + for (uint32_t worms = Random() % WORMS_MAX + 1; worms > 0; worms--) + { + float speed = random_unit() * 2 + 1; + float angle = random_unit() * WORM_TURN; + float distance = random_unit() * HALF * heart.size; + Vector position = + vector_make(std::cos(angle) * distance + heart.pos.x, std::sin(angle) * distance + heart.pos.y); + float heading = random_unit() * WORM_TURN; + Vector velocity = vector_make(std::cos(heading) * speed, speed * std::sin(heading) * HALF); + g_game->Spawn({.position = position, + .velocity = velocity, + .type = ENTITY_EFFECT, + .variant = EFFECT_WORM, + .seed = Random()}); + } +} + // 006e3940 Runs the pickup for a frame: a thrown chest's flight, Keeper's hearts turning into flies, Sack Head's -// sacks, troll bombs going off, holding its place where it must, its motion and friction, its appear animation and -// drop sound, its timeouts and the crawl space's gravity. A mimic chest turns into a spiked one as a player comes near. -// Items, the glitched pickups and the rarer kinds' behaviours are not reconstructed yet. +// sacks, troll bombs going off, holding its place where it must, a scared heart's flight, its motion and friction, +// its appear animation and drop sound, the glitch it may appear with, its timeouts and the crawl space's gravity. +// Haunted, mega and mimic chests open or wake, rotten hearts drip, and the seeds slide and hide pickups. void Entity_Pickup::Update() { if (dropDelay > 0) @@ -1035,7 +1206,7 @@ void Entity_Pickup::Update() entityGridCollisionClass = height < THROW_LOW ? GRIDCOLL_WALLS : GRIDCOLL_NOPITS; heightVelocity = speedMultiplier * THROW_GRAVITY + fallSpeed; height = speedMultiplier * fallSpeed + height; - if (isCollidesWithGrid && IsChest(variant) && subtype != 0) TryOpenChest(nullptr); + if (isCollidesWithGrid && IsChest(variant) && subtype != 0) chest_open_alone(*this, nullptr, OPTIONS_KEEP); if (height >= 0) { ClearEntityFlags(FLAG_THROWN); @@ -1043,7 +1214,7 @@ void Entity_Pickup::Update() heightVelocity = 0; entityCollisionClass = ENTCOLL_ALL; entityGridCollisionClass = GRIDCOLL_GROUND; - if (IsChest(variant) && subtype != 0) TryOpenChest(nullptr); + if (IsChest(variant) && subtype != 0) chest_open_alone(*this, nullptr, OPTIONS_KEEP); } } if (IsChest(variant)) @@ -1077,8 +1248,8 @@ void Entity_Pickup::Update() if (variant == PICKUP_BOMB) { - int bomb = subtype == BOMB_TROLL ? BOMB_VARIANT_TROLL : subtype == BOMB_SUPERTROLL ? BOMB_VARIANT_SUPERTROLL - : subtype == BOMB_GOLDENTROLL ? BOMB_VARIANT_GOLDENTROLL : 0; + int bomb = subtype == BOMB_SUBTYPE_TROLL ? BOMB_VARIANT_TROLL : subtype == BOMB_SUBTYPE_SUPERTROLL ? BOMB_VARIANT_SUPERTROLL + : subtype == BOMB_SUBTYPE_GOLDENTROLL ? BOMB_VARIANT_GOLDENTROLL : 0; if (bomb) { entity_spawn({pos, {}, nullptr, 0, ENTITY_BOMB, bomb, Random()}); @@ -1096,12 +1267,23 @@ void Entity_Pickup::Update() target_position_update(); if (variant == PICKUP_BED) renderZOffset = BED_RENDER_Z; - else if (variant == PICKUP_HEART && subtype == HEART_SCARED && price == 0 && !isDead) - reconstruction_missing("Entity_Pickup::Update 006e3940: a scared heart running away"); + else if (variant == PICKUP_HEART && subtype == HEART_SCARED && price == 0 && !isDead) scared_heart_flee(*this); + if (variant == PICKUP_COLLECTIBLE && subtype == COLLECTIBLE_BROKEN_SHOVEL_1 && isTouched && + g_game->room->GetFrameCount() == BROKEN_SHOVEL_VANISH_FRAME) + { + pedestal_poof_spawn(*this)->SetColor(BROKEN_SHOVEL_POOF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + timeout = PEDESTAL_VANISH_FRAMES; + entityCollisionClass = ENTCOLL_NONE; + } Entity::Update(); if (IsChest(variant) && !HasEntityFlags(FLAG_THROWN)) velocity = vector_make(velocity.x * CHEST_DRAG, velocity.y * CHEST_DRAG); + else if (variant == PICKUP_BIGCHEST || variant == PICKUP_TROPHY) + { + sizeMulti = vector_make(ENDING_PICKUP_WIDTH, 1); + velocity = vector_sub(targetPosition, pos); + } if (variant == PICKUP_COLLECTIBLE) { mass = PEDESTAL_MASS; @@ -1113,13 +1295,26 @@ void Entity_Pickup::Update() if (isAutoUpdatePrice && price != 0) price_refresh(); appear_update(); - bool isClosedChest = IsChest(variant) && subtype != 0; - bool isAwake = collisionCooldown < 1 && entityCollisionClass != ENTCOLL_NONE; - bool isHaunting = variant == PICKUP_HAUNTEDCHEST && isClosedChest && - (HasEntityFlags(FLAG_HELD) || (isAwake && is_player_near(pos, HAUNTED_CHEST_RANGE))); - bool isMegaOpening = variant == PICKUP_MEGACHEST && isClosedChest && sprite.IsEventTriggered("Open"); - if (isHaunting || isMegaOpening || (variant == PICKUP_HEART && subtype == HEART_ROTTEN)) - reconstruction_missing("Entity_Pickup::Update 006e3940: haunted and mega chests and rotten hearts"); + if (variant == PICKUP_HAUNTEDCHEST && subtype != 0) haunted_chest_update(*this); + if (variant == PICKUP_HEART && subtype == HEART_ROTTEN) rotten_heart_drip(*this); + if (variant == PICKUP_MEGACHEST && subtype != 0 && sprite.animState.animData && sprite.IsEventTriggered("Open")) + { + if (subtype == 1) + { + Entity_Player* opener = target && target->type == ENTITY_PLAYER ? static_cast(target.get()) + : nullptr; + chest_open_alone(*this, opener, OPTIONS_REMOVE); + } + else subtype--; + } + bool isLeavingDeathCertificate = variant == PICKUP_COLLECTIBLE && + g_game->currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE && + optionsPickupIndex == 1 && g_game->deathCertificateExitTimer > 0 && timeout < 1; + if (isLeavingDeathCertificate) + { + pedestal_poof_spawn(*this); + timeout = PEDESTAL_VANISH_FRAMES; + } if (timeout > 0 && --timeout == 0) Remove(); if (wait > 0) wait--; if (chestReCloseTimer > 0 && --chestReCloseTimer == 0 && variant == PICKUP_ETERNALCHEST) @@ -1156,9 +1351,13 @@ void Entity_Pickup::Update() variant) || IsChest(variant); if (g_game->seedEffects.HasSeedEffect(SEED_PICKUPS_SLIDE) && isSlider) - reconstruction_missing("Entity_Pickup::Update 006e3940: the seed that slides pickups"); + { + velocity = {}; + if (Entity_Player* player = main_player_nearest(pos)) + AddVelocity_divided(vector_scale(player->lastVelocity, SLIDE_SEED_PUSH), false); + } if (g_game->seedEffects.HasSeedEffect(SEED_CAMO_PICKUPS) || g_game->seedEffects.HasSeedEffect(SEED_CAMO_EVERYTHING)) - reconstruction_missing("Entity_Pickup::Update 006e3940: the seeds that recolor pickups"); + camouflage_blend(*this, colorMod, CAMO_PICKUP_DARKNESS); if (timeout > 0 && variant != PICKUP_COLLECTIBLE) { @@ -1238,9 +1437,17 @@ void Entity_Pickup::target_position_update() gridRepositionState = 0; } - bool isHeld = price != 0 || variant == PICKUP_COLLECTIBLE || variant == PICKUP_BED || (variant == PICKUP_COIN && subtype == COIN_STICKYNICKEL) || - variant == PICKUP_MOMSCHEST || variant == PICKUP_MEGACHEST; - if (isHeld) + bool isHeld = price != 0 || variant == PICKUP_COLLECTIBLE || variant == PICKUP_BED || + (variant == PICKUP_COIN && subtype == COIN_STICKYNICKEL) || variant == PICKUP_MOMSCHEST || + variant == PICKUP_MEGACHEST; + Entity* megaPartner = variant == PICKUP_COLLECTIBLE ? megaChestCollectible[0].get() : nullptr; + if (megaPartner) + { + targetPosition = megaPartner->targetPosition; + velocity = megaPartner->velocity; + pos = megaPartner->pos; + } + else if (isHeld) { Room& room = *g_game->room; bool isFresh = room.roomType != ROOM_DUNGEON && g_game->frameCount - spawnFrame < SETTLE_FRAMES; @@ -1248,15 +1455,115 @@ void Entity_Pickup::target_position_update() targetPosition = room_free_pickup_position_find({targetPosition, PICKUP_REPOSITION_STEP, true}); velocity = vector_sub(targetPosition, pos); } - if (gridRepositionState == 1) - reconstruction_missing("Entity_Pickup::Update 006e3940: a pickup pushed away from a door"); + if (gridRepositionState == 1) door_push(); +} + +// A pickup the nearest player is near a door with is pushed away from both, from the first such door, once. +void Entity_Pickup::door_push() +{ + constexpr float DOOR_NEAR = 70; + constexpr float PUSH_FROM_PLAYER = 3; + constexpr float PUSH_FROM_DOOR = 5; + Room& room = *g_game->room; + Entity_Player* player = game_nearest_player(pos); + + for (GridEntity_Door* door : room.doors) + { + if (!door) continue; + Vector doorPos = room.GetGridPosition(door->gridIndex); + if (vector_length_squared(vector_sub(doorPos, player->pos)) >= DOOR_NEAR * DOOR_NEAR) continue; + Vector fromPlayer = vector_resized(vector_sub(pos, player->pos), PUSH_FROM_PLAYER); + Vector fromDoor = vector_resized(vector_sub(pos, doorPos), PUSH_FROM_DOOR); + velocity = vector_add(velocity, vector_add(fromPlayer, fromDoor)); + break; + } + gridRepositionState = 2; +} + +// A glitched pickup's arrival: an item flickers on its third frame and becomes a new glitched item on its fourth. +// Any other pickup skips ahead, then flickers and jumps frames until its tenth to fifteenth frame, when it settles, +// replays its animation and splits into two copies of itself, a step apart. +static void glitch_update(Entity_Pickup& pickup) +{ + constexpr int GLITCH_ITEM_FLICKER_FRAME = 3; + constexpr int GLITCH_ITEM_FRAME = 4; + constexpr int GLITCH_SKIP_FRAME = 5; + constexpr int GLITCH_SKIP = 2; + constexpr int GLITCH_FRAMES_MIN = 6; + constexpr int GLITCH_FRAMES_SURE = 10; + constexpr int GLITCH_FRAMES_MAX = 15; + constexpr uint32_t GLITCH_KEEP_MASK = 7; + constexpr uint32_t GLITCH_FLICKER_ODDS = 6; + constexpr uint32_t GLITCH_JUMP_RANGE = 5; + constexpr int GLITCH_JUMP_BACK = 2; + constexpr int GLITCH_FIRST_FRAME = 6; + constexpr float GLITCH_SPLIT = 8; + constexpr uint32_t GLITCH_SPLIT_SHIFT = 3; + ANM2& sprite = pickup.sprite; + int age = g_game->frameCount - pickup.spawnFrame; + auto settle = [&] + { + sprite.bitflags &= ~ANIM_RENDER_GLITCH; + pickup.ClearEntityFlags(FLAG_GLITCH); + }; + + if (pickup.isDead) return settle(); + if (pickup.variant == PICKUP_COLLECTIBLE) + { + if (age == GLITCH_ITEM_FLICKER_FRAME) sprite.bitflags |= ANIM_RENDER_GLITCH; + else if (age > GLITCH_ITEM_FRAME) settle(); + else if (age == GLITCH_ITEM_FRAME) + { + pickup.subtype = g_game->proceduralItemManager.CreateProceduralItem(pickup.dropRNG.Next(), 0); + pickup.UpdateSprite(true); + if (ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(pickup.subtype)) + pickup.charge = item->initCharge >= 0 ? item->initCharge : item->maxCharges; + } + return; + } + if (age < GLITCH_FRAMES_MIN) + { + if (age != GLITCH_SKIP_FRAME) return; + int frame = sprite.GetFrame(); + if (sprite.animState.animData) sprite.animState.SetFrameFloat((float)(frame + GLITCH_SKIP)); + if (sprite.animState.animData) sprite.animState.isPlaying = false; + return; + } + if (age < GLITCH_FRAMES_SURE || (age < GLITCH_FRAMES_MAX && (Random() & GLITCH_KEEP_MASK) != 0)) + { + if (sprite.bitflags & ANIM_RENDER_GLITCH) + { + if ((Random() & 1) == 0) sprite.bitflags &= ~ANIM_RENDER_GLITCH; + } + else if (Random() % GLITCH_FLICKER_ODDS == 0) sprite.bitflags |= ANIM_RENDER_GLITCH; + else if ((Random() & GLITCH_KEEP_MASK) == 0) + { + int jump = (int)(Random() % GLITCH_JUMP_RANGE); + sprite.SetFrame((float)std::max(GLITCH_FIRST_FRAME, sprite.GetFrame() - GLITCH_JUMP_BACK + jump)); + } + return; + } + + settle(); + sprite.Play(sprite.GetAnimation(), PLAY_FORCED); + Vector split = vector_scale(random_direction(), GLITCH_SPLIT); + uint32_t seed = rng_make(pickup.initSeed, GLITCH_SPLIT_SHIFT).Next(); + g_game->Spawn({.position = vector_add(pickup.pos, split), + .spawner = pickup.spawnerEntity.get(), + .subType = pickup.subtype, + .type = pickup.type, + .variant = pickup.variant, + .seed = seed}) + ->Update(); + pickup.pos = vector_sub(pickup.pos, split); } // Settles the appear animation: once it ends the pickup idles (a chest without contents shows open) and can be -// collected. Its drop sound plays on its event, which also lets it be collected while it still appears. +// collected. Its drop sound plays on its event, which also lets it be collected while it still appears. A glitched +// pickup runs its glitch instead. void Entity_Pickup::appear_update() { - if (HasEntityFlags(FLAG_GLITCH)) reconstruction_missing("Entity_Pickup::Update 006e3940: a glitched pickup"); + if (HasEntityFlags(FLAG_GLITCH)) return glitch_update(*this); if (isDead && !sprite.IsPlaying()) return Remove(); if (!sprite.animState.animData) return; @@ -1351,12 +1658,10 @@ static void magneto_chest_open(Entity_Pickup& pickup, Entity_Player& player) // 006ed690 Magneto, Super Magnet and Broken Magnet pull free pickups to the nearest player who wants them (Broken // Magnet only coins until doubled), and Magneto opens the chests a player comes near. Without a magnet a pickup flying -// over the pits lands again. The original also pulls coins to a second player of one kind, which needs co-op. +// over the pits lands again. Coins are also pulled to co-op Mag Babies. void Entity_Pickup::update_magnet_attraction() { constexpr float MAX_DISTANCE_SQUARED = 1e9f; - constexpr float PULL = 0.5f; - constexpr float PULL_FRICTION = 0.8f; PlayerManager& players = g_game->playerManager; if (variant == PICKUP_THROWABLEBOMB) return; bool isMagnet = anyone_has_collectible(COLLECTIBLE_MAGNETO) || players.AnyoneHasTrinket(TRINKET_SUPER_MAGNET) || @@ -1364,7 +1669,7 @@ void Entity_Pickup::update_magnet_attraction() if (!isMagnet) { if (entityGridCollisionClass == GRIDCOLL_WALLS) entityGridCollisionClass = GRIDCOLL_GROUND; - return; + return mag_baby_pull(); } bool isPriceless = price == 0 || is_listed({PICKUP_KEY, PICKUP_BOMB, PICKUP_COIN, PICKUP_HEART, PICKUP_LIL_BATTERY}, variant); @@ -1393,11 +1698,25 @@ void Entity_Pickup::update_magnet_attraction() Vector toward = vector_make(closest->pos.x - pos.x, closest->pos.y - pos.y); float length = std::sqrt(toward.x * toward.x + toward.y * toward.y); if (length > 0) toward = vector_make(1 / length * toward.x, 1 / length * toward.y); - velocity = vector_make((toward.x * PULL + velocity.x) * PULL_FRICTION, (toward.y * PULL + velocity.y) * PULL_FRICTION); + velocity = vector_make((toward.x * PICKUP_MAGNET_PULL + velocity.x) * PICKUP_MAGNET_FRICTION, + (toward.y * PICKUP_MAGNET_PULL + velocity.y) * PICKUP_MAGNET_FRICTION); entityGridCollisionClass = GRIDCOLL_WALLS; } - if (price == 0 && variant == PICKUP_COIN && players.playerList.size() > 1) - reconstruction_missing("Entity_Pickup::update_magnet_attraction 006ed690: the coins pulled to a second player"); + mag_baby_pull(); +} + +// The end of 006ed690: a free coin is pulled to each co-op Mag Baby after the first player. +void Entity_Pickup::mag_baby_pull() +{ + std::vector& players = g_game->playerManager.playerList; + if (price != 0 || variant != PICKUP_COIN) return; + for (size_t i = 1; i < players.size(); i++) + { + if (players[i]->babySkin != BABY_MAG) continue; + Vector toward = vector_normalized(vector_sub(players[i]->pos, pos)); + entityGridCollisionClass = GRIDCOLL_WALLS; + velocity = vector_scale(vector_add(vector_scale(toward, PICKUP_MAGNET_PULL), velocity), PICKUP_MAGNET_FRICTION); + } } // Part of 006e8ae0: a devil deal taken (bought, or a spike offer paid for). The run counts it, Azazel unlocking at @@ -1552,8 +1871,16 @@ static void bed_touch(Entity_Pickup& bed, Entity_Player& player) // that collect and the rarer items and trinkets that change what a pickup gives are not reconstructed yet. bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) { - if (variant == PICKUP_COLLECTIBLE && (megaChestCollectible[0] || megaChestCollectible[1])) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a Mega Chest's items"); + if (variant == PICKUP_COLLECTIBLE && megaChestCollectible[0] && g_forceCollideDepth == 0) return true; + Entity* megaPartner = variant == PICKUP_COLLECTIBLE ? megaChestCollectible[1].get() : nullptr; + if (megaPartner && collider->pos.x > pos.x) + { + g_forceCollideDepth++; + bool isSolid = collider->HandleCollision(megaPartner, true); + isSolid |= megaPartner->HandleCollision(collider, false); + g_forceCollideDepth--; + return isSolid; + } LuaResult result = static_cast(g_luaEngine)->PrePickupCollision(this, collider, isLow); if (result == LUA_RESULT_TRUE) return true; if (result == LUA_RESULT_FALSE) return false; @@ -1569,16 +1896,16 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) collider->subtype == PLAYER_KEEPER) return false; if (g_game->seedEffects.HasSeedEffect(SEED_PICKUPS_TIMEOUT)) ResetColor(); - if (HasEntityFlags(FLAG_THROWN) && spawnerType == ENTITY_POLTY) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a thrown pickup's hit"); + if (HasEntityFlags(FLAG_THROWN) && spawnerType == ENTITY_POLTY && g_forceCollideDepth == 0) + collider->TakeDamage(1, 0, EntityRef(this), THROWN_PICKUP_HIT_COUNTDOWN); } if (variant == PICKUP_COIN && subtype == COIN_STICKYNICKEL) { if (collider->type != ENTITY_PLAYER) return true; sprite.Play("Touched"); collisionCooldown = COLLISION_COOLDOWN; - if (static_cast(collider)->HasTrinket(TRINKET_CURSED_PENNY)) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Cursed Penny"); + auto* player = static_cast(collider); + if (player->HasTrinket(TRINKET_CURSED_PENNY)) player->cursedPennyPending = subtype; return true; } if (isLow || collider->type != ENTITY_PLAYER) @@ -1616,7 +1943,7 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) player = player->twin_get(); bool isRestricted = (variant == PICKUP_HEART && subtype == HEART_ETERNAL) || - (variant == PICKUP_BOMB && (subtype == BOMB_SUPERTROLL || subtype == BOMB_TROLL)) || + (variant == PICKUP_BOMB && (subtype == BOMB_SUBTYPE_SUPERTROLL || subtype == BOMB_SUBTYPE_TROLL)) || !is_listed({PICKUP_HEART, PICKUP_COIN, PICKUP_BOMB, PICKUP_GRAB_BAG, PICKUP_KEY}, variant); if (!player->CanPickupItem() && isRestricted && !player->isDead) return price != 0; @@ -1745,6 +2072,27 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) return variant != PICKUP_COLLECTIBLE || g_game->room->roomType == ROOM_DUNGEON || price != 0; } +// A golden penny taken comes back somewhere in the room, less likely each time (0.98 to the times it came back). +static void golden_penny_return(Entity_Pickup& penny) +{ + constexpr double RETURN_DECAY = 0.98; + float chance = (float)std::pow(RETURN_DECAY, (double)penny.varData); + if (penny.dropRNG.RandomFloat() > chance) return; + + Room& room = *g_game->room; + Vector spot = + room_free_pickup_position_find({.position = room.GetRandomPosition(0), .isAvoidActiveEntities = true}); + g_pickupIgnoreModifiers++; + auto* copy = static_cast(g_game->Spawn({.position = spot, + .subType = penny.subtype, + .type = penny.type, + .variant = penny.variant, + .seed = penny.dropRNG.Next()})); + copy->varData = penny.varData + 1; + copy->sprite.Play("Reappear"); + g_pickupIgnoreModifiers--; +} + // The end of a collection: the procedural items' triggers, the pickup flying into its "Collect" animation and dying, // and the run's note that a heart, bomb or coin was picked up. void Entity_Pickup::collect_finish(Entity_Player* player) @@ -1758,12 +2106,92 @@ void Entity_Pickup::collect_finish(Entity_Player* player) sprite.Play("Collect"); isDead = true; UpdateLootPreview(); - if (variant == PICKUP_COIN && subtype == COIN_GOLDEN) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a golden penny's return"); + if (variant == PICKUP_COIN && subtype == COIN_GOLDEN) golden_penny_return(*this); if (variant == PICKUP_HEART || variant == PICKUP_BOMB || variant == PICKUP_COIN) g_game->gameStateFlags |= 1ull << GAME_STATE_HEART_BOMB_COIN_PICKED; } +// What April Fool's challenge gives instead of a pickup. +enum FoolGift +{ + FOOL_NOTHING, + FOOL_COINS, + FOOL_KEYS, + FOOL_BOMBS, + FOOL_HEARTS, + FOOL_SOUL_HEARTS, + FOOL_BLACK_HEARTS, + FOOL_GOLDEN_HEARTS, + FOOL_ETERNAL_HEARTS, + FOOL_GOLDEN_KEY, + FOOL_GOLDEN_BOMB +}; + +// April Fool's draws for hearts, keys, bombs, golden keys, golden bombs and golden hearts. +constexpr std::array FOOL_HEART_GIFTS = {FOOL_KEYS, FOOL_BOMBS, FOOL_COINS, FOOL_COINS}; +constexpr std::array FOOL_KEY_GIFTS = {FOOL_BOMBS, FOOL_KEYS, FOOL_HEARTS, + FOOL_SOUL_HEARTS, FOOL_BLACK_HEARTS, FOOL_GOLDEN_HEARTS}; +constexpr std::array FOOL_BOMB_GIFTS = {FOOL_COINS, FOOL_KEYS, FOOL_HEARTS, FOOL_SOUL_HEARTS, + FOOL_BLACK_HEARTS}; +constexpr std::array FOOL_GOLDEN_KEY_GIFTS = {FOOL_ETERNAL_HEARTS, FOOL_GOLDEN_BOMB, FOOL_GOLDEN_HEARTS}; +constexpr std::array FOOL_GOLDEN_BOMB_GIFTS = {FOOL_GOLDEN_KEY, FOOL_GOLDEN_HEARTS, FOOL_ETERNAL_HEARTS}; +constexpr std::array FOOL_GOLDEN_HEART_GIFTS = {FOOL_GOLDEN_KEY, FOOL_GOLDEN_BOMB, FOOL_COINS, + FOOL_NOTHING}; +// A coin's April Fool's gift by a roll under each bound, and the coins a golden heart gives. +constexpr std::array FOOL_COIN_ROLLS = {0.12f, 0.24f, 0.36f, 0.42f, 0.48f, 0.5f, 0.75f}; +constexpr int FOOL_GOLDEN_COINS = 10; +constexpr float FOOL_FART_RADIUS = 120; + +// Gives a player an amount of an April Fool's gift. +static void fool_give(Entity_Player& player, FoolGift gift, int amount) +{ + switch (gift) + { + case FOOL_NOTHING: break; + case FOOL_COINS: player.AddCoins(amount); break; + case FOOL_KEYS: player.AddKeys(amount); break; + case FOOL_BOMBS: player.AddBombs(amount); break; + case FOOL_HEARTS: player.AddHearts(amount, true, false); break; + case FOOL_SOUL_HEARTS: player.AddSoulHearts(amount, false); break; + case FOOL_BLACK_HEARTS: player.AddBlackHearts(amount); break; + case FOOL_GOLDEN_HEARTS: player.AddGoldenHearts(amount, false); break; + case FOOL_ETERNAL_HEARTS: player.AddEternalHearts(amount); break; + case FOOL_GOLDEN_KEY: player.AddGoldenKey(); break; + case FOOL_GOLDEN_BOMB: player.AddGoldenBomb(); break; + } +} + +// One of April Fool's gifts, drawn by the pickup's generator. +static FoolGift fool_draw(Entity_Pickup& pickup, std::span gifts) +{ + return gifts[pickup.dropRNG.RandomInt((uint32_t)gifts.size())]; +} + +// A coin's April Fool's gift: bombs, keys, red, soul or black hearts, a golden heart once unlocked, blue flies or a +// fart, as many as the coin is worth up to three. +static void fool_coin_give(Entity_Pickup& coin, Entity_Player& player, int value) +{ + constexpr int FOOL_SMALL_COIN = 6; + int amount = value < FOOL_SMALL_COIN ? std::min(value, 2) : 3; + float roll = coin.dropRNG.RandomFloat(); + auto bound = std::ranges::upper_bound(FOOL_COIN_ROLLS, roll) - FOOL_COIN_ROLLS.begin(); + bool isGoldenHeart = bound == 5 && is_run_unlocked(ACHIEVEMENT_GOLDEN_HEART); + + switch (bound) + { + case 0: player.AddBombs(amount); break; + case 1: player.AddKeys(amount); break; + case 3: player.AddSoulHearts(amount, false); break; + case 4: player.AddBlackHearts(amount); break; + case 6: player.AddBlueFlies(amount, coin.pos, nullptr); break; + case 7: game_butter_bean_fart({.position = coin.pos, .source = &player, .radius = FOOL_FART_RADIUS}); break; + default: + if (isGoldenHeart) player.AddGoldenHearts(1, false); + else player.AddHearts(amount, true, false); + break; + } +} + // The hearts a red heart of each kind holds, in halves. static int red_heart_amount(int heartKind) { @@ -1779,101 +2207,50 @@ static int red_heart_room(Entity_Player& player) return containers - player.redHearts; } -// A heart into the player's health: red hearts fill every player who can take them, the picker first, then the -// wisps they heal and The Jar. Soul, black, eternal, golden, bone and rotten hearts go to the picker, a blended heart -// fills red first and soul after. Whether anything was taken. -bool Entity_Pickup::heart_collect(Entity_Player& player) +// An Apple of Sodom heart bursts in blood, gibs and blue spiders (more for the heartier kinds) with a fart, and goes. +static void apple_of_sodom_burst(Entity_Pickup& heart, Entity_Player& player, int spiders) { - if (player.HasTrinket(TRINKET_APPLE_OF_SODOM)) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Apple of Sodom"); - if (g_game->challenge == CHALLENGE_APRILS_FOOL) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Bloody Mary's hearts"); + constexpr int SODOM_EXPLOSION_SUBTYPE = 3; + constexpr uint32_t SODOM_EXTRA_ODDS = 3; + constexpr float SODOM_FART_RADIUS = 100; + constexpr float SODOM_GIB_SPEED_MIN = 2; + constexpr float SODOM_GIB_SPEED_RANGE = 4; + EntitySpawn effect = {.position = heart.pos, .type = ENTITY_EFFECT}; - switch (subtype) + pickup_sound_play(SOUND_DEATH_BURST_SMALL); + effect.variant = EFFECT_BLOOD_EXPLOSION; + effect.subType = SODOM_EXPLOSION_SUBTYPE; + effect.seed = Random(); + g_game->Spawn(effect)->Update(); + effect.variant = EFFECT_BLOOD_SPLAT; + effect.subType = 0; + effect.seed = Random(); + g_game->Spawn(effect)->Update(); + + effect.variant = EFFECT_BLOOD_PARTICLE; + for (int gibs = (int)(Random() % SODOM_EXTRA_ODDS) + spiders; gibs > 0; gibs--) { - case HEART_FULL: - case HEART_HALF: - case HEART_DOUBLEPACK: - case HEART_SCARED: - break; - case HEART_SOUL: - case HEART_HALF_SOUL: - { - if (!player.CanPickSoulHearts()) return false; - int amount = subtype == HEART_SOUL ? 2 : 1; - player.AddSoulHearts(amount, false); - player.AddImmaculateConceptionCounter(amount); - return true; - } - case HEART_ETERNAL: - { - bool isRoom = player.maxHearts < player.GetHeartLimit(false) || player.eternalHearts == 0; - if (!isRoom || player.GetHealthType() == HEALTH_COIN) return false; - player.AddEternalHearts(1); - player.AddImmaculateConceptionCounter(1); - return true; - } - case HEART_BLACK: - if (!player.CanPickBlackHearts()) return false; - player.AddBlackHearts(2); - player.AddImmaculateConceptionCounter(2); - return true; - case HEART_GOLDEN: - if (!player.CanPickGoldenHearts()) return false; - player.AddGoldenHearts(1, false); - return true; - case HEART_BLENDED: - { - bool isMaggysBow = player.HasCollectible(COLLECTIBLE_MAGGYS_BOW); - bool isRed = false; - bool isSoul = false; - for (int left = 2; left > 0; left--) - { - if (player.CanPickRedHearts()) - { - player.AddHearts(isMaggysBow + 1, true, false); - isRed = true; - continue; - } - if (player.CanPickSoulHearts()) - { - player.AddSoulHearts(left, false); - isSoul = true; - } - else if (left > 1) return false; - break; - } - if (isRed) - { - pickup_sound_play(SOUND_BOSS2_BUBBLES); - player.AddImmaculateConceptionCounter(2); - } - if (isSoul) pickup_sound_play(SOUND_HOLY); - return true; - } - case HEART_BONE: - if (!player.CanPickBoneHearts()) return false; - player.AddBoneHearts(1); - player.AddImmaculateConceptionCounter(2); - return true; - case HEART_ROTTEN: - if (player.playerType == PLAYER_BETHANY_B && player.CanPickRedHearts()) - { - player.AddHearts(std::min(1, BLOOD_CHARGE_CAP - player.effectiveBloodCharge), false, false); - return true; - } - if (!player.CanPickRottenHearts()) return false; - player.AddRottenHearts(2, false); - player.AddImmaculateConceptionCounter(2); - return true; - default: - return false; + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float reach = HALF * heart.size; + effect.position = vector_make(std::cos(angle) * reach + heart.pos.x, std::sin(angle) * reach + heart.pos.y); + float heading = random_unit() * RANDOM_HALF_TURN * 2; + float speed = random_between(SODOM_GIB_SPEED_MIN, SODOM_GIB_SPEED_RANGE); + effect.velocity = vector_make(std::cos(heading) * speed, std::sin(heading) * speed); + effect.seed = Random(); + g_game->Spawn(effect)->Update(); } + for (int count = spiders + (int)(Random() % SODOM_EXTRA_ODDS); count > 0; count--) + player.ThrowBlueSpider(heart.pos, {}); + game_butter_bean_fart({.position = heart.pos, .source = &player, .radius = SODOM_FART_RADIUS}); + heart.Remove(); +} - int amount = red_heart_amount(subtype); - bool isMaggysBow = player.HasCollectible(COLLECTIBLE_MAGGYS_BOW); +// A red heart into the health of every player who can take it, the picker first (April Fool's gifts instead), then +// into the wisps that heal by hearts and The Jar. Whether anything was taken. +static bool red_heart_collect(Entity_Pickup& heart, Entity_Player& player, bool isMaggysBow) +{ + int amount = red_heart_amount(heart.subtype) * (isMaggysBow ? 2 : 1); bool isPickedUp = false; - if (isMaggysBow) amount *= 2; if (player.playerType == PLAYER_BETHANY_B && player.CanPickRedHearts()) { int taken = std::min(amount, BLOOD_CHARGE_CAP - player.effectiveBloodCharge); @@ -1891,15 +2268,23 @@ bool Entity_Pickup::heart_collect(Entity_Player& player) bool isSoulOwner = other == &player && other->variant == 0 && other->playerType == PLAYER_THESOUL && other->subPlayer; int taken = std::min(amount, red_heart_room(isSoulOwner ? *other->subPlayer : *other)); - other->AddHearts(taken, true, false); + if (g_game->challenge == CHALLENGE_APRILS_FOOL) + fool_give(*other, fool_draw(heart, FOOL_HEART_GIFTS), taken / 2); + else other->AddHearts(taken, true, false); other->AddImmaculateConceptionCounter(taken); amount -= taken; isPickedUp = true; } for (Entity* entity : g_game->room->entityList.updateEL) - if (entity->IsType(ENTITY_FAMILIAR, Entity_Familiar::WISP, WISP_HEALED_BY_HEARTS) && entity->isExists && - static_cast(entity)->player == &player) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a wisp healed by hearts"); + { + bool isHealedWisp = entity->IsType(ENTITY_FAMILIAR, Entity_Familiar::WISP, WISP_HEALED_BY_HEARTS) && + entity->isExists && static_cast(entity)->player == &player; + if (!isHealedWisp || entity->health >= entity->maxHitPoints) continue; + int healed = std::min((int)((entity->maxHitPoints - entity->health) * 2), amount); + amount -= healed; + entity->health += (float)healed * HALF; + isPickedUp = true; + } int jarAmount = isMaggysBow ? amount / 2 : amount; if (jarAmount > 0 && player.activeItems[0].item == COLLECTIBLE_THE_JAR && player.jarHearts < JAR_HEARTS_MAX) @@ -1910,14 +2295,169 @@ bool Entity_Pickup::heart_collect(Entity_Player& player) return isPickedUp; } -// A coin into the player's coins, the penny trinkets' effects (entity_player_trinkets.cpp), and a lucky penny's luck -// with its name shown. +// A heart into the player's health: red hearts fill every player who can take them (red_heart_collect). Soul, black, +// eternal, golden, bone and rotten hearts go to the picker, a blended heart fills red first and soul after. April +// Fool's gives other pickups instead. Apple of Sodom bursts a red heart into blue spiders half the time, any other +// heart half the time with a doubled trinket, and every heart it could not take. Whether anything was taken. +bool Entity_Pickup::heart_collect(Entity_Player& player) +{ + constexpr uint32_t SODOM_SHIFT = 37; + bool isFool = g_game->challenge == CHALLENGE_APRILS_FOOL; + bool isSodom = player.HasTrinket(TRINKET_APPLE_OF_SODOM); + bool isSodomRoll = rng_make(dropRNG._seed, SODOM_SHIFT).RandomInt(2) == 0; + bool isRefused = player.GetTrinketMultiplier(TRINKET_APPLE_OF_SODOM) > 1 && isSodomRoll; + bool isPickedUp = false; + int spiders = 0; + auto foolHeart = [&](int immaculate) + { + fool_give(player, fool_draw(*this, FOOL_HEART_GIFTS), 1); + player.AddImmaculateConceptionCounter(immaculate); + return true; + }; + + switch (subtype) + { + case HEART_FULL: + case HEART_HALF: + case HEART_DOUBLEPACK: + case HEART_SCARED: + { + bool isMaggysBow = player.HasCollectible(COLLECTIBLE_MAGGYS_BOW); + spiders = (subtype == HEART_HALF ? 1 : subtype == HEART_DOUBLEPACK ? 6 : 3) * (isMaggysBow ? 2 : 1); + if (!isSodom || !isSodomRoll) isPickedUp = red_heart_collect(*this, player, isMaggysBow); + break; + } + case HEART_SOUL: + case HEART_HALF_SOUL: + { + int amount = subtype == HEART_SOUL ? 2 : 1; + spiders = subtype == HEART_SOUL ? 4 : 2; + if (isRefused || !player.CanPickSoulHearts()) break; + if (isFool) isPickedUp = foolHeart(amount); + else + { + player.AddSoulHearts(amount, false); + player.AddImmaculateConceptionCounter(amount); + isPickedUp = true; + } + break; + } + case HEART_ETERNAL: + { + spiders = 6; + bool isRoom = player.maxHearts < player.GetHeartLimit(false) || player.eternalHearts == 0; + if (isRefused || !isRoom || player.GetHealthType() == HEALTH_COIN) break; + if (isFool) isPickedUp = foolHeart(1); + else + { + player.AddEternalHearts(1); + player.AddImmaculateConceptionCounter(1); + isPickedUp = true; + } + break; + } + case HEART_BLACK: + spiders = 5; + if (isRefused || !player.CanPickBlackHearts()) break; + if (isFool) isPickedUp = foolHeart(2); + else + { + player.AddBlackHearts(2); + player.AddImmaculateConceptionCounter(2); + isPickedUp = true; + } + break; + case HEART_GOLDEN: + { + spiders = 4; + if (isRefused || !player.CanPickGoldenHearts()) break; + FoolGift gift = isFool ? fool_draw(*this, FOOL_GOLDEN_HEART_GIFTS) : FOOL_GOLDEN_HEARTS; + if (gift == FOOL_GOLDEN_BOMB && !is_run_unlocked(ACHIEVEMENT_GOLDEN_BOMB)) gift = FOOL_COINS; + fool_give(player, gift, gift == FOOL_COINS ? FOOL_GOLDEN_COINS : 1); + isPickedUp = true; + break; + } + case HEART_BLENDED: + { + spiders = 4; + if (isRefused) break; + if (isFool) + { + fool_give(player, fool_draw(*this, FOOL_HEART_GIFTS), 1); + pickup_sound_play(SOUND_BOSS2_BUBBLES); + isPickedUp = true; + break; + } + bool isMaggysBow = player.HasCollectible(COLLECTIBLE_MAGGYS_BOW); + bool isRed = false; + bool isSoul = false; + for (int left = 2; left > 0; left--) + { + if (player.CanPickRedHearts()) + { + player.AddHearts(isMaggysBow + 1, true, false); + isRed = true; + continue; + } + if (player.CanPickSoulHearts()) + { + player.AddSoulHearts(left, false); + isSoul = true; + } + break; + } + if (!isRed && !isSoul) break; + if (isRed) + { + pickup_sound_play(SOUND_BOSS2_BUBBLES); + player.AddImmaculateConceptionCounter(2); + } + if (isSoul) pickup_sound_play(SOUND_HOLY); + isPickedUp = true; + break; + } + case HEART_BONE: + spiders = 3; + if (isRefused || !player.CanPickBoneHearts()) break; + if (isFool) isPickedUp = foolHeart(2); + else + { + player.AddBoneHearts(1); + player.AddImmaculateConceptionCounter(2); + isPickedUp = true; + } + break; + case HEART_ROTTEN: + if (player.playerType == PLAYER_BETHANY_B && player.CanPickRedHearts()) + { + player.AddHearts(std::min(1, BLOOD_CHARGE_CAP - player.effectiveBloodCharge), false, false); + return true; + } + spiders = 3; + if (isRefused || !player.CanPickRottenHearts()) break; + if (isFool) isPickedUp = foolHeart(2); + else + { + player.AddRottenHearts(2, false); + player.AddImmaculateConceptionCounter(2); + isPickedUp = true; + } + break; + default: + break; + } + if (isSodom && !isPickedUp) apple_of_sodom_burst(*this, player, spiders); + return isPickedUp; +} + +// A coin into the player's coins (April Fool's gifts instead), the penny trinkets' effects +// (entity_player_trinkets.cpp), and a lucky penny's luck with its name shown. void Entity_Pickup::coin_collect(Entity_Player& player) { - if (g_game->challenge == CHALLENGE_APRILS_FOOL) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Bloody Mary's coins"); - player.AddCoins(GetCoinValue()); - coin_trinkets_collect(*this, player, GetCoinValue()); + int value = GetCoinValue(); + if (g_game->challenge == CHALLENGE_APRILS_FOOL) fool_coin_give(*this, player, value); + else player.AddCoins(value); + coin_trinkets_collect(*this, player, value); if (subtype != COIN_LUCKYPENNY) return; StringTable& strings = g_manager->stringTable; @@ -1928,51 +2468,62 @@ void Entity_Pickup::coin_collect(Entity_Player& player) player.AnimateHappy(); } -// A key into the player's keys: one, two from a key ring, or a golden key. Whether it was taken. -// A charged key's charge is not reconstructed yet. +// A key into the player's keys: one, two from a key ring, a golden key (April Fool's gifts instead), or a charged +// key with charge for the first active that takes it. Whether it was taken. bool Entity_Pickup::key_collect(Entity_Player& player) { - if (g_game->challenge == CHALLENGE_APRILS_FOOL) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Bloody Mary's keys"); + constexpr int CHARGED_KEY_CHARGE = 6; + bool isFool = g_game->challenge == CHALLENGE_APRILS_FOOL; switch (subtype) { case KEY_NORMAL: - player.AddKeys(1); - return true; case KEY_DOUBLEPACK: - player.AddKeys(2); + { + int amount = subtype == KEY_DOUBLEPACK ? 2 : 1; + if (isFool) fool_give(player, fool_draw(*this, FOOL_KEY_GIFTS), amount); + else player.AddKeys(amount); return true; + } case KEY_GOLDEN: - player.AddGoldenKey(); + if (isFool) fool_give(player, fool_draw(*this, FOOL_GOLDEN_KEY_GIFTS), 1); + else player.AddGoldenKey(); return true; case KEY_CHARGED: - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a charged key"); + player.AddKeys(1); + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + if (player.AddActiveCharge(CHARGED_KEY_CHARGE, slot, true, false, false) != 0) break; + return true; default: return false; } } -// A bomb into the player's bombs: one, two, a golden bomb or a giga bomb with its bomb. Whether it was taken. +// A bomb into the player's bombs: one, two, a golden bomb or a giga bomb with its bomb (April Fool's gifts instead). +// Whether it was taken. bool Entity_Pickup::bomb_collect(Entity_Player& player) { - if (g_game->challenge == CHALLENGE_APRILS_FOOL) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Bloody Mary's bombs"); + bool isFool = g_game->challenge == CHALLENGE_APRILS_FOOL; switch (subtype) { - case BOMB_NORMAL: - player.AddBombs(1); + case BOMB_SUBTYPE_NORMAL: + case BOMB_SUBTYPE_DOUBLEPACK: + { + int amount = subtype == BOMB_SUBTYPE_DOUBLEPACK ? 2 : 1; + if (isFool) fool_give(player, fool_draw(*this, FOOL_BOMB_GIFTS), amount); + else player.AddBombs(amount); return true; - case BOMB_DOUBLEPACK: - player.AddBombs(2); - return true; - case BOMB_GOLDEN: - player.AddGoldenBomb(); - return true; - case BOMB_GIGA: - player.AddBombs(1); - player.AddGigaBombs(1); + } + case BOMB_SUBTYPE_GOLDEN: + case BOMB_SUBTYPE_GIGA: + if (isFool) fool_give(player, fool_draw(*this, FOOL_GOLDEN_BOMB_GIFTS), 1); + else if (subtype == BOMB_SUBTYPE_GOLDEN) player.AddGoldenBomb(); + else + { + player.AddBombs(1); + player.AddGigaBombs(1); + } return true; default: return false; @@ -1999,7 +2550,7 @@ void Entity_Pickup::PlayDropSound() sound = SOUND_KEY_DROP0; break; case PICKUP_BOMB: - sound = subtype == BOMB_GOLDEN ? SOUND_GOLD_HEART_DROP : SOUND_FETUS_LAND; + sound = subtype == BOMB_SUBTYPE_GOLDEN ? SOUND_GOLD_HEART_DROP : SOUND_FETUS_LAND; break; case PICKUP_PILL: sound = (subtype & PILL_COLOR_MASK) == PILL_COLOR_GOLD ? SOUND_GOLD_HEART_DROP : SOUND_FETUS_JUMP; @@ -2056,7 +2607,7 @@ void Entity_Pickup::PlayPickupSound() return pickup_sound_play(SOUND_KEYPICKUP_GAUNTLET, {KEY_PICKUP_VOLUME}); break; case PICKUP_BOMB: - sound = subtype == BOMB_GOLDEN ? SOUND_GOLDENBOMB : SOUND_FETUS_FEET; + sound = subtype == BOMB_SUBTYPE_GOLDEN ? SOUND_GOLDENBOMB : SOUND_FETUS_FEET; break; case PICKUP_PILL: case PICKUP_TRINKET: @@ -2119,7 +2670,7 @@ bool Entity_Pickup::CanRerollVariant(int pickupVariant, int pickupSubType) if (pickupSubType == COLLECTIBLE_DADS_NOTE) return false; if (g_game->seedEffects.HasSeedEffect(SEED_G_FUEL) && pickupSubType == -1) return false; - bool isChallenge = g_game->challenge != 0 || g_game->dailyChallenge._id != 0; + bool isChallenge = g_game->challenge != 0 || g_game->dailyChallenge.id != 0; PathType path = isChallenge ? g_game->GetChallengeParams().pathType : PATH_TYPE_SHEOL; bool isKnifePiece = pickupSubType == COLLECTIBLE_KNIFE_PIECE_1 || pickupSubType == COLLECTIBLE_KNIFE_PIECE_2; bool isPhoto = pickupSubType == COLLECTIBLE_THE_POLAROID || pickupSubType == COLLECTIBLE_THE_NEGATIVE; @@ -2197,8 +2748,6 @@ bool Entity_Pickup::IsChest(int pickupVariant) return std::find(CHESTS.begin(), CHESTS.end(), pickupVariant) != CHESTS.end(); } -// The rest of Entity_Pickup is not reconstructed yet. - // 006edda0 An explosion or a crush hitting a pickup: it opens a stone chest (any chest with Broken Padlock, which in a // versus match only counts for the hitting player), the mega chest losing a lock first, and a chest blown in a // challenge room starts its ambush. A sticky nickel comes loose. A pickup never counts as damaged. @@ -2245,12 +2794,6 @@ bool Entity_Pickup::TakeDamage(float damage, uint64_t damageFlags, const EntityR return false; } -// 005832c0 -void Entity_Pickup::GetLootList(const Vector&) -{ - reconstruction_missing("Entity_Pickup::GetLootList 005832c0"); -} - // 006e1e60 Hides or shows a collectible as a question mark, redrawing an item whose state changed. void Entity_Pickup::SetForceBlind(uint8_t setBlind) { diff --git a/src/entity_pickup.h b/src/entity_pickup.h index 105e2ca..4dcdacd 100644 --- a/src/entity_pickup.h +++ b/src/entity_pickup.h @@ -118,9 +118,36 @@ enum KeySubType : int KEY_CHARGED }; +// A bomb's subtypes (Lua's BombSubType). +enum BombSubType : int +{ + BOMB_SUBTYPE_NORMAL = 1, + BOMB_SUBTYPE_DOUBLEPACK, + BOMB_SUBTYPE_TROLL, + BOMB_SUBTYPE_GOLDEN, + BOMB_SUBTYPE_SUPERTROLL, + BOMB_SUBTYPE_GOLDENTROLL, + BOMB_SUBTYPE_GIGA +}; + // 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 small, sickly blood splat of a rotten heart and a Rotten Beggar. +constexpr ColorMod ROTTEN_SPLAT_COLOR = {{0.7f, 0.9f, 0.65f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float ROTTEN_SPLAT_MIN = 0.2f; +constexpr float ROTTEN_SPLAT_RANGE = 0.4f; + +// The sprite subtype every Cantripped card shows. +constexpr int ITEM_CARD_SPRITE_SUBTYPE = 16; + +// Whether a G FUEL! burst greets a pickup appearing or an item pedestal, which order their effects differently. +enum GfuelAppear +{ + GFUEL_APPEAR_PICKUP, + GFUEL_APPEAR_PEDESTAL +}; + // 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; @@ -185,7 +212,6 @@ struct Entity_Pickup : Entity bool TryThrow(const EntityRef& source, const Vector& direction, float force) override; bool HandleCollision(Entity* collider, bool isLow) override; - void GetLootList(const Vector& renderOffset); bool IsShopItem(); static Vector GetRandomPickupVelocity(const Vector& position, RNG* rng, uint32_t ePickupVelType); bool TryFlip(Entity_Player* unusedPlayer, uint32_t unusedSeed); @@ -197,6 +223,7 @@ struct Entity_Pickup : Entity void Morph(int entityType, int entityVariant, int entitySubType, bool isKeepPrice, bool isKeepSeed, bool isIgnoreModifiers); void update_price_sprite(int newPrice); + int sacrifice_item_pick(); void AppearFast(); bool TryOpenChest(Entity_Player* player); LootList GetChestLoot(PoolDraw draw, Entity_Player* player); @@ -207,6 +234,7 @@ struct Entity_Pickup : Entity void TriggerShopPurchase(Entity_Player& player, int spentMoney); uint8_t empty_pedestal(); void update_magnet_attraction(); + void mag_baby_pull(); void update_cycle_collectible(bool isForce); bool CanReroll(); static bool CanRerollVariant(int variant, int subType); @@ -222,6 +250,7 @@ private: void appear_start(); bool keeper_flies_update(); void target_position_update(); + void door_push(); void appear_update(); bool heart_collect(Entity_Player& player); void coin_collect(Entity_Player& player); @@ -236,14 +265,15 @@ private: void chest_loot_spawn(const LootList& loot, Entity_Player& player, int chestVariant); // The shop's parts of Init, Update, update_price_sprite and HandleCollision (entity_pickup_shop.cpp). - void shop_ware_choose(PickupChoice& choice, uint32_t seed); + void shop_ware_choose(PickupChoice& choice, RNG& rng); + void shop_price_assign(); void price_sprite_load(); void price_refresh(); void other_deals_take(); void purchase_finish(Entity_Player& player, int paidPrice); // The item pedestal's parts of Init, Update, Render, HandleCollision and PlayPickupSound (item_pickup.cpp). - void collectible_choose(int& collectibleId, uint32_t seed); + void collectible_choose(int& collectibleId, RNG& rng); void pedestal_start(); void pedestal_update(); void pedestal_render(const Vector& offset); @@ -255,4 +285,5 @@ private: bool pickup_variant_pick(PickupChoice& choice); void collectible_subtype_pick(PickupChoice& choice, RNG& rng); +void gfuel_appear_spawn(const Vector& position, GfuelAppear appear); bool entity_type_is_saved(int type, int variant, uint32_t subType, int spawnerType, bool isRoomEntry); diff --git a/src/entity_pickup_chest.cpp b/src/entity_pickup_chest.cpp index 3309c16..bdcd051 100644 --- a/src/entity_pickup_chest.cpp +++ b/src/entity_pickup_chest.cpp @@ -49,7 +49,6 @@ constexpr int CHEST_COINS_ROLL = 3; constexpr int MEGA_CHEST_DRAWS = 5; constexpr size_t WOODEN_CHEST_TRINKETS = 2; constexpr int CHEST_TRINKET_ODDS = 100; -constexpr int LUCKY_TOE_ODDS = 3; // The pickups a chest's own draw gives (the outcome ids of GetChestLoot's first draw). enum ChestOutcome @@ -177,7 +176,6 @@ constexpr int LEFT_HAND_NO_SPIDERS = 3; constexpr int FAMILIAR_BLUE_FLY = 43; constexpr int FAMILIAR_BLUE_SPIDER = 73; constexpr int RED_CHEST_TELEPORT = 1; -constexpr int RED_CHEST_BOMB_SUBTYPE = 3; constexpr float RED_CHEST_SPIDER_STEP = 70; constexpr float RED_CHEST_SPIDER_HEIGHT = -30; constexpr uint32_t POKER_QUALITY_BANS = 0x1f0; @@ -534,8 +532,8 @@ static void red_chest_loot_draw(ChestDraw& draw, bool isChestFloor) break; } case RED_OUTCOME_BOMBS: - loot_add(draw, PICKUP_BOMB, RED_CHEST_BOMB_SUBTYPE); - loot_add(draw, PICKUP_BOMB, RED_CHEST_BOMB_SUBTYPE); + loot_add(draw, PICKUP_BOMB, BOMB_SUBTYPE_TROLL); + loot_add(draw, PICKUP_BOMB, BOMB_SUBTYPE_TROLL); break; case RED_OUTCOME_PILLS: loot_add(draw, PICKUP_PILL); @@ -575,7 +573,7 @@ static void sack_loot_draw(ChestDraw& draw, int subtype) static void moms_chest_loot_draw(ChestDraw& draw) { bool isLocked = !g_manager->persistentGameData.achievements[ACHIEVEMENT_RED_KEY] && - (g_manager->state != MANAGER_STATE_GAME || (g_game->dailyChallenge._id == 0 && !g_game->isDebug)); + (g_manager->state != MANAGER_STATE_GAME || (g_game->dailyChallenge.id == 0 && !g_game->isDebug)); if (!isLocked) return loot_item_add(draw, POOL_MOMS_CHEST); uint32_t seed = draw.rng->Next(); diff --git a/src/entity_pickup_morph.cpp b/src/entity_pickup_morph.cpp index caca21d..574fc7c 100644 --- a/src/entity_pickup_morph.cpp +++ b/src/entity_pickup_morph.cpp @@ -3,6 +3,10 @@ #include "game.h" #include "log.h" #include "manager.h" +#include "room_special.h" +#include +#include +#include constexpr int MORPH_RNG_SHIFT = 7; @@ -29,10 +33,28 @@ struct MorphKept bool isUnknown52d = false; }; +// A devil deal's sacrifice item turned into something else stays a sacrifice item: another of the tagged items, not +// one its pedestal cycles through, drawn from its seed. With none tagged it keeps its item. +// The original draws forever when every tagged item is refused. Here it stops after a draw per item and keeps its own. +int Entity_Pickup::sacrifice_item_pick() +{ + std::vector& items = g_manager->itemConfig.GetTaggedItems(TAG_DEVIL_SACRIFICE); + RNG rng = rng_make(initSeed, DEFAULT_SHIFT_INDEX); + auto cycle = std::span(cycleCollectibleList).first(cycleCollectibleCount); + + for (size_t attempt = 0; attempt < items.size(); attempt++) + { + int pick = items[rng.Next() % items.size()]->id; + if (pick != subtype && std::ranges::count(cycle, (uint32_t)pick) == 0) return pick; + } + return subtype; +} + // 006e30a0 Turns a pickup into another in place (Lua's EntityPickup:Morph): a new seed unless kept, its place, links, // index, flags and timers kept, its price kept or dropped, an active's initial charge, and its pedestal. Entities -// pointing at it forget it. The deathmatch's swaps, a devil deal keeping its sacrifice item, a priced shop item's -// reroll and a Mega Chest's halves are not written yet. Flip's other item stays while the pickup keeps its kind. +// pointing at it forget it. A devil deal keeps a sacrifice item, a priced item rerolled to nothing gets a new ware of +// its shop slot at its price, a Mega Chest's halves stay paired, and Flip's other item stays while the pickup keeps its +// kind. void Entity_Pickup::Morph(int entityType, int entityVariant, int entitySubType, bool isKeepPrice, bool isKeepSeed, bool isIgnoreModifiers) { @@ -43,8 +65,7 @@ void Entity_Pickup::Morph(int entityType, int entityVariant, int entitySubType, } if (g_game->deathmatchManager.is_active()) reconstruction_missing("Entity_Pickup::Morph 006e30a0 (the deathmatch's blacklist)"); - if (megaChestCollectible[0] || megaChestCollectible[1]) - reconstruction_missing("Entity_Pickup::Morph 006e30a0 (a Mega Chest's halves)"); + std::array megaPair = megaChestCollectible; std::shared_ptr flipOther = flipSaveState; MorphKept saved = {.child = child, @@ -70,11 +91,21 @@ void Entity_Pickup::Morph(int entityType, int entityVariant, int entitySubType, if (itemPoolType == POOL_DEVIL && price == 0 && ItemConfig::is_collectible_tagged(subtype, TAG_DEVIL_SACRIFICE) && !ItemConfig::is_collectible_tagged(entitySubType, TAG_DEVIL_SACRIFICE)) - reconstruction_missing("Entity_Pickup::Morph 006e30a0 (a devil deal keeping its sacrifice item)"); + entitySubType = sacrifice_item_pick(); int newPrice = isKeepPrice ? price : 0; if (price != 0 && isKeepPrice && entitySubType == 0) - reconstruction_missing("Entity_Pickup::Morph 006e30a0 (a priced shop item's reroll)"); - Init(entityType, entityVariant, entitySubType, initSeed); + { + Room& room = *g_game->room; + RNG rng = rng_make(initSeed, DEFAULT_SHIFT_INDEX); + ShopOffer offer = {.shopItemId = shopItemId, .variant = entityVariant}; + offer.seed = rng.Next(); + if (shopItemId >= 0) shop_offer_pick(room, offer); + entityVariant = offer.variant; + entitySubType = offer.subType; + newPrice = room_shop_discount(room, shopItemId, room_shop_item_price(room, offer, nullptr), nullptr); + Init(entityType, entityVariant, entitySubType, rng.Next()); + } + else Init(entityType, entityVariant, entitySubType, initSeed); itemPoolType = saved.itemPoolType; g_pickupIgnoreModifiers = savedIgnoreModifiers; @@ -111,5 +142,15 @@ void Entity_Pickup::Morph(int entityType, int entityVariant, int entitySubType, if (variant == PICKUP_COLLECTIBLE && subtype != 0 && isBlindChanged) UpdateSprite(false); for (EntityPtr* referrer : referrers) referrer->forget(); referrers.clear(); + if (auto* second = static_cast(megaPair[1].get())) + { + megaChestCollectible[1] = second; + second->megaChestCollectible[0] = this; + } + if (auto* first = static_cast(megaPair[0].get())) + { + megaChestCollectible[0] = first; + first->megaChestCollectible[1] = this; + } if (flipOther && flipOther->type == type && flipOther->variant == variant) flipSaveState = flipOther; } diff --git a/src/entity_pickup_shop.cpp b/src/entity_pickup_shop.cpp index d037a69..5868cb7 100644 --- a/src/entity_pickup_shop.cpp +++ b/src/entity_pickup_shop.cpp @@ -60,10 +60,9 @@ constexpr std::array HEART_COSTS = { // The ware a shop slot sells, the Init part of 006e02f0: the room rolls the slot's ware and price from the pickup's // seed, the pick's modifiers may change it (pricing it again), and a devil treasure room's crawlspace ware stands // higher. -void Entity_Pickup::shop_ware_choose(PickupChoice& choice, uint32_t seed) +void Entity_Pickup::shop_ware_choose(PickupChoice& choice, RNG& rng) { Room& room = *g_game->room; - RNG rng = {seed, 5, 9, 7}; ShopOffer offer = {.seed = rng.Next()}; shopItemId = room_shop_ware_roll(room, offer); @@ -82,6 +81,16 @@ void Entity_Pickup::shop_ware_choose(PickupChoice& choice, uint32_t seed) if (isRaised) pos.y -= DEVIL_TREASURE_RAISE; } +// The price the shop would ask for the pickup as it is, outside the shop's wares (Tainted Keeper's pedestals and the +// seed that sells every pickup). +void Entity_Pickup::shop_price_assign() +{ + Room& room = *g_game->room; + shopItemId = -1; + ShopOffer offer = {.shopItemId = shopItemId, .subType = subtype, .variant = variant}; + price = room_shop_discount(room, shopItemId, room_shop_item_price(room, offer, nullptr), nullptr); +} + // A price on its sprite: hearts by frame, spikes as a spike effect under the ware, free as a struck price, coins as // two digits and the coin, red while discounted. void Entity_Pickup::price_sprite_load() diff --git a/src/entity_player.cpp b/src/entity_player.cpp index 00d01d7..989dbd8 100644 --- a/src/entity_player.cpp +++ b/src/entity_player.cpp @@ -20,6 +20,7 @@ #include "room.h" #include "room_grid.h" #include +#include #include constexpr float PLAYER_START_TEAR_HEIGHT = -23.75f; @@ -51,20 +52,15 @@ constexpr uint32_t PILL_RNG_SHIFT = 8; constexpr uint32_t CARD_RNG_SHIFT = 9; constexpr uint32_t PRE_LEVEL_RNG_SHIFT = 2; constexpr uint32_t FLOOR_RNG_SHIFT = 12; -constexpr uint32_t JACOBS_CURSE_RNG_SHIFT = 66; -constexpr int JACOBS_CURSE_STEPS = 20; constexpr int REDEMPTION_LIGHT_FADE = 2; constexpr int NECROMANCER_OVERLAY_DELAY = 3; // The step from a door slot (left, up, right, down) into the room. constexpr float ASCENT_DOOR_STEPS[][2] = {{40, 0}, {0, 40}, {-40, 0}, {0, -40}}; -constexpr int JACOBS_CURSE_STEP_FRAMES = 30; -constexpr int JACOBS_CURSE_MIN_FRAMES = 610; constexpr int ASCENT_HOME_STAGE = 6; constexpr int CAINS_EYE_CHANCE = 25; constexpr int CANTRIPPED_CARDS = 3; constexpr int CARD_START_RUNE_CHANCE = 10; -constexpr int COLOR_PRIORITY_TOP = 255; constexpr int DAILY_CHRISTMAS = 19; constexpr int EMPTY_HEART_RED_HEARTS = 3; constexpr int EVENT_BONUS_ITEMS = 114; @@ -128,7 +124,7 @@ bool is_run_unlocked(int achievement) Game* game = g_game; if (g_manager->persistentGameData.achievements[achievement]) return true; - return g_manager->state == MANAGER_STATE_GAME && game && (game->dailyChallenge._id != 0 || game->isDebug); + return g_manager->state == MANAGER_STATE_GAME && game && (game->dailyChallenge.id != 0 || game->isDebug); } // Fills a list of item generators, one per id, each seeded by the next step of a generator of its own. @@ -820,7 +816,7 @@ void Entity_Player::InitPostLevelInitStats() isPostLevelInitFinished = true; return; } - if (game.dailyChallenge._specialDailyId != 0) + if (game.dailyChallenge.specialDailyId != 0) reconstruction_missing("Entity_Player::InitPostLevelInitStats 007bc740 (a daily's special start)"); if (playerConfig->card > 0) AddPocketItem(playerConfig->card, POCKET_CARD); @@ -872,7 +868,7 @@ void Entity_Player::InitPostLevelInitStats() starting_collectible_add(COLLECTIBLE_KEY_PIECE_1); starting_collectible_add(COLLECTIBLE_KEY_PIECE_2); } - if (game.challenge == 0 && game.dailyChallenge._id == 0) + if (game.challenge == 0 && game.dailyChallenge.id == 0) { if (startFrame == 0) bonus_items_roll(rng); } @@ -931,16 +927,16 @@ void Entity_Player::companions_init() ->Update(); break; case PLAYER_JACOB_B: - if (game.challenge != CHALLENGE_RED_REDEMPTION) jacobs_curse_add(); + if (game.challenge != CHALLENGE_RED_REDEMPTION) jacobs_curse_add(JACOBS_CURSE_FLOOR); break; default: break; } } -// Starts the countdown to Dark Esau's next charge on Tainted Jacob: 20 to 600 seconds after 610 frames, drawn from the -// devil room generator. -void Entity_Player::jacobs_curse_add() +// Starts the countdown to Dark Esau's next charge on Tainted Jacob, a number of second-steps after the delay's least, +// drawn from the devil room generator without advancing it. +void Entity_Player::jacobs_curse_add(const JacobsCurseDelay& delay) { temporaryEffects.RemoveNullEffect(NULLITEM_JACOBS_CURSE, -1); ItemConfig_Item* item = g_manager->itemConfig.GetNullItem(NULLITEM_JACOBS_CURSE); @@ -948,7 +944,7 @@ void Entity_Player::jacobs_curse_add() RNG rng = rng_make(g_game->devilAngelRoomRNG._seed, JACOBS_CURSE_RNG_SHIFT); TemporaryEffect effect(item); - effect.cooldown = (int)(rng.Next() % JACOBS_CURSE_STEPS) * JACOBS_CURSE_STEP_FRAMES + JACOBS_CURSE_MIN_FRAMES; + effect.cooldown = (int)(rng.Next() % delay.steps) * JACOBS_CURSE_STEP_FRAMES + delay.minFrames; temporaryEffects.AddEffect(effect, true, 1); } @@ -999,6 +995,37 @@ void Entity_Player::start_position_set() pos = PlayerManager::get_player_start_position(this, vector_make(START_SPOT_X, startY)); } +// 007e7820 Whether a walk through the room's grid paths leads from one spot to another (not onto a solid cell), no +// longer than half the room's cells, stepping left, up, right and down. +static bool pathfinder_can_reach_pos(const Vector& target, const Vector& start) +{ + Room& room = *g_game->room; + int targetIndex = room.GetGridIndex(target); + if (targetIndex >= 0 && targetIndex < ROOM_GRID_CELLS && room.gridPaths[targetIndex] == GRID_PATH_SOLID) return false; + + auto cell = [&room](int column, int row) { return room.GetGridIndexByTile(column, row); }; + std::array paths = room.gridPaths; + std::deque> open = {{room.GetGridIndex(start), 0}}; + int depthLimit = room.gridHeight * room.gridWidth / 2; + while (!open.empty()) + { + auto [index, depth] = open.front(); + if (depth >= depthLimit) return false; + open.pop_front(); + + int column = index % room.gridWidth; + int row = index / room.gridWidth; + for (int next : {cell(column - 1, row), cell(column, row - 1), cell(column + 1, row), cell(column, row + 1)}) + { + if (next < 0 || paths[next] < 0 || paths[next] >= GRID_PATH_IMPASSABLE) continue; + paths[next] = -(depth + 1); + if (next == targetIndex) return true; + open.push_back({next, depth + 1}); + } + } + return false; +} + // The Ascent starts the player a cell inside a door: the room's first, or from a random slot the next one its shape // allows. A trapdoor reachable from there takes the start instead. void Entity_Player::ascent_start_set() @@ -1022,7 +1049,7 @@ void Entity_Player::ascent_start_set() GridEntity* grid = room.gridEntities[cell]; if (!grid || grid->type != GRID_TRAPDOOR) continue; Vector trapdoor = room.GetGridPosition(grid->gridIndex); - if (!pathfinder_can_reach_pos(&trapdoor, &start, &room)) continue; + if (!pathfinder_can_reach_pos(trapdoor, start)) continue; pos = trapdoor; return; } @@ -1048,7 +1075,7 @@ void Entity_Player::level_items_apply(bool isForced) temporaryEffects.RemoveNullEffect(NULLITEM_JUDAS_BIRTHRIGHT_STAGE, 1); if (playerType == PLAYER_JACOB2_B) ChangePlayerType(PLAYER_JACOB_B, false); else if (playerType == PLAYER_LAZARUS2) ChangePlayerType(PLAYER_LAZARUS, false); - if (playerType == PLAYER_JACOB_B && game.challenge != CHALLENGE_RED_REDEMPTION) jacobs_curse_add(); + if (playerType == PLAYER_JACOB_B && game.challenge != CHALLENGE_RED_REDEMPTION) jacobs_curse_add(JACOBS_CURSE_FLOOR); if (HasCollectible(COLLECTIBLE_EMPTY_HEART)) for (Entity_Player* player : {this, subPlayer}) @@ -1319,7 +1346,7 @@ void Entity_Player::spawn_low_health_blood_splat() splat->sprite.rotation = (float)(Random() & 3) * 90; splat->sprite.isFlipX = !(Random() & 1); if (!HasCollectible(COLLECTIBLE_KIDNEY_STONE) && playerType != PLAYER_EVE && playerType != PLAYER_EVE_B) - splat->SetColor(color_from_bytes(0, 0, 0, PEE_ALPHA, PEE_OFFSET, PEE_OFFSET, 0), -1, COLOR_PRIORITY_TOP, false, + splat->SetColor(color_from_bytes(0, 0, 0, PEE_ALPHA, PEE_OFFSET, PEE_OFFSET, 0), -1, COLOR_PRIORITY_DEFAULT, false, true); splat->Update(); } @@ -1462,7 +1489,7 @@ void Entity_Player::update_player_skin() bool isBombForm = playerType == PLAYER_THEFORGOTTEN_B || playerType == PLAYER_THESOUL_B; if (variant == PLAYER_VARIANT_PLAYER && !game.GetChallengeParams().isCanShoot && !isBombForm) AddCostume(items.GetNullItem(NULLITEM_BLINDFOLD), false); - if (game.seedEffects.HasSeedEffect(SEED_CHRISTMAS) || game.dailyChallenge._specialDailyId == DAILY_CHRISTMAS) + if (game.seedEffects.HasSeedEffect(SEED_CHRISTMAS) || game.dailyChallenge.specialDailyId == DAILY_CHRISTMAS) AddCostume(items.GetNullItem(NULLITEM_CHRISTMAS), false); if (game.challenge == CHALLENGE_HOT_POTATO && playerType == PLAYER_THEFORGOTTEN_B) AddCostume(items.GetNullItem(NULLITEM_FORGOTTEN_BOMB), false); diff --git a/src/entity_player.h b/src/entity_player.h index f0d8d6b..cc37400 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -38,8 +38,24 @@ 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; +// Daemon's Tail lets a heart drop only one time in this many. +constexpr int DAEMONS_TAIL_HEART_ODDS = 5; +// Lucky Toe adds a drop two times in three. +constexpr uint32_t LUCKY_TOE_ODDS = 3; constexpr uint32_t CARD_ITEM_FLAG = 0x8000; constexpr int DEAD_CAT_LIVES = 9; + +// Tainted Jacob's curse: its generator's shift, and the delays before Dark Esau charges, after a floor starts and +// after becoming Tainted Jacob, in steps of a second after a least. +struct JacobsCurseDelay +{ + int minFrames = 0; + int steps = 0; +}; +constexpr uint32_t JACOBS_CURSE_RNG_SHIFT = 66; +constexpr int JACOBS_CURSE_STEP_FRAMES = 30; +constexpr JacobsCurseDelay JACOBS_CURSE_FLOOR = {610, 20}; +constexpr JacobsCurseDelay JACOBS_CURSE_CHANGE = {100, 3}; constexpr uint8_t WILD_CARD_NONE = 0xff; constexpr uint8_t WILD_CARD_PILL = 0; constexpr uint8_t WILD_CARD_CARD = 1; @@ -142,11 +158,16 @@ enum BabySubType : int BABY_PSY = 4, BABY_YBAB = 7, BABY_SHADOW = 13, + BABY_MAG = 18, BABY_BEGOTTEN = 21, BABY_DEAD = 22, BABY_FIGHTING = 23, BABY_GLITCH = 25, BABY_MAGNET = 26, + BABY_BLACK = 27, + BABY_RED = 28, + BABY_WHITE = 29, + BABY_BLUE = 30, BABY_SUPER_GREED = 54, BABY_APOLLYON = 56, BABY_BONE = 57, @@ -248,6 +269,7 @@ enum Direction : int // The head animations the player turns to, by direction. constexpr std::string_view PLAYER_HEAD_ANIMS[] = {"HeadLeft", "HeadUp", "HeadRight", "HeadDown"}; +constexpr std::string_view HEAD_SHOOT_ANIMS[] = {"HeadLeftShoot", "HeadUpShoot", "HeadRightShoot", "HeadDownShoot"}; // The layers of the player's sprite, in the order its .anm2 lists them: the glow, the body, the head and the top // layers costumes can cover. @@ -340,6 +362,12 @@ enum PlayerItemId : int COLLECTIBLE_BOOK_OF_BELIAL = 34, COLLECTIBLE_NECRONOMICON = 35, COLLECTIBLE_POOP = 36, + COLLECTIBLE_HEART = 15, + COLLECTIBLE_COMMON_COLD = 103, + COLLECTIBLE_BUTT_BOMBS = 209, + COLLECTIBLE_DEAD_TOOTH = 446, + COLLECTIBLE_COMPOUND_FRACTURE = 453, + COLLECTIBLE_SINUS_INFECTION = 459, COLLECTIBLE_TELEPORT = 44, COLLECTIBLE_YUM_HEART = 45, COLLECTIBLE_LUCKY_FOOT = 46, @@ -507,6 +535,7 @@ enum PlayerItemId : int COLLECTIBLE_TELEPORT_2 = 419, COLLECTIBLE_BLACK_POWDER = 420, COLLECTIBLE_GLOWING_HOUR_GLASS = 422, + COLLECTIBLE_CIRCLE_OF_PROTECTION = 423, COLLECTIBLE_NIGHT_LIGHT = 425, COLLECTIBLE_HEAD_OF_THE_KEEPER = 429, COLLECTIBLE_TAROT_CLOTH = 451, @@ -634,6 +663,7 @@ enum PlayerItemId : int COLLECTIBLE_HEARTBREAK = 694, COLLECTIBLE_BLOODY_GUST = 695, COLLECTIBLE_SALVATION = 696, + COLLECTIBLE_VANISHING_TWIN = 697, COLLECTIBLE_TWISTED_PAIR = 698, COLLECTIBLE_VENGEFUL_SPIRIT = 702, COLLECTIBLE_HYPERCOAGULATION = 724, @@ -992,6 +1022,8 @@ enum PlayerItemId : int COLLECTIBLE_LEO = 302, COLLECTIBLE_D1 = 476, COLLECTIBLE_BELT = 28, + COLLECTIBLE_MOMS_UNDERWEAR = 29, + COLLECTIBLE_MOMS_HEELS = 30, COLLECTIBLE_BLUE_CAP = 342, COLLECTIBLE_MR_BOOM = 37, COLLECTIBLE_TAMMYS_HEAD = 38, @@ -1027,6 +1059,7 @@ enum PlayerItemId : int COLLECTIBLE_QUARTER = 74, COLLECTIBLE_GHOST_BABY = 163, COLLECTIBLE_HIVE_MIND = 248, + COLLECTIBLE_THERES_OPTIONS = 249, COLLECTIBLE_DRY_BABY = 265, COLLECTIBLE_EYE_OF_GREED = 450, COLLECTIBLE_GHOST_PEPPER = 495, @@ -1427,9 +1460,11 @@ public: std::array trinkets{}; uint32_t grantedCollectibleFlags = 0; uint32_t playerFormsRewarded = 0; + uint32_t previewTrinket = 0; int grantedCollectibleCountdown = 0; int metronomeCollectibleId = 0; int modelingClayEffect = 0; + int previewCollectible = 0; int threeDollarBillItem = 0; std::array activeItems{}; @@ -1509,7 +1544,7 @@ public: std::shared_ptr unlistedRestoreState; std::shared_ptr playerHUD; - std::vector contactHitList; + std::vector contactHitList; std::vector darkArtsHitList; std::vector curseMistFamiliars; std::vector pendingWisps; @@ -1559,6 +1594,7 @@ public: bool hasBabyRoomShield = false; bool hasCurseMistEffect = false; bool isCoopGhost = false; + bool isPreviewAdded = true; bool isGlitchBaby = false; bool isHeldEntityVisible = false; @@ -1817,7 +1853,7 @@ private: void starting_collectible_add(int id); void starting_trinket_add(int id); void companions_init(); - void jacobs_curse_add(); + void jacobs_curse_add(const JacobsCurseDelay& delay); void start_position_set(); void ascent_start_set(); void level_items_apply(bool isForced); diff --git a/src/entity_player_actives.cpp b/src/entity_player_actives.cpp index c2ae1ad..18fc1f6 100644 --- a/src/entity_player_actives.cpp +++ b/src/entity_player_actives.cpp @@ -1,4 +1,6 @@ #include "entity_player.h" +#include "entity_knife.h" +#include "entity_laser.h" #include "entity_player_characters.h" #include "entity_player_crafting.h" #include "entity_player_trinkets.h" @@ -28,6 +30,7 @@ #include "npc_basement.h" #include "npc_fireplace.h" #include "room.h" +#include "room_state.h" #include "room_special.h" #include "tainted_characters.h" #include @@ -47,8 +50,6 @@ constexpr int CHARGE_FLASH_MAX = 12; constexpr int EVENT_BATTERIES_COLLECTED = 195; constexpr int GLOWING_HOUR_GLASS_LIT_USES = 3; constexpr float THE_POOP_FART_RADIUS = 120; -constexpr int INPUT_HOOK_PRESSED = 0; -constexpr int INPUT_HOOK_TRIGGERED = 1; constexpr int INPUT_RAW_ACTION = 33; constexpr int MECONIUM_CHANCES[] = {33, 66, 100}; constexpr int MIDAS_POOP_CHANCE = 34; @@ -84,6 +85,15 @@ constexpr float SPIDER_BUTT_SLOW = 0.9f; constexpr float TAMMY_TEAR_DAMAGE = 25; constexpr float TAMMY_TEAR_SCALE = 1.355f; constexpr float TAMMY_TEAR_SPEED = 10; +// Tammy's Head's other rings: a beam's bonus per scale (and Mega Blast's beams: how high, how long, their damage +// scale and the shake), a bomb's, and the step between knives. +constexpr float TAMMY_BEAM_DAMAGE = 3.5f; +constexpr float TAMMY_BEAM_RISE = -30; +constexpr int TAMMY_BEAM_TIMEOUT = 30; +constexpr float TAMMY_BEAM_DAMAGE_SCALE = 5; +constexpr int TAMMY_BEAM_SHAKE = 15; +constexpr float TAMMY_BOMB_DAMAGE = 35; +constexpr float TAMMY_KNIFE_STEP = 36; constexpr int METRONOME_TRIES = 15; constexpr uint32_t METRONOME_RNG_SHIFT = 15; constexpr int METRONOME_EXCLUDED[] = {488, 475, 422, 326, 482, 636, 640}; @@ -830,18 +840,103 @@ static void poop_use(ItemUse& use) player.ShootCandle(Vector{}); } -// Tammy's Head: a ring of ten tears turned at random, bigger and with bonus damage a data value scales in percent. -// The rings of the other weapons are not written yet. +// One shot of Tammy's Head's ring: its direction, the bonus damage's scale, the ring's turn and the shot's place in it. +struct TammyShot +{ + Vector direction{}; + float scale = 1; + float turn = 0; + int index = 0; +}; + +// Tammy's Head with Mega Blast running: a ring of ten giant beams (Technology's when held) with the laser hit params, +// five times their damage and no delay, sounding as they start, and the screen shakes. +static void tammys_head_mega_blast(Entity_Player& player, float turn, float bonus) +{ + int variant = player.HasCollectible(COLLECTIBLE_TECHNOLOGY) ? LASER_GIANT_BRIM_TECH : LASER_GIANT_RED; + for (int i = 0; i < TAMMY_TEAR_COUNT; i++) + { + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = player.pos, + .posOffset = vector_make(0, TAMMY_BEAM_RISE), + .source = &player, + .angleDegrees = ((float)i / TAMMY_TEAR_COUNT + turn) * FULL_CIRCLE, + .timeout = TAMMY_BEAM_TIMEOUT, + .variant = variant}); + int displacement = (int)(Random() % 2) * 2 - 1; + TearParams params = player.GetTearHitParams(WEAPON_LASER, 1, displacement, nullptr); + laser->SetCollisionDamage(params.tearDamage * TAMMY_BEAM_DAMAGE_SCALE + bonus); + laser->isDisableInitSound = false; + laser->tearFlags = params.tearFlags; + laser->tearFlags.reset(TEAR_WAIT); + laser->SetColor(player.laserColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + laser->Update(); + } + game_shake_screen(TAMMY_BEAM_SHAKE); +} + +// One shot of Tammy's Head's ring for another weapon along a direction, the tenth of the ring it is: a Dr. Fetus bomb, +// a Brimstone beam, a Technology laser on the player or a homing knife, each with bonus damage scaled to its weapon. +static void tammys_head_weapon_shot(Entity_Player& player, WeaponType weapon, const TammyShot& shot) +{ + if (weapon == WEAPON_BOMBS) + { + Entity_Bomb* bomb = player.FireBomb(player.pos, vector_resized(shot.direction, TAMMY_TEAR_SPEED), nullptr); + bomb->explosionDamage += shot.scale * TAMMY_BOMB_DAMAGE; + bomb->Update(); + return; + } + if (weapon == WEAPON_BRIMSTONE) + { + Entity_Laser* beam = player.FireBrimstone(shot.direction, nullptr, 1); + beam->SetCollisionDamage(beam->collisionDamage + shot.scale * TAMMY_BEAM_DAMAGE); + beam->Update(); + return; + } + if (weapon == WEAPON_LASER) + { + Entity_Laser* laser = player.FireTechLaser( + {.direction = shot.direction, .position = player.pos, .isLeftEye = true, .isOneHit = true}); + laser->SetCollisionDamage(laser->collisionDamage + shot.scale * TAMMY_TEAR_DAMAGE); + laser->posOffset = vector_make(0, laser->posOffset.y); + laser->Update(); + return; + } + Entity_Knife* knife = player.FireKnife({.parent = &player, .subType = 1}); + knife->rotation = normalize_angle_degrees((float)shot.index * TAMMY_KNIFE_STEP + shot.turn * FULL_CIRCLE); + knife->SetCollisionDamage(knife->collisionDamage + shot.scale * TAMMY_TEAR_DAMAGE); + knife->InitHomingPath(vector_from_angle(knife->rotation), &player, 0); + knife->Update(); +} + +// Tammy's Head: a ring of ten tears turned at random, bigger and with bonus damage a data value scales in percent, or +// a ring of whatever else the player shoots. static void tammys_head_use(ItemUse& use) { Entity_Player& player = use.player; float turn = random_unit(); float scale = use.request.varData != 0 ? use.request.varData / (float)PERCENT : 1; + if (player.megaBlastLaser) + { + tammys_head_mega_blast(player, turn, scale * TAMMY_BEAM_DAMAGE); + use.isShowAnimation = false; + return; + } bool isOtherWeapon = player.HasWeaponType(WEAPON_BOMBS) || player.HasWeaponType(WEAPON_BRIMSTONE) || player.HasWeaponType(WEAPON_LASER) || player.HasWeaponType(WEAPON_KNIFE); - if (player.megaBlastLaser || isOtherWeapon) - reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (Tammy's Head with another weapon)"); + if (isOtherWeapon) + { + WeaponType weapon = player.HasWeaponType(WEAPON_BOMBS) ? WEAPON_BOMBS + : player.HasWeaponType(WEAPON_BRIMSTONE) ? WEAPON_BRIMSTONE + : player.HasWeaponType(WEAPON_LASER) ? WEAPON_LASER + : WEAPON_KNIFE; + for (int i = 0; i < TAMMY_TEAR_COUNT; i++) + { + Vector direction = vector_from_angle(((float)i / TAMMY_TEAR_COUNT + turn) * FULL_CIRCLE); + tammys_head_weapon_shot(player, weapon, {.direction = direction, .scale = scale, .turn = turn, .index = i}); + } + return; + } float bonus = TAMMY_TEAR_DAMAGE * scale; for (int i = 0; i < TAMMY_TEAR_COUNT; i++) @@ -940,8 +1035,8 @@ static void book_of_revelations_use(ItemUse& use) g_game->SetStateFlag(REVELATIONS_STATE_FLAG, true); } -// A pedestal the D6 rerolls: another item from the pools, or none a quarter of the time for the Eternal D6, then a poof. -// The D6's wisps for Book of Virtues are not written yet. +// A pedestal the D6 rerolls: another item from the pools (with a wisp for Book of Virtues), or none a quarter of the +// time for the Eternal D6, then a poof. static void pedestal_reroll(ItemUse& use, Entity_Pickup& pickup) { constexpr int ETERNAL_D6_RNG_SHIFT = 44; @@ -964,11 +1059,23 @@ static void pedestal_reroll(ItemUse& use, Entity_Pickup& pickup) pickup.Morph(pickup.type, pickup.variant, 0, true, false, false); pickup.isTouched = false; if (use.player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed && use.id == COLLECTIBLE_D6) - reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (the D6's wisps)"); + use.player.AddWisp(COLLECTIBLE_D6, pickup.pos, false, false); } g_game->Spawn({.position = pickup.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); } +// The Eternal D6's wisps for Book of Virtues: one more, or every one of them dies, a coin flip. +static void eternal_d6_wisps_roll(Entity_Player& player) +{ + if (Random() % 2 == 0) + { + player.AddWisp(COLLECTIBLE_ETERNAL_D6, player.pos, false, false); + return; + } + for (Entity* wisp : entity_query(ENTITY_FAMILIAR, Entity_Familiar::WISP)) + if (wisp->subtype == COLLECTIBLE_ETERNAL_D6) wisp->Kill(EntityRef()); +} + // The D6 and the Eternal D6: every pedestal item of the room rerolled. static void d6_use(ItemUse& use) { @@ -989,7 +1096,7 @@ static void d6_use(ItemUse& use) pedestal_reroll(use, *pickup); } if (use.id == COLLECTIBLE_ETERNAL_D6 && player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed) - reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (the Eternal D6's wisps)"); + eternal_d6_wisps_roll(player); } if (!use.isShowAnimation) return; @@ -1048,7 +1155,7 @@ static int metronome_item_roll(Entity_Player& player) if (g_game->challenge == CHALLENGE_CANTRIPPED && ItemConfig::is_collectible_tagged(id, TAG_NO_CANTRIP)) continue; if (id == COLLECTIBLE_DEATH_CERTIFICATE && chances.RandomFloat() >= METRONOME_DEATH_CERTIFICATE_CHANCE) continue; if (id == COLLECTIBLE_GENESIS && chances.RandomFloat() >= METRONOME_GENESIS_CHANCE) continue; - if (g_game->dailyChallenge._id != 0 && id == COLLECTIBLE_FORGET_ME_NOW) continue; + if (g_game->dailyChallenge.id != 0 && id == COLLECTIBLE_FORGET_ME_NOW) continue; if (!ItemConfig::IsValidCollectible(id) || !config.GetCollectible(id)) continue; if (g_game->deathmatchManager.is_active()) reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (Metronome's pick in a versus match)"); @@ -2485,9 +2592,36 @@ bool active_pedestal_swap(Entity_Pickup& pickup, Entity_Player& player) return true; } +// Part of 006e8ae0: a golden battery hurts its taker for a heart and runs off to a random other room of the floor +// (outside the ultra secret room, in the current room's group or none), saved there to be found again. +static void golden_battery_escape(Entity_Pickup& battery, Entity_Player& player) +{ + constexpr float GOLDEN_BATTERY_DAMAGE = 2; + constexpr int GOLDEN_BATTERY_COUNTDOWN = 30; + Game& game = *g_game; + + player.TakeDamage(GOLDEN_BATTERY_DAMAGE, DAMAGE_INVINCIBLE | DAMAGE_NO_PENALTIES, EntityRef{}, + GOLDEN_BATTERY_COUNTDOWN); + RoomDescriptor* current = game.GetCurrentRoomDesc(); + std::vector rooms; + for (int i = 0; i < game.nbRooms; i++) + { + RoomDescriptor& room = game.roomList[i]; + bool isOpen = room.data && room.safeGridIndex >= 0 && room.data->type != ROOM_ULTRASECRET && &room != current; + if (isOpen && (room.group == current->group || room.group == -1)) rooms.push_back(&room); + } + if (rooms.empty()) return; + + RoomDescriptor* target = rooms[battery.dropRNG.RandomInt((uint32_t)rooms.size())]; + EntitySaveState state; + if (!entity_state_save(*game.room, battery, state, MINECART_REFUSED)) return; + state.targetPosition = {}; + target->savedEntities.push_back(state); +} + // The battery part of 006e8ae0: a battery charges the first active slot that takes it (a normal or timed one), six // charges for a lil' or golden battery and two for a micro one, while a mega battery overcharges every slot twice -// over. Whether it was taken. The golden battery's own effect is not written yet. +// over. Whether it was taken. A golden battery then runs off to another room. bool battery_collect(Entity_Pickup& battery, Entity_Player& player) { bool isMega = battery.subtype == BATTERY_MEGA; @@ -2507,6 +2641,6 @@ bool battery_collect(Entity_Pickup& battery, Entity_Player& player) if (!isTaken) return false; g_manager->persistentGameData.IncreaseEventCounter(EVENT_BATTERIES_COLLECTED, 1); - if (battery.subtype == BATTERY_GOLDEN) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0 (a golden battery)"); + if (battery.subtype == BATTERY_GOLDEN) golden_battery_escape(battery, player); return true; } diff --git a/src/entity_player_actives_grid.cpp b/src/entity_player_actives_grid.cpp index 2f4aa0f..f0ab441 100644 --- a/src/entity_player_actives_grid.cpp +++ b/src/entity_player_actives_grid.cpp @@ -184,7 +184,7 @@ constexpr std::array D12_OUTCOMES = { static D12Outcome d12_outcome_allowed(D12Outcome outcome) { PersistentGameData& data = g_manager->persistentGameData; - bool isDaily = g_game->dailyChallenge._id != 0; + bool isDaily = g_game->dailyChallenge.id != 0; if (outcome.type == GRID_POOP && outcome.variant == 6 && !data.Unlocked(D12_ACHIEVEMENT_HOLY_POOP)) return {GRID_POOP, 0}; if (outcome.type == GRID_POOP && outcome.variant == 11 && !data.Unlocked(D12_ACHIEVEMENT_CHARMING_POOP)) diff --git a/src/entity_player_actives_rebirth.cpp b/src/entity_player_actives_rebirth.cpp index bdfc931..4faca39 100644 --- a/src/entity_player_actives_rebirth.cpp +++ b/src/entity_player_actives_rebirth.cpp @@ -21,6 +21,7 @@ #include "pocket_items.h" #include "room.h" #include "room_grid.h" +#include "room_special.h" #include "sfx_manager.h" #include #include @@ -533,7 +534,7 @@ static void d20_use(ItemUse& use) if (player.variant == PLAYER_VARIANT_PLAYER) { if (g_game->room->roomType == ROOM_SHOP) - reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (the D20 in a shop: Room::ShopReshuffle 00816000)"); + room_shop_reshuffle(*g_game->room, RESHUFFLE_KEEP_ITEMS); for (Entity* entity : entity_query(ENTITY_PICKUP, -1)) { if (entity->isDead || entity->variant == PICKUP_COLLECTIBLE) continue; diff --git a/src/entity_player_actives_repentance.cpp b/src/entity_player_actives_repentance.cpp index eb0d148..869b691 100644 --- a/src/entity_player_actives_repentance.cpp +++ b/src/entity_player_actives_repentance.cpp @@ -123,11 +123,7 @@ constexpr float JAR_OF_WISPS_VIRTUES_CHANCE = 0.67f; constexpr ColorMod MYSTERY_GIFT_COAL_COLOR = {{0.05f, 0.05f, 0.05f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr int GLOWING_HOUR_GLASS_REWINDS = 3; constexpr int DOOR_SLOT_LAST = 7; -constexpr int D7_DUNGEON_GIDEON = 2; -constexpr int D7_DUNGEON_ROTGUT = 3; -constexpr int GENESIS_ROOM_SUBTYPE = 99; constexpr int GENESIS_WISPS = 3; -constexpr RNG GENESIS_RNG_SHIFTS = {0, 3, 3, 26}; constexpr int R_KEY_RAISE_DELAY = 3; constexpr int PEELER_BLOOD_SUBTYPE = 3; constexpr int PEELER_GORE_MIN = 2; @@ -1237,8 +1233,8 @@ static void glowing_hour_glass_use(ItemUse& use) sound_play(SOUND_GLOWING_HOURGLASS_ACTIVATE); } -// D7: the room's enemies come back to fight again, never in a boss room, the Beast's dungeon, Gideon's or Rotgut's -// crawl space, or at Home. +// D7: the room's enemies come back to fight again, never in a boss room, the Beast's dungeon, Rotgut's two crawl +// spaces (subtypes 2 and 3) or at Home. static void d7_use(ItemUse& use) { Entity_Player& player = use.player; @@ -1251,8 +1247,9 @@ static void d7_use(ItemUse& use) use_animate(use); } RoomConfig_Room* data = room.descriptor->data; - bool isBossDungeon = room.roomType == ROOM_DUNGEON && data && (data->subtype == D7_DUNGEON_GIDEON || data->subtype == D7_DUNGEON_ROTGUT); - if (room.roomType == ROOM_BOSS || room.IsBeastDungeon() || isBossDungeon || g_game->stage == STAGE_HOME) return; + bool isRotgutDungeon = room.roomType == ROOM_DUNGEON && data && + (data->subtype == DUNGEON_ROTGUT || data->subtype == DUNGEON_ROTGUT_HEART); + if (room.roomType == ROOM_BOSS || room.IsBeastDungeon() || isRotgutDungeon || g_game->stage == STAGE_HOME) return; room.RespawnEnemies(); g_game->isRoomRespawned = true; } @@ -1273,22 +1270,6 @@ static void stitches_use(ItemUse& use) stitches->Update(); } -// 0074bce0 The Genesis room made anew: a fresh descriptor with an Isaac's room of the special rooms' subtype 99, -// seeded from the devil room's generator. -static void genesis_room_prepare() -{ - Game& game = *g_game; - RoomDescriptor* genesis = game.GetRoomByIdx(ROOM_GENESIS_IDX); - - *genesis = RoomDescriptor{}; - genesis->listIndex = ROOM_GENESIS_IDX; - RNG rng = GENESIS_RNG_SHIFTS; - rng._seed = game.devilAngelRoomRNG._seed; - genesis->InitSeeds(rng); - RoomQuery query = {.stageId = STAGE_ID_SPECIAL_ROOMS, .subtype = GENESIS_ROOM_SUBTYPE, .type = ROOM_ISAACS}; - genesis->data = game.roomConfig.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); -} - // Genesis' three Book of Virtues wisps, once the player stands in the Genesis room. static void genesis_wisps_add(Entity_Effect* timer) { @@ -1304,7 +1285,7 @@ static void genesis_use(ItemUse& use) if (player.variant != PLAYER_VARIANT_PLAYER) return; single_use_remove(use); - genesis_room_prepare(); + g_game->InitializeGenesisRoom(); g_game->leaveDoor = -1; g_game->StartRoomTransition({.player = player.GetMainTwin(), .animation = TRANSITION_TELEPORT, .dimension = 0, .roomIndex = ROOM_GENESIS_IDX}); @@ -1320,7 +1301,6 @@ static void genesis_use(ItemUse& use) static void r_key_restart(Entity_Effect*) { constexpr int STAGE_LAST_SAVED = 8; - constexpr int GREED_STAGE_ICON = -3; constexpr int BOSS_RUSH_PAR = 36000; constexpr int BOSS_RUSH_ALT_PAR = 45000; constexpr float R_KEY_FADE_SPEED = 0.04f; diff --git a/src/entity_player_bombs.cpp b/src/entity_player_bombs.cpp index f4f94f1..f50edd6 100644 --- a/src/entity_player_bombs.cpp +++ b/src/entity_player_bombs.cpp @@ -16,7 +16,6 @@ // The items a player's bombs ask about (Lua's CollectibleType and TrinketType). constexpr int COLLECTIBLE_BOBBY_BOMB = 125; -constexpr int COLLECTIBLE_BUTT_BOMBS = 209; constexpr int COLLECTIBLE_SAD_BOMBS = 220; constexpr int COLLECTIBLE_BOMBER_BOY = 353; constexpr int COLLECTIBLE_SCATTER_BOMBS = 366; diff --git a/src/entity_player_cards.cpp b/src/entity_player_cards.cpp index 6470a1d..474bcb1 100644 --- a/src/entity_player_cards.cpp +++ b/src/entity_player_cards.cpp @@ -38,7 +38,6 @@ constexpr int WHEEL_CRANE_GAME_ACHIEVEMENT = 607; constexpr int JUDGEMENT_ROTTEN_BEGGAR_ACHIEVEMENT = 614; constexpr int BERKANO_LOCUSTS = 3; constexpr int BERKANO_LOCUST_SUBTYPE = 25; -constexpr int DAEMONS_TAIL_HEART_ODDS = 5; constexpr int DAGAZ_EVIL_CHARM_FRAMES = 600; constexpr int DEATH_EVENT_COUNTER = 7; constexpr int EMERGENCY_HANDS = 2; @@ -70,9 +69,6 @@ constexpr float SUN_DAMAGE = 100; constexpr float WHEEL_VOLUME = 1.2f; constexpr int REVERSE_DEVIL_SOUND = 266; // The bomb pickup subtypes IX - The Hermit? values higher (Lua's BombSubType, which entity_pickup.cpp keeps). -constexpr int BOMB_SUBTYPE_DOUBLEPACK = 2; -constexpr int BOMB_SUBTYPE_GOLDEN = 4; -constexpr int BOMB_SUBTYPE_GIGA = 7; constexpr int BLANK_RUNE_KEEP_ODDS = 4; constexpr int REVERSE_TOWER_RNG_SHIFT = 45; constexpr int REVERSE_TOWER_FREE_WEIGHT = 5; diff --git a/src/entity_player_characters.cpp b/src/entity_player_characters.cpp index 4b3d00a..3b580a5 100644 --- a/src/entity_player_characters.cpp +++ b/src/entity_player_characters.cpp @@ -3,6 +3,7 @@ #include "entity_effect.h" #include "entity_familiar.h" #include "entity_knife.h" +#include "entity_pickup.h" #include "entity_player_tainted.h" #include "game.h" #include "hud.h" @@ -19,6 +20,7 @@ #include #include #include +#include constexpr int CHARGE_STORE_MAX = 99; constexpr int SOUL_CHARGE_CONSUMABLE = 0x20; @@ -29,6 +31,8 @@ constexpr int DEATHMATCH_WHORE_RED_HEARTS = 16; constexpr int NULLITEM_SLOW_A = 62; constexpr int NULLITEM_SLOW_B = 65; constexpr float AZAZELS_STUMP_DAMAGE_SCALE = 1.5f; +// The shift Esau's share of Jacob's hearts and items is rolled with, from Clicker's seed. +constexpr uint32_t ESAU_SPLIT_RNG_SHIFT = 59; constexpr int MAGGY_HEART_LIMIT = 4; constexpr int MAGGY_BIRTHRIGHT_HEART_LIMIT = 6; constexpr int MAGGY_DRAIN_FRAMES = 300; @@ -695,7 +699,7 @@ void Entity_Player::Revive() // 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 +// and Tainted Jacob's curse, Tainted Forgotten's flight, and its pocket active for the new // one's. void Entity_Player::player_type_change_prepare(int oldType) { @@ -714,7 +718,7 @@ void Entity_Player::player_type_change_prepare(int oldType) if (playerType == PLAYER_ISAAC_B) tainted_isaac_inventory_trim(*this); if ((playerType == PLAYER_JACOB_B || playerType == PLAYER_JACOB2_B) && !temporaryEffects.HasNullEffect(NULLITEM_JACOBS_CURSE)) - reconstruction_missing("Entity_Player::player_type_change_prepare 007cf610 (Tainted Jacob's curse)"); + jacobs_curse_add(JACOBS_CURSE_CHANGE); if (oldType == PLAYER_THEFORGOTTEN_B) { cacheFlags |= CACHE_FLYING; @@ -831,6 +835,130 @@ static void health_type_apply(Entity_Player& player, HealthType health) } } +// The hearts Esau takes from Jacob: about half of each kind, rolled from a copy of Clicker's generator. +struct EsauHearts +{ + int black = 0; + int bone = 0; + int golden = 0; + int max = 0; + int red = 0; + int rotten = 0; + int soul = 0; +}; + +// Half of an amount, its odd half rolled up or down. +static int esau_half_roll(RNG& rng, int amount) +{ + return (int)rng.RandomInt((uint32_t)(amount % 2 + 1)) + amount / 2; +} + +// Esau's share of Jacob's hearts: whole heart containers, bone hearts, red hearts as far as his containers hold them +// (and whatever Jacob's own can no longer hold), rotten hearts as far as his red hearts hold them, soul and golden +// hearts. +static EsauHearts esau_hearts_roll(Entity_Player& jacob, RNG& rng) +{ + EsauHearts esau; + esau.max = esau_half_roll(rng, (jacob.maxHearts + 1) / 2) * 2; + esau.bone = esau_half_roll(rng, jacob.boneHearts); + esau.red = std::min(esau_half_roll(rng, jacob.redHearts), esau.max + esau.bone * 2); + esau.red += std::max(0, esau.max + (esau.bone - jacob.boneHearts) * 2 - jacob.maxHearts - esau.red + jacob.redHearts); + esau.rotten = std::min(esau_half_roll(rng, jacob.rottenHearts), (esau.red + 1) / 2); + esau.rotten += std::max(0, jacob.rottenHearts - (jacob.redHearts - esau.red) / 2 - esau.rotten); + esau.soul = esau_half_roll(rng, jacob.soulHearts); + esau.golden = esau_half_roll(rng, jacob.goldenHearts); + return esau; +} + +// Whether Esau takes a history entry of Jacob's: a passive collectible Jacob still has or a smelted trinket, on an even +// roll. +static bool esau_item_takes(Entity_Player& jacob, const HistoryItem& entry, RNG& rng) +{ + if (entry.isTrinket) + { + SmeltedTrinket& smelted = jacob.smeltedTrinkets[entry.id & TRINKET_ID_MASK]; + return (smelted.count > 0 || smelted.goldenCount > 0) && (rng.Next() & 1) == 0; + } + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(entry.id); + return jacob.CanRerollCollectible(entry.id, false) && item->type != ITEM_ACTIVE && + jacob.collectibleCounts[entry.id] > 0 && (rng.Next() & 1) == 0; +} + +// Moves a history entry from Jacob to Esau: a collectible with its costume when it shows one, or a smelted trinket with +// its costume when Esau had none of it. +static void esau_item_take(Entity_Player& jacob, Entity_Player& esau, size_t index) +{ + HistoryItem entry = jacob.history.historyItems[index]; + ItemConfig& config = g_manager->itemConfig; + if (!entry.isTrinket) + { + ItemConfig_Item* item = config.GetCollectible(entry.id); + esau.collectibleCounts[entry.id]++; + if (item->isAddCostumeOnPickup) esau.AddCostume(item, false); + esau.history.AddHistoryItem(entry); + jacob.history.historyItems.erase(jacob.history.historyItems.begin() + (long)index); + jacob.history.remove_index_refs((int)index); + jacob.RemoveCollectible(entry.id, true, ACTIVE_SLOT_PRIMARY, true); + return; + } + int id = entry.id & TRINKET_ID_MASK; + SmeltedTrinket& smelted = esau.smeltedTrinkets[id]; + if (smelted.count < 1 && smelted.goldenCount < 1) esau.AddCostume(config.GetTrinket(id), false); + if (entry.id & TRINKET_GOLDEN_FLAG) smelted.goldenCount++; + else smelted.count++; + esau.history.AddHistoryItem(entry); + jacob.TryRemoveSmeltedTrinket((uint32_t)entry.id); + jacob.history.historyItems.erase(jacob.history.historyItems.begin() + (long)index); + jacob.history.remove_index_refs((int)index); +} + +// The ChangePlayerType part that makes a player Jacob: Esau joins with about half of each kind of heart and every other +// passive collectible and smelted trinket Jacob picked up, both keep at least half a heart, and Jacob drops his pocket +// items. +static void esau_split(Entity_Player& jacob) +{ + Entity_Player* esau = jacob.InitTwin(PLAYER_ESAU); + esau->InitPostLevelInitStats(); + RNG rng = rng_make(jacob.collectibleRNGs[COLLECTIBLE_CLICKER]._seed, ESAU_SPLIT_RNG_SHIFT); + EsauHearts share = esau_hearts_roll(jacob, rng); + + esau->maxHearts = share.max; + esau->AddBoneHearts(share.bone); + esau->soulHearts = share.soul; + esau->redHearts = share.red; + esau->blackHearts |= jacob.blackHearts << ((jacob.soulHearts - share.soul) / 2 & 31); + esau->goldenHearts = share.golden; + esau->rottenHearts = share.rotten; + esau->brokenHearts = jacob.brokenHearts; + if (share.soul > 0) jacob.AddSoulHearts(-share.soul, false); + if (share.red > 0) jacob.AddHearts(-share.red, false, false); + if (share.bone > 0) jacob.AddBoneHearts(-share.bone); + if (share.max > 0) jacob.AddMaxHearts(-share.max, false); + jacob.goldenHearts -= share.golden; + jacob.rottenHearts -= share.rotten; + for (Entity_Player* each : {&jacob, esau}) + if (each->soulHearts + each->redHearts + each->boneHearts < 1) each->AddSoulHearts(1, false); + for (Entity_Player* each : {&jacob, esau}) + { + each->ClampGoldenHearts(false); + each->update_bone_hearts(); + each->UpdateHeartDependentEffects(); + } + + jacob.history.isLocked = true; + for (size_t i = 0; i < jacob.history.historyItems.size();) + { + if (esau_item_takes(jacob, jacob.history.historyItems[i], rng)) esau_item_take(jacob, *esau, i); + else i++; + } + jacob.history.isLocked = false; + esau->cacheFlags = CACHE_ALL; + esau->EvaluateItems(); + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); + for (uint32_t slot = 0; slot < jacob.GetMaxPocketItems(); slot++) + jacob.DropPocketItem((int)slot, room_free_pickup_position_find({.position = jacob.pos})); +} + // The ChangePlayerType part that takes a twin's hearts into the player that no longer needs it: the most broken hearts, // then its containers, bone, eternal, red, soul and golden hearts, its black ones after the player's soul hearts, and // its rotten ones as far as the red hearts hold them. @@ -914,8 +1042,7 @@ void Entity_Player::ChangePlayerType(int newType, bool isKeepState) AddEternalHearts(0); if (playerType == PLAYER_JACOB) { - if (!isKeepState) - reconstruction_missing("Entity_Player::ChangePlayerType 007ce6e0 (Jacob splitting his hearts with Esau)"); + if (!isKeepState) esau_split(*this); } else if (Entity_Player* twin = twin_get(); twin && !isKeepState) twin_hearts_take(*this, *twin); if (playerType == PLAYER_BETHANY && soulHearts > 0) @@ -1219,10 +1346,98 @@ constexpr int BIRTHRIGHT_HEARTS = 2; constexpr int BIRTHRIGHT_RED_STEW_FRAMES = 1800; constexpr int BIRTHRIGHT_RECALL_SLOT = 2; constexpr int BIRTHRIGHT_BETHANY_EFFECTS = 4; +// Eden's Birthright offers three collectibles, each rolled up to a hundred times. The twins share three. +constexpr int EDEN_BIRTHRIGHT_ITEMS = 3; +constexpr int EDEN_BIRTHRIGHT_TRIES = 100; +constexpr size_t TWINS_BIRTHRIGHT_ITEMS = 3; -// Part of 0075f0e0: what Birthright does as it is picked up, by character. Judas's Book of Belial swap, Eden's three -// items and Jacob and Esau's shared items are not reconstructed yet. -void birthright_gain(Entity_Player& player, bool isFirstTime) +// Judas' Birthright: a Book of Belial held in either active slot (the second first) turns into the kept Book of +// Belial, keeping its charges. +static void judas_belial_keep(Entity_Player& player) +{ + for (int slot = ACTIVE_SLOT_SECONDARY; slot >= ACTIVE_SLOT_PRIMARY; slot--) + { + ActiveItemDesc& active = player.activeItems[slot]; + if (active.item != COLLECTIBLE_BOOK_OF_BELIAL) continue; + ActiveItemDesc kept = active; + player.RemoveCollectible(COLLECTIBLE_BOOK_OF_BELIAL, true, slot, false); + if (active.item != COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) continue; + active = kept; + active.item = COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE; + } +} + +// A random passive collectible Eden's Birthright offers: any available one Eden may roll, else the room's pool draw, +// taken out of the pools. None after a hundred misses and an empty pool. +static int eden_birthright_roll(RNG& rng) +{ + ItemConfig& config = g_manager->itemConfig; + for (int tries = 0; tries < EDEN_BIRTHRIGHT_TRIES; tries++) + { + int id = (int)rng.RandomInt((uint32_t)config.collectibles.size() - 1) + 1; + ItemConfig_Item* item = config.GetCollectible(id); + if (!ItemConfig::IsValidCollectible(id) || (item->tags & TAG_NO_EDEN) || !item->IsAvailable(UNLOCK_CHECKED) || + item->type == ITEM_ACTIVE) + continue; + g_game->itemPool.RemoveCollectible(id, REMOVE_ANY, REMOVE_APPLY); + return id; + } + int id = g_game->itemPool.GetSeededCollectible(rng._seed, 0, *g_game->room->descriptor); + if (id != 0) g_game->itemPool.RemoveCollectible(id, REMOVE_ANY, REMOVE_APPLY); + return id; +} + +// Eden's Birthright: three collectibles to choose one of, each by its first pool. +static void eden_birthright_offer(Entity_Player& player, RNG& rng) +{ + int optionsIndex = -1; + for (int i = 0; i < EDEN_BIRTHRIGHT_ITEMS; i++) + { + Vector position = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_SPOT_STEP}); + int id = eden_birthright_roll(rng); + auto* item = static_cast(g_game->Spawn({.position = position, + .subType = id, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = rng.Next()})); + item->itemPoolType = g_game->itemPool.GetFirstItemPoolForCollectible(id); + if (optionsIndex < 0) optionsIndex = item->AssignOptionsIndex(); + else item->optionsPickupIndex = optionsIndex; + } +} + +// Jacob's and Esau's Birthright: the lead twin takes copies of the last three passive collectibles or trinkets its twin +// picked up, the oldest first (trinkets straight into its smelted ones). +static void twins_birthright_share(Entity_Player& player) +{ + Entity_Player* twin = player.twin_get(); + if (!twin || player.parent) return; + + std::vector shared; + std::vector& items = twin->history.historyItems; + for (int i = (int)items.size() - 1; i >= 0 && shared.size() < TWINS_BIRTHRIGHT_ITEMS; i--) + { + const HistoryItem& entry = items[i]; + if (entry.isTrinket) shared.push_back(-entry.id); + else if (player.CanRerollCollectible(entry.id, false) && + g_manager->itemConfig.GetCollectible(entry.id)->type != ITEM_ACTIVE && + twin->collectibleCounts[entry.id] > 0) + shared.push_back(entry.id); + } + for (int id : std::views::reverse(shared)) + { + if (id > 0) player.AddCollectible(id, 0, false, ACTIVE_SLOT_PRIMARY, 0, 0); + if (id >= 0) continue; + uint32_t trinket = (uint32_t)-id; + player.history.AddHistoryItem({g_game->frameCount, true, (int)trinket, 1, 0, 1, 0}); + SmeltedTrinket& smelted = player.smeltedTrinkets[trinket & TRINKET_ID_MASK]; + if (trinket & TRINKET_GOLDEN_FLAG) smelted.goldenCount++; + else smelted.count++; + } +} + +// Part of 0075f0e0: what Birthright does as it is picked up, by character. +void birthright_gain(Entity_Player& player, RNG& rng, bool isFirstTime) { switch (player.playerType) { @@ -1233,21 +1448,26 @@ void birthright_gain(Entity_Player& player, bool isFirstTime) player.AddMaxHearts(BIRTHRIGHT_HEARTS, false); player.AddHearts(BIRTHRIGHT_HEARTS, false, false); return; + case PLAYER_JUDAS: + case PLAYER_BLACKJUDAS: return judas_belial_keep(player); case PLAYER_EVE: return player.UpdateHeartDependentEffects(); + case PLAYER_EDEN: + if (isFirstTime) eden_birthright_offer(player, rng); + return; case PLAYER_LAZARUS2: if (isFirstTime) player.redStewBonusDuration = BIRTHRIGHT_RED_STEW_FRAMES; return; + case PLAYER_JACOB: + case PLAYER_ESAU: + if (isFirstTime) twins_birthright_share(player); + return; case PLAYER_EDEN_B: player.edenBirthrightFrame = g_game->frameCount + 1; return; case PLAYER_THEFORGOTTEN_B: return player.SetPocketActiveItem(COLLECTIBLE_RECALL, BIRTHRIGHT_RECALL_SLOT, false); case PLAYER_BETHANY_B: if (isFirstTime) player.temporaryEffects.AddNullEffect(NULLITEM_BETHANY_B_BIRTHRIGHT, false, BIRTHRIGHT_BETHANY_EFFECTS); return; - case PLAYER_JUDAS: - case PLAYER_BLACKJUDAS: - case PLAYER_EDEN: - case PLAYER_JACOB: - case PLAYER_ESAU: - reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (this character's Birthright)"); + default: + return; } } diff --git a/src/entity_player_characters.h b/src/entity_player_characters.h index 5ca2319..105e236 100644 --- a/src/entity_player_characters.h +++ b/src/entity_player_characters.h @@ -58,7 +58,7 @@ ButtonAction twin_button_action(Entity_Player& player, TwinButton button); bool is_twin_button_blocked(Entity_Player& player, TwinButton button); // Birthright's pickup effect by character (part of 0075f0e0). -void birthright_gain(Entity_Player& player, bool isFirstTime); +void birthright_gain(Entity_Player& player, RNG& rng, bool isFirstTime); // Cambion Conception's count of hits (part of 007729d0). void cambion_conception_hit(Entity_Player& player); diff --git a/src/entity_player_costumes.cpp b/src/entity_player_costumes.cpp index 8c102d8..e4253c4 100644 --- a/src/entity_player_costumes.cpp +++ b/src/entity_player_costumes.cpp @@ -1,4 +1,8 @@ #include "entity_player.h" +#include "item_config.h" +#include "seeds.h" +#include "npc_ai.h" +#include "entity_bomb.h" #include "game.h" #include "log.h" #include "manager.h" @@ -10,6 +14,14 @@ #include #include +// Hot Potato's bomb head: its blast's damage (more for a big bomb), radius, and the throw it gives the player. +constexpr float HOT_POTATO_DAMAGE = 60; +constexpr float HOT_POTATO_BIG_DAMAGE = 110; +constexpr float HOT_POTATO_BIG_SCALE = 1.5f; +constexpr float HOT_POTATO_RADIUS = 1.25f; +constexpr float HOT_POTATO_KNOCK_MIN = 2; +constexpr float HOT_POTATO_KNOCK_RANGE = 3; +constexpr float HOT_POTATO_KNOCK_HEIGHT = 8; constexpr float BLEED_OUT_TINT_HEALTH = 150; constexpr int REVERSE_CHARIOT_FLASH_FRAMES = 90; constexpr float HEAD_LIFT_PER_HEAD_SCALE = 2.5f; @@ -197,10 +209,60 @@ static void squash_look_read(Entity_Player& player, LayerLook& look) look.offsetX = REVERSE_CHARIOT_SHAKE[std::min(player.reverseChariotMoveCooldown, REVERSE_CHARIOT_SHAKE_LAST)]; } +// Hot Potato's bomb head blowing up: an explosion of the player's own bomb near him (stronger for a big bomb) that +// knocks him into the air. +static void hot_potato_explode(Entity_Player& player) +{ + TearFlags flags = player.GetBombFlags(false); + bool isBig = player.check_bomb_tearflags(flags) >= HOT_POTATO_BIG_SCALE; + float damage = isBig ? HOT_POTATO_BIG_DAMAGE : HOT_POTATO_DAMAGE; + explosion_effects({.tearFlags = flags, + .color = player.color, + .position = vector_add(player.pos, random_direction()), + .source = &player, + .damage = damage, + .radiusMultiplier = HOT_POTATO_RADIUS, + .isDamageSource = true}); + player.velocity = {}; + Vector knock = vector_scale(random_direction(), random_unit() * HOT_POTATO_KNOCK_RANGE + HOT_POTATO_KNOCK_MIN); + player.TryThrow(EntityRef(), knock, HOT_POTATO_KNOCK_HEIGHT); +} + +// Hot Potato's bomb head on Tainted Forgotten: its pulse starts, and each pulse that ends outside his extra and item +// animations blows up and pulses again. Those animations stop it. The pulse's HeadAnim null moves, sizes and tints his +// head and body. +static void hot_potato_head_update(Entity_Player& player, LayerLook& look) +{ + ItemConfig_Item* bombHead = g_manager->itemConfig.GetNullItem(NULLITEM_FORGOTTEN_BOMB); + for (PlayerCostumeMap& map : player.playerCostumeMap) + { + if (map.index < 0 || map.isBodyLayer) continue; + ANM2& sprite = player.costumeSpriteDescs[map.index].sprite; + if (player.costumeSpriteDescs[map.index].item != bombHead) continue; + + if (!sprite.overlayAnimState.animData) sprite.PlayOverlay("Pulse"); + else if (player.isPlayingExtraAnimation || player.isPlayingItemAnimation) sprite.RemoveOverlay(); + else if (sprite.IsOverlayFinished()) + { + sprite.PlayOverlay("Pulse", PLAY_FORCED); + hot_potato_explode(player); + } + if (!sprite.overlayAnimState.animData) return; + if (const NullFrame* pulse = sprite.overlayAnimState.GetNullFrame("HeadAnim")) + { + look.headSize = vector_mul(look.headSize, pulse->scale); + look.headOffset = vector_add(look.headOffset, pulse->pos); + color_multiply(look.headColor, pulse->color); + color_multiply(look.bodyColor, pulse->color); + } + return; + } +} + // Reads how the player's layers draw this frame: the head's size from the head costume's frame (Pluto's and Inner // Child's heads keep theirs), Adrenaline's heartbeat, the head's offset and size from the body costume's HeadTransform // null (lower under Tainted Lilith's Gello, riding Tainted Forgotten's height), the effects' tints and squashes, and a -// bleeding out player reddening. Hot Potato's bomb head and a remote player's fading stop the game until reached. +// bleeding out player reddening, and Hot Potato's bomb head. A remote player's fading stops the game until reached. static void layer_look_read(Entity_Player& player, LayerLook& look) { PlayerCostumeMap& head = player.playerCostumeMap[PLAYER_LAYER_HEAD]; @@ -230,7 +292,7 @@ static void layer_look_read(Entity_Player& player, LayerLook& look) tint_look_read(player, look); squash_look_read(player, look); if (g_game->challenge == CHALLENGE_HOT_POTATO && player.playerType == PLAYER_THEFORGOTTEN_B) - reconstruction_missing("Entity_Player::Update 00782af0 (Hot Potato's bomb head)"); + hot_potato_head_update(player, look); if (player.playerType == PLAYER_THEFORGOTTEN_B) look.headOffset.y += player.forgottenBHeight; bool isBleeding = player.HasEntityFlags(FLAG_BLEED_OUT) && player.bleedSource.entity == &player && diff --git a/src/entity_player_crafting.cpp b/src/entity_player_crafting.cpp index 5bfd329..e7882cb 100644 --- a/src/entity_player_crafting.cpp +++ b/src/entity_player_crafting.cpp @@ -4,6 +4,8 @@ #include "entity_knife.h" #include "entity_pickup.h" #include "game.h" +#include "game_state.h" +#include "game_state_player.h" #include "hud.h" #include "item_pool.h" #include "manager.h" @@ -509,16 +511,61 @@ void Entity_Player::tainted_cain_pedestal_burst(Vector position, uint32_t seed, } } +// The Glowing Hourglass' state a rewind would go back to: the other slot's when it is kept, else the current one's. +// None before a slot was saved. +static GlowingHourglassState* glowing_hourglass_state_find() +{ + Game& game = *g_game; + int slot = game.currentGlowingHourglassSlot; + if (slot < 0) return nullptr; + GlowingHourglassState* state = &game.glowingHourglassStates[1 - slot]; + if (!state->isUsable) state = &game.glowingHourglassStates[slot]; + return state->isUsable ? state : nullptr; +} + +// The Cantripped bag's oldest item card: shown, counted among the room's temporary collectibles, then used as its +// active or picked up as its passive with its name shown. A Glowing Hourglass card is also struck from the rewind's +// saved cards, so a rewind cannot bring it back. +static void cantripped_card_play(Entity_Player& player) +{ + int card = player.itemCards.front(); + player.AnimateCollectible(card, "UseItem", "PlayerPickupSparkle"); + player.roomTemporaryCollectibles[card]++; + + if (ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(card)) + { + GlowingHourglassState* state = glowing_hourglass_state_find(); + int index = player.glowingHourglassIndex; + if (item->id == COLLECTIBLE_GLOWING_HOUR_GLASS && state && index >= 0 && + index < (int)state->gameState.players.size()) + { + std::vector& saved = state->gameState.players[index].itemCards; + if (auto found = std::ranges::find(saved, (int)COLLECTIBLE_GLOWING_HOUR_GLASS); found != saved.end()) + saved.erase(found); + } + if (item->type == ITEM_ACTIVE) player.UseActiveItem({.item = item->id, .flags = USE_OWNED}); + else player.AddCollectible(item->id, 0, true, ACTIVE_SLOT_PRIMARY, 0, 0); + g_game->hud.ShowItemText(&player, item); + } + npc_sound_play(SOUND_POWERUP1, 1, 2, 1); + player.itemCards.erase(player.itemCards.begin()); + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); +} + // The Bag of Crafting part of 005b39d0: used from a main slot with a craft ready, the bag drops the crafted item on a // pedestal (counted from its pool, with a wisp under Book of Virtues) and empties with a thumbs up. From the pocket it -// is lifted to swing. The animation the player shows, none for a co-op baby. The Cantripped challenge's card bag is not -// written yet. +// is lifted to swing. In Cantripped it plays its oldest item card instead. The animation the player shows, none for a +// co-op baby or an empty card bag. const char* bag_of_crafting_use(Entity_Player& player, int slot) { if (player.variant != PLAYER_VARIANT_PLAYER) return nullptr; crafting_sound_play(SOUND_BAG_OF_CRAFTING); if (g_game->challenge == CHALLENGE_CANTRIPPED) - reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (the Cantripped bag's cards)"); + { + if (player.itemCards.empty()) return nullptr; + cantripped_card_play(player); + return nullptr; + } if ((slot != ACTIVE_SLOT_PRIMARY && slot != ACTIVE_SLOT_SECONDARY) || player.bagOfCraftingOutput == 0) { player.SetItemState(COLLECTIBLE_BAG_OF_CRAFTING); diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp index 53b9903..df9534f 100644 --- a/src/entity_player_damage.cpp +++ b/src/entity_player_damage.cpp @@ -859,7 +859,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR bool isGhost = playerType == PLAYER_THELOST || playerType == PLAYER_THELOST_B || playerType == PLAYER_THESOUL_B; if (isGhost || HasInstantDeathCurse() || isDead) return false; spawn_ghost_corpse(); - if (!temporaryEffects.HasNullEffect(NULLITEM_LOST_CURSE)) game.playerManager.add_lost_curse(NULLITEM_LOST_CURSE); + if (!temporaryEffects.HasNullEffect(NULLITEM_LOST_CURSE)) game.playerManager.add_lost_curse(); sound_play(SOUND_FIREDEATH_HISS); // The controllers' rumble is not wired here. return true; diff --git a/src/entity_player_death.cpp b/src/entity_player_death.cpp index 08ea516..2a290ce 100644 --- a/src/entity_player_death.cpp +++ b/src/entity_player_death.cpp @@ -6,6 +6,14 @@ #include "entity_list.h" #include "entity_npc.h" #include "entity_player.h" +#include "fx_layers.h" +#include "active_items.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "entity_tear.h" +#include "entity_pickup.h" +#include "entity_config.h" +#include "entity_bomb.h" #include "entity_player_characters.h" #include "game.h" #include "item_config.h" @@ -28,6 +36,31 @@ 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; +// Tainted Forgotten's bones: the Hot Potato giga bomb's damage, and how many bones scatter how far. +constexpr float HOT_POTATO_DEATH_DAMAGE = 60; +constexpr int FORGOTTEN_BONES = 6; +constexpr float FORGOTTEN_BONES_SPREAD = 40; +// Tainted ???'s last poops: the fart and poop behind him, his brown splashes (their speed, growth and color), the +// poop pickups' speed and at most 19 of them, all within an arc behind him. +constexpr float BLUE_BABY_POOP_BEHIND = 10; +constexpr float BLUE_BABY_FART_RADIUS = 120; +constexpr float BLUE_BABY_SPRAY_BEHIND = 4; +constexpr float BLUE_BABY_SCATTER_ARC = 40; +constexpr int BLUE_BABY_SPLASHES = 6; +constexpr float BLUE_BABY_SPLASH_SPEED_MIN = 6; +constexpr float BLUE_BABY_SPLASH_SPEED_RANGE = 20; +constexpr float BLUE_BABY_SPLASH_GROWTH = 1.5f; +constexpr ColorMod BLUE_BABY_SPLASH_COLOR = {{0.4f, 0.33f, 0.25f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float BLUE_BABY_POOP_SPEED_MIN = 3; +constexpr float BLUE_BABY_POOP_SPEED_RANGE = 6; +constexpr int BLUE_BABY_POOPS_MAX = 18; +// The ghost a dead player's Vade Retro releases: its size, damage, cry and shake. +constexpr float VADE_RETRO_GHOST_SCALE = 1.5f; +constexpr float VADE_RETRO_GHOST_DAMAGE = 200; +constexpr float VADE_RETRO_GHOST_VOLUME = 1.25f; +constexpr float VADE_RETRO_GHOST_PITCH_MIN = 0.9f; +constexpr float VADE_RETRO_GHOST_PITCH_RANGE = 0.2f; +constexpr int VADE_RETRO_GHOST_SHAKE = 14; constexpr int PAPER_FRAME_PERIOD = 4; constexpr int PAPER_FRAME_SINGLE = 3; constexpr int PAPER_FRAME_DOUBLE = 2; @@ -155,7 +188,7 @@ static bool is_missing_poster_unlocked() { Manager& manager = *g_manager; bool isExemptRun = - manager.state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge._id != 0 || g_game->isDebug); + manager.state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge.id != 0 || g_game->isDebug); return manager.persistentGameData.achievements[ACHIEVEMENT_THE_LOST] || isExemptRun; } @@ -757,6 +790,104 @@ static bool is_run_lost(Entity_Player& dying) return true; } +// Tainted Forgotten's bones break as he dies: his weapons go, and in Hot Potato he blows up as a giga bomb, else his +// bones scatter in a cloud of dust. +static void forgotten_bones_break(Entity_Player& player) +{ + for (size_t slot = 1; slot <= player.weapons.size(); slot++) player.weapons[slot % player.weapons.size()].reset(); + if (g_game->challenge == CHALLENGE_HOT_POTATO) + { + TearFlags giga; + giga.set(TEAR_GIGA_BOMB); + explosion_effects({.tearFlags = giga, .position = player.pos, .source = &player, + .damage = HOT_POTATO_DEATH_DAMAGE, .isDamageSource = true}); + return; + } + gibs_spawn({.color = player.color, + .position = player.pos, + .spawner = &player, + .spread = FORGOTTEN_BONES_SPREAD, + .amount = FORGOTTEN_BONES, + .gibFlags = GIB_FLAG_BONE | GIB_FLAG_SOUND_BONE | GIB_FLAG_DUST}); + npc_sound_play(SOUND_DEATH_BURST_BONE, 1, 2, 1); +} + +// The flight of a bit Tainted ??? leaves behind: backwards, turned up to 20 degrees either way, at a random speed. +static Vector blue_baby_scatter_velocity(float speedMin, float speedRange) +{ + float turn = random_unit() * BLUE_BABY_SCATTER_ARC - BLUE_BABY_SCATTER_ARC / 2; + Vector direction = vector_rotated(vector_make(-1, 0), turn); + return vector_scale(direction, random_unit() * speedRange + speedMin); +} + +// Tainted ???'s death: a last fart and a poop behind him, a spray of brown splashes, and his spare poop mana falling out +// as poop pickups (fewer the more falls), one frame apart. +static void blue_baby_last_poops(Entity_Player& player) +{ + Vector behind = vector_make(player.pos.x - BLUE_BABY_POOP_BEHIND, player.pos.y); + game_butter_bean_fart({.position = behind, .source = &player, .radius = BLUE_BABY_FART_RADIUS}); + g_game->Spawn({.position = behind, .type = ENTITY_POOP, .seed = Random()}); + + Vector spray = vector_make(player.pos.x - BLUE_BABY_SPRAY_BEHIND, player.pos.y); + for (int i = 0; i < BLUE_BABY_SPLASHES; i++) + { + uint32_t seed = Random(); + Vector velocity = blue_baby_scatter_velocity(BLUE_BABY_SPLASH_SPEED_MIN, BLUE_BABY_SPLASH_SPEED_RANGE); + Entity* splash = g_game->Spawn({.position = spray, .velocity = velocity, .subType = 1, + .type = ENTITY_EFFECT, .variant = EFFECT_WATER_SPLASH, .seed = seed}); + splash->sprite.scale = vector_scale(splash->sprite.scale, random_unit() * BLUE_BABY_SPLASH_GROWTH + 1); + splash->sprite.color = BLUE_BABY_SPLASH_COLOR; + splash->Update(); + } + for (int i = 0; i < player.poopMana && i <= BLUE_BABY_POOPS_MAX; i++) + { + uint32_t seed = Random(); + Vector velocity = blue_baby_scatter_velocity(BLUE_BABY_POOP_SPEED_MIN, BLUE_BABY_POOP_SPEED_RANGE); + auto* poop = static_cast(g_game->Spawn({.position = spray, .velocity = velocity, + .type = ENTITY_PICKUP, .variant = PICKUP_POOP, + .seed = seed})); + poop->dropDelay = i; + poop->Update(); + player.AddPoopMana(-1); + } +} + +// Where the dying player's ghost layer shows, from the player: the middle of its keyframe's quad, in world units. None +// when the animation has no track for it. +static Vector ghost_layer_offset(Entity_Player& player, const LayerState& ghost, const AnimationFrame& frame) +{ + const AnimationData* data = player.sprite.animState.animData; + int layerId = ghost.layerData->id; + if (!data || data->layerMap[layerId] < 0) return {}; + + DestinationQuad quad = AnimationLayer::GetDestQuad(frame, ghost, SpriteDraw{}, player.sprite); + Vector middle = vector_scale(vector_add(quad._topLeft, quad._bottomRight), HALF); + return vector_scale(middle, 1 / ROOM_SCREEN_SCALE); +} + +// A dead player holding Vade Retro lets its ghost go with the item button: the ghost layer, while shown, leaves as a +// big enemy ghost that hurts, with a demon's cry and a shake. +static void vade_retro_ghost_release(Entity_Player& player) +{ + LayerState* ghost = player.sprite.GetLayer("ghost"); + if (!ghost || !ghost->layerData || !ghost->isVisible) return; + const AnimationFrame* frame = player.sprite.animState.GetLayerFrame(ghost->layerData->id); + if (!frame || !frame->isVisible) return; + + Vector offset = ghost_layer_offset(player, *ghost, *frame); + Entity* released = g_game->Spawn({.position = player.pos, .subType = 2, .type = ENTITY_EFFECT, + .variant = EFFECT_ENEMY_GHOST, .seed = Random()}); + released->posOffset = offset; + released->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + released->sprite.scale = vector_make(VADE_RETRO_GHOST_SCALE, VADE_RETRO_GHOST_SCALE); + released->SetCollisionDamage(VADE_RETRO_GHOST_DAMAGE); + released->Update(); + npc_sound_play(SOUND_DEMON_HIT, VADE_RETRO_GHOST_VOLUME, 2, + random_unit() * VADE_RETRO_GHOST_PITCH_RANGE + VADE_RETRO_GHOST_PITCH_MIN); + game_shake_screen(VADE_RETRO_GHOST_SHAKE); + ghost->isVisible = false; +} + // 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 @@ -790,18 +921,17 @@ void Entity_Player::death_update() } friction *= DEATH_FRICTION; - if (activeItems[0].item == COLLECTIBLE_VADE_RETRO && sprite.IsPlaying()) - reconstruction_missing("Entity_Player::Update 00782af0 (Vade Retro used by a dead player's ghost)"); + if (activeItems[0].item == COLLECTIBLE_VADE_RETRO && sprite.IsPlaying() && + input_is_action_triggered(twin_button_action(*this, TWIN_BUTTON_ITEM), controllerIndex, nullptr)) + vade_retro_ghost_release(*this); if (playerType == PLAYER_THEFORGOTTEN_B) { - if (sprite.IsPlaying(animation) && sprite.GetFrame() == DEATH_FRAME_BONES_BREAK) - reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Forgotten's bones break)"); + if (sprite.IsPlaying(animation) && sprite.GetFrame() == DEATH_FRAME_BONES_BREAK) forgotten_bones_break(*this); } else if (sprite.IsPlaying(animation) && sprite.IsEventTriggered("DeathSound")) { 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)"); + if (playerType == PLAYER_BLUEBABY_B) blue_baby_last_poops(*this); } bool isDeathShown = (sprite.IsPlaying(animation) && @@ -915,7 +1045,7 @@ bool Entity_Player::FlushQueueItem() queuedItem.charge = 0; queuedItem.varData = 0; bool isFirstTime = !(queued.flags & QUEUED_TOUCHED); - bool isShuffledDaily = g_game->dailyChallenge._specialDailyId == SPECIAL_DAILY_SHUFFLED_ITEMS; + bool isShuffledDaily = g_game->dailyChallenge.specialDailyId == SPECIAL_DAILY_SHUFFLED_ITEMS; if (queued.item->type == ITEM_TRINKET) { diff --git a/src/entity_player_effects.cpp b/src/entity_player_effects.cpp index 867007a..e5799d7 100644 --- a/src/entity_player_effects.cpp +++ b/src/entity_player_effects.cpp @@ -28,6 +28,10 @@ // The Ladder's reach: how near a player must stand to a laid ladder to keep it, and the turn of a ladder laid across. constexpr float LADDER_KEEP_DISTANCE_SQUARED = 3249; constexpr float LADDER_ACROSS_ROTATION = 90; +// Azazel's Rage's beam: its damage scale, how high over the player it starts and how long it lasts. +constexpr float RAGE_DAMAGE_SCALE = 1.5f; +constexpr float RAGE_LASER_RISE = -30; +constexpr int RAGE_LASER_TIMEOUT = 90; // The pit at a cell, or null off the grid or on any other grid entity. static GridEntity_Pit* pit_at(Room& room, int gridIndex) @@ -478,14 +482,42 @@ static void empty_vessel_update(Entity_Player& player) effects.AddEffect(shield, true, 1); } +// Azazel's Rage's beam: a thicker red Brimstone at one and a half times the damage, three seconds long, the way the +// player aims (else faces), in the laser color with its hit flags but no delay, and the rage costume's head shooting +// along it. +static void azazels_rage_fire(Entity_Player& player) +{ + int displacement = (int)(Random() % 2) * 2 - 1; + TearParams params = player.GetTearHitParams(WEAPON_LASER, RAGE_DAMAGE_SCALE, displacement, nullptr); + Vector direction = vector_from_direction(player.headDirection); + if (player.aimDirection.x != 0 || player.aimDirection.y != 0) direction = player.aimDirection; + + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = player.pos, + .posOffset = vector_make(0, RAGE_LASER_RISE), + .source = &player, + .angleDegrees = vector_angle(direction), + .timeout = RAGE_LASER_TIMEOUT, + .variant = LASER_THICKER_RED}); + laser->SetCollisionDamage(player.damage); + player.azazelsRageLaser = laser; + laser->tearFlags = params.tearFlags; + laser->tearFlags.reset(TEAR_WAIT); + laser->SetColor(player.laserColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + laser->Update(); + + player.AddCostume(g_manager->itemConfig.GetNullItem(NULLITEM_AZAZELS_RAGE_4), false); + player.play_null_costume_anim(NULLITEM_AZAZELS_RAGE_4, HEAD_SHOOT_ANIMS[vector_to_direction(direction)], -1); +} + // Azazel's Rage: on a room's third frame (or once its beam is spent) the rage ends with the item gone. With four -// rooms gathered, a room still fighting (an ambush not yet over) unleashes its beam, which is not written yet. A -// spent beam's rage settles back into the item's costume. +// rooms gathered, a room still fighting (an ambush not yet over) unleashes its beam. A spent beam's rage settles back +// into the item's costume. static void azazels_rage_update(Entity_Player& player) { constexpr int RAGE_ROOM_FRAME = 3; constexpr int RAGE_READY = 4; constexpr int RAGE_FIRING = 5; + constexpr int RAGE_FIRED = 6; TemporaryEffects& effects = player.temporaryEffects; ItemConfig& config = g_manager->itemConfig; Room& room = *g_game->room; @@ -504,7 +536,10 @@ static void azazels_rage_update(Entity_Player& player) bool isAmbush = room.roomType == ROOM_CHALLENGE || room.roomType == ROOM_BOSSRUSH; bool isCalm = isAmbush ? room.IsAmbushDone() : room.IsClear(); if (!isCalm && (rooms == RAGE_READY || rooms == RAGE_FIRING)) - reconstruction_missing("Entity_Player::update_effects 00794e50 (Azazel's Rage's beam)"); + { + effects.AddCollectibleEffect(COLLECTIBLE_AZAZELS_RAGE, false, RAGE_FIRED - rooms); + azazels_rage_fire(player); + } } } if (effects.GetCollectibleEffectNum(COLLECTIBLE_AZAZELS_RAGE) <= RAGE_FIRING || player.azazelsRageLaser) return; @@ -748,6 +783,17 @@ static void reverse_empress_blink_update(Entity_Player& player) else if (phase >= 4 && !isShown) player.AddCostume(costume, false); } +// Reverse Sun keeps the room dark for a second at a time while it lasts (in versus only for the local main player). +static void reverse_sun_update(Entity_Player& player) +{ + constexpr int REVERSE_SUN_DARKNESS_FRAMES = 60; + if (!player.temporaryEffects.HasNullEffect(NULLITEM_REVERSE_SUN)) return; + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::update_effects 00794e50 (Reverse Sun in versus)"); + g_game->darknessStrength = 1; + g_game->darknessTimeout = REVERSE_SUN_DARKNESS_FRAMES; +} + // IBS charges with the damage enemies took this frame, up to full. A spent charge (negative) drains back to zero // over a second. static void ibs_charge_update(Entity_Player& player) @@ -1030,6 +1076,7 @@ void items_frame_update(Entity_Player& player) divine_intervention_recharge(player); tooth_and_nail_update(player); reverse_empress_blink_update(player); + reverse_sun_update(player); if (effects.HasNullEffect(NULLITEM_REVERSE_STARS) && player.IsExtraAnimationFinished()) effects.RemoveNullEffect(NULLITEM_REVERSE_STARS, 1); ibs_charge_update(player); diff --git a/src/entity_player_evaluate.cpp b/src/entity_player_evaluate.cpp index 0040827..c4b8536 100644 --- a/src/entity_player_evaluate.cpp +++ b/src/entity_player_evaluate.cpp @@ -152,7 +152,7 @@ static void bulbs_apply(Entity_Player& p, float& stat, float dimScale, float vib // but do not run yet: collectible effects and null effects. An effect the frame never asks about only counts down // there. The frame's own part (00782af0) runs or stops on its own. constexpr int FRAME_COLLECTIBLE_EFFECTS[] = {130, 181, 593, 705, 714}; -constexpr int FRAME_NULL_EFFECTS[] = {60, 66, 69, 111, 114, 116, 122, 128}; +constexpr int FRAME_NULL_EFFECTS[] = {60, 69, 111, 114, 116, 122, 128}; // Whether the frame runs a temporary effect: the effects written for it, and those it never asks about. static bool is_frame_effect_known(const TemporaryEffect& effect) @@ -886,7 +886,7 @@ static void speed_evaluate(Entity_Player& p, const StatBonuses& bonus) else if (effects.HasCollectibleEffect(COLLECTIBLE_CAMO_UNDIES)) p.moveSpeed = p.moveSpeed + 0.5f; p.moveSpeed = p.d8SpeedModifier * p.moveSpeed; if (crownScale != 1 && p.moveSpeed > 1) p.moveSpeed = (p.moveSpeed - 1) * (crownScale - 1) + p.moveSpeed; - if (g_game->dailyChallenge._id == DAILY_SLOW) p.moveSpeed = p.moveSpeed - 1; + if (g_game->dailyChallenge.id == DAILY_SLOW) p.moveSpeed = p.moveSpeed - 1; static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_SPEED); } @@ -919,7 +919,7 @@ static void luck_evaluate(Entity_Player& p, const StatBonuses& bonus) bulbs_apply(p, p.luck, 2, 0); if (p.HasCollectible(492)) p.luck = p.luck + 1; bulbs_apply(p, p.luck, 0, 1); - if (g_game->dailyChallenge._id == DAILY_LUCKY) p.luck = p.luck + DAILY_LUCK_BONUS; + if (g_game->dailyChallenge.id == DAILY_LUCKY) p.luck = p.luck + DAILY_LUCK_BONUS; if (g_game->debugFlags & DEBUG_HIGH_LUCK) p.luck = p.luck + DEBUG_LUCK_BONUS; static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_LUCK); @@ -1223,7 +1223,7 @@ static void size_evaluate(Entity_Player& p) float head = (float)(effect(121) + ((n(121) - n(120)) - effect(120))) * 0.152f + 0; if (game.seedEffects.HasSeedEffect(SEED_BIG_HEAD)) head = head + BIG_HEAD_BONUS; if (game.seedEffects.HasSeedEffect(SEED_SMALL_HEAD)) head = head - 1; - if (game.dailyChallenge._id == DAILY_BIG_SIZE) body = body + DAILY_BIG_SIZE_BONUS; + if (game.dailyChallenge.id == DAILY_BIG_SIZE) body = body + DAILY_BIG_SIZE_BONUS; float bodyScale = size_scale(body); float headScale = size_scale(head); diff --git a/src/entity_player_familiars.cpp b/src/entity_player_familiars.cpp index 7dc91cd..33b8f88 100644 --- a/src/entity_player_familiars.cpp +++ b/src/entity_player_familiars.cpp @@ -50,7 +50,7 @@ Entity* Entity_Player::AddBoneOrbital(Vector position) } // 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). +// (the first in the room's list first). Entity* Entity_Player::AddSwarmFlyOrbital(Vector position) { std::deque flies; @@ -58,7 +58,7 @@ Entity* Entity_Player::AddSwarmFlyOrbital(Vector position) 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); + if (isFly && static_cast(entity)->player == this) flies.push_back(entity); } for (; flies.size() > SWARM_FLIES_MAX; flies.pop_front()) flies.front()->Remove(); diff --git a/src/entity_player_forgotten.cpp b/src/entity_player_forgotten.cpp index 01c7b0d..76b7cad 100644 --- a/src/entity_player_forgotten.cpp +++ b/src/entity_player_forgotten.cpp @@ -503,7 +503,7 @@ void Entity_Player::pockets_rotate() actionHoldDrop = 0; return; } - if ((uint32_t)++actionHoldDrop > DROP_HOLD_FRAMES && game.dailyChallenge._specialDailyId != SPECIAL_DAILY_NO_DROP) + if ((uint32_t)++actionHoldDrop > DROP_HOLD_FRAMES && game.dailyChallenge.specialDailyId != SPECIAL_DAILY_NO_DROP) drop_hold_update(*this); } diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index 684f4ff..886f29a 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -5,6 +5,7 @@ #include "entity_player_passives.h" #include "tainted_characters.h" #include "boss_ai.h" +#include "color_stack.h" #include "entity_bomb.h" #include "entity_effect.h" #include "sfx_manager.h" @@ -30,6 +31,7 @@ #include "hud.h" #include "room.h" #include "weapon_lasers.h" +#include #include #include @@ -83,7 +85,6 @@ 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; @@ -126,6 +127,8 @@ constexpr float CANDLE_FLAME_DAMAGE = 23; constexpr float BOBS_HEAD_DAMAGE = 185; constexpr float BOBS_HEAD_FALL_BASE = 1.2f; constexpr float BOBS_HEAD_FALL_SPREAD = 0.2f; +// How far toward the cursor the mouse aims, from what the camera follows. +constexpr float MOUSE_AIM_SCALE = 0.2f; constexpr float BOBS_HEAD_HEIGHT = -33; constexpr int SHOOP_STATE_FRAMES = 30; constexpr int SHOOP_LASER_TIMEOUT = 15; @@ -675,12 +678,26 @@ void Entity_Player::head_turn(Vector toward) headAnim = PLAYER_HEAD_ANIMS[headDirection]; } -// 007b9f60 Where the mouse aims the player's shots, offline only the keyboard player's while the option is on. Mouse -// aiming (the left button held) is not written yet. -bool Entity_Player::GetMouseAimTarget(Vector&, bool) +// 007b9f60 Where the mouse aims the player's shots while its left button is held, offline only the keyboard player's +// with the option on: the cursor in the world (mirrored in the mirror world), a fifth of the way from what the camera +// follows. An online player's cursor is not reconstructed. +bool Entity_Player::GetMouseAimTarget(Vector& target, bool) { if (!g_manager->optionsConfig.isMouseControlEnabled || controllerIndex != 0) return false; - reconstruction_missing("Entity_Player::GetMouseAimTarget 007b9f60 (mouse aiming)"); + Vector cursor = {}; + if (!(SDL_GetMouseState(&cursor.x, &cursor.y) & SDL_BUTTON_LMASK)) return false; + + Room& room = *g_game->room; + if (Room::IsMirrorWorld()) cursor.x = (float)platform.windowSize.width - cursor.x; + float pixelScale = (float)platform.windowSize.height / KAGE::Graphics::manager.orthographicHeight; + target.x = (cursor.x / pixelScale - room.renderScrollOffset.x - (g_screenWidth - ROOM_VIEW_WIDTH) * HALF) / + ROOM_SCREEN_SCALE + ROOM_ORIGIN_X; + target.y = (cursor.y / pixelScale - room.renderScrollOffset.y - (g_screenHeight - ROOM_VIEW_HEIGHT) * HALF) / + ROOM_SCREEN_SCALE + ROOM_ORIGIN_Y; + + Entity* focus = GetFocusEntity(); + target = vector_scale(vector_sub(target, focus ? focus->pos : pos), MOUSE_AIM_SCALE); + return true; } // Reads the shoot actions, or the movement ones under the seeds that shoot with movement: whether any is held, @@ -1166,6 +1183,34 @@ struct ChargeShot // The charged shots' timings: a full charge, the room's first frames that only reset it, and the shot's block. constexpr uint32_t CHARGE_FULL = 150; +// The charge bars over the player: which bar each charge fills, its full percent and the least shown of a charging +// item's, how far above and beside the player they start, each shown bar's offset, the Bag of Crafting's hold before +// and while its bar fills, Sumptorium's charge, and Tainted Lazarus' second form's faint flicker. +enum ChargeBar +{ + CHARGE_BAR_WEAPON, + CHARGE_BAR_WEAPON_SECOND, + CHARGE_BAR_MAW, + CHARGE_BAR_REVELATION, + CHARGE_BAR_MONTEZUMA, + CHARGE_BAR_BERSERK, + CHARGE_BAR_SUMPTORIUM +}; +constexpr int CHARGE_BAR_PERCENT_FULL = 100; +constexpr int CHARGE_BAR_MIN = 5; +constexpr float CHARGE_BAR_SIDE = 12; +constexpr float CHARGE_BAR_RISE = -35; +constexpr std::array, 4> CHARGE_BAR_OFFSETS = {{{0, 0}, {7, 11}, {14, 0}, {21, 11}}}; +constexpr int CRAFT_BAR_DELAY = 5; +constexpr float CRAFT_BAR_FRAMES = 25; +constexpr float SUMPTORIUM_BAR_FRAMES = 60; +constexpr uint32_t CHARGE_BAR_FLICKER_SHIFT = 10; +constexpr float CHARGE_BAR_FLICKER = 0.15f; +constexpr float CHARGE_BAR_FLICKER_MIN = 0.05f; +// Tainted Lazarus' hologram flickers as faintly from its own generator, fading in over its first second. +constexpr uint32_t HOLOGRAM_FLICKER_SEED = 0x194fc4ad; +constexpr uint32_t HOLOGRAM_FLICKER_SHIFT = 31; +constexpr float HOLOGRAM_FADE_FRAMES = 30; constexpr int CHARGE_ROOM_FRAMES = 5; constexpr int CHARGE_FIRE_BLOCK = 30; constexpr int NO_2_FRAMES = 150; @@ -1706,7 +1751,7 @@ void Entity_Player::update_shooting() if (HasCollectible(COLLECTIBLE_NO_2) && game.stageTransition.state == 0 && isInputAllowed && fireBlockCooldown < 1) number_two_update(*this, isShootHeld); - bool isButterBeanDaily = game.dailyChallenge._specialDailyId == SPECIAL_DAILY_BUTTER_BEAN; + 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}); @@ -1919,46 +1964,134 @@ void Entity_Player::Render(const Vector& offset) reconstruction_missing("Entity_Player::Render 0078ca00 (the deathmatch overlay)"); } +// The reflection Tainted Lazarus casts on water: his other form, shown and posed as he is, its layers and costumes +// rescaled to its own body and head, drawn where he stands. +static void lazarus_reflection_render(Entity_Player& player, const Vector& offset, RenderPass pass) +{ + Entity_Player& other = *player.backupPlayer; + bool wasVisible = other.isVisible; + bool wasExisting = other.isExists; + other.isVisible = true; + other.isExists = true; + if (!player.bodySprite.isLoaded) + { + if (other.bodySprite.isLoaded) other.bodySprite.Reset(); + } + else if (!other.bodySprite.isLoaded) other.bodySprite = other.sprite; + + int bodyFrame = player.sprite.GetFrame(); + const AnimationState& head = player.sprite.overlayAnimState; + int headFrame = head.animData ? (int)head.animFrame : -1; + std::string bodyAnim = player.sprite.GetAnimation(); + player.sprite.animation_copy(other.sprite); + other.sprite.scale = vector_div(vector_mul(player.sprite.scale, other.playerSpriteScale), player.playerSpriteScale); + other.isPlayingExtraAnimation = player.isPlayingExtraAnimation; + other.isPlayingItemAnimation = player.isPlayingItemAnimation; + player.bodySprite.animation_copy(other.bodySprite); + + for (int layerId = 0; layerId < COSTUME_LAYER_COUNT && !player.IsFullSpriteRendering(); layerId++) + { + PlayerCostumeMap& map = other.playerCostumeMap[layerId]; + Vector to = map.isBodyLayer ? other.bodyScale : other.headScale; + Vector from = map.isBodyLayer ? player.bodyScale : player.headScale; + LayerState* own = player.sprite.GetLayer(layerId); + LayerState* copy = other.sprite.GetLayer(layerId); + if (!own || !copy) continue; + Vector layerPos = vector_div(vector_mul(own->pos, to), from); + Vector layerSize = vector_div(vector_mul(own->size, to), from); + copy->pos = layerPos; + copy->size = layerSize; + if (map.index < 0) continue; + + CostumeSpriteDesc& costume = other.costumeSpriteDescs[map.index]; + costume.sprite.SetFrame(map.isBodyLayer ? bodyAnim : player.headAnim, map.isBodyLayer ? bodyFrame : headFrame); + costume.sprite.offset = layerPos; + costume.sprite.scale = layerSize; + if (map.isBodyLayer || !costume.isHasOverlay) continue; + std::string overlay = player.headAnim + "_Overlay"; + if (costume.sprite.GetAnimationData(overlay) && costume.sprite.SetOverlayAnimation(overlay) && + costume.sprite.overlayAnimState.animData) + costume.sprite.overlayAnimState.SetFrameFloat((float)headFrame); + } + + other.pos = player.pos; + other.render_pass(offset, pass); + other.isVisible = wasVisible; + other.isExists = wasExisting; +} + +// Tainted Lilith's body while she lifts an item: her lower body, head and extra layers with the body costumes, then the +// held item on the main pass, without the head's overlay, where she stands. +static void lilith_lift_render(Entity_Player& player, RenderPass pass, const Vector& offset) +{ + Vector heldOffset = player.posOffset; + player.posOffset = {}; + player.sprite.overlayAnimState.SetAnimationData(nullptr); + player.renderPosition = vector_add(render_position_get(player.pos, RENDER_SNAPPED), offset); + + SpriteDraw draw{player.renderPosition, {}, {}}; + for (int layer : {PLAYER_LAYER_BODY0, PLAYER_LAYER_HEAD, PLAYER_LAYER_EXTRA}) player.sprite.RenderLayer(layer, draw); + for (int layer = PLAYER_LAYER_BODY; layer <= PLAYER_LAYER_BODY1; layer++) + if (PlayerCostumeMap& map = player.playerCostumeMap[layer]; map.index >= 0) + player.costumeSpriteDescs[map.index].sprite.RenderLayer(map.layerId, draw); + if (pass == RENDER_PASS_MAIN && player.IsHoldingItem()) player.heldSprite.Render(draw); + player.posOffset = heldOffset; +} + +// The faint, flickering colour Tainted Lazarus' hologram draws in, fading in over its first second. +static ColorMod hologram_color_get(Entity_Player& player) +{ + static RNG flicker = rng_make(HOLOGRAM_FLICKER_SEED, HOLOGRAM_FLICKER_SHIFT); + float alpha = flicker.RandomFloat() * CHARGE_BAR_FLICKER + CHARGE_BAR_FLICKER_MIN; + + if (player.updateTime < HOLOGRAM_FADE_FRAMES) alpha *= player.updateTime / HOLOGRAM_FADE_FRAMES; + return {{1, 1, 1, alpha}, {0, 0, 0, 0}, {0, 0, 0}}; +} + // 0078b640 Draws the player's body: the glow, body, head and top layers of its sprite and costumes at its snapped -// position, or the whole sprite during extra animations. Co-op babies and ghosts draw as plain entities, Tainted -// Lazarus's hologram in a shimmer, and the twin behind Tainted Lazarus as its backup. +// position, or the whole sprite during extra animations, then its emote. Co-op babies and ghosts draw as plain +// entities, Tainted Lazarus's hologram in a faint flicker, Tainted Lilith's lifting body on its own, and on water +// Tainted Lazarus reflects as his other form. The online outlines and names are not reconstructed. void Entity_Player::render_pass(const Vector& offset, RenderPass pass) { if (g_game->room->entityList.renderMode == RENDER_WATER_REFLECT && variant == PLAYER_VARIANT_PLAYER && !isCoopGhost && (playerType == PLAYER_LAZARUS_B || playerType == PLAYER_LAZARUS2_B) && backupPlayer && isValid) - reconstruction_missing("Entity_Player::render_pass 0078b640 (Tainted Lazarus's reflection)"); - if (variant == PLAYER_VARIANT_COOP_BABY || isCoopGhost) + return lazarus_reflection_render(*this, offset, pass); + + if (variant == PLAYER_VARIANT_COOP_BABY || isCoopGhost) Entity::Render(offset); + else { - Entity::Render(offset); - return; - } - if (IsHologram()) reconstruction_missing("Entity_Player::render_pass 0078b640 (Tainted Lazarus's hologram)"); - if (IsHoldingItem() && bodySprite.animState.animData) - if (const NullFrame* held = bodySprite.animState.GetNullFrameById(0); - held && held->isVisible && playerType == PLAYER_LILITH_B) - reconstruction_missing("Entity_Player::render_pass 0078b640 (Tainted Lilith's held item)"); - if (IsFullSpriteRendering()) - { - Vector heldOffset = posOffset; - posOffset = {}; - sprite.overlayAnimState.SetAnimationData(nullptr); - Entity::Render(offset); - if (pass == RENDER_PASS_MAIN && IsHoldingItem()) heldSprite.Render(SpriteDraw{renderPosition, {}, {}}); - posOffset = heldOffset; - return; + bool isHologram = IsHologram(); + if (isHologram) color_stack_push(hologram_color_get(*this)); + const NullFrame* held = IsHoldingItem() && bodySprite.animState.animData + ? bodySprite.animState.GetNullFrameById(0) + : nullptr; + if (held && held->isVisible && playerType == PLAYER_LILITH_B) lilith_lift_render(*this, pass, offset); + else if (IsFullSpriteRendering()) + { + Vector heldOffset = posOffset; + posOffset = {}; + sprite.overlayAnimState.SetAnimationData(nullptr); + Entity::Render(offset); + if (pass == RENDER_PASS_MAIN && IsHoldingItem()) heldSprite.Render(SpriteDraw{renderPosition, {}, {}}); + posOffset = heldOffset; + } + else + { + renderPosition = vector_add(render_position_get(pos, RENDER_SNAPPED), offset); + bool isHeaded = !IsHeadless(); + if (isHeaded) + { + RenderGlow(renderPosition); + render_back(renderPosition); + } + RenderBody(renderPosition); + if (isHeaded) RenderHead(renderPosition); + RenderTop(renderPosition); + } + if (isHologram) color_stack_pop(); } - renderPosition = vector_add(render_position_get(pos, RENDER_SNAPPED), offset); - bool isHeaded = !IsHeadless(); - if (isHeaded) - { - RenderGlow(renderPosition); - render_back(renderPosition); - } - RenderBody(renderPosition); - if (isHeaded) RenderHead(renderPosition); - RenderTop(renderPosition); - (void)pass; bool isMoving = velocity.x * velocity.x + velocity.y * velocity.y > EMOTE_MOVING_SPEED; if (!emotes.isActive || emotes.emote != EMOTE_TYPING || !isMoving) emotes.Render(vector_make(renderPosition.x, renderPosition.y - bodyScale.y * EMOTE_HEIGHT)); @@ -2062,10 +2195,114 @@ bool Entity_Player::RenderShadowLayer(const Vector& offset) return Entity::RenderShadowLayer(offset); } -// 0075ea40 Draws the charge bars over the player when the options show them: the weapons' charge, the crafting bag and -// the charging items. Only the hidden case is reconstructed: shown bars stop the game until reached. -void Entity_Player::render_charge_bars(Vector) +// The charge bars shown this frame, in the order they were updated. +struct ChargeBars { - if (!g_manager->optionsConfig.isChargeBarsEnabled) return; - reconstruction_missing("Entity_Player::render_charge_bars 0075ea40 (the charge bars)"); + std::array shown{}; + int count = 0; + + void update(ANM2& bar, int percent); +}; + +// (0075ef20) Moves a bar to a percent: an empty bar disappears, a partial one stops on its frame of "Charging", a full +// one plays "StartCharged" once and then "Charged". A bar still playing or not empty is shown. +void ChargeBars::update(ANM2& bar, int percent) +{ + if (percent == 0) + { + if (bar.animState.animData) bar.Play("Disappear"); + } + else if (percent < CHARGE_BAR_PERCENT_FULL) bar.SetFrame("Charging", percent); + else + { + const AnimationData* data = bar.animState.animData; + if (!data || (!data->isLooping && !bar.animState.isPlaying)) + { + bar.Play("StartCharged"); + if (!bar.animState.animData || !bar.animState.isPlaying) bar.Play("Charged"); + } + } + + if ((bar.animState.animData && bar.animState.isPlaying) || percent >= 1) shown[count++] = &bar; +} + +// The percent a charging item's bar shows of a timer that fills at CHARGE_FULL, empty below a few percent. +static int item_charge_percent(uint32_t timer) +{ + float full = CHARGE_BAR_PERCENT_FULL; + int percent = (int)std::clamp((float)timer * full / CHARGE_FULL, 0.0f, full); + return percent > CHARGE_BAR_MIN ? percent : 0; +} + +// The first charge a weapon of slots 1 to 4 reports through a getter, as a percent. +template static int weapons_charge_percent(Entity_Player& player, Getter getCharge) +{ + for (size_t slot = 1; slot < WEAPON_SLOT_COUNT; slot++) + if (Weapon* weapon = player.weapons[slot].get(); weapon && getCharge(*weapon) > 0) + return (int)(getCharge(*weapon) * CHARGE_BAR_PERCENT_FULL); + return 0; +} + +// 0075ea40 Draws the charge bars over a local player when the options show them: the held Bag of Crafting's, or the +// weapons' two bars, Tainted Samson's Berserk, Tainted Eve's Sumptorium, Maw of the Void, Revelation and Montezuma's +// Revenge. The shown bars stack in the order updated, a Tainted Lazarus' second form's flickering faintly. +void Entity_Player::render_charge_bars(Vector renderPos) +{ + if (!g_manager->optionsConfig.isChargeBarsEnabled || !IsLocalPlayer()) return; + ChargeBars bars; + Vector anchor = vector_make(renderPos.x + playerSpriteScale.y * CHARGE_BAR_SIDE, + renderPos.y + playerSpriteScale.y * CHARGE_BAR_RISE); + + if (itemState == COLLECTIBLE_BAG_OF_CRAFTING && bagOfCraftingHoldFrames > CRAFT_BAR_DELAY) + { + float held = (float)(bagOfCraftingHoldFrames - CRAFT_BAR_DELAY) / CRAFT_BAR_FRAMES; + bars.update(chargeBarSprites[CHARGE_BAR_WEAPON], (int)(held * CHARGE_BAR_PERCENT_FULL)); + } + else + { + if (playerType == PLAYER_SAMSON_B) + { + TemporaryEffect* berserk = temporaryEffects.GetCollectibleEffect(COLLECTIBLE_BERSERK); + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_BERSERK); + float percent = 0; + if (berserk && item) percent = (float)berserk->cooldown * CHARGE_BAR_PERCENT_FULL / (float)item->maxCooldown; + bars.update(chargeBarSprites[CHARGE_BAR_BERSERK], (int)percent); + } + if (HasCollectible(COLLECTIBLE_SUMPTORIUM) && playerType == PLAYER_EVE_B) + bars.update(chargeBarSprites[CHARGE_BAR_SUMPTORIUM], + (int)((float)eveSumptoriumCharge / SUMPTORIUM_BAR_FRAMES * CHARGE_BAR_PERCENT_FULL)); + bars.update(chargeBarSprites[CHARGE_BAR_WEAPON], + weapons_charge_percent(*this, [](Weapon& weapon) { return weapon.GetChargeBarAmount(); })); + // The weapons' second bar (vtable slot 8), which every weapon leaves empty. + bars.update(chargeBarSprites[CHARGE_BAR_WEAPON_SECOND], + weapons_charge_percent(*this, [](Weapon&) { return 0.0f; })); + if (HasCollectible(COLLECTIBLE_MAW_OF_THE_VOID)) + bars.update(chargeBarSprites[CHARGE_BAR_MAW], item_charge_percent(mawOfTheVoidChargeTimer)); + if (HasCollectible(COLLECTIBLE_REVELATION)) + bars.update(chargeBarSprites[CHARGE_BAR_REVELATION], item_charge_percent(revelationChargeTimer)); + if (HasCollectible(COLLECTIBLE_MONTEZUMAS_REVENGE)) + bars.update(chargeBarSprites[CHARGE_BAR_MONTEZUMA], item_charge_percent(montezumaChargeTimer)); + } + + float alpha = 1; + Entity_Player* twin = twin_get(); + bool isLazarus = playerType == PLAYER_LAZARUS_B || playerType == PLAYER_LAZARUS2_B; + if (isExists && isLazarus && twin && twin->playerIndex != -1 && twin->playerIndex < playerIndex && twin != this) + alpha = rng_make(g_game->frameCount + 1, CHARGE_BAR_FLICKER_SHIFT).RandomFloat() * CHARGE_BAR_FLICKER + + CHARGE_BAR_FLICKER_MIN; + + // Past the fourth bar the original reads beyond its offsets table, so the offsets repeat. + for (int i = bars.count - 1; i >= 0; i--) + { + ANM2& bar = *bars.shown[i]; + bar.color._tint[3] = alpha; + auto [x, y] = CHARGE_BAR_OFFSETS[i % CHARGE_BAR_OFFSETS.size()]; + SpriteDraw draw{vector_make(anchor.x + x, anchor.y + y), {}, {}}; + if (bar.isLoaded) + { + (bar.isOverlayRenderFirst ? bar.overlayAnimState : bar.animState).Render(draw, bar); + (bar.isOverlayRenderFirst ? bar.animState : bar.overlayAnimState).Render(draw, bar); + } + bar.color._tint[3] = 1; + } } diff --git a/src/entity_player_hold.cpp b/src/entity_player_hold.cpp index e095b31..3b33fb9 100644 --- a/src/entity_player_hold.cpp +++ b/src/entity_player_hold.cpp @@ -2,6 +2,8 @@ #include "entity_effect.h" #include "entity_familiar.h" #include "entity_player.h" +#include "entity_tear.h" +#include "grid_entity_poop.h" #include "game.h" #include "log.h" #include "manager.h" @@ -43,9 +45,68 @@ static void bomb_throw(Entity_Bomb& bomb, Vector throwVelocity) bomb.rocketSpeed = THROWN_ROCKET_SPEED; } +// Part of 007d2470: Mom's Bracelet's lifted grid entity flies off from the player as a tear that looks like it, its +// type and variant in its subtype: 40 damage (15 in a versus match), a poop's by how whole it is (eight times a Giga +// Poop's, at triple scale, a poop that drops nothing keeping that), 80 for an armed spiked rock. Its index is the +// backdrop it was lifted from. The carrying effect goes. +static Entity_Tear* lifted_grid_throw(Entity_Player& player, Entity_Effect& lifted, Vector throwVelocity) +{ + constexpr float GRID_TEAR_DAMAGE = 40; + constexpr float GRID_TEAR_DAMAGE_VERSUS = 15; + constexpr float POOP_WHOLE = 1000; + constexpr float GIGA_POOP_SCALE = 3; + constexpr float GIGA_POOP_DAMAGE_SCALE = 8; + constexpr int SPIKED_ROCK_ARMED = 4; + constexpr float SPIKED_ROCK_TEAR_DAMAGE = 80; + constexpr int POOP_NO_DROPS = 1; + constexpr float GRID_TEAR_HEIGHT = -30; + constexpr float GRID_TEAR_FALL_ACCEL = 0.8f; + constexpr float GRID_TEAR_FALL_SPEED = -5; + + const GridEntityDesc& desc = lifted.gridDesc; + int subType = desc._type << 16 | (desc._variant & 0xffff); + auto* tear = static_cast(g_game->Spawn({.position = player.pos, + .velocity = throwVelocity, + .spawner = &player, + .subType = subType, + .type = ENTITY_TEAR, + .variant = TEAR_GRIDENT, + .seed = desc._spawnSeed})); + tear->SetCollisionDamage(g_game->deathmatchManager.is_active() ? GRID_TEAR_DAMAGE_VERSUS : GRID_TEAR_DAMAGE); + if (desc._type == GRID_POOP) + { + tear->health = (float)desc._state; + float wholeShare = (float)((int)POOP_WHOLE - desc._state) / POOP_WHOLE; + if (desc._variant >= POOP_GIGA_TOP_LEFT && desc._variant <= POOP_GIGA_BOTTOM_RIGHT) + { + tear->baseScale = GIGA_POOP_SCALE; + tear->fScale = GIGA_POOP_SCALE; + tear->ResetSpriteScale(); + wholeShare *= GIGA_POOP_DAMAGE_SCALE; + } + tear->SetCollisionDamage(wholeShare * GRID_TEAR_DAMAGE); + if (desc._varData == POOP_NO_DROPS) tear->AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + } + if (desc._type == GRID_ROCK_SPIKED && desc._state == SPIKED_ROCK_ARMED) tear->SetCollisionDamage(SPIKED_ROCK_TEAR_DAMAGE); + tear->tearIdx = lifted.state; + tear->SetHeight(GRID_TEAR_HEIGHT); + tear->fallingAccel = GRID_TEAR_FALL_ACCEL; + tear->fallingSpeed = GRID_TEAR_FALL_SPEED; + tear->isPrismTouched = true; + tear->sprite = lifted.sprite; + for (LayerState& layer : tear->sprite.layerStates) + { + layer.pos = {}; + layer.size = vector_make(1, 1); + } + tear->Update(); + lifted.Remove(); + return tear; +} + // 007d2470 Lets go of the held entity at a velocity, giving back its visibility and collision classes. An entity that // takes the throw flies off (a thrown player regains control and flies over the grid, a poop farts), a bomb leaves the -// hands, a small rocket vanishes. Returns what was let go. +// hands, a lifted grid entity becomes a tear, a small rocket vanishes. Returns what was let go, or the grid's tear. Entity* Entity_Player::ThrowHeldEntity(Vector throwVelocity) { Entity* held = heldEntity; @@ -74,8 +135,7 @@ Entity* Entity_Player::ThrowHeldEntity(Vector throwVelocity) } else if (held->type == ENTITY_BOMB) bomb_throw(*static_cast(held), throwVelocity); else if (held->type == ENTITY_EFFECT && held->variant == EFFECT_GRID_ENTITY_PROJECTILE_HELPER) - reconstruction_missing("Entity_Player::ThrowHeldEntity 007d2470: a lifted grid entity's tear (Entity_Effect " - "lacks the GridEntityDesc fields 0x430 to 0x43c Room::PickupGridEntity stores)"); + held = lifted_grid_throw(*this, *static_cast(held), throwVelocity); else if (held->type == ENTITY_EFFECT && held->variant == EFFECT_SMALL_ROCKET) held->Remove(); heldEntity = nullptr; diff --git a/src/entity_player_items.cpp b/src/entity_player_items.cpp index fa4f9d5..01fa520 100644 --- a/src/entity_player_items.cpp +++ b/src/entity_player_items.cpp @@ -83,7 +83,8 @@ static bool is_quest_item(ItemConfig_Item* item) // 007706e0 Whether the player has a collectible: owned, or lent by a trinket, a seed, a character, a temporary effect, // a wisp, Modeling Clay, a $3 Bill, Metronome or a conception. ITEM_CHECK_OWNED only looks at what it owns. -// Co-op babies ask their owner. Negative ids are procedural items. +// Co-op babies ask their owner. Negative ids are procedural items. An info panel's preview counts as one more copy, or +// one less. bool Entity_Player::HasCollectible(int collectibleType, ItemCheck check) { ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleType); @@ -92,6 +93,8 @@ bool Entity_Player::HasCollectible(int collectibleType, ItemCheck check) Entity_Player& owner = *item_owner_get(this); Game& game = *g_game; if (owner.isCoopGhost && !game.deathmatchManager.is_active() && !is_quest_item(item)) return false; + bool isPreviewed = owner.previewCollectible != 0 && collectibleType == owner.previewCollectible; + if (isPreviewed && owner.isPreviewAdded) return true; if (collectibleType < 0) { auto found = owner.proceduralItems.find(collectibleType); @@ -99,7 +102,7 @@ bool Entity_Player::HasCollectible(int collectibleType, ItemCheck check) } if (check == ITEM_CHECK_MODIFIED) if (std::optional lent = owner.collectible_lent(collectibleType, *item)) return *lent; - return owner.collectibleCounts[collectibleType] > 0; + return owner.collectibleCounts[collectibleType] > (isPreviewed ? 1 : 0); } // Whether something other than owning it decides that the player has a collectible, as HasCollectible checks after @@ -204,6 +207,8 @@ int Entity_Player::GetCollectibleNum(int collectibleId, ItemCheck check) ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); int count = item && item->type == ITEM_ACTIVE ? 0 : collectibleCounts[collectibleId]; + if (previewCollectible != 0 && previewCollectible == collectibleId) + count = isPreviewAdded ? count + 1 : std::max(count - 1, 0); if (isCoopGhost && !is_quest_item(item)) return 0; for (ActiveItemDesc& active : activeItems) if (active.item != 0 && active.item == collectibleId) count++; @@ -337,10 +342,13 @@ void Entity_Player::apply_innate_collectibles() } // 00771550 Whether the player has a trinket: held or smelted, or lent by the items that copy trinkets. ITEM_CHECK_OWNED -// only looks at the held slots, the second one only with Mom's Purse or Belly Button. +// only looks at the held slots, the second one only with Mom's Purse or Belly Button. An info panel's preview counts as +// one more copy, or one less. bool Entity_Player::HasTrinket(uint32_t trinketType, ItemCheck check) { - if (check == ITEM_CHECK_MODIFIED) return GetTrinketMultiplier(trinketType) > 0; + bool isPreviewed = previewTrinket != 0 && previewTrinket == trinketType; + if (isPreviewed && isPreviewAdded) return true; + if (check == ITEM_CHECK_MODIFIED) return GetTrinketMultiplier(trinketType) > (isPreviewed ? 1 : 0); int slots = HasCollectible(COLLECTIBLE_MOMS_PURSE) || HasCollectible(COLLECTIBLE_BELLY_BUTTON) ? 2 : 1; for (int i = 0; i < slots; i++) @@ -360,7 +368,7 @@ int Entity_Player::GetTrinketMultiplier(uint32_t trinketType) int multiplier = trinketType == TRINKET_LIL_LARVA && owner.playerType == PLAYER_BLUEBABY ? 1 : 0; if (owner.hasCurseMistEffect || owner.isCoopGhost) return multiplier; - if (game.dailyChallenge._specialDailyId == DAILY_RAINBOW_TRINKETS && + if (game.dailyChallenge.specialDailyId == DAILY_RAINBOW_TRINKETS && std::ranges::find(RAINBOW_WORM_TRINKETS, (int)id) != RAINBOW_WORM_TRINKETS.end()) multiplier++; @@ -372,11 +380,17 @@ int Entity_Player::GetTrinketMultiplier(uint32_t trinketType) for (int i = 0; i < slots; i++) if ((owner.trinkets[i] & TRINKET_ID_MASK) == id) multiplier += owner.trinkets[i] & TRINKET_GOLDEN_FLAG ? 2 : 1; ItemConfig_Item* queued = owner.queuedItem.item; - if (queued && queued->type == ITEM_TRINKET && (uint32_t)queued->id == id) + bool isQueuedCounted = owner.previewTrinket == 0 || owner.previewTrinket == id; + if (queued && queued->type == ITEM_TRINKET && (uint32_t)queued->id == id && isQueuedCounted) multiplier += owner.queuedItem.flags & QUEUED_GOLDEN ? 2 : 1; if (id < owner.smeltedTrinkets.size()) multiplier += owner.smeltedTrinkets[id].count + owner.smeltedTrinkets[id].goldenCount * 2; if (id < owner.extraTrinketCounts.size() && owner.extraTrinketCounts[id] != 0) multiplier++; + if (owner.previewTrinket != 0 && (owner.previewTrinket & TRINKET_ID_MASK) == id) + { + int copies = owner.previewTrinket & TRINKET_GOLDEN_FLAG ? 2 : 1; + multiplier = owner.isPreviewAdded ? multiplier + copies : std::max(multiplier - copies, 0); + } if (multiplier > 0 && owner.HasCollectible(COLLECTIBLE_MOMS_BOX)) multiplier++; return multiplier; } @@ -1388,7 +1402,7 @@ static void collectible_effect_apply(Entity_Player& p, const CollectibleGain& ga game.ApplyBlueMapEffect(); return; case 381: - if (isFirst && game.challenge == 0 && game.dailyChallenge._id == 0) + if (isFirst && game.challenge == 0 && game.dailyChallenge.id == 0) g_manager->persistentGameData.eventCounters[EVENT_EDENS_BLESSING]++; return; case 412: @@ -1471,7 +1485,7 @@ static void collectible_effect_apply(Entity_Player& p, const CollectibleGain& ga case 721: late_collectible_gain(p, gain.type, isFirst); return; - case 619: return birthright_gain(p, isFirst); + case 619: return birthright_gain(p, rng, isFirst); case 644: if (isFirst) consolation_prize_gain(p, rng); return; @@ -1687,7 +1701,7 @@ void Entity_Player::AddCostume(ItemConfig_Item* item, bool isItemStateOnly) costume.isOverwriteColor = item->costume.isOverwriteColor; costume.isItemStateOnly = isItemStateOnly; costume.playerType = -1; - if (g_game->dailyChallenge._specialDailyId == SPECIAL_DAILY_COSTUME_PRIORITY && item->IsCollectible() && + if (g_game->dailyChallenge.specialDailyId == SPECIAL_DAILY_COSTUME_PRIORITY && item->IsCollectible() && item->id == COLLECTIBLE_SACK_HEAD_COSTUME) costume.priority += DAILY_COSTUME_PRIORITY_BONUS; costume.sprite.Load(item->costume.anm2Path, GRAPHICS_DEFER); diff --git a/src/entity_player_pockets.cpp b/src/entity_player_pockets.cpp index 2c4e2ac..438d063 100644 --- a/src/entity_player_pockets.cpp +++ b/src/entity_player_pockets.cpp @@ -236,9 +236,9 @@ void Entity_Player::AnimateCard(int cardId, std::string_view animName) reconstruction_missing("Entity_Player::AnimateCard 007ab6b0 (a mod's card front)"); heldSprite.Reset(); - heldSprite.Load("gfx/ui/ui_cardspills.anm2", GRAPHICS_LOAD); + heldSprite.Load(CARDS_PILLS_ANM2, GRAPHICS_LOAD); heldSprite.Play("Sparkle"); - overlay_frame_set(heldSprite, "CardFronts", (float)cardId); + overlay_frame_set(heldSprite, ANIMATION_CARD_FRONTS, (float)cardId); bool isFrontShown = false; for (int layer = 0; layer < (int)heldSprite.layerStates.size(); layer++) { @@ -252,7 +252,7 @@ void Entity_Player::AnimateCard(int cardId, std::string_view animName) { heldSprite.Load(pickup->anm2Path, GRAPHICS_LOAD); heldSprite.Play("Sparkle"); - overlay_frame_set(heldSprite, "HUD", 0); + overlay_frame_set(heldSprite, ANIMATION_HUD, 0); } heldSprite.offset = vector_make(0, CARD_HELD_RISE); PlayExtraAnimation(animName); @@ -266,22 +266,35 @@ void Entity_Player::AnimatePill(int pillColor, std::string_view animName) { heldSprite.Load(pill->anm2Path, GRAPHICS_LOAD); heldSprite.Play("Sparkle"); - overlay_frame_set(heldSprite, "HUD", 0); + overlay_frame_set(heldSprite, ANIMATION_HUD, 0); } heldSprite.offset = vector_make(0, CARD_HELD_RISE); PlayExtraAnimation(animName); } -// The pocket part of 006e8ae0: a free hand takes a card (its name and description shown, but for Jacob and Esau) or a -// pill, holding it up. Whether it was taken. The challenge that turns cards into items and the seeds that hide or -// scramble the text are not written yet. +// A pocket item's name or description as the HUD shows it, its #keys looked up in the "PocketItems" string table. +static std::string pocket_text(std::string_view text) +{ + bool isMissing = false; + if (text.empty() || text[0] != '#') return std::string(text); + + StringTable& table = g_manager->stringTable; + std::string_view localized = table.get_string("PocketItems", table.language, text.substr(1), &isMissing); + return std::string(isMissing ? text : localized); +} + +// The pocket part of 006e8ae0: a free hand takes a card (its name and description shown, but for Jacob and Esau, +// hidden or scrambled by the seeds) or a pill, holding it up. Cantripped's cards are items, put in front of the hand. +// Whether it was taken. bool pocket_item_collect(Entity_Pickup& pocket, Entity_Player& player) { - constexpr int CHALLENGE_CARDS_AS_ITEMS = 43; - if (player.IsHoldingItem()) return false; - if (g_game->challenge == CHALLENGE_CARDS_AS_ITEMS) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0 (a card as an item)"); + if (g_game->challenge == CHALLENGE_CANTRIPPED) + { + uint32_t item = player.AddItemCard((uint32_t)pocket.subtype & ~CARD_ITEM_FLAG); + if (item != 0) player.AnimateCollectible((int)item, "UseItem", "PlayerPickupSparkle"); + return item != 0; + } if (pocket.variant == PICKUP_PILL) { player.AddPocketItem(pocket.subtype, POCKET_PILL); @@ -295,9 +308,19 @@ bool pocket_item_collect(Entity_Pickup& pocket, Entity_Player& player) if (player.playerType == PLAYER_JACOB || player.playerType == PLAYER_ESAU || !card) return true; Seeds& seeds = g_game->seedEffects; - if (seeds.HasSeedEffect(SEED_MYSTERY_TAROT_CARDS) || seeds.HasSeedEffect(SEED_DYSLEXIA)) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0 (a card's hidden or scrambled text)"); - g_game->hud.show_pill_name(&player, card->GetName().c_str(), card->description_get().c_str()); + std::string name = card->GetName(); + std::string description = card->description_get(); + if (seeds.HasSeedEffect(SEED_MYSTERY_TAROT_CARDS)) + { + name = pocket_text("#QUESTION_MARKS_NAME"); + description.clear(); + } + if (seeds.HasSeedEffect(SEED_DYSLEXIA)) + { + name = string_scramble_seeded(name); + description = string_scramble_seeded(description); + } + g_game->hud.show_pill_name(&player, name.c_str(), description.c_str()); return true; } @@ -340,17 +363,6 @@ void tears_up_unlock_check(Entity_Player& player) if (tearsUps >= TEARS_UP_UNLOCK_COUNT) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_TEARS_UP_ITEMS); } -// The pill's name and description as the HUD shows them, its #keys looked up in the "PocketItems" string table. -static std::string pocket_text(std::string_view text) -{ - bool isMissing = false; - if (text.empty() || text[0] != '#') return std::string(text); - - StringTable& table = g_manager->stringTable; - std::string_view localized = table.get_string("PocketItems", table.language, text.substr(1), &isMissing); - return std::string(isMissing ? text : localized); -} - // 007c4180 Uses a pill effect: the screen blooms, the pill color is identified (a golden pill changes the pools // instead), its name shows and its use counts, its effect runs, the announcer names it now and then and the mods see // it. A horse pill doubles the count and swaps the thumbs' sounds for louder ones. False PHD turns a bad pill into a @@ -549,7 +561,7 @@ uint32_t Entity_Player::AddItemCard(uint32_t itemId) } if (itemCards.size() >= item_cards_max(*this)) return 0; - if (itemId == 0) reconstruction_missing("ItemPool::GetCardImpl 007376c0 (the item card pool)"); + if (itemId == 0) itemId = (uint32_t)ItemPool::GetCardImpl(GetCollectibleRNG(COLLECTIBLE_BAG_OF_CRAFTING).Next()); 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 407444e..62b47d3 100644 --- a/src/entity_player_room.cpp +++ b/src/entity_player_room.cpp @@ -41,7 +41,6 @@ constexpr int DOOR_STOP_UNLOCK_COPIES = 3; constexpr int DOOR_STOP_BOSS_RUSH_COPIES = 2; constexpr float DOOR_STOP_REACH_SQUARED = 10000; constexpr float DOOR_ENTER_OFFSET = 40; -constexpr uint32_t DOOR_SIDES = 4; // The grid entities Dog Tooth howls at when the floor's crawlspace rock hides there. constexpr GridEntityType DOG_TOOTH_ROCKS[] = {GRID_ROCK, GRID_ROCKT, GRID_ROCK_BOMB, diff --git a/src/entity_player_tears.cpp b/src/entity_player_tears.cpp index 0877f80..84a8322 100644 --- a/src/entity_player_tears.cpp +++ b/src/entity_player_tears.cpp @@ -114,7 +114,6 @@ constexpr int COLLECTIBLE_CUPIDS_ARROW = 48; constexpr int COLLECTIBLE_PACT = 80; constexpr int COLLECTIBLE_SPIDER_BITE = 89; constexpr int COLLECTIBLE_SMALL_ROCK = 90; -constexpr int COLLECTIBLE_COMMON_COLD = 103; constexpr int COLLECTIBLE_MOMS_CONTACTS = 110; constexpr int COLLECTIBLE_STIGMATA = 138; constexpr int COLLECTIBLE_TOUGH_LOVE = 150; @@ -135,8 +134,6 @@ constexpr int COLLECTIBLE_HOLY_LIGHT = 374; constexpr int COLLECTIBLE_PUPULA_DUPLEX = 379; constexpr int COLLECTIBLE_GODS_FLESH = 398; constexpr int COLLECTIBLE_EXPLOSIVO = 401; -constexpr int COLLECTIBLE_COMPOUND_FRACTURE = 453; -constexpr int COLLECTIBLE_SINUS_INFECTION = 459; constexpr int COLLECTIBLE_PARASITOID = 461; constexpr int COLLECTIBLE_EYE_OF_BELIAL = 462; constexpr int COLLECTIBLE_SULFURIC_ACID = 463; diff --git a/src/entity_player_trinkets.cpp b/src/entity_player_trinkets.cpp index 8b6ce56..aba4ee7 100644 --- a/src/entity_player_trinkets.cpp +++ b/src/entity_player_trinkets.cpp @@ -98,13 +98,13 @@ void Entity_Player::remove_wooden_cross_mantles() holyMantleStacks = (uint8_t)((holyMantleStacks & MANTLE_STACK_LOW) | (lent << MANTLE_STACK_HIGH_SHIFT)); } -// 00771620 Whether the player holds the trinket golden, in a slot or smelted. -// The original also reads a trinket slot only the constructor writes, always empty. +// 00771620 Whether the player holds the trinket golden, in a slot or smelted, or previews it golden. bool Entity_Player::HasGoldenTrinket(uint32_t trinketId) { for (int i = 0; i < GetMaxTrinkets(); i++) if ((trinkets[i] & TRINKET_ID_MASK) == trinketId && (trinkets[i] & TRINKET_GOLDEN_FLAG)) return true; - return trinketId < smeltedTrinkets.size() && smeltedTrinkets[trinketId].goldenCount > 0; + if (trinketId < smeltedTrinkets.size() && smeltedTrinkets[trinketId].goldenCount > 0) return true; + return (previewTrinket & TRINKET_ID_MASK) == trinketId && (previewTrinket & TRINKET_GOLDEN_FLAG); } // 007716f0 Whether the player can take a trinket: a free slot, or one holding a trinket that may be swapped out. The @@ -662,7 +662,7 @@ static void divorce_papers_gain(Entity_Player& player, RNG& rng) player.AddBoneHearts(1); Game& game = *g_game; bool isAllowed = g_manager->persistentGameData.achievements[ACHIEVEMENT_MYSTERIOUS_PAPER] || - (g_manager->state == MANAGER_STATE_GAME && (game.dailyChallenge._id != 0 || game.isDebug)); + (g_manager->state == MANAGER_STATE_GAME && (game.dailyChallenge.id != 0 || game.isDebug)); if (!isAllowed || !game.itemPool.RemoveTrinket(TRINKET_MYSTERIOUS_PAPER)) return; Vector position = room_free_pickup_position_find({.position = player.pos, .step = GAIN_PICKUP_STEP}); game.Spawn({.position = position, .subType = TRINKET_MYSTERIOUS_PAPER, .type = ENTITY_PICKUP, diff --git a/src/entity_player_update.cpp b/src/entity_player_update.cpp index c45ff7b..c7bc540 100644 --- a/src/entity_player_update.cpp +++ b/src/entity_player_update.cpp @@ -132,6 +132,8 @@ constexpr int ACHIEVEMENT_HALF_HEART_FLOORS = 329; constexpr int TRAIL_FRAMES_MAX = 900; constexpr int VOID_STAGE = 12; constexpr int VOID_HALLUCINATION_PERIOD = 150; +// An extra player rides up to the enemy it controls this much of the way more each frame. +constexpr float EXTRA_PLAYER_RIDE_STEP = 0.1f; constexpr int VOID_HALLUCINATION_ODDS = 75; constexpr int VOID_HALLUCINATION_ODDS_PER_ROOM = 105; constexpr int VOID_HALLUCINATION_FRAMES = 30; @@ -573,7 +575,7 @@ static void how_to_jump_update(Entity_Player& player) Vector leap = vector_scale(vector_sub(player.targetPosition, player.pos), progress * progress); player.pos = vector_add(player.pos, leap); player.velocity = {}; - if (g_game->dailyChallenge._specialDailyId != HOW_TO_JUMP_SPECIAL_DAILY || jump->cooldown != 1) return; + if (g_game->dailyChallenge.specialDailyId != HOW_TO_JUMP_SPECIAL_DAILY || jump->cooldown != 1) return; auto* wave = static_cast(g_game->Spawn({.position = player.pos, .spawner = &player, @@ -1048,6 +1050,31 @@ static void living_frame_update(Entity_Player& player) moms_hand_player_release_update(player); } +// An extra player's frame: offline it rides the enemy it controls, closing in over ten frames, or takes the first valid +// enemy of the room and jumps onto it. Online the original first checks its controller's device, not reconstructed. +static void extra_player_update(Entity_Player& player) +{ + if (g_manager->netplayManager.is_online()) + reconstruction_missing("Entity_Player::Update 00782af0 (an online extra player)"); + if (Entity* ridden = player.target.get()) + { + player.targetPosition.x = std::min(player.targetPosition.x + EXTRA_PLAYER_RIDE_STEP, 1.0f); + vector_lerp(player.pos, ridden->pos, player.targetPosition.x); + player.velocity = {}; + return; + } + for (Entity* entity : g_game->room->entityList.updateEL) + { + Entity* enemy = entity->to_npc_or_coop_player(); + if (!enemy || !enemy->is_valid_target()) continue; + player.target = enemy; + player.pos = enemy->pos; + player.velocity = {}; + player.targetPosition.x = 1; + return; + } +} + // 00782af0 The player's frame. It rides along with what it carries, catches up with the room's mist and pending floor // starts, falls, builds up poison, moves as an entity, reacts to hurts, then runs its living frame or its death, its // items' animations, footprints, sounds, bleeding, status effect and the Void's hallucination, and calls @@ -1069,7 +1096,7 @@ void Entity_Player::Update() } curse_mist_update(*this); equality_update(*this); - if (variant == PLAYER_VARIANT_EXTRA) reconstruction_missing("Entity_Player::Update 00782af0 (an extra player)"); + if (variant == PLAYER_VARIANT_EXTRA) return extra_player_update(*this); if (!isExists) return; riders_update(*this); diff --git a/src/entity_player_weapons.cpp b/src/entity_player_weapons.cpp index b7e37ff..fe43a39 100644 --- a/src/entity_player_weapons.cpp +++ b/src/entity_player_weapons.cpp @@ -70,7 +70,6 @@ constexpr float TECH_X_RING_LIFT = -20; constexpr int COLLECTIBLE_BRIMSTONE_WEAPON = 118; constexpr int COLLECTIBLE_CURSED_EYE_WEAPON = 316; -constexpr int COLLECTIBLE_DEAD_TOOTH = 446; constexpr float DEAD_TOOTH_RING_SCALE = 0.8f; constexpr int LARGE_ZIT_INTERVAL = 30; constexpr uint32_t LARGE_ZIT_ODDS = 3; @@ -544,7 +543,7 @@ Vector Entity_Player::GetLaserOffset(int laserOffsetId, const Vector& shootDirec // 007aab70 Fires a Technology laser from the player: from an eye's offset along a direction, lasting three frames, // in the player's laser color with its laser hit params (Technology 2's with the player's damage, one of Tech.5's in -// twenty with a random flag of its own), drawn behind the head when it fires up or away from the eye. +// twenty with a random flag of the first 64 only), drawn behind the head when it fires up or away from the eye. Entity_Laser* Entity_Player::FireTechLaser(const TechLaserShot& shot) { Vector offset = GetLaserOffset(shot.offsetId, shot.direction); @@ -563,7 +562,8 @@ Entity_Laser* Entity_Player::FireTechLaser(const TechLaserShot& shot) if (shot.offsetId == LASER_OFFSET_TECH5 && Random() % TECH5_FLAG_ROLL < TECH5_FLAG_CHANCE) { flags.reset(); - flags.set(Random() % TECH5_FLAG_COUNT); + uint32_t bit = Random() % TECH5_FLAG_COUNT; + if (bit < TECH5_FLAG_REACH) flags.set(bit); } laser->tearFlags = flags; laser->SetColor(laserColor, -1, COLOR_PRIORITY_DEFAULT, false, true); diff --git a/src/entity_projectile.cpp b/src/entity_projectile.cpp index 2e8aa31..777ba3a 100644 --- a/src/entity_projectile.cpp +++ b/src/entity_projectile.cpp @@ -1,4 +1,5 @@ #include "entity_projectile.h" +#include "boss_ai.h" #include "boss_repentance.h" #include "entity_bomb.h" #include "entity_combat.h" @@ -6,8 +7,10 @@ #include "entity_effect_combat.h" #include "entity_familiar.h" #include "entity_knife.h" +#include "entity_laser.h" #include "entity_pickup.h" #include "entity_player.h" +#include "entity_tear.h" #include "game.h" #include "grid_entity.h" #include "lua_callbacks.h" @@ -49,8 +52,7 @@ constexpr uint64_t CHANGE_BOTH_FLAGS = PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT | PROJECTILE_CHANGE_VELOCITY_AFTER_TIMEOUT; constexpr uint64_t BURST3_CHILD_CLEARED = PROJECTILE_CURVE_LEFT | PROJECTILE_CURVE_RIGHT | PROJECTILE_SINE_VELOCITY; -// The flags whose effects belong to the late bosses and items, and are not reconstructed. -constexpr uint64_t UNRECONSTRUCTED_FLAGS = PROJECTILE_STASIS | PROJECTILE_LASER_SHOT; +// The flags whose shots leave fire waves or fires where they land. constexpr uint64_t FIRE_FLAGS = PROJECTILE_FIRE_WAVE | PROJECTILE_FIRE_WAVE_X | PROJECTILE_FIRE_SPAWN; // The glow a fiery, Heretic's, blue fire or side wave shot carries. @@ -372,7 +374,6 @@ constexpr int SOUND_BEAST_FIRE = 700; constexpr int COLLECTIBLE_SOUL = 335; constexpr int COLLECTIBLE_BETRAYAL = 391; -constexpr int COLLECTIBLE_CIRCLE_OF_PROTECTION = 423; constexpr uint32_t CHALLENGE_BROKEN_WATCH = 22; // The familiars shots hurt (the two Infamy guards as the player does), and the subtype of the one that is spared. @@ -753,19 +754,14 @@ static void fly_ball_update(Entity_Projectile& ball) if (ball.GetIntervalTicks(4, 0) && fly_ball_flies(ball).empty()) ball.Remove(); } -// and its splash once it has died. A shot the Broken Modem froze waits, then vanishes. +// 00653070 A shot's frame: its look, trails, homing, steering, speed and fall, what its flags do on the way and its +// splash once it has died. A shot the Broken Modem froze waits, then vanishes, and one held in stasis floats by its +// parent. void Entity_Projectile::Update() { speedMultiplier = time_scale_get(); if (pauseTimer > 0) pauseTimer--; if (projectileFlags & GRID_PASS_FLAGS) isCollidesWithGrid = false; - if (projectileFlags & UNRECONSTRUCTED_FLAGS) - { - char name[96]; - std::snprintf(name, sizeof(name), "Entity_Projectile::Update 00653070: the projectile flags %llx", - (unsigned long long)(projectileFlags & UNRECONSTRUCTED_FLAGS)); - reconstruction_missing(name); - } if (modem_freeze_update()) return; animation_update(); @@ -790,6 +786,7 @@ void Entity_Projectile::Update() fly_orbit_update(*this); trails_update(); if (isDead) return death_update(); + if ((projectileFlags & PROJECTILE_STASIS) && stasis_update()) return lua_engine_get().PostProjectileUpdate(this); if (motionHook) motionHook(*this, PROJECTILE_STEP_UPDATE); homing_update(); @@ -801,6 +798,51 @@ void Entity_Projectile::Update() lua_engine_get().PostProjectileUpdate(this); } +// Stasis: a shot held by its parent drifts back toward 50 from it, carried along with it, settling to its usual +// height and flashing every 8 frames, until its timed change. It then flies off the way it last faced from the parent +// at its changed speed. Whether it was held, which ends its frame. +bool Entity_Projectile::stasis_update() +{ + constexpr float HOLD_DISTANCE = 50; + constexpr float HOLD_PULL = 0.1f; + constexpr float HOLD_EASE = 0.3f; + constexpr float HEIGHT_EASE = 0.4f; + constexpr int STASIS_FLASH_FRAMES = 8; + constexpr int STASIS_FLASH_DURATION = 4; + constexpr float RELEASE_CURVE = 0.015f; + constexpr ColorMod STASIS_FLASH_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.35f, 0.45f, 0.5f}}; + + bool isChangeDue = changeTimeout < 1 || GetIntervalTicks((float)changeTimeout, 0) != 0; + bool isReleased = (projectileFlags & PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT) && FrameCount() > 0 && isChangeDue; + if (!parent || isReleased) + { + velocity = vector_scale(vector_from_angle(curvingStrength), changeVelocity); + curvingStrength = RELEASE_CURVE; + return false; + } + + Vector away = vector_sub(vector_add(pos, velocity), parent->pos); + float distance = vector_length(away); + if (distance != 0) + { + Vector direction = vector_scale(away, 1 / distance); + curvingStrength = vector_angle(direction); + velocity = vector_sub(velocity, targetPosition); + vector_lerp(velocity, vector_scale(direction, (HOLD_DISTANCE - distance) * HOLD_PULL), HOLD_EASE); + velocity = vector_add(velocity, parent->velocity); + targetPosition = parent->velocity; + } + height = lerp(height, HEIGHT_START, HEIGHT_EASE); + update_height_collision(); + if (IsFrame(STASIS_FLASH_FRAMES, 0)) + { + ColorMod flash = STASIS_FLASH_COLOR; + color_multiply(flash, color); + SetColor(flash, STASIS_FLASH_DURATION, COLOR_PRIORITY, true, true); + } + return true; +} + // The Broken Modem's freeze: a frozen shot vanishes after a while, and waits in place until then. Whether it did. bool Entity_Projectile::modem_freeze_update() { @@ -1200,11 +1242,53 @@ void Entity_Projectile::death_update() death_bursts_spawn(); if (projectileFlags & PROJECTILE_BLUE_FIRE_SPAWN) blue_fire_spawn(); if (projectileFlags & PROJECTILE_FIRE_SPAWN) fire_spawn(); + if (projectileFlags & PROJECTILE_LASER_SHOT) laser_shot_dot_spawn(); + if (projectileFlags & PROJECTILE_SIDE_WAVE) side_wave_burst(); if (variant == PROJECTILE_HEAD) head_splash(); Remove(); if (variant == PROJECTILE_FIRE && spawnerType == ENTITY_BEAST) npc_sound_play(SOUND_BEAST_FIRE, 1, 2, 1); } +// Part of 00653070: a dead laser shot leaves a Tech dot shining toward its target (found anywhere when it had none), +// or back the way it came. +void Entity_Projectile::laser_shot_dot_spawn() +{ + constexpr float LASER_SHOT_RANGE = 5000; + constexpr int TECH_DOT_SHOT = 1; + constexpr ColorMod TECH_DOT_COLOR = {{1, 1, 1, 1}, {2.5f, 2.5f, 2.5f, 1}, {0, 0, 0}}; + + if (!target) target_find(LASER_SHOT_RANGE); + Entity_Effect* dot = effect_spawn(EFFECT_TECH_DOT, pos, spawnerEntity, TECH_DOT_SHOT); + dot->sprite.color = TECH_DOT_COLOR; + dot->targetPosition = target ? vector_normalized(vector_sub(target->pos, pos)) + : vector_scale(vector_normalized(velocity), -1); + dot->Update(); +} + +// Part of 00653070: a dead side wave shot bursts in a splash into five shots fanned back the way it came, 24 apart, +// aimed at it and tinted its color. +void Entity_Projectile::side_wave_burst() +{ + constexpr int SIDE_FAN_SIDE = 2; + constexpr float SIDE_FAN_TURN = 24; + constexpr float SIDE_FAN_SPEED = 10; + + Vector back = vector_scale(vector_normalized(velocity), -1); + npc_sound_play(SOUND_DEATH_BURST_SMALL, 1, 2, 1); + effect_spawn(EFFECT_BLOOD_EXPLOSION, pos, nullptr, BLOOD_EXPLOSION_SPLASH)->Update(); + for (int i = -SIDE_FAN_SIDE; i <= SIDE_FAN_SIDE; i++) + { + uint32_t seed = Random(); + Vector shotVelocity = vector_scale(vector_rotated(back, (float)i * SIDE_FAN_TURN), SIDE_FAN_SPEED); + Entity* shot = g_game->Spawn({.position = pos, .velocity = shotVelocity, .spawner = spawnerEntity, + .type = ENTITY_PROJECTILE, .seed = seed}); + shot->target = this; + shot->parent = parent.get(); + shot->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + shot->Update(); + } +} + // Part of 00653070: whether the shot is on the players' side, which its fires take. bool Entity_Projectile::is_friendly_fire() { @@ -1289,6 +1373,98 @@ void Entity_Projectile::fire_spawn() .timeoutRange = RED_FLAME_TIMEOUT_RANGE}); } +// 0065ad30 (misnamed reroll_entity_to_free_tile) A tick of the lava the Beast's fire ball raised: a pair of glowing +// lava shots thrown up either side, as far out as its state counts in cells and slower the farther, then the next. +static void beast_lava_tick(Entity_Effect* timer) +{ + constexpr float RISE_PER_STEP = 3; + constexpr float RISE_BASE = -30; + constexpr float LAVA_SHOT_SCALE = 1.5f; + constexpr ColorMod LAVA_SHOT_COLOR = {{2, 2, 2, 1}, {0, 0, 0, 0}, {0.4f, 0.12f, -0.3f}}; + + for (int side = -1; side <= 1; side += 2) + { + Vector position = vector_make((float)side * (float)timer->state * GRID_CELL_SIZE + timer->pos.x, timer->pos.y); + float jitter = random_unit(); + float rise = (float)timer->state * RISE_PER_STEP + RISE_BASE + (jitter + jitter); + auto* shot = static_cast(g_game->Spawn( + {.position = position, .velocity = vector_make(0, rise), .type = ENTITY_PROJECTILE, .seed = Random()})); + shot->scale = LAVA_SHOT_SCALE; + shot->spawnerEntity = timer->spawnerEntity; + shot->spawnerType = timer->spawnerType; + shot->spawnerVariant = timer->spawnerVariant; + shot->SetColor(LAVA_SHOT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + shot->fallingSpeed = 0; + shot->fallingAccel = 1; + shot->Update(); + } + timer->state++; +} + +// Part of 00653070: the Beast's fire ball bursts with a shake into fourteen rising smoke clouds and as many lava shots +// thrown up around it. Over the lava, the lava rises either side in four ticks. +void Entity_Projectile::beast_fire_ball_burst() +{ + constexpr int FIRE_BALL_SHAKE = 8; + constexpr int FIRE_BALL_BURSTS = 14; + constexpr float SMOKE_RISE = -2; + constexpr float SMOKE_RISE_STEP = 7; + constexpr float SMOKE_SPREAD = 10; + constexpr float FIRE_BALL_SMOKE_SCALE_MIN = 1.2f; + constexpr float SMOKE_SCALE_RANGE = 0.3f; + constexpr int SMOKE_TIMEOUT = 360; + constexpr float SHOT_RISE_MIN = -10; + constexpr float SHOT_RISE_RANGE = 28; + constexpr float SHOT_SPREAD_X = 60; + constexpr float SHOT_SPREAD_Y = 20; + constexpr float FIRE_BALL_SHOT_SCALE_MIN = 1; + constexpr float SHOT_SCALE_RANGE = 0.7f; + constexpr uint32_t LAVA_TICK_DELAY = 5; + constexpr uint32_t LAVA_TICKS = 4; + + game_shake_screen(FIRE_BALL_SHAKE); + for (int i = 0; i < FIRE_BALL_BURSTS; i++) + { + uint32_t smokeSeed = Random(); + Vector smokeVelocity = vector_make(0, SMOKE_RISE - (float)i * SMOKE_RISE_STEP); + Vector smokePosition = vector_add(pos, vector_scale(random_direction(), SMOKE_SPREAD)); + Entity* smoke = g_game->Spawn({.position = smokePosition, .velocity = smokeVelocity, .spawner = spawnerEntity, + .type = ENTITY_EFFECT, .variant = EFFECT_SMOKE_CLOUD, .seed = smokeSeed}); + smoke->spawnerType = spawnerType; + smoke->spawnerVariant = spawnerVariant; + float smokeScale = random_unit() * SMOKE_SCALE_RANGE + FIRE_BALL_SMOKE_SCALE_MIN; + smoke->sprite.scale = vector_make(smokeScale, smokeScale); + smoke->Update(); + static_cast(smoke)->SetTimeout(SMOKE_TIMEOUT); + + uint32_t shotSeed = Random(); + Vector shotVelocity = vector_make(0, SHOT_RISE_MIN - random_unit() * SHOT_RISE_RANGE); + float offsetY = random_unit() * SHOT_SPREAD_Y - SHOT_SPREAD_Y * HALF; + float offsetX = random_unit() * SHOT_SPREAD_X - SHOT_SPREAD_X * HALF; + Vector shotPosition = vector_add(pos, vector_make(offsetX, offsetY)); + auto* shot = static_cast(g_game->Spawn( + {.position = shotPosition, .velocity = shotVelocity, .type = ENTITY_PROJECTILE, .seed = shotSeed})); + shot->scale = random_unit() * SHOT_SCALE_RANGE + FIRE_BALL_SHOT_SCALE_MIN; + shot->spawnerEntity = spawnerEntity.get(); + shot->spawnerType = spawnerType; + shot->spawnerVariant = spawnerVariant; + shot->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + shot->fallingSpeed = 0; + shot->fallingAccel = 1; + shot->Update(); + } + + float lavaLine = g_game->room->get_lava_line_y(); + if (pos.y < lavaLine) return; + Entity_Effect* lava = + Entity_Effect::CreateTimer(reinterpret_cast(&beast_lava_tick), LAVA_TICK_DELAY, LAVA_TICKS, false); + lava->spawnerEntity = spawnerEntity.get(); + lava->spawnerType = spawnerType; + lava->spawnerVariant = spawnerVariant; + lava->pos = vector_make(pos.x, lavaLine); + lava->state = 1; +} + // Part of 00653070: a Heretic's fireball bursts into six purple fire shots. void Entity_Projectile::heretic_burst_spawn() { @@ -1323,8 +1499,7 @@ void Entity_Projectile::death_poof_spawn() .radius = EXPLOSION_RADIUS}); projectileFlags &= ~PROJECTILE_EXPLODE; if (spawnerType == ENTITY_HERETIC) heretic_burst_spawn(); - if (spawnerType == ENTITY_BEAST && spawnerVariant == BEAST_FIRE_BALL) - reconstruction_missing("Entity_Projectile::Update 00653070: the Beast's exploding shot"); + if (spawnerType == ENTITY_BEAST && spawnerVariant == BEAST_FIRE_BALL) beast_fire_ball_burst(); } else if (is_listed(POOF_VARIANTS, variant)) { @@ -1626,20 +1801,20 @@ void Entity_Projectile::death_bursts_spawn() } } +// The shot's next target within a range: the nearest enemy for a friendly shot (charmed shooter or one that cannot +// hit the player), else the player its shooter would go after. +void Entity_Projectile::target_find(float range) +{ + bool isFriendly = (spawnerEntity && spawnerEntity->HasEntityFlags(FLAG_CHARM)) || + (projectileFlags & PROJECTILE_CANT_HIT_PLAYER); + target = isFriendly ? game_nearest_enemy(pos, spawnerEntity, range) + : game_nearest_target_player(pos, spawnerEntity, false, true, range); +} + // Homing: SMART_PERFECT turns straight at its target, SMART pulls toward a near one (purple while it does). A // friendly shot goes after enemies. void Entity_Projectile::homing_update() { - auto target_find = [this](float range) - { - bool isFriendly = (spawnerEntity && spawnerEntity->HasEntityFlags(FLAG_CHARM)) || - (projectileFlags & PROJECTILE_CANT_HIT_PLAYER); - if (isFriendly) - reconstruction_missing("Entity_Projectile::Update 00653070: a friendly shot's nearest enemy " - "(Game::GetNearestEnemy 00707370)"); - target = game_nearest_target_player(pos, spawnerEntity, false, true, range); - }; - if (projectileFlags & PROJECTILE_SMART_PERFECT) { if (!target) target_find(PERFECT_RANGE); @@ -1922,8 +2097,7 @@ void Entity_Projectile::fall_update() { RNG rng; rng.SetSeed(initSeed, CIRCLE_RNG_SHIFT); - if ((int)rng.RandomInt(CIRCLE_CHANCE) <= CIRCLE_PROC_MAX) - reconstruction_missing("Entity_Projectile::Update 00653070: the Circle of Protection's reflection"); + if ((int)rng.RandomInt(CIRCLE_CHANCE) <= CIRCLE_PROC_MAX) circle_reflect(); } fallingSpeed = speedMultiplier * fallingAccel + speedMultiplier * GRAVITY_PULL + @@ -1939,7 +2113,59 @@ void Entity_Projectile::fall_update() Vector clamped = room.GetClampedPositionImpl(pos, CRAWLSPACE_MARGIN_TOP, CRAWLSPACE_MARGIN, CRAWLSPACE_MARGIN, CRAWLSPACE_MARGIN); if ((clamped.x != pos.x || clamped.y != pos.y) && vector_dot(vector_sub(clamped, pos), velocity) < 0) Remove(); - if (room.IsBeastDungeon()) reconstruction_missing("Entity_Projectile::Update 00653070: the Beast's lava"); + if (room.IsBeastDungeon() && FrameCount() > 2 && velocity.y > 0 && pos.y > room.get_lava_line_y()) lava_sink(); +} + +// Circle of Protection: a shot inside a player's light ring becomes that player's homing tear (a plain one's without +// a player), flying back the way it came at its height and fall, purple. +void Entity_Projectile::circle_reflect() +{ + constexpr int LIGHT_RING_CIRCLE = 3; + constexpr ColorMod CIRCLE_TEAR_COLOR = {{0.4f, 0.15f, 0.38f, 1}, {0, 0, 0, 0}, {0.2784314f, 0, 0.454902f}}; + + for (Entity* entity : entity_query(ENTITY_LASER, LASER_LIGHT_RING)) + { + auto& ring = *static_cast(entity); + Vector offset = vector_sub(pos, ring.pos); + if (ring.subtype != LIGHT_RING_CIRCLE || vector_length_squared(offset) >= ring.radius * ring.radius) continue; + + Remove(); + Entity* spawner = ring.spawnerEntity; + auto* player = spawner && spawner->is_player() ? static_cast(spawner) : nullptr; + TearParams params = + player ? player->GetTearHitParams(WEAPON_TEARS, 1, random_below(2) * 2 - 1, nullptr) : TearParams{}; + auto* tear = static_cast(g_game->Spawn({.position = pos, + .velocity = vector_scale(velocity, -1), + .spawner = player, + .type = ENTITY_TEAR, + .seed = Random()})); + tear->SetHeight(height); + tear->fallingSpeed = fallingSpeed; + tear->SetCollisionDamage(params.tearDamage); + tear->SetTearFlags(TearFlags().set(TEAR_HOMING)); + tear->SetScale(params.tearScale); + tear->fallingAccel = fallingAccel; + tear->SetColor(CIRCLE_TEAR_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + tear->parent = player; + tear->Update(); + } +} + +// The Beast's lava swallows a falling shot past its line with a splash (a big one with a sound for the Beast's lava +// ball). An exploding shot dies there instead. +void Entity_Projectile::lava_sink() +{ + if (projectileFlags & PROJECTILE_EXPLODE) + { + isDead = true; + return; + } + + Remove(); + bool isLavaBall = variant == PROJECTILE_LAVA && spawnerType == ENTITY_BEAST; + if (isLavaBall) npc_sound_play(SOUND_BEAST_LAVA_BALL_SPLASH, 1, 2, 1); + int splash = isLavaBall ? POOF02_LAVA_SPLASH_LARGE : POOF02_LAVA_SPLASH; + effect_spawn(EFFECT_POOF02, pos, nullptr, splash)->Update(); } // The rest of its frame: the slowdown's tint, the timed changes, the bounces, its height's collision, The Soul's diff --git a/src/entity_projectile.h b/src/entity_projectile.h index 059565b..302dfbf 100644 --- a/src/entity_projectile.h +++ b/src/entity_projectile.h @@ -212,6 +212,13 @@ private: bool wiggles_update(); void speed_update(); void fall_update(); + void lava_sink(); + void circle_reflect(); + void beast_fire_ball_burst(); + void target_find(float range); + void laser_shot_dot_spawn(); + void side_wave_burst(); + bool stasis_update(); void ground_update(); void late_update(); bool player_hit(Entity_Player& player); diff --git a/src/entity_rock_drop.cpp b/src/entity_rock_drop.cpp index 83e7c70..f38e3db 100644 --- a/src/entity_rock_drop.cpp +++ b/src/entity_rock_drop.cpp @@ -65,7 +65,7 @@ void Entity::DestroyRockGridAt(const Vector& position, GridEntityDesc* desc, Ent explosion_effects({.position = position, .source = source, .damage = LANDED_BLAST_DAMAGE}); if (type == GRID_ROCK_BOMB) return; wood_particles_spawn(position); - return trinket_drop_try(desc->_spawnSeed); + return trinket_drop_try(desc->_spawnSeed, position); } if (is_landed_rock(type)) diff --git a/src/entity_slot.cpp b/src/entity_slot.cpp index 734fb44..f87ca39 100644 --- a/src/entity_slot.cpp +++ b/src/entity_slot.cpp @@ -23,6 +23,13 @@ #include // The run's state flags of a broken or jammed donation machine, and of one blown up. +// The tainted character Home's closet holds for each regular character. +constexpr std::array TAINTED_TWINS = { + PLAYER_ISAAC_B, PLAYER_MAGDALENE_B, PLAYER_CAIN_B, PLAYER_JUDAS_B, PLAYER_BLUEBABY_B, + PLAYER_EVE_B, PLAYER_SAMSON_B, PLAYER_AZAZEL_B, PLAYER_LAZARUS_B, PLAYER_EDEN_B, + PLAYER_THELOST_B, PLAYER_LAZARUS_B, PLAYER_JUDAS_B, PLAYER_LILITH_B, PLAYER_KEEPER_B, + PLAYER_APOLLYON_B, PLAYER_THEFORGOTTEN_B, PLAYER_THEFORGOTTEN_B, PLAYER_BETHANY_B, PLAYER_JACOB_B, + PLAYER_JACOB_B}; constexpr int GAME_STATE_DONATION_SLOT_BROKEN = 17; constexpr int GAME_STATE_DONATION_SLOT_JAMMED = 18; constexpr int GAME_STATE_DONATION_SLOT_BLOWN = 30; @@ -100,7 +107,6 @@ constexpr int SLOT_MACHINE_PEDESTAL = 3; constexpr int CONFESSIONAL_PEDESTAL = 15; constexpr int REVIVE_MACHINE_EXCLUDED_ROOM = -20; -constexpr int DIGIT_BASE = 10; constexpr int HUNDREDS = 100; constexpr int COUNTER_LIMIT = 1000; constexpr int COUNTER_FULL = 999; @@ -174,6 +180,18 @@ constexpr int CRANE_WIN = 25; constexpr int CRANE_LUCK = 5; constexpr int CRANE_PRIZES = 3; constexpr int BETHS_ESSENCE_ODDS = 4; +// Mom's dresser broken: one time in 100 an item of Mom's clothes on the dresser's pedestal, else one to four pills. +constexpr uint32_t DRESSER_DROP_SHIFT = 31; +constexpr uint32_t DRESSER_ITEM_ODDS = 100; +constexpr uint32_t DRESSER_PILLS_MAX = 4; +constexpr int PEDESTAL_DRESSER = 9; +constexpr std::array DRESSER_ITEMS = {29, 30, 31, 39, 41, 200, 110, 217, 228, 355}; +// The Revive Machine broken on a first visit: nothing to 32 of 100, a soul heart to 65, an eternal heart to 94, 1up! +// above, the hearts thrown slowly. +constexpr uint32_t REVIVE_DROP_NOTHING = 32; +constexpr uint32_t REVIVE_DROP_SOUL_MAX = 66; +constexpr uint32_t REVIVE_DROP_HEART_MAX = 94; +constexpr float REVIVE_DROP_SPEED = 0.4f; constexpr int DONATION_JAM_ODDS = 3000; constexpr int DONATION_LIMIT = 7; constexpr int DONATION_LIMIT_RANGE = 9; @@ -202,9 +220,6 @@ constexpr float BLOOD_SPLASH_RISE = -2; constexpr int BLOOD_EXPLOSION_MACHINE = 4; constexpr int SLOT_BLOOD_SPLASH = 3; -constexpr ColorMod ROTTEN_SPLAT_COLOR = {{0.7f, 0.9f, 0.65f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; -constexpr float ROTTEN_SPLAT_MIN = 0.2f; -constexpr float ROTTEN_SPLAT_RANGE = 0.4f; constexpr float ROTTEN_PARTICLE_SPEED = 2; constexpr float ROTTEN_PARTICLE_HEIGHT = 100000; @@ -403,7 +418,6 @@ Vector collectible_spawn_position(Vector target) // 0065d200 Starts a slot from its config's sprite, sized and offset for its kind. The donation machines show their // save's count and break or jam as the run left them, the dresser appears on a first visit, and the Revive Machine // only stays in co-op. In Greed mode the blood donation machine is a devil beggar. -// Isaac's secret closet and the Revive Machine's setup are not reconstructed yet. void Entity_Slot::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) { bool isGreed = g_game->difficulty == DIFFICULTY_GREED || g_game->difficulty == DIFFICULTY_GREEDIER; @@ -463,7 +477,7 @@ void Entity_Slot::Init(int entityType, int entityVariant, int entitySubType, uin bool isOnline = g_manager->netplayManager.is_online(); bool isBroken = g_game->GetStateFlag((GameStateFlag)GAME_STATE_DONATION_SLOT_BROKEN) || - (isOnline ? g_game->challenge != 0 || g_game->dailyChallenge._id != 0 : achievements_disallowed()); + (isOnline ? g_game->challenge != 0 || g_game->dailyChallenge.id != 0 : achievements_disallowed()); if (isBroken) Remove(); if (g_game->GetStateFlag((GameStateFlag)GAME_STATE_DONATION_SLOT_JAMMED)) { @@ -499,16 +513,44 @@ void Entity_Slot::Init(int entityType, int entityVariant, int entitySubType, uin } break; case SLOT_ISAAC_SECRET: - reconstruction_missing("Entity_Slot::Init 0065d200: Isaac's secret closet"); + { + if (g_manager->netplayManager.is_online()) + reconstruction_missing("Entity_Slot::Init 0065d200: the closet of the online local player"); + int playerType = g_game->GetPlayer(0)->playerType; + bool isRegular = playerType >= 0 && playerType < (int)TAINTED_TWINS.size(); + EntityConfig_Player* tainted = g_manager->entityConfig.GetPlayer(isRegular ? TAINTED_TWINS[playerType] + : playerType); + if (!tainted) break; + for (int layer = 0; layer < (int)sprite.layerStates.size(); layer++) + sprite.ReplaceSpritesheet(layer, tainted->skinPath); + sprite.LoadGraphics(); + break; + } case SLOT_REVIVE_MACHINE: + // 006655e0 The Revive Machine stands only in co-op, out of the excluded room, showing its price. if (!g_game->playerManager.IsCoopPlay() || g_game->currentRoomIdx == REVIVE_MACHINE_EXCLUDED_ROOM) Remove(); - else reconstruction_missing("Entity_Slot::Init 0065d200: the Revive Machine in co-op (FUN_006655e0)"); + else + { + posOffset.y = MACHINE_OFFSET_Y; + sizeMulti = vector_make(MACHINE_WIDTH, MACHINE_DEPTH); + revive_counter_show(); + AddEntityFlags(FLAG_NO_KNOCKBACK); + } break; } entityGridCollisionClass = GRIDCOLL_NONE; timeout = 0; } +// 00665630 Shows the coins the Revive Machine still asks for on its two digit layers. +void Entity_Slot::revive_counter_show() +{ + int coins = g_game->reviveMachineCoinsLeft; + sprite.SetFrame("Prize", 0); + sprite.SetLayerFrame(1, coins / DIGIT_BASE % DIGIT_BASE); + sprite.SetLayerFrame(2, coins % DIGIT_BASE); +} + // Shows a donation count on the machine's three digit layers. void Entity_Slot::counter_show(int count) { @@ -815,7 +857,7 @@ void Entity_Slot::idle_update() if (state == SLOT_STATE_REWARD) { if (isMachine && sprite.IsFinished()) sprite.Play("Wiggle"); - if (variant == SLOT_ISAAC_SECRET) reconstruction_missing("Entity_Slot::Update 0065d950: Isaac's secret closet"); + if (variant == SLOT_ISAAC_SECRET) closet_effects_update(); } else if (state == SLOT_STATE_BROKEN) { @@ -1567,7 +1609,9 @@ void Entity_Slot::payout(Entity_Player& player) battery_bum_pay(player, prizeRng, count); break; case SLOT_ISAAC_SECRET: - reconstruction_missing("Entity_Slot::Update 0065d950: Isaac's secret closet"); + Remove(); + PlayerManager::unlock_completion_mark(COMPLETION_TAINTED); + return; case SLOT_CRANE_GAME: case SLOT_CONFESSIONAL: break; @@ -1591,6 +1635,33 @@ void Entity_Slot::payout(Entity_Player& player) sprite.Play("Idle"); } +// Part of 0065d950: freeing the tainted character from Home's closet shows a burst over the closet (its "FX" event) +// and a poof (its "Poof" event). +void Entity_Slot::closet_effects_update() +{ + constexpr int CLOSET_FX_SUBTYPE = 10; + constexpr float CLOSET_FX_DEPTH = -10; + constexpr float CLOSET_FX_RISE = -20; + + if (sprite.IsEventTriggered("FX")) + { + auto* burst = static_cast(g_game->Spawn({.position = pos, + .subType = CLOSET_FX_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_TEAR_POOF_A, + .seed = Random()})); + burst->FollowParent(this); + burst->renderDepthOffset = CLOSET_FX_DEPTH; + burst->sprite.scale = sprite.scale; + burst->sprite.offset = vector_mul(burst->sprite.scale, vector_make(0, CLOSET_FX_RISE)); + burst->AddEntityFlags(FLAG_TRANSITION_UPDATE); + burst->Update(); + burst->rotation = 0; + } + if (sprite.IsEventTriggered("Poof")) + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); +} + // 0065d950 Runs a slot each frame: its appearance, its spot, a Rotten Beggar's first splat, a Bomb Bum's Troll Bombs, // the slot machine's roll once its spin ends, the Crane Game and Confessional prizes, and the payout once a payment's // animation is done. A shell game shuffles with a sound, and touches count while a player keeps touching it. @@ -1947,6 +2018,92 @@ void Entity_Slot::payment_react(Entity_Player& player, Entity* collider) npc_anim_restart(sprite, animation); } +// Part of 006627e0: Beth's Essence gives a beggar's payer a wisp of a random active item that has one (Book of +// Virtues' otherwise). Two or three copies draw again among every active with a wisp, and more give none. +// The original reads past an empty list of such actives. Here it gives no wisp. +static void beths_essence_wisp_add(Entity_Player& player, const Vector& position) +{ + ItemConfig& items = g_manager->itemConfig; + RNG& rng = player.GetTrinketRNG(TRINKET_BETHS_ESSENCE); + auto isWispActive = [](ItemConfig_Item* item) + { return item && item->type == ITEM_ACTIVE && item->wispConfig && item->wispConfig->count >= 1; }; + + int id = (int)rng.RandomInt((uint32_t)items.collectibles.size() - 1) + 1; + ItemConfig_Item* item = items.GetCollectible(id); + if (!ItemConfig::IsValidCollectible(id) || !isWispActive(item)) + item = items.GetCollectible(COLLECTIBLE_BOOK_OF_VIRTUES); + int copies = player.GetTrinketMultiplier(TRINKET_BETHS_ESSENCE); + if (copies == 1) player.AddWisp(item->id, position, true, false); + if (copies != 2 && copies != 3) return; + + std::vector actives; + for (int each = 0; each < (int)items.collectibles.size(); each++) + if (isWispActive(items.GetCollectible(each))) actives.push_back(each); + if (!actives.empty()) player.AddWisp(actives[rng.RandomInt((uint32_t)actives.size())], position, true, false); +} + +// 0075d9f0 Mom's dresser shuffles the player's costumes: each costume, from the first, swaps with a random later one, a +// head and its body (the same item's costumes side by side) moving as a pair. A lone costume before a pair first moves +// behind the pair when it is to swap with another pair. The costumes are then rebuilt. +static void costumes_shuffle(Entity_Player& player, uint32_t seed) +{ + constexpr uint32_t DRESSER_SHUFFLE_SHIFT = 19; + std::vector& costumes = player.costumeSpriteDescs; + int count = (int)costumes.size(); + RNG rng = rng_make(seed, DRESSER_SHUFFLE_SHIFT); + auto isPairAt = [&](int at) { return at < count - 1 && costumes[at].item == costumes[at + 1].item; }; + + log_printf(LOG_INFO, "costume map:\n"); + for (int i = 0; i < count; i++) log_printf(LOG_INFO, "%d: %s\n", i, costumes[i].sprite.filename.c_str()); + for (int i = 0; i < count - 1; i++) + { + bool isPair = isPairAt(i); + uint32_t range = (uint32_t)(isPair ? count - 1 - i : count - i); + uint32_t roll = rng.Next(); + int other = (range ? (int)(roll % range) : 0) + i; + if (i < other && costumes[other - 1].item == costumes[other].item) other--; + else if (isPair && other < count - 2 && isPairAt(other + 1)) other++; + bool isOtherPair = isPairAt(other); + + if (other == i) + { + if (isPair || isOtherPair) i++; + continue; + } + if (isOtherPair && !isPair && i < count - 2 && isPairAt(i + 1)) + { + log_printf(LOG_INFO, "swap (src body) %d %d\n", i, i + 1); + log_printf(LOG_INFO, "swap (src body) %d %d\n", i + 1, i + 2); + std::swap(costumes[i], costumes[i + 1]); + std::swap(costumes[i + 1], costumes[i + 2]); + isPair = true; + if (other == i + 1) + { + i++; + continue; + } + } + log_printf(LOG_INFO, "swap %d %d\n", i, other); + std::swap(costumes[i], costumes[other]); + if (!isPair && !isOtherPair) continue; + log_printf(LOG_INFO, "swap (body) %d %d\n", i + 1, other + 1); + std::swap(costumes[i + 1], costumes[other + 1]); + i++; + } + player.UpdateCostumes(); +} + +// 006653e0 Opening Mom's dresser: it plays its use, a poof rises at the player with the chest's sound, and the player's +// costumes are shuffled. +void Entity_Slot::dresser_open(Entity_Player& player) +{ + sprite.Play("Use", PLAY_FORCED); + EntitySpawn poof = {.position = player.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}; + g_game->Spawn(poof)->Update(); + npc_sound_play(SOUND_CHEST_OPEN, 1, 2, 1); + costumes_shuffle(player, dropRNG.Next()); +} + // 006627e0 A player touching an idle slot pays it, which makes it the slot's target, may give Beth's Essence a wisp // for a beggar, and starts the slot's payment. A player touching Mom's dresser opens it. Touches are counted while a // player keeps touching. Enemies and bombs pass through a slot. @@ -1955,7 +2112,7 @@ bool Entity_Slot::HandleCollision(Entity* collider, bool) bool isPlayer = collider->type == ENTITY_PLAYER; if (variant == SLOT_MOMS_DRESSER && isPlayer && collider->variant == PLAYER_VARIANT_PLAYER && state != SLOT_STATE_BROKEN && (!sprite.animState.animData || !sprite.animState.isPlaying)) - reconstruction_missing("Entity_Slot::HandleCollision 006627e0: Mom's dresser (FUN_006653e0, FUN_0075d9f0)"); + dresser_open(*collider->ToPlayer()); bool isShellGame = variant == SLOT_SHELL_GAME || variant == SLOT_HELL_GAME; const AnimationData* animation = sprite.animState.animData; @@ -1977,7 +2134,7 @@ bool Entity_Slot::HandleCollision(Entity* collider, bool) target = &player; if (is_beggar(variant) && player.HasTrinket(TRINKET_BETHS_ESSENCE) && player.GetTrinketRNG(TRINKET_BETHS_ESSENCE).RandomInt(BETHS_ESSENCE_ODDS) == 0) - reconstruction_missing("Entity_Slot::HandleCollision 006627e0: Beth's Essence's wisp"); + beths_essence_wisp_add(player, pos); payment_react(player, collider); } } @@ -2181,9 +2338,44 @@ void Entity_Slot::spawn_break_drops() } return; case SLOT_MOMS_DRESSER: - reconstruction_missing("Entity_Slot::spawn_break_drops 00663aa0: Mom's dresser"); + { + RNG rng = rng_make(initSeed, DRESSER_DROP_SHIFT); + if (rng.RandomInt(DRESSER_ITEM_ODDS) != 0) + { + for (int pills = (int)rng.RandomInt(DRESSER_PILLS_MAX) + 1; pills > 0; pills--) + drop(PICKUP_PILL, 0, rng.Next(), 1); + return; + } + ItemPool& pool = g_game->itemPool; + int item = + pool.GetCollectibleFromList(DRESSER_ITEMS, rng.Next(), COLLECTIBLE_MOMS_HEELS, LIST_PICK_BLACKLIST); + auto* pedestal = static_cast(g_game->Spawn({.position = pos, + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = rng.Next()})); + pedestal->SetAlternatePedestal(PEDESTAL_DRESSER); + pedestal->Update(); + return Remove(); + } case SLOT_REVIVE_MACHINE: - reconstruction_missing("Entity_Slot::spawn_break_drops 00663aa0: the Revive Machine"); + { + if (!g_game->room->isFirstVisit) return; + uint32_t roll = dropRNG.RandomInt(100); + if (roll <= REVIVE_DROP_NOTHING) return; + if (roll > REVIVE_DROP_HEART_MAX) + { + g_game->Spawn({.position = pos, + .subType = COLLECTIBLE_1UP, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = dropRNG.Next()}); + return; + } + uint32_t seed = dropRNG.Next(); + int heart = roll < REVIVE_DROP_SOUL_MAX ? (int)HEART_SOUL : (int)HEART_ETERNAL; + return drop(PICKUP_HEART, heart, seed, REVIVE_DROP_SPEED); + } default: break; } diff --git a/src/entity_slot.h b/src/entity_slot.h index 8b4eccb..c1e3677 100644 --- a/src/entity_slot.h +++ b/src/entity_slot.h @@ -80,6 +80,7 @@ struct Entity_Slot : Entity private: void counter_show(int count); + void revive_counter_show(); void drops_spawn(const SlotDrop& drop); void explode(); void leave(); @@ -107,6 +108,8 @@ private: void payment_react(Entity_Player& player, Entity* collider); void shell_game_start(Entity_Player& player); void blood_trails_spawn(); + void closet_effects_update(); + void dresser_open(Entity_Player& player); }; Vector room_pickup_position_random(bool isAvoidActiveEntities, bool isAllowPits); diff --git a/src/entity_tear.cpp b/src/entity_tear.cpp index 0bd0e34..819112e 100644 --- a/src/entity_tear.cpp +++ b/src/entity_tear.cpp @@ -10,6 +10,9 @@ #include "entity_player.h" #include "game.h" #include "grid_entity.h" +#include "persistent_game_data.h" +#include "grid_entity_poop.h" +#include "grid_entity_rock.h" #include "log.h" #include "lua_engine.h" #include "manager.h" @@ -28,6 +31,20 @@ constexpr float TEAR_DAMAGE_DEFAULT = 3.5f; constexpr float TEAR_HOMING_FRICTION = 0.85f; constexpr float DEFLECT_REBOUND = 0.85f; constexpr float TEAR_KNOCKBACK_MULTIPLIER = 1.7f; +// A teleporting tear's hit: the tries for a spot, how far the enemy must move and stay from the nearest target within +// range, and the blue of its poofs. +constexpr int TEAR_TELEPORT_TRIES = 33; +// A rerolled rock's kinds, and where a roll for a poop turns from plain to corny, red, black, rainbow and golden. +constexpr uint32_t ROCK_REROLL_KINDS = 6; +constexpr float ROCK_REROLL_POOP_NORMAL = 0.6f; +constexpr float ROCK_REROLL_POOP_CORNY = 0.8f; +constexpr float ROCK_REROLL_POOP_RED = 0.95f; +constexpr float ROCK_REROLL_POOP_BLACK = 0.97f; +constexpr float ROCK_REROLL_POOP_RAINBOW = 0.98f; +constexpr float TELEPORT_MOVE_SQUARED = 400; +constexpr float TELEPORT_TARGET_DISTANCE_SQUARED = 6400; +constexpr float TELEPORT_TARGET_RANGE = 5000; +constexpr ColorMod TELEPORT_POOF_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.2509804f, 0.34901962f, 0.5019608f}}; constexpr float TEAR_RANGE_DEFAULT = 260; constexpr float TEAR_GRID_HIT_HEIGHT = -60; // A Chaos Card on the floor lies upside down, and a water tear bounces off the floor a little faster than it fell. @@ -635,8 +652,7 @@ void Entity_Tear::flight_update(float verticalMotion) bool isBouncing = tearFlags[TEAR_BOUNCE] || tearFlags[TEAR_BOUNCE_WALLSONLY] || variant == TEAR_FIRE; if (isOnFloor && !isLudovico) floor_hit(); else if ((isBouncing && !g_game->room->IsBeastDungeon()) || (isLudovico && (subtype & LUDOVICO_FAST))) bounce_hit(); - else if (tearFlags[TEAR_REROLL_ROCK_WISP]) - reconstruction_missing("Entity_Tear::Update 006670f0: a rock rerolling tear"); + else if (tearFlags[TEAR_REROLL_ROCK_WISP]) rock_reroll(); else grid_hit(); if (variant == TEAR_CHAOS_CARD) chaos_card_stick(); key_open(); @@ -1138,6 +1154,54 @@ void Entity_Tear::floor_hit() } } +// The rock a rerolled rock becomes: a poop of some kind, a block, a bomb rock, an alternate rock, TNT, or the rock of +// its cell (tinted on the tinted rock's cell, now and then super tinted once unlocked). +static std::pair rock_reroll_roll(RNG& rng, int gridIndex) +{ + uint32_t roll = rng.RandomInt(ROCK_REROLL_KINDS); + bool isTinted = gridIndex == g_game->room->tintedRockIdx; + GridEntityType rock = isTinted ? GRID_ROCKT : GRID_ROCK; + if (isTinted && rng.RandomInt(SUPER_TINTED_ODDS) == 0 && + g_manager->persistentGameData.Unlocked(ACHIEVEMENT_SUPER_TINTED_ROCK)) + rock = GRID_ROCK_SS; + + switch (roll) + { + case 0: + { + float poop = rng.RandomFloat(); + if (poop < ROCK_REROLL_POOP_NORMAL) return {GRID_POOP, POOP_NORMAL}; + if (poop < ROCK_REROLL_POOP_CORNY) return {GRID_POOP, POOP_CORNY}; + if (poop < ROCK_REROLL_POOP_RED) return {GRID_POOP, POOP_RED}; + if (poop < ROCK_REROLL_POOP_BLACK) return {GRID_POOP, POOP_BLACK}; + return {GRID_POOP, poop < ROCK_REROLL_POOP_RAINBOW ? POOP_RAINBOW : POOP_GOLDEN}; + } + case 1: return {GRID_ROCKB, 0}; + case 2: return {GRID_ROCK_BOMB, 0}; + case 3: return {GRID_ROCK_ALT, 0}; + case 4: return {GRID_TNT, 0}; + default: return {rock, 0}; + } +} + +// The rock rerolling tear: a breakable rock it flies over breaks, without drops, into another obstacle rolled from the +// tear's drop generator, and the tear rerolls no more. +void Entity_Tear::rock_reroll() +{ + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(pos); + if (gridIndex < 0) return; + GridEntity* grid = room.GetGridEntity((uint32_t)gridIndex); + if (!grid || !grid->IsBreakableRock()) return; + + tearFlags.reset(TEAR_REROLL_ROCK_WISP); + grid->state = ROCK_STATE_BROKEN; + static_cast(grid)->UpdateNeighbors(); + auto [type, variant] = rock_reroll_roll(dropRNG, gridIndex); + room.SetGridPath(gridIndex, 0); + room.SpawnGridEntity(gridIndex, type, variant, dropRNG.Next(), 0); +} + // The tear hit the grid, or stands on a wall: it dies, hurting the rocks and poop it touches, unless it is spectral // or stuck in an enemy (a Chaos Card sticks in the wall instead). Missing anything but poop or TNT ends its player's // streak. @@ -1291,7 +1355,7 @@ void Entity_Tear::ludovico_interpolate() pos = vector_add(main->pos, vector_resized(offset, vector_length(offset) * (sway * LUDOVICO_SWAY + 1))); } if (!tearFlags[TEAR_HYDROBOUNCE]) return; - float bob = std::sin(((float)(g_game->frameCount - spawnFrame) + HALF_FRAME) * (PI_F / fallingSpeed)); + float bob = std::sin(((float)(g_game->frameCount - spawnFrame) + HALF_FRAME) * (PI_F / hydrobounce_period_get())); posOffset.y = std::fabs(bob) * height; } @@ -2174,8 +2238,26 @@ void Entity_Tear::ChangeVariant(int newVariant) entityGridCollisionClass = gridCollision; } -// 006b5320 -void Entity_Tear::reroll_hit_entity(int) +// 006b5320 Teleports an enemy a teleporting tear hit: to a free tile at least 20 away from it and 80 from the nearest +// target, tried 33 times, leaving a blue poof where it was and one where it lands. It stays when no spot fits. +// The original reads a missing nearest target and crashes. Without one, any spot fits. +void tear_hit_teleport(Entity& entity) { - reconstruction_missing("Entity_Tear::reroll_hit_entity 006b5320"); + Room& room = *g_game->room; + Vector spot = {}; + for (int tries = 0; tries < TEAR_TELEPORT_TRIES; tries++) + { + spot = room_free_tile_position_find(room.GetRandomPosition(0), 0); + Entity* target = game_nearest_target_player(spot, &entity, false, false, TELEPORT_TARGET_RANGE); + bool isFarFromTarget = !target || vector_length_squared(vector_sub(target->pos, spot)) > TELEPORT_TARGET_DISTANCE_SQUARED; + if (vector_length_squared(vector_sub(spot, entity.pos)) > TELEPORT_MOVE_SQUARED && isFarFromTarget) break; + spot = {}; + } + if (spot.x == 0 && spot.y == 0) return; + + for (Vector at : {entity.pos, spot}) + if (Entity* poof = g_game->Spawn({.position = at, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, + .seed = Random()})) + poof->sprite.color = TELEPORT_POOF_COLOR; + entity.pos = spot; } diff --git a/src/entity_tear.h b/src/entity_tear.h index 5c5d55a..ca59fed 100644 --- a/src/entity_tear.h +++ b/src/entity_tear.h @@ -2,6 +2,7 @@ #include "entity.h" #include "anm2.h" +#include #include #include @@ -11,6 +12,12 @@ constexpr std::array TEAR_ANIMATION_SCALES = {0.25f, 0.5f, 0.625f, 1.375f, 1.625f, 1.875f, 2.125f, 2.5f, 2.75f}; constexpr float TEAR_ANIMATION_MARGIN = 0.05f; +// FUN_0067af30: the scale of a RegularTear animation by its number, held inside 1 to 13. +inline float tear_size_scale(int size) +{ + return TEAR_ANIMATION_SCALES[std::clamp(size, 1, (int)TEAR_ANIMATION_SCALES.size()) - 1]; +} + // Lua's TearFlags bits the game reads. Bits 84 and 101 to 103 have no Lua name: It Hurts' creep on death, flags // swapped in on an interval, a speed reset on an interval, and steering back toward the parent. enum TearFlagBit : int @@ -348,7 +355,6 @@ struct Entity_Tear : Entity void apply_link_spring_forces(); bool try_make_bridges(const Vector& position); void bridge_beyond(GridEntity& rock); - void reroll_hit_entity(int unused); static void ApplyTearFlagEffects(Entity* entity, const Vector& position, const TearFlags& flags, Entity* source, float damage); @@ -396,6 +402,7 @@ private: bool is_popping(); void floor_hit(); void grid_hit(); + void rock_reroll(); void bounce_hit(); void chaos_card_stick(); void key_open(); @@ -431,6 +438,7 @@ Vector tear_vector_rotate(Vector v, float degrees); Entity* homing_target_find(Entity_Tear& tear, bool isFetus); float dead_eye_glow_get(Entity_Player& player); int tear_variant_blood(int variant); +void tear_hit_teleport(Entity& entity); // Game::AttractEntities' arguments: where everything is pulled to, how hard and how far, and the one entity spared. struct Attraction diff --git a/src/entity_tear_death.cpp b/src/entity_tear_death.cpp index 7ace9ae..37cb0f0 100644 --- a/src/entity_tear_death.cpp +++ b/src/entity_tear_death.cpp @@ -3,6 +3,7 @@ #include "entity_effect_combat.h" #include "entity_familiar.h" #include "entity_knife.h" +#include "entity_laser.h" #include "entity_player.h" #include "entity_effect.h" #include "game.h" @@ -143,6 +144,19 @@ constexpr float HAEMO_BURST_HEIGHT = -6; constexpr float HAEMO_BURST_FALL_ACCEL = 1.3f; constexpr float HAEMO_BURST_FALL_MIN = 0.5f; constexpr float HAEMO_BURST_FALL_SPREAD = 0.75f; +// Haemolacria's Dr. Fetus bombs: their throw speed, how far from the tear they start (around 3.14 for pi), their blast, +// rise and fuse, and its Tech X rings' radius. +constexpr float HAEMO_BOMB_SPEED_MIN = 3; +constexpr float HAEMO_BOMB_SPEED_RANGE = 4; +constexpr float HAEMO_BOMB_PI = 3.14f; +constexpr float HAEMO_BOMB_SPREAD = 10; +constexpr float HAEMO_BOMB_RADIUS = 0.65f; +constexpr float HAEMO_BOMB_RISE_MIN = 3; +constexpr float HAEMO_BOMB_RISE_RANGE = 5; +constexpr uint32_t HAEMO_BOMB_FUSE_RANGE = 14; +constexpr int HAEMO_BOMB_FUSE_MIN = 10; +constexpr float HAEMO_RING_RADIUS_MIN = 20; +constexpr float HAEMO_RING_RADIUS_RANGE = 60; constexpr float BURST_CRAWLSPACE_OFFSET = -18; // The flags Haemolacria's burst keeps of its tear. @@ -656,6 +670,82 @@ static int burst_count_get(Entity_Player* player, bool isHalved) return isHalved ? (count + 1) / 2 : count; } +// A laser of Haemolacria's burst: where the tear died, not following its player, in the tear's color and touched by +// what touched it. +static void haemo_laser_finish(Entity_Tear& tear, Entity_Laser& laser) +{ + laser.pos = tear.pos; + laser.isDisableFollowParent = true; + laser.SetColor(tear.sprite.color, -1, TEAR_COLOR_PRIORITY, false, true); + laser.isPrismTouched = tear.isPrismTouched; + laser.isMultidimensionalTouched = tear.isMultidimensionalTouched; + laser.Update(); +} + +// A Dr. Fetus bomb of Haemolacria's burst: thrown at random from near the tear, half size and damage with a smaller +// blast, without Sad Bombs unless the tear may end a streak, popping up with a short random fuse unless a rocket. +static void haemo_bomb_throw(Entity_Tear& tear, Entity_Player& player) +{ + float speed = (random_unit() * HAEMO_BOMB_SPEED_RANGE + HAEMO_BOMB_SPEED_MIN) * player.shotSpeed; + Vector velocity = vector_scale(vector_from_angle(random_unit() * TEAR_FULL_TURN), speed); + float angle = random_unit() * HAEMO_BOMB_PI * 2; + float reach = random_unit() * HAEMO_BOMB_SPREAD; + Vector position = vector_make(std::cos(angle) * reach + tear.pos.x, std::sin(angle) * reach + tear.pos.y); + + Entity_Bomb& bomb = *player.FireBomb(position, velocity, nullptr); + bomb.SetColor(tear.sprite.color, -1, TEAR_COLOR_PRIORITY, false, true); + bomb.isPrismTouched = tear.isPrismTouched; + if (!tear.isCanTriggerStreakEnd) bomb.tearFlags.reset(TEAR_SAD_BOMB); + bomb.isLoadCostumes = true; + bomb.scale *= HALF; + bomb.explosionDamage *= HALF; + bomb.radiusMultiplier *= HAEMO_BOMB_RADIUS; + bomb.SetSize(bomb.size * HALF, vector_make(-1, -1), -1); + if (!bomb.IsRocket()) + { + bomb.fallSpeed = -HAEMO_BOMB_RISE_MIN - random_unit() * HAEMO_BOMB_RISE_RANGE; + int fuse = (int)(bomb.dropRNG.Next() % HAEMO_BOMB_FUSE_RANGE) + HAEMO_BOMB_FUSE_MIN; + bomb.posOffset = vector_make(0, -HAEMO_BOMB_RISE_MIN); + bomb.explosionCountdown = fuse; + bomb.explosionCountdown2 = fuse; + } + bomb.AddEntityFlags(FLAG_NO_KNOCKBACK | FLAG_NO_REWARD); +} + +// A piece of Haemolacria's burst for a player with a weapon: a delayed Brimstone beam, a Dr. Fetus bomb, a Tech X ring +// or a Technology laser at a random angle, in that order of preference. False for a player with none. +static bool haemo_weapon_burst(Entity_Tear& tear, Entity_Player& player) +{ + if (player.HasCollectible(COLLECTIBLE_BRIMSTONE)) + { + haemo_laser_finish(tear, *player.FireDelayedBrimstone(random_unit() * TEAR_FULL_TURN, &player)); + return true; + } + if (player.HasCollectible(COLLECTIBLE_DR_FETUS)) + { + haemo_bomb_throw(tear, player); + return true; + } + if (player.HasCollectible(COLLECTIBLE_TECH_X)) + { + float radius = random_unit() * HAEMO_RING_RADIUS_RANGE + HAEMO_RING_RADIUS_MIN; + Vector velocity = vector_scale(vector_from_angle(random_unit() * TEAR_FULL_TURN), player.shotSpeed * HAEMO_BURST_SPEED); + Entity_Laser* ring = player.FireTechXLaser({.position = tear.pos, .velocity = velocity, .radius = radius}); + ring->isPrismTouched = tear.isPrismTouched; + ring->isMultidimensionalTouched = tear.isMultidimensionalTouched; + ring->Update(); + return true; + } + if (!player.HasCollectible(COLLECTIBLE_TECHNOLOGY)) return false; + + Vector direction = vector_from_angle(random_unit() * TEAR_FULL_TURN); + Entity_Laser* laser = + player.FireTechLaser({.direction = direction, .position = tear.pos, .offsetId = LASER_OFFSET_TECH2}); + laser->SetCollisionDamage(laser->collisionDamage / HAEMO_BURST_DAMAGE_SHARE); + haemo_laser_finish(tear, *laser); + return true; +} + // 00678080 Haemolacria: the dying tear bursts into blood tears flying off at random at ten times its player's shot // speed, keeping most of its flags, smaller and weaker by a random share, falling back from the burst's height. // A player with Brimstone, Dr. Fetus, Tech X or Technology bursts into those weapons instead. @@ -674,12 +764,7 @@ void Entity_Tear::fire_split_projectiles(bool isHalved) if (tearFlags[flag]) kept.set(flag); for (int i = 0; i < count; i++) { - bool isWeapon = player && (player->HasCollectible(COLLECTIBLE_BRIMSTONE) || - player->HasCollectible(COLLECTIBLE_DR_FETUS) || - player->HasCollectible(COLLECTIBLE_TECH_X) || - player->HasCollectible(COLLECTIBLE_TECHNOLOGY)); - if (isWeapon) - reconstruction_missing("Entity_Tear::fire_split_projectiles 00678080: Haemolacria's burst of a weapon"); + if (player && haemo_weapon_burst(*this, *player)) continue; uint32_t seed = Random(); Vector burstVelocity = vector_scale(vector_from_angle(random_unit() * TEAR_FULL_TURN), shotSpeed * HAEMO_BURST_SPEED); diff --git a/src/entity_tear_flags.cpp b/src/entity_tear_flags.cpp index c6356be..3f276af 100644 --- a/src/entity_tear_flags.cpp +++ b/src/entity_tear_flags.cpp @@ -366,13 +366,13 @@ void Entity_Tear::lasershot_update() laserShotLaser = nullptr; } -// (006670f0's Ludovico water bounce) A Ludovico water tear bobs on a sine of its height over its fall, splashing on -// the floor each time the bob turns. The vertical motion its sprite turns with, its fall speed otherwise. +// (006670f0's Ludovico water bounce) A Ludovico water tear bobs on a sine of its height over its player's fire delay, +// splashing on the floor each time the bob turns. The vertical motion its sprite turns with, its fall speed otherwise. float Entity_Tear::ludovico_hydrobounce_update() { if (!tearFlags[TEAR_LUDOVICO] || !tearFlags[TEAR_HYDROBOUNCE]) return fallingSpeed; - float rate = PI_F / fallingSpeed; + float rate = PI_F / hydrobounce_period_get(); float before = std::sin((float)(FrameCount() - 1) * rate); float now = std::sin((float)FrameCount() * rate); posOffset.y = std::fabs(now) * height; diff --git a/src/familiar_ai.cpp b/src/familiar_ai.cpp index 3539c36..b25465c 100644 --- a/src/familiar_ai.cpp +++ b/src/familiar_ai.cpp @@ -19,6 +19,7 @@ // The items a familiar's drops and charges read. constexpr int FISH_TAIL_TRIPLED_FACTOR = 4; +constexpr float CHARMED_INTRUDER_RANGE = 300; constexpr int BLUE_FLY_ACHIEVEMENT_COUNT = 20; constexpr int ACHIEVEMENT_BLUE_FLIES = 388; constexpr int COLLECTIBLE_MILK_ID = 436; @@ -141,9 +142,43 @@ constexpr uint32_t SPIDER_MOD_ROLL = 100; constexpr uint32_t SPIDER_MOD_BFFS_ROLL = 80; constexpr int SPIDER_MOD_DROP_ODDS = 10; +// Part of 00615030: a familiar the Siren charmed hunts the player the Siren targets, checked every few frames when +// that player is in reach (twice the range, Intruder's 300). An invincible player is dropped. +static void charmed_target_pick(Entity_Familiar& familiar, const TargetSearch& search) +{ + Entity* target = familiar.target; + if (target && target->type == ENTITY_PLAYER && static_cast(target)->HasInvincibility(0, EntityRef())) + familiar.target = nullptr; + if (search.frameInterval > 1 && !familiar.IsFrame(search.frameInterval, (int)familiar.index)) return; + if (familiar.target) return; + + float range = familiar.variant == Entity_Familiar::INTRUDER ? CHARMED_INTRUDER_RANGE : search.range + search.range; + Entity* siren = familiar.player->parent; + if (!siren || !siren->IsEnemy()) return; + + Entity* hunted = static_cast(siren)->GetPlayerTarget(); + if (vector_length(vector_sub(familiar.pos, hunted->pos)) > range) return; + familiar.target = hunted; +} + +// Whether a versus match's player is no prey for a familiar: unseen, or keeping its own flies or spiders off. +static bool is_versus_player_spared(Entity_Familiar& familiar, Entity_Player& player) +{ + int variant = familiar.variant; + bool isFlyLord = player.HasCollectible(COLLECTIBLE_SKATOLE) || + (player.variant == PLAYER_VARIANT_PLAYER && player.HasPlayerForm(PLAYER_FORM_BEELZEBUB)); + bool isSpiderLord = player.variant == PLAYER_VARIANT_PLAYER && player.HasPlayerForm(PLAYER_FORM_SPIDER_BABY); + if (player.IsInvisible()) return true; + if (isFlyLord && (variant == Entity_Familiar::BLUE_FLY || variant == Entity_Familiar::BLUE_SPIDER || + variant == Entity_Familiar::ABYSS_LOCUST)) + return true; + return isSpiderLord && (variant == Entity_Familiar::BLUE_SPIDER || variant == Entity_Familiar::SPIDER_BABY); +} + // 00615030 Picks what to chase: the best scored enemy in reach (closer, near the player, weaker or healthier as asked, // inside a cone if one is given, the current one preferred), checked every few frames. A pacifist room drops the -// target, an enemy given up on (a versus match's long chase) is skipped, and a charmed familiar turns on the player. +// target, an enemy given up on is skipped, and a charmed familiar turns on the player. In a versus match it always +// looks again, and hunts the other players (unseen ones and fly or spider lords spared) and their Punching Bags. void Entity_Familiar::PickEnemyTarget(const TargetSearch& search) { if (g_game->room->isPacifist) @@ -151,19 +186,19 @@ void Entity_Familiar::PickEnemyTarget(const TargetSearch& search) target = nullptr; return; } - if (familiar_versus()) reconstruction_missing("Entity_Familiar::PickEnemyTarget 00615030 (a versus match)"); + bool isVersus = familiar_versus(); bool hasCone = !vector_is_zero(search.coneDirection); Vector coneDirection = vector_normalized(search.coneDirection); float coneCos = hasCone ? std::cos(search.coneAngle * PI_F / 360) : 0; - bool isRetarget = search.flags & TARGET_RETARGET; + bool isRetarget = isVersus || (search.flags & TARGET_RETARGET); bool isNearPlayer = !(search.flags & TARGET_NOT_NEAR_PLAYER); auto isGivenUp = [this](Entity& entity) { auto found = targetFrames.find(entity.index); return found != targetFrames.end() && found->second < 0; }; if (target && isGivenUp(*target)) target = nullptr; - if (HasEntityFlags(FLAG_CHARM)) reconstruction_missing("Entity_Familiar::PickEnemyTarget 00615030 (a charmed one)"); + if (HasEntityFlags(FLAG_CHARM)) return charmed_target_pick(*this, search); Entity* previous = target; Entity* kept = nullptr; @@ -186,16 +221,21 @@ void Entity_Familiar::PickEnemyTarget(const TargetSearch& search) float bestScore = 0; for (Entity* entity : g_game->room->entityList.updateEL) { - if (isGivenUp(*entity) || !Entity::is_enemy_type(entity->type)) continue; + if (isGivenUp(*entity)) continue; float distance = vector_length(vector_sub(entity->pos, pos)); float playerDistance = vector_length(vector_sub(entity->pos, player->pos)); + bool isFoeType = Entity::is_enemy_type(entity->type) || (isVersus && entity->type == ENTITY_PLAYER); bool isOut = entity->entityCollisionClass == ENTCOLL_NONE || entity->entityCollisionClass == ENTCOLL_PLAYERONLY || entity->isInvincible || entity->isDead || entity->IsDescendantOf(spawnerEntity) || entity->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET) || entity->type == ENTITY_BLOOD_PUPPY_ENEMY || (search.range < distance && (!isNearPlayer || search.range <= playerDistance)); - if (isOut) continue; + bool isVersusBag = isVersus && entity->type == ENTITY_FAMILIAR && entity->variant == PUNCHING_BAG && + !entity->IsDescendantOf(spawnerEntity); + if ((!isFoeType || isOut) && !isVersusBag) continue; + if (entity->type == ENTITY_PLAYER && is_versus_player_spared(*this, *static_cast(entity))) + continue; float score = 0; if (hasCone) diff --git a/src/familiar_babies.cpp b/src/familiar_babies.cpp index 85f387d..10df4a2 100644 --- a/src/familiar_babies.cpp +++ b/src/familiar_babies.cpp @@ -1,23 +1,27 @@ #include "boss_ai.h" #include "data.h" +#include "entity_bomb.h" #include "entity_effect.h" #include "entity_factory.h" #include "entity_familiar.h" #include "entity_knife.h" +#include "entity_laser.h" #include "entity_npc.h" #include "entity_player.h" #include "entity_tear.h" +#include "familiar_wisp.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 "npc_basement.h" #include "room.h" #include "room_config.h" #include "room_descriptor.h" +#include "room_grid.h" #include #include #include @@ -222,6 +226,96 @@ constexpr int STAR_GLOW_DEPTH = 10000; constexpr float MULTIDIMENSIONAL_KNIFE_SIDE = 10; constexpr float MULTIDIMENSIONAL_KNIFE_SPEED = 5; +// Multidimensional Baby's tear copies: the original a third faster, both half again higher, 5 to one side of its path +// and the copy 10 to the other. +constexpr int MULTIDIMENSIONAL_FOLLOW_FRAMES = 20; +constexpr float MULTIDIMENSIONAL_TEAR_SPEED = 1.333f; +constexpr float MULTIDIMENSIONAL_TEAR_HEIGHT = 1.5f; +constexpr float MULTIDIMENSIONAL_TEAR_SHIFT = 5; +constexpr float MULTIDIMENSIONAL_TEAR_SIDE = 10; +constexpr int MULTIDIMENSIONAL_KEPT_VARIANTS[] = {TEAR_BALLOON, TEAR_BALLOON_BRIMSTONE, TEAR_BALLOON_BOMB}; +constexpr int PRISMLESS_TEAR_VARIANTS[] = {TEAR_CHAOS_CARD, TEAR_ERASER, TEAR_GRIDENT}; + +// Angelic Prism's reach (25 squared), its fans of tears and fetus bombs (30 degrees turning down by 20) and a Ludovico +// tear's copies pushed 10 out in the four directions, and the half radius a Tech X ring must have it in. +constexpr float PRISM_REACH_SQUARED = 625; +constexpr float PRISM_FAN_FIRST = 30; +constexpr float PRISM_FAN_STEP = 20; +constexpr float PRISM_LUDOVICO_PUSH = 10; +constexpr float PRISM_RING_SHARE = 0.5f; + +// Buddy in a Box: the co-op babies it may look like (ten draws among the unlocked ones, then any past the first 71), +// and its tears: a random kind, strength, rise, colour and speed from a generator seeded by itself and the floor, a +// tenth ahead of it, carried along by its player's motion unless aimed at a mark. +constexpr int BUDDY_LOOK_DRAWS = 10; +constexpr int BUDDY_LOOK_FALLBACK_FIRST = 71; +constexpr float BUDDY_SCALE_BFFS = 0.25f; +constexpr float BUDDY_SCALE_BASE = 0.75f; +constexpr float BUDDY_SCALE_SHARE = 0.8f; +constexpr float BUDDY_DAMAGE_SPREAD = 4; +constexpr float BUDDY_DAMAGE_MIN = 2; +constexpr float BUDDY_FALL_SPREAD = 0.4f; +constexpr float BUDDY_FALL_MIN = -0.2f; +constexpr float BUDDY_FALL_JITTER = 0.2f; +constexpr float BUDDY_SPEED_SPREAD = 0.6f; +constexpr float BUDDY_SPEED_MIN = 0.7f; +constexpr float BUDDY_SHOT_SPEED = 10; +constexpr float BUDDY_DRIFT_SHARE = 0.6f; +constexpr int BUDDY_COOLDOWN_SPREAD = 12; +constexpr int BUDDY_COOLDOWN_MIN = 10; +constexpr int BUDDY_HEAD_FRAMES = 18; +constexpr int BUDDY_HEAD_TURN_FRAMES = 8; +constexpr float BUDDY_HEAD_SHOT_FRAME = 2; +constexpr std::string_view BUDDY_SHOOT_ANIMS[] = {"Left", "Up", "Right", "Down"}; + +// Baby Plum: its blows (12), the sweep's 13 shots a frame apart in 30 degree steps from straight down, its stomp's +// creep and two rings of tears, and the spray's tears every other frame up to 120 frames, all blood tears it chases +// enemies with, leading them by a tenth of their distance. +constexpr float BABY_PLUM_DAMAGE = 12; +constexpr float BABY_PLUM_TARGET_RANGE = 1000; +constexpr uint32_t BABY_PLUM_TARGET_FLAGS = TARGET_RETARGET | TARGET_PREFER_HEALTHY; +constexpr float BABY_PLUM_LEAD = 0.1f; +constexpr float BABY_PLUM_FALL = 0.099f; +constexpr float BABY_PLUM_SWEEP_SPEED = 4; +constexpr float BABY_PLUM_SWEEP_SLOWDOWN = 0.93f; +constexpr int BABY_PLUM_SWEEP_STEP = 30; +constexpr int BABY_PLUM_SWEEP_LAST = 360; +constexpr float BABY_PLUM_SWEEP_SHOT_SPEED = 7; +constexpr float BABY_PLUM_SWEEP_DAMAGE = 3.5f; +constexpr float BABY_PLUM_JUMP_REACH = 120; +constexpr float BABY_PLUM_JUMP_PULL = 0.2f; +constexpr int BABY_PLUM_STOMP_SHAKE = 5; +constexpr float BABY_PLUM_STOMP_CREEP_SCALE = 1.5f; +constexpr int BABY_PLUM_STOMP_CREEP_FRAMES = 150; +constexpr int BABY_PLUM_STOMP_FAST_TEARS = 8; +constexpr int BABY_PLUM_STOMP_SLOW_TEARS = 14; +constexpr float BABY_PLUM_STOMP_FAST_SPEED = 10; +constexpr float BABY_PLUM_STOMP_SLOW_SPEED = 5; +constexpr float BABY_PLUM_STOMP_DAMAGE = 5; +constexpr float BABY_PLUM_SPRAY_FRICTION = 0.98f; +constexpr float BABY_PLUM_SPRAY_SPEED = 5; +constexpr float BABY_PLUM_SPRAY_SPEED_SPREAD = 0.2f; +constexpr float BABY_PLUM_SPRAY_SPEED_MIN = 0.9f; +constexpr float BABY_PLUM_SPRAY_TURN = 60; +constexpr float BABY_PLUM_SPRAY_MOUTH = 12; +constexpr float BABY_PLUM_SPRAY_MOUTH_LIFT = 4; +constexpr int BABY_PLUM_SPRAY_SIZE_MAX = 4; +constexpr float BABY_PLUM_SPRAY_HEIGHT = 10; +constexpr float BABY_PLUM_SPRAY_DAMAGE = 3; +constexpr float BABY_PLUM_SPRAY_SPLASH_SPREAD = 0.3f; +constexpr float BABY_PLUM_SPRAY_SPLASH_MIN = 0.8f; +constexpr ColorMod BABY_PLUM_SPRAY_SPLASH_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.54901963f, 0.043137256f, 0.058823533f}}; +constexpr float BABY_PLUM_SPRAY_SPLASH_LIFT = -33; +constexpr float BABY_PLUM_SPRAY_SPLASH_DEPTH = 10; +constexpr float BABY_PLUM_SPRAY_BOUNCE_NORMAL = 0.2f; +constexpr float BABY_PLUM_SPRAY_TURN_DOT = 0.9f; +constexpr float BABY_PLUM_SPRAY_PUSH = 0.4f; +constexpr int BABY_PLUM_SPRAY_FRAMES = 120; +constexpr float BABY_PLUM_LEAVE_PUSH = 0.75f; +constexpr float BABY_PLUM_LEAVE_DRAG = 0.98f; +constexpr float BABY_PLUM_FRICTION = 0.8f; +constexpr float BABY_PLUM_FRICTION_LIGHT = 0.9f; + // A Lil Spewer kind from its state. static int spewer_kind(Entity_Familiar& spewer) { @@ -1176,3 +1270,605 @@ bool multidimensional_knife_copy(Entity_Knife& knife) if (knife.subtype == KNIFE_SUBTYPE_PATH) knife.Remove(); return true; } + +// Part of 00634b10: Buddy in a Box takes a co-op baby's look once, drawn from its seed and the floor's. +static void buddy_in_a_box_look(Entity_Familiar& buddy) +{ + std::vector& babies = g_manager->entityConfig.babies; + RNG rng{buddy.initSeed ^ g_game->dungeonPlacementSeed, 1, 21, 20}; + const EntityConfig_Baby* look = nullptr; + + for (int draw = 0; draw < BUDDY_LOOK_DRAWS && !look; draw++) + { + const EntityConfig_Baby& baby = babies[rng.Next() % babies.size()]; + if (baby.achievementID < 0 || g_manager->persistentGameData.Unlocked(baby.achievementID)) look = &baby; + } + if (!look) look = &babies[BUDDY_LOOK_FALLBACK_FIRST + rng.Next() % (babies.size() - BUDDY_LOOK_FALLBACK_FIRST)]; + + for (size_t layer = 0; layer < buddy.sprite.layerStates.size(); layer++) + buddy.sprite.ReplaceSpritesheet((int)layer, look->gfx); + buddy.sprite.LoadGraphics(); + buddy.subtype = 1; +} + +// Part of 00634b10: a tear of Buddy in a Box's own kind, strength, rise, colour and speed. +static void buddy_in_a_box_fire(Entity_Familiar& buddy, RNG& rng, int& direction) +{ + float scale = (buddy.GetMultiplier() * BUDDY_SCALE_BFFS + BUDDY_SCALE_BASE) * BUDDY_SCALE_SHARE; + WispTear kind; + monster_tear_pick(rng, kind); + float multiplier = buddy.GetMultiplier(); + float damage = rng.RandomFloat() * BUDDY_DAMAGE_SPREAD + BUDDY_DAMAGE_MIN; + float fall = rng.RandomFloat() * BUDDY_FALL_SPREAD + BUDDY_FALL_MIN; + float blue = rng.RandomFloat(); + float green = rng.RandomFloat(); + float red = rng.RandomFloat(); + ColorMod color = {{red, green, blue, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + + Vector aim = direction_unit(direction); + bool isAimingAtMark = buddy.TryAimAtMarkedTarget(aim, direction, nullptr); + float speed = rng.RandomFloat() * BUDDY_SPEED_SPREAD + BUDDY_SPEED_MIN; + Vector velocity = vector_scale(vector_scale(aim, BUDDY_SHOT_SPEED), speed); + if (!isAimingAtMark) + { + Vector drift = vector_scale(buddy.player->velocity, BUDDY_DRIFT_SHARE); + velocity = vector_make(drift.x + drift.x + velocity.x, drift.y + drift.y + velocity.y); + } + + Vector mouth = vector_add(vector_scale(aim, BUDDY_SHOT_SPEED), buddy.pos); + auto* tear = static_cast(g_game->Spawn({.position = mouth, + .velocity = velocity, + .spawner = &buddy, + .type = ENTITY_TEAR, + .variant = kind.variant, + .seed = Random()})); + tear->fallingAccel = 0; + tear->fallingSpeed = random_unit() * BUDDY_FALL_JITTER + fall; + tear->SetCollisionDamage(damage * multiplier); + tear->SetTearFlags(kind.flags); + scale = std::max(scale, TEAR_SCALE_MIN); + tear->baseScale = scale; + tear->fScale = scale; + tear->ResetSpriteScale(); + tear->parent = &buddy; + tear->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + tear->tearIdx = (int)(Random() & 1); + buddy.TryFireTear(tear); + buddy.shot_owner_convert(tear); + buddy.fireCooldown = familiar_lullaby_delay(buddy, (int)(rng.Next() % BUDDY_COOLDOWN_SPREAD) + BUDDY_COOLDOWN_MIN); + buddy.headFrameDelay = BUDDY_HEAD_FRAMES; +} + +// Stops a look on a frame. +static void buddy_head_set(Entity_Familiar& buddy, std::string_view anim, float frame) +{ + if (!buddy.sprite.SetAnimation(anim, SWITCH_RESET) || !buddy.sprite.animState.animData) return; + + buddy.sprite.animState.SetFrameFloat(frame); + if (buddy.sprite.animState.animData) buddy.sprite.animState.isPlaying = false; +} + +// 00634b10 Buddy in a Box follows in a co-op baby's look and shoots with its player, its head turned while it does and +// lowered a while after. Its random tears draw again from the same seed every shot. +void buddy_in_a_box_update(Entity_Familiar& buddy) +{ + if (buddy.subtype == 0) buddy_in_a_box_look(buddy); + RNG rng{buddy.initSeed ^ g_game->dungeonPlacementSeed, 1, 27, 27}; + if (buddy.player->isDead) return; + + if (buddy.fireCooldown > 0) buddy.fireCooldown--; + int direction = buddy.player->fireDirection; + if (direction == DIRECTION_NONE) + { + if (buddy.headFrameDelay >= 0 && --buddy.headFrameDelay < 0) buddy_head_set(buddy, "Down", 0); + return buddy.FollowParent(); + } + + if (buddy.fireCooldown < 1) buddy_in_a_box_fire(buddy, rng, direction); + else if (buddy.headFrameDelay <= BUDDY_HEAD_TURN_FRAMES) + { + buddy_head_set(buddy, BUDDY_SHOOT_ANIMS[direction], 0); + buddy.headFrameDelay = BUDDY_HEAD_TURN_FRAMES; + return buddy.FollowParent(); + } + buddy_head_set(buddy, BUDDY_SHOOT_ANIMS[direction], BUDDY_HEAD_SHOT_FRAME); + buddy.headFrameDelay--; + buddy.FollowParent(); +} + +// Baby Plum's attack states, after its descent. +enum BabyPlumState +{ + BABY_PLUM_START, + BABY_PLUM_DESCEND = 3, + BABY_PLUM_SWEEP, + BABY_PLUM_STOMP, + BABY_PLUM_SPRAY, + BABY_PLUM_LEAVE +}; + +// The target Baby Plum picks, or none. +static Entity* plum_target_pick(Entity_Familiar& plum) +{ + plum.PickEnemyTarget({.range = BABY_PLUM_TARGET_RANGE, .flags = BABY_PLUM_TARGET_FLAGS}); + return plum.target; +} + +// Where Baby Plum's target will be, a tenth of its distance ahead, from the target it picks, or none. +static Entity* plum_target_lead(Entity_Familiar& plum, Vector& lead) +{ + Entity* target = plum_target_pick(plum); + if (!target) return nullptr; + + float distance = vector_length(vector_sub(plum.pos, target->pos)); + lead = vector_add(vector_scale(target->velocity, distance * BABY_PLUM_LEAD), target->pos); + return target; +} + +// One of Baby Plum's blood tears, falling a little faster, turned on the player when Baby Plum is charmed. +static Entity_Tear* plum_tear(Entity_Familiar& plum, Vector position, Vector velocity, float damage) +{ + auto* tear = static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = &plum, + .type = ENTITY_TEAR, + .variant = TEAR_BLOOD, + .seed = Random()})); + tear->fallingAccel -= BABY_PLUM_FALL; + if (damage > 0) tear->SetCollisionDamage(damage); + return tear; +} + +// Baby Plum's stomp: a shake, a big pool of creep and two rings of tears. +static void plum_stomp(Entity_Familiar& plum) +{ + game_shake_screen(BABY_PLUM_STOMP_SHAKE); + familiar_sound_play(SOUND_MEAT_JUMPS); + plum.fireCooldown = 0; + plum.targetPosition = {}; + auto* creep = static_cast(g_game->Spawn({.position = plum.pos, + .spawner = &plum, + .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_RED, + .seed = Random()})); + creep->sprite.scale = vector_make(BABY_PLUM_STOMP_CREEP_SCALE, BABY_PLUM_STOMP_CREEP_SCALE); + creep->SetTimeout(BABY_PLUM_STOMP_CREEP_FRAMES); + + for (int i = 0; i < BABY_PLUM_STOMP_FAST_TEARS; i++) + { + float angle = (float)i * FULL_TURN_DEGREES * (1.0f / BABY_PLUM_STOMP_FAST_TEARS); + plum.shot_owner_convert(plum_tear(plum, plum.pos, vector_scale(vector_from_angle(angle), BABY_PLUM_STOMP_FAST_SPEED), + BABY_PLUM_STOMP_DAMAGE)); + } + for (int i = 0; i < BABY_PLUM_STOMP_SLOW_TEARS; i++) + { + float angle = (float)i * FULL_TURN_DEGREES / BABY_PLUM_STOMP_SLOW_TEARS; + plum.shot_owner_convert(plum_tear(plum, plum.pos, vector_scale(vector_from_angle(angle), BABY_PLUM_STOMP_SLOW_SPEED), + BABY_PLUM_STOMP_DAMAGE)); + } +} + +// A tear of Baby Plum's spray from its mouth behind it, of a random size, with a dark red splash. +static void plum_spray_shot(Entity_Familiar& plum) +{ + familiar_sound_play(SOUND_BOSS2_BUBBLES); + float speed = random_unit() * BABY_PLUM_SPRAY_SPEED_SPREAD + BABY_PLUM_SPRAY_SPEED_MIN; + Vector back = vector_make(-plum.targetPosition.x * BABY_PLUM_SPRAY_SPEED * speed, + -plum.targetPosition.y * BABY_PLUM_SPRAY_SPEED * speed); + Vector velocity = vector_rotated(back, random_unit() * BABY_PLUM_SPRAY_TURN - BABY_PLUM_SPRAY_TURN / 2); + Vector mouth = + vector_make(plum.pos.x - plum.targetPosition.x * BABY_PLUM_SPRAY_MOUTH, plum.pos.y - BABY_PLUM_SPRAY_MOUTH_LIFT); + float size = random_unit(); + + Entity_Tear* tear = plum_tear(plum, mouth, velocity, 0); + float scale = std::max(tear_size_scale(BABY_PLUM_SPRAY_SIZE_MAX - (int)(size * -BABY_PLUM_SPRAY_SIZE_MAX)), TEAR_SCALE_MIN); + tear->baseScale = scale; + tear->fScale = scale; + tear->ResetSpriteScale(); + tear->SetHeight(tear->height - BABY_PLUM_SPRAY_HEIGHT); + tear->SetCollisionDamage(size + BABY_PLUM_SPRAY_DAMAGE); + plum.shot_owner_convert(tear); + + Entity* splash = g_game->Spawn({.position = mouth, .type = ENTITY_EFFECT, .variant = EFFECT_TEAR_POOF_SMALL, + .seed = Random()}); + splash->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + float splashScale = random_unit() * BABY_PLUM_SPRAY_SPLASH_SPREAD + BABY_PLUM_SPRAY_SPLASH_MIN; + splash->sprite.scale = vector_make(splashScale, splashScale); + splash->sprite.color = BABY_PLUM_SPRAY_SPLASH_COLOR; + splash->posOffset = vector_make(0, BABY_PLUM_SPRAY_SPLASH_LIFT); + if (plum.targetPosition.y < 0) splash->renderDepthOffset = BABY_PLUM_SPRAY_SPLASH_DEPTH; +} + +// Baby Plum's spray: it rises, then flies off diagonally spraying behind it, bouncing off walls and turning toward a +// target close ahead, until it heads up past 120 frames. +static void plum_spray(Entity_Familiar& plum) +{ + if (plum.fireCooldown == -1) + { + plum.friction *= BABY_PLUM_FRICTION; + plum.sprite.Play("Attack3"); + if (plum.sprite.IsEventTriggered("Shoot")) + { + float side = (Random() & 1) == 0 ? 1.0f : -1.0f; + plum.sprite.isFlipX = side < 0; + plum.targetPosition = vector_normalized(vector_make(side, -1)); + plum.fireCooldown = 0; + } + } + else if (plum.fireCooldown == -2) + { + plum.friction *= BABY_PLUM_FRICTION_LIGHT; + plum.sprite.Play("Attack3End"); + if (!plum.sprite.IsPlaying()) + { + plum.state = BABY_PLUM_LEAVE; + plum.targetPosition = {}; + plum.fireCooldown = -1; + plum.headFrameDelay = 0; + } + } + if (plum.fireCooldown < 0) return; + + if (!plum.sprite.IsPlaying()) plum.sprite.Play("Attack3Loop"); + plum.friction = BABY_PLUM_SPRAY_FRICTION; + if (++plum.fireCooldown % 2 == 0) plum_spray_shot(plum); + + if (plum.isCollidesWithGrid) + { + Vector normal = plum.gridCollisionNormal; + Vector& heading = plum.targetPosition; + float bounce = BABY_PLUM_SPRAY_BOUNCE_NORMAL; + if ((heading.x > 0 && normal.x > bounce) || (heading.x < 0 && normal.x < -bounce)) heading.x = -heading.x; + if ((heading.y > 0 && normal.y > bounce) || (heading.y < 0 && normal.y < -bounce)) heading.y = -heading.y; + plum.velocity = vector_normalized(plum.velocity); + if (Entity* target = plum_target_pick(plum)) + { + float distance = vector_length(vector_sub(plum.pos, target->pos)); + Vector lead = vector_add(vector_scale(vector_scale(target->velocity, distance), BABY_PLUM_LEAD), target->pos); + Vector toward = vector_normalized(vector_sub(lead, plum.pos)); + if (vector_dot(toward, plum.velocity) > BABY_PLUM_SPRAY_TURN_DOT) plum.velocity = toward; + } + plum.velocity = vector_scale(plum.velocity, vector_length(plum.gridCollisionVelocity)); + } + + plum.sprite.Play(plum.targetPosition.y > 0 ? "Attack3BackLoop" : "Attack3Loop"); + plum.sprite.isFlipX = plum.targetPosition.x < 0; + plum.velocity = vector_add(vector_scale(plum.targetPosition, BABY_PLUM_SPRAY_PUSH), plum.velocity); + if (plum.fireCooldown > BABY_PLUM_SPRAY_FRAMES && plum.targetPosition.y < 0) + { + plum.sprite.isFlipX = false; + plum.fireCooldown = -2; + } +} + +// Baby Plum's sweep: on its shot it aims at its target (or its player) and slides there, firing a fan of tears a frame +// apart that turns from straight down, slowing as it goes, then stomps. +static void plum_sweep(Entity_Familiar& plum) +{ + plum.friction *= BABY_PLUM_FRICTION; + plum.sprite.Play("Attack1"); + if (plum.sprite.IsEventTriggered("Shoot")) + { + Vector lead; + if (!plum_target_lead(plum, lead)) lead = plum.player->pos; + Vector aim = vector_normalized(vector_sub(lead, plum.pos)); + plum.targetPosition = vector_scale(aim, BABY_PLUM_SWEEP_SPEED); + plum.fireCooldown = 0; + plum.sprite.isFlipX = plum.targetPosition.x < 0; + } + if (plum.sprite.IsEventTriggered("Sound")) plum.sprite.isFlipX = false; + if (plum.sprite.IsPlaying()) + { + if (plum.fireCooldown < 0) return; + + if (plum.fireCooldown <= BABY_PLUM_SWEEP_LAST) + { + float step = (float)plum.fireCooldown; + float angle = plum.sprite.isFlipX ? step + RIGHT_ANGLE_DEGREES : RIGHT_ANGLE_DEGREES - step; + Vector velocity = vector_scale(vector_from_angle(angle), BABY_PLUM_SWEEP_SHOT_SPEED); + plum.shot_owner_convert(plum_tear(plum, plum.pos, velocity, BABY_PLUM_SWEEP_DAMAGE)); + } + plum.velocity = vector_add(plum.velocity, plum.targetPosition); + plum.targetPosition = vector_scale(plum.targetPosition, BABY_PLUM_SWEEP_SLOWDOWN); + plum.fireCooldown += BABY_PLUM_SWEEP_STEP; + return; + } + plum.state = BABY_PLUM_STOMP; + plum.fireCooldown = -1; + plum.targetPosition = {}; +} + +// Baby Plum's stomp: it jumps toward its target (120 at most) and lands with creep and tears, then sprays. +static void plum_jump(Entity_Familiar& plum) +{ + plum.friction *= BABY_PLUM_FRICTION_LIGHT; + plum.sprite.Play("Attack2"); + plum.entityGridCollisionClass = GRIDCOLL_WALLS; + Vector lead; + if (plum.sprite.IsEventTriggered("Jump") && plum_target_lead(plum, lead)) + { + Vector reach = vector_sub(lead, plum.pos); + float distance = vector_length(reach); + if (distance > BABY_PLUM_JUMP_REACH && distance > 0) reach = vector_scale(reach, BABY_PLUM_JUMP_REACH / distance); + plum.targetPosition = vector_add(plum.pos, reach); + } + if (!vector_is_zero(plum.targetPosition)) + plum.velocity = vector_scale(vector_sub(plum.targetPosition, plum.pos), BABY_PLUM_JUMP_PULL); + + if (plum.sprite.IsEventTriggered("Shoot")) plum_stomp(plum); + if (plum.sprite.IsEventTriggered("Sound")) plum.fireCooldown = -1; + else if (plum.fireCooldown >= 0) + { + plum.entityGridCollisionClass = GRIDCOLL_GROUND; + plum.friction *= HALF; + } + if (plum.sprite.IsPlaying()) return; + + plum.state = BABY_PLUM_SPRAY; + plum.fireCooldown = -1; +} + +// Baby Plum leaves: on its shot it flies off sideways away from the room's centre, and goes when done. +static void plum_leave(Entity_Familiar& plum) +{ + plum.sprite.Play("Leave"); + plum.entityCollisionClass = ENTCOLL_NONE; + plum.entityGridCollisionClass = GRIDCOLL_NONE; + if (plum.fireCooldown == -2) + { + plum.velocity = vector_add(vector_scale(plum.targetPosition, BABY_PLUM_LEAVE_PUSH), plum.velocity); + plum.friction *= BABY_PLUM_LEAVE_DRAG; + } + else + { + if (plum.sprite.IsEventTriggered("Shoot")) + { + plum.fireCooldown = -2; + bool isRightOfCentre = Room::GetCenterPos().x <= plum.pos.x; + plum.targetPosition = vector_make(isRightOfCentre ? 1.0f : -1.0f, 0); + plum.sprite.isFlipX = !isRightOfCentre; + } + plum.friction *= BABY_PLUM_FRICTION; + } + if (!plum.sprite.IsPlaying()) plum.Remove(); +} + +// 0063e180 Baby Plum (Plum Flute) lends itself as the target of its player's Plum Flute wisps on its first frame, +// descends, then sweeps, stomps, sprays and leaves. +void baby_plum_update(Entity_Familiar& plum) +{ + if (g_game->frameCount - plum.spawnFrame == 1) + for (Entity* entity : g_game->room->entityList.updateEL) + { + auto* wisp = static_cast(entity); + bool isFluteWisp = entity && entity->type == ENTITY_FAMILIAR && wisp->player == plum.player && + entity->variant == Entity_Familiar::WISP && entity->subtype == COLLECTIBLE_PLUM_FLUTE; + if (isFluteWisp && !entity->target) entity->target = &plum; + } + + switch (plum.state) + { + case BABY_PLUM_START: + plum.state = BABY_PLUM_DESCEND; + break; + case BABY_PLUM_DESCEND: + plum.friction *= BABY_PLUM_FRICTION; + if (plum.sprite.IsPlaying()) break; + plum.entityCollisionClass = ENTCOLL_ALL; + plum.entityGridCollisionClass = GRIDCOLL_WALLS; + plum.state = BABY_PLUM_SWEEP; + plum.fireCooldown = -1; + plum.SetCollisionDamage(BABY_PLUM_DAMAGE); + break; + case BABY_PLUM_SWEEP: return plum_sweep(plum); + case BABY_PLUM_STOMP: return plum_jump(plum); + case BABY_PLUM_SPRAY: return plum_spray(plum); + case BABY_PLUM_LEAVE: return plum_leave(plum); + } +} + +// Whether a list holds a variant. +template +static bool is_variant_listed(const int (&list)[N], int variant) +{ + return std::find(std::begin(list), std::end(list), variant) != std::end(list); +} + +// Whether a shot may be copied: in a versus match only when the familiar descends from the shot's spawner. +static bool is_versus_shot_kept(Entity& familiar, Entity& shot) +{ + return !g_game->deathmatchManager.is_active() || familiar.IsDescendantOf(shot.spawnerEntity.get()); +} + +// Part of 0061da10: a tear through Multidimensional Baby goes a third faster and higher, steps aside and gains a twin +// on its other side, a Ludovico tear once each of its player's fire delays. +static void multidimensional_tear_copy(Entity_Familiar& baby, Entity_Tear& tear) +{ + if (is_variant_listed(PRISMLESS_TEAR_VARIANTS, tear.variant)) return; + if (tear.tearFlags[TEAR_LUDOVICO] && !tear.GetIntervalTicks(baby.player->maxFireDelay, 0)) return; + if (tear.isMultidimensionalTouched) return; + + tear.isMultidimensionalTouched = true; + bool isWaiting = tear.waitFrames > 0; + Vector motion = isWaiting ? tear.continueVelocity : tear.velocity; + if (isWaiting) tear.continueVelocity = vector_scale(motion, MULTIDIMENSIONAL_TEAR_SPEED); + else tear.velocity = vector_scale(motion, MULTIDIMENSIONAL_TEAR_SPEED); + tear.SetHeight(tear.height * MULTIDIMENSIONAL_TEAR_HEIGHT); + + Vector side = vector_normalized(vector_rotated(motion, RIGHT_ANGLE_DEGREES)); + tear.pos = vector_sub(tear.pos, vector_scale(side, MULTIDIMENSIONAL_TEAR_SHIFT)); + if (!is_variant_listed(MULTIDIMENSIONAL_KEPT_VARIANTS, tear.variant)) tear.ChangeVariant(TEAR_MULTIDIMENSIONAL); + Entity_Tear* copy = tear.MakeMultidimensionalCopy(tear.spawnerEntity.get()); + copy->parent = tear.parent.get(); + copy->pos = vector_add(tear.pos, vector_scale(side, MULTIDIMENSIONAL_TEAR_SIDE)); + copy->Update(); +} + +// Part of 0061da10 (case 101): Multidimensional Baby trails behind and doubles the tears and flying knives passing +// through it. +void multidimensional_baby_update(Entity_Familiar& baby) +{ + baby.MoveDelayed(MULTIDIMENSIONAL_FOLLOW_FRAMES); + for (Entity* entity : entity_query_radius(baby.pos, baby.size, QUERY_TEARS)) + { + if (entity->isDead || !is_versus_shot_kept(baby, *entity)) continue; + + if (entity->type == ENTITY_KNIFE) + { + auto& knife = *static_cast(entity); + if (knife.isFlying) multidimensional_knife_copy(knife); + } + else if (entity->type == ENTITY_TEAR) multidimensional_tear_copy(baby, *static_cast(entity)); + } + baby.PlayFloatAnim(DIRECTION_DOWN); +} + +// Part of 0061da10: a tear in Angelic Prism splits into four tinted ones fanned out (a Ludovico tear leaves the +// original and spreads its copies once each fire delay), each like it but no longer Ludovico. +static void prism_tear_split(Entity_Familiar& prism, Entity_Tear& tear) +{ + if (tear.isPrismTouched) return; + if (g_game->deathmatchManager.is_active() && !tear.IsDescendantOf(prism.spawnerEntity.get())) return; + + bool isLudovico = tear.tearFlags[TEAR_LUDOVICO]; + if (!isLudovico) tear.Remove(); + else if (!tear.GetIntervalTicks(prism.player->maxFireDelay, 0)) return; + + TearFlags flags = tear.tearFlags; + flags.reset(TEAR_LUDOVICO); + for (size_t i = 0; i < PRISM_COLORS.size(); i++) + { + auto* copy = static_cast(g_game->Spawn({.position = tear.pos, + .velocity = tear.velocity, + .spawner = tear.spawnerEntity.get(), + .subType = tear.subtype, + .type = ENTITY_TEAR, + .variant = tear.variant, + .seed = tear.initSeed})); + copy->SetHeight(tear.height); + copy->fallingSpeed = tear.fallingSpeed; + copy->fallingAccel = tear.fallingAccel; + copy->homingFriction = tear.homingFriction; + copy->SetScale(tear.baseScale); + copy->SetTearFlags(flags); + copy->waitFrames = tear.waitFrames; + copy->tearIdx = tear.tearIdx; + copy->SetCollisionDamage(tear.collisionDamage); + copy->rotation = tear.rotation; + copy->knockbackMultiplier = tear.knockbackMultiplier; + copy->SetDeadEyeIntensity(tear.deadEyeIntensity); + copy->isMultidimensionalTouched = tear.isMultidimensionalTouched; + copy->isCanTriggerStreakEnd = false; + copy->isPrismTouched = true; + copy->parent = tear.parent.get(); + copy->spawnerEntity = tear.spawnerEntity.get(); + float turn = (float)i; + Vector push = vector_scale(vector_from_angle(turn * RIGHT_ANGLE_DEGREES), PRISM_LUDOVICO_PUSH); + if (isLudovico) copy->velocity = vector_add(copy->velocity, push); + else copy->velocity = vector_rotated(copy->velocity, PRISM_FAN_FIRST - turn * PRISM_FAN_STEP); + copy->SetColor(PRISM_COLORS[i], -1, COLOR_PRIORITY_DEFAULT, false, true); + copy->Update(); + } +} + +// Part of 0061da10: a fetus bomb in Angelic Prism splits into four tinted ones fanned out, each like it. +static void prism_bomb_split(Entity_Bomb& bomb) +{ + if (bomb.isPrismTouched || !bomb.isFetus) return; + + bomb.Remove(); + for (size_t i = 0; i < PRISM_COLORS.size(); i++) + { + auto* copy = static_cast(g_game->Spawn({.position = bomb.pos, + .velocity = bomb.velocity, + .spawner = bomb.spawnerEntity.get(), + .subType = bomb.subtype, + .type = bomb.type, + .variant = bomb.variant, + .seed = bomb.initSeed})); + copy->isFetus = bomb.isFetus; + copy->AddEntityFlags(FLAG_NO_KNOCKBACK); + copy->entityGridCollisionClass = bomb.entityGridCollisionClass; + copy->isPrismTouched = true; + copy->tearFlags = bomb.tearFlags; + copy->isLoadCostumes = true; + copy->explosionDamage = bomb.explosionDamage; + copy->SetExplosionCountdown(bomb.explosionCountdown); + copy->radiusMultiplier = bomb.radiusMultiplier; + float turn = PRISM_FAN_FIRST - (float)i * PRISM_FAN_STEP; + copy->velocity = vector_rotated(copy->velocity, turn); + copy->rocketAngle = bomb.rocketAngle + turn; + copy->rocketSpeed = bomb.rocketSpeed; + copy->SetColor(PRISM_COLORS[i], -1, COLOR_PRIORITY_DEFAULT, false, true); + } +} + +// Part of 0061da10: a Tech X ring holding Angelic Prism within half its radius splits into four of its player's, +// fanned 30 and 10 degrees either side and tinted, each like it. +static void prism_ring_split(Entity_Familiar& prism, Entity_Laser& ring) +{ + if (ring.isPrismTouched) return; + float reach = ring.radius * PRISM_RING_SHARE; + if (vector_length_squared(vector_sub(ring.pos, prism.pos)) > reach * reach) return; + + for (size_t i = 0; i < PRISM_LASER_COLORS.size(); i++) + { + auto* copy = static_cast(g_game->Spawn({.position = ring.pos, + .velocity = ring.velocity, + .spawner = prism.player, + .subType = ring.subtype, + .type = ENTITY_LASER, + .variant = ring.variant, + .seed = Random()})); + copy->posOffset = ring.posOffset; + copy->radius = ring.radius; + copy->spawnerEntity = prism.player; + copy->isDisableFollowParent = true; + copy->tearFlags = ring.tearFlags; + copy->maxDistance = ring.maxDistance; + copy->blackHpDropChance = ring.blackHpDropChance; + copy->SetCollisionDamage(ring.collisionDamage); + copy->renderDepthOffset = ring.renderDepthOffset; + copy->dropRNG = DROP_RNG_SAVED; + copy->dropRNG._seed = ring.initSeed; + copy->entityGridCollisionClass = ring.entityGridCollisionClass; + copy->homingType = ring.homingType; + copy->spawnerType = ring.spawnerType; + copy->targetPosition = ring.targetPosition; + copy->isMultidimensionalTouched = ring.isMultidimensionalTouched; + copy->parent = prism.player; + copy->timeout = ring.timeout; + copy->isOneHit = ring.isOneHit; + copy->isShrink = ring.isShrink; + copy->isVisible = ring.isVisible; + copy->velocity = vector_rotated(copy->velocity, PRISM_LASER_SPREAD[i]); + copy->SetColor(PRISM_LASER_COLORS[i], -1, COLOR_PRIORITY_DEFAULT, false, true); + copy->isPrismTouched = true; + copy->Update(); + } + ring.Remove(); +} + +// Part of 0061da10 (case 123): Angelic Prism orbits its player and splits the tears, fetus bombs, Tech X rings and +// flying knives that pass through it into four tinted ones. The shots it makes, marked as split, are not split again. +void angelic_prism_update(Entity_Familiar& prism) +{ + prism.velocity = vector_sub(prism.GetOrbitPosition(prism.player->pos), prism.pos); + EntityList_EL entities = g_game->room->entityList.updateEL; + for (Entity* entity : entities) + { + if (entity->isDead) continue; + + bool isNear = vector_length_squared(vector_sub(entity->pos, prism.pos)) < PRISM_REACH_SQUARED; + if (entity->type == ENTITY_TEAR && isNear) prism_tear_split(prism, *static_cast(entity)); + else if (entity->type == ENTITY_BOMB && isNear) prism_bomb_split(*static_cast(entity)); + else if (entity->type == ENTITY_LASER && entity->subtype == LASER_SUBTYPE_RING_PROJECTILE) + prism_ring_split(prism, *static_cast(entity)); + else if (entity->type == ENTITY_KNIFE) + { + auto& knife = *static_cast(entity); + bool isInReach = vector_length_squared(vector_sub(knife.pos, prism.pos)) <= PRISM_REACH_SQUARED; + if (!knife.isPrismApplied && knife.isFlying && isInReach) knife.spawn_child_knife(); + } + } +} diff --git a/src/familiar_collision.cpp b/src/familiar_collision.cpp index 01effec..27c41e4 100644 --- a/src/familiar_collision.cpp +++ b/src/familiar_collision.cpp @@ -172,6 +172,10 @@ constexpr uint64_t DAMAGE_ISAACS_HEART = 1ull << 11; constexpr float PUNCHING_BAG_KNOCKBACK = 5; constexpr float DIP_HURT_VOLUME = 0.8f; constexpr int DIP_HURT_DELAY = 15; +constexpr int VERSUS_BAG_COUNTDOWN = 4; +constexpr int LEECH_HEAL_DAMAGE = 50; +constexpr float LEECH_HEART_LIFT = -24; +constexpr int MILK_HIT_COUNTDOWN = 30; // The familiars that never yield to what they touch, unless it is a player or a bomb. constexpr int SOLID_VARIANTS[] = {62, 67, 228, 238}; @@ -284,6 +288,23 @@ static void bone_wear(Entity_Familiar& bone, Entity& collider) if (bone.state > BONE_WEAR_LIMIT) bone.Kill(EntityRef()); } +// Part of 006261f0: in a versus match the Leech heals its player a half heart for every 50 damage it deals. +static void leech_versus_drain(Entity_Familiar& leech, float dealt) +{ + leech.roomClearCount += (int)(dealt + HALF); + for (; leech.roomClearCount > LEECH_HEAL_DAMAGE; leech.roomClearCount -= LEECH_HEAL_DAMAGE) + { + Entity_Player* player = leech.player; + if (!player || player->isDead) continue; + + player->AddHearts(1, false, false); + Entity* heart = + g_game->Spawn({.position = player->pos, .type = ENTITY_EFFECT, .variant = EFFECT_HEART, .seed = Random()}); + heart->sprite.offset = vector_make(0, LEECH_HEART_LIFT); + heart->renderDepthOffset = 1; + } +} + // After a familiar's hit hurts an enemy (part of 006261f0): Cube Baby's slowing ice, the Shade's and the bones' wear, // Leprosy's, then Guppy's Hairball calling a blue fly where the challenge forbids shooting, Lil Haunt's scare and Mom's // Razor's bleed. @@ -297,7 +318,7 @@ void Entity_Familiar::collision_hurt(Entity& collider, float damageMultiplier, f collider.AddSlowing(EntityRef(this), frames, CUBE_SLOWING, CUBE_SLOW_COLOR, false); collider.AddIce(EntityRef(this), CUBE_ICE_FRAMES); } - if (variant == LEECH && familiar_versus()) reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (a versus Leech)"); + if (variant == LEECH && familiar_versus()) leech_versus_drain(*this, dealt); if (variant == LIL_GURDY && damageMultiplier > 0) lil_gurdy_bounce(*this, collider); if (variant == SHADE) state += (int)dealt; @@ -374,17 +395,45 @@ bool Entity_Familiar::collision_contact(Entity& collider, float damageMultiplier isVisible = false; familiar_sound_play(SOUND_EDEN_GLITCH); subtype = 1; - reconstruction_missing("Game::RerollEnemy 007050c0 (GB Bug's reroll of an enemy)"); + g_game->RerollEnemy(&collider, REROLL_MATCH_HEALTH); } if (variant == BBF || variant == BOBS_BRAIN) brain_explode(*this, collider, damageMultiplier); if (variant == HOLY_WATER && subtype == 0) holy_water_break(*this); return isIgnored; } +// Part of 006261f0: Slipped Rib bounces a shot coming at the face it turns along its orbit back the other way, pushed +// on by its player's motion toward that side (no faster than the shot or the player), as the enemies' shot or a tear +// of its own. +static void slipped_rib_reflect(Entity_Familiar& rib, Entity& shot) +{ + float turn = orbit_layer_angle_offset(rib.orbitLayer) * HALF_TURN_DEGREES / PI_F + rib.sprite.GetLayer(0)->rotation; + float angle = turn * DEGREES_TO_RADIANS; + Vector facing = vector_make(std::cos(angle), std::sin(angle)); + float along = facing.x * shot.velocity.x + facing.y * shot.velocity.y; + if (along >= 0) return; + + Vector reflected = vector_make(shot.velocity.x - (facing.x + facing.x) * along, + shot.velocity.y - (facing.y + facing.y) * along); + Vector carried = rib.player->velocity; + float push = facing.y * carried.y + facing.x * carried.x; + if (push > 0) + { + reflected = vector_make(carried.x * push + reflected.x, carried.y * push + reflected.y); + float limit = std::max(vector_length(carried), vector_length(shot.velocity)); + if (vector_length(reflected) > limit) reflected = vector_resized(reflected, limit); + } + + if (shot.type == ENTITY_PROJECTILE) static_cast(shot).Reflect(reflected); + else if (shot.type == ENTITY_TEAR) static_cast(shot).Deflect(&rib, reflected); + else return; + familiar_sound_play(SOUND_RIB_DEFLECT, {.volume = rib.player->local_volume_get()}); +} + // A projectile or tear meeting a familiar (part of 006261f0): one that cannot be stopped passes, a blocking familiar // stops it. Dry Baby may answer with the Necronomicon and Farting Baby with a fart, Sworn Protector counts its blocks -// for an eternal heart, Leprosy and Bone Spur wear and the bone and swarm orbitals break. Slipped Rib's reflection and -// the familiars hurt by a block stop the game. +// for an eternal heart, Leprosy and Bone Spur wear and the bone and swarm orbitals break, and Slipped Rib reflects +// what comes at its face. bool Entity_Familiar::collision_block(Entity& collider, bool isIgnored) { if (collider.type == ENTITY_PROJECTILE && @@ -394,7 +443,8 @@ bool Entity_Familiar::collision_block(Entity& collider, bool isIgnored) if (!CanBlockProjectiles()) { if (variant != SLIPPED_RIB) return true; - reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (Slipped Rib's reflection)"); + slipped_rib_reflect(*this, collider); + return isIgnored; } if (variant == DRY_BABY) @@ -576,8 +626,7 @@ static bool dip_touch(Entity_Familiar& dip, Entity& enemy, float damageMultiplie // 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 // spinning orbital hits, Skatole and Beelzebub keep the flies off the player, a familiar with contact damage hurts -// enemies (once per hit list) and a blocking one stops shots. Returns whether the touch is ignored. The familiars with -// their own touch still unwritten stop the game. +// enemies (once per hit list) and a blocking one stops shots. Returns whether the touch is ignored. bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) { if (familiar_versus()) @@ -604,8 +653,6 @@ bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) isIgnored = false; } if (variant == PSY_FLY && psy_fly_touch(*this, *collider)) return true; - if (sirenHelper) - reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (this familiar's touch)"); if (variant == DEPRESSION) depression_touch(*this, *collider); float damageMultiplier = collision_multiplier(*collider); @@ -693,17 +740,17 @@ bool Entity_Familiar::solid_check(Entity& collider, bool isIgnored) } // 0062cdc0 A hit on a familiar: shielded from friends, spikes and poop (Isaac's Heart excepted), Isaac's Heart passing -// it to its player, the Punching Bag knocked back, a Dip squeaking, the Lost Soul losing its mantle or dying. Milk -// stops the game. +// it to its player, the Punching Bag knocked back (briefly shielded in a versus match), a Dip squeaking, the Lost Soul +// losing its mantle or dying, Milk filling up without losing health. bool Entity_Familiar::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& source, int damageCountdown) { if (IsDamageSourceFriendly(source) || source.IsFriendly()) return false; if ((damageFlags & (DAMAGE_SPIKES | DAMAGE_POOP)) && variant != ISAACS_HEART) return false; - if (variant == MILK) reconstruction_missing("Entity_Familiar::TakeDamage 0062cdc0 (this familiar's hit)"); bool isWisp = variant == WISP || variant == ITEM_WISP; if (isWisp && !wisp_take_damage(damage, damageFlags, source)) return false; if (isWisp) damageCountdown = wisp_hit_countdown(damageCountdown); - if (variant == BLOOD_BABY && counter > 0) return false; + if (g_game->deathmatchManager.is_active() && variant == PUNCHING_BAG) damageCountdown = VERSUS_BAG_COUNTDOWN; + else if (variant == BLOOD_BABY && counter > 0) return false; bool isPassed = variant == ISAACS_HEART || (g_game->challenge == CHALLENGE_GUARDIAN && variant == PUNCHING_BAG); bool isDamaged = @@ -715,13 +762,20 @@ bool Entity_Familiar::TakeDamage(float damage, uint64_t damageFlags, const Entit if (variant == PUNCHING_BAG && friction != 0) { - Vector away = vector_normalized(vector_sub(pos, source.position)); - velocity = vector_add(velocity, vector_scale(away, PUNCHING_BAG_KNOCKBACK * speedMultiplier / friction)); + Vector push = vector_scale(vector_scale(vector_normalized(vector_sub(pos, source.position)), PUNCHING_BAG_KNOCKBACK), + speedMultiplier); + velocity = vector_add(velocity, vector_make(push.x / friction, push.y / friction)); } if (variant == DIP && (Random() & 1) == 0) familiar_sound_play(SOUND_DIP_HURT, {.volume = DIP_HURT_VOLUME, .frameDelay = DIP_HURT_DELAY}); if (isWisp) wisp_countdown_share(*this); if (variant == LOST_SOUL) lost_soul_hurt(*this); + if (variant == MILK) + { + if ((uint32_t)subtype < (uint32_t)maxSubtype && (uint32_t)++subtype == (uint32_t)maxSubtype) sprite.Play("Drop"); + this->damageCountdown = MILK_HIT_COUNTDOWN; + health += damage; + } return isDamaged; } diff --git a/src/familiar_follow.cpp b/src/familiar_follow.cpp index 36e391c..887473a 100644 --- a/src/familiar_follow.cpp +++ b/src/familiar_follow.cpp @@ -145,6 +145,12 @@ static const OrbitLayer& orbit_layer(int layer) return ORBIT_LAYER_TABLE[std::clamp(layer, 0, ORBIT_LAYER_MAX)]; } +// The angle in radians an orbit layer's first orbital starts at. +float orbit_layer_angle_offset(int layer) +{ + return orbit_layer(layer).angleOffset; +} + // Whether a familiar is one of the wisps whose orbit is twice as fast. static bool is_wide_wisp(Entity_Familiar& familiar) { diff --git a/src/familiar_locust.cpp b/src/familiar_locust.cpp index 144d697..29611ab 100644 --- a/src/familiar_locust.cpp +++ b/src/familiar_locust.cpp @@ -15,6 +15,7 @@ #include "manager.h" #include "npc_ai.h" #include "npc_basement.h" +#include "pocket_items.h" #include "room.h" #include "room_grid.h" #include "seeds.h" @@ -718,9 +719,27 @@ static void locust_rift(Entity_Familiar& locust, float scale) familiar_sound_play(SOUND_OCCULAR_RIFT_PORTAL); } +// Part of 00649290: the locust devolves a living enemy it has not hit yet that the hit leaves alive (no fireplace, +// shopkeeper, TNT, poop, prop, minecart or blood cultist's spawn), remembering the weaker form so it is not hit again. +static void locust_devolve(Entity_Familiar& locust, Entity& target) +{ + int type = target.type; + bool isExcluded = type == ENTITY_PLAYER || type == ENTITY_FIREPLACE || type == ENTITY_SHOPKEEPER || + type == ENTITY_MOVABLE_TNT || type == ENTITY_GENERIC_PROP || type == ENTITY_MINECART || + type == ENTITY_POOP || (type == ENTITY_CULTIST && target.variant == CULTIST_BLOOD_SPAWN); + std::vector& hitList = locust_data(locust).devolvedHitList; + if (!Entity::is_enemy_type(type) || isExcluded || target.isDead) return; + if (EntityList::HitListContains(hitList, target) || target.HasMortalDamage() || !target.CanDevolve()) return; + + familiar_sound_play(SOUND_EDEN_GLITCH); + Entity* devolved = nullptr; + game_enemy_devolve(target, &devolved); + if (devolved) hit_list_insert(hitList, *devolved); +} + // 00649290 What a locust's hit sets off besides the tear effects: bone shards, a rift, an explosion, Black Powder's -// circle, creep, the Necronomicon, the Maw of the Void's ring, farts, a brimstone beam and Jacob's Ladder. Devolving, -// erasing and the shockwave stop the game. +// circle, creep, the Necronomicon, the Maw of the Void's ring, farts, a brimstone beam and Jacob's Ladder, devolving +// and erasing. static void locust_hit_effects(Entity_Familiar& locust, const TearFlags& flags, uint32_t locustFlags, Entity& target) { Entity_Player& player = *locust.player; @@ -773,12 +792,11 @@ static void locust_hit_effects(Entity_Familiar& locust, const TearFlags& flags, circle->Update(); } if (locustFlags & LOCUST_FLAGS_CREEP) locust_creep(locust, locustFlags); - if ((locustFlags & LOCUST_FLAG_DEVOLVE) && target.CanDevolve()) - reconstruction_missing("Entity_Familiar::apply_tear_flag_effects 00649290 (devolving, Game::DevolveEnemy)"); + if (locustFlags & LOCUST_FLAG_DEVOLVE) locust_devolve(locust, target); if (locustFlags & LOCUST_FLAG_NECRONOMICON) player.UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM}); - if ((locustFlags & LOCUST_FLAG_ERASE) && target.IsVulnerableEnemy(nullptr)) - reconstruction_missing("Entity_Familiar::apply_tear_flag_effects 00649290 (Eraser, Game::AddErasedEnemy)"); + bool isErasable = target.IsVulnerableEnemy(nullptr) && (!target.IsBoss() || target.HasMortalDamage()); + if ((locustFlags & LOCUST_FLAG_ERASE) && isErasable && enemy_erase(target)) familiar_sound_play(SOUND_PLOP); if (locustFlags & LOCUST_FLAG_SHOCKWAVE) { familiar_sound_play(SOUND_LARYNX_SCREAM_LO, {.volume = LOCUST_LARYNX_VOLUME, .pitch = LOCUST_LARYNX_PITCH}); diff --git a/src/familiar_repentance.cpp b/src/familiar_repentance.cpp index 36270a1..a848924 100644 --- a/src/familiar_repentance.cpp +++ b/src/familiar_repentance.cpp @@ -1,13 +1,18 @@ #include "entity_familiar.h" +#include "boss_ai.h" #include "entity_bomb.h" #include "entity_config.h" #include "entity_effect.h" #include "entity_npc.h" +#include "entity_pickup.h" #include "entity_player.h" #include "entity_projectile.h" #include "entity_tear.h" #include "capsule.h" #include "game.h" +#include "hud.h" +#include "item_pool.h" +#include "level.h" #include "log.h" #include "npc_ai.h" #include "npc_basement.h" @@ -90,6 +95,7 @@ constexpr float BOT_FLY_SHOT_INHERIT = 0.6f; constexpr float BOT_FLY_SHOT_DAMAGE = 3; constexpr float BOT_FLY_SHOT_SCALE = 0.8f; constexpr float BOT_FLY_SHOT_FALL = 0.2f; +constexpr float BOT_FLY_CHARMED_FALL = 0.8f; constexpr uint32_t BOT_FLY_VERSUS_ODDS = 3; constexpr int PROJECTILE_ENEMY_SHOT_EXCLUDED = 14; @@ -629,23 +635,31 @@ void bot_fly_update(Entity_Familiar& fly) aim = vector_add(side, inherited); } if (fly.HasEntityFlags(FLAG_CHARM)) - reconstruction_missing("Entity_Familiar::ai_bot_fly 006431d0 (a charmed Bot Fly's shot)"); - - auto* tear = static_cast(g_game->Spawn({.position = fly.pos, - .velocity = aim, - .spawner = &fly, - .type = ENTITY_TEAR, - .variant = TEAR_LOST_CONTACT, - .seed = Random()})); - tear->SetCollisionDamage(BOT_FLY_SHOT_DAMAGE); - tear->SetTearFlags(TearFlags().set(TEAR_SHIELDED).set(TEAR_SPECTRAL).set(TEAR_HOMING)); - tear->baseScale = BOT_FLY_SHOT_SCALE; - tear->fScale = BOT_FLY_SHOT_SCALE; - tear->ResetSpriteScale(); - tear->fallingAccel = BOT_FLY_SHOT_FALL; - if (target) tear->target = target; - tear->Update(); - fly.shot_owner_convert(tear); + { + auto* shot = static_cast(g_game->Spawn( + {.position = fly.pos, .velocity = aim, .spawner = &fly, .type = ENTITY_PROJECTILE, .seed = Random()})); + shot->projectileFlags = PROJECTILE_NO_WALL_COLLIDE | PROJECTILE_SHIELDED; + shot->fallingAccel = BOT_FLY_CHARMED_FALL; + shot->Update(); + } + else + { + auto* tear = static_cast(g_game->Spawn({.position = fly.pos, + .velocity = aim, + .spawner = &fly, + .type = ENTITY_TEAR, + .variant = TEAR_LOST_CONTACT, + .seed = Random()})); + tear->SetCollisionDamage(BOT_FLY_SHOT_DAMAGE); + tear->SetTearFlags(TearFlags().set(TEAR_SHIELDED).set(TEAR_SPECTRAL).set(TEAR_HOMING)); + tear->baseScale = BOT_FLY_SHOT_SCALE; + tear->fScale = BOT_FLY_SHOT_SCALE; + tear->ResetSpriteScale(); + tear->fallingAccel = BOT_FLY_SHOT_FALL; + if (target) tear->target = target; + tear->Update(); + fly.shot_owner_convert(tear); + } if (!target) return; target->AddEntityFlags(FLAG_NO_TARGET); @@ -683,6 +697,7 @@ constexpr float PSY_FLY_TEAR_SIZE = 0.2f; constexpr float PSY_FLY_TEAR_SIZE_BASE = 0.8f; constexpr ColorMod PSY_FLY_TEAR_COLOR = {{0.4f, 0.15f, 0.38f, 1}, {0, 0, 0, 0}, {0.35f, 0, 0.7f}}; constexpr float PSY_FLY_STILL = 1e-05f; +constexpr int PSY_FLY_SIREN_FRAMES = 30; // Part of 00644780: Psy Fly's trail, following it faintly while it rests. static void psy_fly_trail(Entity_Familiar& fly) @@ -816,11 +831,55 @@ Entity* Entity_Familiar::aim_reflected_projectile() return best; } +// Where Psy Fly sends a shot back: toward the enemy it aims at, else along its motion, else anywhere. +static Vector psy_fly_reflection(Entity_Familiar& fly, Entity* aimed) +{ + if (aimed) return vector_normalized(vector_sub(aimed->pos, fly.pos)); + return vector_length_squared(fly.velocity) <= PSY_FLY_STILL ? random_direction() : vector_normalized(fly.velocity); +} + +// Part of 006261f0: a Psy Fly the Siren charmed 30 frames ago or more turns a player's tear into a smart enemy shot, +// and a blue fly into an attack fly. +static bool psy_fly_siren_touch(Entity_Familiar& fly, Entity& collider) +{ + Entity* siren = fly.sirenHelper.get(); + if (!siren || g_game->frameCount - siren->spawnFrame < PSY_FLY_SIREN_FRAMES) return false; + + if (collider.type == ENTITY_TEAR) + { + TearFlags& flags = static_cast(collider).tearFlags; + if (flags[TEAR_EXPLOSIVE] || flags[TEAR_LUDOVICO]) return false; + + collider.isDead = true; + Vector direction = psy_fly_reflection(fly, fly.aim_reflected_projectile()); + auto* shot = static_cast(g_game->Spawn({.position = fly.pos, + .velocity = vector_scale(direction, PSY_FLY_TEAR_SPEED), + .spawner = &fly, + .type = ENTITY_PROJECTILE, + .variant = PROJECTILE_TEAR, + .seed = Random()})); + shot->projectileFlags = PROJECTILE_SMART; + shot->SetColor(PSY_FLY_TEAR_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + shot->Update(); + return true; + } + if (collider.type != ENTITY_FAMILIAR || collider.variant != Entity_Familiar::BLUE_FLY) return false; + + collider.Remove(); + Entity* attacker = + g_game->Spawn({.position = collider.pos, .velocity = collider.velocity, .type = ENTITY_ATTACKFLY, .seed = Random()}); + attacker->ClearEntityFlags(FLAG_APPEAR); + attacker->Update(); + return true; +} + // Part of 006261f0: a hunting Psy Fly turns a shot it meets back as a homing tear at an enemy, and a fly it meets into -// a blue fly. Whether it handled the touch. +// a blue fly. Charmed by the Siren for 30 frames, it turns the player's tears (not explosive or Ludovico ones) into +// smart enemy shots instead, and the blue flies into attack flies. Whether it handled the touch. bool psy_fly_touch(Entity_Familiar& fly, Entity& collider) { - if (fly.fireCooldown <= PSY_FLY_BLOCKING || fly.HasEntityFlags(FLAG_CHARM)) return false; + if (fly.fireCooldown <= PSY_FLY_BLOCKING) return false; + if (fly.HasEntityFlags(FLAG_CHARM)) return psy_fly_siren_touch(fly, collider); if (collider.type == ENTITY_PROJECTILE) { @@ -828,9 +887,7 @@ bool psy_fly_touch(Entity_Familiar& fly, Entity& collider) collider.isDead = true; Entity* aimed = fly.aim_reflected_projectile(); - Vector direction = aimed ? vector_normalized(vector_sub(aimed->pos, fly.pos)) - : vector_length_squared(fly.velocity) <= PSY_FLY_STILL ? random_direction() - : vector_normalized(fly.velocity); + Vector direction = psy_fly_reflection(fly, aimed); float damage = fly.GetMultiplier() * PSY_FLY_TEAR_DAMAGE; float size = fly.GetMultiplier() * PSY_FLY_TEAR_SIZE + PSY_FLY_TEAR_SIZE_BASE; auto* tear = static_cast(g_game->Spawn({.position = fly.pos, @@ -1438,6 +1495,28 @@ static void damocles_fall(Entity_Familiar& damocles) damocles.Remove(); } +// The Vanishing Twin: its spot (Great Gideon's 100 below the top), nudged 15 to 30 off a taken one, its glide there, +// Larry Jr.'s five parts 20 apart turned up to 45 degrees off the player, the Great Gideons' row 60 below the top 80 +// apart, Gideon's growth and the other bosses' health share, three frames without a copy before its reward, its +// reward kept off the cell 80 above the room's centre in steps of 10, and There's Options' item 24 beside it. +constexpr float TWIN_GIDEON_DROP = 100; +constexpr float TWIN_HALF_TURN = 3.14f; +constexpr float TWIN_NUDGE_SPREAD = 15; +constexpr float TWIN_NUDGE_MIN = 15; +constexpr float TWIN_GLIDE = 0.1f; +constexpr float TWIN_GLIDE_MAX = 20; +constexpr int TWIN_LARRY_SEGMENTS = 5; +constexpr int TWIN_LARRY_TURNS = 90; +constexpr float TWIN_PART_GAP = 20; +constexpr float TWIN_GIDEON_ROW = 60; +constexpr float TWIN_GIDEON_GAP = 80; +constexpr float TWIN_GIDEON_GROWTH = 2; +constexpr float TWIN_BOSS_HEALTH_SHARE = 0.75f; +constexpr int TWIN_EMPTY_FRAMES = 4; +constexpr float TWIN_CENTRE_LIFT = 80; +constexpr float TWIN_SPOT_STEP = 10; +constexpr float TWIN_OPTION_GAP = 24; + // 00644e80 Damocles hangs over the player, swaying, and every fourth frame may fall (its subtype the chance in ten // thousand). Between frames it only keeps over the player. void Entity_Familiar::ai_shadow_intruder_damocles(bool isInterpolating) @@ -1473,8 +1552,171 @@ void Entity_Familiar::ai_shadow_intruder_damocles(bool isInterpolating) state = DAMOCLES_FALLING; } -// 00650610 (FamiliarAI::vanishing_twin) The Vanishing Twin follows the player, hidden while its twin lives. Without a -// boss to copy (its coins hold the boss's type) it only follows. Copying the floor's boss stops the game. +// Part of 00650610: the Vanishing Twin picks its spot near the room's centre (high up for Great Gideon), nudged off a +// spot another twin took, and starts turning into its boss. +static void vanishing_twin_settle(Entity_Familiar& twin) +{ + Room& room = *g_game->room; + Vector centre = Room::GetCenterPos(); + if (twin.coins == ENTITY_GIDEON) centre.y = room.topLeftPos.y + TWIN_GIDEON_DROP; + twin.targetPosition = room_free_pickup_position_find({.position = centre, .isAvoidActiveEntities = true}); + for (Entity* other : entity_query(twin.type, twin.variant)) + { + if (other == &twin || other->targetPosition.x != twin.targetPosition.x || + other->targetPosition.y != twin.targetPosition.y) + continue; + + float half = random_unit() * TWIN_HALF_TURN; + float angle = half + half; + float sine = std::sin(angle); + float distance = random_unit() * TWIN_NUDGE_SPREAD + TWIN_NUDGE_MIN; + float cosine = std::cos(angle); + twin.targetPosition = vector_make(cosine * distance + twin.targetPosition.x, + distance * sine + twin.targetPosition.y); + break; + } + twin.sprite.Play("Transform"); + twin.RemoveFromFollowers(); +} + +// A copy of the twin's boss tied to the twin, run for its first frame. +static Entity* twin_part_spawn(Entity_Familiar& twin, const EntitySpawn& spawn) +{ + Entity* part = g_game->Spawn(spawn); + static_cast(part)->unknownF54 = &twin; + return part; +} + +// Part of 00650610: the twin becomes its boss: Larry Jr. with four segments trailing away from the player, a second +// Gurgling beside the first, the Great Gideons lined up across the room. It poofs (unless the boss appears by itself) +// with a summoning sound, marks the room, and Gideon grows while every other boss in the room loses a quarter of its +// health. +static void vanishing_twin_transform(Entity_Familiar& twin) +{ + twin.isVisible = false; + Entity* boss = twin_part_spawn( + twin, {.position = twin.pos, .type = twin.coins, .variant = twin.keys, .seed = twin.dropRNG.Next()}); + boss->Update(); + twin.target = boss; + + if (boss->type == ENTITY_LARRYJR) + { + Vector away = vector_normalized(vector_sub(twin.pos, twin.player->pos)); + away = vector_rotated(away, (float)((int)(Random() % TWIN_LARRY_TURNS) - TWIN_LARRY_TURNS / 2)); + Entity* previous = boss; + for (int i = 1; i < TWIN_LARRY_SEGMENTS; i++) + { + float step = (float)i; + Vector spot = vector_make(away.x * step * TWIN_PART_GAP + twin.pos.x, step * TWIN_PART_GAP * away.y + twin.pos.y); + Entity* segment = twin_part_spawn( + twin, {.position = spot, .spawner = &twin, .type = boss->type, .variant = boss->variant, .seed = Random()}); + segment->parent = previous; + segment->Update(); + previous = segment; + } + } + else if (boss->type == ENTITY_GURGLING) + { + uint32_t seed = Random(); + Vector spot = vector_add(vector_scale(random_direction(), TWIN_PART_GAP), twin.pos); + twin_part_spawn(twin, {.position = spot, .spawner = &twin, .type = boss->type, .variant = boss->variant, .seed = seed}) + ->Update(); + } + else if (boss->type == ENTITY_GIDEON) + { + std::vector gideons = entity_query(ENTITY_GIDEON, -1); + float y = gideons.size() < 2 ? g_game->room->topLeftPos.y + TWIN_GIDEON_ROW : gideons[0]->targetPosition.y; + float x = Room::GetCenterPos().x - ((float)gideons.size() - 1) * (TWIN_GIDEON_GAP / 2); + for (Entity* gideon : gideons) + { + gideon->targetPosition = vector_make(x, y); + gideon->pos = vector_make(x, y); + x += TWIN_GIDEON_GAP; + } + } + + if (!boss->HasEntityFlags(FLAG_APPEAR)) + g_game->Spawn({.position = twin.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()})->Update(); + familiar_sound_play(SOUND_SUMMONSOUND); + g_game->room->temporaryEffects.AddCollectibleEffect(COLLECTIBLE_VANISHING_TWIN, true, 1); + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (!entity->IsBoss()) continue; + + if (entity->type != ENTITY_GIDEON) entity->health *= TWIN_BOSS_HEALTH_SHARE; + else if (entity->subtype == 0) + { + entity->health += TWIN_GIDEON_GROWTH; + entity->maxHitPoints += TWIN_GIDEON_GROWTH; + if (!entity->parent) + { + g_game->hud.bossCounter = (int16_t)(int)(entity->maxHitPoints - entity->health + 1); + g_game->hud.bossCounterTotal = (int16_t)(int)entity->maxHitPoints; + } + } + } +} + +// A free spot for the twin's reward placed from an origin, kept off the cell two above the room's centre: each time it +// lands there it is placed again a step further out. +static Vector twin_reward_spot(Vector origin, Vector (*place)(Vector)) +{ + Room& room = *g_game->room; + Vector centre = Room::GetCenterPos(); + int blocked = room.GetGridIndex(vector_make(centre.x + 0, centre.y - TWIN_CENTRE_LIFT)); + Vector spot = room_free_pickup_position_find({.position = place(origin), .isAvoidActiveEntities = true}); + for (float step = TWIN_SPOT_STEP; room.GetGridIndex(spot) == blocked; step += TWIN_SPOT_STEP) + spot = room_free_pickup_position_find({.position = place(origin), .step = step, .isAvoidActiveEntities = true}); + return spot; +} + +// The origin itself. +static Vector twin_spot_same(Vector origin) +{ + return origin; +} + +// A spot 24 from the origin in a random direction (the twin's angle draws 3.14, not pi). +static Vector twin_spot_beside(Vector origin) +{ + float half = random_unit() * TWIN_HALF_TURN; + float angle = half + half; + return vector_make(std::cos(angle) * TWIN_OPTION_GAP + origin.x, std::sin(angle) * TWIN_OPTION_GAP + origin.y); +} + +// Part of 00650610: the twin's boss gone, it leaves an item from its seed by the twin (for sale after the Satanic +// Bible's boss or with Tainted Keeper), with There's Options a second one beside it, either one to take. +static void vanishing_twin_reward(Entity_Familiar& twin) +{ + Game& game = *g_game; + bool isBibleBoss = (game.levelStateFlags & (1u << LEVEL_STATE_SATANIC_BIBLE_USED)) && game.room->roomType == ROOM_BOSS; + bool isShopItem = isBibleBoss || game.playerManager.FirstPlayerByType(PLAYER_KEEPER_B); + Vector spot = twin_reward_spot(twin.pos, twin_spot_same); + int item = game.itemPool.GetSeededCollectible(twin.dropRNG.Next(), 0, *game.room->descriptor); + auto* reward = static_cast(game.Spawn({.position = spot, + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = twin.dropRNG.Next()})); + if (isShopItem) reward->MakeShopItem(-1); + if (!game.playerManager.FirstCollectibleOwner(COLLECTIBLE_THERES_OPTIONS, LAZARUS_SHARE_CHECK)) return; + + int optionItem = game.itemPool.GetSeededCollectible(twin.dropRNG.Next(), 0, *game.room->descriptor); + game.itemPool.RemoveCollectible(optionItem, REMOVE_ANY, REMOVE_APPLY); + Vector optionSpot = twin_reward_spot(spot, twin_spot_beside); + auto* option = static_cast(game.Spawn({.position = optionSpot, + .subType = optionItem, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = twin.dropRNG.Next()})); + if (isShopItem) option->MakeShopItem(-1); + option->optionsPickupIndex = reward->AssignOptionsIndex(); +} + +// 00650610 (FamiliarAI::vanishing_twin) The Vanishing Twin follows the player, hidden while its twin lives. With a boss +// to copy (its coins and keys hold the boss's type and variant) it glides to its spot and turns into the boss, rides +// along with it, and once no copy is left for three frames leaves its reward. +// A versus match's players never count as its copy here. The original read an unrelated player field for them. void vanishing_twin_update(Entity_Familiar& twin) { twin.entityCollisionClass = ENTCOLL_NONE; @@ -1483,12 +1725,48 @@ void vanishing_twin_update(Entity_Familiar& twin) twin.isVisible = false; return; } - if (twin.coins != 0) return reconstruction_missing("FamiliarAI::vanishing_twin 00650610 (the twin of a boss)"); + if (twin.coins == 0) + { + twin.sprite.Play("Idle"); + twin.FollowParent(); + twin.isVisible = true; + twin.targetPosition = {}; + twin.state = 0; + twin.fireCooldown = 0; + return; + } - twin.sprite.Play("Idle"); - twin.FollowParent(); - twin.isVisible = true; - twin.targetPosition = {}; - twin.state = 0; - twin.fireCooldown = 0; + if (vector_is_zero(twin.targetPosition)) vanishing_twin_settle(twin); + if (twin.isVisible && !twin.sprite.IsPlaying()) vanishing_twin_transform(twin); + if (twin.fireCooldown >= 0 && !twin.target && !twin.isVisible) + { + for (Entity* entity : g_game->room->entityList.updateEL) + { + auto* npc = dynamic_cast(entity); + if (npc && Entity::is_enemy_type(npc->type) && npc->unknownF54.get() == &twin) + { + twin.target = npc; + break; + } + } + if (twin.target) twin.fireCooldown = 0; + else if (++twin.fireCooldown >= TWIN_EMPTY_FRAMES) + { + twin.fireCooldown = -1; + twin.state = 1; + vanishing_twin_reward(twin); + } + } + + if (Entity* copy = twin.target) + { + twin.pos = copy->pos; + return; + } + if (!twin.isVisible || vector_is_zero(twin.targetPosition)) return; + + Vector glide = vector_scale(vector_sub(twin.targetPosition, twin.pos), TWIN_GLIDE); + twin.velocity = glide; + float speed = vector_length(glide); + if (speed > TWIN_GLIDE_MAX && speed > 0) twin.velocity = vector_scale(glide, TWIN_GLIDE_MAX / speed); } diff --git a/src/familiar_shoot.cpp b/src/familiar_shoot.cpp index fef3522..ffc1c9e 100644 --- a/src/familiar_shoot.cpp +++ b/src/familiar_shoot.cpp @@ -1,7 +1,9 @@ #include "entity_effect.h" #include "entity_familiar.h" #include "entity_laser.h" +#include "entity_npc.h" #include "entity_player.h" +#include "entity_projectile.h" #include "entity_tear.h" #include "game.h" #include "log.h" @@ -367,8 +369,8 @@ void Entity_Familiar::mongo_baby_pick_next_mimic() } // The shot of a familiar by variant (or by the baby Mongo Baby mimics, or the roll of Rainbow Baby): its flags, look, -// damage and arc (part of 00639750). Returns false for the familiars whose shots wait for their takeover. -static bool shot_variant_apply(Entity_Familiar& familiar, FamiliarShot& shot, int mimic, int rainbow) +// damage and arc (part of 00639750). +static void shot_variant_apply(Entity_Familiar& familiar, FamiliarShot& shot, int mimic, int rainbow) { Entity_Player& player = *familiar.player; int variant = familiar.variant; @@ -502,7 +504,6 @@ static bool shot_variant_apply(Entity_Familiar& familiar, FamiliarShot& shot, in shot.flags.set(TEAR_ICE_FLAG); if (Random() % 10 == 0) shot.flags.set(TEAR_FREEZE); } - return true; } // Spawns one of a familiar's tears and finishes it: its arc, damage, flags, size and look, the familiar as its parent, @@ -568,8 +569,7 @@ Entity_Tear* Entity_Familiar::FireProjectile(const Vector& aimDirection, FireMod shot.scale = (GetMultiplier() * 0.25f + 0.75f) * SHOT_SCALE; int mimic = variant == MONGO_BABY ? subtype : -1; int rainbow = variant == RAINBOW_BABY || mimic == 8 ? (int)(Random() % 10) + 1 : 0; - if (!shot_variant_apply(*this, shot, mimic, rainbow)) - reconstruction_missing("Entity_Familiar::FireProjectile 00639750 (this familiar's shot)"); + shot_variant_apply(*this, shot, mimic, rainbow); if (isLilDelirium) { @@ -642,12 +642,77 @@ bool Entity_Familiar::TryFireTear(Entity_Tear* tear) return true; } -// A shot of a familiar the Siren charmed turns on the player (Entity::convert_shot_for_enemy_owner 0064bb70, which does -// nothing for any other familiar, so it is only called then). +// The fly, spider or other enemy a converted shot becomes: no longer appearing, with twice its health. +static void converted_shot_strengthen(Entity& enemy) +{ + enemy.ClearEntityFlags(FLAG_APPEAR); + enemy.maxHitPoints *= 2; + enemy.health = enemy.maxHitPoints; +} + +// 0064bb70 (Entity::convert_shot_for_enemy_owner) A shot of a familiar the Siren charmed turns on the player, owned by +// the Siren: a tear becomes a slower enemy shot, a blue fly an attack fly (Rotten Baby's own fly then), a blue spider +// a spider (thrown when in the air), a laser changes owner, and the red and white creep become the enemies' (the red +// only once the Siren's helper is past 30 frames). Anything else stays. +// The original reads past a missing shot. Here nothing happens then. void Entity_Familiar::shot_owner_convert(Entity* shot) { + constexpr float TEAR_SPEED_SHARE = 0.8f; + constexpr float CREEP_HELPER_FRAMES = 30; + Entity* owner = player->spawnerEntity; - if (HasEntityFlags(FLAG_CHARM) && owner && Entity::is_enemy_type(owner->type)) convert_shot_for_enemy_owner(shot); + if (!shot || !HasEntityFlags(FLAG_CHARM) || !owner || !Entity::is_enemy_type(owner->type)) return; + + EntitySpawn spawn = {.position = shot->pos, .velocity = shot->velocity, .spawner = owner, .seed = Random()}; + if (shot->type == ENTITY_TEAR) + { + auto& tear = *static_cast(shot); + spawn.velocity = vector_scale(shot->velocity, TEAR_SPEED_SHARE); + spawn.type = ENTITY_PROJECTILE; + auto& projectile = *static_cast(g_game->Spawn(spawn)); + projectile.fallingAccel = tear.fallingAccel; + projectile.fallingSpeed = tear.fallingSpeed; + projectile.height = tear.height; + projectile.scale = tear.fScale; + projectile.SetColor(shot->color, -1, COLOR_PRIORITY_DEFAULT, false, true); + shot->Remove(); + } + else if (shot->type == ENTITY_FAMILIAR && shot->variant == BLUE_FLY) + { + spawn.type = ENTITY_ATTACKFLY; + Entity* fly = g_game->Spawn(spawn); + converted_shot_strengthen(*fly); + shot->Remove(); + if (variant == ROTTEN_BABY) linkedEntity = fly; + } + else if (shot->type == ENTITY_FAMILIAR && shot->variant == BLUE_SPIDER) + { + bool isAirborne = shot->posOffset.y < 0 || static_cast(shot)->orbitSpeed < 0; + spawn.type = ENTITY_SPIDER; + Entity* spider = + isAirborne ? Entity_NPC::ThrowSpider(shot->pos, owner, {}, false, posOffset.y) : g_game->Spawn(spawn); + converted_shot_strengthen(*spider); + shot->Remove(); + } + else if (shot->type == ENTITY_LASER) + { + shot->spawnerEntity = owner; + shot->spawnerType = owner->type; + shot->spawnerVariant = owner->variant; + } + else if (shot->type == ENTITY_EFFECT) + { + bool isRedCreep = + shot->variant == EFFECT_PLAYER_CREEP_RED && sirenHelper && sirenHelper->updateTime > CREEP_HELPER_FRAMES; + if (!isRedCreep && shot->variant != EFFECT_PLAYER_CREEP_WHITE) return; + + spawn.type = ENTITY_EFFECT; + spawn.variant = isRedCreep ? EFFECT_CREEP_RED : EFFECT_CREEP_WHITE; + Entity* creep = g_game->Spawn(spawn); + creep->sprite.scale = shot->sprite.scale; + creep->Update(); + shot->Remove(); + } } // 00613c20 Robo-Baby's laser (a wisp's too): a short thin beam from its eye, hitting once and staying where it was diff --git a/src/familiar_wisp.h b/src/familiar_wisp.h index ad4d393..d2d0016 100644 --- a/src/familiar_wisp.h +++ b/src/familiar_wisp.h @@ -50,5 +50,6 @@ void plum_flute_wisp_target(Entity_Familiar& wisp); void plum_flute_wisp_spray(Entity_Familiar& wisp, int updateSteps); bool wisp_kind_fire(Entity_Familiar& wisp, Vector velocity); void wisp_kind_tear(Entity_Familiar& wisp, WispTear& tear); +void monster_tear_pick(RNG& rng, WispTear& tear); WispHit wisp_kind_hit(Entity_Familiar& wisp, float& damage, uint64_t damageFlags, const EntityRef& source); bool wisp_kind_death(Entity_Familiar& wisp); diff --git a/src/familiar_wisp_kinds.cpp b/src/familiar_wisp_kinds.cpp index 051ca19..301245a 100644 --- a/src/familiar_wisp_kinds.cpp +++ b/src/familiar_wisp_kinds.cpp @@ -1214,7 +1214,7 @@ static void pills_wisp_tear(Entity_Familiar& wisp, WispTear& tear) // 00633990 Monster Manual's random tear: half the time a tear kind and shape of its own, the shape sometimes with an // effect, the likelier the higher its first draw. -static void monster_tear_pick(RNG& rng, WispTear& tear) +void monster_tear_pick(RNG& rng, WispTear& tear) { float chance = rng.RandomFloat(); uint32_t variant = rng.Next() % MONSTER_TEAR_VARIANTS.size(); @@ -1396,16 +1396,7 @@ static void eraser_wisp_hit(Entity_Familiar& wisp, const EntityRef& source) if (!enemy || !enemy->IsVulnerableEnemy(nullptr)) return; if (enemy->IsBoss() && enemy->pendingDamage < enemy->health) return; - erased_enemy_add(*enemy); - bool isErased = false; - for (Entity* entity : std::vector(g_game->room->entityList.updateEL.begin(), - g_game->room->entityList.updateEL.end())) - { - if (!entity_is_erased(*entity)) continue; - Entity::RemoveWithPoof(entity); - isErased = true; - } - if (isErased) familiar_sound_play(SOUND_PLOP); + if (enemy_erase(*enemy)) familiar_sound_play(SOUND_PLOP); wisp_die(wisp); } diff --git a/src/fx_layers.cpp b/src/fx_layers.cpp index 5a4fdf3..d609c6a 100644 --- a/src/fx_layers.cpp +++ b/src/fx_layers.cpp @@ -42,7 +42,6 @@ constexpr int STAGE_LAST_IN_CHAPTERS = 8; constexpr int STAGE_ASCENT_LAST = 6; constexpr int STAGE_CHAPTER_TWO = 3; constexpr int GREED_STAGE_SHEOL = 5; -constexpr int DELETE_THIS_STAGES = 11; constexpr int STAGE_TYPE_COUNT = 5; constexpr uint32_t CURSE_DARKNESS = 1; diff --git a/src/fx_layers.h b/src/fx_layers.h index 24bd0b7..a495ce6 100644 --- a/src/fx_layers.h +++ b/src/fx_layers.h @@ -67,6 +67,9 @@ constexpr uint32_t TEXT_ARGB = 0xff362f2d; 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}}; +// Splashes of water, and of the Dross' sewage. +constexpr ColorMod WATER_SPLASH_COLOR = {{1, 1, 1, 1}, {5.5f, 7, 7, 1}, {0, 0, 0}}; +constexpr ColorMod SEWAGE_SPLASH_COLOR = {{1, 1, 1, 1}, {3, 2.5f, 2, 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 4a163ec..40d9909 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -1,6 +1,9 @@ #include "game.h" #include "data.h" +#include "entity_factory.h" +#include "entity_npc.h" #include "entity_player.h" +#include "familiar_wisp.h" #include "level.h" #include "log.h" #include "manager.h" @@ -8,6 +11,7 @@ #include "menu_manager.h" #include "render_passes.h" #include "room.h" +#include "room_render.h" #include "room_transition.h" #include "victory_run_prompt.h" #include @@ -111,9 +115,11 @@ Game::Game() g_manager->modManager.create_shader_render_targets(); } +// 006f3060 Releases the surfaces every room draws through and the room. The rest goes as the members' defaults. Game::~Game() { - reconstruction_missing("Game::~Game 006f3060"); + roomSurfaces = {}; + room.reset(); } // 006f3c00 Reloads the run's configs a Lua reset may have changed, through the mods' redirection (stages, the game's @@ -277,7 +283,7 @@ bool Game::load_bossoverlays_xml(std::string_view path) { Data data; - bossOverlay._state = 0; + bossOverlay.state = BOSS_OVERLAY_HIDDEN; data_load(data, path); if (!data.isLoaded) return false; @@ -294,7 +300,7 @@ bool Game::load_bossoverlays_xml(std::string_view path) if (auto text = attr_find(node, "anm2")) entry.anm2Path = anm2Root + std::string(*text); if (auto text = attr_find(node, "anim")) entry.animation = *text; if (auto text = attr_find(node, "persist")) entry.isPersistent = attr_bool(*text); - if ((unsigned)entry.id < BOSS_OVERLAY_COUNT) bossOverlayEntries[entry.id] = std::move(entry); + if ((unsigned)entry.id < BOSS_OVERLAY_COUNT) bossOverlay.entries[entry.id] = std::move(entry); } return true; } @@ -359,11 +365,11 @@ void Game::reset_run_state() restartHoldFrames = 0; framesSinceRoomTransition = 0; - dailyChallenge._id = 0; - dailyChallenge._seed = 0; - dailyChallenge._specialDailyId = 0; - dailyChallenge._isPractice = false; - // ChallengeParam::Reset on dailyChallenge's params waits for DailyChallenge's takeover (classes.h has bytes). + dailyChallenge.id = 0; + dailyChallenge.seed = 0; + dailyChallenge.specialDailyId = 0; + dailyChallenge.isPractice = false; + dailyChallenge.params.Reset(); scoreSheet.Reset(); currentColorModifier = COLOR_MOD_NEUTRAL; @@ -526,6 +532,58 @@ void Game::Start(int playerType, uint32_t startChallenge, const Seeds& seeds, Di lua_engine_get().PostGameStart(false); } +// 006f7ac0 Starts the next victory lap: progress freezes, the first lap turns the run hard, the main players pay the +// lap's toll, the Mega Satan door closes and the run's seed steps on to new pools. The floor before the backwards +// path is saved, the stage bar starts over and the first floor begins, saved and faded in from black. +// Netplay is offline, so the lobby's notice is left out. +void Game::NextVictoryLap() +{ + constexpr RNG LAP_SEED_SHIFTS = {0, 1, 9, 29}; + Manager& manager = *g_manager; + + manager.persistentGameData.SetReadOnly(true); + if (++victoryLap == 1) difficulty = DIFFICULTY_HARD; + for (Entity_Player* player : std::vector(playerManager.playerList)) + if (player->variant == PLAYER_VARIANT_PLAYER) player->apply_victory_lap_penalty(seedEffects.GetStartSeed()); + gameStateFlags &= ~(1ull << GAME_STATE_MEGA_SATAN_DOOR_OPENED); + + RNG lapSeed = LAP_SEED_SHIFTS; + lapSeed._seed = seedEffects.GetStartSeed(); + seedEffects.set_start_seed(lapSeed.Next()); + fortuneRNG.SetSeed(seedEffects.GetNextSeed(), DEFAULT_SHIFT_INDEX); + uint32_t startSeed = seedEffects.GetStartSeed(); + log_printf(LOG_INFO, "RNG Victory Lap Start Seed: %s (%u)\n", Seeds::Seed2String(startSeed).c_str(), startSeed); + std::string itemPoolsPath = manager.modManager.TryRedirectPath(ITEM_POOLS_XML); + itemPool.Init(seedEffects.GetNextSeed(), itemPoolsPath); + bossPool.init(seedEffects.GetStartSeed()); + + bool isBackwardsSaved = stage > 0 && (stage > STAGE_WOMB_II || !GetStateFlag(GAME_STATE_BACKWARDS_PATH)); + if (isBackwardsSaved && stage_depth_get() <= BACKWARDS_STAGE_COUNT) SaveBackwardsStage(stage_depth_get()); + stage = 0; + stageType = STAGETYPE_ORIGINAL; + manager.nightmareScene.isDogma = false; + manager.nightmareScene.stageIcons[0] = IsGreedMode() ? GREED_STAGE_ICON : 0; + bossRushParTime = BOSS_RUSH_PAR_TIME; + SetNextStage(); + Init(true); + Manager::save_game_state(); + playerManager.trigger_new_room_effects(); + manager.isNightmarePending = true; + manager.pendingNightmareId = 1; + Manager::Update(INPUT_POLL_SKIP); + + frameCount = 0; + timeCounter = 0; + fadeOutColor._alpha = 0; + fadeOutTarget = FADEOUT_MENU_TITLE; + genericPrompt.Disappear(); + if (genericPrompt.sprite.animState.animData) genericPrompt.sprite.animState.isPlaying = false; + genericPrompt.submittedSelection = PROMPT_ANSWER_NONE; + genericPrompt.currentSelection = PROMPT_CHOICE_NO; + Fadein(START_FADE_SPEED, FADE_ICON_SHOW, kcolor_rgba(0, 0, 0, 1)); + framesSinceRoomTransition = 0; +} + // 006f5210 Fades the screen in from a color at a speed, from full (or nearly no) cover as the instant fade asks, with // or without the loading icon. The players cannot move until it ends. void Game::Fadein(float speed, FadeIcon icon, KColor color) @@ -726,7 +784,7 @@ static void overlays_render(Game& game) if (stageState == STAGE_TRANSITION_OUT || stageState == STAGE_TRANSITION_IN) game.stageTransition.Render(); else graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL); game.itemOverlay.Render(); - if (game.bossOverlay._state != 0) reconstruction_missing("Game::Render 006fbc10: BossOverlay's render 00421400"); + game.bossOverlay.render(); popups.render_layer(1); const AnimationState& prompt = game.genericPrompt.sprite.animState; @@ -903,7 +961,62 @@ Entity_Player* Game::GetPlayer(int index) // 00706940 The rules the run is played by: the daily's, else its challenge's (a plain run's for none). ChallengeParam& Game::GetChallengeParams() { - if (dailyChallenge._id != 0) - reconstruction_missing("Game::GetChallengeParams 00706940: the daily's params, which classes.h holds as bytes"); + if (dailyChallenge.id != 0) return dailyChallenge.params; return g_manager->GetChallengeParams((int)challenge); } + +// 007050c0 Turns an enemy into a random rerollable one of its pool (the airborne pool for a grid collision up to the +// walls, the walking one otherwise), drawn among those within 5 of its health on this floor when any are, keeping its +// champion color and health share. The new enemy counts with the ambush. Whether it rerolled. +// The original reads past an empty pool, and treats a versus player as an NPC. Here neither rerolls. +bool Game::RerollEnemy(Entity* entity, RerollMatch match) +{ + constexpr float HEALTH_MATCH_RANGE = 5; + + if (!entity || entity->type == ENTITY_PLAYER || !Entity::is_enemy_type(entity->type)) return false; + auto& npc = static_cast(*entity); + if (!npc.CanReroll()) return false; + + float healthShare = npc.maxHitPoints > 0 ? std::clamp(npc.health / npc.maxHitPoints, 0.0f, 1.0f) : 1; + EntityConfig& configs = g_manager->entityConfig; + bool isAirborne = npc.entityGridCollisionClass <= GRIDCOLL_WALLS; + std::vector& pool = isAirborne ? configs.otherRerolls : configs.groundRerolls; + float health = stage_health_get(npc.config->baseHP, npc.config->stageHP); + std::vector matched; + for (const RerollEntry& entry : pool) + { + bool isNear = std::fabs(health - stage_health_get(entry.baseHP, entry.stageHP)) <= HEALTH_MATCH_RANGE; + if (match == REROLL_MATCH_ANY || isNear) matched.push_back(entry); + } + std::vector& choices = matched.empty() ? pool : matched; + if (choices.empty()) return false; + + RerollEntry& choice = choices[Random() % choices.size()]; + int type = choice.id; + int variant = choice.variant; + Entity_NPC::Redirect(&type, &variant); + auto* rerolled = static_cast( + Spawn({.position = npc.pos, .velocity = npc.velocity, .type = type, .variant = variant, .seed = Random()})); + if (npc.championColorIdx >= 0) + rerolled->Morph(rerolled->type, rerolled->variant, rerolled->subtype, npc.championColorIdx); + rerolled->AddEntityFlags(FLAG_AMBUSH); + rerolled->Update(); + rerolled->health = healthShare * rerolled->maxHitPoints; + npc.Remove(); + return true; +} + +// The Eraser's sweep (part of 00673660, 00649290 and 0043a5e0): the enemy's kind is erased for the run, then every +// entity of the room of an erased kind vanishes in a poof. Whether any did. +bool enemy_erase(Entity& enemy) +{ + erased_enemy_add(enemy); + bool isErased = false; + for (Entity* entity : std::vector(g_game->room->entityList.updateEL)) + { + if (!entity_is_erased(*entity)) continue; + Entity::RemoveWithPoof(entity); + isErased = true; + } + return isErased; +} diff --git a/src/game.h b/src/game.h index a3389dc..2484d83 100644 --- a/src/game.h +++ b/src/game.h @@ -4,6 +4,8 @@ #include "ambush.h" #include "anm2.h" +#include "daily_challenge.h" +#include "boss_overlay.h" #include "boss_pool.h" #include "challenge_params.h" #include "console.h" @@ -42,9 +44,12 @@ constexpr int AZAZEL_DEALS = 3; constexpr int GLOWING_HOURGLASS_SLOTS = 2; constexpr int GIANTBOOK_ENTRY_COUNT = 48; -constexpr int BOSS_OVERLAY_COUNT = 5; constexpr int COOP_AWARD_COUNT = 21; constexpr int COOP_STAT_NONE = 22; +// The room's render surface, its size and margin, centered on the screen. +constexpr float ROOM_SURFACE_WIDTH = 338; +constexpr float ROOM_SURFACE_HEIGHT = 182; +constexpr float ROOM_SURFACE_MARGIN = 52; // The xorshift every RNG of Game starts on, before a run seeds it (shift index 35). constexpr RNG RNG_DEFAULT = {RNG_SEED_DEFAULT, 5, 9, 7}; @@ -85,6 +90,7 @@ enum GameStateFlag : int GAME_STATE_FAMINE_SPAWNED = 0, GAME_STATE_DEVILROOM_SPAWNED = 5, GAME_STATE_DEVILROOM_VISITED = 6, + GAME_STATE_BOOK_PICKED_UP = 8, GAME_STATE_HEAVEN_PATH = 19, GAME_STATE_KRAMPUS_SPAWNED = 29, GAME_STATE_BOSSRUSH_DONE = 33, @@ -94,6 +100,7 @@ enum GameStateFlag : int GAME_STATE_BLUEWOMB_DONE = 40, GAME_STATE_SECRET_PATH = 44, GAME_STATE_MAUSOLEUM_HEART_KILLED = 46, + GAME_STATE_BACKWARDS_PATH_INIT = 47, GAME_STATE_BACKWARDS_PATH = 48, GAME_STATE_MEGA_SATAN_DOOR_OPENED = 49 }; @@ -139,15 +146,6 @@ struct GiantbookEntry int id = 0; }; -// A boss overlay animation (the Dogma and Beast screen effects) as bossoverlays.xml defines it. -struct BossOverlayEntry -{ - std::string anm2Path; - std::string animation; - int id = 0; - bool isPersistent = false; -}; - // What Game::Spawn creates: an entity by type, variant and subtype at a position and velocity, from a seed. struct EntitySpawn { @@ -185,6 +183,13 @@ enum GameRestore RESTORE_CONTINUE }; +// How Game::RerollEnemy picks the new enemy: one of about the same health when any is, or any of its pool. +enum RerollMatch +{ + REROLL_MATCH_HEALTH, + REROLL_MATCH_ANY +}; + // Whether a fade in shows the loading icon. enum FadeIcon { @@ -227,8 +232,7 @@ public: StageTransition stageTransition{}; ItemOverlay itemOverlay{}; std::array giantbookEntries; - BossOverlay bossOverlay{}; - std::array bossOverlayEntries; + BossOverlay bossOverlay; GameOver gameOver{}; Leaderboard leaderboard{}; HUD hud; @@ -339,9 +343,11 @@ public: void create_render_surfaces(); void Start(int playerType, uint32_t startChallenge, const Seeds& seeds, Difficulty startDifficulty); + void NextVictoryLap(); void Fadein(float speed, FadeIcon icon, KColor color); void SetColorModifier(const ColorModState& color, bool isLerp, float rate); void save_rewind_state(int leaveDoor); + static void rewind(Entity_Player* player); void StartRoomTransition(RoomTransitionRequest request); void ChangeRoom(int roomIndex, int dimension); void ShowHallucination(int frames, int backdrop); @@ -361,7 +367,10 @@ public: Entity_Player* GetPlayer(int index); ChallengeParam& GetChallengeParams(); Entity* Spawn(const EntitySpawn& spawn); + bool RerollEnemy(Entity* entity, RerollMatch match); }; +bool enemy_erase(Entity& enemy); + void coop_awards_load(std::array& awards); void pause_screen_reset(PauseScreen& pauseScreen); diff --git a/src/game_end.cpp b/src/game_end.cpp index 82459fe..77cdb38 100644 --- a/src/game_end.cpp +++ b/src/game_end.cpp @@ -13,6 +13,7 @@ #include "stage_transition.h" #include #include +#include // The cutscene each ending plays, none for a death. Mom's Heart's first eleven kills each play the next of the Womb's // endings (cutscenes 4 to 14), any later one the credits. @@ -76,7 +77,7 @@ void game_save_delete() { Manager& manager = *g_manager; - if (g_game->dailyChallenge._id != 0) return; + if (g_game->dailyChallenge.id != 0) return; manager.gamestate.Delete(); manager.persistentGameData.gameStateChecksum = 0; manager.persistentGameData.isChangesMade = true; @@ -132,19 +133,26 @@ void run_progress_save() } // 00959180 (save_rerun_to_steam_cloud) Saves the run to play again once RERUN is unlocked, unless the first player -// died with no lives left. -// The rerun file's writer (GameState::write_rerun 009d8190) is not reconstructed yet. Steam Cloud and netplay are -// offline. +// died with no lives left or the run is itself a rerun. Steam Cloud and netplay are offline. void rerun_save() { Manager& manager = *g_manager; Game& game = *g_game; + GameState& gamestate = manager.gamestate; Entity_Player& player = *game.GetPlayer(0); if (player.isDead && player.GetExtraLives() < 1) return; - if (!manager.persistentGameData.Unlocked(ACHIEVEMENT_RERUN)) return; - game.store_game_state(manager.gamestate); - reconstruction_missing("save_rerun_to_steam_cloud 00959180 (GameState::write_rerun 009d8190)"); + if (!manager.persistentGameData.Unlocked(ACHIEVEMENT_RERUN) || gamestate.isRerun) return; + game.store_game_state(gamestate); + gamestate.isModded = manager.modManager.is_any_mod_loaded(); + + if (std::FILE* file = std::fopen(gamestate.rerunPath.c_str(), "wb")) + { + std::vector bytes = gamestate.write_rerun(); + std::fwrite(bytes.data(), 1, bytes.size(), file); + std::fclose(file); + } + manager.persistentGameData.gameStateChecksum = gamestate.checksum; } // 0095aa30 (unlock_completion_mark_for_player_type) A character's completion mark: its unlock (Mom's Heart's only in a @@ -218,7 +226,7 @@ void game_end(GameEnding ending) if (game.deathmatchManager.is_active() && game.deathmatchManager.state != DEATHMATCH_OVER) return; if (ending == ENDING_DEATH) game_save_delete(); - if (game.dailyChallenge._id != 0) reconstruction_missing("Game::End 006f9770 (a daily run's end, 006f9f20)"); + if (game.dailyChallenge.id != 0) reconstruction_missing("Game::End 006f9770 (a daily run's end, 006f9f20)"); if (ending == ENDING_DEATH) { @@ -241,7 +249,7 @@ GameEnding stage_ending_get(EndingPhotos photos) { Game& game = *g_game; ChallengeParam& params = game.GetChallengeParams(); - bool isChallenge = game.challenge != 0 || game.dailyChallenge._id != 0; + bool isChallenge = game.challenge != 0 || game.dailyChallenge.id != 0; bool isChallengePastStage = isChallenge && params.endStage > STAGE_SHEOL; bool isChallengeCathedral = isChallenge && params.pathType == PATH_TYPE_CATHEDRAL; int stageId = RoomConfig::GetStageID((int)game.stage, (int)game.stageType, ROOM_MODE_CURRENT); @@ -382,7 +390,7 @@ void trophy_update(Entity_Pickup& trophy) if (!isLiftEnd && player.IsHoldingItem()) return; player.entityCollisionClass = ENTCOLL_ALL; - GameEnding ending = g_game->dailyChallenge._id != 0 ? stage_ending_get(ENDING_PHOTOS_IGNORED) : ENDING_NONE; + GameEnding ending = g_game->dailyChallenge.id != 0 ? stage_ending_get(ENDING_PHOTOS_IGNORED) : ENDING_NONE; if (ending == ENDING_NONE || ending == ENDING_UNKNOWN) challenge_finish(); else game_end(ending); } diff --git a/src/game_exit.cpp b/src/game_exit.cpp index 9521a49..7c431ed 100644 --- a/src/game_exit.cpp +++ b/src/game_exit.cpp @@ -86,13 +86,13 @@ static void run_screens_reset(Game& game) game.itemOverlay.megaMushPlayerSprite.Reset(); game.itemOverlay.state = ITEM_OVERLAY_INACTIVE; game.itemOverlay.overlayID = 0; - game.bossOverlay._state = 0; + game.bossOverlay.stop(); } // 006fa0c0 Leaves a started run for the menus: the mods hear of it, the run's sounds stop, a playing overlay // finishes, the music's pitch resets, changed progress is backed up and saved, the run is saved or forgotten, then // the run's screens, flags, room weights, console, floor, players, HUD, preloaded images and pause screen reset. -// The boss overlay's sprite is not modeled. The original also skips saving on a Game+0x2658b flag nothing sets. +// The original also skips saving on a Game+0x2658b flag nothing sets. void Game::Exit(bool isSaving) { Game& game = *g_game; diff --git a/src/game_over.cpp b/src/game_over.cpp index fedacda..50fb06c 100644 --- a/src/game_over.cpp +++ b/src/game_over.cpp @@ -17,21 +17,8 @@ constexpr std::string_view DEATH_SCREEN_ANM2 = "gfx/ui/Death Screen.anm2"; constexpr std::string_view DIARY_ANIMATION = "Diary"; constexpr std::string_view SEED_NULL = "SeedPos"; -// The layers of the diary page, by id. -enum DiaryLayer : int -{ - DIARY_LAYER_PORTRAIT = 1, - DIARY_LAYER_LOCATION, - DIARY_LAYER_BOSS, - DIARY_LAYER_NAME, - DIARY_LAYER_ENEMY, - DIARY_LAYER_ITEMS, - DIARY_LAYER_LOCATION_PREFIX = 8 -}; - constexpr int DIARY_PORTRAIT_COUNT = 12; constexpr int DIARY_ITEM_LIMIT = 16; -constexpr int DIARY_ITEM_UNKNOWN_FRAME = COLLECTIBLE_VANILLA_COUNT; constexpr float DIARY_ITEM_STEP_X = 16; constexpr float DIARY_ITEM_STEP_Y = 2.5f; constexpr float DIARY_ROW_END = 128; @@ -52,7 +39,6 @@ constexpr int LOCATION_FRAME_DEFAULT = 4; constexpr int LOCATION_FRAME_ALT = 7; constexpr int LOCATION_FRAME_ASCENT = 12; constexpr int LOCATION_ALT_LAST_STAGE = 8; -constexpr int GREED_STAGE_SHOP = 5; constexpr int GREED_SHOP_LOCATION = 10; constexpr int PORTRAIT_UNKNOWN = 149; diff --git a/src/game_over.h b/src/game_over.h index 468b845..b48c688 100644 --- a/src/game_over.h +++ b/src/game_over.h @@ -5,6 +5,23 @@ #include "game_end.h" #include "mod_manager.h" +// The layers of the diary page (Death Screen.anm2), by id. +enum DiaryLayer : int +{ + DIARY_LAYER_PORTRAIT = 1, + DIARY_LAYER_LOCATION, + DIARY_LAYER_BOSS, + DIARY_LAYER_NAME, + DIARY_LAYER_ENEMY, + DIARY_LAYER_ITEMS, + DIARY_LAYER_LOCATION_PREFIX = 8, + DIARY_LAYER_TRINKETS +}; + +// The frames of the diary's item and trinket sheets drawn for an id below 1. +constexpr int DIARY_ITEM_UNKNOWN_FRAME = 733; +constexpr int DIARY_TRINKET_UNKNOWN_FRAME = 190; + // Whether the game over screen is up. Show is the only writer of a shown state. enum GameOverState : int { diff --git a/src/game_restore.cpp b/src/game_restore.cpp index d0bbf8d..eb7a761 100644 --- a/src/game_restore.cpp +++ b/src/game_restore.cpp @@ -8,6 +8,7 @@ #include "npc_ai.h" #include "npc_basement.h" #include "room.h" +#include "room_grid.h" #include "texture_cache.h" #include #include @@ -25,6 +26,10 @@ constexpr const char* ITEM_POOLS_XML = "itempools.xml"; constexpr int DIMENSION_ALTERNATE = 1; constexpr int AMBUSH_RESUME_COUNTDOWN = 30; constexpr float FAMILIAR_RESTORE_SCATTER = 20; +// Dark Esau comes back at least this far from Tainted Jacob, a random spot this far from the walls tried this often. +constexpr float DARK_ESAU_MIN_DISTANCE_SQUARED = 6400; +constexpr float DARK_ESAU_SPOT_MARGIN = 20; +constexpr int DARK_ESAU_SPOT_TRIES = 20; constexpr int MINI_MUSH_STACKS_SECOND = 4; constexpr int MINI_MUSH_STACKS_THIRD = 7; constexpr int NULLITEM_WAVY_CAP_2 = 72; @@ -180,6 +185,120 @@ void Game::restore_game_state(GameState& state, GameRestore restore) for (Entity_Player* player : playerManager.playerList) player->update_mini_mush_costume(); } +// Part of 00706020: the familiars and friendly enemies leave the room's lists (the state brings them back), counting +// the Glowing Hourglass wisps made in the last frame, and the co-op babies leave. Last to first. How many wisps. +static int rewind_room_clear(Game& game) +{ + EntityList& list = game.room->entityList; + int hourglassWisps = 0; + + for (size_t i = list.updateEL.size() - 1; i < list.updateEL.size(); i--) + { + Entity* entity = list.updateEL[i]; + bool isFamiliar = entity->type == ENTITY_FAMILIAR; + bool isNewWisp = isFamiliar && entity->variant == Entity_Familiar::WISP && + entity->subtype == COLLECTIBLE_GLOWING_HOUR_GLASS && game.frameCount - entity->spawnFrame < 2; + if (isNewWisp) hourglassWisps++; + if (isFamiliar || (Entity::is_enemy_type(entity->type) && entity->IsFriendly())) + { + entity->ClearReferences(); + for (EntityList_EL* sublist : + {&list.mainEL, &list.updateEL, &list.persistentEL, &list.renderEL, &list.wispEL}) + sublist->remove(entity); + entity->isValid = false; + list.invalidate_type_cache(entity->type, entity->variant, entity->subtype); + } + if (entity->type == ENTITY_PLAYER && entity->parent) + game.playerManager.RemoveCoPlayer(static_cast(entity)); + } + return hourglassWisps; +} + +// Part of 00706020: the more options a treasure room had on its first visit (More Options, or a golden crown on its +// floor) come back with its config's weight at full. +static void rewind_treasure_options_restore(Game& game) +{ + RoomDescriptor& current = *game.GetRoomByIdx(game.currentRoomIdx, -1); + if (current.data->type != ROOM_TREASURE || current.visitedCount != 1) return; + + PlayerManager& players = game.playerManager; + auto isGolden = [&players](int trinket) + { + Entity_Player* owner = players.FirstTrinketOwner(trinket); + return owner && owner->GetTrinketMultiplier(trinket) > 1; + }; + bool isSheol = game.stage == STAGE_SHEOL && game.stageType == STAGETYPE_ORIGINAL; + bool isCathedral = game.stage == STAGE_SHEOL && game.stageType == STAGETYPE_WOTL; + bool isWomb = game.stage == STAGE_WOMB_I || game.stage == STAGE_WOMB_II; + bool isMoreOptions = (isSheol && isGolden(TRINKET_WICKED_CROWN)) || (isCathedral && isGolden(TRINKET_HOLY_CROWN)) || + (isWomb && isGolden(TRINKET_BLOODY_CROWN)) || + players.FirstCollectibleOwner(COLLECTIBLE_MORE_OPTIONS, LAZARUS_SHARE_CHECK); + if (isMoreOptions) current.data->weight = 1; +} + +// 00706020 The Glowing Hourglass: the run goes back to the state saved as the players entered the last room (the one +// before when that one is not kept), the familiars and friendly enemies taken out first. The other state is dropped, +// the event counters return to their saved values and the floor counts the rewind. With a player, the main players +// (and their twins) spend one charge among them (a new floor refills them), the player keeps its Bethany charges and +// gets back the Hourglass wisps of the last frame. Every entity hears of it, the players enter the floor and room +// anew and the room updates. +void Game::rewind(Entity_Player* player) +{ + Game& game = *g_game; + int slot = game.currentGlowingHourglassSlot; + if (slot < 0) return; + + GlowingHourglassState* state = &game.glowingHourglassStates[1 - slot]; + if (!state->isUsable) state = &game.glowingHourglassStates[slot]; + if (!state->isUsable) return; + + int hourglassWisps = rewind_room_clear(game); + int soulCharge = player ? player->effectiveSoulCharge : 0; + int bloodCharge = player ? player->effectiveBloodCharge : 0; + bool isNewFloor = state->gameState.stage != game.stage || state->gameState.stageType != game.stageType; + int rewinds = game.rewindsThisFloor; + rewind_treasure_options_restore(game); + + game.isRestoringGlowingHourglassState = true; + game.restore_game_state(state->gameState, RESTORE_REWIND); + game.playerManager.remove_coplayers_without_device(); + game.isRestoringGlowingHourglassState = false; + for (int other = 0; other < GLOWING_HOURGLASS_SLOTS; other++) + { + if (state == &game.glowingHourglassStates[other]) game.currentGlowingHourglassSlot = other; + else game.glowingHourglassStates[other].isUsable = false; + } + PersistentGameData& data = g_manager->persistentGameData; + for (int counter = 0; counter < EVENT_COUNTER_COUNT; counter++) + if (data.eventCounters[counter] != state->eventCounters[counter]) + data.IncreaseEventCounter(counter, state->eventCounters[counter] - data.eventCounters[counter]); + game.rewindsThisFloor = rewinds + 1; + + if (player) + { + std::vector spenders; + for (Entity_Player* main : game.playerManager.playerList) + { + if (main->variant != PLAYER_VARIANT_PLAYER || main->parent) continue; + spenders.push_back(main); + if (main->backupPlayer) spenders.push_back(main->backupPlayer); + } + bool isDecrease = true; + for (Entity_Player* spender : spenders) + if (spender->TryDecreaseGlowingHourglassUses(isDecrease, isNewFloor)) isDecrease = false; + player->effectiveSoulCharge = soulCharge; + player->effectiveBloodCharge = bloodCharge; + for (int i = 0; i < hourglassWisps; i++) + player->AddWisp(COLLECTIBLE_GLOWING_HOUR_GLASS, player->pos, false, false); + } + + for (Entity* entity : std::vector(game.room->entityList.updateEL)) entity->TriggerGlowingHourglass(); + game.playerManager.enter_level(); + game.playerManager.trigger_new_room_effects(); + for (Entity* entity : std::vector(game.room->entityList.updateEL)) entity->hourglass_rewind_clear(); + game.room->Update(); +} + // 00736530 Restores the pools from a save: each pool's weights in draw order (as many as both have) and its Bible // chance, the seeds, the collectibles removed and the trinkets still in the pool (counting those available), the // pill colors' effects and which are identified, and the Genesis counts. @@ -297,6 +416,7 @@ void Level::RestoreGameState(GameState& state) lastRoomIdx = state.lastRoomIdx; dungeonReturnPosition = state.dungeonReturnPosition; dungeonReturnRoomIndex = state.dungeonReturnRoomIndex; + deathCertificateReturn = state.deathCertificateReturn; enterDoor = state.enterDoor; ventricleRazorPortals = state.ventricleRazorPortals; @@ -390,6 +510,24 @@ static void twins_link(std::vector& matched, size_t index) } } +// Part of 009bcaa0: the dead Lazarus kept as a restored Tainted Lazarus' backup, made for it when it has none, then +// restored from its save, which it keeps for when it comes back. +static void backup_player_restore(Entity_Player& main, GameStatePlayer& saved) +{ + if (!main.backupPlayer) + { + main.backupPlayer = new Entity_Player(); + main.backupPlayer->Init(ENTITY_PLAYER, PLAYER_VARIANT_PLAYER, saved.playerType, main.initSeed); + main.backupPlayer->backupPlayer = &main; + } + + Entity_Player& backup = *main.backupPlayer; + + backup.RestoreGameState(saved); + backup.unlistedRestoreState = std::make_shared(); + backup.StoreGameState(backup.unlistedRestoreState.get(), true); +} + // 009bcaa0 Restores the saved players: each matched player from its save (its twin forgotten first), then the twins, // the parents, the backup players and the Esau Jr. players, the glitched baby generator and random babies from the // first saved player, the join seats and the HUDs. @@ -408,8 +546,7 @@ void PlayerManager::RestoreGameState(GameState& state) GameStatePlayer& saved = state.players[i]; int parentIndex = saved.parentIndex; - if (saved.isBackupPlayer && i > 0 && matched[i - 1]) - reconstruction_missing("PlayerManager::RestoreGameState 009bcaa0: a backup player (Tainted Lazarus)"); + if (saved.isBackupPlayer && i > 0 && matched[i - 1]) backup_player_restore(*matched[i - 1], saved); else if (saved.isBackupPlayer || !matched[i]) continue; else if (parentIndex < 0) twins_link(matched, i); else if ((size_t)parentIndex < matched.size() && matched[parentIndex]) @@ -420,8 +557,10 @@ void PlayerManager::RestoreGameState(GameState& state) { delete esauJrState[i]; esauJrState[i] = nullptr; - if (i < state.esauJrStates.size() && state.esauJrStates[i].playerType != -1) - reconstruction_missing("PlayerManager::RestoreGameState 009bcaa0: an Esau Jr. player"); + if (i >= state.esauJrStates.size() || state.esauJrStates[i].playerType == -1) continue; + esauJrState[i] = new Entity_Player(); + esauJrState[i]->Init(ENTITY_PLAYER, PLAYER_VARIANT_PLAYER, PLAYER_ISAAC, Random()); + esauJrState[i]->RestoreGameState(state.esauJrStates[i]); } if (!state.players.empty()) { @@ -732,11 +871,64 @@ void Entity_Player::RestoreGameState(GameStatePlayer& saved) try_trigger_astral_projection(); } +// A free spot for a restored entity, searched from the room's centre out to a random reach up to its larger side. +static Vector restore_spot_find(bool isAvoidActiveEntities) +{ + Room& room = *g_game->room; + Vector size = vector_sub(room.bottomRightPos, room.topLeftPos); + Vector center = vector_make(size.x * HALF + room.topLeftPos.x, size.y * HALF + room.topLeftPos.y); + float reach = random_unit() * std::max(size.x, size.y); + + return room_free_pickup_position_find( + {.position = center, .step = reach, .isAvoidActiveEntities = isAvoidActiveEntities}); +} + +// Part of 007b0070: a charmed enemy the player kept, back at a free spot as the player's friend, holding no door shut +// and not counted among the room's enemies, the player's own when it was player controlled. +static void charmed_enemy_restore(Entity_Player& player, const EntityDesc& desc) +{ + EntityList& entities = g_game->room->entityList; + Entity_NPC* npc = entity_desc_spawn(desc, restore_spot_find(false), nullptr); + + if (!npc) return; + if (desc.isPlayerControlled) npc->controllerID = player.controllerIndex; + if (npc->CanShutDoors() && npc->type != ENTITY_DARK_ESAU) + { + entities.enemyCount--; + if (npc->IsBoss()) entities.bossCount--; + } + npc->isCanShutDoors = false; + npc->AddCharmed(EntityRef(&player), -1, false, false); + npc->Update(); +} + +// Part of 007b0070: Tainted Jacob's Dark Esau made anew at a free spot, tried again at random spots (up to 20 times) +// while it is too near him. +static void dark_esau_restore(Entity_Player& player) +{ + if (player.darkEsau) player.darkEsau->Remove(); + + Vector spot = restore_spot_find(true); + + for (int tries = 0; tries < DARK_ESAU_SPOT_TRIES; tries++) + { + if (vector_length_squared(vector_sub(player.pos, spot)) >= DARK_ESAU_MIN_DISTANCE_SQUARED) break; + spot = room_free_pickup_position_find( + {.position = g_game->room->GetRandomPosition(DARK_ESAU_SPOT_MARGIN), .isAvoidActiveEntities = true}); + } + + uint32_t seed = Random(); + Entity* esau = g_game->Spawn({.position = spot, .spawner = &player, .type = ENTITY_DARK_ESAU, .seed = seed}); + + player.darkEsau = esau; + esau->ClearEntityFlags(FLAG_APPEAR); + esau->Update(); +} + // 007b0070 Finishes a saved player once its floor is entered: its familiars around it, then (unless it was replaced) // the Forgotten's body for the Soul, its charmed enemies, the items whose effect lasts the floor, its bleeding, Greed's // Gullet, the item it held up, its temporary effects (rebuilt from the persistent ones when it saved none), Dark Esau, // the co-op ghost's entrance and a sub player the Soul of the Forgotten no longer needs. Its stats are evaluated again. -// The charmed enemies, Dark Esau and the co-op ghost wait for their takeovers. void Entity_Player::RestoreGameState_PostLevelInit(GameStatePlayer& saved) { for (const FamiliarData& familiar : saved.familiars) @@ -752,8 +944,7 @@ void Entity_Player::RestoreGameState_PostLevelInit(GameStatePlayer& saved) if (replacedPlayer) return; if (playerType == PLAYER_THESOUL) spawn_forgotten_body(); - if (!saved.charmedEnemies.empty()) - reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: the charmed enemies"); + for (const EntityDesc& enemy : saved.charmedEnemies) charmed_enemy_restore(*this, enemy); levelEffectItems = saved.levelEffectItems; bleedOutHealth = saved.bleedOutHealth; if (bleedOutHealth > 0) @@ -777,11 +968,20 @@ void Entity_Player::RestoreGameState_PostLevelInit(GameStatePlayer& saved) restored.cooldown = effect.cooldown; } - if (saved.darkEsauHealth > 0) - reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: Dark Esau"); - if (isCoopGhost) reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: the co-op ghost"); + if (saved.darkEsauHealth > 0) dark_esau_restore(*this); + if (isCoopGhost) + { + reset_body_sprite(); + PlayExtraAnimation("GhostAppear"); + entityGridCollisionClass = GRIDCOLL_WALLS; + isInvincible = true; + isVisible = true; + } if (temporaryEffects.HasNullEffect(NULLITEM_SOUL_FORGOTTEN) && parent.get() && subPlayer) - reconstruction_missing("Entity_Player::RestoreGameState_PostLevelInit 007b0070: removing the sub player"); + { + subPlayer->ClearReferences(); + delete std::exchange(subPlayer, nullptr); + } UpdateCanShoot(); cacheFlags |= ALL_CACHE_FLAGS; EvaluateItems(); diff --git a/src/game_save.cpp b/src/game_save.cpp index d0aaead..f90ad2a 100644 --- a/src/game_save.cpp +++ b/src/game_save.cpp @@ -215,6 +215,7 @@ void Level::store_game_state(GameState& state) state.lastRoomDimensionIdx = (uint8_t)lastRoomDimensionIdx; state.dungeonReturnPosition = dungeonReturnPosition; state.dungeonReturnRoomIndex = dungeonReturnRoomIndex; + state.deathCertificateReturn = deathCertificateReturn; state.enterDoor = enterDoor; state.ventricleRazorPortals = ventricleRazorPortals; } diff --git a/src/game_state.cpp b/src/game_state.cpp index e196d58..90915bb 100644 --- a/src/game_state.cpp +++ b/src/game_state.cpp @@ -57,9 +57,6 @@ constexpr int ITEM_KIND_NULL = 0; constexpr int ITEM_KIND_TRINKET = 2; constexpr int UNSET_PLAYER_WORDS = 2; -// The Death Certificate floor's way back as a saved run keeps it: three words and two flags. -constexpr size_t DEATH_CERTIFICATE_RETURN_SIZE = 3 * sizeof(int) + 2 * sizeof(uint8_t); - // An Esau Jr. slot without a player. static GameStatePlayer esau_jr_empty() { @@ -148,6 +145,24 @@ struct StateWriter if (count % 8) write(packed); } + // Appends the start seed as its 9 character string. + void seed_write(uint32_t seed) + { + if (!seed) log_printf(LOG_ASSERT, "Error: Game Start Seed was not set.\n"); + std::string seedString = Seeds::Seed2String(seed); + seedString.resize(SEED_STRING_LENGTH); + bytes_write({(const uint8_t*)seedString.data(), seedString.size()}); + } + + // Closes the file with its checksum, scrambled, and gives the checksum. + uint32_t seal() + { + uint32_t value = checksum.value_get(); + uint32_t sealed = value ^ CHECKSUM_KEY; + bytes.insert(bytes.end(), (const uint8_t*)&sealed, (const uint8_t*)&sealed + sizeof(sealed)); + return value; + } + void entity_write(const EntitySaveState& entity); void room_write(const SavedRoom& room); void co_player_write(const CoPlayerState& player); @@ -623,9 +638,12 @@ std::vector GameState::write() writer.write(slowdownDuration); writer.write(dungeonReturnPosition.x); writer.write(dungeonReturnPosition.y); - for (int value : {dungeonReturnRoomIndex, -1, 0, 0}) writer.write(value); - writer.write((uint8_t)0); - writer.write((uint8_t)0); + writer.write(dungeonReturnRoomIndex); + writer.write(deathCertificateReturn.leaveDoor); + writer.write(deathCertificateReturn.roomIdx); + writer.write(deathCertificateReturn.lastRoomIdx); + writer.write(deathCertificateReturn.dimension); + writer.write(deathCertificateReturn.lastRoomDimension); writer.write(enterDoor); for (const VentricleRazorPortal& portal : ventricleRazorPortals) { @@ -647,10 +665,7 @@ std::vector GameState::write() } writer.item_pool_write(itemPool); - if (!seeds.gameStartSeed) log_printf(LOG_ASSERT, "Error: Game Start Seed was not set.\n"); - std::string seedString = Seeds::Seed2String(seeds.gameStartSeed); - seedString.resize(SEED_STRING_LENGTH); - writer.bytes_write({(const uint8_t*)seedString.data(), seedString.size()}); + writer.seed_write(seeds.gameStartSeed); std::array specialSeeds{}; for (int i = 0; i < SPECIAL_SEED_COUNT; i++) if (seeds.HasSeedEffect(i)) specialSeeds[i / 8] |= 1 << (i % 8); @@ -691,9 +706,24 @@ std::vector GameState::write() writer.write(versusRules); writer.list_write(versusPlayers); - checksum = writer.checksum.value_get(); - uint32_t sealed = checksum ^ CHECKSUM_KEY; - writer.bytes.insert(writer.bytes.end(), (const uint8_t*)&sealed, (const uint8_t*)&sealed + sizeof(sealed)); + checksum = writer.seal(); + return writer.bytes; +} + +// 009d8190 Writes the rerun in the original's format: the unchecked header, the console flag, the difficulty and the +// modding, the players and the start seed, closed by the checksum, which the run's checksum takes. +std::vector GameState::write_rerun() +{ + StateWriter writer; + + writer.bytes.assign(SAVE_HEADER, SAVE_HEADER + sizeof(SAVE_HEADER)); + writer.write((uint8_t)isConsoleUsedThisRun); + writer.write(difficulty); + writer.write((uint8_t)isModded); + writer.write((uint8_t)players.size()); + for (const GameStatePlayer& player : players) writer.player_write(player); + writer.seed_write(seeds.gameStartSeed); + checksum = writer.seal(); return writer.bytes; } @@ -1272,14 +1302,35 @@ static std::array room_map_unpack(const std::vector file) +// A saved file's version from its header, 0 when the header names none the reader knows (155 to 169). +static uint32_t header_version_read(std::span file) { std::array header{}; uint32_t version = 0; std::copy_n(file.begin(), std::min(file.size(), sizeof(SAVE_HEADER)), header.begin()); bool isHeaderRead = std::sscanf(header.data(), "ISAACNG_GSR%u", &version) == 1; - if (!isHeaderRead || version < SAVE_VERSION_OLDEST || version > SAVE_VERSION) + return isHeaderRead && version >= SAVE_VERSION_OLDEST && version <= SAVE_VERSION ? version : 0; +} + +// Whether a saved file ends with its checksum, scrambled, over everything after the header, which outChecksum takes. +static bool seal_check(std::span file, uint32_t& outChecksum) +{ + uint32_t sealed = 0; + Checksum fileChecksum; + + if (file.size() < sizeof(SAVE_HEADER) + sizeof(sealed)) return false; + fileChecksum.Update(file.subspan(sizeof(SAVE_HEADER), file.size() - sizeof(SAVE_HEADER) - sizeof(sealed))); + std::memcpy(&sealed, file.data() + file.size() - sizeof(sealed), sizeof(sealed)); + outChecksum = fileChecksum.value_get(); + return (sealed ^ CHECKSUM_KEY) == outChecksum; +} + +bool GameState::read(std::span file) +{ + uint32_t version = header_version_read(file); + + if (!version) { log_printf(LOG_INFO, "[warn] GameState header is incorrect (%u != %u).\n", version, SAVE_VERSION); Delete(); @@ -1287,17 +1338,9 @@ bool GameState::read(std::span file) } log_printf(LOG_INFO, "GameState Version Loaded: %u\n", version); - uint32_t sealed = 0; - Checksum fileChecksum; - bool isSealed = file.size() >= sizeof(SAVE_HEADER) + sizeof(sealed); - if (isSealed) - { - fileChecksum.Update(file.subspan(sizeof(SAVE_HEADER), file.size() - sizeof(SAVE_HEADER) - sizeof(sealed))); - std::memcpy(&sealed, file.data() + file.size() - sizeof(sealed), sizeof(sealed)); - } - checksum = fileChecksum.value_get(); - bool isChecksumValid = (sealed ^ CHECKSUM_KEY) == checksum && checksum == g_manager->persistentGameData.gameStateChecksum; - if (!isSealed || !isChecksumValid) + bool isSealed = seal_check(file, checksum); + bool isChecksumValid = isSealed && checksum == g_manager->persistentGameData.gameStateChecksum; + if (!isChecksumValid) { log_printf(LOG_INFO, "[warn] GameState File %s: Checksum invalid!\n", savePath.c_str()); return false; @@ -1347,7 +1390,8 @@ bool GameState::read(std::span file) reader.fields_read(currentRoomIdx, currentDimensionIdx, lastRoomDimensionIdx, lastRoomIdx); if (version >= SAVE_VERSION_BROKEN_WATCH) reader.fields_read(brokenWatchState, slowdownDuration); reader.fields_read(dungeonReturnPosition, dungeonReturnRoomIndex); - reader.position += DEATH_CERTIFICATE_RETURN_SIZE; + DimensionReturn& back = deathCertificateReturn; + reader.fields_read(back.leaveDoor, back.roomIdx, back.lastRoomIdx, back.dimension, back.lastRoomDimension); enterDoor = reader.read(); for (VentricleRazorPortal& portal : ventricleRazorPortals) reader.fields_read(portal.roomIndex, portal.gridIndex); for (VentricleRazorPortal& portal : ventricleRazorPortals) portal.isMarked = reader.bool_read(); @@ -1424,4 +1468,36 @@ bool GameState::read(std::span file) return false; } -bool GameState::read_rerun(std::span) { reconstruction_missing("GameState::read_rerun 009d7d50"); } +// 009d7d50 Reads the rerun as write_rerun writes it, once its header names a known version and its checksum holds: a +// rerun of the saved players and start seed. A wrong header deletes the rerun. The players' own checks are not +// heeded, as the original's are not. +bool GameState::read_rerun(std::span file) +{ + uint32_t version = header_version_read(file); + uint32_t rerunChecksum = 0; + + if (!version) + { + log_printf(LOG_INFO, "[warn] GameState Rerun header is incorrect (%u != %u).\n", version, SAVE_VERSION); + DeleteRerun(); + return isRerunAvailable; + } + if (!seal_check(file, rerunChecksum)) + { + log_printf(LOG_INFO, "[warn] GameState File %s: Checksum invalid!\n", rerunPath.c_str()); + return false; + } + + StateReader reader = {file, sizeof(SAVE_HEADER), version, rerunPath.c_str()}; + std::array seedString{}; + + isConsoleUsedThisRun = reader.bool_read(); + difficulty = reader.read(); + isModded = reader.bool_read(); + isRerun = true; + players.assign(std::max(reader.read(), 0), {}); + for (GameStatePlayer& player : players) reader.player_read(player); + reader.each_read(std::span(seedString).first(SEED_STRING_LENGTH)); + seeds.set_start_seed(Seeds::String2Seed(seedString.data())); + return true; +} diff --git a/src/game_state.h b/src/game_state.h index 4fbede9..da972ab 100644 --- a/src/game_state.h +++ b/src/game_state.h @@ -103,6 +103,7 @@ struct GameState std::string rerunPath; std::string savePath; + DimensionReturn deathCertificateReturn; Vector dungeonReturnPosition{}; float angelRoomChance = 0; int ambushWave = 0; @@ -183,6 +184,7 @@ struct GameState bool read(std::span file); bool read_rerun(std::span file); std::vector write(); + std::vector write_rerun(); }; // The run as the Glowing Hourglass can rewind it: the game state as the players entered a room, the door they left diff --git a/src/game_transition.cpp b/src/game_transition.cpp index e56f9a6..680e6fc 100644 --- a/src/game_transition.cpp +++ b/src/game_transition.cpp @@ -17,7 +17,6 @@ constexpr int ROOM_INDEX_MIN = -20; constexpr int ROOM_INDEX_MAX = LEVEL_GRID_CELLS - 1; constexpr int DIMENSION_MAX = 2; -constexpr int DOOR_SIDES = 4; constexpr int SIDE_ACROSS = 2; constexpr int MAZE_MOVE_CHANCE = 10; constexpr int MAZE_SWAP_CHANCE = 5; diff --git a/src/game_update.cpp b/src/game_update.cpp index 5248186..1b0b0e6 100644 --- a/src/game_update.cpp +++ b/src/game_update.cpp @@ -32,10 +32,6 @@ constexpr int ASCENT_SHAKE_BASE = 2; constexpr int DEATH_CERTIFICATE_SHAKE = 10; constexpr int HUD_REFRESH_INTERVAL = 30; constexpr uint64_t FADE_IN_ICON_MS = 3000; -// The room's render surface, its size and margin, centered on the screen. -constexpr float ROOM_SURFACE_WIDTH = 338; -constexpr float ROOM_SURFACE_HEIGHT = 182; -constexpr float ROOM_SURFACE_MARGIN = 52; // The menu each menu fade out returns to. @@ -191,7 +187,8 @@ static void fadeout_finish(Game& game) break; } case FADEOUT_VICTORY_LAP: - reconstruction_missing("Game::NextVictoryLap 006f7ac0"); + game.NextVictoryLap(); + break; case FADEOUT_ARENA: game.deathmatchManager.enter_arena(); break; @@ -289,7 +286,7 @@ static void timers_update(Game& game) { game.framesSinceRoomTransition++; game.minimap.Update(); - if (game.bossOverlay._state != 0) BossOverlay::update(); + game.bossOverlay.update(); if (game.ascentTimer > 0) { diff --git a/src/grid_entity.cpp b/src/grid_entity.cpp index df55306..76266aa 100644 --- a/src/grid_entity.cpp +++ b/src/grid_entity.cpp @@ -66,7 +66,7 @@ constexpr int SACRIFICE_LIKE_COIN_COUNT = 6; constexpr int SACRIFICE_LIKE_FORM_STEPS = 3; constexpr float SACRIFICE_BLESS_SMALL = 0.15f; constexpr float SACRIFICE_BLESS_LARGE = 0.5f; -constexpr int SACRIFICE_ANGEL_DELAY = 35; +constexpr int SACRIFICE_BOMB_RAIN_FRAMES = 35; constexpr uint32_t SACRIFICE_REDEMPTION_LAST_STAGE = 6; constexpr int SACRIFICE_END_STAGE = 12; constexpr int SACRIFICE_ASCEND_MIN_END = 10; @@ -403,7 +403,7 @@ static void sacrifice_ascend(RNG& reward, Entity_Player* player) bool isLocked = !g_manager->persistentGameData.achievements[ACHIEVEMENT_SACRIFICE_DARK_ROOM] && (g_manager->state != MANAGER_STATE_GAME || !game.isDebug); int endStage = SACRIFICE_END_STAGE; - if (params.endStage != SACRIFICE_END_STAGE && (game.challenge != 0 || game.dailyChallenge._id != 0 || isLocked)) + if (params.endStage != SACRIFICE_END_STAGE && (game.challenge != 0 || game.dailyChallenge.id != 0 || isLocked)) endStage = SACRIFICE_END_STAGE - 1; if (params.isPathTypeSet) { @@ -482,7 +482,7 @@ static void sacrifice_room_reward(int sacrifices, RNG& reward, Entity_Player* pl break; } case 7: - game.room->unknown7230 = SACRIFICE_ANGEL_DELAY; + game.room->bombRainTimer = SACRIFICE_BOMB_RAIN_FRAMES; break; case 8: case 10: diff --git a/src/grid_entity.h b/src/grid_entity.h index c5e2ce1..ec2eb88 100644 --- a/src/grid_entity.h +++ b/src/grid_entity.h @@ -54,6 +54,10 @@ enum GridCollision : int // The room's grid path a grid entity claims for its cell: freed when it breaks, solid while it stands. constexpr int GRID_PATH_FREED = 900; constexpr int GRID_PATH_SOLID = 1000; +// A tinted rock is a super tinted one one time in this many, once unlocked. +constexpr uint32_t SUPER_TINTED_ODDS = 20; +// The least grid path no path crosses. +constexpr int GRID_PATH_IMPASSABLE = 950; // A path cost's thousands band, and a pit's band. constexpr int GRID_PATH_BAND = 1000; diff --git a/src/grid_entity_door.h b/src/grid_entity_door.h index 8ebdc38..fecb677 100644 --- a/src/grid_entity_door.h +++ b/src/grid_entity_door.h @@ -4,6 +4,8 @@ #include "grid_entity.h" #include +constexpr int DOOR_SIDES = 4; + // How a door is locked (Lua's DoorVariant). enum DoorVariant : int { diff --git a/src/grid_entity_fire.cpp b/src/grid_entity_fire.cpp index 515259b..e1b2c32 100644 --- a/src/grid_entity_fire.cpp +++ b/src/grid_entity_fire.cpp @@ -1,26 +1,195 @@ #include "grid_entity_fire.h" -#include "log.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "game.h" +#include "manager.h" +#include "npc_fireplace.h" +#include "player_stats.h" +#include "room.h" +#include "seeds.h" -// 0067db00 Loads the fire and its embers. +// A grid fire's grid path while it stands, the odds a fresh one burns red, and its red tints. +constexpr int GRID_FIRE_PATH = 1400; +constexpr uint32_t GRID_FIRE_RED_ODDS = 40; +constexpr ColorMod GRID_FIRE_RED = {{0.65882355f, 0.023529412f, 0.023529412f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod GRID_EMBER_RED = {{1, 0.15f, 0.15f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The fire's stages as it is put out, the last one out, and the animations of the burning ones. +constexpr int GRID_FIRE_OUT = 4; +constexpr const char* FIRE_STAGES[GRID_FIRE_OUT] = {"FireStage00", "FireStage01", "FireStage02", "FireStage03"}; + +// What a burning fire deals to what touches it, and how long a fresh room waits before a red one spits. +constexpr GridHurt GRID_FIRE_HURT = {.damageFlags = DAMAGE_FIRE, + .damage = 16, + .distance = 38, + .playerDistance = 38, + .playerDamage = 1, + .isIgnoreGridCollisionClass = true}; +constexpr int GRID_FIRE_SHOOT_AFTER = 60; + +// The embers: at most five at once, their lifetimes, and how they waver and slow. +constexpr size_t GRID_EMBERS_MAX = 5; +constexpr uint32_t GRID_EMBER_LIFETIME = 30; +constexpr float EMBER_WAVER_X = 0.4f; +constexpr float EMBER_WAVER_Y = 0.1f; +constexpr float EMBER_DRAG_X = 0.98f; +constexpr float EMBER_DRAG_Y = 0.97f; + +// A fire put out: its poof a little above the cell, and the one in ten that drops a coin or a heart (one in four, or +// one in twenty with Daemon's Tail), and the odds a hit puts it out a stage more. +constexpr float PUT_OUT_POOF_HEIGHT = 10; +constexpr float PUT_OUT_DROP_CHANCE = 0.1f; +constexpr float PUT_OUT_HEART_CHANCE = 0.25f; +constexpr uint32_t FIRE_HIT_BONUS_ODDS = 3; + +// 0067db00 Sets up the fire: a fresh one may burn red, its cell's path is claimed, the fireplace, flame and ember +// sprites load (tinted red for a red fire) with the poof and drops preloaded, and it takes one of three looks. void GridEntity_Fire::subclass_init() { - reconstruction_missing("GridEntity_Fire::subclass_init 0067db00"); + Room& room = *g_game->room; + EntityConfig& config = g_manager->entityConfig; + + if (spawnCount < 2 && variant == FIRE_NORMAL && Random() % GRID_FIRE_RED_ODDS == 0) variant = FIRE_RED; + if ((uint32_t)gridIndex < ROOM_GRID_CELLS) room.gridPaths[gridIndex] = GRID_FIRE_PATH; + sprite.Load("gfx/grid/grid_fireplace.anm2", GRAPHICS_LOAD); + sprite.Play(FLICKERING[0]); + fireSprite.Load("gfx/grid/effect_005_fire.anm2", GRAPHICS_LOAD); + fireSprite.Play(FIRE_STAGES[0]); + for (auto [type, kind] : {std::pair{ENTITY_EFFECT, (int)EFFECT_POOF01}, {ENTITY_PICKUP, PICKUP_HEART}, {ENTITY_PICKUP, PICKUP_COIN}}) + if (EntityConfig_Entity* entity = config.GetEntity(type, kind, 0)) config.PreloadResources(entity); + if (variant == FIRE_RED) fireSprite.color = GRID_FIRE_RED; + + shotCooldown = 0; + flickerVariant = (int)(Random() % FIRE_LOOKS); + emberSprite.Load("gfx/grid/Effect_Ember.anm2", GRAPHICS_LOAD); + emberSprite.Play("Idle"); + if (variant == FIRE_RED) emberSprite.color = GRID_EMBER_RED; + embers.clear(); } -// 0067e0f0 Burns down as it is hurt, hurts what touches it and drifts its embers. +// 0067e0f0 Shows the fire's stage and burns what touches it while lit, a red one now and then spitting a fire shot at +// the nearest player in sight. Embers drift up from it, wavering, until their time is up. void GridEntity_Fire::Update() { - reconstruction_missing("GridEntity_Fire::Update 0067e0f0"); + Game& game = *g_game; + Room& room = *game.room; + + if (state < GRID_FIRE_OUT) fireSprite.Play(FIRE_STAGES[state]); + else if (state == GRID_FIRE_OUT) + { + fireSprite.Stop(); + fireSprite.GetLayer(0)->isVisible = false; + } + if (state >= GRID_FIRE_OUT) + { + sprite.Play(NO_FIRE[flickerVariant]); + collisionClass = COLLISION_NONE; + } + else + { + sprite.Play(FLICKERING[flickerVariant]); + hurt_surroundings(GRID_FIRE_HURT); + collisionClass = COLLISION_OBJECT; + } + fireSprite.Update(); + sprite.Update(); + + bool isAiming = variant == FIRE_RED && shotCooldown < 1 && state < GRID_FIRE_OUT && Random() % FIRE_AIM_ODDS == 0 && + room.isInitialized && game.frameCount - room.enterFrame > GRID_FIRE_SHOOT_AFTER; + if (isAiming) + { + Vector position = room.GetGridPosition(gridIndex); + Vector target = game_nearest_player(position)->pos; + Vector direction = vector_normalized(vector_sub(target, position)); + Vector mouth = vector_add(position, vector_scale(direction, FIRE_MOUTH_REACH)); + if (vector_distance(target, position) < FIRE_SIGHT && room_check_line(mouth, target, LINE_MODE_PROJECTILE, 0) && + Random() % FIRE_SHOOT_ODDS == 0) + { + Entity* shot = game.Spawn({.position = mouth, + .velocity = vector_scale(direction, FIRE_SHOT_SPEED), + .type = ENTITY_PROJECTILE, + .seed = Random()}); + static_cast(shot)->projectileFlags |= PROJECTILE_FIRE_FLAG; + shotCooldown = FIRE_SHOOT_COOLDOWN; + } + } + else if (shotCooldown > 0) shotCooldown--; + + if (Random() % FIRE_EMBER_ODDS == 0 && embers.size() < GRID_EMBERS_MAX) + { + FireEmber ember; + ember.lifetime = (int)(Random() % GRID_EMBER_LIFETIME); + ember.velocity.y = random_unit() * -FIRE_EMBER_RISE_RANGE - FIRE_EMBER_RISE_MIN; + ember.velocity.x = random_unit() * FIRE_EMBER_DRIFT - FIRE_EMBER_DRIFT / 2; + ember.position.y = -FIRE_EMBER_HEIGHT - random_unit() * FIRE_EMBER_HEIGHT; + ember.position.x = random_unit() * FIRE_EMBER_SPREAD - FIRE_EMBER_SPREAD / 2; + embers.push_back(ember); + } + for (size_t i = 0; i < embers.size();) + { + FireEmber& ember = embers[i]; + ember.position = vector_add(ember.position, ember.velocity); + float waverY = random_unit() * EMBER_WAVER_Y - EMBER_WAVER_Y / 2; + float waverX = random_unit() * EMBER_WAVER_X - EMBER_WAVER_X / 2; + ember.frame++; + ember.velocity.x = (waverX + ember.velocity.x) * EMBER_DRAG_X; + ember.velocity.y = (waverY + ember.velocity.y) * EMBER_DRAG_Y; + if (ember.frame < ember.lifetime) i++; + else embers.erase(embers.begin() + (long)i); + } } -// 0067e880 Draws the fire and its embers. -void GridEntity_Fire::Render(const Vector&) +// 0067e880 Draws the fireplace and its flame, and while it burns each ember at its age's frame. +void GridEntity_Fire::Render(const Vector& offset) { - reconstruction_missing("GridEntity_Fire::Render 0067e880"); + Vector position = vector_add(get_render_position(), offset); + + sprite.Render({.position = position}); + fireSprite.Render({.position = position}); + if (state >= GRID_FIRE_OUT) return; + + for (FireEmber& ember : embers) + { + if (emberSprite.animState.animData) + { + float age = (float)ember.frame / (float)ember.lifetime; + emberSprite.animState.SetFrameFloat((float)(int)(age * (float)emberSprite.animState.GetAnimationLength())); + } + emberSprite.Render({.position = vector_add(position, ember.position)}); + } } -// 0067ea60 Puts the fire out a stage. -bool GridEntity_Fire::Hurt(int, const EntityRef&) +// 0067ea60 Puts the fire out by the damage's stages, one more a third of the time. Once out it hisses and poofs, frees +// its cell, counts for its player (Black Powder's blast) and one time in ten drops a coin, or a heart. +bool GridEntity_Fire::Hurt(int damage, const EntityRef& source) { - reconstruction_missing("GridEntity_Fire::Hurt 0067ea60"); + Game& game = *g_game; + int stages = Random() % FIRE_HIT_BONUS_ODDS == 0 ? std::min(damage + 1, GRID_FIRE_OUT) : damage; + + if (stages < 1 || state >= GRID_FIRE_OUT) return false; + state = std::min(state + stages, GRID_FIRE_OUT); + if (state != GRID_FIRE_OUT) return true; + + grid_sound_play(SOUND_STEAM_HALFSEC, {.volume = PUT_OUT_VOLUME}); + Vector poof = vector_add(game.room->GetGridPosition(gridIndex), vector_make(0, -PUT_OUT_POOF_HEIGHT)); + game.Spawn({.position = poof, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + if ((uint32_t)gridIndex < ROOM_GRID_CELLS) game.room->gridPaths[gridIndex] = GRID_PATH_FREED; + auto* player = source.entity ? static_cast(source.entity->GetPlayerAncestor()) : nullptr; + if (player) + { + Player_stats_add(game.onlinePlayerStats, ONLINE_STAT_FIRES_PUT_OUT, player, 1); + if (player->HasCollectible(COLLECTIBLE_BLACK_POWDER)) + explosion_effects({.position = Position(), .source = player, .damage = BLACK_POWDER_DAMAGE}); + } + if (random_unit() >= PUT_OUT_DROP_CHANCE) return true; + + bool isHeart = random_unit() < PUT_OUT_HEART_CHANCE && + (!game.playerManager.AnyoneHasTrinket(TRINKET_DAEMONS_TAIL) || Random() % (uint32_t)DAEMONS_TAIL_HEART_ODDS == 0); + game.Spawn({.position = Position(), .type = ENTITY_PICKUP, .variant = isHeart ? PICKUP_HEART : PICKUP_COIN, .seed = Random()}); + return true; } diff --git a/src/grid_entity_fire.h b/src/grid_entity_fire.h index a5e5eb3..2e30db3 100644 --- a/src/grid_entity_fire.h +++ b/src/grid_entity_fire.h @@ -13,14 +13,15 @@ struct FireEmber }; // Destruction (0070ba00) is the default. -// A fireplace (Lua's GRID_FIREPLACE grid version): a fire burning on its cell, its embers drifting up. +// A fireplace (Lua's GRID_FIREPLACE grid version): a fire burning on its cell in one of three looks, put out in stages +// (its state), a red one (its variant) spitting fire shots, its embers drifting up. struct GridEntity_Fire : GridEntity { ANM2 emberSprite; ANM2 fireSprite; std::vector embers; int flickerVariant = 0; - int hurtCooldown = 0; + int shotCooldown = 0; void subclass_init() override; void Update() override; diff --git a/src/grid_entity_pressure_plate.cpp b/src/grid_entity_pressure_plate.cpp index 360c49b..92fdd31 100644 --- a/src/grid_entity_pressure_plate.cpp +++ b/src/grid_entity_pressure_plate.cpp @@ -1,4 +1,6 @@ #include "grid_entity_pressure_plate.h" +#include "entity_bomb.h" +#include "entity_effect.h" #include "entity_pickup.h" #include "entity_player.h" #include "entity_slot.h" @@ -7,6 +9,7 @@ #include "grid_entity_door.h" #include "grid_entity_poop.h" #include "manager.h" +#include "npc_fireplace.h" #include "npc_ai.h" #include "room.h" #include "room_grid.h" @@ -20,6 +23,18 @@ constexpr float PLATE_PRESS_RADIUS = 30; // An unpressed plate claims its cell's path, and a plain one holds the room's clear back. constexpr int PLATE_PATH = 300; + +// The kill button: its rumble's delay and shake, the blow it deals and its countdown, the most it strikes a frame, +// the empty frames that end it, a moveable fire's health before its blow, and its first frame's red poofs. +constexpr int KILL_BUTTON_SOUND_DELAY = 20; +constexpr int KILL_BUTTON_SHAKE = 15; +constexpr float KILL_BUTTON_DAMAGE = 1000; +constexpr int KILL_BUTTON_COUNTDOWN = 30; +constexpr int KILL_BUTTON_MAX_KILLS = 10; +constexpr int KILL_BUTTON_EMPTY_FRAMES = 4; +constexpr float KILL_BUTTON_FIRE_HEALTH = 0.1f; +constexpr ColorMod KILL_BUTTON_POOF = {{1, 0.3f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int KILL_BUTTON_POOF_PRIORITY = 255; constexpr int ROOM_CLEAR_HOLD = 10; // A reward plate whose ambush was left unbeaten spawns it again this many frames into the next visit. @@ -55,9 +70,8 @@ constexpr uint32_t REWARD_HEARTS_MAX = 2; constexpr uint32_t REWARD_BOMBS_MAX = 2; constexpr int REWARD_CHESTS[] = {PICKUP_CHEST, PICKUP_LOCKEDCHEST, PICKUP_BOMBCHEST, PICKUP_REDCHEST}; -// The slots and bomb a reward plate drops (Lua's SlotVariant and BombVariant). +// The slot a reward plate drops (Lua's SlotVariant). constexpr int SLOT_FORTUNE_TELLING = 3; -constexpr int BOMB_TROLL = 3; // An ambush brings two to four enemies, near the doors no player stands within reach of, scattered a little. constexpr uint32_t AMBUSH_EXTRA_MAX = 3; @@ -457,9 +471,63 @@ static void plate_ambush_spawn(GridEntity& plate, RNG& rng) if (!room.IsClear()) plate.state = PLATE_AMBUSH; } +// 00983f30 pressure_plate_kill_enemies_timer_callback: each frame the kill button's timer strikes the room's +// door-shutting enemies, ten at most (none friendly, no Blood Puppy or Dark Esau), with 1000 damage from its presser +// (their health dropped to none first) or a plain kill at none, in red poofs on its first frame. Projectiles die while +// the timer lives and moveable fires burn out. Five frames with nothing left end it. +static void kill_button_tick(Entity_Effect* timer) +{ + Game& game = *g_game; + EntityList_EL& entities = game.room->entityList.updateEL; + bool isFirstFrame = game.frameCount == timer->spawnFrame; + bool isEmpty = true; + int kills = 0; + + for (size_t i = 0; i < entities.size(); i++) + { + Entity& entity = *entities[i]; + bool isEnemy = is_npc_type(entity.type) && entity.CanShutDoors() && !entity.HasEntityFlags(FLAG_FRIENDLY) && + entity.type != ENTITY_BLOOD_PUPPY && entity.type != ENTITY_DARK_ESAU; + if (!isEnemy) + { + if (entity.type == ENTITY_PROJECTILE && !timer->isDead) entity.Kill(EntityRef()); + else if (entity.type == ENTITY_FIREPLACE && entity.variant == FIRE_MOVEABLE) + { + entity.health = KILL_BUTTON_FIRE_HEALTH; + entity.TakeDamage(KILL_BUTTON_DAMAGE, 0, EntityRef(timer->parent), KILL_BUTTON_COUNTDOWN); + } + else continue; + isEmpty = false; + continue; + } + if (entity.isDead || kills >= KILL_BUTTON_MAX_KILLS) continue; + + entity.AddEntityFlags(FLAG_KILLSWITCH); + if (!isFirstFrame) entity.AddEntityFlags(FLAG_REDUCE_GIBS); + if (entity.health <= 0) entity.Kill(EntityRef()); + else + { + entity.health = 0; + entity.isInvincible = false; + entity.ClearEntityFlags(FLAG_NO_STATUS_EFFECTS); + entity.TakeDamage(KILL_BUTTON_DAMAGE, 0, EntityRef(timer->parent), KILL_BUTTON_COUNTDOWN); + } + if (isFirstFrame) + { + Entity* poof = entity_spawn(ENTITY_EFFECT, EFFECT_POOF01, entity.pos, Random()); + poof->SetColor(KILL_BUTTON_POOF, -1, KILL_BUTTON_POOF_PRIORITY, false, true); + poof->Update(); + } + kills++; + isEmpty = false; + } + if (!isEmpty) timer->state = 0; + else if (++timer->state > KILL_BUTTON_EMPTY_FRAMES) timer->Remove(); +} + // 00984550 What a pressed plate does: a reward plate rewards or ambushes by its seed, the rail button raises the -// mineshaft's rail, the kill button kills the room's enemies and the output buttons fire their group. -// The kill button's timer and the output groups stop, as Game::ShakeScreen and Room::TriggerOutput are not here yet. +// mineshaft's rail, the kill button (with enemies left) rumbles and starts its timer for the nearest main player, and +// the output buttons fire their group. void GridEntity_PressurePlate::Reward() { if (variant == PLATE_REWARD) @@ -470,9 +538,18 @@ void GridEntity_PressurePlate::Reward() else plate_ambush_spawn(*this, rng); } else if (variant == PLATE_RAIL) g_game->raise_mineshaft_rail(); - else if (variant == PLATE_KILL && g_game->room->GetAliveEnemiesCount() > 0) - reconstruction_missing("GridEntity_PressurePlate::Reward 00984550: the kill button (Game::ShakeScreen, " - "pressure_plate_kill_enemies_timer_callback 00983f30)"); + else if (variant == PLATE_KILL) + { + Entity_Player* player = main_player_nearest(Position()); + if (!player) player = g_game->GetPlayer(0); + if (g_game->room->GetAliveEnemiesCount() < 1) return; + + grid_sound_play(SOUND_THUMBS_DOWN, {.frameDelay = KILL_BUTTON_SOUND_DELAY}); + grid_sound_play(SOUND_DEATH_CARD, {.frameDelay = KILL_BUTTON_SOUND_DELAY}); + game_shake_screen(KILL_BUTTON_SHAKE); + Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(&kill_button_tick), 1, UINT32_MAX, false); + timer->parent = player; + } else if (variant >= PLATE_OUTPUT_FIRST && variant <= PLATE_OUTPUT_LAST) g_game->room->TriggerOutput(variant - PLATE_OUTPUT_FIRST); } diff --git a/src/grid_entity_rock.cpp b/src/grid_entity_rock.cpp index fc5230c..cafae5d 100644 --- a/src/grid_entity_rock.cpp +++ b/src/grid_entity_rock.cpp @@ -23,8 +23,7 @@ #include #include -// The variant a big rock's frame is stored above, and its last frame. -constexpr int BIG_ROCK_VARIANT = 1000; +// A big rock's last frame. constexpr int BIG_ROCK_LAST_FRAME = 7; // The big rock frames by cell: two wide, two tall or four, and the neighbours PostInit joins, by bit. @@ -92,7 +91,6 @@ constexpr int SMALL_ROCK_ITEM = 90; constexpr uint32_t SMALL_ROCK_ODDS = 10; constexpr int TINTED_ROCK_DROPS = 2; constexpr int SS_ROCK_DROPS = 4; -constexpr uint32_t LUCKY_TOE_ODDS = 3; constexpr std::array TINTED_TRINKETS = {TRINKET_ACE_OF_SPADES, TRINKET_SAFETY_CAP, TRINKET_CHILDS_HEART, TRINKET_MATCH_STICK, TRINKET_RUSTED_KEY}; constexpr uint32_t TRINKET_ODDS = 33; @@ -162,7 +160,6 @@ constexpr float BUCKET_SHOT_FALLING_ACCEL = 0.9f; constexpr float BUCKET_SHOT_RISE = -5; constexpr float BUCKET_SHOT_RISE_RANGE = 24; constexpr int BUCKET_SPLASH_SUBTYPE = 2; -constexpr ColorMod BUCKET_SPLASH_COLOR = {{1, 1, 1, 1}, {5.5f, 7, 7, 1}, {0, 0, 0}}; constexpr float BUCKET_SLUDGE_SPEED = 4; constexpr float BUCKET_SLUDGE_SPEED_RANGE = 5; constexpr int BUCKET_SLUDGE_MIN = 4; @@ -1065,7 +1062,7 @@ static void bucket_spill(const RockRoll& roll) { Entity* splash = g_game->Spawn({.position = position, .subType = BUCKET_SPLASH_SUBTYPE, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); - splash->sprite.color = BUCKET_SPLASH_COLOR; + splash->sprite.color = WATER_SPLASH_COLOR; return; } float speed = random_unit() * BUCKET_SLUDGE_SPEED_RANGE + BUCKET_SLUDGE_SPEED; diff --git a/src/grid_entity_rock.h b/src/grid_entity_rock.h index 5e2a4ff..8ba4f40 100644 --- a/src/grid_entity_rock.h +++ b/src/grid_entity_rock.h @@ -4,6 +4,9 @@ #include #include +// The variant a big rock's frame is stored above. +constexpr int BIG_ROCK_VARIANT = 1000; + // A rock standing, broken, primed to blow (a bomb rock hit by an explosion) and cracked (a super secret rock). enum RockState : int { diff --git a/src/grid_entity_statue.cpp b/src/grid_entity_statue.cpp index 237fab9..722e759 100644 --- a/src/grid_entity_statue.cpp +++ b/src/grid_entity_statue.cpp @@ -49,7 +49,7 @@ static bool is_angel_unlocked() { Manager& manager = *g_manager; return manager.persistentGameData.achievements[ACHIEVEMENT_ANGEL_STATUES] || - (manager.state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge._id != 0 || g_game->isDebug)); + (manager.state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge.id != 0 || g_game->isDebug)); } // Picks the angel a statue breaks into: the one not met yet (alive or killed in the room), or the one whose key piece is diff --git a/src/grid_entity_tnt.cpp b/src/grid_entity_tnt.cpp index 82229c5..21eef1f 100644 --- a/src/grid_entity_tnt.cpp +++ b/src/grid_entity_tnt.cpp @@ -2,6 +2,8 @@ #include "entity_bomb.h" #include "entity_config.h" #include "entity_effect_combat.h" +#include "entity_pickup.h" +#include "entity_player.h" #include "game.h" #include "log.h" #include "manager.h" @@ -18,6 +20,8 @@ constexpr uint32_t WOOD_COUNT_EXTRA = 3; constexpr float WOOD_SPEED_MIN = 2; constexpr float WOOD_SPEED_EXTRA = 4; constexpr uint32_t TRINKET_DROP_ODDS = 100; +// GetRandomPickupVelocity's lobbed throw. +constexpr uint32_t PICKUP_VELOCITY_LOBBED = 1; // 0071f3f0 Throws the barrel's wooden pieces about. void wood_particles_spawn(const Vector& position) @@ -27,12 +31,23 @@ void wood_particles_spawn(const Vector& position) game_particles_spawn({.position = position, .speed = speed, .count = count, .variant = EFFECT_WOOD_PARTICLE}); } -// 0071f4b0 One blown barrel in 100, by its seed, leaves a trinket. -void trinket_drop_try(uint32_t seed) +// 0071f4b0 One blown barrel in 100, by its seed, throws a trinket from where it stood: a coin flip for Burnt Penny, +// else Match Stick, whichever is still in the pool. +void trinket_drop_try(uint32_t seed, const Vector& position) { RNG rng = {seed, 1, 5, 16}; - if (rng.Next() % TRINKET_DROP_ODDS == 0) - reconstruction_missing("GridEntity_TNT 0071f4b0: the trinket a blown barrel drops"); + if (rng.Next() % TRINKET_DROP_ODDS != 0) return; + + Game& game = *g_game; + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(position, nullptr, PICKUP_VELOCITY_LOBBED); + bool isPenny = (rng.Next() & 1) == 0 && game.itemPool.RemoveTrinket(TRINKET_BURNT_PENNY); + if (!isPenny && !game.itemPool.RemoveTrinket(TRINKET_MATCH_STICK)) return; + game.Spawn({.position = position, + .velocity = velocity, + .subType = isPenny ? TRINKET_BURNT_PENNY : TRINKET_MATCH_STICK, + .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, + .seed = Random()}); } // 0071ee90 Loads the barrel, blocking its cell, with the wooden pieces' sprite ready, and lights a standing one's @@ -72,7 +87,7 @@ void GridEntity_TNT::Update() explosion_damage({.position = position, .damageFlags = DAMAGE_EXPLOSION | DAMAGE_TNT, .damage = TNT_DAMAGE, .radius = TNT_RADIUS, .isLineCheck = false}); wood_particles_spawn(position); - trinket_drop_try(spawnSeed); + trinket_drop_try(spawnSeed, position); path_set(GRID_PATH_FREED); } diff --git a/src/grid_entity_tnt.h b/src/grid_entity_tnt.h index 111da9e..5c5f042 100644 --- a/src/grid_entity_tnt.h +++ b/src/grid_entity_tnt.h @@ -7,7 +7,7 @@ constexpr int TNT_STATE_READY = 3; constexpr int TNT_STATE_BLOWN = 4; void wood_particles_spawn(const Vector& position); -void trinket_drop_try(uint32_t seed); +void trinket_drop_try(uint32_t seed, const Vector& position); // Destruction (0070bdd0) is the default. // A TNT barrel on the grid (Lua's GRID_TNT): hurt in stages, it explodes. diff --git a/src/grid_entity_trap_door.cpp b/src/grid_entity_trap_door.cpp index e209148..ce06810 100644 --- a/src/grid_entity_trap_door.cpp +++ b/src/grid_entity_trap_door.cpp @@ -35,8 +35,6 @@ constexpr std::string_view ANIM_PLAYER_FALL = "Trapdoor"; // The stages (with a labyrinth counted as the next) whose exits are holes in the floor or the Void's portal. constexpr int STAGE_LAST_CHAPTER = 10; -constexpr int GAME_STATE_BACKWARDS_PATH_INIT = 47; - // Mother's boss room in the special rooms. constexpr int MINES_LAYER_HIDDEN = 1; diff --git a/src/hud.cpp b/src/hud.cpp index 6adbb3d..7274eb0 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -29,7 +29,6 @@ constexpr const char* HEARTS_ANM2 = "gfx/ui/ui_hearts.anm2"; constexpr const char* PICKUPS_ANM2 = "gfx/ui/hudpickups.anm2"; constexpr const char* CHARGE_BAR_ANM2 = "gfx/ui/ui_chargebar.anm2"; constexpr const char* CHARGE_BAR_SMALL_ANM2 = "gfx/ui/ui_chargebar_small.anm2"; -constexpr const char* CARDS_PILLS_ANM2 = "gfx/ui/ui_cardspills.anm2"; constexpr const char* STATS_ANM2 = "gfx/ui/hudstats.anm2"; constexpr const char* STATS_PANEL_ANM2 = "gfx/ui/hudstats2.anm2"; constexpr const char* FORTUNE_ANM2 = "gfx/ui/ui_FortunePaper.anm2"; @@ -88,7 +87,6 @@ constexpr float STATS_ALPHA = 0.5f; constexpr int STB_HOME = 35; constexpr int BOSS_GREAT_GIDEON = 83; constexpr uint32_t ROOM_FLAG_CLEAR = 1; -constexpr int ONLINE_HUD_COMPACT = 1; constexpr int ONLINE_HUD_HIDDEN = 2; constexpr int TEXT_BUFFER_SIZE = 16; constexpr int UTF16_HIGH_HALF_SHIFT = 16; @@ -1114,7 +1112,7 @@ void HUD::Render() Vector at = at_make((g_screenWidth - WAVE_BOX_WIDTH) * 0.5f + shake.x, (1 - options.hudOffset) * WAVE_SHIFT_Y + WAVE_TOP + shake.y); if (game.minimap.configs[MINIMAP_SIZE_LARGE].alpha > 0) at.y += WAVE_LINE; - if (game.dailyChallenge._id != 0) at.y += WAVE_LINE; + if (game.dailyChallenge.id != 0) at.y += WAVE_LINE; Vector box = at_make(WAVE_BOX_WIDTH, WAVE_BOX_HEIGHT); bossHealthBarRushImage->Render(KAGE::Graphics::color_quad_rect(at, box, WHITE), WHITE); @@ -1233,7 +1231,7 @@ void HUD::render_run_icons(Vector& cursor, Vector shake, float& statsX) char text[TEXT_BUFFER_SIZE]; bool isAchievementsOff = game.seedEffects.isCustomRun || game.seedEffects.AchievementUnlocksDisallowed() || Manager::AchievementUnlocksDisallowed() || game.isRerun || game.challenge != 0; - bool isDaily = game.dailyChallenge._id != 0; + bool isDaily = game.dailyChallenge.id != 0; bool isChallenge = isDaily || game.challenge != 0; bool isHard = game.difficulty == DIFFICULTY_HARD && !isChallenge; bool isGreed = !isHard && game.IsGreedMode() && !game.deathmatchManager.is_active(); @@ -1798,6 +1796,14 @@ Vector HUD::get_player_hud_position(int hudIndex, PlayerHudLayout layout) return at; } +// 009a6320 Where the corner showing a player draws in a layout, or the origin when no corner shows it. +Vector HUD::get_player_hud_position(Entity_Player* player, PlayerHudLayout layout) +{ + for (int i = 0; i < PLAYER_HUD_COUNT; i++) + if (playerHUD[i].player == player) return get_player_hud_position(i, layout); + return {}; +} + // 009a64f0 The corner showing a player, Esau's being Jacob's, or -1 (logged) for none or no player. int HUD::GetPlayerHudIndex(Entity_Player* player) { diff --git a/src/hud.h b/src/hud.h index f8d20c1..7d4c5ae 100644 --- a/src/hud.h +++ b/src/hud.h @@ -17,6 +17,12 @@ struct RNG; +// The pocket items' sheet: its cards' fronts by card id, and the animation a card pickup shows on the HUD. +constexpr const char* CARDS_PILLS_ANM2 = "gfx/ui/ui_cardspills.anm2"; +constexpr const char* ANIMATION_CARD_FRONTS = "CardFronts"; +constexpr const char* ANIMATION_HUD = "HUD"; +// The online HUD layout that packs the players closer. +constexpr int ONLINE_HUD_COMPACT = 1; constexpr int MESSAGE_STACK_COUNT = 6; constexpr int HISTORY_PLAYER_COUNT = 2; constexpr float BOSS_BAR_HIDDEN = -1; @@ -210,6 +216,7 @@ public: void update_hud_offset(); Vector get_player_hud_position(int hudIndex, PlayerHudLayout layout); + Vector get_player_hud_position(Entity_Player* player, PlayerHudLayout layout); int GetPlayerHudIndex(Entity_Player* player); PlayerHudLayout GetPlayerHUDLayout(int playerHudIndex, Entity_Player* player); int count_player_huds(); diff --git a/src/info_display.cpp b/src/info_display.cpp index 43e7f7f..d2ad101 100644 --- a/src/info_display.cpp +++ b/src/info_display.cpp @@ -5,6 +5,7 @@ #include "manager.h" #include "data.h" #include +#include #include #include @@ -66,6 +67,15 @@ static std::optional group_find(DataNode root, std::string_view tag) return std::nullopt; } +// The stats a panel lists changes of, and how it formats a change up or down. +constexpr const char* STAT_NAMES[PANEL_STAT_COUNT] = {" Speed", " Tears", " Damage", " Range", " Shot Speed", " Luck"}; +constexpr const char* STAT_UP_FORMAT = "+%.2f"; +constexpr const char* STAT_DOWN_FORMAT = "%.2f"; +constexpr size_t STAT_LINE_SIZE = 256; +constexpr const char* FORM_SEPARATOR = " "; +constexpr uint32_t PREVIEW_CACHE_FLAGS = + CACHE_DAMAGE | CACHE_FIREDELAY | CACHE_SHOTSPEED | CACHE_RANGE | CACHE_SPEED | CACHE_LUCK; + // A line that always applies. static InfoDisplayText line_make(std::string text) { @@ -333,22 +343,96 @@ int InfoDisplayEntry::count_lines(Entity_Player& player, uint32_t subtype) { if (id == 0) return (int)lines.size(); - int count = 0; + int count = (int)statLines.size(); for (std::unique_ptr& form : g_manager->itemConfig.playerForms) - { - if (!form) continue; - if (form->tags == 0) - { - bool isNecromancerCollectible = id == COLLECTIBLE_NECRONOMICON || id == COLLECTIBLE_MISSING_PAGE_2; - bool isNecromancerItem = (type == INFO_DISPLAY_COLLECTIBLE && isNecromancerCollectible) || - (type == INFO_DISPLAY_TRINKET && id == TRINKET_MISSING_PAGE); - count += form->id == PLAYER_FORM_NECROMANCER && isNecromancerItem; - continue; - } - count += (type == INFO_DISPLAY_COLLECTIBLE && ItemConfig::is_collectible_tagged(id, form->tags)) || - (type == INFO_DISPLAY_TRINKET && ItemConfig::is_trinket_tagged(id, form->tags)); - } - + if (form) count += is_form_item(*form); for (size_t index = 0; index < lines.size(); index++) count += is_line_visible(index, player, subtype); return count; } + +// Whether the item counts toward a transformation: by its tags, or as a book of the Necromancer's untagged form. +bool InfoDisplayEntry::is_form_item(const ItemConfig_PlayerForm& form) +{ + if (form.tags != 0) + return (type == INFO_DISPLAY_COLLECTIBLE && ItemConfig::is_collectible_tagged(id, form.tags)) || + (type == INFO_DISPLAY_TRINKET && ItemConfig::is_trinket_tagged(id, form.tags)); + + bool isNecromancerCollectible = id == COLLECTIBLE_NECRONOMICON || id == COLLECTIBLE_MISSING_PAGE_2; + bool isNecromancerItem = (type == INFO_DISPLAY_COLLECTIBLE && isNecromancerCollectible) || + (type == INFO_DISPLAY_TRINKET && id == TRINKET_MISSING_PAGE); + return form.id == PLAYER_FORM_NECROMANCER && isNecromancerItem; +} + +// How many of a transformation's items a player has, none for no player or a form past the player's slots. +int form_progress_get(const ItemConfig_PlayerForm& form, const Entity_Player* player) +{ + return player && form.id < PLAYER_FORM_SLOTS ? player->playerForms[form.id] : 0; +} + +// A transformation's line in a panel: its name and a count of the items it takes. +std::string form_line_get(const ItemConfig_PlayerForm& form, int progress) +{ + std::string name(g_manager->stringTable.translate(form.name)); + return name + FORM_SEPARATOR + std::to_string(progress) + "/" + std::to_string(FORM_GOAL); +} + +// (0084dea0, 0084e200) Lists the stat changes taking (or losing) the item makes for a player, measured by having the +// player preview it. The default entry (id 0) lists none. +void InfoDisplayEntry::stats_set(Entity_Player* statsPlayer, PreviewMode mode, bool isGolden) +{ + if (id == 0) return; + + player = statsPlayer; + if (type == INFO_DISPLAY_COLLECTIBLE) collectible_preview(mode); + else if (type == INFO_DISPLAY_TRINKET) trinket_preview(mode, isGolden); + statLines.clear(); + for (int i = 0; i < PANEL_STAT_COUNT; i++) stat_line_add(STAT_NAMES[i], stats[i].change); +} + +// 0084dc00 Adds a line showing a stat's change, green and signed when up, red when down, none when unchanged. +void InfoDisplayEntry::stat_line_add(std::string_view statName, float change) +{ + char text[STAT_LINE_SIZE]; + + if (change == 0) return; + std::snprintf(text, sizeof(text), change < 0 ? STAT_DOWN_FORMAT : STAT_UP_FORMAT, change); + statLines.push_back(line_make(text + std::string(statName))); +} + +// 0084e9d0 Takes the player's six stats, a change animating when isAnimated (the value after the preview). +void InfoDisplayEntry::stats_snapshot(bool isAnimated) +{ + if (!player) return; + for (int i = 0; i < PANEL_STAT_COUNT; i++) stats[i].set(player_stat_get(*player, (StatHudStat)i), isAnimated); +} + +// Takes the player's stats, then again with the item previewed as taken or lost (a preview field set to it), then +// clears the preview and has the stats evaluated back. +template static void stats_preview(InfoDisplayEntry& entry, PreviewMode mode, T& preview, T item) +{ + Entity_Player& player = *entry.player; + + entry.stats_snapshot(false); + preview = item; + player.isPreviewAdded = mode == PREVIEW_ADDED; + player.cacheFlags |= PREVIEW_CACHE_FLAGS; + player.EvaluateItems(); + entry.stats_snapshot(true); + preview = 0; + player.isPreviewAdded = true; + player.cacheFlags |= PREVIEW_CACHE_FLAGS; + player.EvaluateItems(); +} + +// 0084ea90 Measures the stat changes of the collectible. +void InfoDisplayEntry::collectible_preview(PreviewMode mode) +{ + if (player) stats_preview(*this, mode, player->previewCollectible, id); +} + +// 0084eb10 Measures the stat changes of the trinket, golden or not. +void InfoDisplayEntry::trinket_preview(PreviewMode mode, bool isGolden) +{ + uint32_t trinket = isGolden ? (uint32_t)id | TRINKET_GOLDEN_FLAG : (uint32_t)id; + if (player) stats_preview(*this, mode, player->previewTrinket, trinket); +} diff --git a/src/info_display.h b/src/info_display.h index 1de3aae..1a9a207 100644 --- a/src/info_display.h +++ b/src/info_display.h @@ -1,6 +1,8 @@ #pragma once #include "classes.h" +#include "stat_hud.h" +#include #include #include #include @@ -8,9 +10,22 @@ #include struct ItemConfig_Item; +struct ItemConfig_PlayerForm; struct ModEntry; struct PocketItemConfig; +// The stats a panel shows changes of: speed, tears, damage, range, shot speed and luck. +constexpr int PANEL_STAT_COUNT = STAT_LUCK + 1; +// The items of a transformation a panel counts toward. +constexpr int FORM_GOAL = 3; + +// Whether a panel's stat changes come from taking its item (the HUD's pickups) or losing it (the pause screen's). +enum PreviewMode +{ + PREVIEW_REMOVED, + PREVIEW_ADDED +}; + // What an InfoDisplayEntry describes, as the game numbers it. // Cards the item config adds without an info_display.xml entry are filed as collectibles, as the game does. enum InfoDisplayType : int @@ -51,17 +66,30 @@ struct InfoDisplayText InfoDisplayTag tag = INFO_DISPLAY_TAG_ANY; }; -// The info panel of a collectible, trinket, pill or card: its name and its lines, the stat lines first. +// The info panel of a collectible, trinket, pill or card: its name and its lines, the stat lines first, then the +// stat changes taking it would make for a player (the StatsPanel), and the lines the HUD adds for the pickup shown +// (Spindown Dice's). Unidentified pills and cards show no name. // Construction, copies and assignment (0084dad0, 008568a0, 0084f2e0) are the defaults. struct InfoDisplayEntry { std::string name; + std::array stats{}; + std::vector extraLines; std::vector lines; + std::vector statLines; + Entity_Player* player = nullptr; InfoDisplayType type = INFO_DISPLAY_COLLECTIBLE; int id = 0; + bool isUnidentified = false; int count_lines(Entity_Player& player, uint32_t pickupFlags); bool is_line_visible(size_t lineIndex, Entity_Player& player, uint32_t pickupFlags); + bool is_form_item(const ItemConfig_PlayerForm& form); + void stats_set(Entity_Player* statsPlayer, PreviewMode mode, bool isGolden); + void stats_snapshot(bool isAnimated); + void stat_line_add(std::string_view statName, float change); + void collectible_preview(PreviewMode mode); + void trinket_preview(PreviewMode mode, bool isGolden); }; // The item info panels the HUD and pause screen show, from info_display.xml and the item config, by kind and id. @@ -85,3 +113,6 @@ public: InfoDisplayEntry& get_card(int id); static void describe_pickup_stats(ItemConfig_Item& item, InfoDisplayEntry& entry); }; + +int form_progress_get(const ItemConfig_PlayerForm& form, const Entity_Player* player); +std::string form_line_get(const ItemConfig_PlayerForm& form, int progress); diff --git a/src/item_config.cpp b/src/item_config.cpp index acc2e63..755597b 100644 --- a/src/item_config.cpp +++ b/src/item_config.cpp @@ -38,7 +38,6 @@ constexpr int SPECIAL_CHARGE_SEGMENTS_LAST = 12; // Ids and values the availability and charge rules name. constexpr int COLLECTIBLE_SACRED_ORB = 691; -constexpr int COLLECTIBLE_VANISHING_TWIN = 697; constexpr unsigned int SPECIAL_DAILY_BANNED_SET = 52; constexpr uint32_t STAGE_VANISHING_TWIN_LAST = 6; constexpr int QUALITY_LOW_LAST = 1; @@ -485,13 +484,13 @@ bool ItemConfig_Item::IsAvailableEx(uint32_t checks) { if (game.challenge == CHALLENGE_ONANS_STREAK && isListed(WEAPON_COLLECTIBLES)) return false; if (game.seedEffects.HasSeedEffect(SEED_G_FUEL) && isListed(WEAPON_COLLECTIBLES)) return false; - if (game.dailyChallenge._specialDailyId == SPECIAL_DAILY_BANNED_SET && + if (game.dailyChallenge.specialDailyId == SPECIAL_DAILY_BANNED_SET && isListed(SPECIAL_DAILY_BANNED_COLLECTIBLES)) return false; } if (IsTrinket() && game.challenge == CHALLENGE_PICA_RUN && id == TRINKET_BUTTER) return false; if (game.challenge != 0 && HasTags(TAG_NO_CHALLENGE)) return false; - if (game.dailyChallenge._id != 0 && HasTags(TAG_NO_DAILY)) return false; + if (game.dailyChallenge.id != 0 && HasTags(TAG_NO_DAILY)) return false; if (game.IsGreedMode() && HasTags(TAG_NO_GREED)) return false; } diff --git a/src/item_info_hud.cpp b/src/item_info_hud.cpp index 99e0180..b419d54 100644 --- a/src/item_info_hud.cpp +++ b/src/item_info_hud.cpp @@ -1,19 +1,125 @@ #include "item_info_hud.h" +#include "entity_config.h" +#include "entity_pickup.h" #include "entity_player.h" #include "game.h" -#include "log.h" +#include "info_display.h" +#include "item_pool.h" #include "manager.h" +#include "menu_manager.h" #include "persistent_game_data.h" +#include "popups.h" +#include "render_passes.h" #include "room.h" +#include "room_path.h" #include #include +#include constexpr const char* ITEM_INFO_FONT = "font/TeamMeatEx/TeamMeatEx12.fnt"; constexpr const char* CHARGE_ICONS_ANM2 = "gfx/ui/ui_charge_icons.anm2"; constexpr const char* MINIMAP_ICONS_ANM2 = "gfx/ui/minimap_icons.anm2"; constexpr const char* ANIMATION_CHARGE_ICON = "ChargeIcon"; +constexpr const char* UNIDENTIFIED_KEY = "##GAME###ITEM_INFO_UNIDENTIFIED"; +constexpr const char* SPINDOWN_TEXT = "Spins down into SALE_KNOWN_CARDS = {CARD_CREDIT, CARD_HUMANITY, CARD_GET_OUT_OF_JAIL, CARD_HOLY, + CARD_WILD, CARD_EMERGENCY_CONTACT, CARD_DICE_SHARD, + CARD_CRACKED_KEY, RUNE_BLACK}; +struct CardKind +{ + int below = 0; + const char* key = nullptr; +}; +constexpr std::array CARD_KINDS = {{{23, "#ITEM_INFO_UNIDENTIFIED_TAROT_CARD"}, + {32, "#ITEM_INFO_UNIDENTIFIED_PLAYING_CARD"}, + {42, "#ITEM_INFO_UNIDENTIFIED_RUNE"}, + {55, "#ITEM_INFO_UNIDENTIFIED_CARD"}, + {78, "#ITEM_INFO_UNIDENTIFIED_TAROT_CARD"}, + {81, "#ITEM_INFO_UNIDENTIFIED_CARD"}}}; + +// The minimap icon of each item pool: its animation and frame (none for the animation's own), or nothing. +struct PoolIcon +{ + const char* animation = nullptr; + int frame = -1; +}; +constexpr std::array POOL_ICONS = {{{"IconTreasureRoom"}, + {"IconShop"}, + {"IconBoss"}, + {"IconDevilRoom"}, + {"IconAngelRoom"}, + {"IconSecretRoom"}, + {"IconLibrary"}, + {}, + {"ItemPoolChests", 0}, + {"ItemPoolChests", 1}, + {"IconBeggar", 0}, + {"IconBeggar", 2}, + {"IconCurseRoom"}, + {"IconBeggar", 3}, + {"IconBeggar", 5}, + {}, + {"IconTreasureRoomGreed"}, + {"IconBoss"}, + {"IconShop"}, + {"IconDevilRoom"}, + {"IconAngelRoom"}, + {"IconCurseRoom"}, + {"IconSecretRoom"}, + {"IconSlot", 5}, + {"IconUltraSecretRoom"}, + {"IconBeggar", 4}, + {"IconPlanetarium"}, + {}, + {}, + {"ItemPoolChests", 2}, + {"IconBeggar", 1}}}; +// The pools shown in either mode, then those shown only outside Greed mode and only in it. +constexpr std::array POOLS_SHOWN = {POOL_GOLDEN_CHEST, POOL_RED_CHEST, POOL_WOODEN_CHEST, POOL_BEGGAR, + POOL_DEMON_BEGGAR, POOL_KEY_MASTER, POOL_BATTERY_BUM, POOL_BOMB_BUM, + POOL_ROTTEN_BEGGAR, POOL_ULTRA_SECRET, POOL_CRANE_GAME}; +constexpr std::array POOLS_SHOWN_NORMAL = {POOL_TREASURE, POOL_SHOP, POOL_BOSS, POOL_DEVIL, POOL_ANGEL, + POOL_SECRET, POOL_LIBRARY, POOL_CURSE, POOL_PLANETARIUM}; +constexpr std::array POOLS_SHOWN_GREED = {POOL_TREASURE, POOL_GREED_TREASURE, POOL_GREED_BOSS, + POOL_GREED_SHOP, POOL_GREED_DEVIL, POOL_GREED_ANGEL, + POOL_GREED_CURSE, POOL_GREED_SECRET}; // 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. @@ -48,35 +154,438 @@ void ItemInfoHUD::reset() if (text.icons) text.icons->images.clear(); } +// Whether a pickup can be described: a pill, card or trinket, or a collectible not hidden behind a question mark. +static bool is_describable(Entity* entity) +{ + if (entity->type != ENTITY_PICKUP) return false; + if (entity->variant == PICKUP_PILL || entity->variant == PICKUP_TAROTCARD || entity->variant == PICKUP_TRINKET) + return true; + if (entity->variant != PICKUP_COLLECTIBLE || entity->subtype == 0) return false; + LayerState* layer = entity->sprite.GetLayer(1); + return !layer || layer->spriteSheetPath != QUESTION_MARK_GFX; +} + // 0083c8d0 Describes the pickup the first local player stands nearest to, while the display is on (unlocked, or in a -// daily or debug run), outside April's Fool and in a cleared room. Otherwise it forgets it. -// Finding and describing the pickup waits for the pickups' and the popups' takeovers, and with it the panel's -// is_pickup_known, is_collectible_seen and the popup's measure and render callback. +// daily or debug run), outside April's Fool and in a cleared room. Otherwise, or with no such pickup, it forgets it. +// The popup opens for a new pickup and keeps beside the player. void ItemInfoHUD::Update() { Game& game = *g_game; - bool isUnlocked = g_manager->persistentGameData.Unlocked(ACHIEVEMENT_ITEM_INFO); + Manager& manager = *g_manager; + bool isAllowed = manager.persistentGameData.Unlocked(ACHIEVEMENT_ITEM_INFO) || + (manager.state == MANAGER_STATE_GAME && (game.dailyChallenge.id != 0 || game.isDebug)); bool isCleared = game.room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR; - bool isShown = isUnlocked && game.challenge != CHALLENGE_APRILS_FOOL && - g_manager->optionsConfig.isItemInfoDisplayEnabled && isCleared; + bool isShown = isAllowed && game.challenge != CHALLENGE_APRILS_FOOL && + manager.optionsConfig.isItemInfoDisplayEnabled && isCleared; + Entity_Player* player = isShown ? game.playerManager.get_first_local_main_player() : nullptr; - if (!isShown) reset(); - else if (game.playerManager.get_first_local_main_player()) - reconstruction_missing("ItemInfoHUD::Update 0083c8d0: the nearest pickup's description"); - if (pickup && popupId == POPUP_NONE) - reconstruction_missing("ItemInfoHUD::Update 0083c8d0: the description's popup"); + if (isShown && player) + { + Entity* nearest = nullptr; + float nearestDistance = NEAREST_DISTANCE_SQUARED; + for (Entity* entity : game.room->entityList.updateEL) + { + if (!is_describable(entity)) continue; + float distance = vector_length_squared(vector_sub(player->pos, entity->pos)); + if (distance < nearestDistance) + { + nearestDistance = distance; + nearest = entity; + } + } + if (nearest && nearest->subtype != 0) pickup_describe(*static_cast(nearest), *player); + else reset(); + } + else if (!isShown) reset(); + + if (pickup && popupId == POPUP_NONE) popup_open(); + popup_place(); } -// 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) +// Describes the nearest pickup, unless it is the one described: a collectible with its stat changes (and where +// Spindown Dice would turn it), a trinket golden or not, the effect of a pill, a card. A new pickup closes the popup. +// A card the config lacks is not described. Whether the pickup is identified updates every frame. +void ItemInfoHUD::pickup_describe(Entity_Pickup& nearest, Entity_Player& player) +{ + Manager& manager = *g_manager; + ItemConfig& items = manager.itemConfig; + InfoDisplay& display = manager.infoDisplay; + int pillEffect = g_game->itemPool.GetPillEffect(nearest.subtype, &player); + bool isSame = pickup == &nearest && entry; + if (isSame && nearest.variant == PICKUP_COLLECTIBLE) isSame = (int)nearest.subtype == entry->id; + if (isSame && nearest.variant == PICKUP_TRINKET) isSame = (int)(nearest.subtype & TRINKET_ID_MASK) == entry->id; + if (isSame && nearest.variant == PICKUP_PILL) isSame = pillEffect == entry->id; + + if (!isSame) + { + pickup = &nearest; + auto spriteLoad = [&](EntityConfig_Entity* config) + { + if (!config) return iconSprite.Reset(); + iconSprite.Load(config->anm2Path, GRAPHICS_LOAD); + iconSprite.Play(ANIMATION_IDLE); + }; + auto imageLoad = [&](ItemConfig_Item* item) + { + if (item) itemImage = Manager::LoadImage(item->gfxFilename); + else itemImage.reset(); + iconSprite.Reset(); + }; + + switch (nearest.variant) + { + case PICKUP_COLLECTIBLE: + { + entry = &display.get_collectible((int)nearest.subtype); + entry->stats_set(&player, PREVIEW_ADDED, false); + entry->extraLines.clear(); + bool isSpindown = player.HasCollectible(COLLECTIBLE_SPINDOWN_DICE) && + nearest.optionsPickupIndex == 0 && nearest.CanReroll(); + if (isSpindown) + { + int rolls = player.HasCollectible(COLLECTIBLE_CAR_BATTERY) ? SPINDOWN_ROLLS_CAR_BATTERY : 1; + int id = (int)nearest.subtype; + for (int rolled = 0; rolled < rolls && --id >= 1;) + { + ItemConfig_Item* item = items.GetCollectible(id); + rolled += item && item->IsAvailableEx(AVAILABLE_RUN_RULES | AVAILABLE_UNLOCKED); + } + InfoDisplayText line; + line.text = SPINDOWN_TEXT + std::to_string(id) + ">"; + if (id > 0) entry->extraLines.push_back(line); + } + imageLoad(items.GetCollectible((int)nearest.subtype)); + break; + } + case PICKUP_TRINKET: + entry = &display.get_trinket(nearest.subtype); + entry->stats_set(&player, PREVIEW_ADDED, nearest.subtype & TRINKET_GOLDEN_FLAG); + imageLoad(items.GetTrinket(nearest.subtype)); + break; + case PICKUP_PILL: + entry = &display.get_pill((uint32_t)pillEffect); + spriteLoad(manager.entityConfig.GetEntity(ENTITY_PICKUP, PICKUP_PILL, (int)nearest.subtype)); + itemImage.reset(); + break; + case PICKUP_TAROTCARD: + { + entry = &display.get_card((int)nearest.subtype); + ItemConfig_Card* card = items.GetCard((int)nearest.subtype); + if (!card) + { + pickup = nullptr; + entry = nullptr; + break; + } + spriteLoad(manager.entityConfig.GetEntity(ENTITY_PICKUP, PICKUP_TAROTCARD, card->pickupSubtype)); + itemImage.reset(); + break; + } + } + manager.popupQueue.close(popupId, POPUP_NONE); + popupId = POPUP_NONE; + } + if (entry) entry->isUnidentified = !is_pickup_known(*pickup); +} + +// The popup's render callback (00840370): draws the panel's lines over the popup's frame at its fade. +static void popup_render(Popup& popup, void* context) +{ + ItemInfoHUD& info = *static_cast(context); + Vector center = popup.get_center(); + Vector size = popup.get_size(); + ItemInfoBox box; + Vector extent{}; + + box.position = vector_make(center.x - size.x * HALF - POPUP_TEXT_INSET_X, + center.y - size.y * HALF - POPUP_TEXT_INSET_Y); + box.width = (int)(uint32_t)info.panelSize.x; + box.color._alpha = popup.alpha.get(); + info.render_info(ITEM_INFO_RENDER, box, extent); +} + +// Opens the popup for the pickup, sized to the panel (or to fit "???" and "unidentified" for an unseen collectible), +// fading in on the beige frame behind the HUD. +void ItemInfoHUD::popup_open() +{ + panelSize = measure(); + MessagePopup desc(&g_manager->font1_TeamMeatEx10, nullptr, nullptr, + vector_make(panelSize.x, panelSize.y - POPUP_HEIGHT_TRIM)); + desc.maxWidthFraction = POPUP_WRAP_WIDTH / g_screenWidth; + desc.flags = 0; + desc.animation = POPUP_ANIMATION_FADE; + desc.animationSpeed = POPUP_FADE_SPEED; + desc.layer = POPUP_LAYER; + desc.style = POPUP_STYLE_BEIGE; + desc.color = POPUP_COLOR; + desc.renderCallback = popup_render; + desc.renderContext = this; + if (!is_collectible_seen(*pickup)) + { + PopupLine line; + line.color = WHITE; + desc.paddingX = POPUP_UNSEEN_PADDING_X; + desc.paddingY = POPUP_UNSEEN_PADDING_Y; + for (const char* text : {ITEM_INFO_UNKNOWN, UNIDENTIFIED_KEY}) + { + line.text = text; + desc.line_add(line); + } + desc.size = vector_make(POPUP_SIZE_FIT, POPUP_SIZE_FIT); + } + popupId = g_manager->popupQueue.push(desc); +} + +// Keeps the popup on the screen half away from the first local player, or closes it once the player crosses 20 past +// the middle to its side. With no player it sits centered. +void ItemInfoHUD::popup_place() +{ + Popup* popup = popupId == POPUP_NONE ? nullptr : g_manager->popupQueue.find(popupId); + if (!popup) return; + + Entity_Player* player = g_game->playerManager.get_first_local_main_player(); + float halfWidth = g_screenWidth * HALF; + float playerX = 0; + Vector offset{}; + if (player) + { + playerX = render_position_get(player->pos, RENDER_SNAPPED).x + g_game->room->renderScrollOffset.x; + bool isLeft = playerX <= halfWidth; + float side = isLeft ? -1 : 1; + Vector size = popup->get_size(); + offset = vector_make((isLeft ? POPUP_LEFT_X : POPUP_RIGHT_X) - halfWidth * side + side * size.x * HALF, + -g_screenHeight * HALF + size.y * HALF + POPUP_TOP); + } + + float shownX = popup->desc.offset.x; + bool isCrossed = (shownX < 0 && playerX < halfWidth - POPUP_SIDE_MARGIN) || + (shownX > 0 && halfWidth + POPUP_SIDE_MARGIN < playerX); + if (!isCrossed) return void(popup->desc.offset = offset); + g_manager->popupQueue.close(popupId, POPUP_NONE); + popupId = POPUP_NONE; +} + +// 00840250 The panel's size: the right and bottom its lines reach, laid out 134 wide from the origin. +Vector ItemInfoHUD::measure() +{ + ItemInfoBox box; + Vector extent{}; + + box.width = MEASURE_WIDTH; + render_info(ITEM_INFO_MEASURE, box, extent); + return extent; +} + +// (008402f0, 008404a0) Measures or draws a line at the box's position, wrapping at the box's right edge, and moves +// the box below it. Measuring grows the extent to the line's right and bottom. +void ItemInfoHUD::line_add(ItemInfoPass pass, std::string_view line, ItemInfoBox& box, Vector& extent) +{ + int maxWidth = (int)box.start.x + box.width - (int)box.position.x; + + if (pass == ITEM_INFO_RENDER) + { + box.position.y += text.Render(line, box.position, box.color, box.scale, maxWidth).y; + return; + } + Vector size = text.measure(line, maxWidth, box.scale); + extent.x = std::max(extent.x, size.x + box.position.x); + extent.y = std::max(extent.y, size.y + box.position.y); + box.position.y += size.y; +} + +// The text an unidentified pickup shows: its pill or card kind, or "???". None for a card past the souls' range. +static std::string unidentified_text(const InfoDisplayEntry& entry) +{ + StringTable& strings = g_manager->stringTable; + + if (entry.type == INFO_DISPLAY_PILL) return std::string(strings.translate(ITEM_INFO_UNIDENTIFIED_PILL)); + if (entry.type != INFO_DISPLAY_CARD) return ITEM_INFO_UNKNOWN; + for (const CardKind& kind : CARD_KINDS) + if (entry.id < kind.below) return std::string(strings.translate(kind.key)); + return {}; +} + +// 0083eae0 Measures or draws the panel of an item seen before: its image or sprite (a Monkey Paw's first frame), its +// charge icon, its name (raised a little per extra line) or what it is when unidentified, then bulleted the +// transformations it counts toward (with the player's progress), the HUD's lines, the stat changes and the visible +// lines, and the pools a collectible comes from. Measuring makes room for the charge icon and the pool icons row. +// The original reads a missing first local player. Here it counts no transformation progress and shows no lines. +void ItemInfoHUD::render_info(ItemInfoPass pass, const ItemInfoBox& box, Vector& extent) +{ + if (!entry || !is_collectible_seen(*pickup)) return; + + Entity_Player* player = g_game->playerManager.get_first_local_main_player(); + ItemInfoBox line = box; + auto bulletRender = [&]() + { + if (pass != ITEM_INFO_RENDER) return; + Vector bullet = vector_make(line.position.x - ITEM_INFO_BULLET_INDENT, line.position.y); + text.Render(ITEM_INFO_BULLET, bullet, box.color, ITEM_INFO_BODY_SCALE); + }; + auto linesAdd = [&](const std::vector& lines) + { + for (const InfoDisplayText& added : lines) + { + bulletRender(); + line_add(pass, added.text, line, extent); + line.position.y += PANEL_LINE_GAP; + } + }; + + line.start = box.position; + ColorMod tint = {{1, 1, 1, box.color._alpha}, {0, 0, 0, 0}, {0, 0, 0}}; + if (pass == ITEM_INFO_RENDER && !itemImage && iconSprite.isLoaded) + { + iconSprite.color = tint; + iconSprite.Render({vector_make(box.position.x + ICON_OFFSET_X, box.position.y + ICON_OFFSET_Y)}); + } + else if (pass == ITEM_INFO_RENDER && itemImage) + { + bool isMonkeyPaw = entry->type == INFO_DISPLAY_TRINKET && entry->id == TRINKET_MONKEY_PAW; + Vector iconSize = vector_make(ITEM_INFO_IMAGE_SIZE, ITEM_INFO_IMAGE_SIZE); + Vector sourceSize = isMonkeyPaw ? iconSize : vector_make((float)itemImage->width, (float)itemImage->height); + apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, *itemImage); + itemImage->Render(KAGE::Graphics::source_quad_rect({}, sourceSize), + KAGE::Graphics::color_quad_rect(box.position, iconSize, WHITE), + kcolor_rgba(1, 1, 1, box.color._alpha)); + } + + line.scale = ITEM_INFO_TITLE_SCALE; + line.position = vector_make(line.position.x + ITEM_INFO_TITLE_X, line.position.y + TITLE_OFFSET_Y); + float titleY = line.position.y; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(entry->id); + bool isActive = entry->type == INFO_DISPLAY_COLLECTIBLE && item && item->type == ITEM_ACTIVE; + if (isActive && pass == ITEM_INFO_RENDER && player) + { + charge_icon_frame_set(chargeIconSprite, entry->id, *player); + chargeIconSprite.color = tint; + chargeIconSprite.Render({vector_make(box.position.x + (float)box.width - CHARGE_ICON_INSET, + box.position.y + CHARGE_ICON_OFFSET_Y)}); + } + if (!entry->isUnidentified) + { + int nameWidth = line.width - (int)(line.position.x - line.start.x); + Vector nameSize = text.measure(entry->name, nameWidth, ITEM_INFO_TITLE_SCALE); + float lineHeight = (float)text.font.lineHeight * line.scale; + line.position.y -= std::max(nameSize.y / lineHeight - 1, 0.0f) * lineHeight * TITLE_RISE; + line_add(pass, entry->name, line, extent); + if (pass == ITEM_INFO_MEASURE) extent.x += TITLE_MARGIN; + } + else if (std::string kind = unidentified_text(*entry); !kind.empty()) line_add(pass, kind, line, extent); + + line.position = vector_make(box.position.x + BODY_OFFSET_X, titleY + BODY_OFFSET_Y); + line.scale = ITEM_INFO_BODY_SCALE; + if (entry->isUnidentified) + { + bulletRender(); + line_add(pass, ITEM_INFO_UNKNOWN, line, extent); + return; + } + + KColor accent = kcolor_argb(ITEM_INFO_FORM_ARGB); + line.color = kcolor_rgba(box.color._red * accent._red, box.color._green * accent._green, + box.color._blue * accent._blue, box.color._alpha * accent._alpha); + for (std::unique_ptr& form : g_manager->itemConfig.playerForms) + { + if (!form || !entry->is_form_item(*form)) continue; + InfoDisplayText formLine; + formLine.text = form_line_get(*form, std::min(form_progress_get(*form, player), FORM_GOAL)); + linesAdd({formLine}); + } + line.color = box.color; + linesAdd(entry->extraLines); + linesAdd(entry->statLines); + for (size_t i = 0; player && i < entry->lines.size(); i++) + if (entry->is_line_visible(i, *player, pickup->subtype)) linesAdd({entry->lines[i]}); + + if (entry->type != INFO_DISPLAY_COLLECTIBLE) return; + if (pass == ITEM_INFO_MEASURE) + { + if (!item_pools_shown(entry->id).empty()) extent.y += POOL_ICONS_HEIGHT; + return; + } + float poolsY = line.position.y + POOL_ICONS_GAP; + pool_icons_render(vector_make(box.position.x + (float)box.width * HALF, poolsY), + kcolor_rgba(1, 1, 1, line.color._alpha)); +} + +// The pools a collectible comes from that the panel shows icons of: Greed mode's own pools in Greed mode, the others +// outside it, and the chests, beggars, Ultra Secret Room and crane game in both. +std::vector item_pools_shown(int collectibleId) +{ + std::vector pools = g_game->itemPool.GetItemPoolsForCollectible(collectibleId); + bool isGreed = g_game->IsGreedMode(); + auto isShown = [&](int pool) + { + auto isIn = [pool](const auto& list) { return std::ranges::find(list, pool) != list.end(); }; + return isIn(POOLS_SHOWN) || (isGreed ? isIn(POOLS_SHOWN_GREED) : isIn(POOLS_SHOWN_NORMAL)); + }; + + std::erase_if(pools, [&](int pool) { return !isShown(pool); }); + return pools; +} + +// 0083d8c0 Draws the minimap icon of each pool the collectible comes from, 16 apart, centered on a position and tinted. +void ItemInfoHUD::pool_icons_render(Vector position, KColor color) +{ + std::vector pools = item_pools_shown(entry->id); + Vector at = position; + + if (pools.size() > 1) at.x -= ((float)pools.size() - 1) * ITEM_INFO_POOL_SPACING * HALF; + for (int pool : pools) + { + pool_icon_play(mapIconsSprite, pool); + mapIconsSprite.color = {{color._red, color._green, color._blue, color._alpha}, {0, 0, 0, 0}, {0, 0, 0}}; + if (mapIconsSprite.isLoaded) mapIconsSprite.Render({at}); + at.x += ITEM_INFO_POOL_SPACING; + } +} + +// Plays a pool's minimap icon on a minimap icons sprite: its animation at its frame, if it has one. +void pool_icon_play(ANM2& sprite, int pool) +{ + const PoolIcon& icon = POOL_ICONS[pool]; + + if (!icon.animation) return; + sprite.Play(icon.animation); + if (icon.frame >= 0 && sprite.animState.animData) sprite.animState.SetFrameFloat((float)icon.frame); +} + +// 0083d760 Whether the pickup's item was seen before: only a vanilla collectible never collected is not. +bool ItemInfoHUD::is_collectible_seen(Entity_Pickup& pickup) +{ + int id = (int)pickup.subtype; + bool isVanillaCollectible = pickup.variant == PICKUP_COLLECTIBLE && id > 0 && id < COLLECTIBLE_SEEN_COUNT; + return !isVanillaCollectible || g_manager->persistentGameData.itemsCollection[id]; +} + +// 0083d7c0 Whether the pickup's identity shows: a pill once its color is identified, a card unless it is for sale (but +// for the few whose info always shows) or out of a walking player's reach. +// The original reads a missing first local player. Here a card then counts as reachable. +bool ItemInfoHUD::is_pickup_known(Entity_Pickup& pickup) +{ + int id = (int)pickup.subtype; + if (id <= 0) return true; + if (pickup.variant == PICKUP_PILL) return g_game->itemPool.IsPillIdentified(pickup.subtype); + if (pickup.variant != PICKUP_TAROTCARD) return true; + + bool isSoul = id >= CARD_SOUL_ISAAC && id <= CARD_SOUL_JACOB; + if (pickup.price != 0 && !isSoul && std::ranges::find(SALE_KNOWN_CARDS, id) == SALE_KNOWN_CARDS.end()) return false; + Entity_Player* player = g_game->playerManager.get_first_local_main_player(); + if (!player || player->IsFlying()) return true; + return is_reachable_from_player(*g_game->room, {.position = pickup.pos, .player = player, .goal = REACH_PLAYER}); +} + +// (00840030, 008d8870) Shows on a charge icon sprite 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 charge_icon_frame_set(ANM2& sprite, 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); + if (isLazarusFlip) return sprite.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); + if (isBarless) return sprite.SetFrame((float)CHARGE_FRAME_NONE); ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); if (!item || item->type != ITEM_ACTIVE) return; @@ -84,5 +593,5 @@ void ItemInfoHUD::set_active_charge_frame(int collectibleId, const Entity_Player 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); + sprite.SetFrame((float)frame); } diff --git a/src/item_info_hud.h b/src/item_info_hud.h index 78b03f2..62026c9 100644 --- a/src/item_info_hud.h +++ b/src/item_info_hud.h @@ -1,16 +1,51 @@ #pragma once #include "anm2.h" +#include "fx_layers.h" #include "kage_graphics.h" #include "rich_text.h" +#include constexpr int POPUP_NONE = -1; +// What the item info panels share: the text of something unknown and of an unidentified pill, the bullet before each +// line and how far left of it, the title's and the lines' scales, the item image's size and where the title starts +// right of it, the space between pool icons and the color transformations show in. +constexpr const char* ITEM_INFO_UNKNOWN = "???"; +constexpr const char* ITEM_INFO_UNIDENTIFIED_PILL = "#ITEM_INFO_UNIDENTIFIED_PILL"; +constexpr const char* ITEM_INFO_BULLET = "\u25cf"; +constexpr float ITEM_INFO_BULLET_INDENT = 10; +constexpr float ITEM_INFO_TITLE_SCALE = 0.625f; +constexpr float ITEM_INFO_BODY_SCALE = 0.5f; +constexpr float ITEM_INFO_IMAGE_SIZE = 32; +constexpr float ITEM_INFO_TITLE_X = 34; +constexpr float ITEM_INFO_POOL_SPACING = 16; +constexpr uint32_t ITEM_INFO_FORM_ARGB = 0xff1199b1; + +struct Entity_Pickup; struct InfoDisplayEntry; +// Whether the item info panel's pass measures its lines or draws them. +enum ItemInfoPass +{ + ITEM_INFO_MEASURE, + ITEM_INFO_RENDER +}; + +// Where the panel's next line goes and how it looks: the line's position, the panel's top left, the text's color and +// scale, and the width lines wrap at. +struct ItemInfoBox +{ + KColor color = WHITE; + Vector position{}; + Vector start{}; + float scale = 1; + int width = 0; +}; + // Construction and destruction (0083c400, 0083c4c0) are the defaults. // The item info display (an option unlocked by an achievement): a popup describing the item, trinket, pill or card -// the player stands nearest to, with its image or sprite, its charge and map icons and its rich text. +// the player stands nearest to, with its image or sprite, its charge and pool icons and its rich text. struct ItemInfoHUD { ANM2 chargeIconSprite; @@ -18,13 +53,28 @@ struct ItemInfoHUD ANM2 mapIconsSprite; RichText text; KAGE::Graphics::ImagePtr itemImage; + Vector panelSize{}; Entity_Pickup* pickup = nullptr; - const InfoDisplayEntry* entry = nullptr; + InfoDisplayEntry* entry = nullptr; float iconScale = 0; int popupId = POPUP_NONE; void load_graphics(); void reset(); void Update(); - void set_active_charge_frame(int collectibleId, const Entity_Player& player); + Vector measure(); + void render_info(ItemInfoPass pass, const ItemInfoBox& box, Vector& extent); + void pool_icons_render(Vector position, KColor color); + static bool is_collectible_seen(Entity_Pickup& pickup); + static bool is_pickup_known(Entity_Pickup& pickup); + +private: + void pickup_describe(Entity_Pickup& nearest, Entity_Player& player); + void popup_open(); + void popup_place(); + void line_add(ItemInfoPass pass, std::string_view line, ItemInfoBox& box, Vector& extent); }; + +std::vector item_pools_shown(int collectibleId); +void pool_icon_play(ANM2& sprite, int pool); +void charge_icon_frame_set(ANM2& sprite, int collectibleId, const Entity_Player& player); diff --git a/src/item_pickup.cpp b/src/item_pickup.cpp index c327587..4b75ffd 100644 --- a/src/item_pickup.cpp +++ b/src/item_pickup.cpp @@ -6,10 +6,15 @@ #include "active_items.h" #include "entity_player.h" #include "entity_player_tainted.h" +#include "fx_layers.h" #include "game.h" +#include "menu_special_seeds.h" +#include "menu_options.h" +#include "font.h" #include "grid_entity.h" #include "item_pool.h" #include "level.h" +#include "procedural_item_manager.h" #include "log.h" #include "manager.h" #include "room.h" @@ -30,8 +35,6 @@ constexpr float RESTOCK_PEDESTAL_STEP = 10; constexpr int RESTOCK_PEDESTAL_WAIT = 20; constexpr float CAIN_POOF_DROP = 10; constexpr int CAIN_PEDESTAL_TIMEOUT = 2; -constexpr int COLLECTIBLE_BROKEN_SHOVEL_A = 550; -constexpr int COLLECTIBLE_BROKEN_SHOVEL_B = 551; constexpr int COLLECTIBLE_KNIFE_PIECE_A = 626; constexpr int COLLECTIBLE_KNIFE_PIECE_B = 627; constexpr int COLLECTIBLE_GLITCHED_GFUEL = -1; @@ -43,6 +46,7 @@ constexpr uint32_t MONSTER_MANUEL_ODDS = 3; constexpr int PEDESTAL_MOMS_CHEST = 11; constexpr int PEDESTAL_MEGA_CHEST_A = 14; constexpr int PEDESTAL_MEGA_CHEST_B = 19; +constexpr float MEGA_CHEST_ITEM_SHIFT = 16; constexpr int PEDESTAL_LAYER = 1; constexpr int PEDESTAL_WAIT = 20; constexpr int PEDESTAL_INVISIBLE_FRAMES = 3; @@ -72,9 +76,11 @@ constexpr uint32_t GLITCH_SHIFT = 11; constexpr uint32_t WAIT_WHAT_ODDS = 20; constexpr uint32_t GLITCH_ERROR_ODDS = 16; constexpr uint32_t GLITCH_SECRET_ODDS = 60; -constexpr uint32_t PICKUP_RNG_SHIFT_COLLECTIBLE = 35; constexpr uint32_t ITEM_LAYER_UNFILTERED = 0x20; constexpr int COLLECTIBLE_UNFILTERED_GFX = 633; +// April Fool's shows a random item's sprite on each pedestal, drawn up to 15 times from the pedestal's seed. +constexpr uint32_t APRILS_FOOL_GFX_SHIFT = 69; +constexpr int APRILS_FOOL_GFX_ATTEMPTS = 15; // The sounds an item makes when taken, by the room it was in. constexpr int SOUND_1UP = 1; @@ -117,10 +123,9 @@ void collectible_subtype_pick(PickupChoice& choice, RNG& rng) // charge starts full (or at its initial charge), a save that has seen Butter Bean turns it into Wait What? one time // in 20, and the pedestal waits before it can be taken. // The original reads a missing item's config. A redraw that finds none leaves the pedestal without a charge here. -void Entity_Pickup::collectible_choose(int& collectibleId, uint32_t seed) +void Entity_Pickup::collectible_choose(int& collectibleId, RNG& rng) { ItemConfig& items = g_manager->itemConfig; - RNG rng = rng_make(seed, PICKUP_RNG_SHIFT_COLLECTIBLE); ItemConfig_Item* item = items.GetCollectible(collectibleId); if (!item) @@ -174,7 +179,7 @@ void Entity_Pickup::pedestal_start() if (price == 0 && !g_pickupIgnoreModifiers && is_anyone_owning(COLLECTIBLE_DAMOCLES_PASSIVE)) { AddEntityFlags(FLAG_NO_SPIKE_DAMAGE); - room.isUnknown7769 = true; + room.isItemDuplicatePending = true; } entityCollisionClass = ENTCOLL_ALL; if (room.roomType == ROOM_DUNGEON) entityGridCollisionClass = GRIDCOLL_NONE; @@ -218,17 +223,13 @@ void Entity_Pickup::pedestal_start() bool isKeeperPriced = players.FirstPlayerByType(PLAYER_KEEPER_B) && !g_pickupIgnoreModifiers && price == 0 && !room.isInitialized && !ItemConfig::IsQuestItem(subtype); - if (!isKeeperPriced) return; - - shopItemId = -1; - ShopOffer offer = {.shopItemId = shopItemId, .subType = subtype, .variant = PICKUP_COLLECTIBLE}; - price = room_shop_discount(room, shopItemId, room_shop_item_price(room, offer, nullptr), nullptr); + if (isKeeperPriced) shop_price_assign(); } // 006e1e90 Shows a collectible's image on a layer of a sprite: the question mark when blind, a procedural item's icon // from the procedural items' sheet, or the item's own image, which a challenge swaps for a random item's. void Entity_Pickup::load_collectible_gfx(ANM2& itemSprite, int layerId, int collectibleId, - [[maybe_unused]] uint32_t seed, bool isBlind) + uint32_t seed, bool isBlind) { if (collectibleId == 0) return; @@ -243,9 +244,28 @@ void Entity_Pickup::load_collectible_gfx(ANM2& itemSprite, int layerId, int coll ItemConfig& items = g_manager->itemConfig; ItemConfig_Item* item = items.GetCollectible(collectibleId); std::string gfx = item ? item->gfxFilename : std::string(); - if (g_game->challenge == CHALLENGE_APRILS_FOOL) reconstruction_missing("Entity_Pickup::load_collectible_gfx 006e1e90"); - if (collectibleId < 0) reconstruction_missing("Entity_Pickup::load_collectible_gfx 006e1e90: a procedural item"); + if (g_game->challenge == CHALLENGE_APRILS_FOOL) + { + RNG rng = rng_make(seed, APRILS_FOOL_GFX_SHIFT); + for (int attempt = 0; attempt < APRILS_FOOL_GFX_ATTEMPTS; attempt++) + { + int other = (int)(rng.Next() % (COLLECTIBLE_VANILLA_COUNT - 1)) + 1; + if (!ItemConfig::IsValidCollectible(other)) continue; + gfx = items.GetCollectible(other)->gfxFilename; + break; + } + } + if (collectibleId < 0) + { + if (!layer) return; + layer->spriteSheet = g_game->proceduralItemManager.renderTarget; + layer->cropOffset = vector_make((float)(~collectibleId % PROCEDURAL_CELLS_PER_ROW) * PROCEDURAL_CELL_SIZE, + (float)(~collectibleId / PROCEDURAL_CELLS_PER_ROW) * PROCEDURAL_CELL_SIZE); + layer->isSpriteSheetLoaded = true; + layer->bitflags &= ~ITEM_LAYER_UNFILTERED; + return; + } if (layer) layer->cropOffset = {}; itemSprite.ReplaceSpritesheet(layerId, gfx); if (LayerState* shown = itemSprite.GetLayer(layerId)) @@ -276,8 +296,20 @@ void Entity_Pickup::SetAlternatePedestal(int pedestalType) if (sized) SetSize(sized->collisionRadius, sized->collisionRadiusMulti, sized->gridCollisionPoints); bool isMegaHalf = pedestalType == PEDESTAL_MEGA_CHEST_A || pedestalType == PEDESTAL_MEGA_CHEST_B; - if (isMegaHalf && !megaChestCollectible[0] && !megaChestCollectible[1]) - reconstruction_missing("Entity_Pickup::SetAlternatePedestal 006e1a80: a Mega Chest's pair"); + if (!isMegaHalf || megaChestCollectible[0] || megaChestCollectible[1]) return; + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity == this || !entity->IsType(ENTITY_PICKUP, PICKUP_COLLECTIBLE, -1)) continue; + auto* partner = static_cast(entity); + int partnerType = partner->GetAlternatePedestal(); + bool isPair = (partnerType == PEDESTAL_MEGA_CHEST_A || partnerType == PEDESTAL_MEGA_CHEST_B) && + partner->pos.x == pos.x && partner->pos.y == pos.y && !partner->megaChestCollectible[0] && + !partner->megaChestCollectible[1]; + if (!isPair) continue; + megaChestCollectible[0] = partner; + partner->megaChestCollectible[1] = this; + return; + } } // 006e1d70 The Alternates frame an item's pedestal shows, or -1. @@ -336,8 +368,7 @@ void Entity_Pickup::pedestal_update() { g_game->Spawn({pos, {}, nullptr, 0, ENTITY_EFFECT, EFFECT_POOF01, Random()})->Update(); ClearEntityFlags(FLAG_APPEAR); - if (g_game->playerManager.GetGFuelCount() > 1) - reconstruction_missing("Entity_Pickup::Update 006e3940: the G FUEL! explosion"); + if (g_game->playerManager.GetGFuelCount() > 1) gfuel_appear_spawn(pos, GFUEL_APPEAR_PEDESTAL); } if (!isVisible && entityCollisionClass != ENTCOLL_NONE && ++invisibleFrames > PEDESTAL_INVISIBLE_FRAMES) isVisible = true; @@ -349,9 +380,6 @@ void Entity_Pickup::pedestal_update() altPedestalANM2.animState.Update(altPedestalANM2.playbackSpeed); altPedestalANM2.overlayAnimState.Update(altPedestalANM2.playbackSpeed); } - if (subtype == COLLECTIBLE_BROKEN_SHOVEL_A && isTouched) - reconstruction_missing("Entity_Pickup::Update 006e3940: the broken shovel"); - if (megaChestCollectible[0]) reconstruction_missing("Entity_Pickup::Update 006e3940: a Mega Chest's item"); } // The flicker of Flip's other item, the original's own static generator. @@ -369,9 +397,6 @@ static RNG flip_flicker_rng() // over them. Flip's other item flickers behind the item, which moves aside for it. void Entity_Pickup::pedestal_render(const Vector& offset) { - if (megaChestCollectible[0] || megaChestCollectible[1]) - reconstruction_missing("Entity_Pickup::Render 006e69b0: a Mega Chest's items"); - Vector snapped = render_position_get(vector_make(pos.x + posOffset.x, pos.y + posOffset.y), RENDER_SNAPPED); renderPosition = vector_make(snapped.x + offset.x, snapped.y + offset.y); SpriteDraw draw = {renderPosition, {}, {}}; @@ -391,7 +416,16 @@ void Entity_Pickup::pedestal_render(const Vector& offset) sprite.overlayAnimState.Render(draw, sprite); sprite.animState.Render(draw, sprite); if (item) item->isVisible = true; - sprite.RenderLayer(PEDESTAL_LAYER, {vector_make(renderPosition.x + flipShift, renderPosition.y + flipShift), {}, {}}); + + auto* partner = static_cast(megaChestCollectible[1].get()); + if (!partner) + { + Vector shifted = vector_make(renderPosition.x + flipShift, renderPosition.y + flipShift); + return sprite.RenderLayer(PEDESTAL_LAYER, {shifted, {}, {}}); + } + float apart = sprite.scale.x * MEGA_CHEST_ITEM_SHIFT * ROOM_SCREEN_SCALE; + sprite.RenderLayer(PEDESTAL_LAYER, {vector_make(renderPosition.x - apart, renderPosition.y), {}, {}}); + partner->sprite.RenderLayer(PEDESTAL_LAYER, {vector_make(renderPosition.x + apart, renderPosition.y), {}, {}}); } // The Flip part of 006e3940: Flip's other item shows over the pedestal while someone holds Flip, a copy of the pedestal @@ -505,7 +539,11 @@ bool Entity_Pickup::collectible_collect(Entity_Player& player) if (!isKept) return tainted_cain_pedestal_break(*this, player); } if (collectibleId == COLLECTIBLE_DADS_NOTE) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Dad's Note"); + { + constexpr float DADS_NOTE_MUSIC_FADE = 0.01f; + game.save_rewind_state(-1); + g_manager->musicManager.Fadeout(DADS_NOTE_MUSIC_FADE); + } game.itemPool.RemoveCollectible(collectibleId, REMOVE_ANY, REMOVE_APPLY); int pedestalVariant = variant; @@ -517,9 +555,17 @@ bool Entity_Pickup::collectible_collect(Entity_Player& player) PlayPickupSound(); ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); - if (collectibleId == COLLECTIBLE_BROKEN_SHOVEL_B && player.HasCollectible(COLLECTIBLE_BROKEN_SHOVEL_A)) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Mom's Shovel"); - if (((game.GetCurses() & CURSE_OF_BLIND) || isForceBlind) && item) UpdateSprite(true); + if (collectibleId == COLLECTIBLE_BROKEN_SHOVEL_2 && player.HasCollectible(COLLECTIBLE_BROKEN_SHOVEL_1)) + { + int slot = player.GetActiveItemSlot(COLLECTIBLE_BROKEN_SHOVEL_1); + int heldCharge = slot >= 0 ? player.GetActiveCharge(slot) + player.GetBatteryCharge(slot) : 0; + player.RemoveCollectible(COLLECTIBLE_BROKEN_SHOVEL_1, false, 0, true); + g_manager->persistentGameData.AddToCollection(COLLECTIBLE_BROKEN_SHOVEL_2); + item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_MOMS_SHOVEL); + charge = heldCharge; + UpdateSprite(true); + } + else if (((game.GetCurses() & CURSE_OF_BLIND) || isForceBlind) && item) UpdateSprite(true); item_text_show(game.hud, &player, item); int heldCharge = charge; @@ -600,9 +646,60 @@ void Entity_Pickup::collectible_sound_play() sounds.Play(sound, play); } +// The characters of a UTF-8 text, each as its own bytes. +static std::vector utf8_split(std::string_view text) +{ + std::vector characters; + const char* end = text.data() + text.size(); + for (const char* cursor = text.data(); cursor < end;) + { + uint32_t codepoint = 0; + const char* next = utf8_decode_next(cursor, &codepoint, end); + if (!codepoint) break; + characters.emplace_back(cursor, (size_t)(next - cursor)); + cursor = next; + } + return characters; +} + +// TMTRAINER's description: its first 100 characters overwritten by "#ZZAZZ_PATTERN" (its first 32 characters, over +// and over) wherever the pattern has no dot. +// The original divides by zero on an empty pattern. Here the description stays. +static std::string zzazz_pattern_apply(std::string_view description) +{ + constexpr size_t ZZAZZ_PATTERN_MAX = 32; + constexpr size_t ZZAZZ_TEXT_MAX = 100; + std::string translated(string_table_translate(g_manager->stringTable, "#ZZAZZ_PATTERN")); + std::vector pattern = utf8_split(translated); + if (pattern.size() > ZZAZZ_PATTERN_MAX) pattern.resize(ZZAZZ_PATTERN_MAX); + + std::string result; + std::vector characters = utf8_split(description); + for (size_t i = 0; i < characters.size(); i++) + { + bool isPatterned = i < ZZAZZ_TEXT_MAX && !pattern.empty() && pattern[i % pattern.size()] != "."; + result += isPatterned ? pattern[i % pattern.size()] : characters[i]; + } + return result; +} + +// Birthright's description for a character: its players.xml text, a #key looked up in the "Players" string table. +static std::string birthright_text_get(Entity_Player& player) +{ + EntityConfig_Player* config = g_manager->entityConfig.GetPlayer(player.playerType); + std::string_view text = config ? std::string_view(config->birthrightDescription) : std::string_view(); + if (text.empty() || text[0] != '#') return std::string(text); + + StringTable& table = g_manager->stringTable; + bool isMissing = false; + std::string_view localized = table.get_string("Players", table.language, text.substr(1), &isMissing); + return std::string(isMissing ? text : localized); +} + // 009a2d20 (HUD::ShowItemText, with ShowStackedItemTextCustom 009a34a0) Shows a taken item's name and description in -// the first free banner of the stack. Monster Manual is misspelled a third of the time. Birthright's character text, -// the seed that scrambles text and TMTRAINER's pattern stop the game until reached. +// the first free banner of the stack. Monster Manual is misspelled a third of the time, Birthright tells what it does +// for the character, the seed that scrambles text scrambles both, and TMTRAINER's description is overwritten by its +// pattern. void item_text_show(HUD& hud, Entity_Player* player, ItemConfig_Item* item) { std::string name = item->GetLocalizedName(LANGUAGE_CURRENT); @@ -612,10 +709,13 @@ void item_text_show(HUD& hud, Entity_Player* player, ItemConfig_Item* item) name == "Monster Manual") name = "Monster Manuel"; if (item->IsCollectible() && item->id == COLLECTIBLE_BIRTHRIGHT && player) - reconstruction_missing("HUD::ShowItemText 009a2d20: Birthright's character text"); + description = birthright_text_get(*player); if (g_game->seedEffects.HasSeedEffect(SEED_DYSLEXIA)) - reconstruction_missing("HUD::ShowItemText 009a2d20: the scrambled text"); - if (item->id == COLLECTIBLE_TMTRAINER) reconstruction_missing("HUD::ShowItemText 009a2d20: TMTRAINER's pattern"); + { + name = string_scramble_seeded(name); + description = string_scramble_seeded(description); + } + if (item->id == COLLECTIBLE_TMTRAINER) description = zzazz_pattern_apply(description); hud.ShowStackedItemTextCustom(name.c_str(), description.c_str()); } diff --git a/src/item_pool.cpp b/src/item_pool.cpp index 213587a..ebf72ff 100644 --- a/src/item_pool.cpp +++ b/src/item_pool.cpp @@ -2,8 +2,10 @@ #include "boss_pool.h" #include "data.h" #include "entity_config.h" +#include "entity_pickup.h" #include "entity_player.h" #include "game.h" +#include "loot_list.h" #include "lua_engine.h" #include "manager.h" #include "platform.h" @@ -58,6 +60,8 @@ constexpr uint32_t ERROR_ROOM_SHIFT = 7; constexpr uint32_t MAGIC_SKIN_SHIFT = 55; constexpr uint32_t GOLDEN_SHIFT = 19; constexpr uint32_t PILL_SHIFT = 12; +constexpr uint32_t GOLD_PILL_SHIFT = 3; +constexpr uint32_t ITEM_CARD_SHIFT = 32; // GetCard's odds of a special card, a rune and a playing card, and the shifts of GetCardEx's and Tainted Lost's draws. constexpr int CARD_SPECIAL_ODDS = 25; constexpr int CARD_RUNE_ODDS = 10; @@ -476,14 +480,14 @@ int ItemPool::get_chaos_pool(RNG& rng) return outcome_pick(outcomes, rng_make(rng._seed, POOL_SHIFT)); } -// 00732e90 Every pool holding the collectible, once per copy it holds. +// 00732e90 Every pool holding the collectible, in pool order. std::vector ItemPool::GetItemPoolsForCollectible(int collectible) { std::vector found; for (int id = 0; id < POOL_COUNT; id++) - for (PoolItem& item : pools[id].poolList) - if (item.itemId == collectible) found.push_back(id); + if (std::ranges::any_of(pools[id].poolList, [&](PoolItem& item) { return item.itemId == collectible; })) + found.push_back(id); return found; } @@ -503,7 +507,7 @@ int ItemPool::GetCollectible(ItemPoolType poolType, uint32_t drawSeed, uint32_t int fallbackPool) { PlayerManager& players = g_game->playerManager; - uint32_t daily = g_game->dailyChallenge._specialDailyId; + uint32_t daily = g_game->dailyChallenge.specialDailyId; if (drawSeed == 0) log_printf(LOG_ASSERT, "ItemPool::GetCollectible Seed is 0\n"); if (poolType < 0 || poolType >= POOL_COUNT || drawSeed == 0) return 0; @@ -761,11 +765,22 @@ void ItemPool::AddBibleUpgrade(int add, int poolType) for (ItemPool_Item& pool : pools) pool.bibleUpgrade += add; } -// Whether a Magic Skin pedestal waits in the current room or a visited one. Room's entity list and the saved -// entities of the floor's rooms are not modelled yet. +// Whether a free Magic Skin pedestal waits in the current room or among a visited room's saved entities. static bool is_magic_skin_waiting() { - reconstruction_missing("ItemPool::should_force_magic_skin pedestal scan (Room entity list, saved entities)"); + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity && entity->IsType(ENTITY_PICKUP, PICKUP_COLLECTIBLE, COLLECTIBLE_MAGIC_SKIN) && + static_cast(entity)->price == 0) + return true; + for (RoomDescriptor& room : g_game->roomList) + { + if (!room.data || room.visitedCount == 0) continue; + for (EntitySaveState& saved : room.savedEntities) + if (saved.type == ENTITY_PICKUP && saved.variant == PICKUP_COLLECTIBLE && saved.intStorage3 == 0 && + saved.subtype == COLLECTIBLE_MAGIC_SKIN) + return true; + } + return false; } // 007333f0 Whether Magic Skin replaces a draw: after it has been used, a chance growing with each use, or a fixed @@ -900,7 +915,7 @@ int ItemPool::GetPillEffect(uint32_t pillColor, Entity_Player* player) int effect = color < PILL_COLOR_SLOTS ? pillEffects[color] : PILL_EFFECT_NONE; bool isFalsePhd = false; - if (g_game->dailyChallenge._specialDailyId == DAILY_EXPLOSIVE_PILLS) return PILLEFFECT_EXPLOSIVE_DIARRHEA; + if (g_game->dailyChallenge.specialDailyId == DAILY_EXPLOSIVE_PILLS) return PILLEFFECT_EXPLOSIVE_DIARRHEA; if (player) { bool isPhd = player->HasCollectible(COLLECTIBLE_PHD) || player->HasCollectible(COLLECTIBLE_VIRGO) || @@ -951,10 +966,31 @@ bool ItemPool::IsPillIdentified(uint32_t pillColor) return identifiedPillEffects[pill_slot_get(pillColor)]; } -// (00736c30) What using a pill does to the pools. -int ItemPool::on_pill_used(int, uint32_t, uint32_t&) +// 00736c30 A used gold pill forgets that it was identified and takes a random available effect that no pill color +// holds, its own included. +// The original crashes with no such effect left. Here the color keeps its effect. +int ItemPool::on_pill_used(int pillColor, uint32_t useSeed, uint32_t&) { - reconstruction_missing("ItemPool::on_pill_used 00736c30"); + ItemConfig& config = g_manager->itemConfig; + int slot = pill_slot_get((uint32_t)pillColor); + identifiedPillEffects[slot] = false; + + std::vector isHeld(config.pillEffects.size()); + for (int color = 1; color <= PILL_COLOR_GOLD; color++) + if (pillEffects[color] >= 0 && pillEffects[color] < (int)isHeld.size()) isHeld[pillEffects[color]] = true; + + std::vector candidates; + for (auto& pill : config.pillEffects) + { + if (!pill || (!pill->isGreedModeAllowed && g_game->IsGreedMode())) continue; + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("ItemPool::on_pill_used 00736c30 (the deathmatch's pill ban)"); + if (is_unlocked(pill->achievementId) && !isHeld[pill->id]) candidates.push_back(pill->id); + } + + uint32_t roll = rng_make(useSeed, GOLD_PILL_SHIFT).Next(); + if (!candidates.empty()) pillEffects[slot] = candidates[roll % candidates.size()]; + return pillEffects[slot]; } // (00734cc0) Takes the effects deathmatch bans out of the pill colors. @@ -1050,3 +1086,38 @@ int ItemPool::GetCardEx(int drawSeed, int specialChance, int runeChance, int sui } return card; } + +// The pools an item card draws from outside devil and angel rooms, with their weights. +constexpr std::array ITEM_CARD_POOLS = { + {{POOL_TREASURE, 100}, {POOL_SHOP, 30}, {POOL_BOSS, 30}, {POOL_DEVIL, 10}, {POOL_ANGEL, 10}, {POOL_SECRET, 2}}}; + +// Cantripped's item cards leave out collectibles tagged nocantrip. +static bool is_cantrip_allowed(ItemConfig_Item& item) +{ + bool isCollectible = item.type == ITEM_PASSIVE || item.type == ITEM_ACTIVE || item.type == ITEM_FAMILIAR; + return !isCollectible || !item.HasTags(TAG_NO_CANTRIP); +} + +// 007376c0 An active for an item card: from the devil or angel pool in those rooms, else from a pool picked by weight, +// and from the treasure pool (Tammy's Head at worst) when that pool has none left. +int ItemPool::GetCardImpl(uint32_t drawSeed) +{ + WeightedOutcomePicker picker; + int roomType = g_game->room->roomType; + if (roomType == ROOM_DEVIL || roomType == ROOM_ANGEL) + picker.AddOutcomeWeight(roomType == ROOM_DEVIL ? POOL_DEVIL : POOL_ANGEL, ITEM_CARD_POOLS[0].weight); + else + for (WeightedOutcomePicker::Outcome pool : ITEM_CARD_POOLS) picker.AddOutcomeWeight(pool.id, pool.weight); + + RNG rng = rng_make(drawSeed, ITEM_CARD_SHIFT); + int pool = picker.PickOutcome(rng_make(rng.Next(), DEFAULT_SHIFT_INDEX)); + uint32_t flags = POOL_FLAG_NO_DECREASE | POOL_FLAG_BAN_PASSIVES; + std::vector& filters = g_manager->itemConfig.availabilityFilters; + filters.push_back(is_cantrip_allowed); + ItemPool& itemPool = g_game->itemPool; + int item = itemPool.GetCollectible((ItemPoolType)pool, rng.Next(), flags, 0, POOL_TREASURE); + if (item == 0) + item = itemPool.GetCollectible(POOL_TREASURE, rng.Next(), flags, COLLECTIBLE_TAMMYS_HEAD, POOL_TREASURE); + filters.pop_back(); + return item; +} diff --git a/src/item_pool.h b/src/item_pool.h index a218b4c..a4f4156 100644 --- a/src/item_pool.h +++ b/src/item_pool.h @@ -214,4 +214,5 @@ public: static int GetCard(uint32_t drawSeed, bool isPlaying, bool isRunes, bool isOnlyRunes); static int GetCardEx(int drawSeed, int specialChance, int runeChance, int suitChance, bool isNonCardsAllowed); + static int GetCardImpl(uint32_t drawSeed); }; diff --git a/src/kage_graphics.cpp b/src/kage_graphics.cpp index 399a758..3dfc49f 100644 --- a/src/kage_graphics.cpp +++ b/src/kage_graphics.cpp @@ -26,7 +26,6 @@ constexpr int PNG_COLOR_TYPE_RGB = 2; 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 double SRGB_GAMMA = 2.2; // The color draw calls take to mean "the quad's own colors". constexpr float COLOR_UNSET = -1; diff --git a/src/kage_input.cpp b/src/kage_input.cpp index cfa7642..dbb0e19 100644 --- a/src/kage_input.cpp +++ b/src/kage_input.cpp @@ -10,10 +10,6 @@ constexpr int DIGIT_COUNT = 10; constexpr int LETTER_COUNT = 26; constexpr int FUNCTION_KEY_COUNT = 25; constexpr int KEYPAD_DIGIT_COUNT = 10; -constexpr int KEY_DIGIT_0 = 48; -constexpr int KEY_LETTER_A = 65; -constexpr int KEY_F1 = 290; -constexpr int KEY_KEYPAD_0 = 320; // The gamepad's slots: its buttons, then the eight stick directions. constexpr int GAMEPAD_SLOTS = BUTTON_COUNT + STICK_END - STICK_LEFT_LEFT; // A stick direction counts as pushed past this, as InputDeviceBase's default dead zone (DAT_00c57b40). diff --git a/src/kage_input.h b/src/kage_input.h index 13efdaa..df0931c 100644 --- a/src/kage_input.h +++ b/src/kage_input.h @@ -9,6 +9,37 @@ #include #include +// The GLFW keys the game reads by number. +enum KeyboardKey : int +{ + KEY_SPACE = 32, + KEY_DIGIT_0 = 48, + KEY_LETTER_A = 65, + KEY_V = 86, + KEY_GRAVE_ACCENT = 96, + KEY_ESCAPE = 256, + KEY_ENTER = 257, + KEY_BACKSPACE = 259, + KEY_DELETE = 261, + KEY_RIGHT = 262, + KEY_LEFT = 263, + KEY_DOWN = 264, + KEY_UP = 265, + KEY_PAGE_UP = 266, + KEY_PAGE_DOWN = 267, + KEY_HOME = 268, + KEY_END = 269, + KEY_F1 = 290, + KEY_KEYPAD_0 = 320, + KEY_KEYPAD_SUBTRACT = 333, + KEY_KEYPAD_ADD = 334, + KEY_KEYPAD_ENTER = 335, + KEY_LEFT_CONTROL = 341, + KEY_LEFT_SUPER = 343, + KEY_RIGHT_CONTROL = 345, + KEY_RIGHT_SUPER = 347 +}; + namespace KAGE::Input { // The keyboard's keys are GLFW's key numbers, below KEY_COUNT. diff --git a/src/leaderboard.h b/src/leaderboard.h index cbc7cb8..880f711 100644 --- a/src/leaderboard.h +++ b/src/leaderboard.h @@ -1,6 +1,7 @@ #pragma once #include "anm2.h" +#include "daily_challenge.h" #include "score_sheet.h" #include diff --git a/src/level.cpp b/src/level.cpp index 9af8cba..8a7f9dd 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -1,4 +1,5 @@ #include "level.h" +#include "boss_ai.h" #include "boss_final.h" #include "boss_pool.h" #include "entity_effect.h" @@ -8,6 +9,7 @@ #include "game.h" #include "grid_entity_door.h" #include "grid_entity_pit.h" +#include "grid_entity_stairs.h" #include "hud.h" #include "lua_engine.h" #include "menu_special_seeds.h" @@ -26,6 +28,8 @@ #include #include #include +#include +#include #include #include @@ -62,7 +66,6 @@ constexpr float INTENSE_HEALTH_PER_STAGE = 14; constexpr float INTENSE_HEALTH_ALWAYS = 10000; constexpr float MINESHAFT_HEALTH_PER_PIT = 3; constexpr int GREED_STAGE_LAST_PAIRED = 4; -constexpr int GREED_STAGE_SHOP = 5; constexpr int GREED_DEPTH_SHOP = 10; // The endless basement's floor number as roman numerals, and the counts its jokes start at. @@ -123,7 +126,6 @@ constexpr int ROOM_SCREEN_WIDTH = 13; constexpr int ROOM_SCREEN_HEIGHT = 7; constexpr int START_ROOM_VARIANT = 2; constexpr int ULTRA_SECRET_GROUP = 99; -constexpr int BOSS_MOTHER_HEART = 89; constexpr int BOSS_MOMS_HEART_MAUSOLEUM = 90; constexpr int BOSS_ROOM_RETRIES = 50; constexpr int BOSS_ROOM_VARIANTS = 50; @@ -291,6 +293,59 @@ constexpr std::array OFF_MAP_ENTRY_ROOMS = {ROOM_DEVIL_IDX, ROOM_B // The rooms whose doors out of a Corpse room get blood splats when they use the alternate backdrop. constexpr std::array CORPSE_SPLAT_ROOM_TYPES = {ROOM_DEFAULT, ROOM_TREASURE, ROOM_MINIBOSS, ROOM_BOSS}; +// Red Redemption's stage types by the two noise maps at a cell, the first map's fifth times five plus the second's: +// on the first three chapters, and on the Womb away from its last boss room (the alternate path within reach of it). +constexpr int NOISE_BUCKETS = 5; +constexpr float NOISE_BUCKET_LAST = 4.999f; +constexpr std::array RED_REDEMPTION_STAGE_TYPES = { + 0, 0, 0, 2, 2, 0, 0, 2, 2, 2, 0, 1, 0, 2, 4, 1, 1, 1, 4, 5, 1, 1, 4, 5, 5}; +constexpr std::array RED_REDEMPTION_WOMB_STAGE_TYPES = { + 0, 0, 0, 0, 2, 0, 0, 0, 2, 2, 0, 0, 0, 2, 2, 0, 1, 1, 1, 2, 1, 1, 1, 1, 2}; +constexpr int WOMB_BOSS_REACH = 3; +constexpr uint32_t NOISE_SHIFT_INDEX = 9; +constexpr float NOISE_NORMALIZE = 1.0f / (1 + 2 + 4); + +// Red Redemption's clusters by step, the cells its special rooms are drawn among (the grid's edge left out) and how +// often, and the shapes its normal rooms take (no corridors). +enum RandomClusterStep +{ + RANDOM_STEP_BOSS, + RANDOM_STEP_SECOND_BOSS, + RANDOM_STEP_TREASURE, + RANDOM_STEP_SECOND_TREASURE, + RANDOM_STEP_SHOP, + RANDOM_STEP_COUNT +}; +constexpr uint32_t RANDOM_CELL_SPAN = 11; +constexpr int RANDOM_CELL_TRIES = 80; +constexpr uint32_t RANDOM_LAYOUT_SHAPES = + ROOM_SHAPES_ALL & ~(1u << ROOMSHAPE_IH | 1u << ROOMSHAPE_IV | 1u << ROOMSHAPE_IIV | 1u << ROOMSHAPE_IIH); + +// The Ascent's room counts (less its depth, more on hard and on an XL stage), the dead ends it needs, and its rooms' +// subtypes by chapter, on the main path and the alternate one. +constexpr int BACKWARDS_ROOMS = 12; +constexpr int BACKWARDS_ROOMS_HARD = 14; +constexpr int BACKWARDS_XL_ROOMS = 6; +constexpr int BACKWARDS_DEAD_ENDS = 2; +constexpr std::array BACKWARDS_SUBTYPES = {1, 4, 7}; +constexpr std::array BACKWARDS_ALT_SUBTYPES = {27, 29, 31}; + +// The Death Certificate's floor: its start closet (Home's variant 100) and the cells kept free around it, its rooms +// (Home's subtype 34) and how many, the shift index of the RNG its rooms are drawn with, and its items' options group. +constexpr XY DARK_CLOSET_START = {2, 6}; +constexpr int DARK_CLOSET_START_IDX = DARK_CLOSET_START.y * LEVEL_GRID_WIDTH + DARK_CLOSET_START.x; +constexpr std::array DARK_CLOSET_BLOCKED = {{{1, 6}, {2, 5}, {2, 7}}}; +constexpr int DARK_CLOSET_START_VARIANT = 100; +constexpr int DARK_CLOSET_SUBTYPE = 34; +constexpr int DARK_CLOSET_ROOM_COUNT = 50; +constexpr uint32_t DARK_CLOSET_SHIFT_INDEX = 34; +constexpr uint32_t DARK_CLOSET_OPTIONS_INDEX = 1; + +constexpr uint32_t EXTRA_BOSS_SHIFT_INDEX = 4; +constexpr int GENESIS_ROOM_SUBTYPE = 99; +constexpr int GREED_STAGE_WOMB = 4; +constexpr std::array HORSEMAN_BOSSES = {BOSS_FAMINE, BOSS_PESTILENCE, BOSS_WAR, BOSS_CONQUEST, BOSS_DEATH}; + constexpr XY START_POSITION = {6, 6}; constexpr XY PHOTO_DOOR_CELL = {6, 5}; constexpr int START_GRID_INDEX = 84; @@ -454,7 +509,7 @@ void Level::Init(bool isResetLilPortalRoom) bool isHard = game.difficulty == DIFFICULTY_HARD; uint32_t effectiveStage = stage + (IsAltPath() ? 1 : 0); - game.gameStateFlags &= ~(1ull << LEVEL_GAME_STATE_MAX_COINS_OBTAINED); + game.gameStateFlags &= ~(1ull << GAME_STATE_SECRET_PATH); myosotisPickups.clear(); if (isMyosotis) myosotis_pickups_collect(); @@ -502,7 +557,7 @@ void Level::Init(bool isResetLilPortalRoom) if (is_unlocked(ACHIEVEMENT_THE_WOMB)) curseOdds = CURSE_ODDS_WOMB[isHard]; if (is_unlocked(ACHIEVEMENT_EVERYTHING_IS_TERRIBLE)) curseOdds = CURSE_ODDS_TERRIBLE[isHard]; - if (g_manager->persistentGameData.eventCounters[EVENT_COUNTER_CURSE_ODDS] != 0 || game.dailyChallenge._id != 0) + if (g_manager->persistentGameData.eventCounters[EVENT_COUNTER_CURSE_ODDS] != 0 || game.dailyChallenge.id != 0) curseOdds = CURSE_ODDS_DAILY[isHard]; if (stage == STAGE_BASEMENT_I && !is_unlocked(ACHIEVEMENT_EVERYTHING_IS_TERRIBLE)) curseOdds = 0; @@ -511,7 +566,7 @@ void Level::Init(bool isResetLilPortalRoom) curseRng.SetSeed(generationRNG._seed, DEFAULT_SHIFT_INDEX); bool isCurseRolled = stage != STAGE_HOME && !IsAscent() && curseOdds != 0 && !game.playerManager.FirstCollectibleOwner(COLLECTIBLE_BLACK_CANDLE, LAZARUS_SHARE_CHECK) && - game.dailyChallenge._specialDailyId != SPECIAL_DAILY_NO_CURSES; + game.dailyChallenge.specialDailyId != SPECIAL_DAILY_NO_CURSES; curses = CURSE_NONE; if (isCurseRolled) @@ -550,7 +605,7 @@ void Level::Init(bool isResetLilPortalRoom) } break; case 5: - if (game.dailyChallenge._id == 0) + if (game.dailyChallenge.id == 0) { curses |= CURSE_OF_BLIND; log_printf(LOG_INFO, "Curse of Blind\n"); @@ -561,7 +616,7 @@ void Level::Init(bool isResetLilPortalRoom) curses = lua_engine_get().PostCurseEval(curses); } - if (game.dailyChallenge._specialDailyId == SPECIAL_DAILY_CURSED) curses |= SPECIAL_DAILY_CURSES; + if (game.dailyChallenge.specialDailyId == SPECIAL_DAILY_CURSED) curses |= SPECIAL_DAILY_CURSES; if (game.challenge != 0) { ChallengeParam& params = g_manager->GetChallengeParams((int)game.challenge); @@ -590,7 +645,7 @@ void Level::Init(bool isResetLilPortalRoom) generate_greed(); } else if (stage == STAGE_HOME) generate_home_level(); - else if (stage <= ASCENT_LAST_STAGE && game_flag_get(LEVEL_GAME_STATE_BACKWARDS_PATH)) generate_backwards(); + else if (stage <= ASCENT_LAST_STAGE && game_flag_get(GAME_STATE_BACKWARDS_PATH)) generate_backwards(); else if (game.challenge == CHALLENGE_RED_REDEMPTION) generate_random_layout(); else if (stage == STAGE_BLUE_WOMB) generate_blue_womb(); else @@ -628,7 +683,10 @@ void Level::Init(bool isResetLilPortalRoom) game.challenge != CHALLENGE_BACKASSWARDS) for (int keyPiece : {COLLECTIBLE_KEY_PIECE_1, COLLECTIBLE_KEY_PIECE_2}) if (!game.playerManager.FirstCollectibleOwner(keyPiece, LAZARUS_SHARE_CHECK)) - reconstruction_missing("Level::Init 00744940: a Mega Satan challenge's Key Pieces (AddCollectible)"); + { + game.GetPlayer(0)->AddCollectible(keyPiece, 0, true, 0, 0); + game.itemPool.RemoveCollectible(keyPiece, REMOVE_ANY, REMOVE_APPLY); + } uint32_t voiceStage = effectiveStage; if ((GetCurses() & CURSE_OF_LABYRINTH) && (voiceStage == STAGE_BASEMENT_II || voiceStage == STAGE_CAVES_II)) @@ -769,7 +827,7 @@ void Level::generate_dungeon(RNG& curseRng) settings.isXL = isLabyrinth || game.challenge == CHALLENGE_XXXXXXXXL; bool isStandardPath = - (game.challenge == 0 && game.dailyChallenge._id == 0) || game.GetChallengeParams().pathType == PATH_TYPE_HOME; + (game.challenge == 0 && game.dailyChallenge.id == 0) || game.GetChallengeParams().pathType == PATH_TYPE_HOME; LevelGenerator_Room startRoom; startRoom.position = START_POSITION; @@ -1035,12 +1093,70 @@ uint32_t Level::GetStageID() return stageId == STAGE_ID_VOID && data && data->stageId != 0 ? (uint32_t)data->stageId : (uint32_t)stageId; } -// 0074f690 The stage type a room's layout comes from: the floor's, but for Red Redemption's mixed floors. -int Level::GetRoomStageType(int) +// 0074f690 The stage type a room's layout comes from: the floor's, but for Red Redemption's mixed floors, where the two +// noise maps at the room's cell pick it, and the Womb's cells near its last boss room are always the alternate path's. +// The secret exit's room on the Womb I is the alternate path's too. The original reads past the maps for a room index +// past the grid while no layout is generating. The cell is clamped here. +int Level::GetRoomStageType(int roomIdx) { - if (g_game->challenge == CHALLENGE_RED_REDEMPTION) - reconstruction_missing("Level::GetRoomStageType 0074f690: Red Redemption's stage type noise"); - return (int)stageType; + bool isWomb = stage == STAGE_WOMB_I || stage == STAGE_WOMB_II; + + if (g_game->challenge != CHALLENGE_RED_REDEMPTION) return (int)stageType; + if (roomIdx == ROOM_SECRET_EXIT_IDX && stage == STAGE_WOMB_I) return STAGETYPE_REPENTANCE; + if (roomIdx < 0 || (stage > STAGE_DEPTHS_II && !isWomb)) return (int)stageType; + if (!isLevelGenerating && GetRoomByIdx(roomIdx)->data) roomIdx = GetRoomByIdx(roomIdx)->gridIndex; + roomIdx = std::clamp(roomIdx, 0, LEVEL_GRID_CELLS - 1); + + auto bucket = [&](int map) { + return (int)std::clamp(stageTypeNoise[map][roomIdx] * NOISE_BUCKETS, 0.0f, NOISE_BUCKET_LAST); + }; + int noiseIdx = bucket(0) * NOISE_BUCKETS + bucket(1); + + if (!isWomb) return RED_REDEMPTION_STAGE_TYPES[noiseIdx]; + + XY boss = XY::NewFromGridIdx(roomList[lastBossRoomListIdx].gridIndex); + XY cell = XY::NewFromGridIdx(roomIdx); + + if (std::abs(boss.x - cell.x) + std::abs(boss.y - cell.y) <= WOMB_BOSS_REACH) return STAGETYPE_REPENTANCE; + return RED_REDEMPTION_WOMB_STAGE_TYPES[noiseIdx]; +} + +// One octave of Red Redemption's noise at a cell: the raw values at every step-th cell around it (wrapping at the +// grid's edge), blended bilinearly. +static float noise_octave(const std::array& raw, XY cell, int step) +{ + int left = cell.x & -step; + int top = cell.y & -step; + int right = (left + step) % LEVEL_GRID_WIDTH; + int bottom = (top + step) % LEVEL_GRID_WIDTH; + float fx = (float)(cell.x - left) / (float)step; + float fy = (float)(cell.y - top) / (float)step; + float upper = fx * raw[top * LEVEL_GRID_WIDTH + right] + (1 - fx) * raw[top * LEVEL_GRID_WIDTH + left]; + float lower = fx * raw[bottom * LEVEL_GRID_WIDTH + right] + (1 - fx) * raw[bottom * LEVEL_GRID_WIDTH + left]; + + return upper * (1 - fy) + lower * fy; +} + +// 0074f820 Seeds Red Redemption's two noise maps from the stage's seed: each a grid of random values smoothed with +// its every second and every fourth cell, the coarser octaves weighing more. +void Level::InitStageSeeds() +{ + RNG rng{}; + + rng.SetSeed(g_game->seedEffects.GetStageSeed(stage_depth_get()), NOISE_SHIFT_INDEX); + for (std::array& noise : stageTypeNoise) + { + std::array raw; + + for (float& value : raw) value = rng.RandomFloat(); + for (int i = 0; i < LEVEL_GRID_CELLS; i++) + { + XY cell = XY::NewFromGridIdx(i); + float octave2 = noise_octave(raw, cell, 2); + + noise[i] = NOISE_NORMALIZE * (noise_octave(raw, cell, 4) * 4 + (octave2 * 2 + raw[i])); + } + } } // 00738610 Updates the current room. @@ -1070,7 +1186,7 @@ int Level::stage_depth_get() // 0074f090 Whether the floor is one of the Ascent's. bool Level::IsAscent() { - return stage >= 1 && stage <= ASCENT_LAST_STAGE && game_flag_get(LEVEL_GAME_STATE_BACKWARDS_PATH); + return stage >= 1 && stage <= ASCENT_LAST_STAGE && game_flag_get(GAME_STATE_BACKWARDS_PATH); } // Whether the floor is outside Greed and the Ascent on a normal or alternate path, as the secret path checks ask. @@ -1091,18 +1207,19 @@ static uint32_t stage_with_labyrinth(Level& level) return level.stage + ((level.GetCurses() & CURSE_OF_LABYRINTH) ? 1 : 0); } -// 0074ea50 Whether the run is about to start the Ascent: Mausoleum II (or an XL Mausoleum) after its heart was killed. +// 0074ea50 Whether the run is about to start the Ascent: Mausoleum II (or an XL Mausoleum) entered through Depths II's +// strange door. bool Level::IsPreAscent() { return is_path_stage(*this, true) && stage_with_labyrinth(*this) == STAGE_DEPTHS_II && - game_flag_get(LEVEL_GAME_STATE_MAUSOLEUM_HEART_KILLED); + game_flag_get(GAME_STATE_BACKWARDS_PATH_INIT); } -// 0074e9b0 Whether the floor is Mausoleum II (or an XL Mausoleum) holding Mother's heart room. +// 0074e9b0 Whether the floor is Mausoleum II (or an XL Mausoleum) after Mom's Heart was killed there, the escape on. bool Level::IsMausoleumHeartStage() { return is_path_stage(*this, true) && stage_with_labyrinth(*this) == STAGE_DEPTHS_II && - game_flag_get(LEVEL_GAME_STATE_MAUSOLEUM_HEART_ROOM); + game_flag_get(GAME_STATE_MAUSOLEUM_HEART_KILLED); } // 0074ef70 Whether the floor has Dross or Downpour II's mirror world (or an XL first one). @@ -1403,7 +1520,7 @@ static int treasure_subtype_get(RNG& rng) isOptions = (isHorseShoe && players.FirstTrinketOwner(TRINKET_GOLDEN_HORSE_SHOE, nullptr, LAZARUS_SHARE_CHECK)) || - g_game->dailyChallenge._specialDailyId == SPECIAL_DAILY_TREASURE_OPTIONS; + g_game->dailyChallenge.specialDailyId == SPECIAL_DAILY_TREASURE_OPTIONS; } bool isPayToWin = players.FirstTrinketOwner(TRINKET_PAY_TO_WIN, nullptr, LAZARUS_SHARE_CHECK); @@ -1504,7 +1621,7 @@ static void library_place(SpecialRoomPlacement& placement) auto is_placed = [&]() { if (rng.Next() % LIBRARY_ODDS == 0) return true; rng.Next(); - return (rng._seed & 3) == 0 && game_flag_get(LEVEL_GAME_STATE_BOOK_PICKED_UP); + return (rng._seed & 3) == 0 && game_flag_get(GAME_STATE_BOOK_PICKED_UP); }; if (!placement.is_excluded(ROOM_LIBRARY) && is_placed()) room_place(level, room, config, rng._seed); @@ -2065,8 +2182,8 @@ RoomConfig_Room* Level::pick_boss_room_config(int bossId, uint32_t seed) } return room; } - if (bossId == BOSS_MOTHER_HEART && game_flag_get(LEVEL_GAME_STATE_MAUSOLEUM_HEART_KILLED)) - return fallback_room_get(rng.Next(), room_query(g_game->GetStageID(), ROOM_BOSS, BOSS_MOTHER_HEART), + if (bossId == BOSS_MOM_MAUSOLEUM && game_flag_get(GAME_STATE_BACKWARDS_PATH_INIT)) + return fallback_room_get(rng.Next(), room_query(g_game->GetStageID(), ROOM_BOSS, BOSS_MOM_MAUSOLEUM), STAGE_ID_MAUSOLEUM); do room = random_room_get(rng.Next(), room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_BOSS, bossId)); while (retries > 0 && room && room->type == ROOM_BOSS && @@ -2203,9 +2320,9 @@ bool Level::CanSpawnTrapDoor() if (HasMirrorDimension() && currentDimensionIdx == 1) return false; if (!isLevelGenerating && room && room->roomType == ROOM_BOSS && - room->descriptor->data->subtype == BOSS_MOTHER_HEART && IsPreAscent()) + room->descriptor->data->subtype == BOSS_MOM_MAUSOLEUM && IsPreAscent()) return false; - if (stage >= 1 && stage <= ASCENT_LAST_STAGE && game_flag_get(LEVEL_GAME_STATE_BACKWARDS_PATH)) return false; + if (stage >= 1 && stage <= ASCENT_LAST_STAGE && game_flag_get(GAME_STATE_BACKWARDS_PATH)) return false; if (game.GetChallengeParams().pathType == PATH_TYPE_REPENTANCE && !isRepentanceStart && currentRoomIdx != ROOM_SECRET_EXIT_IDX && game.challenge != CHALLENGE_RED_REDEMPTION) return false; @@ -2236,9 +2353,9 @@ bool Level::IsNextStageAvailable() if (nextStage == STAGE_WOMB_II && IsAltPath()) return false; if ((nextStage == STAGE_DEPTHS_II || (nextStage == STAGE_DEPTHS_I && filter_curses(CURSE_OF_LABYRINTH))) && - params.pathType == PATH_TYPE_HOME && !game_flag_get(LEVEL_GAME_STATE_BACKWARDS_PATH)) + params.pathType == PATH_TYPE_HOME && !game_flag_get(GAME_STATE_BACKWARDS_PATH)) return false; - return (game.challenge == 0 && game.dailyChallenge._id == 0) || nextStage < params.endStage; + return (game.challenge == 0 && game.dailyChallenge.id == 0) || nextStage < params.endStage; } // 0074b830 Whether a stage is within the run's end: Greed's Womb, else the challenge's end stage (the Void once @@ -2248,7 +2365,7 @@ bool Level::IsStageWithinEnd(int levelStage, bool isAltPath) { Game& game = *g_game; ChallengeParam& params = game.GetChallengeParams(); - bool isChallenge = game.challenge != 0 || game.dailyChallenge._id != 0; + bool isChallenge = game.challenge != 0 || game.dailyChallenge.id != 0; int endStage = params.endStage == STAGE_VOID || (!isChallenge && is_unlocked(ACHIEVEMENT_THE_VOID)) ? STAGE_VOID : STAGE_DARK_ROOM; @@ -2579,6 +2696,89 @@ static MineshaftRails mineshaft_rails_get(RoomDescriptor& entrance) return rails; } +// 007dad80 Notes the collectibles a main player (and the dead Lazarus kept as its backup) gets back after Genesis or +// Greed's reset: its quest items, and Pentagram for the Book of Belial's passive. Its other items picked up on a +// floor go back to their pools and add to Genesis's count of their pool. A co-op ghost notes nothing. +void greed_reset_collectibles_collect(Entity_Player& player) +{ + for (Entity_Player* current = &player; current; current = current->backupPlayer) + { + current->greedResetCollectibles.clear(); + if (current->variant != PLAYER_VARIANT_PLAYER || current->isCoopGhost) return; + for (HistoryItem& item : current->history.historyItems) + { + ItemConfig_Item* config = g_manager->itemConfig.GetCollectible(item.id); + + if (item.isTrinket || item.itemPoolType == -1) continue; + if (config && config->HasTags(TAG_QUEST)) current->greedResetCollectibles.push_back(item.id); + else if (item.time > 0) + { + g_game->itemPool.ResetCollectible(item.id); + g_game->itemPool.remainingGenesisItems[item.itemPoolType]++; + } + } + if (current->HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) + current->greedResetCollectibles.push_back(COLLECTIBLE_PENTAGRAM); + if (!current->isValid) return; + } +} + +// 007db3b0 Resets a player as Genesis and Greed do: its familiars removed, its weapons dropped, its entity started anew +// with its controller and damage taken kept, then its noted collectibles given back, and the twin's or backup's noted +// collectibles given back to it. Tainted Lazarus' other side and Esau's form are put back first, the flipped Lazarus' +// own collectibles going to the other side. The player is hidden until the room shows it. +void player_greed_reset(Entity_Player& player) +{ + if (!player.isExists || !player.isValid) return; + + int controller = player.controllerIndex; + Entity_Player* other = player.twin_get() ? player.twin_get() : player.backupPlayer; + std::vector otherCollectibles; + + for (Entity* familiar : entity_query(ENTITY_FAMILIAR, -1)) + if (static_cast(familiar)->player == &player) familiar->Remove(); + if (other) otherCollectibles = std::exchange(other->greedResetCollectibles, {}); + if (player.playerType == PLAYER_LAZARUS2_B) + { + player.playerType = PLAYER_LAZARUS_B; + std::swap(otherCollectibles, player.greedResetCollectibles); + } + else if (player.playerType == PLAYER_JACOB2_B) player.playerType = PLAYER_JACOB_B; + player.release_weapons_and_effects(true); + + int totalDamageTaken = player.totalDamageTaken; + + player.Init(player.type, player.variant, player.playerType, player.initSeed); + player.SetControllerIndex(controller, false); + player.totalDamageTaken = totalDamageTaken; + if (player.twin_get()) player.twin_get()->SetControllerIndex(controller, false); + if (player.backupPlayer) player.backupPlayer->SetControllerIndex(controller, false); + player.ResetPlayer(); + if (Entity_Player* target = player.twin_get() ? player.twin_get() : player.backupPlayer; + target && !otherCollectibles.empty()) + { + target->greedResetCollectibles = std::move(otherCollectibles); + target->ResetPlayer(); + } + player.isVisible = false; + if (player.twin_get()) player.twin_get()->isVisible = false; +} + +// Part of 0073e0a0: the Genesis room entered the first time takes the floor's curses and every player's items away, +// each player started anew with only its noted collectibles, then the HUD's recent items are redrawn. +static void genesis_players_reset(Level& level) +{ + PlayerManager& players = g_game->playerManager; + std::vector playerList = players.playerList; + + level.RemoveCurses(UINT32_MAX); + players.isColorAssignEnabled = false; + for (Entity_Player* player : playerList) greed_reset_collectibles_collect(*player); + for (Entity_Player* player : playerList) player_greed_reset(*player); + players.isColorAssignEnabled = true; + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); +} + // 0073e0a0 Builds the room the players are in from its descriptor: Devil's Crown's devil treasure rooms, the treasure // room rerolls, Greed's takeover config and a door into rooms off the map first, then the room itself, its doors and // the special doors a cleared room spawns, the mineshaft entrance's bridged pits, Genesis's reset, and the players' @@ -2648,9 +2848,7 @@ void Level::load_room() if ((game.challenge == CHALLENGE_RED_REDEMPTION || currentDimensionIdx != DIMENSION_DEATH_CERTIFICATE) && isCorpse && room->backdropType != BACKDROP_CORPSE3) corpse_door_splats_spawn(*this); - if (currentRoomIdx == ROOM_GENESIS_IDX && room->descriptor->visitedCount == 1) - reconstruction_missing("Level::load_room 0073e0a0: Genesis's reset of the players (FUN_007dad80, " - "Game::reset_players_for_greed)"); + if (currentRoomIdx == ROOM_GENESIS_IDX && room->descriptor->visitedCount == 1) genesis_players_reset(*this); if (!game.deathmatchManager.is_active()) game.playerManager.enter_level(); room->fxLayers.Update(PLAYER_FOLLOW_SNAP); room->UpdateRedKey(); @@ -2768,10 +2966,231 @@ void Level::reveal_room_visibility(RoomDescriptor& target, RoomDescriptor* fromR if (target.flags & ROOM_DESCRIPTOR_FLAG_RED_ROOM) target.displayFlags |= ROOM_DISPLAY_BOX | ROOM_DISPLAY_ICON; } -// 00742ef0 Lays out an Ascent floor. +// 00742ef0 Lays out an Ascent floor from its depth's saved stage: fewer rooms the deeper (two more on hard, six more +// and the Labyrinth for an XL stage), drawn from the Ascent's rooms of the chapter's subtype (any difficulty when too +// few), grown again until it has two dead ends and its rooms fit. The original stops with no rooms when its first +// layout lacks the dead ends. This grows another. void Level::generate_backwards() { - reconstruction_missing("Level::generate_backwards 00742ef0"); + Game& game = *g_game; + int depth = stage_depth_get(); + bool isHard = game.difficulty == DIFFICULTY_HARD; + + if (depth < 1 || depth > BACKWARDS_STAGE_COUNT) log_printf(LOG_ASSERT, "Invalid backwards path stage ID"); + + BackwardsStageDesc& saved = game.backwardsStages[std::clamp(depth, 1, BACKWARDS_STAGE_COUNT) - 1]; + int roomCount = (isHard ? BACKWARDS_ROOMS_HARD : BACKWARDS_ROOMS) - depth; + + if (saved.isXL) + { + curses |= CURSE_OF_LABYRINTH; + roomCount += BACKWARDS_XL_ROOMS; + } + + LevelGenerator generator(generationRNG.Next()); + RoomQuery query = {.maxDifficulty = isHard ? DIFFICULTY_MAX : DIFFICULTY_HARD_MAX, + .minDifficulty = DIFFICULTY_EASY, + .stageId = STAGE_ID_BACKWARDS}; + std::vector rooms = game.roomConfig.GetRooms(query); + bool isAltStage = saved.stageType == STAGETYPE_REPENTANCE || saved.stageType == STAGETYPE_REPENTANCE_B; + int subtype = 0; + + if (stage >= 1 && stage <= ASCENT_LAST_STAGE) + subtype = (isAltStage ? BACKWARDS_ALT_SUBTYPES : BACKWARDS_SUBTYPES)[(stage - 1) / 2]; + if (rooms.size() < ROOM_POOL_MIN) + { + query.maxDifficulty = DIFFICULTY_MAX; + rooms = game.roomConfig.GetRooms(query); + } + + GenerationSettings settings = {.allowedShapes = 0, .deadEndCount = BACKWARDS_DEAD_ENDS}; + LevelGenerator_Room startRoom; + int retries = 0; + + for (RoomConfig_Room* config : rooms) + if (config->subtype == subtype) settings.allowedShapes |= 1u << config->shape; + startingRoomIdx = START_GRID_INDEX; + startRoom.position = START_POSITION; + for (;; retries++) + { + if (retries > RETRIES_LOGGED) log_printf(LOG_ASSERT, "failed to generate level too often, giving up\n"); + log_printf(LOG_INFO, "generate...\n"); + generator.blockedPositions = {}; + settings.roomCount = roomCount; + generator.Generate(settings, startRoom); + if ((int)generator.deadEnds.size() < BACKWARDS_DEAD_ENDS) + { + log_printf(LOG_INFO, "not enough dead ends (%d/%d)\n", (int)generator.deadEnds.size(), BACKWARDS_DEAD_ENDS); + if (retries + 1 > RETRIES_BEFORE_GROWTH && (retries + 1) % RETRY_GROWTH_PERIOD == 0 && + roomCount < ROOM_COUNT_RETRY_MAX) + roomCount++; + continue; + } + + log_printf(LOG_INFO, "placing rooms...\n"); + roomMap.fill(-1); + nbRooms = 0; + if (place_rooms_backwards(generator, saved, subtype, query.maxDifficulty)) break; + reset_room_list(false); + } + log_printf(LOG_INFO, "Map Generated in %d Loops\n", retries + 1); +} + +// 00741cf0 Clears what an Ascent room must not bring back from its stage: its doors and Gideon's stairs among its grid +// cells. Its trinkets come back as Cracked Keys once the Red Key is unlocked, and its items no longer blind. +static void backwards_room_sanitize(RoomDescriptor& desc) +{ + for (GridEntityDesc& grid : desc.savedGridEntities) + if (grid._type == GRID_DOOR || (grid._type == GRID_STAIRS && grid._variant == STAIRS_GIDEON)) + grid = GRID_SAVE_EMPTY; + for (EntitySaveState& saved : desc.savedEntities) + { + if (saved.type != ENTITY_PICKUP) continue; + if (saved.variant == PICKUP_COLLECTIBLE) saved.boolStorage2 = false; + if (saved.variant != PICKUP_TRINKET || !is_unlocked(ACHIEVEMENT_RED_KEY)) continue; + saved.variant = PICKUP_TAROTCARD; + saved.subtype = CARD_CRACKED_KEY; + } +} + +// Part of 00741e60: a saved room's state given back to its new descriptor, sanitized. +static void backwards_room_restore(RoomDescriptor& desc, const RoomDescriptor& saved) +{ + desc.flags = saved.flags; + desc.visitedCount = saved.visitedCount; + desc.savedGridEntities = saved.savedGridEntities; + desc.savedEntities = saved.savedEntities; + desc.restrictedGridIndexes = saved.restrictedGridIndexes; + desc.savedEffects = saved.savedEffects; + backwards_room_sanitize(desc); +} + +// Part of 00741e60: a second saved boss room beside the first, on the first spot of its shape around it that is free, +// touches at most one room and has only doors its config has. +static LevelGenerator_Room* backwards_boss_beside_place(LevelGenerator& generator, int previous, + RoomConfig_Room& config) +{ + for (LevelGenerator_Room& candidate : generator.get_neighbor_candidates(previous, CANDIDATE_SHAPES_ANY)) + { + if (candidate.shape != config.shape || !generator.can_place_room(candidate.position, candidate.shape)) continue; + if (generator.count_neighbor_rooms(candidate.linkPos) >= 2) continue; + generator.update_room_neighbors(candidate); + if ((candidate.doors & config.doors) == candidate.doors) return &generator.place_room(candidate); + } + return nullptr; +} + +// Part of 00741e60: the stage's boss rooms placed back, the last first and the second beside it, cleared and visited, +// with their own doors. With none saved, a boss of the stage is drawn as usual and its room is cleared. +static bool backwards_boss_rooms_place(Level& level, LevelGenerator& generator, BackwardsStageDesc& saved) +{ + RNG& rng = level.generationRNG; + int previous = -1; + + if (saved.bossRooms.empty()) + { + int bossId = g_game->bossPool.GetBossId((int)level.stage, (int)level.stageType); + RoomConfig_Room* config = Level::pick_boss_room_config(bossId, rng.Next()); + LevelGenerator_Room* room = nullptr; + + if (config) room = generator.place_boss_room(config->shape, config->doors, BOSS_ROOM_NEXT); + else log_printf(LOG_INFO, "[warn] could not find matching boss room (boss id: %d) for the current stage\n", + bossId); + if (!room) return false; + level.place_room(*room, config, rng.Next(), nullptr); + level.roomList[level.nbRooms - 1].flags = ROOM_DESCRIPTOR_FLAG_CLEAR; + level.roomList[level.nbRooms - 1].visitedCount = 1; + level.lastBossRoomListIdx = level.nbRooms - 1; + return true; + } + for (SavedRoom& bossRoom : saved.bossRooms | std::views::reverse) + { + RoomConfig_Room* config = room_config_ref_load(bossRoom.config, nullptr); + + if (!config) continue; + + LevelGenerator_Room* room = previous < 0 + ? generator.place_boss_room(config->shape, config->doors, BOSS_ROOM_NEXT) + : backwards_boss_beside_place(generator, previous, *config); + + if (!room) return false; + level.place_room(*room, config, rng.Next(), nullptr); + + RoomDescriptor& desc = level.roomList[level.nbRooms - 1]; + + backwards_room_restore(desc, bossRoom.desc); + desc.flags |= ROOM_DESCRIPTOR_FLAG_CLEAR; + desc.visitedCount = std::max(desc.visitedCount, 1); + desc.allowedDoors = config->doors; + generator.block_unused_door_cells(*room, config->doors); + level.lastBossRoomListIdx = level.nbRooms - 1; + previous = room->generationIndex; + } + return true; +} + +// The secret shop's level on the floors laid by hand, rolled twice by the store upgrades unlocked. +static int secret_shop_level_roll(RNG& shopRng) +{ + uint32_t level = + shopRng.RandomInt(1 + is_unlocked(ACHIEVEMENT_STORE_UPGRADE_2) + is_unlocked(ACHIEVEMENT_STORE_UPGRADE_4)); + + return (int)(level + shopRng.RandomInt(1 + is_unlocked(ACHIEVEMENT_STORE_UPGRADE_3))); +} + +// 00741e60 Places an Ascent floor's rooms on its layout: its boss rooms, its saved treasure rooms at the farthest dead +// ends, then the start room's trapdoor room and Ascent rooms of the chapter's subtype everywhere else, and the error +// room, black market, crawl space, the Member Card's shop and the angel shop. False when a room finds no place or +// config, for the layout to be grown again. A saved room whose config is gone is left out, where the original crashed. +bool Level::place_rooms_backwards(LevelGenerator& generator, BackwardsStageDesc& saved, int subtype, int maxDifficulty) +{ + if (!backwards_boss_rooms_place(*this, generator, saved)) return false; + for (SavedRoom& treasure : saved.treasureRooms | std::views::reverse) + { + RoomConfig_Room* config = room_config_ref_load(treasure.config, nullptr); + + if (!config) continue; + + LevelGenerator_Room* room = generator.GetNewEndRoom(config->shape, config->doors); + + if (!room) return false; + place_room(*room, config, generationRNG.Next(), nullptr); + backwards_room_restore(roomList[nbRooms - 1], treasure.desc); + } + for (LevelGenerator_Room* room : generator.get_all_rooms()) + { + bool isStart = room->position == START_POSITION && room->distanceFromStart == 0; + RoomQuery query = {.requiredDoors = room->doors, + .shape = room->shape, + .maxDifficulty = isStart ? 0 : maxDifficulty, + .minDifficulty = isStart ? 0 : DIFFICULTY_EASY, + .stageId = STAGE_ID_BACKWARDS, + .subtype = isStart ? 0 : subtype}; + RoomConfig_Room* config = random_room_get(generationRNG.Next(), query); + + if (!config && !isStart) + log_printf(LOG_INFO, "failed to get room %s %s %d\n", + g_game->roomConfig.stages[STAGE_ID_BACKWARDS].GetDisplayName(LANGUAGE_CURRENT).c_str(), + room_type_name(ROOM_DEFAULT).data(), subtype); + if (!config) return false; + place_room(*room, config, generationRNG._seed, nullptr); + } + + RoomQuery normalQuery = room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_BLACK_MARKET, -1); + + normalQuery.mode = ROOM_MODE_NORMAL; + off_map_room_init(*this, ROOM_ERROR_IDX, generationRNG, room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_ERROR, -1)); + off_map_room_init(*this, ROOM_BLACK_MARKET_IDX, generationRNG, normalQuery); + normalQuery.type = ROOM_DUNGEON; + off_map_room_init(*this, ROOM_DUNGEON_IDX, generationRNG, normalQuery); + + RNG shopRng = {generationRNG.Next(), 3, 3, 26}; + + off_map_room_init(*this, ROOM_SECRET_SHOP_IDX, generationRNG, + room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_SHOP, secret_shop_level_roll(shopRng))); + generationRNG.Next(); + off_map_room_init(*this, ROOM_ANGEL_SHOP_IDX, generationRNG, room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_ANGEL, 1)); + return true; } // A room the Blue Womb lays by hand: its cell, shape, the cell it joins the start room through and from which side, @@ -2843,12 +3262,9 @@ void Level::generate_blue_womb() off_map_room_init(*this, ROOM_THE_VOID_IDX, generationRNG, voidQuery); RNG shopRng = {generationRNG.Next(), 3, 3, 26}; - uint32_t lowLevel = - shopRng.RandomInt(1 + is_unlocked(ACHIEVEMENT_STORE_UPGRADE_2) + is_unlocked(ACHIEVEMENT_STORE_UPGRADE_4)); - uint32_t highLevel = shopRng.RandomInt(1 + is_unlocked(ACHIEVEMENT_STORE_UPGRADE_3)); off_map_room_init(*this, ROOM_SECRET_SHOP_IDX, generationRNG, - room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_SHOP, (int)(lowLevel + highLevel))); + room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_SHOP, secret_shop_level_roll(shopRng))); generationRNG.Next(); off_map_room_init(*this, ROOM_ANGEL_SHOP_IDX, generationRNG, room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_ANGEL, 1)); } @@ -2917,10 +3333,162 @@ void Level::generate_home_level() roomConfig.GetRoomByStageTypeAndVariant(STAGE_ID_HOME, ROOM_DUNGEON, BEAST_ROOM_VARIANT, ROOM_MODE_CURRENT); } -// 007508c0 Lays out a Red Redemption floor. +// A free cell of a layout drawn at random, the grid's edge left out, or the last cell drawn once the tries run out. +static XY random_cell_find(LevelGenerator& generator, RNG& rng, int tries) +{ + XY cell; + + for (int i = 0; i < tries; i++) + { + cell.y = (int)(rng.Next() % RANDOM_CELL_SPAN) + 1; + cell.x = (int)(rng.Next() % RANDOM_CELL_SPAN) + 1; + if (generator.can_place_room(cell, ROOMSHAPE_1x1)) break; + } + return cell; +} + +// Whether a Red Redemption floor has a cluster for a step: all of them but on the Womb I, which has a single boss room, +// and its treasure rooms only with Bloody Crown and its shop only with Silver Dollar. +static bool is_random_cluster_placed(Level& level, int step) +{ + PlayerManager& players = g_game->playerManager; + + if (level.stage != STAGE_WOMB_I) return true; + switch (step) + { + case RANDOM_STEP_SECOND_BOSS: + return false; + case RANDOM_STEP_TREASURE: + case RANDOM_STEP_SECOND_TREASURE: + return players.AnyoneHasTrinket(TRINKET_BLOODY_CROWN); + case RANDOM_STEP_SHOP: + return players.AnyoneHasTrinket(TRINKET_SILVER_DOLLAR); + } + return true; +} + +// Part of 0074fbe0: one cluster of a Red Redemption floor, its special room at a random free cell (Mother's on the +// Womb I) with a few normal rooms of any stage type grown around it, its unused doors and the cells beside it blocked +// for the clusters after it. A special room with no config is left out, where the original crashed. +static void random_cluster_place(Level& level, LevelGenerator& generator, int step) +{ + RNG& rng = level.generationRNG; + LevelGenerator cluster(rng.Next()); + bool isBoss = step < RANDOM_STEP_TREASURE; + + cluster.blockedPositions = generator.blockedPositions; + + XY position = random_cell_find(cluster, rng, RANDOM_CELL_TRIES); + int stageType = level.GetRoomStageType(position.ToGridIdx()); + RoomConfig_Room* config; + + if (isBoss) + { + bool isMother = step == RANDOM_STEP_BOSS && level.stage == STAGE_WOMB_I; + int bossId = isMother ? BOSS_MOTHER : g_game->bossPool.GetBossId((int)level.stage, stageType); + + config = Level::pick_boss_room_config(bossId, rng.Next()); + } + else + { + int stageId = RoomConfig::GetStageID((int)level.stage, stageType, ROOM_MODE_CURRENT); + RoomQuery query = room_query(stageId, step == RANDOM_STEP_SHOP ? ROOM_SHOP : ROOM_TREASURE, -1); + + config = g_game->roomConfig.GetRandomRoomWithFallbackStage(rng.Next(), WEIGHT_REDUCE, query, + STAGE_ID_SPECIAL_ROOMS); + } + if (!config) return; + + LevelGenerator_Room slot; + + slot.position = position; + slot.shape = config->shape; + + LevelGenerator_Room& special = cluster.place_room(slot); + + cluster.update_dead_end_lists(); + level.place_room(special, config, rng.Next(), nullptr); + if (isBoss) level.lastBossRoomListIdx = level.nbRooms - 1; + for (int door = 0; door < DOOR_SLOT_COUNT; door++) + { + XY beside = Level::get_door_neighbor_pos(special.position, special.shape, door); + + if (!(config->doors >> door & 1) && beside != XY_NONE) cluster.block_cell(beside); + } + + LevelGenerator_Room startRoom = special; + int roomCount = isBoss ? (int)(rng.Next() & 3) + 3 : (int)(rng.Next() % 3) + 1; + + cluster.Generate({.allowedShapes = RANDOM_LAYOUT_SHAPES, .roomCount = roomCount}, startRoom); + + std::vector rooms = cluster.get_all_rooms(); + + for (size_t i = 1; i < rooms.size(); i++) + { + LevelGenerator_Room& room = *rooms[i]; + int roomStageType = level.GetRoomStageType(room.position.ToGridIdx()); + RoomQuery query = room_query(RoomConfig::GetStageID((int)level.stage, roomStageType, ROOM_MODE_CURRENT), + ROOM_DEFAULT, 0); + + query.maxDifficulty = DIFFICULTY_MAX; + query.shape = room.shape; + for (int door = 0; door < DOOR_SLOT_COUNT; door++) + if (LevelGenerator::has_shape_slot(room.shape, door, THIN_SHAPES_IGNORED)) + query.requiredDoors |= 1u << door; + if (RoomConfig_Room* data = random_room_get(rng.Next(), query)) + level.place_room(room, data, rng._seed, nullptr); + } + generator.block_cells_near_rooms(cluster); +} + +// 0074fbe0 Lays a Red Redemption floor out as clusters on a cleared map, one per special room: two boss rooms, two +// treasure rooms and a shop. Always true, the check of the original's growth always passing. +bool Level::try_place_random_room(LevelGenerator& generator) +{ + roomMap.fill(-1); + nbRooms = 0; + generator.blockedPositions = {}; + lastBossRoomListIdx = 0; + for (int step = 0; step < RANDOM_STEP_COUNT; step++) + if (is_random_cluster_placed(*this, step)) random_cluster_place(*this, generator, step); + return true; +} + +// 007508c0 Lays out a Red Redemption floor: its clusters, the start room at a free cell between them, then the rooms +// off the map, the error room, black market, crawl space, the Member Card's shop and the angel shop, and on the Womb I +// the Corpse's Mother room as the secret exit. void Level::generate_random_layout() { - reconstruction_missing("Level::generate_random_layout 007508c0"); + LevelGenerator generator(generationRNG.Next()); + + while (!try_place_random_room(generator)); + + LevelGenerator_Room start; + + start.position = random_cell_find(generator, generationRNG, std::numeric_limits::max()); + + LevelGenerator_Room* startRoom = generator.CreateRoom(start); + RoomConfig_Room* startConfig = g_game->roomConfig.GetRoomByStageTypeAndVariant( + STAGE_ID_SPECIAL_ROOMS, ROOM_DEFAULT, START_ROOM_VARIANT, ROOM_MODE_CURRENT); + + place_room(*startRoom, startConfig, generationRNG.Next(), nullptr); + startingRoomIdx = start.position.ToGridIdx(); + off_map_room_init(*this, ROOM_ERROR_IDX, generationRNG, room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_ERROR, -1)); + off_map_room_init(*this, ROOM_BLACK_MARKET_IDX, generationRNG, + room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_BLACK_MARKET, -1)); + off_map_room_init(*this, ROOM_DUNGEON_IDX, generationRNG, room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_DUNGEON, -1)); + + RNG shopRng = {generationRNG.Next(), 3, 3, 26}; + + off_map_room_init(*this, ROOM_SECRET_SHOP_IDX, shopRng, + room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_SHOP, secret_shop_level_roll(shopRng))); + + RNG angelRng = {generationRNG.Next(), 3, 3, 28}; + + off_map_room_init(*this, ROOM_ANGEL_SHOP_IDX, angelRng, room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_ANGEL, 1)); + if (stage != STAGE_WOMB_I) return; + generationRNG.Next(); + off_map_room_init(*this, ROOM_SECRET_EXIT_IDX, generationRNG, room_query(STAGE_ID_CORPSE, ROOM_BOSS, BOSS_MOTHER)); } // 0074f0c0 Lays out the mirror world on dimension 1: a copy of every room of the floor with its decoration seed, but @@ -2997,34 +3565,158 @@ void Level::generate_mineshaft() currentRoomMap = roomMap.data(); } -// 00751650 Lays out the Death Certificate area. +// Part of 00751650: rolls each spawn of a Death Certificate room, every collectible it lands on becoming the next +// available item's pedestal (an options group of one) while items are left, its cell then left out of the room's own +// spawns. +static void dark_closet_items_place(RoomDescriptor& desc, RNG& rng, const std::vector& items, size_t& nextItem) +{ + RoomConfig_Room& data = *desc.data; + int gridWidth = data.width + 2; + + for (RoomSpawn& spawn : data.spawns) + { + float roll = rng.RandomFloat(); + int cell = spawn.x + 1 + (spawn.y + 1) * gridWidth; + RoomEntry* entry = spawn.entries.empty() ? nullptr : spawn.PickEntry(roll); + + if (!entry || entry->type != ENTITY_PICKUP || entry->variant != PICKUP_COLLECTIBLE) continue; + if (nextItem < items.size()) + { + EntitySaveState& item = desc.savedEntities.emplace_back(); + ItemConfig_Item* config = g_manager->itemConfig.GetCollectible(items[nextItem]); + + item.type = ENTITY_PICKUP; + item.variant = PICKUP_COLLECTIBLE; + item.subtype = items[nextItem++]; + item.intStorage2 = config ? (uint32_t)config->initCharge : 0; + item.targetPosition = vector_make((float)(cell % gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_X, + (float)(cell / gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_Y); + item.dropSeed = rng.Next(); + item.initSeed = rng.Next(); + item.intStorage7 = DARK_CLOSET_OPTIONS_INDEX; + item.floatStorage1 = std::bit_cast(g_game->itemPool.GetFirstItemPoolForCollectible(item.subtype)); + } + desc.restrictedGridIndexes.insert(cell); + } +} + +// 00751650 Lays out the Death Certificate's floor on dimension 2 from Home's closet rooms: a layout of 50 rooms grown +// from the start closet, each room drawn from the stage's seed and its collectible spawns holding every available +// item in order (all but Dad's Note and Death Certificate), until the items run out. A room with no config is left +// out, where the original crashed. void Level::generate_dark_closet() { - reconstruction_missing("Level::generate_dark_closet 00751650"); + Game& game = *g_game; + RoomConfig& roomConfig = game.roomConfig; + int savedDimension = currentDimensionIdx; + RNG rng{}; + + currentDimensionIdx = DIMENSION_DEATH_CERTIFICATE; + currentRoomMap = roomMap.data() + DIMENSION_DEATH_CERTIFICATE * LEVEL_GRID_CELLS; + roomConfig.ResetRoomWeights(STAGE_ID_HOME, ROOM_MODE_NORMAL); + rng.SetSeed(game.seedEffects.GetStageSeed(stage_depth_get()), DARK_CLOSET_SHIFT_INDEX); + + LevelGenerator generator(generationRNG.Next()); + RoomQuery query = {.mode = ROOM_MODE_NORMAL, + .maxDifficulty = DIFFICULTY_MAX, + .minDifficulty = DIFFICULTY_EASY, + .stageId = STAGE_ID_HOME, + .subtype = DARK_CLOSET_SUBTYPE}; + GenerationSettings settings = {.allowedShapes = 0, .roomCount = DARK_CLOSET_ROOM_COUNT}; + std::vector items; + + for (RoomConfig_Room* config : roomConfig.GetRooms(query)) settings.allowedShapes |= 1u << config->shape; + for (std::unique_ptr& item : g_manager->itemConfig.collectibles) + { + bool isLeftOut = item && (item->id == COLLECTIBLE_DADS_NOTE || item->id == COLLECTIBLE_DEATH_CERTIFICATE); + + if (item && !isLeftOut && item->IsAvailableEx(AVAILABLE_RUN_RULES | AVAILABLE_UNLOCKED)) + items.push_back(item->id); + } + + LevelGenerator_Room startRoom; + int firstNewRoom = nbRooms; + size_t nextItem = 0; + + log_printf(LOG_INFO, "generate...\n"); + for (XY cell : DARK_CLOSET_BLOCKED) generator.block_cell(cell); + startRoom.position = DARK_CLOSET_START; + startRoom.shape = ROOMSHAPE_IH; + generator.Generate(settings, startRoom); + log_printf(LOG_INFO, "placing rooms...\n"); + std::fill_n(currentRoomMap, LEVEL_GRID_CELLS, -1); + for (LevelGenerator_Room* room : generator.get_all_rooms()) + { + if (room->shape == ROOMSHAPE_IH && room->position == DARK_CLOSET_START) + { + RoomConfig_Room* data = roomConfig.GetRoomByStageTypeAndVariant( + STAGE_ID_HOME, ROOM_DEFAULT, DARK_CLOSET_START_VARIANT, ROOM_MODE_NORMAL); + if (data) place_room(*room, data, rng.Next(), nullptr); + } + else + { + RoomQuery roomQuery = query; + + roomQuery.requiredDoors = room->doors; + roomQuery.shape = room->shape; + roomQuery.maxDifficulty = DIFFICULTY_HARD_MAX; + + RoomConfig_Room* data = roomConfig.GetRandomRoom(rng.Next(), WEIGHT_REDUCE, roomQuery); + uint32_t seed = rng.Next(); + + if (!data) continue; + place_room(*room, data, seed, nullptr); + dark_closet_items_place(roomList[nbRooms - 1], rng, items, nextItem); + } + if (nextItem >= items.size()) break; + } + log_printf(LOG_INFO, "Dark Closet Generated in %d Loops\n", 1); + for (int i = firstNewRoom; i < nbRooms; i++) update_room_doors(roomList[i]); + currentDimensionIdx = savedDimension; + currentRoomMap = roomMap.data() + savedDimension * LEVEL_GRID_CELLS; } -// 007515c0 Enters the Death Certificate area. +// 007515c0 Death Certificate: away from its floor, lays the floor out the first time, remembers where the players +// are to come back to, and takes them to its start closet. void Level::enter_dark_closet() { - reconstruction_missing("Level::enter_dark_closet 007515c0"); + if (currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE) return; + if (!GetRoomByIdx(DARK_CLOSET_START_IDX, DIMENSION_DEATH_CERTIFICATE)->data) generate_dark_closet(); + deathCertificateReturn = {.lastRoomIdx = lastRoomIdx, + .leaveDoor = leaveDoor, + .roomIdx = currentRoomIdx, + .dimension = (uint8_t)currentDimensionIdx, + .lastRoomDimension = (uint8_t)lastRoomDimensionIdx}; + leaveDoor = DOOR_NONE; + g_game->StartRoomTransition({.animation = TRANSITION_DEATH_CERTIFICATE, + .dimension = DIMENSION_DEATH_CERTIFICATE, + .roomIndex = DARK_CLOSET_START_IDX}); } -// 0074f820 Seeds Red Redemption's stage type noise. -void Level::InitStageSeeds() +// 007523e0 The stage and stage type the extra boss room (Reverse Emperor's) draws its boss for: two stages deeper, but +// Depths I from Caves II and the Womb I past the Depths, one deeper in Greed up to its Womb, the Womb's second +// alternate type taken as its first. False past the Blue Womb (past Sheol in Greed). +bool Level::boss_count_adjust(int& bossStage, int& bossStageType) { - reconstruction_missing("Level::InitStageSeeds 0074f820"); -} - -// 0074fbe0 Places one room of a Red Redemption floor. -bool Level::try_place_random_room(LevelGenerator&) -{ - reconstruction_missing("Level::try_place_random_room 0074fbe0"); -} - -// 007523e0 Adjusts the stage a boss count is read for. -bool Level::boss_count_adjust(int&, int&) -{ - reconstruction_missing("Level::boss_count_adjust 007523e0"); + if (is_greed()) + { + if (bossStage > STAGE_GREED_SHEOL) return false; + if (bossStage < GREED_STAGE_WOMB && ++bossStage < GREED_STAGE_WOMB) return true; + } + else + { + if (bossStage > STAGE_BLUE_WOMB) return false; + if (bossStage < STAGE_WOMB_I) bossStage += 2; + if (bossStage == STAGE_DEPTHS_II) + { + bossStage = STAGE_DEPTHS_I; + return true; + } + if (bossStage < STAGE_WOMB_I) return true; + bossStage = STAGE_WOMB_I; + } + if (bossStageType == STAGETYPE_REPENTANCE_B) bossStageType = STAGETYPE_REPENTANCE; + return true; } // 0073fa20 Enters a room config directly, for debugging. @@ -3277,10 +3969,20 @@ int Level::GetNeighborRoomIdx(int roomIdx, int doorSlot) return neighbor < 0 ? -2 : neighbor; } -// 0074d780 Adds a second boss room. -bool Level::TryInitializeExtraBossRoom(uint32_t) +// 0074d780 Reverse Emperor: lays the extra boss room off the map once, its boss drawn for the stage boss_count_adjust +// gives, seeded from seed. False when it was laid already, the floor is too deep or no boss room fits. +bool Level::TryInitializeExtraBossRoom(uint32_t seed) { - reconstruction_missing("Level::TryInitializeExtraBossRoom 0074d780"); + RoomDescriptor& extra = *GetRoomByIdx(ROOM_EXTRA_BOSS_IDX); + int bossStage = (int)stage; + int bossStageType = (int)stageType; + RNG rng{}; + + if (extra.data || !boss_count_adjust(bossStage, bossStageType)) return false; + rng.SetSeed(seed, EXTRA_BOSS_SHIFT_INDEX); + extra.InitSeeds(rng); + extra.data = pick_boss_room_config(g_game->bossPool.GetBossId(bossStage, bossStageType), rng.Next()); + return extra.data; } // 0074d920 Devil's Crown taken or dropped: the floor's unvisited treasure rooms (only the Greed mode's own in Greed) @@ -3325,7 +4027,6 @@ void Level::update_treasure_room_doors_for_trinket() // 0074beb0 Draws Rotgut's two dungeon rooms (dungeon subtypes 2 and 3) from the stage's seed, each once. void Level::init_rotgut_dungeon_room() { - constexpr int ROTGUT_FIRST_SUBTYPE = 2; constexpr uint32_t ROTGUT_RNG_SHIFT1 = 5; constexpr uint32_t ROTGUT_RNG_SHIFT2 = 27; constexpr uint32_t ROTGUT_FIRST_SHIFT = 8; @@ -3340,15 +4041,23 @@ void Level::init_rotgut_dungeon_room() RNG rng = {seed, ROTGUT_RNG_SHIFT1, ROTGUT_RNG_SHIFT2, i == 0 ? ROTGUT_FIRST_SHIFT : ROTGUT_SECOND_SHIFT}; desc.InitSeeds(rng); - RoomQuery query = {.stageId = 0, .subtype = ROTGUT_FIRST_SUBTYPE + i, .type = ROOM_DUNGEON}; + RoomQuery query = {.stageId = 0, .subtype = DUNGEON_ROTGUT + i, .type = ROOM_DUNGEON}; desc.data = g_game->roomConfig.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); } } -// 008e11b0 Sets up Genesis's room. +// 0074bce0 The Genesis room made anew: a fresh descriptor with an Isaac's room of the special rooms' subtype 99, +// seeded from the devil room's generator. 008e11b0, which REPENTOGON names so, is the online lobby's join handler. void Level::InitializeGenesisRoom() { - reconstruction_missing("Level::InitializeGenesisRoom 008e11b0"); + RoomDescriptor& genesis = *GetRoomByIdx(ROOM_GENESIS_IDX); + RNG rng = {devilAngelRoomRNG._seed, 3, 3, 26}; + RoomQuery query = {.stageId = STAGE_ID_SPECIAL_ROOMS, .subtype = GENESIS_ROOM_SUBTYPE, .type = ROOM_ISAACS}; + + genesis = RoomDescriptor{}; + genesis.listIndex = ROOM_GENESIS_IDX; + genesis.InitSeeds(rng); + genesis.data = g_game->roomConfig.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); } // 00748760 Whether a challenge room's door opens: once its challenge is done, for a boss challenge while every player @@ -3378,10 +4087,71 @@ bool Level::CanOpenChallengeRoom(int roomIdx) (desc.flags & ROOM_DESCRIPTOR_FLAG_RED_ROOM); } -// 007481d0 Forces a horseman boss. -bool Level::ForceHorsemanBoss(uint32_t) +// The Horseman the floor's first boss room may take, none past its chapter's: Famine, Pestilence and War on the first +// three chapters' floors, and on the Womb I (not over Mother) Death, or Conquest half the time once unlocked. A rolled +// Horseman draws from the generation RNG. +static int horseman_pick(Level& level, RoomConfig_Room& bossRoom) { - reconstruction_missing("Level::ForceHorsemanBoss 007481d0"); + std::bitset& removed = g_game->bossPool.removedBosses; + + switch (level.stage) + { + case STAGE_BASEMENT_I: + case STAGE_BASEMENT_II: + return removed.test(BOSS_FAMINE) ? 0 : BOSS_FAMINE; + case STAGE_CAVES_I: + case STAGE_CAVES_II: + return removed.test(BOSS_PESTILENCE) ? 0 : BOSS_PESTILENCE; + case STAGE_DEPTHS_I: + return removed.test(BOSS_WAR) ? 0 : BOSS_WAR; + case STAGE_WOMB_I: + if (bossRoom.subtype == BOSS_MOTHER || removed.test(BOSS_DEATH)) return 0; + return (level.generationRNG.Next() & 1) == 0 && is_unlocked(ACHIEVEMENT_FORGOTTEN_HORSEMAN) ? BOSS_CONQUEST + : BOSS_DEATH; + } + return 0; +} + +// 007481d0 Book of Revelations: the floor's boss room becomes a Horseman's of the same shape and doors, drawn from +// seed, when it is not visited yet and no other boss room holds a Horseman already. The Horseman is removed from the +// boss pools (Conquest with Death). Not on the alternate path or the Ascent. True when a room was picked, even if no +// Horseman's room fits it. +bool Level::ForceHorsemanBoss(uint32_t seed) +{ + BossPool& bossPool = g_game->bossPool; + int roomListIdx = -1; + int horseman = 0; + + if (IsAltPath() || IsAscent()) return false; + for (int i = 0; i < nbRooms; i++) + { + RoomConfig_Room& data = *roomList[i].data; + + if (data.type != ROOM_BOSS) continue; + if (roomListIdx >= 0) + { + if (std::ranges::count(HORSEMAN_BOSSES, data.subtype)) roomListIdx = -1; + } + else if (int picked = horseman_pick(*this, data)) + { + horseman = picked; + roomListIdx = i; + } + } + if (roomListIdx < 0 || roomList[roomListIdx].visitedCount != 0) return false; + + RoomDescriptor& desc = roomList[roomListIdx]; + RoomQuery query = room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_BOSS, horseman); + + query.shape = desc.data->shape; + query.requiredDoors = desc.data->doors; + if (RoomConfig_Room* data = random_room_get(seed, query)) + { + desc.data = data; + bossPool.removedBosses.set(horseman); + if (horseman == BOSS_CONQUEST) bossPool.removedBosses.set(BOSS_DEATH); + } + return true; } // 00749830 Whether the floor's last boss room may open a deal door: not in Red Redemption, Mausoleum II, before the @@ -3395,13 +4165,13 @@ bool Level::CanSpawnDevilRoom() int labyrinthStage = (int)stage_with_labyrinth(*this); bool isAltStage = stageType == STAGETYPE_REPENTANCE || stageType == STAGETYPE_REPENTANCE_B; bool isMausoleumTwo = !is_greed() && isAltStage && labyrinthStage == (int)STAGE_WOMB_II; - bool isBackwards = stage - 1 < ASCENT_LAST_STAGE && game_flag_get(LEVEL_GAME_STATE_BACKWARDS_PATH); + bool isBackwards = stage - 1 < ASCENT_LAST_STAGE && game_flag_get(GAME_STATE_BACKWARDS_PATH); if (isMausoleumTwo || IsPreAscent() || isBackwards) return false; int dealStage = labyrinthStage + (isAltStage ? 1 : 0); if (!is_greed()) { - if (dealStage == (int)STAGE_BASEMENT_I && game.dailyChallenge._specialDailyId != SPECIAL_DAILY_DEALS) + if (dealStage == (int)STAGE_BASEMENT_I && game.dailyChallenge.specialDailyId != SPECIAL_DAILY_DEALS) return false; if (dealStage != (int)STAGE_BASEMENT_I && dealStage > (int)STAGE_WOMB_II) return false; if (dealStage == (int)STAGE_DEPTHS_II && !is_unlocked(ACHIEVEMENT_THE_WOMB)) return false; @@ -3492,7 +4262,7 @@ void Level::InitializeDevilAngelRoom(bool isForceAngel, bool isForceDevil) uint32_t odds = 0; if (game.gameStateFlags & (1ull << GAME_STATE_DEVILROOM_VISITED | 1ull << GAME_STATE_KRAMPUS_SPAWNED)) odds = game.devilRoomDeals > 0 ? KRAMPUS_ODDS_DEAL : KRAMPUS_ODDS_VISITED; - bool isDealsDaily = game.dailyChallenge._specialDailyId == SPECIAL_DAILY_DEALS; + bool isDealsDaily = game.dailyChallenge.specialDailyId == SPECIAL_DAILY_DEALS; if (isDealsDaily) odds += KRAMPUS_ODDS_DEALS_DAILY; if (devilAngelRoomRNG.Next() % KRAMPUS_ROLL >= odds || query.minVariant >= DEAL_VARIANT_WOMB) return; @@ -3617,7 +4387,7 @@ bool Level::UpdateBackwardsPathStages() if (data && data->type == ROOM_DUNGEON && data->stageId == STAGE_ID_HOME) return false; int floor = (int)game.stage; bool isAscentFloor = floor >= (int)STAGE_BASEMENT_I && floor <= (int)ASCENT_LAST_STAGE; - if (isAscentFloor && (game.gameStateFlags >> LEVEL_GAME_STATE_BACKWARDS_PATH & 1)) + if (isAscentFloor && (game.gameStateFlags >> GAME_STATE_BACKWARDS_PATH & 1)) { bool isAltPath = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; int first = floor + (isAltPath ? 1 : 0); diff --git a/src/level.h b/src/level.h index 474e455..7ee9d2a 100644 --- a/src/level.h +++ b/src/level.h @@ -20,6 +20,8 @@ constexpr int GREED_WAVE_SEED_COUNT = 12; // Greed mode's boss wave, one later in Greedier, and its normal waves, one more in Greedier. constexpr int GREED_BOSS_WAVE = 9; constexpr int GREED_WAVES = 10; +// The Greed floor the shop is. +constexpr int GREED_STAGE_SHOP = 5; constexpr int VENTRICLE_RAZOR_PORTAL_COUNT = 2; constexpr int PORTAL_ROOM_NONE = -99999; @@ -105,17 +107,6 @@ enum LevelStateFlag : int LEVEL_STATE_LAST = 25 }; -// The run's state flags (Lua's GameStateFlag) a floor checks, by bit: a book picked up, the per floor coin cap, the -// Mausoleum heart's room and its kill, and the Ascent. -enum LevelGameStateFlag : int -{ - LEVEL_GAME_STATE_BOOK_PICKED_UP = 8, - LEVEL_GAME_STATE_MAX_COINS_OBTAINED = 44, - LEVEL_GAME_STATE_MAUSOLEUM_HEART_ROOM = 46, - LEVEL_GAME_STATE_MAUSOLEUM_HEART_KILLED = 47, - LEVEL_GAME_STATE_BACKWARDS_PATH = 48 -}; - // A stage's variant (Lua's StageType): the original chapter, its two alternates, Greed's, and Repentance's two. enum StageType : uint32_t { @@ -221,10 +212,13 @@ struct DimensionReturn int lastRoomIdx = 0; int leaveDoor = -1; int roomIdx = 0; - int8_t dimension = 0; - int8_t lastRoomDimension = 0; + uint8_t dimension = 0; + uint8_t lastRoomDimension = 0; }; +// The two noise maps Red Redemption mixes its stage types from, one value per map cell. +using StageTypeNoise = std::array, 2>; + // 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. @@ -239,6 +233,7 @@ public: std::array greedWaveSeeds{}; std::array ventricleRazorPortals{}; std::vector myosotisPickups; + StageTypeNoise stageTypeNoise{}; DimensionReturn deathCertificateReturn; std::unique_ptr room; int* currentRoomMap = nullptr; @@ -282,6 +277,7 @@ public: bool place_special_rooms(LevelGenerator& generator, int minDifficulty, int maxDifficulty); bool place_room(const LevelGenerator_Room& slot, RoomConfig_Room* data, uint32_t seed, RoomDescriptor** outDesc); void generate_backwards(); + bool place_rooms_backwards(LevelGenerator& generator, BackwardsStageDesc& saved, int subtype, int maxDifficulty); void generate_greed(); void generate_blue_womb(); void generate_home_level(); @@ -385,3 +381,5 @@ public: }; float get_angel_room_chance(); +void greed_reset_collectibles_collect(Entity_Player& player); +void player_greed_reset(Entity_Player& player); diff --git a/src/level_generator.h b/src/level_generator.h index ebe3421..5bd55db 100644 --- a/src/level_generator.h +++ b/src/level_generator.h @@ -138,15 +138,16 @@ public: static XY get_door_target_position(XY position, RoomShape shape, int doorSlot, ThinShapes thinShapes); static std::span get_room_placement_offsets(RoomShape shape); -private: - void generate_rooms(int roomCount, const LevelGenerator_Room& startRoom); std::vector get_neighbor_candidates(int generationIndex, CandidateShapes candidateShapes); LevelGenerator_Room& place_room(const LevelGenerator_Room& room); bool can_place_room(XY position, RoomShape shape); - bool is_placement_valid(XY position, RoomShape shape); int count_neighbor_rooms(XY position); - bool try_resize_room(LevelGenerator_Room& room, RoomShape shape, uint32_t possibleDoors); void update_room_neighbors(LevelGenerator_Room& room); - void mark_dead_ends(); void update_dead_end_lists(); + +private: + void generate_rooms(int roomCount, const LevelGenerator_Room& startRoom); + bool is_placement_valid(XY position, RoomShape shape); + bool try_resize_room(LevelGenerator_Room& room, RoomShape shape, uint32_t possibleDoors); + void mark_dead_ends(); }; diff --git a/src/level_red_room.cpp b/src/level_red_room.cpp index 08e44e1..77afd49 100644 --- a/src/level_red_room.cpp +++ b/src/level_red_room.cpp @@ -192,7 +192,7 @@ int Level::roll_red_room_type(RNG& rng) bool isPlanetariumLocked = !g_manager->persistentGameData.achievements[ACHIEVEMENT_PLANETARIUMS] && - (g_manager->state != MANAGER_STATE_GAME || (g_game->dailyChallenge._id == 0 && !g_game->isDebug)); + (g_manager->state != MANAGER_STATE_GAME || (g_game->dailyChallenge.id == 0 && !g_game->isDebug)); if (type == ROOM_PLANETARIUM && isPlanetariumLocked) return ROOM_TREASURE; if (type == ROOM_ANGEL && g_game->devilRoomDeals > 0) return ROOM_DEVIL; return type; diff --git a/src/level_stage.cpp b/src/level_stage.cpp index d2b3b23..901e1b3 100644 --- a/src/level_stage.cpp +++ b/src/level_stage.cpp @@ -172,7 +172,7 @@ void Level::SetNextStage() if (game.IsGreedMode()) return greed_stage_set(*this, nextStage); if (nextStage == STAGE_HOME) return SetStage(nextStage, nextStageType); - bool isRepentanceChallenge = (game.challenge != 0 || game.dailyChallenge._id != 0) && + bool isRepentanceChallenge = (game.challenge != 0 || game.dailyChallenge.id != 0) && game.GetChallengeParams().pathType == PATH_TYPE_REPENTANCE && game.challenge != CHALLENGE_RED_REDEMPTION; bool isAltStage = is_repentance_type(game.stageType); diff --git a/src/log.h b/src/log.h index 7c37990..50bcc2e 100644 --- a/src/log.h +++ b/src/log.h @@ -4,6 +4,9 @@ #include #include +// The longest message a log line or a driver message holds. +constexpr int MESSAGE_LENGTH = 1024; + // The levels KAGE_LogMessage prints with, each with its own prefix. enum LogLevel : unsigned int { diff --git a/src/lua_api_entity.cpp b/src/lua_api_entity.cpp index 3adc9e9..e6fd28d 100644 --- a/src/lua_api_entity.cpp +++ b/src/lua_api_entity.cpp @@ -156,6 +156,7 @@ static void entity_class_register(lua_State* state) }); lua_method(state, "HasMortalDamage", [](Entity& entity) { return entity.HasMortalDamage(); }); lua_method(state, "Kill", [](Entity& entity) { entity.Kill(EntityRef()); }); + // 008c5cf2 Entity:KillWithSource kills it as the source did. lua_method(state, "KillWithSource", [](Entity& entity, const EntityRef& source) { entity.Kill(source); }); lua_method(state, "Die", [](Entity& entity) { entity.isDead = true; }); lua_method(state, "Remove", [](Entity& entity) { entity.Remove(); }); @@ -180,6 +181,7 @@ static void entity_class_register(lua_State* state) lua_method(state, "IsActiveEnemy", [](Entity& entity, bool isDeadIncluded) { return entity.IsActiveEnemy(isDeadIncluded ? DEAD_INCLUDED : DEAD_EXCLUDED); }); + // 0085e680 Entity:IsVulnerableEnemy, from a source or none. lua_method(state, "IsVulnerableEnemy", [](Entity& entity, Entity* source) { return entity.IsVulnerableEnemy(source); }); lua_method(state, "IsFlying", [](Entity& entity) { return entity.IsFlying(); }); diff --git a/src/lua_api_game.cpp b/src/lua_api_game.cpp index 23316f6..af96cf0 100644 --- a/src/lua_api_game.cpp +++ b/src/lua_api_game.cpp @@ -5,6 +5,7 @@ #include "entity_npc.h" #include "entity_pickup.h" #include "entity_player.h" +#include "entity_tear.h" #include "pocket_items.h" #include "game.h" #include "game_end.h" @@ -168,8 +169,10 @@ static void game_effects_register(lua_State* state) lua_method(state, "MakeShockwave", [](Game&, Vector position, float amplitude, float speed, int duration) { shockwave_make(position, amplitude, speed, duration); }); - lua_method(state, "UpdateStrangeAttractor", - [](Game&, Vector, float, float) { reconstruction_missing("Game::AttractEntities 00705b90"); }); + // 0085e390 Game:UpdateStrangeAttractor pulls everything around a position. + lua_method(state, "UpdateStrangeAttractor", [](Game&, Vector position, float force, float radius) { + entities_attract({.position = position, .radius = radius, .strength = force}); + }); lua_method(state, "CharmFart", [](Game&, Vector position, float radius, Entity* source) { game_charm_fart(position, radius, source); }); lua_method(state, "Darken", [](Game& game, float strength, int timeout) { @@ -222,15 +225,14 @@ static void game_flow_register(lua_State* state) lua_method(state, "GetRandomPlayer", game_random_player); lua_method(state, "RerollLevelCollectibles", game_level_collectibles_reroll); lua_method(state, "RerollLevelPickups", game_level_pickups_reroll); - lua_method(state, "RerollEnemy", [](Game&, Entity*, bool) { - reconstruction_missing("Game::RerollEnemy 007050c0"); - return false; + lua_method(state, "RerollEnemy", [](Game& game, Entity* entity, bool isAnyHealth) { + return game.RerollEnemy(entity, isAnyHealth ? REROLL_MATCH_ANY : REROLL_MATCH_HEALTH); }); lua_pushcfunction(state, game_entity_desc_spawn); lua_table_set(state, -2, "SpawnEntityDesc"); lua_method(state, "End", [](Game&, GameEnding ending) { game_end(ending); }); lua_method(state, "FinishChallenge", [](Game&) { challenge_finish(); }); - lua_method(state, "NextVictoryLap", [](Game&) { reconstruction_missing("Game::NextVictoryLap 006f7ac0"); }); + lua_method(state, "NextVictoryLap", [](Game& game) { game.NextVictoryLap(); }); } // (00703510, 00703570) Registers Lua's Game: the run's level, room, players, pools, seeds and HUD, spawning, room diff --git a/src/lua_api_room.cpp b/src/lua_api_room.cpp index c75aa8f..ef690e4 100644 --- a/src/lua_api_room.cpp +++ b/src/lua_api_room.cpp @@ -268,8 +268,9 @@ static void room_state_register(lua_State* state) }); lua_method(state, "ShopRestockPartial", [](Room& room) { room_restock_partial(room); }); lua_method(state, "ShopRestockFull", [](Room&) { room_shop_restock_full(); }); - lua_method(state, "ShopReshuffle", - [](Room&, bool, bool) { reconstruction_missing("Room::ShopReshuffle 00816000"); }); + lua_method(state, "ShopReshuffle", [](Room& room, bool isKeepItems, bool isSale) { + room_shop_reshuffle(room, (isKeepItems ? RESHUFFLE_KEEP_ITEMS : 0) | (isSale ? RESHUFFLE_SALE : 0)); + }); lua_method(state, "SpawnClearAward", [](Room& room) { room_clear_award_spawn(room); }); lua_method(state, "TriggerClear", [](Room& room, bool isSilent) { room_clear_trigger(room, isSilent ? CLEAR_SOUND_SILENT : CLEAR_SOUND_PLAY); diff --git a/src/lua_callbacks.cpp b/src/lua_callbacks.cpp index 0b2e38e..2448f10 100644 --- a/src/lua_callbacks.cpp +++ b/src/lua_callbacks.cpp @@ -14,7 +14,6 @@ #include "lua_api.h" #include "room_config.h" -constexpr int CALLBACK_PARAM_NONE = -1; constexpr int PILL_EFFECT_UNCHANGED = -1; // One run of a callback: the name its errors log, its id, and the parameter mods filter it by. @@ -230,7 +229,6 @@ std::optional LuaEngine::InputAction(Entity* entity, int hook, int action) // 00864d80 Runs MC_INPUT_ACTION for the action value hook. The value a mod answered, nothing when no mod did. std::optional LuaEngine::InputActionValue(Entity* entity, int action) { - constexpr int INPUT_HOOK_VALUE = 2; CallbackRun run = {"PreActionHookF", MC_INPUT_ACTION, INPUT_HOOK_VALUE}; if (!callback_run(*this, run, entity, INPUT_HOOK_VALUE, action)) return std::nullopt; diff --git a/src/lua_engine.h b/src/lua_engine.h index 989842a..4ecf46f 100644 --- a/src/lua_engine.h +++ b/src/lua_engine.h @@ -32,6 +32,16 @@ constexpr int LUA_GC_STEP_MIN = 50; constexpr int LUA_MEMORY_HISTORY_SIZE = 128; // Lua's LUA_NOREF: a registry reference to nothing. constexpr int LUA_REF_NONE = -2; +// A callback registered for every parameter. +constexpr int CALLBACK_PARAM_NONE = -1; + +// The input hooks of MC_INPUT_ACTION (Lua's InputHook). +enum InputHook : int +{ + INPUT_HOOK_PRESSED, + INPUT_HOOK_TRIGGERED, + INPUT_HOOK_VALUE +}; // The game classes the API binds, each with the registry key of the metatable its objects get. enum LuaClass diff --git a/src/manager.cpp b/src/manager.cpp index 1b7ff02..804a993 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -1,4 +1,5 @@ #include "manager.h" +#include "screenshot.h" #include "backdrop.h" #include "data.h" #include "entity_player.h" @@ -192,6 +193,7 @@ constexpr int CURSOR_VISIBLE_FRAMES = 300; constexpr const char* CURSOR_CLICKED_ANIMATION = "Clicked"; constexpr int SCREENSHOT_KEY = 298; constexpr const char* SCREENSHOTS_FOLDER = "screenshots"; +constexpr const char* MANUAL_SCREENSHOT = "screenshots/ManualScreenshot"; // The stage bar's icon for a stage not reached. constexpr int STAGE_ICON_EMPTY = 17; // The loading screen's image pairs, one per seed numbered from 1, with a set of its own for the greed modes. @@ -504,14 +506,14 @@ static void shaders_load() log_printf(LOG_INFO, "%s", SHADER_BANNER); } -// Drops the daily challenge, so the run is not one. -// Its rules (ChallengeParam::Reset) reset with DailyChallenge's takeover, as classes.h holds them as bytes. +// Drops the daily challenge and its rules, so the run is not one. static void daily_challenge_clear(DailyChallenge& daily) { - daily._id = 0; - daily._seed = 0; - daily._specialDailyId = 0; - daily._isPractice = false; + daily.params.Reset(); + daily.id = 0; + daily.seed = 0; + daily.specialDailyId = 0; + daily.isPractice = false; } // 009aa040 Starts the game once the engine runs: creates the Lua engine, seeds the global random generator, listens to @@ -585,7 +587,7 @@ void isaac_shutdown() PersistentGameData& data = manager.persistentGameData; log_printf(LOG_INFO, "Isaac is shutting down...\n"); - if (g_game && g_game->dailyChallenge._id != 0 && !g_game->dailyChallenge._isPractice) + if (g_game && g_game->dailyChallenge.id != 0 && !g_game->dailyChallenge.isPractice) { data.eventCounters[EVENT_COUNTER_DAILYS_STREAK] = 0; data.IncreaseEventCounter(EVENT_COUNTER_DAILYS_LOSING_STREAK, 1); @@ -1003,7 +1005,7 @@ bool Manager::AchievementUnlocksDisallowed() Manager& manager = *g_manager; bool isModded = manager.modManager.is_any_mod_loaded() || manager.optionsConfig.isDebugConsoleEnabled; bool isExemptRun = manager.state == MANAGER_STATE_GAME && g_game && - (g_game->dailyChallenge._id != 0 || g_game->isDebug); + (g_game->dailyChallenge.id != 0 || g_game->isDebug); return isModded && !manager.persistentGameData.achievements[ACHIEVEMENT_THE_WOMB] && !isExemptRun; } @@ -1204,7 +1206,7 @@ void Manager::LoadGameState(uint32_t slot) { if (isSaveRead) gamestate.Delete(); bool isRerunKept = persistentGameData.achievements[ACHIEVEMENT_RERUN] || - (state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge._id != 0 || g_game->isDebug)); + (state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge.id != 0 || g_game->isDebug)); if (isRerunKept) { gamestate.rerunPath = rerunPath; @@ -1306,7 +1308,7 @@ void Manager::start_pending_game() reconstruction_missing("Game::StartFromRerunState 006f72f0"); } } - else if (dailyChallenge._id != 0) + else if (dailyChallenge.id != 0) reconstruction_missing("Game::StartDailyChallenge 006f6dd0, on the daily's character DailyChallenge holds as bytes"); else if (isDebugStart) reconstruction_missing("Game::StartDebug 006f7750"); else g_game->Start(startPlayerType, startChallenge, startSeeds, (Difficulty)startDifficulty); @@ -1331,7 +1333,7 @@ void Manager::save_game_state() log_printf(LOG_INFO, "[warn] Cannot save game state while not in game.\n"); return; } - if (game.dailyChallenge._id != 0 || manager.netplayManager.is_online()) return; + if (game.dailyChallenge.id != 0 || manager.netplayManager.is_online()) return; Entity_Player& player = *game.GetPlayer(0); if (player.isDead && player.GetExtraLives() < 1) return; @@ -1520,7 +1522,7 @@ void Manager::Update(InputPoll poll) { std::error_code result; std::filesystem::create_directories(platform.userDataDirectory + SCREENSHOTS_FOLDER, result); - save_screenshot(); + save_screenshot(MANUAL_SCREENSHOT); } if (manager.isUpdatePaused) return; diff --git a/src/manager.h b/src/manager.h index a3fd903..e43a9d1 100644 --- a/src/manager.h +++ b/src/manager.h @@ -1,6 +1,7 @@ #pragma once #include "anm2.h" +#include "daily_challenge.h" #include "challenge_params.h" #include "cutscene.h" #include "entity_config.h" diff --git a/src/manager_input.cpp b/src/manager_input.cpp index c7e4121..1ec42ed 100644 --- a/src/manager_input.cpp +++ b/src/manager_input.cpp @@ -50,7 +50,7 @@ static void restart_update(Game& game) if (!isHeld) game.restartHoldFrames = 0; else if (!isRestarting) game.restartHoldFrames++; - bool isReady = !(isEden && edenTokens == 0) && game.dailyChallenge._id == 0 && + bool isReady = !(isEden && edenTokens == 0) && game.dailyChallenge.id == 0 && game.restartHoldFrames >= RESTART_HOLD_FRAMES; if (!isHeld && isRestarting) { @@ -118,7 +118,7 @@ void Manager::update_ingame_input() } bool isInfoAllowed = manager.persistentGameData.achievements[ACHIEVEMENT_ITEM_INFO] || - (manager.state == MANAGER_STATE_GAME && (game.dailyChallenge._id != 0 || game.isDebug)); + (manager.state == MANAGER_STATE_GAME && (game.dailyChallenge.id != 0 || game.isDebug)); if (game.pauseScreen.state == PAUSE_HIDDEN && isInfoAllowed && is_action(ACTION_ITEM_INFO, ACTION_TRIGGERED)) manager.optionsConfig.isItemInfoDisplayEnabled = !manager.optionsConfig.isItemInfoDisplayEnabled; game.playerManager.handle_coop_join(); diff --git a/src/menu_character.cpp b/src/menu_character.cpp index f2ecf56..2b33d15 100644 --- a/src/menu_character.cpp +++ b/src/menu_character.cpp @@ -200,18 +200,6 @@ constexpr float UNLOCK_TITLE_Y = -26; constexpr uint32_t INK_ARGB = 0xff362f2d; constexpr uint32_t EGG_COUNT_ARGB = 0xff3d3234; -// The GLFW keys the seed entry reads. -enum SeedKey : int -{ - KEY_V = 86, - KEY_BACKSPACE = 259, - KEY_KEYPAD_0 = 320, - KEY_LEFT_CONTROL = 341, - KEY_LEFT_SUPER = 343, - KEY_RIGHT_CONTROL = 345, - KEY_RIGHT_SUPER = 347 -}; - // A position moved by an offset. static Vector offset_add(Vector origin, MenuOffset offset) { diff --git a/src/menu_daily_challenge.cpp b/src/menu_daily_challenge.cpp index efd0800..7ff9553 100644 --- a/src/menu_daily_challenge.cpp +++ b/src/menu_daily_challenge.cpp @@ -21,6 +21,7 @@ constexpr const char* CURRENT_STREAK_NULL = "CurrentStreak"; constexpr const char* BEST_STREAK_NULL = "BestStreak"; constexpr const char* COUNTDOWN_FORMAT = "{:02}:{:02}:{:02}"; constexpr int CURSOR_LAYER = 5; +constexpr int DAILY_CHARACTER_LAYER = 11; constexpr int SKETCH_PAPER_LAYER = 11; constexpr int POPUP_PICTURE_LAYER = 2; @@ -199,7 +200,7 @@ void Menu_DailyChallenge::run_start() PersistentGameData& data = manager.persistentGameData; bool isPractice = selectedElement == DAILY_PRACTICE; - manager.dailyChallenge._isPractice = isPractice; + manager.dailyChallenge.isPractice = isPractice; manager.isRerunAvailable = false; manager.isStartingFromRerun = false; manager.isDebugStart = false; @@ -233,7 +234,7 @@ void Menu_DailyChallenge::leaderboard_show() { daily_challenge_refresh(); - uint32_t date = g_manager->dailyChallenge._id; + uint32_t date = g_manager->dailyChallenge.id; leaderboard.mode = LEADERBOARD_BOARDS; leaderboard.displayState = LEADERBOARD_APPEARING; leaderboard.leaderboardSprite.Play(ANIMATION_APPEAR); @@ -287,8 +288,7 @@ void Menu_DailyChallenge::input_update() void Menu_DailyChallenge::layers_update() { dailyRunSprite.SetLayerFrame(CURSOR_LAYER, selectedElement); - reconstruction_missing("Menu_DailyChallenge 008d0840: the day's character, in DailyChallenge's params, which " - "classes.h holds as bytes"); + dailyRunSprite.SetLayerFrame(DAILY_CHARACTER_LAYER, g_manager->dailyChallenge.params.playerType); } // Counts down to the next day on the daily clock, looking the day up again as it turns. diff --git a/src/menu_game.cpp b/src/menu_game.cpp index 0854168..d8db4d2 100644 --- a/src/menu_game.cpp +++ b/src/menu_game.cpp @@ -199,10 +199,10 @@ void Menu_Game::run_start() manager.isDebugStart = false; manager.isRerunAvailable = isSaveAvailable; manager.isStartingFromRerun = !isSaveAvailable; - manager.dailyChallenge._id = 0; - manager.dailyChallenge._seed = 0; - manager.dailyChallenge._specialDailyId = 0; - manager.dailyChallenge._isPractice = false; + manager.dailyChallenge.id = 0; + manager.dailyChallenge.seed = 0; + manager.dailyChallenge.specialDailyId = 0; + manager.dailyChallenge.isPractice = false; manager.isStarting = true; manager.isNetworkPlay = false; manager.consecutiveResetCount = 0; diff --git a/src/menu_options.cpp b/src/menu_options.cpp index 0268158..10ca8e5 100644 --- a/src/menu_options.cpp +++ b/src/menu_options.cpp @@ -44,7 +44,6 @@ constexpr int ROWS_ABOVE = 3; constexpr int ROWS_BELOW = 4; constexpr float GAMMA_COUNTER_X = 50; constexpr float DIGIT_WIDTH = 11; -constexpr int DIGIT_BASE = 10; constexpr int FRAME_MINUS = 11; constexpr float PAUSE_DIM_ALPHA = 0.60784316f; constexpr float LOADING_DIM_ALPHA = 0.5f; @@ -64,7 +63,6 @@ constexpr int EXTRA_HUD_MODE_COUNT = 3; constexpr int JACOB_ESAU_MODE_COUNT = 2; constexpr int ONLINE_HUD_MODE_COUNT = 4; constexpr int ONLINE_COLOR_SET_COUNT = 4; -constexpr int ONLINE_LEVEL_MAX = 10; constexpr int INPUT_DELAY_MIN = 1; constexpr int INPUT_DELAY_MAX = 5; constexpr int CONTROLLER_UNSET = -1; diff --git a/src/menu_save.cpp b/src/menu_save.cpp index 11e4886..2a66b25 100644 --- a/src/menu_save.cpp +++ b/src/menu_save.cpp @@ -1,4 +1,5 @@ #include "menu_save.h" +#include "daily_challenge.h" #include "log.h" #include "manager.h" #include "menu_manager.h" @@ -6,6 +7,7 @@ #include #include #include +#include #include constexpr const char* SAVE_MENU_ANM2 = "gfx/ui/main menu/SaveSelectMenu.anm2"; @@ -35,13 +37,13 @@ constexpr int PHOTO_FULL_PIECES = 5; constexpr ColorMod DELETE_PICK_COLOR = {{1, 0.6f, 0.4f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr int BACKUP_DATE_FIRST = 20000000; constexpr int BACKUP_DATE_LAST = 99999999; -constexpr int DATE_PART = 100; -constexpr int DATE_YEAR = 10000; constexpr int DATE_LINE_SIZE = 100; constexpr int BACKUP_DATE_LINE = 2; constexpr const char* SHARED_SAVE_FILE = "sharedsave"; constexpr const char* SAVE_FILE_EXTENSION = ".dat"; constexpr const char* BACKUP_FOLDER = "save_backups/"; +constexpr size_t BACKUP_DATE_DIGITS = 8; +constexpr int DECIMAL_BASE = 10; constexpr int ACHIEVEMENT_JUST_STOP = 339; constexpr int ACHIEVEMENT_1001_PERCENT = 235; @@ -57,6 +59,31 @@ constexpr int EVENT_BEAST_KILLS = 492; constexpr int CUTSCENE_FINAL = 25; constexpr int COMPLETION_MARK_BITS = 0xc; +// 00926510 The date (YYYYMMDD) of the newest backup of a save in save_backups/ that loads, or 0 for none. +// A backup is a file named by eight digits, any character, then the save's file name. The digits are not checked. +static int save_backup_find_latest(PersistentGameData& data) +{ + std::string folder = platform.userDataDirectory + BACKUP_FOLDER; + std::string saveName = data.get_save_file_name(); + std::error_code result; + int latest = 0; + + for (const std::filesystem::directory_entry& file : std::filesystem::directory_iterator(folder, result)) + { + std::string name = file.path().filename().string(); + if (!file.is_regular_file(result) || name.size() <= BACKUP_DATE_DIGITS + 1) continue; + if (name.compare(BACKUP_DATE_DIGITS + 1, std::string::npos, saveName) != 0) continue; + + int date = 0; + for (size_t i = 0; i < BACKUP_DATE_DIGITS; i++) date = date * DECIMAL_BASE + (name[i] - '0'); + if (date <= latest) continue; + auto backup = std::make_unique(); + backup->Clear(CLEAR_ALL); + if (backup->Load(folder + name)) latest = date; + } + return latest; +} + // The photo drawings by Isaac kills, then the negative's by Satan kills, from none (or the outline) to full. constexpr const char* PHOTO_DRAWINGS[PHOTO_FULL_PIECES + 1] = {"12_PhotoOutline.png", "12_Photo1Piece.png", "11_Photo2Pieces.png", "10_Photo3Pieces.png", @@ -322,7 +349,7 @@ void Menu_Save::select_slot(uint32_t slot) return; } - backupDate = save_backup_find_latest(&manager.persistentGameData); + backupDate = save_backup_find_latest(manager.persistentGameData); bool isBackup = backupDate >= 1; std::array lines; for (int i = 0; i < PROMPT_LINES; i++) diff --git a/src/menu_stats.cpp b/src/menu_stats.cpp index d9befae..ed2829c 100644 --- a/src/menu_stats.cpp +++ b/src/menu_stats.cpp @@ -26,7 +26,6 @@ constexpr int CURSOR_LAYER = 4; constexpr int DIGIT_LAYER = 7; constexpr int SECRETS_LOCK_LAYER = 8; constexpr int SECRETS_LOCK_FRAME = 1; -constexpr int DIGIT_BASE = 10; constexpr int FAST_HOLD = 60; constexpr int FASTER_HOLD = 180; constexpr float SPEED_RAMP_FRAMES = 30; diff --git a/src/minimap.cpp b/src/minimap.cpp index 61a9aba..149a3b5 100644 --- a/src/minimap.cpp +++ b/src/minimap.cpp @@ -211,7 +211,6 @@ constexpr SlotIcon SLOT_ICONS[] = { constexpr int SLOT_VARIANT_NO_ICON = 14; constexpr int EFFECT_PORTAL_VARIANT = 161; constexpr int EFFECT_PORTAL_SUBTYPE = 980; -constexpr int GOLDEN_BOMB_SUBTYPE = 4; constexpr int GOLDEN_KEY_SUBTYPE = 2; constexpr int CHARGED_KEY_SUBTYPE = 4; constexpr int MEGA_BATTERY_SUBTYPE = 4; @@ -495,7 +494,7 @@ static void pickup_icon_add(RoomIcons& icons, const EntitySaveState& saved) return; } case PICKUP_POOP: room_icon_show(icons, MAP_ICON_POOP); return; - case PICKUP_BOMB: room_icon_raise(icons, MAP_ICON_BOMB, subtype == GOLDEN_BOMB_SUBTYPE); return; + case PICKUP_BOMB: room_icon_raise(icons, MAP_ICON_BOMB, subtype == BOMB_SUBTYPE_GOLDEN); return; case PICKUP_KEY: { int frame = subtype == GOLDEN_KEY_SUBTYPE ? 1 : subtype == CHARGED_KEY_SUBTYPE ? 2 : 0; @@ -847,7 +846,7 @@ void Minimap::Render() const RoomConfig_Room* room = game.room->descriptor->data; if (room && room->type == ROOM_DUNGEON && room->stageId == STAGE_ID_HOME) { - if (game.dailyChallenge._id != 0) render_score_time(1); + if (game.dailyChallenge.id != 0) render_score_time(1); return; } @@ -1033,7 +1032,7 @@ void Minimap::render_score_time(float alpha) vector_make(1, 1), color, settings); } - if (game.IsGreedMode() || game.dailyChallenge._id == 0) return; + if (game.IsGreedMode() || game.dailyChallenge.id == 0) return; color = kcolor_make(1, 1, 1, alpha); float scoreY = textY + SCORE_Y + shake.y; diff --git a/src/mod_manager.cpp b/src/mod_manager.cpp index f4b90fa..b36e489 100644 --- a/src/mod_manager.cpp +++ b/src/mod_manager.cpp @@ -68,7 +68,6 @@ constexpr KAGE::Graphics::VertexAttribute MOD_SHADER_ATTRIBUTES[] = { // The wrap mode that clamps texture coordinates to the edge. // The floats of the sprite vertex before RenderData: position, color and texture coordinates. constexpr int SHADER_RENDER_DATA_OFFSET = 9; -constexpr int CALLBACK_PARAM_NONE = -1; constexpr KColor SHADER_QUAD_WHITE = kcolor_rgba(1, 1, 1, 1); constexpr KColor SHADER_QUAD_COLOR_UNSET = kcolor_rgba(-1, -1, -1, -1); diff --git a/src/nightmare_scene.cpp b/src/nightmare_scene.cpp index 8d4216e..0d2829d 100644 --- a/src/nightmare_scene.cpp +++ b/src/nightmare_scene.cpp @@ -247,7 +247,7 @@ static DreamCatcherPage boss_page_get(RoomDescriptor& room) bosses[1] = config; } } - bool isMomsAgain = (game.gameStateFlags & (1ull << LEVEL_GAME_STATE_MAUSOLEUM_HEART_KILLED)) && game.stage == STAGE_DEPTHS_II; + bool isMomsAgain = (game.gameStateFlags & (1ull << GAME_STATE_BACKWARDS_PATH_INIT)) && game.stage == STAGE_DEPTHS_II; if (data.spawns.empty() && isMomsAgain) bosses[0] = configs.GetEntity(ENTITY_MOM, 0, 0); bool isDoubleTrouble = data.type == ROOM_BOSS && data.variant >= DREAM_CATCHER_DOUBLE_TROUBLE_FIRST && @@ -404,7 +404,7 @@ static StageBar stage_bar_get(NightmareScene& scene) if (game.IsGreedMode()) last = STAGE_BAR_LAST_GREED; else { - bool isDailyOrDebug = manager.state == MANAGER_STATE_GAME && (game.dailyChallenge._id != 0 || game.isDebug); + bool isDailyOrDebug = manager.state == MANAGER_STATE_GAME && (game.dailyChallenge.id != 0 || game.isDebug); if (manager.persistentGameData.achievements[ACHIEVEMENT_THE_WOMB] || isDailyOrDebug || scene.stageIndex > STAGE_BAR_LAST_GREED || (scene.stageIndex == STAGE_BAR_LAST && !scene.isSameStage)) last = STAGE_BAR_LAST_WOMB; diff --git a/src/nightmare_scene.h b/src/nightmare_scene.h index ef2244d..2c2c536 100644 --- a/src/nightmare_scene.h +++ b/src/nightmare_scene.h @@ -11,8 +11,9 @@ // The stage bar holds an icon for each stage, by stage number. constexpr int STAGE_ICON_COUNT = 14; -// Home's icon on the nightmare's stage strip. +// Home's icon on the nightmare's stage strip, and the first stage's in a Greed run. constexpr int STAGE_ICON_HOME = 27; +constexpr int GREED_STAGE_ICON = -3; struct EntityConfig_Entity; struct ItemConfig_Item; diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index e493c76..b6d82de 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -493,7 +493,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 412: return boss_delirium_update(npc); case 413: - return (void)NpcAI::ENTITY_MATRIARCH(&npc); + return boss_matriarch_update(npc); case 802: return npc_blood_puppy_update(npc); case 804: @@ -639,7 +639,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 900: return boss_reap_creep_update(npc); case 901: - return (void)NpcAI::ENTITY_LIL_BLUB(&npc); + return boss_lil_blub_update(npc); case 902: return boss_rainmaker_update(npc); case 903: @@ -657,7 +657,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 909: return npc.variant == 10 ? NpcAI::ENTITY_SCOURGE_chain(&npc) : NpcAI::ENTITY_SCOURGE(&npc); case 910: - return npc.variant == 2 ? (void)NpcAI::ENTITY_CHIMERA(&npc) : NpcAI::ENTITY_CHIMERA_body(&npc); + return npc.variant == 2 ? chimera_head_update(npc) : chimera_body_update(npc); case 911: return boss_rotgut_update(npc); case 912: @@ -667,9 +667,9 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 914: return boss_clog_update(npc); case 915: - return npc.variant == 1 ? NpcAI::ENTITY_SINGE_ball(&npc) : NpcAI::ENTITY_SINGE_body(&npc); + return npc.variant == SINGE_BALL ? singe_ball_update(npc) : NpcAI::ENTITY_SINGE_body(&npc); case 916: - return (void)NpcAI::ENTITY_BUMBINO(&npc); + return boss_bumbino_update(npc); case 917: return boss_colostomia_update(npc); case 918: @@ -679,7 +679,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 920: return boss_horny_boys_update(npc); case 921: - if (npc.variant == 0) return NpcAI::ENTITY_CLUTCH(&npc); + if (npc.variant == 0) return boss_clutch_update(npc); return clutch_orbital_update(npc); case 922: return cadavra_update(npc); diff --git a/src/npc_basement.h b/src/npc_basement.h index 34b1c1e..357ed1c 100644 --- a/src/npc_basement.h +++ b/src/npc_basement.h @@ -4,6 +4,8 @@ // The Hopper's Trite variant, which several bosses summon. constexpr int HOPPER_TRITE = 1; +// A Gusher shoots again after its cooldown plus up to this many frames. +constexpr int GUSHER_COOLDOWN_RANGE = 20; // The basement enemies' AIs the dispatcher (npc_ai_update) runs by type. void npc_gusher_update(Entity_NPC& npc); diff --git a/src/npc_bubbles.cpp b/src/npc_bubbles.cpp index 9bd3e69..436389c 100644 --- a/src/npc_bubbles.cpp +++ b/src/npc_bubbles.cpp @@ -35,7 +35,6 @@ constexpr float BUBBLE_BURST_TRAJECTORY = 3; // Dying, it leaves a splash (tinted brown in the Dross), four blood bursts thrown 40 out at 7 between -45 and -135 // degrees, and a geyser of bubbles over 15 frames. constexpr ColorMod BUBBLES_DROSS_SPLASH = {{0.5f, 0.4f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; -constexpr ColorMod BUBBLES_GEYSER_WATER = {{1, 1, 1, 1}, {5.5f, 7, 7, 1}, {0, 0, 0}}; constexpr ColorMod BUBBLES_GEYSER_DROSS = {{1, 1, 1, 1}, {7, 6, 5.5f, 1}, {0, 0, 0}}; constexpr int BUBBLES_GEYSER_BURSTS = 4; constexpr float BUBBLES_GEYSER_ANGLE = -45; @@ -127,7 +126,7 @@ static void bubbles_death_spawn(Entity_NPC& npc) blood->renderDepthOffset = BUBBLES_GEYSER_DEPTH; blood->renderZOffset = BUBBLES_GEYSER_Z; blood->sprite.rotation = random_unit() * FULL_TURN_DEGREES; - blood->SetColor(isDross ? BUBBLES_GEYSER_DROSS : BUBBLES_GEYSER_WATER, -1, COLOR_PRIORITY_DEFAULT, false, true); + blood->SetColor(isDross ? BUBBLES_GEYSER_DROSS : WATER_SPLASH_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); } Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(&bubbles_death_geyser_tick), 1, diff --git a/src/npc_clickety_clack.cpp b/src/npc_clickety_clack.cpp index a439f60..a2feefa 100644 --- a/src/npc_clickety_clack.cpp +++ b/src/npc_clickety_clack.cpp @@ -1,4 +1,7 @@ #include "npc_alt.h" +#include "boss_ai.h" +#include "boss_repentance.h" +#include "homing_laser.h" #include "entity_config.h" #include "entity_player.h" #include "entity_projectile.h" @@ -21,7 +24,6 @@ constexpr int CLACK_SPACING_TIME = 30; constexpr float CLACK_STILL = 0.1f; constexpr std::array CLACK_WALKS = {"WalkLeft", "WalkUp", "WalkRight", "WalkDown"}; constexpr int CLACK_HEAD_LAYER = 2; -constexpr ColorMod CLACK_HEAD_COLOR = {{1, 1, 1, 1}, {1.3f, 1, 2, 1}, {0, 0, 0}}; constexpr int CLACK_FIRST_DELAY = -30; // Killed, it collapses into a pile of bones for 150 frames (or burns with Clutch) and gets up again with 10 health @@ -31,7 +33,6 @@ constexpr float CLACK_PILE_MASS = 200; constexpr int CLACK_PILE_FRAMES = 150; constexpr int CLACK_PILE_COOLDOWN = 30; constexpr int CLACK_PILE_DELAY = -60; -constexpr int CLACK_FLAME = 99; constexpr uint64_t CLACK_PILE_FLAGS = FLAG_HIDE_HP_BAR | FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET; constexpr float CLACK_PILE_FRICTION = 0.5f; constexpr float CLACK_FLAME_REACH_SQUARED = 14400; @@ -43,18 +44,63 @@ constexpr float CLACK_STOMP_FRICTION = 0.5f; constexpr float CLACK_STOMP_SPEED = 10; constexpr float CLACK_STUN_FRICTION = 0.3f; constexpr int CLUTCH_ORBITING = 6; -constexpr int CLUTCH_REVERT_WAIT = -1000; constexpr int CLUTCH_DOWN = NPC_STATE_STOMP; +// Led by Clutch, it keeps a spot 20 from the one he picked (or 100 to 140 from its target, swaying, with none picked), +// found along the four axes, 40 to 200 from the target while it shoots: a bone at 9 along an axis it faces within 200 +// in a clear line, every 15 frames (10 when it is his last), 60 frames of rest after a run. Every 4 frames one time in +// 16 it hands Clutch the one of them farthest toward his target. +constexpr float ORBIT_PICK_REACH = 20; +constexpr float CLACK_ORBIT_REACH = 100; +constexpr float ORBIT_SWAY = 40; +constexpr float ORBIT_SHOOT_REACH = 40; +constexpr float ORBIT_SHOOT_SPREAD = 120; +constexpr float ORBIT_SHOOT_SWAY = 80; +constexpr float ORBIT_SWAY_PERIOD = 15; +constexpr float ORBIT_UNTARGETED_SHARE = 0.001f; +constexpr float ORBIT_RANGE_SHARE = 0.2f; +constexpr float CLACK_ORBIT_FAR = 10000; +constexpr std::array, 4> ORBIT_AXES = {{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}}; +constexpr float ORBIT_AIM = 0.92f; +constexpr float ORBIT_AIM_REACH = 200; +constexpr float ORBIT_PATH_SPEED = 0.9f; +constexpr float ORBIT_STEER_FRICTION = 0.7f; +constexpr float ORBIT_STEER_SHARE = 0.1f; +constexpr float ORBIT_STEER_MAX = 2; +constexpr float ORBIT_HAND_EVERY = 4; +constexpr uint32_t ORBIT_HAND_ODDS = 15; +constexpr float ORBIT_HAND_FLOOR = -1000000; +constexpr float ORBIT_BONE_SPEED = 9; +constexpr int ORBIT_BONE_COOLDOWN = 15; +constexpr int ORBIT_LAST_BONE_COOLDOWN = 10; +constexpr int ORBIT_REST = -60; +constexpr int ORBIT_REST_END = 5; +constexpr std::array CLACK_HEADS = {"HeadLeft", "HeadUp", "HeadRight", "HeadDown"}; +constexpr std::array CLACK_ORBIT_WALKS = {"WalkLeft2", "WalkUp2", "WalkRight2", "WalkDown2"}; + +// Holding Clutch's line, it stands 20 short of where the line from Clutch through his target meets a wall. +constexpr float LINE_REACH = 2; +constexpr float LINE_INSET = 20; + +// Burning with Clutch, it spits a slow fire shot (raised 6, falling slowly) under a fading flash, which turns on its +// target at 10 once 15 frames old with a burst of black fire. +constexpr float FLAME_HEIGHT = -6; +constexpr int FLAME_FLASH_FRAMES = 6; +constexpr ColorMod FLAME_SHOT_FLASH = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod FLAME_RIPPLE_COLOR = {{1, 1, 1, 1}, {0.8f, 0.6f, 1.4f, 1}, {0, 0, 0}}; +constexpr float FLAME_SOUND_VOLUME = 0.5f; +constexpr float FLAME_TURN_AGE = 15; +constexpr float FLAME_TURN_SPEED = 10; +constexpr float FLAME_BURST_RAISE = 0.65f; +constexpr ColorMod FLAME_BURST_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.4f, 0.3f, 0.7f}}; +constexpr int FLAME_BURST_GLOW_LAYER = 4; + // The Clickety Clack's states: Clutch's orbiting, walking, the stomp, the stun, getting up, the quick revert and the // pile of bones. constexpr int CLACK_ORBITING = NPC_STATE_IDLE; constexpr int CLACK_WALK = NPC_STATE_MOVE; -constexpr int CLACK_STOMP = NPC_STATE_SUICIDE; -constexpr int CLACK_STUNNED = NPC_STATE_STOMP; -constexpr int CLACK_REGEN = NPC_STATE_SUMMON; constexpr int CLACK_REVERT = NPC_STATE_SUMMON2; -constexpr int CLACK_PILE = NPC_STATE_SPECIAL; +constexpr int CLUTCH_REGEN_CALL = NPC_STATE_SUMMON; // Standing again: hurt, targeted and moved as usual. static void clack_stand(Entity_NPC& npc) @@ -87,6 +133,195 @@ static Entity* clack_shy_get(Entity_NPC& npc, Vector target) return nullptr; } +// The axis a gap leans along most: left, up, right or down (vertical on a tie). +static int clack_axis_get(Vector gap) +{ + if (std::abs(gap.x) <= std::abs(gap.y)) return gap.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP; + return gap.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; +} + +// Whether another Clickety Clack stands with it under the same Clutch. +static bool clack_is_sibling(Entity_NPC& npc, Entity& other) +{ + auto& clack = static_cast(other); + return Entity::is_enemy_type(other.type) && &other != &npc && other.parent.get() == npc.parent.get() && + clack.state != CLACK_PILE; +} + +// The Clickety Clack it keeps by while not shooting: its pick, kept while it stands, else the farthest sibling (any +// untargetable one counting a thousandth as far). +static Entity* clack_pick_get(Entity_NPC& npc) +{ + Entity* pick = npc.child.get(); + if (pick && pick->IsEnemy() && static_cast(pick)->state != CLACK_PILE) return pick; + if (pick) npc.child = nullptr; + + Entity* farthest = nullptr; + float farthestDistance = 0; + for (Entity* other : Entity_NPC::QueryNPCsType(ENTITY_CLICKETY_CLACK, -1)) + { + if (!clack_is_sibling(npc, *other) || other->IsFriendly() != npc.IsFriendly()) continue; + float distance = vector_distance(npc.pos, other->pos); + if (other->HasEntityFlags(FLAG_NO_TARGET)) distance *= ORBIT_UNTARGETED_SHARE; + if (farthestDistance >= distance) continue; + farthestDistance = distance; + farthest = other; + } + if (farthest) npc.child = farthest; + return npc.child.get(); +} + +// Every 4 frames one time in 16 it hands Clutch the sibling farthest toward his target: Clutch leaves it in a quick +// revert, beaming to that one. Whether it did. +static bool clack_clutch_hand(Entity_NPC& npc) +{ + if (!npc.GetIntervalTicks(ORBIT_HAND_EVERY, 0) || (Random() & ORBIT_HAND_ODDS) != 0 || !npc.parent) return false; + + Vector toward = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + float length = vector_length(toward); + Entity_NPC* best = nullptr; + float bestReach = ORBIT_HAND_FLOOR; + for (Entity* other : Entity_NPC::QueryNPCsType(ENTITY_CLICKETY_CLACK, -1)) + { + if (!clack_is_sibling(npc, *other)) continue; + Vector gap = vector_sub(other->pos, npc.pos); + float reach = gap.x * (toward.x / length) + gap.y * (toward.y / length); + if (reach <= bestReach && best) continue; + best = static_cast(other); + bestReach = reach; + } + if (!best) return false; + + Entity_NPC* clutch = npc.ParentNPC(); + clutch->parent = best; + npc.state = CLACK_REVERT; + npc.sprite.Play("QuickRevert"); + npc.targetPosition = npc.pos; + npc_sound_play(SOUND_DEVILROOM_DEAL, 1, 2, CLUTCH_SOUND_PITCH); + if (clutch->entityRef) clutch->entityRef->Remove(); + clutch->entityRef = clutch_beam_spawn(npc, *best, npc.parent.get()); + return true; +} + +// Part of 004efb90 Led by Clutch: keeping its spot along an axis by its pick or its target, shooting bones down the +// axis it faces, turning its head. Whether the update goes on. +static bool clack_orbit_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + int boneDirection = -1; + int facing = DIRECTION_DOWN; + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.controllerID != -1) + { + Vector target = npc.CalcTargetPosition(0); + float minimum = ORBIT_SHOOT_REACH; + float preferred = 0; + float age = (float)(g_game->frameCount - npc.spawnFrame); + if (npc.projectileDelay < 1) + { + Entity* pick = clack_pick_get(npc); + minimum = pick ? ORBIT_PICK_REACH : CLACK_ORBIT_REACH; + preferred = pick ? ORBIT_PICK_REACH : std::sin(age * PI_F / ORBIT_SWAY_PERIOD) * ORBIT_SWAY + CLACK_ORBIT_REACH; + if (pick) target = pick->pos; + } + else + { + preferred = std::sin(age * PI_F / ORBIT_SWAY_PERIOD) * ORBIT_SHOOT_SWAY + ORBIT_SHOOT_SPREAD; + npc.child = nullptr; + } + + Vector away = vector_sub(npc.pos, target); + Vector spot{}; + float bestDistance = CLACK_ORBIT_FAR; + for (auto [axisX, axisY] : ORBIT_AXES) + { + Vector axis = vector_make(axisX, axisY); + float reach = std::max(vector_dot(away, axis), minimum); + Vector ray = vector_sub(room_laser_target_get(target, axis), target); + float length = vector_length(ray); + if (length < minimum) continue; + float range = (preferred - reach) * ORBIT_RANGE_SHARE + reach; + if (length > range && length > 0) ray = vector_scale(ray, range / length); + Vector candidate = vector_add(target, ray); + float distance = vector_distance(npc.pos, candidate); + if (distance >= bestDistance) continue; + spot = candidate; + bestDistance = distance; + } + + if (vector_is_zero(spot)) + { + spot = target; + facing = clack_axis_get(vector_sub(target, npc.pos)); + } + else + { + Vector gap = vector_sub(target, npc.pos); + int axis = clack_axis_get(gap); + facing = npc.projectileDelay < 0 ? vector_to_direction(npc.velocity) : axis; + bool isAimed = npc.projectileDelay > 0 && vector_dot(vector_from_direction(axis), vector_normalized(gap)) > ORBIT_AIM && + vector_length(gap) < ORBIT_AIM_REACH && room_check_line(npc.pos, spot, LINE_MODE_PROJECTILE, 0); + if (isAimed) boneDirection = axis; + } + + if (!room_check_line(npc.pos, spot, LINE_MODE_GROUND, 0)) + { + npc.pathfinder.FindGridPath(spot, ORBIT_PATH_SPEED, 0, DIRECT_PATH_FAR); + npc.v1 = npc.velocity; + } + else + { + npc.friction *= ORBIT_STEER_FRICTION; + Vector gap = vector_sub(spot, npc.pos); + float length = vector_length(gap); + Vector push = vector_scale(vector_normalized(gap), ORBIT_PATH_SPEED * std::min(length * ORBIT_STEER_SHARE, ORBIT_STEER_MAX)); + npc.v1 = push; + npc.velocity = vector_add(npc.velocity, vector_scale(push, npc.speedMultiplier / npc.friction)); + } + if (clack_clutch_hand(npc)) return true; + + npc.friction *= CLACK_FRICTION; + if (boneDirection != -1 && npc.projectileCooldown <= 0) + { + ProjectileParams params; + params.variant = PROJECTILE_BONE; + npc.FireProjectiles(npc.pos, vector_scale(vector_from_direction(boneDirection), ORBIT_BONE_SPEED), PROJECTILES_SINGLE, params); + Entity_NPC* clutch = npc.ParentNPC(); + npc.projectileCooldown = clutch && clutch->i1 == 1 ? ORBIT_LAST_BONE_COOLDOWN : ORBIT_BONE_COOLDOWN; + npc.projectileDelay = npc.projectileDelay - 1 < 1 ? ORBIT_REST : npc.projectileDelay - 1; + npc_sound_play(SOUND_SCAMPER, 1, 2, 1); + npc.sprite.PlayOverlay(CLACK_HEADS[facing], PLAY_FORCED); + } + } + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= CLACK_FLEE_FRICTION * CLACK_FRICTION; + } + + if (npc.projectileCooldown > 0) npc.projectileCooldown = std::max(npc.projectileCooldown - ticks, 0); + if (npc.projectileDelay < 0) npc.projectileDelay = npc.projectileDelay + ticks < 0 ? npc.projectileDelay + ticks : ORBIT_REST_END; + const AnimationData* head = npc.sprite.overlayAnimState.animData; + if (!head) + { + if (npc.sprite.SetOverlayAnimation(CLACK_HEADS[facing], SWITCH_KEEP_FRAME) && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); + } + else if (head->name != CLACK_HEADS[facing]) npc.sprite.SetOverlayAnimation(CLACK_HEADS[facing], SWITCH_RESET); + if (vector_length(npc.velocity) < CLACK_STILL) npc.sprite.SetFrame(CLACK_ORBIT_WALKS[DIRECTION_DOWN], 0); + else npc.sprite.Play(CLACK_ORBIT_WALKS[vector_to_direction(npc.velocity)]); + return true; +} + +// Holding Clutch's line: 20 short of where the line from Clutch past his target meets a wall. +static Vector clack_line_spot(Entity_NPC& npc) +{ + Entity_NPC* clutch = npc.ParentNPC(); + Vector target = clutch->GetPlayerTarget()->pos; + Vector gap = vector_sub(target, clutch->pos); + LineCheck line = room_line_check(target, vector_add(target, vector_scale(gap, LINE_REACH)), npc.entityGridCollisionClass, false); + return vector_sub(line.hit, vector_scale(vector_normalized(gap), LINE_INSET)); +} + // Walking at its target, keeping off its neighbor, or away from what it fears (or from Clutch's target). static void clack_walk_update(Entity_NPC& npc) { @@ -102,14 +337,14 @@ static void clack_walk_update(Entity_NPC& npc) if (npc.i1 < 1 || (npc.i1 -= npc_ticks_get(npc)) < 1) npc.entityRef = nullptr; Entity_NPC* clutch = npc.ParentNPC(); Entity* shy = nullptr; - if (clutch && npc.i2 == 1) reconstruction_missing("npc_clickety_clack_update 004efb90: holding Clutch's line"); - else if (clutch && npc.i2 == 2) shy = npc.GetPlayerTarget(); - else shy = clack_shy_get(npc, target); + if (clutch && npc.i2 == 2) shy = npc.GetPlayerTarget(); + else if (!clutch || npc.i2 != 1) shy = clack_shy_get(npc, target); if (shy) { path.EvadeTarget(shy->pos, STATUS_OBEYED); npc.friction *= CLACK_FLEE_FRICTION; } + else if (clutch && npc.i2 == 1) path.FindGridPath(clack_line_spot(npc), CLACK_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); else path.FindGridPath(npc.CalcTargetPosition(0), CLACK_SPEED, GRID_PATH_FREED, DIRECT_PATH_FAR); } @@ -129,6 +364,54 @@ static bool clack_any_standing() return false; } +// Burning under Clutch: its flame spits a fire shot under a purple ripple, and a shot it holds turns on its target +// once 15 frames old in a burst of black fire. It gets up when Clutch calls them. +static void clack_flame_update(Entity_NPC& npc) +{ + if (npc.i2 == CLACK_FLAME && npc.sprite.IsEventTriggered("Shoot") && npc.sprite.IsPlaying("FlameShoot")) + { + auto* shot = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_PROJECTILE, .variant = PROJECTILE_BONE, .seed = Random()})); + shot->height = FLAME_HEIGHT; + shot->fallingSpeed = 0; + shot->scale = 1; + shot->projectileFlags = PROJECTILE_ANTI_GRAVITY; + shot->parent = &npc; + shot->SetColor(FLAME_SHOT_FLASH, FLAME_FLASH_FRAMES, 1, true, true); + shot->Update(); + Entity* ripple = g_game->Spawn( + {.position = npc.targetPosition, .type = ENTITY_EFFECT, .variant = EFFECT_WATER_RIPPLE, .seed = Random()}); + ripple->SetColor(FLAME_RIPPLE_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + npc_sound_play(SOUND_PORTAL_SPAWN, FLAME_SOUND_VOLUME, 2, 1); + npc.entityRef = ripple; + } + + Entity* held = npc.entityRef.get(); + if (held && held->type == ENTITY_PROJECTILE && held->updateTime > FLAME_TURN_AGE) + { + auto* shot = static_cast(held); + Vector aim = vector_resized(vector_sub(npc.GetPlayerTarget()->pos, shot->pos), FLAME_TURN_SPEED); + shot->projectileFlags &= ~PROJECTILE_ANTI_GRAVITY; + shot->velocity = aim; + Entity* burst = blood_explosion_spawn(BLOOD_EXPLOSION_FLAME, shot->pos, + vector_scale(shot->posOffset, FLAME_BURST_RAISE), COLOR_DEFAULT, {}); + burst->sprite.isFlipX = true; + burst->renderDepthOffset = 1; + burst->SetColor(FLAME_BURST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (burst->sprite.layerStates.size() > FLAME_BURST_GLOW_LAYER) layer_additive_set(*burst->sprite.GetLayer(FLAME_BURST_GLOW_LAYER)); + burst->Update(); + npc.PlaySound(SOUND_SCAMPER, 1, 2, false, 1); + npc.entityRef = nullptr; + } + + Entity_NPC* clutch = npc.ParentNPC(); + if (!clutch || clutch->state != CLUTCH_REGEN_CALL) return; + npc.stateFrame = 0; + npc.sprite.Play("Regen"); + npc.sprite.SetFrame((float)CLACK_REGEN_FRAME); + npc.state = CLACK_REGEN; +} + // A pile of bones: burning with Clutch, or, alone, ending them all when it was the last standing, then getting up. // Whether the update goes on. static bool clack_pile_update(Entity_NPC& npc) @@ -152,7 +435,7 @@ static bool clack_pile_update(Entity_NPC& npc) if (npc.parent) { - reconstruction_missing("npc_clickety_clack_update 004efb90: Clutch's burning bones"); + clack_flame_update(npc); return true; } if (npc.sprite.IsEventTriggered("Shoot") && !npc.IsFriendly() && !clack_any_standing()) @@ -273,10 +556,10 @@ void npc_clickety_clack_update(Entity_NPC& npc) npc.state = CLACK_WALK; npc.projectileDelay = CLACK_FIRST_DELAY; npc.i2 = 0; - if (npc.sprite.layerStates.size() > CLACK_HEAD_LAYER) npc.sprite.GetLayer(CLACK_HEAD_LAYER)->color = CLACK_HEAD_COLOR; + if (npc.sprite.layerStates.size() > CLACK_HEAD_LAYER) npc.sprite.GetLayer(CLACK_HEAD_LAYER)->color = CLUTCH_FLAME_COLOR; break; case CLACK_ORBITING: - reconstruction_missing("npc_clickety_clack_update 004efb90: orbiting Clutch"); + clack_orbit_update(npc); break; case CLACK_WALK: clack_walk_update(npc); diff --git a/src/npc_cohort.cpp b/src/npc_cohort.cpp index 6388db4..a5b31df 100644 --- a/src/npc_cohort.cpp +++ b/src/npc_cohort.cpp @@ -1,5 +1,4 @@ #include "npc_gehenna.h" -#include "boss_ai.h" #include "entity_effect.h" #include diff --git a/src/npc_depths.h b/src/npc_depths.h index 13d0954..d04788b 100644 --- a/src/npc_depths.h +++ b/src/npc_depths.h @@ -32,6 +32,7 @@ void npc_hush_gaper_update(Entity_NPC& npc); void npc_greed_gaper_update(Entity_NPC& npc); void npc_black_maw_update(Entity_NPC& npc); void npc_fistuloid_update(Entity_NPC& npc); +void fistuloid_orbit_spread(Entity_NPC& npc); void npc_mr_mine_update(Entity_NPC& npc); void npc_tarboy_update(Entity_NPC& npc); void npc_ultra_coin_update(Entity_NPC& npc); diff --git a/src/npc_dust.cpp b/src/npc_dust.cpp index f962993..b3fb105 100644 --- a/src/npc_dust.cpp +++ b/src/npc_dust.cpp @@ -20,7 +20,7 @@ constexpr float DUST_SPLIT_FIRST = 0.66f; constexpr float DUST_SPLIT_STEP = 0.33f; constexpr float DUST_APPEAR_FRICTION = 0.6f; constexpr float DUST_DRIFT_FRICTION = 0.8f; -constexpr float DUST_SPEED = 1.35f; +constexpr float DUST_WALK_SPEED = 1.35f; constexpr float DUST_SPEED_MIN = 0.35f; constexpr float DUST_SLOW_REACH = 80; constexpr float DUST_SLOW = 0.6f; @@ -70,7 +70,7 @@ static void dust_visibility_update(Entity_NPC& npc) static void dust_drift_update(Entity_NPC& npc) { npc.friction *= DUST_DRIFT_FRICTION; - float speed = std::max(npc.v1.x * DUST_SPEED, DUST_SPEED_MIN); + float speed = std::max(npc.v1.x * DUST_WALK_SPEED, DUST_SPEED_MIN); float near = std::clamp(vector_length(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)) / DUST_SLOW_REACH, 0.0f, 1.0f); npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), (near * DUST_SLOW_RANGE + DUST_SLOW) * speed, DUST_PATH_MARKER, DIRECT_PATH_FAR); diff --git a/src/npc_fireplace.cpp b/src/npc_fireplace.cpp index c7842c3..e3bb15d 100644 --- a/src/npc_fireplace.cpp +++ b/src/npc_fireplace.cpp @@ -11,10 +11,7 @@ #include "room.h" #include -// 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"}; -constexpr const char* NO_FIRE[FIRE_LOOKS] = {"NoFire", "NoFire2", "NoFire3"}; +// A fire's dying animation for each of its looks. constexpr const char* DISAPPEAR[FIRE_LOOKS] = {"Dissapear", "Dissapear2", "Dissapear3"}; // The layer of the flame, which shrinks with the fire's health, and how deep a fire that is out draws. @@ -44,26 +41,13 @@ constexpr int FIRE_COOLDOWN_MIN = 60; constexpr uint32_t RELIGHT_COOLDOWN_RANGE = 60; constexpr int RELIGHT_COOLDOWN_MIN = 90; -// How red and purple fires spit: their mouth above them and a little toward the target, the range they see in, the -// odds of trying and of shooting, the cooldown, and the shot's speed and a purple shot's size. +// A spitting fire's mouth height above it, and a purple shot's size. constexpr float FIRE_MOUTH_HEIGHT = 15; -constexpr float FIRE_MOUTH_REACH = 25; -constexpr float FIRE_SIGHT = 160; -constexpr int FIRE_AIM_ODDS = 5; -constexpr int FIRE_SHOOT_ODDS = 15; -constexpr int FIRE_SHOOT_COOLDOWN = 84; -constexpr float FIRE_SHOT_SPEED = 5; constexpr float PURPLE_SHOT_SCALE = 1.5f; constexpr int CHECK_LINE_PROJECTILE = 3; -// The embers a lit fire throws: their odds, where over the flame they start, and how they drift up. -constexpr int EMBER_ODDS = 7; -constexpr float EMBER_SPREAD = 16; -constexpr float EMBER_HEIGHT = 15; +// How much higher a healthier fire's embers start, and their colors by fire. constexpr float EMBER_HEALTH_RISE = 6; -constexpr float EMBER_RISE_MIN = 0.8f; -constexpr float EMBER_RISE_RANGE = 1.6f; -constexpr float EMBER_DRIFT = 0.4f; constexpr int EMBER_PRIORITY = 255; constexpr ColorMod EMBER_RED = {{1, 0.5f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod EMBER_BLUE = {{1, 1, 1, 1}, {0.2f, 1, 1.5f, 1}, {0, 0, 0}}; @@ -77,9 +61,6 @@ constexpr float RELIGHT_RED_BLUE = 0; constexpr float RELIGHT_OFFSET = 0.35f; constexpr float RELIGHT_BLUE = 0.5f; -// The sounds of a fire: lit again, and put out. -constexpr float PUT_OUT_VOLUME = 0.85f; - // A moveable fire burns, then fades in Disappear. A plain one lasts 300 frames (180 colliding with the grid), a blue // one loses a health each time its speed adds up to 90, and a purple one lasts. Its flame never shrinks below a tenth. constexpr int MOVEABLE_FIRE_BURNING = NPC_STATE_IDLE; @@ -384,13 +365,13 @@ static void fire_shoot_update(Entity_NPC& npc) // A lit fire now and then throws an ember up out of its flame, in its fire's color. static void fire_ember_update(Entity_NPC& npc) { - if (npc.state != FIRE_STATE_LIT || Random() % EMBER_ODDS != 0) return; + if (npc.state != FIRE_STATE_LIT || Random() % FIRE_EMBER_ODDS != 0) return; float height = random_unit(); - float x = random_unit() * EMBER_SPREAD - EMBER_SPREAD / 2 + npc.pos.x; - float y = -EMBER_HEIGHT - npc.health * EMBER_HEIGHT / EMBER_HEALTH_RISE - height * EMBER_HEIGHT + npc.pos.y; - float rise = random_unit() * -EMBER_RISE_RANGE - EMBER_RISE_MIN; - float drift = random_unit() * EMBER_DRIFT - EMBER_DRIFT / 2; + float x = random_unit() * FIRE_EMBER_SPREAD - FIRE_EMBER_SPREAD / 2 + npc.pos.x; + float y = -FIRE_EMBER_HEIGHT - npc.health * FIRE_EMBER_HEIGHT / EMBER_HEALTH_RISE - height * FIRE_EMBER_HEIGHT + npc.pos.y; + float rise = random_unit() * -FIRE_EMBER_RISE_RANGE - FIRE_EMBER_RISE_MIN; + float drift = random_unit() * FIRE_EMBER_DRIFT - FIRE_EMBER_DRIFT / 2; Entity* ember = g_game->Spawn({.position = vector_make(x, y), .velocity = vector_make(drift, rise), .spawner = &npc, diff --git a/src/npc_fireplace.h b/src/npc_fireplace.h index 53a653b..3943fd6 100644 --- a/src/npc_fireplace.h +++ b/src/npc_fireplace.h @@ -21,4 +21,29 @@ 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, each with its burning and burnt out animation, shared by the fireplace grid entity. +constexpr int FIRE_LOOKS = 3; +constexpr const char* FLICKERING[FIRE_LOOKS] = {"Flickering", "Flickering2", "Flickering3"}; +constexpr const char* NO_FIRE[FIRE_LOOKS] = {"NoFire", "NoFire2", "NoFire3"}; + +// How a red fire spits at the nearest player: its mouth a little toward them, the range it sees in, the odds of +// trying and of shooting, the cooldown and the shot's speed. +constexpr float FIRE_MOUTH_REACH = 25; +constexpr float FIRE_SIGHT = 160; +constexpr int FIRE_AIM_ODDS = 5; +constexpr int FIRE_SHOOT_ODDS = 15; +constexpr int FIRE_SHOOT_COOLDOWN = 84; +constexpr float FIRE_SHOT_SPEED = 5; + +// The embers a lit fire throws: their odds, where over the flame they start, and how they drift up. +constexpr int FIRE_EMBER_ODDS = 7; +constexpr float FIRE_EMBER_SPREAD = 16; +constexpr float FIRE_EMBER_HEIGHT = 15; +constexpr float FIRE_EMBER_RISE_MIN = 0.8f; +constexpr float FIRE_EMBER_RISE_RANGE = 1.6f; +constexpr float FIRE_EMBER_DRIFT = 0.4f; + +// The volume of a fire's sound when it is put out. +constexpr float PUT_OUT_VOLUME = 0.85f; + void npc_fireplace_update(Entity_NPC& npc); diff --git a/src/npc_fistuloid.cpp b/src/npc_fistuloid.cpp index 407ad79..b570de1 100644 --- a/src/npc_fistuloid.cpp +++ b/src/npc_fistuloid.cpp @@ -39,7 +39,7 @@ constexpr float EJECTING_HEALTH = 0.1f; // npc_distribute_orbit_angles 00547040: the Matriarch's other circling Fistuloids spread evenly round her from the // smallest of their angles. -static void fistuloid_orbit_spread(Entity_NPC& npc) +void fistuloid_orbit_spread(Entity_NPC& npc) { Entity* matriarch = npc.parent.get(); if (!matriarch) return; diff --git a/src/npc_gaper.cpp b/src/npc_gaper.cpp index f366603..3987b77 100644 --- a/src/npc_gaper.cpp +++ b/src/npc_gaper.cpp @@ -46,7 +46,6 @@ constexpr float NULLS_SPEED = 0.90000004f; // The walk: the gap path marker each leaves (the Stoney's lower), the walk animation's threshold, and fleeing. constexpr int PATH_MARKER_STONEY = 100; -constexpr float WALK_THRESHOLD = 0.1f; constexpr float FLEE_FRICTION = 0.8f; constexpr float ATTACK_FRICTION = 0.4f; @@ -54,7 +53,6 @@ constexpr float ATTACK_FRICTION = 0.4f; constexpr float GAPER_OVERKILL = -25; constexpr int GUSHER_ODDS = 3; constexpr int GUSHER_COOLDOWN_MIN = 20; -constexpr int GUSHER_COOLDOWN_RANGE = 20; // The groans: one time in three while it sees its target, each kind with its own delay. constexpr int GROAN_ODDS = 3; @@ -642,7 +640,7 @@ void npc_gaper_update(Entity_NPC& npc) if (npc.type == ENTITY_CYCLOPIA && npc.state == NPC_STATE_ATTACK) cyclopia_attack_update(npc); if (npc.type != ENTITY_STONEY || npc.state != NPC_STATE_SPECIAL) - npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); + npc.AnimWalkFrame("WalkHori", "WalkVert", MOVEMENT_DEADZONE); npc.aiFloat = gaper_speed_get(npc); if (!npc.HasEntityFlags(FLAG_SHRINK | FLAG_FEAR)) { diff --git a/src/npc_gusher.cpp b/src/npc_gusher.cpp index cac142d..39b0057 100644 --- a/src/npc_gusher.cpp +++ b/src/npc_gusher.cpp @@ -7,7 +7,6 @@ // The headless enemies this AI runs: the Gusher and Pacer, Blubber and Half Sack, Splasher and the Black Globin's body. constexpr int ENTITY_HALF_SACK = 211; -constexpr float WALK_THRESHOLD_GUSHER = 0.1f; constexpr float GUSHER_DEADZONE = 0.1f; // Gushers wait 20 to 39 frames to start, 40 to 59 between shots (Splashers 60 to 89), shooting at 5 along their walk @@ -15,7 +14,6 @@ constexpr float GUSHER_DEADZONE = 0.1f; constexpr int GUSHER_START_MIN = 20; constexpr int GUSHER_START_RANGE = 20; constexpr int GUSHER_COOLDOWN = 40; -constexpr int GUSHER_COOLDOWN_RANGE = 20; constexpr int SPLASHER_COOLDOWN = 60; constexpr int SPLASHER_COOLDOWN_RANGE = 30; constexpr int BLUBBER_COOLDOWN = 30; @@ -235,7 +233,7 @@ void npc_gusher_update(Entity_NPC& npc) } if (npc.type == ENTITY_SPLASHER && npc.pendingDamage > 0) npc_hostile_damage_ignore(npc, DAMAGE_EXPLOSION); - npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD_GUSHER); + npc.AnimWalkFrame("WalkHori", "WalkVert", MOVEMENT_DEADZONE); if (is_bleeding_gusher(npc)) { npc_overlay_loop(npc.sprite, "Blood"); diff --git a/src/npc_guts.cpp b/src/npc_guts.cpp index 6c2279a..faff5ea 100644 --- a/src/npc_guts.cpp +++ b/src/npc_guts.cpp @@ -183,9 +183,20 @@ static void guts_deform(Entity_NPC& npc) } } -// The Slog's prey, picked anew every other frame while it keeps its wits, and its eye turned toward it. -// The original scores the players by its own measure (FUN_00515290, the distance cut where the prey's next steps lie -// on a lane), which game_nearest_target_player does not take yet: it scores them by distance. +// 00515290 The Slog's measure of a prey: its squared distance, at a hundredth when its next 5 frames end in an open +// lane from the Slog, doubled otherwise. +static float slog_prey_distance(const Vector& position, Entity*, Entity& prey) +{ + constexpr float LANE_SHARE = 0.01f; + constexpr float OFF_LANE_SCALE = 2; + + Vector lead = vector_add(vector_scale(prey.velocity, SLOG_LEAD_FRAMES), prey.pos); + bool isLane = !vector_is_zero(room_grid_line_direction(position, line_cell_stop_get(prey.pos, lead))); + return vector_length_squared(vector_sub(prey.pos, position)) * (isLane ? LANE_SHARE : OFF_LANE_SCALE); +} + +// The Slog's prey by its own measure, picked anew every other frame while it keeps its wits (a charmed one's the +// nearest enemy, else a player), and its eye turned toward it. static Entity* slog_target_get(Entity_NPC& npc) { Entity* target = nullptr; @@ -194,9 +205,10 @@ static Entity* slog_target_get(Entity_NPC& npc) if (isRetargeting) { if (npc.HasEntityFlags(FLAG_CHARM)) - reconstruction_missing("NpcAI::ENTITY_GUTS 005153b0: a charmed Slog's prey (Game::GetNearestEnemy)"); - target = game_nearest_target_player(npc.pos, &npc, npc.HasEntityFlags(FLAG_FRIENDLY), - npc.decoyTargetTimer >= 0, SLOG_TARGET_RANGE); + target = game_nearest_enemy(npc.pos, &npc, SLOG_TARGET_RANGE, slog_prey_distance); + if (!target) + target = game_nearest_target_player(npc.pos, &npc, npc.HasEntityFlags(FLAG_FRIENDLY), + npc.decoyTargetTimer >= 0, SLOG_TARGET_RANGE, slog_prey_distance); npc.target = target; } if (!target) target = npc.GetPlayerTarget(); diff --git a/src/npc_hive.cpp b/src/npc_hive.cpp index a3c855f..ffe7f01 100644 --- a/src/npc_hive.cpp +++ b/src/npc_hive.cpp @@ -31,7 +31,6 @@ constexpr float TAINTED_REST = 210; constexpr float CALM_REST = 3; constexpr float HIVE_FRICTION = 0.8f; constexpr float DROWNED_FRICTION = 0.95f; -constexpr float WALK_THRESHOLD = 0.1f; // The holy Hive's baby flies out sideways at 8 in a burst of blood. constexpr float BABY_SPEED = 8; @@ -113,7 +112,7 @@ static void hive_walk_update(Entity_NPC& npc) npc.sprite.Play("WalkVert"); if (std::abs(npc.velocity.y) < std::abs(npc.velocity.x)) npc.sprite.isFlipX = npc.velocity.x < 0; } - else npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); + else npc.AnimWalkFrame("WalkHori", "WalkVert", MOVEMENT_DEADZONE); if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) { @@ -286,7 +285,7 @@ void npc_hive_update(Entity_NPC& npc) if (npc.type == ENTITY_HIVE && (npc.variant == HIVE_HOLY || npc.variant == HIVE_TAINTED)) { npc.friction *= HIVE_FRICTION; - npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); + npc.AnimWalkFrame("WalkHori", "WalkVert", MOVEMENT_DEADZONE); } if (npc.sprite.overlayAnimState.IsEventTriggered("Shoot")) hive_release(npc); if (!npc.sprite.overlayAnimState.animData || !npc.sprite.overlayAnimState.isPlaying) diff --git a/src/npc_horf.cpp b/src/npc_horf.cpp index 14252cd..9cae2bd 100644 --- a/src/npc_horf.cpp +++ b/src/npc_horf.cpp @@ -12,7 +12,6 @@ constexpr int HORF_COOLDOWN = 28; constexpr int HORF_HARD_COOLDOWN = 14; constexpr float HORF_SHOT_SPEED = 7; constexpr float HORF_HARD_SHOT_SPEED = 10; -constexpr float MOVEMENT_DEADZONE = 0.1f; constexpr float SPIT_OFFSET_Y = -10; constexpr float SPIT_DEPTH = 1; constexpr float PITCH_TINY = 1.5f; diff --git a/src/npc_render_parts.cpp b/src/npc_render_parts.cpp index d0e9a4d..54481d9 100644 --- a/src/npc_render_parts.cpp +++ b/src/npc_render_parts.cpp @@ -6,7 +6,6 @@ // 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_LINK_SHOWN = NPC_STATE_JUMP; -constexpr int CHIMERA_BODY = 1; constexpr int CHIMERA_BODY_LAYER = 2; constexpr int CHIMERA_SPLIT = NPC_STATE_SPECIAL; diff --git a/src/npc_ultra_coin.cpp b/src/npc_ultra_coin.cpp index 578ea4e..637898b 100644 --- a/src/npc_ultra_coin.cpp +++ b/src/npc_ultra_coin.cpp @@ -74,7 +74,7 @@ static bool ultra_coin_is_tough() { if (g_manager->persistentGameData.achievements[ACHIEVEMENT_EVERYTHING_IS_TERRIBLE_2]) return true; if (g_manager->state != MANAGER_STATE_GAME || !g_game) return false; - return g_game->dailyChallenge._id != 0 || g_game->isDebug; + return g_game->dailyChallenge.id != 0 || g_game->isDebug; } // 0059e2a0 NpcHelper::UltraGreed_Heal: Ultra Greed heals a share of its health and flashes green. diff --git a/src/options_config.cpp b/src/options_config.cpp index a992fa3..ca01699 100644 --- a/src/options_config.cpp +++ b/src/options_config.cpp @@ -14,11 +14,9 @@ constexpr const char* CONFIG_INI = "config.ini"; constexpr const char* OPTIONS_INI = "options.ini"; constexpr std::string_view LEGACY_SAVE_FOLDER = "Binding of Isaac Afterbirth+"; -constexpr std::string_view SAVE_FOLDER = "Binding of Isaac Repentance+"; constexpr std::string_view WHITESPACE = " \t\f\v\r\n"; constexpr int LINE_LENGTH = 256; constexpr int ONLINE_INPUT_DELAY_MAX = 5; -constexpr int ONLINE_LEVEL_MAX = 10; constexpr WindowSetting LOAD_WINDOW_SETTINGS[] = {WINDOW_VSYNC, WINDOW_CURSOR, WINDOW_POSITION, WINDOW_FULLSCREEN}; // The pieces std::getline cuts text into at separator, which drops an empty last piece. diff --git a/src/options_config.h b/src/options_config.h index 5a0b99d..b409caf 100644 --- a/src/options_config.h +++ b/src/options_config.h @@ -7,6 +7,7 @@ constexpr float DEFAULT_VOLUME = 0.3f; constexpr int DEFAULT_MAX_RENDER_SCALE = 2; constexpr int DEFAULT_MAX_SCALE = 99; +constexpr int ONLINE_LEVEL_MAX = 10; constexpr int DEFAULT_ONLINE_INPUT_DELAY = 3; constexpr int DEFAULT_ONLINE_PLAYER_OPACITY = 10; constexpr int DEFAULT_ONLINE_PLAYER_VOLUME = 6; diff --git a/src/path_finder.cpp b/src/path_finder.cpp index 1e95626..c631ed2 100644 --- a/src/path_finder.cpp +++ b/src/path_finder.cpp @@ -75,7 +75,6 @@ constexpr float EVADE_PATH_SPEED = 1.079f; // The grid paths a cell's cost means: a pit band and a blocked band some grid collisions ignore, the highest cost a // path still crosses, and what a rock crusher pays to walk through rocks and through hazards. -constexpr int GRID_PATH_IMPASSABLE = 950; constexpr int GRID_PATH_SOLID_CELL = 1000; constexpr int GRID_PATH_POOP_CELL = 1500; constexpr int GRID_PATH_SLOWING_MAX = 949; diff --git a/src/pause_screen.cpp b/src/pause_screen.cpp index f05e9fd..7742a7e 100644 --- a/src/pause_screen.cpp +++ b/src/pause_screen.cpp @@ -3,7 +3,14 @@ #include "entity_player.h" #include "fx_layers.h" #include "game.h" +#include "game_end.h" #include "hud.h" +#include "mod_manager.h" +#include "render_passes.h" +#include "game_over.h" +#include "entity_config.h" +#include "item_pool.h" +#include "item_info_hud.h" #include "kage_input.h" #include "log.h" #include "manager.h" @@ -41,14 +48,60 @@ constexpr const char* ONLINE_LAYERS[] = {LAYER_INVITE, LAYER_KICK, "InviteKey", constexpr const char* QUIT_DAILY_LINES[] = {"#QUIT_DAILY_RUN_1", "#QUIT_DAILY_RUN_2", "#QUIT_DAILY_RUN_3", "#QUIT_DAILY_RUN_4"}; +// The My Stuff page: how long a direction is held before it repeats and how often, the rows the grid scrolls by, the +// heights and widths its descriptions fit (measured 120 wide), its arrows, nulls and section cursor, the grid of items +// and the player's icon, and the titles' layout (an item's charge icon, the pocket item's sprite). +constexpr int HOLD_REPEAT_DELAY = 30; +constexpr int HOLD_REPEAT_INTERVAL = 15; +constexpr int ITEMS_SCROLL_STEP = 6; +constexpr float ITEM_DESCRIPTION_HEIGHT = 100; +constexpr float SIDE_DESCRIPTION_HEIGHT = 30; +constexpr int DESCRIPTION_MEASURE_WIDTH = 120; +constexpr int ITEM_DESCRIPTION_WIDTH = 130; +constexpr int SIDE_DESCRIPTION_WIDTH = 120; +constexpr const char* LAYER_DESCRIPTION_UP = "DescriptionArrowUp"; +constexpr const char* LAYER_DESCRIPTION_DOWN = "DescriptionArrowDown"; +constexpr const char* LAYER_ITEMS_UP = "ItemsArrowUp"; +constexpr const char* LAYER_ITEMS_DOWN = "ItemsArrowDown"; +constexpr const char* LAYER_TRINKET_UP = "TrinketArrowUp"; +constexpr const char* LAYER_TRINKET_DOWN = "TrinketArrowDown"; +constexpr const char* LAYER_POCKET_UP = "PocketArrowUp"; +constexpr const char* LAYER_POCKET_DOWN = "PocketArrowDown"; +constexpr const char* LAYER_TRINKETS = "Trinkets"; +constexpr const char* NULL_BACK_BUTTON = "BackButton"; +constexpr const char* NULL_COLLECTIBLE_TITLE = "CollectibleTitle"; +constexpr const char* NULL_COLLECTIBLE_DESC = "CollectibleDesc"; +constexpr const char* NULL_COLLECTIBLE_POOLS = "CollectibleItemPools"; +constexpr const char* NULL_TRINKET_TITLE = "TrinketTitle"; +constexpr const char* NULL_TRINKET_DESC = "TrinketDesc"; +constexpr const char* NULL_POCKET_TITLE = "PocketTitle"; +constexpr const char* NULL_POCKET_DESC = "PocketDesc"; +constexpr float SECTION_CURSOR_DROP = 3; +constexpr float GRID_OFFSET_X = 110; +constexpr float GRID_OFFSET_Y = 29; +constexpr float MOD_ITEM_OFFSET_X = -36; +constexpr float MOD_ITEM_OFFSET_Y = -15; +constexpr float ITEM_GRID_CELL = 20; +constexpr float GRID_CURSOR_X = 10; +constexpr float GRID_CURSOR_Y = 8; +constexpr float PLAYER_ICON_OFFSET_X = 26; +constexpr float PLAYER_ICON_OFFSET_Y = 22; +constexpr float PLAYER_ICON_SCALE = 2; +constexpr float ENTRY_TEXT_Y = 7; +constexpr float ITEM_CHARGE_OFFSET = 105; +constexpr float CHARGE_OFFSET_BACK = 4; +constexpr float CHARGE_OFFSET_Y = 16; +constexpr float POCKET_SPRITE_X = 16; +constexpr float POCKET_PILL_Y = 23; +constexpr float POCKET_CARD_Y = 17; +constexpr float POCKET_CHARGE_X = 101; + constexpr float DESCRIPTION_LINE_SPACING = 0.9f; constexpr float PAPER_X = 0.7f; constexpr float PAPER_BOTTOM_MARGIN = 0.025f; constexpr float SEED_LINE_HEIGHT = 15; constexpr uint32_t PAPER_TEXT_ARGB = 0xff362f2d; constexpr float SOUND_VOLUME = 0.7f; -constexpr int SOUND_PAPER_IN = 17; -constexpr int SOUND_PAPER_OUT = 18; constexpr float FADE_SPEED = 0.08f; constexpr int FADE_TARGET_MENU = 2; constexpr int KEYBOARD = 0; @@ -122,23 +175,632 @@ void PauseScreen_MyStuff::diary_load() layer_show(diarySprite, LAYER_ITEMS, true); } -// 008d3250 Closes the page, hides its cursor and forgets the item images its descriptions loaded. -// The item lists and selection it also clears belong to the page's update, not written yet. +// 008d3250 Closes the page on the item list: no players, entries, images or scrolling, the cursor hidden and the item +// images its descriptions loaded forgotten. void PauseScreen_MyStuff::reset() { isOpen = false; + tab = TAB_ITEMS; + itemsScroll = 0; + selectedItem = 0; + itemEntry = nullptr; + itemImage.reset(); + itemScroll = {}; + trinketEntry = nullptr; + trinketImage.reset(); + trinketScroll = {}; + pocketEntry = nullptr; + pocketSprite.Reset(); + pocketId = -1; + pocketScroll = {}; + holdX = 0; + holdY = 0; if (pageSprite.isLoaded) layer_show(pageSprite, LAYER_CURSOR, false); + players.clear(); + selectedPlayer = 0; + trinketSlot = 0; + pocketSlot = 0; if (descriptionText.icons) descriptionText.icons->images.clear(); } -void PauseScreen_MyStuff::Update() +// Whether a held direction acts this frame: when first held, then every 15 frames past half a second. +static bool is_hold_step(int heldFrames) { - reconstruction_missing("PauseScreen_MyStuff::Update 008d3360 (with 008d3890, 008d4040, 008d42a0, 008d84f0)"); + return heldFrames == 1 || (heldFrames > HOLD_REPEAT_DELAY && heldFrames % HOLD_REPEAT_INTERVAL == 0); } +// The player whose items show, if any. +Entity_Player* PauseScreen_MyStuff::player_get() +{ + return players.empty() ? nullptr : players[selectedPlayer]; +} + +// Whether a player still holds an item of its history: the collectible, or the trinket. +static bool is_item_held(Entity_Player& owner, const HistoryItem& item) +{ + return item.isTrinket ? owner.HasTrinket((uint32_t)item.id, ITEM_CHECK_MODIFIED) : owner.HasCollectible(item.id); +} + +// The items of a player's history it still holds, its collectibles then its trinkets, in pickup order. +static std::vector items_shown_get(Entity_Player& owner) +{ + std::vector shown; + for (bool isTrinket : {false, true}) + for (const HistoryItem& item : owner.history.historyItems) + if (item.isTrinket == isTrinket && is_item_held(owner, item)) shown.push_back(item); + return shown; +} + +// 008d3360 Counts how long the menu directions are held, closes on back, and otherwise follows the players, steps the +// tab between the sections that have something (the description only with an item), and updates the item list, the +// descriptions' scrolling and their arrows. With no player to show the page closes. +void PauseScreen_MyStuff::Update() +{ + holdX = is_action(ACTION_MENU_LEFT, ACTION_PRESSED) || is_action(ACTION_MENU_RIGHT, ACTION_PRESSED) ? holdX + 1 : 0; + holdY = is_action(ACTION_MENU_UP, ACTION_PRESSED) || is_action(ACTION_MENU_DOWN, ACTION_PRESSED) ? holdY + 1 : 0; + if (!is_action(ACTION_MENU_BACK, ACTION_PRESSED)) + { + selection_update(); + if (player_get()) + { + if (is_action(ACTION_MENU_TAB, ACTION_TRIGGERED)) + { + tab = (MyStuffTab)((tab + 1) % TAB_COUNT); + if (tab == TAB_DESCRIPTION && !itemEntry) tab = TAB_TRINKET; + if (tab == TAB_TRINKET && !trinketEntry) tab = TAB_POCKET; + if (tab == TAB_POCKET && !pocketEntry) tab = TAB_ITEMS; + } + items_update(); + if (itemEntry) + { + description_scroll(*itemEntry, itemScroll, ITEM_DESCRIPTION_HEIGHT, tab == TAB_DESCRIPTION); + Entity_Player& paused = *g_game->GetPlayer(g_game->pauseScreen.playerIdx); + int lineCount = itemEntry->count_lines(paused, (uint32_t)itemEntry->id); + layer_show(pageSprite, LAYER_DESCRIPTION_UP, itemScroll.first > 0); + layer_show(pageSprite, LAYER_DESCRIPTION_DOWN, itemScroll.end < lineCount); + } + else + { + layer_show(pageSprite, LAYER_DESCRIPTION_UP, false); + layer_show(pageSprite, LAYER_DESCRIPTION_DOWN, false); + } + trinket_update(); + pocket_update(); + return; + } + } + reset(); + isOpen = false; +} + +// 008d84f0 Lists the players whose items show: the paused one, then its twin, sub player and backup. A changed list +// starts over on its first player. Otherwise drop steps through the players on the item list (starting the sections +// over), through the held trinkets on the trinket tab and the filled pocket slots on the pocket tab. +void PauseScreen_MyStuff::selection_update() +{ + std::vector shown; + if (Entity_Player* paused = g_game->GetPlayer(g_game->pauseScreen.playerIdx)) + for (Entity_Player* player : {paused, paused->twin_get(), paused->subPlayer, paused->backupPlayer}) + if (player) shown.push_back(player); + + auto sectionsRestart = [&]() + { + pocketScroll = {}; + itemScroll = {}; + itemsScroll = 0; + selectedItem = 0; + pocketSlot = 0; + trinketSlot = 0; + trinketScroll = {}; + }; + if (shown != players) + { + players = shown; + selectedPlayer = 0; + return sectionsRestart(); + } + if (players.empty() || !is_action(ACTION_DROP, ACTION_TRIGGERED)) return; + + Entity_Player& player = *player_get(); + if (tab == TAB_ITEMS) + { + int previous = selectedPlayer; + selectedPlayer = (selectedPlayer + 1) % (int)players.size(); + if (selectedPlayer != previous) sectionsRestart(); + } + else if (tab == TAB_TRINKET) + { + int previous = trinketSlot; + do trinketSlot = (trinketSlot - 1) & 1; + while (player.trinkets[trinketSlot] == 0 && trinketSlot != previous); + if (trinketSlot != previous) trinketScroll = {}; + } + else if (tab == TAB_POCKET) + { + int previous = pocketSlot; + do pocketSlot = (pocketSlot + 1) & (POCKET_SLOT_COUNT - 1); + while (player.pocketItems[pocketSlot].id == 0 && pocketSlot != previous); + if (pocketSlot != previous) pocketScroll = {}; + } +} + +// 008d3890 Lists the shown player's held items, then its held trinkets, in pickup order, moves the selection over the +// grid on the item list (a row up or down, held directions repeating) scrolling it by rows, and describes the item +// selected with what losing it changes, ticking as the selection moves. The grid's arrows show what is scrolled off. +// A golden trinket is described anew each frame, as the original compares its id with the golden flag. +void PauseScreen_MyStuff::items_update() +{ + Entity_Player& owner = *player_get(); + std::vector shown = items_shown_get(owner); + int count = (int)shown.size(); + if (count == 0) + { + itemsScroll = 0; + selectedItem = 0; + itemEntry = nullptr; + itemImage.reset(); + layer_show(pageSprite, LAYER_ITEMS_UP, false); + layer_show(pageSprite, LAYER_ITEMS_DOWN, false); + return; + } + + int previous = selectedItem; + if (tab == TAB_ITEMS) + { + if (is_hold_step(holdX) && is_action(ACTION_MENU_LEFT, ACTION_PRESSED)) + selectedItem = std::max(selectedItem - 1, 0); + else if (is_hold_step(holdX) && is_action(ACTION_MENU_RIGHT, ACTION_PRESSED)) + selectedItem = std::min(selectedItem + 1, count - 1); + if (is_hold_step(holdY) && is_action(ACTION_MENU_UP, ACTION_PRESSED)) + { + if (selectedItem >= columns) selectedItem = std::max(selectedItem - columns, 0); + } + else if (is_hold_step(holdY) && is_action(ACTION_MENU_DOWN, ACTION_PRESSED) && + selectedItem + columns <= count - 1) + selectedItem += columns; + + if (selectedItem < itemsScroll) itemsScroll = std::max(itemsScroll - ITEMS_SCROLL_STEP, 0); + else if (selectedItem >= visibleItems + itemsScroll) + itemsScroll = std::min(itemsScroll + ITEMS_SCROLL_STEP, count - 1); + } + + const HistoryItem& selected = shown[selectedItem]; + bool isItemEntry = + itemEntry && (itemEntry->type == INFO_DISPLAY_COLLECTIBLE || itemEntry->type == INFO_DISPLAY_TRINKET); + bool isDescribed = itemEntry && (!isItemEntry || itemEntry->id == selected.id); + if (!isDescribed) + { + InfoDisplay& display = g_manager->infoDisplay; + ItemConfig& items = g_manager->itemConfig; + uint32_t trinket = (uint32_t)selected.id; + itemEntry = selected.isTrinket ? &display.get_trinket(trinket) : &display.get_collectible(selected.id); + itemEntry->stats_set(&owner, PREVIEW_REMOVED, false); + trinket = (uint32_t)itemEntry->id; + ItemConfig_Item* item = selected.isTrinket ? items.GetTrinket(trinket) : items.GetCollectible(itemEntry->id); + if (item) itemImage = Manager::LoadImage(item->gfxFilename); + else itemImage.reset(); + itemScroll = {0, (int)(itemEntry->statLines.size() + itemEntry->lines.size())}; + } + if (selectedItem != previous) + { + SoundPlay play; + int sound = SOUND_MENU_SCROLL; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, play); + } + layer_show(pageSprite, LAYER_ITEMS_UP, itemsScroll > 0); + layer_show(pageSprite, LAYER_ITEMS_DOWN, (uint32_t)visibleItems < (uint32_t)(count - itemsScroll)); +} + +// 008d4040 Describes the trinket in the shown player's chosen slot with what losing it changes (golden or not) and +// scrolls its description, or forgets it when the slot is empty. +// A golden trinket is described anew each frame, as the original compares its id with the golden flag. +void PauseScreen_MyStuff::trinket_update() +{ + Entity_Player& owner = *player_get(); + uint32_t trinket = trinketSlot < TRINKET_SLOT_COUNT ? owner.trinkets[trinketSlot] : 0; + + if (trinket == 0) + { + trinketEntry = nullptr; + trinketImage.reset(); + } + else if (!trinketEntry || trinket != (uint32_t)trinketEntry->id) + { + trinketEntry = &g_manager->infoDisplay.get_trinket(trinket); + trinketEntry->stats_set(&owner, PREVIEW_REMOVED, trinket & TRINKET_GOLDEN_FLAG); + ItemConfig_Item* item = g_manager->itemConfig.GetTrinket((uint32_t)trinketEntry->id & TRINKET_ID_MASK); + if (item) trinketImage = Manager::LoadImage(item->gfxFilename); + else trinketImage.reset(); + } + + bool isShown = trinket != 0 && trinketEntry; + if (isShown) description_scroll(*trinketEntry, trinketScroll, SIDE_DESCRIPTION_HEIGHT, tab == TAB_TRINKET); + int lineCount = isShown ? trinketEntry->count_lines(owner, owner.trinkets[0]) : 0; + layer_show(pageSprite, LAYER_TRINKET_UP, isShown && trinketScroll.first > 0); + layer_show(pageSprite, LAYER_TRINKET_DOWN, isShown && trinketScroll.end < lineCount); +} + +// 008d42a0 Describes the pill or card in the shown player's chosen pocket slot, with the pill's or card's sprite (a +// card from the cards sheet, or its pickup when the sheet lacks its front) and the pill's identification, and scrolls +// its description. An empty slot forgets it. A pocket active item keeps the description before it. +void PauseScreen_MyStuff::pocket_update() +{ + Entity_Player& owner = *player_get(); + PocketItem& pocket = owner.pocketItems[std::clamp(pocketSlot, 0, POCKET_SLOT_COUNT - 1)]; + int shownId = pocket.type == POCKET_PILL || pocket.type == POCKET_CARD ? pocket.id : (int)pocket.type; + + if (shownId == 0) + { + pocketEntry = nullptr; + pocketSprite.Reset(); + } + else if (!pocketEntry || pocketId != shownId || pocketEntry->id != pocket.id) + { + pocketId = shownId; + EntityConfig& entities = g_manager->entityConfig; + if (pocket.type == POCKET_PILL) + { + int effect = g_game->itemPool.GetPillEffect((uint32_t)pocket.id, &owner); + pocketEntry = &g_manager->infoDisplay.get_pill((uint32_t)effect); + pocketEntry->isUnidentified = !g_game->itemPool.IsPillIdentified((uint32_t)pocket.id); + EntityConfig_Entity* config = entities.GetEntity(ENTITY_PICKUP, PICKUP_PILL, pocket.id); + if (!config) pocketSprite.Reset(); + else + { + pocketSprite.Load(config->anm2Path, GRAPHICS_LOAD); + pocketSprite.Play(ANIMATION_IDLE); + } + } + else if (pocket.type == POCKET_CARD) + { + pocketEntry = &g_manager->infoDisplay.get_card(pocket.id); + ItemConfig_Card* card = g_manager->itemConfig.GetCard(pocket.id); + EntityConfig_Entity* config = + card ? entities.GetEntity(ENTITY_PICKUP, PICKUP_TAROTCARD, card->pickupSubtype) : nullptr; + if (!config) pocketSprite.Reset(); + else + { + pocketSprite.Load(CARDS_PILLS_ANM2, GRAPHICS_LOAD); + pocketSprite.SetFrame(ANIMATION_CARD_FRONTS, pocket.id); + bool isFrontShown = false; + for (int layer = 0; layer < (int)pocketSprite.layerStates.size(); layer++) + if (const AnimationFrame* frame = pocketSprite.animState.GetLayerFrame(layer)) + isFrontShown |= frame->isVisible; + if (!isFrontShown) + { + pocketSprite.Load(config->anm2Path, GRAPHICS_LOAD); + pocketSprite.Play(ANIMATION_HUD); + } + } + } + } + + bool isShown = shownId != 0 && pocketEntry; + if (isShown) description_scroll(*pocketEntry, pocketScroll, SIDE_DESCRIPTION_HEIGHT, tab == TAB_POCKET); + int lineCount = isShown ? pocketEntry->count_lines(owner, (uint32_t)owner.pocketItems[0].id) : 0; + layer_show(pageSprite, LAYER_POCKET_UP, isShown && pocketScroll.first > 0); + layer_show(pageSprite, LAYER_POCKET_DOWN, isShown && pocketScroll.end < lineCount); +} + +// 008d8460 The subtype a description's lines are checked against: the trinket in the chosen slot, the pocket item in +// the chosen slot, or a collectible's id. +uint32_t PauseScreen_MyStuff::entry_subtype(const InfoDisplayEntry& entry) +{ + Entity_Player* player = player_get(); + + if (entry.type == INFO_DISPLAY_TRINKET) + return player && trinketSlot < TRINKET_SLOT_COUNT ? player->trinkets[trinketSlot] : 0; + if (entry.type != INFO_DISPLAY_PILL && entry.type != INFO_DISPLAY_CARD) return (uint32_t)entry.id; + return player ? (uint32_t)player->pocketItems[std::clamp(pocketSlot, 0, POCKET_SLOT_COUNT - 1)].id : 0; +} + +// 008d47c0 Fits a description's lines from its first into a height, and on its section's tab scrolls them a line +// down (while more lines follow) or up with the held direction. +void PauseScreen_MyStuff::description_scroll(InfoDisplayEntry& entry, DescriptionScroll& scroll, float maxHeight, + bool isActive) +{ + scroll.end = description_end(entry, scroll.first, maxHeight); + Entity_Player* player = player_get(); + int lineCount = player ? entry.count_lines(*player, entry_subtype(entry)) : 0; + if (!isActive || !is_hold_step(holdY)) return; + + if (is_action(ACTION_MENU_DOWN, ACTION_PRESSED)) + { + if (scroll.end < lineCount) scroll.end = description_end(entry, ++scroll.first, maxHeight); + } + else if (is_action(ACTION_MENU_UP, ACTION_PRESSED) && scroll.first > 0) + scroll.end = description_end(entry, --scroll.first, maxHeight); +} + +// 008d7cb0 The line past the last one that fits in a height when a description shows from a line on: its +// transformations, stat changes and visible lines, each measured 120 wide with the gap after it. +// As the original does, transformations are matched by collectible tags whatever the item, and lines are checked +// against the item's id. +int PauseScreen_MyStuff::description_end(InfoDisplayEntry& entry, int startLine, float maxHeight) +{ + Entity_Player& paused = *g_game->GetPlayer(g_game->pauseScreen.playerIdx); + float height = 0; + int line = 0; + auto isFull = [&](std::string_view text, bool isCounted) + { + if (isCounted && startLine <= line) + height += (float)lineGap + descriptionText.measure(text, DESCRIPTION_MEASURE_WIDTH, ITEM_INFO_BODY_SCALE).y; + return maxHeight <= height; + }; + + for (std::unique_ptr& form : g_manager->itemConfig.playerForms) + { + if (!form) continue; + bool isFormItem = entry.is_form_item(*form); + if (form->tags) isFormItem = ItemConfig::is_collectible_tagged(entry.id, form->tags); + if (!isFormItem) continue; + if (isFull(form_line_get(*form, form_progress_get(*form, &paused)), true)) return line; + line++; + } + for (InfoDisplayText& stat : entry.statLines) + { + if (isFull(stat.text, true)) return line; + line++; + } + for (size_t i = 0; i < entry.lines.size(); i++) + { + if (!entry.is_line_visible(i, paused, (uint32_t)entry.id)) continue; + if (isFull(entry.lines[i].text, true)) return line; + line++; + } + return line; +} + +// 008d3640 Draws the page centered on the screen with its back button's glyph and, while a player shows, its item +// grid, the item, trinket and pocket item sections. void PauseScreen_MyStuff::Render() { - reconstruction_missing("PauseScreen_MyStuff::Render 008d3640 (with render_entry 008d5990)"); + const AnimationFrame* frame = pageSprite.animState.GetLayerFrame(0); + Vector size = frame ? vector_make(frame->width, frame->height) : Vector{}; + Vector origin = vector_make(g_screenWidth * HALF - size.x * HALF, g_screenHeight * HALF - size.y * HALF); + + if (pageSprite.isLoaded) pageSprite.Render({origin}); + int controller = g_game->GetPlayer(g_game->pauseScreen.playerIdx)->controllerIndex; + if (const NullFrame* back = pageSprite.animState.animData ? pageSprite.GetNullFrame(NULL_BACK_BUTTON) : nullptr) + g_manager->render_controller_action_glyph( + {.position = vector_add(origin, back->pos), .action = ACTION_MENU_BACK, .controllerIndex = controller}); + if (!player_get()) return; + + items_render(origin); + item_section_render(origin); + trinket_section_render(origin); + pocket_section_render(origin); +} + +// 008d4940 Draws the shown player's character icon and the grid of its held items and trinkets from the scrolled row, +// each from the diary's item or trinket sheet (a modded collectible by its mod), the page's cursor on the selected +// one (hidden with nothing to show), and the section cursor on the grid while it has the tab. +void PauseScreen_MyStuff::items_render(Vector origin) +{ + Entity_Player& owner = *player_get(); + ItemConfig& items = g_manager->itemConfig; + ColorMod outline = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + Vector iconAt = vector_make(origin.x + PLAYER_ICON_OFFSET_X, origin.y + PLAYER_ICON_OFFSET_Y); + g_game->hud.render_player_type_icon({.color = outline, + .position = iconAt, + .filter = FILTER_NEAREST, + .scale = PLAYER_ICON_SCALE, + .playerType = owner.playerType}); + + std::vector shown = items_shown_get(owner); + + Vector cell{}; + int drawn = 0; + for (int i = itemsScroll; i < (int)shown.size() && drawn < visibleItems; i++) + { + const HistoryItem& item = shown[i]; + uint32_t trinket = (uint32_t)item.id & TRINKET_ID_MASK; + bool isConfigured = item.isTrinket ? items.GetTrinket(trinket) : items.GetCollectible(item.id); + if (!isConfigured || !is_item_held(owner, item)) continue; + + Vector at = vector_make(cell.x + GRID_OFFSET_X + origin.x, cell.y + GRID_OFFSET_Y + origin.y); + if (item.isTrinket || item.id < COLLECTIBLE_VANILLA_COUNT) + { + DiaryLayer layer = item.isTrinket ? DIARY_LAYER_TRINKETS : DIARY_LAYER_ITEMS; + int unknownFrame = item.isTrinket ? DIARY_TRINKET_UNKNOWN_FRAME : DIARY_ITEM_UNKNOWN_FRAME; + layer_show(diarySprite, LAYER_TRINKETS, item.isTrinket); + layer_show(diarySprite, LAYER_ITEMS, !item.isTrinket); + diarySprite.SetLayerFrame(layer, item.id < 1 ? unknownFrame : item.id - 1); + if (diarySprite.isLoaded) diarySprite.RenderLayer(layer, {at}); + } + else + { + bool isPremultiplied = KAGE::Graphics::manager.isPremultipliedAlpha; + ModSpriteDraw draw; + draw.blendMode = {BLEND_EQUATION_ADD, isPremultiplied ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA, + BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, BLEND_FACTOR_ONE, BLEND_FACTOR_ONE_MINUS_SRC_ALPHA}; + draw.position = vector_make(cell.x + MOD_ITEM_OFFSET_X + origin.x, cell.y + MOD_ITEM_OFFSET_Y + origin.y); + g_manager->modManager.RenderCustomCollectionItem((unsigned int)item.id, draw); + } + if (i == selectedItem) + { + layer_show(pageSprite, LAYER_CURSOR, true); + pageSprite.SetLayerFrame(LAYER_CURSOR, drawn); + } + cell.x += ITEM_GRID_CELL; + if (cell.x >= (float)columns * ITEM_GRID_CELL) cell = vector_make(0, cell.y + ITEM_GRID_CELL); + drawn++; + } + if (drawn == 0) layer_show(pageSprite, LAYER_CURSOR, false); + if (tab == TAB_ITEMS) section_cursor_render(vector_make(origin.x + GRID_CURSOR_X, origin.y + GRID_CURSOR_Y)); +} + +// Draws the section cursor at a position. +void PauseScreen_MyStuff::section_cursor_render(Vector position) +{ + apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, *sectionCursorImage); + sectionCursorImage->Render(position, WHITE); +} + +// Draws an item's name (or what it is when unidentified: a pill says so, anything else shows "???"). Whether it shows +// a charge icon, as an active collectible does. +// The original draws an unidentified pill's text in no set color. Here it is the page's ink. +bool PauseScreen_MyStuff::title_text_render(InfoDisplayEntry& entry, Vector at) +{ + KColor ink = kcolor_argb(PAPER_TEXT_ARGB); + bool isPill = entry.type == INFO_DISPLAY_PILL; + if (entry.isUnidentified) + { + StringTable& strings = g_manager->stringTable; + std::string_view text = isPill ? strings.translate(ITEM_INFO_UNIDENTIFIED_PILL) : ITEM_INFO_UNKNOWN; + descriptionText.Render(text, at, ink, ITEM_INFO_TITLE_SCALE); + return false; + } + descriptionText.Render(entry.name, at, ink, ITEM_INFO_TITLE_SCALE); + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(entry.id); + return entry.type == INFO_DISPLAY_COLLECTIBLE && item && item->type == ITEM_ACTIVE; +} + +// 008d5990 Draws an item's title: its image (a Monkey Paw at its fingers left), its name, and an active's charge icon +// below it, chargeOffset along. An unidentified pill names itself so, anything else unidentified shows "???". +void PauseScreen_MyStuff::entry_render(InfoDisplayEntry& entry, Vector position, float chargeOffset, + KAGE::Graphics::ImagePtr image) +{ + Entity_Player& paused = *g_game->GetPlayer(g_game->pauseScreen.playerIdx); + if (image) + { + bool isMonkeyPaw = entry.type == INFO_DISPLAY_TRINKET && entry.id == TRINKET_MONKEY_PAW; + Vector iconSize = vector_make(ITEM_INFO_IMAGE_SIZE, ITEM_INFO_IMAGE_SIZE); + float pawX = (float)(MONKEY_PAW_FRAMES - paused.monkeyPawCounter) * ITEM_INFO_IMAGE_SIZE; + Vector sourceOrigin = isMonkeyPaw ? vector_make(pawX, 0) : Vector{}; + Vector sourceSize = isMonkeyPaw ? iconSize : vector_make((float)image->width, (float)image->height); + apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, *image); + image->Render(KAGE::Graphics::source_quad_rect(sourceOrigin, sourceSize), + KAGE::Graphics::color_quad_rect(position, iconSize, WHITE), WHITE); + } + + Vector at = vector_make(position.x + ITEM_INFO_TITLE_X, position.y + ENTRY_TEXT_Y); + if (!title_text_render(entry, at)) return; + charge_icon_frame_set(chargeSprite, entry.id, paused); + chargeSprite.Render({vector_make(chargeOffset - CHARGE_OFFSET_BACK + at.x, at.y + CHARGE_OFFSET_Y)}); +} + +// 008d5da0 Draws the pocket item's title: its sprite (a pill lower), its name (or what it is when unidentified) and an +// active's charge icon. +void PauseScreen_MyStuff::pocket_title_render(InfoDisplayEntry& entry, Vector position) +{ + if (pocketSprite.isLoaded) + { + float spriteY = entry.type == INFO_DISPLAY_PILL ? POCKET_PILL_Y : POCKET_CARD_Y; + pocketSprite.Render({vector_make(position.x + POCKET_SPRITE_X, position.y + spriteY)}); + } + + Vector at = vector_make(position.x + ITEM_INFO_TITLE_X, position.y + ENTRY_TEXT_Y); + if (!title_text_render(entry, at)) return; + charge_icon_frame_set(chargeSprite, entry.id, *g_game->GetPlayer(g_game->pauseScreen.playerIdx)); + chargeSprite.Render({vector_make(at.x + POCKET_CHARGE_X, at.y + CHARGE_OFFSET_Y)}); +} + +// 008d5f70 Draws the scrolled part of a description, bulleted: the transformations the item counts toward with the +// paused player's progress (highlighted), its stat changes and its visible lines (wrapped to the width), each with the +// gap after it. Unidentified, it shows "???". +void PauseScreen_MyStuff::description_render(InfoDisplayEntry& entry, Vector position, int width, + const DescriptionScroll& scroll) +{ + Entity_Player& paused = *g_game->GetPlayer(g_game->pauseScreen.playerIdx); + KColor ink = kcolor_argb(PAPER_TEXT_ARGB); + KColor highlight = kcolor_argb(ITEM_INFO_FORM_ARGB); + Vector at = position; + int line = 0; + auto lineRender = [&](std::string_view text, KColor color, int maxWidth) + { + if (scroll.first <= line) + { + Vector bullet = vector_make(position.x - ITEM_INFO_BULLET_INDENT, at.y); + descriptionText.Render(ITEM_INFO_BULLET, bullet, ink, ITEM_INFO_BODY_SCALE); + at.y += (float)lineGap + descriptionText.Render(text, at, color, ITEM_INFO_BODY_SCALE, maxWidth).y; + } + return ++line >= scroll.end; + }; + + if (entry.isUnidentified) + { + Vector bullet = vector_make(at.x - ITEM_INFO_BULLET_INDENT, at.y); + descriptionText.Render(ITEM_INFO_BULLET, bullet, ink, ITEM_INFO_BODY_SCALE); + descriptionText.Render(ITEM_INFO_UNKNOWN, at, ink, ITEM_INFO_BODY_SCALE); + return; + } + for (std::unique_ptr& form : g_manager->itemConfig.playerForms) + { + if (!form || !entry.is_form_item(*form)) continue; + std::string formLine = form_line_get(*form, std::min(form_progress_get(*form, &paused), FORM_GOAL)); + if (lineRender(formLine, highlight, RICH_TEXT_NO_WRAP)) return; + } + for (InfoDisplayText& stat : entry.statLines) + if (lineRender(stat.text, ink, RICH_TEXT_NO_WRAP)) return; + for (size_t i = 0; i < entry.lines.size(); i++) + if (entry.is_line_visible(i, paused, entry_subtype(entry)) && lineRender(entry.lines[i].text, ink, width)) + return; +} + +// 008d6b30 (008d69d0) Draws the minimap icon of each pool a collectible comes from, 16 apart, as the item info panel +// shows them. They center as if the red and wooden chests' pools showed none, as the original counts them. +void PauseScreen_MyStuff::pool_icons_render(int collectibleId, Vector position) +{ + std::vector pools = item_pools_shown(collectibleId); + auto isCentered = [](int pool) { return pool != POOL_RED_CHEST && pool != POOL_WOODEN_CHEST; }; + int centered = (int)std::ranges::count_if(pools, isCentered); + Vector at = position; + + if (centered > 1) at.x -= ((float)centered - 1) * ITEM_INFO_POOL_SPACING * HALF; + for (int pool : pools) + { + pool_icon_play(iconsSprite, pool); + if (iconsSprite.isLoaded) iconsSprite.Render({at}); + at.x += ITEM_INFO_POOL_SPACING; + } +} + +// A null of the page at an origin. The original reads a missing null. +static Vector page_null_get(ANM2& page, std::string_view name, Vector origin) +{ + const NullFrame* frame = page.animState.animData ? page.GetNullFrame(name) : nullptr; + return frame ? vector_add(origin, frame->pos) : origin; +} + +// 008d5440 Draws the item section: its title, description, the pools a collectible comes from and the section cursor +// on the description's tab. +void PauseScreen_MyStuff::item_section_render(Vector origin) +{ + if (!itemEntry) return; + + Vector title = page_null_get(pageSprite, NULL_COLLECTIBLE_TITLE, origin); + entry_render(*itemEntry, title, ITEM_CHARGE_OFFSET, itemImage); + Vector description = page_null_get(pageSprite, NULL_COLLECTIBLE_DESC, origin); + description_render(*itemEntry, description, ITEM_DESCRIPTION_WIDTH, itemScroll); + if (itemEntry->type == INFO_DISPLAY_COLLECTIBLE) + pool_icons_render(itemEntry->id, page_null_get(pageSprite, NULL_COLLECTIBLE_POOLS, origin)); + if (tab == TAB_DESCRIPTION) section_cursor_render(vector_make(title.x + 1, title.y + 1)); +} + +// 008d5640 Draws the trinket section: its title, description and the section cursor on its tab. +void PauseScreen_MyStuff::trinket_section_render(Vector origin) +{ + if (!trinketEntry) return; + + Vector title = page_null_get(pageSprite, NULL_TRINKET_TITLE, origin); + entry_render(*trinketEntry, title, ITEM_CHARGE_OFFSET, trinketImage); + Vector description = page_null_get(pageSprite, NULL_TRINKET_DESC, origin); + description_render(*trinketEntry, description, SIDE_DESCRIPTION_WIDTH, trinketScroll); + if (tab == TAB_TRINKET) section_cursor_render(vector_make(title.x, title.y + SECTION_CURSOR_DROP)); +} + +// 008d57f0 Draws the pocket item section: its title, description and the section cursor on its tab. +void PauseScreen_MyStuff::pocket_section_render(Vector origin) +{ + if (!pocketEntry) return; + + Vector title = page_null_get(pageSprite, NULL_POCKET_TITLE, origin); + pocket_title_render(*pocketEntry, title); + Vector description = page_null_get(pageSprite, NULL_POCKET_DESC, origin); + description_render(*pocketEntry, description, SIDE_DESCRIPTION_WIDTH, pocketScroll); + if (tab == TAB_POCKET) section_cursor_render(vector_make(title.x, title.y + SECTION_CURSOR_DROP)); } // 009b5840 Loads the options, My Stuff, the completion marks, the menu paper and the prompt, closed on Resume. @@ -275,7 +937,7 @@ void PauseScreen::Update() if (!isPromptStopped || state != PAUSE_QUIT_PROMPT) return; state = PAUSE_MENU; - if (genericPrompt.submittedSelection == PROMPT_ANSWER_YES) reconstruction_missing("Game::End 006f9770"); + if (genericPrompt.submittedSelection == PROMPT_ANSWER_YES) game_end(ENDING_DEATH); } // Moves the cursor up and down the entries (wrapping) and confirms the one it is on. True once Resume is confirmed. @@ -319,7 +981,7 @@ void PauseScreen::selection_confirm(int controller) break; case PAUSE_ITEM_EXIT: { - if (g_game->dailyChallenge._id != 0) + if (g_game->dailyChallenge.id != 0) { std::array lines; for (size_t i = 0; i < std::size(QUIT_DAILY_LINES); i++) @@ -383,7 +1045,7 @@ void PauseScreen::Render() if (game.roomTransition.mode != 0 && game.roomTransition.bossIntroBossId != 0) return; layer_show(menuSprite, LAYER_MENU_TITLE, false); - layer_show(menuSprite, LAYER_SEED_PAPER, game.dailyChallenge._id == 0); + layer_show(menuSprite, LAYER_SEED_PAPER, game.dailyChallenge.id == 0); Vector position = vector_make(g_screenWidth * PAPER_X, g_screenHeight - g_screenHeight * PAPER_BOTTOM_MARGIN); switch (state) { @@ -414,7 +1076,7 @@ void PauseScreen::render_seed_paper(Vector position) LayerState* paper = menuSprite.GetLayer(LAYER_SEED_PAPER); if (!paper) return; - paper->isVisible = g_game->dailyChallenge._id == 0; + paper->isVisible = g_game->dailyChallenge.id == 0; const NullFrame* seed = paper->isVisible ? menuSprite.animState.GetNullFrame(NULL_SEED) : nullptr; if (!seed) return; diff --git a/src/pause_screen.h b/src/pause_screen.h index 79e70c8..950dcc2 100644 --- a/src/pause_screen.h +++ b/src/pause_screen.h @@ -1,11 +1,13 @@ #pragma once #include "anm2.h" +#include "info_display.h" #include "completion_widget.h" #include "generic_prompt.h" #include "kage_graphics.h" #include "menu_options.h" #include "rich_text.h" +#include // What the pause screen shows. The invite and player info pages are online only. enum PauseState : int @@ -29,18 +31,60 @@ enum PauseItem : int PAUSE_ITEM_COUNT }; +// The sections of the My Stuff page the tab key steps through: the item list, the item's description, the trinket +// and the pocket item. +enum MyStuffTab : int +{ + TAB_ITEMS, + TAB_DESCRIPTION, + TAB_TRINKET, + TAB_POCKET, + TAB_COUNT +}; + +// The part of a description a section shows: its first line and the line past its last. +struct DescriptionScroll +{ + int first = 0; + int end = 0; +}; + // Destruction (008d2a30) is the default. -// The pause screen's "My Stuff" page (PauseScreen_MyStuff): the paused player's items, trinkets and pocket items with -// their descriptions, its page sheet, the diary it sits on, the charge and room icons and the section cursor. +// The pause screen's "My Stuff" page (PauseScreen_MyStuff): for the paused player and the players sharing their +// items (their twin, sub player and backup), a grid of the items and trinkets held with the chosen one's description, +// the trinket and the pocket item, each description scrolled by the tab's section. It sits on the diary, drawing the +// items from its sheets, with the charge and pool icons and the section cursor. class PauseScreen_MyStuff { public: RichText descriptionText; + std::vector players; + KAGE::Graphics::ImagePtr itemImage; KAGE::Graphics::ImagePtr sectionCursorImage; + KAGE::Graphics::ImagePtr trinketImage; ANM2 chargeSprite; ANM2 diarySprite; ANM2 iconsSprite; ANM2 pageSprite; + ANM2 pocketSprite; + DescriptionScroll itemScroll; + DescriptionScroll pocketScroll; + DescriptionScroll trinketScroll; + InfoDisplayEntry* itemEntry = nullptr; + InfoDisplayEntry* pocketEntry = nullptr; + InfoDisplayEntry* trinketEntry = nullptr; + MyStuffTab tab = TAB_ITEMS; + int columns = 6; + int holdX = 0; + int holdY = 0; + int itemsScroll = 0; + int lineGap = 2; + int pocketId = -1; + int pocketSlot = 0; + int selectedItem = 0; + int selectedPlayer = 0; + int trinketSlot = 0; + int visibleItems = 36; bool isOpen = false; void Init(); @@ -48,6 +92,26 @@ public: void reset(); void Update(); void Render(); + +private: + Entity_Player* player_get(); + void selection_update(); + void items_update(); + void trinket_update(); + void pocket_update(); + void description_scroll(InfoDisplayEntry& entry, DescriptionScroll& scroll, float maxHeight, bool isActive); + int description_end(InfoDisplayEntry& entry, int startLine, float maxHeight); + uint32_t entry_subtype(const InfoDisplayEntry& entry); + void items_render(Vector origin); + void entry_render(InfoDisplayEntry& entry, Vector position, float chargeOffset, KAGE::Graphics::ImagePtr image); + bool title_text_render(InfoDisplayEntry& entry, Vector at); + void pocket_title_render(InfoDisplayEntry& entry, Vector position); + void description_render(InfoDisplayEntry& entry, Vector position, int width, const DescriptionScroll& scroll); + void item_section_render(Vector origin); + void trinket_section_render(Vector origin); + void pocket_section_render(Vector origin); + void section_cursor_render(Vector position); + void pool_icons_render(int collectibleId, Vector position); }; // Construction and destruction (009b5320, 009b5600) are the defaults. diff --git a/src/persistent_game_data.cpp b/src/persistent_game_data.cpp index f0d23ee..a6657dc 100644 --- a/src/persistent_game_data.cpp +++ b/src/persistent_game_data.cpp @@ -177,7 +177,6 @@ constexpr std::array SHARED_COUNTERS = {114, 115, 159, 160, 161, 162, 1 constexpr std::array SHARED_ACHIEVEMENTS = {242, 243, 244, 245, 275, 246, 247, 248, 341, 249, 250, 251}; // The folder names of the earlier games' saves, swapped into this game's save path to find them. -constexpr std::string_view SAVE_FOLDER = "Binding of Isaac Repentance+"; constexpr std::string_view SAVE_FOLDER_AFTERBIRTH = "Binding of Isaac Afterbirth"; constexpr std::string_view SAVE_FOLDER_AFTERBIRTH_PLUS = "Binding of Isaac Afterbirth+"; constexpr std::string_view SAVE_FOLDER_REBIRTH = "Binding of Isaac Rebirth"; @@ -812,7 +811,7 @@ bool PersistentGameData::Unlocked(int achievementID) { if (achievementID == ACHIEVEMENT_NEVER || achievementID >= ACHIEVEMENT_COUNT) return false; if (achievementID <= 0 || achievements[achievementID]) return true; - return g_manager->state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge._id != 0 || g_game->isDebug); + return g_manager->state == MANAGER_STATE_GAME && g_game && (g_game->dailyChallenge.id != 0 || g_game->isDebug); } // 00929b40 Adds to an event counter (which stops at 0) and checks every unlock counters and completion marks give. diff --git a/src/persistent_game_data.h b/src/persistent_game_data.h index 2796523..2b4bec2 100644 --- a/src/persistent_game_data.h +++ b/src/persistent_game_data.h @@ -21,7 +21,11 @@ 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_BUTTER = 360; +constexpr int ACHIEVEMENT_SOUL_OF_EDEN = 627; +constexpr int ACHIEVEMENT_PLUM_FLUTE = 410; constexpr int ACHIEVEMENT_RED_KEY = 415; +constexpr int ACHIEVEMENT_FORGOTTEN_HORSEMAN = 66; constexpr int ACHIEVEMENT_THE_VOID = 320; constexpr int ACHIEVEMENT_RERUN = 337; constexpr int ACHIEVEMENT_BLUE_BABY = 32; @@ -39,6 +43,7 @@ constexpr int ACHIEVEMENT_STORE_UPGRADE_3 = 153; constexpr int ACHIEVEMENT_STORE_UPGRADE_4 = 154; constexpr int ACHIEVEMENT_ITEM_INFO = 641; constexpr int ACHIEVEMENT_LIL_SPEWER = 384; +constexpr int ACHIEVEMENT_SUPER_TINTED_ROCK = 323; constexpr int BOSS_COUNT = 104; constexpr int CHALLENGE_COUNT = 46; constexpr int COLLECTIBLE_SEEN_COUNT = 733; diff --git a/src/platform.cpp b/src/platform.cpp index dd5f6a2..7423eff 100644 --- a/src/platform.cpp +++ b/src/platform.cpp @@ -25,7 +25,6 @@ #include #include -constexpr const char* SAVE_FOLDER = "Binding of Isaac Repentance+"; constexpr const char* SAVE_FOLDER_ERROR = "Failed to obtain writable save data directory!"; constexpr const char* SAVE_PATHS_NOTICE = "This file is purely informational. Changing it will have no effect on saving or loading data.\n\n"; @@ -45,7 +44,6 @@ constexpr ActionBinding EMPTY_BINDING = {-1, -1, -1, -1}; // A frame shorter than this share of FRAME_TIME is short, and this many in a row switch the pacing over. constexpr double SHORT_FRAME_RATIO = 1.1; constexpr int PACING_SWITCH_FRAMES = 30; -constexpr int MESSAGE_LENGTH = 1024; constexpr int TARGET_HZ = 60; constexpr float REFRESH_TOLERANCE = 0.04f; @@ -167,7 +165,7 @@ static void folder_create(const std::string& path, const char* error) // The game's own folder, where it kept mods/, data/ and savedatapath.txt, is resources/ here. Mod data goes with saves. void Platform::directories_load() { - char* prefPath = SDL_GetPrefPath("", SAVE_FOLDER); + char* prefPath = SDL_GetPrefPath("", SAVE_FOLDER.data()); userDataDirectory = prefPath ? prefPath : ""; SDL_free(prefPath); if (userDataDirectory.empty()) SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", SAVE_FOLDER_ERROR, nullptr); diff --git a/src/platform.h b/src/platform.h index c4eb85d..6e615ab 100644 --- a/src/platform.h +++ b/src/platform.h @@ -13,6 +13,8 @@ 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; +constexpr int DIGIT_BASE = 10; +constexpr std::string_view SAVE_FOLDER = "Binding of Isaac Repentance+"; struct SDL_GLContextState; struct SDL_Window; diff --git a/src/player_hud.cpp b/src/player_hud.cpp index 52f315f..8d7e23b 100644 --- a/src/player_hud.cpp +++ b/src/player_hud.cpp @@ -82,7 +82,6 @@ constexpr int GOLD_RESET_SLOT = 5; constexpr int ROOM_INDEX_DEATHMATCH = -19; constexpr float DEATHMATCH_BAR_SHIFT_X = -4; constexpr float DEATHMATCH_BAR_SHIFT_Y = -6; -constexpr int ONLINE_HUD_COMPACT = 1; // Esau's row of the compact twin layout: how far it drops, and the line between it and Jacob's. constexpr float ESAU_HEARTS_DROP = 34; @@ -762,7 +761,7 @@ void PlayerHUD::RenderHearts(Vector& outExtent, ANM2& sprite, PlayerHudLayout la Vector from = vector_make(at.x - ESAU_LINE_LEFT, at.y - ESAU_LINE_RISE); Vector to = vector_make(at.x + ESAU_LINE_RIGHT, at.y - ESAU_LINE_RISE); KColor white = kcolor_rgba(1, 1, 1, 1); - render_color_quad(&from, &to, &white, &white, 1); + render_color_quad(from, to, white, white, 1); } isCompact = true; } @@ -1375,7 +1374,7 @@ static bool card_front_set(HUD& hud, int id) ANM2& cards = hud.cardsPillsSprite; if (id >= CARD_FRONT_COUNT) return true; - cards.SetFrame("CardFronts", id); + cards.SetFrame(ANIMATION_CARD_FRONTS, id); for (int layer = 0; layer < (int)cards.layerStates.size(); layer++) { const AnimationFrame* frame = cards.animState.GetLayerFrame(layer); @@ -1478,7 +1477,7 @@ void PlayerHUD::RenderPocketItems(Vector at, PlayerHudLayout layout, float alpha ANM2& sprite = pocketItems[0].sprite; if (sprite.isLoaded) { - sprite.SetFrame("HUD", 0); + sprite.SetFrame(ANIMATION_HUD, 0); sprite.Render({spot, {}, {}}); } } diff --git a/src/player_manager.cpp b/src/player_manager.cpp index 2651fae..89ed42e 100644 --- a/src/player_manager.cpp +++ b/src/player_manager.cpp @@ -18,6 +18,7 @@ #include "popups.h" #include "preload_manager.h" #include "room.h" +#include "room_grid.h" #include "seeds.h" #include "texture_cache.h" #include @@ -828,7 +829,152 @@ void PlayerManager::trigger_new_room_effects() } } -void PlayerManager::RemoveCoPlayer(Entity_Player*) { reconstruction_missing("PlayerManager::RemoveCoPlayer 009ba000"); } +// A co-op baby's hearts going back to the main player it followed: its black hearts first for Black Baby, its heart +// for Red, White and Blue Baby, then (unless the main player is dead, its owner or kids mode) every soul, black and bone +// heart in order, its heart containers and red hearts. +static void coop_baby_hearts_return(Entity_Player& baby, Entity_Player& main) +{ + switch (baby.babySkin) + { + case BABY_BLACK: + for (int i = baby.soulHearts - 1; i >= 0; i--) + if (i <= baby.soulHearts && i % 2 == 1 && (baby.blackHearts & (1 << ((i - 1) / 2 & 31)))) + { + baby.blackHearts &= ~(1 << (i / 2 & 31)); + baby.ClampGoldenHearts(false); + baby.update_bone_hearts(); + baby.AddSoulHearts(-2, false); + } + break; + case BABY_RED: + baby.AddMaxHearts(-2, false); + break; + case BABY_WHITE: + main.AddEternalHearts(-1); + break; + case BABY_BLUE: + baby.AddSoulHearts(-2, false); + break; + default: + break; + } + if (main.isDead || baby.parent.get() == &main || g_game->seedEffects.HasSeedEffect(SEED_KIDS_MODE)) return; + + int bonesLeft = baby.boneHearts; + int soulLeft = baby.soulHearts; + int soulIndex = 1; + for (int slot = 0; soulLeft > 0 || bonesLeft > 0; slot++) + { + if (bonesLeft > 0 && baby.boneHearts > 0 && (baby.boneHeartsMask & (1 << (slot & 31)))) + { + main.AddBoneHearts(1); + bonesLeft--; + continue; + } + bool isBlack = soulIndex <= baby.soulHearts && (baby.blackHearts & (1 << ((soulIndex - 1) / 2 & 31))); + if (isBlack) main.AddBlackHearts(std::min(soulLeft, 2)); + else main.AddSoulHearts(std::min(soulLeft, 2), false); + soulLeft -= 2; + soulIndex += 2; + } + main.AddMaxHearts(baby.maxHearts, false); + main.AddHearts(baby.redHearts, true, false); +} + +// (0083bc50) Empties a player's entry of a HUD's per-player slots and moves it after the others. +template static void hud_slot_remove(Slots& slots, Entity_Player* player) +{ + auto slot = std::ranges::find(slots, player, &Slots::value_type::player); + if (slot == slots.end()) return; + + slot->player = nullptr; + std::rotate(slot, slot + 1, slots.end()); +} + +// Takes an entity out of every list of the room without freeing it. +static void entity_detach(EntityList& list, Entity* entity) +{ + for (EntityList_EL* sublist : {&list.mainEL, &list.updateEL, &list.persistentEL, &list.renderEL, &list.wispEL}) + sublist->remove(entity); + entity->isValid = false; + list.invalidate_type_cache(entity->type, entity->variant, entity->subtype); +} + +// 009ba000 Takes a player out of the run: frees its color, drops the extra player outright, hands a co-op baby's hearts +// and familiars to its main player or drops another player's trinkets and pocket items, removes its familiars, then +// takes it out of the list and the room, resets the join seats, frees its HUD slots and detaches the enemies it +// controlled. +void PlayerManager::RemoveCoPlayer(Entity_Player* player) +{ + if (!player) return; + Game& game = *g_game; + Room& room = *game.room; + int controller = player->controllerIndex; + Entity_Player* twin = player->twin_get(); + + bool isLeadTwin = !twin || twin->playerIndex == -1 || player->playerIndex <= twin->playerIndex || twin == player; + if (isLeadTwin && !player->parent) + { + log_printf(LOG_INFO, "Clearing player color assignment for controllerId %d \n", controller); + if (auto color = std::ranges::find(colorControllers, controller); color != colorControllers.end()) *color = -1; + } + + if (player->variant == PLAYER_VARIANT_EXTRA) + { + for (Entity* entity : room.entityList.updateEL) + { + if (entity && entity->type == ENTITY_PLAYER && game.deathmatchManager.is_active()) + reconstruction_missing("PlayerManager::RemoveCoPlayer 009ba000 (a versus player's controller)"); + auto* npc = dynamic_cast(entity); + if (npc && npc->controllerID == controller) npc->controllerID = -1; + } + std::erase(extraPlayers, player); + for (size_t i = 0; i < extraPlayers.size(); i++) extraPlayers[i]->playerIndex = (int)i; + // The original goes on with the deleted player and crashes, so this stops here. + delete player; + return; + } + + if (player->variant == PLAYER_VARIANT_COOP_BABY) + { + Entity_Player* main = player->GetMainPlayer(); + coop_baby_hearts_return(*player, *main); + for (Entity* entity : entity_query(ENTITY_FAMILIAR, -1)) + { + auto* familiar = static_cast(entity); + if (familiar->spawnerVariant == PLAYER_VARIANT_COOP_BABY) familiar->Remove(); + else if (familiar->player == player) familiar->set_player(main); + } + } + else + { + if (room.isInitialized) + { + for (int i = 0; i < TRINKET_SLOT_COUNT; i++) + player->DropTrinket(room_free_pickup_position_find({.position = player->pos}), false); + for (uint32_t slot = 0; slot < player->GetMaxPocketItems(); slot++) + player->DropPocketItem((int)slot, room_free_pickup_position_find({.position = player->pos})); + } + for (Entity* entity : entity_query(ENTITY_FAMILIAR, -1)) + if (static_cast(entity)->player == player) entity->Remove(); + } + + player->release_weapons_and_effects(true); + player_remove(player); + player->Remove(); + player->playerIndex = -1; + for (size_t i = 0; i < playerList.size(); i++) playerList[i]->playerIndex = (int)i; + coop_slots_reset(); + hud_slot_remove(game.hud.historyHUD.players, player); + hud_slot_remove(game.hud.statHUD.players, player); + game.hud.AssignPlayerHUDs(); + + std::vector controlled; + for (Entity* entity : room.entityList.updateEL) + if (auto* npc = dynamic_cast(entity); npc && npc->controllerID == controller) + controlled.push_back(npc); + for (Entity* npc : controlled) entity_detach(room.entityList, npc); +} // 0083bed0 Has the recent items HUD follow a player replaced by another: the two trade their entries, each refreshed. static void history_player_swap(HistoryHUD& history, Entity_Player* oldPlayer, Entity_Player* newPlayer) @@ -967,7 +1113,22 @@ Entity_Player* PlayerManager::get_player_by_user_id(uint64_t) { reconstruction_missing("PlayerManager::get_player_by_user_id 0090abf0"); } -void PlayerManager::add_lost_curse(int) { reconstruction_missing("PlayerManager::add_lost_curse 009be850"); } + +// 009be850 Gives every player the Lost's curse, and each one's backup player too unless it has it already. +void PlayerManager::add_lost_curse() +{ + ItemConfig_Item* item = g_manager->itemConfig.GetNullItem(NULLITEM_LOST_CURSE); + if (!item) return; + + for (Entity_Player* player : playerList) + { + player->temporaryEffects.AddEffect(TemporaryEffect(item), true, 1); + Entity_Player* backup = player->backupPlayer; + if (backup && !backup->temporaryEffects.HasNullEffect(NULLITEM_LOST_CURSE)) + backup->temporaryEffects.AddEffect(TemporaryEffect(item), true, 1); + } +} + void PlayerManager::spawn_coop_baby_for_join(int) { reconstruction_missing("PlayerManager::spawn_coop_baby_for_join 009bd3b0"); @@ -1028,7 +1189,7 @@ static void controller_join_update(PlayerManager& players, KAGE::Input::InputDev bool isJoinAllowed = !PlayerManager::CoopBabiesOnly() || players.GetPlayer(0)->soulHearts + players.GetPlayer(0)->redHearts >= COOP_BABY_MIN_HEARTS; - if (game.dailyChallenge._id == 0 && isJoinAllowed && players.playerList.size() < MAX_PLAYERS && !isJoined) + if (game.dailyChallenge.id == 0 && isJoinAllowed && players.playerList.size() < MAX_PLAYERS && !isJoined) { int slot = is_controller_action(controller, ACTION_JOIN_MULTIPLAYER, ACTION_TRIGGERED) ? players.GetPlayerSlotFromController(controller) : -1; @@ -1036,7 +1197,7 @@ static void controller_join_update(PlayerManager& players, KAGE::Input::InputDev if (PlayerManager::CoopBabiesOnly()) return players.spawn_coop_baby_for_join(controller); CoopJoinSlot& seat = players.coopSlots[slot]; - bool isForced = game.challenge != 0 || game.dailyChallenge._id != 0; + bool isForced = game.challenge != 0 || game.dailyChallenge.id != 0; if (!isForced) device_action_consume(device, ACTION_JOIN_MULTIPLAYER); seat.playerType = isForced ? game.GetChallengeParams().playerType : 0; seat.state = 1; @@ -1044,7 +1205,7 @@ static void controller_join_update(PlayerManager& players, KAGE::Input::InputDev seat.isPlayerTypeForced = isForced; return; } - if (game.dailyChallenge._id != 0 && !isJoined) + if (game.dailyChallenge.id != 0 && !isJoined) { if (is_controller_action(controller, ACTION_JOIN_MULTIPLAYER, ACTION_TRIGGERED)) manager_sound_play(SOUND_JOIN_REFUSED, {.volume = JOIN_REFUSED_VOLUME}); @@ -1167,7 +1328,3 @@ void PlayerManager::Update() sfx.AdjustPitch(SOUND_STATIC_BUILDUP, 1); } -void PlayerManager::remove_coplayer_slot(int*, Entity_Player*) -{ - reconstruction_missing("PlayerManager::remove_coplayer_slot 0083bc50"); -} diff --git a/src/player_manager.h b/src/player_manager.h index c5b9231..e5c211d 100644 --- a/src/player_manager.h +++ b/src/player_manager.h @@ -125,7 +125,7 @@ public: bool HasTemporaryEffect(ItemConfig_Item* item); float get_total_luck(); bool check_full_health(HealthCheck check); - void add_lost_curse(int nullItemId); + void add_lost_curse(); int GetPlayerSlotFromController(int controllerId); void AssignPlayerColor(int controllerId); @@ -146,7 +146,6 @@ public: static Vector get_player_start_position(Entity_Player* player, Vector position); Vector players_center_position(CenterCache cache); static void unlock_completion_mark(int completionType); - static void remove_coplayer_slot(int* hudSlots, Entity_Player* player); void RestoreGameState(GameState& state); void RestoreGameState_PostLevelInit(GameState& state); diff --git a/src/procedural_item_manager.cpp b/src/procedural_item_manager.cpp index 1f5e035..139dd3b 100644 --- a/src/procedural_item_manager.cpp +++ b/src/procedural_item_manager.cpp @@ -9,8 +9,6 @@ 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; @@ -65,8 +63,8 @@ bool ProceduralItemManager::render_item(int itemId, const SourceQuad& source, co 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); + Vector cell = vector_make((float)(index % PROCEDURAL_CELLS_PER_ROW) * PROCEDURAL_CELL_SIZE, + (float)(index / PROCEDURAL_CELLS_PER_ROW) * PROCEDURAL_CELL_SIZE); SourceQuad atlas = source; for (Vector* corner : {&atlas._topLeft, &atlas._topRight, &atlas._bottomLeft, &atlas._bottomRight}) *corner = vector_add(*corner, cell); diff --git a/src/procedural_item_manager.h b/src/procedural_item_manager.h index be350ed..564465c 100644 --- a/src/procedural_item_manager.h +++ b/src/procedural_item_manager.h @@ -7,6 +7,10 @@ #include #include +// The glitched items' icons on the item surface: 32 pixel cells, 32 to a row, by -1 - id. +constexpr int PROCEDURAL_CELLS_PER_ROW = 32; +constexpr float PROCEDURAL_CELL_SIZE = 32; + // Destruction (009dc750) is the default. // The glitched items TMTRAINER makes (Game's ProceduralItemManager): the items by -1 - id, the render surfaces their // sprites are drawn into, the actives their effects may use, and the (type, variant) spawns some of them trigger on. diff --git a/src/rail_manager.h b/src/rail_manager.h index 7249919..2efc78b 100644 --- a/src/rail_manager.h +++ b/src/rail_manager.h @@ -19,9 +19,11 @@ constexpr uint8_t RAIL_WALL_BOTTOM = 0x91; constexpr uint8_t RAIL_WALL_LEFT = 0xa0; constexpr uint8_t RAIL_WALL_RIGHT = 0x90; -// The rail pieces a minecart can start on. +// The rail pieces a minecart can start on, and the dead ends it leaves from. constexpr uint8_t RAIL_HORIZONTAL = 0; constexpr uint8_t RAIL_VERTICAL = 1; +constexpr uint8_t RAIL_END_LEFT = 7; +constexpr uint8_t RAIL_END_RIGHT = 8; constexpr uint8_t RAIL_END_UP = 9; constexpr uint8_t RAIL_END_DOWN = 10; diff --git a/src/render_passes.cpp b/src/render_passes.cpp index ce2c862..fdff112 100644 --- a/src/render_passes.cpp +++ b/src/render_passes.cpp @@ -1,5 +1,6 @@ #include "render_passes.h" #include "anm2.h" +#include constexpr const char* CLIP_PLANE_UNIFORM = "ClipPlane"; constexpr const char* COLORIZE_UNIFORM = "Colorize"; @@ -25,6 +26,25 @@ void render_color_shader_pass(const KAGE::Graphics::ColorQuad& quad) graphics.shader_pop(); } +// 00a1d710 Draws a line of a thickness from one point to another, shaded from one color to the other, unless both are +// fully transparent. The corner colors averaging fully transparent skips it the same way for real alphas. +void render_color_quad(const Vector& from, const Vector& to, const KColor& fromColor, const KColor& toColor, + float thickness) +{ + Vector along = vector_make(to.x - from.x, to.y - from.y); + float length = std::sqrt(along.x * along.x + along.y * along.y); + if (length > 0) along = vector_make(along.x * (1 / length), along.y * (1 / length)); + + Vector side = vector_make(-along.y * thickness * HALF, along.x * thickness * HALF); + KAGE::Graphics::ColorQuad quad; + quad._topLeft = vector_make(from.x - side.x, from.y - side.y - HALF); + quad._topRight = vector_make(to.x - side.x, to.y - side.y - HALF); + quad._bottomLeft = vector_make(from.x + side.x, from.y + side.y - HALF); + quad._bottomRight = vector_make(to.x + side.x, to.y + side.y - HALF); + quad.colors = {fromColor, toColor, fromColor, toColor}; + render_color_shader_pass(quad); +} + // 00683060 Gives the current shader a sprite's uniforms: its color's colorize and offset when asked, the image's size, // and the shared pixelation and clip plane. void apply_sprite_shader_params(const ColorMod& color, SpriteShaderColor mode, const KAGE::Graphics::ImageBase& image) diff --git a/src/render_passes.h b/src/render_passes.h index bce6d6d..496b526 100644 --- a/src/render_passes.h +++ b/src/render_passes.h @@ -26,4 +26,7 @@ struct SpriteShaderParams extern SpriteShaderParams spriteShaderParams; void render_color_shader_pass(const KAGE::Graphics::ColorQuad& quad); +void render_color_quad(const Vector& from, const Vector& to, const KColor& fromColor, const KColor& toColor, + float thickness); +KColor kcolor_argb(uint32_t argb); void apply_sprite_shader_params(const ColorMod& color, SpriteShaderColor mode, const KAGE::Graphics::ImageBase& image); diff --git a/src/revive_player_menu.cpp b/src/revive_player_menu.cpp index a6435ab..009695f 100644 --- a/src/revive_player_menu.cpp +++ b/src/revive_player_menu.cpp @@ -46,12 +46,6 @@ static Entity_Player* player_by_controller(int controller) return nullptr; } -// Where the HUD of a player sits on screen in a HUD layout. -static Vector player_hud_position(Entity_Player*, PlayerHudLayout) -{ - reconstruction_missing("HUD's player HUD position 009a6320 (FUN_009a6320 in classes.h)"); -} - // 008ef560 Loads the menu sheet on its background and the selector sheet on its upper selector at three quarters size, // hidden with no controller and the first player selected. void RevivePlayerMenu::Init() @@ -161,7 +155,7 @@ void RevivePlayerMenu::Render() Entity_Player* player = game.playerManager.get_main_player(selectedPlayer); PlayerHudLayout layout = game.hud.GetPlayerHUDLayout(selectedPlayer, player); - Vector position = player_hud_position(player, layout); + Vector position = game.hud.get_player_hud_position(player, layout); bool isLowerHalf = position.y >= center.y; position.y += isLowerHalf ? -SELECTOR_ABOVE : layout == HUD_LAYOUT_COMPACT ? SELECTOR_BELOW_COMPACT : SELECTOR_BELOW; selectorSprite.Play(isLowerHalf ? ANIMATION_LOWER_SELECTOR : ANIMATION_UPPER_SELECTOR); diff --git a/src/rich_text.cpp b/src/rich_text.cpp index 1d353ea..a455372 100644 --- a/src/rich_text.cpp +++ b/src/rich_text.cpp @@ -1,9 +1,39 @@ #include "rich_text.h" +#include "console.h" +#include "item_config.h" #include "log.h" +#include "manager.h" +#include "menu_manager.h" +#include "render_passes.h" +#include +#include +#include +#include constexpr std::string_view TEXT_ICONS_PATH = "gfx/ui/text_icons.anm2"; // The animation each icon type is a frame of, empty for the collectible, which is an image of its own. constexpr std::string_view ICON_ANIMATIONS[] = {"players", "pickups", "", "rooms"}; +// The pickup icons a tag names, in the order of their frames. +constexpr std::string_view PICKUP_ICON_NAMES[] = {"coin", "key", "bomb", "redheart", "soulheart", "blackheart"}; +constexpr int TAG_PARTS = 2; +constexpr int TAG_BRACKETS = 2; +constexpr int HEX_BASE = 16; +constexpr float ICON_SHIFT = 2; +constexpr float TAG_ICON_SPACING = 4; +constexpr float COLLECTIBLE_ICON_SCALE = 1.5f; + +// Where the layout is in its markup and the style its next token takes: the pen past the last token, the color, +// scale and kind of token, and the icon's id. +struct RichTextCursor +{ + KColor color{}; + float baseScale = 1; + float nextX = 0; + float scale = 1; + size_t pos = 0; + RichTextSpanType type = SPAN_TEXT; + int param = 0; +}; // 009efb60 Loads the font at path and, the first time, the icon sprite, which it then fits to the font's line height. // The game formatted the path into a buffer of 260 characters first. The whole path is used here. @@ -22,6 +52,235 @@ void RichText::load_font(std::string_view path) icons->maxHeight = font.lineHeight; } +// 0067fdf0 The text between the first < and the next > no backslash escapes (the backslash becomes the >), or the +// rest of the text when nothing closes it, or nothing (logged) when there is no <. +// The original reads before the text for a > right after the <. Here that > closes an empty text. +static std::string angle_bracket_text(std::string_view text) +{ + size_t open = text.find('<'); + std::string inside; + + if (open == std::string_view::npos) + { + std::string message = "ExtractAngleBracketText() Couldn't find opening bracket in string: "; + message += std::string(text) + " \n"; + KAGE_LogMessage(LOG_WARN, (uint8_t*)message.data()); + return inside; + } + for (char character : text.substr(open + 1)) + { + if (character != '>') inside += character; + else if (inside.empty() || inside.back() != '\\') return inside; + else inside.back() = character; + } + return inside; +} + +// A tag's name or value without the spaces and tabs around it, lowercased. +static std::string tag_part_clean(std::string part) +{ + auto isBlank = [](char character) { return character == ' ' || character == '\t'; }; + + while (!part.empty() && isBlank(part.front())) part.erase(part.begin()); + while (!part.empty() && isBlank(part.back())) part.pop_back(); + for (char& character : part) character = (char)std::tolower(character); + return part; +} + +// 009f1380 Reads the name=value tag at the cursor into its style or icon, the icon moving the pen (and shifting the +// span before it, spanX, by 2). Whether it was a tag: anything else between brackets is plain text. +// A tag of an unknown name is skipped as a tag. +static bool tag_parse(std::string_view markup, RichTextCursor& cursor, float& spanX, RichTextIcon& icons) +{ + std::string tag = angle_bracket_text(markup.substr(cursor.pos)); + std::vector parts = text_split(tag, '='); + if (parts.size() != TAG_PARTS) return false; + + std::string name = tag_part_clean(parts[0]); + std::string value = tag_part_clean(parts[1]); + auto iconAdd = [&](RichTextIconType type, int id) + { + cursor.param = id; + if (type != ICON_ROOM) spanX += ICON_SHIFT; + icons.set_icon(type, id); + float width = icons.get_size().x; + cursor.nextX += type == ICON_ROOM ? width : width * cursor.scale + TAG_ICON_SPACING; + cursor.type = (RichTextSpanType)(type + 1); + }; + + if (name == "player") iconAdd(ICON_PLAYER, std::atoi(value.c_str())); + else if (name == "pickup") + { + auto named = std::ranges::find(PICKUP_ICON_NAMES, value); + bool isNamed = named != std::end(PICKUP_ICON_NAMES); + iconAdd(ICON_PICKUP, isNamed ? (int)(named - std::begin(PICKUP_ICON_NAMES)) : std::atoi(value.c_str())); + } + else if (name == "rooms") iconAdd(ICON_ROOM, std::atoi(value.c_str())); + else if (name == "collectible") iconAdd(ICON_COLLECTIBLE, std::atoi(value.c_str())); + else if (name == "size") cursor.scale = value == "default" ? cursor.baseScale : (float)std::atof(value.c_str()); + else if (name == "color") + { + float alpha = cursor.color._alpha; + cursor.color = kcolor_argb((uint32_t)std::strtoul(value.c_str(), nullptr, HEX_BASE)); + cursor.color._alpha *= alpha; + } + cursor.pos += tag.size() + TAG_BRACKETS; + return true; +} + +// 009ef9a0 Takes another span's text when both have the same style. Whether it did. +bool RichTextSpan::try_merge(const RichTextSpan& other) +{ + bool isSameColor = color._red == other.color._red && color._green == other.color._green && + color._blue == other.color._blue && color._alpha == other.color._alpha; + if (scale != other.scale || !isSameColor || type != other.type || param != other.param) return false; + + text += other.text; + return true; +} + +// Merges each run of spans of one style into its first span. +static void spans_merge(std::vector& spans) +{ + for (size_t i = 0; i + 1 < spans.size();) + { + if (spans[i].try_merge(spans[i + 1])) spans.erase(spans.begin() + (std::ptrdiff_t)i + 1); + else i++; + } +} + +// 009f0290 Lays markup out into lines of styled spans, wrapping before the word (the text since the last space or +// icon) that would pass maxWidth, -1 for none. Icons fit their height to the font's line. +// A line's width counts the word it wrapped before. A span of the same style as the one before merges into it, two +// identical icons in a row included. +std::vector RichText::layout(std::string_view markup, KColor color, int maxWidth, float scale) +{ + std::vector lines(1); + std::vector word; + RichTextCursor cursor = {.color = color, .baseScale = scale, .scale = scale}; + float limit = (float)(uint32_t)maxWidth; + float cursorX = 0; + float lineWidth = 0; + float lineY = 0; + float wordWidth = 0; + + auto isUsed = [](const RichTextSpan& span) { return span.type != SPAN_TEXT || !span.text.empty(); }; + auto styleApply = [&](RichTextSpan& span) + { + span.color = cursor.color; + span.scale = cursor.scale; + span.type = cursor.type; + span.param = cursor.param; + }; + auto spanStart = [&](float x) + { + RichTextSpan& span = word.emplace_back(); + span.position = vector_make(x, lineY); + styleApply(span); + }; + auto wordCommit = [&]() + { + wordWidth = 0; + lines.back().spans.insert(lines.back().spans.end(), word.begin(), word.end()); + word.clear(); + spanStart(cursorX); + }; + + word.emplace_back().color = color; + word.back().scale = scale; + while (cursor.pos < markup.size() && markup[cursor.pos]) + { + float previousX = cursorX; + bool isTag = markup[cursor.pos] == '<' && tag_parse(markup, cursor, word.back().position.x, *icons); + if (!isTag) + { + char character = markup[cursor.pos++]; + word.back().text += character; + cursor.nextX = (float)font.GetCharacterWidth((uint32_t)(int)(int8_t)character) * cursor.scale + cursorX; + } + + float advance = cursor.nextX - previousX; + cursorX = cursor.nextX; + if (lineWidth + advance <= limit) + { + lineWidth += advance; + wordWidth += advance; + } + else + { + float startX = word.front().position.x; + lineY += (float)font.lineHeight * lineSpacing * scale; + for (RichTextSpan& span : word) span.position = vector_make(span.position.x - startX, lineY); + lines.back().width = (uint32_t)lineWidth; + spans_merge(lines.back().spans); + lineWidth = cursorX = cursor.nextX = wordWidth; + lines.emplace_back(); + if (cursor.type != SPAN_TEXT) + { + if (isUsed(word.back())) spanStart(wordWidth); + styleApply(word.back()); + lineWidth = cursorX = cursor.nextX = advance + wordWidth; + } + } + + RichTextSpan& span = word.back(); + bool isSameColor = cursor.color._red == span.color._red && cursor.color._green == span.color._green && + cursor.color._blue == span.color._blue && cursor.color._alpha == span.color._alpha; + if (!isSameColor || cursor.scale != span.scale || cursor.type != span.type || cursor.param != span.param) + { + if (isUsed(span)) spanStart(cursorX); + styleApply(word.back()); + word.back().position.x = previousX; + } + if (cursor.type != SPAN_TEXT) + { + cursor.type = SPAN_TEXT; + wordCommit(); + } + if (!word.back().text.empty() && word.back().text.back() == ' ') wordCommit(); + } + + lines.back().spans.insert(lines.back().spans.end(), word.begin(), word.end()); + spans_merge(lines.back().spans); + lines.back().width = (uint32_t)std::ceil(lineWidth); + return lines; +} + +// 009efdb0 Draws text with its icons at a position, returning its size: its widest line by its lines' height. +Vector RichText::Render(std::string_view text, Vector position, KColor color, float scale, int maxWidth) +{ + std::vector lines = layout(text, color, maxWidth, scale); + Vector size = vector_make(0, (float)(lines.size() * font.lineHeight) * lineSpacing * scale); + + for (RichTextLine& line : lines) + { + for (RichTextSpan& span : line.spans) + { + Vector at = vector_make(span.position.x + position.x, position.y + span.position.y); + if (span.type == SPAN_TEXT) + { + FontSettings settings; + font.DrawString(span.text, at, vector_make(span.scale, span.scale), span.color, settings); + continue; + } + icons->maxHeight = (float)font.lineHeight * span.scale; + icons->render(at, (RichTextIconType)(span.type - 1), span.param, span.color._alpha); + } + size.x = std::max(size.x, (float)line.width); + } + return size; +} + +// 009f0140 The size text would draw at: its widest line by its lines' height. +Vector RichText::measure(std::string_view text, int maxWidth, float scale) +{ + std::vector lines = layout(text, WHITE, maxWidth, scale); + Vector size = vector_make(0, (float)(lines.size() * font.lineHeight) * lineSpacing * scale); + + for (RichTextLine& line : lines) size.x = std::max(size.x, (float)line.width); + return size; +} + // 009f2b10 The text_icons.anm2 animation an icon type is drawn from, or nothing, logged, for the collectible and // unknown types. std::string_view RichTextIcon::get_animation_name(RichTextIconType type) @@ -32,3 +291,85 @@ std::string_view RichTextIcon::get_animation_name(RichTextIconType type) KAGE_LogMessage(LOG_ERROR, (uint8_t*)message.data()); return {}; } + +// 009f2c10 Shows an icon: a collectible's image, loaded once per id, or the frame of its type's animation, logged and +// left as it was when the animation has no such frame. +void RichTextIcon::set_icon(RichTextIconType type, int id) +{ + if (type == ICON_COLLECTIBLE) + { + iconType = type; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(id); + if (item && !images[id]) images[id] = Manager::LoadImage(item->gfxFilename); + iconId = id; + return; + } + + Play(get_animation_name(type)); + iconType = type; + int length = animState.animData ? animState.animData->length : 0; + if (id < 0 || id > length) + { + log_printf(LOG_ERROR, "Invalid icon id (%d) for Icon Type %d \n", id, type); + return; + } + if (animState.animData) animState.SetFrameFloat((float)id); + iconId = id; +} + +// 009f28b0 The icon's size, shrunk to fit maxHeight: a collectible's image (then made half as big again) or the frame +// of the layer named after its animation. Nothing for no image or layer. +Vector RichTextIcon::get_size() +{ + if (iconType == ICON_COLLECTIBLE) + { + KAGE::Graphics::ImagePtr& image = images[iconId]; + if (!image) return {}; + + Vector size = vector_make((float)image->width, (float)image->height); + if (maxHeight <= 0 || size.y <= maxHeight) return size; + float fit = maxHeight / size.y * COLLECTIBLE_ICON_SCALE; + return vector_make(size.x * fit, size.y * fit); + } + + LayerState* layer = GetLayer(animState.animData ? std::string_view(animState.animData->name) : std::string_view()); + int layerId = layer && layer->layerData ? layer->layerData->id : -1; + const AnimationFrame* frame = layer ? animState.GetLayerFrame(layerId) : nullptr; + if (!frame) return {}; + + Vector size = vector_make(frame->width, frame->height); + if (maxHeight <= 0 || size.y <= maxHeight) return size; + float fit = maxHeight / size.y; + return vector_make(size.x * fit, size.y * fit); +} + +// 009f24b0 Draws an icon faded to alpha at a position: a collectible's image shrunk as get_size does, or the frame of +// its layer, scaled down to maxHeight (a scale that then stays until a taller frame changes it). +// The original reads a missing layer frame's height. Here it scales nothing. +void RichTextIcon::render(Vector position, RichTextIconType type, int id, float alpha) +{ + KColor tint = kcolor_rgba(1, 1, 1, alpha); + + set_icon(type, id); + if (type == ICON_COLLECTIBLE) + { + KAGE::Graphics::ImagePtr image = images[id]; + if (!image) return; + + float height = (float)image->height; + apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, *image); + if (maxHeight <= 0 || height <= maxHeight) return (void)image->Render(position, tint); + float fit = maxHeight / height * COLLECTIBLE_ICON_SCALE; + Vector size = vector_make((float)image->width * fit, height * fit); + image->Render(KAGE::Graphics::color_quad_rect(position, size, WHITE), tint); + return; + } + + LayerState* layer = GetLayer(get_animation_name(type)); + if (!layer) return; + const AnimationFrame* frame = animState.GetLayerFrame(layer->layerData ? layer->layerData->id : -1); + float height = frame ? frame->height : 0; + if (maxHeight > 0 && maxHeight < height) scale = vector_make(maxHeight / height, maxHeight / height); + color = {{1, 1, 1, alpha}, {0, 0, 0, 0}, {0, 0, 0}}; + Render({position}); +} diff --git a/src/rich_text.h b/src/rich_text.h index c86e808..1776b76 100644 --- a/src/rich_text.h +++ b/src/rich_text.h @@ -2,10 +2,16 @@ #include "anm2.h" #include "font.h" +#include "fx_layers.h" +#include "kage_graphics.h" +#include #include #include #include #include +#include + +constexpr int RICH_TEXT_NO_WRAP = -1; // What a rich text icon shows, each but the collectible an animation of gfx/ui/text_icons.anm2. enum RichTextIconType : int @@ -16,21 +22,55 @@ enum RichTextIconType : int ICON_ROOM }; +// What a run of rich text draws: text, or an icon of the type one less than its number. +enum RichTextSpanType : int +{ + SPAN_TEXT, + SPAN_PLAYER, + SPAN_PICKUP, + SPAN_COLLECTIBLE, + SPAN_ROOM +}; + // The icons rich text draws inline from gfx/ui/text_icons.anm2: the sprite, the height icons are fit to, the icon last // set and the collectible images loaded for it so far. -// Its drawing (render, get_size, set_icon) waits on the ANM2 and graphics rework and is not reconstructed yet. struct RichTextIcon : ANM2 { - std::map images; + std::map images; float maxHeight = 0; int iconId = 0; RichTextIconType iconType = ICON_PLAYER; static std::string_view get_animation_name(RichTextIconType type); + void set_icon(RichTextIconType type, int id); + Vector get_size(); + void render(Vector position, RichTextIconType type, int id, float alpha); +}; + +// A run of rich text in one style, at its place in its line: its text or icon (and the icon's id), color and scale. +// Construction, moves and copies (009f1ef0, 009f20f0, 004215a0) are the defaults. +struct RichTextSpan +{ + std::string text; + KColor color = WHITE; + Vector position{}; + float scale = 1; + RichTextSpanType type = SPAN_TEXT; + int param = 0; + + bool try_merge(const RichTextSpan& other); +}; + +// A laid out line of rich text and its width. +struct RichTextLine +{ + std::vector spans; + uint32_t width = 0; }; // Text drawn in a font with icons inline (hearts, pickups, collectibles, rooms), its lines spaced by lineSpacing. -// Its layout and drawing (rich_text_layout, rich_text_render) are not reconstructed yet. +// Markup tags are , , , , +// and . // Destruction (009efa10) is the default: the font unloads and the icons go with their pointer. struct RichText { @@ -40,4 +80,7 @@ struct RichText float lineSpacing = 1; void load_font(std::string_view path); + std::vector layout(std::string_view markup, KColor color, int maxWidth, float scale); + Vector Render(std::string_view text, Vector position, KColor color, float scale, int maxWidth = RICH_TEXT_NO_WRAP); + Vector measure(std::string_view text, int maxWidth, float scale); }; diff --git a/src/room.cpp b/src/room.cpp index 44f9fa0..2810e6b 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -1,4 +1,5 @@ #include "room.h" +#include "boss_ai.h" #include "boss_pool.h" #include "entity_pickup.h" #include "entity_player.h" @@ -9,6 +10,8 @@ #include "game.h" #include "grid_entity.h" #include "grid_entity_door.h" +#include "grid_entity_poop.h" +#include "grid_entity_spikes.h" #include "grid_entity_stairs.h" #include "level.h" #include "log.h" @@ -62,9 +65,21 @@ constexpr uint32_t GREED_PROP_MIN = 3; constexpr int GREED_PROP_VARIANT = 10; constexpr int DOOR_ROWS[2] = {4, 11}; +// Sanguine Bond's spikes stand on this cell, left of a devil room's center. +constexpr int SANGUINE_COLUMN = 7; +constexpr int SANGUINE_ROW = 4; +// The Card Against Humanity: the cells a narrow room's floor spans, the odds of a special poop, and how luck tilts +// Midas' Touch's gold. +constexpr int NARROW_ROW_FIRST = 3; +constexpr int NARROW_ROW_LAST = 5; +constexpr int NARROW_COLUMN_FIRST = 5; +constexpr int NARROW_COLUMN_LAST = 9; +constexpr uint32_t CAH_POOP_CHANCE = 33; +constexpr int CAH_GOLD_CHANCE = 11; +constexpr float CAH_GOLD_LUCK = 5; +constexpr float RANDOM_PLAYER_ANYWHERE = 9999999; constexpr int DOOR_COLUMNS[2] = {7, 20}; constexpr int NARROW_ROW_INSET = 3; -constexpr int NARROW_COLUMN_INSET = 4; struct DoorCell { @@ -122,7 +137,6 @@ constexpr int GRID_PATH_PIT_LAST = 3999; constexpr uint32_t GRID_COLLISION_NONE = 0; constexpr uint32_t GRID_COLLISION_PIT = 1; constexpr uint32_t GRID_COLLISION_SOLID = 3; -constexpr uint32_t GRID_COLLISION_WALL = 4; constexpr int BOSS_ROTGUT = 87; @@ -141,7 +155,6 @@ constexpr int BOSS_RAINMAKER = 77; constexpr int STAGE_ID_LAST_CHAPTER = 12; constexpr int STAGE_ID_FIRST_ALT = 27; constexpr int VOID_BACKDROPS = 17; -constexpr uint32_t DELETE_THIS_STAGES = 11; constexpr uint32_t DELETE_THIS_STAGE_TYPES = 5; // The Beast's arena's bounds, wider than its grid. @@ -185,11 +198,8 @@ constexpr uint64_t GAME_STATE_DEVILROOM_SPAWNED_BITS = 1ull << 5; // The dust a door throws as it appears: how many puffs at least, how fast and far, how they spin and how long they // last. -constexpr int DUST_MIN = 5; -constexpr float DUST_SPEED = 5; -constexpr float DUST_RADIUS = 20; +constexpr int DOOR_DUST_MIN = 5; constexpr float DUST_SPIN_RANGE = 10; -constexpr float DUST_SPIN_MIN = 2; constexpr uint32_t DUST_TIMEOUT_RANGE = 10; constexpr int DUST_TIMEOUT_MIN = 30; @@ -254,10 +264,10 @@ constexpr int CARD_READING_PORTAL_SPREAD = 2; constexpr uint64_t GAME_STATE_SURPRISE_MINIBOSS_SEEN = 1ull << 29; // Init's ambient decoration: how many spawn at most, and how the second door chance raises them. -constexpr int AMBIENT_FLIES = 15; -constexpr int AMBIENT_DUST = 10; -constexpr int AMBIENT_DROPLETS = 10; -constexpr int AMBIENT_RAIN = 50; +constexpr int AMBIENT_FLIES_MAX = 15; +constexpr int AMBIENT_DUST_MAX = 10; +constexpr int AMBIENT_DROPLETS_MAX = 10; +constexpr int AMBIENT_RAIN_MAX = 50; constexpr int AMBIENT_RETRIES = 10; constexpr int EMBER_COUNT = 10; constexpr float EMBER_HEIGHT = 100; @@ -297,14 +307,14 @@ static bool is_backwards_path() static bool is_challenge_or_daily() { - return g_game->challenge != 0 || g_game->dailyChallenge._id != 0; + return g_game->challenge != 0 || g_game->dailyChallenge.id != 0; } // An achievement unlocked, or every one in a debug or daily run being played. static bool is_unlocked(int achievement) { if (g_manager->persistentGameData.achievements[achievement]) return true; - return g_manager->state == MANAGER_STATE_GAME && (g_game->dailyChallenge._id != 0 || g_game->isDebug); + return g_manager->state == MANAGER_STATE_GAME && (g_game->dailyChallenge.id != 0 || g_game->isDebug); } static bool is_curse_active(uint32_t curse) @@ -362,7 +372,7 @@ static void room_reset(Room& room) room.renderScrollOffset = vector_make(0, 0); room.roomType = ROOM_NULL; room.greedWaveTimer = -1; - room.unknown72fc = -1; + room.shovelQuestTimer = -1; room.wallColor = COLOR_DEFAULT; room.floorColor = COLOR_DEFAULT; } @@ -419,7 +429,7 @@ void Room::Init(RoomConfig_Room& config, RoomDescriptor& roomDescriptor) unknown73f0 = 0; genesisTimer = 0; lavaIntensity = 1; - isUnknown7769 = false; + isItemDuplicatePending = false; isPickupVisionInvalid = false; isUnknown11f6 = true; isFirstEnemyDead = false; @@ -431,7 +441,7 @@ void Room::Init(RoomConfig_Room& config, RoomDescriptor& roomDescriptor) bloodFromWallsCount = 0; unknown70fc = 0; slowdownDuration = 0; - unknown7230 = 0; + bombRainTimer = 0; unknown721c = 0; enterFrame = g_game->frameCount; pendingGridRemovals.clear(); @@ -458,7 +468,7 @@ void Room::Init(RoomConfig_Room& config, RoomDescriptor& roomDescriptor) if (roomType == ROOM_BOSS) boss_ids_init(); isSurpriseMiniboss = descriptor->flags & ROOM_DESCRIPTOR_FLAG_SURPRISE_MINIBOSS; - if (g_game->dailyChallenge._specialDailyId == SPECIAL_DAILY_SURPRISE_MINIBOSS && isSurpriseMiniboss) + if (g_game->dailyChallenge.specialDailyId == SPECIAL_DAILY_SURPRISE_MINIBOSS && isSurpriseMiniboss) g_game->gameStateFlags |= GAME_STATE_SURPRISE_MINIBOSS_SEEN; isTriggerPressurePlates = false; update_bounds(true); @@ -492,7 +502,11 @@ void Room::Init(RoomConfig_Room& config, RoomDescriptor& roomDescriptor) TrySpawnMegaSatanRoomDoor(false); TrySpawnSpecialQuestDoor(); if (g_game->challenge == CHALLENGE_BACKASSWARDS && g_game->currentRoomIdx == ROOM_MEGA_SATAN_IDX) - reconstruction_missing("Room::Init 007f2800: Backasswards' door from Mega Satan back to the start (GridEntity_Door)"); + { + MakeDoor(DOOR_DOWN0); + doors[DOOR_DOWN0]->targetRoomIdx = g_game->startingRoomIdx; + doors[DOOR_DOWN0]->SetRoomTypes(descriptor->data->type, ROOM_DEFAULT); + } make_walls(); init_dungeon_rock(); init_decorations(config); @@ -681,7 +695,7 @@ void Room::init_shop_level() } std::array& achievements = g_manager->persistentGameData.achievements; - bool isAllUnlocked = g_manager->state == MANAGER_STATE_GAME && (g_game->dailyChallenge._id != 0 || g_game->isDebug); + bool isAllUnlocked = g_manager->state == MANAGER_STATE_GAME && (g_game->dailyChallenge.id != 0 || g_game->isDebug); shopLevel = 1; if (achievements[ACHIEVEMENT_STORE_UPGRADE_4] || isAllUnlocked) shopLevel = 5; @@ -893,7 +907,7 @@ void Room::init_treasure_blind(RoomConfig_Room& config) bool isOptionsRoom = (config.subtype == 1 || config.subtype == 3) && isMoreOptions; bool isGlasses = players.AnyoneHasTrinket(TRINKET_BROKEN_GLASSES) && g_game->stage != STAGE_BLUE_WOMB && !isOptionsRoom; - if ((isAltStage || isGlasses) && !is_backwards_path() && items.size() > 1 && g_game->dailyChallenge._id == 0) + if ((isAltStage || isGlasses) && !is_backwards_path() && items.size() > 1 && g_game->dailyChallenge.id == 0) { bool isSpared = false; if (isAltStage && players.AnyoneHasTrinket(TRINKET_BROKEN_GLASSES)) @@ -1236,13 +1250,13 @@ void Room::init_ambient_effects(int effectiveStage, int stageId, uint32_t stageT players.FirstCollectibleOwner(COLLECTIBLE_INFESTATION_2, LAZARUS_SHARE_CHECK) || roomType == ROOM_SUPERSECRET || isMineshaft; int extra = isMore ? 1 : 0; - uint32_t flyMax = (extra + 1) * AMBIENT_FLIES; + uint32_t flyMax = (extra + 1) * AMBIENT_FLIES_MAX; int shift = descriptor->gridIndex == g_game->startingRoomIdx ? 1 : 0; int flies = ambient_count(rng, flyMax, shift); - int dust = ambient_count(rng, (extra + 1) * AMBIENT_DUST, shift); - int droplets = ambient_count(rng, (extra + 1) * AMBIENT_DROPLETS, 0); - rng.RandomInt(rng.RandomInt((extra + 2) * AMBIENT_DROPLETS) + 1); + int dust = ambient_count(rng, (extra + 1) * AMBIENT_DUST_MAX, shift); + int droplets = ambient_count(rng, (extra + 1) * AMBIENT_DROPLETS_MAX, 0); + rng.RandomInt(rng.RandomInt((extra + 2) * AMBIENT_DROPLETS_MAX) + 1); droplets >>= shift; if (backdrop.configs[backdropType].walls == 0) droplets = 0; if (effectiveStage == STAGE_BLUE_WOMB) dust = std::max(dust, 5); @@ -1293,7 +1307,7 @@ void Room::init_ambient_effects(int effectiveStage, int stageId, uint32_t stageT if (!isRain) isRain = descriptor->data->type == ROOM_SECRET || is_curse_active(CURSE_OF_DARKNESS); if (isRain && !(descriptor->flags & ROOM_DESCRIPTOR_FLAG_PITCH_BLACK)) { - int drops = ambient_count(rng, extra * 20 + AMBIENT_RAIN, shift); + int drops = ambient_count(rng, extra * 20 + AMBIENT_RAIN_MAX, shift); for (int i = 0; i < drops; i++) ambient_spawn(*this, EFFECT_WISP, 0); } @@ -1669,7 +1683,7 @@ bool Room::IsPositionInRoom(Vector position, float margin) uint32_t Room::GetGridCollision(int gridIndex) { if (IsBeastDungeon()) return GRID_COLLISION_NONE; - if (gridIndex < 0) return GRID_COLLISION_WALL; + if (gridIndex < 0) return COLLISION_WALL; if (gridEntities[gridIndex]) return (uint32_t)gridEntities[gridIndex]->collisionClass; int path = gridPaths[gridIndex]; @@ -1822,6 +1836,13 @@ bool Room::IsBeastDungeon() return data && data->type == ROOM_DUNGEON && data->stageId == STAGE_ID_HOME; } +// 008279c0 The height of the Beast's lava, 30 above the floor's bottom edge. +float Room::get_lava_line_y() +{ + constexpr float LAVA_LINE_ABOVE = 30; + return bottomRightPos.y - LAVA_LINE_ABOVE; +} + // 00827b70 Whether the players are in the mirror world: the second floor of the alternate path's second dimension, // or the first floor's under the Curse of the Labyrinth. bool Room::IsMirrorWorld() @@ -2022,7 +2043,7 @@ static int room_music_get(Room& room, uint32_t stage, uint32_t stageType, int st // 007eb1b0 Plays the room's track, crossfading from the last one (slowly between Downpour and its reversed track, // at once out of the Beast's), and a treasure room's jingle. Floors and dimensions override -// it: the Blue Womb's own music, the Mausoleum heart's, the death certificate's, the mirror world, the mineshaft and +// it: DELETE THIS's random stage from the floor's seed, the Blue Womb's own music, the Mausoleum heart's, the death certificate's, the mirror world, the mineshaft and // the Ascent. While the game's start jingle plays, the track only queues. void Room::PlayMusic() { @@ -2031,7 +2052,12 @@ void Room::PlayMusic() if (g_game->challenge == CHALLENGE_RED_REDEMPTION) stageType = (uint32_t)g_game->GetRoomStageType(g_game->currentRoomIdx); if (g_game->challenge == CHALLENGE_DELETE_THIS) - reconstruction_missing("Room::PlayMusic 007eb1b0: DELETE THIS's random stage music"); + { + RNG rng = {(uint32_t)g_game->dungeonPlacementSeed, 2, 7, 9}; + if (stage - 1 < DELETE_THIS_STAGES) stage = rng.Next() % DELETE_THIS_STAGES + 1; + stageType = rng.Next() % DELETE_THIS_STAGE_TYPES; + if (stageType == STAGETYPE_GREEDMODE) stageType = STAGETYPE_REPENTANCE; + } int jingle = 0; float crossfade = MUSIC_CROSSFADE; @@ -2170,7 +2196,7 @@ float Room::GetDevilRoomChance() if (game.isDevilRoomDisabled) chance = 0; if (is_owned(COLLECTIBLE_GOAT_HEAD) || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_GOAT_HEAD)) chance = DEAL_CHANCE_GOAT_HEAD; - if (game.dailyChallenge._specialDailyId == SPECIAL_DAILY_SURPRISE_MINIBOSS && + if (game.dailyChallenge.specialDailyId == SPECIAL_DAILY_SURPRISE_MINIBOSS && !(game.gameStateFlags & GAME_STATE_SURPRISE_MINIBOSS_SEEN)) chance = 1; if (is_owned(COLLECTIBLE_EUCHARIST)) chance = 1; @@ -2930,7 +2956,7 @@ static void door_dust_spawn(Room& room, GridEntity_Door& door, const DoorDust& d out.x * std::sin(QUARTER_TURN) + out.y * std::cos(QUARTER_TURN)); Vector doorPosition = room.GetGridPosition(door.gridIndex); bool isDeal = dust.style == DUST_DEAL; - int count = (int)(Random() & 3) + DUST_MIN; + int count = (int)(Random() & 3) + DOOR_DUST_MIN; for (int i = 0; i < count; i++) { @@ -3394,10 +3420,60 @@ void Room::UpdateRedKey() } } -// 00827bf0 Spawns Sanguine Bond's spikes. -bool Room::spawn_sanguine_bond_spikes(bool) +// 00827bf0 Sanguine Bond's spikes in a devil room, on the fixed cell left of center: refused where its spikes stand, +// a pit there is filled (its neighbours set up again first), other spikes there go. Outside the room's setup every other +// spike sinks and a poof marks the new ones. They spawn only on an open cell. A room too small for the cell gets none. +bool Room::spawn_sanguine_bond_spikes(bool isRoomInit) { - reconstruction_missing("Room::spawn_sanguine_bond_spikes 00827bf0"); + if (roomType != ROOM_DEVIL || !g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SANGUINE_BOND, LAZARUS_SHARE_CHECK)) + return false; + + bool isFitting = gridWidth >= SANGUINE_COLUMN + 1 && gridHeight >= SANGUINE_ROW + 1; + int spikeIndex = isFitting ? gridWidth * SANGUINE_ROW + SANGUINE_COLUMN : -1; + GridEntity* existing = isFitting && spikeIndex < ROOM_GRID_CELLS ? gridEntities[spikeIndex] : nullptr; + if (existing && existing->type == GRID_SPIKES && existing->variant == SPIKES_LAYOUT_VARIANTS) return false; + if (existing && existing->type == GRID_PIT) + { + for (int dx = -1; dx <= 1; dx++) + for (int y = SANGUINE_ROW - 1; y <= SANGUINE_ROW + 1; y++) + { + int neighbor = GetGridIndexByTile(SANGUINE_COLUMN + dx, y); + if (neighbor >= 0 && gridEntities[neighbor] && gridEntities[neighbor]->type == GRID_PIT) + gridEntities[neighbor]->PostInit(); + } + delete gridEntities[spikeIndex]; + gridEntities[spikeIndex] = nullptr; + } + else if (existing && (existing->type == GRID_SPIKES || existing->type == GRID_SPIKES_ONOFF)) + { + gridPaths[spikeIndex] = GRID_PATH_FREED; + gridEntities[spikeIndex] = nullptr; + delete existing; + } + + if (!isRoomInit) + for (int i = 0; i < gridWidth * gridHeight; i++) + { + GridEntity* grid = gridEntities[i]; + if (i != spikeIndex && grid && (grid->type == GRID_SPIKES || grid->type == GRID_SPIKES_ONOFF)) + static_cast(grid)->unsummon(false); + } + RNG rng = {descriptor->decorationSeed, 11, 7, 12}; + uint32_t seed = rng.Next(); + if (spikeIndex < 0) log_printf(LOG_ASSERT, "SpawnGridEntity: Grid index invalid\n"); + if (spikeIndex >= 0 && gridPaths[spikeIndex] <= GRID_PATH_FREED) + { + GridEntity* spikes = CreateGridEntity(GRID_SPIKES, spikeIndex); + delete gridEntities[spikeIndex]; + gridEntities[spikeIndex] = spikes; + spikes->variant = SPIKES_LAYOUT_VARIANTS; + spikes->varData = 0; + spikes->Init(seed); + } + // The original poofs on a room too small for the cell at the grid's position of -1. Here it does not. + if (!isRoomInit && spikeIndex >= 0) + entity_spawn(ENTITY_EFFECT, EFFECT_POOF01, GetGridPosition(spikeIndex), 0, Random())->Update(); + return true; } // 008167e0 Removes the door in a slot and walls its cell up. @@ -3420,8 +3496,112 @@ void Room::RemoveDoor(int slot) wall->Init(Random()); } -// 007fe220 Fills the room with the Card Against Humanity's poop. +// Whether a cell lies on a shape's floor, as the Card Against Humanity reads the narrow and L shapes. +static bool is_shape_floor_cell(int shape, int x, int y, int width, int height) +{ + switch (shape) + { + case ROOMSHAPE_LTL: + return x >= width / 2 || y >= height / 2; + case ROOMSHAPE_LTR: + return x <= width / 2 || y >= height / 2; + case ROOMSHAPE_LBL: + return x >= width / 2 || y <= height / 2; + case ROOMSHAPE_LBR: + return x <= width / 2 || y <= height / 2; + case ROOMSHAPE_IH: + case ROOMSHAPE_IIH: + return y >= NARROW_ROW_FIRST && y <= NARROW_ROW_LAST; + case ROOMSHAPE_IV: + case ROOMSHAPE_IIV: + return x >= NARROW_COLUMN_FIRST && x <= NARROW_COLUMN_LAST; + default: + return true; + } +} + +// 007fe220 The Card Against Humanity fills the room with poop a few at a time: one time in eight a fly buzzes from a +// player, then each step one time in four ends the frame's run, else a random free floor cell gets a poop (white for +// Hallowed Ground a third of the time, black for Meconium, golden for Midas' Touch by luck). The free cells are the +// floor cells without an obstacle or an enemy, player, slot, pickup or bomb, and the fill goes on while any are left. void Room::card_against_humanity_fill() { - reconstruction_missing("Room::card_against_humanity_fill 007fe220"); + Game& game = *g_game; + std::set occupied; + + isCardAgainstHumanity = false; + for (Entity* entity : entityList.updateEL) + { + bool isNpc = is_npc_type(entity->type); + bool isBlocking = entity->type == ENTITY_PLAYER || entity->type == ENTITY_SLOT || + entity->type == ENTITY_PICKUP || entity->type == ENTITY_BOMB; + if (isNpc || isBlocking) occupied.insert(game.room->GetGridIndex(entity->pos)); + } + + RNG& rng = game.GetPlayer(0)->GetCardRNG(CARD_HUMANITY); + if ((rng.Next() & 7) == 0) + { + uint32_t seed = Random(); + Vector position = game_random_player(game, {}, RANDOM_PLAYER_ANYWHERE)->pos; + entity_spawn(ENTITY_EFFECT, EFFECT_TINY_FLY, position, 0, seed)->Update(); + } + + std::vector freeCells; + freeCells.reserve(gridWidth * gridHeight / 2); + int shape = descriptor->data->shape; + for (int x = 1; x < gridWidth; x++) + for (int y = 1; y < gridHeight; y++) + { + if (!is_shape_floor_cell(shape, x, y, gridWidth, gridHeight)) continue; + int gridIndex = game.room->GetGridIndexByTile(x, y); + GridEntity* grid = gridIndex >= 0 ? game.room->gridEntities[gridIndex] : nullptr; + if ((grid && grid->type != GRID_DECORATION) || occupied.contains(gridIndex)) continue; + + freeCells.push_back(gridIndex); + isCardAgainstHumanity = true; + } + + ItemConfig_Item* meconium = g_manager->itemConfig.GetTrinket(TRINKET_MECONIUM); + bool isMeconiumShared = meconium && meconium->HasTags(TAG_LAZ_SHARED_GLOBAL); + while (!freeCells.empty() && (rng.Next() & 3) != 0) + { + uint32_t whiteRoll = rng.Next(); + uint32_t blackRoll = rng.Next(); + uint32_t goldRoll = rng.Next(); + int variant = POOP_NORMAL; + bool isHallowed = game.playerManager.FirstCollectibleOwner(COLLECTIBLE_HALLOWED_GROUND, LAZARUS_SHARE_CHECK) || + game.playerManager.HasTemporaryEffect(g_manager->itemConfig.GetCollectible(COLLECTIBLE_HALLOWED_GROUND)); + if (isHallowed && whiteRoll % 100 < CAH_POOP_CHANCE) variant = POOP_WHITE; + for (Entity_Player* player : game.playerManager.playerList) + { + if (player->variant != PLAYER_VARIANT_PLAYER) continue; + bool isHolder = player->HasTrinket(TRINKET_MECONIUM) || + (isMeconiumShared && player->backupPlayer && player->backupPlayer->HasTrinket(TRINKET_MECONIUM)); + if (!isHolder) continue; + if (blackRoll % 100 < CAH_POOP_CHANCE) variant = POOP_BLACK; + break; + } + if (game.playerManager.FirstCollectibleOwner(COLLECTIBLE_MIDAS_TOUCH, LAZARUS_SHARE_CHECK)) + { + float luck = 0; + for (Entity_Player* player : game.playerManager.playerList) + if (player->variant == PLAYER_VARIANT_PLAYER && !player->isCoopGhost) luck += player->luck; + if ((int)(luck * -(double)CAH_GOLD_LUCK) + (int)(goldRoll % 100) < CAH_GOLD_CHANCE) variant = POOP_GOLDEN; + } + + size_t pick = rng.RandomInt((uint32_t)freeCells.size()); + int gridIndex = freeCells[pick]; + freeCells.erase(freeCells.begin() + (long)pick); + uint32_t seed = rng.Next(); + if (gridIndex < 0) log_printf(LOG_ASSERT, "SpawnGridEntity: Grid index invalid\n"); + Room& room = *game.room; + if (gridIndex < 0 || room.gridPaths[gridIndex] > GRID_PATH_FREED) continue; + + GridEntity* poop = CreateGridEntity(GRID_POOP, gridIndex); + delete room.gridEntities[gridIndex]; + room.gridEntities[gridIndex] = poop; + poop->variant = variant; + poop->varData = 0; + poop->Init(seed); + } } diff --git a/src/room.h b/src/room.h index 05a8e5b..654e704 100644 --- a/src/room.h +++ b/src/room.h @@ -20,6 +20,9 @@ constexpr float GRID_CELL_SIZE = 40; constexpr float GRID_ORIGIN_X = 40; constexpr float GRID_ORIGIN_Y = 120; +// The wall's thickness in cells, and how far a narrow room's walls sit in from the sides. +constexpr int WALL_CELLS = 2; +constexpr int NARROW_COLUMN_INSET = 4; // An enemy killed in the room, as a Cultist raises it again: its kind, where it fell (moved off a blocked cell), its // champion color and side. @@ -37,6 +40,10 @@ void room_killed_npc_record(Room& room, Entity& npc); // The trigger output groups a room's pressure plates fire (Room::TriggerOutput). constexpr int OUTPUT_GROUP_COUNT = 10; +// The stages DELETE THIS draws its backdrops and decorations from. +constexpr uint32_t DELETE_THIS_STAGES = 11; +// A function an output group calls when it fires. The game itself registers none. +using OutputCallback = void (*)(); // The room descriptor flags room_descriptor.h does not name yet (Lua's RoomDescriptor.FLAG_*). constexpr uint32_t ROOM_DESCRIPTOR_FLAG_ALT_BOSS_MUSIC = 1 << 6; @@ -85,6 +92,8 @@ enum RoomType : int // The rooms a teleport portal leads to by its subtype (Card Reading's portals): treasure, boss, secret and shop. constexpr std::array PORTAL_ROOM_TYPES = {ROOM_TREASURE, ROOM_BOSS, ROOM_SECRET, ROOM_SHOP}; +// A portal's room: its kind by subtype (PORTAL_ROOM_TYPES, else a normal room), or one room past 1000. +constexpr int PORTAL_ROOM_INDEX_BASE = 1000; // What the Broken Watch does to the room: nothing, slows it, or speeds it up. enum BrokenWatchState : int @@ -191,7 +200,7 @@ public: std::array gridTimers{}; std::array itemCounters{}; std::array, OUTPUT_GROUP_COUNT> outputGroupGridIndices; - std::array, OUTPUT_GROUP_COUNT> outputGroupCallbacks; + std::array, OUTPUT_GROUP_COUNT> outputGroupCallbacks; std::set litGridIndices; std::set pendingGridRemovals; std::deque shopRestocks; @@ -202,6 +211,7 @@ public: std::unique_ptr camera; TemporaryEffects temporaryEffects{}; std::array redDoorOutlines; + EntityPtr deathsListTarget; std::array rainSpawners{}; BeastArena beastArena; RailManager railManager; @@ -209,7 +219,6 @@ public: ANM2 satanRadialSprite; ANM2 spotLightSprite; RoomDescriptor* descriptor = nullptr; - Entity* deathsListTarget = nullptr; ColorMod floorColor = COLOR_DEFAULT; ColorMod wallColor = COLOR_DEFAULT; @@ -233,6 +242,7 @@ public: int bloodFromWallsCount = 0; int bloodFromWallsDuration = 0; int bossesRemaining = 0; + int bombRainTimer = 0; int bossId = 0; int dungeonRockIdx = -1; int enterFrame = 0; @@ -247,12 +257,11 @@ public: int secondBossId = 0; int shopLevel = 0; int shopRestockTimer = -1; + int shovelQuestTimer = 0; int slowdownDuration = 0; int tintedRockIdx = -1; int unknown70fc = 0; int unknown721c = 0; - int unknown7230 = 0; - int unknown72fc = 0; int unknown73f0 = 0; int waterLerpColorCountdown = -1; int waterLerpColorDuration = -1; @@ -265,6 +274,7 @@ public: bool isFirstEnemyDead = false; bool isFirstVisit = false; bool isInitialized = false; + bool isItemDuplicatePending = false; bool isPacifist = false; bool isPickupVisionInvalid = false; bool isRainStopped = false; @@ -274,7 +284,6 @@ public: bool isUnknown11f5 = false; bool isUnknown11f6 = true; bool isUnknown7220 = false; - bool isUnknown7769 = false; Room(); Room(const Room&) = delete; @@ -344,6 +353,7 @@ public: int GetFrameCount(); bool IsLShapedRoom(); bool IsBeastDungeon(); + float get_lava_line_y(); static bool IsMirrorWorld(); bool HasCurseMist(); bool HasWater(); @@ -372,6 +382,7 @@ public: void grid_paths_decay(); void Render(); void render_lighting(); + void render_debug_grid_values(Vector offset); void update_bounds(bool isFromGridSize); void LoadBackdropGraphics(); @@ -383,6 +394,8 @@ public: void crawlspace_ladders_make(); void greed_decorations_make(); bool SpawnGridEntity(int gridIndex, GridEntityType type, int variant, uint32_t seed, int varData); + bool CanPickupGridEntity(int gridIndex); + Entity_Effect* PickupGridEntity(int gridIndex); void RemoveGridEntity(int gridIndex, int pathTrail, DecorationRemoval removal); void RemoveGridEntityImmediate(int gridIndex, int pathTrail, DecorationRemoval removal); void RespawnEnemies(); @@ -409,6 +422,9 @@ public: bool spawn_sanguine_bond_spikes(bool isRoomInit); void RemoveDoor(int slot); void card_against_humanity_fill(); + Entity_Pickup* spawn_options_alternative(Entity_Pickup& pickup); }; int room_shape_get_door_grid_index(int doorSlot, int width, int height, int shape); +Vector random_position_away_from_players(Vector center, float clearance); +bool is_npc_type(int type); diff --git a/src/room_clear.cpp b/src/room_clear.cpp index 60885b4..423cf86 100644 --- a/src/room_clear.cpp +++ b/src/room_clear.cpp @@ -34,7 +34,6 @@ constexpr int COLLECTIBLE_LUCKY_FOOT_CLEAR = 46; constexpr int COLLECTIBLE_GUPPYS_TAIL = 134; 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_LITTLE_CHAD = 96; @@ -48,7 +47,6 @@ constexpr int TRINKET_CRYSTAL_KEY = 170; constexpr int TRINKET_TEMPORARY_TATTOO = 177; constexpr int NULLITEM_WAVY_CAP = 71; constexpr int FAMILIAR_BLUE_FLY_CLEAR = 43; -constexpr int ENTITY_ETERNALFLY_CLEAR = 96; constexpr int GRID_PATH_TRODDEN = 900; constexpr int BABY_SKIN_WISP = 64; constexpr int WISP_BABY_ODDS = 10; @@ -59,6 +57,9 @@ constexpr int ACHIEVEMENT_LITTLE_GISH = 23; constexpr int ACHIEVEMENT_LITTLE_STEVEN = 24; constexpr int ACHIEVEMENT_BOOK_OF_REVELATIONS = 7; constexpr int BABY_PLUM_BOSS = 84; +// Options' twin pickup: the rolls for a different kind, and how far the two stand from the first's spot. +constexpr int OPTIONS_PICK_TRIES = 10; +constexpr float OPTIONS_SPREAD = 15; // Ultra Greed's donation machine drops this far from the player, kept this far off the column below him. constexpr float GREED_MACHINE_REACH = 80; constexpr float GREED_MACHINE_CLEAR = 20; @@ -235,9 +236,12 @@ void room_spawn_cell_clear(Room& room, int& gridIndex) else if (grid) { if (grid->type == GRID_POOP) - for (Entity* entity : room.entityList.updateEL) - if (entity->type == ENTITY_ETERNALFLY_CLEAR && room.GetGridIndex(entity->pos) == gridIndex) - reconstruction_missing("Room::remove_grid_entity_for_spawn 007fa360: an Eternal Fly on the poop"); + for (Entity* fly : entity_query(ENTITY_ETERNALFLY, -1)) + if (!fly->parent && room.GetGridIndex(fly->targetPosition) == gridIndex) + { + static_cast(fly)->state = NPC_STATE_SPECIAL; + fly->Update(); + } spawn_cell_destroy(gridIndex); } @@ -517,6 +521,33 @@ static void award_coins_apply(ClearAward& award) if (rng.RandomInt(10000) < (uint32_t)odds) award.subType = RIB_OF_GREED_COINS[rng.RandomInt(5)]; } +// 008276e0 Options' second pickup beside a room's award: another kind of pickup rolled from the pickup's seed (ten +// tries for a different one), the two set 15 apart either way at a random angle and made a choice of one. A trap chest +// that cannot open there turns plain, and a glitched pickup's twin is glitched too. +Entity_Pickup* Room::spawn_options_alternative(Entity_Pickup& pickup) +{ + RNG rng = {pickup.initSeed, 3, 5, 25}; + int variant = PICKUP_NULL; + for (int i = 0; i < OPTIONS_PICK_TRIES && (variant == PICKUP_NULL || variant == pickup.variant); i++) + variant = clear_award_variant_pick(rng, AWARD_ROLL_PICKUP); + if (variant == PICKUP_NULL) return nullptr; + + Vector origin = pickup.pos; + RNG angleRng = {rng.Next(), 3, 1, 14}; + float angle = angleRng.RandomFloat() * RANDOM_HALF_TURN * 2; + Vector offset = vector_make(std::cos(angle) * OPTIONS_SPREAD, std::sin(angle) * OPTIONS_SPREAD); + auto* twin = static_cast(g_game->Spawn( + {.position = vector_add(origin, offset), .type = ENTITY_PICKUP, .variant = variant, .seed = rng.Next()})); + bool isTrapChest = twin->variant == PICKUP_SPIKEDCHEST || twin->variant == PICKUP_MIMICCHEST || + twin->variant == PICKUP_MEGACHEST; + if (twin->type == ENTITY_PICKUP && isTrapChest && !CanSpawnObstacleAtPosition(GetGridIndex(origin), false)) + twin->Morph(ENTITY_PICKUP, PICKUP_CHEST, 1, false, false, false); + if (pickup.HasEntityFlags(FLAG_GLITCH)) twin->AddEntityFlags(FLAG_GLITCH); + twin->optionsPickupIndex = pickup.AssignOptionsIndex(); + pickup.pos = vector_sub(origin, offset); + return &pickup; +} + // Spawns the award's pickups at free spots near the center. Each keeps the subtype the first got, a spiked or mimic // chest that cannot open there turns plain, and Broken Modem glitches the first. static void award_pickups_spawn(ClearAward& award) @@ -540,8 +571,7 @@ static void award_pickups_spawn(ClearAward& award) } if (award.isGlitched && i == 0) pickup->AddEntityFlags(FLAG_GLITCH); if (players.FirstCollectibleOwner(COLLECTIBLE_OPTIONS, LAZARUS_SHARE_CHECK)) - reconstruction_missing("Room::SpawnClearAward 007fb250: Options' alternative (Room::" - "spawn_options_alternative 008276e0)"); + g_game->room->spawn_options_alternative(*pickup); } } @@ -559,10 +589,10 @@ static void award_extras_spawn(Room& room, ClearAward& award) if (award.rng.RandomFloat() < chance) { Vector spot = free_spot_get(award.reward); - game.Spawn({.position = spot, .subType = 1, .type = ENTITY_PICKUP, .variant = PICKUP_LIL_BATTERY, - .seed = award.rng.Next()}); + Entity* battery = game.Spawn({.position = spot, .subType = 1, .type = ENTITY_PICKUP, + .variant = PICKUP_LIL_BATTERY, .seed = award.rng.Next()}); if (players.AnyoneHasCollectible(COLLECTIBLE_OPTIONS)) - reconstruction_missing("Room::SpawnClearAward 007fb250: Options' alternative battery"); + room.spawn_options_alternative(*static_cast(battery)); } } @@ -659,8 +689,12 @@ static int boss_item_pick(Room& room, ClearAward& award) else if (room.roomType == ROOM_BOSSRUSH && game.playerManager.FirstCollectibleOwner(COLLECTIBLE_BROKEN_SHOVEL_1, LAZARUS_SHARE_CHECK)) item = COLLECTIBLE_BROKEN_SHOVEL_2; - else if (room.bossId == BABY_PLUM_BOSS) - reconstruction_missing("Room::SpawnClearAward 007fb250: Baby Plum's Plum Flute (Room +0x73f0)"); + else if (room.bossId == BABY_PLUM_BOSS && room.unknown73f0 == -1 && isLeft(COLLECTIBLE_PLUM_FLUTE)) + { + room.unknown73f0 = 0; + data.TryUnlock(ACHIEVEMENT_PLUM_FLUTE); + item = COLLECTIBLE_PLUM_FLUTE; + } if (!item) return pool.GetSeededCollectible(award.rng.Next(), 0, *room.descriptor); pool.RemoveCollectible(item, REMOVE_ANY, REMOVE_APPLY); @@ -709,7 +743,12 @@ static void boss_items_spawn(Room& room, ClearAward& award) PlayerManager& players = game.playerManager; int item = boss_item_pick(room, award); if (game.challenge == CHALLENGE_CANTRIPPED) - reconstruction_missing("Room::SpawnClearAward 007fb250: Cantripped!'s boss card"); + { + g_pickupIgnoreModifiers++; + boss_item_spawn(room, award, vector_make(award.reward.x, award.itemRow), COLLECTIBLE_STARTER_DECK); + g_pickupIgnoreModifiers--; + return; + } int specialItem = 0; int specialTrinket = 0; @@ -789,7 +828,7 @@ static bool is_void_reachable() ChallengeParam& params = game.GetChallengeParams(); bool isOpen = params.endStage == STAGE_VOID || - (game.challenge == 0 && game.dailyChallenge._id == 0 && + (game.challenge == 0 && game.dailyChallenge.id == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_THE_VOID)); int endStage = isOpen ? STAGE_VOID : STAGE_DARK_ROOM; if (params.isPathTypeSet) @@ -1083,7 +1122,7 @@ static void dark_room_award_spawn(Room& room, ClearAward& award, bool isContinui if (!game.GetStateFlag((GameStateFlag)GAME_STATE_HEART_BOMB_COIN_PICKED)) data.TryUnlock(ACHIEVEMENT_ITS_THE_KEY); for (int lap = 0; lap < (int)VICTORY_LAP_UNLOCKS.size(); lap++) if (game.victoryLap > lap) victory_lap_unlock(VICTORY_LAP_UNLOCKS[lap]); - if (game.challenge == 0 && game.dailyChallenge._id == 0 && !game.IsGreedMode()) + if (game.challenge == 0 && game.dailyChallenge.id == 0 && !game.IsGreedMode()) game.genericPrompt.Show(PROMPT_LOCAL); } @@ -1373,18 +1412,24 @@ void room_clear_award_spawn(Room& room) room.descriptor->awardSeed = award.rng._seed; } -// The Broken Shovel quest: Mom's voice when the Basement's boss falls within a minute after the Lamb was killed. -static void shovel_quest_check() +// The Broken Shovel quest: Mom's voice when the Basement's boss falls within a minute after the Lamb was killed, in a +// run that may unlock achievements (or online). Its alarm then starts. +static void shovel_quest_check(Room& room) { Game& game = *g_game; - bool isQuestBoss = g_manager->persistentGameData.eventCounters[EVENT_COUNTER_LAMB_KILLS] != 0 && + bool isUnlocking = (!game.seedEffects.isCustomRun && !game.seedEffects.AchievementUnlocksDisallowed() && + !Manager::AchievementUnlocksDisallowed() && !game.isRerun) || + g_manager->netplayManager.is_online(); + bool isQuestBoss = isUnlocking && g_manager->persistentGameData.eventCounters[EVENT_COUNTER_LAMB_KILLS] != 0 && !(game.levelStateFlags & (1u << LEVEL_STATE_SHOVEL_QUEST_TRIGGERED)) && Room::IsCurrentRoomLastBoss() && game.stage == 1 && game.stageType != STAGETYPE_REPENTANCE && game.stageType != STAGETYPE_REPENTANCE_B && game.frameCount < SHOVEL_QUEST_FRAMES; - if (isQuestBoss) - reconstruction_missing("Room::TriggerClear 008068f0: the Broken Shovel quest (Manager::IsGameplayInputActive " - "009595e0, Room +0x72fc)"); + if (!isQuestBoss) return; + + game.levelStateFlags |= 1u << LEVEL_STATE_SHOVEL_QUEST_TRIGGERED; + sound_play(SOUND_MOM_VOX_FILTERED_ISAAC); + room.shovelQuestTimer = 0; } // 008068f0 Room::TriggerClear: marks and counts the clear, scores it, opens the exits it earns (the secret exit, the @@ -1417,7 +1462,7 @@ void room_clear_trigger(Room& room, ClearSound sound) room.TrySpawnBossRushDoor(false, false); room.TrySpawnBlueWombDoor(true, false, false); room.TrySpawnTheVoidDoor(false); - shovel_quest_check(); + shovel_quest_check(room); } if (!(descriptor.flags & ROOM_DESCRIPTOR_FLAG_NO_REWARD)) diff --git a/src/room_config.cpp b/src/room_config.cpp index d2ae3bc..313fd80 100644 --- a/src/room_config.cpp +++ b/src/room_config.cpp @@ -37,7 +37,7 @@ constexpr std::string_view GENERATED_ROOM_NAME = "generated"; constexpr int CURSE_SLOTS = 9; constexpr uint16_t QUEST_DOOR_VARIANT = 2; -constexpr uint32_t GRID_PRESSURE_PLATE = 4500; +constexpr uint32_t GRID_SPAWN_PRESSURE_PLATE = 4500; constexpr int ROOM_TYPE_DEFAULT = 1; constexpr int MINESHAFT_SUBTYPE = 31; constexpr int PATCHED_VARIANT_A = 603; @@ -258,7 +258,7 @@ static void read_room(StbReader& reader, int stageId, RoomConfig_Room& room) int slot = RoomConfig::get_door_from_position(spawn.x, spawn.y, room.shape); bool isQuestDoor = entry.type == ENTITY_ENVIRONMENT && entry.variant == QUEST_DOOR_VARIANT; if (isQuestDoor && slot != DOOR_NONE) room.questDoors |= 1u << slot; - if (entry.type == GRID_PRESSURE_PLATE && entry.variant == 0) room.flags |= ROOM_FLAG_PRESSURE_PLATE; + if (entry.type == GRID_SPAWN_PRESSURE_PLATE && entry.variant == 0) room.flags |= ROOM_FLAG_PRESSURE_PLATE; } } } diff --git a/src/room_grid.cpp b/src/room_grid.cpp index da7e0cd..1581d95 100644 --- a/src/room_grid.cpp +++ b/src/room_grid.cpp @@ -1,13 +1,19 @@ #include "room_grid.h" #include "capsule.h" #include "entity_player.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_npc.h" #include "game.h" #include "grid_entity_door.h" #include "grid_entity_pit.h" +#include "grid_entity_poop.h" #include "grid_entity_rock.h" +#include "grid_entity_tnt.h" #include "log.h" #include "npc_ai.h" #include "room.h" +#include "room_descriptor.h" #include #include #include @@ -321,3 +327,92 @@ void Room::RemoveGridEntityImmediate(int gridIndex, int pathTrail, DecorationRem gridPaths[gridIndex] = pathTrail; delete std::exchange(gridEntities[gridIndex], nullptr); } + +// The rocks Mom's Bracelet and the Polty lift: plain, tinted, bomb, urn, super secret, alternate and fool's gold. +static bool is_liftable_rock(GridEntityType type) +{ + return type == GRID_ROCK || type == GRID_ROCKT || type == GRID_ROCK_BOMB || type == GRID_ROCK_ALT || + type == GRID_ROCK_SS || type == GRID_ROCK_ALT2 || type == GRID_ROCK_GOLD; +} + +// 00825730 Whether the grid entity on a cell can be lifted: a solid rock, an unexploded TNT or a whole poop. +bool Room::CanPickupGridEntity(int gridIndex) +{ + GridEntity* grid = (uint32_t)gridIndex < ROOM_GRID_CELLS ? gridEntities[gridIndex] : nullptr; + if (!grid || grid->collisionClass == COLLISION_NONE) return false; + if (grid->type == GRID_TNT) return (uint32_t)grid->state < TNT_STATE_BLOWN; + if (grid->type == GRID_POOP) return grid->state != POOP_STATE_BROKEN; + return is_liftable_rock(grid->type); +} + +// 008257a0 (misnamed spawn_grid_from_desc) Lifts the grid entity off a cell, handing back its description and sprite: +// a rock (spiked ones too: its worms come out, a big rock's neighbours update, the cells around redraw), an unexploded +// TNT or a whole poop. A Giga Poop's four quarters all leave, decorations taking their cells, as does any other cell +// (a rock may leave its ladder in its place instead). The Eternal Flies resting on the cell wake. False for anything +// else. +static bool grid_lift(Room& room, int gridIndex, GridEntityDesc& desc, ANM2& sprite) +{ + constexpr int DECORATION_LIFTED = 1000; + GridEntity* grid = (uint32_t)gridIndex < ROOM_GRID_CELLS ? room.gridEntities[gridIndex] : nullptr; + if (!grid || grid->collisionClass == COLLISION_NONE) return false; + + bool isRock = is_liftable_rock(grid->type) || grid->type == GRID_ROCK_SPIKED; + if (isRock) + { + auto* rock = static_cast(grid); + rock->TrySpawnWorms(); + if (grid->variant >= BIG_ROCK_VARIANT) + { + rock->UpdateNeighbors(); + rock->SetBigRockFrame(-1); + } + grid_mark_neighbors_dirty(grid->gridIndex); + } + else if (!room.CanPickupGridEntity(gridIndex)) + return false; + + sprite = grid->sprite; + desc = grid->desc_save(); + auto decorate = [&room](int cell, uint32_t seed) + { + room.RemoveGridEntityImmediate(cell, 0, DECORATION_REMOVED); + room.SpawnGridEntity(cell, GRID_DECORATION, DECORATION_LIFTED, seed, 0); + }; + bool isGigaPoop = grid->type == GRID_POOP && grid->variant >= POOP_GIGA_TOP_LEFT && + grid->variant <= POOP_GIGA_BOTTOM_RIGHT; + if (isGigaPoop) + { + auto* poop = static_cast(grid); + desc._variant = POOP_GIGA_TOP_LEFT; + for (int part = POOP_GIGA_TOP_LEFT; part <= POOP_GIGA_BOTTOM_RIGHT; part++) + if (GridEntity_Poop* quarter = part != grid->variant ? poop->get_giga_part(part, false) : nullptr) + decorate(quarter->gridIndex, quarter->spawnSeed); + decorate(grid->gridIndex, grid->spawnSeed); + } + else if (!isRock || !static_cast(grid)->TrySpawnLadder()) + decorate(gridIndex, grid->spawnSeed); + + for (Entity* fly : entity_query(ENTITY_ETERNALFLY, -1)) + { + if (fly->parent || room.GetGridIndex(fly->pos) != gridIndex) continue; + static_cast(fly)->state = NPC_STATE_SPECIAL; + fly->Update(); + } + return true; +} + +// 00825c50 Lifts a cell's grid entity into a hidden effect carrying its look and description, the room's backdrop as +// its state. None when nothing there can be lifted. +Entity_Effect* Room::PickupGridEntity(int gridIndex) +{ + GridEntityDesc desc = GRID_SAVE_EMPTY; + ANM2 sprite; + if (!grid_lift(*this, gridIndex, desc, sprite)) return nullptr; + + auto* effect = static_cast( + g_game->Spawn({.type = ENTITY_EFFECT, .variant = EFFECT_GRID_ENTITY_PROJECTILE_HELPER, .seed = Random()})); + std::swap(sprite, effect->sprite); + effect->gridDesc = desc; + effect->state = backdropType; + return effect; +} diff --git a/src/room_path.cpp b/src/room_path.cpp index 20b23c9..9c84611 100644 --- a/src/room_path.cpp +++ b/src/room_path.cpp @@ -104,7 +104,7 @@ static void path_carve(Room& room, const std::array& static_cast(grid)->UpdateCollision(); } else if (room.enterFrame == g_game->frameCount) - reconstruction_missing("Room::PickupGridEntity 00825c50"); + room.PickupGridEntity(cell); else grid->Destroy(true, EntityRef()); } } diff --git a/src/room_render.cpp b/src/room_render.cpp index af6f0b9..a0225d1 100644 --- a/src/room_render.cpp +++ b/src/room_render.cpp @@ -12,6 +12,7 @@ #include "level.h" #include "log.h" #include "manager.h" +#include "menu_collection.h" #include "rail_manager.h" #include "render_passes.h" #include "room.h" @@ -20,6 +21,12 @@ #include #include +// The debug grid views: half a cell's outline on screen, where a cell's text starts, and their faint yellow. +constexpr float DEBUG_CELL_HALF = 13; +constexpr float DEBUG_TEXT_LEFT = 12; +constexpr float DEBUG_TEXT_UP = 10; +constexpr KColor DEBUG_GRID_COLOR = kcolor_rgba(1, 1, 0, 0.2f); + // The images rooms draw from, and the texel settings init_room_render_surfaces gives some of them. constexpr const char* ASH_MASK_PNG = "gfx/ash_mask.png"; constexpr const char* CAUSTICS_PNG = "gfx/backdrop/caustics.png"; @@ -28,7 +35,7 @@ constexpr const char* COLD_LAVA_PNG = "gfx/grid/lava_cold.png"; constexpr const char* LAVA_PNG = "gfx/grid/lava.png"; constexpr const char* PIT_MASK_PNG = "gfx/grid/grid_pit_mask.png"; constexpr int TEXEL_KEEP = -1; -constexpr int ROOM_SURFACE_WIDTH = 780; +constexpr int FLOOR_SURFACE_WIDTH = 780; // The Ashpit's dust: three cloud layers drifting with the room's frames (half a frame more on odd frames), up to 4 a // frame across and 1 either way down, 2 to 6 opaque, lit by the room's light (greyed and darkened) and a faint glow. @@ -58,7 +65,7 @@ constexpr float DUST_RAY_GREEN_DARK = 0.19999999f; constexpr float DUST_RAY_BLUE = 0.8f; constexpr float DUST_RAY_BLUE_DARK = 0.15000004f; constexpr float DUST_RAY_HALF_WIDTH = 0.5f; -constexpr int ROOM_SURFACE_HEIGHT = 468; +constexpr int FLOOR_SURFACE_HEIGHT = 468; // The game shader Render's shadows and lighting overlay draw with (the original's shader table entry 0). constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset"; @@ -102,7 +109,6 @@ constexpr std::array DROSS_WATER_OFFSET = {0.08f, 0.06f, 0.03f}; // A grid cell on screen: the room's floor sits two cells in from the render surface's corner. constexpr float GRID_SCREEN_CELL = 26; constexpr float FLOOR_MARGIN = 52; -constexpr int WALL_CELLS = 2; constexpr float PIT_MASK_CELL_OFFSET = 39; // A flooded Mines room's lava paints over the pits' shapes keeping their alpha. @@ -229,15 +235,6 @@ constexpr int PLATE_VARIANT_ROOM_CLEAR = 3; constexpr int ROOM_IDX_BLUE_WOMB_LIGHT = -9; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_LIT_DOOR = 1u << 18; -// The Beast's arena draws in passes around the room's: under everything, over the floor, over the entities, last. -enum BeastArenaPass -{ - BEAST_PASS_BACKGROUND, - BEAST_PASS_FLOOR, - BEAST_PASS_ENTITIES, - BEAST_PASS_FOREGROUND -}; - // The caustics band along the walls: its width before scaling, how fast it scrolls along the walls, turns and drifts // across them, the pit count that fills a flooded room's water, and the Corpse's red water. constexpr float CAUSTICS_EDGE = 50; @@ -328,9 +325,9 @@ void room_surfaces_init() if (render.isWaterOverlayEnabled) target_create(surfaces.waterOverlay, "Water Overlay Surface", frameWidth, frameHeight); target_create(surfaces.dizzy, "Dizzy Overlay Surface", frameWidth, frameHeight); - target_create(surfaces.shadingSurface, "Shading Surface (workaround)", ROOM_SURFACE_WIDTH, ROOM_SURFACE_HEIGHT); - target_create(surfaces.floorWaterV2, "Floor Water Surface (V2)", ROOM_SURFACE_WIDTH, ROOM_SURFACE_HEIGHT); - target_create(surfaces.texturedPit, "Textured Pit Surface", ROOM_SURFACE_WIDTH, ROOM_SURFACE_HEIGHT); + target_create(surfaces.shadingSurface, "Shading Surface (workaround)", FLOOR_SURFACE_WIDTH, FLOOR_SURFACE_HEIGHT); + target_create(surfaces.floorWaterV2, "Floor Water Surface (V2)", FLOOR_SURFACE_WIDTH, FLOOR_SURFACE_HEIGHT); + target_create(surfaces.texturedPit, "Textured Pit Surface", FLOOR_SURFACE_WIDTH, FLOOR_SURFACE_HEIGHT); image_create(surfaces.pitMask, PIT_MASK_PNG, TEXEL_KEEP, TEXEL_KEEP); image_create(surfaces.lava, LAVA_PNG, WRAP_REPEAT, TEXEL_KEEP); image_create(surfaces.coldLava, COLD_LAVA_PNG, WRAP_REPEAT, TEXEL_KEEP); @@ -1024,7 +1021,7 @@ static void floor_render(Room& room, Vector surfaceOffset, bool isWaterShown) grids_render(room, scroll, [](const GridEntity& grid) { return grid.type == GRID_DECORATION; }); } list.render_up_to(DEPTH_FLOOR, scroll); - if (room.backdropType == BACKDROP_DUNGEON_BEAST) render_beast_arena_background(&room.beastArena, BEAST_PASS_FLOOR); + if (room.backdropType == BACKDROP_DUNGEON_BEAST) room.beastArena.render_background(BEAST_PASS_FLOOR); } // The walls pass: the backdrop's walls, the caustics in the blend the floor began with, and (without a water surface) @@ -1430,6 +1427,23 @@ static void shockwave_surface_resolve(Room& room, Vector surfaceOffset) graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); } +// 008128f0 The debug view of the grid paths (debug 2): each cell outlined in faint yellow with its path's value. +void Room::render_debug_grid_values(Vector offset) +{ + Font& font = g_manager->font6_PFTempestaSevenCondensed; + + for (int i = 0; i < gridWidth * gridHeight; i++) + { + Vector cell = vector_add(render_position_get(GetGridPosition(i), RENDER_SNAPPED), offset); + Vector corner = vector_make(cell.x - DEBUG_CELL_HALF, cell.y - DEBUG_CELL_HALF); + Vector size = vector_make(DEBUG_CELL_HALF * 2, DEBUG_CELL_HALF * 2); + FontSettings settings; + quad_outline_render(KAGE::Graphics::color_quad_rect(corner, size, DEBUG_GRID_COLOR), 1); + font.DrawString(std::to_string(gridPaths[i]), vector_make(cell.x - DEBUG_TEXT_LEFT, cell.y - DEBUG_TEXT_UP), + vector_make(1, 1), DEBUG_GRID_COLOR, settings); + } +} + // 0080f200 Draws the room: the behind layers, the floor with its entities, the walls, rails and flat grid entities, // the doors, shading and shadows, the players' glows, the grid entities and entities by depth, the players' extra // bodies and Night Lights, the lighting overlay, the foreground and overlay layers, and the Ashpit's dust. Retro @@ -1462,7 +1476,7 @@ void Room::Render() if (isUteroSurface) effect_surface_begin(roomSurfaces.waterOverlay); if (isHeatWave) effect_surface_begin(roomSurfaces.heatWave); - if (backdropType == BACKDROP_DUNGEON_BEAST) render_beast_arena_background(&beastArena, BEAST_PASS_BACKGROUND); + if (backdropType == BACKDROP_DUNGEON_BEAST) beastArena.render_background(BEAST_PASS_BACKGROUND); graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); fxLayers.behind_layers_render(); if (!isAnySurface) floor_quad_render(*this, surfaceOffset); @@ -1473,7 +1487,7 @@ void Room::Render() if (roomType != ROOM_DUNGEON) walls_render(*this, surfaceOffset, isWaterShown, floorBlend); entityList.render_up_to(DEPTH_GRID, renderScrollOffset); if (isHeatWave) overlay_surface_resolve(*this, roomSurfaces.heatWave, HEAT_WAVE_SHADER); - if (backdropType == BACKDROP_DUNGEON_BEAST) render_beast_arena_background(&beastArena, BEAST_PASS_ENTITIES); + if (backdropType == BACKDROP_DUNGEON_BEAST) beastArena.render_background(BEAST_PASS_ENTITIES); doors_shading_render(*this, surfaceOffset); if (isUteroSurface) overlay_surface_resolve(*this, roomSurfaces.waterOverlay, WATER_OVERLAY_SHADER); @@ -1483,12 +1497,12 @@ void Room::Render() depth_render(*this, isWaterShown); for (Entity_Player* extra : game.playerManager.extraPlayers) extra->Render(renderScrollOffset); night_lights_render(*this); - if (game.debugFlags & DEBUG_GRID_VALUES) reconstruction_missing("Room::render_debug_grid_values 008128f0"); + if (game.debugFlags & DEBUG_GRID_VALUES) render_debug_grid_values(renderScrollOffset); if (game.debugFlags & DEBUG_GRID_INDICES) reconstruction_missing("Room::render_debug_grid_indices 0081f130"); shader_select(COLOR_OFFSET_SHADER); if (render.isLightingEnabled) lighting_overlay_render(*this); - if (backdropType == BACKDROP_DUNGEON_BEAST) render_beast_arena_background(&beastArena, BEAST_PASS_FOREGROUND); + if (backdropType == BACKDROP_DUNGEON_BEAST) beastArena.render_background(BEAST_PASS_FOREGROUND); fxLayers.Render(); if (is_ashpit_rays()) dust_render(); if (isShockwaveSurface) shockwave_surface_resolve(*this, surfaceOffset); diff --git a/src/room_special.cpp b/src/room_special.cpp index ea17b01..e28dcee 100644 --- a/src/room_special.cpp +++ b/src/room_special.cpp @@ -13,6 +13,7 @@ #include "room.h" #include "room_grid.h" #include +#include #include #include @@ -609,6 +610,32 @@ void room_restock_partial(Room& room) room.descriptor->spawnSeed = rng.Next(); } +// 00816000 Room::ShopReshuffle: shuffles which ware each shop slot sells by the award seed. Kept items stay on slots +// that sold items, swapped with a slot that drew one. A new sale goes on a random slot two times in three, else none. +void room_shop_reshuffle(Room& room, uint32_t flags) +{ + RoomDescriptor& desc = *room.descriptor; + RNG rng = {desc.awardSeed, 5, 9, 7}; + std::array slots{}; + + std::copy(desc.shopItemSlots.begin(), desc.shopItemSlots.end(), slots.begin()); + RNG::Shuffle(&rng, slots.data(), slots.data() + slots.size()); + for (size_t i = 0; i < slots.size() && (flags & RESHUFFLE_KEEP_ITEMS); i++) + { + if (desc.shopItemSlots[i] != SHOP_WARE_ITEM || slots[i] == SHOP_WARE_ITEM) continue; + for (size_t j = 0; j < slots.size(); j++) + if (desc.shopItemSlots[j] != SHOP_WARE_ITEM && slots[j] == SHOP_WARE_ITEM) + { + std::swap(slots[i], slots[j]); + break; + } + } + std::copy(slots.begin(), slots.end(), desc.shopItemSlots.begin()); + + if (flags & RESHUFFLE_SALE) desc.shopItemDiscountIdx = discount_slot_roll(rng, SHOP_SLOT_COUNT); + desc.awardSeed = rng._seed; +} + // 006fe3d0 Teleports a player to a random room of the floor (an error room's random room when asked). void game_random_room_move(Game& game, bool isErrorRoom, uint32_t seed, Entity_Player* player) { @@ -730,6 +757,31 @@ static void shopkeeper_start(Entity_NPC& npc) npc.UpdatePickupGhosts(); } +// Part of 006c2220: Greed jumps out of a secret room's shopkeeper. It counts among the room's enemies, the boss +// music starts, the room turns into a miniboss fight and shuts its doors (secret doors showing open), uncleared. +static void greed_ambush_start(Entity& greed) +{ + Room& room = *g_game->room; + + if (greed.CanShutDoors() && greed.type != ENTITY_DARK_ESAU) + { + room.entityList.enemyCount++; + if (greed.IsBoss()) room.entityList.bossCount++; + } + greed.Update(); + g_manager->musicManager.Crossfade(room.boss_music_get(), MUSIC_FADE_RATE); + room.isSurpriseMiniboss = true; + for (GridEntity_Door* door : room.doors) + { + if (!door || door->state == DOOR_STATE_CLOSED) continue; + door->state = DOOR_STATE_CLOSED; + door->UpdateAnimation(); + for (int type : {door->currentRoomType, door->targetRoomType}) + if (type == ROOM_SECRET || type == ROOM_SUPERSECRET || type == ROOM_ULTRASECRET) door->openAnimation = "Open"; + } + room.descriptor->flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR; +} + // 006c2220 The shopkeeper stands still where it started. Killed, it counts the kill for the run and the floor and // drops its loot: spiders thrown at a free spot, pickups scattered when there are several. void npc_shopkeeper_update(Entity_NPC& npc) @@ -755,17 +807,17 @@ void npc_shopkeeper_update(Entity_NPC& npc) Entity_NPC::ThrowSpider(npc.pos, &npc, target, false, SHOPKEEPER_SPIDER_HEIGHT); continue; } - if (drop.type == ENTITY_GREED) - { - reconstruction_missing("NpcAI::ENTITY_SHOPKEEPER 006c2220: Greed out of a secret room's shopkeeper"); - continue; - } Entity* entity = game.Spawn({.position = npc.pos, .subType = drop.subType, .type = drop.type, .variant = drop.variant, .seed = drop.seed}); + if (entity->type == ENTITY_GREED) + { + greed_ambush_start(*entity); + continue; + } if (loot.size() > 1 && entity->type == ENTITY_PICKUP) entity->velocity = Entity_Pickup::GetRandomPickupVelocity(npc.pos, nullptr, 0); entity->Update(); @@ -812,11 +864,8 @@ constexpr int KNIFE_PARTICLES_SPREAD = 6; constexpr int KNIFE_SPLASH_SUBTYPE = 10; constexpr float POOF_DEPTH = 5; constexpr int DUST_MIN = 3; -constexpr float DUST_SPEED = 5; constexpr float DUST_SIDE_SPEED = 2.5f; -constexpr float DUST_RADIUS = 20; constexpr float DUST_SPIN = 10; -constexpr float DUST_SPIN_MIN = 2; constexpr int DUST_LIFE_MIN = 15; constexpr float HALF_TURN = 3.14f; constexpr ColorMod BLUE_KEY_COLOR = {{1, 1, 1, 1}, {0.4f, 0.6f, 1, 1}, {0, 0, 0}}; @@ -875,7 +924,7 @@ bool GridEntity_Door::TryBlowOpen(bool isFromExplosion, Entity* source) if (doorFlags & DOOR_FLAG_MIRROR) { - bool isRepentancePath = (game.challenge != 0 || game.dailyChallenge._id != 0) && + bool isRepentancePath = (game.challenge != 0 || game.dailyChallenge.id != 0) && game.GetChallengeParams().pathType == PATH_TYPE_REPENTANCE; if (isRepentancePath || state == DOOR_STATE_OPEN) return false; variant = DOOR_UNLOCKED; diff --git a/src/room_special.h b/src/room_special.h index b6938be..ffcfd42 100644 --- a/src/room_special.h +++ b/src/room_special.h @@ -32,6 +32,13 @@ enum ShopWare : int16_t SHOP_WARE_SOUL_CARD }; +// What Room::ShopReshuffle keeps besides shuffling the slots, by bit: the collectibles' slots, and a new sale. +enum ShopReshuffleFlag : uint32_t +{ + RESHUFFLE_KEEP_ITEMS = 1 << 0, + RESHUFFLE_SALE = 1 << 1 +}; + // A shop ware being priced or rolled: its kind, the shop slot it sells from (-1 for none, -2 for never discounted), // the seed it rolls from and its price. struct ShopOffer @@ -50,5 +57,6 @@ int room_shop_item_price(Room& room, const ShopOffer& offer, Entity_Player* play int room_shop_discount(Room& room, int shopItemId, int price, Entity_Player* player); void room_restock_trigger(Room& room, int gridIndex, int shopItemId); void room_restock_partial(Room& room); +void room_shop_reshuffle(Room& room, uint32_t flags); void game_random_room_move(Game& game, bool isErrorRoom, uint32_t seed, Entity_Player* player); void npc_shopkeeper_update(Entity_NPC& npc); diff --git a/src/room_transition.cpp b/src/room_transition.cpp index 4ba20ff..1abdc5a 100644 --- a/src/room_transition.cpp +++ b/src/room_transition.cpp @@ -1,4 +1,5 @@ #include "room_transition.h" +#include "boss_ai.h" #include "boss_final.h" #include "boss_pool.h" #include "entity_familiar.h" @@ -10,6 +11,7 @@ #include "level.h" #include "log.h" #include "manager.h" +#include "npc_basement.h" #include "platform.h" #include "render_passes.h" #include "room.h" @@ -34,8 +36,8 @@ constexpr const char* ANIMATION_PICKUP_SPARKLE = "PlayerPickupSparkle"; constexpr const char* EVENT_POOF = "Poof"; constexpr int SLOWEST_FRAME_UNSET = 1000; constexpr int FOLLOW_MIN_FRAME = 6; -constexpr float RANDOM_PI = 3.14f; constexpr float MINECART_JITTER = 8; +constexpr float MINECART_LAUNCH_SPEED = 0.1f; constexpr int VERSUS_FIRE_BLOCK_FRAMES = 10; constexpr int TELEPORT_SOUND_FRAME = 8; constexpr int SOUND_ONE_UP = 1; @@ -46,6 +48,8 @@ constexpr int NPC_STATE_MINECART_MOVING = 4; constexpr int COLLECTIBLE_GLOWING_HOURGLASS = 422; constexpr const char* ANIMATION_APPEAR = "Appear"; constexpr float APPEAR_FRAME = 2; +constexpr const char* ANIMATION_JUMP = "Jump"; +constexpr int PORTAL_ARRIVAL_COOLDOWN = 35; constexpr float SCREEN_CELL_SIZE = 26; constexpr int ROOM_CELLS_ACROSS = 13; constexpr int ROOM_CELLS_DOWN = 7; @@ -55,20 +59,6 @@ constexpr float TELEPORTER_SCATTER = 10; // Dead Cat, 1up!, Guppy's Collar, Judas' Shadow and Lazarus' Rags. constexpr std::array EXTRA_LIFE_ITEMS = {161, 81, 11, 212, 311, 332}; -// Stops the boss overlay as BossOverlay's own stop does: it hides and the sound effects come back to full volume at -// the normal fade. Its sprite waits for BossOverlay's takeover, so a shown overlay stops the game here. -static void boss_overlay_stop(Game& game) -{ - SFXManager& sounds = g_manager->sfxManager; - if (game.bossOverlay._state != 0) reconstruction_missing("BossOverlay stop 00421260 on a shown overlay"); - - if (sounds.volumeModifier != 1) - { - sounds.volumeModifier = 1; - sounds.ClearVolumeModifier(); - } - sounds.volumeModifierStep = VOLUME_MODIFIER_STEP; -} // 0082ed00 Creates the surfaces the old and new rooms are captured into, of the framebuffer's size. void RoomTransition::surfaces_create() @@ -207,7 +197,7 @@ static void teleporter_arrival_place(Room& room, int target) for (Entity_Player* player : players.playerList) { if (player == traveller) continue; - float angle = random_unit() * RANDOM_PI; + float angle = random_unit() * RANDOM_HALF_TURN; angle += angle; float x = std::cos(angle) * TELEPORTER_SCATTER + at.x; float y = std::sin(angle) * TELEPORTER_SCATTER + at.y; @@ -239,7 +229,7 @@ static void death_certificate_players_place(Room& room) if (!player) continue; if (placed++ != 0) { - float angle = random_unit() * RANDOM_PI; + float angle = random_unit() * RANDOM_HALF_TURN; angle += angle; spot = vector_add(arrival, vector_make(std::cos(angle) * ARRIVAL_SCATTER, std::sin(angle) * ARRIVAL_SCATTER)); } @@ -250,6 +240,25 @@ static void death_certificate_players_place(Room& room) } } +// Part of 00830950: the players jump out of a Ventricle Razor portal, the first on it and the others a step off it, +// held still and unhurt for a moment, its blood babies with them. +static void ventricle_portal_arrive(Vector portal) +{ + bool isFirst = true; + + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (!player) continue; + player->pos = isFirst ? portal : vector_add(portal, random_direction()); + isFirst = false; + player->PlayExtraAnimation(ANIMATION_JUMP); + if (player->sprite.animState.animData) player->sprite.animState.SetFrameFloat(APPEAR_FRAME); + player->damageCooldown = std::max(player->damageCooldown, PORTAL_ARRIVAL_COOLDOWN); + player->isControlsEnabled = false; + } + for (Entity* baby : entity_query(ENTITY_FAMILIAR, Entity_Familiar::BLOOD_BABY)) baby->pos = portal; +} + // 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() @@ -261,9 +270,7 @@ void RoomTransition::arrival_place() if (animation == TRANSITION_WOMB_TELEPORT) { for (VentricleRazorPortal& portal : game.ventricleRazorPortals) - if (portal.roomIndex == game.currentRoomIdx) - reconstruction_missing("RoomTransition::ChangeRoom 00830950: the players jumping out of a Ventricle " - "Razor portal (Entity_Player +0x14c, +0x98)"); + if (portal.roomIndex == game.currentRoomIdx) ventricle_portal_arrive(room.GetGridPosition(portal.gridIndex)); return; } if (!is_teleport()) @@ -304,7 +311,7 @@ void RoomTransition::ChangeRoom() if (game.deathmatchManager.state < DEATHMATCH_INTRO) for (Entity_Player* player : players) player->isControlsEnabled = true; - if (animation == TRANSITION_GLOWING_HOURGLASS) reconstruction_missing("Game::rewind 00706020"); + if (animation == TRANSITION_GLOWING_HOURGLASS) Game::rewind(game.playerManager.roomTransitionPlayer); else { if (direction == DIRECTION_NONE) game.leaveDoor = DOOR_NONE; @@ -333,11 +340,23 @@ static bool is_animating(Entity_Player& player) return (player.isPlayingExtraAnimation || player.isPlayingItemAnimation) && !(data && data->isLooping); } -// Sets the minecart off along its rail, the players riding it. -// The rail it stands on and the minecart's own fields wait for Room's and Entity_NPC's rails. -static void minecart_launch(Entity_NPC&) +// Part of 008318a0: sets the minecart off along its rail, the players riding it. It updates through the transition and +// leaves a dead end away from it, else heads up. +static void minecart_launch(Entity_NPC& minecart) { - reconstruction_missing("RoomTransition::Update 008318a0: the minecart setting off on its rail"); + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(minecart.targetPosition); + uint8_t rail = (uint32_t)gridIndex < ROOM_GRID_CELLS ? room.railManager.rails[gridIndex] : RAIL_NONE; + int piece = rail == RAIL_NONE ? -1 : rail & RAIL_PIECE_MASK; + int direction = piece == RAIL_END_LEFT ? DIRECTION_RIGHT + : piece == RAIL_END_RIGHT ? DIRECTION_LEFT + : piece == RAIL_END_UP ? DIRECTION_DOWN + : DIRECTION_UP; + + minecart.AddEntityFlags(FLAG_TRANSITION_UPDATE); + minecart.state = NPC_STATE_MINECART_MOVING; + minecart.velocity = vector_scale(vector_from_direction(direction), MINECART_LAUNCH_SPEED); + minecart.targetPosition = vector_make(0, 0); } // The frame the players are captured on. They finish the animations that hold the transition, the room and the doors @@ -409,7 +428,7 @@ void RoomTransition::start_update(Entity_NPC* minecartNpc) idlePlayer->moveToTarget = slowestPlayer->moveToTarget; if (animation == TRANSITION_MINECART && minecartNpc) { - float angle = random_unit() * RANDOM_PI * 2; + float angle = random_unit() * RANDOM_HALF_TURN * 2; float reach = random_unit() * MINECART_JITTER; idlePlayer->moveToTarget = vector_make(reach * std::cos(angle) + minecartNpc->targetPosition.x, reach * std::sin(angle) + minecartNpc->targetPosition.y); @@ -510,7 +529,7 @@ void RoomTransition::arrival_update() Entity_Player* player = game.playerManager.roomTransitionPlayer; PlayerManager& players = game.playerManager; - boss_overlay_stop(game); + game.bossOverlay.stop(); frame = 0; mode = TRANSITION_LANDING; if (is_teleport()) diff --git a/src/room_update.cpp b/src/room_update.cpp index 4d5745c..360dcc5 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -1,5 +1,7 @@ #include "npc_basement.h" +#include "boss_ai.h" #include "boss_final.h" +#include "entity_bomb.h" #include "entity_effect.h" #include "entity_laser.h" #include "entity_npc.h" @@ -11,6 +13,7 @@ #include "grid_entity_pit.h" #include "level.h" #include "log.h" +#include "loot_list.h" #include "manager.h" #include "room.h" #include "room_clear.h" @@ -21,6 +24,7 @@ #include "seeds.h" #include #include +#include #include #include #include @@ -83,6 +87,63 @@ constexpr int HEART_DARK_FRAMES = 2; constexpr int HEART_DARKNESS_TIMEOUT = 10; constexpr int BOMB_RAIN_FRAMES = 5; +// Genesis's room retries its items a second later when nothing is left to draw, and poofs them in after its first +// frames. +constexpr int GENESIS_RETRY_FRAMES = 60; +constexpr int GENESIS_POOF_AFTER = 4; + +// The Lil Portal room's first visit: the chests by the percent rolled below each, the rewards below the room by the +// same, and how far below. +constexpr std::array, 5> LIL_PORTAL_CHESTS = {{{4, PICKUP_ETERNALCHEST}, + {9, PICKUP_SPIKEDCHEST}, + {19, PICKUP_BOMBCHEST}, + {29, PICKUP_REDCHEST}, + {54, PICKUP_LOCKEDCHEST}}}; +constexpr uint32_t LIL_PORTAL_SHARD_CHANCE = 25; +constexpr uint32_t LIL_PORTAL_BUTTER_CHANCE = 50; +constexpr uint32_t LIL_PORTAL_SOUL_CHANCE = 60; +constexpr uint32_t LIL_PORTAL_BOX_CHANCE = 61; +constexpr float LIL_PORTAL_BELOW = 32; + +// The enemies Seeing Double and G-Fuel double: the ones never doubled, the segmented ones copied whole, the wide ones +// pushed apart from their copy, and how far copies land. +constexpr std::array SEEING_DOUBLE_EXCLUDED = {ENTITY_MOM, ENTITY_SATAN, ENTITY_MEGA_SATAN, ENTITY_MEGA_SATAN_2}; +constexpr int MOMS_HEART_UNDOUBLED_VARIANT = 10; +constexpr int GFUEL_DOUBLING_FROM = 3; +constexpr std::array SEGMENTED_TYPES = {ENTITY_CHUB, ENTITY_LARRYJR, ENTITY_GRUB, ENTITY_BUTTLICKER}; +constexpr std::array WIDE_DOUBLED_TYPES = {ENTITY_MOMS_HEART, ENTITY_GURDY, ENTITY_MAMA_GURDY, ENTITY_SATAN, + ENTITY_MEGA_MAW, ENTITY_GATE, ENTITY_DADDYLONGLEGS}; +constexpr float WIDE_COPY_APART = 60; +constexpr float ISAAC_COPY_APART = 30; +constexpr float SEGMENT_COPY_DISTANCE = 40; +constexpr float COPY_DISTANCE = 20; + +// A spot away from the players: 20 tries on a ring growing by 20 then 4 every fourth try, kept 20 past a clearance. +constexpr int AWAY_TRIES = 20; +constexpr float AWAY_FIRST_GROWTH = 20; +constexpr float AWAY_GROWTH = 4; +constexpr int AWAY_GROWTH_EVERY = 4; +constexpr float AWAY_MARGIN = 20; + +// Damocles' split pedestals: the offset pairs of cells tried in turn for the pedestal and its twin, how far the free +// spot search starts, and how much lower pedestals stand in a crawlspace. +using SplitOffsets = std::array, 2>; +constexpr std::array SPLIT_PATTERNS = {{{{{-1, 0}, {1, 0}}}, + {{{0, -1}, {0, 1}}}, + {{{-1, -1}, {1, 1}}}, + {{{-1, 1}, {1, -1}}}, + {{{1, -1}, {-1, 1}}}, + {{{1, 1}, {-1, -1}}}, + {{{-1, 0}, {0, 0}}}, + {{{0, 0}, {1, 0}}}, + {{{0, -1}, {0, 0}}}, + {{{0, 0}, {0, 1}}}}}; +constexpr float SPLIT_SPOT_STEP = 60; +constexpr float DUNGEON_PEDESTAL_DROP = 30; + +// The pickups Death's List pays out, drawn evenly. +constexpr std::array DEATHS_LIST_PICKUPS = {PICKUP_PILL, PICKUP_KEY, PICKUP_COIN, PICKUP_BOMB, PICKUP_HEART}; + // The Dataminer's glitch of the music: one frame in ten it bends the pitch low or high and sometimes the volume. constexpr uint32_t DATAMINER_GLITCH_CHANCE = 10; constexpr float DATAMINER_PITCH_LOW = 0.2f; @@ -243,7 +304,8 @@ static Entity* entity_spawn(int type, int variant, Vector position, Vector veloc return g_game->Spawn({.position = position, .velocity = velocity, .type = type, .variant = variant, .seed = seed}); } -static bool is_npc_type(int type) +// Whether an entity type is an NPC (Entity::ToNPC's test): an enemy, or a player in a versus match. +bool is_npc_type(int type) { return (g_game->deathmatchManager.is_active() && type == ENTITY_PLAYER) || (type >= ENTITY_FIRST_ENEMY && type <= ENTITY_LAST_ENEMY); @@ -254,6 +316,27 @@ template static bool contains(const List& list, int value) return std::find(std::begin(list), std::end(list), value) != std::end(list); } +// 00802740 A random spot around a center, on a ring growing with each try, on a free cell and clear of every player. +// A blocked cell ends the search at the center, as in the original. +Vector random_position_away_from_players(Vector center, float clearance) +{ + Game& game = *g_game; + float radius = 0; + float reach = (clearance + AWAY_MARGIN) * (clearance + AWAY_MARGIN); + + for (int attempt = 0; attempt < AWAY_TRIES; attempt++) + { + Vector spot = vector_add(center, vector_scale(random_direction(), radius)); + if (attempt == 0) radius += AWAY_FIRST_GROWTH; + else if (attempt % AWAY_GROWTH_EVERY == 0) radius += AWAY_GROWTH; + if (game.room->GetGridCollision(game.room->GetGridIndex(spot)) != COLLISION_NONE) break; + + auto isNear = [&](Entity_Player* player) { return vector_length_squared(vector_sub(spot, player->pos)) <= reach; }; + if (std::none_of(game.playerManager.playerList.begin(), game.playerManager.playerList.end(), isNear)) return spot; + } + return center; +} + // Whether the room has an entity of a type and variant, as the original's type query finds. static bool entities_any(EntityList& list, int type, int variant) { @@ -386,33 +469,73 @@ static void dataminer_music_update(Room& room) } } -// 008020d0 Death's List: while a player holds it and the room's list is open, marks an enemy to kill next, and pays -// out once the room clears. Without it, or once done, the mark goes. -// The marking and the payout are not reconstructed yet. +// 008020d0 Death's List: while a player holds it and the room's list is open, marks an enemy to kill next (a living, +// vulnerable one that is not friendly, rewarding or a Blood Puppy, and no segment past the first). Once the room is +// clear with the list kept, each owner rolls from the award seed: a stat up one time in four, else a pickup at the last +// kill's spot. Without it, or once done, the mark goes. static void deaths_list_update(Room& room) { - bool isOwned = g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_DEATHS_LIST, LAZARUS_SHARE_CHECK); + Game& game = *g_game; + bool isOwned = game.playerManager.FirstCollectibleOwner(COLLECTIBLE_DEATHS_LIST, LAZARUS_SHARE_CHECK); - if (isOwned && !room.isDeathsListDone) reconstruction_missing("Room::update_deaths_list 008020d0"); + if (!isOwned) room.isDeathsListDone = true; + if (isOwned && !room.isDeathsListDone) + { + for (Entity* entity : entities_live(room.entityList.updateEL)) + { + if (room.deathsListTarget) break; + if (!entity->IsVulnerableEnemy(nullptr) || entity->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_REWARD)) continue; + if (entity->type == ENTITY_BLOOD_PUPPY || (entity->DoesEntityShareStatus() && entity->parent)) continue; + + room.deathsListTarget = entity; + Entity* skull = game.Spawn({.position = entity->pos, .type = ENTITY_EFFECT, .variant = EFFECT_DEATH_SKULL, .seed = Random()}); + skull->target = room.deathsListTarget; + skull->Update(); + } + } + else room.deathsListTarget = nullptr; + if (!(room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR) || room.isDeathsListDone) return; + + RNG rng = {room.descriptor->awardSeed, 1, 27, 27}; + for (Entity_Player* player : game.playerManager.playerList) + { + if (player->variant != PLAYER_VARIANT_PLAYER || !player->HasCollectible(COLLECTIBLE_DEATHS_LIST)) continue; + if ((rng.Next() & 3) == 0) + { + player->add_random_stat_up(&rng); + continue; + } + + int variant = DEATHS_LIST_PICKUPS[rng.Next() % DEATHS_LIST_PICKUPS.size()]; + int subType = variant == PICKUP_COIN ? COIN_NICKEL : variant == PICKUP_HEART ? HEART_SOUL : 0; + if (room.deathsListOffset.x == 0 && room.deathsListOffset.y == 0) + room.deathsListOffset = room_free_pickup_position_find({.position = player->pos, .step = PICKUP_SPOT_STEP}); + game.Spawn({.position = room.deathsListOffset, + .spawner = player, + .subType = subType, + .type = ENTITY_PICKUP, + .variant = variant, + .seed = rng.Next()}) + ->Update(); + } room.isDeathsListDone = true; - room.deathsListTarget = nullptr; } -// 00823080 Fires an output group: the grid entities on its cells, its 1000.120 effects (which then die) and its -// callbacks. -// The callbacks are not reconstructed yet. +// 00823080 Fires an output group: the grid entities on its cells, the spawners holding entities for it (which then let +// them out) and its callbacks. void Room::TriggerOutput(int group) { for (int gridIndex : outputGroupGridIndices[group]) if (gridEntities[gridIndex]) gridEntities[gridIndex]->trigger_output(); for (Entity* entity : entities_live(entityList.updateEL)) { - if (entity->type != ENTITY_EFFECT || entity->variant != 120 || entity->subtype != group) continue; + if (entity->type != ENTITY_EFFECT || entity->variant != EFFECT_SPAWNER) continue; + if (static_cast(entity)->state != group) continue; entity->isDead = true; entity->Update(); } - if (!outputGroupCallbacks[group].empty()) reconstruction_missing("Room::TriggerOutput 00823080: callbacks"); + for (OutputCallback callback : outputGroupCallbacks[group]) callback(); } // The clear check: while enemies or Greed's wave are left (or an ambush runs) the room holds off clearing; once the @@ -817,8 +940,22 @@ static void walls_bleed_update(Room& room) } } -// Flush! fills the room with water, flooding it once nearly full, and water cools the lava down until it is gone, its -// pits solid once it hardens and the screen's color following. Flush!'s pits under the flood are not reconstructed yet. +// The pits inside the room's walls. +static std::vector interior_pits(Room& room) +{ + std::vector pits; + + for (int x = 1; x < room.gridWidth - 1; x++) + for (int y = 1; y < room.gridHeight - 1; y++) + { + GridEntity* grid = room.gridEntities[x + y * room.gridWidth]; + if (grid && grid->type == GRID_PIT) pits.push_back(static_cast(grid)); + } + return pits; +} + +// Flush! fills the room with water, flooding it once nearly full (its pits set up again as water pits), and water +// cools the lava down until it is gone, its pits solid once it hardens and the screen's color following. static void flood_update(Room& room) { if (room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_FLUSH) && room.roomType != ROOM_DUNGEON) @@ -828,7 +965,11 @@ static void flood_update(Room& room) { room.descriptor->flags |= ROOM_DESCRIPTOR_FLAG_FLOODED; if (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER) - reconstruction_missing("Room::Update 00802980: Flush!'s pits"); + for (GridEntity_Pit* pit : interior_pits(room)) + { + pit->subclass_init(); + pit->PostInit(); + } } room.waterAmount = std::min(room.waterAmount, 1.0f); } @@ -836,12 +977,7 @@ static void flood_update(Room& room) float lava = room.lavaIntensity * LAVA_COOLING; if (lava < LAVA_SOLID && room.lavaIntensity >= LAVA_SOLID) - for (int x = 1; x < room.gridWidth - 1; x++) - for (int y = 1; y < room.gridHeight - 1; y++) - { - GridEntity* grid = room.gridEntities[x + y * room.gridWidth]; - if (grid && grid->type == GRID_PIT) static_cast(grid)->UpdateCollision(); - } + for (GridEntity_Pit* pit : interior_pits(room)) pit->UpdateCollision(); room.lavaIntensity = lava < LAVA_GONE ? 0 : lava; room.color_modifier_apply(); } @@ -934,6 +1070,325 @@ static void home_crawlspace_update(Room& room) ember->Update(); } +// Part of 00802980: Genesis's room fills its pedestals once its timer runs out. A pool is drawn from the ones Genesis +// took items from, weighed by how many, and each lone item spawn of the layout gets an item of it (with a poof after the +// first frames). With nothing left to draw the timer starts over. +static void genesis_items_spawn(Room& room) +{ + Game& game = *g_game; + RNG& rng = game.GetPlayer(0)->GetCollectibleRNG(COLLECTIBLE_GENESIS); + uint32_t seed = rng.Next(); + WeightedOutcomePicker picker; + + for (int pool = 0; pool < POOL_COUNT; pool++) + if ((int16_t)game.itemPool.remainingGenesisItems[pool] > 0) + picker.AddOutcomeWeight(pool, (int16_t)game.itemPool.remainingGenesisItems[pool]); + if (picker.outcomes.empty()) + { + room.genesisTimer = GENESIS_RETRY_FRAMES; + return; + } + + int pool = picker.PickOutcome({seed, 5, 9, 7}); + // The original takes one from the count before the pool list on a failed draw. Here nothing is taken. + if (pool < 0) + { + room.genesisTimer = GENESIS_RETRY_FRAMES; + return; + } + game.itemPool.remainingGenesisItems[pool]--; + for (RoomSpawn& spawn : room.descriptor->data->spawns) + { + if (spawn.entries.size() != 1) continue; + RoomEntry& entry = spawn.entries[0]; + if (entry.type != ENTITY_PICKUP || entry.variant != PICKUP_COLLECTIBLE || entry.subtype != 0) continue; + + int gridIndex = spawn.x + 1 + (spawn.y + 1) * room.gridWidth; + Vector position = room.GetGridPosition(gridIndex); + int item = game.itemPool.GetCollectible((ItemPoolType)pool, rng.Next(), 0, 0, 0); + Entity* pedestal = game.Spawn({.position = position, + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = rng.Next()}); + pedestal->AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + pedestal->spawnGridIndex = gridIndex; + if (room.isInitialized && game.frameCount - room.enterFrame > GENESIS_POOF_AFTER) + game.Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + } +} + +// Part of 00802980: the Lil Portal room keeps a portal back to the room it was entered from. On the first visit it +// holds a chest by chance, then maybe a Dice Shard, Butter!, the Soul of Eden or a Moving Box below the room, and one +// time in four a Lil Battery at its bottom left. +static void lil_portal_room_update(Room& room) +{ + Game& game = *g_game; + std::vector portals = entity_query(ENTITY_EFFECT, EFFECT_PORTAL_TELEPORT); + int subType = game.lastRoomIdx + PORTAL_ROOM_INDEX_BASE; + + if (portals.empty()) + { + Vector position = room_free_pickup_position_find( + {.position = Room::GetCenterPos(), .step = PICKUP_SPOT_STEP, .isAvoidActiveEntities = true}); + game.Spawn({.position = position, + .subType = subType, + .type = ENTITY_EFFECT, + .variant = EFFECT_PORTAL_TELEPORT, + .seed = Random()}); + } + else portals[0]->subtype = subType; + if (!room.isFirstVisit || room.enterFrame != game.frameCount) return; + + RNG rng = {room.descriptor->spawnSeed, 5, 9, 7}; + Vector position = room_free_pickup_position_find({.position = room.topLeftPos, .isAvoidActiveEntities = true}); + uint32_t roll = rng.Next() % 100; + int chest = PICKUP_CHEST; + for (auto [chance, variant] : LIL_PORTAL_CHESTS) + if (roll < chance) + { + chest = variant; + break; + } + game.Spawn({.position = position, .subType = 1, .type = ENTITY_PICKUP, .variant = chest, .seed = Random()}); + + Vector below = vector_add(room.bottomRightPos, vector_make(0, LIL_PORTAL_BELOW)); + position = room_free_pickup_position_find({.position = below, .isAvoidActiveEntities = true}); + PersistentGameData& data = g_manager->persistentGameData; + EntitySpawn reward = {.position = position, .type = ENTITY_PICKUP}; + roll = rng.Next() % 100; + if (roll < LIL_PORTAL_SHARD_CHANCE) reward = {.position = position, .subType = CARD_DICE_SHARD, .type = ENTITY_PICKUP, .variant = PICKUP_TAROTCARD}; + else if (roll < LIL_PORTAL_BUTTER_CHANCE) + { + if (data.Unlocked(ACHIEVEMENT_BUTTER)) reward = {.position = position, .subType = TRINKET_BUTTER, .type = ENTITY_PICKUP, .variant = PICKUP_TRINKET}; + } + else if (roll < LIL_PORTAL_SOUL_CHANCE) + { + if (data.Unlocked(ACHIEVEMENT_SOUL_OF_EDEN)) reward = {.position = position, .subType = CARD_SOUL_EDEN, .type = ENTITY_PICKUP, .variant = PICKUP_TAROTCARD}; + } + else if (roll < LIL_PORTAL_BOX_CHANCE && data.Unlocked(ACHIEVEMENT_MOVING_BOX)) + reward = {.position = position, .subType = COLLECTIBLE_MOVING_BOX, .type = ENTITY_PICKUP, .variant = PICKUP_COLLECTIBLE}; + if (reward.variant) + { + reward.seed = Random(); + game.Spawn(reward); + } + + if ((rng.Next() & 3) != 0) return; + Vector corner = vector_make(room.topLeftPos.x, room.bottomRightPos.y); + position = room_free_pickup_position_find({.position = corner, .isAvoidActiveEntities = true}); + game.Spawn({.position = position, .type = ENTITY_PICKUP, .variant = PICKUP_LIL_BATTERY, .seed = Random()}); +} + +// Part of 00802980: the enemies Seeing Double doubles and the ones G-Fuel may double (a coin flip each for every G-Fuel +// past three) on entering: living hostile ones that keep the doors shut and stand on a spawn cell, never Mom, Satan, +// Mega Satan or Mom's Heart's tenth variant, and no bosses for G-Fuel. +static std::vector doubled_enemies_collect(Room& room) +{ + Game& game = *g_game; + std::vector doubled; + int gFuel = game.playerManager.GetGFuelCount(); + + if (game.challenge == CHALLENGE_SEEING_DOUBLE) + for (Entity* entity : room.entityList.updateEL) + { + if (!is_npc_type(entity->type) || entity->HasEntityFlags(FLAG_FRIENDLY) || !entity->CanShutDoors()) continue; + if (entity->spawnGridIndex < 0 || contains(SEEING_DOUBLE_EXCLUDED, entity->type)) continue; + if (entity->type == ENTITY_MOMS_HEART && entity->variant == MOMS_HEART_UNDOUBLED_VARIANT) continue; + doubled.push_back(entity); + } + if (gFuel <= GFUEL_DOUBLING_FROM) return doubled; + + for (Entity* entity : room.entityList.updateEL) + { + if (!is_npc_type(entity->type) || entity->HasEntityFlags(FLAG_FRIENDLY) || !entity->CanShutDoors()) continue; + if (entity->spawnGridIndex < 0 || entity->IsBoss()) continue; + for (int i = GFUEL_DOUBLING_FROM; i < gFuel; i++) + if ((entity->dropRNG.Next() & 1) == 0) doubled.push_back(entity); + } + return doubled; +} + +// Part of 00802980: each doubled enemy's copy, marked as an ambush spawn on its spawn cell. Wide bosses stand apart +// sideways from their copy (Isaac vertically), others get it 20 away. A segmented enemy is copied whole, every +// segment from its tail up spawned on one spot 40 away and updated, hidden from queries until the end. +static void doubled_enemies_spawn(const std::vector& doubled) +{ + Game& game = *g_game; + std::vector hidden; + + for (Entity* entity : doubled) + if (contains(SEGMENTED_TYPES, entity->type)) + { + hidden.push_back(entity); + entity->AddEntityFlags(FLAG_NO_QUERY); + } + for (Entity* entity : doubled) + { + EntitySpawn spawn = {.subType = entity->subtype, .type = entity->type, .variant = entity->variant, .seed = entity->initSeed}; + Vector position = entity->pos; + Entity* copy = nullptr; + + if (entity->HasEntityFlags(FLAG_NO_QUERY)) + { + Vector direction = random_direction(); + if (entity->child) continue; + + std::vector copies; + spawn.position = vector_add(position, vector_scale(direction, SEGMENT_COPY_DISTANCE)); + for (Entity* link = entity; link && is_npc_type(link->type); link = link->parent) copies.push_back(game.Spawn(spawn)); + for (Entity* segment : copies) segment->Update(); + for (Entity* segment : copies) + { + segment->AddEntityFlags(FLAG_NO_QUERY | FLAG_AMBUSH); + hidden.push_back(segment); + } + continue; + } + if (contains(WIDE_DOUBLED_TYPES, entity->type) || entity->type == ENTITY_ISAAC) + { + Vector apart = entity->type == ENTITY_ISAAC ? vector_make(0, -ISAAC_COPY_APART) : vector_make(WIDE_COPY_APART, 0); + spawn.position = random_position_away_from_players(vector_sub(position, apart), entity->size); + copy = game.Spawn(spawn); + entity->pos = random_position_away_from_players(vector_add(position, apart), entity->size); + } + else + { + float size = entity->size; + Vector near = vector_add(position, vector_scale(random_direction(), COPY_DISTANCE)); + spawn.position = random_position_away_from_players(near, size); + copy = game.Spawn(spawn); + } + if (!copy) continue; + copy->AddEntityFlags(FLAG_AMBUSH); + copy->spawnGridIndex = entity->spawnGridIndex; + } + for (Entity* entity : hidden) entity->ClearEntityFlags(FLAG_NO_QUERY); +} + +// Part of 00802980: Damocles' pedestals split once the frame's updates ran. Every free collectible not a quest item +// marked to duplicate gets a twin: both step apart on the first pattern of offsets that keeps every pair on free +// cells, else the twin takes the nearest free spot and the original moves off to another. Options' groups stay +// grouped, each twin joining a new group shared by the twins of the same group. +static void split_pedestals_update(Room& room) +{ + Game& game = *g_game; + int cells = room.gridWidth * room.gridHeight; + std::array occupied{}; + std::vector pedestals; + std::map optionsGroups; + + g_pickupIgnoreModifiers++; + for (int i = 0; i < cells; i++) occupied[i] = room.GetGridCollision(i) != COLLISION_NONE ? -1 : 0; + for (Entity* entity : room.entityList.updateEL) + { + if (!entity || entity->type != ENTITY_PICKUP || entity->variant != PICKUP_COLLECTIBLE) continue; + auto* pickup = static_cast(entity); + int gridIndex = room.GetGridIndex(pickup->pos); + if (gridIndex >= 0) occupied[gridIndex] = 1; + if (pickup->isDead || pickup->price != 0 || !pickup->HasEntityFlags(FLAG_ITEM_SHOULD_DUPLICATE)) continue; + if (ItemConfig::is_collectible_tagged(pickup->subtype, TAG_QUEST)) continue; + + pickup->ClearEntityFlags(FLAG_ITEM_SHOULD_DUPLICATE); + pedestals.push_back(pickup); + } + + int pattern = -1; + for (int candidate = 0; candidate < (int)SPLIT_PATTERNS.size() && !pedestals.empty() && pattern < 0; candidate++) + { + std::array taken = occupied; + bool isFitting = true; + for (Entity_Pickup* pickup : pedestals) + { + int gridIndex = room.GetGridIndex(pickup->pos); + Vector center = room.GetGridPosition(gridIndex); + if (center.x != pickup->pos.x || center.y != pickup->pos.y) continue; + + auto [first, second] = SPLIT_PATTERNS[candidate]; + int column = gridIndex % room.gridWidth; + int row = gridIndex / room.gridWidth; + int firstIndex = room.GetGridIndexByTile(column + first[0], row + first[1]); + int secondIndex = room.GetGridIndexByTile(column + second[0], row + second[1]); + if (firstIndex < 0 || secondIndex < 0 || taken[firstIndex] || taken[secondIndex]) + { + isFitting = false; + break; + } + taken[firstIndex] = 1; + taken[secondIndex] = 1; + taken[gridIndex] = 0; + } + if (isFitting) pattern = candidate; + } + + for (Entity_Pickup* pickup : pedestals) + { + RNG rng = {pickup->initSeed, 3, 3, 29}; + rng.Next(); + rng.Next(); + Vector position = pickup->pos; + int gridIndex = room.GetGridIndex(position); + Vector center = room.GetGridPosition(gridIndex); + Vector moved{}; + Vector twin{}; + if (pattern < 0 || center.x != position.x || center.y != position.y) + { + moved = room_free_pickup_position_find({.position = position, .step = SPLIT_SPOT_STEP}); + int movedIndex = room.GetGridIndex(moved); + if (movedIndex >= 0 && movedIndex < ROOM_GRID_CELLS) + { + int path = room.gridPaths[movedIndex] % GRID_PATH_BAND; + if (path < GRID_PATH_FREED) room.gridPaths[movedIndex] += GRID_PATH_FREED - path; + } + twin = room_free_pickup_position_find({.position = position, .step = SPLIT_SPOT_STEP, .isAvoidActiveEntities = true}); + } + else + { + auto [first, second] = SPLIT_PATTERNS[pattern]; + moved = vector_add(position, vector_make(first[0] * GRID_CELL_SIZE, first[1] * GRID_CELL_SIZE)); + twin = vector_add(position, vector_make(second[0] * GRID_CELL_SIZE, second[1] * GRID_CELL_SIZE)); + } + if (room.roomType == ROOM_DUNGEON) + { + twin.y += DUNGEON_PEDESTAL_DROP; + moved.y += DUNGEON_PEDESTAL_DROP; + } + + auto* copy = static_cast( + game.Spawn({.position = twin, .type = pickup->type, .variant = pickup->variant, .seed = rng.Next()})); + copy->SetAlternatePedestal(pickup->GetAlternatePedestal()); + if (gridIndex >= 0) occupied[gridIndex] = 0; + for (int marked : {room.GetGridIndex(twin), room.GetGridIndex(moved)}) + if (marked >= 0) occupied[marked] = 1; + pickup->pos = moved; + pickup->targetPosition = moved; + if (pickup->optionsPickupIndex <= 0) continue; + + auto group = optionsGroups.find(pickup->optionsPickupIndex); + if (group == optionsGroups.end()) optionsGroups[pickup->optionsPickupIndex] = copy->AssignOptionsIndex(); + else copy->optionsPickupIndex = group->second; + } + g_pickupIgnoreModifiers--; + room.isItemDuplicatePending = false; +} + +// Part of 00802980: the troll bombs a sacrifice rains, one every few frames at a random free spot. +static void bomb_rain_update(Room& room) +{ + if (room.bombRainTimer <= 0) return; + + if (room.bombRainTimer % BOMB_RAIN_FRAMES == 0) + { + float width = room.bottomRightPos.x - room.topLeftPos.x; + float height = room.bottomRightPos.y - room.topLeftPos.y; + Vector center = vector_make(width * HALF + room.topLeftPos.x, height * HALF + room.topLeftPos.y); + float step = random_unit() * std::max(width, height); + Vector position = room_free_pickup_position_find({.position = center, .step = step}); + g_game->Spawn({.position = position, .type = ENTITY_BOMB, .variant = BOMB_TROLL, .seed = Random()}); + } + room.bombRainTimer--; +} + // 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 @@ -950,8 +1405,7 @@ void Room::Update() if (isInitialized && game.frameCount - enterFrame == 1) first_frame_update(); if (genesisTimer >= 0) { - if (genesisTimer == 0 && game.currentRoomIdx == ROOM_GENESIS_IDX) - reconstruction_missing("Room::Update 00802980: Genesis's items"); + if (genesisTimer == 0 && game.currentRoomIdx == ROOM_GENESIS_IDX) genesis_items_spawn(*this); genesisTimer--; } isExorcistActive = players.FirstCollectibleOwner(COLLECTIBLE_VADE_RETRO, LAZARUS_SHARE_CHECK) != nullptr; @@ -959,14 +1413,9 @@ void Room::Update() g_manager->musicManager.targetPitch = time_scale_update(); if (!temporaryEffects.isDisabled && temporaryEffects.HasNullEffect(NULL_EFFECT_POOP_CLOUD)) fxLayers.AddPoopFx(POOP_FX_COLOR); - if (descriptor->gridIndex == ROOM_LIL_PORTAL_IDX) reconstruction_missing("Room::Update 00802980: the Lil Portal room"); - - bool isEnterFrame = isInitialized && game.frameCount == enterFrame; - bool isHasEntities = !entityList.updateEL.empty(); - if (isEnterFrame && isHasEntities && game.challenge == CHALLENGE_SEEING_DOUBLE) - reconstruction_missing("Room::Update 00802980: Seeing Double's doubled enemies"); - if (isEnterFrame && players.GetGFuelCount() > 3 && isHasEntities) - reconstruction_missing("Room::Update 00802980: G-Fuel's champions"); + if (descriptor->gridIndex == ROOM_LIL_PORTAL_IDX) lil_portal_room_update(*this); + std::vector doubled; + if (isInitialized && game.frameCount == enterFrame) doubled = doubled_enemies_collect(*this); if (waterLerpColorCountdown > 0) waterLerpColorCountdown--; for (int gridIndex : pendingGridRemovals) @@ -1046,11 +1495,7 @@ void Room::Update() room_restock_partial(*this); } coupon_update(*this); - if (unknown7230 > 0) - { - if (unknown7230 % BOMB_RAIN_FRAMES == 0) reconstruction_missing("Room::Update 00802980: the troll bomb rain"); - unknown7230--; - } + bomb_rain_update(*this); if (isPickupVisionInvalid) { for (Entity* entity : entities_live(entityList.updateEL)) @@ -1061,8 +1506,8 @@ void Room::Update() } isPickupVisionInvalid = false; } - if (isUnknown7769) reconstruction_missing("Room::Update 00802980: the split collectible pedestals"); - if (DAT_00c82674 != DAT_00c82678) reconstruction_missing("Room::Update 00802980: the enemies pending a split"); + if (isItemDuplicatePending) split_pedestals_update(*this); + if (!doubled.empty()) doubled_enemies_spawn(doubled); } // Whether a source's closeness is cut at zero past its reach before it is squared, or squared as it is. @@ -1297,16 +1742,16 @@ void Room::update_ambient_sounds() sfx.SetAmbientSound(sound.soundId, volume * sound.scale, pitch); } - if (unknown72fc < 0) return; - if (++unknown72fc == ALARM_DELAY) + if (shovelQuestTimer < 0) return; + if (++shovelQuestTimer == ALARM_DELAY) { g_manager->sfxManager.Play(SOUND_ALARM); return; } - if (unknown72fc < ALARM_DELAY) return; + if (shovelQuestTimer < ALARM_DELAY) return; if (!sfx.IsPlaying(SOUND_ALARM)) { - unknown72fc = -1; + shovelQuestTimer = -1; return; } if (game.currentRoomIdx < 0) return; @@ -1317,6 +1762,6 @@ void Room::update_ambient_sounds() float columns = (float)((here / MAP_WIDTH - start / MAP_WIDTH) * MAP_WIDTH - here + start); float length = std::hypot(rows, columns); if (length > 0) columns *= 1 / length; - float fade = std::clamp((float)(unknown72fc - ALARM_DELAY) / ALARM_PAN_FRAMES, 0.0f, 1.0f); + float fade = std::clamp((float)(shovelQuestTimer - ALARM_DELAY) / ALARM_PAN_FRAMES, 0.0f, 1.0f); sfx.pan_adjust(SOUND_ALARM, fade * columns); } diff --git a/src/score_sheet.cpp b/src/score_sheet.cpp index c3bf0ab..510a306 100644 --- a/src/score_sheet.cpp +++ b/src/score_sheet.cpp @@ -191,7 +191,7 @@ void ScoreSheet::AddKilledEnemy(Entity& npc) void ScoreSheet::AddFinishedStage(const StageVisit& visit, int time) { DailyChallenge& daily = g_game->dailyChallenge; - bool isWithinDaily = daily._id == 0 || visit.stage <= g_game->GetChallengeParams().endStage; + bool isWithinDaily = daily.id == 0 || visit.stage <= g_game->GetChallengeParams().endStage; if (runTimeLevel < visit.stage && isWithinDaily) { diff --git a/src/screenshot.cpp b/src/screenshot.cpp new file mode 100644 index 0000000..628e5ed --- /dev/null +++ b/src/screenshot.cpp @@ -0,0 +1,40 @@ +#include "screenshot.h" +#include "gl.h" +#include "log.h" +#include "platform.h" +#define STB_IMAGE_WRITE_IMPLEMENTATION +#include "stb_image_write.h" +#include +#include +#include +#include +#include + +constexpr int READ_CHANNELS = 4; +constexpr int PNG_CHANNELS = 3; +constexpr const char* PNG_EXTENSION = ".png"; + +// 009e6eb0 Saves the window's pixels as an RGB PNG named under the user folder, numbering it -1, -2 ... past the +// files already there. The original reads the window's size, the framebuffer's here (the same on a plain display). +// The original throws when the file cannot open. Here it logs and saves nothing. +void save_screenshot(std::string_view name) +{ + Size size = platform.framebuffer_size_get(); + std::vector pixels((size_t)size.width * size.height * READ_CHANNELS); + std::vector rows((size_t)size.width * size.height * PNG_CHANNELS); + gl.ReadPixels(0, 0, size.width, size.height, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data()); + + for (int y = 0; y < size.height; y++) + for (int x = 0; x < size.width; x++) + { + const uint8_t* source = &pixels[((size_t)(size.height - 1 - y) * size.width + x) * READ_CHANNELS]; + std::copy_n(source, PNG_CHANNELS, &rows[((size_t)y * size.width + x) * PNG_CHANNELS]); + } + + std::string base = platform.userDataDirectory + std::string(name); + std::string path = base + PNG_EXTENSION; + for (int index = 1; std::filesystem::exists(path); index++) + path = base + "-" + std::to_string(index) + PNG_EXTENSION; + if (!stbi_write_png(path.c_str(), size.width, size.height, PNG_CHANNELS, rows.data(), size.width * PNG_CHANNELS)) + log_printf(LOG_ERROR, "Failed to write screenshot %s\n", path.c_str()); +} diff --git a/src/screenshot.h b/src/screenshot.h new file mode 100644 index 0000000..c74151a --- /dev/null +++ b/src/screenshot.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +void save_screenshot(std::string_view name); diff --git a/src/sfx_manager.h b/src/sfx_manager.h index 2b8cee6..bc32bf6 100644 --- a/src/sfx_manager.h +++ b/src/sfx_manager.h @@ -38,6 +38,8 @@ enum SoundId : int SOUND_BOSS_LITE_ROAR = 14, SOUND_BOSS_LITE_SLOPPY_ROAR = 15, SOUND_BOSS_SPIT_BLOB_BARF = 16, + SOUND_PAPER_IN = 17, + SOUND_PAPER_OUT = 18, SOUND_CHEST_DROP = 21, SOUND_CHEST_OPEN = 22, SOUND_COIN_SLOT = 24, @@ -294,6 +296,7 @@ enum SoundId : int SOUND_GFUEL_GUNSHOT_LARGE = 826, SOUND_GFUEL_GUNSHOT_SPREAD = 827, SOUND_GFUEL_AIR_HORN = 828, + SOUND_GFUEL_ITEM_APPEAR = 829, SOUND_GFUEL_GUNSHOT_MINI = 830, SOUND_GFUEL_ROCKETLAUNCHER = 832, SOUND_CRACKED_ORB = 850, @@ -455,6 +458,7 @@ enum SoundId : int SOUND_BERSERK_TICK = 593, SOUND_BERSERK_END = 594, SOUND_SHARP_PLUG = 906, + SOUND_RIB_DEFLECT = 907, SOUND_ISAAC_ROAR = 650, SOUND_ANIMA_TRAP = 611, SOUND_ANIMA_BREAK = 613, @@ -494,6 +498,7 @@ enum SoundId : int SOUND_MOTHER_LAND_SMASH = 649, SOUND_ABYSS = 834, SOUND_FLIP_POOF = 856, + SOUND_ERASER_HIT = 857, SOUND_GNAWED_LEAF_STONE = 858, SOUND_BUTTER_DROP = 901, SOUND_TICK_BURN = 911, @@ -564,6 +569,7 @@ enum SoundId : int SOUND_MINECRAFTER = 1062, SOUND_R_KEY = 904, SOUND_SUPLEX_ACTIVATE = 1030, + SOUND_SUPLEX_GRAB = 1031, SOUND_SUPLEX_JUMP = 1032, SOUND_SUPLEX_LAND = 1033, SOUND_WOODEN_NICKEL_SPAWN = 1066, @@ -622,8 +628,18 @@ enum SoundId : int SOUND_DOGMA_TV_BREAK = 567, SOUND_BEAST_DEATH = 697, SOUND_BEAST_LASER = 698, + SOUND_BEAST_FIRE_RING = 700, SOUND_BEAST_GHOST_DASH = 701, SOUND_BEAST_GHOST_RISE = 702, + SOUND_BUMBINO_DEATH = 719, + SOUND_BUMBINO_DIZZY = 720, + SOUND_BUMBINO_HIT_WALL = 721, + SOUND_BUMBINO_MISC = 722, + SOUND_BUMBINO_PUNCH = 723, + SOUND_BUMBINO_RAM = 724, + SOUND_BUMBINO_SLAM = 725, + SOUND_BUMBINO_SNAP_OUT = 726, + SOUND_BEAST_LAVA_BALL_SPLASH = 703, SOUND_BEAST_LAVA_RISE = 704, SOUND_BEAST_SUCTION_LOOP = 705, SOUND_BEAST_FIRE_BARF = 706, diff --git a/src/stage_transition.cpp b/src/stage_transition.cpp index e6fddca..24b1805 100644 --- a/src/stage_transition.cpp +++ b/src/stage_transition.cpp @@ -24,9 +24,6 @@ constexpr int EXIT_FRAME_UNSET = 1000; constexpr int MUSIC_FRAME = 2; constexpr int FIRST_ASCENT_STAGE = 1; constexpr int LAST_ASCENT_STAGE = 6; -constexpr int GRID_COLUMN_OFFSET = 40; -constexpr int GRID_ROW_OFFSET = 120; -constexpr float GRID_CELL = 40; constexpr int SOUND_ASCENT_START = 615; constexpr int ACHIEVEMENT_NO_HEARTS_STAGES = 42; @@ -152,8 +149,8 @@ void StageTransition::start(const StageTransitionRequest& request) static GridEntity* exit_trapdoor_get(const Vector& position) { Room& room = *g_game->room; - int column = (int)((position.x - GRID_COLUMN_OFFSET) / GRID_CELL + 0.5f); - int row = (int)((position.y - GRID_ROW_OFFSET) / GRID_CELL + 0.5f); + 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); if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return nullptr; uint32_t index = (uint32_t)(row * room.gridWidth + column); diff --git a/src/stat_hud.cpp b/src/stat_hud.cpp index d134e95..c48c36f 100644 --- a/src/stat_hud.cpp +++ b/src/stat_hud.cpp @@ -60,6 +60,20 @@ void StatTracker::set(float newValue, bool isAnimated) value = newValue; } +// A player's speed, tears per second, damage, range in tiles, shot speed or luck, as the stats show them. +float player_stat_get(Entity_Player& player, StatHudStat stat) +{ + switch (stat) + { + case STAT_SPEED: return player.moveSpeed; + case STAT_TEARS: return TEARS_PER_SECOND / (player.maxFireDelay + 1); + case STAT_DAMAGE: return player.damage; + case STAT_RANGE: return player.tearRange / RANGE_UNIT; + case STAT_SHOT_SPEED: return player.shotSpeed; + default: return player.luck; + } +} + // 0084bfd0 Forgets both players' stats. The deal and planetarium chances only show changes of a tenth. void StatHUD::reset() { @@ -124,12 +138,8 @@ void StatHUD::RecomputeStats(int playerId, uint32_t flags) std::array& stats = players[playerId].stats; bool isAnimated = game.frameCount - player.spawnFrame > 1; - if (flags & STAT_FLAG_SPEED) stats[STAT_SPEED].set(player.moveSpeed, isAnimated); - if (flags & STAT_FLAG_TEARS) stats[STAT_TEARS].set(TEARS_PER_SECOND / (player.maxFireDelay + 1), isAnimated); - if (flags & STAT_FLAG_DAMAGE) stats[STAT_DAMAGE].set(player.damage, isAnimated); - if (flags & STAT_FLAG_RANGE) stats[STAT_RANGE].set(player.tearRange / RANGE_UNIT, isAnimated); - if (flags & STAT_FLAG_SHOT_SPEED) stats[STAT_SHOT_SPEED].set(player.shotSpeed, isAnimated); - if (flags & STAT_FLAG_LUCK) stats[STAT_LUCK].set(player.luck, isAnimated); + for (int stat = STAT_SPEED; stat <= STAT_LUCK; stat++) + if (flags & (1u << stat)) stats[stat].set(player_stat_get(player, (StatHudStat)stat), isAnimated); if (flags & (STAT_FLAG_DEVIL_CHANCE | STAT_FLAG_ANGEL_CHANCE)) { float dealChance = std::clamp(game.room->GetDevilRoomChance(), 0.0f, 1.0f); diff --git a/src/stat_hud.h b/src/stat_hud.h index 87a694c..593b35f 100644 --- a/src/stat_hud.h +++ b/src/stat_hud.h @@ -75,3 +75,5 @@ struct StatHUD void RecomputeStats(int playerId, uint32_t flags); void update_player(Entity_Player* oldPlayer, Entity_Player* newPlayer); }; + +float player_stat_get(Entity_Player& player, StatHudStat stat); diff --git a/src/weapon.h b/src/weapon.h index 9ab97a2..5e67ff4 100644 --- a/src/weapon.h +++ b/src/weapon.h @@ -307,10 +307,12 @@ struct Weapon_Tears : Weapon 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. +// Tech.5 fires one laser in twenty with a single random flag of the first 84, which only the first 64 (the flags' +// low word, as the original shifts it) can be: a draw past them gives the laser no flag. constexpr int TECH5_FLAG_CHANCE = 5; constexpr int TECH5_FLAG_ROLL = 100; constexpr int TECH5_FLAG_COUNT = 84; +constexpr uint32_t TECH5_FLAG_REACH = 64; WeaponPtr weapon_create(WeaponType type, Entity* owner); float shot_alpha_get(Entity_Player* player); diff --git a/src/weapon_lasers.cpp b/src/weapon_lasers.cpp index d57d4eb..44458f6 100644 --- a/src/weapon_lasers.cpp +++ b/src/weapon_lasers.cpp @@ -27,13 +27,27 @@ 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; constexpr int LASER_SHOTS_PER_FRAME = 8; + +// The charging Technology: a pee burst releases at five frames of charge, a release keeps a little charge, Marked's aim +// stops the charge between 50 and 300 away, Cursed Eye charges up to five lasers, Chocolate Milk scales a release's +// damage up to four times (Monstro's Lung's up to two and a half, sprayed as twelve lasers). +constexpr float PEE_BURST_CHARGE = 5; +constexpr float RELEASE_CHARGE_MIN = 1e-05f; +constexpr float MARKED_NEAR = 50; +constexpr float MARKED_RANGE = 250; +constexpr int CURSED_EYE_LASERS = 5; +constexpr int CHARGE_BLINK = 8; +constexpr float CHOCOLATE_SCALE_MIN = 0.1f; +constexpr float CHOCOLATE_SCALE_MAX = 4; +constexpr float LUNG_CHOCOLATE_SCALE_MIN = 0.02f; +constexpr float LUNG_CHOCOLATE_SCALE_MAX = 2.5f; +constexpr int LUNG_LASER_SPRAY = 12; constexpr float SPRAY_REACH = 70; constexpr float SPRAY_SCATTER = 50; constexpr float LUNG_SPRAY_SCALE_STEP = 0.4f; @@ -561,24 +575,190 @@ void Weapon_Laser::ludovico_ring_update(const Vector& shootDirection, bool isSho 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 -// not reconstructed yet. +// Part of 00a052b0: one volley of Technology's lasers along an aim, carrying a share of the owner's movement unless a +// Tractor Beam holds them, with the volley's extra backward, sideways and random lasers. Chocolate Milk's release scales +// their damage by its charge, and Monstro's Lung sprays twelve (fewer, each stronger, for a weak Chocolate Milk +// release). The aim they leave along. +Vector Weapon_Laser::volley_fire(Vector aim) +{ + bool isChocolate = modifiers & WEAPON_MOD_CHOCOLATE_MILK; + bool isLung = modifiers & WEAPON_MOD_MONSTROS_LUNG; + bool isTractorBeam = modifiers & WEAPON_MOD_TRACTOR_BEAM; + if (isLung) UpdateHeadChargeAnimation(COLLECTIBLE_MONSTROS_LUNG, HEAD_CHARGE_SHOOT, aim, -1); + Vector velocity = vector_scale(aim, LASER_AIM_SPEED); + if (!isTractorBeam) velocity = vector_add(velocity, vector_scale(get_tear_movement_inheritance(aim), LASER_INHERIT_SCALE)); + aim = vector_normalized(velocity); + SetBlinkTime(LASER_BLINK_BASE - (int)(maxFireDelay * LASER_BLINK_SCALE)); + TriggerTearEffects(aim, 1); + Weapon_MultiShotParams params = GetMultiShotParams(); + + float maxCharge = GetMaxCharge() * ((modifiers & WEAPON_MOD_CURSED_EYE) ? HALF : 1); + float damageScale = 1; + int sprayCount = isLung ? LUNG_LASER_SPRAY : 0; + if (isChocolate) + { + float ratio = (chargeAtRelease + 1) * (isLung ? LUNG_CHOCOLATE_SCALE_MAX : CHOCOLATE_SCALE_MAX) / (maxCharge + 1); + damageScale = isLung ? std::clamp(ratio, LUNG_CHOCOLATE_SCALE_MIN, LUNG_CHOCOLATE_SCALE_MAX) + : std::clamp(ratio, CHOCOLATE_SCALE_MIN, CHOCOLATE_SCALE_MAX); + } + if (isLung && damageScale < 1) + { + float spray = (float)sprayCount; + sprayCount = std::max((int)(float)std::ceil((double)(spray * damageScale)), 1); + damageScale *= spray / (float)sprayCount; + } + + LaserVolley volley = {.direction = aim, + .position = get_owner_position(), + .params = ¶ms, + .damageScale = damageScale, + .offsetId = isLung ? LASER_OFFSET_TRACTOR_BEAM : LASER_OFFSET_TECH1, + .sprayCount = sprayCount}; + std::vector fired = fire_lasers(volley); + volley.params = nullptr; + volley.offsetId = LASER_OFFSET_MOMS_EYE; + auto fire_more = [&](Vector extra) { + volley.direction = extra; + std::vector more = fire_lasers(volley); + fired.insert(fired.end(), more.begin(), more.end()); + }; + if (params.isShootingBackwards) fire_more(vector_make(-aim.x, -aim.y)); + if (params.isShootingSideways) + { + fire_more(vector_make(aim.y, -aim.x)); + fire_more(vector_make(-aim.y, aim.x)); + } + for (int i = 0; i < params.numRandomDirTears; i++) fire_more(random_direction()); + for (Entity_Laser* laser : fired) + { + laser->isDisableFollowParent = !isTractorBeam; + laser->Update(); + } + return aim; +} + +// Part of 00a052b0: holding fire charges Chocolate Milk and Monstro's Lung (their heads turning with the charge, full +// at the weapon's charge) and Cursed Eye (its laser count growing to five with it). Letting go drains a Cursed Eye +// laser, stops the charge and the head's item animations (a familiar's cooldown instead). +void Weapon_Laser::charge_update(bool isFiring, const Vector& aim) +{ + bool isChocolateOrLung = modifiers & (WEAPON_MOD_CHOCOLATE_MILK | WEAPON_MOD_MONSTROS_LUNG); + if (!isFiring) + { + if (cursedEyeCharges > 0) cursedEyeCharges--; + charge = 0; + if ((modifiers & WEAPON_MOD_MONSTROS_LUNG) && !IsItemAnimFinished(COLLECTIBLE_MONSTROS_LUNG)) return; + if (owner && owner->type == ENTITY_FAMILIAR) static_cast(owner)->fireCooldown = 0; + else if (owner && owner->type == ENTITY_PLAYER) owner->ToPlayer()->stop_costume_item_anims(); + return; + } + + float gain = owner ? owner->speedMultiplier : 1; + float newCharge = charge; + if (isChocolateOrLung) + { + float maxCharge = GetMaxCharge() * ((modifiers & WEAPON_MOD_CURSED_EYE) ? HALF : 1); + bool isFull = maxCharge <= charge; + float frame = isFull ? -1 : charge / maxCharge * HEAD_CHARGE_FRAMES; + UpdateHeadChargeAnimation(COLLECTIBLE_MONSTROS_LUNG, isFull ? HEAD_CHARGE_CHARGED : HEAD_CHARGE_CHARGING, aim, frame); + UpdateHeadChargeAnimation(COLLECTIBLE_TECHNOLOGY, isFull ? HEAD_CHARGE_CHARGED : HEAD_CHARGE_CHARGING, aim, frame); + if (!isFull) newCharge = gain + charge; + SetBlinkTime(CHARGE_BLINK); + } + if (modifiers & WEAPON_MOD_CURSED_EYE) + { + float maxCharge = GetMaxCharge(); + if (maxCharge <= charge) + { + UpdateHeadChargeAnimation(COLLECTIBLE_TECHNOLOGY, HEAD_CHARGE_CHARGED, aim, -1); + UpdateHeadChargeAnimation(COLLECTIBLE_CURSED_EYE, HEAD_CHARGE_CHARGED, aim, -1); + } + else + { + if (owner) + { + float frame = charge / maxCharge * HEAD_CHARGE_FRAMES; + if (owner->type == ENTITY_PLAYER) + { + UpdateHeadChargeAnimation(COLLECTIBLE_TECHNOLOGY, HEAD_CHARGE_CHARGING, aim, frame); + frame = 0; + } + UpdateHeadChargeAnimation(COLLECTIBLE_CURSED_EYE, HEAD_CHARGE_CHARGING, aim, frame); + } + newCharge = gain + charge; + } + SetBlinkTime(1); + cursedEyeCharges = (int)((newCharge + 1) * CURSED_EYE_LASERS / (maxCharge + 1)); + } + charge = newCharge; + chargeAtRelease = newCharge; +} + +// 00a052b0 Fires Technology's lasers: one volley per fire delay passed this frame (at most eight). Chocolate Milk and +// Monstro's Lung charge while held and fire one volley on release, Cursed Eye fires one volley per laser charged. A +// pee burst or a full charge releases at once, and with Marked's or a fixed aim the charge stops by the distance. +// Ludovico steers a laser ring instead. Only the charging weapons keep their last aim. void Weapon_Laser::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) { Weapon::Fire(shootDirection, isShooting, isInterpolated); 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)"); - int shots = 0; - if (isShooting) + bool isChocolate = modifiers & WEAPON_MOD_CHOCOLATE_MILK; + bool isCursedEye = modifiers & WEAPON_MOD_CURSED_EYE; + bool isLung = modifiers & WEAPON_MOD_MONSTROS_LUNG; + bool isCharged = isChocolate || isCursedEye || isLung; + Entity_Player* player = weapon_player(owner); + bool isMarkable = player && (player->HasCollectible(COLLECTIBLE_MARKED) || + player->HasCollectible(COLLECTIBLE_EYE_OF_THE_OCCULT)); + bool isReady = (modifiers & WEAPON_MOD_SOY_MILK) || !(maxFireDelay > 0); + float maxCharge = GetMaxCharge() * (isCursedEye ? HALF : 1); + bool isFiring = isShooting; + if (owner && owner->type == ENTITY_PLAYER && owner->ToPlayer()->peeBurstCooldown > 0) + { + if ((isLung || isChocolate) && charge >= std::min(maxCharge, PEE_BURST_CHARGE)) isFiring = false; + else if (isCursedEye && cursedEyeCharges > 0) isFiring = false; + } + if (!isInterpolated && isFiring && isReady) + { + bool isEyeFull = charge > 0 ? cursedEyeCharges >= CURSED_EYE_LASERS : cursedEyeCharges > 0; + if (((isLung || isChocolate) && charge >= maxCharge) || (isCursedEye && isEyeFull)) + { + isFiring = false; + charge = std::max(charge, RELEASE_CHARGE_MIN); + chargeAtRelease = charge; + } + } + + Entity* marked = player ? player->markedTarget.get() : nullptr; + Vector target = marked && isMarkable ? marked->pos : fixedDirection; + if (!isInterpolated && isFiring && !vector_is_zero(target)) + { + float distance = vector_length(vector_sub(target, get_owner_position())); + float share = std::clamp((distance - MARKED_NEAR) / MARKED_RANGE, 0.0f, 1.0f); + int lasers = charge > 0 ? (int)(share * (CURSED_EYE_LASERS - 1) + 1) : 1; + bool isChocolateDone = isChocolate && charge > ((maxCharge - PEE_BURST_CHARGE) * share + PEE_BURST_CHARGE) - 1; + if (isChocolateDone || (isLung && charge > maxCharge) || (isCursedEye && cursedEyeCharges >= lasers)) + isFiring = false; + } + + int volleys = 0; + if (isCharged) + { + bool isRelease = !isFiring && ((isChocolate && charge > 0) || (isLung && charge >= maxCharge) || + (isCursedEye && cursedEyeCharges > 0)); + if (isInterpolated) + { + if (isRelease) SetBlinkTime(1); + return; + } + volleys = isRelease; + } + else if (isFiring) { if (isInterpolated) return; - while (fireDelay < 0 && shots < LASER_SHOTS_PER_FRAME) + while (fireDelay < 0 && volleys < LASER_SHOTS_PER_FRAME) { - shots++; + volleys++; fireDelay += maxFireDelay + 1; } chargeAtRelease = 0; @@ -586,40 +766,10 @@ void Weapon_Laser::Fire(const Vector& shootDirection, bool isShooting, bool isIn Vector aim = isShooting ? shootDirection : direction; aim = IsAxisAligned() ? vector_cardinal(aim) : vector_normalized(aim); - if (shots > 0) - { - bool isTractorBeam = modifiers & WEAPON_MOD_TRACTOR_BEAM; - Vector velocity = vector_scale(aim, LASER_AIM_SPEED); - if (!isTractorBeam) - velocity = vector_add(velocity, vector_scale(get_tear_movement_inheritance(aim), LASER_INHERIT_SCALE)); - aim = vector_normalized(velocity); - SetBlinkTime(LASER_BLINK_BASE - (int)(maxFireDelay * LASER_BLINK_SCALE)); - TriggerTearEffects(aim, 1); - - Weapon_MultiShotParams params = GetMultiShotParams(); - LaserVolley volley = {.direction = aim, .position = get_owner_position(), .params = ¶ms}; - std::vector fired = fire_lasers(volley); - volley.params = nullptr; - volley.offsetId = LASER_OFFSET_MOMS_EYE; - auto fire_more = [&](Vector extra) { - volley.direction = extra; - std::vector more = fire_lasers(volley); - fired.insert(fired.end(), more.begin(), more.end()); - }; - if (params.isShootingBackwards) fire_more(vector_make(-aim.x, -aim.y)); - if (params.isShootingSideways) - { - fire_more(vector_make(aim.y, -aim.x)); - fire_more(vector_make(-aim.y, aim.x)); - } - for (int i = 0; i < params.numRandomDirTears; i++) fire_more(random_direction()); - for (Entity_Laser* laser : fired) - { - laser->isDisableFollowParent = !isTractorBeam; - laser->Update(); - } - } + if (volleys > 0) aim = volley_fire(aim); + if (!isCharged) return; + charge_update(isFiring, aim); if (isShooting) direction = IsAxisAligned() ? aim : get_aim_direction(aim); } diff --git a/src/weapon_lasers.h b/src/weapon_lasers.h index 262b6cd..1defce5 100644 --- a/src/weapon_lasers.h +++ b/src/weapon_lasers.h @@ -35,6 +35,8 @@ 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); + Vector volley_fire(Vector aim); + void charge_update(bool isFiring, const Vector& aim); }; struct BrimstoneAim; diff --git a/src/weapon_monstros_lung.cpp b/src/weapon_monstros_lung.cpp index 763de33..f93a653 100644 --- a/src/weapon_monstros_lung.cpp +++ b/src/weapon_monstros_lung.cpp @@ -116,7 +116,11 @@ void Weapon_MonstrosLung::FireBurst(const Vector& velocity, int count, float dam Entity_Tear* tear = fire_tear({from, shot}, 0, damageMultiplier, 0); if (g_game->deathmatchManager.is_active()) - reconstruction_missing("Weapon_MonstrosLung::FireBurst 00a08700 (versus tears)"); + { + TearFlags flags = tear->tearFlags; + flags.set(TEAR_THROUGH_COOLDOWN); + tear->SetTearFlags(flags); + } if (player && player->tearFallingAcceleration > 0) tear->fallingSpeed = random_unit() * COUGH_LIFT_FALLING - tear->fallingSpeed; else if (player)