Frostdev

KilnAPI reference Guide

Pets for mod authors

Since 0.2.0-dev.32. Kiln provides the framework for pet mods (players see nothing new until they run a mod that uses it). Kiln keeps pets (records, bodies, movement, protection, revive, the owner's HUD); your mod decides what a pet is. Contract and every rule: services/pets.md. A complete example: mods/samples/PetsSample. To make a pet by taming a wild creature: taming.md.

Make it: a hound that follows its owner

A server mod of one class. A pet on a game creature asks nothing of players' games: vanilla clients see the creature, Kiln clients also get a pet bar.

  1. Make the project (mdk.md): dotnet new kiln-mod -n HoundMod, and in the .csproj <KilnModId>hound-mod</KilnModId> and <KilnServices>Blocks;Pets;Players;Saves;Chat;World</KilnServices>.

  2. Define the pet in OnLoad and give a command that grants and summons it:

    public sealed class HoundMod : Mod
    {
        public override void OnLoad() =>
            Blocks.Define("hound", new PetBlock { Creature = "game:enemy_wildbeast_wolf_earlygame", Name = "Hound" });
    
        [Command("hound", Description = "get a hound and bring it out", Permission = CommandPermission.Admin)]
        private async Task Hound(CommandContext c)
        {
            if (!Capabilities.Is(Pets.RecordsCapability)) throw new CommandException($"pets.records is off: {Capabilities.Why(Pets.RecordsCapability)}");
         if (!Capabilities.Is(Pets.SummonCapability)) throw new CommandException($"pets.summon is off: {Capabilities.Why(Pets.SummonCapability)}");
            var key = CharacterData.KeyOf(c.Source.Player);
            var given = await Pets.Grant(key, "hound-mod:hound", PetRequest.New());       // the id is <mod id>:<name>
            if (!given.Ok) throw new CommandException($"refused: {given.Reason}");
            var summoned = await Pets.Summon(PlayerRef.Of(c.Source.Player), given.Pet!.Id, PetRequest.New());
            c.Reply(summoned.Ok ? "your hound is out" : $"refused: {summoned.Reason}");
        }
    }
    
  3. Build and deploy to a server with Kiln (dotnet build with KilnServer set; mdk.md), join, and run /hound. A wolf comes out and follows you; kiln.log says what Kiln did, and each refusal has its reason (PetResult.Reason).

  4. Make choices: what happens when the pet is downed, whether it can fight other players' pets, what a revive costs. Every choice is a field of the block or an event handler below.

Everything else on this page is the reference for step 4. mods/samples/PetsSample is this mod with a second kind of pet (the duelist), /pet commands for every call and the events.

Define a pet

In C# (OnLoad), as a block:

// a game creature, by its creatures-registry id: asks nothing of players' games
var hound = Blocks.Define("hound", new PetBlock { Creature = "game:enemy_wildbeast_wolf_earlygame", Name = "Hound" });

// a creature block of your own, and every choice spelled out
var wolf = Blocks.Define("wolf", new CreatureBlock { Body = Bodies.Vukah });
Blocks.Define("duelist", new PetBlock
{
    Creature = wolf,
    Name = "Duelist",
    Level = new PetLevelPolicy { Mode = PetLevelMode.OwnerAtSummon },
    Movement = new PetMovementPolicy { FollowDistance = 4, AllowCatchUp = false },
    Targets = new PetTargetPolicy { Pvp = PetPvpMode.ByModRule, HostileFactions = [Faction.Vukah, Faction.Fogger] },
    Downed = new PetDownedPolicy { Outcome = PetDownedOutcome.Absent },
    Revive = new ReviveBlock { ChannelDuration = TimeSpan.FromSeconds(5), Cost = new ReviveCostBlock("Material_T1_Twigs", 3) },
    Limits = new PetLimits { LivePerCharacter = 2 },
    Hud = new PetHudPolicy { RecoveryMarker = false },
});

Or in blocks/*.json, section pets, the same fields:

{
  "format": 1,
  "pets": {
    "hound": { "creature": "game:enemy_wildbeast_wolf_earlygame", "name": "Hound" },
    "duelist": {
      "creature": "wolf", "name": "Duelist",
      "targets": { "pvp": "byModRule", "hostileFactions": ["vukah", "fogger"] },
      "downed": { "outcome": "absent" },
      "revive": { "channelSeconds": 5, "cost": { "item": "Material_T1_Twigs", "count": 3 } }
    }
  }
}

The pet's id is <mod id>:<name> (Was keeps it through a rename). Without Kiln.Blocks: Pets.Define(new PetDefinition { Id = "my-mod:hound", Creature = "game:enemy_wildbeast_wolf_earlygame" }). A creature is always a Kiln id: never a template name or a GUID. Enemies, wildlife and farm animals that walk can be pets (no bosses, villagers or flying bodies). A wildlife or farm pet (game:animal_wildlife_dog_05_white_ag2) follows and stays like any pet but never fights: it has no combat AI, so an attack order answers CannotFight and EngineGuard is refused.

A tamed animal as a pet. Pets.Adopt(owner, "my-mod:dog", animal, PetRequest.New()) makes a pet record over a creature in the world: a wild or farm animal the owner tamed (the game's own taming, NativeTamedEvent; Kiln.Taming's TamedEvent), or any creature your mod gives a player. The creature must be the definition's creature, alive, and no player or pet. The pet keeps its share of health, the animal's own body goes and the pet is summoned next to its owner (PetAdoptOptions: KeepHealth, RemoveSource, Summon). Who adopts which animal, and when, is your mod's rule: the game records no tamer, and Kiln names who made the taming step it saw (NativeTamedEvent.TamedBy, null when it saw none).

Events.On<NativeTamedEvent>(e =>
{
    if (!Capabilities.Is(Pets.RecordsCapability)) return;   // records are kept on the server only
    // this mod's rule: the player who made the step that tamed it gets the pet; nobody when Kiln saw no petting
    if (e.TamedBy is not { } tamer) return;
    Pets.Adopt(tamer, "my-mod:dog", EntityRef.Of(e.Creature), PetRequest.New())
        .ContinueWith(t => Log.Info(t.Result.Ok ? "adopted" : $"not adopted: {t.Result.Refusal}"), TaskContinuationOptions.OnlyOnRanToCompletion);
});

Your own creature with its own brain as a pet: Movement = new PetMovementPolicy { Mode = PetMovementMode.Brain } (JSON "movement": { "mode": "brain" }) on a creature block whose behaviour has a Brain. Kiln holds the body (the game's AI off) and your brain moves it: read npc.Pet (null when the creature is no pet) for its order and target and npc.PetOwner for the owner's entity, and decide what following, staying and fighting look like:

public override void Tick(NpcControl npc)
{
    if (npc.Pet is not { } pet) { /* a wild one: your usual behaviour */ return; }
    if (pet.RequestedOrder == PetOrder.Stay || !World.TryGetPosition(npc.PetOwner, out var owner)) { npc.Stop(); return; }
    if (pet.RequestedOrder == PetOrder.Attack && !pet.RequestedTarget.IsNone) { npc.Target = pet.RequestedTarget.Id; /* your attacks */ return; }
    if (npc.Position is { } at && at.DistanceTo(owner) > 3) npc.MoveTo(owner, run: at.DistanceTo(owner) > 10); else npc.Stop();
}

