Skip to main content

cranium_core/
considerations.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
7//! Considerations - registerable Systems that score Actions.
8
9use bevy::platform::prelude::{String, ToOwned};
10
11use bevy::prelude::*;
12use bevy::platform::sync::Arc;
13
14use crate::types::{self, ActionContextRef, AiEntity, CraniumKvMap, CraniumRwLock, PawnEntityRef};
15use crate::identifiers::{ConsiderationIdentifier, CurveIdentifier};
16
17#[cfg(any(feature = "actionset_loader"))]
18use serde::{Serialize, Deserialize};
19
20#[derive(Clone, Debug, Reflect)]
21#[cfg_attr(feature = "actionset_loader", derive(Serialize, Deserialize))]
22pub struct ConsiderationData {
23    #[cfg_attr(any(feature = "actionset_loader"), serde(rename="consideration"))]
24    pub consideration_name: ConsiderationIdentifier,
25
26    #[cfg_attr(any(feature = "actionset_loader"), serde(rename="curve"))]
27    pub curve_name: CurveIdentifier,
28
29    pub min: types::ActionScore,
30    pub max: types::ActionScore,
31}
32
33impl ConsiderationData {
34    pub fn new<CNN: Into<ConsiderationIdentifier>, CRN: Into<CurveIdentifier>>(
35        consideration_name: CNN,
36        curve_name: CRN,
37        min: types::ActionScore,
38        max: types::ActionScore,
39    ) -> Self {
40        Self {
41            consideration_name: consideration_name.into(),
42            curve_name: curve_name.into(),
43            min: min, 
44            max: max, 
45        }
46    }
47}
48
49/// Convenience type-alias for generic inputs piped into each Consideration. 
50/// 
51/// You can use it to simply write `fn your_consideration(params: ConsiderationInputs, your_query:...`
52/// instead of having to memorize the specific interface required by the library.
53/// 
54/// This currently comprises:
55/// - Requesting AI - as Entity
56/// - Requesting AI's Pawn (controlled Entity) - as Entity
57/// - The full Context this Consideration is scoring
58/// 
59/// Changes to this interface will be considered semver-breaking once the core lib stabilizes.
60/// 
61/// Note that Considerations are Plain Old Systems, so you can use `Query`, `Commands`, 
62/// and all the other Bevy goodness to write your Consideration logic - but you must 
63/// also include these inputs as a parameter.
64/// 
65/// The point of those inputs is to let the World inject metadata about the AI query 
66/// into your Considerations so that you can use them in your own logic. 
67/// 
68/// The key Entities in play in particular are included to enable no-fuss fast 
69/// retrieval of data about them in your custom Queries (using `Query::get()`). 
70pub type ConsiderationInputs = bevy::prelude::In<(
71    AiEntity, 
72    PawnEntityRef,
73    ActionContextRef, 
74)>;
75
76/// Convenience type-alias for the output type a Consideration must return.
77pub type ConsiderationOutputs = Option<f32>;
78
79
80/// A specialization of Bevy's `System` trait (or more precisely, `ReadOnlySystem`) 
81/// that can be used as a Cranium Consideration.
82/// 
83/// Note that the associated `In` type only adds the restriction that your custom 
84/// functions must *at least* accept the metadata piped into them; you can add any 
85/// number of Queries, Resource accesses, etc. - as long as they are read-only.
86pub trait ConsiderationSystem: bevy::ecs::system::ReadOnlySystem<
87    In = ConsiderationInputs, 
88    Out = ConsiderationOutputs
89> {}
90
91impl<
92    ROS: bevy::ecs::system::ReadOnlySystem<
93        In = ConsiderationInputs, 
94        Out = ConsiderationOutputs
95    >
96> ConsiderationSystem for ROS {}
97
98
99/// A specialization of Bevy's `IntoSystem` trait that defines any function 
100/// that can be turned into a valid Cranium Consideration System.
101pub trait IntoConsiderationSystem<Marker>: IntoSystem<
102    ConsiderationInputs, 
103    ConsiderationOutputs, 
104    Marker,
105> {}
106
107impl<
108    Marker, 
109    CS: ConsiderationSystem, 
110    IS: IntoSystem<
111        ConsiderationInputs,
112        ConsiderationOutputs, 
113        Marker,
114        System = CS
115    >
116> IntoConsiderationSystem<Marker> for IS {}
117
118
119#[derive(Clone)]
120pub struct ConsiderationMappedToSystem {
121    pub func_name: ConsiderationIdentifier,
122
123    // NOTE: This is Result<T> as the registry lookup is fallible 
124    //       and we will need to propagate these errors later on.
125    // pub consideration_systemid: Result<types::ConsiderationSignature, ()>,
126    pub consideration_system: Result<Arc<CraniumRwLock<dyn ConsiderationSystem>>, ()>,
127    pub curve_name: CurveIdentifier,
128
129    pub min: types::ActionScore,
130    pub max: types::ActionScore,
131}
132
133
134#[derive(Resource, Default)]
135pub struct ConsiderationKeyToSystemMap {
136    pub mapping: CraniumKvMap<
137        ConsiderationIdentifier, 
138        Arc<CraniumRwLock<dyn ConsiderationSystem>>
139    >
140}
141
142
143/// Something that allows us to register a Consideration to the World. 
144/// 
145/// Note that for convenience, the first registration attempt 
146/// will initialize *an empty registry* if one does not exist yet, so
147/// you don't need to use `app.initialize_resource::<UtilityCurveRegistry>()` 
148/// unless you want to be explicit about it.
149pub trait AcceptsConsiderationRegistrations {
150    fn register_consideration<
151        CS: ConsiderationSystem, 
152        Marker, 
153        F: IntoConsiderationSystem<Marker, System = CS> + 'static,
154        IS: Into<String>,
155    >(
156        &mut self, 
157        consideration: F, 
158        key: IS,
159    ) -> &mut Self;
160}
161
162impl AcceptsConsiderationRegistrations for App {
163    fn register_consideration<
164        CS: ConsiderationSystem, 
165        Marker, 
166        F: IntoConsiderationSystem<Marker, System = CS> + 'static,
167        IS: Into<String>,
168    >(
169        &mut self, 
170        consideration: F, 
171        key: IS
172    ) -> &mut Self {
173        self.world_mut().register_consideration(consideration, key);
174        self
175    }
176}
177
178impl AcceptsConsiderationRegistrations for &mut App {
179    fn register_consideration<
180        CS: ConsiderationSystem, 
181        Marker, 
182        F: IntoConsiderationSystem<Marker, System = CS> + 'static,
183        IS: Into<String>,
184    >(
185        &mut self, 
186        consideration: F, 
187        key: IS
188    ) -> &mut Self {
189        self.world_mut().register_consideration(consideration, key);
190        self
191    }
192}
193
194impl AcceptsConsiderationRegistrations for World {
195    fn register_consideration<
196        CS: ConsiderationSystem, 
197        Marker, 
198        F: IntoConsiderationSystem<Marker, System = CS> + 'static,
199        IS: Into<String>,
200    >(
201        &mut self, 
202        consideration: F, 
203        key: IS
204    ) -> &mut Self {
205        let system = F::into_system(consideration);
206        let system_key = ConsiderationIdentifier::from(key);
207        let mut system_registry = self.get_resource_or_init::<ConsiderationKeyToSystemMap>();
208        let old = system_registry.mapping.insert(
209            system_key.to_owned(), 
210            Arc::new(CraniumRwLock::new(
211                system
212            )));
213        match old {
214            None => {},
215            Some(_) => {
216                #[cfg(feature = "logging")]
217                bevy::log::warn!(
218                    "Detected a key collision for key {:?}. Ejecting previous registration...",
219                    system_key
220                );
221            } 
222        }
223        self
224    }
225}
226
227#[derive(Resource, Debug)]
228pub struct ShouldReinitConsiderationQueries(bool);
229
230impl ShouldReinitConsiderationQueries {
231    pub fn get(&self) -> bool {
232        self.0
233    }
234
235    pub fn set(&mut self, val: bool) {
236        self.0 = val;
237    }
238}
239
240impl Default for ShouldReinitConsiderationQueries {
241    fn default() -> Self {
242        Self(true)
243    }
244}
245
246pub fn reinit_consideration_queries(world: &mut World) {
247    let world_cell = world.as_unsafe_world_cell();
248
249    // SAFETY: This is an Exclusive System, so we are the only one with World access.
250    //         We only really need this to bypass a silly borrow-check on the reference.
251    let should_reinit_res = unsafe {
252        world_cell.get_resource::<ShouldReinitConsiderationQueries>()
253    };
254
255    let should_reinit = match should_reinit_res {
256        None => true, 
257        Some(reinit_mark) => reinit_mark.get()
258    };
259
260    if !should_reinit { 
261        return 
262    };
263
264    // SAFETY: This is an Exclusive System, so we are the only one with World access, 
265    //         and we are the only ones with a lock on the initialized System.
266    //         We only really need this to bypass a silly borrow-check on the reference.
267    let registry = unsafe { 
268        world_cell.get_resource_mut::<ConsiderationKeyToSystemMap>() 
269    };
270
271    let mut registry = match registry {
272        None => return,
273        Some(r) => r,
274    };
275
276    registry.mapping.iter_mut().for_each(|(_key, system_lock)| {
277        let write_state = system_lock.write();
278        {
279            match write_state {
280                Ok(mut system) => {
281                    // SAFETY: This is an Exclusive System, so we are the only one with World access, 
282                    //         and we are the only ones with a lock on the initialized System.
283                    //         We only really need this to bypass a silly borrow-check on &muts.
284                    #[cfg(feature = "logging")]
285                    bevy::log::debug!("reinit_consideration_queries: Reinitializing System {:?}", _key);
286                    system.initialize(unsafe { world_cell.world_mut() });
287                },
288                Err(e) => panic!("{:?}", e)
289            }
290        }
291    });
292}
293
294pub struct ConsiderationPlugin;
295
296impl Plugin for ConsiderationPlugin {
297    fn build(&self, app: &mut App) {
298        app
299            // Technically unnecessary, but will give users saner error messages if we pre-initialize:
300            .init_resource::<ShouldReinitConsiderationQueries>()
301            .init_resource::<ConsiderationKeyToSystemMap>()
302            .add_systems(Startup, reinit_consideration_queries)
303            .add_systems(FixedFirst, reinit_consideration_queries)
304            .add_observer(crate::decision_loop::disable_consideration_reinit)
305        ;
306    }
307}