Faction play 1: typed doctrine on Faction and one flight per faction per zone

FactionDoctrine/RoleDoctrine (Faction key 17), Flight as the only writer of
members' Target and Task, hail/grace/compliance, FollowTask/FollowState,
agent removal on Entities removal, doctrine-catalog command, FlightTests.
Not yet built or run; verification follows in later commits.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-08 14:18:41 +02:00
commit 8f42265de3
24 changed files with 812 additions and 42 deletions

View file

@ -23,11 +23,14 @@ public class Agent
public Ship Ship { get; }
public ItemManager ItemManager { get; }
public GameplaySettings Settings { get; }
// How this pilot fights: its faction's doctrine for its role (Zone.CreateAgent resolves it).
public RoleDoctrine Doctrine { get; }
public float TopSpeed => _velocityLimit?.Limit ?? 100;
public Agent(Ship ship)
public Agent(Ship ship, RoleDoctrine doctrine)
{
Ship = ship;
Doctrine = doctrine;
ItemManager = Ship.ItemManager;
Settings = Ship.ItemManager.GameplaySettings;

View file

@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.Linq;
using CultMath;
using static CultMath.math;
// One flight per (zone, faction) of piloted ships; unaffiliated ships form one flight of their own. The flight alone
// decides what its members do: which hostile each engages (Ship.Target) and what each does otherwise (Agent.Task).
// The agent graph executes those two and decides nothing. The faction's doctrine (FactionDoctrine) holds the numbers.
//
// The picture is the union of the members' VisibleEnemies. A track passes through phases the flight owns, runtime only:
// None, Hailing (grace running, one hail spoken), Complied (slow enough at the grace's end: followed, not engaged) and
// Engaged. A member still fires only at what its own VisibleEntities hold (FireControl), so the shared picture never
// lets it fire at what it cannot see.
public class Flight
{
public enum Phase { None, Hailing, Complied, Engaged }
private class Track
{
public Phase Phase;
public double Start;
}
private class Member
{
public Agent Agent;
public PatrolOrbitsTask Patrol;
}
private readonly FactionDoctrine _doctrine;
private readonly GameplaySettings _settings;
private readonly List<Member> _members = new List<Member>();
private readonly Dictionary<Entity, Track> _tracks = new Dictionary<Entity, Track>();
private double _time;
// No doctrine fights as FactionDoctrine.Default; a doctrine that leaves a role unauthored gets that role's default.
public Flight(FactionDoctrine doctrine, GameplaySettings settings)
{
var fallback = FactionDoctrine.Default(settings);
_doctrine = doctrine ?? fallback;
_settings = settings;
Combatant = _doctrine.Combatant ?? fallback.Combatant;
}
public RoleDoctrine Combatant { get; }
public int Count => _members.Count;
public bool Contains(Agent agent) => _members.Any(m => m.Agent == agent);
public Phase PhaseOf(Entity track) => _tracks.TryGetValue(track, out var t) ? t.Phase : Phase.None;
public void Join(Agent agent, PatrolOrbitsTask circuit)
{
_members.Add(new Member { Agent = agent, Patrol = circuit });
agent.Task = circuit;
}
public void Leave(Agent agent) => _members.RemoveAll(m => m.Agent == agent);
public void Update(float dt)
{
_time += dt;
var picture = _members.SelectMany(m => m.Agent.Ship.VisibleEnemies).Distinct().ToList();
foreach (var gone in _tracks.Keys.Where(t => !picture.Contains(t)).ToList()) _tracks.Remove(gone);
foreach (var entity in picture)
{
if (!_tracks.TryGetValue(entity, out var track)) _tracks[entity] = track = new Track();
Advance(entity, track);
}
foreach (var member in _members) Order(member, picture);
}
// A grudge is a hostile IFF override that any member holds on the track.
private bool Grudged(Entity entity) => _members.Any(m => m.Agent.Ship.IffOverride(entity) == true);
private bool Engageable(Entity entity, bool grudge)
{
switch (_doctrine.EngageOn)
{
case EngageOn.Never: return false;
case EngageOn.Detection: return true;
case EngageOn.Identified:
return grudge || _members.Any(m => m.Agent.Ship.EntityInfoGathered.TryGetValue(entity, out var info) &&
info >= _settings.TargetGearInfoThreshold);
case EngageOn.Provoked: return grudge;
case EngageOn.Trespass: return grudge || !(entity.PresencePermitted?.Value ?? true);
default: return false;
}
}
private void Advance(Entity entity, Track track)
{
if (track.Phase == Phase.Engaged) return;
var grudge = Grudged(entity);
if (!Engageable(entity, grudge))
{
track.Phase = Phase.None;
return;
}
// A grudge is already a quarrel: no grace to give.
if (grudge)
{
track.Phase = Phase.Engaged;
return;
}
switch (track.Phase)
{
case Phase.None:
if (_doctrine.Grace > 0)
{
track.Phase = Phase.Hailing;
track.Start = _time;
if (!string.IsNullOrEmpty(_doctrine.Hail)) Nearest(entity)?.Agent.Ship.SetMessage(_doctrine.Hail);
}
else track.Phase = Phase.Engaged;
break;
case Phase.Hailing:
if (_time >= track.Start + _doctrine.Grace)
track.Phase = _doctrine.ComplySpeed > 0 && length(entity.Velocity) < _doctrine.ComplySpeed
? Phase.Complied
: Phase.Engaged;
break;
case Phase.Complied:
if (length(entity.Velocity) >= _doctrine.ComplySpeed) track.Phase = Phase.Engaged;
break;
}
}
private Member Nearest(Entity entity) =>
_members.OrderBy(m => lengthsq(m.Agent.Ship.Position.xz - entity.Position.xz)).FirstOrDefault();
private void Order(Member member, List<Entity> picture)
{
var ship = member.Agent.Ship;
var seen = ship.VisibleEnemies;
// Engage: keep the current target while it stays engaged, else the nearest engaged track this member can see.
var engaged = picture.Where(e => _tracks[e].Phase == Phase.Engaged && seen.Contains(e)).ToList();
if (engaged.Count > 0)
{
var current = ship.Target.Value.Entity;
var pick = current != null && engaged.Contains(current)
? current
: engaged.OrderBy(e => lengthsq(ship.Position.xz - e.Position.xz)).First();
Aim(ship, pick);
return;
}
Aim(ship, null);
var held = picture.Where(e => _tracks[e].Phase == Phase.Hailing || _tracks[e].Phase == Phase.Complied).ToList();
if (held.Count > 0)
{
var anchor = member.Agent.Task is FollowTask follow && held.Contains(follow.Anchor)
? follow.Anchor
: held.OrderBy(e => lengthsq(ship.Position.xz - e.Position.xz)).First();
if (!(member.Agent.Task is FollowTask current) || current.Anchor != anchor)
member.Agent.Task = new FollowTask { Anchor = anchor, Standoff = Standoff(ship) };
}
else if (member.Agent.Task != member.Patrol)
member.Agent.Task = member.Patrol;
}
private static void Aim(Ship ship, Entity target)
{
var wanted = target == null ? TargetRef.None : new TargetRef(target);
if (!ship.Target.Value.Equals(wanted)) ship.SetTarget(wanted);
}
private float Standoff(Ship ship)
{
if (Combatant.HoldStandoff > 0) return Combatant.HoldStandoff;
return 1.1f * ship.Weapons.Select(w => w.Range).DefaultIfEmpty(0f).Max();
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5f6c82a74e5b4bc1b8c79e0d242e3ec2

View file

@ -1,23 +1,30 @@
using System.Linq;
using UniRx;
// The agent graph for a piloted ship. It executes the Task and Target its flight writes (Flight.cs) and decides
// neither: patrol and follow follow the Task kind, combat follows the Target.
public class Minion : Agent
{
public Minion(Ship ship) : base(ship)
public Minion(Ship ship, RoleDoctrine doctrine) : base(ship, doctrine)
{
var patrolState = new PatrolOrbitsState(this);
_rootState.AddTransition(patrolState,
() => Task is PatrolOrbitsTask,
() => patrolState.Task = Task as PatrolOrbitsTask);
var followState = new FollowState(this);
void Patrol() => patrolState.Task = Task as PatrolOrbitsTask;
_rootState.AddTransition(patrolState, () => Task is PatrolOrbitsTask, Patrol);
_rootState.AddTransition(followState, () => Task is FollowTask);
Ship.VisibleEnemies.ObserveAdd().Where(_ => Ship.Target.Value.IsNone).Subscribe(add => Ship.SetTarget(add.Value));
// A Task change switches the substate in one update, from wherever the pilot is in the old task. includeChildren
// reaches the sub-states (MoveToOrbit) that Update actually sits in.
patrolState.AddTransition(followState, () => Task is FollowTask, null, true, _rootState);
followState.AddTransition(patrolState, () => Task is PatrolOrbitsTask, Patrol, true, _rootState);
patrolState.AddTransition(_rootState, () => !(Task is PatrolOrbitsTask), null, true, _rootState);
followState.AddTransition(_rootState, () => !(Task is FollowTask), null, true, _rootState);
var combatState = new CombatState(this);
_rootState.AddTransition(combatState,
() => Ship.Target.Value.Entity != null, null, true, _rootState);
combatState.AddTransition(_rootState,
() => Ship.Target.Value.Entity == null, null, true, _rootState);
}
}
}

View file

@ -11,6 +11,7 @@ public class CombatState : BaseState
{
private const int DPS_SAMPLE_COUNT = 32;
private float _optimumRange;
public float OptimumRange => _optimumRange;
private readonly List<(int index, float dps)> _availableGroups = new List<(int index, float dps)>();
private readonly List<LockWeapon> _availableLockingWeapons = new List<LockWeapon>();
@ -118,7 +119,7 @@ public class CombatState : BaseState
// fires at, and "the target is designated" for a fused one.
foreach (var weapon in _agent.Ship.WeaponGroups[selectedGroup].weapons)
{
if (FireControl.AgentFires(weapon, _agent.Ship, target))
if (FireControl.AgentFires(weapon, _agent.Ship, target, _agent.Doctrine.MinHitProbability))
weapon.Activate();
else if (weapon.Firing)
weapon.Deactivate();
@ -156,7 +157,7 @@ public class CombatState : BaseState
}
// Multiply by range raised to a (sublinear) exponent to bias DPS preference towards longer ranges
dps *= pow(range, _agent.Settings.AgentRangeExponent);
dps *= pow(range, _agent.Doctrine.RangeExponent);
if (dps > optimumDPS)
{

View file

@ -0,0 +1,26 @@
using CultMath;
using static CultMath.math;
using float2 = CultMath.float2;
// Hold a standoff from the anchor: match its velocity, and close or open the gap in proportion to the error.
public class FollowState : BaseState
{
public FollowState(Agent agent) : base(agent) { }
public override void Update(float delta)
{
var task = _agent.Task as FollowTask;
if (task?.Anchor == null) return;
var toAnchor = task.Anchor.Position.xz - _agent.Ship.Position.xz;
var distance = length(toAnchor);
var direction = distance > 0 ? toAnchor / distance : _agent.Ship.Direction;
// Positive error: too far, close. Negative: too near, open.
var error = distance - task.Standoff;
var pull = direction * (float) sign(error) * saturate(abs(error) / max(task.Standoff, 1f));
var desired = task.Anchor.Velocity + pull * _agent.TopSpeed;
_agent.Ship.Aim = float3(direction.x, 0, direction.y);
_agent.Accelerate(desired);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5cf86244ca6648a99f304b061b66348a

View file

@ -29,6 +29,7 @@ public enum TaskType
Tow,
Defend,
Attack,
Explore
Explore,
Follow
}

View file

@ -0,0 +1,11 @@
using System;
using MessagePack;
// Keep station on an entity at a standoff: the flight hailing a track holds its members here (Flight.cs).
// Runtime only, like every agent task.
public class FollowTask : AgentTask
{
[IgnoreMember] public Entity Anchor;
[IgnoreMember] public float Standoff;
[IgnoreMember] public override TaskType Type => TaskType.Follow;
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6bab02326ff64e29ad2b81f0fc1483b5