Control Modules & Job System

Agent behaviors are no longer hard coded but instead created by equippable control modules
Game Context has a job system which assigns appropriate tasks to drone control modules
This commit is contained in:
hyperion51 2020-05-07 03:53:54 +01:00
commit ab8aa5fb9a
27 changed files with 480 additions and 190 deletions

View file

@ -1,7 +1,30 @@
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public abstract class AgentBehavior
{
public abstract void Update(float delta);
protected float ThrustInput(float2 deltaV) =>
saturate( // Input must be normalized
pow( // Apply specificity as exponent to dot product to control how specific the direction needs to be
saturate( // Discard negative dot product (we're facing away from desired direction)
dot(normalize(Entity.Direction), normalize(deltaV))), // Cosine of angle between direction and deltaV
ControllerData.ThrustSpecificity)
* length(deltaV) * ControllerData.ThrustSensitivity);
protected float TurningInput(float2 deltaV) => clamp(-Entity.Direction.AngleDiff(deltaV) * ControllerData.TurningSensitivity, -1, 1);
protected ControllerData ControllerData;
protected GameContext Context;
protected Entity Entity;
public AgentBehavior(GameContext context, Entity entity, ControllerData controllerData)
{
Context = context;
Entity = entity;
ControllerData = controllerData;
}
}

View file

@ -1,64 +1,64 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using static Unity.Mathematics.math;
using Random = Unity.Mathematics.Random;
public class AgentController
{
public Guid Entity { get; }
public EntityAgent EntityAgent { get; }
public GameContext Context { get; }
public Guid Zone { get; set; }
private Locomotion _locomotion;
private VelocityMatch _velocityMatch;
private Random _random = new Random((uint) (DateTime.Now.Ticks%uint.MaxValue));
private Guid _targetOrbit;
public AgentController(GameContext context, Guid zone, Guid entity)
{
Entity = entity;
Zone = zone;
Context = context;
EntityAgent = new EntityAgent(context, entity, zone, Guid.Empty);
_locomotion = new Locomotion(context, entity);
_velocityMatch = new VelocityMatch(context, entity);
_velocityMatch.OnMatch += () =>
{
EntityAgent.CurrentBehavior = _locomotion;
RandomTarget();
};
EntityAgent.CurrentBehavior = _locomotion;
RandomTarget();
}
public void Update(float delta)
{
EntityAgent.Update(delta);
// Context.Log(
// $"Agent Mode: {EntityAgent.CurrentBehavior.GetType()} " +
// $"Agent Distance: {distance} " +
// $"Turnaround Distance: {_stoppingDistance + _turnaroundDistance} " +
// $"Objective: {_objective.Key.ID.ToString().Substring(0, 8)}");
var entity = Context.Cache.Get<Entity>(Entity);
if (EntityAgent.CurrentBehavior == _locomotion)
{
var orbitData = Context.Cache.Get<OrbitData>(_targetOrbit);
_velocityMatch.TargetOrbit = _targetOrbit;
var matchDistanceTime = _velocityMatch.MatchDistanceTime;
_locomotion.Objective = Context.GetOrbitPosition(_targetOrbit) + Context.GetOrbitVelocity(_targetOrbit) * matchDistanceTime.y;
var distance = length(_locomotion.Objective - entity.Position);
if (distance < matchDistanceTime.x)
EntityAgent.CurrentBehavior = _velocityMatch;
}
}
private void RandomTarget()
{
var entities = Context.ZonePlanets[Zone];
_targetOrbit = Context.Cache.Get<PlanetData>(entities[_random.NextInt(entities.Length)]).Orbit;
}
}
// using System;
// using System.Collections;
// using System.Collections.Generic;
// using System.Linq;
// using static Unity.Mathematics.math;
// using Random = Unity.Mathematics.Random;
//
// public class AgentController
// {
// public Guid Entity { get; }
// public EntityAgent EntityAgent { get; }
// public GameContext Context { get; }
// public Guid Zone { get; set; }
//
// private Locomotion _locomotion;
// private VelocityMatch _velocityMatch;
// private Random _random = new Random((uint) (DateTime.Now.Ticks%uint.MaxValue));
// private Guid _targetOrbit;
//
// public AgentController(GameContext context, Guid zone, Guid entity)
// {
// Entity = entity;
// Zone = zone;
// Context = context;
// EntityAgent = new EntityAgent(context, entity, zone, Guid.Empty);
// _locomotion = new Locomotion(context, entity);
// _velocityMatch = new VelocityMatch(context, entity);
// _velocityMatch.OnMatch += () =>
// {
// EntityAgent.CurrentBehavior = _locomotion;
// RandomTarget();
// };
// EntityAgent.CurrentBehavior = _locomotion;
// RandomTarget();
// }
//
// public void Update(float delta)
// {
// EntityAgent.Update(delta);
// // Context.Log(
// // $"Agent Mode: {EntityAgent.CurrentBehavior.GetType()} " +
// // $"Agent Distance: {distance} " +
// // $"Turnaround Distance: {_stoppingDistance + _turnaroundDistance} " +
// // $"Objective: {_objective.Key.ID.ToString().Substring(0, 8)}");
// var entity = Context.Cache.Get<Entity>(Entity);
//
// if (EntityAgent.CurrentBehavior == _locomotion)
// {
// var orbitData = Context.Cache.Get<OrbitData>(_targetOrbit);
// _velocityMatch.TargetOrbit = _targetOrbit;
// var matchDistanceTime = _velocityMatch.MatchDistanceTime;
// _locomotion.Objective = Context.GetOrbitPosition(_targetOrbit) + Context.GetOrbitVelocity(_targetOrbit) * matchDistanceTime.y;
// var distance = length(_locomotion.Objective - entity.Position);
// if (distance < matchDistanceTime.x)
// EntityAgent.CurrentBehavior = _velocityMatch;
// }
// }
//
// private void RandomTarget()
// {
// var entities = Context.ZonePlanets[Zone];
// _targetOrbit = Context.Cache.Get<PlanetData>(entities[_random.NextInt(entities.Length)]).Orbit;
// }
// }

