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