Repository navigation
Writing code mods
Meitou runs ordinary Kenshi mods (.mod data, textures, meshes) unchanged. A code mod adds C# code on top: new simulation systems,
dialogue conditions and effects, save data, interface pieces, debug commands, and Harmony patches on
the game's own code. This page is the practical guide. The engine-side contract and its evidence are in
docs/modding.md.
Code-mod API version: 2 (from nightly v0.16.1-nightly.20261108; earlier builds run API 1 only). API 1 mods still load.
RE_Kenshi plugins and BepInEx are not supported.
-
Make a class library for
net10.0. -
Reference the DLLs from your Meitou install folder, with
Private="false", because the game supplies them at run time:<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net10.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <Reference Include="C:\Games\Meitou\Meitou.Modding.dll" Private="false" /> <Reference Include="C:\Games\Meitou\Meitou.Simulation.dll" Private="false" /> <Reference Include="C:\Games\Meitou\Meitou.Data.dll" Private="false" /> <Reference Include="C:\Games\Meitou\Meitou.Core.dll" Private="false" /> <Reference Include="C:\Games\Meitou\0Harmony.dll" Private="false" /> <!-- Only for interface work: --> <Reference Include="C:\Games\Meitou\Meitou.Ui.dll" Private="false" /> </ItemGroup> </Project>
-
Write the entry type:
using Meitou.Modding; using Meitou.Simulation; namespace MyMod; public sealed class MyMod : IMod { public void Initialize(ModContext c) { c.Log("hello from MyMod"); c.AddSystem("counter", ctx => new CounterSystem(), SystemAnchor.AfterPart(StandardParts.Combat)); } }
-
Put the mod in the Kenshi
modsfolder, next to a.modfile of the same name (it may hold no records):Kenshi/mods/MyMod/ MyMod.mod meitou.json MyMod.dll -
Write
meitou.json:{ "id": "mymod", "version": "1.0.0", "apiVersion": 2, "assemblies": ["MyMod.dll"], "entry": "MyMod.MyMod" } -
Enable the mod in the Meitou launcher and press Play. The launcher asks whether to trust it; say yes. Your log line appears in
log.txtnext to the game.
| Key | Meaning |
|---|---|
id |
Your mod's identity: letters, digits, ., _, -, at most 64 characters. It keys your save data, your Harmony instance and your log lines. Never change it once players have saves. |
version |
Optional. Your mod's SemVer version (1.2.0). Other mods' version ranges check it. |
apiVersion |
The code-mod API you built for: 1 or 2. A number the game doesn't run refuses the mod with a message. |
assemblies |
Your DLL file names in the mod folder, loaded in order. Don't list the game's DLLs. |
entry |
The full name of your IMod class. It needs a public parameterless constructor. |
dependencies |
Optional, API 2. Code mods yours builds on, by their id. See Depending on another mod. |
loadAfter |
Optional, API 2. Ids of code mods that must load before yours when they are enabled. Ordering only. |
incompatible |
Optional, API 2. Code mods yours must not run beside: an id, or { "id": ..., "version": "<3.0.0" }. |
gameVersion |
Optional, API 2. The Meitou versions you built against, e.g. ">=0.16.0 <0.17.0". A nightly counts as its release: 0.16.1-nightly.x is 0.16.1. |
Version ranges are comparators separated by spaces that must all hold: >=, >, <=, <, = (a bare version is =).
Comments and trailing commas are allowed.
- The game loads the enabled mods of the mod list, in order. A disabled mod's DLL is never opened. Nothing reorders the list on its own; the launcher's Arrange button proposes an order that satisfies every dependency and shows the moves before applying them.
- A mod whose dependency is missing, disabled, later in the list, refused, or out of its version range is refused too, with a message.
- Only mods the player trusted in the launcher run their code. Others load as data only, with a message in game and in
log.txt. - Each mod gets its own load context. The game's DLLs and Harmony always come from the game, even if your folder has copies. Any other library you ship loads from your folder, so two mods can use different versions of it.
-
Initializeruns once, after the game data is loaded and before any world exists, on a background thread. - If
Initializethrows, your mod is left out: everything it registered is dropped and its Harmony patches are removed. The game goes on.
Registration only works inside Initialize.
c.AddSystem("counter", ctx => new CounterSystem(), SystemAnchor.AfterPart(StandardParts.Combat));- Your factory runs for every world: each new game and each loaded save builds its systems from scratch.
-
SystemAnchor.Before(part),SystemAnchor.AfterPart(part)orSystemAnchor.Enddecide where your system runs in the tick. If the part isn't built (some test scenes have no aggro), your system goes at the end. -
ctx.Find<T>()gives you a standard system, for examplectx.Find<Meitou.Simulation.Combat.CombatSystem>(). - A system implements only the phases it needs from
ITickSystem(Inputs,Schedule,Think,Move,BeforeAct,Act,Apply,SlowWorld). See the rules before writing a parallel phase. - Implement
IStateHashedso your state counts in the world's state hash, which the determinism check reads.
Make your system implement IModSaveData:
public sealed class CounterSystem : ITickSystem, IStateHashed, IModSaveData
{
int count;
public void SlowWorld(World world) => count++;
public void Hash(ref StateHasher h) => h.Add(count);
public void Write(Stream s) => new BinaryWriter(s).Write(count);
public void Read(Stream s) => count = new BinaryReader(s).ReadInt32();
}Your data goes into meitou-mods/<your id>.dat inside the save folder. Kenshi's own save files stay untouched. Read is only called
when the save has data for that system; otherwise it starts as your factory made it. A save loaded without your mod keeps your file and
writes it again. Importing a save starts mods fresh.
Codes start at 1000; lower numbers are the game's. Use the numbers in your FCS dialogue data as the condition name or
action name of a DIALOG_ACTION.
c.AddDialogueCondition(1000, check => check.Matches(IsRaining(check.World)));
c.AddDialogueCondition(1001, check => check.Compare(CountDogs(check.World, check.Subject)));
c.AddDialogueEffect(1000, act => act.World.Post("Something happened"));-
Matches(bool)andCompare(double)apply the condition's value andcompare bythe way vanilla conditions do. - Conditions must only read: they also run for previews.
- Effects run in a serial step as the line is said.
- Two mods can't take the same code: the second one is refused.
c.AddRecordType(5000, "MY_THING");
foreach (var record in c.Records(5000)) { /* ... */ }This claims the number so no other mod uses it. Whether such records survive the data merge and saves is not tested yet.
c.AddUi(extension) takes an IUiExtension (from Meitou.Ui): your own styles, controls and actions, overrides of vanilla ones, and
contributions to HUD slots (UiSlots).
c.AddDebugCommand("Spawn dogs", d =>
{
d.Enqueue(new MySpawnDogs(d.Target) { Tick = d.Tick });
return "dogs coming";
}, hasField: false);Rows appear in the F10 debug menu after the vanilla ones. The handler runs while a tick may be in progress, so it must not touch the world: read the context, queue commands, return the status text.
Define your own SimCommand records, queue them with c.Enqueue (or a debug row's Enqueue), and handle them in your system's
Inputs.
A mod can build on another code mod (a framework) and use its types directly, with one shared copy:
"dependencies": [
"rivalry.core",
{ "id": "settlement.visitors", "version": ">=1.2.0 <2.0.0", "optional": true }
]- A string is a required dependency on any version; an object takes
id, aversionrange andoptional. - Dependencies must be above your mod in the mod list (Arrange fixes that) and initialize first.
- Reference the framework's DLL with
Private="false", like the game's, and don't list it in yourassemblies. - A required dependency that can't load refuses your mod. A missing optional one is left out and your mod loads without it.
public void Initialize(ModContext c)
{
var rivalry = c.Dependency<IRivalryApi>("rivalry.core")!; // required: never null
if (c.HasDependency("settlement.visitors")) UseVisitors(c); // optional: test first
}
// Apart and not inlined: .NET resolves the types a method names when it compiles it.
[MethodImpl(MethodImplOptions.NoInlining)]
static void UseVisitors(ModContext c) => c.Dependency<VisitorsMod>("settlement.visitors")!.AddBuyer(/* ... */);Name an optional mod's types only in methods like UseVisitors, never in Initialize itself, a field or a lambda it creates: when the mod
is absent, that throws and your mod is refused.
Writing a framework: put the public surface in one DLL listed in assemblies, expose an interface your entry type implements, and
bump the major version when you break it (dependents pin >=1.2.0 <2.0.0). If you take registrations from dependents, key them by the
caller's c.Id and implement IModDependents to drop them when a dependent fails. Also list your .mod in dependents' FCS header
dependencies so the data sorts too. Details: docs/modding-dependencies.md.
Saves record the code mods they were made with (meitou-mods/environment.json); loading with a mod gone, updated or reordered shows a
notice. The save always loads.
Everything the registrations don't cover is a Harmony patch: c.Harmony is your instance, named after
your id.
- All mods share one Harmony that the game ships. Don't rely on your own copy; it is ignored.
- Small methods may be inlined and then a patch silently does nothing. Patch methods large enough not to be inlined, or their callers.
- With code mods enabled, the game compiles its code ahead only after your
Initialize, so patches made there apply to fresh code. - If two mods ship the same helper DLL, Harmony can mix up their patches. Keep patch methods in your own assembly.
- Patching on Linux and macOS is not tested yet.
The simulation gives the same result on any machine and any thread count. Your systems and patches must keep it that way:
- In
Think,Move,BeforeActandAct(parallel), write only theNextslots of your partition, readPreviousand the grid, and send effects on other characters through theEffectBuffer. - No
System.Random, no clock. UseRng.Hash(world.Seed, key, c.RngPurpose, counter). - Don't act in
DictionaryorHashSetorder; sort first. - Don't touch the world outside the tick. Outside input goes through
Enqueue.
meitou-tools comes with Meitou, next to the game. From a terminal in the Meitou folder:
meitou-tools mod-check "<save folder>" --mod "<your mod folder>"
(./meitou-tools on Linux and macOS. It finds Kenshi like the game does; otherwise set KENSHI_PATH.)
It loads the save with your mod, runs it three times and compares every tick. You get either PASS, or the first tick that differs and
which system's state differs:
DIFFERS 1 against 4 threads: from tick 152
mod mymod system 'race'
baseline the game alone agrees: the difference comes with the mods
Use a busy save (64 characters or more), or threading mistakes can't show. Options: --ticks n (default 600), --threads n (default 4).
The reasons a mod is refused, as log.txt and the game show them:
| Message | Fix |
|---|---|
| has not been allowed to | Trust it in the launcher (Play, or the Code mods button on the Mods page). |
| bad meitou.json | Fix the manifest; the message says which key. |
| built for code-mod API n | Rebuild against the current Meitou. |
| uses dependencies, ..., which need apiVersion 2 | Set apiVersion to 2. |
| built for Meitou range; this is x |
gameVersion excludes this Meitou: update the mod or the game. |
| needs X, which is not installed / not enabled | Install or enable X. |
| needs X, which loads after it | Move X above your mod (or press Arrange in the launcher). |
| needs X, which is refused: ... | Fix X first; the reason follows. |
| needs X range; v is installed | Install a version of X in the range. |
| must load after X | Move X above your mod (or Arrange). |
| is incompatible with X | Disable one of the two. |
| id is taken by mod X | Another mod that loads first uses your id. |
| X.dll is missing | List only DLLs that are in the mod folder. |
| X.dll is one of the game's own assemblies | Remove the game's DLL from assemblies. |
| X.dll comes from one of its dependencies | Remove the framework's DLL from assemblies. |
| entry type ... | Check entry: full name, implements IMod, public parameterless constructor. |
| failed to start |
Initialize threw; the stack trace is in log.txt. |
A code mod runs with your user's rights, like any program you install. Meitou cannot sandbox it. Players choose per mod in the launcher: Play asks about new code mods, and the Code mods button on the Mods page changes or takes back a choice at any time.