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
use std::collections::{hash_map::{Values, ValuesMut}, HashMap};
use glam::Vec2;
use serde::{Deserialize, Serialize};
pub const CHUNK_SIZE: usize = 16;

/// Index used internally to identify an element within a cell
#[derive(PartialEq, Eq, Debug, Hash, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct Index {
    x: u32,
    y: u32,
}

/// Index used internally to identify a chunk within a grid
#[derive(PartialEq, Eq, Debug, Hash, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct ChunkIndex {
    x: u32,
    y: u32,
}

impl From<(i32, i32)> for Index {
    fn from(value: (i32, i32)) -> Self {
        Self {
            x: (i32::MAX as i64 + 1 + value.0 as i64) as u32,
            y: (i32::MAX as i64 + 1 + value.1 as i64) as u32,
        }
    }
}
impl From<Index> for (i32, i32) {
    fn from(value: Index) -> Self {
        let x = value.x as i64 - i32::MAX as i64 - 1;
        let y = value.y as i64 - i32::MAX as i64 - 1;
        (x as i32, y as i32)
    }
}

impl Index {
    pub fn chunk_index(&self) -> ChunkIndex {
        ChunkIndex {
            x: self.x / CHUNK_SIZE as u32,
            y: self.y / CHUNK_SIZE as u32,
        }
    }
    
    pub fn local_index(&self) -> usize {
        let x = self.x as usize % CHUNK_SIZE;
        let y = self.y as usize % CHUNK_SIZE;
        y * CHUNK_SIZE + x
    }
}

impl ChunkIndex {
    pub fn index(&self) -> Index {
        Index {
            x: self.x * CHUNK_SIZE as u32,
            y: self.y * CHUNK_SIZE as u32
        }
    }
}

/// A `Chunk` of the `Grid`
#[derive(Serialize, Deserialize, Clone)]
pub struct Chunk<T> {
    index:ChunkIndex,
    len:u16,
    inner:Vec<Option<T>>
}

impl<T:Clone> Default for Chunk<T> {
    fn default() -> Self {
        Self { index:Index::from((0, 0)).chunk_index(), len:0, inner: Vec::new() }
    }
}

impl<T:Clone> Chunk<T> {
    /// Gets the top left index of the chunk
    pub fn top_left(&self) -> (i32, i32) {
        self.index.index().into()
    }

    /// Gets the bottom right index of the chunk
    pub fn bottom_right(&self) -> (i32, i32) {
        let p:(i32, i32) = self.index.index().into();
        (p.0 + CHUNK_SIZE as i32 - 1, p.1 + CHUNK_SIZE as i32 - 1)
    }

    /// Get length of the chunk, i.e. how many elements are in the chunk.
    pub fn len(&self) -> usize {
        self.len as usize
    }

    /// Clear all elements from the chunk
    pub fn clear(&mut self) {
        self.len = 0;
        self.inner = Vec::default();
    }

    /// Get element in chunk using local position within the chunk
    pub fn get_local(&self, local:usize) -> Option<&Option<T>> {
        self.inner.get(local)
    }

    /// Insert element into local position
    pub fn insert(&mut self, local:usize, t:T) {
        if self.inner.is_empty() {
            self.inner = vec![None; CHUNK_SIZE * CHUNK_SIZE];
            self.len = 0;
        }
        if self.inner[local].is_none() {
            self.len += 1;
        }
        self.inner[local] = Some(t);
    }

    /// Get element in chunk using local position within the `chunk`
    pub fn get_local_mut(&mut self, local:usize) -> Option<&mut T> {
        let m = self.inner.get_mut(local)?;
        m.as_mut()
    }
}

