Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ No extra dependency is required. Keep your existing BeaverBuddies Stability Fork
- 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.

The currently selected building still uses its normal game outline. Clearing pins restores normal selection behavior; deselecting that building then hides its normal outline. Pins reset on map exit, loading, and multiplayer resynchronization. They are not saved. Deleting a pinned building removes its pin.
The currently selected building still uses its normal game outline. Clearing pins restores normal selection behavior; deselecting that building then hides its normal outline. Pins are remembered for each settlement on your own computer, in `PersistentWorkAreas\Pins.txt` next to your Timberborn `Saves` folder (on Windows, `Documents\Timberborn\PersistentWorkAreas\Pins.txt`), and come back when you load any save of that settlement, as the latest pins you set there. A different settlement starts with none. They are never written into the save, so co-op players each keep their own. A co-op guest's game names the settlement after the host's save, which changes with every resynchronization, so a guest's pins usually do not come back. The file keeps the 100 settlements you loaded or changed most recently. To forget every pin, delete that file. Deleting a pinned building removes its pin.

The mod supports navigation-based working areas. It does not pin district road coloring, every kind of effect-radius overlay, or building-placement ghosts. UI text is currently English. The panel, button and key-binding text is all in `version-1.1/Localizations/enUS_PersistentWorkAreas.csv` (in the repository, under `packaging/PersistentWorkAreas/`), so a translation is one more file in that folder with the same keys, named for the game's language code (for example `deDE_PersistentWorkAreas.csv`). Keep `{0}` in the clear-button text: it becomes the pin count.

## Compatibility and validation

Designed for compatibility with the **BeaverBuddies Stability Fork**. The mod does not patch game methods, change simulation or building data, send multiplayer events, or modify saves. It uses the same navigation queries as the game's selected-building visualizer and a separate instance of its outline renderer.
Designed for compatibility with the **BeaverBuddies Stability Fork**. The mod does not patch game methods, change simulation or building data, send multiplayer events, or modify saves; the pins live in their own small local file. It uses the same navigation queries as the game's selected-building visualizer and a separate instance of its outline renderer.

The release build passes 38 automated lifecycle/API checks. The mod has been tested in game on Timberborn 1.1.2.4, both single-player and in a two-player BeaverBuddies Stability Fork session with the mod installed on both computers. See `VALIDATION.md` for what was checked and how.

Expand Down
6 changes: 4 additions & 2 deletions VALIDATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
- 38 checks passed: reference-identity pins, duplicate pin/unpin, independent pins, replacement/deletion behavior, global clear, new-map isolation, native renderer constructors/methods/cleanup fields, delegate binding to internal renderer methods, lifecycle/navigation/event interfaces, no simulation persistence interfaces, no Harmony/BeaverBuddies dependencies, package/key-binding consistency, manifest/assembly version agreement, and presence of the Builder's Hut marker component used to exclude it from pinning.
- 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.
- The display service only implements frame-update, input, load, and navigation-notification interfaces. Pin state is per game-scoped service instance. Each settlement's pins are also kept, by entity id, in a local text file next to the `Saves` folder (`Documents\Timberborn\PersistentWorkAreas\Pins.txt` on Windows). It is read once after the map loads, and rewritten from the frame update after the pins change, and once after a load that finds the settlement below the top of the file, to keep it among the 100 most recent. A failed write is retried every 10 seconds and again on leaving the map, which never erases the file. A file this version cannot read is kept as `Pins.txt.bak` before it is replaced. 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.

