legion/internals/serialize/
entities.rs

1pub mod ser {
2    use std::{collections::HashMap, marker::PhantomData};
3
4    use itertools::Itertools;
5    use serde::{ser::SerializeMap, Serialize, Serializer};
6
7    use crate::internals::{
8        query::filter::LayoutFilter,
9        serialize::{ser::WorldSerializer, UnknownType},
10        storage::{
11            archetype::{Archetype, ArchetypeIndex},
12            component::ComponentTypeId,
13            ComponentIndex,
14        },
15        world::World,
16    };
17
18    pub struct EntitiesLayoutSerializer<'a, W: WorldSerializer, F: LayoutFilter> {
19        pub world_serializer: &'a W,
20        pub world: &'a World,
21        pub filter: &'a F,
22    }
23
24    impl<'a, W: WorldSerializer, F: LayoutFilter> Serialize for EntitiesLayoutSerializer<'a, W, F> {
25        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
26        where
27            S: Serializer,
28        {
29            let archetypes = self
30                .world
31                .archetypes()
32                .iter()
33                .enumerate()
34                .filter(|(_, arch)| {
35                    self.filter
36                        .matches_layout(arch.layout().component_types())
37                        .is_pass()
38                })
39                .map(|(i, arch)| (ArchetypeIndex(i as u32), arch))
40                .collect::<Vec<_>>();
41
42            let component_types = archetypes
43                .iter()
44                .flat_map(|(_, arch)| arch.layout().component_types())
45                .unique();
46            let mut type_mappings = HashMap::new();
47            for id in component_types {
48                match self.world_serializer.map_id(*id) {
49                    Ok(type_id) => {
50                        type_mappings.insert(*id, type_id);
51                    }
52                    Err(error) => {
53                        match error {
54                            UnknownType::Ignore => {}
55                            UnknownType::Error => {
56                                return Err(serde::ser::Error::custom(format!(
57                                    "unknown component type {:?}",
58                                    *id
59                                )));
60                            }
61                        }
62                    }
63                }
64            }
65
66            let mut map = serializer.serialize_map(Some(
67                archetypes
68                    .iter()
69                    .map(|(_, arch)| arch.entities().len())
70                    .sum(),
71            ))?;
72
73            for (arch_index, arch) in archetypes {
74                for (i, entity) in arch.entities().iter().enumerate() {
75                    map.serialize_entry(
76                        entity,
77                        &EntitySerializer {
78                            component_index: ComponentIndex(i),
79                            arch_index,
80                            arch,
81                            world: self.world,
82                            world_serializer: self.world_serializer,
83                            type_mappings: &type_mappings,
84                        },
85                    )?;
86                }
87            }
88
89            map.end()
90        }
91    }
92
93    struct EntitySerializer<'a, W: WorldSerializer> {
94        component_index: ComponentIndex,
95        arch_index: ArchetypeIndex,
96        arch: &'a Archetype,
97        world: &'a World,
98        world_serializer: &'a W,
99        type_mappings: &'a HashMap<ComponentTypeId, W::TypeId>,
100    }
101
102    impl<'a, W: WorldSerializer> Serialize for EntitySerializer<'a, W> {
103        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
104        where
105            S: Serializer,
106        {
107            let layout = self.arch.layout().component_types();
108            let components = self.world.components();
109            let type_count = layout
110                .iter()
111                .filter_map(|t| self.type_mappings.get(t))
112                .count();
113
114            let mut map = serializer.serialize_map(Some(type_count))?;
115
116            for type_id in self.arch.layout().component_types() {
117                if let Some(mapped_type_id) = self.type_mappings.get(type_id) {
118                    let storage = components.get(*type_id).unwrap();
119                    let (ptr, len) = storage.get_raw(self.arch_index).unwrap();
120                    assert!(self.component_index.0 < len);
121                    map.serialize_entry(
122                        mapped_type_id,
123                        &ComponentSerializer {
124                            type_id: *type_id,
125                            world_serializer: self.world_serializer,
126                            ptr: unsafe {
127                                ptr.add(self.component_index.0 * storage.element_vtable().size())
128                            },
129                            _phantom: PhantomData,
130                        },
131                    )?;
132                }
133            }
134
135            map.end()
136        }
137    }
138
139    struct ComponentSerializer<'a, W: WorldSerializer> {
140        type_id: ComponentTypeId,
141        ptr: *const u8,
142        world_serializer: &'a W,
143        _phantom: PhantomData<&'a u8>,
144    }
145
146    impl<'a, W: WorldSerializer> Serialize for ComponentSerializer<'a, W> {
147        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
148        where
149            S: Serializer,
150        {
151            unsafe {
152                self.world_serializer
153                    .serialize_component(self.type_id, self.ptr, serializer)
154            }
155        }
156    }
157}
158
159pub mod de {
160    use std::{collections::HashMap, rc::Rc};
161
162    use serde::{
163        de::{DeserializeSeed, IgnoredAny, MapAccess, Visitor},
164        Deserializer,
165    };
166
167    use crate::internals::{
168        entity::Entity,
169        insert::{ArchetypeSource, ArchetypeWriter, ComponentSource, IntoComponentSource},
170        serialize::{de::WorldDeserializer, UnknownType},
171        storage::{archetype::EntityLayout, component::ComponentTypeId},
172        world::World,
173    };
174
175    pub struct EntitiesLayoutDeserializer<'a, W: WorldDeserializer> {
176        pub world_deserializer: &'a W,
177        pub world: &'a mut World,
178    }
179
180    impl<'a, 'de, W: WorldDeserializer> DeserializeSeed<'de> for EntitiesLayoutDeserializer<'a, W> {
181        type Value = ();
182
183        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
184        where
185            D: Deserializer<'de>,
186        {
187            struct EntitySeqVisitor<'b, D: WorldDeserializer> {
188                world_deserializer: &'b D,
189                world: &'b mut World,
190            }
191
192            impl<'b, 'de, D: WorldDeserializer> Visitor<'de> for EntitySeqVisitor<'b, D> {
193                type Value = ();
194
195                fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
196                    formatter.write_str("entity map")
197                }
198
199                fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
200                where
201                    V: MapAccess<'de>,
202                {
203                    while let Some(entity) = map.next_key()? {
204                        self.world.remove(entity);
205                        map.next_value_seed(EntityDeserializer {
206                            world_deserializer: self.world_deserializer,
207                            world: self.world,
208                            entity,
209                        })?
210                    }
211                    Ok(())
212                }
213            }
214
215            deserializer.deserialize_map(EntitySeqVisitor {
216                world_deserializer: self.world_deserializer,
217                world: self.world,
218            })
219        }
220    }
221
222    struct EntityDeserializer<'a, W: WorldDeserializer> {
223        world_deserializer: &'a W,
224        world: &'a mut World,
225        entity: Entity,
226    }
227
228    impl<'a, 'de, W: WorldDeserializer> DeserializeSeed<'de> for EntityDeserializer<'a, W> {
229        type Value = ();
230
231        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
232        where
233            D: Deserializer<'de>,
234        {
235            struct ComponentMapVisitor<'b, D: WorldDeserializer> {
236                world_deserializer: &'b D,
237                world: &'b mut World,
238                entity: Entity,
239            }
240
241            impl<'b, 'de, D: WorldDeserializer> Visitor<'de> for ComponentMapVisitor<'b, D> {
242                type Value = ();
243
244                fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
245                    formatter.write_str("struct Entity")
246                }
247
248                fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
249                where
250                    V: MapAccess<'de>,
251                {
252                    let mut layout = EntityLayout::new();
253                    let mut components = HashMap::new();
254
255                    while let Some(mapped_type_id) = map.next_key::<D::TypeId>()? {
256                        match self.world_deserializer.unmap_id(&mapped_type_id) {
257                            Ok(type_id) => {
258                                self.world_deserializer
259                                    .register_component(mapped_type_id, &mut layout);
260                                components.insert(
261                                    type_id,
262                                    map.next_value_seed(ComponentDeserializer {
263                                        type_id,
264                                        world_deserializer: self.world_deserializer,
265                                    })?,
266                                );
267                            }
268                            Err(missing) => {
269                                match missing {
270                                    UnknownType::Ignore => {
271                                        map.next_value::<IgnoredAny>()?;
272                                    }
273                                    UnknownType::Error => {
274                                        return Err(serde::de::Error::custom(
275                                            "unknown component type",
276                                        ));
277                                    }
278                                }
279                            }
280                        }
281                    }
282
283                    struct SingleEntity {
284                        entity: Entity,
285                        components: HashMap<ComponentTypeId, Box<[u8]>>,
286                        layout: Rc<EntityLayout>,
287                    }
288
289                    impl ArchetypeSource for SingleEntity {
290                        type Filter = Rc<EntityLayout>;
291
292                        fn filter(&self) -> Self::Filter {
293                            self.layout.clone()
294                        }
295
296                        fn layout(&mut self) -> EntityLayout {
297                            (*self.layout).clone()
298                        }
299                    }
300
301                    impl ComponentSource for SingleEntity {
302                        fn push_components<'a>(
303                            &mut self,
304                            writer: &mut ArchetypeWriter<'a>,
305                            _: impl Iterator<Item = Entity>,
306                        ) {
307                            writer.push(self.entity);
308                            for (type_id, component) in self.components.drain() {
309                                let mut storage = writer.claim_components_unknown(type_id);
310                                unsafe { storage.extend_memcopy_raw(component.as_ptr(), 1) };
311                            }
312                        }
313                    }
314
315                    impl IntoComponentSource for SingleEntity {
316                        type Source = Self;
317                        fn into(self) -> Self::Source {
318                            self
319                        }
320                    }
321
322                    self.world.extend(SingleEntity {
323                        entity: self.entity,
324                        components,
325                        layout: Rc::new(layout),
326                    });
327
328                    Ok(())
329                }
330            }
331
332            deserializer.deserialize_map(ComponentMapVisitor {
333                world_deserializer: self.world_deserializer,
334                world: self.world,
335                entity: self.entity,
336            })
337        }
338    }
339
340    struct ComponentDeserializer<'a, W: WorldDeserializer> {
341        type_id: ComponentTypeId,
342        world_deserializer: &'a W,
343    }
344
345    impl<'a, 'de, W: WorldDeserializer> DeserializeSeed<'de> for ComponentDeserializer<'a, W> {
346        type Value = Box<[u8]>;
347
348        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
349        where
350            D: Deserializer<'de>,
351        {
352            self.world_deserializer
353                .deserialize_component(self.type_id, deserializer)
354        }
355    }
356}