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