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
//!
//! # User guide
//!
//! There are four flavors of the same fundamental raycast api provided in this module.
//! There is a naive version, and there is a version that uses the tree, and there are mutable versions of those 
//! that return mutable references.
//!
//! 
//! In addition to the tree, the user provides the geometric functions needed by passing an implementation of RayTrait.
//! The user must also provide a rectangle within which all objects that the user is interested in possibly
//! being hit by the raycast must include. 
//!
//! What is returned is the distance to where the ray cast stopped, plus a list of all bots at that distance. 
//! In most cases, only one object is returned, but in the cases where they are ties more can be returned. 
//! All possible solutions are returned since it would be hard to define which of the tied objects would be returned.
//! So the Option returns Some() if and only if the list returned has atleast one element in it.
//!
//! # Notes

//! At first the algorithm worked by splitting the ray into two where the ray intersected the divider.
//! So one ray would have the same origin point, and the other would have the point at which the ray
//! intersected the divder as the origin point. The problem with this is that there might not be a clean solution
//! to the new point of the second ray. The point that you compute may not lie exactly on a point along the ray. 
//!
//! With real numbers this isnt a problem. There would always be a solution. But real numbers don't exist
//! in the real world. Floating points will be close, but not perfect. If you are using integers, the corner case problems
//! are more apparent.
//! 
//! The solution instead was to never subdivide the ray. Its always the same. Instead, keep subdividing the area into rectangles.
//!
//! Why does the user have to provide a finite rectangle up front? The reason is implementation simplicity/performance.
//! By doing this, we don't have to special case the nodes along the outside of the tree.
//! We also don't have have to worry about overflow and underflow problems of providing a rectangle that 
//! just barely fits into the number type.
//! 

use crate::query::inner_prelude::*;
use core::cmp::Ordering;
use core::convert::TryFrom;

///A Ray.
#[derive(Debug, Copy, Clone)]
pub struct Ray<N> {
    pub point: Vec2<N>,
    pub dir: Vec2<N>,
}

impl<N> Ray<N>{
    

    #[inline(always)]
    pub fn inner_into<B:From<N>>(self)->Ray<B>{
        let point=self.point.inner_into();
        let dir=self.dir.inner_into();
        Ray{point,dir}
    }
    #[inline(always)]
    pub fn inner_try_into<B:TryFrom<N>>(self)->Result<Ray<B>,B::Error>{
        let point=self.point.inner_try_into();
        let dir=self.dir.inner_try_into();
        match(point,dir){
            (Ok(point),Ok(dir))=>{
                Ok(Ray{point,dir})
            },
            (Err(e),Ok(_))=>{
                Err(e)
            },
            (Ok(_),Err(e))=>{
                Err(e)
            },
            (Err(e),Err(_))=>{
                Err(e)
            }
        }
    }
}

impl<N:NumTrait> Ray<N>{
    fn range_side(&self,axis:impl axgeom::AxisTrait,range:&Range<N>)->Ordering{
        
        let v=if axis.is_xaxis(){
            self.point.x
        }else{
            self.point.y
        };

        range.contains_ext(v)
    }
}



///Describes if a ray hit a rectangle.
#[derive(Copy, Clone, Debug)]
pub enum RayIntersectResult<N> {
    Hit(N),
    NoHit
}

impl<N> RayIntersectResult<N>{
    pub fn inner_into<K:From<N>>(self)->RayIntersectResult<K>{
        use RayIntersectResult::*;
        match self{
            Hit(k)=>{
                Hit(K::from(k))
            },
            NoHit=>{
                NoHit
            }
        }
    }
    pub fn inner_try_into<K:TryFrom<N>>(self)->Result<RayIntersectResult<K>,K::Error>{
        use RayIntersectResult::*;
        match self{
            Hit(k)=>{
                match K::try_from(k){
                    Ok(k)=>{
                        Ok(Hit(k))
                    },
                    Err(k)=>{
                        Err(k)
                    }
                }
            },
            NoHit=>{
                Ok(NoHit)
            }
        }
    }
}

