005eb7f3aa0613f812f0a9a16395e0fab26a6c3a
[supertux.git] / src / collision_grid.hpp
1 //  $Id$
2 // 
3 //  SuperTux
4 //  Copyright (C) 2005 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 // 
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
19 //  02111-1307, USA.
20 #ifndef __COLLISION_GRID_H__
21 #define __COLLISION_GRID_H__
22
23 #include <vector>
24 #include "moving_object.hpp"
25
26 class CollisionGridIterator;
27
28 /**
29  * A rectangular grid to keep track of all moving game objects. It allows fast
30  * queries for all objects in a rectangular area.
31  */
32 class CollisionGrid
33 {
34 public:
35   CollisionGrid(float width, float height);
36   ~CollisionGrid();
37
38   void add_object(MovingObject* object);
39   void remove_object(MovingObject* object);
40
41   void check_collisions();
42
43 private:
44   friend class CollisionGridIterator;
45   
46   struct ObjectWrapper
47   {
48     MovingObject* object;
49     Rect dest;
50     /** (pseudo) timestamp. When reading from the grid the timestamp is
51      * changed so that you can easily avoid reading an object multiple times
52      * when it is in several cells that you check.
53      */
54     int timestamp;
55     /// index in the objects vector
56     int id;
57   };
58  
59   /** Element for the single linked list in each grid cell */
60   struct GridEntry
61   {
62     GridEntry* next;
63     ObjectWrapper* object_wrapper;
64   };
65
66   void remove_object_from_gridcell(int gridcell, ObjectWrapper* wrapper);
67   void collide_object(ObjectWrapper* wrapper);
68   void collide_object_object(ObjectWrapper* wrapper, ObjectWrapper* wrapper2);
69   void move_object(ObjectWrapper* wrapper);
70   
71   typedef std::vector<GridEntry*> GridEntries;
72   GridEntries grid;
73   typedef std::vector<ObjectWrapper*> Objects;
74   Objects objects;
75   size_t cells_x, cells_y;
76   float width;
77   float height;
78   float cell_width;
79   float cell_height;
80   int iterator_timestamp;
81 };
82
83 extern CollisionGrid* bla;
84
85 #endif
86