Magic Blocks only turn solid when nothing's blocking them. /
[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 "object/portable.hpp"
60 #include "badguy/jumpy.hpp"
61 #include "trigger/sequence_trigger.hpp"
62 #include "player_status.hpp"
63 #include "scripting/squirrel_util.hpp"
64 #include "script_interface.hpp"
65 #include "log.hpp"
66
67 Sector* Sector::_current = 0;
68
69 bool Sector::show_collrects = false;
70 bool Sector::draw_solids_only = false;
71
72 Sector::Sector(Level* parent)
73   : level(parent), currentmusic(LEVEL_MUSIC),
74   ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10), player(0), camera(0) 
75 {
76   add_object(new Player(player_status, "Tux"));
77   add_object(new DisplayEffect("Effect"));
78   add_object(new TextObject("Text"));
79
80   // create a new squirrel table for the sector
81   using namespace Scripting;
82
83   sq_collectgarbage(global_vm);
84
85   sq_newtable(global_vm);
86   sq_pushroottable(global_vm);
87   if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
88     throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
89
90   sq_resetobject(&sector_table);
91   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &sector_table)))
92     throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
93   sq_addref(global_vm, &sector_table);
94   sq_pop(global_vm, 1);
95 }
96
97 Sector::~Sector()
98 {
99   using namespace Scripting;
100
101   deactivate();
102
103   for(ScriptList::iterator i = scripts.begin();
104       i != scripts.end(); ++i) {
105     HSQOBJECT& object = *i;
106     sq_release(global_vm, &object);
107   }
108   sq_release(global_vm, &sector_table);
109   sq_collectgarbage(global_vm);
110
111   update_game_objects();
112   assert(gameobjects_new.size() == 0);
113
114   for(GameObjects::iterator i = gameobjects.begin();
115       i != gameobjects.end(); ++i) {
116     GameObject* object = *i;
117     before_object_remove(object);
118     object->unref();
119   }
120
121   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
122       ++i)
123     delete *i;
124 }
125
126 Level*
127 Sector::get_level()
128 {
129   return level;
130 }
131
132 GameObject*
133 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
134 {
135   if(name == "camera") {
136     Camera* camera = new Camera(this, "Camera");
137     camera->parse(reader);
138     return camera;
139   } else if(name == "particles-snow") {
140     SnowParticleSystem* partsys = new SnowParticleSystem();
141     partsys->parse(reader);
142     return partsys;
143   } else if(name == "particles-rain") {
144     RainParticleSystem* partsys = new RainParticleSystem();
145     partsys->parse(reader);
146     return partsys;
147   } else if(name == "particles-comets") {
148     CometParticleSystem* partsys = new CometParticleSystem();
149     partsys->parse(reader);
150     return partsys;
151   } else if(name == "particles-ghosts") {
152     GhostParticleSystem* partsys = new GhostParticleSystem();
153     partsys->parse(reader);
154     return partsys;
155   } else if(name == "particles-clouds") {
156     CloudParticleSystem* partsys = new CloudParticleSystem();
157     partsys->parse(reader);
158     return partsys;
159   } else if(name == "money") { // for compatibility with old maps
160     return new Jumpy(reader);
161   }
162
163   try {
164     return create_object(name, reader);
165   } catch(std::exception& e) {
166     log_warning << e.what() << "" << std::endl;
167   }
168
169   return 0;
170 }
171
172 void
173 Sector::parse(const lisp::Lisp& sector)
174 {
175   lisp::ListIterator iter(&sector);
176   while(iter.next()) {
177     const std::string& token = iter.item();
178     if(token == "name") {
179       iter.value()->get(name);
180     } else if(token == "gravity") {
181       iter.value()->get(gravity);
182     } else if(token == "music") {
183       iter.value()->get(music);
184     } else if(token == "spawnpoint") {
185       SpawnPoint* sp = new SpawnPoint(iter.lisp());
186       spawnpoints.push_back(sp);
187     } else if(token == "init-script") {
188       iter.value()->get(init_script);
189     } else if(token == "ambient-light") {
190       std::vector<float> vColor;
191       sector.get_vector( "ambient-light", vColor );
192       ambient_light = Color( vColor );
193     } else {
194       GameObject* object = parse_object(token, *(iter.lisp()));
195       if(object) {
196         add_object(object);
197       }
198     }
199   }
200
201   update_game_objects();
202
203   if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
204
205   fix_old_tiles();
206   if(!camera) {
207     log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
208     update_game_objects();
209     add_object(new Camera(this, "Camera"));
210   }
211
212   update_game_objects();
213 }
214
215 void
216 Sector::parse_old_format(const lisp::Lisp& reader)
217 {
218   name = "main";
219   reader.get("gravity", gravity);
220
221   std::string backgroundimage;
222   reader.get("background", backgroundimage);
223   float bgspeed = .5;
224   reader.get("bkgd_speed", bgspeed);
225   bgspeed /= 100;
226
227   Color bkgd_top, bkgd_bottom;
228   int r = 0, g = 0, b = 128;
229   reader.get("bkgd_red_top", r);
230   reader.get("bkgd_green_top",  g);
231   reader.get("bkgd_blue_top",  b);
232   bkgd_top.red = static_cast<float> (r) / 255.0f;
233   bkgd_top.green = static_cast<float> (g) / 255.0f;
234   bkgd_top.blue = static_cast<float> (b) / 255.0f;
235
236   reader.get("bkgd_red_bottom",  r);
237   reader.get("bkgd_green_bottom", g);
238   reader.get("bkgd_blue_bottom", b);
239   bkgd_bottom.red = static_cast<float> (r) / 255.0f;
240   bkgd_bottom.green = static_cast<float> (g) / 255.0f;
241   bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
242
243   if(backgroundimage != "") {
244     Background* background = new Background();
245     background->set_image(
246             std::string("images/background/") + backgroundimage, bgspeed);
247     add_object(background);
248   } else {
249     Gradient* gradient = new Gradient();
250     gradient->set_gradient(bkgd_top, bkgd_bottom);
251     add_object(gradient);
252   }
253
254   std::string particlesystem;
255   reader.get("particle_system", particlesystem);
256   if(particlesystem == "clouds")
257     add_object(new CloudParticleSystem());
258   else if(particlesystem == "snow")
259     add_object(new SnowParticleSystem());
260   else if(particlesystem == "rain")
261     add_object(new RainParticleSystem());
262
263   Vector startpos(100, 170);
264   reader.get("start_pos_x", startpos.x);
265   reader.get("start_pos_y", startpos.y);
266
267   SpawnPoint* spawn = new SpawnPoint;
268   spawn->pos = startpos;
269   spawn->name = "main";
270   spawnpoints.push_back(spawn);
271
272   music = "chipdisko.ogg";
273   reader.get("music", music);
274   music = "music/" + music;
275
276   int width = 30, height = 15;
277   reader.get("width", width);
278   reader.get("height", height);
279
280   std::vector<unsigned int> tiles;
281   if(reader.get_vector("interactive-tm", tiles)
282       || reader.get_vector("tilemap", tiles)) {
283     TileMap* tilemap = new TileMap();
284     tilemap->set(width, height, tiles, LAYER_TILES, true);
285     add_object(tilemap);
286   }
287
288   if(reader.get_vector("background-tm", tiles)) {
289     TileMap* tilemap = new TileMap();
290     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
291     add_object(tilemap);
292   }
293
294   if(reader.get_vector("foreground-tm", tiles)) {
295     TileMap* tilemap = new TileMap();
296     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
297     add_object(tilemap);
298   }
299
300   // read reset-points (now spawn-points)
301   const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
302   if(resetpoints) {
303     lisp::ListIterator iter(resetpoints);
304     while(iter.next()) {
305       if(iter.item() == "point") {
306         Vector sp_pos;
307         if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
308           {
309           SpawnPoint* sp = new SpawnPoint;
310           sp->name = "main";
311           sp->pos = sp_pos;
312           spawnpoints.push_back(sp);
313           }
314       } else {
315         log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
316       }
317     }
318   }
319
320   // read objects
321   const lisp::Lisp* objects = reader.get_lisp("objects");
322   if(objects) {
323     lisp::ListIterator iter(objects);
324     while(iter.next()) {
325       GameObject* object = parse_object(iter.item(), *(iter.lisp()));
326       if(object) {
327         add_object(object);
328       } else {
329         log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
330       }
331     }
332   }
333
334   // add a camera
335   Camera* camera = new Camera(this, "Camera");
336   add_object(camera);
337
338   update_game_objects();
339
340   if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
341
342   fix_old_tiles();
343   update_game_objects();
344 }
345
346 void
347 Sector::fix_old_tiles()
348 {
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<GameObject*>::iterator i = gameobjects.begin();
578       i != gameobjects.end(); /* nothing */) {
579     GameObject* object = *i;
580
581     if(object->is_valid()) {
582       ++i;
583       continue;
584     }
585
586     before_object_remove(object);
587
588     object->unref();
589     i = gameobjects.erase(i);
590   }
591
592   /* add newly created objects */
593   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
594       i != gameobjects_new.end(); ++i)
595   {
596     GameObject* object = *i;
597
598     before_object_add(object);
599
600     gameobjects.push_back(object);
601   }
602   gameobjects_new.clear();
603 }
604
605 bool
606 Sector::before_object_add(GameObject* object)
607 {
608   Bullet* bullet = dynamic_cast<Bullet*> (object);
609   if(bullet != NULL) {
610     bullets.push_back(bullet);
611   }
612
613   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
614   if(movingobject != NULL) {
615     moving_objects.push_back(movingobject);
616   }
617
618   Portable* portable = dynamic_cast<Portable*> (object);
619   if(portable != NULL) {
620     portables.push_back(portable);
621   }
622
623   TileMap* tilemap = dynamic_cast<TileMap*> (object);
624   if(tilemap != NULL && tilemap->is_solid()) {
625     solid_tilemaps.push_back(tilemap);
626   }
627
628   Camera* camera = dynamic_cast<Camera*> (object);
629   if(camera != NULL) {
630     if(this->camera != 0) {
631       log_warning << "Multiple cameras added. Ignoring" << std::endl;
632       return false;
633     }
634     this->camera = camera;
635   }
636
637   Player* player = dynamic_cast<Player*> (object);
638   if(player != NULL) {
639     if(this->player != 0) {
640       log_warning << "Multiple players added. Ignoring" << std::endl;
641       return false;
642     }
643     this->player = player;
644   }
645
646   if(_current == this) {
647     try_expose(object);
648   }
649
650   return true;
651 }
652
653 void
654 Sector::try_expose(GameObject* object)
655 {
656   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
657   if(interface != NULL) {
658     HSQUIRRELVM vm = Scripting::global_vm;
659     sq_pushobject(vm, sector_table);
660     interface->expose(vm, -1);
661     sq_pop(vm, 1);
662   }
663 }
664
665 void
666 Sector::before_object_remove(GameObject* object)
667 {
668   Portable* portable = dynamic_cast<Portable*> (object);
669   if(portable != NULL) {
670     portables.erase(std::find(portables.begin(), portables.end(), portable));
671   }
672   Bullet* bullet = dynamic_cast<Bullet*> (object);
673   if(bullet != NULL) {
674     bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
675   }
676   MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
677   if(moving_object != NULL) {
678     moving_objects.erase(
679         std::find(moving_objects.begin(), moving_objects.end(), moving_object));
680   }
681           
682   if(_current == this)
683     try_unexpose(object);
684 }
685
686 void
687 Sector::try_unexpose(GameObject* object)
688 {
689   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
690   if(interface != NULL) {
691     HSQUIRRELVM vm = Scripting::global_vm;
692     SQInteger oldtop = sq_gettop(vm);
693     sq_pushobject(vm, sector_table);
694     try {
695       interface->unexpose(vm, -1);
696     } catch(std::exception& e) {
697       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
698     }
699     sq_settop(vm, oldtop);
700   }
701 }
702
703 void
704 Sector::draw(DrawingContext& context)
705 {
706   context.set_ambient_color( ambient_light );
707   context.push_transform();
708   context.set_translation(camera->get_translation());
709
710   for(GameObjects::iterator i = gameobjects.begin();
711       i != gameobjects.end(); ++i) {
712     GameObject* object = *i;
713     if(!object->is_valid())
714       continue;
715
716     if (draw_solids_only)
717     {
718       TileMap* tm = dynamic_cast<TileMap*>(object);
719       if (tm && !tm->is_solid())
720         continue;
721     }
722
723     object->draw(context);
724   }
725
726   if(show_collrects) {
727     Color col(0.2, 0.2, 0.2, 0.7);
728     for(MovingObjects::iterator i = moving_objects.begin();
729             i != moving_objects.end(); ++i) {
730       MovingObject* object = *i;
731       const Rect& rect = object->get_bbox();
732
733       context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
734     }
735   }
736
737   context.pop_transform();
738 }
739
740 /*-------------------------------------------------------------------------
741  * Collision Detection
742  *-------------------------------------------------------------------------*/
743
744 static const float SHIFT_DELTA = 7.0f;
745
746 /** r1 is supposed to be moving, r2 a solid object */
747 void check_collisions(collision::Constraints* constraints,
748                       const Vector& movement, const Rect& r1, const Rect& r2,
749                       GameObject* object = NULL, MovingObject* other = NULL)
750 {
751   if(!collision::intersects(r1, r2))
752     return;
753
754   // calculate intersection
755   float itop = r1.get_bottom() - r2.get_top();
756   float ibottom = r2.get_bottom() - r1.get_top();
757   float ileft = r1.get_right() - r2.get_left();
758   float iright = r2.get_right() - r1.get_left();
759
760   if(fabsf(movement.y) > fabsf(movement.x)) {
761     if(ileft < SHIFT_DELTA) {
762       constraints->right = std::min(constraints->right, r2.get_left());
763       return;
764     } else if(iright < SHIFT_DELTA) {
765       constraints->left = std::max(constraints->left, r2.get_right());
766       return;
767     }
768   } else {
769     // shiftout bottom/top
770     if(itop < SHIFT_DELTA) {
771       constraints->bottom = std::min(constraints->bottom, r2.get_top());
772       return;
773     } else if(ibottom < SHIFT_DELTA) {
774       constraints->top = std::max(constraints->top, r2.get_bottom());
775       return;
776     }
777   }
778
779   if(other != NULL) {
780     CollisionHit dummy;
781     HitResponse response = other->collision(*object, dummy);
782     if(response == PASSTHROUGH)
783       return;
784     if(other->get_movement() != Vector(0, 0)) {
785       // TODO what todo when we collide with 2 moving objects?!?
786       constraints->ground_movement = other->get_movement();
787     }
788   }
789
790   float vert_penetration = std::min(itop, ibottom);
791   float horiz_penetration = std::min(ileft, iright);
792   if(vert_penetration < horiz_penetration) {
793     if(itop < ibottom) {
794       constraints->bottom = std::min(constraints->bottom, r2.get_top());
795       constraints->hit.bottom = true;
796     } else {
797       constraints->top = std::max(constraints->top, r2.get_bottom());
798       constraints->hit.top = true;
799     }
800   } else {
801     if(ileft < iright) {
802       constraints->right = std::min(constraints->right, r2.get_left());
803       constraints->hit.right = true;
804     } else {
805       constraints->left = std::max(constraints->left, r2.get_right());
806       constraints->hit.left = true;
807     }
808   }
809 }
810
811 static const float DELTA = .001;
812
813 void
814 Sector::collision_tilemap(collision::Constraints* constraints,
815                           const Vector& movement, const Rect& dest) const
816 {
817   // calculate rectangle where the object will move
818   float x1 = dest.get_left();
819   float x2 = dest.get_right();
820   float y1 = dest.get_top();
821   float y2 = dest.get_bottom();
822
823   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
824     TileMap* solids = *i;
825
826     // test with all tiles in this rectangle
827     int starttilex = int(x1 - solids->get_x_offset()) / 32;
828     int starttiley = int(y1 - solids->get_y_offset()) / 32;
829     int max_x = int(x2 - solids->get_x_offset());
830     int max_y = int(y2+1 - solids->get_y_offset());
831
832     for(int x = starttilex; x*32 < max_x; ++x) {
833       for(int y = starttiley; y*32 < max_y; ++y) {
834         const Tile* tile = solids->get_tile(x, y);
835         if(!tile)
836           continue;
837         // skip non-solid tiles
838         if((tile->getAttributes() & Tile::SOLID) == 0)
839           continue;
840         // only handle unisolid when the player is falling down and when he was
841         // above the tile before
842         if(tile->getAttributes() & Tile::UNISOLID) {
843           if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
844             continue;
845         }
846
847         if(tile->getAttributes() & Tile::SLOPE) { // slope tile
848           AATriangle triangle;
849           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
850           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
851           triangle = AATriangle(p1, p2, tile->getData());
852
853           collision::rectangle_aatriangle(constraints, dest, triangle);
854         } else { // normal rectangular tile
855           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());
856           check_collisions(constraints, movement, dest, rect);
857         }
858       }
859     }
860   }
861 }
862
863 uint32_t
864 Sector::collision_tile_attributes(const Rect& dest) const
865 {
866   float x1 = dest.p1.x;
867   float y1 = dest.p1.y;
868   float x2 = dest.p2.x;
869   float y2 = dest.p2.y;
870
871   uint32_t result = 0;
872   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
873     TileMap* solids = *i;
874
875     // test with all tiles in this rectangle
876     int starttilex = int(x1 - solids->get_x_offset()) / 32;
877     int starttiley = int(y1 - solids->get_y_offset()) / 32;
878     int max_x = int(x2 - solids->get_x_offset());
879     int max_y = int(y2+1 - solids->get_y_offset());
880
881     for(int x = starttilex; x*32 < max_x; ++x) {
882       for(int y = starttiley; y*32 < max_y; ++y) {
883         const Tile* tile = solids->get_tile(x, y);
884         if(!tile)
885           continue;
886         result |= tile->getAttributes();
887       }
888     }
889   }
890
891   return result;
892 }
893
894 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
895 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
896                            Vector& normal)
897 {
898   float itop = r1.get_bottom() - r2.get_top();
899   float ibottom = r2.get_bottom() - r1.get_top();
900   float ileft = r1.get_right() - r2.get_left();
901   float iright = r2.get_right() - r1.get_left();
902
903   float vert_penetration = std::min(itop, ibottom);
904   float horiz_penetration = std::min(ileft, iright);
905   if(vert_penetration < horiz_penetration) {
906     if(itop < ibottom) {
907       hit.bottom = true;
908       normal.y = vert_penetration;
909     } else {
910       hit.top = true;
911       normal.y = -vert_penetration;
912     }
913   } else {
914     if(ileft < iright) {
915       hit.right = true;
916       normal.x = horiz_penetration;
917     } else {
918       hit.left = true;
919       normal.x = -horiz_penetration;
920     }
921   }
922 }
923
924 void
925 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
926 {
927   using namespace collision;
928
929   const Rect& r1 = object1->dest;
930   const Rect& r2 = object2->dest;
931
932   CollisionHit hit;
933   if(intersects(object1->dest, object2->dest)) {
934     Vector normal;
935     get_hit_normal(r1, r2, hit, normal);
936
937     HitResponse response1 = object1->collision(*object2, hit);
938     std::swap(hit.left, hit.right);
939     std::swap(hit.top, hit.bottom);
940     HitResponse response2 = object2->collision(*object1, hit);
941     assert( response1 != SOLID && response1 != PASSTHROUGH );
942     assert( response2 != SOLID && response2 != PASSTHROUGH );
943     if(response1 == CONTINUE && response2 == CONTINUE) {
944       normal *= (0.5 + DELTA);
945       object1->dest.move(-normal);
946       object2->dest.move(normal);
947     } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
948       normal *= (1 + DELTA);
949       object1->dest.move(-normal);
950     } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
951       normal *= (1 + DELTA);
952       object2->dest.move(normal);
953     }
954   }
955 }
956
957 void
958 Sector::collision_static(collision::Constraints* constraints,
959                          const Vector& movement, const Rect& dest,
960                          GameObject& object)
961 {
962   collision_tilemap(constraints, movement, dest);
963
964   // collision with other (static) objects
965   for(MovingObjects::iterator i = moving_objects.begin();
966       i != moving_objects.end(); ++i) {
967     MovingObject* moving_object = *i;
968     if(moving_object->get_group() != COLGROUP_STATIC
969        && moving_object->get_group() != COLGROUP_MOVING_STATIC)
970       continue;
971     if(!moving_object->is_valid())
972       continue;
973
974     if(moving_object != &object)
975       check_collisions(constraints, movement, dest, moving_object->bbox,
976           &object, moving_object);
977   }
978 }
979
980 void
981 Sector::collision_static_constrains(MovingObject& object)
982 {
983   using namespace collision;
984
985   Constraints constraints;
986   Vector movement = object.get_movement();
987   Rect& dest = object.dest;
988   float owidth = object.get_bbox().get_width();
989   float oheight = object.get_bbox().get_height();
990
991   for(int i = 0; i < 2; ++i) {
992     collision_static(&constraints, Vector(0, movement.y), dest, object);
993     if(!constraints.has_constraints())
994       break;
995
996     // apply calculated horizontal constraints
997     if(constraints.bottom < INFINITY) {
998       float height = constraints.bottom - constraints.top;
999       if(height < oheight) {
1000         // we're crushed, but ignore this for now, we'll get this again
1001         // later if we're really crushed or things will solve itself when
1002         // looking at the vertical constraints
1003       }
1004       dest.p2.y = constraints.bottom - DELTA;
1005       dest.p1.y = dest.p2.y - oheight;
1006     } else if(constraints.top > -INFINITY) {
1007       dest.p1.y = constraints.top + DELTA;
1008       dest.p2.y = dest.p1.y + oheight;
1009     }
1010   }
1011   if(constraints.has_constraints()) {
1012     if(constraints.hit.bottom) {
1013       dest.move(constraints.ground_movement);
1014     }
1015     if(constraints.hit.top || constraints.hit.bottom) {
1016       constraints.hit.left = false;
1017       constraints.hit.right = false;
1018       object.collision_solid(constraints.hit);
1019     }
1020   }
1021
1022   constraints = Constraints();
1023   for(int i = 0; i < 2; ++i) {
1024     collision_static(&constraints, movement, dest, object);
1025     if(!constraints.has_constraints())
1026       break;
1027
1028     // apply calculated vertical constraints
1029     if(constraints.right < INFINITY) {
1030       float width = constraints.right - constraints.left;
1031       if(width + SHIFT_DELTA < owidth) {
1032         printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1033             constraints.left, constraints.right);
1034         CollisionHit h;
1035         h.left = true;
1036         h.right = true;
1037         h.crush = true;
1038         object.collision_solid(h);
1039       } else {
1040         dest.p2.x = constraints.right - DELTA;
1041         dest.p1.x = dest.p2.x - owidth;
1042       }
1043     } else if(constraints.left > -INFINITY) {
1044       dest.p1.x = constraints.left + DELTA;
1045       dest.p2.x = dest.p1.x + owidth;
1046     }
1047   }
1048
1049   if(constraints.has_constraints()) {
1050     if( constraints.hit.left || constraints.hit.right
1051         || constraints.hit.top || constraints.hit.bottom
1052         || constraints.hit.crush )
1053       object.collision_solid(constraints.hit);
1054   }
1055
1056   // an extra pass to make sure we're not crushed horizontally
1057   constraints = Constraints();
1058   collision_static(&constraints, movement, dest, object);
1059   if(constraints.bottom < INFINITY) {
1060     float height = constraints.bottom - constraints.top;
1061     if(height + SHIFT_DELTA < oheight) {
1062       printf("Object %p crushed vertically...\n", &object);
1063       CollisionHit h;
1064       h.top = true;
1065       h.bottom = true;
1066       h.crush = true;
1067       object.collision_solid(h);
1068     }
1069   }
1070 }
1071
1072 void
1073 Sector::handle_collisions()
1074 {
1075   using namespace collision;
1076
1077   // calculate destination positions of the objects
1078   for(MovingObjects::iterator i = moving_objects.begin();
1079       i != moving_objects.end(); ++i) {
1080     MovingObject* moving_object = *i;
1081
1082     moving_object->dest = moving_object->get_bbox();
1083     moving_object->dest.move(moving_object->get_movement());
1084   }
1085
1086   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1087   for(MovingObjects::iterator i = moving_objects.begin();
1088       i != moving_objects.end(); ++i) {
1089     MovingObject* moving_object = *i;
1090     if((moving_object->get_group() != COLGROUP_MOVING
1091           && moving_object->get_group() != COLGROUP_MOVING_STATIC
1092           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1093         || !moving_object->is_valid())
1094       continue;
1095
1096     collision_static_constrains(*moving_object);
1097   }
1098
1099
1100   // part2: COLGROUP_MOVING vs tile attributes
1101   for(MovingObjects::iterator i = moving_objects.begin();
1102       i != moving_objects.end(); ++i) {
1103     MovingObject* moving_object = *i;
1104     if((moving_object->get_group() != COLGROUP_MOVING
1105           && moving_object->get_group() != COLGROUP_MOVING_STATIC
1106           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1107         || !moving_object->is_valid())
1108       continue;
1109
1110     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1111     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1112       moving_object->collision_tile(tile_attributes);
1113     }
1114   }
1115
1116   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1117   for(MovingObjects::iterator i = moving_objects.begin();
1118       i != moving_objects.end(); ++i) {
1119     MovingObject* moving_object = *i;
1120     if((moving_object->get_group() != COLGROUP_MOVING
1121           && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1122         || !moving_object->is_valid())
1123       continue;
1124
1125     for(MovingObjects::iterator i2 = moving_objects.begin();
1126         i2 != moving_objects.end(); ++i2) {
1127       MovingObject* moving_object_2 = *i2;
1128       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1129          || !moving_object_2->is_valid())
1130         continue;
1131
1132       if(intersects(moving_object->dest, moving_object_2->dest)) {
1133         Vector normal;
1134         CollisionHit hit;
1135         get_hit_normal(moving_object->dest, moving_object_2->dest,
1136                        hit, normal);
1137         moving_object->collision(*moving_object_2, hit);
1138         moving_object_2->collision(*moving_object, hit);
1139       }
1140     }
1141   }
1142
1143   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1144   for(MovingObjects::iterator i = moving_objects.begin();
1145       i != moving_objects.end(); ++i) {
1146     MovingObject* moving_object = *i;
1147
1148     if((moving_object->get_group() != COLGROUP_MOVING
1149           && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1150         || !moving_object->is_valid())
1151       continue;
1152
1153     for(MovingObjects::iterator i2 = i+1;
1154         i2 != moving_objects.end(); ++i2) {
1155       MovingObject* moving_object_2 = *i2;
1156       if((moving_object_2->get_group() != COLGROUP_MOVING
1157             && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1158          || !moving_object_2->is_valid())
1159         continue;
1160
1161       collision_object(moving_object, moving_object_2);
1162     }
1163   }
1164
1165   // apply object movement
1166   for(MovingObjects::iterator i = moving_objects.begin();
1167       i != moving_objects.end(); ++i) {
1168     MovingObject* moving_object = *i;
1169
1170     moving_object->bbox = moving_object->dest;
1171     moving_object->movement = Vector(0, 0);
1172   }
1173 }
1174
1175 bool
1176 Sector::is_free_of_tiles(const Rect& rect) const
1177 {
1178   using namespace collision;
1179
1180   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1181     TileMap* solids = *i;
1182
1183     // test with all tiles in this rectangle
1184     int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1185     int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1186     int max_x = int(rect.p2.x - solids->get_x_offset());
1187     int max_y = int(rect.p2.y - solids->get_y_offset());
1188
1189     for(int x = starttilex; x*32 <= max_x; ++x) {
1190       for(int y = starttiley; y*32 <= max_y; ++y) {
1191         const Tile* tile = solids->get_tile(x, y);
1192         if(!tile) continue;
1193         if(tile->getAttributes() & Tile::SLOPE) {
1194           AATriangle triangle;
1195           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1196           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1197           triangle = AATriangle(p1, p2, tile->getData());
1198           Constraints constraints;
1199           return collision::rectangle_aatriangle(&constraints, rect, triangle);
1200         }
1201         if(tile->getAttributes() & Tile::SOLID) return false;
1202       }
1203     }
1204   }
1205
1206   return true;
1207 }
1208
1209 bool
1210 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object) const
1211 {
1212   using namespace collision;
1213
1214   if (!is_free_of_tiles(rect)) return false;
1215
1216   for(MovingObjects::const_iterator i = moving_objects.begin();
1217       i != moving_objects.end(); ++i) {
1218     const MovingObject* moving_object = *i;
1219     if (moving_object == ignore_object) continue;
1220     if (!moving_object->is_valid()) continue;
1221     if (moving_object->get_group() == COLGROUP_STATIC) {
1222       if(intersects(rect, moving_object->get_bbox())) return false;
1223     }
1224   }
1225
1226   return true;
1227 }
1228
1229 bool
1230 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1231 {
1232   using namespace collision;
1233
1234   if (!is_free_of_tiles(rect)) return false;
1235
1236   for(MovingObjects::const_iterator i = moving_objects.begin();
1237       i != moving_objects.end(); ++i) {
1238     const MovingObject* moving_object = *i;
1239     if (moving_object == ignore_object) continue;
1240     if (!moving_object->is_valid()) continue;
1241     if ((moving_object->get_group() == COLGROUP_MOVING) 
1242       || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1243       || (moving_object->get_group() == COLGROUP_STATIC)) {
1244       if(intersects(rect, moving_object->get_bbox())) return false;
1245     }
1246   }
1247
1248   return true;
1249 }
1250
1251 bool
1252 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1253 {
1254   // TODO remove this function and move these checks elsewhere...
1255
1256   Bullet* new_bullet = 0;
1257   if((int)bullets.size() >= player_status->max_fire_bullets)
1258     return false;
1259   new_bullet = new Bullet(pos, xm, dir);
1260   add_object(new_bullet);
1261
1262   sound_manager->play("sounds/shoot.wav");
1263
1264   return true;
1265 }
1266
1267 bool
1268 Sector::add_smoke_cloud(const Vector& pos)
1269 {
1270   add_object(new SmokeCloud(pos));
1271   return true;
1272 }
1273
1274 void
1275 Sector::play_music(MusicType type)
1276 {
1277   currentmusic = type;
1278   switch(currentmusic) {
1279     case LEVEL_MUSIC:
1280       sound_manager->play_music(music);
1281       break;
1282     case HERRING_MUSIC:
1283       sound_manager->play_music("music/salcon.ogg");
1284       break;
1285     case HERRING_WARNING_MUSIC:
1286       sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1287       break;
1288     default:
1289       sound_manager->play_music("");
1290       break;
1291   }
1292 }
1293
1294 MusicType
1295 Sector::get_music_type()
1296 {
1297   return currentmusic;
1298 }
1299
1300 int
1301 Sector::get_total_badguys()
1302 {
1303   int total_badguys = 0;
1304   for(GameObjects::iterator i = gameobjects.begin();
1305       i != gameobjects.end(); ++i) {
1306     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1307     if (badguy && badguy->countMe)
1308       total_badguys++;
1309   }
1310
1311   return total_badguys;
1312 }
1313
1314 bool
1315 Sector::inside(const Rect& rect) const
1316 {
1317   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1318     TileMap* solids = *i;
1319     bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1320     bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1321     if (horizontally && vertically) return true;
1322   }
1323   return false;
1324 }
1325
1326 float
1327 Sector::get_width() const
1328 {
1329   float width = 0;
1330   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1331     TileMap* solids = *i;
1332     if ((solids->get_width() * 32 + solids->get_x_offset()) > width) width = (solids->get_width() * 32 + solids->get_x_offset());
1333   }
1334   return width;
1335 }
1336
1337 float
1338 Sector::get_height() const
1339 {
1340   float height = 0;
1341   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1342     TileMap* solids = *i;
1343     if ((solids->get_height() * 32 + solids->get_y_offset()) > height) height = (solids->get_height() * 32 + solids->get_y_offset());
1344   }
1345   return height;
1346 }
1347
1348 void
1349 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1350 {
1351   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1352     TileMap* solids = *i;
1353     solids->change_all(old_tile_id, new_tile_id);
1354   }
1355 }