pub struct ChunkIter<'a, T> {
    index:usize,
    top_left:(i32, i32),
    iter:core::slice::Iter<'a, Option<T>>,
}
impl<'a, T> Iterator for ChunkIter<'a, T> {
    type Item = ((i32, i32), &'a T);
    fn next(&mut self) -> Option<Self::Item> {
        while let Some(next) = self.iter.next() {
            if let Some(cell) = next {
                let index = (self.top_left.0 + self.index as i32 % CHUNK_SIZE as i32, self.top_left.1 + self.index as i32 / CHUNK_SIZE as i32);
                self.index += 1;
                return Some((index, cell));
            }
            self.index += 1;
            continue;
        }

        None
    }
}

pub struct ChunkIterMut<'a, T> {
    index:usize,
    top_left:(i32, i32),
    iter:core::slice::IterMut<'a, Option<T>>,
}
impl<'a, T> Iterator for ChunkIterMut<'a, T> {
    type Item = ((i32, i32), &'a mut T);
    fn next(&mut self) -> Option<Self::Item> {
        while let Some(next) = self.iter.next() {
            if let Some(cell) = next {
                let index = (self.top_left.0 + self.index as i32 % CHUNK_SIZE as i32, self.top_left.1 + self.index as i32 / CHUNK_SIZE as i32);
                self.index += 1;
                return Some((index, cell));
            }
            self.index += 1;
            continue;
        }

        None
    }
}

impl<'a, T:Clone> IntoIterator for &'a Chunk<T> {
    type Item = ((i32, i32), &'a T);
    type IntoIter = ChunkIter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        Self::IntoIter {
            index:0,
            iter: self.inner.iter(),
            top_left: self.top_left()
        }
    }
}

impl<'a, T:Clone> IntoIterator for &'a mut Chunk<T> {
    type Item = ((i32, i32), &'a mut T);
    type IntoIter = ChunkIterMut<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        let top_left = self.top_left();
        Self::IntoIter {
            index:0,
            iter: self.inner.iter_mut(),
            top_left: top_left
        }
    }
}

/// An endless 2D grid of type `T` implemented using chunks
#[derive(Default, Clone, Serialize, Deserialize)]
pub struct Grid<T> {
    chunks: HashMap<ChunkIndex, Chunk<T>>,
}

impl<'a, T> IntoIterator for &'a Grid<T> {
    type Item = &'a Chunk<T>;

    type IntoIter = Values<'a, ChunkIndex, Chunk<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.chunks.values()
    }
}


impl<'a, T> IntoIterator for &'a mut Grid<T> {
    type Item = &'a mut Chunk<T>;

    type IntoIter = ValuesMut<'a, ChunkIndex, Chunk<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.chunks.values_mut()
    }
}

/// Struct used by the `Grid::cast_ray`
pub struct RayVisit<'a, T> {
    /// Current index of the cell being visited
    pub index:(i32, i32),

    /// The cell being visited
    pub cell:&'a T,

    /// Current position of the ray
    pub pos:(f32, f32),
   
    // Distance traveled by the ray
    pub d:f32
}

/// Struct used by the `Grid::astar`
pub struct AStarVisit<'a, T> {
    /// Current index of the cell being visited
    pub index:(i32, i32),

    /// The cell being visited
    pub cell:&'a T,
}

impl<T: Clone> Grid<T> {
    /// Gets length of the grid, aka. how many cells there are
    pub fn len(&self) -> usize {
        let mut len = 0;
        self.chunks.values().for_each(|x|len += x.len());
        len
    }
    /// Gets a immutable reference to `T`
    pub fn get(&self, index: impl Into<(i32, i32)>) -> Option<&T> {
        let index:(i32, i32) = index.into();
        let index = Index::from(index);
        let chunk_index = index.chunk_index();
        let chunk = self.chunks.get(&chunk_index)?;
        let cell = chunk.get_local(index.local_index())?;
        let cell = cell.as_ref()?;
        Some(cell)
    }

    /// Gets an mutable reference to `T`
    pub fn get_mut(&mut self, index: impl Into<(i32, i32)>) -> Option<&mut T> {
        let index:(i32, i32) = index.into();
        let index:Index = index.into();
        let chunk_index = index.chunk_index();
        let chunk = self.chunks.get_mut(&chunk_index)?;
        chunk.get_local_mut(index.local_index())
    }

