# Agents and brains

> Write an agent record and a hull, register a brain that sends its body round the map, drive a body with raw commands, and check it all with the navigation console commands.

Part of [Plugins](/docs/plugins) in the Evil Engine docs.

An agent is what moves and thinks for a body. It's two things: an `agent` record, data that says the body's hull, how fast it goes at each gait and which brain it thinks with, and the brain, code a Plugin registers by id. A body attaches its agent as it spawns, as every NPC whose class names one does ([NPCs](/docs/plugins/npcs)).

A brain decides; locomotion moves. The brain thinks every so often and says what it wants, a goal, a facing or a raw command. Between thinks, every tick, the engine's locomotion turns that into the body's movement: a route over the map's navigation for its hull, followed corner by corner, slowing to arrive, turning, stepping round other bodies, through the same controller every player moves with.

## Agent records

Put agent records in your Plugin's `Records/` beside its spawnables. This is the brute's from [NPCs](/docs/plugins/npcs):

```toml
[agent."agent/brute"]
hull = "brutes:hull/brute"
brain = "brutes:brain/fetch"
speeds = { walk = 1.1, run = 3.5 }
turn = 180
think = 0.2
drop = 2
```

| Key | What it is |
| --- | --- |
| `base` | An agent record this one builds on. Every key it leaves out comes from the base. |
| `brain` | The brain it thinks with, by the id a Plugin registers it under. |
| `hull` | The hull record its navigation and its body's size come from. |
| `movement` | A `movement` record for the controller's numbers, as a player class names one. |
| `speeds` | Metres a second by gait, `{ walk = 1.1, run = 3.5 }`, or one number for every gait. `"clip"` in place of a number is the moving clip's own ground speed, so its feet never slide. A gait with no speed moves at its movement record's run speed for `run` and its walk speed for any other. |
| `turn` | How fast it turns, in degrees a second. |
| `think` | Seconds between its brain's thinks, above 0. |
| `drop` | The highest fall, in metres, its routes take off a ledge. |
| `moves` | Any of `walk`, `jump`, `climb`, `fly` and `swim`. |
| `route` | The graphs it routes on, `nodes` and `mesh`. |
| `jump` | `{ height, distance }` it can jump. |
| `doors`, `breaks`, `always`, `knows` | Whether it opens doors, breaks breakables on its way, thinks at its full rate when no one can see it and knows where its targets are unseen. |

Every record is merged over its `base`, then over the engine's `evil:agent/default`: the `evil:hull/human` hull, walking on the mesh, turning at 360° a second and thinking every 0.1 s. `evil.source`'s Half-Life 2 agents are all built on `evil.source:agent/npc`, which moves at the clips' own speeds, each naming its class's Source hull, so a record of `base = "evil.source:agent/npc_zombie"` and a `brain` moves as Half-Life 2's zombie does and thinks with your brain.

Only part of the record moves anything yet. Routes walk the navigation mesh and take drops up to `drop`; `nodes` in `route`, `moves` beyond walking, `jump`, `doors`, `breaks`, `always` and `knows` are read and kept, but nothing acts on them yet.

## Hulls

A `hull` record is the box a body is and the navigation it walks:

```toml
[hull."hull/brute"]
title = "Brute"
width = 0.9
height = 2.0
step = 0.45
slope = 45
blocks = ["world", "npcclip"]
```

| Key | What it is |
| --- | --- |
| `width`, `height` | The box, in metres. Both are needed. |
| `origin` | `feet` (the default), where the box stands on its origin, or `centre`, for one that hangs round it, as Source's flying hulls do. |
| `step`, `slope` | The highest step it climbs, in metres, and the steepest ground it walks, in degrees, over its movement record's. |
| `blocks` | What stops it: any of `world`, `npcclip` and `playerclip`. `["world"]` by default. |

