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
//! Container trees that deref to `broccoli::Tree`
//! ```ignore
//! The relationships between Tree types:
//!
//! TreeOwned -> TreeRef --> Tree
//! TreeOwnedInd -> TreeRefInd --> TreeRef --> Tree
//!
//! where:
//! --> = Deref
//! -> = Function
//! ```
//! [`TreeRef`], like [`Tree`], can be composed of anything that implements [`Aabb`].
//! [`TreeRefInd`] is composed of `BBox<N,&mut T>`
//!
//! ### Overview
//!
//! [`Tree`] is written in safe rust, and for most usecases,
//! using [`Tree`] is enough. But in certain cases
//! we want more control. The container trees in this module are for this purpose.
//!
//! For example, with the regular [`Tree`], you can't
//! get access to the unerlying list of elements after
//! the tree has been constructed.
//!
//! ```rust,compile_fail
//! use broccoli::prelude::*;
//! let mut k=[bbox(rect(0,10,0,10),8)];
//! let mut b=broccoli::new(&mut k);
//! b.find_intersections_mut(|a,b|{});
//! k[0].inner=4;    //<---cannot re-borrow
//! b.find_intersections_mut(|a,b|{});
//! ```
//! This is because `broccoli::Tree` constructs itself by splitting up the
//! passed mutable slice to the point where the original mutable slice
//! can't be retrieved.
//!
//! If we use `TreeRef`, we can do the above like this:
//! ```rust
//! use broccoli::prelude::*;
//! let mut k=[bbox(rect(0,10,0,10),8)];
//! let mut b=broccoli::collections::TreeRef::new(&mut k);
//! b.find_colliding_pairs_mut(|a,b|{});
//! *b.get_bbox_elements_mut().get_index_mut(0).inner_mut()=5;
//! b.find_colliding_pairs_mut(|a,b|{});
//! ```
//!
//! This is good and all, but having to work around the PMut<T> pointer
//! that protect the invariants of the tree is cumbersome. To get around that
//! we can use `TreeRefInd` which adds a layer of indirection. 
//!
//! Unintuitively, this version that adds a layer of indirection is typically faster.
//! Check the crate's book for more analysis. This does have some drawbacks
//! in the sense that it uses more memory, as the aabbs are copied.
//! Additionally, `TreeRefInd` provides `collect` functions that allow 
//! storing query results that can then be iterated through multiple times
//! quickly.
//!
//! ```rust
//! use broccoli::prelude::*;
//! let mut k=[0];
//! let mut b=broccoli::collections::TreeRefInd::new(&mut k,|&mut d|rect(d,d,d,d));
//! b.find_colliding_pairs_mut(|a,b|{});
//! b.get_elements_mut()[0]=5;
//! b.find_colliding_pairs_mut(|a,b|{});
//! ```
//!
//! `TreeRef` and `TreeRefInd` are both lifetimed. If you want to store the tree
//! inside an object there are `TreeOwned` and `TreeOwnedInd` equivalents.
//!
//! ## An owned `(Rect<N>,T)` example
//!
//! ```rust
//! use broccoli::{prelude::*,collections::*,DefaultA};
//!
//! fn not_lifetimed()->TreeOwned<DefaultA,BBox<i32,f32>>
//! {
//!     let a=vec![bbox(rect(0,10,0,10),0.0)].into_boxed_slice();
//!     TreeOwned::new(a)
//! }
//!
//! not_lifetimed();
//!
//! ```
//!
//! ## An owned `(Rect<N>,*mut T)` example
//!
//! ```rust
//! use axgeom::*;
//! use broccoli::{*,collections::*,DefaultA};
//!
//! fn not_lifetimed()->TreeOwnedInd<DefaultA,i32,Vec2<i32>>
//! {
//!     let rect=vec![vec2(0,10),vec2(3,30)].into_boxed_slice();
//!     TreeOwnedInd::new(rect,|&mut p|{
//!         let radius=vec2(10,10);
//!         Rect::from_point(p,radius)
//!     })
//! }
//!
//! not_lifetimed();
//!
//! ```

use super::*;

mod collect;
pub use self::collect::*;
use alloc::boxed::Box;
mod inner;

#[repr(transparent)]
struct Ptr<T: ?Sized>(*mut T);
impl<T: ?Sized> Copy for Ptr<T> {}

impl<T: ?Sized> Clone for Ptr<T> {
    #[inline(always)]
    fn clone(&self) -> Ptr<T> {
        *self
    }
}
unsafe impl<T: ?Sized> Send for Ptr<T> {}
unsafe impl<T: ?Sized> Sync for Ptr<T> {}


