First step towards multiple tilesets per tilemap. Code is very inefficient for now...
[supertux.git] / src / sector.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
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 #include <config.h>
20
21 #include <memory>
22 #include <algorithm>
23 #include <stdexcept>
24 #include <iostream>
25 #include <fstream>
26 #include <sstream>
27 #include <stdexcept>
28 #include <float.h>
29 #include <math.h>
30 #include <limits>
31 #include <physfs.h>
32
33 #include "sector.hpp"
34 #include "object/player.hpp"
35 #include "object/gameobjs.hpp"
36 #include "object/camera.hpp"
37 #include "object/background.hpp"
38 #include "object/gradient.hpp"
39 #include "object/particlesystem.hpp"
40 #include "object/particlesystem_interactive.hpp"
41 #include "object/tilemap.hpp"
42 #include "lisp/parser.hpp"
43 #include "lisp/lisp.hpp"
44 #include "lisp/writer.hpp"
45 #include "lisp/list_iterator.hpp"
46 #include "tile.hpp"
47 #include "audio/sound_manager.hpp"
48 #include "game_session.hpp"
49 #include "resources.hpp"
50 #include "statistics.hpp"
51 #include "object_factory.hpp"
52 #include "collision.hpp"
53 #include "spawn_point.hpp"
54 #include "math/rect.hpp"
55 #include "math/aatriangle.hpp"
56 #include "object/coin.hpp"
57 #include "object/block.hpp"
58 #include "object/invisible_block.hpp"
59 #include "object/light.hpp"
60 #include "object/pulsing_light.hpp"
61 #include "object/bullet.hpp"
62 #include "object/text_object.hpp"
63 #include "object/portable.hpp"
64 #include "badguy/jumpy.hpp"
65 #include "trigger/sequence_trigger.hpp"
66 #include "player_status.hpp"
67 #include "scripting/squirrel_util.hpp"
68 #include "script_interface.hpp"
69 #include "log.hpp"
70 #include "main.hpp"
71
72 Sector* Sector::_current = 0;
73
74 bool Sector::show_collrects = false;
75 bool Sector::draw_solids_only = false;
76
77 Sector::Sector(Level* parent)
78   : level(parent), currentmusic(LEVEL_MUSIC),
79   ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10.0), player(0), camera(0)
80 {
81   add_object(new Player(player_status, "Tux"));
82   add_object(new DisplayEffect("Effect"));
83   add_object(new TextObject("Text"));
84
85   // create a new squirrel table for the sector
86   using namespace Scripting;
87
88   sq_collectgarbage(global_vm);
89
90   sq_newtable(global_vm);
91   sq_pushroottable(global_vm);
92   if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
93     throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
94
95   sq_resetobject(&sector_table);
96   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &sector_table)))
97     throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
98   sq_addref(global_vm, &sector_table);
99   sq_pop(global_vm, 1);
100 }
101
102 Sector::~Sector()
103 {
104   using namespace Scripting;
105
106   deactivate();
107
108   for(ScriptList::iterator i = scripts.begin();
109       i != scripts.end(); ++i) {
110     HSQOBJECT& object = *i;
111     sq_release(global_vm, &object);
112   }
113   sq_release(global_vm, &sector_table);
114   sq_collectgarbage(global_vm);
115
116   update_game_objects();
117   assert(gameobjects_new.size() == 0);
118
119   for(GameObjects::iterator i = gameobjects.begin();
120       i != gameobjects.end(); ++i) {
121     GameObject* object = *i;
122     before_object_remove(object);
123     object->unref();
124   }
125
126   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
127       ++i)
128     delete *i;
129 }
130
131 Level*
132 Sector::get_level()
133 {
134   return level;
135 }
136
137 GameObject*
138 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
139 {
140   if(name == "camera") {
141     Camera* camera = new Camera(this, "Camera");
142     camera->parse(reader);
143     return camera;
144   } else if(name == "particles-snow") {
145     SnowParticleSystem* partsys = new SnowParticleSystem();
146     partsys->parse(reader);
147     return partsys;
148   } else if(name == "particles-rain") {
149     RainParticleSystem* partsys = new RainParticleSystem();
150     partsys->parse(reader);
151     return partsys;
152   } else if(name == "particles-comets") {
153     CometParticleSystem* partsys = new CometParticleSystem();
154     partsys->parse(reader);
155     return partsys;
156   } else if(name == "particles-ghosts") {
157     GhostParticleSystem* partsys = new GhostParticleSystem();
158     partsys->parse(reader);
159     return partsys;
160   } else if(name == "particles-clouds") {
161     CloudParticleSystem* partsys = new CloudParticleSystem();
162     partsys->parse(reader);
163     return partsys;
164   } else if(name == "money") { // for compatibility with old maps
165     return new Jumpy(reader);
166   }
167
168   try {
169     return create_object(name, reader);
170   } catch(std::exception& e) {
171     log_warning << e.what() << "" << std::endl;
172   }
173
174   return 0;
175 }
176
177 void
178 Sector::parse(const lisp::Lisp& sector)
179 {
180
181   TileMap::loading_worldmap = false;
182
183   bool has_background = false;
184   lisp::ListIterator iter(&sector);
185   while(iter.next()) {
186     const std::string& token = iter.item();
187     if(token == "name") {
188       iter.value()->get(name);
189     } else if(token == "gravity") {
190       iter.value()->get(gravity);
191     } else if(token == "music") {
192       iter.value()->get(music);
193     } else if(token == "spawnpoint") {
194       SpawnPoint* sp = new SpawnPoint(iter.lisp());
195       spawnpoints.push_back(sp);
196     } else if(token == "init-script") {
197       iter.value()->get(init_script);
198     } else if(token == "ambient-light") {
199       std::vector<float> vColor;
200       sector.get_vector( "ambient-light", vColor );
201       if(vColor.size() < 3) {
202         log_warning << "(ambient-light) requires a color as argument" << std::endl;
203       } else {
204         ambient_light = Color( vColor );
205       }
206     } else {
207       GameObject* object = parse_object(token, *(iter.lisp()));
208       if(object) {
209         if(dynamic_cast<Background *>(object)) {
210            has_background = true;
211         } else if(dynamic_cast<Gradient *>(object)) {
212            has_background = true;
213         }
214         add_object(object);
215       }
216     }
217   }
218
219   if(!has_background) {
220     Gradient* gradient = new Gradient();
221     gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
222     add_object(gradient);
223   }
224
225   update_game_objects();
226
227   if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
228
229   fix_old_tiles();
230   if(!camera) {
231     log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
232     update_game_objects();
233     add_object(new Camera(this, "Camera"));
234   }
235
236   update_game_objects();
237 }
238
239 void
240 Sector::parse_old_format(const lisp::Lisp& reader)
241 {
242
243   TileMap::loading_worldmap = false;
244
245   name = "main";
246   reader.get("gravity", gravity);
247
248   std::string backgroundimage;
249   if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
250     if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
251     if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
252     if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
253     backgroundimage = "images/background/" + backgroundimage;
254     if (!PHYSFS_exists(backgroundimage.c_str())) {
255       log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
256       backgroundimage = "";
257     }
258   }
259
260   float bgspeed = .5;
261   reader.get("bkgd_speed", bgspeed);
262   bgspeed /= 100;
263
264   Color bkgd_top, bkgd_bottom;
265   int r = 0, g = 0, b = 128;
266   reader.get("bkgd_red_top", r);
267   reader.get("bkgd_green_top",  g);
268   reader.get("bkgd_blue_top",  b);
269   bkgd_top.red = static_cast<float> (r) / 255.0f;
270   bkgd_top.green = static_cast<float> (g) / 255.0f;
271   bkgd_top.blue = static_cast<float> (b) / 255.0f;
272
273   reader.get("bkgd_red_bottom",  r);
274   reader.get("bkgd_green_bottom", g);
275   reader.get("bkgd_blue_bottom", b);
276   bkgd_bottom.red = static_cast<float> (r) / 255.0f;
277   bkgd_bottom.green = static_cast<float> (g) / 255.0f;
278   bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
279
280   if(backgroundimage != "") {
281     Background* background = new Background();
282     background->set_image(backgroundimage, bgspeed);
283     add_object(background);
284   } else {
285     Gradient* gradient = new Gradient();
286     gradient->set_gradient(bkgd_top, bkgd_bottom);
287     add_object(gradient);
288   }
289
290   std::string particlesystem;
291   reader.get("particle_system", particlesystem);
292   if(particlesystem == "clouds")
293     add_object(new CloudParticleSystem());
294   else if(particlesystem == "snow")
295     add_object(new SnowParticleSystem());
296   else if(particlesystem == "rain")
297     add_object(new RainParticleSystem());
298
299   Vector startpos(100, 170);
300   reader.get("start_pos_x", startpos.x);
301   reader.get("start_pos_y", startpos.y);
302
303   SpawnPoint* spawn = new SpawnPoint;
304   spawn->pos = startpos;
305   spawn->name = "main";
306   spawnpoints.push_back(spawn);
307
308   music = "chipdisko.ogg";
309   // skip reading music filename. It's all .ogg now, anyway
310   /*
311   reader.get("music", music);
312   */
313   music = "music/" + music;
314
315   int width = 30, height = 15;
316   reader.get("width", width);
317   reader.get("height", height);
318
319   std::vector<unsigned int> tiles;
320   if(reader.get_vector("interactive-tm", tiles)
321       || reader.get_vector("tilemap", tiles)) {
322     TileMap* tilemap = new TileMap();
323     tilemap->set(width, height, tiles, LAYER_TILES, true);
324
325     // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
326     for(size_t x=0; x < tilemap->get_width(); ++x) {
327       for(size_t y=0; y < tilemap->get_height(); ++y) {
328         const Tile* tile = tilemap->get_tile(x, y);
329         if(tile->getID() == 112) tilemap->change(x, y, 1311);
330       }
331     }
332
333     if (height < 19) tilemap->resize(width, 19);
334     add_object(tilemap);
335   }
336
337   if(reader.get_vector("background-tm", tiles)) {
338     TileMap* tilemap = new TileMap();
339     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
340     if (height < 19) tilemap->resize(width, 19);
341     add_object(tilemap);
342   }
343
344   if(reader.get_vector("foreground-tm", tiles)) {
345     TileMap* tilemap = new TileMap();
346     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
347
348     // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
349     if (height < 19) tilemap->resize(width, 19, 2035);
350
351     add_object(tilemap);
352   }
353
354   // read reset-points (now spawn-points)
355   const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
356   if(resetpoints) {
357     lisp::ListIterator iter(resetpoints);
358     while(iter.next()) {
359       if(iter.item() == "point") {
360         Vector sp_pos;
361         if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
362           {
363           SpawnPoint* sp = new SpawnPoint;
364           sp->name = "main";
365           sp->pos = sp_pos;
366           spawnpoints.push_back(sp);
367           }
368       } else {
369         log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
370       }
371     }
372   }
373
374   // read objects
375   const lisp::Lisp* objects = reader.get_lisp("objects");
376   if(objects) {
377     lisp::ListIterator iter(objects);
378     while(iter.next()) {
379       GameObject* object = parse_object(iter.item(), *(iter.lisp()));
380       if(object) {
381         add_object(object);
382       } else {
383         log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
384       }
385     }
386   }
387
388   // add a camera
389   Camera* camera = new Camera(this, "Camera");
390   add_object(camera);
391
392   update_game_objects();
393
394   if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
395
396   fix_old_tiles();
397   update_game_objects();
398 }
399
400 void
401 Sector::fix_old_tiles()
402 {
403   for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
404     TileMap* solids = *i;
405     for(size_t x=0; x < solids->get_width(); ++x) {
406       for(size_t y=0; y < solids->get_height(); ++y) {
407         const Tile* tile = solids->get_tile(x, y);
408         Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
409
410         if(tile->getID() == 112) {
411           add_object(new InvisibleBlock(pos));
412           solids->change(x, y, 0);
413         } else if(tile->getAttributes() & Tile::COIN) {
414           add_object(new Coin(pos));
415           solids->change(x, y, 0);
416         } else if(tile->getAttributes() & Tile::FULLBOX) {
417           add_object(new BonusBlock(pos, tile->getData()));
418           solids->change(x, y, 0);
419         } else if(tile->getAttributes() & Tile::BRICK) {
420           add_object(new Brick(pos, tile->getData()));
421           solids->change(x, y, 0);
422         } else if(tile->getAttributes() & Tile::GOAL) {
423           std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
424           add_object(new SequenceTrigger(pos, sequence));
425           solids->change(x, y, 0);
426         }
427       }
428     }
429   }
430
431   // add lights for special tiles
432   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
433     TileMap* tm = dynamic_cast<TileMap*>(*i);
434     if (!tm) continue;
435     for(size_t x=0; x < tm->get_width(); ++x) {
436       for(size_t y=0; y < tm->get_height(); ++y) {
437         const Tile* tile = tm->get_tile(x, y);
438         Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
439         Vector center(pos.x + 16, pos.y + 16);
440
441         // torch
442         if (tile->getID() == 1517) {
443           float pseudo_rnd = (float)((int)pos.x % 10) / 10;
444           add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
445         }
446         // lava or lavaflow
447         if ((tile->getID() == 173) || (tile->getID() == 1700) || (tile->getID() == 1705) || (tile->getID() == 1706)) {
448           // space lights a bit
449           if (((tm->get_tile(x-1, y)->getID() != tm->get_tile(x,y)->getID())
450               && (tm->get_tile(x, y-1)->getID() != tm->get_tile(x,y)->getID()))
451               || ((x % 3 == 0) && (y % 3 == 0))) {
452             float pseudo_rnd = (float)((int)pos.x % 10) / 10;
453             add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
454           }
455         }
456
457       }
458     }
459   }
460
461
462 }
463
464 void
465 Sector::write(lisp::Writer& writer)
466 {
467   writer.write_string("name", name);
468   writer.write_float("gravity", gravity);
469   writer.write_string("music", music);
470
471   // write spawnpoints
472   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
473       ++i) {
474     SpawnPoint* spawn = *i;
475     writer.start_list("spawn-points");
476     writer.write_string("name", spawn->name);
477     writer.write_float("x", spawn->pos.x);
478     writer.write_float("y", spawn->pos.y);
479     writer.end_list("spawn-points");
480   }
481
482   // write objects
483   for(GameObjects::iterator i = gameobjects.begin();
484       i != gameobjects.end(); ++i) {
485     Serializable* serializable = dynamic_cast<Serializable*> (*i);
486     if(serializable)
487       serializable->write(writer);
488   }
489 }
490
491 HSQUIRRELVM
492 Sector::run_script(std::istream& in, const std::string& sourcename)
493 {
494   using namespace Scripting;
495
496   // garbage collect thread list
497   for(ScriptList::iterator i = scripts.begin();
498       i != scripts.end(); ) {
499     HSQOBJECT& object = *i;
500     HSQUIRRELVM vm = object_to_vm(object);
501
502     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
503       sq_release(global_vm, &object);
504       i = scripts.erase(i);
505       continue;
506     }
507
508     ++i;
509   }
510
511   HSQOBJECT object = create_thread(global_vm);
512   scripts.push_back(object);
513
514   HSQUIRRELVM vm = object_to_vm(object);
515
516   // set sector_table as roottable for the thread
517   sq_pushobject(vm, sector_table);
518   sq_setroottable(vm);
519
520   compile_and_run(vm, in, sourcename);
521
522   return vm;
523 }
524
525 void
526 Sector::add_object(GameObject* object)
527 {
528   // make sure the object isn't already in the list
529 #ifdef DEBUG
530   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
531       ++i) {
532     if(*i == object) {
533       assert("object already added to sector" == 0);
534     }
535   }
536   for(GameObjects::iterator i = gameobjects_new.begin();
537       i != gameobjects_new.end(); ++i) {
538     if(*i == object) {
539       assert("object already added to sector" == 0);
540     }
541   }
542 #endif
543
544   object->ref();
545   gameobjects_new.push_back(object);
546 }
547
548 void
549 Sector::activate(const std::string& spawnpoint)
550 {
551   SpawnPoint* sp = 0;
552   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
553       ++i) {
554     if((*i)->name == spawnpoint) {
555       sp = *i;
556       break;
557     }
558   }
559   if(!sp) {
560     log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
561     if(spawnpoint != "main") {
562       activate("main");
563     } else {
564       activate(Vector(0, 0));
565     }
566   } else {
567     activate(sp->pos);
568   }
569 }
570
571 void
572 Sector::activate(const Vector& player_pos)
573 {
574   if(_current != this) {
575     if(_current != NULL)
576       _current->deactivate();
577     _current = this;
578
579     // register sectortable as sector in scripting
580     HSQUIRRELVM vm = Scripting::global_vm;
581     sq_pushroottable(vm);
582     sq_pushstring(vm, "sector", -1);
583     sq_pushobject(vm, sector_table);
584     if(SQ_FAILED(sq_createslot(vm, -3)))
585       throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
586     sq_pop(vm, 1);
587
588     for(GameObjects::iterator i = gameobjects.begin();
589         i != gameobjects.end(); ++i) {
590       GameObject* object = *i;
591
592       try_expose(object);
593     }
594   }
595   try_expose_me();
596
597   // spawn smalltux below spawnpoint
598   if (!player->is_big()) {
599     player->move(player_pos + Vector(0,32));
600   } else {
601     player->move(player_pos);
602   }
603
604   // spawning tux in the ground would kill him
605   if(!is_free_of_tiles(player->get_bbox())) {
606     log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
607     Vector npos = player->get_bbox().p1;
608     npos.y-=32;
609     player->move(npos);
610   }
611
612   camera->reset(player->get_pos());
613   update_game_objects();
614
615   // Run init script
616   if(init_script != "") {
617     std::istringstream in(init_script);
618     run_script(in, std::string("Sector(") + name + ") - init");
619   }
620 }
621
622 void
623 Sector::deactivate()
624 {
625   if(_current != this)
626     return;
627
628   // remove sector entry from global vm
629   HSQUIRRELVM vm = Scripting::global_vm;
630   sq_pushroottable(vm);
631   sq_pushstring(vm, "sector", -1);
632   if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
633     throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
634   sq_pop(vm, 1);
635
636   for(GameObjects::iterator i = gameobjects.begin();
637       i != gameobjects.end(); ++i) {
638     GameObject* object = *i;
639
640     try_unexpose(object);
641   }
642
643   try_unexpose_me();
644   _current = NULL;
645 }
646
647 Rect
648 Sector::get_active_region()
649 {
650   return Rect(
651     camera->get_translation() - Vector(1600, 1200),
652     camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
653 }
654
655 void
656 Sector::update(float elapsed_time)
657 {
658   player->check_bounds(camera);
659
660   /* update objects */
661   for(GameObjects::iterator i = gameobjects.begin();
662           i != gameobjects.end(); ++i) {
663     GameObject* object = *i;
664     if(!object->is_valid())
665       continue;
666
667     object->update(elapsed_time);
668   }
669
670   /* Handle all possible collisions. */
671   handle_collisions();
672   update_game_objects();
673 }
674
675 void
676 Sector::update_game_objects()
677 {
678   /** cleanup marked objects */
679   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
680       i != gameobjects.end(); /* nothing */) {
681     GameObject* object = *i;
682
683     if(object->is_valid()) {
684       ++i;
685       continue;
686     }
687
688     before_object_remove(object);
689
690     object->unref();
691     i = gameobjects.erase(i);
692   }
693
694   /* add newly created objects */
695   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
696       i != gameobjects_new.end(); ++i)
697   {
698     GameObject* object = *i;
699
700     before_object_add(object);
701
702     gameobjects.push_back(object);
703   }
704   gameobjects_new.clear();
705
706   /* update solid_tilemaps list */
707   //FIXME: this could be more efficient
708   solid_tilemaps.clear();
709   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
710       i != gameobjects.end(); ++i)
711   {
712     TileMap* tm = dynamic_cast<TileMap*>(*i);
713     if (!tm) continue;
714     if (tm->is_solid()) solid_tilemaps.push_back(tm);
715   }
716
717 }
718
719 bool
720 Sector::before_object_add(GameObject* object)
721 {
722   Bullet* bullet = dynamic_cast<Bullet*> (object);
723   if(bullet != NULL) {
724     bullets.push_back(bullet);
725   }
726
727   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
728   if(movingobject != NULL) {
729     moving_objects.push_back(movingobject);
730   }
731
732   Portable* portable = dynamic_cast<Portable*> (object);
733   if(portable != NULL) {
734     portables.push_back(portable);
735   }
736
737   TileMap* tilemap = dynamic_cast<TileMap*> (object);
738   if(tilemap != NULL && tilemap->is_solid()) {
739     solid_tilemaps.push_back(tilemap);
740   }
741
742   Camera* camera = dynamic_cast<Camera*> (object);
743   if(camera != NULL) {
744     if(this->camera != 0) {
745       log_warning << "Multiple cameras added. Ignoring" << std::endl;
746       return false;
747     }
748     this->camera = camera;
749   }
750
751   Player* player = dynamic_cast<Player*> (object);
752   if(player != NULL) {
753     if(this->player != 0) {
754       log_warning << "Multiple players added. Ignoring" << std::endl;
755       return false;
756     }
757     this->player = player;
758   }
759
760   UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
761   if(physic_object)
762   {
763     physic_object->physic.set_gravity(gravity);
764   }
765
766
767   if(_current == this) {
768     try_expose(object);
769   }
770
771   return true;
772 }
773
774 void
775 Sector::try_expose(GameObject* object)
776 {
777   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
778   if(interface != NULL) {
779     HSQUIRRELVM vm = Scripting::global_vm;
780     sq_pushobject(vm, sector_table);
781     interface->expose(vm, -1);
782     sq_pop(vm, 1);
783   }
784 }
785
786 void
787 Sector::try_expose_me()
788 {
789   HSQUIRRELVM vm = Scripting::global_vm;
790   sq_pushobject(vm, sector_table);
791   Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
792   expose_object(vm, -1, interface, "settings", false);
793   sq_pop(vm, 1);
794 }
795
796 void
797 Sector::before_object_remove(GameObject* object)
798 {
799   Portable* portable = dynamic_cast<Portable*> (object);
800   if(portable != NULL) {
801     portables.erase(std::find(portables.begin(), portables.end(), portable));
802   }
803   Bullet* bullet = dynamic_cast<Bullet*> (object);
804   if(bullet != NULL) {
805     bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
806   }
807   MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
808   if(moving_object != NULL) {
809     moving_objects.erase(
810         std::find(moving_objects.begin(), moving_objects.end(), moving_object));
811   }
812
813   if(_current == this)
814     try_unexpose(object);
815 }
816
817 void
818 Sector::try_unexpose(GameObject* object)
819 {
820   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
821   if(interface != NULL) {
822     HSQUIRRELVM vm = Scripting::global_vm;
823     SQInteger oldtop = sq_gettop(vm);
824     sq_pushobject(vm, sector_table);
825     try {
826       interface->unexpose(vm, -1);
827     } catch(std::exception& e) {
828       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
829     }
830     sq_settop(vm, oldtop);
831   }
832 }
833
834 void
835 Sector::try_unexpose_me()
836 {
837   HSQUIRRELVM vm = Scripting::global_vm;
838   SQInteger oldtop = sq_gettop(vm);
839   sq_pushobject(vm, sector_table);
840   try {
841     Scripting::unexpose_object(vm, -1, "settings");
842   } catch(std::exception& e) {
843     log_warning << "Couldn't unregister object: " << e.what() << std::endl;
844   }
845   sq_settop(vm, oldtop);
846 }
847 void
848 Sector::draw(DrawingContext& context)
849 {
850   context.set_ambient_color( ambient_light );
851   context.push_transform();
852   context.set_translation(camera->get_translation());
853
854   for(GameObjects::iterator i = gameobjects.begin();
855       i != gameobjects.end(); ++i) {
856     GameObject* object = *i;
857     if(!object->is_valid())
858       continue;
859
860     if (draw_solids_only)
861     {
862       TileMap* tm = dynamic_cast<TileMap*>(object);
863       if (tm && !tm->is_solid())
864         continue;
865     }
866
867     object->draw(context);
868   }
869
870   if(show_collrects) {
871     Color col(0.2f, 0.2f, 0.2f, 0.7f);
872     for(MovingObjects::iterator i = moving_objects.begin();
873             i != moving_objects.end(); ++i) {
874       MovingObject* object = *i;
875       const Rect& rect = object->get_bbox();
876
877       context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
878     }
879   }
880
881   context.pop_transform();
882 }
883
884 /*-------------------------------------------------------------------------
885  * Collision Detection
886  *-------------------------------------------------------------------------*/
887
888 static const float SHIFT_DELTA = 7.0f;
889
890 /** r1 is supposed to be moving, r2 a solid object */
891 void check_collisions(collision::Constraints* constraints,
892                       const Vector& movement, const Rect& r1, const Rect& r2,
893                       GameObject* object = NULL, MovingObject* other = NULL)
894 {
895   if(!collision::intersects(r1, r2))
896     return;
897
898   MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
899   CollisionHit dummy;
900   if(other != NULL && !other->collides(*object, dummy))
901     return;
902   if(moving_object != NULL && !moving_object->collides(*other, dummy))
903     return;
904
905   // calculate intersection
906   float itop    = r1.get_bottom() - r2.get_top();
907   float ibottom = r2.get_bottom() - r1.get_top();
908   float ileft   = r1.get_right() - r2.get_left();
909   float iright  = r2.get_right() - r1.get_left();
910
911   if(fabsf(movement.y) > fabsf(movement.x)) {
912     if(ileft < SHIFT_DELTA) {
913       constraints->right = std::min(constraints->right, r2.get_left());
914       return;
915     } else if(iright < SHIFT_DELTA) {
916       constraints->left = std::max(constraints->left, r2.get_right());
917       return;
918     }
919   } else {
920     // shiftout bottom/top
921     if(itop < SHIFT_DELTA) {
922       constraints->bottom = std::min(constraints->bottom, r2.get_top());
923       return;
924     } else if(ibottom < SHIFT_DELTA) {
925       constraints->top = std::max(constraints->top, r2.get_bottom());
926       return;
927     }
928   }
929
930   if(other != NULL) {
931     HitResponse response = other->collision(*object, dummy);
932     if(response == PASSTHROUGH)
933       return;
934
935     if(other->get_movement() != Vector(0, 0)) {
936       // TODO what todo when we collide with 2 moving objects?!?
937       constraints->ground_movement = other->get_movement();
938     }
939   }
940
941   float vert_penetration = std::min(itop, ibottom);
942   float horiz_penetration = std::min(ileft, iright);
943   if(vert_penetration < horiz_penetration) {
944     if(itop < ibottom) {
945       constraints->bottom = std::min(constraints->bottom, r2.get_top());
946       constraints->hit.bottom = true;
947     } else {
948       constraints->top = std::max(constraints->top, r2.get_bottom());
949       constraints->hit.top = true;
950     }
951   } else {
952     if(ileft < iright) {
953       constraints->right = std::min(constraints->right, r2.get_left());
954       constraints->hit.right = true;
955     } else {
956       constraints->left = std::max(constraints->left, r2.get_right());
957       constraints->hit.left = true;
958     }
959   }
960 }
961
962 static const float DELTA = .001f;
963
964 void
965 Sector::collision_tilemap(collision::Constraints* constraints,
966                           const Vector& movement, const Rect& dest) const
967 {
968   // calculate rectangle where the object will move
969   float x1 = dest.get_left();
970   float x2 = dest.get_right();
971   float y1 = dest.get_top();
972   float y2 = dest.get_bottom();
973
974   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
975     TileMap* solids = *i;
976
977     // test with all tiles in this rectangle
978     int starttilex = int(x1 - solids->get_x_offset()) / 32;
979     int starttiley = int(y1 - solids->get_y_offset()) / 32;
980     int max_x = int(x2 - solids->get_x_offset());
981     int max_y = int(y2+1 - solids->get_y_offset());
982
983     for(int x = starttilex; x*32 < max_x; ++x) {
984       for(int y = starttiley; y*32 < max_y; ++y) {
985         const Tile* tile = solids->get_tile(x, y);
986         if(!tile)
987           continue;
988         // skip non-solid tiles
989         if((tile->getAttributes() & Tile::SOLID) == 0)
990           continue;
991         // only handle unisolid when the player is falling down and when he was
992         // above the tile before
993         if(tile->getAttributes() & Tile::UNISOLID) {
994           if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
995             continue;
996         }
997
998         if(tile->getAttributes() & Tile::SLOPE) { // slope tile
999           AATriangle triangle;
1000           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1001           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1002           triangle = AATriangle(p1, p2, tile->getData());
1003
1004           collision::rectangle_aatriangle(constraints, dest, triangle);
1005         } else { // normal rectangular tile
1006           Rect rect(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset(), (x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1007           check_collisions(constraints, movement, dest, rect);
1008         }
1009       }
1010     }
1011   }
1012 }
1013
1014 uint32_t
1015 Sector::collision_tile_attributes(const Rect& dest) const
1016 {
1017   float x1 = dest.p1.x;
1018   float y1 = dest.p1.y;
1019   float x2 = dest.p2.x;
1020   float y2 = dest.p2.y;
1021
1022   uint32_t result = 0;
1023   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1024     TileMap* solids = *i;
1025
1026     // test with all tiles in this rectangle
1027     int starttilex = int(x1 - solids->get_x_offset()) / 32;
1028     int starttiley = int(y1 - solids->get_y_offset()) / 32;
1029     int max_x = int(x2 - solids->get_x_offset());
1030     int max_y = int(y2+1 - solids->get_y_offset());
1031
1032     for(int x = starttilex; x*32 < max_x; ++x) {
1033       for(int y = starttiley; y*32 < max_y; ++y) {
1034         const Tile* tile = solids->get_tile(x, y);
1035         if(!tile)
1036           continue;
1037         result |= tile->getAttributes();
1038       }
1039     }
1040   }
1041
1042   return result;
1043 }
1044
1045 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1046 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1047                            Vector& normal)
1048 {
1049   float itop = r1.get_bottom() - r2.get_top();
1050   float ibottom = r2.get_bottom() - r1.get_top();
1051   float ileft = r1.get_right() - r2.get_left();
1052   float iright = r2.get_right() - r1.get_left();
1053
1054   float vert_penetration = std::min(itop, ibottom);
1055   float horiz_penetration = std::min(ileft, iright);
1056   if(vert_penetration < horiz_penetration) {
1057     if(itop < ibottom) {
1058       hit.bottom = true;
1059       normal.y = vert_penetration;
1060     } else {
1061       hit.top = true;
1062       normal.y = -vert_penetration;
1063     }
1064   } else {
1065     if(ileft < iright) {
1066       hit.right = true;
1067       normal.x = horiz_penetration;
1068     } else {
1069       hit.left = true;
1070       normal.x = -horiz_penetration;
1071     }
1072   }
1073 }
1074
1075 void
1076 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1077 {
1078   using namespace collision;
1079
1080   const Rect& r1 = object1->dest;
1081   const Rect& r2 = object2->dest;
1082
1083   CollisionHit hit;
1084   if(intersects(object1->dest, object2->dest)) {
1085     Vector normal;
1086     get_hit_normal(r1, r2, hit, normal);
1087
1088     if(!object1->collides(*object2, hit))
1089       return;
1090     std::swap(hit.left, hit.right);
1091     std::swap(hit.top, hit.bottom);
1092     if(!object2->collides(*object1, hit))
1093       return;
1094     std::swap(hit.left, hit.right);
1095     std::swap(hit.top, hit.bottom);
1096
1097     HitResponse response1 = object1->collision(*object2, hit);
1098     std::swap(hit.left, hit.right);
1099     std::swap(hit.top, hit.bottom);
1100     HitResponse response2 = object2->collision(*object1, hit);
1101     if(response1 == CONTINUE && response2 == CONTINUE) {
1102       normal *= (0.5 + DELTA);
1103       object1->dest.move(-normal);
1104       object2->dest.move(normal);
1105     } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1106       normal *= (1 + DELTA);
1107       object1->dest.move(-normal);
1108     } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1109       normal *= (1 + DELTA);
1110       object2->dest.move(normal);
1111     }
1112   }
1113 }
1114
1115 void
1116 Sector::collision_static(collision::Constraints* constraints,
1117                          const Vector& movement, const Rect& dest,
1118                          GameObject& object)
1119 {
1120   collision_tilemap(constraints, movement, dest);
1121
1122   // collision with other (static) objects
1123   for(MovingObjects::iterator i = moving_objects.begin();
1124       i != moving_objects.end(); ++i) {
1125     MovingObject* moving_object = *i;
1126     if(moving_object->get_group() != COLGROUP_STATIC
1127        && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1128       continue;
1129     if(!moving_object->is_valid())
1130       continue;
1131
1132     if(moving_object != &object)
1133       check_collisions(constraints, movement, dest, moving_object->bbox,
1134           &object, moving_object);
1135   }
1136 }
1137
1138 void
1139 Sector::collision_static_constrains(MovingObject& object)
1140 {
1141   using namespace collision;
1142   float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1143
1144   Constraints constraints;
1145   Vector movement = object.get_movement();
1146   Rect& dest = object.dest;
1147   float owidth = object.get_bbox().get_width();
1148   float oheight = object.get_bbox().get_height();
1149
1150   for(int i = 0; i < 2; ++i) {
1151     collision_static(&constraints, Vector(0, movement.y), dest, object);
1152     if(!constraints.has_constraints())
1153       break;
1154
1155     // apply calculated horizontal constraints
1156     if(constraints.bottom < infinity) {
1157       float height = constraints.bottom - constraints.top;
1158       if(height < oheight) {
1159         // we're crushed, but ignore this for now, we'll get this again
1160         // later if we're really crushed or things will solve itself when
1161         // looking at the vertical constraints
1162       }
1163       dest.p2.y = constraints.bottom - DELTA;
1164       dest.p1.y = dest.p2.y - oheight;
1165     } else if(constraints.top > -infinity) {
1166       dest.p1.y = constraints.top + DELTA;
1167       dest.p2.y = dest.p1.y + oheight;
1168     }
1169   }
1170   if(constraints.has_constraints()) {
1171     if(constraints.hit.bottom) {
1172       dest.move(constraints.ground_movement);
1173     }
1174     if(constraints.hit.top || constraints.hit.bottom) {
1175       constraints.hit.left = false;
1176       constraints.hit.right = false;
1177       object.collision_solid(constraints.hit);
1178     }
1179   }
1180
1181   constraints = Constraints();
1182   for(int i = 0; i < 2; ++i) {
1183     collision_static(&constraints, movement, dest, object);
1184     if(!constraints.has_constraints())
1185       break;
1186
1187     // apply calculated vertical constraints
1188     if(constraints.right < infinity) {
1189       float width = constraints.right - constraints.left;
1190       if(width + SHIFT_DELTA < owidth) {
1191 #if 0
1192         printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1193             constraints.left, constraints.right);
1194 #endif
1195         CollisionHit h;
1196         h.left = true;
1197         h.right = true;
1198         h.crush = true;
1199         object.collision_solid(h);
1200       } else {
1201         dest.p2.x = constraints.right - DELTA;
1202         dest.p1.x = dest.p2.x - owidth;
1203       }
1204     } else if(constraints.left > -infinity) {
1205       dest.p1.x = constraints.left + DELTA;
1206       dest.p2.x = dest.p1.x + owidth;
1207     }
1208   }
1209
1210   if(constraints.has_constraints()) {
1211     if( constraints.hit.left || constraints.hit.right
1212         || constraints.hit.top || constraints.hit.bottom
1213         || constraints.hit.crush )
1214       object.collision_solid(constraints.hit);
1215   }
1216
1217   // an extra pass to make sure we're not crushed horizontally
1218   constraints = Constraints();
1219   collision_static(&constraints, movement, dest, object);
1220   if(constraints.bottom < infinity) {
1221     float height = constraints.bottom - constraints.top;
1222     if(height + SHIFT_DELTA < oheight) {
1223 #if 0
1224       printf("Object %p crushed vertically...\n", &object);
1225 #endif
1226       CollisionHit h;
1227       h.top = true;
1228       h.bottom = true;
1229       h.crush = true;
1230       object.collision_solid(h);
1231     }
1232   }
1233 }
1234
1235 namespace {
1236   const float MAX_SPEED = 16.0f;
1237 }
1238
1239 void
1240 Sector::handle_collisions()
1241 {
1242   using namespace collision;
1243
1244   // calculate destination positions of the objects
1245   for(MovingObjects::iterator i = moving_objects.begin();
1246       i != moving_objects.end(); ++i) {
1247     MovingObject* moving_object = *i;
1248     Vector mov = moving_object->get_movement();
1249
1250     // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1251     if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1252       moving_object->movement = mov.unit() * MAX_SPEED;
1253       //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1254     }
1255
1256     moving_object->dest = moving_object->get_bbox();
1257     moving_object->dest.move(moving_object->get_movement());
1258   }
1259
1260   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1261   for(MovingObjects::iterator i = moving_objects.begin();
1262       i != moving_objects.end(); ++i) {
1263     MovingObject* moving_object = *i;
1264     if((moving_object->get_group() != COLGROUP_MOVING
1265           && moving_object->get_group() != COLGROUP_MOVING_STATIC
1266           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1267         || !moving_object->is_valid())
1268       continue;
1269
1270     collision_static_constrains(*moving_object);
1271   }
1272
1273
1274   // part2: COLGROUP_MOVING vs tile attributes
1275   for(MovingObjects::iterator i = moving_objects.begin();
1276       i != moving_objects.end(); ++i) {
1277     MovingObject* moving_object = *i;
1278     if((moving_object->get_group() != COLGROUP_MOVING
1279           && moving_object->get_group() != COLGROUP_MOVING_STATIC
1280           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1281         || !moving_object->is_valid())
1282       continue;
1283
1284     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1285     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1286       moving_object->collision_tile(tile_attributes);
1287     }
1288   }
1289
1290   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1291   for(MovingObjects::iterator i = moving_objects.begin();
1292       i != moving_objects.end(); ++i) {
1293     MovingObject* moving_object = *i;
1294     if((moving_object->get_group() != COLGROUP_MOVING
1295           && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1296         || !moving_object->is_valid())
1297       continue;
1298
1299     for(MovingObjects::iterator i2 = moving_objects.begin();
1300         i2 != moving_objects.end(); ++i2) {
1301       MovingObject* moving_object_2 = *i2;
1302       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1303          || !moving_object_2->is_valid())
1304         continue;
1305
1306       if(intersects(moving_object->dest, moving_object_2->dest)) {
1307         Vector normal;
1308         CollisionHit hit;
1309         get_hit_normal(moving_object->dest, moving_object_2->dest,
1310                        hit, normal);
1311         if(!moving_object->collides(*moving_object_2, hit))
1312           continue;
1313         if(!moving_object_2->collides(*moving_object, hit))
1314           continue;
1315
1316         moving_object->collision(*moving_object_2, hit);
1317         moving_object_2->collision(*moving_object, hit);
1318       }
1319     }
1320   }
1321
1322   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1323   for(MovingObjects::iterator i = moving_objects.begin();
1324       i != moving_objects.end(); ++i) {
1325     MovingObject* moving_object = *i;
1326
1327     if((moving_object->get_group() != COLGROUP_MOVING
1328           && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1329         || !moving_object->is_valid())
1330       continue;
1331
1332     for(MovingObjects::iterator i2 = i+1;
1333         i2 != moving_objects.end(); ++i2) {
1334       MovingObject* moving_object_2 = *i2;
1335       if((moving_object_2->get_group() != COLGROUP_MOVING
1336             && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1337          || !moving_object_2->is_valid())
1338         continue;
1339
1340       collision_object(moving_object, moving_object_2);
1341     }
1342   }
1343
1344   // apply object movement
1345   for(MovingObjects::iterator i = moving_objects.begin();
1346       i != moving_objects.end(); ++i) {
1347     MovingObject* moving_object = *i;
1348
1349     moving_object->bbox = moving_object->dest;
1350     moving_object->movement = Vector(0, 0);
1351   }
1352 }
1353
1354 bool
1355 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1356 {
1357   using namespace collision;
1358
1359   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1360     TileMap* solids = *i;
1361
1362     // test with all tiles in this rectangle
1363     int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1364     int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1365     int max_x = int(rect.p2.x - solids->get_x_offset());
1366     int max_y = int(rect.p2.y - solids->get_y_offset());
1367
1368     for(int x = starttilex; x*32 <= max_x; ++x) {
1369       for(int y = starttiley; y*32 <= max_y; ++y) {
1370         const Tile* tile = solids->get_tile(x, y);
1371         if(!tile) continue;
1372         if(tile->getAttributes() & Tile::SLOPE) {
1373           AATriangle triangle;
1374           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1375           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1376           triangle = AATriangle(p1, p2, tile->getData());
1377           Constraints constraints;
1378           return collision::rectangle_aatriangle(&constraints, rect, triangle);
1379         }
1380         if((tile->getAttributes() & Tile::SOLID) && !ignoreUnisolid) return false;
1381         if((tile->getAttributes() & Tile::SOLID) && !(tile->getAttributes() & Tile::UNISOLID)) return false;
1382       }
1383     }
1384   }
1385
1386   return true;
1387 }
1388
1389 bool
1390 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1391 {
1392   using namespace collision;
1393
1394   if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1395
1396   for(MovingObjects::const_iterator i = moving_objects.begin();
1397       i != moving_objects.end(); ++i) {
1398     const MovingObject* moving_object = *i;
1399     if (moving_object == ignore_object) continue;
1400     if (!moving_object->is_valid()) continue;
1401     if (moving_object->get_group() == COLGROUP_STATIC) {
1402       if(intersects(rect, moving_object->get_bbox())) return false;
1403     }
1404   }
1405
1406   return true;
1407 }
1408
1409 bool
1410 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1411 {
1412   using namespace collision;
1413
1414   if (!is_free_of_tiles(rect)) return false;
1415
1416   for(MovingObjects::const_iterator i = moving_objects.begin();
1417       i != moving_objects.end(); ++i) {
1418     const MovingObject* moving_object = *i;
1419     if (moving_object == ignore_object) continue;
1420     if (!moving_object->is_valid()) continue;
1421     if ((moving_object->get_group() == COLGROUP_MOVING)
1422       || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1423       || (moving_object->get_group() == COLGROUP_STATIC)) {
1424       if(intersects(rect, moving_object->get_bbox())) return false;
1425     }
1426   }
1427
1428   return true;
1429 }
1430
1431 bool
1432 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1433 {
1434   // TODO remove this function and move these checks elsewhere...
1435
1436   Bullet* new_bullet = 0;
1437   if((player_status->bonus == FIRE_BONUS &&
1438       (int)bullets.size() >= player_status->max_fire_bullets) ||
1439      (player_status->bonus == ICE_BONUS &&
1440       (int)bullets.size() >= player_status->max_ice_bullets))
1441     return false;
1442   new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1443   add_object(new_bullet);
1444
1445   sound_manager->play("sounds/shoot.wav");
1446
1447   return true;
1448 }
1449
1450 bool
1451 Sector::add_smoke_cloud(const Vector& pos)
1452 {
1453   add_object(new SmokeCloud(pos));
1454   return true;
1455 }
1456
1457 void
1458 Sector::play_music(MusicType type)
1459 {
1460   currentmusic = type;
1461   switch(currentmusic) {
1462     case LEVEL_MUSIC:
1463       sound_manager->play_music(music);
1464       break;
1465     case HERRING_MUSIC:
1466       sound_manager->play_music("music/salcon.ogg");
1467       break;
1468     case HERRING_WARNING_MUSIC:
1469       sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1470       break;
1471     default:
1472       sound_manager->play_music("");
1473       break;
1474   }
1475 }
1476
1477 MusicType
1478 Sector::get_music_type()
1479 {
1480   return currentmusic;
1481 }
1482
1483 int
1484 Sector::get_total_badguys()
1485 {
1486   int total_badguys = 0;
1487   for(GameObjects::iterator i = gameobjects.begin();
1488       i != gameobjects.end(); ++i) {
1489     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1490     if (badguy && badguy->countMe)
1491       total_badguys++;
1492   }
1493
1494   return total_badguys;
1495 }
1496
1497 bool
1498 Sector::inside(const Rect& rect) const
1499 {
1500   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1501     TileMap* solids = *i;
1502     bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1503     bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1504
1505     if (horizontally && vertically)
1506       return true;
1507   }
1508   return false;
1509 }
1510
1511 float
1512 Sector::get_width() const
1513 {
1514   float width = 0;
1515   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1516       i != solid_tilemaps.end(); i++) {
1517     TileMap* solids = *i;
1518     if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1519       width = solids->get_width() * 32 + solids->get_x_offset();
1520     }
1521   }
1522
1523   return width;
1524 }
1525
1526 float
1527 Sector::get_height() const
1528 {
1529   float height = 0;
1530   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1531       i != solid_tilemaps.end(); i++) {
1532     TileMap* solids = *i;
1533     if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1534       height = solids->get_height() * 32 + solids->get_y_offset();
1535     }
1536   }
1537
1538   return height;
1539 }
1540
1541 void
1542 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1543 {
1544   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1545     TileMap* solids = *i;
1546     solids->change_all(old_tile_id, new_tile_id);
1547   }
1548 }
1549
1550
1551 void
1552 Sector::set_ambient_light(float red, float green, float blue)
1553 {
1554   ambient_light.red = red;
1555   ambient_light.green = green;
1556   ambient_light.blue = blue;
1557 }
1558
1559 float
1560 Sector::get_ambient_red()
1561 {
1562   return ambient_light.red;
1563 }
1564
1565 float
1566 Sector::get_ambient_green()
1567 {
1568   return ambient_light.green;
1569 }
1570
1571 float
1572 Sector::get_ambient_blue()
1573 {
1574   return ambient_light.blue;
1575 }