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"
59 #include "player_status.h"
63 Sector* Sector::_current = 0;
66 : gravity(10), player(0), solids(0), camera(0),
67 currentmusic(LEVEL_MUSIC)
69 song_title = "Mortimers_chipdisko.mod";
70 player = new Player(&player_status);
73 grid = new CollisionGrid(32000, 32000);
78 update_game_objects();
79 assert(gameobjects_new.size() == 0);
83 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
88 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
97 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
99 if(name == "camera") {
100 Camera* camera = new Camera(this);
101 camera->parse(reader);
103 } else if(name == "particles-snow") {
104 SnowParticleSystem* partsys = new SnowParticleSystem();
105 partsys->parse(reader);
107 } else if(name == "particles-rain") {
108 RainParticleSystem* partsys = new RainParticleSystem();
109 partsys->parse(reader);
111 } else if(name == "particles-clouds") {
112 CloudParticleSystem* partsys = new CloudParticleSystem();
113 partsys->parse(reader);
115 } else if(name == "money") { // for compatibility with old maps
116 return new Jumpy(reader);
120 return create_object(name, reader);
121 } catch(std::exception& e) {
122 std::cerr << e.what() << "\n";
129 Sector::parse(const lisp::Lisp& sector)
133 lisp::ListIterator iter(§or);
135 const std::string& token = iter.item();
136 if(token == "name") {
137 iter.value()->get(name);
138 } else if(token == "gravity") {
139 iter.value()->get(gravity);
140 } else if(token == "music") {
141 iter.value()->get(song_title);
143 } else if(token == "spawnpoint") {
144 const lisp::Lisp* spawnpoint_lisp = iter.lisp();
146 SpawnPoint* sp = new SpawnPoint;
147 spawnpoint_lisp->get("name", sp->name);
148 spawnpoint_lisp->get("x", sp->pos.x);
149 spawnpoint_lisp->get("y", sp->pos.y);
150 spawnpoints.push_back(sp);
152 GameObject* object = parse_object(token, *(iter.lisp()));
159 update_game_objects();
162 std::cerr << "sector '" << name << "' does not contain a camera.\n";
163 update_game_objects();
164 add_object(new Camera(this));
167 throw std::runtime_error("sector does not contain a solid tile layer.");
169 update_game_objects();
173 Sector::parse_old_format(const lisp::Lisp& reader)
178 reader.get("gravity", gravity);
180 std::string backgroundimage;
181 reader.get("background", backgroundimage);
183 reader.get("bkgd_speed", bgspeed);
186 Color bkgd_top, bkgd_bottom;
187 int r = 0, g = 0, b = 128;
188 reader.get("bkgd_red_top", r);
189 reader.get("bkgd_green_top", g);
190 reader.get("bkgd_blue_top", b);
195 reader.get("bkgd_red_bottom", r);
196 reader.get("bkgd_green_bottom", g);
197 reader.get("bkgd_blue_bottom", b);
199 bkgd_bottom.green = g;
200 bkgd_bottom.blue = b;
202 if(backgroundimage != "") {
203 Background* background = new Background;
204 background->set_image(backgroundimage, bgspeed);
205 add_object(background);
207 Background* background = new Background;
208 background->set_gradient(bkgd_top, bkgd_bottom);
209 add_object(background);
212 std::string particlesystem;
213 reader.get("particle_system", particlesystem);
214 if(particlesystem == "clouds")
215 add_object(new CloudParticleSystem());
216 else if(particlesystem == "snow")
217 add_object(new SnowParticleSystem());
218 else if(particlesystem == "rain")
219 add_object(new RainParticleSystem());
221 Vector startpos(100, 170);
222 reader.get("start_pos_x", startpos.x);
223 reader.get("start_pos_y", startpos.y);
225 SpawnPoint* spawn = new SpawnPoint;
226 spawn->pos = startpos;
227 spawn->name = "main";
228 spawnpoints.push_back(spawn);
230 song_title = "Mortimers_chipdisko.mod";
231 reader.get("music", song_title);
234 int width, height = 15;
235 reader.get("width", width);
236 reader.get("height", height);
238 std::vector<unsigned int> tiles;
239 if(reader.get_vector("interactive-tm", tiles)
240 || reader.get_vector("tilemap", tiles)) {
241 TileMap* tilemap = new TileMap();
242 tilemap->set(width, height, tiles, LAYER_TILES, true);
246 if(reader.get_vector("background-tm", tiles)) {
247 TileMap* tilemap = new TileMap();
248 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
252 if(reader.get_vector("foreground-tm", tiles)) {
253 TileMap* tilemap = new TileMap();
254 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
258 // read reset-points (now spawn-points)
259 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
261 lisp::ListIterator iter(resetpoints);
263 if(iter.item() == "point") {
265 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
267 SpawnPoint* sp = new SpawnPoint;
270 spawnpoints.push_back(sp);
273 std::cerr << "Unknown token '" << iter.item() << "' in reset-points.\n";
279 const lisp::Lisp* objects = reader.get_lisp("objects");
281 lisp::ListIterator iter(objects);
283 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
287 std::cerr << "Unknown object '" << iter.item() << "' in level.\n";
293 Camera* camera = new Camera(this);
296 update_game_objects();
298 update_game_objects();
300 throw std::runtime_error("sector does not contain a solid tile layer.");
304 Sector::fix_old_tiles()
307 for(size_t x=0; x < solids->get_width(); ++x) {
308 for(size_t y=0; y < solids->get_height(); ++y) {
309 const Tile* tile = solids->get_tile(x, y);
310 Vector pos(x*32, y*32);
312 if(tile->getID() == 112) {
313 add_object(new InvisibleBlock(pos));
314 solids->change(x, y, 0);
315 } else if(tile->getID() == 295) {
316 add_object(new Spike(pos, Spike::NORTH));
317 solids->change(x, y, 0);
318 } else if(tile->getID() == 296) {
319 add_object(new Spike(pos, Spike::EAST));
320 solids->change(x, y, 0);
321 } else if(tile->getID() == 297) {
322 add_object(new Spike(pos, Spike::SOUTH));
323 solids->change(x, y, 0);
324 } else if(tile->getID() == 298) {
325 add_object(new Spike(pos, Spike::WEST));
326 solids->change(x, y, 0);
327 } else if(tile->getAttributes() & Tile::COIN) {
328 add_object(new Coin(pos));
329 solids->change(x, y, 0);
330 } else if(tile->getAttributes() & Tile::FULLBOX) {
331 add_object(new BonusBlock(pos, tile->getData()));
332 solids->change(x, y, 0);
333 } else if(tile->getAttributes() & Tile::BRICK) {
334 add_object(new Brick(pos, tile->getData()));
335 solids->change(x, y, 0);
336 } else if(tile->getAttributes() & Tile::GOAL) {
337 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
338 add_object(new SequenceTrigger(pos, sequence));
339 solids->change(x, y, 0);
346 Sector::write(lisp::Writer& writer)
348 writer.write_string("name", name);
349 writer.write_float("gravity", gravity);
350 writer.write_string("music", song_title);
353 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
355 SpawnPoint* spawn = *i;
356 writer.start_list("spawn-points");
357 writer.write_string("name", spawn->name);
358 writer.write_float("x", spawn->pos.x);
359 writer.write_float("y", spawn->pos.y);
360 writer.end_list("spawn-points");
364 for(GameObjects::iterator i = gameobjects.begin();
365 i != gameobjects.end(); ++i) {
366 Serializable* serializable = dynamic_cast<Serializable*> (*i);
368 serializable->write(writer);
373 Sector::add_object(GameObject* object)
375 // make sure the object isn't already in the list
377 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
380 assert("object already added to sector" == 0);
383 for(GameObjects::iterator i = gameobjects_new.begin();
384 i != gameobjects_new.end(); ++i) {
386 assert("object already added to sector" == 0);
391 gameobjects_new.push_back(object);
395 Sector::activate(const std::string& spawnpoint)
398 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
400 if((*i)->name == spawnpoint) {
406 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
407 if(spawnpoint != "main") {
410 activate(Vector(0, 0));
418 Sector::activate(const Vector& player_pos)
422 player->move(player_pos);
423 camera->reset(player->get_pos());
427 Sector::get_active_region()
430 camera->get_translation() - Vector(1600, 1200),
431 camera->get_translation() + Vector(1600, 1200));
435 Sector::action(float elapsed_time)
437 player->check_bounds(camera);
440 CollisionGridIterator iter(*grid, get_active_region());
441 while(MovingObject* object = iter.next()) {
442 if(!object->is_valid())
445 object->action(elapsed_time);
449 for(GameObjects::iterator i = gameobjects.begin();
450 i != gameobjects.end(); ++i) {
451 GameObject* object = *i;
452 if(!object->is_valid())
455 object->action(elapsed_time);
459 /* Handle all possible collisions. */
461 update_game_objects();
465 Sector::update_game_objects()
467 /** cleanup marked objects */
468 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
469 i != gameobjects.end(); /* nothing */) {
470 GameObject* object = *i;
472 if(object->is_valid()) {
477 Bullet* bullet = dynamic_cast<Bullet*> (object);
480 std::remove(bullets.begin(), bullets.end(), bullet),
483 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
485 grid->remove_object(movingobject);
488 i = gameobjects.erase(i);
491 /* add newly created objects */
492 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
493 i != gameobjects_new.end(); ++i)
495 GameObject* object = *i;
497 Bullet* bullet = dynamic_cast<Bullet*> (object);
499 bullets.push_back(bullet);
501 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
503 grid->add_object(movingobject);
505 TileMap* tilemap = dynamic_cast<TileMap*> (object);
506 if(tilemap && tilemap->is_solid()) {
510 std::cerr << "Another solid tilemaps added. Ignoring.";
514 Camera* camera = dynamic_cast<Camera*> (object);
516 if(this->camera != 0) {
517 std::cerr << "Warning: Multiple cameras added. Ignoring.";
520 this->camera = camera;
523 gameobjects.push_back(object);
525 gameobjects_new.clear();
529 Sector::draw(DrawingContext& context)
531 context.push_transform();
532 context.set_translation(camera->get_translation());
535 CollisionGridIterator iter(*grid, get_active_region());
536 while(MovingObject* object = iter.next()) {
537 if(!object->is_valid())
540 object->draw(context);
543 for(GameObjects::iterator i = gameobjects.begin();
544 i != gameobjects.end(); ++i) {
545 GameObject* object = *i;
546 if(!object->is_valid())
549 object->draw(context);
553 context.pop_transform();
556 static const float DELTA = .001;
559 Sector::collision_tilemap(MovingObject* object, int depth)
563 std::cout << "Max collision depth reached.\n";
565 object->movement = Vector(0, 0);
569 // calculate rectangle where the object will move
571 if(object->get_movement().x >= 0) {
572 x1 = object->get_pos().x;
573 x2 = object->get_bbox().p2.x + object->get_movement().x;
575 x1 = object->get_pos().x + object->get_movement().x;
576 x2 = object->get_bbox().p2.x;
579 if(object->get_movement().y >= 0) {
580 y1 = object->get_pos().y;
581 y2 = object->get_bbox().p2.y + object->get_movement().y;
583 y1 = object->get_pos().y + object->get_movement().y;
584 y2 = object->get_bbox().p2.y;
587 // test with all tiles in this rectangle
588 int starttilex = int(x1-1) / 32;
589 int starttiley = int(y1-1) / 32;
590 int max_x = int(x2+1);
591 int max_y = int(y2+1);
593 CollisionHit temphit, hit;
594 Rectangle dest = object->get_bbox();
595 dest.move(object->movement);
596 hit.time = -1; // represents an invalid value
597 for(int x = starttilex; x*32 < max_x; ++x) {
598 for(int y = starttiley; y*32 < max_y; ++y) {
599 const Tile* tile = solids->get_tile(x, y);
602 if(!(tile->getAttributes() & Tile::SOLID))
604 if((tile->getAttributes() & Tile::UNISOLID) && object->movement.y < 0)
607 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
609 Vector p1(x*32, y*32);
610 Vector p2((x+1)*32, (y+1)*32);
611 triangle = AATriangle(p1, p2, tile->getData());
613 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
615 if(temphit.time > hit.time)
618 } else { // normal rectangular tile
619 Rectangle rect(x*32, y*32, (x+1)*32, (y+1)*32);
620 if(Collision::rectangle_rectangle(temphit, dest,
621 object->movement, rect)) {
622 if(temphit.time > hit.time)
629 // did we collide at all?
633 // call collision function
634 HitResponse response = object->collision(*solids, hit);
635 if(response == ABORT_MOVE) {
636 object->movement = Vector(0, 0);
639 if(response == FORCE_MOVE) {
642 // move out of collision and try again
643 object->movement += hit.normal * (hit.depth + DELTA);
644 collision_tilemap(object, depth+1);
648 Sector::collision_object(MovingObject* object1, MovingObject* object2)
651 Rectangle dest1 = object1->get_bbox();
652 dest1.move(object1->get_movement());
653 Rectangle dest2 = object2->get_bbox();
654 dest2.move(object2->get_movement());
656 Vector movement = object1->get_movement() - object2->get_movement();
657 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
658 HitResponse response1 = object1->collision(*object2, hit);
660 HitResponse response2 = object2->collision(*object1, hit);
662 if(response1 != CONTINUE) {
663 if(response1 == ABORT_MOVE)
664 object1->movement = Vector(0, 0);
665 if(response2 == CONTINUE)
666 object2->movement += hit.normal * (hit.depth + DELTA);
667 } else if(response2 != CONTINUE) {
668 if(response2 == ABORT_MOVE)
669 object2->movement = Vector(0, 0);
670 if(response1 == CONTINUE)
671 object1->movement += -hit.normal * (hit.depth + DELTA);
673 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
674 object2->movement += hit.normal * (hit.depth/2 + DELTA);
680 Sector::collision_handler()
683 grid->check_collisions();
685 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
686 i != gameobjects.end(); ++i) {
687 GameObject* gameobject = *i;
688 if(!gameobject->is_valid())
690 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
693 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
694 movingobject->bbox.move(movingobject->movement);
695 movingobject->movement = Vector(0, 0);
699 // collision with tilemap
700 if(! (movingobject->movement == Vector(0, 0)))
701 collision_tilemap(movingobject, 0);
703 // collision with other objects
704 for(std::vector<GameObject*>::iterator i2 = i+1;
705 i2 != gameobjects.end(); ++i2) {
706 GameObject* other_object = *i2;
707 if(!other_object->is_valid()
708 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
710 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
714 collision_object(movingobject, movingobject2);
717 movingobject->bbox.move(movingobject->get_movement());
718 movingobject->movement = Vector(0, 0);
724 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
726 // TODO remove this function and move these checks elsewhere...
727 static const size_t MAX_FIRE_BULLETS = 2;
728 static const size_t MAX_ICE_BULLETS = 1;
730 Bullet* new_bullet = 0;
731 if(player_status.bonus == FIRE_BONUS) {
732 if(bullets.size() > MAX_FIRE_BULLETS-1)
734 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
735 } else if(player_status.bonus == ICE_BONUS) {
736 if(bullets.size() > MAX_ICE_BULLETS-1)
738 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
742 add_object(new_bullet);
744 SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
750 Sector::add_smoke_cloud(const Vector& pos)
752 add_object(new SmokeCloud(pos));
757 Sector::add_floating_text(const Vector& pos, const std::string& text)
759 add_object(new FloatingText(pos, text));
768 level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
770 song_path = (char *) malloc(sizeof(char) * datadir.length() +
771 strlen(song_title.c_str()) + 8 + 5);
772 song_subtitle = strdup(song_title.c_str());
773 strcpy(strstr(song_subtitle, "."), "\0");
774 sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
775 song_subtitle, strstr(song_title.c_str(), "."));
776 if(!SoundManager::get()->exists_music(song_path)) {
777 level_song_fast = level_song;
779 level_song_fast = SoundManager::get()->load_music(song_path);
786 Sector::play_music(int type)
789 switch(currentmusic) {
791 SoundManager::get()->play_music(level_song_fast);
794 SoundManager::get()->play_music(level_song);
797 SoundManager::get()->play_music(herring_song);
800 SoundManager::get()->halt_music();
806 Sector::get_music_type()
812 Sector::get_total_badguys()
814 int total_badguys = 0;
815 for(GameObjects::iterator i = gameobjects.begin();
816 i != gameobjects.end(); ++i) {
817 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
822 return total_badguys;
826 Sector::inside(const Rectangle& rect) const
828 if(rect.p1.x > solids->get_width() * 32
829 || rect.p1.y > solids->get_height() * 32
830 || rect.p2.x < 0 || rect.p2.y < 0)