Skip to main content

cranium_core/
actions.rs

1/* 
2This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. 
3If a copy of the MPL was not distributed with this file, 
4You can obtain one at https://mozilla.org/MPL/2.0/. 
5*/
6//! Actions and ActionTemplates. Action = ActionTemplate + Context (from a ContextFetcher).
7//! 
8//! An Action is the ultimate output of the AI engine - it is largely what it sounds like, 
9//! a generic behavior of some sort, for example moving, attacking, using items, etc., 
10//! possibly taking multiple ticks to conclude (as opposed to a one-off trigger only).
11//! 
12//! The first caveat is that Actions are independent of their implementation - AI code cares 
13//! not about how you implement your movement or combat systems, an Action is merely a request 
14//! to run some code that will implement it properly (with hooks to signal when it's done running).
15//! 
16//! The second caveat is that we are not necessarily only talking about individual NPCs!
17//!  
18//! A single AI can be the 'brain' of a single NPC, but we can also have 'Commander' AIs 
19//! driving whole teams or crowds, 'Director' AIs whose target (Pawn) is 'the game world'
20//! (e.g. running spawners, or coordinating other AIs goals to drive story progression), 
21//! and conversely, a single NPC or Faction can be run by multiple AIs working together.
22//! 
23//! An Action is composed of two parts: an ActionTemplate and an ActionContext. 
24//! 
25//! You can think of that as 'function' and 'parameters', more or less - the 
26//! Template represents a capability, e.g. the ability to pick up items, while the 
27//! Context represents what we're doing it *to* (e.g. which item to pick up). 
28//! 
29//! An Action will usually have multiple possible available Contexts to choose from. 
30//! 
31//! This is the core problem AI solves - given all ActionTemplates and all Contexts 
32//! available for them at a given moment, which combination to choose for execution?
33use bevy::prelude::*;
34
35#[cfg(any(feature = "actionset_loader"))]
36use serde::{Serialize, Deserialize};
37
38use crate::considerations::ConsiderationData;
39use crate::types::{self, ActionContextRef, CraniumList, CraniumKvMap};
40use crate::identifiers::{ContextFetcherIdentifier};
41
42pub type ActionContext = Entity;
43pub type ActionKey = String;
44
45/// An Action is effectively an ActionTemplate + a selected ActionContext. 
46#[derive(Clone, Reflect, Debug)]
47pub struct Action {
48    pub name: String,
49    pub context: ActionContextRef,
50    pub action_key: ActionKey,
51}
52
53#[derive(Clone, Reflect, Debug)]
54pub struct ScoredAction {
55    /// 
56    pub action: Action,
57    pub score: types::ActionScore,
58}
59
60
61/// An ActionTemplate is a 'partial' Action (in the sense of a partial function).
62/// It represents an abstract activity an AI may undertake without a specific target.
63/// 
64/// For example, OpenDoor is an ActionTemplate - it becomes an Action when we specify 
65/// WHICH door to open, which we'll refer to by the quasi-generic syntax `OpenDoor<SomeDoor>`. 
66/// 
67/// The square-bracketed value(s) are what the library calls an ActionContext.
68/// 
69/// In total, an ActionTemplate is: 
70/// 1) a String key identifying the Action executor e.g. 'OpenDoorHandler'.
71/// 2) a String key identifying a System that returns possible Contexts (e.g. 'GetAdjacentDoors').
72/// 3) a sequence of Consideration System String keys that will be used to score all of these (e.g. ['DistanceToPawn']).
73/// 4) a Priority multiplier for the final score to make certain activities intrinsically higher priority (e.g. 1.5).
74#[derive(Debug, Clone, Reflect)]
75#[cfg_attr(any(feature = "actionset_loader"), derive(Serialize, Deserialize))]
76pub struct ActionTemplate {
77    // 
78    // name = identifier. Two ActionTemplates may share the same function (as an implementation detail), 
79    //                    but represent very different logical activities. This helps AI designers not go mad.
80
81    /// Human-readable identifier of the Action; as a general rule, should be 
82    pub name: String, 
83
84    /// 
85    #[cfg_attr(any(feature = "actionset_loader"), serde(rename="context_fetcher"))]
86    pub context_fetcher_name: ContextFetcherIdentifier,
87    pub considerations: CraniumList<ConsiderationData>,
88    pub priority: types::ActionScore,
89    pub action_key: ActionKey,
90    // AI LODs: 
91    pub lod_min: Option<types::AiLodLevelPrimitive>,
92    pub lod_max: Option<types::AiLodLevelPrimitive>,
93}
94
95impl ActionTemplate {
96    pub fn new<
97        INS: Into<String>,
98        CFN: Into<ContextFetcherIdentifier>,
99        IAK: Into<String>,
100    >(
101        name: INS,
102        context_fetcher_name: CFN,
103        considerations: CraniumList<ConsiderationData>,
104        priority: types::ActionScore, 
105        action_key: IAK, 
106        lod_min: Option<types::AiLodLevelPrimitive>,
107        lod_max: Option<types::AiLodLevelPrimitive>,
108    ) -> Self {
109        Self {
110            name: name.into(),
111            context_fetcher_name: context_fetcher_name.into(),
112            considerations: considerations,
113            priority: priority,
114            action_key: action_key.into(),
115            lod_min: lod_min,
116            lod_max: lod_max,
117        }
118    }
119
120    /// Checks if this template should be processed at a given LOD.
121    pub fn is_within_lod_range(&self, lod: &Option<crate::lods::AILevelOfDetailValue>) -> bool {
122        let qry_lod = lod.map(|lv| lv.to_primitive()).unwrap_or(crate::lods::LOD_NORMAL);
123        let min = self.lod_min.unwrap_or(crate::lods::LOD_NORMAL);
124        let max = self.lod_max.unwrap_or(crate::lods::LOD_MINIMAL);
125        qry_lod >= min && qry_lod <= max
126    }
127}
128
129impl core::hash::Hash for ActionTemplate {
130    /// ActionTemplates are equal if their Name and ActionKey are equal.
131    /// Both are hashable, so we'll use them for hash keys as well.
132    /// 
133    /// Note that you may need to look up the canonical values of other fields from an Asset or w/e.
134    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
135        self.name.hash(state);
136        self.action_key.hash(state);
137    }
138}
139
140impl PartialEq for ActionTemplate {
141    /// ActionTemplates are equal if their Name and ActionKey are equal.
142    /// Really we only need Names mostly, the ActionKey is just a safeguard on accidental clashes.
143    fn eq(&self, other: &Self) -> bool {
144        self.name == other.name && self.action_key == other.action_key
145    }
146}
147
148impl Eq for ActionTemplate {}
149
150/// Convenience type-alias for the input type required from an ActionHandler. 
151pub type ActionHandlerInputs = (
152    types::AiEntity,
153    types::PawnEntityRef,
154    types::ActionContextRef,
155);
156
157/// Convenience type-alias for the output type required from an ActionHandler. 
158pub type ActionHandlerOutputs = ();
159
160/// Convenience type-alias for register-able ActionHandlers
161pub type ActionHandlerFn = dyn Send + Sync + FnMut(ActionHandlerInputs, Commands) -> ();
162
163/// A 'guardrail' trait for Events that trigger your Action logic. 
164/// 
165/// This trait is not used as an actual bound in any Cranium code; 
166/// the point of it is to give you an interface which, once implemented, 
167/// will ensure you've got the basics covered for working with Actions 
168/// and a solid base for building simple ActionHandler functions quickly.
169pub trait ActionTriggerEvent: Event {
170    /// The event should be buildable from just the standardized inputs.
171    fn build_from_action_handler_inputs(inputs: ActionHandlerInputs) -> Self;
172
173    /// The event should be buildable and triggerable in an ActionHandler function. 
174    /// 
175    /// The simplest impl is `commands.trigger(Self::build_from_action_handler_inputs(inputs))`, 
176    /// but there's some extra bounds on Triggers that made it impossible to provide out of the box. 
177    fn trigger_from_action_handler(inputs: ActionHandlerInputs, commands: Commands);
178}
179
180/// A thin wrapper over an ActionHandler function.
181pub struct ActionPickCallback(Box<ActionHandlerFn>);
182
183impl ActionPickCallback {
184    pub fn new<F: Send + Sync + FnMut(ActionHandlerInputs, Commands) -> () + 'static>(func: F) -> Self {
185        Self(Box::new(func))
186    }
187
188    pub fn call(&mut self, inputs: ActionHandlerInputs, commands: Commands) {
189        self.0(inputs, commands)
190    }
191}
192
193impl<F: 'static + Send + Sync + FnMut(ActionHandlerInputs, Commands)> From<F> for ActionPickCallback {
194    fn from(value: F) -> Self {
195        Self::new(value)
196    }
197}
198
199#[derive(Default, Resource)]
200pub struct ActionHandlerKeyToSystemMap {
201    pub mapping: CraniumKvMap<
202        types::ActionKey, 
203        ActionPickCallback,
204    >
205}
206
207
208/// Something that allows us to register a ActionHandler to the World. 
209/// 
210/// Note that for convenience, the first registration attempt 
211/// will initialize *an empty registry* if one does not exist yet, so
212/// you don't need to use `app.initialize_resource::<UtilityCurveRegistry>()` 
213/// unless you want to be explicit about it.
214pub trait AcceptsActionHandlerRegistrations {
215    fn register_action_handler<
216        ITF: Into<ActionPickCallback>, 
217        IS: Into<String>,
218    >(
219        &mut self, 
220        trigger_fn: ITF, 
221        key: IS,
222    ) -> &mut Self;
223}
224
225impl AcceptsActionHandlerRegistrations for App {
226    fn register_action_handler<
227        ITF: Into<ActionPickCallback>, 
228        IS: Into<String>,
229    >(
230        &mut self, 
231        trigger_fn: ITF, 
232        key: IS,
233    ) -> &mut Self{
234        self.world_mut().register_action_handler(trigger_fn, key);
235        self
236    }
237}
238
239impl AcceptsActionHandlerRegistrations for World {
240    fn register_action_handler<
241        ITF: Into<ActionPickCallback>, 
242        IS: Into<String>,
243    >(
244        &mut self, 
245        trigger_fn: ITF, 
246        key: IS,
247    ) -> &mut Self {
248        let system_key: ActionKey = key.into();
249        let callback = trigger_fn.into();
250        let cell = self.as_unsafe_world_cell();
251
252        let mut system_registry = match unsafe { cell.world_mut() }.get_non_send_resource_mut::<ActionHandlerKeyToSystemMap>() {
253            Some(registry) => registry,
254            None => {
255                unsafe { cell.world_mut() }.init_resource::<ActionHandlerKeyToSystemMap>();
256                unsafe { cell.world_mut() }.get_resource_mut::<ActionHandlerKeyToSystemMap>().unwrap()
257            }
258        };
259
260        let old = system_registry.mapping.insert(
261            system_key.to_owned(), 
262            callback
263        );
264        match old {
265            None => {},
266            Some(_) => {
267                #[cfg(feature = "logging")]
268                bevy::log::warn!(
269                    "Detected a key collision for key {:?}. Ejecting previous registration...",
270                    system_key
271                );
272            } 
273        }
274        self
275    }
276}
277
278pub struct ActionHandlerPlugin;
279
280impl Plugin for ActionHandlerPlugin {
281    fn build(&self, app: &mut App) {
282        app
283            // Technically unnecessary, but will give users saner error messages if we pre-initialize:
284            .init_resource::<ActionHandlerKeyToSystemMap>()
285        ;
286    }
287}