From f38eb87399e402cbf4dc941f19a6855feefb8228 Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 22 Sep 2026 10:02:04 -0700 Subject: [PATCH] Announce only accepted goods, and leave mixed mode fully on reload Two follow-ups from the v1.1.0 reviews. A saved allocation can name a good the game no longer knows, for example after a goods mod is removed. Leaving mixed mode announced every allocated good, and announcing an unknown good reaches InventoryRegistry._inventoriesWithCapacity[good], which throws. Now only goods the building accepts are announced; the game limits any other good to 0 whatever the allocation says (Inventory.LimitedAmount), so nothing else needs to hear about it. A mixed building reloaded without an allocation (the map editor's undo) cleared its shares without announcing its goods, so the game's caches kept the old limits. A redraw already queued then met null shares and disabled mixed visuals for that building for the session. Load now announces the goods of the old and new allocation when a mixed building is reloaded, like Deactivate. That sends its visuals back to the native pile. A queued redraw that finds no allocation now releases the sections instead of failing. A normal save load still announces nothing: a building is never mixed before its own load. visual-tests/AnnouncementTests.cs runs StorageState against the game's own SingleGoodAllower and Inventory, created without Unity, and records every announced good. It fails on main with "announced [Log, Gone], expected [Log]", and fails on a Load that does not announce. Co-Authored-By: Claude Opus 5.5 --- docs/DEVELOPMENT.md | 3 +- source/MixedContentsRenderer.cs | 3 + source/StorageState.cs | 48 +++++++---- visual-tests/AnnouncementTests.cs | 137 ++++++++++++++++++++++++++++++ visual-tests/GameApiTests.cs | 1 + 5 files changed, 173 insertions(+), 19 deletions(-) create mode 100644 visual-tests/AnnouncementTests.cs diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index edc5284..df88dbb 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -18,7 +18,7 @@ The allocation checks need no game files, so GitHub Actions also runs them on ev Percentages use integer units totaling 10,000. Whole-item limits use largest-remainder rounding with ordinal good-ID ordering for ties. Incoming reservations guard against conflicting limit reductions; existing excess stock is preserved. Copy/paste transfers percentages atomically into a draft and rejects incompatible goods. Hauling mode and priority are not copied. In Supply mode a mixed building offers its allocated goods with the most unreserved stock first, ordinal good IDs breaking ties (`AllocationPlan.SupplyCandidates`). Goods without unreserved stock are skipped: the game's search for a building to take one scans the whole district and can only fail, so skipping them never changes which good is carried. Those searches did fill the building's cached road route map, which a few of the game's path queries use only when it is already filled, so co-op players still need the same MixedStorage build. -The game's Duplicate settings tool calls `SingleGoodAllower.DuplicateFrom`. A mixed source applies its allocation to the target through the same checks as Apply. They run before the base game's copy of the single good, so when they reject it that copy is skipped and logged, and the target keeps its allocation or single good whether or not it was mixed. The tool copies each of the building's other settings separately, such as the storage mode (`StockpilePriority`), so those still apply. A source set to store nothing, such as a building just placed, leaves a mixed target's allocation alone (the base game would clear the target's good), so copying the storage mode from a new building does not wipe a tuned allocation, which has no undo. Any other source gives the target that building's single good, as in the base game, so a mixed target first leaves mixed mode (`StorageState.Deactivate`). That is the only way back to the base game's rules. The storage panel stores a single good as a 100% allocation, so such a source is a building given a single good in the goods dropdown of the game's building list (`StockpileDropdownProvider`, which still works on a building without an allocation; `AllowPatch` and `DisallowPatch` ignore it on a mixed one), a warehouse or pile from before the mod, or a storage the mod does not manage, such as the map editor's reserve storage or another mod's storage. Leaving lowers limits too, so it gets Apply's incoming-delivery guard: the base game has room only for the kept good, and none for it while any other good is in stock. A delivery that would no longer fit refuses the copy the same way, before the base game's copy runs. The decision is `AllocationPlan.PlanCopy`, and what the patch then does (leave, run the base game's copy, apply, or log a refusal) is `AllocationPlan.Steps`; the allocation tests cover both. BeaverBuddies replays the tool on every player (`DuplicationEvent`), and the decision reads only simulation state (accepted goods, capacity, stock and reservations), so every player decides the same. Leaving mixed mode announces every formerly allocated good, because the game's `InventoryRegistry` caches which buildings have room for each good and only updates a good when it is announced. During those announcements the visuals are pointed at the representative good, so the pile keeps showing what it holds. Loading also mirrors the save: a building loaded without an allocation (for example by the map editor's undo) leaves mixed mode. +The game's Duplicate settings tool calls `SingleGoodAllower.DuplicateFrom`. A mixed source applies its allocation to the target through the same checks as Apply. They run before the base game's copy of the single good, so when they reject it that copy is skipped and logged, and the target keeps its allocation or single good whether or not it was mixed. The tool copies each of the building's other settings separately, such as the storage mode (`StockpilePriority`), so those still apply. A source set to store nothing, such as a building just placed, leaves a mixed target's allocation alone (the base game would clear the target's good), so copying the storage mode from a new building does not wipe a tuned allocation, which has no undo. Any other source gives the target that building's single good, as in the base game, so a mixed target first leaves mixed mode (`StorageState.Deactivate`). That is the only way back to the base game's rules. The storage panel stores a single good as a 100% allocation, so such a source is a building given a single good in the goods dropdown of the game's building list (`StockpileDropdownProvider`, which still works on a building without an allocation; `AllowPatch` and `DisallowPatch` ignore it on a mixed one), a warehouse or pile from before the mod, or a storage the mod does not manage, such as the map editor's reserve storage or another mod's storage. Leaving lowers limits too, so it gets Apply's incoming-delivery guard: the base game has room only for the kept good, and none for it while any other good is in stock. A delivery that would no longer fit refuses the copy the same way, before the base game's copy runs. The decision is `AllocationPlan.PlanCopy`, and what the patch then does (leave, run the base game's copy, apply, or log a refusal) is `AllocationPlan.Steps`; the allocation tests cover both. BeaverBuddies replays the tool on every player (`DuplicationEvent`), and the decision reads only simulation state (accepted goods, capacity, stock and reservations), so every player decides the same. Leaving mixed mode announces every formerly allocated good the building accepts, because the game's `InventoryRegistry` caches which buildings have room for each good and only updates a good when it is announced. A good the building does not accept is limited to 0 by the game whatever the allocation says, and a saved allocation can name a good the game no longer knows (after a goods mod is removed), which `InventoryRegistry` would throw on, so neither is announced. During those announcements the visuals are pointed at the representative good, so the pile keeps showing what it holds. Loading also mirrors the save: a mixed building reloaded without an allocation (the map editor's undo) leaves mixed mode the same way, and one reloaded with another allocation announces the goods of both. A building loaded from a save is never mixed before its own load, so a normal save load announces nothing. A redraw queued before a building left mixed mode finds no allocation and puts the native pile back instead of disabling the mixed visuals. Every announcement goes through the game's private `SingleGoodAllower.InvokeDisallowedGoodsChangedEvent(string)`, looked up by signature when `ModStarter` starts. If a game update renames or changes it, `ModStarter` logs why and allocations are frozen instead of half-applied: Apply is refused with that reason, and so is every copy that would set or leave an allocation (from a mixed building, or onto one), while copies between single-good buildings work as in the base game. A mixed building stays mixed, and saved allocations keep limiting their buildings. The game still starts: `ModStarter` reads this through `AllocationProblem`, which also reports, rather than throws, a `StorageState` that cannot load at all. Frozen mode depends on the installed game, so every co-op player must run the same game version; BeaverBuddies only warns when they differ, and a player whose game lacks the method would refuse changes the others apply. @@ -55,6 +55,7 @@ The mod reuses the installed game's styles and assets: `NineSliceVisualElement` - Every Harmony patch in the built DLL checked against installed game assemblies (`visual-tests/PatchTargetTests.cs`), resolved the way Harmony does at startup: 22 targets in 20 patch classes, the 4 injected `___` fields and the 11 other named parameters, with their types. A renamed target would otherwise throw from `PatchAll` and stop the game from starting. The same test checks the 6 reflection handles the mod keeps in static fields, the 8 native visualizer members `MixedContentsRenderer` reads by name, that the mod reads the installed BeaverBuddies' `EventIO.IsNull` as "no connection", and that LateGamePerformance's two trusted patches keep their names and Harmony id, with no other patch on the methods its counting workers call, on its 15 saving helpers, or on anything one of the game's component `Save` methods calls directly (read from their IL). - 201 whole-cell partition cases covering boundary ownership, complete topology, compact vertices, per-vertex attributes, and unknown-topology fallback. - 400 random piles (plain and rotated/scaled transforms, random section boundaries) whose extracted sections are compared triangle by triangle with the original algorithm that transformed and kept every vertex, plus the whole-mesh fit used for bulk surfaces. +- Leaving mixed mode and reloading a building run against the game's own `SingleGoodAllower` and `Inventory`, created without Unity (`visual-tests/AnnouncementTests.cs`): the goods the mod announces are recorded, and must be exactly the allocated goods the building accepts, never one the game no longer knows, all announced as the mod's own change; a normal save load announces nothing. - Ten native API signatures checked against installed game assemblies: nine for rendering, plus the goods announcement. The old ambiguous Initialize lookup is reproduced as a regression check, and `StorageState`'s IL must look the announcement up by its `(string)` signature. A copy of the built mod with the announcement's name changed must report why through `ModStarter.AllocationProblem`, refuse Apply and every copy that would set or leave an allocation, and keep a mixed building mixed. A copy with a game type `StorageState` keeps in a static field renamed must be reported there too, without throwing. `StartMod` and `DuplicatePatch` need Unity, so their IL is checked instead: `StartMod` asks `AllocationProblem` before patching and never touches `StorageState` itself, and `DuplicatePatch` checks for frozen allocations before anything else. - Isolated loading processes with and without BeaverBuddies check eager main-type enumeration, bridge event discovery, delegate installation, repeated initialization, and obsolete-addon rejection. A stub BeaverBuddies with one member missing (`loading-tests/StubBeaverBuddies`) checks that an incompatible build is skipped without stopping startup, that the reason names exactly that member, that a failed bridge is not loaded twice, and that Apply without the bridge only counts as single-player when BeaverBuddies reports no connection. They also check that every prefix that can replace the game's method (every prefix returning `bool`, in every class Harmony's `PatchAll` would patch) carries `[HarmonyPriority(Priority.Last)]`, on the method or on its class. - BeaverBuddies replays the Duplicate settings tool on every player. A loading check walks the IL of the patches that run inside that replay, and of every mod method they call, and fails if any of them reads the panel's message or pending state, the panel or renderer, submits a command, or reads a clock, input or random numbers (`loading-tests/ReplayChecks.cs`). Two control scans check that it finds such state where the mod does use it. diff --git a/source/MixedContentsRenderer.cs b/source/MixedContentsRenderer.cs index 77d5eec..4ca5d22 100644 --- a/source/MixedContentsRenderer.cs +++ b/source/MixedContentsRenderer.cs @@ -196,6 +196,9 @@ private static KeyValuePair[] SortedShares(StorageState state) private void Render(StockpileVisualizers owner, StorageState state) { if (_busy || _failed) return; + // A redraw queued before the building left mixed mode, for example when a reload leaves it without an + // allocation, finds no shares; the native pile is back. + if (!state.Active) { Release(); return; } if (_sharesRevision != state.Revision) { _shares = SortedShares(state); diff --git a/source/StorageState.cs b/source/StorageState.cs index c75090e..7512781 100644 --- a/source/StorageState.cs +++ b/source/StorageState.cs @@ -130,8 +130,6 @@ private void Publish() } // Returns the building to the base game's single-good rules; the caller then sets that good. - // Every formerly allocated good is announced because its limit changes, and the game caches - // which buildings have room for each good. public void Deactivate() { // Without the announcement the building stays mixed (see UnavailableReason), and AllowPatch then keeps @@ -139,10 +137,20 @@ public void Deactivate() if (!Active || UnavailableReason != null) return; var previous = Shares; SetShares(null); - // While these fire, the building still has its representative good; the visuals must follow - // that good (VisualizerPatch), not whichever formerly allocated good is announced last. + Announce(previous.Keys); + } + + // Announces goods whose limit changed, because the game caches which buildings have room for each good. + // Only goods the building accepts: the game limits any other good to 0 whatever the allocation says + // (Inventory.LimitedAmount), and a saved allocation can name a good the game no longer knows, which + // would throw from InventoryRegistry. While these fire, the building still has its representative good; + // the visuals must follow that good (VisualizerPatch), not whichever good is announced last. Without the + // announcement method (see UnavailableReason) nothing is announced. + private void Announce(IEnumerable goods) + { + if (NotifyGood == null) return; InternalChange = true; - try { foreach (string good in previous.Keys) Notify(good); } + try { foreach (string good in goods) if (Inventory.Takes(good)) Notify(good); } finally { InternalChange = false; } } @@ -156,21 +164,25 @@ public void Save(IEntitySaver saver) public void Load(IEntityLoader loader) { - // The state mirrors the save, also when the map editor's undo reloads an existing building. - if (!loader.TryGetComponent(SaveKey, out var component) || !component.Has(SharesKey)) - { - if (Active) SetShares(null); - return; - } - string saved = component.Get(SharesKey); - try { SetShares(AllocationPlan.Deserialize(saved)); } - catch (FormatException ex) + // The state mirrors the save, also when the map editor's undo reloads an existing building. A building + // loaded for the first time is never mixed yet, so a mixed one is already in the world: its changed + // limits are announced as Apply and Deactivate do, which also sends its visuals back to the native pile + // when it leaves mixed mode (MixedAllocationVisualPatch). + var previous = Shares; + if (!loader.TryGetComponent(SaveKey, out var component) || !component.Has(SharesKey)) { if (Active) SetShares(null); } + else { - // One unreadable building must not stop the whole save from loading. It keeps the - // single good the base game saved alongside it, and the warning says what was lost. - if (Active) SetShares(null); - Debug.LogWarning("[MixedStorage] Ignoring an unreadable saved allocation for " + Allower.Name + " (" + ex.Message + "): " + saved); + string saved = component.Get(SharesKey); + try { SetShares(AllocationPlan.Deserialize(saved)); } + catch (FormatException ex) + { + // One unreadable building must not stop the whole save from loading. It keeps the + // single good the base game saved alongside it, and the warning says what was lost. + if (Active) SetShares(null); + Debug.LogWarning("[MixedStorage] Ignoring an unreadable saved allocation for " + Allower.Name + " (" + ex.Message + "): " + saved); + } } + if (previous != null) Announce(previous.Keys.Union(Shares?.Keys ?? Enumerable.Empty(), StringComparer.Ordinal)); } public void Duplicate(StorageState source) diff --git a/visual-tests/AnnouncementTests.cs b/visual-tests/AnnouncementTests.cs new file mode 100644 index 0000000..4951c69 --- /dev/null +++ b/visual-tests/AnnouncementTests.cs @@ -0,0 +1,137 @@ +#nullable enable +using System.Linq.Expressions; +using System.Reflection; + +// Leaving mixed mode and reloading a building run the built mod's StorageState against the game's own +// SingleGoodAllower and Inventory, created without Unity. The allower's DisallowedGoodsChanged event records every +// good the mod announces, which is what the game's inventories and InventoryRegistry react to. +internal static class AnnouncementTests +{ + public static void Run(Assembly mod, Func gameType) + { + const BindingFlags Instance = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + var stateType = mod.GetType("MixedStorage.StorageState", true)!; + var allowerType = gameType("Timberborn.InventorySystem", "Timberborn.InventorySystem.SingleGoodAllower"); + var inventoryType = gameType("Timberborn.InventorySystem", "Timberborn.InventorySystem.Inventory"); + var registryType = gameType("Timberborn.Goods", "Timberborn.Goods.StorableGoodRegistry"); + var storableType = gameType("Timberborn.Goods", "Timberborn.Goods.StorableGood"); + var amountType = gameType("Timberborn.Goods", "Timberborn.Goods.StorableGoodAmount"); + var entityLoaderType = gameType("Timberborn.WorldPersistence", "Timberborn.WorldPersistence.IEntityLoader"); + var objectLoaderType = gameType("Timberborn.Persistence", "Timberborn.Persistence.IObjectLoader"); + var serialize = mod.GetType("MixedStorage.AllocationPlan", true)!.GetMethod("Serialize")!; + var shares = stateType.GetProperty("Shares")!; + var internalChange = stateType.GetProperty("InternalChange")!; + + // A building that accepts Log and Plank. "Gone" stands for a good a saved allocation still names after the + // mod that added it was removed: the game has no such good. + var announced = new List<(string Good, bool Internal)>(); + object state = null!; + object Storage() + { + var registry = Activator.CreateInstance(registryType)!; + var goods = Array.CreateInstance(amountType, 2); + for (int i = 0; i < 2; i++) + { + var good = storableType.GetMethod("CreateGiveableAndTakeable")!.Invoke(null, new object[] { i == 0 ? "Log" : "Plank" }); + goods.SetValue(Activator.CreateInstance(amountType, good, 30), i); + } + registryType.GetMethod("Add")!.Invoke(registry, new object[] { goods }); + var inventory = System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(inventoryType); + inventoryType.GetField("_allowedGoods", Instance)!.SetValue(inventory, registry); + var allower = System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(allowerType); + var changed = allowerType.GetEvent("DisallowedGoodsChanged")!; + var sender = Expression.Parameter(typeof(object)); + var args = Expression.Parameter(changed.EventHandlerType!.GetMethod("Invoke")!.GetParameters()[1].ParameterType); + Action record = good => announced.Add((good, (bool)internalChange.GetValue(state)!)); + var handler = Expression.Lambda(changed.EventHandlerType, Expression.Invoke(Expression.Constant(record), Expression.Property(args, "GoodId")), sender, args); + changed.AddEventHandler(allower, handler.Compile()); + state = stateType.GetConstructors(Instance).Single().Invoke(new[] { allower, inventory }); + announced.Clear(); + return state; + } + Dictionary Shares(params (string Good, int Share)[] entries) => + entries.ToDictionary(x => x.Good, x => x.Share, StringComparer.Ordinal); + object Loader(Dictionary? saved) + { + var loader = Proxy(entityLoaderType); + if (saved != null) + { + var component = Proxy(objectLoaderType); + component.Shares = (string)serialize.Invoke(null, new object[] { saved })!; + loader.Component = component; + } + return loader; + } + void Call(string method, string failure, params object[] arguments) + { + try { stateType.GetMethod(method)!.Invoke(state, arguments); } + catch (TargetInvocationException ex) { throw new Exception(failure + " " + ex.InnerException, ex); } + } + void Expect(string check, params string[] goods) + { + if (!announced.Select(x => x.Good).OrderBy(x => x, StringComparer.Ordinal).SequenceEqual(goods)) + throw new Exception($"{check}; announced [{string.Join(", ", announced.Select(x => x.Good))}], expected [{string.Join(", ", goods)}]."); + if (announced.Any(x => !x.Internal) || (bool)internalChange.GetValue(state)!) + throw new Exception(check + ", but the announcements did not all run as the mod's own change, so the visuals could follow the wrong good."); + } + + // Copy Settings leaving mixed mode. + Storage(); + shares.SetValue(state, Shares(("Log", 5000), ("Gone", 5000))); + Call("Deactivate", "Leaving mixed mode with a good the game no longer knows threw:"); + if (shares.GetValue(state) != null) throw new Exception("Deactivate left the building mixed."); + Expect("Leaving mixed mode announces the allocated goods the building accepts, and no good the game does not know", "Log"); + + // The map editor's undo reloading a mixed building without an allocation. + Storage(); + shares.SetValue(state, Shares(("Log", 5000), ("Gone", 5000))); + Call("Load", "Reloading a mixed building without an allocation threw:", Loader(null)); + if (shares.GetValue(state) != null) throw new Exception("A building reloaded without an allocation stayed mixed."); + Expect("A mixed building reloaded without an allocation announces its formerly allocated goods, as Deactivate does", "Log"); + + // Reloading a mixed building with another allocation. + Storage(); + shares.SetValue(state, Shares(("Log", 10000))); + Call("Load", "Reloading a mixed building with another allocation threw:", Loader(Shares(("Log", 5000), ("Plank", 5000)))); + Expect("A mixed building reloaded with another allocation announces the goods of both allocations", "Log", "Plank"); + + // Loading a save: a building loaded for the first time is not in the world yet, so nothing is announced. + Storage(); + Call("Load", "Loading a saved allocation threw:", Loader(Shares(("Log", 5000), ("Plank", 5000)))); + if (shares.GetValue(state) == null) throw new Exception("A saved allocation was not loaded."); + Expect("Loading a save announces nothing"); + Storage(); + Call("Load", "Loading a building without an allocation threw:", Loader(null)); + Expect("Loading a building without an allocation announces nothing"); + Console.WriteLine("PASS: leaving mixed mode and reloading a mixed building announce only goods the building accepts, never one the game no longer knows; loading a save announces nothing."); + } + + private static T Proxy(Type contract) where T : DispatchProxy => + (T)typeof(DispatchProxy).GetMethods().Single(m => m.Name == "Create" && m.IsGenericMethodDefinition) + .MakeGenericMethod(contract, typeof(T)).Invoke(null, null)!; +} + +// IEntityLoader: the building's saved components; only TryGetComponent(key, out loader) is used. +public class EntityLoaderProxy : DispatchProxy +{ + public object? Component; + + protected override object? Invoke(MethodInfo? method, object?[]? args) + { + if (method!.Name == "TryGetComponent" && args!.Length == 2) { args[1] = Component; return Component != null; } + throw new NotSupportedException("StorageState.Load called IEntityLoader." + method.Name); + } +} + +// IObjectLoader: the saved MixedStorage.Allocation component, holding only its Shares string. +public class ObjectLoaderProxy : DispatchProxy +{ + public string Shares = ""; + + protected override object? Invoke(MethodInfo? method, object?[]? args) + { + if (method!.Name == "Has") return true; + if (method.Name == "Get" && method.ReturnType == typeof(string) && args!.Length == 1) return Shares; + throw new NotSupportedException("StorageState.Load called IObjectLoader." + method.Name); + } +} diff --git a/visual-tests/GameApiTests.cs b/visual-tests/GameApiTests.cs index d50a78e..61cd0fc 100644 --- a/visual-tests/GameApiTests.cs +++ b/visual-tests/GameApiTests.cs @@ -46,6 +46,7 @@ void Method(Type type, string name, params Type[] signature) Console.WriteLine("PASS: reproduced v0.4.0 name-only Initialize lookup failure; typed lookups succeed."); Console.WriteLine($"PASS: {checks} native API signatures (rendering, and the goods announcement) resolved against installed game assemblies."); GoodsAnnouncement(modPath, allower); + AnnouncementTests.Run(Assembly.LoadFrom(modPath), GameType); } // The built mod resolves the goods announcement at startup. If a game update renamed or changed it, the