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 "object/gameobjs.h"
32 #include "object/camera.h"
33 #include "object/background.h"
34 #include "object/particlesystem.h"
35 #include "object/tilemap.h"
36 #include "lisp/parser.h"
37 #include "lisp/lisp.h"
38 #include "lisp/writer.h"
39 #include "lisp/list_iterator.h"
41 #include "audio/sound_manager.h"
43 #include "resources.h"
44 #include "statistics.h"
45 #include "collision_grid.h"
46 #include "collision_grid_iterator.h"
47 #include "object_factory.h"
48 #include "special/collision.h"
49 #include "math/rectangle.h"
50 #include "math/aatriangle.h"
51 #include "object/coin.h"
52 #include "object/block.h"
53 #include "object/invisible_block.h"
54 #include "object/bullet.h"
55 #include "badguy/jumpy.h"
56 #include "badguy/spike.h"
57 #include "trigger/sequence_trigger.h"
59 Sector* Sector::_current = 0;
62 : gravity(10), player(0), solids(0), camera(0),
63 currentmusic(LEVEL_MUSIC)
65 song_title = "Mortimers_chipdisko.mod";
66 player = new Player();
69 grid = new CollisionGrid(32000, 32000);
74 update_game_objects();
75 assert(gameobjects_new.size() == 0);
79 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
84 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
93 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
95 if(name == "camera") {
96 Camera* camera = new Camera(this);
97 camera->parse(reader);
99 } else if(name == "particles-snow") {
100 SnowParticleSystem* partsys = new SnowParticleSystem();
101 partsys->parse(reader);
103 } else if(name == "particles-clouds") {
104 CloudParticleSystem* partsys = new CloudParticleSystem();
105 partsys->parse(reader);
107 } else if(name == "money") { // for compatibility with old maps
108 return new Jumpy(reader);
112 return create_object(name, reader);
113 } catch(std::exception& e) {
114 std::cerr << e.what() << "\n";
121 Sector::parse(const lisp::Lisp& sector)
125 lisp::ListIterator iter(§or);
127 const std::string& token = iter.item();
128 if(token == "name") {
129 iter.value()->get(name);
130 } else if(token == "gravity") {
131 iter.value()->get(gravity);
132 } else if(token == "music") {
133 iter.value()->get(song_title);
135 } else if(token == "spawnpoint") {
136 const lisp::Lisp* spawnpoint_lisp = iter.lisp();
138 SpawnPoint* sp = new SpawnPoint;
139 spawnpoint_lisp->get("name", sp->name);
140 spawnpoint_lisp->get("x", sp->pos.x);
141 spawnpoint_lisp->get("y", sp->pos.y);
142 spawnpoints.push_back(sp);
144 GameObject* object = parse_object(token, *(iter.lisp()));
151 update_game_objects();
153 update_game_objects();
155 std::cerr << "sector '" << name << "' does not contain a camera.\n";
156 camera = new Camera(this);
160 throw std::runtime_error("sector does not contain a solid tile layer.");
164 Sector::parse_old_format(const lisp::Lisp& reader)
169 reader.get("gravity", gravity);
171 std::string backgroundimage;
172 reader.get("background", backgroundimage);
174 reader.get("bkgd_speed", bgspeed);
177 Color bkgd_top, bkgd_bottom;
178 int r = 0, g = 0, b = 128;
179 reader.get("bkgd_red_top", r);
180 reader.get("bkgd_green_top", g);
181 reader.get("bkgd_blue_top", b);
186 reader.get("bkgd_red_bottom", r);
187 reader.get("bkgd_green_bottom", g);
188 reader.get("bkgd_blue_bottom", b);
190 bkgd_bottom.green = g;
191 bkgd_bottom.blue = b;
193 if(backgroundimage != "") {
194 Background* background = new Background;
195 background->set_image(backgroundimage, bgspeed);
196 add_object(background);
198 Background* background = new Background;
199 background->set_gradient(bkgd_top, bkgd_bottom);
200 add_object(background);
203 std::string particlesystem;
204 reader.get("particle_system", particlesystem);
205 if(particlesystem == "clouds")
206 add_object(new CloudParticleSystem());
207 else if(particlesystem == "snow")
208 add_object(new SnowParticleSystem());
210 Vector startpos(100, 170);
211 reader.get("start_pos_x", startpos.x);
212 reader.get("start_pos_y", startpos.y);
214 SpawnPoint* spawn = new SpawnPoint;
215 spawn->pos = startpos;
216 spawn->name = "main";
217 spawnpoints.push_back(spawn);
219 song_title = "Mortimers_chipdisko.mod";
220 reader.get("music", song_title);
223 int width, height = 15;
224 reader.get("width", width);
225 reader.get("height", height);
227 std::vector<unsigned int> tiles;
228 if(reader.get_vector("interactive-tm", tiles)
229 || reader.get_vector("tilemap", tiles)) {
230 TileMap* tilemap = new TileMap();
231 tilemap->set(width, height, tiles, LAYER_TILES, true);
235 if(reader.get_vector("background-tm", tiles)) {
236 TileMap* tilemap = new TileMap();
237 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
241 if(reader.get_vector("foreground-tm", tiles)) {
242 TileMap* tilemap = new TileMap();
243 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
247 // read reset-points (now spawn-points)
248 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
250 lisp::ListIterator iter(resetpoints);
252 if(iter.item() == "point") {
254 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
256 SpawnPoint* sp = new SpawnPoint;
259 spawnpoints.push_back(sp);
262 std::cerr << "Unknown token '" << iter.item() << "' in reset-points.\n";
268 const lisp::Lisp* objects = reader.get_lisp("objects");
270 lisp::ListIterator iter(objects);
272 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
276 std::cerr << "Unknown object '" << iter.item() << "' in level.\n";
282 Camera* camera = new Camera(this);
285 update_game_objects();
287 update_game_objects();
289 throw std::runtime_error("sector does not contain a solid tile layer.");
293 Sector::fix_old_tiles()
296 for(size_t x=0; x < solids->get_width(); ++x) {
297 for(size_t y=0; y < solids->get_height(); ++y) {
298 const Tile* tile = solids->get_tile(x, y);
299 Vector pos(x*32, y*32);
301 if(tile->getID() == 112) {
302 add_object(new InvisibleBlock(pos));
303 solids->change(x, y, 0);
304 } else if(tile->getID() == 295) {
305 add_object(new Spike(pos, Spike::NORTH));
306 solids->change(x, y, 0);
307 } else if(tile->getID() == 296) {
308 add_object(new Spike(pos, Spike::EAST));
309 solids->change(x, y, 0);
310 } else if(tile->getID() == 297) {
311 add_object(new Spike(pos, Spike::SOUTH));
312 solids->change(x, y, 0);
313 } else if(tile->getID() == 298) {
314 add_object(new Spike(pos, Spike::WEST));
315 solids->change(x, y, 0);
316 } else if(tile->getAttributes() & Tile::COIN) {
317 add_object(new Coin(pos));
318 solids->change(x, y, 0);
319 } else if(tile->getAttributes() & Tile::FULLBOX) {
320 add_object(new BonusBlock(pos, tile->getData()));
321 solids->change(x, y, 0);
322 } else if(tile->getAttributes() & Tile::BRICK) {
323 add_object(new Brick(pos, tile->getData()));
324 solids->change(x, y, 0);
325 } else if(tile->getAttributes() & Tile::GOAL) {
326 add_object(new SequenceTrigger(pos, "endsequence"));
327 solids->change(x, y, 0);
334 Sector::write(lisp::Writer& writer)
336 writer.write_string("name", name);
337 writer.write_float("gravity", gravity);
338 writer.write_string("music", song_title);
341 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
343 SpawnPoint* spawn = *i;
344 writer.start_list("spawn-points");
345 writer.write_string("name", spawn->name);
346 writer.write_float("x", spawn->pos.x);
347 writer.write_float("y", spawn->pos.y);
348 writer.end_list("spawn-points");
352 for(GameObjects::iterator i = gameobjects.begin();
353 i != gameobjects.end(); ++i) {
354 Serializable* serializable = dynamic_cast<Serializable*> (*i);
356 serializable->write(writer);
361 Sector::add_object(GameObject* object)
363 // make sure the object isn't already in the list
365 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
368 assert("object already added to sector" == 0);
371 for(GameObjects::iterator i = gameobjects_new.begin();
372 i != gameobjects_new.end(); ++i) {
374 assert("object already added to sector" == 0);
379 gameobjects_new.push_back(object);
383 Sector::activate(const std::string& spawnpoint)
387 // Apply bonuses from former levels
388 switch (player_status.bonus)
390 case PlayerStatus::NO_BONUS:
393 case PlayerStatus::FLOWER_BONUS:
394 player->got_power = Player::FIRE_POWER; // FIXME: add ice power to here
397 case PlayerStatus::GROWUP_BONUS:
403 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
405 if((*i)->name == spawnpoint) {
411 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
413 player->move(sp->pos);
416 camera->reset(player->get_pos());
420 Sector::get_best_spawn_point(Vector pos)
422 Vector best_reset_point = Vector(-1,-1);
424 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
426 if((*i)->name != "main")
428 if((*i)->pos.x > best_reset_point.x && (*i)->pos.x < pos.x)
429 best_reset_point = (*i)->pos;
432 return best_reset_point;
436 Sector::get_active_region()
439 camera->get_translation() - Vector(1600, 1200),
440 camera->get_translation() + Vector(1600, 1200));
444 Sector::action(float elapsed_time)
446 player->check_bounds(camera);
449 CollisionGridIterator iter(*grid, get_active_region());
450 while(MovingObject* object = iter.next()) {
451 if(!object->is_valid())
454 object->action(elapsed_time);
458 for(GameObjects::iterator i = gameobjects.begin();
459 i != gameobjects.end(); ++i) {
460 GameObject* object = *i;
461 if(!object->is_valid())
464 object->action(elapsed_time);
468 /* Handle all possible collisions. */
470 update_game_objects();
474 Sector::update_game_objects()
476 /** cleanup marked objects */
477 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
478 i != gameobjects.end(); /* nothing */) {
479 GameObject* object = *i;
481 if(object->is_valid()) {
486 Bullet* bullet = dynamic_cast<Bullet*> (object);
489 std::remove(bullets.begin(), bullets.end(), bullet),
492 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
494 grid->remove_object(movingobject);
497 i = gameobjects.erase(i);
500 /* add newly created objects */
501 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
502 i != gameobjects_new.end(); ++i)
504 GameObject* object = *i;
506 Bullet* bullet = dynamic_cast<Bullet*> (object);
508 bullets.push_back(bullet);
510 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
512 grid->add_object(movingobject);
514 TileMap* tilemap = dynamic_cast<TileMap*> (object);
515 if(tilemap && tilemap->is_solid()) {
519 std::cerr << "Another solid tilemaps added. Ignoring.";
523 Camera* camera = dynamic_cast<Camera*> (object);
525 if(this->camera != 0) {
526 std::cerr << "Warning: Multiple cameras added. Ignoring.";
529 this->camera = camera;
532 gameobjects.push_back(object);
534 gameobjects_new.clear();
538 Sector::draw(DrawingContext& context)
540 context.push_transform();
541 context.set_translation(camera->get_translation());
544 CollisionGridIterator iter(*grid, get_active_region());
545 while(MovingObject* object = iter.next()) {
546 if(!object->is_valid())
549 object->draw(context);
552 for(GameObjects::iterator i = gameobjects.begin();
553 i != gameobjects.end(); ++i) {
554 GameObject* object = *i;
555 if(!object->is_valid())
558 object->draw(context);
562 context.pop_transform();
565 static const float DELTA = .001;
568 Sector::collision_tilemap(MovingObject* object, int depth)
572 std::cout << "Max collision depth reached.\n";
574 object->movement = Vector(0, 0);
578 // calculate rectangle where the object will move
580 if(object->get_movement().x >= 0) {
581 x1 = object->get_pos().x;
582 x2 = object->get_bbox().p2.x + object->get_movement().x;
584 x1 = object->get_pos().x + object->get_movement().x;
585 x2 = object->get_bbox().p2.x;
588 if(object->get_movement().y >= 0) {
589 y1 = object->get_pos().y;
590 y2 = object->get_bbox().p2.y + object->get_movement().y;
592 y1 = object->get_pos().y + object->get_movement().y;
593 y2 = object->get_bbox().p2.y;
596 // test with all tiles in this rectangle
597 int starttilex = int(x1-1) / 32;
598 int starttiley = int(y1-1) / 32;
599 int max_x = int(x2+1);
600 int max_y = int(y2+1);
602 CollisionHit temphit, hit;
603 Rectangle dest = object->get_bbox();
604 dest.move(object->movement);
605 hit.time = -1; // represents an invalid value
606 for(int x = starttilex; x*32 < max_x; ++x) {
607 for(int y = starttiley; y*32 < max_y; ++y) {
608 const Tile* tile = solids->get_tile(x, y);
611 if(!(tile->getAttributes() & Tile::SOLID))
613 if((tile->getAttributes() & Tile::UNISOLID) && object->movement.y < 0)
616 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
618 Vector p1(x*32, y*32);
619 Vector p2((x+1)*32, (y+1)*32);
620 triangle = AATriangle(p1, p2, tile->getData());
622 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
624 if(temphit.time > hit.time)
627 } else { // normal rectangular tile
628 Rectangle rect(x*32, y*32, (x+1)*32, (y+1)*32);
629 if(Collision::rectangle_rectangle(temphit, dest,
630 object->movement, rect)) {
631 if(temphit.time > hit.time)
638 // did we collide at all?
642 // call collision function
643 HitResponse response = object->collision(*solids, hit);
644 if(response == ABORT_MOVE) {
645 object->movement = Vector(0, 0);
648 if(response == FORCE_MOVE) {
651 // move out of collision and try again
652 object->movement += hit.normal * (hit.depth + DELTA);
653 collision_tilemap(object, depth+1);
657 Sector::collision_object(MovingObject* object1, MovingObject* object2)
660 Rectangle dest1 = object1->get_bbox();
661 dest1.move(object1->get_movement());
662 Rectangle dest2 = object2->get_bbox();
663 dest2.move(object2->get_movement());
665 Vector movement = object1->get_movement() - object2->get_movement();
666 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
667 HitResponse response1 = object1->collision(*object2, hit);
669 HitResponse response2 = object2->collision(*object1, hit);
671 if(response1 != CONTINUE) {
672 if(response1 == ABORT_MOVE)
673 object1->movement = Vector(0, 0);
674 if(response2 == CONTINUE)
675 object2->movement += hit.normal * (hit.depth + DELTA);
676 } else if(response2 != CONTINUE) {
677 if(response2 == ABORT_MOVE)
678 object2->movement = Vector(0, 0);
679 if(response1 == CONTINUE)
680 object1->movement += -hit.normal * (hit.depth + DELTA);
682 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
683 object2->movement += hit.normal * (hit.depth/2 + DELTA);
689 Sector::collision_handler()
692 grid->check_collisions();
694 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
695 i != gameobjects.end(); ++i) {
696 GameObject* gameobject = *i;
697 if(!gameobject->is_valid())
699 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
702 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
703 movingobject->bbox.move(movingobject->movement);
704 movingobject->movement = Vector(0, 0);
708 // collision with tilemap
709 if(! (movingobject->movement == Vector(0, 0)))
710 collision_tilemap(movingobject, 0);
712 // collision with other objects
713 for(std::vector<GameObject*>::iterator i2 = i+1;
714 i2 != gameobjects.end(); ++i2) {
715 GameObject* other_object = *i2;
716 if(!other_object->is_valid()
717 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
719 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
723 collision_object(movingobject, movingobject2);
726 movingobject->bbox.move(movingobject->get_movement());
727 movingobject->movement = Vector(0, 0);
733 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
735 if(player->got_power == Player::FIRE_POWER) {
736 if(bullets.size() > MAX_FIRE_BULLETS-1)
738 } else if(player->got_power == Player::ICE_POWER) {
739 if(bullets.size() > MAX_ICE_BULLETS-1)
743 Bullet* new_bullet = 0;
744 if(player->got_power == Player::FIRE_POWER)
745 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
746 else if(player->got_power == Player::ICE_POWER)
747 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
749 throw std::runtime_error("wrong bullet type.");
750 add_object(new_bullet);
752 SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
758 Sector::add_smoke_cloud(const Vector& pos)
760 add_object(new SmokeCloud(pos));
765 Sector::add_floating_text(const Vector& pos, const std::string& text)
767 add_object(new FloatingText(pos, text));
776 level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
778 song_path = (char *) malloc(sizeof(char) * datadir.length() +
779 strlen(song_title.c_str()) + 8 + 5);
780 song_subtitle = strdup(song_title.c_str());
781 strcpy(strstr(song_subtitle, "."), "\0");
782 sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
783 song_subtitle, strstr(song_title.c_str(), "."));
784 if(!SoundManager::get()->exists_music(song_path)) {
785 level_song_fast = level_song;
787 level_song_fast = SoundManager::get()->load_music(song_path);
794 Sector::play_music(int type)
797 switch(currentmusic) {
799 SoundManager::get()->play_music(level_song_fast);
802 SoundManager::get()->play_music(level_song);
805 SoundManager::get()->play_music(herring_song);
808 SoundManager::get()->halt_music();
814 Sector::get_music_type()
820 Sector::get_total_badguys()
822 int total_badguys = 0;
824 for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
826 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
831 return total_badguys;
835 Sector::inside(const Rectangle& rect) const
837 if(rect.p1.x > solids->get_width() * 32
838 || rect.p1.y > solids->get_height() * 32
839 || rect.p2.x < 0 || rect.p2.y < 0)