From 7a1c32bb3258e58a36c395b99ee014eb50c2062d Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 22 Sep 2026 01:49:01 -0700 Subject: [PATCH 1/2] PWA1: re-query only the pins a navigation change can reach Every navigation update, selection change, pin change and visibility change marked the whole pin set dirty, so the next refresh re-ran a range query for every pin and rebuilt the combined outline mesh. The game's range service reuses a single flow field, so with two or more pins each of those queries was a full refill. Selection changes were not throttled. Add PinRefreshPlanner, a Unity-free planner linked into tests/Checks.csproj. Each pin keeps its cached cells, the key its query depends on (access point, live or preview graph, terrain or road spill) and a bounding box of access +/- (NavigationDistance.ResourceBuildings + 2), the same box BuildingTerrainRange uses to skip navigation updates (22 cells in 1.1.2.4). - A navigation update re-queries only pins whose box meets NavMeshUpdate.Bounds. Road-spill ranges follow the district road network, so they have no bound and are always re-queried. - Every pass re-reads each pin's key and re-queries pins whose access or graph changed, which catches a finished construction site cheaply. - The outline is rebuilt only when the combined cells change, or when an update meets the cached cells (blocking objects and previews there change the drawn outline even when the cells do not). - Selecting or deselecting a pinned building rebuilds the outline from the cache with no queries. Selecting an unpinned building does nothing. A selected pin's query waits until it is deselected. - Construction-mode toggles still re-query every pin; visible-level changes only redraw, because range queries do not depend on the visible level. All queries still run in UpdateSingleton at most five times per second. The navigation listeners only mark the mod's own per-pin records. No tick, save or persistence interfaces are added. Display only. Checks: 23 new, 61 total. The planner checks count queries and rebuilds in a fake navigation world, and a game check drives the service's real BoundingBox test with an asymmetric box. Co-Authored-By: Claude Opus 5 --- source/PinRefreshPlanner.cs | 187 ++++++++++++++++++++++++++++++++++++ source/PinSet.cs | 3 +- source/WorkAreaService.cs | 122 +++++++++++++---------- tests/Checks.csproj | 2 +- tests/Program.cs | 102 ++++++++++++++++++++ 5 files changed, 362 insertions(+), 54 deletions(-) create mode 100644 source/PinRefreshPlanner.cs diff --git a/source/PinRefreshPlanner.cs b/source/PinRefreshPlanner.cs new file mode 100644 index 0000000..00dbf3b --- /dev/null +++ b/source/PinRefreshPlanner.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; + +namespace PersistentWorkAreas +{ + // Inclusive grid bounds (x, y, z with z up), the same shape as the game's BoundingBox. + internal readonly struct CellBox + { + public static readonly CellBox Empty = new CellBox(0, 0, 0, -1, -1, -1); + public static readonly CellBox Unbounded = new CellBox(int.MinValue, int.MinValue, int.MinValue, int.MaxValue, int.MaxValue, int.MaxValue); + public readonly int MinX, MinY, MinZ, MaxX, MaxY, MaxZ; + + public CellBox(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) + { + MinX = minX; MinY = minY; MinZ = minZ; MaxX = maxX; MaxY = maxY; MaxZ = maxZ; + } + + public static CellBox Point(int x, int y, int z) => new CellBox(x, y, z, x, y, z); + // BuildingTerrainRange.UpdateBoundingBox builds its box the same way: floor(access - reach) to ceil(access + reach). + public static CellBox Around(float x, float y, float z, float reach) => new CellBox( + (int)Math.Floor(x - reach), (int)Math.Floor(y - reach), (int)Math.Floor(z - reach), + (int)Math.Ceiling(x + reach), (int)Math.Ceiling(y + reach), (int)Math.Ceiling(z + reach)); + public bool IsEmpty => MinX > MaxX || MinY > MaxY || MinZ > MaxZ; + public bool IsUnbounded => MinX == int.MinValue && MinY == int.MinValue && MinZ == int.MinValue && + MaxX == int.MaxValue && MaxY == int.MaxValue && MaxZ == int.MaxValue; + public bool Intersects(CellBox other) => !IsEmpty && !other.IsEmpty && + MinX <= other.MaxX && MaxX >= other.MinX && MinY <= other.MaxY && MaxY >= other.MinY && MinZ <= other.MaxZ && MaxZ >= other.MinZ; + public CellBox Union(CellBox other) => IsEmpty ? other : other.IsEmpty ? this : new CellBox( + Math.Min(MinX, other.MinX), Math.Min(MinY, other.MinY), Math.Min(MinZ, other.MinZ), + Math.Max(MaxX, other.MaxX), Math.Max(MaxY, other.MaxY), Math.Max(MaxZ, other.MaxZ)); + } + + // 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. + 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 + // besides the navigation mesh; reach bounds the navigation changes that can alter the range. + public delegate bool DescribePin(TPin pin, out TKey key, out CellBox reach); + public delegate void QueryRange(TPin pin, TKey key, HashSet cells); + + private sealed class Entry + { + public bool Described; + public TKey Key; + public bool Stale = true; + public CellBox Reach = CellBox.Empty; + // Bounds of the cached cells. Blocking objects and previews placed there change the outline. + public CellBox Extent = CellBox.Empty; + public HashSet Cells = new HashSet(); + } + + private readonly Dictionary _entries = new Dictionary(PinSet.Identity); + private readonly EqualityComparer _keys = EqualityComparer.Default; + private readonly DescribePin _describe; + private readonly QueryRange _query; + private readonly Func _cellBox; + private HashSet _cells = new HashSet(); + private HashSet _next = new HashSet(); + private HashSet _queried = new HashSet(); + private TPin _selected; + private bool _pending; + private bool _union; + private bool _redraw; + + public PinRefreshPlanner(DescribePin describe, QueryRange query, Func cellBox) + { + _describe = describe; _query = query; _cellBox = cellBox; + } + + public int Count => _entries.Count; + public bool Pending => _pending; + // The combined range of every pin except the selected one, which the game outlines itself. + public IReadOnlyCollection Cells => _cells; + + public bool Add(TPin pin) + { + if (pin == null || _entries.ContainsKey(pin)) return false; + _entries.Add(pin, new Entry()); + _pending = true; + return true; + } + + public bool Remove(TPin pin) + { + if (pin == null || !_entries.Remove(pin)) return false; + _pending = _union = true; + return true; + } + + public void Clear() + { + _entries.Clear(); + _cells.Clear(); _next.Clear(); _queried.Clear(); + _pending = _union = _redraw = false; + } + + public void Select(TPin pin) + { + bool pinned = Has(_selected) || Has(pin); + _selected = pin; + if (pinned) _pending = _union = true; + } + + // Construction mode switches finished buildings between the live and preview navigation graphs. + public void InvalidateAll() + { + if (_entries.Count == 0) return; + foreach (var entry in _entries.Values) entry.Stale = true; + _pending = _redraw = true; + } + + // The visible level changes what is drawn, never which cells are in range. + public void Redraw() + { + if (_entries.Count == 0) return; + _pending = _redraw = true; + } + + // A navigation change with the given bounds. Only pins it can reach are re-queried. + public void Touch(TBounds bounds, Func intersects) + { + if (_entries.Count == 0) return; + // Also re-describe every pin on the next pass, which catches access and graph changes cheaply. + _pending = true; + foreach (var pair in _entries) + { + var entry = pair.Value; + if (!entry.Stale && Hits(entry.Reach, bounds, intersects)) entry.Stale = true; + if (!_redraw && !ReferenceEquals(pair.Key, _selected) && Hits(entry.Extent, bounds, intersects)) _redraw = true; + } + } + + // Adds pins that can no longer be shown to dropped and forgets them. + // Returns true when the outline must be rebuilt from Cells. + public bool Refresh(List dropped) + { + _pending = false; + bool union = _union; + _union = false; + int first = dropped.Count; + foreach (var pair in _entries) + { + var pin = pair.Key; + var entry = pair.Value; + if (!_describe(pin, out var key, out var reach)) { dropped.Add(pin); continue; } + if (!entry.Described || !_keys.Equals(entry.Key, key)) + { + entry.Described = true; + entry.Key = key; + entry.Stale = true; + } + // The selected pin is not drawn, so its query waits until it is deselected. + if (entry.Stale && !ReferenceEquals(pin, _selected)) + { + entry.Stale = false; + _queried.Clear(); + _query(pin, key, _queried); + if (!entry.Cells.SetEquals(_queried)) + { + var cached = entry.Cells; entry.Cells = _queried; _queried = cached; + entry.Extent = CellBox.Empty; + foreach (var cell in entry.Cells) entry.Extent = entry.Extent.Union(_cellBox(cell)); + union = true; + } + } + entry.Reach = reach.Union(entry.Extent); + } + for (int i = first; i < dropped.Count; i++) union |= _entries.Remove(dropped[i]); + bool redraw = _redraw; + _redraw = false; + if (!union) return redraw; + _next.Clear(); + foreach (var pair in _entries) + if (!ReferenceEquals(pair.Key, _selected)) _next.UnionWith(pair.Value.Cells); + if (_next.SetEquals(_cells)) return redraw; + var drawn = _cells; _cells = _next; _next = drawn; + return true; + } + + private bool Has(TPin pin) => pin != null && _entries.ContainsKey(pin); + + private static bool Hits(CellBox box, TBounds bounds, Func intersects) => + !box.IsEmpty && (box.IsUnbounded || intersects(box, bounds)); + } +} diff --git a/source/PinSet.cs b/source/PinSet.cs index fa13f5b..9ddc4f3 100644 --- a/source/PinSet.cs +++ b/source/PinSet.cs @@ -11,7 +11,8 @@ private sealed class IdentityComparer : IEqualityComparer public bool Equals(T x, T y) => ReferenceEquals(x, y); public int GetHashCode(T value) => RuntimeHelpers.GetHashCode(value); } - private readonly HashSet _items = new HashSet(new IdentityComparer()); + internal static readonly IEqualityComparer Identity = new IdentityComparer(); + private readonly HashSet _items = new HashSet(Identity); public int Count => _items.Count; public IEnumerable Items => _items; public bool Contains(T item) => item != null && _items.Contains(item); diff --git a/source/WorkAreaService.cs b/source/WorkAreaService.cs index 9af453f..01930ed 100644 --- a/source/WorkAreaService.cs +++ b/source/WorkAreaService.cs @@ -8,6 +8,7 @@ using Timberborn.Buildings; using Timberborn.Common; using Timberborn.ConstructionMode; +using Timberborn.Coordinates; using Timberborn.EntitySystem; using Timberborn.InputSystem; using Timberborn.LevelVisibilitySystem; @@ -26,10 +27,11 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto IInputProcessor, ISingletonInstantNavMeshListener, ISingletonPreviewNavMeshListener, IDisposable { public const string ClearKey = "PersistentWorkAreas.Clear"; + private static readonly Func Touches = (box, bounds) => ToBoundingBox(box).Intersects(in bounds); private readonly PinSet _pins = new PinSet(); - private readonly HashSet _cells = new HashSet(); - private readonly HashSet _nextCells = new HashSet(); + private readonly PinRefreshPlanner _planner; private readonly List _removed = new List(); + private readonly float _reach; private readonly INavigationRangeService _navigation; private readonly ConstructionModeService _construction; private readonly IBlockService _blocks; @@ -43,17 +45,14 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto private readonly InputService _input; private NativeOutline _outline; private Button _clearButton; - private EntityComponent _selected; private bool _active; - private bool _dirty; - private bool _geometryDirty; private float _nextRefresh; private bool _rendererFailed; public event Action Changed; public int Count => _pins.Count; public bool Available => _active && !_rendererFailed; - public WorkAreaService(INavigationRangeService navigation, ConstructionModeService construction, + public WorkAreaService(INavigationRangeService navigation, NavigationDistance distance, ConstructionModeService construction, IBlockService blocks, PreviewBlockService previews, ILevelVisibilityService visibility, MapSize mapSize, ISpecService specs, EventBus events, LoadingScreen loading, UILayout layout, InputService input) @@ -61,6 +60,10 @@ public WorkAreaService(INavigationRangeService navigation, ConstructionModeServi _navigation = navigation; _construction = construction; _blocks = blocks; _previews = previews; _visibility = visibility; _mapSize = mapSize; _specs = specs; _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( + Describe, Query, cell => CellBox.Point(cell.x, cell.y, cell.z)); } public void PostLoad() @@ -92,9 +95,10 @@ public static bool Supports(BaseComponent component) public void SetPinned(BaseComponent entity, bool value) { if (!Available || !entity || (value && !Supports(entity))) return; - if (_pins.Set(entity.GetComponent(), value)) + var pin = entity.GetComponent(); + if (_pins.Set(pin, value)) { - Invalidate(); + if (value) _planner.Add(pin); else _planner.Remove(pin); _nextRefresh = 0; if (_pins.Count == 0) ReleaseOutline(); Notify(); @@ -120,12 +124,12 @@ public void UpdateSingleton() if (!Available || Count == 0) return; try { - if (_dirty && Time.unscaledTime >= _nextRefresh) + if (_planner.Pending && Time.unscaledTime >= _nextRefresh) { RefreshCells(); _nextRefresh = Time.unscaledTime + .2f; } - if (_cells.Count > 0) _outline?.Draw(); + if (_planner.Cells.Count > 0) _outline?.Draw(); } catch (Exception error) { @@ -138,62 +142,77 @@ public void UpdateSingleton() private void RefreshCells() { - _dirty = false; - _nextCells.Clear(); _removed.Clear(); - foreach (var entity in _pins.Items) - { - if (!Supports(entity)) { _removed.Add(entity); continue; } - // The selected building already has its normal outline. - if (ReferenceEquals(entity, _selected)) continue; - var block = entity.GetComponent(); - var access = entity.GetComponent(); - bool unfinished = !block.IsFinished; - Vector3? center = unfinished ? access.CalculateAccess() : access.Accessible.UnblockedSingleAccessInstant; - if (!center.HasValue) continue; - bool terrain = entity.GetComponent(); - bool preview = unfinished || _construction.InConstructionMode; - IEnumerable range = terrain - ? (preview ? _navigation.GetTerrainPreviewNodesInRange(center.Value) : _navigation.GetTerrainNodesInRange(center.Value)) - : (preview ? _navigation.GetRoadSpillPreviewNodesInRange(center.Value) : _navigation.GetRoadSpillNodesInRange(center.Value)); - _nextCells.UnionWith(range); - } + bool redraw = _planner.Refresh(_removed); foreach (var entity in _removed) _pins.Set(entity, false); if (_removed.Count > 0) Notify(); - if (_geometryDirty || !_cells.SetEquals(_nextCells)) + var cells = _planner.Cells; + if ((redraw || _outline == null) && cells.Count > 0) { - _geometryDirty = false; - _cells.Clear(); - _cells.UnionWith(_nextCells); - if (_cells.Count > 0) - { - if (_outline == null) _outline = new NativeOutline(_blocks, _previews, _visibility, _mapSize, _specs); - _outline.Update(_cells); - } + if (_outline == null) _outline = new NativeOutline(_blocks, _previews, _visibility, _mapSize, _specs); + _outline.Update(cells); } if (Count == 0) ReleaseOutline(); } - private void Invalidate() { _dirty = true; _geometryDirty = true; } - public void OnInstantNavMeshUpdated(NavMeshUpdate update) => Invalidate(); - public void OnPreviewNavMeshUpdated(NavMeshUpdate update) => Invalidate(); - [OnEvent] public void OnVisibleLevel(MaxVisibleLevelChangedEvent e) { Invalidate(); _nextRefresh = 0; } - [OnEvent] public void OnConstruction(ConstructionModeChangedEvent e) { Invalidate(); _nextRefresh = 0; } + private bool Describe(EntityComponent entity, out (Vector3? Center, bool Preview, bool Terrain) key, out CellBox reach) + { + key = default; reach = CellBox.Empty; + if (!Supports(entity)) return false; + var block = entity.GetComponent(); + var access = entity.GetComponent(); + bool unfinished = !block.IsFinished; + Vector3? center = unfinished ? access.CalculateAccess() : access.Accessible.UnblockedSingleAccessInstant; + bool terrain = entity.GetComponent(); + key = (center, unfinished || _construction.InConstructionMode, terrain); + if (!center.HasValue) return true; + // A road-spill range follows its district's whole road network, so any navigation change can alter it. + if (!terrain) { reach = CellBox.Unbounded; return true; } + var grid = CoordinateSystem.WorldToGrid(center.Value); + reach = CellBox.Around(grid.x, grid.y, grid.z, _reach); + return true; + } + + private void Query(EntityComponent entity, (Vector3? Center, bool Preview, bool Terrain) key, HashSet cells) + { + if (!key.Center.HasValue) return; + var center = key.Center.Value; + // The game refills one shared flow field per query, so each result is copied before the next query. + cells.UnionWith(key.Terrain + ? (key.Preview ? _navigation.GetTerrainPreviewNodesInRange(center) : _navigation.GetTerrainNodesInRange(center)) + : (key.Preview ? _navigation.GetRoadSpillPreviewNodesInRange(center) : _navigation.GetRoadSpillNodesInRange(center))); + } + + private static BoundingBox ToBoundingBox(CellBox box) + { + var builder = new BoundingBox.Builder(); + builder.Expand(new Vector3Int(box.MinX, box.MinY, box.MinZ)); + builder.Expand(new Vector3Int(box.MaxX, box.MaxY, box.MaxZ)); + return builder.Build(); + } + + public void OnInstantNavMeshUpdated(NavMeshUpdate update) => _planner.Touch(update.Bounds, Touches); + public void OnPreviewNavMeshUpdated(NavMeshUpdate update) => _planner.Touch(update.Bounds, Touches); + [OnEvent] public void OnVisibleLevel(MaxVisibleLevelChangedEvent e) { _planner.Redraw(); _nextRefresh = 0; } + [OnEvent] public void OnConstruction(ConstructionModeChangedEvent e) { _planner.InvalidateAll(); _nextRefresh = 0; } + // The selected building already has its normal outline, so the pinned outline leaves it out. [OnEvent] public void OnSelected(SelectableObjectSelectedEvent e) { - _selected = e.SelectableObject.GetComponent(); - Invalidate(); _nextRefresh = 0; + _planner.Select(e.SelectableObject.GetComponent()); + _nextRefresh = 0; } [OnEvent] public void OnUnselected(SelectableObjectUnselectedEvent e) { - _selected = null; - Invalidate(); _nextRefresh = 0; + _planner.Select(null); + _nextRefresh = 0; } [OnEvent] public void OnDeleted(EntityDeletedEvent e) { - if (_pins.Set(e.Entity.GetComponent(), false)) + var pin = e.Entity.GetComponent(); + if (_pins.Set(pin, false)) { - Invalidate(); _nextRefresh = 0; + _planner.Remove(pin); + _nextRefresh = 0; if (Count == 0) ReleaseOutline(); Notify(); } @@ -214,8 +233,7 @@ private void ReleaseOutline() _outline = null; try { outline?.Dispose(); } catch (Exception error) { Debug.LogError("[PersistentWorkAreas] Renderer cleanup failed: " + error); } - _cells.Clear(); _nextCells.Clear(); - _dirty = false; _geometryDirty = false; + _planner.Clear(); } private void OnLoading(object sender, EventArgs e) => Dispose(); public void Dispose() @@ -226,7 +244,7 @@ public void Dispose() _input.RemoveInputProcessor(this); _events.Unregister(this); ClearAll(); - _selected = null; + _planner.Select(null); _clearButton?.RemoveFromHierarchy(); _clearButton = null; Changed = null; diff --git a/tests/Checks.csproj b/tests/Checks.csproj index 7f6c633..b82c3f7 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 1355807..86cd70e 100644 --- a/tests/Program.cs +++ b/tests/Program.cs @@ -27,6 +27,83 @@ void Check(bool ok, string name) Check(pins.Set(forester, false) && pins.Count == 0, "Deleting last pinned building empties collection"); Check(new PinSet().Count == 0, "New map begins without pins"); +// Refresh planning, against a fake navigation world that counts range queries and outline rebuilds. +var around = CellBox.Around(10.5f, 20.5f, 3f, 22f); +Check(around.MinX == -12 && around.MaxX == 33 && around.MinY == -2 && around.MaxY == 43 && around.MinZ == -19 && around.MaxZ == 25, + "Pin bounds match BuildingTerrainRange: floor(access - 22) to ceil(access + 22)"); +Check(CellBox.Point(0, 0, 0).Intersects(new CellBox(0, 0, 0, 1, 1, 1)) && !CellBox.Point(0, 0, 0).Intersects(CellBox.Point(1, 0, 0)) && + !CellBox.Empty.Intersects(CellBox.Unbounded), "Cell boxes are inclusive like the game's BoundingBox"); +int queries = 0, rebuilds = 0; +bool DescribeFakePin(FakePin pin, out (int X, int Y, int Z, bool Preview) key, out CellBox reach) +{ + key = (pin.X, pin.Y, pin.Z, pin.Preview); + reach = pin.RoadSpill ? CellBox.Unbounded : CellBox.Around(pin.X, pin.Y, pin.Z, 22f); + return !pin.Gone; +} +void QueryFakeRange(FakePin pin, (int X, int Y, int Z, bool Preview) key, HashSet<(int, int, int)> cells) +{ + queries++; + for (int dx = -pin.Radius; dx <= pin.Radius; dx++) + for (int dy = Math.Abs(dx) - pin.Radius; dy <= pin.Radius - Math.Abs(dx); dy++) + cells.Add((key.X + dx, key.Y + dy, key.Z)); +} +var planner = new PinRefreshPlanner( + DescribeFakePin, QueryFakeRange, cell => CellBox.Point(cell.Item1, cell.Item2, cell.Item3)); +var dropped = new List(); +(int Queries, int Rebuilds) Pass() +{ + int queried = queries, rebuilt = rebuilds; + dropped.Clear(); + if (planner.Pending && planner.Refresh(dropped)) rebuilds++; + return (queries - queried, rebuilds - rebuilt); +} +void NavigationChange(CellBox bounds) => planner.Touch(bounds, (box, changed) => box.Intersects(changed)); +var elsewhere = new CellBox(300, 300, 0, 310, 310, 10); +var pinA = new FakePin(0, 0, 5); var pinB = new FakePin(100, 0, 5); var pinC = new FakePin(0, 100, 5); +planner.Add(pinA); planner.Add(pinB); planner.Add(pinC); +Check(Pass() == (3, 1) && planner.Cells.Count == 3 * 13, "New pins are queried once each and drawn as one outline"); +Check(!planner.Pending && Pass() == (0, 0), "No refresh work until something changes"); +NavigationChange(elsewhere); +Check(Pass() == (0, 0), "Navigation change missing every pin: 0 queries and 0 rebuilds"); +NavigationChange(CellBox.Point(15, 0, 5)); +Check(Pass() == (1, 0), "Navigation change near pin A only: 1 query, and unchanged cells need no rebuild"); +pinA.Radius = 3; NavigationChange(CellBox.Point(3, 0, 5)); +Check(Pass() == (1, 1) && planner.Cells.Contains((3, 0, 5)), "Navigation change that alters pin A's range: 1 query and 1 rebuild"); +NavigationChange(CellBox.Point(1, 0, 5)); +Check(Pass() == (1, 1), "Navigation change inside a drawn range redraws even when its cells are unchanged"); +planner.Select(pinA); +Check(Pass() == (0, 1) && !planner.Cells.Contains((3, 0, 5)) && planner.Cells.Contains((100, 0, 5)), + "Selecting a pinned building: 0 queries and 1 rebuild from the cached ranges"); +planner.Select(null); +Check(Pass() == (0, 1) && planner.Cells.Contains((3, 0, 5)), "Deselecting it restores its cached range without a query"); +planner.Select(new FakePin(0, 0, 5)); +Check(!planner.Pending && Pass() == (0, 0), "Selecting an unpinned building does no refresh work"); +planner.Select(null); +planner.InvalidateAll(); +Check(Pass() == (3, 1), "Construction-mode toggle: N queries for N pins"); +planner.Redraw(); +Check(Pass() == (0, 1), "Visible-level change redraws without queries"); +pinB.Preview = true; NavigationChange(elsewhere); +Check(Pass() == (1, 0), "A pin whose access or graph changed is re-queried even when the navigation change was elsewhere"); +planner.Select(pinA); Pass(); +pinA.Radius = 2; NavigationChange(CellBox.Point(0, 0, 5)); +Check(Pass() == (0, 0), "A selected pin's query waits while the game draws its outline"); +planner.Select(null); +Check(Pass() == (1, 1) && !planner.Cells.Contains((3, 0, 5)), "Deselecting a pin that went stale queries it once"); +var spill = new FakePin(0, 200, 5) { RoadSpill = true }; +planner.Add(spill); Pass(); +NavigationChange(elsewhere); +Check(Pass() == (1, 0), "Road-spill ranges have no bound, so every navigation change re-queries them"); +Check(planner.Remove(spill) && Pass() == (0, 1) && !planner.Cells.Contains((0, 200, 5)), "Unpinning rebuilds from the cache without queries"); +pinC.Gone = true; NavigationChange(elsewhere); +Check(Pass() == (0, 1) && dropped.SequenceEqual(new[] { pinC }) && planner.Count == 2 && !planner.Cells.Contains((0, 100, 5)), + "A pin that can no longer be shown is dropped with its range"); +var twins = new PinRefreshPlanner((EqualBuilding _, out int key, out CellBox reach) => + { key = 0; reach = CellBox.Empty; return true; }, (_, _, _) => { }, _ => CellBox.Empty); +Check(twins.Add(new EqualBuilding()) && twins.Add(new EqualBuilding()) && twins.Count == 2, "Refresh planning keeps equal-valued buildings apart"); +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"); + var game = Path.GetFullPath(args[0]); var modPath = Path.GetFullPath(args[1]); var managed = Path.Combine(game, "Timberborn_Data", "Managed"); @@ -70,9 +147,25 @@ void Method(Type type, string name, Type returns, params Type[] args) var builderHut = GameType("Timberborn.BuilderHubSystem", "Timberborn.BuilderHubSystem.BuilderHubWorkplaceBehavior"); Check(builderHut.IsClass, "Builder's Hut marker component exists (excluded from pinning)"); +var distance = GameType("Timberborn.Navigation", "Timberborn.Navigation.NavigationDistance"); +Check((float)distance.GetProperty("ResourceBuildings")!.GetValue(Activator.CreateInstance(distance))! + 2f == 22f, + "Game range distance plus BuildingTerrainRange's margin is the 22 cells the planner checks use"); var mod = Assembly.LoadFrom(modPath); var service = mod.GetType("PersistentWorkAreas.WorkAreaService", true)!; +var boundingBox = GameType("Timberborn.Common", "Timberborn.Common.BoundingBox"); +object GameBox(int x, int y, int z) +{ + var builderType = boundingBox.GetNestedType("Builder")!; + var builder = Activator.CreateInstance(builderType)!; + builderType.GetMethod("Expand")!.Invoke(builder, new[] { Activator.CreateInstance(vector, x, y, z) }); + return builderType.GetMethod("Build")!.Invoke(builder, null)!; +} +var touches = (Delegate)service.GetField("Touches", BindingFlags.Static | BindingFlags.NonPublic)!.GetValue(null)!; +var pinBox = Activator.CreateInstance(mod.GetType("PersistentWorkAreas.CellBox", true)!, 0, 0, 0, 10, 20, 30); +bool Touched(int x, int y, int z) => (bool)touches.DynamicInvoke(pinBox, GameBox(x, y, z))!; +Check(Touched(0, 0, 0) && Touched(10, 20, 30) && Touched(5, 5, 25) && !Touched(11, 5, 5) && !Touched(5, 25, 5) && !Touched(5, 5, -1), + "Navigation-change test uses the game's BoundingBox with the same axes and inclusive edges"); 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"); @@ -98,3 +191,12 @@ sealed class EqualBuilding public override bool Equals(object obj) => obj is EqualBuilding; public override int GetHashCode() => 1; } + +// Radius stands in for the navigation state: changing it changes the range the next query returns. +sealed class FakePin +{ + public readonly int X, Y, Z; + public int Radius = 2; + public bool Preview, RoadSpill, Gone; + public FakePin(int x, int y, int z) { X = x; Y = y; Z = z; } +} From bb694dd2f246340155805bc8415b8deb187104c8 Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 22 Sep 2026 03:58:07 -0700 Subject: [PATCH 2/2] PWA1: check the service's planner wiring, not a game constant Review found that the planner checks drive PinRefreshPlanner through a fake world, so a regression in WorkAreaService's glue (the reach margin, which planner call each event makes, the preview navigation listener) still passed every check. Build a WorkAreaService outside the game (its constructor only stores its dependencies and reads NavigationDistance), add an entity to its planner, and call each handler through reflection: - the pin reach is ResourceBuildings + 2, read from the game at run time; - a visible-level change redraws without marking the pin for a query; - a construction-mode change marks every pin for a query; - live and preview navigation updates mark the pin only inside its reach and keep the 0.2 s throttle; - deselecting a pinned building rebuilds the outline from the cache. This replaces the check that NavigationDistance.ResourceBuildings + 2 is exactly 22: it pinned a game constant the service already reads at run time, so a game change there would have blocked packaging a working build while a dropped margin in the service would still have passed. The fake-world CellBox check is renamed, since production code tests bounds with the game's BoundingBox. Each new check fails when its handler is mutated (reach 1, no redraw on visible level, redraw instead of invalidate on construction, empty preview listener, no deselect). Checks: 67 (was 61). Co-Authored-By: Claude Opus 5 --- tests/Program.cs | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/tests/Program.cs b/tests/Program.cs index 86cd70e..3f58877 100644 --- a/tests/Program.cs +++ b/tests/Program.cs @@ -32,7 +32,7 @@ void Check(bool ok, string name) Check(around.MinX == -12 && around.MaxX == 33 && around.MinY == -2 && around.MaxY == 43 && around.MinZ == -19 && around.MaxZ == 25, "Pin bounds match BuildingTerrainRange: floor(access - 22) to ceil(access + 22)"); Check(CellBox.Point(0, 0, 0).Intersects(new CellBox(0, 0, 0, 1, 1, 1)) && !CellBox.Point(0, 0, 0).Intersects(CellBox.Point(1, 0, 0)) && - !CellBox.Empty.Intersects(CellBox.Unbounded), "Cell boxes are inclusive like the game's BoundingBox"); + !CellBox.Empty.Intersects(CellBox.Unbounded), "Fake-world cell boxes are inclusive and empty boxes meet nothing"); int queries = 0, rebuilds = 0; bool DescribeFakePin(FakePin pin, out (int X, int Y, int Z, bool Preview) key, out CellBox reach) { @@ -148,8 +148,6 @@ void Method(Type type, string name, Type returns, params Type[] args) var builderHut = GameType("Timberborn.BuilderHubSystem", "Timberborn.BuilderHubSystem.BuilderHubWorkplaceBehavior"); Check(builderHut.IsClass, "Builder's Hut marker component exists (excluded from pinning)"); var distance = GameType("Timberborn.Navigation", "Timberborn.Navigation.NavigationDistance"); -Check((float)distance.GetProperty("ResourceBuildings")!.GetValue(Activator.CreateInstance(distance))! + 2f == 22f, - "Game range distance plus BuildingTerrainRange's margin is the 22 cells the planner checks use"); var mod = Assembly.LoadFrom(modPath); var service = mod.GetType("PersistentWorkAreas.WorkAreaService", true)!; @@ -166,6 +164,41 @@ object GameBox(int x, int y, int z) bool Touched(int x, int y, int z) => (bool)touches.DynamicInvoke(pinBox, GameBox(x, y, z))!; Check(Touched(0, 0, 0) && Touched(10, 20, 30) && Touched(5, 5, 25) && !Touched(11, 5, 5) && !Touched(5, 25, 5) && !Touched(5, 5, -1), "Navigation-change test uses the game's BoundingBox with the same axes and inclusive edges"); + +// Service wiring, on an instance built outside the game: the constructor only stores its dependencies and reads NavigationDistance. +var distanceValue = Activator.CreateInstance(distance)!; +var serviceCtor = service.GetConstructors().Single(); +var live = serviceCtor.Invoke(serviceCtor.GetParameters().Select(p => p.ParameterType == distance ? distanceValue : null).ToArray()); +Check((float)service.GetField("_reach", fields)!.GetValue(live)! == (float)distance.GetProperty("ResourceBuildings")!.GetValue(distanceValue)! + 2f, + "Pin reach is the game's range distance plus BuildingTerrainRange's 2-cell margin"); +T Get(object target, string name) => (T)target.GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)!.GetValue(target)!; +void Set(object target, string name, object value) => target.GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)!.SetValue(target, value); +var livePlanner = Get(live, "_planner"); +var livePin = RuntimeHelpers.GetUninitializedObject(GameType("Timberborn.EntitySystem", "Timberborn.EntitySystem.EntityComponent")); +Check((bool)livePlanner.GetType().GetMethod("Add")!.Invoke(livePlanner, new[] { livePin })!, "Service planner accepts a pinned entity"); +var liveEntry = Get(livePlanner, "_entries")[livePin]!; +Set(liveEntry, "Reach", pinBox); +var navMeshUpdate = GameType("Timberborn.Navigation", "Timberborn.Navigation.NavMeshUpdate").GetConstructors(fields).Single(); +object Update(int x, int y, int z) => navMeshUpdate.Invoke(navMeshUpdate.GetParameters() + .Select((p, i) => i == 0 ? GameBox(x, y, z) : p.ParameterType.IsValueType ? Activator.CreateInstance(p.ParameterType) : null).ToArray()); +// What a handler leaves behind: a pass pending, the outline marked for a redraw, the pin marked for a query, the throttle skipped. +(bool Pending, bool Redraw, bool Query, bool Now) Handle(string handler, object argument) +{ + Set(livePlanner, "_pending", false); Set(livePlanner, "_redraw", false); Set(liveEntry, "Stale", false); Set(live, "_nextRefresh", 99f); + service.GetMethod(handler)!.Invoke(live, new[] { argument }); + return (Get(livePlanner, "_pending"), Get(livePlanner, "_redraw"), Get(liveEntry, "Stale"), Get(live, "_nextRefresh") == 0f); +} +Check(Handle("OnVisibleLevel", null) == (true, true, false, true), "Visible-level event redraws the pinned outline without re-querying"); +Check(Handle("OnConstruction", null) == (true, true, true, true), "Construction-mode event re-queries every pin"); +Check(Handle("OnInstantNavMeshUpdated", Update(5, 5, 25)) == (true, false, true, false) && + Handle("OnPreviewNavMeshUpdated", Update(10, 20, 30)) == (true, false, true, false), + "Live and preview navigation updates inside a pin's reach re-query it at the throttled rate"); +Check(Handle("OnInstantNavMeshUpdated", Update(11, 5, 5)) == (true, false, false, false) && + Handle("OnPreviewNavMeshUpdated", Update(5, 25, 5)) == (true, false, false, false), + "Navigation updates outside a pin's reach keep its cached range"); +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"); 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");