pub struct TreeRefInd<'a, A: Axis, N: Num, T> {
    tree: inner::TreeIndInner<A,N,T>,
    _p: PhantomData<&'a mut (T, N)>,
}

impl<'a, N: Num, T> TreeRefInd<'a, DefaultA, N, T> {
    pub fn new(
        arr: &'a mut [T],
        func: impl FnMut(&mut T) -> Rect<N>,
    ) -> TreeRefInd<'a, DefaultA, N, T> {
        Self::with_axis(default_axis(),arr,func)
    }
}

impl<'a, N: Num, T:Send+Sync> TreeRefInd<'a, DefaultA, N, T> {
    pub fn new_par(
        arr: &'a mut [T],
        func: impl FnMut(&mut T) -> Rect<N>,
    ) -> TreeRefInd<'a, DefaultA, N, T> {
        Self::with_axis_par(default_axis(),arr,func)
    }
}

impl<'a, A: Axis, N: Num, T:Send+Sync> TreeRefInd<'a, A, N, T> {
    pub fn with_axis_par(
        axis: A,
        arr: &'a mut [T],
        func: impl FnMut(&mut T) -> Rect<N>,
    ) -> TreeRefInd<'a, A, N, T> {
        TreeRefInd{tree:inner::TreeIndInner::with_axis_par(axis,arr,func),_p:PhantomData}       
    }
}
impl<'a, A: Axis, N: Num, T> TreeRefInd<'a, A, N, T> {
    pub fn with_axis(
        axis: A,
        arr: &'a mut [T],
        func: impl FnMut(&mut T) -> Rect<N>,
    ) -> TreeRefInd<'a, A, N, T> {
        TreeRefInd{tree:inner::TreeIndInner::with_axis(axis,arr,func),_p:PhantomData}             
    }
    pub fn get_elements(&self) -> &[T] {
        unsafe { &*self.tree.orig.0 }
    }
    pub fn get_elements_mut(&mut self) -> &'a mut [T] {
        unsafe { &mut *self.tree.orig.0 }
    }
}

impl<'a, A: Axis, N: Num + 'a, T> core::ops::Deref for TreeRefInd<'a, A, N, T> {
    type Target = TreeRef<'a, A, BBox<N, &'a mut T>>;
    fn deref(&self) -> &Self::Target {
        //TODO do these in one place
        unsafe { &*(self.tree.inner.as_tree() as *const _ as *const _) }
    }
}
impl<'a, A: Axis, N: Num + 'a, T> core::ops::DerefMut for TreeRefInd<'a, A, N, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        //TODO do these in one place
        unsafe { &mut *(self.tree.inner.as_tree_mut() as *mut _ as *mut _) }
    }
}

pub struct TreeRef<'a, A: Axis, T: Aabb> {
    tree: inner::TreeRefInner<A, T>,
    _p: PhantomData<&'a mut T>,
}

impl<'a, A: Axis, T: Aabb> core::ops::Deref for TreeRef<'a, A, T> {
    type Target = Tree<'a, A, T>;
    fn deref(&self) -> &Self::Target {
        //TODO do these in one place
        unsafe { &*(&self.tree.inner as *const _ as *const _) }
    }
}
impl<'a, A: Axis, T: Aabb> core::ops::DerefMut for TreeRef<'a, A, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        //TODO do these in one place
        unsafe { &mut *(&mut self.tree.inner as *mut _ as *mut _) }
    }
}

impl<'a, T: Aabb> TreeRef<'a, DefaultA, T> {
    pub fn new(arr: &'a mut [T]) -> TreeRef<'a, DefaultA, T> {
        TreeRef::with_axis(default_axis(), arr)
    }
}

impl<'a, T: Aabb + Send + Sync> TreeRef<'a, DefaultA, T> {
    pub fn new_par(arr: &'a mut [T]) -> TreeRef<'a, DefaultA, T> {
        TreeRef::with_axis_par(default_axis(), arr)
    }
}

impl<'a, A: Axis, T: Aabb + Send + Sync> TreeRef<'a, A, T> {
    pub fn with_axis_par(a: A, arr: &'a mut [T]) -> TreeRef<'a, A, T> {
        TreeRef {
            tree: inner::TreeRefInner::with_axis_par(a,arr),
            _p: PhantomData,
        }
    }
}

impl<'a, A: Axis, T: Aabb> TreeRef<'a, A, T> {
    pub fn with_axis(a: A, arr: &'a mut [T]) -> TreeRef<'a, A, T> {
        TreeRef {
            tree: inner::TreeRefInner::with_axis(a,arr),
            _p: PhantomData,
        }
    }
    pub fn get_bbox_elements(&self) -> &[T] {
        unsafe { &*self.tree.orig.0 }
    }
    pub fn get_bbox_elements_mut(&mut self) -> PMut<'a, [T]> {
        PMut::new(unsafe { &mut *self.tree.orig.0 })
    }
}

///A Node in a Tree.
pub(crate) struct NodePtr<T: Aabb> {
    _range: PMutPtr<[T]>,

