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