Unstable v0.10.6.0 (October 13th 2020)

This commit is contained in:
Juan Pablo Arce
2020-10-13 12:59:45 -03:00
parent 768f516e7c
commit 6b36bf809d
59 changed files with 1036 additions and 421 deletions
@@ -3,7 +3,7 @@ using System.Collections.Generic;
namespace Barotrauma
{
public enum AIState { Idle, Attack, Escape, Eat, Flee, Avoid, Aggressive, PassiveAggressive, Protect, Observe, Freeze }
public enum AIState { Idle, Attack, Escape, Eat, Flee, Avoid, Aggressive, PassiveAggressive, Protect, Observe, Freeze, Follow }
abstract partial class AIController : ISteerable
{
@@ -48,13 +48,11 @@ namespace Barotrauma
private float attackLimbResetTimer;
private bool IsCoolDownRunning => AttackingLimb != null && AttackingLimb.attack.CoolDownTimer > 0;
public float CombatStrength => Character.Params.AI.CombatStrength;
private float Sight => Character.Params.AI.Sight;
private float Hearing => Character.Params.AI.Hearing;
private float FleeHealthThreshold => Character.Params.AI.FleeHealthThreshold;
private float AggressionGreed => Character.Params.AI.AggressionGreed;
private float AggressionHurt => Character.Params.AI.AggressionHurt;
private bool AggressiveBoarding => Character.Params.AI.AggressiveBoarding;
public float CombatStrength => AIParams.CombatStrength;
private float Sight => AIParams.Sight;
private float Hearing => AIParams.Hearing;
private float FleeHealthThreshold => AIParams.FleeHealthThreshold;
private bool AggressiveBoarding => AIParams.AggressiveBoarding;
private FishAnimController FishAnimController => Character.AnimController as FishAnimController;
@@ -90,7 +88,6 @@ namespace Barotrauma
private readonly float priorityFearIncreasement = 2;
private readonly float memoryFadeTime = 0.5f;
private readonly float avoidTime = 3;
private float avoidTimer;
private float observeTimer;
@@ -241,6 +238,10 @@ namespace Barotrauma
{
targetingTag = "dead";
}
else if (PetBehavior != null && aiTarget.Entity == PetBehavior.Owner)
{
targetingTag = "owner";
}
else if (AIParams.TryGetTarget(targetCharacter.SpeciesName, out CharacterParams.TargetParams tP))
{
targetingTag = tP.Tag;
@@ -384,7 +385,7 @@ namespace Barotrauma
{
updateTargetsTimer -= deltaTime;
}
else
else if (avoidTimer <= 0)
{
CharacterParams.TargetParams targetingParams = null;
UpdateTargets(Character, out targetingParams);
@@ -393,11 +394,7 @@ namespace Barotrauma
UpdateWallTarget();
}
updateTargetsTimer = updateTargetsInterval * Rand.Range(0.75f, 1.25f);
if (avoidTimer > 0)
{
State = AIState.Escape;
}
else if (SelectedAiTarget == null)
if (SelectedAiTarget == null)
{
State = AIState.Idle;
}
@@ -502,17 +499,21 @@ namespace Barotrauma
}
break;
case AIState.Protect:
case AIState.Follow:
if (SelectedAiTarget == null || SelectedAiTarget.Entity == null || SelectedAiTarget.Entity.Removed)
{
State = AIState.Idle;
return;
}
if (SelectedAiTarget.Entity is Character targetCharacter && targetCharacter.LastAttacker is Character attacker && !attacker.Removed && !attacker.IsDead)
if (State == AIState.Protect)
{
// Attack the character that attacked the target we are protecting
ChangeTargetState(attacker, AIState.Attack, selectedTargetingParams.Priority * 2);
SelectTarget(attacker.AiTarget);
return;
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);
SelectTarget(attacker.AiTarget);
return;
}
}
float sqrDist = Vector2.DistanceSquared(WorldPosition, SelectedAiTarget.WorldPosition);
float reactDist = selectedTargetingParams != null && selectedTargetingParams.ReactDistance > 0 ? selectedTargetingParams.ReactDistance : GetPerceivingRange(SelectedAiTarget);
@@ -568,6 +569,7 @@ namespace Barotrauma
}
else
{
// TODO: doesn't work right here
FaceTarget(SelectedAiTarget.Entity);
}
observeTimer -= deltaTime;
@@ -592,7 +594,6 @@ namespace Barotrauma
if (!Character.AnimController.SimplePhysicsEnabled)
{
LatchOntoAI?.Update(this, deltaTime);
PetBehavior?.Update(deltaTime);
}
IsSteeringThroughGap = false;
if (SwarmBehavior != null)
@@ -1454,7 +1455,8 @@ namespace Barotrauma
bool isFriendly = IsFriendly(Character, attacker);
if (wasLatched)
{
avoidTimer = avoidTime * Rand.Range(0.75f, 1.25f);
State = AIState.Escape;
avoidTimer = AIParams.AvoidTime * Rand.Range(0.75f, 1.25f);
if (!isFriendly)
{
SelectTarget(attacker.AiTarget);
@@ -1527,7 +1529,7 @@ namespace Barotrauma
}
AITargetMemory targetMemory = GetTargetMemory(attacker.AiTarget, true);
targetMemory.Priority += GetRelativeDamage(attackResult.Damage, Character.Vitality) * AggressionHurt;
targetMemory.Priority += GetRelativeDamage(attackResult.Damage, Character.Vitality) * AIParams.AggressionHurt;
// Only allow to react once. Otherwise would attack the target with only a fraction of a cooldown
bool retaliate = !isFriendly && SelectedAiTarget != attacker.AiTarget && attacker.Submarine == Character.Submarine;
@@ -1552,12 +1554,14 @@ namespace Barotrauma
}
else if (avoidGunFire)
{
avoidTimer = avoidTime * Rand.Range(0.75f, 1.25f);
State = AIState.Escape;
avoidTimer = AIParams.AvoidTime * Rand.Range(0.75f, 1.25f);
SelectTarget(attacker.AiTarget);
}
if (Character.HealthPercentage <= FleeHealthThreshold)
{
avoidTimer = Rand.Range(15, 30);
State = AIState.Flee;
avoidTimer = AIParams.MinFleeTime * Rand.Range(0.75f, 1.25f);
SelectTarget(attacker.AiTarget);
}
}
@@ -1587,7 +1591,7 @@ namespace Barotrauma
if (damageTarget.Health > 0)
{
// Managed to hit a living/non-destroyed target. Increase the priority more if the target is low in health -> dies easily/soon
selectedTargetMemory.Priority += GetRelativeDamage(attackResult.Damage, damageTarget.Health) * AggressionGreed;
selectedTargetMemory.Priority += GetRelativeDamage(attackResult.Damage, damageTarget.Health) * AIParams.AggressionGreed;
}
else
{
@@ -1654,10 +1658,13 @@ namespace Barotrauma
if (!item.Removed && item.body != null)
{
float itemBodyExtent = item.body.GetMaxExtent() * 2;
if (limbDiff.LengthSquared() < itemBodyExtent * itemBodyExtent)
if (Math.Abs(limbDiff.X) < itemBodyExtent &&
Math.Abs(limbDiff.Y) < Character.AnimController.Collider.GetMaxExtent() + Character.AnimController.ColliderHeightFromFloor)
{
item.body.LinearVelocity *= 0.9f;
item.body.LinearVelocity -= limbDiff * 0.25f;
item.AddDamage(Character, item.WorldPosition, new Attack(0.0f, 0.0f, 0.0f, 0.0f, 0.1f), deltaTime);
item.body.ApplyForce(-limbDiff * item.body.Mass);
if (item.Condition <= 0.0f)
{
@@ -1697,15 +1704,40 @@ namespace Barotrauma
State = AIState.Idle;
return;
}
Vector2 dir = Vector2.Normalize(SelectedAiTarget.Entity.WorldPosition - Character.WorldPosition);
if (!MathUtils.IsValid(dir))
if (Character.CurrentHull != null && PathSteering != null)
{
return;
// Inside
Character targetCharacter = SelectedAiTarget.Entity as Character;
if ((Character.AnimController.InWater || !Character.AnimController.CanWalk) &&
(targetCharacter != null && VisibleHulls.Contains(targetCharacter.CurrentHull) || Character.CanSeeTarget(SelectedAiTarget.Entity)))
{
// Steer towards the target if in the same room and swimming
Vector2 dir = Vector2.Normalize(SelectedAiTarget.Entity.WorldPosition - Character.WorldPosition);
if (MathUtils.IsValid(dir))
{
SteeringManager.SteeringManual(deltaTime, dir);
}
}
else
{
// Use path finding
SteeringManager.SteeringSeek(Character.GetRelativeSimPosition(SelectedAiTarget.Entity), 2);
if (!PathSteering.IsPathDirty && PathSteering.CurrentPath.Unreachable)
{
// Can't reach
State = AIState.Idle;
return;
}
}
}
SteeringManager.SteeringSeek(Character.GetRelativeSimPosition(SelectedAiTarget.Entity), 5);
if (Character.AnimController.InWater)
else
{
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: avoidLookAheadDistance, weight: 15);
// Outside
SteeringManager.SteeringSeek(Character.GetRelativeSimPosition(SelectedAiTarget.Entity), 5);
if (Character.AnimController.InWater)
{
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: avoidLookAheadDistance, weight: 15);
}
}
}
@@ -1748,6 +1780,10 @@ namespace Barotrauma
{
targetingTag = "dead";
}
else if (PetBehavior != null && aiTarget.Entity == PetBehavior.Owner)
{
targetingTag = "owner";
}
else if (AIParams.TryGetTarget(targetCharacter.SpeciesName, out CharacterParams.TargetParams tP))
{
targetingTag = tP.Tag;
@@ -1992,9 +2028,16 @@ namespace Barotrauma
if (targetingTag == null) { continue; }
var targetParams = GetTargetParams(targetingTag);
if (targetParams == null) { continue; }
if (targetCharacter != null && targetCharacter.Submarine != Character.Submarine && targetParams.State == AIState.Observe)
if (targetParams.State == AIState.Observe || targetParams.State == AIState.Eat)
{
if (targetCharacter != null && targetCharacter.Submarine != Character.Submarine)
{
// Don't allow to target characters that are inside a different submarine / outside when we are inside.
continue;
}
}
if (aiTarget.Entity is Item targetItem && targetParams.IgnoreContained && targetItem.ParentInventory != null)
{
// Don't allow to observe characters that are inside a different submarine / outside when we are inside.
continue;
}
valueModifier *= targetParams.Priority;
@@ -2066,6 +2109,17 @@ namespace Barotrauma
}
if (targetCharacter != null)
{
if (Character.CurrentHull != null && targetCharacter.CurrentHull != Character.CurrentHull)
{
if (targetParams.State == AIState.Follow || targetParams.State == AIState.Protect || targetParams.State == AIState.Observe)
{
// Ignore targets that cannot see
if (!VisibleHulls.Contains(targetCharacter.CurrentHull))
{
continue;
}
}
}
if (targetCharacter.Submarine != Character.Submarine)
{
if (targetCharacter.Submarine != null)
@@ -1111,7 +1111,10 @@ namespace Barotrauma
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; }
if (item.ParentInventory is ItemInventory itemInventory)
{
if (!itemInventory.Container.HasRequiredItems(Character, addMessage: false)) { return false; }
}
if (equip)
{
int targetSlot = -1;
@@ -190,6 +190,7 @@ namespace Barotrauma
}
}
pathFinder.InsideSubmarine = character.Submarine != null;
pathFinder.ApplyPenaltyToOutsideNodes = character.PressureProtection <= 0;
var newPath = pathFinder.FindPath(currentPos, target, character.Submarine, "(Character: " + character.Name + ")", startNodeFilter, endNodeFilter, nodeFilter, checkVisibility: checkVisibility);
bool useNewPath = needsNewPath || currentPath == null || currentPath.CurrentNode == null || findPathTimer < -1;
if (!useNewPath && currentPath != null && currentPath.CurrentNode != null && newPath.Nodes.Any() && !newPath.Unreachable)
@@ -343,7 +344,7 @@ namespace Barotrauma
}
return diff;
}
else if (!canClimb || character.AnimController.InWater)
else if (character.AnimController.InWater)
{
// If the character is underwater, we don't need the ladders anymore
if (character.IsClimbing && isDiving)
@@ -370,7 +371,7 @@ namespace Barotrauma
}
}
}
else if (!IsNextLadderSameAsCurrent)
else if (!canClimb || !IsNextLadderSameAsCurrent)
{
// Walking horizontally
Vector2 colliderBottom = character.AnimController.GetColliderBottom();
@@ -378,6 +379,8 @@ namespace Barotrauma
Vector2 velocity = collider.LinearVelocity;
// If the character is smaller than this, it would fail to use the waypoint nodes because they are always too high.
float minHeight = 1;
// If the character is very thin, without a min value, it would often fail to reach the waypoints, because the horizontal distance is too small.
float minWidth = 0.17f;
// Cannot use the head position, because not all characters have head or it can be below the total height of the character
float characterHeight = Math.Max(colliderSize.Y + character.AnimController.ColliderHeightFromFloor, minHeight);
float horizontalDistance = Math.Abs(collider.SimPosition.X - currentPath.CurrentNode.SimPosition.X);
@@ -386,7 +389,7 @@ namespace Barotrauma
var door = currentPath.CurrentNode.ConnectedDoor;
bool blockedByDoor = door != null && !door.IsOpen && !door.IsBroken;
float margin = MathHelper.Lerp(1, 10, MathHelper.Clamp(Math.Abs(velocity.X) / 10, 0, 1));
float targetDistance = collider.radius * margin;
float targetDistance = Math.Max(collider.radius * margin, minWidth);
if (horizontalDistance < targetDistance && isAboveFeet && isNotTooHigh && !blockedByDoor)
{
currentPath.SkipToNextNode();
@@ -204,11 +204,15 @@ namespace Barotrauma
{
// Don't ignore any hulls if outside, because apparently it happens that we can't find a path, in which case we just want to try again.
// If we ignore the hull, it might be the only airlock in the target sub, which ignores the whole sub.
if (currentHull != null && goToObjective != null)
// If the target hull is inside a submarine that is not our main sub, just ignore it normally when it cannot be reached. This happens with outposts.
if (goToObjective != null)
{
if (goToObjective.Target is Hull hull)
{
HumanAIController.UnreachableHulls.Add(hull);
if (currentHull != null || !Submarine.MainSubs.Contains(hull.Submarine))
{
HumanAIController.UnreachableHulls.Add(hull);
}
}
}
RemoveSubObjective(ref goToObjective);
@@ -257,6 +257,10 @@ namespace Barotrauma
// 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; }
if (item.ParentInventory is ItemInventory itemInventory)
{
if (!itemInventory.Container.HasRequiredItems(character, addMessage: false)) { continue; }
}
float itemPriority = 1;
if (GetItemPriority != null)
{
@@ -342,7 +342,7 @@ namespace Barotrauma
SteeringManager.SteeringManual(deltaTime, Vector2.Normalize(Target.WorldPosition - character.WorldPosition));
if (character.AnimController.InWater)
{
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: 5, weight: 15);
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: 5, weight: 2);
}
}
}
@@ -360,7 +360,10 @@ namespace Barotrauma
else
{
SteeringManager.SteeringSeek(character.GetRelativeSimPosition(Target), 10);
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: 5, weight: 15);
if (character.AnimController.InWater)
{
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: 5, weight: 15);
}
}
}
}
@@ -94,6 +94,7 @@ namespace Barotrauma
private readonly List<PathNode> nodes;
public bool InsideSubmarine { get; set; }
public bool ApplyPenaltyToOutsideNodes { get; set; }
public PathFinder(List<WayPoint> wayPoints, bool indoorsSteering = false)
{
@@ -178,7 +179,7 @@ namespace Barotrauma
node.TempDistance = xDiff + (InsideSubmarine ? yDiff * 10.0f : yDiff); //higher cost for vertical movement when inside the sub
//much higher cost to waypoints that are outside
if (node.Waypoint.CurrentHull == null && InsideSubmarine) { node.TempDistance *= 10.0f; }
if (node.Waypoint.CurrentHull == null && ApplyPenaltyToOutsideNodes) { node.TempDistance *= 10.0f; }
//prefer nodes that are closer to the end position
node.TempDistance += (Math.Abs(end.X - node.TempPosition.X) + Math.Abs(end.Y - node.TempPosition.Y)) / 100.0f;
@@ -231,8 +232,11 @@ namespace Barotrauma
node.TempDistance = Vector2.DistanceSquared(end, node.TempPosition);
if (InsideSubmarine)
{
//much higher cost to waypoints that are outside
if (node.Waypoint.CurrentHull == null) { node.TempDistance *= 10.0f; }
if (ApplyPenaltyToOutsideNodes)
{
//much higher cost to waypoints that are outside
if (node.Waypoint.CurrentHull == null) { node.TempDistance *= 10.0f; }
}
//avoid stopping at a doorway
if (node.Waypoint.ConnectedDoor != null) { node.TempDistance *= 10.0f; }
//avoid stopping at a ladder
@@ -1,3 +1,4 @@
using Barotrauma.Extensions;
using Barotrauma.Items.Components;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
@@ -9,6 +10,14 @@ namespace Barotrauma
{
class PetBehavior
{
public enum StatusIndicatorType
{
None,
Happy,
Sad,
Hungry
}
public float Hunger { get; set; } = 50.0f;
public float Happiness { get; set; } = 50.0f;
@@ -21,6 +30,7 @@ namespace Barotrauma
public float PlayForce { get; set; }
public float PlayTimer { get; set; }
private float? unstunY { get; set; }
public EnemyAIController AiController { get; private set; } = null;
@@ -126,6 +136,7 @@ namespace Barotrauma
public float Hunger;
public float Happiness;
public float Priority;
public bool IgnoreContained;
public CharacterParams.TargetParams TargetParams = null;
}
@@ -159,7 +170,11 @@ namespace Barotrauma
case "eat":
Food food = new Food
{
Tag = subElement.GetAttributeString("tag", "")
Tag = subElement.GetAttributeString("tag", ""),
Hunger = subElement.GetAttributeFloat("hunger", -1),
Happiness = subElement.GetAttributeFloat("happiness", 1),
Priority = subElement.GetAttributeFloat("priority", 100),
IgnoreContained = subElement.GetAttributeBool("ignorecontained", true)
};
string[] requiredHungerStr = subElement.GetAttributeString("requiredhunger", "0-100").Split('-');
food.HungerRange = new Vector2(0, 100);
@@ -168,15 +183,20 @@ namespace Barotrauma
if (float.TryParse(requiredHungerStr[0], NumberStyles.Any, CultureInfo.InvariantCulture, out float tempF)) { food.HungerRange.X = tempF; }
if (float.TryParse(requiredHungerStr[1], NumberStyles.Any, CultureInfo.InvariantCulture, out tempF)) { food.HungerRange.Y = tempF; }
}
food.Hunger = subElement.GetAttributeFloat("hunger", -1);
food.Happiness = subElement.GetAttributeFloat("happiness", 1);
food.Priority = subElement.GetAttributeFloat("priority", 100);
foods.Add(food);
break;
}
}
}
public StatusIndicatorType GetCurrentStatusIndicatorType()
{
if (Hunger > MaxHunger * 0.5f) { return StatusIndicatorType.Hungry; }
if (Happiness > MaxHappiness * 0.75f) { return StatusIndicatorType.Happy; }
if (Happiness < MaxHappiness * 0.25f) { return StatusIndicatorType.Sad; }
return StatusIndicatorType.None;
}
public void OnEat(IEnumerable<string> tags, float amount)
{
for (int i = 0; i < foods.Count; i++)
@@ -203,17 +223,19 @@ namespace Barotrauma
}
}
public void Play()
public void Play(Character player)
{
if (PlayTimer > 0.0f) { return; }
if (Owner == null) { Owner = player; }
PlayTimer = 5.0f;
AiController.Character.Stun = 1.0f;
AiController.Character.IsRagdolled = true;
Happiness += 10.0f;
if (Happiness > MaxHappiness) { Happiness = MaxHappiness; }
AiController.Character.AnimController.MainLimb.body.LinearVelocity += new Vector2(0, PlayForce);
unstunY = AiController.Character.SimPosition.Y;
}
public string GetName()
public string GetTagName()
{
if (AiController.Character.Inventory != null)
{
@@ -230,14 +252,16 @@ namespace Barotrauma
}
}
return AiController.Character.Name;
return string.Empty;
}
public void Update(float deltaTime)
{
var character = AiController.Character;
if (character?.Removed ?? true || character.IsDead) { return; }
if (GameMain.NetworkMember?.IsClient ?? false) { return; } //TODO: syncing
if (GameMain.NetworkMember?.IsClient ?? false) { return; }
if (Owner != null && (Owner.Removed || Owner.IsDead)) { Owner = null; }
Hunger += HungerIncreaseRate * deltaTime;
@@ -245,20 +269,45 @@ namespace Barotrauma
PlayTimer -= deltaTime;
for (int i = 0; i < foods.Count; i++)
if (unstunY.HasValue)
{
if (Hunger >= foods[i].HungerRange.X && Hunger <= foods[i].HungerRange.Y)
if (PlayTimer > 4.0f)
{
if (foods[i].TargetParams == null &&
AiController.AIParams.TryAddNewTarget(foods[i].Tag, AIState.Eat, foods[i].Priority, out CharacterParams.TargetParams targetParams))
float extent = character.AnimController.MainLimb.body.GetMaxExtent();
if (character.SimPosition.Y < (unstunY.Value + extent * 3.0f) &&
character.AnimController.MainLimb.body.LinearVelocity.Y < 0.0f)
{
foods[i].TargetParams = targetParams;
character.IsRagdolled = false;
unstunY = null;
}
else
{
character.IsRagdolled = true;
}
}
else if (foods[i].TargetParams != null)
else
{
AiController.AIParams.RemoveTarget(foods[i].TargetParams);
foods[i].TargetParams = null;
character.IsRagdolled = false;
unstunY = null;
}
}
for (int i = 0; i < foods.Count; i++)
{
Food food = foods[i];
if (Hunger >= food.HungerRange.X && Hunger <= food.HungerRange.Y)
{
if (food.TargetParams == null &&
AiController.AIParams.TryAddNewTarget(food.Tag, AIState.Eat, food.Priority, out CharacterParams.TargetParams targetParams))
{
targetParams.IgnoreContained = food.IgnoreContained;
food.TargetParams = targetParams;
}
}
else if (food.TargetParams != null)
{
AiController.AIParams.RemoveTarget(food.TargetParams);
food.TargetParams = null;
}
}
@@ -279,7 +328,8 @@ namespace Barotrauma
if (character.SelectedBy != null)
{
character.Stun = 1.0f;
character.IsRagdolled = true;
unstunY = character.SimPosition.Y;
}
for (int i = 0; i < itemsToProduce.Count; i++)
@@ -287,5 +337,73 @@ namespace Barotrauma
itemsToProduce[i].Update(this, deltaTime);
}
}
public static void SavePets(XElement petsElement)
{
foreach (Character c in Character.CharacterList)
{
if (!c.IsPet || c.IsDead) { continue; }
if (c.Submarine?.Info.Type != SubmarineType.Player) { continue; }
var petBehavior = (c.AIController as EnemyAIController)?.PetBehavior;
if (petBehavior == null) { continue; }
XElement petElement = new XElement("pet",
new XAttribute("speciesname", c.SpeciesName),
new XAttribute("ownerid", petBehavior.Owner?.ID ?? Entity.NullEntityID),
new XAttribute("seed", c.Seed));
var petBehaviorElement = new XElement("petbehavior",
new XAttribute("hunger", petBehavior.Hunger.ToString("G", CultureInfo.InvariantCulture)),
new XAttribute("happiness", petBehavior.Happiness.ToString("G", CultureInfo.InvariantCulture)));
petElement.Add(petBehaviorElement);
var healthElement = new XElement("health");
c.CharacterHealth.Save(healthElement);
petElement.Add(healthElement);
if (c.Inventory != null)
{
var inventoryElement = new XElement("inventory");
c.SaveInventory(c.Inventory, inventoryElement);
petElement.Add(inventoryElement);
}
petsElement.Add(petElement);
}
}
public static void LoadPets(XElement petsElement)
{
foreach (XElement subElement in petsElement.Elements())
{
string speciesName = subElement.GetAttributeString("speciesname", "");
string seed = subElement.GetAttributeString("seed", "123");
ushort ownerID = (ushort)subElement.GetAttributeInt("ownerid", 0);
Vector2 spawnPos = Vector2.Zero;
Character owner = Entity.FindEntityByID(ownerID) as Character;
if (owner != null)
{
spawnPos = owner.WorldPosition;
}
else
{
var spawnPoint = WayPoint.WayPointList.Where(wp => wp.SpawnType == SpawnType.Human && wp.Submarine?.Info.Type == SubmarineType.Player).GetRandom();
spawnPos = spawnPoint?.WorldPosition ?? Submarine.MainSub.WorldPosition;
}
var pet = Character.Create(speciesName, spawnPos, seed);
var petBehavior = (pet.AIController as EnemyAIController)?.PetBehavior;
if (petBehavior != null)
{
petBehavior.Owner = owner;
var petBehaviorElement = subElement.Attribute("petbehavior");
if (petBehaviorElement != null)
{
petBehavior.Hunger = petBehaviorElement.GetAttributeFloat(50.0f);
petBehavior.Happiness = petBehaviorElement.GetAttributeFloat(50.0f);
}
}
}
}
}
}