## Not established by the automated checks
Expand All @@ -28,9 +28,11 @@ Re-run this for each release and after each Timberborn update.
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.
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.
6. Delete a pinned building. Its outline and pin count should disappear. Load a different settlement: it should start with no pins.
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.
9. Pin two buildings, save, exit to the main menu and load that save: both outlines should come back and the button should read **Clear pinned areas (2)**. Unpin one, save, exit and load again: only the other should come back. Load an older save of the same settlement: the remembered buildings that exist in it should be pinned, with no error in the log. In co-op, pin different buildings on each computer and perform a resync: the host's pins should come back and the guest's should be empty.
10. While still in the map, pin a building: within a second its settlement's line in `Documents\Timberborn\PersistentWorkAreas\Pins.txt` should list one more id. Press **Clear pinned areas**: the line should disappear. Pin a building that is already in your latest save, exit to the desktop without saving, relaunch and load that save: the pin should come back. Load an older save that lacks one of the pinned buildings, then load the newest save again: every pin should come back. `Pins.txt.tmp` should never be left behind.

## References

Expand Down
7 changes: 6 additions & 1 deletion source/PinSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,21 @@ private sealed class IdentityComparer : IEqualityComparer<T>
private readonly HashSet<T> _items = new HashSet<T>(Identity);
public int Count => _items.Count;
public IEnumerable<T> Items => _items;
// Set by every pin, unpin or clear that changes the set, so the pin file is written only after a change.
public bool Changed { get; set; }
public bool Contains(T item) => item != null && _items.Contains(item);
public bool Set(T item, bool pinned)
{
if (item == null) return false;
return pinned ? _items.Add(item) : _items.Remove(item);
bool changed = pinned ? _items.Add(item) : _items.Remove(item);
Changed |= changed;
return changed;
}
public bool Clear()
{
if (_items.Count == 0) return false;
_items.Clear();
Changed = true;
return true;
}
}
Expand Down
158 changes: 158 additions & 0 deletions source/PinStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace PersistentWorkAreas
{
// Each settlement's pins, remembered in a local text file and never in the save, so co-op players keep their own
// and a resync or join never carries them. A building is identified by its entity id, which the save keeps, so a pin
// finds the same building after a load. Unity-free so the checks can run it.
internal static class PinStore
{
// A later format should keep this header and add only fields that this version skips (anything that is not an
// entity id), so that going back to an older build still reads it. This version does not read a file with any
// other header, and PinFile keeps a copy of such a file before replacing it.
public const string Header = "Persistent Work Areas pins v1";
// Only the most recently loaded or changed settlements are kept. A co-op guest's settlement is named after the
// host's map, which changes on every join or resync, so the file would otherwise grow with every session.
public const int MaxSettlements = 100;

// The entity ids remembered for a settlement. A missing, corrupt or unrecognized file remembers none.
public static List<Guid> Read(string text, string settlement)
{
foreach (var entry in Parse(text))
if (entry.Settlement == settlement) return entry.Pins;
return new List<Guid>();
}

// The file text with the settlement's pins replaced and listed first. A settlement without pins is removed.
public static string Write(string text, string settlement, IEnumerable<Guid> pins)
{
if (string.IsNullOrEmpty(settlement)) throw new ArgumentException("A settlement name is required.", nameof(settlement));
var entries = Parse(text);
entries.RemoveAll(entry => entry.Settlement == settlement);
var ids = pins.Where(id => id != Guid.Empty).Select(id => id.ToString("D")).Distinct()
.OrderBy(id => id, StringComparer.Ordinal).ToList();
var output = new StringBuilder(Header).Append('\n');
if (ids.Count > 0) output.Append(Escape(settlement)).Append('\t').Append(string.Join("\t", ids)).Append('\n');
foreach (var entry in entries.Take(ids.Count > 0 ? MaxSettlements - 1 : MaxSettlements))
{
output.Append(Escape(entry.Settlement));
foreach (var id in entry.Pins) output.Append('\t').Append(id.ToString("D"));
output.Append('\n');
}
return output.ToString();
}

// The file text with the settlement's entry moved first and its pins unchanged, so that loading a settlement keeps
// it among the most recent. Null when there is nothing to move: it has no entry, or its entry is already first.
public static string Touch(string text, string settlement)
{
var entries = Parse(text);
int index = entries.FindIndex(entry => entry.Settlement == settlement);
return index > 0 ? Write(text, settlement, entries[index].Pins) : null;
}

// Whether this version can read the file: there is none yet, or it starts with this version's header.
public static bool Recognizes(string text) => string.IsNullOrEmpty(text) || text.Split('\n')[0].TrimEnd('\r') == Header;

// The buildings to pin again: every remembered id that still names a building which can be pinned, once each.
public static List<T> Restore<T>(IEnumerable<Guid> ids, Func<Guid, T> resolve, Func<T, bool> supports) where T : class
{
var restored = new List<T>();
var seen = new HashSet<T>(PinSet<T>.Identity);
foreach (var id in ids)
{
var pin = resolve(id);
if (pin != null && supports(pin) && seen.Add(pin)) restored.Add(pin);
}
return restored;
}

// One line per settlement: its escaped name, then its pinned entity ids, separated by tabs.
// Damaged lines and ids are skipped; the first line for a name wins.
private static List<(string Settlement, List<Guid> Pins)> Parse(string text)
{
var entries = new List<(string Settlement, List<Guid> Pins)>();
if (string.IsNullOrEmpty(text)) return entries;
var lines = text.Split('\n');
if (!Recognizes(text)) return entries;
for (int i = 1; i < lines.Length; i++)
{
var fields = lines[i].TrimEnd('\r').Split('\t');
if (!Unescape(fields[0], out var settlement) || settlement.Length == 0 || entries.Any(entry => entry.Settlement == settlement)) continue;
var pins = new List<Guid>();
for (int j = 1; j < fields.Length; j++)
if (Guid.TryParseExact(fields[j], "D", out var id) && id != Guid.Empty && !pins.Contains(id)) pins.Add(id);
if (pins.Count > 0) entries.Add((settlement, pins));
}
return entries;
}

private static string Escape(string name) =>
name.Replace("\\", "\\\\").Replace("\t", "\\t").Replace("\n", "\\n").Replace("\r", "\\r");

private static bool Unescape(string field, out string name)
{
name = null;
var result = new StringBuilder(field.Length);
for (int i = 0; i < field.Length; i++)
{
char c = field[i];
if (c != '\\') { result.Append(c); continue; }
if (++i == field.Length) return false;
switch (field[i])
{
case '\\': result.Append('\\'); break;
case 't': result.Append('\t'); break;
case 'n': result.Append('\n'); break;
case 'r': result.Append('\r'); break;
default: return false;
}
}
name = result.ToString();
return true;
}
}

// The pin file on disk. Every call reads or rewrites the whole file, which stays small.
internal sealed class PinFile
{
public PinFile(string filePath) { FilePath = filePath; }
public string FilePath { get; }

public List<Guid> Load(string settlement) => PinStore.Read(ReadText(), settlement);

public void Save(string settlement, IEnumerable<Guid> pins)
{
var existing = ReadText();
Replace(existing, PinStore.Write(existing, settlement, pins));
}

// Moves the settlement's entry first, so that loading the settlement counts as using it. Writes nothing when
// there is nothing to move.
public void Touch(string settlement)
{
var existing = ReadText();
var text = PinStore.Touch(existing, settlement);
if (text != null) Replace(existing, text);
}

private string ReadText() => File.Exists(FilePath) ? File.ReadAllText(FilePath) : null;

private void Replace(string existing, string text)
{
var folder = Path.GetDirectoryName(FilePath);
if (!string.IsNullOrEmpty(folder)) Directory.CreateDirectory(folder);
// A file this version cannot read, such as one from a newer version, is kept beside it instead of being lost.
if (!PinStore.Recognizes(existing)) File.Copy(FilePath, FilePath + ".bak", true);
// Written beside the file and swapped in, so an interrupted write never leaves half a file.
var temporary = FilePath + ".tmp";
File.WriteAllText(temporary, text);
if (File.Exists(FilePath)) File.Replace(temporary, FilePath, null);
else File.Move(temporary, FilePath);
}
}
}
Loading
Loading