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