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