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