View file

@ -9,14 +9,21 @@ using UnityEngine;
[MessagePackObject,
Union(0, typeof(StationTowing)),
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
public abstract class AgentTask
public abstract class AgentTask : DatabaseEntry
{
[IgnoreMember] public abstract AgentJob JobType { get; }
[JsonProperty("id"), Key(0)] public int Priority;
[JsonProperty("zone"), Key(1)] public Guid Zone;
[JsonProperty("priority"), Key(1)]
public int Priority;
[JsonProperty("zone"), Key(2)]
public Guid Zone;
[JsonProperty("assignedEntity"), Key(3)]
public bool Reserved;
[IgnoreMember] public abstract TaskType Type { get; }
}
public enum AgentJob
public enum TaskType
{
Mine,
Haul,

View file

@ -11,30 +11,45 @@ public class Locomotion : AgentBehavior
private const float Sensitivity = 1;
private const float TangentSensitivity = 2;
private GameContext _context;
private Guid _entity;
private IAnalogBehavior _thrust;
private IAnalogBehavior _turning;
private Thruster _thrust;
private Turning _turning;
private VelocityLimit _velocityLimit;
public Locomotion(GameContext context, Guid entity)
public Locomotion(GameContext context, Entity entity, ControllerData controllerData) : base(context, entity, controllerData)
{
_context = context;
_entity = entity;
var entityObject = _context.Cache.Get<Entity>(_entity);
_thrust = entityObject.Axes.Keys.FirstOrDefault(x => x is Thruster);
_turning = entityObject.Axes.Keys.FirstOrDefault(x => x is Turning);
_velocityLimit = Entity.GetBehaviors<VelocityLimit>().FirstOrDefault();
_thrust = Entity.Axes.Keys.FirstOrDefault(x => x is Thruster) as Thruster;
_turning = Entity.Axes.Keys.FirstOrDefault(x => x is Turning) as Turning;
}
public override void Update(float delta)
{
var entity = _context.Cache.Get<Entity>(_entity);
if (_thrust != null && _turning != null)
{
float2 diff = Objective - entity.Position;
float2 tangential = entity.Velocity - dot(normalize(diff), normalize(entity.Velocity)) * entity.Velocity;
float angleDiff = entity.Direction.AngleDiff(normalize(diff) - tangential * TangentSensitivity);
entity.Axes[_turning] = clamp(-angleDiff * Sensitivity, -1, 1);
entity.Axes[_thrust] = 1;
float2 diff = Objective - Entity.Position;
// We want to go top speed in the direction of our target
var topSpeed = _velocityLimit?.Limit ?? 1000;
float2 desiredVelocity = normalize(diff) * topSpeed;
var accelerationTime = length(desiredVelocity - Entity.Velocity) / (_thrust.Thrust / Entity.Mass);
var accelerationDistance = accelerationTime * length((desiredVelocity + Entity.Velocity) / 2);
// We do not have enough space to get to full speed, use approximate maneuvering
if (accelerationDistance > length(diff))
{
float2 tangential = Entity.Velocity - dot(normalize(diff), normalize(Entity.Velocity)) * Entity.Velocity;
float2 adjustedDirection = normalize(diff) - tangential * TangentSensitivity;
Entity.Axes[_turning] = TurningInput(adjustedDirection);
Entity.Axes[_thrust] = 1;
}
// We have plenty of space, use exact maneuvering
else
{
var deltaV = desiredVelocity - Entity.Velocity;
Entity.Axes[_turning] = TurningInput(deltaV);
Entity.Axes[_thrust] = ThrustInput(deltaV);
}
}
}
}

View file

@ -4,21 +4,23 @@ using System.Collections.Generic;
using JsonKnownTypes;
using MessagePack;
using Newtonsoft.Json;
using UnityEngine;
[MessagePackObject,
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
public class StationTowing : AgentTask
{
[IgnoreMember] public override AgentJob JobType => AgentJob.Tow;
[IgnoreMember] public override TaskType Type => TaskType.Tow;
private Guid _entity;
[JsonProperty("station"), Key(4)]
private Guid _station;
[JsonProperty("targetOrbit"), Key(5)]
private Guid _targetOrbit;
public StationTowing(Guid zone, Guid entity, Guid targetOrbit)
public StationTowing(Guid zone, Guid station, Guid targetOrbit)
{
Zone = zone;
_entity = entity;
_station = station;
_targetOrbit = targetOrbit;
}
}

View file

@ -9,35 +9,28 @@ public class VelocityMatch : AgentBehavior
{
public event Action OnMatch;
public Guid TargetOrbit;
private Guid _entity;
private IAnalogBehavior _thrust;
private IAnalogBehavior _turning;
private const float TurningSensitivity = 1;
private const float ThrustSensitivity = 1;
private Thruster _thrust;
private Turning _turning;
private const float TargetThreshold = .1f;
private GameContext _context;
public VelocityMatch(GameContext context, Guid entity)
public VelocityMatch(GameContext context, Entity entity, ControllerData controllerData) : base(context, entity, controllerData)
{
_context = context;
_entity = entity;
var entityObject = _context.Cache.Get<Entity>(_entity);
_thrust = entityObject.Axes.Keys.FirstOrDefault(x => x is Thruster);
_turning = entityObject.Axes.Keys.FirstOrDefault(x => x is Turning);
_thrust = Entity.Axes.Keys.FirstOrDefault(x => x is Thruster) as Thruster;
_turning = Entity.Axes.Keys.FirstOrDefault(x => x is Turning) as Turning;
}
public override void Update(float delta)
{
var entity = _context.Cache.Get<Entity>(_entity);
if (TargetOrbit != Guid.Empty && _thrust != null && _turning != null)
{
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - entity.Velocity;
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - Entity.Velocity;
if(length(deltaV) < TargetThreshold)
OnMatch?.Invoke();
var angleDiff = entity.Direction.AngleDiff(deltaV);
entity.Axes[_turning] = clamp(-angleDiff * TurningSensitivity, -1, 1);
entity.Axes[_thrust] = saturate(length(pow(saturate(dot(normalize(entity.Direction),normalize(deltaV))), 8)*length(deltaV))*ThrustSensitivity);
Entity.Axes[_turning] = TurningInput(deltaV);
Entity.Axes[_thrust] = ThrustInput(deltaV);
}
}
@ -45,15 +38,14 @@ public class VelocityMatch : AgentBehavior
{
get
{
var entity = _context.Cache.Get<Entity>(_entity);
var velocity = length(entity.Velocity);
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - entity.Velocity;
var velocity = length(Entity.Velocity);
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - Entity.Velocity;
var stoppingTime = length(deltaV) / (_context.Evaluate((_thrust.Data as ThrusterData).Thrust, _thrust.Item, entity) / entity.Mass);
var stoppingTime = length(deltaV) / (_thrust.Thrust / Entity.Mass);
var stoppingDistance = stoppingTime * (velocity / 2);
var angleDiff = entity.Direction.AngleDiff(deltaV);
var turnaroundTime = angleDiff / (_context.Evaluate((_turning.Data as TurningData).Torque, _turning.Item, entity) / entity.Mass);
var angleDiff = Entity.Direction.AngleDiff(deltaV);
var turnaroundTime = angleDiff / (_turning.Torque / Entity.Mass);
var turnaroundDistance = turnaroundTime * velocity;
return float2(stoppingDistance + turnaroundDistance, stoppingTime + turnaroundTime);

View file

@ -13,9 +13,6 @@ public interface IBehavior
{
void Initialize();
void Update(float delta);
Entity Entity { get; }
Gear Item { get; }
GameContext Context { get; }
BehaviorData Data { get; }
}
@ -36,6 +33,13 @@ public interface IPersistentBehavior//<T> where T : IBehavior
void Restore(PersistentBehaviorData data);
}
public interface IController
{
bool Available { get; }
TaskType JobType { get; }
void AssignTask(Guid task);
}
[MessagePackObject,
Union(0, typeof(FactoryPersistence)),
JsonObject(MemberSerialization.OptIn),
@ -58,6 +62,8 @@ public abstract class PersistentBehaviorData
Union(10, typeof(VelocityConversionData)),
Union(11, typeof(VelocityLimitData)),
Union(12, typeof(FactoryData)),
Union(13, typeof(PatrolControllerData)),
Union(14, typeof(TowingControllerData)),
JsonConverter(typeof(JsonKnownTypesConverter<BehaviorData>)), JsonObject(MemberSerialization.OptIn)]
public abstract class BehaviorData
{

View file

@ -0,0 +1,25 @@
using System.Collections;
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
[Union(0, typeof(TowingControllerData))]
public abstract class ControllerData : BehaviorData
{
[InspectableField, JsonProperty("thrustSensitivity"), Key(0)]
public float ThrustSensitivity = 1;
[InspectableField, JsonProperty("thrustSpecificity"), Key(1)]
public float ThrustSpecificity = 8;
[InspectableField, JsonProperty("turningSensitivity"), Key(2)]
public float TurningSensitivity = 1;
[InspectableField, JsonProperty("tangentSensitivity"), Key(3)]
public float TangentSensitivity = 4;
}
// public abstract class Controller
// {
//
// }

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0bd22c9213b660e4d845f7a751f18848
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,68 @@
using System;
using System.Collections;
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[MessagePackObject, JsonObject(MemberSerialization.OptIn), EntityTypeRestriction(HullType.Ship)]
public class PatrolControllerData : ControllerData
{
[InspectableField, JsonProperty("targetDistance"), Key(4)]
public float TargetDistance = 10;
public override IBehavior CreateInstance(GameContext context, Entity entity, Gear item)
{
return new PatrolController(context, this, entity, item);
}
}
public class PatrolController : IBehavior, IController
{
public TaskType JobType => TaskType.Tow;
public bool Available => false;
public BehaviorData Data => _data;
private PatrolControllerData _data;
private GameContext _context;
private Entity _entity;
private Gear _item;
private Guid _towingTask;
private Locomotion _locomotion;
private Guid _targetOrbit;
public PatrolController(GameContext context, PatrolControllerData data, Entity entity, Gear item)
{
_context = context;
_data = data;
_entity = entity;
_item = item;
}
public void Initialize()
{
_locomotion = new Locomotion(_context, _entity, _data);
RandomTarget();
}
public void Update(float delta)
{
_locomotion.Objective = _context.GetOrbitPosition(_targetOrbit);
_locomotion.Update(delta);
if(length(_entity.Position - _locomotion.Objective) < _data.TargetDistance)
RandomTarget();
}
public void AssignTask(Guid task)
{
throw new NotImplementedException();
}
private void RandomTarget()
{
var entities = _context.ZonePlanets[_entity.Zone];
_targetOrbit = _context.Cache.Get<PlanetData>(entities[_context.Random.NextInt(entities.Length)]).Orbit;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cc2d16773614011488d30e38edf7c3bb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -26,12 +26,14 @@ public class Thruster : IAnalogBehavior
public Entity Entity { get; }
public Gear Item { get; }
public GameContext Context { get; }
public float Thrust { get; private set; }
public BehaviorData Data => _data;
private ThrusterData _data;
private float _thrust;
private float _input;
public Thruster(GameContext context, ThrusterData data, Entity entity, Gear item)
{
@ -43,7 +45,7 @@ public class Thruster : IAnalogBehavior
public void SetAxis(float value)
{
_thrust = saturate(value);
_input = saturate(value);
}
public void Initialize()
@ -52,8 +54,9 @@ public class Thruster : IAnalogBehavior
public void Update(float delta)
{
Entity.Velocity += Entity.Direction * _thrust * Context.Evaluate(_data.Thrust, Item, Entity) / Entity.Mass * delta;
Entity.AddHeat(_thrust * Context.Evaluate(_data.Heat, Item, Entity) * delta);
Entity.VisibilitySources[this] = _thrust * Context.Evaluate(_data.Visibility, Item, Entity);
Thrust = Context.Evaluate(_data.Thrust, Item, Entity);
Entity.Velocity += Entity.Direction * _input * Thrust / Entity.Mass * delta;
Entity.AddHeat(_input * Context.Evaluate(_data.Heat, Item, Entity) * delta);
Entity.VisibilitySources[this] = _input * Context.Evaluate(_data.Visibility, Item, Entity);
}
}

View file

@ -0,0 +1,69 @@
using System;
using System.Collections;
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
[MessagePackObject, JsonObject(MemberSerialization.OptIn), EntityTypeRestriction(HullType.Ship)]
public class TowingControllerData : ControllerData
{
public override IBehavior CreateInstance(GameContext context, Entity entity, Gear item)
{
return new TowingController(context, this, entity, item);
}
}
public class TowingController : IBehavior, IPersistentBehavior, IController
{
public TaskType JobType => TaskType.Tow;
public bool Available => _towingTask != Guid.Empty;
public BehaviorData Data => _data;
private TowingControllerData _data;
private GameContext _context;
private Entity _entity;
private Gear _item;
private Guid _towingTask;
public TowingController(GameContext context, TowingControllerData data, Entity entity, Gear item)
{
_context = context;
_data = data;
_entity = entity;
_item = item;
}
public void Initialize()
{
}
public void Update(float delta)
{
}
public PersistentBehaviorData Store()
{
return new TowingControllerPersistence
{
TowingTask = _towingTask
};
}
public void Restore(PersistentBehaviorData data)
{
var towingControllerPersistence = data as TowingControllerPersistence;
_towingTask = towingControllerPersistence.TowingTask;
}
public void AssignTask(Guid task)
{
_towingTask = task;
}
}
public class TowingControllerPersistence : PersistentBehaviorData
{
[JsonProperty("towingTask"), Key(0)]
public Guid TowingTask;
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: de134a549a7d86f43a3590b78a2edeee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -26,12 +26,14 @@ public class Turning : IAnalogBehavior
public Entity Entity { get; }
public Gear Item { get; }
public GameContext Context { get; }
public float Torque { get; private set; }
public BehaviorData Data => _data;
private TurningData _data;
private float _turning;
private float _input;
public Turning(GameContext context, TurningData data, Entity entity, Gear item)
{
@ -43,7 +45,7 @@ public class Turning : IAnalogBehavior
public void SetAxis(float value)
{
_turning = clamp(value, -1, 1);
_input = clamp(value, -1, 1);
}
public void Initialize()
@ -52,8 +54,9 @@ public class Turning : IAnalogBehavior
public void Update(float delta)
{
Entity.Direction = mul(Entity.Direction, Unity.Mathematics.float2x2.Rotate(_turning * Context.Evaluate(_data.Torque, Item, Entity) / Entity.Mass * delta));
Entity.AddHeat(abs(_turning) * Context.Evaluate(_data.Heat, Item, Entity) * delta);
Entity.VisibilitySources[this] = abs(_turning) * Context.Evaluate(_data.Visibility, Item, Entity);
Torque = Context.Evaluate(_data.Torque, Item, Entity);
Entity.Direction = mul(Entity.Direction, Unity.Mathematics.float2x2.Rotate(_input * Torque / Entity.Mass * delta));
Entity.AddHeat(abs(_input) * Context.Evaluate(_data.Heat, Item, Entity) * delta);
Entity.VisibilitySources[this] = abs(_input) * Context.Evaluate(_data.Visibility, Item, Entity);
}
}

View file

@ -21,6 +21,8 @@ public class VelocityLimit : IBehavior
public Entity Entity { get; }
public Gear Item { get; }
public GameContext Context { get; }
public float Limit { get; private set; }
public BehaviorData Data => _data;
@ -40,8 +42,8 @@ public class VelocityLimit : IBehavior
public void Update(float delta)
{
var limit = Context.Evaluate(_data.TopSpeed, Item, Entity);
if (length(Entity.Velocity) > limit)
Entity.Velocity = normalize(Entity.Velocity) * limit;
Limit = Context.Evaluate(_data.TopSpeed, Item, Entity);
if (length(Entity.Velocity) > Limit)
Entity.Velocity = normalize(Entity.Velocity) * Limit;
}
}

View file

@ -36,6 +36,7 @@ public interface INamedEntry
Union(15, typeof(OrbitData)),
Union(16, typeof(PlanetData)),
Union(17, typeof(PersonalityAttribute)),
Union(18, typeof(AgentTask)),
// Union(17, typeof(ShipData)),
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
//[Union(21, typeof(ContractData))]
@ -67,8 +68,11 @@ public class Player : DatabaseEntry, INamedEntry
[RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class Corporation : DatabaseEntry, INamedEntry
{
[JsonProperty("name"), Key(1)] public string Name;
[JsonProperty("tasks"), Key(2)] public List<AgentTask> Tasks = new List<AgentTask>();
[JsonProperty("name"), Key(1)]
public string Name;
[JsonProperty("tasks"), Key(2)]
public List<Guid> Tasks = new List<Guid>();
[IgnoreMember] public string EntryName
{

View file

@ -26,7 +26,7 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR
[JsonProperty("children"), Key(9)] public List<Guid> Children = new List<Guid>(); // Type: Entity
[JsonProperty("hull"), Key(10)] public Guid Hull; // Type: Gear
[JsonProperty("persistedBehaviorData"), Key(11)] public Dictionary<Guid, PersistentBehaviorData[]> PersistedBehaviors;
[JsonProperty("agent"), Key(12)] public EntityAgent Agent;
[JsonProperty("corporation"), Key(12)] public Guid Corporation;
// [IgnoreMember] protected List<IBehavior> Behaviors;
[IgnoreMember] public Guid Zone;
@ -43,10 +43,11 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR
[IgnoreMember] public float Visibility => VisibilitySources.Values.Sum();
public Entity(GameContext context, Guid hull, IEnumerable<Guid> items, IEnumerable<Guid> cargo)
public Entity(GameContext context, Guid hull, IEnumerable<Guid> items, IEnumerable<Guid> cargo, Guid zone)
{
ID = Guid.NewGuid();
Context = context;
Zone = zone;
EquippedItems = items.ToList();
Cargo = cargo.ToList();
@ -63,29 +64,27 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR
var gearData = gear.ToDictionary(id => id, id => Context.Cache.Get<Gear>(id));
GearData = gearData.Values.ToDictionary(g => g, g => g.ItemData);
var allbehaviors = gear
.Where(i=>gearData[i].ItemData.Behaviors?.Any()??false)
.SelectMany(i => gearData[i].ItemData.Behaviors
.Select(bd => bd.CreateInstance(Context, this, gearData[i])))
.OrderBy(b => b.GetType().GetCustomAttribute<UpdateOrderAttribute>()?.Order ?? 0).ToList();
ItemBehaviors = gear
.Where(i=> gearData[i].ItemData.Behaviors?.Any()??false)
.ToDictionary(i=> gearData[i], i => gearData[i].ItemData.Behaviors
.Select(bd => bd.CreateInstance(Context, this, gearData[i]))
.OrderBy(b => b.GetType().GetCustomAttribute<UpdateOrderAttribute>()?.Order ?? 0)
.ToList());
ItemBehaviors = allbehaviors
.GroupBy(b => b.Item.ID, (guid, behaviors) => new {guid, behaviors})
.ToDictionary(g => gearData[g.guid], g => g.behaviors.ToList());
Bindings = ItemBehaviors
.Where(x => x.Value.Any(g => g is IActivatedBehavior))
.Select(x=> new {gear = x.Key, behaviors = x.Value
.Where(g => g is IActivatedBehavior)
.Cast<IActivatedBehavior>().ToList()})
.ToDictionary(x => x.gear, x => x.behaviors);
Bindings = allbehaviors
.Where(b => b is IActivatedBehavior)
.GroupBy(b => b.Item.ID, (guid, behaviors) => new {guid, behaviors})
.ToDictionary(g => gearData[g.guid], g => g.behaviors.Cast<IActivatedBehavior>().ToList());
Axes = allbehaviors
Axes = ItemBehaviors.Values
.SelectMany(behaviors=>behaviors)
.Where(b => b is IAnalogBehavior)
.ToDictionary(b => b as IAnalogBehavior, b => 0f);
foreach (var behavior in allbehaviors)
{
behavior.Initialize();
}
foreach (var behavior in ItemBehaviors.Values
.SelectMany(behaviors=>behaviors)) behavior.Initialize();
}
public void RecalculateMass()
@ -149,6 +148,9 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR
.Select(bd => bd.CreateInstance(Context, this, staleItem))
.OrderBy(b => b.GetType().GetCustomAttribute<UpdateOrderAttribute>()?.Order ?? 0).ToList();
foreach(var behavior in ItemBehaviors[staleItem])
behavior.Initialize();
// Restore state for persisted behaviors
foreach(var persistentBehaviorData in ItemBehaviors[staleItem]
.Where(b => b is IPersistentBehavior)
@ -220,8 +222,5 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR
.Cast<IPersistentBehavior>()
.Zip(PersistedBehaviors[itemBehaviors.Key.ID], (behavior, data) => new{behavior, data})))
persistentBehaviorData.behavior.Restore(persistentBehaviorData.data);
Agent.Context = Context;
Agent.Entity = ID;
}
}

View file

@ -10,10 +10,10 @@ using Random = Unity.Mathematics.Random;
public class GameContext
{
public Random Random = new Random((uint) (DateTime.Now.Ticks%uint.MaxValue));
public List<AgentController> Agents = new List<AgentController>();
public Dictionary<Guid, Guid[]> ZonePlanets = new Dictionary<Guid, Guid[]>();
public Dictionary<Guid, Dictionary<Guid, Entity>> ZoneEntities = new Dictionary<Guid, Dictionary<Guid, Entity>>();
public Dictionary<string, GalaxyMapLayerData> MapLayers = new Dictionary<string, GalaxyMapLayerData>();
public Dictionary<Guid, List<IController>> CorporationControllers = new Dictionary<Guid, List<IController>>();
private Action<string> _logger;
@ -38,6 +38,7 @@ public class GameContext
{
_deltaTime = (float) (value - _time);
_time = value;
//Log($"GameContext delta time: {_deltaTime}");
}
}
@ -82,6 +83,7 @@ public class GameContext
ZonePlanets[zoneID] = zoneData.Planets;
// TODO: Load stored entities
ZoneEntities[zoneID] = new Dictionary<Guid, Entity>();
}
public void Update()
@ -93,13 +95,30 @@ public class GameContext
{
_orbitPositions[orbit] = GetOrbitPosition(orbit);
_orbitVelocities[orbit] = _previousOrbitPositions.ContainsKey(orbit)
? _orbitPositions[orbit] - _previousOrbitPositions[orbit]
? (_orbitPositions[orbit] - _previousOrbitPositions[orbit]) / _deltaTime
: float2.zero;
}
foreach (var agent in Agents)
foreach (var corporation in Cache.GetAll<Corporation>())
{
agent.Update(_deltaTime);
foreach (var taskController in corporation.Tasks
.Select(id => Cache.Get<AgentTask>(id)) // Fetch the tasks from the database cache
.Where(task => task.Reserved == false) // Filter out tasks that have already been reserved
.GroupBy(task => task.Type) // Group tasks by job type
.Where(grouping =>
CorporationControllers[corporation.ID] // Filter out groupings with no available controller
.Any(controller => controller.Available && controller.JobType == grouping.Key))
.Select(grouping => grouping // Pair each task in remaining groupings with available controllers
.OrderByDescending(task => task.Priority) // Sort by priority, highest first
.Zip(CorporationControllers[corporation.ID]
.Where(controller => controller.Available && controller.JobType == grouping.Key),
(task, controller) => new {task, controller}))
.SelectMany(x => x)) // Flatten groupings
{
taskController.task.Reserved = true;
taskController.controller.AssignTask(taskController.task.ID);
}
}
foreach (var kvp in ZoneEntities)

View file

@ -9,7 +9,7 @@ public class OrbitalEntity : Entity
{
private Guid _orbitData;
public OrbitalEntity(GameContext context, Guid hull, IEnumerable<Guid> items, IEnumerable<Guid> cargo, Guid orbit) : base(context, hull, items, cargo)
public OrbitalEntity(GameContext context, Guid hull, IEnumerable<Guid> items, IEnumerable<Guid> cargo, Guid orbit, Guid zone) : base(context, hull, items, cargo, zone)
{
_orbitData = orbit;
}

View file

@ -19,7 +19,7 @@ public class Ship : Entity
// [IgnoreMember] public Dictionary<Targetable, float> Contacts = new Dictionary<Targetable, float>();
// [IgnoreMember] public Targetable Target;
public Ship(GameContext context, Guid hull, IEnumerable<Guid> items, IEnumerable<Guid> cargo) : base(context, hull, items, cargo)
public Ship(GameContext context, Guid hull, IEnumerable<Guid> items, IEnumerable<Guid> cargo, Guid zone) : base(context, hull, items, cargo, zone)
{
}