    /// Insert `T`
    pub fn insert(&mut self, index: impl Into<(i32, i32)>, t: T) {
        let index:(i32, i32) = index.into();
        let index:Index = index.into();
        let chunk_index = index.chunk_index();
        let chunk = match self.chunks.get_mut(&chunk_index) {
            Some(chunk) => chunk,
            None => {
                let mut chunk = Chunk::default();
                chunk.index = chunk_index;
                self.chunks.insert(chunk_index, chunk);
                self.chunks.get_mut(&chunk_index).unwrap()
            }
        };
        let local = index.local_index();
        chunk.insert(local, t);
    }

    /// Perform the A-star algorithm
    /// `F is a function which returns `false` when path is blocked and `true` when not blocked
    pub fn astar<F:Fn(AStarVisit<T>)->bool>(&self, start:impl Into<(i32, i32)>, end:impl Into<(i32, i32)>, visit:F) -> Option<Vec<(i32, i32)>> {
        let start = start.into();
        let end = end.into();
        let p = pathfinding::directed::astar::astar(&start, |(nx, ny)| {
            let (nx, ny) = (*nx, *ny);
            let mut vec:Vec<((i32, i32), i32)> = Vec::with_capacity(4);
            for p in [(nx - 1, ny), (nx + 1, ny), (nx, ny - 1), (nx, ny + 1)] {
                if let Some(tile) = self.get(p) {
                    if !visit(AStarVisit {
                        index: p,
                        cell: tile,
                    }) {
                        vec.push((p, 1));
                    }
                }
            }
            vec
        }, |(nx, ny)|{
            let (vx, vy) = ((nx - end.0).abs(), (ny - end.1).abs());
            vx + vy
        }, |n|{
            n == &end
        });
        if let Some((vec, _)) = p {
            return Some(vec);
        }

        None
    }

