From 5e20a3f09aa6a80114dd5cca111928ac47aa9b30 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 17 Jul 2026 10:03:10 +0100 Subject: [PATCH] Persist playable regular sectors --- Aetheria.State.Daemon.Smoke/Program.cs | 92 ++++++++++++++ .../AetheriaDaemonRegularRunWriter.cs | 118 ++++++++++++++++++ .../AetheriaDaemonRegularTopologyGenerator.cs | 1 + .../AetheriaDaemonRunFactory.cs | 39 ++++++ .../AetheriaDaemonTutorialRunWriter.cs | 6 +- ...AetheriaDaemonTutorialWorldMaterializer.cs | 24 ++-- .../AetheriaDaemonZoneBodyGenerator.cs | 27 +++- .../AetheriaDaemonZoneGenerator.cs | 1 + Aetheria.State.Daemon/Program.cs | 51 ++++---- .../AetheriaRuntimeStateDocuments.cs | 3 + .../AetheriaRuntimeSnapshotDocuments.cs | 3 + docs/aetheria-perfect-machine-map.md | 21 +++- docs/original-game-migration-matrix.md | 2 +- docs/renderless-aetheria-architecture.md | 12 +- 14 files changed, 346 insertions(+), 54 deletions(-) create mode 100644 Aetheria.State.Daemon/AetheriaDaemonRegularRunWriter.cs create mode 100644 Aetheria.State.Daemon/AetheriaDaemonRunFactory.cs diff --git a/Aetheria.State.Daemon.Smoke/Program.cs b/Aetheria.State.Daemon.Smoke/Program.cs index e1c95d66f..193f1e9a6 100644 --- a/Aetheria.State.Daemon.Smoke/Program.cs +++ b/Aetheria.State.Daemon.Smoke/Program.cs @@ -39,6 +39,11 @@ else if (args.Contains("--regular-topology", StringComparer.Ordinal)) checks.RunRegularTopology(); Console.WriteLine("Daemon regular-sector topology smoke passed."); } +else if (args.Contains("--regular-run", StringComparer.Ordinal)) +{ + checks.RunRegularRun(); + Console.WriteLine("Daemon persisted regular-sector run smoke passed."); +} else if (args.Contains("--zone-bodies", StringComparer.Ordinal)) { checks.RunZoneBodies(); @@ -104,6 +109,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks public void RunTutorialTopology() => RunCheck(TutorialTopologyIsDeterministicConnectedAndRoleOwned); public void RunRegularTopology() => RunCheck(RegularTopologyOwnsFossilSectorStructure); + public void RunRegularRun() => RunCheck(RegularRunPersistsPlayableWorldTruth); public void RunZoneBodies() => RunCheck(GeneratedZoneBodiesPreserveFossilHierarchy); public void RunTutorialWorld() => RunCheck(TutorialWorldMaterializesEveryTopologyZone); public void RunTutorialMaterialization() => RunCheck(TutorialPopulationPreservesFossilEntityMechanics); @@ -245,6 +251,91 @@ internal sealed class AetheriaDaemonYmirSmokeChecks "regular topology, faction placement, boss placement, and names must be seed deterministic"); } + private static void RegularRunPersistsPlayableWorldTruth() + { + var tutorialCatalog = TutorialPopulationCatalog(out var factions); + var manufacturer = factions[0].CorporationKey; + foreach (var item in tutorialCatalog.Items) + item.ManufacturerKey = manufacturer; + var corporations = factions.Select((faction, index) => new AetheriaRuntimeCorporation( + faction.CorporationKey, + faction.Name, + faction.ShortName, + "", + $"names.{faction.ShortName}", + index < 2 ? "tutorial-ship-hull" : "", + 4, + 1, + [new AetheriaRuntimeCorporationAllegiance(manufacturer, 1)])).ToArray(); + var catalog = new AetheriaRuntimeCatalogSnapshot( + tutorialCatalog.Items.ToArray(), corporations, tutorialCatalog.NameFiles.ToArray()); + var root = Path.Combine(Path.GetTempPath(), $"aetheria-regular-run-{Guid.NewGuid():N}"); + var statePath = Path.Combine(root, "aetheria.cc"); + Directory.CreateDirectory(root); + try + { + string runKey; + using (var node = AetheriaStateNode.OpenAsync(statePath).GetAwaiter().GetResult()) + { + node.MutableDocument(AetheriaStateNode.PlayerSettingsKey) + .ReplaceAsync(new AetheriaPlayerSettings { TutorialPassed = true }) + .GetAwaiter().GetResult(); + var written = AetheriaDaemonRunFactory.WriteAsync( + node, + catalog, + "2026-07-17T00:00:00.0000000Z", + "regular-run-command", + new AetheriaDaemonRegularTopologySettings(24, 0.5f, 6, 2)) + .GetAwaiter().GetResult(); + runKey = written.RunKey; + var run = node.MutableDocument(new CultRecordKey(runKey)) + .ReadAsync().GetAwaiter().GetResult(); + var settings = node.MutableDocument(AetheriaStateNode.PlayerSettingsKey) + .ReadAsync().GetAwaiter().GetResult(); + Require(run != null && !run.IsTutorial && + run.GameMode == AetheriaGameSessionState.AetheriaMode && + run.ZoneKeys.Length == 24 && run.ExitZoneIndex >= 0 && + run.CurrentZoneIndex == run.EntranceZoneIndex, + "regular writer must persist an Aetheria-mode sector rather than a Terminus scenario"); + RequireEqual(AetheriaDaemonRunFactory.StableSeed("regular-run-command"), run!.GenerationSeed, + "accepted New Game identity must deterministically own regular-sector generation"); + Require(written.SessionMode == AetheriaGameSessionState.AetheriaMode && + settings?.ActiveRunKey == runKey && settings.TutorialPassed, + "regular writer must select the new sector without erasing tutorial completion"); + Require(run!.AgentTasks.Length > 0 && run.AgentTasks.All(task => + task.TaskType == AetheriaRuntimeAgentTaskTypes.Patrol && + task.Status == AetheriaRuntimeAgentTaskStatuses.Assigned), + "regular population must persist autonomous patrol inhabitants"); + Require(run.ZoneKeys.All(key => key.Contains(run.RunId, StringComparison.Ordinal)), + "regular zone records must be namespaced by the generated run identity"); + var entrance = node.MutableDocument( + new CultRecordKey(run.ZoneKeys[run.EntranceZoneIndex])) + .ReadAsync().GetAwaiter().GetResult(); + Require(entrance != null && entrance.EntityKeys.Contains(run.CurrentEntityKey) && + entrance.EntityKeys.All(key => !key.Contains("tutorial", StringComparison.OrdinalIgnoreCase)), + "regular entrance must contain the controlled starter under regular identities"); + var starter = node.MutableDocument( + new CultRecordKey(run.CurrentEntityKey)) + .ReadAsync().GetAwaiter().GetResult(); + Require(starter != null && starter.IsActive && + !string.IsNullOrWhiteSpace(starter.HullItemKey) && + starter.Equipment.Length > 0 && starter.LoadoutGeneration.Selections.Length > 0, + "regular entrance must persist a generated, equipped, controllable starter ship"); + } + + using var reopened = AetheriaStateNode.OpenAsync(statePath).GetAwaiter().GetResult(); + var restored = reopened.MutableDocument(new CultRecordKey(runKey)) + .ReadAsync().GetAwaiter().GetResult(); + Require(restored != null && restored.GameMode == AetheriaGameSessionState.AetheriaMode && + restored.ZoneKeys.Length == 24 && !string.IsNullOrWhiteSpace(restored.CurrentEntityKey), + "regular sector selection and controlled identity must survive a hard CultCache reopen"); + } + finally + { + if (Directory.Exists(root)) Directory.Delete(root, recursive: true); + } + } + private static void TutorialPopulationPreservesFossilEntityMechanics() { var catalog = TutorialPopulationCatalog(out var factions); @@ -673,6 +764,7 @@ internal sealed class AetheriaDaemonYmirSmokeChecks PositiveGravityDepthAttractsAndProjectsAsAWell, TutorialTopologyIsDeterministicConnectedAndRoleOwned, RegularTopologyOwnsFossilSectorStructure, + RegularRunPersistsPlayableWorldTruth, GeneratedZoneBodiesPreserveFossilHierarchy, TutorialWorldMaterializesEveryTopologyZone, GeneratedOrbitsAdvanceOrbitalWorldTruth, diff --git a/Aetheria.State.Daemon/AetheriaDaemonRegularRunWriter.cs b/Aetheria.State.Daemon/AetheriaDaemonRegularRunWriter.cs new file mode 100644 index 000000000..b0d01aceb --- /dev/null +++ b/Aetheria.State.Daemon/AetheriaDaemonRegularRunWriter.cs @@ -0,0 +1,118 @@ +using Aetheria.State; +using Aetheria.State.Documents; +using GameCult.Aetheria.State.Verse; +using GameCult.Caching; + +public static class AetheriaDaemonRegularRunWriter +{ + public static async Task WriteAsync( + AetheriaStateNode node, + AetheriaRuntimeCatalogSnapshot catalog, + string now, + uint generationSeed, + AetheriaDaemonRegularTopologySettings? topologySettings = null) + { + if (node == null) throw new ArgumentNullException(nameof(node)); + if (catalog == null) throw new ArgumentNullException(nameof(catalog)); + if (generationSeed == 0) throw new ArgumentOutOfRangeException(nameof(generationSeed)); + + var factions = AetheriaDaemonRegularTopologyGenerator.ResolveFossilFactions(catalog); + var world = AetheriaDaemonTutorialWorldGenerator.GenerateRegular( + factions, generationSeed, topologySettings); + var materialized = AetheriaDaemonTutorialWorldMaterializer.Materialize( + world, factions, catalog, isPrelude: false, identityPrefix: "regular"); + var runId = $"sector-{generationSeed:x8}"; + var runKey = RunKey(runId); + var corporationIndices = (catalog.Corporations ?? Array.Empty()) + .Select((corporation, index) => (corporation.CorporationKey, index)) + .Where(value => !string.IsNullOrWhiteSpace(value.CorporationKey)) + .ToDictionary(value => value.CorporationKey, value => value.index, StringComparer.Ordinal); + var zoneKeys = materialized.Topology.Zones + .OrderBy(zone => zone.ZoneIndex) + .Select(zone => ZoneKey(runId, zone.ZoneIndex)) + .ToArray(); + var playerEntityKey = EntityKey(runId, materialized.PlayerZoneIndex, materialized.PlayerEntityIndex); + + foreach (var zone in materialized.Zones.Values.OrderBy(zone => zone.Topology.ZoneIndex)) + { + var entityKeys = Enumerable.Range(0, zone.Entities.Length) + .Select(index => EntityKey(runId, zone.Topology.ZoneIndex, index)) + .ToArray(); + await node.MutableDocument(new CultRecordKey(ZoneKey(runId, zone.Topology.ZoneIndex))) + .ReplaceAsync(new AetheriaZoneState + { + Name = zone.Topology.Name, + Position = new AetheriaVector2 { X = zone.Topology.X, Y = zone.Topology.Y }, + AdjacentZoneIndices = zone.Topology.AdjacentZoneIndices.ToArray(), + FactionIndices = zone.Topology.FactionKeys.Select(key => corporationIndices[key]).ToArray(), + OwnerFactionIndex = string.IsNullOrWhiteSpace(zone.Topology.OwnerFactionKey) + ? -1 + : corporationIndices[zone.Topology.OwnerFactionKey], + EntityKeys = entityKeys, + Orbits = zone.Orbits, + Bodies = zone.CelestialPlan.Bodies, + GravityTerrainRadius = zone.CelestialPlan.Radius, + GravityTerrainDepth = zone.CelestialPlan.GravityTerrainDepth, + GravityTerrainDepthExponent = zone.CelestialPlan.GravityTerrainDepthExponent, + GravityTerrainBoundaryFog = zone.CelestialPlan.GravityTerrainBoundaryFog, + GravityTerrainWaveFrequency = 1, + DroppedPickups = [], + NextPickupIndex = 0 + }).ConfigureAwait(false); + for (var entityIndex = 0; entityIndex < zone.Entities.Length; entityIndex++) + { + await node.MutableDocument(new CultRecordKey(entityKeys[entityIndex])) + .ReplaceAsync(zone.Entities[entityIndex]) + .ConfigureAwait(false); + } + } + + await node.MutableDocument(new CultRecordKey(runKey)).ReplaceAsync(new AetheriaRunState + { + RunId = runId, + IsTutorial = false, + GameMode = AetheriaGameSessionState.AetheriaMode, + EntranceZoneIndex = materialized.Topology.EntranceZoneIndex, + ExitZoneIndex = materialized.Topology.ExitZoneIndex, + CurrentZoneIndex = materialized.PlayerZoneIndex, + DiscoveredZoneIndices = materialized.Topology.DiscoveredZoneIndices.ToArray(), + ZoneKeys = zoneKeys, + FactionRelationships = materialized.Topology.HomeZoneByFactionKey.Keys + .Select(key => new AetheriaFactionRelationshipState + { + FactionKey = key, + Relationship = "Neutral", + Standing = 0 + }) + .ToArray(), + GenerationSeed = generationSeed, + CurrentEntityKey = playerEntityKey, + LifecyclePhase = AetheriaRuntimeRunLifecycle.Active, + TerminalFrameId = -1, + AgentTasks = materialized.Zones.Values + .OrderBy(zone => zone.Topology.ZoneIndex) + .SelectMany(zone => zone.AgentTasks) + .ToArray(), + UpdatedAtUtc = now + }).ConfigureAwait(false); + + var settings = await node.MutableDocument(AetheriaStateNode.PlayerSettingsKey) + .ReadAsync().ConfigureAwait(false) ?? new AetheriaPlayerSettings(); + settings.ActiveRunKey = runKey; + settings.PlayerName = string.IsNullOrWhiteSpace(settings.PlayerName) ? "Pilot" : settings.PlayerName; + settings.LastUpdatedAtUtc = now; + await node.MutableDocument(AetheriaStateNode.PlayerSettingsKey) + .ReplaceAsync(settings).ConfigureAwait(false); + await node.FlushAsync().ConfigureAwait(false); + return new AetheriaDaemonWrittenRun(runId, runKey, playerEntityKey, false) + { + SessionMode = AetheriaGameSessionState.AetheriaMode + }; + } + + public static string RunKey(string runId) => $"global:aetheria.run_state.{runId}.v1"; + public static string ZoneKey(string runId, int zoneIndex) => + $"global:aetheria.zone_state.{runId}.{zoneIndex}.v1"; + public static string EntityKey(string runId, int zoneIndex, int entityIndex) => + $"global:aetheria.run_state.{runId}.zone.{zoneIndex}.entity.{entityIndex}.v1"; +} diff --git a/Aetheria.State.Daemon/AetheriaDaemonRegularTopologyGenerator.cs b/Aetheria.State.Daemon/AetheriaDaemonRegularTopologyGenerator.cs index ce21c3aab..26669231d 100644 --- a/Aetheria.State.Daemon/AetheriaDaemonRegularTopologyGenerator.cs +++ b/Aetheria.State.Daemon/AetheriaDaemonRegularTopologyGenerator.cs @@ -97,6 +97,7 @@ public static class AetheriaDaemonRegularTopologyGenerator if (catalog == null) throw new ArgumentNullException(nameof(catalog)); return (catalog.Corporations ?? Array.Empty()) .Where(corporation => corporation != null && !string.IsNullOrWhiteSpace(corporation.CorporationKey)) + .Where(corporation => !string.IsNullOrWhiteSpace(corporation.GeonameFileKey)) .Select(corporation => { var names = catalog.FindNameFile(corporation.GeonameFileKey); diff --git a/Aetheria.State.Daemon/AetheriaDaemonRunFactory.cs b/Aetheria.State.Daemon/AetheriaDaemonRunFactory.cs new file mode 100644 index 000000000..db8e69d7a --- /dev/null +++ b/Aetheria.State.Daemon/AetheriaDaemonRunFactory.cs @@ -0,0 +1,39 @@ +using Aetheria.State; +using Aetheria.State.Documents; +using GameCult.Aetheria.State.Verse; + +public static class AetheriaDaemonRunFactory +{ + public static async Task WriteAsync( + AetheriaStateNode node, + AetheriaRuntimeCatalogSnapshot catalog, + string now, + string generationIdentity, + AetheriaDaemonRegularTopologySettings? regularTopologySettings = null) + { + if (node == null) throw new ArgumentNullException(nameof(node)); + if (catalog == null) throw new ArgumentNullException(nameof(catalog)); + var settings = await node.MutableDocument(AetheriaStateNode.PlayerSettingsKey) + .ReadAsync().ConfigureAwait(false) ?? new AetheriaPlayerSettings(); + if (!settings.TutorialPassed) + return await AetheriaDaemonTutorialRunWriter.WriteAsync(node, catalog, now).ConfigureAwait(false); + + return await AetheriaDaemonRegularRunWriter.WriteAsync( + node, + catalog, + now, + StableSeed(generationIdentity), + regularTopologySettings).ConfigureAwait(false); + } + + public static uint StableSeed(string value) + { + var hash = 2166136261u; + foreach (var character in value ?? "") + { + hash ^= character; + hash *= 16777619u; + } + return hash == 0 ? 1u : hash; + } +} diff --git a/Aetheria.State.Daemon/AetheriaDaemonTutorialRunWriter.cs b/Aetheria.State.Daemon/AetheriaDaemonTutorialRunWriter.cs index d4a746e74..2219f333c 100644 --- a/Aetheria.State.Daemon/AetheriaDaemonTutorialRunWriter.cs +++ b/Aetheria.State.Daemon/AetheriaDaemonTutorialRunWriter.cs @@ -7,7 +7,10 @@ public sealed record AetheriaDaemonWrittenRun( string RunId, string RunKey, string CurrentEntityKey, - bool IsTutorial); + bool IsTutorial) +{ + public string SessionMode { get; init; } = AetheriaGameSessionState.AetheriaMode; +} public static class AetheriaDaemonTutorialRunWriter { @@ -88,6 +91,7 @@ public static class AetheriaDaemonTutorialRunWriter CurrentEntityKey = playerEntityKey, LifecyclePhase = AetheriaRuntimeRunLifecycle.Active, TerminalFrameId = -1, + GameMode = AetheriaGameSessionState.AetheriaMode, AgentTasks = materialized.Zones.Values .OrderBy(zone => zone.Topology.ZoneIndex) .SelectMany(zone => zone.AgentTasks) diff --git a/Aetheria.State.Daemon/AetheriaDaemonTutorialWorldMaterializer.cs b/Aetheria.State.Daemon/AetheriaDaemonTutorialWorldMaterializer.cs index d38b31cd7..047fdfa72 100644 --- a/Aetheria.State.Daemon/AetheriaDaemonTutorialWorldMaterializer.cs +++ b/Aetheria.State.Daemon/AetheriaDaemonTutorialWorldMaterializer.cs @@ -27,11 +27,17 @@ public static class AetheriaDaemonTutorialWorldMaterializer public static AetheriaDaemonMaterializedTutorialWorld Materialize( AetheriaDaemonTutorialWorldPlan world, IReadOnlyList factions, - AetheriaRuntimeCatalogSnapshot catalog) + AetheriaRuntimeCatalogSnapshot catalog, + bool isPrelude = true, + string identityPrefix = "tutorial") { if (world == null) throw new ArgumentNullException(nameof(world)); if (catalog == null) throw new ArgumentNullException(nameof(catalog)); var homes = world.Topology.HomeZoneByFactionKey; + factions = homes.Keys + .Select(key => factions.First(faction => + string.Equals(faction.CorporationKey, key, StringComparison.Ordinal))) + .ToArray(); var adjacency = world.Topology.Zones.ToDictionary( zone => zone.ZoneIndex, zone => zone.AdjacentZoneIndices, @@ -52,8 +58,10 @@ public static class AetheriaDaemonTutorialWorldMaterializer .OrderBy(faction => distances[faction.CorporationKey][topology.ZoneIndex]) .First(); var homeDistance = distances[nearest.CorporationKey][topology.ZoneIndex]; - var tutorialInfluence = Math.Max(0, (nearest.InfluenceDistance + 1) / 2); - var factionPresence = tutorialInfluence - homeDistance + 1; + var influence = isPrelude + ? Math.Max(0, (nearest.InfluenceDistance + 1) / 2) + : Math.Max(0, nearest.InfluenceDistance); + var factionPresence = influence - homeDistance + 1; var stationCount = (int)(random.NextFloat() * (factionPresence + 1)); var orbits = celestial.Orbits.ToList(); var entities = new List(); @@ -70,7 +78,7 @@ public static class AetheriaDaemonTutorialWorldMaterializer topology.ZoneIndex, homes, adjacency, - isPrelude: true); + isPrelude: isPrelude); generators.Add(factionKey, generator); } return generator; @@ -90,7 +98,7 @@ public static class AetheriaDaemonTutorialWorldMaterializer var baseOrbit = selected[stationIndex]; var stationOrbit = new AetheriaOrbitSnapshot { - OrbitKey = $"tutorial.zone.{topology.ZoneIndex}.station.{stationIndex}.orbit", + OrbitKey = $"{identityPrefix}.zone.{topology.ZoneIndex}.station.{stationIndex}.orbit", ParentOrbitKey = baseOrbit.ParentOrbitKey, Distance = baseOrbit.Distance, Phase = baseOrbit.Phase + MathF.PI / 3 * Sign(random.NextFloat() - 0.5f), @@ -114,7 +122,7 @@ public static class AetheriaDaemonTutorialWorldMaterializer if (turretIndex % 2 == 0) distanceMultiplier = -distanceMultiplier; var turretOrbit = new AetheriaOrbitSnapshot { - OrbitKey = $"tutorial.zone.{topology.ZoneIndex}.station.{stationIndex}.turret.{turretIndex}.orbit", + OrbitKey = $"{identityPrefix}.zone.{topology.ZoneIndex}.station.{stationIndex}.turret.{turretIndex}.orbit", ParentOrbitKey = stationOrbit.ParentOrbitKey, Distance = stationOrbit.Distance, Phase = stationOrbit.Phase + 20f * distanceMultiplier / stationOrbit.Distance, @@ -145,7 +153,7 @@ public static class AetheriaDaemonTutorialWorldMaterializer spawnRandom.NextFloat((float)-halfRadius, (float)halfRadius), spawnRandom.NextFloat((float)-halfRadius, (float)halfRadius)); var entityIndex = entities.Count; - var taskId = $"tutorial.zone.{topology.ZoneIndex}.entity.{entityIndex}.patrol"; + var taskId = $"{identityPrefix}.zone.{topology.ZoneIndex}.entity.{entityIndex}.patrol"; enemy.AgentTaskCapabilities = [ AetheriaRuntimeAgentTaskTypes.Attack, @@ -183,7 +191,7 @@ public static class AetheriaDaemonTutorialWorldMaterializer topology.ZoneIndex, homes, adjacency, - isPrelude: true).Build("ship", protagonist.CorporationKey); + isPrelude: isPrelude).Build("ship", protagonist.CorporationKey); localPlayerIndex = entities.Count; entities.Add(AetheriaDaemonGeneratedEntityFactory.Create( "Pilot", diff --git a/Aetheria.State.Daemon/AetheriaDaemonZoneBodyGenerator.cs b/Aetheria.State.Daemon/AetheriaDaemonZoneBodyGenerator.cs index 14a07625f..32ab3ef5c 100644 --- a/Aetheria.State.Daemon/AetheriaDaemonZoneBodyGenerator.cs +++ b/Aetheria.State.Daemon/AetheriaDaemonZoneBodyGenerator.cs @@ -38,6 +38,22 @@ public static class AetheriaDaemonTutorialWorldGenerator topology.NoisePosition))); return new AetheriaDaemonTutorialWorldPlan(topology, zones); } + + public static AetheriaDaemonTutorialWorldPlan GenerateRegular( + IReadOnlyList factions, + uint seed, + AetheriaDaemonRegularTopologySettings? settings = null) + { + var topology = AetheriaDaemonRegularTopologyGenerator.GenerateFossil(factions, seed, settings); + var zones = topology.Zones.ToDictionary( + zone => zone.ZoneIndex, + zone => AetheriaDaemonZoneBodyGenerator.Generate( + seed, + zone, + AetheriaDaemonRegularTopologyGenerator.MainCloudDensity(zone.X, zone.Y), + "regular")); + return new AetheriaDaemonTutorialWorldPlan(topology, zones); + } } /// @@ -51,7 +67,8 @@ public static class AetheriaDaemonZoneBodyGenerator public static AetheriaDaemonGeneratedZonePlan Generate( uint galaxySeed, AetheriaDaemonTutorialZoneTopology zone, - float cloudDensity) + float cloudDensity, + string identityPrefix = "tutorial") { var density = Saturate(cloudDensity / 2f); var radius = ExponentialLerp(density, 1.5f, 1000, 10000); @@ -100,7 +117,7 @@ public static class AetheriaDaemonZoneBodyGenerator planets.AddRange(GenerateSystem(ref random, mass, radius, new CultMath.float2(0, 0))); } - var orbitKeys = planets.Select((_, index) => $"tutorial.zone.{zone.ZoneIndex}.orbit.{index}").ToArray(); + var orbitKeys = planets.Select((_, index) => $"{identityPrefix}.zone.{zone.ZoneIndex}.orbit.{index}").ToArray(); var nodeIndices = planets.Select((node, index) => (node, index)).ToDictionary(value => value.node, value => value.index); var orbits = planets.Select((planet, index) => new AetheriaOrbitSnapshot { @@ -118,7 +135,8 @@ public static class AetheriaDaemonZoneBodyGenerator var planet = planets[nodeIndex]; if (planet.Empty) continue; - bodies.Add(ProjectBody(zone.ZoneIndex, bodies.Count, planet, orbits[nodeIndex], ref random)); + bodies.Add(ProjectBody( + identityPrefix, zone.ZoneIndex, bodies.Count, planet, orbits[nodeIndex], ref random)); } return new AetheriaDaemonGeneratedZonePlan( @@ -227,6 +245,7 @@ public static class AetheriaDaemonZoneBodyGenerator } private static AetheriaBodySnapshot ProjectBody( + string identityPrefix, int zoneIndex, int bodyIndex, PlanetNode planet, @@ -239,7 +258,7 @@ public static class AetheriaDaemonZoneBodyGenerator planet.Mass > 100 ? "planet" : "planetoid"; var body = new AetheriaBodySnapshot { - BodyKey = $"tutorial.zone.{zoneIndex}.body.{bodyIndex}", + BodyKey = $"{identityPrefix}.zone.{zoneIndex}.body.{bodyIndex}", Kind = kind, Name = $"Z{zoneIndex:D2}-{bodyIndex:D3}", OrbitKey = orbit.OrbitKey, diff --git a/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs b/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs index 46a4336ba..86804fa1e 100644 --- a/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs +++ b/Aetheria.State.Daemon/AetheriaDaemonZoneGenerator.cs @@ -97,6 +97,7 @@ internal static class AetheriaDaemonZoneGenerator CurrentEntityKey = entityKeys[1], LifecyclePhase = AetheriaRuntimeRunLifecycle.Active, TerminalFrameId = -1, + GameMode = AetheriaGameSessionState.TerminusMode, UpdatedAtUtc = now }).ConfigureAwait(false); diff --git a/Aetheria.State.Daemon/Program.cs b/Aetheria.State.Daemon/Program.cs index 38ce8582a..72484a092 100644 --- a/Aetheria.State.Daemon/Program.cs +++ b/Aetheria.State.Daemon/Program.cs @@ -2478,7 +2478,14 @@ static async Task EnsurePlayableRunDocumentsAsync( return; } - await WriteNewRunAsync(node, options, now).ConfigureAwait(false); + if (options.UseTerminusFixture) + { + await AetheriaDaemonZoneGenerator.WritePlayableRunAsync( + node, node.RuntimeCatalog().Latest(), now, options.TerminusScenario).ConfigureAwait(false); + return; + } + await AetheriaDaemonRunFactory.WriteAsync( + node, node.RuntimeCatalog().Latest(), now, now).ConfigureAwait(false); } static async Task EnsureGameSessionAsync( @@ -2493,9 +2500,9 @@ static async Task EnsureGameSessionAsync( var run = await node.MutableDocument(new CultRecordKey(player.ActiveRunKey)) .ReadAsync().ConfigureAwait(false) ?? throw new InvalidDataException($"Active Aetheria run is missing: {player.ActiveRunKey}"); - var expectedMode = run.IsTutorial - ? AetheriaGameSessionState.AetheriaMode - : AetheriaGameSessionState.TerminusMode; + var expectedMode = string.IsNullOrWhiteSpace(run.GameMode) + ? run.IsTutorial ? AetheriaGameSessionState.AetheriaMode : AetheriaGameSessionState.TerminusMode + : run.GameMode; var existing = await node.MutableDocument(AetheriaStateNode.GameSessionStateKey) .ReadAsync().ConfigureAwait(false); if (existing != null && @@ -2536,8 +2543,9 @@ static async Task ApplyRequestedNewGameSessionAsync( return false; var now = DateTimeOffset.UtcNow.ToString("O"); - var written = await WriteNewRunAsync(node, options, now).ConfigureAwait(false); - session.Mode = written.IsTutorial ? AetheriaGameSessionState.AetheriaMode : AetheriaGameSessionState.TerminusMode; + var written = await AetheriaDaemonRunFactory.WriteAsync( + node, node.RuntimeCatalog().Latest(), now, menu.LastCommandId).ConfigureAwait(false); + session.Mode = written.SessionMode; session.SessionId = options.SessionId; session.RunId = written.RunId; session.ControlledEntityKey = written.CurrentEntityKey; @@ -2552,29 +2560,6 @@ static async Task ApplyRequestedNewGameSessionAsync( return true; } -static async Task WriteNewRunAsync( - AetheriaStateNode node, - AetheriaDaemonHostOptions options, - string now) -{ - var settings = await node.MutableDocument(AetheriaStateNode.PlayerSettingsKey) - .ReadAsync().ConfigureAwait(false) ?? new AetheriaPlayerSettings(); - var catalog = node.RuntimeCatalog().Latest(); - if (!settings.TutorialPassed) - return await AetheriaDaemonTutorialRunWriter.WriteAsync(node, catalog, now).ConfigureAwait(false); - - await AetheriaDaemonZoneGenerator.WritePlayableRunAsync( - node, - catalog, - now, - options.TerminusScenario).ConfigureAwait(false); - return new AetheriaDaemonWrittenRun( - AetheriaDaemonZoneGenerator.RunIdFor(options.TerminusScenario), - $"global:aetheria.run_state.{AetheriaDaemonZoneGenerator.RunIdFor(options.TerminusScenario)}.v1", - AetheriaDaemonZoneGenerator.EntityKey(options.TerminusScenario, 0, 1), - false); -} - static async Task EnsureVerseAuthorityPolicyAsync( AetheriaStateNode node, AetheriaDaemonHostOptions options) @@ -2617,6 +2602,9 @@ static async Task ReadRuntimeRunCheckpointA { RunId = run.RunId ?? "", IsTutorial = run.IsTutorial, + GameMode = string.IsNullOrWhiteSpace(run.GameMode) + ? run.IsTutorial ? AetheriaGameSessionState.AetheriaMode : AetheriaGameSessionState.TerminusMode + : run.GameMode, EntranceZoneIndex = run.EntranceZoneIndex, ExitZoneIndex = run.ExitZoneIndex, CurrentZoneIndex = run.CurrentZoneIndex, @@ -3137,6 +3125,7 @@ internal sealed class AetheriaDaemonHostOptions public AetheriaRuntimeDaemonSimulationSettings SimulationSettings { get; init; } = AetheriaRuntimeDaemonSimulationSettings.AetheriaDefault; public string TerminusScenario { get; init; } = AetheriaDaemonTerminusScenarios.Standard; + public bool UseTerminusFixture { get; init; } public bool Once { get; init; } public static AetheriaDaemonHostOptions Parse(IReadOnlyList args) @@ -3165,7 +3154,8 @@ internal sealed class AetheriaDaemonHostOptions var noOdinAnnouncements = HasFlag(args, "--no-odin-announcements"); var apiPublicationIntervalMs = ReadPositiveInt(args, "--api-publication-interval-ms") ?? 1000; var sessionId = ReadOption(args, "--session-id"); - var terminusScenario = AetheriaDaemonTerminusScenarios.Parse(ReadOption(args, "--terminus-scenario")); + var requestedTerminusScenario = ReadOption(args, "--terminus-scenario"); + var terminusScenario = AetheriaDaemonTerminusScenarios.Parse(requestedTerminusScenario); return new AetheriaDaemonHostOptions { @@ -3197,6 +3187,7 @@ internal sealed class AetheriaDaemonHostOptions ApiPublicationInterval = TimeSpan.FromMilliseconds(apiPublicationIntervalMs), FixedDeltaSeconds = fixedDeltaMs / 1000.0, TerminusScenario = terminusScenario, + UseTerminusFixture = !string.IsNullOrWhiteSpace(requestedTerminusScenario), Once = HasFlag(args, "--once") }; } diff --git a/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs b/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs index 04453459a..1c861cbd8 100644 --- a/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs +++ b/Aetheria.State/Documents/AetheriaRuntimeStateDocuments.cs @@ -253,6 +253,9 @@ public sealed class AetheriaRunState [Key(16)] public AetheriaAgentTaskState[] AgentTasks { get; set; } = []; + + [Key(17)] + public string GameMode { get; set; } = AetheriaGameSessionState.AetheriaMode; } [MessagePackObject] diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs index 12a1244f2..89df40236 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeSnapshotDocuments.cs @@ -227,6 +227,9 @@ namespace GameCult.Aetheria.State.Verse [Key(19)] public long TerminalFrameId { get; set; } = -1; + [Key(20)] + public string GameMode { get; set; } = "aetheria"; + public AetheriaRuntimeLoadoutTemplateCommit CreateLoadoutTemplate(string entityKey) { return TryParseEntityKey(entityKey, out var zoneIndex, out var entityIndex) diff --git a/docs/aetheria-perfect-machine-map.md b/docs/aetheria-perfect-machine-map.md index e7961c991..2978b601f 100644 --- a/docs/aetheria-perfect-machine-map.md +++ b/docs/aetheria-perfect-machine-map.md @@ -1196,14 +1196,25 @@ the Terminus proof arena cannot award completion. or reinterpret entrance and exit. - Forbidden writers: Unity `Galaxy`, menus, map renderers, and Terminus scenario generation cannot decide regular-sector topology. -- Cut line: this topology owner is implemented and deterministic, but the - regular population/run writer is not wired yet. Post-tutorial New Game still - selects Terminus until that writer can persist a playable sector; topology - existence alone is not claimed as a playable run. +- Population and persistence: the regular topology feeds the same daemon-owned + celestial hierarchy, full-influence population, loadout, orbit, patrol, and + CultCache persistence organs as the tutorial, under distinct regular-run + identities. The entrance receives one equipped controlled starter; every + persisted run carries its explicit `aetheria` game mode. +- Shared paths: accepted New Game identity hashes to the regular generation + seed, so command replay cannot create a different sector. Fresh boot and menu + requests use `AetheriaDaemonRunFactory`; incomplete tutorial state selects the + tutorial writer and completed tutorial state selects the regular writer. +- Cut line: post-tutorial Terminus fallback selection is deleted. Terminus can + only be created when the daemon is explicitly launched with a + `--terminus-scenario` witness fixture; `IsTutorial=false` is no longer allowed + to decide session mode for new state. - Verification layer: focused smoke generates the full sector twice and proves exact seeded repeatability, connected symmetric links, twelve homes, three boss zones, exit isolation, entrance distance, discovery, names, and home - presence. + presence. A persisted-run smoke uses the shared factory and proves explicit + Aetheria mode, command-stable seed, generated starter/loadout, regular record + identities, autonomous patrols, selection, and hard CultCache reopen. ### Daemon Generated Zone Body Ownership diff --git a/docs/original-game-migration-matrix.md b/docs/original-game-migration-matrix.md index 0f8a12235..fa5442354 100644 --- a/docs/original-game-migration-matrix.md +++ b/docs/original-game-migration-matrix.md @@ -15,7 +15,7 @@ validation proves contract shape, not wiring, exclusivity, lowering, or parity. | Organ | Original authority/evidence | Target owner | Eve contract | Runtime lowering | Current status | Required proof | |---|---|---|---|---|---|---| -| Run/session state | `ServerShared`, `ActionGameManager` | Aetheria daemon/CultCache | provider/session advertisement plus run lifecycle bindings | all clients | active/failed lifecycle is daemon-owned and restart-stable: controlled-entity destruction commits the fossil cause, terminal frame, one `run.failed` fact, releases control, rejects later gameplay commands, and freezes the world; Eve receives terminal presentation/input levers without becoming an owner. Terminus keeps persistent requested simulation rate distinct from effective rate: compressed batches inspect authoritative facts after each fixed step, stop at the causal damage/destruction/cargo/thermal/docking/weapon/wormhole/run event, pause effectively without erasing the request, and project the exact cause and executed-step count through Eve. Docked, travelling, fighting, mining, looting, and refitting remain derived world conditions rather than counterfeit durable phases. The distinct tutorial is now daemon-owned and selectable: authored 64-zone topology, bodies, post-body station/turret/agent population, resolved orbital placement, deterministic half-zone NPC distribution, starter entry ship, loadout receipts, discovery, and canonical persistence feed an Aetheria-mode session. Generated orbit facts carry the fossil distance-derived period; daemon fixed steps advance phase and project the shared graph into orbital pose/velocity before Ymir while Eve and body queries observe the same graph. New Game submits its Eve operation and waits for the new tutorial sector-map publication. The daemon now also owns the distinct fossil regular-sector topology: 196 weighted zones, pruned Delaunay graph, twelve selected corporations, three boss chokepoints, full influence radii, isolated exit, furthest entrance, discovery, and order-four names are seed deterministic. Its population/run writer is not wired yet, so Terminus remains the explicit post-tutorial fallback rather than being misreported as a regular run | source-backed tutorial completion rule (none survived in the fossil); materialize and persist the regular sector, then delete the post-tutorial Terminus fallback; full-daemon death/restart witness, broader attention taxonomy, and multi-client convergence | +| Run/session state | `ServerShared`, `ActionGameManager` | Aetheria daemon/CultCache | provider/session advertisement plus run lifecycle bindings | all clients | active/failed lifecycle is daemon-owned and restart-stable: controlled-entity destruction commits the fossil cause, terminal frame, one `run.failed` fact, releases control, rejects later gameplay commands, and freezes the world; Eve receives terminal presentation/input levers without becoming an owner. Terminus keeps persistent requested simulation rate distinct from effective rate: compressed batches inspect authoritative facts after each fixed step, stop at the causal damage/destruction/cargo/thermal/docking/weapon/wormhole/run event, pause effectively without erasing the request, and project the exact cause and executed-step count through Eve. Docked, travelling, fighting, mining, looting, and refitting remain derived world conditions rather than counterfeit durable phases. The distinct tutorial is now daemon-owned and selectable: authored 64-zone topology, bodies, post-body station/turret/agent population, resolved orbital placement, deterministic half-zone NPC distribution, starter entry ship, loadout receipts, discovery, and canonical persistence feed an Aetheria-mode session. Generated orbit facts carry the fossil distance-derived period; daemon fixed steps advance phase and project the shared graph into orbital pose/velocity before Ymir while Eve and body queries observe the same graph. New Game submits its Eve operation and waits for the new sector-map publication. The daemon also owns the distinct fossil regular sector: 196 weighted zones, pruned Delaunay graph, twelve selected corporations, three boss chokepoints, full influence radii, isolated exit, furthest entrance, discovery, order-four names, celestial/population/loadout materialization, controlled starter, patrol work, and CultCache persistence. Accepted New Game identity determines the seed. New runs explicitly carry `aetheria` mode; post-tutorial Terminus fallback selection is deleted and Terminus generation requires an explicit witness launch option | source-backed tutorial completion rule (none survived in the fossil); full-scale real-catalog daemon/client regular-sector witness, boss entity/narrative behavior where source evidence exists, full-daemon death/restart witness, broader attention taxonomy, and multi-client convergence | | Entity identity/loadout | `ServerShared/Entity*` | daemon | typed entity and inventory surfaces | EveUnity/Electron | daemon-owned hull identity, exact installed placement/rotation and instance state, cargo stacks, weapon membership/held state, equipment wear, executable behavior state, weapon chronology, active-effect state, and loadout-generation provenance survive a hard CultCache close/reopen through the durable latest-frame checkpoint. An advertised generic Eve equip operation now translates into the typed daemon transaction before that checkpoint; its accepted placement survives restart and its consumed station-cargo source does not resurrect. Generic Eve rebuilds weapon and scalar thermostat controls from that restored truth; legacy per-entity documents are bootstrap inputs only when no live frame exists | live client refit witness and multi-client convergence | | Loadout generation | map/faction availability, item cost, hull hardpoints and role constraints | daemon using canonical galaxy, faction knowledge/economy and typed catalog | generated loadout plus provenance/availability facts | Eve inspection and refit surfaces | daemon now uses the fossil candidate filter and seeded weighted selection: manufacturer must be present and allied, ally weight decays by home-zone graph distance, price uses the authored exponent, and hardpoints require matching semantic type, rotated footprint containment, and controller role. Prelude generation retains the fossil exception that allied catalog manufacturers need not own one of the six tutorial home zones; unknown manufacturers remain zero-weight. The April 2021 catalog fossil restores the distinct common `Longinus`, rare AetherDrive-compatible `LonginusX`, and `Djinni` rows with their original IDs, shapes, hardpoints, prices, drag, and prefabs, plus missing Thruster rows required to fill their authored mounts; typed `rarity:rare` tags apply a 0.05 generation multiplier to `LonginusX` and AetherDrive equipment; the generator owns one mutable CultMath stream, fixing the readonly-struct defensive-copy bug that restarted every weighted draw; placement rotation survives durable state and reconnect; generation fills the largest compatible footprint before economic weighting; cargo/capacitor plus station docking equipment must fit remaining hull space; stations pack faction-available inventory largest-first; ordinary ships begin without invented scenario cargo; every generated entity persists a source/selection receipt that reaches Eve as `loadout.item` semantics | multi-zone generated-world parity and exact root-to-zone stream sequencing against the fossil | | Flight intent | `Ship`, `Thruster`, `AetherDrive`, `VelocityConversion`, `VelocityLimit`, input paths | daemon actuator simulation + Ymir integration | analog local helm/look/tractor plus actuator state | generic Eve input and scene lowerers | direct faction-speed velocity ownership is deleted; daemon persists local strafe/forward helm and desired look, allocates ordinary directional thruster banks by authored rotation, derives torque from hull/item placement, compensates lateral torque, gates execution through the shared energy ledger, deposits equipment-cell heat, publishes plume visibility and actuator state, applies hull drag, then runs operational velocity conversion with the fossil exponential damp equation and clamps the result through evaluated velocity limits before giving velocity/direction to Ymir. The evaluated limit remains in durable behavior state for reconnect and Eve inspection. Autonomous tasks translate world travel into the same local helm axes and issue look commands instead of mutating heading. AetherDrive rotor/coupling simulation is additive and explicitly non-default: common `Longinus` and `Djinni` hulls use ordinary thrusters; the rare `LonginusX` replaces those mounts with the single rare `Traction` AetherDrive path | hardpoint-transform direction parity, exact cross-equipment behavior execution ordering, CultMath/float32 parity harness, live production-frequency evidence, generic thrust/turn feedback lowering, and live handling screenshots | diff --git a/docs/renderless-aetheria-architecture.md b/docs/renderless-aetheria-architecture.md index 71d009ddb..f527b4ad6 100644 --- a/docs/renderless-aetheria-architecture.md +++ b/docs/renderless-aetheria-architecture.md @@ -170,11 +170,13 @@ fixture and the fallback for the still-unmigrated post-tutorial sector path. No surviving source defines tutorial completion, so entering this run does not change `TutorialPassed`. -The non-tutorial sector topology now has a separate daemon owner matching the -fossil's 196-zone settings, corporation selection, entrance/exit isolation, -boss chokepoints, full influence radii, discovery, and order-four names. It is -not yet a selectable run: population and persistence must be wired before the -post-tutorial Terminus fixture can be deleted as a fallback. +The non-tutorial sector has a separate daemon owner matching the fossil's +196-zone settings, corporation selection, entrance/exit isolation, boss +chokepoints, full influence radii, discovery, and order-four names. It feeds +the daemon celestial, population, loadout, patrol, and persistence pipeline and +enters through an explicit Aetheria-mode run. Post-tutorial New Game selects it +using a command-stable generation seed. Terminus is no longer a fallback; it is +created only by an explicit witness launch option. ## Current Mechanism