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