Kiln still protects it (your attacks hit only what the pet's target rule allows), catches it up when it is far (AllowCatchUp) and retires it when it goes down. Without Mode = Brain a creature block with a brain is walked by Kiln as any pet, and its brain does not run on the pet's body. A revive cost's item is checked once the game's content is ready: an item the game lacks (or gear) is your mod's error in kiln.log and the launcher, and that pet's revives are refused (CostUnavailable) with nothing taken. A dedicated server reads its item catalog only once its world runs, so there the item is found in the game's data (as loot tables find theirs); gear is told only where the catalog is readable (the SDK's bake, a game that hosts).

Give, summon, order, revive, release

if (!Capabilities.Is(Pets.RecordsCapability) || !Capabilities.Is(Pets.SummonCapability)) return;   // a joined client has neither
var owner = CharacterData.KeyOf(player);              // the character
var given = await Pets.Grant(owner, "my-mod:hound", PetRequest.New());
if (!given.Ok) { Log.Info($"not given: {given.Refusal}"); return; }
var who = PlayerRef.Of(player);
var pet = given.Pet!.Id;
var r = await Pets.Summon(who, pet, PetRequest.New());
if (!r.Ok) Log.Info($"not out: {r.Refusal}");          // a refusal is a result: Capacity, NoSafeGround, ...
if (Capabilities.Is(Pets.FollowCapability))
{
    r = await Pets.Command(who, pet, PetOrder.Stay, EntityRef.None, PetRequest.New());
    r = await Pets.Command(who, pet, PetOrder.Attack, EntityRef.Of(enemy), PetRequest.New());   // checked against the pet's rule
    if (r.Refusal == PetRefusal.TargetProtected) Log.Info("its rule protects that target");
}
if (Capabilities.Is(Pets.DownedCapability))
{
    r = await Pets.Revive(who, pet, PetRequest.New());  // stand at its recovery anchor
    if (!r.Ok) Log.Info($"no revive: {r.Refusal}");
}
r = await Pets.Release(who, pet, PetRequest.New());
if (!r.Ok) Log.Info($"not released: {r.Refusal}");
foreach (var p in Pets.Of(owner)) Log.Info($"{p.DisplayName}: {p.Life} {p.Presence} {p.Health}/{p.HealthMax}");   // "Hound: Ready Live 80/100"

