use bevy::math::{self, curve::CurveExt, Curve, curve::Interval};
use bevy::platform::prelude::{String, ToOwned};
use bevy::platform::sync::Arc;
use crate::types::{ActionScore, CraniumKvMap, MIN_CONSIDERATION_SCORE, MAX_CONSIDERATION_SCORE};
pub use bevy::math::curve::{LinearCurve, QuadraticInCurve, QuadraticInOutCurve, ExponentialInCurve, CubicInCurve};
pub trait UtilityCurve: Curve<ActionScore> + Send + Sync {
fn domain(&self) -> Interval {
Interval::UNIT
}
fn sample_safe(&self, t: ActionScore) -> ActionScore {
let clampin = Interval::UNIT.clamp(t);
let raw = self.sample_unchecked(clampin);
let clampout = raw.clamp(MIN_CONSIDERATION_SCORE, MAX_CONSIDERATION_SCORE);
clampout
}
}
pub trait UtilityCurveExt: UtilityCurve + Sized {
fn average_with<O: UtilityCurve>(self, other: O) -> AverageCurve<Self, O> {
AverageCurve::from((self, other))
}
fn halfway_mirror(self) -> HalfwayMirrorCurve<Self> {
HalfwayMirrorCurve::from(self)
}
fn soft_leak(self, gain: ActionScore) -> SoftLeak<Self> {
SoftLeak::new(self, gain)
}
fn hard_leak(self, gain: ActionScore) -> HardLeak<Self> {
HardLeak::new(self, gain)
}
fn inverse_samples(self) -> UtilityCurveSampler<Self> {
UtilityCurveSampler::new_inverse(self)
}
}
impl<T: UtilityCurve + Sized> UtilityCurveExt for T {}
#[derive(Debug, Clone)]
pub struct UtilityConstantCurve {
val: ActionScore
}
impl UtilityConstantCurve {
pub fn new(value: ActionScore) -> Result<Self, ()> {
match Interval::UNIT.contains(value) {
true => Ok(Self {val: value}),
false => Err(())
}
}
pub fn new_unchecked(value: ActionScore) -> Self {
Self { val: value }
}
pub fn new_clamped(value: ActionScore) -> Self {
Self { val: Interval::UNIT.clamp(value) }
}
pub const fn new_const(value: u8) -> Self {
Self {
val: match value {
0 => 0.,
255 => 1.,
mid => (mid as ActionScore) / 256.
}
}
}
}
impl Curve<ActionScore> for UtilityConstantCurve {
fn domain(&self) -> Interval {
Interval::UNIT
}
fn sample_unchecked(&self, _: f32) -> ActionScore {
self.val
}
}
impl UtilityCurve for UtilityConstantCurve {}
#[derive(Clone)]
pub struct UtilityBinaryCurve;
impl UtilityBinaryCurve {
fn new() -> Self { Self {} }
}
impl math::curve::Curve<ActionScore> for UtilityBinaryCurve {
fn domain(&self) -> Interval {
Interval::UNIT
}
fn sample_unchecked(&self, t: f32) -> ActionScore {
match t >= 1. {
true => 1.,
false => 0.,
}
}
}
impl UtilityCurve for UtilityBinaryCurve {}
#[derive(Clone)]
pub struct HalfwayMirrorCurve<C: UtilityCurve> {
wrapped_curve: math::curve::LinearReparamCurve<
ActionScore,
math::curve::PingPongCurve<ActionScore, C>
>
}
impl<C: UtilityCurve> Curve<ActionScore> for HalfwayMirrorCurve<C> {
fn domain(&self) -> Interval {
self.wrapped_curve.domain()
}
fn sample_unchecked(&self, t: f32) -> ActionScore {
self.wrapped_curve.sample_unchecked(t)
}
}
impl<C: UtilityCurve> HalfwayMirrorCurve<C> {
pub fn try_from_curve(curve: C) -> Result<Self, ()> {
let wrapped = curve
.ping_pong()
.map(|pingponged|
pingponged.reparametrize_linear(Interval::UNIT)
)
;
match wrapped {
Err(_pperr) => Err(()),
Ok(reparam) => match reparam {
Err(_reperr) => Err(()),
Ok(wrapped_curve) => Ok(Self {
wrapped_curve: wrapped_curve
})
}
}
}
}
impl<C: UtilityCurve> From<C> for HalfwayMirrorCurve<C> {
fn from(value: C) -> Self {
Self::try_from_curve(value)
.expect("The source Curve's domain is not a unit interval. This should never happen.")
}
}
impl<C: UtilityCurve> UtilityCurve for HalfwayMirrorCurve<C> {}
pub struct AverageCurve<A: UtilityCurve, B: UtilityCurve> {
a: A,
b: B,
}
impl<A: UtilityCurve, B: UtilityCurve> From<(A, B)> for AverageCurve<A, B> {
fn from(value: (A, B)) -> Self {
Self {
a: value.0,
b: value.1,
}
}
}
impl<A: UtilityCurve, B: UtilityCurve> math::curve::Curve<ActionScore> for AverageCurve<A, B> {
fn domain(&self) -> Interval {
Interval::UNIT
}
fn sample_unchecked(&self, t: f32) -> ActionScore {
(self.a.sample_safe(t) + self.b.sample_safe(t)) / 2.
}
}
impl<A: UtilityCurve, B: UtilityCurve> UtilityCurve for AverageCurve<A, B> {}
#[derive(Clone)]
pub struct SoftLeak<C: UtilityCurve> {
curve: C,
gain: ActionScore,
}
impl<C: UtilityCurve> SoftLeak<C> {
pub fn new(curve: C, gain: ActionScore) -> Self {
Self {
curve: curve,
gain: gain,
}
}
pub const fn new_const_compressor<const GAIN: u8>(curve: C) -> Self {
let gain = (GAIN as f32) / (u8::MAX as f32);
Self {
curve: curve,
gain: gain,
}
}
pub const fn new_const_expander<const GAIN: u8>(curve: C) -> Self {
let gain = (GAIN as f32) / (u8::MAX as f32);
Self {
curve: curve,
gain: -gain,
}
}
}
impl<C: UtilityCurve> Curve<ActionScore> for SoftLeak<C> {
fn domain(&self) -> Interval {
Interval::UNIT
}
fn sample_unchecked(&self, t: f32) -> ActionScore {
self.gain + (1. - self.gain) * self.curve.sample_unchecked(t)
}
}
impl<C: UtilityCurve> UtilityCurve for SoftLeak<C> {}
#[derive(Clone)]
pub struct HardLeak<C: UtilityCurve> {
curve: C,
gain: ActionScore,
}
impl<C: UtilityCurve> HardLeak<C> {
pub fn new(curve: C, gain: ActionScore) -> Self {
Self {
curve: curve,
gain: gain,
}
}
pub const fn new_const_distortion<const GAIN: u8>(curve: C) -> Self {
let gain = (GAIN as f32) / (u8::MAX as f32);
Self {
curve: curve,
gain: gain,
}
}
pub const fn new_const_subtraction<const GAIN: u8>(curve: C) -> Self {
let gain = (GAIN as f32) / (u8::MAX as f32);
Self {
curve: curve,
gain: -gain,
}
}
}
impl<C: UtilityCurve> Curve<ActionScore> for HardLeak<C> {
fn domain(&self) -> Interval {
Interval::UNIT
}
fn sample_unchecked(&self, t: f32) -> ActionScore {
(self.gain + self.curve.sample_unchecked(t)).clamp(
crate::types::MIN_CONSIDERATION_SCORE,
crate::types::MAX_CONSIDERATION_SCORE,
)
}
}
impl<C: UtilityCurve> UtilityCurve for HardLeak<C> {}
pub const NEVER_CURVE: UtilityConstantCurve = UtilityConstantCurve::new_const(0);
pub const ALWAYS_CURVE: UtilityConstantCurve = UtilityConstantCurve::new_const(255);
pub const CONST_QUARTER_CURVE: UtilityConstantCurve = UtilityConstantCurve::new_const(64);
pub const CONST_HALF_CURVE: UtilityConstantCurve = UtilityConstantCurve::new_const(128);
pub const CONST_THREEQUARTER_CURVE: UtilityConstantCurve = UtilityConstantCurve::new_const(192);
impl UtilityCurve for math::curve::CircularInCurve {}
impl UtilityCurve for math::curve::CircularInOutCurve {}
impl UtilityCurve for math::curve::CircularOutCurve {}
impl UtilityCurve for CubicInCurve {}
impl UtilityCurve for math::curve::CubicInOutCurve {}
impl UtilityCurve for math::curve::CubicOutCurve {}
impl UtilityCurve for ExponentialInCurve {}
impl UtilityCurve for math::curve::ExponentialInOutCurve {}
impl UtilityCurve for math::curve::ExponentialOutCurve {}
impl UtilityCurve for LinearCurve {}
impl UtilityCurve for QuadraticInCurve {}
impl UtilityCurve for QuadraticInOutCurve {}
impl UtilityCurve for math::curve::QuadraticOutCurve {}
impl UtilityCurve for math::curve::QuarticInCurve {}
impl UtilityCurve for math::curve::QuarticInOutCurve {}
impl UtilityCurve for math::curve::QuarticOutCurve {}
impl UtilityCurve for math::curve::QuinticInCurve {}
impl UtilityCurve for math::curve::QuinticInOutCurve {}
impl UtilityCurve for math::curve::QuinticOutCurve {}
impl UtilityCurve for math::curve::SineInCurve {}
impl UtilityCurve for math::curve::SineInOutCurve {}
impl UtilityCurve for math::curve::SineOutCurve {}
impl UtilityCurve for math::curve::SmoothStepCurve {}
impl UtilityCurve for math::curve::SmoothStepInCurve {}
impl UtilityCurve for math::curve::SmoothStepOutCurve {}
impl UtilityCurve for math::curve::SmootherStepCurve {}
impl UtilityCurve for math::curve::SmootherStepInCurve {}
impl UtilityCurve for math::curve::SmootherStepOutCurve {}
impl<U: UtilityCurve> UtilityCurve for math::curve::ReverseCurve<ActionScore, U> {}
#[derive(Debug, Clone)]
pub enum CurveSamplerMode {
FORWARD,
INVERSE,
}
#[derive(Debug, Clone)]
pub struct UtilityCurveSampler<U: UtilityCurve> {
curve: U,
mode: CurveSamplerMode,
}
impl<U: UtilityCurve> UtilityCurveSampler<U> {
pub const fn new(curve: U, mode: CurveSamplerMode) -> Self {
Self {
curve: curve,
mode: mode,
}
}
pub const fn new_forward(curve: U) -> Self {
Self {
curve: curve,
mode: CurveSamplerMode::FORWARD,
}
}
pub const fn new_inverse(curve: U) -> Self {
Self {
curve: curve,
mode: CurveSamplerMode::INVERSE,
}
}
}
impl<U: UtilityCurve> Curve<ActionScore> for UtilityCurveSampler<U> {
fn domain(&self) -> Interval {
Interval::UNIT
}
fn sample_unchecked(&self, t: f32) -> ActionScore {
match self.mode {
CurveSamplerMode::FORWARD => self.curve.sample_safe(t),
CurveSamplerMode::INVERSE => 1. - self.curve.sample_safe(t),
}
}
}
impl<U: UtilityCurve> UtilityCurve for UtilityCurveSampler<U> {}
pub const CURVE_CONST_ZERO: UtilityCurveSampler<UtilityConstantCurve> = UtilityCurveSampler::new_forward(UtilityConstantCurve::new_const(0));
pub const CURVE_CONST_MAX: UtilityCurveSampler<UtilityConstantCurve> = UtilityCurveSampler::new_forward(UtilityConstantCurve::new_const(255));
pub const CURVE_CONST_HALF: UtilityCurveSampler<UtilityConstantCurve> = UtilityCurveSampler::new_forward(UtilityConstantCurve::new_const(128));
pub const CURVE_ATLEAST: UtilityCurveSampler<UtilityBinaryCurve> = UtilityCurveSampler::new_forward(UtilityBinaryCurve {});
pub const CURVE_LESSTHAN: UtilityCurveSampler<UtilityBinaryCurve> = UtilityCurveSampler::new_inverse(UtilityBinaryCurve {});
pub const CURVE_LINEAR: UtilityCurveSampler<LinearCurve> = UtilityCurveSampler::new_forward(LinearCurve {});
pub const CURVE_ANTILINEAR: UtilityCurveSampler<LinearCurve> = UtilityCurveSampler::new_inverse(LinearCurve {});
pub const CURVE_SQUARE: UtilityCurveSampler<QuadraticInCurve> = UtilityCurveSampler::new_forward(QuadraticInCurve {});
pub const CURVE_ANTISQUARE: UtilityCurveSampler<QuadraticInCurve> = UtilityCurveSampler::new_inverse(QuadraticInCurve {});
pub const CURVE_EXPONENTIAL: UtilityCurveSampler<ExponentialInCurve> = UtilityCurveSampler::new_forward(ExponentialInCurve {});
pub const CURVE_ANTIEXPONENTIAL: UtilityCurveSampler<ExponentialInCurve> = UtilityCurveSampler::new_inverse(ExponentialInCurve {});
#[derive(Clone)]
pub enum SupportedUtilityCurve {
ConstZero(UtilityCurveSampler<UtilityConstantCurve>),
ConstMax(UtilityCurveSampler<UtilityConstantCurve>),
ConstHalf(UtilityCurveSampler<UtilityConstantCurve>),
AtLeast(UtilityCurveSampler<UtilityBinaryCurve>),
LessThan(UtilityCurveSampler<UtilityBinaryCurve>),
Equals(UtilityCurveSampler<HalfwayMirrorCurve<UtilityBinaryCurve>>),
NotEquals(UtilityCurveSampler<HalfwayMirrorCurve<UtilityBinaryCurve>>),
Linear(UtilityCurveSampler<LinearCurve>),
AntiLinear(UtilityCurveSampler<LinearCurve>),
Linear25pSoftLeak(SoftLeak<UtilityCurveSampler<LinearCurve>>),
AntiLinear25pSoftLeak(SoftLeak<UtilityCurveSampler<LinearCurve>>),
Square(UtilityCurveSampler<QuadraticInCurve>),
AntiSquare(UtilityCurveSampler<QuadraticInCurve>),
ExponentialIn(UtilityCurveSampler<ExponentialInCurve>),
AntiExponentialIn(UtilityCurveSampler<ExponentialInCurve>),
Triangle(UtilityCurveSampler<HalfwayMirrorCurve<LinearCurve>>),
AntiTriangle(UtilityCurveSampler<HalfwayMirrorCurve<LinearCurve>>),
QuadraticQuasiGauss(UtilityCurveSampler<HalfwayMirrorCurve<QuadraticInOutCurve>>),
AntiQuadraticQuasiGauss(UtilityCurveSampler<HalfwayMirrorCurve<QuadraticInOutCurve>>),
Custom(Arc<dyn UtilityCurve>)
}
impl core::fmt::Debug for SupportedUtilityCurve {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::ConstZero(_) => f.debug_tuple("ConstZero").finish(),
Self::ConstMax(_) => f.debug_tuple("ConstMax").finish(),
Self::ConstHalf(_) => f.debug_tuple("ConstHalf").finish(),
Self::AtLeast(_) => f.debug_tuple("AtLeast").finish(),
Self::LessThan(_) => f.debug_tuple("LessThan").finish(),
Self::Equals(_) => f.debug_tuple("Equals").finish(),
Self::NotEquals(_) => f.debug_tuple("NotEquals").finish(),
Self::Linear(_) => f.debug_tuple("Linear").finish(),
Self::AntiLinear(_) => f.debug_tuple("AntiLinear").finish(),
Self::Linear25pSoftLeak(_) => f.debug_tuple("Linear25%SoftLeak").finish(),
Self::AntiLinear25pSoftLeak(_) => f.debug_tuple("AntiLinear25%SoftLeak").finish(),
Self::Square(_) => f.debug_tuple("Square").finish(),
Self::AntiSquare(_) => f.debug_tuple("AntiSquare").finish(),
Self::ExponentialIn(_) => f.debug_tuple("ExponentialIn").finish(),
Self::AntiExponentialIn(_) => f.debug_tuple("AntiExponentialIn").finish(),
Self::Triangle(_) => f.debug_tuple("Triangle").finish(),
Self::AntiTriangle(_) => f.debug_tuple("AntiTriangle").finish(),
Self::QuadraticQuasiGauss(_) => f.debug_tuple("QuadraticQuasiGauss").finish(),
Self::AntiQuadraticQuasiGauss(_) => f.debug_tuple("AntiQuadraticQuasiGauss").finish(),
Self::Custom(_) => f.debug_tuple("Custom").finish(),
}
}
}
impl Curve<ActionScore> for SupportedUtilityCurve {
fn domain(&self) -> Interval {
Interval::UNIT
}
fn sample_unchecked(&self, t: f32) -> ActionScore {
match self {
Self::ConstZero(c) => c.sample_unchecked(t),
Self::ConstMax(c) => c.sample_unchecked(t),
Self::ConstHalf(c) => c.sample_unchecked(t),
Self::AtLeast(c) => c.sample_unchecked(t),
Self::LessThan(c) => c.sample_unchecked(t),
Self::Equals(c) => c.sample_unchecked(t),
Self::NotEquals(c) => c.sample_unchecked(t),
Self::Linear(c) => c.sample_unchecked(t),
Self::AntiLinear(c) => c.sample_unchecked(t),
Self::Linear25pSoftLeak(c) => c.sample_unchecked(t),
Self::AntiLinear25pSoftLeak(c) => c.sample_unchecked(t),
Self::Square(c) => c.sample_unchecked(t),
Self::AntiSquare(c) => c.sample_unchecked(t),
Self::ExponentialIn(c) => c.sample_unchecked(t),
Self::AntiExponentialIn(c) => c.sample_unchecked(t),
Self::Triangle(c) => c.sample_unchecked(t),
Self::AntiTriangle(c) => c.sample_unchecked(t),
Self::QuadraticQuasiGauss(c) => c.sample_unchecked(t),
Self::AntiQuadraticQuasiGauss(c) => c.sample_unchecked(t),
Self::Custom(arc) => arc.sample_safe(t),
}
}
}
impl UtilityCurve for SupportedUtilityCurve {}
impl TryFrom<&str> for SupportedUtilityCurve {
type Error = ();
fn try_from(value: &str) -> Result<Self, Self::Error> {
resolve_curve_from_name(value).ok_or(())
}
}
impl TryFrom<&String> for SupportedUtilityCurve {
type Error = ();
fn try_from(value: &String) -> Result<Self, Self::Error> {
resolve_curve_from_name(value.as_str()).ok_or(())
}
}
pub fn resolve_curve_from_name<S: core::borrow::Borrow<str>>(curve_name: S) -> Option<SupportedUtilityCurve> {
match curve_name.borrow() {
"ConstZero" => Some(SupportedUtilityCurve::ConstZero(CURVE_CONST_ZERO)),
"ConstMax" => Some(SupportedUtilityCurve::ConstMax(CURVE_CONST_MAX)),
"ConstHalf" => Some(SupportedUtilityCurve::ConstHalf(CURVE_CONST_HALF)),
"AtLeast" => Some(SupportedUtilityCurve::AtLeast(CURVE_ATLEAST)),
"LessThan" => Some(SupportedUtilityCurve::AtLeast(CURVE_LESSTHAN)),
"Equals" => Some(SupportedUtilityCurve::Equals(
UtilityCurveSampler::new_forward(UtilityBinaryCurve::new().halfway_mirror())
)),
"NotEquals" => Some(SupportedUtilityCurve::Equals(
UtilityCurveSampler::new_inverse(UtilityBinaryCurve::new().halfway_mirror())
)),
"Linear" => Some(SupportedUtilityCurve::Linear(CURVE_LINEAR)),
"AntiLinear" => Some(SupportedUtilityCurve::AntiLinear(CURVE_ANTILINEAR)),
"Linear25%SoftLeak" => Some(SupportedUtilityCurve::Linear25pSoftLeak(
UtilityCurveSampler::new_forward(LinearCurve {}).soft_leak(0.25)
)),
"AntiLinear25%SoftLeak" => Some(SupportedUtilityCurve::AntiLinear25pSoftLeak(
UtilityCurveSampler::new_inverse(LinearCurve {}).soft_leak(0.25)
)),
"Square" => Some(SupportedUtilityCurve::Square(CURVE_SQUARE)),
"AntiSquare" => Some(SupportedUtilityCurve::AntiSquare(CURVE_ANTISQUARE)),
"ExponentialIn" => Some(SupportedUtilityCurve::ExponentialIn(CURVE_EXPONENTIAL)),
"AntiExponentialIn" => Some(SupportedUtilityCurve::AntiExponentialIn(CURVE_ANTIEXPONENTIAL)),
"Triangle" => Some(SupportedUtilityCurve::Triangle(
UtilityCurveSampler::new_forward((LinearCurve {}).halfway_mirror())
)),
"AntiTriangle" => Some(SupportedUtilityCurve::AntiTriangle(
UtilityCurveSampler::new_inverse((LinearCurve {}).halfway_mirror())
)),
"QuadGauss" => Some(SupportedUtilityCurve::QuadraticQuasiGauss(
UtilityCurveSampler::new_forward((QuadraticInOutCurve {}).halfway_mirror())
)),
"AntiQuadGauss" => Some(SupportedUtilityCurve::QuadraticQuasiGauss(
UtilityCurveSampler::new_inverse((QuadraticInOutCurve {}).halfway_mirror())
)),
_ => None,
}
}
#[derive(bevy::prelude::Resource, Clone, Default)]
pub struct UtilityCurveRegistry {
mapping: CraniumKvMap<String, SupportedUtilityCurve>
}
impl UtilityCurveRegistry {
pub fn get_curve_by_name<S: core::borrow::Borrow<str>>(&self, name: S) -> Option<SupportedUtilityCurve> {
let static_resolve = resolve_curve_from_name(name.borrow());
match static_resolve {
Some(static_curve) => Some(static_curve),
None => self.mapping.get(name.borrow()).cloned()
}
}
pub fn register_curve<C: UtilityCurve + 'static>(
&mut self,
curve: C,
name: String
) -> Result<SupportedUtilityCurve, ()> {
let is_static = resolve_curve_from_name(name.as_str());
match is_static {
Some(_) => Err(()),
None => {
let wrapper = SupportedUtilityCurve::Custom(Arc::new(curve));
self.mapping.insert(name, wrapper.clone());
Ok(wrapper)
}
}
}
}
pub trait AcceptsCurveRegistrations {
fn register_utility_curve<
U: UtilityCurve + 'static,
IS: Into<String>
>(
&mut self,
curve: U,
key: IS,
) -> &mut Self;
}
impl AcceptsCurveRegistrations for bevy::prelude::World {
fn register_utility_curve<
U: UtilityCurve + 'static,
IS: Into<String>
>(
&mut self,
curve: U,
key: IS,
) -> &mut Self {
let mut registry = self.get_resource_or_init::<UtilityCurveRegistry>();
let curve_key = crate::types::UtilityCurveKey::from(key.into());
let old = registry.mapping.insert(
curve_key.to_owned(),
SupportedUtilityCurve::Custom(
Arc::new(curve)
)
);
match old {
None => {},
Some(_) => {
#[cfg(feature = "logging")]
bevy::log::warn!(
"Detected a key collision for key {:?}. Ejecting previous registration...",
curve_key
);
}
};
self
}
}
impl AcceptsCurveRegistrations for bevy::prelude::App {
fn register_utility_curve<
U: UtilityCurve + 'static,
IS: Into<String>
>(
&mut self,
curve: U,
key: IS,
) -> &mut Self {
self.world_mut().register_utility_curve(curve, key);
self
}
}