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
use crate::*;
use core::cmp::Ordering;
use core::convert::TryInto;

///Convenience function to create a ray.
#[must_use]
pub fn ray<N>(point: Vec2<N>, dir: Vec2<N>) -> Ray<N> {
    Ray { point, dir }
}

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

impl<B: Copy> Ray<B> {
    #[inline(always)]
    #[must_use]
    pub fn inner_as<C:'static+Copy>(&self) -> Ray<C> where B: num_traits::AsPrimitive<C>{
        ray(self.point.inner_as(),self.dir.inner_as())
    }
}

impl<N: Copy + core::ops::Add<Output = N> + core::ops::Mul<Output = N>> Ray<N> {
    #[inline(always)]
    pub fn point_at_tval(&self, tval: N) -> Vec2<N> {
        self.point + self.dir * tval
    }
}
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>(self) -> Result<Ray<B>, N::Error> where N:TryInto<B> {
        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: PartialOrd + Copy> Ray<N> {
    #[inline(always)]
    pub fn range_side(&self, axis: impl Axis, 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,PartialEq,Eq)]
#[must_use]
pub enum CastResult<N> {
    Hit(N),
    NoHit,
}

impl<N> CastResult<N> {
    #[inline(always)]
    pub fn map<X>(self, mut func: impl FnMut(N) -> X) -> CastResult<X> {
        match self {
            CastResult::Hit(a) => CastResult::Hit(func(a)),
            CastResult::NoHit => CastResult::NoHit,
        }
    }

    #[inline(always)]
    pub fn unwrap(self) -> N {
        match self {
            CastResult::Hit(a) => a,
            CastResult::NoHit => panic!("unwrapped a NoHit in CastResult"),
        }
    }
}


#[cfg(feature = "std")]
pub mod foo{
    use super::*;
    use roots;
    use roots::*;
    impl<N: num_traits::float::FloatCore + roots::FloatType> Ray<N> {
        ///Checks if a ray intersects a circle.
        pub fn cast_to_circle(&self, center: Vec2<N>, radius: N) -> CastResult<N> {
            //https://math.stackexchange.com/questions/311921/get-location-of-vector-circle-intersection
            //circle
            //(x-center.x)^2+(y-center.y)^2=r2
            //ray
            //x(t)=ray.dir.x*t+ray.point.x
            //y(t)=ray.dir.y*t+ray.point.y
            //
            //solve for t.
            //
            //
            //we get:
            //
            //𝑎𝑡^2+𝑏𝑡+𝑐=0
            //
            //
            //
            //
            let ray = self;
            let zz = <N as FloatType>::zero();
            let two = <N as FloatType>::one()+<N as FloatType>::one();

            let a = ray.dir.x.powi(2) + ray.dir.y.powi(2);
            let b =
                two * ray.dir.x * (ray.point.x - center.x) + two * ray.dir.y * (ray.point.y - center.y);
            let c =
                (ray.point.x - center.x).powi(2) + (ray.point.y - center.y).powi(2) - radius.powi(2);

            match find_roots_quadratic(a, b, c) {
                Roots::No(_) => CastResult::NoHit,
                Roots::One([a]) => {
                    if a < zz {
                        CastResult::NoHit
                    } else {
                        CastResult::Hit(a)
                    }
                }
                Roots::Two([a, b]) => {
                    let (closer, further) = if a < b { (a, b) } else { (b, a) };

                    if closer < zz && further < zz {
                        CastResult::NoHit
                    } else if closer < zz && further > zz {
                        CastResult::Hit(<N as FloatType>::zero())
                    } else {
                        CastResult::Hit(closer)
                    }
                }
                _ => unreachable!(),
            }
        }
    }
}



impl<N: num_traits::Num + num_traits::Signed + PartialOrd + Copy  + core::fmt::Debug> Ray<N> {
    
    //if axis is x, then the line is top to bottom
    //if axis is y, then the line is left to right
    pub fn cast_to_aaline<A:Axis>(&self,a:A,line:N)->CastResult<N>{
        let ray=self;
        let  tval=if a.is_xaxis(){
            if ray.dir.x==N::zero(){
                return CastResult::NoHit;
            }
            (line-ray.point.x)/ray.dir.x
        }else{
            if ray.dir.y==N::zero(){
                return CastResult::NoHit;
            }
            (line-ray.point.y)/ray.dir.y
        };

        if tval>N::zero() {
            CastResult::Hit(tval)
        }else{
            CastResult::NoHit
        }
    }    



    fn prune_rect_axis<A:Axis>(&self,tval:N,rect:&Rect<N>,axis:A)->CastResult<N>{
        use CastResult::*;
        
        if axis.is_xaxis(){
            let xx=self.point.x+self.dir.x*tval;
            if rect.x.contains(xx){
                Hit(tval)
            }else{
                NoHit
            }
        }else{
            let yy=self.point.y+self.dir.y*tval;
            if rect.y.contains(yy){
                Hit(tval)
            }else{
                NoHit
            }
        }
        
    }
    pub fn cast_to_rect(&self,rect:&Rect<N>)->CastResult<N>{
        
        if rect.contains_point(self.point){
            return CastResult::Hit(N::zero())
        }
        /*
        https://gamedev.stackexchange.com/questions/18436/most-efficient-aabb-vs-ray-collision-algorithms
        Nobody described the algorithm here, but the Graphics Gems algorithm is simply:
        Using your ray's direction vector, determine which 3 of the 6 candidate planes would be hit first. If your (unnormalized) ray direction vector is (-1, 1, -1), then the 3 planes that are possible to be hit are +x, -y, and +z.
        Of the 3 candidate planes, do find the t-value for the intersection for each. Accept the plane that gets the largest t value as being the plane that got hit, and check that the hit is within the box. The diagram in the text makes this clear:
        */
        let &Rect{x:Range{start:startx,end:endx},y:Range{start:starty,end:endy}}=rect;

        let x=if self.dir.x>=N::zero(){
            startx
        }else{
            endx
        };

        let y=if self.dir.y>=N::zero(){
            starty
        }else{
            endy
        };

        let tval1=self.cast_to_aaline(XAXIS,x);
        let tval2=self.cast_to_aaline(YAXIS,y);

        use CastResult::*;
        match (tval1,tval2){
            (Hit(a),Hit(b))=>{
                //xaxis hit
                if a>b{
                    self.prune_rect_axis(a,rect,YAXIS)
                }else{
                    self.prune_rect_axis(b,rect,XAXIS)
                }
            },
            (Hit(a),NoHit)=>{
                self.prune_rect_axis(a,rect,YAXIS)
            },
            (NoHit,Hit(b))=>{
                self.prune_rect_axis(b,rect,XAXIS)
            },
            (NoHit,NoHit)=>{
                NoHit
            }
        } 
    }

/*
    pub fn find_candidate_planes(&self,rect:&Rect<N>)->[bool;4]{
        //In cases where the ray is directly vertical or horizant, 
        //we technically only need to check one side of the rect.
        //but these cases are so rare, and it doesnt hurt much to check
        //one exra side. So we condense these cases into cases
        //where we check two sides.

        let x=self.dir.x>N::zero();
        let y=self.dir.y>N::zero();
        
        match (x,y){
            (true,true)=>{
                //left top 
            },
            (true,false)=>{
                //left bottom
            },
            (false,true)=>{
                //right top
            },
            (false,false)=>{
                //right bottom
            }
        }

        //Observation to make is that in each case, there was on x and one y coordinate.

        todo!()

    }
*/
    
}