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