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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
use crate::{DataAccesses, MaskType, ReadGuardRef, ResourcesThreadLocal, Sto, entity::EntitiesStorage, operators::{
        ChangedDataSend, EntitiesComponentIter, OrderedDataSend,
        ReadOnlyOp, ReadOnlyOrderedOp, UnorderedDataSend, UnorderedData, OrderedData, EntitiesData,
    }, storage::{FastIndexExt, SubStorages, ReadOnlyStorage}, sync::{IndexGuard, LazyIndexGuard, OrderedIndexGuard, StorageWriteGuard}, utils::IntoEntitiesIterator};
use crate::entity::Entity;
use crate::sync::{Ptr, PtrMut, NodePtr, NodePtrMut};
use crate::component::{self, Component, OneToNComponent, ComponentSend};
#[cfg(feature="debug_parameters")]
use erased_serde::Serializer;
use serde::{Serialize, ser::SerializeSeq};
use crate::storage::{Storage, SliceView, HierarchicalStorage, OneToNStorage, StorageRef};
use crate::entity::{Entities, EntitiesThreadLocal, EntitiesExt};
use crate::Bitmask;
use crate::SystemId;
use std::{any::TypeId, cell::UnsafeCell};


/// `EntitiesDebug` is passed to `DebugSystem`s when they are run and allows
/// to access debug information for entities' compoenents
pub struct EntitiesDebug<'a>{
    pub(crate) storages: SubStorages<'a>,
}

