First step towards multiple tilesets per tilemap. Code is very inefficient for now...
[supertux.git] / src / object / tilemap.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 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
20 #include <config.h>
21
22 #include <cassert>
23 #include <algorithm>
24 #include <iostream>
25 #include <stdexcept>
26 #include <math.h>
27 #include <limits>
28
29 #include "tilemap.hpp"
30 #include "video/drawing_context.hpp"
31 #include "level.hpp"
32 #include "tile.hpp"
33 #include "resources.hpp"
34 #include "tile_manager.hpp"
35 #include "lisp/lisp.hpp"
36 #include "lisp/list_iterator.hpp"
37 #include "lisp/writer.hpp"
38 #include "object_factory.hpp"
39 #include "main.hpp"
40 #include "log.hpp"
41 #include "scripting/tilemap.hpp"
42 #include "scripting/squirrel_util.hpp"
43
44 TileMap::TileMap()
45   : tilemanager(0), solid(false), speed_x(1), speed_y(1), width(0), height(0), z_pos(0), x_offset(0), y_offset(0),
46     drawing_effect(NO_EFFECT), alpha(1.0), current_alpha(1.0), remaining_fade_time(0),
47     draw_target(DrawingContext::NORMAL)
48 {
49 }
50
51 TileMap::TileMap(const lisp::Lisp& reader)
52   : tilemanager(0), solid(false), speed_x(1), speed_y(1), width(-1), height(-1), z_pos(0),
53     x_offset(0), y_offset(0),
54     drawing_effect(NO_EFFECT), alpha(1.0), current_alpha(1.0),
55     remaining_fade_time(0),
56     draw_target(DrawingContext::NORMAL)
57 {
58   tilemanager = new TileManager();
59
60   reader.get("name", name);
61   reader.get("z-pos", z_pos);
62   reader.get("solid", solid);
63   reader.get("speed", speed_x);
64   reader.get("speed-y", speed_y);
65
66   if(solid && ((speed_x != 1) || (speed_y != 1))) {
67     log_warning << "Speed of solid tilemap is not 1. fixing" << std::endl;
68     speed_x = 1;
69     speed_y = 1;
70   }
71
72   const lisp::Lisp* pathLisp = reader.get_lisp("path");
73   if (pathLisp) {
74     path.reset(new Path());
75     path->read(*pathLisp);
76     walker.reset(new PathWalker(path.get(), /*running*/false));
77     Vector v = path->get_base();
78     set_x_offset(v.x);
79     set_y_offset(v.y);
80   }
81
82   std::string draw_target_s = "normal";
83   reader.get("draw-target", draw_target_s);
84   if (draw_target_s == "normal") draw_target = DrawingContext::NORMAL;
85   if (draw_target_s == "lightmap") draw_target = DrawingContext::LIGHTMAP;
86
87   if (reader.get("alpha", alpha)) {
88     current_alpha = alpha;
89   }
90
91   reader.get("width", width);
92   reader.get("height", height);
93   if(width < 0 || height < 0)
94     throw std::runtime_error("Invalid/No width/height specified in tilemap.");
95
96   const lisp::Lisp* tilesets_reader = reader.get_lisp("tilesets");
97   if (tilesets_reader) {
98     lisp::ListIterator iter(tilesets_reader);
99     while(iter.next()) {
100       const std::string& token = iter.item();
101       if(token != "tileset") {
102         log_warning << "Skipping unrecognized token \"" << token << "\" in tilemap's tilesets list" << std::endl;
103         continue;
104       }
105       const lisp::Lisp* tileset_reader = iter.lisp();
106       std::string file; 
107       unsigned int start = 0;
108       unsigned int end = std::numeric_limits<unsigned int>::max();
109       int offset = 0;
110       if (!tileset_reader->get("file", file)) {
111         log_warning << "Skipping tileset import without file name" << std::endl;
112         continue;
113       }
114       tileset_reader->get("start", start);
115       tileset_reader->get("end", end);
116       tileset_reader->get("offset", offset);
117       tilemanager->load_tileset(file, start, end, offset);
118     }
119   } else {
120     log_warning << "No tilesets list in tilemap, loading default tiles" << std::endl;
121     if (loading_worldmap) {
122       tilemanager->load_tileset("images/worldmap.strf", 0, std::numeric_limits<unsigned int>::max(), 0);
123     } else {
124       tilemanager->load_tileset("images/tiles.strf", 0, std::numeric_limits<unsigned int>::max(), 0);
125     }
126   }
127
128   if(!reader.get_vector("tiles", tiles))
129     throw std::runtime_error("No tiles in tilemap.");
130
131   if(int(tiles.size()) != width*height) {
132     throw std::runtime_error("wrong number of tiles in tilemap.");
133   }
134
135   // make sure all tiles are loaded
136   for(Tiles::iterator i = tiles.begin(); i != tiles.end(); ++i)
137     tilemanager->get(*i);
138 }
139
140 TileMap::TileMap(std::string name, int z_pos, bool solid, size_t width, size_t height)
141   : tilemanager(0), solid(solid), speed_x(1), speed_y(1), width(0), height(0), z_pos(z_pos),
142     x_offset(0), y_offset(0), drawing_effect(NO_EFFECT), alpha(1.0),
143     current_alpha(1.0), remaining_fade_time(0),
144     draw_target(DrawingContext::NORMAL)
145 {
146   this->name = name;
147
148   resize(width, height);
149 }
150
151 TileMap::~TileMap()
152 {
153   delete tilemanager;
154 }
155
156 void
157 TileMap::write(lisp::Writer& writer)
158 {
159   writer.start_list("tilemap");
160
161   writer.write_int("z-pos", z_pos);
162
163   writer.write_bool("solid", solid);
164   writer.write_float("speed", speed_x);
165   writer.write_float("speed-y", speed_y);
166   writer.write_int("width", width);
167   writer.write_int("height", height);
168   writer.write_int_vector("tiles", tiles);
169
170   writer.end_list("tilemap");
171 }
172
173 void
174 TileMap::update(float elapsed_time)
175 {
176   // handle tilemap fading
177   if (current_alpha != alpha) {
178     remaining_fade_time = std::max(0.0f, remaining_fade_time - elapsed_time);
179     if (remaining_fade_time == 0.0f) {
180       current_alpha = alpha;
181     } else {
182       float amt = (alpha - current_alpha) / (remaining_fade_time / elapsed_time);
183       if (amt > 0) current_alpha = std::min(current_alpha + amt, alpha);
184       if (amt < 0) current_alpha = std::max(current_alpha + amt, alpha);
185     }
186     if ((alpha < 0.25) && (current_alpha < 0.25)) set_solid(false);
187     if ((alpha > 0.75) && (current_alpha > 0.75)) set_solid(true);
188   }
189
190   // if we have a path to follow, follow it
191   if (walker.get()) {
192     Vector v = walker->advance(elapsed_time);
193     set_x_offset(v.x);
194     set_y_offset(v.y);
195   }
196 }
197
198 void
199 TileMap::draw(DrawingContext& context)
200 {
201   // skip draw if current opacity is set to 0.0
202   if (current_alpha == 0.0) return;
203
204   context.push_transform();
205   context.push_target();
206   context.set_target(draw_target);
207
208   if(drawing_effect != 0) context.set_drawing_effect(drawing_effect);
209   if(current_alpha != 1.0) context.set_alpha(current_alpha);
210
211   float trans_x = roundf(context.get_translation().x);
212   float trans_y = roundf(context.get_translation().y);
213   context.set_translation(Vector(trans_x * speed_x, trans_y * speed_y));
214
215   /** if we don't round here, we'll have a 1 pixel gap on screen sometimes.
216    * I have no idea why */
217   float start_x = int((roundf(context.get_translation().x) - roundf(x_offset)) / 32) * 32 + roundf(x_offset);
218   float start_y = int((roundf(context.get_translation().y) - roundf(y_offset)) / 32) * 32 + roundf(y_offset);
219   float end_x = std::min(start_x + SCREEN_WIDTH + 32, float(width * 32 + roundf(x_offset)));
220   float end_y = std::min(start_y + SCREEN_HEIGHT + 32, float(height * 32 + roundf(y_offset)));
221   int tsx = int((start_x - roundf(x_offset)) / 32); // tilestartindex x
222   int tsy = int((start_y - roundf(y_offset)) / 32); // tilestartindex y
223
224   Vector pos;
225   int tx, ty;
226   for(pos.x = start_x, tx = tsx; pos.x < end_x; pos.x += 32, ++tx) {
227     for(pos.y = start_y, ty = tsy; pos.y < end_y; pos.y += 32, ++ty) {
228       if ((tx < 0) || (ty < 0)) continue;
229       const Tile* tile = tilemanager->get(tiles[ty*width + tx]);
230       assert(tile != 0);
231       tile->draw(context, pos, z_pos);
232     }
233   }
234
235   context.pop_target();
236   context.pop_transform();
237 }
238
239 void
240 TileMap::goto_node(int node_no)
241 {
242   if (!walker.get()) return;
243   walker->goto_node(node_no);
244 }
245
246 void
247 TileMap::start_moving()
248 {
249   if (!walker.get()) return;
250   walker->start_moving();
251 }
252
253 void
254 TileMap::stop_moving()
255 {
256   if (!walker.get()) return;
257   walker->stop_moving();
258 }
259
260 void
261 TileMap::expose(HSQUIRRELVM vm, SQInteger table_idx)
262 {
263   if (name.empty()) return;
264   Scripting::TileMap* interface = new Scripting::TileMap(this);
265   expose_object(vm, table_idx, interface, name, true);
266 }
267
268 void
269 TileMap::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
270 {
271   if (name.empty()) return;
272   Scripting::unexpose_object(vm, table_idx, name);
273 }
274
275 void
276 TileMap::set(int newwidth, int newheight, const std::vector<unsigned int>&newt,
277     int new_z_pos, bool newsolid)
278 {
279   if(int(newt.size()) != newwidth * newheight)
280     throw std::runtime_error("Wrong tilecount count.");
281
282   width  = newwidth;
283   height = newheight;
284
285   tiles.resize(newt.size());
286   tiles = newt;
287
288   z_pos  = new_z_pos;
289   solid  = newsolid;
290
291   // make sure all tiles are loaded
292   for(Tiles::iterator i = tiles.begin(); i != tiles.end(); ++i)
293     tilemanager->get(*i);
294 }
295
296 void
297 TileMap::resize(int new_width, int new_height, int fill_id)
298 {
299   if(new_width < width) {
300     // remap tiles for new width
301     for(int y = 0; y < height && y < new_height; ++y) {
302       for(int x = 0; x < new_width; ++x) {
303         tiles[y * new_width + x] = tiles[y * width + x];
304       }
305     }
306   }
307
308   tiles.resize(new_width * new_height, fill_id);
309
310   if(new_width > width) {
311     // remap tiles
312     for(int y = std::min(height, new_height)-1; y >= 0; --y) {
313       for(int x = new_width-1; x >= 0; --x) {
314         if(x >= width) {
315           tiles[y * new_width + x] = fill_id;
316           continue;
317         }
318
319         tiles[y * new_width + x] = tiles[y * width + x];
320       }
321     }
322   }
323
324   height = new_height;
325   width = new_width;
326 }
327
328 void
329 TileMap::set_solid(bool solid)
330 {
331   this->solid = solid;
332 }
333
334 const Tile*
335 TileMap::get_tile(int x, int y) const
336 {
337   if(x < 0 || x >= width || y < 0 || y >= height) {
338     //log_warning << "tile outside tilemap requested" << std::endl;
339     return tilemanager->get(0);
340   }
341
342   return tilemanager->get(tiles[y*width + x]);
343 }
344
345 const Tile*
346 TileMap::get_tile_at(const Vector& pos) const
347 {
348   return get_tile(int(pos.x - x_offset)/32, int(pos.y - y_offset)/32);
349 }
350
351 void
352 TileMap::change(int x, int y, uint32_t newtile)
353 {
354   assert(x >= 0 && x < width && y >= 0 && y < height);
355   tiles[y*width + x] = newtile;
356 }
357
358 void
359 TileMap::change_at(const Vector& pos, uint32_t newtile)
360 {
361   change(int(pos.x - x_offset)/32, int(pos.y - y_offset)/32, newtile);
362 }
363
364 void
365 TileMap::change_all(uint32_t oldtile, uint32_t newtile)
366 {
367   for (size_t x = 0; x < get_width(); x++)
368     for (size_t y = 0; y < get_height(); y++) {
369       if (get_tile(x,y)->getID() == oldtile) change(x,y,newtile);
370     }
371 }
372
373 void
374 TileMap::fade(float alpha, float seconds)
375 {
376   this->alpha = alpha;
377   this->remaining_fade_time = seconds;
378 }
379
380
381 void 
382 TileMap::set_alpha(float alpha)
383 {
384   this->alpha = alpha;
385   this->current_alpha = alpha;
386   this->remaining_fade_time = 0;
387   if (current_alpha < 0.25) set_solid(false);
388   if (current_alpha > 0.75) set_solid(true);
389 }
390
391 float 
392 TileMap::get_alpha()
393 {
394   return this->current_alpha;
395 }
396   
397 bool TileMap::loading_worldmap; /**< FIXME: hack to make TileMap load default tileset if none was set */
398
399 IMPLEMENT_FACTORY(TileMap, "tilemap");