Files
Bubberstation/code/datums/ai/_ai_behavior.dm
df7832aa43 Replaced our NPC AI with Behavior Trees. (#96628)
This PR replaces our current NPC AI with a [behavior tree
system](https://en.wikipedia.org/wiki/Behavior_tree_(artificial_intelligence,_robotics_and_control)).
Behavior trees are a common way of creating AI in which you place nodes
in a tree structure to define what actions an AI should take.

AI controllers defined a list of /datum/ai_planning_subtree types in
behavior_nodes. Each subtree was a self-contained unit that could call
queue_behavior() to fire off /datum/ai_behavior actions. The controller
iterated subtrees in order, each one deciding independently whether to
queue something and deciding whether the next subtree would run.

This has a few issues:
1. There's no real structure; you are just defining a list of things to
try in order.
2. There was a loooot of subtrees that were basically the same as
another but with some slight modification
3. It was hard to understand.

Controllers now define a single json file describing a tree of nodes.
The tree is composed of structural composites:

Sequence - do A, then B, then C (and so on)
Selector - try A, if it fails try B, then C (and so on)
Parallel - run A and B simultaneously, with configurable failure/success
policies and or looping behavior
Subplan - loop a child continiously

Along that we also have "Decorators". These are nodes that basically
check a condition (E.g.; do we have a combat target). These decorators
can be used to gate behavior and are re-useable across behavior trees.
They also have a concept known as "Observers". Which lets them cancel
lower priority behavior in case their condition changes (Which we check
whenever a signal fires that fits that specific decorator). This makes
the AI much more responsive to change in environment.

For behaviors, we still use the ai_behavior datums. These are the actual
behaviors such as "Move to X", "Attack X". The only major change is that
these can no longer sleep() since they now run in the ai_controller.

Lastly, we now also have subtrees, except now they are essentially
pieces of behavior tree that can be re-used, or even overriden at
runtime or as a variable. Allowing for making modular AI made out of
several smaller trees.

You can set variables on these nodes directly via the extension (see
below), which should reduce the need to make subtypes of behaviors by a
lot. All of these vars are saved on the JSON and will be applied at
runtime.

If you are using subtrees, you can also assign "bindings" to these
variables, which will allow instances of the subtree to override those
variables.

Since a tree structure with variables becomes hard to parse in a JSON,
I've made a VSCode extension to edit these JSONs:

https://marketplace.visualstudio.com/items?itemName=BehaviorTreeG.behaviortreeg
https://github.com/CabinetOnFire/BehaviorTreeG

<img width="1795" height="1268" alt="image"
src="https://github.com/user-attachments/assets/56aa2f0b-3cf9-449f-bca4-8281fca82db6"
/>

This extension allows you to edit the behavior tree JSONs, and browse
through all the behaviors/decorators/subtrees we have

If you'd like more info on how to build these AI check out the
learn_ai.md. I will also make a tutorial to go over more depth on what
the system offers because I kind of suck at doing technical write-ups.

Targetting has been changed to. I've made a new acquire_targets behavior
that takes a target_source (what am I targetting) and
targetting_strategy (what does the candidate need to fulfill to be
considered a target). This allows us to make composites targetting
combinations to reduce the amount of specific find_and_set esque
behaviors we had before. Not everything is ported to this system but
that would be a longer term goal.

I've added a new build_bt script that converts all the behavior tree
JSONs into compiled versions. Why is this needed? Because I wanted to
keep using defines in behavior trees, so we need a way to convert this
into literal values before we send it to DM. This script runs on compile
and should also run in CI (If I didn't fuck that up!). This saves to a
new build/ folder.

I've ported every single AI in the game to this system (except raptors,
Kobsa is working on those so should be in soon!), so I do expect some
bugs to come out of this. But I also fixed some issues that have
probably been in the game for a long time such as:
- Fixed penguins being unable to fish
- Fixed bileworms not being able to devour people
- Fixes goldgrubs not grubbing gold (they could not mine!)
- Lizards actually eat food they find

Either way, I'd reccomend a long TM on this.

1. (Hopefully) a better development experience for making AI
2. Less copy-paste for behaviors, we should be able to re-use more
pieces to make behavior
3. Behavior trees is a more common pattern in making AI, so it should be
easier to find resources to find out how to do things.

🆑 CabinetOnFire, Iamgoofball, SmartKar, Ben10omintrix
refactor: Replaces our AI system with behavior trees, porting all
datum/ai to it
/🆑

I will add this PR with more details down the line. I think I got the
big picture but its a big PR, so sorry if I missed something important.

---------

Co-authored-by: Iamgoofball <iamgoofball@gmail.com>
Co-authored-by: SmArtKar <44720187+SmArtKar@users.noreply.github.com>
Co-authored-by: Ghom <42542238+Ghommie@users.noreply.github.com>
Co-authored-by: Ben10Omintrix <138636438+Ben10Omintrix@users.noreply.github.com>
Co-authored-by: SyncIt21 <110812394+SyncIt21@users.noreply.github.com>
2026-08-15 10:33:57 -06:00

132 lines
5.2 KiB
Plaintext

/// Base type for AI behavior leaf nodes in the behavior tree system.
/// setup() is called once on first activation, perform() each tick while running.
/// Returns BT_SUCCESS / BT_FAILURE on completion, BT_RUNNING while active.
/datum/bt_node/ai_behavior
///Flags for extra behavior (see AI_BEHAVIOR_* defines)
var/behavior_flags = NONE
///Cooldown between perform() calls; do not read directly use get_cooldown()
var/time_between_perform = 0
/// TRUE after setup() has been called and before finish_action() completes.
var/running = FALSE
/// world.time when perform() may next be called.
var/next_perform_time = 0
/// TRUE when the last perform() failed and we are waiting out next_perform_time to say we failed
var/failed_last_perform = FALSE
/// TRUE while an async perform kicked off by start_async() is going
VAR_PRIVATE/async_running = FALSE
/// TRUE once async finished and via finish_async
VAR_PRIVATE/async_finished = FALSE
/// AI_BEHAVIOR_* flags that came out of async perform
VAR_PRIVATE/async_result_flags = NONE
/datum/bt_node/ai_behavior/has_active_descendants()
return running
/datum/bt_node/ai_behavior/get_status_marker()
if(running)
return "*"
return ..()
/datum/bt_node/ai_behavior/append_active_nodes(list/lines, indent)
if(running)
lines += "[indent][span_bold("● [label]")]"
/**
* ai behavior tick. Runs setup() once on first activation, then perform() each tick.
* Respects per-controller cooldowns set by AI_BEHAVIOR_DELAY.
* Returns BT_SUCCESS / BT_FAILURE on completion, BT_RUNNING while active.
*/
/datum/bt_node/ai_behavior/tick(datum/ai_controller/controller, seconds_per_tick)
if(next_perform_time > world.time)
if(!running && failed_last_perform)
return BT_FAILURE
controller.active_execution_index = execution_index
return BT_RUNNING
if(controller.bt_execution_log != null) // dont track if we're not viewing
if(length(controller.bt_execution_log) < BT_EXECUTION_LOG_MAX)
controller.bt_execution_log += execution_index
if(!running)
if(!setup(controller))
EVLOG_TEXT(controller, EVLOG_CATEGORY_AI_BEHAVIORS, "[controller.pawn] [type]: setup() failed")
return BT_FAILURE
EVLOG_TEXT(controller, EVLOG_CATEGORY_AI_BEHAVIORS, "[controller.pawn] starting [type]")
running = TRUE
var/process_flags = perform(seconds_per_tick, controller)
if(process_flags & AI_BEHAVIOR_DELAY)
next_perform_time = world.time + get_cooldown(controller)
if(process_flags & AI_BEHAVIOR_SUCCEEDED)
EVLOG_TEXT(controller, EVLOG_CATEGORY_AI_BEHAVIORS, "[controller.pawn] [type]: succeeded")
failed_last_perform = FALSE
finish_action(controller, TRUE)
return BT_SUCCESS
if(process_flags & AI_BEHAVIOR_FAILED)
EVLOG_TEXT(controller, EVLOG_CATEGORY_AI_BEHAVIORS, "[controller.pawn] [type]: failed")
failed_last_perform = TRUE
finish_action(controller, FALSE)
return BT_FAILURE
controller.active_execution_index = execution_index
return BT_RUNNING
/// Returns the cooldown to apply after a AI_BEHAVIOR_DELAY perform(). Override for conditional delays.
/datum/bt_node/ai_behavior/proc/get_cooldown(datum/ai_controller/cooldown_for)
return time_between_perform
/// Called when this behavior first activates on a controller. Return FALSE to abort (returns BT_FAILURE).
/datum/bt_node/ai_behavior/proc/setup(datum/ai_controller/controller)
return TRUE
/// Called each tick while the behavior is running. Returns AI_BEHAVIOR_* flags.
/datum/bt_node/ai_behavior/proc/perform(seconds_per_tick, datum/ai_controller/controller)
SHOULD_NOT_SLEEP(TRUE)
return
/// Called when the behavior finishes (succeeded or failed). Subtypes should call ..().
/datum/bt_node/ai_behavior/proc/finish_action(datum/ai_controller/controller, succeeded)
SHOULD_CALL_PARENT(TRUE)
running = FALSE
async_running = FALSE
async_finished = FALSE
async_result_flags = NONE
///Checks if we're running async behavior, and if its finished, returns result flags
/datum/bt_node/ai_behavior/proc/handle_async()
if(async_running)
return AI_BEHAVIOR_DELAY
if(async_finished)
return async_result_flags | AI_BEHAVIOR_DELAY
return NONE
///Marks that async behavior has started and runs perform_async
/datum/bt_node/ai_behavior/proc/start_async()
async_running = TRUE
INVOKE_ASYNC(src, PROC_REF(perform_async), owning_controller)
return AI_BEHAVIOR_DELAY
///Override this if you have sleeping behavior, be sure to implement the other async procs in perform()
/datum/bt_node/ai_behavior/proc/perform_async(datum/ai_controller/controller)
return
/// Call from an async behavior after its sleeping call, before committing side effects. FALSE means the behavior was aborted/reset mid-flight bail out without side effects.
/datum/bt_node/ai_behavior/proc/async_still_valid()
return async_running && !QDELETED(owning_controller?.pawn)
/// Call from an async behavior to commit its result. No-op if the behavior was aborted mid-flight.
/datum/bt_node/ai_behavior/proc/finish_async(result_flags)
if(!async_still_valid())
return
async_result_flags = result_flags
async_finished = TRUE
async_running = FALSE
/datum/bt_node/ai_behavior/proc/modify_cooldown(new_next_perform_time)
next_perform_time = new_next_perform_time
/datum/bt_node/ai_behavior/reset_tick_state()
if(running)
finish_action(owning_controller, FALSE)
..()