Energy & Heat

Energy Generation (Reactor behavior)
Heat Conduction / Radiation
Temperature Display
In-game ship schematic
Better asteroid distribution
This commit is contained in:
Reinier Vens 2020-12-27 22:18:22 +00:00
commit 6db7c65961
117 changed files with 9506 additions and 9134 deletions

View file

@ -27,7 +27,9 @@ public class ActionGameManager : MonoBehaviour
public CinemachineVirtualCamera FollowCamera;
public GameObject GameplayUI;
public MenuPanel Menu;
public MapRenderer MenuMap;
public InventoryMenu Inventory;
public InventoryPanel ShipPanel;
public float2 Sensitivity;
//public PlayerInput Input;
@ -99,12 +101,15 @@ public class ActionGameManager : MonoBehaviour
Cursor.lockState = CursorLockMode.Locked;
_input.Player.Enable();
Menu.gameObject.SetActive(false);
GameplayUI.SetActive(true);
return;
}
Cursor.lockState = CursorLockMode.None;
_input.Player.Disable();
GameplayUI.SetActive(false);
Menu.ShowTab(MenuTab.Map);
MenuMap.Position = _currentShip.Position;
};
_input.Global.Inventory.performed += context =>
@ -114,12 +119,21 @@ public class ActionGameManager : MonoBehaviour
Cursor.lockState = CursorLockMode.Locked;
_input.Player.Enable();
Menu.gameObject.SetActive(false);
GameplayUI.SetActive(true);
return;
}
Cursor.lockState = CursorLockMode.None;
_input.Player.Disable();
Menu.ShowTab(MenuTab.Inventory);
GameplayUI.SetActive(false);
var cargo = _currentShip.CargoBays.FirstOrDefault();
if (cargo != null)
{
Inventory.GetPanel.Display(cargo);
}
else Inventory.GetPanel.Clear();
Inventory.GetPanel.Display(_currentShip);
};
_input.Global.Dock.performed += context =>
@ -156,8 +170,6 @@ public class ActionGameManager : MonoBehaviour
PlayerShips.Add(ship);
_currentShip = ship;
var dockingCargo = station.DockingBays.First();
var thrusterData = ItemData.GetAll<GearData>().First(x => x.HardpointType == HardpointType.Thruster && x.Shape.Height == 1);
for (int i = 0; i < 8; i++)
{
@ -207,6 +219,7 @@ public class ActionGameManager : MonoBehaviour
_shipInput = null;
Cursor.lockState = CursorLockMode.None;
_input.Player.Disable();
GameplayUI.SetActive(false);
}
}
}
@ -225,7 +238,9 @@ public class ActionGameManager : MonoBehaviour
FollowCamera.LookAt = _lookAt;
FollowCamera.Follow = SectorRenderer.Ships[_currentShip].Transform;
Cursor.lockState = CursorLockMode.Locked;
GameplayUI.SetActive(true);
_input.Player.Enable();
ShipPanel.Display(_currentShip);
}
}

View file

