From 7a7000f2021c8c9babb6d399988dea206b747479 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 29 Jun 2026 04:02:45 +0100 Subject: [PATCH] Move loadout template access onto run checkpoints --- Aetheria.State.Verify/Program.cs | 72 +++--- Assets/Scripts/UI/Menu/InventoryPanel.cs | 9 +- GameCult.Aetheria.State.Unity.csproj | 1 - .../AetheriaRuntimeDaemonOperations.cs | 3 +- ...AetheriaRuntimeLoadoutSnapshotProjector.cs | 240 ------------------ ...riaRuntimeLoadoutSnapshotProjector.cs.meta | 2 - .../AetheriaRuntimeSnapshotDocuments.cs | 224 ++++++++++++++++ 7 files changed, 272 insertions(+), 279 deletions(-) delete mode 100644 Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeLoadoutSnapshotProjector.cs delete mode 100644 Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeLoadoutSnapshotProjector.cs.meta diff --git a/Aetheria.State.Verify/Program.cs b/Aetheria.State.Verify/Program.cs index d7232dd37..0ba99d794 100644 --- a/Aetheria.State.Verify/Program.cs +++ b/Aetheria.State.Verify/Program.cs @@ -17868,6 +17868,12 @@ static void RequireInventoryLoadoutSaveRequestAuthority(string root) var runtimeStateMapperPath = Path.Combine(root, "Aetheria.State", "AetheriaRuntimeStateMapper.cs"); var inventoryPanelPath = Path.Combine(root, "Assets", "Scripts", "UI", "Menu", "InventoryPanel.cs"); var loadoutProjectorPath = Path.Combine(root, "Assets", "Scripts", "ServerShared", "AetheriaRuntimeLoadoutProjector.cs"); + var snapshotDocumentsPath = Path.Combine( + root, + "Packages", + "org.gamecult.aetheria.state", + "Runtime", + "AetheriaRuntimeSnapshotDocuments.cs"); var loadoutSnapshotProjectorPath = Path.Combine( root, "Packages", @@ -17890,7 +17896,7 @@ static void RequireInventoryLoadoutSaveRequestAuthority(string root) "Legacy AetheriaRuntimeLoadoutProjector must stay deleted; loadout-template saves should compose typed commits from managed daemon-frame documents."); } - var requiredFiles = new[] { eveCommandDocumentPath, loadoutCommandsPath, eveBridgePath, runtimeStateMapperPath, inventoryPanelPath, loadoutSnapshotProjectorPath, clientStatePath, dragSessionPath, gameplaySceneWiringPath }; + var requiredFiles = new[] { eveCommandDocumentPath, loadoutCommandsPath, eveBridgePath, runtimeStateMapperPath, inventoryPanelPath, snapshotDocumentsPath, clientStatePath, dragSessionPath, gameplaySceneWiringPath }; var missingFiles = requiredFiles.Where(path => !File.Exists(path)).ToArray(); if (missingFiles.Length > 0) { @@ -17904,7 +17910,7 @@ static void RequireInventoryLoadoutSaveRequestAuthority(string root) var eveBridge = File.ReadAllText(eveBridgePath); var runtimeStateMapper = File.ReadAllText(runtimeStateMapperPath); var inventoryPanel = File.ReadAllText(inventoryPanelPath); - var loadoutSnapshotProjector = File.ReadAllText(loadoutSnapshotProjectorPath); + var snapshotDocuments = File.ReadAllText(snapshotDocumentsPath); var clientState = File.ReadAllText(clientStatePath); var dragSession = File.ReadAllText(dragSessionPath); var gameplaySceneWiring = File.ReadAllText(gameplaySceneWiringPath); @@ -17965,8 +17971,8 @@ static void RequireInventoryLoadoutSaveRequestAuthority(string root) "RequestLoadoutTemplateSave(Entity entity)", "TryResolveEntityRecordKey(entity, out var targetEntityKey)", "CultMeshReactiveDocument _loadoutFrame", - "ProjectLoadoutTemplate(targetEntityKey)", - "AetheriaRuntimeLoadoutSnapshotProjector.ProjectLoadoutTemplate(", + "CreateLoadoutTemplate(targetEntityKey)", + ".CreateLoadoutTemplate(targetEntityKey ?? \"\")", ".Document().Reactive()", "_loadoutFrame?.Dispose()", ".Ui.SaveLoadoutTemplateAsync(loadout, \"unity-inventory\")" @@ -18006,51 +18012,59 @@ static void RequireInventoryLoadoutSaveRequestAuthority(string root) "InventoryPanel still asks an aggregate compatibility helper for loadout templates instead of caching the managed reactive daemon frame."); } - var requiredLoadoutSnapshotProjectorSymbols = new[] - { - "public static AetheriaRuntimeLoadoutTemplateCommit ProjectLoadoutTemplate(", - "AetheriaRuntimeRunCheckpointCommit run,", - "TryParseEntityKey(entityKey, out var zoneIndex, out var entityIndex)", - "ProjectLoadoutTemplate(run, zoneIndex, entityIndex)", - "ProjectEntityLoadout(entity, entities)" - }; - var missingLoadoutSnapshotProjectorSymbols = requiredLoadoutSnapshotProjectorSymbols - .Where(symbol => !loadoutSnapshotProjector.Contains(symbol, StringComparison.Ordinal)) - .ToArray(); - if (missingLoadoutSnapshotProjectorSymbols.Length > 0) + if (File.Exists(loadoutSnapshotProjectorPath)) { throw new InvalidOperationException( - "Loadout template save payloads must be composed from managed typed daemon frame documents: " + - string.Join(", ", missingLoadoutSnapshotProjectorSymbols)); + "AetheriaRuntimeLoadoutSnapshotProjector is dead access chaff; AetheriaRuntimeRunCheckpointCommit owns loadout-template creation and append."); } - if (loadoutSnapshotProjector.Contains("ProjectLoadoutTemplateAsync(", StringComparison.Ordinal) || - loadoutSnapshotProjector.Contains("AetheriaClientState state", StringComparison.Ordinal) || - loadoutSnapshotProjector.Contains(".Document().Reactive()", StringComparison.Ordinal) || - loadoutSnapshotProjector.Contains("frame.Current?.Run", StringComparison.Ordinal)) + var requiredRunCheckpointLoadoutSymbols = new[] + { + "public AetheriaRuntimeLoadoutTemplateCommit CreateLoadoutTemplate(string entityKey)", + "public AetheriaRuntimeLoadoutTemplateCommit CreateLoadoutTemplate(int zoneIndex, int entityIndex)", + "public string AppendLoadoutTemplateToZone(", + "TryParseEntityKey(entityKey, out var zoneIndex, out var entityIndex)", + "CreateLoadoutTemplate(zoneIndex, entityIndex)", + "CreateEntityLoadout(entity, entities)", + "AppendEntity(entities, template.RootEntity, template.Name)" + }; + var missingRunCheckpointLoadoutSymbols = requiredRunCheckpointLoadoutSymbols + .Where(symbol => !snapshotDocuments.Contains(symbol, StringComparison.Ordinal)) + .ToArray(); + if (missingRunCheckpointLoadoutSymbols.Length > 0) + { + throw new InvalidOperationException( + "Loadout template save payloads must be composed by the managed typed run checkpoint document: " + + string.Join(", ", missingRunCheckpointLoadoutSymbols)); + } + + if (snapshotDocuments.Contains("ProjectLoadoutTemplateAsync(", StringComparison.Ordinal) || + snapshotDocuments.Contains("AetheriaClientState state", StringComparison.Ordinal) || + snapshotDocuments.Contains(".Document().Reactive()", StringComparison.Ordinal) || + snapshotDocuments.Contains("frame.Current?.Run", StringComparison.Ordinal)) { throw new InvalidOperationException( "Loadout snapshot composition must not own managed document sampling; InventoryPanel already caches the reactive daemon frame."); } - if (loadoutSnapshotProjector.Contains("state.Daemon.LatestFrame.LatestAsync()", StringComparison.Ordinal)) + if (snapshotDocuments.Contains("state.Daemon.LatestFrame.LatestAsync()", StringComparison.Ordinal)) { throw new InvalidOperationException( "Loadout template save payloads still perform one-shot daemon frame reads instead of using a reactive typed frame document."); } - if (loadoutSnapshotProjector.Contains("state.Daemon.LatestFrame.ReactiveAsync", StringComparison.Ordinal) || - loadoutSnapshotProjector.Contains("state.LatestFrame.ReactiveAsync", StringComparison.Ordinal) || - loadoutSnapshotProjector.Contains(".ObserveDaemonFrame()", StringComparison.Ordinal) || - loadoutSnapshotProjector.Contains(".ReactiveDaemonFrame()", StringComparison.Ordinal)) + if (snapshotDocuments.Contains("state.Daemon.LatestFrame.ReactiveAsync", StringComparison.Ordinal) || + snapshotDocuments.Contains("state.LatestFrame.ReactiveAsync", StringComparison.Ordinal) || + snapshotDocuments.Contains(".ObserveDaemonFrame()", StringComparison.Ordinal) || + snapshotDocuments.Contains(".ReactiveDaemonFrame()", StringComparison.Ordinal)) { throw new InvalidOperationException( "Loadout template save payloads must use generic AetheriaClientState reactive typed document access instead of named wrappers or raw handle walks."); } if (clientState.Contains("ReactiveLoadoutSnapshotProjector", StringComparison.Ordinal) || - loadoutSnapshotProjector.Contains("AetheriaRuntimeReactiveLoadoutSnapshotProjector", StringComparison.Ordinal) || - loadoutSnapshotProjector.Contains("ProjectLoadoutTemplate(string entityKey)", StringComparison.Ordinal)) + snapshotDocuments.Contains("AetheriaRuntimeReactiveLoadoutSnapshotProjector", StringComparison.Ordinal) || + inventoryPanel.Contains("ProjectLoadoutTemplate(string targetEntityKey)", StringComparison.Ordinal)) { throw new InvalidOperationException( "Loadout template save payloads must not recreate aggregate reactive projector wrappers; cache or sample the managed typed daemon frame document directly."); diff --git a/Assets/Scripts/UI/Menu/InventoryPanel.cs b/Assets/Scripts/UI/Menu/InventoryPanel.cs index a13e570d4..39e9736e1 100644 --- a/Assets/Scripts/UI/Menu/InventoryPanel.cs +++ b/Assets/Scripts/UI/Menu/InventoryPanel.cs @@ -1081,7 +1081,7 @@ private void Update() try { var client = ResolveClient(); - var loadout = ProjectLoadoutTemplate(targetEntityKey); + var loadout = CreateLoadoutTemplate(targetEntityKey); if (loadout?.RootEntity == null || string.IsNullOrWhiteSpace(loadout.RootEntity.Hull?.ItemKey ?? "")) return; @@ -1532,12 +1532,11 @@ private void Update() return _stationRefit?.Current; } - private AetheriaRuntimeLoadoutTemplateCommit ProjectLoadoutTemplate(string targetEntityKey) + private AetheriaRuntimeLoadoutTemplateCommit CreateLoadoutTemplate(string targetEntityKey) { var frame = ResolveLoadoutFrame(); - return AetheriaRuntimeLoadoutSnapshotProjector.ProjectLoadoutTemplate( - frame?.Run ?? new AetheriaRuntimeRunCheckpointCommit(), - targetEntityKey ?? ""); + return (frame?.Run ?? new AetheriaRuntimeRunCheckpointCommit()) + .CreateLoadoutTemplate(targetEntityKey ?? ""); } private AetheriaRuntimeDaemonFrameDocument ResolveLoadoutFrame() diff --git a/GameCult.Aetheria.State.Unity.csproj b/GameCult.Aetheria.State.Unity.csproj index b9688c828..5af10d810 100644 --- a/GameCult.Aetheria.State.Unity.csproj +++ b/GameCult.Aetheria.State.Unity.csproj @@ -49,7 +49,6 @@ - diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs index 94824ca11..79c09dae5 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonOperations.cs @@ -902,8 +902,7 @@ namespace GameCult.Aetheria.State.Verse if (!TryParseEntityKey(command.TargetEntityKey, out var zoneIndex, out _)) return false; - var newEntityKey = AetheriaRuntimeLoadoutSnapshotProjector.AppendToZone( - run, + var newEntityKey = run.AppendLoadoutTemplateToZone( zoneIndex, command.TargetEntityKey, template); diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeLoadoutSnapshotProjector.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeLoadoutSnapshotProjector.cs deleted file mode 100644 index 066021312..000000000 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeLoadoutSnapshotProjector.cs +++ /dev/null @@ -1,240 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -#nullable enable - -namespace GameCult.Aetheria.State.Verse -{ - public static class AetheriaRuntimeLoadoutSnapshotProjector - { - public static AetheriaRuntimeLoadoutTemplateCommit ProjectLoadoutTemplate( - AetheriaRuntimeRunCheckpointCommit run, - string entityKey) - { - if (run == null || - !TryParseEntityKey(entityKey, out var zoneIndex, out var entityIndex)) - { - return new AetheriaRuntimeLoadoutTemplateCommit(); - } - - return ProjectLoadoutTemplate(run, zoneIndex, entityIndex); - } - - public static AetheriaRuntimeLoadoutTemplateCommit ProjectLoadoutTemplate( - AetheriaRuntimeRunCheckpointCommit run, - int zoneIndex, - int entityIndex) - { - var zone = (run?.Zones ?? Array.Empty()) - .FirstOrDefault(candidate => candidate != null && candidate.ZoneIndex == zoneIndex); - var entities = zone?.Entities ?? Array.Empty(); - var entity = entities.FirstOrDefault(candidate => candidate != null && candidate.EntityIndex == entityIndex); - if (entity == null) - return new AetheriaRuntimeLoadoutTemplateCommit(); - - return new AetheriaRuntimeLoadoutTemplateCommit - { - Name = entity.Name ?? "", - OwnerPlayerKey = "global:aetheria.player_settings.v1", - RootEntity = ProjectEntityLoadout(entity, entities) - }; - } - - public static string AppendToZone( - AetheriaRuntimeRunCheckpointCommit run, - int zoneIndex, - string parentEntityKey, - AetheriaRuntimeLoadoutTemplateCommit template) - { - if (run == null || template?.RootEntity == null) - return ""; - - var zones = (run.Zones ?? Array.Empty()).ToArray(); - var zone = zones.FirstOrDefault(candidate => candidate != null && candidate.ZoneIndex == zoneIndex); - if (zone == null) - return ""; - - var entities = (zone.Entities ?? Array.Empty()).ToList(); - var parentIndex = TryParseEntityKey(parentEntityKey, out var parentZoneIndex, out var parsedParentIndex) && - parentZoneIndex == zoneIndex - ? parsedParentIndex - : -1; - var rootIndex = AppendEntity(entities, template.RootEntity, template.Name); - - if (parentIndex >= 0 && parentIndex < entities.Count) - { - var children = (entities[parentIndex].ChildEntityIndices ?? Array.Empty()).ToList(); - if (!children.Contains(rootIndex)) - children.Add(rootIndex); - entities[parentIndex].ChildEntityIndices = children.ToArray(); - } - - zone.Entities = entities.ToArray(); - run.Zones = zones; - return EntityKey(run.RunId, zoneIndex, rootIndex); - } - - private static AetheriaRuntimeEntityLoadoutCommit ProjectEntityLoadout( - AetheriaRuntimeEntitySnapshotCommit entity, - IReadOnlyList zoneEntities) - { - var childIndices = (entity.ChildEntityIndices ?? Array.Empty()) - .Where(index => index >= 0) - .ToArray(); - var children = childIndices - .Select(index => zoneEntities.FirstOrDefault(candidate => candidate != null && candidate.EntityIndex == index)) - .Where(child => child != null) - .Select(child => ProjectEntityLoadout(child!, zoneEntities)) - .ToArray(); - var childIndexByEntityIndex = childIndices - .Select((entityIndex, childIndex) => new { entityIndex, childIndex }) - .ToDictionary(pair => pair.entityIndex, pair => pair.childIndex); - - return new AetheriaRuntimeEntityLoadoutCommit - { - Name = entity.Name ?? "", - Kind = string.IsNullOrWhiteSpace(entity.Kind) ? "ship" : entity.Kind, - FactionKey = entity.FactionKey ?? "", - Hull = new AetheriaRuntimeLoadoutItemCommit - { - ItemKey = entity.HullItemKey ?? "", - Quality = 1.0, - Durability = 1.0, - Quantity = 1, - Enabled = true - }, - Equipment = CloneSlots(entity.Equipment), - CargoBays = CloneSlots(entity.CargoBays), - DockingBays = CloneSlots(entity.DockingBays), - CargoContents = CloneCargo(entity.CargoContents), - DockingBayContents = CloneCargo(entity.DockingBayContents), - DockingBayAssignments = (entity.DockingBayAssignments ?? Array.Empty()) - .Select(index => childIndexByEntityIndex.TryGetValue(index, out var childIndex) ? childIndex : -1) - .ToArray(), - WeaponGroups = (entity.WeaponGroups ?? Array.Empty>()) - .Select(group => (IReadOnlyList)(group ?? Array.Empty()).ToArray()) - .ToArray(), - Children = children - }; - } - - private static int AppendEntity( - List entities, - AetheriaRuntimeEntityLoadoutCommit loadout, - string templateName) - { - var entityIndex = entities.Count; - var entity = new AetheriaRuntimeEntitySnapshotCommit - { - EntityIndex = entityIndex, - Name = string.IsNullOrWhiteSpace(loadout.Name) ? templateName ?? "" : loadout.Name, - Kind = string.IsNullOrWhiteSpace(loadout.Kind) ? "ship" : loadout.Kind, - DirectionX = 0, - DirectionY = 1, - IsActive = true, - HullItemKey = loadout.Hull?.ItemKey ?? "", - FactionKey = loadout.FactionKey ?? "", - Equipment = CloneSlots(loadout.Equipment), - CargoBays = CloneSlots(loadout.CargoBays), - DockingBays = CloneSlots(loadout.DockingBays), - CargoContents = CloneCargo(loadout.CargoContents), - DockingBayContents = CloneCargo(loadout.DockingBayContents), - DockingBayAssignments = (loadout.DockingBayAssignments ?? Array.Empty()).ToArray(), - WeaponGroups = (loadout.WeaponGroups ?? Array.Empty>()) - .Select(group => (IReadOnlyList)(group ?? Array.Empty()).ToArray()) - .ToArray(), - TargetEntityIndex = -1, - ShutdownPerformance = 0.25 - }; - entities.Add(entity); - - var childIndices = new List(); - foreach (var child in loadout.Children ?? Array.Empty()) - { - if (child == null) - continue; - childIndices.Add(AppendEntity(entities, child, "")); - } - - entity.ChildEntityIndices = childIndices.ToArray(); - return entityIndex; - } - - private static AetheriaRuntimeLoadoutItemSlotCommit[] CloneSlots( - IReadOnlyList? slots) - { - return (slots ?? Array.Empty()) - .Where(slot => slot != null) - .Select(CloneSlot) - .ToArray(); - } - - private static AetheriaRuntimeCargoBayLoadoutCommit[] CloneCargo( - IReadOnlyList? cargo) - { - return (cargo ?? Array.Empty()) - .Select(bay => new AetheriaRuntimeCargoBayLoadoutCommit - { - Items = CloneSlots(bay?.Items) - }) - .ToArray(); - } - - private static AetheriaRuntimeLoadoutItemSlotCommit CloneSlot(AetheriaRuntimeLoadoutItemSlotCommit slot) - { - return new AetheriaRuntimeLoadoutItemSlotCommit - { - X = slot.X, - Y = slot.Y, - Item = CloneItem(slot.Item) - }; - } - - private static AetheriaRuntimeLoadoutItemCommit CloneItem(AetheriaRuntimeLoadoutItemCommit? item) - { - return new AetheriaRuntimeLoadoutItemCommit - { - ItemKey = item?.ItemKey ?? "", - Quality = item?.Quality ?? 1.0, - Durability = item?.Durability ?? 1.0, - Quantity = item?.Quantity ?? 1, - Enabled = item?.Enabled ?? true, - OverrideShutdown = item?.OverrideShutdown ?? false, - Temperature = item?.Temperature ?? 0 - }; - } - - private static string EntityKey(string runId, int zoneIndex, int entityIndex) - { - return $"global:aetheria.run_state.{(string.IsNullOrWhiteSpace(runId) ? "local" : runId)}.zone.{zoneIndex}.entity.{entityIndex}.v1"; - } - - private static bool TryParseEntityKey(string entityKey, out int zoneIndex, out int entityIndex) - { - zoneIndex = -1; - entityIndex = -1; - if (string.IsNullOrWhiteSpace(entityKey)) - return false; - - var parts = entityKey.Split('.'); - for (var i = 0; i < parts.Length - 1; i++) - { - if (string.Equals(parts[i], "zone", StringComparison.Ordinal) && - int.TryParse(parts[i + 1], out zoneIndex)) - { - continue; - } - - if (string.Equals(parts[i], "entity", StringComparison.Ordinal) && - int.TryParse(parts[i + 1], out entityIndex)) - { - continue; - } - } - - return zoneIndex >= 0 && entityIndex >= 0; - } - } - -} diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeLoadoutSnapshotProjector.cs.meta b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeLoadoutSnapshotProjector.cs.meta deleted file mode 100644 index 444a5d642..000000000 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeLoadoutSnapshotProjector.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 3eb83163e4f8b4447a733c13bc719416 \ No newline at end of file diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs index f92ec091b..c062c0193 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using MessagePack; #nullable enable @@ -192,6 +193,229 @@ namespace GameCult.Aetheria.State.Verse [Key(11)] public int Credits { get; set; } + + public AetheriaRuntimeLoadoutTemplateCommit CreateLoadoutTemplate(string entityKey) + { + return TryParseEntityKey(entityKey, out var zoneIndex, out var entityIndex) + ? CreateLoadoutTemplate(zoneIndex, entityIndex) + : new AetheriaRuntimeLoadoutTemplateCommit(); + } + + public AetheriaRuntimeLoadoutTemplateCommit CreateLoadoutTemplate(int zoneIndex, int entityIndex) + { + var zone = (Zones ?? Array.Empty()) + .FirstOrDefault(candidate => candidate != null && candidate.ZoneIndex == zoneIndex); + var entities = zone?.Entities ?? Array.Empty(); + var entity = entities.FirstOrDefault(candidate => candidate != null && candidate.EntityIndex == entityIndex); + if (entity == null) + return new AetheriaRuntimeLoadoutTemplateCommit(); + + return new AetheriaRuntimeLoadoutTemplateCommit + { + Name = entity.Name ?? "", + OwnerPlayerKey = "global:aetheria.player_settings.v1", + RootEntity = CreateEntityLoadout(entity, entities) + }; + } + + public string AppendLoadoutTemplateToZone( + int zoneIndex, + string parentEntityKey, + AetheriaRuntimeLoadoutTemplateCommit template) + { + if (template?.RootEntity == null) + return ""; + + var zones = (Zones ?? Array.Empty()).ToArray(); + var zone = zones.FirstOrDefault(candidate => candidate != null && candidate.ZoneIndex == zoneIndex); + if (zone == null) + return ""; + + var entities = (zone.Entities ?? Array.Empty()).ToList(); + var parentIndex = TryParseEntityKey(parentEntityKey, out var parentZoneIndex, out var parsedParentIndex) && + parentZoneIndex == zoneIndex + ? parsedParentIndex + : -1; + var rootIndex = AppendEntity(entities, template.RootEntity, template.Name); + + if (parentIndex >= 0 && parentIndex < entities.Count) + { + var children = (entities[parentIndex].ChildEntityIndices ?? Array.Empty()).ToList(); + if (!children.Contains(rootIndex)) + children.Add(rootIndex); + entities[parentIndex].ChildEntityIndices = children.ToArray(); + } + + zone.Entities = entities.ToArray(); + Zones = zones; + return EntityRecordKey(zoneIndex, rootIndex); + } + + public string EntityRecordKey(int zoneIndex, int entityIndex) + { + return EntityRecordKey(RunId, zoneIndex, entityIndex); + } + + public static string EntityRecordKey(string runId, int zoneIndex, int entityIndex) + { + return $"global:aetheria.run_state.{(string.IsNullOrWhiteSpace(runId) ? "local" : runId)}.zone.{zoneIndex}.entity.{entityIndex}.v1"; + } + + public static bool TryParseEntityKey(string entityKey, out int zoneIndex, out int entityIndex) + { + zoneIndex = -1; + entityIndex = -1; + if (string.IsNullOrWhiteSpace(entityKey)) + return false; + + var parts = entityKey.Split('.'); + for (var i = 0; i < parts.Length - 1; i++) + { + if (string.Equals(parts[i], "zone", StringComparison.Ordinal) && + int.TryParse(parts[i + 1], out zoneIndex)) + { + continue; + } + + if (string.Equals(parts[i], "entity", StringComparison.Ordinal) && + int.TryParse(parts[i + 1], out entityIndex)) + { + continue; + } + } + + return zoneIndex >= 0 && entityIndex >= 0; + } + + private static AetheriaRuntimeEntityLoadoutCommit CreateEntityLoadout( + AetheriaRuntimeEntitySnapshotCommit entity, + IReadOnlyList zoneEntities) + { + var childIndices = (entity.ChildEntityIndices ?? Array.Empty()) + .Where(index => index >= 0) + .ToArray(); + var children = childIndices + .Select(index => zoneEntities.FirstOrDefault(candidate => candidate != null && candidate.EntityIndex == index)) + .Where(child => child != null) + .Select(child => CreateEntityLoadout(child!, zoneEntities)) + .ToArray(); + var childIndexByEntityIndex = childIndices + .Select((entityIndex, childIndex) => new { entityIndex, childIndex }) + .ToDictionary(pair => pair.entityIndex, pair => pair.childIndex); + + return new AetheriaRuntimeEntityLoadoutCommit + { + Name = entity.Name ?? "", + Kind = string.IsNullOrWhiteSpace(entity.Kind) ? "ship" : entity.Kind, + FactionKey = entity.FactionKey ?? "", + Hull = new AetheriaRuntimeLoadoutItemCommit + { + ItemKey = entity.HullItemKey ?? "", + Quality = 1.0, + Durability = 1.0, + Quantity = 1, + Enabled = true + }, + Equipment = CloneSlots(entity.Equipment), + CargoBays = CloneSlots(entity.CargoBays), + DockingBays = CloneSlots(entity.DockingBays), + CargoContents = CloneCargo(entity.CargoContents), + DockingBayContents = CloneCargo(entity.DockingBayContents), + DockingBayAssignments = (entity.DockingBayAssignments ?? Array.Empty()) + .Select(index => childIndexByEntityIndex.TryGetValue(index, out var childIndex) ? childIndex : -1) + .ToArray(), + WeaponGroups = (entity.WeaponGroups ?? Array.Empty>()) + .Select(group => (IReadOnlyList)(group ?? Array.Empty()).ToArray()) + .ToArray(), + Children = children + }; + } + + private static int AppendEntity( + List entities, + AetheriaRuntimeEntityLoadoutCommit loadout, + string templateName) + { + var entityIndex = entities.Count; + var entity = new AetheriaRuntimeEntitySnapshotCommit + { + EntityIndex = entityIndex, + Name = string.IsNullOrWhiteSpace(loadout.Name) ? templateName ?? "" : loadout.Name, + Kind = string.IsNullOrWhiteSpace(loadout.Kind) ? "ship" : loadout.Kind, + DirectionX = 0, + DirectionY = 1, + IsActive = true, + HullItemKey = loadout.Hull?.ItemKey ?? "", + FactionKey = loadout.FactionKey ?? "", + Equipment = CloneSlots(loadout.Equipment), + CargoBays = CloneSlots(loadout.CargoBays), + DockingBays = CloneSlots(loadout.DockingBays), + CargoContents = CloneCargo(loadout.CargoContents), + DockingBayContents = CloneCargo(loadout.DockingBayContents), + DockingBayAssignments = (loadout.DockingBayAssignments ?? Array.Empty()).ToArray(), + WeaponGroups = (loadout.WeaponGroups ?? Array.Empty>()) + .Select(group => (IReadOnlyList)(group ?? Array.Empty()).ToArray()) + .ToArray(), + TargetEntityIndex = -1, + ShutdownPerformance = 0.25 + }; + entities.Add(entity); + + var childIndices = new List(); + foreach (var child in loadout.Children ?? Array.Empty()) + { + if (child == null) + continue; + childIndices.Add(AppendEntity(entities, child, "")); + } + + entity.ChildEntityIndices = childIndices.ToArray(); + return entityIndex; + } + + private static AetheriaRuntimeLoadoutItemSlotCommit[] CloneSlots( + IReadOnlyList? slots) + { + return (slots ?? Array.Empty()) + .Where(slot => slot != null) + .Select(CloneSlot) + .ToArray(); + } + + private static AetheriaRuntimeCargoBayLoadoutCommit[] CloneCargo( + IReadOnlyList? cargo) + { + return (cargo ?? Array.Empty()) + .Select(bay => new AetheriaRuntimeCargoBayLoadoutCommit + { + Items = CloneSlots(bay?.Items) + }) + .ToArray(); + } + + private static AetheriaRuntimeLoadoutItemSlotCommit CloneSlot(AetheriaRuntimeLoadoutItemSlotCommit slot) + { + return new AetheriaRuntimeLoadoutItemSlotCommit + { + X = slot.X, + Y = slot.Y, + Item = CloneItem(slot.Item) + }; + } + + private static AetheriaRuntimeLoadoutItemCommit CloneItem(AetheriaRuntimeLoadoutItemCommit? item) + { + return new AetheriaRuntimeLoadoutItemCommit + { + ItemKey = item?.ItemKey ?? "", + Quality = item?.Quality ?? 1.0, + Durability = item?.Durability ?? 1.0, + Quantity = item?.Quantity ?? 1, + Enabled = item?.Enabled ?? true, + OverrideShutdown = item?.OverrideShutdown ?? false, + Temperature = item?.Temperature ?? 0 + }; + } } [MessagePackObject]