    //range is empty iff cont is none.
    _cont: Option<axgeom::Range<T::Num>>,
    //for non leafs:
    //  div is some iff mid is nonempty.
    //  div is none iff mid is empty.
    //for leafs:
    //  div is none
    _div: Option<T::Num>,
}

pub struct TreeOwnedInd<A: Axis, N: Num, T> {
    tree:inner::TreeIndInner<A,N,T>,
    _bots: Box<[T]>,
}

impl<N: Num, T: Send + Sync> TreeOwnedInd<DefaultA, N, T> {
    pub fn new_par(bots: Box<[T]>, func: impl FnMut(&mut T) -> Rect<N>) -> TreeOwnedInd<DefaultA, N, T> {
        TreeOwnedInd::with_axis_par(default_axis(), bots, func)
    }
}
impl<A: Axis, N: Num, T: Send + Sync> TreeOwnedInd<A, N, T> {
    pub fn with_axis_par(
        axis: A,
        mut bots: Box<[T]>,
        func: impl FnMut(&mut T) -> Rect<N>,
    ) -> TreeOwnedInd<A, N, T> {
     

        TreeOwnedInd { tree:inner::TreeIndInner::with_axis_par(axis,&mut bots,func), _bots:bots }
    }
}

impl<N: Num, T> TreeOwnedInd<DefaultA, N, T> {
    pub fn new(bots: Box<[T]>, func: impl FnMut(&mut T) -> Rect<N>) -> TreeOwnedInd<DefaultA, N, T> {
        Self::with_axis(default_axis(), bots, func)
    }
}
impl<A: Axis, N: Num, T> TreeOwnedInd<A, N, T> {
    ///Create an owned Tree in one thread.
    pub fn with_axis(
        axis: A,
        mut bots: Box<[T]>,
        func: impl FnMut(&mut T) -> Rect<N>,
    ) -> TreeOwnedInd<A, N, T> {
        TreeOwnedInd { tree:inner::TreeIndInner::with_axis(axis,&mut bots,func), _bots:bots }
    
    }
    ///Cant use Deref because of lifetime
    pub fn as_tree(&self) -> &TreeRefInd<A,N, T> {
        unsafe { &*(&self.tree as *const _ as *const _) }
    }

    ///Cant use Deref because of lifetime
    pub fn as_tree_mut(&mut self) -> &mut TreeRefInd<A,N,T> {
        unsafe { &mut *(&mut self.tree as *mut _ as *mut _) }
    }
}

///An owned Tree componsed of `T:Aabb`
pub struct TreeOwned<A: Axis, T: Aabb> {
    tree: inner::TreeRefInner<A, T>,
    _bots: Box<[T]>,
}

impl<T: Aabb + Send + Sync> TreeOwned<DefaultA, T> {
    pub fn new_par(bots: Box<[T]>) -> TreeOwned<DefaultA, T> {
        TreeOwned::with_axis_par(default_axis(), bots)
    }
}
impl<A: Axis, T: Aabb + Send + Sync> TreeOwned<A, T> {
    pub fn with_axis_par(axis: A, mut bots: Box<[T]>) -> TreeOwned<A, T> {
        TreeOwned {
            tree: inner::TreeRefInner::with_axis_par(axis,&mut bots),
            _bots:bots,
        }
    }
}
impl<T: Aabb> TreeOwned<DefaultA, T> {
    pub fn new(bots: Box<[T]>) -> TreeOwned<DefaultA, T> {
        Self::with_axis(default_axis(), bots)
    }
}
impl<A: Axis, T: Aabb> TreeOwned<A, T> {
    ///Create an owned Tree in one thread.
    pub fn with_axis(axis: A, mut bots: Box<[T]>) -> TreeOwned<A, T> {
        TreeOwned {
            tree: inner::TreeRefInner::with_axis(axis,&mut bots),
            _bots:bots,
        }
    }

    ///Cant use Deref because of lifetime
    pub fn as_tree(&self) -> &TreeRef<A, T> {
        unsafe { &*(&self.tree as *const _ as *const _) }
    }

    ///Cant use Deref because of lifetime
    pub fn as_tree_mut(&mut self) -> &mut TreeRef<A, T> {
        unsafe { &mut *(&mut self.tree as *mut _ as *mut _) }
    }
}