1df58d4a18da4f709e566b6dbc17ece813c7d5b7
[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
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 "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), gravity(10),
74     player(0), solids(0), camera(0)
75 {
76   add_object(new Player(player_status));
77   add_object(new DisplayEffect());
78   add_object(new TextObject());
79
80 #ifdef USE_GRID
81   grid.reset(new CollisionGrid(32000, 32000));
82 #endif
83
84   // create a new squirrel table for the sector
85   using namespace Scripting;
86
87   sq_collectgarbage(global_vm);
88
89   sq_newtable(global_vm);
90   sq_pushroottable(global_vm);
91   if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
92     throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
93
94   sq_resetobject(&sector_table);
95   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &sector_table)))
96     throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
97   sq_addref(global_vm, &sector_table);
98   sq_pop(global_vm, 1);
99 }
100
101 Sector::~Sector()
102 {
103   using namespace Scripting;
104   
105   deactivate();
106
107   for(ScriptList::iterator i = scripts.begin();
108       i != scripts.end(); ++i) {
109     HSQOBJECT& object = *i;
110     sq_release(global_vm, &object);
111   }
112   sq_release(global_vm, &sector_table);
113   sq_collectgarbage(global_vm);
114  
115   update_game_objects();
116   assert(gameobjects_new.size() == 0);
117
118   for(GameObjects::iterator i = gameobjects.begin();
119       i != gameobjects.end(); ++i) {
120     GameObject* object = *i;
121     before_object_remove(object);
122     object->unref();
123   }
124
125   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
126       ++i)
127     delete *i;
128 }
129
130 Level*
131 Sector::get_level()
132 {
133   return level;
134 }
135
136 GameObject*
137 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
138 {
139   if(name == "camera") {
140     Camera* camera = new Camera(this);
141     camera->parse(reader);
142     return camera;
143   } else if(name == "particles-snow") {
144     SnowParticleSystem* partsys = new SnowParticleSystem();
145     partsys->parse(reader);
146     return partsys;
147   } else if(name == "particles-rain") {
148     RainParticleSystem* partsys = new RainParticleSystem();
149     partsys->parse(reader);
150     return partsys;
151   } else if(name == "particles-comets") {
152     CometParticleSystem* partsys = new CometParticleSystem();
153     partsys->parse(reader);
154     return partsys;
155   } else if(name == "particles-ghosts") {
156     GhostParticleSystem* partsys = new GhostParticleSystem();
157     partsys->parse(reader);
158     return partsys;
159   } else if(name == "particles-clouds") {
160     CloudParticleSystem* partsys = new CloudParticleSystem();
161     partsys->parse(reader);
162     return partsys;
163   } else if(name == "money") { // for compatibility with old maps
164     return new Jumpy(reader);
165   } 
166
167   try {
168     return create_object(name, reader);
169   } catch(std::exception& e) {
170     log_warning << e.what() << "" << std::endl;
171   }
172   
173   return 0;
174 }
175
176 void
177 Sector::parse(const lisp::Lisp& sector)
178 {  
179   lisp::ListIterator iter(&sector);
180   while(iter.next()) {
181     const std::string& token = iter.item();
182     if(token == "name") {
183       iter.value()->get(name);
184     } else if(token == "gravity") {
185       iter.value()->get(gravity);
186     } else if(token == "music") {
187       iter.value()->get(music);
188     } else if(token == "spawnpoint") {
189       SpawnPoint* sp = new SpawnPoint(iter.lisp());
190       spawnpoints.push_back(sp);
191     } else if(token == "init-script") {
192       iter.value()->get(init_script);
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(!solids)
204     throw std::runtime_error("sector does not contain a solid tile layer.");
205
206   fix_old_tiles();
207   if(!camera) {
208     log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
209     update_game_objects();
210     add_object(new Camera(this));
211   }
212
213   update_game_objects();
214 }
215
216 void
217 Sector::parse_old_format(const lisp::Lisp& reader)
218 {
219   name = "main";
220   reader.get("gravity", gravity);
221
222   std::string backgroundimage;
223   reader.get("background", backgroundimage);
224   float bgspeed = .5;
225   reader.get("bkgd_speed", bgspeed);
226   bgspeed /= 100;
227
228   Color bkgd_top, bkgd_bottom;
229   int r = 0, g = 0, b = 128;
230   reader.get("bkgd_red_top", r);
231   reader.get("bkgd_green_top",  g);
232   reader.get("bkgd_blue_top",  b);
233   bkgd_top.red = static_cast<float> (r) / 255.0f;
234   bkgd_top.green = static_cast<float> (g) / 255.0f;
235   bkgd_top.blue = static_cast<float> (b) / 255.0f;
236   
237   reader.get("bkgd_red_bottom",  r);
238   reader.get("bkgd_green_bottom", g);
239   reader.get("bkgd_blue_bottom", b);
240   bkgd_bottom.red = static_cast<float> (r) / 255.0f;
241   bkgd_bottom.green = static_cast<float> (g) / 255.0f;
242   bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
243   
244   if(backgroundimage != "") {
245     Background* background = new Background();
246     background->set_image(
247             std::string("images/background/") + backgroundimage, bgspeed);
248     add_object(background);
249   } else {
250     Gradient* gradient = new Gradient();
251     gradient->set_gradient(bkgd_top, bkgd_bottom);
252     add_object(gradient);
253   }
254
255   std::string particlesystem;
256   reader.get("particle_system", particlesystem);
257   if(particlesystem == "clouds")
258     add_object(new CloudParticleSystem());
259   else if(particlesystem == "snow")
260     add_object(new SnowParticleSystem());
261   else if(particlesystem == "rain")
262     add_object(new RainParticleSystem());
263
264   Vector startpos(100, 170);
265   reader.get("start_pos_x", startpos.x);
266   reader.get("start_pos_y", startpos.y);
267
268   SpawnPoint* spawn = new SpawnPoint;
269   spawn->pos = startpos;
270   spawn->name = "main";
271   spawnpoints.push_back(spawn);
272
273   music = "chipdisko.ogg";
274   reader.get("music", music);
275   music = "music/" + music;
276
277   int width = 30, height = 15;
278   reader.get("width", width);
279   reader.get("height", height);
280   
281   std::vector<unsigned int> tiles;
282   if(reader.get_vector("interactive-tm", tiles)
283       || reader.get_vector("tilemap", tiles)) {
284     TileMap* tilemap = new TileMap();
285     tilemap->set(width, height, tiles, LAYER_TILES, true);
286     add_object(tilemap);
287   }
288
289   if(reader.get_vector("background-tm", tiles)) {
290     TileMap* tilemap = new TileMap();
291     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
292     add_object(tilemap);
293   }
294
295   if(reader.get_vector("foreground-tm", tiles)) {
296     TileMap* tilemap = new TileMap();
297     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
298     add_object(tilemap);
299   }
300
301   // read reset-points (now spawn-points)
302   const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
303   if(resetpoints) {
304     lisp::ListIterator iter(resetpoints);
305     while(iter.next()) {
306       if(iter.item() == "point") {
307         Vector sp_pos;
308         if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
309           {
310           SpawnPoint* sp = new SpawnPoint;
311           sp->name = "main";
312           sp->pos = sp_pos;
313           spawnpoints.push_back(sp);
314           }
315       } else {
316         log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
317       }
318     }
319   }
320
321   // read objects
322   const lisp::Lisp* objects = reader.get_lisp("objects");
323   if(objects) {
324     lisp::ListIterator iter(objects);
325     while(iter.next()) {
326       GameObject* object = parse_object(iter.item(), *(iter.lisp()));
327       if(object) {
328         add_object(object);
329       } else {
330         log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
331       }
332     }
333   }
334
335   // add a camera
336   Camera* camera = new Camera(this);
337   add_object(camera);
338
339   update_game_objects();
340
341   if(solids == 0)
342     throw std::runtime_error("sector does not contain a solid tile layer.");
343
344   fix_old_tiles();
345   update_game_objects();
346 }
347
348 void
349 Sector::fix_old_tiles()
350 {
351   // hack for now...
352   for(size_t x=0; x < solids->get_width(); ++x) {
353     for(size_t y=0; y < solids->get_height(); ++y) {
354       const Tile* tile = solids->get_tile(x, y);
355       Vector pos(x*32, y*32);
356       
357       if(tile->getID() == 112) {
358         add_object(new InvisibleBlock(pos));
359         solids->change(x, y, 0);
360       } else if(tile->getAttributes() & Tile::COIN) {
361         add_object(new Coin(pos));
362         solids->change(x, y, 0);
363       } else if(tile->getAttributes() & Tile::FULLBOX) {
364         add_object(new BonusBlock(pos, tile->getData()));
365         solids->change(x, y, 0);
366       } else if(tile->getAttributes() & Tile::BRICK) {
367         add_object(new Brick(pos, tile->getData()));
368         solids->change(x, y, 0);
369       } else if(tile->getAttributes() & Tile::GOAL) {
370         std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
371         add_object(new SequenceTrigger(pos, sequence));
372         solids->change(x, y, 0);
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 #if 0
559   CollisionGridIterator iter(*grid, get_active_region());
560   while(MovingObject* object = iter.next()) {
561     if(!object->is_valid())
562       continue;
563
564     object->update(elapsed_time);
565   }
566 #else
567   /* update objects */
568   for(GameObjects::iterator i = gameobjects.begin();
569           i != gameobjects.end(); ++i) {
570     GameObject* object = *i;
571     if(!object->is_valid())
572       continue;
573     
574     object->update(elapsed_time);
575   }
576 #endif
577   
578   /* Handle all possible collisions. */
579   handle_collisions();
580   update_game_objects();
581 }
582
583 void
584 Sector::update_game_objects()
585 {
586   /** cleanup marked objects */
587   for(std::vector<Bullet*>::iterator i = bullets.begin();
588       i != bullets.end(); /* nothing */) {
589     Bullet* bullet = *i;
590     if(bullet->is_valid()) {
591       ++i;
592       continue;
593     }
594
595     i = bullets.erase(i);
596   }
597   for(MovingObjects::iterator i = moving_objects.begin();
598       i != moving_objects.end(); /* nothing */) {
599     MovingObject* moving_object = *i;
600     if(moving_object->is_valid()) {
601       ++i;
602       continue;
603     }
604
605 #ifdef USE_GRID
606     grid->remove_object(moving_object);
607 #endif
608     
609     i = moving_objects.erase(i);
610   }
611   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
612       i != gameobjects.end(); /* nothing */) {
613     GameObject* object = *i;
614     
615     if(object->is_valid()) {
616       ++i;
617       continue;
618     }
619
620     before_object_remove(object);
621     
622     object->unref();
623     i = gameobjects.erase(i);
624   }
625
626   /* add newly created objects */
627   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
628       i != gameobjects_new.end(); ++i)
629   {
630     GameObject* object = *i;
631
632     before_object_add(object);
633     
634     gameobjects.push_back(object);
635   }
636   gameobjects_new.clear();
637 }
638
639 bool
640 Sector::before_object_add(GameObject* object)
641 {
642   Bullet* bullet = dynamic_cast<Bullet*> (object);
643   if(bullet)
644     bullets.push_back(bullet);
645
646   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
647   if(movingobject) {
648     moving_objects.push_back(movingobject);
649 #ifdef USE_GRID
650     grid->add_object(movingobject);
651 #endif
652   }
653   
654   TileMap* tilemap = dynamic_cast<TileMap*> (object);
655   if(tilemap && tilemap->is_solid()) {
656     if(solids == 0) {
657       solids = tilemap;
658     } else {
659       log_warning << "Another solid tilemaps added. Ignoring" << std::endl;
660     }
661   }
662
663   Camera* camera = dynamic_cast<Camera*> (object);
664   if(camera) {
665     if(this->camera != 0) {
666       log_warning << "Multiple cameras added. Ignoring" << std::endl;
667       return false;
668     }
669     this->camera = camera;
670   }
671
672   Player* player = dynamic_cast<Player*> (object);
673   if(player) {
674     if(this->player != 0) {
675       log_warning << "Multiple players added. Ignoring" << std::endl;
676       return false;
677     }
678     this->player = player;
679   }
680
681   if(_current == this) {
682     try_expose(object);
683   }
684   
685   return true;
686 }
687
688 void
689 Sector::try_expose(GameObject* object)
690 {
691   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
692   if(interface != NULL) {
693     HSQUIRRELVM vm = Scripting::global_vm;
694     sq_pushobject(vm, sector_table);
695     interface->expose(vm, -1);
696     sq_pop(vm, 1);
697   }
698 }
699
700 void
701 Sector::before_object_remove(GameObject* object)
702 {
703   if(_current == this)
704     try_unexpose(object);
705 }
706
707 void
708 Sector::try_unexpose(GameObject* object)
709 {
710   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
711   if(interface != NULL) {
712     HSQUIRRELVM vm = Scripting::global_vm;
713     SQInteger oldtop = sq_gettop(vm);
714     sq_pushobject(vm, sector_table);
715     try {
716       interface->unexpose(vm, -1);
717     } catch(std::exception& e) {
718       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
719     }
720     sq_settop(vm, oldtop);
721   }
722
723
724 void
725 Sector::draw(DrawingContext& context)
726 {
727   context.push_transform();
728   context.set_translation(camera->get_translation());
729
730   for(GameObjects::iterator i = gameobjects.begin();
731       i != gameobjects.end(); ++i) {
732     GameObject* object = *i; 
733     if(!object->is_valid())
734       continue;
735
736     if (draw_solids_only)
737     {
738       TileMap* tm = dynamic_cast<TileMap*>(object);
739       if (tm && !tm->is_solid())
740         continue;
741     }
742
743     object->draw(context);
744   }
745
746   if(show_collrects) {
747     Color col(0.2, 0.2, 0.2, 0.7);
748     for(MovingObjects::iterator i = moving_objects.begin();
749             i != moving_objects.end(); ++i) {
750       MovingObject* object = *i;
751       const Rect& rect = object->get_bbox();
752
753       context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
754     }
755   }
756
757   context.pop_transform();
758 }
759
760 static const float DELTA = .001;
761
762 void
763 Sector::collision_tilemap(const Rect& dest, const Vector& movement,
764                           CollisionHit& hit) const
765 {
766   // calculate rectangle where the object will move
767   float x1 = dest.get_left();
768   float x2 = dest.get_right();
769   float y1 = dest.get_top();
770   float y2 = dest.get_bottom();
771
772   // test with all tiles in this rectangle
773   int starttilex = int(x1) / 32;
774   int starttiley = int(y1) / 32;
775   int max_x = int(x2 + (1 - DELTA));
776   int max_y = int(y2 + (1 - DELTA));
777
778   CollisionHit temphit;
779   for(int x = starttilex; x*32 < max_x; ++x) {
780     for(int y = starttiley; y*32 < max_y; ++y) {
781       const Tile* tile = solids->get_tile(x, y);
782       if(!tile)
783         continue;
784       // skip non-solid tiles
785       if(tile->getAttributes() == 0)
786         continue;
787       // only handle unisolid when the player is falling down and when he was
788       // above the tile before
789       if(tile->getAttributes() & Tile::UNISOLID) {
790         if(movement.y < 0 || dest.get_top() - movement.y > y*32)
791           continue;
792       }
793
794       if(tile->getAttributes() & Tile::SLOPE) { // slope tile
795         AATriangle triangle;
796         Vector p1(x*32, y*32);
797         Vector p2((x+1)*32, (y+1)*32);
798         triangle = AATriangle(p1, p2, tile->getData());
799
800         if(Collision::rectangle_aatriangle(temphit, dest, movement,
801               triangle)) {
802           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
803             hit = temphit;
804           }
805         }
806       } else { // normal rectangular tile
807         Rect rect(x*32, y*32, (x+1)*32, (y+1)*32);
808         if(Collision::rectangle_rectangle(temphit, dest, movement, rect)) {
809           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
810             hit = temphit;
811           }
812         }
813       }
814     }
815   }
816 }
817
818 uint32_t
819 Sector::collision_tile_attributes(const Rect& dest) const
820 {
821   /** XXX This function doesn't work correctly as it will check all tiles
822    * in the bounding box of the object movement, this might include tiles
823    * that have actually never been touched by the object
824    * (though this only occures for very fast objects...)
825    */
826  
827 #if 0
828   // calculate rectangle where the object will move
829   float x1, x2;
830   if(object->get_movement().x >= 0) {
831     x1 = object->get_bbox().p1.x;
832     x2 = object->get_bbox().p2.x + object->get_movement().x;
833   } else {
834     x1 = object->get_bbox().p1.x + object->get_movement().x;
835     x2 = object->get_bbox().p2.x;
836   }
837   float y1, y2;
838   if(object->get_movement().y >= 0) {
839     y1 = object->get_bbox().p1.y;
840     y2 = object->get_bbox().p2.y + object->get_movement().y;
841   } else {
842     y1 = object->get_bbox().p1.y + object->get_movement().y;
843     y2 = object->get_bbox().p2.y;
844   }
845 #endif
846   float x1 = dest.p1.x;
847   float y1 = dest.p1.y;
848   float x2 = dest.p2.x;
849   float y2 = dest.p2.y;
850
851   // test with all tiles in this rectangle
852   int starttilex = int(x1) / 32;
853   int starttiley = int(y1) / 32;
854   int max_x = int(x2);
855   int max_y = int(y2);
856
857   uint32_t result = 0;
858   for(int x = starttilex; x*32 < max_x; ++x) {
859     for(int y = starttiley; y*32 < max_y; ++y) {
860       const Tile* tile = solids->get_tile(x, y);
861       if(!tile)
862         continue;
863       result |= tile->getAttributes();
864     }
865   }
866
867   return result;
868 }
869
870 void
871 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
872 {
873   CollisionHit hit;
874
875   Vector movement = object1->get_movement() - object2->get_movement();
876   if(Collision::rectangle_rectangle(hit, object1->dest, movement, object2->dest)) {
877     HitResponse response1 = object1->collision(*object2, hit);
878     hit.normal *= -1;
879     HitResponse response2 = object2->collision(*object1, hit);
880
881     if(response1 != CONTINUE) {
882       if(response1 == ABORT_MOVE)
883         object1->dest = object1->get_bbox();
884       if(response2 == CONTINUE)
885         object2->dest.move(hit.normal * (hit.depth + DELTA));
886     } else if(response2 != CONTINUE) {
887       if(response2 == ABORT_MOVE)
888         object2->dest = object2->get_bbox();
889       if(response1 == CONTINUE)
890         object1->dest.move(-hit.normal * (hit.depth + DELTA));
891     } else {
892       object1->dest.move(-hit.normal * (hit.depth/2 + DELTA));
893       object2->dest.move(hit.normal * (hit.depth/2 + DELTA));
894     }
895   }
896 }
897
898 bool
899 Sector::collision_static(MovingObject* object, const Vector& movement)
900 {
901   GameObject* collided_with = solids;
902   CollisionHit hit;
903   hit.time = -1;
904
905   collision_tilemap(object->dest, movement, hit);
906
907   // collision with other (static) objects
908   CollisionHit temphit;
909   for(MovingObjects::iterator i2 = moving_objects.begin();
910       i2 != moving_objects.end(); ++i2) {
911     MovingObject* moving_object_2 = *i2;
912     if(moving_object_2->get_group() != COLGROUP_STATIC
913         || !moving_object_2->is_valid())
914       continue;
915         
916     Rect dest = moving_object_2->dest;
917
918     Vector rel_movement 
919       = movement - moving_object_2->get_movement();
920
921     if(Collision::rectangle_rectangle(temphit, object->dest, rel_movement, dest)
922         && temphit.time > hit.time) {
923       hit = temphit;
924       collided_with = moving_object_2;
925     }
926   }
927
928   if(hit.time < 0)
929     return true;
930
931   HitResponse response = object->collision(*collided_with, hit);
932   hit.normal *= -1;
933   if(collided_with != solids) {
934     MovingObject* moving_object = (MovingObject*) collided_with;
935     HitResponse other_response = moving_object->collision(*object, hit);
936     if(other_response == ABORT_MOVE) {
937       moving_object->dest = moving_object->get_bbox();
938     } else if(other_response == FORCE_MOVE) {
939       // the static object "wins" move tux out of the collision
940       object->dest.move(-hit.normal * (hit.depth + DELTA));
941       return false;
942     } else if(other_response == PASS_MOVEMENT) {
943       object->dest.move(moving_object->get_movement());
944       //object->movement += moving_object->get_movement();
945     }
946   }
947
948   if(response == CONTINUE) {
949     object->dest.move(-hit.normal * (hit.depth + DELTA));
950     return false;
951   } else if(response == ABORT_MOVE) {
952     object->dest = object->get_bbox();
953     return true;
954   }
955   
956   // force move
957   return false;
958 }
959
960 void
961 Sector::handle_collisions()
962 {
963   // calculate destination positions of the objects
964   for(MovingObjects::iterator i = moving_objects.begin();
965       i != moving_objects.end(); ++i) {
966     MovingObject* moving_object = *i;
967
968     moving_object->dest = moving_object->get_bbox();
969     moving_object->dest.move(moving_object->get_movement());
970   }
971     
972   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
973   //   we do this up to 4 times and have to sort all results for the smallest
974   //   one before we can continue here
975   for(MovingObjects::iterator i = moving_objects.begin();
976       i != moving_objects.end(); ++i) {
977     MovingObject* moving_object = *i;
978     if((moving_object->get_group() != COLGROUP_MOVING
979           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
980         || !moving_object->is_valid())
981       continue;
982
983     Vector movement = moving_object->get_movement();
984
985     // test if x or y movement is dominant
986     if(fabsf(moving_object->get_movement().x) < fabsf(moving_object->get_movement().y)) {
987
988       // test in x direction first, then y direction
989       moving_object->dest.move(Vector(0, -movement.y));
990       for(int i = 0; i < 2; ++i) {
991         bool res = collision_static(moving_object, Vector(movement.x, 0));
992         if(res)
993           break;
994       }
995       moving_object->dest.move(Vector(0, movement.y));
996       for(int i = 0; i < 2; ++i) {
997         bool res = collision_static(moving_object, Vector(0, movement.y));
998         if(res)
999           break;
1000       }
1001       
1002     } else {
1003
1004       // test in y direction first, then x direction
1005       moving_object->dest.move(Vector(-movement.x, 0));
1006       for(int i = 0; i < 2; ++i) {
1007         bool res = collision_static(moving_object, Vector(0, movement.y));
1008         if(res)
1009           break;
1010       }
1011       moving_object->dest.move(Vector(movement.x, 0)); 
1012       for(int i = 0; i < 2; ++i) {
1013         bool res = collision_static(moving_object, Vector(movement.x, 0));
1014         if(res)
1015           break;
1016       }
1017     }
1018   }
1019
1020   // part2: COLGROUP_MOVING vs tile attributes
1021   for(MovingObjects::iterator i = moving_objects.begin();
1022       i != moving_objects.end(); ++i) {
1023     MovingObject* moving_object = *i;
1024     if((moving_object->get_group() != COLGROUP_MOVING
1025           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1026         || !moving_object->is_valid())
1027       continue;
1028
1029     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1030     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1031       moving_object->collision_tile(tile_attributes);
1032     }
1033   }
1034
1035   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1036   for(MovingObjects::iterator i = moving_objects.begin();
1037       i != moving_objects.end(); ++i) {
1038     MovingObject* moving_object = *i;
1039     if(moving_object->get_group() != COLGROUP_MOVING
1040         || !moving_object->is_valid())
1041       continue;
1042
1043     for(MovingObjects::iterator i2 = moving_objects.begin();
1044         i2 != moving_objects.end(); ++i2) {
1045       MovingObject* moving_object_2 = *i2;
1046       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1047          || !moving_object_2->is_valid())
1048         continue;
1049
1050       collision_object(moving_object, moving_object_2);
1051     } 
1052   }
1053
1054   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1055   for(MovingObjects::iterator i = moving_objects.begin();
1056       i != moving_objects.end(); ++i) {
1057     MovingObject* moving_object = *i;
1058
1059     if(moving_object->get_group() != COLGROUP_MOVING
1060         || !moving_object->is_valid())
1061       continue;
1062
1063     for(MovingObjects::iterator i2 = i+1;
1064         i2 != moving_objects.end(); ++i2) {
1065       MovingObject* moving_object_2 = *i2;
1066       if(moving_object_2->get_group() != COLGROUP_MOVING
1067          || !moving_object_2->is_valid())
1068         continue;
1069
1070       collision_object(moving_object, moving_object_2);
1071     }    
1072   }
1073
1074   // apply object movement
1075   for(MovingObjects::iterator i = moving_objects.begin();
1076       i != moving_objects.end(); ++i) {
1077     MovingObject* moving_object = *i;
1078
1079     moving_object->bbox = moving_object->dest;
1080     moving_object->movement = Vector(0, 0);
1081   }
1082 }
1083
1084 bool
1085 Sector::is_free_space(const Rect& rect) const
1086 {
1087   // test with all tiles in this rectangle
1088   int starttilex = int(rect.p1.x) / 32;
1089   int starttiley = int(rect.p1.y) / 32;
1090   int max_x = int(rect.p2.x);
1091   int max_y = int(rect.p2.y);
1092
1093   for(int x = starttilex; x*32 <= max_x; ++x) {
1094     for(int y = starttiley; y*32 <= max_y; ++y) {
1095       const Tile* tile = solids->get_tile(x, y);
1096       if(!tile)
1097         continue;
1098       if(tile->getAttributes() & Tile::SOLID)
1099         return false;
1100     }
1101   }
1102
1103   for(MovingObjects::const_iterator i = moving_objects.begin();
1104       i != moving_objects.end(); ++i) {
1105     const MovingObject* moving_object = *i;
1106     if(moving_object->get_group() != COLGROUP_STATIC
1107         || !moving_object->is_valid())
1108       continue;
1109
1110     if(Collision::intersects(rect, moving_object->get_bbox()))
1111       return false;
1112   }
1113
1114   return true;
1115 }
1116
1117 bool
1118 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1119 {
1120   // TODO remove this function and move these checks elsewhere...
1121
1122   Bullet* new_bullet = 0;
1123   if(player_status->bonus == FIRE_BONUS) {
1124     if((int)bullets.size() >= player_status->max_fire_bullets)
1125       return false;
1126     new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
1127   } else if(player_status->bonus == ICE_BONUS) {
1128     if((int)bullets.size() >= player_status->max_ice_bullets)
1129       return false;
1130     new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
1131   } else {
1132     return false;
1133   }
1134   add_object(new_bullet);
1135
1136   sound_manager->play("sounds/shoot.wav");
1137
1138   return true;
1139 }
1140
1141 bool
1142 Sector::add_smoke_cloud(const Vector& pos)
1143 {
1144   add_object(new SmokeCloud(pos));
1145   return true;
1146 }
1147
1148 void
1149 Sector::add_floating_text(const Vector& pos, const std::string& text)
1150 {
1151   add_object(new FloatingText(pos, text));
1152 }
1153
1154 void
1155 Sector::play_music(MusicType type)
1156 {
1157   currentmusic = type;
1158   switch(currentmusic) {
1159     case LEVEL_MUSIC:
1160       sound_manager->play_music(music);
1161       break;
1162     case HERRING_MUSIC:
1163       sound_manager->play_music("music/salcon.ogg");
1164       break;
1165     case HERRING_WARNING_MUSIC:
1166       sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1167       break;
1168     default:
1169       sound_manager->play_music("");
1170       break;
1171   }
1172 }
1173
1174 MusicType
1175 Sector::get_music_type()
1176 {
1177   return currentmusic;
1178 }
1179
1180 int
1181 Sector::get_total_badguys()
1182 {
1183   int total_badguys = 0;
1184   for(GameObjects::iterator i = gameobjects.begin();
1185       i != gameobjects.end(); ++i) {
1186     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1187     if (badguy && badguy->countMe)
1188       total_badguys++;
1189   }
1190
1191   return total_badguys;
1192 }
1193
1194 bool
1195 Sector::inside(const Rect& rect) const
1196 {
1197   if(rect.p1.x > solids->get_width() * 32 
1198       || rect.p1.y > solids->get_height() * 32
1199       || rect.p2.x < 0)
1200     return false;
1201
1202   return true;
1203 }