Data-driven trees

Keep a behavior tree in a file instead of in code: what a designer can change without a programmer, how a game builds the tree from the file and reloads it while running, and how to version and review the file.

A designer wants the wolf to flee a little sooner. If the tree is written in code, that is a ticket for a programmer, a rebuild and a new build of the game, all to change 0.25 to 0.4. A data-driven tree is one whose shape and numbers live in a data file that the game reads, so the people who tune behavior can change it without changing code. It is how most behavior tree tools work: Unreal keeps a tree as an asset, BehaviorTree.CPP loads XML, and BeeTreeCraft keeps it in a .beetree.yaml file.

This page splits a tree into what belongs in data and what belongs in code, then covers the three things a data-driven tree needs: a way for the game to build the tree from the file, a way to reload it while the game runs, and a way to version and review the file like any other source.

What goes in the file and what stays in code

The file holds the decisions: which nodes exist, how they are arranged, in what order a selector tries its branches, and the numbers each node decides by. The code holds what a node does in the world: how to measure health, how to find prey, how to walk to a point. The line between them is the custom node: a leaf type your game provides, declared in the file under custom_nodes with a name, a type (action or condition) and typed parameters, the settings each use of the node passes to your code.

version: "1.0"
metadata:
  name: wolf
  description: "Flees to its den when badly hurt, chases prey it can reach, and roams otherwise; every number it decides by is in this file"
  tags: [data-driven]
custom_nodes:
  - name: HealthBelow
    type: condition
    description: "Succeeds when the wolf's health, from 0 to 1, is below threshold"
    parameters:
      - {name: threshold, type: float, default: 0.3}
  - name: PreyWithin
    type: condition
    description: "Succeeds when prey is closer than distance, in metres"
    parameters:
      - {name: distance, type: float, default: 12.0}
  - name: MoveTo
    type: action
    description: "Runs toward a named target at a multiple of the walking speed"
    parameters:
      - {name: target, type: string}
      - {name: speed, type: float, default: 1.0}
tree:
  type: selector
  name: wolf_root
  children:
    - type: sequence
      name: flee_when_hurt
      children:
        - {type: condition, name: badly_hurt, node: HealthBelow, parameters: {threshold: 0.25}}
        - {type: action, name: run_to_den, node: MoveTo, parameters: {target: den, speed: 1.5}}
    - type: sequence
      name: hunt
      children:
        - {type: condition, name: prey_near, node: PreyWithin, parameters: {distance: 15.0}}
        - {type: action, name: chase, node: MoveTo, parameters: {target: prey, speed: 1.2}}
    - {type: action, name: roam, node: MoveTo, parameters: {target: anywhere, speed: 0.6}}

Save it as wolf.beetree.yaml. The root is a selector (a Fallback, from Building blocks): it tries its branches in order, so fleeing outranks hunting and hunting outranks roaming. Three custom nodes do all the work, and MoveTo is used three times with different settings.

With the tree in this shape, a designer can do all of these by editing the file, with no new code:

  • change a number: flee at 40 % health instead of 25 %, chase faster;
  • reorder branches: hunt before fleeing, for a braver wolf;
  • add and remove branches made of nodes the game already provides, such as a second MoveTo toward water;
  • make a second animal from the same nodes with different numbers, in a second file.

A new kind of node, such as Howl, still needs code, because the file can only arrange what the game knows how to do.

Check the file before the game reads it

A file edited by hand will one day hold a typo, and a game that finds it at run time fails in front of a player. Run beetree validate on the file first: it checks the shape against the format, and it checks every use of a custom node against its declaration. Suppose a hurried edit misspells threshold on badly_hurt and gives chase the speed fast:

beetree validate wolf.beetree.yaml
Validation errors in wolf.beetree.yaml:
  - tree.children[0].children[0]: parameter "treshold" of "badly_hurt" is not declared by custom node "HealthBelow" (did you mean "threshold"?)
  - tree.children[1].children[1]: parameter "speed" of "chase" has type float, so it expects a number such as 0.0 or 2.5, not "fast"
Error: found 2 validation error(s)

The command exits with a failure, so a commit hook or a build step can refuse the file. A declared parameter with a default, such as speed, may be left out of a node, and the node gets the default. Then run the tree without the game to see that it still decides what you meant: beetree simulate wolf.beetree.yaml --override badly_hurt=FAILURE shows the wolf skip fleeing and chase (Testing and simulation covers this in full).

