Restore the stable legacy Unity project

This commit is contained in:
Meta Vens 2026-08-10 14:57:50 +01:00
commit 7006a6b0dd
2070 changed files with 180490 additions and 169303 deletions

View file

@ -0,0 +1,32 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
public abstract class NotAnActionCollection{}
public class ActionCollection<T> : NotAnActionCollection where T : Message
{
private List<Action<T>> _actions = new List<Action<T>>();
public void Add(Action<T> action)
{
_actions.Add(action);
}
public void Invoke(T message)
{
foreach (var action in _actions)
{
action(message);
}
}
public void Clear()
{
_actions.Clear();
}
}

View file

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 7b36e5ee07ee44d68e755ea4993d9dd6
guid: 24330c4f854f8d047a47cbe0ae360b73
MonoImporter:
externalObjects: {}
serializedVersion: 2

View file

@ -2,11 +2,11 @@
"name": "Aetheria.Shared.Unity",
"rootNamespace": "",
"references": [
"CultMath",
"MessagePack",
"Unity.Mathematics",
"UniRx",
"Ink",
"GameCult.Aetheria.State.Unity"
"RethinkDB",
"Ink"
],
"includePlatforms": [],
"excludePlatforms": [],
@ -17,4 +17,4 @@
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": true
}
}

View file

@ -1,78 +1,13 @@
using System.Collections;
using System.Collections.Generic;
using CultMath;
using static CultMath.math;
using double2 = CultMath.double2;
using double3 = CultMath.double3;
using float2 = CultMath.float2;
using float3 = CultMath.float3;
using unityfloat2 = Unity.Mathematics.float2;
using unityfloat3 = Unity.Mathematics.float3;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public static class AetheriaMath
{
public const float Deg2Rad = 0.01745329f;
public const float Rad2Deg = 57.29578f;
public static float2 ToCult(unityfloat2 value) => float2(value.x, value.y);
public static float3 ToCult(unityfloat3 value) => float3(value.x, value.y, value.z);
public static float2 ToCultXZ(unityfloat3 value) => float2(value.x, value.z);
public static unityfloat2 ToUnity(float2 value) => new(value.x, value.y);
public static unityfloat3 ToUnity(float3 value) => new(value.x, value.y, value.z);
public static unityfloat3 ToUnityXZ(float2 value) => new(value.x, 0, value.y);
public static float AngleDegrees(float2 from, float2 to)
{
return AngleRadians(from, to) * Rad2Deg;
}
public static float AngleDegrees(float3 from, float3 to)
{
return AngleRadians(from, to) * Rad2Deg;
}
public static float AngleDegrees(unityfloat2 from, unityfloat2 to)
{
return AngleDegrees(ToCult(from), ToCult(to));
}
public static float AngleDegrees(unityfloat3 from, unityfloat3 to)
{
return AngleDegrees(ToCult(from), ToCult(to));
}
public static float AngleRadians(float2 from, float2 to)
{
var denom = sqrt(lengthsq(from) * lengthsq(to));
if (denom <= 0.000001f)
{
return 0;
}
return acos(clamp(dot(from, to) / denom, -1.0f, 1.0f));
}
public static float AngleRadians(float3 from, float3 to)
{
var denom = sqrt(lengthsq(from) * lengthsq(to));
if (denom <= 0.000001f)
{
return 0;
}
return acos(clamp(dot(from, to) / denom, -1.0f, 1.0f));
}
public static float AngleRadians(unityfloat2 from, unityfloat2 to)
{
return AngleRadians(ToCult(from), ToCult(to));
}
public static float AngleRadians(unityfloat3 from, unityfloat3 to)
{
return AngleRadians(ToCult(from), ToCult(to));
}
public static float Decay(float source, float lambda, float dt)
{
return source * exp(-lambda * dt);
@ -83,20 +18,10 @@ public static class AetheriaMath
return source * exp(-lambda * dt);
}
public static unityfloat3 Decay(unityfloat3 source, float lambda, float dt)
{
return ToUnity(Decay(ToCult(source), lambda, dt));
}
public static float3 Decay(float3 source, float3 lambda, float dt)
{
return source * exp(-lambda * dt);
}
public static unityfloat3 Decay(unityfloat3 source, unityfloat3 lambda, float dt)
{
return ToUnity(Decay(ToCult(source), ToCult(lambda), dt));
}
public static float Damp(float a, float b, float lambda, float dt)
{
@ -107,21 +32,11 @@ public static class AetheriaMath
{
return lerp(a, b, 1 - exp(-lambda * dt));
}
public static unityfloat2 Damp(unityfloat2 a, unityfloat2 b, float lambda, float dt)
{
return ToUnity(Damp(ToCult(a), ToCult(b), lambda, dt));
}
public static float3 Damp(float3 a, float3 b, float lambda, float dt)
{
return lerp(a, b, 1 - exp(-lambda * dt));
}
public static unityfloat3 Damp(unityfloat3 a, unityfloat3 b, float lambda, float dt)
{
return ToUnity(Damp(ToCult(a), ToCult(b), lambda, dt));
}
public static double Damp(double a, double b, double lambda, double dt)
{
@ -157,22 +72,6 @@ public static class AetheriaMath
);
return targetPosition + t*targetRelativeVelocity;
}
public static unityfloat3 FirstOrderIntercept
(
unityfloat3 shooterPosition,
unityfloat3 shooterVelocity,
float shotSpeed,
unityfloat3 targetPosition,
unityfloat3 targetVelocity
) {
return ToUnity(FirstOrderIntercept(
ToCult(shooterPosition),
ToCult(shooterVelocity),
shotSpeed,
ToCult(targetPosition),
ToCult(targetVelocity)));
}
//first-order intercept using relative target position
public static float FirstOrderInterceptTime
@ -213,15 +112,6 @@ public static class AetheriaMath
else //determinant = 0; one intercept path, pretty much never happens
return max(-b/(2f*a), 0f); //don't shoot back in time
}
public static float FirstOrderInterceptTime
(
float shotSpeed,
unityfloat3 targetRelativePosition,
unityfloat3 targetRelativeVelocity
) {
return FirstOrderInterceptTime(shotSpeed, ToCult(targetRelativePosition), ToCult(targetRelativeVelocity));
}
// http://csharphelper.com/blog/2016/09/find-the-shortest-distance-between-a-point-and-a-line-segment-in-c/
// Calculate the distance between
@ -350,38 +240,4 @@ public static class AetheriaMath
x = saturate(x);
return x * x * x * (x * (x * 6 - 15) + 10);
}
public static float2 Rotate(float2 value, float radians)
{
var s = (float)System.Math.Sin(radians);
var c = (float)System.Math.Cos(radians);
return float2(value.x * c - value.y * s, value.x * s + value.y * c);
}
public static float2 Rotate(float2 value, ItemRotation rotation)
{
switch (rotation)
{
case ItemRotation.None:
return value;
case ItemRotation.CounterClockwise:
return float2(-value.y, value.x);
case ItemRotation.Reversed:
return float2(-value.x, -value.y);
case ItemRotation.Clockwise:
return float2(value.y, -value.x);
default:
throw new System.ArgumentOutOfRangeException(nameof(rotation), rotation, null);
}
}
public static unityfloat2 Rotate(unityfloat2 value, float radians)
{
return ToUnity(Rotate(ToCult(value), radians));
}
public static unityfloat2 Rotate(unityfloat2 value, ItemRotation rotation)
{
return ToUnity(Rotate(ToCult(value), rotation));
}
}

View file

@ -1,30 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using cfloat3 = CultMath.float3;
public interface INamedEntry
{
string EntryName { get; set; }
}
public class AetheriaRuntimeItemReference
{
public string ItemKey;
public AetheriaRuntimeItemReference()
{
}
public AetheriaRuntimeItemReference(string itemKey)
{
ItemKey = itemKey;
}
}
public interface ITintInspector
{
cfloat3 TintColor { get; }
}

View file

@ -7,8 +7,9 @@ using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UniRx;
using static CultMath.math;
using cfloat2 = CultMath.float2;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
public class Agent
{
@ -54,27 +55,26 @@ public class Agent
}
}
public void Accelerate(cfloat2 targetVelocity, bool noTurn = false)
public void Accelerate(float2 targetVelocity, bool noTurn = false)
{
var deltaV = targetVelocity - Ship.CultVelocity;
var deltaV = targetVelocity - Ship.Velocity;
var deltaVMag = length(deltaV);
var deltaVDirection = normalize(deltaV);
// If Delta V is above the threshold, direct the ship towards the delta and use only main thrusters
if (!noTurn && deltaVMag > FORWARD_DELTA_THRESHOLD)
{
Ship.CultLookDirectionXZ = deltaVDirection;
Ship.MovementDirection = new cfloat2(0, pow(dot(Ship.CultDirection, deltaVDirection), 2));
Ship.LookDirection = float3(deltaVDirection.x, 0, deltaVDirection.y);
Ship.MovementDirection = float2(0, pow(dot(Ship.Direction, deltaVDirection), 2));
}
// If Delta V is low, direct the ship towards the target and use all thrusters
else if(deltaVMag > THRUST_DELTA_THRESHOLD)
{
var shipDirection = Ship.CultDirection;
var right = AetheriaMath.Rotate(shipDirection, ItemRotation.Clockwise);
Ship.MovementDirection = new cfloat2(dot(right, deltaVDirection), dot(shipDirection, deltaVDirection));
var right = Ship.Direction.Rotate(ItemRotation.Clockwise);
Ship.MovementDirection = float2(dot(right, deltaVDirection), dot(Ship.Direction, deltaVDirection));
}
else
{
Ship.MovementDirection = cfloat2.zero;
Ship.MovementDirection = float2.zero;
}
}
}

View file

@ -2,8 +2,10 @@ using System;
using System.Collections.Generic;
using System.Linq;
using UniRx;
using static CultMath.math;
using cfloat3 = CultMath.float3;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
using float3 = Unity.Mathematics.float3;
using float2x2 = Unity.Mathematics.float2x2;
public class CombatState : BaseState
{
@ -11,7 +13,7 @@ public class CombatState : BaseState
private float _optimumRange;
private readonly List<(int index, float dps)> _availableGroups = new List<(int index, float dps)>();
private readonly List<LockWeapon> _availableLockingWeapons = new List<LockWeapon>();
public CombatState(Agent agent) : base(agent)
{
SampleDps();
@ -29,9 +31,7 @@ public class CombatState : BaseState
_availableGroups.Clear();
_availableLockingWeapons.Clear();
var shipPosition = _agent.Ship.CultPosition;
var targetPosition = target.CultPosition;
var toTarget = targetPosition - shipPosition;
var toTarget = target.Position - _agent.Ship.Position;
var targetDistance = length(toTarget);
for (var i = 0; i < _agent.Ship.WeaponGroups.Length; i++)
{
@ -66,17 +66,16 @@ public class CombatState : BaseState
}
}
var targetDirection = target.CultDirection;
var targetRight = AetheriaMath.Rotate(targetDirection, ItemRotation.Clockwise);
var targetRight = target.Direction.Rotate(ItemRotation.Clockwise);
var optimumRangeDelta = abs(_optimumRange - targetDistance);
var directionToTarget = normalize(toTarget.xz);
var targetPortAlignment = dot(targetRight, directionToTarget);
var targetForeAlignment = dot(-targetDirection, directionToTarget);
var targetForeAlignment = dot(-target.Direction, directionToTarget);
var forwardness = saturate(optimumRangeDelta / _agent.Settings.AgentMaxForwardDistance) * _agent.Settings.AgentForwardLerp;
if (targetForeAlignment > 0) forwardness = lerp(forwardness, 1, pow(targetPortAlignment, 2));
var movementDirection = normalize(lerp(
AetheriaMath.Rotate(directionToTarget, targetPortAlignment > 0 ? ItemRotation.Clockwise : ItemRotation.CounterClockwise),
directionToTarget.Rotate(targetPortAlignment > 0 ? ItemRotation.Clockwise : ItemRotation.CounterClockwise),
targetDistance > _optimumRange ? directionToTarget : -directionToTarget, forwardness));
if (selectedGroup >= 0)
@ -84,17 +83,18 @@ public class CombatState : BaseState
var testWeapon = _agent.Ship.WeaponGroups[selectedGroup].weapons.First();
if(testWeapon.Velocity > 1)
{
var targetHull = _agent.ItemManager.GetRuntimeItem(target.Hull);
var targetVelocity = new cfloat3(target.CultVelocity.x, 0, target.CultVelocity.y);
var targetHullData = _agent.ItemManager.GetData(target.Hull) as HullData;
var targetVelocity = float3(target.Velocity.x, 0, target.Velocity.y);
var shipVelocity = float3(_agent.Ship.Velocity.x, 0, _agent.Ship.Velocity.y);
var predictedPosition = AetheriaMath.FirstOrderIntercept(
shipPosition,
cfloat3.zero,
_agent.Ship.Position,
float3.zero,
testWeapon.Velocity,
targetPosition,
target.Position,
targetVelocity
);
predictedPosition.y = _agent.Ship.Zone.GetHeight(predictedPosition.xz) + (float)(targetHull?.HullGridOffset ?? 0);
toTarget = normalize(predictedPosition - shipPosition);
predictedPosition.y = _agent.Ship.Zone.GetHeight(predictedPosition.xz) + targetHullData.GridOffset;
toTarget = normalize(predictedPosition - _agent.Ship.Position);
}
var shouldFire = dot(
@ -108,7 +108,7 @@ public class CombatState : BaseState
weapon.Deactivate();
}
}
_agent.Ship.CultLookDirection = toTarget;
_agent.Ship.LookDirection = toTarget;
_agent.Accelerate(movementDirection * _agent.TopSpeed, true);//selectedGroup >= 0);
// Fire charged guns!
@ -148,4 +148,4 @@ public class CombatState : BaseState
}
}
}
}
}

View file

@ -1,9 +1,10 @@
using static CultMath.math;
using cfloat2 = CultMath.float2;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
public abstract class MatchVelocityState : BaseState
{
protected abstract cfloat2 TargetVelocity { get; }
protected abstract float2 TargetVelocity { get; }
protected MatchVelocityState(Agent agent) : base(agent) { }
@ -12,12 +13,12 @@ public abstract class MatchVelocityState : BaseState
_agent.Accelerate(TargetVelocity);
}
public cfloat2 MatchDistanceTime
public float2 MatchDistanceTime
{
get
{
var velocity = length(_agent.Ship.CultVelocity);
var deltaV = TargetVelocity - _agent.Ship.CultVelocity;
var velocity = length(_agent.Ship.Velocity);
var deltaV = TargetVelocity - _agent.Ship.Velocity;
var stoppingTime = length(deltaV) / (_agent.Ship.ForwardThrust / _agent.Ship.Mass);
var stoppingDistance = stoppingTime * (velocity / 2);
@ -25,7 +26,7 @@ public abstract class MatchVelocityState : BaseState
var turnaroundTime = _agent.Ship.TurnTime(deltaV);
var turnaroundDistance = turnaroundTime * velocity;
return new cfloat2(stoppingDistance + turnaroundDistance, stoppingTime + turnaroundTime);
return float2(stoppingDistance + turnaroundDistance, stoppingTime + turnaroundTime);
}
}
}
}

View file

@ -1,12 +1,13 @@
using System;
using static CultMath.math;
using cfloat2 = CultMath.float2;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
public abstract class MoveToState : BaseState
{
private VelocityLimit _velocityLimit;
protected abstract cfloat2 TargetPosition { get; }
protected abstract float2 TargetPosition { get; }
public float Distance { get; private set; }
protected MoveToState(Agent agent) : base(agent)
@ -15,13 +16,13 @@ public abstract class MoveToState : BaseState
public override void Update(float delta)
{
var diff = TargetPosition - _agent.Ship.CultPositionXZ;
var diff = TargetPosition - _agent.Ship.Position.xz;
var dir = normalize(diff);
Distance = length(diff);
// We want to go top speed in the direction of our target
var desiredVelocity = dir * _agent.TopSpeed;
_agent.Ship.CultLookDirectionXZ = dir;
_agent.Ship.LookDirection = float3(dir.x, 0, dir.y);
_agent.Accelerate(desiredVelocity);
}
}
@ -29,15 +30,15 @@ public abstract class MoveToState : BaseState
public class MoveToEntityState : MoveToState
{
public Entity TargetEntity { get; set; }
protected override cfloat2 TargetPosition => TargetEntity != null ? TargetEntity.CultPositionXZ : cfloat2.zero;
protected override float2 TargetPosition => TargetEntity?.Position.xz ?? float2.zero;
public MoveToEntityState(Agent agent) : base(agent) { }
}
public class MoveToOrbitState : MoveToState
{
public string OrbitKey { get; set; } = "";
public Guid Orbit { get; set; }
public MoveToOrbitState(Agent agent) : base(agent) { }
protected override cfloat2 TargetPosition => AetheriaMath.ToCult(_agent.Ship.Zone.GetOrbitPosition(OrbitKey));
protected override float2 TargetPosition => _agent.Ship.Zone.GetOrbitPosition(Orbit);
}

View file

@ -1,16 +1,32 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
public abstract class AgentTask
using System;
using System.Collections;
using System.Collections.Generic;
using JsonKnownTypes;
using MessagePack;
using Newtonsoft.Json;
[MessagePackObject,
Union(0, typeof(StationTowing)),
Union(1, typeof(Mining)),
Union(2, typeof(Survey)),
Union(3, typeof(HaulingTask)),
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
public abstract class AgentTask : DatabaseEntry
{
[JsonProperty("priority"), Key(1)]
public int Priority;
public string ZoneKey = "";
[JsonProperty("zone"), Key(2)]
public Guid Zone;
[JsonProperty("reserved"), Key(3)]
public bool Reserved;
public abstract TaskType Type { get; }
[IgnoreMember] public abstract TaskType Type { get; }
}
public enum TaskType

View file

@ -1,16 +1,26 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
public class HaulingTask : AgentTask
{
public override TaskType Type => TaskType.Haul;
[JsonProperty("origin"), Key(4)]
public Entity Origin;
[JsonProperty("target"), Key(5)]
public Entity Target;
public string ItemKey;
[JsonProperty("itemType"), Key(6)]
public Guid ItemType;
[JsonProperty("quantity"), Key(7)]
public int Quantity;
}

View file

@ -1,10 +1,20 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
using JsonKnownTypes;
using MessagePack;
using Newtonsoft.Json;
[MessagePackObject,
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
public class Mining : AgentTask
{
public override TaskType Type => TaskType.Mine;
public string AsteroidBeltBodyKey = "";
}
[IgnoreMember] public override TaskType Type => TaskType.Mine;
[JsonProperty("asteroids"), Key(4)]
public Guid Asteroids;
}

View file

@ -3,13 +3,13 @@ using System;
public class PatrolOrbitsTask : AgentTask
{
public override TaskType Type => TaskType.Defend;
public string[] Circuit = Array.Empty<string>();
public Guid[] Circuit;
}
public class PatrolOrbitsState : BaseState
{
public PatrolOrbitsTask Task;
public string CurrentTarget
public Guid CurrentTarget
{
get => Task.Circuit[_currentTargetIndex];
}
@ -25,7 +25,7 @@ public class PatrolOrbitsState : BaseState
var patrolMoveState = new MoveToOrbitState(agent);
Transitions.Add(new StateTransition(patrolMoveState,
() => true,
() => patrolMoveState.OrbitKey = CurrentTarget));
() => patrolMoveState.Orbit = CurrentTarget));
patrolMoveState.Transitions.Add(new StateTransition(this, () => patrolMoveState.Distance < 10, NextTarget));
}
}
}

View file