impl<'a> EntitiesDebug<'a>{
    /// Iterator over all the components that match the operator
    ///
    /// ```
    /// # #[macro_use] extern crate rinecs_derive;
    /// # use rinecs::*;
    /// # #[derive(Component, Debug)]
    /// # struct Position{x: f32, y: f32}
    /// # #[derive(Component, Debug)]
    /// # struct Velocity{x: f32, y: f32}
    /// # let mut world = World::new();
    /// # let entities = world.entities();
    /// for (pos, vel) in entities.iter_for::<(Write<Position>, Read<Velocity>)>(){
    ///     pos.x += vel.x;
    ///     pos.y += vel.y;
    /// }
    /// ```
    ///
    /// Will iterate over all the entities that have both position and velocity
    /// and update the position by adding the velocity to it. In this example
    /// position can be modified cause we use the Write operator but velocity
    /// can only be read.
    pub fn iter_for<'e, S: UnorderedData<'e> + ReadOnlyOp<'e>>(&'e self) -> <S as UnorderedData<'e>>::Iter{
        S::into_iter(self)
    }

    /// Iterator over all the components that match the operator
    ///
    /// Can be used with operators that access a storage mutably
    ///
    /// ```
    /// # #[macro_use] extern crate rinecs_derive;
    /// # use rinecs::*;
    /// # #[derive(Component, Debug)]
    /// # struct Position{x: f32, y: f32}
    /// # #[derive(Component, Debug)]
    /// # struct Velocity{x: f32, y: f32}
    /// # let mut world = World::new();
    /// # let mut entities = world.entities();
    /// for (pos, vel) in entities.iter_for_mut::<(Write<Position>, Read<Velocity>)>(){
    ///     pos.x += vel.x;
    ///     pos.y += vel.y;
    /// }
    /// ```
    ///
    /// Will iterate over all the entities that have both position and velocity
    /// and update the position by adding the velocity to it. In this example
    /// position can be modified cause we use the Write operator but velocity
    /// can only be read.
    pub fn iter_for_mut<'e, S: UnorderedDataSend<'e>>(&'e mut self) -> <S as UnorderedData<'e>>::IterMut {
        S::into_iter_mut(self)
    }

    /// Storage for the operator passed as type parameter
    ///
    /// Calling iter_for can be slow if it needs to be called lots of times. In those cases
    /// calling instead `storage_for` once and then iter() on it multiple times can make performance
    /// much better
    ///
    /// ```
    /// # #[macro_use] extern crate rinecs_derive;
    /// # use rinecs::*;
    /// # #[derive(Component, Debug)]
    /// # struct Position{x: f32, y: f32}
    /// # #[derive(Component, Debug)]
    /// # struct Velocity{x: f32, y: f32}
    /// # let mut world = World::new();
    /// # world.new_entity().add(Position{x: 0., y: 0.}).add(Velocity{x: 0.0, y: 0.0}).build();
    /// # let mut entities = world.entities();
    /// let mut storage = entities.storage_for_mut::<(Write<Position>, Read<Velocity>)>().unwrap();
    /// for i in 0..1000000 {
    ///     for (pos, vel) in storage.iter_mut() {
    ///         pos.x += vel.x;
    ///         pos.y += vel.y;
    ///     }
    /// }
    /// ```
    pub fn storage_for<'r, S>(&'r self) -> Sto<'r, S>
    where S: UnorderedDataSend<'r> + ReadOnlyOp<'r>
    {
        Sto::new(
            S::storage(self),
            Entities{
                storages: self.storages.clone()
            }
        )
    }

    pub fn storage_for_mut<'r, S>(&'r mut self) -> Sto<'r, S>
    where S: UnorderedDataSend<'r>
    {
        Sto::new(
            S::storage(self),
            Entities{
                storages: self.storages.clone()
            }
        )
    }

    /// Iterator over ordered data
    ///
    /// Similar to iter_for but to be used with operators that specify an order
    /// like ReadAndParent in which parents will be processed first and then
    /// their children
    pub fn ordered_iter_for<'e, S: OrderedDataSend<'e> + ReadOnlyOrderedOp<'e>>(&'e self) -> <S as OrderedData<'e>>::Iter{
        S::into_iter(self)
    }

    /// Iterator over ordered data
    ///
    /// Similar to iter_for but to be used with operators that specify an order
    /// like ReadAndParent in which parents will be processed first and then
    /// their children
    pub fn ordered_iter_for_mut<'e, S: OrderedDataSend<'e>>(&'e mut self) -> <S as OrderedData<'e>>::Iter{
        S::into_iter(self)
    }

    /// Storage for the operator passed as type parameter
    ///
    /// Calling ordered_iter_for can be slow if it needs to be called lots of times. In those cases
    /// calling instead `ordered_storage_for` once and then iter() on it multiple times can make performance
    /// much better
    pub fn ordered_storage_for<'e, S: OrderedDataSend<'e> + ReadOnlyOrderedOp<'e>>(&'e self) -> Option<<S as OrderedData<'e>>::Storage> {
        S::storage(self)
    }

    pub fn ordered_storage_for_mut<'e, S: OrderedDataSend<'e>>(&'e mut self) -> Option<<S as OrderedData<'e>>::Storage> {
        S::storage(self)
    }

    /// Iterator for the specified operators over a set of entities instead of
    /// every entity in the world
    ///
    /// It's usage is similar to iter_for but instead of iterating over all the
    /// entities it only returns components that match the operators for the entities
    /// passed as parameter
    ///
    /// ```
    /// # #[macro_use] extern crate rinecs_derive;
    /// # use rinecs::*;
    /// # #[derive(Component, Debug)]
    /// # struct Position{x: f32, y: f32};
    /// # let mut world = World::new();
    /// let e1 = world.new_entity()
    ///     .add(Position{x: 0., y: 0.})
    ///     .build();
    /// let e2 = world.new_entity()
    ///     .add(Position{x: 0., y: 0.})
    ///     .build();
    /// let e3 = world.new_entity()
    ///     .add(Position{x: 0., y: 0.})
    ///     .build();
    /// let entities = world.entities();
    /// for pos in entities.iter_for_entities::<Read<Position>, _>(vec![e1, e2]){
    ///     //...
    /// }
    /// ```
    ///
    /// The operators parameter in this method needs a second type for
    /// the entities iterator type which can jsut be elided with a _
    /// since it'll be guessed from the passed parameter
    pub fn iter_for_entities<'e, U, E>(&'e self, entities: E) -> E::IntoEntitiesIter
    where
        E: IntoEntitiesIterator<'e, U::Storage>,
        U: UnorderedData<'e>,
        U::Storage: ReadOnlyStorage
    {
        entities.storage_entities_iter(U::storage(self))
    }

    pub fn iter_for_entities_mut<'e, U, E>(&'e mut self, entities: E) -> E::IntoEntitiesIterMut
    where
        E: IntoEntitiesIterator<'e, U::Storage>,
        U: UnorderedData<'e>,
    {
        entities.storage_entities_iter_mut(U::storage(self))
    }

    pub fn iter_for_entities_opt<'e, U, E>(&'e self, entities: E) -> E::IntoEntitiesOptIter
    where
        E: IntoEntitiesIterator<'e, U::Storage>,
        U: UnorderedData<'e>,
        U::Storage: ReadOnlyStorage
    {
        entities.storage_entities_opt_iter(U::storage(self))
    }

    pub fn iter_for_entities_opt_mut<'e, U, E>(&'e mut self, entities: E) -> E::IntoEntitiesOptIterMut
    where
        E: IntoEntitiesIterator<'e, U::Storage>,
        U: UnorderedData<'e>,
    {
        entities.storage_entities_opt_iter_mut(U::storage(self))
    }


    /// Similar to iter_for_entities but for one entity instead of several
    ///
    /// ```
    /// # #[macro_use] extern crate rinecs_derive;
    /// # use rinecs::*;
    /// # #[derive(Component, Debug)]
    /// # struct Position{x: f32, y: f32};
    /// # #[derive(Component, Debug)]
    /// # struct Velocity{x: f32, y: f32};
    /// # let mut world = World::new();
    /// let e1 = world.new_entity()
    ///     .add(Position{x: 0., y: 0.})
    ///     .add(Velocity{x: 0., y: 0.})
    ///     .build();
    /// let entities = world.entities();
    /// let (pos, vel) = entities
    ///     .entity_components::<(Write<Position>, Read<Velocity>)>(&e1)
    ///     .unwrap();
    /// ```
    pub fn entity_components<'r, S>(&'r self, entity: &Entity) -> Option<<S as UnorderedData<'r>>::ComponentsRef>
    where
        S: UnorderedDataSend<'r> + ReadOnlyOp<'r> + 'r,
        S::Storage: StorageRef<'r, Component = S::ComponentsRef>
    {
        let mut storage = S::storage(self)?;
        if storage.contains(entity.guid()){
            let storage = &mut storage as *mut S::Storage;
            unsafe{ Some((*storage).get_unchecked(entity.guid())) }
        }else{
            None
        }
    }

    pub fn entity_components_mut<'r, S>(&'r mut self, entity: &Entity) -> Option<<S as UnorderedData<'r>>::ComponentsRef>
    where
        S: UnorderedDataSend<'r> + 'r,
        S::Storage: StorageRef<'r, Component = S::ComponentsRef>
    {
        let mut storage = S::storage(self)?;
        if storage.contains(entity.guid()){
            let storage = &mut storage as *mut S::Storage;
            unsafe{ Some((*storage).get_unchecked(entity.guid())) }
        }else{
            None
        }
    }

    /// Returns a component for reading for the passed entity
    ///
    /// ```
    /// # #[macro_use] extern crate rinecs_derive;
    /// # use rinecs::*;
    /// # #[derive(Component, Debug)]
    /// # struct Position{x: f32, y: f32};
    /// # let mut world = World::new();
    /// let e1 = world.new_entity()
    ///     .add(Position{x: 0., y: 0.})
    ///     .build();
    /// let entities = world.entities();
    /// let pos = entities.component_for::<Position>(&e1).unwrap();
    /// ```
    pub fn component_for<C: Component>(&self, entity: &Entity) -> Option<Ptr<C>>
    where for<'s> <C as Component>::Storage: Storage<'s, C>
    {
        self.to_thread_local().component_for::<C>(entity)
    }

    /// Returns a component for writing for the passed entity
    ///
    /// ```
    /// # #[macro_use] extern crate rinecs_derive;
    /// # use rinecs::*;
    /// # #[derive(Component, Debug)]
    /// # struct Position{x: f32, y: f32};
    /// # let mut world = World::new();
    /// let e1 = world.new_entity()
    ///     .add(Position{x: 0., y: 0.})
    ///     .build();
    /// let entities = world.entities();
    /// let mut pos = entities.component_for_mut::<Position>(&e1).unwrap();
    /// ```
    pub fn component_for_mut<C: Component>(&self, entity: &Entity) -> Option<PtrMut<C>>
    where for<'s> <C as Component>::Storage: Storage<'s, C>
    {
        self.to_thread_local().component_for_mut::<C>(entity)
    }

    /// Returns true if the entity has the specified component
    ///
    /// ```
    /// # #[macro_use] extern crate rinecs_derive;
    /// # use rinecs::*;
    /// # #[derive(Component, Debug)]
    /// # struct Position{x: f32, y: f32}
    /// # let mut world = World::new();
    /// let e1 = world.new_entity()
    ///     .add(Position{x: 0., y: 0.})
    ///     .build();
    /// let entities = world.entities();
    /// assert!(entities.has_component::<Position>(&e1));
    /// ```
    pub fn has_component<C: 'static>(&self, entity: &Entity) -> bool{
        self.to_thread_local().has_component::<C>(entity)
    }

    /// Returns the node for a hierarchical component
    pub fn tree_node_for<'r, C: Component>(&'r self, entity: &Entity) -> Option<NodePtr<'r, C>>
    where for<'b> <C as Component>::Storage: HierarchicalStorage<'b, C>
    {
        self.to_thread_local().tree_node_for::<C>(entity)
    }

    /// Returns the node for a hierarchical component for writing
    pub fn tree_node_for_mut<'r, C: Component>(&'r self, entity: &Entity) -> Option<NodePtrMut<'r, C>>
        where for<'b> <C as Component>::Storage: HierarchicalStorage<'b, C>
    {
        self.to_thread_local().tree_node_for_mut::<C>(entity)
    }

    /// Debug all the components for the passed entity
    ///
    /// Returns an iterator over the component Id (it's `TypeId`) and
    /// a `String` that is the `Debug` representation of the component
    #[cfg(not(feature="debug_parameters"))]
    pub fn debug_components_for(&self, entity: Entity) -> impl Iterator<Item = (component::Id, String)> + '_{
        self.entity_component_ids(entity)
            .map(move |id| (id.clone(), self.storages.debug_components_mask_index(&entity, id)))
    }

    /// Returns an iterator over all the component Ids of the passed entity
    ///
    /// Used to later ask for individual components to debug using `debug_compoentn_for`
    pub fn entity_component_ids(&self, entity: Entity) -> impl Iterator<Item = &'_ component::Id> + '_{
        let entity_mask = self.storages.entities_ref()[entity.guid()].1.clone();
        self.storages.components_masks_iter()
            .filter_map(move |(id, mask)| {
                // let bitmask = Bitmask::has(mask.clone()).check(entity_mask.clone());
                if self.storages.check(&entity, &entity_mask, &Bitmask::has(mask.clone())){
                    Some(id)
                }else{
                    None
                }
            })
    }

    /// Debug all the components for an entity using the passed serializer
    ///
    /// Only available when the `debug_parameters` feature is enabled.
    ///
    /// Uses the passed serializer to debug the components of the entity.
    ///
    /// By default when `debug_parameters` is enabled all components that
    /// implement `Serialize` will automatically implement  `DebugParameter`
    /// used by this method to debug the components thorugh the serializer passed
    /// as parameter.
    ///
    /// Components that don't implement `Serialize` can still use the attribute
    /// `#[debug_as_string]` so they are debugged using their `Debug` `String` representation
    /// or `#[debug_as_custom]` and then explicitly implement `DebugParameter` which works
    /// as a custom serialization of the component more apt for debugging purposes
    #[cfg(feature="debug_parameters")]
    pub fn debug_components_for<S: Serializer>(&self, entity: Entity, mut serializer: S) -> Result<(), erased_serde::Error>{
        for id in self.entity_component_ids(entity){
            self.storages.debug_component(&entity, id, &mut serializer)?
        }
        Ok(())
    }

    /// Debug one specific compoenent of an entity.
    ///
    /// Use entity_component_ids to retrieve all the Ids of the components of an entity
    /// or Component::id() ot get one specific component's Id
    ///
    /// See `debug_components_for` for more info about specifiying components debug format
    #[cfg(feature="debug_parameters")]
    pub fn debug_component_for<S: Serializer>(&self, entity: Entity, id: &component::Id, serializer: S) -> Result<(), erased_serde::Error>{
        self.storages.debug_component(&entity, id, serializer)
    }

    pub fn split<D: DataAccesses>(&mut self) -> (EntitiesDebug, EntitiesDebug) {
        let (split, rest) = self.storages.split::<D>();
        (
            EntitiesDebug{
                storages: split,
            },
            EntitiesDebug{
                storages: rest,
            }
        )
    }

    fn to_thread_local(&self) -> &EntitiesThreadLocal<'a>{
        unsafe{ std::mem::transmute(&self.storages) }
    }

    fn to_send(&self) -> &Entities<'a>{
        unsafe{ std::mem::transmute(&self.storages) }
    }

    fn to_send_mut(&mut self) -> &mut Entities<'a>{
        unsafe{ std::mem::transmute(&mut self.storages) }
    }

    pub(crate) fn storages(&self) -> &SubStorages<'a> {
        &self.storages
    }
}