Two ways a game uses the file

Generate code from it. beetree generate godot wolf.beetree.yaml (or unity, unreal) writes the tree as engine code, with one stub per custom node for your game’s code, and the parameter values of each node passed to it. The file is the source and the code is rebuilt from it, so a change to the file is a regenerate and a rebuild. This suits a team that wants the tree checked by the engine’s compiler and shipped as code.

Load it at run time. The game reads the file, builds the nodes itself, and runs them. A change to the file needs no rebuild, and the tree can even be reloaded while the game runs. This needs two small pieces of code: a node registry, a table from each custom node’s name to the code that makes it, and a loader that walks the file’s nodes and builds composites itself and leaves through the registry.

Hot reload is the second idea: when the file changes on disk, read it again, build the new tree, and replace the running one between ticks, never in the middle of one, so no node is left half run. If the new file does not build (an unknown node, a broken file), keep the tree that works and report the error, so a typo while tuning does not stop the game.

The samples below do both. The loader builds sequences, selectors and registered leaves, and the reloadable tree swaps in a new tree only when it builds. The registration function is the part each game writes: it is where HealthBelow becomes a check of the wolf’s real health, reading threshold from the file. Each sample builds on the Status type and tick() contract from Building blocks. Unity C# and Unreal C++ have no YAML reader built in, so their samples start from a NodeData the game’s JSON or YAML library fills in; Godot reads JSON itself, so its sample loads a .beetree.json copy of the tree, which beetree validate checks just like the YAML.

Agnostic

Registry: makers = {}          // custom node name -> function(nodeData) -> node

register(name, make): makers[name] = make

build(data):
    if data.type is sequence or selector:
        children = [build(child) for child in data.children]
        if any child is none: return none
        return Sequence(children) or Fallback(children)
    if data.node in makers: return makers[data.node](data)
    error = data.name + ": no code is registered for node " + data.node
    return none

ReloadableTree(registry, data):
    root = registry.build(data)
    reload(changed):           // call between ticks, after the file changed
        fresh = registry.build(changed)
        if fresh is not none: root = fresh
        else: report(registry.error)   // keep the tree that works
    tick(): return root.tick()

registerWolfNodes(registry, health):
    registry.register("HealthBelow", data ->
        Condition(health() < data.parameters.threshold, or 0.3 when absent))

Unity C#

// One node of a tree file, as your JSON or YAML library reads it.
public class NodeData
{
    public string Type;      // selector, sequence, action or condition
    public string Name;
    public string NodeClass; // the file's node: field, such as HealthBelow
    public System.Collections.Generic.Dictionary<string, object> Parameters =
        new System.Collections.Generic.Dictionary<string, object>();
    public System.Collections.Generic.List<NodeData> Children =
        new System.Collections.Generic.List<NodeData>();
}

public class NodeRegistry
{
    readonly System.Collections.Generic.Dictionary<string, System.Func<NodeData, Node>> makers =
        new System.Collections.Generic.Dictionary<string, System.Func<NodeData, Node>>();

    public void Register(string nodeClass, System.Func<NodeData, Node> make) => makers[nodeClass] = make;

    // Throws when the data names something this game cannot build.
    public Node Build(NodeData data)
    {
        switch (data.Type)
        {
            case "sequence": return new Sequence(data.Children.ConvertAll<Node>(Build).ToArray());
            case "selector": return new Fallback(data.Children.ConvertAll<Node>(Build).ToArray());
        }
        if (data.NodeClass != null && makers.TryGetValue(data.NodeClass, out var make)) return make(data);
        throw new System.ArgumentException($"{data.Name}: no code is registered for node {data.NodeClass}");
    }

    // A number parameter, or the declared default when the file leaves it out.
    public static float Number(NodeData data, string name, float fallback) =>
        data.Parameters.TryGetValue(name, out var value) ? System.Convert.ToSingle(value) : fallback;
}

public class ReloadableTree
{
    readonly NodeRegistry registry;
    Node root;
    public string LastError { get; private set; }

    public ReloadableTree(NodeRegistry registry, NodeData data)
    {
        this.registry = registry;
        root = registry.Build(data);
    }

    // Call between ticks, after the file changed and was read again.
    public void Reload(NodeData changed)
    {
        try
        {
            root = registry.Build(changed);
            LastError = null;
        }
        catch (System.ArgumentException e)
        {
            LastError = e.Message; // keep the tree that works
        }
    }