@ -1,16 +1,26 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
using JsonKnownTypes;
using MessagePack;
using Newtonsoft.Json;
[MessagePackObject,
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
public class StationTowing : AgentTask
{
public override TaskType Type => TaskType.Tow;
[IgnoreMember] public override TaskType Type => TaskType.Tow;
[JsonProperty("station"), Key(4)]
public OrbitalEntity Station;
public string OrbitParentKey = "";
[JsonProperty("orbitParent"), Key(5)]
public Guid OrbitParent;
[JsonProperty("orbitDistance"), Key(6)]
public float OrbitDistance;
}

View file

@ -1,12 +1,20 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
using JsonKnownTypes;
using MessagePack;
using Newtonsoft.Json;
[MessagePackObject,
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
public class Survey : AgentTask
{
public override TaskType Type => TaskType.Explore;
public List<string> PlanetBodyKeys;
}
[IgnoreMember] public override TaskType Type => TaskType.Explore;
[JsonProperty("station"), Key(4)]
public List<Guid> Planets;
}

View file

@ -0,0 +1,27 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
[AttributeUsage(AttributeTargets.Class)]
public class EntityTypeRestrictionAttribute : Attribute
{
public readonly HullType Type;
public EntityTypeRestrictionAttribute(HullType type)
{
Type = type;
}
}
public class RuntimeInspectable : Attribute { }
// public class CategoryAttribute : Attribute
// {
// public readonly Type Type;
//
// public CategoryAttribute(Type type)
// {
// Type = type;
// }
// }

View file

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

View file

@ -2,153 +2,145 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using static CultMath.math;
using cfloat2 = CultMath.float2;
using cfloat3 = CultMath.float3;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), EntityTypeRestriction(HullType.Ship), RuntimeInspectable]
public class AetherDriveData : BehaviorData
{
[Inspectable, JsonProperty("diameters"), Key(1)]
public float3 RotorDiameter;
[Inspectable, JsonProperty("masses"), Key(2)]
public float3 RotorMass;
[Inspectable, JsonProperty("rpm"), Key(3), RuntimeInspectable]
public PerformanceStat MaximumRpm;
[Inspectable, JsonProperty("couplingLambdas"), Key(4)]
public float3 CouplingLambda;
[Inspectable, JsonProperty("lambdaMultiplier"), Key(5)]
public PerformanceStat LambdaMultiplier;
[Inspectable, JsonProperty("couplingEfficiency"), Key(6), RuntimeInspectable]
public PerformanceStat CouplingEfficiency;
[Inspectable, JsonProperty("torque"), Key(7), RuntimeInspectable]
public PerformanceStat Torque;
[Inspectable, JsonProperty("torqueProfile"), Key(8), RuntimeInspectable]
public BezierCurve TorqueProfile;
[Inspectable, JsonProperty("draw"), Key(9), RuntimeInspectable]
public PerformanceStat EnergyDraw;
[Inspectable, JsonProperty("passiveCoupling"), Key(10), RuntimeInspectable]
public PerformanceStat PassiveCoupling;
[InspectableAudioParameter, JsonProperty("rpmAudio"), Key(11), RuntimeInspectable]
public uint RpmAudioParameter;
[InspectableAudioParameter, JsonProperty("torqueAudio"), Key(12), RuntimeInspectable]
public uint TorqueRatioAudioParameter;
[InspectablePrefab, JsonProperty("particles"), Key(13)]
public string Particles;
public override Behavior CreateInstance(EquippedItem item)
{
return new AetherDrive(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new AetherDrive(this, item);
}
}
public class AetherDrive : Behavior
{
private readonly cfloat3 _rotorDiameter;
private readonly cfloat3 _rotorMass;
private readonly PerformanceStat _maximumRpm;
private readonly cfloat3 _couplingLambda;
private readonly PerformanceStat _lambdaMultiplier;
private readonly PerformanceStat _couplingEfficiency;
private readonly PerformanceStat _torque;
private readonly BezierCurve _torqueProfile;
private readonly PerformanceStat _energyDraw;
private readonly PerformanceStat _passiveCoupling;
private readonly uint _rpmAudioParameter;
private readonly uint _torqueRatioAudioParameter;
private cfloat3 _axis;
private AetherDriveData _data;
private float3 _axis;
public cfloat3 Thrust { get; private set; }
public cfloat3 Rpm { get; private set; }
public float3 Thrust { get; private set; }
public float3 Rpm { get; private set; }
public float MaximumRpm { get; private set; }
public cfloat2 ThrustDirection { get; private set; }
public string Particles { get; }
public float2 ThrustDirection { get; private set; }
public cfloat3 Axis
public AetherDriveData DriveData => _data;
public float3 Axis
{
get => _axis;
set => _axis = clamp(value, -1, 1);
}
public AetherDrive(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public AetherDrive(AetherDriveData data, EquippedItem item) : base(data, item)
{
_rotorDiameter = definition.Float3(1);
_rotorMass = definition.Float3(2);
_maximumRpm = definition.PerformanceStat(3, null);
_couplingLambda = definition.Float3(4);
_lambdaMultiplier = definition.PerformanceStat(5, null);
_couplingEfficiency = definition.PerformanceStat(6, null);
_torque = definition.PerformanceStat(7, null);
_torqueProfile = definition.BezierCurve(8, null);
_energyDraw = definition.PerformanceStat(9, null);
_passiveCoupling = definition.PerformanceStat(10, null);
_rpmAudioParameter = definition.UInt(11);
_torqueRatioAudioParameter = definition.UInt(12);
Particles = definition.String(13);
RegisterAetherDriveStats();
_data = data;
}
public AetherDrive(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public AetherDrive(AetherDriveData data, ConsumableItemEffect item) : base(data, item)
{
_rotorDiameter = definition.Float3(1);
_rotorMass = definition.Float3(2);
_maximumRpm = definition.PerformanceStat(3, null);
_couplingLambda = definition.Float3(4);
_lambdaMultiplier = definition.PerformanceStat(5, null);
_couplingEfficiency = definition.PerformanceStat(6, null);
_torque = definition.PerformanceStat(7, null);
_torqueProfile = definition.BezierCurve(8, null);
_energyDraw = definition.PerformanceStat(9, null);
_passiveCoupling = definition.PerformanceStat(10, null);
_rpmAudioParameter = definition.UInt(11);
_torqueRatioAudioParameter = definition.UInt(12);
Particles = definition.String(13);
RegisterAetherDriveStats();
}
private void RegisterAetherDriveStats()
{
RegisterPerformanceStat(nameof(MaximumRpm), _maximumRpm);
RegisterPerformanceStat("LambdaMultiplier", _lambdaMultiplier);
RegisterPerformanceStat("CouplingEfficiency", _couplingEfficiency);
RegisterPerformanceStat("Torque", _torque);
RegisterPerformanceStat("EnergyDraw", _energyDraw);
RegisterPerformanceStat("PassiveCoupling", _passiveCoupling);
_data = data;
}
public override bool Execute(float dt)
{
var rotorSpeed = Rpm * _rotorDiameter / 100;
var forward = normalize(Entity.CultDirection);
var right = AetheriaMath.Rotate(Entity.CultDirection, ItemRotation.Clockwise);
var velocity = Entity.CultVelocity;
var speed = float2(dot(velocity, forward), dot(velocity, right));
var couplingEfficiency = Evaluate(_couplingEfficiency);
var rotorSpeed = Rpm * _data.RotorDiameter / 100;
var forward = normalize(Entity.Direction);
var right = forward.Rotate(ItemRotation.Clockwise);
var speed = float2(dot(Entity.Velocity, forward), dot(Entity.Velocity, right));
var couplingEfficiency = Evaluate(_data.CouplingEfficiency);
var efficiency = float3(saturate(1 - speed / max(rotorSpeed.xy, 1) * sign(_axis.xy)) * couplingEfficiency, 1);
Thrust = (Rpm - AetheriaMath.Decay(Rpm, _couplingLambda, dt)) * _rotorMass * efficiency;
Thrust = (Rpm - AetheriaMath.Decay(Rpm, _data.CouplingLambda, dt)) * _data.RotorMass * efficiency;
var couplingLambda = _couplingLambda * Evaluate(_lambdaMultiplier) * max(abs(_axis), Evaluate(_passiveCoupling));
var couplingLambda = _data.CouplingLambda * Item.Evaluate(_data.LambdaMultiplier) * max(abs(_axis), Evaluate(_data.PassiveCoupling));
var previousRpm = Rpm;
Rpm = AetheriaMath.Decay(Rpm, couplingLambda, dt);
var rpmLoss = previousRpm - Rpm;
var force = rpmLoss * _rotorMass * efficiency;
var force = rpmLoss * _data.RotorMass * efficiency;
var heat = rpmLoss * _rotorMass * (1 - couplingEfficiency);
var heat = rpmLoss * _data.RotorMass * (1 - couplingEfficiency);
AddHeat((heat.x + heat.y + heat.z)*ItemManager.GameplaySettings.AetherHeatMultiplier);
ThrustDirection = forward * (_axis.x * force.x / Entity.Mass) + right * (_axis.y * force.y / Entity.Mass);
Entity.CultVelocity += ThrustDirection;
Entity.Velocity += ThrustDirection;
Entity.Direction = mul(Entity.Direction,
Unity.Mathematics.float2x2.Rotate(force.z * _axis.z * ItemManager.GameplaySettings.AetherTorqueMultiplier / Entity.Mass));
Entity.CultDirection = AetheriaMath.Rotate(
Entity.CultDirection,
force.z * _axis.z * ItemManager.GameplaySettings.AetherTorqueMultiplier / Entity.Mass);
if(float.IsNaN(Entity.CultVelocity.x))
ItemManager.Log("AetherDrive produced NaN velocity.");
MaximumRpm = Evaluate(_maximumRpm);
if(float.IsNaN(Entity.Velocity.x))
ItemManager.Log("FUCK FUCK FUCK FUCK");
MaximumRpm = Evaluate(_data.MaximumRpm);
var torqueProfile = float3(
_torqueProfile.Evaluate(Rpm.x / MaximumRpm),
_torqueProfile.Evaluate(Rpm.y / MaximumRpm),
_torqueProfile.Evaluate(Rpm.z / MaximumRpm));
var potentialTorque = Evaluate(_torque) * torqueProfile;
var potentialRpmDelta = potentialTorque / length(_rotorMass) * dt;
_data.TorqueProfile.Evaluate(Rpm.x / MaximumRpm),
_data.TorqueProfile.Evaluate(Rpm.y / MaximumRpm),
_data.TorqueProfile.Evaluate(Rpm.z / MaximumRpm));
var potentialTorque = Evaluate(_data.Torque) * torqueProfile;
var potentialRpmDelta = potentialTorque / length(_data.RotorMass) * dt;
var actualRpmDelta = min(MaximumRpm - Rpm, potentialRpmDelta);
var torqueRatio = actualRpmDelta / potentialRpmDelta;
var draw = torqueRatio * Evaluate(_energyDraw) / 3;
var draw = torqueRatio * Evaluate(_data.EnergyDraw) / 3;
Item.SetAudioParameter(SpecialAudioParameter.Intensity, max(max(abs(_axis.x), abs(_axis.y)), abs(_axis.z)));
Item.SetAudioParameter(_rpmAudioParameter, (Rpm.x + Rpm.y + Rpm.z) / 3 / MaximumRpm);
Item.SetAudioParameter(_torqueRatioAudioParameter, max(max(torqueRatio.x, torqueRatio.y), torqueRatio.z));
Item.SetAudioParameter(_data.RpmAudioParameter, (Rpm.x + Rpm.y + Rpm.z) / 3 / MaximumRpm);
Item.SetAudioParameter(_data.TorqueRatioAudioParameter, max(max(torqueRatio.x, torqueRatio.y), torqueRatio.z));
if (Entity.TryConsumeEnergy((draw.x + draw.y + draw.z)*dt))
{
Rpm += actualRpmDelta;
return true;
}
return false;
}
public void RestoreRuntimeState(
cfloat3 axis,
cfloat3 thrust,
cfloat3 rpm,
float maximumRpm,
cfloat2 thrustDirection)
{
Axis = axis;
Thrust = thrust;
Rpm = rpm;
MaximumRpm = maximumRpm;
ThrustDirection = thrustDirection;
}
}
}

View file

@ -1,8 +1,25 @@
using System;
using System.Collections;
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class AutoWeaponData : InstantWeaponData
{
public override Behavior CreateInstance(EquippedItem item)
{
return new AutoWeapon(this, item);
}
}
public class AutoWeapon : InstantWeapon
{
public AutoWeapon(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item) { }
public AutoWeapon(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item) { }
public AutoWeapon(InstantWeaponData data, EquippedItem item) : base(data, item) { }
public AutoWeapon(InstantWeaponData data, ConsumableItemEffect item) : base(data, item) { }
public override bool Execute(float dt)
{

View file

@ -1,4 +1,4 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
@ -6,16 +6,16 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using static CultMath.math;
using cfloat3 = CultMath.float3;
using cfloat4 = CultMath.float4;
using JsonKnownTypes;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using static Unity.Mathematics.noise;
public abstract class Behavior
{
private readonly Dictionary<string, PerformanceStat> _performanceStats;
public string Kind { get; }
public int Group { get; }
public BehaviorData Data { get; }
public EquippedItem Item { get; }
private ConsumableItemEffect Consumable { get; }
protected ItemManager ItemManager { get; }
@ -23,82 +23,43 @@ public abstract class Behavior
protected Entity Entity => Item?.Entity ?? Consumable.Entity;
public float Temperature => Item?.Temperature ?? Consumable.Entity.MaxTemp;
public cfloat3 Direction
public float3 Direction
{
get
{
if(Item != null)
{
var hardpoint = Entity.Hardpoints[Item.Position.x, Item.Position.y];
if (hardpoint != null && Entity.HardpointTransforms.TryGetValue(hardpoint, out var hardpointTransform))
if (hardpoint != null && Entity.HardpointTransforms.ContainsKey(hardpoint))
{
return normalize(hardpointTransform.direction);
return normalize(Entity.HardpointTransforms[hardpoint].direction);
}
else
{
var itemDirection = AetheriaMath.Rotate(Entity.CultDirection, Item.EquippableItem.Rotation);
return new cfloat3(itemDirection.x, 0, itemDirection.y);
var itemDirection = Entity.Direction.Rotate(Item.EquippableItem.Rotation);
return float3(itemDirection.x, 0, itemDirection.y);
}
}
var entityDirection = Entity.CultDirection;
return new cfloat3(entityDirection.x, 0, entityDirection.y);
return float3(Entity.Direction.x, 0, Entity.Direction.y);
}
}
protected Behavior(RuntimeBehaviorDefinition definition, EquippedItem item)
protected Behavior(BehaviorData data, EquippedItem item)
{
_performanceStats = new Dictionary<string, PerformanceStat>(StringComparer.Ordinal);
Kind = definition?.Kind ?? "";
Group = definition?.Group ?? 0;
Data = data;
Item = item;
ItemManager = Item.ItemManager;
}
protected Behavior(RuntimeBehaviorDefinition definition, ConsumableItemEffect consumable)
protected Behavior(BehaviorData data, ConsumableItemEffect consumable)
{
_performanceStats = new Dictionary<string, PerformanceStat>(StringComparer.Ordinal);
Kind = definition?.Kind ?? "";
Group = definition?.Group ?? 0;
Data = data;
Consumable = consumable;
ItemManager = consumable.Entity.ItemManager;
}
public float Evaluate(PerformanceStat stat) => Item?.Evaluate(stat) ?? Consumable.Evaluate(stat);
public float Evaluate(PerformanceStat stat, StatConditionMask condition, float value) =>
Item?.Evaluate(stat, condition, value) ?? Consumable.Evaluate(stat, condition, value);
public float Evaluate(
PerformanceStat stat,
StatConditionMask firstCondition,
float firstValue,
StatConditionMask secondCondition,
float secondValue) =>
Item?.Evaluate(stat, firstCondition, firstValue, secondCondition, secondValue) ??
Consumable.Evaluate(stat, firstCondition, firstValue, secondCondition, secondValue);
public bool TryGetPerformanceStat(string statName, out PerformanceStat stat)
{
if (!string.IsNullOrWhiteSpace(statName) &&
_performanceStats.TryGetValue(statName, out stat))
{
return true;
}
stat = null;
return false;
}
protected void RegisterPerformanceStat(string statName, PerformanceStat stat)
{
if (!string.IsNullOrWhiteSpace(statName) && stat != null)
{
_performanceStats[statName] = stat;
Item?.RegisterPerformanceStat(Kind, statName, stat);
}
}
protected void AddHeat(float heat) => Item?.AddHeat(heat); // TODO: Heat for Consumables
protected void CauseDamage(float damage)
@ -122,7 +83,7 @@ public abstract class Behavior
CauseDamage(Item.Wear * multiplier);
}
}
public virtual bool Execute(float dt)
{
return true;
@ -170,146 +131,74 @@ public interface IOrderedBehavior
int Order { get; }
}
public interface IPersistentBehavior//<T> where T : IBehavior
{
PersistentBehaviorData Store();
void Restore(PersistentBehaviorData data);
}
public interface IPopulationAssignment
{
int AssignedPopulation { get; set; }
}
public sealed class RuntimeBehaviorDefinition
[MessagePackObject,
JsonObject(MemberSerialization.OptIn),
JsonConverter(typeof(JsonKnownTypesConverter<PersistentBehaviorData>))]
public abstract class PersistentBehaviorData
{
private readonly IReadOnlyDictionary<int, AetheriaRuntimeBehaviorValue> _fields;
public string Kind { get; }
public int Group { get; }
public RuntimeBehaviorDefinition(AetheriaRuntimeBehaviorPayload payload)
{
Kind = payload?.Kind ?? "";
Group = payload?.Group ?? 0;
var fields = new Dictionary<int, AetheriaRuntimeBehaviorValue>();
if (payload != null)
{
foreach (var field in payload.Fields)
{
if (!fields.ContainsKey(field.Key))
{
fields.Add(field.Key, field.Value);
}
}
}
_fields = fields;
}
public bool Bool(int key, bool fallback = false)
{
return _fields.TryGetValue(key, out var value) ? value.BoolValue : fallback;
}
public float Float(int key, float fallback = 0)
{
return _fields.TryGetValue(key, out var value) ? (float)value.NumberValue : fallback;
}
public int Int(int key, int fallback = 0)
{
return _fields.TryGetValue(key, out var value) ? checked((int)value.NumberValue) : fallback;
}
public uint UInt(int key, uint fallback = 0)
{
return _fields.TryGetValue(key, out var value) ? checked((uint)value.NumberValue) : fallback;
}
public cfloat3 Float3(int key, cfloat3 fallback = default)
{
return _fields.TryGetValue(key, out var value) ? ToFloat3(value) : fallback;
}
public string String(int key, string fallback = "")
{
return _fields.TryGetValue(key, out var value) ? value.StringValue ?? "" : fallback;
}
public string ItemKey(int key, string fallback = "")
{
return _fields.TryGetValue(key, out var value) &&
!string.IsNullOrWhiteSpace(value.ItemKeyValue)
? value.ItemKeyValue
: fallback;
}
public PerformanceStat PerformanceStat(int key, PerformanceStat fallback)
{
return _fields.TryGetValue(key, out var value)
? AetheriaRuntimeBehaviorValueReader.ReadPerformanceStat(value)
: fallback;
}
public BezierCurve BezierCurve(int key, BezierCurve fallback)
{
if (!_fields.TryGetValue(key, out var value))
{
return fallback;
}
return global::BezierCurve.FromKeys(value.Children.Count > 0
? value.Children[0].Children.Select(ToBezierKey)
: Enumerable.Empty<(float, float, float, float)>());
}
public cfloat4[] Float4Array(int key, cfloat4[] fallback)
{
return _fields.TryGetValue(key, out var value)
? value.Children.Select(ToFloat4).ToArray()
: fallback;
}
public StatReference StatReference(int key, StatReference fallback)
{
if (!_fields.TryGetValue(key, out var value))
{
return fallback;
}
return AetheriaRuntimeBehaviorValueReader.ReadStatReference(value);
}
public T Enum<T>(int key, T fallback) where T : struct
{
return _fields.TryGetValue(key, out var value)
? AetheriaRuntimeBehaviorValueReader.ReadEnum(value, fallback)
: fallback;
}
private static cfloat4 ToFloat4(AetheriaRuntimeBehaviorValue value)
{
return new cfloat4(ChildFloat(value, 0), ChildFloat(value, 1), ChildFloat(value, 2), ChildFloat(value, 3));
}
private static (float, float, float, float) ToBezierKey(AetheriaRuntimeBehaviorValue value)
{
return (ChildFloat(value, 0), ChildFloat(value, 1), ChildFloat(value, 2), ChildFloat(value, 3));
}
private static cfloat3 ToFloat3(AetheriaRuntimeBehaviorValue value)
{
return new cfloat3(ChildFloat(value, 0), ChildFloat(value, 1), ChildFloat(value, 2));
}
private static float ChildFloat(AetheriaRuntimeBehaviorValue value, int index)
{
return value.Children.Count > index ? (float)value.Children[index].NumberValue : 0;
}
private static string ChildString(AetheriaRuntimeBehaviorValue value, int index)
{
return value.Children.Count > index ? value.Children[index].StringValue ?? "" : "";
}
private static AetheriaRuntimeBehaviorValue ChildValue(AetheriaRuntimeBehaviorValue value, int index)
{
return value != null && value.Children.Count > index ? value.Children[index] : null;
}
}
[Inspectable,
Union(0, typeof(GuidedWeaponData)),
Union(1, typeof(LauncherData)),
Union(2, typeof(ReactorData)),
Union(3, typeof(RadiatorData)),
Union(4, typeof(StatModifierData)),
Union(5, typeof(SensorData)),
Union(6, typeof(ReflectorData)),
Union(7, typeof(ShieldData)),
Union(8, typeof(ThrusterData)),
Union(9, typeof(WearData)),
Union(10, typeof(VelocityConversionData)),
Union(11, typeof(VelocityLimitData)),
Union(12, typeof(AetherDriveData)),
// Union(14, typeof(TowingControllerData)),
Union(15, typeof(CooldownData)),
Union(16, typeof(HeatData)),
// Union(17, typeof(HitscanData)),
Union(18, typeof(ItemUsageData)),
//Union(19, typeof(RadianceData)),
Union(20, typeof(SwitchData)),
Union(21, typeof(TriggerData)),
Union(22, typeof(VisibilityData)),
Union(23, typeof(ThermotoggleData)),
Union(24, typeof(EnergyDrawData)),
// Union(25, typeof(MiningControllerData)),
Union(26, typeof(MiningToolData)),
// Union(27, typeof(SurveyControllerData)),
Union(28, typeof(ResourceScannerData)),
// Union(29, typeof(WanderControllerData)),
// Union(30, typeof(HaulingControllerData)),
Union(31, typeof(CapacitorData)),
Union(32, typeof(CockpitData)),
Union(33, typeof(HeatStorageData)),
Union(34, typeof(TurretControllerData)),
Union(35, typeof(InstantWeaponData)),
Union(36, typeof(ConstantWeaponData)),
Union(37, typeof(ChargedWeaponData)),
Union(38, typeof(AutoWeaponData)),
JsonConverter(typeof(JsonKnownTypesConverter<BehaviorData>)), JsonObject(MemberSerialization.OptIn)]
public abstract class BehaviorData
{
[Inspectable, JsonProperty("group"), Key(0)]
public int Group;
public abstract Behavior CreateInstance(EquippedItem item);
public abstract Behavior CreateInstance(ConsumableItemEffect consumable);
public override string ToString()
{
return base.ToString().FormatTypeName();
}
}

View file

@ -2,12 +2,35 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using static CultMath.math;
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class CapacitorData : BehaviorData
{
[Inspectable, JsonProperty("capacity"), Key(1), RuntimeInspectable]
public PerformanceStat Capacity = new PerformanceStat();
[Inspectable, JsonProperty("efficiency"), Key(2), RuntimeInspectable]
public PerformanceStat Efficiency = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new Capacitor(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Capacitor(this, item);
}
}
public class Capacitor : Behavior
{
private readonly PerformanceStat _capacity;
private readonly PerformanceStat _efficiency;
private CapacitorData _data;
public float Charge { get; private set; }
public float Capacity { get; private set; }
@ -19,33 +42,20 @@ public class Capacitor : Behavior
AddHeat(abs(charge) * (1-Efficiency));
}
public Capacitor(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Capacitor(CapacitorData data, EquippedItem item) : base(data, item)
{
_capacity = definition.PerformanceStat(1, new PerformanceStat());
_efficiency = definition.PerformanceStat(2, new PerformanceStat());
RegisterPerformanceStat(nameof(Capacity), _capacity);
RegisterPerformanceStat(nameof(Efficiency), _efficiency);
_data = data;
}
public Capacitor(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Capacitor(CapacitorData data, ConsumableItemEffect item) : base(data, item)
{
_capacity = definition.PerformanceStat(1, new PerformanceStat());
_efficiency = definition.PerformanceStat(2, new PerformanceStat());
RegisterPerformanceStat(nameof(Capacity), _capacity);
RegisterPerformanceStat(nameof(Efficiency), _efficiency);
_data = data;
}
public override bool Execute(float dt)
{
Capacity = Evaluate(_capacity);
Efficiency = Evaluate(_efficiency);
Capacity = Evaluate(_data.Capacity);
Efficiency = Evaluate(_data.Efficiency);
return true;
}
public void RestoreRuntimeState(float charge, float capacity, float efficiency)
{
Charge = clamp(charge, 0, capacity);
Capacity = capacity;
Efficiency = efficiency;
}
}
}

View file

@ -1,37 +1,79 @@
using System;
using System.Collections;
using System.Collections.Generic;
using static CultMath.math;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class ChargedWeaponData : InstantWeaponData
{
[Inspectable, JsonProperty("chargeTime"), Key(21), RuntimeInspectable]
public PerformanceStat ChargeTime = new PerformanceStat();
[Inspectable, JsonProperty("chargeEnergy"), Key(22), RuntimeInspectable]
public PerformanceStat ChargeEnergy = new PerformanceStat();
[Inspectable, JsonProperty("chargeHeat"), Key(23), RuntimeInspectable]
public PerformanceStat ChargeHeat = new PerformanceStat();
[Inspectable, JsonProperty("canFireEarly"), Key(24)]
public bool CanFireEarly;
[Inspectable, JsonProperty("failureCharge"), Key(25)]
public float FailureCharge;
[Inspectable, JsonProperty("failureDamage"), Key(26)]
public float FailureDamage = 1;
[Inspectable, JsonProperty("chargeDamage"), Key(27)]
public float ChargeFiringDamageMultiplier = 1;
[Inspectable, JsonProperty("chargeSpread"), Key(28)]
public float ChargeFiringSpreadMultiplier = 1;
[Inspectable, JsonProperty("chargeBurstCount"), Key(29)]
public float ChargeFiringBurstCountMultiplier = 1;
[Inspectable, JsonProperty("chargeVisibility"), Key(30)]
public float ChargeFiringVisibilityMultiplier = 1;
[Inspectable, JsonProperty("chargeVelocity"), Key(31)]
public float ChargeFiringVelocityMultiplier = 1;
[Inspectable, JsonProperty("chargeHeatMul"), Key(32)]
public float ChargeFiringHeatMultiplier = 1;
public override Behavior CreateInstance(EquippedItem item)
{
return new ChargedWeapon(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new ChargedWeapon(this, item);
}
}
public class ChargedWeapon : InstantWeapon
{
private readonly PerformanceStat _chargeTime;
private readonly PerformanceStat _chargeEnergy;
private readonly PerformanceStat _chargeHeat;
private readonly bool _canFireEarly;
private readonly float _failureCharge;
private readonly float _failureDamage;
private readonly float _chargeFiringDamageMultiplier;
private readonly float _chargeFiringSpreadMultiplier;
private readonly float _chargeFiringBurstCountMultiplier;
private readonly float _chargeFiringVisibilityMultiplier;
private readonly float _chargeFiringVelocityMultiplier;
private readonly float _chargeFiringHeatMultiplier;
private ChargedWeaponData _data;
private bool _charging;
private bool _charged;
private float _charge;
private float _progress;
public float ChargeTime { get; protected set; }
public float ChargeEnergy { get; protected set; }
public float ChargeHeat { get; protected set; }
public override float DamagePerSecond => Damage * _chargeFiringDamageMultiplier / (Cooldown + ChargeTime);
public override float DamagePerSecond => Damage * _data.ChargeFiringDamageMultiplier / (Cooldown + ChargeTime);
public override float RangeDamagePerSecond(float range)
{
return EvaluateRangeDamage(range, StatConditionMask.Charge, saturate(_charge)) *
lerp(1, _chargeFiringDamageMultiplier, saturate(_charge)) *
_chargeFiringDamageMultiplier /
return Damage *
_data.ChargeFiringDamageMultiplier *
_data.DamageCurve.Evaluate(saturate(unlerp(MinRange, Range, range))) /
(Cooldown + ChargeTime);
}
@ -55,63 +97,29 @@ public class ChargedWeapon : InstantWeapon
{
get => _charge;
}
public bool Charging => _charging;
public bool Charged => _charged;
public ChargedWeapon(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public ChargedWeapon(ChargedWeaponData data, EquippedItem item) : base(data, item)
{
_chargeTime = definition.PerformanceStat(21, new PerformanceStat());
_chargeEnergy = definition.PerformanceStat(22, new PerformanceStat());
_chargeHeat = definition.PerformanceStat(23, new PerformanceStat());
_canFireEarly = definition.Bool(24);
_failureCharge = definition.Float(25);
_failureDamage = definition.Float(26, 1);
_chargeFiringDamageMultiplier = definition.Float(27, 1);
_chargeFiringSpreadMultiplier = definition.Float(28, 1);
_chargeFiringBurstCountMultiplier = definition.Float(29, 1);
_chargeFiringVisibilityMultiplier = definition.Float(30, 1);
_chargeFiringVelocityMultiplier = definition.Float(31, 1);
_chargeFiringHeatMultiplier = definition.Float(32, 1);
RegisterChargedWeaponStats();
_data = data;
}
public ChargedWeapon(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public ChargedWeapon(ChargedWeaponData data, ConsumableItemEffect item) : base(data, item)
{
_chargeTime = definition.PerformanceStat(21, new PerformanceStat());
_chargeEnergy = definition.PerformanceStat(22, new PerformanceStat());
_chargeHeat = definition.PerformanceStat(23, new PerformanceStat());
_canFireEarly = definition.Bool(24);
_failureCharge = definition.Float(25);
_failureDamage = definition.Float(26, 1);
_chargeFiringDamageMultiplier = definition.Float(27, 1);
_chargeFiringSpreadMultiplier = definition.Float(28, 1);
_chargeFiringBurstCountMultiplier = definition.Float(29, 1);
_chargeFiringVisibilityMultiplier = definition.Float(30, 1);
_chargeFiringVelocityMultiplier = definition.Float(31, 1);
_chargeFiringHeatMultiplier = definition.Float(32, 1);
RegisterChargedWeaponStats();
}
private void RegisterChargedWeaponStats()
{
RegisterPerformanceStat(nameof(ChargeTime), _chargeTime);
RegisterPerformanceStat(nameof(ChargeEnergy), _chargeEnergy);
RegisterPerformanceStat(nameof(ChargeHeat), _chargeHeat);
_data = data;
}
protected override void UpdateStats()
{
base.UpdateStats();
ChargeTime = Evaluate(_chargeTime);
ChargeEnergy = Evaluate(_chargeEnergy);
ChargeHeat = Evaluate(_chargeHeat);
Damage = EvaluateDamage(StatConditionMask.Charge, saturate(_charge)) *
lerp(1, _chargeFiringDamageMultiplier, saturate(_charge));
Heat *= lerp(1, _chargeFiringHeatMultiplier, saturate(_charge));
Spread *= lerp(1, _chargeFiringSpreadMultiplier, saturate(_charge));
BurstCount *= lerp(1, _chargeFiringBurstCountMultiplier, saturate(_charge));
Visibility *= lerp(1, _chargeFiringVisibilityMultiplier, saturate(_charge));
Velocity *= lerp(1, _chargeFiringVelocityMultiplier, saturate(_charge));
ChargeTime = Evaluate(_data.ChargeTime);
ChargeEnergy = Evaluate(_data.ChargeEnergy);
ChargeHeat = Evaluate(_data.ChargeHeat);
Damage *= lerp(1, _data.ChargeFiringDamageMultiplier, saturate(_charge));
Heat *= lerp(1, _data.ChargeFiringHeatMultiplier, saturate(_charge));
Spread *= lerp(1, _data.ChargeFiringSpreadMultiplier, saturate(_charge));
BurstCount *= lerp(1, _data.ChargeFiringBurstCountMultiplier, saturate(_charge));
Visibility *= lerp(1, _data.ChargeFiringVisibilityMultiplier, saturate(_charge));
Velocity *= lerp(1, _data.ChargeFiringVelocityMultiplier, saturate(_charge));
}
public override bool Execute(float dt)
@ -129,7 +137,7 @@ public class ChargedWeapon : InstantWeapon
OnCharged?.Invoke();
}
}
if (_failureCharge > 1 && _charge > _failureCharge)
if (_data.FailureCharge > 1 && _charge > _data.FailureCharge)
{
_charging = false;
_cooldown = 1;
@ -137,7 +145,7 @@ public class ChargedWeapon : InstantWeapon
_charge = 0;
OnFailed?.Invoke();
Item.FireAudioEvent(ChargedWeaponAudioEvent.Fail);
CauseDamage(_failureDamage);
CauseDamage(_data.FailureDamage);
}
}
return base.Execute(dt);
@ -158,7 +166,7 @@ public class ChargedWeapon : InstantWeapon
{
if (_charging)
{
if (_canFireEarly || _charge > 1)
if (_data.CanFireEarly || _charge > 1)
{
Trigger();
_charge = 0;
@ -168,29 +176,5 @@ public class ChargedWeapon : InstantWeapon
_charging = false;
}
}
public void RestoreRuntimeState(
bool firing,
int ammo,
int burstRemaining,
float burstTimer,
float burstInterval,
float cooldownProgress,
bool coolingDown,
bool charging,
bool charged,
float charge)
{
base.RestoreRuntimeState(
firing,
ammo,
burstRemaining,
burstTimer,
burstInterval,
cooldownProgress,
coolingDown);
_charging = charging;
_charged = charged;
_charge = charge;
}
}

View file

@ -2,13 +2,36 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
public class Cockpit : Behavior
{
public Cockpit(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
{
}
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public Cockpit(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class CockpitData : BehaviorData
{
public override Behavior CreateInstance(EquippedItem item)
{
return new Cockpit(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Cockpit(this, item);
}
}
public class Cockpit : Behavior
{
private CockpitData _data;
public Cockpit(CockpitData data, EquippedItem item) : base(data, item)
{
_data = data;
}
public Cockpit(CockpitData data, ConsumableItemEffect item) : base(data, item)
{
_data = data;
}
}

View file

@ -3,40 +3,57 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using static CultMath.math;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class ConstantWeaponData : WeaponData
{
[InspectablePrefab, JsonProperty("ammoInterval"), Key(17)]
public float AmmoInterval = 1;
public override Behavior CreateInstance(EquippedItem item)
{
return new ConstantWeapon(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new ConstantWeapon(this, item);
}
}
public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior
{
private readonly float _ammoIntervalDuration;
private ConstantWeaponData _data;
private int _ammo = 1;
private float _ammoInterval;
private float _reload;
private bool _reloading;
public override int Ammo
{
get => _ammo;
}
public float AmmoIntervalProgress => _ammoInterval;
public float ReloadProgress => _reload;
public bool Reloading => _reloading;
public float Progress
{
get { return saturate(_reload); }
}
public override float DamagePerSecond => Damage;
public override float RangeDamagePerSecond(float range)
{
return EvaluateRangeDamage(range);
return Damage * _data.DamageCurve.Evaluate(saturate(unlerp(MinRange, Range, range)));
}
public event Action OnReloadBegin;
public event Action OnReloadComplete;
public event Action OnStartFiring;
public event Action OnStopFiring;
public void ResetEvents()
{
OnReloadBegin = null;
@ -45,14 +62,14 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior
OnStopFiring = null;
}
public ConstantWeapon(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public ConstantWeapon(ConstantWeaponData data, EquippedItem item) : base(data, item)
{
_ammoIntervalDuration = definition.Float(17, 1);
_data = data;
}
public ConstantWeapon(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public ConstantWeapon(ConstantWeaponData data, ConsumableItemEffect item) : base(data, item)
{
_ammoIntervalDuration = definition.Float(17, 1);
_data = data;
}
public override bool Execute(float dt)
@ -60,17 +77,17 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior
base.Execute(dt);
if (_firing)
{
if (!Entity.TryConsumeEnergy(Energy * dt))
if (!Entity.TryConsumeEnergy(Evaluate(_data.Energy) * dt))
{
_firing = false;
OnStopFiring?.Invoke();
return false;
}
if (!string.IsNullOrWhiteSpace(AmmoItemKey))
if (_data.AmmoType != Guid.Empty)
{
if (_reloading)
{
_reload -= dt / ReloadTime;
_reload -= dt / _data.ReloadTime;
if (_reload < 0)
{
_reloading = false;
@ -78,22 +95,22 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior
}
return false;
}
_ammoInterval -= dt / _ammoIntervalDuration;
_ammoInterval -= dt / _data.AmmoInterval;
if (_ammoInterval < 0)
{
_ammoInterval = 1;
if (MagazineSize > 1 && _ammo > 0) _ammo--;
if (_data.MagazineSize > 1 && _ammo > 0) _ammo--;
else
{
var cargo = Entity.FindItemInCargo(AmmoItemKey);
var cargo = Entity.FindItemInCargo(_data.AmmoType);
if (cargo != null)
{
var item = cargo.GetFirstItem(AmmoItemKey);
var item = cargo.ItemsOfType[_data.AmmoType][0];
if (item is SimpleCommodity simpleCommodity)
cargo.Remove(simpleCommodity, 1);
if(MagazineSize > 1)
if(_data.MagazineSize > 1)
{
_reloading = true;
_reload = 1;
@ -109,8 +126,8 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior
}
CauseWearDamage(dt);
AddHeat(Heat * dt);
Entity.VisibilitySources[this] = Visibility;
AddHeat(Evaluate(_data.Heat) * dt);
Entity.VisibilitySources[this] = Evaluate(_data.Visibility);
}
return true;
}
@ -119,7 +136,6 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior
{
if(!_firing && !_reloading)
{
UpdateStats();
_firing = true;
OnStartFiring?.Invoke();
}
@ -133,18 +149,4 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior
OnStopFiring?.Invoke();
}
}
public void RestoreRuntimeState(
bool firing,
int ammo,
float ammoIntervalProgress,
float reloadProgress,
bool reloading)
{
base.RestoreRuntimeState(firing);
_ammo = ammo;
_ammoInterval = ammoIntervalProgress;
_reload = reloadProgress;
_reloading = reloading;
}
}
}

View file

@ -1,27 +1,47 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using static CultMath.math;
using System;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), Order(-10), RuntimeInspectable]
public class CooldownData : BehaviorData
{
[Inspectable, JsonProperty("cooldown"), Key(1), RuntimeInspectable]
public PerformanceStat Cooldown = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new Cooldown(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Cooldown(this, item);
}
}
public class Cooldown : Behavior, IAlwaysUpdatedBehavior, IProgressBehavior
{
private readonly PerformanceStat _cooldownDuration;
private CooldownData _data;
private float _cooldown; // Normalized
public float Progress => saturate(_cooldown);
public Cooldown(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Cooldown(CooldownData data, EquippedItem item) : base(data, item)
{
_cooldownDuration = definition.PerformanceStat(1, new PerformanceStat());
RegisterPerformanceStat(nameof(Cooldown), _cooldownDuration);
_data = data;
}
public Cooldown(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Cooldown(CooldownData data, ConsumableItemEffect item) : base(data, item)
{
_cooldownDuration = definition.PerformanceStat(1, new PerformanceStat());
RegisterPerformanceStat(nameof(Cooldown), _cooldownDuration);
_data = data;
}
public override bool Execute(float dt)
@ -37,6 +57,6 @@ public class Cooldown : Behavior, IAlwaysUpdatedBehavior, IProgressBehavior
public void Update(float delta)
{
_cooldown -= delta / Evaluate(_cooldownDuration);
_cooldown -= delta / Evaluate(_data.Cooldown);
}
}
}

View file

@ -1,30 +1,48 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), Order(-20), RuntimeInspectable]
public class EnergyDrawData : BehaviorData
{
[Inspectable, JsonProperty("draw"), Key(1), RuntimeInspectable]
public PerformanceStat EnergyDraw = new PerformanceStat();
[Inspectable, JsonProperty("perSecond"), Key(2)]
public bool PerSecond;
public override Behavior CreateInstance(EquippedItem item)
{
return new EnergyDraw(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new EnergyDraw(this, item);
}
}
public class EnergyDraw : Behavior
{
private readonly PerformanceStat _energyDraw;
private readonly bool _perSecond;
private EnergyDrawData _data;
public EnergyDraw(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public EnergyDraw(EnergyDrawData data, EquippedItem item) : base(data, item)
{
_energyDraw = definition.PerformanceStat(1, new PerformanceStat());
_perSecond = definition.Bool(2);
RegisterPerformanceStat(nameof(EnergyDraw), _energyDraw);
_data = data;
}
public EnergyDraw(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public EnergyDraw(EnergyDrawData data, ConsumableItemEffect item) : base(data, item)
{
_energyDraw = definition.PerformanceStat(1, new PerformanceStat());
_perSecond = definition.Bool(2);
RegisterPerformanceStat(nameof(EnergyDraw), _energyDraw);
_data = data;
}
public override bool Execute(float dt)
{
return Entity.TryConsumeEnergy(Evaluate(_energyDraw) * (_perSecond ? dt : 1));
return Entity.TryConsumeEnergy(Evaluate(_data.EnergyDraw) * (_data.PerSecond ? dt : 1));
}
}
}

View file

@ -1,32 +1,49 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), Order(10)]
public class HeatData : BehaviorData
{
[Inspectable, JsonProperty("heat"), Key(1), RuntimeInspectable]
public PerformanceStat Heat = new PerformanceStat();
[Inspectable, JsonProperty("perSecond"), Key(2)]
public bool PerSecond;
public override Behavior CreateInstance(EquippedItem item)
{
return new Heat(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Heat(this, item);
}
}
public class Heat : Behavior
{
private readonly PerformanceStat _heat;
private readonly bool _perSecond;
private HeatData _data;
public Heat(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Heat(HeatData data, EquippedItem item) : base(data, item)
{
_heat = definition.PerformanceStat(1, new PerformanceStat());
_perSecond = definition.Bool(2);
RegisterPerformanceStat(nameof(Heat), _heat);
_data = data;
}
public Heat(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Heat(HeatData data, ConsumableItemEffect item) : base(data, item)
{
_heat = definition.PerformanceStat(1, new PerformanceStat());
_perSecond = definition.Bool(2);
RegisterPerformanceStat(nameof(Heat), _heat);
_data = data;
}
public override bool Execute(float dt)
{
AddHeat(Evaluate(_heat) * (_perSecond ? dt : 1));
AddHeat(Evaluate(_data.Heat) * (_data.PerSecond ? dt : 1));
return true;
}
}
}

View file

@ -2,13 +2,36 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
public class HeatStorage : Behavior
{
public HeatStorage(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
{
}
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public HeatStorage(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class HeatStorageData : BehaviorData
{
public override Behavior CreateInstance(EquippedItem item)
{
return new HeatStorage(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new HeatStorage(this, item);
}
}
public class HeatStorage : Behavior
{
private HeatStorageData _data;
public HeatStorage(HeatStorageData data, EquippedItem item) : base(data, item)
{
_data = data;
}
public HeatStorage(HeatStorageData data, ConsumableItemEffect item) : base(data, item)
{
_data = data;
}
}

View file

@ -1,14 +1,40 @@
using System;
using System.Collections;
using System.Collections.Generic;
using static CultMath.math;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class InstantWeaponData : WeaponData
{
[Inspectable, JsonProperty("count"), Key(17)]
public PerformanceStat Count = new PerformanceStat();
[Inspectable, JsonProperty("burstTime"), Key(18)]
public PerformanceStat BurstTime = new PerformanceStat();
[Inspectable, JsonProperty("cooldown"), Key(19), RuntimeInspectable]
public PerformanceStat Cooldown = new PerformanceStat();
[InspectablePrefab, JsonProperty("ammoInterval"), Key(20)]
public bool SingleAmmoBurst;
public override Behavior CreateInstance(EquippedItem item)
{
return new InstantWeapon(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new InstantWeapon(this, item);
}
}
public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
{
private readonly PerformanceStat _count;
private readonly PerformanceStat _burstTime;
private readonly PerformanceStat _cooldownDuration;
private readonly bool _singleAmmoBurst;
private InstantWeaponData _data;
protected int _burstRemaining;
private float _burstTimer;
@ -28,18 +54,13 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
public override float DamagePerSecond => Damage / Cooldown;
public override float RangeDamagePerSecond(float range)
{
return EvaluateRangeDamage(range) / Cooldown;
return Damage * _data.DamageCurve.Evaluate(saturate(unlerp(MinRange, Range, range))) / Cooldown;
}
public override int Ammo
{
get => _ammo;
}
public int BurstRemaining => _burstRemaining;
public float BurstTimer => _burstTimer;
public float BurstInterval => _burstInterval;
public float CooldownProgress => _cooldown;
public bool CoolingDown => _coolingDown;
public virtual float Progress => saturate(_cooldown);
public event Action OnReloadBegin;
@ -55,39 +76,24 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
OnFire = null;
}
public InstantWeapon(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public InstantWeapon(InstantWeaponData data, EquippedItem item) : base(data, item)
{
_count = definition.PerformanceStat(17, new PerformanceStat());
_burstTime = definition.PerformanceStat(18, new PerformanceStat());
_cooldownDuration = definition.PerformanceStat(19, new PerformanceStat());
_singleAmmoBurst = definition.Bool(20);
_ammo = MagazineSize;
RegisterInstantWeaponStats();
_data = data;
_ammo = data.MagazineSize;
}
public InstantWeapon(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public InstantWeapon(InstantWeaponData data, ConsumableItemEffect item) : base(data, item)
{
_count = definition.PerformanceStat(17, new PerformanceStat());
_burstTime = definition.PerformanceStat(18, new PerformanceStat());
_cooldownDuration = definition.PerformanceStat(19, new PerformanceStat());
_singleAmmoBurst = definition.Bool(20);
_ammo = MagazineSize;
RegisterInstantWeaponStats();
}
private void RegisterInstantWeaponStats()
{
RegisterPerformanceStat("Count", _count);
RegisterPerformanceStat(nameof(BurstTime), _burstTime);
RegisterPerformanceStat(nameof(Cooldown), _cooldownDuration);
_data = data;
_ammo = data.MagazineSize;
}
protected void Trigger()
{
// If 1 ammo is consumed per burst, perform ammo and energy consumption here
// UseAmmo returns false when triggering reload; cancel firing if that is the case
if(_singleAmmoBurst && (!Entity.TryConsumeEnergy(Energy) || !UseAmmo())) return;
if(_data.SingleAmmoBurst && (!Entity.TryConsumeEnergy(Energy) || !UseAmmo())) return;
_burstRemaining = (int) BurstCount;
_burstInterval = BurstTime / _burstRemaining;
_burstTimer = 0;
@ -98,9 +104,9 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
protected override void UpdateStats()
{
base.UpdateStats();
BurstCount = Evaluate(_count);
BurstTime = Evaluate(_burstTime);
Cooldown = Evaluate(_cooldownDuration);
BurstCount = Evaluate(_data.Count);
BurstTime = Evaluate(_data.BurstTime);
Cooldown = Evaluate(_data.Cooldown);
Damage /= (int) BurstCount;
Heat /= (int) BurstCount;
@ -109,21 +115,21 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
private bool UseAmmo()
{
if (MagazineSize <= 1) return true;
if (_data.MagazineSize <= 1) return true;
if (_ammo > 0)
{
_ammo--;
return true;
}
var hasAmmo = true;
if (!string.IsNullOrWhiteSpace(AmmoItemKey))
if (_data.AmmoType != Guid.Empty)
{
var cargo = Entity.FindItemInCargo(AmmoItemKey);
var cargo = Entity.FindItemInCargo(_data.AmmoType);
if (cargo != null)
{
var item = cargo.GetFirstItem(AmmoItemKey);
var item = cargo.ItemsOfType[_data.AmmoType][0];
if (item is SimpleCommodity simpleCommodity)
cargo.Remove(simpleCommodity, 1);
}
@ -146,13 +152,13 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
base.Execute(dt);
if (_coolingDown)
{
_cooldown -= dt / (MagazineSize > 0 && _ammo == 0 ? ReloadTime : Cooldown);
_cooldown -= dt / (_data.MagazineSize > 0 && _ammo == 0 ? _data.ReloadTime : Cooldown);
if (_cooldown < 0)
{
_coolingDown = false;
if (MagazineSize > 0 && _ammo == 0)
if (_data.MagazineSize > 0 && _ammo == 0)
{
_ammo = MagazineSize;
_ammo = _data.MagazineSize;
OnReloadComplete?.Invoke();
}
else
@ -166,12 +172,12 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
{
// If multiple ammo is consumed per burst, perform ammo and energy consumption here
// UseAmmo returns false when triggering reload; cancel firing if that is the case
if (!_singleAmmoBurst && (!Entity.TryConsumeEnergy(Energy) || !UseAmmo()))
if (!_data.SingleAmmoBurst && (!Entity.TryConsumeEnergy(Energy) || !UseAmmo()))
{
_burstRemaining = 0;
return false;
}
_burstRemaining--;
_burstTimer -= _burstInterval;
OnFire?.Invoke();
@ -193,22 +199,4 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior
Trigger();
base.Activate();
}
public void RestoreRuntimeState(
bool firing,
int ammo,
int burstRemaining,
float burstTimer,
float burstInterval,
float cooldownProgress,
bool coolingDown)
{
base.RestoreRuntimeState(firing);
_ammo = ammo;
_burstRemaining = burstRemaining;
_burstTimer = burstTimer;
_burstInterval = burstInterval;
_cooldown = cooldownProgress;
_coolingDown = coolingDown;
}
}
}

View file

@ -1,33 +1,54 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), Order(-5), RuntimeInspectable]
public class ItemUsageData : BehaviorData
{
[InspectableDatabaseLink(typeof(SimpleCommodityData)), JsonProperty("item"), Key(1), RuntimeInspectable]
public Guid Item;
public override Behavior CreateInstance(EquippedItem item)
{
return new ItemUsage(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new ItemUsage(this, item);
}
}
public class ItemUsage : Behavior
{
private readonly string _itemKey;
private ItemUsageData _data;
public ItemUsage(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public ItemUsage(ItemUsageData data, EquippedItem item) : base(data, item)
{
_itemKey = definition.ItemKey(1);
_data = data;
}
public ItemUsage(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public ItemUsage(ItemUsageData data, ConsumableItemEffect item) : base(data, item)
{
_itemKey = definition.ItemKey(1);
_data = data;
}
public override bool Execute(float dt)
{
var cargo = Entity.FindItemInCargo(_itemKey);
var cargo = Entity.FindItemInCargo(_data.Item);
if (cargo == null) return false;
var item = cargo.GetFirstItem(_itemKey);
var item = cargo.ItemsOfType[_data.Item][0];
if (item is SimpleCommodity simpleCommodity)
cargo.Remove(simpleCommodity, 1);
if (item is CraftedItemInstance craftedItemInstance)
cargo.Remove(craftedItemInstance);
return true;
}
}
}

View file

@ -0,0 +1,61 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class LauncherData : LockWeaponData
{
[InspectableAnimationCurve, JsonProperty("guidance"), Key(26)]
public float4[] GuidanceCurve;
[InspectableAnimationCurve, JsonProperty("thrustCurve"), Key(27)]
public float4[] ThrustCurve;
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(28)]
public float4[] LiftCurve;
[Inspectable, JsonProperty("thrust"), Key(29)]
public PerformanceStat Thrust = new PerformanceStat();
[Inspectable, JsonProperty("frequency"), Key(30)]
public float DodgeFrequency;
[Inspectable, JsonProperty("missileSpeed"), Key(31), RuntimeInspectable]
public PerformanceStat MissileVelocity = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new LockWeapon(this, item);
}
}
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class GuidedWeaponData : InstantWeaponData
{
[InspectableAnimationCurve, JsonProperty("guidance"), Key(21)]
public float4[] GuidanceCurve;
[InspectableAnimationCurve, JsonProperty("thrustCurve"), Key(22)]
public float4[] ThrustCurve;
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(23)]
public float4[] LiftCurve;
[Inspectable, JsonProperty("thrust"), Key(24)]
public PerformanceStat Thrust = new PerformanceStat();
[Inspectable, JsonProperty("frequency"), Key(25)]
public float DodgeFrequency;
[Inspectable, JsonProperty("missileSpeed"), Key(26), RuntimeInspectable]
public PerformanceStat MissileVelocity = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new InstantWeapon(this, item);
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5fd0ce9fd7384ba5a40c2ba41ece74eb
timeCreated: 1584292825

View file

@ -1,13 +1,42 @@
using System;
using static CultMath.math;
using System.Collections;
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class LockWeaponData : InstantWeaponData
{
[Inspectable, JsonProperty("speed"), Key(21), RuntimeInspectable]
public PerformanceStat LockSpeed = new PerformanceStat();
[Inspectable, JsonProperty("sensorImpact"), Key(22)]
public PerformanceStat SensorImpact = new PerformanceStat();
[Inspectable, JsonProperty("threshold"), Key(23), RuntimeInspectable]
public PerformanceStat LockAngle = new PerformanceStat();
[Inspectable, JsonProperty("directionImpact"), Key(24)]
public PerformanceStat DirectionImpact = new PerformanceStat();
[Inspectable, JsonProperty("decay"), Key(25)]
public PerformanceStat Decay = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new LockWeapon(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new LockWeapon(this, item);
}
}
public class LockWeapon : InstantWeapon
{
private readonly PerformanceStat _lockSpeed;
private readonly PerformanceStat _sensorImpact;
private readonly PerformanceStat _lockAngle;
private readonly PerformanceStat _directionImpact;
private readonly PerformanceStat _decay;
private LockWeaponData _data;
private float _lock;
private bool _locking;
private Entity _target;
@ -30,37 +59,14 @@ public class LockWeapon : InstantWeapon
{
get => saturate(_lock);
}
public float LockProgress => saturate(_lock);
public Entity LockTarget => _target;
public LockWeapon(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public LockWeapon(LockWeaponData data, EquippedItem item) : base(data, item)
{
_lockSpeed = definition.PerformanceStat(21, new PerformanceStat());
_sensorImpact = definition.PerformanceStat(22, new PerformanceStat());
_lockAngle = definition.PerformanceStat(23, new PerformanceStat());
_directionImpact = definition.PerformanceStat(24, new PerformanceStat());
_decay = definition.PerformanceStat(25, new PerformanceStat());
RegisterLockWeaponStats();
_data = data;
}
public LockWeapon(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public LockWeapon(LockWeaponData data, ConsumableItemEffect item) : base(data, item)
{
_lockSpeed = definition.PerformanceStat(21, new PerformanceStat());
_sensorImpact = definition.PerformanceStat(22, new PerformanceStat());
_lockAngle = definition.PerformanceStat(23, new PerformanceStat());
_directionImpact = definition.PerformanceStat(24, new PerformanceStat());
_decay = definition.PerformanceStat(25, new PerformanceStat());
RegisterLockWeaponStats();
}
private void RegisterLockWeaponStats()
{
RegisterPerformanceStat(nameof(LockSpeed), _lockSpeed);
RegisterPerformanceStat(nameof(SensorImpact), _sensorImpact);
RegisterPerformanceStat(nameof(LockAngle), _lockAngle);
RegisterPerformanceStat(nameof(DirectionImpact), _directionImpact);
RegisterPerformanceStat(nameof(Decay), _decay);
_data = data;
}
public override bool Execute(float dt)
@ -73,17 +79,16 @@ public class LockWeapon : InstantWeapon
if (Entity.Target.Value != null && Entity.Target.Value.IsHostileTo(Entity))
{
LockSpeed = Evaluate(_lockSpeed);
SensorImpact = Evaluate(_sensorImpact);
LockAngle = Evaluate(_lockAngle);
DirectionImpact = Evaluate(_directionImpact);
Decay = Evaluate(_decay);
LockSpeed = Evaluate(_data.LockSpeed);
SensorImpact = Evaluate(_data.SensorImpact);
LockAngle = Evaluate(_data.LockAngle);
DirectionImpact = Evaluate(_data.DirectionImpact);
Decay = Evaluate(_data.Decay);
var targetDirection = Entity.Target.Value.CultPosition - Entity.CultPosition;
var angleDegrees = AetheriaMath.AngleDegrees(targetDirection, Entity.CultLookDirection);
if (angleDegrees < LockAngle)
var degrees = acos(dot(normalize(Entity.Target.Value.Position - Entity.Position), normalize(Entity.LookDirection))) * 57.2958f;
if (degrees < LockAngle)
{
var lerp = 1 - unlerp(0, 90, angleDegrees);
var lerp = 1 - unlerp(0, 90, degrees);
_lock = saturate(_lock + pow(lerp, DirectionImpact) * dt * LockSpeed * pow(Entity.EntityInfoGathered[Entity.Target.Value], SensorImpact));
}
else _lock = saturate(_lock - dt * Decay);
@ -91,28 +96,5 @@ public class LockWeapon : InstantWeapon
return base.Execute(dt);
}
public void RestoreRuntimeState(
bool firing,
int ammo,
int burstRemaining,
float burstTimer,
float burstInterval,
float cooldownProgress,
bool coolingDown,
float lockProgress,
Entity lockTarget)
{
base.RestoreRuntimeState(
firing,
ammo,
burstRemaining,
burstTimer,
burstInterval,
cooldownProgress,
coolingDown);
_lock = lockProgress;
_target = lockTarget;
_locking = lockTarget != null;
}
}

View file

@ -1,70 +1,75 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using static CultMath.math;
using System;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), Order(10)]
public class MiningToolData : BehaviorData
{
[Inspectable, JsonProperty("dps"), Key(1)]
public PerformanceStat DamagePerSecond = new PerformanceStat();
[Inspectable, JsonProperty("efficiency"), Key(2)]
public PerformanceStat Efficiency = new PerformanceStat();
[Inspectable, JsonProperty("penetration"), Key(3)]
public PerformanceStat Penetration = new PerformanceStat();
[Inspectable, JsonProperty("range"), Key(4)]
public PerformanceStat Range = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new MiningTool(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new MiningTool(this, item);
}
}
public class MiningTool : Behavior
{
public string AsteroidBeltBodyKey = "";
public Guid AsteroidBelt;
public int Asteroid;
private readonly PerformanceStat _damagePerSecond;
private readonly PerformanceStat _efficiency;
private readonly PerformanceStat _penetration;
private readonly PerformanceStat _range;
private MiningToolData _data;
public float Range { get; private set; }
public MiningTool(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public MiningTool(MiningToolData data, EquippedItem item) : base(data, item)
{
_damagePerSecond = definition.PerformanceStat(1, new PerformanceStat());
_efficiency = definition.PerformanceStat(2, new PerformanceStat());
_penetration = definition.PerformanceStat(3, new PerformanceStat());
_range = definition.PerformanceStat(4, new PerformanceStat());
RegisterPerformanceStat("DamagePerSecond", _damagePerSecond);
RegisterPerformanceStat("Efficiency", _efficiency);
RegisterPerformanceStat("Penetration", _penetration);
RegisterPerformanceStat(nameof(Range), _range);
_data = data;
}
public MiningTool(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public MiningTool(MiningToolData data, ConsumableItemEffect item) : base(data, item)
{
_damagePerSecond = definition.PerformanceStat(1, new PerformanceStat());
_efficiency = definition.PerformanceStat(2, new PerformanceStat());
_penetration = definition.PerformanceStat(3, new PerformanceStat());
_range = definition.PerformanceStat(4, new PerformanceStat());
RegisterPerformanceStat("DamagePerSecond", _damagePerSecond);
RegisterPerformanceStat("Efficiency", _efficiency);
RegisterPerformanceStat("Penetration", _penetration);
RegisterPerformanceStat(nameof(Range), _range);
_data = data;
}
public override bool Execute(float dt)
{
Range = Evaluate(_range);
if (!string.IsNullOrWhiteSpace(AsteroidBeltBodyKey) &&
Entity.Zone.TryGetAsteroidBelt(AsteroidBeltBodyKey, out var belt) &&
Entity.Zone.AsteroidExists(AsteroidBeltBodyKey, Asteroid) &&
Entity.Zone.TryGetCultAsteroidTransform(AsteroidBeltBodyKey, Asteroid, out var asteroidPosition, out var asteroidRadius) &&
length(Entity.CultPositionXZ - asteroidPosition) - asteroidRadius < Range)
Range = Evaluate(_data.Range);
var belt = Entity.Zone.AsteroidBelts[AsteroidBelt];
if (AsteroidBelt != Guid.Empty &&
Entity.Zone.AsteroidExists(AsteroidBelt, Asteroid) &&
length(Entity.Position.xz - belt.Transforms[Asteroid].xy) - belt.Transforms[Asteroid].w < Range)
{
Entity.Zone.MineAsteroid(
Entity,
AsteroidBeltBodyKey,
AsteroidBelt,
Asteroid,
Evaluate(_damagePerSecond) * dt,
Evaluate(_efficiency),
Evaluate(_penetration));
Evaluate(_data.DamagePerSecond) * dt,
Evaluate(_data.Efficiency),
Evaluate(_data.Penetration));
return true;
}
return false;
}
public void RestoreRuntimeState(string asteroidBeltBodyKey, int asteroid, float range)
{
AsteroidBeltBodyKey = asteroidBeltBodyKey ?? "";
Asteroid = asteroid;
Range = range;
}
}
}

View file

@ -2,84 +2,93 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using static CultMath.math;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class RadiatorData : BehaviorData
{
[Inspectable, JsonProperty("emissivity"), Key(1), RuntimeInspectable]
public PerformanceStat Emissivity = new PerformanceStat();
[Inspectable, JsonProperty("pumpedHeat"), Key(2), RuntimeInspectable]
public PerformanceStat PumpedHeat = new PerformanceStat();
[InspectableTemperature, JsonProperty("temperatureFloor"), Key(3), RuntimeInspectable]
public float TemperatureFloor;
[Inspectable, JsonProperty("wasteHeat"), Key(4), RuntimeInspectable]
public PerformanceStat WasteHeat = new PerformanceStat();
[Inspectable, JsonProperty("energyUsage"), Key(5), RuntimeInspectable]
public PerformanceStat EnergyUsage = new PerformanceStat();
[Inspectable, JsonProperty("thermalMass"), Key(6), RuntimeInspectable]
public PerformanceStat ThermalMass = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new Radiator(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Radiator(this, item);
}
}
public class Radiator : Behavior, IAlwaysUpdatedBehavior, IInitializableBehavior
{
public float RadiatorTemperature { get; private set; }
public float Emissivity { get; private set; }
public float PumpedHeat { get; private set; }
public float WasteHeat { get; private set; }
public float EnergyUsage { get; private set; }
private RadiatorData _data;
private readonly PerformanceStat _emissivity;
private readonly PerformanceStat _pumpedHeat;
private readonly float _temperatureFloor;
private readonly PerformanceStat _wasteHeat;
private readonly PerformanceStat _energyUsage;
private readonly PerformanceStat _thermalMass;
public Radiator(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Radiator(RadiatorData data, EquippedItem item) : base(data, item)
{
_emissivity = definition.PerformanceStat(1, new PerformanceStat());
_pumpedHeat = definition.PerformanceStat(2, new PerformanceStat());
_temperatureFloor = definition.Float(3);
_wasteHeat = definition.PerformanceStat(4, new PerformanceStat());
_energyUsage = definition.PerformanceStat(5, new PerformanceStat());
_thermalMass = definition.PerformanceStat(6, new PerformanceStat());
RegisterPerformanceStat(nameof(Emissivity), _emissivity);
RegisterPerformanceStat(nameof(PumpedHeat), _pumpedHeat);
RegisterPerformanceStat(nameof(WasteHeat), _wasteHeat);
RegisterPerformanceStat(nameof(EnergyUsage), _energyUsage);
RegisterPerformanceStat("ThermalMass", _thermalMass);
_data = data;
}
public Radiator(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Radiator(RadiatorData data, ConsumableItemEffect item) : base(data, item)
{
_emissivity = definition.PerformanceStat(1, new PerformanceStat());
_pumpedHeat = definition.PerformanceStat(2, new PerformanceStat());
_temperatureFloor = definition.Float(3);
_wasteHeat = definition.PerformanceStat(4, new PerformanceStat());
_energyUsage = definition.PerformanceStat(5, new PerformanceStat());
_thermalMass = definition.PerformanceStat(6, new PerformanceStat());
RegisterPerformanceStat(nameof(Emissivity), _emissivity);
RegisterPerformanceStat(nameof(PumpedHeat), _pumpedHeat);
RegisterPerformanceStat(nameof(WasteHeat), _wasteHeat);
RegisterPerformanceStat(nameof(EnergyUsage), _energyUsage);
RegisterPerformanceStat("ThermalMass", _thermalMass);
_data = data;
}
public override bool Execute(float dt)
{
PumpedHeat = Evaluate(_pumpedHeat);
WasteHeat = Evaluate(_wasteHeat);
EnergyUsage = Evaluate(_energyUsage);
PumpedHeat = Evaluate(_data.PumpedHeat);
WasteHeat = Evaluate(_data.WasteHeat);
EnergyUsage = Evaluate(_data.EnergyUsage);
var itemTemperature = Temperature;
var tempRatio = max(RadiatorTemperature / itemTemperature, 1);
// Temperature ratio would cause more waste heat than pump capacity, stop executing
if (tempRatio > PumpedHeat / WasteHeat) return true;
if (!Entity.TryConsumeEnergy(EnergyUsage * tempRatio * dt)) return false;
var pumpedHeat = PumpedHeat * max(itemTemperature - _temperatureFloor, 0);
var pumpedHeat = PumpedHeat * max(itemTemperature - _data.TemperatureFloor, 0);
// Radiator temperature is below temperature floor, stop executing
if (pumpedHeat < 0.01f) return true;
var wasteHeat = WasteHeat * tempRatio;
AddHeat((wasteHeat - pumpedHeat) * dt);
RadiatorTemperature += pumpedHeat / Evaluate(_thermalMass) * dt;
RadiatorTemperature += pumpedHeat / Evaluate(_data.ThermalMass) * dt;
return true;
}
public void Update(float delta)
{
Emissivity = Evaluate(_emissivity);
Emissivity = Evaluate(_data.Emissivity);
var rad = pow(RadiatorTemperature, ItemManager.GameplaySettings.HeatRadiationExponent) * ItemManager.GameplaySettings.HeatRadiationMultiplier * Emissivity;
RadiatorTemperature -= rad * delta;
Entity.VisibilitySources[this] = rad;
@ -89,18 +98,4 @@ public class Radiator : Behavior, IAlwaysUpdatedBehavior, IInitializableBehavior
{
RadiatorTemperature = Temperature;
}
public void RestoreRuntimeState(
float radiatorTemperature,
float emissivity,
float pumpedHeat,
float wasteHeat,
float energyUsage)
{
RadiatorTemperature = radiatorTemperature;
Emissivity = emissivity;
PumpedHeat = pumpedHeat;
WasteHeat = wasteHeat;
EnergyUsage = energyUsage;
}
}
}

View file

@ -5,18 +5,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
using UniRx;
using static CultMath.math;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class ReactorData : BehaviorData
{
[Inspectable, JsonProperty("charge"), Key(1), RuntimeInspectable]
public PerformanceStat Charge = new PerformanceStat();
[Inspectable, JsonProperty("efficiency"), Key(2), RuntimeInspectable]
public PerformanceStat Efficiency = new PerformanceStat();
[Inspectable, JsonProperty("overload"), Key(3), RuntimeInspectable]
public PerformanceStat OverloadEfficiency = new PerformanceStat();
[Inspectable, JsonProperty("underload"), Key(4), RuntimeInspectable]
public PerformanceStat ThrottlingFactor = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new Reactor(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Reactor(this, item);
}
}
public class Reactor : Behavior, IOrderedBehavior, IDisposable
{
private readonly PerformanceStat _charge;
private readonly PerformanceStat _efficiency;
private readonly PerformanceStat _overloadEfficiency;
private readonly PerformanceStat _throttlingFactor;
private ReactorData _data;
public float Draw { get; private set; }
public float CurrentLoadRatio { get; private set; }
public int Order => 100;
@ -25,29 +51,14 @@ public class Reactor : Behavior, IOrderedBehavior, IDisposable
private List<IDisposable> _subscriptions = new List<IDisposable>();
public Reactor(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Reactor(ReactorData data, EquippedItem item) : base(data, item)
{
_charge = definition.PerformanceStat(1, new PerformanceStat());
_efficiency = definition.PerformanceStat(2, new PerformanceStat());
_overloadEfficiency = definition.PerformanceStat(3, new PerformanceStat());
_throttlingFactor = definition.PerformanceStat(4, new PerformanceStat());
RegisterPerformanceStat("Charge", _charge);
RegisterPerformanceStat("Efficiency", _efficiency);
RegisterPerformanceStat("OverloadEfficiency", _overloadEfficiency);
RegisterPerformanceStat("ThrottlingFactor", _throttlingFactor);
_data = data;
FindCapacitors();
}
public Reactor(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Reactor(ReactorData data, ConsumableItemEffect item) : base(data, item)
{
_charge = definition.PerformanceStat(1, new PerformanceStat());
_efficiency = definition.PerformanceStat(2, new PerformanceStat());
_overloadEfficiency = definition.PerformanceStat(3, new PerformanceStat());
_throttlingFactor = definition.PerformanceStat(4, new PerformanceStat());
RegisterPerformanceStat("Charge", _charge);
RegisterPerformanceStat("Efficiency", _efficiency);
RegisterPerformanceStat("OverloadEfficiency", _overloadEfficiency);
RegisterPerformanceStat("ThrottlingFactor", _throttlingFactor);
_data = data;
FindCapacitors();
}
@ -73,14 +84,14 @@ public class Reactor : Behavior, IOrderedBehavior, IDisposable
public override bool Execute(float dt)
{
var charge = Evaluate(_charge) * dt;
var efficiency = Evaluate(_efficiency);
var charge = Evaluate(_data.Charge) * dt;
var efficiency = Evaluate(_data.Efficiency);
// This behavior executes last, so any components drawing power have already done so
// Subtract the baseline charge from draw
Draw -= charge;
// Generate heat using baseline efficiency
var heat = charge / efficiency;
@ -88,11 +99,11 @@ public class Reactor : Behavior, IOrderedBehavior, IDisposable
if (Draw > .01f)
{
CurrentLoadRatio = (Draw + charge) / max(charge, .01f);
var overloadEfficiency = Evaluate(_overloadEfficiency);
var overloadEfficiency = Evaluate(_data.OverloadEfficiency);
// Generate heat using overload efficiency, usually much less efficient!
heat += Draw / overloadEfficiency;
// Overload power will always neutralize the energy deficit
Draw = 0;
}
@ -121,16 +132,16 @@ public class Reactor : Behavior, IOrderedBehavior, IDisposable
if (Draw < -.01f)
{
CurrentLoadRatio = (Draw + charge) / max(charge, .01f);
heat -= Draw / efficiency * (1 - 1 / Evaluate(_throttlingFactor));
heat -= Draw / efficiency * (1 - 1 / Evaluate(_data.ThrottlingFactor));
Draw = 0;
}
else
{
CurrentLoadRatio = 1;
}
Item.SetAudioParameter(SpecialAudioParameter.Intensity, max(.25f, 1 - 1 / CurrentLoadRatio));
AddHeat(heat);
return true;
}
@ -140,10 +151,4 @@ public class Reactor : Behavior, IOrderedBehavior, IDisposable
foreach(var sub in _subscriptions)
sub.Dispose();
}
public void RestoreRuntimeState(float draw, float currentLoadRatio)
{
Draw = draw;
CurrentLoadRatio = currentLoadRatio;
}
}
}

View file

@ -2,26 +2,49 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class ReflectorData : BehaviorData
{
[Inspectable, JsonProperty("crossSection"), Key(1), RuntimeInspectable]
public PerformanceStat CrossSection = new PerformanceStat();
// [InspectableAnimationCurve, JsonProperty("visibility"), Key(1)]
// public float4[] VisibilityCurve;
public override Behavior CreateInstance(EquippedItem item)
{
return new Reflector(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Reflector(this, item);
}
}
public class Reflector : Behavior
{
private readonly PerformanceStat _crossSection;
private ReflectorData _data;
public Reflector(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Reflector(ReflectorData data, EquippedItem item) : base(data, item)
{
_crossSection = definition.PerformanceStat(1, new PerformanceStat());
RegisterPerformanceStat("CrossSection", _crossSection);
_data = data;
}
public Reflector(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Reflector(ReflectorData data, ConsumableItemEffect item) : base(data, item)
{
_crossSection = definition.PerformanceStat(1, new PerformanceStat());
RegisterPerformanceStat("CrossSection", _crossSection);
_data = data;
}
public override bool Execute(float dt)
{
Entity.VisibilitySources[this] = Evaluate(_crossSection) * Entity.Zone.GetLight(Entity.CultPositionXZ);
Entity.VisibilitySources[this] = Evaluate(_data.CrossSection) * Entity.Zone.GetLight(Entity.Position.xz);
return true;
}
}
}

View file

@ -1,85 +1,105 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using static CultMath.math;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class ResourceScannerData : BehaviorData
{
[Inspectable, JsonProperty("range"), Key(1), RuntimeInspectable]
public PerformanceStat Range = new PerformanceStat();
[Inspectable, JsonProperty("minDensity"), Key(2), RuntimeInspectable]
public PerformanceStat MinimumDensity = new PerformanceStat();
[Inspectable, JsonProperty("scanDuration"), Key(3), RuntimeInspectable]
public PerformanceStat ScanDuration = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new ResourceScanner(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new ResourceScanner(this, item);
}
}
public class ResourceScanner : Behavior, IAlwaysUpdatedBehavior
{
public int Asteroid = -1;
private readonly PerformanceStat _range;
private readonly PerformanceStat _minimumDensity;
private readonly PerformanceStat _scanDuration;
private ResourceScannerData _data;
private float _scanTime;
private string _scanTargetBodyKey = "";
private Guid _scanTarget;
public float Range { get; private set; }
public float MinimumDensity { get; private set; }
public float ScanDuration { get; private set; }
public float ScanTime => _scanTime;
public string ScanTargetBodyKey
public Guid ScanTarget
{
get => _scanTargetBodyKey;
get => _scanTarget;
set
{
value ??= "";
if (!string.Equals(value, _scanTargetBodyKey, StringComparison.Ordinal))
if (value != _scanTarget)
{
_scanTargetBodyKey = value;
_scanTarget = value;
_scanTime = 0;
}
}
}
public ResourceScanner(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public ResourceScanner(ResourceScannerData data, EquippedItem item) : base(data, item)
{
_range = definition.PerformanceStat(1, new PerformanceStat());
_minimumDensity = definition.PerformanceStat(2, new PerformanceStat());
_scanDuration = definition.PerformanceStat(3, new PerformanceStat());
RegisterPerformanceStat(nameof(Range), _range);
RegisterPerformanceStat(nameof(MinimumDensity), _minimumDensity);
RegisterPerformanceStat(nameof(ScanDuration), _scanDuration);
_data = data;
}
public ResourceScanner(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public ResourceScanner(ResourceScannerData data, ConsumableItemEffect item) : base(data, item)
{
_range = definition.PerformanceStat(1, new PerformanceStat());
_minimumDensity = definition.PerformanceStat(2, new PerformanceStat());
_scanDuration = definition.PerformanceStat(3, new PerformanceStat());
RegisterPerformanceStat(nameof(Range), _range);
RegisterPerformanceStat(nameof(MinimumDensity), _minimumDensity);
RegisterPerformanceStat(nameof(ScanDuration), _scanDuration);
_data = data;
}
public override bool Execute(float dt)
{
if (Entity.Zone.TryGetAsteroidBelt(ScanTargetBodyKey, out var belt))
var planetData = Entity.Zone.Planets[ScanTarget];
if (planetData != null)
{
if (Entity.Zone.TryGetCultAsteroidTransform(ScanTargetBodyKey, Asteroid, out var asteroidPosition, out _) &&
length(Entity.CultPositionXZ - asteroidPosition) < Range)
if (planetData is AsteroidBeltData beltData)
{
_scanTime += dt;
if (_scanTime > ScanDuration)
if(Asteroid > -1 &&
Asteroid < beltData.Asteroids.Length &&
length(Entity.Position.xz - Entity.Zone.AsteroidBelts[ScanTarget].Transforms[Asteroid].xy) < Range)
{
// TODO: Implement Scanning!
_scanTime = 0;
_scanTime += dt;
if (_scanTime > ScanDuration)
{
// TODO: Implement Scanning!
//Context.ItemData.Get<Corporation>(Entity.Corporation).PlanetSurveyFloor[ScanTarget] = MinimumDensity;
_scanTime = 0;
}
return true;
}
return true;
}
}
else if (Entity.Zone.TryGetPlanet(ScanTargetBodyKey, out var planet))
{
if(length(Entity.CultPositionXZ - AetheriaMath.ToCult(Entity.Zone.GetOrbitPosition(planet.OrbitKey))) < Range)
else
{
_scanTime += dt;
if (_scanTime > ScanDuration)
if(length(Entity.Position.xz - Entity.Zone.GetOrbitPosition(planetData.Orbit)) < Range)
{
_scanTime = 0;
_scanTime += dt;
if (_scanTime > ScanDuration)
{
//Context.ItemData.Get<Corporation>(Entity.Corporation).PlanetSurveyFloor[ScanTarget] = MinimumDensity;
_scanTime = 0;
}
return true;
}
return true;
}
}
return false;
@ -87,24 +107,8 @@ public class ResourceScanner : Behavior, IAlwaysUpdatedBehavior
public void Update(float delta)
{
Range = Evaluate(_range);
MinimumDensity = Evaluate(_minimumDensity);
ScanDuration = Evaluate(_scanDuration);
Range = Evaluate(_data.Range);
MinimumDensity = Evaluate(_data.MinimumDensity);
ScanDuration = Evaluate(_data.ScanDuration);
}
public void RestoreRuntimeState(
string scanTargetBodyKey,
int asteroid,
float scanTime,
float range,
float minimumDensity,
float scanDuration)
{
_scanTargetBodyKey = scanTargetBodyKey ?? "";
Asteroid = asteroid;
_scanTime = scanTime;
Range = range;
MinimumDensity = minimumDensity;
ScanDuration = scanDuration;
}
}
}

View file

@ -4,19 +4,55 @@
using System;
using System.Collections.Generic;
using static CultMath.math;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class SensorData : BehaviorData
{
[Inspectable, JsonProperty("sensitivity"), Key(3), RuntimeInspectable]
public PerformanceStat Sensitivity = new PerformanceStat();
[InspectableAnimationCurve, JsonProperty("sensCurve"), Key(4), RuntimeInspectable]
public BezierCurve SensitivityCurve;
[Inspectable, JsonProperty("pingBoost"), Key(5), RuntimeInspectable]
public PerformanceStat PingBoost;
[Inspectable, JsonProperty("pingEnergy"), Key(6), RuntimeInspectable]
public PerformanceStat PingEnergy;
[Inspectable, JsonProperty("pingVisibility"), Key(7), RuntimeInspectable]
public PerformanceStat PingVisibility;
[Inspectable, JsonProperty("pingRange"), Key(8), RuntimeInspectable]
public PerformanceStat PingRange;
[Inspectable, JsonProperty("pingCooldown"), Key(9), RuntimeInspectable]
public PerformanceStat PingCooldown;
[Inspectable, JsonProperty("pingDuration"), Key(10)]
public float PingDuration = 2;
[Inspectable, JsonProperty("pingRadiusExponent"), Key(11)]
public float PingRadiusExponent = .5f;
public override Behavior CreateInstance(EquippedItem item)
{
return new Sensor(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Sensor(this, item);
}
}
public class Sensor : Behavior, IEventBehavior
{
private readonly PerformanceStat _sensitivity;
private readonly BezierCurve _sensitivityCurve;
private readonly PerformanceStat _pingBoost;
private readonly PerformanceStat _pingEnergy;
private readonly PerformanceStat _pingVisibility;
private readonly PerformanceStat _pingRange;
private readonly PerformanceStat _pingCooldownDuration;
private readonly float _pingDuration;
private readonly float _pingRadiusExponent;
private SensorData _data;
private float _pingCooldown;
private float _pingLerp;
private bool _pinging;
@ -27,16 +63,13 @@ public class Sensor : Behavior, IEventBehavior
{
get => saturate(_pingCooldown);
}
public float PingRadius
{
get => _pingRadius;
}
public float PingLerp => _pingLerp;
public bool Pinging => _pinging;
public int PingedEntityCount => _pingedEntities.Count;
public float PingBrightness => pow(1 - _pingLerp, _pingRadiusExponent);
public float PingBrightness => pow(1 - _pingLerp, _data.PingRadiusExponent);
public event Action OnPingStart;
public event Action OnPingEnd;
@ -49,9 +82,9 @@ public class Sensor : Behavior, IEventBehavior
public void Ping()
{
if(_pingCooldown < 0 && Entity.TryConsumeEnergy(Evaluate(_pingEnergy)))
if(_pingCooldown < 0 && Entity.TryConsumeEnergy(Evaluate(_data.PingEnergy)))
{
Entity.VisibilitySources[this] = Evaluate(_pingVisibility);
Entity.VisibilitySources[this] = Evaluate(_data.PingVisibility);
_pinging = true;
_pingCooldown = 1;
_pingLerp = 0;
@ -61,50 +94,22 @@ public class Sensor : Behavior, IEventBehavior
}
}
public Sensor(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Sensor(SensorData data, EquippedItem item) : base(data, item)
{
_sensitivity = definition.PerformanceStat(3, new PerformanceStat());
_sensitivityCurve = definition.BezierCurve(4, null);
_pingBoost = definition.PerformanceStat(5, null);
_pingEnergy = definition.PerformanceStat(6, null);
_pingVisibility = definition.PerformanceStat(7, null);
_pingRange = definition.PerformanceStat(8, null);
_pingCooldownDuration = definition.PerformanceStat(9, null);
_pingDuration = definition.Float(10, 2);
_pingRadiusExponent = definition.Float(11, .5f);
RegisterPerformanceStats();
_data = data;
}
public Sensor(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Sensor(SensorData data, ConsumableItemEffect item) : base(data, item)
{
_sensitivity = definition.PerformanceStat(3, new PerformanceStat());
_sensitivityCurve = definition.BezierCurve(4, null);
_pingBoost = definition.PerformanceStat(5, null);
_pingEnergy = definition.PerformanceStat(6, null);
_pingVisibility = definition.PerformanceStat(7, null);
_pingRange = definition.PerformanceStat(8, null);
_pingCooldownDuration = definition.PerformanceStat(9, null);
_pingDuration = definition.Float(10, 2);
_pingRadiusExponent = definition.Float(11, .5f);
RegisterPerformanceStats();
}
private void RegisterPerformanceStats()
{
RegisterPerformanceStat("Sensitivity", _sensitivity);
RegisterPerformanceStat("PingBoost", _pingBoost);
RegisterPerformanceStat("PingEnergy", _pingEnergy);
RegisterPerformanceStat("PingVisibility", _pingVisibility);
RegisterPerformanceStat("PingRange", _pingRange);
RegisterPerformanceStat("PingCooldown", _pingCooldownDuration);
_data = data;
}
public override bool Execute(float dt)
{
if (_pinging)
{
_pingLerp += dt / _pingDuration;
_pingRadius = lerp(0, Evaluate(_pingRange), pow(_pingLerp, _pingRadiusExponent));
_pingLerp += dt / _data.PingDuration;
_pingRadius = lerp(0, Evaluate(_data.PingRange), pow(_pingLerp, _data.PingRadiusExponent));
if (_pingLerp > 1)
{
_pinging = false;
@ -112,17 +117,16 @@ public class Sensor : Behavior, IEventBehavior
}
}
_pingCooldown -= dt / Evaluate(_pingCooldownDuration);
_pingCooldown -= dt / Evaluate(_data.PingCooldown);
// TODO: Handle Active Detection / Visibility From Reflected Radiance
var forward = Direction.xz;
var entityPosition = Entity.CultPositionXZ;
foreach (var entity in Entity.Zone.Entities)
{
if (entity == Entity) continue;
var diff = entity.CultPositionXZ - entityPosition;
var angle = AetheriaMath.AngleRadians(forward, diff);
var diff = entity.Position.xz - Entity.Position.xz;
var angle = acos(dot(forward, normalize(diff)));
var dist = length(diff);
float previous, next;
Entity.EntityInfoGathered.TryGetValue(entity, out previous);
@ -132,8 +136,8 @@ public class Sensor : Behavior, IEventBehavior
next = saturate(
previous +
entity.Visibility *
Evaluate(_sensitivity) *
Evaluate(_pingBoost) *
Evaluate(_data.Sensitivity) *
Evaluate(_data.PingBoost) *
dist);
}
else
@ -141,8 +145,8 @@ public class Sensor : Behavior, IEventBehavior
next = saturate(
previous +
entity.Visibility *
Evaluate(_sensitivity) *
_sensitivityCurve.Evaluate(angle / PI) *
Evaluate(_data.Sensitivity) *
_data.SensitivityCurve.Evaluate(angle / PI) *
dt / dist);
}
next *= 1 - ItemManager.GameplaySettings.TargetInfoDecay * dt;
@ -151,17 +155,4 @@ public class Sensor : Behavior, IEventBehavior
}
return true;
}
public void RestoreRuntimeState(
bool pinging,
float pingCooldown,
float pingLerp,
float pingRadius)
{
_pinging = pinging;
_pingCooldown = pingCooldown;
_pingLerp = pingLerp;
_pingRadius = pingRadius;
_pingedEntities.Clear();
}
}
}

View file

@ -2,34 +2,50 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class ShieldData : BehaviorData
{
[Inspectable, JsonProperty("efficiency"), Key(1), RuntimeInspectable]
public PerformanceStat Efficiency = new PerformanceStat();
[Inspectable, JsonProperty("energy"), Key(2), RuntimeInspectable]
public PerformanceStat EnergyUsage = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new Shield(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Shield(this, item);
}
}
public class Shield : Behavior, IProgressBehavior
{
public float Efficiency { get; private set; }
public float EnergyUsage { get; private set; }
private readonly PerformanceStat _efficiency;
private readonly PerformanceStat _energyUsage;
private ShieldData _data;
public Shield(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Shield(ShieldData data, EquippedItem item) : base(data, item)
{
_efficiency = definition.PerformanceStat(1, new PerformanceStat());
_energyUsage = definition.PerformanceStat(2, new PerformanceStat());
RegisterPerformanceStat(nameof(Efficiency), _efficiency);
RegisterPerformanceStat(nameof(EnergyUsage), _energyUsage);
_data = data;
}
public Shield(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Shield(ShieldData data, ConsumableItemEffect item) : base(data, item)
{
_efficiency = definition.PerformanceStat(1, new PerformanceStat());
_energyUsage = definition.PerformanceStat(2, new PerformanceStat());
RegisterPerformanceStat(nameof(Efficiency), _efficiency);
RegisterPerformanceStat(nameof(EnergyUsage), _energyUsage);
_data = data;
}
public override bool Execute(float dt)
{
Efficiency = Evaluate(_efficiency);
EnergyUsage = Evaluate(_energyUsage);
Efficiency = Evaluate(_data.Efficiency);
EnergyUsage = Evaluate(_data.EnergyUsage);
return true;
}
@ -45,10 +61,4 @@ public class Shield : Behavior, IProgressBehavior
}
public virtual float Progress => Item.ThermalPerformance;
public void RestoreRuntimeState(float efficiency, float energyUsage)
{
Efficiency = efficiency;
EnergyUsage = energyUsage;
}
}
}

View file

@ -1,118 +1,105 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using MessagePack;
using Newtonsoft.Json;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class StatModifierData : BehaviorData
{
[Inspectable, JsonProperty("stat"), Key(1)]
public StatReference Stat = new StatReference();
[Inspectable, JsonProperty("modifier"), Key(2)]
public PerformanceStat Modifier = new PerformanceStat();
[Inspectable, JsonProperty("type"), Key(3)]
public StatModifierType Type;
[InspectableType(typeof(BehaviorData)), JsonProperty("requireBehavior"), Key(4)]
public Type RequireBehavior;
public override Behavior CreateInstance(EquippedItem item)
{
return new StatModifier(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect consumable)
{
return new StatModifier(this, consumable);
}
}
[Order(-4)]
public class StatModifier : Behavior, IInitializableBehavior, IDisposable, IAlwaysUpdatedBehavior
{
private readonly string _targetBehaviorKind;
private readonly string _targetStatName;
private readonly PerformanceStat _modifier;
private readonly StatModifierType _type;
private readonly string _requiredBehaviorKind;
private StatModifierData _data;
private StatModifierTarget[] _targets;
private PerformanceStat[] _stats;
private static Type[] _statObjects;
private bool _applied;
private bool _executed;
public bool Applied => _applied;
public bool Executed => _executed;
public int TargetStatCount => _targets?.Length ?? 0;
private static Type[] StatObjects => _statObjects = _statObjects ?? typeof(BehaviorData).GetAllChildClasses()
.Concat(typeof(EquippableItemData).GetAllChildClasses()).ToArray();
public StatModifier(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public StatModifier(StatModifierData data, EquippedItem item) : base(data, item)
{
var stat = definition.StatReference(1, new StatReference());
_targetBehaviorKind = stat.Target;
_targetStatName = stat.Stat;
_modifier = definition.PerformanceStat(2, new PerformanceStat());
_type = definition.Enum(3, default(StatModifierType));
_requiredBehaviorKind = definition.String(4);
RegisterPerformanceStat("Modifier", _modifier);
_data = data;
}
public StatModifier(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public StatModifier(StatModifierData data, ConsumableItemEffect item) : base(data, item)
{
var stat = definition.StatReference(1, new StatReference());
_targetBehaviorKind = stat.Target;
_targetStatName = stat.Stat;
_modifier = definition.PerformanceStat(2, new PerformanceStat());
_type = definition.Enum(3, default(StatModifierType));
_requiredBehaviorKind = definition.String(4);
RegisterPerformanceStat("Modifier", _modifier);
_data = data;
}
public void Initialize()
{
var targets = new List<StatModifierTarget>();
foreach (var gear in Entity.Equipment.Where(HasRequiredBehavior))
foreach (var behavior in gear.Behaviors ?? Array.Empty<Behavior>())
var targetType = StatObjects.FirstOrDefault(so => so.Name == _data.Stat.Target);
if (targetType != null)
{
if (!BehaviorKindMatches(behavior.Kind, _targetBehaviorKind))
continue;
var stat = FindTargetStat(behavior);
if (stat != null)
targets.Add(new StatModifierTarget(gear, stat));
var statField = targetType.GetFields()
.Where(f => f.FieldType == typeof(PerformanceStat)).FirstOrDefault(f => f.Name == _data.Stat.Stat);
if (statField != null)
{
if (typeof(EquippableItemData).IsAssignableFrom(targetType))
_stats = Entity.Equipment
.Select(hp => hp.EquippableItem)
.Where(gear => _data.RequireBehavior == null || ItemManager.GetData(gear).Behaviors.Any(behavior => behavior.GetType() == _data.RequireBehavior))
.Where(gear => ItemManager.GetData(gear).GetType() == targetType)
.Select(gear => statField.GetValue(ItemManager.GetData(gear)) as PerformanceStat)
.ToArray();
else
_stats = Entity.Equipment
.Select(hp => hp.EquippableItem)
.Where(gear => _data.RequireBehavior == null || ItemManager.GetData(gear).Behaviors.Any(behavior => behavior.GetType() == _data.RequireBehavior))
.SelectMany(gear => ItemManager.GetData(gear).Behaviors)
.Where(behaviorData => behaviorData.GetType() == targetType)
.Select(behaviorData => statField.GetValue(behaviorData) as PerformanceStat)
.ToArray();
}
}
_targets = targets.ToArray();
}
private PerformanceStat FindTargetStat(Behavior behavior)
{
return behavior.TryGetPerformanceStat(_targetStatName, out var stat) ? stat : null;
}
private static bool BehaviorKindMatches(string runtimeKind, string expectedKind)
{
return AetheriaRuntimeBehaviorMetadataCatalog.IsKindOrDescendant(
runtimeKind,
NormalizeExpectedBehaviorKind(expectedKind));
}
private static string NormalizeExpectedBehaviorKind(string expectedKind)
{
if (string.IsNullOrWhiteSpace(expectedKind))
{
return "";
}
const string legacyDataSuffix = "Data";
return expectedKind.EndsWith(legacyDataSuffix, StringComparison.Ordinal)
? expectedKind.Substring(0, expectedKind.Length - legacyDataSuffix.Length)
: expectedKind;
}
private bool HasRequiredBehavior(EquippedItem gear)
{
return string.IsNullOrWhiteSpace(_requiredBehaviorKind) ||
(gear?.Behaviors ?? Array.Empty<Behavior>())
.Any(behavior => BehaviorKindMatches(behavior.Kind, _requiredBehaviorKind));
}
private void ApplyModifier()
{
_applied = true;
RefreshModifier();
foreach (var stat in _stats)
(_data.Type == StatModifierType.Constant
? stat.GetConstantModifiers(Entity)
: stat.GetScaleModifiers(Entity))[this] = Evaluate(_data.Modifier);
}
private void RemoveModifier()
{
_applied = false;
foreach (var target in _targets ?? Array.Empty<StatModifierTarget>())
target.Item.RemoveStatModifier(target.Stat, this, _type);
}
private void RefreshModifier()
{
var value = Evaluate(_modifier);
foreach (var target in _targets ?? Array.Empty<StatModifierTarget>())
target.Item.SetStatModifier(target.Stat, this, _type, value);
foreach (var stat in _stats)
(_data.Type == StatModifierType.Constant ? stat.GetConstantModifiers(Entity) : stat.GetScaleModifiers(Entity)).Remove(this);
}
public override bool Execute(float dt)
@ -131,37 +118,10 @@ public class StatModifier : Behavior, IInitializableBehavior, IDisposable, IAlwa
{
if(_executed && !_applied)
ApplyModifier();
else if(_executed && _applied)
RefreshModifier();
if(!_executed && _applied)
RemoveModifier();
_executed = false;
}
public void RestoreRuntimeState(bool applied, bool executed)
{
if (_targets == null)
Initialize();
if (applied && !_applied)
ApplyModifier();
if (applied && _applied)
RefreshModifier();
if (!applied && _applied)
RemoveModifier();
_executed = executed;
}
private readonly struct StatModifierTarget
{
public StatModifierTarget(EquippedItem item, PerformanceStat stat)
{
Item = item;
Stat = stat;
}
public EquippedItem Item { get; }
public PerformanceStat Stat { get; }
}
}
public enum StatModifierType
@ -170,9 +130,12 @@ public enum StatModifierType
Multiplier
}
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class StatReference
{
[InspectableType(typeof(BehaviorData)), JsonProperty("behavior"), Key(1)]
public string Target;
[Inspectable, JsonProperty("stat"), Key(2)]
public string Stat;
}
}

View file

@ -1,18 +1,38 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), Order(-25)]
public class SwitchData : BehaviorData
{
public override Behavior CreateInstance(EquippedItem item)
{
return new Switch(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Switch(this, item);
}
}
public class Switch : Behavior, IActivatedBehavior
{
private SwitchData _data;
public bool Activated { get; set; }
public Switch(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Switch(SwitchData data, EquippedItem item) : base(data, item)
{
_data = data;
}
public Switch(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Switch(SwitchData data, ConsumableItemEffect item) : base(data, item)
{
_data = data;
}
public override bool Execute(float dt)
@ -29,4 +49,4 @@ public class Switch : Behavior, IActivatedBehavior
{
Activated = false;
}
}
}

View file

@ -1,31 +1,54 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), Order(-22)]
public class ThermotoggleData : BehaviorData
{
[InspectableTemperature, JsonProperty("targetTemp"), Key(1)]
public float TargetTemperature;
[Inspectable, JsonProperty("highPass"), Key(2)]
public bool HighPass;
[Inspectable, JsonProperty("adjustable"), Key(3)]
public bool Adjustable;
public override Behavior CreateInstance(EquippedItem item)
{
return new Thermotoggle(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Thermotoggle(this, item);
}
}
public class Thermotoggle : Behavior
{
public float TargetTemperature;
public bool Adjustable { get; }
private readonly bool _highPass;
private ThermotoggleData _data;
public Thermotoggle(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public ThermotoggleData ThermotoggleData => _data;
public Thermotoggle(ThermotoggleData data, EquippedItem item) : base(data, item)
{
TargetTemperature = definition.Float(1);
_highPass = definition.Bool(2);
Adjustable = definition.Bool(3);
_data = data;
TargetTemperature = data.TargetTemperature;
}
public Thermotoggle(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Thermotoggle(ThermotoggleData data, ConsumableItemEffect item) : base(data, item)
{
TargetTemperature = definition.Float(1);
_highPass = definition.Bool(2);
Adjustable = definition.Bool(3);
_data = data;
TargetTemperature = data.TargetTemperature;
}
public override bool Execute(float dt)
{
return Temperature < TargetTemperature ^ _highPass;
return Temperature < TargetTemperature ^ _data.HighPass;
}
}
}

View file

@ -2,14 +2,44 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using static CultMath.math;
using cfloat2 = CultMath.float2;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), EntityTypeRestriction(HullType.Ship), RuntimeInspectable]
public class ThrusterData : BehaviorData
{
[Inspectable, JsonProperty("thrust"), Key(1), RuntimeInspectable]
public PerformanceStat Thrust = new PerformanceStat();
[Inspectable, JsonProperty("visibility"), Key(2), RuntimeInspectable]
public PerformanceStat Visibility = new PerformanceStat();
[Inspectable, JsonProperty("heat"), Key(3), RuntimeInspectable]
public PerformanceStat Heat = new PerformanceStat();
[Inspectable, JsonProperty("energy"), Key(4), RuntimeInspectable]
public PerformanceStat EnergyUsage = new PerformanceStat();
[InspectablePrefab, JsonProperty("Particles"), Key(5)]
public string ParticlesPrefab;
public override Behavior CreateInstance(EquippedItem item)
{
return new Thruster(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Thruster(this, item);
}
}
public class Thruster : Behavior, IAnalogBehavior
{
public float Thrust { get; private set; }
public float Torque { get; }
public string ParticlesPrefab { get; }
public float Axis
{
@ -17,70 +47,44 @@ public class Thruster : Behavior, IAnalogBehavior
set => _input = saturate(value);
}
private readonly PerformanceStat _thrust;
private readonly PerformanceStat _visibility;
private readonly PerformanceStat _heat;
private readonly PerformanceStat _energyUsage;
private ThrusterData _data;
private float _input;
public Thruster(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Thruster(ThrusterData data, EquippedItem item) : base(data, item)
{
_thrust = definition.PerformanceStat(1, new PerformanceStat());
_visibility = definition.PerformanceStat(2, new PerformanceStat());
_heat = definition.PerformanceStat(3, new PerformanceStat());
_energyUsage = definition.PerformanceStat(4, new PerformanceStat());
ParticlesPrefab = definition.String(5);
RegisterPerformanceStat(nameof(Thrust), _thrust);
RegisterPerformanceStat(nameof(Visibility), _visibility);
RegisterPerformanceStat(nameof(Heat), _heat);
RegisterPerformanceStat("EnergyUsage", _energyUsage);
var hullShape = ItemManager.GetRuntimeShape(Entity.Hull);
var itemShape = ItemManager.GetRuntimeShape(item.EquippableItem);
var hullCenter = hullShape.CenterOfMass;
var itemCenter = hullShape.Inset(itemShape, item.Position, item.EquippableItem.Rotation).CenterOfMass;
_data = data;
var hullData = ItemManager.GetData(Entity.Hull) as HullData;
var hullCenter = hullData.Shape.CenterOfMass;
var itemData = ItemManager.GetData(item.EquippableItem);
var itemCenter = hullData.Shape.Inset(itemData.Shape, item.Position, item.EquippableItem.Rotation).CenterOfMass;
var toCenter = hullCenter - itemCenter;
Torque = -dot(normalize(toCenter), AetheriaMath.Rotate(new cfloat2(1, 0), item.EquippableItem.Rotation));
Thrust = Evaluate(_thrust);
Torque = -dot(normalize(toCenter), float2(1, 0).Rotate(item.EquippableItem.Rotation));
Thrust = Evaluate(_data.Thrust);
}
public Thruster(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Thruster(ThrusterData data, ConsumableItemEffect item) : base(data, item)
{
_thrust = definition.PerformanceStat(1, new PerformanceStat());
_visibility = definition.PerformanceStat(2, new PerformanceStat());
_heat = definition.PerformanceStat(3, new PerformanceStat());
_energyUsage = definition.PerformanceStat(4, new PerformanceStat());
ParticlesPrefab = definition.String(5);
RegisterPerformanceStat(nameof(Thrust), _thrust);
RegisterPerformanceStat(nameof(Visibility), _visibility);
RegisterPerformanceStat(nameof(Heat), _heat);
RegisterPerformanceStat("EnergyUsage", _energyUsage);
_data = data;
Torque = 0;
Thrust = Evaluate(_thrust);
Thrust = Evaluate(_data.Thrust);
}
public override bool Execute(float dt)
{
Item.SetAudioParameter(SpecialAudioParameter.Intensity, _input);
if(_input > .01f && Entity.TryConsumeEnergy(_input * Evaluate(_energyUsage)))
if(_input > .01f && Entity.TryConsumeEnergy(_input * Evaluate(_data.EnergyUsage)))
{
Thrust = Evaluate(_thrust);
Entity.CultVelocity -= Direction.xz * _input * Thrust / Entity.Mass * dt;
Entity.CultDirection = AetheriaMath.Rotate(
Entity.CultDirection,
_input * Torque * Thrust * ItemManager.GameplaySettings.TorqueMultiplier / Entity.Mass * dt);
AddHeat(_input * Evaluate(_heat) * dt);
var vis = _input * Evaluate(_visibility);
if (!Entity.VisibilitySources.TryGetValue(this, out var existingVisibility) || vis > existingVisibility)
Thrust = Evaluate(_data.Thrust);
Entity.Velocity -= Direction.xz * _input * Thrust / Entity.Mass * dt;
Entity.Direction = mul(Entity.Direction,
Unity.Mathematics.float2x2.Rotate(_input * Torque * Thrust * ItemManager.GameplaySettings.TorqueMultiplier / Entity.Mass * dt));
AddHeat(_input * Evaluate(_data.Heat) * dt);
var vis = _input * Evaluate(_data.Visibility);
if (!Entity.VisibilitySources.ContainsKey(this) || vis > Entity.VisibilitySources[this])
Entity.VisibilitySources[this] = vis;
return true;
}
return false;
}
public void RestoreRuntimeState(float axis, float thrust)
{
Axis = axis;
Thrust = thrust;
}
}
}

View file

@ -1,16 +1,31 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), Order(-20)]
public class TriggerData : BehaviorData
{
public override Behavior CreateInstance(EquippedItem item)
{
return new Trigger(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Trigger(this, item);
}
}
public class Trigger : Behavior, IActivatedBehavior
{
public bool _pulled;
public bool Pulled => _pulled;
public Trigger(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item) { }
public Trigger(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item) { }
public Trigger(TriggerData data, EquippedItem item) : base(data, item) { }
public Trigger(TriggerData data, ConsumableItemEffect item) : base(data, item) { }
public override bool Execute(float dt)
{
@ -31,9 +46,4 @@ public class Trigger : Behavior, IActivatedBehavior
public void Deactivate()
{
}
public void RestoreRuntimeState(bool pulled)
{
_pulled = pulled;
}
}
}

View file

@ -1,29 +1,44 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.Collections.Generic;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
using UniRx;
using static CultMath.math;
using cfloat3 = CultMath.float3;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using float3 = Unity.Mathematics.float3;
[MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class TurretControllerData : BehaviorData
{
public override Behavior CreateInstance(EquippedItem item)
{
return new TurretController(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new TurretController(this, item);
}
}
public class TurretController : Behavior, IInitializableBehavior
{
private TurretControllerData _data;
private List<Weapon> _weapons = new List<Weapon>();
private float _shotSpeed;
private bool _predictShots;
public int WeaponCount => _weapons.Count;
public float ShotSpeed => _shotSpeed;
public bool PredictShots => _predictShots;
public TurretController(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public TurretController(TurretControllerData data, EquippedItem item) : base(data, item)
{
_data = data;
}
public TurretController(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public TurretController(TurretControllerData data, ConsumableItemEffect item) : base(data, item)
{
_data = data;
}
public void Initialize()
@ -31,7 +46,7 @@ public class TurretController : Behavior, IInitializableBehavior
foreach (var weapon in Entity.GetBehaviors<Weapon>())
{
_weapons.Add(weapon);
var vel = weapon.EvaluateVelocity();
var vel = weapon.Evaluate(weapon.WeaponData.Velocity);
if (vel > .1f)
{
_predictShots = true;
@ -44,30 +59,29 @@ public class TurretController : Behavior, IInitializableBehavior
{
if (Entity.Target.Value != null)
{
var entityPosition = Entity.CultPosition;
var targetPosition = Entity.Target.Value.CultPosition;
var diff = targetPosition - entityPosition;
var diff = Entity.Target.Value.Position - Entity.Position;
if (_predictShots)
{
var targetHull = Entity.ItemManager.GetRuntimeItem(Entity.Target.Value.Hull);
var targetVelocity = new cfloat3(Entity.Target.Value.CultVelocity.x, 0, Entity.Target.Value.CultVelocity.y);
var targetHullData = Entity.ItemManager.GetData(Entity.Target.Value.Hull) as HullData;
var targetVelocity = float3(Entity.Target.Value.Velocity.x, 0, Entity.Target.Value.Velocity.y);
var predictedPosition = AetheriaMath.FirstOrderIntercept(
entityPosition, cfloat3.zero, _shotSpeed,
targetPosition, targetVelocity
Entity.Position, float3.zero, _shotSpeed,
Entity.Target.Value.Position, targetVelocity
);
predictedPosition.y = Entity.Zone.GetHeight(predictedPosition.xz) + (float)(targetHull?.HullGridOffset ?? 0);
Entity.CultLookDirection = normalize(predictedPosition - entityPosition);
predictedPosition.y = Entity.Zone.GetHeight(predictedPosition.xz) + targetHullData.GridOffset;
Entity.LookDirection = normalize(predictedPosition - Entity.Position);
}
else
Entity.CultLookDirection = normalize(diff);
Entity.LookDirection = normalize(diff);
var dist = length(diff);
foreach (var x in _weapons)
{
var data = x.Data as WeaponData;
var fire = dot(
x.Direction,
Entity.CultLookDirection) > .99f;
if (x.EvaluateRange() > dist && fire)
Entity.LookDirection) > .99f;
if (x.Evaluate(data.Range) > dist && fire)
{
x.Activate();
}
@ -86,10 +100,4 @@ public class TurretController : Behavior, IInitializableBehavior
}
return true;
}
public void RestoreRuntimeState(float shotSpeed, bool predictShots)
{
_shotSpeed = shotSpeed;
_predictShots = predictShots;
}
}
}

View file

@ -2,28 +2,43 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using static CultMath.math;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class VelocityConversionData : BehaviorData
{
[Inspectable, JsonProperty("lambda"), Key(1), RuntimeInspectable]
public PerformanceStat Lambda = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new VelocityConversion(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new VelocityConversion(this, item);
}
}
public class VelocityConversion : Behavior
{
private readonly PerformanceStat _lambda;
private VelocityConversionData _data;
public VelocityConversion(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public VelocityConversion(VelocityConversionData data, EquippedItem item) : base(data, item)
{
_lambda = definition.PerformanceStat(1, new PerformanceStat());
RegisterPerformanceStat("Lambda", _lambda);
_data = data;
}
public VelocityConversion(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public VelocityConversion(VelocityConversionData data, ConsumableItemEffect item) : base(data, item)
{
_lambda = definition.PerformanceStat(1, new PerformanceStat());
RegisterPerformanceStat("Lambda", _lambda);
_data = data;
}
public override bool Execute(float dt)
{
var velocity = Entity.CultVelocity;
Entity.CultVelocity = AetheriaMath.Damp(velocity, Entity.CultDirection * length(velocity), Evaluate(_lambda), dt);
Entity.Velocity = AetheriaMath.Damp(Entity.Velocity, Entity.Direction * length(Entity.Velocity), Evaluate(_data.Lambda), dt);
return true;
}
}
}

View file

@ -2,39 +2,51 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using static CultMath.math;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class VelocityLimitData : BehaviorData
{
[Inspectable, JsonProperty("topSpeed"), Key(1), RuntimeInspectable]
public PerformanceStat TopSpeed = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new VelocityLimit(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new VelocityLimit(this, item);
}
}
[Order(100)]
public class VelocityLimit : Behavior
{
public float Limit { get; private set; }
private readonly PerformanceStat _topSpeed;
private VelocityLimitData _data;
public VelocityLimit(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public VelocityLimit(VelocityLimitData data, EquippedItem item) : base(data, item)
{
_topSpeed = definition.PerformanceStat(1, new PerformanceStat());
RegisterPerformanceStat("TopSpeed", _topSpeed);
Limit = Evaluate(_topSpeed);
_data = data;
Limit = Evaluate(_data.TopSpeed);
}
public VelocityLimit(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public VelocityLimit(VelocityLimitData data, ConsumableItemEffect item) : base(data, item)
{
_topSpeed = definition.PerformanceStat(1, new PerformanceStat());
RegisterPerformanceStat("TopSpeed", _topSpeed);
Limit = Evaluate(_topSpeed);
_data = data;
Limit = Evaluate(_data.TopSpeed);
}
public override bool Execute(float dt)
{
Limit = Evaluate(_topSpeed);
var velocity = Entity.CultVelocity;
if (length(velocity) > Limit)
Entity.CultVelocity = normalize(velocity) * Limit;
Limit = Evaluate(_data.TopSpeed);
if (length(Entity.Velocity) > Limit)
Entity.Velocity = normalize(Entity.Velocity) * Limit;
return true;
}
public void RestoreRuntimeState(float limit)
{
Limit = limit;
}
}
}

View file

@ -1,30 +1,47 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class VisibilityData : BehaviorData
{
[Inspectable, JsonProperty("visibility"), Key(1), RuntimeInspectable]
public PerformanceStat Visibility = new PerformanceStat();
[Inspectable, JsonProperty("visibilityDecay"), Key(2)]
public PerformanceStat VisibilityDecay = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new Visibility(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Visibility(this, item);
}
}
public class Visibility : Behavior
{
private readonly PerformanceStat _visibility;
private VisibilityData _data;
public Visibility(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Visibility(VisibilityData data, EquippedItem item) : base(data, item)
{
_visibility = definition.PerformanceStat(1, new PerformanceStat());
RegisterPerformanceStat(nameof(Visibility), _visibility);
RegisterPerformanceStat("VisibilityDecay", definition.PerformanceStat(2, new PerformanceStat()));
_data = data;
}
public Visibility(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Visibility(VisibilityData data, ConsumableItemEffect item) : base(data, item)
{
_visibility = definition.PerformanceStat(1, new PerformanceStat());
RegisterPerformanceStat(nameof(Visibility), _visibility);
RegisterPerformanceStat("VisibilityDecay", definition.PerformanceStat(2, new PerformanceStat()));
_data = data;
}
public override bool Execute(float dt)
{
Entity.VisibilitySources[this] = Evaluate(_visibility);
Entity.VisibilitySources[this] = Evaluate(_data.Visibility);
return true;
}
}
}

View file

@ -2,43 +2,80 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Linq;
using static CultMath.math;
using float4 = CultMath.float4;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable,
Union(0, typeof(InstantWeaponData)),
Union(1, typeof(LauncherData)),
Union(2, typeof(ConstantWeaponData)),
Union(3, typeof(ChargedWeaponData)),
RuntimeInspectable]
public abstract class WeaponData : BehaviorData
{
[Inspectable, JsonProperty("damageType"), Key(1), RuntimeInspectable]
public DamageType DamageType;
[Inspectable, JsonProperty("damage"), Key(2), RuntimeInspectable]
public PerformanceStat Damage = new PerformanceStat();
[InspectableRangedFloat(0,1), JsonProperty("penetration"), Key(3), RuntimeInspectable]
public PerformanceStat Penetration = new PerformanceStat();
[InspectableRangedFloat(0,1), JsonProperty("damageSpread"), Key(4)]
public PerformanceStat DamageSpread = new PerformanceStat();
[Inspectable, JsonProperty("minRange"), Key(5)]
public PerformanceStat MinRange = new PerformanceStat();
[Inspectable, JsonProperty("range"), Key(6)]
public PerformanceStat Range = new PerformanceStat();
[InspectableAnimationCurve, JsonProperty("damageCurve"), Key(7)]
public BezierCurve DamageCurve;
[InspectablePrefab, JsonProperty("effect"), Key(8)]
public string EffectPrefab;
[InspectablePrefab, JsonProperty("energy"), Key(9), RuntimeInspectable]
public PerformanceStat Energy = new PerformanceStat();
[InspectablePrefab, JsonProperty("heat"), Key(10), RuntimeInspectable]
public PerformanceStat Heat = new PerformanceStat();
[InspectablePrefab, JsonProperty("visibility"), Key(11), RuntimeInspectable]
public PerformanceStat Visibility = new PerformanceStat();
[InspectableDatabaseLink(typeof(SimpleCommodityData)), JsonProperty("ammo"), Key(12), RuntimeInspectable]
public Guid AmmoType;
[InspectablePrefab, JsonProperty("magSize"), Key(13)]
public int MagazineSize;
[InspectablePrefab, JsonProperty("reloadTime"), Key(14)]
public float ReloadTime = 1;
[InspectablePrefab, JsonProperty("spread"), Key(15)]
public PerformanceStat Spread = new PerformanceStat();
[Inspectable, JsonProperty("velocity"), Key(16)]
public PerformanceStat Velocity = new PerformanceStat();
}
public abstract class Weapon : Behavior, IActivatedBehavior
{
private readonly PerformanceStat _damage;
private readonly PerformanceStat _penetration;
private readonly PerformanceStat _damageSpread;
private readonly PerformanceStat _minRange;
private readonly PerformanceStat _range;
private readonly PerformanceStat _energy;
private readonly PerformanceStat _heat;
private readonly PerformanceStat _visibility;
private readonly PerformanceStat _spread;
private readonly PerformanceStat _velocity;
private PerformanceStat _guidedProjectileThrust;
private PerformanceStat _guidedProjectileVelocity;
private WeaponData _data;
public abstract float DamagePerSecond { get; }
public abstract float RangeDamagePerSecond(float range);
public abstract int Ammo { get; }
public DamageType DamageType { get; }
public string EffectPrefab { get; }
public string AmmoItemKey { get; }
public int MagazineSize { get; }
protected float ReloadTime { get; }
protected BezierCurve DamageCurve { get; }
public bool UsesAmmo => !string.IsNullOrWhiteSpace(AmmoItemKey);
public GuidedProjectileTargetMode GuidedProjectileTargeting { get; private set; }
public bool HasGuidedProjectileProfile => GuidedProjectileTargeting != GuidedProjectileTargetMode.None;
public float4[] GuidedProjectileGuidanceCurve { get; private set; }
public float4[] GuidedProjectileLiftCurve { get; private set; }
public float4[] GuidedProjectileThrustCurve { get; private set; }
public float GuidedProjectileDodgeFrequency { get; private set; }
public WeaponData WeaponData => _data;
public float Damage { get; protected set; }
public float Penetration { get; protected set; }
public float DamageSpread { get; protected set; }
@ -56,123 +93,29 @@ public abstract class Weapon : Behavior, IActivatedBehavior
{
get => _firing;
}
public Weapon(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Weapon(WeaponData data, EquippedItem item) : base(data, item)
{
_damage = definition.PerformanceStat(2, new PerformanceStat());
_penetration = definition.PerformanceStat(3, new PerformanceStat());
_damageSpread = definition.PerformanceStat(4, new PerformanceStat());
_minRange = definition.PerformanceStat(5, new PerformanceStat());
_range = definition.PerformanceStat(6, new PerformanceStat());
_energy = definition.PerformanceStat(9, new PerformanceStat());
_heat = definition.PerformanceStat(10, new PerformanceStat());
_visibility = definition.PerformanceStat(11, new PerformanceStat());
_spread = definition.PerformanceStat(15, new PerformanceStat());
_velocity = definition.PerformanceStat(16, new PerformanceStat());
DamageType = definition.Enum(1, default(DamageType));
DamageCurve = definition.BezierCurve(7, null);
EffectPrefab = definition.String(8);
AmmoItemKey = definition.ItemKey(12);
MagazineSize = definition.Int(13);
ReloadTime = definition.Float(14, 1);
RegisterWeaponStats();
InitializeGuidedProjectileProfile(definition);
_data = data;
}
public Weapon(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Weapon(WeaponData data, ConsumableItemEffect item) : base(data, item)
{
_damage = definition.PerformanceStat(2, new PerformanceStat());
_penetration = definition.PerformanceStat(3, new PerformanceStat());
_damageSpread = definition.PerformanceStat(4, new PerformanceStat());
_minRange = definition.PerformanceStat(5, new PerformanceStat());
_range = definition.PerformanceStat(6, new PerformanceStat());
_energy = definition.PerformanceStat(9, new PerformanceStat());
_heat = definition.PerformanceStat(10, new PerformanceStat());
_visibility = definition.PerformanceStat(11, new PerformanceStat());
_spread = definition.PerformanceStat(15, new PerformanceStat());
_velocity = definition.PerformanceStat(16, new PerformanceStat());
DamageType = definition.Enum(1, default(DamageType));
DamageCurve = definition.BezierCurve(7, null);
EffectPrefab = definition.String(8);
AmmoItemKey = definition.ItemKey(12);
MagazineSize = definition.Int(13);
ReloadTime = definition.Float(14, 1);
RegisterWeaponStats();
InitializeGuidedProjectileProfile(definition);
}
private void RegisterWeaponStats()
{
RegisterPerformanceStat(nameof(Damage), _damage);
RegisterPerformanceStat(nameof(Penetration), _penetration);
RegisterPerformanceStat(nameof(DamageSpread), _damageSpread);
RegisterPerformanceStat(nameof(MinRange), _minRange);
RegisterPerformanceStat(nameof(Range), _range);
RegisterPerformanceStat(nameof(Energy), _energy);
RegisterPerformanceStat(nameof(Heat), _heat);
RegisterPerformanceStat(nameof(Visibility), _visibility);
RegisterPerformanceStat(nameof(Spread), _spread);
RegisterPerformanceStat(nameof(Velocity), _velocity);
}
private void InitializeGuidedProjectileProfile(RuntimeBehaviorDefinition definition)
{
if (string.Equals(definition.Kind, "Launcher"))
{
GuidedProjectileTargeting = GuidedProjectileTargetMode.TargetEntity;
GuidedProjectileGuidanceCurve = definition.Float4Array(26, null);
GuidedProjectileThrustCurve = definition.Float4Array(27, null);
GuidedProjectileLiftCurve = definition.Float4Array(28, null);
_guidedProjectileThrust = definition.PerformanceStat(29, new PerformanceStat());
GuidedProjectileDodgeFrequency = definition.Float(30);
_guidedProjectileVelocity = definition.PerformanceStat(31, new PerformanceStat());
}
else if (string.Equals(definition.Kind, "GuidedWeapon"))
{
GuidedProjectileTargeting = GuidedProjectileTargetMode.LookDirection;
GuidedProjectileGuidanceCurve = definition.Float4Array(21, null);
GuidedProjectileThrustCurve = definition.Float4Array(22, null);
GuidedProjectileLiftCurve = definition.Float4Array(23, null);
_guidedProjectileThrust = definition.PerformanceStat(24, new PerformanceStat());
GuidedProjectileDodgeFrequency = definition.Float(25);
_guidedProjectileVelocity = definition.PerformanceStat(26, new PerformanceStat());
}
RegisterPerformanceStat("Thrust", _guidedProjectileThrust);
RegisterPerformanceStat("MissileVelocity", _guidedProjectileVelocity);
_data = data;
}
protected virtual void UpdateStats()
{
Damage = Evaluate(_damage);
Penetration = Evaluate(_penetration);
DamageSpread = Evaluate(_damageSpread);
MinRange = Evaluate(_minRange);
Range = Evaluate(_range);
Energy = Evaluate(_energy);
Heat = Evaluate(_heat);
Visibility = Evaluate(_visibility);
Spread = Evaluate(_spread);
Velocity = Evaluate(_velocity);
}
protected float EvaluateRangeDamage(float range)
{
var normalizedRange = saturate(unlerp(MinRange, Range, range));
return Evaluate(_damage, StatConditionMask.Range, normalizedRange) *
DamageCurve.Evaluate(normalizedRange);
}
protected float EvaluateRangeDamage(float range, StatConditionMask condition, float value)
{
var normalizedRange = saturate(unlerp(MinRange, Range, range));
return Evaluate(_damage, StatConditionMask.Range, normalizedRange, condition, value) *
DamageCurve.Evaluate(normalizedRange);
}
protected float EvaluateDamage(StatConditionMask condition, float value)
{
return Evaluate(_damage, condition, value);
Damage = Evaluate(_data.Damage);
Penetration = Evaluate(_data.Penetration);
DamageSpread = Evaluate(_data.DamageSpread);
MinRange = Evaluate(_data.MinRange);
Range = Evaluate(_data.Range);
Energy = Evaluate(_data.Energy);
Heat = Evaluate(_data.Heat);
Visibility = Evaluate(_data.Visibility);
Spread = Evaluate(_data.Spread);
Velocity = Evaluate(_data.Velocity);
}
public override bool Execute(float dt)
@ -190,36 +133,4 @@ public abstract class Weapon : Behavior, IActivatedBehavior
{
_firing = false;
}
public virtual void RestoreRuntimeState(bool firing)
{
_firing = firing;
}
public float EvaluateRange()
{
return Evaluate(_range);
}
public float EvaluateVelocity()
{
return Evaluate(_velocity);
}
public float EvaluateGuidedProjectileThrust()
{
return _guidedProjectileThrust == null ? 0 : Evaluate(_guidedProjectileThrust);
}
public float EvaluateGuidedProjectileVelocity()
{
return _guidedProjectileVelocity == null ? 0 : Evaluate(_guidedProjectileVelocity);
}
}
public enum GuidedProjectileTargetMode
{
None,
TargetEntity,
LookDirection
}

View file

@ -2,23 +2,44 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), Order(1000), RuntimeInspectable]
public class WearData : BehaviorData
{
[InspectableTemperature, JsonProperty("perSecond"), Key(1)]
public bool PerSecond = true;
public override Behavior CreateInstance(EquippedItem item)
{
return new Wear(this, item);
}
public override Behavior CreateInstance(ConsumableItemEffect item)
{
return new Wear(this, item);
}
}
public class Wear : Behavior
{
private readonly bool _perSecond;
private WearData _data;
public Wear(RuntimeBehaviorDefinition definition, EquippedItem item) : base(definition, item)
public Wear(WearData data, EquippedItem item) : base(data, item)
{
_perSecond = definition.Bool(1, true);
_data = data;
}
public Wear(RuntimeBehaviorDefinition definition, ConsumableItemEffect item) : base(definition, item)
public Wear(WearData data, ConsumableItemEffect item) : base(data, item)
{
_perSecond = definition.Bool(1, true);
_data = data;
}
public override bool Execute(float dt)
{
CauseWearDamage(_perSecond ? dt : 1);
CauseWearDamage(_data.PerSecond ? dt : 1);
return true;
}
}
}

View file

@ -1,29 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using CultMath;
using static CultMath.math;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class BezierCurve
{
public float4[] Keys;
private int2 _cachedIndices;
private const int STEPS = 64;
private float? _maximum;
public static BezierCurve FromKeys(IEnumerable<(float time, float value, float inTangent, float outTangent)> keys)
{
return new BezierCurve
{
Keys = keys
.Select(key => float4(key.time, key.value, key.inTangent, key.outTangent))
.ToArray()
};
}
[JsonProperty("keys"), Key(0)] public float4[] Keys;
[IgnoreMember] private int2 _cachedIndices;
[IgnoreMember] private const int STEPS = 64;
[IgnoreMember] private float? _maximum;
[IgnoreMember]
public float Maximum
{
get
@ -45,7 +38,7 @@ public class BezierCurve
return _maximum??0;
}
}
// Integrate area under curve between start and end time
public float IntegrateCurve(float startTime, float endTime, int steps)
{
@ -68,26 +61,26 @@ public class BezierCurve
// {
// return 1 - (1 - a)*(1 - b);
// }
public float Evaluate(float time)
{
// Clamp time
time = clamp(time, Keys[0].x, Keys[Keys.Length - 1].x);
FindSurroundingKeyframes(time, Keys);
FindSurroundingKeyframes(time, Keys);
return HermiteInterpolate(time, Keys[_cachedIndices.x], Keys[_cachedIndices.y]);
}
void FindSurroundingKeyframes(float time, float4[] curve)
{
// Check that time is within cached keyframe time
if (time >= curve[_cachedIndices.x].x &&
if (time >= curve[_cachedIndices.x].x &&
time <= curve[_cachedIndices.y].x)
{
return;
}
// Fall back to using dichotomic search.
var length = curve.Length;
int half;
@ -155,4 +148,4 @@ public class BezierCurve
return t * (t * (a * t + b) + c) + d;
}
}
}

View file

@ -2,14 +2,15 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using static CultMath.math;
using cfloat3 = CultMath.float3;
using cfloat4 = CultMath.float4;
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using static Unity.Mathematics.math;
// Thanks to Ian Taylor at https://www.chilliant.com/rgb2hsv.html
public static class ColorMath
{
public static cfloat3 HueToRgb(in float h)
public static float3 HueToRgb(in float h)
{
float r = abs(h * 6 - 3) - 1;
float g = 2 - abs(h * 6 - 2);
@ -17,40 +18,40 @@ public static class ColorMath
return saturate(float3(r,g,b));
}
public static cfloat3 HsvToRgb(in cfloat3 hsv)
public static float3 HsvToRgb(in float3 hsv)
{
cfloat3 rgb = HueToRgb(hsv.x);
float3 rgb = HueToRgb(hsv.x);
return ((rgb - 1) * hsv.y + 1) * hsv.z;
}
public static cfloat3 HslToRgb(in cfloat3 hsl)
public static float3 HslToRgb(in float3 hsl)
{
cfloat3 rgb = HueToRgb(hsl.x);
float3 rgb = HueToRgb(hsl.x);
float c = (1 - abs(2 * hsl.z - 1)) * hsl.y;
return (rgb - 0.5f) * c + hsl.z;
}
const float Epsilon = 1e-10f;
public static cfloat3 RgbToHcv(in cfloat3 rgb)
public static float3 RgbToHcv(in float3 rgb)
{
// Based on work by Sam Hocevar and Emil Persson
cfloat4 p = (rgb.y < rgb.z) ? float4(rgb.zy, -1.0f, 2.0f/3.0f) : float4(rgb.zy, 0.0f, -1.0f/3.0f);
cfloat4 q = (rgb.x < p.x) ? float4(p.xyw, rgb.x) : float4(rgb.x, p.yzx);
float4 p = (rgb.y < rgb.z) ? float4(rgb.zy, -1.0f, 2.0f/3.0f) : float4(rgb.zy, 0.0f, -1.0f/3.0f);
float4 q = (rgb.x < p.x) ? float4(p.xyw, rgb.x) : float4(rgb.x, p.yzx);
float c = q.x - min(q.w, q.y);
float h = abs((q.w - q.y) / (6 * c + Epsilon) + q.z);
return float3(h, c, q.x);
}
public static cfloat3 RgbToHsv(in cfloat3 rgb)
public static float3 RgbToHsv(in float3 rgb)
{
cfloat3 hcv = RgbToHcv(rgb);
float3 hcv = RgbToHcv(rgb);
float s = hcv.y / (hcv.z + Epsilon);
return float3(hcv.x, s, hcv.z);
}
public static cfloat3 RgbToHsl(in cfloat3 rgb)
public static float3 RgbToHsl(in float3 rgb)
{
cfloat3 hcv = RgbToHcv(rgb);
float3 hcv = RgbToHcv(rgb);
float l = hcv.z - hcv.y * 0.5f;
float s = hcv.y / (1 - abs(l * 2 - 1) + Epsilon);
return float3(hcv.x, s, l);

View file

@ -1,62 +1,79 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
using float3 = CultMath.float3;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
public class Faction : INamedEntry
[RethinkTable("Galaxy"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class Faction : DatabaseEntry, INamedEntry
{
public string FactionKey;
[Inspectable, JsonProperty("name"), Key(1)]
public string Name;
[Inspectable, JsonProperty("shortName"), Key(2)]
public string ShortName;
[InspectableText, JsonProperty("description"), Key(3)]
public string Description;
[InspectableTexture, JsonProperty("logo"), Key(4)]
public string Logo;
[InspectableDatabaseLink(typeof(PersonalityAttribute)), JsonProperty("personality"), Key(5)]
public Dictionary<Guid, float> Personality = new Dictionary<Guid, float>();
// [Inspectable, JsonProperty("hostile"), Key(6)]
// public bool PlayerHostile;
[InspectableColor, JsonProperty("primaryColor"), Key(7)]
public float3 PrimaryColor;
[InspectableColor, JsonProperty("secondaryColor"), Key(8)]
public float3 SecondaryColor;
public string GeonameFileKey;
public string BossHullItemKey;
[InspectableDatabaseLink(typeof(NameFile)), JsonProperty("nameFile"), Key(9)]
public Guid GeonameFile;
[InspectableDatabaseLink(typeof(HullData)), JsonProperty("bossHull"), Key(10)]
public Guid BossHull;
[Inspectable, JsonProperty("influence"), Key(11)]
public int InfluenceDistance = 4;
[InspectableDatabaseLink(typeof(Faction)), RangedFloat(0, 1), JsonProperty("allegiance"), Key(12)]
public Dictionary<Guid, float> Allegiance = new Dictionary<Guid, float>();
public Dictionary<string, float> AllegianceByKey = new Dictionary<string, float>();
[InspectableSoundBank, JsonProperty("overworldMusic"), Key(13)]
public uint OverworldMusic;
[InspectableSoundBank, JsonProperty("combatMusic"), Key(14)]
public uint CombatMusic;
[InspectableSoundBank, JsonProperty("bossMusic"), Key(15)]
public uint BossMusic;
[IgnoreMember] public string EntryName
{
get => Name;
set => Name = value;
}
}
[Inspectable, MessagePackObject]
public class NameFile : DatabaseEntry, INamedEntry
{
[Key(1)] public string Name;
[Key(2)] public string[] Names;
[IgnoreMember]
public string EntryName
{
get => Name;
set => Name = value;
}
public bool HasSameKey(Faction other)
{
return other != null &&
!string.IsNullOrWhiteSpace(FactionKey) &&
string.Equals(FactionKey, other.FactionKey, StringComparison.OrdinalIgnoreCase);
}
public override int GetHashCode()
{
return StringComparer.OrdinalIgnoreCase.GetHashCode(FactionKey ?? "");
}
public override bool Equals(object obj)
{
return obj is Faction faction && HasSameKey(faction);
}
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 49ec0c83548c7084ab0d3f6c2175ee71
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,146 @@
using System;
[AttributeUsage(AttributeTargets.Class)]
public class GlobalSettingsAttribute : Attribute { }
// [AttributeUsage(AttributeTargets.Class)]
// public class ExternalEntryAttribute : Attribute { }
[AttributeUsage(AttributeTargets.All, Inherited = false)]
public class InspectableAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Field)]
public abstract class PreferredInspectorAttribute : InspectableAttribute { }
public class InspectableTextAttribute : PreferredInspectorAttribute { }
public class InspectablePrefabAttribute : PreferredInspectorAttribute { }
public class InspectableTextureAttribute : PreferredInspectorAttribute { }
public class InspectableTextAssetAttribute : PreferredInspectorAttribute { }
public class InspectableTemperatureAttribute : PreferredInspectorAttribute { }
public class InspectableAnimationCurveAttribute : PreferredInspectorAttribute { }
public class InspectableColorAttribute : PreferredInspectorAttribute { }
public class InspectableSoundBankAttribute : PreferredInspectorAttribute { }
public class InspectableAudioParameterAttribute : PreferredInspectorAttribute { }
public class InspectableSchematicShapeAttribute : PreferredInspectorAttribute { }
public class InspectableEnumValuesAttribute : PreferredInspectorAttribute
{
public Type EnumType;
public InspectableEnumValuesAttribute(Type enumType)
{
EnumType = enumType;
}
}
public class InspectableDatabaseLinkAttribute : PreferredInspectorAttribute
{
public readonly Type EntryType;
public InspectableDatabaseLinkAttribute(Type entryType)
{
EntryType = entryType;
}
}
public class InspectableRangedFloatAttribute : PreferredInspectorAttribute
{
public readonly float Min, Max;
public InspectableRangedFloatAttribute(float min, float max)
{
Min = min;
Max = max;
}
}
public class InspectableRangedIntAttribute : PreferredInspectorAttribute
{
public readonly int Min, Max;
public InspectableRangedIntAttribute(int min, int max)
{
Min = min;
Max = max;
}
}
public class InspectableTypeAttribute : PreferredInspectorAttribute
{
public readonly Type Type;
public InspectableTypeAttribute(Type type)
{
Type = type;
}
}
[AttributeUsage(AttributeTargets.Field)]
public class RangedFloatAttribute : Attribute
{
public readonly float Min, Max;
public RangedFloatAttribute(float min, float max)
{
Min = min;
Max = max;
}
}
/// <summary>
/// <para>Specify a tooltip for a field in the Inspector window.</para>
/// </summary>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class TooltipAttribute : Attribute
{
/// <summary>
/// <para>The tooltip text.</para>
/// </summary>
public readonly string tooltip;
/// <summary>
/// <para>Specify a tooltip for a field.</para>
/// </summary>
/// <param name="tooltip">The tooltip text.</param>
public TooltipAttribute(string tooltip) => this.tooltip = tooltip;
}
[AttributeUsage(AttributeTargets.Class)]
public class RethinkTableAttribute : Attribute
{
public string TableName;
public RethinkTableAttribute(string tableName)
{
TableName = tableName;
}
}
public class NameAttribute : Attribute
{
public string Name;
public NameAttribute(string name)
{
Name = name;
}
}
public class OrderAttribute : Attribute
{
public int Order;
public OrderAttribute(int order)
{
Order = order;
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = true)]
public class InspectorHeaderAttribute : Attribute
{
public readonly string header;
public InspectorHeaderAttribute(string header) => this.header = header;
}

View file

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

View file

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
public static class CollectionExtensions
{
// https://stackoverflow.com/a/800469
public static string GetHashSHA1(this byte[] data)
{
using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
{
return string.Concat(sha1.ComputeHash(data).Select(x => x.ToString("X2")));
}
}
// https://stackoverflow.com/a/3188835
public static T MaxBy<T, U>(this IEnumerable<T> items, Func<T, U> selector)
{
if (!items.Any())
{
throw new InvalidOperationException("Empty input sequence");
}
var comparer = Comparer<U>.Default;
T maxItem = items.First();
U maxValue = selector(maxItem);
foreach (T item in items.Skip(1))
{
// Get the value of the item and compare it to the current max.
U value = selector(item);
if (comparer.Compare(value, maxValue) > 0)
{
maxValue = value;
maxItem = item;
}
}
return maxItem;
}
public static T MinBy<T, U>(this IEnumerable<T> items, Func<T, U> selector)
{
if (!items.Any())
{
throw new InvalidOperationException("Empty input sequence");
}
var comparer = Comparer<U>.Default;
T maxItem = items.First();
U maxValue = selector(maxItem);
foreach (T item in items.Skip(1))
{
// Get the value of the item and compare it to the current max.
U value = selector(item);
if (comparer.Compare(value, maxValue) < 0)
{
maxValue = value;
maxItem = item;
}
}
return maxItem;
}
}
public static class AsyncAwaitExtensions
{
public static async void WrapAwait(this Task task)
{
await task;
}
}

View file

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

View file

@ -0,0 +1,574 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using MessagePack;
using Newtonsoft.Json;
using RethinkDb.Driver;
using RethinkDb.Driver.Net;
using UniRx;
public class CultCache
{
private readonly object addLock = new object();
//public Action<string> Logger = Console.WriteLine;
//private string _filePath;
public event Action<DatabaseEntry, DatabaseEntry> OnUpdate;
private List<CacheBackingStore> _backingStores = new List<CacheBackingStore>();
private readonly Dictionary<Type, CacheBackingStore> _typeStores = new Dictionary<Type, CacheBackingStore>();
private readonly Dictionary<CacheBackingStore, Type[]> _storeTypes = new Dictionary<CacheBackingStore, Type[]>();
private readonly Dictionary<Guid, DatabaseEntry> _entries = new Dictionary<Guid, DatabaseEntry>();
private readonly Dictionary<Type, DatabaseEntry> _globals = new Dictionary<Type, DatabaseEntry>();
private readonly Dictionary<Type, HashSet<DatabaseEntry>> _types = new Dictionary<Type, HashSet<DatabaseEntry>>();
// private readonly Dictionary<Type, (DirectoryInfo directory, List<Guid> entries)> _externalTypes = new Dictionary<Type, (DirectoryInfo directory, List<Guid> entries)>();
// private class ExternalEntry
// {
// public string FilePath;
// public DatabaseEntry Entry;
//
// public ExternalEntry(string filePath, DatabaseEntry entry)
// {
// FilePath = filePath;
// Entry = entry;
// }
// }
// private readonly Dictionary<Guid, ExternalEntry> _externalEntries = new Dictionary<Guid, ExternalEntry>();
public IEnumerable<DatabaseEntry> AllEntries => _entries.Values;
public CultCache()
{
DatabaseLinkBase.Cache = this;
foreach (var type in typeof(DatabaseEntry).GetAllChildClasses())
{
_types[type] = new HashSet<DatabaseEntry>();
if (type.GetCustomAttribute<GlobalSettingsAttribute>() != null)
{
_globals[type] = null;
Add(Activator.CreateInstance(type) as DatabaseEntry);
}
}
}
public void AddBackingStore(CacheBackingStore store, params Type[] domain)
{
if (domain.Length > 0)
{
_storeTypes[store] = domain;
foreach (var t in domain) _typeStores[t] = store;
}
else
{
foreach(var existingStore in _backingStores) store.SubscribeTo(existingStore);
_backingStores.Add(store);
}
store.EntryAdded.Subscribe(entry =>
{
Add(entry, store);
OnUpdate?.Invoke(null, entry);
});
store.EntryUpdated.Subscribe(entry =>
{
Add(entry, store);
OnUpdate?.Invoke(entry, entry);
});
store.EntryDeleted.Subscribe(entry =>
{
Remove(entry, store);
OnUpdate?.Invoke(entry, null);
});
}
public void PullAllBackingStores()
{
foreach(var store in _backingStores) store.PullAll();
foreach(var store in _storeTypes.Keys) store.PullAll();
}
public void Add(DatabaseEntry entry, CacheBackingStore source = null)
{
lock(addLock)
{
if (entry != null)
{
var exists = _entries.ContainsKey(entry.ID);
var type = entry.GetType();
if (_globals.ContainsKey(type))
{
if(_globals[type]!=null)
{
Remove(_globals[type]);
exists = true;
}
_globals[type] = entry;
}
if(_typeStores.ContainsKey(type))
_typeStores[type].Push(entry);
else
{
var masterStore = _backingStores.First();
if(masterStore!=source)
masterStore.Push(entry);
}
_entries[entry.ID] = entry;
_types[type].Add(entry);
foreach (var parentType in type.GetParentTypes())
{
if(_types.ContainsKey(parentType))
_types[parentType].Add(entry);
}
}
}
}
public bool IsGlobal(DatabaseEntry entry) => _globals.ContainsKey(entry.GetType());
public void AddAll(IEnumerable<DatabaseEntry> entries)
{
foreach (var entry in entries)
{
Add(entry);
}
}
public DatabaseEntry Get(Guid guid)
{
DatabaseEntry entry;
_entries.TryGetValue(guid, out entry);
return entry;
}
public T Get<T>(Guid guid) where T : DatabaseEntry
{
return Get(guid) as T;
}
public DatabaseEntry GetGlobal(Type type)
{
if (_globals.ContainsKey(type)) return _globals[type];
return null;
}
public T GetGlobal<T>() where T : DatabaseEntry
{
return GetGlobal(typeof(T)) as T;
}
public IEnumerable<DatabaseEntry> GetAll(Type type)
{
return !_types.ContainsKey(type) ? Enumerable.Empty<DatabaseEntry>() : _types[type];
}
public IEnumerable<T> GetAll<T>() where T : DatabaseEntry
{
var type = typeof(T);
return !_types.ContainsKey(type) ? Enumerable.Empty<T>() : _types[type].Cast<T>();
}
public void Remove(DatabaseEntry entry, CacheBackingStore source = null)
{
_entries.Remove(entry.ID);
var type = entry.GetType();
if(_typeStores.ContainsKey(type))
_typeStores[type].Delete(entry);
else foreach(var store in _backingStores)
{
if(store != source)
store.Delete(entry);
}
foreach (var parentType in type.GetParentTypes())
{
if(_types.ContainsKey(parentType))
_types[parentType].Remove(entry);
}
}
}
public interface RealtimeBackingStore
{
public void ObserveChanges();
}
public abstract class CacheBackingStore
{
protected CacheBackingStore()
{
EntryAdded = new Subject<DatabaseEntry>();
EntryDeleted = new Subject<DatabaseEntry>();
EntryUpdated = new Subject<DatabaseEntry>();
}
public abstract void PullAll();
public abstract void Push(DatabaseEntry entry);
public abstract void Delete(DatabaseEntry entry);
public abstract void PushAll(bool soft = false);
public Subject<DatabaseEntry> EntryAdded { get; }
public Subject<DatabaseEntry> EntryDeleted { get; }
public Subject<DatabaseEntry> EntryUpdated { get; }
protected Dictionary<Guid, DatabaseEntry> Entries = new Dictionary<Guid, DatabaseEntry>();
public void SubscribeTo(CacheBackingStore targetStore)
{
targetStore.EntryAdded.Subscribe(Push);
targetStore.EntryDeleted.Subscribe(Delete);
targetStore.EntryUpdated.Subscribe(Push);
}
}
public abstract class MultiFileBackingStore : CacheBackingStore, RealtimeBackingStore
{
public DirectoryInfo DirectoryInfo { get; }
protected Dictionary<Type, DirectoryInfo> _entryTypeDirectories = new Dictionary<Type, DirectoryInfo>();
public abstract byte[] Serialize(DatabaseEntry entry);
public abstract DatabaseEntry Deserialize(byte[] data);
public abstract string Extension { get; }
public MultiFileBackingStore(string path)
{
DirectoryInfo = new DirectoryInfo(path);
foreach (var type in typeof(DatabaseEntry).GetAllChildClasses())
{
_entryTypeDirectories[type] = DirectoryInfo.CreateSubdirectory(type.Name);
}
}
public override void PullAll()
{
if (!DirectoryInfo.Exists) return;
foreach (var directory in _entryTypeDirectories.Values)
{
foreach (var file in directory.EnumerateFiles($"*.{Extension}"))
{
var entry = Deserialize(File.ReadAllBytes(file.FullName));
Entries[entry.ID] = entry;
EntryAdded.OnNext(entry);
}
}
}
private string GetFileName(DatabaseEntry entry) =>
$"{(entry is INamedEntry namedEntry ? namedEntry.EntryName : entry.ID.ToString())}.{Extension}";
public override void Push(DatabaseEntry entry)
{
var type = entry.GetType();
Entries[entry.ID] = entry;
var directory = _entryTypeDirectories[type];
File.WriteAllBytes(Path.Combine(directory.FullName, GetFileName(entry)), Serialize(entry));
}
public override void Delete(DatabaseEntry entry)
{
if(Entries.ContainsKey(entry.ID))
{
var type = entry.GetType();
Entries.Remove(entry.ID);
var directory = _entryTypeDirectories[type];
var file = new FileInfo(Path.Combine(directory.FullName, GetFileName(entry)));
if (file.Exists)
file.Delete();
}
}
public override void PushAll(bool soft = false)
{
foreach(var entry in Entries.Values.ToArray()) Push(entry);
}
public void ObserveChanges()
{
foreach (var directory in _entryTypeDirectories.Values)
{
var watcher = new FileSystemWatcher(directory.FullName);
watcher.Changed += (sender, args) =>
{
var entry = Deserialize(File.ReadAllBytes(args.FullPath));
Entries[entry.ID] = entry;
EntryUpdated.OnNext(entry);
};
watcher.Created += (sender, args) =>
{
var entry = Deserialize(File.ReadAllBytes(args.FullPath));
Entries[entry.ID] = entry;
EntryAdded.OnNext(entry);
};
watcher.Deleted += (sender, args) =>
{
var entry = Deserialize(File.ReadAllBytes(args.FullPath));
Entries[entry.ID] = entry;
EntryDeleted.OnNext(entry);
};
}
}
}
public class MultiFileJsonBackingStore : MultiFileBackingStore
{
public MultiFileJsonBackingStore(string path) : base(path)
{
RegisterResolver.Register();
}
public override byte[] Serialize(DatabaseEntry entry)
{
return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(entry));
}
public override DatabaseEntry Deserialize(byte[] data)
{
return JsonConvert.DeserializeObject<DatabaseEntry>(Encoding.UTF8.GetString(data));
}
public override string Extension => "json";
}
public class MultiFileMessagePackBackingStore : MultiFileBackingStore
{
public MultiFileMessagePackBackingStore(string path) : base(path)
{
RegisterResolver.Register();
}
public override byte[] Serialize(DatabaseEntry entry)
{
return MessagePackSerializer.Serialize(entry);
}
public override DatabaseEntry Deserialize(byte[] data)
{
return MessagePackSerializer.Deserialize<DatabaseEntry>(data);
}
public override string Extension => "msgpack";
}
public abstract class SingleFileBackingStore : CacheBackingStore
{
public FileInfo FileInfo { get; }
public abstract byte[] Serialize(DatabaseEntry[] entries);
public abstract DatabaseEntry[] Deserialize(byte[] data);
public SingleFileBackingStore(string filePath)
{
FileInfo = new FileInfo(filePath);
}
public override void PullAll()
{
if (!FileInfo.Exists) return;
foreach (var entry in Deserialize(File.ReadAllBytes(FileInfo.FullName)))
{
Entries[entry.ID] = entry;
EntryAdded.OnNext(entry);
}
}
public override void Push(DatabaseEntry entry)
{
var type = entry.GetType();
Entries[entry.ID] = entry;
PushAll();
}
public override void Delete(DatabaseEntry entry)
{
if(Entries.ContainsKey(entry.ID))
{
Entries.Remove(entry.ID);
PushAll();
}
}
public override void PushAll(bool soft = false)
{
var entriesArray = Entries.Values.ToArray();
File.WriteAllBytes(FileInfo.FullName, Serialize(entriesArray));
}
}
public class SingleFileMessagePackBackingStore : SingleFileBackingStore
{
public SingleFileMessagePackBackingStore(string filePath) : base(filePath)
{
RegisterResolver.Register();
}
public override byte[] Serialize(DatabaseEntry[] entries)
{
return MessagePackSerializer.Serialize(entries);
}
public override DatabaseEntry[] Deserialize(byte[] data)
{
return MessagePackSerializer.Deserialize<DatabaseEntry[]>(data);
}
}
public class SingleFileJsonBackingStore : SingleFileBackingStore
{
public SingleFileJsonBackingStore(string filePath) : base(filePath)
{
RegisterResolver.Register();
}
public override byte[] Serialize(DatabaseEntry[] entries)
{
return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(entries));
}
public override DatabaseEntry[] Deserialize(byte[] data)
{
return JsonConvert.DeserializeObject<DatabaseEntry[]>(Encoding.UTF8.GetString(data));
}
}
public class RethinkBackingStore : CacheBackingStore, RealtimeBackingStore
{
public const string DEFAULT_TABLE = "Default";
public static RethinkDB R = RethinkDB.R;
public string DatabaseName { get; }
public string ConnectionString { get; }
private string[] _syncTables;
private Connection _connection;
private Dictionary<DatabaseEntry, string> _entryHashes = new Dictionary<DatabaseEntry, string>();
public void ObserveChanges()
{
foreach (var table in _syncTables)
{
// Subscribe to changes from RethinkDB
Task.Run(async () =>
{
var result = await R
.Db(DatabaseName)
.Table(table)
.Changes()
.RunChangesAsync<DatabaseEntry>(_connection);
while (await result.MoveNextAsync())
{
var change = result.Current;
if(change.NewValue==null)
EntryDeleted.OnNext(change.OldValue);
else if(change.OldValue==null)
EntryAdded.OnNext(change.NewValue);
else EntryUpdated.OnNext(change.NewValue);
}
}).WrapAwait();
}
}
public RethinkBackingStore(string databaseName, string connectionString)
{
DatabaseName = databaseName;
ConnectionString = connectionString;
RegisterResolver.Register();
var connectionStringDomainLength = connectionString.IndexOf(':');
if (connectionStringDomainLength < 1)
throw new ArgumentException("Illegal Connection String: must include port!");
var portString = connectionString.Substring(connectionStringDomainLength + 1);
if (!int.TryParse(portString, out var port))
throw new ArgumentException($"Illegal connection string! \"{portString}\" is not a valid port number!");
_connection = R.Connection()
.Hostname(connectionString.Substring(0,connectionStringDomainLength))
.Port(port).Timeout(60).Connect();
var tables = R.Db(DatabaseName).TableList().RunAtom<string[]>(_connection);
_syncTables = typeof(DatabaseEntry).GetAllChildClasses()
.Select(t => t.GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? DEFAULT_TABLE).Distinct().ToArray();
foreach (var st in _syncTables.Where(st => !tables.Contains(st)))
R.Db(DatabaseName).TableCreate(st).RunNoReply(_connection);
}
public override void PullAll()
{
foreach (var table in _syncTables)
{
// Get entries from RethinkDB
Task.Run(async () =>
{
var result = await R
.Db(DatabaseName)
.Table(table)
.RunCursorAsync<DatabaseEntry>(_connection);
while (await result.MoveNextAsync())
{
var entry = result.Current;
EntryAdded.OnNext(entry);
}
}).WrapAwait();
}
}
public override async void Push(DatabaseEntry entry)
{
var type = entry.GetType();
//(Entries.ContainsKey(entry.ID) ? EntryUpdated : EntryAdded).OnNext(entry);
var table = type.GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? DEFAULT_TABLE;
var result = await R
.Db(DatabaseName)
.Table(table)
.Get(entry.ID)
.Replace(entry)
.RunAsync(_connection);
}
public override async void Delete(DatabaseEntry entry)
{
if(Entries.ContainsKey(entry.ID))
{
var type = entry.GetType();
var table = type.GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? DEFAULT_TABLE;
var result = await R
.Db(DatabaseName)
.Table(table)
.Get(entry.ID)
.Delete()
.RunAsync(_connection);
}
}
public override void PushAll(bool soft = false)
{
foreach(var entry in Entries.Values)
Push(entry);
}
}

View file

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

View file

@ -0,0 +1,91 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Linq;
using JsonKnownTypes;
using MessagePack;
using MessagePack.Formatters;
using Newtonsoft.Json;
// TODO: USE THIS EVERYWHERE
using Unity.Mathematics;
using static Unity.Mathematics.math;
public interface INamedEntry
{
string EntryName { get; set; }
}
[MessagePackObject,
JsonObject(MemberSerialization.OptIn),
JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>)),
Union(0, typeof(SimpleCommodityData)),
Union(1, typeof(CompoundCommodityData)),
Union(2, typeof(GearData)),
Union(3, typeof(HullData)),
Union(4, typeof(SimpleCommodity)),
Union(5, typeof(CompoundCommodity)),
Union(6, typeof(EquippableItem)),
Union(8, typeof(GalaxyMapLayerData)),
Union(9, typeof(NameFile)),
//Union(10, typeof(ZoneData)),
Union(11, typeof(PlayerData)),
// Union(12, typeof(Corporation)),
Union(13, typeof(Faction)),
Union(14, typeof(OrbitalEntity)),
Union(15, typeof(OrbitData)),
Union(16, typeof(BodyData)),
Union(17, typeof(PersonalityAttribute)),
Union(18, typeof(AgentTask)),
// Union(19, typeof(LoadoutData)),
Union(20, typeof(Ship)),
Union(21, typeof(Mining)),
Union(22, typeof(StationTowing)),
Union(23, typeof(Survey)),
Union(24, typeof(HaulingTask)),
Union(25, typeof(AsteroidBeltData)),
Union(26, typeof(GasGiantData)),
Union(27, typeof(SunData)),
Union(28, typeof(PlanetData)),
Union(29, typeof(CargoBayData)),
Union(30, typeof(DockingBayData)),
Union(31, typeof(WeaponItemData))]
public abstract class DatabaseEntry
{
[JsonProperty("id"), Key(0)]
public Guid ID = Guid.NewGuid();
public override int GetHashCode()
{
return ID.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is DatabaseEntry entry) return entry.ID == ID;
return false;
}
}
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class DatabaseLink<T> : DatabaseLinkBase where T : DatabaseEntry
{
[IgnoreMember]
public T Value => Cache.Get<T>(LinkID);
}
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class DatabaseLinkBase
{
[Key(0), JsonProperty("linkID")]
public Guid LinkID;
[IgnoreMember]
public static CultCache Cache;
}
public interface ITintInspector
{
float3 TintColor { get; }
}

View file

@ -0,0 +1,120 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public static class ReflectionExtensions
{
private static Dictionary<Type,Type[]> InterfaceClasses = new Dictionary<Type, Type[]>();
public static Type[] GetAllInterfaceClasses(this Type type)
{
if (InterfaceClasses.ContainsKey(type))
return InterfaceClasses[type];
return InterfaceClasses[type] = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(ass => ass.GetTypes()).Where(t => t.IsClass && t.GetInterfaces().Contains(type)).ToArray();
}
private static Dictionary<Type,Type[]> ParentTypes = new Dictionary<Type, Type[]>();
public static Type[] GetParentTypes(this Type type)
{
if (ParentTypes.ContainsKey(type))
return ParentTypes[type];
return ParentTypes[type] = type.GetParents().ToArray();
}
private static IEnumerable<Type> GetParents(this Type type)
{
// is there any base type?
if (type == null)
{
yield break;
}
yield return type;
// return all implemented or inherited interfaces
foreach (var i in type.GetInterfaces())
{
yield return i;
}
// return all inherited types
var currentBaseType = type.BaseType;
while (currentBaseType != null)
{
yield return currentBaseType;
currentBaseType= currentBaseType.BaseType;
}
}
private static Dictionary<Type,Type[]> ChildClasses = new Dictionary<Type, Type[]>();
public static Type[] GetAllChildClasses(this Type type)
{
if (ChildClasses.ContainsKey(type))
return ChildClasses[type];
return ChildClasses[type] = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(ass => ass.GetTypes()).Where(type.IsAssignableFrom).ToArray();
}
private static Dictionary<Type,Type[]> GenericChildClasses = new Dictionary<Type, Type[]>();
public static Type[] GetAllGenericChildClasses(this Type genericType)
{
if (GenericChildClasses.ContainsKey(genericType))
return ChildClasses[genericType];
return ChildClasses[genericType] = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(ass => ass.GetTypes()).Where(type=>type.IsAssignableToGenericType(genericType)).ToArray();
}
public static bool IsAssignableToGenericType(this Type givenType, Type genericType)
{
var interfaceTypes = givenType.GetInterfaces();
foreach (var it in interfaceTypes)
{
if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType)
return true;
}
if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
return true;
Type baseType = givenType.BaseType;
if (baseType == null) return false;
return IsAssignableToGenericType(baseType, genericType);
}
public static string SplitCamelCase( this string str )
{
return Regex.Replace(
Regex.Replace(
str,
@"(\P{Ll})(\P{Ll}\p{Ll})",
"$1 $2"
),
@"(\p{Ll})(\P{Ll})",
"$1 $2"
);
}
public static string FormatTypeName(this string typeName)
{
return (typeName.EndsWith("Data", StringComparison.InvariantCultureIgnoreCase)
? typeName.Substring(0, typeName.Length - 4)
: typeName).SplitCamelCase();
}
public static string GetFullName(this Type t)
{
if (!t.IsGenericType)
return t.Name.FormatTypeName();
var name = t.Name.FormatTypeName();
return
$"{name.Substring(0, name.LastIndexOf("`"))}{t.GetGenericArguments().Aggregate("<", (aggregate, type) => $"{aggregate}{(aggregate == "<" ? "" : ",")}{GetFullName(type)}")}>";
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: fd5642f26b80465fb57f3d2610633140
timeCreated: 1617055075

View file

@ -0,0 +1,34 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RethinkDb.Driver;
using RethinkDb.Driver.Ast;
using RethinkDb.Driver.Net;
public static class RethinkConnection
{
public static RethinkDB R = RethinkDB.R;
public static RethinkQueryStatus RethinkConnect(CultCache cache, string connectionString, string dbName, bool syncLocalChanges = true)
{
var status = new RethinkQueryStatus();
return status;
}
}
public class RethinkQueryStatus
{
public int RetrievedEntries;
public int TotalEntries;
}

View file

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

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8035c545a12367f419eb4a2fe1c917b6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,169 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public class MathJsonConverter : JsonConverter
{
private readonly Dictionary<Type, Action<JsonWriter, object>> _writers;
private readonly Dictionary<Type, Func<JArray, object>> _readers;
public MathJsonConverter()
{
_writers = GenerateWriters();
_readers = GenerateReaders();
}
private Dictionary<Type, Action<JsonWriter, object>> GenerateWriters()
{
var writers = new Dictionary<Type, Action<JsonWriter, object>>();
writers[typeof(float2)] = (writer, o) =>
{
if (!(o is float2 v))
throw new JsonReaderException();
writer.WriteStartArray();
writer.WriteValue(v.x);
writer.WriteValue(v.y);
writer.WriteEndArray();
};
writers[typeof(int2)] = (writer, o) =>
{
if (!(o is int2 v))
throw new JsonReaderException();
writer.WriteStartArray();
writer.WriteValue(v.x);
writer.WriteValue(v.y);
writer.WriteEndArray();
};
writers[typeof(float3)] = (writer, o) =>
{
if (!(o is float3 v))
throw new JsonReaderException();
writer.WriteStartArray();
writer.WriteValue(v.x);
writer.WriteValue(v.y);
writer.WriteValue(v.z);
writer.WriteEndArray();
};
writers[typeof(float4)] = (writer, o) =>
{
if (!(o is float4 v))
throw new JsonReaderException();
writer.WriteStartArray();
writer.WriteValue(v.x);
writer.WriteValue(v.y);
writer.WriteValue(v.z);
writer.WriteValue(v.w);
writer.WriteEndArray();
};
return writers;
}
private Dictionary<Type, Func<JArray, object>> GenerateReaders()
{
var readers = new Dictionary<Type, Func<JArray, object>>();
readers[typeof(float2)] = array =>
{
if (array.Count < 2)
{
throw new JsonReaderException(
$"Could not read {typeof(float2)} from json, expected a json array with 2 elements");
}
return float2(
array[0].ToObject<float>(),
array[1].ToObject<float>());
};
readers[typeof(int2)] = array =>
{
if (array.Count < 2)
{
throw new JsonReaderException(
$"Could not read {typeof(float2)} from json, expected a json array with 2 elements");
}
return int2(
array[0].ToObject<int>(),
array[1].ToObject<int>());
};
readers[typeof(float3)] = array =>
{
if (array.Count < 3)
{
throw new JsonReaderException(
$"Could not read {typeof(float3)} from json, expected a json array with 3 elements");
}
return float3(
array[0].ToObject<float>(),
array[1].ToObject<float>(),
array[2].ToObject<float>());
};
readers[typeof(float4)] = array =>
{
if (array.Count < 4)
{
throw new JsonReaderException(
$"Could not read {typeof(float4)} from json, expected a json array with 4 elements");
}
return float4(
array[0].ToObject<float>(),
array[1].ToObject<float>(),
array[2].ToObject<float>(),
array[3].ToObject<float>());
};
return readers;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (_writers.TryGetValue(value.GetType(), out var serializeAction))
serializeAction(writer, value);
else
throw new JsonReaderException($"Invalid type for ValueConverter:{value.GetType()}");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (_readers.TryGetValue(objectType, out var deserializeFunc))
{
// Convert token from reader to array for deserialize function
var token = JToken.ReadFrom(reader);
if (!(token is JArray asArray))
throw new JsonReaderException(
$"Could not read {objectType} from json, expected a json array but got {token.Type}");
return deserializeFunc(asArray);
}
throw new JsonReaderException($"Invalid type for ValueConverter:{objectType}");
}
public override bool CanConvert(Type objectType)
{
//If the dictionary contains the key, the type can be handled by this class
return _writers.ContainsKey(objectType);
}
//Enable this JSON Converter for reading as well as writing values
public override bool CanRead => true;
public override bool CanWrite => true;
}

View file

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

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f94c63c8b140fb34bb5d70a8d8a5dbd6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,16 @@
using System;
namespace JsonKnownTypes
{
public static class AttributesManager
{
public static JsonKnownTypeAttribute[] GetJsonKnownAttributes(Type type) =>
(JsonKnownTypeAttribute[])Attribute.GetCustomAttributes(type, typeof(JsonKnownTypeAttribute));
public static JsonKnownThisTypeAttribute GetJsonKnownThisAttribute(Type type) =>
(JsonKnownThisTypeAttribute)Attribute.GetCustomAttribute(type, typeof(JsonKnownThisTypeAttribute));
public static JsonDiscriminatorAttribute GetJsonDiscriminatorAttribute(Type type) =>
(JsonDiscriminatorAttribute)Attribute.GetCustomAttribute(type, typeof(JsonDiscriminatorAttribute));
}
}

View file

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

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 01722fba3f2fd3942bca61d48508ad27
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,15 @@
using System;
namespace JsonKnownTypes.Exceptions
{
public class JsonKnownTypesException : Exception
{
public JsonKnownTypesException(string message)
: base(message)
{ }
public JsonKnownTypesException(string message, Exception innerException)
: base(message, innerException)
{ }
}
}

View file

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

View file

@ -0,0 +1,18 @@
using System;
namespace JsonKnownTypes
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
public class JsonDiscriminatorAttribute : Attribute
{
public string Name { get; set; }
internal bool? _autoJson;
public bool AutoJson
{
get => _autoJson != null && (bool) _autoJson;
set => _autoJson = value;
}
}
}

View file

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

View file

@ -0,0 +1,8 @@
namespace JsonKnownTypes
{
public class JsonDiscriminatorSettings
{
public string Name { get; set; } = "$type";
public bool AutoJsonKnown { get; set; } = true;
}
}

View file

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

View file

@ -0,0 +1,17 @@
using System;
namespace JsonKnownTypes
{
public class JsonKnownThisTypeAttribute : Attribute
{
public string Discriminator { get; }
public JsonKnownThisTypeAttribute()
{ }
public JsonKnownThisTypeAttribute(string discriminator)
{
Discriminator = discriminator;
}
}
}

View file

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

View file

@ -0,0 +1,22 @@
using System;
namespace JsonKnownTypes
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true)]
public class JsonKnownTypeAttribute : Attribute
{
public Type Type { get; }
public string Discriminator { get; }
public JsonKnownTypeAttribute(Type type)
{
Type = type;
}
public JsonKnownTypeAttribute(Type type, string discriminator)
{
Type = type;
Discriminator = discriminator;
}
}
}

View file

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

View file

@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>
<PropertyGroup>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>0.2.0</Version>
<Authors>Dmitry Kaznacheev</Authors>
<PackageProjectUrl>https://github.com/dmitry-bym/JsonKnownTypes</PackageProjectUrl>
<PackageLicenseUrl>https://github.com/dmitry-bym/JsonKnownTypes/blob/master/LICENSE</PackageLicenseUrl>
<Copyright>Dmitry Kaznacheev</Copyright>
<RepositoryUrl>https://github.com/dmitry-bym/JsonKnownTypes</RepositoryUrl>
<PackageTags>json known polymorphic types</PackageTags>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 937d902757d946b47a7bea20ade37beb
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,16 @@
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace JsonKnownTypes
{
public class JsonKnownTypesContractResolver<T> : DefaultContractResolver
{
protected override JsonConverter ResolveContractConverter(Type objectType)
{
if (typeof(T).IsAssignableFrom(objectType) && !objectType.IsAbstract)
return null;
return base.ResolveContractConverter(objectType);
}
}
}

View file

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

View file

@ -0,0 +1,57 @@
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace JsonKnownTypes
{
public class JsonKnownTypesConverter<T> : JsonConverter
{
private readonly JsonKnownTypesSettings _typesSettings
= JsonKnownTypesSettingsManager.GetSettings<T>();
private JsonSerializerSettings SpecifiedSubclassConversion
{
get =>
new JsonSerializerSettings
{
ContractResolver = new JsonKnownTypesContractResolver<T>()
};
}
public override bool CanConvert(Type objectType)
=> _typesSettings.TypeToDiscriminator.ContainsKey(objectType);
public override bool CanWrite { get => true; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null) return null;
var jo = JObject.Load(reader);
var discriminator = jo[_typesSettings.Name].ToString();
if(_typesSettings.DiscriminatorToType.TryGetValue(discriminator, out var typeForObject))
return JsonConvert.DeserializeObject(jo.ToString(), typeForObject, SpecifiedSubclassConversion);
return null;
//throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var objectType = value.GetType();
if (_typesSettings.TypeToDiscriminator.TryGetValue(objectType, out var discriminator))
{
var json = JsonConvert.SerializeObject(value, SpecifiedSubclassConversion);
var jo = JObject.Parse(json);
jo.Add(_typesSettings.Name, new JValue(discriminator));
jo.WriteTo(writer);
}
else
{
throw new ArgumentException($"Json Known Types: Type Unknown {objectType.FullName}!");
}
}
}
}

View file

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

View file

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using JsonKnownTypes.Exceptions;
namespace JsonKnownTypes
{
internal static class JsonKnownTypesDictionaryManager
{
public static void AddJsonKnown<T>(this Dictionary<Type, string> dictionary)
{
var attrs = AttributesManager.GetJsonKnownAttributes(typeof(T));
foreach (var attr in attrs)
{
var discriminator = attr.Discriminator ?? attr.Type.Name;
dictionary.TryAdd(attr.Type, discriminator);
}
}
public static void AddJsonKnownThis(this Dictionary<Type, string> dictionary, Type[] inherited)
{
foreach (var type in inherited)
{
var attr = AttributesManager.GetJsonKnownThisAttribute(type);
if (attr != null)
{
var discriminator = attr.Discriminator ?? type.Name;
dictionary.TryAdd(type, discriminator);
}
}
}
public static void AddAutoGenerated(this Dictionary<Type, string> dictionary, Type[] inherited)
{
foreach (var type in inherited.Except(dictionary.Keys))
{
dictionary.TryAdd(type, type.Name);
}
}
public static void TryAdd(this Dictionary<Type, string> dictionary, Type key, string discriminator)
{
if (dictionary.ContainsKey(key))
throw new JsonKnownTypesException($"Dictionary already contains the key {key.Name}");//todo
if (dictionary.ContainsValue(discriminator))
throw new JsonKnownTypesException($"Dictionary already contains the value {discriminator}");//todo
dictionary.Add(key, discriminator);
}
public static Dictionary<string, Type> Revert(this Dictionary<Type, string> dictionary)
{
try
{
return dictionary.ToDictionary(x => x.Value, x => x.Key);
}
catch (ArgumentException e)
{
throw new JsonKnownTypesException("Dictionary has a repeated value", e);
}
}
}
}

View file

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

View file

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
namespace JsonKnownTypes
{
public class JsonKnownTypesSettings
{
public string Name { get; set; }
public Dictionary<string, Type> DiscriminatorToType { get; set; } = new Dictionary<string, Type>();
public Dictionary<Type, string> TypeToDiscriminator { get; set; } = new Dictionary<Type, string>();
}
}

View file

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

View file

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using JsonKnownTypes.Exceptions;
using JsonKnownTypes.Utils;
namespace JsonKnownTypes
{
public static class JsonKnownTypesSettingsManager
{
public static JsonDiscriminatorSettings DefaultDiscriminatorSettings { get; set; } = new JsonDiscriminatorSettings();
private static HashSet<Assembly> RegisteredAssemblies = new HashSet<Assembly>();
public static void RegisterTypeAssembly<T>()
{
var type = typeof(T);
RegisteredAssemblies.Add(type.Assembly);
}
public static JsonKnownTypesSettings GetSettings<T>()
{
var discriminatorAttribute = AttributesManager.GetJsonDiscriminatorAttribute(typeof(T));
var discriminatorSettings = discriminatorAttribute == null ? DefaultDiscriminatorSettings : Mapper.Map(discriminatorAttribute);
var typeSettings = new JsonKnownTypesSettings
{
Name = discriminatorSettings.Name
};
var allTypes = GetAllInheritance<T>();
typeSettings.TypeToDiscriminator.AddJsonKnown<T>();
typeSettings.TypeToDiscriminator.AddJsonKnownThis(allTypes);
if (discriminatorSettings.AutoJsonKnown)
{
typeSettings.TypeToDiscriminator.AddAutoGenerated(allTypes);
}
else if(!allTypes.All(typeSettings.TypeToDiscriminator.ContainsKey))
{
throw new JsonKnownTypesException("Dictionary contains not all types of hierarchy, enable AutoJsonKnow or add attributes for all classes"); //todo
}
typeSettings.DiscriminatorToType = typeSettings.TypeToDiscriminator.Revert();
return typeSettings;
}
private static Type[] GetAllInheritance<T>()
{
RegisterTypeAssembly<T>();
var type = typeof(T);
return RegisteredAssemblies.SelectMany(a=>a.GetTypes())
.Where(x => type.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
.ToArray();
}
}
}

View file

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

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6d6706b0998d8af458321fd5f35906fb
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,15 @@
namespace JsonKnownTypes.Utils
{
internal static class Mapper
{
public static JsonDiscriminatorSettings Map(JsonDiscriminatorAttribute entity)
{
var settings = new JsonDiscriminatorSettings();
settings.Name = entity.Name ?? settings.Name;
settings.AutoJsonKnown = entity._autoJson ?? settings.AutoJsonKnown;
return settings;
}
}
}

View file

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

View file

@ -0,0 +1,226 @@
using System;
using System.Collections;
using System.Collections.Generic;
using MessagePack;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public class Float2Formatter : MessagePack.Formatters.IMessagePackFormatter<float2>
{
public void Serialize(ref MessagePackWriter writer, float2 value, MessagePackSerializerOptions options)
{
writer.WriteArrayHeader(2);
writer.Write(value.x);
writer.Write(value.y);
}
public float2 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.IsNil)
{
throw new InvalidOperationException("typecode is null, struct not supported");
}
var length = reader.ReadArrayHeader();
var x = default(float);
var y = default(float);
for (int i = 0; i < length; i++)
{
var key = i;
switch (key)
{
case 0:
x = reader.ReadSingle();
break;
case 1:
y = reader.ReadSingle();
break;
default:
reader.Skip();
break;
}
}
var result = float2(x, y);
return result;
}
}
public class Int2Formatter : MessagePack.Formatters.IMessagePackFormatter<int2>
{
public void Serialize(ref MessagePackWriter writer, int2 value, MessagePackSerializerOptions options)
{
writer.WriteArrayHeader(2);
writer.Write(value.x);
writer.Write(value.y);
}
public int2 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.IsNil)
{
throw new InvalidOperationException("typecode is null, struct not supported");
}
var length = reader.ReadArrayHeader();
var x = default(int);
var y = default(int);
for (int i = 0; i < length; i++)
{
var key = i;
switch (key)
{
case 0:
x = reader.ReadInt32();
break;
case 1:
y = reader.ReadInt32();
break;
default:
reader.Skip();
break;
}
}
var result = int2(x, y);
return result;
}
}
public class Bool2Formatter : MessagePack.Formatters.IMessagePackFormatter<bool2>
{
public void Serialize(ref MessagePackWriter writer, bool2 value, MessagePackSerializerOptions options)
{
writer.WriteArrayHeader(2);
writer.Write(value.x);
writer.Write(value.y);
}
public bool2 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.IsNil)
{
throw new InvalidOperationException("typecode is null, struct not supported");
}
var length = reader.ReadArrayHeader();
var x = default(bool);
var y = default(bool);
for (int i = 0; i < length; i++)
{
var key = i;
switch (key)
{
case 0:
x = reader.ReadBoolean();
break;
case 1:
y = reader.ReadBoolean();
break;
default:
reader.Skip();
break;
}
}
var result = bool2(x, y);
return result;
}
}
public class Float3Formatter : MessagePack.Formatters.IMessagePackFormatter<float3>
{
public void Serialize(ref MessagePackWriter writer, float3 value, MessagePackSerializerOptions options)
{
writer.WriteArrayHeader(3);
writer.Write(value.x);
writer.Write(value.y);
writer.Write(value.z);
}
public float3 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.IsNil)
{
throw new InvalidOperationException("typecode is null, struct not supported");
}
var length = reader.ReadArrayHeader();
var x = default(float);
var y = default(float);
var z = default(float);
for (int i = 0; i < length; i++)
{
var key = i;
switch (key)
{
case 0:
x = reader.ReadSingle();
break;
case 1:
y = reader.ReadSingle();
break;
case 2:
z = reader.ReadSingle();
break;
default:
reader.Skip();
break;
}
}
var result = float3(x, y, z);
return result;
}
}
public class Float4Formatter : MessagePack.Formatters.IMessagePackFormatter<float4>
{
public void Serialize(ref MessagePackWriter writer, float4 value, MessagePackSerializerOptions options)
{
writer.WriteArrayHeader(4);
writer.Write(value.x);
writer.Write(value.y);
writer.Write(value.z);
writer.Write(value.w);
}
public float4 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.IsNil)
{
throw new InvalidOperationException("typecode is null, struct not supported");
}
var length = reader.ReadArrayHeader();
var x = default(float);
var y = default(float);
var z = default(float);
var w = default(float);
for (int i = 0; i < length; i++)
{
var key = i;
switch (key)
{
case 0:
x = reader.ReadSingle();
break;
case 1:
y = reader.ReadSingle();
break;
case 2:
z = reader.ReadSingle();
break;
case 3:
w = reader.ReadSingle();
break;
default:
reader.Skip();
break;
}
}
var result = float4(x, y, z, w);
return result;
}
}

Some files were not shown because too many files have changed in this diff Show more