From 523a712987da75af1ed7944176b0fd39a73d6cb0 Mon Sep 17 00:00:00 2001 From: Memes <114233643+Mr-Memes@users.noreply.github.com> Date: Mon, 10 Feb 2025 12:08:44 +0100 Subject: [PATCH] Major change to IPathFinder. 1. Fixed lag in IPathFinder. 2. Deleted Pathfinding property in IPathFinder. 3. Improvements to SunkenSeaNPC to fit IPathFinder. 4. Adaptation of Probesnaut and Sharkoon to the new changes. --- NPCs/SunkenSea/Probesnout.cs | 249 ++++++------ NPCs/SunkenSea/Sharkoon.cs | 531 +++++++++++-------------- NPCs/SunkenSea/SunkenSeaNPC.cs | 425 ++++---------------- Projectiles/Enemy/SharkoonExplosion.cs | 4 +- Utilities/NPCUtils.cs | 2 + Utilities/PathfindingUtils.cs | 55 ++- 6 files changed, 445 insertions(+), 821 deletions(-) diff --git a/NPCs/SunkenSea/Probesnout.cs b/NPCs/SunkenSea/Probesnout.cs index 4ef95c1c49..adaa978d5f 100644 --- a/NPCs/SunkenSea/Probesnout.cs +++ b/NPCs/SunkenSea/Probesnout.cs @@ -3,51 +3,44 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using CalamityMod.Enums; -using CalamityMod.Particles; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; +using Terraria.DataStructures; using Terraria.GameContent; using Terraria.ID; -using Terraria.Utilities; +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 +59,157 @@ 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 + { + if (value != _currentBehavior) + OnBehaviorChange(value); + _previousBehavior = _currentBehavior; + _currentBehavior = value; + } + } + + private Action _previousBehavior; + + public Task> Paths { 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; + #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.X * 3f); + NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); - NPC.rotation = MathHelper.ToRadians(NPC.velocity.Length() * 3f) * MathF.Sign(NPC.velocity.X); - if (MathF.Abs(NPC.velocity.X) > 2f) - NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); if (!NPC.wet) CurrentBehavior = OutsideWaterBehavior; - if (NPC.velocity.LengthSquared() > MaximumSpeed * MaximumSpeed) - NPC.velocity = NPC.velocity.SafeNormalize(-Vector2.UnitY) * MaximumSpeed; - if (ScaleSquish.Y > 1f) + { ScaleSquish.Y -= 0.025f; - - if (ScaleSquish.Y < 1f) - ScaleSquish.Y = 1f; + if (ScaleSquish.Y < 1f) + ScaleSquish.Y = 1f; + } } - protected override void OnBehaviorChange(Action newBehavior) => NPC.noGravity = newBehavior != OutsideWaterBehavior; + private 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. + PathfindingParams parameters = null; + if (Main.rand.NextBool(IdleRandomMovementUnlikeliness)) { - 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() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance); + NPC.netUpdate = true; + parameters = new PathfindingParams(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; - - if (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 (!Collision.CanHitLine(NPC.Center, 1, 1, NPC.Center + CurrentPredator.DirectionTo(NPC.Center) * 120f, 1, 1)) { - 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); - - + _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * 80f; + NPC.netUpdate = true; + this.DoPathfinding(new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); } else - GenericPathFollowing(acceleration: 0.14f); + { + NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; + Paths = 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 +217,24 @@ 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)) - { - if (HasPath) - GenericPathFollowing(acceleration: 0.14f); - 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 PathfindingParams(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); else - NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * 0.14f; + NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; } private void OutsideWaterBehavior() { if (NPC.wet) - CurrentBehavior = PreviousBehavior; + { + NPC.noGravity = true; + CurrentBehavior = _previousBehavior; + } } #endregion @@ -274,7 +257,7 @@ namespace CalamityMod.NPCs.SunkenSea { Texture2D texture = TextureAssets.Npc[Type].Value; Vector2 drawPosition = NPC.Center - screenPos; - Rectangle frame = texture.Frame(horizontalFrames: 2, verticalFrames: 12, frameX: (int)Animation, frameY: NPC.frame.Y / NPC.height); + Rectangle frame = texture.Frame(horizontalFrames: 2, verticalFrames: 12, frameX: (int)Animation, frameY: NPC.frame.Y / 44); Vector2 anchorPoint = frame.Size() * 0.5f; SpriteEffects flip = NPC.spriteDirection == 1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None; @@ -301,32 +284,28 @@ namespace CalamityMod.NPCs.SunkenSea 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.width = 32; + NPC.height = 32; } #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 diff --git a/NPCs/SunkenSea/Sharkoon.cs b/NPCs/SunkenSea/Sharkoon.cs index 74c11e6a09..b3bf5326f1 100644 --- a/NPCs/SunkenSea/Sharkoon.cs +++ b/NPCs/SunkenSea/Sharkoon.cs @@ -9,59 +9,34 @@ 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 static CalamityMod.CalamityUtils; using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea { 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; - #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. @@ -99,8 +74,6 @@ namespace CalamityMod.NPCs.SunkenSea ChangeAnimation(animationFrames: 6, timePerAnimationFrame: 6, loops: true); break; } - - NetUpdate(); } } @@ -108,46 +81,81 @@ 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]; - /// - /// 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(), + ]; + + protected override List PredatorIDs => + [ + // NPCType(), + // NPCType(), + NPCType(), + // NPCType, + ]; + protected override SunkenSeaBiomeFlags BiomeDesignation => SunkenSeaBiomeFlags.RadiantReefs; - protected override float SpawningChance => SpawnCondition.CaveJellyfish.Chance * 0.9f; + #endregion - public CalamityUtils.PathfindingParams Pathfinding { get; set; } + #region IPathFinder Implementation public Task> Paths { get; set; } @@ -157,16 +165,13 @@ namespace CalamityMod.NPCs.SunkenSea public float Acceleration { get; set; } = 0.25f; - public float MaxSpeed { get; set; } = 4f; - - /// - /// The squish of this NPC while drawing. - /// - private Vector2 ScaleSquish = Vector2.One; + public float MaxSpeed { get; set; } = 6f; #endregion - #region Other Overridden Methods + #endregion + + #region SetDefaults public override void SetStaticDefaults() { @@ -184,8 +189,6 @@ namespace CalamityMod.NPCs.SunkenSea NPC.knockBackResist = 0.15f; NPC.chaseable = false; - NPC.aiStyle = -1; - AIType = -1; NPC.width = 52; NPC.height = 46; NPC.noGravity = true; @@ -193,8 +196,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 +203,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) { - CurrentBehavior = IdlingBehavior; + return base.PlayerSearchFilter(p) || p == CurrentPlayer && Vector2.DistanceSquared(NPC.Center, p.Center) < 960f * 960f; + } - 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) - MaxSpeed *= 1.5f; + 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(); - // 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,86 +245,29 @@ namespace CalamityMod.NPCs.SunkenSea if (!NPC.wet && !IsExploding) CurrentBehavior = OutsideWaterBehavior; - 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() { - // Randomly, it'll decide a path whose destination is somewhere around him. - if (Main.rand.NextBool(RandomIdleMovementUnlikeliness)) - Pathfinding = new(NPC.Center, Main.rand.NextVector2Circular(400f, 400f), SunkenSeaTileValidity); - - // While it hasn't decided yet which path to follow, it'll deaccelerate and stand still. - else - Pathfinding = null; - - this.DoPathfinding(); + // At random, the mob will choose a random nearby point and pathfind there. + PathfindingParams parameters = null; + if (Main.rand.NextBool(IdleRandomMovementUnlikeliness)) + { + _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance); + NPC.netUpdate = true; + parameters = new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); + } + this.DoPathfinding(parameters); } - private void HuntBehavior() + private void HuntingBehavior() { // If there's no more prey, go back to idling. if (CurrentPrey is null) @@ -400,68 +276,46 @@ namespace CalamityMod.NPCs.SunkenSea return; } - if (!HasLineOfSight(CurrentPrey.Center)) - { - Pathfinding = new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity); - this.DoPathfinding(); - } - + // With sight, just go straight at him. Without it, try to pathfind over them. + if (!NPC.HasSight(CurrentPrey.Center)) + this.DoPathfinding(new PathfindingParams(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); else NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; } - private void AvoidBehavior() - { - // 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; - } - // If there aren't any more targets detected, go back to idling. - if (entityToAvoid is null) + private void FleeingBehavior() + { + // Check who is the avoided entity specifically. + _avoidedEntity = _avoidedEntity is NPC ? CurrentPredator : CurrentPlayer; + + // 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; - Pathfinding = 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 PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); } - // Attempt to path find through an escape route. - this.DoPathfinding(); - - // If one couldn't be found, just try to swim away. - if (Paths.IsCompleted && Paths.Result == null) - 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; } @@ -481,16 +335,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. @@ -500,12 +354,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; @@ -521,10 +373,92 @@ 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; + } + + 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.whoAmI != NPC.whoAmI; + + 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) @@ -534,11 +468,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) @@ -564,8 +500,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 @@ -577,21 +511,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); } } @@ -603,36 +537,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(MaxSpeed); - writer.Write7BitEncodedInt(RandomIdleMovementUnlikeliness); + writer.WriteVector2(_randomPathPoint); } public override void ReceiveExtraAI(BinaryReader reader) { - base.ReceiveExtraAI(reader); - AnimationFrames = reader.Read7BitEncodedInt(); - TimePerAnimationFrame = reader.Read7BitEncodedInt(); - AnimationLoop = reader.ReadBoolean(); - MaxSpeed = reader.ReadSingle(); - RandomIdleMovementUnlikeliness = reader.Read7BitEncodedInt(); + _randomPathPoint = reader.ReadVector2(); } #endregion diff --git a/NPCs/SunkenSea/SunkenSeaNPC.cs b/NPCs/SunkenSea/SunkenSeaNPC.cs index ee29a2e843..03b84f2512 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()) + NPC.aiStyle = -1; + AIType = -1; + + SpawnModBiomes = Enum.GetValues() + .Where(flag => flag != SunkenSeaBiomeFlags.None && + flag != SunkenSeaBiomeFlags.UndergroundDesert && + BiomeDesignation.HasFlag(flag)) + .Select(flag => SunkenSeaBiomeCorrespondentDict.Dict[flag].BiomeType) + .ToArray(); + + try { - if (flag == SunkenSeaBiomeFlags.None) - continue; - - if (!BiomeDesignation.HasFlag(flag)) - continue; - - 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); + Banner = Type; + BannerItem = ModContent.Find($"{Name}Banner").Type; + } + catch (Exception ex) + { + CalamityMod.Instance.Logger.Warn(ex); } - SpawnModBiomes = [.. biomeTypes]; } - 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) { + if (PredatorIDs.Contains(searchResults.NearestNPC.type)) + CurrentPredator = searchResults.NearestNPC; + else + CurrentPredator = null; + + if (PreyIDs.Contains(searchResults.NearestNPC.type)) + CurrentPrey = searchResults.NearestNPC; + else + CurrentPrey = null; + CurrentPlayer = searchResults.NearestTankOwner; - NearestEntity = searchResults.NearestTankOwner; - - if (searchResults.FoundNPC) - { - if (AvoidNPCs.Contains(searchResults.NearestNPC.type)) - CurrentPredator = searchResults.NearestNPC; - - else if (HuntNPCs.Contains(searchResults.NearestNPC.type)) - CurrentPrey = searchResults.NearestNPC; - - if (searchResults.NearestNPCDistance < searchResults.NearestTankDistance) - NearestEntity = searchResults.NearestNPC; - } - - NetUpdate(); } 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) - { - 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); - } - } - - #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 + /// The tile location to check. + /// if the tile is valid; otherwise, . + protected bool SunkenSeaTileValidity(Point point) + => Main.tile[point].LiquidAmount > 128 && Main.tile[point].LiquidType == LiquidID.Water && NPC.DoesEntityFitInPath(point, 6, 6); } } 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/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 b2d4c8854c..5f1127d8ae 100644 --- a/Utilities/PathfindingUtils.cs +++ b/Utilities/PathfindingUtils.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Terraria; @@ -15,12 +13,6 @@ namespace CalamityMod /// public interface IPathFinder { - /// - /// The parameters to be used in that determines how pathfinding should be calculated.
- /// This can return if you do not want the entity to find a path. - ///
- public PathfindingParams Pathfinding { get; } - /// /// The result of the pathfinding task that contains a set of points this entity should follow. /// @@ -85,7 +77,7 @@ namespace CalamityMod /// Assigns the value of to based on .
/// You can override this and do - public void FindPath() => Paths = FindPathAsync(Pathfinding); + public void FindPath(PathfindingParams parameters) => Paths = FindPathAsync(parameters); } public static partial class CalamityUtils @@ -95,34 +87,39 @@ namespace CalamityMod /// This method should be called every frame that you want your entity to follow it's pathfinding logic. /// /// The entity that should be moving. - public static void DoPathfinding(this IPathFinder pathfinder) + public static void DoPathfinding(this IPathFinder pathfinder, PathfindingParams parameters) { - // Checks to make sure that: - // A. The pathfinding task has completed - // B. There is a valid result - // C. There are points left in the previously found path - if (pathfinder.Paths.Result != null && - pathfinder.Paths.Result.Count > 0) + // If the task is NOT in-progress... + if (pathfinder.Paths == null || pathfinder.Paths.IsCompleted) { - // Follows the point at index 0 of the path result. - Vector2 nextPoint = pathfinder.Paths.Result[0]; + // If the task result has entries... + if ((pathfinder.Paths?.Result?.Count ?? 0) > 0) + { + // Follows the point at index 0 of the path result. + Vector2 nextPoint = pathfinder.Paths.Result[0]; - // Once that point is reached, it is removed from the list of points to follow. - if (pathfinder.FollowPath(nextPoint)) - pathfinder.Paths.Result.RemoveAt(0); + // Once that point is reached, it is removed from the list of points to follow. + if (pathfinder.FollowPath(nextPoint)) + pathfinder.Paths.Result.RemoveAt(0); + } + + // If it does not have entries, that means the pathfinding task is + // complete OR the last pathfinding attempt was invalid. + // We need to attempt pathfinding again. Idle in the meantime. + else + { + pathfinder.FindPath(parameters); + pathfinder.IdleBehavior(); + } } - // Idle if the task is currently finding a path or there is no path to be followed. + // If the task IS in-progress, just idle while waiting for it to complete. else - { pathfinder.IdleBehavior(); - - // Only attempt to find a path again if the task is not currently running. - if (pathfinder.Paths.Status != TaskStatus.Running) - pathfinder.FindPath(); - } } + public static void DoPathfinding(this IPathFinder pathfinder, Vector2 target) => pathfinder.DoPathfinding(new PathfindingParams(pathfinder.Position, target)); + /// /// Represents a node in a pathfinding algorithm, containing position, cost, and parent information. /// @@ -230,7 +227,7 @@ namespace CalamityMod { // If the entity isn't actually supposed to follow a path right now, null // can be passed as the parameters to make implementation more concise. - if (parameters is null) + if (parameters is null || Main.tile[parameters.End.Position].IsTileSolid()) return null; var openSet = new List();