Files
Bubberstation/code/datums/ai/bots/bot_subtrees.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

282 lines
12 KiB
Plaintext

#define BOT_NO_BEACON_PATH_PENALTY 30 SECONDS
/**
* Searches for a valid target in oview and sets a blackboard key when found.
* Subtypes override valid_target() to refine selection criteria.
* looking_for is an optional typecache pre-filter; pass null to check all atoms via valid_target().
*/
/datum/bt_node/ai_behavior/bot_search
var/target_key
var/looking_for = null
var/radius = 5
var/pathing_distance = 10
var/bypass_add_blacklist = FALSE
var/turf_search = FALSE
/// How close the path must get to the target (0 = onto/adjacent). Repairbot raises this so it stops next to the walls/girders it repairs.
var/minimum_distance = 0
time_between_perform = 2 SECONDS
/// Stashed candidate list between perform() and the async worker (not a blackboard value).
VAR_PRIVATE/list/candidate_stash
/datum/bt_node/ai_behavior/bot_search/perform(seconds_per_tick, datum/ai_controller/basic_controller/bot/controller)
if(!istype(controller))
stack_trace("attempted to give [controller.pawn] the bot search behavior!")
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
var/async_flags = handle_async()
if(async_flags)
return async_flags
if(isnull(looking_for))
looking_for = get_looking_for_typecache()
// Build candidate list synchronously (no sleeping), then hand off to async.
var/mob/living/living_pawn = controller.pawn
var/list/ignore_list = controller.blackboard[BB_TEMPORARY_IGNORE_LIST]
var/list/candidates = list()
for(var/atom/potential_target as anything in (turf_search ? RANGE_TURFS(radius, controller.pawn) : oview(radius, controller.pawn)))
if(!isnull(looking_for) && !is_type_in_typecache(potential_target, looking_for))
continue
if(LAZYACCESS(ignore_list, potential_target))
continue
if(!valid_target(controller, potential_target))
continue
if(!can_see(controller.pawn, potential_target, radius))
continue
candidates += potential_target
if(!length(candidates))
EVLOG_TEXT(controller, EVLOG_CATEGORY_AI_BEHAVIORS, "[living_pawn] bot_search ([type]): no valid target found in radius [radius]")
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
candidate_stash = candidates
return start_async()
/datum/bt_node/ai_behavior/bot_search/perform_async(datum/ai_controller/basic_controller/bot/controller)
var/mob/living/living_pawn = controller.pawn
var/found = FALSE
for(var/atom/potential_target as anything in candidate_stash)
if(!async_still_valid())
break
if(controller.set_if_can_reach(key = target_key, target = potential_target, distance = pathing_distance, bypass_add_to_blacklist = bypass_add_blacklist, minimum_distance = minimum_distance))
found = TRUE
break
if(!async_still_valid())
return
if(!found)
EVLOG_TEXT(controller, EVLOG_CATEGORY_AI_BEHAVIORS, "[living_pawn] bot_search ([type]): no reachable target found")
finish_async(found ? AI_BEHAVIOR_SUCCEEDED : AI_BEHAVIOR_FAILED)
/datum/bt_node/ai_behavior/bot_search/finish_action(datum/ai_controller/controller, succeeded)
. = ..()
candidate_stash = null
/datum/bt_node/ai_behavior/bot_search/proc/get_looking_for_typecache()
return
/datum/bt_node/ai_behavior/bot_search/proc/valid_target(datum/ai_controller/basic_controller/bot/controller, atom/my_target)
return TRUE
///Performs bot speech from a list of options
/datum/bt_node/ai_behavior/bot_speech
var/list/list_to_pick_from
var/announce_key
time_between_perform = 5 SECONDS
/datum/bt_node/ai_behavior/bot_speech/perform(seconds_per_tick, datum/ai_controller/controller)
var/datum/action/cooldown/bot_announcement/announcement = controller.blackboard[announce_key]
if(isnull(announcement) || !length(list_to_pick_from))
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
announcement.announce(pick(list_to_pick_from))
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_SUCCEEDED
///Interact with an object. Could probably be moved to a generic behavior as the only unique thing is the blacklist.
/datum/bt_node/ai_behavior/bot_interact
var/target_key
var/clear_target = TRUE
/datum/bt_node/ai_behavior/bot_interact/perform(seconds_per_tick, datum/ai_controller/controller)
var/mob/living/basic/living_pawn = controller.pawn
var/atom/target = controller.blackboard[target_key]
if(QDELETED(target))
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
if(get_dist(living_pawn, target) > 1)
return AI_BEHAVIOR_INSTANT
living_pawn.UnarmedAttack(target, proximity_flag = TRUE)
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_SUCCEEDED
/datum/bt_node/ai_behavior/bot_interact/finish_action(datum/ai_controller/basic_controller/bot/controller, succeeded)
. = ..()
var/atom/target = controller.blackboard[target_key]
if(clear_target)
controller.clear_blackboard_key(target_key)
if(!succeeded && !isnull(target))
controller.add_to_blacklist(target)
/// Variant that keeps the target key after interacting (caller must clear it).
/datum/bt_node/ai_behavior/bot_interact/keep_target
clear_target = FALSE
/// Searches GLOB.deliverybeacons for a beacon whose location matches the tag in tag_key, and sets it as target_key.
/datum/bt_node/ai_behavior/find_delivery_beacon
var/target_key
/// Blackboard key holding the location tag string to match against beacon.location.
var/tag_key
time_between_perform = 2 SECONDS
/datum/bt_node/ai_behavior/find_delivery_beacon/perform(seconds_per_tick, datum/ai_controller/controller)
var/beacon_tag = controller.blackboard[tag_key]
if(isnull(beacon_tag))
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
for(var/obj/machinery/navbeacon/beacon as anything in GLOB.deliverybeacons)
if(beacon.location != beacon_tag)
continue
controller.set_blackboard_key(target_key, beacon)
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_SUCCEEDED
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
///Find the closest beacon and set it as the target
/datum/bt_node/ai_behavior/find_first_beacon_target
var/target_key
/datum/bt_node/ai_behavior/find_first_beacon_target/perform(seconds_per_tick, datum/ai_controller/controller)
var/closest_distance = INFINITY
var/mob/living/basic/bot/bot_pawn = controller.pawn
var/atom/final_target
var/atom/previous_target = controller.blackboard[BB_PREVIOUS_BEACON_TARGET]
for(var/obj/machinery/navbeacon/beacon as anything in GLOB.navbeacons["[bot_pawn.z]"])
var/dist = get_dist(bot_pawn, beacon)
if(beacon == previous_target || dist <= 1)
continue
if(dist > closest_distance)
continue
closest_distance = dist
final_target = beacon
if(isnull(final_target))
EVLOG_TEXT(controller, EVLOG_CATEGORY_AI_BEHAVIORS, "[bot_pawn] find_first_beacon_target: no beacon found on z=[bot_pawn.z] (previous=[previous_target])")
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
EVLOG_MAPTEXT(controller, EVLOG_CATEGORY_AI_BEHAVIORS, "[bot_pawn] first beacon target: [final_target]", get_turf(final_target), "Beacon")
EVLOG_LINES(controller, EVLOG_CATEGORY_AI_BEHAVIORS, "Beacon path", get_turf(bot_pawn), get_turf(final_target))
controller.set_blackboard_key(target_key, final_target)
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_SUCCEEDED
///Find the next beacon from a previous target and set it as the new target
/datum/bt_node/ai_behavior/find_next_beacon_target
var/target_key
time_between_perform = 5 SECONDS
/datum/bt_node/ai_behavior/find_next_beacon_target/perform(seconds_per_tick, datum/ai_controller/basic_controller/bot/controller)
var/mob/living/basic/bot/bot_pawn = controller.pawn
var/obj/machinery/navbeacon/prev_beacon = controller.blackboard[BB_PREVIOUS_BEACON_TARGET]
if(QDELETED(prev_beacon))
EVLOG_TEXT(controller, EVLOG_CATEGORY_AI_BEHAVIORS, "[bot_pawn] find_next_beacon_target: previous beacon is deleted")
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
var/atom/final_target
for(var/obj/machinery/navbeacon/beacon as anything in GLOB.navbeacons["[bot_pawn.z]"])
if(beacon.location == prev_beacon.codes[NAVBEACON_PATROL_NEXT])
final_target = beacon
break
if(isnull(final_target))
EVLOG_TEXT(controller, EVLOG_CATEGORY_AI_BEHAVIORS, "[bot_pawn] find_next_beacon_target: no beacon with location=[prev_beacon.codes[NAVBEACON_PATROL_NEXT]] (prev=[prev_beacon])")
controller.clear_blackboard_key(BB_PREVIOUS_BEACON_TARGET)
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
controller.set_blackboard_key(BB_PREVIOUS_BEACON_TARGET, final_target)
controller.set_blackboard_key(target_key, final_target)
return AI_BEHAVIOR_SUCCEEDED
/datum/bt_node/ai_behavior/find_next_beacon_target/finish_action(datum/ai_controller/controller, succeeded)
. = ..()
/// Records the beacon as visited and clears the target key once the bot is on the same turf.
/datum/bt_node/ai_behavior/arrive_at_beacon
var/target_key
/datum/bt_node/ai_behavior/arrive_at_beacon/perform(seconds_per_tick, datum/ai_controller/basic_controller/bot/controller)
var/obj/machinery/navbeacon/beacon = controller.blackboard[target_key]
if(QDELETED(beacon))
return AI_BEHAVIOR_INSTANT | AI_BEHAVIOR_FAILED
if(get_dist(controller.pawn, beacon) > 0)
return AI_BEHAVIOR_INSTANT
controller.set_blackboard_key(BB_PREVIOUS_BEACON_TARGET, beacon)
controller.clear_blackboard_key(target_key)
return AI_BEHAVIOR_INSTANT | AI_BEHAVIOR_SUCCEEDED
/// Completes summon travel once the bot reaches the summon target's turf.
/datum/bt_node/ai_behavior/complete_summon_travel
var/target_key
/datum/bt_node/ai_behavior/complete_summon_travel/perform(seconds_per_tick, datum/ai_controller/controller)
var/mob/living/basic/bot/bot_pawn = controller.pawn
if(QDELETED(bot_pawn))
return AI_BEHAVIOR_INSTANT | AI_BEHAVIOR_FAILED
var/atom/target = controller.blackboard[target_key]
if(get_dist(bot_pawn, target) > 0)
return AI_BEHAVIOR_INSTANT
bot_pawn.calling_ai_ref = null
bot_pawn.update_bot_mode(new_mode = BOT_IDLE)
controller.clear_blackboard_key(target_key)
return AI_BEHAVIOR_INSTANT | AI_BEHAVIOR_SUCCEEDED
///Find a valid authority to salute and set them as the target
/datum/bt_node/ai_behavior/find_valid_authority
var/target_key
/datum/bt_node/ai_behavior/find_valid_authority/perform(seconds_per_tick, datum/ai_controller/controller)
for(var/mob/living/nearby_mob in oview(7, controller.pawn))
if(!HAS_TRAIT(nearby_mob, TRAIT_COMMISSIONED))
continue
controller.set_blackboard_key(target_key, nearby_mob)
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_SUCCEEDED
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
///Salute the authority /(o.o)
/datum/bt_node/ai_behavior/salute_authority
var/target_key
var/salute_keys
/datum/bt_node/ai_behavior/salute_authority/perform(seconds_per_tick, datum/ai_controller/controller)
if(!controller.blackboard_key_exists(target_key))
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
var/list/salute_list = controller.blackboard[salute_keys]
if(!length(salute_list))
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_FAILED
var/mob/living/basic/bot/bot_pawn = controller.pawn
var/obj/item/our_hat = (locate(/obj/item/clothing/head) in bot_pawn)
if(our_hat)
salute_list += "tips [our_hat] at "
bot_pawn.manual_emote(pick(salute_list) + " [controller.blackboard[target_key]]!")
return AI_BEHAVIOR_DELAY | AI_BEHAVIOR_SUCCEEDED
/datum/bt_node/ai_behavior/salute_authority/finish_action(datum/ai_controller/controller, succeeded)
. = ..()
controller.clear_blackboard_key(target_key)
/// Travel to BB_BOT_SUMMON_TARGET if set, completing when on the same turf.
/datum/bt_node/subtree/bot_respond_to_summon
behavior_tree_json = "code/datums/ai/bots/bot_respond_to_summon.bt.json"
/// Salute any commissioned officer in range
/datum/bt_node/subtree/bot_salute_authority
behavior_tree_json = "code/datums/ai/bots/bot_salute_authority.bt.json"
/**
* Patrol to navbeacons in sequence when autopatrol is enabled and not on cooldown.
* Priority: travel to current target -> find next in chain -> find first (nearest) beacon.
*/
/datum/bt_node/subtree/bot_patrol
behavior_tree_json = "code/datums/ai/bots/bot_patrol.bt.json"
#undef BOT_NO_BEACON_PATH_PENALTY