Skip to main content

Game API

This section is a reference for the game's own code: Root.Township.dll and the Alta.* assemblies next to it in A Township Tale_Data\Managed. It covers game build main-1.7.2.1.42203, assembly version 0.0.39.2.

The game was never meant to be modded. There's no API, no events for mods and no promise that anything stays the same. You reach it through MelonLoader, which loads your DLL, and Harmony, which lets you run your code before, after or instead of the game's methods. These pages tell you what exists, what it does, which side runs it and how to hook it safely.

Everything here comes from reading the decompiled game, the patches in working mods and the notes from Rover's testing. Some pages also use the game's asset data (prefab and scene object names, components and field values), only as names and values. Where a page infers something rather than reading it in the code, it says so.

note

None of this is TavernLib. TavernLib's own API (roles, events, services) is in its own section, the TavernLib API. When TavernLib changes how a game method behaves, the page for that method says so.

Two builds, one of them everywhere​

Alta shipped two builds of Root.Township.dll with the same assembly version:

These pages describe the server build. att-stubs is made from it too. If you decompile the game yourself, check which one you have (see Finding your way around).

So every class is loaded on both sides, and a mod's DLL loads on both sides too. Most code only does anything on one of them.

How to tell where you are:

CheckTrue whenWatch out
CommandLineArguments.Contains(CommandLineArguments.StartServerArgument)The process was started as a dedicated server ("/start_server").The most reliable check, and the one TavernLib, Steady and Rover use. CommandLineArguments is in Alta.CommandLine.
ApplicationManager.IsHeadless-batchmode or -nographics is on the command line.Also true for a headless client, like a Rover bot. Several game behaviours switch on this, not on being a server.
NetworkSceneManager.IsServerThis process hosts the current scene.Also true on a client sitting in the main menu: the menu runs a small local scene (LocalNetworkScene) that sets it. It goes false when the client joins a server.
ServerHandler.CurrentNot null while a server runs.On a client in the main menu it's a dummy local server (IsDummyLocalServer is true).

See Client, server or both for the guide version, and Harmony in A Township Tale for checks inside patches.

How the game fits together​

Entities and prefabs​

Almost everything in the world that can move, be picked up or be saved is a NetworkEntity (Alta.Networking). Each has a uint Identifier, unique on that server, and a Hash that names the prefab it came from. Prefabs are NetworkPrefabs, found by hash through PrefabManager. One spawned prefab is usually several entities: a root (PrefabRoot) and its embedded children, such as a player body's hands and head. See World, entities and spawning.

Things are spawned by the server (SpawnManager, SpawnHelper), which calls InitializeAsServer(SpawnData) on the entity and its behaviours and then tells the clients that can see it. A client only builds the copies it's sent.

Chunks​

The world is cut into chunks (Alta.Chunks.Chunk, with LocationChunk for the places in the handcrafted world). Every entity belongs to a chunk, and each chunk saves its own entities. The server keeps chunks loaded around each player, spawns their contents for that player, and saves and unloads them when nobody is near. Chunk 0 is the global chunk for things that belong nowhere in particular. The procedural forest and the caves stream in their own chunks as players reach them (ForestChunk, CaveLayerStreamer).

Who decides​

The server holds the saves, spawns and destroys everything, runs creatures, stats, crafting and damage, and sends the results to clients. Clients send input and their own body. Two things to know:

  • A client owns its own body. Rover's tests found the server takes the position a client sends without checking speed, ground or teleports. Anti-cheat is only what mods like TavernLib add.
  • Many network handlers check who sent a message, through StreamAuthorityHelper, and log the rest as unauthorized. When you send your own messages, check the sender yourself.

Only the server has a navmesh (AstarPath) and pathfinding. Clients have none.

Messages​

Clients and the server talk over kcp2k (UDP). Each message starts with a MessageType (Alta.Networking, 23 values in the game). The game writes that type in 5 bits, so it can't go past 31. TavernLib widens it to 8 bits on both ends, so a client and server only understand each other when both have TavernLib. See Networking and players.

Threads​

The game's code runs on Unity's main thread: Update, coroutines, spawning, and network message handlers (received in the "Networking Receiving" update module). Pathfinding runs on its own worker threads. Async methods resume on the main thread when they were started there. If your patch starts work on another thread, hand Unity calls back with MainThreadDispatcher.Run (see Threads, coroutines and the timeline).

What TavernLib already patches​

On a modded server, TavernLib has already changed a lot of the game's behaviour. The main ones:

  • Joining: it puts its own filter in front of the game's join check (fly-camera players, TavernLib account tokens, mod parity, whitelist and blacklist), then hands over to the game's check, whose allow step it also replaces (token user id, player limit, roles). See Joining a server.
  • Message types: 8 bits instead of 5 (above).
  • Player limit from server_settings.json (max_players), enforced at join, and the server's web and console ports from tavern_server.json.
  • Alta's dead web services: cosmetics presets are kept in local files, every cosmetic is owned by everyone, and the internet check always answers yes.
  • The console: its own token logins, refusing commands given an empty player list, and fixes for several built-in commands that answered Success having done nothing.
  • Garbage collection: the server's forced collection interval is read from server_settings.json.

