Stat Effects and Tech Tree Improvements

Tech tree layout is now correct thanks to MSAGL
Blueprint stat effects can now target item stats
Durability is now a PerformanceStat
This commit is contained in:
hyperion51 2020-04-16 03:08:18 +01:00
commit d8ff1e2289
23 changed files with 356 additions and 210 deletions

View file

@ -31,7 +31,7 @@ public interface IAnalogBehavior : IBehavior
}
[InspectableField,
Union(0, typeof(CannonData)),
Union(0, typeof(ProjectileWeaponData)),
Union(1, typeof(LauncherData)),
Union(2, typeof(ReactorData)),
Union(3, typeof(RadiatorData)),

View file

@ -2,7 +2,7 @@ using MessagePack;
using Newtonsoft.Json;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class CannonData : WeaponData, IBehaviorData
public class ProjectileWeaponData : WeaponData, IBehaviorData
{
[InspectablePrefab, JsonProperty("bullet"), Key(9)]
public string BulletPrefab;
@ -18,31 +18,31 @@ public class CannonData : WeaponData, IBehaviorData
public IBehavior CreateInstance(GameContext context, Entity entity, Gear item)
{
return new Cannon(context, this, entity, item);
return new ProjectileWeapon(context, this, entity, item);
}
}
public class Cannon : IActivatedBehavior
public class ProjectileWeapon : IActivatedBehavior
{
private bool _firing;
private float _cooldown; // normalized
private CannonData _cannon;
private ProjectileWeaponData _projectileWeapon;
public Entity Entity { get; }
public Gear Item { get; }
public GameContext Context { get; }
private float _firingVisibility;
public Cannon(GameContext context, CannonData c, Entity entity, Gear item)
public ProjectileWeapon(GameContext context, ProjectileWeaponData c, Entity entity, Gear item)
{
Context = context;
_cannon = c;
_projectileWeapon = c;
Entity = entity;
Item = item;
}
public void Activate()
{
// Debug.Log("Activating Cannon");
// Debug.Log("Activating ProjectileWeapon");
// _firing = true;
// Observable.EveryUpdate().TakeWhile(_ => _firing).Subscribe(_ =>
// {
@ -51,8 +51,8 @@ public class Cannon : IActivatedBehavior
// {
// _cooldown = 1;
// Fire(0);
// if(_cannon.BurstCount>1)
// Observable.Interval(TimeSpan.FromSeconds(_cannon.BurstTime.Evaluate(Hardpoint) / (_cannon.BurstCount-1))).Take(_cannon.BurstCount-1)
// if(_projectileWeapon.BurstCount>1)
// Observable.Interval(TimeSpan.FromSeconds(_projectileWeapon.BurstTime.Evaluate(Hardpoint) / (_projectileWeapon.BurstCount-1))).Take(_projectileWeapon.BurstCount-1)
// .Subscribe(l => Fire(l+1));
// }
// });
@ -60,19 +60,19 @@ public class Cannon : IActivatedBehavior
private void Fire(long b)
{
// _firingVisibility += _cannon.Visibility.Evaluate(Hardpoint);
// Hardpoint.Temperature += _cannon.Heat.Evaluate(Hardpoint) / Hardpoint.HeatCapacity;
// var inst = GameObject.Instantiate(_cannon.BulletPrefab).transform;
// _firingVisibility += _projectileWeapon.Visibility.Evaluate(Hardpoint);
// Hardpoint.Temperature += _projectileWeapon.Heat.Evaluate(Hardpoint) / Hardpoint.HeatCapacity;
// var inst = GameObject.Instantiate(_projectileWeapon.BulletPrefab).transform;
// Physics.IgnoreCollision(Hardpoint.Ship.Ship.GetComponent<Collider>(), inst.GetComponent<Collider>());
// var bullet = inst.GetComponent<Bullet>();
// bullet.Target = Hardpoint.Ship.Ship.Target;
// bullet.Source = Hardpoint.Ship.Ship.Hitpoints;
// bullet.Lifetime = _cannon.Range.Evaluate(Hardpoint) / _cannon.Velocity.Evaluate(Hardpoint);
// bullet.Damage = _cannon.Damage.Evaluate(Hardpoint);
// bullet.Lifetime = _projectileWeapon.Range.Evaluate(Hardpoint) / _projectileWeapon.Velocity.Evaluate(Hardpoint);
// bullet.Damage = _projectileWeapon.Damage.Evaluate(Hardpoint);
// inst.position = Hardpoint.Proxy.position;
// inst.rotation = Hardpoint.Proxy.rotation;
// inst.GetComponent<Rigidbody>().velocity = _cannon.Velocity.Evaluate(Hardpoint) * Vector3.RotateTowards(-inst.forward, Hardpoint.Ship.Ship.Direction, _cannon.Deflection * Mathf.Deg2Rad, 1);
// Hardpoint.Ship.Ship.AudioSource.PlayOneShot(_cannon.Sounds.RandomElement());
// inst.GetComponent<Rigidbody>().velocity = _projectileWeapon.Velocity.Evaluate(Hardpoint) * Vector3.RotateTowards(-inst.forward, Hardpoint.Ship.Ship.Direction, _projectileWeapon.Deflection * Mathf.Deg2Rad, 1);
// Hardpoint.Ship.Ship.AudioSource.PlayOneShot(_projectileWeapon.Sounds.RandomElement());
// Debug.Log($"Firing bullet {b}");
}
@ -87,9 +87,9 @@ public class Cannon : IActivatedBehavior
public void Update(float delta)
{
_cooldown -= delta / Context.Evaluate(_cannon.Cooldown, Item, Entity);
_cooldown -= delta / Context.Evaluate(_projectileWeapon.Cooldown, Item, Entity);
_firingVisibility *= Context.Evaluate(_cannon.VisibilityDecay, Item, Entity);
_firingVisibility *= Context.Evaluate(_projectileWeapon.VisibilityDecay, Item, Entity);
if (_firingVisibility < 0.01f)
{
@ -97,5 +97,5 @@ public class Cannon : IActivatedBehavior
}
}
public IBehaviorData Data => _cannon;
public IBehaviorData Data => _projectileWeapon;
}

View file

@ -1,7 +1,7 @@
using MessagePack;
using Newtonsoft.Json;
[Union(0, typeof(CannonData)),
[Union(0, typeof(ProjectileWeaponData)),
Union(1, typeof(LauncherData))]
public abstract class WeaponData
{

View file

@ -30,7 +30,7 @@ public interface INamedEntry
Union(11, typeof(Player)),
Union(12, typeof(Corporation)),
Union(13, typeof(Ship)),
Union(14, typeof(Station)),
Union(14, typeof(StationData)),
Union(15, typeof(OrbitData)),
Union(16, typeof(PlanetData)),
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]

View file

@ -14,6 +14,7 @@ public class Entity
public float Energy;
public float2 Position;
public float2 Direction;
public float2 Velocity;
protected readonly GameContext Context;
protected readonly List<IBehavior> Behaviors;

View file

@ -7,23 +7,87 @@ using static Unity.Mathematics.math;
public class GameContext
{
private Action<string> _logger;
private DatabaseCache _cache;
public GlobalData GlobalData => _cache.GetAll<GlobalData>().FirstOrDefault();
private Dictionary<BlueprintStatEffect, PerformanceStat> AffectedStats =
new Dictionary<BlueprintStatEffect, PerformanceStat>();
private double _time;
private float _deltaTime;
public GlobalData GlobalData => Cache.GetAll<GlobalData>().FirstOrDefault();
public DatabaseCache Cache { get; }
public double Time
{
get => _time;
set
{
_deltaTime = (float) (value - _time);
_time = value;
}
}
private Dictionary<ZoneData, Dictionary<DatabaseEntry, Entity>> ZoneContents = new Dictionary<ZoneData, Dictionary<DatabaseEntry, Entity>>();
// private readonly Dictionary<CraftedItemData, int> Tier = new Dictionary<CraftedItemData, int>();
public GameContext(DatabaseCache cache, Action<string> logger)
{
_cache = cache;
Cache = cache;
_logger = logger;
var globalData = _cache.GetAll<GlobalData>().FirstOrDefault();
var globalData = Cache.GetAll<GlobalData>().FirstOrDefault();
if (globalData == null)
{
globalData = new GlobalData();
_cache.Add(globalData);
Cache.Add(globalData);
}
}
public void Log(string s)
{
_logger(s);
}
public Dictionary<DatabaseEntry, Entity> InitializeZone(Guid zoneID)
{
var contents = new Dictionary<DatabaseEntry, Entity>();
var zoneData = Cache.Get<ZoneData>(zoneID);
var planetsData = zoneData.Planets.Select(id => Cache.Get<PlanetData>(id)).ToArray();
var planetEntities = planetsData.ToDictionary(p => p,
p => new OrbitalEntity(this, Enumerable.Empty<Gear>(), Enumerable.Empty<ItemInstance>(), p.Orbit));
foreach(var kvp in planetEntities)
contents.Add(kvp.Key, kvp.Value);
var stationsData = zoneData.Stations.Select(id => Cache.Get<StationData>(id));
var stationEntities = stationsData.ToDictionary(s => s,
s => new OrbitalEntity(this, Enumerable.Empty<Gear>(), Enumerable.Empty<ItemInstance>(), s.Parent));
foreach(var kvp in stationEntities)
contents.Add(kvp.Key, kvp.Value);
ZoneContents.Add(zoneData, contents);
return contents;
}
public void Update()
{
foreach (var kvp in ZoneContents)
{
var zone = kvp.Key;
var entities = kvp.Value.Values;
foreach (var entity in entities)
{
entity.Update(_deltaTime);
}
}
}
public void UnloadZone(ZoneData zone)
{
ZoneContents.Remove(zone);
}
// public int ItemTier(CraftedItemData itemData)
// {
@ -36,22 +100,22 @@ public class GameContext
public ItemData GetData(ItemInstance item)
{
return _cache.Get<ItemData>(item.Data);
return Cache.Get<ItemData>(item.Data);
}
public SimpleCommodityData GetData(SimpleCommodity item)
{
return _cache.Get<SimpleCommodityData>(item.Data);
return Cache.Get<SimpleCommodityData>(item.Data);
}
public CraftedItemData GetData(CraftedItemInstance item)
{
return _cache.Get<CraftedItemData>(item.Data);
return Cache.Get<CraftedItemData>(item.Data);
}
public EquippableItemData GetData(Gear gear)
{
return _cache.Get<EquippableItemData>(gear.Data);
return Cache.Get<EquippableItemData>(gear.Data);
}
public float GetMass(ItemInstance item)
@ -82,16 +146,13 @@ public class GameContext
return 0;
}
private Dictionary<BlueprintStatEffect, PerformanceStat> AffectedStats =
new Dictionary<BlueprintStatEffect, PerformanceStat>();
public PerformanceStat GetAffectedStat(BlueprintData blueprint, BlueprintStatEffect effect)
{
// We've already cached this effect's stat, return it directly
if (AffectedStats.ContainsKey(effect)) return AffectedStats[effect];
// Get the data for the item the blueprint is for, return null if not found or not equippable
var blueprintItem = _cache.Get<EquippableItemData>(blueprint.Item);
var blueprintItem = Cache.Get<EquippableItemData>(blueprint.Item);
if (blueprintItem == null)
{
_logger($"Attempted to get stat effect but Blueprint {blueprint.ID} is not for an equippable item!");
@ -99,25 +160,25 @@ public class GameContext
}
// Get the first behavior of the type specified in the blueprint stat effect, return null if not found
var effectBehavior =
var effectObject = effect.StatReference.Behavior == blueprintItem.Name ? (object) blueprintItem :
blueprintItem.Behaviors.FirstOrDefault(b => b.GetType().Name == effect.StatReference.Behavior);
if (effectBehavior == null)
if (effectObject == null)
{
_logger($"Attempted to get stat effect for Blueprint {blueprint.ID} but stat references missing behavior \"{effect.StatReference.Behavior}\"!");
return AffectedStats[effect] = null;
}
// Get the first field in the behavior matching the name specified in the stat effect, return null if not found
var type = effectBehavior.GetType();
var type = effectObject.GetType();
var field = type.GetField(effect.StatReference.Stat);
if (field == null)
{
_logger($"Attempted to get stat effect for Blueprint {blueprint.ID} but behavior {effect.StatReference.Behavior} does not have a stat named \"{effect.StatReference.Stat}\"!");
_logger($"Attempted to get stat effect for Blueprint {blueprint.ID} but object {effect.StatReference.Behavior} does not have a stat named \"{effect.StatReference.Stat}\"!");
return AffectedStats[effect] = null;
}
// Finally we've confirmed the stat effect is valid, return the affected stat
return AffectedStats[effect] = field.GetValue(effectBehavior) as PerformanceStat;
return AffectedStats[effect] = field.GetValue(effectObject) as PerformanceStat;
}
// Determine quality of either the item itself or the specific ingredient this stat depends on
@ -170,7 +231,7 @@ public class GameContext
var itemData = GetData(item);
var heat = !stat.HeatDependent ? 1 : pow(itemData.Performance(entity.Temperature), Evaluate(itemData.HeatExponent,item));
var durability = !stat.DurabilityDependent ? 1 : pow(item.Durability / itemData.Durability, Evaluate(itemData.DurabilityExponent,item));
var durability = !stat.DurabilityDependent ? 1 : pow(item.Durability / Evaluate(itemData.Durability, item), Evaluate(itemData.DurabilityExponent,item));
var quality = pow(Quality(stat, item), stat.QualityExponent);
var scaleModifier = stat.GetScaleModifiers(entity).Values.Aggregate(1.0f, (current, mod) => current * mod);
@ -185,7 +246,7 @@ public class GameContext
public SimpleCommodity CreateInstance(Guid data, int count)
{
var item = _cache.Get<SimpleCommodityData>(data);
var item = Cache.Get<SimpleCommodityData>(data);
if (item != null)
return new SimpleCommodity
{
@ -200,14 +261,14 @@ public class GameContext
public CraftedItemInstance CreateInstance(Guid data, float quality)
{
var item = _cache.Get<CraftedItemData>(data);
var item = Cache.Get<CraftedItemData>(data);
if (item == null)
{
_logger("Attempted to create crafted item instance using missing or incorrect item id!");
return null;
}
var blueprint = _cache.GetAll<BlueprintData>().FirstOrDefault(b => b.Item == data);
var blueprint = Cache.GetAll<BlueprintData>().FirstOrDefault(b => b.Item == data);
if (blueprint == null)
{
_logger("Attempted to create crafted item instance which has no blueprint!");
@ -216,7 +277,7 @@ public class GameContext
var ingredients = blueprint.Ingredients.SelectMany(ci =>
{
var ingredient = _cache.Get(ci.Key);
var ingredient = Cache.Get(ci.Key);
return ingredient is SimpleCommodityData
? (IEnumerable<ItemInstance>) new[] {CreateInstance(ci.Key, ci.Value)}
: Enumerable.Range(0, ci.Value).Select(i => CreateInstance(ci.Key, quality));
@ -225,15 +286,16 @@ public class GameContext
if (item is EquippableItemData equippableItemData)
{
return new Gear
var newGear = new Gear
{
Context = this,
Data = data,
Durability = equippableItemData.Durability,
ID = Guid.NewGuid(),
Ingredients = ingredients,
Quality = quality
};
newGear.Durability = Evaluate(equippableItemData.Durability, newGear);
return newGear;
}
return new CompoundCommodity
@ -245,4 +307,4 @@ public class GameContext
Quality = quality
};
}
}
}

View file

@ -87,8 +87,8 @@ public abstract class EquippableItemData : CraftedItemData
[TemperatureInspectable, JsonProperty("maxTemp"), Key(9)]
public float MaximumTemperature;
[InspectableField, JsonProperty("durability"), Key(10)]
public float Durability;
[InspectableField, JsonProperty("durabilityStat"), Key(10)]
public PerformanceStat Durability = new PerformanceStat();
[InspectableField, JsonProperty("durabilityExponent"), Key(11)]
public PerformanceStat DurabilityExponent = new PerformanceStat();

View file

@ -0,0 +1,17 @@
using System.Collections;
using System.Collections.Generic;
public class Locomotion
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}

View file

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

View file

@ -0,0 +1,54 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
public class OrbitalEntity : Entity
{
private Guid _orbitData;
private static Dictionary<Guid, float2> _orbitPositions = new Dictionary<Guid, float2>();
public OrbitalEntity(GameContext context, IEnumerable<Gear> items, IEnumerable<ItemInstance> cargo, Guid orbit) : base(context, items, cargo)
{
_orbitData = orbit;
}
public static void ClearOrbits()
{
_orbitPositions.Clear();
}
// Determine orbital position recursively, caching parent positions to avoid repeated calculations
private float2 GetOrbitPosition(Guid orbit)
{
// Root orbit is fixed at center
if(orbit==Guid.Empty)
return float2.zero;
if (!_orbitPositions.ContainsKey(orbit))
{
var orbitData = Context.Cache.Get<OrbitData>(orbit);
_orbitPositions[orbit] = GetOrbitPosition(orbitData.Parent) + (orbitData.Period < .01f ? float2.zero :
OrbitData.Evaluate((float) (Context.Time / -orbitData.Period + orbitData.Phase)) *
orbitData.Distance);
}
var position = _orbitPositions[orbit];
if (float.IsNaN(position.x))
{
Context.Log("Orbit position is NaN, something went very wrong!");
return float2.zero;
}
return _orbitPositions[orbit];
}
public override void Update(float delta)
{
var newPosition = GetOrbitPosition(_orbitData);
Velocity = (newPosition - Position) / delta;
Position = newPosition;
base.Update(delta);
}
}

View file

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

View file

@ -20,10 +20,8 @@ public class Ship : Entity
// [IgnoreMember] public Dictionary<Targetable, float> Contacts = new Dictionary<Targetable, float>();
// [IgnoreMember] public Targetable Target;
[IgnoreMember] public float2 Velocity;
private HullData _hullData;
public Ship(GameContext context, IEnumerable<Gear> items, IEnumerable<ItemInstance> cargo) : base(context, items, cargo)
{

View file

@ -41,7 +41,7 @@ public class ZoneData : DatabaseEntry, INamedEntry
}
[RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class Station : DatabaseEntry, INamedEntry
public class StationData : DatabaseEntry, INamedEntry
{
[JsonProperty("name"), Key(1)]
public string Name;
@ -90,7 +90,7 @@ public class PlanetData : DatabaseEntry, INamedEntry
[JsonProperty("belt"), Key(5)]
public bool Belt;
[JsonProperty("resources"), Key(5)]
[JsonProperty("resources"), Key(6)]
public Dictionary<Guid, float> Resources = new Dictionary<Guid, float>();
// [JsonProperty("radius")] [Key(5)]