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