impl<'a> EntitiesExt<'a> for EntitiesDebug<'a>{
    fn iter_for<'e, S: UnorderedDataSend<'e> + ReadOnlyOp<'e>>(&'e self) -> <S as UnorderedData<'e>>::Iter {
        S::into_iter(self)
    }

    fn iter_for_mut<'e, S: UnorderedDataSend<'e>>(&'e mut self) -> <S as UnorderedData<'e>>::IterMut {
        S::into_iter_mut(self)
    }

    fn ordered_iter_for<'e, S: OrderedDataSend<'e> + ReadOnlyOrderedOp<'e>>(&'e self) -> <S as OrderedData<'e>>::Iter{
        S::into_iter( self )
    }

    fn ordered_iter_for_mut<'e, S: OrderedDataSend<'e>>(&'e mut self) -> <S as OrderedData<'e>>::Iter{
        S::into_iter( self )
    }

    fn iter_for_entities<'e, U, E>(&'e self, entities: E) -> E::IntoEntitiesIter
    where
        E: IntoEntitiesIterator<'e, U::Storage>,
        U: UnorderedDataSend<'e>,
        U::Storage: ReadOnlyStorage
    {
        entities.storage_entities_iter(U::storage(self))
    }

    fn iter_for_entities_mut<'e, U, E>(&'e mut self, entities: E) -> E::IntoEntitiesIterMut
    where
        E: IntoEntitiesIterator<'e, U::Storage>,
        U: UnorderedDataSend<'e>,
    {
        entities.storage_entities_iter_mut(U::storage(self))
    }

    fn iter_for_entities_opt<'e, U, E>(&'e self, entities: E) -> E::IntoEntitiesOptIter
    where
        E: IntoEntitiesIterator<'e, U::Storage>,
        U: UnorderedDataSend<'e>,
        U::Storage: ReadOnlyStorage
    {
        entities.storage_entities_opt_iter(U::storage(self))
    }

    fn iter_for_entities_opt_mut<'e, U, E>(&'e mut self, entities: E) -> E::IntoEntitiesOptIterMut
    where
        E: IntoEntitiesIterator<'e, U::Storage>,
        U: UnorderedDataSend<'e>,
    {
        entities.storage_entities_opt_iter_mut(U::storage(self))
    }


    fn entity_components<'r, S>(&'r self, entity: &Entity) -> Option<<S as UnorderedData<'r>>::ComponentsRef>
    where
        S: UnorderedDataSend<'r> + ReadOnlyOp<'r> + 'r,
        S::Storage: StorageRef<'r, Component = S::ComponentsRef>
    {
        self.to_send().entity_components::<S>(entity)
    }

    fn entity_components_mut<'r, S>(&'r mut self, entity: &Entity) -> Option<<S as UnorderedData<'r>>::ComponentsRef>
    where
        S: UnorderedDataSend<'r> + 'r,
        S::Storage: StorageRef<'r, Component = S::ComponentsRef>
    {
        self.to_send_mut().entity_components_mut::<S>(entity)
    }

    fn component_for<C: ComponentSend>(&self, entity: &Entity) -> Option<Ptr<C>>
    where for<'s> <C as Component>::Storage: Storage<'s, C>
    {
        self.to_send().component_for::<C>(entity)
    }

    fn component_for_mut<C: ComponentSend>(&self, entity: &Entity) -> Option<PtrMut<C>>
    where for<'s> <C as Component>::Storage: Storage<'s, C>
    {
        self.to_send().component_for_mut::<C>(entity)
    }

    fn has_component<C: 'static>(&self, entity: &Entity) -> bool{
        self.to_send().has_component::<C>(entity)
    }

    fn tree_node_for<C: ComponentSend>(&self, entity: &Entity) -> Option<NodePtr<C>>
        where for<'b> <C as Component>::Storage: HierarchicalStorage<'b, C>
    {
        self.to_send().tree_node_for::<C>(entity)
    }

    fn tree_node_for_mut<C: ComponentSend>(&self, entity: &Entity) -> Option<NodePtrMut<C>>
        where for<'b> <C as Component>::Storage: HierarchicalStorage<'b, C>
    {
        self.to_send().tree_node_for_mut::<C>(entity)
    }

    fn changed_iter_for<'r, S>(&'r self) -> EntitiesComponentIter<'r, S::ChangedIter, <S as UnorderedData<'r>>::Storage>
    where
        S: ChangedDataSend<'r> + EntitiesData + ReadOnlyOp<'r> + 'r,
        <S as UnorderedData<'r>>::Storage: StorageRef<'r>
    {
        let iter = S::changed_iter(self);
        S::into_entities_iter(self, iter)
    }

    fn changed_iter_for_mut<'r, S>(&'r mut self) -> EntitiesComponentIter<'r, S::ChangedIter, <S as UnorderedData<'r>>::Storage>
    where
        S: ChangedDataSend<'r> + EntitiesData + 'r,
        <S as UnorderedData<'r>>::Storage: StorageRef<'r>
    {
        let iter = S::changed_iter(self);
        S::into_entities_iter(self, iter)
    }

    fn storage_for<'r, S>(&'r self) -> Sto<'r, S>
    where S: UnorderedDataSend<'r> + ReadOnlyOp<'r>
    {
        Sto::new(
            S::storage(self),
            Entities{
                storages: self.storages.clone()
            }
        )
    }

    fn storage_for_mut<'r, S>(&'r mut self) -> Sto<'r, S>
    where S: UnorderedDataSend<'r>
    {
        Sto::new(
            S::storage(self),
            Entities{
                storages: self.storages.clone()
            }
        )
    }
}

