Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

7.4 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    BtPlugin.ts
 * @brief   Ticks BehaviorTreeAgents against the shared runtime + registry.
 *
 * Per-entity blackboard + tree run-state live in a closure Map (the
 * `defineBehavior` pattern); the component stays serializable. Reuses the same
 * `aiRegistry` and `AiContext` as FSM, so a tree's leaves and an FSM's actions
 * are the same named-registry entries. `stepBehaviorTrees` is extracted to
 * unit-test against a fake world. Gated to play mode; runs before nav follow.
 */

import type { App, Plugin } from '../../app/app';
import type { Entity } from '../../types';
import type { World } from '../../ecs/world';
import { defineSystem, Schedule, GetWorld, type SystemTouches } from '../../ecs/system';
import { Res, Time, type TimeData } from '../../ecs/resource';
import { defineResource } from '../../ecs/resource';
import { Commands, type CommandsInstance } from '../../ecs/commands';
import { playModeOnly } from '../../ecs/env';
import type { AnyComponentDef, ComponentData } from '../../ecs/component';
import { Blackboard } from '../fsm/Blackboard';
import { aiRegistry, noInput, type AiContext } from '../fsm/AiContext';
import { Input, type InputState } from '../../input/input';
import { tickBt, createBtRunState, type BtRunState } from './BtRunner';
import { BehaviorTreeAgent, getBt, allBts } from './BehaviorTreeAgent';
import { appRegistryAsset, appRegistryAssets } from '../../asset/registryLookup';
import type { BtNode, BtDefinition } from './types';
import { TouchesBuilder, touchesOfLeaves, type LeafRef } from '../worldView';
import { ensureBuiltinAiRegistrations } from '../builtins';

interface BtAgentState {
    bb: Blackboard;
    rs: BtRunState;
    btKey: string | null;
    status: string;
}

/** The slice of `World` the BT step needs — lets tests inject a fake. */
export interface AiWorldView {
    getEntitiesWithComponents(components: readonly AnyComponentDef[]): readonly Entity[];
    get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;
    set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void;
    has(entity: Entity, component: AnyComponentDef): boolean;
}

type MutableAiContext = { -readonly [K in keyof AiContext]: AiContext[K] };

/** Get (creating if needed) an agent's blackboard — lets game code seed data early. */
export function agentBtBlackboard(states: Map<Entity, BtAgentState>, entity: Entity): Blackboard {
    let st = states.get(entity);
    if (!st) {
        st = { bb: new Blackboard(), rs: createBtRunState(), btKey: null, status: '' };
        states.set(entity, st);
    }
    return st.bb;
}

/** Advance every BehaviorTreeAgent one tick. `states` carries per-entity runtime across frames. */
export function stepBehaviorTrees(
    world: AiWorldView,
    commands: CommandsInstance,
    dt: number,
    states: Map<Entity, BtAgentState>,
    // A `.esbt` asset registers under its resolved path; the agent holds the
    // authored ref, so resolve before lookup (falls back to the raw ref for
    // `registerBt` code names). Optional so tests need no realm.
    resolveTree?: (ref: string) => BtDefinition | undefined,
    input: InputState = noInput(),
): void {
    if (dt <= 0) return;

    const ctx: MutableAiContext = {
        entity: 0 as Entity,
        dt,
        blackboard: null as unknown as Blackboard,
        input,
        world: world as unknown as World,
        commands,
        get: c => world.get(ctx.entity, c),
        set: (c, d) => world.set(ctx.entity, c, d),
        has: c => world.has(ctx.entity, c),
    };

    for (const entity of world.getEntitiesWithComponents([BehaviorTreeAgent])) {
        const agent = world.get(entity, BehaviorTreeAgent);
        if (!agent.bt) continue;
        const def = resolveTree?.(agent.bt) ?? getBt(agent.bt);
        if (!def) continue;

        let st = states.get(entity);
        if (!st) {
            st = { bb: new Blackboard(), rs: createBtRunState(), btKey: null, status: '' };
            states.set(entity, st);
        }
        // A changed tree resets the run-state (Running memory would be stale).
        if (st.btKey !== agent.bt) {
            st.rs = createBtRunState();
            st.btKey = agent.bt;
        }

        ctx.entity = entity;
        ctx.dt = dt;
        ctx.blackboard = st.bb;
        const status = tickBt(def, ctx, st.bb, aiRegistry, st.rs, dt);

        st.status = status;
        if (agent.status !== status) {
            agent.status = status;
            world.set(entity, BehaviorTreeAgent, agent);
        }
    }
}

/** Resource for game code to reach an agent's blackboard / last status. */
export class BehaviorTrees {
    constructor(private states: Map<Entity, BtAgentState>) {}

    blackboard(entity: Entity): Blackboard {
        return agentBtBlackboard(this.states, entity);
    }

    status(entity: Entity): string | null {
        return this.states.get(entity)?.status ?? null;
    }
}

/** Every leaf in a tree, root first. Orphans are not walked — the interpreter
 *  ticks only `root`, so an unwired subtree reaches nothing. */
export function* btLeaves(node: BtNode): Iterable<LeafRef> {
    if (node.name && (node.type === 'action' || node.type === 'condition')) {
        yield { kind: node.type, name: node.name, input: { arg: node.arg, params: node.params } };
    }
    for (const child of node.children ?? []) yield* btLeaves(child);
}

/** What the BT system reaches for: the union over every loaded tree. */
/** The union over the trees THIS app has: its realm's, plus code-registered
 *  ones. Per app, because a schedule is per app. */
export function btTouches(app: App): SystemTouches {
    const builder = new TouchesBuilder().writing(BehaviorTreeAgent._name);
    const loaded = [...appRegistryAssets<BtDefinition>(app, 'behaviortree'), ...allBts()];
    for (const tree of loaded) touchesOfLeaves(aiRegistry, btLeaves(tree.root), builder);
    return builder.build();
}

export const AiBt = defineResource<BehaviorTrees>(null!, 'AiBt');

export class BtPlugin implements Plugin {
    name = 'bt';
    /** Nothing to tick without an agent; state per entity is dropped on despawn. */
    readonly activeWhen = [BehaviorTreeAgent];

    build(app: App): void {
        ensureBuiltinAiRegistrations();
        const states = new Map<Entity, BtAgentState>();
        app.world.onDespawn((entity: Entity) => states.delete(entity));
        app.insertResource(AiBt, new BehaviorTrees(states));

        // This realm's publication first, then a code registration keyed verbatim.
        const resolveTree = (ref: string): BtDefinition | undefined =>
            appRegistryAsset<BtDefinition>(app, 'behaviortree', ref);

        app.addSystemToSchedule(
            Schedule.Update,
            defineSystem(
                [Res(Time), Res(Input), Commands(), GetWorld()],
                (time: TimeData, input: InputState, commands: CommandsInstance, world) => {
                    stepBehaviorTrees(world as AiWorldView, commands, time.delta, states, resolveTree, input);
                },
                // See fsmTouches: the reach is the union over the loaded trees,
                // which is why it is asked for rather than stated.
                { name: 'BehaviorTreeSystem', touches: () => btTouches(app) },
            ),
            { runIf: playModeOnly },
        );
    }
}

export const btPlugin = new BtPlugin();