diff --git a/Assets/Scripts/ServerShared/Behaviors/Facility.cs b/Assets/Scripts/ServerShared/Behaviors/Facility.cs index 8ca2a9f90..e3ba8466a 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Facility.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Facility.cs @@ -33,6 +33,9 @@ public class Facility : Behavior // until the hold changes a retry fails the same way and is skipped. Not persisted: a restored facility tries once on its first step. private long _failedAt; + // How many steps tried to take a cycle's inputs: a diagnostic of the skip above, derived and not persisted. + public int Attempts { get; private set; } + public Facility(FacilityData data, EquippedItem item) : base(data, item) { _runList = Production.RunList(ItemManager.ItemData, Item.EquippableItem.Data.Key); @@ -43,6 +46,7 @@ public class Facility : Behavior _hold ??= new EntityHold(Entity); var idle = Item.EquippableItem.Run == null || Item.EquippableItem.Run.Progress <= 0; if (idle && Stall == Stall.Inputs && _hold.Revision == _failedAt) return true; + Attempts++; var (run, stall) = Production.Advance(ItemManager.ItemData, _runList, Item.EquippableItem.Run, dt, _hold); Item.EquippableItem.Run = run; Stall = stall; diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 23f83e37b..2c2cfefdb 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -51,6 +51,11 @@ public abstract class Entity public readonly ReactiveCollection Equipment = new ReactiveCollection(); public readonly ReactiveCollection CargoBays = new ReactiveCollection(); + // The one counter of what the entity's bays hold: it moves on every change to any bay's contents and on every bay seated or removed, + // and never returns to a value it had. Not persisted. A holder that remembers the value it last read learns whether anything it could + // hold changed since, without comparing the contents. + public long CargoRevision { get; private set; } + internal void CargoChanged() => CargoRevision++; public readonly ReactiveCollection DockingBays = new ReactiveCollection(); public readonly ReactiveCollection VisibleEntities = new ReactiveCollection(); // The cache of IsHostileTo for each zone entity: written only by RefreshStance, refreshed each Update. @@ -1491,6 +1496,7 @@ public abstract class Entity } CargoBays.Remove(cargoBay); + CargoChanged(); } Equipment.Remove(item); @@ -1693,6 +1699,7 @@ public abstract class Entity { equippedItem = new EquippedCargoBay(ItemManager, item, hullCoord, this, $"{Name} Cargo Bay {CargoBays.Count + 1}"); CargoBays.Add((EquippedCargoBay) equippedItem); + CargoChanged(); } } else @@ -2425,10 +2432,6 @@ public class EquippedCargoBay : EquippedItem public float ThermalMass { get; private set; } public string Name { get; } - // Counts every change to what the bay holds (a stack stored, merged, split or removed, a unit stored or removed). Monotonic and - // not persisted: a holder that remembers the value it last read learns whether the contents changed since, without comparing them. - public long Revision { get; private set; } - public Shape UnoccupiedSpace { get @@ -2583,7 +2586,7 @@ public class EquippedCargoBay : EquippedItem Occupancy[pos.x, pos.y] = item; } Cargo[item] = cargoCoord; - Revision++; + Entity.CargoChanged(); if(!ItemsOfType.ContainsKey(item.Data.Key)) ItemsOfType[item.Data.Key] = new List(); @@ -2591,7 +2594,7 @@ public class EquippedCargoBay : EquippedItem } else if (Occupancy[cargoCoord.x, cargoCoord.y] is ICommodityStack held && stack.StacksWith(Occupancy[cargoCoord.x, cargoCoord.y])) { - Revision++; + Entity.CargoChanged(); if (held.Quantity + stack.Quantity <= maxStack) { held.Quantity += stack.Quantity; @@ -2629,7 +2632,7 @@ public class EquippedCargoBay : EquippedItem Occupancy[pos.x, pos.y] = item; } Cargo[item] = cargoCoord; - Revision++; + Entity.CargoChanged(); if(!ItemsOfType.ContainsKey(item.Data.Key)) ItemsOfType[item.Data.Key] = new List(); @@ -2688,7 +2691,7 @@ public class EquippedCargoBay : EquippedItem if (item is ICommodityStack stack && quantity < stack.Quantity) { var itemData = ItemManager.GetData(item); - Revision++; + Entity.CargoChanged(); stack.Quantity -= quantity; Mass -= itemData.Mass * quantity; ThermalMass -= itemData.Mass * itemData.SpecificHeat * quantity; @@ -2710,7 +2713,7 @@ public class EquippedCargoBay : EquippedItem // The item, with everything it holds, leaves the bay: the one place a cell is freed. private void RemoveWhole(ItemInstance item) { - Revision++; + Entity.CargoChanged(); foreach(var v in Data.InteriorShape.Coordinates) if (Occupancy[v.x, v.y] == item) Occupancy[v.x, v.y] = null; diff --git a/Assets/Scripts/ServerShared/Production.cs b/Assets/Scripts/ServerShared/Production.cs index a3e3902ce..e97fc58a0 100644 --- a/Assets/Scripts/ServerShared/Production.cs +++ b/Assets/Scripts/ServerShared/Production.cs @@ -101,6 +101,14 @@ public static class Production } var recipe = catalog.Get(run.Recipe); + // A run whose recipe the catalog no longer has, or no longer runs here (a save outliving a catalog edit), is dropped: its + // progress is gone and the inputs it took stay consumed, as they are taken whole at cycle start and the recipe that named + // them is not there to return them against. The facility then starts its next recipe, and Advance never throws on it. + if (recipe == null || !Runs(catalog, recipe)) + { + run = null; + continue; + } var progress = run.Progress; if (progress < recipe.Cycle) { @@ -132,17 +140,8 @@ public sealed class EntityHold : IProductionHold public EntityHold(Entity entity) => _entity = entity; - // Changes whenever anything the bays hold changes (each bay counts its own changes); a bay seated or removed moves it too. A holder - // that remembers the value it last failed to take from learns whether a retry could differ. - public long Revision - { - get - { - long revision = _entity.CargoBays.Count; - for (var at = 0; at < _entity.CargoBays.Count; at++) revision += _entity.CargoBays[at].Revision; - return revision; - } - } + // The entity's cargo revision: moves on every change to the bays' contents and on every bay seated or removed, never repeats. + public long Revision => _entity.CargoRevision; public int Held(CultRecordKey design) => _entity.CargoBays.Sum(bay => bay.Count(design)); diff --git a/Assets/Scripts/ServerShared/Recipes.cs b/Assets/Scripts/ServerShared/Recipes.cs index 4a5de9631..8bd6dc430 100644 --- a/Assets/Scripts/ServerShared/Recipes.cs +++ b/Assets/Scripts/ServerShared/Recipes.cs @@ -148,7 +148,9 @@ public static class Recipes // Role to its fillers, derived from the recipes and owned by the catalog it was built from (one index per catalog, dropped with it). // The catalog is read-only while a game runs, so a build serves every read; a write to a recipe or a commodity design (a test, an - // authoring batch) marks it stale, and the next read rebuilds it. + // authoring batch) marks it stale, and the next read rebuilds it. It is right only for recipes written through the catalog: a + // document edited in place and never written back is outside the catalog's admission, so the index cannot see it and the scan it + // replaced could. Write an edited recipe back (every authoring path and fixture does). private sealed class FillerIndex { private readonly CultCache _catalog; diff --git a/tests/Aetheria.Shared.Tests/FacilityProductionTests.cs b/tests/Aetheria.Shared.Tests/FacilityProductionTests.cs index 240c3d530..74b7bdfc2 100644 --- a/tests/Aetheria.Shared.Tests/FacilityProductionTests.cs +++ b/tests/Aetheria.Shared.Tests/FacilityProductionTests.cs @@ -373,28 +373,102 @@ public sealed class FacilityProductionTests : IDisposable Assert.Equal(0, Held(world, IronFillers[0])); } - // The bay's change count moves on every kind of change to its contents and on nothing else. + // The entity's cargo revision moves on every kind of change to what its bays hold (a stack stored, merged, split or removed, a unit + // stored or removed, a bay seated or removed) and on nothing else. [Fact] - public void ABayCountsEveryChangeToWhatItHolds() + public void TheCargoRevisionCountsEveryChangeToWhatTheBaysHold() { var world = Build(); var bay = world.Station.CargoBays[0]; - var at = bay.Revision; - Assert.Equal(at, bay.Revision); + var at = world.Station.CargoRevision; + Assert.Equal(at, world.Hold.Revision); + void Moved() { Assert.True(world.Station.CargoRevision > at); at = world.Station.CargoRevision; } Assert.True(bay.TryStore(Goods("Slag", 5))); - Assert.True(bay.Revision > at); - at = bay.Revision; + Moved(); Assert.True(bay.TryStore(Goods("Slag", 5))); - Assert.True(bay.Revision > at); - at = bay.Revision; + Moved(); var stack = bay.Cargo.Keys.Single(); Assert.NotNull(bay.Remove(stack, 3)); - Assert.True(bay.Revision > at); - at = bay.Revision; - Assert.Equal(7, bay.Count(((ItemInstance) stack).Data.Key)); - Assert.Equal(at, bay.Revision); + Moved(); + Assert.Equal(7, bay.Count(stack.Data.Key)); + Assert.Equal(at, world.Station.CargoRevision); bay.Remove(stack); - Assert.True(bay.Revision > at); + Moved(); + var unit = Mint(world.Items, _cache, "Pocket"); + Assert.True(bay.TryStore(unit)); + Moved(); + bay.Remove(unit); + Moved(); + world.Station.Deactivate(); + var pocket = world.Station.TryEquip(Mint(world.Items, _cache, "Pocket"), new int2(6, 6)); + Assert.True(pocket); + Moved(); + Assert.NotNull(world.Station.TryUnequip(world.Station.CargoBays[1])); + Moved(); + } + + // Soul's sequence: a take fails with 2 ore held; the station is deactivated, its empty second bay removed, one ore stored, and it + // is activated again. The hold's revision is never the one the failure recorded, so the facility takes the 3 ore. + [Fact] + public void AFacilityTakesWhatIsStockedAfterABayLeaves() + { + var world = Build(); + world.Station.Deactivate(); + Assert.True(world.Station.TryEquip(Mint(world.Items, _cache, "Pocket"), new int2(6, 6))); + world.Station.Activate(); + Stock(world, IronFillers[0], 2); + Step(world, 3); + Assert.Equal(Stall.Inputs, world.Facility.Stall); + + world.Station.Deactivate(); + Assert.NotNull(world.Station.TryUnequip(world.Station.CargoBays[1])); + Stock(world, IronFillers[0], 1); + world.Station.Activate(); + Step(world, 3); + Assert.NotNull(world.Unit.Run); + Assert.Equal(0, Held(world, IronFillers[0])); + } + + // An idle facility whose take failed does not try again until the hold changes: the failed take is recorded. + [Fact] + public void AnIdleFacilityDoesNotRetryUntilTheHoldChanges() + { + var world = Build(); + Stock(world, IronFillers[0], 2); + Step(world, 20); + Assert.Equal(1, world.Facility.Attempts); + Stock(world, IronFillers[0], 1); + Step(world, 1); + Assert.Equal(2, world.Facility.Attempts); + Assert.NotNull(world.Unit.Run); + } + + // A save written mid-cycle, then a catalog that no longer has the recipe: the run is dropped, the inputs it took stay consumed, and + // the facility starts its next recipe. Nothing throws on any step. + [Fact] + public void ASaveNamingADeletedRecipeIsDroppedNotThrown() + { + var world = Build(); + var copperOre = Recipes.Fillers(_cache, "copper ore").Except(IronFillers).First(); + Stock(world, IronFillers[0], 3); + Step(world, 101); + Assert.Equal(RecipeData.KeyOf(Iron), world.Unit.Run.Recipe.Key); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + var bytes = MessagePackSerializer.Serialize(EntitySerializer.Pack(world.Station), options); + + _cache.Remove(RecipeData.KeyOf(Iron)); + var zone = new Zone(world.Items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + var station = (OrbitalEntity) EntitySerializer.Unpack(world.Items, zone, MessagePackSerializer.Deserialize(bytes, options)); + if (!zone.Entities.Contains(station)) zone.Admit(station, piloted: false); + var restored = Wrap(world.Items, zone, station); + Assert.Equal(RecipeData.KeyOf(Iron), restored.Unit.Run.Recipe.Key); + + Stock(restored, copperOre, 4); + Step(restored, 2); + Assert.Equal(RecipeData.KeyOf(new CultRecordKey("commodity:copper")), restored.Unit.Run.Recipe.Key); + Assert.Equal(0, Held(restored, copperOre)); + Assert.Equal(0, Held(restored, Iron)); + Assert.Equal(0, Held(restored, IronFillers[0])); } // Recipes.Fillers reads an index built once per catalog; it is rebuilt when a recipe changes.