Build typed Aetheria client surfaces

This commit is contained in:
Meta Vens 2026-06-25 18:09:33 +01:00
commit 2e96660d48
246 changed files with 37893 additions and 6728 deletions

View file

@ -45,14 +45,54 @@ public class ActionBarSlot : MonoBehaviour
public abstract class ActionBarBinding
{
public Entity Entity { get; }
protected AetheriaClient Client { get; }
protected ActionBarSlot Slot { get; }
protected GameSettings Settings { get; }
private AetheriaRuntimeCatalogSnapshot _catalog;
public abstract void Activate();
public abstract void Deactivate();
public abstract void Update();
public ActionBarBinding(Entity entity, ActionBarSlot slot)
protected ActionBarBinding(Entity entity, ActionBarSlot slot, AetheriaClient client, GameSettings settings)
{
Entity = entity;
Slot = slot;
Client = client;
Settings = settings;
}
protected bool TrySubmit(Action<AetheriaControl> submit, string label)
{
if (Client == null || submit == null)
return false;
try
{
submit(Client.Control);
return true;
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to send Aetheria daemon action-bar {label} operation; operation not submitted: {ex.Message}");
return false;
}
}
protected AetheriaRuntimeCatalogItem FindCatalogItem(ItemInstance item)
{
if (item == null || string.IsNullOrWhiteSpace(item.ItemKey) || Client == null)
return null;
try
{
_catalog ??= Client.OpenRuntimeCatalog();
return _catalog?.FindItem(item.ItemKey);
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria runtime catalog for action-bar binding: {ex.Message}");
return null;
}
}
}
@ -63,7 +103,9 @@ public class ActionBarConsumableBinding : ActionBarBinding
public ActionBarConsumableBinding(
Entity entity,
ActionBarSlot slot,
AetheriaRuntimeCatalogItem target) : base(entity, slot)
AetheriaClient client,
GameSettings settings,
AetheriaRuntimeCatalogItem target) : base(entity, slot, client, settings)
{
Target = target;
Slot.QuantityRemaining.gameObject.SetActive(true);
@ -73,7 +115,9 @@ public class ActionBarConsumableBinding : ActionBarBinding
public override void Activate()
{
ActionGameManager.Instance.RequestActionBarConsumable(TargetItemKey);
TrySubmit(
operations => operations.ActivateConsumable(TargetItemKey),
"consumable");
}
public override void Deactivate()
@ -111,7 +155,13 @@ public class ActionBarGearBinding : ActionBarBinding
public string TargetItemKey => Item?.EquippableItem?.ItemKey ?? "";
public ActionBarGearBinding(Entity entity, ActionBarSlot slot, EquippedItem item, IActivatedBehavior behavior) : base(entity, slot)
public ActionBarGearBinding(
Entity entity,
ActionBarSlot slot,
AetheriaClient client,
GameSettings settings,
EquippedItem item,
IActivatedBehavior behavior) : base(entity, slot, client, settings)
{
Item = item;
Behavior = behavior;
@ -123,7 +173,7 @@ public class ActionBarGearBinding : ActionBarBinding
private Texture2D ResolveIconTexture()
{
var typedItem = FindTypedGearItem(Item.EquippableItem);
var typedItem = FindCatalogItem(Item.EquippableItem);
if (typedItem != null)
{
var actionBarIcon = LoadActionBarIcon(typedItem.ActionBarIcon);
@ -131,13 +181,13 @@ public class ActionBarGearBinding : ActionBarBinding
return actionBarIcon;
if (Enum.TryParse<WeaponType>(typedItem.WeaponType, out var weaponType))
return ActionGameManager.Instance.Settings.GetIcon(weaponType).texture;
return Settings.GetIcon(weaponType).texture;
if (Enum.TryParse<HardpointType>(typedItem.HardpointType, out var hardpointType))
return ActionGameManager.Instance.Settings.GetIcon(hardpointType).texture;
return Settings.GetIcon(hardpointType).texture;
}
return ActionGameManager.Instance.Settings.GetIcon(HardpointType.Tool).texture;
return Settings.GetIcon(HardpointType.Tool).texture;
}
private static Texture2D LoadActionBarIcon(string path)
@ -154,21 +204,20 @@ public class ActionBarGearBinding : ActionBarBinding
return Resources.Load<Texture2D>(resourcePath);
}
private static AetheriaRuntimeCatalogItem FindTypedGearItem(ItemInstance item)
{
return ActionGameManager.RuntimeCatalog?.FindItem(item?.ItemKey ?? "");
}
public override void Activate()
{
Active = true;
ActionGameManager.Instance.RequestActionBarBehavior(EquipmentIndex, BehaviorIndex, true);
TrySubmit(
operations => operations.SetBehaviorActive(EquipmentIndex, BehaviorIndex, true),
"behavior activation");
}
public override void Deactivate()
{
Active = false;
ActionGameManager.Instance.RequestActionBarBehavior(EquipmentIndex, BehaviorIndex, false);
TrySubmit(
operations => operations.SetBehaviorActive(EquipmentIndex, BehaviorIndex, false),
"behavior activation");
}
public override void Update()
@ -181,7 +230,12 @@ public class ActionBarWeaponGroupBinding : ActionBarBinding
{
public int Group;
public ActionBarWeaponGroupBinding(Entity entity, ActionBarSlot slot, int group) : base(entity, slot)
public ActionBarWeaponGroupBinding(
Entity entity,
ActionBarSlot slot,
AetheriaClient client,
GameSettings settings,
int group) : base(entity, slot, client, settings)
{
Group = group;
slot.Label.gameObject.SetActive(true);
@ -191,12 +245,16 @@ public class ActionBarWeaponGroupBinding : ActionBarBinding
public override void Activate()
{
ActionGameManager.Instance.RequestActionBarWeaponGroup(Group, true);
TrySubmit(
operations => operations.SetWeaponGroupActive(Group, true),
"weapon-group");
}
public override void Deactivate()
{
ActionGameManager.Instance.RequestActionBarWeaponGroup(Group, false);
TrySubmit(
operations => operations.SetWeaponGroupActive(Group, false),
"weapon-group");
}
public override void Update()

File diff suppressed because it is too large Load diff

View file

@ -18,10 +18,8 @@ public sealed class AetheriaDaemonObserver : MonoBehaviour
private readonly AetheriaRuntimeDaemonObservationCursor _cursor = new AetheriaRuntimeDaemonObservationCursor();
private float _nextPollTime;
private AetheriaRuntimeDaemonOperationClient _operationClient;
private AetheriaRuntimeDaemonOperationsClient _operations;
private AetheriaRuntimeVerseClient _verseClient;
private string _verseClientStatePath;
private AetheriaClient _client;
private string _clientStatePath;
private AetheriaDaemonSoaMemoryMap _soaMemoryMap;
private AetheriaDaemonRenderNativeView _renderNativeView;
@ -36,34 +34,11 @@ public sealed class AetheriaDaemonObserver : MonoBehaviour
public AetheriaDaemonSoaMemoryMap LastSoaMemoryMap => _soaMemoryMap;
public AetheriaDaemonRenderNativeView LastRenderNativeView => _renderNativeView;
public bool HasRenderNativeView => _renderNativeView.IsCreated;
public AetheriaRuntimeDaemonOperationsClient Operations =>
_operations ??= new AetheriaRuntimeDaemonOperationsClient(SendOperation);
public AetheriaClient Client => ResolveClient();
public AetheriaControl Control => Client.Control;
public event Action<AetheriaRuntimeObservedDaemonState, AetheriaRuntimeDaemonObservationResult> ObservedDaemonStateChanged;
internal AetheriaRuntimeDaemonCommandEnvelope SendOperation(
Func<AetheriaRuntimeDaemonOperationClient, AetheriaRuntimeObservedDaemonState, AetheriaRuntimeDaemonCommandEnvelope> submit)
{
if (submit == null)
{
throw new ArgumentNullException(nameof(submit));
}
_operationClient ??= new AetheriaRuntimeDaemonOperationClient(
ActionGameManager.RuntimeStateFilePath,
clientId,
LastObservedState?.Frame.SessionId ?? "local");
var envelope = submit(_operationClient, LastObservedState);
if (logChanges)
{
Debug.Log($"Submitted Aetheria daemon operation {envelope.Kind}: {envelope.CommandId}");
}
return envelope;
}
private void Update()
{
if (!pollInUpdate || Time.unscaledTime < _nextPollTime)
@ -117,38 +92,42 @@ public sealed class AetheriaDaemonObserver : MonoBehaviour
private void OnDisable()
{
DisposeVerseClient();
DisposeClient();
DisposeSoaMemoryMap();
}
private AetheriaRuntimeObservedDaemonState ReadObservedDaemonState()
{
var client = ResolveVerseClient();
return client.GetObservedDaemonStateAsync().GetAwaiter().GetResult();
return ResolveClient().ObserveAsync().GetAwaiter().GetResult();
}
private AetheriaRuntimeVerseClient ResolveVerseClient()
private AetheriaClient ResolveClient()
{
var statePath = ActionGameManager.RuntimeStateFilePath;
if (_verseClient != null && string.Equals(_verseClientStatePath, statePath, StringComparison.Ordinal))
var statePath = AetheriaUnityRuntimePaths.RuntimeStateFilePath;
if (_client != null && string.Equals(_clientStatePath, statePath, StringComparison.Ordinal))
{
return _verseClient;
return _client;
}
DisposeVerseClient();
_verseClient = AetheriaRuntimeVerseClient
.OpenAsync(statePath, clientId, startServer: false, pullOnOpen: true)
DisposeClient();
_client = AetheriaClient
.OpenAsync(
statePath,
clientId,
LastObservedState?.Frame.SessionId ?? "local",
startServer: false,
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_verseClientStatePath = statePath;
return _verseClient;
_clientStatePath = statePath;
return _client;
}
private void DisposeVerseClient()
private void DisposeClient()
{
_verseClient?.Dispose();
_verseClient = null;
_verseClientStatePath = null;
_client?.Dispose();
_client = null;
_clientStatePath = null;
}
private void RemapSoaView(AetheriaRuntimeObservedDaemonState observed)

View file

@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: c70095f8b49f42446aa3b0b9cb76356f

View file

@ -140,9 +140,7 @@ public sealed class AetheriaDaemonRenderBuffer : MonoBehaviour
using var writtenCount = new NativeArray<int>(1, Allocator.TempJob);
var job = new AetheriaDaemonRenderGroupMatrixJob
{
PositionX = view.PositionX,
PositionY = view.PositionY,
PositionZ = view.PositionZ,
Position = view.Position,
RotationRadians = view.RotationRadians,
PhysicsBodyRadius = view.PhysicsBodyRadius,
RenderScale = view.RenderScale,

View file

@ -104,9 +104,7 @@ public sealed class AetheriaDaemonRenderGroupBatch : IDisposable
using var writtenCount = new NativeArray<int>(1, Allocator.TempJob);
var job = new AetheriaDaemonRenderGroupMatrixJob
{
PositionX = view.PositionX,
PositionY = view.PositionY,
PositionZ = view.PositionZ,
Position = view.Position,
RotationRadians = view.RotationRadians,
PhysicsBodyRadius = view.PhysicsBodyRadius,
RenderScale = view.RenderScale,

View file

@ -7,13 +7,7 @@ using Unity.Mathematics;
public struct AetheriaDaemonRenderGroupMatrixJob : IJob
{
[ReadOnly]
public NativeArray<float> PositionX;
[ReadOnly]
public NativeArray<float> PositionY;
[ReadOnly]
public NativeArray<float> PositionZ;
public NativeArray<float3> Position;
[ReadOnly]
public NativeArray<float> RotationRadians;
@ -51,7 +45,7 @@ public struct AetheriaDaemonRenderGroupMatrixJob : IJob
public void Execute()
{
var written = 0;
for (var index = 0; index < PositionX.Length; index++)
for (var index = 0; index < Position.Length; index++)
{
if (HasRenderGroupFilter && RenderGroupId[index] != TargetRenderGroupId)
{
@ -73,7 +67,7 @@ public struct AetheriaDaemonRenderGroupMatrixJob : IJob
break;
}
var position = new float3(PositionX[index], PositionY[index], PositionZ[index]);
var position = Position[index];
var rotation = HasRotation
? quaternion.RotateY(RotationRadians[index])
: quaternion.identity;

View file

@ -7,13 +7,7 @@ using Unity.Mathematics;
public struct AetheriaDaemonRenderMatrixJob : IJobParallelFor
{
[ReadOnly]
public NativeArray<float> PositionX;
[ReadOnly]
public NativeArray<float> PositionY;
[ReadOnly]
public NativeArray<float> PositionZ;
public NativeArray<float3> Position;
[ReadOnly]
public NativeArray<float> RotationRadians;
@ -34,7 +28,7 @@ public struct AetheriaDaemonRenderMatrixJob : IJobParallelFor
public void Execute(int index)
{
var position = new float3(PositionX[index], PositionY[index], PositionZ[index]);
var position = Position[index];
var rotation = HasRotation
? quaternion.RotateY(RotationRadians[index])
: quaternion.identity;

View file

@ -9,13 +9,9 @@ public struct AetheriaDaemonRenderNativeView
public long Generation;
public int Count;
public NativeArray<int> EntityIndex;
public NativeArray<float> PositionX;
public NativeArray<float> PositionY;
public NativeArray<float> PositionZ;
public NativeArray<float3> Position;
public NativeArray<float> RotationRadians;
public NativeArray<float> VelocityX;
public NativeArray<float> VelocityY;
public NativeArray<float> VelocityZ;
public NativeArray<float3> Velocity;
public NativeArray<float> PhysicsBodyRadius;
public NativeArray<float> PhysicsBodyMass;
public NativeArray<float> PhysicsBodyInverseMass;
@ -26,13 +22,11 @@ public struct AetheriaDaemonRenderNativeView
public bool IsCreated =>
Count > 0 &&
PositionX.IsCreated &&
PositionY.IsCreated &&
PositionZ.IsCreated;
Position.IsCreated;
public bool HasRotation => RotationRadians.IsCreated;
public bool HasEntityIndex => EntityIndex.IsCreated;
public bool HasVelocity => VelocityX.IsCreated && VelocityY.IsCreated && VelocityZ.IsCreated;
public bool HasVelocity => Velocity.IsCreated;
public bool HasPhysicsRadius => PhysicsBodyRadius.IsCreated;
public bool HasPhysicsMass => PhysicsBodyMass.IsCreated;
public bool HasPhysicsInverseMass => PhysicsBodyInverseMass.IsCreated;
@ -60,9 +54,7 @@ public struct AetheriaDaemonRenderNativeView
var job = new AetheriaDaemonRenderMatrixJob
{
PositionX = PositionX,
PositionY = PositionY,
PositionZ = PositionZ,
Position = Position,
RotationRadians = RotationRadians,
PhysicsBodyRadius = PhysicsBodyRadius,
RenderScale = RenderScale,
@ -89,33 +81,18 @@ public struct AetheriaDaemonRenderNativeView
if (!map.TryCreateFirstNativeArrayOfKind(
index,
AetheriaRuntimeDaemonSoaColumnKinds.PositionX,
out view.PositionX) ||
!map.TryCreateFirstNativeArrayOfKind(
index,
AetheriaRuntimeDaemonSoaColumnKinds.PositionY,
out view.PositionY) ||
!map.TryCreateFirstNativeArrayOfKind(
index,
AetheriaRuntimeDaemonSoaColumnKinds.PositionZ,
out view.PositionZ))
AetheriaRuntimeDaemonSoaColumnKinds.Position,
out view.Position))
{
view = default;
return false;
}
view.Count = view.PositionX.Length;
if (view.PositionY.Length != view.Count || view.PositionZ.Length != view.Count)
{
view = default;
return false;
}
view.Count = view.Position.Length;
TryAssignOptionalIntColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.EntityIndex, view.Count, out view.EntityIndex);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RotationRadians, view.Count, out view.RotationRadians);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.VelocityX, view.Count, out view.VelocityX);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.VelocityY, view.Count, out view.VelocityY);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.VelocityZ, view.Count, out view.VelocityZ);
TryAssignOptionalFloat3Column(index, map, AetheriaRuntimeDaemonSoaColumnKinds.Velocity, view.Count, out view.Velocity);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.PhysicsBodyRadius, view.Count, out view.PhysicsBodyRadius);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.PhysicsBodyMass, view.Count, out view.PhysicsBodyMass);
TryAssignOptionalColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.PhysicsBodyInverseMass, view.Count, out view.PhysicsBodyInverseMass);
@ -124,19 +101,39 @@ public struct AetheriaDaemonRenderNativeView
TryAssignOptionalIntColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RenderLod, view.Count, out view.RenderLod);
TryAssignOptionalUIntColumn(index, map, AetheriaRuntimeDaemonSoaColumnKinds.RenderGroupId, view.Count, out view.RenderGroupId);
if ((view.VelocityX.IsCreated || view.VelocityY.IsCreated || view.VelocityZ.IsCreated) &&
!view.HasVelocity)
{
view.VelocityX = default;
view.VelocityY = default;
view.VelocityZ = default;
}
view.FrameId = index.View.FrameId;
view.Generation = index.View.Generation;
return true;
}
private static bool TryAssignOptionalFloat3Column(
AetheriaRuntimeDaemonSoaViewIndex index,
AetheriaDaemonSoaMemoryMap map,
string kind,
int expectedCount,
out NativeArray<float3> array)
{
array = default;
if (!index.TryGetFirstColumnOfKind(kind, out _))
{
return false;
}
if (!map.TryCreateFirstNativeArrayOfKind(index, kind, out array))
{
array = default;
return false;
}
if (array.Length == expectedCount)
{
return true;
}
array = default;
return false;
}
private static bool TryAssignOptionalColumn(
AetheriaRuntimeDaemonSoaViewIndex index,
AetheriaDaemonSoaMemoryMap map,

View file

@ -0,0 +1,13 @@
/* 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 sealed class AetheriaUnityActionBarBinding
{
public string ControlPath { get; set; } = "";
public string Kind { get; set; } = "";
public string ItemKey { get; set; } = "";
public int EquipmentIndex { get; set; } = -1;
public int BehaviorIndex { get; set; } = -1;
public int WeaponGroup { get; set; } = -1;
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: af36b057bd1c2ba46adad018b02fd568

View file

@ -0,0 +1,22 @@
/* 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;
public sealed class AetheriaUnityActionBarBindingAdapter
{
private readonly AetheriaUnityActionBarPresentation _presentation;
public AetheriaUnityActionBarBindingAdapter(
AetheriaUnityActionBarPresentation presentation)
{
_presentation = presentation ?? throw new ArgumentNullException(nameof(presentation));
}
public void ApplyBindings(IReadOnlyList<AetheriaUnityActionBarBinding> bindings)
{
_presentation.ApplyLocalBindings();
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c70aab770e351924eb213421f9096e22

View file

@ -0,0 +1,275 @@
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
public sealed class AetheriaUnityActionBarPresentation
{
private IReadOnlyList<ActionBarSlot> _slots = Array.Empty<ActionBarSlot>();
private AetheriaRuntimeCatalogSnapshot _catalog;
private GameSettings _settings;
private Func<Entity> _resolveEntity = () => null;
private Func<AetheriaClient> _resolveClient = () => null;
private IReadOnlyList<AetheriaUnityActionBarBinding> _localBindings =
Array.Empty<AetheriaUnityActionBarBinding>();
public void Bind(
IReadOnlyList<ActionBarSlot> slots,
AetheriaRuntimeCatalogSnapshot catalog,
GameSettings settings,
Func<Entity> resolveEntity,
Func<AetheriaClient> resolveClient)
{
_slots = slots ?? Array.Empty<ActionBarSlot>();
_catalog = catalog;
_settings = settings;
_resolveEntity = resolveEntity ?? (() => null);
_resolveClient = resolveClient ?? (() => null);
}
public int SlotCount => _slots?.Count ?? 0;
public string SlotLabel(int slotIndex)
{
var slot = ResolveSlot(slotIndex);
if (slot == null)
return "";
var controlPath = slot.ControlPath ?? "";
if (string.IsNullOrWhiteSpace(controlPath))
return "Action Bar";
var slashIndex = controlPath.LastIndexOf('/');
return slashIndex >= 0 && slashIndex < controlPath.Length - 1
? controlPath.Substring(slashIndex + 1)
: controlPath;
}
public string BindingLabel(int slotIndex)
{
var slot = ResolveSlot(slotIndex);
return slot?.Binding switch
{
ActionBarWeaponGroupBinding weaponGroup => $"G{weaponGroup.Group + 1}",
ActionBarConsumableBinding consumable => consumable.Target?.Name ?? "Consumable",
ActionBarGearBinding gear => _catalog?.FindItem(gear.Item?.EquippableItem?.ItemKey ?? "")?.Name ?? "Gear",
_ => "Empty"
};
}
public bool TryResolveControlPath(int slotIndex, out string controlPath)
{
controlPath = ResolveSlot(slotIndex)?.ControlPath ?? "";
return !string.IsNullOrWhiteSpace(controlPath);
}
public void RequestBinding(ActionBarSlot slot, DragObject dragAction)
{
var entity = _resolveEntity();
if (slot == null || dragAction == null || entity == null)
return;
var binding = CreateBindingCommit(slot, entity, dragAction);
if (binding == null ||
string.IsNullOrWhiteSpace(binding.ControlPath) ||
string.IsNullOrWhiteSpace(binding.Kind))
{
return;
}
SetLocalBinding(binding);
ApplyLocalBindings();
}
public bool RequestWeaponGroupBinding(int slotIndex, int groupIndex)
{
if (groupIndex < 0 || !TryResolveControlPath(slotIndex, out var controlPath))
return false;
SetLocalBinding(new AetheriaUnityActionBarBinding
{
ControlPath = controlPath,
Kind = "weapon_group",
ItemKey = "",
EquipmentIndex = -1,
BehaviorIndex = -1,
WeaponGroup = groupIndex
});
ApplyLocalBindings();
return true;
}
public bool ClearBinding(int slotIndex)
{
if (!TryResolveControlPath(slotIndex, out var controlPath))
return false;
_localBindings = (_localBindings ?? Array.Empty<AetheriaUnityActionBarBinding>())
.Where(binding => !string.Equals(binding?.ControlPath ?? "", controlPath, StringComparison.Ordinal))
.ToArray();
ApplyLocalBindings();
return true;
}
public void ApplyLocalBindings()
{
ApplyBindings(_resolveEntity(), _localBindings);
}
public void ApplyBindings(
Entity entity,
IReadOnlyList<AetheriaUnityActionBarBinding> bindings)
{
if (_slots == null || _slots.Count == 0)
return;
foreach (var slot in _slots)
slot.Binding = null;
if (entity == null || bindings == null || bindings.Count == 0)
return;
var slotsByControlPath = _slots
.Where(slot => !string.IsNullOrWhiteSpace(slot?.ControlPath))
.GroupBy(slot => slot.ControlPath, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => group.First(), StringComparer.Ordinal);
foreach (var binding in bindings)
{
if (binding == null ||
string.IsNullOrWhiteSpace(binding.ControlPath) ||
!slotsByControlPath.TryGetValue(binding.ControlPath, out var slot))
{
continue;
}
var slotBinding = CreateBinding(slot, entity, binding);
if (slotBinding != null)
slot.Binding = slotBinding;
}
}
public ActionBarBinding CreateBinding(ActionBarSlot slot, Entity entity, DragObject dragAction)
{
var binding = CreateBindingCommit(slot, entity, dragAction);
return binding == null ? null : CreateBinding(slot, entity, binding);
}
private AetheriaUnityActionBarBinding CreateBindingCommit(
ActionBarSlot slot,
Entity entity,
DragObject dragAction)
{
if (slot == null || entity == null || dragAction == null)
return null;
switch (dragAction)
{
case EquippedItemDragObject equippedItemDragAction:
var equippedItem = equippedItemDragAction.EquippedItem;
var trigger = equippedItem?.GetBehavior<IActivatedBehavior>();
var equipmentIndex = equippedItem == null ? -1 : entity.Equipment.IndexOf(equippedItem);
var behaviorIndex = equippedItem?.Behaviors == null ? -1 : Array.IndexOf(equippedItem.Behaviors, trigger);
return trigger == null || equipmentIndex < 0 || behaviorIndex < 0
? null
: new AetheriaUnityActionBarBinding
{
ControlPath = slot.ControlPath ?? "",
Kind = "gear",
ItemKey = equippedItem.EquippableItem?.ItemKey ?? "",
EquipmentIndex = equipmentIndex,
BehaviorIndex = behaviorIndex
};
case ItemInstanceDragObject itemInstanceDragAction:
var consumable = FindConsumable(itemInstanceDragAction.Item);
return consumable == null
? null
: new AetheriaUnityActionBarBinding
{
ControlPath = slot.ControlPath ?? "",
Kind = "consumable",
ItemKey = consumable.ItemKey ?? ""
};
default:
return null;
}
}
private void SetLocalBinding(AetheriaUnityActionBarBinding binding)
{
if (binding == null || string.IsNullOrWhiteSpace(binding.ControlPath))
return;
_localBindings = (_localBindings ?? Array.Empty<AetheriaUnityActionBarBinding>())
.Where(existing => !string.Equals(existing?.ControlPath ?? "", binding.ControlPath, StringComparison.Ordinal))
.Concat(new[] { binding })
.ToArray();
}
private ActionBarBinding CreateBinding(
ActionBarSlot slot,
Entity entity,
AetheriaUnityActionBarBinding binding)
{
if (slot == null || entity == null || binding == null)
return null;
var client = _resolveClient();
switch (binding.Kind)
{
case "consumable":
var consumable = _catalog?.FindItem(binding.ItemKey ?? "");
return consumable != null &&
string.Equals(consumable.Category, AetheriaRuntimeItemCategories.Consumable, StringComparison.Ordinal)
? new ActionBarConsumableBinding(entity, slot, client, _settings, consumable)
: null;
case "gear":
if (binding.EquipmentIndex < 0 || binding.EquipmentIndex >= entity.Equipment.Count)
return null;
var equippedItem = entity.Equipment[binding.EquipmentIndex];
var behaviors = equippedItem?.Behaviors;
if (equippedItem == null ||
!string.Equals(equippedItem.EquippableItem?.ItemKey ?? "", binding.ItemKey ?? "", StringComparison.Ordinal) ||
behaviors == null ||
binding.BehaviorIndex < 0 ||
binding.BehaviorIndex >= behaviors.Length)
{
return null;
}
if (!(behaviors[binding.BehaviorIndex] is IActivatedBehavior activatedBehavior))
return null;
return new ActionBarGearBinding(entity, slot, client, _settings, equippedItem, activatedBehavior);
case "weapon_group":
return entity.WeaponGroups != null &&
binding.WeaponGroup >= 0 &&
binding.WeaponGroup < entity.WeaponGroups.Length
? new ActionBarWeaponGroupBinding(entity, slot, client, _settings, binding.WeaponGroup)
: null;
default:
return null;
}
}
private AetheriaRuntimeCatalogItem FindConsumable(ItemInstance item)
{
var typedItem = _catalog?.FindItem(item?.ItemKey ?? "");
return typedItem != null &&
string.Equals(typedItem.Category, AetheriaRuntimeItemCategories.Consumable, StringComparison.Ordinal)
? typedItem
: null;
}
private ActionBarSlot ResolveSlot(int slotIndex)
{
return _slots != null &&
slotIndex >= 0 &&
slotIndex < _slots.Count
? _slots[slotIndex]
: null;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0f239f607245e8143805587f4c34fbee

View file

@ -0,0 +1,38 @@
/* 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 sealed class AetheriaUnityCockpitHudShell
{
public InventoryPanel ShipPanel { get; set; }
public InventoryPanel TargetShipPanel { get; set; }
public SchematicDisplay SchematicDisplay { get; set; }
public SchematicDisplay TargetSchematicDisplay { get; set; }
public PlaceUIElementWorldspace TargetIndicator { get; set; }
public void SetRenderSettings(AetheriaRuntimeDaemonRenderSettings renderSettings)
{
SchematicDisplay?.SetRenderSettings(renderSettings);
TargetSchematicDisplay?.SetRenderSettings(renderSettings);
}
public void UpdatePlayer(Entity currentEntity)
{
ShipPanel?.Display(currentEntity, true);
SchematicDisplay?.ShowShip(currentEntity);
}
public void UpdateTarget(Entity target, Entity currentEntity)
{
if (TargetIndicator != null)
TargetIndicator.gameObject.SetActive(target != null);
if (TargetShipPanel != null)
TargetShipPanel.gameObject.SetActive(target != null);
if (target == null)
return;
TargetShipPanel?.Display(target, true);
TargetSchematicDisplay?.ShowShip(target, currentEntity);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 027535b4501541f4aa60df9ae50d9eed

View file

@ -0,0 +1,87 @@
/* 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 UnityEngine;
using UnityEngine.Rendering.PostProcessing;
using float3 = Unity.Mathematics.float3;
public sealed class AetheriaUnityCurrentEntityBinder
{
public ZoneRenderer ZoneRenderer { get; set; }
public PostProcessVolume DeathPost { get; set; }
public CanvasGroup GameplayUI { get; set; }
public AetheriaUnityObservedDockingIndex ObservedDocking { get; set; }
public AetheriaUnityCurrentEntityPresentation CurrentEntityPresentation { get; set; }
public AetheriaUnityTargetPresentation TargetPresentation { get; set; }
public Func<Entity> GetCurrentEntity { get; set; }
public Action<Entity> SetCurrentEntity { get; set; }
public Func<float3> GetViewDirection { get; set; }
public Action<float3> SetViewDirection { get; set; }
public Func<AetheriaRuntimeZoneRenderDocument> ResolveZoneRender { get; set; }
public Action<IReadOnlyList<AetheriaUnityActionBarBinding>> ApplyActionBarBindings { get; set; }
public Action EnablePlayerInput { get; set; }
public Action DisablePlayerInput { get; set; }
public Action<MusicType> PlayMusic { get; set; }
public Action<Entity> UpdateTargetPanel { get; set; }
public void RestoreBinding(Entity currentEntity)
{
if (ObservedDocking != null &&
ObservedDocking.TryResolveDockingBay(currentEntity, out var dockParent, out _))
{
SetCurrentEntity?.Invoke(currentEntity);
ApplyActionBarBindings?.Invoke(Array.Empty<AetheriaUnityActionBarBinding>());
CurrentEntityPresentation?.BindDocked(
dockParent,
null,
ResolveZoneRender?.Invoke());
return;
}
BindUndocked(
currentEntity);
}
public void ClearBinding()
{
TargetPresentation?.ClearIndicators();
CurrentEntityPresentation?.ClearBinding();
DisablePlayerInput?.Invoke();
Cursor.lockState = CursorLockMode.None;
if (GameplayUI != null)
GameplayUI.gameObject.SetActive(false);
}
private void BindUndocked(Entity entity)
{
if (ZoneRenderer == null ||
!ZoneRenderer.TryGetEntityInstance(entity, out var entityInstance))
{
Debug.LogError($"Attempted to bind to entity {entity?.Name}, but ZoneRenderer has no daemon-indexed instance.");
return;
}
SetCurrentEntity?.Invoke(entity);
if (DeathPost != null)
DeathPost.weight = 0;
if (CultMath.math.length(entity.CultDirection) > .1f)
SetViewDirection?.Invoke((float3)AetheriaMath.ToUnityXZ(entity.CultDirection));
CurrentEntityPresentation?.BindUndocked(
entity,
entityInstance,
Array.Empty<AetheriaUnityActionBarBinding>(),
EnablePlayerInput,
PlayMusic,
SetCurrentEntity,
UpdateTargetPanel,
() => TargetPresentation?.ReconcileVisibleTargetIndicators(GetCurrentEntity?.Invoke()),
ApplyActionBarBindings);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c599c7371ae28e249bcf132744d4e547

View file

@ -0,0 +1,228 @@
/* 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 Cinemachine;
using GameCult.Aetheria.State.Verse;
using UniRx;
using UnityEngine;
public sealed class AetheriaUnityCurrentEntityPresentation
{
private readonly List<IDisposable> _shipSubscriptions = new List<IDisposable>();
private readonly List<IDisposable> _targetSubscriptions = new List<IDisposable>();
private float _hitMarkerTime;
public ZoneRenderer ZoneRenderer { get; set; }
public CinemachineVirtualCamera DockCamera { get; set; }
public CinemachineVirtualCamera FollowCamera { get; set; }
public MenuPanel Menu { get; set; }
public TradeMenu TradeMenu { get; set; }
public CanvasGroup GameplayUI { get; set; }
public InventoryPanel ShipPanel { get; set; }
public InventoryPanel TargetShipPanel { get; set; }
public SchematicDisplay SchematicDisplay { get; set; }
public SchematicDisplay TargetSchematicDisplay { get; set; }
public ImageTargetPresentation TargetImages { get; set; }
public AetheriaRuntimeCatalogSnapshot RuntimeCatalog { get; set; }
public PlaceUIElementWorldspace[] Crosshairs { get; set; } = Array.Empty<PlaceUIElementWorldspace>();
public Prototype LockIndicator { get; set; }
public GameObject HitMarker { get; set; }
public float HitMarkerDuration { get; set; }
public (HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)[] ArticulationGroups { get; private set; } =
Array.Empty<(HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)>();
public (LockWeapon targetLock, PlaceUIElementWorldspace indicator, Rotate spin)[] LockingIndicators { get; private set; } =
Array.Empty<(LockWeapon targetLock, PlaceUIElementWorldspace indicator, Rotate spin)>();
public void BindUndocked(
Entity entity,
EntityInstance entityInstance,
IReadOnlyList<AetheriaUnityActionBarBinding> actionBarBindings,
Action enablePlayerInput,
Action<MusicType> playMusic,
Action<Entity> updateCurrentEntity,
Action<Entity> updateTargetPanel,
Action reconcileVisibleTargetIndicators,
Action<IReadOnlyList<AetheriaUnityActionBarBinding>> applyActionBarBindings)
{
if (entity == null || entityInstance == null)
return;
updateCurrentEntity?.Invoke(entity);
ZoneRenderer.PerspectiveEntity = entity;
Menu.gameObject.SetActive(false);
DockCamera.enabled = false;
FollowCamera.enabled = true;
Cursor.lockState = CursorLockMode.Locked;
enablePlayerInput?.Invoke();
GameplayUI.gameObject.SetActive(true);
ShipPanel.Display(entity, true);
SchematicDisplay.ShowShip(entity);
FollowCamera.LookAt = entityInstance.LookAtPoint;
FollowCamera.Follow = entityInstance.transform;
ArticulationGroups = entity.Equipment
.Where(HasArticulatedWeaponBehavior)
.GroupBy(item => entityInstance
.GetBarrel(entity.Hardpoints[item.Position.x, item.Position.y])
.GetComponentInParent<ArticulationPoint>()?.Group ?? -1)
.Select((group, index) =>
{
return (
group.Select(item => entity.Hardpoints[item.Position.x, item.Position.y]).ToArray(),
group.Select(item => entityInstance.GetBarrel(entity.Hardpoints[item.Position.x, item.Position.y])).ToArray(),
Crosshairs[index]
);
}).ToArray();
foreach (var crosshair in Crosshairs)
crosshair.gameObject.SetActive(false);
foreach (var group in ArticulationGroups)
group.crosshair.gameObject.SetActive(true);
_shipSubscriptions.Add(entity.TargetedByCount.Subscribe(count =>
{
playMusic?.Invoke(count > 0 ? MusicType.Combat : MusicType.Overworld);
}));
_shipSubscriptions.Add(entity.Target.Subscribe(target =>
{
ClearTargetSubscriptions();
updateTargetPanel?.Invoke(target);
ConfigureTargetShieldPresentation(target);
if (target != null)
{
_targetSubscriptions.Add(target.IncomingHit.Where(e => e == entity).Subscribe(_ =>
{
HitMarker.SetActive(true);
_hitMarkerTime = HitMarkerDuration;
}));
}
}));
reconcileVisibleTargetIndicators?.Invoke();
LockingIndicators = entity.GetBehaviors<LockWeapon>()
.Select(x =>
{
var indicator = LockIndicator.Instantiate<PlaceUIElementWorldspace>();
return (x, indicator, indicator.GetComponent<Rotate>());
}).ToArray();
applyActionBarBindings?.Invoke(actionBarBindings ?? Array.Empty<AetheriaUnityActionBarBinding>());
}
public bool HasArticulatedWeaponBehavior(EquippedItem item)
{
return AetheriaUnityWeaponPresentationPolicy.HasArticulatedWeaponBehavior(RuntimeCatalog, item);
}
public void BindDocked(
Entity entity,
AetheriaRuntimeCurrentDockingDocument docking,
AetheriaRuntimeZoneRenderDocument zoneRender)
{
if (entity == null)
return;
TradeMenu.Inventory = entity.CargoBays.First();
ZoneRenderer.PerspectiveEntity = entity;
DockCamera.enabled = true;
FollowCamera.enabled = false;
var orbital = entity as OrbitalEntity;
if (orbital == null || !ZoneRenderer.TryGetEntityInstance(orbital, out var orbitalInstance))
{
Debug.LogError($"Attempted to dock at entity {entity.Name}, but ZoneRenderer has no daemon-indexed instance.");
return;
}
DockCamera.Follow = orbitalInstance.transform;
var parentOrbitPlanetBodyKey = ResolveDockParentBodyKey(orbital, docking, zoneRender);
if (ZoneRenderer.TryGetBodyView(parentOrbitPlanetBodyKey, out var parentBodyView))
DockCamera.LookAt = parentBodyView.Body.transform;
else DockCamera.LookAt = ZoneRenderer.ZoneRoot;
Menu.ShowTab(MenuTab.Inventory);
}
private static string ResolveDockParentBodyKey(
OrbitalEntity orbital,
AetheriaRuntimeCurrentDockingDocument docking,
AetheriaRuntimeZoneRenderDocument zoneRender)
{
if (orbital == null)
return "";
var bodyPoses = zoneRender?.BodyPoses ?? Array.Empty<AetheriaRuntimeZoneRenderBodyPose>();
var parentOrbitKey = bodyPoses
.FirstOrDefault(body => body != null &&
string.Equals(body.OrbitKey ?? "", orbital.OrbitKey, StringComparison.Ordinal))
?.ParentOrbitKey ?? docking?.DockParentParentOrbitKey ?? "";
return bodyPoses
.FirstOrDefault(body => body != null &&
string.Equals(body.OrbitKey ?? "", parentOrbitKey, StringComparison.Ordinal))
?.BodyKey ?? docking?.DockParentParentBodyKey ?? "";
}
public void ClearBinding()
{
foreach (var (_, indicator, _) in LockingIndicators)
indicator.GetComponent<Prototype>().ReturnToPool();
LockingIndicators = Array.Empty<(LockWeapon targetLock, PlaceUIElementWorldspace indicator, Rotate spin)>();
ArticulationGroups = Array.Empty<(HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)>();
foreach (var subscription in _shipSubscriptions)
subscription.Dispose();
_shipSubscriptions.Clear();
ClearTargetSubscriptions();
}
public void Tick(float deltaTime)
{
_hitMarkerTime -= deltaTime;
if (HitMarker.activeSelf && _hitMarkerTime < 0)
HitMarker.SetActive(false);
}
private void ClearTargetSubscriptions()
{
foreach (var subscription in _targetSubscriptions)
subscription.Dispose();
_targetSubscriptions.Clear();
}
private void ConfigureTargetShieldPresentation(Entity target)
{
if (target == null || TargetImages == null)
return;
if (target.Shield != null)
{
TargetImages.TargetShieldsBackground.color = new Color(TargetImages.ShieldColor.r, TargetImages.ShieldColor.g, TargetImages.ShieldColor.b, .4f);
TargetImages.TargetShieldsIcon.color = TargetImages.ShieldColor;
TargetImages.TargetShieldsIcon.sprite = TargetImages.ShieldIcon;
}
else
{
TargetImages.TargetShieldsBackground.color = new Color(TargetImages.NoShieldColor.r, TargetImages.NoShieldColor.g, TargetImages.NoShieldColor.b, .4f);
TargetImages.TargetShieldsIcon.color = TargetImages.NoShieldColor;
TargetImages.TargetShieldsIcon.sprite = TargetImages.NoShieldIcon;
}
}
}
public sealed class ImageTargetPresentation
{
public UnityEngine.UI.Image TargetShieldsBackground { get; set; }
public UnityEngine.UI.Image TargetShieldsIcon { get; set; }
public Color ShieldColor { get; set; }
public Color NoShieldColor { get; set; }
public Sprite ShieldIcon { get; set; }
public Sprite NoShieldIcon { get; set; }
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f5a7b36e50785fc45ab94ae5a03dd1d6

View file

@ -0,0 +1,263 @@
/* 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 Regex = System.Text.RegularExpressions.Regex;
public static class AetheriaUnityDaemonEntitySnapshotProjector
{
public static AetheriaRuntimeEntitySnapshot[] CreateSnapshots(
string runId,
AetheriaRuntimeZoneSnapshotCommit zone)
{
if (zone == null)
return Array.Empty<AetheriaRuntimeEntitySnapshot>();
return CreateSnapshots(runId, zone.ZoneIndex, zone.Entities);
}
public static AetheriaRuntimeEntitySnapshot[] CreateSnapshots(
string runId,
int zoneIndex,
IReadOnlyList<AetheriaRuntimeEntitySnapshotCommit> entities)
{
return (entities ?? Array.Empty<AetheriaRuntimeEntitySnapshotCommit>())
.Where(entity => entity != null)
.Select(entity => CreateSnapshot(runId, zoneIndex, entity))
.ToArray();
}
public static int EntityIndexFromRecordKey(string recordKey)
{
var match = Regex.Match(recordKey ?? "", @"\.entity\.(\d+)\.v1$");
return match.Success && int.TryParse(match.Groups[1].Value, out var index)
? index
: int.MaxValue;
}
public static string DaemonEntityRecordKey(string runId, int zoneIndex, int entityIndex)
{
return string.IsNullOrWhiteSpace(runId)
? ""
: $"global:aetheria.run_state.{runId}.zone.{zoneIndex}.entity.{entityIndex}.v1";
}
private static AetheriaRuntimeEntitySnapshot CreateSnapshot(
string runId,
int zoneIndex,
AetheriaRuntimeEntitySnapshotCommit entity)
{
return new AetheriaRuntimeEntitySnapshot(
DaemonEntityRecordKey(runId, zoneIndex, entity.EntityIndex),
entity.Name ?? "",
entity.Kind ?? "",
entity.PositionX,
entity.PositionY,
entity.PositionZ,
entity.DirectionX,
entity.DirectionY,
entity.FactionKey ?? "",
entity.HullItemKey ?? "",
CreateItemSlots(entity.Equipment),
CreateItemSlots(entity.CargoBays),
CreateItemSlots(entity.DockingBays),
(entity.ChildEntityIndices ?? Array.Empty<int>())
.Where(index => index >= 0)
.Select(index => DaemonEntityRecordKey(runId, zoneIndex, index))
.ToArray(),
(entity.WeaponGroups ?? Array.Empty<IReadOnlyList<int>>())
.Select(group => (IReadOnlyList<int>)(group ?? Array.Empty<int>()).ToArray())
.ToArray(),
(entity.StatGrids ?? Array.Empty<AetheriaRuntimeEntityStatGridCommit>())
.Select(grid => new AetheriaRuntimeEntityStatGridSnapshot(
grid.Name ?? "",
grid.Width,
grid.Height,
(grid.Values ?? Array.Empty<double>()).ToArray()))
.ToArray(),
entity.VelocityX,
entity.VelocityY,
entity.TargetEntityIndex < 0 ? "" : DaemonEntityRecordKey(runId, zoneIndex, entity.TargetEntityIndex),
entity.IsActive,
entity.HeatsinksEnabled,
entity.OverrideShutdown,
entity.TractorPower,
entity.Heatstroke,
entity.Hypothermia,
(entity.ActiveConsumables ?? Array.Empty<AetheriaRuntimeActiveConsumableCommit>())
.Select(consumable => new AetheriaRuntimeActiveConsumableSnapshot(
consumable.ItemKey ?? "",
consumable.Quality,
consumable.RemainingDuration,
consumable.Duration))
.ToArray(),
(entity.BehaviorProgress ?? Array.Empty<AetheriaRuntimeBehaviorProgressCommit>())
.Select(progress => new AetheriaRuntimeBehaviorProgressSnapshot(
progress.OwnerKind ?? "",
progress.OwnerIndex,
progress.BehaviorIndex,
progress.BehaviorKind ?? "",
progress.Progress))
.ToArray(),
CreateWeaponStates(runId, zoneIndex, entity.WeaponStates),
CreateBehaviorStates(entity.BehaviorStates),
CreateCargoBays(entity.CargoContents),
CreateCargoBays(entity.DockingBayContents),
(entity.DockingBayAssignments ?? Array.Empty<int>()).ToArray(),
entity.Visibility,
entity.VisibilitySourceCount,
(entity.Contacts ?? Array.Empty<AetheriaRuntimeEntityContactCommit>())
.Where(contact => contact != null && contact.TargetEntityIndex >= 0)
.Select(contact => new AetheriaRuntimeEntityContactSnapshot(
DaemonEntityRecordKey(runId, zoneIndex, contact.TargetEntityIndex),
contact.InfoGathered,
contact.Hostile,
contact.Visible))
.ToArray(),
entity.ShutdownPerformance);
}
private static AetheriaRuntimeEntityItemSlotSnapshot[] CreateItemSlots(
IReadOnlyList<AetheriaRuntimeLoadoutItemSlotCommit> slots)
{
return (slots ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotCommit>())
.Where(slot => slot?.Item != null)
.Select(slot => new AetheriaRuntimeEntityItemSlotSnapshot(
slot.X,
slot.Y,
slot.Item.ItemKey ?? "",
slot.Item.Quality,
slot.Item.Durability,
slot.Item.Quantity,
slot.Item.Enabled,
slot.Item.OverrideShutdown,
slot.Item.Temperature))
.ToArray();
}
private static AetheriaRuntimeCargoBayLoadoutSnapshot[] CreateCargoBays(
IReadOnlyList<AetheriaRuntimeCargoBayLoadoutCommit> cargoBays)
{
return (cargoBays ?? Array.Empty<AetheriaRuntimeCargoBayLoadoutCommit>())
.Select(bay => new AetheriaRuntimeCargoBayLoadoutSnapshot(
CreateLoadoutSlots(bay?.Items)))
.ToArray();
}
private static AetheriaRuntimeLoadoutItemSlotSnapshot[] CreateLoadoutSlots(
IReadOnlyList<AetheriaRuntimeLoadoutItemSlotCommit> slots)
{
return (slots ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotCommit>())
.Where(slot => slot?.Item != null)
.Select(slot => new AetheriaRuntimeLoadoutItemSlotSnapshot(
slot.X,
slot.Y,
new AetheriaRuntimeLoadoutItemSnapshot(
slot.Item.ItemKey ?? "",
slot.Item.Quality,
slot.Item.Durability,
slot.Item.Quantity,
slot.Item.Enabled,
slot.Item.OverrideShutdown,
slot.Item.Temperature)))
.ToArray();
}
private static AetheriaRuntimeWeaponStateSnapshot[] CreateWeaponStates(
string runId,
int zoneIndex,
IReadOnlyList<AetheriaRuntimeWeaponStateCommit> weaponStates)
{
return (weaponStates ?? Array.Empty<AetheriaRuntimeWeaponStateCommit>())
.Where(state => state != null)
.Select(state => new AetheriaRuntimeWeaponStateSnapshot(
state.OwnerKind ?? "",
state.OwnerIndex,
state.BehaviorIndex,
state.BehaviorKind ?? "",
state.Firing,
state.Ammo,
state.BurstRemaining,
state.BurstTimer,
state.BurstInterval,
state.CooldownProgress,
state.CoolingDown,
state.Charging,
state.Charged,
state.Charge,
state.Reloading,
state.ReloadProgress,
state.AmmoIntervalProgress,
state.LockProgress,
state.LockTargetEntityIndex < 0 ? "" : DaemonEntityRecordKey(runId, zoneIndex, state.LockTargetEntityIndex)))
.ToArray();
}
private static AetheriaRuntimeBehaviorStateSnapshot[] CreateBehaviorStates(
IReadOnlyList<AetheriaRuntimeBehaviorStateCommit> behaviorStates)
{
return (behaviorStates ?? Array.Empty<AetheriaRuntimeBehaviorStateCommit>())
.Where(state => state != null)
.Select(state => new AetheriaRuntimeBehaviorStateSnapshot(
state.OwnerKind ?? "",
state.OwnerIndex,
state.BehaviorIndex,
state.BehaviorKind ?? "",
state.Pinging,
state.PingCooldown,
state.PingLerp,
state.PingRadius,
state.PingedEntityCount,
state.RadiatorTemperature,
state.Emissivity,
state.PumpedHeat,
state.WasteHeat,
state.EnergyUsage,
state.ReactorDraw,
state.ReactorLoadRatio,
state.CapacitorCharge,
state.CapacitorCapacity,
state.CapacitorEfficiency,
state.AetherDriveAxisX,
state.AetherDriveAxisY,
state.AetherDriveAxisZ,
state.AetherDriveThrustX,
state.AetherDriveThrustY,
state.AetherDriveThrustZ,
state.AetherDriveRpmX,
state.AetherDriveRpmY,
state.AetherDriveRpmZ,
state.AetherDriveMaximumRpm,
state.AetherDriveThrustDirectionX,
state.AetherDriveThrustDirectionY,
state.ResourceScannerTargetBodyKey ?? "",
state.ResourceScannerAsteroidIndex,
state.ResourceScannerScanTime,
state.ResourceScannerRange,
state.ResourceScannerMinimumDensity,
state.ResourceScannerScanDuration,
state.MiningToolAsteroidBeltKey ?? "",
state.MiningToolAsteroidIndex,
state.MiningToolRange,
state.ThrusterAxis,
state.ThrusterThrust,
state.ThrusterTorque,
state.ShieldEfficiency,
state.ShieldEnergyUsage,
state.VelocityLimit,
state.ThermotoggleTargetTemperature,
state.SwitchActivated,
state.TriggerPulled,
state.StatModifierApplied,
state.StatModifierExecuted,
state.StatModifierTargetStatCount,
state.TurretControllerWeaponCount,
state.TurretControllerShotSpeed,
state.TurretControllerPredictShots))
.ToArray();
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e81930c7560adfe48b4f959791ab3572

View file

@ -0,0 +1,45 @@
/* 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 int2 = Unity.Mathematics.int2;
public abstract class DragObject
{
}
public abstract class ItemDragObject : DragObject
{
protected ItemDragObject(int2 originCellOffset, ItemInstance item)
{
OriginCellOffset = originCellOffset;
Item = item;
}
public ItemInstance Item { get; }
public int2 OriginCellOffset { get; }
}
public class ItemInstanceDragObject : ItemDragObject
{
public ItemInstanceDragObject(ItemInstance item, EquippedCargoBay originInventory, int2 originCellOffset)
: base(originCellOffset, item)
{
OriginInventory = originInventory;
}
public EquippedCargoBay OriginInventory { get; }
}
public class EquippedItemDragObject : ItemDragObject
{
public EquippedItemDragObject(EquippedItem item, Entity originEntity, int2 originCellOffset)
: base(originCellOffset, item.EquippableItem)
{
EquippedItem = item;
OriginEntity = originEntity;
}
public EquippedItem EquippedItem { get; }
public Entity OriginEntity { get; }
}

View file

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

View file

@ -0,0 +1,37 @@
using System;
public sealed class AetheriaUnityDragSession
{
private DragObject _dragObject;
private Action<DragObject> _endDragCallback;
public void Begin(DragObject dragObject)
{
_dragObject = dragObject;
}
public bool TryGetDraggedItem(out ItemDragObject itemDragObject)
{
itemDragObject = _dragObject as ItemDragObject;
return itemDragObject != null;
}
public void RegisterTarget(Action<DragObject> onEndDrag)
{
_endDragCallback = onEndDrag;
}
public void UnregisterTarget()
{
_endDragCallback = null;
}
public bool End()
{
var hadTarget = _endDragCallback != null;
_endDragCallback?.Invoke(_dragObject);
_dragObject = null;
_endDragCallback = null;
return hadTarget;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6454eeaf62eadb44abbe5d54bf497312

View file

@ -0,0 +1,153 @@
/* 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 Unity.Mathematics;
public sealed class AetheriaUnityEntityConstructionBlueprintProjector
{
private readonly AetheriaUnityLoadoutItemProjector _loadoutItemProjector;
public AetheriaUnityEntityConstructionBlueprintProjector(
AetheriaUnityLoadoutItemProjector loadoutItemProjector)
{
_loadoutItemProjector = loadoutItemProjector ?? throw new ArgumentNullException(nameof(loadoutItemProjector));
}
public EntityConstructionBlueprint ProjectTemplate(AetheriaRuntimeLoadoutTemplateSnapshot template)
{
if (template == null)
return null;
var blueprint = ProjectLoadoutEntity(template.RootEntity);
if (blueprint != null && string.IsNullOrWhiteSpace(blueprint.Name))
blueprint.Name = template.Name;
return blueprint;
}
public EntityConstructionBlueprint ProjectLoadoutEntity(AetheriaRuntimeEntityLoadoutSnapshot entity)
{
if (entity == null)
return null;
var hull = CreateEquippableItem(entity.Hull);
if (hull == null)
return null;
var blueprint = CreateBlueprint(entity.Kind);
if (blueprint is ShipConstructionBlueprint shipBlueprint)
{
shipBlueprint.Direction = new float2(0, 1);
}
blueprint.Name = entity.Name;
blueprint.FactionKey = entity.FactionKey ?? "";
blueprint.Hull = hull;
blueprint.Equipment = CreateEquippableSlots(entity.Equipment);
blueprint.CargoBays = CreateEquippableSlots(entity.CargoBays);
blueprint.DockingBays = CreateEquippableSlots(entity.DockingBays);
blueprint.CargoContents = CreateCargoBayContents(entity.CargoContents);
blueprint.DockingBayContents = CreateCargoBayContents(entity.DockingBayContents);
blueprint.DockingBayAssignments = entity.DockingBayAssignments.ToArray();
blueprint.WeaponGroups = entity.WeaponGroups.Select(group => group.ToArray()).ToArray();
blueprint.Children = entity.Children
.Select(ProjectLoadoutEntity)
.Where(child => child != null)
.ToArray();
return blueprint;
}
public EntityConstructionBlueprint ProjectObservedEntity(
AetheriaRuntimeEntitySnapshot entity,
bool isCurrentEntity)
{
if (entity == null)
return null;
var hull = CreateEquippableItem(new AetheriaRuntimeLoadoutItemSnapshot(
entity.HullItemKey,
1,
1,
1,
true,
false));
if (hull == null)
return null;
var blueprint = CreateBlueprint(entity.Kind);
if (blueprint is ShipConstructionBlueprint shipBlueprint)
{
shipBlueprint.Position = new float3((float)entity.PositionX, (float)entity.PositionY, (float)entity.PositionZ);
shipBlueprint.Direction = new float2((float)entity.DirectionX, (float)entity.DirectionY);
shipBlueprint.IsPlayerShip = isCurrentEntity;
}
blueprint.Name = entity.Name ?? "";
blueprint.FactionKey = entity.FactionKey ?? "";
blueprint.Hull = hull;
blueprint.Equipment = CreateEquippableSlots(entity.Equipment);
blueprint.CargoBays = CreateEquippableSlots(entity.CargoBays);
blueprint.DockingBays = CreateEquippableSlots(entity.DockingBays);
blueprint.CargoContents = CreateCargoBayContents(entity.CargoContents);
blueprint.DockingBayContents = CreateCargoBayContents(entity.DockingBayContents);
blueprint.DockingBayAssignments = entity.DockingBayAssignments.ToArray();
blueprint.WeaponGroups = entity.WeaponGroups.Select(group => group.ToArray()).ToArray();
blueprint.Children = Array.Empty<EntityConstructionBlueprint>();
return blueprint;
}
private static EntityConstructionBlueprint CreateBlueprint(string kind)
{
return string.Equals(kind, "orbital", StringComparison.OrdinalIgnoreCase)
? new OrbitalEntityConstructionBlueprint()
: new ShipConstructionBlueprint();
}
private (int2 position, EquippableItem item)[] CreateEquippableSlots(
IReadOnlyList<AetheriaRuntimeLoadoutItemSlotSnapshot> slots)
{
return (slots ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotSnapshot>())
.Select(slot => (position: new int2(slot.X, slot.Y), item: CreateEquippableItem(slot.Item)))
.Where(slot => slot.item != null)
.ToArray();
}
private (int2 position, EquippableItem item)[] CreateEquippableSlots(
IReadOnlyList<AetheriaRuntimeEntityItemSlotSnapshot> slots)
{
return (slots ?? Array.Empty<AetheriaRuntimeEntityItemSlotSnapshot>())
.Select(slot => (position: new int2(slot.X, slot.Y), item: CreateEquippableItem(new AetheriaRuntimeLoadoutItemSnapshot(
slot.ItemKey,
slot.Quality,
slot.Durability,
slot.Quantity,
slot.Enabled,
slot.OverrideShutdown,
slot.Temperature))))
.Where(slot => slot.item != null)
.ToArray();
}
private (int2 position, ItemInstance item)[][] CreateCargoBayContents(
IReadOnlyList<AetheriaRuntimeCargoBayLoadoutSnapshot> bays)
{
return (bays ?? Array.Empty<AetheriaRuntimeCargoBayLoadoutSnapshot>())
.Select(bay => (bay.Items ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotSnapshot>())
.Select(slot => (position: new int2(slot.X, slot.Y), item: _loadoutItemProjector.CreateLoadoutItem(slot.Item)))
.Where(slot => slot.item != null)
.ToArray())
.ToArray();
}
private EquippableItem CreateEquippableItem(AetheriaRuntimeLoadoutItemSnapshot item)
{
var instance = _loadoutItemProjector.CreateLoadoutItem(item) as EquippableItem;
if (instance != null && item.Durability > 0)
instance.Durability = (float)item.Durability;
return instance;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 88f0588c14c7a1d4c87095a96585c957

View file

@ -0,0 +1,117 @@
/* 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 GameCult.Aetheria.State.Verse;
public sealed class AetheriaUnityGameplayBootShell
{
public GameSettings Settings { get; set; }
public ZoneRenderer ZoneRenderer { get; set; }
public AetheriaUnityCockpitHudShell CockpitHudShell { get; set; }
public float TargetSpottedBlinkFrequency { get; set; }
public float TargetSpottedBlinkOffset { get; set; }
public Action<string> Log { get; set; }
public AetheriaUnityGameplayBootResult Boot()
{
var stateBoot = AetheriaRuntimeStateBoot.Inspect(AetheriaUnityRuntimePaths.GameDataDirectory);
Log?.Invoke($"Aetheria runtime target: {stateBoot.TargetLabel} via {stateBoot.TargetKind} ({stateBoot.TargetSource})");
Log?.Invoke($"Aetheria runtime id: {stateBoot.RuntimeId}");
Log?.Invoke($"Aetheria runtime state file: {stateBoot.StateFilePath}");
stateBoot = SyncRemoteReplicaBeforeBoot(stateBoot);
if (!stateBoot.SupportsLocalStateFileRead)
{
throw new InvalidOperationException(
$"Aetheria runtime target cannot read the daemon mirror state required for gameplay boot: {stateBoot.FailureMessage}");
}
if (!stateBoot.StateFileExists)
{
throw new InvalidOperationException(
$"Aetheria runtime state file is missing at {stateBoot.StateFilePath}; gameplay requires an authoritative daemon mirror.");
}
var runtimeCatalog = AetheriaUnityRuntimeClientProvider.ResolveClient(stateBoot.StateFilePath, stateBoot.RuntimeId)
.OpenRuntimeCatalog();
if (runtimeCatalog == null)
throw new InvalidOperationException("Aetheria typed runtime catalog is required before gameplay boot.");
Log?.Invoke($"Aetheria runtime catalog: {runtimeCatalog.Items.Count} items, {runtimeCatalog.Corporations.Count} corporations, {runtimeCatalog.NameFiles.Count} name files");
var itemManager = new ItemManager(
runtimeCatalog,
Settings.GameplaySettings,
message => Log?.Invoke(message));
var loadoutItemProjector = new AetheriaUnityLoadoutItemProjector(itemManager, runtimeCatalog);
ZoneRenderer.SetDroppedPickupItemProjector(loadoutItemProjector.CreateLoadoutItem);
ZoneRenderer.BodySettingsCollections = Settings.BodySettingsCollections;
ZoneRenderer.RenderSettings = AetheriaUnityRenderSettingsBridge.Build(
Settings,
TargetSpottedBlinkFrequency,
TargetSpottedBlinkOffset);
CockpitHudShell.SetRenderSettings(ZoneRenderer.RenderSettings);
if (!AetheriaUnityRuntimeClientProvider.PlayerSettings.GraphicsSettings.ShowAsteroidsInMinimap)
ZoneRenderer.ShowAsteroidUI = false;
return new AetheriaUnityGameplayBootResult(
runtimeCatalog,
itemManager,
loadoutItemProjector);
}
private AetheriaRuntimeStateBootReport SyncRemoteReplicaBeforeBoot(AetheriaRuntimeStateBootReport stateBoot)
{
if (!ShouldSyncRemoteReplicaBeforeBoot(stateBoot))
return stateBoot;
Log?.Invoke($"Aetheria remote Verse replica missing; syncing {stateBoot.TargetLabel} from {stateBoot.CultMeshAddress}");
try
{
var target = AetheriaState.At(AetheriaUnityRuntimePaths.GameDataDirectory)
.ClientTarget
.SyncReplica();
AetheriaUnityRuntimePaths.ClearRuntimeStateFilePathCache();
var refreshed = AetheriaRuntimeStateBoot.Inspect(AetheriaUnityRuntimePaths.GameDataDirectory);
Log?.Invoke($"Aetheria remote Verse replica synced: {refreshed.StateFilePath}");
if (!string.IsNullOrWhiteSpace(target.LastReplicaSyncAtUtc))
Log?.Invoke($"Aetheria remote Verse replica sync time: {target.LastReplicaSyncAtUtc}");
return refreshed;
}
catch (Exception ex)
{
AetheriaUnityRuntimePaths.ClearRuntimeStateFilePathCache();
throw new InvalidOperationException(
$"Aetheria remote Verse replica sync failed before gameplay boot: {ex.Message}",
ex);
}
}
private static bool ShouldSyncRemoteReplicaBeforeBoot(AetheriaRuntimeStateBootReport stateBoot)
{
return string.Equals(stateBoot.TargetSource, "client-target", StringComparison.Ordinal)
&& string.Equals(stateBoot.TargetKind, AetheriaRuntimeClientTargetKinds.CultMeshVerse, StringComparison.Ordinal)
&& (!stateBoot.SupportsLocalStateFileRead || !stateBoot.StateFileExists);
}
}
public readonly struct AetheriaUnityGameplayBootResult
{
public AetheriaUnityGameplayBootResult(
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
ItemManager itemManager,
AetheriaUnityLoadoutItemProjector loadoutItemProjector)
{
RuntimeCatalog = runtimeCatalog;
ItemManager = itemManager;
LoadoutItemProjector = loadoutItemProjector;
}
public AetheriaRuntimeCatalogSnapshot RuntimeCatalog { get; }
public ItemManager ItemManager { get; }
public AetheriaUnityLoadoutItemProjector LoadoutItemProjector { get; }
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 70318b35e2014bdfad48683869bfc04d

View file

@ -0,0 +1,218 @@
/* 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 TMPro;
using UniRx;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
public sealed class AetheriaUnityGameplayInputShell : IDisposable
{
private readonly List<ActionBarSlot> _actionBarSlots = new List<ActionBarSlot>();
private readonly List<InputAction> _actionBarActions = new List<InputAction>();
private bool _uiHidden;
private int _zoomLevelIndex;
public AetheriaInput Input { get; private set; }
public RuntimePlayerSettings RuntimePlayerSettings { get; set; }
public InputDisplayLayout InputDisplayLayout { get; set; }
public ConfirmationDialog Dialog { get; set; }
public MainMenu MainMenu { get; set; }
public MenuPanel Menu { get; set; }
public MapRenderer MenuMap { get; set; }
public CanvasGroup GameplayUI { get; set; }
public Transform ActionBar { get; set; }
public ActionBarSlot ActionBarSlot { get; set; }
public ZoneRenderer ZoneRenderer { get; set; }
public AetheriaUnityMenuShell MenuShell { get; set; }
public AetheriaUnityDragSession DragSession { get; set; }
public AetheriaUnityActionBarPresentation ActionBarPresentation { get; set; }
public AetheriaUnityPilotOperationAdapter PilotOperationAdapter { get; set; }
public Func<Entity> ResolveCurrentEntity { get; set; }
public Action<AetheriaInput> SetInput { get; set; }
public IReadOnlyList<ActionBarSlot> ActionBarSlots => _actionBarSlots;
public void Bootstrap()
{
Input = new AetheriaInput();
SetInput?.Invoke(Input);
if (RuntimePlayerSettings?.InputSettings != null)
{
foreach (var binding in RuntimePlayerSettings.InputSettings.InputActionMap)
Input.asset[binding.Key.action].ApplyBindingOverride(binding.Key.binding, binding.Value);
}
if (InputDisplayLayout != null)
InputDisplayLayout.Input = Input.asset;
Dialog?.SetInputGate(
() => Input.Global.Enable(),
() => Input.Global.Disable());
Input.Global.Enable();
_zoomLevelIndex = ZoneRenderer.RenderSettings.ResolveDefaultMinimapZoomIndex();
ZoneRenderer.MinimapDistance = (float)ZoneRenderer.RenderSettings.ResolveMinimapDistance(_zoomLevelIndex);
RegisterGlobalInput();
RegisterPlayerInput();
RegisterActionBarInput();
}
public void EnablePlayerInput()
{
Cursor.lockState = CursorLockMode.Locked;
Input.Player.Enable();
foreach (var action in _actionBarActions)
action.Enable();
}
public void DisablePlayerInput()
{
Cursor.lockState = CursorLockMode.None;
Input.Player.Disable();
foreach (var action in _actionBarActions)
action.Disable();
}
public void Dispose()
{
foreach (var action in _actionBarActions)
action.Dispose();
_actionBarActions.Clear();
_actionBarSlots.Clear();
Input?.Dispose();
Input = null;
}
private void RegisterGlobalInput()
{
Input.Global.ZoneMap.performed += context =>
{
MenuShell.ToggleMenuTab(MenuTab.Map);
var currentEntity = ResolveCurrentEntity?.Invoke();
if (currentEntity == null)
return;
MenuMap.Position = AetheriaMath.ToUnity(currentEntity.CultPositionXZ);
};
Input.Global.Inventory.performed += context => MenuShell.ToggleMenuTab(MenuTab.Inventory);
Input.Global.GalaxyMap.performed += context => MenuShell.ToggleMenuTab(MenuTab.Galaxy);
Input.Global.Interact.performed += context =>
{
if (IsTextInputFocused() || MainMenu.gameObject.activeSelf)
return;
if (ResolveCurrentEntity?.Invoke() == null)
{
Dialog.Clear();
Dialog.Title.text = "Can't undock. You dont have a ship!";
Dialog.Show();
Dialog.MoveToCursor();
return;
}
PilotOperationAdapter.RequestInteract();
};
Input.Global.MainMenu.performed += context =>
{
if (Menu.gameObject.activeSelf)
MenuShell.ToggleMenuTab(Menu.CurrentTab);
else
MenuShell.ToggleFullscreenMenu(MainMenu.gameObject);
};
Input.Global.InputScreen.performed += context => MenuShell.ToggleFullscreenMenu(MenuShell.HelpScreen);
}
private void RegisterPlayerInput()
{
Input.Player.MinimapZoom.performed += context =>
{
_zoomLevelIndex = ZoneRenderer.RenderSettings.ResolveNextMinimapZoomIndex(_zoomLevelIndex);
ZoneRenderer.MinimapDistance = (float)ZoneRenderer.RenderSettings.ResolveMinimapDistance(_zoomLevelIndex);
};
Input.Player.HideUI.performed += context =>
{
_uiHidden = !_uiHidden;
GameplayUI.alpha = _uiHidden ? 0 : 1;
ActionBar.gameObject.SetActive(!_uiHidden);
};
Input.Player.OverrideShutdown.performed += context =>
{
var currentEntity = ResolveCurrentEntity?.Invoke();
if (currentEntity != null)
PilotOperationAdapter.RequestOverrideShutdown(!currentEntity.OverrideShutdown);
};
Input.Player.Ping.performed += context => PilotOperationAdapter.RequestSensorPing();
Input.Player.ToggleHeatsinks.performed += context =>
{
var currentEntity = ResolveCurrentEntity?.Invoke();
if (currentEntity != null)
PilotOperationAdapter.RequestHeatsinksEnabled(!currentEntity.HeatsinksEnabled);
};
Input.Player.ToggleShield.performed += context => PilotOperationAdapter.RequestShieldToggle();
Input.Player.TargetReticle.performed += context => PilotOperationAdapter.RequestTargetReticle();
Input.Player.TargetNearest.performed += context => PilotOperationAdapter.RequestTargetNearest();
Input.Player.TargetNext.performed += context => PilotOperationAdapter.RequestTargetNext();
Input.Player.TargetPrevious.performed += context => PilotOperationAdapter.RequestTargetPrevious();
}
private void RegisterActionBarInput()
{
foreach (var controlPath in (RuntimePlayerSettings?.InputSettings?.ActionBarInputs ?? Enumerable.Empty<string>()).OrderBy(input => input))
CreateActionBarSlot(controlPath);
}
private void CreateActionBarSlot(string controlPath)
{
var action = new InputAction(binding: controlPath);
_actionBarActions.Add(action);
var slot = UnityEngine.Object.Instantiate(ActionBarSlot, ActionBar);
slot.ControlPath = controlPath;
slot.Binding = null;
_actionBarSlots.Add(slot);
action.started += context => slot.Binding?.Activate();
action.canceled += context => slot.Binding?.Deactivate();
var shortName = controlPath.Substring(controlPath.LastIndexOf('/') + 1);
var sprite = Resources.Load<Sprite>($"Sprites/Input/{shortName}");
if (sprite != null)
{
slot.InputIcon.sprite = sprite;
slot.InputLabel.gameObject.SetActive(false);
}
else
{
slot.InputLabel.text = shortName;
slot.InputIcon.gameObject.SetActive(false);
}
slot.PointerEnterTrigger.OnPointerEnterAsObservable().Subscribe(_ =>
{
DragSession.RegisterTarget(dragAction => ActionBarPresentation.RequestBinding(slot, dragAction));
});
slot.PointerExitTrigger.OnPointerExitAsObservable().Subscribe(_ => DragSession.UnregisterTarget());
}
private static bool IsTextInputFocused()
{
return EventSystem.current != null &&
EventSystem.current.currentSelectedGameObject != null &&
EventSystem.current.currentSelectedGameObject.GetComponent<TMP_InputField>() != null;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 055f68d70b7c7634991717c468672f15

View file

@ -0,0 +1,35 @@
/* 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;
public sealed class AetheriaUnityGameplayLoopShell
{
public bool Paused { get; set; }
public Func<Entity> ResolveCurrentEntity { get; set; }
public Func<bool> IsCurrentEntityUndocked { get; set; }
public Action ApplyLatestZoneRender { get; set; }
public AetheriaUnityCurrentEntityPresentation CurrentEntityPresentation { get; set; }
public AetheriaUnityPilotFrameAdapter PilotFrameAdapter { get; set; }
public AetheriaUnityTargetPresentation TargetPresentation { get; set; }
public void Tick(float deltaTime, float time)
{
if (Paused)
return;
ApplyLatestZoneRender?.Invoke();
CurrentEntityPresentation?.Tick(deltaTime);
if (IsCurrentEntityUndocked?.Invoke() == true)
PilotFrameAdapter?.Tick(ResolveCurrentEntity?.Invoke(), deltaTime, time);
}
public void LateTick()
{
TargetPresentation?.UpdateTargetIndicators(
ResolveCurrentEntity?.Invoke(),
IsCurrentEntityUndocked?.Invoke() == true,
CurrentEntityPresentation);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f4705e6dd36d4d89add3f3751008bf82

View file

@ -0,0 +1,147 @@
/* 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 Cinemachine;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.UI;
public sealed class AetheriaUnityGameplaySceneWiring
{
public ZoneRenderer ZoneRenderer { get; set; }
public CinemachineVirtualCamera DockCamera { get; set; }
public CinemachineVirtualCamera FollowCamera { get; set; }
public MenuPanel Menu { get; set; }
public TradeMenu TradeMenu { get; set; }
public CanvasGroup GameplayUI { get; set; }
public InventoryMenu Inventory { get; set; }
public InventoryPanel ShipPanel { get; set; }
public InventoryPanel TargetShipPanel { get; set; }
public SchematicDisplay SchematicDisplay { get; set; }
public SchematicDisplay TargetSchematicDisplay { get; set; }
public PlaceUIElementWorldspace[] Crosshairs { get; set; } = Array.Empty<PlaceUIElementWorldspace>();
public Prototype LockIndicator { get; set; }
public GameObject HitMarker { get; set; }
public float HitMarkerDuration { get; set; }
public Image TargetShieldsBackground { get; set; }
public Image TargetShieldsIcon { get; set; }
public Color ShieldColor { get; set; }
public Color NoShieldColor { get; set; }
public Sprite ShieldIcon { get; set; }
public Sprite NoShieldIcon { get; set; }
public Prototype HostileTargetIndicator { get; set; }
public Prototype FriendlyTargetIndicator { get; set; }
public PlaceUIElementWorldspace ViewDot { get; set; }
public PlaceUIElementWorldspace TargetIndicator { get; set; }
public Image TargetHitpointsFill { get; set; }
public Image TargetVisibilityFill { get; set; }
public Image VisibilityToTargetFill { get; set; }
public Image TargetShieldsFill { get; set; }
public MainMenu MainMenu { get; set; }
public void ConfigureCurrentEntityPresentation(
AetheriaUnityCurrentEntityPresentation presentation,
AetheriaRuntimeCatalogSnapshot runtimeCatalog)
{
if (presentation == null)
return;
presentation.ZoneRenderer = ZoneRenderer;
presentation.RuntimeCatalog = runtimeCatalog;
presentation.DockCamera = DockCamera;
presentation.FollowCamera = FollowCamera;
presentation.Menu = Menu;
presentation.TradeMenu = TradeMenu;
presentation.GameplayUI = GameplayUI;
presentation.ShipPanel = ShipPanel;
presentation.TargetShipPanel = TargetShipPanel;
presentation.SchematicDisplay = SchematicDisplay;
presentation.TargetSchematicDisplay = TargetSchematicDisplay;
presentation.Crosshairs = Crosshairs;
presentation.LockIndicator = LockIndicator;
presentation.HitMarker = HitMarker;
presentation.HitMarkerDuration = HitMarkerDuration;
presentation.TargetImages = new ImageTargetPresentation
{
TargetShieldsBackground = TargetShieldsBackground,
TargetShieldsIcon = TargetShieldsIcon,
ShieldColor = ShieldColor,
NoShieldColor = NoShieldColor,
ShieldIcon = ShieldIcon,
NoShieldIcon = NoShieldIcon
};
}
public void ConfigureTargetPresentation(
AetheriaUnityTargetPresentation presentation,
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
AetheriaUnityObservedFacadeIndex observedFacadeIndex,
AetheriaUnityObservedTargetQuery observedTargetQuery,
Func<AetheriaClient> resolveClient)
{
if (presentation == null)
return;
presentation.ZoneRenderer = ZoneRenderer;
presentation.RuntimeCatalog = runtimeCatalog;
presentation.HostileTargetIndicator = HostileTargetIndicator;
presentation.FriendlyTargetIndicator = FriendlyTargetIndicator;
presentation.ViewDot = ViewDot;
presentation.TargetIndicator = TargetIndicator;
presentation.TargetHitpointsFill = TargetHitpointsFill;
presentation.TargetVisibilityFill = TargetVisibilityFill;
presentation.VisibilityToTargetFill = VisibilityToTargetFill;
presentation.TargetShieldsFill = TargetShieldsFill;
presentation.ResolveClient = resolveClient;
presentation.ResolveEntity = daemonEntityIndex =>
observedFacadeIndex != null &&
observedFacadeIndex.TryResolveEntityByDaemonIndex(daemonEntityIndex, out var entity)
? entity
: null;
presentation.ResolveTarget = observedTargetQuery.GetObservedTarget;
presentation.ResolveInfoGathered = observedTargetQuery.GetObservedInfoGathered;
presentation.ResolveHostileContact = observedTargetQuery.IsObservedHostileContact;
presentation.ResolveVisibleContacts = observedTargetQuery.GetObservedVisibleContacts;
}
public void ConfigureInventoryDragSession(AetheriaUnityDragSession dragSession)
{
Inventory?.SetDragSession(dragSession);
ShipPanel?.SetDragSession(dragSession);
TargetShipPanel?.SetDragSession(dragSession);
}
public void ConfigureActionBarPresentation(
AetheriaUnityActionBarPresentation actionBarPresentation,
AetheriaUnityGameplayInputShell gameplayInputShell,
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
GameSettings settings,
Func<Entity> resolveCurrentEntity,
Func<AetheriaClient> resolveActionBarClient)
{
actionBarPresentation?.Bind(
gameplayInputShell?.ActionBarSlots ?? Array.Empty<ActionBarSlot>(),
runtimeCatalog,
settings,
resolveCurrentEntity,
resolveActionBarClient);
Inventory?.SetActionBarPresentation(actionBarPresentation);
}
public void ConfigureRuntimeInputScreenShell(AetheriaUnityMenuShell menuShell)
{
MainMenu?.SetRuntimeInputScreenShell(menuShell.CanOpenRuntimeInputScreen, menuShell.ShowRuntimeInputScreen);
}
public void ConfigureObservedFacadeIndex(AetheriaUnityObservedFacadeIndex observedFacadeIndex)
{
Inventory?.SetObservedFacadeIndex(observedFacadeIndex);
ShipPanel?.SetObservedFacadeIndex(observedFacadeIndex);
TargetShipPanel?.SetObservedFacadeIndex(observedFacadeIndex);
foreach (var localMenu in UnityEngine.Object.FindObjectsByType<LocalMenu>(FindObjectsSortMode.None))
localMenu.SetObservedFacadeIndex(observedFacadeIndex);
}
}

View file

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

View file

@ -0,0 +1,63 @@
/* 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 GameCult.Aetheria.State.Verse;
public sealed class AetheriaUnityLoadoutItemProjector
{
private readonly ItemManager _itemManager;
private readonly AetheriaRuntimeCatalogSnapshot _catalog;
public AetheriaUnityLoadoutItemProjector(
ItemManager itemManager,
AetheriaRuntimeCatalogSnapshot catalog)
{
_itemManager = itemManager ?? throw new ArgumentNullException(nameof(itemManager));
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
}
public ItemInstance CreateLoadoutItem(AetheriaRuntimeLoadoutItemCommit item)
{
if (item == null)
return null;
return CreateLoadoutItem(
item.ItemKey,
item.Quality,
item.Durability,
Math.Max(1, item.Quantity));
}
public ItemInstance CreateLoadoutItem(AetheriaRuntimeLoadoutItemSnapshot item)
{
if (item == null)
return null;
return CreateLoadoutItem(
item.ItemKey,
item.Quality,
item.Durability,
Math.Max(1, item.Quantity));
}
private ItemInstance CreateLoadoutItem(
string itemKey,
double quality,
double durability,
int quantity)
{
var typedItem = _catalog.FindItem(itemKey ?? "");
if (typedItem == null)
return null;
if (typedItem.Stackable)
return _itemManager.CreateSimpleCommodityInstance(typedItem, Math.Max(1, quantity));
var instance = _itemManager.CreateCraftedInstance(typedItem, (float)quality);
if (instance is EquippableItem equippable && durability > 0)
equippable.Durability = (float)durability;
return instance;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f14a61accda77214798bd71817fa2dcb

View file

@ -0,0 +1,129 @@
/* 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 TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
public sealed class AetheriaUnityMenuShell
{
public MainMenu MainMenu { get; set; }
public GameObject HelpScreen { get; set; }
public InputDisplayLayout InputDisplayLayout { get; set; }
public GameObject UiRoot { get; set; }
public MenuPanel Menu { get; set; }
public CanvasGroup GameplayUI { get; set; }
public Func<Entity> ResolveCurrentEntity { get; set; }
public Func<bool> IsCurrentEntityUndocked { get; set; }
public Func<Entity, Entity> ResolveObservedTarget { get; set; }
public Action<bool> SetPaused { get; set; }
public Action EnablePlayerInput { get; set; }
public Action DisablePlayerInput { get; set; }
public Action UpdatePlayerPanel { get; set; }
public Action<Entity> UpdateTargetPanel { get; set; }
private bool _menuShownBeforeFullscreen;
public bool CanOpenRuntimeInputScreen()
{
return ResolveCurrentEntity?.Invoke() != null &&
HelpScreen != null &&
InputDisplayLayout != null;
}
public void ShowRuntimeInputScreen()
{
ShowFullscreenMenu(HelpScreen);
}
public void ToggleFullscreenMenu(GameObject menu)
{
if (IsTextInputFocused() || menu == null || ResolveCurrentEntity?.Invoke() == null)
return;
if (menu.activeSelf)
HideFullscreenMenu(menu);
else
ShowFullscreenMenu(menu);
}
public void ToggleMenuTab(MenuTab tab)
{
if (IsTextInputFocused() || MainMenu == null || Menu == null)
return;
if (MainMenu.gameObject.activeSelf)
return;
if (Menu.gameObject.activeSelf && Menu.CurrentTab == tab)
{
Menu.gameObject.SetActive(false);
if (IsCurrentEntityUndocked?.Invoke() == true)
{
EnablePlayerInput?.Invoke();
RefreshCurrentPanels();
if (GameplayUI != null)
GameplayUI.gameObject.SetActive(true);
}
return;
}
DisablePlayerInput?.Invoke();
Menu.ShowTab(tab);
if (GameplayUI != null)
GameplayUI.gameObject.SetActive(false);
}
private void ShowFullscreenMenu(GameObject menu)
{
if (IsTextInputFocused() || menu == null || ResolveCurrentEntity?.Invoke() == null)
return;
if (MainMenu != null && MainMenu.gameObject != menu)
MainMenu.gameObject.SetActive(false);
if (HelpScreen != null && HelpScreen != menu)
HelpScreen.SetActive(false);
SetPaused?.Invoke(true);
menu.SetActive(true);
if (UiRoot != null)
UiRoot.SetActive(false);
_menuShownBeforeFullscreen = Menu != null && Menu.gameObject.activeSelf;
if (!_menuShownBeforeFullscreen)
DisablePlayerInput?.Invoke();
}
private void HideFullscreenMenu(GameObject menu)
{
if (menu == null || ResolveCurrentEntity?.Invoke() == null)
return;
SetPaused?.Invoke(false);
menu.SetActive(false);
if (UiRoot != null)
UiRoot.SetActive(true);
if (!_menuShownBeforeFullscreen)
{
EnablePlayerInput?.Invoke();
RefreshCurrentPanels();
}
}
private void RefreshCurrentPanels()
{
var currentEntity = ResolveCurrentEntity?.Invoke();
UpdatePlayerPanel?.Invoke();
UpdateTargetPanel?.Invoke(ResolveObservedTarget?.Invoke(currentEntity));
}
private static bool IsTextInputFocused()
{
return EventSystem.current != null &&
EventSystem.current.currentSelectedGameObject != null &&
EventSystem.current.currentSelectedGameObject.GetComponent<TMP_InputField>() != null;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1a95f06d9ca2ddb47a07fdc47791f5af

View file

@ -0,0 +1,106 @@
/* 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 GameCult.Aetheria.State.Verse;
public sealed class AetheriaUnityObservedDockingIndex
{
private readonly Func<AetheriaClient> _resolveClient;
private readonly AetheriaUnityObservedFacadeIndex _observedFacadeIndex;
public AetheriaUnityObservedDockingIndex(
Func<AetheriaClient> resolveClient,
AetheriaUnityObservedFacadeIndex observedFacadeIndex)
{
_resolveClient = resolveClient ?? throw new ArgumentNullException(nameof(resolveClient));
_observedFacadeIndex = observedFacadeIndex ?? throw new ArgumentNullException(nameof(observedFacadeIndex));
}
public int ResolveEntityZoneIndex(Entity entity)
{
return TryResolveCurrentDocking(entity, out var docking)
? docking.ZoneIndex
: -1;
}
public bool IsEntityUndocked(Entity entity)
{
return TryResolveCurrentDocking(entity, out var docking) &&
!docking.IsDocked;
}
public bool TryResolveDockingBay(
Entity child,
out Entity dockParent,
out EquippedDockingBay dockingBay)
{
return TryResolveDockingBay(child, out dockParent, out dockingBay, out _);
}
public bool TryResolveDockingBay(
Entity child,
out Entity dockParent,
out EquippedDockingBay dockingBay,
out AetheriaRuntimeCurrentDockingDocument docking)
{
dockParent = null;
dockingBay = null;
docking = null;
if (!TryResolveCurrentDocking(child, out docking) || !docking.IsDocked)
return false;
if (!_observedFacadeIndex.TryResolveEntityByRecordKey(docking.DockParentEntityKey, out var parent) ||
!(parent is OrbitalEntity))
{
return false;
}
if (parent.DockingBays == null ||
docking.DockingBayIndex < 0 ||
docking.DockingBayIndex >= parent.DockingBays.Count)
{
return false;
}
dockParent = parent;
dockingBay = parent.DockingBays[docking.DockingBayIndex];
return dockingBay != null;
}
private bool TryResolveCurrentDocking(
Entity entity,
out AetheriaRuntimeCurrentDockingDocument docking)
{
docking = ReadCurrentDocking();
if (entity == null ||
docking == null ||
docking.CurrentEntityIndex != entity.DaemonEntityIndex)
{
return false;
}
if (_observedFacadeIndex.TryResolveEntityRecordKey(entity, out var entityKey) &&
!string.IsNullOrWhiteSpace(docking.CurrentEntityKey) &&
!string.Equals(docking.CurrentEntityKey, entityKey, StringComparison.Ordinal))
{
return false;
}
return true;
}
private AetheriaRuntimeCurrentDockingDocument ReadCurrentDocking()
{
try
{
return _resolveClient()?.CurrentDockingAsync().GetAwaiter().GetResult();
}
catch
{
return null;
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3131bc989a39393489b141a3d040e186

View file

@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
public sealed class AetheriaUnityObservedFacadeIndex
{
private readonly Dictionary<string, Entity> _entitiesByRecordKey = new Dictionary<string, Entity>(StringComparer.Ordinal);
private readonly Dictionary<int, Entity> _entitiesByDaemonIndex = new Dictionary<int, Entity>();
public IReadOnlyDictionary<string, Entity> EntitiesByRecordKey => _entitiesByRecordKey;
public IReadOnlyDictionary<int, Entity> EntitiesByDaemonIndex => _entitiesByDaemonIndex;
public int Count => _entitiesByRecordKey.Count;
public bool ContainsRecordKey(string recordKey)
{
return !string.IsNullOrWhiteSpace(recordKey) &&
_entitiesByRecordKey.ContainsKey(recordKey);
}
public void Replace(IReadOnlyDictionary<string, Entity> entitiesByRecordKey)
{
_entitiesByRecordKey.Clear();
if (entitiesByRecordKey != null)
{
foreach (var pair in entitiesByRecordKey)
{
if (!string.IsNullOrWhiteSpace(pair.Key) && pair.Value != null)
_entitiesByRecordKey[pair.Key] = pair.Value;
}
}
RebuildDaemonIndex();
}
public void RefreshDaemonIndex()
{
RebuildDaemonIndex();
}
public bool TryResolveEntityRecordKey(Entity entity, out string recordKey)
{
recordKey = "";
if (entity == null)
return false;
foreach (var pair in _entitiesByRecordKey)
{
if (ReferenceEquals(pair.Value, entity))
{
recordKey = pair.Key;
return true;
}
}
return false;
}
public bool TryResolveEntityByRecordKey(string recordKey, out Entity entity)
{
entity = null;
return !string.IsNullOrWhiteSpace(recordKey) &&
_entitiesByRecordKey.TryGetValue(recordKey, out entity);
}
public bool TryResolveEntityByDaemonIndex(int daemonEntityIndex, out Entity entity)
{
return _entitiesByDaemonIndex.TryGetValue(daemonEntityIndex, out entity);
}
public bool TryResolveDockingBayByRecordKey(
string parentRecordKey,
int dockingBayIndex,
out EquippedDockingBay dockingBay)
{
dockingBay = null;
if (dockingBayIndex < 0 ||
!TryResolveEntityByRecordKey(parentRecordKey, out var parent) ||
parent?.DockingBays == null ||
dockingBayIndex >= parent.DockingBays.Count)
{
return false;
}
dockingBay = parent.DockingBays[dockingBayIndex];
return dockingBay != null;
}
private void RebuildDaemonIndex()
{
_entitiesByDaemonIndex.Clear();
foreach (var entity in _entitiesByRecordKey.Values)
{
if (entity != null && entity.DaemonEntityIndex >= 0)
_entitiesByDaemonIndex[entity.DaemonEntityIndex] = entity;
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1561fad48f5f1aa43a9070d788f6eaa7

View file

@ -0,0 +1,337 @@
/* 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 GameCult.Aetheria.State.Verse;
public sealed class AetheriaUnityObservedFacadeProjector
{
private readonly AetheriaUnityObservedFacadeIndex _facadeIndex;
private readonly ItemManager _itemManager;
private readonly Func<AetheriaRuntimeEntitySnapshot, bool, EntityConstructionBlueprint> _createBlueprint;
private readonly Func<AetheriaRuntimeLoadoutItemSnapshot, ItemInstance> _createLoadoutItem;
private readonly Action<string> _logWarning;
public AetheriaUnityObservedFacadeProjector(
AetheriaUnityObservedFacadeIndex facadeIndex,
ItemManager itemManager,
Func<AetheriaRuntimeEntitySnapshot, bool, EntityConstructionBlueprint> createBlueprint,
Func<AetheriaRuntimeLoadoutItemSnapshot, ItemInstance> createLoadoutItem,
Action<string> logWarning)
{
_facadeIndex = facadeIndex ?? throw new ArgumentNullException(nameof(facadeIndex));
_itemManager = itemManager ?? throw new ArgumentNullException(nameof(itemManager));
_createBlueprint = createBlueprint ?? throw new ArgumentNullException(nameof(createBlueprint));
_createLoadoutItem = createLoadoutItem ?? throw new ArgumentNullException(nameof(createLoadoutItem));
_logWarning = logWarning ?? (_ => { });
}
public bool TryApplyInPlace(
string lastRunId,
int lastZoneIndex,
string runId,
int zoneIndex,
IReadOnlyList<AetheriaRuntimeEntitySnapshot> entitySnapshots,
string currentEntityKey,
Entity currentEntity,
out Entity reboundCurrentEntity)
{
reboundCurrentEntity = null;
if (!string.Equals(lastRunId, runId, StringComparison.Ordinal) ||
lastZoneIndex != zoneIndex ||
_facadeIndex.Count != entitySnapshots.Count)
{
return false;
}
foreach (var snapshot in entitySnapshots)
{
if (!_facadeIndex.ContainsRecordKey(snapshot.RecordKey))
return false;
}
ApplyInPlace(entitySnapshots);
if (_facadeIndex.TryResolveEntityByRecordKey(currentEntityKey, out var resolvedCurrentEntity) &&
currentEntity != resolvedCurrentEntity)
{
reboundCurrentEntity = resolvedCurrentEntity;
}
return true;
}
public void Replace(
IReadOnlyList<AetheriaRuntimeEntitySnapshot> entitySnapshots,
string currentEntityKey,
Zone zone)
{
var restoredEntities = new Dictionary<string, Entity>();
foreach (var entitySnapshot in entitySnapshots)
{
var blueprint = _createBlueprint(
entitySnapshot,
string.Equals(entitySnapshot.RecordKey, currentEntityKey, StringComparison.Ordinal));
if (blueprint == null)
{
_logWarning($"Typed entity snapshot {entitySnapshot.RecordKey} could not be lowered into a runtime entity.");
continue;
}
var entity = EntityConstructionBlueprintProjector.ProjectObservedFromBlueprint(_itemManager, zone, blueprint);
if (entity == null)
continue;
ApplyPoseAndSimpleRuntimeState(entity, entitySnapshot);
entity.RestoreActiveState(entitySnapshot.IsActive);
restoredEntities[entitySnapshot.RecordKey] = entity;
}
foreach (var entitySnapshot in entitySnapshots)
{
if (!restoredEntities.TryGetValue(entitySnapshot.RecordKey, out var entity))
continue;
entity.HeatsinksEnabled = entitySnapshot.HeatsinksEnabled;
entity.RestoreStatGrids(entitySnapshot.StatGrids);
entity.RestoreThermalExposure((float)entitySnapshot.Heatstroke, (float)entitySnapshot.Hypothermia);
RestoreActiveConsumables(entity, entitySnapshot);
RestoreRuntimeBehaviorState(entity, entitySnapshot, restoredEntities);
}
_facadeIndex.Replace(restoredEntities);
}
private void ApplyInPlace(IReadOnlyList<AetheriaRuntimeEntitySnapshot> entitySnapshots)
{
foreach (var entitySnapshot in entitySnapshots)
{
if (!_facadeIndex.TryResolveEntityByRecordKey(entitySnapshot.RecordKey, out var entity))
continue;
ApplyPoseAndSimpleRuntimeState(entity, entitySnapshot);
entity.HeatsinksEnabled = entitySnapshot.HeatsinksEnabled;
if (entity.Settings != null)
entity.Settings.ShutdownPerformance = (float)entitySnapshot.ShutdownPerformance;
entity.RestoreThermalExposure((float)entitySnapshot.Heatstroke, (float)entitySnapshot.Hypothermia);
RestoreRuntimeBehaviorState(entity, entitySnapshot, _facadeIndex.EntitiesByRecordKey);
}
_facadeIndex.RefreshDaemonIndex();
}
private static void ApplyPoseAndSimpleRuntimeState(Entity entity, AetheriaRuntimeEntitySnapshot entitySnapshot)
{
entity.DaemonEntityIndex =
AetheriaUnityDaemonEntitySnapshotProjector.EntityIndexFromRecordKey(entitySnapshot.RecordKey);
entity.Name = entitySnapshot.Name ?? "";
entity.CultPosition = new CultMath.float3((float)entitySnapshot.PositionX, (float)entitySnapshot.PositionY, (float)entitySnapshot.PositionZ);
entity.CultDirection = new CultMath.float2((float)entitySnapshot.DirectionX, (float)entitySnapshot.DirectionY);
entity.CultVelocity = new CultMath.float2((float)entitySnapshot.VelocityX, (float)entitySnapshot.VelocityY);
entity.OverrideShutdown = entitySnapshot.OverrideShutdown;
entity.TractorPower = (float)entitySnapshot.TractorPower;
}
private void RestoreActiveConsumables(Entity entity, AetheriaRuntimeEntitySnapshot snapshot)
{
foreach (var activeConsumable in snapshot.ActiveConsumables)
{
var item = _createLoadoutItem(new AetheriaRuntimeLoadoutItemSnapshot(
activeConsumable.ItemKey,
activeConsumable.Quality,
1,
1,
true,
false)) as ConsumableItem;
if (item == null)
{
_logWarning($"Typed active consumable {activeConsumable.ItemKey} could not be lowered for restored entity {snapshot.RecordKey}.");
continue;
}
entity.RestoreActiveConsumable(
item,
(float)activeConsumable.RemainingDuration,
(float)activeConsumable.Duration);
}
}
private static void RestoreRuntimeBehaviorState(
Entity entity,
AetheriaRuntimeEntitySnapshot snapshot,
IReadOnlyDictionary<string, Entity> restoredEntities)
{
foreach (var weaponState in snapshot.WeaponStates)
{
if (!(ResolveRuntimeBehavior(entity, weaponState.OwnerKind, weaponState.OwnerIndex, weaponState.BehaviorIndex) is Weapon weapon))
continue;
if (weapon is LockWeapon lockWeapon)
{
restoredEntities.TryGetValue(weaponState.LockTargetEntityKey, out var lockTarget);
lockWeapon.RestoreRuntimeState(
weaponState.Firing,
weaponState.Ammo,
weaponState.BurstRemaining,
(float)weaponState.BurstTimer,
(float)weaponState.BurstInterval,
(float)weaponState.CooldownProgress,
weaponState.CoolingDown,
(float)weaponState.LockProgress,
lockTarget);
}
else if (weapon is ChargedWeapon chargedWeapon)
{
chargedWeapon.RestoreRuntimeState(
weaponState.Firing,
weaponState.Ammo,
weaponState.BurstRemaining,
(float)weaponState.BurstTimer,
(float)weaponState.BurstInterval,
(float)weaponState.CooldownProgress,
weaponState.CoolingDown,
weaponState.Charging,
weaponState.Charged,
(float)weaponState.Charge);
}
else if (weapon is ConstantWeapon constantWeapon)
{
constantWeapon.RestoreRuntimeState(
weaponState.Firing,
weaponState.Ammo,
(float)weaponState.AmmoIntervalProgress,
(float)weaponState.ReloadProgress,
weaponState.Reloading);
}
else if (weapon is InstantWeapon instantWeapon)
{
instantWeapon.RestoreRuntimeState(
weaponState.Firing,
weaponState.Ammo,
weaponState.BurstRemaining,
(float)weaponState.BurstTimer,
(float)weaponState.BurstInterval,
(float)weaponState.CooldownProgress,
weaponState.CoolingDown);
}
else
{
weapon.RestoreRuntimeState(weaponState.Firing);
}
}
foreach (var behaviorState in snapshot.BehaviorStates)
{
var behavior = ResolveRuntimeBehavior(entity, behaviorState.OwnerKind, behaviorState.OwnerIndex, behaviorState.BehaviorIndex);
switch (behavior)
{
case Sensor sensor:
sensor.RestoreRuntimeState(
behaviorState.Pinging,
(float)behaviorState.PingCooldown,
(float)behaviorState.PingLerp,
(float)behaviorState.PingRadius);
break;
case Radiator radiator:
radiator.RestoreRuntimeState(
(float)behaviorState.RadiatorTemperature,
(float)behaviorState.Emissivity,
(float)behaviorState.PumpedHeat,
(float)behaviorState.WasteHeat,
(float)behaviorState.EnergyUsage);
break;
case Reactor reactor:
reactor.RestoreRuntimeState(
(float)behaviorState.ReactorDraw,
(float)behaviorState.ReactorLoadRatio);
break;
case Capacitor capacitor:
capacitor.RestoreRuntimeState(
(float)behaviorState.CapacitorCharge,
(float)behaviorState.CapacitorCapacity,
(float)behaviorState.CapacitorEfficiency);
break;
case AetherDrive drive:
drive.RestoreRuntimeState(
new CultMath.float3((float)behaviorState.AetherDriveAxisX, (float)behaviorState.AetherDriveAxisY, (float)behaviorState.AetherDriveAxisZ),
new CultMath.float3((float)behaviorState.AetherDriveThrustX, (float)behaviorState.AetherDriveThrustY, (float)behaviorState.AetherDriveThrustZ),
new CultMath.float3((float)behaviorState.AetherDriveRpmX, (float)behaviorState.AetherDriveRpmY, (float)behaviorState.AetherDriveRpmZ),
(float)behaviorState.AetherDriveMaximumRpm,
new CultMath.float2((float)behaviorState.AetherDriveThrustDirectionX, (float)behaviorState.AetherDriveThrustDirectionY));
break;
case ResourceScanner resourceScanner:
resourceScanner.RestoreRuntimeState(
behaviorState.ResourceScannerTargetBodyKey,
behaviorState.ResourceScannerAsteroidIndex,
(float)behaviorState.ResourceScannerScanTime,
(float)behaviorState.ResourceScannerRange,
(float)behaviorState.ResourceScannerMinimumDensity,
(float)behaviorState.ResourceScannerScanDuration);
break;
case MiningTool miningTool:
miningTool.RestoreRuntimeState(
behaviorState.MiningToolAsteroidBeltKey,
behaviorState.MiningToolAsteroidIndex,
(float)behaviorState.MiningToolRange);
break;
case Thruster thruster:
thruster.RestoreRuntimeState(
(float)behaviorState.ThrusterAxis,
(float)behaviorState.ThrusterThrust);
break;
case Shield shield:
shield.RestoreRuntimeState(
(float)behaviorState.ShieldEfficiency,
(float)behaviorState.ShieldEnergyUsage);
break;
case VelocityLimit velocityLimit:
velocityLimit.RestoreRuntimeState((float)behaviorState.VelocityLimit);
break;
case Thermotoggle thermotoggle:
thermotoggle.TargetTemperature = (float)behaviorState.ThermotoggleTargetTemperature;
break;
case Switch switchBehavior:
switchBehavior.Activated = behaviorState.SwitchActivated;
break;
case Trigger trigger:
trigger.RestoreRuntimeState(behaviorState.TriggerPulled);
break;
case StatModifier statModifier:
statModifier.RestoreRuntimeState(
behaviorState.StatModifierApplied,
behaviorState.StatModifierExecuted);
break;
case TurretController turretController:
turretController.RestoreRuntimeState(
(float)behaviorState.TurretControllerShotSpeed,
behaviorState.TurretControllerPredictShots);
break;
}
}
}
private static Behavior ResolveRuntimeBehavior(Entity entity, string ownerKind, int ownerIndex, int behaviorIndex)
{
var behaviors = ResolveRuntimeBehaviorList(entity, ownerKind, ownerIndex);
return behaviors != null && behaviorIndex >= 0 && behaviorIndex < behaviors.Count
? behaviors[behaviorIndex]
: null;
}
private static IReadOnlyList<Behavior> ResolveRuntimeBehaviorList(Entity entity, string ownerKind, int ownerIndex)
{
if (entity == null || ownerIndex < 0)
return null;
switch (ownerKind)
{
case "equipment":
return ownerIndex < entity.Equipment.Count ? entity.Equipment[ownerIndex].Behaviors : null;
case "active_consumable":
return ownerIndex < entity.ActiveConsumables.Count ? entity.ActiveConsumables[ownerIndex].Behaviors : null;
default:
return null;
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0a109bddc65c3d64bb233e11260276d5

View file

@ -0,0 +1,173 @@
/* 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;
public sealed class AetheriaUnityObservedFrameApplier
{
private readonly Func<AetheriaDaemonObserver> _resolveObserver;
private readonly Func<int, GalaxyZone> _resolveObservedZone;
private readonly Func<Zone> _getZone;
private readonly Action<Zone> _setZone;
private readonly AetheriaUnityObservedFacadeIndex _facadeIndex;
private readonly AetheriaUnityObservedFacadeProjector _facadeProjector;
private readonly AetheriaUnityObservedZoneContextProjector _zoneContextProjector;
private readonly Func<ZoneRenderer> _resolveZoneRenderer;
private readonly Func<Entity> _getCurrentEntity;
private readonly Action<Entity> _restoreCurrentEntityBinding;
private readonly Action<string> _logWarning;
private long _lastAppliedZoneRenderFrameId = -1;
private string _lastAppliedZoneRenderRunId = "";
private int _lastAppliedZoneRenderZoneIndex = -1;
private AetheriaRuntimeZoneRenderDocument _lastZoneRender;
public AetheriaUnityObservedFrameApplier(
Func<AetheriaDaemonObserver> resolveObserver,
Func<int, GalaxyZone> resolveObservedZone,
Func<Zone> getZone,
Action<Zone> setZone,
AetheriaUnityObservedFacadeIndex facadeIndex,
AetheriaUnityObservedFacadeProjector facadeProjector,
AetheriaUnityObservedZoneContextProjector zoneContextProjector,
Func<ZoneRenderer> resolveZoneRenderer,
Func<Entity> getCurrentEntity,
Action<Entity> restoreCurrentEntityBinding,
Action<string> logWarning)
{
_resolveObserver = resolveObserver ?? (() => null);
_resolveObservedZone = resolveObservedZone ?? (_ => null);
_getZone = getZone ?? (() => null);
_setZone = setZone ?? (_ => { });
_facadeIndex = facadeIndex ?? throw new ArgumentNullException(nameof(facadeIndex));
_facadeProjector = facadeProjector ?? throw new ArgumentNullException(nameof(facadeProjector));
_zoneContextProjector = zoneContextProjector ?? throw new ArgumentNullException(nameof(zoneContextProjector));
_resolveZoneRenderer = resolveZoneRenderer ?? (() => null);
_getCurrentEntity = getCurrentEntity ?? (() => null);
_restoreCurrentEntityBinding = restoreCurrentEntityBinding ?? (_ => { });
_logWarning = logWarning ?? (_ => { });
}
public bool ApplyLatestZoneRender()
{
var observer = _resolveObserver();
if (observer == null || !observer.HasAuthoritativeState)
{
return false;
}
var render = ReadLatestZoneRender(observer);
if (render == null)
{
return false;
}
return TryRestoreEntityGraphFromZoneRender(render);
}
private AetheriaRuntimeZoneRenderDocument ReadLatestZoneRender(AetheriaDaemonObserver observer)
{
try
{
return observer.Client
.ZoneRenderAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
_logWarning($"Failed to read Aetheria zone-render feed from local Verse state: {ex.Message}");
return null;
}
}
private bool TryRestoreEntityGraphFromZoneRender(AetheriaRuntimeZoneRenderDocument render)
{
if (render == null || render.ZoneIndex < 0)
{
return false;
}
if (string.IsNullOrWhiteSpace(render.RunId))
{
_logWarning("Aetheria zone-render feed does not identify a run id.");
return false;
}
var runId = render.RunId;
var currentEntityKey = string.IsNullOrWhiteSpace(render.CurrentEntityKey) ? "" : render.CurrentEntityKey;
if (string.IsNullOrWhiteSpace(currentEntityKey))
{
_logWarning($"Aetheria zone-render feed for run {runId} does not identify a current entity.");
return false;
}
var entitySnapshots = AetheriaUnityDaemonEntitySnapshotProjector.CreateSnapshots(runId, render.ZoneIndex, render.EntityFacades)
.OrderBy(entity => AetheriaUnityDaemonEntitySnapshotProjector.EntityIndexFromRecordKey(entity.RecordKey))
.ToArray();
if (entitySnapshots.Length == 0)
{
_logWarning($"Aetheria zone-render feed has no entity facades for zone {render.ZoneIndex}.");
return false;
}
var targetZone = _resolveObservedZone(render.ZoneIndex);
if (targetZone == null)
{
_logWarning($"Aetheria zone-render feed references missing zone index {render.ZoneIndex}.");
return false;
}
if (render.FrameId == _lastAppliedZoneRenderFrameId &&
string.Equals(render.RunId, _lastAppliedZoneRenderRunId, StringComparison.Ordinal) &&
render.ZoneIndex == _lastAppliedZoneRenderZoneIndex)
{
return false;
}
var zoneRenderer = _resolveZoneRenderer();
if (_facadeProjector.TryApplyInPlace(
_lastAppliedZoneRenderRunId,
_lastAppliedZoneRenderZoneIndex,
runId,
render.ZoneIndex,
entitySnapshots,
currentEntityKey,
_getCurrentEntity(),
out var reboundCurrentEntity))
{
if (reboundCurrentEntity != null)
_restoreCurrentEntityBinding(reboundCurrentEntity);
zoneRenderer?.ApplyZoneRender(render);
zoneRenderer?.RestoreDroppedPickupsFromZoneRender(render);
_lastAppliedZoneRenderFrameId = render.FrameId;
_lastZoneRender = render;
return true;
}
if (_getZone()?.GalaxyZone != targetZone)
{
var resolvedZone = _zoneContextProjector.ResolveContext(targetZone, render);
if (resolvedZone == null)
return false;
_setZone(resolvedZone);
}
_facadeProjector.Replace(entitySnapshots, currentEntityKey, _getZone());
zoneRenderer?.LoadDaemonZoneView(_facadeIndex.EntitiesByDaemonIndex, render);
if (_facadeIndex.TryResolveEntityByRecordKey(currentEntityKey, out var currentEntity))
_restoreCurrentEntityBinding(currentEntity);
zoneRenderer?.RestoreDroppedPickupsFromZoneRender(render);
_lastAppliedZoneRenderFrameId = render.FrameId;
_lastAppliedZoneRenderRunId = runId;
_lastAppliedZoneRenderZoneIndex = render.ZoneIndex;
_lastZoneRender = render;
return true;
}
}

View file

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

View file

@ -0,0 +1,47 @@
using System;
using System.Linq;
using GameCult.Aetheria.State.Verse;
public static class AetheriaUnityObservedRunProjection
{
public static Galaxy Galaxy { get; private set; }
public static void Project(
AetheriaRuntimeSectorMapDocument sectorMap,
SectorBackgroundSettings backgroundSettings,
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
Action<string> log)
{
Galaxy = global::Galaxy.ProjectObservedSectorMap(sectorMap, backgroundSettings, runtimeCatalog, log);
}
public static void Project(
AetheriaRuntimeDaemonFrameDocument frame,
SectorBackgroundSettings backgroundSettings,
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
Action<string> log)
{
if (frame == null || frame.Run == null)
throw new ArgumentNullException(nameof(frame));
Galaxy = global::Galaxy.ProjectObservedDaemonRun(frame.Run, backgroundSettings, runtimeCatalog, log);
}
public static GalaxyZone FindZone(int daemonZoneIndex)
{
return daemonZoneIndex < 0
? null
: Galaxy?.Zones?.FirstOrDefault(zone => zone != null && zone.ZoneIndex == daemonZoneIndex);
}
public static AetheriaRuntimeZoneSnapshotCommit FindZoneSnapshot(AetheriaRuntimeRunCheckpointCommit run)
{
if (run == null)
return null;
return (run.Zones ?? Array.Empty<AetheriaRuntimeZoneSnapshotCommit>())
.FirstOrDefault(zone => zone != null && zone.ZoneIndex == run.CurrentZoneIndex)
?? (run.Zones ?? Array.Empty<AetheriaRuntimeZoneSnapshotCommit>())
.FirstOrDefault(zone => zone != null);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5262d4719f1ec6647a465a9450b2787c

View file

@ -0,0 +1,103 @@
/* 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 GameCult.Aetheria.State.Verse;
public sealed class AetheriaUnityObservedTargetQuery
{
private readonly Func<AetheriaClient> _resolveClient;
private readonly AetheriaUnityObservedFacadeIndex _facadeIndex;
public AetheriaUnityObservedTargetQuery(
Func<AetheriaClient> resolveClient,
AetheriaUnityObservedFacadeIndex facadeIndex)
{
_resolveClient = resolveClient ?? (() => null);
_facadeIndex = facadeIndex ?? throw new ArgumentNullException(nameof(facadeIndex));
}
public Entity GetObservedTarget(Entity observer)
{
if (TryQueryEntityTarget(observer, out var targetEntityIndex) &&
_facadeIndex.TryResolveEntityByDaemonIndex(targetEntityIndex, out var targetEntity))
{
return targetEntity;
}
return null;
}
public float GetObservedInfoGathered(Entity observer, Entity target)
{
return TryQueryEntityContact(observer, target, out var contact)
? (float)contact.InfoGathered
: 0f;
}
public bool IsObservedHostileContact(Entity observer, Entity target)
{
return TryQueryEntityContact(observer, target, out var contact) && contact.Hostile;
}
public AetheriaRuntimeZoneContactRow[] GetObservedVisibleContacts(
Entity observer,
double minimumInfoGathered,
bool visibleOnly)
{
var contacts = ReadZoneContacts();
if (observer == null || contacts == null)
return Array.Empty<AetheriaRuntimeZoneContactRow>();
return (contacts.Contacts ?? Array.Empty<AetheriaRuntimeZoneContactRow>())
.Where(contact =>
contact.ObserverEntityIndex == observer.DaemonEntityIndex &&
contact.InfoGathered > minimumInfoGathered &&
(!visibleOnly || contact.Visible))
.ToArray();
}
private bool TryQueryEntityContact(
Entity observer,
Entity target,
out AetheriaRuntimeZoneContactRow contact)
{
contact = default;
if (observer == null || target == null)
return false;
contact = (ReadZoneContacts()?.Contacts ?? Array.Empty<AetheriaRuntimeZoneContactRow>())
.FirstOrDefault(row =>
row.ObserverEntityIndex == observer.DaemonEntityIndex &&
row.TargetEntityIndex == target.DaemonEntityIndex);
return contact != null;
}
private bool TryQueryEntityTarget(
Entity observer,
out int targetEntityIndex)
{
targetEntityIndex = -1;
if (observer == null)
return false;
targetEntityIndex = (ReadZoneContacts()?.Targets ?? Array.Empty<AetheriaRuntimeZoneTargetRow>())
.FirstOrDefault(row => row.EntityIndex == observer.DaemonEntityIndex)
?.TargetEntityIndex ?? -1;
return targetEntityIndex >= 0;
}
private AetheriaRuntimeZoneContactsDocument ReadZoneContacts()
{
try
{
return _resolveClient()?.ZoneContactsAsync().GetAwaiter().GetResult();
}
catch
{
return null;
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 735b01f66e370d741bd3a5130eb166c7

View file

@ -0,0 +1,192 @@
/* 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 UnityEngine;
using float2 = Unity.Mathematics.float2;
using float4 = Unity.Mathematics.float4;
public sealed class AetheriaUnityObservedZoneContextProjector
{
private readonly Dictionary<int, Zone> _observedZoneContextsByDaemonIndex = new Dictionary<int, Zone>();
private readonly ItemManager _itemManager;
private readonly PlanetSettings _planetSettings;
private readonly Func<Galaxy> _resolveObservedGalaxy;
private readonly Action<string> _logWarning;
private readonly Action<MusicType> _playMusic;
private Galaxy _observedGalaxy;
public AetheriaUnityObservedZoneContextProjector(
ItemManager itemManager,
PlanetSettings planetSettings,
Func<Galaxy> resolveObservedGalaxy,
Action<string> logWarning,
Action<MusicType> playMusic)
{
_itemManager = itemManager ?? throw new ArgumentNullException(nameof(itemManager));
_planetSettings = planetSettings ?? throw new ArgumentNullException(nameof(planetSettings));
_resolveObservedGalaxy = resolveObservedGalaxy ?? (() => null);
_logWarning = logWarning ?? (_ => { });
_playMusic = playMusic ?? (_ => { });
}
public Zone ResolveContext(
GalaxyZone galaxyZone,
AetheriaRuntimeZoneRenderDocument render)
{
if (galaxyZone == null)
throw new ArgumentNullException(nameof(galaxyZone));
if (render == null)
{
_logWarning($"Daemon-authoritative zone population suppressed for {galaxyZone.Name}; no zone-render document was provided.");
return null;
}
var zoneIndex = render.ZoneIndex;
if (!_observedZoneContextsByDaemonIndex.TryGetValue(zoneIndex, out var observedZoneContext))
{
_observedGalaxy = _resolveObservedGalaxy();
if (_observedGalaxy == null)
{
_logWarning($"Daemon-authoritative zone population suppressed for {galaxyZone.Name}; no observed sector projection is available.");
return null;
}
var constructionBlueprint = CreateZoneConstructionBlueprint(render);
observedZoneContext = new Zone(_itemManager, _planetSettings, constructionBlueprint, galaxyZone, _observedGalaxy);
_observedZoneContextsByDaemonIndex[zoneIndex] = observedZoneContext;
}
_playMusic(MusicType.Overworld);
observedZoneContext.Log = s => Debug.Log($"Zone: {s}");
return observedZoneContext;
}
private static ZoneConstructionBlueprint CreateZoneConstructionBlueprint(AetheriaRuntimeZoneRenderDocument render)
{
var blueprint = new ZoneConstructionBlueprint
{
Radius = 2000,
Mass = 10000,
Time = (float)render.SimulationTimeSeconds
};
foreach (var orbit in render.Orbits ?? Array.Empty<AetheriaRuntimeOrbitSnapshotCommit>())
{
if (orbit == null)
continue;
blueprint.Orbits.Add(new OrbitConstructionData
{
OrbitKey = orbit.OrbitKey ?? "",
ParentOrbitKey = orbit.ParentOrbitKey ?? "",
Distance = (float)orbit.Distance,
Phase = (float)orbit.Phase,
FixedPosition = new float2((float)orbit.FixedPositionX, (float)orbit.FixedPositionY)
});
}
foreach (var body in render.Bodies ?? Array.Empty<AetheriaRuntimeBodySnapshotCommit>())
{
if (body == null)
continue;
blueprint.Bodies.Add(CreateBodyConstructionData(body));
}
return blueprint;
}
private static BodyConstructionData CreateBodyConstructionData(AetheriaRuntimeBodySnapshotCommit body)
{
BodyConstructionData data = (body.Kind ?? "").ToLowerInvariant() switch
{
"asteroid_belt" => new AsteroidBeltConstructionData
{
Asteroids = (body.Asteroids ?? Array.Empty<AetheriaRuntimeAsteroidCommit>())
.Where(asteroid => asteroid != null)
.Select(asteroid => new Asteroid
{
Distance = (float)asteroid.Distance,
Phase = (float)asteroid.Phase,
Size = (float)asteroid.Size,
RotationSpeed = (float)asteroid.RotationSpeed
})
.ToArray()
},
"sun" => CreateSunConstructionData(body),
"gas_giant" => CreateGasGiantConstructionData(body),
_ => new PlanetConstructionData()
};
PopulateBodyConstructionData(data, body);
return data;
}
private static GasGiantConstructionData CreateGasGiantConstructionData(AetheriaRuntimeBodySnapshotCommit body)
{
var visual = body.GasGiantVisual ?? new AetheriaRuntimeGasGiantVisualCommit();
return new GasGiantConstructionData
{
FirstOffsetDomainRotationSpeed = (float)visual.FirstOffsetDomainRotationSpeed,
FirstOffsetRotationSpeed = (float)visual.FirstOffsetRotationSpeed,
SecondOffsetDomainRotationSpeed = (float)visual.SecondOffsetDomainRotationSpeed,
SecondOffsetRotationSpeed = (float)visual.SecondOffsetRotationSpeed,
AlbedoRotationSpeed = (float)visual.AlbedoRotationSpeed,
WaveRadiusMultiplier = (float)visual.WaveRadiusMultiplier,
WaveDepthMultiplier = (float)visual.WaveDepthMultiplier,
WaveDepthExponent = (float)visual.WaveDepthExponent,
WaveSpeedMultiplier = (float)visual.WaveSpeedMultiplier,
MaterialOverrides = (visual.MaterialOverrides ?? Array.Empty<string>()).ToList(),
Colors = (visual.Colors ?? Array.Empty<AetheriaRuntimeColorCommit>())
.Where(color => color != null)
.Select(color => new float4((float)color.X, (float)color.Y, (float)color.Z, (float)color.W))
.ToArray()
};
}
private static SunConstructionData CreateSunConstructionData(AetheriaRuntimeBodySnapshotCommit body)
{
var gas = CreateGasGiantConstructionData(body);
var visual = body.SunVisual ?? new AetheriaRuntimeSunVisualCommit();
return new SunConstructionData
{
FirstOffsetDomainRotationSpeed = gas.FirstOffsetDomainRotationSpeed,
FirstOffsetRotationSpeed = gas.FirstOffsetRotationSpeed,
SecondOffsetDomainRotationSpeed = gas.SecondOffsetDomainRotationSpeed,
SecondOffsetRotationSpeed = gas.SecondOffsetRotationSpeed,
AlbedoRotationSpeed = gas.AlbedoRotationSpeed,
WaveRadiusMultiplier = gas.WaveRadiusMultiplier,
WaveDepthMultiplier = gas.WaveDepthMultiplier,
WaveDepthExponent = gas.WaveDepthExponent,
WaveSpeedMultiplier = gas.WaveSpeedMultiplier,
MaterialOverrides = gas.MaterialOverrides,
Colors = gas.Colors,
LightColor = new CultMath.float3((float)visual.LightColorX, (float)visual.LightColorY, (float)visual.LightColorZ),
FogTintColor = new CultMath.float3((float)visual.FogTintColorX, (float)visual.FogTintColorY, (float)visual.FogTintColorZ),
LightRadiusMultiplier = (float)visual.LightRadiusMultiplier
};
}
private static void PopulateBodyConstructionData(
BodyConstructionData data,
AetheriaRuntimeBodySnapshotCommit body)
{
data.BodyKey = body.BodyKey ?? "";
data.Name = body.Name ?? "";
data.OrbitKey = body.OrbitKey ?? "";
data.Mass = (float)body.Mass;
data.BodyRadiusMultiplier = (float)body.BodyRadiusMultiplier;
data.GravityRadiusMultiplier = (float)body.GravityRadiusMultiplier;
data.GravityDepthMultiplier = (float)body.GravityDepthMultiplier;
data.GravityDepthExponent = (float)body.GravityDepthExponent;
data.Resources = (body.Resources ?? Array.Empty<AetheriaRuntimeBodyResourceCommit>())
.Where(resource => resource != null && !string.IsNullOrWhiteSpace(resource.ItemKey))
.ToDictionary(resource => resource.ItemKey, resource => (float)resource.Amount, StringComparer.Ordinal);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 585768cd246ecc249b1e49ee64a7def9

View file

@ -0,0 +1,120 @@
/* 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 GameCult.Aetheria.State.Verse;
using UnityEngine;
public sealed class AetheriaUnityPilotCommandSender
{
private const float DaemonMoveCommandIntervalSeconds = 0.05f;
private const float DaemonMoveCommandChangeThreshold = 0.001f;
private const float DaemonLookCommandIntervalSeconds = 0.02f;
private const float DaemonLookCommandChangeThreshold = 0.0001f;
private const float DaemonTractorCommandIntervalSeconds = 0.05f;
private const float DaemonTractorCommandChangeThreshold = 0.001f;
private readonly Func<AetheriaClient> _resolveClient;
private readonly Func<float> _time;
private Vector2 _lastSentDaemonMoveVector;
private Vector3 _lastSentDaemonLookDirection;
private float _lastSentDaemonTractorPower;
private float _nextDaemonMoveCommandTime;
private float _nextDaemonLookCommandTime;
private float _nextDaemonTractorCommandTime;
private bool _hasSentDaemonMoveVector;
private bool _hasSentDaemonLookDirection;
private bool _hasSentDaemonTractorPower;
public AetheriaUnityPilotCommandSender(
Func<AetheriaClient> resolveClient,
Func<float> time)
{
_resolveClient = resolveClient ?? throw new ArgumentNullException(nameof(resolveClient));
_time = time ?? throw new ArgumentNullException(nameof(time));
}
public void RequestMoveVector(Vector2 movement)
{
var changed = !_hasSentDaemonMoveVector ||
(movement - _lastSentDaemonMoveVector).sqrMagnitude >
DaemonMoveCommandChangeThreshold * DaemonMoveCommandChangeThreshold;
if (!changed && _time() < _nextDaemonMoveCommandTime)
{
return;
}
if (TrySubmit(
operations => operations.SetMoveVector(movement.x, movement.y, movement.magnitude),
"movement"))
{
_lastSentDaemonMoveVector = movement;
_hasSentDaemonMoveVector = true;
_nextDaemonMoveCommandTime = _time() + DaemonMoveCommandIntervalSeconds;
}
}
public void RequestLookDirection(Vector3 lookDirection)
{
var changed = !_hasSentDaemonLookDirection ||
(lookDirection - _lastSentDaemonLookDirection).sqrMagnitude >
DaemonLookCommandChangeThreshold * DaemonLookCommandChangeThreshold;
if (!changed && _time() < _nextDaemonLookCommandTime)
{
return;
}
if (TrySubmit(
operations => operations.SetLookDirection(lookDirection.x, lookDirection.y, lookDirection.z),
"look"))
{
_lastSentDaemonLookDirection = lookDirection;
_hasSentDaemonLookDirection = true;
_nextDaemonLookCommandTime = _time() + DaemonLookCommandIntervalSeconds;
}
}
public void RequestTractorPower(float power)
{
var changed = !_hasSentDaemonTractorPower ||
Mathf.Abs(power - _lastSentDaemonTractorPower) >
DaemonTractorCommandChangeThreshold;
if (!changed && _time() < _nextDaemonTractorCommandTime)
{
return;
}
if (TrySubmit(
operations => operations.SetTractorPower(power),
"tractor-power"))
{
_lastSentDaemonTractorPower = power;
_hasSentDaemonTractorPower = true;
_nextDaemonTractorCommandTime = _time() + DaemonTractorCommandIntervalSeconds;
}
}
public bool TrySubmit(
Action<AetheriaControl> submit,
string label)
{
var client = _resolveClient();
if (client == null ||
submit == null)
{
return false;
}
try
{
submit(client.Control);
return true;
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to send Aetheria daemon pilot {label} operation; operation not submitted: {ex.Message}");
return false;
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2c98d1a89797d6c4ba1034ac4d171e51

View file

@ -0,0 +1,75 @@
/* 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 Unity.Mathematics;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Rendering.PostProcessing;
using static Unity.Mathematics.math;
public sealed class AetheriaUnityPilotFrameAdapter
{
private float2 _entityYawPitch;
private readonly Action<float3> _setViewDirection;
public AetheriaUnityPilotFrameAdapter(Action<float3> setViewDirection)
{
_setViewDirection = setViewDirection ?? (_ => { });
}
public ZoneRenderer ZoneRenderer { get; set; }
public AetheriaInput Input { get; set; }
public AetheriaUnityTargetPresentation TargetPresentation { get; set; }
public AetheriaUnityPilotCommandSender PilotCommands { get; set; }
public PostProcessVolume HeatstrokePost { get; set; }
public PostProcessVolume SevereHeatstrokePost { get; set; }
public float2 Sensitivity { get; set; }
public void Tick(Entity currentEntity, float deltaTime, float timeSeconds)
{
if (currentEntity == null ||
Input == null ||
PilotCommands == null)
{
return;
}
var renderSettings = ZoneRenderer?.RenderSettings;
TargetPresentation?.Tick(currentEntity, timeSeconds);
var look = Input.Player.Look.ReadValue<Vector2>();
_entityYawPitch = new float2(
_entityYawPitch.x + look.x * Sensitivity.x,
Mathf.Clamp(_entityYawPitch.y + look.y * Sensitivity.y, -.45f * Mathf.PI, .45f * Mathf.PI));
var viewDirection = (float3)(Quaternion.Euler(
_entityYawPitch.y * Mathf.Rad2Deg,
_entityYawPitch.x * Mathf.Rad2Deg,
0) * Vector3.forward);
_setViewDirection(viewDirection);
PilotCommands.RequestLookDirection(viewDirection);
if (renderSettings != null)
{
if (HeatstrokePost != null)
HeatstrokePost.weight = (float)renderSettings.NormalizeHeatstrokePost(currentEntity.Heatstroke);
if (SevereHeatstrokePost != null)
SevereHeatstrokePost.weight =
(float)renderSettings.ResolveSevereHeatstrokePostWeight(currentEntity.Heatstroke, timeSeconds);
}
if (currentEntity is Ship)
{
var movement = Input.Player.Move.ReadValue<Vector2>();
PilotCommands.RequestMoveVector(movement);
}
var tractorPowerInput = Input.Player.TractorBeam.ReadValue<float>();
PilotCommands.RequestTractorPower(Saturate(
currentEntity.TractorPower +
Mathf.Sign(tractorPowerInput - currentEntity.TractorPower) * deltaTime * 2));
}
private static float Saturate(float value) => Mathf.Clamp01(value);
}

View file

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

View file

@ -0,0 +1,114 @@
/* 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 GameCult.Aetheria.State.Verse;
using Unity.Mathematics;
public sealed class AetheriaUnityPilotOperationAdapter
{
private readonly Func<AetheriaUnityPilotCommandSender> _resolvePilotCommands;
private readonly AetheriaUnityObservedFacadeIndex _observedFacadeIndex;
private readonly Func<float3> _resolveViewDirection;
private readonly Func<Entity> _resolveCurrentEntity;
public AetheriaUnityPilotOperationAdapter(
Func<AetheriaUnityPilotCommandSender> resolvePilotCommands,
AetheriaUnityObservedFacadeIndex observedFacadeIndex,
Func<float3> resolveViewDirection,
Func<Entity> resolveCurrentEntity)
{
_resolvePilotCommands = resolvePilotCommands ?? throw new ArgumentNullException(nameof(resolvePilotCommands));
_observedFacadeIndex = observedFacadeIndex ?? throw new ArgumentNullException(nameof(observedFacadeIndex));
_resolveViewDirection = resolveViewDirection ?? (() => default);
_resolveCurrentEntity = resolveCurrentEntity ?? (() => null);
}
public void RequestInteract()
{
Submit(operations => operations.Interact(), "interact");
}
public void RequestTargetSelection(Entity target)
{
if (target == null)
{
Submit(operations => operations.ClearTarget(), "target clear");
return;
}
if (!_observedFacadeIndex.TryResolveEntityRecordKey(target, out var targetEntityKey) ||
string.IsNullOrWhiteSpace(targetEntityKey))
{
return;
}
Submit(
operations => operations.SetTarget(targetEntityKey),
"target");
}
public void RequestTargetNearest()
{
Submit(operations => operations.TargetNearest(), "target nearest");
}
public void RequestTargetNext()
{
Submit(operations => operations.TargetNext(), "target next");
}
public void RequestTargetPrevious()
{
Submit(operations => operations.TargetPrevious(), "target previous");
}
public void RequestTargetReticle()
{
var lookDirection = _resolveViewDirection();
Submit(
operations => operations.TargetReticle(lookDirection.x, lookDirection.y, lookDirection.z),
"reticle target");
}
public void RequestOverrideShutdown(bool enabled)
{
Submit(operations => operations.SetOverrideShutdown(enabled), "override-shutdown");
}
public void RequestSensorPing()
{
Submit(operations => operations.SensorPing(), "sensor-ping");
}
public void RequestHeatsinksEnabled(bool enabled)
{
Submit(operations => operations.SetHeatsinksEnabled(enabled), "heatsinks");
}
public void RequestShieldToggle()
{
Submit(operations => operations.ToggleShieldEnabled(), "shield enablement");
}
public void RequestDock()
{
Submit(operations => operations.DockNearest(), "dock");
}
public void RequestUndock()
{
if (_resolveCurrentEntity() == null)
return;
Submit(operations => operations.Undock(), "undock");
}
private void Submit(
Action<AetheriaControl> submit,
string label)
{
_resolvePilotCommands()?.TrySubmit(submit, label);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 65505a1513191d64fa99fd51d3508383

View file

@ -0,0 +1,71 @@
/* 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.Linq;
public static class AetheriaUnityRenderSettingsBridge
{
public static AetheriaRuntimeDaemonRenderSettings Build(
GameSettings settings,
float targetSpottedBlinkFrequency,
float targetSpottedBlinkOffset)
{
var emissionCurve = settings.GameplaySettings.TemperatureEmissionCurve;
var bodyIconSizeCurve = settings.IconSize;
var bodyRadiusCurve = settings.PlanetSettings.BodyRadius;
var lightRadiusCurve = settings.PlanetSettings.LightRadius;
var gravityWaveFrequencyCurve = settings.PlanetSettings.WaveFrequency;
return new AetheriaRuntimeDaemonRenderSettings(
new AetheriaRuntimeExponentialCurve(
emissionCurve.Exponent,
emissionCurve.Multiplier,
emissionCurve.Constant),
new AetheriaRuntimeExponentialLerp(
settings.GameplaySettings.LockIndicatorFrequency.Exponent,
settings.GameplaySettings.LockIndicatorFrequency.Minimum,
settings.GameplaySettings.LockIndicatorFrequency.Maximum),
new AetheriaRuntimeExponentialLerp(
settings.GameplaySettings.LockSpinSpeed.Exponent,
settings.GameplaySettings.LockSpinSpeed.Minimum,
settings.GameplaySettings.LockSpinSpeed.Maximum),
settings.GameplaySettings.ConvergenceMinimumDistance,
settings.GameplaySettings.HypothermiaTemperature,
settings.GameplaySettings.HeatstrokeTemperature,
settings.GameplaySettings.SevereHeatstrokeRiskThreshold,
settings.GameplaySettings.TargetDetectionInfoThreshold,
settings.GameplaySettings.LockIndicatorNoiseAmplitude,
settings.HeatstrokePhasingFloor,
settings.HeatstrokePhasingFrequency,
targetSpottedBlinkFrequency,
targetSpottedBlinkOffset,
settings.MinimapZoomLevels?.Select(level => (double)level).ToArray(),
settings.DefaultMinimapZoom,
settings.WormholeDistanceRatio,
settings.DefaultViewDistance,
settings.MinimapIconSize,
settings.MinimapAsteroidSize,
new AetheriaRuntimeExponentialCurve(
bodyIconSizeCurve.Exponent,
bodyIconSizeCurve.Multiplier,
bodyIconSizeCurve.Constant),
settings.MinimapZoneGravityRange,
settings.PlanetSettings.AsteroidVerticalOffset,
settings.PlanetRotationSpeed,
settings.PlanetSettings.ZoneDepthExponent,
settings.PlanetSettings.ZoneDepth + settings.PlanetSettings.ZoneBoundaryFog,
settings.AsteroidMeshCount,
new AetheriaRuntimeExponentialCurve(
bodyRadiusCurve.Exponent,
bodyRadiusCurve.Multiplier,
bodyRadiusCurve.Constant),
new AetheriaRuntimeExponentialCurve(
lightRadiusCurve.Exponent,
lightRadiusCurve.Multiplier,
lightRadiusCurve.Constant),
new AetheriaRuntimeExponentialCurve(
gravityWaveFrequencyCurve.Exponent,
gravityWaveFrequencyCurve.Multiplier,
gravityWaveFrequencyCurve.Constant));
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0d5dc044370e0c340b28db46e4bfeca7

View file

@ -0,0 +1,144 @@
/* 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.IO;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
public static class AetheriaUnityRuntimeClientProvider
{
private static AetheriaClient _runtimeClient;
private static string _runtimeClientStatePath;
private static string _runtimeClientRuntimeId;
private static RuntimePlayerSettings _runtimePlayerSettings;
public static RuntimePlayerSettings PlayerSettings =>
_runtimePlayerSettings ??= LoadPlayerSettings();
public static AetheriaClient ResolveClient(string stateFilePath, string runtimeId = "")
{
var effectiveRuntimeId = string.IsNullOrWhiteSpace(runtimeId) ? "raven-unity" : runtimeId;
if (_runtimeClient != null &&
string.Equals(_runtimeClientStatePath, stateFilePath, StringComparison.Ordinal) &&
string.Equals(_runtimeClientRuntimeId, effectiveRuntimeId, StringComparison.Ordinal))
{
return _runtimeClient;
}
Dispose();
_runtimeClient = AetheriaClient
.OpenAsync(
stateFilePath,
effectiveRuntimeId,
"local",
startServer: false,
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_runtimeClientStatePath = stateFilePath;
_runtimeClientRuntimeId = effectiveRuntimeId;
return _runtimeClient;
}
public static AetheriaClient CurrentClientForStateFile(string stateFilePath)
{
return _runtimeClient != null &&
string.Equals(_runtimeClientStatePath, stateFilePath, StringComparison.Ordinal)
? _runtimeClient
: null;
}
public static void Dispose()
{
_runtimeClient?.Dispose();
_runtimeClient = null;
_runtimeClientStatePath = null;
_runtimeClientRuntimeId = null;
}
private static RuntimePlayerSettings LoadPlayerSettings()
{
var settings = CreateDefaultPlayerSettings();
try
{
var stored = ResolveClient(AetheriaUnityRuntimePaths.RuntimeStateFilePath)
.PlayerSettingsAsync()
.GetAwaiter()
.GetResult();
if (stored == null)
return settings;
ApplyPlayerSettings(settings, stored);
Debug.Log("Loaded Aetheria Verse player settings from typed state.");
}
catch (FileNotFoundException)
{
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to load Aetheria Verse player settings from typed state; using defaults: {ex}");
}
return settings;
}
private static RuntimePlayerSettings CreateDefaultPlayerSettings()
{
var settings = new RuntimePlayerSettings();
settings.Name = Environment.UserName;
settings.InputSettings.SetActionBarInputEnabled("<Keyboard>/leftShift", true);
settings.InputSettings.SetActionBarInputEnabled("<Mouse>/leftButton", true);
settings.InputSettings.SetActionBarInputEnabled("<Mouse>/rightButton", true);
settings.InputSettings.SetActionBarInputEnabled("<Mouse>/middleButton", true);
for (var i = 1; i < 6; i++)
settings.InputSettings.SetActionBarInputEnabled($"<Keyboard>/{i}", true);
return settings;
}
private static void ApplyPlayerSettings(
RuntimePlayerSettings settings,
AetheriaRuntimePlayerSettingsSnapshot stored)
{
if (!string.IsNullOrWhiteSpace(stored.PlayerName))
settings.Name = stored.PlayerName;
settings.TutorialPassed = stored.TutorialPassed;
settings.HashedStoryFiles.Clear();
foreach (var storyFileHash in stored.StoryFileHashes)
{
if (!string.IsNullOrWhiteSpace(storyFileHash.StoryPath))
settings.HashedStoryFiles[storyFileHash.StoryPath] = storyFileHash.Hash;
}
if (Enum.TryParse(stored.TemperatureUnit, out TemperatureUnit temperatureUnit))
settings.GameplaySettings.TemperatureUnit = temperatureUnit;
settings.GameplaySettings.SignificantDigits = Math.Max(0, stored.SignificantDigits);
if (Enum.TryParse(stored.NebulaQuality, out Quality nebulaQuality))
settings.GraphicsSettings.NebulaQuality = nebulaQuality;
settings.GraphicsSettings.ShowAsteroidsInMinimap = stored.ShowAsteroidsInMinimap;
settings.InputSettings.InputActionMap.Clear();
foreach (var binding in stored.BindingOverrides)
{
if (string.IsNullOrWhiteSpace(binding.ActionName) ||
string.IsNullOrWhiteSpace(binding.BindingPath) ||
binding.BindingIndex < 0)
{
continue;
}
settings.InputSettings.SetBindingOverride(binding.ActionName, binding.BindingIndex, binding.BindingPath);
}
settings.InputSettings.ActionBarInputs.Clear();
foreach (var input in stored.ActionBarInputs)
{
if (!string.IsNullOrWhiteSpace(input))
settings.InputSettings.SetActionBarInputEnabled(input, true);
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 95ae2790dbb68864a954847834215f2f

View file

@ -0,0 +1,20 @@
using System.IO;
using GameCult.Aetheria.State.Verse;
using UnityEngine;
public static class AetheriaUnityRuntimePaths
{
private static DirectoryInfo _gameDataDirectory;
private static string _runtimeStateFilePath;
public static DirectoryInfo GameDataDirectory =>
_gameDataDirectory ??= new DirectoryInfo(Application.dataPath).Parent.CreateSubdirectory("GameData");
public static string RuntimeStateFilePath =>
_runtimeStateFilePath ??= AetheriaRuntimeStateBoot.Inspect(GameDataDirectory).StateFilePath;
public static void ClearRuntimeStateFilePathCache()
{
_runtimeStateFilePath = null;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 36e68ebb69d4af84cb7f485e11fd6e6c

View file

@ -0,0 +1,232 @@
/* 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 GameCult.Aetheria.State.Verse;
using UnityEngine;
using UnityEngine.UI;
using float3 = Unity.Mathematics.float3;
public sealed class AetheriaUnityTargetPresentation
{
private readonly Dictionary<Entity, VisibleTargetIndicator> _visibleHostileIndicators =
new Dictionary<Entity, VisibleTargetIndicator>();
private readonly Dictionary<Entity, VisibleTargetIndicator> _visibleFriendlyIndicators =
new Dictionary<Entity, VisibleTargetIndicator>();
private readonly HashSet<Entity> _observedHostileIndicatorTargets = new HashSet<Entity>();
private readonly HashSet<Entity> _observedFriendlyIndicatorTargets = new HashSet<Entity>();
private readonly List<Entity> _staleIndicatorTargets = new List<Entity>();
public ZoneRenderer ZoneRenderer { get; set; }
public Prototype HostileTargetIndicator { get; set; }
public Prototype FriendlyTargetIndicator { get; set; }
public PlaceUIElementWorldspace ViewDot { get; set; }
public PlaceUIElementWorldspace TargetIndicator { get; set; }
public Image TargetHitpointsFill { get; set; }
public Image TargetVisibilityFill { get; set; }
public Image VisibilityToTargetFill { get; set; }
public Image TargetShieldsFill { get; set; }
public AetheriaRuntimeCatalogSnapshot RuntimeCatalog { get; set; }
public Func<AetheriaClient> ResolveClient { get; set; }
public Func<int, Entity> ResolveEntity { get; set; }
public Func<Entity, Entity> ResolveTarget { get; set; }
public Func<Entity, Entity, float> ResolveInfoGathered { get; set; }
public Func<Entity, Entity, bool> ResolveHostileContact { get; set; }
public Func<Entity, double, bool, AetheriaRuntimeZoneContactRow[]> ResolveVisibleContacts { get; set; }
public Entity Tick(Entity currentEntity, float time)
{
var observedTarget = ResolveTarget?.Invoke(currentEntity);
ReconcileVisibleTargetIndicators(currentEntity);
UpdateVisibleIndicatorPresentation(
_visibleHostileIndicators,
currentEntity,
observedTarget,
time,
blinkSpottedTargets: true);
UpdateVisibleIndicatorPresentation(
_visibleFriendlyIndicators,
currentEntity,
observedTarget,
time,
blinkSpottedTargets: false);
UpdateTargetStatus(currentEntity, observedTarget);
return observedTarget;
}
public void ReconcileVisibleTargetIndicators(Entity currentEntity)
{
_observedHostileIndicatorTargets.Clear();
_observedFriendlyIndicatorTargets.Clear();
var renderSettings = ZoneRenderer?.RenderSettings;
if (currentEntity != null && renderSettings != null)
{
var contacts = ResolveVisibleContacts?.Invoke(
currentEntity,
renderSettings.TargetDetectionInfoThreshold,
true) ?? Array.Empty<AetheriaRuntimeZoneContactRow>();
foreach (var contact in contacts)
{
if (ResolveEntity?.Invoke(contact.TargetEntityIndex) is not { } target ||
ReferenceEquals(target, currentEntity))
{
continue;
}
if (contact.Hostile)
_observedHostileIndicatorTargets.Add(target);
else
_observedFriendlyIndicatorTargets.Add(target);
}
}
ReconcileVisibleTargetIndicators(
_visibleHostileIndicators,
_observedHostileIndicatorTargets,
HostileTargetIndicator);
ReconcileVisibleTargetIndicators(
_visibleFriendlyIndicators,
_observedFriendlyIndicatorTargets,
FriendlyTargetIndicator);
}
public void ClearIndicators()
{
ClearIndicators(_visibleHostileIndicators);
ClearIndicators(_visibleFriendlyIndicators);
}
public void UpdateTargetIndicators(
Entity currentEntity,
bool isCurrentEntityObservedUndocked,
AetheriaUnityCurrentEntityPresentation currentEntityPresentation)
{
if (!isCurrentEntityObservedUndocked ||
currentEntity == null ||
ZoneRenderer == null ||
ViewDot == null ||
!ZoneRenderer.TryGetEntityInstance(currentEntity, out var entityInstance))
{
return;
}
var observedTarget = ResolveTarget?.Invoke(currentEntity);
ViewDot.Target = entityInstance.LookAtPoint.position;
if (observedTarget != null && TargetIndicator != null)
TargetIndicator.Target = observedTarget.Position;
var distance = CultMath.math.length(AetheriaMath.ToCult((float3)ViewDot.Target) - currentEntity.CultPosition);
foreach (var (_, barrels, crosshair) in currentEntityPresentation.ArticulationGroups)
{
var averagePosition = Vector3.zero;
foreach (var barrel in barrels)
averagePosition += barrel.position + barrel.forward * distance;
averagePosition /= barrels.Length;
crosshair.Target = averagePosition;
}
foreach (var (targetLock, indicator, spin) in currentEntityPresentation.LockingIndicators)
{
var showLockingIndicator = targetLock.Lock > .01f &&
observedTarget != null &&
ResolveHostileContact?.Invoke(currentEntity, observedTarget) == true;
indicator.gameObject.SetActive(showLockingIndicator);
if (!showLockingIndicator)
continue;
var renderSettings = ZoneRenderer.RenderSettings;
indicator.Target = observedTarget.Position;
indicator.NoiseAmplitude = (float)renderSettings.ResolveLockIndicatorNoiseAmplitude(targetLock.Lock);
indicator.NoiseFrequency = (float)renderSettings.ResolveLockIndicatorNoiseFrequency(targetLock.Lock);
spin.Speed = (float)renderSettings.ResolveLockSpinSpeed(targetLock.Lock);
}
}
private void UpdateVisibleIndicatorPresentation(
Dictionary<Entity, VisibleTargetIndicator> indicators,
Entity currentEntity,
Entity observedTarget,
float time,
bool blinkSpottedTargets)
{
var renderSettings = ZoneRenderer?.RenderSettings;
if (renderSettings == null)
return;
foreach (var indicator in indicators)
{
indicator.Value.gameObject.SetActive(indicator.Key != observedTarget);
indicator.Value.Place.Target = indicator.Key.Position;
if (!indicator.Key.Active)
{
indicator.Value.Fill.enabled = false;
continue;
}
var infoGathered = ResolveInfoGathered?.Invoke(indicator.Key, currentEntity) ?? 0f;
indicator.Value.Fill.fillAmount = (float)renderSettings.NormalizeDetectionProgress(infoGathered);
indicator.Value.Fill.enabled = !blinkSpottedTargets ||
renderSettings.ResolveTargetSpottedFillEnabled(infoGathered, time);
}
}
private void UpdateTargetStatus(Entity currentEntity, Entity target)
{
if (currentEntity == null || target == null || ZoneRenderer?.RenderSettings == null)
return;
var renderSettings = ZoneRenderer.RenderSettings;
var targetInfoGathered = ResolveInfoGathered?.Invoke(currentEntity, target) ?? 0f;
var visibilityToTarget = ResolveInfoGathered?.Invoke(target, currentEntity) ?? 0f;
TargetVisibilityFill.fillAmount = (float)renderSettings.NormalizeTargetVisibilityFill(targetInfoGathered);
VisibilityToTargetFill.fillAmount = (float)renderSettings.NormalizeVisibilityToTargetFill(visibilityToTarget);
var targetHull = RuntimeCatalog?.FindItem(target.Hull?.ItemKey ?? "");
var targetMaxDurability = targetHull?.Durability > 0
? (float)targetHull.Durability
: Math.Max(target.Hull.Durability, 1f);
TargetHitpointsFill.fillAmount =
(float)renderSettings.NormalizeTargetStatusFill(target.Hull.Durability / targetMaxDurability);
TargetShieldsFill.fillAmount = target.Shield == null
? 0
: (float)renderSettings.NormalizeTargetStatusFill(target.Shield.Progress);
}
private void ReconcileVisibleTargetIndicators(
Dictionary<Entity, VisibleTargetIndicator> indicators,
HashSet<Entity> desiredTargets,
Prototype prototype)
{
if (prototype == null)
return;
_staleIndicatorTargets.Clear();
foreach (var indicator in indicators)
{
if (!desiredTargets.Contains(indicator.Key))
_staleIndicatorTargets.Add(indicator.Key);
}
foreach (var staleTarget in _staleIndicatorTargets)
{
indicators[staleTarget].GetComponent<Prototype>().ReturnToPool();
indicators.Remove(staleTarget);
}
foreach (var target in desiredTargets)
{
if (!indicators.ContainsKey(target))
indicators.Add(target, prototype.Instantiate<VisibleTargetIndicator>());
}
}
private static void ClearIndicators(Dictionary<Entity, VisibleTargetIndicator> indicators)
{
foreach (var indicator in indicators.Values)
indicator.GetComponent<Prototype>().ReturnToPool();
indicators.Clear();
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 51baf83a22ca0be45abd418061686244

View file

@ -0,0 +1,36 @@
/* 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 GameCult.Aetheria.State.Verse;
public static class AetheriaUnityWeaponPresentationPolicy
{
private static readonly HashSet<string> ArticulatedWeaponBehaviorKinds = new HashSet<string>(StringComparer.Ordinal)
{
"GuidedWeapon",
"InstantWeapon",
"ConstantWeapon",
"ChargedWeapon",
"AutoWeapon"
};
public static bool HasArticulatedWeaponBehavior(
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
EquippedItem item)
{
var typedItem = runtimeCatalog?.FindItem(item?.EquippableItem?.ItemKey ?? "");
if (typedItem?.BehaviorKinds == null)
return false;
foreach (var behaviorKind in typedItem.BehaviorKinds)
{
if (ArticulatedWeaponBehaviorKinds.Contains(behaviorKind))
return true;
}
return false;
}
}

View file

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

View file

@ -41,11 +41,6 @@ public class EntityInstance : MonoBehaviour
// private (Reactor reactor, GameObject sfxSource) _reactor;
// private Dictionary<Radiator, GameObject> _radiatorSfx = new Dictionary<Radiator, GameObject>();
private static AetheriaRuntimeCatalogItem FindTypedHull(ItemInstance hull)
{
return ActionGameManager.RuntimeCatalog?.FindItem(hull?.ItemKey ?? "");
}
private static Vector2 ToVector2(CultMath.float2 value) => new Vector2(value.x, value.y);
private static Vector2 ToVector2(Unity.Mathematics.float2 value) => new Vector2(value.x, value.y);
@ -156,7 +151,7 @@ public class EntityInstance : MonoBehaviour
Entity = entity;
DaemonEntityIndex = entity.DaemonEntityIndex;
ZoneRenderer = zoneRenderer;
var typedHull = FindTypedHull(entity.Hull);
var typedHull = ZoneRenderer?.FindCatalogItem(entity.Hull);
if (typedHull == null || typedHull.ShapeWidth <= 0 || typedHull.ShapeHeight <= 0 || typedHull.ShapeCells.Count == 0)
{
Debug.LogError($"Cannot bind entity instance for {entity.Name}: missing typed hull shape.");

View file

@ -473,13 +473,15 @@ public sealed class AetheriaYmirPhysicsBridge : MonoBehaviour
? 1.0f / inverseMass
: 1.0f;
var rotation = view.HasRotation ? view.RotationRadians[i] : 0;
var position = view.Position[i];
var velocity = view.HasVelocity ? view.Velocity[i] : default;
_daemonBodies.Add(new YmirPhysicsBody
{
id = DaemonEntityBodyPrefix + daemonEntityIndex,
position = new YmirVec2 { x = view.PositionX[i], y = view.PositionZ[i] },
position = new YmirVec2 { x = position.x, y = position.z },
velocity = view.HasVelocity
? new YmirVec2 { x = view.VelocityX[i], y = view.VelocityZ[i] }
? new YmirVec2 { x = velocity.x, y = velocity.z }
: default,
direction = new YmirVec2 { x = Mathf.Sin(rotation), y = Mathf.Cos(rotation) },
angularVelocity = 0,

View file

@ -131,15 +131,10 @@ public class ShipInstance : EntityInstance
private float GetMaxDurability(ItemInstance item)
{
var typedItem = FindTypedItem(item);
var typedItem = ZoneRenderer?.FindCatalogItem(item);
if (typedItem != null && typedItem.Durability > 0)
return (float)typedItem.Durability;
return item is EquippableItem equippable ? Math.Max(equippable.Durability, 1f) : 1f;
}
private static AetheriaRuntimeCatalogItem FindTypedItem(ItemInstance item)
{
return ActionGameManager.RuntimeCatalog?.FindItem(item?.ItemKey ?? "");
}
}

View file

@ -16,6 +16,7 @@ public class ConstantLaser : MonoBehaviour
public float Spread { get; set; }
public DamageType DamageType { get; set; }
public Entity SourceEntity { get; set; }
public ZoneRenderer ZoneRenderer { get; set; }
public float Range { get; set; }
private float _intensity;
@ -69,7 +70,7 @@ public class ConstantLaser : MonoBehaviour
LineRenderer.SetPosition(0, transform.position);
var hitFound = false;
if (AetheriaYmirPhysicsBridge.Instance.TryCastZoneHulls(
ActionGameManager.Instance?.ZoneRenderer,
ZoneRenderer,
SourceEntity,
transform.position,
transform.forward,

View file

@ -12,6 +12,7 @@ public class ConstantLaserManager : ConstantWeaponEffectManager
{
var p = LaserPrototype.Instantiate<ConstantLaser>();
p.SourceEntity = source.Entity;
p.ZoneRenderer = source.ZoneRenderer;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var barrel = source.GetBarrel(hp);
p.Range = weapon.Range;

View file

@ -39,6 +39,7 @@ public class GuidedProjectile : MonoBehaviour
public float Spread { get; set; }
public DamageType DamageType { get; set; }
public Entity SourceEntity { get; set; }
public ZoneRenderer ZoneRenderer { get; set; }
public event Action OnKill;
@ -112,6 +113,7 @@ public class GuidedProjectile : MonoBehaviour
child.Source = Source;
child.Target = Target;
child.SourceEntity = SourceEntity;
child.ZoneRenderer = ZoneRenderer;
child.GuidanceCurve = GuidanceCurve;
child.LiftCurve = LiftCurve;
child.ThrustCurve = ThrustCurve;
@ -144,7 +146,7 @@ public class GuidedProjectile : MonoBehaviour
if(_alive)
{
if (AetheriaYmirPhysicsBridge.Instance.TryCastZoneHulls(
ActionGameManager.Instance?.ZoneRenderer,
ZoneRenderer,
SourceEntity,
t.position,
Velocity,

View file

@ -25,6 +25,7 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
var p = ProjectilePrototype.Instantiate<GuidedProjectile>();
p.Source = source.transform;
p.SourceEntity = source.Entity;
p.ZoneRenderer = source.ZoneRenderer;
p.Target = target.transform;
p.Frequency = weapon.GuidedProjectileDodgeFrequency;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
@ -48,6 +49,7 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
var p = ProjectilePrototype.Instantiate<GuidedProjectile>();
p.Source = source.transform;
p.SourceEntity = source.Entity;
p.ZoneRenderer = source.ZoneRenderer;
p.Frequency = weapon.GuidedProjectileDodgeFrequency;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var barrel = source.GetBarrel(hp);

View file

@ -13,6 +13,7 @@ public class HitscanEffect : MonoBehaviour
public float Spread { get; set; }
public DamageType DamageType { get; set; }
public Entity SourceEntity { get; set; }
public ZoneRenderer ZoneRenderer { get; set; }
public float Range { get; set; }
private float _startTime;
@ -23,7 +24,7 @@ public class HitscanEffect : MonoBehaviour
_startTime = Time.time;
var hitFound = false;
if (AetheriaYmirPhysicsBridge.Instance.TryCastZoneHulls(
ActionGameManager.Instance?.ZoneRenderer,
ZoneRenderer,
SourceEntity,
transform.position,
transform.forward,

View file

@ -7,6 +7,7 @@ public class HitscanManager : InstantWeaponEffectManager
{
var p = Prototype.Instantiate<HitscanEffect>();
p.SourceEntity = source.Entity;
p.ZoneRenderer = source.ZoneRenderer;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var barrel = source.GetBarrel(hp);
var t = p.transform;

View file

@ -13,6 +13,7 @@ public class Laser : MonoBehaviour
public float Spread { get; set; }
public DamageType DamageType { get; set; }
public Entity SourceEntity { get; set; }
public ZoneRenderer ZoneRenderer { get; set; }
public float Range { get; set; }
private float _startTime;
@ -36,7 +37,7 @@ public class Laser : MonoBehaviour
LineRenderer.SetPosition(0, transform.position);
var hitFound = false;
if (AetheriaYmirPhysicsBridge.Instance.TryCastZoneHulls(
ActionGameManager.Instance?.ZoneRenderer,
ZoneRenderer,
SourceEntity,
transform.position,
transform.forward,

View file

@ -16,6 +16,7 @@ public class LaserManager : InstantWeaponEffectManager
t.forward = barrel.forward;
t.position = barrel.position;
p.SourceEntity = source.Entity;
p.ZoneRenderer = source.ZoneRenderer;
p.Damage = weapon.Damage;
p.Range = weapon.Range;
p.Penetration = weapon.Penetration;

View file

@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using Unity.Mathematics;
public static class AetheriaRuntimeLoadoutProjector
{
public static AetheriaRuntimeLoadoutTemplateCommit ProjectLoadoutTemplate(EntityConstructionBlueprint blueprint)
{
return new AetheriaRuntimeLoadoutTemplateCommit
{
Name = blueprint?.Name ?? "",
OwnerPlayerKey = "global:aetheria.player_settings.v1",
RootEntity = ProjectEntityLoadout(blueprint)
};
}
public static AetheriaRuntimeLoadoutTemplateCommit ProjectLoadoutTemplate(Entity entity)
{
return new AetheriaRuntimeLoadoutTemplateCommit
{
Name = entity?.Name ?? "",
OwnerPlayerKey = "global:aetheria.player_settings.v1",
RootEntity = ProjectEntityLoadout(entity)
};
}
private static AetheriaRuntimeEntityLoadoutCommit ProjectEntityLoadout(EntityConstructionBlueprint blueprint)
{
return new AetheriaRuntimeEntityLoadoutCommit
{
Name = blueprint?.Name ?? "",
Kind = blueprint is ShipConstructionBlueprint ? "ship" : blueprint is OrbitalEntityConstructionBlueprint ? "orbital" : "entity",
FactionKey = blueprint?.FactionKey ?? "",
Hull = ProjectLoadoutItem(blueprint?.Hull),
Equipment = ProjectSlots(blueprint?.Equipment),
CargoBays = ProjectSlots(blueprint?.CargoBays),
DockingBays = ProjectSlots(blueprint?.DockingBays),
CargoContents = ProjectCargoBays(blueprint?.CargoContents),
DockingBayContents = ProjectCargoBays(blueprint?.DockingBayContents),
DockingBayAssignments = blueprint?.DockingBayAssignments ?? Array.Empty<int>(),
WeaponGroups = blueprint?.WeaponGroups?.Select(group => (IReadOnlyList<int>)group).ToArray() ?? Array.Empty<IReadOnlyList<int>>(),
Children = blueprint?.Children?.Select(ProjectEntityLoadout).ToArray() ?? Array.Empty<AetheriaRuntimeEntityLoadoutCommit>()
};
}
private static AetheriaRuntimeEntityLoadoutCommit ProjectEntityLoadout(Entity entity)
{
return new AetheriaRuntimeEntityLoadoutCommit
{
Name = entity?.Name ?? "",
Kind = entity is Ship ? "ship" : entity is OrbitalEntity ? "orbital" : "entity",
FactionKey = entity?.Faction?.FactionKey ?? "",
Hull = ProjectLoadoutItem(entity?.Hull),
Equipment = ProjectSlots(entity?.Equipment),
CargoBays = ProjectSlots(entity?.CargoBays),
DockingBays = ProjectSlots(entity?.DockingBays),
CargoContents = ProjectCargoBays(entity?.CargoBays),
DockingBayContents = ProjectCargoBays(entity?.DockingBays),
DockingBayAssignments = entity?.DockingBays?
.Select(dockingBay => entity.Children.IndexOf(dockingBay.DockedShip))
.ToArray() ?? Array.Empty<int>(),
WeaponGroups = entity?.WeaponGroups?
.Select(group => (IReadOnlyList<int>)group.items
.Select(item => entity.Equipment.IndexOf(item))
.ToArray())
.ToArray() ?? Array.Empty<IReadOnlyList<int>>(),
Children = entity?.Children?
.Select(ProjectEntityLoadout)
.ToArray() ?? Array.Empty<AetheriaRuntimeEntityLoadoutCommit>()
};
}
private static AetheriaRuntimeLoadoutItemSlotCommit[] ProjectSlots((int2 position, EquippableItem item)[] slots)
{
return slots?
.Select(slot => new AetheriaRuntimeLoadoutItemSlotCommit
{
X = slot.position.x,
Y = slot.position.y,
Item = ProjectLoadoutItem(slot.item)
})
.ToArray() ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotCommit>();
}
private static AetheriaRuntimeLoadoutItemSlotCommit[] ProjectSlots(IEnumerable<EquippedItem> slots)
{
return slots?
.Select(slot => new AetheriaRuntimeLoadoutItemSlotCommit
{
X = slot.Position.x,
Y = slot.Position.y,
Item = ProjectLoadoutItem(slot.EquippableItem, slot.Temperature)
})
.ToArray() ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotCommit>();
}
private static AetheriaRuntimeCargoBayLoadoutCommit[] ProjectCargoBays((int2 position, ItemInstance item)[][] bays)
{
return bays?
.Select(bay => new AetheriaRuntimeCargoBayLoadoutCommit
{
Items = bay?
.Select(slot => new AetheriaRuntimeLoadoutItemSlotCommit
{
X = slot.position.x,
Y = slot.position.y,
Item = ProjectLoadoutItem(slot.item)
})
.ToArray() ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotCommit>()
})
.ToArray() ?? Array.Empty<AetheriaRuntimeCargoBayLoadoutCommit>();
}
private static AetheriaRuntimeCargoBayLoadoutCommit[] ProjectCargoBays(IEnumerable<EquippedCargoBay> bays)
{
return bays?
.Select(bay => new AetheriaRuntimeCargoBayLoadoutCommit
{
Items = bay.Cargo?
.Select(slot => new AetheriaRuntimeLoadoutItemSlotCommit
{
X = slot.Value.x,
Y = slot.Value.y,
Item = ProjectLoadoutItem(slot.Key)
})
.ToArray() ?? Array.Empty<AetheriaRuntimeLoadoutItemSlotCommit>()
})
.ToArray() ?? Array.Empty<AetheriaRuntimeCargoBayLoadoutCommit>();
}
private static AetheriaRuntimeLoadoutItemCommit ProjectLoadoutItem(
ItemInstance item,
double temperature = 0)
{
if (item == null)
return new AetheriaRuntimeLoadoutItemCommit();
return new AetheriaRuntimeLoadoutItemCommit
{
ItemKey = item.ItemKey,
Quality = item is CraftedItemInstance crafted ? crafted.Quality : 1.0,
Durability = item is EquippableItem equippable ? equippable.Durability : 1.0,
Quantity = item is SimpleCommodity commodity ? commodity.Quantity : 1,
Enabled = true,
OverrideShutdown = item is EquippableItem overrideable && overrideable.OverrideShutdown,
Temperature = temperature
};
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 59812ba0964c83444ba4389689548195

View file

@ -91,6 +91,15 @@ public class Galaxy
if(progressCallback!=null) Thread.Sleep(500); // Inserting Delay to make it seem like it's doing more work lmao
}
public static Galaxy ProjectObservedSectorMap(
AetheriaRuntimeSectorMapDocument sectorMap,
SectorBackgroundSettings background,
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
Action<string> log)
{
return new Galaxy(sectorMap, background, runtimeCatalog, log);
}
public static Galaxy ProjectObservedDaemonRun(
AetheriaRuntimeRunCheckpointCommit run,
SectorBackgroundSettings background,
@ -115,9 +124,9 @@ public class Galaxy
Log = log;
GenerationSeed = run.GenerationSeed;
NameGeneratorSettings = null;
Factions = ResolveDaemonFactions(run);
Factions = ResolveRunFactions(run);
foreach (var faction in Factions)
FactionRelationships[faction] = ResolveDaemonFactionRelationship(run, faction);
FactionRelationships[faction] = ResolveRunFactionRelationship(run, faction);
Zones = (run.Zones ?? Array.Empty<AetheriaRuntimeZoneSnapshotCommit>())
.Where(zone => zone != null && zone.ZoneIndex >= 0)
@ -127,8 +136,8 @@ public class Galaxy
ZoneIndex = zone.ZoneIndex,
Name = string.IsNullOrWhiteSpace(zone.Name) ? $"Daemon Zone {zone.ZoneIndex}" : zone.Name,
Position = new float2((float)zone.PositionX, (float)zone.PositionY),
Factions = ResolveDaemonZoneFactions(zone),
Owner = ResolveDaemonFactionByIndex(zone.OwnerFactionIndex),
Factions = ResolveRunZoneFactions(zone),
Owner = ResolveFactionByIndex(zone.OwnerFactionIndex),
NamedZone = !string.IsNullOrWhiteSpace(zone.Name)
})
.ToArray();
@ -154,11 +163,13 @@ public class Galaxy
}
}
Entrance = ResolveDaemonZone(run.EntranceZoneIndex) ?? ResolveDaemonZone(run.CurrentZoneIndex) ?? Zones.FirstOrDefault();
Exit = ResolveDaemonZone(run.ExitZoneIndex);
Entrance = ResolveRunZone(run.EntranceZoneIndex) ??
ResolveRunZone(run.CurrentZoneIndex) ??
Zones.FirstOrDefault();
Exit = ResolveRunZone(run.ExitZoneIndex);
foreach (var zone in run.DiscoveredZoneIndices ?? Array.Empty<int>())
{
var discovered = ResolveDaemonZone(zone);
var discovered = ResolveRunZone(zone);
if (discovered != null)
DiscoveredZones.Add(discovered);
}
@ -167,13 +178,128 @@ public class Galaxy
CalculateDistanceMatrix();
GalaxyZone ResolveDaemonZone(int zoneIndex)
GalaxyZone ResolveRunZone(int zoneIndex)
{
return zonesByIndex.TryGetValue(zoneIndex, out var zone) ? zone : null;
}
}
private Faction[] ResolveDaemonFactions(AetheriaRuntimeRunCheckpointCommit run)
private Galaxy(
AetheriaRuntimeSectorMapDocument sectorMap,
SectorBackgroundSettings background,
AetheriaRuntimeCatalogSnapshot runtimeCatalog,
Action<string> log)
{
if (sectorMap == null) throw new ArgumentNullException(nameof(sectorMap));
_runtimeCatalog = runtimeCatalog ?? throw new InvalidOperationException("Daemon-observed galaxy requires the typed Aetheria runtime catalog.");
_allFactions = ProjectFactions(_runtimeCatalog);
IsPrelude = sectorMap.IsTutorial;
Background = background;
Log = log;
GenerationSeed = sectorMap.GenerationSeed;
NameGeneratorSettings = null;
Factions = ResolveSectorMapFactions(sectorMap);
foreach (var faction in Factions)
FactionRelationships[faction] = ResolveSectorMapFactionRelationship(sectorMap, faction);
Zones = (sectorMap.Zones ?? Array.Empty<AetheriaRuntimeSectorMapZone>())
.Where(zone => zone != null && zone.ZoneIndex >= 0)
.OrderBy(zone => zone.ZoneIndex)
.Select(zone => new GalaxyZone
{
ZoneIndex = zone.ZoneIndex,
Name = string.IsNullOrWhiteSpace(zone.Name) ? $"Daemon Zone {zone.ZoneIndex}" : zone.Name,
Position = new float2((float)zone.X, (float)zone.Y),
Factions = ResolveSectorMapZoneFactions(zone),
Owner = ResolveFactionByIndex(zone.OwnerFactionIndex),
NamedZone = !string.IsNullOrWhiteSpace(zone.Name)
})
.ToArray();
var zonesByIndex = (sectorMap.Zones ?? Array.Empty<AetheriaRuntimeSectorMapZone>())
.Where(zone => zone != null && zone.ZoneIndex >= 0)
.OrderBy(zone => zone.ZoneIndex)
.Select((zone, ordinal) => new { zone.ZoneIndex, Zone = Zones[ordinal] })
.ToDictionary(pair => pair.ZoneIndex, pair => pair.Zone);
foreach (var link in sectorMap.Links ?? Array.Empty<AetheriaRuntimeSectorMapLink>())
{
if (link == null ||
!zonesByIndex.TryGetValue(link.FromZoneIndex, out var from) ||
!zonesByIndex.TryGetValue(link.ToZoneIndex, out var to))
continue;
if (!from.AdjacentZones.Contains(to))
from.AdjacentZones.Add(to);
if (!to.AdjacentZones.Contains(from))
to.AdjacentZones.Add(from);
}
foreach (var source in sectorMap.Zones ?? Array.Empty<AetheriaRuntimeSectorMapZone>())
{
if (source == null || !zonesByIndex.TryGetValue(source.ZoneIndex, out var sourceZone))
continue;
foreach (var adjacentIndex in source.AdjacentZoneIndices ?? Array.Empty<int>())
{
if (zonesByIndex.TryGetValue(adjacentIndex, out var adjacentZone) &&
!sourceZone.AdjacentZones.Contains(adjacentZone))
{
sourceZone.AdjacentZones.Add(adjacentZone);
}
}
}
Entrance = ResolveSectorMapZone(sectorMap.EntranceZoneIndex) ??
ResolveSectorMapZone(sectorMap.CurrentZoneIndex) ??
Zones.FirstOrDefault();
Exit = ResolveSectorMapZone(sectorMap.ExitZoneIndex);
foreach (var zone in sectorMap.DiscoveredZoneIndices ?? Array.Empty<int>())
{
var discovered = ResolveSectorMapZone(zone);
if (discovered != null)
DiscoveredZones.Add(discovered);
}
if (DiscoveredZones.Count == 0 && Entrance != null)
DiscoveredZones.Add(Entrance);
CalculateDistanceMatrix();
GalaxyZone ResolveSectorMapZone(int zoneIndex)
{
return zonesByIndex.TryGetValue(zoneIndex, out var zone) ? zone : null;
}
}
private Faction[] ResolveSectorMapFactions(AetheriaRuntimeSectorMapDocument sectorMap)
{
var factionKeys = new HashSet<string>(
(sectorMap.FactionRelationships ?? Array.Empty<AetheriaRuntimeFactionRelationshipCommit>())
.Select(relationship => relationship?.FactionKey)
.Where(key => !string.IsNullOrWhiteSpace(key)),
StringComparer.OrdinalIgnoreCase);
var factionIndices = (sectorMap.Zones ?? Array.Empty<AetheriaRuntimeSectorMapZone>())
.Where(zone => zone != null)
.SelectMany(zone => (zone.FactionIndices ?? Array.Empty<int>()).Concat(new[] { zone.OwnerFactionIndex }))
.Where(index => index >= 0)
.Distinct()
.ToArray();
foreach (var index in factionIndices)
{
if (index >= 0 && index < _allFactions.Length)
factionKeys.Add(_allFactions[index].FactionKey);
}
var factions = _allFactions
.Where(faction => factionKeys.Contains(faction.FactionKey))
.ToArray();
return factions.Length == 0 ? _allFactions : factions;
}
private Faction[] ResolveRunFactions(AetheriaRuntimeRunCheckpointCommit run)
{
var factionKeys = new HashSet<string>(
(run.FactionRelationships ?? Array.Empty<AetheriaRuntimeFactionRelationshipCommit>())
@ -200,20 +326,39 @@ public class Galaxy
return factions.Length == 0 ? _allFactions : factions;
}
private Faction[] ResolveDaemonZoneFactions(AetheriaRuntimeZoneSnapshotCommit zone)
private Faction[] ResolveSectorMapZoneFactions(AetheriaRuntimeSectorMapZone zone)
{
return (zone.FactionIndices ?? Array.Empty<int>())
.Select(ResolveDaemonFactionByIndex)
.Select(ResolveFactionByIndex)
.Where(faction => faction != null)
.ToArray();
}
private Faction ResolveDaemonFactionByIndex(int index)
private Faction[] ResolveRunZoneFactions(AetheriaRuntimeZoneSnapshotCommit zone)
{
return (zone.FactionIndices ?? Array.Empty<int>())
.Select(ResolveFactionByIndex)
.Where(faction => faction != null)
.ToArray();
}
private Faction ResolveFactionByIndex(int index)
{
return index >= 0 && index < _allFactions.Length ? _allFactions[index] : null;
}
private FactionRelationship ResolveDaemonFactionRelationship(
private FactionRelationship ResolveSectorMapFactionRelationship(
AetheriaRuntimeSectorMapDocument sectorMap,
Faction faction)
{
var relationship = (sectorMap.FactionRelationships ?? Array.Empty<AetheriaRuntimeFactionRelationshipCommit>())
.FirstOrDefault(candidate => string.Equals(candidate?.FactionKey ?? "", faction?.FactionKey ?? "", StringComparison.OrdinalIgnoreCase));
return Enum.TryParse<FactionRelationship>(relationship?.Relationship ?? "", out var parsed)
? parsed
: FactionRelationship.Neutral;
}
private FactionRelationship ResolveRunFactionRelationship(
AetheriaRuntimeRunCheckpointCommit run,
Faction faction)
{

View file

@ -58,4 +58,17 @@ public sealed class CultMathPrimitiveTests
Assert.AreEqual(float3(1, 0, 0), rgb);
Assert.AreEqual(new Unity.Mathematics.float3(1, 0, 0), AetheriaMath.ToUnity(rgb));
}
[Test]
public void RectNormalizesBoundsAndContainsPoints()
{
var viewport = rect(10, 20, -5, -2);
Assert.AreEqual(float2(-5, -2), viewport.min);
Assert.AreEqual(float2(10, 20), viewport.max);
Assert.AreEqual(float2(15, 22), viewport.size);
Assert.AreEqual(float2(2.5f, 9), viewport.center);
Assert.IsTrue(viewport.Contains(float2(0, 0)));
Assert.IsFalse(viewport.Contains(float2(11, 0)));
}
}

View file

@ -1,11 +1,18 @@
using CultMath;
using GameCult.Aetheria.State.Verse;
using GameCult.Eve.Surface;
using GameCult.Mesh;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using EveCommandTemplate = GameCult.Eve.Surface.EveCommandTemplate;
using EveStyleToken = GameCult.Eve.Surface.EveStyleToken;
using EveSurfaceCommandRequest = GameCult.Eve.Surface.EveSurfaceCommandRequest;
using EveSurfaceComponent = GameCult.Eve.Surface.EveSurfaceComponent;
using EveSurfaceDocument = GameCult.Eve.Surface.EveSurfaceDocument;
using EveSurfaceTree = GameCult.Eve.Surface.EveSurfaceTree;
public class DaemonRuntimeDocumentTests
{
@ -281,6 +288,11 @@ public class DaemonRuntimeDocumentTests
gameSurface.Surface.Root,
AetheriaRuntimeSurfaceStateRefs.Source,
AetheriaRuntimeDaemonStateRefs.CurrentEntityName));
Assert.IsTrue(ContainsSurfaceStateBinding(
gameSurface.Surface.Root,
"value",
AetheriaRuntimeDaemonStateRefs.CurrentEntityName,
AetheriaRuntimeDaemonSchemas.Frame));
Assert.IsTrue(AetheriaRuntimeStateReader.TryResolveDaemonStateRef(
frame,
health,
@ -358,6 +370,19 @@ public class DaemonRuntimeDocumentTests
genericGameSurface.Surface.Root,
AetheriaRuntimeSurfaceStateRefs.Source,
AetheriaRuntimeDaemonStateRefs.CurrentTargetName));
Assert.IsTrue(ContainsEveSurfaceProp(
genericGameSurface.Surface.Root,
AetheriaRuntimeSurfaceStateBindings.PropPrefix + "value" + AetheriaRuntimeSurfaceStateBindings.SourceIdSuffix,
AetheriaRuntimeDaemonStateRefs.CurrentTargetName));
Assert.IsTrue(ContainsEveSurfaceProp(
genericGameSurface.Surface.Root,
AetheriaRuntimeSurfaceStateBindings.PropPrefix + "value" + AetheriaRuntimeSurfaceStateBindings.SchemaIdSuffix,
AetheriaRuntimeDaemonSchemas.Frame));
Assert.IsTrue(ContainsEveSurfaceStateBinding(
genericGameSurface.Surface.Root,
"value",
AetheriaRuntimeDaemonStateRefs.CurrentTargetName,
AetheriaRuntimeDaemonSchemas.Frame));
var genericGameTuiSurface = AetheriaRuntimeStateReader.ReadEveSurface(
statePath,
AetheriaRuntimeDaemonGameSurfaceBuilder.TuiSurfaceId);
@ -576,21 +601,21 @@ public class DaemonRuntimeDocumentTests
DaemonWritable = true,
ObserverWritable = false
};
var positionX = new AetheriaRuntimeDaemonSoaColumnDocument
var position = new AetheriaRuntimeDaemonSoaColumnDocument
{
ColumnId = "position-x",
Kind = AetheriaRuntimeDaemonSoaColumnKinds.PositionX,
ColumnId = "position",
Kind = AetheriaRuntimeDaemonSoaColumnKinds.Position,
BufferId = buffer.BufferId,
ScalarType = "float32",
ScalarType = "float3",
ByteOffset = 0,
ElementStride = 4,
ElementStride = 12,
ElementCount = 128,
Unit = "world_units",
CoordinateSpace = "zone"
};
var dirtyRange = new AetheriaRuntimeDaemonSoaDirtyRangeDocument
{
ColumnId = positionX.ColumnId,
ColumnId = position.ColumnId,
StartIndex = 16,
Count = 8,
Generation = 77
@ -602,7 +627,7 @@ public class DaemonRuntimeDocumentTests
42,
77,
new[] { buffer },
new[] { positionX },
new[] { position },
new[] { dirtyRange },
AetheriaRuntimeDaemonSoaBackends.MemoryMappedFile,
AetheriaRuntimeDaemonSoaSynchronizationModes.DoubleBuffered);
@ -618,7 +643,7 @@ public class DaemonRuntimeDocumentTests
Assert.AreEqual(1, view.Buffers.Count);
Assert.IsTrue(view.Buffers[0].DaemonWritable);
Assert.IsFalse(view.Buffers[0].ObserverWritable);
Assert.AreEqual(AetheriaRuntimeDaemonSoaColumnKinds.PositionX, view.Columns[0].Kind);
Assert.AreEqual(AetheriaRuntimeDaemonSoaColumnKinds.Position, view.Columns[0].Kind);
Assert.AreEqual(16, view.DirtyRanges[0].StartIndex);
Assert.AreEqual(8, view.DirtyRanges[0].Count);
Assert.IsNotEmpty(view.PublishedAtUtc);
@ -650,12 +675,12 @@ public class DaemonRuntimeDocumentTests
{
new AetheriaRuntimeDaemonSoaColumnDocument
{
ColumnId = "position-x",
Kind = AetheriaRuntimeDaemonSoaColumnKinds.PositionX,
ColumnId = "position",
Kind = AetheriaRuntimeDaemonSoaColumnKinds.Position,
BufferId = "transform-hot",
ScalarType = "float32",
ScalarType = "float3",
ByteOffset = 16,
ElementStride = 4,
ElementStride = 12,
ElementCount = 64,
Unit = "world_units",
CoordinateSpace = "zone"
@ -665,7 +690,7 @@ public class DaemonRuntimeDocumentTests
{
new AetheriaRuntimeDaemonSoaDirtyRangeDocument
{
ColumnId = "position-x",
ColumnId = "position",
StartIndex = 8,
Count = 4,
Generation = 91
@ -676,14 +701,14 @@ public class DaemonRuntimeDocumentTests
var index = AetheriaRuntimeDaemonSoaViewIndex.Build(view);
Assert.IsTrue(index.IsValid);
Assert.IsTrue(index.TryGetFirstColumnOfKind(AetheriaRuntimeDaemonSoaColumnKinds.PositionX, out var binding));
Assert.AreEqual("position-x", binding.Column.ColumnId);
Assert.IsTrue(index.TryGetFirstColumnOfKind(AetheriaRuntimeDaemonSoaColumnKinds.Position, out var binding));
Assert.AreEqual("position", binding.Column.ColumnId);
Assert.AreEqual("transform-hot", binding.Buffer.BufferId);
Assert.AreEqual(144, binding.AbsoluteByteOffset);
Assert.AreEqual(256, binding.ByteLength);
Assert.AreEqual(768, binding.ByteLength);
Assert.IsTrue(binding.DirectMemoryCompatible);
Assert.AreEqual(1, index.GetDirtyRanges("position-x").Count);
Assert.AreEqual(8, index.GetDirtyRanges("position-x")[0].StartIndex);
Assert.AreEqual(1, index.GetDirtyRanges("position").Count);
Assert.AreEqual(8, index.GetDirtyRanges("position")[0].StartIndex);
}
[Test]
@ -888,7 +913,7 @@ public class DaemonRuntimeDocumentTests
var brushes = new List<AetheriaRuntimeGravityInfluenceBrush>();
var count = AetheriaRuntimeDaemonRenderQueries.QueryGravityInfluences(
zone,
new AetheriaRuntimeXzRect(-10, -10, 10, 10),
new rect(-10, -10, 10, 10),
brushes);
Assert.AreEqual(1, count);
@ -1080,6 +1105,14 @@ public class DaemonRuntimeDocumentTests
Assert.AreEqual(7, views[0].Body.GravityWellDepth, 0.0001);
Assert.AreEqual("body:belt", views[1].Body.BodyKey);
Assert.IsTrue(views[1].IsAsteroidBelt);
count = AetheriaRuntimeDaemonRenderQueries.QueryBodyViews(
zone,
new rect(0, -20, 30, 10),
views);
Assert.AreEqual(1, count);
Assert.AreEqual("body:planet", views[0].Body.BodyKey);
}
[Test]
@ -1364,6 +1397,102 @@ public class DaemonRuntimeDocumentTests
Assert.AreEqual(11, visible[1]);
}
[Test]
public void DaemonRenderQueriesPublishCollectiveVisibleEntitiesInsideObjectsViewport()
{
var zone = new AetheriaRuntimeZoneSnapshotCommit
{
Entities = new[]
{
new AetheriaRuntimeEntitySnapshotCommit
{
EntityIndex = 1,
PositionX = 0,
PositionZ = 0,
Contacts = new[]
{
new AetheriaRuntimeEntityContactCommit
{
TargetEntityIndex = 3,
InfoGathered = 0.8,
Visible = true
},
new AetheriaRuntimeEntityContactCommit
{
TargetEntityIndex = 4,
InfoGathered = 0.4,
Visible = true
},
new AetheriaRuntimeEntityContactCommit
{
TargetEntityIndex = 6,
InfoGathered = 0.9,
Visible = true
},
new AetheriaRuntimeEntityContactCommit
{
TargetEntityIndex = 7,
InfoGathered = 0.9,
Visible = true
}
}
},
new AetheriaRuntimeEntitySnapshotCommit
{
EntityIndex = 2,
PositionX = 30,
PositionZ = 0,
Contacts = new[]
{
new AetheriaRuntimeEntityContactCommit
{
TargetEntityIndex = 5,
InfoGathered = 0.9,
Visible = true
},
new AetheriaRuntimeEntityContactCommit
{
TargetEntityIndex = 7,
InfoGathered = 0.9,
Visible = true
}
}
},
new AetheriaRuntimeEntitySnapshotCommit { EntityIndex = 3, PositionX = 8, PositionZ = 8 },
new AetheriaRuntimeEntitySnapshotCommit { EntityIndex = 4, PositionX = 9, PositionZ = 9 },
new AetheriaRuntimeEntitySnapshotCommit { EntityIndex = 5, PositionX = 12, PositionZ = 0 },
new AetheriaRuntimeEntitySnapshotCommit { EntityIndex = 6, PositionX = 100, PositionZ = 100 },
new AetheriaRuntimeEntitySnapshotCommit { EntityIndex = 7, PositionX = 5, PositionZ = 5 }
}
};
var visible = new List<int>();
var count = AetheriaRuntimeDaemonRenderQueries.QueryObjectsViewportEntityIndices(
zone,
new[] { 1, 2 },
0.5,
new rect(-10, -10, 40, 20),
visible);
Assert.AreEqual(5, count);
CollectionAssert.AreEqual(new[] { 1, 2, 3, 5, 7 }, visible);
var objects = AetheriaRuntimeDaemonRenderQueries.QueryObjectsViewport(
zone,
new[] { 1, 2 },
0.5,
new rect(-10, -10, 40, 20));
Assert.AreEqual(5, objects.Length);
Assert.AreEqual(1, objects[0].EntityIndex);
Assert.IsTrue(objects[0].Controlled);
Assert.AreEqual(new double3(0, 0, 0), objects[0].Position);
Assert.AreEqual(new double2(0, 0), objects[0].Xy);
Assert.AreEqual(7, objects[4].EntityIndex);
Assert.IsFalse(objects[4].Controlled);
Assert.AreEqual(new double2(5, 5), objects[4].Xy);
}
[Test]
public void DaemonRenderQueriesPublishWormholeExitsFromZoneAdjacency()
{
@ -1721,24 +1850,26 @@ public class DaemonRuntimeDocumentTests
Assert.AreEqual(AetheriaRuntimeDaemonSoaBackends.MemoryMappedFile, stored.Backend);
Assert.AreEqual(1, stored.Buffers.Count);
Assert.IsFalse(stored.Buffers[0].ObserverWritable);
Assert.AreEqual(15, stored.Columns.Count);
Assert.AreEqual(11, stored.Columns.Count);
Assert.AreEqual(1, stored.RenderGroups.Count);
Assert.AreEqual(2, stored.RenderGroups[0].InstanceCount);
var index = AetheriaRuntimeDaemonSoaViewIndex.Build(stored);
Assert.IsTrue(index.IsValid, string.Join("\n", index.ValidationErrors));
Assert.IsTrue(index.TryGetFirstColumnOfKind(AetheriaRuntimeDaemonSoaColumnKinds.EntityIndex, out var entityIndex));
Assert.IsTrue(index.TryGetFirstColumnOfKind(AetheriaRuntimeDaemonSoaColumnKinds.PositionX, out var positionX));
Assert.IsTrue(index.TryGetFirstColumnOfKind(AetheriaRuntimeDaemonSoaColumnKinds.VelocityZ, out var velocityZ));
Assert.IsTrue(index.TryGetFirstColumnOfKind(AetheriaRuntimeDaemonSoaColumnKinds.Position, out var position));
Assert.IsTrue(index.TryGetFirstColumnOfKind(AetheriaRuntimeDaemonSoaColumnKinds.Velocity, out var velocity));
Assert.IsTrue(index.TryGetFirstColumnOfKind(AetheriaRuntimeDaemonSoaColumnKinds.RenderVisibility, out var visibility));
using var memory = MemoryMappedFile.OpenExisting(stored.Buffers[0].Location, MemoryMappedFileRights.Read);
using var accessor = memory.CreateViewAccessor(0, stored.Buffers[0].ByteLength, MemoryMappedFileAccess.Read);
Assert.AreEqual(3, accessor.ReadInt32(entityIndex.AbsoluteByteOffset));
Assert.AreEqual(7, accessor.ReadInt32(entityIndex.AbsoluteByteOffset + entityIndex.Column.ElementStride));
Assert.AreEqual(-2f, accessor.ReadSingle(positionX.AbsoluteByteOffset), 0.0001f);
Assert.AreEqual(12f, accessor.ReadSingle(positionX.AbsoluteByteOffset + positionX.Column.ElementStride), 0.0001f);
Assert.AreEqual(6f, accessor.ReadSingle(velocityZ.AbsoluteByteOffset + velocityZ.Column.ElementStride), 0.0001f);
Assert.AreEqual(-2f, accessor.ReadSingle(position.AbsoluteByteOffset), 0.0001f);
Assert.AreEqual(-8f, accessor.ReadSingle(position.AbsoluteByteOffset + 8), 0.0001f);
Assert.AreEqual(12f, accessor.ReadSingle(position.AbsoluteByteOffset + position.Column.ElementStride), 0.0001f);
Assert.AreEqual(34f, accessor.ReadSingle(position.AbsoluteByteOffset + position.Column.ElementStride + 8), 0.0001f);
Assert.AreEqual(6f, accessor.ReadSingle(velocity.AbsoluteByteOffset + velocity.Column.ElementStride + 8), 0.0001f);
Assert.AreEqual(0, accessor.ReadByte(visibility.AbsoluteByteOffset));
Assert.AreEqual(1, accessor.ReadByte(visibility.AbsoluteByteOffset + visibility.Column.ElementStride));
}
@ -1797,11 +1928,11 @@ public class DaemonRuntimeDocumentTests
{
new AetheriaRuntimeDaemonSoaColumnDocument
{
ColumnId = "position-x",
Kind = AetheriaRuntimeDaemonSoaColumnKinds.PositionX,
ColumnId = "position",
Kind = AetheriaRuntimeDaemonSoaColumnKinds.Position,
BufferId = "entity-hot",
ScalarType = "float32",
ElementStride = 4,
ScalarType = "float3",
ElementStride = 12,
ElementCount = 64
}
});
@ -1943,8 +2074,8 @@ public class DaemonRuntimeDocumentTests
var request = new EveSurfaceCommandRequest(
"aetheria.daemon",
AetheriaRuntimeDaemonGameSurfaceBuilder.SurfaceId,
"aetheria.daemon.commands.FireWeaponGroup",
new Dictionary<string, string>(StringComparer.Ordinal),
CultMesh.OperationInvocation("aetheria.daemon.commands.FireWeaponGroup"),
CultMesh.OperationPayload(),
DateTimeOffset.UtcNow,
"unity-uitoolkit");
@ -1980,8 +2111,8 @@ public class DaemonRuntimeDocumentTests
var request = new EveSurfaceCommandRequest(
"aetheria.daemon",
AetheriaRuntimeDaemonGameSurfaceBuilder.SurfaceId,
"aetheria.daemon.commands.SensorPing",
new Dictionary<string, string>(StringComparer.Ordinal),
CultMesh.OperationInvocation("aetheria.daemon.commands.SensorPing"),
CultMesh.OperationPayload(),
DateTimeOffset.UtcNow,
"");
@ -2012,8 +2143,8 @@ public class DaemonRuntimeDocumentTests
var request = new EveSurfaceCommandRequest(
"aetheria.daemon",
AetheriaRuntimeDaemonGameSurfaceBuilder.SurfaceId,
"aetheria.daemon.commands.TransferCargoItem",
new Dictionary<string, string>(StringComparer.Ordinal),
CultMesh.OperationInvocation("aetheria.daemon.commands.TransferCargoItem"),
CultMesh.OperationPayload(),
DateTimeOffset.UtcNow,
"unity-uitoolkit");
@ -2291,78 +2422,17 @@ public class DaemonRuntimeDocumentTests
}
[Test]
public void DaemonOperationsOwnsActionBarBindingsInDaemonState()
public void DaemonCommandSchemaDoesNotOwnActionBarBindings()
{
var run = RunWithTwoEntities();
run.ActionBarBindings = new[]
{
new AetheriaRuntimeActionBarBindingCommit
{
ControlPath = "<Keyboard>/1",
Kind = "equipment",
EquipmentIndex = 0
}
};
var set = AetheriaRuntimeDaemonCommandDocument.Create(
AetheriaRuntimeDaemonCommandKinds.SetActionBarBinding,
"codex",
"session-bindings",
17,
"zone.0.entity.0");
set.TextValue = "<Keyboard>/1";
set.ActionBarBinding.Kind = "weapon_group";
set.ActionBarBinding.ItemKey = "laser";
set.WeaponGroup = 2;
var clear = AetheriaRuntimeDaemonCommandDocument.Create(
AetheriaRuntimeDaemonCommandKinds.ClearActionBarBinding,
"codex",
"session-bindings",
18,
"zone.0.entity.0");
clear.TextValue = "<Keyboard>/1";
var commandNames = Enum.GetNames(typeof(AetheriaRuntimeDaemonCommandKinds));
var boundary = AetheriaRuntimeDaemonCommandBoundaryDocument.Create("codex");
var commandBodies = boundary.Commands
.Select(command => command.CommandBody)
.ToArray();
var setResult = AetheriaRuntimeDaemonOperations.Execute(run, new[] { set });
Assert.AreEqual(1, setResult.AppliedCommandIds.Count);
Assert.AreEqual(1, run.ActionBarBindings.Count);
Assert.AreEqual("weapon_group", run.ActionBarBindings[0].Kind);
Assert.AreEqual("laser", run.ActionBarBindings[0].ItemKey);
Assert.AreEqual(2, run.ActionBarBindings[0].WeaponGroup);
var clearResult = AetheriaRuntimeDaemonOperations.Execute(run, new[] { clear });
Assert.AreEqual(1, clearResult.AppliedCommandIds.Count);
Assert.AreEqual(0, run.ActionBarBindings.Count);
}
[Test]
public void DaemonOperationsRejectsWeaponGroupActionBarBindingForMissingGroup()
{
var run = RunWithTwoEntities();
var negative = AetheriaRuntimeDaemonCommandDocument.Create(
AetheriaRuntimeDaemonCommandKinds.SetActionBarBinding,
"codex",
"session-bindings",
17,
"zone.0.entity.0");
negative.TextValue = "<Keyboard>/1";
negative.ActionBarBinding.Kind = "weapon_group";
negative.WeaponGroup = -1;
var tooHigh = AetheriaRuntimeDaemonCommandDocument.Create(
AetheriaRuntimeDaemonCommandKinds.SetActionBarBinding,
"codex",
"session-bindings",
18,
"zone.0.entity.0");
tooHigh.TextValue = "<Keyboard>/2";
tooHigh.ActionBarBinding.Kind = "weapon_group";
tooHigh.WeaponGroup = 99;
var result = AetheriaRuntimeDaemonOperations.Execute(run, new[] { negative, tooHigh });
Assert.AreEqual(0, result.AppliedCommandIds.Count);
Assert.AreEqual(2, result.RejectedCommandIds.Count);
Assert.AreEqual(0, run.ActionBarBindings.Count);
Assert.IsFalse(commandNames.Contains("SetActionBarBinding"));
Assert.IsFalse(commandNames.Contains("ClearActionBarBinding"));
Assert.IsFalse(commandBodies.Contains("AetheriaRuntimeActionBarBindingCommand"));
}
[Test]
@ -3269,7 +3339,9 @@ public class DaemonRuntimeDocumentTests
new AetheriaRuntimeEntitySnapshotCommit
{
EntityIndex = 0,
Name = "Tow Station"
Name = "Tow Station",
PositionX = 300,
PositionZ = 400
}
}
}
@ -3281,9 +3353,6 @@ public class DaemonRuntimeDocumentTests
46,
"zone.0.entity.0");
command.TargetEntityKey = "zone.3.entity.0";
command.TargetZoneIndex = 3;
command.PositionX = 300;
command.PositionY = 400;
var result = AetheriaRuntimeDaemonOperations.Execute(run, new[] { command });
@ -3624,6 +3693,47 @@ public class DaemonRuntimeDocumentTests
Assert.AreEqual(-1, envelope.ObservedFrameId);
Assert.AreEqual("", envelope.ActorEntityKey);
Assert.IsEmpty(envelope.Path);
Assert.AreEqual(AetheriaRuntimeDaemonOperationIds.SetMoveVector, envelope.OperationId);
Assert.IsTrue(envelope.Accepted);
Assert.AreEqual(CultMeshLocalityKind.Network, envelope.Route.Kind);
Assert.IsNull(envelope.Diagnostic);
}
[Test]
public void EveCommandDocumentPreservesCultMeshInvocationAndPayload()
{
var request = new EveSurfaceCommandRequest(
"aetheria",
AetheriaRuntimePlayerSettingsCommands.SurfaceId,
CultMesh.OperationInvocation(
AetheriaRuntimePlayerSettingsCommands.SetPlayerName,
AetheriaRuntimeEveCommandDocument.SchemaId,
new CultMeshRouteHint(CultMeshLocalityKind.Ipc, "eve-ui-test"),
"idempotent-player-name"),
CultMesh.OperationPayload(("value", "Raven")),
DateTimeOffset.UtcNow,
"unity-raven");
var envelope = AetheriaRuntimeEveCommandClient.CreatePlayerSettingsCommand(request, "unity-raven");
var document = AetheriaRuntimeEveCommandClient.ToDocument(envelope);
var restored = AetheriaRuntimeEveCommandClient.ToEnvelope(document);
Assert.AreEqual(AetheriaRuntimePlayerSettingsCommands.SetPlayerName, document.OperationId);
Assert.AreEqual(AetheriaRuntimeEveCommandDocument.SchemaId, document.OperationSchemaId);
Assert.AreEqual(CultMeshLocalityKind.Ipc.ToString(), document.OperationRouteKind);
Assert.AreEqual("eve-ui-test", document.OperationRouteDescription);
Assert.AreEqual("idempotent-player-name", document.OperationIdempotencyKey);
Assert.AreEqual(AetheriaRuntimePlayerSettingsCommands.SetPlayerName, document.Operation.OperationId);
Assert.AreEqual(AetheriaRuntimeEveCommandDocument.SchemaId, document.Operation.SchemaId);
Assert.AreEqual(CultMeshLocalityKind.Ipc.ToString(), document.Operation.RouteKind);
Assert.AreEqual("eve-ui-test", document.Operation.RouteDescription);
Assert.AreEqual("idempotent-player-name", document.Operation.IdempotencyKey);
Assert.IsTrue(document.Payload.TryGetValue("value", out var documentValue));
Assert.AreEqual("Raven", documentValue);
Assert.AreEqual(AetheriaRuntimePlayerSettingsCommands.SetPlayerName, restored.Invocation.OperationId);
Assert.AreEqual(CultMeshLocalityKind.Ipc, restored.Invocation.RouteHint.Kind);
Assert.AreEqual("Raven", restored.Payload.GetString("value"));
Assert.AreEqual("Raven", restored.PlayerSettings.PlayerName);
}
private static AetheriaRuntimeRunCheckpointCommit RunWithTwoEntities()
@ -3794,7 +3904,7 @@ public class DaemonRuntimeDocumentTests
frameId,
soaGeneration,
new[] { new AetheriaRuntimeDaemonSoaBufferDocument { BufferId = "hot" } },
new[] { new AetheriaRuntimeDaemonSoaColumnDocument { ColumnId = "position-x", BufferId = "hot" } });
new[] { new AetheriaRuntimeDaemonSoaColumnDocument { ColumnId = "position", BufferId = "hot" } });
return new AetheriaRuntimeObservedDaemonState(
frame,
@ -3932,6 +4042,23 @@ public class DaemonRuntimeDocumentTests
return component.Children.Any(child => ContainsSurfaceProp(child, key, value));
}
private static bool ContainsSurfaceStateBinding(
AetheriaRuntimeSurfaceComponent component,
string targetProp,
string sourceId,
string schemaId)
{
if (component.StateBindings.Any(binding =>
binding.TargetProp == targetProp &&
binding.SourceId == sourceId &&
binding.SchemaId == schemaId))
{
return true;
}
return component.Children.Any(child => ContainsSurfaceStateBinding(child, targetProp, sourceId, schemaId));
}
private static bool ContainsEveSurfaceMetric(
EveSurfaceComponent component,
string label,
@ -3962,4 +4089,21 @@ public class DaemonRuntimeDocumentTests
return component.Children.Any(child => ContainsEveSurfaceProp(child, key, value));
}
private static bool ContainsEveSurfaceStateBinding(
EveSurfaceComponent component,
string targetProp,
string sourceId,
string schemaId)
{
if (component.StateBindings.Any(binding =>
binding.TargetProp == targetProp &&
binding.SourceId == sourceId &&
binding.SchemaId == schemaId))
{
return true;
}
return component.Children.Any(child => ContainsEveSurfaceStateBinding(child, targetProp, sourceId, schemaId));
}
}

View file

@ -7,7 +7,8 @@
"Unity.Mathematics",
"CultMath",
"Aetheria.Shared.Unity",
"GameCult.Aetheria.State.Unity"
"GameCult.Aetheria.State.Unity",
"GameCult.Eve.Surface"
],
"includePlatforms": [
"Editor"

View file

@ -30,6 +30,8 @@ public class ConfirmationDialog : MonoBehaviour
private readonly List<Action> _refreshers = new();
private Action _onCancel;
private Action _onConfirm;
private Action _enableGlobalInput;
private Action _disableGlobalInput;
private void Start()
{
@ -88,6 +90,12 @@ public class ConfirmationDialog : MonoBehaviour
return property;
}
public void SetInputGate(Action enableGlobalInput, Action disableGlobalInput)
{
_enableGlobalInput = enableGlobalInput;
_disableGlobalInput = disableGlobalInput;
}
public void AddField(string name, Func<string> read, Action<string> write)
{
var field = Instantiate(InputField, Content ?? (RectTransform)transform);
@ -129,7 +137,7 @@ public class ConfirmationDialog : MonoBehaviour
CancelClickCatcher?.gameObject.SetActive(false);
gameObject.SetActive(false);
ActionGameManager.Instance?.Input.Global.Enable();
_enableGlobalInput?.Invoke();
}
public void MoveToCursor()
@ -153,7 +161,7 @@ public class ConfirmationDialog : MonoBehaviour
ButtonGroup.SetActive(onConfirm != null || onCancel != null);
CancelClickCatcher?.gameObject.SetActive(true);
ActionGameManager.Instance?.Input.Global.Disable();
_disableGlobalInput?.Invoke();
}
private void RegisterEntry(GameObject entry)

View file

@ -1,6 +1,8 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using TMPro;
@ -67,6 +69,14 @@ public class SchematicDisplay : MonoBehaviour
private EquippedCargoBay[] _cargoBays;
private SchematicDisplayItem[] _schematicItems;
private AetherDrive _aetherDrive;
private AetheriaClient _client;
private string _clientStatePath = "";
private AetheriaRuntimeCatalogSnapshot _catalog;
private AetheriaRuntimePlayerSettingsSnapshot _playerSettings;
private AetheriaRuntimeDaemonRenderSettings _renderSettings;
private AetheriaRuntimeCurrentEntityDocument _currentEntityDocument;
private float _currentEntityDocumentReadTime = float.NegativeInfinity;
private const float CurrentEntityHudRefreshIntervalSeconds = 0.1f;
private bool _enemy;
private Entity _player;
@ -85,6 +95,11 @@ public class SchematicDisplay : MonoBehaviour
public Weapon Weapon;
}
public void SetRenderSettings(AetheriaRuntimeDaemonRenderSettings renderSettings)
{
_renderSettings = renderSettings;
}
public void ShowShip(Entity entity, Entity player = null)
{
_enemy = player != null;
@ -142,16 +157,16 @@ public class SchematicDisplay : MonoBehaviour
}
}
private static AetheriaRuntimeCatalogItem FindTypedWeapon(ItemInstance item)
private AetheriaRuntimeCatalogItem FindTypedWeapon(ItemInstance item)
{
var typedItem = ActionGameManager.RuntimeCatalog?.FindItem(item?.ItemKey ?? "");
var typedItem = FindTypedItem(item);
return typedItem != null && !string.IsNullOrWhiteSpace(typedItem.WeaponType)
? typedItem
: null;
}
private static bool HasTypedWeaponBehavior(EquippedItem item)
private bool HasTypedWeaponBehavior(EquippedItem item)
{
var typedItem = FindTypedItem(item.EquippableItem);
return typedItem?.BehaviorKinds.Any(WeaponBehaviorKinds.Contains) == true;
@ -163,66 +178,67 @@ public class SchematicDisplay : MonoBehaviour
{
if (!_enemy)
{
OverrideIcon.SetActive(_entity.OverrideShutdown && cos(Time.time * OverrideIconBlinkSpeed) > 0);
ShieldIcon.SetActive(_entity.Shield!=null && _entity.Shield.Item.Active.Value);
if (_radiators.Length == 1)
RadiatorTemperatureLabel.text = $"{((int)(_radiators[0].RadiatorTemperature - 273.15f)).ToString()}°C";
else if (_radiators.Length > 1)
var hud = ResolveCurrentEntityHudStatus();
OverrideIcon.SetActive(hud.OverrideShutdown && cos(Time.time * OverrideIconBlinkSpeed) > 0);
ShieldIcon.SetActive(hud.ShieldActive);
if (hud.RadiatorCount == 1)
RadiatorTemperatureLabel.text = FormatTemperature((float)hud.RadiatorTemperatureMinimum);
else if (hud.RadiatorCount > 1)
RadiatorTemperatureLabel.text =
$"{((int)(_radiators.Min(r => r.RadiatorTemperature) - 273.15f)).ToString()}-" +
$"{((int)(_radiators.Max(r => r.RadiatorTemperature) - 273.15f)).ToString()}°C";
HeatsinkBackground.color = _entity.HeatsinksEnabled ? HeaderElementEnabledColor : HeaderElementDisabledColor;
$"{FormatTemperature((float)hud.RadiatorTemperatureMinimum)}-" +
$"{FormatTemperature((float)hud.RadiatorTemperatureMaximum)}";
HeatsinkBackground.color = hud.HeatsinksEnabled ? HeaderElementEnabledColor : HeaderElementDisabledColor;
if (_heatStorages.Length == 1)
HeatStorageTemperatureLabel.text = $"{((int)(_heatStorages[0].Item.Temperature - 273.15f)).ToString()}°C";
HeatStorageTemperatureLabel.text = FormatTemperature(_heatStorages[0].Item.Temperature);
else if (_heatStorages.Length > 1)
HeatStorageTemperatureLabel.text =
$"{((int)(_heatStorages.Min(r => r.Item.Temperature) - 273.15f)).ToString()}-" +
$"{((int)(_heatStorages.Max(r => r.Item.Temperature) - 273.15f)).ToString()}°C";
$"{FormatTemperature(_heatStorages.Min(r => r.Item.Temperature))}-" +
$"{FormatTemperature(_heatStorages.Max(r => r.Item.Temperature))}";
if (_cargoBays.Length == 1)
CargoTemperatureLabel.text = $"{((int)(_cargoBays[0].Temperature - 273.15f)).ToString()}°C";
CargoTemperatureLabel.text = FormatTemperature(_cargoBays[0].Temperature);
else if (_cargoBays.Length > 1)
CargoTemperatureLabel.text =
$"{((int)(_cargoBays.Min(r => r.Temperature) - 273.15f)).ToString()}-" +
$"{((int)(_cargoBays.Max(r => r.Temperature) - 273.15f)).ToString()}°C";
$"{FormatTemperature(_cargoBays.Min(r => r.Temperature))}-" +
$"{FormatTemperature(_cargoBays.Max(r => r.Temperature))}";
if(_cockpit != null)
{
CockpitTemperatureLabel.text = $"{((int) (_cockpit.Item.Temperature - 273.15f)).ToString()}°C";
CockpitTemperatureLabel.text = FormatTemperature(_cockpit.Item.Temperature);
HeatstrokeMeterFill.anchorMax = new Vector2(_entity.Heatstroke, 1);
HypothermiaMeterFill.anchorMax = new Vector2(_entity.Hypothermia, 1);
HeatstrokeMeterFill.anchorMax = new Vector2((float)hud.Heatstroke, 1);
HypothermiaMeterFill.anchorMax = new Vector2((float)hud.Hypothermia, 1);
HeatstrokeLimitFill.anchorMax = new Vector2(
(float)ActionGameManager.Instance.ZoneRenderer.RenderSettings.NormalizeThermalRisk(_cockpit.Item.Temperature),
(float)(_renderSettings?.NormalizeThermalRisk(_cockpit.Item.Temperature) ?? 0),
1);
}
SensorCooldownFill.anchorMax = new Vector2(_entity.Sensor?.Cooldown ?? 0, 1);
SensorCooldownFill.anchorMax = new Vector2((float)hud.SensorCooldown, 1);
if (_capacitors.Length == 0)
if (hud.CapacitorCapacity <= 0)
{
EnergyFill.anchorMax = Vector2.up;
EnergyLabel.text = ActionGameManager.RuntimePlayerSettings.Format(_reactor.Draw);
EnergyLabel.text = FormatValue((float)hud.ReactorDraw);
}
else
{
var charge = _capacitors.Sum(x => x.Charge);
var maxCharge = _capacitors.Sum(x => x.Capacity);
var charge = hud.CapacitorCharge;
var maxCharge = hud.CapacitorCapacity;
EnergyFill.anchorMax = new Vector2(charge / maxCharge, 1);
EnergyLabel.text = $"{((int)charge).ToString()}/{((int)maxCharge).ToString()} + ({((int)_reactor.Draw).ToString()})";
EnergyLabel.text = $"{((int)charge).ToString()}/{((int)maxCharge).ToString()} + ({((int)hud.ReactorDraw).ToString()})";
}
if (_aetherDrive != null)
if (hud.AetherDriveMaximumRpm > 0)
{
ForwardRPMLabel.text = ActionGameManager.RuntimePlayerSettings.Format(_aetherDrive.Rpm.x);
ForwardRPMFill.anchorMax = new Vector2(_aetherDrive.Rpm.x / _aetherDrive.MaximumRpm, 1);
ForwardRPMLabel.text = FormatValue((float)hud.AetherDriveRpmX);
ForwardRPMFill.anchorMax = new Vector2((float)(hud.AetherDriveRpmX / hud.AetherDriveMaximumRpm), 1);
StrafeRPMLabel.text = ActionGameManager.RuntimePlayerSettings.Format(_aetherDrive.Rpm.y);
StrafeRPMFill.anchorMax = new Vector2(_aetherDrive.Rpm.y / _aetherDrive.MaximumRpm, 1);
StrafeRPMLabel.text = FormatValue((float)hud.AetherDriveRpmY);
StrafeRPMFill.anchorMax = new Vector2((float)(hud.AetherDriveRpmY / hud.AetherDriveMaximumRpm), 1);
TurnRPMLabel.text = ActionGameManager.RuntimePlayerSettings.Format(_aetherDrive.Rpm.z);
TurnRPMFill.anchorMax = new Vector2(_aetherDrive.Rpm.z / _aetherDrive.MaximumRpm, 1);
TurnRPMLabel.text = FormatValue((float)hud.AetherDriveRpmZ);
TurnRPMFill.anchorMax = new Vector2((float)(hud.AetherDriveRpmZ / hud.AetherDriveMaximumRpm), 1);
}
}
// else
@ -230,15 +246,31 @@ public class SchematicDisplay : MonoBehaviour
// DistanceLabel.text = $"{(int)length(_entity.Position - _player.Position)}";
// }
if(VisibilityLabel)
VisibilityLabel.text = ((int)_entity.Visibility).ToString();
if(HullDurabilityFill)
if (!_enemy)
{
_hull = _entity.Hull;
var dur = _hull.Durability / GetMaxDurability(_hull);
HullDurabilityFill.anchorMax = new Vector2(dur, 1);
HullDurabilityLabel.text = $"{ActionGameManager.RuntimePlayerSettings.Format(dur * 100)}%";
var hud = ResolveCurrentEntityHudStatus();
if(VisibilityLabel)
VisibilityLabel.text = ((int)hud.Visibility).ToString();
if(HullDurabilityFill)
{
var dur = (float)hud.HullDurabilityRatio;
HullDurabilityFill.anchorMax = new Vector2(dur, 1);
HullDurabilityLabel.text = $"{FormatValue(dur * 100)}%";
}
}
else
{
if(VisibilityLabel)
VisibilityLabel.text = ((int)_entity.Visibility).ToString();
if(HullDurabilityFill)
{
_hull = _entity.Hull;
var dur = _hull.Durability / GetMaxDurability(_hull);
HullDurabilityFill.anchorMax = new Vector2(dur, 1);
HullDurabilityLabel.text = $"{FormatValue(dur * 100)}%";
}
}
foreach (var x in _schematicItems)
@ -268,7 +300,7 @@ public class SchematicDisplay : MonoBehaviour
}
}
private static (float minimum, float maximum) GetThermalRange(ItemInstance item, float currentTemperature)
private (float minimum, float maximum) GetThermalRange(ItemInstance item, float currentTemperature)
{
var typedItem = FindTypedItem(item);
if (typedItem != null && typedItem.MaximumTemperature > typedItem.MinimumTemperature)
@ -285,8 +317,132 @@ public class SchematicDisplay : MonoBehaviour
return item is EquippableItem equippable ? Math.Max(equippable.Durability, 1f) : 1f;
}
private static AetheriaRuntimeCatalogItem FindTypedItem(ItemInstance item)
private AetheriaRuntimeCatalogItem FindTypedItem(ItemInstance item)
{
return ActionGameManager.RuntimeCatalog?.FindItem(item?.ItemKey ?? "");
return ResolveCatalog()?.FindItem(item?.ItemKey ?? "");
}
private AetheriaRuntimeCatalogSnapshot ResolveCatalog()
{
if (_catalog != null)
return _catalog;
try
{
_catalog = ResolveClient().OpenRuntimeCatalog();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria runtime catalog for schematic display: {ex.Message}");
}
return _catalog;
}
private AetheriaRuntimePlayerSettingsSnapshot ResolvePlayerSettings()
{
if (_playerSettings != null)
return _playerSettings;
try
{
_playerSettings = ResolveClient()
.PlayerSettingsAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria player settings for schematic display: {ex.Message}");
}
return _playerSettings;
}
private AetheriaRuntimeCurrentEntityHudStatus ResolveCurrentEntityHudStatus()
{
if (_currentEntityDocument == null ||
Time.unscaledTime - _currentEntityDocumentReadTime >= CurrentEntityHudRefreshIntervalSeconds)
{
try
{
_currentEntityDocument = ResolveClient()
.CurrentEntityAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria current entity HUD status: {ex.Message}");
}
_currentEntityDocumentReadTime = Time.unscaledTime;
}
return _currentEntityDocument?.Hud ?? new AetheriaRuntimeCurrentEntityHudStatus();
}
private AetheriaClient ResolveClient()
{
var gameDataDirectory = new DirectoryInfo(Path.Combine(Application.dataPath, "..", "GameData"));
var stateBoot = AetheriaRuntimeStateBoot.Inspect(gameDataDirectory);
if (_client != null && string.Equals(_clientStatePath, stateBoot.StateFilePath, StringComparison.Ordinal))
return _client;
DisposeClient();
_client = AetheriaClient
.OpenLocalAsync(
gameDataDirectory,
"unity-schematic-display",
"local",
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_clientStatePath = stateBoot.StateFilePath;
return _client;
}
private string FormatValue(float value)
{
var settings = ResolvePlayerSettings();
var significantDigits = settings?.SignificantDigits ?? 3;
var magnitude = value == 0.0f ? 0 : (int)Math.Floor(Math.Log10(Math.Abs(value))) + 1;
var digits = significantDigits - magnitude;
if (digits < 0)
digits = 0;
var formatted = value.ToString($"N{digits}", CultureInfo.CurrentCulture);
var separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
var decimalSeparator = Convert.ToChar(separator);
return formatted.Contains(separator)
? formatted.TrimEnd('0').TrimEnd(decimalSeparator)
: formatted;
}
private string FormatTemperature(float value)
{
var unit = ResolvePlayerSettings()?.TemperatureUnit ?? nameof(TemperatureUnit.Celsius);
if (string.Equals(unit, nameof(TemperatureUnit.Kelvin), StringComparison.OrdinalIgnoreCase))
return $"{FormatValue(value)} K";
if (string.Equals(unit, nameof(TemperatureUnit.Fahrenheit), StringComparison.OrdinalIgnoreCase))
return $"{FormatValue(value * (9f / 5) - 459.67f)} F";
return $"{FormatValue(value - 273.15f)} C";
}
private void DisposeClient()
{
_client?.Dispose();
_client = null;
_clientStatePath = "";
_catalog = null;
_playerSettings = null;
_currentEntityDocument = null;
_currentEntityDocumentReadTime = float.NegativeInfinity;
}
private void OnDestroy()
{
DisposeClient();
}
}

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GameCult.Aetheria.EveRuntime;
using GameCult.Aetheria.State.Verse;
@ -13,6 +14,9 @@ public class InputDisplayLayout : MonoBehaviour
{
private UIDocument _surfaceDocument;
private AetheriaInput _ownedInput;
private AetheriaClient _client;
private string _clientStatePath = "";
private AetheriaRuntimePlayerSettingsSnapshot _playerSettings;
private InputAction _captureAction;
private InputActionAsset _input;
private string _captureActionName = "";
@ -92,6 +96,8 @@ public class InputDisplayLayout : MonoBehaviour
_ownedInput?.Dispose();
_ownedInput = null;
DisposeClient();
if (_surfaceDocument != null)
{
AetheriaEveUnitySurfaceHost.DestroyDocument(_surfaceDocument);
@ -164,10 +170,10 @@ public class InputDisplayLayout : MonoBehaviour
private AetheriaRuntimeInputSettingsSurfaceState ProjectSurfaceState()
{
var runtimeSettings = ActionGameManager.RuntimePlayerSettings.InputSettings;
var runtimeSettings = ResolvePlayerSettings();
return AetheriaRuntimeInputSettingsSurfaceBuilder.Project(
ProjectObservedBindings(),
runtimeSettings.ActionBarInputs,
runtimeSettings?.ActionBarInputs ?? Array.Empty<string>(),
capturePending: _captureBindingIndex >= 0 && !string.IsNullOrWhiteSpace(_captureActionName),
capturePrompt: BuildCapturePrompt(),
updatedAtUtc: DateTime.UtcNow.ToString("O"));
@ -286,7 +292,14 @@ public class InputDisplayLayout : MonoBehaviour
return;
}
ActionGameManager.RequestRuntimeActionBarInput(command.InputPath, command.Enabled);
SendInputSettingsCommand(
AetheriaRuntimeEveCommandKind.SetActionBarEnabled,
new AetheriaRuntimeInputSettingsCommandBody
{
InputSystemPath = command.InputPath,
Enabled = command.Enabled
},
"action-bar input");
RenderSurface();
}
@ -316,11 +329,96 @@ public class InputDisplayLayout : MonoBehaviour
}
action.ApplyBindingOverride(_captureBindingIndex, inputPath);
ActionGameManager.RequestRuntimeInputBindingOverride(action.name, _captureBindingIndex, inputPath);
SendInputSettingsCommand(
AetheriaRuntimeEveCommandKind.SetBindingOverride,
new AetheriaRuntimeInputSettingsCommandBody
{
ActionName = action.name,
BindingIndex = _captureBindingIndex,
InputSystemPath = inputPath
},
"input binding override");
ClearCapture();
RenderSurface();
}
private void SendInputSettingsCommand(
AetheriaRuntimeEveCommandKind command,
AetheriaRuntimeInputSettingsCommandBody body,
string label)
{
try
{
var submitted = ResolveClient()
.Ui.InputSettingsAsync(command, body, "unity-input-screen")
.GetAwaiter()
.GetResult();
Debug.Log($"Submitted Aetheria {label} Eve operation: {submitted.OperationId}");
}
catch (Exception ex)
{
Debug.LogError($"Failed to send Aetheria {label} Eve command: {ex}");
}
}
private AetheriaClient ResolveClient()
{
var gameDataDirectory = new DirectoryInfo(Path.Combine(Application.dataPath, "..", "GameData"));
var stateBoot = AetheriaRuntimeStateBoot.Inspect(gameDataDirectory);
if (!stateBoot.SupportsLocalStateFileRead || !stateBoot.StateFileExists)
{
throw new InvalidOperationException(
$"Input settings require a readable local Aetheria Verse state file: {stateBoot.FailureMessage}");
}
if (_client != null && string.Equals(_clientStatePath, stateBoot.StateFilePath, StringComparison.Ordinal))
{
return _client;
}
DisposeClient();
_client = AetheriaClient
.OpenAsync(
stateBoot.StateFilePath,
"unity-input-screen",
"local",
startServer: false,
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_clientStatePath = stateBoot.StateFilePath;
return _client;
}
private void DisposeClient()
{
_client?.Dispose();
_client = null;
_clientStatePath = "";
_playerSettings = null;
}
private AetheriaRuntimePlayerSettingsSnapshot ResolvePlayerSettings()
{
if (_playerSettings != null)
return _playerSettings;
try
{
_playerSettings = ResolveClient()
.PlayerSettingsAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria player settings for input screen: {ex.Message}");
}
return _playerSettings;
}
private void ClearCapture()
{
_captureActionName = "";

View file

@ -17,8 +17,11 @@ public class MainMenu : MonoBehaviour
public bool InGame;
private UIDocument _menuSurfaceDocument;
private AetheriaRuntimeVerseClient _verseClient;
private string _verseClientStatePath;
private AetheriaClient _client;
private string _clientStatePath;
private AetheriaRuntimeCatalogSnapshot _catalog;
private Func<bool> _canOpenRuntimeInputScreen;
private Action _openRuntimeInputScreen;
private readonly AetheriaEveUnitySurfaceChrome _menuSurfaceChrome = new AetheriaEveUnitySurfaceChrome
{
RootAlignItems = Align.Center,
@ -48,14 +51,14 @@ public class MainMenu : MonoBehaviour
private void ShowMain()
{
var stateBoot = CurrentStateBoot();
var frame = LatestDaemonFrame(stateBoot);
var sectorMap = LatestSectorMap(stateBoot);
var verseHost = LatestVerseHostSettings(stateBoot);
var playerSettings = LatestPlayerSettings(stateBoot);
RenderMenuSurface(
AetheriaRuntimeMainMenuSurfaceBuilder.BuildRoot(
AetheriaRuntimeMainMenuSurfaceBuilder.ProjectRoot(
stateBoot,
frame,
sectorMap,
verseHost,
playerSettings,
CanOpenRuntimeInputScreen(),
@ -75,9 +78,9 @@ public class MainMenu : MonoBehaviour
switch (command.Kind)
{
case AetheriaRuntimeMainMenuCommandKind.ContinueRun:
if (LatestDaemonFrame(CurrentStateBoot()) == null)
if (LatestSectorMap(CurrentStateBoot()) == null)
{
Debug.LogWarning("Main-menu Continue requested without an authoritative daemon frame.");
Debug.LogWarning("Main-menu Continue requested without a typed Aetheria sector-map projection.");
ShowMain();
return;
}
@ -110,10 +113,10 @@ public class MainMenu : MonoBehaviour
private bool TryStartDaemonObservedGame(string title)
{
var stateBoot = CurrentStateBoot();
var frame = LatestDaemonFrame(stateBoot);
if (frame == null)
var sectorMap = LatestSectorMap(stateBoot);
if (sectorMap == null)
{
Debug.LogWarning($"Cannot start Aetheria observer scene without an authoritative daemon frame in {stateBoot.StateFilePath}.");
Debug.LogWarning($"Cannot start Aetheria observer scene without a typed Aetheria sector-map projection in {stateBoot.StateFilePath}.");
return false;
}
@ -126,14 +129,20 @@ public class MainMenu : MonoBehaviour
Dialog.AddProperty(() => generatorState);
Dialog.Show();
setState($"Observing daemon frame {frame.FrameId}");
ActionGameManager.IsTutorial = frame.Run.IsTutorial;
var backgroundSettings = frame.Run.IsTutorial ? Settings.TutorialBackgroundSettings : Settings.SectorBackgroundSettings;
backgroundSettings.NoisePosition = frame.Run.GenerationSeed == 0 ? 1 : frame.Run.GenerationSeed;
ActionGameManager.ObservedGalaxy = Galaxy.ProjectObservedDaemonRun(
frame.Run,
setState($"Observing sector-map frame {sectorMap.FrameId}");
var backgroundSettings = sectorMap.IsTutorial ? Settings.TutorialBackgroundSettings : Settings.SectorBackgroundSettings;
backgroundSettings.NoisePosition = sectorMap.GenerationSeed == 0 ? 1 : sectorMap.GenerationSeed;
var runtimeCatalog = OpenRuntimeCatalog(stateBoot);
if (runtimeCatalog == null)
{
Debug.LogWarning($"Cannot start Aetheria observer scene without a runtime catalog in {stateBoot.StateFilePath}.");
return false;
}
AetheriaUnityObservedRunProjection.Project(
sectorMap,
backgroundSettings,
ActionGameManager.RuntimeCatalog,
runtimeCatalog,
Debug.Log);
SceneManager.LoadScene("ARPG");
return true;
@ -141,10 +150,10 @@ public class MainMenu : MonoBehaviour
private static AetheriaRuntimeStateBootReport CurrentStateBoot()
{
return AetheriaRuntimeStateBoot.Inspect(ActionGameManager.GameDataDirectory);
return AetheriaRuntimeStateBoot.Inspect(AetheriaUnityRuntimePaths.GameDataDirectory);
}
private AetheriaRuntimeDaemonFrameDocument LatestDaemonFrame(AetheriaRuntimeStateBootReport stateBoot)
private AetheriaRuntimeSectorMapDocument LatestSectorMap(AetheriaRuntimeStateBootReport stateBoot)
{
if (!stateBoot.SupportsLocalStateFileRead || !stateBoot.StateFileExists)
{
@ -153,14 +162,14 @@ public class MainMenu : MonoBehaviour
try
{
return ResolveVerseClient(stateBoot)
.GetLatestAuthoritativeRunFrameAsync()
return ResolveClient(stateBoot)
.SectorMapAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogError($"Failed to read authoritative Aetheria daemon frame for the main menu: {ex}");
Debug.LogError($"Failed to read typed Aetheria sector-map state for the main menu: {ex}");
return null;
}
}
@ -172,8 +181,8 @@ public class MainMenu : MonoBehaviour
try
{
return ResolveVerseClient(stateBoot)
.GetPlayerSettingsAsync()
return ResolveClient(stateBoot)
.PlayerSettingsAsync()
.GetAwaiter()
.GetResult();
}
@ -191,8 +200,8 @@ public class MainMenu : MonoBehaviour
try
{
return ResolveVerseClient(stateBoot)
.GetVerseHostSettingsAsync()
return ResolveClient(stateBoot)
.VerseHostSettingsAsync()
.GetAwaiter()
.GetResult();
}
@ -203,6 +212,26 @@ public class MainMenu : MonoBehaviour
}
}
private AetheriaRuntimeCatalogSnapshot OpenRuntimeCatalog(AetheriaRuntimeStateBootReport stateBoot)
{
if (!stateBoot.SupportsLocalStateFileRead || !stateBoot.StateFileExists)
return null;
if (_catalog != null)
return _catalog;
try
{
_catalog = ResolveClient(stateBoot).OpenRuntimeCatalog();
return _catalog;
}
catch (Exception ex)
{
Debug.LogError($"Failed to read typed Aetheria runtime catalog for the main menu: {ex}");
return null;
}
}
private void ContinueGame()
{
if (!TryStartDaemonObservedGame("Continuing Daemon Run"))
@ -381,12 +410,16 @@ public class MainMenu : MonoBehaviour
AetheriaEveUnitySurfaceHost.Hide(_menuSurfaceDocument);
}
public void SetRuntimeInputScreenShell(Func<bool> canOpenRuntimeInputScreen, Action openRuntimeInputScreen)
{
_canOpenRuntimeInputScreen = canOpenRuntimeInputScreen;
_openRuntimeInputScreen = openRuntimeInputScreen;
}
private bool CanOpenRuntimeInputScreen()
{
return InGame &&
ActionGameManager.Instance != null &&
ActionGameManager.Instance.CanShowInputScreenFromMenu() &&
ActionGameManager.Instance.InputDisplayLayout != null;
_canOpenRuntimeInputScreen?.Invoke() == true;
}
private bool TryOpenRuntimeInputScreen()
@ -396,7 +429,7 @@ public class MainMenu : MonoBehaviour
HideMenuSurface();
gameObject.SetActive(false);
ActionGameManager.Instance.ShowInputScreenFromMenu();
_openRuntimeInputScreen?.Invoke();
return true;
}
@ -405,7 +438,7 @@ public class MainMenu : MonoBehaviour
try
{
if (!AetheriaRuntimeClientTargetSurfaceCommands.TryRequest(
AetheriaState.At(ActionGameManager.GameDataDirectory).ClientTarget,
AetheriaState.At(AetheriaUnityRuntimePaths.GameDataDirectory).ClientTarget,
request,
out _))
{
@ -431,12 +464,12 @@ public class MainMenu : MonoBehaviour
try
{
var submitted = ResolveVerseClient(stateBoot)
.SubmitKnownSurfaceCommandAsync(request, "unity-main-menu")
var submitted = ResolveClient(stateBoot)
.Ui.SurfaceCommandAsync(request, "unity-main-menu")
.GetAwaiter()
.GetResult();
Debug.Log($"Submitted Aetheria {label} Eve command: {submitted.CommandId}");
Debug.Log($"Submitted Aetheria {label} Eve operation: {submitted.OperationId}");
}
catch (Exception ex)
{
@ -458,33 +491,39 @@ public class MainMenu : MonoBehaviour
return true;
}
private AetheriaRuntimeVerseClient ResolveVerseClient(AetheriaRuntimeStateBootReport stateBoot)
private AetheriaClient ResolveClient(AetheriaRuntimeStateBootReport stateBoot)
{
var statePath = stateBoot.StateFilePath;
if (_verseClient != null && string.Equals(_verseClientStatePath, statePath, StringComparison.Ordinal))
if (_client != null && string.Equals(_clientStatePath, statePath, StringComparison.Ordinal))
{
return _verseClient;
return _client;
}
DisposeVerseClient();
_verseClient = AetheriaRuntimeVerseClient
.OpenAsync(statePath, "unity-main-menu", startServer: false, pullOnOpen: true)
DisposeClient();
_client = AetheriaClient
.OpenAsync(
statePath,
"unity-main-menu",
"local",
startServer: false,
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_verseClientStatePath = statePath;
return _verseClient;
_clientStatePath = statePath;
return _client;
}
private void DisposeVerseClient()
private void DisposeClient()
{
_verseClient?.Dispose();
_verseClient = null;
_verseClientStatePath = null;
_client?.Dispose();
_client = null;
_clientStatePath = null;
_catalog = null;
}
private void OnDestroy()
{
DisposeVerseClient();
DisposeClient();
if (_menuSurfaceDocument != null)
{
Destroy(_menuSurfaceDocument.gameObject);

View file

@ -5,6 +5,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using GameCult.Aetheria.EveRuntime;
using GameCult.Aetheria.State.Verse;
@ -18,7 +19,6 @@ using UnityEngine.UIElements;
public class InventoryMenu : MonoBehaviour
{
public InventoryPanel[] InventoryPanels;
public ActionGameManager GameManager;
public ConfirmationDialog Dialog;
// public ClickCatcher Background;
@ -27,9 +27,16 @@ public class InventoryMenu : MonoBehaviour
private ItemInstance _selectedItem;
private EquippedItem _selectedEquippedItem;
private int2[] _selectedCells;
private AetheriaRuntimeCurrentEntityDocument _shipSettingsCurrentEntity;
private UIDocument _shipSettingsSurfaceDocument;
private UIDocument _cargoItemDetailsSurfaceDocument;
private UIDocument _equippedItemDetailsSurfaceDocument;
private AetheriaClient _client;
private string _clientStatePath = "";
private AetheriaRuntimeCatalogSnapshot _catalog;
private AetheriaRuntimePlayerSettingsSnapshot _playerSettings;
private AetheriaUnityActionBarPresentation _actionBarPresentation;
private AetheriaUnityObservedFacadeIndex _observedFacadeIndex;
private readonly AetheriaEveUnitySurfaceChrome _shipSettingsSurfaceChrome = PanelChrome(360f, 420f);
private readonly AetheriaEveUnitySurfaceChrome _cargoItemDetailsSurfaceChrome = PanelChrome(420f, 520f);
private readonly AetheriaEveUnitySurfaceChrome _equippedItemDetailsSurfaceChrome = PanelChrome(460f, 560f);
@ -38,6 +45,25 @@ public class InventoryMenu : MonoBehaviour
// private ItemInstance _dragItem;
// private Transform[] _dragCells;
// private Vector2[] _dragOffsets;
public void SetDragSession(AetheriaUnityDragSession dragSession)
{
if (InventoryPanels == null)
return;
foreach (var panel in InventoryPanels)
panel?.SetDragSession(dragSession);
}
public void SetActionBarPresentation(AetheriaUnityActionBarPresentation actionBarPresentation)
{
_actionBarPresentation = actionBarPresentation;
}
public void SetObservedFacadeIndex(AetheriaUnityObservedFacadeIndex observedFacadeIndex)
{
_observedFacadeIndex = observedFacadeIndex;
}
// private int2 _dragCellOffset;
// private ItemRotation _originalRotation;
// //private Shape _previousFakeOccupancy;
@ -63,8 +89,8 @@ public class InventoryMenu : MonoBehaviour
// {
// _destroyItem = false;
// });
var hasObservedCurrentEntity = GameManager.TryGetObservedCurrentEntity(out var currentEntity);
var cargo = GameManager.TryGetObservedDockingBay(out var dockingBay)
var hasObservedCurrentEntity = TryGetTypedCurrentEntityFacade(out var currentEntity);
var cargo = TryGetTypedCurrentDockingBayFacade(out var dockingBay)
? dockingBay
: currentEntity?.CargoBays.FirstOrDefault();
if (cargo!=null)
@ -157,44 +183,45 @@ public class InventoryMenu : MonoBehaviour
panel.OnBackgroundClick.Subscribe(data =>
{
if (!GameManager.TryGetObservedCurrentEntity(out var currentEntity)) return;
if (!TryResolveCurrentEntityDocument(out var currentEntity)) return;
RenderCurrentShipSettingsSurface(currentEntity);
});
}
}
private void RenderCurrentShipSettingsSurface(Entity entity)
private void RenderCurrentShipSettingsSurface(AetheriaRuntimeCurrentEntityDocument currentEntity)
{
if (entity == null)
if (currentEntity == null || string.IsNullOrWhiteSpace(currentEntity.EntityKey))
return;
HideCargoItemDetailsSurface();
HideEquippedItemDetailsSurface();
ClearSelectedItemSelection();
_shipSettingsCurrentEntity = currentEntity;
_shipSettingsSurfaceDocument = AetheriaEveUnitySurfaceHost.RenderRuntime(
transform,
_shipSettingsSurfaceDocument,
"Aetheria Inventory Ship Settings Surface",
AetheriaRuntimeShipSettingsSurfaceBuilder.Build(ProjectCurrentShipSettingsSurface(entity)),
AetheriaRuntimeShipSettingsSurfaceBuilder.Build(ProjectCurrentShipSettingsSurface(currentEntity)),
HandleCurrentShipSettingsSurfaceCommand,
_shipSettingsSurfaceChrome);
}
private void HandleCurrentShipSettingsSurfaceCommand(EveSurfaceCommandRequest request)
{
if (!GameManager.TryGetObservedCurrentEntity(out var entity))
var currentEntity = _shipSettingsCurrentEntity;
if (currentEntity == null ||
string.IsNullOrWhiteSpace(currentEntity.EntityKey) ||
!TryResolveCurrentEntityDocument(out var latestCurrentEntity) ||
!string.Equals(latestCurrentEntity.EntityKey, currentEntity.EntityKey, StringComparison.Ordinal))
{
HideCurrentShipSettingsSurface();
return;
}
if (entity?.Settings == null)
{
HideCurrentShipSettingsSurface();
return;
}
_shipSettingsCurrentEntity = latestCurrentEntity;
if (!AetheriaRuntimeShipSettingsSurfaceCommands.TryRead(request, out var command))
{
@ -207,12 +234,12 @@ public class InventoryMenu : MonoBehaviour
case AetheriaRuntimeShipSettingsCommandKind.DecrementShutdownThreshold:
case AetheriaRuntimeShipSettingsCommandKind.IncrementShutdownThreshold:
case AetheriaRuntimeShipSettingsCommandKind.ResetShutdownThreshold:
GameManager.RequestEntityShutdownPerformance(
entity,
RequestEntityShutdownPerformance(
latestCurrentEntity.EntityKey,
AetheriaRuntimeShipSettingsSurfaceCommands.ResolveShutdownPerformance(
command.Kind,
entity.Settings.ShutdownPerformance,
GameManager.Settings.GameplaySettings.DefaultShutdownPerformance));
(float)latestCurrentEntity.ShutdownPerformance,
ResolveDefaultShutdownPerformance()));
return;
case AetheriaRuntimeShipSettingsCommandKind.Close:
HideCurrentShipSettingsSurface();
@ -225,18 +252,20 @@ public class InventoryMenu : MonoBehaviour
private void HideCurrentShipSettingsSurface()
{
_shipSettingsCurrentEntity = null;
if (_shipSettingsSurfaceDocument == null)
return;
AetheriaEveUnitySurfaceHost.Hide(_shipSettingsSurfaceDocument);
}
private static AetheriaRuntimeShipSettingsSurfaceState ProjectCurrentShipSettingsSurface(Entity entity)
private AetheriaRuntimeShipSettingsSurfaceState ProjectCurrentShipSettingsSurface(
AetheriaRuntimeCurrentEntityDocument currentEntity)
{
return AetheriaRuntimeShipSettingsSurfaceBuilder.Project(
entity?.Name ?? "",
entity?.Settings?.ShutdownPerformance ?? 0f,
ActionGameManager.RuntimePlayerSettings.Format);
currentEntity?.Entity?.DisplayName ?? "",
(float)(currentEntity?.ShutdownPerformance ?? 0),
FormatValue);
}
private void RenderCargoItemDetailsSurface(ItemInstance item)
@ -322,16 +351,15 @@ public class InventoryMenu : MonoBehaviour
ClearSelectedItemSelection();
return;
case AetheriaRuntimeEquippedItemDetailsCommandKind.ToggleOverrideShutdown:
GameManager.RequestEquippedItemOverrideShutdown(item, !item.EquippableItem.OverrideShutdown);
RequestEquippedItemOverrideShutdown(item, !item.EquippableItem.OverrideShutdown);
return;
case AetheriaRuntimeEquippedItemDetailsCommandKind.SetTargetTemperature:
if (command.BehaviorIndex >= 0 &&
command.BehaviorIndex < (item.Behaviors?.Length ?? 0) &&
item.Behaviors[command.BehaviorIndex] is Thermotoggle thermotoggle &&
thermotoggle.Adjustable &&
GameManager != null)
thermotoggle.Adjustable)
{
GameManager.RequestThermotoggleTargetTemperature(thermotoggle, command.TargetTemperature);
RequestThermotoggleTargetTemperature(item, command.BehaviorIndex, command.TargetTemperature);
return;
}
@ -342,31 +370,12 @@ public class InventoryMenu : MonoBehaviour
if (command.GroupIndex >= 0)
{
var assigned = !IsWeaponGroupAssigned(item, command.GroupIndex);
GameManager.RequestWeaponGroupMembership(item, command.GroupIndex, assigned);
RequestWeaponGroupMembership(item, command.GroupIndex, assigned);
return;
}
Debug.LogWarning("Unable to submit equipped-item weapon group membership request.");
return;
case AetheriaRuntimeEquippedItemDetailsCommandKind.BindWeaponGroup:
if (command.GroupIndex >= 0 &&
command.SlotIndex >= 0)
{
GameManager.RequestWeaponGroupActionBarBinding(command.SlotIndex, command.GroupIndex);
return;
}
Debug.LogWarning("Unable to submit equipped-item action-bar binding request.");
return;
case AetheriaRuntimeEquippedItemDetailsCommandKind.ClearActionBarBinding:
if (command.SlotIndex >= 0)
{
GameManager.RequestClearActionBarBinding(command.SlotIndex);
return;
}
Debug.LogWarning("Unable to submit equipped-item action-bar clear request.");
return;
default:
Debug.LogWarning($"Unknown inventory equipped item details command: {request?.Command}");
return;
@ -408,12 +417,11 @@ public class InventoryMenu : MonoBehaviour
typedItem,
ProjectEquippedItemObservation(item),
BuildEquippedItemTitle(item, typedItem),
ActionGameManager.RuntimeCatalog?.GetManufacturer(typedItem)?.Name ?? "GameCult",
ActionGameManager.RuntimePlayerSettings.Format,
ActionGameManager.RuntimePlayerSettings.FormatTemperature,
ResolveManufacturerName(typedItem),
FormatValue,
FormatTemperature,
ProjectEquippedItemTemperatureControls(item).ToArray(),
hasWeapon ? ProjectEquippedItemWeaponGroupControls(item).ToArray() : Array.Empty<AetheriaRuntimeEquippedItemControl>(),
hasWeapon ? ProjectEquippedItemActionBarSlots(item).ToArray() : Array.Empty<AetheriaRuntimeEquippedItemActionBarSlot>());
hasWeapon ? ProjectEquippedItemWeaponGroupControls(item).ToArray() : Array.Empty<AetheriaRuntimeEquippedItemControl>());
}
private static AetheriaRuntimeEquippedItemObservation ProjectEquippedItemObservation(EquippedItem item)
@ -456,38 +464,6 @@ public class InventoryMenu : MonoBehaviour
("group", groupIndex.ToString(CultureInfo.InvariantCulture)))));
}
private IEnumerable<AetheriaRuntimeEquippedItemActionBarSlot> ProjectEquippedItemActionBarSlots(
EquippedItem item)
{
for (var slotIndex = 0; slotIndex < GameManager.GetActionBarSlotCount(); slotIndex++)
{
var controls = Enumerable.Range(0, item.Entity?.WeaponGroups?.Length ?? 0)
.Select(groupIndex => new AetheriaRuntimeEquippedItemControl(
$"{AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.SurfaceId}.action_bar.{slotIndex}.group.{groupIndex}",
$"G{groupIndex + 1}",
AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.BindWeaponGroup,
AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.Payload(
("slot", slotIndex.ToString(CultureInfo.InvariantCulture)),
("group", groupIndex.ToString(CultureInfo.InvariantCulture)))))
.Concat(new[]
{
new AetheriaRuntimeEquippedItemControl(
$"{AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.SurfaceId}.action_bar.{slotIndex}.clear",
"Clear",
AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.ClearActionBarBinding,
AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.Payload(
("slot", slotIndex.ToString(CultureInfo.InvariantCulture))))
})
.ToArray();
yield return new AetheriaRuntimeEquippedItemActionBarSlot(
$"{AetheriaRuntimeEquippedItemDetailsSurfaceBuilder.SurfaceId}.action_bar.{slotIndex}.card",
$"Action Bar {GameManager.GetActionBarSlotLabel(slotIndex)}",
GameManager.GetActionBarBindingLabel(slotIndex),
controls);
}
}
private AetheriaRuntimeCargoItemDetailsSurfaceState ProjectCargoItemDetailsSurface(
ItemInstance item,
AetheriaRuntimeCatalogItem typedItem)
@ -495,10 +471,10 @@ public class InventoryMenu : MonoBehaviour
return AetheriaRuntimeCargoItemDetailsSurfaceBuilder.Project(
typedItem,
ProjectCargoItemObservation(item),
ActionGameManager.RuntimeCatalog?.GetManufacturer(typedItem)?.Name ?? "GameCult",
ResolveManufacturerName(typedItem),
item is EquippableItem equippableItem ? FormatItemTier(typedItem, equippableItem) : "",
ActionGameManager.RuntimePlayerSettings.Format,
ActionGameManager.RuntimePlayerSettings.FormatTemperature);
FormatValue,
FormatTemperature);
}
private static AetheriaRuntimeCargoItemObservation ProjectCargoItemObservation(ItemInstance item)
@ -510,7 +486,7 @@ public class InventoryMenu : MonoBehaviour
equippableItem != null,
equippableItem?.Quality ?? 1,
equippableItem?.Durability ?? 1,
equippableItem?.Temperature ?? 0,
0,
equippableItem != null && equippableItem.OverrideShutdown);
}
@ -524,7 +500,7 @@ public class InventoryMenu : MonoBehaviour
var tradeProjection = AetheriaRuntimeDaemonTradeItemQueries.ProjectTradeItem(
typedItem,
ToRuntimeLoadoutItem(item),
GameManager.ObservedTradeValueSettings());
ResolveCatalog()?.TradeValueSettings);
return tradeProjection.HasTier
? $"{tradeProjection.TierName}{new string('+', tradeProjection.Upgrades)}"
: "";
@ -552,12 +528,12 @@ public class InventoryMenu : MonoBehaviour
{
if (destination.DisplayedEntity != null && item is EquippableItem equippableItem)
{
GameManager.RequestCargoItemEquip(origin, destination.DisplayedEntity, equippableItem);
RequestCargoItemEquip(origin, destination.DisplayedEntity, equippableItem);
return;
}
if (destination.DisplayedCargo != null)
GameManager.RequestCargoItemTransfer(origin, destination.DisplayedCargo, item);
RequestCargoItemTransfer(origin, destination.DisplayedCargo, item);
}
private void ClearSelectedItemSelection()
@ -573,7 +549,440 @@ public class InventoryMenu : MonoBehaviour
private void RequestEquippedItemTransfer(Entity origin, EquippedItem item, InventoryPanel destination)
{
if (destination.DisplayedCargo != null)
GameManager.RequestEquippedItemStore(origin, item, destination.DisplayedCargo);
RequestEquippedItemStore(item, destination.DisplayedCargo);
}
private void RequestCargoItemTransfer(
EquippedCargoBay origin,
EquippedCargoBay destination,
ItemInstance item)
{
if (!TryResolveCargoBay(origin, out var originEntityKey, out var originCargoIndex) ||
!TryResolveCargoBay(destination, out var destinationEntityKey, out var destinationCargoIndex) ||
item == null ||
string.IsNullOrWhiteSpace(item.ItemKey) ||
!origin.Cargo.TryGetValue(item, out var originPosition) ||
!TryValidateTypedCargoSlot(originEntityKey, originCargoIndex, item, originPosition, true))
{
return;
}
var quantity = item is SimpleCommodity commodity ? commodity.Quantity : 1;
if (quantity <= 0)
return;
TrySubmitOperation(
operations => operations.TransferCargoItem(
originEntityKey,
originCargoIndex,
destinationEntityKey,
destinationCargoIndex,
item.ItemKey,
quantity,
originPosition.x,
originPosition.y,
default,
default,
false),
"cargo transfer");
}
private void RequestCargoItemEquip(
EquippedCargoBay origin,
Entity destination,
EquippableItem item)
{
if (!TryResolveCargoBay(origin, out var originEntityKey, out var originCargoIndex) ||
!TryResolveEntityRecordKey(destination, out var destinationEntityKey) ||
item == null ||
string.IsNullOrWhiteSpace(item.ItemKey) ||
!origin.Cargo.TryGetValue(item, out var originPosition) ||
!TryValidateTypedCargoSlot(originEntityKey, originCargoIndex, item, originPosition, true))
{
return;
}
TrySubmitOperation(
operations => operations.EquipItem(
"cargo",
originEntityKey,
originCargoIndex,
destinationEntityKey,
item.ItemKey,
originPosition.x,
originPosition.y,
default,
default,
false),
"cargo equip");
}
private void RequestEquippedItemStore(
EquippedItem item,
EquippedCargoBay destination)
{
if (!TryResolveEquippedItem(item, out var originEntityKey, out var equipmentIndex) ||
!TryResolveCargoBay(destination, out var destinationEntityKey, out var destinationCargoIndex) ||
item?.EquippableItem == null ||
!TryValidateTypedEquipmentSlot(originEntityKey, equipmentIndex, item))
{
return;
}
TrySubmitOperation(
operations => operations.StoreItem(
originEntityKey,
equipmentIndex,
destinationEntityKey,
destinationCargoIndex,
item.EquippableItem.ItemKey,
default,
default,
false),
"equipment store");
}
private void RequestEntityShutdownPerformance(string targetEntityKey, float shutdownPerformance)
{
if (string.IsNullOrWhiteSpace(targetEntityKey))
return;
TrySubmitOperation(
operations => operations.SetShutdownPerformance(targetEntityKey, shutdownPerformance),
"entity shutdown-performance");
}
private void RequestEquippedItemOverrideShutdown(EquippedItem item, bool enabled)
{
if (!TryResolveEquippedItem(item, out var targetEntityKey, out var equipmentIndex) ||
item?.EquippableItem == null)
{
return;
}
TrySubmitOperation(
operations => operations.SetItemOverrideShutdown(targetEntityKey, equipmentIndex, enabled),
"equipped-item override-shutdown");
}
private void RequestThermotoggleTargetTemperature(
EquippedItem item,
int behaviorIndex,
float targetTemperature)
{
if (!TryResolveEquippedItem(item, out var targetEntityKey, out var equipmentIndex) ||
behaviorIndex < 0 ||
behaviorIndex >= (item?.Behaviors?.Length ?? 0))
{
return;
}
TrySubmitOperation(
operations => operations.SetThermotoggleTargetTemperature(
targetEntityKey,
equipmentIndex,
behaviorIndex,
targetTemperature),
"thermotoggle target-temperature");
}
private void RequestWeaponGroupMembership(EquippedItem item, int groupIndex, bool assigned)
{
if (!TryResolveEquippedItem(item, out var targetEntityKey, out var equipmentIndex) ||
groupIndex < 0)
{
return;
}
TrySubmitOperation(
operations => operations.SetWeaponGroupMembership(
targetEntityKey,
equipmentIndex,
groupIndex,
assigned),
"weapon-group membership");
}
private bool TryResolveEntityRecordKey(Entity entity, out string recordKey)
{
recordKey = "";
return _observedFacadeIndex != null &&
_observedFacadeIndex.TryResolveEntityRecordKey(entity, out recordKey);
}
private bool IsCurrentEntity(Entity entity)
{
if (entity == null ||
!TryResolveEntityRecordKey(entity, out var entityKey) ||
string.IsNullOrWhiteSpace(entityKey) ||
!TryResolveCurrentEntityKey(out var currentEntityKey))
{
return false;
}
return string.Equals(entityKey, currentEntityKey, StringComparison.Ordinal);
}
private bool TryGetTypedCurrentEntityFacade(out Entity entity)
{
entity = null;
if (_observedFacadeIndex == null ||
!TryResolveCurrentEntityKey(out var currentEntityKey))
{
return false;
}
return _observedFacadeIndex.TryResolveEntityByRecordKey(currentEntityKey, out entity);
}
private bool TryGetTypedCurrentDockingBayFacade(out EquippedDockingBay dockingBay)
{
dockingBay = null;
var stationRefit = ResolveStationRefit();
var dockParentEntityKey = stationRefit?.DockParentEntityKey ?? "";
if (_observedFacadeIndex == null ||
!TryResolveCurrentDockingBayRow(out var dockingBayRow) ||
string.IsNullOrWhiteSpace(dockParentEntityKey) ||
!_observedFacadeIndex.TryResolveDockingBayByRecordKey(
dockParentEntityKey,
dockingBayRow.DockingBayIndex,
out dockingBay))
{
return false;
}
return dockingBay != null;
}
private bool TryResolveCurrentDockingBayRow(out AetheriaRuntimeStationDockingBayRow dockingBay)
{
dockingBay = null;
var stationRefit = ResolveStationRefit();
if (stationRefit?.IsDocked != true || stationRefit.DockingBayIndex < 0)
return false;
dockingBay = (stationRefit.DockingBays ?? Array.Empty<AetheriaRuntimeStationDockingBayRow>())
.FirstOrDefault(row => row != null && row.DockingBayIndex == stationRefit.DockingBayIndex);
return dockingBay != null;
}
private bool TryResolveCurrentEntityKey(out string currentEntityKey)
{
currentEntityKey = "";
if (!TryResolveCurrentEntityDocument(out var currentEntity))
return false;
currentEntityKey = currentEntity?.EntityKey ?? "";
return !string.IsNullOrWhiteSpace(currentEntityKey);
}
private bool TryResolveCurrentEntityDocument(out AetheriaRuntimeCurrentEntityDocument currentEntity)
{
currentEntity = null;
try
{
currentEntity = ResolveClient()
.CurrentEntityAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria current entity for inventory menu: {ex.Message}");
return false;
}
return currentEntity != null;
}
private bool TryResolveCurrentDocking(out AetheriaRuntimeCurrentDockingDocument docking)
{
docking = null;
try
{
docking = ResolveClient()
.CurrentDockingAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria current docking for inventory menu: {ex.Message}");
return false;
}
return docking != null;
}
private bool TryResolveCargoBay(EquippedCargoBay cargoBay, out string entityKey, out int cargoIndex)
{
return TryResolveEquippedItem(cargoBay, out entityKey, out cargoIndex);
}
private bool TryResolveEquippedItem(EquippedItem item, out string entityKey, out int equipmentIndex)
{
entityKey = "";
equipmentIndex = -1;
var entity = item?.Entity;
if (entity?.Equipment == null ||
!TryResolveEntityRecordKey(entity, out entityKey))
{
return false;
}
equipmentIndex = entity.Equipment.IndexOf(item);
return equipmentIndex >= 0;
}
private bool TryResolveTypedInventoryRows(
string entityKey,
out IReadOnlyList<AetheriaRuntimeRtsInventoryItem> equipment,
out IReadOnlyList<AetheriaRuntimeRtsInventoryItem> cargo)
{
equipment = Array.Empty<AetheriaRuntimeRtsInventoryItem>();
cargo = Array.Empty<AetheriaRuntimeRtsInventoryItem>();
if (string.IsNullOrWhiteSpace(entityKey))
return false;
try
{
var current = ResolveClient()
.CurrentEntityAsync()
.GetAwaiter()
.GetResult();
if (current != null && string.Equals(current.EntityKey, entityKey, StringComparison.Ordinal))
{
equipment = current.Equipment ?? Array.Empty<AetheriaRuntimeRtsInventoryItem>();
cargo = current.Cargo ?? Array.Empty<AetheriaRuntimeRtsInventoryItem>();
return true;
}
var refit = ResolveClient()
.StationRefitAsync()
.GetAwaiter()
.GetResult();
var entityIndex = -1;
if (refit != null)
{
if (string.Equals(refit.DockParentEntityKey, entityKey, StringComparison.Ordinal))
entityIndex = refit.DockParentEntityIndex;
else
entityIndex = (refit.AvailableEntities ?? Array.Empty<AetheriaRuntimeStationRefitEntityOption>())
.FirstOrDefault(option => string.Equals(option.EntityKey, entityKey, StringComparison.Ordinal))
?.EntityIndex ?? -1;
}
if (entityIndex < 0)
return false;
var inventory = ResolveClient()
.InventoryAsync(entityIndex)
.GetAwaiter()
.GetResult();
if (inventory == null || !string.Equals(inventory.EntityKey, entityKey, StringComparison.Ordinal))
return false;
equipment = inventory.Equipment ?? Array.Empty<AetheriaRuntimeRtsInventoryItem>();
cargo = inventory.Cargo ?? Array.Empty<AetheriaRuntimeRtsInventoryItem>();
return true;
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to validate Aetheria inventory projection for {entityKey}: {ex.Message}");
return false;
}
}
private bool TryValidateTypedCargoSlot(
string entityKey,
int cargoIndex,
ItemInstance item,
int2 originPosition,
bool hasOriginPosition)
{
if (item == null ||
string.IsNullOrWhiteSpace(item.ItemKey) ||
!TryResolveTypedInventoryRows(entityKey, out _, out var cargo))
{
return false;
}
return cargo.Any(row =>
string.Equals(row.Source, "cargo", StringComparison.Ordinal) &&
row.SourceIndex == cargoIndex &&
string.Equals(row.ItemKey, item.ItemKey, StringComparison.Ordinal) &&
(!hasOriginPosition || (row.X == originPosition.x && row.Y == originPosition.y)));
}
private bool TryValidateTypedEquipmentSlot(
string entityKey,
int equipmentIndex,
EquippedItem item)
{
if (item?.EquippableItem == null ||
string.IsNullOrWhiteSpace(item.EquippableItem.ItemKey) ||
!TryResolveTypedInventoryRows(entityKey, out var equipment, out _))
{
return false;
}
return equipment.Any(row =>
string.Equals(row.Source, "equipment", StringComparison.Ordinal) &&
row.SourceIndex == equipmentIndex &&
row.X == item.Position.x &&
row.Y == item.Position.y &&
string.Equals(row.ItemKey, item.EquippableItem.ItemKey, StringComparison.Ordinal));
}
private bool TrySubmitOperation(
Action<AetheriaControl> submit,
string label)
{
if (submit == null)
return false;
try
{
submit(ResolveClient().Control);
return true;
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to send Aetheria daemon inventory menu {label} operation; operation not submitted: {ex.Message}");
return false;
}
}
private AetheriaClient ResolveClient()
{
var gameDataDirectory = new DirectoryInfo(Path.Combine(Application.dataPath, "..", "GameData"));
var stateBoot = AetheriaRuntimeStateBoot.Inspect(gameDataDirectory);
if (_client != null && string.Equals(_clientStatePath, stateBoot.StateFilePath, StringComparison.Ordinal))
return _client;
DisposeClient();
_client = AetheriaClient
.OpenLocalAsync(
gameDataDirectory,
"unity-inventory-menu",
"local",
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_clientStatePath = stateBoot.StateFilePath;
return _client;
}
private void DisposeClient()
{
_client?.Dispose();
_client = null;
_clientStatePath = "";
_catalog = null;
_playerSettings = null;
}
void Update()
@ -623,9 +1032,85 @@ public class InventoryMenu : MonoBehaviour
return Array.Empty<int2>();
}
private static AetheriaRuntimeCatalogItem FindTypedInventoryItem(ItemInstance item)
private AetheriaRuntimeCatalogItem FindTypedInventoryItem(ItemInstance item)
{
return ActionGameManager.RuntimeCatalog?.FindItem(item?.ItemKey ?? "");
return ResolveCatalog()?.FindItem(item?.ItemKey ?? "");
}
private AetheriaRuntimeCatalogSnapshot ResolveCatalog()
{
if (_catalog != null)
return _catalog;
try
{
_catalog = ResolveClient().OpenRuntimeCatalog();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria runtime catalog for inventory menu: {ex.Message}");
}
return _catalog;
}
private AetheriaRuntimePlayerSettingsSnapshot ResolvePlayerSettings()
{
if (_playerSettings != null)
return _playerSettings;
try
{
_playerSettings = ResolveClient()
.PlayerSettingsAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria player settings for inventory menu: {ex.Message}");
}
return _playerSettings;
}
private float ResolveDefaultShutdownPerformance()
{
var value = ResolvePlayerSettings()?.DefaultShutdownPerformance ?? 0.25;
return (float)(value <= 0 ? 0.25 : value);
}
private string ResolveManufacturerName(AetheriaRuntimeCatalogItem item)
{
return ResolveCatalog()?.GetManufacturer(item)?.Name ?? "GameCult";
}
private string FormatValue(float value)
{
var settings = ResolvePlayerSettings();
var significantDigits = settings?.SignificantDigits ?? 3;
var magnitude = value == 0.0f ? 0 : (int)Math.Floor(Math.Log10(Math.Abs(value))) + 1;
var digits = significantDigits - magnitude;
if (digits < 0)
digits = 0;
var formatted = value.ToString($"N{digits}", CultureInfo.CurrentCulture);
var separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
var decimalSeparator = Convert.ToChar(separator);
return formatted.Contains(separator)
? formatted.TrimEnd('0').TrimEnd(decimalSeparator)
: formatted;
}
private string FormatTemperature(float value)
{
var unit = ResolvePlayerSettings()?.TemperatureUnit ?? nameof(TemperatureUnit.Celsius);
if (string.Equals(unit, nameof(TemperatureUnit.Kelvin), StringComparison.OrdinalIgnoreCase))
return $"{FormatValue(value)} K";
if (string.Equals(unit, nameof(TemperatureUnit.Fahrenheit), StringComparison.OrdinalIgnoreCase))
return $"{FormatValue(value * (9f / 5) - 459.67f)} F";
return $"{FormatValue(value - 273.15f)} C";
}
private static int2 RotateTypedShapeCell(
@ -644,6 +1129,8 @@ public class InventoryMenu : MonoBehaviour
private void OnDestroy()
{
DisposeClient();
if (_shipSettingsSurfaceDocument != null)
{
AetheriaEveUnitySurfaceHost.DestroyDocument(_shipSettingsSurfaceDocument);

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,18 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using GameCult.Aetheria.EveRuntime;
using GameCult.Aetheria.State.Verse;
using GameCult.Eve.Surface;
using Ink.Runtime;
using TMPro;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
using UnityEngine.UIElements;
public class LocalMenu : MonoBehaviour
{
@ -18,13 +24,37 @@ public class LocalMenu : MonoBehaviour
private string _currentPath;
private LocationStory _currentLocation;
private Story _activeStory;
private List<GameObject> _choiceInstances = new List<GameObject>();
private readonly List<ActiveStoryChoice> _activeChoices = new List<ActiveStoryChoice>();
private UIDocument _surfaceDocument;
private readonly AetheriaEveUnitySurfaceChrome _surfaceChrome = new AetheriaEveUnitySurfaceChrome();
private AetheriaClient _client;
private string _clientStatePath = "";
private AetheriaUnityObservedFacadeIndex _observedFacadeIndex;
public void SetObservedFacadeIndex(AetheriaUnityObservedFacadeIndex observedFacadeIndex)
{
_observedFacadeIndex = observedFacadeIndex;
}
private sealed class ActiveStoryChoice
{
public ActiveStoryChoice(int index, Story story, Choice choice)
{
Index = index;
Story = story;
Choice = choice;
}
public int Index { get; }
public Story Story { get; }
public Choice Choice { get; }
}
private void OnEnable()
{
if (ActionGameManager.Instance == null ||
!ActionGameManager.Instance.TryGetObservedDockedLocalStory(out _currentLocation))
if (!TryResolveDockedLocalStory(out _currentLocation))
{
HideStorySurface();
return;
}
@ -46,11 +76,10 @@ public class LocalMenu : MonoBehaviour
if (!_activeStory.state.previousPointer.isNull) _currentPath = _activeStory.state.previousPointer.path.head.name;
if(_activeStory.canContinue) _activeStory.Continue();
if (!_activeStory.state.previousPointer.isNull) _currentPath = _activeStory.state.previousPointer.path.head.name;
Output.text = _activeStory.currentText;
if (Output != null)
Output.text = _activeStory.currentText;
foreach(var instance in _choiceInstances)
Destroy(instance);
_choiceInstances.Clear();
_activeChoices.Clear();
if(_activeStory.currentChoices.Any())
{
@ -72,6 +101,8 @@ public class LocalMenu : MonoBehaviour
Continue();
}
}
RenderStorySurface();
}
void PresentCurrentChoices()
@ -93,15 +124,174 @@ public class LocalMenu : MonoBehaviour
void PresentChoice(Story story, Choice choice)
{
var choiceInstance = Instantiate(ChoicePrefab, ChoiceParent);
choiceInstance.Label.text = choice.text;
choiceInstance.Button.onClick.AddListener(() =>
_activeChoices.Add(new ActiveStoryChoice(_activeChoices.Count, story, choice));
}
private void RenderStorySurface()
{
if (_activeStory == null)
return;
if (Output != null)
Output.gameObject.SetActive(false);
if (ChoiceParent != null)
ChoiceParent.gameObject.SetActive(false);
_surfaceDocument = AetheriaEveUnitySurfaceHost.RenderRuntime(
transform,
_surfaceDocument,
"Aetheria Runtime Local Story Surface",
AetheriaRuntimeLocalStorySurfaceBuilder.Build(ProjectStorySurface()),
HandleStorySurfaceCommand,
_surfaceChrome);
}
private AetheriaRuntimeLocalStorySurfaceState ProjectStorySurface()
{
return AetheriaRuntimeLocalStorySurfaceBuilder.Project(
ResolveLocationLabel(),
_currentPath,
_activeStory?.currentText ?? "",
_activeStory?.canContinue == true,
_activeChoices.Select(choice => new AetheriaRuntimeLocalStoryChoiceState(
choice.Index,
choice.Choice?.text ?? "")),
DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture));
}
private void HandleStorySurfaceCommand(EveSurfaceCommandRequest request)
{
if (!AetheriaRuntimeLocalStorySurfaceCommands.TryRead(request, out var command))
{
_activeStory = story;
_activeStory.ChoosePath(choice.targetPath);
Continue();
});
_choiceInstances.Add(choiceInstance.gameObject);
Debug.LogWarning($"Unknown runtime local story command: {request?.Command}");
return;
}
switch (command.Kind)
{
case AetheriaRuntimeLocalStoryCommandKind.Continue:
Continue();
return;
case AetheriaRuntimeLocalStoryCommandKind.Choose:
ChooseStoryOption(command.ChoiceIndex);
return;
default:
Debug.LogWarning($"Unknown runtime local story command: {request?.Command}");
return;
}
}
private void ChooseStoryOption(int choiceIndex)
{
var selected = _activeChoices.FirstOrDefault(choice => choice.Index == choiceIndex);
if (selected == null)
{
Debug.LogWarning($"Unknown runtime local story choice index: {choiceIndex}");
return;
}
_activeStory = selected.Story;
_activeStory.ChoosePath(selected.Choice.targetPath);
Continue();
}
private string ResolveLocationLabel()
{
if (!string.IsNullOrWhiteSpace(_currentLocation?.Name))
return _currentLocation.Name;
if (!string.IsNullOrWhiteSpace(_currentLocation?.FileName))
return _currentLocation.FileName;
return "Local";
}
private bool TryResolveCurrentDocking(out AetheriaRuntimeCurrentDockingDocument docking)
{
docking = null;
try
{
docking = ResolveClient()
.CurrentDockingAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria current docking for local story surface: {ex.Message}");
return false;
}
return docking != null;
}
private bool TryResolveDockedLocalStory(out LocationStory story)
{
story = null;
if (_observedFacadeIndex == null ||
!TryResolveCurrentDocking(out var docking) ||
!docking.IsDocked ||
!_observedFacadeIndex.TryResolveDockingBayByRecordKey(
docking.DockParentEntityKey,
docking.DockingBayIndex,
out var dockingBay) ||
dockingBay?.Entity is not OrbitalEntity { Story: { } dockedStory })
{
return false;
}
story = dockedStory;
return true;
}
private AetheriaClient ResolveClient()
{
var gameDataDirectory = new DirectoryInfo(Path.Combine(Application.dataPath, "..", "GameData"));
var stateBoot = AetheriaRuntimeStateBoot.Inspect(gameDataDirectory);
if (_client != null && string.Equals(_clientStatePath, stateBoot.StateFilePath, StringComparison.Ordinal))
return _client;
DisposeClient();
_client = AetheriaClient
.OpenLocalAsync(
gameDataDirectory,
"unity-runtime-local-story",
"local",
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_clientStatePath = stateBoot.StateFilePath;
return _client;
}
private void HideStorySurface()
{
if (_surfaceDocument == null)
return;
AetheriaEveUnitySurfaceHost.Hide(_surfaceDocument);
}
private void DisposeClient()
{
_client?.Dispose();
_client = null;
_clientStatePath = "";
}
private void OnDisable()
{
HideStorySurface();
}
private void OnDestroy()
{
DisposeClient();
if (_surfaceDocument != null)
{
AetheriaEveUnitySurfaceHost.DestroyDocument(_surfaceDocument);
_surfaceDocument = null;
}
}
// Update is called once per frame

View file

@ -5,6 +5,9 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using TMPro;
using UnityEngine;
using Unity.Mathematics;
@ -14,7 +17,6 @@ using int2 = Unity.Mathematics.int2;
public class MapRenderer : MonoBehaviour
{
public ActionGameManager GameManager;
public ZoneRenderer ZoneRenderer;
public TextMeshProUGUI Title;
public Camera MapOverlayCamera;
@ -36,6 +38,11 @@ public class MapRenderer : MonoBehaviour
private RenderTexture _influenceTexture;
private int2 _size;
private bool _init;
private AetheriaClient _client;
private string _clientStatePath = "";
private AetheriaRuntimeObjectsViewportDocument _objectsViewport;
private AetheriaRuntimeGravityViewportDocument _gravityViewport;
private float _nextViewportRefreshTime;
void Start()
{
@ -49,11 +56,10 @@ public class MapRenderer : MonoBehaviour
GravityCamera.gameObject.SetActive(true);
TintCamera.gameObject.SetActive(true);
InfluenceCamera.gameObject.SetActive(true);
GameManager.TryGetObservedRunZone(out var currentZone);
Title.text = $"Zone: {currentZone?.Name ?? "Unknown"}";
RefreshViewportDocuments(force: true);
// If hiding minimap asteroids, turn them back on for the map screen
if (!ActionGameManager.RuntimePlayerSettings.GraphicsSettings.ShowAsteroidsInMinimap)
if (!ResolveShowAsteroidsInMinimap())
ZoneRenderer.ShowAsteroidUI = true;
}
@ -69,10 +75,15 @@ public class MapRenderer : MonoBehaviour
InfluenceCamera.gameObject.SetActive(false);
// If hiding minimap asteroids, turn them back off when leaving the map screen
if (!ActionGameManager.RuntimePlayerSettings.GraphicsSettings.ShowAsteroidsInMinimap)
if (!ResolveShowAsteroidsInMinimap())
ZoneRenderer.ShowAsteroidUI = false;
}
private void OnDestroy()
{
DisposeClient();
}
void ReleaseTextures()
{
_mapTexture.Release();
@ -130,5 +141,96 @@ public class MapRenderer : MonoBehaviour
InfluenceCamera.orthographicSize = _size.y * Scale * .5f;
ZoneRenderer.SetIconSize(IconSize * Scale);
RefreshViewportDocuments(force: false);
}
private void RefreshViewportDocuments(bool force)
{
if (!force && Time.unscaledTime < _nextViewportRefreshTime)
return;
_nextViewportRefreshTime = Time.unscaledTime + .5f;
try
{
var client = ResolveClient();
var viewport = ResolveViewportBounds();
_objectsViewport = client
.ObjectsViewportAsync(viewport)
.GetAwaiter()
.GetResult();
_gravityViewport = client
.GravityViewportAsync(viewport)
.GetAwaiter()
.GetResult();
var zoneName = string.IsNullOrWhiteSpace(_objectsViewport?.ZoneName)
? "Unknown"
: _objectsViewport.ZoneName;
Title.text = $"Zone: {zoneName}";
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria map viewport from local Verse state: {ex.Message}");
Title.text = "Zone: Unknown";
}
}
private AetheriaRuntimeRtsViewportBounds ResolveViewportBounds()
{
var screenHeight = _size.y <= 0 ? Math.Max(1, Screen.height) : _size.y;
var screenWidth = _size.x <= 0 ? Math.Max(1, Screen.width) : _size.x;
var halfHeight = screenHeight * Scale * .5f;
var halfWidth = screenWidth * Scale * .5f;
return new AetheriaRuntimeRtsViewportBounds
{
MinX = Position.x - halfWidth,
MinY = Position.y - halfHeight,
MaxX = Position.x + halfWidth,
MaxY = Position.y + halfHeight
};
}
private bool ResolveShowAsteroidsInMinimap()
{
try
{
return ResolveClient()
.PlayerSettingsAsync()
.GetAwaiter()
.GetResult()
?.ShowAsteroidsInMinimap ?? false;
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria map graphics settings from local Verse state: {ex.Message}");
return false;
}
}
private AetheriaClient ResolveClient()
{
var gameDataDirectory = new DirectoryInfo(Path.Combine(Application.dataPath, "..", "GameData"));
var stateBoot = AetheriaRuntimeStateBoot.Inspect(gameDataDirectory);
if (_client != null && string.Equals(_clientStatePath, stateBoot.StateFilePath, StringComparison.Ordinal))
return _client;
DisposeClient();
_client = AetheriaClient
.OpenLocalAsync(
gameDataDirectory,
"unity-map-renderer",
"local",
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_clientStatePath = stateBoot.StateFilePath;
return _client;
}
private void DisposeClient()
{
_client?.Dispose();
_client = null;
_clientStatePath = "";
}
}

View file

@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GameCult.Aetheria.EveRuntime;
using GameCult.Aetheria.State.Verse;
@ -22,7 +23,6 @@ public class MenuPanel : MonoBehaviour
public bool RequireDock;
}
public ActionGameManager GameManager;
public RectTransform TabButtons;
[SerializeField] private MenuTabBinding[] TabBindings = Array.Empty<MenuTabBinding>();
@ -32,6 +32,8 @@ public class MenuPanel : MonoBehaviour
private MenuTabBinding _current;
private UIDocument _tabSurfaceDocument;
private readonly AetheriaEveUnitySurfaceChrome _tabSurfaceChrome = new AetheriaEveUnitySurfaceChrome();
private AetheriaClient _client;
private string _clientStatePath = "";
public MenuTab CurrentTab { get; private set; }
@ -89,6 +91,7 @@ public class MenuPanel : MonoBehaviour
private void OnDestroy()
{
DisposeClient();
if (_tabSurfaceDocument != null)
{
AetheriaEveUnitySurfaceHost.DestroyDocument(_tabSurfaceDocument);
@ -158,13 +161,58 @@ public class MenuPanel : MonoBehaviour
private MenuTabBinding[] ResolveVisibleTabs()
{
var isDocked = ResolveCurrentDocking()?.IsDocked == true;
return _tabs.Values
.Where(tabBinding => !tabBinding.RequireDock || GameManager.IsObservedDocked)
.Where(tabBinding => tabBinding.Tab != MenuTab.Local || GameManager.TryGetObservedDockedLocalStory(out _))
.Where(tabBinding => !tabBinding.RequireDock || isDocked)
.Where(tabBinding => tabBinding.Tab != MenuTab.Local || isDocked)
.OrderBy(tabBinding => (int)tabBinding.Tab)
.ToArray();
}
private AetheriaRuntimeCurrentDockingDocument ResolveCurrentDocking()
{
try
{
return ResolveClient()
.CurrentDockingAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria current docking for runtime menu tabs: {ex.Message}");
return null;
}
}
private AetheriaClient ResolveClient()
{
var gameDataDirectory = new DirectoryInfo(Path.Combine(Application.dataPath, "..", "GameData"));
var stateBoot = AetheriaRuntimeStateBoot.Inspect(gameDataDirectory);
if (_client != null && string.Equals(_clientStatePath, stateBoot.StateFilePath, StringComparison.Ordinal))
return _client;
DisposeClient();
_client = AetheriaClient
.OpenLocalAsync(
gameDataDirectory,
"unity-runtime-menu-tabs",
"local",
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_clientStatePath = stateBoot.StateFilePath;
return _client;
}
private void DisposeClient()
{
_client?.Dispose();
_client = null;
_clientStatePath = "";
}
private static string GetTabLabel(MenuTabBinding tabBinding)
{
return string.IsNullOrWhiteSpace(tabBinding.Label)

View file

@ -3,13 +3,13 @@ using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GameCult.Aetheria.State.Verse;
using TMPro;
using UniRx;
using UnityEngine;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using static Unity.Mathematics.noise;
using Random = UnityEngine.Random;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
public class SectorMap : MonoBehaviour
@ -41,32 +41,44 @@ public class SectorMap : MonoBehaviour
public Color PlayerLocationLabelColor;
public float PlayerLocationIconSize = 1.25f;
public Subject<GalaxyZone> ZoneClicked = new Subject<GalaxyZone>();
public Subject<int> ZoneClicked = new Subject<int>();
private GalaxyZone _currentPlayerLocation;
private HashSet<GalaxyZone> _revealedZones = new HashSet<GalaxyZone>();
private HashSet<(GalaxyZone, GalaxyZone)> _revealedLinks = new HashSet<(GalaxyZone, GalaxyZone)>();
private int _currentPlayerLocation = -1;
private readonly HashSet<int> _revealedZones = new HashSet<int>();
private readonly HashSet<(int, int)> _revealedLinks = new HashSet<(int, int)>();
private readonly Dictionary<int, (MeshRenderer influenceRenderer, RenderTexture influence, Material primaryMaterial, Material secondaryMaterial, Material linkMaterial)> _factionMaterials =
new Dictionary<int, (MeshRenderer influenceRenderer, RenderTexture influence, Material primaryMaterial, Material secondaryMaterial, Material linkMaterial)>();
private readonly Dictionary<int, SectorZoneUI> _zoneInstances = new Dictionary<int, SectorZoneUI>();
private readonly Queue<IEnumerable<int>> _queuedZoneReveals = new Queue<IEnumerable<int>>();
private readonly Dictionary<int, AetheriaRuntimeSectorMapZone> _zonesByIndex =
new Dictionary<int, AetheriaRuntimeSectorMapZone>();
private AetheriaRuntimeSectorMapDocument _sectorMap;
private AetheriaClient _client;
private string _clientStatePath = "";
private bool _sectorMapLoaded;
private Dictionary<Faction, (MeshRenderer influenceRenderer, RenderTexture influence, Material primaryMaterial, Material secondaryMaterial, Material linkMaterial)> _factionMaterials =
new Dictionary<Faction, (MeshRenderer influenceRenderer, RenderTexture influence, Material primaryMaterial, Material secondaryMaterial, Material linkMaterial)>();
private Dictionary<GalaxyZone, SectorZoneUI> _zoneInstances = new Dictionary<GalaxyZone, SectorZoneUI>();
private Queue<IEnumerable<GalaxyZone>> _queuedZoneReveals = new Queue<IEnumerable<GalaxyZone>>();
public void MarkPlayerLocation(GalaxyZone zone)
public bool TryMarkPlayerLocation(int zoneIndex)
{
if (_currentPlayerLocation != null)
EnsureSectorMapLoaded();
if (!_zonesByIndex.ContainsKey(zoneIndex))
return false;
MarkPlayerLocation(zoneIndex);
return true;
}
private void MarkPlayerLocation(int zoneIndex)
{
if (_currentPlayerLocation >= 0 && _zoneInstances.TryGetValue(_currentPlayerLocation, out var previous))
{
_zoneInstances[_currentPlayerLocation].Label.color = Color.white;
_zoneInstances[_currentPlayerLocation].Label.fontStyle = FontStyles.Normal;
_zoneInstances[_currentPlayerLocation].IconContainer.localScale = Vector3.one;
previous.Label.color = Color.white;
previous.Label.fontStyle = FontStyles.Normal;
previous.IconContainer.localScale = Vector3.one;
}
_currentPlayerLocation = zone;
if(_zoneInstances.ContainsKey(_currentPlayerLocation))
{
MarkPlayerLocation(_zoneInstances[_currentPlayerLocation]);
}
_currentPlayerLocation = zoneIndex;
if (_zoneInstances.TryGetValue(_currentPlayerLocation, out var zoneUI))
MarkPlayerLocation(zoneUI);
}
private void MarkPlayerLocation(SectorZoneUI zoneUI)
@ -76,274 +88,315 @@ public class SectorMap : MonoBehaviour
zoneUI.IconContainer.localScale = new Vector3(PlayerLocationIconSize, PlayerLocationIconSize, 1);
}
public void QueueZoneReveal(IEnumerable<GalaxyZone> zones)
public void QueueZoneReveal(IEnumerable<int> zoneIndices)
{
_queuedZoneReveals.Enqueue(zones);
_queuedZoneReveals.Enqueue(zoneIndices ?? Array.Empty<int>());
}
public void StartReveal(float linkDuration, float iconDuration)
{
EnsureSectorMapLoaded();
if (_queuedZoneReveals.Count > 0)
{
StartCoroutine(RevealZone(_queuedZoneReveals.Dequeue(), linkDuration, iconDuration));
}
}
public IEnumerator RevealZone(IEnumerable<GalaxyZone> zones, float linkDuration, float iconDuration)
public IEnumerator RevealZone(IEnumerable<int> zoneIndices, float linkDuration, float iconDuration)
{
if (!ActionGameManager.TryGetObservedGalaxy(out var observedGalaxy))
yield break;
var linksToReveal = new List<(float2 start, float2 end, Transform linkInstance, bool critical)>();
var zoneTransforms = new List<Transform>();
var zoneInstanceScale = ZonePrototype.transform.localScale;
foreach (var zone in zones)
foreach (var zoneIndex in zoneIndices ?? Array.Empty<int>())
{
if (!_revealedZones.Contains(zone))
if (!_zonesByIndex.TryGetValue(zoneIndex, out var zone) || _revealedZones.Contains(zoneIndex))
continue;
var zoneInstance = ZonePrototype.Instantiate<SectorZoneUI>();
zoneInstance.Clickable.OnClick += (_, _, _, _) => ZoneClicked.OnNext(zone.ZoneIndex);
if(zone.ZoneIndex == _currentPlayerLocation)
MarkPlayerLocation(zoneInstance);
_zoneInstances[zone.ZoneIndex] = zoneInstance;
var zoneInstanceTransform = zoneInstance.transform;
zoneTransforms.Add(zoneInstanceTransform);
zoneInstanceTransform.localPosition = new Vector3((float)zone.X, (float)zone.Y);
if (zone.OwnerFactionIndex >= 0 && _factionMaterials.TryGetValue(zone.OwnerFactionIndex, out var ownerMaterials))
{
var zoneInstance = ZonePrototype.Instantiate<SectorZoneUI>();
zoneInstance.Clickable.OnClick += (_, _, _, _) => ZoneClicked.OnNext(zone);
if(zone == _currentPlayerLocation)
MarkPlayerLocation(zoneInstance);
_zoneInstances[zone] = zoneInstance;
var zoneInstanceTransform = zoneInstance.transform;
zoneTransforms.Add(zoneInstanceTransform);
zoneInstanceTransform.localPosition = new Vector3(zone.Position.x, zone.Position.y);
if(zone.Owner != null)
{
zoneInstance.Primary.sharedMaterial = _factionMaterials[zone.Owner].primaryMaterial;
zoneInstance.Secondary.sharedMaterial = _factionMaterials[zone.Owner].secondaryMaterial;
if(zone == observedGalaxy.HomeZones[zone.Owner])
zoneInstance.Secondary.transform.localScale = Vector3.one * 4;
}
else
{
zoneInstance.Secondary.gameObject.SetActive(false);
}
var isOnCriticalPath = observedGalaxy.ExitPath?.Contains(zone) ?? false;
foreach (var adjacentZone in zone.AdjacentZones)
{
// If the adjacent zone is in the set already revealed, then show the link
if (_revealedZones.Contains(adjacentZone) &&
!(_revealedLinks.Contains((zone, adjacentZone)) ||
_revealedLinks.Contains((adjacentZone, zone))))
{
var link = LinkPrototype.Instantiate<Transform>();
var critical = isOnCriticalPath && (observedGalaxy.ExitPath?.Contains(adjacentZone) ?? false);
linksToReveal.Add((zone.Position, adjacentZone.Position, link, critical));
if (zone.Owner != null && zone.Owner.HasSameKey(adjacentZone.Owner))
link.GetComponent<MeshRenderer>().sharedMaterial = _factionMaterials[zone.Owner].linkMaterial;
var dir = normalize(zone.Position - adjacentZone.Position);
link.rotation = Quaternion.Euler(0,0,atan2(dir.y,dir.x) * Mathf.Rad2Deg);
placeLink(zone.Position, adjacentZone.Position, link, 0, critical);
}
}
_revealedZones.Add(zone);
// Determine center of mass for adjacent zone links, used for placement of label and icons
var linkDirection = normalize(zone.AdjacentZones
.Aggregate(float2.zero, (v, adjacentZone) => v + normalize(adjacentZone.Position - zone.Position)));
var zoneText = zoneInstance.Label;
zoneText.text = zone.Name;
var zoneTextTransform = zoneText.GetComponent<RectTransform>();
zoneTextTransform.pivot = new Vector2(sign(linkDirection.x)/2+.5f,sign(linkDirection.y)/2+.5f);
zoneTextTransform.localPosition = new Vector3(-linkDirection.x * LabelDistance, -linkDirection.y * LabelDistance, -1);
if (zone == observedGalaxy.Entrance)
{
var iconInstance = IconPrototype.Instantiate<MeshRenderer>();
iconInstance.material.mainTexture = EntranceIcon;
var iconTransform = iconInstance.transform;
iconTransform.SetParent(zoneInstanceTransform);
iconTransform.localScale = Vector3.one;
iconTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance);
}
if (zone == observedGalaxy.Exit)
{
var iconInstance = IconPrototype.Instantiate<MeshRenderer>();
iconInstance.material.mainTexture = ExitIcon;
var iconTransform = iconInstance.transform;
iconTransform.SetParent(zoneInstanceTransform);
iconTransform.localScale = Vector3.one;
iconTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance);
}
var homeMega = observedGalaxy.HomeZones.Keys
.FirstOrDefault(m => observedGalaxy.HomeZones[m] == zone);
if (homeMega != null)
{
var backgroundInstance = IconBackgroundPrototype.Instantiate<MeshRenderer>();
var iconInstance = IconPrototype.Instantiate<MeshRenderer>();
backgroundInstance.material.SetColor("_Color", homeMega.SecondaryColor.ToColor());
iconInstance.material.mainTexture = HomeIcon;
iconInstance.material.SetColor("_Color", homeMega.PrimaryColor.ToColor());
var backgroundTransform = backgroundInstance.transform;
var iconTransform = iconInstance.transform;
backgroundTransform.SetParent(zoneInstanceTransform);
iconTransform.SetParent(zoneInstanceTransform);
backgroundTransform.localScale = Vector3.one * IconBackgroundSize;
iconTransform.localScale = Vector3.one;
backgroundTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance, .5f);
iconTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance);
}
var bossMega = observedGalaxy.BossZones.Keys
.FirstOrDefault(m => observedGalaxy.BossZones[m] == zone);
if (bossMega != null)
{
var backgroundInstance = IconBackgroundPrototype.Instantiate<MeshRenderer>();
var iconInstance = IconPrototype.Instantiate<MeshRenderer>();
backgroundInstance.material.SetColor("_Color", bossMega.SecondaryColor.ToColor());
iconInstance.material.mainTexture = BossIcon;
iconInstance.material.SetColor("_Color", bossMega.PrimaryColor.ToColor());
var backgroundTransform = backgroundInstance.transform;
var iconTransform = iconInstance.transform;
backgroundTransform.SetParent(zoneInstanceTransform);
iconTransform.SetParent(zoneInstanceTransform);
backgroundTransform.localScale = Vector3.one * IconBackgroundSize;
iconTransform.localScale = Vector3.one;
if (homeMega != null)
{
backgroundTransform.localPosition = new Vector3(linkDirection.x * IconDistance, linkDirection.y * IconDistance, .5f);
iconTransform.localPosition = new Vector3(linkDirection.x * IconDistance, linkDirection.y * IconDistance);
}
else
{
backgroundTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance, .5f);
iconTransform.localPosition = new Vector3(-linkDirection.x * IconDistance, -linkDirection.y * IconDistance);
}
}
zoneInstance.Primary.sharedMaterial = ownerMaterials.primaryMaterial;
zoneInstance.Secondary.sharedMaterial = ownerMaterials.secondaryMaterial;
}
else
{
zoneInstance.Secondary.gameObject.SetActive(false);
}
foreach (var link in LinksForZone(zone.ZoneIndex))
{
var adjacentIndex = link.FromZoneIndex == zone.ZoneIndex ? link.ToZoneIndex : link.FromZoneIndex;
if (!_zonesByIndex.TryGetValue(adjacentIndex, out var adjacentZone) ||
!_revealedZones.Contains(adjacentIndex) ||
_revealedLinks.Contains((zone.ZoneIndex, adjacentIndex)) ||
_revealedLinks.Contains((adjacentIndex, zone.ZoneIndex)))
{
continue;
}
var linkInstance = LinkPrototype.Instantiate<Transform>();
var critical = zone.Entrance || zone.Exit || adjacentZone.Entrance || adjacentZone.Exit;
var start = Position(zone);
var end = Position(adjacentZone);
linksToReveal.Add((start, end, linkInstance, critical));
if (zone.OwnerFactionIndex >= 0 &&
zone.OwnerFactionIndex == adjacentZone.OwnerFactionIndex &&
_factionMaterials.TryGetValue(zone.OwnerFactionIndex, out var factionMaterials))
{
linkInstance.GetComponent<MeshRenderer>().sharedMaterial = factionMaterials.linkMaterial;
}
var dir = normalize(start - end);
linkInstance.rotation = Quaternion.Euler(0, 0, atan2(dir.y, dir.x) * Mathf.Rad2Deg);
placeLink(start, end, linkInstance, 0, critical);
_revealedLinks.Add((zone.ZoneIndex, adjacentIndex));
}
_revealedZones.Add(zone.ZoneIndex);
var linkDirection = ResolveLabelDirection(zone);
var zoneText = zoneInstance.Label;
zoneText.text = zone.Name;
var zoneTextTransform = zoneText.GetComponent<RectTransform>();
zoneTextTransform.pivot = new Vector2(sign(linkDirection.x) / 2 + .5f, sign(linkDirection.y) / 2 + .5f);
zoneTextTransform.localPosition = new Vector3(-linkDirection.x * LabelDistance, -linkDirection.y * LabelDistance, -1);
if (zone.Entrance)
AddZoneIcon(zoneInstanceTransform, EntranceIcon, linkDirection, -1);
if (zone.Exit)
AddZoneIcon(zoneInstanceTransform, ExitIcon, linkDirection, zone.Entrance ? 1 : -1);
}
foreach (var tr in zoneTransforms) tr.gameObject.SetActive(false);
// Local function for animating the placement of a link
void placeLink(float2 start, float2 end, Transform link, float t, bool critical)
{
var pos = lerp(start, end, t / 2);
link.localPosition = new Vector3(pos.x, pos.y);
var localScale = link.localScale;
localScale = new Vector3(length(start - end)*t, critical ? CriticalLinkWidth : LinkWidth, 1);
link.localScale = localScale;
link.localScale = new Vector3(length(start - end) * t, critical ? CriticalLinkWidth : LinkWidth, 1);
}
var startTime = Time.time;
while (Time.time - startTime < linkDuration)
{
var t = (Time.time - startTime) / linkDuration;
foreach (var (start, end, link, critical) in linksToReveal) placeLink(end, start, link, t, critical);
foreach (var (start, end, link, critical) in linksToReveal)
placeLink(end, start, link, t, critical);
yield return null;
}
foreach (var (start, end, link, critical) in linksToReveal) placeLink(start, end, link, 1, critical);
foreach (var (start, end, link, critical) in linksToReveal)
placeLink(start, end, link, 1, critical);
foreach (var tr in zoneTransforms)
tr.gameObject.SetActive(true);
foreach (var tr in zoneTransforms) tr.gameObject.SetActive(true);
startTime = Time.time;
while (Time.time - startTime < iconDuration)
{
var t = (Time.time - startTime) / iconDuration;
foreach (var tr in zoneTransforms) tr.localScale = zoneInstanceScale * IconScaleAnimation.Evaluate(t);
foreach (var tr in zoneTransforms)
tr.localScale = zoneInstanceScale * IconScaleAnimation.Evaluate(t);
RenderInfluence();
yield return null;
}
foreach (var tr in zoneTransforms) tr.localScale = zoneInstanceScale;
foreach (var tr in zoneTransforms)
tr.localScale = zoneInstanceScale;
StartReveal(linkDuration, iconDuration);
}
public void Start()
{
if (!ActionGameManager.TryGetObservedGalaxy(out var observedGalaxy))
EnsureSectorMapLoaded();
}
private void EnsureSectorMapLoaded()
{
_sectorMap = ResolveClient()
.SectorMapAsync()
.GetAwaiter()
.GetResult();
if (_sectorMapLoaded)
return;
_sectorMapLoaded = true;
if (_sectorMap?.Zones == null || _sectorMap.Zones.Count == 0)
{
gameObject.SetActive(false);
return;
}
foreach (var mega in observedGalaxy.Factions)
_zonesByIndex.Clear();
foreach (var zone in _sectorMap.Zones)
_zonesByIndex[zone.ZoneIndex] = zone;
foreach (var factionIndex in ResolveFactionIndices())
AddFactionMaterials(factionIndex);
foreach (var zoneIndex in _sectorMap.DiscoveredZoneIndices)
QueueZoneReveal([zoneIndex]);
if (_queuedZoneReveals.Count == 0)
QueueZoneReveal(_sectorMap.Zones.Select(zone => zone.ZoneIndex));
if (_sectorMap.CurrentZoneIndex >= 0)
TryMarkPlayerLocation(_sectorMap.CurrentZoneIndex);
}
private void OnDestroy()
{
DisposeClient();
}
private void AddFactionMaterials(int factionIndex)
{
if (_factionMaterials.ContainsKey(factionIndex))
return;
var primaryColor = ResolveFactionColor(factionIndex, secondary: false);
var secondaryColor = ResolveFactionColor(factionIndex, secondary: true);
var influenceTexture = new RenderTexture(1024, 1024, 0, RenderTextureFormat.RHalf);
var influenceRenderer = InfluenceRendererPrototype.Instantiate<MeshRenderer>();
influenceRenderer.material.mainTexture = influenceTexture;
influenceRenderer.material.SetColor("_Color1", primaryColor);
influenceRenderer.material.SetColor("_Color2", secondaryColor);
influenceRenderer.material.SetFloat("_FillTilt", Random.value * PI);
var primary = Instantiate(ZonePrimaryMaterial);
primary.SetColor("_Color", primaryColor * MegaPrimaryBoost);
var secondary = Instantiate(ZoneSecondaryMaterial);
secondary.SetColor("_Color", secondaryColor * MegaSecondaryBoost);
var link = Instantiate(ZoneLinkMaterial);
link.SetColor("_Color", primaryColor * MegaLinkBoost);
_factionMaterials.Add(factionIndex, (influenceRenderer, influenceTexture, primary, secondary, link));
var legendElement = LegendPrototype.Instantiate<LegendElement>();
legendElement.Primary.color = primaryColor;
legendElement.Secondary.color = secondaryColor;
legendElement.Label.text = factionIndex < 0 ? "None" : $"F{factionIndex}";
}
private IEnumerable<int> ResolveFactionIndices()
{
return (_sectorMap?.Zones ?? Array.Empty<AetheriaRuntimeSectorMapZone>())
.SelectMany(zone => (zone.FactionIndices ?? Array.Empty<int>()).Append(zone.OwnerFactionIndex))
.Where(index => index >= 0)
.Distinct()
.OrderBy(index => index);
}
private Color ResolveFactionColor(int factionIndex, bool secondary)
{
var hue = frac((factionIndex + (secondary ? 0.37f : 0f)) * 0.173f);
return Color.HSVToRGB(hue, secondary ? 0.48f : 0.62f, secondary ? 0.72f : 0.88f);
}
private IEnumerable<AetheriaRuntimeSectorMapLink> LinksForZone(int zoneIndex)
{
return (_sectorMap?.Links ?? Array.Empty<AetheriaRuntimeSectorMapLink>())
.Where(link => link.FromZoneIndex == zoneIndex || link.ToZoneIndex == zoneIndex);
}
private float2 ResolveLabelDirection(AetheriaRuntimeSectorMapZone zone)
{
var direction = float2.zero;
foreach (var adjacentIndex in zone.AdjacentZoneIndices ?? Array.Empty<int>())
{
var influenceTexture = new RenderTexture(1024, 1024, 0, RenderTextureFormat.RHalf);
var influenceRenderer = InfluenceRendererPrototype.Instantiate<MeshRenderer>();
influenceRenderer.material.mainTexture = influenceTexture;
influenceRenderer.material.SetColor("_Color1", mega.PrimaryColor.ToColor());
influenceRenderer.material.SetColor("_Color2", mega.SecondaryColor.ToColor());
influenceRenderer.material.SetFloat("_FillTilt", Random.value * PI);
var primary = Instantiate(ZonePrimaryMaterial);
primary.SetColor("_Color", (mega.PrimaryColor * MegaPrimaryBoost).ToColor());
var secondary = Instantiate(ZoneSecondaryMaterial);
secondary.SetColor("_Color", (mega.SecondaryColor * MegaSecondaryBoost).ToColor());
var link = Instantiate(ZoneLinkMaterial);
link.SetColor("_Color", (mega.PrimaryColor * MegaLinkBoost).ToColor());
_factionMaterials.Add(mega, (influenceRenderer, influenceTexture, primary, secondary, link));
var legendElement = LegendPrototype.Instantiate<LegendElement>();
legendElement.Primary.color = mega.PrimaryColor.ToColor();
legendElement.Secondary.color = mega.SecondaryColor.ToColor();
legendElement.Label.text = mega.ShortName;
if (_zonesByIndex.TryGetValue(adjacentIndex, out var adjacent))
direction += normalizesafe(Position(adjacent) - Position(zone));
}
SectorRenderer.material.SetFloat("CloudAmplitude", observedGalaxy.Background.CloudAmplitude);
SectorRenderer.material.SetFloat("CloudExponent", observedGalaxy.Background.CloudExponent);
SectorRenderer.material.SetFloat("NoisePosition", observedGalaxy.Background.NoisePosition);
SectorRenderer.material.SetFloat("NoiseAmplitude", observedGalaxy.Background.NoiseAmplitude);
SectorRenderer.material.SetFloat("NoiseOffset", observedGalaxy.Background.NoiseOffset);
SectorRenderer.material.SetFloat("NoiseGain", observedGalaxy.Background.NoiseGain);
SectorRenderer.material.SetFloat("NoiseLacunarity", observedGalaxy.Background.NoiseLacunarity);
SectorRenderer.material.SetFloat("NoiseFrequency", observedGalaxy.Background.NoiseFrequency);
return lengthsq(direction) <= 0 ? new float2(0, 1) : normalize(direction);
}
private void AddZoneIcon(
Transform zoneInstanceTransform,
Texture2D icon,
float2 linkDirection,
int side)
{
var iconInstance = IconPrototype.Instantiate<MeshRenderer>();
iconInstance.material.mainTexture = icon;
var iconTransform = iconInstance.transform;
iconTransform.SetParent(zoneInstanceTransform);
iconTransform.localScale = Vector3.one;
iconTransform.localPosition = new Vector3(
side * -linkDirection.x * IconDistance,
side * -linkDirection.y * IconDistance);
}
private void RenderInfluence()
{
if (!ActionGameManager.TryGetObservedGalaxy(out var observedGalaxy))
return;
// Render Influence Textures
foreach (var mega in observedGalaxy.Factions)
foreach (var pair in _factionMaterials)
{
foreach (var zone in observedGalaxy.Zones)
foreach (var zone in _sectorMap?.Zones ?? Array.Empty<AetheriaRuntimeSectorMapZone>())
{
if(_zoneInstances.ContainsKey(zone))
{
var instance = _zoneInstances[zone];
var influence = 0f;
if (zone.Factions.Length > 0)
{
if (zone.Factions.Contains(mega))
{
influence = 10;
if (!zone.Owner.HasSameKey(mega))
influence *= .5f;
}
else influence = -10;
}
if (!_zoneInstances.TryGetValue(zone.ZoneIndex, out var instance))
continue;
instance.Influence.material.SetFloat("_Depth", influence);
var influence = 0f;
if (zone.FactionIndices?.Count > 0)
{
if (zone.FactionIndices.Contains(pair.Key))
{
influence = 10;
if (zone.OwnerFactionIndex != pair.Key)
influence *= .5f;
}
else influence = -10;
}
instance.Influence.material.SetFloat("_Depth", influence);
}
InfluenceCamera.targetTexture = _factionMaterials[mega].influence;
InfluenceCamera.targetTexture = pair.Value.influence;
InfluenceCamera.Render();
}
}
private AetheriaClient ResolveClient()
{
var gameDataDirectory = new DirectoryInfo(Path.Combine(Application.dataPath, "..", "GameData"));
var stateBoot = AetheriaRuntimeStateBoot.Inspect(gameDataDirectory);
if (_client != null && string.Equals(_clientStatePath, stateBoot.StateFilePath, StringComparison.Ordinal))
return _client;
DisposeClient();
_client = AetheriaClient
.OpenLocalAsync(
gameDataDirectory,
"unity-sector-map",
"local",
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_clientStatePath = stateBoot.StateFilePath;
return _client;
}
private void DisposeClient()
{
_client?.Dispose();
_client = null;
_clientStatePath = "";
_sectorMapLoaded = false;
}
private static float2 Position(AetheriaRuntimeSectorMapZone zone)
{
return new float2((float)zone.X, (float)zone.Y);
}
}

View file

@ -1,6 +1,8 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using GameCult.Aetheria.EveRuntime;
using GameCult.Aetheria.State.Verse;
@ -19,7 +21,6 @@ public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IS
public ClickRaycaster Raycaster;
public Canvas Canvas;
public SectorMap Map;
public ActionGameManager GameManager;
public Camera SectorCamera;
public MeshRenderer SectorBackgroundRenderer;
public float ZoomSpeed;
@ -45,6 +46,10 @@ public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IS
private float _sectorBackgroundDepth;
private float _sectorCameraDepth;
private UIDocument _zoneDetailsSurfaceDocument;
private AetheriaClient _client;
private string _clientStatePath = "";
private AetheriaRuntimeCatalogSnapshot _catalog;
private AetheriaRuntimePlayerSettingsSnapshot _playerSettings;
private readonly AetheriaEveUnitySurfaceChrome _zoneDetailsSurfaceChrome = new AetheriaEveUnitySurfaceChrome
{
RootAlignItems = Align.FlexEnd,
@ -84,13 +89,13 @@ public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IS
// });
}
private void RenderZoneDetailsSurface(GalaxyZone zone)
private void RenderZoneDetailsSurface(int zoneIndex)
{
_zoneDetailsSurfaceDocument = AetheriaEveUnitySurfaceHost.RenderRuntime(
transform,
_zoneDetailsSurfaceDocument,
"Aetheria Sector Zone Details Surface",
AetheriaRuntimeZoneDetailsSurfaceBuilder.Build(ProjectZoneDetailsSurfaceState(zone)),
AetheriaRuntimeZoneDetailsSurfaceBuilder.Build(ProjectZoneDetailsSurfaceState(zoneIndex)),
HandleZoneDetailsSurfaceCommand,
_zoneDetailsSurfaceChrome);
}
@ -120,24 +125,25 @@ public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IS
AetheriaEveUnitySurfaceHost.Hide(_zoneDetailsSurfaceDocument);
}
private AetheriaRuntimeZoneDetailsSurfaceState ProjectZoneDetailsSurfaceState(GalaxyZone zone)
private AetheriaRuntimeZoneDetailsSurfaceState ProjectZoneDetailsSurfaceState(int zoneIndex)
{
var otherFactions = zone.Factions
.Where(faction => !faction.HasSameKey(zone.Owner))
.Select(faction => faction.Name)
.Where(name => !string.IsNullOrWhiteSpace(name))
var sectorZone = ResolveSectorZone(zoneIndex);
var zoneDetails = ResolveZoneDetails(zoneIndex);
var ownerFactionIndex = sectorZone?.OwnerFactionIndex ?? -1;
var otherFactions = (sectorZone?.FactionIndices ?? Array.Empty<int>())
.Where(index => index >= 0 && index != ownerFactionIndex)
.Distinct()
.Select(FormatFaction)
.ToArray();
var hasContents = GameManager != null &&
GameManager.TryGetObservedZoneSnapshot(zone?.ZoneIndex ?? -1, out var daemonZone);
var daemonProjection = AetheriaRuntimeZoneDetailsSurfaceBuilder.ProjectDaemonZone(
hasContents ? daemonZone : null,
zoneDetails,
ResolveHullType);
return AetheriaRuntimeZoneDetailsSurfaceBuilder.Project(
string.IsNullOrWhiteSpace(daemonZone?.Name) ? zone.Name : daemonZone.Name,
zone.Owner?.Name ?? "None",
ActionGameManager.RuntimePlayerSettings.Format(daemonProjection.Mass),
ActionGameManager.RuntimePlayerSettings.Format(daemonProjection.Radius),
ResolveZoneName(sectorZone, zoneDetails),
ownerFactionIndex >= 0 ? FormatFaction(ownerFactionIndex) : "None",
FormatValue((float)daemonProjection.Mass),
FormatValue((float)daemonProjection.Radius),
otherFactions,
daemonProjection.Bodies,
daemonProjection.Entities,
@ -145,52 +151,181 @@ public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IS
updatedAtUtc: DateTime.UtcNow.ToString("O"));
}
private static string ResolveHullType(string hullItemKey)
private string ResolveZoneName(
AetheriaRuntimeSectorMapZone sectorZone,
AetheriaRuntimeZoneDetailsDocument zoneDetails)
{
var typedHull = ActionGameManager.RuntimeCatalog?.FindItem(hullItemKey ?? "");
if (!string.IsNullOrWhiteSpace(zoneDetails?.ZoneName))
return zoneDetails.ZoneName;
if (!string.IsNullOrWhiteSpace(sectorZone?.Name))
return sectorZone.Name;
return sectorZone == null ? "Unknown" : $"Zone {sectorZone.ZoneIndex}";
}
private AetheriaRuntimeSectorMapZone ResolveSectorZone(int zoneIndex)
{
if (zoneIndex < 0)
return null;
try
{
var sectorMap = ResolveClient()
.SectorMapAsync()
.GetAwaiter()
.GetResult();
return (sectorMap?.Zones ?? Array.Empty<AetheriaRuntimeSectorMapZone>())
.FirstOrDefault(zone => zone.ZoneIndex == zoneIndex);
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria sector map zone from local Verse state: {ex.Message}");
return null;
}
}
private static string FormatFaction(int factionIndex)
{
return factionIndex < 0 ? "None" : $"Faction {factionIndex}";
}
private AetheriaRuntimeZoneDetailsDocument ResolveZoneDetails(int zoneIndex)
{
if (zoneIndex < 0)
return null;
try
{
return ResolveClient()
.ZoneDetailsAsync(zoneIndex)
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria sector zone details from local Verse state: {ex.Message}");
return null;
}
}
private string ResolveHullType(string hullItemKey)
{
var typedHull = ResolveCatalog()?.FindItem(hullItemKey ?? "");
return typedHull?.HullType ?? "";
}
// private IEnumerator AnimatePath()
// {
// var pathZones = ActionGameManager.CurrentSector.ExitPath;
// LegendPanel.SetActive(false);
// PathAnimationButton.gameObject.SetActive(false);
//
// var revealCount = ActionGameManager.CurrentSector.Entrance.Distance[ActionGameManager.CurrentSector.Exit];
// Map.StartReveal(
// PathAnimationDuration / revealCount * (LinkAnimationDuration / (IconAnimationDuration + LinkAnimationDuration)),
// PathAnimationDuration / revealCount * (IconAnimationDuration / (IconAnimationDuration + LinkAnimationDuration)));
// MainCamera.enabled = false;
// SectorCamera.targetTexture = null;
// Canvas.gameObject.SetActive(false);
// SectorCamera.gameObject.SetActive(true);
//
// var pathAnimationLerp = 0f;
// while (pathAnimationLerp < 1)
// {
// var currentTargetZone = pathZones[(int) (pathZones.Length * pathAnimationLerp)];
// _position = lerp(_position, currentTargetZone.Position, PathAnimationDamping);
// pathAnimationLerp += Time.deltaTime / (PathAnimationDuration * PathAnimationDurationPadding);
// UpdateCamera();
// yield return null;
// }
//
// LegendPanel.SetActive(true);
// PathAnimationButton.gameObject.SetActive(true);
// }
private AetheriaRuntimeCatalogSnapshot ResolveCatalog()
{
if (_catalog != null)
return _catalog;
try
{
_catalog = ResolveClient().OpenRuntimeCatalog();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria sector catalog from local Verse state: {ex.Message}");
}
return _catalog;
}
private AetheriaRuntimePlayerSettingsSnapshot ResolvePlayerSettings()
{
if (_playerSettings != null)
return _playerSettings;
try
{
_playerSettings = ResolveClient()
.PlayerSettingsAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria sector player settings from local Verse state: {ex.Message}");
}
return _playerSettings;
}
private string FormatValue(float value)
{
var digits = ResolvePlayerSettings()?.SignificantDigits ?? 3;
var magnitude = value == 0f ? 0 : (int)Math.Floor(Math.Log10(Math.Abs(value))) + 1;
digits -= magnitude;
if (digits < 0)
digits = 0;
var formatted = value.ToString($"N{digits}");
var decimalSeparator = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
return formatted.Contains(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)
? formatted.TrimEnd('0').TrimEnd(decimalSeparator)
: formatted;
}
private AetheriaClient ResolveClient()
{
var gameDataDirectory = new DirectoryInfo(Path.Combine(Application.dataPath, "..", "GameData"));
var stateBoot = AetheriaRuntimeStateBoot.Inspect(gameDataDirectory);
if (_client != null && string.Equals(_clientStatePath, stateBoot.StateFilePath, StringComparison.Ordinal))
return _client;
DisposeClient();
_client = AetheriaClient
.OpenLocalAsync(
gameDataDirectory,
"unity-sector-renderer",
"local",
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_clientStatePath = stateBoot.StateFilePath;
_catalog = null;
_playerSettings = null;
return _client;
}
private void DisposeClient()
{
_client?.Dispose();
_client = null;
_clientStatePath = "";
_catalog = null;
_playerSettings = null;
}
private void OnEnable()
{
_init = true;
SectorCamera.gameObject.SetActive(true);
GameManager.TryGetObservedRunZone(out var currentZone);
_position = currentZone?.Position ?? float2.zero;
var currentZone = ResolveCurrentZone();
_position = currentZone == null
? float2.zero
: new float2((float)currentZone.PositionX, (float)currentZone.PositionY);
_viewSize = .25f;
Map.StartReveal(LinkAnimationDuration, IconAnimationDuration);
if (currentZone != null)
Map.MarkPlayerLocation(currentZone);
Map.TryMarkPlayerLocation(currentZone.ZoneIndex);
}
private AetheriaRuntimeCurrentZoneDocument ResolveCurrentZone()
{
try
{
return ResolveClient()
.CurrentZoneAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria sector current zone from local Verse state: {ex.Message}");
return null;
}
}
private void OnDisable()
@ -206,6 +341,8 @@ public class SectorRenderer : MonoBehaviour, IBeginDragHandler, IDragHandler, IS
private void OnDestroy()
{
DisposeClient();
if (_zoneDetailsSurfaceDocument != null)
{
AetheriaEveUnitySurfaceHost.DestroyDocument(_zoneDetailsSurfaceDocument);

View file

@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using GameCult.Aetheria.EveRuntime;
using GameCult.Aetheria.State.Verse;
@ -13,7 +15,6 @@ using static Unity.Mathematics.math;
public class TradeMenu : MonoBehaviour
{
public ActionGameManager GameManager;
public ConfirmationDialog Dialog;
public UnityEngine.UI.Button NewFilterButton;
public Prototype FilterPrototype;
@ -24,7 +25,9 @@ public class TradeMenu : MonoBehaviour
public UnityEngine.UI.Button FoldoutButton;
public TextMeshProUGUI CreditsLabel;
private EquippedCargoBay _targetCargo;
private string _targetCargoEntityKey = "";
private int _targetCargoIndex = -1;
private string _targetCargoLabel = "Docking Bay";
private (ItemFilter filter, HardpointType type) _hardpointFilter;
private (ItemFilter filter, SimpleCommodityCategory type) _commodityFilter;
private (ItemFilter filter, CompoundCommodityCategory type) _compoundCommodityFilter;
@ -33,11 +36,18 @@ public class TradeMenu : MonoBehaviour
private UIDocument _filterSurfaceDocument;
private UIDocument _rowActionSurfaceDocument;
private UIDocument _tradeItemSurfaceDocument;
private AetheriaClient _client;
private string _clientStatePath = "";
private AetheriaRuntimeCatalogSnapshot _catalog;
private AetheriaRuntimePlayerSettingsSnapshot _playerSettings;
private readonly AetheriaEveUnitySurfaceChrome _cargoSelectorSurfaceChrome = PanelChrome(360f, 420f, Align.FlexEnd);
private readonly AetheriaEveUnitySurfaceChrome _filterSurfaceChrome = PanelChrome(420f, 520f, Align.FlexStart);
private readonly AetheriaEveUnitySurfaceChrome _rowActionSurfaceChrome = PanelChrome(320f, 360f, Align.FlexStart);
private readonly AetheriaEveUnitySurfaceChrome _tradeItemSurfaceChrome = PanelChrome(420f, 520f, Align.FlexStart);
private AetheriaRuntimeTradeCargoSelectorSurfaceProjection _cargoSelectorSurfaceProjection;
private AetheriaRuntimeStationCargoTargetRow[] _cargoSelectorStationRefitTargets =
Array.Empty<AetheriaRuntimeStationCargoTargetRow>();
private AetheriaRuntimeStationRefitDocument _stationRefit;
private AetheriaRuntimeTradeFilterSurfaceProjection _filterSurfaceProjection;
private Action[] _rowActionCallbacks = Array.Empty<Action>();
private AetheriaRuntimeTradeRowActionSurfaceProjection _rowActionSurfaceProjection;
@ -46,9 +56,15 @@ public class TradeMenu : MonoBehaviour
private void OnEnable()
{
if (!GameManager.TryGetObservedDockingBay(out var dockingBay)) return;
_targetCargo = dockingBay;
TargetCargoLabel.text = "Docking Bay";
if (!TryResolveCurrentDocking(out var docking) ||
!docking.IsDocked ||
string.IsNullOrWhiteSpace(docking.DockParentEntityKey) ||
docking.DockingBayIndex < 0)
{
return;
}
SetTargetCargo(docking.DockParentEntityKey, docking.DockingBayIndex, "Docking Bay");
HideCargoSelectorSurface();
HideFilterSurface();
HideRowActionSurface();
@ -80,7 +96,7 @@ public class TradeMenu : MonoBehaviour
var columns = new List<(string name, int size, Func<TradeRow, Func<string>> output, Func<TradeRow, IComparable> sortKey)>();
columns.Add(("Name", 3,
x => () => x.Item is CraftedItemInstance && !string.IsNullOrWhiteSpace(x.TierColorHex) ?
x => () => !string.IsNullOrWhiteSpace(x.TierColorHex) ?
$"<color=#{x.TierColorHex}>{x.Name}" :
x.Name,
x => x.Name));
@ -107,7 +123,7 @@ public class TradeMenu : MonoBehaviour
return 0;
}));
columns.Add(("Mass", 1,
x => () => ActionGameManager.RuntimePlayerSettings.Format(x.Mass),
x => () => FormatValue(x.Mass),
x => x.Mass));
columns.Add(("Price", 1,
x => () => x.Price.ToString("N0"),
@ -116,9 +132,7 @@ public class TradeMenu : MonoBehaviour
x => () => $"{x.ShapeWidth}x{x.ShapeHeight}",
x => x.ShapeWidth * x.ShapeHeight));
var items = Inventory.Cargo.Keys
.Where(PassesTypedTradeFilters)
.Select(item => new TradeRow(item, FindTypedTradeItem(item), ProjectTradeItem(item)));
var items = BuildStationStockRows();
if (MinimumSizeFilter.gameObject.activeSelf)
items = items.Where(i =>
@ -149,7 +163,7 @@ public class TradeMenu : MonoBehaviour
columns.Add((field.Name, 1, x =>
{
var value = GetTypedBehaviorNumber(x, behaviorFilter, field);
return () => ActionGameManager.RuntimePlayerSettings.Format((float)value);
return () => FormatValue((float)value);
}, x =>
{
return (float)GetTypedBehaviorNumber(x, behaviorFilter, field);
@ -158,7 +172,7 @@ public class TradeMenu : MonoBehaviour
columns.Add((field.Name, 1, x =>
{
var value = GetTypedBehaviorNumber(x, behaviorFilter, field);
return () => ActionGameManager.RuntimePlayerSettings.FormatTemperature((float)value);
return () => FormatTemperature((float)value);
}, x =>
{
return (float)GetTypedBehaviorNumber(x, behaviorFilter, field);
@ -177,7 +191,7 @@ public class TradeMenu : MonoBehaviour
columns.Add((field.Name, 1, x =>
{
var value = GetTypedBehaviorNumber(x, behaviorFilter, field);
return () => ActionGameManager.RuntimePlayerSettings.Format((float)value);
return () => FormatValue((float)value);
}, x =>
{
return (float)GetTypedBehaviorNumber(x, behaviorFilter, field);
@ -187,22 +201,8 @@ public class TradeMenu : MonoBehaviour
}
columns.Add(("Owned", 1,
x => () =>
{
if (x.IsHull)
return CountAvailablePlayerShips(x.ItemKey).ToString();
if(x.Item is SimpleCommodity)
return (_targetCargo.ItemsOfType.ContainsKey(x.ItemKey) ? _targetCargo.ItemsOfType[x.ItemKey].Cast<SimpleCommodity>().Sum(s=>s.Quantity) : 0).ToString();
return (_targetCargo.ItemsOfType.ContainsKey(x.ItemKey) ? _targetCargo.ItemsOfType[x.ItemKey].Count : 0).ToString();
},
x =>
{
if (x.IsHull)
return CountAvailablePlayerShips(x.ItemKey);
if(x.Item is SimpleCommodity)
return _targetCargo.ItemsOfType.ContainsKey(x.ItemKey) ? _targetCargo.ItemsOfType[x.ItemKey].Cast<SimpleCommodity>().Sum(s=>s.Quantity) : 0;
return _targetCargo.ItemsOfType.ContainsKey(x.ItemKey) ? _targetCargo.ItemsOfType[x.ItemKey].Count : 0;
}));
x => () => x.OwnedQuantity.ToString(),
x => x.OwnedQuantity));
Spreadsheet.ShowData(
columns.Select(x => x.name).ToArray(),
@ -217,33 +217,39 @@ public class TradeMenu : MonoBehaviour
OnClick = () => RenderTradeItemDetailsSurface(i.TypedItem),
OnDoubleClick = () =>
{
switch (i.Item)
{
case CraftedItemInstance c:
Buy(c);
break;
case SimpleCommodity s:
Buy(s, 1);
break;
}
Buy(i, 1);
Populate();
},
OnRightClick = () =>
{
if (i.Item is SimpleCommodity s)
if (i.TryGetTypedSimpleCommodityCategory(out _))
{
RenderRowActionSurface(
$"Buying {i.Name}",
("Buy Quantity", () => ShowBuyQuantityDialog(i.Name, i.Price, s)));
("Buy Quantity", () => ShowBuyQuantityDialog(i)));
}
}
}));
}
private bool PassesTypedTradeFilters(ItemInstance item)
private IEnumerable<TradeRow> BuildStationStockRows()
{
var typedItem = FindTypedTradeItem(item);
return (ResolveStationRefit()?.StationStock ?? Array.Empty<AetheriaRuntimeStationStockItem>())
.Select(stock =>
{
var typedItem = FindTypedTradeItem(stock.ItemKey);
return new TradeRow(
stock,
typedItem,
ProjectTradeItem(stock, typedItem));
})
.Where(row => row.TypedItem != null)
.Where(PassesTypedTradeFilters);
}
private bool PassesTypedTradeFilters(TradeRow row)
{
var typedItem = row.TypedItem;
if (typedItem == null)
{
return true;
@ -272,30 +278,30 @@ public class TradeMenu : MonoBehaviour
return _behaviorFilters.All(filter => HasTypedBehavior(typedItem, filter));
}
private static AetheriaRuntimeCatalogItem FindTypedTradeItem(ItemInstance item)
private AetheriaRuntimeCatalogItem FindTypedTradeItem(string itemKey)
{
return ActionGameManager.RuntimeCatalog?.FindItem(item?.ItemKey ?? "");
return ResolveCatalog()?.FindItem(itemKey ?? "");
}
private AetheriaRuntimeTradeItemProjection ProjectTradeItem(ItemInstance item)
private AetheriaRuntimeTradeItemProjection ProjectTradeItem(
AetheriaRuntimeStationStockItem stock,
AetheriaRuntimeCatalogItem typedItem)
{
var typedItem = FindTypedTradeItem(item);
return AetheriaRuntimeDaemonTradeItemQueries.ProjectTradeItem(
typedItem,
ProjectTradeItemCommit(item),
GameManager.ObservedTradeValueSettings());
ProjectTradeItemCommit(stock),
ResolveCatalog()?.TradeValueSettings);
}
private static AetheriaRuntimeLoadoutItemCommit? ProjectTradeItemCommit(ItemInstance item)
private static AetheriaRuntimeLoadoutItemCommit? ProjectTradeItemCommit(AetheriaRuntimeStationStockItem stock)
{
if (item is not CraftedItemInstance crafted)
if (stock == null || string.IsNullOrWhiteSpace(stock.ItemKey))
return null;
var durability = item is EquippableItem equippable ? equippable.Durability : 1f;
return AetheriaRuntimeDaemonTradeItemQueries.CraftedItemCommit(
item.ItemKey,
crafted.Quality,
durability);
stock.ItemKey,
stock.Quality,
stock.Durability);
}
private static double GetTypedBehaviorNumber(TradeRow row, BehaviorFilter behaviorFilter, AetheriaRuntimeBehaviorFieldMetadata field)
@ -353,22 +359,22 @@ public class TradeMenu : MonoBehaviour
private sealed class TradeRow
{
public TradeRow(
ItemInstance item,
AetheriaRuntimeStationStockItem stock,
AetheriaRuntimeCatalogItem typedItem,
AetheriaRuntimeTradeItemProjection tradeProjection)
{
Item = item;
Stock = stock;
TypedItem = typedItem;
TradeProjection = tradeProjection;
}
public ItemInstance Item { get; }
public AetheriaRuntimeStationStockItem Stock { get; }
public AetheriaRuntimeCatalogItem TypedItem { get; }
public AetheriaRuntimeTradeItemProjection TradeProjection { get; }
public string ItemKey => Item?.ItemKey ?? "";
public string ItemKey => Stock?.ItemKey ?? "";
public string Name => !string.IsNullOrWhiteSpace(TypedItem?.Name) ? TypedItem.Name : "Unknown Item";
@ -376,6 +382,8 @@ public class TradeMenu : MonoBehaviour
public int Price => TradeProjection.Price;
public int OwnedQuantity => Stock?.OwnedQuantity ?? 0;
public string TierColorHex => TradeProjection.TierColorHex;
public int ShapeWidth => TypedItem != null && TypedItem.ShapeWidth > 0 ? TypedItem.ShapeWidth : 0;
@ -410,52 +418,303 @@ public class TradeMenu : MonoBehaviour
{
if (CreditsLabel != null)
{
CreditsLabel.text = GameManager.Credits.ToString("N0");
CreditsLabel.text = ResolveStationRefit()?.Credits.ToString("N0") ?? "0";
}
}
private void Buy(CraftedItemInstance item)
private void Buy(TradeRow row, int quantity)
{
var typedItem = FindTypedTradeItem(item);
if (typedItem == null)
if (row?.TypedItem == null || row.Stock == null)
{
ShowUnableToBuy("Missing typed trade row!");
return;
}
var price = GetTypedTradePrice(item, typedItem);
var isShipHull = !string.IsNullOrWhiteSpace(typedItem?.HullType);
if (isShipHull &&
!string.Equals(typedItem.HullType, nameof(HullType.Ship), StringComparison.Ordinal))
var createsDockedShip = !string.IsNullOrWhiteSpace(row.TypedItem.HullType);
if (createsDockedShip &&
!string.Equals(row.TypedItem.HullType, nameof(HullType.Ship), StringComparison.Ordinal))
{
ShowUnableToBuy("Unsupported hull purchase!");
return;
}
GameManager.RequestTradePurchase(Inventory, _targetCargo, item, price, isShipHull);
RequestTradePurchase(row, quantity, createsDockedShip);
}
private void Buy(SimpleCommodity simpleCommodity, int quantity)
private void RequestTradePurchase(
TradeRow row,
int quantity,
bool createsDockedShip)
{
var typedItem = FindTypedTradeItem(simpleCommodity);
if (typedItem == null)
if (row?.Stock == null ||
string.IsNullOrWhiteSpace(row.ItemKey) ||
quantity <= 0 ||
row.Price < 0)
{
ShowUnableToBuy("Missing typed trade row!");
return;
}
var price = typedItem.Price;
GameManager.RequestTradePurchase(Inventory, _targetCargo, simpleCommodity, quantity, price);
var totalPrice = (long)quantity * row.Price;
if (totalPrice > int.MaxValue)
return;
var stationRefit = ResolveStationRefit();
var stationEntityKey = stationRefit?.DockParentEntityKey ?? "";
var stationCargoIndex = row.Stock.CargoBayIndex;
var sourcePosition = new int2(row.Stock.X, row.Stock.Y);
if (string.IsNullOrWhiteSpace(stationEntityKey) ||
stationCargoIndex < 0 ||
sourcePosition.x < 0 ||
sourcePosition.y < 0)
{
return;
}
var targetEntityKey = _targetCargoEntityKey ?? "";
var targetCargoIndex = _targetCargoIndex;
if (createsDockedShip)
{
if (!TryResolveCurrentDockingTargetEntityKey(out targetEntityKey))
{
return;
}
targetCargoIndex = -1;
}
else if (string.IsNullOrWhiteSpace(targetEntityKey) ||
targetCargoIndex < 0)
{
return;
}
var purchaseKind = createsDockedShip
? "docked_ship"
: row.TryGetTypedSimpleCommodityCategory(out _)
? "commodity"
: "crafted";
TrySubmitOperation(
operations => operations.TradePurchase(
purchaseKind,
row.ItemKey,
quantity,
row.Price,
(int)totalPrice,
stationEntityKey,
stationCargoIndex,
targetEntityKey,
targetCargoIndex,
sourcePosition.x,
sourcePosition.y,
createsDockedShip),
"trade purchase");
}
private int GetTypedTradePrice(CraftedItemInstance item, AetheriaRuntimeCatalogItem typedItem)
private bool TryResolveCurrentDockingTargetEntityKey(out string targetEntityKey)
{
return AetheriaRuntimeDaemonTradeItemQueries.ProjectTradeItem(
typedItem,
ProjectTradeItemCommit(item),
GameManager.ObservedTradeValueSettings()).Price;
targetEntityKey = "";
if (!TryResolveCurrentDocking(out var docking) ||
!docking.IsDocked ||
string.IsNullOrWhiteSpace(docking.DockParentEntityKey))
{
return false;
}
targetEntityKey = docking.DockParentEntityKey;
return true;
}
private bool TryResolveCurrentDocking(out AetheriaRuntimeCurrentDockingDocument docking)
{
docking = null;
try
{
docking = ResolveClient()
.CurrentDockingAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria current docking for trade menu: {ex.Message}");
return false;
}
return docking != null;
}
private AetheriaRuntimeStationRefitDocument ResolveStationRefit()
{
if (_stationRefit != null)
return _stationRefit;
try
{
_stationRefit = ResolveClient()
.StationRefitAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria station refit projection for trade menu: {ex.Message}");
return null;
}
return _stationRefit;
}
private void InvalidateStationRefit()
{
_stationRefit = null;
}
private bool TryResolveStationRefitCargoTarget(
string entityKey,
int cargoBayIndex,
out AetheriaRuntimeStationCargoTargetRow target)
{
target = null;
if (string.IsNullOrWhiteSpace(entityKey) ||
cargoBayIndex < 0)
{
return false;
}
target = (_cargoSelectorStationRefitTargets ?? Array.Empty<AetheriaRuntimeStationCargoTargetRow>())
.FirstOrDefault(option =>
option != null &&
string.Equals(option.EntityKey, entityKey, StringComparison.Ordinal) &&
option.BayIndex == cargoBayIndex);
return target != null;
}
private bool IsTargetCargoBayKey(string entityKey, int cargoBayIndex)
{
return string.Equals(_targetCargoEntityKey, entityKey, StringComparison.Ordinal) &&
_targetCargoIndex == cargoBayIndex;
}
private bool TrySubmitOperation(
Action<AetheriaControl> submit,
string label)
{
if (submit == null)
return false;
try
{
submit(ResolveClient().Control);
InvalidateStationRefit();
return true;
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to send Aetheria daemon trade {label} operation; operation not submitted: {ex.Message}");
return false;
}
}
private AetheriaClient ResolveClient()
{
var gameDataDirectory = new DirectoryInfo(Path.Combine(Application.dataPath, "..", "GameData"));
var stateBoot = AetheriaRuntimeStateBoot.Inspect(gameDataDirectory);
if (_client != null && string.Equals(_clientStatePath, stateBoot.StateFilePath, StringComparison.Ordinal))
return _client;
DisposeClient();
_client = AetheriaClient
.OpenLocalAsync(
gameDataDirectory,
"unity-trade",
"local",
pullOnOpen: true)
.GetAwaiter()
.GetResult();
_clientStatePath = stateBoot.StateFilePath;
return _client;
}
private void DisposeClient()
{
_client?.Dispose();
_client = null;
_clientStatePath = "";
_catalog = null;
_playerSettings = null;
_stationRefit = null;
}
private AetheriaRuntimeCatalogSnapshot ResolveCatalog()
{
if (_catalog != null)
return _catalog;
try
{
_catalog = ResolveClient().OpenRuntimeCatalog();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria runtime catalog for trade menu: {ex.Message}");
}
return _catalog;
}
private AetheriaRuntimePlayerSettingsSnapshot ResolvePlayerSettings()
{
if (_playerSettings != null)
return _playerSettings;
try
{
_playerSettings = ResolveClient()
.PlayerSettingsAsync()
.GetAwaiter()
.GetResult();
}
catch (Exception ex)
{
Debug.LogWarning($"Failed to read Aetheria player settings for trade menu: {ex.Message}");
}
return _playerSettings;
}
private string ResolveManufacturerName(AetheriaRuntimeCatalogItem item)
{
return ResolveCatalog()?.GetManufacturer(item)?.Name ?? "GameCult";
}
private string FormatValue(float value)
{
var settings = ResolvePlayerSettings();
var significantDigits = settings?.SignificantDigits ?? 3;
var magnitude = value == 0.0f ? 0 : (int)Math.Floor(Math.Log10(Math.Abs(value))) + 1;
var digits = significantDigits - magnitude;
if (digits < 0)
digits = 0;
var formatted = value.ToString($"N{digits}", CultureInfo.CurrentCulture);
var separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
var decimalSeparator = Convert.ToChar(separator);
return formatted.Contains(separator)
? formatted.TrimEnd('0').TrimEnd(decimalSeparator)
: formatted;
}
private string FormatTemperature(float value)
{
var unit = ResolvePlayerSettings()?.TemperatureUnit ?? nameof(TemperatureUnit.Celsius);
if (string.Equals(unit, nameof(TemperatureUnit.Kelvin), StringComparison.OrdinalIgnoreCase))
return $"{FormatValue(value)} K";
if (string.Equals(unit, nameof(TemperatureUnit.Fahrenheit), StringComparison.OrdinalIgnoreCase))
return $"{FormatValue(value * (9f / 5) - 459.67f)} F";
return $"{FormatValue(value - 273.15f)} C";
}
private void ShowUnableToBuy(string reason)
@ -466,18 +725,18 @@ public class TradeMenu : MonoBehaviour
Dialog.MoveToCursor();
}
private void ShowBuyQuantityDialog(string itemName, int price, SimpleCommodity simpleCommodity)
private void ShowBuyQuantityDialog(TradeRow row)
{
int quantity = 1;
Dialog.Clear();
Dialog.Title.text = $"Buying {itemName}";
Dialog.Title.text = $"Buying {row?.Name ?? "Unknown Item"}";
Dialog.AddField(
"Quantity",
() => quantity,
q => quantity = q);
Dialog.Show(() =>
{
Buy(simpleCommodity, quantity);
Buy(row, quantity);
Populate();
});
Dialog.MoveToCursor();
@ -523,13 +782,13 @@ public class TradeMenu : MonoBehaviour
AetheriaEveUnitySurfaceHost.Hide(_tradeItemSurfaceDocument);
}
private static AetheriaRuntimeTradeItemDetailsSurfaceState ProjectTradeItemDetailsSurface(AetheriaRuntimeCatalogItem item)
private AetheriaRuntimeTradeItemDetailsSurfaceState ProjectTradeItemDetailsSurface(AetheriaRuntimeCatalogItem item)
{
return AetheriaRuntimeTradeItemDetailsSurfaceBuilder.Project(
item,
ActionGameManager.RuntimeCatalog?.GetManufacturer(item)?.Name ?? "GameCult",
ActionGameManager.RuntimePlayerSettings.Format,
ActionGameManager.RuntimePlayerSettings.FormatTemperature);
ResolveManufacturerName(item),
FormatValue,
FormatTemperature);
}
void Start()
@ -978,27 +1237,33 @@ public class TradeMenu : MonoBehaviour
private AetheriaRuntimeTradeCargoSelectorSurfaceProjection ProjectTradeCargoSelectorSurface()
{
var targets = new List<AetheriaRuntimeTradeCargoProjectionOption>();
if (GameManager.TryGetObservedDockingBay(out var dockingBay))
var stationRefit = ResolveStationRefit();
if (stationRefit?.IsDocked == true &&
!string.IsNullOrWhiteSpace(stationRefit.DockParentEntityKey) &&
stationRefit.DockingBayIndex >= 0)
{
targets.Add(new AetheriaRuntimeTradeCargoProjectionOption(
AetheriaRuntimeTradeCargoTargetKind.DockingBay,
"Docking Bay",
isCurrent: _targetCargo == dockingBay));
stationRefit.DockParentEntityKey,
bayIndex: stationRefit.DockingBayIndex,
isCurrent: IsTargetCargoBayKey(stationRefit.DockParentEntityKey, stationRefit.DockingBayIndex)));
}
targets.AddRange(GameManager.ObservedAvailableEntities()
.OfType<Ship>()
.Where(ship => ship.IsPlayerShip)
.SelectMany((ship, shipIndex) => ship.CargoBays.Select((cargoBay, bayIndex) =>
new AetheriaRuntimeTradeCargoProjectionOption(
AetheriaRuntimeTradeCargoTargetKind.ShipBay,
$"{ship.Name} Bay {bayIndex + 1}",
shipIndex,
bayIndex,
_targetCargo == cargoBay))));
_cargoSelectorStationRefitTargets = (stationRefit?.CargoTargets ??
Array.Empty<AetheriaRuntimeStationCargoTargetRow>())
.ToArray();
targets.AddRange(_cargoSelectorStationRefitTargets
.Select(target => new AetheriaRuntimeTradeCargoProjectionOption(
target.Kind,
target.Label,
target.EntityKey,
target.TargetIndex,
target.BayIndex,
IsTargetCargoBayKey(target.EntityKey, target.BayIndex))));
return AetheriaRuntimeTradeCargoSelectorSurfaceBuilder.Project(
TargetCargoLabel.text ?? "",
_targetCargoLabel ?? "",
targets,
DateTime.UtcNow.ToString("O"));
}
@ -1008,34 +1273,32 @@ public class TradeMenu : MonoBehaviour
switch (selection.Kind)
{
case AetheriaRuntimeTradeCargoTargetKind.DockingBay:
if (GameManager.TryGetObservedDockingBay(out var dockingBay))
if (TryResolveStationRefitCargoTarget(selection.EntityKey, selection.BayIndex, out var target) &&
target.Kind == AetheriaRuntimeTradeCargoTargetKind.DockingBay)
{
_targetCargo = dockingBay;
TargetCargoLabel.text = selection.Label;
SetTargetCargo(selection.EntityKey, selection.BayIndex, selection.Label);
}
return;
case AetheriaRuntimeTradeCargoTargetKind.ShipBay:
var ships = GameManager.ObservedAvailableEntities()
.OfType<Ship>()
.Where(ship => ship.IsPlayerShip)
.ToArray();
if (selection.ShipIndex >= 0 &&
selection.ShipIndex < ships.Length &&
selection.BayIndex >= 0 &&
selection.BayIndex < ships[selection.ShipIndex].CargoBays.Count)
if (TryResolveStationRefitCargoTarget(selection.EntityKey, selection.BayIndex, out target) &&
target.Kind == AetheriaRuntimeTradeCargoTargetKind.ShipBay &&
target.TargetIndex == selection.ShipIndex)
{
_targetCargo = ships[selection.ShipIndex].CargoBays[selection.BayIndex];
TargetCargoLabel.text = selection.Label;
SetTargetCargo(target.EntityKey, selection.BayIndex, selection.Label);
}
return;
}
}
private int CountAvailablePlayerShips(string itemKey)
private void SetTargetCargo(string entityKey, int cargoBayIndex, string label)
{
return GameManager.ObservedAvailableEntities()
.OfType<Ship>()
.Count(ship => ship.IsPlayerShip && ship.Hull?.ItemKey == itemKey);
_targetCargoEntityKey = entityKey ?? "";
_targetCargoIndex = cargoBayIndex;
_targetCargoLabel = string.IsNullOrWhiteSpace(label) ? "Docking Bay" : label;
if (TargetCargoLabel != null)
{
TargetCargoLabel.text = _targetCargoLabel;
}
}
private void OnDisable()
@ -1048,6 +1311,8 @@ public class TradeMenu : MonoBehaviour
private void OnDestroy()
{
DisposeClient();
if (_cargoSelectorSurfaceDocument != null)
{
AetheriaEveUnitySurfaceHost.DestroyDocument(_cargoSelectorSurfaceDocument);

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