First Implementation

This commit is contained in:
Memes authored and Cameron Ewell committed 2025-11-25 16:28:43 -05:00
1 parent 4c02e44122
commit b614c30bc2
20 files changed
+576 -496

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
namespace CalamityMod.DataStructures
{
/// <summary>
/// A <see cref="HeapDict{TKey, TValue}"/> is a Dictionary-like data structure
/// that also keeps its entries in a binary-heap ordered by <see cref="TValue"/> (The priority).<br/>
/// This allows for O(log n) retrievals of the <see cref="TKey"/> with the lowest <see cref="TValue"/>
/// (Thanks to the MinHeap/PriorityQueue structure) and O(1) lookups of any element (Thanks to the Dictionary structure).<br/>
/// This data structure is specially useful for graph algorithms where getting the minimum element is a constant process, like A*.<br/>
/// It essentially combines a <see cref="PriorityQueue{TElement, TPriority}"/> and a <see cref="Dictionary{TKey, TValue}"/> into one data structure.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
public class HeapDict<TKey, TValue> where TValue : IComparable<TValue>
{
private readonly Dictionary<TKey, int> _indexMap = [];
private readonly List<(TKey Key, TValue Value)> _heap = [];
public int Count => _heap.Count;
public void Add(TKey key, TValue value)
{
if (_indexMap.TryGetValue(key, out int index))
{
TValue oldValue = _heap[index].Value;
_heap[index] = (key, value);
int cmp = value.CompareTo(oldValue);
if (cmp < 0)
HeapifyUp(index);
else if (cmp > 0)
HeapifyDown(index);
}
else
{
_heap.Add((key, value));
index = _heap.Count - 1;
_indexMap[key] = index;
HeapifyUp(index);
}
}
public (TKey, TValue) PopMin()
{
if (_heap.Count == 0)
throw new InvalidOperationException("Heap is empty");
var min = _heap[0];
var last = _heap[^1];
_heap[0] = last;
_indexMap[last.Key] = 0;
_heap.RemoveAt(_heap.Count - 1);
_indexMap.Remove(min.Key);
if (_heap.Count > 0)
HeapifyDown(0);
return min;
}
public (TKey, TValue) PeekMin()
{
if (_heap.Count == 0)
throw new InvalidOperationException("Heap is empty");
return _heap[0];
}
private void HeapifyUp(int index)
{
while (index > 0)
{
int parent = (index - 1) / 2;
if (_heap[index].Value.CompareTo(_heap[parent].Value) >= 0)
break;
Swap(index, parent);
index = parent;
}
}
private void HeapifyDown(int index)
{
int lastIndex = _heap.Count - 1;
while (true)
{
int left = 2 * index + 1;
int right = 2 * index + 2;
int smallest = index;
if (left <= lastIndex && _heap[left].Value.CompareTo(_heap[smallest].Value) < 0)
smallest = left;
if (right <= lastIndex && _heap[right].Value.CompareTo(_heap[smallest].Value) < 0)
smallest = right;
if (smallest == index)
break;
Swap(index, smallest);
index = smallest;
}
}
private void Swap(int i, int j)
{
(_heap[i], _heap[j]) = (_heap[j], _heap[i]);
_indexMap[_heap[i].Key] = i;
_indexMap[_heap[j].Key] = j;
}
public bool ContainsKey(TKey key) => _indexMap.ContainsKey(key);
public TValue GetValue(TKey key) => _heap[_indexMap[key]].Value;
}
}
+10 -12
View File
@@ -116,11 +116,9 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.6f,
MaxSpeed = 4f,
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.6f;
MaxSpeed = 4f;
}
if (NPC.wet)
{
@@ -150,7 +148,7 @@ namespace CalamityMod.NPCs.SunkenSea
public void IdleBehavior()
{
// At random, the mob will choose a random nearby point and pathfind there.
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity));
}
public void FleeBehavior()
@@ -159,30 +157,30 @@ namespace CalamityMod.NPCs.SunkenSea
if (CurrentPredator == null)
{
CurrentBehavior = (int)PhaseType.Idle;
pathfinding.MaxSpeed = 4;
MaxSpeed = 4f;
return;
}
pathfinding.MaxSpeed = 8;
MaxSpeed = 8f;
// 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.
Point lookAheadPosition = (NPC.Center + NPC.DirectionFrom(CurrentPredator.Center) * FleeTileAnticipationDistance).ToTileCoordinates();
if (!CalamityUtils.ParanoidTileRetrieval(lookAheadPosition.X, lookAheadPosition.Y).IsTileSolid())
{
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * pathfinding.Acceleration;
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration;
pathfinding.ClearResults();
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed;
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
{
float distanceFromAvoided = Vector2.Distance(NPC.Center, CurrentPredator.Center);
randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f);
NPC.netUpdate = true;
pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity));
}
}
+12 -16
View File
@@ -114,11 +114,9 @@ namespace CalamityMod.NPCs.SunkenSea
public override void OnSpawn(IEntitySource source)
{
pathfinding = new PathfindingManager(NPC)
{
MaxSpeed = 4.85f,
Acceleration = 0.5f
};
pathfinding = new PathfindingManager(this);
MaxSpeed = 4.85f;
Acceleration = 0.5f;
CurrentBehavior = IdleBehavior;
}
@@ -127,11 +125,9 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
MaxSpeed = 4.85f,
Acceleration = 0.5f
};
pathfinding = new PathfindingManager(this);
MaxSpeed = 4.85f;
Acceleration = 0.5f;
}
CurrentBehavior?.Invoke();
@@ -160,7 +156,7 @@ namespace CalamityMod.NPCs.SunkenSea
if (newBehavior == OutOfWaterBehavior)
NPC.noGravity = false;
pathfinding.MaxSpeed = newBehavior == FleeBehavior ? 6.5f : 5f;
MaxSpeed = newBehavior == FleeBehavior ? 6.5f : 5f;
}
private void IdleBehavior()
@@ -175,7 +171,7 @@ namespace CalamityMod.NPCs.SunkenSea
NPC.velocity *= 0.98f;
}
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(200f, 800f), SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(200f, 800f), SunkenSeaTileValidity));
}
private void AttackBehavior()
{
@@ -237,19 +233,19 @@ namespace CalamityMod.NPCs.SunkenSea
// Flee in a straight line if possible, otherwise pathfind away from the attacker.
if (!Main.tile[(NPC.Center + NPC.DirectionFrom(AvoidedEntity.Center) * 64f).ToTileCoordinates()].IsTileSolid())
{
NPC.velocity += NPC.DirectionFrom(AvoidedEntity.Center) * pathfinding.Acceleration;
NPC.velocity += NPC.DirectionFrom(AvoidedEntity.Center) * Acceleration;
pathfinding.ClearResults();
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed;
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
{
float distanceFromAvoided = Vector2.Distance(NPC.Center, AvoidedEntity.Center);
Vector2 pathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f);
NPC.netUpdate = true;
pathfinding.DoPathfinding(new(NPC.Center, pathPoint, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, pathPoint, SunkenSeaTileValidity));
}
}
private void OutOfWaterBehavior()
+4 -7
View File
@@ -159,13 +159,10 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.1f,
MaxSpeed = 1f,
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.1f;
MaxSpeed = 1f;
}
CreateTentacles();
NPC.ai[2]++;
@@ -253,7 +250,7 @@ namespace CalamityMod.NPCs.SunkenSea
// Move towards target
else if (target != null)
{
pathfinding.DoPathfinding(new PathfindingParameters(NPC.Center, target.Center, SunkenSeaTileValiditySizeless));
pathfinding.DoPathfinding(new PathfindingParameters(this, NPC.Center, target.Center, SunkenSeaTileValiditySizeless));
if (pathfinding.Path.Count > 0)
if (pathfinding.Path[^1].Distance(target.Center) > 300)
{
+29 -23
View File
@@ -94,11 +94,9 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.3f,
MaxSpeed = 3f,
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.3f;
MaxSpeed = 3f;
}
if (NPC.direction == 0)
{
@@ -166,20 +164,7 @@ namespace CalamityMod.NPCs.SunkenSea
NPC.ai[2] = Main.rand.Next(13, 30);
// With sight, just go straight at him. Without it, try to pathfind over them.
pathfinding.DoPathfinding(new(NPC.Center, currentTarget.Center, SunkenSeaTileValidity), forceNewTask: huntReady);
pathfinding.CustomIdleBehavior = () =>
{
if (currentTarget != null)
{
NPC.velocity += NPC.DirectionTo(currentTarget.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;
};
pathfinding.DoPathfinding(new(this, NPC.Center, currentTarget.Center, SunkenSeaTileValidity), forceNewTask: huntReady);
NPC.ai[2]--;
@@ -248,19 +233,19 @@ namespace CalamityMod.NPCs.SunkenSea
// Try to manuever if there are any obstacles.
if (!Main.tile[(NPC.Center + NPC.DirectionFrom(CurrentPredator.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid())
{
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * pathfinding.Acceleration;
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration;
pathfinding.ClearResults();
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed;
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
{
float distanceFromAvoided = Vector2.Distance(NPC.Center, CurrentPredator.Center);
randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f);
NPC.netUpdate = true;
pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity));
}
break;
}
@@ -329,6 +314,27 @@ namespace CalamityMod.NPCs.SunkenSea
SquishY = 1.05f;
}
public override void AwaitingPathBehavior()
{
Player target = Main.player[NPC.target];
bool hasSight = Collision.CanHitLine(NPC.Center, 1, 1, target.Center, 1, 1);
if (NPC.ai[0] == 1f && (currentTarget.Distance(NPC.Center) > 300 || !hasSight || currentTarget is NPC))
{
if (currentTarget != null)
{
NPC.velocity += NPC.DirectionTo(currentTarget.Center) * Acceleration;
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
NPC.velocity *= 0.95f;
}
else
base.AwaitingPathBehavior();
}
protected override bool NPCSearchFilter(NPC n)
{
return base.NPCSearchFilter(n) || (n == CurrentPredator || n == CurrentPrey) && Vector2.DistanceSquared(NPC.Center, n.Center) < 900f * 900f;
+38 -46
View File
@@ -116,11 +116,9 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.2f,
MaxSpeed = 3f,
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.2f;
MaxSpeed = 3f;
}
if (NPC.direction == 0)
{
@@ -154,24 +152,11 @@ namespace CalamityMod.NPCs.SunkenSea
NPC.ai[2] = Main.rand.Next(13, 30);
// With sight, just go straight at him. Without it, try to pathfind over them.
pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), forceNewTask: huntReady);
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;
};
pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), forceNewTask: huntReady);
}
else
{
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity));
}
break;
case (int)PhaseType.Attacking:
@@ -181,12 +166,12 @@ namespace CalamityMod.NPCs.SunkenSea
CurrentPhase = (int)PhaseType.Idle;
Timer = 0;
NPC.ai[2] = 0;
pathfinding.MaxSpeed = 3;
pathfinding.Acceleration = 0.2f;
MaxSpeed = 3;
Acceleration = 0.2f;
break;
}
pathfinding.MaxSpeed = 8;
pathfinding.Acceleration = 0.3f;
MaxSpeed = 8;
Acceleration = 0.3f;
NPC.chaseable = true;
bool hasSight = Collision.CanHitLine(NPC.Center, 1, 1, currentTarget.Center, 1, 1);
// If the target is too far from its shooting range or a tile is in the way, move closer
@@ -197,20 +182,7 @@ namespace CalamityMod.NPCs.SunkenSea
NPC.ai[2] = Main.rand.Next(13, 30);
// With sight, just go straight at him. Without it, try to pathfind over them.
pathfinding.DoPathfinding(new(NPC.Center, currentTarget.Center, SunkenSeaTileValidity), forceNewTask: restart);
pathfinding.CustomIdleBehavior = () =>
{
if (currentTarget != null)
{
NPC.velocity += NPC.DirectionTo(currentTarget.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;
};
pathfinding.DoPathfinding(new(this, NPC.Center, currentTarget.Center, SunkenSeaTileValidity), forceNewTask: restart);
NPC.ai[2]--;
}
@@ -248,8 +220,8 @@ namespace CalamityMod.NPCs.SunkenSea
{
CurrentPhase = currentTarget != null ? (int)PhaseType.Attacking : (int)PhaseType.Idle;
Timer = 0;
pathfinding.MaxSpeed = 3;
pathfinding.Acceleration = 0.2f;
MaxSpeed = 3;
Acceleration = 0.2f;
NPC.ai[2] = currentTarget != null ? 0 : 120;
break;
}
@@ -258,8 +230,8 @@ namespace CalamityMod.NPCs.SunkenSea
NPC.spriteDirection = NPC.direction *= -1;
}
Timer++;
pathfinding.MaxSpeed = 8;
pathfinding.Acceleration = 0.4f;
MaxSpeed = 8;
Acceleration = 0.4f;
if (Math.Abs(NPC.velocity.X) > 0)
{
@@ -274,19 +246,19 @@ namespace CalamityMod.NPCs.SunkenSea
// Try to manuever if there are any obstacles.
if (!Main.tile[(NPC.Center + NPC.DirectionFrom(currentTarget.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid())
{
NPC.velocity += NPC.DirectionFrom(currentTarget.Center) * pathfinding.Acceleration;
NPC.velocity += NPC.DirectionFrom(currentTarget.Center) * Acceleration;
pathfinding.ClearResults();
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed;
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
{
float distanceFromAvoided = Vector2.Distance(NPC.Center, currentTarget.Center);
randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f);
NPC.netUpdate = true;
pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity));
}
break;
}
@@ -344,6 +316,26 @@ namespace CalamityMod.NPCs.SunkenSea
public override bool CanBeHitByNPC(NPC attacker) => PredatorIDs.Contains(attacker.type);
public override void AwaitingPathBehavior()
{
bool hasSight = Collision.CanHitLine(NPC.Center, 1, 1, currentTarget.Center, 1, 1);
if (CurrentPhase == (int)PhaseType.Idle && CurrentPrey != null || CurrentPhase == (int)PhaseType.Attacking && currentTarget.Distance(NPC.Center) > 200 || !hasSight)
{
if (CurrentPrey != null)
{
NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration;
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
NPC.velocity *= 0.95f;
}
else
base.AwaitingPathBehavior();
}
public override void SendExtraAI(BinaryWriter writer)
{
writer.WriteVector2(randomPathPoint);
+18 -20
View File
@@ -125,11 +125,9 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.5f,
MaxSpeed = 4f,
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.5f;
MaxSpeed = 4f;
}
if (NPC.ai[3] <= 0)
{
@@ -171,7 +169,7 @@ namespace CalamityMod.NPCs.SunkenSea
public void IdleBehavior()
{
// At random, the mob will choose a random nearby point and pathfind there.
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), LavaTileValidityLenient));
pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), LavaTileValidityLenient));
}
/// <summary>
@@ -194,29 +192,29 @@ namespace CalamityMod.NPCs.SunkenSea
if (CurrentPredator == null)
{
CurrentBehavior = (int)PhaseType.Idle;
pathfinding.MaxSpeed = 4;
MaxSpeed = 4;
return;
}
pathfinding.MaxSpeed = 8;
MaxSpeed = 8;
// 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(CurrentPredator.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid())
{
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * pathfinding.Acceleration;
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration;
pathfinding.ClearResults();
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed;
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
{
float distanceFromAvoided = Vector2.Distance(NPC.Center, CurrentPredator.Center);
randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f);
NPC.netUpdate = true;
pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, LavaTileValidityLenient));
pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, LavaTileValidityLenient));
}
}
@@ -224,13 +222,13 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (CurrentPrey == null)
{
pathfinding.MaxSpeed = 4;
MaxSpeed = 4;
CurrentBehavior = (int)PhaseType.Idle;
pathfinding.ClearResults();
return;
}
pathfinding.MaxSpeed = 8;
pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, LavaTileValidityLenient));
MaxSpeed = 8;
pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPrey.Center, LavaTileValidityLenient));
}
public void HostileBehavior()
@@ -238,7 +236,7 @@ namespace CalamityMod.NPCs.SunkenSea
// Reset
if (CurrentPlayer == null || !NPC.HasSight(CurrentPlayer.Center))
{
pathfinding.MaxSpeed = 4;
MaxSpeed = 4;
CurrentBehavior = (int)PhaseType.Idle;
NPC.ai[2] = 0;
pathfinding.ClearResults();
@@ -277,7 +275,7 @@ namespace CalamityMod.NPCs.SunkenSea
// Go to the location if not close enough, otherwise slow down
if (NPC.Distance(destination) > distNeeded)
{
pathfinding.DoPathfinding(new(NPC.Center, destination));
pathfinding.DoPathfinding(new(this, NPC.Center, destination));
}
else
{
@@ -292,8 +290,8 @@ namespace CalamityMod.NPCs.SunkenSea
{
NPC.velocity.Y = 4;
}
pathfinding.MaxSpeed = 6;
pathfinding.DoPathfinding(new(NPC.Center, CurrentPlayer.Center, LavaTileValidityLenient));
MaxSpeed = 6;
pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPlayer.Center, LavaTileValidityLenient));
// Mark the fish as currently trying to chase the player
NPC.Calamity().newAI[0] = 1;
}
@@ -365,7 +363,7 @@ namespace CalamityMod.NPCs.SunkenSea
// Air attack, shoot projectiles at the player in arches
else if (useAirAI)
{
pathfinding.MaxSpeed = 4;
MaxSpeed = 4;
ShootTimer--;
if (ShootTimer <= -40)
+13 -15
View File
@@ -180,11 +180,9 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.5f,
MaxSpeed = 4f,
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.5f;
MaxSpeed = 4f;
}
// Reset polyp index in case the polyp dies
if (PolypIndex > -1)
@@ -238,7 +236,7 @@ namespace CalamityMod.NPCs.SunkenSea
public void IdleBehavior()
{
// At random, the mob will choose a random nearby point and pathfind there.
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(100, IdleMaxPathDistance), SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(100, IdleMaxPathDistance), SunkenSeaTileValidity));
}
public void HideBehavior()
{
@@ -253,10 +251,10 @@ namespace CalamityMod.NPCs.SunkenSea
// Become invincible while hiding
NPC.dontTakeDamage = true;
pathfinding.MaxSpeed = 2;
MaxSpeed = 2;
// At random, the mob will choose a random nearby point and pathfind there.
pathfinding.DoPathfinding(new(NPC.Center, Main.npc[PolypIndex].Center + Main.rand.NextVector2Unit() * Main.rand.Next(20, 30), SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, Main.npc[PolypIndex].Center + Main.rand.NextVector2Unit() * Main.rand.Next(20, 30), SunkenSeaTileValidity));
}
public void FleeBehavior()
@@ -265,18 +263,18 @@ namespace CalamityMod.NPCs.SunkenSea
if (CurrentPredator == null && PolypIndex <= -1)
{
CurrentBehavior = (int)PhaseType.Idle;
pathfinding.MaxSpeed = 4;
MaxSpeed = 4;
return;
}
pathfinding.MaxSpeed = 6;
MaxSpeed = 6;
// If a polyp is found, try to run into it
if (PolypIndex > -1)
{
NPC.netUpdate = true;
Vector2 polypPos = Main.npc[PolypIndex].position;
pathfinding.DoPathfinding(new(NPC.Center, polypPos, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, polypPos, SunkenSeaTileValidity));
if (NPC.Distance(Main.npc[PolypIndex].Center) < 50)
{
@@ -288,19 +286,19 @@ namespace CalamityMod.NPCs.SunkenSea
// Try to manuever if there are any obstacles.
else if (!Main.tile[(NPC.Center + NPC.DirectionFrom(CurrentPredator.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid())
{
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * pathfinding.Acceleration;
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration;
pathfinding.ClearResults();
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed;
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
{
float distanceFromAvoided = Vector2.Distance(NPC.Center, CurrentPredator.Center);
randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f);
NPC.netUpdate = true;
pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity));
}
}
+4 -6
View File
@@ -103,10 +103,8 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
MaxSpeed = 1.8f
};
pathfinding = new PathfindingManager(this);
MaxSpeed = 1.8f;
}
NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X);
@@ -154,7 +152,7 @@ namespace CalamityMod.NPCs.SunkenSea
// Go to the vine if not far enough
if (tilePos.Value.Distance(NPC.Center) > 40 && BiteCount == 0)
{
pathfinding.DoPathfinding(new(NPC.Center, tilePos.Value, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, tilePos.Value, SunkenSeaTileValidity));
}
// Slow down and eat the kelp
else
@@ -189,7 +187,7 @@ namespace CalamityMod.NPCs.SunkenSea
TileX = 0;
TileY = 0;
BiteCount = 0;
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(200f, 800f), SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(200f, 800f), SunkenSeaTileValidity));
}
}
else
+15 -17
View File
@@ -244,11 +244,9 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.5f,
MaxSpeed = 4f,
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.5f;
MaxSpeed = 4f;
}
// Spawn more guppies if a leader/naturally spawned guppy
if (Role == 0 && NPC.releaseOwner == 255)
@@ -280,12 +278,12 @@ namespace CalamityMod.NPCs.SunkenSea
// Just do generic pathfinding if a leader. Target prey if one exists
case (int)PhaseType.Idle:
{
pathfinding.Acceleration = 0.5f;
pathfinding.MaxSpeed = 4;
Acceleration = 0.5f;
MaxSpeed = 4;
if (CurrentPrey is not null)
pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity));
else
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity));
}
break;
// The unenlightened masses, They cannot make the judgement call
@@ -302,7 +300,7 @@ namespace CalamityMod.NPCs.SunkenSea
return;
if (NPC.Distance(owner.Center) > 20)
pathfinding.DoPathfinding(new(NPC.Center, owner.Center, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, owner.Center, SunkenSeaTileValidity));
else
{
float passiveMvtFloat = 0.5f;
@@ -421,8 +419,8 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (CurrentPredator is not null)
{
pathfinding.Acceleration = 0.6f;
pathfinding.MaxSpeed = 6;
Acceleration = 0.6f;
MaxSpeed = 6;
Vector2? tilePos = tilePosition;
// Find a sea prism
@@ -436,7 +434,7 @@ namespace CalamityMod.NPCs.SunkenSea
{
TileX = tilePos.Value.X;
TileY = tilePos.Value.Y;
pathfinding.DoPathfinding(new(NPC.Center, tilePos.Value, SunkenSeaTileValiditySizeless));
pathfinding.DoPathfinding(new(this, NPC.Center, tilePos.Value, SunkenSeaTileValiditySizeless));
if (NPC.Distance(tilePos.Value) < 16)
{
CurrentPhase = (int)PhaseType.Hiding;
@@ -448,19 +446,19 @@ namespace CalamityMod.NPCs.SunkenSea
// Try to manuever if there are any obstacles.
else if (!Main.tile[(NPC.Center + NPC.DirectionFrom(CurrentPredator.Center) * 96).ToTileCoordinates()].IsTileSolid())
{
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * pathfinding.Acceleration;
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration;
pathfinding.ClearResults();
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed;
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
{
float distanceFromAvoided = Vector2.Distance(NPC.Center, CurrentPredator.Center);
randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f);
NPC.netUpdate = true;
pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity));
}
}
else
+35 -37
View File
@@ -107,10 +107,6 @@ namespace CalamityMod.NPCs.SunkenSea
public Vector2 Velocity { get => NPC.velocity; set => NPC.velocity = value; }
public float Acceleration => 0.4f;
public float MaxSpeed => 8f;
private Vector2 SpongeFoundPosition;
private bool HasEatenSponge;
@@ -131,12 +127,10 @@ namespace CalamityMod.NPCs.SunkenSea
public override void OnSpawn(IEntitySource source)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.4f,
MaxSpeed = 8f,
MinimumPointDistance = 60f
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.4f;
MaxSpeed = 8f;
MinimumPointDistance = 60f;
CurrentBehavior = IdlingBehavior;
NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt();
NPC.GravityMultiplier *= 2f;
@@ -147,12 +141,10 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.4f,
MaxSpeed = 8f,
MinimumPointDistance = 60f
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.4f;
MaxSpeed = 8f;
MinimumPointDistance = 60f;
}
CurrentBehavior?.Invoke();
@@ -206,8 +198,8 @@ namespace CalamityMod.NPCs.SunkenSea
private void IdlingBehavior()
{
// At random, the mob will choose a random nearby point and pathfind there.
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(500f, 3000f), SunkenSeaTileValidity));
pathfinding.MaxSpeed = 6f;
pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(500f, 3000f), SunkenSeaTileValidity));
MaxSpeed = 6f;
}
private void FleeingBehavior()
@@ -235,8 +227,8 @@ namespace CalamityMod.NPCs.SunkenSea
}
while (!Main.tile[(NPC.Center + _randomPathPoint).ToTileCoordinates()].IsTileSolid());
NPC.netUpdate = true;
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + _randomPathPoint, SunkenSeaTileValidity));
pathfinding.MaxSpeed = 8f;
pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + _randomPathPoint, SunkenSeaTileValidity));
MaxSpeed = 8f;
}
else
{
@@ -263,21 +255,8 @@ namespace CalamityMod.NPCs.SunkenSea
HuntCooldown = Main.rand.Next(13, 30);
// With sight, just go straight at him. Without it, try to pathfind over them.
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;
};
pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPrey.Center, tileValidity: SunkenSeaTileValidity), forceNewTask: huntReady);
MaxSpeed = 8f;
HuntCooldown--;
}
@@ -299,8 +278,8 @@ namespace CalamityMod.NPCs.SunkenSea
}
else
{
pathfinding.DoPathfinding(new(NPC.Center, SpongeFoundPosition, SunkenSeaTileValidity));
pathfinding.MaxSpeed = 6f;
pathfinding.DoPathfinding(new(this, NPC.Center, SpongeFoundPosition, SunkenSeaTileValidity));
MaxSpeed = 6f;
}
}
@@ -361,6 +340,25 @@ namespace CalamityMod.NPCs.SunkenSea
public override bool CanBeHitByNPC(NPC attacker) => PredatorIDs.Contains(attacker.type);
public override void AwaitingPathBehavior()
{
if (CurrentBehavior == HuntBehavior)
{
if (CurrentPrey != null)
{
NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration;
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
NPC.velocity *= 0.95f;
}
else
base.AwaitingPathBehavior();
}
#endregion
#region Drawing & Animation
+9 -11
View File
@@ -76,11 +76,9 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.6f,
MaxSpeed = 5f,
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.6f;
MaxSpeed = 5f;
}
NPC owner = Main.npc[(int)NPC.ai[2]];
if (NPC.wet)
@@ -208,24 +206,24 @@ namespace CalamityMod.NPCs.SunkenSea
// Try to manuever if there are any obstacles.
if (!Main.tile[(NPC.Center + NPC.DirectionFrom(avoidedEntity.Center) * 96).ToTileCoordinates()].IsTileSolid())
{
NPC.velocity += NPC.DirectionFrom(avoidedEntity.Center) * pathfinding.Acceleration;
NPC.velocity += NPC.DirectionFrom(avoidedEntity.Center) * Acceleration;
pathfinding.ClearResults();
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed;
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;
pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity));
}
}
else
{
pathfinding.DoPathfinding(new(NPC.Center, Main.rand.NextVector2Unit() * Main.rand.Next(300, 1000), SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, Main.rand.NextVector2Unit() * Main.rand.Next(300, 1000), SunkenSeaTileValidity));
}
}
}
@@ -235,7 +233,7 @@ namespace CalamityMod.NPCs.SunkenSea
return;
if (NPC.Distance(owner.Center) > 200)
pathfinding.DoPathfinding(new(NPC.Center, owner.Center, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, owner.Center, SunkenSeaTileValidity));
else
{
float passiveMvtFloat = 0.5f;
+32 -30
View File
@@ -217,11 +217,9 @@ namespace CalamityMod.NPCs.SunkenSea
public override void OnSpawn(IEntitySource source)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.3f,
MaxSpeed = 6f,
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.3f;
MaxSpeed = 6f;
CurrentBehavior = IdlingBehavior;
NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt();
NPC.GravityMultiplier *= 2f;
@@ -232,11 +230,9 @@ namespace CalamityMod.NPCs.SunkenSea
{
if (pathfinding == null)
{
pathfinding = new PathfindingManager(NPC)
{
Acceleration = 0.3f,
MaxSpeed = 6f,
};
pathfinding = new PathfindingManager(this);
Acceleration = 0.3f;
MaxSpeed = 6f;
}
CurrentBehavior?.Invoke();
@@ -266,7 +262,7 @@ namespace CalamityMod.NPCs.SunkenSea
private void IdlingBehavior()
{
// At random, the mob will choose a random nearby point and pathfind there.
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity));
}
private void HuntingBehavior()
@@ -283,20 +279,7 @@ namespace CalamityMod.NPCs.SunkenSea
HuntCooldown = Main.rand.Next(13, 30);
// With sight, just go straight at him. Without it, try to pathfind over them.
pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), forceNewTask: huntReady);
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;
};
pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), forceNewTask: huntReady);
HuntCooldown--;
}
@@ -317,19 +300,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) * pathfinding.Acceleration;
NPC.velocity += NPC.DirectionFrom(_avoidedEntity.Center) * Acceleration;
pathfinding.ClearResults();
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed;
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;
pathfinding.DoPathfinding(new(NPC.Center, _randomPathPoint, SunkenSeaTileValidity));
pathfinding.DoPathfinding(new(this, NPC.Center, _randomPathPoint, SunkenSeaTileValidity));
}
// If it's capable of exploding and the predator's within distance, kaboom.
@@ -409,7 +392,7 @@ namespace CalamityMod.NPCs.SunkenSea
if (newBehavior == OutsideWaterBehavior)
NPC.noGravity = false;
pathfinding.MinimumPointDistance = newBehavior == HuntingBehavior ? 20f : 48f;
MinimumPointDistance = newBehavior == HuntingBehavior ? 20f : 48f;
}
protected override void OnPreyDetection(NPC prey)
@@ -528,6 +511,25 @@ namespace CalamityMod.NPCs.SunkenSea
}
}
public override void AwaitingPathBehavior()
{
if (CurrentBehavior == HuntingBehavior)
{
if (CurrentPrey != null)
{
NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration;
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
NPC.velocity *= 0.95f;
}
else
base.AwaitingPathBehavior();
}
public override float SpawnChance(NPCSpawnInfo spawnInfo)
{
if (spawnInfo.Water && !spawnInfo.Player.Calamity().clamity)
+31 -4
View File
@@ -2,8 +2,9 @@
using System.Collections.Generic;
using System.Linq;
using CalamityMod.Enums;
using CalamityMod.Pathfinding;
using CalamityMod.Pathfinding.Movements;
using CalamityMod.Systems.Collections;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.GameContent.Bestiary;
@@ -17,10 +18,10 @@ namespace CalamityMod.NPCs.SunkenSea
/// An abstract class that provides the necessary members for an NPC to function as a Sunken Sea NPC.<br/>
/// These NPCs can hunt both players and other NPCs, and maintain lists of NPCs they hunt and avoid.
/// </summary>
public abstract class SunkenSeaNPC : ModNPC
public abstract class SunkenSeaNPC : ModNPC, IPathfinder
{
protected PathfindingManager pathfinding = null;
private NPC _currentPrey;
private NPC _currentPredator;
private Player _currentPlayer;
@@ -203,7 +204,7 @@ namespace CalamityMod.NPCs.SunkenSea
public static bool SunkenSeaTileValidity(NPC npc, Point point, bool accountForSize = true)
{
Point actualFuckingPoint = new Point(point.X * 16, point.Y * 16);
if (accountForSize)
{
return npc.Hitbox.Contains(actualFuckingPoint)
@@ -229,5 +230,31 @@ namespace CalamityMod.NPCs.SunkenSea
|| !NPC.GetIntersectingHitboxPoints(
actualFuckingPoint, 10, 10).Any(a => Main.tile[a].IsTileSolidGround() || Main.tile[a].LiquidAmount < 255 || Main.tile[a].LiquidType != LiquidID.Lava);
}
#region IPathfinder Implementation
/// <summary>
/// The acceleration this PathfindingManager will impart to its Entity when making it follow a found path.<br />
/// This has no impact on the Entity's other behaviors, AI, etc.
/// </summary>
public float Acceleration { get; set; } = 0.2f;
/// <summary>
/// The maximum speed this PathfindingManager allow its Entity to move at when making it follow a found path.<br />
/// This has no impact on the Entity's other behaviors, AI, etc.
/// </summary>
public float MaxSpeed { get; set; } = 4f;
/// <summary>
/// The minimum distance this PathdingManager requires its Entity to reach from its target point before the point is marked as "reached".<br />
/// This has no impact on the Entity's other behaviors, AI, etc.
/// </summary>
public float MinimumPointDistance { get; set; } = 48f;
public virtual IEnumerable<IMovement> Movements => [new SunkenSeaSwimMovement(NPC)];
public virtual void AwaitingPathBehavior() => NPC.velocity *= 0.95f;
#endregion
}
}
+21
View File
@@ -0,0 +1,21 @@
using System.Collections.Generic;
using CalamityMod.Pathfinding.Movements;
namespace CalamityMod.Pathfinding
{
/// <summary>
/// Defines an interface for a class that can use pathfinding.
/// </summary>
public interface IPathfinder
{
/// <summary>
/// A enumerable collection of <see cref="IMovement"/> this pathfinder can use.
/// </summary>
IEnumerable<IMovement> Movements { get; }
/// <summary>
/// A method that defines behavior when the pathfinding is still being calculated.
/// </summary>
void AwaitingPathBehavior();
}
}
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Terraria.ModLoader;
namespace CalamityMod.Pathfinding.Movements
{
public abstract class BaseEntityMovement<TEntity>(TEntity pathfinder) : IMovement where TEntity : ModType, IPathfinder
{
public TEntity Pathfinder { get; } = pathfinder;
public abstract string RegistrationName { get; }
public abstract Func<Point, Point, float> Cost { get; }
public abstract void Start();
public abstract bool FollowPath(Vector2 nextPoint);
public abstract IEnumerable<Point> GetDestinations(Point current);
}
}
+45
View File
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
namespace CalamityMod.Pathfinding.Movements
{
/// <summary>
/// Defines an interface for what is a movement in the context of pathfinding.
/// Every movement has a cost function, and a way to follow a path.
/// </summary>
public interface IMovement
{
/// <summary>
/// The internal name given to this movement.<br/>
/// Needed to differentiate between movements.
/// </summary>
string RegistrationName { get; }
/// <summary>
/// The cost function of this movement.<br/>
/// Takes in two positions and returns the cost of the movement.
/// </summary>
Func<Point, Point, float> Cost { get; }
/// <summary>
/// Defines a method that is run whenever this movement starts execution.<br/>
/// Useful to get any variable set up for this movement's action.
/// </summary>
void Start();
/// <summary>
/// A method that defines the way to follow from one position to another.
/// </summary>
/// <param name="nextPoint">The destination of this movement.</param>
/// <returns><see langword="true"/> if it this movement has finished; otherwise <see langword="false"/>.</returns>
bool FollowPath(Vector2 nextPoint);
/// <summary>
/// Defines a method to retrieve the possiblement destinations that this movement can achieve
/// </summary>
/// <param name="current">The starting position where this movement takes place.</param>
/// <returns>An enumerable collection of <see cref="Point"/> with all the destinations.</returns>
IEnumerable<Point> GetDestinations(Point current);
}
}
+14
View File
@@ -0,0 +1,14 @@
using System.Collections.Generic;
using Microsoft.Xna.Framework;
namespace CalamityMod.Pathfinding.Movements
{
public abstract class Movement
{
public abstract float Cost { get; }
public abstract bool FollowPath(IPathfinder pathfinder, Vector2 nextPoint);
public abstract IEnumerable<Point> GetNeighborPositions(Point current);
}
}
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using CalamityMod.NPCs.SunkenSea;
using Microsoft.Xna.Framework;
using Terraria;
namespace CalamityMod.Pathfinding.Movements
{
public class SunkenSeaSwimMovement(NPC creature) : IMovement
{
public NPC Creature = creature;
private SunkenSeaNPC ssn => Creature.ModNPC<SunkenSeaNPC>();
public Func<Point, Point, float> Cost => (_, _) => 0;
public string RegistrationName => "Swim";
public bool FollowPath(Vector2 nextPoint)
{
// Accelerate to the target point.
Creature.velocity += (nextPoint - Creature.Center).SafeNormalize(Vector2.Zero) * ssn.Acceleration;
// Cap the speed if MaxSpeed has been surpassed.
if (Creature.velocity.LengthSquared() > ssn.MaxSpeed * ssn.MaxSpeed)
Creature.velocity = Creature.velocity.SafeNormalize(Vector2.UnitY) * ssn.MaxSpeed;
// If the NPC is within 48 pixels of its target point, consider the point reached.
if (Vector2.DistanceSquared(Creature.Center, nextPoint) < ssn.MinimumPointDistance * ssn.MinimumPointDistance)
return true;
// Otherwise, continue following.
return false;
}
public IEnumerable<Point> GetDestinations(Point current)
{
int nodeX = current.X;
int nodeY = current.Y;
foreach (var direction in CalamityUtils.Directions)
yield return new Point(nodeX + (int)direction.X, nodeY + (int)direction.Y);
}
public void Start() { }
}
}
+66 -252
View File
@@ -1,11 +1,12 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using CalamityMod.DataStructures;
using CalamityMod.Pathfinding;
using CalamityMod.Pathfinding.Movements;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using static CalamityMod.CalamityUtils;
namespace CalamityMod
@@ -17,6 +18,7 @@ namespace CalamityMod
internal static readonly Func<Point, Point, float> DefaultDistanceFunction = OctileDistance;
internal static readonly Func<Point, Point, float> DefaultHeuristic = OctileDistance;
internal readonly IPathfinder Pathfinder;
internal readonly Vector2 Start;
internal readonly Vector2 End;
internal readonly Func<Point, bool> TileValidity;
@@ -24,12 +26,14 @@ namespace CalamityMod
internal readonly Func<Point, Point, float> Heuristic;
public PathfindingParameters(
IPathfinder pathfinder,
Vector2 start,
Vector2 end,
Func<Point, bool> tileValidity = null,
Func<Point, Point, float> distanceFunction = null,
Func<Point, Point, float> heuristic = null)
{
Pathfinder = pathfinder;
Start = start;
End = end;
TileValidity = tileValidity;
@@ -44,33 +48,31 @@ namespace CalamityMod
/// Creates a new PathfindingManager for the selected entity.<br />
/// Entities should only ever need one PathfindingManager for their lifetime, but more can be created.
/// </summary>
/// <param name="e">The entity to pathfind for.</param>
public class PathfindingManager(Entity e)
/// <param name="p">The entity to pathfind for.</param>
public class PathfindingManager(IPathfinder p)
{
public List<Vector2> Path { get => lastSuccessfulTask?.Result ?? []; }
public List<Vector2> Path
{
get
{
if (lastSuccessfulTask == null)
return [];
else if (lastSuccessfulTask.Result == null)
return [];
else
{
var path = new List<Vector2>();
foreach (var node in lastSuccessfulTask.Result)
path.Add(node.Position.ToWorldCoordinates());
return path;
}
}
}
/// <summary>
/// The entity which this PathfindingManager manages. This cannot be changed after creation.
/// </summary>
internal readonly Entity entity = e;
/// <summary>
/// The acceleration this PathfindingManager will impart to its Entity when making it follow a found path.<br />
/// This has no impact on the Entity's other behaviors, AI, etc.
/// </summary>
internal float Acceleration { get; set; } = 0.2f;
/// <summary>
/// The maximum speed this PathfindingManager allow its Entity to move at when making it follow a found path.<br />
/// This has no impact on the Entity's other behaviors, AI, etc.
/// </summary>
internal float MaxSpeed { get; set; } = 4f;
/// <summary>
/// The minimum distance this PathdingManager requires its Entity to reach from its target point before the point is marked as "reached".<br />
/// This has no impact on the Entity's other behaviors, AI, etc.
/// </summary>
internal float MinimumPointDistance { get; set; } = 48f;
internal readonly IPathfinder pathfinder = p;
/// <summary>
/// The last completed pathfinding task that this manager has performed.<br />
@@ -87,22 +89,6 @@ namespace CalamityMod
/// </summary>
private PathfindingTask currentTask;
/// <summary>
/// You may override the path-following behavior imposed on the Entity by the PathfindingManager by providing a Func here.
/// <br /><br />
/// This Func should return <see langword="true"/> when the entity has reached its target point, and <see langword="false"/> otherwise.<br/>
/// </summary>
public Func<Vector2, bool> CustomFollowPath { get; set; }
/// <summary>
/// You may override the idling behavior imposed on the Entity by the PathfindingManager by providing an Action here.
/// <br /><br />
/// This Action has no parameters and no return value, and can do basically anything you want.
/// <br />
/// It will usually only run for a frame or two while the PathfindingManager is finding the next path to take.
/// </summary>
public Action CustomIdleBehavior { get; set; }
/// <summary>
/// Finds a path based on the specified parameters and assigns it to this manager's entity.<br/>
/// This method does not force the entity to begin following the path - it only locates a new path.
@@ -125,7 +111,7 @@ namespace CalamityMod
{
// 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 sameEndPosition = parameters.End.ToTileCoordinates() == currentTask.work.End;
bool forceNewPathAttempt = forceNewTask && !sameEndPosition;
if (forceNewPathAttempt)
@@ -166,16 +152,19 @@ namespace CalamityMod
{
if (lastSuccessfulTask is null)
{
IdleBehavior();
pathfinder.AwaitingPathBehavior();
return;
}
Vector2 nextPoint = lastSuccessfulTask.Result[0];
PathfindingNode nextPoint = lastSuccessfulTask.Result[0];
// If that point is reached, it is removed from the list of points to follow.
bool nextPointReached = FollowPath(nextPoint);
bool nextPointReached = nextPoint.Move.FollowPath(nextPoint.Position.ToWorldCoordinates());
if (nextPointReached)
{
Main.NewText(lastSuccessfulTask.Result[0].Move.RegistrationName);
lastSuccessfulTask.Result.RemoveAt(0);
}
// If the previous successful found path has been followed to its endpoint, delete the task.
if (lastSuccessfulTask.Result.Count == 0)
@@ -192,51 +181,6 @@ namespace CalamityMod
PathfindingBehavior();
}
private bool DefaultFollowPath(Vector2 nextPoint)
{
// Accelerate to the target point.
entity.velocity += (nextPoint - entity.Center).SafeNormalize(Vector2.Zero) * Acceleration;
// Cap the speed if MaxSpeed has been surpassed.
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(entity.Center, nextPoint) < MinimumPointDistance * MinimumPointDistance)
return true;
// Otherwise, continue following.
return false;
}
/// <summary>
/// Defines how this entity should move to the next point. Contains a default implementation with basic acceleration towards the next point.<br/>
/// This method should return <see langword="true"/> when the entity has reached its target point, and <see langword="false"/> otherwise.<br/>
/// <br/>
/// The target point is specified by <paramref name="nextPoint"/> - usually index 0 in the <see cref="Paths"/> task result.
/// <br /><br />
/// The behavior of this function can be completely overridden by providing a CustomFollowPath Func.
/// </summary>
/// <param name="nextPoint">The next point in the path that this PathfindingManager has made.</param>
/// <returns>Whether or not the destination has been reached.</returns>
public bool FollowPath(Vector2 nextPoint) => CustomFollowPath?.Invoke(nextPoint) ?? DefaultFollowPath(nextPoint);
private static readonly float DefaultSlowdown = 0.95f;
private void DefaultIdleBehavior() => entity.velocity *= DefaultSlowdown;
/// <summary>
/// Defines how this entity should behave while there is no current path to follow.<br/>
/// By default, decelerates to a stop using the DefaultSlowdown value.<br />
/// This behavior will usually only run for a frame or two while the PathfindingManager is finding the next path to take.
/// </summary>
public void IdleBehavior()
{
if (CustomIdleBehavior is not null)
CustomIdleBehavior();
else
DefaultIdleBehavior();
}
public void ClearResults()
{
currentTask = null;
@@ -253,7 +197,7 @@ namespace CalamityMod
/// <summary>
/// The result of this pathfinding task.
/// </summary>
internal List<Vector2> Result { get => _task.Task.Result; }
internal List<PathfindingNode> Result { get => _task.Task.Result; }
/// <summary>
/// Whether this pathfinding task has completed running.
@@ -266,7 +210,7 @@ namespace CalamityMod
internal bool Running { get; private set; } = false;
// Interal task representation of the work.
internal readonly TaskCompletionSource<List<Vector2>> _task = new();
internal readonly TaskCompletionSource<List<PathfindingNode>> _task = new();
// Internal containing object for the actual work.
internal readonly PathfindingWork work = new(parameters);
@@ -293,118 +237,6 @@ namespace CalamityMod
#region Pathfinding Work Record
/// <summary>
/// A <see cref="HeapDict{TKey, TValue}"/> is a Dictionary-like data structure
/// that also keeps its entries in a binary-heap ordered by <see cref="TValue"/> (The priority).<br/>
/// This allows for O(log n) retrievals of the <see cref="TKey"/> with the lowest <see cref="TValue"/>
/// (Thanks to the MinHeap/PriorityQueue structure) and O(1) lookups of any element (Thanks to the Dictionary structure).<br/>
/// This data structure is specially useful for graph algorithms where getting the minimum element is a constant process, like A*.<br/>
/// It essentially combines a <see cref="PriorityQueue{TElement, TPriority}"/> and a <see cref="Dictionary{TKey, TValue}"/> into one data structure.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
public class HeapDict<TKey, TValue> where TValue : IComparable<TValue>
{
private readonly Dictionary<TKey, int> _indexMap = [];
private readonly List<(TKey Key, TValue Value)> _heap = [];
public int Count => _heap.Count;
public void Add(TKey key, TValue value)
{
if (_indexMap.TryGetValue(key, out int index))
{
TValue oldValue = _heap[index].Value;
_heap[index] = (key, value);
int cmp = value.CompareTo(oldValue);
if (cmp < 0)
HeapifyUp(index);
else if (cmp > 0)
HeapifyDown(index);
}
else
{
_heap.Add((key, value));
index = _heap.Count - 1;
_indexMap[key] = index;
HeapifyUp(index);
}
}
public (TKey, TValue) PopMin()
{
if (_heap.Count == 0)
throw new InvalidOperationException("Heap is empty");
var min = _heap[0];
var last = _heap[^1];
_heap[0] = last;
_indexMap[last.Key] = 0;
_heap.RemoveAt(_heap.Count - 1);
_indexMap.Remove(min.Key);
if (_heap.Count > 0)
HeapifyDown(0);
return min;
}
public (TKey, TValue) PeekMin()
{
if (_heap.Count == 0)
throw new InvalidOperationException("Heap is empty");
return _heap[0];
}
private void HeapifyUp(int index)
{
while (index > 0)
{
int parent = (index - 1) / 2;
if (_heap[index].Value.CompareTo(_heap[parent].Value) >= 0)
break;
Swap(index, parent);
index = parent;
}
}
private void HeapifyDown(int index)
{
int lastIndex = _heap.Count - 1;
while (true)
{
int left = 2 * index + 1;
int right = 2 * index + 2;
int smallest = index;
if (left <= lastIndex && _heap[left].Value.CompareTo(_heap[smallest].Value) < 0)
smallest = left;
if (right <= lastIndex && _heap[right].Value.CompareTo(_heap[smallest].Value) < 0)
smallest = right;
if (smallest == index)
break;
Swap(index, smallest);
index = smallest;
}
}
private void Swap(int i, int j)
{
(_heap[i], _heap[j]) = (_heap[j], _heap[i]);
_indexMap[_heap[i].Key] = i;
_indexMap[_heap[j].Key] = j;
}
public bool ContainsKey(TKey key) => _indexMap.ContainsKey(key);
public TValue GetValue(TKey key) => _heap[_indexMap[key]].Value;
}
/// <summary>
/// Represents the working computation for a <see cref="PathfindingTask"/>.
/// </summary>
@@ -421,28 +253,13 @@ namespace CalamityMod
/// - <see cref="Heuristic"/>: A function that estimates the cost from a given point to the end point. Defaults to <see cref="OctileDistance"/>.<br/>
/// </para>
/// </remarks>
private record PathfindingWork(PathfindingNode Start, PathfindingNode End, Func<Point, bool> TileValidity, Func<Point, Point, float> DistanceFunction, Func<Point, Point, float> Heuristic)
private record PathfindingWork(IPathfinder Pathfinder, Point Start, Point End, Func<Point, bool> TileValidity, Func<Point, Point, float> DistanceFunction, Func<Point, Point, float> Heuristic)
{
public PathfindingWork(
Point start,
Point end,
float minimalPointDistance,
Func<Point, bool> tileValidity = null,
Func<Point, Point, float> distanceFunction = null,
Func<Point, Point, float> heuristic = null) : this(
new PathfindingNode(start),
new PathfindingNode(end),
tileValidity ?? PathfindingParameters.DefaultTileValidity,
distanceFunction ?? PathfindingParameters.DefaultDistanceFunction,
heuristic ?? PathfindingParameters.DefaultHeuristic
)
{
}
public PathfindingWork(
PathfindingParameters p) : this(
new PathfindingNode(p.Start.ToTileCoordinates()),
new PathfindingNode(p.End.ToTileCoordinates()),
p.Pathfinder,
p.Start.ToTileCoordinates(),
p.End.ToTileCoordinates(),
p.TileValidity ?? PathfindingParameters.DefaultTileValidity,
p.DistanceFunction ?? PathfindingParameters.DefaultDistanceFunction,
p.Heuristic ?? PathfindingParameters.DefaultHeuristic
@@ -457,10 +274,10 @@ namespace CalamityMod
/// <returns>
/// A list of <see cref="Vector2"/> positions representing the path from start to end, or <see langword="null"/> if no path is found.
/// </returns>
internal List<Vector2> CalculatePath()
internal List<PathfindingNode> CalculatePath()
{
// Trying to pathfind to a solid tile would be a waste of resources, we don't even consider pathfinding to it.
Tile endTile = ParanoidTileRetrieval(End.Position.X, End.Position.Y);
Tile endTile = ParanoidTileRetrieval(End.X, End.Y);
if (endTile.IsTileSolid())
return null;
@@ -468,8 +285,12 @@ namespace CalamityMod
var explored = new HashSet<PathfindingNode>();
// At first, we only know the starting node.
(Start.Distance, Start.Total) = (0, Heuristic.Invoke(Start.Position, End.Position));
candidates.Add(Start, Start.Total);
foreach (var movement in Pathfinder.Movements)
{
var start = new PathfindingNode(Start, movement);
(start.Distance, start.Total) = (0f, Heuristic.Invoke(start.Position, End));
candidates.Add(start, start.Total);
}
while (candidates.Count > 0)
{
@@ -477,7 +298,7 @@ namespace CalamityMod
var current = candidates.PeekMin().Item1;
// Check if we've reached the goal.
if (current.Position == End.Position)
if (current.Position == End)
return current.ReconstructPath();
// Add the current node to the set of explored nodes so we don't have to check it again,
@@ -485,7 +306,7 @@ namespace CalamityMod
candidates.PopMin();
explored.Add(current);
foreach (var neighbor in current.GetNeighbors())
foreach (var neighbor in current.GetNeighborSteps(Pathfinder))
{
// If the node has already been explored or is not a valid neighbor, we can skip it.
if (explored.Contains(neighbor) || Main.tile[neighbor.Position].IsTileSolid() || !TileValidity.Invoke(neighbor.Position))
@@ -499,7 +320,7 @@ namespace CalamityMod
neighbor.Parent = current;
neighbor.Distance = newDistance;
neighbor.Total = newDistance + Heuristic.Invoke(neighbor.Position, End.Position);
neighbor.Total = newDistance + Heuristic.Invoke(neighbor.Position, End) + neighbor.Move.Cost.Invoke(current.Position, neighbor.Position);
// We put it on our heap of candidates.
// If the node was already on our heap of candidates, it updates its priority.
@@ -508,7 +329,7 @@ namespace CalamityMod
}
// If we ran out of candidates and no path was found, we return null.
return null;
return null;
}
}
#endregion
@@ -517,48 +338,41 @@ namespace CalamityMod
/// <summary>
/// Represents a node in a pathfinding algorithm, containing position, cost, and parent information.
/// </summary>
private class PathfindingNode(Point position)
public class PathfindingNode(Point position, IMovement move)
{
internal Point Position { get; set; } = position;
internal float Distance { get; set; } = float.MaxValue; // Cost from start to this node.
internal float Total { get; set; } = float.MaxValue; // Total cost.
internal IMovement Move { get; set; } = move;
internal PathfindingNode Parent { get; set; }
public override bool Equals(object obj)
{
if (obj is PathfindingNode other)
return Position == other.Position;
return Position == other.Position && Move.RegistrationName.Equals(other.Move.RegistrationName);
return false;
}
public override int GetHashCode() => Position.GetHashCode();
public override int GetHashCode() => Position.GetHashCode() ^ Move.RegistrationName.GetHashCode();
internal List<PathfindingNode> GetNeighbors()
internal IEnumerable<PathfindingNode> GetNeighborSteps(IPathfinder pathfinder)
{
var neighbors = new List<PathfindingNode>(Directions.Count);
int nodeX = Position.X;
int nodeY = Position.Y;
foreach (var direction in Directions)
foreach (var movement in pathfinder.Movements)
{
int newX = nodeX + (int)direction.X;
int newY = nodeY + (int)direction.Y;
if (WorldGen.InWorld(newX, newY))
neighbors.Add(new PathfindingNode(new Point(newX, newY)));
foreach (var neighbor in movement.GetDestinations(Position))
{
yield return new PathfindingNode(neighbor, movement);
}
}
return neighbors;
}
internal List<Vector2> ReconstructPath()
internal List<PathfindingNode> ReconstructPath()
{
var path = new List<Vector2>();
var path = new List<PathfindingNode>();
var current = this;
while (current != null)
{
path.Add(current.Position.ToWorldCoordinates());
path.Add(current);
current = current.Parent;
}
path.Reverse();
@@ -622,7 +436,7 @@ namespace CalamityMod
Rectangle hitbox = entity.Hitbox;
hitbox.Location = new Point(position.X - hitbox.Width / 2, position.Y - hitbox.Height / 2);
hitbox.Inflate(fluffX, fluffY);
int startX = (int)MathF.Floor(hitbox.Left / 16);
int endX = (int)Math.Floor((hitbox.Right - float.Epsilon) / 16);
int startY = (int)MathF.Floor(hitbox.Top / 16);