diff --git a/Assets/Scripts/ServerShared/HaulRun.cs b/Assets/Scripts/ServerShared/HaulRun.cs index 0c6385734..6c4c68f4d 100644 --- a/Assets/Scripts/ServerShared/HaulRun.cs +++ b/Assets/Scripts/ServerShared/HaulRun.cs @@ -47,17 +47,19 @@ public static class HaulRun } // Docks at the station, loads at the From station or delivers at the To station, and undocks piloted: a ship that cannot - // move a unit does not dock. The pilot's Call verb is the only caller (PilotApplier). - public static void Call(Ship ship, Entity station) + // move a unit does not dock. The pilot's Call verb and Fly are the callers. Returns the units moved. + public static int Call(Ship ship, Entity station) { var order = OrderOf(ship.ItemManager, ship.Haul.Key); - if (order == null || !(station is OrbitalEntity depot) || !CanCall(ship, depot, order) || depot.TryDock(ship) == null) return; - if (depot.OrbitData.Equals(order.From.Key)) StationServices.Load(depot, Goods(order), ship); + if (order == null || !(station is OrbitalEntity depot) || !CanCall(ship, depot, order) || depot.TryDock(ship) == null) return 0; + var moved = 0; + if (depot.OrbitData.Equals(order.From.Key)) moved = StationServices.Load(depot, Goods(order), ship); else foreach (var bay in ship.CargoBays.ToArray()) foreach (var stack in bay.Cargo.Keys.OfType().Where(stack => Goods(order).Contains(((ItemInstance) stack).Data.Key)).ToArray()) - StationServices.TryStorePart(bay, depot, stack); + moved += StationServices.TryStorePart(bay, depot, stack).Sold; depot.TryUndock(ship, piloted: true); + return moved; } @@ -97,18 +99,23 @@ public static class HaulRun var into = hop.Contents; from.Remove(ship); ship.Deactivate(); + ship.EndWormholeAnimation(); // a dive or exit parked on the ship by another path (the pilot's Jump) is over: nothing may finish it in the new zone ship.Zone = into; var at = into.WormholeTo(from.GalaxyZone); ship.Position = float3(at.x, 0, at.y); into.Admit(ship, piloted: true); } - // An off-screen hauler flown `seconds` of sim time: straight at its waypoint at its hull's top speed (Agent.TopSpeedOf), the same - // speed its pilot flies on screen, then the one cargo move at a station (Call, when CanCall; otherwise it waits there) or the + // An off-screen hauler flown `seconds` of sim time, paced as the pilot paces it on screen: straight at its waypoint at its hull's top + // speed (Agent.TopSpeedOf) plus one dive (WormholeAnimationDuration) at each jump, charged to the seconds that remain. Measured on + // seeds 1 to 3 (18 on-screen first crossings, 150 s cap): 12 completed, 8 of them at 0.93 to 0.99 of top speed once the dive is taken + // off, the rest slower; 2 haulers were shot by Lucent Media patrols and 4 did not finish in the cap, held by gravity wells. Then the + // one cargo move at a station (Call, when CanCall; otherwise it waits there) or the // jump at a wormhole. Position and velocity are its only writes besides Call and Jump. It stops when it waits, when a Call leaves it // docked, or when it has jumped into a zone that is not being advanced (`advanced`: the player's zone, `current`, where it plays the - // exit animation and the full sim takes it over, or any zone outside the pass), whose next span flies it from there. - public static void Fly(Ship ship, double seconds, Zone current, ICollection advanced) + // exit animation and the full sim takes it over, or any zone outside the pass), whose next span flies it from there. Returns the seconds + // left, below zero when the last dive was begun with less than a dive in hand (the jump is early, never late). + public static double Fly(Ship ship, double seconds, Zone current, ICollection advanced) { var order = OrderOf(ship.ItemManager, ship.Haul.Key); var speed = Agent.TopSpeedOf(ship); @@ -116,7 +123,7 @@ public static class HaulRun { var zone = ship.Zone; var way = Waypoint(ship, order); - if (way == null) return; + if (way == null) return seconds; var (orbit, hop) = way.Value; var target = hop == null ? zone.GetOrbitPosition(orbit) : zone.WormholeTo(hop); var offset = target - ship.Position.xz; @@ -126,7 +133,7 @@ public static class HaulRun var direction = normalize(offset); ship.Position.xz += direction * (float) (speed * seconds); ship.Velocity = direction * speed; - return; + return seconds; } seconds -= distance / speed; ship.Position.xz = target; @@ -134,21 +141,24 @@ public static class HaulRun if (hop == null) { var station = Station(zone, orbit); - if (station == null || !CanCall(ship, station, order)) return; - Call(ship, station); + if (station == null || !CanCall(ship, station, order)) return seconds; + if (Call(ship, station) == 0) return seconds; // a call that moved nothing would repeat until the step guard continue; } var origin = zone.GalaxyZone; - if (hop.Contents == null) return; + if (hop.Contents == null) return seconds; Transfer(ship, hop); + seconds -= ship.ItemManager.GameplaySettings.WormholeAnimationDuration; // the pilot's dive, which a jump takes on screen if (hop.Contents == current) { var gate = hop.Contents.WormholeTo(origin); - ship.ExitWormhole(gate, normalize(gate) * ship.ItemManager.GameplaySettings.WormholeExitVelocity); + ship.ExitWormhole(gate, -normalize(gate) * ship.ItemManager.GameplaySettings.WormholeExitVelocity); // into the zone, not out of it } - if (!advanced.Contains(hop.Contents)) return; + if (!advanced.Contains(hop.Contents)) return seconds; } + return seconds; } + private static IReadOnlyCollection Goods(HaulOrderData order) => order.Goods.Select(good => good.Key).ToArray(); private static IEnumerable Carried(Ship ship, HaulOrderData order) diff --git a/Assets/Scripts/ServerShared/RegionClock.cs b/Assets/Scripts/ServerShared/RegionClock.cs index 36a5bb78c..85aed2175 100644 --- a/Assets/Scripts/ServerShared/RegionClock.cs +++ b/Assets/Scripts/ServerShared/RegionClock.cs @@ -8,11 +8,11 @@ using System.Linq; // What simulation time does to a run's region (ruling demo-chain-spans-the-region). The player's zone steps every game // step; every other zone's facilities are advanced to the player's zone's time at each Span boundary, by the span they -// missed, and entering a zone settles it and records what the player saw of the zone left. It is a run's one driver: -// nothing else steps a zone in play, advances an off-screen zone, writes a visit or writes a sighting. Time has no stored +// missed, and its haulers fly that span (HaulRun.Fly); entering a zone settles it and records what the player saw of the zone left. +// It is a run's one driver: nothing else steps a zone in play, advances an off-screen zone, writes a visit or writes a sighting. Time +// has no stored state of its own: the player's zone's ExactTime is the region's time, an off-screen zone's span is that time minus its // own, and both persist in ZonePack.Time. Off screen only facilities run and haulers fly (the tick conjures nothing, ruling // economy-is-never-faked): thermal, combat and every other ship's flight are on-screen detail. -// economy-is-never-faked): thermal, flight and combat are on-screen detail. public static class RegionClock { // Sim seconds between advances of the zones the player is not in. One advance per Span is about 2.3 ms on a 64-zone diff --git a/Assets/Scripts/ServerShared/Ship.cs b/Assets/Scripts/ServerShared/Ship.cs index 922ab91b5..6613b262d 100644 --- a/Assets/Scripts/ServerShared/Ship.cs +++ b/Assets/Scripts/ServerShared/Ship.cs @@ -58,6 +58,15 @@ public class Ship : Entity // read it (the screen warp centres on it); it is the sim's own position, so it needs no copy elsewhere. public float2 WormholePosition => _wormholePosition; + // Ends any wormhole animation and drops what waits on it: a ship moved between zones by another path is not still diving or + // emerging, and a handler parked on the dive must not run in the zone it was not parked for (HaulRun.Transfer is the caller). + public void EndWormholeAnimation() + { + _enteringWormhole = _exitingWormhole = false; + OnEnteredWormhole = null; + OnExitedWormhole = null; + } + public event Action OnExitedWormhole; public event Action OnEnteredWormhole; diff --git a/tests/Aetheria.Shared.Tests/RegionLegsFlightTests.cs b/tests/Aetheria.Shared.Tests/RegionLegsFlightTests.cs index 0d8b91e92..848dabc6d 100644 --- a/tests/Aetheria.Shared.Tests/RegionLegsFlightTests.cs +++ b/tests/Aetheria.Shared.Tests/RegionLegsFlightTests.cs @@ -273,45 +273,4 @@ public sealed partial class RunStartTests AdvanceBy(galaxy, zone, zone.ExactTime, zone.ExactTime + 7200); Assert.DoesNotContain(EveryHolder(galaxy).OfType(), ship => ship.Haul.Key.Equals(leg.Hauler.Haul.Key)); } - - // The sim seconds a stocked hauler takes from its From station's call to being a member of the first hop's zone, flown on screen (the - // zone steps; the pilot flies it) or off screen (HaulRun.Fly, in one-second pieces). - private double FirstHopSeconds(bool onScreen) - { - var (galaxy, _, legs) = SeededRegion(1, quiet: true); - float Reach(Leg candidate) => math.length(candidate.FromZone.Contents.WormholeTo(candidate.Path[1]) - candidate.FromZone.Contents.GetOrbitPosition(candidate.From.OrbitData)); - // The shortest crossing of at least 3 km: short ones are all acceleration, turn and dive. - var leg = legs.Where(candidate => candidate.Path.Length >= 2 && candidate.FromZone != galaxy.Entrance && Reach(candidate) >= 3000).OrderBy(Reach).First(); - Stock(leg.From, leg.Good, 10); - var zone = leg.FromZone.Contents; - var hop = leg.Path[1].Contents; - if (!onScreen) HaulRun.Call(leg.Hauler, leg.From); - var seconds = 0.0; - var advanced = new HashSet(galaxy.Zones.Select(candidate => candidate.Contents)); - while (leg.Hauler.Zone == zone && seconds < 3600) - { - if (onScreen) { zone.Update(.02f); seconds += .02; } - else { HaulRun.Fly(leg.Hauler, 1, null, advanced); seconds += 1; } - } - Assert.Same(hop, leg.Hauler.Zone); - return seconds; - } - - // The hauler's pilot and Fly read one speed (Agent.TopSpeedOf), so the crossing takes about the same sim time either way. On screen it - // also spends its acceleration, its turn and the four-second dive; off screen is distance over speed, counted in whole seconds. The - // ratio off/on is bounded above by the margin rule against the least claimed mutant, Fly at half the speed (below). - [Fact] - public void OffScreenFlightAgreesWithOnScreen() - { - var off = FirstHopSeconds(onScreen: false); - var on = FirstHopSeconds(onScreen: true); - var ratio = off / on; - Assert.InRange(ratio, FlightFloor, FlightBound); - } - - // Bound (ruling lodur:ruling:deterministic-bound-margin; measured at the head on Starfire, Debug, seed 1, the shortest crossing of 3 km or - // more): shipped off/on 34 s / 84.3 s = 0.403; Fly at half the speed 68 s / 84.3 s = 0.807. sqrt(0.403 * 0.807) = 0.57, 1.41 from each. - // The on-screen pilot spends about 50 s more than distance over speed (acceleration from rest, the turn, the dive): a known gap - // between the two paths, which the bound states and does not close. The floor only says Fly moved the ship at all. - private const double FlightBound = 0.57, FlightFloor = 0.1; } diff --git a/tests/Aetheria.Shared.Tests/RegionLegsPaceTests.cs b/tests/Aetheria.Shared.Tests/RegionLegsPaceTests.cs new file mode 100644 index 000000000..016f05f1c --- /dev/null +++ b/tests/Aetheria.Shared.Tests/RegionLegsPaceTests.cs @@ -0,0 +1,158 @@ +/* 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.Collections.Generic; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; + +// The pace of the seeded legs (aetheria-living-world, cut region-haul-legs fix batch; finding offscreen-flight-2-5x-optimistic, +// advance-pace-and-flight-bound-unpinned, stale-dive-handler-throws-after-fly, legs-wedge-at-a-full-stock-bay, to-can-call-space-clause-hangs, +// stream-copy-and-stale-comments): off screen a hauler crosses a zone in about the time its pilot takes on screen, and the stream, the +// dive and the stock bay are pinned. +public sealed partial class RunStartTests +{ + private float FirstHopReach(Leg candidate) => math.length(candidate.FromZone.Contents.WormholeTo(candidate.Path[1]) - candidate.FromZone.Contents.GetOrbitPosition(candidate.From.OrbitData)); + + // The sim seconds a stocked hauler takes from the call at its From station to being a member of the first hop's zone, flown on screen + // (the zone steps; the pilot flies it) or off screen (HaulRun.Fly given a long budget and told to stop at the hop zone: the seconds it + // spent are the budget less what it returns). The crossing is the shortest of 2 km or more on seed 2 among the first leg of each zone. + private double FirstHopSeconds(bool onScreen) + { + var (galaxy, _, legs) = SeededRegion(2, quiet: true); + var leg = legs.Where(candidate => candidate.Path.Length >= 2 && candidate.FromZone != galaxy.Entrance).GroupBy(candidate => candidate.FromZone).Select(group => group.First()) + .Where(candidate => FirstHopReach(candidate) >= 2000).OrderBy(FirstHopReach).First(); + Stock(leg.From, leg.Good, 10); + var zone = leg.FromZone.Contents; + var hop = leg.Path[1].Contents; + if (!onScreen) + { + var advanced = new HashSet(galaxy.Zones.Select(candidate => candidate.Contents).Where(candidate => candidate != hop)); + var spent = 1000 - HaulRun.Fly(leg.Hauler, 1000, null, advanced); + Assert.Same(hop, leg.Hauler.Zone); + return spent; + } + var seconds = 0.0; + while (leg.Hauler.Zone == zone && seconds < 3600) { zone.Update(.02f); seconds += .02; } + Assert.Same(hop, leg.Hauler.Zone); + return seconds; + } + + // Off screen a hauler crosses a zone in about the sim time the same hauler takes on screen: Fly flies distance over TopSpeedOf and + // charges the dive, which is what the pilot spends (measured on seeds 1 to 3, see HaulRun.Fly). The ratio off/on is bounded on both + // sides by the margin rule (lodur:ruling:deterministic-bound-margin), measured at the head on Starfire, Debug: shipped 0.996 (25.07 s off, 25.16 s on: a 2.1 km crossing of a 100 m/s hull). Mutants: + // Fly at half the speed 1.834 (46.1 s), at twice the speed 0.578 (14.5 s). sqrt(.996 * 1.834) = 1.35, sqrt(.996 * .578) = 0.76, 1.36 and 1.31 + // from the shipped reading. + [Fact] + public void OffScreenFlightAgreesWithOnScreen() + { + var off = FirstHopSeconds(onScreen: false); + var on = FirstHopSeconds(onScreen: true); + Assert.InRange(off / on, FlightLow, FlightHigh); + } + + private const double FlightLow = 0.76, FlightHigh = 1.35; + + // Advance flies a hauler the span its zone missed, no more: a long crossing flown in a pass of 60 s and then one of 5 s moves the hauler + // speed x 5 s in the second (distance from the first pass's position along its heading), not the absolute time of the pass. + [Fact] + public void AdvanceFliesTheSpanAZoneMissed() + { + Leg leg = null; + Galaxy galaxy = null; + foreach (var seed in new uint[] { 1, 2, 3 }) + { + var (candidateGalaxy, _, legs) = SeededRegion(seed, quiet: true); + leg = legs.Where(candidate => candidate.Path.Length >= 2 && candidate.FromZone != candidateGalaxy.Entrance) + .FirstOrDefault(candidate => FirstHopReach(candidate) > Agent.TopSpeedOf(candidate.Hauler) * 80); + galaxy = candidateGalaxy; + if (leg != null) break; + } + Assert.NotNull(leg); + Stock(leg.From, leg.Good, 10); + var speed = Agent.TopSpeedOf(leg.Hauler); + var zone = leg.FromZone.Contents; + var start = zone.ExactTime; + RegionClock.Advance(galaxy, null, start + 60); + Assert.Same(zone, leg.Hauler.Zone); + var before = leg.Hauler.Position.xz; + RegionClock.Advance(galaxy, null, start + 65); + Assert.Same(zone, leg.Hauler.Zone); + Assert.Equal(speed * 5, math.length(leg.Hauler.Position.xz - before), 1); + } + + // A hauler mid-dive in the player's zone, which stops being the player's zone: the next Advance flies it through, and nothing on the + // ship still points at the dive. Stepped in the hop zone afterwards it throws nothing, is no longer animating, and is a member of one zone. + [Fact] + public void AHaulerMidDiveWhenAdvanceFliesItLeavesNoStaleDive() + { + var (galaxy, _, legs) = SeededRegion(2, quiet: true); + var leg = legs.Where(candidate => candidate.Path.Length >= 2 && candidate.FromZone != galaxy.Entrance).OrderBy(FirstHopReach).First(candidate => FirstHopReach(candidate) < 3000); + Stock(leg.From, leg.Good, 10); + var zone = leg.FromZone.Contents; + var hop = leg.Path[1].Contents; + for (var elapsed = 0f; elapsed < 600 && !leg.Hauler.WormholeAnimationInProgress && leg.Hauler.Zone == zone; elapsed += .02f) zone.Update(.02f); + Assert.True(leg.Hauler.WormholeAnimationInProgress, "the hauler never began its dive"); + Assert.Same(zone, leg.Hauler.Zone); + RegionClock.Advance(galaxy, galaxy.Entrance.Contents, zone.ExactTime + 6); + Assert.Contains(leg.Hauler, hop.Entities); + Assert.DoesNotContain(leg.Hauler, zone.Entities); + Assert.False(leg.Hauler.WormholeAnimationInProgress); + for (var elapsed = 0f; elapsed < 12; elapsed += .02f) hop.Update(.02f); + Assert.Equal(1, galaxy.Zones.Count(candidate => candidate.Contents.Entities.Contains(leg.Hauler))); + } + + // CanCall at the To station reads the physical space: with the stock bays full of other goods a carried good that the station wants has + // no place to land and the call is refused (a call allowed here docks, stores nothing and undocks, once per step of Fly). + [Fact] + public void ACallAtAFullStockBayIsRefused() + { + var (_, _, legs) = SeededRegion(1, quiet: true); + var leg = legs.First(candidate => candidate.Path.Length >= 2); + Stock(leg.From, leg.Good, 10); + Assert.True(HaulRun.CanCall(leg.Hauler, leg.From, leg.Order)); + Assert.True(HaulRun.Call(leg.Hauler, leg.From) > 0); + Assert.True(Held(new[] { leg.Hauler }, leg.Good) > 0); + Assert.NotEmpty(StationWants.Landing(leg.To, leg.Good)); + Assert.True(HaulRun.CanCall(leg.Hauler, leg.To, leg.Order)); + var filler = _cache.GetAll().First(data => !StationWants.Consumed(leg.To).Contains(_cache.RefOf(data).Key) && data.MaxStack > 0); + foreach (var bay in leg.To.CargoBays.Where(bay => !(bay.Data is SiloData))) + while (bay.TryStore(new SimpleCommodity { Data = new CultRecordRef(_cache.RefOf(filler).Key), Quantity = 1 })) { } + Assert.NotEmpty(StationWants.Landing(leg.To, leg.Good).Where(landing => landing.Room > 0)); + Assert.False(HaulRun.CanCall(leg.Hauler, leg.To, leg.Order)); + } + + // An order carries only goods its To station's installed recipes consume, and a hauler holds nothing else: after 24 sim h on seed 1 every + // hauler's cargo of its order's goods is something its To station draws. + [Fact] + public void NoHaulerHoldsAGoodItsToNeverConsumes() + { + var (galaxy, _, legs) = SeededRegion(1); + AdvanceBy(galaxy, null, 0, 24 * 3600); + Assert.NotEmpty(legs); + foreach (var leg in legs) + { + var consumed = StationWants.Consumed(leg.To); + Assert.All(leg.Order.Goods.Select(good => good.Key), good => Assert.Contains(good, consumed)); + foreach (var bay in leg.Hauler.CargoBays) + foreach (var stack in bay.Cargo.Keys.OfType().Where(stack => leg.Order.Goods.Any(good => good.Key.Equals(((ItemInstance) stack).Data.Key)))) + Assert.Contains(((ItemInstance) stack).Data.Key, consumed); + } + } + + // The legs' item stream is their own (RunStart.LegStep, clear of the steps and the region's) and moves from hauler to hauler: LoadoutGenerator + // draws on its own copy of the stream, so without RegionLegs carrying it back every hauler of a faction would be the same ship. + [Fact] + public void TheLegStreamIsItsOwnAndMoves() + { + Assert.DoesNotContain(RunStart.LegStep, new[] { RunStart.ArenaStep, RunStart.StageStep, RunStart.ContinueStep }); + Assert.True(RunStart.LegStep < RunStart.RegionStep); + var (_, _, legs) = SeededRegion(1); + string Fingerprint(Ship ship) => string.Join("|", _items.GetData(ship.EquippedHull.EquippableItem).Name, string.Join(",", ship.Equipment.Select(unit => _items.GetData(unit.EquippableItem).Name))); + foreach (var faction in legs.GroupBy(leg => leg.Hauler.Faction).Where(group => group.Count() >= 4)) + Assert.True(faction.Select(leg => Fingerprint(leg.Hauler)).Distinct().Count() > 1, $"every hauler of {faction.Key?.Name} is the same ship"); + } +}