diff --git a/Assets/Resources/Settings.asset b/Assets/Resources/Settings.asset index 4536e99f1..f92142d6b 100644 --- a/Assets/Resources/Settings.asset +++ b/Assets/Resources/Settings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:2c67fcecfea500365c54e5c80e59b6f26d0526e877c266d9fa75a43053df225d -size 12647 +oid sha256:ab2cdc0732716dcbfa4875e90e598b0dff3f0c8d4f871cc180649a3db2e4cf0c +size 12562 diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index 4987fc43a..033060d7e 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -722,6 +722,7 @@ public class ActionGameManager : MonoBehaviour galaxyZone.PackedContents ??= ZoneGenerator.GenerateZone( ItemManager, Settings.ZoneSettings, + Settings.PlanetSettings, CurrentGalaxy, galaxyZone, CurrentGalaxy.IsPrelude @@ -845,7 +846,7 @@ public class ActionGameManager : MonoBehaviour { staged = RunSave.Replace(CultCache, () => { - RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, CurrentGalaxy, scenario); + RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, scenario); PopulateLevel(CurrentGalaxy.Entrance); return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, Settings.TutorialGenerationSettings, failures); }); diff --git a/Assets/Scripts/ServerShared/RunStart.cs b/Assets/Scripts/ServerShared/RunStart.cs index a8e0f6134..b330ad944 100644 --- a/Assets/Scripts/ServerShared/RunStart.cs +++ b/Assets/Scripts/ServerShared/RunStart.cs @@ -23,11 +23,11 @@ public static class RunStart return scenario.Generate(stage) ?? throw new InvalidOperationException($"Scenario {scenario.Name} generated no galaxy."); } - public static ZonePack GenerateArena(ItemManager itemManager, ZoneGenerationSettings zoneSettings, Galaxy galaxy, Scenario scenario) + public static ZonePack GenerateArena(ItemManager itemManager, ZoneGenerationSettings zoneSettings, PlanetSettings planetSettings, Galaxy galaxy, Scenario scenario) { SeedItems(itemManager, galaxy, 1); return galaxy.Entrance.PackedContents = ZoneGenerator.GenerateZone( - itemManager, zoneSettings, galaxy, galaxy.Entrance, galaxy.IsPrelude, scenario.Ambient); + itemManager, zoneSettings, planetSettings, galaxy, galaxy.Entrance, galaxy.IsPrelude, scenario.Ambient); } // Runs the scenario's Stage, then admits its player and everything it placed: each entity's stance set both ways diff --git a/Assets/Scripts/ServerShared/Scenarios/Belt.cs b/Assets/Scripts/ServerShared/Scenarios/Belt.cs index cf0150ff8..5ac8926c8 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Belt.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Belt.cs @@ -10,9 +10,10 @@ public sealed class Belt : Scenario "across the belt without a hitch; Previous with nothing targeted takes the farthest rock; the target indicator " + "sits on the rock it names."; - // Seeds 1-256 scanned for the arena whose entrance zone holds the belt with the most asteroids: seed 24, a belt of - // 615 rocks. The next four: 179 (553), 251 (548), 221 (532), 29 (515). - public override uint Seed => 24; + // Seeds 1-90 scanned for the arena whose entrance zone holds the belt with the most asteroids once the generator + // placed belts by their parent's window (children-within-reach): seed 86, a belt of 484 rocks. The next four: + // 55 (478), 83 (402), 64 (383), 63 (323). 37 of the 90 arenas hold no belt. + public override uint Seed => 86; public override bool Ambient => false; public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); diff --git a/Assets/Scripts/ServerShared/Scenarios/LockOn.cs b/Assets/Scripts/ServerShared/Scenarios/LockOn.cs index 450020506..87fc14103 100644 --- a/Assets/Scripts/ServerShared/Scenarios/LockOn.cs +++ b/Assets/Scripts/ServerShared/Scenarios/LockOn.cs @@ -7,7 +7,7 @@ public sealed class LockOn : Scenario public override string Brief => "A hostile closes from out of sight, finds you and locks. Verify: no warning at first; once it locks, one " + "indicator appears toward it and tightens as the lock grows; break line of sight or range and it vanishes; " + "your own ping shows no incoming paint on its side, only the lock does."; - public override uint Seed => 113; + public override uint Seed => 1; public override bool Ambient => false; // The hostile starts about 4000 m off, ahead and to port of the player, facing the player. At that range its passive diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 235092f90..85d1f3d96 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -111,7 +111,6 @@ public class TutorialGenerationSettings [Serializable, MessagePackObject(keyAsPropertyName:true), JsonObject] public class ZoneGenerationSettings { - public ExponentialCurve PlanetSafetyRadius; public float MassFloor = 1; public float SunMass = 10000; diff --git a/Assets/Scripts/ServerShared/WellTree.cs b/Assets/Scripts/ServerShared/WellTree.cs index bacf474de..5f9f408e6 100644 --- a/Assets/Scripts/ServerShared/WellTree.cs +++ b/Assets/Scripts/ServerShared/WellTree.cs @@ -257,19 +257,29 @@ public sealed class WellTree } } - // A root's reach. The one place the subzone shape is decided (question multi-root-zone-shape): a sole massive root is the - // whole zone (+inf, so its global term is the far field); with several, isolated-subzones bounds each root to Reach x the - // distance to the nearest other massive root, or its floor (Beta x support) if more. The superposed-inside option - // (Beta x max(pack radius, max over massive roots of |anchor - Centre| + support)) is not a change to this return: it needs - // every massive root's support, and roots are processed one at a time here, so it would take a second pass over the roots - // once their supports exist. + // A root's reach: the floor (Beta x support) or the subzone reach, whichever is more. The subzone shape is decided in the + // public static SubzoneReach (multi-root-isolated-subzones): the generator calls the same function, so Reach x the nearest + // root's distance is spelled once and the roots' windows are fitted to it (root-window-floor). private float SubzoneReach(int root, float floor) { - if (_massiveRoots.Length < 2) return float.PositiveInfinity; + var anchors = new List(); + foreach (var other in _massiveRoots) anchors.Add(_anchor[other]); + return Math.Max(SubzoneReach(anchors, Array.IndexOf(_massiveRoots, root)), floor); + } + + /// + /// A subzone root's reach among the zone's massive roots' anchors: a sole massive root is the whole zone (+inf, so its + /// global term is the far field); with several, each root is bounded to GravityField.Reach x the distance to the nearest + /// other root (multi-root-isolated-subzones). The superposed-inside option is not a change to this return: it needs every + /// root's support, and roots are processed one at a time. + /// + public static float SubzoneReach(IReadOnlyList anchors, int root) + { + if (anchors.Count < 2) return float.PositiveInfinity; var nearest = float.PositiveInfinity; - foreach (var other in _massiveRoots) - if (other != root) nearest = Math.Min(nearest, length(_anchor[other] - _anchor[root])); - return Math.Max(GravityField.Reach * nearest, floor); + for (var other = 0; other < anchors.Count; other++) + if (other != root) nearest = Math.Min(nearest, length(anchors[other] - anchors[root])); + return GravityField.Reach * nearest; } private void EmitTerms(int[] parent, float[] body, float[] family, int[][] ring, float[] lower, RingGroup[] group, @@ -395,8 +405,7 @@ public sealed class WellTree /// /// The pull (toward the node, u/s^2) a rail at `distance` round `parentOrbit` is given: the node's own terms at that /// distance. A ring member of a bodyless node adds each other member's own terms at their chord (positions at t = 0), - /// projected toward the node; a strengthless orbit on that ring (a station, a turret) takes the mean of what the ring's - /// members feel, so it keeps their period. Infinite period for a pull of 0 is the caller's. + /// projected toward the node. Infinite period for a pull of 0 is the caller's. /// public float PullAround(CultRecordKey parentOrbit, float distance, CultRecordKey self) { @@ -405,12 +414,7 @@ public sealed class WellTree var members = _ring[node]; if (members == null || members.Length < 2) return pull; if (_index.TryGetValue(self, out var me) && Array.IndexOf(members, me) >= 0) return pull + PartnersPull(members, me); - var inner = float.PositiveInfinity; - foreach (var m in members) inner = Math.Min(inner, _distance[m]); - if (Math.Abs(distance - inner) > RingWindow) return pull; - var mean = 0f; - foreach (var m in members) mean += PartnersPull(members, m) / members.Length; - return pull + mean; + return pull; } // What the other members of a ring pull member m with, along the direction from m to the node. diff --git a/Assets/Scripts/ServerShared/ZoneGenerator.cs b/Assets/Scripts/ServerShared/ZoneGenerator.cs index c6ec75375..30d9d52ae 100644 --- a/Assets/Scripts/ServerShared/ZoneGenerator.cs +++ b/Assets/Scripts/ServerShared/ZoneGenerator.cs @@ -40,6 +40,7 @@ public static class ZoneGenerator public static ZonePack GenerateZone( ItemManager itemManager, ZoneGenerationSettings zoneSettings, + PlanetSettings planetSettings, Galaxy galaxy, GalaxyZone galaxyZone, bool isTutorial = false, @@ -88,13 +89,17 @@ public static class ZoneGenerator } var totalArea = occupiedAreas.Sum(c => c.Area); - foreach (var c in occupiedAreas) + // Every area root is massive, so a root's reach is Reach x its nearest area's centre (WellTree.SubzoneReach) + var centres = occupiedAreas.Select(c => c.Center).ToList(); + for (var k = 0; k < occupiedAreas.Count; k++) { - planets.AddRange(GenerateEntities(zoneSettings, ref random, c.Area / totalArea * pack.Mass, c.Radius, c.Center)); + var c = occupiedAreas[k]; + planets.AddRange(GenerateEntities(zoneSettings, planetSettings, ref random, c.Area / totalArea * pack.Mass, c.Radius, c.Center, + WellTree.SubzoneReach(centres, k))); } } else - planets.AddRange(GenerateEntities(zoneSettings, ref random, pack.Mass, pack.Radius, float2.zero)); + planets.AddRange(GenerateEntities(zoneSettings, planetSettings, ref random, pack.Mass, pack.Radius, float2.zero, float.PositiveInfinity)); // Every orbit is a record; parents link to records, so each orbit holds its key before any child names it var orbitMap = new Dictionary(); @@ -147,7 +152,7 @@ public static class ZoneGenerator Enumerable.Range(0, (int) zoneSettings.AsteroidCount.Evaluate(beltData.Mass * orbitMap[planet].Distance)) .Select(_ => new Asteroid { - Distance = orbitMap[planet].Distance + random.NextFloat()*(random.NextFloat()-.5f)*zoneSettings.AsteroidBeltWidth.Evaluate(orbitMap[planet].Distance), + Distance = orbitMap[planet].Distance + random.NextFloat()*(random.NextFloat()-.5f)*2*planet.BeltHalfWidth, Phase = random.NextFloat(), Size = random.NextFloat(), RotationSpeed = zoneSettings.AsteroidRotationSpeed.Evaluate(random.NextFloat()) @@ -209,6 +214,20 @@ public static class ZoneGenerator return cache.Upsert(planetData); }).ToList(); + // The generator's own well tree, for clearance only (the Zone builds its own): what a rail must stay out of is the body's + // support, or its Roche margin if more. + var wellNodes = planets.Select(p => new WellNode(cache.RefOf(orbitMap[p]).Key, p.Parent == null ? default : cache.RefOf(orbitMap[p.Parent]).Key, + p.Distance, p.Phase, p.Empty || p.Belt ? 0f : p.Mass, + p.Belt ? p.Distance + p.BeltHalfWidth : p.Distance, p.FixedPosition)).ToList(); + var wells = WellTree.Build(wellNodes, planetSettings, pack.Radius); + float Extent(GeneratorPlanet p) + { + var key = cache.RefOf(orbitMap[p]).Key; + var roche = p.Empty || p.Belt ? 0f : WellTree.Curves(planetSettings, p.Mass).Softening * RocheMargin; + return Math.Max(wells.Support(key), roche); + } + bool Massive(GeneratorPlanet p) => wells.Reach(cache.RefOf(orbitMap[p]).Key) > 0f; + var nearestFaction = galaxy.Factions.MinBy(f => galaxy.HomeZones[f].Distance[galaxyZone]); var nearestFactionHomeZone = galaxy.HomeZones[nearestFaction]; var factionPresence = galaxy.InfluenceOf(nearestFaction) - nearestFactionHomeZone.Distance[galaxyZone] + 1; @@ -224,30 +243,39 @@ public static class ZoneGenerator // seed. galaxy.Entrance is reference-identity, not a name comparison. var isTutorialEntrance = isTutorial && galaxyZone == galaxy.Entrance; if (isTutorialEntrance && stationCount < 1) stationCount = 1; - var potentialLagrangePoints = planets - .Where(p => p.Parent != null && p.Parent.Children - .TrueForAll(c => !(c != p && abs(c.Distance - p.Distance) < .1f))) // Filter Rosettes + // A station's source is a well-bearing body alone on its ring whose rail clears every massive sibling's extent (the + // sibling's support, or its Roche margin if more) and the largest reach of any station or turret hull: whatever hull + // is built there, its Lagrange orbit then sits clear of any other body. + var cellSize = itemManager.GameplaySettings.SchematicCellSize; + var largestReach = cache.GetAll().Where(h => h.HullType == HullType.Station || h.HullType == HullType.Turret) + .Select(h => h.Reach(cellSize)).DefaultIfEmpty(0f).Max(); + var candidates = planets + .Where(p => p.Parent != null && !p.Empty && !p.Belt + && p.Parent.Children.TrueForAll(c => c == p || (abs(c.Distance - p.Distance) >= WellTree.RingWindow + && (!Massive(c) || abs(c.Distance - p.Distance) > Extent(c) + largestReach)))) .OrderBy(p => p.Distance) .ToArray(); - // The entrance's own station count is the floor above; its orbit always comes from this same selection. - // Ordinarily that selection is potentialLagrangePoints (non-rosette planet orbits). If the entrance zone - // has none of those (a boring single-body system, or a system that is entirely one rosette), widen to - // every planet orbit ordinary placement's own candidate pool is drawn from before the rosette filter -- - // still a real, parented planet orbit with a positive Distance -- rather than inventing an unparented, - // zero-distance orbit (that gave PlaceTurret's phase = 20*multiplier/orbit.Distance a division by zero, - // and left an orbit record with no planet behind it). - var lagrangeCandidates = potentialLagrangePoints; - if (isTutorialEntrance && lagrangeCandidates.Length == 0) - lagrangeCandidates = planets.Where(p => p.Parent != null).OrderBy(p => p.Distance).ToArray(); - // Pick a selection from the middle of the distribution - var selectedStationOrbits = lagrangeCandidates - .Skip(lagrangeCandidates.Length / 2) - .Take(stationCount) - .Select(p=>orbitMap[p]) - .ToArray(); - if (isTutorialEntrance && lagrangeCandidates.Length == 0) - throw new InvalidOperationException( - "The tutorial entrance zone must always get a station, but it has no candidate orbit at all -- every planet in the zone is a parentless root."); + // (the rail, how far a body on it keeps others out, whether it is a station's own orbit rather than a base's) + var sources = candidates.Skip(candidates.Length / 2).Take(stationCount) + .Select(p => (orbit: orbitMap[p], extent: Extent(p), direct: false)).ToArray(); + if (isTutorialEntrance && candidates.Length == 0) + { + // The entrance gets a station whatever its bodies: it orbits a root node beyond its ring group (or, for a body, its + // whole family), never at a ring member's distance, and sits there, not at a Lagrange point. + var roots = planets.Where(p => p.Parent == null).ToList(); + var rootNode = roots.FirstOrDefault(p => p.Children.Count > 0) ?? (roots.Count > 1 ? roots.OrderByDescending(p => p.Mass).First() : null); + if (rootNode == null) + throw new InvalidOperationException( + "The tutorial entrance zone must always get a station, but it has no candidate orbit at all -- every planet in the zone is a parentless root."); + var distance = rootNode.Empty + ? (1 + GravityField.RingReach) * GravityField.Beta * rootNode.Children.Where(Massive).Min(c => c.Distance) + : Extent(rootNode); + var direct = new OrbitData { Parent = cache.RefOf(orbitMap[rootNode]), Distance = distance, Phase = random.NextFloat() }; + pack.Orbits.Add(cache.Upsert(direct)); + sources = new[] { (orbit: direct, extent: float.NegativeInfinity, direct: true) }; + } + var selectedStationOrbits = sources.Select(x => x.orbit).ToArray(); + var extentOf = sources.ToDictionary(x => x.orbit, x => x.extent); var loadoutGenerators = new Dictionary(); @@ -261,6 +289,7 @@ public static class ZoneGenerator // L4 or L5: 60 degrees (one sixth of a turn) ahead of or behind the planet on its orbit. Phase is in turns. OrbitData CreateLagrangeOrbit(OrbitData baseOrbit) { + if (sources.First(x => x.orbit == baseOrbit).direct) return baseOrbit; var lagrangeOrbit = new OrbitData { Parent = baseOrbit.Parent, @@ -276,36 +305,48 @@ public static class ZoneGenerator // body's. Every body's reach counts, so turrets of differing reach clear each other. Phase is in turns, so the // arc length divides by the orbit's circumference. Returns where the turret sits (signed arc from the station) // and its reach, or null when there is no turret hull to generate, before any orbit is created. - (float arc, float reach)? PlaceTurret(OrbitData orbit, LoadoutGenerator loadoutGenerator, float side, float innerArc, float innerReach) + (float arc, float reach, bool placed)? PlaceTurret(OrbitData orbit, LoadoutGenerator loadoutGenerator, float side, float innerArc, float innerReach, + OrbitData baseOrbit) { var turret = loadoutGenerator.GenerateTurretLoadout(); if (turret == null) return null; var turretReach = (itemManager.GetData(turret.Hull) as HullData).Reach(itemManager.GameplaySettings.SchematicCellSize); var arc = innerArc + side * (innerReach + 2 * turretReach); + // A turret whose centre is within the base body's extent plus its own reach of the base is not placed: its side stops. + var phase = orbit.Phase + arc / (2 * PI * orbit.Distance); + if (2 * orbit.Distance * abs(sin(PI * (phase - baseOrbit.Phase))) < extentOf[baseOrbit] + turretReach) + { + itemManager.Log("A turret was not placed: its station's base body is within its reach (story-turret-tail-clearance)."); + return (arc, turretReach, false); + } var turretOrbit = new OrbitData { Parent = orbit.Parent, Distance = orbit.Distance, - Phase = orbit.Phase + arc / (2 * PI * orbit.Distance) + Phase = phase + }; pack.Orbits.Add(cache.Upsert(turretOrbit)); turret.Orbit = cache.RefOf(turretOrbit); pack.Entities.Add(turret); - return (arc, turretReach); + return (arc, turretReach, true); } // Turrets flank the station alternately, behind then ahead, each side growing outward from the station. - void PlaceTurrets(OrbitData orbit, LoadoutGenerator loadoutGenerator, int count, float stationReach) + void PlaceTurrets(OrbitData orbit, LoadoutGenerator loadoutGenerator, int count, float stationReach, OrbitData baseOrbit) { var arcs = new float[2]; + var stopped = new bool[2]; var reaches = new[] { stationReach, stationReach }; for(int t=0; t= selectedStationOrbits.Length) { itemManager.Log($"Story station for {story.Faction?.Name} has no rail clear of the bodies; its story has nowhere to live!"); continue; } var orbit = selectedStationOrbits[i]; var lagrangeOrbit = CreateLagrangeOrbit(orbit); var station = GetLoadoutGenerator(story.Faction).GenerateStationLoadout(); @@ -329,7 +371,7 @@ public static class ZoneGenerator station.Story = i; pack.Entities.Add(station); - if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(story.Faction), story.Turrets, StationReach(station)); + if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(story.Faction), story.Turrets, StationReach(station), orbit); } for (var i = storyStations.Length; i < selectedStationOrbits.Length; i++) @@ -351,7 +393,7 @@ public static class ZoneGenerator station.SecurityRadius = pack.Radius; pack.Entities.Add(station); - if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(nearestFaction), 2, StationReach(station)); + if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(nearestFaction), 2, StationReach(station), orbit); } // A boss zone gets its faction's boss whether or not the zone is ambient: the boss is the run's goal, not @@ -413,16 +455,15 @@ public static class ZoneGenerator // 1 / lerp(settings.ResourceDensityMinimum, settings.ResourceDensityMaximum, density)); // } - public static GeneratorPlanet[] GenerateEntities(ZoneGenerationSettings settings, ref Random random, float mass, float radius, float2 fixedPosition) + public static GeneratorPlanet[] GenerateEntities(ZoneGenerationSettings settings, PlanetSettings planetSettings, ref Random random, float mass, float radius, float2 fixedPosition, + float rootReach) { var root = new GeneratorPlanet { FixedPosition = fixedPosition, Settings = settings, - Mass = mass, - ChildDistanceMaximum = radius * .75f, - ChildDistanceMinimum = settings.PlanetSafetyRadius.Evaluate(mass) - }; + Mass = mass + }; // There is some chance of generating a rosette or binary system // Probabilities which are fixed for the entire galaxy are in GlobalData, contained in the GameContext @@ -439,8 +480,6 @@ public static class ZoneGenerator count: (int)(random.NextFloat(1, 3) * random.NextFloat(1, 2)), massMulMin: .6f, massMulMax: .8f, - distMulMin: 1.25f, - distMulMax: 1.75f, jupiterJump: 1, massFraction: .1f); @@ -454,8 +493,6 @@ public static class ZoneGenerator count: (int) (random.NextFloat(1, 3 * m) + random.NextFloat(1, 3 * m)), massMulMin: 0.75f, massMulMax: 2.5f, - distMulMin: 1 + m * .25f, - distMulMax: 1.05f + m * .5f, jupiterJump: random.NextFloat() * random.NextFloat() * 10 + 1, massFraction: .5f ); @@ -469,8 +506,6 @@ public static class ZoneGenerator count: random.NextInt(5, 15), massMulMin: 0.75f, massMulMax: 2.5f, - distMulMin: 1.1f, - distMulMax: 1.25f, jupiterJump: random.NextFloat() * random.NextFloat() * 10 + 1, massFraction: .25f ); @@ -511,8 +546,6 @@ public static class ZoneGenerator count: planet.Mass < settings.GasGiantMass ? random.NextInt(1, 3) : random.NextInt(2, 6), massMulMin: .75f, massMulMax: 1.5f, - distMulMin: 1.05f, - distMulMax: 1.25f, jupiterJump: 1, massFraction: .15f); // Planetary satellites are not nearly as massive as planets themselves } @@ -535,8 +568,131 @@ public static class ZoneGenerator foreach (var planet in root.AllPlanets()) planet.Mass = (planet.Mass / totalMass) * rootMass; + Place(root, planetSettings, radius, rootReach); + return root.AllPlanets().ToArray(); } + + // Placement (tail-taming-law-r3-band-loose-cusp, c4-proceed-and-fly): a child sits at least RocheMargin of its parent's Roche + // limits out; a massive child of a body also far enough that its own pull peak beats CuspMargin times its parent's pull there; + // siblings sit SiblingSpacing of a reach apart. Every other number is a GravityField constant. + public const float RocheMargin = 1.5f; + public const float CuspMargin = 1.5f; + public const float SiblingSpacing = .5f; + + /// + /// The one placement pass: gives every generated node its distance and every belt its half width, top-down. A body's children + /// are laid inside-out at the nearest the rules allow, the lightest family is folded into the parent (its mass kept) while the + /// outermost overflows the window, and the rest are stretched geometrically so the outermost sits at the window's edge. A + /// non-root's window ends before its own fade (Gamma x Reach x its distance); a root's, in a zone of several, ends under + /// rootReach / Beta so its support never meets another root's (root-window-floor), and is 0.75 x the area radius at most. + /// A rosette's ring is one orbit; it folds into its node, which becomes a body, if it cannot keep the heavy member outside + /// its Roche margin. Ported from docs/research/gravity-well-law/replace.py. + /// + public static void Place(GeneratorPlanet root, PlanetSettings planetSettings, float radius, float rootReach) + { + var q = 1 / (1 - SiblingSpacing * GravityField.Reach); + float Roche(float mass) => WellTree.Curves(planetSettings, mass).Softening; + float Strength(float mass) => WellTree.Curves(planetSettings, mass).Strength; + float WellMass(GeneratorPlanet p) => p.Empty || p.Belt ? 0f : p.Mass; + float Family(GeneratorPlanet p) => (p.Empty ? 0f : p.Mass) + p.Children.Sum(c => Family(c)); + void Fold(GeneratorPlanet node, GeneratorPlanet into) + { + into.Mass += Family(node); + node.Parent.Children.Remove(node); + } + + void PlaceChildren(List children, Func lower, float upper, GeneratorPlanet into) + { + upper *= 1 - 1e-6f; + float AtLeast(GeneratorPlanet child, float edge) + { + // A bodyless node stands in for one body of its family's mass, which it becomes if its ring cannot stand + var m = child.Empty ? Family(child) : WellMass(child); + var mInto = WellMass(into); + return m <= 0 || mInto <= 0 ? edge : Math.Max(edge, 2 * CuspMargin * Roche(m) * Strength(mInto) / Strength(m)); + } + + var lo = 0f; + var positions = new List(); + while (children.Count > 0) + { + lo = lower(); + positions.Clear(); + for (var k = 0; k < children.Count; k++) + positions.Add(AtLeast(children[k], k == 0 ? lo : Math.Max(lo, positions[k - 1] * q))); + if (positions[positions.Count - 1] <= upper) break; + var lightest = children.OrderBy(c => Family(c)).First(); + Fold(lightest, into); + children.Remove(lightest); + } + if (children.Count == 0) return; + + var g = children.Count > 1 ? pow(upper / positions[positions.Count - 1], 1f / (children.Count - 1)) : 1f; + for (var k = 0; k < children.Count; k++) + children[k].Distance = positions[k] * pow(g, k); + // A belt is an interval inside its slot: inner edge outside the lower bound and the previous sibling's spacing, outer edge + // inside the next sibling's spacing and the window; the authored width is the widest it may be. + var outer = 0f; + for (var k = 0; k < children.Count; k++) + { + var c = children[k]; + if (!c.Belt) { outer = c.Distance; continue; } + var inner = Math.Max(lo, outer * q); + var outerLimit = k + 1 < children.Count ? Math.Min(upper, children[k + 1].Distance / q) : upper; + c.Distance = (inner + outerLimit) / 2; + var half = Math.Max(0f, Math.Min(c.Settings.AsteroidBeltWidth.Evaluate(c.Distance), outerLimit - inner) / 2); + c.BeltHalfWidth = half; + outer = c.Distance + half; + } + } + + var chordCap = new Dictionary(); // a ring member's children stay within .2 of the nearest partner's chord + void Settle(GeneratorPlanet node) + { + var isRoot = node.Parent == null; + var reach = isRoot ? rootReach : GravityField.Reach * node.Distance; + var share = isRoot ? 1 / GravityField.Beta : GravityField.Gamma; + var cap = isRoot ? .75f * radius : float.PositiveInfinity; + var upper = Math.Min(cap, share * reach / Math.Max(GravityField.Beta, 1 + GravityField.Reach)); + if (chordCap.TryGetValue(node, out var chord)) upper = Math.Min(upper, chord); + if (WellMass(node) > 0) + { + PlaceChildren(node.Children.ToList(), () => RocheMargin * Roche(WellMass(node)), upper, node); + return; + } + + var ring = node.Children.Where(c => c.Ring && WellMass(c) > 0).ToList(); + if (ring.Count == 0) return; + var heavy = ring.OrderByDescending(c => c.Mass).First(); + var ringDistance = Math.Min(.5f * cap, share * reach / (GravityField.Beta * GravityField.Beta * (1 + GravityField.RingReach))); + PlaceChildren(node.Children.Where(c => !ring.Contains(c)).ToList(), + () => (1 + GravityField.RingReach) * ringDistance * GravityField.Beta, upper, heavy); + // The heavy member's mass is final only now (the outer children fold into it). + if (ringDistance < RocheMargin * Roche(heavy.Mass)) + { + // The pair cannot keep its heavy member outside its Roche margin inside its node's reach: the node is one body. + node.Empty = false; + node.Mass = 0; + foreach (var child in node.Children.ToList()) Fold(child, node); + return; + } + foreach (var member in ring) + { + member.Distance = ringDistance; + chordCap[member] = .2f * 2 * ringDistance * sin(PI / ring.Count); + } + } + + var queue = new Queue(); + queue.Enqueue(root); + while (queue.Count > 0) + { + var node = queue.Dequeue(); + Settle(node); + foreach (var child in node.Children) queue.Enqueue(child); + } + } } // All orbiting bodies are referred to here as "Planets" @@ -548,10 +704,13 @@ public class GeneratorPlanet public float Distance; public float Phase; public float Mass; - public float ChildDistanceMinimum; - public float ChildDistanceMaximum; + // A belt's half width, written by ZoneGenerator.Place: the belt fills the slot between its siblings' spacing, the parent's + // Roche margin and the parent's window, up to the authored width (ruling belt-fills-its-slot). + public float BeltHalfWidth; public bool Empty = false; public bool Belt = false; + // A member of a rosette's ring, which Place puts on one orbit round its bodyless parent. + public bool Ring = false; public List Children = new List(); // Planets orbiting this one are referred to as children public GeneratorPlanet Parent; public float2 FixedPosition; @@ -562,12 +721,10 @@ public class GeneratorPlanet return new[]{this}.Concat(Children.SelectMany(c=>c.AllPlanets())); } - // Create children that fill a single orbit, equally spaced + // Create children that fill a single orbit, equally spaced; Place sets the orbit's radius // https://en.wikipedia.org/wiki/Klemperer_rosette public void ExpandRosette(ref Random random, int vertices) { - //Debug.Log("Expanding Rosette"); - // Rosette children replace the parent, parent orbital node is left empty Empty = true; @@ -577,60 +734,37 @@ public class GeneratorPlanet // Proportion of the masses of sequential pairs is random, but only for even vertex counts var proportion = vertices % 2 == 0 ? random.NextFloat(.5f,.95f) : .5f; - // Place children at a fixed distance in the center of the range - var dist = (ChildDistanceMinimum + ChildDistanceMaximum) / 2; - - // Position of first child - var p0 = new float2(0, dist); - - // Position of second child - var p1 = OrbitData.Evaluate(1.0f / vertices) * dist; - - // Maximum child distance is half the distance to the neighbor minus the neighbor's radius - var p0ChildDist = (distance(p0, p1) * proportion - Settings.PlanetSafetyRadius.Evaluate(sharedMass * (1 - proportion))) * .75f; - var p1ChildDist = (distance(p0, p1) * (1 - proportion) - Settings.PlanetSafetyRadius.Evaluate(sharedMass * proportion)) * .75f; - for (int i = 0; i < vertices; i++) { - var child = new GeneratorPlanet + Children.Add(new GeneratorPlanet { Settings = Settings, Parent = this, Mass = sharedMass * (i % 2 == 0 ? proportion : 1 - proportion), // Masses alternate - Distance = dist, Phase = (float) i / vertices, - ChildDistanceMaximum = (i % 2 == 0 ? p0ChildDist : p1ChildDist) - }; - child.ChildDistanceMinimum = Settings.PlanetSafetyRadius.Evaluate(child.Mass) * 2; - Children.Add(child); + Ring = true + }); } - - ChildDistanceMinimum = dist + p0ChildDist; } - // Create children that mimic the distribution of planetary masses in the solar system - public void ExpandSolar(ref Random random, int count, float massMulMin, float massMulMax, float distMulMin, float distMulMax, float jupiterJump, float massFraction) + // Create children that mimic the distribution of planetary masses in the solar system, inside-out in list order; + // Place gives them their distances + public void ExpandSolar(ref Random random, int count, float massMulMin, float massMulMax, float jupiterJump, float massFraction) { - //Debug.Log("Expanding Solar"); - // Expansion is impossible when child space is full - if (count == 0 || ChildDistanceMaximum < ChildDistanceMinimum) + if (count == 0) return; var masses = new float[count]; - var distances = new float[count]; // Accumulate total mass - // Initialize first mass and distance, actual number doesn't matter since total mass will be divided proportionally - float massTotal = distances[0] = masses[0] = 1; + // Initialize first mass, actual number doesn't matter since total mass will be divided proportionally + float massTotal = masses[0] = 1; - // Masses and distances multiply from one planet to the next + // Masses multiply from one planet to the next // Mass typically increases exponentially as you go further out // jupiterJump is an additional mass multiplier applied after half of the planets for (var i = 1; i < count; i++) - { massTotal += masses[i] = masses[i - 1] * random.NextFloat(massMulMin, massMulMax) * (count/2==i ? jupiterJump : 1); - distances[i] = distances[i - 1] * random.NextFloat(distMulMin, distMulMax); - } // Add some randomness to child masses for (var i = 0; i < masses.Length; i++) @@ -640,37 +774,17 @@ public class GeneratorPlanet for (var i = 0; i < count; i++) masses[i] = masses[i] / massTotal * Mass * massFraction; - // Map child distances to range between minimum and maximum - if (count > 1) - { - var oldDistances = (float[]) distances.Clone(); - for (var i = 0; i < count; i++) - distances[i] = lerp(ChildDistanceMinimum, ChildDistanceMaximum, - (oldDistances[i] - oldDistances[0]) / (oldDistances[count - 1] - oldDistances[0])) + Settings.PlanetSafetyRadius.Evaluate(masses[i]); - } - for (var i = 0; i < count; i++) { // Only instantiate children above the mass floor if (masses[i] > Settings.MassFloor) - { - var child = new GeneratorPlanet + Children.Add(new GeneratorPlanet { Settings = Settings, Parent = this, Mass = masses[i], - Distance = distances[i], Phase = random.NextFloat() - }; - child.ChildDistanceMinimum = Settings.PlanetSafetyRadius.Evaluate(child.Mass) * 2; - // Maximum child distance of child is the smallest distance to either of its neighbors - child.ChildDistanceMaximum = min(i == 0 ? child.Distance - ChildDistanceMinimum : child.Distance - distances[i - 1], - i < count - 1 ? distances[i + 1] - child.Distance : float.PositiveInfinity); - if (float.IsNaN(child.Distance)) - throw new NotFiniteNumberException($"Planet created with NaN distance, something went very wrong!"); - if (child.ChildDistanceMaximum > child.ChildDistanceMinimum) - Children.Add(child); - } + }); } } } diff --git a/tests/Aetheria.Shared.Tests/BeltScenarioTests.cs b/tests/Aetheria.Shared.Tests/BeltScenarioTests.cs index 0222ca035..2c352b6e8 100644 --- a/tests/Aetheria.Shared.Tests/BeltScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/BeltScenarioTests.cs @@ -7,9 +7,9 @@ using static CultMath.math; // mining-merge-on-agent-proof). The test launches the scenario the way New Game does and reads what it staged. public sealed partial class RunStartTests { - // The scan behind Belt's seed: seeds 1-256 of the demo cast's arena, no ambient traffic, the most asteroids in one belt - // per seed. Seed 24 holds 615; seed 1 holds 299. - private const int ScannedBeltAsteroids = 615; + // The scan behind Belt's seed: seeds 1-90 of the demo cast's arena, no ambient traffic, the most asteroids in one belt + // per seed. Seed 86 holds 484. + private const int ScannedBeltAsteroids = 484; // Belt: the arena carries a belt of at least the scanned asteroid count, nothing else flies in it, the player stands // 100 m outside the ring on the side nearest the origin and faces along it, and the player's sensors see rocks within diff --git a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs new file mode 100644 index 000000000..96ffb8b82 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs @@ -0,0 +1,505 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; +using Xunit.Abstractions; +using static CultMath.math; +using float2 = CultMath.float2; + +// Aetheria gravity, children within reach: the production generator's zones (every zone of seeds 1-6, ambient off) read back +// through the Zone's own tree, orbits and bodies. Each expectation is spelled from the rule it names and the law's constants +// (GravityField), never from ZoneGenerator.Place's helpers. +public sealed class ChildrenWithinReachTests : IClassFixture +{ + public sealed class Zones : IDisposable + { + private readonly ZoneWorlds _worlds = new ZoneWorlds(); + public readonly List<(uint Seed, Zone Zone)> All = new List<(uint, Zone)>(); + public ZoneGenerationSettings Settings; + + public Zones() : this(1, 6, null) { } + + // Not public: xunit builds the fixture through its one public constructor; a test that wants a tuned sample builds its own. + internal Zones(uint first, uint last, Action tune) + { + for (uint seed = first; seed <= last; seed++) + { + var dir = Path.Combine(_worlds.Root, $"galaxy{seed}"); + Directory.CreateDirectory(dir); + var catalog = Path.Combine(dir, "Aetheria.cc"); + File.Copy(TestCatalog.Repo, catalog); + var cache = new CultCache(TestCatalog.Registry()); + _worlds.Caches.Add(cache); + cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(catalog), AetheriaStores.CatalogTypes); + cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); + var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); + var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), + authored.Read("TutorialBackgroundSettings"), + authored.Read("NameGeneratorSettings"), cache, new PlayerSettings(), + Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var items = new ItemManager(cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); + var planetSettings = authored.Read("PlanetSettings"); + foreach (var galaxyZone in galaxy.Zones) + { + Settings = authored.Read("ZoneSettings"); + tune?.Invoke(Settings); + var pack = ZoneGenerator.GenerateZone(items, Settings, planetSettings, galaxy, galaxyZone, + galaxyZone == galaxy.Entrance && galaxy.IsPrelude, false); + All.Add((seed, new Zone(items, planetSettings, pack, galaxyZone, galaxy))); + } + } + } + + public void Dispose() => _worlds.Dispose(); + } + + private readonly Zones _zones; + private readonly ITestOutputHelper _out; + + public ChildrenWithinReachTests(Zones zones, ITestOutputHelper output) + { + _zones = zones; + _out = output; + } + + private const float Tolerance = 1e-3f; + // A child's own family folded into it after it was placed raises its mass, and the cusp bound grows as mass^.05. + private const float CuspTolerance = 1e-2f; + private const float RocheMargin = 1.5f, CuspMargin = 1.5f; // the rulings tail-taming-law-r3-band-loose-cusp and c4-proceed-and-fly + + private static float Roche(Zone zone, float mass) => zone.Settings.RocheLimit.Evaluate(mass); + private static float Strength(Zone zone, float mass) => zone.Settings.WellStrength.Evaluate(mass); + + // Orbits that carry a well-bearing body, with its mass; belts and bodyless nodes carry none. + private static Dictionary BodyMass(Zone zone) => + zone.Planets.Values.Where(b => !(b is AsteroidBeltData)).GroupBy(b => b.Orbit.Key).ToDictionary(g => g.Key, g => g.First().Mass); + + // The generated orbits: every body's and its ancestors', which leaves out stations, turrets and Lagrange copies. + private static HashSet Placed(Zone zone) + { + var placed = new HashSet(); + foreach (var body in zone.Planets.Values) + for (var key = body.Orbit.Key; placed.Add(key) && zone.Orbits[key].Data.Parent.IsSet();) key = zone.Orbits[key].Data.Parent.Key; + return placed; + } + + private static List ChildrenOf(Zone zone, CultRecordKey parent, HashSet placed) => + placed.Where(k => zone.Orbits[k].Data.Parent.IsSet() && zone.Orbits[k].Data.Parent.Key.Equals(parent)) + .OrderBy(k => zone.Orbits[k].Data.Distance).ToList(); + + private static float DistanceOf(Zone zone, CultRecordKey orbit) => zone.Orbits[orbit].Data.Distance; + + private static List MassiveRoots(Zone zone) => + zone.Orbits.Keys.Where(k => !zone.Orbits[k].Data.Parent.IsSet() && zone.Wells.Reach(k) > 0f).ToList(); + + private static float2 Anchor(Zone zone, CultRecordKey root) => zone.Orbits[root].Data.FixedPosition; + + private static IEnumerable Descendants(Zone zone, CultRecordKey root, HashSet placed) + { + foreach (var child in ChildrenOf(zone, root, placed)) + { + yield return child; + foreach (var below in Descendants(zone, child, placed)) yield return below; + } + } + + [Fact] + public void SubzonesAreIsolated() + { + var zonesChecked = 0; + var pairs = 0; + var violatingPairs = 0; + var orbits = 0; + var violatingOrbits = 0; + foreach (var (seed, zone) in _zones.All) + { + var roots = MassiveRoots(zone); + if (roots.Count < 2) continue; + zonesChecked++; + var placed = Placed(zone); + foreach (var i in roots) + { + var nearest = roots.Where(j => !j.Equals(i)).Min(j => length(Anchor(zone, i) - Anchor(zone, j))); + Assert.True(Math.Abs(zone.Wells.Reach(i) - GravityField.Reach * nearest) <= Tolerance * nearest, + $"seed {seed}: a root's reach {zone.Wells.Reach(i)} is not Reach x the nearest root's distance {nearest} (its floor binds)"); + foreach (var j in roots.Where(j => !j.Equals(i))) + { + pairs++; + if (zone.Wells.Reach(i) + zone.Wells.Support(j) > length(Anchor(zone, i) - Anchor(zone, j)) * (1 + Tolerance)) violatingPairs++; + foreach (var orbit in Descendants(zone, i, placed)) + { + orbits++; + if (length(zone.OrbitPositionAt(orbit, 0) - Anchor(zone, j)) < zone.Wells.Reach(j) * (1 - Tolerance)) violatingOrbits++; + } + } + } + } + _out.WriteLine($"subzones isolated: {zonesChecked} multi-root zones, {pairs} ordered root pairs ({violatingPairs} with reach_i + support_j > d), " + + $"{orbits} orbit-vs-root checks ({violatingOrbits} inside another root's reach)"); + Assert.True(zonesChecked > 0 && pairs > 0 && orbits > 0, "the seeds generated no zone with two massive roots"); + Assert.True(violatingPairs == 0, $"{violatingPairs} of {pairs} ordered root pairs overlap"); + Assert.True(violatingOrbits == 0, $"{violatingOrbits} of {orbits} orbits sit inside another root's reach"); + } + + [Fact] + public void NoChildSitsInsideItsParentsRocheMargin() + { + var children = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + foreach (var parent in placed.Where(mass.ContainsKey)) + foreach (var child in ChildrenOf(zone, parent, placed)) + { + children++; + var margin = RocheMargin * Roche(zone, mass[parent]); + Assert.True(DistanceOf(zone, child) >= margin * (1 - Tolerance), $"seed {seed}: a child sits at {DistanceOf(zone, child)}, inside {margin}"); + } + } + Assert.True(children > 100, $"only {children} children checked"); + } + + [Fact] + public void EveryMassiveChildKeepsACusp() + { + var checkedChildren = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + foreach (var parent in placed.Where(mass.ContainsKey)) + foreach (var child in ChildrenOf(zone, parent, placed).Where(mass.ContainsKey)) + { + checkedChildren++; + var cusp = 2 * CuspMargin * Roche(zone, mass[child]) * Strength(zone, mass[parent]) / Strength(zone, mass[child]); + Assert.True(DistanceOf(zone, child) >= cusp * (1 - CuspTolerance), $"seed {seed}: a massive child sits at {DistanceOf(zone, child)}, inside its cusp bound {cusp}"); + } + } + Assert.True(checkedChildren > 50, $"only {checkedChildren} massive children checked"); + } + + [Fact] + public void AFamilyEndsBeforeItsParentsFade() + { + var families = 0; + foreach (var (seed, zone) in _zones.All) + { + var placed = Placed(zone); + var mass = BodyMass(zone); + foreach (var node in placed.Where(k => zone.Orbits[k].Data.Parent.IsSet() && zone.Wells.Reach(k) > 0f)) + { + var kids = ChildrenOf(zone, node, placed); + if (!kids.Any(k => zone.Wells.Reach(k) > 0f)) continue; + families++; + Assert.True(zone.Wells.Support(node) <= GravityField.Gamma * zone.Wells.Reach(node) * (1 + Tolerance), + $"seed {seed}: a family's support {zone.Wells.Support(node)} runs past Gamma x its reach {zone.Wells.Reach(node)}"); + var parent = zone.Orbits[node].Data.Parent.Key; + if (mass.ContainsKey(parent)) // a ring member's reach is RingReach x D; a body's child's is Reach x D + Assert.True(Math.Abs(zone.Wells.Reach(node) - GravityField.Reach * DistanceOf(zone, node)) <= Tolerance * DistanceOf(zone, node), + $"seed {seed}: a family's reach {zone.Wells.Reach(node)} is not Reach x its distance {DistanceOf(zone, node)}"); + } + } + Assert.True(families > 20, $"only {families} families checked"); + } + + [Fact] + public void SiblingsSitHalfAReachApart() + { + var q = 1 / (1 - GravityField.Reach / 2); + var pairs = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + foreach (var parent in placed.Where(mass.ContainsKey)) + { + var kids = ChildrenOf(zone, parent, placed); + for (var k = 1; k < kids.Count; k++) + { + pairs++; + Assert.True(DistanceOf(zone, kids[k]) >= DistanceOf(zone, kids[k - 1]) * q * (1 - Tolerance), + $"seed {seed}: siblings at {DistanceOf(zone, kids[k - 1])} and {DistanceOf(zone, kids[k])} are closer than a factor {q}"); + } + } + } + Assert.True(pairs > 100, $"only {pairs} sibling pairs checked"); + } + + // The same random stream makes the same tree; only the window differs, so a small one (tight) folds some of what a huge one + // (wide) keeps whole. No rosette or binary: a bodyless node's own mass is renormalised with the rest. + private static IEnumerable<(uint Seed, GeneratorPlanet[] Tight, GeneratorPlanet[] Wide)> TightAndWideTrees(float mass) + { + var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); + var zoneSettings = authored.Read("ZoneSettings"); + var planetSettings = authored.Read("PlanetSettings"); + zoneSettings.RosetteProbability = 0; + zoneSettings.BinaryCreationProbability = 0; + for (uint seed = 1; seed <= 200; seed++) + { + var tight = new CultMath.Random(seed); + var tightTree = ZoneGenerator.GenerateEntities(zoneSettings, planetSettings, ref tight, mass, 1500f, float2.zero, float.PositiveInfinity); + var wide = new CultMath.Random(seed); + var wideTree = ZoneGenerator.GenerateEntities(zoneSettings, planetSettings, ref wide, mass, 1e7f, float2.zero, float.PositiveInfinity); + yield return (seed, tightTree, wideTree); + } + } + + // Folding moves a family's mass into its parent body, so a tree's masses still sum to its root's. + [Fact] + public void FoldingConservesMass() + { + const float mass = 300000f; + var folded = 0; + foreach (var (seed, tight, wide) in TightAndWideTrees(mass)) + { + if (tight.Length < wide.Length) folded++; + Assert.True(Math.Abs(tight.Sum(p => p.Mass) - mass) <= 1e-3f * mass, $"seed {seed}: a folded tree's bodies sum to {tight.Sum(p => p.Mass)}, not {mass}"); + } + _out.WriteLine($"folding: {folded} of 200 trees with a fold"); + Assert.True(folded > 10, $"only {folded} trees folded"); + } + + // Under one parent the families folded away are never heavier than the ones kept (rule 4: the lightest goes first). + [Fact] + public void FoldingTakesTheLightestFamily() + { + float Family(GeneratorPlanet p) => p.Mass + p.Children.Sum(Family); + var parentsThatFolded = 0; + foreach (var (seed, tight, wide) in TightAndWideTrees(300000f)) + { + var tightByPhase = tight.ToDictionary(p => p.Phase); + void Compare(GeneratorPlanet w) + { + if (w.Children.Count == 0 || !tightByPhase.TryGetValue(w.Phase, out var t)) return; + var keptPhases = t.Children.Select(c => c.Phase).ToHashSet(); + var kept = w.Children.Where(c => keptPhases.Contains(c.Phase)).ToList(); + var gone = w.Children.Where(c => !keptPhases.Contains(c.Phase)).ToList(); + if (gone.Count > 0 && kept.Count > 0) + { + parentsThatFolded++; + Assert.True(gone.Max(Family) <= kept.Min(Family) * (1 + 1e-4f), $"seed {seed}: a folded family outweighs one that was kept"); + } + foreach (var child in kept) Compare(child); + } + Compare(wide[0]); + } + Assert.True(parentsThatFolded > 10, $"only {parentsThatFolded} parents folded part of their children"); + } + + [Fact] + public void RingsKeepTheirMembersApartAndCircumbinaryChildrenFar() + { + var rings = 0; + var outer = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + foreach (var node in placed.Where(k => !mass.ContainsKey(k) && !zone.Planets.Values.Any(b => b.Orbit.Key.Equals(k)))) + { + var kids = ChildrenOf(zone, node, placed); + var members = kids.Where(mass.ContainsKey).ToList(); + if (members.Count < 2) continue; + var ring = members.Where(k => DistanceOf(zone, k) - DistanceOf(zone, members[0]) <= WellTree.RingWindow).ToList(); + if (ring.Count < 2) continue; + rings++; + var radius = DistanceOf(zone, ring[0]); + var heavy = ring.Max(k => mass[k]); + Assert.True(radius >= RocheMargin * Roche(zone, heavy) * (1 - Tolerance), + $"seed {seed}: a ring of radius {radius} sits inside its heavy member's Roche margin"); + foreach (var far in kids.Where(k => !ring.Contains(k))) + { + outer++; + Assert.True(DistanceOf(zone, far) >= (1 + GravityField.RingReach) * GravityField.Beta * radius * (1 - Tolerance), + $"seed {seed}: a circumbinary child at {DistanceOf(zone, far)} is inside the ring group of radius {radius}"); + } + } + } + Assert.True(rings > 3, $"only {rings} rings checked"); + _out.WriteLine($"rings {rings}, circumbinary children {outer}"); + } + + [Fact] + public void BeltsKeepTheirEdges() + { + var belts = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + foreach (var (beltKey, belt) in zone.AsteroidBelts) + { + belts++; + var orbit = zone.Planets[beltKey].Orbit.Key; + var parent = zone.Orbits[orbit].Data.Parent.Key; + var inner = belt.Data.Asteroids.Min(a => a.Distance); + var outermost = belt.Data.Asteroids.Max(a => a.Distance); + Assert.True(inner > 0f, $"seed {seed}: an asteroid sits at {inner}"); + if (mass.TryGetValue(parent, out var m)) + Assert.True(inner >= RocheMargin * Roche(zone, m) * (1 - Tolerance), $"seed {seed}: a belt's inner edge {inner} is inside its parent's Roche margin"); + // The belt keeps clear of its neighbours' rails by a sibling spacing (rule 3), inner and outer. + var sibling = ChildrenOf(zone, parent, Placed(zone)); + var at = sibling.IndexOf(orbit); + if (at > 0) + Assert.True(inner >= DistanceOf(zone, sibling[at - 1]) * (1 / (1 - GravityField.Reach / 2)) * (1 - Tolerance), $"seed {seed}: a belt reaches in to {inner}, within a spacing of its inner neighbour"); + if (at < sibling.Count - 1) + Assert.True(outermost <= DistanceOf(zone, sibling[at + 1]) * (1 - GravityField.Reach / 2) * (1 + Tolerance), $"seed {seed}: a belt reaches out to {outermost}, within a spacing of its outer neighbour"); + if (zone.Orbits[parent].Data.Parent.IsSet()) + Assert.True(outermost <= GravityField.Gamma * GravityField.Reach * DistanceOf(zone, parent) / Math.Max(GravityField.Beta, 1 + GravityField.Reach) * (1 + Tolerance), + $"seed {seed}: a belt reaches {outermost}, past its parent's window"); + } + } + Assert.True(belts > 20, $"only {belts} belts checked"); + } + + private static float Percentile(List sorted, float fraction) => sorted[Math.Min(sorted.Count - 1, (int) (fraction * sorted.Count))]; + + // A belt fills the slot between its neighbours' spacing, its parent's Roche margin and the parent's window, up to the + // authored width (ruling belt-fills-its-slot): it sits at the slot's midpoint where the test can spell both edges, and + // none collapses to a line (finding belts-collapse-to-a-line). Rocks are scattered inside the belt's half width, so their + // spread is at most the belt's width; a belt beside another belt has an edge only the generator knows, and is checked + // against the weaker bound. + [Fact] + public void BeltsFillTheirSlots() + { + var q = 1 / (1 - GravityField.Reach / 2); + var ratios = new List(); + int belts = 0, bounded = 0, midpoints = 0, lines = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + var beltAt = zone.AsteroidBelts.ToDictionary(b => zone.Planets[b.Key].Orbit.Key, b => b.Value.Data.Asteroids); + foreach (var (orbit, rocks) in beltAt) + { + var parent = zone.Orbits[orbit].Data.Parent.Key; + if (rocks.Length == 0 || !mass.TryGetValue(parent, out var parentMass)) continue; + belts++; + var sibling = ChildrenOf(zone, parent, placed); + var at = sibling.IndexOf(orbit); + var d = DistanceOf(zone, orbit); + var spread = rocks.Max(a => a.Distance) - rocks.Min(a => a.Distance); + var width = _zones.Settings.AsteroidBeltWidth.Evaluate(d); + ratios.Add(spread / width); + if (spread < 1e-3f) lines++; + + var prevIsBelt = at > 0 && beltAt.ContainsKey(sibling[at - 1]); + var nextIsBelt = at < sibling.Count - 1 && beltAt.ContainsKey(sibling[at + 1]); + var prevEdge = at == 0 ? 0f : prevIsBelt && beltAt[sibling[at - 1]].Length > 0 ? beltAt[sibling[at - 1]].Max(a => a.Distance) : DistanceOf(zone, sibling[at - 1]); + var inner = Math.Max(RocheMargin * Roche(zone, parentMass), prevEdge * q); + var grand = zone.Orbits[parent].Data.Parent; + var window = grand.IsSet() ? GravityField.Gamma * GravityField.Reach * DistanceOf(zone, parent) / Math.Max(GravityField.Beta, 1 + GravityField.Reach) : float.PositiveInfinity; + var next = at < sibling.Count - 1 && !nextIsBelt ? DistanceOf(zone, sibling[at + 1]) / q : float.PositiveInfinity; + var outerLimit = Math.Min(window, next); + if (!nextIsBelt) bounded++; + Assert.True(spread <= Math.Min(width, outerLimit - inner) * (1 + Tolerance), + $"seed {seed}: a belt spreads {spread} in a slot of {outerLimit - inner} and an authored width of {width}"); + // Past the last sibling a root's window is its own to spell, and a ring member's child is held by a chord as well. + var upperKnown = at < sibling.Count - 1 || (grand.IsSet() && mass.ContainsKey(grand.Key)); + if (prevIsBelt || nextIsBelt || !upperKnown) continue; + midpoints++; + Assert.True(Math.Abs(d - (inner + outerLimit) / 2) <= Tolerance * d, + $"seed {seed}: a belt at {d} is not the midpoint {(inner + outerLimit) / 2} of its slot [{inner}, {outerLimit}]"); + } + } + ratios.Sort(); + _out.WriteLine($"belts {belts}, with a slot bound {bounded}, midpoints checked {midpoints}, rock spread under 0.001: {lines}; " + + $"spread / authored width at p10/25/50/75/90/max: {string.Join(" / ", new[] { .1f, .25f, .5f, .75f, .9f }.Select(f => Percentile(ratios, f).ToString("F3")))} / {ratios[ratios.Count - 1]:F3}"); + Assert.True(belts > 20 && bounded > 0 && midpoints > 0, $"{belts} belts, {bounded} bounded, {midpoints} midpoints: the seeds do not exercise the rule"); + Assert.True(lines == 0, $"{lines} of {belts} belts have no radial width"); + } + + // With the authored width narrower than the slot the width is the ceiling and the belt keeps it: neither wider (W/2 -> W, a + // deleted cap) nor reduced to the slot. + [Fact] + public void ANarrowAuthoredBeltKeepsItsWidth() + { + var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()).Read("ZoneSettings").AsteroidBeltWidth; + using var narrow = new Zones(1, 3, z => z.AsteroidBeltWidth = new ExponentialCurve + { Exponent = authored.Exponent, Multiplier = authored.Multiplier * .02f, Constant = authored.Constant * .02f }); + int belts = 0, filled = 0; + foreach (var (seed, zone) in narrow.All) + foreach (var (key, belt) in zone.AsteroidBelts) + { + var rocks = belt.Data.Asteroids; + if (rocks.Length < 2) continue; + var width = narrow.Settings.AsteroidBeltWidth.Evaluate(DistanceOf(zone, zone.Planets[key].Orbit.Key)); + var spread = rocks.Max(a => a.Distance) - rocks.Min(a => a.Distance); + belts++; + Assert.True(spread <= width * (1 + Tolerance), $"seed {seed}: a belt spreads {spread}, past its authored width {width}"); + if (spread >= .5f * width) filled++; + } + _out.WriteLine($"narrow belts {belts}, spreading at least half the authored width {filled}"); + Assert.True(filled >= 10, $"only {filled} of {belts} belts fill the authored width"); + } + + private static GeneratorPlanet Body(GeneratorPlanet parent, float mass, float phase = 0, bool ring = false) + { + var node = new GeneratorPlanet { Parent = parent, Mass = mass, Phase = phase, Ring = ring }; + parent.Children.Add(node); + return node; + } + + private static PlanetSettings AuthoredPlanetSettings() => AuthoredSettings.Load(RunStartTests.FindRepoRoot()).Read("PlanetSettings"); + + // A rosette's ring round a root with no reach limit of its own sits at half the root's 0.75 x radius window, 3/8 of the radius. + [Fact] + public void ASoleRootRingSitsAtThreeEighthsOfItsRadius() + { + const float radius = 1e6f; + var root = new GeneratorPlanet { Empty = true }; + var members = new[] { Body(root, 100f, 0, true), Body(root, 100f, .5f, true) }; + ZoneGenerator.Place(root, AuthoredPlanetSettings(), radius, float.PositiveInfinity); + Assert.True(root.Empty && root.Children.Count == 2, "the ring folded into its node"); + foreach (var member in members) + Assert.True(Math.Abs(member.Distance - .375f * radius) <= 1e-4f * radius, $"a ring member sits at {member.Distance}, not {.375f * radius}"); + } + + // A ring member's children end within a fifth of the chord to the member's nearest partner, where the chord, not the member's + // fade, is what holds them. + [Fact] + public void ARingMembersChildrenStayWithinAFifthOfTheChord() + { + const float radius = 1e6f; + const int count = 12; + var root = new GeneratorPlanet { Empty = true }; + var members = Enumerable.Range(0, count).Select(i => Body(root, 100f, (float) i / count, true)).ToList(); + foreach (var member in members) { Body(member, 10f); Body(member, 10f); } + ZoneGenerator.Place(root, AuthoredPlanetSettings(), radius, float.PositiveInfinity); + foreach (var member in members) + { + Assert.True(root.Children.Count == count && member.Children.Count == 2, "a ring member or its children folded"); + var chord = .2f * 2 * member.Distance * (float) Math.Sin(Math.PI / count); + var fade = GravityField.Gamma * GravityField.Reach * member.Distance / Math.Max(GravityField.Beta, 1 + GravityField.Reach); + Assert.True(chord < fade, "the fade, not the chord, would hold these children"); + var outermost = member.Children.Max(c => c.Distance); + Assert.True(Math.Abs(outermost - chord) <= 1e-4f * chord, $"a ring member's outermost child sits at {outermost}, not at the chord's fifth {chord}"); + } + } + + [Fact] + public void NoStrengthlessOrbitRidesARing() + { + var rings = 0; + foreach (var (seed, zone) in _zones.All) + { + var mass = BodyMass(zone); + var placed = Placed(zone); + foreach (var node in placed.Where(k => !mass.ContainsKey(k) && !zone.Planets.Values.Any(b => b.Orbit.Key.Equals(k)))) + { + var members = ChildrenOf(zone, node, placed).Where(mass.ContainsKey).ToList(); + if (members.Count < 2) continue; + rings++; + var radius = DistanceOf(zone, members[0]); + // Every orbit of the zone, stations and turrets included, that hangs on the node and carries no body. + foreach (var orbit in zone.Orbits.Keys.Where(k => zone.Orbits[k].Data.Parent.IsSet() && zone.Orbits[k].Data.Parent.Key.Equals(node) && !mass.ContainsKey(k))) + Assert.True(DistanceOf(zone, orbit) >= (1 + GravityField.RingReach) * radius * (1 - Tolerance), + $"seed {seed}: a strengthless orbit at {DistanceOf(zone, orbit)} rides the ring group of radius {radius}"); + } + } + Assert.True(rings > 3, $"only {rings} rings checked"); + } +} diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index fd522e357..e77d6c89b 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -820,7 +820,7 @@ public sealed partial class MiningCut3Tests : IDisposable var items = new ItemManager(cache, new ProvenanceLedger(), GameSettings(), _ => { }); foreach (var zone in galaxy.Zones.Take(4)) { - var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance); + var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance); foreach (var body in pack.Planets) { if (!(cache.Get(body) is AsteroidBeltData belt)) continue; diff --git a/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs b/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs index fea0d84c6..6a3b1c618 100644 --- a/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs +++ b/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs @@ -150,41 +150,6 @@ public sealed class OrbitsFromFieldTests : IDisposable Assert.Equal(zone.Orbits[planet2].Period, zone.Orbits[companion2].Period); } - // A station on a binary's ring, with nothing inside, feels what the pair's members feel (the mean of what each does), - // and so does one a hair off the ring's distance but within its window. - [Theory] - [InlineData(0f)] - [InlineData(.05f)] - [InlineData(-.05f)] - public void ACompanionOnABinarysRingTakesTheMembersPeriod(float offset) - { - var w = NewWorld(); - var node = w.Orbit(default, 0f); - var light = w.Orbit(node, 400f, 0f); - var heavy = w.Orbit(node, 400f, .5f); - var lightBody = w.Body(light, 100f); - var heavyBody = w.Body(heavy, 2000f); - var companion = w.Orbit(node, 400f + offset, .25f); - var zone = w.Build(); - - Assert.True(C(zone, heavyBody) > 1.5f * C(zone, lightBody), "fixture: unequal members"); - AssertPeriod(PeriodUnder((Pull(zone, lightBody, 800f) + Pull(zone, heavyBody, 800f)) / 2, 400f + offset), zone.Orbits[companion].Period, - "the companion, between its two members"); - - // An equal pair: the companion has the members' period. - w = NewWorld(); - node = w.Orbit(default, 0f); - var a = w.Orbit(node, 400f, 0f); - var b = w.Orbit(node, 400f, .5f); - w.Body(a, 300f); - w.Body(b, 300f); - companion = w.Orbit(node, 400f, .25f); - zone = w.Build(); - Assert.True(float.IsFinite(zone.Orbits[a].Period)); - AssertPeriod(zone.Orbits[a].Period, zone.Orbits[companion].Period, "the companion, against the first member"); - AssertPeriod(zone.Orbits[b].Period, zone.Orbits[companion].Period, "the companion, against the second member"); - } - // The ring is the 0.1 u window about the innermost massive distance: a member just inside it is a ring partner (felt at // the chord), one just outside it is not a partner and the rail has the node's own terms alone, which give a // ring's own member next to no pull. @@ -291,7 +256,7 @@ public sealed class OrbitsFromFieldTests : IDisposable authored.Read("NameGeneratorSettings"), cache, new PlayerSettings(), Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); var items = new ItemManager(cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), galaxy, galaxy.Entrance, + var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, galaxy.IsPrelude, false); var zone = new Zone(items, authored.Read("PlanetSettings"), pack, galaxy.Entrance, galaxy); diff --git a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs index 217be696a..6711f894a 100644 --- a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs +++ b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs @@ -57,9 +57,10 @@ public sealed class RestoredHullsTests // Shared tutorial-galaxy construction settings (Assets/Resources/Settings.asset's own values), factored out // so every test that needs a real tutorial Galaxy -- not just EntranceZoneAlwaysGetsADockedStationAcrossSeeds // -- builds it the same way instead of re-inlining the same ~20 fields. + internal static PlanetSettings AuthoredPlanetSettings() => AuthoredSettings.Load(RunStartTests.FindRepoRoot()).Read("PlanetSettings"); + internal static ZoneGenerationSettings TutorialZoneSettings() => new ZoneGenerationSettings { - PlanetSafetyRadius = new ExponentialCurve { Exponent = .25f, Multiplier = 2.5f, Constant = 0 }, MassFloor = 1, SunMass = 5000, GasGiantMass = 1000, PlanetMass = 100, SatellitePasses = 5, SatelliteCreationMassFloor = 100, SatelliteCreationProbability = .25f, BinaryCreationProbability = .1f, RosetteProbability = .1f, @@ -156,7 +157,7 @@ public sealed class RestoredHullsTests cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); foreach (var zone in galaxy.Zones.Where(z => !ReferenceEquals(z, galaxy.Entrance))) { - var orbits = ParentedPlanetOrbits(cache, ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, zone, isTutorial: false, ambient: false)); + var orbits = ParentedPlanetOrbits(cache, ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial: false, ambient: false)); if (orbits.Length > 0 && !HasGenuineLagrangeCandidate(orbits)) return (seed, zone.Name); } } @@ -377,7 +378,7 @@ public sealed class RestoredHullsTests var galaxy = new Galaxy(tutorialSettings, background, names, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); var dockedStation = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -418,7 +419,7 @@ public sealed class RestoredHullsTests var galaxy = new Galaxy(tutorialSettings, background, names, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); var planetOrbits = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Where(o => o.Parent.IsSet()).ToArray(); var hasGenuineCandidate = planetOrbits.Any(o => planetOrbits.Count(c => c.Parent.Key.Equals(o.Parent.Key) && abs(c.Distance - o.Distance) < .1f) == 1); @@ -460,9 +461,11 @@ public sealed class RestoredHullsTests var zoneSettings = TutorialZoneSettings(); zoneSettings.RosetteProbability = 0; zoneSettings.MassFloor = 1e9f; + // One subzone: the zone's only body is a parentless root. (Several roots give the station a root to orbit.) + zoneSettings.SubZoneCount = new ExponentialLerp { Exponent = 1, Minimum = 0, Maximum = 0 }; Assert.Throws(() => - ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, galaxy.Entrance, isTutorial: true)); + ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true)); } finally { @@ -497,13 +500,10 @@ public sealed class RestoredHullsTests zoneSettings.SatelliteCreationProbability = 0; zoneSettings.BinaryCreationProbability = 0; - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); - var roots = pack.Planets.Select(p => cache.Get(p).Orbit) - .Select(cache.Get) - .Select(o => o.Parent.IsSet() ? o.Parent.Key.Value : "(root)") - .Distinct().Count(); - Assert.True(roots > 1, $"this fixture no longer produces a multi-root entrance (only {roots} distinct parent); it no longer tests the fragmented-topology case."); + var roots = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Count(o => !o.Parent.IsSet()); + Assert.True(roots > 1, $"this fixture no longer produces a multi-root entrance (only {roots} root); it no longer tests the fragmented-topology case."); var stations = pack.Entities.OfType() .Where(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station).ToArray(); @@ -545,7 +545,7 @@ public sealed class RestoredHullsTests var galaxy = new Galaxy(tutorialSettings, background, names, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); var dockedStation = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -740,7 +740,7 @@ public sealed class RestoredHullsTests var galaxy = BuildGalaxyWithForcedEntrance(cache, seed, zoneName); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); var station = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -749,7 +749,11 @@ public sealed class RestoredHullsTests // Confirms this fixture still exercises the widened path (a regression here would mean the fixture no // longer probes what this test claims to probe). - Assert.True(IsRosetteMember(cache, pack, stationOrbit), "the entrance station no longer sits on a rosette-only orbit -- this fixture no longer tests the widened candidate path."); + // The zone has no body alone on its ring, so the station orbits the root node beyond its ring group. + var rootOrbit = cache.Get(stationOrbit.Parent); + Assert.False(rootOrbit.Parent.IsSet(), "the entrance station no longer orbits a root node -- this fixture no longer tests the no-candidate path."); + var ring = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Where(o => o.Parent.IsSet() && o.Parent.Key.Equals(stationOrbit.Parent.Key)).Select(o => o.Distance).DefaultIfEmpty(0f).Min(); + Assert.True(stationOrbit.Distance >= (1 + GravityField.RingReach) * GravityField.Beta * ring * .999f, $"the entrance station at {stationOrbit.Distance} sits inside its node's ring group of radius {ring}."); var turrets = pack.Entities.OfType() .Where(e => (cache.Get(e.Hull.Data) as HullData)?.HullType != HullType.Station).ToArray(); @@ -790,7 +794,7 @@ public sealed class RestoredHullsTests var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); int StationCount(GalaxyZone zone, bool isTutorial) => - ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, zone, isTutorial) + ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial) .Entities.OfType() .Count(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station); @@ -830,7 +834,7 @@ public sealed class RestoredHullsTests cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); var stationCount = pack.Entities.OfType().Count(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station); // Soul's finding (this cut's fix batch 3): pack.Entities.OfType().Count() also counts the // zone's neutral wanderers (ZoneGenerator.cs's own EligibleWandererFactions spawn, keyed to @@ -914,7 +918,7 @@ public sealed class RestoredHullsTests Assert.NotSame(galaxy.Entrance, zone); var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, zone, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial: true); // Confirms this fixture still has no genuine (non-rosette) Lagrange candidate -- a regression here // would mean the fixture no longer probes what this test claims to probe. diff --git a/tests/Aetheria.Shared.Tests/RunGoalTests.cs b/tests/Aetheria.Shared.Tests/RunGoalTests.cs index ed96732c9..25b46fdd3 100644 --- a/tests/Aetheria.Shared.Tests/RunGoalTests.cs +++ b/tests/Aetheria.Shared.Tests/RunGoalTests.cs @@ -19,7 +19,7 @@ public sealed partial class RunStartTests private ZonePack BossZonePack(Galaxy galaxy, ItemManager items, GalaxyZone zone, bool ambient = true) { items.Random = new CultMath.Random(7); - return ZoneGenerator.GenerateZone(items, _zoneSettings, galaxy, zone, galaxy.IsPrelude, ambient); + return ZoneGenerator.GenerateZone(items, _zoneSettings, _planetSettings, galaxy, zone, galaxy.IsPrelude, ambient); } private Zone ZoneOf(Galaxy galaxy, GalaxyZone zone) => diff --git a/tests/Aetheria.Shared.Tests/RunStartTests.cs b/tests/Aetheria.Shared.Tests/RunStartTests.cs index 18286649d..2ce12782e 100644 --- a/tests/Aetheria.Shared.Tests/RunStartTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartTests.cs @@ -78,7 +78,7 @@ public sealed partial class RunStartTests : IDisposable // The fixture galaxy's arena, with or without its generated ships and turrets. private Zone Arena(bool ambient) => - new Zone(_items, _planetSettings, RunStart.GenerateArena(_items, _zoneSettings, _galaxy, new Scripted(ambient, _ => { })), _galaxy.Entrance, _galaxy); + new Zone(_items, _planetSettings, RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new Scripted(ambient, _ => { })), _galaxy.Entrance, _galaxy); private HullData Hull(string name) => _cache.GetAll().Single(hull => hull.Name == name); @@ -311,8 +311,14 @@ public sealed partial class RunStartTests : IDisposable [Fact] public void NoOrbitStandsStillAgainstItsParent() { - var zone = Arena(false); // no ships: nothing but the zone runs - Assert.True(zone.AsteroidBelts.Count > 0, "the arena has an asteroid belt to race against"); + // No ships: nothing but the zone runs. Belts are rarer than they were, so the first galaxy seed whose entrance holds one. + Zone zone = null; + for (uint seed = GalaxySeed; zone == null && seed < GalaxySeed + 60; seed++) + { + var (_, arena, _, _) = Launch(new Scripted(false, _ => { }, seed), Inputs()); + if (arena.AsteroidBelts.Count > 0) zone = arena; + } + Assert.True(zone != null, "no arena of the first 60 seeds has an asteroid belt to race against"); float2 Relative(Orbit orbit, bool previous) => (previous ? orbit.PreviousPosition : orbit.Position) - (zone.Orbits.TryGetValue(orbit.Data.Parent.Key, out var parent) ? previous ? parent.PreviousPosition : parent.Position : orbit.Data.FixedPosition); @@ -673,7 +679,7 @@ public sealed partial class RunStartTests : IDisposable [Fact] public void AdmitIsTheOnlyAgentCreator() { - var pack = RunStart.GenerateArena(_items, _zoneSettings, _galaxy, new Scripted(true, _ => { })); + var pack = RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new Scripted(true, _ => { })); var packedPlayer = pack.Entities.OfType().First(); packedPlayer.IsPlayerShip = true; var zone = new Zone(_items, _planetSettings, pack, _galaxy.Entrance, _galaxy); diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index 66deaea9a..8e435d2f0 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -64,7 +64,7 @@ public sealed partial class RunStartTests private (Galaxy galaxy, Zone arena, RunStart.Staged staged, List failures) Launch(Scenario scenario, GalaxyStage inputs = null, Action beforeStaging = null) { var galaxy = RunStart.Generate(scenario, inputs ?? Inputs()); - var arena = new Zone(_items, _planetSettings, RunStart.GenerateArena(_items, _zoneSettings, galaxy, scenario), galaxy.Entrance, galaxy); + var arena = new Zone(_items, _planetSettings, RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, galaxy, scenario), galaxy.Entrance, galaxy); beforeStaging?.Invoke(); var failures = new List(); var staged = RunStart.Stage(_items, arena, scenario, _startingHull, _tutorialSettings, failures); @@ -392,8 +392,8 @@ public sealed partial class RunStartTests { Zone = _galaxy.Entrance, Name = "story", Type = LocationType.Station, Faction = _protagonist, Turrets = 2 }); - var ambient = Census(RunStart.GenerateArena(_items, _zoneSettings, _galaxy, new Scripted(true, _ => { }))); - var quietPack = RunStart.GenerateArena(_items, _zoneSettings, _galaxy, new Scripted(false, _ => { })); + var ambient = Census(RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new Scripted(true, _ => { }))); + var quietPack = RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new Scripted(false, _ => { })); var quiet = Census(quietPack); Assert.Same(quietPack, _galaxy.Entrance.PackedContents); diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index 52bd650f7..759e3e83d 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -5,6 +5,7 @@ using System.Linq; using CultMath; using GameCult.Caching; using Xunit; +using Xunit.Abstractions; using static CultMath.math; using float2 = CultMath.float2; @@ -16,8 +17,15 @@ public sealed class StationPlacementTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-stationplacement-" + Guid.NewGuid().ToString("N")); private readonly List _caches = new List(); + private int _generation; - public StationPlacementTests() => Directory.CreateDirectory(_root); + private readonly ITestOutputHelper _output; + + public StationPlacementTests(ITestOutputHelper output) + { + _output = output; + Directory.CreateDirectory(_root); + } public void Dispose() { @@ -29,11 +37,12 @@ public sealed class StationPlacementTests : IDisposable // stock may rearrange the catalog before a galaxy is generated; storyTurrets > 0 gives every zone a story station that // authors that many turrets (the '#turrets' tag), the way a narrative does. - private IEnumerable GeneratedZones(Action stock = null, int storyTurrets = 0, uint seeds = 6, int zonesPerSeed = int.MaxValue) + private IEnumerable GeneratedZones(Action stock = null, int storyTurrets = 0, uint seeds = 6, int zonesPerSeed = int.MaxValue, + Action tune = null, bool entranceOnly = false) { for (uint seed = 1; seed <= seeds; seed++) { - var dir = Path.Combine(_root, $"galaxy{seed}"); + var dir = Path.Combine(_root, $"galaxy{seed}-{_generation++}"); Directory.CreateDirectory(dir); var catalog = Path.Combine(dir, "Aetheria.cc"); File.Copy(TestCatalog.Repo, catalog); @@ -49,11 +58,13 @@ public sealed class StationPlacementTests : IDisposable Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); var items = new ItemManager(cache, new ProvenanceLedger(), settings, _ => { }); stock?.Invoke(items); - foreach (var galaxyZone in galaxy.Zones.Take(zonesPerSeed)) + foreach (var galaxyZone in entranceOnly ? new[] { galaxy.Entrance } : galaxy.Zones.Take(zonesPerSeed)) { if (storyTurrets > 0) galaxyZone.Locations.Add(new LocationStory { Zone = galaxyZone, Name = "Test station", Faction = galaxy.Factions[0], Type = LocationType.Station, Turrets = storyTurrets }); - var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), galaxy, galaxyZone, + var zoneSettings = authored.Read("ZoneSettings"); + tune?.Invoke(zoneSettings); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, authored.Read("PlanetSettings"), galaxy, galaxyZone, galaxyZone == galaxy.Entrance && galaxy.IsPrelude, true); var zone = new Zone(items, authored.Read("PlanetSettings"), pack, galaxyZone, galaxy); zone.Update(.02f); @@ -74,6 +85,7 @@ public sealed class StationPlacementTests : IDisposable public void AStationSitsAtItsPlanetsL4OrL5() { var checkedStations = 0; + var rootStations = 0; var ahead = 0; var behind = 0; foreach (var built in GeneratedZones()) @@ -85,7 +97,21 @@ public sealed class StationPlacementTests : IDisposable { var orbit = zone.Orbits[station.OrbitData]; var sources = zone.Orbits.Where(o => !ridden.Contains(o.Key) && SameRing(o.Value, orbit)).ToList(); + if (sources.Count == 0) + { + // The tutorial entrance's one exception: a station on its own orbit round a root node, beyond the node's ring + // group (or, for a body, its whole family), at no Lagrange point. + var rootKey = orbit.Data.Parent.Key; + Assert.False(zone.Orbits[rootKey].Data.Parent.IsSet(), $"seed {built.Seed}: a station with no source orbit does not orbit a root node"); + var innermost = zone.Orbits.Where(o => o.Value.Data.Parent.IsSet() && o.Value.Data.Parent.Key.Equals(rootKey) && zone.Wells.Reach(o.Key) > 0f && !o.Key.Equals(station.OrbitData)) + .Select(o => o.Value.Data.Distance).DefaultIfEmpty(0f).Min(); + Assert.True(orbit.Data.Distance >= zone.Wells.Support(rootKey) * .999f || orbit.Data.Distance >= (1 + GravityField.RingReach) * GravityField.Beta * innermost * .999f, + $"seed {built.Seed}: a root-node station at {orbit.Data.Distance} sits inside its node's family"); + rootStations++; + continue; + } Assert.True(sources.Count == 1, $"seed {built.Seed}: a station shares its ring with {sources.Count} unridden orbits, not one"); + Assert.Contains(zone.Planets.Values, b => b.Orbit.Key.Equals(sources[0].Key) && !(b is AsteroidBeltData)); var planet = sources[0].Value; var offset = Turns(orbit.Data.Phase - planet.Data.Phase); @@ -103,9 +129,100 @@ public sealed class StationPlacementTests : IDisposable } } Assert.True(checkedStations > 0, "the seeds generated no station"); + Assert.True(rootStations == 0 || rootStations < checkedStations, "every station is a root-node fallback"); Assert.True(ahead > 0 && behind > 0, $"the seeds put stations on one side only (ahead {ahead}, behind {behind})"); } + // A binary is a bodyless node under its parent; the station's source is never such a node, however many binaries there are. + [Fact] + public void AStationNeverSitsOnABinarysBodylessNode() + { + var binaries = 0; + var stations = 0; + foreach (var built in GeneratedZones(null, 0, 4, int.MaxValue, z => { z.SatelliteCreationProbability = 1; z.BinaryCreationProbability = 1; })) + { + var zone = built.Zone; + var bodyOrbits = zone.Planets.Values.Select(b => b.Orbit.Key).ToHashSet(); + binaries += zone.Orbits.Count(o => o.Value.Data.Parent.IsSet() && !bodyOrbits.Contains(o.Key) && zone.Wells.Reach(o.Key) > 0f); + var ridden = zone.Entities.OfType().Select(e => e.OrbitData).ToHashSet(); + foreach (var station in Orbitals(built).Where(e => TypeOf(built.Items, e) == HullType.Station)) + { + var orbit = zone.Orbits[station.OrbitData]; + var sources = zone.Orbits.Where(o => !ridden.Contains(o.Key) && SameRing(o.Value, orbit)).ToList(); + if (sources.Count == 0) continue; // the tutorial entrance's own orbit round a root + stations++; + Assert.Contains(bodyOrbits, key => key.Equals(sources[0].Key)); + } + } + Assert.True(binaries > 5 && stations > 5, $"{binaries} bodyless nodes and {stations} stations: the seeds do not exercise the rule"); + } + + // The zone's own well tree counts a station's rail as a member of its root's family, so the extent the generator checked + // (the bodies' alone) is rebuilt here from the generated bodies' orbits and their ancestors. + private static float ExtentOfBodies(Zone zone, CultRecordKey orbit) + { + var mass = zone.Planets.Values.Where(b => !(b is AsteroidBeltData)).GroupBy(b => b.Orbit.Key).ToDictionary(g => g.Key, g => g.First().Mass); + var placed = new HashSet(); + foreach (var body in zone.Planets.Values) + for (var key = body.Orbit.Key; placed.Add(key) && zone.Orbits[key].Data.Parent.IsSet();) key = zone.Orbits[key].Data.Parent.Key; + var beltExtent = zone.AsteroidBelts.ToDictionary(b => zone.Planets[b.Key].Orbit.Key, b => b.Value.Data.Asteroids.Select(a => a.Distance).DefaultIfEmpty(0f).Max()); + var nodes = placed.Select(k => + { + var d = zone.Orbits[k].Data; + return new WellNode(k, d.Parent.Key, d.Distance, d.Phase, mass.TryGetValue(k, out var m) ? m : 0f, + beltExtent.TryGetValue(k, out var e) ? Math.Max(e, d.Distance) : d.Distance, d.FixedPosition + OrbitData.Evaluate(frac(d.Phase)) * d.Distance); + }).ToList(); + var wells = WellTree.Build(nodes, zone.Settings, zone.Pack.Radius); + return Math.Max(wells.Support(orbit), 1.5f * zone.Settings.RocheLimit.Evaluate(mass[orbit])); + } + + // How far a body keeps others out: its family's support, or 1.5 Roche limits (tail-taming-law-r3-band-loose-cusp) if more. + private static float BaseExtent(Zone zone, CultRecordKey orbit) + { + var body = zone.Planets.Values.FirstOrDefault(b => b.Orbit.Key.Equals(orbit) && !(b is AsteroidBeltData)); + return Math.Max(zone.Wells.Support(orbit), body == null ? 0f : 1.5f * zone.Settings.RocheLimit.Evaluate(body.Mass)); + } + + // Over 64 instants of the longest period in the zone, no station or turret centre is within 1.5 Roche limits plus its + // reach of any body other than its base (station-orbit-choice-residuals item 1). + [Fact] + public void NoStationOrTurretSitsOnAnUnrelatedBody() + { + var checkedEntities = 0; + foreach (var built in GeneratedZones()) + { + var zone = built.Zone; + var longest = zone.Orbits.Values.Select(o => o.Period).Where(float.IsFinite).DefaultIfEmpty(1f).Max(); + var bodies = zone.Planets.Values.Where(b => !(b is AsteroidBeltData)).ToList(); + foreach (var entity in Orbitals(built).Where(e => TypeOf(built.Items, e) is HullType.Station or HullType.Turret)) + { + var orbit = zone.Orbits[entity.OrbitData]; + checkedEntities++; + foreach (var body in bodies) + { + var bodyOrbit = zone.Orbits[body.Orbit.Key]; + if (SameRing(bodyOrbit, orbit)) continue; // its base + if (IsAncestorBody(zone, orbit, body.Orbit.Key)) continue; // the body it orbits round: it keeps its distance by its own Roche margin + var margin = 1.5f * zone.Settings.RocheLimit.Evaluate(body.Mass) + Contacts.Radius(entity); + for (var k = 0; k < 64; k++) + { + var t = k / 64.0 * longest; + Assert.True(length(zone.OrbitPositionAt(entity.OrbitData, t) - zone.OrbitPositionAt(body.Orbit.Key, t)) >= margin * .999f, + $"seed {built.Seed}: a {TypeOf(built.Items, entity)} on a ring of {orbit.Data.Distance} passes within {margin} of an unrelated body (mass {body.Mass}, ring {bodyOrbit.Data.Distance}, same parent {bodyOrbit.Data.Parent.Key.Equals(orbit.Data.Parent.Key)}) at instant {k}"); + } + } + } + } + Assert.True(checkedEntities > 0, "the seeds generated no station"); + } + + private static bool IsAncestorBody(Zone zone, Orbit orbit, CultRecordKey bodyOrbit) + { + for (var parent = orbit.Data.Parent; parent.IsSet(); parent = zone.Orbits[parent.Key].Data.Parent) + if (parent.Key.Equals(bodyOrbit)) return true; + return false; + } + private static List Orbitals(Built built) => built.Zone.Entities.OfType().ToList(); // Every turret belongs to one station on its ring. Each side of a station grows outward from it: a turret's centre sits @@ -139,8 +256,7 @@ public sealed class StationPlacementTests : IDisposable var behind = arcs.Where(a => a.arc < 0).OrderByDescending(a => a.arc).ToList(); var ahead = arcs.Where(a => a.arc > 0).OrderBy(a => a.arc).ToList(); // Turrets alternate behind then ahead, so behind holds the extra one when the count is odd. - Assert.Equal((mine.Count + 1) / 2, behind.Count); - Assert.Equal(mine.Count / 2, ahead.Count); + // (A side whose next turret would reach the base body stops, so the sides need not stay level.) if (mine.Select(Contacts.Radius).Distinct().Count() > 1) mixedReach++; foreach (var (side, sign) in new[] { (behind, -1f), (ahead, 1f) }) @@ -157,6 +273,17 @@ public sealed class StationPlacementTests : IDisposable } } + // No turret reaches its base body: the planet whose Lagrange orbit the station rides (the ring's one unridden orbit). + var ridden = built.Zone.Entities.OfType().Select(e => e.OrbitData).ToHashSet(); + var source = built.Zone.Orbits.Where(o => !ridden.Contains(o.Key) && SameRing(o.Value, orbit)).Select(o => o.Key).ToList(); + if (source.Count == 1) + { + var extent = BaseExtent(built.Zone, source[0]); + foreach (var turret in mine) + Assert.True(length(turret.Position.xz - built.Zone.Orbits[source[0]].Position) >= (extent + Contacts.Radius(turret)) * .999f, + $"seed {built.Seed}: a turret sits within the base body's extent {extent} and its reach of the base"); + } + var bodies = new List { station }; bodies.AddRange(mine); for (var a = 0; a < bodies.Count; a++) @@ -193,13 +320,15 @@ public sealed class StationPlacementTests : IDisposable [Fact] public void ANarrativeStationsTurretsKeepFlankingAndClearEachOtherWhateverTheirReach() { - const int authored = 5; - var flanked = 0; + var flanked = 0; var mixed = 0; - var most = 0; - foreach (var built in GeneratedZones(WithALargerTurretHull, authored, 3, 3)) - most = Math.Max(most, AssertFlanks(built, ref flanked, ref mixed)); - Assert.True(most == authored, $"no story station carried its {authored} authored turrets (most {most})"); + foreach (var authored in new[] { 3, 5, 9 }) + { + var most = 0; + foreach (var built in GeneratedZones(WithALargerTurretHull, authored, 6, 6)) + most = Math.Max(most, AssertFlanks(built, ref flanked, ref mixed)); + Assert.True(most > 0 && most <= authored, $"the most turrets a station carried is {most} of {authored} authored"); + } Assert.True(mixed > 0, "no station carried turrets of differing reach"); } @@ -224,6 +353,84 @@ public sealed class StationPlacementTests : IDisposable Assert.True(stations > 0, "the seeds generated no station"); } + + // A side of a station grows outward until its next turret would sit within the base body's extent plus that turret's reach of + // the base (story-turret-tail-clearance). With a single wide turret hull on offer and sixteen story turrets a station + // reaches the base: a side that placed fewer than its half stopped, and its would-be next turret, spelled from the zone, is + // inside that distance. Ambient stations carry at most two turrets, so only a station with three or more is a story one. + [Fact] + public void ATurretTailStopsAtItsBaseBody() + { + const int turrets = 16; + int stations = 0, ambiguous = 0, sides = 0, stops = 0, nearBase = 0; + foreach (var built in GeneratedZones(WithOnlyAWiderTurretHull, turrets, 6)) + { + var zone = built.Zone; + var orbitals = Orbitals(built); + var ridden = orbitals.Select(e => e.OrbitData).ToHashSet(); + foreach (var station in orbitals.Where(e => TypeOf(built.Items, e) == HullType.Station)) + { + var orbit = zone.Orbits[station.OrbitData]; + var mine = orbitals.Where(e => TypeOf(built.Items, e) == HullType.Turret && SameRing(zone.Orbits[e.OrbitData], orbit)).ToList(); + var source = zone.Orbits.Where(o => !ridden.Contains(o.Key) && SameRing(o.Value, orbit)).Select(o => o.Key).ToList(); + if (mine.Count < 3 || source.Count != 1) continue; + var extent = BaseExtent(zone, source[0]); + var reach = Contacts.Radius(mine[0]); + var circumference = 2 * PI * orbit.Data.Distance; + var arcs = mine.Select(t => { var turn = Turns(zone.Orbits[t.OrbitData].Data.Phase - orbit.Data.Phase); return (turn > .5f ? turn - 1 : turn) * circumference; }).ToList(); + // Half the ring away a turret's side is ambiguous (its signed arc wraps). A belt in the base's family has an extent the + // generator spelled from its authored width and the zone reads from its rocks, so the stop distance is not known to the + // test. Neither station is read. + bool InFamily(CultRecordKey key) { for (; zone.Orbits[key].Data.Parent.IsSet(); key = zone.Orbits[key].Data.Parent.Key) if (key.Equals(source[0])) return true; return key.Equals(source[0]); } + if (arcs.Any(a => Math.Abs(a) > .45f * circumference) || zone.AsteroidBelts.Any(b => InFamily(zone.Planets[b.Key].Orbit.Key))) { ambiguous++; continue; } + stations++; + foreach (var sign in new[] { -1f, 1f }) + { + var side = arcs.Where(a => a * sign > 0).OrderBy(a => a * sign).ToList(); + sides++; + foreach (var placed in side) + { + var at = 2 * orbit.Data.Distance * Math.Abs((float) Math.Sin(PI * (orbit.Data.Phase + placed / circumference - zone.Orbits[source[0]].Data.Phase))); + Assert.True(at >= (extent + reach) * .999f, $"seed {built.Seed}: a turret sits {at} from its base, inside {extent + reach}"); + } + var wouldBe = (side.Count == 0 ? 0f : side[side.Count - 1]) + sign * ((side.Count == 0 ? Contacts.Radius(station) : reach) + 2 * reach); + var phase = orbit.Data.Phase + wouldBe / circumference; + var chord = 2 * orbit.Data.Distance * Math.Abs((float) Math.Sin(PI * (phase - zone.Orbits[source[0]].Data.Phase))); + if (side.Count >= turrets / 2) continue; + stops++; + Assert.True(chord < (extent + reach) * (1 + 1e-3f), $"seed {built.Seed}: a side stopped at {side.Count} turrets with its next turret still {chord} from the base, outside {extent + reach}"); + if (chord >= .8f * (extent + reach)) nearBase++; + } + } + } + _output.WriteLine($"story stations {stations} (not read: {ambiguous}), sides {sides}, sides that stopped {stops}, of them with the next turret at 0.8 to 1 of the stop distance {nearBase}"); + Assert.True(stops > 0 && nearBase > 0, $"{stops} stops, {nearBase} in the 0.8 band: the seeds do not exercise the rule"); + } + + // The entrance always gets a station. With no candidate orbit (a station hull so large that no rail clears a massive sibling + // by its reach) it orbits a body root outside that root's extent, not at a Lagrange point. + [Fact] + public void ATutorialEntranceWithNoCandidateOrbitsItsBodyRootOutsideItsExtent() + { + var fired = 0; + foreach (var built in GeneratedZones(WithAnUnofferedHugeStationHull, 0, 20, 1, + z => { z.RosetteProbability = 0; z.BinaryCreationProbability = 0; z.SatelliteCreationProbability = 0; }, true)) + { + var zone = built.Zone; + var station = Orbitals(built).FirstOrDefault(e => TypeOf(built.Items, e) == HullType.Station); + if (station == null) continue; + var orbit = zone.Orbits[station.OrbitData]; + var root = orbit.Data.Parent.IsSet() ? orbit.Data.Parent.Key : default; + if (!orbit.Data.Parent.IsSet() || zone.Orbits[root].Data.Parent.IsSet() || !zone.Planets.Values.Any(b => !(b is AsteroidBeltData) && b.Orbit.Key.Equals(root))) continue; + if (zone.Planets.Values.Any(b => SameRing(zone.Orbits[b.Orbit.Key], orbit))) continue; + fired++; + var extent = ExtentOfBodies(zone, root); + Assert.True(Math.Abs(orbit.Data.Distance - extent) <= 1e-4f * extent, $"seed {built.Seed}: the entrance station orbits its root at {orbit.Data.Distance}, not at its extent {extent}"); + } + _output.WriteLine($"entrance zones where the fallback seated a station at a body root: {fired}"); + Assert.True(fired > 0, "no entrance zone of seeds 1-20 took the fallback for a body root"); + } + private static List TurretProducts(ItemManager items) => items.ItemData.GetAll().Where(p => items.ItemData.Get(p.Design) is HullData { HullType: HullType.Turret }).ToList(); @@ -235,7 +442,24 @@ public sealed class StationPlacementTests : IDisposable // The shipped catalog has one turret hull. A copy with a bigger solid shape (a larger reach) and its own product // gives the generator two turret hulls to choose between. - private static void WithALargerTurretHull(ItemManager items) + private static void WithALargerTurretHull(ItemManager items) => AddATurretHull(items, 2, false); + + // Only the wider hull is on offer: the shipped turret is priced at zero once the wider copy has its price. + private static void WithOnlyAWiderTurretHull(ItemManager items) => AddATurretHull(items, 6, true); + + // A station hull with no product, so nothing builds it, but wide enough that its reach is the largest in the catalog. + private static void WithAnUnofferedHugeStationHull(ItemManager items) + { + var copyOf = typeof(object).GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + var hull = items.ItemData.GetAll().First(h => h.HullType == HullType.Station); + var huge = (HullData) copyOf.Invoke(hull, null); + huge.Name = hull.Name + " (huge)"; + huge.Shape = new Shape(20000, 1); + foreach (var cell in huge.Shape.AllCoordinates) huge.Shape[cell] = true; + items.ItemData.Upsert(huge); + } + + private static void AddATurretHull(ItemManager items, int extraCells, bool only) { var copyOf = typeof(object).GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); foreach (var product in TurretProducts(items)) @@ -243,12 +467,13 @@ public sealed class StationPlacementTests : IDisposable var hull = (HullData) items.ItemData.Get(product.Design); var larger = (HullData) copyOf.Invoke(hull, null); larger.Name = hull.Name + " (large)"; - larger.Shape = new Shape(hull.Shape.Width + 2, hull.Shape.Height + 2); + larger.Shape = new Shape(hull.Shape.Width + extraCells, hull.Shape.Height + extraCells); foreach (var cell in larger.Shape.AllCoordinates) larger.Shape[cell] = true; var largerProduct = (FactionProductData) copyOf.Invoke(product, null); largerProduct.Name = product.Name + " (large)"; largerProduct.Design = new CultRecordRef(items.ItemData.Upsert(larger).Key); items.ItemData.Upsert(largerProduct); + if (only) hull.Price = 0; } } diff --git a/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs b/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs index e6f5314ef..85cbe7ec8 100644 --- a/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs +++ b/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs @@ -191,7 +191,7 @@ public sealed class SunsNeverGreenTests : IDisposable foreach (var zone in galaxy.Zones) { zones++; - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, zone, false, false); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, false, false); suns.AddRange(pack.Planets.Select(p => cache.Get(p)).OfType()); } } diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 61691d180..691fe3420 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -563,7 +563,6 @@ public static class Program var missing = new List(); if (zones.ZoneRadius == null || zones.ZoneRadius.Maximum <= 0) missing.Add("ZoneSettings.ZoneRadius"); if (zones.SubZoneCount == null || zones.SubZoneCount.Maximum <= 0) missing.Add("ZoneSettings.SubZoneCount"); - if (zones.PlanetSafetyRadius == null || zones.PlanetSafetyRadius.Multiplier <= 0) missing.Add("ZoneSettings.PlanetSafetyRadius"); if (gameplay.Tiers == null || gameplay.Tiers.Length != 5) missing.Add($"GameplaySettings.Tiers (expected 5, got {gameplay.Tiers?.Length ?? 0})"); else if (gameplay.Tiers.Any(t => string.IsNullOrEmpty(t.Name) || t.Quality <= 0)) missing.Add("GameplaySettings.Tiers (a tier parsed without a name or quality)"); if (gameplay.DefaultEntitySettings == null) missing.Add("GameplaySettings.DefaultEntitySettings");