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