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 "math/rect.h"
50 #include "math/aatriangle.h"
51 #include "object/coin.h"
52 #include "object/block.h"
53 #include "object/invisible_block.h"
54 #include "object/bullet.h"
55 #include "object/text_object.h"
56 #include "badguy/jumpy.h"
57 #include "badguy/spike.h"
58 #include "trigger/sequence_trigger.h"
59 #include "player_status.h"
60 #include "scripting/script_interpreter.h"
61 #include "scripting/sound.h"
62 #include "scripting/scripted_object.h"
63 #include "scripting/text.h"
67 Sector* Sector::_current = 0;
70 : gravity(10), player(0), solids(0), camera(0),
71 interpreter(0), currentmusic(LEVEL_MUSIC)
73 song_title = "Mortimers_chipdisko.mod";
74 player = new Player(&player_status);
77 grid = new CollisionGrid(32000, 32000);
82 update_game_objects();
83 assert(gameobjects_new.size() == 0);
87 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
92 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
101 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
103 if(name == "camera") {
104 Camera* camera = new Camera(this);
105 camera->parse(reader);
107 } else if(name == "particles-snow") {
108 SnowParticleSystem* partsys = new SnowParticleSystem();
109 partsys->parse(reader);
111 } else if(name == "particles-rain") {
112 RainParticleSystem* partsys = new RainParticleSystem();
113 partsys->parse(reader);
115 } else if(name == "particles-clouds") {
116 CloudParticleSystem* partsys = new CloudParticleSystem();
117 partsys->parse(reader);
119 } else if(name == "money") { // for compatibility with old maps
120 return new Jumpy(reader);
124 return create_object(name, reader);
125 } catch(std::exception& e) {
126 std::cerr << e.what() << "\n";
133 Sector::parse(const lisp::Lisp& sector)
137 lisp::ListIterator iter(§or);
139 const std::string& token = iter.item();
140 if(token == "name") {
141 iter.value()->get(name);
142 } else if(token == "gravity") {
143 iter.value()->get(gravity);
144 } else if(token == "music") {
145 iter.value()->get(song_title);
147 } else if(token == "spawnpoint") {
148 const lisp::Lisp* spawnpoint_lisp = iter.lisp();
150 SpawnPoint* sp = new SpawnPoint;
151 spawnpoint_lisp->get("name", sp->name);
152 spawnpoint_lisp->get("x", sp->pos.x);
153 spawnpoint_lisp->get("y", sp->pos.y);
154 spawnpoints.push_back(sp);
155 } else if(token == "init-script") {
156 iter.value()->get(init_script);
158 GameObject* object = parse_object(token, *(iter.lisp()));
165 update_game_objects();
168 std::cerr << "sector '" << name << "' does not contain a camera.\n";
169 update_game_objects();
170 add_object(new Camera(this));
173 throw std::runtime_error("sector does not contain a solid tile layer.");
175 update_game_objects();
179 Sector::parse_old_format(const lisp::Lisp& reader)
184 reader.get("gravity", gravity);
186 std::string backgroundimage;
187 reader.get("background", backgroundimage);
189 reader.get("bkgd_speed", bgspeed);
192 Color bkgd_top, bkgd_bottom;
193 int r = 0, g = 0, b = 128;
194 reader.get("bkgd_red_top", r);
195 reader.get("bkgd_green_top", g);
196 reader.get("bkgd_blue_top", b);
201 reader.get("bkgd_red_bottom", r);
202 reader.get("bkgd_green_bottom", g);
203 reader.get("bkgd_blue_bottom", b);
205 bkgd_bottom.green = g;
206 bkgd_bottom.blue = b;
208 if(backgroundimage != "") {
209 Background* background = new Background;
210 background->set_image(backgroundimage, bgspeed);
211 add_object(background);
213 Background* background = new Background;
214 background->set_gradient(bkgd_top, bkgd_bottom);
215 add_object(background);
218 std::string particlesystem;
219 reader.get("particle_system", particlesystem);
220 if(particlesystem == "clouds")
221 add_object(new CloudParticleSystem());
222 else if(particlesystem == "snow")
223 add_object(new SnowParticleSystem());
224 else if(particlesystem == "rain")
225 add_object(new RainParticleSystem());
227 Vector startpos(100, 170);
228 reader.get("start_pos_x", startpos.x);
229 reader.get("start_pos_y", startpos.y);
231 SpawnPoint* spawn = new SpawnPoint;
232 spawn->pos = startpos;
233 spawn->name = "main";
234 spawnpoints.push_back(spawn);
236 song_title = "Mortimers_chipdisko.mod";
237 reader.get("music", song_title);
240 int width, height = 15;
241 reader.get("width", width);
242 reader.get("height", height);
244 std::vector<unsigned int> tiles;
245 if(reader.get_vector("interactive-tm", tiles)
246 || reader.get_vector("tilemap", tiles)) {
247 TileMap* tilemap = new TileMap();
248 tilemap->set(width, height, tiles, LAYER_TILES, true);
252 if(reader.get_vector("background-tm", tiles)) {
253 TileMap* tilemap = new TileMap();
254 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
258 if(reader.get_vector("foreground-tm", tiles)) {
259 TileMap* tilemap = new TileMap();
260 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
264 // read reset-points (now spawn-points)
265 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
267 lisp::ListIterator iter(resetpoints);
269 if(iter.item() == "point") {
271 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
273 SpawnPoint* sp = new SpawnPoint;
276 spawnpoints.push_back(sp);
279 std::cerr << "Unknown token '" << iter.item() << "' in reset-points.\n";
285 const lisp::Lisp* objects = reader.get_lisp("objects");
287 lisp::ListIterator iter(objects);
289 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
293 std::cerr << "Unknown object '" << iter.item() << "' in level.\n";
299 Camera* camera = new Camera(this);
302 update_game_objects();
304 update_game_objects();
306 throw std::runtime_error("sector does not contain a solid tile layer.");
310 Sector::fix_old_tiles()
313 for(size_t x=0; x < solids->get_width(); ++x) {
314 for(size_t y=0; y < solids->get_height(); ++y) {
315 const Tile* tile = solids->get_tile(x, y);
316 Vector pos(x*32, y*32);
318 if(tile->getID() == 112) {
319 add_object(new InvisibleBlock(pos));
320 solids->change(x, y, 0);
321 } else if(tile->getID() == 295) {
322 add_object(new Spike(pos, Spike::NORTH));
323 solids->change(x, y, 0);
324 } else if(tile->getID() == 296) {
325 add_object(new Spike(pos, Spike::EAST));
326 solids->change(x, y, 0);
327 } else if(tile->getID() == 297) {
328 add_object(new Spike(pos, Spike::SOUTH));
329 solids->change(x, y, 0);
330 } else if(tile->getID() == 298) {
331 add_object(new Spike(pos, Spike::WEST));
332 solids->change(x, y, 0);
333 } else if(tile->getAttributes() & Tile::COIN) {
334 add_object(new Coin(pos));
335 solids->change(x, y, 0);
336 } else if(tile->getAttributes() & Tile::FULLBOX) {
337 add_object(new BonusBlock(pos, tile->getData()));
338 solids->change(x, y, 0);
339 } else if(tile->getAttributes() & Tile::BRICK) {
340 add_object(new Brick(pos, tile->getData()));
341 solids->change(x, y, 0);
342 } else if(tile->getAttributes() & Tile::GOAL) {
343 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
344 add_object(new SequenceTrigger(pos, sequence));
345 solids->change(x, y, 0);
352 Sector::write(lisp::Writer& writer)
354 writer.write_string("name", name);
355 writer.write_float("gravity", gravity);
356 writer.write_string("music", song_title);
359 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
361 SpawnPoint* spawn = *i;
362 writer.start_list("spawn-points");
363 writer.write_string("name", spawn->name);
364 writer.write_float("x", spawn->pos.x);
365 writer.write_float("y", spawn->pos.y);
366 writer.end_list("spawn-points");
370 for(GameObjects::iterator i = gameobjects.begin();
371 i != gameobjects.end(); ++i) {
372 Serializable* serializable = dynamic_cast<Serializable*> (*i);
374 serializable->write(writer);
379 Sector::add_object(GameObject* object)
381 // make sure the object isn't already in the list
383 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
386 assert("object already added to sector" == 0);
389 for(GameObjects::iterator i = gameobjects_new.begin();
390 i != gameobjects_new.end(); ++i) {
392 assert("object already added to sector" == 0);
397 gameobjects_new.push_back(object);
401 Sector::activate(const std::string& spawnpoint)
404 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
406 if((*i)->name == spawnpoint) {
412 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
413 if(spawnpoint != "main") {
416 activate(Vector(0, 0));
423 if(init_script != "") {
425 // TODO we should keep the interpreter across sessions (or some variables)
426 // so that you can store information across levels/sectors...
429 interpreter = new ScriptInterpreter();
431 // expose ScriptedObjects to the script
432 for(GameObjects::iterator i = gameobjects.begin();
433 i != gameobjects.end(); ++i) {
434 GameObject* object = *i;
435 Scripting::ScriptedObject* scripted_object
436 = dynamic_cast<Scripting::ScriptedObject*> (object);
440 std::cout << "Exposing " << scripted_object->get_name() << "\n";
441 interpreter->expose_object(scripted_object,
442 scripted_object->get_name(),
445 Scripting::Sound* sound = new Scripting::Sound();
446 interpreter->expose_object(sound, "Sound", "Sound");
447 TextObject* text_object = new TextObject();
448 add_object(text_object);
449 Scripting::Text* text = static_cast<Scripting::Text*> (text_object);
450 interpreter->expose_object(text, "Text", "Text");
452 std::string sourcename = std::string("Sector(") + name + ") - init";
453 std::istringstream in(init_script);
454 printf("Load script.\n");
455 interpreter->load_script(in, sourcename);
456 printf("run script.\n");
457 interpreter->run_script();
458 } catch(std::exception& e) {
459 std::cerr << "Couldn't execute init script: " << e.what() << "\n";
465 Sector::activate(const Vector& player_pos)
469 player->move(player_pos);
470 camera->reset(player->get_pos());
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)
485 interpreter->update();
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 Rect 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 // skip non-solid tiles
653 if(!(tile->getAttributes() & Tile::SOLID))
655 // only handle unisolid when the player is falling down and when he was
656 // above the tile before
657 if(tile->getAttributes() & Tile::UNISOLID) {
658 if(object->movement.y < 0 || object->get_bbox().p2.y > y*32)
662 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
664 Vector p1(x*32, y*32);
665 Vector p2((x+1)*32, (y+1)*32);
666 triangle = AATriangle(p1, p2, tile->getData());
668 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
670 if(temphit.time > hit.time)
673 } else { // normal rectangular tile
674 Rect rect(x*32, y*32, (x+1)*32, (y+1)*32);
675 if(Collision::rectangle_rectangle(temphit, dest,
676 object->movement, rect)) {
677 if(temphit.time > hit.time)
684 // did we collide at all?
688 // call collision function
689 HitResponse response = object->collision(*solids, hit);
690 if(response == ABORT_MOVE) {
691 object->movement = Vector(0, 0);
694 if(response == FORCE_MOVE) {
697 // move out of collision and try again
698 object->movement += hit.normal * (hit.depth + DELTA);
699 collision_tilemap(object, depth+1);
703 Sector::collision_object(MovingObject* object1, MovingObject* object2)
706 Rect dest1 = object1->get_bbox();
707 dest1.move(object1->get_movement());
708 Rect dest2 = object2->get_bbox();
709 dest2.move(object2->get_movement());
711 Vector movement = object1->get_movement() - object2->get_movement();
712 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
713 HitResponse response1 = object1->collision(*object2, hit);
715 HitResponse response2 = object2->collision(*object1, hit);
717 if(response1 != CONTINUE) {
718 if(response1 == ABORT_MOVE)
719 object1->movement = Vector(0, 0);
720 if(response2 == CONTINUE)
721 object2->movement += hit.normal * (hit.depth + DELTA);
722 } else if(response2 != CONTINUE) {
723 if(response2 == ABORT_MOVE)
724 object2->movement = Vector(0, 0);
725 if(response1 == CONTINUE)
726 object1->movement += -hit.normal * (hit.depth + DELTA);
728 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
729 object2->movement += hit.normal * (hit.depth/2 + DELTA);
735 Sector::collision_handler()
738 grid->check_collisions();
740 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
741 i != gameobjects.end(); ++i) {
742 GameObject* gameobject = *i;
743 if(!gameobject->is_valid())
745 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
748 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
749 movingobject->bbox.move(movingobject->movement);
750 movingobject->movement = Vector(0, 0);
754 // collision with tilemap
755 if(! (movingobject->movement == Vector(0, 0)))
756 collision_tilemap(movingobject, 0);
758 // collision with other objects
759 for(std::vector<GameObject*>::iterator i2 = i+1;
760 i2 != gameobjects.end(); ++i2) {
761 GameObject* other_object = *i2;
762 if(!other_object->is_valid()
763 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
765 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
769 collision_object(movingobject, movingobject2);
772 movingobject->bbox.move(movingobject->get_movement());
773 movingobject->movement = Vector(0, 0);
779 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
781 // TODO remove this function and move these checks elsewhere...
782 static const size_t MAX_FIRE_BULLETS = 2;
783 static const size_t MAX_ICE_BULLETS = 1;
785 Bullet* new_bullet = 0;
786 if(player_status.bonus == FIRE_BONUS) {
787 if(bullets.size() > MAX_FIRE_BULLETS-1)
789 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
790 } else if(player_status.bonus == ICE_BONUS) {
791 if(bullets.size() > MAX_ICE_BULLETS-1)
793 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
797 add_object(new_bullet);
799 sound_manager->play_sound("shoot");
805 Sector::add_smoke_cloud(const Vector& pos)
807 add_object(new SmokeCloud(pos));
812 Sector::add_floating_text(const Vector& pos, const std::string& text)
814 add_object(new FloatingText(pos, text));
820 level_song = sound_manager->load_music(
821 get_resource_filename("/music/" + song_title));
825 Sector::play_music(MusicType type)
828 switch(currentmusic) {
830 sound_manager->play_music(level_song);
833 sound_manager->play_music(herring_song);
836 sound_manager->halt_music();
842 Sector::get_music_type()
848 Sector::get_total_badguys()
850 int total_badguys = 0;
851 for(GameObjects::iterator i = gameobjects.begin();
852 i != gameobjects.end(); ++i) {
853 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
858 return total_badguys;
862 Sector::inside(const Rect& rect) const
864 if(rect.p1.x > solids->get_width() * 32
865 || rect.p1.y > solids->get_height() * 32
866 || rect.p2.x < 0 || rect.p2.y < 0)