Unstable v0.10.600.0

This commit is contained in:
Juan Pablo Arce
2020-10-01 12:19:24 -03:00
parent 20a69375ca
commit ebe1ce1427
217 changed files with 4284 additions and 1547 deletions
@@ -3,7 +3,7 @@ using System.Collections.Generic;
namespace Barotrauma
{
public enum AIState { Idle, Attack, Escape, Eat, Flee, Avoid, Aggressive, PassiveAggressive, Protect }
public enum AIState { Idle, Attack, Escape, Eat, Flee, Avoid, Aggressive, PassiveAggressive, Protect, Observe }
abstract partial class AIController : ISteerable
{
@@ -147,6 +147,8 @@ namespace Barotrauma
_selectedAiTarget = null;
}
public void FaceTarget(ISpatialEntity target) => Character.AnimController.TargetDir = target.WorldPosition.X > Character.WorldPosition.X ? Direction.Right : Direction.Left;
protected virtual void OnStateChanged(AIState from, AIState to) { }
protected virtual void OnTargetChanged(AITarget previousTarget, AITarget newTarget) { }
@@ -38,7 +38,7 @@ namespace Barotrauma
{
if (float.IsNaN(value))
{
DebugConsole.ThrowError("Attempted to set the SoundRange of an AITarget to NaN.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to set the SoundRange of an AITarget to NaN.\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
soundRange = MathHelper.Clamp(value, MinSoundRange, MaxSoundRange);
@@ -52,7 +52,7 @@ namespace Barotrauma
{
if (float.IsNaN(value))
{
DebugConsole.ThrowError("Attempted to set the SightRange of an AITarget to NaN.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to set the SightRange of an AITarget to NaN.\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
sightRange = MathHelper.Clamp(value, MinSightRange, MaxSightRange);
@@ -74,7 +74,7 @@ namespace Barotrauma
{
if (!MathUtils.IsValid(value))
{
string errorMsg = "Invalid AITarget sector direction (" + value + ")\n" + Environment.StackTrace;
string errorMsg = "Invalid AITarget sector direction (" + value + ")\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("AITarget.SectorDir:" + entity?.ToString(), GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return;
@@ -113,11 +113,11 @@ namespace Barotrauma
if (entity == null || entity.Removed)
{
#if DEBUG
DebugConsole.ThrowError("Attempted to access a removed AITarget\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to access a removed AITarget\n" + Environment.StackTrace.CleanupStackTrace());
#endif
GameAnalyticsManager.AddErrorEventOnce("AITarget.WorldPosition:EntityRemoved",
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Attempted to access a removed AITarget\n" + Environment.StackTrace);
"Attempted to access a removed AITarget\n" + Environment.StackTrace.CleanupStackTrace());
return Vector2.Zero;
}
@@ -132,11 +132,11 @@ namespace Barotrauma
if (entity == null || entity.Removed)
{
#if DEBUG
DebugConsole.ThrowError("Attempted to access a removed AITarget\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to access a removed AITarget\n" + Environment.StackTrace.CleanupStackTrace());
#endif
GameAnalyticsManager.AddErrorEventOnce("AITarget.WorldPosition:EntityRemoved",
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Attempted to access a removed AITarget\n" + Environment.StackTrace);
"Attempted to access a removed AITarget\n" + Environment.StackTrace.CleanupStackTrace());
return Vector2.Zero;
}
@@ -56,6 +56,8 @@ namespace Barotrauma
private float AggressionHurt => Character.Params.AI.AggressionHurt;
private bool AggressiveBoarding => Character.Params.AI.AggressiveBoarding;
private FishAnimController FishAnimController => Character.AnimController as FishAnimController;
//a point in a wall which the Character is currently targeting
private WallTarget wallTarget;
@@ -70,10 +72,6 @@ namespace Barotrauma
_attackingLimb = value;
attackVector = null;
Reverse = _attackingLimb != null && _attackingLimb.attack.Reverse;
if (Character.AnimController is FishAnimController fishController)
{
fishController.reverse = Reverse;
}
}
}
@@ -95,6 +93,7 @@ namespace Barotrauma
private readonly float avoidTime = 3;
private float avoidTimer;
private float observeTimer;
public bool StayInsideLevel = true;
@@ -107,7 +106,7 @@ namespace Barotrauma
{
get
{
var target = GetTarget(CharacterPrefab.HumanSpeciesName);
var target = GetTargetParams(CharacterPrefab.HumanSpeciesName);
return target != null && target.Priority > 0.0f && (target.State == AIState.Attack || target.State == AIState.Aggressive);
}
}
@@ -116,7 +115,7 @@ namespace Barotrauma
{
get
{
var target = GetTarget("room");
var target = GetTargetParams("room");
return target != null && target.Priority > 0.0f && (target.State == AIState.Attack || target.State == AIState.Aggressive);
}
}
@@ -145,7 +144,16 @@ namespace Barotrauma
public bool IsBeingChasedBy(Character c) => c.AIController is EnemyAIController enemyAI && enemyAI.SelectedAiTarget?.Entity is Character && (enemyAI.State == AIState.Aggressive || enemyAI.State == AIState.Attack);
private bool IsBeingChased => SelectedAiTarget?.Entity is Character targetCharacter && IsBeingChasedBy(targetCharacter);
public bool Reverse { get; private set; }
private bool reverse;
public bool Reverse
{
get { return reverse; }
private set
{
reverse = value;
FishAnimController.reverse = reverse;
}
}
public EnemyAIController(Character c, string seed) : base(c)
{
@@ -214,7 +222,69 @@ namespace Barotrauma
}
private CharacterParams.AIParams AIParams => Character.Params.AI;
private CharacterParams.TargetParams GetTarget(string targetTag) => AIParams.GetTarget(targetTag, false);
private CharacterParams.TargetParams GetTargetParams(string targetTag) => AIParams.GetTarget(targetTag, false);
private CharacterParams.TargetParams GetTargetParams(AITarget aiTarget) => GetTargetParams(GetTargetingTag(aiTarget));
private string GetTargetingTag(AITarget aiTarget)
{
if (aiTarget.Entity == null) { return null; }
string targetingTag = null;
if (aiTarget.Entity is Character targetCharacter)
{
if (targetCharacter.IsDead)
{
targetingTag = "dead";
}
else if (AIParams.TryGetTarget(targetCharacter.SpeciesName, out CharacterParams.TargetParams tP))
{
targetingTag = tP.Tag;
}
else if (targetCharacter.AIController is EnemyAIController enemy)
{
if (targetCharacter.IsHusk && AIParams.HasTag("husk"))
{
targetingTag = "husk";
}
else
{
if (enemy.CombatStrength > CombatStrength)
{
targetingTag = "stronger";
}
else if (enemy.CombatStrength < CombatStrength)
{
targetingTag = "weaker";
}
}
}
}
else if (aiTarget.Entity is Item targetItem)
{
foreach (var prio in AIParams.Targets)
{
if (targetItem.HasTag(prio.Tag))
{
targetingTag = prio.Tag;
break;
}
}
if (targetingTag == null)
{
if (targetItem.GetComponent<Sonar>() != null)
{
targetingTag = "sonar";
}
}
}
else if (aiTarget.Entity is Structure)
{
targetingTag = "wall";
}
else if (aiTarget.Entity is Hull)
{
targetingTag = "room";
}
return targetingTag;
}
public override void SelectTarget(AITarget target) => SelectTarget(target, 100);
@@ -295,8 +365,9 @@ namespace Barotrauma
updateMemoriesTimer = updateMemoriesInverval;
}
if (Character.HealthPercentage <= FleeHealthThreshold && SelectedAiTarget != null &&
SelectedAiTarget.Entity is Character target && (target.IsPlayer || IsBeingChasedBy(target)))
SelectedAiTarget.Entity is Character target && (target.IsHuman && CanPerceive(SelectedAiTarget) || IsBeingChasedBy(target)))
{
// Keep fleeing if being chased
State = AIState.Flee;
wallTarget = null;
}
@@ -348,6 +419,7 @@ namespace Barotrauma
steeringManager = insideSteering;
}
bool useSteeringLengthAsMovementSpeed = State == AIState.Idle && Character.AnimController.InWater;
bool run = false;
switch (State)
{
@@ -425,7 +497,7 @@ namespace Barotrauma
State = AIState.Idle;
return;
}
if (SelectedAiTarget.Entity is Character targetCharacter && targetCharacter.LastAttacker is Character attacker)
if (SelectedAiTarget.Entity is Character targetCharacter && targetCharacter.LastAttacker is Character attacker && !attacker.Removed && !attacker.IsDead)
{
// Attack the character that attacked the target we are protecting
ChangeTargetState(attacker, AIState.Attack, selectedTargetingParams.Priority * 2);
@@ -446,6 +518,63 @@ namespace Barotrauma
UpdateIdle(deltaTime);
}
break;
case AIState.Observe:
if (SelectedAiTarget == null || SelectedAiTarget.Entity == null || SelectedAiTarget.Entity.Removed)
{
State = AIState.Idle;
return;
}
run = false;
sqrDist = Vector2.DistanceSquared(WorldPosition, SelectedAiTarget.WorldPosition);
reactDist = selectedTargetingParams != null && selectedTargetingParams.ReactDistance > 0 ? selectedTargetingParams.ReactDistance : GetPerceivingRange(SelectedAiTarget);
float halfReactDist = reactDist / 2;
float attackDist = selectedTargetingParams != null && selectedTargetingParams.AttackDistance > 0 ? selectedTargetingParams.AttackDistance : halfReactDist;
if (sqrDist > Math.Pow(reactDist, 2))
{
// Too far to react
UpdateIdle(deltaTime);
}
else if (sqrDist < Math.Pow(attackDist + movementMargin, 2))
{
movementMargin = attackDist;
SteeringManager.Reset();
if (Character.AnimController.InWater)
{
useSteeringLengthAsMovementSpeed = true;
Vector2 dir = Vector2.Normalize(SelectedAiTarget.WorldPosition - Character.WorldPosition);
if (sqrDist < Math.Pow(attackDist * 0.75f, 2))
{
// Keep the distance, if too close
dir = -dir;
useSteeringLengthAsMovementSpeed = false;
Reverse = true;
run = true;
}
else
{
Reverse = false;
}
SteeringManager.SteeringManual(deltaTime, dir * 0.2f);
}
else
{
FaceTarget(SelectedAiTarget.Entity);
}
observeTimer -= deltaTime;
if (observeTimer < 0)
{
IgnoreTarget(SelectedAiTarget);
State = AIState.Idle;
ResetAITarget();
}
}
else
{
run = sqrDist > Math.Pow(attackDist * 2, 2);
movementMargin = MathHelper.Clamp(movementMargin -= deltaTime, 0, attackDist);
UpdateFollow(deltaTime);
}
break;
default:
throw new NotImplementedException();
}
@@ -465,7 +594,8 @@ namespace Barotrauma
SteerInsideLevel(deltaTime);
float speed = Character.AnimController.GetCurrentSpeed(run && Character.CanRun);
steeringManager.Update(speed);
Character.AnimController.TargetMovement = Character.ApplyMovementLimits(Steering, State == AIState.Idle && Character.AnimController.InWater ? Steering.Length() : speed);
float targetMovement = useSteeringLengthAsMovementSpeed ? Steering.Length() : speed;
Character.AnimController.TargetMovement = Character.ApplyMovementLimits(Steering, targetMovement);
if (Character.CurrentHull != null && Character.AnimController.InWater)
{
// Halve the swimming speed inside the sub
@@ -601,7 +731,7 @@ namespace Barotrauma
{
// Steer away from the target if in the same room
Vector2 escapeDir = Vector2.Normalize(SelectedAiTarget != null ? WorldPosition - SelectedAiTarget.WorldPosition : Character.AnimController.TargetMovement);
if (!MathUtils.IsValid(escapeDir)) escapeDir = Vector2.UnitY;
if (!MathUtils.IsValid(escapeDir)) { escapeDir = Vector2.UnitY; }
SteeringManager.SteeringManual(deltaTime, escapeDir);
}
else if (pathSteering != null)
@@ -922,7 +1052,7 @@ namespace Barotrauma
}
if (!Character.AnimController.SimplePhysicsEnabled && SelectedAiTarget.Entity.Submarine != null && Character.Submarine == null && (!canAttackDoors || !canAttackWalls || !AIParams.TargetOuterWalls))
{
if (Vector2.DistanceSquared(Character.WorldPosition, attackWorldPos) < 2000 * 2000)
if (wallTarget == null && Vector2.DistanceSquared(Character.WorldPosition, attackWorldPos) < 2000 * 2000)
{
// Check that we are not bumping into a door or a wall
Vector2 rayStart = SimPosition;
@@ -1193,7 +1323,7 @@ namespace Barotrauma
}
if (AIParams.RandomAttack)
{
selectedLimb = ToolBox.SelectWeightedRandom(attackLimbs, weights, Rand.RandSync.Server);
selectedLimb = ToolBox.SelectWeightedRandom(attackLimbs, weights, Rand.RandSync.Unsynced);
attackLimbs.Clear();
weights.Clear();
}
@@ -1268,7 +1398,7 @@ namespace Barotrauma
LatchOntoAI?.SetAttachTarget(wall.Submarine.PhysicsBody.FarseerBody, wall.Submarine, ConvertUnits.ToSimUnits(sectionPos), attachTargetNormal);
if (Character.AnimController.CanEnterSubmarine || !wall.SectionBodyDisabled(sectionIndex) && !IsWallDisabled(wall))
{
if (AIParams.TargetOuterWalls || wall.prefab.Tags.Contains("inner"))
if (AIParams.TargetOuterWalls || wall.prefab.Tags.Contains("inner") || wall.Submarine != null && wall.Submarine == Character.Submarine)
{
wallTarget = new WallTarget(sectionPos, wall, sectionIndex);
}
@@ -1309,7 +1439,7 @@ namespace Barotrauma
bool wasLatched = IsLatchedOnSub;
Character.AnimController.ReleaseStuckLimbs();
LatchOntoAI?.DeattachFromBody(cooldown: 1);
if (attacker == null || attacker.AiTarget == null) { return; }
if (attacker == null || attacker.AiTarget == null || attacker.Removed || attacker.IsDead) { return; }
bool isFriendly = IsFriendly(Character, attacker);
if (wasLatched)
{
@@ -1414,6 +1544,11 @@ namespace Barotrauma
avoidTimer = avoidTime * Rand.Range(0.75f, 1.25f);
SelectTarget(attacker.AiTarget);
}
if (Character.HealthPercentage <= FleeHealthThreshold)
{
avoidTimer = Rand.Range(15, 30);
SelectTarget(attacker.AiTarget);
}
}
// 10 dmg, 100 health -> 0.1
@@ -1534,7 +1669,7 @@ namespace Barotrauma
{
return;
}
steeringManager.SteeringManual(deltaTime, dir);
SteeringManager.SteeringSeek(Character.GetRelativeSimPosition(SelectedAiTarget.Entity), 5);
if (Character.AnimController.InWater)
{
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: avoidLookAheadDistance, weight: 15);
@@ -1557,6 +1692,7 @@ namespace Barotrauma
foreach (AITarget aiTarget in AITarget.List)
{
if (!aiTarget.Enabled) { continue; }
if (aiTarget.Entity == null) { continue; }
if (ignoredTargets.Contains(aiTarget)) { continue; }
if (Level.Loaded != null && aiTarget.WorldPosition.Y > Level.Loaded.Size.Y)
{
@@ -1626,7 +1762,7 @@ namespace Barotrauma
}
}
}
else if (aiTarget.Entity != null)
else
{
// Ignore all structures and items inside wrecks
if (aiTarget.Entity.Submarine != null && aiTarget.Entity.Submarine.Info.IsWreck) { continue; }
@@ -1784,8 +1920,10 @@ namespace Barotrauma
{
targetingTag = "door";
}
if (door.Item.Submarine == null) { continue;}
if (door.Item.Submarine == null) { continue; }
bool isOutdoor = door.LinkedGap?.FlowTargetHull != null && !door.LinkedGap.IsRoomToRoom;
// Ignore inner doors when outside
if (character.CurrentHull == null && !isOutdoor) { continue; }
bool isOpen = door.IsOpen || door.IsBroken;
if (!isOpen && !canAttackDoors || (isOutdoor && !AIParams.TargetOuterWalls))
{
@@ -1795,26 +1933,22 @@ namespace Barotrauma
if (isOpen && (!Character.AnimController.CanEnterSubmarine || !AggressiveBoarding))
{
// Ignore broken and open doors
// Aggressive boarders don't ignore open doors, because they use them for get in.
// Aggressive boarders don't ignore open doors, because they use them for getting in.
continue;
}
if (AggressiveBoarding)
{
// Increase the priority if the character is outside and the door is from outside to inside
if (character.CurrentHull == null && isOutdoor)
if (character.CurrentHull == null)
{
valueModifier *= isOpen ? 5 : 1;
}
else
{
// Inside
// Inside -> ignore open doors and outer doors
valueModifier *= isOpen || isOutdoor ? 0 : 1;
}
}
else if (character.CurrentHull == null)
{
valueModifier = isOutdoor ? 1 : 0;
}
}
else if (aiTarget.Entity is IDamageable targetDamageable && targetDamageable.Health <= 0.0f)
{
@@ -1823,8 +1957,13 @@ namespace Barotrauma
}
if (targetingTag == null) { continue; }
var targetParams = GetTarget(targetingTag);
var targetParams = GetTargetParams(targetingTag);
if (targetParams == null) { continue; }
if (targetCharacter != null && targetCharacter.Submarine != Character.Submarine && targetParams.State == AIState.Observe)
{
// Don't allow to observe characters that are inside a different submarine / outside when we are inside.
continue;
}
valueModifier *= targetParams.Priority;
if (valueModifier == 0.0f) { continue; }
@@ -1939,7 +2078,7 @@ namespace Barotrauma
newTarget = aiTarget;
selectedTargetMemory = targetMemory;
targetValue = valueModifier;
targetingParams = GetTarget(targetingTag);
targetingParams = GetTargetParams(targetingTag);
}
}
@@ -1999,7 +2138,7 @@ namespace Barotrauma
{
_selectedAiTarget = null;
}
else if (CanPerceive(_selectedAiTarget, distSquared: Vector2.DistanceSquared(Character.WorldPosition, _selectedAiTarget.WorldPosition)))
else if (CanPerceive(_selectedAiTarget))
{
var memory = GetTargetMemory(_selectedAiTarget, false);
if (memory != null)
@@ -2040,7 +2179,7 @@ namespace Barotrauma
removals.ForEach(r => targetMemories.Remove(r));
}
private readonly float targetIgnoreTime = 5;
private readonly float targetIgnoreTime = 10;
private float targetIgnoreTimer;
private readonly HashSet<AITarget> ignoredTargets = new HashSet<AITarget>();
public void IgnoreTarget(AITarget target)
@@ -2168,6 +2307,17 @@ namespace Barotrauma
}
#endregion
protected override void OnTargetChanged(AITarget previousTarget, AITarget newTarget)
{
base.OnTargetChanged(previousTarget, newTarget);
if (newTarget == null) { return; }
var targetParams = GetTargetParams(newTarget);
if (targetParams != null)
{
observeTimer = targetParams.Timer * Rand.Range(0.75f, 1.25f);
}
}
protected override void OnStateChanged(AIState from, AIState to)
{
LatchOntoAI?.DeattachFromBody();
@@ -2189,13 +2339,17 @@ namespace Barotrauma
private bool CanPerceive(AITarget target, float dist = -1, float distSquared = -1)
{
if (distSquared > -1)
if (dist > 0)
{
return distSquared <= MathUtils.Pow(target.SightRange * Sight, 2) || distSquared <= MathUtils.Pow(target.SoundRange * Hearing, 2);
return dist <= target.SightRange * Sight || dist <= target.SoundRange * Hearing;
}
else
{
return dist <= target.SightRange * Sight || dist <= target.SoundRange * Hearing;
if (distSquared < 0)
{
distSquared = Vector2.DistanceSquared(Character.WorldPosition, target.WorldPosition);
}
return distSquared <= MathUtils.Pow(target.SightRange * Sight, 2) || distSquared <= MathUtils.Pow(target.SoundRange * Hearing, 2);
}
}
@@ -35,6 +35,14 @@ namespace Barotrauma
public readonly HashSet<Hull> UnsafeHulls = new HashSet<Hull>();
public readonly List<Item> IgnoredItems = new List<Item>();
private float respondToAttackTimer;
private const float RespondToAttackInterval = 1.0f;
/// <summary>
/// List of previous attacks done to this character
/// </summary>
private readonly Dictionary<Character, AttackResult> previousAttackResults = new Dictionary<Character, AttackResult>();
private class HullSafety
{
public float safety;
@@ -138,6 +146,17 @@ namespace Barotrauma
}
if (isIncapacitated) { return; }
respondToAttackTimer -= deltaTime;
if (respondToAttackTimer <= 0.0f)
{
foreach (var previousAttackResult in previousAttackResults)
{
RespondToAttack(previousAttackResult.Key, previousAttackResult.Value);
}
previousAttackResults.Clear();
respondToAttackTimer = RespondToAttackInterval;
}
base.Update(deltaTime);
foreach (var values in knownHulls)
@@ -316,6 +335,7 @@ namespace Barotrauma
{
if (Character.LockHands) { return; }
if (ObjectiveManager.CurrentObjective == null) { return; }
if (Character.CurrentHull == null) { return; }
bool oxygenLow = !Character.AnimController.HeadInWater && Character.OxygenAvailable < CharacterHealth.LowOxygenThreshold;
bool isCarrying = ObjectiveManager.HasActiveObjective<AIObjectiveContainItem>() || ObjectiveManager.HasActiveObjective<AIObjectiveDecontainItem>();
@@ -349,7 +369,9 @@ namespace Barotrauma
if (!NeedsDivingGear(Character.CurrentHull, out bool needsSuit) || !needsSuit || oxygenLow)
{
bool shouldKeepTheGearOn = Character.AnimController.HeadInWater
|| Character.Submarine.TeamID != Character.TeamID && Character.Submarine.TeamID != Character.TeamType.FriendlyNPC
|| ObjectiveManager.IsCurrentObjective<AIObjectiveFindSafety>()
|| ObjectiveManager.CurrentOrder is AIObjectiveGoTo goTo && goTo.Target == Character // wait order
|| ObjectiveManager.CurrentObjective.GetSubObjectivesRecursive(true).Any(o => o.KeepDivingGearOn);
if (oxygenLow && Character.CurrentHull.Oxygen > 0)
{
@@ -425,12 +447,14 @@ namespace Barotrauma
{
var decontainObjective = new AIObjectiveDecontainItem(Character, divingSuit, ObjectiveManager, targetContainer: targetContainer.GetComponent<ItemContainer>())
{
DropIfFailsToContain = false
DropIfFails = false
};
decontainObjective.Abandoned += () =>
{
ReequipUnequipped();
IgnoredItems.Add(targetContainer);
};
decontainObjective.Completed += () => ReequipUnequipped();
ObjectiveManager.CurrentObjective.AddSubObjective(decontainObjective, addFirst: true);
return;
}
@@ -451,7 +475,7 @@ namespace Barotrauma
{
if (!mask.AllowedSlots.Contains(InvSlotType.Any) || !Character.Inventory.TryPutItem(mask, Character, new List<InvSlotType>() { InvSlotType.Any }))
{
if (oxygenLow || ObjectiveManager.GetCurrentPriority() >= AIObjectiveManager.RunPriority)
if (ObjectiveManager.GetCurrentPriority() >= AIObjectiveManager.RunPriority)
{
mask.Drop(Character);
}
@@ -465,7 +489,12 @@ namespace Barotrauma
if (targetContainer != null)
{
var decontainObjective = new AIObjectiveDecontainItem(Character, mask, ObjectiveManager, targetContainer: targetContainer.GetComponent<ItemContainer>());
decontainObjective.Abandoned += () => IgnoredItems.Add(targetContainer);
decontainObjective.Abandoned += () =>
{
ReequipUnequipped();
IgnoredItems.Add(targetContainer);
};
decontainObjective.Completed += () => ReequipUnequipped();
ObjectiveManager.CurrentObjective.AddSubObjective(decontainObjective, addFirst: true);
return;
}
@@ -476,6 +505,10 @@ namespace Barotrauma
}
}
}
else
{
ReequipUnequipped();
}
}
}
}
@@ -504,7 +537,11 @@ namespace Barotrauma
if (targetContainer != null)
{
var decontainObjective = new AIObjectiveDecontainItem(Character, item, ObjectiveManager, targetContainer: targetContainer.GetComponent<ItemContainer>());
decontainObjective.Abandoned += () => IgnoredItems.Add(targetContainer);
decontainObjective.Abandoned += () =>
{
ReequipUnequipped();
IgnoredItems.Add(targetContainer);
};
ObjectiveManager.CurrentObjective.AddSubObjective(decontainObjective, addFirst: true);
return;
}
@@ -519,6 +556,18 @@ namespace Barotrauma
}
}
public void ReequipUnequipped()
{
foreach (var item in unequippedItems)
{
if (item != null && !item.Removed && Character.HasItem(item))
{
TakeItem(item, Character.Inventory, equip: true, dropOtherIfCannotMove: true, allowSwapping: true, storeUnequipped: false);
}
}
unequippedItems.Clear();
}
private enum FindItemState
{
None,
@@ -528,10 +577,13 @@ namespace Barotrauma
}
private FindItemState findItemState;
private int itemIndex;
public bool FindSuitableContainer(Item containableItem, out Item suitableContainer)
public bool FindSuitableContainer(Item containableItem, out Item suitableContainer) => FindSuitableContainer(Character, containableItem, IgnoredItems, ref itemIndex, out suitableContainer);
public static bool FindSuitableContainer(Character character, Item containableItem, List<Item> ignoredItems, ref int itemIndex, out Item suitableContainer)
{
suitableContainer = null;
if (Character.FindItem(ref itemIndex, out Item targetContainer, ignoredItems: IgnoredItems, customPriorityFunction: i =>
if (character.FindItem(ref itemIndex, out Item targetContainer, ignoredItems: ignoredItems, customPriorityFunction: i =>
{
var container = i.GetComponent<ItemContainer>();
if (container == null) { return 0; }
@@ -683,6 +735,38 @@ namespace Barotrauma
public override void OnAttacked(Character attacker, AttackResult attackResult)
{
if (Character.IsDead) { return; }
if (attacker == null || Character.IsPlayer)
{
// The player characters need to "respond" to the attack always, because the update loop doesn't run for them.
// Otherwise other NPCs totally ignore when player characters are attacked.
RespondToAttack(attacker, attackResult);
return;
}
if (previousAttackResults.ContainsKey(attacker))
{
foreach (Affliction newAffliction in attackResult.Afflictions)
{
var matchingAffliction = previousAttackResults[attacker].Afflictions.Find(a => a.Prefab == newAffliction.Prefab && a.Source == newAffliction.Source);
if (matchingAffliction == null)
{
previousAttackResults[attacker].Afflictions.Add(newAffliction);
}
else
{
matchingAffliction.Strength += newAffliction.Strength;
}
}
previousAttackResults[attacker] = new AttackResult(previousAttackResults[attacker].Afflictions, previousAttackResults[attacker].HitLimb);
}
else
{
previousAttackResults.Add(attacker, attackResult);
}
}
private void RespondToAttack(Character attacker, AttackResult attackResult)
{
// excluding poisons etc
float realDamage = attackResult.Damage;
// including poisons etc
@@ -691,7 +775,7 @@ namespace Barotrauma
{
totalDamage -= affliction.Prefab.KarmaChangeOnApplied * affliction.Strength;
}
if (totalDamage <= 0) { return; }
if (totalDamage <= 0.01f) { return; }
if (Character.IsBot)
{
if (attacker != null)
@@ -735,7 +819,7 @@ namespace Barotrauma
return;
}
float cumulativeDamage = GetDamageDoneByAttacker(attacker);
if (!Character.IsSecurity && attacker.IsBot && !attacker.IsInstigator)
if (!Character.IsSecurity && attacker.IsBot && Character.CombatAction == null)
{
if (cumulativeDamage > 1)
{
@@ -834,7 +918,17 @@ namespace Barotrauma
}
else
{
if (attacker.TeamID == Character.TeamType.FriendlyNPC)
// If there are any enemies around, just ignore the friendly fire
if (Character.CharacterList.Any(ch => ch.Submarine == Character.Submarine && !ch.Removed && !ch.IsDead && !ch.IsIncapacitated && !IsFriendly(ch) && VisibleHulls.Contains(ch.CurrentHull)))
{
return AIObjectiveCombat.CombatMode.None;
}
if (Character.IsInstigator && attacker.IsPlayer)
{
// The guards don't react when the player attacks instigators.
return c.IsSecurity ? AIObjectiveCombat.CombatMode.None : (Character.CombatAction != null ? Character.CombatAction.WitnessReaction : AIObjectiveCombat.CombatMode.Retreat);
}
else if (attacker.TeamID == Character.TeamType.FriendlyNPC)
{
if (c.IsSecurity)
{
@@ -847,11 +941,7 @@ namespace Barotrauma
}
else
{
if (Character.IsInstigator)
{
return c.IsSecurity ? AIObjectiveCombat.CombatMode.Arrest : AIObjectiveCombat.CombatMode.Retreat;
}
else if (cumulativeDamage > dmgThreshold)
if (cumulativeDamage > dmgThreshold)
{
if (c.IsSecurity)
{
@@ -1006,39 +1096,51 @@ namespace Barotrauma
return true;
}
public bool TryToMoveItem(Item item, Inventory targetInventory, bool dropIfCannotMove = true)
private readonly HashSet<Item> unequippedItems = new HashSet<Item>();
public bool TakeItem(Item item, Inventory targetInventory, bool equip, bool dropOtherIfCannotMove = true, bool allowSwapping = false, bool storeUnequipped = false)
{
var pickable = item.GetComponent<Pickable>();
if (pickable == null) { return false; }
int targetSlot = -1;
//check if all the slots required by the item are free
foreach (InvSlotType slots in pickable.AllowedSlots)
if (equip)
{
if (slots.HasFlag(InvSlotType.Any)) { continue; }
for (int i = 0; i < targetInventory.Items.Length; i++)
int targetSlot = -1;
//check if all the slots required by the item are free
foreach (InvSlotType slots in pickable.AllowedSlots)
{
if (targetInventory is CharacterInventory characterInventory)
if (slots.HasFlag(InvSlotType.Any)) { continue; }
for (int i = 0; i < targetInventory.Items.Length; i++)
{
//slot not needed by the item, continue
if (!slots.HasFlag(characterInventory.SlotTypes[i])) { continue; }
}
targetSlot = i;
//slot free, continue
var otherItem = targetInventory.Items[i];
if (otherItem == null) { continue; }
//try to move the existing item to LimbSlot.Any and continue if successful
if (otherItem.AllowedSlots.Contains(InvSlotType.Any) && targetInventory.TryPutItem(otherItem, Character, new List<InvSlotType>() { InvSlotType.Any }))
{
continue;
}
if (dropIfCannotMove)
{
//if everything else fails, simply drop the existing item
otherItem.Drop(Character);
if (targetInventory is CharacterInventory characterInventory)
{
//slot not needed by the item, continue
if (!slots.HasFlag(characterInventory.SlotTypes[i])) { continue; }
}
targetSlot = i;
//slot free, continue
var otherItem = targetInventory.Items[i];
if (otherItem == null) { continue; }
//try to move the existing item to LimbSlot.Any and continue if successful
if (otherItem.AllowedSlots.Contains(InvSlotType.Any) && targetInventory.TryPutItem(otherItem, Character, CharacterInventory.anySlot))
{
if (storeUnequipped && targetInventory.Owner == Character)
{
unequippedItems.Add(otherItem);
}
continue;
}
if (dropOtherIfCannotMove)
{
//if everything else fails, simply drop the existing item
otherItem.Drop(Character);
}
}
}
return targetInventory.TryPutItem(item, targetSlot, allowSwapping, allowCombine: false, Character);
}
else
{
return targetInventory.TryPutItem(item, Character, CharacterInventory.anySlot);
}
return targetInventory.TryPutItem(item, targetSlot, false, false, Character);
}
public static bool NeedsDivingGear(Hull hull, out bool needsSuit)
@@ -1107,7 +1209,7 @@ namespace Barotrauma
}
//if (!otherCharacter.IsFacing(thief.WorldPosition)) { continue; }
if (!otherCharacter.CanSeeCharacter(thief)) { continue; }
if (!someoneSpoke)
if (!someoneSpoke && !character.IsIncapacitated && character.Stun <= 0.0f)
{
if (!item.StolenDuringRound && GameMain.GameSession?.Campaign?.Map?.CurrentLocation != null)
{
@@ -1306,7 +1408,7 @@ namespace Barotrauma
// Use the cached visible hulls
visibleHulls = VisibleHulls;
}
bool ignoreFire = objectiveManager.HasActiveObjective<AIObjectiveExtinguishFire>();
bool ignoreFire = objectiveManager.CurrentOrder is AIObjectiveExtinguishFires extinguishOrder && extinguishOrder.Priority > 0 || objectiveManager.HasActiveObjective<AIObjectiveExtinguishFire>();
bool ignoreWater = HasDivingSuit(character);
bool ignoreOxygen = ignoreWater || HasDivingMask(character);
bool ignoreEnemies = ObjectiveManager.IsCurrentObjective<AIObjectiveFightIntruders>();
@@ -1391,13 +1493,10 @@ namespace Barotrauma
return hullSafety.safety;
}
public void FaceTarget(ISpatialEntity target) => Character.AnimController.TargetDir = target.WorldPosition.X > Character.WorldPosition.X ? Direction.Right : Direction.Left;
public static bool IsFriendly(Character me, Character other, bool onlySameTeam = false)
{
bool sameTeam = me.TeamID == other.TeamID;
// Only enemies are in the Team "None"
bool friendlyTeam = me.TeamID != Character.TeamType.None && other.TeamID != Character.TeamType.None;
bool friendlyTeam = IsOnFriendlyTeam(GameMain.GameSession?.GameMode, me, other);
bool teamGood = sameTeam || friendlyTeam && !onlySameTeam;
if (!teamGood) { return false; }
bool speciesGood = other.SpeciesName == me.SpeciesName || other.Params.CompareGroup(me.Params.Group);
@@ -1413,6 +1512,18 @@ namespace Barotrauma
return true;
}
private static bool IsOnFriendlyTeam(GameMode mode, Character me, Character other)
{
// Only enemies are in the Team "None"
bool friendlyTeam = me.TeamID != Character.TeamType.None && other.TeamID != Character.TeamType.None;
// When playing a combat mission, we need to be on the same team to be friendlies
if (friendlyTeam && mode is MissionMode mm && mm.Mission is CombatMission)
{
friendlyTeam = me.TeamID == other.TeamID;
}
return friendlyTeam;
}
public static bool IsActive(Character other) => other != null && !other.Removed && !other.IsDead && !other.IsUnconscious;
public static bool IsTrueForAllCrewMembers(Character character, Func<HumanAIController, bool> predicate)
@@ -191,7 +191,7 @@ namespace Barotrauma
}
pathFinder.InsideSubmarine = character.Submarine != null;
var newPath = pathFinder.FindPath(currentPos, target, character.Submarine, "(Character: " + character.Name + ")", startNodeFilter, endNodeFilter, nodeFilter, checkVisibility: checkVisibility);
bool useNewPath = needsNewPath || currentPath == null || currentPath.CurrentNode == null;
bool useNewPath = needsNewPath || currentPath == null || currentPath.CurrentNode == null || findPathTimer < -1;
if (!useNewPath && currentPath != null && currentPath.CurrentNode != null && newPath.Nodes.Any() && !newPath.Unreachable)
{
// It's possible that the current path was calculated from a start point that is no longer valid.
@@ -15,6 +15,7 @@ namespace Barotrauma
public virtual bool IgnoreUnsafeHulls => false;
public virtual bool AbandonWhenCannotCompleteSubjectives => true;
public virtual bool AllowSubObjectiveSorting => false;
public virtual bool ForceOrderPriority => true;
/// <summary>
/// Can there be multiple objective instaces of the same type?
@@ -34,6 +35,7 @@ namespace Barotrauma
public virtual bool AllowAutomaticItemUnequipping => false;
public virtual bool AllowOutsideSubmarine => false;
public virtual bool AllowInFriendlySubs => false;
public virtual bool AllowInAnySub => false;
protected readonly List<AIObjective> subObjectives = new List<AIObjective>();
private float _cumulatedDevotion;
@@ -198,12 +200,10 @@ namespace Barotrauma
{
get
{
if (AllowOutsideSubmarine) { return true; }
if (character.Submarine == null) { return false; }
return
character.Submarine.TeamID == character.TeamID ||
(AllowInFriendlySubs && character.Submarine.TeamID == Character.TeamType.FriendlyNPC) ||
character.Submarine.DockedTo.Any(sub => sub.TeamID == character.TeamID);
if (!AllowOutsideSubmarine && character.Submarine == null) { return false; }
if (AllowInAnySub) { return true; }
if (AllowInFriendlySubs && character.Submarine.TeamID == Character.TeamType.FriendlyNPC) { return true; }
return character.Submarine.TeamID == character.TeamID || character.Submarine.DockedTo.Any(sub => sub.TeamID == character.TeamID);
}
}
@@ -212,12 +212,14 @@ namespace Barotrauma
/// </summary>
public virtual float GetPriority()
{
bool isOrder = objectiveManager.CurrentOrder == this;
if (!IsAllowed)
{
Priority = 0;
Abandon = !isOrder;
return Priority;
}
if (objectiveManager.CurrentOrder == this)
if (isOrder)
{
Priority = AIObjectiveManager.OrderPriority;
}
@@ -306,7 +308,7 @@ namespace Barotrauma
return true;
}
#if DEBUG
DebugConsole.ThrowError("Attempted to add a duplicate subobjective!\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to add a duplicate subobjective!\n" + Environment.StackTrace.CleanupStackTrace());
#endif
return false;
}
@@ -0,0 +1,124 @@
using Barotrauma.Extensions;
using Barotrauma.Items.Components;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Barotrauma
{
class AIObjectiveCleanupItem : AIObjective
{
public override string DebugTag => "cleanup item";
public override bool KeepDivingGearOn => true;
public override bool AllowAutomaticItemUnequipping => false;
public readonly Item item;
public bool IsPriority { get; set; }
private readonly List<Item> ignoredContainers = new List<Item>();
private AIObjectiveDecontainItem decontainObjective;
private int itemIndex = 0;
public AIObjectiveCleanupItem(Item item, Character character, AIObjectiveManager objectiveManager, float priorityModifier = 1)
: base(character, objectiveManager, priorityModifier)
{
this.item = item;
}
public override float GetPriority()
{
if (!IsAllowed)
{
Priority = 0;
Abandon = true;
return Priority;
}
else
{
float distanceFactor = 0.9f;
if (!IsPriority && item.CurrentHull != character.CurrentHull)
{
float yDist = Math.Abs(character.WorldPosition.Y - item.WorldPosition.Y);
yDist = yDist > 100 ? yDist * 5 : 0;
float dist = Math.Abs(character.WorldPosition.X - item.WorldPosition.X) + yDist;
distanceFactor = MathHelper.Lerp(0.9f, 0, MathUtils.InverseLerp(0, 5000, dist));
}
bool isSelected = character.HasItem(item);
float selectedBonus = isSelected ? 100 - MaxDevotion : 0;
float devotion = (CumulatedDevotion + selectedBonus) / 100;
float reduction = IsPriority ? 1 : isSelected ? 2 : 3;
float max = MathHelper.Min(AIObjectiveManager.OrderPriority - reduction, 90);
Priority = MathHelper.Lerp(0, max, MathHelper.Clamp(devotion + (distanceFactor * PriorityModifier), 0, 1));
}
return Priority;
}
protected override void Act(float deltaTime)
{
// Only continue when the get item sub objectives have been completed.
if (subObjectives.Any()) { return; }
if (HumanAIController.FindSuitableContainer(character, item, ignoredContainers, ref itemIndex, out Item suitableContainer))
{
itemIndex = 0;
if (suitableContainer != null)
{
bool equip = item.HasTag(AIObjectiveFindDivingGear.HEAVY_DIVING_GEAR) || (
item.GetComponent<Wearable>() == null &&
item.AllowedSlots.None(s =>
s == InvSlotType.Card ||
s == InvSlotType.Head ||
s == InvSlotType.Headset ||
s == InvSlotType.InnerClothes ||
s == InvSlotType.OuterClothes));
TryAddSubObjective(ref decontainObjective, () => new AIObjectiveDecontainItem(character, item, objectiveManager, targetContainer: suitableContainer.GetComponent<ItemContainer>())
{
Equip = equip,
DropIfFails = true
},
onCompleted: () =>
{
if (equip)
{
HumanAIController.ReequipUnequipped();
}
IsCompleted = true;
},
onAbandon: () =>
{
if (equip)
{
HumanAIController.ReequipUnequipped();
}
if (decontainObjective != null && decontainObjective.ContainObjective != null && decontainObjective.ContainObjective.CanBeCompleted)
{
ignoredContainers.Add(suitableContainer);
}
else
{
Abandon = true;
}
});
}
else
{
Abandon = true;
}
}
else
{
objectiveManager.GetObjective<AIObjectiveIdle>().Wander(deltaTime);
}
}
protected override bool Check() => IsCompleted;
public override void Reset()
{
base.Reset();
ignoredContainers.Clear();
itemIndex = 0;
decontainObjective = null;
}
}
}
@@ -0,0 +1,85 @@
using Barotrauma.Items.Components;
using System.Collections.Generic;
using System.Linq;
namespace Barotrauma
{
class AIObjectiveCleanupItems : AIObjectiveLoop<Item>
{
public override string DebugTag => "cleanup items";
public override bool KeepDivingGearOn => true;
public override bool AllowAutomaticItemUnequipping => false;
public override bool ForceOrderPriority => false;
public readonly Item prioritizedItem;
public AIObjectiveCleanupItems(Character character, AIObjectiveManager objectiveManager, float priorityModifier = 1, Item prioritizedItem = null)
: base(character, objectiveManager, priorityModifier)
{
this.prioritizedItem = prioritizedItem;
}
protected override float TargetEvaluation() => Targets.Any() ? AIObjectiveManager.RunPriority - 1 : 0;
protected override bool Filter(Item target)
{
// If the target was selected as a valid target, we'll have to accept it so that the objective can be completed.
// The validity changes when a character picks the item up.
if (!IsValidTarget(target, character)) { return Objectives.ContainsKey(target) && IsItemInsideValidSubmarine(target, character); }
if (target.CurrentHull.FireSources.Count > 0) { return false; }
// Don't repair items in rooms that have enemies inside.
if (Character.CharacterList.Any(c => c.CurrentHull == target.CurrentHull && !HumanAIController.IsFriendly(c) && HumanAIController.IsActive(c))) { return false; }
return true;
}
protected override IEnumerable<Item> GetList() => Item.ItemList;
protected override AIObjective ObjectiveConstructor(Item item)
=> new AIObjectiveCleanupItem(item, character, objectiveManager, priorityModifier: PriorityModifier)
{
IsPriority = prioritizedItem == item
};
protected override void OnObjectiveCompleted(AIObjective objective, Item target)
=> HumanAIController.RemoveTargets<AIObjectiveCleanupItems, Item>(character, target);
private static bool IsItemInsideValidSubmarine(Item item, Character character)
{
if (item.CurrentHull == null) { return false; }
if (item.Submarine == null) { return false; }
if (item.Submarine.TeamID != character.TeamID) { return false; }
if (character.Submarine != null)
{
if (!character.Submarine.IsConnectedTo(item.Submarine)) { return false; }
}
return true;
}
public static bool IsValidTarget(Item item, Character character)
{
if (item == null) { return false; }
if (item.NonInteractable) { return false; }
if (item.ParentInventory != null) { return false; }
if (character != null && !IsItemInsideValidSubmarine(item, character)) { return false; }
//var rootContainer = item.GetRootContainer();
//// Only target items lying on the ground (= not inside a container) (do we need this check?)
//if (rootContainer != null) { return false; }
var pickable = item.GetComponent<Pickable>();
if (pickable == null) { return false; }
var wire = item.GetComponent<Wire>();
if (wire != null)
{
if (wire.Connections.Any()) { return false; }
}
else
{
var connectionPanel = item.GetComponent<ConnectionPanel>();
if (connectionPanel != null && connectionPanel.Connections.Any(c => c.Wires.Any(w => w != null)))
{
return false;
}
}
return item.Prefab.PreferredContainers.Any();
}
}
}
@@ -15,6 +15,7 @@ namespace Barotrauma
public override bool KeepDivingGearOn => true;
public override bool IgnoreUnsafeHulls => true;
public override bool AllowOutsideSubmarine => true;
public override bool AllowInAnySub => true;
private readonly CombatMode initialMode;
@@ -54,8 +55,8 @@ namespace Barotrauma
if (_weaponComponent == null)
{
_weaponComponent =
Weapon.GetComponent<RangedWeapon>() as ItemComponent ??
Weapon.GetComponent<MeleeWeapon>() as ItemComponent ??
Weapon.GetComponent<RangedWeapon>() ??
Weapon.GetComponent<MeleeWeapon>() ??
Weapon.GetComponent<RepairTool>() as ItemComponent;
}
return _weaponComponent;
@@ -144,6 +145,7 @@ namespace Barotrauma
if (Enemy.Submarine == null || (Enemy.Submarine.TeamID != character.TeamID && Enemy.Submarine != character.Submarine))
{
Priority = 0;
Abandon = true;
return Priority;
}
}
@@ -760,11 +762,7 @@ namespace Barotrauma
if (HumanAIController.HasItem(character, "handlocker", out IEnumerable<Item> matchingItems) && Enemy.Stun > 0 && character.CanInteractWith(Enemy))
{
var handCuffs = matchingItems.First();
if (HumanAIController.TryToMoveItem(handCuffs, Enemy.Inventory))
{
handCuffs.Equip(Enemy);
}
else
if (!HumanAIController.TakeItem(handCuffs, Enemy.Inventory, equip: true))
{
#if DEBUG
DebugConsole.NewMessage($"{character.Name}: Failed to handcuff the target.", Color.Red);
@@ -777,7 +775,7 @@ namespace Barotrauma
if (item.StolenDuringRound)
{
item.Drop(character);
character.Inventory.TryPutItem(item, character, new List<InvSlotType>() { InvSlotType.Any });
character.Inventory.TryPutItem(item, character, CharacterInventory.anySlot);
}
}
character.Speak(TextManager.Get("DialogTargetArrested"), null, 3.0f, "targetarrested", 30.0f);
@@ -885,7 +883,11 @@ namespace Barotrauma
private void Attack(float deltaTime)
{
character.CursorPosition = Enemy.Position;
character.CursorPosition = Enemy.WorldPosition;
if (character.Submarine != null)
{
character.CursorPosition -= character.Submarine.Position;
}
visibilityCheckTimer -= deltaTime;
if (visibilityCheckTimer <= 0.0f)
{
@@ -142,6 +142,7 @@ namespace Barotrauma
}
else
{
// TODO: should we just use GetItem?
TryAddSubObjective(ref goToObjective, () => new AIObjectiveGoTo(container.Item, character, objectiveManager, getDivingGearIfNeeded: AllowToFindDivingGear)
{
DialogueIdentifier = "dialogcannotreachtarget",
@@ -153,27 +154,34 @@ namespace Barotrauma
}
else
{
// No matching items in the inventory, try to get an item
TryAddSubObjective(ref getItemObjective, () =>
new AIObjectiveGetItem(character, itemIdentifiers, objectiveManager, equip: Equip, checkInventory: checkInventory, spawnItemIfNotFound: spawnItemIfNotFound)
{
GetItemPriority = GetItemPriority,
ignoredContainerIdentifiers = ignoredContainerIdentifiers,
ignoredItems = containedItems,
AllowToFindDivingGear = AllowToFindDivingGear,
AllowDangerousPressure = AllowDangerousPressure,
TargetCondition = ConditionLevel
}, onAbandon: () =>
{
Abandon = true;
}, onCompleted: () =>
{
if (getItemObjective?.TargetItem != null)
if (character.Submarine == null)
{
Abandon = true;
}
else
{
// No matching items in the inventory, try to get an item
TryAddSubObjective(ref getItemObjective, () =>
new AIObjectiveGetItem(character, itemIdentifiers, objectiveManager, equip: Equip, checkInventory: checkInventory, spawnItemIfNotFound: spawnItemIfNotFound)
{
containedItems.Add(getItemObjective.TargetItem);
}
RemoveSubObjective(ref getItemObjective);
});
GetItemPriority = GetItemPriority,
ignoredContainerIdentifiers = ignoredContainerIdentifiers,
ignoredItems = containedItems,
AllowToFindDivingGear = AllowToFindDivingGear,
AllowDangerousPressure = AllowDangerousPressure,
TargetCondition = ConditionLevel
}, onAbandon: () =>
{
Abandon = true;
}, onCompleted: () =>
{
if (getItemObjective?.TargetItem != null)
{
containedItems.Add(getItemObjective.TargetItem);
}
RemoveSubObjective(ref getItemObjective);
});
}
}
}
@@ -16,9 +16,12 @@ namespace Barotrauma
private ItemContainer targetContainer;
private readonly Item targetItem;
private AIObjectiveGoTo goToObjective;
private AIObjectiveGetItem getItemObjective;
private AIObjectiveContainItem containObjective;
public AIObjectiveGetItem GetItemObjective => getItemObjective;
public AIObjectiveContainItem ContainObjective => containObjective;
public bool Equip { get; set; }
/// <summary>
@@ -26,7 +29,7 @@ namespace Barotrauma
/// In both cases abandons the objective.
/// Note that has no effect if the target container was not defined (always drops) -> completes when the item is dropped.
/// </summary>
public bool DropIfFailsToContain { get; set; } = true;
public bool DropIfFails { get; set; } = true;
public AIObjectiveDecontainItem(Character character, Item targetItem, AIObjectiveManager objectiveManager, ItemContainer sourceContainer = null, ItemContainer targetContainer = null, float priorityModifier = 1)
: base(character, objectiveManager, priorityModifier)
@@ -74,54 +77,30 @@ namespace Barotrauma
return;
}
}
else
else if (targetContainer.Inventory.Items.Contains(itemToDecontain))
{
if (targetContainer.Inventory.Items.Contains(itemToDecontain))
{
IsCompleted = true;
return;
}
IsCompleted = true;
return;
}
if (goToObjective == null && !itemToDecontain.IsOwnedBy(character))
if (getItemObjective == null && !itemToDecontain.IsOwnedBy(character))
{
if (sourceContainer == null)
{
Abandon = true;
return;
}
if (!character.CanInteractWith(sourceContainer.Item, out _, checkLinked: false))
{
TryAddSubObjective(ref goToObjective,
constructor: () => new AIObjectiveGoTo(sourceContainer.Item, character, objectiveManager)
{
// If the container changes, the item is no longer where it was
abortCondition = () => itemToDecontain.Container != sourceContainer.Item,
DialogueIdentifier = "dialogcannotreachtarget",
TargetName = sourceContainer.Item.Name
},
onAbandon: () => Abandon = true);
return;
}
TryAddSubObjective(ref getItemObjective,
constructor: () => new AIObjectiveGetItem(character, targetItem, objectiveManager, Equip),
onAbandon: () => Abandon = true);
return;
}
if (targetContainer != null)
{
TryAddSubObjective(ref containObjective,
constructor: () => new AIObjectiveContainItem(character, itemToDecontain, targetContainer, objectiveManager)
{
Equip = this.Equip,
Equip = Equip,
RemoveEmpty = false,
GetItemPriority = this.GetItemPriority,
GetItemPriority = GetItemPriority,
ignoredContainerIdentifiers = sourceContainer != null ? new string[] { sourceContainer.Item.Prefab.Identifier } : null
},
onCompleted: () => IsCompleted = true,
onAbandon: () =>
{
if (DropIfFailsToContain)
{
itemToDecontain.Drop(character);
}
Abandon = true;
});
onAbandon: () => Abandon = true);
}
else
{
@@ -133,8 +112,17 @@ namespace Barotrauma
public override void Reset()
{
base.Reset();
goToObjective = null;
getItemObjective = null;
containObjective = null;
}
protected override void OnAbandon()
{
base.OnAbandon();
if (DropIfFails && targetItem != null && targetItem.IsOwnedBy(character))
{
targetItem.Drop(character);
}
}
}
}
@@ -13,6 +13,8 @@ namespace Barotrauma
public override bool ConcurrentObjectives => true;
public override bool KeepDivingGearOn => true;
public override bool AllowInAnySub => true;
private readonly Hull targetHull;
private AIObjectiveGetItem getExtinguisherObjective;
@@ -30,12 +32,15 @@ namespace Barotrauma
if (!IsAllowed)
{
Priority = 0;
Abandon = true;
return Priority;
}
if (!objectiveManager.IsCurrentOrder<AIObjectiveExtinguishFires>()
&& Character.CharacterList.Any(c => c.CurrentHull == targetHull && !HumanAIController.IsFriendly(c) && HumanAIController.IsActive(c)))
bool isOrder = objectiveManager.IsCurrentOrder<AIObjectiveExtinguishFires>();
if (!isOrder && Character.CharacterList.Any(c => c.CurrentHull == targetHull && !HumanAIController.IsFriendly(c) && HumanAIController.IsActive(c)))
{
// Don't go into rooms with any enemies, unless it's an order
Priority = 0;
Abandon = true;
}
else
{
@@ -43,14 +48,22 @@ namespace Barotrauma
yDist = yDist > 100 ? yDist * 3 : 0;
float dist = Math.Abs(character.WorldPosition.X - targetHull.WorldPosition.X) + yDist;
float distanceFactor = MathHelper.Lerp(1, 0.1f, MathUtils.InverseLerp(0, 5000, dist));
if (targetHull == character.CurrentHull)
if (targetHull == character.CurrentHull || HumanAIController.VisibleHulls.Contains(targetHull))
{
distanceFactor = 1;
}
float severity = AIObjectiveExtinguishFires.GetFireSeverity(targetHull);
float severityFactor = MathHelper.Lerp(0, 1, severity / 100);
float devotion = CumulatedDevotion / 100;
Priority = MathHelper.Lerp(0, 100, MathHelper.Clamp(devotion + (severityFactor * distanceFactor * PriorityModifier), 0, 1));
if (severity > 0.5f && !isOrder)
{
// Ignore severe fires unless ordered. (Let the fire drain all the oxygen instead).
Priority = 0;
Abandon = true;
}
else
{
float devotion = CumulatedDevotion / 100;
Priority = MathHelper.Lerp(0, 100, MathHelper.Clamp(devotion + (severity * distanceFactor * PriorityModifier), 0, 1));
}
}
return Priority;
}
@@ -131,13 +144,16 @@ namespace Barotrauma
if (move)
{
//go to the first firesource
TryAddSubObjective(ref gotoObjective, () => new AIObjectiveGoTo(fs, character, objectiveManager, closeEnough: extinguisher.Range / 2)
if (TryAddSubObjective(ref gotoObjective, () => new AIObjectiveGoTo(fs, character, objectiveManager, closeEnough: extinguisher.Range / 2)
{
DialogueIdentifier = "dialogcannotreachfire",
TargetName = fs.Hull.DisplayName
},
onAbandon: () => Abandon = true,
onCompleted: () => RemoveSubObjective(ref gotoObjective)))
{
DialogueIdentifier = "dialogcannotreachfire",
TargetName = fs.Hull.DisplayName
},
onAbandon: () => Abandon = true,
onCompleted: () => RemoveSubObjective(ref gotoObjective));
gotoObjective.requiredCondition = () => HumanAIController.VisibleHulls.Contains(fs.Hull);
}
}
else
{
@@ -1,6 +1,8 @@
using System.Linq;
using System;
using System.Linq;
using System.Collections.Generic;
using Barotrauma.Extensions;
using Microsoft.Xna.Framework;
namespace Barotrauma
{
@@ -8,14 +10,22 @@ namespace Barotrauma
{
public override string DebugTag => "extinguish fires";
public override bool ForceRun => true;
public override bool AllowInAnySub => true;
public AIObjectiveExtinguishFires(Character character, AIObjectiveManager objectiveManager, float priorityModifier = 1) : base(character, objectiveManager, priorityModifier) { }
protected override bool Filter(Hull hull) => IsValidTarget(hull, character);
protected override float TargetEvaluation() => Targets.Sum(t => GetFireSeverity(t));
protected override float TargetEvaluation() =>
// If any target is visible -> 100 priority
Targets.Any(t => t == character.CurrentHull || HumanAIController.VisibleHulls.Contains(t)) ? 100 :
// Else based on the fire severity
Targets.Sum(t => GetFireSeverity(t) * 100);
public static float GetFireSeverity(Hull hull) => hull.FireSources.Sum(fs => fs.Size.X);
/// <summary>
/// 0-1 based on the horizontal size of all of the fires in the hull.
/// </summary>
public static float GetFireSeverity(Hull hull) => MathHelper.Lerp(0, 1, MathUtils.InverseLerp(0, Math.Min(hull.Rect.Width, 1000), hull.FireSources.Sum(fs => fs.Size.X)));
protected override IEnumerable<Hull> GetList() => Hull.hullList;
@@ -31,22 +41,7 @@ namespace Barotrauma
if (hull.FireSources.None()) { return false; }
if (hull.Submarine == null) { return false; }
if (character.Submarine == null) { return false; }
if (!character.Submarine.IsConnectedTo(hull.Submarine)) { return false; }
if (character.AIController is HumanAIController humanAI)
{
if (hull.Submarine.TeamID != character.TeamID)
{
if (humanAI.ObjectiveManager.IsCurrentOrder<AIObjectiveExtinguishFires>())
{
// For orders, allow targets in the current sub (for example if the bot is inside an outpost or a wreck)
if (hull.Submarine != character.Submarine) { return false; }
}
else
{
return false;
}
}
}
if (!character.Submarine.IsEntityFoundOnThisSub(hull, includingConnectedSubs: true)) { return false; }
return true;
}
}
@@ -17,7 +17,7 @@ namespace Barotrauma
private Item targetItem;
public static float MIN_OXYGEN = 10;
public static string HEAVY_DIVING_GEAR = "heavydiving";
public static string HEAVY_DIVING_GEAR = "deepdiving";
public static string LIGHT_DIVING_GEAR = "lightdiving";
public static string OXYGEN_SOURCE = "oxygensource";
@@ -14,8 +14,9 @@ namespace Barotrauma
public override bool IgnoreUnsafeHulls => true;
public override bool ConcurrentObjectives => true;
public override bool AllowOutsideSubmarine => true;
public override bool AllowInAnySub => true;
public override bool AbandonWhenCannotCompleteSubjectives => false;
public override bool IsLoop { get => true; set => throw new Exception("Trying to set the value for IsLoop from: " + Environment.StackTrace); }
public override bool IsLoop { get => true; set => throw new Exception("Trying to set the value for IsLoop from: " + Environment.StackTrace.CleanupStackTrace()); }
// TODO: expose?
const float priorityIncrease = 100;
@@ -12,6 +12,7 @@ namespace Barotrauma
public override string DebugTag => "fix leak";
public override bool ForceRun => true;
public override bool KeepDivingGearOn => true;
public override bool AllowInAnySub => true;
public Gap Leak { get; private set; }
@@ -35,11 +36,7 @@ namespace Barotrauma
if (!IsAllowed)
{
Priority = 0;
return Priority;
}
if (Leak.Removed || Leak.Open <= 0)
{
Priority = 0;
Abandon = true;
}
else if (HumanAIController.IsTrueForAnyCrewMember(other => other != HumanAIController && other.ObjectiveManager.GetActiveObjective<AIObjectiveFixLeak>()?.Leak == Leak))
{
@@ -116,7 +113,7 @@ namespace Barotrauma
{
HumanAIController.AnimController.Crouching = true;
}
float reach = repairTool.Range + ConvertUnits.ToDisplayUnits(((HumanoidAnimController)character.AnimController).ArmLength);
float reach = CalculateReach(repairTool, character);
bool canOperate = toLeak.LengthSquared() < reach * reach;
if (canOperate)
{
@@ -144,7 +141,7 @@ namespace Barotrauma
onAbandon: () =>
{
if (Check()) { IsCompleted = true; }
else if ((Leak.WorldPosition - character.WorldPosition).LengthSquared() > reach * reach * 2)
else if ((Leak.WorldPosition - character.WorldPosition).LengthSquared() > MathUtils.Pow(reach * 2, 2))
{
// Too far
Abandon = true;
@@ -167,5 +164,14 @@ namespace Barotrauma
gotoObjective = null;
operateObjective = null;
}
public static float CalculateReach(RepairTool repairTool, Character character)
{
float armLength = ConvertUnits.ToDisplayUnits(((HumanoidAnimController)character.AnimController).ArmLength);
// This is an approximation, because we don't know the exact reach until the pose is taken.
// And even then the actual range depends on the direction we are aiming to.
// Found out that without any multiplier the value (209) is often too short.
return repairTool.Range + armLength * 1.2f;
}
}
}
@@ -9,6 +9,7 @@ namespace Barotrauma
public override string DebugTag => "fix leaks";
public override bool ForceRun => true;
public override bool KeepDivingGearOn => true;
public override bool AllowInAnySub => true;
private Hull PrioritizedHull { get; set; }
public AIObjectiveFixLeaks(Character character, AIObjectiveManager objectiveManager, float priorityModifier = 1, Hull prioritizedHull = null) : base(character, objectiveManager, priorityModifier)
@@ -71,12 +72,9 @@ namespace Barotrauma
{
if (gap == null) { return false; }
if (gap.ConnectedWall == null || gap.ConnectedDoor != null || gap.Open <= 0 || gap.linkedTo.All(l => l == null)) { return false; }
if (gap.Submarine == null) { return false; }
if (gap.Submarine.TeamID != character.TeamID) { return false; }
if (character.Submarine != null)
{
if (!character.Submarine.IsConnectedTo(gap.Submarine)) { return false; }
}
if (gap.Submarine == null || character.Submarine == null) { return false; }
// Don't allow going into another sub, unless it's connected and of the same team and type.
if (!character.Submarine.IsEntityFoundOnThisSub(gap, includingConnectedSubs: true)) { return false; }
return true;
}
}
@@ -37,6 +37,7 @@ namespace Barotrauma
public static float DefaultReach = 100;
public bool AllowToFindDivingGear { get; set; } = true;
public bool MustBeSpecificItem { get; set; }
public AIObjectiveGetItem(Character character, Item targetItem, AIObjectiveManager objectiveManager, bool equip = true, float priorityModifier = 1)
: base(character, objectiveManager, priorityModifier)
@@ -84,6 +85,11 @@ namespace Barotrauma
Abandon = true;
return;
}
if (character.Submarine == null)
{
Abandon = true;
return;
}
if (identifiersOrTags != null && !isDoneSeeking)
{
if (checkInventory)
@@ -109,7 +115,10 @@ namespace Barotrauma
}
}
FindTargetItem();
objectiveManager.GetObjective<AIObjectiveIdle>().Wander(deltaTime);
if (!objectiveManager.IsCurrentOrder<AIObjectiveGoTo>())
{
objectiveManager.GetObjective<AIObjectiveIdle>().Wander(deltaTime);
}
return;
}
}
@@ -137,7 +146,8 @@ namespace Barotrauma
if (originalTarget == null)
{
// Try again
Reset();
ignoredItems.Add(targetItem);
ResetInternal();
}
else
{
@@ -176,12 +186,8 @@ namespace Barotrauma
return;
}
if (HumanAIController.TryToMoveItem(targetItem, character.Inventory))
if (HumanAIController.TakeItem(targetItem, character.Inventory, equip, storeUnequipped: true))
{
if (equip)
{
targetItem.Equip(character);
}
IsCompleted = true;
}
else
@@ -207,8 +213,16 @@ namespace Barotrauma
},
onAbandon: () =>
{
ignoredItems.Add(targetItem);
Reset();
if (originalTarget == null)
{
// Try again
ignoredItems.Add(targetItem);
ResetInternal();
}
else
{
Abandon = true;
}
},
onCompleted: () => RemoveSubObjective(ref goToObjective));
}
@@ -235,13 +249,13 @@ namespace Barotrauma
Submarine mySub = character.Submarine;
if (itemSub == null) { continue; }
if (mySub == null) { continue; }
if (itemSub.TeamID != mySub.TeamID && itemSub.TeamID != character.TeamID) { continue; }
if (!CheckItem(item)) { continue; }
if (ignoredContainerIdentifiers != null && item.Container != null)
{
if (ignoredContainerIdentifiers.Contains(item.ContainerIdentifier)) { continue; }
}
if (!mySub.IsConnectedTo(itemSub)) { continue; }
// Don't allow going into another sub, unless it's connected and of the same team and type.
if (!character.Submarine.IsEntityFoundOnThisSub(item, includingConnectedSubs: true)) { continue; }
if (character.IsItemTakenBySomeoneElse(item)) { continue; }
float itemPriority = 1;
if (GetItemPriority != null)
@@ -272,7 +286,7 @@ namespace Barotrauma
if (!(MapEntityPrefab.List.FirstOrDefault(me => me is ItemPrefab ip && identifiersOrTags.Any(id => id == ip.Identifier || ip.Tags.Contains(id))) is ItemPrefab prefab))
{
#if DEBUG
DebugConsole.NewMessage($"{character.Name}: Cannot find the item with the following identifier(s): {string.Join(", ", identifiersOrTags)}, tried to spawn the item but no matching item prefabs were found.", Color.Yellow);
DebugConsole.NewMessage($"{character.Name}: Cannot find the item with the following identifier(s) or tag(s): {string.Join(", ", identifiersOrTags)}, tried to spawn the item but no matching item prefabs were found.", Color.Yellow);
#endif
Abandon = true;
}
@@ -291,7 +305,7 @@ namespace Barotrauma
else
{
#if DEBUG
DebugConsole.NewMessage($"{character.Name}: Cannot find the item with the following identifier(s): {string.Join(", ", identifiersOrTags)}", Color.Yellow);
DebugConsole.NewMessage($"{character.Name}: Cannot find the item with the following identifier(s) or tag(s): {string.Join(", ", identifiersOrTags)}", Color.Yellow);
#endif
Abandon = true;
}
@@ -330,11 +344,28 @@ namespace Barotrauma
public override void Reset()
{
base.Reset();
ResetInternal();
}
/// <summary>
/// Does not reset the ignored items list
/// </summary>
private void ResetInternal()
{
goToObjective = null;
targetItem = originalTarget;
moveToTarget = targetItem?.GetRootInventoryOwner();
isDoneSeeking = false;
currSearchIndex = 0;
}
protected override void OnAbandon()
{
base.OnAbandon();
if (objectiveManager.CurrentOrder != null)
{
character.Speak(TextManager.Get("DialogCannotFindItem"), null, 0.0f, "cannotfinditem", 10.0f);
}
}
}
}
@@ -1,5 +1,6 @@
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Barotrauma
@@ -50,6 +51,7 @@ namespace Barotrauma
public override bool AbandonWhenCannotCompleteSubjectives => !repeat;
public override bool AllowOutsideSubmarine => AllowGoingOutside;
public override bool AllowInAnySub => true;
public string DialogueIdentifier { get; set; }
public string TargetName { get; set; }
@@ -60,17 +62,27 @@ namespace Barotrauma
public override float GetPriority()
{
bool isOrder = objectiveManager.CurrentOrder == this;
if (!IsAllowed)
{
Priority = 0;
Abandon = !isOrder;
return Priority;
}
if (followControlledCharacter && Character.Controlled == null)
{
Priority = 0;
Abandon = !isOrder;
}
if (Target is Entity e && e.Removed)
{
Priority = 0;
Abandon = !isOrder;
}
if (IgnoreIfTargetDead && Target is Character character && character.IsDead)
{
Priority = 0;
Abandon = !isOrder;
}
else
{
@@ -84,7 +96,7 @@ namespace Barotrauma
}
else
{
Priority = objectiveManager.CurrentOrder == this ? AIObjectiveManager.OrderPriority : 10;
Priority = isOrder ? AIObjectiveManager.OrderPriority : 10;
}
}
return Priority;
@@ -93,7 +105,7 @@ namespace Barotrauma
public AIObjectiveGoTo(ISpatialEntity target, Character character, AIObjectiveManager objectiveManager, bool repeat = false, bool getDivingGearIfNeeded = true, float priorityModifier = 1, float closeEnough = 0)
: base(character, objectiveManager, priorityModifier)
{
this.Target = target;
Target = target;
this.repeat = repeat;
waitUntilPathUnreachable = 3.0f;
this.getDivingGearIfNeeded = getDivingGearIfNeeded;
@@ -260,6 +272,53 @@ namespace Barotrauma
}
}
}
if (!character.AnimController.InWater)
{
useScooter = false;
checkScooterTimer = 0;
}
else if (checkScooterTimer <= 0)
{
useScooter = false;
checkScooterTimer = checkScooterTime;
string scooterTag = "scooter";
string batteryTag = "mobilebattery";
Item scooter = null;
bool isScooterEquipped = false;
float closeEnough = 250;
float squaredDistance = Vector2.DistanceSquared(character.WorldPosition, Target.WorldPosition);
bool shouldUseScooter = squaredDistance > closeEnough * closeEnough && (!mimic ||
(Target is Character targetCharacter && targetCharacter.HasEquippedItem(scooterTag, allowBroken: false)) || squaredDistance > Math.Pow(closeEnough * 2, 2));
if (HumanAIController.HasItem(character, scooterTag, out IEnumerable<Item> equippedScooters, batteryTag, requireEquipped: true))
{
scooter = equippedScooters.FirstOrDefault();
isScooterEquipped = scooter != null;
}
else if (shouldUseScooter && HumanAIController.HasItem(character, scooterTag, out IEnumerable<Item> scooters, batteryTag, requireEquipped: false))
{
scooter = scooters.FirstOrDefault();
if (scooter != null)
{
isScooterEquipped = HumanAIController.TakeItem(scooter, character.Inventory, equip: true, dropOtherIfCannotMove: false, allowSwapping: true, storeUnequipped: false);
}
}
if (scooter != null && isScooterEquipped)
{
if (shouldUseScooter)
{
useScooter = true;
}
else
{
// Unequip
character.Inventory.TryPutItem(scooter, character, CharacterInventory.anySlot);
}
}
}
else
{
checkScooterTimer -= deltaTime;
}
if (SteeringManager == PathSteering)
{
Func<PathNode, bool> nodeFilter = null;
@@ -274,47 +333,90 @@ namespace Barotrauma
}, endNodeFilter, nodeFilter, CheckVisibility);
if (!isInside && PathSteering.CurrentPath == null || PathSteering.IsPathDirty || PathSteering.CurrentPath.Unreachable)
{
SteeringManager.SteeringManual(deltaTime, Vector2.Normalize(Target.WorldPosition - character.WorldPosition));
if (character.AnimController.InWater)
if (useScooter)
{
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: 5, weight: 15);
UseScooter(Target.WorldPosition);
}
else
{
SteeringManager.SteeringManual(deltaTime, Vector2.Normalize(Target.WorldPosition - character.WorldPosition));
if (character.AnimController.InWater)
{
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: 5, weight: 15);
}
}
}
else if (useScooter && PathSteering.CurrentPath?.CurrentNode != null)
{
UseScooter(PathSteering.CurrentPath.CurrentNode.WorldPosition);
}
}
else
{
SteeringManager.SteeringSeek(character.GetRelativeSimPosition(Target), 10);
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: 5, weight: 15);
if (useScooter)
{
UseScooter(Target.WorldPosition);
}
else
{
SteeringManager.SteeringSeek(character.GetRelativeSimPosition(Target), 10);
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: 5, weight: 15);
}
}
}
void UseScooter(Vector2 targetWorldPos)
{
SteeringManager.Reset();
character.CursorPosition = targetWorldPos;
if (character.Submarine != null)
{
character.CursorPosition -= character.Submarine.Position;
}
Vector2 dir = Vector2.Normalize(character.CursorPosition - character.Position);
if (!MathUtils.IsValid(dir)) { dir = Vector2.UnitY; }
SteeringManager.SteeringManual(1.0f, dir);
character.SetInput(InputType.Aim, false, true);
character.SetInput(InputType.Shoot, false, true);
}
}
public Hull GetTargetHull()
private bool useScooter;
private float checkScooterTimer;
private readonly float checkScooterTime = 0.2f;
public Hull GetTargetHull() => GetTargetHull(Target);
public static Hull GetTargetHull(ISpatialEntity target)
{
if (Target is Hull h)
if (target is Hull h)
{
return h;
}
else if (Target is Item i)
else if (target is Item i)
{
return i.CurrentHull;
}
else if (Target is Character c)
else if (target is Character c)
{
return c.CurrentHull;
}
else if (Target is Gap g)
else if (target is Gap g)
{
return g.FlowTargetHull;
}
else if (Target is WayPoint wp)
else if (target is WayPoint wp)
{
return wp.CurrentHull;
}
else if (Target is FireSource fs)
else if (target is FireSource fs)
{
return fs.Hull;
}
else if (target is OrderTarget ot)
{
return ot.Hull;
}
return null;
}
@@ -361,7 +463,7 @@ namespace Barotrauma
{
if (Target is Item item)
{
if (character.CanInteractWith(item, out _, checkLinked: false)) { IsCompleted = true; }
if (!character.IsClimbing && character.CanInteractWith(item, out _, checkLinked: false)) { IsCompleted = true; }
}
else if (Target is Character targetCharacter)
{
@@ -1,4 +1,5 @@
using Barotrauma.Items.Components;
using Barotrauma.Extensions;
using Barotrauma.Items.Components;
using FarseerPhysics;
using Microsoft.Xna.Framework;
using System;
@@ -11,14 +12,14 @@ namespace Barotrauma
{
public override string DebugTag => "idle";
public override bool AllowAutomaticItemUnequipping => true;
public override bool AllowOutsideSubmarine => true;
public override bool AllowInAnySub => true;
private BehaviorType behavior;
public BehaviorType Behavior
{
get { return behavior; }
set
{
set
{
behavior = value;
switch (behavior)
{
@@ -27,16 +28,13 @@ namespace Barotrauma
newTargetIntervalMax = 20;
standStillMin = 2;
standStillMax = 10;
walkDurationMin = 5;
walkDurationMax = 10;
break;
case BehaviorType.Passive:
case BehaviorType.StayInHull:
newTargetIntervalMin = 60;
newTargetIntervalMax = 120;
standStillMin = 30;
standStillMax = 60;
walkDurationMin = 5;
walkDurationMax = 10;
break;
}
}
@@ -46,8 +44,8 @@ namespace Barotrauma
private float newTargetIntervalMax;
private float standStillMin;
private float standStillMax;
private float walkDurationMin;
private float walkDurationMax;
private readonly float walkDurationMin = 5;
private readonly float walkDurationMax = 10;
public enum BehaviorType
{
@@ -55,7 +53,7 @@ namespace Barotrauma
Passive,
StayInHull
}
public Hull TargetHull { get; set; }
private Hull currentTarget;
private float newTargetTimer;
@@ -86,7 +84,7 @@ namespace Barotrauma
protected override bool Check() => false;
public override bool CanBeCompleted => true;
public override bool IsLoop { get => true; set => throw new Exception("Trying to set the value for IsLoop from: " + Environment.StackTrace); }
public override bool IsLoop { get => true; set => throw new Exception("Trying to set the value for IsLoop from: " + Environment.StackTrace.CleanupStackTrace()); }
public readonly HashSet<string> PreferredOutpostModuleTypes = new HashSet<string>();
@@ -142,6 +140,8 @@ namespace Barotrauma
timerMargin = 0;
}
private bool IsSteeringFinished() => PathSteering.CurrentPath != null && (PathSteering.CurrentPath.Finished || PathSteering.CurrentPath.Unreachable);
protected override void Act(float deltaTime)
{
if (PathSteering == null) { return; }
@@ -164,12 +164,30 @@ namespace Barotrauma
character.DeselectCharacter();
}
if (behavior != BehaviorType.StayInHull)
if (!character.IsClimbing)
{
bool currentTargetIsInvalid = currentTarget == null || IsForbidden(currentTarget) ||
(PathSteering.CurrentPath != null && PathSteering.CurrentPath.Nodes.Any(n => HumanAIController.UnsafeHulls.Contains(n.CurrentHull)));
character.SelectedConstruction = null;
}
bool IsSteeringFinished() => PathSteering.CurrentPath != null && (PathSteering.CurrentPath.Finished || PathSteering.CurrentPath.Unreachable);
CleanupItems(deltaTime);
if (behavior == BehaviorType.StayInHull)
{
currentTarget = TargetHull;
bool stayInHull = character.CurrentHull == currentTarget && IsSteeringFinished() && !character.IsClimbing;
if (stayInHull)
{
Wander(deltaTime);
}
else if (currentTarget != null)
{
PathSteering.SteeringSeek(character.GetRelativeSimPosition(currentTarget), weight: 1, nodeFilter: node => node.Waypoint.CurrentHull != null);
}
}
else
{
bool currentTargetIsInvalid = currentTarget == null || IsForbidden(currentTarget) ||
(PathSteering.CurrentPath != null && PathSteering.CurrentPath.Nodes.Any(n => HumanAIController.UnsafeHulls.Contains(n.CurrentHull)));
if (currentTarget != null && !currentTargetIsInvalid)
{
@@ -226,7 +244,7 @@ namespace Barotrauma
searchingNewHull = true;
return;
}
else if (targetHulls.Count > 0)
else if (targetHulls.Any())
{
//choose a random available hull
currentTarget = ToolBox.SelectWeightedRandom(targetHulls, hullWeights, Rand.RandSync.Unsynced);
@@ -242,12 +260,13 @@ namespace Barotrauma
});
if (path.Unreachable)
{
//can't go to this room, remove it from the list and try another room next frame
//can't go to this room, remove it from the list and try another room
int index = targetHulls.IndexOf(currentTarget);
targetHulls.RemoveAt(index);
hullWeights.RemoveAt(index);
PathSteering.Reset();
currentTarget = null;
SetTargetTimerLow();
return;
}
searchingNewHull = false;
@@ -263,47 +282,25 @@ namespace Barotrauma
{
character.AIController.SelectTarget(currentTarget.AiTarget);
string errorMsg = null;
#if DEBUG
#if DEBUG
bool isRoomNameFound = currentTarget.DisplayName != null;
errorMsg = "(Character " + character.Name + " idling, target " + (isRoomNameFound ? currentTarget.DisplayName : currentTarget.ToString()) + ")";
#endif
#endif
var path = PathSteering.PathFinder.FindPath(character.SimPosition, currentTarget.SimPosition, errorMsgStr: errorMsg, nodeFilter: node => node.Waypoint.CurrentHull != null);
PathSteering.SetPath(path);
}
SetTargetTimerNormal();
}
}
newTargetTimer -= deltaTime;
}
//wander randomly
// - if reached the end of the path
// - if the target is unreachable
// - if the path requires going outside
if (!character.IsClimbing)
{
if (behavior == BehaviorType.StayInHull || SteeringManager != PathSteering || (PathSteering.CurrentPath != null &&
(PathSteering.CurrentPath.Finished || PathSteering.CurrentPath.Unreachable || PathSteering.CurrentPath.HasOutdoorsNodes)))
if (!character.IsClimbing && IsSteeringFinished())
{
Wander(deltaTime);
return;
}
character.SelectedConstruction = null;
}
if (currentTarget != null)
{
if (SteeringManager == PathSteering)
else if (currentTarget != null)
{
PathSteering.SteeringSeek(character.GetRelativeSimPosition(currentTarget), weight: 1, nodeFilter: node => node.Waypoint.CurrentHull != null);
}
else
{
character.AIController.SteeringManager.SteeringSeek(character.GetRelativeSimPosition(currentTarget));
}
}
else
{
Wander(deltaTime);
}
}
@@ -328,7 +325,7 @@ namespace Barotrauma
{
//if there are characters too close on both sides, don't try to steer away from them
//because it'll cause the character to spaz out trying to avoid both
if (tooCloseCharacter != null &&
if (tooCloseCharacter != null &&
Math.Sign(tooCloseCharacter.WorldPosition.X - character.WorldPosition.X) != Math.Sign(c.WorldPosition.X - character.WorldPosition.X))
{
tooCloseCharacter = null;
@@ -336,7 +333,7 @@ namespace Barotrauma
}
tooCloseCharacter = c;
}
HumanAIController.FaceTarget(c);
HumanAIController.FaceTarget(c);
}
}
@@ -344,7 +341,7 @@ namespace Barotrauma
{
Vector2 diff = character.WorldPosition - tooCloseCharacter.WorldPosition;
if (diff.LengthSquared() < 0.0001f) { diff = Rand.Vector(1.0f); }
if (Math.Abs(diff.X) > 0 &&
if (Math.Abs(diff.X) > 0 &&
(character.WorldPosition.X > currentHull.WorldRect.Right - 50 || character.WorldPosition.X < currentHull.WorldRect.Left + 50))
{
// Between a wall and a character -> move away
@@ -459,6 +456,48 @@ namespace Barotrauma
}
}
#region Cleaning
private readonly float checkItemsInterval = 1;
private float checkItemsTimer;
private readonly List<Item> itemsToClean = new List<Item>();
private readonly List<Item> ignoredItems = new List<Item>();
private void CleanupItems(float deltaTime)
{
if (checkItemsTimer <= 0)
{
checkItemsTimer = checkItemsInterval * Rand.Range(0.9f, 1.1f);
var hull = character.CurrentHull;
if (hull != null)
{
itemsToClean.Clear();
foreach (Item item in Item.ItemList)
{
if (item.CurrentHull != hull) { continue; }
if (AIObjectiveCleanupItems.IsValidTarget(item, character) && !ignoredItems.Contains(item))
{
itemsToClean.Add(item);
}
}
if (itemsToClean.Any())
{
var targetItem = itemsToClean.OrderBy(i => Math.Abs(character.WorldPosition.X - i.WorldPosition.X)).FirstOrDefault();
if (targetItem != null)
{
var cleanupObjective = new AIObjectiveCleanupItem(targetItem, character, objectiveManager, PriorityModifier);
cleanupObjective.Abandoned += () => ignoredItems.Add(targetItem);
subObjectives.Add(cleanupObjective);
}
}
}
}
else
{
checkItemsTimer -= deltaTime;
}
}
#endregion
public static bool IsForbidden(Hull hull)
{
if (hull == null) { return true; }
@@ -475,6 +514,9 @@ namespace Barotrauma
tooCloseCharacter = null;
targetHulls.Clear();
hullWeights.Clear();
checkItemsTimer = 0;;
itemsToClean.Clear();
ignoredItems.Clear();
autonomousObjectiveRetryTimer = 10;
}
}
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using Barotrauma.Extensions;
using Microsoft.Xna.Framework;
namespace Barotrauma
@@ -46,7 +45,7 @@ namespace Barotrauma
public override bool AllowSubObjectiveSorting => true;
public virtual bool InverseTargetEvaluation => false;
public override bool IsLoop { get => true; set => throw new Exception("Trying to set the value for IsLoop from: " + System.Environment.StackTrace); }
public override bool IsLoop { get => true; set => throw new Exception("Trying to set the value for IsLoop from: " + System.Environment.StackTrace.CleanupStackTrace()); }
public override void Update(float deltaTime)
{
@@ -79,7 +78,12 @@ namespace Barotrauma
var target = objective.Key;
if (!Targets.Contains(target))
{
subObjectives.Remove(objective.Value);
var subObjective = objective.Value;
if (CurrentSubObjective == subObjective)
{
CurrentSubObjective.Abandon = !CurrentSubObjective.IsCompleted;
}
subObjectives.Remove(subObjective);
}
}
SyncRemovedObjectives(Objectives, GetList());
@@ -137,7 +141,7 @@ namespace Barotrauma
{
if (objectiveManager.CurrentOrder == this)
{
Priority = AIObjectiveManager.OrderPriority;
Priority = ForceOrderPriority ? AIObjectiveManager.OrderPriority : targetValue;
}
else
{
@@ -70,7 +70,7 @@ namespace Barotrauma
if (objective == null)
{
#if DEBUG
DebugConsole.ThrowError("Attempted to add a null objective to AIObjectiveManager\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to add a null objective to AIObjectiveManager\n" + Environment.StackTrace.CleanupStackTrace());
#endif
return;
}
@@ -128,8 +128,7 @@ namespace Barotrauma
var orderPrefab = Order.GetPrefab(autonomousObjective.identifier);
if (orderPrefab == null) { throw new Exception($"Could not find a matching prefab by the identifier: '{autonomousObjective.identifier}'"); }
var item = orderPrefab.MustSetTarget ? orderPrefab.GetMatchingItems(character.Submarine, mustBelongToPlayerSub: false, requiredTeam: character.Info.TeamID)?.GetRandom() : null;
var order = new Order(orderPrefab, item ?? character.CurrentHull as Entity,
item?.Components.FirstOrDefault(ic => ic.GetType() == orderPrefab.ItemComponentType), orderGiver: character);
var order = new Order(orderPrefab, item ?? character.CurrentHull as Entity, orderPrefab.GetTargetItemComponent(item), orderGiver: character);
if (order == null) { continue; }
if (autonomousObjective.ignoreAtOutpost && Level.IsLoadedOutpost && character.TeamID != Character.TeamType.FriendlyNPC) { continue; }
var objective = CreateObjective(order, autonomousObjective.option, character, isAutonomous: true, autonomousObjective.priorityModifier);
@@ -147,7 +146,7 @@ namespace Barotrauma
if (objective == null)
{
#if DEBUG
DebugConsole.ThrowError($"{character.Name}: Attempted to add a null objective to AIObjectiveManager\n" + Environment.StackTrace);
DebugConsole.ThrowError($"{character.Name}: Attempted to add a null objective to AIObjectiveManager\n" + Environment.StackTrace.CleanupStackTrace());
#endif
return;
}
@@ -314,9 +313,10 @@ namespace Barotrauma
};
break;
case "wait":
newObjective = new AIObjectiveGoTo(order.TargetEntity ?? character, character, this, repeat: true, priorityModifier: priorityModifier)
newObjective = new AIObjectiveGoTo(order.TargetSpatialEntity ?? character, character, this, repeat: true, priorityModifier: priorityModifier)
{
AllowGoingOutside = character.CurrentHull == null
AllowGoingOutside = order.TargetSpatialEntity == null ? character.CurrentHull == null :
character.Submarine == null || character.Submarine != order.TargetSpatialEntity.Submarine
};
break;
case "fixleaks":
@@ -374,6 +374,32 @@ namespace Barotrauma
Override = orderGiver != null && orderGiver.IsPlayer
};
break;
case "setchargepct":
newObjective = new AIObjectiveOperateItem(order.TargetItemComponent, character, this, option, false, priorityModifier: priorityModifier)
{
IsLoop = false,
Override = character.CurrentOrder != null,
completionCondition = () =>
{
if (float.TryParse(option, out float pct))
{
var targetRatio = Math.Clamp(pct, 0f, 1f);
var currentRatio = (order.TargetItemComponent as PowerContainer).RechargeRatio;
return Math.Abs(targetRatio - currentRatio) < 0.05f;
}
return true;
}
};
break;
case "getitem":
newObjective = new AIObjectiveGetItem(character, order.TargetEntity as Item ?? order.TargetItemComponent?.Item, this, false, priorityModifier: priorityModifier)
{
MustBeSpecificItem = true
};
break;
case "cleanupitems":
newObjective = new AIObjectiveCleanupItems(character, this, priorityModifier, order.TargetEntity as Item);
break;
default:
if (order.TargetItemComponent == null) { return null; }
if (order.TargetItemComponent.Item.NonInteractable) { return null; }
@@ -11,6 +11,7 @@ namespace Barotrauma
public override string DebugTag => $"operate item {component.Name}";
public override bool AllowAutomaticItemUnequipping => true;
public override bool AllowMultipleInstances => true;
public override bool AllowInAnySub => true;
private ItemComponent component, controller;
private Entity operateTarget;
@@ -35,9 +36,11 @@ namespace Barotrauma
public override float GetPriority()
{
bool isOrder = objectiveManager.CurrentOrder == this;
if (!IsAllowed || character.LockHands)
{
Priority = 0;
Abandon = !isOrder;
return Priority;
}
if (component.Item.ConditionPercentage <= 0)
@@ -46,7 +49,6 @@ namespace Barotrauma
}
else
{
bool isOrder = objectiveManager.CurrentOrder == this;
if (isOrder)
{
Priority = AIObjectiveManager.OrderPriority;
@@ -172,7 +174,7 @@ namespace Barotrauma
}
if (target.CanBeSelected)
{
if (character.CanInteractWith(target.Item, out _, checkLinked: false))
if (!character.IsClimbing && character.CanInteractWith(target.Item, out _, checkLinked: false))
{
HumanAIController.FaceTarget(target.Item);
if (character.SelectedConstruction != target.Item)
@@ -189,7 +191,8 @@ namespace Barotrauma
TryAddSubObjective(ref goToObjective, () => new AIObjectiveGoTo(target.Item, character, objectiveManager, closeEnough: 50)
{
DialogueIdentifier = "dialogcannotreachtarget",
TargetName = target.Item.Name
TargetName = target.Item.Name,
endNodeFilter = node => node.Waypoint.Ladders == null
},
onAbandon: () => Abandon = true,
onCompleted: () => RemoveSubObjective(ref goToObjective));
@@ -10,6 +10,8 @@ namespace Barotrauma
{
public override string DebugTag => "repair item";
public override bool AllowInAnySub => true;
public Item Item { get; private set; }
private AIObjectiveGoTo goToObjective;
@@ -34,6 +36,7 @@ namespace Barotrauma
if (!IsAllowed)
{
Priority = 0;
Abandon = true;
return Priority;
}
// TODO: priority list?
@@ -69,7 +72,7 @@ namespace Barotrauma
IsCompleted = Item.IsFullCondition;
if (IsCompleted && IsRepairing())
{
character?.Speak(TextManager.GetWithVariable("DialogItemRepaired", "[itemname]", Item.Name, true), null, 0.0f, "itemrepaired", 10.0f);
character.Speak(TextManager.GetWithVariable("DialogItemRepaired", "[itemname]", Item.Name, true), null, 0.0f, "itemrepaired", 10.0f);
}
return IsCompleted;
}
@@ -134,7 +137,7 @@ namespace Barotrauma
return;
}
}
if (character.CanInteractWith(Item, out _, checkLinked: false))
if (!character.IsClimbing && character.CanInteractWith(Item, out _, checkLinked: false))
{
HumanAIController.FaceTarget(Item);
if (repairTool != null)
@@ -235,7 +238,11 @@ namespace Barotrauma
private void OperateRepairTool(float deltaTime)
{
character.CursorPosition = Item.Position;
character.CursorPosition = Item.WorldPosition;
if (character.Submarine != null)
{
character.CursorPosition -= character.Submarine.Position;
}
if (repairTool.Item.RequireAimToUse)
{
character.SetInput(InputType.Aim, false, true);
@@ -24,11 +24,11 @@ namespace Barotrauma
private readonly Item prioritizedItem;
public override bool AllowMultipleInstances => true;
public override bool AllowInAnySub => true;
public readonly static float RequiredSuccessFactor = 0.4f;
public override bool IsDuplicate<T>(T otherObjective) =>
(otherObjective as AIObjective) is AIObjectiveRepairItems repairObjective && repairObjective.RequireAdequateSkills == RequireAdequateSkills;
public override bool IsDuplicate<T>(T otherObjective) => otherObjective is AIObjectiveRepairItems repairObjective && repairObjective.RequireAdequateSkills == RequireAdequateSkills;
public AIObjectiveRepairItems(Character character, AIObjectiveManager objectiveManager, float priorityModifier = 1, Item prioritizedItem = null)
: base(character, objectiveManager, priorityModifier)
@@ -151,13 +151,9 @@ namespace Barotrauma
if (item.NonInteractable) { return false; }
if (item.IsFullCondition) { return false; }
if (item.CurrentHull == null) { return false; }
if (item.Submarine == null) { return false; }
if (item.Submarine.TeamID != character.TeamID) { return false; }
if (item.Submarine == null || character.Submarine == null) { return false; }
if (!character.Submarine.IsEntityFoundOnThisSub(item, includingConnectedSubs: true)) { return false; }
if (item.Repairables.None()) { return false; }
if (character.Submarine != null)
{
if (!character.Submarine.IsConnectedTo(item.Submarine)) { return false; }
}
return true;
}
}
@@ -14,6 +14,7 @@ namespace Barotrauma
public override bool KeepDivingGearOn => true;
public override bool AllowOutsideSubmarine => true;
public override bool AllowInAnySub => true;
const float TreatmentDelay = 0.5f;
@@ -35,7 +36,7 @@ namespace Barotrauma
{
if (targetCharacter == null)
{
string errorMsg = $"{character.Name}: Attempted to create a Rescue objective with no target!\n" + Environment.StackTrace;
string errorMsg = $"{character.Name}: Attempted to create a Rescue objective with no target!\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("AIObjectiveRescue:ctor:targetnull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
Abandon = true;
@@ -392,11 +393,13 @@ namespace Barotrauma
if (!IsAllowed)
{
Priority = 0;
Abandon = true;
return Priority;
}
if (character.LockHands || targetCharacter == null || targetCharacter.CurrentHull == null || targetCharacter.Removed || targetCharacter.IsDead)
{
Priority = 0;
Abandon = true;
}
else
{
@@ -11,6 +11,7 @@ namespace Barotrauma
public override bool ForceRun => true;
public override bool InverseTargetEvaluation => true;
public override bool AllowOutsideSubmarine => true;
public override bool AllowInAnySub => true;
private const float vitalityThreshold = 75;
private const float vitalityThresholdForOrders = 85;
@@ -38,7 +38,8 @@ namespace Barotrauma
}
public bool MatchesOrder(Order order, string option) =>
order.Identifier == Order.Identifier && option == OrderOption && order.TargetEntity == Order.TargetEntity;
order.Identifier == Order.Identifier &&
option == OrderOption;
}
class Order
@@ -54,7 +55,7 @@ namespace Barotrauma
}
return order;
}
public Order Prefab { get; private set; }
public readonly string Name;
@@ -62,7 +63,8 @@ namespace Barotrauma
public readonly Sprite SymbolSprite;
public readonly Type ItemComponentType;
public readonly string[] ItemIdentifiers;
public readonly bool CanTypeBeSubclass;
public readonly string[] TargetItems;
public readonly string Identifier;
@@ -89,14 +91,14 @@ namespace Barotrauma
color = value;
}
}
//if true, the order is issued to all available characters
public bool TargetAllCharacters;
public readonly float FadeOutTime;
public Entity TargetEntity;
public Entity TargetEntity;
public ItemComponent TargetItemComponent;
public readonly bool UseController;
public Controller ConnectedController;
@@ -123,6 +125,18 @@ namespace Barotrauma
public bool IsPrefab { get; private set; }
public readonly bool MustManuallyAssign;
public readonly OrderTarget TargetPosition;
private ISpatialEntity targetSpatialEntity;
public ISpatialEntity TargetSpatialEntity
{
get
{
if (targetSpatialEntity == null) { targetSpatialEntity = TargetEntity ?? TargetPosition as ISpatialEntity; }
return targetSpatialEntity;
}
}
public static void Init()
{
Prefabs = new Dictionary<string, Order>();
@@ -218,8 +232,9 @@ namespace Barotrauma
DebugConsole.ThrowError("Error in the order definitions: item component type " + targetItemType + " not found", e);
}
}
CanTypeBeSubclass = orderElement.GetAttributeBool("cantypebesubclass", false);
ItemIdentifiers = orderElement.GetAttributeStringArray("targetitemidentifiers", new string[0], trim: true, convertToLowerInvariant: true);
TargetItems = orderElement.GetAttributeStringArray("targetitems", new string[0], trim: true, convertToLowerInvariant: true);
color = orderElement.GetAttributeColor("color");
FadeOutTime = orderElement.GetAttributeFloat("fadeouttime", 0.0f);
UseController = orderElement.GetAttributeBool("usecontroller", false);
@@ -228,7 +243,6 @@ namespace Barotrauma
Options = orderElement.GetAttributeStringArray("options", new string[0]);
var category = orderElement.GetAttributeString("category", null);
if (!string.IsNullOrWhiteSpace(category)) { this.Category = (OrderCategory)Enum.Parse(typeof(OrderCategory), category, true); }
Weight = orderElement.GetAttributeFloat(0.0f, "weight");
MustSetTarget = orderElement.GetAttributeBool("mustsettarget", false);
AppropriateSkill = orderElement.GetAttributeString("appropriateskill", null);
@@ -279,7 +293,7 @@ namespace Barotrauma
IsPrefab = true;
MustManuallyAssign = orderElement.GetAttributeBool("mustmanuallyassign", false);
}
/// <summary>
/// Constructor for order instances
/// </summary>
@@ -290,7 +304,8 @@ namespace Barotrauma
Name = prefab.Name;
Identifier = prefab.Identifier;
ItemComponentType = prefab.ItemComponentType;
ItemIdentifiers = prefab.ItemIdentifiers;
CanTypeBeSubclass = prefab.CanTypeBeSubclass;
TargetItems = prefab.TargetItems;
Options = prefab.Options;
SymbolSprite = prefab.SymbolSprite;
Color = prefab.Color;
@@ -298,7 +313,6 @@ namespace Barotrauma
TargetAllCharacters = prefab.TargetAllCharacters;
AppropriateJobs = prefab.AppropriateJobs;
FadeOutTime = prefab.FadeOutTime;
Weight = prefab.Weight;
MustSetTarget = prefab.MustSetTarget;
AppropriateSkill = prefab.AppropriateSkill;
Category = prefab.Category;
@@ -325,6 +339,11 @@ namespace Barotrauma
IsPrefab = false;
}
public Order(Order prefab, OrderTarget target, Character orderGiver = null) : this(prefab, targetEntity: null, targetItem: null, orderGiver)
{
TargetPosition = target;
}
public bool HasAppropriateJob(Character character)
{
@@ -358,15 +377,38 @@ namespace Barotrauma
return msg;
}
/// <summary>
/// Get the target item component based on the target item type
/// </summary>
public ItemComponent GetTargetItemComponent(Item item)
{
if (item?.Components == null || ItemComponentType == null) { return null; }
foreach (ItemComponent component in item.Components)
{
if (component?.GetType() is Type componentType)
{
if (componentType == ItemComponentType) { return component; }
if (CanTypeBeSubclass && componentType.IsSubclassOf(ItemComponentType)) { return component; }
}
}
return null;
}
public bool TryGetTargetItemComponent(Item item, out ItemComponent firstMatchingComponent)
{
firstMatchingComponent = GetTargetItemComponent(item);
return firstMatchingComponent != null;
}
public List<Item> GetMatchingItems(Submarine submarine, bool mustBelongToPlayerSub, Character.TeamType? requiredTeam = null)
{
List<Item> matchingItems = new List<Item>();
if (submarine == null) { return matchingItems; }
if (ItemComponentType != null || ItemIdentifiers.Length > 0)
if (ItemComponentType != null || TargetItems.Length > 0)
{
matchingItems = ItemIdentifiers.Length > 0 ?
Item.ItemList.FindAll(it => ItemIdentifiers.Contains(it.Prefab.Identifier) || it.HasTag(ItemIdentifiers)) :
Item.ItemList.FindAll(it => it.Components.Any(ic => ic.GetType() == ItemComponentType));
matchingItems = TargetItems.Length > 0 ?
Item.ItemList.FindAll(it => TargetItems.Contains(it.Prefab.Identifier) || it.HasTag(TargetItems)) :
Item.ItemList.FindAll(it => TryGetTargetItemComponent(it, out _));
if (mustBelongToPlayerSub)
{
matchingItems.RemoveAll(it => it.Submarine?.Info != null && it.Submarine.Info.Type != SubmarineType.Player);
@@ -167,7 +167,7 @@ namespace Barotrauma
{
get
{
return Crouching ? CurrentGroundedParams.CrouchingTorsoPos * RagdollParams.JointScale : base.TorsoPosition;
return Crouching && !swimming ? CurrentGroundedParams.CrouchingTorsoPos * RagdollParams.JointScale : base.TorsoPosition;
}
}
@@ -175,7 +175,7 @@ namespace Barotrauma
{
get
{
return Crouching ? CurrentGroundedParams.CrouchingHeadPos * RagdollParams.JointScale : base.HeadPosition;
return Crouching && !swimming ? CurrentGroundedParams.CrouchingHeadPos * RagdollParams.JointScale : base.HeadPosition;
}
}
@@ -183,7 +183,7 @@ namespace Barotrauma
{
get
{
return Crouching ? MathHelper.ToRadians(CurrentGroundedParams.CrouchingTorsoAngle) : base.TorsoAngle;
return Crouching && !swimming ? MathHelper.ToRadians(CurrentGroundedParams.CrouchingTorsoAngle) : base.TorsoAngle;
}
}
@@ -191,7 +191,7 @@ namespace Barotrauma
{
get
{
return Crouching ? MathHelper.ToRadians(CurrentGroundedParams.CrouchingHeadAngle) : base.HeadAngle;
return Crouching && !swimming ? MathHelper.ToRadians(CurrentGroundedParams.CrouchingHeadAngle) : base.HeadAngle;
}
}
@@ -322,11 +322,12 @@ namespace Barotrauma
if (MainLimb == null) { return; }
levitatingCollider = true;
ColliderIndex = Crouching ? 1 : 0;
if (character.SelectedConstruction?.GetComponent<Controller>()?.ControlCharacterPose ?? false)
ColliderIndex = Crouching && !swimming ? 1 : 0;
if (character.SelectedConstruction?.GetComponent<Controller>()?.ControlCharacterPose ?? false ||
(ForceSelectAnimationType != AnimationType.Walk && ForceSelectAnimationType != AnimationType.NotDefined))
{
Crouching = false;
ColliderIndex = 0;
}
else if (!Crouching && ColliderIndex == 1)
{
@@ -1903,7 +1904,7 @@ namespace Barotrauma
{
if (!MathUtils.IsValid(pos))
{
string errorMsg = "Invalid foot position in FootIK (" + pos + ")\n" + Environment.StackTrace;
string errorMsg = "Invalid foot position in FootIK (" + pos + ")\n" + Environment.StackTrace.CleanupStackTrace();
#if DEBUG
DebugConsole.ThrowError(errorMsg);
#endif
@@ -1937,7 +1938,7 @@ namespace Barotrauma
float legAngle = MathUtils.VectorToAngle(pos - waistPos) + MathHelper.PiOver2;
if (!MathUtils.IsValid(legAngle))
{
string errorMsg = "Invalid leg angle (" + legAngle + ") in FootIK. Waist pos: " + waistPos + ", target pos: " + pos + "\n" + Environment.StackTrace;
string errorMsg = "Invalid leg angle (" + legAngle + ") in FootIK. Waist pos: " + waistPos + ", target pos: " + pos + "\n" + Environment.StackTrace.CleanupStackTrace();
#if DEBUG
DebugConsole.ThrowError(errorMsg);
#endif
@@ -60,12 +60,12 @@ namespace Barotrauma
if (!accessRemovedCharacterErrorShown)
{
string errorMsg = "Attempted to access a potentially removed ragdoll. Character: " + character.Name + ", id: " + character.ID + ", removed: " + character.Removed + ", ragdoll removed: " + !list.Contains(this);
errorMsg += '\n' + Environment.StackTrace;
errorMsg += '\n' + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce(
"Ragdoll.Limbs:AccessRemoved",
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Attempted to access a potentially removed ragdoll. Character: " + character.Name + ", id: " + character.ID + ", removed: " + character.Removed + ", ragdoll removed: " + !list.Contains(this) + "\n" + Environment.StackTrace);
"Attempted to access a potentially removed ragdoll. Character: " + character.Name + ", id: " + character.ID + ", removed: " + character.Removed + ", ragdoll removed: " + !list.Contains(this) + "\n" + Environment.StackTrace.CleanupStackTrace());
accessRemovedCharacterErrorShown = true;
}
return new Limb[0];
@@ -768,7 +768,7 @@ namespace Barotrauma
if (!string.IsNullOrEmpty(character.BloodDecalName))
{
character.CurrentHull?.AddDecal(character.BloodDecalName,
(limbJoint.LimbA.WorldPosition + limbJoint.LimbB.WorldPosition) / 2, MathHelper.Clamp(Math.Min(limbJoint.LimbA.Mass, limbJoint.LimbB.Mass), 0.5f, 2.0f), true);
(limbJoint.LimbA.WorldPosition + limbJoint.LimbB.WorldPosition) / 2, MathHelper.Clamp(Math.Min(limbJoint.LimbA.Mass, limbJoint.LimbB.Mass), 0.5f, 2.0f), isNetworkEvent: false);
}
SeverLimbJointProjSpecific(limbJoint, playSound: true);
@@ -905,7 +905,7 @@ namespace Barotrauma
GameAnalyticsManager.AddErrorEventOnce(
"Ragdoll.FindHull:InvalidPosition",
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Attempted to find a hull at an invalid position (" + findPos + ")\n" + Environment.StackTrace);
"Attempted to find a hull at an invalid position (" + findPos + ")\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
@@ -1557,11 +1557,11 @@ namespace Barotrauma
{
if (!MathUtils.IsValid(simPosition))
{
DebugConsole.ThrowError("Attempted to move a ragdoll (" + character.Name + ") to an invalid position (" + simPosition + "). " + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to move a ragdoll (" + character.Name + ") to an invalid position (" + simPosition + "). " + Environment.StackTrace.CleanupStackTrace());
GameAnalyticsManager.AddErrorEventOnce(
"Ragdoll.SetPosition:InvalidPosition",
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Attempted to move a ragdoll (" + character.Name + ") to an invalid position (" + simPosition + "). " + Environment.StackTrace);
"Attempted to move a ragdoll (" + character.Name + ") to an invalid position (" + simPosition + "). " + Environment.StackTrace.CleanupStackTrace());
return;
}
if (MainLimb == null) { return; }
@@ -40,7 +40,11 @@ namespace Barotrauma
struct AttackResult
{
public readonly float Damage;
public float Damage
{
get;
private set;
}
public readonly List<Affliction> Afflictions;
public readonly Limb HitLimb;
@@ -64,9 +68,7 @@ namespace Barotrauma
{
Damage = damage;
HitLimb = null;
Afflictions = null;
AppliedDamageModifiers = appliedDamageModifiers;
}
}
@@ -18,7 +18,7 @@ namespace Barotrauma
{
if (type == CauseOfDeathType.Affliction && affliction == null)
{
string errorMsg = "Invalid cause of death (the type of the cause of death was Affliction, but affliction was not specified).\n" + Environment.StackTrace;
string errorMsg = "Invalid cause of death (the type of the cause of death was Affliction, but affliction was not specified).\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("InvalidCauseOfDeath", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
type = CauseOfDeathType.Unknown;
@@ -137,6 +137,8 @@ namespace Barotrauma
public Character LastAttacker;
public Entity LastDamageSource;
public float InvisibleTimer;
private CharacterPrefab prefab;
public readonly CharacterParams Params;
@@ -181,6 +183,8 @@ namespace Barotrauma
public bool IsTraitor;
public string TraitorCurrentObjective = "";
public bool IsHuman => SpeciesName.Equals(CharacterPrefab.HumanSpeciesName, StringComparison.OrdinalIgnoreCase);
public bool IsMale => Info != null && Info.HasGenders && Info.Gender == Gender.Male;
public bool IsFemale => Info != null && Info.HasGenders && Info.Gender == Gender.Female;
private float attackCoolDown;
@@ -195,6 +199,7 @@ namespace Barotrauma
if (Info != null) { Info.CurrentOrder = value; }
}
}
public string CurrentOrderOption
{
get
@@ -207,6 +212,8 @@ namespace Barotrauma
}
}
public bool IsDismissed => Info != null && Info.IsDismissed;
private readonly List<StatusEffect> statusEffects = new List<StatusEffect>();
private readonly List<float> speedMultipliers = new List<float>();
private float greatestNegativeSpeedMultiplier = 1f;
@@ -563,7 +570,28 @@ namespace Barotrauma
get { return selectedItems; }
}
public Item SelectedConstruction { get; set; }
private Item _selectedConstruction;
public Item SelectedConstruction
{
get => _selectedConstruction;
set
{
_selectedConstruction = value;
#if CLIENT
if (Controlled == this)
{
if (_selectedConstruction == null)
{
GameMain.GameSession?.CrewManager?.ResetCrewList();
}
else if (_selectedConstruction.GetComponent<Ladder>() == null)
{
GameMain.GameSession?.CrewManager?.AutoHideCrewList();
}
}
#endif
}
}
public Item FocusedItem
{
@@ -584,6 +612,8 @@ namespace Barotrauma
public bool IsDead { get; private set; }
public bool IsObserving => AIController is EnemyAIController enemyAI && enemyAI.Enabled && enemyAI.State == AIState.Observe;
public bool EnableDespawn { get; set; } = true;
public CauseOfDeath CauseOfDeath
@@ -662,12 +692,12 @@ namespace Barotrauma
{
errorMsg += " AnimController.Collider == null";
}
errorMsg += '\n' + Environment.StackTrace;
errorMsg += '\n' + Environment.StackTrace.CleanupStackTrace();
DebugConsole.NewMessage(errorMsg, Color.Red);
GameAnalyticsManager.AddErrorEventOnce(
"Character.SimPosition:AccessRemoved",
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
errorMsg + "\n" + Environment.StackTrace);
errorMsg + "\n" + Environment.StackTrace.CleanupStackTrace());
accessRemovedCharacterErrorShown = true;
}
return Vector2.Zero;
@@ -1780,7 +1810,6 @@ namespace Barotrauma
if (ignoreBroken && item.Condition <= 0) { continue; }
if (Submarine != null)
{
if (item.Submarine.Info.Type != Submarine.Info.Type) { continue; }
if (!Submarine.IsEntityFoundOnThisSub(item, true)) { continue; }
}
if (customPredicate != null && !customPredicate(item)) { continue; }
@@ -1813,7 +1842,7 @@ namespace Barotrauma
public bool CanInteractWith(Character c, float maxDist = 200.0f, bool checkVisibility = true, bool skipDistanceCheck = false)
{
if (c == this || Removed || !c.Enabled || !c.CanBeSelected) { return false; }
if (c == this || Removed || !c.Enabled || !c.CanBeSelected || c.InvisibleTimer > 0.0f) { return false; }
if (!c.CharacterHealth.UseHealthWindow && !c.CanBeDragged && (c.onCustomInteract == null || !c.AllowCustomInteract)) { return false; }
if (!skipDistanceCheck)
@@ -2654,7 +2683,7 @@ namespace Barotrauma
if (orderGiver != null && !CanHearCharacter(orderGiver)) { return; }
// If there's another character operating the same device, make them dismiss themself
if (order != null && order.Category == OrderCategory.Operate)
if (order != null && order.Category == OrderCategory.Operate && order.TargetEntity != null)
{
CharacterList.FindAll(c => c != this && c.TeamID == TeamID && c.CurrentOrder is Order characterOrder && characterOrder.Category == OrderCategory.Operate &&
characterOrder.Identifier.Equals(order.Identifier) && characterOrder.TargetEntity == order.TargetEntity)?
@@ -2794,7 +2823,7 @@ namespace Barotrauma
{
if (Removed)
{
string errorMsg = "Tried to apply an attack to a removed character (" + Name + ").\n" + Environment.StackTrace;
string errorMsg = "Tried to apply an attack to a removed character (" + Name + ").\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("Character.ApplyAttack:RemovedCharacter", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return new AttackResult();
@@ -2937,7 +2966,7 @@ namespace Barotrauma
// string errorMsg = $"Character {Name} received damage from outside the sub while inside (attacker: {attacker.Name})";
// GameAnalyticsManager.AddErrorEventOnce("Character.DamageLimb:DamageFromOutside" + Name + attacker.Name,
// GameAnalyticsSDK.Net.EGAErrorSeverity.Warning,
// errorMsg + "\n" + Environment.StackTrace);
// errorMsg + "\n" + Environment.StackTrace.CleanupStackTrace());
//#if DEBUG
// DebugConsole.ThrowError(errorMsg);
//#endif
@@ -2968,11 +2997,6 @@ namespace Barotrauma
Vector2 simPos = hitLimb.SimPosition + ConvertUnits.ToSimUnits(dir);
AttackResult attackResult = hitLimb.AddDamage(simPos, afflictions, playSound);
CharacterHealth.ApplyDamage(hitLimb, attackResult);
ApplyStatusEffects(ActionType.OnDamaged, 1.0f);
if (attackResult.Damage > 0)
{
hitLimb.ApplyStatusEffects(ActionType.OnDamaged, 1.0f);
}
if (attacker != this)
{
OnAttacked?.Invoke(attacker, attackResult);
@@ -2982,12 +3006,15 @@ namespace Barotrauma
TryAdjustAttackerSkill(attacker, -attackResult.Damage);
}
};
if (attacker != null && attackResult.Damage > 0.0f)
if (attackResult.Damage > 0)
{
LastAttacker = attacker;
ApplyStatusEffects(ActionType.OnDamaged, 1.0f);
hitLimb.ApplyStatusEffects(ActionType.OnDamaged, 1.0f);
if (attacker != null)
{
LastAttacker = attacker;
}
}
return attackResult;
}
@@ -3045,7 +3072,7 @@ namespace Barotrauma
{
targets.Clear();
statusEffect.GetNearbyTargets(WorldPosition, targets);
statusEffect.Apply(ActionType.OnActive, deltaTime, this, targets);
statusEffect.Apply(actionType, deltaTime, this, targets);
}
else
{
@@ -3215,7 +3242,7 @@ namespace Barotrauma
{
if (Removed)
{
DebugConsole.ThrowError("Attempting to revive an already removed character\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempting to revive an already removed character\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
@@ -3260,7 +3287,7 @@ namespace Barotrauma
{
if (Removed)
{
DebugConsole.ThrowError("Attempting to remove an already removed character\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempting to remove an already removed character\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
DebugConsole.Log("Removing character " + Name + " (ID: " + ID + ")");
@@ -300,6 +300,7 @@ namespace Barotrauma
public Order CurrentOrder { get; set; }
public string CurrentOrderOption { get; set; }
public bool IsDismissed => CurrentOrder == null || CurrentOrder.Identifier.Equals("dismissed", StringComparison.OrdinalIgnoreCase);
//unique ID given to character infos in MP
//used by clients to identify which infos are the same to prevent duplicate characters in round summary
@@ -37,7 +37,7 @@ namespace Barotrauma
public string Identifier { get; private set; }
[Serialize(1.0f, true, description: "The probability for the affliction to be applied."), Editable(minValue: 0f, maxValue: 1f)]
public float Probability { get; private set; } = 1.0f;
public float Probability { get; set; } = 1.0f;
public float DamagePerSecond;
public float DamagePerSecondTimer;
@@ -264,5 +264,10 @@ namespace Barotrauma
/// Ideally we would keep this private, but doing so would require too much refactoring.
/// </summary>
public void SetStrength(float strength) => _strength = strength;
public bool ShouldShowIcon(Character afflictedCharacter)
{
return Strength >= (afflictedCharacter == Character.Controlled ? Prefab.ShowIconThreshold : Prefab.ShowIconToOthersThreshold);
}
}
}
@@ -273,6 +273,8 @@ namespace Barotrauma
public readonly float ActivationThreshold = 0.0f;
//how high the strength has to be for the affliction icon to be shown in the UI
public readonly float ShowIconThreshold = 0.05f;
//how high the strength has to be for the affliction icon to be shown to others with a health scanner or via the health interface
public readonly float ShowIconToOthersThreshold = 0.05f;
public readonly float MaxStrength = 100.0f;
//how high the strength has to be for the affliction icon to be shown with a health scanner
@@ -555,6 +557,7 @@ namespace Barotrauma
ActivationThreshold = element.GetAttributeFloat("activationthreshold", 0.0f);
ShowIconThreshold = element.GetAttributeFloat("showiconthreshold", Math.Max(ActivationThreshold, 0.05f));
ShowIconToOthersThreshold = element.GetAttributeFloat("showicontoothersthreshold", ShowIconThreshold);
MaxStrength = element.GetAttributeFloat("maxstrength", 100.0f);
ShowInHealthScannerThreshold = element.GetAttributeFloat("showinhealthscannerthreshold", Math.Max(ActivationThreshold, 0.05f));
@@ -1,12 +1,4 @@
using Microsoft.Xna.Framework;
using System.Collections.Generic;
using Barotrauma.IO;
using System.Linq;
using Barotrauma.Extensions;
using System.Xml.Linq;
using System;
namespace Barotrauma
namespace Barotrauma
{
partial class AfflictionPsychosis : Affliction
{
@@ -725,10 +725,10 @@ namespace Barotrauma
OxygenAmount = MathHelper.Clamp(OxygenAmount + deltaTime * (Character.OxygenAvailable < InsufficientOxygenThreshold ? -5.0f : 10.0f), -100.0f, 100.0f);
}
UpdateOxygenProjSpecific(prevOxygen);
UpdateOxygenProjSpecific(prevOxygen, deltaTime);
}
partial void UpdateOxygenProjSpecific(float prevOxygen);
partial void UpdateOxygenProjSpecific(float prevOxygen, float deltaTime);
partial void UpdateBleedingProjSpecific(AfflictionBleeding affliction, Limb targetLimb, float deltaTime);
@@ -203,7 +203,7 @@ namespace Barotrauma
partial class Limb : ISerializableEntity, ISpatialEntity
{
//how long it takes for severed limbs to fade out
private const float SeveredFadeOutTime = 10.0f;
public float SeveredFadeOutTime => Params.SeveredFadeOutTime;
public readonly Character character;
/// <summary>
@@ -327,10 +327,10 @@ namespace Barotrauma
if (Removed)
{
#if DEBUG
DebugConsole.ThrowError("Attempted to access a removed limb.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to access a removed limb.\n" + Environment.StackTrace.CleanupStackTrace());
#endif
GameAnalyticsManager.AddErrorEventOnce("Limb.LinearVelocity:SimPosition", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Attempted to access a removed limb.\n" + Environment.StackTrace);
"Attempted to access a removed limb.\n" + Environment.StackTrace.CleanupStackTrace());
return Vector2.Zero;
}
return body.SimPosition;
@@ -344,10 +344,10 @@ namespace Barotrauma
if (Removed)
{
#if DEBUG
DebugConsole.ThrowError("Attempted to access a removed limb.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to access a removed limb.\n" + Environment.StackTrace.CleanupStackTrace());
#endif
GameAnalyticsManager.AddErrorEventOnce("Limb.LinearVelocity:SimPosition", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Attempted to access a removed limb.\n" + Environment.StackTrace);
"Attempted to access a removed limb.\n" + Environment.StackTrace.CleanupStackTrace());
return 0.0f;
}
return body.Rotation;
@@ -364,10 +364,10 @@ namespace Barotrauma
if (Removed)
{
#if DEBUG
DebugConsole.ThrowError("Attempted to access a removed limb.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to access a removed limb.\n" + Environment.StackTrace.CleanupStackTrace());
#endif
GameAnalyticsManager.AddErrorEventOnce("Limb.Mass:AccessRemoved", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Attempted to access a removed limb.\n" + Environment.StackTrace);
"Attempted to access a removed limb.\n" + Environment.StackTrace.CleanupStackTrace());
return 1.0f;
}
return body.Mass;
@@ -383,10 +383,10 @@ namespace Barotrauma
if (Removed)
{
#if DEBUG
DebugConsole.ThrowError("Attempted to access a removed limb.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to access a removed limb.\n" + Environment.StackTrace.CleanupStackTrace());
#endif
GameAnalyticsManager.AddErrorEventOnce("Limb.LinearVelocity:AccessRemoved", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Attempted to access a removed limb.\n" + Environment.StackTrace);
"Attempted to access a removed limb.\n" + Environment.StackTrace.CleanupStackTrace());
return Vector2.Zero;
}
return body.LinearVelocity;
@@ -428,7 +428,7 @@ namespace Barotrauma
{
if (!MathUtils.IsValid(value))
{
string errorMsg = "Attempted to set the anchor A of a limb's pull joint to an invalid value (" + value + ")\n" + Environment.StackTrace;
string errorMsg = "Attempted to set the anchor A of a limb's pull joint to an invalid value (" + value + ")\n" + Environment.StackTrace.CleanupStackTrace();
GameAnalyticsManager.AddErrorEventOnce("Limb.SetPullJointAnchorA:InvalidValue", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
#if DEBUG
DebugConsole.ThrowError(errorMsg);
@@ -442,7 +442,7 @@ namespace Barotrauma
string errorMsg = "Attempted to move the anchor A of a limb's pull joint extremely far from the limb (diff: " + diff +
", limb enabled: " + body.Enabled +
", simple physics enabled: " + character.AnimController.SimplePhysicsEnabled + ")\n"
+ Environment.StackTrace;
+ Environment.StackTrace.CleanupStackTrace();
GameAnalyticsManager.AddErrorEventOnce("Limb.SetPullJointAnchorA:ExcessiveValue", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
#if DEBUG
DebugConsole.ThrowError(errorMsg);
@@ -461,7 +461,7 @@ namespace Barotrauma
{
if (!MathUtils.IsValid(value))
{
string errorMsg = "Attempted to set the anchor B of a limb's pull joint to an invalid value (" + value + ")\n" + Environment.StackTrace;
string errorMsg = "Attempted to set the anchor B of a limb's pull joint to an invalid value (" + value + ")\n" + Environment.StackTrace.CleanupStackTrace();
GameAnalyticsManager.AddErrorEventOnce("Limb.SetPullJointAnchorB:InvalidValue", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
#if DEBUG
DebugConsole.ThrowError(errorMsg);
@@ -475,7 +475,7 @@ namespace Barotrauma
string errorMsg = "Attempted to move the anchor B of a limb's pull joint extremely far from the limb (diff: " + diff +
", limb enabled: " + body.Enabled +
", simple physics enabled: " + character.AnimController.SimplePhysicsEnabled + ")\n"
+ Environment.StackTrace;
+ Environment.StackTrace.CleanupStackTrace();
GameAnalyticsManager.AddErrorEventOnce("Limb.SetPullJointAnchorB:ExcessiveValue", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
#if DEBUG
DebugConsole.ThrowError(errorMsg);
@@ -715,7 +715,7 @@ namespace Barotrauma
float bloodDecalSize = MathHelper.Clamp(bleedingDamage / 5, 0.1f, 1.0f);
if (character.CurrentHull != null && !string.IsNullOrEmpty(character.BloodDecalName))
{
character.CurrentHull.AddDecal(character.BloodDecalName, WorldPosition, MathHelper.Clamp(bloodDecalSize, 0.5f, 1.0f), true);
character.CurrentHull.AddDecal(character.BloodDecalName, WorldPosition, MathHelper.Clamp(bloodDecalSize, 0.5f, 1.0f), isNetworkEvent: false);
}
}
}
@@ -571,12 +571,15 @@ namespace Barotrauma
[Serialize(0f, true, description: "What base priority is given to the target?"), Editable(minValue: 0f, maxValue: 1000f, ValueStep = 1, DecimalCount = 0)]
public float Priority { get; set; }
[Serialize(0f, true, description: "Generic distance that can be used for different purposes depending on the state. Eg. in Avoid state this defines the distance that the character tries to keep to the target. If the distance is 0, it's not used."), Editable(MinValueFloat = 0, ValueStep = 10, DecimalCount = 0)]
[Serialize(0f, true, description: "Generic distance that can be used for different purposes depending on the state. E.g. in Avoid state this defines the distance that the character tries to keep to the target. If the distance is 0, it's not used."), Editable(MinValueFloat = 0, ValueStep = 10, DecimalCount = 0)]
public float ReactDistance { get; set; }
[Serialize(0f, true, description: "Used for defining the attack distance for PassiveAggressive and Aggressive states. If the distance is 0, it's not used."), Editable(MinValueFloat = 0, ValueStep = 10, DecimalCount = 0)]
public float AttackDistance { get; set; }
[Serialize(0f, true, description: "Generic timer that can be used for different purposes depending on the state. E.g. in Observe state this defines how long the character in general keeps staring the targets (Some random is always applied)."), Editable]
public float Timer { get; set; }
public TargetParams(XElement element, CharacterParams character) : base(element, character) { }
public TargetParams(string tag, AIState state, float priority, CharacterParams character) : base(CreateNewElement(tag, state, priority), character) { }
@@ -464,7 +464,7 @@ namespace Barotrauma
/// <summary>
/// Should be converted to sim units.
/// </summary>
[Serialize("1.0, 1.0", true, description: "Local position of the join in the Limb2."), Editable()]
[Serialize("1.0, 1.0", true, description: "Local position of the joint in the Limb2."), Editable()]
public Vector2 Limb2Anchor { get; set; }
[Serialize(true, true), Editable]
@@ -500,6 +500,9 @@ namespace Barotrauma
[Serialize(false, false), Editable(ReadOnly = true)]
public bool WeldJoint { get; set; }
[Serialize(false, true), Editable]
public bool ClockWiseRotation { get; set; }
public JointParams(XElement element, RagdollParams ragdoll) : base(element, ragdoll) { }
}
@@ -617,6 +620,10 @@ namespace Barotrauma
[Serialize(1f, true, description:"How much damage must be done by the attack in order to be able to cut off the limb. Note that it's evaluated after the damage modifiers."), Editable(DecimalCount = 0, MinValueFloat = 0, MaxValueFloat = 1000)]
public float MinSeveranceDamage { get; set; }
//how long it takes for severed limbs to fade out
[Serialize(10f, true, "How long it takes for the severed limb to fade out"), Editable(MinValueFloat = 0, MaxValueFloat = 100, ValueStep = 1)]
public float SeveredFadeOutTime { get; set; } = 10.0f;
// Non-editable ->
// TODO: make read-only
[Serialize(0, true)]
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Barotrauma.Extensions;
using Barotrauma.Items.Components;
using Microsoft.Xna.Framework;
namespace Barotrauma
{
/// <summary>
/// Implementation of the Command pattern.
/// <see href="https://en.wikipedia.org/wiki/Command_pattern"/>
/// </summary>
/// <remarks>
/// Created by Markus Isberg on 11th of March 2020 for the submarine editor.
/// "Implementing a global undo and redo with Memento pattern proved too difficult of a task for me so I implemented it with this pattern instead."
/// </remarks>
internal abstract partial class Command
{
/// <summary>
/// A method that should apply a new state on an object or perform an action
/// </summary>
public abstract void Execute();
/// <summary>
/// A method that should revert Execute() method's actions
/// </summary>
public abstract void UnExecute();
/// <summary>
/// State no longer exists, clean up the lingering garbage
/// </summary>
public abstract void Cleanup();
}
}
@@ -543,9 +543,6 @@ namespace Barotrauma
if (SteamWorkshopId != 0)
{
doc.Root.Add(new XAttribute("steamworkshopid", SteamWorkshopId.ToString()));
#if UNSTABLE
doc.Root.Add(new XAttribute("steamworkshopurl", $"http://steamcommunity.com/sharedfiles/filedetails/?source=Facepunch.Steamworks&id={SteamWorkshopId}"));
#endif
}
if (InstallTime != null)
@@ -230,7 +230,7 @@ namespace Barotrauma
#if CLIENT && WINDOWS
if (e is SharpDX.SharpDXException) { throw; }
#endif
DebugConsole.ThrowError("Coroutine " + handle.Name + " threw an exception: " + e.Message + "\n" + e.StackTrace.ToString());
DebugConsole.ThrowError("Coroutine " + handle.Name + " threw an exception: " + e.Message + "\n" + e.StackTrace.CleanupStackTrace());
handle.Exception = e;
return true;
}
@@ -230,7 +230,7 @@ namespace Barotrauma
{
string errorMsg = "Failed to spawn an item. Arguments: \"" + string.Join(" ", args) + "\".";
ThrowError(errorMsg, e);
GameAnalyticsManager.AddErrorEventOnce("DebugConsole.SpawnItem:Error", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg + '\n' + e.Message + '\n' + e.StackTrace);
GameAnalyticsManager.AddErrorEventOnce("DebugConsole.SpawnItem:Error", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg + '\n' + e.Message + '\n' + e.StackTrace.CleanupStackTrace());
}
},
() =>
@@ -1019,7 +1019,7 @@ namespace Barotrauma
}
catch (InvalidOperationException e)
{
string errorMsg = "Error while executing the fixhulls command.\n" + e.StackTrace;
string errorMsg = "Error while executing the fixhulls command.\n" + e.StackTrace.CleanupStackTrace();
GameAnalyticsManager.AddErrorEventOnce("DebugConsole.FixHulls", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
}
}
@@ -1899,15 +1899,15 @@ namespace Barotrauma
{
if (e != null)
{
error += " {" + e.Message + "}\n" + e.StackTrace;
error += " {" + e.Message + "}\n" + e.StackTrace.CleanupStackTrace();
if (e.InnerException != null)
{
error += "\n\nInner exception: " + e.InnerException.Message + "\n" + e.InnerException.StackTrace;
error += "\n\nInner exception: " + e.InnerException.Message + "\n" + e.InnerException.StackTrace.CleanupStackTrace();
}
}
else if (appendStackTrace)
{
error += "\n" + Environment.StackTrace;
error += "\n" + Environment.StackTrace.CleanupStackTrace();
}
System.Diagnostics.Debug.WriteLine(error);
@@ -34,11 +34,11 @@ namespace Barotrauma
get { return Prefab.LifeTime; }
}
private float baseAlpha = 1.0f;
public float BaseAlpha
{
get { return baseAlpha; }
}
get;
set;
} = 1.0f;
public Color Color
{
@@ -58,9 +58,10 @@ namespace Barotrauma
}
}
public Vector2 Position
public Vector2 CenterPosition
{
get { return position; }
get;
private set;
}
public Vector2 NonClampedPosition
@@ -69,6 +70,12 @@ namespace Barotrauma
private set;
}
public int SpriteIndex
{
get;
private set;
}
private readonly HashSet<BackgroundSection> affectedSections;
private readonly Hull hull;
@@ -79,7 +86,7 @@ namespace Barotrauma
private bool cleaned = false;
public Decal(DecalPrefab prefab, float scale, Vector2 worldPosition, Hull hull)
public Decal(DecalPrefab prefab, float scale, Vector2 worldPosition, Hull hull, int? spriteIndex = null)
{
Prefab = prefab;
@@ -90,7 +97,8 @@ namespace Barotrauma
Vector2 drawPos = position + hull.Rect.Location.ToVector2();
Sprite = prefab.Sprites[Rand.Range(0, prefab.Sprites.Count, Rand.RandSync.Unsynced)];
SpriteIndex = spriteIndex ?? Rand.Range(0, prefab.Sprites.Count, Rand.RandSync.Unsynced);
Sprite = prefab.Sprites[SpriteIndex];
Color = prefab.Color;
Rectangle drawRect = new Rectangle(
@@ -111,6 +119,8 @@ namespace Barotrauma
Sprite.SourceRect.Width - (int)((overFlowAmount.X + overFlowAmount.Width) / scale),
Sprite.SourceRect.Height - (int)((overFlowAmount.Y + overFlowAmount.Height) / scale));
CenterPosition = position;
position -= new Vector2(Sprite.size.X / 2 * scale - overFlowAmount.X, -Sprite.size.Y / 2 * scale + overFlowAmount.Y);
this.Scale = scale;
@@ -148,20 +158,20 @@ namespace Barotrauma
{
cleaned = true;
float sizeModifier = MathHelper.Clamp(Sprite.size.X * Sprite.size.Y * Scale / 10000, 1.0f, 25.0f);
baseAlpha -= val * -1 / sizeModifier;
BaseAlpha -= val * -1 / sizeModifier;
}
private float GetAlpha()
{
if (fadeTimer < Prefab.FadeInTime && !cleaned)
{
return baseAlpha * fadeTimer / Prefab.FadeInTime;
return BaseAlpha * fadeTimer / Prefab.FadeInTime;
}
else if (cleaned || fadeTimer > Prefab.LifeTime - Prefab.FadeOutTime)
{
return baseAlpha * Math.Min((Prefab.LifeTime - fadeTimer) / Prefab.FadeOutTime, 1.0f);
return BaseAlpha * Math.Min((Prefab.LifeTime - fadeTimer) / Prefab.FadeOutTime, 1.0f);
}
return baseAlpha;
return BaseAlpha;
}
}
}
@@ -108,7 +108,7 @@ namespace Barotrauma
}
}
public Decal CreateDecal(string decalName, float scale, Vector2 worldPosition, Hull hull)
public Decal CreateDecal(string decalName, float scale, Vector2 worldPosition, Hull hull, int? spriteIndex = null)
{
if (!Prefabs.ContainsKey(decalName.ToLowerInvariant()))
{
@@ -118,7 +118,7 @@ namespace Barotrauma
DecalPrefab prefab = Prefabs[decalName];
return new Decal(prefab, scale, worldPosition, hull);
return new Decal(prefab, scale, worldPosition, hull, spriteIndex);
}
}
}
@@ -21,6 +21,7 @@
OnDeath = OnBroken,
OnDamaged,
OnSevered,
OnProduceSpawned
OnProduceSpawned,
OnOpen, OnClose,
}
}
@@ -63,6 +63,16 @@ namespace Barotrauma
{
return $"({value.X.FormatSingleDecimal()}, {value.Y.FormatSingleDecimal()})";
}
public static string FormatSingleDecimal(this Vector3 value)
{
return $"({value.X.FormatSingleDecimal()}, {value.Y.FormatSingleDecimal()}, {value.Z.FormatSingleDecimal()})";
}
public static string FormatSingleDecimal(this Vector4 value)
{
return $"({value.X.FormatSingleDecimal()}, {value.Y.FormatSingleDecimal()}, {value.Z.FormatSingleDecimal()}, {value.W.FormatSingleDecimal()})";
}
public static string FormatDoubleDecimal(this Vector2 value)
{
@@ -0,0 +1,60 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Barotrauma
{
static class ForbiddenWordFilter
{
static readonly string fileListPath = Path.Combine("Data", "forbiddenwordlist.txt");
private static readonly HashSet<string> forbiddenWords;
static ForbiddenWordFilter()
{
try
{
forbiddenWords = File.ReadAllLines(fileListPath).ToHashSet();
}
catch (IOException e)
{
DebugConsole.ThrowError($"Failed to load the list of forbidden words from {fileListPath}.", e);
}
}
public static bool IsForbidden(string text)
{
return IsForbidden(text, out _);
}
public static bool IsForbidden(string text, out string forbiddenWord)
{
forbiddenWord = string.Empty;
if (forbiddenWords == null)
{
return false;
}
char[] delimiters = new char[] { ' ', '-', '.', '_', ':', ';', '\'' };
HashSet<string> words = new HashSet<string>();
foreach (char delimiter in delimiters)
{
foreach (string word in text.Split(delimiter))
{
words.Add(word);
}
}
foreach (string word in words)
{
if (forbiddenWords.Any(w => Homoglyphs.Compare(word, w) || Homoglyphs.Compare(word + 's', w)))
{
forbiddenWord = word;
return true;
}
}
return false;
}
}
}
@@ -44,7 +44,7 @@ namespace Barotrauma
{
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
{
DebugConsole.ThrowError("Clients are not allowed to use AutoItemPlacer.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Clients are not allowed to use AutoItemPlacer.\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
@@ -135,7 +135,7 @@ namespace Barotrauma
{
if (itemPrefab == null)
{
string errorMsg = "Error in AutoItemPlacer.SpawnItems - itemPrefab was null.\n"+Environment.StackTrace;
string errorMsg = "Error in AutoItemPlacer.SpawnItems - itemPrefab was null.\n"+Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("AutoItemPlacer.SpawnItems:ItemNull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return false;
@@ -14,6 +14,8 @@ namespace Barotrauma
private float conversationTimer, conversationLineTimer;
private readonly List<Pair<Character, string>> pendingConversationLines = new List<Pair<Character, string>>();
public const int MaxCrewSize = 16;
private readonly List<CharacterInfo> characterInfos = new List<CharacterInfo>();
private readonly List<Character> characters = new List<Character>();
@@ -40,7 +42,7 @@ namespace Barotrauma
{
if (order.TargetEntity == null)
{
DebugConsole.ThrowError("Attempted to add an order with no target entity to CrewManager!\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempted to add an order with no target entity to CrewManager!\n" + Environment.StackTrace.CleanupStackTrace());
return false;
}
@@ -95,12 +97,12 @@ namespace Barotrauma
{
if (character.Removed)
{
DebugConsole.ThrowError("Tried to add a removed character to CrewManager!\n" + Environment.StackTrace);
DebugConsole.ThrowError("Tried to add a removed character to CrewManager!\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
if (character.IsDead)
{
DebugConsole.ThrowError("Tried to add a dead character to CrewManager!\n" + Environment.StackTrace);
DebugConsole.ThrowError("Tried to add a dead character to CrewManager!\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
@@ -122,7 +124,7 @@ namespace Barotrauma
{
if (characterInfos.Contains(characterInfo))
{
DebugConsole.ThrowError("Tried to add the same character info to CrewManager twice.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Tried to add the same character info to CrewManager twice.\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
@@ -31,6 +31,7 @@ namespace Barotrauma
get => Math.Min(MaxReputation, Metadata.GetFloat(metaDataIdentifier, InitialReputation));
set
{
if (MathUtils.NearlyEqual(Value, value)) { return; }
Metadata.SetValue(metaDataIdentifier, Math.Clamp(value, MinReputation, MaxReputation));
OnReputationValueChanged?.Invoke();
OnAnyReputationValueChanged?.Invoke();
@@ -188,7 +188,7 @@ namespace Barotrauma
if (CoroutineManager.IsCoroutineRunning("LevelTransition"))
{
DebugConsole.ThrowError("Level transition already running.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Level transition already running.\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
@@ -208,7 +208,7 @@ namespace Barotrauma
"leaving sub: " + (leavingSub?.Info?.Name ?? "null") + ", " +
"at start: " + (leavingSub?.AtStartPosition.ToString() ?? "null") + ", " +
"at end: " + (leavingSub?.AtEndPosition.ToString() ?? "null") + ")\n" +
Environment.StackTrace);
Environment.StackTrace.CleanupStackTrace());
return;
}
if (nextLevel == null)
@@ -220,7 +220,7 @@ namespace Barotrauma
"leaving sub: " + (leavingSub?.Info?.Name ?? "null") + ", " +
"at start: " + (leavingSub?.AtStartPosition.ToString() ?? "null") + ", " +
"at end: " + (leavingSub?.AtEndPosition.ToString() ?? "null") + ")\n" +
Environment.StackTrace);
Environment.StackTrace.CleanupStackTrace());
return;
}
#if CLIENT
@@ -348,6 +348,8 @@ namespace Barotrauma
GUI.AddMessage(TextManager.AddPunctuation(':', TextManager.Get("Location"), StartLocation.Name), Color.CadetBlue, playSound: false);
}
}
GUI.PreventPauseMenuToggle = false;
#endif
}
@@ -542,6 +544,12 @@ namespace Barotrauma
Mission == null ? "None" : Mission.GetType().ToString());
#if CLIENT
if (GUI.PauseMenuOpen)
{
GUI.TogglePauseMenu();
}
GUI.PreventPauseMenuToggle = true;
if (!(GameMode is TestGameMode) && Screen.Selected == GameMain.GameScreen && RoundSummary != null)
{
GUI.ClearMessages();
@@ -262,7 +262,7 @@ namespace Barotrauma
lastErrorSpeak = DateTime.Now;
}
#if CLIENT
GUI.PlayUISound(GUISoundType.PickItemFail);
SoundPlayer.PlayUISound(GUISoundType.PickItemFail);
#endif
}
@@ -730,6 +730,7 @@ namespace Barotrauma
public static bool EnableSubmarineAutoSave { get; set; }
public static int MaximumAutoSaves { get; set; }
public static Color SubEditorBackgroundColor { get; set; }
public static int SubEditorMaxUndoBuffer { get; set; }
public bool ShowTutorialSkipWarning
{
@@ -898,6 +899,7 @@ namespace Barotrauma
new XAttribute("submarineautosave", EnableSubmarineAutoSave),
new XAttribute("maxautosaves", MaximumAutoSaves),
new XAttribute("subeditorbackground", XMLExtensions.ColorToString(SubEditorBackgroundColor)),
new XAttribute("subeditorundobuffer", SubEditorMaxUndoBuffer),
new XAttribute("enablesplashscreen", EnableSplashScreen),
new XAttribute("usesteammatchmaking", UseSteamMatchmaking),
new XAttribute("quickstartsub", QuickStartSubmarineName),
@@ -1033,7 +1035,7 @@ namespace Barotrauma
{
DebugConsole.ThrowError("Saving game settings failed.", e);
GameAnalyticsManager.AddErrorEventOnce("GameSettings.Save:SaveFailed", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Saving game settings failed.\n" + e.Message + "\n" + e.StackTrace);
"Saving game settings failed.\n" + e.Message + "\n" + e.StackTrace.CleanupStackTrace());
}
}
@@ -1119,6 +1121,7 @@ namespace Barotrauma
new XAttribute("verboselogging", VerboseLogging),
new XAttribute("savedebugconsolelogs", SaveDebugConsoleLogs),
new XAttribute("submarineautosave", EnableSubmarineAutoSave),
new XAttribute("subeditorundobuffer", SubEditorMaxUndoBuffer),
new XAttribute("maxautosaves", MaximumAutoSaves),
new XAttribute("subeditorbackground", XMLExtensions.ColorToString(SubEditorBackgroundColor)),
new XAttribute("enablesplashscreen", EnableSplashScreen),
@@ -1232,17 +1235,6 @@ namespace Barotrauma
doc.Root.Add(contentPackagesElement);
#if UNSTABLE
//TODO: remove at some point
foreach (ContentPackage package in AllEnabledPackages)
{
XElement compatibilityElement = new XElement("contentpackage");
compatibilityElement.Add(new XAttribute("path", package.Path));
doc.Root.Add(compatibilityElement);
}
#endif
#if CLIENT
var keyMappingElement = new XElement("keymapping");
doc.Root.Add(keyMappingElement);
@@ -1337,7 +1329,7 @@ namespace Barotrauma
{
DebugConsole.ThrowError("Saving game settings failed.", e);
GameAnalyticsManager.AddErrorEventOnce("GameSettings.Save:SaveFailed", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Saving game settings failed.\n" + e.Message + "\n" + e.StackTrace);
"Saving game settings failed.\n" + e.Message + "\n" + e.StackTrace.CleanupStackTrace());
}
}
#endregion
@@ -1355,6 +1347,7 @@ namespace Barotrauma
EnableSubmarineAutoSave = doc.Root.GetAttributeBool("submarineautosave", true);
MaximumAutoSaves = doc.Root.GetAttributeInt("maxautosaves", 8);
SubEditorBackgroundColor = doc.Root.GetAttributeColor("subeditorbackground", new Color(0.051f, 0.149f, 0.271f, 1.0f));
SubEditorMaxUndoBuffer = doc.Root.GetAttributeInt("subeditorundobuffer", 32);
UseSteamMatchmaking = doc.Root.GetAttributeBool("usesteammatchmaking", UseSteamMatchmaking);
RequireSteamAuthentication = doc.Root.GetAttributeBool("requiresteamauthentication", RequireSteamAuthentication);
EnableSplashScreen = doc.Root.GetAttributeBool("enablesplashscreen", EnableSplashScreen);
@@ -1,6 +1,4 @@
using Barotrauma.Items.Components;
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -11,7 +9,7 @@ namespace Barotrauma
[Flags]
public enum InvSlotType
{
None = 0, Any = 1, RightHand = 2, LeftHand = 4, Head = 8, InnerClothes = 16, OuterClothes = 32, Headset = 64, Card = 128
None = 0, Any = 1, RightHand = 2, LeftHand = 4, Head = 8, InnerClothes = 16, OuterClothes = 32, Headset = 64, Card = 128, Bag = 256
};
partial class CharacterInventory : Inventory
@@ -24,6 +22,9 @@ namespace Barotrauma
private set;
}
public static readonly List<InvSlotType> anySlot = new List<InvSlotType>() { InvSlotType.Any };
protected bool[] IsEquipped;
public bool AccessibleWhenAlive
@@ -68,7 +69,7 @@ namespace Barotrauma
#if CLIENT
//clients don't create items until the server says so
if (GameMain.Client != null) return;
if (GameMain.Client != null) { return; }
#endif
foreach (XElement subElement in element.Elements())
@@ -76,8 +77,7 @@ namespace Barotrauma
if (!subElement.Name.ToString().Equals("item", StringComparison.OrdinalIgnoreCase)) { continue; }
string itemIdentifier = subElement.GetAttributeString("identifier", "");
ItemPrefab itemPrefab = MapEntityPrefab.Find(null, itemIdentifier) as ItemPrefab;
if (itemPrefab == null)
if (!(MapEntityPrefab.Find(null, itemIdentifier) is ItemPrefab itemPrefab))
{
DebugConsole.ThrowError("Error in character inventory \"" + character.SpeciesName + "\" - item \"" + itemIdentifier + "\" not found.");
continue;
@@ -164,7 +164,7 @@ namespace Barotrauma
#if DEBUG
throw new Exception("Tried to put a removed item (" + item.Name + ") in an inventory");
#else
DebugConsole.ThrowError("Tried to put a removed item (" + item.Name + ") in an inventory.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Tried to put a removed item (" + item.Name + ") in an inventory.\n" + Environment.StackTrace.CleanupStackTrace());
return false;
#endif
}
@@ -284,7 +284,7 @@ namespace Barotrauma
{
if (index < 0 || index >= Items.Length)
{
string errorMsg = "CharacterInventory.TryPutItem failed: index was out of range(" + index + ").\n" + Environment.StackTrace;
string errorMsg = "CharacterInventory.TryPutItem failed: index was out of range(" + index + ").\n" + Environment.StackTrace.CleanupStackTrace();
GameAnalyticsManager.AddErrorEventOnce("CharacterInventory.TryPutItem:IndexOutOfRange", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return false;
}
@@ -431,7 +431,7 @@ namespace Barotrauma.Items.Components
string errorMsg =
"Attempted to create a door body at an invalid position (item pos: " + item.Position
+ ", item world pos: " + item.WorldPosition
+ ", docking target world pos: " + DockingTarget.Door.Item.WorldPosition + ")\n" + Environment.StackTrace;
+ ", docking target world pos: " + DockingTarget.Door.Item.WorldPosition + ")\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce(
@@ -377,6 +377,8 @@ namespace Barotrauma.Items.Components
private int flowerVariants;
private int leafVariants;
private int[] flowerTiles;
private const int serverHealthUpdateDelay = 10;
private int serverHealthUpdateTimer;
public float Health
{
@@ -469,6 +471,20 @@ namespace Barotrauma.Items.Components
{
Health -= FloodTolerance;
}
#if SERVER
if (FullyGrown)
{
if (serverHealthUpdateTimer > serverHealthUpdateDelay)
{
item.CreateServerEvent(this);
serverHealthUpdateTimer = 0;
}
else
{
serverHealthUpdateTimer++;
}
}
#endif
}
CheckPlantState();
@@ -312,7 +312,7 @@ namespace Barotrauma.Items.Components
if (item.Removed)
{
DebugConsole.ThrowError($"Attempted to equip a removed item ({item.Name})\n" + Environment.StackTrace);
DebugConsole.ThrowError($"Attempted to equip a removed item ({item.Name})\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
@@ -416,7 +416,7 @@ namespace Barotrauma.Items.Components
{
if (item.Removed)
{
DebugConsole.ThrowError($"Attempted to pick up a removed item ({item.Name})\n" + Environment.StackTrace);
DebugConsole.ThrowError($"Attempted to pick up a removed item ({item.Name})\n" + Environment.StackTrace.CleanupStackTrace());
return false;
}
@@ -104,14 +104,14 @@ namespace Barotrauma.Items.Components
ApplyStatusEffects(ActionType.OnPicked, 1.0f, picker);
#if CLIENT
if (!GameMain.Instance.LoadingScreenOpen && picker == Character.Controlled) GUI.PlayUISound(GUISoundType.PickItem);
if (!GameMain.Instance.LoadingScreenOpen && picker == Character.Controlled) SoundPlayer.PlayUISound(GUISoundType.PickItem);
PlaySound(ActionType.OnPicked, picker);
#endif
return true;
}
#if CLIENT
if (!GameMain.Instance.LoadingScreenOpen && picker == Character.Controlled) GUI.PlayUISound(GUISoundType.PickItemFail);
if (!GameMain.Instance.LoadingScreenOpen && picker == Character.Controlled) SoundPlayer.PlayUISound(GUISoundType.PickItemFail);
#endif
return false;
@@ -248,6 +248,7 @@ namespace Barotrauma.Items.Components
partial void UseProjSpecific(float deltaTime, Vector2 raystart);
private static readonly List<Body> hitBodies = new List<Body>();
private readonly HashSet<Character> hitCharacters = new HashSet<Character>();
private readonly List<FireSource> fireSourcesInRange = new List<FireSource>();
private void Repair(Vector2 rayStart, Vector2 rayEnd, float deltaTime, Character user, float degreeOfSuccess, List<Body> ignoredBodies)
@@ -291,10 +292,14 @@ namespace Barotrauma.Items.Components
return true;
},
allowInsideFixture: true);
hitBodies.Clear();
hitBodies.AddRange(bodies);
lastPickedFraction = Submarine.LastPickedFraction;
Type lastHitType = null;
hitCharacters.Clear();
foreach (Body body in bodies)
foreach (Body body in hitBodies)
{
Type bodyType = body.UserData?.GetType();
if (!RepairThroughWalls && bodyType != null && bodyType != lastHitType)
@@ -372,13 +377,23 @@ namespace Barotrauma.Items.Components
fireSourcesInRange.Add(fs);
}
}
foreach (FireSource fs in hull.FakeFireSources)
{
if (fs.IsInDamageRange(displayPos, 100.0f) && !fireSourcesInRange.Contains(fs))
{
fireSourcesInRange.Add(fs);
}
}
}
foreach (FireSource fs in fireSourcesInRange)
{
fs.Extinguish(deltaTime, ExtinguishAmount);
#if SERVER
GameMain.Server.KarmaManager.OnExtinguishingFire(user, deltaTime);
if (!(fs is DummyFireSource))
{
GameMain.Server.KarmaManager.OnExtinguishingFire(user, deltaTime);
}
#endif
}
}
@@ -562,13 +577,22 @@ namespace Barotrauma.Items.Components
partial void FixItemProjSpecific(Character user, float deltaTime, Item targetItem);
private float sinTime;
private float repairTimer;
private Gap previousGap;
private readonly float repairTimeOut = 5;
public override bool AIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
{
if (!(objective.OperateTarget is Gap leak)) { return true; }
if (leak.Submarine == null) { return true; }
if (leak != previousGap)
{
sinTime = 0;
repairTimer = 0;
previousGap = leak;
}
Vector2 fromCharacterToLeak = leak.WorldPosition - character.WorldPosition;
float dist = fromCharacterToLeak.Length();
float reach = Range + ConvertUnits.ToDisplayUnits(((HumanoidAnimController)character.AnimController).ArmLength);
float reach = AIObjectiveFixLeak.CalculateReach(this, character);
//too far away -> consider this done and hope the AI is smart enough to move closer
if (dist > reach * 2) { return true; }
@@ -626,7 +650,11 @@ namespace Barotrauma.Items.Components
else if (dist < reach * 2)
{
// In or almost in range
character.CursorPosition = leak.Position;
character.CursorPosition = leak.WorldPosition;
if (character.Submarine != null)
{
character.CursorPosition -= character.Submarine.Position;
}
character.CursorPosition += VectorExtensions.Forward(Item.body.TransformedRotation + (float)Math.Sin(sinTime) / 2, dist / 2);
if (character.AnimController.InWater)
{
@@ -656,6 +684,12 @@ namespace Barotrauma.Items.Components
var angle = VectorExtensions.Angle(VectorExtensions.Forward(item.body.TransformedRotation), fromItemToLeak);
if (angle < MathHelper.PiOver4)
{
if (Submarine.PickBody(item.SimPosition, leak.SimPosition, collisionCategory: Physics.CollisionWall, allowInsideFixture: true)?.UserData is Item i)
{
var door = i.GetComponent<Door>();
// Hit a door, abandon so that we don't weld it shut.
return door != null && !door.IsOpen && !door.IsBroken;
}
// Check that we don't hit any friendlies
if (Submarine.PickBodies(item.SimPosition, leak.SimPosition, collisionCategory: Physics.CollisionCharacter).None(hit =>
{
@@ -669,6 +703,14 @@ namespace Barotrauma.Items.Components
{
character.SetInput(InputType.Shoot, false, true);
Use(deltaTime, character);
repairTimer += deltaTime;
if (repairTimer > repairTimeOut)
{
#if DEBUG
DebugConsole.NewMessage($"{character.Name}: timed out while welding a leak in {leak.FlowTargetHull.DisplayName}.", color: Color.Yellow);
#endif
return true;
}
}
}
@@ -604,7 +604,7 @@ namespace Barotrauma.Items.Components
if (character == null)
{
string errorMsg = "ItemComponent.DegreeOfSuccess failed (character was null).\n" + Environment.StackTrace;
string errorMsg = "ItemComponent.DegreeOfSuccess failed (character was null).\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("ItemComponent.DegreeOfSuccess:CharacterNull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return 0.0f;
@@ -846,7 +846,7 @@ namespace Barotrauma.Items.Components
DebugConsole.ThrowError("Error while loading entity of the type " + t + ".", e.InnerException);
GameAnalyticsManager.AddErrorEventOnce("ItemComponent.Load:TargetInvocationException" + item.Name + element.Name,
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Error while loading entity of the type " + t + " (" + e.InnerException + ")\n" + Environment.StackTrace);
"Error while loading entity of the type " + t + " (" + e.InnerException + ")\n" + Environment.StackTrace.CleanupStackTrace());
}
return ic;
@@ -1014,8 +1014,8 @@ namespace Barotrauma.Items.Components
var container = i.GetComponent<ItemContainer>();
if (container == null) { return 0; }
if (container.Inventory.IsFull()) { return 0; }
// Ignore containers that are identical to the source container
if (sourceC != null && container.Item.Prefab == sourceC.Item.Prefab) { return 0; }
// Ignore containers that are identical to the source container
if (sourceC != null && container.Item.Prefab == sourceC.Item.Prefab) { return 0; }
if (container.ShouldBeContained(containedItem, out bool isRestrictionsDefined))
{
if (isRestrictionsDefined)
@@ -328,10 +328,10 @@ namespace Barotrauma.Items.Components
}
catch (Exception e)
{
DebugConsole.Log("SetTransformIgnoreContacts threw an exception in SetContainedItemPositions (" + e.Message + ")\n" + e.StackTrace);
DebugConsole.Log("SetTransformIgnoreContacts threw an exception in SetContainedItemPositions (" + e.Message + ")\n" + e.StackTrace.CleanupStackTrace());
GameAnalyticsManager.AddErrorEventOnce("ItemContainer.SetContainedItemPositions.InvalidPosition:" + contained.Name,
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"SetTransformIgnoreContacts threw an exception in SetContainedItemPositions (" + e.Message + ")\n" + e.StackTrace);
"SetTransformIgnoreContacts threw an exception in SetContainedItemPositions (" + e.Message + ")\n" + e.StackTrace.CleanupStackTrace());
}
contained.body.Submarine = item.Submarine;
}
@@ -388,9 +388,9 @@ namespace Barotrauma.Items.Components
inventoryBottomSprite?.Remove();
ContainedStateIndicator?.Remove();
if (Screen.Selected == GameMain.SubEditorScreen && !Submarine.Unloading)
if (SubEditorScreen.IsSubEditor())
{
GameMain.SubEditorScreen.HandleContainerContentsDeletion(Item, Inventory);
Inventory.DeleteAllItems();
return;
}
#endif
@@ -34,7 +34,7 @@ namespace Barotrauma.Items.Components
set { maxFlow = value; }
}
[Editable, Serialize(false, false, alwaysUseInstanceValues: true)]
[Editable, Serialize(true, false, alwaysUseInstanceValues: true)]
public bool IsOn
{
get { return IsActive; }
@@ -201,6 +201,7 @@ namespace Barotrauma.Items.Components
if (seed.Decayed || seed.FullyGrown)
{
container?.Inventory.RemoveItem(seed.Item);
Entity.Spawner?.AddToRemoveQueue(seed.Item);
GrowableSeeds[i] = null;
return true;
}
@@ -214,14 +214,15 @@ namespace Barotrauma.Items.Components
}
if (HasBeenTuned) { return true; }
if (string.IsNullOrEmpty(objective.Option) || objective.Option.Equals("charge", StringComparison.OrdinalIgnoreCase))
float targetRatio = string.IsNullOrEmpty(objective.Option) || objective.Option.Equals("charge", StringComparison.OrdinalIgnoreCase) ? aiRechargeTargetRatio : -1;
if (targetRatio > 0 || float.TryParse(objective.Option, out targetRatio))
{
if (Math.Abs(rechargeSpeed - maxRechargeSpeed * aiRechargeTargetRatio) > 0.05f)
if (Math.Abs(rechargeSpeed - maxRechargeSpeed * targetRatio) > 0.05f)
{
#if SERVER
item.CreateServerEvent(this);
#endif
RechargeSpeed = maxRechargeSpeed * aiRechargeTargetRatio;
RechargeSpeed = maxRechargeSpeed * targetRatio;
#if CLIENT
if (rechargeSpeedSlider != null)
{
@@ -271,7 +271,7 @@ namespace Barotrauma.Items.Components
if (wires[i] == null) { continue; }
Connection recipient = wires[i].OtherConnection(this);
if (recipient == null) { continue; }
if (recipient == null || !recipient.IsPower) { continue; }
recipient.item.GetComponent<Powered>()?.ReceivePowerProbeSignal(recipient, source, power);
}
@@ -5,7 +5,7 @@ namespace Barotrauma.Items.Components
{
partial class MemoryComponent : ItemComponent, IServerSerializable
{
const int MaxValueLength = 256;
const int MaxValueLength = ChatMessage.MaxLength;
private string value;
@@ -11,6 +11,7 @@ namespace Barotrauma.Items.Components
private string previousReceivedSignal;
private bool previousResult;
private GroupCollection previousGroups;
private Regex regex;
@@ -19,6 +20,9 @@ namespace Barotrauma.Items.Components
[InGameEditable, Serialize("1", true, description: "The signal this item outputs when the received signal matches the regular expression.", alwaysUseInstanceValues: true)]
public string Output { get; set; }
[InGameEditable, Serialize(false, true, description: "Should the component output a value of a capture group instead of a constant signal.", alwaysUseInstanceValues: true)]
public bool UseCaptureGroup { get; set; }
[Serialize("0", true, description: "The signal this item outputs when the received signal does not match the regular expression.", alwaysUseInstanceValues: true)]
public string FalseOutput { get; set; }
@@ -64,6 +68,7 @@ namespace Barotrauma.Items.Components
{
Match match = regex.Match(receivedSignal);
previousResult = match.Success;
previousGroups = UseCaptureGroup && previousResult ? match.Groups : null;
previousReceivedSignal = receivedSignal;
}
@@ -75,7 +80,30 @@ namespace Barotrauma.Items.Components
}
}
string signalOut = previousResult ? Output : FalseOutput;
string signalOut;
if (previousResult)
{
if (UseCaptureGroup)
{
if (previousGroups != null && previousGroups.TryGetValue(Output, out Group group))
{
signalOut = group.Value;
}
else
{
signalOut = FalseOutput;
}
}
else
{
signalOut = Output;
}
}
else
{
signalOut = FalseOutput;
}
if (ContinuousOutput)
{
if (!string.IsNullOrEmpty(signalOut)) { item.SendSignal(0, signalOut, "signal_out", null); }
@@ -37,7 +37,7 @@ namespace Barotrauma.Items.Components
}
}
[Editable, Serialize(false, true, description: "Can the relay currently pass power and signals through it.", alwaysUseInstanceValues: true)]
[Editable, Serialize(true, true, description: "Can the relay currently pass power and signals through it.", alwaysUseInstanceValues: true)]
public bool IsOn
{
get
@@ -21,7 +21,7 @@ namespace Barotrauma.Items.Components
{
if (welcomeMessage == value) { return; }
welcomeMessage = value;
DisplayedWelcomeMessage = TextManager.Get(welcomeMessage, returnNull: true) ?? welcomeMessage;
DisplayedWelcomeMessage = TextManager.Get(welcomeMessage, returnNull: true) ?? welcomeMessage.Replace("\\n", "\n");
}
}
@@ -45,7 +45,9 @@ namespace Barotrauma.Items.Components
{
signal = signal.Substring(0, MaxMessageLength);
}
ShowOnDisplay(signal);
string inputSignal = signal.Replace("\\n", "\n");
ShowOnDisplay(inputSignal);
}
}
}
@@ -198,7 +198,21 @@ namespace Barotrauma.Items.Components
int newNodeIndex = 0;
if (nodes.Count > 1)
{
if (Vector2.DistanceSquared(nodes[nodes.Count - 1], nodePos) < Vector2.DistanceSquared(nodes[0], nodePos))
if (connections[0] != null && connections[0] != newConnection)
{
if (Vector2.DistanceSquared(nodes[0], connections[0].Item.Position - (refSub?.HiddenSubPosition ?? Vector2.Zero)) < Vector2.DistanceSquared(nodes[nodes.Count - 1], nodePos))
{
newNodeIndex = nodes.Count;
}
}
else if (connections[1] != null && connections[1] != newConnection)
{
if (Vector2.DistanceSquared(nodes[0], connections[1].Item.Position - (refSub?.HiddenSubPosition ?? Vector2.Zero)) < Vector2.DistanceSquared(nodes[nodes.Count - 1], nodePos))
{
newNodeIndex = nodes.Count;
}
}
else if (Vector2.DistanceSquared(nodes[nodes.Count - 1], nodePos) < Vector2.DistanceSquared(nodes[0], nodePos))
{
newNodeIndex = nodes.Count;
}
@@ -384,7 +384,7 @@ namespace Barotrauma.Items.Components
if (!flashLowPower && character != null && character == Character.Controlled)
{
flashLowPower = true;
GUI.PlayUISound(GUISoundType.PickItemFail);
SoundPlayer.PlayUISound(GUISoundType.PickItemFail);
}
#endif
return false;
@@ -422,7 +422,7 @@ namespace Barotrauma.Items.Components
{
flashNoAmmo = true;
failedLaunchAttempts = 0;
GUI.PlayUISound(GUISoundType.PickItemFail);
SoundPlayer.PlayUISound(GUISoundType.PickItemFail);
}
#endif
return false;
@@ -151,7 +151,7 @@ namespace Barotrauma
{
if (i < 0 || i >= Items.Length)
{
string errorMsg = "Inventory.TryPutItem failed: index was out of range(" + i + ").\n" + Environment.StackTrace;
string errorMsg = "Inventory.TryPutItem failed: index was out of range(" + i + ").\n" + Environment.StackTrace.CleanupStackTrace();
GameAnalyticsManager.AddErrorEventOnce("Inventory.TryPutItem:IndexOutOfRange", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return false;
}
@@ -192,7 +192,7 @@ namespace Barotrauma
{
if (i < 0 || i >= Items.Length)
{
string errorMsg = "Inventory.PutItem failed: index was out of range(" + i + ").\n" + Environment.StackTrace;
string errorMsg = "Inventory.PutItem failed: index was out of range(" + i + ").\n" + Environment.StackTrace.CleanupStackTrace();
GameAnalyticsManager.AddErrorEventOnce("Inventory.PutItem:IndexOutOfRange", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return;
}
@@ -486,6 +486,22 @@ namespace Barotrauma
}
Items[i].Remove();
}
}
}
public List<Item> GetAllItems()
{
List<Item> deletedItems = new List<Item>();
for (int i = 0; i < capacity; i++)
{
if (Items[i] == null) continue;
foreach (ItemContainer itemContainer in Items[i].GetComponents<ItemContainer>())
{
deletedItems.AddRange(itemContainer.Inventory.GetAllItems());
}
deletedItems.Add(Items[i]);
}
return deletedItems;
}
}
}
@@ -1016,7 +1016,7 @@ namespace Barotrauma
{
string errorMsg =
"Attempted to move the item " + Name +
" to an invalid position (" + simPosition + ")\n" + Environment.StackTrace;
" to an invalid position (" + simPosition + ")\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce(
@@ -1073,7 +1073,7 @@ namespace Barotrauma
{
if (!MathUtils.IsValid(amount))
{
DebugConsole.ThrowError($"Attempted to move an item by an invalid amount ({amount})\n{Environment.StackTrace}");
DebugConsole.ThrowError($"Attempted to move an item by an invalid amount ({amount})\n{Environment.StackTrace.CleanupStackTrace()}");
return;
}
@@ -1360,12 +1360,15 @@ namespace Barotrauma
public AttackResult AddDamage(Character attacker, Vector2 worldPosition, Attack attack, float deltaTime, bool playSound = true)
{
if (Indestructible) return new AttackResult();
if (Indestructible) { return new AttackResult(); }
float damageAmount = attack.GetItemDamage(deltaTime);
Condition -= damageAmount;
ApplyStatusEffects(ActionType.OnDamaged, 1.0f);
if (damageAmount > 0)
{
ApplyStatusEffects(ActionType.OnDamaged, 1.0f);
}
return new AttackResult(damageAmount, null);
}
@@ -1629,7 +1632,7 @@ namespace Barotrauma
OnCollisionProjSpecific(impact);
if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer)
{
if (ImpactTolerance > 0.0f && condition > 0.0f && impact > ImpactTolerance)
if (ImpactTolerance > 0.0f && condition > 0.0f && Math.Abs(impact) > ImpactTolerance)
{
ApplyStatusEffects(ActionType.OnImpact, 1.0f);
#if SERVER
@@ -1980,17 +1983,14 @@ namespace Barotrauma
{
if (picker.SelectedConstruction == this)
{
if (picker.IsKeyHit(InputType.Select) || forceSelectKey) picker.SelectedConstruction = null;
if (picker.IsKeyHit(InputType.Select) || forceSelectKey)
{
picker.SelectedConstruction = null;
}
}
else if (selected)
{
picker.SelectedConstruction = this;
#if CLIENT
if (GameMain.GameSession?.CrewManager != null && picker == Character.Controlled && GetComponent<Ladder>() == null)
{
GameMain.GameSession.CrewManager.ToggleCrewListOpen = false;
}
#endif
}
}
@@ -2215,7 +2215,7 @@ namespace Barotrauma
{
if (Removed)
{
DebugConsole.ThrowError($"Tried to equip a removed item ({Name}).\n{Environment.StackTrace}");
DebugConsole.ThrowError($"Tried to equip a removed item ({Name}).\n{Environment.StackTrace.CleanupStackTrace()}");
return;
}
@@ -2712,7 +2712,7 @@ namespace Barotrauma
{
if (Removed)
{
DebugConsole.ThrowError("Attempting to remove an already removed item (" + Name + ")\n" + Environment.StackTrace);
DebugConsole.ThrowError("Attempting to remove an already removed item (" + Name + ")\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
DebugConsole.Log("Removing item " + Name + " (ID: " + ID + ")");
@@ -93,7 +93,7 @@ namespace Barotrauma
{
if (!Item.ItemList.Contains(container.Item))
{
string errorMsg = "Attempted to create a network event for an item (" + container.Item.Name + ") that hasn't been fully initialized yet.\n" + Environment.StackTrace;
string errorMsg = "Attempted to create a network event for an item (" + container.Item.Name + ") that hasn't been fully initialized yet.\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce(
"ItemInventory.CreateServerEvent:EventForUninitializedItem" + container.Item.Name + container.Item.ID,
@@ -319,6 +319,13 @@ namespace Barotrauma
private set;
}
[Serialize(false, false)]
public bool AllowSellingWhenBroken
{
get;
private set;
}
[Serialize(false, false)]
public bool Indestructible
{
@@ -7,14 +7,13 @@ namespace Barotrauma
{
private Vector2 maxSize;
public bool Removed
{
get { return removed; }
}
public bool CausedByPsychosis;
public DummyFireSource(Vector2 maxSize, Vector2 worldPosition, Hull spawningHull = null, bool isNetworkMessage = false) : base(worldPosition, spawningHull, isNetworkMessage)
{
this.maxSize = maxSize;
DamagesItems = false;
DamagesCharacters = true;
}
public override float DamageRange
@@ -24,11 +23,7 @@ namespace Barotrauma
protected override void LimitSize()
{
if (hull == null) return;
position.X = Math.Max(hull.Rect.X, position.X);
position.Y = Math.Min(hull.Rect.Y, position.Y);
base.LimitSize();
size.X = Math.Min(maxSize.X, size.X);
size.Y = Math.Min(maxSize.Y, size.Y);
}
@@ -51,13 +51,13 @@ namespace Barotrauma
if (value == NullEntityID)
{
DebugConsole.ThrowError("Cannot set the ID of an entity to " + NullEntityID +
"! The value is reserved for entity events referring to a non-existent (e.g. removed) entity.\n" + Environment.StackTrace);
"! The value is reserved for entity events referring to a non-existent (e.g. removed) entity.\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
if (value == EntitySpawnerID)
{
DebugConsole.ThrowError("Cannot set the ID of an entity to " + EntitySpawnerID +
"! The value is reserved for EntitySpawner.\n" + Environment.StackTrace);
"! The value is reserved for EntitySpawner.\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
@@ -183,7 +183,7 @@ namespace Barotrauma
GameAnalyticsManager.AddErrorEventOnce(
"Entity.RemoveAll:Exception" + e.ToString(),
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Error while removing entity \"" + e.ToString() + " (" + exception.Message + ")\n" + exception.StackTrace);
"Error while removing entity \"" + e.ToString() + " (" + exception.Message + ")\n" + exception.StackTrace.CleanupStackTrace());
}
}
StringBuilder errorMsg = new StringBuilder();
@@ -266,7 +266,7 @@ namespace Barotrauma
GameAnalyticsManager.AddErrorEventOnce(
"Entity.FreeID:EntityNotFound" + ID,
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Entity " + ToString() + " (" + ID + ") not present in entity dictionary.\n" + Environment.StackTrace);
"Entity " + ToString() + " (" + ID + ") not present in entity dictionary.\n" + Environment.StackTrace.CleanupStackTrace());
}
else if (existingEntity != this)
{
@@ -105,7 +105,7 @@ namespace Barotrauma
if (hull != null && !string.IsNullOrWhiteSpace(decal) && decalSize > 0.0f)
{
hull.AddDecal(decal, worldPosition, decalSize, true);
hull.AddDecal(decal, worldPosition, decalSize, isNetworkEvent: false);
}
float displayRange = attack.Range;
@@ -340,6 +340,15 @@ namespace Barotrauma
}
}
if (c == Character.Controlled && !c.IsDead)
{
Limb head = c.AnimController.GetLimb(LimbType.Head);
if (damages.TryGetValue(head, out float headDamage) && headDamage > 0.0f && distFactors.TryGetValue(head, out float headFactor))
{
PlayTinnitusProjSpecific(headFactor);
}
}
//sever joints
if (attack.SeverLimbsProbability > 0.0f)
{
@@ -402,5 +411,7 @@ namespace Barotrauma
return damagedStructures;
}
static partial void PlayTinnitusProjSpecific(float volume);
}
}
@@ -69,6 +69,23 @@ namespace Barotrauma
get { return Math.Min((float)Math.Sqrt(size.X) * 10.0f, MaxDamageRange); }
}
public bool DamagesItems
{
get;
set;
}
public bool DamagesCharacters
{
get;
set;
}
public bool Removed
{
get { return removed; }
}
public Hull Hull
{
get { return hull; }
@@ -80,7 +97,7 @@ namespace Barotrauma
if (hull == null || worldPosition.Y < hull.WorldSurface) return;
#if CLIENT
if (!isNetworkMessage && GameMain.Client != null) return;
if (!isNetworkMessage && GameMain.Client != null) { return; }
#endif
hull.AddFireSource(this);
@@ -140,9 +157,43 @@ namespace Barotrauma
}
}
}
public static void UpdateAll(List<DummyFireSource> fireSources, float deltaTime)
{
for (int i = fireSources.Count - 1; i >= 0; i--)
{
fireSources[i].Update(deltaTime);
}
//combine overlapping fires
for (int i = fireSources.Count - 1; i >= 0; i--)
{
for (int j = i - 1; j >= 0; j--)
{
i = Math.Min(i, fireSources.Count - 1);
j = Math.Min(j, i - 1);
if (!fireSources[i].CheckOverLap(fireSources[j])) { continue; }
float leftEdge = Math.Min(fireSources[i].position.X, fireSources[j].position.X);
fireSources[j].size.X =
Math.Max(fireSources[i].position.X + fireSources[i].size.X, fireSources[j].position.X + fireSources[j].size.X)
- leftEdge;
fireSources[j].position.X = leftEdge;
fireSources[i].Remove();
}
}
}
private bool CheckOverLap(FireSource fireSource)
{
if (this is DummyFireSource != fireSource is DummyFireSource)
{
return false;
}
return !(position.X > fireSource.position.X + fireSource.size.X ||
position.X + size.X < fireSource.position.X);
}
@@ -152,8 +203,8 @@ namespace Barotrauma
//the firesource will start to shrink if oxygen percentage is below 10
float growModifier = Math.Min((hull.OxygenPercentage / 10.0f) - 1.0f, 1.0f);
DamageCharacters(deltaTime);
DamageItems(deltaTime);
if (DamagesCharacters) { DamageCharacters(deltaTime); }
if (DamagesItems) { DamageItems(deltaTime); }
if (hull.WaterVolume > 0.0f)
{
@@ -161,7 +212,10 @@ namespace Barotrauma
if (removed) { return; }
}
ReduceOxygen(deltaTime);
if (!(this is DummyFireSource))
{
ReduceOxygen(deltaTime);
}
AdjustXPos(growModifier, deltaTime);
@@ -175,21 +229,21 @@ namespace Barotrauma
LimitSize();
if (size.X > 256.0f)
if (size.X > 256.0f && !(this is DummyFireSource))
{
if (burnDecals.Count == 0)
{
var newDecal = hull.AddDecal("burnt", WorldPosition + size / 2, 1f, true);
var newDecal = hull.AddDecal("burnt", WorldPosition + size / 2, 1f, isNetworkEvent: false);
if (newDecal != null) { burnDecals.Add(newDecal); }
}
else if (WorldPosition.X < burnDecals[0].WorldPosition.X - 256.0f)
{
var newDecal = hull.AddDecal("burnt", WorldPosition, 1f, true);
var newDecal = hull.AddDecal("burnt", WorldPosition, 1f, isNetworkEvent: false);
if (newDecal != null) { burnDecals.Insert(0, newDecal); }
}
else if (WorldPosition.X + size.X > burnDecals[burnDecals.Count - 1].WorldPosition.X + 256.0f)
{
var newDecal = hull.AddDecal("burnt", WorldPosition + Vector2.UnitX * size.X, 1f, true);
var newDecal = hull.AddDecal("burnt", WorldPosition + Vector2.UnitX * size.X, 1f, isNetworkEvent: false);
if (newDecal != null) { burnDecals.Add(newDecal); }
}
}
@@ -281,14 +335,13 @@ namespace Barotrauma
private void DamageItems(float deltaTime)
{
if (size.X <= 0.0f) return;
if (size.X <= 0.0f) { return; }
#if CLIENT
if (GameMain.Client != null) return;
if (GameMain.Client != null) { return; }
#endif
foreach (Item item in Item.ItemList)
{
if (item.CurrentHull != hull || item.FireProof || item.Condition <= 0.0f) continue;
if (item.CurrentHull != hull || item.FireProof || item.Condition <= 0.0f) { continue; }
//don't apply OnFire effects if the item is inside a fireproof container
//(or if it's inside a container that's inside a fireproof container, etc)
@@ -300,8 +353,8 @@ namespace Barotrauma
}
float range = (float)Math.Sqrt(size.X) * 10.0f;
if (item.Position.X < position.X - range || item.Position.X > position.X + size.X + range) continue;
if (item.Position.Y < position.Y - size.Y || item.Position.Y > hull.Rect.Y) continue;
if (item.Position.X < position.X - range || item.Position.X > position.X + size.X + range) { continue; }
if (item.Position.Y < position.Y - size.Y || item.Position.Y > hull.Rect.Y) { continue; }
item.ApplyStatusEffects(ActionType.OnFire, deltaTime);
if (item.Condition <= 0.0f && GameMain.NetworkMember != null && GameMain.NetworkMember.IsServer)
@@ -162,7 +162,7 @@ namespace Barotrauma
{
if (!MathUtils.IsValid(amount))
{
DebugConsole.ThrowError($"Attempted to move a gap by an invalid amount ({amount})\n{Environment.StackTrace}");
DebugConsole.ThrowError($"Attempted to move a gap by an invalid amount ({amount})\n{Environment.StackTrace.CleanupStackTrace()}");
return;
}
@@ -389,6 +389,8 @@ namespace Barotrauma
public List<FireSource> FireSources { get; private set; }
public List<DummyFireSource> FakeFireSources { get; private set; }
public Hull(MapEntityPrefab prefab, Rectangle rectangle)
: this (prefab, rectangle, Submarine.MainSub)
{
@@ -405,6 +407,7 @@ namespace Barotrauma
OxygenPercentage = 100.0f;
FireSources = new List<FireSource>();
FakeFireSources = new List<DummyFireSource>();
properties = SerializableProperty.GetProperties(this);
@@ -554,7 +557,7 @@ namespace Barotrauma
{
if (!MathUtils.IsValid(amount))
{
DebugConsole.ThrowError($"Attempted to move a hull by an invalid amount ({amount})\n{Environment.StackTrace}");
DebugConsole.ThrowError($"Attempted to move a hull by an invalid amount ({amount})\n{Environment.StackTrace.CleanupStackTrace()}");
return;
}
@@ -583,11 +586,13 @@ namespace Barotrauma
}
List<FireSource> fireSourcesToRemove = new List<FireSource>(FireSources);
fireSourcesToRemove.AddRange(FakeFireSources);
foreach (FireSource fireSource in fireSourcesToRemove)
{
fireSource.Remove();
}
FireSources.Clear();
FakeFireSources.Clear();
if (EntityGrids != null)
{
@@ -627,10 +632,17 @@ namespace Barotrauma
public void AddFireSource(FireSource fireSource)
{
FireSources.Add(fireSource);
if (fireSource is DummyFireSource dummyFire)
{
FakeFireSources.Add(dummyFire);
}
else
{
FireSources.Add(fireSource);
}
}
public Decal AddDecal(UInt32 decalId, Vector2 worldPosition, float scale, bool isNetworkEvent)
public Decal AddDecal(UInt32 decalId, Vector2 worldPosition, float scale, bool isNetworkEvent, int? spriteIndex = null)
{
//clients are only allowed to create decals when the server says so
if (!isNetworkEvent && GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
@@ -644,11 +656,11 @@ namespace Barotrauma
DebugConsole.ThrowError($"Could not find a decal prefab with the UInt identifier {decalId}!");
return null;
}
return AddDecal(decal.Name, worldPosition, scale, isNetworkEvent);
return AddDecal(decal.Name, worldPosition, scale, isNetworkEvent, spriteIndex);
}
public Decal AddDecal(string decalName, Vector2 worldPosition, float scale, bool isNetworkEvent)
public Decal AddDecal(string decalName, Vector2 worldPosition, float scale, bool isNetworkEvent, int? spriteIndex = null)
{
//clients are only allowed to create decals when the server says so
if (!isNetworkEvent && GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
@@ -658,7 +670,7 @@ namespace Barotrauma
if (decals.Count >= MaxDecalsPerHull) { return null; }
var decal = GameMain.DecalManager.CreateDecal(decalName, scale, worldPosition, this);
var decal = GameMain.DecalManager.CreateDecal(decalName, scale, worldPosition, this, spriteIndex);
if (decal != null)
{
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsServer)
@@ -679,7 +691,19 @@ namespace Barotrauma
Oxygen -= OxygenDeteriorationSpeed * deltaTime;
if ((Character.Controlled?.CharacterHealth?.GetAffliction("psychosis")?.Strength ?? 0.0f) <= 0.0f)
{
for (int i = FakeFireSources.Count - 1; i >= 0; i--)
{
if (FakeFireSources[i].CausedByPsychosis)
{
FakeFireSources[i].Remove();
}
}
}
FireSource.UpdateAll(FireSources, deltaTime);
FireSource.UpdateAll(FakeFireSources, deltaTime);
foreach (Decal decal in decals)
{
@@ -687,7 +711,6 @@ namespace Barotrauma
}
decals.RemoveAll(d => d.FadeTimer >= d.LifeTime || d.BaseAlpha <= 0.001f);
if (aiTarget != null)
{
aiTarget.SightRange = Submarine == null ? aiTarget.MinSightRange : Submarine.Velocity.Length() / 2 * aiTarget.MaxSightRange;
@@ -842,17 +865,31 @@ namespace Barotrauma
}
}
public void Extinguish(float deltaTime, float amount, Vector2 position)
public void Extinguish(float deltaTime, float amount, Vector2 position, bool extinguishRealFires = true, bool extinguishFakeFires = true)
{
for (int i = FireSources.Count - 1; i >= 0; i--)
if (extinguishRealFires)
{
FireSources[i].Extinguish(deltaTime, amount, position);
for (int i = FireSources.Count - 1; i >= 0; i--)
{
FireSources[i].Extinguish(deltaTime, amount, position);
}
}
if (extinguishFakeFires)
{
for (int i = FakeFireSources.Count - 1; i >= 0; i--)
{
FakeFireSources[i].Extinguish(deltaTime, amount, position);
}
}
}
public void RemoveFire(FireSource fire)
{
FireSources.Remove(fire);
if (fire is DummyFireSource dummyFire)
{
FakeFireSources.Remove(dummyFire);
}
}
private readonly HashSet<Hull> adjacentHulls = new HashSet<Hull>();
@@ -1221,7 +1258,7 @@ namespace Barotrauma
return index >= 0 && row >= 0 && BackgroundSections.Count > index && BackgroundSections[index] != null && BackgroundSections[index].RowIndex == row;
}
public void SetSectionColorOrStrength(BackgroundSection section, Color? color, float? strength, bool requiresUpdate, bool isCleaning)
public void IncreaseSectionColorOrStrength(BackgroundSection section, Color? color, float? strength, bool requiresUpdate, bool isCleaning)
{
bool sectionUpdated = isCleaning;
if (color != null)
@@ -1263,13 +1300,31 @@ namespace Barotrauma
}
}
public void SetSectionColorOrStrength(BackgroundSection section, Color? color, float? strength)
{
if (color != null)
{
section.SetColor(color.Value);
}
if (strength != null)
{
float previous = section.SetColorStrength(Math.Max(minColorStrength, Math.Min(maxColorStrength, section.ColorStrength + strength.Value)));
if (previous != -1f)
{
#if CLIENT
paintAmount = Math.Max(0, paintAmount + (section.ColorStrength - previous) / BackgroundSections.Count);
#endif
}
}
}
public void DirtySections(List<BackgroundSection> sections, float dirtyVal)
{
if (sections == null) { return; }
for (int i = 0; i < sections.Count; i++)
{
float sectionDirtyVal = dirtyVal;
SetSectionColorOrStrength(sections[i], sections[i].DirtColor, sectionDirtyVal, false, false);
IncreaseSectionColorOrStrength(sections[i], sections[i].DirtColor, dirtyVal, false, false);
}
}
@@ -1283,11 +1338,14 @@ namespace Barotrauma
{
decal.Clean(cleanVal);
decalsCleaned = true;
#if SERVER
decalUpdatePending = true;
#endif
}
}
if (section.ColorStrength == 0 && !decalsCleaned) { return; }
SetSectionColorOrStrength(section, null, cleanVal, updateRequired, true);
IncreaseSectionColorOrStrength(section, null, cleanVal, updateRequired, true);
}
#endregion
@@ -1341,10 +1399,12 @@ namespace Barotrauma
Vector2 pos = subElement.GetAttributeVector2("pos", Vector2.Zero);
float scale = subElement.GetAttributeFloat("scale", 1.0f);
float timer = subElement.GetAttributeFloat("timer", 1.0f);
float baseAlpha = subElement.GetAttributeFloat("alpha", 1.0f);
var decal = hull.AddDecal(id, pos + hull.WorldRect.Location.ToVector2(), scale, true);
if (decal != null)
{
decal.FadeTimer = timer;
decal.BaseAlpha = baseAlpha;
}
break;
}
@@ -1362,7 +1422,7 @@ namespace Barotrauma
if (int.TryParse(backgroundSectionData[0], out int index) &&
float.TryParse(backgroundSectionData[2], NumberStyles.Any, CultureInfo.InvariantCulture, out float strength))
{
hull.SetSectionColorOrStrength(hull.BackgroundSections[index], color, strength, false, false);
hull.SetSectionColorOrStrength(hull.BackgroundSections[index], color, strength);
}
}
}
@@ -1377,7 +1437,7 @@ namespace Barotrauma
{
if (Submarine == null)
{
string errorMsg = "Error - tried to save a hull that's not a part of any submarine.\n" + Environment.StackTrace;
string errorMsg = "Error - tried to save a hull that's not a part of any submarine.\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("Hull.Save:WorldHull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return null;
@@ -1420,7 +1480,8 @@ namespace Barotrauma
new XAttribute("id", decal.Prefab.Identifier),
new XAttribute("pos", XMLExtensions.Vector2ToString(decal.NonClampedPosition)),
new XAttribute("scale", decal.Scale.ToString("G", CultureInfo.InvariantCulture)),
new XAttribute("timer", decal.FadeTimer.ToString("G", CultureInfo.InvariantCulture))
new XAttribute("timer", decal.FadeTimer.ToString("G", CultureInfo.InvariantCulture)),
new XAttribute("alpha", decal.BaseAlpha.ToString("G", CultureInfo.InvariantCulture))
));
}
@@ -110,7 +110,13 @@ namespace Barotrauma
protected override void CreateInstance(Rectangle rect)
{
CreateInstance(rect.Location.ToVector2(), Submarine.MainSub);
var loaded = CreateInstance(rect.Location.ToVector2(), Submarine.MainSub);
#if CLIENT
if (Screen.Selected is SubEditorScreen)
{
SubEditorScreen.StoreCommand(new AddOrDeleteCommand(loaded, false));
}
#endif
}
public List<MapEntity> CreateInstance(Vector2 position, Submarine sub, bool selectPrefabs = false)
@@ -1398,7 +1398,7 @@ namespace Barotrauma
}
if (!suitablePositions.Any())
{
string errorMsg = "Could not find a suitable position of interest. (PositionType: " + positionType + ", minDistFromSubs: " + minDistFromSubs + ")\n" + Environment.StackTrace;
string errorMsg = "Could not find a suitable position of interest. (PositionType: " + positionType + ", minDistFromSubs: " + minDistFromSubs + ")\n" + Environment.StackTrace.CleanupStackTrace();
GameAnalyticsManager.AddErrorEventOnce("Level.TryGetInterestingPosition:PositionTypeNotFound", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
#if DEBUG
DebugConsole.ThrowError(errorMsg);
@@ -1418,7 +1418,7 @@ namespace Barotrauma
}
if (!farEnoughPositions.Any())
{
string errorMsg = "Could not find a position of interest far enough from the submarines. (PositionType: " + positionType + ", minDistFromSubs: " + minDistFromSubs + ")\n" + Environment.StackTrace;
string errorMsg = "Could not find a position of interest far enough from the submarines. (PositionType: " + positionType + ", minDistFromSubs: " + minDistFromSubs + ")\n" + Environment.StackTrace.CleanupStackTrace();
GameAnalyticsManager.AddErrorEventOnce("Level.TryGetInterestingPosition:TooCloseToSubs", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
#if DEBUG
DebugConsole.ThrowError(errorMsg);
@@ -132,7 +132,15 @@ namespace Barotrauma
public override MapEntity Clone()
{
return CreateDummy(Submarine, filePath, Position);
var path = filePath;
if (string.IsNullOrEmpty(path))
{
var linkedSubmarine = CreateDummy(Submarine, saveElement, Position);
linkedSubmarine.saveElement = saveElement;
return linkedSubmarine;
}
return CreateDummy(Submarine, path, Position);
}
private void GenerateWallVertices(XElement rootElement)
@@ -176,7 +184,7 @@ namespace Barotrauma
else
{
string levelSeed = element.GetAttributeString("location", "");
LevelData levelData = GameMain.GameSession.Campaign?.NextLevel ?? GameMain.GameSession.Level?.LevelData;
LevelData levelData = GameMain.GameSession.Campaign?.NextLevel ?? GameMain.GameSession.LevelData;
linkedSub = new LinkedSubmarine(submarine)
{
purchasedLostShuttles = GameMain.GameSession.GameMode is CampaignMode campaign && campaign.PurchasedLostShuttles,
@@ -424,12 +424,12 @@ namespace Barotrauma
{
if (!Type.HasHireableCharacters)
{
DebugConsole.ThrowError("Cannot hire a character from location \"" + Name + "\" - the location has no hireable characters.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Cannot hire a character from location \"" + Name + "\" - the location has no hireable characters.\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
if (HireManager == null)
{
DebugConsole.ThrowError("Cannot hire a character from location \"" + Name + "\" - hire manager has not been instantiated.\n" + Environment.StackTrace);
DebugConsole.ThrowError("Cannot hire a character from location \"" + Name + "\" - hire manager has not been instantiated.\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
@@ -524,12 +524,12 @@ namespace Barotrauma
{
if (SelectedConnection == null)
{
DebugConsole.ThrowError("Could not move to the next location (no connection selected).\n"+Environment.StackTrace);
DebugConsole.ThrowError("Could not move to the next location (no connection selected).\n"+Environment.StackTrace.CleanupStackTrace());
return;
}
if (SelectedLocation == null)
{
DebugConsole.ThrowError("Could not move to the next location (no location selected).\n" + Environment.StackTrace);
DebugConsole.ThrowError("Could not move to the next location (no location selected).\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
@@ -354,7 +354,7 @@ namespace Barotrauma
GameAnalyticsManager.AddErrorEventOnce(
"MapEntity.Clone:" + e.Name,
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Cloning entity \"" + e.Name + "\" failed (" + ex.Message + ").\n" + ex.StackTrace);
"Cloning entity \"" + e.Name + "\" failed (" + ex.Message + ").\n" + ex.StackTrace.CleanupStackTrace());
return clones;
}
Debug.Assert(clones.Last() != null);
@@ -284,7 +284,7 @@ namespace Barotrauma
if (showErrorMessages)
{
DebugConsole.ThrowError("Failed to find a matching MapEntityPrefab (name: \"" + name + "\", identifier: \"" + identifier + "\").\n" + Environment.StackTrace);
DebugConsole.ThrowError("Failed to find a matching MapEntityPrefab (name: \"" + name + "\", identifier: \"" + identifier + "\").\n" + Environment.StackTrace.CleanupStackTrace());
}
return null;
}
@@ -44,7 +44,7 @@ namespace Barotrauma
}
catch (Exception e)
{
DebugConsole.NewMessage($"Failed to load hash cache: {e.Message}\n{e.StackTrace}", Microsoft.Xna.Framework.Color.Orange);
DebugConsole.NewMessage($"Failed to load hash cache: {e.Message}\n{e.StackTrace.CleanupStackTrace()}", Microsoft.Xna.Framework.Color.Orange);
cache.Clear();
}
}
@@ -0,0 +1,22 @@
using FarseerPhysics;
using Microsoft.Xna.Framework;
namespace Barotrauma
{
class OrderTarget : ISpatialEntity
{
public Vector2 Position { get; private set; }
public Hull Hull { get; private set; }
public Vector2 WorldPosition => Submarine == null ? Position : Position + Submarine.Position;
public Vector2 SimPosition => ConvertUnits.ToSimUnits(Position);
public Submarine Submarine => Hull?.Submarine;
public OrderTarget(Vector2 position, Hull hull, bool creatingFromExistingData = false)
{
if (!creatingFromExistingData && hull?.Submarine != null) { position -= hull.Submarine.Position; }
Position = position;
Hull = hull;
}
}
}
@@ -1407,11 +1407,16 @@ namespace Barotrauma
if (item != null) { item.SpawnedInOutpost = true; }
}
npc.GiveIdCardTags(gotoTarget as WayPoint);
var humanAI = npc.AIController as HumanAIController;
if (humanAI != null)
if (npc.AIController is HumanAIController humanAI)
{
var idleObjective = humanAI.ObjectiveManager.GetObjective<AIObjectiveIdle>();
if (idleObjective != null)
if (humanPrefab.CampaignInteractionType != CampaignMode.InteractionType.None)
{
idleObjective.Behavior = AIObjectiveIdle.BehaviorType.StayInHull;
idleObjective.TargetHull = AIObjectiveGoTo.GetTargetHull(gotoTarget);
(GameMain.GameSession.GameMode as CampaignMode)?.AssignNPCMenuInteraction(npc, humanPrefab.CampaignInteractionType);
}
else
{
idleObjective.Behavior = humanPrefab.BehaviorType;
foreach (string moduleType in humanPrefab.PreferredOutpostModuleTypes)
@@ -1420,21 +1425,6 @@ namespace Barotrauma
}
}
}
if (humanPrefab.CampaignInteractionType != CampaignMode.InteractionType.None)
{
if (humanAI != null)
{
Hull goToHull = gotoTarget as Hull ?? (gotoTarget as WayPoint)?.CurrentHull ?? (gotoTarget as Item)?.CurrentHull;
var goToObjective = new AIObjectiveGoTo(gotoTarget, npc, humanAI.ObjectiveManager, repeat: true, getDivingGearIfNeeded: false, closeEnough: 200);
if (goToHull != null)
{
goToObjective.priorityGetter = () => npc.CurrentHull == goToHull ? 0.0f : AIObjectiveManager.OrderPriority;
}
humanAI.ObjectiveManager.SetOrder(goToObjective);
humanAI.ObjectiveManager.GetObjective<AIObjectiveIdle>().Behavior = AIObjectiveIdle.BehaviorType.StayInHull;
}
(GameMain.GameSession.GameMode as CampaignMode)?.AssignNPCMenuInteraction(npc, humanPrefab.CampaignInteractionType);
}
}
}
}
@@ -312,7 +312,7 @@ namespace Barotrauma
{
if (!MathUtils.IsValid(amount))
{
DebugConsole.ThrowError($"Attempted to move a structure by an invalid amount ({amount})\n{Environment.StackTrace}");
DebugConsole.ThrowError($"Attempted to move a structure by an invalid amount ({amount})\n{Environment.StackTrace.CleanupStackTrace()}");
return;
}
@@ -986,12 +986,20 @@ namespace Barotrauma
{
diffFromCenter = (gapRect.Center.X - this.rect.Center.X) / (float)this.rect.Width * BodyWidth;
if (BodyWidth > 0.0f) { gapRect.Width = (int)(BodyWidth * (gapRect.Width / (float)this.rect.Width)); }
if (BodyHeight > 0.0f) { gapRect.Height = (int)BodyHeight; }
if (BodyHeight > 0.0f)
{
gapRect.Y = (gapRect.Y - gapRect.Height / 2) + (int)(BodyHeight / 2 + BodyOffset.Y * scale);
gapRect.Height = (int)BodyHeight;
}
}
else
{
diffFromCenter = ((gapRect.Y - gapRect.Height / 2) - (this.rect.Y - this.rect.Height / 2)) / (float)this.rect.Height * BodyHeight;
if (BodyWidth > 0.0f) { gapRect.Width = (int)BodyWidth; }
if (BodyWidth > 0.0f)
{
gapRect.X = gapRect.Center.X + (int)(-BodyWidth / 2 + BodyOffset.X * scale);
gapRect.Width = (int)BodyWidth;
}
if (BodyHeight > 0.0f) { gapRect.Height = (int)(BodyHeight * (gapRect.Height / (float)this.rect.Height)); }
}
if (FlippedX) { diffFromCenter = -diffFromCenter; }
@@ -1001,7 +1009,7 @@ namespace Barotrauma
Vector2 structureCenter = Position;
Vector2 gapPos = structureCenter + new Vector2(
(float)Math.Cos(IsHorizontal ? -BodyRotation : MathHelper.PiOver2 - BodyRotation),
(float)Math.Sin(IsHorizontal ? -BodyRotation : MathHelper.PiOver2 - BodyRotation)) * diffFromCenter;
(float)Math.Sin(IsHorizontal ? -BodyRotation : MathHelper.PiOver2 - BodyRotation)) * diffFromCenter + BodyOffset * scale;
gapRect = new Rectangle((int)(gapPos.X - gapRect.Width / 2), (int)(gapPos.Y + gapRect.Height / 2), gapRect.Width, gapRect.Height);
}
@@ -661,7 +661,7 @@ namespace Barotrauma
catch (System.IO.FileNotFoundException e)
{
exception = e;
DebugConsole.ThrowError("Loading submarine \"" + file + "\" failed! (File not found) " + Environment.StackTrace, e);
DebugConsole.ThrowError("Loading submarine \"" + file + "\" failed! (File not found) " + Environment.StackTrace.CleanupStackTrace(), e);
return null;
}
catch (Exception e)
@@ -15,7 +15,7 @@ namespace Barotrauma.Networking
partial class ChatMessage
{
public const int MaxLength = 150;
public const int MaxLength = 200;
public const int MaxMessagesPerPacket = 10;
@@ -179,7 +179,7 @@ namespace Barotrauma
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return; }
if (itemPrefab == null)
{
string errorMsg = "Attempted to add a null item to entity spawn queue.\n" + Environment.StackTrace;
string errorMsg = "Attempted to add a null item to entity spawn queue.\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("EntitySpawner.AddToSpawnQueue1:ItemPrefabNull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return;
@@ -192,7 +192,7 @@ namespace Barotrauma
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return; }
if (itemPrefab == null)
{
string errorMsg = "Attempted to add a null item to entity spawn queue.\n" + Environment.StackTrace;
string errorMsg = "Attempted to add a null item to entity spawn queue.\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("EntitySpawner.AddToSpawnQueue2:ItemPrefabNull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return;
@@ -205,7 +205,7 @@ namespace Barotrauma
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return; }
if (itemPrefab == null)
{
string errorMsg = "Attempted to add a null item to entity spawn queue.\n" + Environment.StackTrace;
string errorMsg = "Attempted to add a null item to entity spawn queue.\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("EntitySpawner.AddToSpawnQueue3:ItemPrefabNull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return;
@@ -218,7 +218,7 @@ namespace Barotrauma
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return; }
if (string.IsNullOrEmpty(speciesName))
{
string errorMsg = "Attempted to add an empty/null species name to entity spawn queue.\n" + Environment.StackTrace;
string errorMsg = "Attempted to add an empty/null species name to entity spawn queue.\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("EntitySpawner.AddToSpawnQueue4:SpeciesNameNullOrEmpty", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return;
@@ -231,7 +231,7 @@ namespace Barotrauma
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return; }
if (string.IsNullOrEmpty(speciesName))
{
string errorMsg = "Attempted to add an empty/null species name to entity spawn queue.\n" + Environment.StackTrace;
string errorMsg = "Attempted to add an empty/null species name to entity spawn queue.\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("EntitySpawner.AddToSpawnQueue5:SpeciesNameNullOrEmpty", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return;
@@ -32,7 +32,7 @@ namespace Barotrauma.Networking
DebugConsole.ThrowError("Failed to write an event for the entity \"" + e.Entity + "\"", exception);
GameAnalyticsManager.AddErrorEventOnce("NetEntityEventManager.Write:WriteFailed" + e.Entity.ToString(),
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Failed to write an event for the entity \"" + e.Entity + "\"\n" + exception.StackTrace);
"Failed to write an event for the entity \"" + e.Entity + "\"\n" + exception.StackTrace.CleanupStackTrace());
//write an empty event to avoid messing up IDs
//(otherwise the clients might read the next event in the message and think its ID

Some files were not shown because too many files have changed in this diff Show More