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