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, combat hit callbacks, equipment slots, save data, interface pieces, settings, debug commands, and Harmony patches on
the game's own code. This page is the practical guide; every hook is listed in Code mod hooks, and making characters act (goals, jobs,
orders) is in AI goals and orders. The engine-side contract and its evidence are in
docs/modding.md.
Code-mod API version: 3, which adds the AI goals and orders surface. Older builds run API 2, and
v0.16.1-nightly.20261107 and older API 1 only. API 1 and 2 mods still load; see Moving from API 1 or 2.
BepInEx is not supported; for RE_Kenshi plugins see RE_Kenshi compatibility.
-
Make a class library for
net11.0(the standard builds on every platform since v0.17.4;net10.0for the legacy macOS build and for v0.17.3 and older). -
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>net11.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <!-- The game: Meitou.Modding (IMod, ModContext, ...) and Meitou.Game.Ui --> <Reference Include="C:\Games\Meitou\MeitouClient.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" /> </ItemGroup> </Project>
Releases after v0.17.1 have no
Meitou.Modding.dllorMeitou.Ui.dll: both are compiled intoMeitouClient.dll, and a mod built against v0.17.1 or earlier must be rebuilt. -
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": 3, "assemblies": ["MyMod.dll"], "entry": "MyMod.MyMod" } -
Enable the mod in the Meitou launcher and press Play. 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, 2 or 3. A number the game doesn't run refuses the mod with a message. A mod using AI goals and orders declares 3, so a game without that surface refuses it. |
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.
- Every enabled code mod runs its code; enabling it is the player's consent. There is no trust list or question.
- 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.AddEquipmentSlot(new ModSlot("mymod_hands", 10, 2, 2, 300, 120)); // section, FCS slot, width, height, x, yModSlot is in Meitou.Simulation.Items. Builds after v0.17.5-nightly.20261112.2.
- The slot is a new inventory section, named by its first argument. ARMOUR and ITEM records whose FCS
slotis the second argument go in it, so the items stay an ordinary data mod: setslotin your.mod(10 is ATTACH_GLOVES, 11 ATTACH_NECK). - Allowed
slotnumbers: 4, 10, 11, or 15 and up. The others are the game's. A game section name, or a name or number another mod took, refuses your mod. - It holds one item, 1 to 20 cells wide and high, and counts as worn gear like the vanilla clothing slots: armour stats, the character's look, equipping, trade, looting and locks.
- It shows in the character and loot windows as a copy of the belt slot, at
x,ylayout pixels (UI scale 1) from the window's top-left corner. Pick a free spot: the window doesn't grow. Animals get none. - Saves store the section name. Loaded without your mod, the item goes back to the character's main grid.
- A registered system implementing
ICombatHitObservergetsHitResolved(World, in CombatHit)once for every landed melee or projectile hit and every execution blow: damage dealt, armour absorbed, the body part hit, attacker and victim. It may read the world and change its own state; game changes go through queued commands. A throw disables it for that world. -
c.AddCombatHitFeed(hits => ...)is for display only (blood, hit markers): once a frame on the render thread, the hits since the last frame. Don't touch the world there, and copy what you keep: the list is reused.
c.AddUi(extension) takes an IUiExtension (from Meitou.Game.Ui, in MeitouClient.dll): your own styles, controls and actions, overrides of vanilla ones, and
contributions to HUD slots (UiSlots).
public sealed class MySettings
{
[Setting("Dog count", Min = 0, Max = 20)] public int Dogs { get; set; } = 5;
[Setting("Loud dogs")] public bool Loud { get; set; }
}
var group = c.AddSettings(new MySettings());
group.Changed += setting => { /* copy into your system's inputs */ };Once per mod. The marked properties appear under your mod on the Settings screen's Mods page: a bool as a switch, numbers as sliders
(Min and Max required, optional Step), an enum or a string with Options as a list. The player's values are kept between runs and
set before AddSettings returns; your initial values are the defaults. The page sets a property outside the tick, so copy what the
simulation needs in a serial step.
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 |
|---|---|
| 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 mod that loads but uses a member the game removed (for example a hook API 3 replaced) is not refused as a whole: the part that binds the
member is stopped, the game goes on, and the player sees one notice for the session, Mod <mod> was built for another version of the game and needs an update; it is stopped and the rest of the game goes on. Rebuild it against the current Meitou
(Moving from API 1 or 2).
A code mod runs with your user's rights, like any program you install. Meitou cannot sandbox it. Installing and enabling a code mod is the consent: the game runs every enabled code mod's code without asking.