Move faction exception and everything it needs to shared (#25154)

* move faction prototype to shared

* move faction exception and member stuff to shared

* fix breaking changes for random stuff

* move pettable friend stuff to shared

* mostly fix

* final fixy

* dragonops

* final fixy II

* use querys and fix warpspeed fish (probably)

* fixer

* Rrrr!

---------

Co-authored-by: deltanedas <@deltanedas:kde.org>
Co-authored-by: metalgearsloth <comedian_vs_clown@hotmail.com>
This commit is contained in:
deltanedas
2024-03-18 07:23:25 +00:00
committed by GitHub
parent 0493130591
commit 7561bef6a7
29 changed files with 448 additions and 407 deletions

View File

@@ -1,23 +0,0 @@
using Content.Server.NPC.Systems;
namespace Content.Server.NPC.Components;
/// <summary>
/// Prevents an NPC from attacking ignored entities from enemy factions.
/// Can be added to if pettable, see PettableFriendComponent.
/// </summary>
[RegisterComponent, Access(typeof(NpcFactionSystem))]
public sealed partial class FactionExceptionComponent : Component
{
/// <summary>
/// Collection of entities that this NPC will refuse to attack
/// </summary>
[DataField("ignored")]
public HashSet<EntityUid> Ignored = new();
/// <summary>
/// Collection of entities that this NPC will attack, regardless of faction.
/// </summary>
[DataField("hostiles")]
public HashSet<EntityUid> Hostiles = new();
}

View File

@@ -1,16 +0,0 @@
using Content.Server.NPC.Systems;
namespace Content.Server.NPC.Components;
/// <summary>
/// This is used for tracking entities stored in <see cref="FactionExceptionComponent"/>
/// </summary>
[RegisterComponent, Access(typeof(NpcFactionSystem))]
public sealed partial class FactionExceptionTrackerComponent : Component
{
/// <summary>
/// entities with <see cref="FactionExceptionComponent"/> that are tracking this entity.
/// </summary>
[DataField("entities")]
public HashSet<EntityUid> Entities = new();
}

View File

@@ -1,29 +0,0 @@
using Content.Server.NPC.Systems;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype.Set;
namespace Content.Server.NPC.Components
{
[RegisterComponent]
[Access(typeof(NpcFactionSystem))]
public sealed partial class NpcFactionMemberComponent : Component
{
/// <summary>
/// Factions this entity is a part of.
/// </summary>
[ViewVariables(VVAccess.ReadWrite),
DataField("factions", customTypeSerializer:typeof(PrototypeIdHashSetSerializer<NpcFactionPrototype>))]
public HashSet<string> Factions = new();
/// <summary>
/// Cached friendly factions.
/// </summary>
[ViewVariables]
public readonly HashSet<string> FriendlyFactions = new();
/// <summary>
/// Cached hostile factions.
/// </summary>
[ViewVariables]
public readonly HashSet<string> HostileFactions = new();
}
}

View File

@@ -1,22 +0,0 @@
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype.List;
namespace Content.Server.NPC.Components
{
/// <summary>
/// Contains data about this faction's relations with other factions.
/// </summary>
[Prototype("npcFaction")]
public sealed partial class NpcFactionPrototype : IPrototype
{
[ViewVariables]
[IdDataField]
public string ID { get; private set; } = default!;
[ViewVariables(VVAccess.ReadWrite), DataField("friendly", customTypeSerializer:typeof(PrototypeIdListSerializer<NpcFactionPrototype>))]
public List<string> Friendly = new();
[ViewVariables(VVAccess.ReadWrite), DataField("hostile", customTypeSerializer:typeof(PrototypeIdListSerializer<NpcFactionPrototype>))]
public List<string> Hostile = new();
}
}

View File

@@ -1,13 +0,0 @@
namespace Content.Server.NPC;
/// <summary>
/// Cached data for the faction prototype. Can be modified at runtime.
/// </summary>
public sealed class FactionData
{
[ViewVariables]
public HashSet<string> Friendly = new();
[ViewVariables]
public HashSet<string> Hostile = new();
}

View File

@@ -1,7 +1,9 @@
using Content.Server.NPC.Components;
using Content.Server.NPC.Components;
using Content.Shared.CombatMode;
using Content.Shared.Damage;
using Content.Shared.Mobs.Components;
using Content.Shared.NPC.Components;
using Content.Shared.NPC.Systems;
using Robust.Shared.Collections;
using Robust.Shared.Timing;
@@ -22,37 +24,35 @@ public sealed class NPCRetaliationSystem : EntitySystem
SubscribeLocalEvent<NPCRetaliationComponent, DisarmedEvent>(OnDisarmed);
}
private void OnDamageChanged(EntityUid uid, NPCRetaliationComponent component, DamageChangedEvent args)
private void OnDamageChanged(Entity<NPCRetaliationComponent> ent, ref DamageChangedEvent args)
{
if (!args.DamageIncreased)
return;
if (args.Origin is not { } origin)
if (args.Origin is not {} origin)
return;
TryRetaliate(uid, origin, component);
TryRetaliate(ent, origin);
}
private void OnDisarmed(EntityUid uid, NPCRetaliationComponent component, DisarmedEvent args)
private void OnDisarmed(Entity<NPCRetaliationComponent> ent, ref DisarmedEvent args)
{
TryRetaliate(uid, args.Source, component);
TryRetaliate(ent, args.Source);
}
public bool TryRetaliate(EntityUid uid, EntityUid target, NPCRetaliationComponent? component = null)
public bool TryRetaliate(Entity<NPCRetaliationComponent> ent, EntityUid target)
{
if (!Resolve(uid, ref component))
return false;
// don't retaliate against inanimate objects.
if (!HasComp<MobStateComponent>(target))
return false;
if (_npcFaction.IsEntityFriendly(uid, target))
// don't retaliate against the same faction
if (_npcFaction.IsEntityFriendly(ent.Owner, target))
return false;
_npcFaction.AggroEntity(uid, target);
if (component.AttackMemoryLength is { } memoryLength)
component.AttackMemories[target] = _timing.CurTime + memoryLength;
_npcFaction.AggroEntity(ent.Owner, target);
if (ent.Comp.AttackMemoryLength is {} memoryLength)
ent.Comp.AttackMemories[target] = _timing.CurTime + memoryLength;
return true;
}
@@ -64,12 +64,14 @@ public sealed class NPCRetaliationSystem : EntitySystem
var query = EntityQueryEnumerator<NPCRetaliationComponent, FactionExceptionComponent>();
while (query.MoveNext(out var uid, out var retaliationComponent, out var factionException))
{
// TODO: can probably reuse this allocation and clear it
foreach (var entity in new ValueList<EntityUid>(retaliationComponent.AttackMemories.Keys))
{
if (!TerminatingOrDeleted(entity) && _timing.CurTime < retaliationComponent.AttackMemories[entity])
continue;
_npcFaction.DeAggroEntity(uid, entity, factionException);
_npcFaction.DeAggroEntity((uid, factionException), entity);
// TODO: should probably remove the AttackMemory, thats the whole point of the ValueList right??
}
}
}

