Skip to main content

cranium_core/
errors.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//! Errors and error-handling.
8
9use bevy::ecs::resource::Resource;
10use bevy::platform::prelude::String;
11use bevy::platform::sync::Arc;
12
13#[derive(Debug)]
14pub enum DynResolutionError {
15    UnexpectedType(String),
16    NotInRegistry(String)
17}
18
19pub trait CurveResolverFn: Send + Sync + Fn(&String) -> crate::curves::SupportedUtilityCurve {}
20impl<F: Send + Sync + Fn(&String) -> crate::curves::SupportedUtilityCurve> CurveResolverFn for F {}
21
22/// A config value indicating how the library code should handle Curve keys that 
23/// do not correspond to any known value (dynamically registered or hardcoded). 
24/// 
25/// By default the AI code will panic to avoid either running Actions in unexpected 
26/// and potentially harmful ways or silently skipping bad inputs, but users may 
27/// opt-in into alternative behaviors (skip/default) at their own responsibility.
28#[derive(Default, Clone)]
29pub enum NoCurveMatchStrategy {
30    #[default]
31    SkipActionWithLog,
32    SkipConsiderationWithLog,
33    DefaultCurveWithLog(Arc<dyn CurveResolverFn>),
34    DefaultCurveWithoutLog(Arc<dyn CurveResolverFn>),
35    Panic,
36}
37
38impl NoCurveMatchStrategy {
39    pub const fn panic() -> Self {
40        Self::Panic
41    }
42
43    pub const fn skip_consideration() -> Self {
44        Self::SkipConsiderationWithLog
45    }
46
47    pub const fn skip_action() -> Self {
48        Self::SkipActionWithLog
49    }
50
51    pub fn log_and_default_to<F: Send + Sync + Fn(&String) -> crate::curves::SupportedUtilityCurve + 'static>(
52        curve_fn: F
53    ) -> Self {
54        Self::DefaultCurveWithLog(Arc::new(curve_fn))
55    }
56
57    pub fn quietly_default_to<F: Send + Sync + Fn(&String) -> crate::curves::SupportedUtilityCurve + 'static>(
58        curve_fn: F
59    ) -> Self {
60        Self::DefaultCurveWithoutLog(Arc::new(curve_fn))
61    }
62}
63
64impl core::fmt::Debug for NoCurveMatchStrategy {
65    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
66        match self {
67            Self::Panic => write!(f, "Panic"),
68            Self::SkipConsiderationWithLog => write!(f, "SkipConsiderationWithLog"),
69            Self::SkipActionWithLog => write!(f, "SkipActionWithLog"),
70            Self::DefaultCurveWithLog(_) => write!(f, "DefaultCurveWithLog"),
71            Self::DefaultCurveWithoutLog(_) => write!(f, "DefaultCurveWithoutLog"),
72        }
73    }
74}
75
76/// A Resource that represents app-wide configuration for how to handle bad Curve keys. 
77/// 
78#[derive(Resource, Default)]
79pub struct NoCurveMatchStrategyConfig(pub NoCurveMatchStrategy);
80
81impl NoCurveMatchStrategyConfig {
82    pub fn get_current_value(&self) -> &NoCurveMatchStrategy {
83        return &self.0
84    }
85
86    /// Sets the handler to one of the supported strategies (panic, skip, default, etc.).
87    pub fn set(&mut self, strategy: NoCurveMatchStrategy) -> &mut Self {
88        self.0 = strategy;
89        self
90    }
91
92    /// Configures the app to panic if a Curve key cannot be resolved to a Curve.
93    /// 
94    /// This is the default behavior, so this method is only useful if something 
95    /// else has already modified the default settings.
96    pub fn set_panic(&mut self) -> &mut Self {
97        self.set(NoCurveMatchStrategy::panic())
98    }
99
100    /// Configures the app to ignore the Consideration and log a warning   
101    /// if its associated Curve key cannot be resolved to a Curve.
102    /// 
103    /// **WARNING**: This is generally **NOT** recommended as it is roughly 
104    /// equivalent to returning max score on error, so you may run actions 
105    /// that should not be valid and processing Considerations that should 
106    /// have been optimized away, so it may be a footgun - but you do you.
107    pub fn set_skip_consideration(&mut self) -> &mut Self {
108        self.set(NoCurveMatchStrategy::skip_consideration())
109    }
110
111    /// Configures the app to discard the whole Action and log a warning   
112    /// if any of its Considerations' associated Curve keys cannot be  
113    /// resolved to a Curve.
114    /// 
115    /// This means any buggy Actions effectively get disabled; this means 
116    /// the application can keep on truckin' in case of designer errors, 
117    /// but the AIs may be missing some capabilities. 
118    /// 
119    /// However, this may be desirable if you have multiple versions of 
120    /// an ActionTemplate, each compatible with a different version of your 
121    /// app/modding API/whatever other integration things you are exposing.
122    pub fn set_skip_action(&mut self) -> &mut Self {
123        self.set(NoCurveMatchStrategy::skip_action())
124    }
125
126    /// Configures the app to log a warning if a Curve key cannot be 
127    /// resolves to a Curve and select a fallback Curve using the 
128    /// provided (`'static`!) mapping function instead.
129    /// 
130    /// This allows for graceful recovery in case of AI designer error, 
131    /// but puts the responsibility on the user to specify good fallbacks. 
132    /// 
133    /// Broadly speaking, fallbacks should try to match the expected Curve first on 
134    /// order relation class (increasing/decreasing/peaking, if peaking - how many peaks), 
135    /// then secondarily on 'falloff sharpness similarity' (we could try to define it with derivatives, 
136    /// but you probably get the idea informally - e.g. `MoreThan` > `Exponential` > `Square` > `Linear`). 
137    /// 
138    /// It does not need to be perfect, but the closer the match, the better your chances 
139    /// are that things will still work reasonably well using the fallback.
140    /// 
141    /// If you are happy handling the resolution, this is probably the most robust strategy, 
142    /// giving you both a crash-free experience and a log warning about the fallback used.
143    pub fn set_log_and_use_default<F: CurveResolverFn + 'static>(
144        &mut self, 
145        curve_resolver: F
146    ) -> &mut Self {
147        self.set(NoCurveMatchStrategy::log_and_default_to(curve_resolver))
148    }
149
150    /// Configures the app to select a fallback Curve using the 
151    /// provided (`'static`!) mapping function if a Curve key cannot  
152    /// be resolves to a Curve without logging a warning.
153    /// 
154    /// This allows for graceful recovery in case of AI designer error, 
155    /// but puts the responsibility on the user to specify good fallbacks.
156    /// 
157    /// Broadly speaking, fallbacks should try to match the expected Curve first on 
158    /// order relation class (increasing/decreasing/peaking, if peaking - how many peaks), 
159    /// then secondarily on 'falloff sharpness' (we could try to define it with derivatives, 
160    /// but you probably get the idea - e.g. Exponential is sharper than Square than Linear). 
161    /// 
162    /// It does not need to be perfect, but the closer the match, the better your chances 
163    /// are that things will still work reasonably well using the fallback.
164    /// 
165    /// As you might guess, this is effectively a quiet variant of DefaultCurveWithLog. 
166    /// 
167    /// The primary use-case for this would be if you are using a lot of custom Curves 
168    /// and are very confident in your fallback resolution doing a good job and you want 
169    /// to reduce warning-spam without necessarily filtering out the warnings from the library altogether.
170    pub fn set_silently_use_default<F: CurveResolverFn + 'static>(
171        &mut self, 
172        curve_resolver: F
173    ) -> &mut Self {
174        self.set(NoCurveMatchStrategy::quietly_default_to(curve_resolver))
175    }
176}