diff --git a/NPCs/SunkenSea/Sharkoon.cs b/NPCs/SunkenSea/Sharkoon.cs index f5f5cb9a1d..3ac500f1b5 100644 --- a/NPCs/SunkenSea/Sharkoon.cs +++ b/NPCs/SunkenSea/Sharkoon.cs @@ -1,53 +1,180 @@ -using CalamityMod.BiomeManagers; -using CalamityMod.Items.Placeables; -using CalamityMod.Items.Placeables.Banners; +using System; +using System.Collections.Generic; +using System.IO; +using CalamityMod.BiomeManagers; using CalamityMod.Projectiles.Enemy; -using CalamityMod.Projectiles.Ranged; -using CalamityMod.World; -using Microsoft.CodeAnalysis; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; -using System.IO; using Terraria; -using Terraria.Audio; using Terraria.GameContent; using Terraria.GameContent.Bestiary; -using Terraria.GameContent.ItemDropRules; using Terraria.ID; using Terraria.ModLoader; using Terraria.ModLoader.Utilities; +using static CalamityMod.CalamityUtils; + namespace CalamityMod.NPCs.SunkenSea { public class Sharkoon : ModNPC { - public override void SetStaticDefaults() + public static float TargetDistanceDetection = 160f; + public static int IdleMovementUnlikeliness = 150; + public static float MaxIdleSpeed = 3f; + public static float IdleMovementMaxRange = 1600f; + + #region Fields & Properties + + /// + /// The that this has detected as its target. + /// + private Player PlayerTarget { - Main.npcFrameCount[NPC.type] = 23; + get => playerTarget; + set + { + playerTarget = value; + NetUpdate(); + } } + private Player playerTarget; + + /// + /// The different AI states this enemy can have. + /// + private enum AIState { OutsideWater, Normal, Exploding } + + /// + /// The current AI state of this enemy. + /// + private AIState State + { + get => (AIState)NPC.ai[0]; + set + { + NPC.ai[0] = (float)value; + + if (value == AIState.Exploding) + Animation = AnimationState.Explosion; + + // When outside of water, it'll gravitate down, can't swim. + NPC.noGravity = value != AIState.OutsideWater; + + NetUpdate(); + } + } + + /// + /// The different types of animation this enemy can have. + /// + private enum AnimationState { Normal, Explosion, Shrunk } + + /// + /// The current animation being played right now. + /// + private AnimationState Animation + { + get => (AnimationState)NPC.ai[1]; + set + { + NPC.ai[1] = (float)value; + + // In case an animation is being set constantly, + // so we don't have it reset to the first frame every time, + // it'll only reset the current frame when actually changing animations. + if (value != Animation) + { + NPC.frame.Y = 0; + NPC.frameCounter = 0; + } + + switch (value) + { + case AnimationState.Normal: + ChangeAnimation(animationFrames: 7, timePerAnimationFrame: 7, loops: true); + break; + case AnimationState.Explosion: + ChangeAnimation(animationFrames: 16, timePerAnimationFrame: 8, loops: false); + break; + case AnimationState.Shrunk: + ChangeAnimation(animationFrames: 6, timePerAnimationFrame: 6, loops: true); + break; + } + + NetUpdate(); + } + } + + /// + /// 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; + + /// + /// The amount, in frames, that it takes to go to the next animation frame.
+ /// Defaults to 7. + ///
+ private int TimePerAnimationFrame = 7; + + /// + /// Whether or not the animation loops or not.
+ /// Defaults to . + ///
+ private bool AnimationLoop = true; + + /// + /// A netcode-synced boolean that is when this is the first frame that it exists,
+ /// meaning it just spawned. + ///
+ private bool HasSpawned + { + get => NPC.ai[2] == 1f; + set + { + NPC.ai[2] = value.ToInt(); + NetUpdate(); + } + } + + private ref float Timer => ref NPC.ai[3]; + + /// + /// A list of which makes a path for the to follow. + /// + private List PathPositions; + + #endregion + + #region Other Overridden Methods + + public override void SetStaticDefaults() => Main.npcFrameCount[Type] = 16; public override void SetDefaults() { - NPC.noGravity = true; NPC.damage = 20; - NPC.width = 20; - NPC.height = 58; - NPC.defense = 5; NPC.lifeMax = 350; + NPC.defense = 5; + NPC.knockBackResist = 0.15f; + NPC.chaseable = false; + NPC.aiStyle = -1; AIType = -1; - NPC.value = Item.buyPrice(0, 0, 5, 0); + NPC.width = 52; + NPC.height = 46; + NPC.noGravity = true; + NPC.HitSound = SoundID.NPCHit1; NPC.DeathSound = SoundID.NPCDeath1; - NPC.knockBackResist = 0.15f; - //Banner = NPC.type; - //BannerItem = ModContent.ItemType(); - NPC.chaseable = false; + NPC.value = Item.buyPrice(0, 0, 5, 0); + // Banner = NPC.type; + // BannerItem = ModContent.ItemType(); + + SpawnModBiomes = new int[1] { ModContent.GetInstance().Type }; + NPC.Calamity().VulnerableToHeat = false; NPC.Calamity().VulnerableToSickness = true; NPC.Calamity().VulnerableToElectricity = true; NPC.Calamity().VulnerableToWater = false; - SpawnModBiomes = new int[1] { ModContent.GetInstance().Type }; } public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry) @@ -58,42 +185,6 @@ namespace CalamityMod.NPCs.SunkenSea }); } - public override void AI() - { - CalamityAI.PassiveSwimmingAI(NPC, Mod, 1, 1000f, 0.15f, 0.15f, 2.5f, 2.5f, 0.1f); - } - - public override void FindFrame(int frameHeight) - { - NPC.frameCounter++; - if (NPC.frameCounter > 6 && NPC.frame.Y < frameHeight * 22) - { - NPC.frame.Y += frameHeight; - NPC.frameCounter = 0; - } - // EKUSPLOSIONE - if (NPC.ai[1] == 1) - { - if (NPC.frame.Y < frameHeight * 9) - { - NPC.frame.Y = frameHeight * 9; - } - } - // Idle - else - { - if (NPC.frame.Y > 8 * frameHeight) - { - NPC.frame.Y = 0; - } - } - } - - public override bool? CanBeHitByProjectile(Projectile projectile) - { - return null; - } - public override float SpawnChance(NPCSpawnInfo spawnInfo) { if (spawnInfo.Player.Calamity().ZoneSunkenSea && spawnInfo.Water && !spawnInfo.Player.Calamity().clamity) @@ -117,5 +208,310 @@ namespace CalamityMod.NPCs.SunkenSea } } } + + #endregion + + #region AI + + public override void AI() + { + if (!HasSpawned) + { + NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); + NPC.GravityMultiplier *= 2f; + NPC.MaxFallSpeedMultiplier *= 2f; + HasSpawned = true; + } + + switch (State) + { + case AIState.Normal: + NormalState(); + break; + case AIState.Exploding: + ExplodingState(); + break; + case AIState.OutsideWater: + OutsideWaterState(); + return; + } + } + + /// + /// The behavior of this NPC when it it's just doing normal behavior. + /// + private void NormalState() + { + // If the NPC's outside of water, switch the state. + if (!NPC.wet) + { + State = AIState.OutsideWater; + return; + } + + // If the NPC finds a valid target and it still is normal, go, commit boom. + if (Animation == AnimationState.Normal && FindsTarget()) + { + State = AIState.Exploding; + return; + } + + if (PathPositions == null) + { + // When there's no path, it'll deacclerate and eventually stay still. + NPC.velocity *= 0.95f; + + // At a random moment, it'll choose to move. + if (Main.rand.NextBool(IdleMovementUnlikeliness)) + { + var grid = GetPathGrid(); + AStar pathfinding = new AStar(grid, new(NPC.Center.ToSafeTileCoordinates()), new(grid[Main.rand.Next(grid.Count)])); + PathPositions = pathfinding.FindPath(); + Timer = 0f; + NetUpdate(); + } + } + + else + { + // Iterates through all the vectors in the path as time goes on. + Vector2 followedPathPoint = PathPositions[(int)Math.Floor(Timer)]; + + // Accelerates towards the followed point. + NPC.velocity += NPC.Center.DirectionTo(followedPathPoint) * 0.03f; + + Timer += 0.07f; + Timer = MathF.Min(Timer, PathPositions.Count - 1); + + // If very near the end point or too far from the followed path, reset the path. + if (NPC.Center.DistanceSQ(PathPositions[^1]) < 14400f || NPC.Center.DistanceSQ(followedPathPoint) > 102400f) + { + PathPositions = null; + NetUpdate(); + } + } + + NPC.velocity = Vector2.Clamp(NPC.velocity, -Vector2.One * MaxIdleSpeed, Vector2.One * MaxIdleSpeed); + NPC.rotation = MathHelper.ToRadians(NPC.velocity.Length() * 3f) * MathF.Sign(NPC.velocity.X); + NPC.spriteDirection = -MathF.Sign(NPC.velocity.X); + } + + /// + /// The behavior of this NPC when it is currently trying to explode. + /// + private void ExplodingState() + { + // Deaccelerate. + NPC.velocity *= 0.95f; + + // On the exact frame that the NPC explodes, it'll will, indeed, explode. + if (NPC.frame.Y == NPC.height * 9 && NPC.frameCounter == 0) + Kaboom(); + + // When the animation's finished, go back to being a normal fish. + if (NPC.frame.Y >= NPC.height * 16) + { + Animation = AnimationState.Shrunk; + State = AIState.Normal; + } + } + + /// + /// The behavior of this NPC when it's outside of water. + /// + private void OutsideWaterState() + { + if (NPC.wet) + { + State = AIState.Normal; + return; + } + } + + /// + /// What happens when this NPC explodes. + /// + private void Kaboom() + { + if (Main.netMode != NetmodeID.MultiplayerClient) + { + Projectile.NewProjectileDirect( + NPC.GetSource_FromThis(), + NPC.Center, + Vector2.Zero, + ModContent.ProjectileType(), + NPC.damage, + 10f, + Main.myPlayer); + } + + // VFX and sound effects go here, + // a dedicated server doesn't need to load these. + if (!Main.dedServ) + { + // HI XYK! + } + + NetUpdate(); + } + + /// + /// Finds a valid target for this NPC. + /// + /// Whether or not it has a found a valid target. + private bool FindsTarget() + { + // When the NPC already had a valid target, + // consider it null if it's not at a desired distance anymore. + if (PlayerTarget is not null) + { + if (NPC.Center.Distance(PlayerTarget.Center) > TargetDistanceDetection) + { + PlayerTarget = null; + return false; + } + + return true; + } + + // Finds the closest target. + NPC.TargetClosest(false); + PlayerTarget = Main.player[NPC.target]; + + // If there was a target but not at a desired distance, we consider there was no target. + if (PlayerTarget is not null && NPC.Center.Distance(PlayerTarget.Center) > TargetDistanceDetection) + { + PlayerTarget = null; + return false; + } + + return true; + } + + /// + /// Creates a list of points that constitutes the grid which the A* algorithm will use. + /// + private List GetPathGrid() + { + List grid = new(); + + Point topLeftCorner = CalamityUtils.ToSafeTileCoordinates(NPC.position + new Vector2(-IdleMovementMaxRange, -IdleMovementMaxRange)); + Point bottomRightCorner = CalamityUtils.ToSafeTileCoordinates(NPC.position + new Vector2(IdleMovementMaxRange, IdleMovementMaxRange)); + + for (int coordY = topLeftCorner.Y; coordY <= bottomRightCorner.Y; coordY++) + { + for (int coordX = topLeftCorner.X; coordX <= bottomRightCorner.X; coordX++) + { + Point point = new(coordX, coordY); + + if (Main.tile[point].IsTileSolid() || Main.tile[point].LiquidAmount != 255 || !AdjacentPointsValid(point)) + continue; + + grid.Add(point); + } + } + + return grid; + } + + /// + /// Checks whether or not path point is valid depending on its adjacent points. + /// + private bool AdjacentPointsValid(Point point) + { + foreach (var direction in Directions) + { + Point adjacentPoint = new(point.X + (int)direction.X, point.Y + (int)direction.Y); + + if (Main.tile[adjacentPoint].IsTileSolid()) + return false; + + adjacentPoint = new(point.X + (int)(direction.X * 2f), point.Y + (int)(direction.Y * 2f)); + + if (Main.tile[adjacentPoint].IsTileSolid()) + return false; + } + + return true; + } + + /// + /// Syncs to the server. + /// + private void NetUpdate() + { + NPC.netUpdate = true; + NPC.netSpam = 0; + } + + #endregion + + #region Drawing & Animation + + /// + /// A quick method to change all the animation's properties. + /// + private void ChangeAnimation(int animationFrames, int timePerAnimationFrame, bool loops) + { + AnimationFrames = animationFrames; + TimePerAnimationFrame = timePerAnimationFrame; + AnimationLoop = loops; + } + + public override void FindFrame(int frameHeight) + { + NPC.frameCounter++; + if (NPC.frameCounter > TimePerAnimationFrame) + { + NPC.frame.Y += frameHeight; + NPC.frame.Y = Math.Min(NPC.frame.Y, AnimationFrames * frameHeight); + NPC.frameCounter = 0; + if (AnimationLoop) + NPC.frame.Y = NPC.frame.Y % (AnimationFrames * frameHeight); + } + } + + public override bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) + { + Texture2D texture = TextureAssets.Npc[Type].Value; + Vector2 drawPosition = NPC.Center - screenPos; + Rectangle frame = texture.Frame(horizontalFrames: 3, verticalFrames: 16, frameX: (int)Animation, frameY: NPC.frame.Y / NPC.height); + Vector2 anchorPoint = frame.Size() * 0.5f; + SpriteEffects flip = NPC.spriteDirection == -1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None; + + spriteBatch.Draw(texture, drawPosition, frame, NPC.GetAlpha(drawColor), NPC.rotation, anchorPoint, NPC.scale, flip, 0f); + + return false; + } + + #endregion + + #region Syncing + + public override void SendExtraAI(BinaryWriter writer) + { + writer.Write7BitEncodedInt(AnimationFrames); + writer.Write7BitEncodedInt(TimePerAnimationFrame); + writer.Write(AnimationLoop); + + writer.Write7BitEncodedInt(PathPositions.Count); + foreach (var position in PathPositions) + writer.WritePackedVector2(position); + } + + public override void ReceiveExtraAI(BinaryReader reader) + { + AnimationFrames = reader.Read7BitEncodedInt(); + TimePerAnimationFrame = reader.Read7BitEncodedInt(); + AnimationLoop = reader.ReadBoolean(); + + List receivedPathPositions = new(); + int receivedCount = reader.Read7BitEncodedInt(); + for (int i = 0; i < receivedCount; i++) + receivedPathPositions.Add(reader.ReadPackedVector2()); + PathPositions = receivedPathPositions; + } + + #endregion } } diff --git a/NPCs/SunkenSea/Sharkoon.png b/NPCs/SunkenSea/Sharkoon.png index 4bd4b62e39..5306c2b6ec 100644 Binary files a/NPCs/SunkenSea/Sharkoon.png and b/NPCs/SunkenSea/Sharkoon.png differ diff --git a/Projectiles/Enemy/SharkoonExplosion.cs b/Projectiles/Enemy/SharkoonExplosion.cs new file mode 100644 index 0000000000..16d3ba5d52 --- /dev/null +++ b/Projectiles/Enemy/SharkoonExplosion.cs @@ -0,0 +1,18 @@ +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Enemy +{ + public class SharkoonExplosion : ModProjectile, ILocalizedModType + { + public new string LocalizationCategory => "Projectiles.Enemy"; + + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + + public override void SetDefaults() + { + Projectile.hostile = true; + Projectile.width = Projectile.height = 160; + Projectile.timeLeft = 2; + } + } +} diff --git a/Utilities/MathematicalUtils.cs b/Utilities/MathematicalUtils.cs index 1813494294..3e358be06d 100644 --- a/Utilities/MathematicalUtils.cs +++ b/Utilities/MathematicalUtils.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Microsoft.Xna.Framework; using Terraria; @@ -88,6 +89,8 @@ namespace CalamityMod /// The second point. public static float ManhattanDistance(this Vector2 a, Vector2 b) => Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y); + public static int ManhattanDistance(this Point a, Point b) => Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y); + /// /// Wraps an angle between -90 and 90 degrees. If an angle goes past this range it'll go back to the other end. /// @@ -359,5 +362,104 @@ namespace CalamityMod } #endregion + + #region A* Search Algorithm + + public class Node(Point position, Node parent = null) + { + public Point Position { get; set; } = position; + + /// + /// Cost from start to the current node. + /// + public int Cost { get; set; } + + /// + /// Heuristic cost from the current node to the goal. + /// + public int HeuristicCost { get; set; } + + public int TotalCost => Cost + HeuristicCost; + + public Node Parent { get; set; } = parent; + + public override bool Equals(object obj) => obj is Node node && Position == node.Position; + + public override int GetHashCode() => Position.X.GetHashCode() ^ Position.Y.GetHashCode(); + } + + public class AStar(List grid, Node start, Node goal) + { + private List grid = grid; + private Node goal = goal; + private List openList = new() { start }; + private HashSet closedList = new(); + + public List FindPath() + { + while (openList.Count > 0) + { + var currentNode = openList.OrderBy(node => node.TotalCost).First(); + + if (currentNode.Equals(goal)) + return ReconstructPath(currentNode); + + openList.Remove(currentNode); + closedList.Add(currentNode); + + foreach (var neighbor in GetNeighbors(currentNode)) + { + // Ignore the neighbor which is already evaluated. + if (closedList.Contains(neighbor)) + continue; + + int tentativeScore = currentNode.Cost + currentNode.Position.ManhattanDistance(neighbor.Position); + + // Discover a new node. + if (!openList.Contains(neighbor)) + openList.Add(neighbor); + + // This is not a better path. + else if (tentativeScore >= neighbor.Cost) + continue; + + neighbor.Parent = currentNode; + neighbor.Cost = tentativeScore; + neighbor.HeuristicCost = neighbor.Position.ManhattanDistance(goal.Position); + } + } + + return null; + } + + private List ReconstructPath(Node node) + { + var path = new List(); + while (node != null) + { + path.Add(node.Position.ToWorldCoordinates()); + node = node.Parent; + } + path.Reverse(); + return path; + } + + private IEnumerable GetNeighbors(Node node) + { + var neighbors = new List(); + + foreach (var direction in Directions) + { + Point newPoint = new(node.Position.X + (int)direction.X, node.Position.Y + (int)direction.Y); + + if (!Main.tile[newPoint].IsTileSolid() && grid.Contains(newPoint)) + neighbors.Add(new Node(newPoint, node)); + } + + return neighbors; + } + } + + #endregion } }