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