diff --git a/Assets/Scripts/ServerShared/Galaxy.cs b/Assets/Scripts/ServerShared/Galaxy.cs index a5660f52e..be2973a27 100644 --- a/Assets/Scripts/ServerShared/Galaxy.cs +++ b/Assets/Scripts/ServerShared/Galaxy.cs @@ -33,7 +33,6 @@ public class Galaxy // restored from a save. public uint Seed { get; } - private HashSet _containedFactions; private GalaxyZone[] _exitPath; private Dictionary _nameGenerators = new Dictionary(); private readonly CultCache _cache; @@ -432,12 +431,6 @@ public class Galaxy } } - public bool ContainsFaction(CultRecordRef faction) - { - _containedFactions ??= new HashSet(Factions.Select(f => _cache.RefOf(f).Key)); - return _containedFactions.Contains(faction.Key); - } - class DijkstraVertex { public float Cost; diff --git a/Assets/Scripts/ServerShared/LoadoutGenerator.cs b/Assets/Scripts/ServerShared/LoadoutGenerator.cs index 2fb2a69f9..91af76a90 100644 --- a/Assets/Scripts/ServerShared/LoadoutGenerator.cs +++ b/Assets/Scripts/ServerShared/LoadoutGenerator.cs @@ -174,26 +174,30 @@ public class LoadoutGenerator design.HardpointType == HardpointType.Tool || design.HardpointType == HardpointType.Hull || hulls.Any(hull => hull.Hardpoints.Any(hardpoint => hardpoint.Takes(design))); - // No galaxy means no availability to filter by: every product is on offer. A fixture generates loadouts that - // way, so a test can exercise placement and products without standing up a whole galaxy; no game path does. - // Loadouts.Materialize takes availability as a predicate; RunStart, the game's one preset spawner, passes this, so - // presets and generation share one availability rule. In a galaxy, a faction always reaches its own manufacturer's - // gear, and otherwise gear made by a manufacturer in that galaxy that its allegiance names (operator, 2026-09-30: - // allegiance lists only other factions). + // No galaxy, or no faction, means no allegiance to filter by: every product is on offer. A fixture generates + // loadouts that way, so a test can exercise placement and products without standing up a whole galaxy; a scenario + // stage has no faction and reaches every maker. Loadouts.Materialize takes availability as a predicate; RunStart, + // the game's one preset spawner, passes this, so presets and generation share one availability rule. A faction + // always reaches its own manufacturer's gear, and otherwise gear made by a manufacturer its allegiance names + // (operator, 2026-09-30: allegiance lists only other factions). Whether that manufacturer is present in the galaxy + // does not matter (operator, 2026-10-06: a faction need not be present for its gear to be available). public bool IsAvailable(FactionProductData product) => - Galaxy == null || Galaxy.IsPrelude || - Faction != null && ItemManager.ItemData.Get(product.Manufacturer) == Faction || - Galaxy.ContainsFaction(product.Manufacturer) && (Faction == null || Faction.Allegiance.ContainsKey(product.Manufacturer)); + Galaxy == null || Faction == null || + ItemManager.ItemData.Get(product.Manufacturer) == Faction || Faction.Allegiance.ContainsKey(product.Manufacturer); - // Prioritize products from the zone faction and its allies, penalizing distance to the manufacturer's headquarters - private float ManufacturerPreference(CultRecordRef manufacturer) + // Prioritize products from the zone faction and its allies, penalizing distance to the manufacturer's headquarters. + // A manufacturer with no home zone in this galaxy weighs as if its headquarters lay one jump beyond the farthest + // zone this zone reaches: reachable through allegiance, least preferred. + public float ManufacturerPreference(CultRecordRef manufacturer) { if (Faction == null || Galaxy == null) return 1; var maker = ItemManager.ItemData.Get(manufacturer); var allegiance = maker == Faction ? 1 : Faction.Allegiance.TryGetValue(manufacturer, out var a) ? a : 0; var home = maker != null && Galaxy.HomeZones.TryGetValue(maker, out var h) ? h : null; - var distance = home != null && Zone?.Distance != null && Zone.Distance.TryGetValue(home, out var d) ? d : 0; + var distance = Zone?.Distance == null ? 0 : + home != null && Zone.Distance.TryGetValue(home, out var d) ? d : + home == null && Zone.Distance.Count > 0 ? Zone.Distance.Values.Max() + 1 : 0; return allegiance / (1 + distance); } diff --git a/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs b/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs index 844e4995b..d02d8f9b7 100644 --- a/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs +++ b/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs @@ -231,9 +231,9 @@ public sealed class FireControlCut6cTests : IDisposable var cache = AetheriaStores.Open(Catalog, Run(), Player()); _openCaches.Add(cache); - // A minimal one-zone galaxy whose faction roster excludes Targeting Maker entirely, the same - // SavedGame/Galaxy round trip RunSaveTests uses to build a real Galaxy without standing up full - // procedural generation. + // A minimal one-zone galaxy the same SavedGame/Galaxy round trip RunSaveTests uses builds, without standing + // up full procedural generation. Its generator's faction is Maker, whose allegiance does not name + // Targeting Maker, so IsAvailable rejects Targeting Maker's products by allegiance. var game = new SavedGame { Factions = new[] { maker }, @@ -250,13 +250,14 @@ public sealed class FireControlCut6cTests : IDisposable }; RunSave.Commit(cache, game, zones, new ProvenanceLedger()); var galaxy = new Galaxy(cache, cache.GetGlobal(), _ => { }); - Assert.False(galaxy.ContainsFaction(targetingMaker)); + var makerFaction = cache.Get(maker); + Assert.False(makerFaction.Allegiance.ContainsKey(targetingMaker)); var random = new Random(1u); var settings = TestSettings(); var log = new List(); var items = new ItemManager(cache, new ProvenanceLedger(), settings, log.Add); - var generator = new LoadoutGenerator(ref random, items, galaxy, null, null, .5f); + var generator = new LoadoutGenerator(ref random, items, galaxy, null, makerFaction, .5f); var pack = generator.GenerateShipLoadout(candidate => candidate.Name == "Armed"); diff --git a/tests/Aetheria.Shared.Tests/RunStartGearTests.cs b/tests/Aetheria.Shared.Tests/RunStartGearTests.cs new file mode 100644 index 000000000..800081852 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/RunStartGearTests.cs @@ -0,0 +1,92 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// Gear does not need its maker present: LoadoutGenerator.IsAvailable reaches by allegiance alone, and an absent +// maker only weighs less (operator, 2026-10-06: a faction need not be present in the galaxy for its gear to be +// available). Every galaxy reaches the same way, the prelude included. +public sealed partial class RunStartTests +{ + // A maker the galaxy does not carry, with one product made from a real design, and a generator for a fresh + // faction whose allegiance names exactly the makers given (the absent one among them, or not). + private (FactionProductData product, Faction absent) AbsentMaker(string name) + { + var absent = new Faction { Name = name, ShortName = name }; + _cache.Upsert(absent); + var design = _cache.GetAll().First(p => p.Manufacturer.IsSet()).Design; + var product = new FactionProductData { Name = name + " Product", Design = design, Manufacturer = _cache.RefOf(absent) }; + _cache.Upsert(product); + return (product, absent); + } + + private LoadoutGenerator GeneratorFor(Galaxy galaxy, string name, params Faction[] allies) + { + var faction = new Faction { Name = name, ShortName = name }; + _cache.Upsert(faction); + foreach (var ally in allies) faction.Allegiance[_cache.RefOf(ally)] = 1; + return new LoadoutGenerator(ref _items.Random, _items, galaxy, galaxy.Entrance, faction, .5f); + } + + [Fact] + public void AnAbsentMakersGearIsAvailableThroughAllegiance() + { + var galaxy = MainSectorGalaxy(); + var (product, absent) = AbsentMaker("AbsentAlly"); + Assert.DoesNotContain(galaxy.Factions, f => f == absent); + Assert.True(GeneratorFor(galaxy, "Friend", absent).IsAvailable(product)); + } + + [Fact] + public void AnAbsentMakerOutsideAllegianceIsNot() + { + var galaxy = MainSectorGalaxy(); + var (product, _) = AbsentMaker("AbsentStranger"); + Assert.False(GeneratorFor(galaxy, "Loner").IsAvailable(product)); + } + + [Fact] + public void AFactionlessGeneratorReachesEveryMaker() + { + var galaxy = MainSectorGalaxy(); + AbsentMaker("AbsentToAll"); + var generator = new LoadoutGenerator(ref _items.Random, _items, galaxy, galaxy.Entrance, null, .5f); + var products = _cache.GetAll().Where(p => p.Manufacturer.IsSet()).ToArray(); + Assert.NotEmpty(products); + Assert.All(products, product => Assert.True(generator.IsAvailable(product), product.Name)); + } + + [Fact] + public void AnAbsentMakerWeighsAsTheFarthest() + { + var galaxy = MainSectorGalaxy(); + var (product, absent) = AbsentMaker("AbsentFar"); + var zone = galaxy.Entrance; + var farthest = galaxy.Factions + .Where(f => galaxy.HomeZones.TryGetValue(f, out var home) && zone.Distance.ContainsKey(home)) + .OrderByDescending(f => zone.Distance[galaxy.HomeZones[f]]).First(); + var generator = GeneratorFor(galaxy, "Trader", absent, farthest); + var absentWeight = generator.ManufacturerPreference(product.Manufacturer); + var farthestWeight = generator.ManufacturerPreference(_cache.RefOf(farthest)); + Assert.True(absentWeight > 0, "an absent ally is reachable"); + Assert.True(absentWeight < farthestWeight, $"absent {absentWeight} must weigh below the farthest present maker {farthestWeight}"); + Assert.Equal(1f / (2 + zone.Distance.Values.Max()), absentWeight); + } + + [Fact] + public void APreludeNoLongerOffersEverything() + { + Assert.True(_galaxy.IsPrelude); + var (absentProduct, _) = AbsentMaker("AbsentToPrelude"); + var generator = GeneratorFor(_galaxy, "PreludeLoner"); + Assert.False(generator.IsAvailable(absentProduct)); + var present = _cache.GetAll().Where(p => p.Manufacturer.IsSet() && + _galaxy.Factions.Any(f => _cache.RefOf(f).Key.Equals(p.Manufacturer.Key))).ToArray(); + Assert.NotEmpty(present); + Assert.All(present, product => Assert.False(generator.IsAvailable(product), product.Name)); + } +} diff --git a/tests/Aetheria.Shared.Tests/RunStartTests.cs b/tests/Aetheria.Shared.Tests/RunStartTests.cs index 755dd91bb..284469741 100644 --- a/tests/Aetheria.Shared.Tests/RunStartTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartTests.cs @@ -119,8 +119,8 @@ public sealed partial class RunStartTests : IDisposable private const float Freezing = 273.15f; - // A main-sector galaxy (not the prelude, which offers every product): each station's gear must come from - // manufacturers its faction can reach, the galaxy's factions its allegiance names. + // A main-sector galaxy: each station's gear must come from manufacturers its faction can reach, the makers its + // allegiance names, present in the galaxy or not. private Galaxy MainSectorGalaxy() { var authored = AuthoredSettings.Load(FindRepoRoot()); diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index c65f4c3f2..3c28c23ff 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -743,19 +743,11 @@ public static class Program } // Runs the real LoadoutGenerator against every hull, so a generation failure reproduces here instead of on a - // flight to a populated sector. No galaxy by default, so this covers placement, roles and products but NOT + // flight to a populated sector. No galaxy, so this covers placement, roles and products but NOT // availability filtering or distance weighting, which need a real galaxy. Seeded: a failure repeats. - // - // Cut 6c, 6c.2 verification: "exclude-sellers Short1,Short2,..." builds a minimal one-zone Galaxy (the same - // SavedGame/Galaxy round trip FireControlCut6cTests uses) whose faction roster is every catalog faction - // EXCEPT the named ones, so IsAvailable actually rejects their products instead of the null-Galaxy "every - // product is on offer" shortcut this command otherwise takes. That is the one way to reproduce the single - // point of failure 6c.2 fixed: a null-galaxy run can never exercise Galaxy.ContainsFaction at all. private static int Loadout(string[] args) { - var seedArgument = args.FirstOrDefault(a => !a.StartsWith("exclude-sellers")); - var excludeArg = args.FirstOrDefault(a => a.StartsWith("exclude-sellers")); - var seed = uint.TryParse(seedArgument, out var parsed) ? parsed : 1u; + var seed = uint.TryParse(args.FirstOrDefault(), out var parsed) ? parsed : 1u; var db = AetherDb.Open(); var settings = new GameplaySettings { @@ -764,45 +756,6 @@ public static class Program QualityPriceModifier = new ExponentialLerp() }; - Galaxy galaxy = null; - CultCache galaxyCache = null; - if (excludeArg != null) - { - var excludedShortNames = excludeArg.Contains(':') - ? excludeArg.Substring(excludeArg.IndexOf(':') + 1).Split(',', StringSplitOptions.RemoveEmptyEntries) - : Array.Empty(); - var excluded = new HashSet(excludedShortNames); - - // A second, scratch-run-store cache over the SAME catalog file, read-only on the catalog side -- - // RunSave.Commit only ever touches run-store record types (SavedGame, SavedZone, ProvenanceLedger), - // but it needs a store that is "home" to them, which the plain read-only db.Cache above is not. - // The scratch run.cc lives in the OS temp directory, never under GameData, so this command cannot - // leave behind or corrupt a real save. Factions are looked up through THIS cache instance, not - // db.Cache -- CultCache.RefOf needs the document to be one this specific instance's identity map - // tracks, and two Open() calls over the same file do not share object identity. - var scratchRun = Path.Combine(Path.GetTempPath(), $"aetherdb-loadout-exclude-{Guid.NewGuid():N}.cc"); - galaxyCache = AetheriaStores.Open(Path.Combine(db.Root, "GameData", "Aetheria.cc"), runPath: scratchRun); - var includedFactions = galaxyCache.GetAll().Where(f => !excluded.Contains(f.ShortName)).ToArray(); - Console.WriteLine($"Excluding sellers [{string.Join(", ", excluded)}] -- galaxy carries {includedFactions.Length} of {galaxyCache.GetAll().Count()} factions.\n"); - - var game = new SavedGame - { - Factions = includedFactions.Select(f => galaxyCache.RefOf(f)).ToArray(), - Relationships = includedFactions.Select(_ => FactionRelationship.Neutral).ToArray(), - HomeZones = new Dictionary { { 0, 0 } }, - BossZones = new Dictionary(), - DiscoveredZones = new[] { 0 }, - ActionBarBindings = new SavedActionBarBinding[0], - Exit = -1 - }; - var zones = new[] - { - new SavedZone { Name = "Zone 0", Position = new float2(0, 0), AdjacentZones = Array.Empty(), Factions = new[] { 0 }, Owner = 0, Contents = null } - }; - RunSave.Commit(galaxyCache, game, zones, new ProvenanceLedger()); - galaxy = new Galaxy(galaxyCache, galaxyCache.GetGlobal(), _ => { }); - } - var log = new List(); var itemManager = new ItemManager(db.Cache, new ProvenanceLedger(), settings, log.Add); var failures = 0; @@ -811,7 +764,7 @@ public static class Program foreach (var hull in db.Cache.GetAll().OrderBy(h => h.HullType).ThenBy(h => h.Name)) { var random = new Random(seed); - var generator = new LoadoutGenerator(ref random, itemManager, galaxy, null, null, .5f); + var generator = new LoadoutGenerator(ref random, itemManager, null, null, null, .5f); log.Clear(); string outcome; try @@ -837,7 +790,6 @@ public static class Program } Console.WriteLine($"\n{failures} hulls failed to generate a loadout (seed {seed}), {targetingGaps} armed hulls generated with no targeting system (fired unaided)"); - galaxyCache?.Dispose(); return failures; }