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 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
336 add_object(new SequenceTrigger(pos, sequence));
337 solids->change(x, y, 0);
344 Sector::write(lisp::Writer& writer)
346 writer.write_string("name", name);
347 writer.write_float("gravity", gravity);
348 writer.write_string("music", song_title);
351 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
353 SpawnPoint* spawn = *i;
354 writer.start_list("spawn-points");
355 writer.write_string("name", spawn->name);
356 writer.write_float("x", spawn->pos.x);
357 writer.write_float("y", spawn->pos.y);
358 writer.end_list("spawn-points");
362 for(GameObjects::iterator i = gameobjects.begin();
363 i != gameobjects.end(); ++i) {
364 Serializable* serializable = dynamic_cast<Serializable*> (*i);
366 serializable->write(writer);
371 Sector::add_object(GameObject* object)
373 // make sure the object isn't already in the list
375 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
378 assert("object already added to sector" == 0);
381 for(GameObjects::iterator i = gameobjects_new.begin();
382 i != gameobjects_new.end(); ++i) {
384 assert("object already added to sector" == 0);
389 gameobjects_new.push_back(object);
393 Sector::activate(const std::string& spawnpoint)
396 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
398 if((*i)->name == spawnpoint) {
404 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
405 if(spawnpoint != "main") {
408 activate(Vector(0, 0));
416 Sector::activate(const Vector& player_pos)
420 // Apply bonuses from former levels
421 switch (player_status.bonus) {
422 case PlayerStatus::NO_BONUS:
425 case PlayerStatus::FLOWER_BONUS:
426 player->got_power = Player::FIRE_POWER; // FIXME: add ice power to here
429 case PlayerStatus::GROWUP_BONUS:
434 std::cerr << "Unknown bonus in PlayerStatus?!?\n";
438 player->move(player_pos);
439 camera->reset(player->get_pos());
443 Sector::get_active_region()
446 camera->get_translation() - Vector(1600, 1200),
447 camera->get_translation() + Vector(1600, 1200));
451 Sector::action(float elapsed_time)
453 player->check_bounds(camera);
456 CollisionGridIterator iter(*grid, get_active_region());
457 while(MovingObject* object = iter.next()) {
458 if(!object->is_valid())
461 object->action(elapsed_time);
465 for(GameObjects::iterator i = gameobjects.begin();
466 i != gameobjects.end(); ++i) {
467 GameObject* object = *i;
468 if(!object->is_valid())
471 object->action(elapsed_time);
475 /* Handle all possible collisions. */
477 update_game_objects();
481 Sector::update_game_objects()
483 /** cleanup marked objects */
484 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
485 i != gameobjects.end(); /* nothing */) {
486 GameObject* object = *i;
488 if(object->is_valid()) {
493 Bullet* bullet = dynamic_cast<Bullet*> (object);
496 std::remove(bullets.begin(), bullets.end(), bullet),
499 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
501 grid->remove_object(movingobject);
504 i = gameobjects.erase(i);
507 /* add newly created objects */
508 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
509 i != gameobjects_new.end(); ++i)
511 GameObject* object = *i;
513 Bullet* bullet = dynamic_cast<Bullet*> (object);
515 bullets.push_back(bullet);
517 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
519 grid->add_object(movingobject);
521 TileMap* tilemap = dynamic_cast<TileMap*> (object);
522 if(tilemap && tilemap->is_solid()) {
526 std::cerr << "Another solid tilemaps added. Ignoring.";
530 Camera* camera = dynamic_cast<Camera*> (object);
532 if(this->camera != 0) {
533 std::cerr << "Warning: Multiple cameras added. Ignoring.";
536 this->camera = camera;
539 gameobjects.push_back(object);
541 gameobjects_new.clear();
545 Sector::draw(DrawingContext& context)
547 context.push_transform();
548 context.set_translation(camera->get_translation());
551 CollisionGridIterator iter(*grid, get_active_region());
552 while(MovingObject* object = iter.next()) {
553 if(!object->is_valid())
556 object->draw(context);
559 for(GameObjects::iterator i = gameobjects.begin();
560 i != gameobjects.end(); ++i) {
561 GameObject* object = *i;
562 if(!object->is_valid())
565 object->draw(context);
569 context.pop_transform();
572 static const float DELTA = .001;
575 Sector::collision_tilemap(MovingObject* object, int depth)
579 std::cout << "Max collision depth reached.\n";
581 object->movement = Vector(0, 0);
585 // calculate rectangle where the object will move
587 if(object->get_movement().x >= 0) {
588 x1 = object->get_pos().x;
589 x2 = object->get_bbox().p2.x + object->get_movement().x;
591 x1 = object->get_pos().x + object->get_movement().x;
592 x2 = object->get_bbox().p2.x;
595 if(object->get_movement().y >= 0) {
596 y1 = object->get_pos().y;
597 y2 = object->get_bbox().p2.y + object->get_movement().y;
599 y1 = object->get_pos().y + object->get_movement().y;
600 y2 = object->get_bbox().p2.y;
603 // test with all tiles in this rectangle
604 int starttilex = int(x1-1) / 32;
605 int starttiley = int(y1-1) / 32;
606 int max_x = int(x2+1);
607 int max_y = int(y2+1);
609 CollisionHit temphit, hit;
610 Rectangle dest = object->get_bbox();
611 dest.move(object->movement);
612 hit.time = -1; // represents an invalid value
613 for(int x = starttilex; x*32 < max_x; ++x) {
614 for(int y = starttiley; y*32 < max_y; ++y) {
615 const Tile* tile = solids->get_tile(x, y);
618 if(!(tile->getAttributes() & Tile::SOLID))
620 if((tile->getAttributes() & Tile::UNISOLID) && object->movement.y < 0)
623 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
625 Vector p1(x*32, y*32);
626 Vector p2((x+1)*32, (y+1)*32);
627 triangle = AATriangle(p1, p2, tile->getData());
629 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
631 if(temphit.time > hit.time)
634 } else { // normal rectangular tile
635 Rectangle rect(x*32, y*32, (x+1)*32, (y+1)*32);
636 if(Collision::rectangle_rectangle(temphit, dest,
637 object->movement, rect)) {
638 if(temphit.time > hit.time)
645 // did we collide at all?
649 // call collision function
650 HitResponse response = object->collision(*solids, hit);
651 if(response == ABORT_MOVE) {
652 object->movement = Vector(0, 0);
655 if(response == FORCE_MOVE) {
658 // move out of collision and try again
659 object->movement += hit.normal * (hit.depth + DELTA);
660 collision_tilemap(object, depth+1);
664 Sector::collision_object(MovingObject* object1, MovingObject* object2)
667 Rectangle dest1 = object1->get_bbox();
668 dest1.move(object1->get_movement());
669 Rectangle dest2 = object2->get_bbox();
670 dest2.move(object2->get_movement());
672 Vector movement = object1->get_movement() - object2->get_movement();
673 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
674 HitResponse response1 = object1->collision(*object2, hit);
676 HitResponse response2 = object2->collision(*object1, hit);
678 if(response1 != CONTINUE) {
679 if(response1 == ABORT_MOVE)
680 object1->movement = Vector(0, 0);
681 if(response2 == CONTINUE)
682 object2->movement += hit.normal * (hit.depth + DELTA);
683 } else if(response2 != CONTINUE) {
684 if(response2 == ABORT_MOVE)
685 object2->movement = Vector(0, 0);
686 if(response1 == CONTINUE)
687 object1->movement += -hit.normal * (hit.depth + DELTA);
689 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
690 object2->movement += hit.normal * (hit.depth/2 + DELTA);
696 Sector::collision_handler()
699 grid->check_collisions();
701 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
702 i != gameobjects.end(); ++i) {
703 GameObject* gameobject = *i;
704 if(!gameobject->is_valid())
706 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
709 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
710 movingobject->bbox.move(movingobject->movement);
711 movingobject->movement = Vector(0, 0);
715 // collision with tilemap
716 if(! (movingobject->movement == Vector(0, 0)))
717 collision_tilemap(movingobject, 0);
719 // collision with other objects
720 for(std::vector<GameObject*>::iterator i2 = i+1;
721 i2 != gameobjects.end(); ++i2) {
722 GameObject* other_object = *i2;
723 if(!other_object->is_valid()
724 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
726 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
730 collision_object(movingobject, movingobject2);
733 movingobject->bbox.move(movingobject->get_movement());
734 movingobject->movement = Vector(0, 0);
740 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
742 // TODO remove this function and move these checks elsewhere...
743 static const size_t MAX_FIRE_BULLETS = 2;
744 static const size_t MAX_ICE_BULLETS = 1;
746 if(player->got_power == Player::FIRE_POWER) {
747 if(bullets.size() > MAX_FIRE_BULLETS-1)
749 } else if(player->got_power == Player::ICE_POWER) {
750 if(bullets.size() > MAX_ICE_BULLETS-1)
754 Bullet* new_bullet = 0;
755 if(player->got_power == Player::FIRE_POWER)
756 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
757 else if(player->got_power == Player::ICE_POWER)
758 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
760 throw std::runtime_error("wrong bullet type.");
761 add_object(new_bullet);
763 SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
769 Sector::add_smoke_cloud(const Vector& pos)
771 add_object(new SmokeCloud(pos));
776 Sector::add_floating_text(const Vector& pos, const std::string& text)
778 add_object(new FloatingText(pos, text));
787 level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
789 song_path = (char *) malloc(sizeof(char) * datadir.length() +
790 strlen(song_title.c_str()) + 8 + 5);
791 song_subtitle = strdup(song_title.c_str());
792 strcpy(strstr(song_subtitle, "."), "\0");
793 sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
794 song_subtitle, strstr(song_title.c_str(), "."));
795 if(!SoundManager::get()->exists_music(song_path)) {
796 level_song_fast = level_song;
798 level_song_fast = SoundManager::get()->load_music(song_path);
805 Sector::play_music(int type)
808 switch(currentmusic) {
810 SoundManager::get()->play_music(level_song_fast);
813 SoundManager::get()->play_music(level_song);
816 SoundManager::get()->play_music(herring_song);
819 SoundManager::get()->halt_music();
825 Sector::get_music_type()
831 Sector::get_total_badguys()
833 int total_badguys = 0;
834 for(GameObjects::iterator i = gameobjects.begin();
835 i != gameobjects.end(); ++i) {
836 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
841 return total_badguys;
845 Sector::inside(const Rectangle& rect) const
847 if(rect.p1.x > solids->get_width() * 32
848 || rect.p1.y > solids->get_height() * 32
849 || rect.p2.x < 0 || rect.p2.y < 0)