New sector attribute 'ambient-light'.
[supertux.git] / src / sector.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <memory>
22 #include <algorithm>
23 #include <stdexcept>
24 #include <iostream>
25 #include <fstream>
26 #include <sstream>
27 #include <stdexcept>
28 #include <float.h>
29 #include <math.h>
30
31 #include "sector.hpp"
32 #include "object/player.hpp"
33 #include "object/gameobjs.hpp"
34 #include "object/camera.hpp"
35 #include "object/background.hpp"
36 #include "object/gradient.hpp"
37 #include "object/particlesystem.hpp"
38 #include "object/particlesystem_interactive.hpp"
39 #include "object/tilemap.hpp"
40 #include "lisp/parser.hpp"
41 #include "lisp/lisp.hpp"
42 #include "lisp/writer.hpp"
43 #include "lisp/list_iterator.hpp"
44 #include "tile.hpp"
45 #include "audio/sound_manager.hpp"
46 #include "game_session.hpp"
47 #include "resources.hpp"
48 #include "statistics.hpp"
49 #include "object_factory.hpp"
50 #include "collision.hpp"
51 #include "spawn_point.hpp"
52 #include "math/rect.hpp"
53 #include "math/aatriangle.hpp"
54 #include "object/coin.hpp"
55 #include "object/block.hpp"
56 #include "object/invisible_block.hpp"
57 #include "object/bullet.hpp"
58 #include "object/text_object.hpp"
59 #include "badguy/jumpy.hpp"
60 #include "trigger/sequence_trigger.hpp"
61 #include "player_status.hpp"
62 #include "scripting/squirrel_util.hpp"
63 #include "script_interface.hpp"
64 #include "log.hpp"
65
66 Sector* Sector::_current = 0;
67
68 bool Sector::show_collrects = false;
69 bool Sector::draw_solids_only = false;
70
71 Sector::Sector(Level* parent)
72   : level(parent), currentmusic(LEVEL_MUSIC),
73   ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10), player(0), camera(0) 
74 {
75   add_object(new Player(player_status, "Tux"));
76   add_object(new DisplayEffect("Effect"));
77   add_object(new TextObject("Text"));
78
79   // create a new squirrel table for the sector
80   using namespace Scripting;
81
82   sq_collectgarbage(global_vm);
83
84   sq_newtable(global_vm);
85   sq_pushroottable(global_vm);
86   if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
87     throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
88
89   sq_resetobject(&sector_table);
90   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &sector_table)))
91     throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
92   sq_addref(global_vm, &sector_table);
93   sq_pop(global_vm, 1);
94 }
95
96 Sector::~Sector()
97 {
98   using namespace Scripting;
99
100   deactivate();
101
102   for(ScriptList::iterator i = scripts.begin();
103       i != scripts.end(); ++i) {
104     HSQOBJECT& object = *i;
105     sq_release(global_vm, &object);
106   }
107   sq_release(global_vm, &sector_table);
108   sq_collectgarbage(global_vm);
109
110   update_game_objects();
111   assert(gameobjects_new.size() == 0);
112
113   for(GameObjects::iterator i = gameobjects.begin();
114       i != gameobjects.end(); ++i) {
115     GameObject* object = *i;
116     before_object_remove(object);
117     object->unref();
118   }
119
120   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
121       ++i)
122     delete *i;
123 }
124
125 Level*
126 Sector::get_level()
127 {
128   return level;
129 }
130
131 GameObject*
132 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
133 {
134   if(name == "camera") {
135     Camera* camera = new Camera(this, "Camera");
136     camera->parse(reader);
137     return camera;
138   } else if(name == "particles-snow") {
139     SnowParticleSystem* partsys = new SnowParticleSystem();
140     partsys->parse(reader);
141     return partsys;
142   } else if(name == "particles-rain") {
143     RainParticleSystem* partsys = new RainParticleSystem();
144     partsys->parse(reader);
145     return partsys;
146   } else if(name == "particles-comets") {
147     CometParticleSystem* partsys = new CometParticleSystem();
148     partsys->parse(reader);
149     return partsys;
150   } else if(name == "particles-ghosts") {
151     GhostParticleSystem* partsys = new GhostParticleSystem();
152     partsys->parse(reader);
153     return partsys;
154   } else if(name == "particles-clouds") {
155     CloudParticleSystem* partsys = new CloudParticleSystem();
156     partsys->parse(reader);
157     return partsys;
158   } else if(name == "money") { // for compatibility with old maps
159     return new Jumpy(reader);
160   }
161
162   try {
163     return create_object(name, reader);
164   } catch(std::exception& e) {
165     log_warning << e.what() << "" << std::endl;
166   }
167
168   return 0;
169 }
170
171 void
172 Sector::parse(const lisp::Lisp& sector)
173 {
174   lisp::ListIterator iter(&sector);
175   while(iter.next()) {
176     const std::string& token = iter.item();
177     if(token == "name") {
178       iter.value()->get(name);
179     } else if(token == "gravity") {
180       iter.value()->get(gravity);
181     } else if(token == "music") {
182       iter.value()->get(music);
183     } else if(token == "spawnpoint") {
184       SpawnPoint* sp = new SpawnPoint(iter.lisp());
185       spawnpoints.push_back(sp);
186     } else if(token == "init-script") {
187       iter.value()->get(init_script);
188     } else if(token == "ambient-light") {
189       std::vector<float> vColor;
190       sector.get_vector( "ambient-light", vColor );
191       ambient_light = Color( vColor );
192     } else {
193       GameObject* object = parse_object(token, *(iter.lisp()));
194       if(object) {
195         add_object(object);
196       }
197     }
198   }
199
200   update_game_objects();
201
202   if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
203
204   fix_old_tiles();
205   if(!camera) {
206     log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
207     update_game_objects();
208     add_object(new Camera(this, "Camera"));
209   }
210
211   update_game_objects();
212 }
213
214 void
215 Sector::parse_old_format(const lisp::Lisp& reader)
216 {
217   name = "main";
218   reader.get("gravity", gravity);
219
220   std::string backgroundimage;
221   reader.get("background", backgroundimage);
222   float bgspeed = .5;
223   reader.get("bkgd_speed", bgspeed);
224   bgspeed /= 100;
225
226   Color bkgd_top, bkgd_bottom;
227   int r = 0, g = 0, b = 128;
228   reader.get("bkgd_red_top", r);
229   reader.get("bkgd_green_top",  g);
230   reader.get("bkgd_blue_top",  b);
231   bkgd_top.red = static_cast<float> (r) / 255.0f;
232   bkgd_top.green = static_cast<float> (g) / 255.0f;
233   bkgd_top.blue = static_cast<float> (b) / 255.0f;
234
235   reader.get("bkgd_red_bottom",  r);
236   reader.get("bkgd_green_bottom", g);
237   reader.get("bkgd_blue_bottom", b);
238   bkgd_bottom.red = static_cast<float> (r) / 255.0f;
239   bkgd_bottom.green = static_cast<float> (g) / 255.0f;
240   bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
241
242   if(backgroundimage != "") {
243     Background* background = new Background();
244     background->set_image(
245             std::string("images/background/") + backgroundimage, bgspeed);
246     add_object(background);
247   } else {
248     Gradient* gradient = new Gradient();
249     gradient->set_gradient(bkgd_top, bkgd_bottom);
250     add_object(gradient);
251   }
252
253   std::string particlesystem;
254   reader.get("particle_system", particlesystem);
255   if(particlesystem == "clouds")
256     add_object(new CloudParticleSystem());
257   else if(particlesystem == "snow")
258     add_object(new SnowParticleSystem());
259   else if(particlesystem == "rain")
260     add_object(new RainParticleSystem());
261
262   Vector startpos(100, 170);
263   reader.get("start_pos_x", startpos.x);
264   reader.get("start_pos_y", startpos.y);
265
266   SpawnPoint* spawn = new SpawnPoint;
267   spawn->pos = startpos;
268   spawn->name = "main";
269   spawnpoints.push_back(spawn);
270
271   music = "chipdisko.ogg";
272   reader.get("music", music);
273   music = "music/" + music;
274
275   int width = 30, height = 15;
276   reader.get("width", width);
277   reader.get("height", height);
278
279   std::vector<unsigned int> tiles;
280   if(reader.get_vector("interactive-tm", tiles)
281       || reader.get_vector("tilemap", tiles)) {
282     TileMap* tilemap = new TileMap();
283     tilemap->set(width, height, tiles, LAYER_TILES, true);
284     add_object(tilemap);
285   }
286
287   if(reader.get_vector("background-tm", tiles)) {
288     TileMap* tilemap = new TileMap();
289     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
290     add_object(tilemap);
291   }
292
293   if(reader.get_vector("foreground-tm", tiles)) {
294     TileMap* tilemap = new TileMap();
295     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
296     add_object(tilemap);
297   }
298
299   // read reset-points (now spawn-points)
300   const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
301   if(resetpoints) {
302     lisp::ListIterator iter(resetpoints);
303     while(iter.next()) {
304       if(iter.item() == "point") {
305         Vector sp_pos;
306         if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
307           {
308           SpawnPoint* sp = new SpawnPoint;
309           sp->name = "main";
310           sp->pos = sp_pos;
311           spawnpoints.push_back(sp);
312           }
313       } else {
314         log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
315       }
316     }
317   }
318
319   // read objects
320   const lisp::Lisp* objects = reader.get_lisp("objects");
321   if(objects) {
322     lisp::ListIterator iter(objects);
323     while(iter.next()) {
324       GameObject* object = parse_object(iter.item(), *(iter.lisp()));
325       if(object) {
326         add_object(object);
327       } else {
328         log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
329       }
330     }
331   }
332
333   // add a camera
334   Camera* camera = new Camera(this, "Camera");
335   add_object(camera);
336
337   update_game_objects();
338
339   if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
340
341   fix_old_tiles();
342   update_game_objects();
343 }
344
345 void
346 Sector::fix_old_tiles()
347 {
348   // hack for now...
349   for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
350     TileMap* solids = *i;
351     for(size_t x=0; x < solids->get_width(); ++x) {
352       for(size_t y=0; y < solids->get_height(); ++y) {
353         const Tile* tile = solids->get_tile(x, y);
354         Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
355
356         if(tile->getID() == 112) {
357           add_object(new InvisibleBlock(pos));
358           solids->change(x, y, 0);
359         } else if(tile->getAttributes() & Tile::COIN) {
360           add_object(new Coin(pos));
361           solids->change(x, y, 0);
362         } else if(tile->getAttributes() & Tile::FULLBOX) {
363           add_object(new BonusBlock(pos, tile->getData()));
364           solids->change(x, y, 0);
365         } else if(tile->getAttributes() & Tile::BRICK) {
366           add_object(new Brick(pos, tile->getData()));
367           solids->change(x, y, 0);
368         } else if(tile->getAttributes() & Tile::GOAL) {
369           std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
370           add_object(new SequenceTrigger(pos, sequence));
371           solids->change(x, y, 0);
372         }
373       }
374     }
375   }
376 }
377
378 void
379 Sector::write(lisp::Writer& writer)
380 {
381   writer.write_string("name", name);
382   writer.write_float("gravity", gravity);
383   writer.write_string("music", music);
384
385   // write spawnpoints
386   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
387       ++i) {
388     SpawnPoint* spawn = *i;
389     writer.start_list("spawn-points");
390     writer.write_string("name", spawn->name);
391     writer.write_float("x", spawn->pos.x);
392     writer.write_float("y", spawn->pos.y);
393     writer.end_list("spawn-points");
394   }
395
396   // write objects
397   for(GameObjects::iterator i = gameobjects.begin();
398       i != gameobjects.end(); ++i) {
399     Serializable* serializable = dynamic_cast<Serializable*> (*i);
400     if(serializable)
401       serializable->write(writer);
402   }
403 }
404
405 HSQUIRRELVM
406 Sector::run_script(std::istream& in, const std::string& sourcename)
407 {
408   using namespace Scripting;
409
410   // garbage collect thread list
411   for(ScriptList::iterator i = scripts.begin();
412       i != scripts.end(); ) {
413     HSQOBJECT& object = *i;
414     HSQUIRRELVM vm = object_to_vm(object);
415
416     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
417       sq_release(global_vm, &object);
418       i = scripts.erase(i);
419       continue;
420     }
421
422     ++i;
423   }
424
425   HSQOBJECT object = create_thread(global_vm);
426   scripts.push_back(object);
427
428   HSQUIRRELVM vm = object_to_vm(object);
429
430   // set sector_table as roottable for the thread
431   sq_pushobject(vm, sector_table);
432   sq_setroottable(vm);
433
434   compile_and_run(vm, in, sourcename);
435
436   return vm;
437 }
438
439 void
440 Sector::add_object(GameObject* object)
441 {
442   // make sure the object isn't already in the list
443 #ifdef DEBUG
444   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
445       ++i) {
446     if(*i == object) {
447       assert("object already added to sector" == 0);
448     }
449   }
450   for(GameObjects::iterator i = gameobjects_new.begin();
451       i != gameobjects_new.end(); ++i) {
452     if(*i == object) {
453       assert("object already added to sector" == 0);
454     }
455   }
456 #endif
457
458   object->ref();
459   gameobjects_new.push_back(object);
460 }
461
462 void
463 Sector::activate(const std::string& spawnpoint)
464 {
465   SpawnPoint* sp = 0;
466   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
467       ++i) {
468     if((*i)->name == spawnpoint) {
469       sp = *i;
470       break;
471     }
472   }
473   if(!sp) {
474     log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
475     if(spawnpoint != "main") {
476       activate("main");
477     } else {
478       activate(Vector(0, 0));
479     }
480   } else {
481     activate(sp->pos);
482   }
483 }
484
485 void
486 Sector::activate(const Vector& player_pos)
487 {
488   if(_current != this) {
489     if(_current != NULL)
490       _current->deactivate();
491     _current = this;
492
493     // register sectortable as sector in scripting
494     HSQUIRRELVM vm = Scripting::global_vm;
495     sq_pushroottable(vm);
496     sq_pushstring(vm, "sector", -1);
497     sq_pushobject(vm, sector_table);
498     if(SQ_FAILED(sq_createslot(vm, -3)))
499       throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
500     sq_pop(vm, 1);
501
502     for(GameObjects::iterator i = gameobjects.begin();
503         i != gameobjects.end(); ++i) {
504       GameObject* object = *i;
505
506       try_expose(object);
507     }
508   }
509
510   player->move(player_pos);
511   camera->reset(player->get_pos());
512   update_game_objects();
513
514   // Run init script
515   if(init_script != "") {
516     std::istringstream in(init_script);
517     run_script(in, std::string("Sector(") + name + ") - init");
518   }
519 }
520
521 void
522 Sector::deactivate()
523 {
524   if(_current != this)
525     return;
526
527   // remove sector entry from global vm
528   HSQUIRRELVM vm = Scripting::global_vm;
529   sq_pushroottable(vm);
530   sq_pushstring(vm, "sector", -1);
531   if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
532     throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
533   sq_pop(vm, 1);
534
535   for(GameObjects::iterator i = gameobjects.begin();
536       i != gameobjects.end(); ++i) {
537     GameObject* object = *i;
538
539     try_unexpose(object);
540   }
541
542   _current = NULL;
543 }
544
545 Rect
546 Sector::get_active_region()
547 {
548   return Rect(
549     camera->get_translation() - Vector(1600, 1200),
550     camera->get_translation() + Vector(1600, 1200));
551 }
552
553 void
554 Sector::update(float elapsed_time)
555 {
556   player->check_bounds(camera);
557
558   /* update objects */
559   for(GameObjects::iterator i = gameobjects.begin();
560           i != gameobjects.end(); ++i) {
561     GameObject* object = *i;
562     if(!object->is_valid())
563       continue;
564
565     object->update(elapsed_time);
566   }
567
568   /* Handle all possible collisions. */
569   handle_collisions();
570   update_game_objects();
571 }
572
573 void
574 Sector::update_game_objects()
575 {
576   /** cleanup marked objects */
577   for(std::vector<Bullet*>::iterator i = bullets.begin();
578       i != bullets.end(); /* nothing */) {
579     Bullet* bullet = *i;
580     if(bullet->is_valid()) {
581       ++i;
582       continue;
583     }
584
585     i = bullets.erase(i);
586   }
587   for(MovingObjects::iterator i = moving_objects.begin();
588       i != moving_objects.end(); /* nothing */) {
589     MovingObject* moving_object = *i;
590     if(moving_object->is_valid()) {
591       ++i;
592       continue;
593     }
594
595     i = moving_objects.erase(i);
596   }
597   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
598       i != gameobjects.end(); /* nothing */) {
599     GameObject* object = *i;
600
601     if(object->is_valid()) {
602       ++i;
603       continue;
604     }
605
606     before_object_remove(object);
607
608     object->unref();
609     i = gameobjects.erase(i);
610   }
611
612   /* add newly created objects */
613   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
614       i != gameobjects_new.end(); ++i)
615   {
616     GameObject* object = *i;
617
618     before_object_add(object);
619
620     gameobjects.push_back(object);
621   }
622   gameobjects_new.clear();
623 }
624
625 bool
626 Sector::before_object_add(GameObject* object)
627 {
628   Bullet* bullet = dynamic_cast<Bullet*> (object);
629   if(bullet)
630     bullets.push_back(bullet);
631
632   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
633   if(movingobject) {
634     moving_objects.push_back(movingobject);
635   }
636
637   TileMap* tilemap = dynamic_cast<TileMap*> (object);
638   if(tilemap && tilemap->is_solid()) solid_tilemaps.push_back(tilemap);
639
640   Camera* camera = dynamic_cast<Camera*> (object);
641   if(camera) {
642     if(this->camera != 0) {
643       log_warning << "Multiple cameras added. Ignoring" << std::endl;
644       return false;
645     }
646     this->camera = camera;
647   }
648
649   Player* player = dynamic_cast<Player*> (object);
650   if(player) {
651     if(this->player != 0) {
652       log_warning << "Multiple players added. Ignoring" << std::endl;
653       return false;
654     }
655     this->player = player;
656   }
657
658   if(_current == this) {
659     try_expose(object);
660   }
661
662   return true;
663 }
664
665 void
666 Sector::try_expose(GameObject* object)
667 {
668   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
669   if(interface != NULL) {
670     HSQUIRRELVM vm = Scripting::global_vm;
671     sq_pushobject(vm, sector_table);
672     interface->expose(vm, -1);
673     sq_pop(vm, 1);
674   }
675 }
676
677 void
678 Sector::before_object_remove(GameObject* object)
679 {
680   if(_current == this)
681     try_unexpose(object);
682 }
683
684 void
685 Sector::try_unexpose(GameObject* object)
686 {
687   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
688   if(interface != NULL) {
689     HSQUIRRELVM vm = Scripting::global_vm;
690     SQInteger oldtop = sq_gettop(vm);
691     sq_pushobject(vm, sector_table);
692     try {
693       interface->unexpose(vm, -1);
694     } catch(std::exception& e) {
695       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
696     }
697     sq_settop(vm, oldtop);
698   }
699 }
700
701 void
702 Sector::draw(DrawingContext& context)
703 {
704   context.set_ambient_color( ambient_light );
705   context.push_transform();
706   context.set_translation(camera->get_translation());
707
708   for(GameObjects::iterator i = gameobjects.begin();
709       i != gameobjects.end(); ++i) {
710     GameObject* object = *i;
711     if(!object->is_valid())
712       continue;
713
714     if (draw_solids_only)
715     {
716       TileMap* tm = dynamic_cast<TileMap*>(object);
717       if (tm && !tm->is_solid())
718         continue;
719     }
720
721     object->draw(context);
722   }
723
724   if(show_collrects) {
725     Color col(0.2, 0.2, 0.2, 0.7);
726     for(MovingObjects::iterator i = moving_objects.begin();
727             i != moving_objects.end(); ++i) {
728       MovingObject* object = *i;
729       const Rect& rect = object->get_bbox();
730
731       context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
732     }
733   }
734
735   context.pop_transform();
736 }
737
738 /*-------------------------------------------------------------------------
739  * Collision Detection
740  *-------------------------------------------------------------------------*/
741
742 static const float SHIFT_DELTA = 7.0f;
743
744 /** r1 is supposed to be moving, r2 a solid object */
745 void check_collisions(collision::Constraints* constraints,
746                       const Vector& movement, const Rect& r1, const Rect& r2,
747                       GameObject* object = NULL, MovingObject* other = NULL)
748 {
749   if(!collision::intersects(r1, r2))
750     return;
751
752   // calculate intersection
753   float itop = r1.get_bottom() - r2.get_top();
754   float ibottom = r2.get_bottom() - r1.get_top();
755   float ileft = r1.get_right() - r2.get_left();
756   float iright = r2.get_right() - r1.get_left();
757
758   if(fabsf(movement.y) > fabsf(movement.x)) {
759     if(ileft < SHIFT_DELTA) {
760       constraints->right = std::min(constraints->right, r2.get_left());
761       return;
762     } else if(iright < SHIFT_DELTA) {
763       constraints->left = std::max(constraints->left, r2.get_right());
764       return;
765     }
766   } else {
767     // shiftout bottom/top
768     if(itop < SHIFT_DELTA) {
769       constraints->bottom = std::min(constraints->bottom, r2.get_top());
770       return;
771     } else if(ibottom < SHIFT_DELTA) {
772       constraints->top = std::max(constraints->top, r2.get_bottom());
773       return;
774     }
775   }
776
777   if(other != NULL) {
778     CollisionHit dummy;
779     HitResponse response = other->collision(*object, dummy);
780     if(response == PASSTHROUGH)
781       return;
782     if(other->get_movement() != Vector(0, 0)) {
783       // TODO what todo when we collide with 2 moving objects?!?
784       constraints->ground_movement = other->get_movement();
785     }
786   }
787
788   float vert_penetration = std::min(itop, ibottom);
789   float horiz_penetration = std::min(ileft, iright);
790   if(vert_penetration < horiz_penetration) {
791     if(itop < ibottom) {
792       constraints->bottom = std::min(constraints->bottom, r2.get_top());
793       constraints->hit.bottom = true;
794     } else {
795       constraints->top = std::max(constraints->top, r2.get_bottom());
796       constraints->hit.top = true;
797     }
798   } else {
799     if(ileft < iright) {
800       constraints->right = std::min(constraints->right, r2.get_left());
801       constraints->hit.right = true;
802     } else {
803       constraints->left = std::max(constraints->left, r2.get_right());
804       constraints->hit.left = true;
805     }
806   }
807 }
808
809 static const float DELTA = .001;
810
811 void
812 Sector::collision_tilemap(collision::Constraints* constraints,
813                           const Vector& movement, const Rect& dest) const
814 {
815   // calculate rectangle where the object will move
816   float x1 = dest.get_left();
817   float x2 = dest.get_right();
818   float y1 = dest.get_top();
819   float y2 = dest.get_bottom();
820
821   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
822     TileMap* solids = *i;
823
824     // test with all tiles in this rectangle
825     int starttilex = int(x1 - solids->get_x_offset()) / 32;
826     int starttiley = int(y1 - solids->get_y_offset()) / 32;
827     int max_x = int(x2 - solids->get_x_offset());
828     int max_y = int(y2+1 - solids->get_y_offset());
829
830     for(int x = starttilex; x*32 < max_x; ++x) {
831       for(int y = starttiley; y*32 < max_y; ++y) {
832         const Tile* tile = solids->get_tile(x, y);
833         if(!tile)
834           continue;
835         // skip non-solid tiles
836         if((tile->getAttributes() & Tile::SOLID) == 0)
837           continue;
838         // only handle unisolid when the player is falling down and when he was
839         // above the tile before
840         if(tile->getAttributes() & Tile::UNISOLID) {
841           if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
842             continue;
843         }
844
845         if(tile->getAttributes() & Tile::SLOPE) { // slope tile
846           AATriangle triangle;
847           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
848           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
849           triangle = AATriangle(p1, p2, tile->getData());
850
851           collision::rectangle_aatriangle(constraints, dest, triangle);
852         } else { // normal rectangular tile
853           Rect rect(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset(), (x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
854           check_collisions(constraints, movement, dest, rect);
855         }
856       }
857     }
858   }
859 }
860
861 uint32_t
862 Sector::collision_tile_attributes(const Rect& dest) const
863 {
864   float x1 = dest.p1.x;
865   float y1 = dest.p1.y;
866   float x2 = dest.p2.x;
867   float y2 = dest.p2.y;
868
869   uint32_t result = 0;
870   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
871     TileMap* solids = *i;
872
873     // test with all tiles in this rectangle
874     int starttilex = int(x1 - solids->get_x_offset()) / 32;
875     int starttiley = int(y1 - solids->get_y_offset()) / 32;
876     int max_x = int(x2 - solids->get_x_offset());
877     int max_y = int(y2+1 - solids->get_y_offset());
878
879     for(int x = starttilex; x*32 < max_x; ++x) {
880       for(int y = starttiley; y*32 < max_y; ++y) {
881         const Tile* tile = solids->get_tile(x, y);
882         if(!tile)
883           continue;
884         result |= tile->getAttributes();
885       }
886     }
887   }
888
889   return result;
890 }
891
892 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
893 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
894                            Vector& normal)
895 {
896   float itop = r1.get_bottom() - r2.get_top();
897   float ibottom = r2.get_bottom() - r1.get_top();
898   float ileft = r1.get_right() - r2.get_left();
899   float iright = r2.get_right() - r1.get_left();
900
901   float vert_penetration = std::min(itop, ibottom);
902   float horiz_penetration = std::min(ileft, iright);
903   if(vert_penetration < horiz_penetration) {
904     if(itop < ibottom) {
905       hit.bottom = true;
906       normal.y = vert_penetration;
907     } else {
908       hit.top = true;
909       normal.y = -vert_penetration;
910     }
911   } else {
912     if(ileft < iright) {
913       hit.right = true;
914       normal.x = horiz_penetration;
915     } else {
916       hit.left = true;
917       normal.x = -horiz_penetration;
918     }
919   }
920 }
921
922 void
923 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
924 {
925   using namespace collision;
926
927   const Rect& r1 = object1->dest;
928   const Rect& r2 = object2->dest;
929
930   CollisionHit hit;
931   if(intersects(object1->dest, object2->dest)) {
932     Vector normal;
933     get_hit_normal(r1, r2, hit, normal);
934
935     HitResponse response1 = object1->collision(*object2, hit);
936     std::swap(hit.left, hit.right);
937     std::swap(hit.top, hit.bottom);
938     HitResponse response2 = object2->collision(*object1, hit);
939     assert( response1 != SOLID && response1 != PASSTHROUGH );
940     assert( response2 != SOLID && response2 != PASSTHROUGH );
941     if(response1 == CONTINUE && response2 == CONTINUE) {
942       normal *= (0.5 + DELTA);
943       object1->dest.move(-normal);
944       object2->dest.move(normal);
945     } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
946       normal *= (1 + DELTA);
947       object1->dest.move(-normal);
948     } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
949       normal *= (1 + DELTA);
950       object2->dest.move(normal);
951     }
952   }
953 }
954
955 void
956 Sector::collision_static(collision::Constraints* constraints,
957                          const Vector& movement, const Rect& dest,
958                          GameObject& object)
959 {
960   collision_tilemap(constraints, movement, dest);
961
962   // collision with other (static) objects
963   for(MovingObjects::iterator i = moving_objects.begin();
964       i != moving_objects.end(); ++i) {
965     MovingObject* moving_object = *i;
966     if(moving_object->get_group() != COLGROUP_STATIC
967         || !moving_object->is_valid())
968       continue;
969
970     check_collisions(constraints, movement, dest, moving_object->dest,
971         &object, moving_object);
972   }
973 }
974
975 void
976 Sector::collision_static_constrains(MovingObject& object)
977 {
978   using namespace collision;
979
980   Constraints constraints;
981   Vector movement = object.get_movement();
982   Rect& dest = object.dest;
983   float owidth = object.get_bbox().get_width();
984   float oheight = object.get_bbox().get_height();
985
986   for(int i = 0; i < 2; ++i) {
987     collision_static(&constraints, Vector(0, movement.y), dest, object);
988     if(!constraints.has_constraints())
989       break;
990
991     // apply calculated horizontal constraints
992     if(constraints.bottom < INFINITY) {
993       float height = constraints.bottom - constraints.top;
994       if(height < oheight) {
995         // we're crushed, but ignore this for now, we'll get this again
996         // later if we're really crushed or things will solve itself when
997         // looking at the vertical constraints
998       }
999       dest.p2.y = constraints.bottom - DELTA;
1000       dest.p1.y = dest.p2.y - oheight;
1001     } else if(constraints.top > -INFINITY) {
1002       dest.p1.y = constraints.top + DELTA;
1003       dest.p2.y = dest.p1.y + oheight;
1004     }
1005   }
1006   if(constraints.has_constraints()) {
1007     if(constraints.hit.bottom) {
1008       dest.move(constraints.ground_movement);
1009     }
1010     if(constraints.hit.top || constraints.hit.bottom) {
1011       constraints.hit.left = false;
1012       constraints.hit.right = false;
1013       object.collision_solid(constraints.hit);
1014     }
1015   }
1016
1017   constraints = Constraints();
1018   for(int i = 0; i < 2; ++i) {
1019     collision_static(&constraints, movement, dest, object);
1020     if(!constraints.has_constraints())
1021       break;
1022
1023     // apply calculated vertical constraints
1024     if(constraints.right < INFINITY) {
1025       float width = constraints.right - constraints.left;
1026       if(width + SHIFT_DELTA < owidth) {
1027         printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1028             constraints.left, constraints.right);
1029         CollisionHit h;
1030         h.left = true;
1031         h.right = true;
1032         h.crush = true;
1033         object.collision_solid(h);
1034       } else {
1035         dest.p2.x = constraints.right - DELTA;
1036         dest.p1.x = dest.p2.x - owidth;
1037       }
1038     } else if(constraints.left > -INFINITY) {
1039       dest.p1.x = constraints.left + DELTA;
1040       dest.p2.x = dest.p1.x + owidth;
1041     }
1042   }
1043
1044   if(constraints.has_constraints()) {
1045     if( constraints.hit.left || constraints.hit.right
1046         || constraints.hit.top || constraints.hit.bottom
1047         || constraints.hit.crush )
1048       object.collision_solid(constraints.hit);
1049   }
1050
1051   // an extra pass to make sure we're not crushed horizontally
1052   constraints = Constraints();
1053   collision_static(&constraints, movement, dest, object);
1054   if(constraints.bottom < INFINITY) {
1055     float height = constraints.bottom - constraints.top;
1056     if(height + SHIFT_DELTA < oheight) {
1057       printf("Object %p crushed vertically...\n", &object);
1058       CollisionHit h;
1059       h.top = true;
1060       h.bottom = true;
1061       h.crush = true;
1062       object.collision_solid(h);
1063     }
1064   }
1065 }
1066
1067 void
1068 Sector::handle_collisions()
1069 {
1070   using namespace collision;
1071
1072   // calculate destination positions of the objects
1073   for(MovingObjects::iterator i = moving_objects.begin();
1074       i != moving_objects.end(); ++i) {
1075     MovingObject* moving_object = *i;
1076
1077     moving_object->dest = moving_object->get_bbox();
1078     moving_object->dest.move(moving_object->get_movement());
1079   }
1080
1081   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1082   for(MovingObjects::iterator i = moving_objects.begin();
1083       i != moving_objects.end(); ++i) {
1084     MovingObject* moving_object = *i;
1085     if((moving_object->get_group() != COLGROUP_MOVING
1086           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1087         || !moving_object->is_valid())
1088       continue;
1089
1090     collision_static_constrains(*moving_object);
1091   }
1092
1093
1094   // part2: COLGROUP_MOVING vs tile attributes
1095   for(MovingObjects::iterator i = moving_objects.begin();
1096       i != moving_objects.end(); ++i) {
1097     MovingObject* moving_object = *i;
1098     if((moving_object->get_group() != COLGROUP_MOVING
1099           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1100         || !moving_object->is_valid())
1101       continue;
1102
1103     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1104     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1105       moving_object->collision_tile(tile_attributes);
1106     }
1107   }
1108
1109   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1110   for(MovingObjects::iterator i = moving_objects.begin();
1111       i != moving_objects.end(); ++i) {
1112     MovingObject* moving_object = *i;
1113     if(moving_object->get_group() != COLGROUP_MOVING
1114         || !moving_object->is_valid())
1115       continue;
1116
1117     for(MovingObjects::iterator i2 = moving_objects.begin();
1118         i2 != moving_objects.end(); ++i2) {
1119       MovingObject* moving_object_2 = *i2;
1120       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1121          || !moving_object_2->is_valid())
1122         continue;
1123
1124       if(intersects(moving_object->dest, moving_object_2->dest)) {
1125         Vector normal;
1126         CollisionHit hit;
1127         get_hit_normal(moving_object->dest, moving_object_2->dest,
1128                        hit, normal);
1129         moving_object->collision(*moving_object_2, hit);
1130         moving_object_2->collision(*moving_object, hit);
1131       }
1132     }
1133   }
1134
1135   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1136   for(MovingObjects::iterator i = moving_objects.begin();
1137       i != moving_objects.end(); ++i) {
1138     MovingObject* moving_object = *i;
1139
1140     if(moving_object->get_group() != COLGROUP_MOVING
1141         || !moving_object->is_valid())
1142       continue;
1143
1144     for(MovingObjects::iterator i2 = i+1;
1145         i2 != moving_objects.end(); ++i2) {
1146       MovingObject* moving_object_2 = *i2;
1147       if(moving_object_2->get_group() != COLGROUP_MOVING
1148          || !moving_object_2->is_valid())
1149         continue;
1150
1151       collision_object(moving_object, moving_object_2);
1152     }
1153   }
1154
1155   // apply object movement
1156   for(MovingObjects::iterator i = moving_objects.begin();
1157       i != moving_objects.end(); ++i) {
1158     MovingObject* moving_object = *i;
1159
1160     moving_object->bbox = moving_object->dest;
1161     moving_object->movement = Vector(0, 0);
1162   }
1163 }
1164
1165 bool
1166 Sector::is_free_space(const Rect& rect) const
1167 {
1168   using namespace collision;
1169
1170   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1171     TileMap* solids = *i;
1172
1173     // test with all tiles in this rectangle
1174     int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1175     int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1176     int max_x = int(rect.p2.x - solids->get_x_offset());
1177     int max_y = int(rect.p2.y - solids->get_y_offset());
1178
1179     for(int x = starttilex; x*32 <= max_x; ++x) {
1180       for(int y = starttiley; y*32 <= max_y; ++y) {
1181         const Tile* tile = solids->get_tile(x, y);
1182         if(!tile) continue;
1183         if(tile->getAttributes() & Tile::SLOPE) {
1184           AATriangle triangle;
1185           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1186           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1187           triangle = AATriangle(p1, p2, tile->getData());
1188           Constraints constraints;
1189           return collision::rectangle_aatriangle(&constraints, rect, triangle);
1190         }
1191         if(tile->getAttributes() & Tile::SOLID) return false;
1192       }
1193     }
1194   }
1195
1196   for(MovingObjects::const_iterator i = moving_objects.begin();
1197       i != moving_objects.end(); ++i) {
1198     const MovingObject* moving_object = *i;
1199     if(moving_object->get_group() != COLGROUP_STATIC
1200         || !moving_object->is_valid())
1201       continue;
1202
1203     if(intersects(rect, moving_object->get_bbox()))
1204       return false;
1205   }
1206
1207   return true;
1208 }
1209
1210 bool
1211 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1212 {
1213   // TODO remove this function and move these checks elsewhere...
1214
1215   Bullet* new_bullet = 0;
1216   if((int)bullets.size() >= player_status->max_fire_bullets)
1217     return false;
1218   new_bullet = new Bullet(pos, xm, dir);
1219   add_object(new_bullet);
1220
1221   sound_manager->play("sounds/shoot.wav");
1222
1223   return true;
1224 }
1225
1226 bool
1227 Sector::add_smoke_cloud(const Vector& pos)
1228 {
1229   add_object(new SmokeCloud(pos));
1230   return true;
1231 }
1232
1233 void
1234 Sector::play_music(MusicType type)
1235 {
1236   currentmusic = type;
1237   switch(currentmusic) {
1238     case LEVEL_MUSIC:
1239       sound_manager->play_music(music);
1240       break;
1241     case HERRING_MUSIC:
1242       sound_manager->play_music("music/salcon.ogg");
1243       break;
1244     case HERRING_WARNING_MUSIC:
1245       sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1246       break;
1247     default:
1248       sound_manager->play_music("");
1249       break;
1250   }
1251 }
1252
1253 MusicType
1254 Sector::get_music_type()
1255 {
1256   return currentmusic;
1257 }
1258
1259 int
1260 Sector::get_total_badguys()
1261 {
1262   int total_badguys = 0;
1263   for(GameObjects::iterator i = gameobjects.begin();
1264       i != gameobjects.end(); ++i) {
1265     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1266     if (badguy && badguy->countMe)
1267       total_badguys++;
1268   }
1269
1270   return total_badguys;
1271 }
1272
1273 bool
1274 Sector::inside(const Rect& rect) const
1275 {
1276   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1277     TileMap* solids = *i;
1278     bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1279     bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1280     if (horizontally && vertically) return true;
1281   }
1282   return false;
1283 }
1284
1285 float
1286 Sector::get_width() const
1287 {
1288   float width = 0;
1289   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1290     TileMap* solids = *i;
1291     if ((solids->get_width() * 32 + solids->get_x_offset()) > width) width = (solids->get_width() * 32 + solids->get_x_offset());
1292   }
1293   return width;
1294 }
1295
1296 float
1297 Sector::get_height() const
1298 {
1299   float height = 0;
1300   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1301     TileMap* solids = *i;
1302     if ((solids->get_height() * 32 + solids->get_y_offset()) > height) height = (solids->get_height() * 32 + solids->get_y_offset());
1303   }
1304   return height;
1305 }
1306
1307 void
1308 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1309 {
1310   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1311     TileMap* solids = *i;
1312     solids->change_all(old_tile_id, new_tile_id);
1313   }
1314 }