Applied sound pre-loading patch from mathnerd314 (#331)
[supertux.git] / src / sector.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <memory>
22 #include <algorithm>
23 #include <stdexcept>
24 #include <iostream>
25 #include <fstream>
26 #include <sstream>
27 #include <stdexcept>
28 #include <float.h>
29 #include <math.h>
30 #include <limits>
31 #include <physfs.h>
32
33 #include "sector.hpp"
34 #include "object/player.hpp"
35 #include "object/gameobjs.hpp"
36 #include "object/camera.hpp"
37 #include "object/background.hpp"
38 #include "object/gradient.hpp"
39 #include "object/particlesystem.hpp"
40 #include "object/particlesystem_interactive.hpp"
41 #include "object/tilemap.hpp"
42 #include "lisp/parser.hpp"
43 #include "lisp/lisp.hpp"
44 #include "lisp/writer.hpp"
45 #include "lisp/list_iterator.hpp"
46 #include "tile.hpp"
47 #include "audio/sound_manager.hpp"
48 #include "game_session.hpp"
49 #include "resources.hpp"
50 #include "statistics.hpp"
51 #include "object_factory.hpp"
52 #include "collision.hpp"
53 #include "spawn_point.hpp"
54 #include "math/rect.hpp"
55 #include "math/aatriangle.hpp"
56 #include "object/coin.hpp"
57 #include "object/block.hpp"
58 #include "object/invisible_block.hpp"
59 #include "object/light.hpp"
60 #include "object/pulsing_light.hpp"
61 #include "object/bullet.hpp"
62 #include "object/text_object.hpp"
63 #include "object/portable.hpp"
64 #include "badguy/jumpy.hpp"
65 #include "trigger/sequence_trigger.hpp"
66 #include "player_status.hpp"
67 #include "scripting/squirrel_util.hpp"
68 #include "script_interface.hpp"
69 #include "log.hpp"
70 #include "main.hpp"
71 #include "level.hpp"
72
73 Sector* Sector::_current = 0;
74
75 bool Sector::show_collrects = false;
76 bool Sector::draw_solids_only = false;
77
78 Sector::Sector(Level* parent)
79   : level(parent), currentmusic(LEVEL_MUSIC),
80   ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10.0), player(0), camera(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 lisp::Lisp& 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 lisp::Lisp& 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_vector( "ambient-light", vColor );
201       if(vColor.size() < 3) {
202         log_warning << "(ambient-light) requires a color as argument" << std::endl;
203       } else {
204         ambient_light = Color( vColor );
205       }
206     } else {
207       GameObject* object = parse_object(token, *(iter.lisp()));
208       if(object) {
209         if(dynamic_cast<Background *>(object)) {
210            has_background = true;
211         } else if(dynamic_cast<Gradient *>(object)) {
212            has_background = true;
213         }
214         add_object(object);
215       }
216     }
217   }
218
219   if(!has_background) {
220     Gradient* gradient = new Gradient();
221     gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
222     add_object(gradient);
223   }
224
225   update_game_objects();
226
227   if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
228
229   fix_old_tiles();
230   if(!camera) {
231     log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
232     update_game_objects();
233     add_object(new Camera(this, "Camera"));
234   }
235
236   update_game_objects();
237 }
238
239 void
240 Sector::parse_old_format(const lisp::Lisp& reader)
241 {
242   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_vector("interactive-tm", tiles)
318       || reader.get_vector("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_vector("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_vector("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
463 void
464 Sector::write(lisp::Writer& writer)
465 {
466   writer.write_string("name", name);
467   writer.write_float("gravity", gravity);
468   writer.write_string("music", music);
469
470   // write spawnpoints
471   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
472       ++i) {
473     SpawnPoint* spawn = *i;
474     writer.start_list("spawn-points");
475     writer.write_string("name", spawn->name);
476     writer.write_float("x", spawn->pos.x);
477     writer.write_float("y", spawn->pos.y);
478     writer.end_list("spawn-points");
479   }
480
481   // write objects
482   for(GameObjects::iterator i = gameobjects.begin();
483       i != gameobjects.end(); ++i) {
484     Serializable* serializable = dynamic_cast<Serializable*> (*i);
485     if(serializable)
486       serializable->write(writer);
487   }
488 }
489
490 HSQUIRRELVM
491 Sector::run_script(std::istream& in, const std::string& sourcename)
492 {
493   using namespace Scripting;
494
495   // garbage collect thread list
496   for(ScriptList::iterator i = scripts.begin();
497       i != scripts.end(); ) {
498     HSQOBJECT& object = *i;
499     HSQUIRRELVM vm = object_to_vm(object);
500
501     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
502       sq_release(global_vm, &object);
503       i = scripts.erase(i);
504       continue;
505     }
506
507     ++i;
508   }
509
510   HSQOBJECT object = create_thread(global_vm);
511   scripts.push_back(object);
512
513   HSQUIRRELVM vm = object_to_vm(object);
514
515   // set sector_table as roottable for the thread
516   sq_pushobject(vm, sector_table);
517   sq_setroottable(vm);
518
519   compile_and_run(vm, in, sourcename);
520
521   return vm;
522 }
523
524 void
525 Sector::add_object(GameObject* object)
526 {
527   // make sure the object isn't already in the list
528 #ifdef DEBUG
529   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
530       ++i) {
531     if(*i == object) {
532       assert("object already added to sector" == 0);
533     }
534   }
535   for(GameObjects::iterator i = gameobjects_new.begin();
536       i != gameobjects_new.end(); ++i) {
537     if(*i == object) {
538       assert("object already added to sector" == 0);
539     }
540   }
541 #endif
542
543   object->ref();
544   gameobjects_new.push_back(object);
545 }
546
547 void
548 Sector::activate(const std::string& spawnpoint)
549 {
550   SpawnPoint* sp = 0;
551   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
552       ++i) {
553     if((*i)->name == spawnpoint) {
554       sp = *i;
555       break;
556     }
557   }
558   if(!sp) {
559     log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
560     if(spawnpoint != "main") {
561       activate("main");
562     } else {
563       activate(Vector(0, 0));
564     }
565   } else {
566     activate(sp->pos);
567   }
568 }
569
570 void
571 Sector::activate(const Vector& player_pos)
572 {
573   if(_current != this) {
574     if(_current != NULL)
575       _current->deactivate();
576     _current = this;
577
578     // register sectortable as sector in scripting
579     HSQUIRRELVM vm = Scripting::global_vm;
580     sq_pushroottable(vm);
581     sq_pushstring(vm, "sector", -1);
582     sq_pushobject(vm, sector_table);
583     if(SQ_FAILED(sq_createslot(vm, -3)))
584       throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
585     sq_pop(vm, 1);
586
587     for(GameObjects::iterator i = gameobjects.begin();
588         i != gameobjects.end(); ++i) {
589       GameObject* object = *i;
590
591       try_expose(object);
592     }
593   }
594   try_expose_me();
595
596   // spawn smalltux below spawnpoint
597   if (!player->is_big()) {
598     player->move(player_pos + Vector(0,32));
599   } else {
600     player->move(player_pos);
601   }
602
603   // spawning tux in the ground would kill him
604   if(!is_free_of_tiles(player->get_bbox())) {
605     log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
606     Vector npos = player->get_bbox().p1;
607     npos.y-=32;
608     player->move(npos);
609   }
610
611   camera->reset(player->get_pos());
612   update_game_objects();
613
614   // Run init script
615   if(init_script != "") {
616     std::istringstream in(init_script);
617     run_script(in, std::string("Sector(") + name + ") - init");
618   }
619 }
620
621 void
622 Sector::deactivate()
623 {
624   if(_current != this)
625     return;
626
627   // remove sector entry from global vm
628   HSQUIRRELVM vm = Scripting::global_vm;
629   sq_pushroottable(vm);
630   sq_pushstring(vm, "sector", -1);
631   if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
632     throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
633   sq_pop(vm, 1);
634
635   for(GameObjects::iterator i = gameobjects.begin();
636       i != gameobjects.end(); ++i) {
637     GameObject* object = *i;
638
639     try_unexpose(object);
640   }
641
642   try_unexpose_me();
643   _current = NULL;
644 }
645
646 Rect
647 Sector::get_active_region()
648 {
649   return Rect(
650     camera->get_translation() - Vector(1600, 1200),
651     camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
652 }
653
654 void
655 Sector::update(float elapsed_time)
656 {
657   player->check_bounds(camera);
658
659   /* update objects */
660   for(GameObjects::iterator i = gameobjects.begin();
661           i != gameobjects.end(); ++i) {
662     GameObject* object = *i;
663     if(!object->is_valid())
664       continue;
665
666     object->update(elapsed_time);
667   }
668
669   /* Handle all possible collisions. */
670   handle_collisions();
671   update_game_objects();
672 }
673
674 void
675 Sector::update_game_objects()
676 {
677   /** cleanup marked objects */
678   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
679       i != gameobjects.end(); /* nothing */) {
680     GameObject* object = *i;
681
682     if(object->is_valid()) {
683       ++i;
684       continue;
685     }
686
687     before_object_remove(object);
688
689     object->unref();
690     i = gameobjects.erase(i);
691   }
692
693   /* add newly created objects */
694   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
695       i != gameobjects_new.end(); ++i)
696   {
697     GameObject* object = *i;
698
699     before_object_add(object);
700
701     gameobjects.push_back(object);
702   }
703   gameobjects_new.clear();
704
705   /* update solid_tilemaps list */
706   //FIXME: this could be more efficient
707   solid_tilemaps.clear();
708   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
709       i != gameobjects.end(); ++i)
710   {
711     TileMap* tm = dynamic_cast<TileMap*>(*i);
712     if (!tm) continue;
713     if (tm->is_solid()) solid_tilemaps.push_back(tm);
714   }
715
716 }
717
718 bool
719 Sector::before_object_add(GameObject* object)
720 {
721   Bullet* bullet = dynamic_cast<Bullet*> (object);
722   if(bullet != NULL) {
723     bullets.push_back(bullet);
724   }
725
726   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
727   if(movingobject != NULL) {
728     moving_objects.push_back(movingobject);
729   }
730
731   Portable* portable = dynamic_cast<Portable*> (object);
732   if(portable != NULL) {
733     portables.push_back(portable);
734   }
735
736   TileMap* tilemap = dynamic_cast<TileMap*> (object);
737   if(tilemap != NULL && tilemap->is_solid()) {
738     solid_tilemaps.push_back(tilemap);
739   }
740
741   Camera* camera = dynamic_cast<Camera*> (object);
742   if(camera != NULL) {
743     if(this->camera != 0) {
744       log_warning << "Multiple cameras added. Ignoring" << std::endl;
745       return false;
746     }
747     this->camera = camera;
748   }
749
750   Player* player = dynamic_cast<Player*> (object);
751   if(player != NULL) {
752     if(this->player != 0) {
753       log_warning << "Multiple players added. Ignoring" << std::endl;
754       return false;
755     }
756     this->player = player;
757   }
758
759   UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
760   if(physic_object)
761   {
762     physic_object->physic.set_gravity(gravity);
763   }
764
765
766   if(_current == this) {
767     try_expose(object);
768   }
769
770   return true;
771 }
772
773 void
774 Sector::try_expose(GameObject* object)
775 {
776   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
777   if(interface != NULL) {
778     HSQUIRRELVM vm = Scripting::global_vm;
779     sq_pushobject(vm, sector_table);
780     interface->expose(vm, -1);
781     sq_pop(vm, 1);
782   }
783 }
784
785 void
786 Sector::try_expose_me()
787 {
788   HSQUIRRELVM vm = Scripting::global_vm;
789   sq_pushobject(vm, sector_table);
790   Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
791   expose_object(vm, -1, interface, "settings", false);
792   sq_pop(vm, 1);
793 }
794
795 void
796 Sector::before_object_remove(GameObject* object)
797 {
798   Portable* portable = dynamic_cast<Portable*> (object);
799   if(portable != NULL) {
800     portables.erase(std::find(portables.begin(), portables.end(), portable));
801   }
802   Bullet* bullet = dynamic_cast<Bullet*> (object);
803   if(bullet != NULL) {
804     bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
805   }
806   MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
807   if(moving_object != NULL) {
808     moving_objects.erase(
809         std::find(moving_objects.begin(), moving_objects.end(), moving_object));
810   }
811
812   if(_current == this)
813     try_unexpose(object);
814 }
815
816 void
817 Sector::try_unexpose(GameObject* object)
818 {
819   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
820   if(interface != NULL) {
821     HSQUIRRELVM vm = Scripting::global_vm;
822     SQInteger oldtop = sq_gettop(vm);
823     sq_pushobject(vm, sector_table);
824     try {
825       interface->unexpose(vm, -1);
826     } catch(std::exception& e) {
827       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
828     }
829     sq_settop(vm, oldtop);
830   }
831 }
832
833 void
834 Sector::try_unexpose_me()
835 {
836   HSQUIRRELVM vm = Scripting::global_vm;
837   SQInteger oldtop = sq_gettop(vm);
838   sq_pushobject(vm, sector_table);
839   try {
840     Scripting::unexpose_object(vm, -1, "settings");
841   } catch(std::exception& e) {
842     log_warning << "Couldn't unregister object: " << e.what() << std::endl;
843   }
844   sq_settop(vm, oldtop);
845 }
846 void
847 Sector::draw(DrawingContext& context)
848 {
849   context.set_ambient_color( ambient_light );
850   context.push_transform();
851   context.set_translation(camera->get_translation());
852
853   for(GameObjects::iterator i = gameobjects.begin();
854       i != gameobjects.end(); ++i) {
855     GameObject* object = *i;
856     if(!object->is_valid())
857       continue;
858
859     if (draw_solids_only)
860     {
861       TileMap* tm = dynamic_cast<TileMap*>(object);
862       if (tm && !tm->is_solid())
863         continue;
864     }
865
866     object->draw(context);
867   }
868
869   if(show_collrects) {
870     Color col(0.2f, 0.2f, 0.2f, 0.7f);
871     for(MovingObjects::iterator i = moving_objects.begin();
872             i != moving_objects.end(); ++i) {
873       MovingObject* object = *i;
874       const Rect& rect = object->get_bbox();
875
876       context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
877     }
878   }
879
880   context.pop_transform();
881 }
882
883 /*-------------------------------------------------------------------------
884  * Collision Detection
885  *-------------------------------------------------------------------------*/
886
887 static const float SHIFT_DELTA = 7.0f;
888
889 /** r1 is supposed to be moving, r2 a solid object */
890 void check_collisions(collision::Constraints* constraints,
891                       const Vector& movement, const Rect& r1, const Rect& r2,
892                       GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
893 {
894   if(!collision::intersects(r1, r2))
895     return;
896
897   MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
898   CollisionHit dummy;
899   if(other != NULL && !other->collides(*object, dummy))
900     return;
901   if(moving_object != NULL && !moving_object->collides(*other, dummy))
902     return;
903
904   // calculate intersection
905   float itop    = r1.get_bottom() - r2.get_top();
906   float ibottom = r2.get_bottom() - r1.get_top();
907   float ileft   = r1.get_right() - r2.get_left();
908   float iright  = r2.get_right() - r1.get_left();
909
910   if(fabsf(movement.y) > fabsf(movement.x)) {
911     if(ileft < SHIFT_DELTA) {
912       constraints->right = std::min(constraints->right, r2.get_left());
913       return;
914     } else if(iright < SHIFT_DELTA) {
915       constraints->left = std::max(constraints->left, r2.get_right());
916       return;
917     }
918   } else {
919     // shiftout bottom/top
920     if(itop < SHIFT_DELTA) {
921       constraints->bottom = std::min(constraints->bottom, r2.get_top());
922       return;
923     } else if(ibottom < SHIFT_DELTA) {
924       constraints->top = std::max(constraints->top, r2.get_bottom());
925       return;
926     }
927   }
928
929   constraints->ground_movement += addl_ground_movement;
930   if(other != NULL) {
931     HitResponse response = other->collision(*object, dummy);
932     if(response == PASSTHROUGH)
933       return;
934
935     if(other->get_movement() != Vector(0, 0)) {
936       // TODO what todo when we collide with 2 moving objects?!?
937       constraints->ground_movement += other->get_movement();
938     }
939   }
940
941   float vert_penetration = std::min(itop, ibottom);
942   float horiz_penetration = std::min(ileft, iright);
943   if(vert_penetration < horiz_penetration) {
944     if(itop < ibottom) {
945       constraints->bottom = std::min(constraints->bottom, r2.get_top());
946       constraints->hit.bottom = true;
947     } else {
948       constraints->top = std::max(constraints->top, r2.get_bottom());
949       constraints->hit.top = true;
950     }
951   } else {
952     if(ileft < iright) {
953       constraints->right = std::min(constraints->right, r2.get_left());
954       constraints->hit.right = true;
955     } else {
956       constraints->left = std::max(constraints->left, r2.get_right());
957       constraints->hit.left = true;
958     }
959   }
960 }
961
962 static const float DELTA = .001f;
963
964 void
965 Sector::collision_tilemap(collision::Constraints* constraints,
966                           const Vector& movement, const Rect& dest) const
967 {
968   // calculate rectangle where the object will move
969   float x1 = dest.get_left();
970   float x2 = dest.get_right();
971   float y1 = dest.get_top();
972   float y2 = dest.get_bottom();
973
974   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
975     TileMap* solids = *i;
976
977     // test with all tiles in this rectangle
978     int starttilex = int(x1 - solids->get_x_offset()) / 32;
979     int starttiley = int(y1 - solids->get_y_offset()) / 32;
980     int max_x = int(x2 - solids->get_x_offset());
981     int max_y = int(y2+1 - solids->get_y_offset());
982
983     for(int x = starttilex; x*32 < max_x; ++x) {
984       for(int y = starttiley; y*32 < max_y; ++y) {
985         const Tile* tile = solids->get_tile(x, y);
986         if(!tile)
987           continue;
988         // skip non-solid tiles
989         if((tile->getAttributes() & Tile::SOLID) == 0)
990           continue;
991         // only handle unisolid when the player is falling down and when he was
992         // above the tile before
993         if(tile->getAttributes() & Tile::UNISOLID) {
994           if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
995             continue;
996         }
997
998         if(tile->getAttributes() & Tile::SLOPE) { // slope tile
999           AATriangle triangle;
1000           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1001           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1002           triangle = AATriangle(p1, p2, tile->getData());
1003
1004           collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
1005         } else { // normal rectangular tile
1006           Rect rect(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset(), (x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1007           check_collisions(constraints, movement, dest, rect, NULL, NULL, solids->get_movement());
1008         }
1009       }
1010     }
1011   }
1012 }
1013
1014 uint32_t
1015 Sector::collision_tile_attributes(const Rect& dest) const
1016 {
1017   float x1 = dest.p1.x;
1018   float y1 = dest.p1.y;
1019   float x2 = dest.p2.x;
1020   float y2 = dest.p2.y;
1021
1022   uint32_t result = 0;
1023   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1024     TileMap* solids = *i;
1025
1026     // test with all tiles in this rectangle
1027     int starttilex = int(x1 - solids->get_x_offset()) / 32;
1028     int starttiley = int(y1 - solids->get_y_offset()) / 32;
1029     int max_x = int(x2 - solids->get_x_offset());
1030     int max_y = int(y2+1 - solids->get_y_offset());
1031
1032     for(int x = starttilex; x*32 < max_x; ++x) {
1033       for(int y = starttiley; y*32 < max_y; ++y) {
1034         const Tile* tile = solids->get_tile(x, y);
1035         if(!tile)
1036           continue;
1037         result |= tile->getAttributes();
1038       }
1039     }
1040   }
1041
1042   return result;
1043 }
1044
1045 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1046 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1047                            Vector& normal)
1048 {
1049   float itop = r1.get_bottom() - r2.get_top();
1050   float ibottom = r2.get_bottom() - r1.get_top();
1051   float ileft = r1.get_right() - r2.get_left();
1052   float iright = r2.get_right() - r1.get_left();
1053
1054   float vert_penetration = std::min(itop, ibottom);
1055   float horiz_penetration = std::min(ileft, iright);
1056   if(vert_penetration < horiz_penetration) {
1057     if(itop < ibottom) {
1058       hit.bottom = true;
1059       normal.y = vert_penetration;
1060     } else {
1061       hit.top = true;
1062       normal.y = -vert_penetration;
1063     }
1064   } else {
1065     if(ileft < iright) {
1066       hit.right = true;
1067       normal.x = horiz_penetration;
1068     } else {
1069       hit.left = true;
1070       normal.x = -horiz_penetration;
1071     }
1072   }
1073 }
1074
1075 void
1076 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1077 {
1078   using namespace collision;
1079
1080   const Rect& r1 = object1->dest;
1081   const Rect& r2 = object2->dest;
1082
1083   CollisionHit hit;
1084   if(intersects(object1->dest, object2->dest)) {
1085     Vector normal;
1086     get_hit_normal(r1, r2, hit, normal);
1087
1088     if(!object1->collides(*object2, hit))
1089       return;
1090     std::swap(hit.left, hit.right);
1091     std::swap(hit.top, hit.bottom);
1092     if(!object2->collides(*object1, hit))
1093       return;
1094     std::swap(hit.left, hit.right);
1095     std::swap(hit.top, hit.bottom);
1096
1097     HitResponse response1 = object1->collision(*object2, hit);
1098     std::swap(hit.left, hit.right);
1099     std::swap(hit.top, hit.bottom);
1100     HitResponse response2 = object2->collision(*object1, hit);
1101     if(response1 == CONTINUE && response2 == CONTINUE) {
1102       normal *= (0.5 + DELTA);
1103       object1->dest.move(-normal);
1104       object2->dest.move(normal);
1105     } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1106       normal *= (1 + DELTA);
1107       object1->dest.move(-normal);
1108     } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1109       normal *= (1 + DELTA);
1110       object2->dest.move(normal);
1111     }
1112   }
1113 }
1114
1115 void
1116 Sector::collision_static(collision::Constraints* constraints,
1117                          const Vector& movement, const Rect& dest,
1118                          GameObject& object)
1119 {
1120   collision_tilemap(constraints, movement, dest);
1121
1122   // collision with other (static) objects
1123   for(MovingObjects::iterator i = moving_objects.begin();
1124       i != moving_objects.end(); ++i) {
1125     MovingObject* moving_object = *i;
1126     if(moving_object->get_group() != COLGROUP_STATIC
1127        && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1128       continue;
1129     if(!moving_object->is_valid())
1130       continue;
1131
1132     if(moving_object != &object)
1133       check_collisions(constraints, movement, dest, moving_object->bbox,
1134           &object, moving_object);
1135   }
1136 }
1137
1138 void
1139 Sector::collision_static_constrains(MovingObject& object)
1140 {
1141   using namespace collision;
1142   float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1143
1144   Constraints constraints;
1145   Vector movement = object.get_movement();
1146   Rect& dest = object.dest;
1147   float owidth = object.get_bbox().get_width();
1148   float oheight = object.get_bbox().get_height();
1149
1150   for(int i = 0; i < 2; ++i) {
1151     collision_static(&constraints, Vector(0, movement.y), dest, object);
1152     if(!constraints.has_constraints())
1153       break;
1154
1155     // apply calculated horizontal constraints
1156     if(constraints.bottom < infinity) {
1157       float height = constraints.bottom - constraints.top;
1158       if(height < oheight) {
1159         // we're crushed, but ignore this for now, we'll get this again
1160         // later if we're really crushed or things will solve itself when
1161         // looking at the vertical constraints
1162       }
1163       dest.p2.y = constraints.bottom - DELTA;
1164       dest.p1.y = dest.p2.y - oheight;
1165     } else if(constraints.top > -infinity) {
1166       dest.p1.y = constraints.top + DELTA;
1167       dest.p2.y = dest.p1.y + oheight;
1168     }
1169   }
1170   if(constraints.has_constraints()) {
1171     if(constraints.hit.bottom) {
1172       dest.move(constraints.ground_movement);
1173     }
1174     if(constraints.hit.top || constraints.hit.bottom) {
1175       constraints.hit.left = false;
1176       constraints.hit.right = false;
1177       object.collision_solid(constraints.hit);
1178     }
1179   }
1180
1181   constraints = Constraints();
1182   for(int i = 0; i < 2; ++i) {
1183     collision_static(&constraints, movement, dest, object);
1184     if(!constraints.has_constraints())
1185       break;
1186
1187     // apply calculated vertical constraints
1188     if(constraints.right < infinity) {
1189       float width = constraints.right - constraints.left;
1190       if(width + SHIFT_DELTA < owidth) {
1191 #if 0
1192         printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1193             constraints.left, constraints.right);
1194 #endif
1195         CollisionHit h;
1196         h.left = true;
1197         h.right = true;
1198         h.crush = true;
1199         object.collision_solid(h);
1200       } else {
1201         dest.p2.x = constraints.right - DELTA;
1202         dest.p1.x = dest.p2.x - owidth;
1203       }
1204     } else if(constraints.left > -infinity) {
1205       dest.p1.x = constraints.left + DELTA;
1206       dest.p2.x = dest.p1.x + owidth;
1207     }
1208   }
1209
1210   if(constraints.has_constraints()) {
1211     if( constraints.hit.left || constraints.hit.right
1212         || constraints.hit.top || constraints.hit.bottom
1213         || constraints.hit.crush )
1214       object.collision_solid(constraints.hit);
1215   }
1216
1217   // an extra pass to make sure we're not crushed horizontally
1218   constraints = Constraints();
1219   collision_static(&constraints, movement, dest, object);
1220   if(constraints.bottom < infinity) {
1221     float height = constraints.bottom - constraints.top;
1222     if(height + SHIFT_DELTA < oheight) {
1223 #if 0
1224       printf("Object %p crushed vertically...\n", &object);
1225 #endif
1226       CollisionHit h;
1227       h.top = true;
1228       h.bottom = true;
1229       h.crush = true;
1230       object.collision_solid(h);
1231     }
1232   }
1233 }
1234
1235 namespace {
1236   const float MAX_SPEED = 16.0f;
1237 }
1238
1239 void
1240 Sector::handle_collisions()
1241 {
1242   using namespace collision;
1243
1244   // calculate destination positions of the objects
1245   for(MovingObjects::iterator i = moving_objects.begin();
1246       i != moving_objects.end(); ++i) {
1247     MovingObject* moving_object = *i;
1248     Vector mov = moving_object->get_movement();
1249
1250     // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1251     if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1252       moving_object->movement = mov.unit() * MAX_SPEED;
1253       //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1254     }
1255
1256     moving_object->dest = moving_object->get_bbox();
1257     moving_object->dest.move(moving_object->get_movement());
1258   }
1259
1260   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1261   for(MovingObjects::iterator i = moving_objects.begin();
1262       i != moving_objects.end(); ++i) {
1263     MovingObject* moving_object = *i;
1264     if((moving_object->get_group() != COLGROUP_MOVING
1265           && moving_object->get_group() != COLGROUP_MOVING_STATIC
1266           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1267         || !moving_object->is_valid())
1268       continue;
1269
1270     collision_static_constrains(*moving_object);
1271   }
1272
1273
1274   // part2: COLGROUP_MOVING vs tile attributes
1275   for(MovingObjects::iterator i = moving_objects.begin();
1276       i != moving_objects.end(); ++i) {
1277     MovingObject* moving_object = *i;
1278     if((moving_object->get_group() != COLGROUP_MOVING
1279           && moving_object->get_group() != COLGROUP_MOVING_STATIC
1280           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1281         || !moving_object->is_valid())
1282       continue;
1283
1284     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1285     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1286       moving_object->collision_tile(tile_attributes);
1287     }
1288   }
1289
1290   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1291   for(MovingObjects::iterator i = moving_objects.begin();
1292       i != moving_objects.end(); ++i) {
1293     MovingObject* moving_object = *i;
1294     if((moving_object->get_group() != COLGROUP_MOVING
1295           && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1296         || !moving_object->is_valid())
1297       continue;
1298
1299     for(MovingObjects::iterator i2 = moving_objects.begin();
1300         i2 != moving_objects.end(); ++i2) {
1301       MovingObject* moving_object_2 = *i2;
1302       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1303          || !moving_object_2->is_valid())
1304         continue;
1305
1306       if(intersects(moving_object->dest, moving_object_2->dest)) {
1307         Vector normal;
1308         CollisionHit hit;
1309         get_hit_normal(moving_object->dest, moving_object_2->dest,
1310                        hit, normal);
1311         if(!moving_object->collides(*moving_object_2, hit))
1312           continue;
1313         if(!moving_object_2->collides(*moving_object, hit))
1314           continue;
1315
1316         moving_object->collision(*moving_object_2, hit);
1317         moving_object_2->collision(*moving_object, hit);
1318       }
1319     }
1320   }
1321
1322   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1323   for(MovingObjects::iterator i = moving_objects.begin();
1324       i != moving_objects.end(); ++i) {
1325     MovingObject* moving_object = *i;
1326
1327     if((moving_object->get_group() != COLGROUP_MOVING
1328           && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1329         || !moving_object->is_valid())
1330       continue;
1331
1332     for(MovingObjects::iterator i2 = i+1;
1333         i2 != moving_objects.end(); ++i2) {
1334       MovingObject* moving_object_2 = *i2;
1335       if((moving_object_2->get_group() != COLGROUP_MOVING
1336             && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1337          || !moving_object_2->is_valid())
1338         continue;
1339
1340       collision_object(moving_object, moving_object_2);
1341     }
1342   }
1343
1344   // apply object movement
1345   for(MovingObjects::iterator i = moving_objects.begin();
1346       i != moving_objects.end(); ++i) {
1347     MovingObject* moving_object = *i;
1348
1349     moving_object->bbox = moving_object->dest;
1350     moving_object->movement = Vector(0, 0);
1351   }
1352 }
1353
1354 bool
1355 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1356 {
1357   using namespace collision;
1358
1359   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1360     TileMap* solids = *i;
1361
1362     // test with all tiles in this rectangle
1363     int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1364     int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1365     int max_x = int(rect.p2.x - solids->get_x_offset());
1366     int max_y = int(rect.p2.y - solids->get_y_offset());
1367
1368     for(int x = starttilex; x*32 <= max_x; ++x) {
1369       for(int y = starttiley; y*32 <= max_y; ++y) {
1370         const Tile* tile = solids->get_tile(x, y);
1371         if(!tile) continue;
1372         if(tile->getAttributes() & Tile::SLOPE) {
1373           AATriangle triangle;
1374           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1375           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1376           triangle = AATriangle(p1, p2, tile->getData());
1377           Constraints constraints;
1378           return collision::rectangle_aatriangle(&constraints, rect, triangle);
1379         }
1380         if((tile->getAttributes() & Tile::SOLID) && !ignoreUnisolid) return false;
1381         if((tile->getAttributes() & Tile::SOLID) && !(tile->getAttributes() & Tile::UNISOLID)) return false;
1382       }
1383     }
1384   }
1385
1386   return true;
1387 }
1388
1389 bool
1390 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1391 {
1392   using namespace collision;
1393
1394   if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1395
1396   for(MovingObjects::const_iterator i = moving_objects.begin();
1397       i != moving_objects.end(); ++i) {
1398     const MovingObject* moving_object = *i;
1399     if (moving_object == ignore_object) continue;
1400     if (!moving_object->is_valid()) continue;
1401     if (moving_object->get_group() == COLGROUP_STATIC) {
1402       if(intersects(rect, moving_object->get_bbox())) return false;
1403     }
1404   }
1405
1406   return true;
1407 }
1408
1409 bool
1410 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1411 {
1412   using namespace collision;
1413
1414   if (!is_free_of_tiles(rect)) return false;
1415
1416   for(MovingObjects::const_iterator i = moving_objects.begin();
1417       i != moving_objects.end(); ++i) {
1418     const MovingObject* moving_object = *i;
1419     if (moving_object == ignore_object) continue;
1420     if (!moving_object->is_valid()) continue;
1421     if ((moving_object->get_group() == COLGROUP_MOVING)
1422       || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1423       || (moving_object->get_group() == COLGROUP_STATIC)) {
1424       if(intersects(rect, moving_object->get_bbox())) return false;
1425     }
1426   }
1427
1428   return true;
1429 }
1430
1431 bool
1432 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1433 {
1434   // TODO remove this function and move these checks elsewhere...
1435
1436   Bullet* new_bullet = 0;
1437   if((player_status->bonus == FIRE_BONUS &&
1438       (int)bullets.size() >= player_status->max_fire_bullets) ||
1439      (player_status->bonus == ICE_BONUS &&
1440       (int)bullets.size() >= player_status->max_ice_bullets))
1441     return false;
1442   new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1443   add_object(new_bullet);
1444
1445   sound_manager->play("sounds/shoot.wav");
1446
1447   return true;
1448 }
1449
1450 bool
1451 Sector::add_smoke_cloud(const Vector& pos)
1452 {
1453   add_object(new SmokeCloud(pos));
1454   return true;
1455 }
1456
1457 void
1458 Sector::play_music(MusicType type)
1459 {
1460   currentmusic = type;
1461   switch(currentmusic) {
1462     case LEVEL_MUSIC:
1463       sound_manager->play_music(music);
1464       break;
1465     case HERRING_MUSIC:
1466       sound_manager->play_music("music/invincible.ogg");
1467       break;
1468     case HERRING_WARNING_MUSIC:
1469       sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1470       break;
1471     default:
1472       sound_manager->play_music("");
1473       break;
1474   }
1475 }
1476
1477 MusicType
1478 Sector::get_music_type()
1479 {
1480   return currentmusic;
1481 }
1482
1483 int
1484 Sector::get_total_badguys()
1485 {
1486   int total_badguys = 0;
1487   for(GameObjects::iterator i = gameobjects.begin();
1488       i != gameobjects.end(); ++i) {
1489     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1490     if (badguy && badguy->countMe)
1491       total_badguys++;
1492   }
1493
1494   return total_badguys;
1495 }
1496
1497 bool
1498 Sector::inside(const Rect& rect) const
1499 {
1500   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1501     TileMap* solids = *i;
1502     bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1503     bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1504
1505     if (horizontally && vertically)
1506       return true;
1507   }
1508   return false;
1509 }
1510
1511 float
1512 Sector::get_width() const
1513 {
1514   float width = 0;
1515   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1516       i != solid_tilemaps.end(); i++) {
1517     TileMap* solids = *i;
1518     if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1519       width = solids->get_width() * 32 + solids->get_x_offset();
1520     }
1521   }
1522
1523   return width;
1524 }
1525
1526 float
1527 Sector::get_height() const
1528 {
1529   float height = 0;
1530   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1531       i != solid_tilemaps.end(); i++) {
1532     TileMap* solids = *i;
1533     if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1534       height = solids->get_height() * 32 + solids->get_y_offset();
1535     }
1536   }
1537
1538   return height;
1539 }
1540
1541 void
1542 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1543 {
1544   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1545     TileMap* solids = *i;
1546     solids->change_all(old_tile_id, new_tile_id);
1547   }
1548 }
1549
1550
1551 void
1552 Sector::set_ambient_light(float red, float green, float blue)
1553 {
1554   ambient_light.red = red;
1555   ambient_light.green = green;
1556   ambient_light.blue = blue;
1557 }
1558
1559 float
1560 Sector::get_ambient_red()
1561 {
1562   return ambient_light.red;
1563 }
1564
1565 float
1566 Sector::get_ambient_green()
1567 {
1568   return ambient_light.green;
1569 }
1570
1571 float
1572 Sector::get_ambient_blue()
1573 {
1574   return ambient_light.blue;
1575 }
1576
1577 void
1578 Sector::set_gravity(float gravity)
1579 {
1580   log_warning << "Changing a Sector's gravitational constant might have unforseen side-effects" << std::endl;
1581
1582   this->gravity = gravity;
1583
1584   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); ++i) {
1585     GameObject* game_object = *i;
1586     if(!game_object) continue;
1587     if(!game_object->is_valid()) continue;
1588     UsesPhysic *physics_object = dynamic_cast<UsesPhysic*>(game_object);
1589     if (!physics_object) continue;
1590
1591     physics_object->physic.set_gravity(gravity);
1592   }
1593 }
1594