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