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.
30 #include "player_status.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"
42 #include "game_session.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 "collision.h"
49 #include "spawn_point.h"
50 #include "math/rect.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 "object/text_object.h"
57 #include "badguy/jumpy.h"
58 #include "badguy/spike.h"
59 #include "trigger/sequence_trigger.h"
60 #include "player_status.h"
61 #include "scripting/script_interpreter.h"
62 #include "scripting/sound.h"
63 #include "scripting/scripted_object.h"
64 #include "scripting/text.h"
68 Sector* Sector::_current = 0;
71 : gravity(10), player(0), solids(0), camera(0),
72 currentmusic(LEVEL_MUSIC)
74 song_title = "Mortimers_chipdisko.mod";
75 player = new Player(&player_status);
78 grid = new CollisionGrid(32000, 32000);
83 update_game_objects();
84 assert(gameobjects_new.size() == 0);
88 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
93 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
102 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
104 if(name == "camera") {
105 Camera* camera = new Camera(this);
106 camera->parse(reader);
108 } else if(name == "particles-snow") {
109 SnowParticleSystem* partsys = new SnowParticleSystem();
110 partsys->parse(reader);
112 } else if(name == "particles-rain") {
113 RainParticleSystem* partsys = new RainParticleSystem();
114 partsys->parse(reader);
116 } else if(name == "particles-clouds") {
117 CloudParticleSystem* partsys = new CloudParticleSystem();
118 partsys->parse(reader);
120 } else if(name == "money") { // for compatibility with old maps
121 return new Jumpy(reader);
125 return create_object(name, reader);
126 } catch(std::exception& e) {
127 std::cerr << e.what() << "\n";
134 Sector::parse(const lisp::Lisp& sector)
138 lisp::ListIterator iter(§or);
140 const std::string& token = iter.item();
141 if(token == "name") {
142 iter.value()->get(name);
143 } else if(token == "gravity") {
144 iter.value()->get(gravity);
145 } else if(token == "music") {
146 iter.value()->get(song_title);
148 } else if(token == "spawnpoint") {
149 SpawnPoint* sp = new SpawnPoint(iter.lisp());
150 spawnpoints.push_back(sp);
151 } else if(token == "init-script") {
152 iter.value()->get(init_script);
154 GameObject* object = parse_object(token, *(iter.lisp()));
161 update_game_objects();
164 std::cerr << "sector '" << name << "' does not contain a camera.\n";
165 update_game_objects();
166 add_object(new Camera(this));
169 throw std::runtime_error("sector does not contain a solid tile layer.");
171 update_game_objects();
175 Sector::parse_old_format(const lisp::Lisp& reader)
180 reader.get("gravity", gravity);
182 std::string backgroundimage;
183 reader.get("background", backgroundimage);
185 reader.get("bkgd_speed", bgspeed);
188 Color bkgd_top, bkgd_bottom;
189 int r = 0, g = 0, b = 128;
190 reader.get("bkgd_red_top", r);
191 reader.get("bkgd_green_top", g);
192 reader.get("bkgd_blue_top", b);
197 reader.get("bkgd_red_bottom", r);
198 reader.get("bkgd_green_bottom", g);
199 reader.get("bkgd_blue_bottom", b);
201 bkgd_bottom.green = g;
202 bkgd_bottom.blue = b;
204 if(backgroundimage != "") {
205 Background* background = new Background;
206 background->set_image(backgroundimage, bgspeed);
207 add_object(background);
209 Background* background = new Background;
210 background->set_gradient(bkgd_top, bkgd_bottom);
211 add_object(background);
214 std::string particlesystem;
215 reader.get("particle_system", particlesystem);
216 if(particlesystem == "clouds")
217 add_object(new CloudParticleSystem());
218 else if(particlesystem == "snow")
219 add_object(new SnowParticleSystem());
220 else if(particlesystem == "rain")
221 add_object(new RainParticleSystem());
223 Vector startpos(100, 170);
224 reader.get("start_pos_x", startpos.x);
225 reader.get("start_pos_y", startpos.y);
227 SpawnPoint* spawn = new SpawnPoint;
228 spawn->pos = startpos;
229 spawn->name = "main";
230 spawnpoints.push_back(spawn);
232 song_title = "Mortimers_chipdisko.mod";
233 reader.get("music", song_title);
236 int width, height = 15;
237 reader.get("width", width);
238 reader.get("height", height);
240 std::vector<unsigned int> tiles;
241 if(reader.get_vector("interactive-tm", tiles)
242 || reader.get_vector("tilemap", tiles)) {
243 TileMap* tilemap = new TileMap();
244 tilemap->set(width, height, tiles, LAYER_TILES, true);
248 if(reader.get_vector("background-tm", tiles)) {
249 TileMap* tilemap = new TileMap();
250 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
254 if(reader.get_vector("foreground-tm", tiles)) {
255 TileMap* tilemap = new TileMap();
256 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
260 // read reset-points (now spawn-points)
261 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
263 lisp::ListIterator iter(resetpoints);
265 if(iter.item() == "point") {
267 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
269 SpawnPoint* sp = new SpawnPoint;
272 spawnpoints.push_back(sp);
275 std::cerr << "Unknown token '" << iter.item() << "' in reset-points.\n";
281 const lisp::Lisp* objects = reader.get_lisp("objects");
283 lisp::ListIterator iter(objects);
285 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
289 std::cerr << "Unknown object '" << iter.item() << "' in level.\n";
295 Camera* camera = new Camera(this);
298 update_game_objects();
300 update_game_objects();
302 throw std::runtime_error("sector does not contain a solid tile layer.");
306 Sector::fix_old_tiles()
309 for(size_t x=0; x < solids->get_width(); ++x) {
310 for(size_t y=0; y < solids->get_height(); ++y) {
311 const Tile* tile = solids->get_tile(x, y);
312 Vector pos(x*32, y*32);
314 if(tile->getID() == 112) {
315 add_object(new InvisibleBlock(pos));
316 solids->change(x, y, 0);
317 } else if(tile->getID() == 295) {
318 add_object(new Spike(pos, Spike::NORTH));
319 solids->change(x, y, 0);
320 } else if(tile->getID() == 296) {
321 add_object(new Spike(pos, Spike::EAST));
322 solids->change(x, y, 0);
323 } else if(tile->getID() == 297) {
324 add_object(new Spike(pos, Spike::SOUTH));
325 solids->change(x, y, 0);
326 } else if(tile->getID() == 298) {
327 add_object(new Spike(pos, Spike::WEST));
328 solids->change(x, y, 0);
329 } else if(tile->getAttributes() & Tile::COIN) {
330 add_object(new Coin(pos));
331 solids->change(x, y, 0);
332 } else if(tile->getAttributes() & Tile::FULLBOX) {
333 add_object(new BonusBlock(pos, tile->getData()));
334 solids->change(x, y, 0);
335 } else if(tile->getAttributes() & Tile::BRICK) {
336 add_object(new Brick(pos, tile->getData()));
337 solids->change(x, y, 0);
338 } else if(tile->getAttributes() & Tile::GOAL) {
339 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
340 add_object(new SequenceTrigger(pos, sequence));
341 solids->change(x, y, 0);
348 Sector::write(lisp::Writer& writer)
350 writer.write_string("name", name);
351 writer.write_float("gravity", gravity);
352 writer.write_string("music", song_title);
355 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
357 SpawnPoint* spawn = *i;
358 writer.start_list("spawn-points");
359 writer.write_string("name", spawn->name);
360 writer.write_float("x", spawn->pos.x);
361 writer.write_float("y", spawn->pos.y);
362 writer.end_list("spawn-points");
366 for(GameObjects::iterator i = gameobjects.begin();
367 i != gameobjects.end(); ++i) {
368 Serializable* serializable = dynamic_cast<Serializable*> (*i);
370 serializable->write(writer);
375 Sector::add_object(GameObject* object)
377 // make sure the object isn't already in the list
379 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
382 assert("object already added to sector" == 0);
385 for(GameObjects::iterator i = gameobjects_new.begin();
386 i != gameobjects_new.end(); ++i) {
388 assert("object already added to sector" == 0);
393 gameobjects_new.push_back(object);
397 Sector::activate(const std::string& spawnpoint)
400 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
402 if((*i)->name == spawnpoint) {
408 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
409 if(spawnpoint != "main") {
412 activate(Vector(0, 0));
419 if(init_script != "") {
421 ScriptInterpreter* interpreter = new ScriptInterpreter(this);
422 std::string sourcename = std::string("Sector(") + name + ") - init";
423 std::istringstream in(init_script);
424 interpreter->load_script(in, sourcename);
425 interpreter->start_script();
426 add_object(interpreter);
428 } catch(std::exception& e) {
429 std::cerr << "Couldn't execute init script: " << e.what() << "\n";
435 Sector::activate(const Vector& player_pos)
439 player->move(player_pos);
440 camera->reset(player->get_pos());
444 Sector::get_active_region()
447 camera->get_translation() - Vector(1600, 1200),
448 camera->get_translation() + Vector(1600, 1200));
452 Sector::update(float elapsed_time)
454 player->check_bounds(camera);
457 CollisionGridIterator iter(*grid, get_active_region());
458 while(MovingObject* object = iter.next()) {
459 if(!object->is_valid())
462 object->update(elapsed_time);
466 for(GameObjects::iterator i = gameobjects.begin();
467 i != gameobjects.end(); ++i) {
468 GameObject* object = *i;
469 if(!object->is_valid())
472 object->update(elapsed_time);
476 /* Handle all possible collisions. */
478 update_game_objects();
482 Sector::update_game_objects()
484 /** cleanup marked objects */
485 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
486 i != gameobjects.end(); /* nothing */) {
487 GameObject* object = *i;
489 if(object->is_valid()) {
494 Bullet* bullet = dynamic_cast<Bullet*> (object);
497 std::remove(bullets.begin(), bullets.end(), bullet),
500 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
502 grid->remove_object(movingobject);
505 i = gameobjects.erase(i);
508 /* add newly created objects */
509 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
510 i != gameobjects_new.end(); ++i)
512 GameObject* object = *i;
514 Bullet* bullet = dynamic_cast<Bullet*> (object);
516 bullets.push_back(bullet);
518 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
520 grid->add_object(movingobject);
522 TileMap* tilemap = dynamic_cast<TileMap*> (object);
523 if(tilemap && tilemap->is_solid()) {
527 std::cerr << "Another solid tilemaps added. Ignoring.";
531 Camera* camera = dynamic_cast<Camera*> (object);
533 if(this->camera != 0) {
534 std::cerr << "Warning: Multiple cameras added. Ignoring.";
537 this->camera = camera;
540 gameobjects.push_back(object);
542 gameobjects_new.clear();
546 Sector::draw(DrawingContext& context)
548 context.push_transform();
549 context.set_translation(camera->get_translation());
552 CollisionGridIterator iter(*grid, get_active_region());
553 while(MovingObject* object = iter.next()) {
554 if(!object->is_valid())
557 object->draw(context);
560 for(GameObjects::iterator i = gameobjects.begin();
561 i != gameobjects.end(); ++i) {
562 GameObject* object = *i;
563 if(!object->is_valid())
566 object->draw(context);
570 context.pop_transform();
573 static const float DELTA = .001;
576 Sector::collision_tilemap(MovingObject* object, int depth)
580 std::cout << "Max collision depth reached.\n";
582 object->movement = Vector(0, 0);
586 // calculate rectangle where the object will move
588 if(object->get_movement().x >= 0) {
589 x1 = object->get_pos().x;
590 x2 = object->get_bbox().p2.x + object->get_movement().x;
592 x1 = object->get_pos().x + object->get_movement().x;
593 x2 = object->get_bbox().p2.x;
596 if(object->get_movement().y >= 0) {
597 y1 = object->get_pos().y;
598 y2 = object->get_bbox().p2.y + object->get_movement().y;
600 y1 = object->get_pos().y + object->get_movement().y;
601 y2 = object->get_bbox().p2.y;
604 // test with all tiles in this rectangle
605 int starttilex = int(x1-1) / 32;
606 int starttiley = int(y1-1) / 32;
607 int max_x = int(x2+1);
608 int max_y = int(y2+1);
610 CollisionHit temphit, hit;
611 Rect dest = object->get_bbox();
612 dest.move(object->movement);
613 hit.time = -1; // represents an invalid value
614 for(int x = starttilex; x*32 < max_x; ++x) {
615 for(int y = starttiley; y*32 < max_y; ++y) {
616 const Tile* tile = solids->get_tile(x, y);
619 // skip non-solid tiles
620 if(!(tile->getAttributes() & Tile::SOLID))
622 // only handle unisolid when the player is falling down and when he was
623 // above the tile before
624 if(tile->getAttributes() & Tile::UNISOLID) {
625 if(object->movement.y < 0 || object->get_bbox().p2.y > y*32)
629 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
631 Vector p1(x*32, y*32);
632 Vector p2((x+1)*32, (y+1)*32);
633 triangle = AATriangle(p1, p2, tile->getData());
635 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
637 if(temphit.time > hit.time)
640 } else { // normal rectangular tile
641 Rect rect(x*32, y*32, (x+1)*32, (y+1)*32);
642 if(Collision::rectangle_rectangle(temphit, dest,
643 object->movement, rect)) {
644 if(temphit.time > hit.time)
651 // did we collide at all?
655 // call collision function
656 HitResponse response = object->collision(*solids, hit);
657 if(response == ABORT_MOVE) {
658 object->movement = Vector(0, 0);
661 if(response == FORCE_MOVE) {
664 // move out of collision and try again
665 object->movement += hit.normal * (hit.depth + DELTA);
666 collision_tilemap(object, depth+1);
670 Sector::collision_object(MovingObject* object1, MovingObject* object2)
673 Rect dest1 = object1->get_bbox();
674 dest1.move(object1->get_movement());
675 Rect dest2 = object2->get_bbox();
676 dest2.move(object2->get_movement());
678 Vector movement = object1->get_movement() - object2->get_movement();
679 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
680 HitResponse response1 = object1->collision(*object2, hit);
682 HitResponse response2 = object2->collision(*object1, hit);
684 if(response1 != CONTINUE) {
685 if(response1 == ABORT_MOVE)
686 object1->movement = Vector(0, 0);
687 if(response2 == CONTINUE)
688 object2->movement += hit.normal * (hit.depth + DELTA);
689 } else if(response2 != CONTINUE) {
690 if(response2 == ABORT_MOVE)
691 object2->movement = Vector(0, 0);
692 if(response1 == CONTINUE)
693 object1->movement += -hit.normal * (hit.depth + DELTA);
695 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
696 object2->movement += hit.normal * (hit.depth/2 + DELTA);
702 Sector::collision_handler()
705 grid->check_collisions();
707 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
708 i != gameobjects.end(); ++i) {
709 GameObject* gameobject = *i;
710 if(!gameobject->is_valid())
712 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
715 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
716 movingobject->bbox.move(movingobject->movement);
717 movingobject->movement = Vector(0, 0);
721 // collision with tilemap
722 if(! (movingobject->movement == Vector(0, 0)))
723 collision_tilemap(movingobject, 0);
725 // collision with other objects
726 for(std::vector<GameObject*>::iterator i2 = i+1;
727 i2 != gameobjects.end(); ++i2) {
728 GameObject* other_object = *i2;
729 if(!other_object->is_valid()
730 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
732 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
736 collision_object(movingobject, movingobject2);
739 movingobject->bbox.move(movingobject->get_movement());
740 movingobject->movement = Vector(0, 0);
746 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
748 // TODO remove this function and move these checks elsewhere...
749 static const size_t MAX_FIRE_BULLETS = 2;
750 static const size_t MAX_ICE_BULLETS = 1;
752 Bullet* new_bullet = 0;
753 if(player_status.bonus == FIRE_BONUS) {
754 if(bullets.size() > MAX_FIRE_BULLETS-1)
756 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
757 } else if(player_status.bonus == ICE_BONUS) {
758 if(bullets.size() > MAX_ICE_BULLETS-1)
760 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
764 add_object(new_bullet);
766 sound_manager->play_sound("shoot");
772 Sector::add_smoke_cloud(const Vector& pos)
774 add_object(new SmokeCloud(pos));
779 Sector::add_floating_text(const Vector& pos, const std::string& text)
781 add_object(new FloatingText(pos, text));
787 level_song = sound_manager->load_music(
788 get_resource_filename("/music/" + song_title));
792 Sector::play_music(MusicType type)
795 switch(currentmusic) {
797 sound_manager->play_music(level_song);
800 sound_manager->play_music(herring_song);
803 sound_manager->halt_music();
809 Sector::get_music_type()
815 Sector::get_total_badguys()
817 int total_badguys = 0;
818 for(GameObjects::iterator i = gameobjects.begin();
819 i != gameobjects.end(); ++i) {
820 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
825 return total_badguys;
829 Sector::inside(const Rect& rect) const
831 if(rect.p1.x > solids->get_width() * 32
832 || rect.p1.y > solids->get_height() * 32
833 || rect.p2.x < 0 || rect.p2.y < 0)