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