bevy_proto_backend/schematics/schematic.rs
1use bevy::prelude::{FromReflect, Reflect};
2use bevy::reflect::{GetTypeRegistration, Typed};
3
4use crate::deps::DependenciesBuilder;
5use crate::schematics::SchematicContext;
6
7/// Trait used to create a [prototype] schematic for modifying an [entity]
8/// (or the [world] in general).
9///
10/// This trait can either be manually implemented or [derived].
11///
12/// See the [module-level documentation] for details.
13///
14/// # Example
15///
16/// ```
17/// use bevy::prelude::{Component, Reflect};
18/// use bevy_proto_backend::schematics::{Schematic, SchematicContext};
19/// #[derive(Component, Reflect)]
20/// struct PlayerId(usize);
21///
22/// impl Schematic for PlayerId {
23/// type Input = Self;
24///
25/// fn apply(input: &Self::Input, context: &mut SchematicContext) {
26/// entity.insert(Self(input.0));
27/// }
28///
29/// fn remove(input: &Self::Input, context: &mut SchematicContext) {
30/// entity.remove::<Self>();
31/// }
32/// }
33/// ```
34///
35/// [prototype]: crate::proto::Prototypical
36/// [entity]: bevy::ecs::world::EntityMut
37/// [world]: bevy::ecs::world::World
38/// [derived]: bevy_proto_derive::Schematic
39/// [module-level documentation]: crate::schematics
40pub trait Schematic: Reflect + Typed {
41 /// The input type to this schematic.
42 ///
43 /// This acts as an intermediate between serialized schematic information
44 /// and the actual schematic instance.
45 ///
46 /// For types that don't need an intermediate type, this can just be
47 /// set to `Self`.
48 type Input: FromReflect + GetTypeRegistration;
49
50 /// Controls how this schematic is applied to the given entity.
51 fn apply(input: &Self::Input, context: &mut SchematicContext);
52 /// Controls how this schematic is removed from the given entity.
53 fn remove(input: &Self::Input, context: &mut SchematicContext);
54
55 /// Allows dependency assets to be loaded when this schematic is loaded.
56 #[allow(unused_variables)]
57 fn preload_dependencies(input: &mut Self::Input, dependencies: &mut DependenciesBuilder) {}
58}
59
60/// A custom [`From`]-like trait used to convert the [input] of a [schematic]
61/// to itself.
62///
63/// This is used by [derive macro] to automatically handle the conversion.
64///
65/// This trait is has a blanket implementation for any type where the input
66/// type satisfies [`Into`] for the schematic type.
67///
68/// [input]: Schematic::Input
69/// [schematic]: Schematic
70/// [derive macro]: bevy_proto_derive::Schematic
71pub trait FromSchematicInput<T> {
72 fn from_input(input: T, context: &mut SchematicContext) -> Self;
73}
74
75impl<S, T: Into<S>> FromSchematicInput<T> for S {
76 fn from_input(input: T, _context: &mut SchematicContext) -> S {
77 input.into()
78 }
79}