    /// Casts a ray from `start` to `end` and call a function `F` for each cell visited
    /// 
    /// The ray will be traced until `F` returns `false` or untill `end` has been reached
    pub fn cast_ray<F:FnMut(RayVisit<T>)->bool>(&self, start:impl Into<(f32, f32)>, end:impl Into<(f32, f32)>, mut f:F) {
        let start:(f32, f32) = start.into();
        let end:(f32, f32) = end.into();
        let start:Vec2 = start.into();
        let end:Vec2 = end.into();
        fn get_helper(cell_size:f32, pos:f32, dir:f32) -> (f32, f32, f32, f32) {
            let tile = (pos / cell_size).floor();// + 1.0;
            let dtile;
            let dt;
            let mut dir = dir;
            if dir == 0.0 {
                dir = 0.00001; // FIXME: avoid divide by zero but can be solved better
            }
            if dir > 0.0 {
                dtile = 1.0;
                dt = ((tile + 1.0) * cell_size - pos) / dir;
            } else {
                dtile = -1.0;
                dt = (tile  * cell_size - pos) / dir;
            }
    
            (tile, dtile, dt, dtile * cell_size / dir)
        }
        let v = end - start;
        let dir = v.normalize_or_zero();
        if dir.length() == 0.0 {
            return;
        }
        let (mut tile_x, dtile_x, mut dt_x, ddt_x) = get_helper(1.0, start.x, dir.x);
        let (mut tile_y, dtile_y, mut dt_y, ddt_y) = get_helper(1.0, start.y, dir.y);
    
        let mut t = 0.0;
        if dir.x*dir.x + dir.y*dir.y > 0.0 {
            loop {
                if v.length() < t {
                    break;
                }
                let index = (tile_x as i32, tile_y as i32);
                if let Some(cell) = self.get(index) {
                    if !f(RayVisit {index, cell, d:t, pos:(tile_x, tile_y) }) {
                        break;
                    }
                } else {
                    break;
                }
                if dt_x < dt_y {
                    tile_x += dtile_x;
                    let dt = dt_x;
                    t += dt;
                    dt_x = dt_x + ddt_x - dt;
                    dt_y -= dt;
                } else {
                    tile_y += dtile_y;
                    let dt = dt_y;
                    t += dt;
                    dt_x -= dt;
                    dt_y = dt_y + ddt_y - dt;
                }
            }
        } 
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn index_test() {
        let p1: Index = (0, 0).into();
        let p2: Index = (0, 0).into();
        assert_eq!(p1, p2);
        let p1: Index = (5, 3).into();
        let p2: Index = (5, 3).into();
        assert_eq!(p1, p2);
        let p1: Index = (1, 2).into();
        let p2: Index = (2, 1).into();
        assert_ne!(p1, p2);
        let p1: Index = (i32::MIN, i32::MAX).into();
        let p2: Index = (i32::MIN, i32::MAX).into();
        assert_eq!(p1, p2);

        let p1: Index = (0, 0).into();
        let p2: Index = (15, 15).into();
        assert_ne!(p1, p2);
        assert_eq!(p1.chunk_index(), p2.chunk_index());

        let p1: Index = (-7, -7).into();
        let p2: Index = (-9, -9).into();
        assert_ne!(p1, p2);
        assert_eq!(p1.chunk_index(), p2.chunk_index());

        let p1: Index = (CHUNK_SIZE as i32 * 10, CHUNK_SIZE as i32 * 10).into();
        let p2 = p1.chunk_index().index();
        assert_eq!(p1, p2);
        let p1: Index = (CHUNK_SIZE as i32 * -10, CHUNK_SIZE as i32 * -10).into();
        let p2 = p1.chunk_index().index();
        assert_eq!(p1, p2);

        let p1 = (1024, 5431);
        let p2:Index = p1.into();
        let p2:(i32, i32) = p2.into();
        assert_eq!(p1, p2);

        let p1 = (-1024, -5431);
        let p2:Index = p1.into();
        let p2:(i32, i32) = p2.into();
        assert_eq!(p1, p2);
    }

    #[test]
    fn chunk_test() {
        #[derive(Clone)]
        struct Test;
        let mut chunk = Chunk::default() as Chunk<Test>;
        assert_eq!(chunk.inner.len(), 0);
        assert_eq!(chunk.len(), 0);
        chunk.insert(0, Test);
        assert_eq!(chunk.inner.len(), CHUNK_SIZE * CHUNK_SIZE);
        assert_eq!(chunk.len(), 1);
        chunk.insert(0, Test);
        assert_eq!(chunk.len(), 1);
        chunk.insert(1, Test);
        assert_eq!(chunk.len(), 2);
        chunk.clear();
        assert_eq!(chunk.len(), 0);
        assert_eq!(chunk.inner.len(), 0);

        let chunk = Chunk::default() as Chunk<Test>;
        assert_eq!(chunk.top_left(), (0, 0));
        assert_eq!(chunk.bottom_right(), (CHUNK_SIZE as i32 -1, CHUNK_SIZE as i32 -1));

        let mut chunk = Chunk::default() as Chunk<Test>;
        let p = (-1024, -1024);
        let chunk_index = Index::from(p).chunk_index();
        chunk.index = chunk_index;

        assert_eq!(chunk.top_left(), p);
        assert_eq!(chunk.bottom_right(), (p.0 + CHUNK_SIZE as i32 - 1, p.1 + CHUNK_SIZE as i32 -1 ));
        //assert_eq!(chunk.bottom_right(), (CHUNK_SIZE as i32 -1, CHUNK_SIZE as i32 -1));
    }

    #[test]
    fn grid_test() {
        let mut grid = Grid::default() as Grid<(i32, i32)>;
        let size = 33;
        for y in -size..size {
            for x in -size..size {
                let p = (x, y);
                grid.insert(p, p);
                let p2 = grid.get(p).unwrap();
                assert_eq!(&p, p2);
                grid.get_mut(p).unwrap().0 = 0;
                grid.get_mut(p).unwrap().1 = 0;
                let p2 = grid.get_mut(p).unwrap();
                assert_eq!(p2, &mut (0, 0));
            }
        }

        let bincoded = bincode::serialize(&grid).unwrap();
        let grid2:Grid<(i32, i32)> = bincode::deserialize(&bincoded).unwrap();
        for y in -size..size {
            for x in -size..size {
                let p = (x, y);
                let g1 = grid.get(p);
                let g2 = grid2.get(p);
                assert_eq!(g1, g2);
            }
        }
    }

    #[test]
    fn grid_test2() {
        let mut grid = Grid::default() as Grid<(i32, i32)>;
        let size = 64;
        for y in 0..size {
            for x in 0..size {
                let p = (x, y);
                grid.insert(p, p);
            }
        }
        assert_eq!(grid.len(), size as usize * size as usize);
    }

    #[test]
    fn grid_test3() {
        let mut grid = Grid::default() as Grid<(i32, i32)>;
        let size: i32 = 33;
        let mut inserted = 0;
        for y in -size..size {
            for x in -size..size {
                let p = (x, y);
                grid.insert(p, p);
                inserted += 1;
            }
        }

        let mut read = 0;
        for chunk in &grid {
            for (p, cell) in chunk {
                assert_eq!(p, *cell);
                read += 1;
            }
        }
        assert_eq!(read, inserted);

        let mut read = 0;
        for chunk in &mut grid {
            for (_, cell) in chunk {
                *cell = Default::default();
                assert_eq!((0,0), *cell);
                read += 1;
            }
        }
        assert_eq!(read, inserted);
    }

    #[test]
    fn grid_test4() {
        let mut grid = Grid::default() as Grid<(i32, i32)>;
        let values = vec![(14, 0), (-1011,32), (-6654,-213), (5543,123), (65645, 12312), (0, 0)];
        for v in values.iter() {
            grid.insert(v.to_owned(), v.to_owned());
        }
        
        let mut count = 0;
        for chunk in &grid {
            for cell in chunk {
                assert_eq!(cell.0.to_owned(), cell.1.to_owned());
                count += 1;
            }
        }

        assert_eq!(count, values.len());
        assert_eq!(grid.len(), values.len());
    }

    #[test]
    fn grid_serde_test() {
        let mut grid = Grid::default() as Grid<(i32, i32)>;
        let size = 64;
        for y in -size..size {
            for x in -size..size {
                let p = (x, y);
                grid.insert(p, p);
            }
        }

        let bincoded = bincode::serialize(&grid).unwrap();
        let grid2:Grid<(i32, i32)> = bincode::deserialize(&bincoded).unwrap();
        for y in -size..size {
            for x in -size..size {
                let p = (x, y);
                let g1 = grid.get(p);
                let g2 = grid2.get(p);
                assert_eq!(g1, g2);
            }
        }
    }

    #[test]
    fn raycast_test() {
        let mut grid = Grid::default() as Grid<bool>;
        for y in 0..8 {
            for x in 0..8 {
                grid.insert((x, y), x == 4 && y == 4);
            }
        }
        let mut last_hit = (0, 0);
        let mut last_pos_before_hit = (0.0, 0.0);
        grid.cast_ray((0.5, 0.5), (7.5, 7.5), |v| {
            if *v.cell {
                last_hit = v.index;
                return false;
            } 
            last_pos_before_hit = v.pos;

            true
        });

        assert_eq!(last_hit, (4, 4));
        assert_eq!(last_pos_before_hit, (3.0, 4.0));
    }

    #[test]
    fn astar_test() {
        let mut grid = Grid::default() as Grid<bool>;
        for y in 0..8 {
            for x in 0..8 {
                grid.insert((x, y), x == 4 && y != 7);
            }
        }

        assert!(!(*grid.get((4,7)).unwrap()));

        let path = grid.astar((0,0), (7,0), |x|{
            *x.cell
        });

        assert!(path.is_some());
        let path = path.unwrap();
        assert_eq!(*path.last().unwrap(), (7,0));
        assert_eq!(*path.first().unwrap(), (0,0));
        assert!(path.iter().any(|x| *x == (4,7)));
    }
}