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
use crate::{
    ecs::{
        commands::{DespawnEntity, UniverseCommands},
        components::Name,
        life_cycle::EntityChanges,
        Comp, Entity, Universe, WorldRef,
    },
    prefab::{Prefab, PrefabError, PrefabProxy},
    state::StateToken,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Debug, Clone, PartialEq)]
pub struct Parent(pub Entity);

impl PrefabProxy<ParentPrefabProxy> for Parent {
    fn from_proxy_with_extras(
        proxy: ParentPrefabProxy,
        named_entities: &HashMap<String, Entity>,
        _: StateToken,
    ) -> Result<Self, PrefabError> {
        if let Some(entity) = named_entities.get(&proxy.0) {
            Ok(Self(*entity))
        } else {
            Err(PrefabError::Custom(format!(
                "Could not find entity named: {}",
                proxy.0
            )))
        }
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ParentPrefabProxy(pub String);

impl Prefab for ParentPrefabProxy {}

#[derive(Debug, Default)]
pub struct Hierarchy {
    roots: Vec<Entity>,
    child_parent_relations: HashMap<Entity, Entity>,
    parent_children_relations: HashMap<Entity, Vec<Entity>>,
    entity_names_map: HashMap<Entity, String>,
    name_entities_map: HashMap<String, Entity>,
}

impl Hierarchy {
    pub fn roots(&self) -> impl Iterator<Item = Entity> + '_ {
        self.roots.iter().copied()
    }

    pub fn parents(&self) -> impl Iterator<Item = Entity> + '_ {
        self.parent_children_relations.keys().copied()
    }

    pub fn childs(&self) -> impl Iterator<Item = Entity> + '_ {
        self.child_parent_relations.keys().copied()
    }

    pub fn parent(&self, child: Entity) -> Option<Entity> {
        self.child_parent_relations.get(&child).copied()
    }

    pub fn children(&self, parent: Entity) -> Option<impl Iterator<Item = Entity> + '_> {
        self.parent_children_relations
            .get(&parent)
            .map(|list| list.iter().copied())
    }

    pub fn entity_by_name(&self, name: &str) -> Option<Entity> {
        self.name_entities_map.get(name).copied()
    }

    pub fn name_by_entity(&self, entity: Entity) -> Option<&str> {
        self.entity_names_map.get(&entity).map(|name| name.as_str())
    }

    pub fn find(&self, root: Option<Entity>, mut path: &str) -> Option<Entity> {
        let mut root = match root {
            Some(root) => root,
            None => {
                let part = match path.find('/') {
                    Some(found) => {
                        let part = &path[..found];
                        path = &path[(found + 1)..];
                        part
                    }
                    None => {
                        let part = path;
                        path = "";
                        part
                    }
                };
                match self.entity_by_name(part) {
                    Some(root) => root,
                    None => return None,
                }
            }
        };
        for part in path.split('/') {
            match part {
                "" | "." => {}
                ".." => match self.parent(root) {
                    Some(parent) => root = parent,
                    None => return None,
                },
                part => match self.children(root) {
                    Some(mut iter) => match iter.find(|child| {
                        self.name_by_entity(*child)
                            .map(|name| name == part)
                            .unwrap_or_default()
                    }) {
                        Some(child) => root = child,
                        None => return None,
                    },
                    None => return None,
                },
            }
        }
        Some(root)
    }

    pub fn iter(&self) -> HierarchyIter {
        HierarchyIter {
            hierarchy: self,
            iter_stack: vec![Box::new(self.roots.iter().copied())],
            parent_stack: vec![],
        }
    }
}

pub struct HierarchyIter<'a> {
    hierarchy: &'a Hierarchy,
    iter_stack: Vec<Box<dyn Iterator<Item = Entity> + 'a>>,
    parent_stack: Vec<Entity>,
}

impl<'a> Iterator for HierarchyIter<'a> {
    type Item = (Entity, Option<Entity>);

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(mut iter) = self.iter_stack.pop() {
                if let Some(entity) = iter.next() {
                    self.iter_stack.push(iter);
                    if let Some(children) = self.hierarchy.children(entity) {
                        self.iter_stack.push(Box::new(children));
                    }
                    return Some((entity, self.parent_stack.last().copied()));
                } else {
                    continue;
                }
            } else {
                return None;
            }
        }
    }
}

pub type HierarchySystemResources<'a> = (
    WorldRef,
    &'a mut UniverseCommands,
    &'a EntityChanges,
    &'a mut Hierarchy,
    Comp<&'a Parent>,
    Comp<&'a Name>,
);

pub fn hierarchy_system(universe: &mut Universe) {
    let (world, mut commands, changes, mut hierarchy, ..) =
        universe.query_resources::<HierarchySystemResources>();

    if changes.has_changed() {
        despawn(&mut commands, &changes, &hierarchy);

        hierarchy.roots = Vec::with_capacity(world.len() as usize);
        hierarchy.child_parent_relations = HashMap::with_capacity(world.len() as usize);
        hierarchy.parent_children_relations = HashMap::with_capacity(world.len() as usize / 10);
        hierarchy.entity_names_map = HashMap::with_capacity(world.len() as usize / 10);
        hierarchy.name_entities_map = HashMap::with_capacity(world.len() as usize / 10);
    } else {
        hierarchy.roots.clear();
        hierarchy.child_parent_relations.clear();
        hierarchy.parent_children_relations.clear();
        hierarchy.entity_names_map.clear();
        hierarchy.name_entities_map.clear();
    }

    for (entity, _) in world.query::<()>().without::<&Parent>().iter() {
        hierarchy.roots.push(entity);
    }

    for (child, (parent, name)) in world.query::<(Option<&Parent>, Option<&Name>)>().iter() {
        if let Some(parent) = parent {
            hierarchy.child_parent_relations.insert(child, parent.0);
            let list: &mut Vec<Entity> = hierarchy
                .parent_children_relations
                .entry(parent.0)
                .or_default();
            list.push(child);
        }
        if let Some(name) = name {
            let name: String = name.0.clone().into();
            hierarchy.entity_names_map.insert(child, name.to_owned());
            hierarchy.name_entities_map.insert(name, child);
        }
    }

    for (child, name) in world.query::<&Name>().iter() {
        hierarchy
            .entity_names_map
            .insert(child, name.0.as_ref().to_owned());
        hierarchy
            .name_entities_map
            .insert(name.0.as_ref().to_owned(), child);
    }
}

fn despawn(commands: &mut UniverseCommands, changes: &EntityChanges, hierarchy: &Hierarchy) {
    for entity in changes.despawned() {
        despawn_children(commands, entity, hierarchy);
    }
}

fn despawn_children(commands: &mut UniverseCommands, parent: Entity, hierarchy: &Hierarchy) {
    if let Some(iter) = hierarchy.children(parent) {
        for entity in iter {
            commands.schedule(DespawnEntity(entity));
            despawn_children(commands, entity, hierarchy);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hecs::Component;

    #[test]
    fn test_send_sync() {
        fn foo<T>()
        where
            T: Component + Send + Sync,
        {
            println!("{} is Component", std::any::type_name::<T>());
        }

        foo::<Parent>();
    }
}