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