fix tiles being 1 pixel off their correct position
[supertux.git] / src / tilemap.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 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  02111-1307, USA.
19 #include "tilemap.h"
20
21 #include <assert.h>
22 #include <algorithm>
23 #include <math.h>
24 #include "screen/drawing_context.h"
25 #include "level.h"
26 #include "tile.h"
27 #include "globals.h"
28
29 TileMap::TileMap(Level* newlevel)
30   : level(newlevel)
31 {
32   tilemanager = TileManager::instance();
33 }
34
35 TileMap::~TileMap()
36 {
37 }
38
39 void
40 TileMap::action(float )
41 {
42 }
43
44 void
45 TileMap::draw(const std::vector<unsigned int>& tiles, DrawingContext& context,
46     int layer)
47 {
48   /** if we don't round here, we'll have a 1 pixel gap on screen sometimes.
49    * I have no idea why */
50   float start_x = roundf(context.get_translation().x);
51   float start_y = roundf(context.get_translation().y);
52   float end_x = std::min(start_x + screen->w, float(level->width * 32));
53   float end_y = std::min(start_y + screen->h, float(level->height * 32));
54   start_x -= int(start_x) % 32;
55   start_y -= int(start_y) % 32;  
56   int tsx = int(start_x / 32); // tilestartindex x
57   int tsy = int(start_y / 32); // tilestartindex y
58   
59   Vector pos;
60   int tx, ty;
61   for(pos.x = start_x, tx = tsx; pos.x < end_x; pos.x += 32, ++tx) {
62     for(pos.y = start_y, ty = tsy; pos.y < end_y; pos.y += 32, ++ty) {
63       tilemanager->draw_tile(context, tiles[ty*level->width + tx], pos, layer);
64     }
65   }
66 }
67
68 void
69 TileMap::draw(DrawingContext& context)
70 {
71   draw(level->bg_tiles, context, LAYER_BACKGROUNDTILES);
72   draw(level->ia_tiles, context, LAYER_TILES);
73   draw(level->fg_tiles, context, LAYER_FOREGROUNDTILES);
74 }