Skip to content

Modding Guide

Guy Friley edited this page Nov 6, 2026 · 3 revisions

Modding Guide

Build notes from Beaver Bridge, a mod that exposes the running game over local HTTP so an external agent can read and control a colony. Written against game version 1.1.2.4, Unity 6000.5.5f1, Mono, on the macOS Steam build. The original source was lost; a 0.9.0 rebuild now lives in mods/BeaverBridge/src/ in the repo, compiles against 1.1.2.7, and awaits its first in-game run. Build and install with mods/BeaverBridge/install.sh. See Roadmap.

Why build one

The purpose-built mod for this, Timberbot API, is broken on 1.1.x. Its HTTP listener answers /ping but every endpoint touching the simulation times out. That failure signature, listener alive but game data dead, is what a mod looks like when its game-side bindings never attach after a version bump. Building a fresh one turned out to be a smaller job than patching it.

Toolchain

Mod layout:  ~/Documents/Timberborn/Mods/<Name>/
                 manifest.json   { Name, Version, Id, MinimumGameVersion, Description }
                 Code.dll
  • Target netstandard2.1, assembly name Code.
  • Reference the game's own DLLs from Timberborn.app/Contents/Resources/Data/Managed with <Private>false</Private> so they are not copied into the output.
  • Build offline: a nuget.config with <packageSources><clear /></packageSources> lets dotnet build restore with no network.
  • No Steam, no Workshop. Dropping the folder into Mods/ is the whole install.
  • Mods bind at process start. There is no hot reload. Every code change costs a full quit and relaunch, so batch fixes aggressively.

Reading the API without documentation

The wiki is thin. The assemblies are not. A roughly 120-line System.Reflection.Metadata dumper, which needs no NuGet because it ships in the .NET runtime, lists every public type, base type, interface and member signature in any assembly. Set it to include protected members to find things like Configurator.Configure().

This is the single highest-leverage tool in the project. It turns "what does the API look like in this version" from guesswork into a grep. The repo now ships it as tools/apidump: dotnet run --project tools/apidump -- --out DIR <Managed folder> writes one greppable text file per assembly in under a second, and tools/sync-gamerefs.sh keeps a local copy of the assemblies current with the installed game.

Architecture

The one non-obvious constraint: game state may only be touched on Unity's main thread. A socket listener runs on a background thread, so it cannot read the simulation directly.

TcpListener (background thread)
      |  enqueue Job + ManualResetEventSlim
      v
ConcurrentQueue<Job>
      v
IUpdatableSingleton.UpdateSingleton()   <- main thread, once per FRAME
      |  execute, fill Job.Result, signal
      v
socket thread wakes, writes HTTP response

Use IUpdatableSingleton, not a tick hook. UpdateSingleton fires every rendered frame, so the bridge answers even while the game is paused. A simulation-tick hook would starve whenever the player pauses, which is a plausible explanation for Timberbot's permanent 2-second timeouts.

/ping is answered directly from the socket thread and reports pumpRunning, a flag the main-thread pump sets. That one boolean distinguishes "mod not loaded" from "mod loaded but not bound" without guessing from timeouts.

Registration

[Context("Game")]                       // "MainMenu" | "Game" | "MapEditor" | "Bootstrapper"
public class BridgeConfigurator : Configurator {
  protected override void Configure() {
    Bind<BridgeServer>().AsSingleton();
  }
}

Lifecycle interfaces the container honours: ILoadableSingleton.Load(), IUpdatableSingleton.UpdateSingleton(), ILateUpdatableSingleton, IPostLoadableSingleton, IUnloadableSingleton.

Why TcpListener and not HttpListener

System.Net.HttpListener is not in netstandard2.1. Rather than fight BCL profiles with NuGet unavailable, the bridge speaks minimal HTTP/1.1 over a raw TcpListener in about 60 lines. It also hand-rolls JSON read and write, avoiding a dependency on the game's bundled Newtonsoft.

