9064af73d2d793c3d6cafcde15c9406dea7f1e38
[supertux.git] / src / sector.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 Matthias Braun <matze@braunis.de
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 #include <memory>
21 #include <algorithm>
22 #include <stdexcept>
23 #include <iostream>
24 #include <fstream>
25 #include <stdexcept>
26
27 #include "app/globals.h"
28 #include "sector.h"
29 #include "utils/lispreader.h"
30 #include "badguy.h"
31 #include "special.h"
32 #include "gameobjs.h"
33 #include "camera.h"
34 #include "background.h"
35 #include "particlesystem.h"
36 #include "tile.h"
37 #include "tilemap.h"
38 #include "audio/sound_manager.h"
39 #include "gameloop.h"
40 #include "resources.h"
41 #include "interactive_object.h"
42 #include "door.h"
43
44 Sector* Sector::_current = 0;
45
46 Sector::Sector()
47   : gravity(10), player(0), solids(0), background(0), camera(0),
48     currentmusic(LEVEL_MUSIC)
49 {
50   song_title = "Mortimers_chipdisko.mod";
51   player = new Player();
52   add_object(player);
53 }
54
55 Sector::~Sector()
56 {
57   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
58       ++i)
59     delete *i;
60
61   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
62       ++i)
63     delete *i;
64     
65   if(_current == this)
66     _current = 0;
67 }
68
69 void
70 Sector::parse(LispReader& lispreader)
71 {
72   _current = this;
73   
74   for(lisp_object_t* cur = lispreader.get_lisp(); !lisp_nil_p(cur);
75       cur = lisp_cdr(cur)) {
76     std::string token = lisp_symbol(lisp_car(lisp_car(cur)));
77     // FIXME: doesn't handle empty data
78     lisp_object_t* data = lisp_car(lisp_cdr(lisp_car(cur)));
79     LispReader reader(lisp_cdr(lisp_car(cur)));
80
81     if(token == "name") {
82       name = lisp_string(data);
83     } else if(token == "gravity") {
84       gravity = lisp_real(data);
85     } else if(token == "music") {
86       song_title = lisp_string(data);
87       load_music();
88     } else if(token == "camera") {
89       if(camera) {
90         std::cerr << "Warning: More than 1 camera defined in sector.\n";
91         continue;
92       }
93       camera = new Camera(this);
94       camera->read(reader);
95       add_object(camera);
96     } else if(token == "background") {
97       background = new Background(reader);
98       add_object(background);
99     } else if(token == "spawn-points") {
100       SpawnPoint* sp = new SpawnPoint;
101       reader.read_string("name", sp->name);
102       reader.read_float("x", sp->pos.x);
103       reader.read_float("y", sp->pos.y);
104       spawnpoints.push_back(sp);
105     } else if(token == "tilemap") {
106       TileMap* tilemap = new TileMap(reader);
107       add_object(tilemap);
108
109       if(tilemap->is_solid()) {
110         if(solids) {
111           std::cerr << "Warning multiple solid tilemaps in sector.\n";
112           continue;
113         }
114         solids = tilemap;
115       }
116     } else if(badguykind_from_string(token) != BAD_INVALID) {
117       add_object(new BadGuy(badguykind_from_string(token), reader));
118     } else if(token == "trampoline") {
119       add_object(new Trampoline(reader));
120     } else if(token == "flying-platform") {
121       add_object(new FlyingPlatform(reader));
122     } else if(token == "particles-snow") {
123       SnowParticleSystem* partsys = new SnowParticleSystem();
124       partsys->parse(reader);
125       add_object(partsys);
126     } else if(token == "particles-clouds") {
127       CloudParticleSystem* partsys = new CloudParticleSystem();
128       partsys->parse(reader);
129       add_object(partsys);
130     } else if(token == "door") {
131       add_object(new Door(reader));
132     } else {
133       std::cerr << "Unknown object type '" << token << "'.\n";
134     }
135   }
136
137   if(!camera) {
138     std::cerr << "sector '" << name << "' does not contain a camera.\n";
139     camera = new Camera(this);
140     add_object(camera);
141   }
142   if(!solids)
143     throw std::runtime_error("sector does not contain a solid tile layer.");
144 }
145
146 void
147 Sector::parse_old_format(LispReader& reader)
148 {
149   _current = this;
150   
151   name = "main";
152   reader.read_float("gravity", gravity);
153
154   std::string backgroundimage;
155   reader.read_string("background", backgroundimage);
156   float bgspeed = .5;
157   reader.read_float("bkgd_speed", bgspeed);
158   bgspeed /= 100;
159
160   Color bkgd_top, bkgd_bottom;
161   int r = 0, g = 0, b = 128;
162   reader.read_int("bkgd_red_top", r);
163   reader.read_int("bkgd_green_top",  g);
164   reader.read_int("bkgd_blue_top",  b);
165   bkgd_top.red = r;
166   bkgd_top.green = g;
167   bkgd_top.blue = b;
168   
169   reader.read_int("bkgd_red_bottom",  r);
170   reader.read_int("bkgd_green_bottom", g);
171   reader.read_int("bkgd_blue_bottom", b);
172   bkgd_bottom.red = r;
173   bkgd_bottom.green = g;
174   bkgd_bottom.blue = b;
175   
176   if(backgroundimage != "") {
177     background = new Background;
178     background->set_image(backgroundimage, bgspeed);
179     add_object(background);
180   } else {
181     background = new Background;
182     background->set_gradient(bkgd_top, bkgd_bottom);
183     add_object(background);
184   }
185
186   std::string particlesystem;
187   reader.read_string("particle_system", particlesystem);
188   if(particlesystem == "clouds")
189     add_object(new CloudParticleSystem());
190   else if(particlesystem == "snow")
191     add_object(new SnowParticleSystem());
192
193   Vector startpos(100, 170);
194   reader.read_float("start_pos_x", startpos.x);
195   reader.read_float("start_pos_y", startpos.y);
196
197   SpawnPoint* spawn = new SpawnPoint;
198   spawn->pos = startpos;
199   spawn->name = "main";
200   spawnpoints.push_back(spawn);
201
202   song_title = "Mortimers_chipdisko.mod";
203   reader.read_string("music", song_title);
204   load_music();
205
206   int width, height = 15;
207   reader.read_int("width", width);
208   reader.read_int("height", height);
209   
210   std::vector<unsigned int> tiles;
211   if(reader.read_int_vector("interactive-tm", tiles)
212       || reader.read_int_vector("tilemap", tiles)) {
213     TileMap* tilemap = new TileMap();
214     tilemap->set(width, height, tiles, LAYER_TILES, true);
215     solids = tilemap;
216     add_object(tilemap);
217   }
218
219   if(reader.read_int_vector("background-tm", tiles)) {
220     TileMap* tilemap = new TileMap();
221     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
222     add_object(tilemap);
223   }
224
225   if(reader.read_int_vector("foreground-tm", tiles)) {
226     TileMap* tilemap = new TileMap();
227     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
228     add_object(tilemap);
229   }
230
231   // read reset-points (now spawn-points)
232   {
233     lisp_object_t* cur = 0;
234     if(reader.read_lisp("reset-points", cur)) {
235       while(!lisp_nil_p(cur)) {
236         lisp_object_t* data = lisp_car(cur);
237         LispReader reader(lisp_cdr(data));
238
239         Vector sp_pos;
240         if(reader.read_float("x", sp_pos.x) && reader.read_float("y", sp_pos.y))
241           {
242           SpawnPoint* sp = new SpawnPoint;
243           sp->name = "main";
244           sp->pos = sp_pos;
245           spawnpoints.push_back(sp);
246           }
247                                                              
248         cur = lisp_cdr(cur);
249       }
250     }
251   }
252
253   // read objects
254   {
255     lisp_object_t* cur = 0;
256     if(reader.read_lisp("objects", cur)) {
257       while(!lisp_nil_p(cur)) {
258         lisp_object_t* data = lisp_car(cur);
259         std::string object_type = lisp_symbol(lisp_car(data));
260                                                                                 
261         LispReader reader(lisp_cdr(data));
262                                                                                 
263         if(object_type == "trampoline") {
264           add_object(new Trampoline(reader));
265         }
266         else if(object_type == "flying-platform") {
267           add_object(new FlyingPlatform(reader));
268         }
269         else {
270           BadGuyKind kind = badguykind_from_string(object_type);
271           add_object(new BadGuy(kind, reader));
272         }
273                                                                                 
274         cur = lisp_cdr(cur);
275       }
276     }
277   }
278
279   // add a camera
280   camera = new Camera(this);
281   add_object(camera);
282 }
283
284 void
285 Sector::write(LispWriter& writer)
286 {
287   writer.write_string("name", name);
288   writer.write_float("gravity", gravity);
289   writer.write_string("music", song_title);
290
291   // write spawnpoints
292   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
293       ++i) {
294     SpawnPoint* spawn = *i;
295     writer.start_list("spawn-points");
296     writer.write_string("name", spawn->name);
297     writer.write_float("x", spawn->pos.x);
298     writer.write_float("y", spawn->pos.y);
299     writer.end_list("spawn-points");
300   }
301
302   // write objects
303   for(GameObjects::iterator i = gameobjects.begin();
304       i != gameobjects.end(); ++i) {
305     Serializable* serializable = dynamic_cast<Serializable*> (*i);
306     if(serializable)
307       serializable->write(writer);
308   }
309 }
310
311 void
312 Sector::do_vertical_flip()
313 {
314   for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
315     {
316     TileMap* tilemap = dynamic_cast<TileMap*> (*i);
317     if(tilemap)
318       {
319       tilemap->do_vertical_flip();
320       }
321
322     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
323     if(badguy)
324       badguy->start_position.y = solids->get_height()*32 - badguy->start_position.y - 32;
325     Trampoline* trampoline = dynamic_cast<Trampoline*> (*i);
326     if(trampoline)
327       trampoline->base.y = solids->get_height()*32 - trampoline->base.y - 32;
328     FlyingPlatform* flying_platform = dynamic_cast<FlyingPlatform*> (*i);
329     if(flying_platform)
330       flying_platform->base.y = solids->get_height()*32 - flying_platform->base.y - 32;
331     Door* door = dynamic_cast<Door*> (*i);
332     if(door)
333       door->set_area(door->get_area().x, solids->get_height()*32 - door->get_area().y - 32);
334     }
335
336   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
337       ++i) {
338     SpawnPoint* spawn = *i;
339     spawn->pos.y = solids->get_height()*32 - spawn->pos.y - 32;
340   }
341 }
342
343 void
344 Sector::add_object(GameObject* object)
345 {
346   gameobjects_new.push_back(object);
347 }
348
349 void
350 Sector::activate(const std::string& spawnpoint)
351 {
352   _current = this;
353
354   // Apply bonuses from former levels
355   switch (player_status.bonus)
356     {
357     case PlayerStatus::NO_BONUS:
358       break;
359                                                                                 
360     case PlayerStatus::FLOWER_BONUS:
361       player->got_power = Player::FIRE_POWER;  // FIXME: add ice power to here
362       // fall through
363                                                                                 
364     case PlayerStatus::GROWUP_BONUS:
365       player->grow(false);
366       break;
367     }
368
369   SpawnPoint* sp = 0;
370   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
371       ++i) {
372     if((*i)->name == spawnpoint) {
373       sp = *i;
374       break;
375     }
376   }
377   if(!sp) {
378     std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
379   } else {
380     player->move(sp->pos);
381   }
382
383   camera->reset(Vector(player->base.x, player->base.y));
384 }
385
386 Vector
387 Sector::get_best_spawn_point(Vector pos)
388 {
389 Vector best_reset_point = Vector(-1,-1);
390
391 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
392       ++i) {
393   if((*i)->name != "main")
394     continue;
395   if((*i)->pos.x > best_reset_point.x && (*i)->pos.x < pos.x)
396     best_reset_point = (*i)->pos;
397   }
398
399 return best_reset_point;
400 }
401
402 void
403 Sector::action(float elapsed_time)
404 {
405   player->check_bounds(camera);
406                                                                                 
407   /* update objects (don't use iterators here, because the list might change
408    * during the iteration)
409    */
410   for(size_t i = 0; i < gameobjects.size(); ++i)
411     if(gameobjects[i]->is_valid())
412       gameobjects[i]->action(elapsed_time);
413                                                                                 
414   /* Handle all possible collisions. */
415   collision_handler();
416                                                                                 
417   update_game_objects();
418 }
419
420 void
421 Sector::update_game_objects()
422 {
423   /** cleanup marked objects */
424   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
425       i != gameobjects.end(); /* nothing */) {
426     if((*i)->is_valid() == false) {
427       BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
428       if(badguy) {
429         badguys.erase(std::remove(badguys.begin(), badguys.end(), badguy),
430             badguys.end());
431       }
432       Bullet* bullet = dynamic_cast<Bullet*> (*i);
433       if(bullet) {
434         bullets.erase(
435             std::remove(bullets.begin(), bullets.end(), bullet),
436             bullets.end());
437       }
438       InteractiveObject* interactive_object =
439           dynamic_cast<InteractiveObject*> (*i);
440       if(interactive_object) {
441         interactive_objects.erase(
442             std::remove(interactive_objects.begin(), interactive_objects.end(),
443                 interactive_object), interactive_objects.end());
444       }
445       Upgrade* upgrade = dynamic_cast<Upgrade*> (*i);
446       if(upgrade) {
447         upgrades.erase(
448             std::remove(upgrades.begin(), upgrades.end(), upgrade),
449             upgrades.end());
450       }
451       Trampoline* trampoline = dynamic_cast<Trampoline*> (*i);
452       if(trampoline) {
453         trampolines.erase(
454             std::remove(trampolines.begin(), trampolines.end(), trampoline),
455             trampolines.end());
456       }
457       FlyingPlatform* flying_platform= dynamic_cast<FlyingPlatform*> (*i);
458       if(flying_platform) {
459         flying_platforms.erase(
460             std::remove(flying_platforms.begin(), flying_platforms.end(), flying_platform),
461             flying_platforms.end());
462       }
463       SmokeCloud* smoke_cloud = dynamic_cast<SmokeCloud*> (*i);
464       if(smoke_cloud) {
465         smoke_clouds.erase(
466             std::remove(smoke_clouds.begin(), smoke_clouds.end(), smoke_cloud),
467             smoke_clouds.end());
468       }
469                                                                                 
470       delete *i;
471       i = gameobjects.erase(i);
472     } else {
473       ++i;
474     }
475   }
476
477   /* add newly created objects */
478   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
479       i != gameobjects_new.end(); ++i)
480   {
481           BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
482           if(badguy)
483             badguys.push_back(badguy);
484           Bullet* bullet = dynamic_cast<Bullet*> (*i);
485           if(bullet)
486             bullets.push_back(bullet);
487           Upgrade* upgrade = dynamic_cast<Upgrade*> (*i);
488           if(upgrade)
489             upgrades.push_back(upgrade);
490           Trampoline* trampoline = dynamic_cast<Trampoline*> (*i);
491           if(trampoline)
492             trampolines.push_back(trampoline);
493           FlyingPlatform* flying_platform = dynamic_cast<FlyingPlatform*> (*i);
494           if(flying_platform)
495             flying_platforms.push_back(flying_platform);
496           InteractiveObject* interactive_object 
497               = dynamic_cast<InteractiveObject*> (*i);
498           if(interactive_object)
499             interactive_objects.push_back(interactive_object);
500           SmokeCloud* smoke_cloud = dynamic_cast<SmokeCloud*> (*i);
501           if(smoke_cloud)
502             smoke_clouds.push_back(smoke_cloud);
503
504
505           gameobjects.push_back(*i);
506   }
507   gameobjects_new.clear();
508 }
509
510 void
511 Sector::draw(DrawingContext& context)
512 {
513   context.push_transform();
514   context.set_translation(camera->get_translation());
515   
516   for(GameObjects::iterator i = gameobjects.begin();
517       i != gameobjects.end(); ++i) {
518     if( (*i)->is_valid() )
519       (*i)->draw(context);
520   }
521
522   context.pop_transform();
523 }
524
525 void
526 Sector::collision_handler()
527 {
528   // CO_BULLET & CO_BADGUY check
529   for(unsigned int i = 0; i < bullets.size(); ++i)
530     {
531       for (BadGuys::iterator j = badguys.begin(); j != badguys.end(); ++j)
532         {
533           if((*j)->dying != DYING_NOT)
534             continue;
535                                                                                 
536           if(rectcollision(bullets[i]->base, (*j)->base))
537             {
538               // We have detected a collision and now call the
539               // collision functions of the collided objects.
540               (*j)->collision(bullets[i], CO_BULLET, COLLISION_NORMAL);
541               bullets[i]->collision(CO_BADGUY);
542               break; // bullet is invalid now, so break
543             }
544         }
545     }
546                                                                                 
547   /* CO_BADGUY & CO_BADGUY check */
548   for (BadGuys::iterator i = badguys.begin(); i != badguys.end(); ++i)
549     {
550       if((*i)->dying != DYING_NOT)
551         continue;
552                                                                                 
553       BadGuys::iterator j = i;
554       ++j;
555       for (; j != badguys.end(); ++j)
556         {
557           if(j == i || (*j)->dying != DYING_NOT)
558             continue;
559                                                                                 
560           if(rectcollision((*i)->base, (*j)->base))
561             {
562               // We have detected a collision and now call the
563               // collision functions of the collided objects.
564               (*j)->collision(*i, CO_BADGUY);
565               (*i)->collision(*j, CO_BADGUY);
566             }
567         }
568     }
569   if(player->dying != DYING_NOT) return;
570                                                                                 
571   // CO_BADGUY & CO_PLAYER check
572   for (BadGuys::iterator i = badguys.begin(); i != badguys.end(); ++i)
573     {
574       if((*i)->dying != DYING_NOT)
575         continue;
576                                                                                 
577       if(rectcollision_offset((*i)->base, player->base, 0, 0))
578         {
579           // We have detected a collision and now call the collision
580           // functions of the collided objects.
581           if (player->previous_base.y < player->base.y &&
582               player->previous_base.y + player->previous_base.height
583               < (*i)->base.y + (*i)->base.height/2
584               && !player->invincible_timer.started())
585             {
586               (*i)->collision(player, CO_PLAYER, COLLISION_SQUISH);
587             }
588           else
589             {
590               player->collision(*i, CO_BADGUY);
591               (*i)->collision(player, CO_PLAYER, COLLISION_NORMAL);
592             }
593         }
594     }
595                                                                                 
596   // CO_UPGRADE & CO_PLAYER check
597   for(unsigned int i = 0; i < upgrades.size(); ++i)
598     {
599       if(rectcollision(upgrades[i]->base, player->base))
600         {
601           // We have detected a collision and now call the collision
602           // functions of the collided objects.
603           upgrades[i]->collision(player, CO_PLAYER, COLLISION_NORMAL);
604         }
605     }
606                                                                                 
607   // CO_TRAMPOLINE & (CO_PLAYER or CO_BADGUY)
608   for (Trampolines::iterator i = trampolines.begin(); i != trampolines.end(); ++i)
609   {
610     if (rectcollision((*i)->base, player->base))
611     {
612       if (player->previous_base.y < player->base.y &&
613           player->previous_base.y + player->previous_base.height
614           < (*i)->base.y + (*i)->base.height/2)
615       {
616         (*i)->collision(player, CO_PLAYER, COLLISION_SQUISH);
617       }
618       else if (player->previous_base.y <= player->base.y)
619       {
620         player->collision(*i, CO_TRAMPOLINE);
621         (*i)->collision(player, CO_PLAYER, COLLISION_NORMAL);
622       }
623     }
624   }
625                                                                                 
626   // CO_FLYING_PLATFORM & (CO_PLAYER or CO_BADGUY)
627   for (FlyingPlatforms::iterator i = flying_platforms.begin(); i != flying_platforms.end(); ++i)
628   {
629     if (rectcollision((*i)->base, player->base))
630     {
631       if (player->previous_base.y < player->base.y &&
632           player->previous_base.y + player->previous_base.height
633           < (*i)->base.y + (*i)->base.height/2)
634       {
635         (*i)->collision(player, CO_PLAYER, COLLISION_SQUISH);
636         player->collision(*i, CO_FLYING_PLATFORM);
637       }
638 /*      else if (player->previous_base.y <= player->base.y)
639       {
640       }*/
641     }
642   }
643 }
644
645 void
646 Sector::add_score(const Vector& pos, int s)
647 {
648   player_status.score += s;
649                                                                                 
650   add_object(new FloatingScore(pos, s));
651 }
652                                                                                 
653 void
654 Sector::add_bouncy_distro(const Vector& pos)
655 {
656   add_object(new BouncyDistro(pos));
657 }
658                                                                                 
659 void
660 Sector::add_broken_brick(const Vector& pos, Tile* tile)
661 {
662   add_broken_brick_piece(pos, Vector(-1, -4), tile);
663   add_broken_brick_piece(pos + Vector(0, 16), Vector(-1.5, -3), tile);
664                                                                                 
665   add_broken_brick_piece(pos + Vector(16, 0), Vector(1, -4), tile);
666   add_broken_brick_piece(pos + Vector(16, 16), Vector(1.5, -3), tile);
667 }
668                                                                                 
669 void
670 Sector::add_broken_brick_piece(const Vector& pos, const Vector& movement,
671     Tile* tile)
672 {
673   add_object(new BrokenBrick(tile, pos, movement));
674 }
675                                                                                 
676 void
677 Sector::add_bouncy_brick(const Vector& pos)
678 {
679   add_object(new BouncyBrick(pos));
680 }
681
682 BadGuy*
683 Sector::add_bad_guy(float x, float y, BadGuyKind kind)
684 {
685   BadGuy* badguy = new BadGuy(kind, x, y);
686   add_object(badguy);
687   return badguy;
688 }
689                                                                                 
690 void
691 Sector::add_upgrade(const Vector& pos, Direction dir, UpgradeKind kind)
692 {
693   add_object(new Upgrade(pos, dir, kind));
694 }
695                                                                                 
696 bool
697 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
698 {
699   if(player->got_power == Player::FIRE_POWER)
700     {
701     if(bullets.size() > MAX_FIRE_BULLETS-1)
702       return false;
703     }
704   else if(player->got_power == Player::ICE_POWER)
705     {
706     if(bullets.size() > MAX_ICE_BULLETS-1)
707       return false;
708     }
709                                                                                 
710   Bullet* new_bullet = 0;
711   if(player->got_power == Player::FIRE_POWER)
712     new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
713   else if(player->got_power == Player::ICE_POWER)
714     new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
715   else
716     throw std::runtime_error("wrong bullet type.");
717   add_object(new_bullet);
718                                                                                 
719   SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
720                                                                                 
721   return true;
722 }
723
724 bool
725 Sector::add_smoke_cloud(const Vector& pos)
726 {
727   add_object(new SmokeCloud(pos));
728   return true;
729 }
730
731 /* Break a brick: */
732 bool
733 Sector::trybreakbrick(const Vector& pos, bool small)
734 {
735   Tile* tile = solids->get_tile_at(pos);
736   if (!tile)
737   {
738     char errmsg[64];
739     sprintf(errmsg, "Invalid tile at %i,%i", (int)((pos.x+1)/32*32), (int)((pos.y+1)/32*32));
740     throw SuperTuxException(errmsg, __FILE__, __LINE__);
741   }
742
743   if (tile->attributes & Tile::BRICK)
744     {
745       if (tile->data > 0)
746         {
747           /* Get a distro from it: */
748           add_bouncy_distro(
749               Vector(((int)(pos.x + 1) / 32) * 32, (int)(pos.y / 32) * 32));
750                                                                                 
751           // TODO: don't handle this in a global way but per-tile...
752           if (!counting_distros)
753             {
754               counting_distros = true;
755               distro_counter = 5;
756             }
757           else
758             {
759               distro_counter--;
760             }
761                                                                                 
762           if (distro_counter <= 0)
763             {
764               counting_distros = false;
765               solids->change_at(pos, tile->next_tile);
766             }
767                                                                                 
768           SoundManager::get()->play_sound(IDToSound(SND_DISTRO));
769           player_status.score = player_status.score + SCORE_DISTRO;
770           player_status.distros++;
771           return true;
772         }
773       else if (!small)
774         {
775           /* Get rid of it: */
776           solids->change_at(pos, tile->next_tile);
777                                                                                 
778           /* Replace it with broken bits: */
779           add_broken_brick(Vector(
780                                  ((int)(pos.x + 1) / 32) * 32,
781                                  (int)(pos.y / 32) * 32), tile);
782                                                                                 
783           /* Get some score: */
784           SoundManager::get()->play_sound(IDToSound(SND_BRICK));
785           player_status.score = player_status.score + SCORE_BRICK;
786                                                                                 
787           return true;
788         }
789     }
790                                                                                 
791   return false;
792 }
793                                                                                 
794 /* Empty a box: */
795 void
796 Sector::tryemptybox(const Vector& pos, Direction col_side)
797 {
798   Tile* tile = solids->get_tile_at(pos);
799   if (!tile)
800   {
801     char errmsg[64];
802     sprintf(errmsg, "Invalid tile at %i,%i", (int)((pos.x+1)/32*32), (int)((pos.y+1)/32*32));
803     throw SuperTuxException(errmsg, __FILE__, __LINE__);
804   }
805
806
807   if (!(tile->attributes & Tile::FULLBOX))
808     return;
809                                                                                 
810   // according to the collision side, set the upgrade direction
811   if(col_side == LEFT)
812     col_side = RIGHT;
813   else
814     col_side = LEFT;
815                                                                                 
816   int posx = ((int)(pos.x+1) / 32) * 32;
817   int posy = (int)(pos.y/32) * 32 - 32;
818   switch(tile->data)
819     {
820     case 1: // Box with a distro!
821       add_bouncy_distro(Vector(posx, posy));
822       SoundManager::get()->play_sound(IDToSound(SND_DISTRO));
823       player_status.score = player_status.score + SCORE_DISTRO;
824       player_status.distros++;
825       break;
826                                                                                 
827     case 2: // Add a fire flower upgrade!
828       if (player->size == SMALL)     /* Tux is small, add mints! */
829         add_upgrade(Vector(posx, posy), col_side, UPGRADE_GROWUP);
830       else     /* Tux is big, add a fireflower: */
831         add_upgrade(Vector(posx, posy), col_side, UPGRADE_FIREFLOWER);
832       SoundManager::get()->play_sound(IDToSound(SND_UPGRADE));
833       break;
834                                                                                 
835     case 5: // Add an ice flower upgrade!
836       if (player->size == SMALL)     /* Tux is small, add mints! */
837         add_upgrade(Vector(posx, posy), col_side, UPGRADE_GROWUP);
838       else     /* Tux is big, add an iceflower: */
839         add_upgrade(Vector(posx, posy), col_side, UPGRADE_ICEFLOWER);
840       SoundManager::get()->play_sound(IDToSound(SND_UPGRADE));
841       break;
842                                                                                 
843     case 3: // Add a golden herring
844       add_upgrade(Vector(posx, posy), col_side, UPGRADE_STAR);
845       break;
846                                                                                 
847     case 4: // Add a 1up extra
848       add_upgrade(Vector(posx, posy), col_side, UPGRADE_1UP);
849       break;
850     default:
851       break;
852     }
853                                                                                 
854   /* Empty the box: */
855   solids->change_at(pos, tile->next_tile);
856 }
857                                                                                 
858 /* Try to grab a distro: */
859 void
860 Sector::trygrabdistro(const Vector& pos, int bounciness)
861 {
862   Tile* tile = solids->get_tile_at(pos);
863   if (!tile)
864   {
865     /*char errmsg[64];
866     sprintf(errmsg, "Invalid tile at %i,%i", (int)((pos.x+1)/32*32), (int)((pos.y+1)/32*32));
867     throw SuperTuxException(errmsg, __FILE__, __LINE__); */
868     
869     //Bad tiles (i.e. tiles that are not defined in supertux.stgt but appear in the map) are changed to ID 0 (blank tile)
870     std::cout << "Warning: Undefined tile at " <<(int)pos.x/32 << "/" << (int)pos.y/32 << " (ID: " << (int)solids->get_tile_id_at(pos).id << ")" << std::endl;
871     solids->change_at(pos,0);
872     tile = solids->get_tile_at(pos);
873   }
874
875
876   if (!(tile->attributes & Tile::COIN))
877     return;
878
879   solids->change_at(pos, tile->next_tile);
880   SoundManager::get()->play_sound(IDToSound(SND_DISTRO));
881                                                                             
882   if (bounciness == BOUNCE)
883     {
884       add_bouncy_distro(Vector(((int)(pos.x + 1) / 32) * 32,
885                               (int)(pos.y / 32) * 32));
886     }
887                                                                             
888   player_status.score = player_status.score + SCORE_DISTRO;
889   player_status.distros++;
890
891 }
892                                                                                 
893 /* Try to bump a bad guy from below: */
894 void
895 Sector::trybumpbadguy(const Vector& pos)
896 {
897   // Bad guys:
898   for (BadGuys::iterator i = badguys.begin(); i != badguys.end(); ++i)
899     {
900       if ((*i)->base.x >= pos.x - 32 && (*i)->base.x <= pos.x + 32 &&
901           (*i)->base.y >= pos.y - 16 && (*i)->base.y <= pos.y + 16)
902         {
903           (*i)->collision(player, CO_PLAYER, COLLISION_BUMP);
904         }
905     }
906                                                                                 
907   // Upgrades:
908   for (unsigned int i = 0; i < upgrades.size(); i++)
909     {
910       if (upgrades[i]->base.height == 32 &&
911           upgrades[i]->base.x >= pos.x - 32 && upgrades[i]->base.x <= pos.x + 32 &&
912           upgrades[i]->base.y >= pos.y - 16 && upgrades[i]->base.y <= pos.y + 16)
913         {
914           upgrades[i]->collision(player, CO_PLAYER, COLLISION_BUMP);
915         }
916     }
917 }
918
919 void
920 Sector::load_music()
921 {
922   char* song_path;
923   char* song_subtitle;
924                                                                                 
925   level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
926                                                                                 
927   song_path = (char *) malloc(sizeof(char) * datadir.length() +
928                               strlen(song_title.c_str()) + 8 + 5);
929   song_subtitle = strdup(song_title.c_str());
930   strcpy(strstr(song_subtitle, "."), "\0");
931   sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
932           song_subtitle, strstr(song_title.c_str(), "."));
933   if(!SoundManager::get()->exists_music(song_path)) {
934     level_song_fast = level_song;
935   } else {
936     level_song_fast = SoundManager::get()->load_music(song_path);
937   }
938   free(song_subtitle);
939   free(song_path);
940 }
941
942 void
943 Sector::play_music(int type)
944 {
945   currentmusic = type;
946   switch(currentmusic) {
947     case HURRYUP_MUSIC:
948       SoundManager::get()->play_music(level_song_fast);
949       break;
950     case LEVEL_MUSIC:
951       SoundManager::get()->play_music(level_song);
952       break;
953     case HERRING_MUSIC:
954       SoundManager::get()->play_music(herring_song);
955       break;
956     default:
957       SoundManager::get()->halt_music();
958       break;
959   }
960 }
961
962 int
963 Sector::get_music_type()
964 {
965   return currentmusic;
966 }