Every patch, with the method it hooks, is in Known patch points.

The assemblies​

AssemblyWhat it's for
Root.TownshipThe game itself: about 5,600 source files when decompiled. Almost everything in this section.
Alta.Analytics.RuntimeAnalytics events and the service that sends them. Alta's servers are gone, so mods drop them.
Alta.Api.ClientThe client for Alta's web API (accounts, servers, groups, friends, cosmetics). The servers are gone, so its calls time out.
Alta.Api.DataTransferModelsThe data types that API used: server info, user info, JWT helpers (JWTUtility). The game still passes these around.
Alta.ArrayPools.RuntimePools of reusable arrays.
Alta.AttributesInspector attributes (ButtonAttribute, CommentAttribute and so on). Nothing a mod needs.
Alta.AuthenticationLogin helpers, PlayerSubscriberStatus and UserPermissions.
Alta.BuildBuild-time baking interfaces.
Alta.CommandLineCommandLineArguments: reading the game's command line, and the StartServerArgument constant.
Alta.Core.RuntimeOne small helper, AverageNumber.
Alta.CoroutinesAltaCoroutine, a coroutine that catches exceptions, and RateLimiter.
Alta.EventBus.RuntimeA small event bus.
Alta.Global.RuntimeGlobalSettings, settings assets loaded at start.
Alta.IOAltaFile and AltaFolder: the game's file access, including safe saves through temp files.
Alta.LifecycleManagement.RuntimeDisposable helpers.
Alta.LifetimeScopesVContainer scopes for the app, the game and the player.
Alta.MenuItemEditor menu items.
Alta.NetworkTransport.RuntimeThe transport under the game's networking: kcp2k wrappers, the receive pool, transport errors.
Alta.Platform, Alta.Platform.GenericPlatform services, and the PlayerMode and PlatformTarget enums.
Alta.PlatformInformation.RuntimeWhich platform the game thinks it's on.
Alta.Profiling.RuntimeProfiler markers.
Alta.SearchableToolsOne editor interface.
Alta.Serialization.RuntimeBit-level Stream, StreamReader, StreamWriter, BitReader, BitWriter: how messages and saves are written.
Alta.SingletonsSingletonBehaviour, the base of the game's singletons.
Alta.Timing.RuntimeTimeline and priority queues, for things scheduled in game time.
Alta.ValuesGeneralValue and hashed values, and HashHelper.
Alta.VContainerLayer.RuntimeFactories on top of VContainer.
Alta.XRManagement, Alta.XRManagement.WindowsPicking and starting VR: XRUtility, TownshipXRMode. Rover patches these to run without a headset.

There are also smaller Township.* assemblies next to them, such as Township.Core.Runtime, which holds MainThreadDispatcher. Console, utilities and Alta assemblies goes through each assembly in more depth.

Third-party code inside Root.Township​

Root.Township has several libraries compiled into it. They're out of scope here, but you'll meet them:

NamespaceLibraryWhere the game uses it
Pathfinding, AstarPath, SeekerA* Pathfinding Project, apparently changed by AltaCreature navigation, server only. Steady and ATT-Optimizations patch it heavily.
RootMotionFinalIKPlayer bodies and hands.
SteamworksSteamworks.NETSteam login and overlay.
AK, Ak*WwiseSound. Some sound calls throw on a headless client.
I2I2 LocalizationText in the menus.
TriangleNetTriangle.NETMeshing.
FlyingWormConsole3Console ProEditor logging.
DiscordDiscord Game SDKRich presence.
QuickLod, AmplifyImpostorsLOD and impostor toolsRendering at distance.
AgonesAgones SDKAlta's hosted servers.

kcp2k (from Mirror), VContainer, NLog and Newtonsoft.Json are separate DLLs in Managed, not inside Root.Township.

The section​

AreaWhat's in it
Patching the gameHarmony in this game, every known patch point in our mods and others, and how to find your way around the decompiled code.
Networking and playersConnections, messages, joining, the server's handler and lifecycle, Player and its controller.
World, entities and spawningNetworkEntity, prefabs, chunks, loading and saving, spawning, finding and moving things, the forest and the caves.
Items, interaction and damageHands, pickups, docks and bags, durability, impacts, health and damage.
Game systemsStats, hunger, crafting, smelting, cooking, liquids, progression and the rest.
Creatures and AIAgents, decisions, senses, combat, movement, spawning.
Console, utilities and Alta assembliesConsole commands, the remote console, logging, update modules, threads, start-up, settings and files.