diff --git a/Buffs/DamageOverTime/Shred.cs b/Buffs/DamageOverTime/Shred.cs index 4cdc780be8..d46d375305 100644 --- a/Buffs/DamageOverTime/Shred.cs +++ b/Buffs/DamageOverTime/Shred.cs @@ -1,6 +1,7 @@ using System; using CalamityMod.NPCs; using CalamityMod.Particles; +using CalamityMod.Projectiles; using CalamityMod.Projectiles.Typeless; using Microsoft.Xna.Framework; using Terraria; @@ -12,8 +13,8 @@ namespace CalamityMod.Buffs.DamageOverTime { internal const int StackFalloffFrames = 320; - // 150 DPS (30x5) per stack may seem low, but it gets boosted by ranged stats and can supercrit. - internal static int BaseDamage = 30; + // This deals 600 DPS per stack, is boosted by ranged stats and can supercrit. + internal static int BaseDamage = 120; internal static int FramesPerDamageTick = 12; public override void SetStaticDefaults() @@ -62,15 +63,20 @@ namespace CalamityMod.Buffs.DamageOverTime // This cannot be done with SimpleStrikeNPC because that would not allow for supercrits. int bleedTickDamage = (int)applicator.GetTotalDamage().ApplyTo(BaseDamage * cgn.somaShredStacks); Projectile tick = Projectile.NewProjectileDirect(target.GetSource_FromThis(), target.Center, Vector2.Zero, ModContent.ProjectileType(), bleedTickDamage, 0f, applicator.whoAmI, target.whoAmI); + tick.DamageType = DamageClass.Ranged; // Uncommon for DirectStrikes, but it needs to be able to crit. - tick.Calamity().supercritHits = -1; + + // All ticks of Shred have a 3x base crit multiplier and have supercrits enabled. + CalamityGlobalProjectile cgp = tick.Calamity(); + cgp.supercritHits = -1; + cgp.bonusCritDamage += 1f; } } } internal static void DrawEffects(Player player) { - + // TODO -- Players inflicted with Shred don't display any visuals. } // Enemies suffering from Soma Prime's Shred spray blood like Violence diff --git a/CalPlayer/CalamityPlayerOnHit.cs b/CalPlayer/CalamityPlayerOnHit.cs index 0b40dcdb0c..368faf31ba 100644 --- a/CalPlayer/CalamityPlayerOnHit.cs +++ b/CalPlayer/CalamityPlayerOnHit.cs @@ -362,9 +362,23 @@ namespace CalamityMod.CalPlayer CalamityGlobalProjectile cgp = proj.Calamity(); if (cgp.appliesSomaShred) { - target.AddBuff(BuffType(), 320); - // This information cannot be transferred through the buff, but is necessary to calculate damage - cgn.somaShredApplicator = Player.whoAmI; + // 08MAR2025: Ozzatron: Obsessive Warframe accuracy. + // Typical endgame Soma Prime builds have a 5% chance to apply debuff, then 30% extra chance if it's a crit, rolled separately. + bool actuallyApplyShred = false; + if (Main.rand.NextFloat() < 0.05f) + actuallyApplyShred = true; + if (hit.Crit && Main.rand.NextFloat() < 0.3f) + actuallyApplyShred = true; + + if (actuallyApplyShred) + { + target.AddBuff(BuffType(), 320); + // This information cannot be transferred through the buff, but is necessary to calculate damage + cgn.somaShredApplicator = Player.whoAmI; + + // 08MAR2025: Ozzatron: God Slayer Slugs can no longer apply Shred multiple times. + cgp.appliesSomaShred = false; + } } // Similarly, all shots from Animosity are also marked diff --git a/Items/Weapons/Ranged/SomaPrime.cs b/Items/Weapons/Ranged/SomaPrime.cs index b1b9159bfd..beed00b0e5 100644 --- a/Items/Weapons/Ranged/SomaPrime.cs +++ b/Items/Weapons/Ranged/SomaPrime.cs @@ -19,7 +19,7 @@ namespace CalamityMod.Items.Weapons.Ranged { Item.width = 94; Item.height = 34; - Item.damage = 488; + Item.damage = 705; Item.DamageType = DamageClass.Ranged; Item.useAnimation = Item.useTime = 5; Item.useStyle = ItemUseStyleID.Shoot; @@ -38,7 +38,7 @@ namespace CalamityMod.Items.Weapons.Ranged } // Terraria seems to really dislike high crit values in SetDefaults - public override void ModifyWeaponCrit(Player player, ref float crit) => crit += 30; + public override void ModifyWeaponCrit(Player player, ref float crit) => crit += 26; public override Vector2? HoldoutOffset() => new Vector2(-25, 0); @@ -54,8 +54,12 @@ namespace CalamityMod.Items.Weapons.Ranged velocity.Y += Main.rand.NextFloat(-XYInaccuracy, XYInaccuracy); Vector2 vel = velocity; Projectile shot = Projectile.NewProjectileDirect(source, position, vel, type, damage, knockback, player.whoAmI); + + // Set all projectiles fired from Soma Prime to have 3x base crit multiplier and to have supercrits enabled. + // They also are able to apply one stack of Shred. CalamityGlobalProjectile cgp = shot.Calamity(); cgp.supercritHits = -1; + cgp.bonusCritDamage += 1f; cgp.appliesSomaShred = true; return false; } diff --git a/Localization/en-US/Mods.CalamityMod.Items.Weapons.Ranged.hjson b/Localization/en-US/Mods.CalamityMod.Items.Weapons.Ranged.hjson index 0f7f1d8f5d..e4025b826b 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Weapons.Ranged.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Weapons.Ranged.hjson @@ -1157,9 +1157,10 @@ SomaPrime: { Tooltip: ''' This weapon can supercrit if its crit chance is over 100% - All bullets fired inflict Shred, a stacking bleed debuff - Shred deals 150 DPS per stack and scales with your ranged stats - Damage ticks of Shred can also critically strike or supercrit + All bullets fired have a 5% chance to inflict Shred, a stacking bleed debuff + Critical strikes deal 3x damage instead of 2x by default and have a 30% chance to inflict Shred + Shred deals 600 DPS per stack and scales with your ranged stats + Damage ticks of Shred can critically strike for 3x damage and can supercrit Replaces musket balls with enhanced High Velocity Bullets 80% chance to save ammo ''' diff --git a/NPCs/CalamityGlobalNPC.cs b/NPCs/CalamityGlobalNPC.cs index c08906126d..c7b51475f5 100644 --- a/NPCs/CalamityGlobalNPC.cs +++ b/NPCs/CalamityGlobalNPC.cs @@ -6304,6 +6304,10 @@ namespace CalamityMod.NPCs } } + // 08MAR2025: Simplistic crit damage increase. Doesn't force a crit, though you can do that separately. + // STACKS MULTIPLICATIVELY (!!!) with above supercrit behavior. + modifiers.CritDamage += cgp.bonusCritDamage; + // // DAAWNLIGHT SPIRIT ORIGIN AIM IMPLEMENTATION // diff --git a/NPCs/SunkenSea/Probesnout.cs b/NPCs/SunkenSea/Probesnout.cs index 90f0d198b1..e04e5115a0 100644 --- a/NPCs/SunkenSea/Probesnout.cs +++ b/NPCs/SunkenSea/Probesnout.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; +using System.Xml.XPath; using CalamityMod.Enums; using CalamityMod.Items.Placeables.Banners; using CalamityMod.Tiles; @@ -18,7 +19,7 @@ using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea { - public class Probesnout : SunkenSeaNPC, IPathFinder + public class Probesnout : SunkenSeaNPC { #region Members @@ -94,7 +95,11 @@ namespace CalamityMod.NPCs.SunkenSea private Action _previousBehavior; - public PathfindingTask Path { get; set; } + private int HuntCooldown + { + get => (int)NPC.ai[3]; + set => NPC.ai[3] = value; + } public Vector2 Position => NPC.Center; @@ -128,6 +133,12 @@ namespace CalamityMod.NPCs.SunkenSea NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; NPC.MaxFallSpeedMultiplier *= 2f; + pathfinding = new PathfindingManager(NPC) + { + Acceleration = 0.4f, + MaxSpeed = 8f, + MinimumPointDistance = 60f + }; } public override void AI() @@ -140,9 +151,12 @@ namespace CalamityMod.NPCs.SunkenSea else if (NPC.velocity.LengthSquared() != 0f) NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); - if (Main.rand.NextBool(50) && !HasEatenSponge && CurrentBehavior == IdlingBehavior) + if (Main.rand.NextBool(150) && !HasEatenSponge && CurrentBehavior == IdlingBehavior) ThreadPool.QueueUserWorkItem(_ => DetectSponges(), null); + if (Main.rand.NextBool(300) && HasEatenSponge && Vector2.DistanceSquared(NPC.Center, SpongeFoundPosition) > 160f * 160f) + HasEatenSponge = false; + if (!NPC.wet && CurrentBehavior != OutsideWaterBehavior) { NPC.noGravity = false; @@ -181,14 +195,8 @@ namespace CalamityMod.NPCs.SunkenSea private void IdlingBehavior() { // At random, the mob will choose a random nearby point and pathfind there. - PathfindingTask parameters = null; - if (Main.rand.NextBool(150)) - { - _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * 300f; - NPC.netUpdate = true; - parameters = new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); - } - this.DoPathfinding(parameters); + pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(500f, 3000f), SunkenSeaTileValidity)); + pathfinding.MaxSpeed = 6f; } private void FleeingBehavior() @@ -210,18 +218,19 @@ namespace CalamityMod.NPCs.SunkenSea do { var randomNormalDirection = headedDirection.RotatedBy(MathHelper.PiOver2 * Main.rand.NextBool().ToDirectionInt()); - _randomPathPoint = randomNormalDirection.RotatedByRandom(MathHelper.PiOver4); + _randomPathPoint = randomNormalDirection.RotatedByRandom(MathHelper.PiOver4 * 0.7f); 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)); + pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + _randomPathPoint, SunkenSeaTileValidity)); + pathfinding.MaxSpeed = 8f; } else { NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; - Path = null; + pathfinding.ClearResults(); // Cap the speed if MaxSpeed has been surpassed. if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) @@ -238,8 +247,28 @@ namespace CalamityMod.NPCs.SunkenSea return; } + bool huntReady = HuntCooldown == 0; + if (huntReady) + HuntCooldown = Main.rand.Next(13, 30); + // 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); + pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, tileValidity: SunkenSeaTileValidity), forceNewTask: huntReady); + pathfinding.MaxSpeed = 8f; + pathfinding.CustomIdleBehavior = () => + { + if (CurrentPrey != null) + { + NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * pathfinding.Acceleration; + + // Cap the speed if MaxSpeed has been surpassed. + if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; + } + else + NPC.velocity *= 0.95f; + }; + + HuntCooldown--; } private void EatingBehavior() @@ -253,11 +282,15 @@ namespace CalamityMod.NPCs.SunkenSea HasEatenSponge = true; Animation = AnimationState.Idle; CurrentBehavior = IdlingBehavior; + SpongeFoundPosition = Vector2.Zero; return; } } else - this.DoPathfinding(new PathfindingTask(NPC.Center, SpongeFoundPosition, SunkenSeaTileValidity)); + { + pathfinding.DoPathfinding(new(NPC.Center, SpongeFoundPosition, SunkenSeaTileValidity)); + pathfinding.MaxSpeed = 6f; + } } private void OutsideWaterBehavior() @@ -271,60 +304,39 @@ namespace CalamityMod.NPCs.SunkenSea private void DetectSponges() { - Vector2? closestSpongeFound = null; - float closestDistanceSquared = float.MaxValue; - - foreach (var direction in Directions) + Vector2? spongeFoundPosition = null; + int? tileIndexFound = null; + for (int i = 0; i < 360 && spongeFoundPosition == null; i += 15) { - // var points = GetIntersectingPoints(NPC.Center, NPC.Center + direction * 360f); - var points = new Point[1]; - foreach (var point in points) + var points = GetIntersectingPointsInLine(NPC.Center, NPC.Center - Vector2.UnitY.RotatedBy(MathHelper.ToRadians(i)) * 360f); + for (int j = points.Count - 1; j >= 0; j--) { - // 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()) + if (Main.tile[points[j]].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 + tileIndexFound = j; break; } } + + if (tileIndexFound == null) + continue; + + for (int k = tileIndexFound.Value; k >= 0; k--) + { + Vector2 worldPos = points[k].ToWorldCoordinates(); + if (NPC.HasSight(worldPos) && SunkenSeaTileValidity(points[k])) + { + CurrentBehavior = EatingBehavior; + spongeFoundPosition = worldPos; + break; + } + } + + tileIndexFound = null; } - // Update behavior if a valid tile was found - if (closestSpongeFound.HasValue) - { - CurrentBehavior = EatingBehavior; - SpongeFoundPosition = closestSpongeFound.Value; - } + if (spongeFoundPosition.HasValue) + SpongeFoundPosition = spongeFoundPosition.Value; } public override void HitEffect(NPC.HitInfo hit) @@ -385,8 +397,8 @@ namespace CalamityMod.NPCs.SunkenSea public override void SetDefaults() { base.SetDefaults(); - - // BannerItem = ItemType(); + + BannerItem = ItemType(); NPC.lifeMax = 5; diff --git a/NPCs/SunkenSea/Sharkoon.cs b/NPCs/SunkenSea/Sharkoon.cs index 6a7045e509..11d3285bfa 100644 --- a/NPCs/SunkenSea/Sharkoon.cs +++ b/NPCs/SunkenSea/Sharkoon.cs @@ -18,7 +18,7 @@ using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea { - public class Sharkoon : SunkenSeaNPC, IPathFinder + public class Sharkoon : SunkenSeaNPC { #region Fields & Properties @@ -99,7 +99,7 @@ namespace CalamityMod.NPCs.SunkenSea /// /// The squish of this NPC while drawing. /// - private Vector2 _scaleSquish = Vector2.One; + private Vector2 ScaleSquish = Vector2.One; private Entity _avoidedEntity; @@ -133,6 +133,12 @@ namespace CalamityMod.NPCs.SunkenSea private Action _previousBehavior; + private int HuntCooldown + { + get => (int)NPC.ai[3]; + set => NPC.ai[3] = value; + } + #region SunkenSeaNPC Implementation protected override List PreyIDs => @@ -157,20 +163,6 @@ namespace CalamityMod.NPCs.SunkenSea #endregion - #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 @@ -185,7 +177,7 @@ namespace CalamityMod.NPCs.SunkenSea { base.SetDefaults(); - // BannerItem = ItemType(); + BannerItem = ItemType(); NPC.damage = 20; NPC.lifeMax = 350; @@ -223,6 +215,11 @@ namespace CalamityMod.NPCs.SunkenSea public override void OnSpawn(IEntitySource source) { + pathfinding = new PathfindingManager(NPC) + { + Acceleration = 0.3f, + MaxSpeed = 6f, + }; CurrentBehavior = IdlingBehavior; NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; @@ -250,25 +247,14 @@ namespace CalamityMod.NPCs.SunkenSea CurrentBehavior = OutsideWaterBehavior; // Reset any squish that is done to the Sharkoon. - if (_scaleSquish.Y > 1f) - { - _scaleSquish.Y -= 0.025f; - if (_scaleSquish.Y < 1f) - _scaleSquish.Y = 1f; - } + if (ScaleSquish.Y > 1f) + ScaleSquish.Y = Math.Max(1f, ScaleSquish.Y - 0.025f); } private void IdlingBehavior() { // At random, the mob will choose a random nearby point and pathfind there. - PathfindingTask task = null; - if (Main.rand.NextBool(IdleRandomMovementUnlikeliness)) - { - _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance); - NPC.netUpdate = true; - task = new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); - } - this.DoPathfinding(task); + pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * 2000f, SunkenSeaTileValidity)); } private void HuntingBehavior() @@ -280,15 +266,27 @@ namespace CalamityMod.NPCs.SunkenSea return; } + bool huntReady = HuntCooldown == 0; + if (huntReady) + HuntCooldown = Main.rand.Next(13, 30); + // 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 + pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), forceNewTask: huntReady); + pathfinding.CustomIdleBehavior = () => { - NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; - if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; - } + if (CurrentPrey != null) + { + NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * pathfinding.Acceleration; + + // Cap the speed if MaxSpeed has been surpassed. + if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; + } + else + NPC.velocity *= 0.95f; + }; + + HuntCooldown--; } private void FleeingBehavior() @@ -307,18 +305,19 @@ namespace CalamityMod.NPCs.SunkenSea // Try to manuever if there are any obstacles. if (!Main.tile[(NPC.Center + NPC.DirectionFrom(_avoidedEntity.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid()) { - NPC.velocity += NPC.DirectionFrom(_avoidedEntity.Center) * Acceleration; + NPC.velocity += NPC.DirectionFrom(_avoidedEntity.Center) * pathfinding.Acceleration; + pathfinding.ClearResults(); // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; + if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.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)); + pathfinding.DoPathfinding(new(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); } // If it's capable of exploding and the predator's within distance, kaboom. @@ -398,7 +397,7 @@ namespace CalamityMod.NPCs.SunkenSea if (newBehavior == OutsideWaterBehavior) NPC.noGravity = false; - Path = null; + pathfinding.MinimumPointDistance = newBehavior == HuntingBehavior ? 20f : 48f; } protected override void OnPreyDetection(NPC prey) @@ -407,7 +406,7 @@ namespace CalamityMod.NPCs.SunkenSea if (CanExplode && CurrentPredator is null && !IsExploding) { CurrentBehavior = HuntingBehavior; - _scaleSquish.Y += 0.4f; + ScaleSquish.Y += 0.4f; } } @@ -418,7 +417,7 @@ namespace CalamityMod.NPCs.SunkenSea { CurrentBehavior = FleeingBehavior; _avoidedEntity = predator; - _scaleSquish.Y += 0.4f; + ScaleSquish.Y += 0.4f; } } @@ -430,7 +429,7 @@ namespace CalamityMod.NPCs.SunkenSea CurrentBehavior = FleeingBehavior; _avoidedEntity = player; - _scaleSquish.Y += 0.4f; + ScaleSquish.Y += 0.4f; } public override void HitEffect(NPC.HitInfo hit) @@ -552,7 +551,7 @@ namespace CalamityMod.NPCs.SunkenSea 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, _scaleSquish, flip, 0f); + spriteBatch.Draw(texture, drawPosition, frame, NPC.GetAlpha(drawColor), NPC.rotation, anchorPoint, ScaleSquish, flip, 0f); return false; } diff --git a/NPCs/SunkenSea/SunkenSeaNPC.cs b/NPCs/SunkenSea/SunkenSeaNPC.cs index 1f1680f7a0..7ed695128d 100644 --- a/NPCs/SunkenSea/SunkenSeaNPC.cs +++ b/NPCs/SunkenSea/SunkenSeaNPC.cs @@ -18,6 +18,8 @@ namespace CalamityMod.NPCs.SunkenSea /// public abstract class SunkenSeaNPC : ModNPC { + protected PathfindingManager pathfinding = null; + private NPC _currentPrey; private NPC _currentPredator; private Player _currentPlayer; @@ -188,7 +190,7 @@ namespace CalamityMod.NPCs.SunkenSea 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); + actualFuckingPoint, 10, 10).Any(a => Main.tile[a].IsTileSolidGround() || Main.tile[a].LiquidAmount < 255 || Main.tile[a].LiquidType != LiquidID.Water); } } } diff --git a/Projectiles/CalamityGlobalProjectile.cs b/Projectiles/CalamityGlobalProjectile.cs index 86aa2ff20e..ad32facac2 100644 --- a/Projectiles/CalamityGlobalProjectile.cs +++ b/Projectiles/CalamityGlobalProjectile.cs @@ -96,7 +96,15 @@ namespace CalamityMod.Projectiles /// public int supercritHits = 0; - // TODO -- In the TML 1.4.4 port, there is a much better way to set NPC strike events to be forced crits. + /// + /// Bonus damage on critical strikes expressed as a ratio.
+ /// 0f = 200% crit damage, vanilla standard.
+ /// 1f = 300% crit damage.

+ /// This applies independently of supercrits and will stack additively with them. + ///
+ public float bonusCritDamage = 0f; + + // 08MAR2025: This remains so that "delayed forced crits" can still be set. This is used for Marksman Ricoshots. /// Set to true to force a projectile to critically strike. public bool forcedCrit = false; diff --git a/Projectiles/Ranged/ExoLightningBolt.cs b/Projectiles/Ranged/ExoLightningBolt.cs index 9fb2aad3a1..24b74afde4 100644 --- a/Projectiles/Ranged/ExoLightningBolt.cs +++ b/Projectiles/Ranged/ExoLightningBolt.cs @@ -86,10 +86,6 @@ namespace CalamityMod.Projectiles.Ranged HasPlayedSound = true; } - // This projectile is forced to critically strike. - // This technically is a nerf, as it makes DSO's crits deal less damage. - Projectile.Calamity().forcedCrit = true; - Lighting.AddLight(Projectile.Center, Color.White.ToVector3()); if (Projectile.frameCounter >= Projectile.extraUpdates * 2) { @@ -173,6 +169,10 @@ namespace CalamityMod.Projectiles.Ranged return false; } + // This projectile is forced to critically strike. + // This technically is a nerf, as it makes DSO's crits deal less damage. + public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) => modifiers.SetCrit(); + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 300); public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType(), 300); diff --git a/Utilities/PathfindingUtils.cs b/Utilities/PathfindingUtils.cs index b4143f8482..f8af93a82c 100644 --- a/Utilities/PathfindingUtils.cs +++ b/Utilities/PathfindingUtils.cs @@ -2,212 +2,300 @@ 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 + #region Pathfinding Parameters + public readonly struct PathfindingParameters { + internal static readonly Func DefaultTileValidity = point => true; + internal static readonly Func DefaultDistanceFunction = OctileDistance; + internal static readonly Func DefaultHeuristic = OctileDistance; + + internal readonly Vector2 Start; + internal readonly Vector2 End; + internal readonly Func TileValidity; + internal readonly Func DistanceFunction; + internal readonly Func Heuristic; + + public PathfindingParameters( + Vector2 start, + Vector2 end, + Func tileValidity = null, + Func distanceFunction = null, + Func heuristic = null) + { + Start = start; + End = end; + TileValidity = tileValidity; + DistanceFunction = distanceFunction; + Heuristic = heuristic; + } + } + #endregion + + #region Pathfinding Manager + /// + /// Creates a new PathfindingManager for the selected entity.
+ /// Entities should only ever need one PathfindingManager for their lifetime, but more can be created. + ///
+ /// The entity to pathfind for. + public class PathfindingManager(Entity e) + { + public List Path { get => lastSuccessfulTask?.Result ?? []; } + + /// + /// The entity which this PathfindingManager manages. This cannot be changed after creation. + /// + internal readonly Entity entity = e; + + /// + /// The acceleration this PathfindingManager will impart to its Entity when making it follow a found path.
+ /// This has no impact on the Entity's other behaviors, AI, etc. + ///
+ internal float Acceleration { get; set; } = 0.2f; + + /// + /// The maximum speed this PathfindingManager allow its Entity to move at when making it follow a found path.
+ /// This has no impact on the Entity's other behaviors, AI, etc. + ///
+ internal float MaxSpeed { get; set; } = 4f; + + /// + /// The minimum distance this PathdingManager requires its Entity to reach from its target point before the point is marked as "reached".
+ /// This has no impact on the Entity's other behaviors, AI, etc. + ///
+ internal float MinimumPointDistance { get; set; } = 48f; + + /// + /// The last completed pathfinding task that this manager has performed.
+ /// This is kept in place so that the entity may continue to follow its last successful path while calculating a new one.
+ ///
+ /// This task will always be in a Completed state with a valid Result. + ///
+ private PathfindingTask lastSuccessfulTask; + /// /// 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; } + private PathfindingTask currentTask; /// - /// 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; } + /// You may override the path-following behavior imposed on the Entity by the PathfindingManager by providing a Func here. + ///

+ /// This Func should return when the entity has reached its target point, and otherwise.
///
- public Vector2 Position { get; } + public Func CustomFollowPath { get; set; } /// - /// 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; } + /// You may override the idling behavior imposed on the Entity by the PathfindingManager by providing an Action here. + ///

+ /// This Action has no parameters and no return value, and can do basically anything you want. + ///
+ /// It will usually only run for a frame or two while the PathfindingManager is finding the next path to take. ///
- public Vector2 Velocity { get; set; } + public Action CustomIdleBehavior { get; set; } /// - /// The acceleration this entity should use when moving. Only used to calculate movement for this entity, not pathfinding. + /// Finds a path based on the specified parameters and assigns it to this manager's entity.
+ /// This method does not force the entity to begin following the path - it only locates a new path. ///
- public float Acceleration { get; } + public void FindPath(PathfindingParameters parameters, bool forceNewTask = true) + { + var potentialNewTask = new PathfindingTask(parameters); + + // Case 1: No current pathfinding task. + // Set the current task to be the potential new task. + if (currentTask is null) + { + currentTask = potentialNewTask; + currentTask.Run(); + } + + // Case 2: Current task exists and is currently running. + // Make the Entity idle and continue to await results. + if (currentTask.Running) + { + // Case 2A: We don't care about the previous pathfinding task. We have changed our goals. + // In order to trigger this behavior, you must set forceNewTask to true, and provide a different end goal position. + bool sameEndPosition = parameters.End.ToTileCoordinates() == currentTask.work.End.Position; + bool forceNewPathAttempt = forceNewTask && !sameEndPosition; + + if (forceNewPathAttempt) + { + currentTask = potentialNewTask; + currentTask.Run(); + } + + // Regardles of whether a new pathing execution is forced, the entity will continue to behave based on any previous successful pathing. + // Its calculations have not finished. + return; + } + + // Case 3: Current task exists, but is not currently running. + // There are two reasons why this can be the case. + bool previousTaskHadNoResult = currentTask.Result is null; + bool previousTaskPathFollowed = (currentTask.Result?.Count ?? -1) == 0; + // The third case is that you are forcing it to start a new task, either to the same or a new destination. + + // Regardless of which reason the pathfinding has ended, start the new task. + if (previousTaskHadNoResult || previousTaskPathFollowed || forceNewTask) + { + currentTask = potentialNewTask; + currentTask.Run(); + return; + } + + // Case 4: "Your paths found." + // The pathfinding task has completed its execution and a valid path has been found. + // Lock in that successful pathfinding task so the entity may consume its results. + lastSuccessfulTask = currentTask; + } /// - /// The maximum speed this entity should be able to reach while moving. Only used to calculate movement for this entity, not pathfinding. + /// Glue code to cause the Entity to either follow its last successful path, or idle. /// - public float MaxSpeed { get; } + public void PathfindingBehavior() + { + if (lastSuccessfulTask is null) + { + IdleBehavior(); + return; + } + + Vector2 nextPoint = lastSuccessfulTask.Result[0]; + + // If that point is reached, it is removed from the list of points to follow. + bool nextPointReached = FollowPath(nextPoint); + if (nextPointReached) + lastSuccessfulTask.Result.RemoveAt(0); + + // If the previous successful found path has been followed to its endpoint, delete the task. + if (lastSuccessfulTask.Result.Count == 0) + lastSuccessfulTask = null; + } /// - /// 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. + /// Performs appropriate "path-finding behavior" for the Entity this PathfindingManager is attached to.
+ /// This method is intended to be called every frame that you want the Entity to obey its pathfinding logic. ///
- /// - /// - public bool FollowPath(Vector2 nextPoint) + public void DoPathfinding(PathfindingParameters parameters, bool forceNewTask = false) + { + FindPath(parameters, forceNewTask); + PathfindingBehavior(); + } + + private bool DefaultFollowPath(Vector2 nextPoint) { // Accelerate to the target point. - Velocity += (nextPoint - Position).SafeNormalize(Vector2.Zero) * Acceleration; + entity.velocity += (nextPoint - entity.Center).SafeNormalize(Vector2.Zero) * Acceleration; // Cap the speed if MaxSpeed has been surpassed. - if (Velocity.LengthSquared() > MaxSpeed * MaxSpeed) - Velocity = Velocity.SafeNormalize(Vector2.UnitY) * MaxSpeed; + if (entity.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + entity.velocity = entity.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) + if (Vector2.DistanceSquared(entity.Center, nextPoint) < MinimumPointDistance * MinimumPointDistance) return true; // Otherwise, continue following. return false; } + /// + /// 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. + ///

+ /// The behavior of this function can be completely overridden by providing a CustomFollowPath Func. + ///
+ /// The next point in the path that this PathfindingManager has made. + /// Whether or not the destination has been reached. + public bool FollowPath(Vector2 nextPoint) => CustomFollowPath?.Invoke(nextPoint) ?? DefaultFollowPath(nextPoint); + + private static readonly float DefaultSlowdown = 0.95f; + private void DefaultIdleBehavior() => entity.velocity *= DefaultSlowdown; + /// /// Defines how this entity should behave while there is no current path to follow.
- /// By default, decelerates and stops based on . + /// By default, decelerates to a stop using the DefaultSlowdown value.
+ /// This behavior will usually only run for a frame or two while the PathfindingManager is finding the next path to take. ///
- 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) + public void IdleBehavior() { - 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. + if (CustomIdleBehavior is not null) + CustomIdleBehavior(); 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); - } + DefaultIdleBehavior(); } + public void ClearResults() + { + currentTask = null; + lastSuccessfulTask = null; + } + + #region Pathfinding Task + /// + /// Represents a task for calculating a complex path.
+ /// Allows for synchronous access to an asynchronous execution state, while still providing blocking access where needed. + ///
+ private class PathfindingTask(PathfindingParameters parameters) + { + /// + /// The result of this pathfinding task. + /// + internal List Result { get => _task.Task.Result; } + + /// + /// Whether this pathfinding task has completed running. + /// + internal bool Ready { get; private set; } = false; + + /// + /// Whether this pathfinding task is still currently running. + /// + internal bool Running { get; private set; } = false; + + // Interal task representation of the work. + internal readonly TaskCompletionSource> _task = new(); + + // Internal containing object for the actual work. + internal readonly PathfindingWork work = new(parameters); + + /// + /// Begins execution of this pathfinding task on a background thread. + /// + internal 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); + } + } + #endregion + + #region Pathfinding Work Record /// /// Represents the working computation for a . /// /// /// - /// Has 2 overloads, one for inputting the start and end nodes as , and the other one as . + /// Has 2 constructors. One option provides the start and end positions 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. @@ -218,38 +306,31 @@ namespace CalamityMod /// - : 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 record PathfindingWork(PathfindingNode Start, PathfindingNode 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, + float minimalPointDistance, Func tileValidity = null, Func distanceFunction = null, Func heuristic = null) : this( - new Node(start), - new Node(end), - tileValidity ?? DefaultTileValidity, - distanceFunction ?? DefaultDistanceFunction, - heuristic ?? DefaultHeuristic + new PathfindingNode(start), + new PathfindingNode(end), + tileValidity ?? PathfindingParameters.DefaultTileValidity, + distanceFunction ?? PathfindingParameters.DefaultDistanceFunction, + heuristic ?? PathfindingParameters.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 + PathfindingParameters p) : this( + new PathfindingNode(p.Start.ToTileCoordinates()), + new PathfindingNode(p.End.ToTileCoordinates()), + p.TileValidity ?? PathfindingParameters.DefaultTileValidity, + p.DistanceFunction ?? PathfindingParameters.DefaultDistanceFunction, + p.Heuristic ?? PathfindingParameters.DefaultHeuristic ) { } @@ -261,13 +342,13 @@ namespace CalamityMod /// /// A list of positions representing the path from start to end, or if no path is found. /// - public List CalculatePath() + internal List CalculatePath() { if (Main.tile[End.Position].IsTileSolid()) return null; - var openSet = new List(); - var closedSet = new HashSet(); + var openSet = new List(); + var closedSet = new HashSet(); openSet.Add(Start); while (openSet.Count > 0) @@ -310,30 +391,32 @@ namespace CalamityMod return null; // No path found. } } + #endregion + #region Pathfinding Node /// /// Represents a node in a pathfinding algorithm, containing position, cost, and parent information. /// - public class Node(Point position) + private class PathfindingNode(Point position) { - public Point Position { get; set; } = position; - public float G { get; set; } // Cost from start to this node. - public float H { get; set; } // Heuristic cost to goal. - public float F => G + H; // Total cost. - public Node Parent { get; set; } + internal Point Position { get; set; } = position; + internal float G { get; set; } // Cost from start to this node. + internal float H { get; set; } // Heuristic cost to goal. + internal float F => G + H; // Total cost. + internal PathfindingNode Parent { get; set; } public override bool Equals(object obj) { - if (obj is Node other) + if (obj is PathfindingNode other) return Position == other.Position; return false; } public override int GetHashCode() => Position.GetHashCode(); - public List GetNeighbors() + internal List GetNeighbors() { - var neighbors = new List(Directions.Count); + var neighbors = new List(Directions.Count); int nodeX = Position.X; int nodeY = Position.Y; @@ -344,13 +427,13 @@ namespace CalamityMod int newY = nodeY + (int)direction.Y; if (WorldGen.InWorld(newX, newY)) - neighbors.Add(new Node(new Point(newX, newY))); + neighbors.Add(new PathfindingNode(new Point(newX, newY))); } return neighbors; } - public List ReconstructPath() + internal List ReconstructPath() { var pathStack = new Stack(); var node = this; @@ -367,9 +450,13 @@ namespace CalamityMod return path; } } + #endregion + } + #endregion + public static partial class CalamityUtils + { #region Heuristic Functions - public static float TaxicabDistance(Point a, Point b) => MathF.Abs(a.X - b.X) + MathF.Abs(a.Y - b.Y); public static float EuclideanDistance(Point a, Point b) @@ -387,7 +474,6 @@ namespace CalamityMod float dy = MathF.Abs(a.Y - b.Y); return dx + dy - 0.586f * MathF.Min(dx, dy); } - #endregion ///