leafwing_input_manager/input_processing/single_axis/
custom.rs1use std::any::Any;
2use std::fmt::Debug;
3use std::sync::{LazyLock, RwLock};
4
5use bevy::app::App;
6use bevy::prelude::{FromReflect, Reflect, ReflectDeserialize, ReflectSerialize, TypePath};
7use bevy::reflect::utility::{GenericTypePathCell, NonGenericTypeInfoCell};
8use bevy::reflect::{
9 erased_serde, FromType, GetTypeRegistration, OpaqueInfo, PartialReflect, ReflectFromPtr,
10 ReflectKind, ReflectMut, ReflectOwned, ReflectRef, TypeInfo, TypeRegistration, Typed,
11};
12use dyn_clone::DynClone;
13use dyn_eq::DynEq;
14use dyn_hash::DynHash;
15use serde::{Deserialize, Deserializer, Serialize, Serializer};
16use serde_flexitos::ser::require_erased_serialize_impl;
17use serde_flexitos::{serialize_trait_object, Registry};
18
19use crate::input_processing::AxisProcessor;
20use crate::typetag::{InfallibleMapRegistry, RegisterTypeTag};
21
22pub trait CustomAxisProcessor:
92 Send + Sync + Debug + DynClone + DynEq + DynHash + Reflect + erased_serde::Serialize
93{
94 fn process(&self, input_value: f32) -> f32;
96}
97
98impl<P: CustomAxisProcessor> From<P> for AxisProcessor {
99 fn from(value: P) -> Self {
100 Self::Custom(Box::new(value))
101 }
102}
103
104dyn_clone::clone_trait_object!(CustomAxisProcessor);
105dyn_eq::eq_trait_object!(CustomAxisProcessor);
106dyn_hash::hash_trait_object!(CustomAxisProcessor);
107
108impl PartialReflect for Box<dyn CustomAxisProcessor> {
109 fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
110 Some(Self::type_info())
111 }
112
113 fn reflect_kind(&self) -> ReflectKind {
114 ReflectKind::Opaque
115 }
116
117 fn reflect_ref(&self) -> ReflectRef<'_> {
118 ReflectRef::Opaque(self)
119 }
120
121 fn reflect_mut(&mut self) -> ReflectMut<'_> {
122 ReflectMut::Opaque(self)
123 }
124
125 fn reflect_owned(self: Box<Self>) -> ReflectOwned {
126 ReflectOwned::Opaque(self)
127 }
128
129 fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), bevy::reflect::ApplyError> {
130 if let Some(value) = value.try_downcast_ref::<Self>() {
131 *self = value.clone();
132 Ok(())
133 } else {
134 Err(bevy::reflect::ApplyError::MismatchedTypes {
135 from_type: self
136 .reflect_type_ident()
137 .unwrap_or_default()
138 .to_string()
139 .into_boxed_str(),
140 to_type: self
141 .reflect_type_ident()
142 .unwrap_or_default()
143 .to_string()
144 .into_boxed_str(),
145 })
146 }
147 }
148
149 fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
150 self
151 }
152
153 fn as_partial_reflect(&self) -> &dyn PartialReflect {
154 self
155 }
156
157 fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
158 self
159 }
160
161 fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
162 Ok(self)
163 }
164
165 fn try_as_reflect(&self) -> Option<&dyn Reflect> {
166 Some(self)
167 }
168
169 fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
170 Some(self)
171 }
172}
173
174impl Reflect for Box<dyn CustomAxisProcessor> {
175 fn into_any(self: Box<Self>) -> Box<dyn Any> {
176 self
177 }
178
179 fn as_any(&self) -> &dyn Any {
180 self
181 }
182
183 fn as_any_mut(&mut self) -> &mut dyn Any {
184 self
185 }
186
187 fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
188 self
189 }
190
191 fn as_reflect(&self) -> &dyn Reflect {
192 self
193 }
194
195 fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
196 self
197 }
198
199 fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
200 *self = value.take()?;
201 Ok(())
202 }
203}
204
205impl Typed for Box<dyn CustomAxisProcessor> {
206 fn type_info() -> &'static TypeInfo {
207 static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
208 CELL.get_or_set(|| TypeInfo::Opaque(OpaqueInfo::new::<Self>()))
209 }
210}
211
212impl TypePath for Box<dyn CustomAxisProcessor> {
213 fn type_path() -> &'static str {
214 static CELL: GenericTypePathCell = GenericTypePathCell::new();
215 CELL.get_or_insert::<Self, _>(|| {
216 {
217 format!(
218 "std::boxed::Box<dyn {}::CustomAxisProcessor>",
219 module_path!()
220 )
221 }
222 })
223 }
224
225 fn short_type_path() -> &'static str {
226 static CELL: GenericTypePathCell = GenericTypePathCell::new();
227 CELL.get_or_insert::<Self, _>(|| "Box<dyn CustomAxisProcessor>".to_string())
228 }
229
230 fn type_ident() -> Option<&'static str> {
231 Some("Box<dyn CustomAxisProcessor>")
232 }
233
234 fn crate_name() -> Option<&'static str> {
235 Some(module_path!().split(':').next().unwrap())
236 }
237
238 fn module_path() -> Option<&'static str> {
239 Some(module_path!())
240 }
241}
242
243impl GetTypeRegistration for Box<dyn CustomAxisProcessor> {
244 fn get_type_registration() -> TypeRegistration {
245 let mut registration = TypeRegistration::of::<Self>();
246 registration.insert::<ReflectDeserialize>(FromType::<Self>::from_type());
247 registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
248 registration.insert::<ReflectSerialize>(FromType::<Self>::from_type());
249 registration
250 }
251}
252
253impl FromReflect for Box<dyn CustomAxisProcessor> {
254 fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
255 Some(reflect.try_downcast_ref::<Self>()?.clone())
256 }
257}
258
259impl Serialize for dyn CustomAxisProcessor + '_ {
260 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
261 where
262 S: Serializer,
263 {
264 const fn __check_erased_serialize_super_trait<T: ?Sized + CustomAxisProcessor>() {
267 require_erased_serialize_impl::<T>();
268 }
269 serialize_trait_object(serializer, self.reflect_short_type_path(), self)
270 }
271}
272
273impl<'de> Deserialize<'de> for Box<dyn CustomAxisProcessor> {
274 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
275 where
276 D: Deserializer<'de>,
277 {
278 let registry = PROCESSOR_REGISTRY.read().unwrap();
279 registry.deserialize_trait_object(deserializer)
280 }
281}
282
283static PROCESSOR_REGISTRY: LazyLock<RwLock<InfallibleMapRegistry<dyn CustomAxisProcessor>>> =
285 LazyLock::new(|| RwLock::new(InfallibleMapRegistry::new("CustomAxisProcessor")));
286
287pub trait RegisterCustomAxisProcessorExt {
289 fn register_axis_processor<'de, T>(&mut self) -> &mut Self
291 where
292 T: RegisterTypeTag<'de, dyn CustomAxisProcessor> + GetTypeRegistration;
293}
294
295impl RegisterCustomAxisProcessorExt for App {
296 fn register_axis_processor<'de, T>(&mut self) -> &mut Self
297 where
298 T: RegisterTypeTag<'de, dyn CustomAxisProcessor> + GetTypeRegistration,
299 {
300 let mut registry = PROCESSOR_REGISTRY.write().unwrap();
301 T::register_typetag(&mut registry);
302 self.register_type::<T>();
303 self
304 }
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310 use crate as leafwing_input_manager;
311 use leafwing_input_manager_macros::serde_typetag;
312 use serde_test::{assert_tokens, Token};
313
314 #[test]
315 fn test_custom_axis_processor() {
316 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
317 struct CustomAxisInverted;
318
319 #[serde_typetag]
320 impl CustomAxisProcessor for CustomAxisInverted {
321 fn process(&self, input_value: f32) -> f32 {
322 -input_value
323 }
324 }
325
326 let mut app = App::new();
327 app.register_axis_processor::<CustomAxisInverted>();
328
329 let custom: Box<dyn CustomAxisProcessor> = Box::new(CustomAxisInverted);
330 assert_tokens(
331 &custom,
332 &[
333 Token::Map { len: Some(1) },
334 Token::BorrowedStr("CustomAxisInverted"),
335 Token::UnitStruct {
336 name: "CustomAxisInverted",
337 },
338 Token::MapEnd,
339 ],
340 );
341
342 let processor = AxisProcessor::Custom(custom);
343 assert_eq!(AxisProcessor::from(CustomAxisInverted), processor);
344
345 for value in -300..300 {
346 let value = value as f32 * 0.01;
347
348 assert_eq!(processor.process(value), -value);
349 assert_eq!(CustomAxisInverted.process(value), -value);
350 }
351 }
352}