View File

@@ -582,7 +582,7 @@ public sealed partial class NPCSteeringSystem
(mask & otherBody.CollisionLayer) == 0x0 &&
(layer & otherBody.CollisionMask) == 0x0 ||
!_factionQuery.TryGetComponent(ent, out var otherFaction) ||
!_npcFaction.IsEntityFriendly(uid, ent, ourFaction, otherFaction) ||
!_npcFaction.IsEntityFriendly((uid, ourFaction), (ent, otherFaction)) ||
// Use <= 0 so we ignore stationary friends in case.
Vector2.Dot(otherBody.LinearVelocity, ourVelocity) <= 0f)
{

View File

@@ -13,6 +13,8 @@ using Content.Shared.Interaction;
using Content.Shared.Movement.Components;
using Content.Shared.Movement.Systems;
using Content.Shared.NPC;
using Content.Shared.NPC.Components;
using Content.Shared.NPC.Systems;
using Content.Shared.NPC.Events;
using Content.Shared.Physics;
using Content.Shared.Weapons.Melee;

View File

@@ -12,6 +12,7 @@ using Content.Shared.Fluids.Components;
using Content.Shared.Hands.Components;
using Content.Shared.Inventory;
using Content.Shared.Mobs.Systems;
using Content.Shared.NPC.Systems;
using Content.Shared.Nutrition.Components;
using Content.Shared.Tools.Systems;
using Content.Shared.Weapons.Melee;

View File

@@ -1,130 +0,0 @@
using System.Linq;
using Content.Server.NPC.Components;
namespace Content.Server.NPC.Systems;
/// <summary>
/// Prevents an NPC from attacking some entities from an enemy faction.
/// </summary>
public sealed partial class NpcFactionSystem
{
private EntityQuery<FactionExceptionComponent> _exceptionQuery;
private EntityQuery<FactionExceptionTrackerComponent> _trackerQuery;
public void InitializeException()
{
_exceptionQuery = GetEntityQuery<FactionExceptionComponent>();
_trackerQuery = GetEntityQuery<FactionExceptionTrackerComponent>();
SubscribeLocalEvent<FactionExceptionComponent, ComponentShutdown>(OnShutdown);
SubscribeLocalEvent<FactionExceptionTrackerComponent, ComponentShutdown>(OnTrackerShutdown);
}
private void OnShutdown(EntityUid uid, FactionExceptionComponent component, ComponentShutdown args)
{
foreach (var ent in component.Hostiles)
{
if (!_trackerQuery.TryGetComponent(ent, out var trackerComponent))
continue;
trackerComponent.Entities.Remove(uid);
}
foreach (var ent in component.Ignored)
{
if (!_trackerQuery.TryGetComponent(ent, out var trackerComponent))
continue;
trackerComponent.Entities.Remove(uid);
}
}
private void OnTrackerShutdown(EntityUid uid, FactionExceptionTrackerComponent component, ComponentShutdown args)
{
foreach (var ent in component.Entities)
{
if (!_exceptionQuery.TryGetComponent(ent, out var exceptionComponent))
continue;
exceptionComponent.Ignored.Remove(uid);
exceptionComponent.Hostiles.Remove(uid);
}
}
/// <summary>
/// Returns whether the entity from an enemy faction won't be attacked
/// </summary>
public bool IsIgnored(EntityUid uid, EntityUid target, FactionExceptionComponent? comp = null)
{
if (!Resolve(uid, ref comp, false))
return false;
return comp.Ignored.Contains(target);
}
/// <summary>
/// Returns the specific hostile entities for a given entity.
/// </summary>
public IEnumerable<EntityUid> GetHostiles(EntityUid uid, FactionExceptionComponent? comp = null)
{
if (!Resolve(uid, ref comp, false))
return Array.Empty<EntityUid>();
return comp.Hostiles;
}
/// <summary>
/// Prevents an entity from an enemy faction from being attacked
/// </summary>
public void IgnoreEntity(EntityUid uid, EntityUid target, FactionExceptionComponent? comp = null)
{
comp ??= EnsureComp<FactionExceptionComponent>(uid);
comp.Ignored.Add(target);
EnsureComp<FactionExceptionTrackerComponent>(target).Entities.Add(uid);
}
/// <summary>
/// Prevents a list of entities from an enemy faction from being attacked
/// </summary>
public void IgnoreEntities(EntityUid uid, IEnumerable<EntityUid> ignored, FactionExceptionComponent? comp = null)
{
comp ??= EnsureComp<FactionExceptionComponent>(uid);
foreach (var ignore in ignored)
{
IgnoreEntity(uid, ignore, comp);
}
}
/// <summary>
/// Makes an entity always be considered hostile.
/// </summary>
public void AggroEntity(EntityUid uid, EntityUid target, FactionExceptionComponent? comp = null)
{
comp ??= EnsureComp<FactionExceptionComponent>(uid);
comp.Hostiles.Add(target);
EnsureComp<FactionExceptionTrackerComponent>(target).Entities.Add(uid);
}
/// <summary>
/// Makes an entity no longer be considered hostile, if it was.
/// Doesn't apply to regular faction hostilities.
/// </summary>
public void DeAggroEntity(EntityUid uid, EntityUid target, FactionExceptionComponent? comp = null)
{
if (!Resolve(uid, ref comp, false))
return;
if (!comp.Hostiles.Remove(target) || !_trackerQuery.TryGetComponent(target, out var tracker))
return;
tracker.Entities.Remove(uid);
}
/// <summary>
/// Makes a list of entities no longer be considered hostile, if it was.
/// Doesn't apply to regular faction hostilities.
/// </summary>
public void AggroEntities(EntityUid uid, IEnumerable<EntityUid> entities, FactionExceptionComponent? comp = null)
{
comp ??= EnsureComp<FactionExceptionComponent>(uid);
foreach (var ent in entities)
{
AggroEntity(uid, ent, comp);
}
}
}

View File

@@ -1,271 +0,0 @@
using System.Collections.Frozen;
using System.Linq;
using Content.Server.NPC.Components;
using JetBrains.Annotations;
using Robust.Shared.Prototypes;
namespace Content.Server.NPC.Systems;
/// <summary>
/// Outlines faction relationships with each other.
/// </summary>
public sealed partial class NpcFactionSystem : EntitySystem
{
[Dependency] private readonly EntityLookupSystem _lookup = default!;
[Dependency] private readonly IPrototypeManager _protoManager = default!;
/// <summary>
/// To avoid prototype mutability we store an intermediary data class that gets used instead.
/// </summary>
private FrozenDictionary<string, FactionData> _factions = FrozenDictionary<string, FactionData>.Empty;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<NpcFactionMemberComponent, ComponentStartup>(OnFactionStartup);
SubscribeLocalEvent<PrototypesReloadedEventArgs>(OnProtoReload);
InitializeException();
RefreshFactions();
}
private void OnProtoReload(PrototypesReloadedEventArgs obj)
{
if (obj.WasModified<NpcFactionPrototype>())
RefreshFactions();
}
private void OnFactionStartup(EntityUid uid, NpcFactionMemberComponent memberComponent, ComponentStartup args)
{
RefreshFactions(memberComponent);
}
/// <summary>
/// Refreshes the cached factions for this component.
/// </summary>
private void RefreshFactions(NpcFactionMemberComponent memberComponent)
{
memberComponent.FriendlyFactions.Clear();
memberComponent.HostileFactions.Clear();
foreach (var faction in memberComponent.Factions)
{
// YAML Linter already yells about this
if (!_factions.TryGetValue(faction, out var factionData))
continue;
memberComponent.FriendlyFactions.UnionWith(factionData.Friendly);
memberComponent.HostileFactions.UnionWith(factionData.Hostile);
}
}
/// <summary>
/// Adds this entity to the particular faction.
/// </summary>
public void AddFaction(EntityUid uid, string faction, bool dirty = true)
{
if (!_protoManager.HasIndex<NpcFactionPrototype>(faction))
{
Log.Error($"Unable to find faction {faction}");
return;
}
var comp = EnsureComp<NpcFactionMemberComponent>(uid);
if (!comp.Factions.Add(faction))
return;
if (dirty)
{
RefreshFactions(comp);
}
}
/// <summary>
/// Removes this entity from the particular faction.
/// </summary>
public void RemoveFaction(EntityUid uid, string faction, bool dirty = true)
{
if (!_protoManager.HasIndex<NpcFactionPrototype>(faction))
{
Log.Error($"Unable to find faction {faction}");
return;
}
if (!TryComp<NpcFactionMemberComponent>(uid, out var component))
return;
if (!component.Factions.Remove(faction))
return;
if (dirty)
{
RefreshFactions(component);
}
}
/// <summary>
/// Remove this entity from all factions.
/// </summary>
public void ClearFactions(EntityUid uid, bool dirty = true)
{
if (!TryComp<NpcFactionMemberComponent>(uid, out var component))
return;
component.Factions.Clear();
if (dirty)
RefreshFactions(component);
}
public IEnumerable<EntityUid> GetNearbyHostiles(EntityUid entity, float range, NpcFactionMemberComponent? component = null)
{
if (!Resolve(entity, ref component, false))
return Array.Empty<EntityUid>();
var hostiles = GetNearbyFactions(entity, range, component.HostileFactions);
if (TryComp<FactionExceptionComponent>(entity, out var factionException))
{
// ignore anything from enemy faction that we are explicitly friendly towards
return hostiles
.Union(GetHostiles(entity, factionException))
.Where(target => !IsIgnored(entity, target, factionException));
}
return hostiles;
}
[PublicAPI]
public IEnumerable<EntityUid> GetNearbyFriendlies(EntityUid entity, float range, NpcFactionMemberComponent? component = null)
{
if (!Resolve(entity, ref component, false))
return Array.Empty<EntityUid>();
return GetNearbyFactions(entity, range, component.FriendlyFactions);
}
private IEnumerable<EntityUid> GetNearbyFactions(EntityUid entity, float range, HashSet<string> factions)
{
var xformQuery = GetEntityQuery<TransformComponent>();
if (!xformQuery.TryGetComponent(entity, out var entityXform))
yield break;
foreach (var ent in _lookup.GetEntitiesInRange<NpcFactionMemberComponent>(entityXform.MapPosition, range))
{
if (ent.Owner == entity)
continue;
if (!factions.Overlaps(ent.Comp.Factions))
continue;
yield return ent.Owner;
}
}
public bool IsEntityFriendly(EntityUid uidA, EntityUid uidB, NpcFactionMemberComponent? factionA = null, NpcFactionMemberComponent? factionB = null)
{
if (!Resolve(uidA, ref factionA, false) || !Resolve(uidB, ref factionB, false))
return false;
return factionA.Factions.Overlaps(factionB.Factions) || factionA.FriendlyFactions.Overlaps(factionB.Factions);
}
public bool IsFactionFriendly(string target, string with)
{
return _factions[target].Friendly.Contains(with) && _factions[with].Friendly.Contains(target);
}
public bool IsFactionFriendly(string target, EntityUid with, NpcFactionMemberComponent? factionWith = null)
{
if (!Resolve(with, ref factionWith, false))
return false;
return factionWith.Factions.All(x => IsFactionFriendly(target, x)) ||
factionWith.FriendlyFactions.Contains(target);
}
public bool IsFactionHostile(string target, string with)
{
return _factions[target].Hostile.Contains(with) && _factions[with].Hostile.Contains(target);
}
public bool IsFactionHostile(string target, EntityUid with, NpcFactionMemberComponent? factionWith = null)
{
if (!Resolve(with, ref factionWith, false))
return false;
return factionWith.Factions.All(x => IsFactionHostile(target, x)) ||
factionWith.HostileFactions.Contains(target);
}
public bool IsFactionNeutral(string target, string with)
{
return !IsFactionFriendly(target, with) && !IsFactionHostile(target, with);
}
/// <summary>
/// Makes the source faction friendly to the target faction, 1-way.
/// </summary>
public void MakeFriendly(string source, string target)
{
if (!_factions.TryGetValue(source, out var sourceFaction))
{
Log.Error($"Unable to find faction {source}");
return;
}
if (!_factions.ContainsKey(target))
{
Log.Error($"Unable to find faction {target}");
return;
}
sourceFaction.Friendly.Add(target);
sourceFaction.Hostile.Remove(target);
RefreshFactions();
}
private void RefreshFactions()
{
_factions = _protoManager.EnumeratePrototypes<NpcFactionPrototype>().ToFrozenDictionary(
faction => faction.ID,
faction => new FactionData
{
Friendly = faction.Friendly.ToHashSet(),
Hostile = faction.Hostile.ToHashSet()
});
foreach (var comp in EntityQuery<NpcFactionMemberComponent>(true))
{
comp.FriendlyFactions.Clear();
comp.HostileFactions.Clear();
RefreshFactions(comp);
}
}
/// <summary>
/// Makes the source faction hostile to the target faction, 1-way.
/// </summary>
public void MakeHostile(string source, string target)
{
if (!_factions.TryGetValue(source, out var sourceFaction))
{
Log.Error($"Unable to find faction {source}");
return;
}
if (!_factions.ContainsKey(target))
{
Log.Error($"Unable to find faction {target}");
return;
}
sourceFaction.Friendly.Remove(target);
sourceFaction.Hostile.Add(target);
RefreshFactions();
}
}