Gotchas that only show up at runtime

  • GetComponent<T>() throws on multiples. District centers carry several IPrioritizable components. Use a helper that calls GetComponentsAllocating<T>() and returns the first match, everywhere, or you will hit InvalidOperationException on entities you never anticipated.
  • A registry you create at Load() is empty forever. EntityComponentRegistry is populated by registration events, so one created after the save has loaded never sees existing entities. Enumerate through DistrictCenter.DistrictBuildingRegistry.GetEnabledBuildings<T>() instead, which also tags every building with its district. T must be IRegisteredComponent: Building, Dwelling and Workplace qualify; Inventory and BlockObject do not, so reach those off a Building.
  • Workplace.DesiredWorkers has no setter. Use IncreaseDesiredWorkers() and DecreaseDesiredWorkers() in a guarded loop.
  • SpeedManager.CurrentSpeed reads stale in the same frame. It applies on LateUpdate. Echo the requested value, not a read-back.
  • Compiling proves signatures, not correctness. Every one of the above compiled clean and failed at runtime. Budget for iteration.
  • Verify deployments by checksum, not by the copy tool's success response. A file transfer reported success twice while silently leaving the old DLL in place, costing a wasted restart. Read the file back and compare hashes.
  • The game only persists on save. Everything the bridge does lives in memory. Quitting without saving discards all of it; a fully staffed district was lost this way. /save calls GameSaver.QueueSaveSkippingNameValidation with a SaveReference(name, SettlementReferenceService.SettlementReference).

Endpoints

GET Returns
/ping version, pumpRunning. Liveness without touching game state
/state cycle, day, weather, speed, districts with population
/districts district list with population
/housing homes, beds, adult and child slots, occupancy, free beds per district
/buildings?filter= inventories with template, district, coords, stock, reachability
/workplaces desired versus assigned workers, priority, district, understaffed flag
/prefabs every template with real footprint Size, entrance offset, flippable
/unreachable finished buildings the game reports as having no valid access
POST Body
/speed {speed}. 0 pauses; 3 is the UI max but higher values work
/place {prefab,x,y,z,orientation}. Creates a construction site
/demolish {x,y,z}. Instant delete, no refund, no undo
/priority {x,y,z,priority}. VeryLow to VeryHigh
/workers {x,y,z,desired}
/migrate {from,to,adults,children,bots} by district name
/camera {x,y,z,zoom}. Moves the player's view
/save {name}

Placement chain

name -> TemplateCollectionService.AllTemplates
     -> Blueprint carrying a TemplateSpec whose IsNamed(name) matches
     -> new EntitySetup.Builder(blueprint)
     -> ConstructionFactory.CreateAsUnfinished(builder, new Placement(coord, orientation, FlipMode.Unflipped))

This produces a real construction site that beavers build with real materials, not a spawned freebie. Invalid placements throw cleanly and create nothing, so brute-forcing candidate tiles is safe and costs nothing. The game is a reliable placement oracle; trust it over your own occupancy model.

API check against 1.1.2.7

The build notes above are from 1.1.2.4. On 2026-11-05 the installed game was 1.1.2.7, and 628 of its 658 managed assemblies differ from the 1.1.2.4 copies, including every one the mod touches. A static inspection of the current assemblies found every type and member the mod relied on still present under the same names, with two things to handle: GameSaver.QueueSaveSkippingNameValidation now takes a second argument, and the EntitySetup builder's nested type name needs confirming at compile time. SingletonSystem.EventBus with [OnEvent] handlers is available and would replace polling. The full table, including the save-format keys confirmed from string literals, is in docs/modding-notes.md in the repo.

Known wrong in the last build

  • Auto-orientation is broken. It keeps the first attempt as a fallback, which occupies the tile, so rotations 90, 180 and 270 fail with InvalidOperationException. It must delete each attempt before trying the next.
  • Accessible.ValidAccessible appears to be false on unfinished buildings, making the placement-time reachability check a false negative. Verify against /unreachable after construction finishes instead.

Clone this wiki locally