Had a bit of time today and worked on supertux:
[supertux.git] / src / collision_grid_iterator.h
1 #ifndef __COLLISION_GRID_ITERATOR_H__
2 #define __COLLISION_GRID_ITERATOR_H__
3
4 #include "math/rectangle.h"
5
6 using namespace SuperTux;
7
8 class CollisionGrid;
9
10 class CollisionGridIterator
11 {
12 public:
13   CollisionGridIterator(CollisionGrid& newgrid, const Rectangle& bbox)
14     : grid(newgrid)
15   {
16     start_x = int(bbox.p1.x / grid.cell_width) - 2;
17     if(start_x < 0)
18       start_x = 0;
19     x = start_x;
20         
21     y = int(bbox.p1.y / grid.cell_height) - 2;
22     if(y < 0)
23       y = 0;
24     
25     end_x = int(bbox.p2.x / grid.cell_width) + 2;
26     if(end_x > (int) grid.cells_x)
27       end_x = grid.cells_x;
28     
29     end_y = int(bbox.p2.y / grid.cell_height) + 2;
30     if(end_y > (int) grid.cells_y)
31       end_y = grid.cells_y;
32
33     if(start_x >= end_x) {
34       printf("bad region.\n");
35       y = 0;
36       end_y = 0;
37       return;
38     }
39
40     timestamp = grid.iterator_timestamp++;
41     entry = 0;
42   }
43
44   MovingObject* next()
45   {
46     CollisionGrid::ObjectWrapper* wrapper = next_wrapper();
47     if(wrapper == 0)
48       return 0;
49         
50     return wrapper->object;
51   }
52
53 private:
54   friend class CollisionGrid;
55
56   CollisionGrid::ObjectWrapper* next_wrapper() 
57   {
58     CollisionGrid::ObjectWrapper* wrapper;
59     
60     do {
61       while(entry == 0) {
62         if(y >= end_y)
63           return 0;
64         
65         entry = grid.grid[y*grid.cells_x + x];
66         x++;
67         if(x >= end_x) {
68           x = start_x;
69           y++;
70         }
71       }
72       
73       wrapper = entry->object_wrapper;
74       entry = entry->next;
75     } while(wrapper->timestamp == timestamp);
76     
77     wrapper->timestamp = timestamp;
78     
79     return wrapper;
80   }
81     
82   CollisionGrid& grid;
83   CollisionGrid::GridEntry* entry;
84   int x, y;
85   int start_x, end_x, end_y;
86   int timestamp;
87 };
88
89 #endif
90