@ -109,6 +109,8 @@ public abstract class PersistentBehaviorData
Union(28, typeof(ResourceScannerData)),
Union(29, typeof(WanderControllerData)),
Union(30, typeof(HaulingControllerData)),
Union(31, typeof(CapacitorData)),
Union(32, typeof(CockpitData)),
JsonConverter(typeof(JsonKnownTypesConverter<BehaviorData>)), JsonObject(MemberSerialization.OptIn)]
public abstract class BehaviorData
{

View file

@ -0,0 +1,60 @@
/* 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 MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class CapacitorData : BehaviorData
{
[InspectableField, JsonProperty("capacity"), Key(1), RuntimeInspectable]
public PerformanceStat Capacity = new PerformanceStat();
[InspectableField, JsonProperty("efficiency"), Key(2), RuntimeInspectable]
public PerformanceStat Efficiency = new PerformanceStat();
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
{
return new Capacitor(context, this, entity, item);
}
}
public class Capacitor : IBehavior
{
private CapacitorData _data;
public Entity Entity { get; }
public EquippedItem Item { get; }
public ItemManager Context { get; }
public BehaviorData Data => _data;
public float Charge { get; private set; }
public float Capacity { get; private set; }
public float Efficiency { get; private set; } = 1;
public void AddCharge(float charge)
{
Charge = clamp(Charge + charge, 0, Capacity);
Item.AddHeat(abs(charge) * (1-Efficiency));
}
public Capacitor(ItemManager context, CapacitorData data, Entity entity, EquippedItem item)
{
Context = context;
_data = data;
Entity = entity;
Item = item;
}
public bool Update(float delta)
{
Capacity = Context.Evaluate(_data.Capacity, Item.EquippableItem, Entity);
Efficiency = Context.Evaluate(_data.Efficiency, Item.EquippableItem, Entity);
return true;
}
}

View file

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

View file

@ -0,0 +1,42 @@
/* 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 MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class CockpitData : BehaviorData
{
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
{
return new Cockpit(context, this, entity, item);
}
}
public class Cockpit : IBehavior
{
private CockpitData _data;
public Entity Entity { get; }
public EquippedItem Item { get; }
public ItemManager Context { get; }
public BehaviorData Data => _data;
public Cockpit(ItemManager context, CockpitData data, Entity entity, EquippedItem item)
{
Context = context;
_data = data;
Entity = entity;
Item = item;
}
public bool Update(float delta)
{
return true;
}
}

View file

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

View file

@ -22,11 +22,10 @@ public class EnergyDrawData : BehaviorData
}
}
public class EnergyDraw : IBehavior, IOrderedBehavior
public class EnergyDraw : IBehavior
{
private EnergyDrawData _data;
public int Order => -100;
private Entity Entity { get; }
private EquippedItem Item { get; }
private ItemManager Context { get; }

View file

@ -42,7 +42,8 @@ public class Heat : IBehavior
public bool Update(float delta)
{
Item.Temperature += Context.Evaluate(_data.Heat, Item.EquippableItem, Entity) * (_data.PerSecond ? delta : 1) / Context.GetThermalMass(Item.EquippableItem);
Item.AddHeat(Context.Evaluate(_data.Heat, Item.EquippableItem, Entity) * (_data.PerSecond ? delta : 1));
return true;
}
}

View file

@ -43,7 +43,7 @@ public class Radiator : IBehavior
{
Emissivity = Context.Evaluate(_data.Emissivity, Item.EquippableItem, Entity);
var rad = pow(Item.Temperature, Context.GameplaySettings.HeatRadiationExponent) * Context.GameplaySettings.HeatRadiationMultiplier * Emissivity;
Item.Temperature -= rad * delta;
Item.AddHeat(-rad * delta);
Entity.VisibilitySources[this] = rad;
return true;
}

View file

@ -2,8 +2,13 @@
* 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 Unity.Mathematics;
using static Unity.Mathematics.math;
[MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class ReactorData : BehaviorData
@ -11,16 +16,13 @@ public class ReactorData : BehaviorData
[InspectableField, JsonProperty("charge"), Key(1), RuntimeInspectable]
public PerformanceStat Charge = new PerformanceStat();
[InspectableField, JsonProperty("capacitance"), Key(2), RuntimeInspectable]
public PerformanceStat Capacitance = new PerformanceStat();
[InspectableField, JsonProperty("efficiency"), Key(3), RuntimeInspectable]
[InspectableField, JsonProperty("efficiency"), Key(2), RuntimeInspectable]
public PerformanceStat Efficiency = new PerformanceStat();
[InspectableField, JsonProperty("overload"), Key(4), RuntimeInspectable]
[InspectableField, JsonProperty("overload"), Key(3), RuntimeInspectable]
public PerformanceStat OverloadEfficiency = new PerformanceStat();
[InspectableField, JsonProperty("underload"), Key(5), RuntimeInspectable]
[InspectableField, JsonProperty("underload"), Key(4), RuntimeInspectable]
public PerformanceStat ThrottlingFactor = new PerformanceStat();
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
@ -29,7 +31,7 @@ public class ReactorData : BehaviorData
}
}
public class Reactor : IBehavior
public class Reactor : IBehavior, IOrderedBehavior
{
private ReactorData _data;
@ -37,8 +39,11 @@ public class Reactor : IBehavior
public EquippedItem Item { get; }
public ItemManager Context { get; }
public int Order => 100;
public BehaviorData Data => _data;
public float Capacitance;
private List<Capacitor> _capacitors;
public Reactor(ItemManager context, ReactorData data, Entity entity, EquippedItem item)
{
@ -46,26 +51,69 @@ public class Reactor : IBehavior
_data = data;
Entity = entity;
Item = item;
_capacitors = entity.GetBehaviors<Capacitor>().ToList();
entity.Equipment.ObserveAdd().Subscribe(onAdd =>
{
var cap = onAdd.Value.Behaviors.FirstOrDefault(x => x is Capacitor);
if (cap != null)
_capacitors.Add((Capacitor) cap);
});
}
public bool Update(float delta)
{
Capacitance = Context.Evaluate(_data.Capacitance, Item.EquippableItem, Entity);
var charge = Context.Evaluate(_data.Charge, Item.EquippableItem, Entity) * delta;
var efficiency = Context.Evaluate(_data.Efficiency, Item.EquippableItem, Entity);
Item.Temperature += (charge / efficiency) / Context.GetThermalMass(Item.EquippableItem);
Item.AddHeat(charge / efficiency);
Entity.Energy += charge;
if (Entity.Energy > Capacitance)
{
Item.Temperature -= (Entity.Energy - Capacitance) / efficiency * (1 - 1 / Context.Evaluate(_data.ThrottlingFactor, Item.EquippableItem, Entity)) / Context.GetThermalMass(Item.EquippableItem);
Entity.Energy = Capacitance;
}
// We have an energy deficit, try to get some energy out of our capacitors first
if (Entity.Energy < 0)
{
Item.Temperature += -Entity.Energy / Context.Evaluate(_data.OverloadEfficiency, Item.EquippableItem, Entity) / Context.GetThermalMass(Item.EquippableItem);
Capacitor[] chargedCapacitors;
do
{
var chargeToRemove = -Entity.Energy;
chargedCapacitors = _capacitors.Where(x => x.Charge > 0.01f).ToArray();
foreach (var cap in chargedCapacitors)
{
var chargeRemoved = min(chargeToRemove / chargedCapacitors.Length, cap.Charge);
cap.AddCharge(-chargeRemoved);
Entity.Energy += chargeRemoved;
}
} while (chargedCapacitors.Length > 0 && Entity.Energy < -.01f);
}
// We still have an energy deficit, have to overload the reactor, run at reduced efficiency
if (Entity.Energy < -.01f)
{
var overloadEfficiency = Context.Evaluate(_data.OverloadEfficiency, Item.EquippableItem, Entity);
Item.AddHeat(-Entity.Energy / overloadEfficiency);
Entity.Energy = 0;
}
// We have an energy surplus, try to store energy in our capacitors
if (Entity.Energy > .01f)
{
Capacitor[] capacitors;
do
{
var chargeToAdd = Entity.Energy;
capacitors = _capacitors.Where(x => x.Charge < x.Capacity - .01f).ToArray();
foreach (var cap in capacitors)
{
var chargeAdded = min(chargeToAdd / capacitors.Length, cap.Capacity - cap.Charge);
cap.AddCharge(chargeAdded);
Entity.Energy -= chargeAdded;
}
} while (capacitors.Length > 0 && Entity.Energy < -.01f);
}
// We still have an energy surplus, try to throttle the reactor to reduce heat generation
if (Entity.Energy > .01f)
{
Item.AddHeat(-Entity.Energy / efficiency * (1 - 1 / Context.Evaluate(_data.ThrottlingFactor, Item.EquippableItem, Entity)));
Entity.Energy = 0;
}
return true;

View file

@ -68,7 +68,7 @@ public class Thruster : IAnalogBehavior
Thrust = Context.Evaluate(_data.Thrust, Item.EquippableItem, Entity);
Entity.Velocity -= Entity.Direction.Rotate(Item.EquippableItem.Rotation) * _input * Thrust / Entity.Mass * delta;
Entity.Direction = mul(Entity.Direction, Unity.Mathematics.float2x2.Rotate(_input * Torque * Thrust / Entity.Mass / 100 * delta));
Item.Temperature += (_input * Context.Evaluate(_data.Heat, Item.EquippableItem, Entity) * delta) / Context.GetThermalMass(Item.EquippableItem);
Item.AddHeat(_input * Context.Evaluate(_data.Heat, Item.EquippableItem, Entity) * delta);
Entity.VisibilitySources[this] = _input * Context.Evaluate(_data.Visibility, Item.EquippableItem, Entity);
return true;
}

View file

@ -61,7 +61,7 @@ public class Turning : IAnalogBehavior
{
Torque = Context.Evaluate(_data.Torque, Item.EquippableItem, Entity);
Entity.Direction = mul(Entity.Direction, Unity.Mathematics.float2x2.Rotate(_input * Torque / Entity.Mass * delta));
Item.Temperature += (abs(_input) * Context.Evaluate(_data.Heat, Item.EquippableItem, Entity) * delta) / Context.GetThermalMass(Item.EquippableItem);
Item.AddHeat(abs(_input) * Context.Evaluate(_data.Heat, Item.EquippableItem, Entity) * delta);
Entity.VisibilitySources[this] = abs(_input) * Context.Evaluate(_data.Visibility, Item.EquippableItem, Entity);
return true;
}

View file

@ -3,8 +3,7 @@
"references": [
"MessagePack",
"Unity.Mathematics",
"UniRx",
"com.alelievr.NodeGraphProcessor.Runtime"
"UniRx"
],
"includePlatforms": [],
"excludePlatforms": [],

View file

@ -28,6 +28,8 @@ public abstract class Entity
public float2 Velocity;
public float[,] Temperature;
public float4[,] Conductivity;
public float[,] ThermalMass;
public float Energy;
public readonly ReactiveCollection<EquippedItem> Equipment = new ReactiveCollection<EquippedItem>();
@ -46,12 +48,14 @@ public abstract class Entity
public readonly Dictionary<object, float> VisibilitySources = new Dictionary<object, float>();
private List<IPopulationAssignment> PopulationAssignments = new List<IPopulationAssignment>();
private bool _active;
public EquippedItem[,] GearOccupancy;
public EquippedItem[,] ThermalOccupancy;
public HardpointData[,] Hardpoints;
private EquippedItem[] _orderedEquipment;
private bool _active;
public ItemManager ItemManager { get; }
public int AssignedPopulation => PopulationAssignments.Sum(pa => pa.AssignedPopulation);
public float Mass { get; private set; }
@ -87,10 +91,20 @@ public abstract class Entity
private void MapShip()
{
var hullData = ItemManager.GetData(Hull) as HullData;
var hull = new EquippedItem(ItemManager, Hull, int2.zero);
var hull = new EquippedItem(ItemManager, Hull, int2.zero, this);
Equipment.Add(hull);
Hydrate(hull);
Mass = hullData.Mass;
Temperature = new float[hullData.Shape.Width, hullData.Shape.Height];
Conductivity = new float4[hullData.Shape.Width, hullData.Shape.Height];
ThermalMass = new float[hullData.Shape.Width, hullData.Shape.Height];
var cellCount = hullData.Shape.Coordinates.Length;
foreach (var v in hullData.Shape.Coordinates)
{
Temperature[v.x, v.y] = 280;
Conductivity[v.x, v.y] = hullData.Conductivity;
ThermalMass[v.x, v.y] = hullData.Mass * hullData.SpecificHeat / cellCount;
}
GearOccupancy = new EquippedItem[hullData.Shape.Width, hullData.Shape.Height];
ThermalOccupancy = new EquippedItem[hullData.Shape.Width, hullData.Shape.Height];
Hardpoints = new HardpointData[hullData.Shape.Width, hullData.Shape.Height];
@ -121,7 +135,7 @@ public abstract class Entity
equippedItem.BehaviorGroups = equippedItem.Behaviors
.GroupBy(b => b.Data.Group)
.OrderBy(g=>g.Key)
.Select(g=>new BehaviorGroup {
.Select(g=> new BehaviorGroup {
Behaviors = g.ToArray(),
//Axis = (IAnalogBehavior) g.FirstOrDefault(b=>b is IAnalogBehavior),
Switch = (Switch) g.FirstOrDefault(b=>b is Switch),
@ -131,11 +145,18 @@ public abstract class Entity
foreach (var behavior in equippedItem.Behaviors)
{
if (behavior is IOrderedBehavior orderedBehavior)
equippedItem.SortPosition = orderedBehavior.Order;
if(behavior is IPopulationAssignment populationAssignment)
PopulationAssignments.Add(populationAssignment);
}
}
public void AddHeat(int2 position, float heat)
{
Temperature[position.x, position.y] += heat / ThermalMass[position.x, position.y];
}
public EquippedCargoBay FindItemInCargo(Guid itemDataID)
{
return CargoBays.FirstOrDefault(c => c.ItemsOfType.ContainsKey(itemDataID));
@ -197,13 +218,18 @@ public abstract class Entity
}
Equipment.Remove(item);
_orderedEquipment = Equipment.OrderBy(x => x.SortPosition).ToArray();
var hullData = ItemManager.GetData(Hull) as HullData;
var itemData = ItemManager.GetData(item.EquippableItem);
var itemLayer = (itemData.HardpointType == HardpointType.Thermal ? ThermalOccupancy : GearOccupancy);
foreach (var i in hullData.Shape.Coordinates)
if (itemLayer[i.x, i.y] == item)
{
ThermalMass[i.x, i.y] -= ItemManager.GetThermalMass(item.EquippableItem) / itemData.Shape.Coordinates.Length;
Conductivity[i.x, i.y] /= itemData.Conductivity;
itemLayer[i.x, i.y] = null;
}
Mass -= itemData.Mass;
return item.EquippableItem;
@ -328,18 +354,18 @@ public abstract class Entity
{
if (itemData is DockingBayData)
{
equippedItem = new EquippedDockingBay(ItemManager, item, hullCoord, $"{Name} Docking Bay {DockingBays.Count + 1}");
equippedItem = new EquippedDockingBay(ItemManager, item, hullCoord, this, $"{Name} Docking Bay {DockingBays.Count + 1}");
DockingBays.Add((EquippedDockingBay) equippedItem);
}
else
{
equippedItem = new EquippedCargoBay(ItemManager, item, hullCoord, $"{Name} Cargo Bay {CargoBays.Count + 1}");
equippedItem = new EquippedCargoBay(ItemManager, item, hullCoord, this, $"{Name} Cargo Bay {CargoBays.Count + 1}");
CargoBays.Add((EquippedCargoBay) equippedItem);
}
}
else
{
equippedItem = new EquippedItem(ItemManager, item, hullCoord);
equippedItem = new EquippedItem(ItemManager, item, hullCoord, this);
Equipment.Add(equippedItem);
}
@ -351,21 +377,25 @@ public abstract class Entity
Mass += itemData.Mass;
Hydrate(equippedItem);
_orderedEquipment = Equipment.OrderBy(x => x.SortPosition).ToArray();
return true;
}
else
{
var equippedItem = new EquippedItem(ItemManager, item, hullCoord);
var equippedItem = new EquippedItem(ItemManager, item, hullCoord, this);
Equipment.Add(equippedItem);
foreach (var i in itemData.Shape.Coordinates)
{
var occupiedCoord = hullCoord + itemData.Shape.Rotate(i, item.Rotation);
ThermalMass[occupiedCoord.x, occupiedCoord.y] += ItemManager.GetThermalMass(item) / itemData.Shape.Coordinates.Length;
Conductivity[occupiedCoord.x, occupiedCoord.y] *= itemData.Conductivity;
(itemData.HardpointType == HardpointType.Thermal ? ThermalOccupancy : GearOccupancy)[occupiedCoord.x, occupiedCoord.y] = equippedItem;
}
Mass += itemData.Mass;
Hydrate(equippedItem);
_orderedEquipment = Equipment.OrderBy(x => x.SortPosition).ToArray();
return true;
}
}
@ -432,18 +462,20 @@ public abstract class Entity
public T GetBehavior<T>() where T : class, IBehavior
{
foreach (var equippedItem in Equipment)
foreach (var behavior in equippedItem.Behaviors)
if (behavior is T b)
return b;
if(equippedItem.Behaviors != null)
foreach (var behavior in equippedItem.Behaviors)
if (behavior is T b)
return b;
return null;
}
public IEnumerable<T> GetBehaviors<T>() where T : class, IBehavior
{
foreach (var equippedItem in Equipment)
foreach (var behavior in equippedItem.Behaviors)
if (behavior is T b)
yield return b;
if(equippedItem.Behaviors != null)
foreach (var behavior in equippedItem.Behaviors)
if (behavior is T b)
yield return b;
}
public IEnumerable<T> GetBehaviorData<T>() where T : BehaviorData
@ -476,9 +508,44 @@ public abstract class Entity
public virtual void Update(float delta)
{
var hullData = ItemManager.GetData(Hull) as HullData;
float[,] newTemp = new float[hullData.Shape.Width,hullData.Shape.Height];
var radiation = 0f;
foreach (var v in hullData.Shape.Coordinates)
{
var temp = Temperature[v.x, v.y];
var heatTransfer = 0f;
if (v.x > 0)
heatTransfer += (Temperature[v.x - 1, v.y] - temp) * Conductivity[v.x, v.y].y * Conductivity[v.x - 1, v.y].w;
if (v.x < hullData.Shape.Width - 1)
heatTransfer += (Temperature[v.x + 1, v.y] - temp) * Conductivity[v.x, v.y].w * Conductivity[v.x + 1, v.y].y;
if (v.y > 0)
heatTransfer += (Temperature[v.x, v.y - 1] - temp) * Conductivity[v.x, v.y].z * Conductivity[v.x, v.y - 1].x;
if (v.y < hullData.Shape.Height - 1)
heatTransfer += (Temperature[v.x, v.y + 1] - temp) * Conductivity[v.x, v.y].x * Conductivity[v.x, v.y + 1].z;;
newTemp[v.x, v.y] = Temperature[v.x, v.y] + heatTransfer * min(ItemManager.GameplaySettings.HeatConductionMultiplier * delta,1) / ThermalMass[v.x,v.y];
// For all cells on the border of the entity, radiate some heat into space, increasing the visibility of the ship
if (!hullData.InteriorCells[v])
{
var rad = pow(newTemp[v.x, v.y], ItemManager.GameplaySettings.HeatRadiationExponent) *
ItemManager.GameplaySettings.HeatRadiationMultiplier;
newTemp[v.x, v.y] -= rad * delta;
radiation += rad;
}
}
VisibilitySources[this] = radiation;
Temperature = newTemp;
if (Active)
{
foreach (var equippedItem in Equipment)
foreach (var equippedItem in _orderedEquipment)
{
equippedItem.Update(delta);
}
@ -541,8 +608,6 @@ public class EquippedItem
[JsonProperty("item"), Key(0)] public EquippableItem EquippableItem;
[JsonProperty("position"), Key(1)] public int2 Position;
[JsonProperty("temperature"), Key(2)] public float Temperature;
[IgnoreMember]
public IBehavior[] Behaviors;
@ -550,15 +615,39 @@ public class EquippedItem
[IgnoreMember]
public BehaviorGroup[] BehaviorGroups;
public Shape InsetShape { get; }
public int SortPosition;
public float Temperature
{
get
{
float sum = 0;
foreach (var x in InsetShape.Coordinates) sum += _entity.Temperature[x.x, x.y];
return sum/InsetShape.Coordinates.Length;
}
}
protected readonly ItemManager _itemManager;
private readonly EquippableItemData _data;
private Entity _entity;
public EquippedItem(ItemManager itemManager, EquippableItem item, int2 position)
public EquippedItem(ItemManager itemManager, EquippableItem item, int2 position, Entity entity)
{
_itemManager = itemManager;
_data = _itemManager.GetData(item);
_entity = entity;
EquippableItem = item;
Position = position;
var hullData = itemManager.GetData(entity.Hull);
InsetShape = hullData.Shape.Inset(_data.Shape, position, item.Rotation);
}
public void AddHeat(float heat)
{
foreach(var hullCoord in InsetShape.Coordinates)
_entity.AddHeat(hullCoord, heat / InsetShape.Coordinates.Length);
}
public void Update(float delta)
@ -597,7 +686,7 @@ public class EquippedCargoBay : EquippedItem
public float ThermalMass { get; private set; }
public string Name { get; }
public EquippedCargoBay(ItemManager itemManager, EquippableItem item, int2 position, string name) : base(itemManager, item, position)
public EquippedCargoBay(ItemManager itemManager, EquippableItem item, int2 position, Entity entity, string name) : base(itemManager, item, position, entity)
{
Data = _itemManager.GetData(EquippableItem) as CargoBayData;
Name = name;
@ -867,7 +956,7 @@ public class EquippedDockingBay : EquippedCargoBay
public Ship DockedShip;
public int2 MaxSize => _data.MaxSize;
private DockingBayData _data;
public EquippedDockingBay(ItemManager itemManager, EquippableItem item, int2 position, string name) : base(itemManager, item, position, name)
public EquippedDockingBay(ItemManager itemManager, EquippableItem item, int2 position, Entity entity, string name) : base(itemManager, item, position, entity, name)
{
_data = _itemManager.GetData(EquippableItem) as DockingBayData;
}

View file

@ -5,7 +5,6 @@ using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Text.RegularExpressions;
using Grpc.Core;
using LiteNetLib;
using MessagePack;
using Unity.Mathematics;

View file

@ -201,10 +201,10 @@ public abstract class ItemData : DatabaseEntry, INamedEntry
// Heat needed to change temperature of 1 gram by 1 degree
[InspectableField, JsonProperty("specificHeat"), Key(5)]
public float SpecificHeat;
public float SpecificHeat = 1;
// [InspectableField, JsonProperty("conductivity"), Key(6)]
// public float Conductivity;
[InspectableField, JsonProperty("conductivity"), Key(6)]
public float Conductivity = 1;
[IgnoreMember] public string EntryName
{
@ -233,10 +233,10 @@ public class SimpleCommodityData : ItemData
// [InspectableField, JsonProperty("floor"), Key(11)]
// public float Floor = 5f;
[InspectableField, JsonProperty("maxStackSize"), Key(6)]
[InspectableField, JsonProperty("maxStackSize"), Key(7)]
public int MaxStack = 10;
[InspectableField, JsonProperty("category"), Key(7)]
[InspectableField, JsonProperty("category"), Key(8)]
public SimpleCommodityCategory Category;
}
@ -248,17 +248,17 @@ public class SimpleCommodityData : ItemData
JsonConverter(typeof(JsonKnownTypesConverter<CraftedItemData>))]
public abstract class CraftedItemData : ItemData
{
[InspectableField, JsonProperty("ingredientQualityWeight"), Key(6)]
[InspectableField, JsonProperty("ingredientQualityWeight"), Key(7)]
public float IngredientQualityWeight = .5f;
}
[RethinkTable("Items"), Inspectable, MessagePackObject]
public class CompoundCommodityData : CraftedItemData
{
[InspectableDatabaseLink(typeof(PersonalityAttribute)), JsonProperty("demandProfile"), Key(7)]
[InspectableDatabaseLink(typeof(PersonalityAttribute)), JsonProperty("demandProfile"), Key(8)]
public Dictionary<Guid, float> DemandProfile = new Dictionary<Guid, float>();
[InspectableField, JsonProperty("category"), Key(8)]
[InspectableField, JsonProperty("category"), Key(9)]
public CompoundCommodityCategory Category;
}
@ -267,22 +267,22 @@ public class CompoundCommodityData : CraftedItemData
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<EquippableItemData>))]
public abstract class EquippableItemData : CraftedItemData
{
[InspectableTexture, JsonProperty("schematic"), Key(7)]
[InspectableTexture, JsonProperty("schematic"), Key(8)]
public string Schematic;
[InspectableField, JsonProperty("behaviors"), Key(8)]
[InspectableField, JsonProperty("behaviors"), Key(9)]
public List<BehaviorData> Behaviors = new List<BehaviorData>();
[InspectableField, JsonProperty("durability"), Key(9)]
[InspectableField, JsonProperty("durability"), Key(10)]
public float Durability;
[TemperatureInspectable, JsonProperty("minTemp"), Key(10)]
[TemperatureInspectable, JsonProperty("minTemp"), Key(11)]
public float MinimumTemperature;
[TemperatureInspectable, JsonProperty("maxTemp"), Key(11)]
[TemperatureInspectable, JsonProperty("maxTemp"), Key(12)]
public float MaximumTemperature;
[InspectableField, JsonProperty("durabilityExponent"), Key(12), SimplePerformanceStat]
[InspectableField, JsonProperty("durabilityExponent"), Key(13), SimplePerformanceStat]
public PerformanceStat DurabilityExponent = new PerformanceStat();
[IgnoreMember]
@ -296,7 +296,7 @@ public abstract class EquippableItemData : CraftedItemData
[RethinkTable("Items"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class GearData : EquippableItemData
{
[InspectableField, JsonProperty("hardpointType"), Key(13)]
[InspectableField, JsonProperty("hardpointType"), Key(14)]
public HardpointType Hardpoint;
[IgnoreMember] public override HardpointType HardpointType => Hardpoint;
@ -305,7 +305,7 @@ public class GearData : EquippableItemData
[RethinkTable("Items"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class CargoBayData : EquippableItemData
{
[InspectableField, JsonProperty("interiorShape"), Key(13)]
[InspectableField, JsonProperty("interiorShape"), Key(14)]
public Shape InteriorShape;
[IgnoreMember] public override HardpointType HardpointType => HardpointType.Tool;
}
@ -313,7 +313,7 @@ public class CargoBayData : EquippableItemData
[RethinkTable("Items"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class DockingBayData : CargoBayData
{
[InspectableField, JsonProperty("maxSize"), Key(14)]
[InspectableField, JsonProperty("maxSize"), Key(15)]
public int2 MaxSize;
[IgnoreMember] public override HardpointType HardpointType => HardpointType.Tool;
}
@ -321,16 +321,16 @@ public class DockingBayData : CargoBayData
[RethinkTable("Items"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class HullData : EquippableItemData
{
[InspectableField, JsonProperty("hardpoints"), Key(13)]
[InspectableField, JsonProperty("hardpoints"), Key(14)]
public List<HardpointData> Hardpoints = new List<HardpointData>();
[InspectablePrefab, JsonProperty("prefab"), Key(14)]
[InspectablePrefab, JsonProperty("prefab"), Key(15)]
public string Prefab;
[InspectableField, JsonProperty("hullType"), Key(15)]
[InspectableField, JsonProperty("hullType"), Key(16)]
public HullType HullType;
[InspectableField, JsonProperty("gridOffset"), Key(16)]
[InspectableField, JsonProperty("gridOffset"), Key(17)]
public float GridOffset;
[IgnoreMember]

View file

@ -97,5 +97,6 @@ public class GameplaySettings
public ExponentialLerp StartingGearQuality;
public float HeatRadiationExponent = 1;
public float HeatRadiationMultiplier = 1;
public float HeatConductionMultiplier = 1;
}

View file

@ -146,7 +146,7 @@ public class ZoneGenerator
Enumerable.Range(0, (int) (settings.AsteroidCount.Evaluate(beltData.Mass.Value * orbitMap[planet].Distance.Value)))
.Select(_ => new Asteroid
{
Distance = random.NextFloat(orbitMap[planet].Distance.Value, orbitMap[planet].Distance.Value + settings.AsteroidBeltWidth.Evaluate(orbitMap[planet].Distance.Value)),
Distance = orbitMap[planet].Distance.Value + random.NextFloat()*(random.NextFloat()-.5f)*settings.AsteroidBeltWidth.Evaluate(orbitMap[planet].Distance.Value),
Phase = random.NextFloat(),
Size = random.NextFloat(),
RotationSpeed = settings.AsteroidRotationSpeed.Evaluate(random.NextFloat())

View file

@ -13,6 +13,7 @@ using UnityEngine;
using UnityEngine.UI;
using Unity.Mathematics;
using UnityEngine.EventSystems;
using UnityEngine.Experimental.Rendering;
using static Unity.Mathematics.math;
using int2 = Unity.Mathematics.int2;
@ -23,8 +24,15 @@ public class InventoryPanel : MonoBehaviour
public TextMeshProUGUI Title;
public Button Dropdown;
public GridLayoutGroup Grid;
public Sprite[] NodeBackgroundTextures;
public Sprite[] NodeTextures;
public Prototype NodePrototype;
public RawImage TemperatureDisplay;
public Texture2D TemperatureColor;
public ExponentialLerp TemperatureColorCurve;
public ExponentialLerp TemperatureAlphaCurve;
public float MaxTemperature;
public bool FitToContent;
Subject<InventoryEventData> _onBeginDrag;
Subject<InventoryEventData> _onDrag;
@ -35,6 +43,8 @@ public class InventoryPanel : MonoBehaviour
private Entity _displayedEntity;
private EquippedCargoBay _displayedCargo;
private Texture2D _temperatureTexture;
private RectTransform _firstRect;
public EquippedItem FakeEquipment;
public ItemInstance FakeItem;
@ -56,32 +66,64 @@ public class InventoryPanel : MonoBehaviour
private void Start()
{
Dropdown.onClick.AddListener(() =>
if(Dropdown)
{
ContextMenu.Clear();
foreach (var ship in GameManager.AvailableShips())
Dropdown.onClick.AddListener(() =>
{
if (ship.CargoBays.Any())
ContextMenu.Clear();
foreach (var ship in GameManager.AvailableShips())
{
ContextMenu.AddDropdown(ship.Name,
ship.CargoBays
.Select<EquippedCargoBay, (string text, Action action, bool enabled)>((bay, index) =>
($"Bay {index}", () => Display(bay), true))
.Prepend(("Equipment", () => Display(ship), true)));
if (ship.CargoBays.Any())
{
ContextMenu.AddDropdown(ship.Name,
ship.CargoBays
.Select<EquippedCargoBay, (string text, Action action, bool enabled)>((bay, index) =>
($"Bay {index}", () => Display(bay), true))
.Prepend(("Equipment", () => Display(ship), true)));
}
else ContextMenu.AddOption(ship.Name, () => Display(ship));
}
else ContextMenu.AddOption(ship.Name, () => Display(ship));
}
foreach (var bay in GameManager.AvailableCargoBays())
{
ContextMenu.AddOption(bay.Name, () => Display(bay));
}
ContextMenu.Show();
});
foreach (var bay in GameManager.AvailableCargoBays())
{
ContextMenu.AddOption(bay.Name, () => Display(bay));
}
ContextMenu.Show();
});
}
}
public void Display(Entity entity)
private void Update()
{
if (_displayedEntity != null)
{
var hullData = GameManager.ItemManager.GetData(_displayedEntity.Hull) as HullData;
for(var x = 0; x < _temperatureTexture.width; x++)
{
for (var y = 0; y < _temperatureTexture.height; y++)
{
if (hullData.Shape[int2(x-1, y-1)])
{
var temp = _displayedEntity.Temperature[x - 1, y - 1] / MaxTemperature;
var color = TemperatureColor.GetPixelBilinear(TemperatureColorCurve.Evaluate(temp), 0);
color.a = TemperatureAlphaCurve.Evaluate(temp);
_temperatureTexture.SetPixel(x,y,color);
}
else
_temperatureTexture.SetPixel(x,y,new Color(0,0,0,0));
}
}
_temperatureTexture.Apply();
TemperatureDisplay.rectTransform.anchoredPosition = _firstRect.anchoredPosition - Vector2.one * Grid.cellSize * 1.5f;
}
}
public void Clear()
{
_displayedCargo = null;
_displayedEntity = null;
foreach(var empty in EmptyCells)
Destroy(empty);
EmptyCells.Clear();
@ -89,13 +131,38 @@ public class InventoryPanel : MonoBehaviour
foreach(var node in CellInstances.Values)
node.GetComponent<Prototype>().ReturnToPool();
CellInstances.Clear();
if(Title)
Title.text = "None";
}
public void Display(Entity entity)
{
Clear();
_displayedEntity = entity;
_displayedCargo = null;
_firstRect = null;
if(Title)
Title.text = entity.Name;
Title.text = entity.Name;
var hullData = GameManager.ItemManager.GetData(entity.Hull) as HullData;
if (FitToContent)
{
var gridRect = Grid.GetComponent<RectTransform>();
var rect = gridRect.rect;
Grid.cellSize = Vector2.one * (int) min(rect.width / (hullData.Shape.Width + 1), rect.height / (hullData.Shape.Height + 1));
}
_temperatureTexture = new Texture2D(
hullData.Shape.Width+2,
hullData.Shape.Height+2,
TextureFormat.RGBA32,
false, false);
TemperatureDisplay.gameObject.SetActive(true);
TemperatureDisplay.texture = _temperatureTexture;
var tempRect = TemperatureDisplay.rectTransform;
tempRect.sizeDelta = Grid.cellSize * new Vector2(hullData.Shape.Width + 2, hullData.Shape.Height + 2);
//tempRect.anchoredPosition =
//FakeOccupancy = new Shape(hullData.Shape.Width, hullData.Shape.Height);
//IgnoreOccupancy = new Shape(hullData.Shape.Width, hullData.Shape.Height);
Grid.constraintCount = hullData.Shape.Width;
@ -105,11 +172,15 @@ public class InventoryPanel : MonoBehaviour
{
var empty = new GameObject("Empty Node", typeof(RectTransform));
empty.transform.SetParent(Grid.transform);
if (!_firstRect)
_firstRect = empty.GetComponent<RectTransform>();
EmptyCells.Add(empty);
}
else
{
var cell = NodePrototype.Instantiate<InventoryCell>();
if (!_firstRect)
_firstRect = cell.GetComponent<RectTransform>();
cell.PointerClickTrigger.OnPointerClickAsObservable()
.Subscribe(data => _onClick?.OnNext(new InventoryEntityEventData(data, v, entity)));
cell.BeginDragTrigger.OnBeginDragAsObservable()
@ -130,18 +201,13 @@ public class InventoryPanel : MonoBehaviour
public void Display(EquippedCargoBay cargo)
{
foreach(var empty in EmptyCells)
Destroy(empty);
EmptyCells.Clear();
Clear();
foreach(var node in CellInstances.Values)
node.GetComponent<Prototype>().ReturnToPool();
CellInstances.Clear();
_displayedEntity = null;
_displayedCargo = cargo;
TemperatureDisplay.gameObject.SetActive(false);
Title.text = cargo.Name;
if(Title)
Title.text = cargo.Name;
// FakeOccupancy = new Shape(cargo.Data.InteriorShape.Width, cargo.Data.InteriorShape.Height);
// IgnoreOccupancy = new Shape(cargo.Data.InteriorShape.Width, cargo.Data.InteriorShape.Height);
@ -230,12 +296,14 @@ public class InventoryPanel : MonoBehaviour
spriteIndex += 1 << i;
}
var bgSpriteIndex = spriteIndex;
if (item != null)
spriteIndex += 1 << 8;
var image = CellInstances[v].GetComponentInChildren<Image>();
image.sprite = NodeTextures[spriteIndex];
image.color = GetColor(v);
CellInstances[v].Background.sprite = NodeBackgroundTextures[bgSpriteIndex];
CellInstances[v].Icon.sprite = NodeTextures[spriteIndex];
CellInstances[v].Icon.color = GetColor(v);
}
}
else if(_displayedCargo != null)
@ -257,13 +325,15 @@ public class InventoryPanel : MonoBehaviour
for(int i = 0; i < 8; i++)
if (ItemMatch(_offsets[i]))
spriteIndex += 1 << i;
var bgSpriteIndex = spriteIndex;
if (item != null)
spriteIndex += 1 << 8;
var image = CellInstances[v].GetComponentInChildren<Image>();
image.sprite = NodeTextures[spriteIndex];
image.color = GetColor(v);
CellInstances[v].Background.sprite = NodeBackgroundTextures[bgSpriteIndex];
CellInstances[v].Icon.sprite = NodeTextures[spriteIndex];
CellInstances[v].Icon.color = GetColor(v);
}
}
}

View file

@ -465,6 +465,7 @@ public class PropertiesPanel : MonoBehaviour
Clear();
if (item.EquippableItem != null)
{
AddProperty("Temperature", () => (item.Temperature - 273.15f).SignificantDigits(Context.GameplaySettings.SignificantDigits));
AddItemProperties(entity, item.EquippableItem);
foreach (var behavior in item.Behaviors)
{