///This is the trait that defines raycast specific geometric functions that are needed by this raytracing algorithm.
///By containing all these functions in this trait, we can keep the trait bounds of the underlying NumTrait to a minimum
///of only needing Ord.
pub trait RayTrait{
    type N:NumTrait;
    type T:HasAabb<Num=Self::N>;

    ///Returns the length of ray between its origin, and where it intersects the line provided.
    ///Returns none if the ray doesnt intersect it.
    ///We use this to further prune nodes.If the closest possible distance of a bot in a particular node is 
    ///bigger than what we've already seen, then we dont need to visit that node.
    //fn compute_distance_to_line<A:AxisTrait>(&mut self,axis:A,line:Self::N)->Option<Self::N>;

    ///The expensive collision detection
    ///This is where the user can do expensive collision detection on the shape
    ///contains within it's bounding box.
    ///Its default implementation just calls compute_distance_to_rect()
    fn compute_distance_to_bot(&self,ray:&Ray<Self::N>,a:&Self::T)->RayIntersectResult<Self::N>{
        self.compute_distance_to_rect(ray,a.get())
    }

    ///Returns true if the ray intersects with this rectangle.
    ///This function allows as to prune which nodes to visit.
    fn compute_distance_to_rect(&self,ray:&Ray<Self::N>,a:&Rect<Self::N>)->RayIntersectResult<Self::N>;
}






fn make_rect_from_range<A:AxisTrait,N:NumTrait>(axis:A,range:&Range<N>,rect:&Rect<N>)->Rect<N>{
    if axis.is_xaxis(){
        Rect{x:*range,y:rect.y}
    }else{
        Rect{x:rect.x,y:*range}
    }
}



     
struct Closest<'a,T:HasAabb>{
    closest:Option<(Vec<ProtectedBBox<'a,T>>,T::Num)>
}
impl<'a,T:HasAabb> Closest<'a,T>{
    fn consider<R:RayTrait<N=T::Num,T=T>>(&mut self,ray:&Ray<T::Num>, b:ProtectedBBox<'a,T>,raytrait:&mut R){

        let x=match raytrait.compute_distance_to_bot(ray,b.as_ref()){
            RayIntersectResult::Hit(val)=>{
                val
            },
            RayIntersectResult::NoHit=>{
                return;
            },
        };

        match self.closest.as_mut(){
            Some(mut dis)=>{
                match x.cmp(&dis.1){
                    Ordering::Greater=>{
                        //dis
                        //do nothing.
                    },
                    Ordering::Less=>{
                        dis.0.clear();
                        dis.0.push(b);
                        dis.1=x;
                    },
                    Ordering::Equal=>{
                        dis.0.push(b);
                    }
                }
            },
            None=>{
                self.closest=Some((vec![b],x))  
            }
        };
    }

    fn get_dis(&self)->Option<T::Num>{
        match &self.closest{
            Some(x)=>{
                Some(x.1)
            },
            None=>{
                None
            }
        }
    }
}


struct Blap<'a:'b,'b,R:RayTrait>{
    rtrait:&'b mut R,
    ray:Ray<R::N>,
    closest:Closest<'a,R::T>
}
impl<'a:'b,'b,R:RayTrait> Blap<'a,'b,R>{
    fn should_handle_rect(&mut self,rect:&Rect<R::N>)->bool{
        match self.rtrait.compute_distance_to_rect(&self.ray,rect){
            RayIntersectResult::Hit(val)=>{

                match self.closest.get_dis(){
                    Some(dis)=>{
                        if val<=dis{
                            return true;
                        }        
                    },
                    None=>{
                        return true;
                    }
                }   
                
            },
            RayIntersectResult::NoHit=>{

            }
        }
        false
    } 
}

