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