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