1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
//! Provides the core abstractions [`Prototypical`] and [`Prototype`] for implementing prototypical structs.
use std::fmt::Formatter;
use std::iter::Rev;
use std::slice::Iter;

use bevy::ecs::prelude::Commands;
use bevy::ecs::system::EntityCommands;
use bevy::prelude::{AssetServer, Res};
use indexmap::IndexSet;
use serde::{
    de::{self, Error, SeqAccess, Visitor},
    Deserialize, Deserializer, Serialize,
};

use crate::{
    components::ProtoComponent, data::ProtoCommands, data::ProtoData, utils::handle_cycle,
};

/// Allows access to a prototype's name and components so that it can be spawned in
pub trait Prototypical: 'static + Send + Sync {
    /// The name of the prototype
    ///
    /// This should be unique amongst all prototypes in the world
    fn name(&self) -> &str;

    /// The names of the parent templates (if any).
    fn templates(&self) -> &[String] {
        &[]
    }

    /// The names of the parent templates (if any) in reverse order.
    fn templates_rev(&self) -> Rev<Iter<'_, String>> {
        self.templates().iter().rev()
    }

    /// Returns an iterator of [`ProtoComponent`] trait objects.
    fn iter_components(&self) -> Iter<'_, Box<dyn ProtoComponent>>;

    /// Creates [`ProtoCommands`] used to modify the given entity.
    ///
    /// # Arguments
    ///
    /// * `entity`: The entity commands
    /// * `data`: The prototype data in this world
    ///
    fn create_commands<'w, 's, 'a, 'p>(
        &'p self,
        entity: EntityCommands<'w, 's, 'a>,
        data: &'p Res<ProtoData>,
    ) -> ProtoCommands<'w, 's, 'a, 'p>;

    /// Spawns an entity with this prototype's component structure.
    ///
    /// # Arguments
    ///
    /// * `commands`: The world `Commands`
    /// * `data`: The prototype data in this world
    /// * `asset_server`: The asset server
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy::prelude::*;
    /// use bevy_proto_typetag::prelude::{ProtoData, Prototype, Prototypical};
    ///
    /// fn setup_system(mut commands: Commands, data: Res<ProtoData>, asset_server: &Res<AssetServer>) {
    ///     let proto: Prototype = serde_yaml::from_str(r#"
    ///     name: My Prototype
    ///     components:
    ///       - type: SomeMarkerComponent
    ///       - type: SomeComponent
    ///         value:
    ///           - speed: 10.0
    ///     "#).unwrap();
    ///
    ///     let entity = proto.spawn(&mut commands, &data, &asset_server).id();
    ///
    ///     // ...
    /// }
    ///
    /// ```
    fn spawn<'w, 's, 'a, 'p>(
        &'p self,
        commands: &'a mut Commands<'w, 's>,
        data: &Res<ProtoData>,
        asset_server: &Res<AssetServer>,
    ) -> EntityCommands<'w, 's, 'a> {
        let entity = commands.spawn_empty();
        self.insert(entity, data, asset_server)
    }

    /// Inserts this prototype's component structure to the given entity.
    ///
    /// __Note:__ This _will_ override existing components of the same type.
    ///
    /// # Arguments
    ///
    /// * `entity`: The `EntityCommands` for a given entity
    /// * `data`: The prototype data in this world
    /// * `asset_server`: The asset server
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy::prelude::*;
    /// use bevy_proto_typetag::prelude::{ProtoData, Prototype, Prototypical};
    ///
    /// #[derive(Component)]
    /// struct Player(pub Entity);
    ///
    /// fn setup_system(mut commands: Commands, data: Res<ProtoData>, asset_server: &Res<AssetServer>, player: Query<&Player>) {
    ///     let proto: Prototype = serde_yaml::from_str(r#"
    ///     name: My Prototype
    ///     components:
    ///       - type: SomeMarkerComponent
    ///       - type: SomeComponent
    ///         value:
    ///           - speed: 10.0
    ///     "#).unwrap();
    ///
    ///     // Get the EntityCommands for the player entity
    ///     let entity = commands.entity(player.single().0);
    ///
    ///     // Insert the new components
    ///     let entity = proto.insert(entity, &data, &asset_server).id();
    ///
    ///     // ...
    /// }
    ///
    /// ```
    fn insert<'w, 's, 'a, 'p>(
        &'p self,
        entity: EntityCommands<'w, 's, 'a>,
        data: &Res<ProtoData>,
        asset_server: &Res<AssetServer>,
    ) -> EntityCommands<'w, 's, 'a> {
        let mut proto_commands = self.create_commands(entity, data);

        spawn_internal(
            self.name(),
            self.templates().iter().rev(),
            self.iter_components(),
            &mut proto_commands,
            data,
            asset_server,
            &mut IndexSet::default(),
        );

        proto_commands.into()
    }
}