    public Status Tick() => root.Tick();
}

public static class WolfNodes
{
    public static void Register(NodeRegistry registry, System.Func<float> health)
    {
        registry.Register("HealthBelow", data =>
        {
            float threshold = NodeRegistry.Number(data, "threshold", 0.3f);
            return new ConditionNode(() => health() < threshold);
        });
    }
}

GDScript

class TreeLoader:
    var makers := {}   # custom node name -> Callable(node: Dictionary) -> BTNode
    var error := ""

    func register(node_class: String, make: Callable) -> void:
        makers[node_class] = make

    # Reads a .beetree.json file; returns null and sets error when it cannot be built.
    func load_file(path: String) -> BTNode:
        var data = JSON.parse_string(FileAccess.get_file_as_string(path))
        if not (data is Dictionary) or not data.has("tree"):
            error = "%s is not a tree file" % path
            return null
        error = ""
        return build(data["tree"])

    func build(node: Dictionary) -> BTNode:
        var type := str(node.get("type", ""))
        if type == "sequence" or type == "selector":
            var children: Array[BTNode] = []
            for child_data in node.get("children", []):
                var child := build(child_data)
                if child == null:
                    return null
                children.append(child)
            return Branch.new(type == "sequence", children)
        var node_class := str(node.get("node", ""))
        if makers.has(node_class):
            return makers[node_class].call(node)
        error = "%s: no code is registered for node %s" % [node.get("name", "?"), node_class]
        return null

class Branch extends BTNode:   # a sequence, or a selector when is_sequence is false
    var is_sequence: bool
    var children: Array[BTNode]

    func _init(s: bool, c: Array[BTNode]):
        is_sequence = s
        children = c

    func tick() -> Status:
        var stop_on: Status = Status.FAILURE if is_sequence else Status.SUCCESS
        for child in children:
            var status := child.tick()
            if status == stop_on or status == Status.RUNNING:
                return status
        return Status.SUCCESS if is_sequence else Status.FAILURE

class ReloadableTree:
    var loader: TreeLoader
    var path: String
    var root: BTNode
    var modified := 0

    func _init(l: TreeLoader, p: String):
        loader = l
        path = p

    # Call before each tick: rebuilds when the file changed, and keeps the tree that works if the new one fails.
    func reload_if_changed() -> void:
        var stamp := FileAccess.get_modified_time(path)
        if stamp == modified:
            return
        modified = stamp
        var fresh := loader.load_file(path)
        if fresh != null:
            root = fresh
        else:
            push_warning(loader.error)

    func tick() -> BTNode.Status:
        if root == null:
            return BTNode.Status.FAILURE
        return root.tick()

class HealthBelow extends BTNode:
    var health: Callable   # returns the wolf's health, from 0 to 1
    var threshold: float

    func _init(h: Callable, t: float):
        health = h
        threshold = t

    func tick() -> Status:
        return Status.SUCCESS if float(health.call()) < threshold else Status.FAILURE

static func register_wolf_nodes(loader: TreeLoader, health: Callable) -> void:
    loader.register("HealthBelow", func(node: Dictionary) -> BTNode:
        return HealthBelow.new(health, float(node.get("parameters", {}).get("threshold", 0.3))))

Unreal C++

// One node of a tree file, as your JSON reader (FJsonSerializer) reads it.
struct FNodeData
{
    FString Type;      // selector, sequence, action or condition
    FString Name;
    FString NodeClass; // the file's node: field, such as HealthBelow
    TMap<FString, float> Numbers; // the node's number parameters
    TArray<FNodeData> Children;
};

class FNodeRegistry
{
public:
    using FMaker = TFunction<TSharedPtr<FNode>(const FNodeData&)>;
    FString Error;

    void Register(const FString& NodeClass, FMaker Make) { Makers.Add(NodeClass, MoveTemp(Make)); }

