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 "special/collision.h"
48 #include "math/rectangle.h"
49 #include "math/aatriangle.h"
50 #include "object/coin.h"
51 #include "object/block.h"
52 #include "object/invisible_block.h"
53 #include "object/platform.h"
54 #include "object/bullet.h"
55 #include "badguy/jumpy.h"
56 #include "badguy/snowball.h"
57 #include "badguy/bouncing_snowball.h"
58 #include "badguy/flame.h"
59 #include "badguy/flyingsnowball.h"
60 #include "badguy/mriceblock.h"
61 #include "badguy/mrbomb.h"
62 #include "badguy/dispenser.h"
63 #include "badguy/spike.h"
64 #include "badguy/spiky.h"
65 #include "badguy/nolok_01.h"
66 #include "trigger/door.h"
67 #include "trigger/sequence_trigger.h"
68 #include "trigger/secretarea_trigger.h"
70 Sector* Sector::_current = 0;
73 : gravity(10), player(0), solids(0), camera(0),
74 currentmusic(LEVEL_MUSIC)
76 song_title = "Mortimers_chipdisko.mod";
77 player = new Player();
80 grid = new CollisionGrid(32000, 32000);
85 update_game_objects();
86 assert(gameobjects_new.size() == 0);
90 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
95 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
104 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
106 if(name == "background") {
107 return new Background(reader);
108 } else if(name == "camera") {
109 Camera* camera = new Camera(this);
110 camera->parse(reader);
112 } else if(name == "tilemap") {
113 return new TileMap(reader);
114 } else if(name == "particles-snow") {
115 SnowParticleSystem* partsys = new SnowParticleSystem();
116 partsys->parse(reader);
118 } else if(name == "particles-clouds") {
119 CloudParticleSystem* partsys = new CloudParticleSystem();
120 partsys->parse(reader);
122 } else if(name == "door") {
123 return new Door(reader);
124 } else if(name == "secretarea") {
125 return new SecretAreaTrigger(reader);
126 } else if(name == "sequencetrigger") {
127 return new SequenceTrigger(reader);
128 } else if(name == "platform") {
129 return new Platform(reader);
130 } else if(name == "jumpy" || name == "money") {
131 return new Jumpy(reader);
132 } else if(name == "snowball") {
133 return new SnowBall(reader);
134 } else if(name == "bouncingsnowball") {
135 return new BouncingSnowball(reader);
136 } else if(name == "flame") {
137 return new Flame(reader);
138 } else if(name == "flyingsnowball") {
139 return new FlyingSnowBall(reader);
140 } else if(name == "mriceblock") {
141 return new MrIceBlock(reader);
142 } else if(name == "mrbomb") {
143 return new MrBomb(reader);
144 } else if(name == "dispenser") {
145 return new Dispenser(reader);
146 } else if(name == "spike") {
147 return new Spike(reader);
148 } else if(name == "spiky") {
149 return new Spiky(reader);
150 } else if(name == "nolok_01") {
151 return new Nolok_01(reader);
154 std::cerr << "Unknown object type '" << name << "'.\n";
159 Sector::parse(const lisp::Lisp& sector)
163 lisp::ListIterator iter(§or);
165 const std::string& token = iter.item();
166 if(token == "name") {
167 iter.value()->get(name);
168 } else if(token == "gravity") {
169 iter.value()->get(gravity);
170 } else if(token == "music") {
171 iter.value()->get(song_title);
173 } else if(token == "spawnpoint") {
174 const lisp::Lisp* spawnpoint_lisp = iter.lisp();
176 SpawnPoint* sp = new SpawnPoint;
177 spawnpoint_lisp->get("name", sp->name);
178 spawnpoint_lisp->get("x", sp->pos.x);
179 spawnpoint_lisp->get("y", sp->pos.y);
180 spawnpoints.push_back(sp);
182 GameObject* object = parse_object(token, *(iter.lisp()));
189 update_game_objects();
191 update_game_objects();
193 std::cerr << "sector '" << name << "' does not contain a camera.\n";
194 camera = new Camera(this);
198 throw std::runtime_error("sector does not contain a solid tile layer.");
202 Sector::parse_old_format(const lisp::Lisp& reader)
207 reader.get("gravity", gravity);
209 std::string backgroundimage;
210 reader.get("background", backgroundimage);
212 reader.get("bkgd_speed", bgspeed);
215 Color bkgd_top, bkgd_bottom;
216 int r = 0, g = 0, b = 128;
217 reader.get("bkgd_red_top", r);
218 reader.get("bkgd_green_top", g);
219 reader.get("bkgd_blue_top", b);
224 reader.get("bkgd_red_bottom", r);
225 reader.get("bkgd_green_bottom", g);
226 reader.get("bkgd_blue_bottom", b);
228 bkgd_bottom.green = g;
229 bkgd_bottom.blue = b;
231 if(backgroundimage != "") {
232 Background* background = new Background;
233 background->set_image(backgroundimage, bgspeed);
234 add_object(background);
236 Background* background = new Background;
237 background->set_gradient(bkgd_top, bkgd_bottom);
238 add_object(background);
241 std::string particlesystem;
242 reader.get("particle_system", particlesystem);
243 if(particlesystem == "clouds")
244 add_object(new CloudParticleSystem());
245 else if(particlesystem == "snow")
246 add_object(new SnowParticleSystem());
248 Vector startpos(100, 170);
249 reader.get("start_pos_x", startpos.x);
250 reader.get("start_pos_y", startpos.y);
252 SpawnPoint* spawn = new SpawnPoint;
253 spawn->pos = startpos;
254 spawn->name = "main";
255 spawnpoints.push_back(spawn);
257 song_title = "Mortimers_chipdisko.mod";
258 reader.get("music", song_title);
261 int width, height = 15;
262 reader.get("width", width);
263 reader.get("height", height);
265 std::vector<unsigned int> tiles;
266 if(reader.get_vector("interactive-tm", tiles)
267 || reader.get_vector("tilemap", tiles)) {
268 TileMap* tilemap = new TileMap();
269 tilemap->set(width, height, tiles, LAYER_TILES, true);
273 if(reader.get_vector("background-tm", tiles)) {
274 TileMap* tilemap = new TileMap();
275 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
279 if(reader.get_vector("foreground-tm", tiles)) {
280 TileMap* tilemap = new TileMap();
281 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
285 // read reset-points (now spawn-points)
286 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
288 lisp::ListIterator iter(resetpoints);
290 if(iter.item() == "point") {
292 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
294 SpawnPoint* sp = new SpawnPoint;
297 spawnpoints.push_back(sp);
300 std::cerr << "Unknown token '" << iter.item() << "' in reset-points.\n";
306 const lisp::Lisp* objects = reader.get_lisp("objects");
308 lisp::ListIterator iter(objects);
310 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
314 std::cerr << "Unknown object '" << iter.item() << "' in level.\n";
320 Camera* camera = new Camera(this);
323 update_game_objects();
325 update_game_objects();
327 throw std::runtime_error("sector does not contain a solid tile layer.");
331 Sector::fix_old_tiles()
334 for(size_t x=0; x < solids->get_width(); ++x) {
335 for(size_t y=0; y < solids->get_height(); ++y) {
336 const Tile* tile = solids->get_tile(x, y);
337 Vector pos(x*32, y*32);
339 if(tile->getID() == 112) {
340 add_object(new InvisibleBlock(pos));
341 solids->change(x, y, 0);
342 } else if(tile->getID() == 295) {
343 add_object(new Spike(pos, Spike::NORTH));
344 solids->change(x, y, 0);
345 } else if(tile->getID() == 296) {
346 add_object(new Spike(pos, Spike::EAST));
347 solids->change(x, y, 0);
348 } else if(tile->getID() == 297) {
349 add_object(new Spike(pos, Spike::SOUTH));
350 solids->change(x, y, 0);
351 } else if(tile->getID() == 298) {
352 add_object(new Spike(pos, Spike::WEST));
353 solids->change(x, y, 0);
354 } else if(tile->getAttributes() & Tile::COIN) {
355 add_object(new Coin(pos));
356 solids->change(x, y, 0);
357 } else if(tile->getAttributes() & Tile::FULLBOX) {
358 add_object(new BonusBlock(pos, tile->getData()));
359 solids->change(x, y, 0);
360 } else if(tile->getAttributes() & Tile::BRICK) {
361 add_object(new Brick(pos, tile->getData()));
362 solids->change(x, y, 0);
363 } else if(tile->getAttributes() & Tile::GOAL) {
364 add_object(new SequenceTrigger(pos, "endsequence"));
365 solids->change(x, y, 0);
372 Sector::write(lisp::Writer& writer)
374 writer.write_string("name", name);
375 writer.write_float("gravity", gravity);
376 writer.write_string("music", song_title);
379 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
381 SpawnPoint* spawn = *i;
382 writer.start_list("spawn-points");
383 writer.write_string("name", spawn->name);
384 writer.write_float("x", spawn->pos.x);
385 writer.write_float("y", spawn->pos.y);
386 writer.end_list("spawn-points");
390 for(GameObjects::iterator i = gameobjects.begin();
391 i != gameobjects.end(); ++i) {
392 Serializable* serializable = dynamic_cast<Serializable*> (*i);
394 serializable->write(writer);
399 Sector::add_object(GameObject* object)
401 // make sure the object isn't already in the list
403 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
406 assert("object already added to sector" == 0);
409 for(GameObjects::iterator i = gameobjects_new.begin();
410 i != gameobjects_new.end(); ++i) {
412 assert("object already added to sector" == 0);
417 gameobjects_new.push_back(object);
421 Sector::activate(const std::string& spawnpoint)
425 // Apply bonuses from former levels
426 switch (player_status.bonus)
428 case PlayerStatus::NO_BONUS:
431 case PlayerStatus::FLOWER_BONUS:
432 player->got_power = Player::FIRE_POWER; // FIXME: add ice power to here
435 case PlayerStatus::GROWUP_BONUS:
441 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
443 if((*i)->name == spawnpoint) {
449 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
451 player->move(sp->pos);
454 camera->reset(player->get_pos());
458 Sector::get_best_spawn_point(Vector pos)
460 Vector best_reset_point = Vector(-1,-1);
462 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
464 if((*i)->name != "main")
466 if((*i)->pos.x > best_reset_point.x && (*i)->pos.x < pos.x)
467 best_reset_point = (*i)->pos;
470 return best_reset_point;
474 Sector::get_active_region()
477 camera->get_translation() - Vector(1600, 1200),
478 camera->get_translation() + Vector(1600, 1200));
482 Sector::action(float elapsed_time)
484 player->check_bounds(camera);
487 CollisionGridIterator iter(*grid, get_active_region());
488 while(MovingObject* object = iter.next()) {
489 if(!object->is_valid())
492 object->action(elapsed_time);
496 for(GameObjects::iterator i = gameobjects.begin();
497 i != gameobjects.end(); ++i) {
498 GameObject* object = *i;
499 if(!object->is_valid())
502 object->action(elapsed_time);
506 /* Handle all possible collisions. */
508 update_game_objects();
512 Sector::update_game_objects()
514 /** cleanup marked objects */
515 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
516 i != gameobjects.end(); /* nothing */) {
517 GameObject* object = *i;
519 if(object->is_valid()) {
524 Bullet* bullet = dynamic_cast<Bullet*> (object);
527 std::remove(bullets.begin(), bullets.end(), bullet),
530 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
532 grid->remove_object(movingobject);
535 i = gameobjects.erase(i);
538 /* add newly created objects */
539 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
540 i != gameobjects_new.end(); ++i)
542 GameObject* object = *i;
544 Bullet* bullet = dynamic_cast<Bullet*> (object);
546 bullets.push_back(bullet);
548 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
550 grid->add_object(movingobject);
552 TileMap* tilemap = dynamic_cast<TileMap*> (object);
553 if(tilemap && tilemap->is_solid()) {
557 std::cerr << "Another solid tilemaps added. Ignoring.";
561 Camera* camera = dynamic_cast<Camera*> (object);
563 if(this->camera != 0) {
564 std::cerr << "Warning: Multiple cameras added. Ignoring.";
567 this->camera = camera;
570 gameobjects.push_back(object);
572 gameobjects_new.clear();
576 Sector::draw(DrawingContext& context)
578 context.push_transform();
579 context.set_translation(camera->get_translation());
582 CollisionGridIterator iter(*grid, get_active_region());
583 while(MovingObject* object = iter.next()) {
584 if(!object->is_valid())
587 object->draw(context);
590 for(GameObjects::iterator i = gameobjects.begin();
591 i != gameobjects.end(); ++i) {
592 GameObject* object = *i;
593 if(!object->is_valid())
596 object->draw(context);
600 context.pop_transform();
603 static const float DELTA = .001;
606 Sector::collision_tilemap(MovingObject* object, int depth)
610 std::cout << "Max collision depth reached.\n";
612 object->movement = Vector(0, 0);
616 // calculate rectangle where the object will move
618 if(object->get_movement().x >= 0) {
619 x1 = object->get_pos().x;
620 x2 = object->get_bbox().p2.x + object->get_movement().x;
622 x1 = object->get_pos().x + object->get_movement().x;
623 x2 = object->get_bbox().p2.x;
626 if(object->get_movement().y >= 0) {
627 y1 = object->get_pos().y;
628 y2 = object->get_bbox().p2.y + object->get_movement().y;
630 y1 = object->get_pos().y + object->get_movement().y;
631 y2 = object->get_bbox().p2.y;
634 // test with all tiles in this rectangle
635 int starttilex = int(x1-1) / 32;
636 int starttiley = int(y1-1) / 32;
637 int max_x = int(x2+1);
638 int max_y = int(y2+1);
640 CollisionHit temphit, hit;
641 Rectangle dest = object->get_bbox();
642 dest.move(object->movement);
643 hit.time = -1; // represents an invalid value
644 for(int x = starttilex; x*32 < max_x; ++x) {
645 for(int y = starttiley; y*32 < max_y; ++y) {
646 const Tile* tile = solids->get_tile(x, y);
649 if(!(tile->getAttributes() & Tile::SOLID))
651 if((tile->getAttributes() & Tile::UNISOLID) && object->movement.y < 0)
654 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
656 Vector p1(x*32, y*32);
657 Vector p2((x+1)*32, (y+1)*32);
658 triangle = AATriangle(p1, p2, tile->getData());
660 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
662 if(temphit.time > hit.time)
665 } else { // normal rectangular tile
666 Rectangle rect(x*32, y*32, (x+1)*32, (y+1)*32);
667 if(Collision::rectangle_rectangle(temphit, dest,
668 object->movement, rect)) {
669 if(temphit.time > hit.time)
676 // did we collide at all?
680 // call collision function
681 HitResponse response = object->collision(*solids, hit);
682 if(response == ABORT_MOVE) {
683 object->movement = Vector(0, 0);
686 if(response == FORCE_MOVE) {
689 // move out of collision and try again
690 object->movement += hit.normal * (hit.depth + DELTA);
691 collision_tilemap(object, depth+1);
695 Sector::collision_object(MovingObject* object1, MovingObject* object2)
698 Rectangle dest1 = object1->get_bbox();
699 dest1.move(object1->get_movement());
700 Rectangle dest2 = object2->get_bbox();
701 dest2.move(object2->get_movement());
703 Vector movement = object1->get_movement() - object2->get_movement();
704 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
705 HitResponse response1 = object1->collision(*object2, hit);
707 HitResponse response2 = object2->collision(*object1, hit);
709 if(response1 != CONTINUE) {
710 if(response1 == ABORT_MOVE)
711 object1->movement = Vector(0, 0);
712 if(response2 == CONTINUE)
713 object2->movement += hit.normal * (hit.depth + DELTA);
714 } else if(response2 != CONTINUE) {
715 if(response2 == ABORT_MOVE)
716 object2->movement = Vector(0, 0);
717 if(response1 == CONTINUE)
718 object1->movement += -hit.normal * (hit.depth + DELTA);
720 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
721 object2->movement += hit.normal * (hit.depth/2 + DELTA);
727 Sector::collision_handler()
730 grid->check_collisions();
732 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
733 i != gameobjects.end(); ++i) {
734 GameObject* gameobject = *i;
735 if(!gameobject->is_valid())
737 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
740 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
741 movingobject->bbox.move(movingobject->movement);
742 movingobject->movement = Vector(0, 0);
746 // collision with tilemap
747 if(! (movingobject->movement == Vector(0, 0)))
748 collision_tilemap(movingobject, 0);
750 // collision with other objects
751 for(std::vector<GameObject*>::iterator i2 = i+1;
752 i2 != gameobjects.end(); ++i2) {
753 GameObject* other_object = *i2;
754 if(!other_object->is_valid()
755 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
757 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
761 collision_object(movingobject, movingobject2);
764 movingobject->bbox.move(movingobject->get_movement());
765 movingobject->movement = Vector(0, 0);
771 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
773 if(player->got_power == Player::FIRE_POWER) {
774 if(bullets.size() > MAX_FIRE_BULLETS-1)
776 } else if(player->got_power == Player::ICE_POWER) {
777 if(bullets.size() > MAX_ICE_BULLETS-1)
781 Bullet* new_bullet = 0;
782 if(player->got_power == Player::FIRE_POWER)
783 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
784 else if(player->got_power == Player::ICE_POWER)
785 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
787 throw std::runtime_error("wrong bullet type.");
788 add_object(new_bullet);
790 SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
796 Sector::add_smoke_cloud(const Vector& pos)
798 add_object(new SmokeCloud(pos));
803 Sector::add_floating_text(const Vector& pos, const std::string& text)
805 add_object(new FloatingText(pos, text));
814 level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
816 song_path = (char *) malloc(sizeof(char) * datadir.length() +
817 strlen(song_title.c_str()) + 8 + 5);
818 song_subtitle = strdup(song_title.c_str());
819 strcpy(strstr(song_subtitle, "."), "\0");
820 sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
821 song_subtitle, strstr(song_title.c_str(), "."));
822 if(!SoundManager::get()->exists_music(song_path)) {
823 level_song_fast = level_song;
825 level_song_fast = SoundManager::get()->load_music(song_path);
832 Sector::play_music(int type)
835 switch(currentmusic) {
837 SoundManager::get()->play_music(level_song_fast);
840 SoundManager::get()->play_music(level_song);
843 SoundManager::get()->play_music(herring_song);
846 SoundManager::get()->halt_music();
852 Sector::get_music_type()
858 Sector::get_total_badguys()
860 int total_badguys = 0;
862 for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
864 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
869 return total_badguys;
873 Sector::inside(const Rectangle& rect) const
875 if(rect.p1.x > solids->get_width() * 32
876 || rect.p1.y > solids->get_height() * 32
877 || rect.p2.x < 0 || rect.p2.y < 0)