a710145e07b63fa00ce8e27903130dea4f506c3e
[supertux.git] / src / sector.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 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
30 #include "sector.hpp"
31 #include "player_status.hpp"
32 #include "object/gameobjs.hpp"
33 #include "object/camera.hpp"
34 #include "object/background.hpp"
35 #include "object/gradient.hpp"
36 #include "object/particlesystem.hpp"
37 #include "object/particlesystem_interactive.hpp"
38 #include "object/tilemap.hpp"
39 #include "lisp/parser.hpp"
40 #include "lisp/lisp.hpp"
41 #include "lisp/writer.hpp"
42 #include "lisp/list_iterator.hpp"
43 #include "tile.hpp"
44 #include "audio/sound_manager.hpp"
45 #include "game_session.hpp"
46 #include "resources.hpp"
47 #include "statistics.hpp"
48 #include "collision_grid.hpp"
49 #include "collision_grid_iterator.hpp"
50 #include "object_factory.hpp"
51 #include "collision.hpp"
52 #include "spawn_point.hpp"
53 #include "math/rect.hpp"
54 #include "math/aatriangle.hpp"
55 #include "object/coin.hpp"
56 #include "object/block.hpp"
57 #include "object/invisible_block.hpp"
58 #include "object/bullet.hpp"
59 #include "object/text_object.hpp"
60 #include "badguy/jumpy.hpp"
61 #include "trigger/sequence_trigger.hpp"
62 #include "player_status.hpp"
63 #include "script_manager.hpp"
64 #include "scripting/wrapper_util.hpp"
65 #include "script_interface.hpp"
66 #include "msg.hpp"
67
68 Sector* Sector::_current = 0;
69
70 Sector::Sector()
71   : currentmusic(LEVEL_MUSIC), gravity(10),
72     player(0), solids(0), camera(0)
73 {
74   add_object(new Player(player_status));
75   add_object(new DisplayEffect());
76   add_object(new TextObject());
77
78 #ifdef USE_GRID
79   grid = new CollisionGrid(32000, 32000);
80 #else
81   grid = 0;
82 #endif
83
84   // create a new squirrel table for the sector
85   HSQUIRRELVM vm = script_manager->get_global_vm();
86   
87   sq_newtable(vm);
88   sq_pushroottable(vm);
89   if(SQ_FAILED(sq_setdelegate(vm, -2)))
90     throw Scripting::SquirrelError(vm, "Couldn't set sector_table delegate");
91
92   sq_resetobject(&sector_table);
93   if(SQ_FAILED(sq_getstackobj(vm, -1, &sector_table)))
94     throw Scripting::SquirrelError(vm, "Couldn't get sector table");
95   sq_addref(vm, &sector_table);
96   sq_pop(vm, 1);
97 }
98
99 Sector::~Sector()
100 {
101   update_game_objects();
102   assert(gameobjects_new.size() == 0);
103
104   deactivate();
105
106   delete grid;
107
108   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
109       ++i) {
110     before_object_remove(*i);
111     delete *i;
112   }
113
114   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
115       ++i)
116     delete *i;
117
118   sq_release(script_manager->get_global_vm(), &sector_table);
119 }
120
121 GameObject*
122 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
123 {
124   if(name == "camera") {
125     Camera* camera = new Camera(this);
126     camera->parse(reader);
127     return camera;
128   } else if(name == "particles-snow") {
129     SnowParticleSystem* partsys = new SnowParticleSystem();
130     partsys->parse(reader);
131     return partsys;
132   } else if(name == "particles-rain") {
133     RainParticleSystem* partsys = new RainParticleSystem();
134     partsys->parse(reader);
135     return partsys;
136   } else if(name == "particles-comets") {
137     CometParticleSystem* partsys = new CometParticleSystem();
138     partsys->parse(reader);
139     return partsys;
140   } else if(name == "particles-ghosts") {
141     GhostParticleSystem* partsys = new GhostParticleSystem();
142     partsys->parse(reader);
143     return partsys;
144   } else if(name == "particles-clouds") {
145     CloudParticleSystem* partsys = new CloudParticleSystem();
146     partsys->parse(reader);
147     return partsys;
148   } else if(name == "money") { // for compatibility with old maps
149     return new Jumpy(reader);
150   } 
151
152   try {
153     return create_object(name, reader);
154   } catch(std::exception& e) {
155     msg_warning << e.what() << "" << std::endl;
156   }
157   
158   return 0;
159 }
160
161 void
162 Sector::parse(const lisp::Lisp& sector)
163 {  
164   lisp::ListIterator iter(&sector);
165   while(iter.next()) {
166     const std::string& token = iter.item();
167     if(token == "name") {
168       iter.value()->get(name);
169     } else if(token == "gravity") {
170       iter.value()->get(gravity);
171     } else if(token == "music") {
172       iter.value()->get(music);
173     } else if(token == "spawnpoint") {
174       SpawnPoint* sp = new SpawnPoint(iter.lisp());
175       spawnpoints.push_back(sp);
176     } else if(token == "init-script") {
177       iter.value()->get(init_script);
178     } else {
179       GameObject* object = parse_object(token, *(iter.lisp()));
180       if(object) {
181         add_object(object);
182       }
183     }
184   }
185
186   update_game_objects();
187
188   if(!solids)
189     throw std::runtime_error("sector does not contain a solid tile layer.");
190
191   fix_old_tiles();
192   if(!camera) {
193     msg_warning << "sector '" << name << "' does not contain a camera." << std::endl;
194     update_game_objects();
195     add_object(new Camera(this));
196   }
197
198   update_game_objects();
199 }
200
201 void
202 Sector::parse_old_format(const lisp::Lisp& reader)
203 {
204   name = "main";
205   reader.get("gravity", gravity);
206
207   std::string backgroundimage;
208   reader.get("background", backgroundimage);
209   float bgspeed = .5;
210   reader.get("bkgd_speed", bgspeed);
211   bgspeed /= 100;
212
213   Color bkgd_top, bkgd_bottom;
214   int r = 0, g = 0, b = 128;
215   reader.get("bkgd_red_top", r);
216   reader.get("bkgd_green_top",  g);
217   reader.get("bkgd_blue_top",  b);
218   bkgd_top.red = static_cast<float> (r) / 255.0f;
219   bkgd_top.green = static_cast<float> (g) / 255.0f;
220   bkgd_top.blue = static_cast<float> (b) / 255.0f;
221   
222   reader.get("bkgd_red_bottom",  r);
223   reader.get("bkgd_green_bottom", g);
224   reader.get("bkgd_blue_bottom", b);
225   bkgd_bottom.red = static_cast<float> (r) / 255.0f;
226   bkgd_bottom.green = static_cast<float> (g) / 255.0f;
227   bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
228   
229   if(backgroundimage != "") {
230     Background* background = new Background();
231     background->set_image(
232             std::string("images/background/") + backgroundimage, bgspeed);
233     add_object(background);
234   } else {
235     Gradient* gradient = new Gradient();
236     gradient->set_gradient(bkgd_top, bkgd_bottom);
237     add_object(gradient);
238   }
239
240   std::string particlesystem;
241   reader.get("particle_system", particlesystem);
242   if(particlesystem == "clouds")
243     add_object(new CloudParticleSystem());
244   else if(particlesystem == "snow")
245     add_object(new SnowParticleSystem());
246   else if(particlesystem == "rain")
247     add_object(new RainParticleSystem());
248
249   Vector startpos(100, 170);
250   reader.get("start_pos_x", startpos.x);
251   reader.get("start_pos_y", startpos.y);
252
253   SpawnPoint* spawn = new SpawnPoint;
254   spawn->pos = startpos;
255   spawn->name = "main";
256   spawnpoints.push_back(spawn);
257
258   music = "chipdisko.ogg";
259   reader.get("music", music);
260   music = "music/" + music;
261
262   int width = 30, height = 15;
263   reader.get("width", width);
264   reader.get("height", height);
265   
266   std::vector<unsigned int> tiles;
267   if(reader.get_vector("interactive-tm", tiles)
268       || reader.get_vector("tilemap", tiles)) {
269     TileMap* tilemap = new TileMap();
270     tilemap->set(width, height, tiles, LAYER_TILES, true);
271     add_object(tilemap);
272   }
273
274   if(reader.get_vector("background-tm", tiles)) {
275     TileMap* tilemap = new TileMap();
276     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
277     add_object(tilemap);
278   }
279
280   if(reader.get_vector("foreground-tm", tiles)) {
281     TileMap* tilemap = new TileMap();
282     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
283     add_object(tilemap);
284   }
285
286   // read reset-points (now spawn-points)
287   const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
288   if(resetpoints) {
289     lisp::ListIterator iter(resetpoints);
290     while(iter.next()) {
291       if(iter.item() == "point") {
292         Vector sp_pos;
293         if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
294           {
295           SpawnPoint* sp = new SpawnPoint;
296           sp->name = "main";
297           sp->pos = sp_pos;
298           spawnpoints.push_back(sp);
299           }
300       } else {
301         msg_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
302       }
303     }
304   }
305
306   // read objects
307   const lisp::Lisp* objects = reader.get_lisp("objects");
308   if(objects) {
309     lisp::ListIterator iter(objects);
310     while(iter.next()) {
311       GameObject* object = parse_object(iter.item(), *(iter.lisp()));
312       if(object) {
313         add_object(object);
314       } else {
315         msg_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
316       }
317     }
318   }
319
320   // add a camera
321   Camera* camera = new Camera(this);
322   add_object(camera);
323
324   update_game_objects();
325
326   if(solids == 0)
327     throw std::runtime_error("sector does not contain a solid tile layer.");
328
329   fix_old_tiles();
330   update_game_objects();
331 }
332
333 void
334 Sector::fix_old_tiles()
335 {
336   // hack for now...
337   for(size_t x=0; x < solids->get_width(); ++x) {
338     for(size_t y=0; y < solids->get_height(); ++y) {
339       const Tile* tile = solids->get_tile(x, y);
340       Vector pos(x*32, y*32);
341       
342       if(tile->getID() == 112) {
343         add_object(new InvisibleBlock(pos));
344         solids->change(x, y, 0);
345       } else if(tile->getAttributes() & Tile::COIN) {
346         add_object(new Coin(pos));
347         solids->change(x, y, 0);
348       } else if(tile->getAttributes() & Tile::FULLBOX) {
349         add_object(new BonusBlock(pos, tile->getData()));
350         solids->change(x, y, 0);
351       } else if(tile->getAttributes() & Tile::BRICK) {
352         add_object(new Brick(pos, tile->getData()));
353         solids->change(x, y, 0);
354       } else if(tile->getAttributes() & Tile::GOAL) {
355         std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
356         add_object(new SequenceTrigger(pos, sequence));
357         solids->change(x, y, 0);
358       }
359     }
360   }
361 }
362
363 void
364 Sector::write(lisp::Writer& writer)
365 {
366   writer.write_string("name", name);
367   writer.write_float("gravity", gravity);
368   writer.write_string("music", music);
369
370   // write spawnpoints
371   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
372       ++i) {
373     SpawnPoint* spawn = *i;
374     writer.start_list("spawn-points");
375     writer.write_string("name", spawn->name);
376     writer.write_float("x", spawn->pos.x);
377     writer.write_float("y", spawn->pos.y);
378     writer.end_list("spawn-points");
379   }
380
381   // write objects
382   for(GameObjects::iterator i = gameobjects.begin();
383       i != gameobjects.end(); ++i) {
384     Serializable* serializable = dynamic_cast<Serializable*> (*i);
385     if(serializable)
386       serializable->write(writer);
387   }
388 }
389
390 HSQUIRRELVM
391 Sector::run_script(std::istream& in, const std::string& sourcename)
392 {
393   HSQUIRRELVM vm = script_manager->create_thread();
394   sq_pushobject(vm, sector_table);
395   sq_setroottable(vm);
396   Scripting::compile_and_run(vm, in, sourcename);
397
398   return vm;
399 }
400
401 void
402 Sector::add_object(GameObject* object)
403 {
404   // make sure the object isn't already in the list
405 #ifdef DEBUG
406   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
407       ++i) {
408     if(*i == object) {
409       assert("object already added to sector" == 0);
410     }
411   }
412   for(GameObjects::iterator i = gameobjects_new.begin();
413       i != gameobjects_new.end(); ++i) {
414     if(*i == object) {
415       assert("object already added to sector" == 0);
416     }
417   }
418 #endif
419
420   gameobjects_new.push_back(object);
421 }
422
423 void
424 Sector::activate(const std::string& spawnpoint)
425 {
426   SpawnPoint* sp = 0;
427   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
428       ++i) {
429     if((*i)->name == spawnpoint) {
430       sp = *i;
431       break;
432     }
433   }                                                                           
434   if(!sp) {
435     msg_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
436     if(spawnpoint != "main") {
437       activate("main");
438     } else {
439       activate(Vector(0, 0));
440     }
441   } else {
442     activate(sp->pos);
443   }
444 }
445
446 void
447 Sector::activate(const Vector& player_pos)
448 {
449   if(_current != this) {
450     if(_current != NULL)
451       _current->deactivate();
452     _current = this;
453
454     // register sectortable as current_sector in scripting
455     HSQUIRRELVM vm = script_manager->get_global_vm();
456     sq_pushroottable(vm);
457     sq_pushstring(vm, "current_sector", -1);
458     sq_pushobject(vm, sector_table);
459     if(SQ_FAILED(sq_createslot(vm, -3)))
460       throw Scripting::SquirrelError(vm, "Couldn't set current_sector in roottable");
461     sq_pop(vm, 1);
462
463     for(GameObjects::iterator i = gameobjects.begin();
464         i != gameobjects.end(); ++i) {
465       GameObject* object = *i;
466
467       try_expose(object);
468     }
469   }
470
471   player->move(player_pos);
472   camera->reset(player->get_pos());
473
474   // Run init script
475   if(init_script != "") {
476     std::istringstream in(init_script);
477     run_script(in, std::string("Sector(") + name + ") - init");
478   }
479 }
480
481 void
482 Sector::deactivate()
483 {
484   if(_current != this)
485     return;
486
487   HSQUIRRELVM vm = script_manager->get_global_vm();
488   sq_pushroottable(vm);
489   sq_pushstring(vm, "current_sector", -1);
490   if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
491     throw Scripting::SquirrelError(vm, "Couldn't unset current_sector in roottable");
492   sq_pop(vm, 1);
493   
494   for(GameObjects::iterator i = gameobjects.begin();
495       i != gameobjects.end(); ++i) {
496     GameObject* object = *i;
497     
498     try_unexpose(object);
499   }
500
501   _current = NULL;
502 }
503
504 Rect
505 Sector::get_active_region()
506 {
507   return Rect(
508     camera->get_translation() - Vector(1600, 1200),
509     camera->get_translation() + Vector(1600, 1200));
510 }
511
512 void
513 Sector::update(float elapsed_time)
514 {
515   player->check_bounds(camera);
516
517 #if 0
518   CollisionGridIterator iter(*grid, get_active_region());
519   while(MovingObject* object = iter.next()) {
520     if(!object->is_valid())
521       continue;
522
523     object->update(elapsed_time);
524   }
525 #else
526   /* update objects */
527   for(GameObjects::iterator i = gameobjects.begin();
528           i != gameobjects.end(); ++i) {
529     GameObject* object = *i;
530     if(!object->is_valid())
531       continue;
532     
533     object->update(elapsed_time);
534   }
535 #endif
536   
537   /* Handle all possible collisions. */
538   handle_collisions();
539   update_game_objects();
540 }
541
542 void
543 Sector::update_game_objects()
544 {
545   /** cleanup marked objects */
546   for(std::vector<Bullet*>::iterator i = bullets.begin();
547       i != bullets.end(); /* nothing */) {
548     Bullet* bullet = *i;
549     if(bullet->is_valid()) {
550       ++i;
551       continue;
552     }
553
554     i = bullets.erase(i);
555   }
556   for(MovingObjects::iterator i = moving_objects.begin();
557       i != moving_objects.end(); /* nothing */) {
558     MovingObject* moving_object = *i;
559     if(moving_object->is_valid()) {
560       ++i;
561       continue;
562     }
563
564 #ifdef USE_GRID
565     grid->remove_object(moving_object);
566 #endif
567     
568     i = moving_objects.erase(i);
569   }
570   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
571       i != gameobjects.end(); /* nothing */) {
572     GameObject* object = *i;
573     
574     if(object->is_valid()) {
575       ++i;
576       continue;
577     }
578
579     before_object_remove(object);
580     
581     delete *i;
582     i = gameobjects.erase(i);
583   }
584
585   /* add newly created objects */
586   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
587       i != gameobjects_new.end(); ++i)
588   {
589     GameObject* object = *i;
590
591     before_object_add(object);
592     
593     gameobjects.push_back(object);
594   }
595   gameobjects_new.clear();
596 }
597
598 bool
599 Sector::before_object_add(GameObject* object)
600 {
601   Bullet* bullet = dynamic_cast<Bullet*> (object);
602   if(bullet)
603     bullets.push_back(bullet);
604
605   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
606   if(movingobject) {
607     moving_objects.push_back(movingobject);
608 #ifdef USE_GRID
609     grid->add_object(movingobject);
610 #endif
611   }
612   
613   TileMap* tilemap = dynamic_cast<TileMap*> (object);
614   if(tilemap && tilemap->is_solid()) {
615     if(solids == 0) {
616       solids = tilemap;
617     } else {
618       msg_warning << "Another solid tilemaps added. Ignoring" << std::endl;
619     }
620   }
621
622   Camera* camera = dynamic_cast<Camera*> (object);
623   if(camera) {
624     if(this->camera != 0) {
625       msg_warning << "Multiple cameras added. Ignoring" << std::endl;
626       return false;
627     }
628     this->camera = camera;
629   }
630
631   Player* player = dynamic_cast<Player*> (object);
632   if(player) {
633     if(this->player != 0) {
634       msg_warning << "Multiple players added. Ignoring" << std::endl;
635       return false;
636     }
637     this->player = player;
638   }
639
640   if(_current == this) {
641     try_expose(object);
642   }
643   
644   return true;
645 }
646
647 void
648 Sector::try_expose(GameObject* object)
649 {
650   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
651   if(interface != NULL) {
652     HSQUIRRELVM vm = script_manager->get_global_vm();
653     sq_pushobject(vm, sector_table);
654     interface->expose(vm, -1);
655     sq_pop(vm, 1);
656   }
657 }
658
659 void
660 Sector::before_object_remove(GameObject* object)
661 {
662   if(_current == this)
663     try_unexpose(object);
664 }
665
666 void
667 Sector::try_unexpose(GameObject* object)
668 {
669   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
670   if(interface != NULL) {
671     HSQUIRRELVM vm = script_manager->get_global_vm();
672     sq_pushobject(vm, sector_table);
673     interface->unexpose(vm, -1);
674     sq_pop(vm, 1);
675   }
676
677
678 void
679 Sector::draw(DrawingContext& context)
680 {
681   context.push_transform();
682   context.set_translation(camera->get_translation());
683
684   for(GameObjects::iterator i = gameobjects.begin();
685       i != gameobjects.end(); ++i) {
686     GameObject* object = *i; 
687     if(!object->is_valid())
688       continue;
689     
690     object->draw(context);
691   }
692
693   context.pop_transform();
694 }
695
696 static const float DELTA = .001;
697
698 void
699 Sector::collision_tilemap(const Rect& dest, const Vector& movement,
700                           CollisionHit& hit) const
701 {
702   // calculate rectangle where the object will move
703   float x1 = dest.get_left();
704   float x2 = dest.get_right();
705   float y1 = dest.get_top();
706   float y2 = dest.get_bottom();
707
708   // test with all tiles in this rectangle
709   int starttilex = int(x1) / 32;
710   int starttiley = int(y1) / 32;
711   int max_x = int(x2 + (1 - DELTA));
712   int max_y = int(y2 + (1 - DELTA));
713
714   CollisionHit temphit;
715   for(int x = starttilex; x*32 < max_x; ++x) {
716     for(int y = starttiley; y*32 < max_y; ++y) {
717       const Tile* tile = solids->get_tile(x, y);
718       if(!tile)
719         continue;
720       // skip non-solid tiles
721       if(tile->getAttributes() == 0)
722         continue;
723       // only handle unisolid when the player is falling down and when he was
724       // above the tile before
725       if(tile->getAttributes() & Tile::UNISOLID) {
726         if(movement.y < 0 || dest.get_top() - movement.y > y*32)
727           continue;
728       }
729
730       if(tile->getAttributes() & Tile::SLOPE) { // slope tile
731         AATriangle triangle;
732         Vector p1(x*32, y*32);
733         Vector p2((x+1)*32, (y+1)*32);
734         triangle = AATriangle(p1, p2, tile->getData());
735
736         if(Collision::rectangle_aatriangle(temphit, dest, movement,
737               triangle)) {
738           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
739             hit = temphit;
740           }
741         }
742       } else { // normal rectangular tile
743         Rect rect(x*32, y*32, (x+1)*32, (y+1)*32);
744         if(Collision::rectangle_rectangle(temphit, dest, movement, rect)) {
745           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
746             hit = temphit;
747           }
748         }
749       }
750     }
751   }
752 }
753
754 uint32_t
755 Sector::collision_tile_attributes(const Rect& dest) const
756 {
757   /** XXX This function doesn't work correctly as it will check all tiles
758    * in the bounding box of the object movement, this might include tiles
759    * that have actually never been touched by the object
760    * (though this only occures for very fast objects...)
761    */
762  
763 #if 0
764   // calculate rectangle where the object will move
765   float x1, x2;
766   if(object->get_movement().x >= 0) {
767     x1 = object->get_bbox().p1.x;
768     x2 = object->get_bbox().p2.x + object->get_movement().x;
769   } else {
770     x1 = object->get_bbox().p1.x + object->get_movement().x;
771     x2 = object->get_bbox().p2.x;
772   }
773   float y1, y2;
774   if(object->get_movement().y >= 0) {
775     y1 = object->get_bbox().p1.y;
776     y2 = object->get_bbox().p2.y + object->get_movement().y;
777   } else {
778     y1 = object->get_bbox().p1.y + object->get_movement().y;
779     y2 = object->get_bbox().p2.y;
780   }
781 #endif
782   float x1 = dest.p1.x;
783   float y1 = dest.p1.y;
784   float x2 = dest.p2.x;
785   float y2 = dest.p2.y;
786
787   // test with all tiles in this rectangle
788   int starttilex = int(x1) / 32;
789   int starttiley = int(y1) / 32;
790   int max_x = int(x2);
791   int max_y = int(y2);
792
793   uint32_t result = 0;
794   for(int x = starttilex; x*32 < max_x; ++x) {
795     for(int y = starttiley; y*32 < max_y; ++y) {
796       const Tile* tile = solids->get_tile(x, y);
797       if(!tile)
798         continue;
799       result |= tile->getAttributes();
800     }
801   }
802
803   return result;
804 }
805
806 void
807 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
808 {
809   CollisionHit hit;
810
811   Vector movement = object1->get_movement() - object2->get_movement();
812   if(Collision::rectangle_rectangle(hit, object1->dest, movement, object2->dest)) {
813     HitResponse response1 = object1->collision(*object2, hit);
814     hit.normal *= -1;
815     HitResponse response2 = object2->collision(*object1, hit);
816
817     if(response1 != CONTINUE) {
818       if(response1 == ABORT_MOVE)
819         object1->dest = object1->get_bbox();
820       if(response2 == CONTINUE)
821         object2->dest.move(hit.normal * (hit.depth + DELTA));
822     } else if(response2 != CONTINUE) {
823       if(response2 == ABORT_MOVE)
824         object2->dest = object2->get_bbox();
825       if(response1 == CONTINUE)
826         object1->dest.move(-hit.normal * (hit.depth + DELTA));
827     } else {
828       object1->dest.move(-hit.normal * (hit.depth/2 + DELTA));
829       object2->dest.move(hit.normal * (hit.depth/2 + DELTA));
830     }
831   }
832 }
833
834 bool
835 Sector::collision_static(MovingObject* object, const Vector& movement)
836 {
837   GameObject* collided_with = solids;
838   CollisionHit hit;
839   hit.time = -1;
840
841   collision_tilemap(object->dest, movement, hit);
842
843   // collision with other (static) objects
844   CollisionHit temphit;
845   for(MovingObjects::iterator i2 = moving_objects.begin();
846       i2 != moving_objects.end(); ++i2) {
847     MovingObject* moving_object_2 = *i2;
848     if(moving_object_2->get_group() != COLGROUP_STATIC
849         || !moving_object_2->is_valid())
850       continue;
851         
852     Rect dest = moving_object_2->dest;
853
854     Vector rel_movement 
855       = movement - moving_object_2->get_movement();
856
857     if(Collision::rectangle_rectangle(temphit, object->dest, rel_movement, dest)
858         && temphit.time > hit.time) {
859       hit = temphit;
860       collided_with = moving_object_2;
861     }
862   }
863
864   if(hit.time < 0)
865     return true;
866
867   HitResponse response = object->collision(*collided_with, hit);
868   hit.normal *= -1;
869   if(collided_with != solids) {
870     MovingObject* moving_object = (MovingObject*) collided_with;
871     HitResponse other_response = moving_object->collision(*object, hit);
872     if(other_response == ABORT_MOVE) {
873       moving_object->dest = moving_object->get_bbox();
874     } else if(other_response == FORCE_MOVE) {
875       // the static object "wins" move tux out of the collision
876       object->dest.move(-hit.normal * (hit.depth + DELTA));
877       return false;
878     } else if(other_response == PASS_MOVEMENT) {
879       object->dest.move(moving_object->get_movement());
880       //object->movement += moving_object->get_movement();
881     }
882   }
883
884   if(response == CONTINUE) {
885     object->dest.move(-hit.normal * (hit.depth + DELTA));
886     return false;
887   } else if(response == ABORT_MOVE) {
888     object->dest = object->get_bbox();
889     return true;
890   }
891   
892   // force move
893   return false;
894 }
895
896 void
897 Sector::handle_collisions()
898 {
899   // calculate destination positions of the objects
900   for(MovingObjects::iterator i = moving_objects.begin();
901       i != moving_objects.end(); ++i) {
902     MovingObject* moving_object = *i;
903
904     moving_object->dest = moving_object->get_bbox();
905     moving_object->dest.move(moving_object->get_movement());
906   }
907     
908   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
909   //   we do this up to 4 times and have to sort all results for the smallest
910   //   one before we can continue here
911   for(MovingObjects::iterator i = moving_objects.begin();
912       i != moving_objects.end(); ++i) {
913     MovingObject* moving_object = *i;
914     if((moving_object->get_group() != COLGROUP_MOVING
915           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
916         || !moving_object->is_valid())
917       continue;
918
919     Vector movement = moving_object->get_movement();
920
921     // test if x or y movement is dominant
922     if(fabsf(moving_object->get_movement().x) < fabsf(moving_object->get_movement().y)) {
923
924       // test in x direction first, then y direction
925       moving_object->dest.move(Vector(0, -movement.y));
926       for(int i = 0; i < 2; ++i) {
927         bool res = collision_static(moving_object, Vector(movement.x, 0));
928         if(res)
929           break;
930       }
931       moving_object->dest.move(Vector(0, movement.y));
932       for(int i = 0; i < 2; ++i) {
933         bool res = collision_static(moving_object, Vector(0, movement.y));
934         if(res)
935           break;
936       }
937       
938     } else {
939
940       // test in y direction first, then x direction
941       moving_object->dest.move(Vector(-movement.x, 0));
942       for(int i = 0; i < 2; ++i) {
943         bool res = collision_static(moving_object, Vector(0, movement.y));
944         if(res)
945           break;
946       }
947       moving_object->dest.move(Vector(movement.x, 0)); 
948       for(int i = 0; i < 2; ++i) {
949         bool res = collision_static(moving_object, Vector(movement.x, 0));
950         if(res)
951           break;
952       }
953     }
954   }
955
956   // part2: COLGROUP_MOVING vs tile attributes
957   for(MovingObjects::iterator i = moving_objects.begin();
958       i != moving_objects.end(); ++i) {
959     MovingObject* moving_object = *i;
960     if((moving_object->get_group() != COLGROUP_MOVING
961           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
962         || !moving_object->is_valid())
963       continue;
964
965     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
966     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
967       moving_object->collision_tile(tile_attributes);
968     }
969   }
970
971   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
972   for(MovingObjects::iterator i = moving_objects.begin();
973       i != moving_objects.end(); ++i) {
974     MovingObject* moving_object = *i;
975     if(moving_object->get_group() != COLGROUP_MOVING
976         || !moving_object->is_valid())
977       continue;
978
979     for(MovingObjects::iterator i2 = moving_objects.begin();
980         i2 != moving_objects.end(); ++i2) {
981       MovingObject* moving_object_2 = *i2;
982       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
983          || !moving_object_2->is_valid())
984         continue;
985
986       collision_object(moving_object, moving_object_2);
987     } 
988   }
989
990   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
991   for(MovingObjects::iterator i = moving_objects.begin();
992       i != moving_objects.end(); ++i) {
993     MovingObject* moving_object = *i;
994
995     if(moving_object->get_group() != COLGROUP_MOVING
996         || !moving_object->is_valid())
997       continue;
998
999     for(MovingObjects::iterator i2 = i+1;
1000         i2 != moving_objects.end(); ++i2) {
1001       MovingObject* moving_object_2 = *i2;
1002       if(moving_object_2->get_group() != COLGROUP_MOVING
1003          || !moving_object_2->is_valid())
1004         continue;
1005
1006       collision_object(moving_object, moving_object_2);
1007     }    
1008   }
1009
1010   // apply object movement
1011   for(MovingObjects::iterator i = moving_objects.begin();
1012       i != moving_objects.end(); ++i) {
1013     MovingObject* moving_object = *i;
1014
1015     moving_object->bbox = moving_object->dest;
1016     moving_object->movement = Vector(0, 0);
1017   }
1018 }
1019
1020 bool
1021 Sector::is_free_space(const Rect& rect) const
1022 {
1023   // test with all tiles in this rectangle
1024   int starttilex = int(rect.p1.x) / 32;
1025   int starttiley = int(rect.p1.y) / 32;
1026   int max_x = int(rect.p2.x);
1027   int max_y = int(rect.p2.y);
1028
1029   for(int x = starttilex; x*32 < max_x; ++x) {
1030     for(int y = starttiley; y*32 < max_y; ++y) {
1031       const Tile* tile = solids->get_tile(x, y);
1032       if(!tile)
1033         continue;
1034       if(tile->getAttributes() & Tile::SOLID)
1035         return false;
1036     }
1037   }
1038
1039   for(MovingObjects::const_iterator i = moving_objects.begin();
1040       i != moving_objects.end(); ++i) {
1041     const MovingObject* moving_object = *i;
1042     if(moving_object->get_group() != COLGROUP_STATIC
1043         || !moving_object->is_valid())
1044       continue;
1045
1046     if(Collision::intersects(rect, moving_object->get_bbox()))
1047       return false;
1048   }
1049
1050   return true;
1051 }
1052
1053 bool
1054 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1055 {
1056   // TODO remove this function and move these checks elsewhere...
1057   static const size_t MAX_FIRE_BULLETS = 2;
1058   static const size_t MAX_ICE_BULLETS = 1;
1059
1060   Bullet* new_bullet = 0;
1061   if(player_status->bonus == FIRE_BONUS) {
1062     if(bullets.size() > MAX_FIRE_BULLETS-1)
1063       return false;
1064     new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
1065   } else if(player_status->bonus == ICE_BONUS) {
1066     if(bullets.size() > MAX_ICE_BULLETS-1)
1067       return false;
1068     new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
1069   } else {
1070     return false;
1071   }
1072   add_object(new_bullet);
1073
1074   sound_manager->play("sounds/shoot.wav");
1075
1076   return true;
1077 }
1078
1079 bool
1080 Sector::add_smoke_cloud(const Vector& pos)
1081 {
1082   add_object(new SmokeCloud(pos));
1083   return true;
1084 }
1085
1086 void
1087 Sector::add_floating_text(const Vector& pos, const std::string& text)
1088 {
1089   add_object(new FloatingText(pos, text));
1090 }
1091
1092 void
1093 Sector::play_music(MusicType type)
1094 {
1095   currentmusic = type;
1096   switch(currentmusic) {
1097     case LEVEL_MUSIC:
1098       sound_manager->play_music(music);
1099       break;
1100     case HERRING_MUSIC:
1101       sound_manager->play_music("music/salcon.ogg");
1102       break;
1103     default:
1104       sound_manager->play_music("");
1105       break;
1106   }
1107 }
1108
1109 MusicType
1110 Sector::get_music_type()
1111 {
1112   return currentmusic;
1113 }
1114
1115 int
1116 Sector::get_total_badguys()
1117 {
1118   int total_badguys = 0;
1119   for(GameObjects::iterator i = gameobjects.begin();
1120       i != gameobjects.end(); ++i) {
1121     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1122     if (badguy && badguy->countMe)
1123       total_badguys++;
1124   }
1125
1126   return total_badguys;
1127 }
1128
1129 bool
1130 Sector::inside(const Rect& rect) const
1131 {
1132   if(rect.p1.x > solids->get_width() * 32 
1133       || rect.p1.y > solids->get_height() * 32
1134       || rect.p2.x < 0 || rect.p2.y < 0)
1135     return false;
1136
1137   return true;
1138 }