    // Returns nullptr and sets Error when the data names something this game cannot build.
    TSharedPtr<FNode> Build(const FNodeData& Data)
    {
        if (Data.Type == TEXT("sequence") || Data.Type == TEXT("selector"))
        {
            TArray<TSharedPtr<FNode>> Children;
            for (const FNodeData& ChildData : Data.Children)
            {
                TSharedPtr<FNode> Child = Build(ChildData);
                if (!Child) return nullptr;
                Children.Add(Child);
            }
            if (Data.Type == TEXT("sequence"))
            {
                TSharedPtr<FSequence> Sequence(new FSequence());
                Sequence->Children = MoveTemp(Children);
                return Sequence;
            }
            TSharedPtr<FFallback> Fallback(new FFallback());
            Fallback->Children = MoveTemp(Children);
            return Fallback;
        }
        if (const FMaker* Make = Makers.Find(Data.NodeClass)) return (*Make)(Data);
        Error = Data.Name; // the node this game has no code for
        return nullptr;
    }

private:
    TMap<FString, FMaker> Makers;
};

class FReloadableTree
{
public:
    FNodeRegistry* Registry = nullptr;
    TSharedPtr<FNode> Root;
    FString LastError;

    // Call between ticks, after the file changed and was read again.
    void Reload(const FNodeData& Changed)
    {
        TSharedPtr<FNode> Fresh = Registry->Build(Changed);
        if (Fresh)
        {
            Root = Fresh;
            LastError = FString();
        }
        else
        {
            LastError = Registry->Error; // keep the tree that works
        }
    }

    EStatus Tick() { return Root ? Root->Tick() : EStatus::Failure; }
};

void RegisterWolfNodes(FNodeRegistry& Registry, TFunction<float()> Health)
{
    Registry.Register(TEXT("HealthBelow"), [Health](const FNodeData& Data) {
        const float* Found = Data.Numbers.Find(TEXT("threshold"));
        const float Threshold = Found ? *Found : 0.3f;
        return TSharedPtr<FNode>(new FCondition([Health, Threshold] { return Health() < Threshold; }));
    });
}

To reload while the game runs, check the file’s modified time once a second (from Update in Unity, _process in Godot, a timer in Unreal), and when it changed, read it, run it through your JSON or YAML library, and call Reload before the next tick. Keep this in development builds: a shipped game loads its trees once, from files that beetree validate passed before release.

One choice to make on purpose: whether a reload keeps the old tree’s state. The samples build every node fresh, so a running action restarts and memory nodes forget which child they were on (Reactive versus memory nodes). For tuning that is what you want, since the new numbers apply at once. Keeping state across a reload means matching old nodes to new ones by name, which the unique node names in a tree file make possible, and is worth it only when a restart would show on screen.

Versioning the file

A tree file is source, so keep it in version control next to the code that registers its nodes. Three habits make that work:

  • The format version. Every file starts with version: "1.0", the version of the tree format it is written in. A loader should refuse a version it does not know rather than guess. Editors can check the file as you type against the format’s JSON Schema at https://beetreecraft.com/schemas/v1/beetree.schema.json (the tree format shows how to point an editor at it).
  • Review the decision, not the text. beetree diff compares two versions of a tree by node: it names each node added, removed or moved, each parameter that changed, and each change to a custom node’s declaration. After the designer’s change to the wolf:
beetree diff wolf-before.beetree.yaml wolf.beetree.yaml
2 change(s):
  ~ tree.children.flee_when_hurt.children.badly_hurt.parameters.threshold: 0.25 → 0.4
  ~ tree.children.flee_when_hurt.children.run_to_den.parameters.speed: 1.5 → 1.8
  • Keep the code and the file in step. A custom node’s declaration in the file and its registration in code must agree. When a parameter is renamed, change both in one commit, and beetree validate every tree file in the same commit so a tree still using the old name is found before the game is.

What BeeTreeCraft shows today

  • beetree generate turns a file into engine code, and the parameter values of each node reach that code. The generated code builds its tree when it starts, so a change to the file is a regenerate.
  • There is no runtime loader in the generated code yet. Loading and hot reload are the samples above, written in your game.
  • Custom node declarations live in each tree file, so two files that use MoveTo declare it twice; keep the declarations equal by hand for now.

Where it comes from

Champandard and Dunstan’s The Behavior Tree Starter Kit (Game AI Pro, 2013) separates a tree’s data from the nodes that run it, which is what lets one set of node code run many trees. Unreal’s Behavior Tree user guide keeps trees as assets that designers edit, and BehaviorTree.CPP loads trees from XML at run time through a factory of registered node types, the same split as the registry above. More reading is on the Resources page.

Next, open the Build hub, paste the wolf into the builder and change a number, then read about the tree format to declare custom nodes and parameters of your own.