A pet's DisplayName (never empty, the name to show players) is its definition's Name, else its creature's name (Kiln's creature catalog, a creature block's Name, else one made from the template or block name), else one made from the definition id; DisplayNameSource says which, and Label is the same name (display names).

Every answer is a PetResult (Ok, Reason, the pet after it, cost receipts). Decide by Refusal (PetRefusal.Capacity, PetRefusal.NotOwner, ...), never by the Reason text, which is for logs. Requests run on the server's tick thread; await them from your handlers or commands.

Decide per pet

  • PetDowningEvent: set Outcome to choose what this pet becomes (an anchor, absent, released, or a body left lying: PetDownedOutcome.Body, an inert decorative body of the creature at its anchor in its Dead pose until it is revived, dismissed or its owner leaves; PetSnapshot.DownedBody names it).
  • PetRevivingEvent: Cancel() to refuse a revive (a cooldown, a zone); nothing is taken. Every mod sees every pet's revive: check e.Pet.Definition and rule only your own pets (PetsSample's cooldown counts and refuses only pets-sample: pets).
  • Pets.SetHostile(a, b, true): your duel rule. Pets whose targets say byModRule may then fight the other character and that character's by-mod-rule pets. Declare it when both players agreed; end it with false. Pairs last for the world session.
  • Attack, assist, defend: Kiln never attacks by itself. Order an attack when your rule says so (the owner was hit, a key was pressed); Kiln refuses targets the pet's rule protects (TargetProtected).

Walking beside the owner: measured clearance

