-Started to move stuff from library back to main game
[supertux.git] / src / collision_grid.h
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
21 #ifndef __COLLISION_GRID_H__
22 #define __COLLISION_GRID_H__
23
24 #include <vector>
25 #include "moving_object.h"
26
27 using namespace SuperTux;
28
29 class CollisionGridIterator;
30
31 /**
32  * A rectangular grid to keep track of all moving game objects. It allows fast
33  * queries for all objects in a rectangular area.
34  */
35 class CollisionGrid
36 {
37 public:
38   CollisionGrid(float width, float height);
39   ~CollisionGrid();
40
41   void add_object(MovingObject* object);
42   void remove_object(MovingObject* object);
43
44   void check_collisions();
45
46 private:
47   friend class CollisionGridIterator;
48   
49   struct ObjectWrapper
50   {
51     MovingObject* object;
52     Rectangle dest;
53     /** (pseudo) timestamp. When reading from the grid the timestamp is
54      * changed so that you can easily avoid reading an object multiple times
55      * when it is in several cells that you check.
56      */
57     int timestamp;
58     /// index in the objects vector
59     int id;
60   };
61  
62   /** Element for the single linked list in each grid cell */
63   struct GridEntry
64   {
65     GridEntry* next;
66     ObjectWrapper* object_wrapper;
67   };
68
69   void remove_object_from_gridcell(int gridcell, ObjectWrapper* wrapper);
70   void collide_object(ObjectWrapper* wrapper);
71   void collide_object_object(ObjectWrapper* wrapper, ObjectWrapper* wrapper2);
72   void move_object(ObjectWrapper* wrapper);
73   
74   typedef std::vector<GridEntry*> GridEntries;
75   GridEntries grid;
76   typedef std::vector<ObjectWrapper*> Objects;
77   Objects objects;
78   size_t cells_x, cells_y;
79   float width;
80   float height;
81   float cell_width;
82   float cell_height;
83   int iterator_timestamp;
84 };
85
86 extern CollisionGrid* bla;
87
88 #endif
89