The host bakes a navigation mesh for every hull in the session's records as it loads a map, and caches it, and hulls of the same shape share one mesh. So a hull costs a bake on every map the first time it's seen. When one already fits, name it: the engine's are `evil:hull/tiny`, `small`, `human` and `large`, and `evil.source` has Source's nine, `evil.source:hull/human` among them.

An agent whose hull the map has no mesh for walks straight at its goals, with a note.

## Registering a brain

A brain is an [IBrain](/docs/api/ibrain), one for each body, made by a function you register through your context's [Agents](/docs/api/plugincontext#agents) while your Plugin loads. The brute Plugin's `Load` registers its brain beside its class:

```csharp
context.Agents.Brain(ContentId.Parse("brutes:brain/fetch"), agent => new Fetch(context.Physics));
```

The function gets the [IAgent](/docs/api/iagent) the brain thinks for, as the body attaches its agent. [Brain](/docs/api/iagents#brain) only works inside `Load`: a call after it has returned throws `InvalidOperationException`. When two Plugins register one id, the later in load order wins, and when it unloads the earlier's comes back.

A body whose record names a brain no loaded Plugin registers stands idle, and the session notes it once. One whose brain's function throws stands idle too, with a note.

## Thinking

[Think](/docs/api/ibrain#think) is called at the record's `think` interval, which the agent's [Interval](/docs/api/iagent#interval) reads back, in the session's think phase on the server's thread. Agents on the same interval are spread over its ticks, so a hundred zombies never all think on one tick. A body that dies lets go of its agent, and its brain never thinks again.

A brain reads the body through the agent, its [Feet](/docs/api/iagent#feet), `Velocity`, `Yaw`, `OnGround`, `Health`, `Class` and `Time`, and says what it wants. It has no senses of its own yet, so what else it knows is what your Plugin hands it as you make it, such as its view of the physics world.

Here's the brute's brain. It runs to the nearest prop, ragdoll or any other dynamic body, faces it once it's there, and gives up on one it can't reach:

```csharp
using EvilEngine.Api.Agents;
using EvilEngine.Api.Physics;
using EvilEngine.Formats.Maps;

namespace Brutes;

sealed class Fetch(IPhysicsWorld? physics) : IBrain
{
    readonly HashSet<IPhysicsBody> unreached = [];
    IPhysicsBody? target;
    MapVector sent;

    public void Think(IAgent agent)
    {
        if (agent.Motion is AgentMotion.Unreachable or AgentMotion.Stuck && target is not null)
        {
            unreached.Add(target);
            target = null;
        }

        if (target is null || target.Removed)
        {
            target = physics?.Bodies
                .Where(body => body.Motion == BodyMotion.Dynamic && !unreached.Contains(body))
                .MinBy(body => Flat(body.Position, agent.Feet));
            if (target is null)
            {
                agent.Stop();
                return;
            }

            sent = target.Position;
            agent.MoveTo(sent, new AgentMove { Gait = AgentMove.Run, Within = 1.5 });
        }

        var at = target.Position;
        if (Flat(at, sent) > 1)
        {
            sent = at;
            agent.MoveTo(sent, new AgentMove { Gait = AgentMove.Run, Within = 1.5 });
        }

        if (agent.Motion == AgentMotion.Arrived)
            agent.Face(Math.Atan2(agent.Feet.X - at.X, agent.Feet.Z - at.Z) * 180 / Math.PI);
        else
            agent.Face(null);
    }

    static double Flat(MapVector a, MapVector b)
    {
        return Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Z - b.Z) * (a.Z - b.Z));
    }
}
```

## Moving

[MoveTo](/docs/api/iagent#moveto) sends the body to a point at an [AgentMove](/docs/api/agentmove):

| Member | What it is |
| --- | --- |
| [Gait](/docs/api/agentmove#gait) | `walk` unless set, or `AgentMove.Run`, or any name of your own. The body plays its `motion` slot of that name, and the record's `speeds` say how fast. |
| [Within](/docs/api/agentmove#within) | How near is near enough, in metres. 0 gets as near as it can. |
| [Speed](/docs/api/agentmove#speed) | Metres a second for this move alone, over the record's. |

[Motion](/docs/api/iagent#motion) says how it's going, as an [AgentMotion](/docs/api/agentmotion): `Still` before it's sent anywhere or after a [Stop](/docs/api/iagent#stop), `Moving` on its way, then `Arrived`, `Unreachable` when no route reaches the goal and it stands where the route ran out, or `Stuck` when it kept making under a quarter of the progress it asked for, even after a fresh route and backing off. [Goal](/docs/api/iagent#goal) is where it's going, [Route](/docs/api/iagent#route) the corners still ahead, and [Gait](/docs/api/iagent#gait) what the body plays, `idle` when it isn't moving.

Sending it again replaces the goal and plans a fresh route, and starts its count towards `Stuck` again. So send a new goal when the old one has gone stale, as the fetch brain does when its target has moved a metre, not on every think, or a body walking into a wall never finds out it's stuck.

[Face](/docs/api/iagent#face) turns it to a yaw in degrees at the record's `turn` rate, even while it moves, and `null` turns it back to facing where it goes. Yaw 0 faces −Z, and a body at its feet faces a point at `atan2(feet.X − point.X, feet.Z − point.Z)` in degrees, as the fetch brain turns to its target.

## Raw commands

When locomotion isn't what you want, a jump, a dodge or a body you steer yourself, drive it with [Command](/docs/api/iagent#command), the same command a player's input fills:

```csharp
agent.Command(new AgentCommand(1, 0, 0, 0, agent.Yaw, AgentButtons.Run | AgentButtons.Jump));
```

An [AgentCommand](/docs/api/agentcommand) is `Forward` and `Side` from −1 to 1 of the speed its buttons give, `Up` for flying and swimming, the `Pitch` and `Yaw` it looks and moves along in degrees, and its [AgentButtons](/docs/api/agentbuttons): `Jump`, `Crouch`, `Run`, `Walk`, and `Attack`, `Attack2` and `Reload` for a weapon it holds. The command holds every tick until you give another, and while it does locomotion stands aside, so a goal waits. `agent.Command(null)` hands the body back to it.

## When a brain goes wrong

A brain that throws is dropped with a note naming it and the body, and its body stands idle from then on. The agent's calls throw on what they can't use: a goal, facing or command that isn't finite, a move's `Within` or `Speed` below 0, or buttons that aren't `AgentButtons` throw `ArgumentOutOfRangeException`, and a move with no gait throws `ArgumentException`. Thrown inside `Think`, any of them drops the brain like any other throw, so check your numbers before you send them.

## Checking it

The console has two commands for seeing what an agent has to walk on and where it'll go:

```
nav_show human
nav_show evil.source:hull/human
ai_goto
ai_goto run
ai_goto run 10 0 -4
```

`nav_show` draws a hull's navigation mesh and its drops over the world, by its id or by its name after `hull/`, and empty draws none. Only a host draws it, since clients never bake navigation. `ai_goto` sends every NPC's agent walking, or with `run` running, to where you look or to a point. It's the same `MoveTo` a brain calls, so it replaces whatever goal a brain sent, until the brain sends another. A body with no brain walks there and stands.

`just map-shot` takes the same as flags, for a screenshot of a route, and `just nav-check` bakes every hull's mesh headless on gm_construct, gm_flatgrass and gm_bigcity_dusk, or the `--maps` you give it, and fails if any spawn point has no path to another for `--hull`:

```
just map-shot gmod:gm_construct --walk=-:1 --spawn=brutes:npc_brute --goto=10,0,-4@run --nav-show=brutes:hull/brute --screenshot=route.png
just nav-check --hull=brutes:hull/brute
```

---

- [Previous: NPCs](/docs/plugins/npcs)
