diff --git a/Assets/Scripts/ServerShared/DrawAhead.cs b/Assets/Scripts/ServerShared/DrawAhead.cs index a5d4736c5..a1d389083 100644 --- a/Assets/Scripts/ServerShared/DrawAhead.cs +++ b/Assets/Scripts/ServerShared/DrawAhead.cs @@ -106,7 +106,7 @@ public static class DrawAhead } public static BeltDraw DrawListOf(AsteroidBelt belt, PlanetSettings settings, IReadOnlyList meshes, System.Func radius, int keep, CultRecordKey beltKey) => - new(Enumerable.Range(0, belt.Data.Asteroids.Length).Select(i => belt.UndamagedSize(i, settings)).ToArray(), meshes, radius, keep, beltKey.Value); + new(Enumerable.Range(0, belt.Data.Asteroids.Length).Select(i => belt.UndamagedSize(i, settings)).ToArray(), meshes, radius, keep, belt.Data.SiteOr(beltKey)); // A ship in a wormhole animation has its pose scripted by the step, not integrated from Velocity and TurnRate, // so it is drawn where the step put it: extrapolating a scripted pose draws a streak that resets every step. diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 9edf45e19..94c57a61b 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -551,7 +551,7 @@ public abstract class Entity foreach (var candidate in _targetCandidates) if (candidate.Target.Chunk is ChunkId chunk && ChunkVisible(chunk)) into.Add(chunk); - into.Sort(ByIndexThenField); + into.Sort(ByIndexThenSite); } // The one search every chunk question asks the zone's targeting index: from here, as far as the longest range @@ -737,8 +737,12 @@ public abstract class Entity } private readonly List _targetCandidates = new List(); - private static readonly Comparison ByIndexThenField = (a, b) => - a.Index != b.Index ? a.Index.CompareTo(b.Index) : a.Field.GetHashCode().CompareTo(b.Field.GetHashCode()); + private int ByIndexThenSite(ChunkId a, ChunkId b) + { + if (a.Index != b.Index) return a.Index.CompareTo(b.Index); + var bySite = string.CompareOrdinal(Zone.AsteroidBelts[a.Field].Data.SiteOr(a.Field), Zone.AsteroidBelts[b.Field].Data.SiteOr(b.Field)); + return bySite != 0 ? bySite : string.CompareOrdinal(a.Field.Value, b.Field.Value); + } // The planar distance per unit of visibility beyond which no target can pass ChunkVisible's threshold: an upper // bound, never a decision. ChunkInfo is saturate(sum_i v s_i c_i(angle) / d / (n k)), linear in v and falling as diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 9102b16eb..8760fae93 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -1850,7 +1850,7 @@ public static class FireControl var total = 0f; for (var i = 0; i < ores.Length; i++) { - var g = $"{chunk.Field.Value}:{chunk.Index}:{ores[i].Commodity.Key.Value}".StableHash() / 2147483648.0 - 1.0; + var g = $"{belt.Data.SiteOr(chunk.Field)}:{chunk.Index}:{ores[i].Commodity.Key.Value}".StableHash() / 2147483648.0 - 1.0; total += weights[i] = ores[i].Amount * (float) Math.Exp(settings.ChunkCompositionVariance * g); } var counts = new int[ores.Length]; diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index 74d1486c3..e830c29ee 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -201,7 +201,7 @@ public class Zone case AsteroidBeltData belt: // Mining Cut 3 (Q16 B): a belt from before field kinds existed gets its kind here, once, by // the rule generation uses, and keeps it. - FieldKinds.Ensure(body.Key.Value, belt, cache, GalaxyZone?.Province?.Type ?? default); + FieldKinds.Ensure(belt.SiteOr(body.Key), belt, cache, GalaxyZone?.Province?.Type ?? default); AsteroidBelts[body.Key] = new AsteroidBelt(belt); break; case SunData sun: diff --git a/Assets/Scripts/ServerShared/ZoneData.cs b/Assets/Scripts/ServerShared/ZoneData.cs index e76963a43..6708ee47f 100644 --- a/Assets/Scripts/ServerShared/ZoneData.cs +++ b/Assets/Scripts/ServerShared/ZoneData.cs @@ -88,6 +88,14 @@ public abstract class BodyData [JsonProperty("bodyRadiusMul")] [Key(5)] public float BodyRadiusMultiplier = 1; + + // The body's generation coordinate: the zone seed, its kind and its place in the pack. Written once, by ZoneGenerator. + // The key is identity and is minted by the cache; no content hash reads it when a Site exists (SiteOr). + [JsonProperty("site"), Key(23)] + public string Site; + + public string SiteOr(GameCult.Caching.CultRecordKey key) => string.IsNullOrEmpty(Site) ? key.Value : Site; + public static string NameOf(string site) => site.StableHash().ToString("x8"); } [CultDocument("aetheria.planetdata", "1"), MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/ZoneGenerator.cs b/Assets/Scripts/ServerShared/ZoneGenerator.cs index 50bea93df..ada967f1d 100644 --- a/Assets/Scripts/ServerShared/ZoneGenerator.cs +++ b/Assets/Scripts/ServerShared/ZoneGenerator.cs @@ -209,12 +209,11 @@ public static class ZoneGenerator gas.SecondOffsetDomainRotationSpeed = -25; } - // A body is named for the first eight characters of the key the cache mints for it - var bodyKey = cache.Upsert(planetData).Key; - planetData.Name = bodyKey.Value.Substring(0, 8); - // Mining Cut 3 (Q16 B): a belt's field kind is chosen here, at generation, and saved with it. - if (planetData is AsteroidBeltData generatedBelt) FieldKinds.Ensure($"{seed}:belt:{index}", generatedBelt, cache, galaxyZone.Province?.Type ?? default); - return cache.Upsert(planetData); + planetData.Site = planetData is AsteroidBeltData ? $"{seed}:belt:{index}" : $"{seed}:body:{index}"; + planetData.Name = BodyData.NameOf(planetData.Site); + var held = cache.Upsert(planetData); + if (planetData is AsteroidBeltData generatedBelt) FieldKinds.Ensure(planetData.Site, generatedBelt, cache, galaxyZone.Province?.Type ?? default); + return held; }).ToList(); // Trojan swarms (rulings trojans-first, trojans-ride-host-period-with-stations): a belt on a copy of its host's rail, its @@ -237,10 +236,10 @@ public static class ZoneGenerator Asteroids = TrojanRocks(zoneSettings, ref swarmRandom, rail.Distance, rail.Phase) }; BodyData swarmBody = swarm; - var swarmKey = cache.Upsert(swarmBody).Key; - swarm.Name = swarmKey.Value.Substring(0, 8); - FieldKinds.Ensure($"{seed}:swarm:{swarmHosts.Count}", swarm, cache, galaxyZone.Province?.Type ?? default); + swarm.Site = $"{seed}:swarm:{swarmHosts.Count}"; + swarm.Name = BodyData.NameOf(swarm.Site); pack.Planets.Add(cache.Upsert(swarmBody)); + FieldKinds.Ensure(swarm.Site, swarm, cache, galaxyZone.Province?.Type ?? default); } // Laned belts (rulings belt-shapes-direction, lanes-two-sided-visual-margin): a belt candidate that kept its body carries @@ -266,10 +265,10 @@ public static class ZoneGenerator Asteroids = LaneRocks(zoneSettings, ref laneRandom, host.Mass, rail.Distance, lane, host.SlotInner, host.SlotOuter) }; BodyData lanedBody = laned; - var lanedKey = cache.Upsert(lanedBody).Key; - laned.Name = lanedKey.Value.Substring(0, 8); - FieldKinds.Ensure($"{seed}:lane:{shaped.Count}", laned, cache, galaxyZone.Province?.Type ?? default); + laned.Site = $"{seed}:lane:{shaped.Count}"; + laned.Name = BodyData.NameOf(laned.Site); pack.Planets.Add(cache.Upsert(lanedBody)); + FieldKinds.Ensure(laned.Site, laned, cache, galaxyZone.Province?.Type ?? default); } // 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 diff --git a/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs b/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs index e7254fac6..7497e2e81 100644 --- a/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs +++ b/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs @@ -530,6 +530,26 @@ public sealed class DrawnPoseTests : IDisposable Assert.Equal(candidates.Select(c => c.Name).ToArray(), Kept("belt-0", 20)); } + // The mesh choice reads the belt's Site: whatever key the caller passes, a belt with a Site draws the same meshes, and without + // one the key decides (so a belt from before sites draws as it did). + [Fact] + public void TheDrawFollowsTheSite() + { + var w = Build(); + var belt = w.Zone.AsteroidBelts[w.Belt]; + var candidates = Enumerable.Range(0, 8).Select(i => new Candidate("c" + i, 1f + i)).ToArray(); + string Drawn(string key) + { + var list = DrawAhead.DrawListOf(belt, w.Zone.Settings, candidates, c => c.Radius, 3, new CultRecordKey(key)); + return string.Join(",", MeshOf(list, w.Asteroids.Length).Select(m => list.Meshes[m].Name)); + } + var keys = Enumerable.Range(0, 40).Select(i => "belt-" + i).ToArray(); + Assert.True(keys.Select(Drawn).Distinct().Count() > 1, "with no Site the key decides"); + belt.Data.Site = "7:belt:2"; + var first = Drawn(keys[0]); + foreach (var key in keys) Assert.Equal(first, Drawn(key)); + } + // A mined rock keeps its mesh and only shrinks: the assignment reads the unworn size. [Fact] public void AMinedRockKeepsItsMesh() diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index 6fd28041b..77c19deab 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -485,6 +485,29 @@ public sealed partial class MiningCut3Tests : IDisposable Assert.Contains(farther, offered); } + // Chunks of equal index are offered in the order of their belts' Sites, then keys: the minted key's text decides nothing + // when a Site exists. The Sites are set against the keys' ordinal order, so a key comparison would offer the other way. + [Fact] + public void ChunkTieBreakFollowsSiteNotKey() + { + var kind = Kind("Asteroid", 4f); + var s = BuildScene(new[] { kind }, Belt(kind, Rock(150f)), Belt(kind, Rock(150f))); + var byKey = s.Belts.OrderBy(key => key.Value, StringComparer.Ordinal).ToArray(); + s.Zone.AsteroidBelts[byKey[0]].Data.Site = "site-b"; + s.Zone.AsteroidBelts[byKey[1]].Data.Site = "site-a"; + var eyeAt = float2(150, -100); + var observer = SpawnShip(s, eyeAt, sensor: true, weaponRanges: new[] { 400f }); + Tick((observer, eyeAt)); + var offered = new List(); + observer.VisibleChunksInReach(offered); + Assert.Equal(new[] { new ChunkId(byKey[1], 0), new ChunkId(byKey[0], 0) }, offered); + + s.Zone.AsteroidBelts[byKey[0]].Data.Site = "site-a"; + s.Zone.AsteroidBelts[byKey[1]].Data.Site = "site-b"; + observer.VisibleChunksInReach(offered); + Assert.Equal(new[] { new ChunkId(byKey[0], 0), new ChunkId(byKey[1], 0) }, offered); + } + // The chunk query returns exactly the chunks within range, from inside the belt's hole, from within the // annulus and from outside it -- the belt skip never drops a chunk the brute-force answer would keep -- and it // leaves out a broken chunk. diff --git a/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs index 04f02164d..301ae1f3b 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs @@ -209,10 +209,10 @@ public sealed class MiningCut5aTests : IDisposable } // Every rock broken once; the shooter is not in the zone, so everything floats and the floats are the record. - private static (int Rock, int Gold)[] Break(MiningCut3Tests.Scene scene, Zone zone, Ship ship, int rocks, uint seed) => + private static (int Rock, int Gold)[] Break(MiningCut3Tests.Scene scene, Zone zone, Ship ship, int rocks, uint seed, int belt = 0) => Enumerable.Range(0, rocks).Select(rock => { - var chunk = new ChunkId(scene.Belts[0], rock); + var chunk = new ChunkId(scene.Belts[belt], rock); var before = zone.FloatingItems.Select(f => f.Item).ToArray(); FireControl.Extract(zone, chunk, zone.Wear(chunk, 1e6f), ship, SimulationDice.For(seed, SimulationDice.OreStream, (uint) rock)); var added = zone.FloatingItems.Select(f => f.Item).Except(before).ToArray(); @@ -228,6 +228,31 @@ public sealed class MiningCut5aTests : IDisposable Assert.NotEqual(first, Break(scene, newZone(), ship, 20, 12)); } + // Ore reads the body's Site, not the key the cache minted for it: two belts of one scene (one set of commodities) wear the + // same ore under one seed when they share a Site, and with no Site (a save from before sites, or a hand-built belt) the key + // stands in and they differ. + [Fact] + public void TwoBeltsOfOneSiteGiveTheSameOre() + { + const int rocks = 20; + var kind = MiningCut3Tests.Kind("Asteroid", 4f); + MiningCut3Tests.BeltSpec Belt() => MiningCut3Tests.Belt(kind, + Enumerable.Range(0, rocks).Select(i => MiningCut3Tests.Rock(150f + i, i / (float) rocks, .5f)).ToArray()); + var scene = _scenes.BuildScene(new[] { kind }, Belt(), Belt()); + Stock(scene, kind, (Commodity("Rock"), 1f), (Commodity("Gold"), 1f)); + var settings = MiningCut3Tests.PlanetSettings(); + settings.ChunkCompositionVariance = 2f; + settings.AsteroidYield = new ExponentialLerp { Minimum = 40f, Maximum = 40f, Exponent = 1f }; + var ship = new Ship(scene.Items, scene.Zone, MiningCut3Tests.Mint(scene, scene.Hull), new EntitySettings()); + Zone NewZone() => new Zone(scene.Items, settings, scene.Pack, new GalaxyZone { Name = "MiningCut3", Owner = null }, null); + + Assert.NotEqual(Break(scene, NewZone(), ship, rocks, 11, belt: 0), Break(scene, NewZone(), ship, rocks, 11, belt: 1)); + + var zone = NewZone(); + foreach (var key in scene.Belts) zone.AsteroidBelts[key].Data.Site = "7:belt:3"; + Assert.Equal(Break(scene, zone, ship, rocks, 11, belt: 0), Break(scene, NewZone(), ship, rocks, 11, belt: 1)); + } + // Composition is derived from the rock's identity every call: variance 0 reads the kind's ratio, variance above 0 gives // rocks different mixes, and nothing stores it (a second zone of the pack reads the same mixes from the dice and keys). [Fact] diff --git a/tests/Aetheria.Shared.Tests/OreGeographyTests.cs b/tests/Aetheria.Shared.Tests/OreGeographyTests.cs index bae4d18aa..d354f1904 100644 --- a/tests/Aetheria.Shared.Tests/OreGeographyTests.cs +++ b/tests/Aetheria.Shared.Tests/OreGeographyTests.cs @@ -1015,7 +1015,7 @@ public sealed class OreGeographyTests : IDisposable var settings = RestoredHullsTests.AuthoredPlanetSettings(); var loaded = new Zone(items, settings, packs[0].Key, inProvince, galaxy); foreach (var key in packs[0].Select(g => cache.RefOf(g.Belt).Key)) - Assert.Equal(FieldKinds.Assign(key.Value, cache, noA).Key.Value, ((AsteroidBeltData) loaded.Planets[key]).Kind.Key.Value); + Assert.Equal(FieldKinds.Assign(((AsteroidBeltData) loaded.Planets[key]).SiteOr(key), cache, noA).Key.Value, ((AsteroidBeltData) loaded.Planets[key]).Kind.Key.Value); Assert.All(packs[0].Select(g => cache.RefOf(g.Belt).Key), key => Assert.Equal("field-kind:b", ((AsteroidBeltData) loaded.Planets[key]).Kind.Key.Value)); // No GalaxyZone: the unweighted pick. @@ -1026,7 +1026,7 @@ public sealed class OreGeographyTests : IDisposable foreach (var key in pack.Select(g => cache.RefOf(g.Belt).Key)) { var kind = ((AsteroidBeltData) bare.Planets[key]).Kind.Key.Value; - Assert.Equal(FieldKinds.Assign(key.Value, cache, default).Key.Value, kind); + Assert.Equal(FieldKinds.Assign(((AsteroidBeltData) bare.Planets[key]).SiteOr(key), cache, default).Key.Value, kind); if (kind == "field-kind:a") unweighted++; } } diff --git a/tests/Aetheria.Shared.Tests/ZoneSiteTests.cs b/tests/Aetheria.Shared.Tests/ZoneSiteTests.cs new file mode 100644 index 000000000..0956eb65f --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ZoneSiteTests.cs @@ -0,0 +1,51 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// Zone body identity (cut zone-body-sites, ruling zone-body-site-identity): a generated body's key is minted by the cache and +// is identity only; its Site is the generation coordinate (zone seed, kind, place in the pack) that ore, tie-breaks, rock meshes +// and names read. Every input is the production one: the fixture galaxy, GenerateZone, the run store. +public sealed partial class RunStartTests +{ + private BodyData BodyOf(CultRecordRef body) => _cache.Get(body); + + // Replace and Beside generate a scenario of a saved run's seed beside the saved run in one store. + [Fact] + public void ASameSeedBesideItselfTouchesNoneOfTheFirstBodies() + { + var zone = _galaxy.Entrance; + var first = BossZonePack(_galaxy, _items, zone, ambient: false); + var held = first.Planets.Select(body => (body, Doc: BodyOf(body))).ToArray(); + var second = BossZonePack(_galaxy, _items, zone, ambient: false); + + Assert.Equal(first.Planets.Count, second.Planets.Count); + Assert.Empty(first.Planets.Select(body => body.Key).Intersect(second.Planets.Select(body => body.Key))); + Assert.Empty(first.Orbits.Select(orbit => orbit.Key).Intersect(second.Orbits.Select(orbit => orbit.Key))); + Assert.Equal(first.Planets.Select(body => BodyOf(body).Site), second.Planets.Select(body => BodyOf(body).Site)); + Assert.Equal(first.Planets.Select(body => BodyOf(body).Name), second.Planets.Select(body => BodyOf(body).Name)); + foreach (var (body, doc) in held) Assert.Same(doc, BodyOf(body)); + } + + [Fact] + public void EveryGeneratedBodyHasASiteUniqueInItsPack() + { + var swarms = 0; + var lanes = 0; + foreach (var zone in _galaxy.Zones) + { + var bodies = BossZonePack(_galaxy, _items, zone, ambient: false).Planets.Select(BodyOf).ToArray(); + Assert.All(bodies, body => Assert.False(string.IsNullOrEmpty(body.Site), $"{zone.Name} has a body with no Site")); + Assert.Equal(bodies.Length, bodies.Select(body => body.Site).Distinct().Count()); + Assert.All(bodies, body => Assert.Equal(BodyData.NameOf(body.Site), body.Name)); + swarms += bodies.Count(body => body.Site.Contains(":swarm:")); + lanes += bodies.Count(body => body.Site.Contains(":lane:")); + } + Assert.True(swarms > 0, "the fixture galaxy generated no trojan swarm"); + Assert.True(lanes > 0, "the fixture galaxy generated no laned belt"); + } +}