/// Internal method used for recursing up the template hierarchy and spawning components
/// from the top to the bottom
fn spawn_internal<'a>(
    name: &'a str,
    templates: Rev<Iter<'a, String>>,
    components: Iter<'a, Box<dyn ProtoComponent>>,
    proto_commands: &mut ProtoCommands,
    data: &'a Res<ProtoData>,
    asset_server: &Res<AssetServer>,
    traversed: &mut IndexSet<&'a str>,
) {
    // We insert first on the off chance that someone made a prototype its own template...
    traversed.insert(name);

    for template in templates {
        if traversed.contains(template.as_str()) {
            // ! === Found Circular Dependency === ! //
            handle_cycle!(
                template,
                traversed,
                "For now, the rest of the spawn has been skipped."
            );

            continue;
        }

        // === Spawn Template === //
        if let Some(parent) = data.get_prototype(template) {
            spawn_internal(
                parent.name(),
                parent.templates_rev(),
                parent.iter_components(),
                proto_commands,
                data,
                asset_server,
                traversed,
            );
        }
    }

    // === Spawn Self === //
    for component in components {
        component.insert_self(proto_commands, asset_server);
    }
}

/// The default prototype object, providing the basics for the prototype system.
#[derive(Serialize, Deserialize)]
pub struct Prototype {
    /// The name of this prototype.
    pub name: String,
    /// The names of this prototype's templates (if any).
    ///
    /// See [`deserialize_templates_list`] for how these names are deserialized.
    #[serde(default)]
    #[serde(alias = "template")]
    #[serde(deserialize_with = "deserialize_templates_list")]
    pub templates: Vec<String>,
    /// The components belonging to this prototype.
    #[serde(default)]
    pub components: Vec<Box<dyn ProtoComponent>>,
}

impl Prototypical for Prototype {
    fn name(&self) -> &str {
        &self.name
    }

    fn templates(&self) -> &[String] {
        &self.templates
    }

    fn iter_components(&self) -> Iter<'_, Box<dyn ProtoComponent>> {
        self.components.iter()
    }

    fn create_commands<'w, 's, 'a, 'p>(
        &'p self,
        entity: EntityCommands<'w, 's, 'a>,
        data: &'p Res<ProtoData>,
    ) -> ProtoCommands<'w, 's, 'a, 'p> {
        data.get_commands(self, entity)
    }
}

/// A function used to deserialize a list of templates.
///
/// A template list can take on the following forms:
///
/// * Inline List:
///   > ```yaml
///   > templates: [ A, B, C ]
///   > ```
/// * Multi-Line List:
///   > ```yaml
///   > templates:
///   >   - A
///   >   - B
///   >   - C
///   > ```
/// * Comma-Separated String:
///   > ```yaml
///   > templates: A, B, C # OR: "A, B, C"
///   > ```
pub fn deserialize_templates_list<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    struct TemplatesList;

    impl<'de> Visitor<'de> for TemplatesList {
        type Value = Vec<String>;

        fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
            formatter.write_str("string or vec")
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: Error,
        {
            // Split string by commas
            // Allowing for: "A, B, C" to become [A, B, C]
            Ok(v.split(',').map(|s| s.trim().to_string()).collect())
        }

        fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            Deserialize::deserialize(de::value::SeqAccessDeserializer::new(seq))
        }
    }

    deserializer.deserialize_any(TemplatesList)
}