replaced INFINITY macro with query to numeric_limits
[supertux.git] / src / sector.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <memory>
22 #include <algorithm>
23 #include <stdexcept>
24 #include <iostream>
25 #include <fstream>
26 #include <sstream>
27 #include <stdexcept>
28 #include <float.h>
29 #include <math.h>
30 #include <limits>
31
32 #include "sector.hpp"
33 #include "object/player.hpp"
34 #include "object/gameobjs.hpp"
35 #include "object/camera.hpp"
36 #include "object/background.hpp"
37 #include "object/gradient.hpp"
38 #include "object/particlesystem.hpp"
39 #include "object/particlesystem_interactive.hpp"
40 #include "object/tilemap.hpp"
41 #include "lisp/parser.hpp"
42 #include "lisp/lisp.hpp"
43 #include "lisp/writer.hpp"
44 #include "lisp/list_iterator.hpp"
45 #include "tile.hpp"
46 #include "audio/sound_manager.hpp"
47 #include "game_session.hpp"
48 #include "resources.hpp"
49 #include "statistics.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 "object/portable.hpp"
61 #include "badguy/jumpy.hpp"
62 #include "trigger/sequence_trigger.hpp"
63 #include "player_status.hpp"
64 #include "scripting/squirrel_util.hpp"
65 #include "script_interface.hpp"
66 #include "log.hpp"
67
68 Sector* Sector::_current = 0;
69
70 bool Sector::show_collrects = false;
71 bool Sector::draw_solids_only = false;
72
73 Sector::Sector(Level* parent)
74   : level(parent), currentmusic(LEVEL_MUSIC),
75   ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10), player(0), camera(0) 
76 {
77   add_object(new Player(player_status, "Tux"));
78   add_object(new DisplayEffect("Effect"));
79   add_object(new TextObject("Text"));
80
81   // create a new squirrel table for the sector
82   using namespace Scripting;
83
84   sq_collectgarbage(global_vm);
85
86   sq_newtable(global_vm);
87   sq_pushroottable(global_vm);
88   if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
89     throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
90
91   sq_resetobject(&sector_table);
92   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &sector_table)))
93     throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
94   sq_addref(global_vm, &sector_table);
95   sq_pop(global_vm, 1);
96 }
97
98 Sector::~Sector()
99 {
100   using namespace Scripting;
101
102   deactivate();
103
104   for(ScriptList::iterator i = scripts.begin();
105       i != scripts.end(); ++i) {
106     HSQOBJECT& object = *i;
107     sq_release(global_vm, &object);
108   }
109   sq_release(global_vm, &sector_table);
110   sq_collectgarbage(global_vm);
111
112   update_game_objects();
113   assert(gameobjects_new.size() == 0);
114
115   for(GameObjects::iterator i = gameobjects.begin();
116       i != gameobjects.end(); ++i) {
117     GameObject* object = *i;
118     before_object_remove(object);
119     object->unref();
120   }
121
122   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
123       ++i)
124     delete *i;
125 }
126
127 Level*
128 Sector::get_level()
129 {
130   return level;
131 }
132
133 GameObject*
134 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
135 {
136   if(name == "camera") {
137     Camera* camera = new Camera(this, "Camera");
138     camera->parse(reader);
139     return camera;
140   } else if(name == "particles-snow") {
141     SnowParticleSystem* partsys = new SnowParticleSystem();
142     partsys->parse(reader);
143     return partsys;
144   } else if(name == "particles-rain") {
145     RainParticleSystem* partsys = new RainParticleSystem();
146     partsys->parse(reader);
147     return partsys;
148   } else if(name == "particles-comets") {
149     CometParticleSystem* partsys = new CometParticleSystem();
150     partsys->parse(reader);
151     return partsys;
152   } else if(name == "particles-ghosts") {
153     GhostParticleSystem* partsys = new GhostParticleSystem();
154     partsys->parse(reader);
155     return partsys;
156   } else if(name == "particles-clouds") {
157     CloudParticleSystem* partsys = new CloudParticleSystem();
158     partsys->parse(reader);
159     return partsys;
160   } else if(name == "money") { // for compatibility with old maps
161     return new Jumpy(reader);
162   }
163
164   try {
165     return create_object(name, reader);
166   } catch(std::exception& e) {
167     log_warning << e.what() << "" << std::endl;
168   }
169
170   return 0;
171 }
172
173 void
174 Sector::parse(const lisp::Lisp& sector)
175 {
176   lisp::ListIterator iter(&sector);
177   while(iter.next()) {
178     const std::string& token = iter.item();
179     if(token == "name") {
180       iter.value()->get(name);
181     } else if(token == "gravity") {
182       iter.value()->get(gravity);
183     } else if(token == "music") {
184       iter.value()->get(music);
185     } else if(token == "spawnpoint") {
186       SpawnPoint* sp = new SpawnPoint(iter.lisp());
187       spawnpoints.push_back(sp);
188     } else if(token == "init-script") {
189       iter.value()->get(init_script);
190     } else if(token == "ambient-light") {
191       std::vector<float> vColor;
192       sector.get_vector( "ambient-light", vColor );
193       if(vColor.size() < 3) {
194         log_warning << "(ambient-light) requires a color as argument" << std::endl;
195       } else {
196         ambient_light = Color( vColor );
197       }
198     } else {
199       GameObject* object = parse_object(token, *(iter.lisp()));
200       if(object) {
201         add_object(object);
202       }
203     }
204   }
205
206   update_game_objects();
207
208   if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
209
210   fix_old_tiles();
211   if(!camera) {
212     log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
213     update_game_objects();
214     add_object(new Camera(this, "Camera"));
215   }
216
217   update_game_objects();
218 }
219
220 void
221 Sector::parse_old_format(const lisp::Lisp& reader)
222 {
223   name = "main";
224   reader.get("gravity", gravity);
225
226   std::string backgroundimage;
227   reader.get("background", backgroundimage);
228   float bgspeed = .5;
229   reader.get("bkgd_speed", bgspeed);
230   bgspeed /= 100;
231
232   Color bkgd_top, bkgd_bottom;
233   int r = 0, g = 0, b = 128;
234   reader.get("bkgd_red_top", r);
235   reader.get("bkgd_green_top",  g);
236   reader.get("bkgd_blue_top",  b);
237   bkgd_top.red = static_cast<float> (r) / 255.0f;
238   bkgd_top.green = static_cast<float> (g) / 255.0f;
239   bkgd_top.blue = static_cast<float> (b) / 255.0f;
240
241   reader.get("bkgd_red_bottom",  r);
242   reader.get("bkgd_green_bottom", g);
243   reader.get("bkgd_blue_bottom", b);
244   bkgd_bottom.red = static_cast<float> (r) / 255.0f;
245   bkgd_bottom.green = static_cast<float> (g) / 255.0f;
246   bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
247
248   if(backgroundimage != "") {
249     Background* background = new Background();
250     background->set_image(
251             std::string("images/background/") + backgroundimage, bgspeed);
252     add_object(background);
253   } else {
254     Gradient* gradient = new Gradient();
255     gradient->set_gradient(bkgd_top, bkgd_bottom);
256     add_object(gradient);
257   }
258
259   std::string particlesystem;
260   reader.get("particle_system", particlesystem);
261   if(particlesystem == "clouds")
262     add_object(new CloudParticleSystem());
263   else if(particlesystem == "snow")
264     add_object(new SnowParticleSystem());
265   else if(particlesystem == "rain")
266     add_object(new RainParticleSystem());
267
268   Vector startpos(100, 170);
269   reader.get("start_pos_x", startpos.x);
270   reader.get("start_pos_y", startpos.y);
271
272   SpawnPoint* spawn = new SpawnPoint;
273   spawn->pos = startpos;
274   spawn->name = "main";
275   spawnpoints.push_back(spawn);
276
277   music = "chipdisko.ogg";
278   reader.get("music", music);
279   music = "music/" + music;
280
281   int width = 30, height = 15;
282   reader.get("width", width);
283   reader.get("height", height);
284
285   std::vector<unsigned int> tiles;
286   if(reader.get_vector("interactive-tm", tiles)
287       || reader.get_vector("tilemap", tiles)) {
288     TileMap* tilemap = new TileMap();
289     tilemap->set(width, height, tiles, LAYER_TILES, true);
290     add_object(tilemap);
291   }
292
293   if(reader.get_vector("background-tm", tiles)) {
294     TileMap* tilemap = new TileMap();
295     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
296     add_object(tilemap);
297   }
298
299   if(reader.get_vector("foreground-tm", tiles)) {
300     TileMap* tilemap = new TileMap();
301     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
302     add_object(tilemap);
303   }
304
305   // read reset-points (now spawn-points)
306   const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
307   if(resetpoints) {
308     lisp::ListIterator iter(resetpoints);
309     while(iter.next()) {
310       if(iter.item() == "point") {
311         Vector sp_pos;
312         if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
313           {
314           SpawnPoint* sp = new SpawnPoint;
315           sp->name = "main";
316           sp->pos = sp_pos;
317           spawnpoints.push_back(sp);
318           }
319       } else {
320         log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
321       }
322     }
323   }
324
325   // read objects
326   const lisp::Lisp* objects = reader.get_lisp("objects");
327   if(objects) {
328     lisp::ListIterator iter(objects);
329     while(iter.next()) {
330       GameObject* object = parse_object(iter.item(), *(iter.lisp()));
331       if(object) {
332         add_object(object);
333       } else {
334         log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
335       }
336     }
337   }
338
339   // add a camera
340   Camera* camera = new Camera(this, "Camera");
341   add_object(camera);
342
343   update_game_objects();
344
345   if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
346
347   fix_old_tiles();
348   update_game_objects();
349 }
350
351 void
352 Sector::fix_old_tiles()
353 {
354   for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
355     TileMap* solids = *i;
356     for(size_t x=0; x < solids->get_width(); ++x) {
357       for(size_t y=0; y < solids->get_height(); ++y) {
358         const Tile* tile = solids->get_tile(x, y);
359         Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
360
361         if(tile->getID() == 112) {
362           add_object(new InvisibleBlock(pos));
363           solids->change(x, y, 0);
364         } else if(tile->getAttributes() & Tile::COIN) {
365           add_object(new Coin(pos));
366           solids->change(x, y, 0);
367         } else if(tile->getAttributes() & Tile::FULLBOX) {
368           add_object(new BonusBlock(pos, tile->getData()));
369           solids->change(x, y, 0);
370         } else if(tile->getAttributes() & Tile::BRICK) {
371           add_object(new Brick(pos, tile->getData()));
372           solids->change(x, y, 0);
373         } else if(tile->getAttributes() & Tile::GOAL) {
374           std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
375           add_object(new SequenceTrigger(pos, sequence));
376           solids->change(x, y, 0);
377         }
378       }
379     }
380   }
381 }
382
383 void
384 Sector::write(lisp::Writer& writer)
385 {
386   writer.write_string("name", name);
387   writer.write_float("gravity", gravity);
388   writer.write_string("music", music);
389
390   // write spawnpoints
391   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
392       ++i) {
393     SpawnPoint* spawn = *i;
394     writer.start_list("spawn-points");
395     writer.write_string("name", spawn->name);
396     writer.write_float("x", spawn->pos.x);
397     writer.write_float("y", spawn->pos.y);
398     writer.end_list("spawn-points");
399   }
400
401   // write objects
402   for(GameObjects::iterator i = gameobjects.begin();
403       i != gameobjects.end(); ++i) {
404     Serializable* serializable = dynamic_cast<Serializable*> (*i);
405     if(serializable)
406       serializable->write(writer);
407   }
408 }
409
410 HSQUIRRELVM
411 Sector::run_script(std::istream& in, const std::string& sourcename)
412 {
413   using namespace Scripting;
414
415   // garbage collect thread list
416   for(ScriptList::iterator i = scripts.begin();
417       i != scripts.end(); ) {
418     HSQOBJECT& object = *i;
419     HSQUIRRELVM vm = object_to_vm(object);
420
421     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
422       sq_release(global_vm, &object);
423       i = scripts.erase(i);
424       continue;
425     }
426
427     ++i;
428   }
429
430   HSQOBJECT object = create_thread(global_vm);
431   scripts.push_back(object);
432
433   HSQUIRRELVM vm = object_to_vm(object);
434
435   // set sector_table as roottable for the thread
436   sq_pushobject(vm, sector_table);
437   sq_setroottable(vm);
438
439   compile_and_run(vm, in, sourcename);
440
441   return vm;
442 }
443
444 void
445 Sector::add_object(GameObject* object)
446 {
447   // make sure the object isn't already in the list
448 #ifdef DEBUG
449   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
450       ++i) {
451     if(*i == object) {
452       assert("object already added to sector" == 0);
453     }
454   }
455   for(GameObjects::iterator i = gameobjects_new.begin();
456       i != gameobjects_new.end(); ++i) {
457     if(*i == object) {
458       assert("object already added to sector" == 0);
459     }
460   }
461 #endif
462
463   object->ref();
464   gameobjects_new.push_back(object);
465 }
466
467 void
468 Sector::activate(const std::string& spawnpoint)
469 {
470   SpawnPoint* sp = 0;
471   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
472       ++i) {
473     if((*i)->name == spawnpoint) {
474       sp = *i;
475       break;
476     }
477   }
478   if(!sp) {
479     log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
480     if(spawnpoint != "main") {
481       activate("main");
482     } else {
483       activate(Vector(0, 0));
484     }
485   } else {
486     activate(sp->pos);
487   }
488 }
489
490 void
491 Sector::activate(const Vector& player_pos)
492 {
493   if(_current != this) {
494     if(_current != NULL)
495       _current->deactivate();
496     _current = this;
497
498     // register sectortable as sector in scripting
499     HSQUIRRELVM vm = Scripting::global_vm;
500     sq_pushroottable(vm);
501     sq_pushstring(vm, "sector", -1);
502     sq_pushobject(vm, sector_table);
503     if(SQ_FAILED(sq_createslot(vm, -3)))
504       throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
505     sq_pop(vm, 1);
506
507     for(GameObjects::iterator i = gameobjects.begin();
508         i != gameobjects.end(); ++i) {
509       GameObject* object = *i;
510
511       try_expose(object);
512     }
513   }
514   try_expose_me();
515
516   player->move(player_pos);
517   camera->reset(player->get_pos());
518   update_game_objects();
519
520   // Run init script
521   if(init_script != "") {
522     std::istringstream in(init_script);
523     run_script(in, std::string("Sector(") + name + ") - init");
524   }
525 }
526
527 void
528 Sector::deactivate()
529 {
530   if(_current != this)
531     return;
532
533   // remove sector entry from global vm
534   HSQUIRRELVM vm = Scripting::global_vm;
535   sq_pushroottable(vm);
536   sq_pushstring(vm, "sector", -1);
537   if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
538     throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
539   sq_pop(vm, 1);
540
541   for(GameObjects::iterator i = gameobjects.begin();
542       i != gameobjects.end(); ++i) {
543     GameObject* object = *i;
544
545     try_unexpose(object);
546   }
547
548   try_unexpose_me();
549   _current = NULL;
550 }
551
552 Rect
553 Sector::get_active_region()
554 {
555   return Rect(
556     camera->get_translation() - Vector(1600, 1200),
557     camera->get_translation() + Vector(1600, 1200));
558 }
559
560 void
561 Sector::update(float elapsed_time)
562 {
563   player->check_bounds(camera);
564
565   /* update objects */
566   for(GameObjects::iterator i = gameobjects.begin();
567           i != gameobjects.end(); ++i) {
568     GameObject* object = *i;
569     if(!object->is_valid())
570       continue;
571
572     object->update(elapsed_time);
573   }
574
575   /* Handle all possible collisions. */
576   handle_collisions();
577   update_game_objects();
578 }
579
580 void
581 Sector::update_game_objects()
582 {
583   /** cleanup marked objects */
584   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
585       i != gameobjects.end(); /* nothing */) {
586     GameObject* object = *i;
587
588     if(object->is_valid()) {
589       ++i;
590       continue;
591     }
592
593     before_object_remove(object);
594
595     object->unref();
596     i = gameobjects.erase(i);
597   }
598
599   /* add newly created objects */
600   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
601       i != gameobjects_new.end(); ++i)
602   {
603     GameObject* object = *i;
604
605     before_object_add(object);
606
607     gameobjects.push_back(object);
608   }
609   gameobjects_new.clear();
610 }
611
612 bool
613 Sector::before_object_add(GameObject* object)
614 {
615   Bullet* bullet = dynamic_cast<Bullet*> (object);
616   if(bullet != NULL) {
617     bullets.push_back(bullet);
618   }
619
620   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
621   if(movingobject != NULL) {
622     moving_objects.push_back(movingobject);
623   }
624
625   Portable* portable = dynamic_cast<Portable*> (object);
626   if(portable != NULL) {
627     portables.push_back(portable);
628   }
629
630   TileMap* tilemap = dynamic_cast<TileMap*> (object);
631   if(tilemap != NULL && tilemap->is_solid()) {
632     solid_tilemaps.push_back(tilemap);
633   }
634
635   Camera* camera = dynamic_cast<Camera*> (object);
636   if(camera != NULL) {
637     if(this->camera != 0) {
638       log_warning << "Multiple cameras added. Ignoring" << std::endl;
639       return false;
640     }
641     this->camera = camera;
642   }
643
644   Player* player = dynamic_cast<Player*> (object);
645   if(player != NULL) {
646     if(this->player != 0) {
647       log_warning << "Multiple players added. Ignoring" << std::endl;
648       return false;
649     }
650     this->player = player;
651   }
652
653   if(_current == this) {
654     try_expose(object);
655   }
656
657   return true;
658 }
659
660 void
661 Sector::try_expose(GameObject* object)
662 {
663   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
664   if(interface != NULL) {
665     HSQUIRRELVM vm = Scripting::global_vm;
666     sq_pushobject(vm, sector_table);
667     interface->expose(vm, -1);
668     sq_pop(vm, 1);
669   }
670 }
671
672 void
673 Sector::try_expose_me()
674 {
675   HSQUIRRELVM vm = Scripting::global_vm;
676   sq_pushobject(vm, sector_table);
677   Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
678   expose_object(vm, -1, interface, "settings", false);
679   sq_pop(vm, 1);
680 }
681
682 void
683 Sector::before_object_remove(GameObject* object)
684 {
685   Portable* portable = dynamic_cast<Portable*> (object);
686   if(portable != NULL) {
687     portables.erase(std::find(portables.begin(), portables.end(), portable));
688   }
689   Bullet* bullet = dynamic_cast<Bullet*> (object);
690   if(bullet != NULL) {
691     bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
692   }
693   MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
694   if(moving_object != NULL) {
695     moving_objects.erase(
696         std::find(moving_objects.begin(), moving_objects.end(), moving_object));
697   }
698           
699   if(_current == this)
700     try_unexpose(object);
701 }
702
703 void
704 Sector::try_unexpose(GameObject* object)
705 {
706   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
707   if(interface != NULL) {
708     HSQUIRRELVM vm = Scripting::global_vm;
709     SQInteger oldtop = sq_gettop(vm);
710     sq_pushobject(vm, sector_table);
711     try {
712       interface->unexpose(vm, -1);
713     } catch(std::exception& e) {
714       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
715     }
716     sq_settop(vm, oldtop);
717   }
718 }
719
720 void
721 Sector::try_unexpose_me()
722 {
723   HSQUIRRELVM vm = Scripting::global_vm;
724   SQInteger oldtop = sq_gettop(vm);
725   sq_pushobject(vm, sector_table);
726   try {
727     Scripting::unexpose_object(vm, -1, "settings");
728   } catch(std::exception& e) {
729     log_warning << "Couldn't unregister object: " << e.what() << std::endl;
730   }
731   sq_settop(vm, oldtop);
732 }
733 void
734 Sector::draw(DrawingContext& context)
735 {
736   context.set_ambient_color( ambient_light );
737   context.push_transform();
738   context.set_translation(camera->get_translation());
739
740   for(GameObjects::iterator i = gameobjects.begin();
741       i != gameobjects.end(); ++i) {
742     GameObject* object = *i;
743     if(!object->is_valid())
744       continue;
745
746     if (draw_solids_only)
747     {
748       TileMap* tm = dynamic_cast<TileMap*>(object);
749       if (tm && !tm->is_solid())
750         continue;
751     }
752
753     object->draw(context);
754   }
755
756   if(show_collrects) {
757     Color col(0.2, 0.2, 0.2, 0.7);
758     for(MovingObjects::iterator i = moving_objects.begin();
759             i != moving_objects.end(); ++i) {
760       MovingObject* object = *i;
761       const Rect& rect = object->get_bbox();
762
763       context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
764     }
765   }
766
767   context.pop_transform();
768 }
769
770 /*-------------------------------------------------------------------------
771  * Collision Detection
772  *-------------------------------------------------------------------------*/
773
774 static const float SHIFT_DELTA = 7.0f;
775
776 /** r1 is supposed to be moving, r2 a solid object */
777 void check_collisions(collision::Constraints* constraints,
778                       const Vector& movement, const Rect& r1, const Rect& r2,
779                       GameObject* object = NULL, MovingObject* other = NULL)
780 {
781   if(!collision::intersects(r1, r2))
782     return;
783
784   // calculate intersection
785   float itop = r1.get_bottom() - r2.get_top();
786   float ibottom = r2.get_bottom() - r1.get_top();
787   float ileft = r1.get_right() - r2.get_left();
788   float iright = r2.get_right() - r1.get_left();
789
790   if(fabsf(movement.y) > fabsf(movement.x)) {
791     if(ileft < SHIFT_DELTA) {
792       constraints->right = std::min(constraints->right, r2.get_left());
793       return;
794     } else if(iright < SHIFT_DELTA) {
795       constraints->left = std::max(constraints->left, r2.get_right());
796       return;
797     }
798   } else {
799     // shiftout bottom/top
800     if(itop < SHIFT_DELTA) {
801       constraints->bottom = std::min(constraints->bottom, r2.get_top());
802       return;
803     } else if(ibottom < SHIFT_DELTA) {
804       constraints->top = std::max(constraints->top, r2.get_bottom());
805       return;
806     }
807   }
808
809   if(other != NULL) {
810     CollisionHit dummy;
811     HitResponse response = other->collision(*object, dummy);
812     if(response == PASSTHROUGH)
813       return;
814     if(other->get_movement() != Vector(0, 0)) {
815       // TODO what todo when we collide with 2 moving objects?!?
816       constraints->ground_movement = other->get_movement();
817     }
818   }
819
820   float vert_penetration = std::min(itop, ibottom);
821   float horiz_penetration = std::min(ileft, iright);
822   if(vert_penetration < horiz_penetration) {
823     if(itop < ibottom) {
824       constraints->bottom = std::min(constraints->bottom, r2.get_top());
825       constraints->hit.bottom = true;
826     } else {
827       constraints->top = std::max(constraints->top, r2.get_bottom());
828       constraints->hit.top = true;
829     }
830   } else {
831     if(ileft < iright) {
832       constraints->right = std::min(constraints->right, r2.get_left());
833       constraints->hit.right = true;
834     } else {
835       constraints->left = std::max(constraints->left, r2.get_right());
836       constraints->hit.left = true;
837     }
838   }
839 }
840
841 static const float DELTA = .001;
842
843 void
844 Sector::collision_tilemap(collision::Constraints* constraints,
845                           const Vector& movement, const Rect& dest) const
846 {
847   // calculate rectangle where the object will move
848   float x1 = dest.get_left();
849   float x2 = dest.get_right();
850   float y1 = dest.get_top();
851   float y2 = dest.get_bottom();
852
853   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
854     TileMap* solids = *i;
855
856     // test with all tiles in this rectangle
857     int starttilex = int(x1 - solids->get_x_offset()) / 32;
858     int starttiley = int(y1 - solids->get_y_offset()) / 32;
859     int max_x = int(x2 - solids->get_x_offset());
860     int max_y = int(y2+1 - solids->get_y_offset());
861
862     for(int x = starttilex; x*32 < max_x; ++x) {
863       for(int y = starttiley; y*32 < max_y; ++y) {
864         const Tile* tile = solids->get_tile(x, y);
865         if(!tile)
866           continue;
867         // skip non-solid tiles
868         if((tile->getAttributes() & Tile::SOLID) == 0)
869           continue;
870         // only handle unisolid when the player is falling down and when he was
871         // above the tile before
872         if(tile->getAttributes() & Tile::UNISOLID) {
873           if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
874             continue;
875         }
876
877         if(tile->getAttributes() & Tile::SLOPE) { // slope tile
878           AATriangle triangle;
879           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
880           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
881           triangle = AATriangle(p1, p2, tile->getData());
882
883           collision::rectangle_aatriangle(constraints, dest, triangle);
884         } else { // normal rectangular tile
885           Rect rect(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset(), (x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
886           check_collisions(constraints, movement, dest, rect);
887         }
888       }
889     }
890   }
891 }
892
893 uint32_t
894 Sector::collision_tile_attributes(const Rect& dest) const
895 {
896   float x1 = dest.p1.x;
897   float y1 = dest.p1.y;
898   float x2 = dest.p2.x;
899   float y2 = dest.p2.y;
900
901   uint32_t result = 0;
902   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
903     TileMap* solids = *i;
904
905     // test with all tiles in this rectangle
906     int starttilex = int(x1 - solids->get_x_offset()) / 32;
907     int starttiley = int(y1 - solids->get_y_offset()) / 32;
908     int max_x = int(x2 - solids->get_x_offset());
909     int max_y = int(y2+1 - solids->get_y_offset());
910
911     for(int x = starttilex; x*32 < max_x; ++x) {
912       for(int y = starttiley; y*32 < max_y; ++y) {
913         const Tile* tile = solids->get_tile(x, y);
914         if(!tile)
915           continue;
916         result |= tile->getAttributes();
917       }
918     }
919   }
920
921   return result;
922 }
923
924 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
925 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
926                            Vector& normal)
927 {
928   float itop = r1.get_bottom() - r2.get_top();
929   float ibottom = r2.get_bottom() - r1.get_top();
930   float ileft = r1.get_right() - r2.get_left();
931   float iright = r2.get_right() - r1.get_left();
932
933   float vert_penetration = std::min(itop, ibottom);
934   float horiz_penetration = std::min(ileft, iright);
935   if(vert_penetration < horiz_penetration) {
936     if(itop < ibottom) {
937       hit.bottom = true;
938       normal.y = vert_penetration;
939     } else {
940       hit.top = true;
941       normal.y = -vert_penetration;
942     }
943   } else {
944     if(ileft < iright) {
945       hit.right = true;
946       normal.x = horiz_penetration;
947     } else {
948       hit.left = true;
949       normal.x = -horiz_penetration;
950     }
951   }
952 }
953
954 void
955 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
956 {
957   using namespace collision;
958
959   const Rect& r1 = object1->dest;
960   const Rect& r2 = object2->dest;
961
962   CollisionHit hit;
963   if(intersects(object1->dest, object2->dest)) {
964     Vector normal;
965     get_hit_normal(r1, r2, hit, normal);
966
967     HitResponse response1 = object1->collision(*object2, hit);
968     std::swap(hit.left, hit.right);
969     std::swap(hit.top, hit.bottom);
970     HitResponse response2 = object2->collision(*object1, hit);
971     assert( response1 != SOLID && response1 != PASSTHROUGH );
972     assert( response2 != SOLID && response2 != PASSTHROUGH );
973     if(response1 == CONTINUE && response2 == CONTINUE) {
974       normal *= (0.5 + DELTA);
975       object1->dest.move(-normal);
976       object2->dest.move(normal);
977     } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
978       normal *= (1 + DELTA);
979       object1->dest.move(-normal);
980     } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
981       normal *= (1 + DELTA);
982       object2->dest.move(normal);
983     }
984   }
985 }
986
987 void
988 Sector::collision_static(collision::Constraints* constraints,
989                          const Vector& movement, const Rect& dest,
990                          GameObject& object)
991 {
992   collision_tilemap(constraints, movement, dest);
993
994   // collision with other (static) objects
995   for(MovingObjects::iterator i = moving_objects.begin();
996       i != moving_objects.end(); ++i) {
997     MovingObject* moving_object = *i;
998     if(moving_object->get_group() != COLGROUP_STATIC
999        && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1000       continue;
1001     if(!moving_object->is_valid())
1002       continue;
1003
1004     if(moving_object != &object)
1005       check_collisions(constraints, movement, dest, moving_object->bbox,
1006           &object, moving_object);
1007   }
1008 }
1009
1010 void
1011 Sector::collision_static_constrains(MovingObject& object)
1012 {
1013   using namespace collision;
1014   float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1015
1016   Constraints constraints;
1017   Vector movement = object.get_movement();
1018   Rect& dest = object.dest;
1019   float owidth = object.get_bbox().get_width();
1020   float oheight = object.get_bbox().get_height();
1021
1022   for(int i = 0; i < 2; ++i) {
1023     collision_static(&constraints, Vector(0, movement.y), dest, object);
1024     if(!constraints.has_constraints())
1025       break;
1026
1027     // apply calculated horizontal constraints
1028     if(constraints.bottom < infinity) {
1029       float height = constraints.bottom - constraints.top;
1030       if(height < oheight) {
1031         // we're crushed, but ignore this for now, we'll get this again
1032         // later if we're really crushed or things will solve itself when
1033         // looking at the vertical constraints
1034       }
1035       dest.p2.y = constraints.bottom - DELTA;
1036       dest.p1.y = dest.p2.y - oheight;
1037     } else if(constraints.top > -infinity) {
1038       dest.p1.y = constraints.top + DELTA;
1039       dest.p2.y = dest.p1.y + oheight;
1040     }
1041   }
1042   if(constraints.has_constraints()) {
1043     if(constraints.hit.bottom) {
1044       dest.move(constraints.ground_movement);
1045     }
1046     if(constraints.hit.top || constraints.hit.bottom) {
1047       constraints.hit.left = false;
1048       constraints.hit.right = false;
1049       object.collision_solid(constraints.hit);
1050     }
1051   }
1052
1053   constraints = Constraints();
1054   for(int i = 0; i < 2; ++i) {
1055     collision_static(&constraints, movement, dest, object);
1056     if(!constraints.has_constraints())
1057       break;
1058
1059     // apply calculated vertical constraints
1060     if(constraints.right < infinity) {
1061       float width = constraints.right - constraints.left;
1062       if(width + SHIFT_DELTA < owidth) {
1063         printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1064             constraints.left, constraints.right);
1065         CollisionHit h;
1066         h.left = true;
1067         h.right = true;
1068         h.crush = true;
1069         object.collision_solid(h);
1070       } else {
1071         dest.p2.x = constraints.right - DELTA;
1072         dest.p1.x = dest.p2.x - owidth;
1073       }
1074     } else if(constraints.left > -infinity) {
1075       dest.p1.x = constraints.left + DELTA;
1076       dest.p2.x = dest.p1.x + owidth;
1077     }
1078   }
1079
1080   if(constraints.has_constraints()) {
1081     if( constraints.hit.left || constraints.hit.right
1082         || constraints.hit.top || constraints.hit.bottom
1083         || constraints.hit.crush )
1084       object.collision_solid(constraints.hit);
1085   }
1086
1087   // an extra pass to make sure we're not crushed horizontally
1088   constraints = Constraints();
1089   collision_static(&constraints, movement, dest, object);
1090   if(constraints.bottom < infinity) {
1091     float height = constraints.bottom - constraints.top;
1092     if(height + SHIFT_DELTA < oheight) {
1093       printf("Object %p crushed vertically...\n", &object);
1094       CollisionHit h;
1095       h.top = true;
1096       h.bottom = true;
1097       h.crush = true;
1098       object.collision_solid(h);
1099     }
1100   }
1101 }
1102
1103 void
1104 Sector::handle_collisions()
1105 {
1106   using namespace collision;
1107
1108   // calculate destination positions of the objects
1109   for(MovingObjects::iterator i = moving_objects.begin();
1110       i != moving_objects.end(); ++i) {
1111     MovingObject* moving_object = *i;
1112
1113     moving_object->dest = moving_object->get_bbox();
1114     moving_object->dest.move(moving_object->get_movement());
1115   }
1116
1117   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1118   for(MovingObjects::iterator i = moving_objects.begin();
1119       i != moving_objects.end(); ++i) {
1120     MovingObject* moving_object = *i;
1121     if((moving_object->get_group() != COLGROUP_MOVING
1122           && moving_object->get_group() != COLGROUP_MOVING_STATIC
1123           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1124         || !moving_object->is_valid())
1125       continue;
1126
1127     collision_static_constrains(*moving_object);
1128   }
1129
1130
1131   // part2: COLGROUP_MOVING vs tile attributes
1132   for(MovingObjects::iterator i = moving_objects.begin();
1133       i != moving_objects.end(); ++i) {
1134     MovingObject* moving_object = *i;
1135     if((moving_object->get_group() != COLGROUP_MOVING
1136           && moving_object->get_group() != COLGROUP_MOVING_STATIC
1137           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1138         || !moving_object->is_valid())
1139       continue;
1140
1141     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1142     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1143       moving_object->collision_tile(tile_attributes);
1144     }
1145   }
1146
1147   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1148   for(MovingObjects::iterator i = moving_objects.begin();
1149       i != moving_objects.end(); ++i) {
1150     MovingObject* moving_object = *i;
1151     if((moving_object->get_group() != COLGROUP_MOVING
1152           && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1153         || !moving_object->is_valid())
1154       continue;
1155
1156     for(MovingObjects::iterator i2 = moving_objects.begin();
1157         i2 != moving_objects.end(); ++i2) {
1158       MovingObject* moving_object_2 = *i2;
1159       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1160          || !moving_object_2->is_valid())
1161         continue;
1162
1163       if(intersects(moving_object->dest, moving_object_2->dest)) {
1164         Vector normal;
1165         CollisionHit hit;
1166         get_hit_normal(moving_object->dest, moving_object_2->dest,
1167                        hit, normal);
1168         moving_object->collision(*moving_object_2, hit);
1169         moving_object_2->collision(*moving_object, hit);
1170       }
1171     }
1172   }
1173
1174   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1175   for(MovingObjects::iterator i = moving_objects.begin();
1176       i != moving_objects.end(); ++i) {
1177     MovingObject* moving_object = *i;
1178
1179     if((moving_object->get_group() != COLGROUP_MOVING
1180           && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1181         || !moving_object->is_valid())
1182       continue;
1183
1184     for(MovingObjects::iterator i2 = i+1;
1185         i2 != moving_objects.end(); ++i2) {
1186       MovingObject* moving_object_2 = *i2;
1187       if((moving_object_2->get_group() != COLGROUP_MOVING
1188             && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1189          || !moving_object_2->is_valid())
1190         continue;
1191
1192       collision_object(moving_object, moving_object_2);
1193     }
1194   }
1195
1196   // apply object movement
1197   for(MovingObjects::iterator i = moving_objects.begin();
1198       i != moving_objects.end(); ++i) {
1199     MovingObject* moving_object = *i;
1200
1201     moving_object->bbox = moving_object->dest;
1202     moving_object->movement = Vector(0, 0);
1203   }
1204 }
1205
1206 bool
1207 Sector::is_free_of_tiles(const Rect& rect) const
1208 {
1209   using namespace collision;
1210
1211   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1212     TileMap* solids = *i;
1213
1214     // test with all tiles in this rectangle
1215     int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1216     int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1217     int max_x = int(rect.p2.x - solids->get_x_offset());
1218     int max_y = int(rect.p2.y - solids->get_y_offset());
1219
1220     for(int x = starttilex; x*32 <= max_x; ++x) {
1221       for(int y = starttiley; y*32 <= max_y; ++y) {
1222         const Tile* tile = solids->get_tile(x, y);
1223         if(!tile) continue;
1224         if(tile->getAttributes() & Tile::SLOPE) {
1225           AATriangle triangle;
1226           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1227           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1228           triangle = AATriangle(p1, p2, tile->getData());
1229           Constraints constraints;
1230           return collision::rectangle_aatriangle(&constraints, rect, triangle);
1231         }
1232         if(tile->getAttributes() & Tile::SOLID) return false;
1233       }
1234     }
1235   }
1236
1237   return true;
1238 }
1239
1240 bool
1241 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object) const
1242 {
1243   using namespace collision;
1244
1245   if (!is_free_of_tiles(rect)) return false;
1246
1247   for(MovingObjects::const_iterator i = moving_objects.begin();
1248       i != moving_objects.end(); ++i) {
1249     const MovingObject* moving_object = *i;
1250     if (moving_object == ignore_object) continue;
1251     if (!moving_object->is_valid()) continue;
1252     if (moving_object->get_group() == COLGROUP_STATIC) {
1253       if(intersects(rect, moving_object->get_bbox())) return false;
1254     }
1255   }
1256
1257   return true;
1258 }
1259
1260 bool
1261 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1262 {
1263   using namespace collision;
1264
1265   if (!is_free_of_tiles(rect)) return false;
1266
1267   for(MovingObjects::const_iterator i = moving_objects.begin();
1268       i != moving_objects.end(); ++i) {
1269     const MovingObject* moving_object = *i;
1270     if (moving_object == ignore_object) continue;
1271     if (!moving_object->is_valid()) continue;
1272     if ((moving_object->get_group() == COLGROUP_MOVING) 
1273       || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1274       || (moving_object->get_group() == COLGROUP_STATIC)) {
1275       if(intersects(rect, moving_object->get_bbox())) return false;
1276     }
1277   }
1278
1279   return true;
1280 }
1281
1282 bool
1283 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1284 {
1285   // TODO remove this function and move these checks elsewhere...
1286
1287   Bullet* new_bullet = 0;
1288   if((player_status->bonus == FIRE_BONUS &&
1289       (int)bullets.size() >= player_status->max_fire_bullets) ||
1290      (player_status->bonus == ICE_BONUS &&
1291       (int)bullets.size() >= player_status->max_ice_bullets))
1292     return false;
1293   new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1294   add_object(new_bullet);
1295
1296   sound_manager->play("sounds/shoot.wav");
1297
1298   return true;
1299 }
1300
1301 bool
1302 Sector::add_smoke_cloud(const Vector& pos)
1303 {
1304   add_object(new SmokeCloud(pos));
1305   return true;
1306 }
1307
1308 void
1309 Sector::play_music(MusicType type)
1310 {
1311   currentmusic = type;
1312   switch(currentmusic) {
1313     case LEVEL_MUSIC:
1314       sound_manager->play_music(music);
1315       break;
1316     case HERRING_MUSIC:
1317       sound_manager->play_music("music/salcon.ogg");
1318       break;
1319     case HERRING_WARNING_MUSIC:
1320       sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1321       break;
1322     default:
1323       sound_manager->play_music("");
1324       break;
1325   }
1326 }
1327
1328 MusicType
1329 Sector::get_music_type()
1330 {
1331   return currentmusic;
1332 }
1333
1334 int
1335 Sector::get_total_badguys()
1336 {
1337   int total_badguys = 0;
1338   for(GameObjects::iterator i = gameobjects.begin();
1339       i != gameobjects.end(); ++i) {
1340     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1341     if (badguy && badguy->countMe)
1342       total_badguys++;
1343   }
1344
1345   return total_badguys;
1346 }
1347
1348 bool
1349 Sector::inside(const Rect& rect) const
1350 {
1351   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1352     TileMap* solids = *i;
1353     bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1354     bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1355     if (horizontally && vertically) return true;
1356   }
1357   return false;
1358 }
1359
1360 float
1361 Sector::get_width() const
1362 {
1363   float width = 0;
1364   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1365     TileMap* solids = *i;
1366     if ((solids->get_width() * 32 + solids->get_x_offset()) > width) width = (solids->get_width() * 32 + solids->get_x_offset());
1367   }
1368   return width;
1369 }
1370
1371 float
1372 Sector::get_height() const
1373 {
1374   float height = 0;
1375   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1376     TileMap* solids = *i;
1377     if ((solids->get_height() * 32 + solids->get_y_offset()) > height) height = (solids->get_height() * 32 + solids->get_y_offset());
1378   }
1379   return height;
1380 }
1381
1382 void
1383 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1384 {
1385   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1386     TileMap* solids = *i;
1387     solids->change_all(old_tile_id, new_tile_id);
1388   }
1389 }
1390
1391
1392 void
1393 Sector::set_ambient_light(float red, float green, float blue)
1394 {
1395   ambient_light.red = red;
1396   ambient_light.green = green;
1397   ambient_light.blue = blue;
1398 }
1399
1400 float
1401 Sector::get_ambient_red()
1402 {
1403   return ambient_light.red;
1404 }
1405
1406 float
1407 Sector::get_ambient_green()
1408 {
1409   return ambient_light.green;
1410 }
1411
1412 float
1413 Sector::get_ambient_blue()
1414 {
1415   return ambient_light.blue;
1416 }