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