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

@ -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);