impl<'a> EntitiesStorage for EntitiesDebug<'a> {
    fn storage<C: Component>(&self) -> Option<ReadGuardRef<<C as Component>::Storage>> {
        self.storages.storage_thread_local::<C>()
    }

    fn storage_mut<C: Component>(&self) -> Option<StorageWriteGuard<C>> {
        self.storages.storage_thread_local_mut::<C>()
    }

    fn entities_ref(&self) -> &[(Entity, MaskType)]{
        self.storages.entities_ref()
    }

    fn component_mask<C: 'static>(&self) -> MaskType{
        self.storages.component_mask::<C>()
    }

    fn entities_for_mask<S: FastIndexExt>(&self, query_mask: Bitmask, storage: &S) -> IndexGuard{
        self.storages.entities_for_mask(query_mask, storage)
    }

    fn lazy_entities_for_mask(&self, query_mask: Bitmask) -> LazyIndexGuard {
        LazyIndexGuard{
            query_mask,
            storages: self.storages.clone(),
            index_guard: UnsafeCell::new(None),
        }
    }

    fn ordered_entities_for<C: Component, S: FastIndexExt>(&self, query_mask: Bitmask, unordered_storage: &S) -> OrderedIndexGuard
    where for<'b> <C as Component>::Storage: HierarchicalStorage<'b,C>
    {
        self.storages.ordered_entities_for_thread_local::<C,S>(query_mask, unordered_storage)
    }
}