//Returns the first object that touches the ray.
fn recc<'a:'b,'b,
    A: AxisTrait,
    //T: HasAabb,
    N:NodeTrait,
    R: RayTrait<N=N::Num,T=N::T>
    >(axis:A,stuff:LevelIter<VistrMut<'a,N>>,rect:Rect<N::Num>,blap:&mut Blap<'a,'b,R>){

    let ((_depth,nn),rest)=stuff.next();
    let nn=nn.get_mut();
    match rest{
        Some([left,right])=>{
            let axis_next=axis.next();

            let div=match nn.div{
                Some(b)=>b,
                None=>return
            };

            let (rleft,rright) = rect.subdivide(axis,*div);


            let range = &match nn.cont{
                Some(range)=>{
                    *range
                },
                None=>{
                    Range{start:*div,end:*div}
                }
            };


            
            let rmiddle=make_rect_from_range(axis,range,&rect);


            match blap.ray.range_side(axis,range){
                Ordering::Less=>{
                    if blap.should_handle_rect(&rleft){
                        recc(axis_next,left,rleft,blap);
                    }
                   

                    if blap.should_handle_rect(&rmiddle){
                        for b in nn.bots.iter_mut(){
                            blap.closest.consider(&blap.ray,b,blap.rtrait);
                        }
                    }

                    if blap.should_handle_rect(&rright){
                        recc(axis_next,right,rright,blap);
                    }
                },
                Ordering::Greater=>{
                    
                    if blap.should_handle_rect(&rright){
                        recc(axis_next,right,rright,blap);
                    }
                    
                    
                    if blap.should_handle_rect(&rmiddle){
                        for b in nn.bots.iter_mut(){
                            blap.closest.consider(&blap.ray,b,blap.rtrait);
                        }
                    }


                    if blap.should_handle_rect(&rleft){
                        recc(axis_next,left,rleft,blap);
                    }
                },
                Ordering::Equal=>{
                            
                    if blap.should_handle_rect(&rmiddle){
                        for b in nn.bots.iter_mut(){
                            blap.closest.consider(&blap.ray,b,blap.rtrait);
                        }
                    }

                    if blap.should_handle_rect(&rleft){
                        recc(axis_next,left,rleft,blap);
                    }
                    
                    if blap.should_handle_rect(&rright){
                        recc(axis_next,right,rright,blap);
                    }
                }
            }

        },
        None=>{
            
            //Can't do better here since for leafs, cont is none.
            for b in nn.bots.iter_mut(){
                blap.closest.consider(&blap.ray,b,blap.rtrait);
            } 

        
        }
    }
}


pub use self::mutable::raycast_naive_mut;
pub use self::mutable::raycast_mut;


pub enum RayCastResult<'a,T:HasAabb>{
    Hit(Vec<ProtectedBBox<'a,T>>,T::Num),
    NoHit
}


mod mutable{
    use super::*;

    pub fn raycast_naive_mut<
        'a,
        T:HasAabb,
        >(bots:ProtectedBBoxSlice<'a,T>,ray:Ray<T::Num>,rtrait:&mut impl RayTrait<N=T::Num,T=T>)->RayCastResult<'a,T>{
        let mut closest=Closest{closest:None};

        for b in bots.iter_mut(){
            closest.consider(&ray,b,rtrait);
        }


        match closest.closest{
            Some((a,b))=>{
                RayCastResult::Hit(a,b)
            },
            None=>{
                RayCastResult::NoHit
            }
        }
    }

    pub fn raycast_mut<
        'a,   
        A:AxisTrait,
        N:NodeTrait
        >(tree:&'a mut DinoTree<A,N>,rect:Rect<N::Num>,ray:Ray<N::Num>,rtrait:&mut impl RayTrait<N=N::Num,T=N::T>)->RayCastResult<'a,N::T>{
        
        let axis=tree.axis();
        let dt = tree.vistr_mut().with_depth(Depth(0));


        let closest=Closest{closest:None};
        let mut blap=Blap{rtrait,ray,closest};
        recc(axis,dt,rect,&mut blap);

        match blap.closest.closest{
            Some((a,b))=>{
                RayCastResult::Hit(a,b)
            },
            None=>{
                RayCastResult::NoHit
            }
        }
    }
}