From 79e1790a5f1f38f69e29111e44bb9c8774adb9e0 Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 22 Sep 2026 07:49:15 -0700 Subject: [PATCH 1/2] PWA4: show farmhouse and forester ranges while the planting tool is open The game's planting tools draw no working areas, so a player marking crops or trees has to pin or re-select each farmhouse or forester to see where it reaches. While a crop or tree planting tool is open, the service now outlines every building that plants it, alongside the player's pins: - ToolEnteredEvent/ToolExitedEvent with `Tool is PlantingTool` (what the game's PlantingModeService uses) record the plant's resource group. PlantingToolGroupSpec is internal, so the tool group is not used. - The next UpdateSingleton scans EntityComponentRegistry.GetAll for buildings whose PlanterBuildingSpec.PlantableResourceGroup matches PlantableSpec.ResourceGroup, the pairing PlanterBuilding and PlantingToolButtonFactory use: farmhouses for crops, aquatic farmhouses for aquatic crops, foresters for trees and bushes. Construction sites are included, as pins already allow. The scan waits for the update because ToolService.SwitchTool posts the old tool's exit and the new tool's entry in one call, so switching between two crops of the same planters keeps their cached ranges and does no work. - A planter created or deleted while the tool is open triggers a rescan. - PinRefreshPlanner entries are now pinned, shown, or both, with one cache. Show(set) replaces the shown set: a building leaving it keeps its range only while pinned, and one joining it reuses a pin's cache. Navigation, selection and construction-mode handling apply to shown buildings exactly as to pins. - Clear pinned areas clears only pins; the tool's buildings stay until it closes. The renderer is released once nothing is drawn. Display only: all work stays in UpdateSingleton and event handlers that set fields; no tick, save or persistence interface, no patches. Tests (tests/Program.cs, 67 -> 95 checks): - PlantingRanges.Shows, a Unity-free rule linked into Checks.csproj. - Planner counts: opening a crop's tool queries each farmhouse once and rebuilds once; another crop for the same farmhouses is 0/0; switching to a tree queries only the forester; closing is 0 queries and 1 rebuild back to the pins; pinned-and-shown buildings keep one cache. - The rule on the game's Blueprints.zip: every plantable shows at least one planter, crops only farmhouses, trees and bushes only foresters; every planter is a workplace with an access point. - The service's tool handlers, driven with the game's own PlantingTool, CancelPlantingTool and tool events through reflection. Before the fix the checks do not compile (CS0103 PlantingRanges, CS1061 no Show on PinRefreshPlanner). Nine mutations (Show dropping pinned buildings, Add refusing a shown one, Remove dropping a shown one, Show forgetting caches, a case-insensitive rule, a rule accepting buildings without a group, exit not hiding, any tool showing planters, entry not scheduling a scan) each fail a check. The registry scan itself runs only in game. Co-Authored-By: Claude Opus 5 --- README.md | 3 +- VALIDATION.md | 7 +-- source/PinRefreshPlanner.cs | 50 +++++++++++++++-- source/PlantingRanges.cs | 13 +++++ source/WorkAreaService.cs | 86 +++++++++++++++++++++++++---- tests/Checks.csproj | 2 +- tests/Program.cs | 105 +++++++++++++++++++++++++++++++++++- 7 files changed, 245 insertions(+), 21 deletions(-) create mode 100644 source/PlantingRanges.cs diff --git a/README.md b/README.md index 80011e5..9449808 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,9 @@ No extra dependency is required. Keep your existing BeaverBuddies Stability Fork - Select a farm, forester, lumberjack flag, gatherer, or another building with a terrain/road-spill working range. - Check **Keep working area visible**. - Deselect it and use your planting/building tools. The outline remains. +- Pick a crop or tree in the planting tools and the working areas of the buildings that plant it appear on their own: every farmhouse for crops (aquatic farmhouses for aquatic crops) and every forester for trees and bushes, including ones still under construction. They disappear when you leave the planting tool; your pins stay. - Pin additional buildings as needed. Overlapping pinned areas merge into a combined outline. -- Click **Clear pinned areas (N)** at the top right to remove every pin, without finding or selecting any building. +- Click **Clear pinned areas (N)** at the top right to remove every pin, without finding or selecting any building. Areas the planting tool shows stay until you leave that tool. - For a keyboard shortcut, assign **Clear all pinned working areas** under **Persistent Work Areas** in the game's key-binding settings. It starts unbound to avoid taking an existing shortcut. - To remove just one pin, select its building and uncheck the checkbox. diff --git a/VALIDATION.md b/VALIDATION.md index c6e166d..92a5340 100644 --- a/VALIDATION.md +++ b/VALIDATION.md @@ -13,7 +13,7 @@ - Compared the display path with the installed game's `BuildingRangeDrawer`, `BoundsNavRangeDrawer`, and navigation query calls. The mod uses those same range queries and its own outline-renderer instance. - Reviewed the BeaverBuddies Stability Fork's `IO/BuildCompatibility.cs`: its handshake identifies Timberborn and the BeaverBuddies/TimberNet binaries. This mod changes none of them. - The display service only implements frame-update, input, load, and navigation-notification interfaces. Pin state is per game-scoped service instance. There are no Harmony patches, replay events, simulation ticks, random calls, or save writes. -- Renderer geometry refreshes on pin, selection, construction-mode, height-visibility and navigation changes, with navigation refreshes capped at five per second. Empty pin sets do no range queries or drawing. All pins share a combined mesh. Clearing releases the renderer's owned meshes and cloned materials. +- Renderer geometry refreshes on pin, planting-tool, selection, construction-mode, height-visibility and navigation changes, with navigation refreshes capped at five per second. With no pins and no crop or tree planting tool open, the mod does no range queries or drawing. The planting tool's farmhouses or foresters are found when the tool opens, from the game's workplace registry, and share the pins' cached ranges. All pins share a combined mesh. Clearing releases the renderer's owned meshes and cloned materials. ## Not established by the automated checks @@ -23,13 +23,14 @@ These are compiled API and logic checks, not Unity rendering tests or a co-op se Re-run this for each release and after each Timberborn update. -1. With the BeaverBuddies Stability Fork enabled, load a colony, select a farm and enable its checkbox. Deselect and paint crops: the working-area outline should remain. +1. With the BeaverBuddies Stability Fork enabled, load a colony, select a farm and enable its checkbox. Deselect, paint crops and leave the planting tool: the working-area outline should remain. 2. Pin a forester and paint trees. Pin a second nearby building; verify overlapping areas merge and separate areas both remain visible. 3. Select an unrelated building, then clear all from the top-right button. No pinned outlines should remain after deselecting. Reselect formerly pinned buildings and verify their checkboxes are off. -4. Assign the clear command in key bindings and verify it clears while a planting tool is active. Do not assign a shortcut already used by a tool. +4. Assign the clear command in key bindings and verify it clears the pins while a planting tool is active; the buildings that tool shows stay until you leave it. Do not assign a shortcut already used by a tool. 5. Modify a path or terrain, switch visible levels and construction mode, and verify the outline updates. Pause the simulation and repeat selection/clear. 6. Delete a pinned building. Its outline and pin count should disappear. Exit/load another map or perform a co-op resync: pins should be empty. 7. Join with two BeaverBuddies Stability Fork clients. Pin different buildings on each computer and clear on only one. Only that player's pins should change; normal building/planting actions should remain synchronized. +8. With a few farmhouses (one still under construction) and foresters placed and none pinned, pick a crop in the Fields tools: every farmhouse's outline should appear and no forester's. Pick a tree or bush: only the foresters'. As Folktails, pick an aquatic crop: only the aquatic farmhouses'. Pin one forester and leave the planting tool: only that forester's outline should remain. ## References diff --git a/source/PinRefreshPlanner.cs b/source/PinRefreshPlanner.cs index 00dbf3b..ab2c924 100644 --- a/source/PinRefreshPlanner.cs +++ b/source/PinRefreshPlanner.cs @@ -33,6 +33,7 @@ public bool Intersects(CellBox other) => !IsEmpty && !other.IsEmpty && // Decides which pinned ranges need a fresh navigation query and when the combined outline must be rebuilt. // Each pin caches its cells, so a navigation change re-queries only the pins it can reach, and a // selection change rebuilds the outline from the cache. Unity-free so the checks can count the work. + // A building is drawn while the player pins it, the planting tool shows it, or both; either way it has one cache. internal sealed class PinRefreshPlanner where TPin : class { // Returns false when the pin can no longer be shown. The key holds everything the query depends on @@ -42,6 +43,8 @@ internal sealed class PinRefreshPlanner where TPin : class private sealed class Entry { + public bool Pinned; + public bool Shown; public bool Described; public TKey Key; public bool Stale = true; @@ -59,6 +62,7 @@ private sealed class Entry private HashSet _cells = new HashSet(); private HashSet _next = new HashSet(); private HashSet _queried = new HashSet(); + private readonly List _hidden = new List(); private TPin _selected; private bool _pending; private bool _union; @@ -69,6 +73,7 @@ public PinRefreshPlanner(DescribePin describe, QueryRange query, Func _entries.Count; public bool Pending => _pending; // The combined range of every pin except the selected one, which the game outlines itself. @@ -76,19 +81,50 @@ public PinRefreshPlanner(DescribePin describe, QueryRange query, Func pins) + { + foreach (var entry in _entries.Values) entry.Shown = false; + foreach (var pin in pins) + { + if (pin == null) continue; + if (!_entries.TryGetValue(pin, out var entry)) + { + _entries.Add(pin, entry = new Entry()); + _pending = true; + } + entry.Shown = true; + } + _hidden.Clear(); + foreach (var pair in _entries) + if (!pair.Value.Pinned && !pair.Value.Shown) _hidden.Add(pair.Key); + foreach (var pin in _hidden) Drop(pin); + _hidden.Clear(); + } + public void Clear() { _entries.Clear(); @@ -181,6 +217,12 @@ public bool Refresh(List dropped) private bool Has(TPin pin) => pin != null && _entries.ContainsKey(pin); + private void Drop(TPin pin) + { + _entries.Remove(pin); + _pending = _union = true; + } + private static bool Hits(CellBox box, TBounds bounds, Func intersects) => !box.IsEmpty && (box.IsUnbounded || intersects(box, bounds)); } diff --git a/source/PlantingRanges.cs b/source/PlantingRanges.cs new file mode 100644 index 0000000..80aa082 --- /dev/null +++ b/source/PlantingRanges.cs @@ -0,0 +1,13 @@ +using System; + +namespace PersistentWorkAreas +{ + // Which buildings' working areas the planting tool shows. Unity-free so the checks can run it on the game's blueprints. + internal static class PlantingRanges + { + // The game pairs a plantable with the planter buildings of its resource group (PlanterBuilding.GetAllowedPlantables): + // crops with farmhouses, aquatic crops with aquatic farmhouses, trees and bushes with foresters. + public static bool Shows(string plantableGroup, string planterGroup) => + !string.IsNullOrEmpty(plantableGroup) && string.Equals(plantableGroup, planterGroup, StringComparison.Ordinal); + } +} diff --git a/source/WorkAreaService.cs b/source/WorkAreaService.cs index 01930ed..dfbdde7 100644 --- a/source/WorkAreaService.cs +++ b/source/WorkAreaService.cs @@ -14,10 +14,14 @@ using Timberborn.LevelVisibilitySystem; using Timberborn.MapStateSystem; using Timberborn.Navigation; +using Timberborn.Planting; +using Timberborn.PlantingUI; using Timberborn.SceneLoading; using Timberborn.SelectionSystem; using Timberborn.SingletonSystem; +using Timberborn.ToolSystem; using Timberborn.UILayoutSystem; +using Timberborn.WorkSystem; using UnityEngine; using UnityEngine.UIElements; @@ -31,6 +35,7 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto private readonly PinSet _pins = new PinSet(); private readonly PinRefreshPlanner _planner; private readonly List _removed = new List(); + private readonly List _planters = new List(); private readonly float _reach; private readonly INavigationRangeService _navigation; private readonly ConstructionModeService _construction; @@ -39,6 +44,7 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto private readonly ILevelVisibilityService _visibility; private readonly MapSize _mapSize; private readonly ISpecService _specs; + private readonly EntityComponentRegistry _registry; private readonly EventBus _events; private readonly LoadingScreen _loading; private readonly UILayout _layout; @@ -48,18 +54,21 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto private bool _active; private float _nextRefresh; private bool _rendererFailed; + // The resource group of the plant whose planting tool is open, or null. + private string _planting; + private bool _plantersChanged; public event Action Changed; public int Count => _pins.Count; public bool Available => _active && !_rendererFailed; public WorkAreaService(INavigationRangeService navigation, NavigationDistance distance, ConstructionModeService construction, IBlockService blocks, PreviewBlockService previews, ILevelVisibilityService visibility, - MapSize mapSize, ISpecService specs, EventBus events, LoadingScreen loading, + MapSize mapSize, ISpecService specs, EntityComponentRegistry registry, EventBus events, LoadingScreen loading, UILayout layout, InputService input) { _navigation = navigation; _construction = construction; _blocks = blocks; _previews = previews; _visibility = visibility; _mapSize = mapSize; _specs = specs; - _events = events; _loading = loading; _layout = layout; _input = input; + _registry = registry; _events = events; _loading = loading; _layout = layout; _input = input; // BuildingTerrainRange's own margin for deciding whether a navigation change can alter a range. _reach = distance.ResourceBuildings + 2f; _planner = new PinRefreshPlanner( @@ -100,15 +109,18 @@ public void SetPinned(BaseComponent entity, bool value) { if (value) _planner.Add(pin); else _planner.Remove(pin); _nextRefresh = 0; - if (_pins.Count == 0) ReleaseOutline(); + if (_planner.Count == 0) ReleaseOutline(); Notify(); } } + // Clears the player's pins. An open planting tool keeps showing its buildings. public void ClearAll() { + foreach (var pin in _pins.Items) _planner.Remove(pin); _pins.Clear(); - ReleaseOutline(); + _nextRefresh = 0; + if (_planner.Count == 0) ReleaseOutline(); Notify(); } @@ -121,9 +133,11 @@ public bool ProcessInput() public void UpdateSingleton() { - if (!Available || Count == 0) return; + if (!Available) return; try { + if (_plantersChanged) ShowPlanters(); + if (_planner.Count == 0) return; if (_planner.Pending && Time.unscaledTime >= _nextRefresh) { RefreshCells(); @@ -136,23 +150,42 @@ public void UpdateSingleton() // Fail only this cosmetic feature if a later game update changes an internal API. _rendererFailed = true; Debug.LogError("[PersistentWorkAreas] Outline disabled for this map: " + error); - ClearAll(); + Reset(); } } + // The planting tool shows the working areas of the buildings that plant its crop or tree, finished or not. + private void ShowPlanters() + { + _plantersChanged = false; + _planters.Clear(); + if (_planting != null) + foreach (var workplace in _registry.GetAll()) + { + var planter = workplace.GetComponent(); + if (planter != null && PlantingRanges.Shows(_planting, planter.PlantableResourceGroup) && Supports(workplace)) + _planters.Add(workplace.GetComponent()); + } + _planner.Show(_planters); + _planters.Clear(); + _nextRefresh = 0; + if (_planner.Count == 0) ReleaseOutline(); + } + private void RefreshCells() { _removed.Clear(); bool redraw = _planner.Refresh(_removed); - foreach (var entity in _removed) _pins.Set(entity, false); - if (_removed.Count > 0) Notify(); + bool unpinned = false; + foreach (var entity in _removed) unpinned |= _pins.Set(entity, false); + if (unpinned) Notify(); var cells = _planner.Cells; if ((redraw || _outline == null) && cells.Count > 0) { if (_outline == null) _outline = new NativeOutline(_blocks, _previews, _visibility, _mapSize, _specs); _outline.Update(cells); } - if (Count == 0) ReleaseOutline(); + if (_planner.Count == 0) ReleaseOutline(); } private bool Describe(EntityComponent entity, out (Vector3? Center, bool Preview, bool Terrain) key, out CellBox reach) @@ -208,15 +241,37 @@ [OnEvent] public void OnUnselected(SelectableObjectUnselectedEvent e) } [OnEvent] public void OnDeleted(EntityDeletedEvent e) { + // The game has already taken a deleted building out of the entity registry, so the next scan drops it. + if (_planting != null && e.Entity.GetComponent() != null) _plantersChanged = true; var pin = e.Entity.GetComponent(); if (_pins.Set(pin, false)) { _planner.Remove(pin); _nextRefresh = 0; - if (Count == 0) ReleaseOutline(); + if (_planner.Count == 0) ReleaseOutline(); Notify(); } } + // A planter loaded, or placed by another co-op player, while the planting tool is open. + [OnEvent] public void OnInitialized(EntityInitializedEvent e) + { + if (_planting != null && e.Entity.GetComponent() != null) _plantersChanged = true; + } + // ToolService.SwitchTool exits the old tool and enters the new one in the same call, so the buildings are found + // on the next update: switching between crops of the same planters keeps their cached ranges. + [OnEvent] public void OnToolEntered(ToolEnteredEvent e) + { + if (e.Tool is PlantingTool tool) Plant(tool.PlantableSpec?.ResourceGroup); + } + [OnEvent] public void OnToolExited(ToolExitedEvent e) + { + if (e.Tool is PlantingTool) Plant(null); + } + private void Plant(string group) + { + _planting = group; + _plantersChanged = true; + } private void Notify() { @@ -235,6 +290,15 @@ private void ReleaseOutline() catch (Exception error) { Debug.LogError("[PersistentWorkAreas] Renderer cleanup failed: " + error); } _planner.Clear(); } + // Forgets the pins and the planting tool's buildings, and releases the renderer. + private void Reset() + { + _planting = null; + _plantersChanged = false; + _pins.Clear(); + ReleaseOutline(); + Notify(); + } private void OnLoading(object sender, EventArgs e) => Dispose(); public void Dispose() { @@ -243,7 +307,7 @@ public void Dispose() _loading.LoadingScreenEnabled -= OnLoading; _input.RemoveInputProcessor(this); _events.Unregister(this); - ClearAll(); + Reset(); _planner.Select(null); _clearButton?.RemoveFromHierarchy(); _clearButton = null; diff --git a/tests/Checks.csproj b/tests/Checks.csproj index b82c3f7..835233a 100644 --- a/tests/Checks.csproj +++ b/tests/Checks.csproj @@ -1,4 +1,4 @@ net8.0Exeenable - + diff --git a/tests/Program.cs b/tests/Program.cs index 3f58877..e0f5463 100644 --- a/tests/Program.cs +++ b/tests/Program.cs @@ -1,3 +1,4 @@ +using System.IO.Compression; using System.Reflection; using System.Runtime.Loader; using System.Runtime.CompilerServices; @@ -104,6 +105,46 @@ void QueryFakeRange(FakePin pin, (int X, int Y, int Z, bool Preview) key, HashSe planner.Clear(); NavigationChange(CellBox.Point(0, 0, 5)); Check(planner.Count == 0 && planner.Cells.Count == 0 && !planner.Pending, "Clearing forgets every pin and cached range"); +// The planting tool shows the ranges of the buildings that plant the selected crop or tree, alongside the pins. +Check(PlantingRanges.Shows("Farmhouse", "Farmhouse") && PlantingRanges.Shows("Forester", "Forester") && PlantingRanges.Shows("AquaticFarmhouse", "AquaticFarmhouse"), + "The planting tool shows the planter buildings of the plant's resource group"); +Check(!PlantingRanges.Shows("Farmhouse", "Forester") && !PlantingRanges.Shows("Forester", "Farmhouse") && !PlantingRanges.Shows("AquaticFarmhouse", "Farmhouse"), + "Crops never show foresters, trees never show farmhouses, and aquatic crops show only aquatic farmhouses"); +Check(!PlantingRanges.Shows("Farmhouse", null) && !PlantingRanges.Shows(null, null) && !PlantingRanges.Shows("", ""), + "Buildings that plant nothing, and plants without a group, show nothing"); +Check(!PlantingRanges.Shows("farmhouse", "Farmhouse"), "Groups match exactly, as the game compares them"); +var farmA = new FakePin(0, 0, 5); var farmB = new FakePin(100, 0, 5); var grove = new FakePin(0, 100, 5); var kept = new FakePin(200, 0, 5); +planner.Add(kept); Pass(); +planner.Show(new[] { farmA, farmB }); +Check(Pass() == (2, 1) && planner.Cells.Count == 3 * 13 && planner.Cells.Contains((100, 0, 5)) && planner.Cells.Contains((200, 0, 5)), + "Opening the planting tool for a crop: 1 query per farmhouse and 1 rebuild, drawn with the pins"); +planner.Show(new[] { farmB, farmA }); +Check(!planner.Pending && Pass() == (0, 0), "Switching to another crop for the same farmhouses reuses their ranges: 0 queries and 0 rebuilds"); +NavigationChange(CellBox.Point(15, 0, 5)); +Check(Pass() == (1, 0), "A navigation change near one shown farmhouse re-queries only that farmhouse"); +planner.Select(farmB); +Check(Pass() == (0, 1) && !planner.Cells.Contains((100, 0, 5)), "A shown building that is selected is left to the game's own outline"); +planner.Select(null); Pass(); +planner.InvalidateAll(); +Check(Pass() == (3, 1), "Construction-mode toggle re-queries pins and shown buildings alike"); +planner.Show(new[] { grove }); +Check(Pass() == (1, 1) && planner.Count == 2 && planner.Cells.Contains((0, 100, 5)) && !planner.Cells.Contains((0, 0, 5)), + "Switching to a tree: the forester is queried and the farmhouses are dropped with their ranges"); +planner.Show(Array.Empty()); +Check(Pass() == (0, 1) && planner.Count == 1 && planner.Cells.Count == 13 && planner.Cells.Contains((200, 0, 5)), + "Closing the planting tool: 0 queries and 1 rebuild back to the pinned outline"); +planner.Show(new FakePin[] { null }); +Check(!planner.Pending && Pass() == (0, 0) && planner.Count == 1, "Closing it again does no work"); +planner.Show(new[] { kept, farmA }); +Check(Pass() == (1, 1), "A pinned building the tool also shows keeps its cached range: only the other farmhouse is queried"); +Check(planner.Remove(kept) && !planner.Remove(kept) && Pass() == (0, 0) && planner.Cells.Contains((200, 0, 5)), + "Unpinning a building the tool shows keeps its range drawn while the tool is open"); +Check(planner.Add(farmA) && !planner.Add(farmA) && Pass() == (0, 0), "Pinning a building the tool shows reuses its range"); +planner.Show(Array.Empty()); +Check(Pass() == (0, 1) && planner.Count == 1 && planner.Cells.Contains((0, 0, 5)) && !planner.Cells.Contains((200, 0, 5)), + "Closing the tool keeps the ranges that are pinned and drops the rest"); +planner.Clear(); + var game = Path.GetFullPath(args[0]); var modPath = Path.GetFullPath(args[1]); var managed = Path.Combine(game, "Timberborn_Data", "Managed"); @@ -199,6 +240,68 @@ object Update(int x, int y, int z) => navMeshUpdate.Invoke(navMeshUpdate.GetPara Set(livePlanner, "_selected", livePin); Check(Handle("OnUnselected", null) == (true, false, false, true) && Get(livePlanner, "_selected") == null, "Deselecting a pinned building rebuilds the pinned outline from the cache"); + +// Planting tool events, with the game's own tool types. The handlers only record the plant's group; the next update finds the buildings. +var plantableSpec = GameType("Timberborn.Planting", "Timberborn.Planting.PlantableSpec"); +var plantingTool = GameType("Timberborn.PlantingUI", "Timberborn.PlantingUI.PlantingTool"); +object Planting(string group) +{ + var spec = RuntimeHelpers.GetUninitializedObject(plantableSpec); + Set(spec, "k__BackingField", group); + var tool = RuntimeHelpers.GetUninitializedObject(plantingTool); + Set(tool, "k__BackingField", spec); + return tool; +} +var cancelPlanting = RuntimeHelpers.GetUninitializedObject(GameType("Timberborn.PlantingUI", "Timberborn.PlantingUI.CancelPlantingTool")); +var toolEntered = GameType("Timberborn.ToolSystem", "Timberborn.ToolSystem.ToolEnteredEvent"); +var toolExited = GameType("Timberborn.ToolSystem", "Timberborn.ToolSystem.ToolExitedEvent"); +// What a tool switch leaves behind: the plant group shown, and whether the next update scans for its buildings. +// ToolService.SwitchTool posts the old tool's exit and then the new tool's entry within one call. +(string Group, bool Scan) Switch(object from, object to) +{ + Set(live, "_plantersChanged", false); + if (from != null) service.GetMethod("OnToolExited")!.Invoke(live, new[] { Activator.CreateInstance(toolExited, from) }); + service.GetMethod("OnToolEntered")!.Invoke(live, new[] { Activator.CreateInstance(toolEntered, to, false) }); + return (Get(live, "_planting"), Get(live, "_plantersChanged")); +} +var crops = Planting("Farmhouse"); var trees = Planting("Forester"); +Check(Switch(null, crops) == ("Farmhouse", true), "Opening a crop's planting tool shows the farmhouses from the next update"); +Check(Switch(crops, trees) == ("Forester", true), "Switching from a crop to a tree shows the foresters instead"); +Check(Switch(trees, cancelPlanting) == (null, true), "Leaving the planting tools, even for the cancel-planting tool beside them, hides the planters"); +Check(Switch(null, cancelPlanting) == (null, false), "Other tools show no planter ranges and cause no scan"); +Check(GameType("Timberborn.WorkSystem", "Timberborn.WorkSystem.Workplace").GetInterfaces().Any(x => x.FullName == "Timberborn.EntitySystem.IRegisteredComponent"), + "Workplaces are registered components, so the entity registry lists every planter building"); + +// The planting tool's rule on the game's own blueprints: crops show farmhouses, trees and bushes show foresters. +var plantables = new List<(string Name, string Group, bool Crop, bool Tree)>(); +var planters = new List<(string Name, string Group, bool FarmHouse, bool Forester, bool Outlined)>(); +using (var blueprints = ZipFile.OpenRead(Path.Combine(game, "Timberborn_Data", "StreamingAssets", "Modding", "Blueprints.zip"))) + foreach (var entry in blueprints.Entries.Where(x => x.FullName.EndsWith(".blueprint.json", StringComparison.OrdinalIgnoreCase))) + { + using var stream = entry.Open(); + using var blueprint = JsonDocument.Parse(stream, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }); + var root = blueprint.RootElement; + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("TemplateSpec", out var template)) continue; + var name = template.GetProperty("TemplateName").GetString()!; + bool Has(string spec) => root.TryGetProperty(spec, out _); + if (root.TryGetProperty("PlantableSpec", out var plantable)) + plantables.Add((name, plantable.GetProperty("ResourceGroup").GetString()!, Has("CropSpec"), Has("TreeComponentSpec") || Has("BushSpec"))); + if (root.TryGetProperty("PlanterBuildingSpec", out var planter)) + planters.Add((name, planter.GetProperty("PlantableResourceGroup").GetString()!, Has("FarmHouseSpec"), Has("ForesterSpec"), + Has("WorkplaceSpec") && Has("BuildingAccessibleSpec"))); + } +string[] ShownFor(string plant) => planters.Where(p => PlantingRanges.Shows(plantables.Single(x => x.Name == plant).Group, p.Group)) + .Select(p => p.Name).OrderBy(x => x, StringComparer.Ordinal).ToArray(); +Check(planters.Count >= 4 && planters.All(p => p.Outlined), + "Every planter building is a workplace with an access point, so the planting tool finds and outlines it"); +Check(plantables.Count >= 20 && plantables.All(x => x.Crop != x.Tree && ShownFor(x.Name).Length > 0), "Every plantable in the game shows at least one planter building"); +Check(plantables.All(x => ShownFor(x.Name).All(n => x.Crop ? planters.Single(p => p.Name == n).FarmHouse : planters.Single(p => p.Name == n).Forester)), + "Crops show only farmhouses; trees and bushes show only foresters"); +Check(ShownFor("Carrot").SequenceEqual(new[] { "EfficientFarmHouse.Folktails", "FarmHouse.IronTeeth" }) && + ShownFor("Cattail").SequenceEqual(new[] { "AquaticFarmhouse.Folktails" }) && + ShownFor("Pine").SequenceEqual(new[] { "Forester.Folktails", "Forester.IronTeeth" }) && + ShownFor("BlueberryBush").SequenceEqual(new[] { "Forester.Folktails", "Forester.IronTeeth" }), + "Carrots show both factions' farmhouses, cattails only the aquatic farmhouse, pines and blueberries only foresters"); var interfaces = service.GetInterfaces().Select(x => x.FullName).ToArray(); Check(interfaces.Contains("Timberborn.SingletonSystem.IPostLoadableSingleton"), "Game post-load lifecycle"); Check(interfaces.Contains("Timberborn.SingletonSystem.IUpdatableSingleton"), "Display refresh lifecycle"); @@ -208,7 +311,7 @@ object Update(int x, int y, int z) => navMeshUpdate.Invoke(navMeshUpdate.GetPara Check(mod.GetTypes().All(t => !t.GetCustomAttributesData().Any(a => a.AttributeType.Name.StartsWith("HarmonyPatch"))), "No method patches"); var fragment = mod.GetType("PersistentWorkAreas.WorkAreaFragment", true)!; Check(fragment.GetInterfaces().Any(x => x.FullName == "Timberborn.EntityPanelSystem.IEntityPanelFragment"), "Building checkbox fragment contract"); -foreach (var method in new[] { "OnVisibleLevel", "OnConstruction", "OnSelected", "OnUnselected", "OnDeleted" }) +foreach (var method in new[] { "OnVisibleLevel", "OnConstruction", "OnSelected", "OnUnselected", "OnDeleted", "OnInitialized", "OnToolEntered", "OnToolExited" }) Check(service.GetMethod(method)!.GetCustomAttributesData().Any(x => x.AttributeType.Name == "OnEventAttribute"), method + " event subscription"); var packaging = Path.GetFullPath(args[2]); From 7ec9ee2ddd62d23fd34d10b42d1948d85438b66f Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 22 Sep 2026 08:03:46 -0700 Subject: [PATCH 2/2] PWA4: check Clear and the tool scan on the service, fix playtest steps Review found that no check exercised the service's own wiring of the planting tool: deleting `_planner.Show(_planters)` from ShowPlanters, or reverting ClearAll to wipe everything, still passed all 95 checks. Two offline checks on the service instance the checks already build: - ClearAll with one pinned entity and one the tool shows leaves only the shown one drawn and no pins. - ShowPlanters (the scan UpdateSingleton starts with) after leaving the tool, with no pins, empties the planner and clears the scan flag. UpdateSingleton itself reads Time.unscaledTime and cannot run outside the game; the registry scan, the create/delete rescans and the release on the last unpin remain in-game checks. Both checks fail on those two mutations and pass on the fix (97 checks). VALIDATION.md: - Playtest step 2 now leaves the planting tool before checking the pinned forester, since a tree tool outlines every forester by itself. - The Automated checks bullet goes back to its 1.0.0 wording. That section records the 1.0.0 release (it still says 38 checks) and is refreshed at release time together with the check count. Co-Authored-By: Claude Opus 5 --- VALIDATION.md | 4 ++-- tests/Program.cs | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/VALIDATION.md b/VALIDATION.md index 92a5340..39ff593 100644 --- a/VALIDATION.md +++ b/VALIDATION.md @@ -13,7 +13,7 @@ - Compared the display path with the installed game's `BuildingRangeDrawer`, `BoundsNavRangeDrawer`, and navigation query calls. The mod uses those same range queries and its own outline-renderer instance. - Reviewed the BeaverBuddies Stability Fork's `IO/BuildCompatibility.cs`: its handshake identifies Timberborn and the BeaverBuddies/TimberNet binaries. This mod changes none of them. - The display service only implements frame-update, input, load, and navigation-notification interfaces. Pin state is per game-scoped service instance. There are no Harmony patches, replay events, simulation ticks, random calls, or save writes. -- Renderer geometry refreshes on pin, planting-tool, selection, construction-mode, height-visibility and navigation changes, with navigation refreshes capped at five per second. With no pins and no crop or tree planting tool open, the mod does no range queries or drawing. The planting tool's farmhouses or foresters are found when the tool opens, from the game's workplace registry, and share the pins' cached ranges. All pins share a combined mesh. Clearing releases the renderer's owned meshes and cloned materials. +- Renderer geometry refreshes on pin, selection, construction-mode, height-visibility and navigation changes, with navigation refreshes capped at five per second. Empty pin sets do no range queries or drawing. All pins share a combined mesh. Clearing releases the renderer's owned meshes and cloned materials. ## Not established by the automated checks @@ -24,7 +24,7 @@ These are compiled API and logic checks, not Unity rendering tests or a co-op se Re-run this for each release and after each Timberborn update. 1. With the BeaverBuddies Stability Fork enabled, load a colony, select a farm and enable its checkbox. Deselect, paint crops and leave the planting tool: the working-area outline should remain. -2. Pin a forester and paint trees. Pin a second nearby building; verify overlapping areas merge and separate areas both remain visible. +2. Pin a forester, paint trees and leave the planting tool: the forester's outline should remain. Pin a second nearby building; verify overlapping areas merge and separate areas both remain visible. 3. Select an unrelated building, then clear all from the top-right button. No pinned outlines should remain after deselecting. Reselect formerly pinned buildings and verify their checkboxes are off. 4. Assign the clear command in key bindings and verify it clears the pins while a planting tool is active; the buildings that tool shows stay until you leave it. Do not assign a shortcut already used by a tool. 5. Modify a path or terrain, switch visible levels and construction mode, and verify the outline updates. Pause the simulation and repeat selection/clear. diff --git a/tests/Program.cs b/tests/Program.cs index e0f5463..93debd0 100644 --- a/tests/Program.cs +++ b/tests/Program.cs @@ -272,6 +272,27 @@ object Planting(string group) Check(GameType("Timberborn.WorkSystem", "Timberborn.WorkSystem.Workplace").GetInterfaces().Any(x => x.FullName == "Timberborn.EntitySystem.IRegisteredComponent"), "Workplaces are registered components, so the entity registry lists every planter building"); +// The service's Clear and scan with the planting tool's buildings, on the same instance: one building only the tool shows, one only pinned. +var entityComponent = GameType("Timberborn.EntitySystem", "Timberborn.EntitySystem.EntityComponent"); +var shownOnly = RuntimeHelpers.GetUninitializedObject(entityComponent); +var pinnedOnly = RuntimeHelpers.GetUninitializedObject(entityComponent); +var liveEntries = Get(livePlanner, "_entries"); +var livePins = Get(live, "_pins"); +livePlanner.GetType().GetMethod("Clear")!.Invoke(livePlanner, null); +var shownSet = Array.CreateInstance(entityComponent, 1); +shownSet.SetValue(shownOnly, 0); +livePlanner.GetType().GetMethod("Show")!.Invoke(livePlanner, new object[] { shownSet }); +livePlanner.GetType().GetMethod("Add")!.Invoke(livePlanner, new[] { pinnedOnly }); +livePins.GetType().GetMethod("Set")!.Invoke(livePins, new object[] { pinnedOnly, true }); +service.GetMethod("ClearAll")!.Invoke(live, null); +Check(liveEntries.Count == 1 && liveEntries.Contains(shownOnly) && (int)service.GetProperty("Count")!.GetValue(live)! == 0, + "Clear pinned areas removes the pins and keeps drawing the planting tool's buildings"); +// UpdateSingleton reads Time.unscaledTime, which only runs in the game, so the scan it starts with is invoked directly. +Set(live, "_planting", null!); +Set(live, "_plantersChanged", true); +service.GetMethod("ShowPlanters", fields)!.Invoke(live, null); +Check(liveEntries.Count == 0 && !Get(live, "_plantersChanged"), "Leaving the planting tool with no pins drops its buildings at the next update"); + // The planting tool's rule on the game's own blueprints: crops show farmhouses, trees and bushes show foresters. var plantables = new List<(string Name, string Group, bool Crop, bool Tree)>(); var planters = new List<(string Name, string Group, bool FarmHouse, bool Forester, bool Outlined)>();