/// System that gives access to debug information for entites and their components
///
/// Any function that receives an EntitiesDebug and a ResourcesThreadLocal parameters
/// in that order will automatically implement this trait and can be added as a debug
/// system to the world
pub trait SystemDebug{
    fn run(&mut self, entities: EntitiesDebug, resources: ResourcesThreadLocal);
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str {""}
}



impl<'a, F: FnMut(EntitiesDebug, ResourcesThreadLocal)> SystemDebug for F{
    fn run(&mut self, entities: EntitiesDebug, resources: ResourcesThreadLocal){
        self(entities, resources)
    }
}


pub trait Inspector {
    type InspectSeq;
    type InspectTuple;
    type InspectTupleStruct;
    type InspectTupleVariant;
    type InspectMap;
    type InspectStruct;
    type InspectStructVariant;

    fn inspect_bool(self, v: &mut bool, changed: Option<bool>);
    fn inspect_i8(self, v: &mut i8, changed: Option<bool>);
    fn inspect_i16(self, v: &mut i16, changed: Option<bool>);
    fn inspect_i32(self, v: &mut i32, changed: Option<bool>);
    fn inspect_i64(self, v: &mut i64, changed: Option<bool>);
    fn inspect_u8(self, v: &mut u8, changed: Option<bool>);
    fn inspect_u16(self, v: &mut u16, changed: Option<bool>);
    fn inspect_u32(self, v: &mut u32, changed: Option<bool>);
    fn inspect_u64(self, v: &mut u64, changed: Option<bool>);
    fn inspect_f32(self, v: &mut f32, changed: Option<bool>);
    fn inspect_f64(self, v: &mut f64, changed: Option<bool>);
    fn inspect_char(self, v: &mut char, changed: Option<bool>);
    fn inspect_str(self, v: &mut String, changed: Option<bool>);
    fn inspect_bytes(self, v: &mut [u8], changed: Option<bool>);
    fn inspect_none(self, changed: Option<bool>);
    fn inspect_some<T>(self, value: &mut T, changed: Option<bool>);
    fn inspect_unit_variant(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        changed: Option<bool>
    );
    fn inspect_newtype_struct<T>(
        self,
        name: &'static str,
        value: &T,
        changed: Option<bool>
    );
    fn inspect_newtype_variant<T>(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        value: &T,
        changed: Option<bool>
    );
    fn inspect_seq(self, len: Option<usize>, changed: Option<bool>);
    fn inspect_tuple(self, len: usize, changed: Option<bool>);
    fn inspect_tuple_struct(
        self,
        name: &'static str,
        len: usize,
        changed: Option<bool>
    );
    fn inspect_tuple_variant(
        self,
        name: &'static str,
        variant_index: u32,
        variant: &'static str,
        len: usize,
        changed: Option<bool>
    );
    fn inspect_map(self, _len: Option<usize>, changed: Option<bool>);
    fn inspect_struct(
        self,
        name: &'static str,
        _len: usize,
        changed: Option<bool>
    );
    fn inspect_struct_variant(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
        changed: Option<bool>
    );
}


