3 // SuperTux - A Jump'n Run
4 // Copyright (C) 2004 Matthias Braun <matze@braunis.de
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.
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.
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.
29 #include "app/globals.h"
31 #include "player_status.h"
32 #include "object/gameobjs.h"
33 #include "object/camera.h"
34 #include "object/background.h"
35 #include "object/particlesystem.h"
36 #include "object/tilemap.h"
37 #include "lisp/parser.h"
38 #include "lisp/lisp.h"
39 #include "lisp/writer.h"
40 #include "lisp/list_iterator.h"
42 #include "audio/sound_manager.h"
44 #include "resources.h"
45 #include "statistics.h"
46 #include "collision_grid.h"
47 #include "collision_grid_iterator.h"
48 #include "object_factory.h"
49 #include "special/collision.h"
50 #include "math/rectangle.h"
51 #include "math/aatriangle.h"
52 #include "object/coin.h"
53 #include "object/block.h"
54 #include "object/invisible_block.h"
55 #include "object/bullet.h"
56 #include "badguy/jumpy.h"
57 #include "badguy/spike.h"
58 #include "trigger/sequence_trigger.h"
62 Sector* Sector::_current = 0;
65 : gravity(10), player(0), solids(0), camera(0),
66 currentmusic(LEVEL_MUSIC)
68 song_title = "Mortimers_chipdisko.mod";
69 player = new Player();
72 grid = new CollisionGrid(32000, 32000);
77 update_game_objects();
78 assert(gameobjects_new.size() == 0);
82 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
87 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
96 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
98 if(name == "camera") {
99 Camera* camera = new Camera(this);
100 camera->parse(reader);
102 } else if(name == "particles-snow") {
103 SnowParticleSystem* partsys = new SnowParticleSystem();
104 partsys->parse(reader);
106 } else if(name == "particles-rain") {
107 RainParticleSystem* partsys = new RainParticleSystem();
108 partsys->parse(reader);
110 } else if(name == "particles-clouds") {
111 CloudParticleSystem* partsys = new CloudParticleSystem();
112 partsys->parse(reader);
114 } else if(name == "money") { // for compatibility with old maps
115 return new Jumpy(reader);
119 return create_object(name, reader);
120 } catch(std::exception& e) {
121 std::cerr << e.what() << "\n";
128 Sector::parse(const lisp::Lisp& sector)
132 lisp::ListIterator iter(§or);
134 const std::string& token = iter.item();
135 if(token == "name") {
136 iter.value()->get(name);
137 } else if(token == "gravity") {
138 iter.value()->get(gravity);
139 } else if(token == "music") {
140 iter.value()->get(song_title);
142 } else if(token == "spawnpoint") {
143 const lisp::Lisp* spawnpoint_lisp = iter.lisp();
145 SpawnPoint* sp = new SpawnPoint;
146 spawnpoint_lisp->get("name", sp->name);
147 spawnpoint_lisp->get("x", sp->pos.x);
148 spawnpoint_lisp->get("y", sp->pos.y);
149 spawnpoints.push_back(sp);
151 GameObject* object = parse_object(token, *(iter.lisp()));
158 update_game_objects();
160 update_game_objects();
162 std::cerr << "sector '" << name << "' does not contain a camera.\n";
163 camera = new Camera(this);
167 throw std::runtime_error("sector does not contain a solid tile layer.");
171 Sector::parse_old_format(const lisp::Lisp& reader)
176 reader.get("gravity", gravity);
178 std::string backgroundimage;
179 reader.get("background", backgroundimage);
181 reader.get("bkgd_speed", bgspeed);
184 Color bkgd_top, bkgd_bottom;
185 int r = 0, g = 0, b = 128;
186 reader.get("bkgd_red_top", r);
187 reader.get("bkgd_green_top", g);
188 reader.get("bkgd_blue_top", b);
193 reader.get("bkgd_red_bottom", r);
194 reader.get("bkgd_green_bottom", g);
195 reader.get("bkgd_blue_bottom", b);
197 bkgd_bottom.green = g;
198 bkgd_bottom.blue = b;
200 if(backgroundimage != "") {
201 Background* background = new Background;
202 background->set_image(backgroundimage, bgspeed);
203 add_object(background);
205 Background* background = new Background;
206 background->set_gradient(bkgd_top, bkgd_bottom);
207 add_object(background);
210 std::string particlesystem;
211 reader.get("particle_system", particlesystem);
212 if(particlesystem == "clouds")
213 add_object(new CloudParticleSystem());
214 else if(particlesystem == "snow")
215 add_object(new SnowParticleSystem());
216 else if(particlesystem == "rain")
217 add_object(new RainParticleSystem());
219 Vector startpos(100, 170);
220 reader.get("start_pos_x", startpos.x);
221 reader.get("start_pos_y", startpos.y);
223 SpawnPoint* spawn = new SpawnPoint;
224 spawn->pos = startpos;
225 spawn->name = "main";
226 spawnpoints.push_back(spawn);
228 song_title = "Mortimers_chipdisko.mod";
229 reader.get("music", song_title);
232 int width, height = 15;
233 reader.get("width", width);
234 reader.get("height", height);
236 std::vector<unsigned int> tiles;
237 if(reader.get_vector("interactive-tm", tiles)
238 || reader.get_vector("tilemap", tiles)) {
239 TileMap* tilemap = new TileMap();
240 tilemap->set(width, height, tiles, LAYER_TILES, true);
244 if(reader.get_vector("background-tm", tiles)) {
245 TileMap* tilemap = new TileMap();
246 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
250 if(reader.get_vector("foreground-tm", tiles)) {
251 TileMap* tilemap = new TileMap();
252 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
256 // read reset-points (now spawn-points)
257 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
259 lisp::ListIterator iter(resetpoints);
261 if(iter.item() == "point") {
263 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
265 SpawnPoint* sp = new SpawnPoint;
268 spawnpoints.push_back(sp);
271 std::cerr << "Unknown token '" << iter.item() << "' in reset-points.\n";
277 const lisp::Lisp* objects = reader.get_lisp("objects");
279 lisp::ListIterator iter(objects);
281 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
285 std::cerr << "Unknown object '" << iter.item() << "' in level.\n";
291 Camera* camera = new Camera(this);
294 update_game_objects();
296 update_game_objects();
298 throw std::runtime_error("sector does not contain a solid tile layer.");
302 Sector::fix_old_tiles()
305 for(size_t x=0; x < solids->get_width(); ++x) {
306 for(size_t y=0; y < solids->get_height(); ++y) {
307 const Tile* tile = solids->get_tile(x, y);
308 Vector pos(x*32, y*32);
310 if(tile->getID() == 112) {
311 add_object(new InvisibleBlock(pos));
312 solids->change(x, y, 0);
313 } else if(tile->getID() == 295) {
314 add_object(new Spike(pos, Spike::NORTH));
315 solids->change(x, y, 0);
316 } else if(tile->getID() == 296) {
317 add_object(new Spike(pos, Spike::EAST));
318 solids->change(x, y, 0);
319 } else if(tile->getID() == 297) {
320 add_object(new Spike(pos, Spike::SOUTH));
321 solids->change(x, y, 0);
322 } else if(tile->getID() == 298) {
323 add_object(new Spike(pos, Spike::WEST));
324 solids->change(x, y, 0);
325 } else if(tile->getAttributes() & Tile::COIN) {
326 add_object(new Coin(pos));
327 solids->change(x, y, 0);
328 } else if(tile->getAttributes() & Tile::FULLBOX) {
329 add_object(new BonusBlock(pos, tile->getData()));
330 solids->change(x, y, 0);
331 } else if(tile->getAttributes() & Tile::BRICK) {
332 add_object(new Brick(pos, tile->getData()));
333 solids->change(x, y, 0);
334 } else if(tile->getAttributes() & Tile::GOAL) {
335 add_object(new SequenceTrigger(pos, "endsequence"));
336 solids->change(x, y, 0);
343 Sector::write(lisp::Writer& writer)
345 writer.write_string("name", name);
346 writer.write_float("gravity", gravity);
347 writer.write_string("music", song_title);
350 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
352 SpawnPoint* spawn = *i;
353 writer.start_list("spawn-points");
354 writer.write_string("name", spawn->name);
355 writer.write_float("x", spawn->pos.x);
356 writer.write_float("y", spawn->pos.y);
357 writer.end_list("spawn-points");
361 for(GameObjects::iterator i = gameobjects.begin();
362 i != gameobjects.end(); ++i) {
363 Serializable* serializable = dynamic_cast<Serializable*> (*i);
365 serializable->write(writer);
370 Sector::add_object(GameObject* object)
372 // make sure the object isn't already in the list
374 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
377 assert("object already added to sector" == 0);
380 for(GameObjects::iterator i = gameobjects_new.begin();
381 i != gameobjects_new.end(); ++i) {
383 assert("object already added to sector" == 0);
388 gameobjects_new.push_back(object);
392 Sector::activate(const std::string& spawnpoint)
396 // Apply bonuses from former levels
397 switch (player_status.bonus)
399 case PlayerStatus::NO_BONUS:
402 case PlayerStatus::FLOWER_BONUS:
403 player->got_power = Player::FIRE_POWER; // FIXME: add ice power to here
406 case PlayerStatus::GROWUP_BONUS:
412 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
414 if((*i)->name == spawnpoint) {
420 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
422 player->move(sp->pos);
425 camera->reset(player->get_pos());
429 Sector::get_best_spawn_point(Vector pos)
431 Vector best_reset_point = Vector(-1,-1);
433 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
435 if((*i)->name != "main")
437 if((*i)->pos.x > best_reset_point.x && (*i)->pos.x < pos.x)
438 best_reset_point = (*i)->pos;
441 return best_reset_point;
445 Sector::get_active_region()
448 camera->get_translation() - Vector(1600, 1200),
449 camera->get_translation() + Vector(1600, 1200));
453 Sector::action(float elapsed_time)
455 player->check_bounds(camera);
458 CollisionGridIterator iter(*grid, get_active_region());
459 while(MovingObject* object = iter.next()) {
460 if(!object->is_valid())
463 object->action(elapsed_time);
467 for(GameObjects::iterator i = gameobjects.begin();
468 i != gameobjects.end(); ++i) {
469 GameObject* object = *i;
470 if(!object->is_valid())
473 object->action(elapsed_time);
477 /* Handle all possible collisions. */
479 update_game_objects();
483 Sector::update_game_objects()
485 /** cleanup marked objects */
486 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
487 i != gameobjects.end(); /* nothing */) {
488 GameObject* object = *i;
490 if(object->is_valid()) {
495 Bullet* bullet = dynamic_cast<Bullet*> (object);
498 std::remove(bullets.begin(), bullets.end(), bullet),
501 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
503 grid->remove_object(movingobject);
506 i = gameobjects.erase(i);
509 /* add newly created objects */
510 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
511 i != gameobjects_new.end(); ++i)
513 GameObject* object = *i;
515 Bullet* bullet = dynamic_cast<Bullet*> (object);
517 bullets.push_back(bullet);
519 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
521 grid->add_object(movingobject);
523 TileMap* tilemap = dynamic_cast<TileMap*> (object);
524 if(tilemap && tilemap->is_solid()) {
528 std::cerr << "Another solid tilemaps added. Ignoring.";
532 Camera* camera = dynamic_cast<Camera*> (object);
534 if(this->camera != 0) {
535 std::cerr << "Warning: Multiple cameras added. Ignoring.";
538 this->camera = camera;
541 gameobjects.push_back(object);
543 gameobjects_new.clear();
547 Sector::draw(DrawingContext& context)
549 context.push_transform();
550 context.set_translation(camera->get_translation());
553 CollisionGridIterator iter(*grid, get_active_region());
554 while(MovingObject* object = iter.next()) {
555 if(!object->is_valid())
558 object->draw(context);
561 for(GameObjects::iterator i = gameobjects.begin();
562 i != gameobjects.end(); ++i) {
563 GameObject* object = *i;
564 if(!object->is_valid())
567 object->draw(context);
571 context.pop_transform();
574 static const float DELTA = .001;
577 Sector::collision_tilemap(MovingObject* object, int depth)
581 std::cout << "Max collision depth reached.\n";
583 object->movement = Vector(0, 0);
587 // calculate rectangle where the object will move
589 if(object->get_movement().x >= 0) {
590 x1 = object->get_pos().x;
591 x2 = object->get_bbox().p2.x + object->get_movement().x;
593 x1 = object->get_pos().x + object->get_movement().x;
594 x2 = object->get_bbox().p2.x;
597 if(object->get_movement().y >= 0) {
598 y1 = object->get_pos().y;
599 y2 = object->get_bbox().p2.y + object->get_movement().y;
601 y1 = object->get_pos().y + object->get_movement().y;
602 y2 = object->get_bbox().p2.y;
605 // test with all tiles in this rectangle
606 int starttilex = int(x1-1) / 32;
607 int starttiley = int(y1-1) / 32;
608 int max_x = int(x2+1);
609 int max_y = int(y2+1);
611 CollisionHit temphit, hit;
612 Rectangle dest = object->get_bbox();
613 dest.move(object->movement);
614 hit.time = -1; // represents an invalid value
615 for(int x = starttilex; x*32 < max_x; ++x) {
616 for(int y = starttiley; y*32 < max_y; ++y) {
617 const Tile* tile = solids->get_tile(x, y);
620 if(!(tile->getAttributes() & Tile::SOLID))
622 if((tile->getAttributes() & Tile::UNISOLID) && object->movement.y < 0)
625 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
627 Vector p1(x*32, y*32);
628 Vector p2((x+1)*32, (y+1)*32);
629 triangle = AATriangle(p1, p2, tile->getData());
631 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
633 if(temphit.time > hit.time)
636 } else { // normal rectangular tile
637 Rectangle rect(x*32, y*32, (x+1)*32, (y+1)*32);
638 if(Collision::rectangle_rectangle(temphit, dest,
639 object->movement, rect)) {
640 if(temphit.time > hit.time)
647 // did we collide at all?
651 // call collision function
652 HitResponse response = object->collision(*solids, hit);
653 if(response == ABORT_MOVE) {
654 object->movement = Vector(0, 0);
657 if(response == FORCE_MOVE) {
660 // move out of collision and try again
661 object->movement += hit.normal * (hit.depth + DELTA);
662 collision_tilemap(object, depth+1);
666 Sector::collision_object(MovingObject* object1, MovingObject* object2)
669 Rectangle dest1 = object1->get_bbox();
670 dest1.move(object1->get_movement());
671 Rectangle dest2 = object2->get_bbox();
672 dest2.move(object2->get_movement());
674 Vector movement = object1->get_movement() - object2->get_movement();
675 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
676 HitResponse response1 = object1->collision(*object2, hit);
678 HitResponse response2 = object2->collision(*object1, hit);
680 if(response1 != CONTINUE) {
681 if(response1 == ABORT_MOVE)
682 object1->movement = Vector(0, 0);
683 if(response2 == CONTINUE)
684 object2->movement += hit.normal * (hit.depth + DELTA);
685 } else if(response2 != CONTINUE) {
686 if(response2 == ABORT_MOVE)
687 object2->movement = Vector(0, 0);
688 if(response1 == CONTINUE)
689 object1->movement += -hit.normal * (hit.depth + DELTA);
691 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
692 object2->movement += hit.normal * (hit.depth/2 + DELTA);
698 Sector::collision_handler()
701 grid->check_collisions();
703 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
704 i != gameobjects.end(); ++i) {
705 GameObject* gameobject = *i;
706 if(!gameobject->is_valid())
708 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
711 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
712 movingobject->bbox.move(movingobject->movement);
713 movingobject->movement = Vector(0, 0);
717 // collision with tilemap
718 if(! (movingobject->movement == Vector(0, 0)))
719 collision_tilemap(movingobject, 0);
721 // collision with other objects
722 for(std::vector<GameObject*>::iterator i2 = i+1;
723 i2 != gameobjects.end(); ++i2) {
724 GameObject* other_object = *i2;
725 if(!other_object->is_valid()
726 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
728 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
732 collision_object(movingobject, movingobject2);
735 movingobject->bbox.move(movingobject->get_movement());
736 movingobject->movement = Vector(0, 0);
742 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
744 // TODO remove this function and move these checks elsewhere...
745 static const size_t MAX_FIRE_BULLETS = 2;
746 static const size_t MAX_ICE_BULLETS = 1;
748 if(player->got_power == Player::FIRE_POWER) {
749 if(bullets.size() > MAX_FIRE_BULLETS-1)
751 } else if(player->got_power == Player::ICE_POWER) {
752 if(bullets.size() > MAX_ICE_BULLETS-1)
756 Bullet* new_bullet = 0;
757 if(player->got_power == Player::FIRE_POWER)
758 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
759 else if(player->got_power == Player::ICE_POWER)
760 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
762 throw std::runtime_error("wrong bullet type.");
763 add_object(new_bullet);
765 SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
771 Sector::add_smoke_cloud(const Vector& pos)
773 add_object(new SmokeCloud(pos));
778 Sector::add_floating_text(const Vector& pos, const std::string& text)
780 add_object(new FloatingText(pos, text));
789 level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
791 song_path = (char *) malloc(sizeof(char) * datadir.length() +
792 strlen(song_title.c_str()) + 8 + 5);
793 song_subtitle = strdup(song_title.c_str());
794 strcpy(strstr(song_subtitle, "."), "\0");
795 sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
796 song_subtitle, strstr(song_title.c_str(), "."));
797 if(!SoundManager::get()->exists_music(song_path)) {
798 level_song_fast = level_song;
800 level_song_fast = SoundManager::get()->load_music(song_path);
807 Sector::play_music(int type)
810 switch(currentmusic) {
812 SoundManager::get()->play_music(level_song_fast);
815 SoundManager::get()->play_music(level_song);
818 SoundManager::get()->play_music(herring_song);
821 SoundManager::get()->halt_music();
827 Sector::get_music_type()
833 Sector::get_total_badguys()
835 int total_badguys = 0;
836 for(GameObjects::iterator i = gameobjects.begin();
837 i != gameobjects.end(); ++i) {
838 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
843 return total_badguys;
847 Sector::inside(const Rectangle& rect) const
849 if(rect.p1.x > solids->get_width() * 32
850 || rect.p1.y > solids->get_height() * 32
851 || rect.p2.x < 0 || rect.p2.y < 0)