diff --git a/Assets/Scripts/ServerShared/DemoPressure.cs b/Assets/Scripts/ServerShared/DemoPressure.cs new file mode 100644 index 000000000..25987b3b2 --- /dev/null +++ b/Assets/Scripts/ServerShared/DemoPressure.cs @@ -0,0 +1,67 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Linq; + +// The demo's pressure curve (aetheria-release, cut demo-pressure-curve): how many hostiles, of what hull tier, a zone of a +// galaxy with a gate antagonist (Galaxy.Antagonist) holds, as a function of its depth toward the gate. The single owner of these numbers; +// ZoneGenerator asks and draws. Pure: no Unity, no cache, no randomness, so the same persisted galaxy yields the same zone. +public static class DemoPressure +{ + // Depth at or below which a zone carries no hostiles. Depth is e / (e + x), the share of the way from the entrance to the + // gate a zone sits at, so a quarter covers the entrance, its neighbours, and on a short galaxy the first jump out. + public const float GraceDepth = 0.25f; + + // Hostiles at the gate (its ring, besides the boss), the most the curve ever asks for. + public const int MaxHostiles = 6; + + // Tier is depth raised to this power: above 1 keeps heavy hulls rare until the last stretch. + public const float TierExponent = 2f; + + public readonly struct Pressure + { + public readonly int Hostiles; + // 0..1: the antagonist's ship hulls up to this quantile of cost may be drawn. + public readonly float Tier; + public Pressure(int hostiles, float tier) { Hostiles = hostiles; Tier = tier; } + } + + // e / (e + x) for e = jumps from the entrance and x = jumps to the exit: 0 only at the entrance, 1 only at the gate, from + // the persisted Entrance and Exit alone. On a shortest entrance-exit path it is the share of the way travelled; a zone + // behind the entrance rises slowly with its distance from it rather than sitting at 0. + public static float Depth(Galaxy galaxy, GalaxyZone zone) + { + float e = galaxy.Entrance.Distance[zone], x = galaxy.Exit.Distance[zone]; + return e + x == 0 ? 0f : e / (e + x); + } + + // The entrance and this many jumps around it are quiet whatever the galaxy's depth scale, so a short galaxy's first + // neighbours are no deeper than the grace. + public const int GraceJumps = 1; + + // No antagonist ship, station or turret holds a zone in grace. + public static bool InGrace(Galaxy galaxy, GalaxyZone zone) => + galaxy.Entrance.Distance[zone] <= GraceJumps || Depth(galaxy, zone) <= GraceDepth; + + // What the zone holds: the curve at its depth, none in grace. + public static Pressure Of(Galaxy galaxy, GalaxyZone zone) => + InGrace(galaxy, zone) ? new Pressure(0, At(Depth(galaxy, zone)).Tier) : At(Depth(galaxy, zone)); + + public static Pressure At(float depth) + { + depth = Math.Clamp(depth, 0f, 1f); + var ramp = Math.Clamp((depth - GraceDepth) / (1f - GraceDepth), 0f, 1f); + var smooth = ramp * ramp * (3f - 2f * ramp); + return new Pressure((int)MathF.Round(MaxHostiles * smooth), MathF.Pow(depth, TierExponent)); + } + + // The dearest hull price the tier admits: the price at that quantile of the hulls offered, cheapest first. Never below the + // cheapest hull offered, so the draw is never empty while any hull is offered. + public static int PriceCeiling(int[] offeredPrices, float tier) + { + var sorted = offeredPrices.OrderBy(price => price).ToArray(); + return sorted[(int)MathF.Round(Math.Clamp(tier, 0f, 1f) * (sorted.Length - 1))]; + } +} diff --git a/Assets/Scripts/ServerShared/DemoPressure.cs.meta b/Assets/Scripts/ServerShared/DemoPressure.cs.meta new file mode 100644 index 000000000..df1cf5708 --- /dev/null +++ b/Assets/Scripts/ServerShared/DemoPressure.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7c1e9a40d3b84f26a5e08b19f6d2c371 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Galaxy.cs b/Assets/Scripts/ServerShared/Galaxy.cs index 5befe2ad5..5861f7131 100644 --- a/Assets/Scripts/ServerShared/Galaxy.cs +++ b/Assets/Scripts/ServerShared/Galaxy.cs @@ -31,6 +31,11 @@ public class Galaxy // 1 for a main galaxy. Carried by the save because every zone generated after Continue reads it. public float InfluenceScale { get; } + // The faction whose gate this galaxy has, null when it has none: the scope and the source of the demo's raids + // (ZoneGenerator reads it through DemoPressure). Written only by PlaceGate and the save constructor; carried by the + // save because every zone generated after Continue reads it and nothing else persisted regenerates it. + public Faction Antagonist { get; private set; } + // The run's seed, minted once by GalaxyStage.SeedFrom and carried by the save (SavedGame.Seed). It seeds // generation, the run's item draws (RunStart) and the zone's drop dice (Zone.DropSeed). public uint Seed { get; } @@ -102,6 +107,11 @@ public class Galaxy if(savedGame.Exit != -1) Exit = Zones[savedGame.Exit]; + // Unset: no gate antagonist (a save from before key 18). Set but not one of the save's factions: refused. + if (savedGame.Antagonist.IsSet()) + Antagonist = Factions.Contains(cultCache.Get(savedGame.Antagonist)) ? cultCache.Get(savedGame.Antagonist) + : throw new InvalidOperationException("SavedGame.Antagonist is not one of the save's factions"); + // A save from before ore geography has no provinces: it gets them by the rule generation uses. BuildProvinces(global::Provinces.DefaultZonesPerProvince, savedGame.Provinces == null ? null : savedZones.Select(zone => zone.Province).ToArray(), savedGame.Provinces); @@ -195,10 +205,11 @@ public class Galaxy private Faction ResolveCast(string field, string name) => ResolveFaction(name) ?? throw new InvalidOperationException($"cast faction {name} ({field}) is not in the catalog"); - // Gives a cast galaxy its gate: the antagonist's home is the boss zone and the exit. The only writer of Exit - // besides the constructors. + // Gives a cast galaxy its gate: the antagonist's home is the boss zone and the exit. The only writer of Exit and + // Antagonist besides the constructors. public void PlaceGate(Faction antagonist) { + Antagonist = antagonist; BossZones[antagonist] = HomeZones[antagonist]; Exit = HomeZones[antagonist]; } diff --git a/Assets/Scripts/ServerShared/LoadoutGenerator.cs b/Assets/Scripts/ServerShared/LoadoutGenerator.cs index 62e8632a1..d4e2d5643 100644 --- a/Assets/Scripts/ServerShared/LoadoutGenerator.cs +++ b/Assets/Scripts/ServerShared/LoadoutGenerator.cs @@ -64,6 +64,11 @@ public class LoadoutGenerator return EntitySerializer.Pack(entity); } + // The ship hulls this faction's generator can draw (its products, with the any-manufacturer fallback a required hull has). + public HullData[] OfferedShipHulls() => + AvailableProducts(hull => hull.HullType == HullType.Ship, required: true).available + .Select(entry => entry.design).Distinct().ToArray(); + public OrbitalEntityPack GenerateTurretLoadout() { var (hullProduct, hullData) = RandomHull(HullType.Turret); diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index 867714a5e..429b50d4d 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -72,6 +72,12 @@ public class SavedGame // by RunSave.Capture and read only by Galaxy's save constructor, which refuses a save without one (0). [Key(17)] public float InfluenceScale; + + // Galaxy.Antagonist: the faction whose gate the galaxy has, the scope and source of the demo's raids, which every zone + // generated after Continue reads. Written only by RunSave.Capture and read only by Galaxy's save constructor; unset means + // no gate antagonist, set but not one of Factions refuses Continue. Keyed by the record, as Standings is. + [Key(18)] + public CultRecordRef Antagonist; } [MessagePackObject] @@ -127,6 +133,7 @@ public static class RunSave Entrance = Array.IndexOf(galaxy.Zones, galaxy.Entrance), Exit = Array.IndexOf(galaxy.Zones, galaxy.Exit), InfluenceScale = galaxy.InfluenceScale, + Antagonist = galaxy.Antagonist == null ? default : cache.RefOf(galaxy.Antagonist), ActionBarBindings = actionBar, Credits = credits, Seed = galaxy.Seed diff --git a/Assets/Scripts/ServerShared/ZoneGenerator.cs b/Assets/Scripts/ServerShared/ZoneGenerator.cs index 42c4c15c0..50bea93df 100644 --- a/Assets/Scripts/ServerShared/ZoneGenerator.cs +++ b/Assets/Scripts/ServerShared/ZoneGenerator.cs @@ -292,6 +292,13 @@ public static class ZoneGenerator var nearestFactionHomeZone = galaxy.HomeZones[nearestFaction]; var factionPresence = galaxy.InfluenceOf(nearestFaction) - nearestFactionHomeZone.Distance[galaxyZone] + 1; + // In a galaxy with a gate antagonist that faction raids by DemoPressure's curve (below); inside its grace its stations and + // turrets are as absent as its ships, so the zone's structures belong to the nearest faction that is not the antagonist. + var antagonist = galaxy.Antagonist; + var structureFaction = antagonist != null && nearestFaction == antagonist && DemoPressure.InGrace(galaxy, galaxyZone) + ? galaxy.Factions.Where(f => f != antagonist).MinBy(f => galaxy.HomeZones[f].Distance[galaxyZone]) + : nearestFaction; + var storyStations = galaxyZone.Locations.Where(story => story.Type == LocationType.Station).ToArray(); var stationCount = (int)(random.NextFloat() * (factionPresence + 1)) + storyStations.Length; // Enemy count below is based on this pre-override value, so the entrance station zone doesn't gain an enemy @@ -441,13 +448,13 @@ public static class ZoneGenerator var security = (SecurityLevel) ((int) ((1f - pow(random.NextFloat(), factionPresence / 2f)) * 3f)); var lagrangeOrbit = CreateLagrangeOrbit(orbit); - var station = GetLoadoutGenerator(nearestFaction).GenerateStationLoadout( - StationKinds.Choose(cache, nearestFaction, $"{seed}:station:{i}", itemManager.Log)); + var station = GetLoadoutGenerator(structureFaction).GenerateStationLoadout( + StationKinds.Choose(cache, structureFaction, $"{seed}:station:{i}", itemManager.Log)); if (station == null) { if (isEntranceStation) throw new InvalidOperationException( - $"The entrance station zone must always get a station, but {nearestFaction?.Name} has no station loadout to generate."); + $"The entrance station zone must always get a station, but {structureFaction?.Name} has no station loadout to generate."); continue; } station.Orbit = cache.RefOf(lagrangeOrbit); @@ -455,7 +462,7 @@ public static class ZoneGenerator station.SecurityRadius = pack.Radius; pack.Entities.Add(station); - if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(nearestFaction), 2, StationReach(station), orbit); + if (ambient) PlaceTurrets(lagrangeOrbit, GetLoadoutGenerator(structureFaction), 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 @@ -489,18 +496,36 @@ public static class ZoneGenerator if (!ambient) return pack; - var enemyCount = (int)(random.NextFloat() * factionPresence * 2) + baseStationCount; - for (int i = 0; i < enemyCount; i++) + // A galaxy with a gate antagonist is raided by it in proportion to depth toward the gate (DemoPressure owns the curve); + // every other galaxy keeps the nearest faction's presence-sized patrol. + if (antagonist != null) { - var ship = GetLoadoutGenerator(nearestFaction).GenerateShipLoadout(); - if (ship == null) continue; - pack.Entities.Add(ship); + var pressure = DemoPressure.Of(galaxy, galaxyZone); + var raiders = GetLoadoutGenerator(antagonist); + var ceiling = pressure.Hostiles == 0 ? 0 : DemoPressure.PriceCeiling(raiders.OfferedShipHulls().Select(hull => hull.Price).ToArray(), pressure.Tier); + for (int i = 0; i < pressure.Hostiles; i++) + { + var ship = raiders.GenerateShipLoadout(hull => hull.Price <= ceiling); + if (ship == null) continue; + pack.Entities.Add(ship); + } + } + else + { + var enemyCount = (int)(random.NextFloat() * factionPresence * 2) + baseStationCount; + for (int i = 0; i < enemyCount; i++) + { + var ship = GetLoadoutGenerator(nearestFaction).GenerateShipLoadout(); + if (ship == null) continue; + pack.Entities.Add(ship); + } } // Neutral wanderers: ships belonging to a faction that neither owns the zone nor is its // nearest faction, so existing hostility rules leave them non-hostile to the player. // Testing affordance for hand-testing combat/targeting; none spawn if no faction qualifies. - var eligibleWandererFactions = EligibleWandererFactions(galaxy.Factions, galaxyZone.Owner, nearestFaction); + // The antagonist is no wanderer where DemoPressure raids: its presence is the curve's alone, and it is hostile. + var eligibleWandererFactions = EligibleWandererFactions(galaxy.Factions, galaxyZone.Owner, nearestFaction).Where(f => f != antagonist).ToArray(); if (zoneSettings.NeutralWandererCount > 0 && eligibleWandererFactions.Length > 0) { var wandererFaction = eligibleWandererFactions[random.NextInt(eligibleWandererFactions.Length)];