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
use unchecked_unwrap::UncheckedUnwrap;

use crate::{IntoSendStorage, Storage, entity::EntitiesStorage, storage::{FastIndexExt, ReadOnlyStorage}, sync::{ReadGuardRef, OrderedIndexGuard}, utils::delete_lifetime_mut};
use std::{marker, ops::Deref};
use crate::Component;
use crate::ComponentSend;
use crate::Bitmask;
use crate::entity::Entity;
use super::{
    OrderedData, UnorderedData
};
use crate::storage::{HierarchicalStorage, StorageRef, IntoHierarchicalIter};
use crate::utils::delete_lifetime;
use crate::storage::forest::ForestHierarchicalIter;
use crate::idtree;

/// Operator over hierarchical components that will select an entity's
/// component for read only and apply another operator on it's parent
///
/// ```
/// # #[macro_use] extern crate rinecs_derive;
/// # use rinecs::*;
/// #[derive(HierarchicalComponent, 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();
/// let iter = entities.ordered_iter_for::<ReadAndParentRef<Position, Read<Velocity>>>();
/// for (pos, parent_vel) in iter {
///
/// }
/// ```
pub struct ReadAndParentRef<'a, T, Ref>{
    _marker_t: marker::PhantomData<&'a T>,
    _marker_ref: marker::PhantomData<Ref>,
}

pub struct ParentStorageReadRef<'a, S, T, Ref, SRef> {
    storage: S,
    storage_ref: SRef,
    _marker_t: marker::PhantomData<&'a T>,
    _marker_ref: marker::PhantomData<Ref>,
}

impl<'a, 'r, S, T, Ref, SRef> FastIndexExt for ParentStorageReadRef<'a, S, T, Ref, SRef>
where
    T: Component,
    S: Deref<Target = T::Storage>,
    T::Storage: HierarchicalStorage<'a,T>,
    Ref: UnorderedData<'a>,
{
    type FastIndex = idtree::NodeId;
    type StaticTypeId = (T, Ref::Components);

    fn fast_index(&self, guid: usize) -> idtree::NodeId {
        unsafe{ self.storage.ordered_fast_index(guid) }
    }
}

