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