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