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 "object/rock.h"
56 #include "badguy/jumpy.h"
57 #include "badguy/snowball.h"
58 #include "badguy/bouncing_snowball.h"
59 #include "badguy/flame.h"
60 #include "badguy/flyingsnowball.h"
61 #include "badguy/mriceblock.h"
62 #include "badguy/mrbomb.h"
63 #include "badguy/dispenser.h"
64 #include "badguy/spike.h"
65 #include "badguy/spiky.h"
66 #include "badguy/nolok_01.h"
67 #include "trigger/door.h"
68 #include "trigger/sequence_trigger.h"
69 #include "trigger/secretarea_trigger.h"
71 Sector* Sector::_current = 0;
74 : gravity(10), player(0), solids(0), camera(0),
75 currentmusic(LEVEL_MUSIC)
77 song_title = "Mortimers_chipdisko.mod";
78 player = new Player();
81 grid = new CollisionGrid(32000, 32000);
86 update_game_objects();
87 assert(gameobjects_new.size() == 0);
91 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
96 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
105 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
107 if(name == "background") {
108 return new Background(reader);
109 } else if(name == "camera") {
110 Camera* camera = new Camera(this);
111 camera->parse(reader);
113 } else if(name == "tilemap") {
114 return new TileMap(reader);
115 } else if(name == "particles-snow") {
116 SnowParticleSystem* partsys = new SnowParticleSystem();
117 partsys->parse(reader);
119 } else if(name == "particles-clouds") {
120 CloudParticleSystem* partsys = new CloudParticleSystem();
121 partsys->parse(reader);
123 } else if(name == "door") {
124 return new Door(reader);
125 } else if(name == "secretarea") {
126 return new SecretAreaTrigger(reader);
127 } else if(name == "sequencetrigger") {
128 return new SequenceTrigger(reader);
129 } else if(name == "platform") {
130 return new Platform(reader);
131 } else if(name == "jumpy" || name == "money") {
132 return new Jumpy(reader);
133 } else if(name == "snowball") {
134 return new SnowBall(reader);
135 } else if(name == "bouncingsnowball") {
136 return new BouncingSnowball(reader);
137 } else if(name == "flame") {
138 return new Flame(reader);
139 } else if(name == "flyingsnowball") {
140 return new FlyingSnowBall(reader);
141 } else if(name == "mriceblock") {
142 return new MrIceBlock(reader);
143 } else if(name == "mrbomb") {
144 return new MrBomb(reader);
145 } else if(name == "dispenser") {
146 return new Dispenser(reader);
147 } else if(name == "spike") {
148 return new Spike(reader);
149 } else if(name == "spiky") {
150 return new Spiky(reader);
151 } else if(name == "nolok_01") {
152 return new Nolok_01(reader);
153 } else if(name == "rock") {
154 return new Rock(reader);
157 std::cerr << "Unknown object type '" << name << "'.\n";
162 Sector::parse(const lisp::Lisp& sector)
166 lisp::ListIterator iter(§or);
168 const std::string& token = iter.item();
169 if(token == "name") {
170 iter.value()->get(name);
171 } else if(token == "gravity") {
172 iter.value()->get(gravity);
173 } else if(token == "music") {
174 iter.value()->get(song_title);
176 } else if(token == "spawnpoint") {
177 const lisp::Lisp* spawnpoint_lisp = iter.lisp();
179 SpawnPoint* sp = new SpawnPoint;
180 spawnpoint_lisp->get("name", sp->name);
181 spawnpoint_lisp->get("x", sp->pos.x);
182 spawnpoint_lisp->get("y", sp->pos.y);
183 spawnpoints.push_back(sp);
185 GameObject* object = parse_object(token, *(iter.lisp()));
192 update_game_objects();
194 update_game_objects();
196 std::cerr << "sector '" << name << "' does not contain a camera.\n";
197 camera = new Camera(this);
201 throw std::runtime_error("sector does not contain a solid tile layer.");
205 Sector::parse_old_format(const lisp::Lisp& reader)
210 reader.get("gravity", gravity);
212 std::string backgroundimage;
213 reader.get("background", backgroundimage);
215 reader.get("bkgd_speed", bgspeed);
218 Color bkgd_top, bkgd_bottom;
219 int r = 0, g = 0, b = 128;
220 reader.get("bkgd_red_top", r);
221 reader.get("bkgd_green_top", g);
222 reader.get("bkgd_blue_top", b);
227 reader.get("bkgd_red_bottom", r);
228 reader.get("bkgd_green_bottom", g);
229 reader.get("bkgd_blue_bottom", b);
231 bkgd_bottom.green = g;
232 bkgd_bottom.blue = b;
234 if(backgroundimage != "") {
235 Background* background = new Background;
236 background->set_image(backgroundimage, bgspeed);
237 add_object(background);
239 Background* background = new Background;
240 background->set_gradient(bkgd_top, bkgd_bottom);
241 add_object(background);
244 std::string particlesystem;
245 reader.get("particle_system", particlesystem);
246 if(particlesystem == "clouds")
247 add_object(new CloudParticleSystem());
248 else if(particlesystem == "snow")
249 add_object(new SnowParticleSystem());
251 Vector startpos(100, 170);
252 reader.get("start_pos_x", startpos.x);
253 reader.get("start_pos_y", startpos.y);
255 SpawnPoint* spawn = new SpawnPoint;
256 spawn->pos = startpos;
257 spawn->name = "main";
258 spawnpoints.push_back(spawn);
260 song_title = "Mortimers_chipdisko.mod";
261 reader.get("music", song_title);
264 int width, height = 15;
265 reader.get("width", width);
266 reader.get("height", height);
268 std::vector<unsigned int> tiles;
269 if(reader.get_vector("interactive-tm", tiles)
270 || reader.get_vector("tilemap", tiles)) {
271 TileMap* tilemap = new TileMap();
272 tilemap->set(width, height, tiles, LAYER_TILES, true);
276 if(reader.get_vector("background-tm", tiles)) {
277 TileMap* tilemap = new TileMap();
278 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
282 if(reader.get_vector("foreground-tm", tiles)) {
283 TileMap* tilemap = new TileMap();
284 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
288 // read reset-points (now spawn-points)
289 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
291 lisp::ListIterator iter(resetpoints);
293 if(iter.item() == "point") {
295 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
297 SpawnPoint* sp = new SpawnPoint;
300 spawnpoints.push_back(sp);
303 std::cerr << "Unknown token '" << iter.item() << "' in reset-points.\n";
309 const lisp::Lisp* objects = reader.get_lisp("objects");
311 lisp::ListIterator iter(objects);
313 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
317 std::cerr << "Unknown object '" << iter.item() << "' in level.\n";
323 Camera* camera = new Camera(this);
326 update_game_objects();
328 update_game_objects();
330 throw std::runtime_error("sector does not contain a solid tile layer.");
334 Sector::fix_old_tiles()
337 for(size_t x=0; x < solids->get_width(); ++x) {
338 for(size_t y=0; y < solids->get_height(); ++y) {
339 const Tile* tile = solids->get_tile(x, y);
340 Vector pos(x*32, y*32);
342 if(tile->getID() == 112) {
343 add_object(new InvisibleBlock(pos));
344 solids->change(x, y, 0);
345 } else if(tile->getID() == 295) {
346 add_object(new Spike(pos, Spike::NORTH));
347 solids->change(x, y, 0);
348 } else if(tile->getID() == 296) {
349 add_object(new Spike(pos, Spike::EAST));
350 solids->change(x, y, 0);
351 } else if(tile->getID() == 297) {
352 add_object(new Spike(pos, Spike::SOUTH));
353 solids->change(x, y, 0);
354 } else if(tile->getID() == 298) {
355 add_object(new Spike(pos, Spike::WEST));
356 solids->change(x, y, 0);
357 } else if(tile->getAttributes() & Tile::COIN) {
358 add_object(new Coin(pos));
359 solids->change(x, y, 0);
360 } else if(tile->getAttributes() & Tile::FULLBOX) {
361 add_object(new BonusBlock(pos, tile->getData()));
362 solids->change(x, y, 0);
363 } else if(tile->getAttributes() & Tile::BRICK) {
364 add_object(new Brick(pos, tile->getData()));
365 solids->change(x, y, 0);
366 } else if(tile->getAttributes() & Tile::GOAL) {
367 add_object(new SequenceTrigger(pos, "endsequence"));
368 solids->change(x, y, 0);
375 Sector::write(lisp::Writer& writer)
377 writer.write_string("name", name);
378 writer.write_float("gravity", gravity);
379 writer.write_string("music", song_title);
382 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
384 SpawnPoint* spawn = *i;
385 writer.start_list("spawn-points");
386 writer.write_string("name", spawn->name);
387 writer.write_float("x", spawn->pos.x);
388 writer.write_float("y", spawn->pos.y);
389 writer.end_list("spawn-points");
393 for(GameObjects::iterator i = gameobjects.begin();
394 i != gameobjects.end(); ++i) {
395 Serializable* serializable = dynamic_cast<Serializable*> (*i);
397 serializable->write(writer);
402 Sector::add_object(GameObject* object)
404 // make sure the object isn't already in the list
406 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
409 assert("object already added to sector" == 0);
412 for(GameObjects::iterator i = gameobjects_new.begin();
413 i != gameobjects_new.end(); ++i) {
415 assert("object already added to sector" == 0);
420 gameobjects_new.push_back(object);
424 Sector::activate(const std::string& spawnpoint)
428 // Apply bonuses from former levels
429 switch (player_status.bonus)
431 case PlayerStatus::NO_BONUS:
434 case PlayerStatus::FLOWER_BONUS:
435 player->got_power = Player::FIRE_POWER; // FIXME: add ice power to here
438 case PlayerStatus::GROWUP_BONUS:
444 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
446 if((*i)->name == spawnpoint) {
452 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
454 player->move(sp->pos);
457 camera->reset(player->get_pos());
461 Sector::get_best_spawn_point(Vector pos)
463 Vector best_reset_point = Vector(-1,-1);
465 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
467 if((*i)->name != "main")
469 if((*i)->pos.x > best_reset_point.x && (*i)->pos.x < pos.x)
470 best_reset_point = (*i)->pos;
473 return best_reset_point;
477 Sector::get_active_region()
480 camera->get_translation() - Vector(1600, 1200),
481 camera->get_translation() + Vector(1600, 1200));
485 Sector::action(float elapsed_time)
487 player->check_bounds(camera);
490 CollisionGridIterator iter(*grid, get_active_region());
491 while(MovingObject* object = iter.next()) {
492 if(!object->is_valid())
495 object->action(elapsed_time);
499 for(GameObjects::iterator i = gameobjects.begin();
500 i != gameobjects.end(); ++i) {
501 GameObject* object = *i;
502 if(!object->is_valid())
505 object->action(elapsed_time);
509 /* Handle all possible collisions. */
511 update_game_objects();
515 Sector::update_game_objects()
517 /** cleanup marked objects */
518 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
519 i != gameobjects.end(); /* nothing */) {
520 GameObject* object = *i;
522 if(object->is_valid()) {
527 Bullet* bullet = dynamic_cast<Bullet*> (object);
530 std::remove(bullets.begin(), bullets.end(), bullet),
533 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
535 grid->remove_object(movingobject);
538 i = gameobjects.erase(i);
541 /* add newly created objects */
542 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
543 i != gameobjects_new.end(); ++i)
545 GameObject* object = *i;
547 Bullet* bullet = dynamic_cast<Bullet*> (object);
549 bullets.push_back(bullet);
551 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
553 grid->add_object(movingobject);
555 TileMap* tilemap = dynamic_cast<TileMap*> (object);
556 if(tilemap && tilemap->is_solid()) {
560 std::cerr << "Another solid tilemaps added. Ignoring.";
564 Camera* camera = dynamic_cast<Camera*> (object);
566 if(this->camera != 0) {
567 std::cerr << "Warning: Multiple cameras added. Ignoring.";
570 this->camera = camera;
573 gameobjects.push_back(object);
575 gameobjects_new.clear();
579 Sector::draw(DrawingContext& context)
581 context.push_transform();
582 context.set_translation(camera->get_translation());
585 CollisionGridIterator iter(*grid, get_active_region());
586 while(MovingObject* object = iter.next()) {
587 if(!object->is_valid())
590 object->draw(context);
593 for(GameObjects::iterator i = gameobjects.begin();
594 i != gameobjects.end(); ++i) {
595 GameObject* object = *i;
596 if(!object->is_valid())
599 object->draw(context);
603 context.pop_transform();
606 static const float DELTA = .001;
609 Sector::collision_tilemap(MovingObject* object, int depth)
613 std::cout << "Max collision depth reached.\n";
615 object->movement = Vector(0, 0);
619 // calculate rectangle where the object will move
621 if(object->get_movement().x >= 0) {
622 x1 = object->get_pos().x;
623 x2 = object->get_bbox().p2.x + object->get_movement().x;
625 x1 = object->get_pos().x + object->get_movement().x;
626 x2 = object->get_bbox().p2.x;
629 if(object->get_movement().y >= 0) {
630 y1 = object->get_pos().y;
631 y2 = object->get_bbox().p2.y + object->get_movement().y;
633 y1 = object->get_pos().y + object->get_movement().y;
634 y2 = object->get_bbox().p2.y;
637 // test with all tiles in this rectangle
638 int starttilex = int(x1-1) / 32;
639 int starttiley = int(y1-1) / 32;
640 int max_x = int(x2+1);
641 int max_y = int(y2+1);
643 CollisionHit temphit, hit;
644 Rectangle dest = object->get_bbox();
645 dest.move(object->movement);
646 hit.time = -1; // represents an invalid value
647 for(int x = starttilex; x*32 < max_x; ++x) {
648 for(int y = starttiley; y*32 < max_y; ++y) {
649 const Tile* tile = solids->get_tile(x, y);
652 if(!(tile->getAttributes() & Tile::SOLID))
654 if((tile->getAttributes() & Tile::UNISOLID) && object->movement.y < 0)
657 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
659 Vector p1(x*32, y*32);
660 Vector p2((x+1)*32, (y+1)*32);
661 triangle = AATriangle(p1, p2, tile->getData());
663 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
665 if(temphit.time > hit.time)
668 } else { // normal rectangular tile
669 Rectangle rect(x*32, y*32, (x+1)*32, (y+1)*32);
670 if(Collision::rectangle_rectangle(temphit, dest,
671 object->movement, rect)) {
672 if(temphit.time > hit.time)
679 // did we collide at all?
683 // call collision function
684 HitResponse response = object->collision(*solids, hit);
685 if(response == ABORT_MOVE) {
686 object->movement = Vector(0, 0);
689 if(response == FORCE_MOVE) {
692 // move out of collision and try again
693 object->movement += hit.normal * (hit.depth + DELTA);
694 collision_tilemap(object, depth+1);
698 Sector::collision_object(MovingObject* object1, MovingObject* object2)
701 Rectangle dest1 = object1->get_bbox();
702 dest1.move(object1->get_movement());
703 Rectangle dest2 = object2->get_bbox();
704 dest2.move(object2->get_movement());
706 Vector movement = object1->get_movement() - object2->get_movement();
707 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
708 HitResponse response1 = object1->collision(*object2, hit);
710 HitResponse response2 = object2->collision(*object1, hit);
712 if(response1 != CONTINUE) {
713 if(response1 == ABORT_MOVE)
714 object1->movement = Vector(0, 0);
715 if(response2 == CONTINUE)
716 object2->movement += hit.normal * (hit.depth + DELTA);
717 } else if(response2 != CONTINUE) {
718 if(response2 == ABORT_MOVE)
719 object2->movement = Vector(0, 0);
720 if(response1 == CONTINUE)
721 object1->movement += -hit.normal * (hit.depth + DELTA);
723 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
724 object2->movement += hit.normal * (hit.depth/2 + DELTA);
730 Sector::collision_handler()
733 grid->check_collisions();
735 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
736 i != gameobjects.end(); ++i) {
737 GameObject* gameobject = *i;
738 if(!gameobject->is_valid())
740 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
743 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
744 movingobject->bbox.move(movingobject->movement);
745 movingobject->movement = Vector(0, 0);
749 // collision with tilemap
750 if(! (movingobject->movement == Vector(0, 0)))
751 collision_tilemap(movingobject, 0);
753 // collision with other objects
754 for(std::vector<GameObject*>::iterator i2 = i+1;
755 i2 != gameobjects.end(); ++i2) {
756 GameObject* other_object = *i2;
757 if(!other_object->is_valid()
758 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
760 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
764 collision_object(movingobject, movingobject2);
767 movingobject->bbox.move(movingobject->get_movement());
768 movingobject->movement = Vector(0, 0);
774 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
776 if(player->got_power == Player::FIRE_POWER) {
777 if(bullets.size() > MAX_FIRE_BULLETS-1)
779 } else if(player->got_power == Player::ICE_POWER) {
780 if(bullets.size() > MAX_ICE_BULLETS-1)
784 Bullet* new_bullet = 0;
785 if(player->got_power == Player::FIRE_POWER)
786 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
787 else if(player->got_power == Player::ICE_POWER)
788 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
790 throw std::runtime_error("wrong bullet type.");
791 add_object(new_bullet);
793 SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
799 Sector::add_smoke_cloud(const Vector& pos)
801 add_object(new SmokeCloud(pos));
806 Sector::add_floating_text(const Vector& pos, const std::string& text)
808 add_object(new FloatingText(pos, text));
817 level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
819 song_path = (char *) malloc(sizeof(char) * datadir.length() +
820 strlen(song_title.c_str()) + 8 + 5);
821 song_subtitle = strdup(song_title.c_str());
822 strcpy(strstr(song_subtitle, "."), "\0");
823 sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
824 song_subtitle, strstr(song_title.c_str(), "."));
825 if(!SoundManager::get()->exists_music(song_path)) {
826 level_song_fast = level_song;
828 level_song_fast = SoundManager::get()->load_music(song_path);
835 Sector::play_music(int type)
838 switch(currentmusic) {
840 SoundManager::get()->play_music(level_song_fast);
843 SoundManager::get()->play_music(level_song);
846 SoundManager::get()->play_music(herring_song);
849 SoundManager::get()->halt_music();
855 Sector::get_music_type()
861 Sector::get_total_badguys()
863 int total_badguys = 0;
865 for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
867 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
872 return total_badguys;
876 Sector::inside(const Rectangle& rect) const
878 if(rect.p1.x > solids->get_width() * 32
879 || rect.p1.y > solids->get_height() * 32
880 || rect.p2.x < 0 || rect.p2.y < 0)