impl<'a, 'r, S, T, Ref, SRef> StorageRef<'r> for ParentStorageReadRef<'a, S, T, Ref, SRef>
where
    T: Component,
    S: Deref<Target = T::Storage>,
    T::Storage: HierarchicalStorage<'a,T>,
    Ref: UnorderedData<'a>,
    SRef: StorageRef<'r>,
{
    type Data = ReadAndParentRef<'a, T, Ref>;
    type Component = (&'r T, Option<SRef::Component>);

    unsafe fn get_fast_unchecked(&'r mut self, idx: idtree::NodeId) -> Self::Component {
        let storage = &self.storage;
        let storage_ref = &mut self.storage_ref;
        let node = storage.fast_get_node(idx);
        let parent = node.parent().and_then(move |p| {
            let guid = storage.guid_for(p.id());
            storage_ref.get(&Entity{ guid })
        });
        let node = delete_lifetime(&node as &T);
        (&node, parent)
    }

    unsafe fn get_unchecked(&'r mut self, guid: usize) -> Self::Component {
        let storage = &self.storage;
        let storage_ref = &mut self.storage_ref;
        let node = storage.get_node(guid);
        let parent = node.parent().and_then(move |p| {
            let guid = storage.guid_for(p.id());
            storage_ref.get(&Entity{ guid })
        });
        let node = delete_lifetime(&node as &T);
        (&node, parent)
    }

    fn contains(&self, guid: usize) -> bool {
        self.storage.contains(guid)
    }
}

impl<'a, 'r, T, Ref> IntoSendStorage<'r> for ParentStorageReadRef<'a, ReadGuardRef<'a, T::Storage>, T, Ref, Ref::Storage>
where
    T: Component,
    T::Storage: HierarchicalStorage<'a,T>,
    Ref: UnorderedData<'a>,
    Ref::Storage: IntoSendStorage<'r>,
{
    type SendStorage = ParentStorageReadRef<'a, &'r T::Storage, T, Ref,  <Ref::Storage as IntoSendStorage<'r>>::SendStorage>;
    fn into_send_storage(&'r mut self) -> Self::SendStorage {
        ParentStorageReadRef{
            storage: &self.storage,
            storage_ref: self.storage_ref.into_send_storage(),
            _marker_t: marker::PhantomData,
            _marker_ref: marker::PhantomData,
        }
    }
}

unsafe impl<'a, S, T, Ref, SRef> ReadOnlyStorage for ParentStorageReadRef<'a, S, T, Ref, SRef>
where SRef: ReadOnlyStorage
{}

pub struct ReadAndParentRefIter<'a, S, T, Ref, SRef>
where
    T: Component,
    Ref: UnorderedData<'a>,

{
    it: Option<ForestHierarchicalIter<'a, T>>,
    storage: Option<ParentStorageReadRef<'a, S, T, Ref, SRef>>,
}

impl<'a,S,T,Ref,SRef> Iterator for ReadAndParentRefIter<'a, S, T, Ref, SRef>
where
    T: Component,
    S: Deref<Target = T::Storage>,
    T::Storage: HierarchicalStorage<'a,T>,
    Ref: UnorderedData<'a> + 'a,
    SRef: StorageRef<'a> + 'a,
{
    type Item = (&'a T, Option<SRef::Component>);
    fn next(&mut self) -> Option<Self::Item>{
        let storage = self.storage.as_mut()?;
        let it = unsafe{ self.it.as_mut().unchecked_unwrap() };
        it.next().map(|n| {
            let n_ref = unsafe{ delete_lifetime(&n as &T) };
            let p = n.parent().and_then(|p| unsafe {
                let storage_ref = delete_lifetime_mut(&mut storage.storage_ref);
                let guid = storage.storage.guid_for(p.id());
                storage_ref.get(&Entity{ guid })
            });
            (n_ref, p)
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.it.as_ref().map(|it| it.size_hint()).unwrap_or((0, None))
    }
}


impl<'a, T, Ref> OrderedData<'a> for ReadAndParentRef<'a,T,Ref>
where
    for<'b> <T as Component>::Storage: HierarchicalStorage<'b,T>,
    for<'b> ReadGuardRef<'b, <T as Component>::Storage>: IntoHierarchicalIter<'b,T>,
    T: ComponentSend,
    Ref: UnorderedData<'a>,
{
    type Iter = ReadAndParentRefIter<'a, ReadGuardRef<'a, T::Storage>, T, Ref, Ref::Storage>;
    type Components = T;
    type ComponentsRef = (&'a T, Option<<Ref as UnorderedData<'a>>::ComponentsRef>);
    type Storage = ParentStorageReadRef<'a, ReadGuardRef<'a, T::Storage>, T, Ref, Ref::Storage>;

    fn query_mask<E: EntitiesStorage>(entities: &E) -> Bitmask{
        Bitmask::has(entities.component_mask::<T>())
    }

    fn into_iter<E: EntitiesStorage>(entities: &'a E) -> Self::Iter{
        let storage = <Self as OrderedData>::storage(entities);
        ReadAndParentRefIter{
            it: entities.storage::<T>().map(|s| s.into_hierarchical_iter()),
            storage,
        }
    }

    fn storage<E: EntitiesStorage>(entities: &'a E) -> Option<Self::Storage>{
        Some(ParentStorageReadRef{
            storage: entities.storage::<T>()?,
            storage_ref: Ref::storage(entities)?,
            _marker_t: marker::PhantomData,
            _marker_ref: marker::PhantomData,
        })
    }

    fn ordered_ids<S: FastIndexExt, E: EntitiesStorage>(entities: &'a E, query_mask: Bitmask, unordered_storage: &S) -> OrderedIndexGuard<'a>{
        entities.ordered_entities_for::<T,S>(query_mask, unordered_storage)
    }
}