A pet walks routes beside its owner only when Kiln has a measured clearance profile for its creature's body, at its scale, on the running game build (the service page). Without one it still follows, by catching up to its owner on safe ground. Kiln ships two kinds, and a game update invalidates both until Kiln ships new ones:

  • creature profiles for the game creatures it calibrated one by one (the list is on the service page);
  • body profiles: when three or more walking creatures with the same body (path walker, movement collider, the template's own scale) were calibrated, every walking creature with that body gets the best pair that every one of them passed. These cover most of the game's walking enemies at scale 1 (the service page lists the bodies).

Since PETS-3 they cover the game's wildlife and farm animals that walk as well: the tameable dogs, cats, goats, bunnies, cat-deer, turkeys, desert birds, the capybara and the yak, and the farm babies, at scale 1 (the list). A tamed dog adopted with Pets.Adopt walks beside its owner. Fish and flying birds have none: their pets catch up.

Since PETS-4 every profiled body up to 1 m wide walks through 1 m gaps, and the short ones under low ceilings: cats, bunnies and the farm babies under 1 m, the dogs, goats, wolves and the other beasts up to 1.5 m tall under 1.5 m (the measurements). Every pet still catches up through a 0.5 m gap and around a 1 m corner.

A game creature's id matches whatever its case (game:Enemy_Vukah_Melee is game:enemy_vukah_melee).

Your own creature block, or a game creature at a scale Kiln did not calibrate, needs a profile of your own (unless its body has a body profile). The calibration runs on Kiln's own lab tooling, on a dedicated lab server (no game client), so it needs what Kiln's developers use:

  • a Kiln source checkout, on Linux (Building on Linux: prepare builds Kiln and deploys it into the lab);
  • the lab base: a vanilla SteamCMD install of the dedicated server in ~/srv/enshrouded/lab2 with a world in its savegame folder, and a GE-Proton Wine prefix in ~/srv/enshrouded/ge-pfx (Lab base; tools/lab/lab.sh says what it reads).
  1. Build your mod, then calibrate in a lab of your own (a lowercase <name>-<name> and a free UDP port):
    tools/pets-clearance/calibrate.sh prepare --lab my-pets --port 32100 --creature my-mod:wolfling --mod path/to/built/my-mod --out .out/my-clearance
    tools/pets-clearance/calibrate.sh run --lab my-pets --out .out/my-clearance     # one lab session: 1 min, then about 12 min a small creature with the default sweep (2.5 more with the native walk)
    tools/pets-clearance/calibrate.sh profile --lab my-pets --out .out/my-clearance
    
    For a game creature at another scale: --creature game:[email protected]. report.md shows every fixture and requirement pair, and why a pair failed or does not vouch for the body. run stops at once when the lab server ends before the lab mod's last line. The default sweep asks every fixture for HorizontalSpace 0, 0.5, 1 and 2 m with VerticalSpace 1, 1.5, 2 and 3 m. 0 is the only value that finds a 1 m gap, and 1.5 the only one that walks a body of 1 to 1.5 m under a 1.5 m ceiling. --horizontal 0,0.5 --vertical 1,1.5 (metres, 0 to 16) sweeps fewer pairs, which shortens a session: every accepted route is walked, about 10 s each (two pairs took Kiln's lab 3 to 4 minutes a creature). For a small creature the larger values only walk the open control. calibrate.sh plan (the same options) writes the next session's plan into the stopped lab without building anything.
  2. Ship .out/my-clearance/clearance.json as pets/clearance.json in your mod's folder. It applies to your mod's pets only, and only on the game build it names. It may hold body profiles too, when you calibrated three or more creatures of one body. Any of its profiles comes before any of Kiln's (your body profile beats Kiln's creature profile for your pets), and any profile in a server operator's kiln/data/kiln.pets/clearance.json comes before any of yours: an operator may override your profile for your pets on their server, even with a body profile over your creature profile (kiln.log says so once per creature). Within one file a creature profile beats a body profile.
  3. Calibrate again after a game update (the profile names the build), and after you change the creature's Body.Size or Body.Scale (the profile names the body it was measured on; a running server notices a changed body within 10 s).

A creature for which no requirement pair passes gets no profile: a route it accepts somewhere would be one its body cannot walk. Nor does a body wider than 2 m or taller than 3 m (the lab's widest gap and highest headroom), which the fixtures cannot judge, nor a pair that leaves a gap or headroom one 0.5 m cell narrower or lower than the body unmeasured. Its pets catch up instead.

The HUD

Kiln draws a pet bar for owners whose game runs Kiln. Per definition: PetHudPolicy. Per player: PetsClient.Configure(new PetHudOptions(Enabled: false)) and draw your own from PetsClient.Snapshot in a RenderFrameEvent handler (read the snapshot once per frame; never act on the game from the render thread).

Your HUD's buttons or keys order a pet through the server: PetsClient.Send(new PetCommand(PetCommandKind.Stay, pet)) (Summon, Dismiss, Follow, Stay, Attack with a Target, Revive, CancelRevive with the ReviveRequest, Release). The server runs it as the owner's own request with every rule of the pet, and answers your game alone (PetCommandAnswer; decide on its Refusal). A command is an explicit action of the player, never something a frame sends:

// the owner's game: a key or a button of your HUD
if (!Capabilities.Is(Pets.CommandsCapability)) return;   // no Kiln server, or a game without Kiln.Network
PetCommandAnswer answer = await PetsClient.Send(new PetCommand(PetCommandKind.Stay, pet));
if (!answer.Ok) Log.Info($"the pet did not stay: {answer.Refusal}");   // RateLimited, RefusedByMod, NoAnswer, NotOwner, ...

To refuse some orders from players' games (say, no release from the HUD, or no attack outside an arena), cancel PetCommandRequestedEvent on the server and set its Reason:

Events.On<PetCommandRequestedEvent>(e =>
{
    if (e.Command.Kind != PetCommandKind.Release) return;
    e.Reason = "release a pet with /pet release";
    e.Cancel();   // the game is told RefusedByMod with this reason; nothing changes
});

What a player's game needs

A pet on a game creature: nothing (vanilla players see the creature; only Kiln clients see the bar). A pet on a creature block with a body or animation of your own: what that creature block needs (clients: mod).

Enshrouded is a trademark of Keen Games GmbH. Kiln is unofficial.