Recursive composition

Write a behavior once as a tree of its own and run it inside other trees as a subtree: one node to the parent, a whole tree inside.

Every guard, merchant and villager in a game should run away from danger. You could copy the same three nodes into each of their trees, but then a fix to fleeing has to be made in every copy, and the copies drift apart. A subtree is the answer: a node that runs another tree and returns that tree’s result. Fleeing is written once, in a file of its own, and every character that needs it points at that file.

This works because of a property the building blocks page set up: every node has the same one operation, tick(), and returns the same three statuses. A whole tree is ticked through its root, so a whole tree looks like one node from the outside. That is what recursive composition means: trees are made of nodes, and a node can be a tree. A subtree can hold subtrees of its own, as deep as you like.

What the parent sees

To the tree that uses it, a subtree is one child. The parent does not know or care what is inside:

  • It returns Success when the inner tree’s root succeeds, Failure when it fails, and Running while it is still at work.
  • A sequence or selector treats it like any other child: a failing subtree makes a sequence stop, and makes a selector try its next child.
  • A decorator can wrap it. Retry(flee) retries the whole escape, not one step of it.

The inside of the subtree is a normal tree. You can open it, test it and simulate it alone, which is the second reason to split a tree: a small tree is easier to read than a large one.

A tree you can run

A gate guard runs away and patches up when badly hurt, fights an intruder, and otherwise stands watch. Fleeing and patching up are trees of their own, in a subtrees folder. Save the three files below under the names in their first line.

# file: gate-guard.beetree.yaml
version: "1.0"
metadata:
  name: gate-guard
  description: "Guards a gate; reuses the flee and patch-up trees"
  tags: [subtrees, recursive-composition]
subtrees:
  - {name: flee, file: subtrees/flee.beetree.yaml}
  - {name: patch_up, file: subtrees/patch-up.beetree.yaml}
tree:
  type: selector
  name: guard_root
  children:
    - type: sequence
      name: retreat_when_hurt
      children:
        - {type: condition, name: badly_hurt, node: IsBadlyHurt}
        - {type: subtree, name: run_away, ref: flee}
        - {type: subtree, name: heal, ref: patch_up}
    - type: sequence
      name: hold_the_gate
      children:
        - {type: condition, name: intruder_seen, node: IntruderSeen}
        - {type: action, name: attack, node: Attack}
    - {type: action, name: stand_watch, node: StandWatch}
# file: subtrees/flee.beetree.yaml
version: "1.0"
metadata:
  name: flee
  description: "Break line of sight, then run to cover"
tree:
  type: sequence
  name: flee
  children:
    - {type: action, name: break_line_of_sight, node: BreakLineOfSight}
    - {type: action, name: run_to_cover, node: RunToCover}
# file: subtrees/patch-up.beetree.yaml
version: "1.0"
metadata:
  name: patch-up
  description: "Drink a potion if there is one, else bandage"
tree:
  type: selector
  name: patch_up
  children:
    - type: sequence
      name: drink_potion
      children:
        - {type: condition, name: has_potion, node: HasPotion}
        - {type: action, name: drink, node: DrinkPotion}
    - {type: action, name: bandage, node: Bandage}

The guard names each file once under subtrees and points at it with ref. A node can also name the file directly with file, which suits a tree that uses a subtree only once. Paths are relative to the tree that names them. Check all three, then run the guard:

beetree validate gate-guard.beetree.yaml subtrees/flee.beetree.yaml subtrees/patch-up.beetree.yaml
beetree simulate gate-guard.beetree.yaml --override has_potion=FAILURE

The trace shows each subtree as a node (run_away, heal) with the inner tree’s lines indented under it, so you can see where one tree ends and the next begins. With no potion, drink_potion fails and the patch_up selector falls back to bandage, and the guard’s own tree never notices: heal still succeeds.

beetree render gate-guard.beetree.yaml draws the whole tree, subtrees included. In the web builder, which cannot open files from your disk, a subtree acts as one leaf: you choose the result the whole subtree returns, which is exactly how its parent sees it.

Rules that keep composition safe

  • No loops. A tree that includes itself, directly or through another subtree, would never finish building. beetree validate rejects it and names the chain of files.
  • One copy per use. Two characters running flee must not share its state: if one is halfway through run_to_cover, the other has not started. In engine code, build a fresh copy of the subtree for every place it is used. The samples below do that.
  • Shared variables. A blackboard is the set of named variables a tree reads and writes, such as health or target. In BeeTreeCraft a subtree’s blackboard variables join the tree’s own, so the guard and its flee tree see one target. Some engines give each subtree a blackboard of its own and map names in and out instead. BehaviorTree.CPP does this with port remapping.

Engine code

beetree generate reads the subtree files and builds them in, so the generated code holds the whole behavior and one class per leaf, even when two trees share it. If you write your own runtime, a subtree is a node that ticks the root of another tree. Build that tree from a function, so each use gets a fresh copy. Each sample uses the Status type and tick() contract from Building blocks.

Agnostic

Subtree(label, build):
    root = build()              // a fresh copy of the inner tree for this use
    tick():
        return root.tick()      // the inner tree's result is the subtree's result

flee = () => Sequence(BreakLineOfSight, RunToCover)
guard = Fallback(
    Sequence(IsBadlyHurt, Subtree("run_away", flee), Subtree("heal", patchUp)),
    Sequence(IntruderSeen, Attack),
    StandWatch)

Unity C#

public class Subtree : Node
{
    public readonly string Label;
    readonly Node root;

    // build makes a fresh copy of the inner tree, so two uses never share state
    public Subtree(string label, System.Func<Node> build) { Label = label; root = build(); }

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

// e.g. the guard's escape, written once and used wherever it is needed
new Subtree("run_away", () => new Sequence(new ActionNode(BreakLineOfSight), new ActionNode(RunToCover)));

GDScript

class Subtree extends BTNode:
    var label: String
    var root: BTNode

    # build makes a fresh copy of the inner tree, so two uses never share state
    func _init(l: String, build: Callable):
        label = l
        root = build.call()

    func tick() -> Status:
        return root.tick()

Unreal C++

class FSubtree : public FNode
{
public:
    FString Label;
    TSharedPtr<FNode> Root;

    // Build makes a fresh copy of the inner tree, so two uses never share state
    FSubtree(FString InLabel, TFunction<TSharedPtr<FNode>()> Build)
        : Label(InLabel), Root(Build()) {}

    EStatus Tick() override { return Root->Tick(); }
};

The Label is not needed to run the tree. It is there so a debugger or a log can say which subtree is running, the way the beetree simulate trace does.

Where it comes from

Halo 2’s AI reused whole behaviors in many places, which made its tree a graph rather than a strict tree. Damian Isla describes it in Handling Complexity in the Halo 2 AI (2005). Colledanchise and Ögren show in Behavior Trees in Robotics and AI (2018) why this modularity is the main strength of behavior trees: every subtree has the same interface as a single node. The BehaviorTree.CPP tutorial Subtrees and port remapping shows the other blackboard design. More reading is on the Resources page.

Next, read how subtrees are written in a tree file in the tree format’s Subtrees section, or open the Build hub and start a tree of your own.