diff --git a/Buffs/DamageOverTime/HadopelagicPressure.cs b/Buffs/DamageOverTime/HadopelagicPressure.cs new file mode 100644 index 0000000000..f4edd97b85 --- /dev/null +++ b/Buffs/DamageOverTime/HadopelagicPressure.cs @@ -0,0 +1,86 @@ +using CalamityMod.Particles; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Buffs.DamageOverTime +{ + public class HadopelagicPressure : ModBuff + { + public override void SetStaticDefaults() + { + Main.debuff[Type] = true; + Main.pvpBuff[Type] = true; + Main.buffNoSave[Type] = true; + BuffID.Sets.LongerExpertDebuff[Type] = true; + } + + public override void Update(Player player, ref int buffIndex) + { + player.Calamity().hPressure = true; + } + + public override void Update(NPC npc, ref int buffIndex) + { + if (npc.Calamity().hPressure < npc.buffTime[buffIndex]) + npc.Calamity().hPressure = npc.buffTime[buffIndex]; + npc.DelBuff(buffIndex); + buffIndex--; + } + + internal static void DrawEffects(PlayerDrawSet drawInfo) + { + Player Player = drawInfo.drawPlayer; + // Blue n black dust + Dust water = Dust.NewDustDirect(drawInfo.Position - new Vector2(2f), Player.width + 4, Player.height + 4, 390, Player.velocity.X * 0.4f, Player.velocity.Y * 0.4f, 100, default, 1.4f); + water.noGravity = true; + water.velocity *= 0.75f; + water.velocity.X *= 0.75f; + water.velocity.Y -= 1f; + if (Main.rand.NextBool(4)) + { + water.noGravity = false; + water.scale *= 0.5f; + } + if (Main.rand.NextBool(4)) + { + DirectionalPulseRing pulse = new DirectionalPulseRing(Player.Calamity().RandomDebuffVisualSpot, new Vector2(Main.rand.NextFloat(-1f, 1f), Main.rand.NextFloat(-3f, -4f)), Main.rand.NextBool() ? Color.DeepSkyBlue : Color.MediumBlue, new Vector2(0.8f, 1), 0, 0.09f, 0f, 45); + GeneralParticleHandler.SpawnParticle(pulse); + } + if (Main.rand.NextBool(10)) + { + Color smokeColor = Color.MediumBlue; + Particle smoke = new HeavySmokeParticle(Player.Calamity().RandomDebuffVisualSpot, new Vector2(2f, 2f).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 0.7f), smokeColor, 40, Main.rand.NextFloat(0.3f, 0.4f), 0.5f, Main.rand.NextFloat(-0.2f, 0.2f), false, required: true); + GeneralParticleHandler.SpawnParticle(smoke); + } + } + + internal static void DrawEffects(NPC npc, ref Color drawColor) + { + Vector2 npcSize = npc.Center + new Vector2(Main.rand.NextFloat(-npc.width / 2, npc.width / 2), Main.rand.NextFloat(-npc.height / 2, npc.height / 2)); + if (Main.rand.NextBool(13)) + { + Color smokeColor = Color.MediumBlue; + Particle smoke = new HeavySmokeParticle(npcSize, new Vector2(2f, 2f).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 0.7f), smokeColor, 40, Main.rand.NextFloat(0.3f, 0.4f) + (0.00000013f * npc.width * npc.height), 0.5f, Main.rand.NextFloat(-0.2f, 0.2f), false, required: true); + GeneralParticleHandler.SpawnParticle(smoke); + } + Dust water = Dust.NewDustDirect(npc.position - new Vector2(2f), npc.width + 4, npc.height + 4, 360, npc.velocity.X * 0.4f, npc.velocity.Y * 0.4f, 100, default, 1.4f); + water.noGravity = true; + water.velocity *= 0.75f; + water.velocity.X = water.velocity.X * 0.75f; + water.velocity.Y = water.velocity.Y - 1f; + if (Main.rand.NextBool(4)) + { + water.noGravity = false; + water.scale *= 0.5f; + } + if (Main.rand.NextBool(6)) + { + DirectionalPulseRing pulse = new DirectionalPulseRing(npcSize, new Vector2(Main.rand.NextFloat(-1f, 1f), Main.rand.NextFloat(-4.5f, -6f)), Main.rand.NextBool() ? Color.DeepSkyBlue : Color.MediumBlue, new Vector2(1f), 0, 0.12f + (0.0000007f * npc.width * npc.height), 0f, 35); + GeneralParticleHandler.SpawnParticle(pulse); + } + } + } +} diff --git a/Buffs/DamageOverTime/HadopelagicPressure.png b/Buffs/DamageOverTime/HadopelagicPressure.png new file mode 100644 index 0000000000..ac56060a69 Binary files /dev/null and b/Buffs/DamageOverTime/HadopelagicPressure.png differ diff --git a/CalPlayer/CalamityPlayer.cs b/CalPlayer/CalamityPlayer.cs index f9a27a9264..2e0f5774db 100644 --- a/CalPlayer/CalamityPlayer.cs +++ b/CalPlayer/CalamityPlayer.cs @@ -4,6 +4,9 @@ using System.Linq; using CalamityMod.Balancing; using CalamityMod.BiomeManagers; using CalamityMod.Buffs; +using CalamityMod.Buffs.Alcohol; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Buffs.Placeables; using CalamityMod.Buffs.StatBuffs; using CalamityMod.Buffs.StatDebuffs; using CalamityMod.CalPlayer.Dashes; @@ -1227,6 +1230,7 @@ namespace CalamityMod.CalPlayer public bool warped = false; public bool cDepth = false; public bool rTide = false; + public bool hPressure = false; public bool fishAlert = false; public bool clamity = false; public bool NOU = false; @@ -2415,6 +2419,7 @@ namespace CalamityMod.CalPlayer warped = false; cDepth = false; rTide = false; + hPressure = false; fishAlert = false; clamity = false; NOU = false; @@ -2870,6 +2875,7 @@ namespace CalamityMod.CalPlayer warped = false; cDepth = false; rTide = false; + hPressure = false; fishAlert = false; clamity = false; NOU = false; diff --git a/CalPlayer/CalamityPlayerDrawEffects.cs b/CalPlayer/CalamityPlayerDrawEffects.cs index ffc4fe25bf..eaaeda1189 100644 --- a/CalPlayer/CalamityPlayerDrawEffects.cs +++ b/CalPlayer/CalamityPlayerDrawEffects.cs @@ -263,6 +263,9 @@ namespace CalamityMod.CalPlayer if (drawInfo.shadow == 0f && (calamityPlayer.hFlames || calamityPlayer.hInferno || calamityPlayer.banishingFire)) HolyFlames.DrawEffects(drawInfo); + if (calamityPlayer.hPressure && drawInfo.shadow == 0f) + HadopelagicPressure.DrawEffects(drawInfo); + // Icarus' Folly has visual effects but they are mutually exclusive with all Holy Flames variations to prevent visual clutter else if (calamityPlayer.icarusFolly && drawInfo.shadow == 0f) IcarusFolly.DrawEffects(drawInfo); @@ -280,9 +283,6 @@ namespace CalamityMod.CalPlayer if (calamityPlayer.nightwither && drawInfo.shadow == 0f) // Looks weaker if you have Moon Stone equipped Nightwither.DrawEffects(drawInfo, reducedNightwitherDamage); - if (calamityPlayer.voidfrost && drawInfo.shadow == 0f) - Voidfrost.DrawEffects(drawInfo); - if (calamityPlayer.pFlames && drawInfo.shadow == 0f) Plague.DrawEffects(drawInfo); @@ -311,6 +311,9 @@ namespace CalamityMod.CalPlayer if (calamityPlayer.vermillionFlux && drawInfo.shadow == 0f) VermillionFlux.DrawEffects(drawInfo); + if (calamityPlayer.voidfrost && drawInfo.shadow == 0f) + Voidfrost.DrawEffects(drawInfo); + if (calamityPlayer.vHex && drawInfo.shadow == 0f) VulnerabilityHex.DrawEffects(drawInfo); #endregion diff --git a/CalPlayer/CalamityPlayerHitHurt.cs b/CalPlayer/CalamityPlayerHitHurt.cs index 7847878bba..2ef0997336 100644 --- a/CalPlayer/CalamityPlayerHitHurt.cs +++ b/CalPlayer/CalamityPlayerHitHurt.cs @@ -451,6 +451,10 @@ namespace CalamityMod.CalPlayer { damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.Riptide" + Main.rand.Next(1, 2 + 1)).Format(Player.name)); } + if (hPressure) + { + damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.HadopelagicPressure" + Main.rand.Next(1, 3 + 1)).Format(Player.name)); + } if (bFlames || weakBrimstoneFlames || demonicFlames) { damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.BrimstoneFlames" + Main.rand.Next(1, 3 + 1)).Format(Player.name)); diff --git a/CalPlayer/CalamityPlayerLifeRegen.cs b/CalPlayer/CalamityPlayerLifeRegen.cs index cee57ec0a2..5a65730151 100644 --- a/CalPlayer/CalamityPlayerLifeRegen.cs +++ b/CalPlayer/CalamityPlayerLifeRegen.cs @@ -120,6 +120,7 @@ namespace CalamityMod.CalPlayer ApplyDoTDebuff(trueVHex, 50); ApplyDoTDebuff(cDepth, 18, purity); ApplyDoTDebuff(astralInfection, 24, infectedJewel || hideOfDeus || purity); + ApplyDoTDebuff(hPressure, 40, purity); ApplyDoTDebuff(pFlames, alchFlask ? 10 : 30, purity); ApplyDoTDebuff(cragsLava, 30); ApplyDoTDebuff(shadowflame, 30, purity); diff --git a/CalPlayer/CalamityPlayerMiscEffects.cs b/CalPlayer/CalamityPlayerMiscEffects.cs index d0b0ee94de..4cb915bd96 100644 --- a/CalPlayer/CalamityPlayerMiscEffects.cs +++ b/CalPlayer/CalamityPlayerMiscEffects.cs @@ -2816,16 +2816,23 @@ namespace CalamityMod.CalPlayer // Record the final breath loss rate for the stat meter abyssBreathLossRateStat = (float)tick; + float resistanceSlowdownFactor = 1f; + // Reduce breath over ticks (frames) - abyssBreathCD++; - if (abyssBreathCD >= (int)tick) + abyssBreathCD++; + if (abyssBreathCD >= (int)(tick * resistanceSlowdownFactor)) { // Reset modded breath variable abyssBreathCD = 0; // Reduce breath if (Player.breath > 0) + { Player.breath -= (int)(cDepth && !depthCharm ? breathLoss + 1D : breathLoss); + + if (hPressure) + resistanceSlowdownFactor -= (int)(!abyssalDivingSuit ? 1.2f : 0.5f); + } } // If breath is greater than 0 and player has gills or is merfolk, balance out the effects by reducing breath diff --git a/CalPlayer/CalamityPlayerOnHit.cs b/CalPlayer/CalamityPlayerOnHit.cs index 27c09e4e8c..37c7f8800c 100644 --- a/CalPlayer/CalamityPlayerOnHit.cs +++ b/CalPlayer/CalamityPlayerOnHit.cs @@ -1191,7 +1191,7 @@ namespace CalamityMod.CalPlayer if (frostFlare) CalamityUtils.Inflict246DebuffsNPC(target, BuffID.Frostburn2); if (omegaBlueChestplate) - target.AddBuff(BuffType(), 180); + target.AddBuff(BuffType(), 180); if (sulphurSet) target.AddBuff(BuffID.Poisoned, 60); if (aSpark && Player.IsUnderwater()) diff --git a/Localization/en-US/Mods.CalamityMod.Buffs.hjson b/Localization/en-US/Mods.CalamityMod.Buffs.hjson index f7c4ad38cc..a14bf4da75 100644 --- a/Localization/en-US/Mods.CalamityMod.Buffs.hjson +++ b/Localization/en-US/Mods.CalamityMod.Buffs.hjson @@ -1008,6 +1008,11 @@ GlacialState: { Description: Cannot move } +HadopelagicPressure: { + DisplayName: Hadopelagic Pressure + Description: Rapidly sinking to a watery grave +} + IcarusFolly: { DisplayName: Icarus' Folly Description: diff --git a/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson b/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson index d6ab009289..2382dca290 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson @@ -34,6 +34,7 @@ AbyssalDivingSuit: { Provides a moderate amount of light and reduces breath loss in the abyss Abyss creatures are less likely to see you, mitigates the abyss' defense reduction, and lets you sink faster in liquids Grants immunity to the sulphurous waters and Crush Depth's increased breath loss + Grants resistance to the increased breath loss caused by Hadopelagic Pressure ''' } diff --git a/Localization/en-US/Mods.CalamityMod.Items.Armor.PostMoonLord.hjson b/Localization/en-US/Mods.CalamityMod.Items.Armor.PostMoonLord.hjson index 360e51e89a..f94a0fd15a 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Armor.PostMoonLord.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Armor.PostMoonLord.hjson @@ -369,7 +369,7 @@ OmegaBlueChestplate: { Tooltip: ''' 12% increased damage and 8% increased critical strike chance - Your attacks inflict Crush Depth + Your attacks inflict Hadopelagic Pressure No positive life regen ''' } diff --git a/Localization/en-US/Mods.CalamityMod.Status.Death.hjson b/Localization/en-US/Mods.CalamityMod.Status.Death.hjson index af5aea506a..472bb07020 100644 --- a/Localization/en-US/Mods.CalamityMod.Status.Death.hjson +++ b/Localization/en-US/Mods.CalamityMod.Status.Death.hjson @@ -52,6 +52,9 @@ CorpusAvertor: "{0} became the Blood God's sacrifice." CrushDepth1: "{0} was crushed by the pressure." CrushDepth2: "{0}'s lungs collapsed." CrushDepth3: "{0}'s bones crunched under the deep pressure." +HadopelagicPressure1: "{0} was crushed in the lightless void." +HadopelagicPressure2: "{0} was reduced to a smear of waterlogged paste." +HadopelagicPressure3: "{0} suffered a critical pressurization event." Daybroken: "{0} was incinerated by solar rays." Dragonfire1: "{0}'s ashes scatter in the wind." Dragonfire2: "{0}'s embers fade away in a warm glow." diff --git a/NPCs/Abyss/BobbitWormHead.cs b/NPCs/Abyss/BobbitWormHead.cs index d60cbe1b33..b9218ec8df 100644 --- a/NPCs/Abyss/BobbitWormHead.cs +++ b/NPCs/Abyss/BobbitWormHead.cs @@ -256,7 +256,7 @@ namespace CalamityMod.NPCs.Abyss public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 300, true); + target.AddBuff(ModContent.BuffType(), 300, true); } public override void ModifyNPCLoot(NPCLoot npcLoot) diff --git a/NPCs/Abyss/ColossalSquid.cs b/NPCs/Abyss/ColossalSquid.cs index 77b717aaf5..2b7e4564fa 100644 --- a/NPCs/Abyss/ColossalSquid.cs +++ b/NPCs/Abyss/ColossalSquid.cs @@ -624,7 +624,7 @@ namespace CalamityMod.NPCs.Abyss public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 300, true); + target.AddBuff(ModContent.BuffType(), 300, true); } public override void ModifyNPCLoot(NPCLoot npcLoot) diff --git a/NPCs/Abyss/EidolonWyrmHead.cs b/NPCs/Abyss/EidolonWyrmHead.cs index 5db9631938..3ad3252016 100644 --- a/NPCs/Abyss/EidolonWyrmHead.cs +++ b/NPCs/Abyss/EidolonWyrmHead.cs @@ -512,7 +512,7 @@ namespace CalamityMod.NPCs.Abyss public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 300, true); + target.AddBuff(ModContent.BuffType(), 300, true); } } } diff --git a/NPCs/Abyss/OarfishHead.cs b/NPCs/Abyss/OarfishHead.cs index 82664b5438..c59d64fa26 100644 --- a/NPCs/Abyss/OarfishHead.cs +++ b/NPCs/Abyss/OarfishHead.cs @@ -364,7 +364,7 @@ namespace CalamityMod.NPCs.Abyss public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 90); + target.AddBuff(ModContent.BuffType(), 90); } public override bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) diff --git a/NPCs/Abyss/ReaperShark.cs b/NPCs/Abyss/ReaperShark.cs index 688511587b..0eed46ccb3 100644 --- a/NPCs/Abyss/ReaperShark.cs +++ b/NPCs/Abyss/ReaperShark.cs @@ -709,7 +709,7 @@ namespace CalamityMod.NPCs.Abyss public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 300, true); + target.AddBuff(ModContent.BuffType(), 300, true); } public override float SpawnChance(NPCSpawnInfo spawnInfo) diff --git a/NPCs/CalamityGlobalNPC.cs b/NPCs/CalamityGlobalNPC.cs index b9fdaa6c2f..c08906126d 100644 --- a/NPCs/CalamityGlobalNPC.cs +++ b/NPCs/CalamityGlobalNPC.cs @@ -359,6 +359,7 @@ namespace CalamityMod.NPCs public int cDepth = 0; public int rTide = 0; + public int hPressure = 0; public int gsInferno = 0; public int dragonFire = 0; public int vermillionFlux = 0; @@ -610,6 +611,7 @@ namespace CalamityMod.NPCs myClone.cDepth = cDepth; myClone.rTide = rTide; + myClone.hPressure = hPressure; myClone.gsInferno = gsInferno; myClone.miracleBlight = miracleBlight; myClone.dragonFire = dragonFire; @@ -1272,6 +1274,13 @@ namespace CalamityMod.NPCs int baseCrushDepthDoTValue = (int)(100 * waterDamageMult); ApplyDPSDebuff(baseCrushDepthDoTValue, baseCrushDepthDoTValue / 2, ref npc.lifeRegen, ref damage); } + + //Hadopelagic Pressure + if (hPressure > 0) + { + int baseHadopelagicPressureDoTValue = (int)(400 * waterDamageMult); + ApplyDPSDebuff(baseHadopelagicPressureDoTValue, baseHadopelagicPressureDoTValue / 2, ref npc.lifeRegen, ref damage); + } #endregion if (npc.dryadBane) @@ -5639,6 +5648,8 @@ namespace CalamityMod.NPCs crumble--; if (cDepth > 0) cDepth--; + if (hPressure > 0) + hPressure--; if (rTide > 0) rTide--; if (gsInferno > 0) @@ -7198,6 +7209,9 @@ namespace CalamityMod.NPCs if (cDepth > 0) CrushDepth.DrawEffects(npc, ref drawColor); + if (hPressure > 0) + HadopelagicPressure.DrawEffects(npc, ref drawColor); + if (dragonFire > 0) Dragonfire.DrawEffects(npc, ref drawColor); @@ -7414,6 +7428,7 @@ namespace CalamityMod.NPCs ("CalamityMod/Buffs/DamageOverTime/Dragonfire", NPC => NPC.Calamity().dragonFire > 0), ("CalamityMod/Buffs/DamageOverTime/ElementalMix", NPC => NPC.Calamity().elementalMix > 0), ("CalamityMod/Buffs/DamageOverTime/GodSlayerInferno", NPC => NPC.Calamity().gsInferno > 0), + ("CalamityMod/Buffs/DamageOverTime/HadopelagicPressure", NPC => NPC.Calamity().hPressure > 0), ("CalamityMod/Buffs/DamageOverTime/HolyFlames", NPC => NPC.Calamity().hFlames > 0), ("CalamityMod/Buffs/DamageOverTime/Laceration", NPC => NPC.Calamity().laceration > 0), ("CalamityMod/Buffs/DamageOverTime/HeavyBleeding", NPC => NPC.Calamity().heavybleeding > 0), diff --git a/NPCs/CalamityGlobalNPCLoot.cs b/NPCs/CalamityGlobalNPCLoot.cs index 7ebe6fa3cd..a35904f55e 100644 --- a/NPCs/CalamityGlobalNPCLoot.cs +++ b/NPCs/CalamityGlobalNPCLoot.cs @@ -221,9 +221,11 @@ namespace CalamityMod.NPCs // Sand Elemental // Elemental in a Bottle @ 20% Normal, 33.33% Expert+ // Rare Elemental in a Bottle @ 10% Normal, 16.67% Expert+ + // Desert Key @ 10% case NPCID.SandElemental: npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 5, 3)); npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 10, 6)); + npcLoot.Add(ItemID.DungeonDesertKey, 10); break; #endregion @@ -302,8 +304,10 @@ namespace CalamityMod.NPCs // Ice Golem // 8-10 Essence of Eleum @ 100%, 10-12 Expert+ + // Frozen Key @ 10% case NPCID.IceGolem: npcLoot.Add(DropHelper.NormalVsExpertQuantity(ModContent.ItemType(), 1, 8, 10, 10, 12)); + npcLoot.Add(ItemID.FrozenKey, 10); break; #endregion @@ -363,13 +367,27 @@ namespace CalamityMod.NPCs npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 25, 15)); break; - // Biome Mimics + // Corrupt Mimic // Celestial Claymore @ 14.29% Normal, 25% Expert+ - case NPCID.BigMimicHallow: case NPCID.BigMimicCorruption: - case NPCID.BigMimicCrimson: - case NPCID.BigMimicJungle: npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 7, 4)); + npcLoot.Add(ItemID.CorruptionKey, 10); + break; + + // Crimson Mimic + // Celestial Claymore @ 14.29% Normal, 25% Expert+ + // Crimson Key @ 10% + case NPCID.BigMimicCrimson: + npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 7, 4)); + npcLoot.Add(ItemID.CrimsonKey, 10); + break; + + // Hallowed Mimic + // Celestial Claymore @ 14.29% Normal, 25% Expert+ + // Hallowed Key @ 10% + case NPCID.BigMimicHallow: + npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 7, 4)); + npcLoot.Add(ItemID.HallowedKey, 10); break; // World Feeder @@ -411,6 +429,20 @@ namespace CalamityMod.NPCs case NPCID.Moth: npcLoot.ChangeDropRate(ItemID.ButterflyDust, 1, 1); break; + + // Jungle Mimic + // Celestial Claymore @ 14.29% Normal, 25% Expert+ + case NPCID.BigMimicJungle: + npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 7, 4)); + break; + + // Lihzahrd + Flying Snake + // Jungle Key @ 0.67% + case NPCID.Lihzahrd: + case NPCID.LihzahrdCrawler: + case NPCID.FlyingSnake: + npcLoot.Add(ItemID.JungleKey, 150); + break; #endregion #region Dungeon @@ -1222,10 +1254,6 @@ namespace CalamityMod.NPCs // Would be in the bag otherwise npcLoot.AddNormalOnly(ModContent.ItemType(), ThankYouPainting.DropInt); - // WoF drops Evil Keys - npcLoot.Add(ItemID.CorruptionKey, 3); - npcLoot.Add(ItemID.CrimsonKey, 3); - // Master items drop in Revengeance rev.Add(ItemID.WallofFleshMasterTrophy); rev.Add(ItemID.WallOfFleshGoatMountItem, 4); @@ -1248,9 +1276,6 @@ namespace CalamityMod.NPCs // Would be in the bag otherwise npcLoot.AddNormalOnly(ModContent.ItemType(), ThankYouPainting.DropInt); - // Queen Slime drops the Hallowed Key - npcLoot.Add(ItemID.HallowedKey, 3); - // Master items drop in Revengeance rev.Add(ItemID.QueenSlimeMasterTrophy); rev.Add(ItemID.QueenSlimePetItem, 4); @@ -1404,9 +1429,6 @@ namespace CalamityMod.NPCs npcLoot.AddNormalOnly(DropHelper.PerPlayer(ModContent.ItemType(), 1, 25, 30)); npcLoot.AddNormalOnly(ModContent.ItemType(), ThankYouPainting.DropInt); - // Plantera drops Jungle Key - npcLoot.Add(ItemID.JungleKey, 3); - // Master items drop in Revengeance rev.Add(ItemID.PlanteraMasterTrophy); rev.Add(ItemID.PlanteraPetItem, 4); diff --git a/NPCs/Cryogen/Cryogen.cs b/NPCs/Cryogen/Cryogen.cs index 3fda713ab3..cc397cdec9 100644 --- a/NPCs/Cryogen/Cryogen.cs +++ b/NPCs/Cryogen/Cryogen.cs @@ -1428,8 +1428,6 @@ namespace CalamityMod.NPCs.Cryogen normalOnly.Add(ModContent.ItemType(), DropHelper.NormalWeaponDropRateFraction); } - npcLoot.Add(ItemID.FrozenKey, 3); - // Trophy (always directly from boss, never in bag) npcLoot.Add(ModContent.ItemType(), 10); diff --git a/NPCs/GreatSandShark/GreatSandShark.cs b/NPCs/GreatSandShark/GreatSandShark.cs index e295167654..008c2637d5 100644 --- a/NPCs/GreatSandShark/GreatSandShark.cs +++ b/NPCs/GreatSandShark/GreatSandShark.cs @@ -677,9 +677,6 @@ IL_6899: { npcLoot.Add(ItemID.AncientBattleArmorMaterial); - // Great Sand Shark drops the Desert Key - npcLoot.Add(ItemID.DungeonDesertKey, 3); - // 1 Grand Scale guaranteed; on Expert, 33% chance of getting a second one npcLoot.Add(ModContent.ItemType()); npcLoot.AddIf(() => Main.expertMode, ModContent.ItemType(), 3); diff --git a/NPCs/PrimordialWyrm/PrimordialWyrmHead.cs b/NPCs/PrimordialWyrm/PrimordialWyrmHead.cs index 1ba04b13fa..086ac9f062 100644 --- a/NPCs/PrimordialWyrm/PrimordialWyrmHead.cs +++ b/NPCs/PrimordialWyrm/PrimordialWyrmHead.cs @@ -1519,7 +1519,7 @@ namespace CalamityMod.NPCs.PrimordialWyrm public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (NPC.Opacity == 1f && hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 1200, true); + target.AddBuff(ModContent.BuffType(), 1200, true); } } } diff --git a/NPCs/SunkenSea/Probesnout.cs b/NPCs/SunkenSea/Probesnout.cs index 4ef95c1c49..1c138250c2 100644 --- a/NPCs/SunkenSea/Probesnout.cs +++ b/NPCs/SunkenSea/Probesnout.cs @@ -1,53 +1,50 @@ using System; using System.Collections.Generic; using System.IO; -using System.Threading.Tasks; +using System.Linq; +using System.Threading; using CalamityMod.Enums; -using CalamityMod.Particles; +using CalamityMod.Items.Placeables.Banners; +using CalamityMod.Tiles; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; +using Terraria.DataStructures; using Terraria.GameContent; using Terraria.ID; -using Terraria.Utilities; +using Terraria.ModLoader; +using static CalamityMod.CalamityUtils; using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea { - public class Probesnout : SunkenSeaNPC + public class Probesnout : SunkenSeaNPC, IPathFinder { - public static float PathDetectionSize = 300f; - private static Task> _pathfindingTask; - #region Members - protected override List HuntNPCs => new() - { - // NPCType(), - }; + public static int IdleRandomMovementUnlikeliness = 250; + public static int IdleMinPathDistance = 200; + public static int IdleMaxPathDistance = 400; - protected override List AvoidNPCs => new() - { + public static int FleeTileAnticipationDistance = 5 * 16; + public static int FleeMinPathDistance = 80; + public static int FleeMaxPathDistance = 160; + + protected override List PreyIDs => + [ + // NPCType(), + ]; + + protected override List PredatorIDs => + [ // NPCType(), NPCType(), // NPCType(), // NPCType(), // NPCType(), - }; + ]; - private enum PersonalityType { Curious, Shy, Paranoid } - - private PersonalityType Personality - { - get => (PersonalityType)NPC.ai[0]; - set - { - NPC.ai[0] = (float)value; - NetUpdate(); - } - } - - private enum AnimationState { Idle, Attack } + private enum AnimationState { Idle, Eating } private AnimationState Animation { @@ -66,166 +63,170 @@ namespace CalamityMod.NPCs.SunkenSea AnimationFrames = 8; TimePerAnimationFrame = 5; break; - case AnimationState.Attack: + case AnimationState.Eating: AnimationFrames = 12; TimePerAnimationFrame = 7; break; } NPC.ai[1] = (float)value; - NetUpdate(); } } protected override SunkenSeaBiomeFlags BiomeDesignation => SunkenSeaBiomeFlags.RadiantReefs; - protected override float SpawningChance => 0f; - private int AnimationFrames = 8; private int TimePerAnimationFrame = 5; - private float MaximumSpeed = 6f; - private Vector2 ScaleSquish = Vector2.One; + private Action _currentBehavior; + private Action CurrentBehavior + { + get => _currentBehavior; + set + { + _previousBehavior = _currentBehavior; + _currentBehavior = value; + } + } + + private Action _previousBehavior; + + public PathfindingTask Path { get; set; } + + public Vector2 Position => NPC.Center; + + public Vector2 Velocity { get => NPC.velocity; set => NPC.velocity = value; } + + public float Acceleration => 0.4f; + + public float MaxSpeed => 8f; + + private Vector2 SpongeFoundPosition; + + private bool HasEatenSponge; + #endregion #region AI - protected override void BehaviorOnSpawn() + protected override bool PlayerSearchFilter(Player p) { - CurrentBehavior = IdleBehavior; + return base.PlayerSearchFilter(p) || p == CurrentPlayer && Vector2.DistanceSquared(NPC.Center, p.Center) < 960f * 960f; + } - WeightedRandom randomPersonality = new(); - randomPersonality.Add(PersonalityType.Curious, 0.6f); - randomPersonality.Add(PersonalityType.Shy, 0.3f); - randomPersonality.Add(PersonalityType.Paranoid, 0.1f); - Personality = randomPersonality.Get(); + protected override bool NPCSearchFilter(NPC n) + { + return base.NPCSearchFilter(n) || (n == CurrentPrey || n == CurrentPredator) && Vector2.DistanceSquared(NPC.Center, n.Center) < 960f * 960f; + } + public override void OnSpawn(IEntitySource source) + { + CurrentBehavior = IdlingBehavior; NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; NPC.MaxFallSpeedMultiplier *= 2f; } - protected override void CreatureAI() + public override void AI() { - CurrentBehavior.Invoke(); + CurrentBehavior?.Invoke(); - if (!NPC.velocity.HasNaNs()) - ConeDetectionDirection = (NPC.rotation * MathF.Sign(NPC.velocity.Y) + (NPC.spriteDirection == -1 ? MathHelper.Pi : 0f)).ToRotationVector2(); - - NPC.rotation = MathHelper.ToRadians(NPC.velocity.Length() * 3f) * MathF.Sign(NPC.velocity.X); - - if (MathF.Abs(NPC.velocity.X) > 2f) + NPC.rotation = MathHelper.ToRadians(NPC.velocity.X * 3f); + if (CurrentBehavior == EatingBehavior && Vector2.DistanceSquared(NPC.Center, SpongeFoundPosition) <= 64f * 64f) + NPC.spriteDirection = NPC.direction = MathF.Sign(SpongeFoundPosition.X - NPC.Center.X); + else if (NPC.velocity.LengthSquared() != 0f) NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); - if (!NPC.wet) - CurrentBehavior = OutsideWaterBehavior; + if (Main.rand.NextBool(50) && !HasEatenSponge && CurrentBehavior == IdlingBehavior) + ThreadPool.QueueUserWorkItem(_ => DetectSponges(), null); - if (NPC.velocity.LengthSquared() > MaximumSpeed * MaximumSpeed) - NPC.velocity = NPC.velocity.SafeNormalize(-Vector2.UnitY) * MaximumSpeed; + if (!NPC.wet && CurrentBehavior != OutsideWaterBehavior) + { + NPC.noGravity = false; + CurrentBehavior = OutsideWaterBehavior; + } if (ScaleSquish.Y > 1f) - ScaleSquish.Y -= 0.025f; - - if (ScaleSquish.Y < 1f) - ScaleSquish.Y = 1f; + ScaleSquish.Y = Math.Max(1f, ScaleSquish.Y - 0.025f); } - protected override void OnBehaviorChange(Action newBehavior) => NPC.noGravity = newBehavior != OutsideWaterBehavior; - protected override void OnPreyDetection(NPC prey) { // If it's not a small fish and it's not being chased by a predator, the Probesnout may hunt. - if (CurrentPredator is null) - { - CurrentBehavior = HuntBehavior; - React(Color.Orange * 0.6f, EmoteExpressionParticle.EmoteType.Exclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - } + if (CurrentPredator != null) + return; - ScaleSquish.Y += 1.4f; + CurrentBehavior = HuntBehavior; + ScaleSquish.Y += 0.4f; } protected override void OnPredatorDetection(NPC predator) { // Regardless of anything, if it detects a predator, time to run. - CurrentBehavior = AvoidBehavior; - - React(Color.Red * 0.6f, EmoteExpressionParticle.EmoteType.DoubleExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - - ScaleSquish.Y += 1.4f; + CurrentBehavior = FleeingBehavior; + ScaleSquish.Y += 0.4f; } protected override void OnPlayerDetection(Player player) { - // If the Probesnout is shy, it'll run away from the player. - if (Personality == PersonalityType.Shy) - { - CurrentBehavior = AvoidBehavior; - React(Color.Orange, EmoteExpressionParticle.EmoteType.QuestionExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - } - - if (Personality == PersonalityType.Curious) - React(Color.Green, EmoteExpressionParticle.EmoteType.Question, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); + if (CurrentPredator != null) + return; ScaleSquish.Y += 0.4f; } - private void IdleBehavior() + private void IdlingBehavior() { - if (_pathfindingTask.Result == null) + // At random, the mob will choose a random nearby point and pathfind there. + PathfindingTask parameters = null; + if (Main.rand.NextBool(150)) { - NPC.velocity *= 0.95f; - - if (Main.rand.NextBool(125)) - _pathfindingTask = CalamityUtils.FindPathAsync(new( - NPC.Center, - NPC.Center + Main.rand.NextVector2CircularEdge(PathDetectionSize, PathDetectionSize) * Main.rand.NextFloat(0.75f, 1f), - SunkenSeaTileValidity)); + _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * 300f; + NPC.netUpdate = true; + parameters = new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); } - else - GenericPathFollowing(acceleration: 0.03f); + this.DoPathfinding(parameters); } - private void AvoidBehavior() + private void FleeingBehavior() { - // Depending on the personality, the Sharkoon will choose who to avoid. - Entity entityToAvoid = null; - switch (Personality) + // If the avoided entity is gone, go back to idling. + if (CurrentPredator == null) { - case PersonalityType.Shy: - entityToAvoid = (NearestEntity is NPC nearestNPC && HuntNPCs.Contains(nearestNPC.type)) ? null : NearestEntity; - break; - case PersonalityType.Curious: - entityToAvoid = CurrentPredator; - break; - case PersonalityType.Paranoid: - entityToAvoid = CurrentPredator; - break; - } - - // If there aren't any more targets detected, go back to idling. - if (entityToAvoid is null) - { - CurrentBehavior = IdleBehavior; + CurrentBehavior = IdlingBehavior; return; } - bool isAvoidingPredator = entityToAvoid is NPC npc && npc.whoAmI == CurrentPredator.whoAmI; + // While it doesn't have any obstacles in front of it, run away in a straight line. + // Try to manuever if there are any obstacles. + var headedDirection = CurrentPredator.DirectionTo(NPC.Center) * 200f; + // bool tileNotWater = GetIntersectingPoints(NPC.Center, NPC.Center + headedDirection).Any(point => Main.tile[point].IsTileSolid() || Main.tile[point].LiquidAmount < 255); - if (HasPath) + if (false) { - float fleeingDistance = isAvoidingPredator ? 600f : 300f; - - Vector2 randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(fleeingDistance, fleeingDistance + 100f); - while (Main.tile[randomEscapePoint.ToTileCoordinates()].IsTileSolid()) - randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(fleeingDistance, fleeingDistance + 100f); - - + do + { + var randomNormalDirection = headedDirection.RotatedBy(MathHelper.PiOver2 * Main.rand.NextBool().ToDirectionInt()); + _randomPathPoint = randomNormalDirection.RotatedByRandom(MathHelper.PiOver4); + if (!Main.tile[(NPC.Center + _randomPathPoint).ToTileCoordinates()].IsTileSolid()) + break; + } + while (!Main.tile[(NPC.Center + _randomPathPoint).ToTileCoordinates()].IsTileSolid()); + NPC.netUpdate = true; + this.DoPathfinding(new PathfindingTask(NPC.Center, NPC.Center + _randomPathPoint, SunkenSeaTileValidity)); } else - GenericPathFollowing(acceleration: 0.14f); + { + NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; + Path = null; + + // Cap the speed if MaxSpeed has been surpassed. + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; + } } private void HuntBehavior() @@ -233,25 +234,110 @@ namespace CalamityMod.NPCs.SunkenSea // If there's no more prey, go back to idling. if (CurrentPrey is null) { - CurrentBehavior = IdleBehavior; + CurrentBehavior = IdlingBehavior; return; } - if (!HasLineOfSight(CurrentPrey.Center)) + // With sight, just go straight at him. Without it, try to pathfind over them. + this.DoPathfinding(new PathfindingTask(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), continuouslyUpdatePath: true); + } + + private void EatingBehavior() + { + if (Vector2.DistanceSquared(NPC.Center, SpongeFoundPosition) <= 64f * 64f) { - if (HasPath) - GenericPathFollowing(acceleration: 0.14f); - else - _pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); + NPC.velocity *= 0.9f; + Animation = AnimationState.Eating; + if (NPC.frame.Y >= NPC.height * AnimationFrames) + { + HasEatenSponge = true; + Animation = AnimationState.Idle; + CurrentBehavior = IdlingBehavior; + return; + } } else - NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * 0.14f; + this.DoPathfinding(new PathfindingTask(NPC.Center, SpongeFoundPosition, SunkenSeaTileValidity)); } private void OutsideWaterBehavior() { if (NPC.wet) - CurrentBehavior = PreviousBehavior; + { + NPC.noGravity = true; + CurrentBehavior = _previousBehavior; + } + } + + private void DetectSponges() + { + Vector2? closestSpongeFound = null; + float closestDistanceSquared = float.MaxValue; + + foreach (var direction in Directions) + { + // var points = GetIntersectingPoints(NPC.Center, NPC.Center + direction * 360f); + var points = new Point[1]; + foreach (var point in points) + { + // Check if the tile coordinates are within the valid range + if (!WorldGen.InWorld(point.X, point.Y)) + continue; + + // Check if the current tile is AerialiteBrick + if (Main.tile[point].TileType == TileType()) + { + // Check all adjacent directions for a non-solid tile with line of sight + foreach (var adjacentDirection in Directions) + { + Point adjacentPoint = point + adjacentDirection.ToPoint(); + + // Validate adjacent tile coordinates + if (!WorldGen.InWorld(adjacentPoint.X, adjacentPoint.Y)) + continue; + + // Skip if the adjacent tile is solid + if (Main.tile[adjacentPoint].IsTileSolid()) + continue; + + Vector2 worldPos = adjacentPoint.ToWorldCoordinates(); + if (NPC.HasSight(worldPos)) + { + // Calculate the squared distance from NPC to the adjacent tile + float distanceSquared = Vector2.DistanceSquared(NPC.Center, worldPos); + if (distanceSquared < closestDistanceSquared) + { + closestDistanceSquared = distanceSquared; + closestSpongeFound = worldPos; + } + } + } + + // Break after checking the first sponge nutrient in this direction + break; + } + } + } + + // Update behavior if a valid tile was found + if (closestSpongeFound.HasValue) + { + CurrentBehavior = EatingBehavior; + SpongeFoundPosition = closestSpongeFound.Value; + } + } + + public override void HitEffect(NPC.HitInfo hit) + { + for (int k = 0; k < 25; k++) + { + Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.Blood, hit.HitDirection, -1f, 0, default, 1f); + } + if (NPC.life <= 0) + { + for (int i = 0; i < 4; i++) + Gore.NewGoreDirect(NPC.GetSource_Death(), NPC.Center, new Vector2(hit.HitDirection, -1f), Mod.Find($"{Name}{i + 1}").Type); + } } #endregion @@ -265,8 +351,9 @@ namespace CalamityMod.NPCs.SunkenSea { NPC.frame.Y += frameHeight; NPC.frame.Y = Math.Min(NPC.frame.Y, AnimationFrames * frameHeight); - NPC.frame.Y = NPC.frame.Y % (AnimationFrames * frameHeight); NPC.frameCounter = 0; + if (Animation == AnimationState.Idle) + NPC.frame.Y %= AnimationFrames * frameHeight; } } @@ -290,7 +377,7 @@ namespace CalamityMod.NPCs.SunkenSea public override void SetStaticDefaults() { base.SetStaticDefaults(); - Main.npcFrameCount[Type] = 15; + Main.npcFrameCount[Type] = 12; Main.npcCatchable[Type] = true; NPCID.Sets.CountsAsCritter[Type] = true; } @@ -298,35 +385,42 @@ namespace CalamityMod.NPCs.SunkenSea public override void SetDefaults() { base.SetDefaults(); + + // BannerItem = ItemType(); NPC.lifeMax = 5; - NPC.aiStyle = -1; - AIType = -1; NPC.npcSlots = 0.1f; NPC.noGravity = true; NPC.chaseable = false; NPC.width = 44; - NPC.height = 55; + NPC.height = 50; + + NPC.HitSound = SoundID.NPCHit1; + NPC.DeathSound = SoundID.NPCDeath1; + NPC.value = Item.buyPrice(0, 0, 5, 0); + + NPC.Calamity().VulnerableToHeat = false; + NPC.Calamity().VulnerableToSickness = true; + NPC.Calamity().VulnerableToElectricity = true; + NPC.Calamity().VulnerableToWater = false; } #endregion #region Syncing + private Vector2 _randomPathPoint; + public override void SendExtraAI(BinaryWriter writer) { - base.SendExtraAI(writer); - writer.Write7BitEncodedInt(AnimationFrames); - writer.Write7BitEncodedInt(TimePerAnimationFrame); + writer.WriteVector2(_randomPathPoint); } public override void ReceiveExtraAI(BinaryReader reader) { - base.ReceiveExtraAI(reader); - AnimationFrames = reader.Read7BitEncodedInt(); - TimePerAnimationFrame = reader.Read7BitEncodedInt(); + _randomPathPoint = reader.ReadVector2(); } #endregion @@ -348,8 +442,15 @@ namespace CalamityMod.NPCs.SunkenSea public override void HitEffect(NPC.HitInfo hit) { - for (int i = 0; i < 5; i++) - Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.GoldCritter, hit.HitDirection, -1f); + for (int k = 0; k < 25; k++) + { + Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.GoldCritter, hit.HitDirection, -1f, 0, default, 1f); + } + if (NPC.life <= 0) + { + for (int i = 0; i < 4; i++) + Gore.NewGoreDirect(NPC.GetSource_Death(), NPC.Center, new Vector2(hit.HitDirection, -1f), Mod.Find($"{Name}{i + 1}").Type); + } } } } diff --git a/NPCs/SunkenSea/Sharkoon.cs b/NPCs/SunkenSea/Sharkoon.cs index 90b6707b47..020db79c93 100644 --- a/NPCs/SunkenSea/Sharkoon.cs +++ b/NPCs/SunkenSea/Sharkoon.cs @@ -1,69 +1,43 @@ using System; using System.Collections.Generic; using System.IO; -using System.Threading.Tasks; using CalamityMod.Enums; +using CalamityMod.Items.Placeables.Banners; using CalamityMod.Particles; using CalamityMod.Projectiles.Enemy; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.Audio; +using Terraria.DataStructures; using Terraria.GameContent; -using Terraria.GameContent.UI.Elements; using Terraria.ID; -using Terraria.ModLoader.Utilities; -using Terraria.Utilities; +using Terraria.ModLoader; +using static CalamityMod.CalamityUtils; using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea { - public class Sharkoon : SunkenSeaNPC + public class Sharkoon : SunkenSeaNPC, IPathFinder { - public static float DistanceToKaboom = 80f; - public static float IdleMovementMaxRange = 300f; - public static int ExplosionRadius = 80; - public static float TimeToRecover = 600f; - public static float TimeRecovering = 120f; - - private Task> _pathfindingTask = null; - #region Fields & Properties - protected override List HuntNPCs => new() - { - // NPCType(), - NPCType(), - NPCType(), - NPCType(), - NPCType(), - }; + #region Static Fields - protected override List AvoidNPCs => new() - { - // NPCType(), - // NPCType(), - NPCType(), - // NPCType, - }; + public static int IdleRandomMovementUnlikeliness = 250; + public static int IdleMinPathDistance = 200; + public static int IdleMaxPathDistance = 400; - /// - /// The different types of personality this NPC can have. - /// - private enum PersonalityType { Shy, Curious, Paranoid } + public static int FleeTileAnticipationDistance = 64; + public static int FleeMinPathDistance = 80; + public static int FleeMaxPathDistance = 160; - /// - /// The current personality of this NPC. - /// - private PersonalityType Personality - { - get => (PersonalityType)NPC.ai[0]; - set - { - NPC.ai[0] = (float)value; - NetUpdate(); - } - } + public static int ExplosionDistance = 80; + public static int ExplosionRadius = 80; + public static int ExplosionCooldown = 600; + public static int RecoveringTime = 120; + + #endregion /// /// The different types of animation this enemy can have. @@ -101,8 +75,6 @@ namespace CalamityMod.NPCs.SunkenSea ChangeAnimation(animationFrames: 6, timePerAnimationFrame: 6, loops: true); break; } - - NetUpdate(); } } @@ -110,63 +82,98 @@ namespace CalamityMod.NPCs.SunkenSea /// The amount of frames that one column of sprites has.
/// Defaults to 7 since that's the first column's amount of frames. ///
- private int AnimationFrames = 7; + private int _animationFrames = 7; /// /// The amount, in frames, that it takes to go to the next animation frame.
/// Defaults to 7. ///
- private int TimePerAnimationFrame = 7; + private int _timePerAnimationFrame = 7; /// /// Whether or not the animation loops or not.
/// Defaults to . ///
- private bool AnimationLoop = true; + private bool _animationLoop = true; + + /// + /// The squish of this NPC while drawing. + /// + private Vector2 _scaleSquish = Vector2.One; + + private Entity _avoidedEntity; /// /// A timer used to know when the NPC should recover after it explodes. /// private ref float RecoverTimer => ref NPC.ai[2]; - /// - /// The maximum speed this NPC can have, it cannot be faster than this number. - /// - private float MaximumSpeed = 4f; - - /// - /// The acceleration of the Sharkoon. - /// - private const float Acceleration = 0.25f; - - /// - /// How unlikely is the Sharkoon going to move normally.
- /// Defaults to 250. - ///
- private int RandomIdleMovementUnlikeliness = 250; - /// /// Whether or not the Sharkoon is capable of exploding. /// - private bool IsBig => Animation == AnimationState.Normal; + private bool CanExplode => Animation == AnimationState.Normal; /// /// Whether or not the Sharkoon is currently exploding. /// private bool IsExploding => CurrentBehavior == ExplodingBehavior; + private Action _currentBehavior; + private Action CurrentBehavior + { + get => _currentBehavior; + set + { + if (value != _currentBehavior) + OnBehaviorChange(value); + _previousBehavior = _currentBehavior; + _currentBehavior = value; + } + } + + private Action _previousBehavior; + + #region SunkenSeaNPC Implementation + + protected override List PreyIDs => + [ + // NPCType(), + NPCType(), + NPCType(), + NPCType(), + NPCType(), + NPCType(), + ]; + + protected override List PredatorIDs => + [ + // NPCType(), + // NPCType(), + NPCType(), + // NPCType, + ]; + protected override SunkenSeaBiomeFlags BiomeDesignation => SunkenSeaBiomeFlags.RadiantReefs; - protected override float SpawningChance => SpawnCondition.CaveJellyfish.Chance * 0.9f; - - /// - /// The squish of this NPC while drawing. - /// - private Vector2 ScaleSquish = Vector2.One; - #endregion - #region Other Overridden Methods + #region IPathFinder Implementation + + public PathfindingTask Path { get; set; } + + public Vector2 Position => NPC.Center; + + public Vector2 Velocity { get => NPC.velocity; set => NPC.velocity = value; } + + public float Acceleration { get; set; } = 0.25f; + + public float MaxSpeed { get; set; } = 6f; + + #endregion + + #endregion + + #region SetDefaults public override void SetStaticDefaults() { @@ -178,14 +185,14 @@ namespace CalamityMod.NPCs.SunkenSea { base.SetDefaults(); + // BannerItem = ItemType(); + NPC.damage = 20; NPC.lifeMax = 350; NPC.defense = 5; NPC.knockBackResist = 0.15f; NPC.chaseable = false; - NPC.aiStyle = -1; - AIType = -1; NPC.width = 52; NPC.height = 46; NPC.noGravity = true; @@ -193,8 +200,6 @@ namespace CalamityMod.NPCs.SunkenSea NPC.HitSound = SoundID.NPCHit1; NPC.DeathSound = SoundID.NPCDeath1; NPC.value = Item.buyPrice(0, 0, 5, 0); - // Banner = NPC.type; - // BannerItem = ModContent.ItemType(); NPC.Calamity().VulnerableToHeat = false; NPC.Calamity().VulnerableToSickness = true; @@ -202,109 +207,41 @@ namespace CalamityMod.NPCs.SunkenSea NPC.Calamity().VulnerableToWater = false; } - public override void HitEffect(NPC.HitInfo hit) - { - for (int k = 0; k < 5; k++) - { - Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f); - } - if (NPC.life <= 0) - { - for (int k = 0; k < 25; k++) - { - Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f); - } - } - } - - public override bool CanBeHitByNPC(NPC attacker) - { - if (attacker.whoAmI == NPC.whoAmI) - return false; - - return true; - } - - public override void OnHitByNPC(NPC attacker) - { - if (IsBig) - CurrentBehavior = ExplodingBehavior; - } - - public override void OnHitByItem(Player player, Item item, NPC.HitInfo hit, int damageDone) - { - if (IsBig) - CurrentBehavior = ExplodingBehavior; - } - - public override void OnHitByProjectile(Projectile projectile, NPC.HitInfo hit, int damageDone) - { - if (IsBig) - CurrentBehavior = ExplodingBehavior; - } - #endregion - #region AI + #region Behavior - protected override void BehaviorOnSpawn() + protected override bool PlayerSearchFilter(Player p) + { + return base.PlayerSearchFilter(p) || p == CurrentPlayer && Vector2.DistanceSquared(NPC.Center, p.Center) < 960f * 960f; + } + + protected override bool NPCSearchFilter(NPC n) + { + return base.NPCSearchFilter(n) || (n == CurrentPrey || n == CurrentPredator) && Vector2.DistanceSquared(NPC.Center, n.Center) < 960f * 960f; + } + + public override void OnSpawn(IEntitySource source) { CurrentBehavior = IdlingBehavior; - - WeightedRandom randomPersonality = new(); - randomPersonality.Add(PersonalityType.Shy, 0.4f); - randomPersonality.Add(PersonalityType.Curious, 0.4f); - randomPersonality.Add(PersonalityType.Paranoid, 0.2f); - Personality = randomPersonality.Get(); - - DetectionDistance = 320f; - ConeDetectionAngle = MathHelper.ToRadians(30f); - - if (Personality == PersonalityType.Curious) - { - DetectionDistance *= 1.5f; - ConeDetectionAngle *= 1.5f; - RandomIdleMovementUnlikeliness /= 2; - } - - if (Personality == PersonalityType.Paranoid) - MaximumSpeed *= 1.5f; - NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; NPC.MaxFallSpeedMultiplier *= 2f; } - protected override void CreatureAI() + public override void AI() { CurrentBehavior?.Invoke(); - // Sets the direction at which it looks at the cone. - // This makes it look at the direction it's going. - if (!NPC.velocity.HasNaNs()) - ConeDetectionDirection = (NPC.rotation * MathF.Sign(NPC.velocity.Y) + (NPC.spriteDirection == -1 ? MathHelper.Pi : 0f)).ToRotationVector2(); - // Leans the Sharkoon towards the direction it's going. - NPC.rotation = MathHelper.ToRadians(NPC.velocity.Length() * 3f) * MathF.Sign(NPC.velocity.X); - - // When the Sharkoon is fast enough in one direction, it'll turn to that direction. - if (MathF.Abs(NPC.velocity.X) > 1f) - NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); - - // When the Sharkoon's paranoid, it'll explode at anything that isn't prey which gets close to the Sharkoon. - bool isEntityPlayerOrNonPreyNPC = NearestEntity is not null && (NearestEntity is Player || NearestEntity is NPC npc && !HuntNPCs.Contains(npc.type)); - if (isEntityPlayerOrNonPreyNPC) - { - bool isWithinDistance = NPC.DistanceSQ(NearestEntity.Center) < DistanceToKaboom * DistanceToKaboom; - if (IsBig && Personality == PersonalityType.Paranoid && isEntityPlayerOrNonPreyNPC && isWithinDistance) - CurrentBehavior = ExplodingBehavior; - } + NPC.rotation = MathHelper.ToRadians(NPC.velocity.X * 3f); + NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); // When it has already exploded, a timer will start, which when finished it'll make the Sharkoon recover. - if (!IsBig) + if (!CanExplode) { RecoverTimer++; - if (RecoverTimer > TimeToRecover) + if (RecoverTimer > ExplosionCooldown) CurrentBehavior = RecoveringBehavior; } @@ -312,92 +249,29 @@ namespace CalamityMod.NPCs.SunkenSea if (!NPC.wet && !IsExploding) CurrentBehavior = OutsideWaterBehavior; - // Clamps the velocity at all times. - if (NPC.velocity.LengthSquared() > MaximumSpeed * MaximumSpeed) - NPC.velocity = NPC.velocity.SafeNormalize(Vector2.UnitY) * MaximumSpeed; - - if (ScaleSquish.Y > 1f) + // Reset any squish that is done to the Sharkoon. + if (_scaleSquish.Y > 1f) { - ScaleSquish.Y -= 0.025f; - if (ScaleSquish.Y < 1f) - ScaleSquish.Y = 1f; - } - } - - protected override void OnBehaviorChange(Action newBehavior) - { - // Obviously, when it gets to the exploding behaivor, it should make the explosion animation. - if (newBehavior == ExplodingBehavior) - Animation = AnimationState.Explosion; - - // Resets the timer when it needs to use it again. - if (newBehavior == RecoveringBehavior || CurrentBehavior == RecoveringBehavior) - RecoverTimer = 0f; - - // When it gets outside of water, it'll try to gravitate downards towards the water. - if (newBehavior == OutsideWaterBehavior) - NPC.noGravity = false; - } - - protected override void OnPreyDetection(NPC prey) - { - // If it's not a small fish and it's not being chased by a predator, the Sharkoon may hunt. - if (IsBig && CurrentPredator is null && !IsExploding) - { - CurrentBehavior = HuntBehavior; - ScaleSquish.Y += 0.4f; - React(Color.Orange * 0.6f, EmoteExpressionParticle.EmoteType.Exclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - } - } - - protected override void OnPredatorDetection(NPC predator) - { - // If it detects a predator, time to run. - if (!IsExploding) - { - CurrentBehavior = AvoidBehavior; - React(Color.Red * 0.6f, EmoteExpressionParticle.EmoteType.DoubleExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - ScaleSquish.Y += 0.4f; - } - } - - protected override void OnPlayerDetection(Player player) - { - // When there's a predator, player's shouldn't matter. - if (CurrentPredator is not null) - return; - - // If the Sharkoon is shy, it'll run away from the player. - if (Personality == PersonalityType.Shy) - { - CurrentBehavior = AvoidBehavior; - React(Color.Orange, EmoteExpressionParticle.EmoteType.QuestionExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - ScaleSquish.Y += 0.4f; - } - - if (Personality == PersonalityType.Curious) - { - React(Color.Green, EmoteExpressionParticle.EmoteType.Question, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - ScaleSquish.Y += 0.4f; + _scaleSquish.Y -= 0.025f; + if (_scaleSquish.Y < 1f) + _scaleSquish.Y = 1f; } } private void IdlingBehavior() { - if (_pathfindingTask.Result != null) + // At random, the mob will choose a random nearby point and pathfind there. + PathfindingTask task = null; + if (Main.rand.NextBool(IdleRandomMovementUnlikeliness)) { - // While it hasn't decided yet which path to follow, it'll deaccelerate and stand still. - NPC.velocity *= 0.95f; - - // Randomly, it'll decide a path whose destination is somewhere around him. - if (Main.rand.NextBool(RandomIdleMovementUnlikeliness) && !_pathfindingTask.IsCompleted) - _pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, Main.rand.NextVector2Circular(400f, 400f), SunkenSeaTileValidity)); + _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance); + NPC.netUpdate = true; + task = new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); } - else - GenericPathFollowing(Acceleration); + this.DoPathfinding(task); } - private void HuntBehavior() + private void HuntingBehavior() { // If there's no more prey, go back to idling. if (CurrentPrey is null) @@ -406,72 +280,49 @@ namespace CalamityMod.NPCs.SunkenSea return; } - if (!HasLineOfSight(CurrentPrey.Center)) - { - if (_pathfindingTask.Result != null) - PathfindingPoints = _pathfindingTask.Result; - - if (_pathfindingTask.Result != null) - GenericPathFollowing(Acceleration); - else - _pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); - } + // With sight, just go straight at him. Without it, try to pathfind over them. + if (!NPC.HasSight(CurrentPrey.Center)) + this.DoPathfinding(new PathfindingTask(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); else + { NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; + } } - private void AvoidBehavior() + private void FleeingBehavior() { - // Depending on the personality, the Sharkoon will choose who to avoid. - Entity entityToAvoid = null; - switch (Personality) - { - case PersonalityType.Shy: - entityToAvoid = (NearestEntity is NPC nearestNPC && HuntNPCs.Contains(nearestNPC.type)) ? null : NearestEntity; - break; - case PersonalityType.Curious: - case PersonalityType.Paranoid: - entityToAvoid = CurrentPredator; - break; - } + // Check who is the avoided entity specifically. + _avoidedEntity = _avoidedEntity is NPC ? CurrentPredator : CurrentPlayer; - // If there aren't any more targets detected, go back to idling. - if (entityToAvoid is null) + // If the avoided entity is gone, go back to idling. + if (_avoidedEntity == null) { CurrentBehavior = IdlingBehavior; return; } - // When it's going in a direction and it detects that it'll stumble into tiles, it'll try to path-find a way to continue avoiding whichever entity. - const int TileAnticipationDistance = 5 * 16; - const float AngleVariance = 2.2f; // In radians. - const int MaxAttemptsToFindPath = 20; - const int MinimumEscapeDistance = 160; - const int MaximumEscapeDistance = 320; - if (Main.tile[(NPC.Center + NPC.DirectionFrom(entityToAvoid.Center) * TileAnticipationDistance).ToTileCoordinates()].IsTileSolid() && !HasPath) + // While it doesn't have any obstacles in front of it, run away in a straight line. + // Try to manuever if there are any obstacles. + if (!Main.tile[(NPC.Center + NPC.DirectionFrom(_avoidedEntity.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid()) { - Vector2 randomEscapePoint; - int attempts = 0; - do - { - randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(AngleVariance) * Main.rand.NextFloat(MinimumEscapeDistance, MaximumEscapeDistance); - attempts++; - } - while (Main.tile[randomEscapePoint.ToTileCoordinates()].IsTileSolid() || attempts < MaxAttemptsToFindPath); + NPC.velocity += NPC.DirectionFrom(_avoidedEntity.Center) * Acceleration; - _pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, randomEscapePoint, SunkenSeaTileValidity)); + // Cap the speed if MaxSpeed has been surpassed. + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; + } + else + { + float distanceFromAvoided = Vector2.Distance(NPC.Center, _avoidedEntity.Center); + _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f); + NPC.netUpdate = true; + this.DoPathfinding(new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); } - if (_pathfindingTask.Result != null) - PathfindingPoints = _pathfindingTask.Result; - - if (HasPath) - GenericPathFollowing(Acceleration); - else - NPC.velocity += NPC.DirectionFrom(entityToAvoid.Center) * Acceleration; - // If it's capable of exploding and the predator's within distance, kaboom. - if (IsBig && NPC.DistanceSQ(entityToAvoid.Center) < DistanceToKaboom * DistanceToKaboom && entityToAvoid is NPC predator && AvoidNPCs.Contains(predator.type)) + if (CanExplode && NPC.DistanceSQ(_avoidedEntity.Center) < ExplosionDistance * ExplosionDistance && _avoidedEntity is NPC predator && PredatorIDs.Contains(predator.type)) CurrentBehavior = ExplodingBehavior; } @@ -491,16 +342,16 @@ namespace CalamityMod.NPCs.SunkenSea if (NPC.frame.Y >= NPC.height * 16) { Animation = AnimationState.Shrunk; - CurrentBehavior = PreviousBehavior; + CurrentBehavior = _previousBehavior; } } private void RecoveringBehavior() { - if (RecoverTimer >= TimeRecovering) + if (RecoverTimer >= RecoveringTime) { Animation = AnimationState.Normal; - CurrentBehavior = PreviousBehavior; + CurrentBehavior = _previousBehavior; } // Deaccelerates to stay still. @@ -510,12 +361,10 @@ namespace CalamityMod.NPCs.SunkenSea // a dedicated server doesn't need to load these. if (!Main.dedServ) { - float fade = Utils.GetLerpValue(TimeRecovering, 0, RecoverTimer); - float rotFactor = 360f; + float fade = Utils.GetLerpValue(RecoveringTime, 0, RecoverTimer); if (Main.rand.NextBool()) { - float rot = MathHelper.ToRadians(rotFactor); - Vector2 velOffset = CalamityUtils.RandomVelocity(50f, 20f, 70f, 0.04f); + Vector2 velOffset = RandomVelocity(50f, 20f, 70f, 0.04f); velOffset *= Main.rand.NextFloat(15, 20) * fade; Dust dust = Dust.NewDustPerfect(NPC.Center + velOffset * 2.5f, 267, -velOffset * Main.rand.NextFloat(0.08f, 0.12f) * 1.5f, 0, default, Main.rand.NextFloat(0.8f, 0.95f)); dust.noGravity = true; @@ -531,10 +380,94 @@ namespace CalamityMod.NPCs.SunkenSea if (NPC.wet) { NPC.noGravity = true; - CurrentBehavior = PreviousBehavior; + CurrentBehavior = _previousBehavior; } } + private void OnBehaviorChange(Action newBehavior) + { + // Obviously, when it gets to the exploding behaivor, it should make the explosion animation. + if (newBehavior == ExplodingBehavior) + Animation = AnimationState.Explosion; + + // Resets the timer when it needs to use it again. + if (newBehavior == RecoveringBehavior || CurrentBehavior == RecoveringBehavior) + RecoverTimer = 0f; + + // When it gets outside of water, it'll try to gravitate downards towards the water. + if (newBehavior == OutsideWaterBehavior) + NPC.noGravity = false; + + Path = null; + } + + protected override void OnPreyDetection(NPC prey) + { + // If it's not a small fish and it's not being chased by a predator, the Sharkoon may hunt. + if (CanExplode && CurrentPredator is null && !IsExploding) + { + CurrentBehavior = HuntingBehavior; + _scaleSquish.Y += 0.4f; + } + } + + protected override void OnPredatorDetection(NPC predator) + { + // If it detects a predator, time to run. + if (!IsExploding) + { + CurrentBehavior = FleeingBehavior; + _avoidedEntity = predator; + _scaleSquish.Y += 0.4f; + } + } + + protected override void OnPlayerDetection(Player player) + { + // When there's a predator, player's shouldn't matter. + if (CurrentPredator is not null && !IsExploding) + return; + + CurrentBehavior = FleeingBehavior; + _avoidedEntity = player; + _scaleSquish.Y += 0.4f; + } + + public override void HitEffect(NPC.HitInfo hit) + { + for (int k = 0; k < 5; k++) + { + Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f); + } + if (NPC.life <= 0) + { + for (int k = 0; k < 25; k++) + { + Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f); + } + } + } + + public override bool CanBeHitByNPC(NPC attacker) => attacker.type != Type; + + public override void OnHitByNPC(NPC attacker) + { + if (CanExplode) + CurrentBehavior = ExplodingBehavior; + } + + public override void OnHitByItem(Player player, Item item, NPC.HitInfo hit, int damageDone) + { + if (CanExplode) + CurrentBehavior = ExplodingBehavior; + } + + public override void OnHitByProjectile(Projectile projectile, NPC.HitInfo hit, int damageDone) + { + if (CanExplode) + CurrentBehavior = ExplodingBehavior; + } + private void Kaboom() { if (Main.netMode != NetmodeID.MultiplayerClient) @@ -544,11 +477,13 @@ namespace CalamityMod.NPCs.SunkenSea NPC.Center, Vector2.Zero, ProjectileType(), - NPC.damage, + NPC.damage * 10, 10f, - Main.myPlayer); + ai0: NPC.whoAmI); } + AddScreenshakeAt(NPC.Center, 15f); + // VFX and sound effects go here, // a dedicated server doesn't need to load these. if (!Main.dedServ) @@ -574,8 +509,6 @@ namespace CalamityMod.NPCs.SunkenSea SoundStyle boom = new("CalamityMod/Sounds/Custom/SharkoonBoom"); SoundEngine.PlaySound(boom with { Volume = 0.7f, PitchVariance = 0.15f }, NPC.Center); } - - NetUpdate(); } #endregion @@ -587,21 +520,21 @@ namespace CalamityMod.NPCs.SunkenSea /// private void ChangeAnimation(int animationFrames, int timePerAnimationFrame, bool loops) { - AnimationFrames = animationFrames; - TimePerAnimationFrame = timePerAnimationFrame; - AnimationLoop = loops; + _animationFrames = animationFrames; + _timePerAnimationFrame = timePerAnimationFrame; + _animationLoop = loops; } public override void FindFrame(int frameHeight) { NPC.frameCounter++; - if (NPC.frameCounter > TimePerAnimationFrame) + if (NPC.frameCounter > _timePerAnimationFrame) { NPC.frame.Y += frameHeight; - NPC.frame.Y = Math.Min(NPC.frame.Y, AnimationFrames * frameHeight); + NPC.frame.Y = Math.Min(NPC.frame.Y, _animationFrames * frameHeight); NPC.frameCounter = 0; - if (AnimationLoop) - NPC.frame.Y = NPC.frame.Y % (AnimationFrames * frameHeight); + if (_animationLoop) + NPC.frame.Y = NPC.frame.Y % (_animationFrames * frameHeight); } } @@ -613,36 +546,25 @@ namespace CalamityMod.NPCs.SunkenSea Vector2 anchorPoint = frame.Size() * 0.5f; SpriteEffects flip = NPC.spriteDirection == -1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None; - if (Personality == PersonalityType.Paranoid) - drawPosition += Main.rand.NextVector2Circular(1.5f, 1.5f); - - spriteBatch.Draw(texture, drawPosition, frame, NPC.GetAlpha(drawColor), NPC.rotation, anchorPoint, ScaleSquish, flip, 0f); + spriteBatch.Draw(texture, drawPosition, frame, NPC.GetAlpha(drawColor), NPC.rotation, anchorPoint, _scaleSquish, flip, 0f); return false; } #endregion - #region Syncing + #region Sycning + + private Vector2 _randomPathPoint; public override void SendExtraAI(BinaryWriter writer) { - base.SendExtraAI(writer); - writer.Write7BitEncodedInt(AnimationFrames); - writer.Write7BitEncodedInt(TimePerAnimationFrame); - writer.Write(AnimationLoop); - writer.Write(MaximumSpeed); - writer.Write7BitEncodedInt(RandomIdleMovementUnlikeliness); + writer.WriteVector2(_randomPathPoint); } public override void ReceiveExtraAI(BinaryReader reader) { - base.ReceiveExtraAI(reader); - AnimationFrames = reader.Read7BitEncodedInt(); - TimePerAnimationFrame = reader.Read7BitEncodedInt(); - AnimationLoop = reader.ReadBoolean(); - MaximumSpeed = reader.ReadSingle(); - RandomIdleMovementUnlikeliness = reader.Read7BitEncodedInt(); + _randomPathPoint = reader.ReadVector2(); } #endregion diff --git a/NPCs/SunkenSea/SunkenSeaNPC.cs b/NPCs/SunkenSea/SunkenSeaNPC.cs index ee29a2e843..1f1680f7a0 100644 --- a/NPCs/SunkenSea/SunkenSeaNPC.cs +++ b/NPCs/SunkenSea/SunkenSeaNPC.cs @@ -1,13 +1,10 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using CalamityMod.Enums; -using CalamityMod.Particles; using CalamityMod.Systems.Collections; using Microsoft.Xna.Framework; using Terraria; -using Terraria.Audio; using Terraria.GameContent.Bestiary; using Terraria.ID; using Terraria.ModLoader; @@ -16,182 +13,71 @@ using static Terraria.Utilities.NPCUtils; namespace CalamityMod.NPCs.SunkenSea { /// - /// An abstract class that gives an NPC the memebers needed to be a Sunken Sea NPC.
- /// These have the ability to hunt both players and NPCs, and also have a list of NPCs they hunt and avoid. + /// An abstract class that provides the necessary members for an NPC to function as a Sunken Sea NPC.
+ /// These NPCs can hunt both players and other NPCs, and maintain lists of NPCs they hunt and avoid. ///
public abstract class SunkenSeaNPC : ModNPC { - #region Fields & Properties + private NPC _currentPrey; + private NPC _currentPredator; + private Player _currentPlayer; /// - /// Since a lot of these NPCs change behaviors a lot, this abstract class provides an property to store and trigger behaviors.
- /// Automatically resets and to not cause errors. + /// A list of NPC IDs that this creature hunts. ///
- protected Action CurrentBehavior - { - get => _currentBehavior; - set - { - OnBehaviorChange(value); - - PathfindingPoints = null; - PathPointIndex = 0; - - PreviousBehavior = _currentBehavior; - _currentBehavior = value; - - NetUpdate(); - } - } - private Action _currentBehavior; + protected abstract List PreyIDs { get; } /// - /// The previous behavior that was used for . + /// A list of NPC IDs that this creature avoids. /// - protected Action PreviousBehavior { get; private set; } + protected abstract List PredatorIDs { get; } /// - /// A lot of these Sunken Sea creatures use the pathfinding algorithm,
- /// so this abstract class provides a so you can store the paths.
- /// Defaults to . + /// The biome flags that define where this Sunken Sea NPC can spawn. ///
- protected List PathfindingPoints { get; set; } + protected abstract SunkenSeaBiomeFlags BiomeDesignation { get; } /// - /// The probablity that this Sunken Sea NPC spawns given the conditions. - /// - protected abstract float SpawningChance { get; } - - protected int PathPointIndex { get; set; } - - private bool _hasSpawned; - - #region Targetting - - /// - /// A list which stores the NPC's IDs that this creature hunts. - /// - protected abstract List HuntNPCs { get; } - - /// - /// A list which stores the NPC's IDs that this creature avoids. - /// - protected abstract List AvoidNPCs { get; } - - /// - /// The current NPC that this creature has detected as prey. + /// The current NPC that this creature has identified as prey. /// protected NPC CurrentPrey { get => _currentPrey; private set { - if (value != _currentPrey && value != null) + if (value != null && (_currentPrey == null || _currentPrey.whoAmI != value.whoAmI)) OnPreyDetection(value); - _currentPrey = value; } } - private NPC _currentPrey; /// - /// The current NPC that this creature has detected as a predator. + /// The current NPC that this creature has identified as a predator. /// protected NPC CurrentPredator { get => _currentPredator; private set { - if (value != _currentPredator && value != null) + if (value != null && (_currentPredator == null || _currentPredator.whoAmI != value.whoAmI)) OnPredatorDetection(value); - _currentPredator = value; } } - private NPC _currentPredator; /// - /// The current Player that this creature has detected. + /// The current player that this creature has detected. /// protected Player CurrentPlayer { get => _currentPlayer; private set { - if (value != _currentPlayer && value != null) + if (value != null && (_currentPlayer == null || _currentPlayer.whoAmI != value.whoAmI)) OnPlayerDetection(value); - _currentPlayer = value; } } - private Player _currentPlayer; - - /// - /// The nearest entity detected, could be an NPC or Player. - /// - protected Entity NearestEntity { get; private set; } - - /// - /// The distance detection radius.
- /// Defaults to 300 pixels. - ///
- protected float DetectionDistance { get; set; } = 300f; - - /// - /// The direction of the cone used to detect targets.
- /// Defaults to times the direction.
- /// When set, it normalizes the vector. - ///
- protected Vector2 ConeDetectionDirection - { - get => _coneDetectionDirection; - set - { - _coneDetectionDirection = value.SafeNormalize(Vector2.UnitX * NPC.direction); - NetUpdate(); - } - } - private Vector2 _coneDetectionDirection; - - /// - /// How open the cone detection is -- given an angle.
- /// Defaults to 45 degrees. - ///
- protected float ConeDetectionAngle { get; set; } = MathHelper.ToRadians(45f); - - /// - /// When a this creature has lost sight of a target, it'll still have a sense of permanence.
- /// This means that, even if it can't see it, it can know it's there.
- /// This property states how much seconds it can know it's there.
- /// Defaults to 3 seconds. - ///
- protected virtual float PermanenceSenseTime => CalamityUtils.SecondsToFrames(3f); - private int _permanenceSenseTimer; - - /// - /// Whether or not the creature has detected anything at all. - /// - protected bool HasAnyTargets => CurrentPrey != null || CurrentPredator != null || CurrentPlayer != null; - - #endregion - - #region Biome Designation - - /// - /// The biomes that this Sunken Sea NPC belongs to. - /// - protected abstract SunkenSeaBiomeFlags BiomeDesignation { get; } - - /// - /// The spawn conditions for each biome that this Sunken Sea NPC belongs to. - /// - protected List> BiomeSpawnConditions { get; private set; } = []; - - #endregion - - #endregion - - #region ModNPC Overrides public override void SetStaticDefaults() { @@ -201,273 +87,108 @@ namespace CalamityMod.NPCs.SunkenSea public override void SetDefaults() { - List biomeTypes = []; - foreach (var flag in Enum.GetValues()) - { - if (flag == SunkenSeaBiomeFlags.None) - continue; + NPC.aiStyle = -1; + AIType = -1; - if (!BiomeDesignation.HasFlag(flag)) - continue; + SpawnModBiomes = Enum.GetValues() + .Where(flag => flag != SunkenSeaBiomeFlags.None && + flag != SunkenSeaBiomeFlags.UndergroundDesert && + BiomeDesignation.HasFlag(flag)) + .Select(flag => SunkenSeaBiomeCorrespondentDict.Dict[flag].BiomeType) + .ToArray(); - if (!SunkenSeaBiomeCorrespondentDict.TryGet(flag, out var spawnCondition, out var biomeType)) - continue; - - // Apply Conditions and Biome Types - BiomeSpawnConditions.Add(spawnCondition); - if (flag != SunkenSeaBiomeFlags.UndergroundDesert) - biomeTypes.Add(biomeType); - } - SpawnModBiomes = [.. biomeTypes]; + Banner = Type; } - public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry) => bestiaryEntry.Info.AddRange([new FlavorTextBestiaryInfoElement($"Mods.CalamityMod.Bestiary.{Name}")]); + public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry) + => bestiaryEntry.Info.AddRange([new FlavorTextBestiaryInfoElement($"Mods.CalamityMod.Bestiary.{Name}")]); - public override float SpawnChance(NPCSpawnInfo spawnInfo) + public override bool PreAI() { - if (BiomeSpawnConditions.Any(f => f.Invoke(spawnInfo)) && spawnInfo.Water && !spawnInfo.Player.Calamity().clamity) - return SpawningChance; - return 0f; - } - - public sealed override void AI() - { - if (!_hasSpawned) - { - _coneDetectionDirection = Vector2.UnitX * NPC.direction; - BehaviorOnSpawn(); - _hasSpawned = true; - NetUpdate(); - } - UpdateTargets(); - - CreatureAI(); + return true; } - #endregion - - #region Methods - /// - /// Same function as OnSpawn, but this one actually syncs to the server. + /// Called when this NPC is hit by another NPC. Override this method to define custom behavior when attacked. /// - protected virtual void BehaviorOnSpawn() { } - - /// - /// A method that is called on every frame, to put your actual enemy AI. - /// - protected virtual void CreatureAI() { } - - /// - /// A method that is triggered when this NPC's behavior is changed. - /// - protected virtual void OnBehaviorChange(Action newBehavior) { } - - /// - /// A custom method for when this NPC is hit by another NPC. - /// - /// + /// The NPC that attacked this creature. public virtual void OnHitByNPC(NPC attacker) { } /// - /// A method that is triggered when this creature has detected a prey. + /// Called when this creature detects a prey NPC. Override this method to define custom behavior upon detecting prey. /// + /// The NPC that has been detected as prey. protected virtual void OnPreyDetection(NPC prey) { } /// - /// A method that is triggered when this creature has detected a predator. + /// Called when this creature detects a predator NPC. Override this method to define custom behavior upon detecting a predator. /// + /// The NPC that has been detected as a predator. protected virtual void OnPredatorDetection(NPC predator) { } /// - /// A method that is triggered when this creature detects a player. + /// Called when this creature detects a player. Override this method to define custom behavior upon detecting a player. /// + /// The player that has been detected. protected virtual void OnPlayerDetection(Player player) { } /// - /// Whether or not a detected player is valid to be set as a target given some conditions. + /// Determines whether a detected player is a valid target based on specific conditions. /// - protected virtual bool PlayerSearchFilter(Player p) - { - if (!HasLineOfSight(p.Center)) - return false; - - bool isInsideCone = Vector2.Dot(_coneDetectionDirection, NPC.DirectionTo(p.Center)) >= MathF.Cos(ConeDetectionAngle) && NPC.DistanceSQ(p.Center) < DetectionDistance * DetectionDistance; - bool isInsideCirlceWhenAware = HasAnyTargets && NPC.DistanceSQ(p.Center) <= DetectionDistance * DetectionDistance; - if (isInsideCone || isInsideCirlceWhenAware) - return true; - - return false; - } + /// The player to evaluate. + /// if the NPC is a valid target; otherwise, . + protected virtual bool PlayerSearchFilter(Player p) => NPC.HasSight(p.Center) && Vector2.DistanceSquared(NPC.Center, p.Center) < 72900f; /// - /// Whether or not a detected NPC is valid to be set as a target given some conditions. + /// Determines whether a detected NPC is a valid target based on specific conditions. /// - protected virtual bool NPCSearchFilter(NPC n) - { - if (!HasLineOfSight(n.Center)) - return false; - - bool isInsideCone = Vector2.Dot(_coneDetectionDirection, NPC.DirectionTo(n.Center)) >= MathF.Cos(ConeDetectionAngle) && NPC.DistanceSQ(n.Center) < DetectionDistance * DetectionDistance; - bool isInsideCirlceWhenAware = HasAnyTargets && NPC.DistanceSQ(n.Center) <= DetectionDistance * DetectionDistance; - if (isInsideCone || isInsideCirlceWhenAware) - return true; - - return false; - } + /// The NPC to evaluate. + /// if the NPC is a valid target; otherwise, . + protected virtual bool NPCSearchFilter(NPC n) => NPC.HasSight(n.Center) && Vector2.DistanceSquared(NPC.Center, n.Center) < 72900f; /// - /// A method that finds and updates the current detected targets of this creature. + /// Updates the current targets of this creature, including prey, predators, and players, based on detection logic. /// protected void UpdateTargets() { var searchResults = SearchForTarget(NPC, playerFilter: PlayerSearchFilter, npcFilter: NPCSearchFilter); if (searchResults.FoundTarget) { - CurrentPlayer = searchResults.NearestTankOwner; - NearestEntity = searchResults.NearestTankOwner; - if (searchResults.FoundNPC) { - if (AvoidNPCs.Contains(searchResults.NearestNPC.type)) + if (PredatorIDs.Contains(searchResults.NearestNPC.type)) CurrentPredator = searchResults.NearestNPC; + else + CurrentPredator = null; - else if (HuntNPCs.Contains(searchResults.NearestNPC.type)) + if (PreyIDs.Contains(searchResults.NearestNPC.type)) CurrentPrey = searchResults.NearestNPC; - - if (searchResults.NearestNPCDistance < searchResults.NearestTankDistance) - NearestEntity = searchResults.NearestNPC; + else + CurrentPrey = null; } - NetUpdate(); + CurrentPlayer = searchResults.NearestTankOwner; } else { - _permanenceSenseTimer++; - if (_permanenceSenseTimer > PermanenceSenseTime) - { - CurrentPlayer = null; - NearestEntity = null; - CurrentPredator = null; - CurrentPrey = null; - _permanenceSenseTimer = 0; - } - } - } - - #endregion - - #region Helper Methods - - protected bool HasPath => PathfindingPoints is not null; - - protected bool SunkenSeaTileValidity(Point point) => - Main.tile[point].LiquidAmount > 125 && Main.tile[point].LiquidType == LiquidID.Water && NPC.DoesEntityFitInPath(point, 6, 6); - - /// - /// A quickhand method to follow a path found. - /// - protected void GenericPathFollowing(float acceleration) - { - Vector2 currentlyFollowedPathPoint = PathfindingPoints[PathPointIndex]; - - NPC.velocity += NPC.DirectionTo(currentlyFollowedPathPoint) * acceleration; - - if (NPC.DistanceSQ(currentlyFollowedPathPoint) < 48f * 48f) - { - PathPointIndex++; - PathPointIndex = (int)MathHelper.Clamp(PathPointIndex, 0, PathfindingPoints.Count - 1); - } - - if (PathPointIndex == PathfindingPoints.Count - 1) - { - PathPointIndex = 0; - PathfindingPoints = null; + CurrentPredator = null; + CurrentPrey = null; + CurrentPlayer = null; } } /// - /// A quick method to check whether this NPC has line of sight with something. + /// Checks whether a specific tile is valid for this NPC, considering water level and entity size. /// - protected bool HasLineOfSight(Vector2 position) => Collision.CanHitLine(NPC.Center, 0, 0, position, 0, 0); - - /// - /// Spawns an emote particle. - /// - protected void React(Color emoteColor, EmoteExpressionParticle.EmoteType emoteImage, SoundStyle? sound = null) + /// The tile location to check. + /// if the tile is valid; otherwise, . + protected bool SunkenSeaTileValidity(Point point) { - if (!Main.dedServ) - { - var emoteDirection = -Vector2.UnitY.RotatedByRandom(MathHelper.PiOver4) * Main.rand.NextFloat(2f, 3f); - Particle emote = new EmoteExpressionParticle( - NPC.Center + emoteDirection * 2f, - emoteDirection, - 2.2f, - emoteColor, - Main.rand.Next(30, 46), - emoteImage); - GeneralParticleHandler.SpawnParticle(emote); - - if (sound is not null) - SoundEngine.PlaySound(sound, NPC.Center); - } + Point actualFuckingPoint = new Point(point.X * 16, point.Y * 16); + return NPC.Hitbox.Contains(actualFuckingPoint) + || !NPC.GetIntersectingHitboxPoints( + actualFuckingPoint, 10, 10).Any(a => Main.tile[a].IsTileSolid() || Main.tile[a].LiquidAmount < 255 || Main.tile[a].LiquidType != LiquidID.Water); } - - #endregion - - #region Syncing - - /// - /// A quick method to both do and set .
- /// Defaults to 0. - ///
- protected void NetUpdate(int netSpam = 0) - { - NPC.netUpdate = true; - NPC.netSpam = netSpam; - } - - public override void SendExtraAI(BinaryWriter writer) - { - writer.Write7BitEncodedInt(CurrentPrey.whoAmI); - writer.Write7BitEncodedInt(CurrentPredator.whoAmI); - writer.Write7BitEncodedInt(CurrentPlayer.whoAmI); - writer.Write7BitEncodedInt(NearestEntity.whoAmI); - - writer.Write(DetectionDistance); - writer.WritePackedVector2(_coneDetectionDirection); - writer.Write(ConeDetectionAngle); - writer.Write7BitEncodedInt(_permanenceSenseTimer); - - writer.Write7BitEncodedInt(PathfindingPoints.Count); - foreach (var point in PathfindingPoints) - writer.WritePackedVector2(point); - writer.Write7BitEncodedInt(PathPointIndex); - - writer.Write(_hasSpawned); - } - - public override void ReceiveExtraAI(BinaryReader reader) - { - CurrentPrey.whoAmI = reader.Read7BitEncodedInt(); - CurrentPredator.whoAmI = reader.Read7BitEncodedInt(); - CurrentPlayer.whoAmI = reader.Read7BitEncodedInt(); - NearestEntity.whoAmI = reader.Read7BitEncodedInt(); - - DetectionDistance = reader.ReadSingle(); - _coneDetectionDirection = reader.ReadPackedVector2(); - ConeDetectionAngle = reader.ReadSingle(); - _permanenceSenseTimer = reader.Read7BitEncodedInt(); - - int count = reader.Read7BitEncodedInt(); - for (int i = 0; i < count; i++) - PathfindingPoints.Add(reader.ReadPackedVector2()); - PathPointIndex = reader.Read7BitEncodedInt(); - - _hasSpawned = reader.ReadBoolean(); - } - - #endregion } } diff --git a/Projectiles/Enemy/SharkoonExplosion.cs b/Projectiles/Enemy/SharkoonExplosion.cs index c672ea04e8..ce4efa0722 100644 --- a/Projectiles/Enemy/SharkoonExplosion.cs +++ b/Projectiles/Enemy/SharkoonExplosion.cs @@ -1,5 +1,6 @@ using CalamityMod.NPCs.SunkenSea; using Microsoft.Xna.Framework; +using Terraria; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Enemy @@ -13,12 +14,13 @@ namespace CalamityMod.Projectiles.Enemy public override void SetDefaults() { Projectile.hostile = true; - Projectile.friendly = true; Projectile.width = Projectile.height = Sharkoon.ExplosionRadius * 2; Projectile.timeLeft = 2; } public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, Sharkoon.ExplosionRadius, targetHitbox); + + public override bool? CanHitNPC(NPC target) => target.whoAmI != Projectile.ai[0]; } } diff --git a/Projectiles/Magic/EidolicWailSoundwave.cs b/Projectiles/Magic/EidolicWailSoundwave.cs index 0f15340a45..23316f5c74 100644 --- a/Projectiles/Magic/EidolicWailSoundwave.cs +++ b/Projectiles/Magic/EidolicWailSoundwave.cs @@ -72,7 +72,7 @@ namespace CalamityMod.Projectiles.Magic public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 240); + target.AddBuff(ModContent.BuffType(), 240); if (Projectile.numHits == 0) Projectile.velocity *= 0.4f; } diff --git a/Projectiles/Melee/NeptunesBountyProjectile.cs b/Projectiles/Melee/NeptunesBountyProjectile.cs index 4e6abc98df..bdb1bb90f6 100644 --- a/Projectiles/Melee/NeptunesBountyProjectile.cs +++ b/Projectiles/Melee/NeptunesBountyProjectile.cs @@ -256,7 +256,7 @@ namespace CalamityMod.Projectiles.Melee public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 300); + target.AddBuff(ModContent.BuffType(), 300); if (spinMode2 && Projectile.numHits == 0) { diff --git a/Projectiles/Melee/NeptunesBountySplitProjectile.cs b/Projectiles/Melee/NeptunesBountySplitProjectile.cs index b57d6e0f38..439bf42e1c 100644 --- a/Projectiles/Melee/NeptunesBountySplitProjectile.cs +++ b/Projectiles/Melee/NeptunesBountySplitProjectile.cs @@ -81,7 +81,7 @@ namespace CalamityMod.Projectiles.Melee public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 240); + target.AddBuff(ModContent.BuffType(), 240); } } } diff --git a/Projectiles/Ranged/TheMaelstromExplosion.cs b/Projectiles/Ranged/TheMaelstromExplosion.cs index b2ae9a476e..e8a8318177 100644 --- a/Projectiles/Ranged/TheMaelstromExplosion.cs +++ b/Projectiles/Ranged/TheMaelstromExplosion.cs @@ -61,9 +61,9 @@ namespace CalamityMod.Projectiles.Ranged } } - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 180); + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 180); - public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType(), 180); + public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType(), 180); public override bool PreDraw(ref Color lightColor) { diff --git a/Projectiles/Rogue/DeepSeaDumbbell1.cs b/Projectiles/Rogue/DeepSeaDumbbell1.cs index 7c58cfb78b..0d9fcd7c32 100644 --- a/Projectiles/Rogue/DeepSeaDumbbell1.cs +++ b/Projectiles/Rogue/DeepSeaDumbbell1.cs @@ -72,7 +72,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 240); + target.AddBuff(ModContent.BuffType(), 240); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); @@ -112,7 +112,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitPlayer(Player target, Player.HurtInfo info) { - target.AddBuff(ModContent.BuffType(), 240); + target.AddBuff(ModContent.BuffType(), 240); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); diff --git a/Projectiles/Rogue/DeepSeaDumbbell2.cs b/Projectiles/Rogue/DeepSeaDumbbell2.cs index 6a1671bc6e..5bfb9bcbc1 100644 --- a/Projectiles/Rogue/DeepSeaDumbbell2.cs +++ b/Projectiles/Rogue/DeepSeaDumbbell2.cs @@ -79,7 +79,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 180); + target.AddBuff(ModContent.BuffType(), 180); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); @@ -119,7 +119,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitPlayer(Player target, Player.HurtInfo info) { - target.AddBuff(ModContent.BuffType(), 180); + target.AddBuff(ModContent.BuffType(), 180); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); diff --git a/Projectiles/Rogue/DeepSeaDumbbell3.cs b/Projectiles/Rogue/DeepSeaDumbbell3.cs index f1f25a14da..c4bb1358bb 100644 --- a/Projectiles/Rogue/DeepSeaDumbbell3.cs +++ b/Projectiles/Rogue/DeepSeaDumbbell3.cs @@ -71,7 +71,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 120); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); @@ -105,7 +105,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitPlayer(Player target, Player.HurtInfo info) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 120); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); diff --git a/Projectiles/Rogue/DeepSeaDumbbellWeight.cs b/Projectiles/Rogue/DeepSeaDumbbellWeight.cs index c5953a8397..dc4d6fb937 100644 --- a/Projectiles/Rogue/DeepSeaDumbbellWeight.cs +++ b/Projectiles/Rogue/DeepSeaDumbbellWeight.cs @@ -57,12 +57,12 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 120); } public override void OnHitPlayer(Player target, Player.HurtInfo info) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 120); } } } diff --git a/Projectiles/Rogue/JawsProjectile.cs b/Projectiles/Rogue/JawsProjectile.cs index 912353b6be..25b55a5c37 100644 --- a/Projectiles/Rogue/JawsProjectile.cs +++ b/Projectiles/Rogue/JawsProjectile.cs @@ -64,7 +64,7 @@ namespace CalamityMod.Projectiles.Rogue target.AddBuff(ModContent.BuffType(), 120); if (Projectile.Calamity().stealthStrike) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 120); Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), Projectile.damage, 10f, Projectile.owner, 0, 0); } } @@ -76,8 +76,8 @@ namespace CalamityMod.Projectiles.Rogue target.AddBuff(ModContent.BuffType(), 120); if (Projectile.Calamity().stealthStrike) { - target.AddBuff(ModContent.BuffType(), 120); Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), Projectile.damage, 10f, Projectile.owner, 0, 0); + target.AddBuff(ModContent.BuffType(), 120); } } diff --git a/Projectiles/Rogue/JawsShockwave.cs b/Projectiles/Rogue/JawsShockwave.cs index 41437e9836..b1eb5e72ba 100644 --- a/Projectiles/Rogue/JawsShockwave.cs +++ b/Projectiles/Rogue/JawsShockwave.cs @@ -58,9 +58,9 @@ namespace CalamityMod.Projectiles.Rogue } } - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 240); + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 240); - public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType(), 240); + public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType(), 240); public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, 160f, targetHitbox); } diff --git a/Projectiles/Rogue/ValedictionBoomerang.cs b/Projectiles/Rogue/ValedictionBoomerang.cs index 739bd2364b..a06515a9e8 100644 --- a/Projectiles/Rogue/ValedictionBoomerang.cs +++ b/Projectiles/Rogue/ValedictionBoomerang.cs @@ -121,13 +121,13 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 180); + target.AddBuff(ModContent.BuffType(), 180); OnHitEffects(); } public override void OnHitPlayer(Player target, Player.HurtInfo info) { - target.AddBuff(ModContent.BuffType(), 180); + target.AddBuff(ModContent.BuffType(), 180); OnHitEffects(); } diff --git a/Projectiles/Summon/CalamarisLamentMinion.cs b/Projectiles/Summon/CalamarisLamentMinion.cs index 867337a78c..c18b37282d 100644 --- a/Projectiles/Summon/CalamarisLamentMinion.cs +++ b/Projectiles/Summon/CalamarisLamentMinion.cs @@ -1,4 +1,5 @@ -using CalamityMod.Buffs.Summon; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Buffs.Summon; using CalamityMod.Items.Weapons.Summon; using CalamityMod.Projectiles.BaseProjectiles; using Microsoft.Xna.Framework; @@ -211,6 +212,8 @@ namespace CalamityMod.Projectiles.Summon // The minion will only have contact damage if it's on latching mode. public override bool MinionContactDamage() => State == AIState.Latching; + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 240); + // The minion will do 1.5x damage if it's latched on. public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) => modifiers.SourceDamage *= CalamarisLament.LatchingDamageMultiplier; diff --git a/Projectiles/Summon/CalamarisLamentProjectile.cs b/Projectiles/Summon/CalamarisLamentProjectile.cs index fc710a4973..6b89f77c5d 100644 --- a/Projectiles/Summon/CalamarisLamentProjectile.cs +++ b/Projectiles/Summon/CalamarisLamentProjectile.cs @@ -1,4 +1,5 @@ -using CalamityMod.Items.Weapons.Summon; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Items.Weapons.Summon; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -72,6 +73,8 @@ namespace CalamityMod.Projectiles.Summon // and hit DoG's head and/or tail reliably and without penetration. public override bool? CanDamage() => Projectile.getRect().Intersects(TargetShot.getRect()) ? null : false; + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 120); + public override void OnKill(int timeLeft) { for (int i = 0; i < 15; i++) diff --git a/Utilities/NPCUtils.cs b/Utilities/NPCUtils.cs index bddf8b9e8d..b035594a15 100644 --- a/Utilities/NPCUtils.cs +++ b/Utilities/NPCUtils.cs @@ -893,6 +893,8 @@ namespace CalamityMod return false; } + public static bool HasSight(this NPC npc, Vector2 target) => Collision.CanHit(npc.Center, 1, 1, target, 1, 1); + #region Boss Spawning /// /// Shortcut for the generic boss summon message. diff --git a/Utilities/PathfindingUtils.cs b/Utilities/PathfindingUtils.cs index c157e2ddcf..b4143f8482 100644 --- a/Utilities/PathfindingUtils.cs +++ b/Utilities/PathfindingUtils.cs @@ -1,13 +1,316 @@ using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; +using CalamityMod.Projectiles.Typeless; using Microsoft.Xna.Framework; using Terraria; +using static CalamityMod.CalamityUtils; namespace CalamityMod { + /// + /// Represents an entity that is capable of finding and following a complex path.
+ /// To use this interface, supply all of the required properties, and then simply call this.DoPathfinding() in your entity's movement logic. + ///
+ public interface IPathFinder + { + /// + /// Represents the working task for calculating this entity's complex path.
+ ///
+ /// If you want to manually access the result of this task, make sure to check before accessing the value of .
+ ///
+ /// Accessing before execution has completed will result in the calling thread being blocked until execution is complete. + ///
+ public PathfindingTask Path { get; set; } + + /// + /// The current position of this entity. Only used to calculate movement for this entity, not pathfinding.
+ /// In most cases, this should look like the following, where ENTITY is replace by your entity instance. + /// public Vector2 Position { get => ENTITY.center; } + ///
+ public Vector2 Position { get; } + + /// + /// The current velocity of this entity. Only used to calculate movement for this entity, not pathfinding.
+ /// In most cases, this should look like the following, where ENTITY is replace by your entity instance. + /// public Vector2 Velocity { get => ENTITY.velocity; } + ///
+ public Vector2 Velocity { get; set; } + + /// + /// The acceleration this entity should use when moving. Only used to calculate movement for this entity, not pathfinding. + /// + public float Acceleration { get; } + + /// + /// The maximum speed this entity should be able to reach while moving. Only used to calculate movement for this entity, not pathfinding. + /// + public float MaxSpeed { get; } + + /// + /// Defines how this entity should move to the next point. Contains a default implementation with basic acceleration towards the next point.
+ /// This method should return when the entity has reached its target point, and otherwise.
+ ///
+ /// The target point is specified by - usually index 0 in the task result. + ///
+ /// + /// + public bool FollowPath(Vector2 nextPoint) + { + // Accelerate to the target point. + Velocity += (nextPoint - Position).SafeNormalize(Vector2.Zero) * Acceleration; + + // Cap the speed if MaxSpeed has been surpassed. + if (Velocity.LengthSquared() > MaxSpeed * MaxSpeed) + Velocity = Velocity.SafeNormalize(Vector2.UnitY) * MaxSpeed; + + // If the entity is within 48 pixels of its target point, consider the point reached. + if (Vector2.DistanceSquared(Position, nextPoint) < 48f * 48f) + return true; + + // Otherwise, continue following. + return false; + } + + /// + /// Defines how this entity should behave while there is no current path to follow.
+ /// By default, decelerates and stops based on . + ///
+ public void IdleBehavior() => Velocity *= 0.95f; + + /// + /// Assigns the value of to and executes the pathfinding calculations on a background thread.
+ /// You can override this to do your own modifications to the pathfinding task before assigning and starting the calculations. + ///
+ public void FindPath(PathfindingTask pathfindingTask) + { + if (pathfindingTask == null) + return; + + Path = pathfindingTask; + Path.Run(); + } + } + + /// + /// Represents a task for calculating a complex path.
+ /// Allows for synchronous access to an asynchronous execution state, while still providing blocking access where needed. + ///
+ public class PathfindingTask( + Vector2 start, + Vector2 end, + Func tileValidity = null, + Func distanceFunction = null, + Func heuristic = null) + { + public PathfindingTask(Vector2 start, Vector2 end) : this(start, end, null, null, null) + { } + + /// + /// The result of this pathfinding task. + /// + public List Result { get => _task.Task.Result; } + + /// + /// Whether this pathfinding task has completed running. + /// + public bool Ready { get; private set; } = false; + + /// + /// Whether this pathfinding task is still currently running. + /// + public bool Running { get; private set; } = false; + + /// + /// The starting position of this pathfinding task. + /// + public Vector2 StartPosition { get; init; } = start; + + /// + /// The ending position of this pathfinding task. + /// + public Vector2 EndPosition { get; init; } = end; + + // Interal task representation of the work. + private readonly TaskCompletionSource> _task = new(); + + // Internal containing object for the actual work. + private readonly PathfindingWork _work = new(start, end, tileValidity, distanceFunction, heuristic); + + /// + /// Begins execution of this pathfinding task on a background thread. + /// + public void Run() + { + Running = true; + + ThreadPool.QueueUserWorkItem((pathfindingTask) => + { + var task = pathfindingTask as PathfindingTask; + task._task.TrySetResult(task._work.CalculatePath()); + + task.Ready = true; + task.Running = false; + }, + this); + } + } + public static partial class CalamityUtils { + /// + /// Causes this to perform path finding and follow the path result, idling when a path is not available.
+ /// This method should be called every frame that you want your entity to follow it's pathfinding logic. + ///
+ public static void DoPathfinding(this IPathFinder pathfinder, Vector2 target) => pathfinder.DoPathfinding(new PathfindingTask(pathfinder.Position, target)); + + /// + /// Causes this to perform path finding and follow the path result, idling when a path is not available.
+ /// This method should be called every frame that you want your entity to follow it's pathfinding logic. + ///
+ public static void DoPathfinding(this IPathFinder pathfinder, PathfindingTask task, bool continuouslyUpdatePath = false) + { + // If the task has been started but is not finished yet, just idle. + if (pathfinder.Path?.Running ?? false) + pathfinder.IdleBehavior(); + + // If the task has not been started, + // or was previously unable to find a path, + // OR is now being told to follow a new path... + // + // start the task (potentially again). + else if (pathfinder.Path == null || // Not started + pathfinder.Path.Result == null || // Unable to find previous path + pathfinder.Path.Result.Count == 0 || // Previous path is done being followed + (continuouslyUpdatePath && pathfinder.Path.EndPosition != task.EndPosition)) // New path + { + pathfinder.FindPath(task); + pathfinder.IdleBehavior(); + } + + // Otherwise, the task has been started, completed, and found a valid path. + // Follow the found path. + else + { + // Follows the point at index 0 of the path result. + Vector2 nextPoint = pathfinder.Path.Result[0]; + + // Once that point is reached, it is removed from the list of points to follow. + if (pathfinder.FollowPath(nextPoint)) + pathfinder.Path.Result.RemoveAt(0); + } + } + + /// + /// Represents the working computation for a . + /// + /// + /// + /// Has 2 overloads, one for inputting the start and end nodes as , and the other one as . + /// + /// + /// This record contains the start and end nodes, along with functions for tile validity, distance calculation, and heuristic estimation. + /// + /// + /// - : A function that checks if a tile at a given point is valid for traversal. If not provided, all non-solid tiles are considered valid.
+ /// - : A function that calculates the distance between two points. Defaults to .
+ /// - : A function that estimates the cost from a given point to the end point. Defaults to .
+ ///
+ ///
+ public record PathfindingWork(Node Start, Node End, Func TileValidity, Func DistanceFunction, Func Heuristic) + { + private static readonly Func DefaultTileValidity = point => true; + private static readonly Func DefaultDistanceFunction = OctileDistance; + private static readonly Func DefaultHeuristic = OctileDistance; + + public PathfindingWork( + Point start, + Point end, + Func tileValidity = null, + Func distanceFunction = null, + Func heuristic = null) : this( + new Node(start), + new Node(end), + tileValidity ?? DefaultTileValidity, + distanceFunction ?? DefaultDistanceFunction, + heuristic ?? DefaultHeuristic + ) + { + } + + public PathfindingWork( + Vector2 start, + Vector2 end, + Func tileValidity = null, + Func distanceFunction = null, + Func heuristic = null) : this( + new Node(start.ToTileCoordinates()), + new Node(end.ToTileCoordinates()), + tileValidity ?? DefaultTileValidity, + distanceFunction ?? DefaultDistanceFunction, + heuristic ?? DefaultHeuristic + ) + { + } + + /// + /// Calculates a path from the start to the end position using the A* pathfinding algorithm. + /// + /// + /// + /// A list of positions representing the path from start to end, or if no path is found. + /// + public List CalculatePath() + { + if (Main.tile[End.Position].IsTileSolid()) + return null; + + var openSet = new List(); + var closedSet = new HashSet(); + openSet.Add(Start); + + while (openSet.Count > 0) + { + // Get the node with the lowest F value. + var current = openSet[0]; + for (int i = 1; i < openSet.Count; i++) + { + if (openSet[i].F < current.F || (openSet[i].F == current.F && openSet[i].H < current.H)) + current = openSet[i]; + } + + openSet.Remove(current); + closedSet.Add(current); + + // Check if we've reached the goal. + if (current.Position == End.Position) + return current.ReconstructPath(); + + // Generate neighbors. + foreach (var neighbor in current.GetNeighbors()) + { + if (closedSet.Contains(neighbor) || Main.tile[neighbor.Position].IsTileSolid() || !TileValidity.Invoke(neighbor.Position)) + continue; + + float tentativeG = current.G + DistanceFunction.Invoke(current.Position, neighbor.Position); + + if (!openSet.Contains(neighbor) || tentativeG < neighbor.G) + { + neighbor.Parent = current; + neighbor.G = tentativeG; + neighbor.H = Heuristic.Invoke(neighbor.Position, End.Position); + + if (!openSet.Contains(neighbor)) + openSet.Add(neighbor); + } + } + } + + return null; // No path found. + } + } + /// /// Represents a node in a pathfinding algorithm, containing position, cost, and parent information. /// @@ -27,169 +330,42 @@ namespace CalamityMod } public override int GetHashCode() => Position.GetHashCode(); - } - /// - /// Represents the parameters required for the method. - /// - /// - /// - /// Has 2 overloads, one for inputting the start and end nodes as , and the other one as . - /// - /// - /// This record contains the start and end nodes, along with functions for tile validity, distance calculation, and heuristic estimation. - /// - /// - /// - : A function that checks if a tile at a given point is valid for traversal. If not provided, all non-solid tiles are considered valid.
- /// - : A function that calculates the distance between two points. Defaults to .
- /// - : A function that estimates the cost from a given point to the end point. Defaults to .
- ///
- ///
- public record PathfindingParams(Node Start, Node End, Func TileValidity, Func DistanceFunction, Func Heuristic) - { - private static readonly Func DefaultTileValidity = point => true; - private static readonly Func DefaultDistanceFunction = OctileDistance; - private static readonly Func DefaultHeuristic = OctileDistance; - - public PathfindingParams( - Point start, - Point end, - Func tileValidity = null, - Func distanceFunction = null, - Func heuristic = null) : this( - new Node(start), - new Node(end), - tileValidity ?? DefaultTileValidity, - distanceFunction ?? DefaultDistanceFunction, - heuristic ?? DefaultHeuristic - ) + public List GetNeighbors() { - } + var neighbors = new List(Directions.Count); - public PathfindingParams( - Vector2 start, - Vector2 end, - Func tileValidity = null, - Func distanceFunction = null, - Func heuristic = null) : this( - new Node(start.ToTileCoordinates()), - new Node(end.ToTileCoordinates()), - tileValidity ?? DefaultTileValidity, - distanceFunction ?? DefaultDistanceFunction, - heuristic ?? DefaultHeuristic - ) - { - } - } + int nodeX = Position.X; + int nodeY = Position.Y; - /// - /// Asynchronously finds a path from the start to the end position using the A* pathfinding algorithm. - /// - /// - /// The parameters for the pathfinding algorithm, including start, end, and cost functions. - /// - /// - /// A task that represents the asynchronous operation.
The task result contains a list of positions - /// representing the path from start to end, or if no path is found. - ///
- /// - /// - /// - /// This method runs the pathfinding calculations on a separate CPU thread using .
- /// Use to check if the pathfinding is complete, and - /// to retrieve the resulting path. - ///
- ///
- /// - /// - /// - /// var parameters = new PathfindingParams(start, end, TileValidity, DistanceFunction, Heuristic); - /// var pathTask = FindPathAsync(parameters); - /// if (pathTask.Result != null) - /// PathPoints = pathTask.Result; - /// - /// - public static async Task> FindPathAsync(PathfindingParams parameters) - { - return await Task.Run(() => - { - var openSet = new List(); - var closedSet = new HashSet(); - openSet.Add(parameters.Start); - - while (openSet.Count > 0) + foreach (var direction in Directions) { - // Get the node with the lowest F value. - var current = openSet[0]; - for (int i = 1; i < openSet.Count; i++) - { - if (openSet[i].F < current.F || (openSet[i].F == current.F && openSet[i].H < current.H)) - current = openSet[i]; - } + int newX = nodeX + (int)direction.X; + int newY = nodeY + (int)direction.Y; - openSet.Remove(current); - closedSet.Add(current); - - // Check if we've reached the goal. - if (current.Position == parameters.End.Position) - return ReconstructPath(current); - - // Generate neighbors. - foreach (var neighbor in GetNeighbors(current)) - { - if (closedSet.Contains(neighbor) || Main.tile[neighbor.Position].IsTileSolid() || !parameters.TileValidity.Invoke(neighbor.Position)) - continue; - - float tentativeG = current.G + parameters.DistanceFunction.Invoke(current.Position, neighbor.Position); - - if (!openSet.Contains(neighbor) || tentativeG < neighbor.G) - { - neighbor.Parent = current; - neighbor.G = tentativeG; - neighbor.H = parameters.Heuristic.Invoke(neighbor.Position, parameters.End.Position); - - if (!openSet.Contains(neighbor)) - openSet.Add(neighbor); - } - } + if (WorldGen.InWorld(newX, newY)) + neighbors.Add(new Node(new Point(newX, newY))); } - return null; // No path found. - }); - } - - private static List GetNeighbors(Node node) - { - var neighbors = new List(Directions.Count); - - int nodeX = node.Position.X; - int nodeY = node.Position.Y; - - foreach (var direction in Directions) - { - int newX = nodeX + (int)direction.X; - int newY = nodeY + (int)direction.Y; - - if (WorldGen.InWorld(newX, newY)) - neighbors.Add(new Node(new Point(newX, newY))); + return neighbors; } - return neighbors; - } - - private static List ReconstructPath(Node node) - { - var pathStack = new Stack(); - while (node != null) + public List ReconstructPath() { - pathStack.Push(node.Position.ToWorldCoordinates()); - node = node.Parent; + var pathStack = new Stack(); + var node = this; + + while (node != null) + { + pathStack.Push(node.Position.ToWorldCoordinates()); + node = node.Parent; + } + + var path = new List(pathStack.Count); + path.AddRange(pathStack); + + return path; } - - var path = new List(pathStack.Count); - path.AddRange(pathStack); - - return path; } #region Heuristic Functions @@ -239,5 +415,26 @@ namespace CalamityMod return doesFit; } + + public static List GetIntersectingHitboxPoints(this Entity entity, Point position, int fluffX = 0, int fluffY = 0) + { + Rectangle hitbox = entity.Hitbox; + hitbox.Location = new Point(position.X - hitbox.Width / 2, position.Y - hitbox.Height / 2); + hitbox.Inflate(fluffX, fluffY); + + int startX = (int)MathF.Floor(hitbox.Left / 16); + int endX = (int)Math.Floor((hitbox.Right - float.Epsilon) / 16); + int startY = (int)MathF.Floor(hitbox.Top / 16); + int endY = (int)Math.Floor((hitbox.Bottom - float.Epsilon) / 16); + + List intersectingPoints = []; + for (int i = startX; i <= endX; i++) + { + for (int j = startY; j <= endY; j++) + intersectingPoints.Add(new Point(i, j)); + } + + return intersectingPoints; + } } }