struct AsSeq<'a, T>(&'a [T]);

impl<'a, T: DebugParameter> Serialize for AsSeq<'a, T>{
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>{
        let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
        for d in self.0.iter() {
            let element = AsSeqElemement{
                element: d,
            };
            seq.serialize_element(&element)?;
        }
        seq.end()
    }
}

struct AsSeqElemement<'a,T>{
    element: &'a T,
}

impl<'a, T: DebugParameter> Serialize for AsSeqElemement<'a, T>{
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>{
        self.element.debug(serializer)
    }
}

pub trait DebugParameter{
    fn debug<S: serde::Serializer>(&self, serializer: S) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>;
}

impl<'a, D: DebugParameter> DebugParameter for &'a D{
    fn debug<S: serde::Serializer>(&self, serializer: S) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>{
        (*self).debug(serializer)
    }
}

impl<'a, D> DebugParameter for &'a [D]
where
    D: OneToNComponent + DebugParameter + Component,
    for<'b> <D as Component>::Storage: OneToNStorage<'b, D>
{
    fn debug<S: serde::Serializer>(&self, serializer: S) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>{
        serializer.serialize_newtype_struct(D::slice_type_name(), &AsSeq(self))
    }
}

impl<'a, D> DebugParameter for SliceView<'a,D>
where
    D: OneToNComponent + DebugParameter + Component,
    for<'b> <D as Component>::Storage: OneToNStorage<'b, D>
{
    fn debug<S: serde::Serializer>(&self, serializer: S) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>{
        serializer.serialize_newtype_struct(D::slice_type_name(), &AsSeq(&**self))
    }
}