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 "badguy/jumpy.h"
56 #include "badguy/spike.h"
57 #include "trigger/sequence_trigger.h"
58 #include "player_status.h"
59 #include "scripting/script_interpreter.h"
60 #include "scripting/sound.h"
61 #include "scripting/scripted_object.h"
65 Sector* Sector::_current = 0;
68 : gravity(10), player(0), solids(0), camera(0),
69 interpreter(0), currentmusic(LEVEL_MUSIC)
71 song_title = "Mortimers_chipdisko.mod";
72 player = new Player(&player_status);
75 grid = new CollisionGrid(32000, 32000);
80 update_game_objects();
81 assert(gameobjects_new.size() == 0);
85 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
90 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
99 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
101 if(name == "camera") {
102 Camera* camera = new Camera(this);
103 camera->parse(reader);
105 } else if(name == "particles-snow") {
106 SnowParticleSystem* partsys = new SnowParticleSystem();
107 partsys->parse(reader);
109 } else if(name == "particles-rain") {
110 RainParticleSystem* partsys = new RainParticleSystem();
111 partsys->parse(reader);
113 } else if(name == "particles-clouds") {
114 CloudParticleSystem* partsys = new CloudParticleSystem();
115 partsys->parse(reader);
117 } else if(name == "money") { // for compatibility with old maps
118 return new Jumpy(reader);
122 return create_object(name, reader);
123 } catch(std::exception& e) {
124 std::cerr << e.what() << "\n";
131 Sector::parse(const lisp::Lisp& sector)
135 lisp::ListIterator iter(§or);
137 const std::string& token = iter.item();
138 if(token == "name") {
139 iter.value()->get(name);
140 } else if(token == "gravity") {
141 iter.value()->get(gravity);
142 } else if(token == "music") {
143 iter.value()->get(song_title);
145 } else if(token == "spawnpoint") {
146 const lisp::Lisp* spawnpoint_lisp = iter.lisp();
148 SpawnPoint* sp = new SpawnPoint;
149 spawnpoint_lisp->get("name", sp->name);
150 spawnpoint_lisp->get("x", sp->pos.x);
151 spawnpoint_lisp->get("y", sp->pos.y);
152 spawnpoints.push_back(sp);
153 } else if(token == "init-script") {
154 iter.value()->get(init_script);
156 GameObject* object = parse_object(token, *(iter.lisp()));
163 update_game_objects();
166 std::cerr << "sector '" << name << "' does not contain a camera.\n";
167 update_game_objects();
168 add_object(new Camera(this));
171 throw std::runtime_error("sector does not contain a solid tile layer.");
173 update_game_objects();
177 Sector::parse_old_format(const lisp::Lisp& reader)
182 reader.get("gravity", gravity);
184 std::string backgroundimage;
185 reader.get("background", backgroundimage);
187 reader.get("bkgd_speed", bgspeed);
190 Color bkgd_top, bkgd_bottom;
191 int r = 0, g = 0, b = 128;
192 reader.get("bkgd_red_top", r);
193 reader.get("bkgd_green_top", g);
194 reader.get("bkgd_blue_top", b);
199 reader.get("bkgd_red_bottom", r);
200 reader.get("bkgd_green_bottom", g);
201 reader.get("bkgd_blue_bottom", b);
203 bkgd_bottom.green = g;
204 bkgd_bottom.blue = b;
206 if(backgroundimage != "") {
207 Background* background = new Background;
208 background->set_image(backgroundimage, bgspeed);
209 add_object(background);
211 Background* background = new Background;
212 background->set_gradient(bkgd_top, bkgd_bottom);
213 add_object(background);
216 std::string particlesystem;
217 reader.get("particle_system", particlesystem);
218 if(particlesystem == "clouds")
219 add_object(new CloudParticleSystem());
220 else if(particlesystem == "snow")
221 add_object(new SnowParticleSystem());
222 else if(particlesystem == "rain")
223 add_object(new RainParticleSystem());
225 Vector startpos(100, 170);
226 reader.get("start_pos_x", startpos.x);
227 reader.get("start_pos_y", startpos.y);
229 SpawnPoint* spawn = new SpawnPoint;
230 spawn->pos = startpos;
231 spawn->name = "main";
232 spawnpoints.push_back(spawn);
234 song_title = "Mortimers_chipdisko.mod";
235 reader.get("music", song_title);
238 int width, height = 15;
239 reader.get("width", width);
240 reader.get("height", height);
242 std::vector<unsigned int> tiles;
243 if(reader.get_vector("interactive-tm", tiles)
244 || reader.get_vector("tilemap", tiles)) {
245 TileMap* tilemap = new TileMap();
246 tilemap->set(width, height, tiles, LAYER_TILES, true);
250 if(reader.get_vector("background-tm", tiles)) {
251 TileMap* tilemap = new TileMap();
252 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
256 if(reader.get_vector("foreground-tm", tiles)) {
257 TileMap* tilemap = new TileMap();
258 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
262 // read reset-points (now spawn-points)
263 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
265 lisp::ListIterator iter(resetpoints);
267 if(iter.item() == "point") {
269 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
271 SpawnPoint* sp = new SpawnPoint;
274 spawnpoints.push_back(sp);
277 std::cerr << "Unknown token '" << iter.item() << "' in reset-points.\n";
283 const lisp::Lisp* objects = reader.get_lisp("objects");
285 lisp::ListIterator iter(objects);
287 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
291 std::cerr << "Unknown object '" << iter.item() << "' in level.\n";
297 Camera* camera = new Camera(this);
300 update_game_objects();
302 update_game_objects();
304 throw std::runtime_error("sector does not contain a solid tile layer.");
308 Sector::fix_old_tiles()
311 for(size_t x=0; x < solids->get_width(); ++x) {
312 for(size_t y=0; y < solids->get_height(); ++y) {
313 const Tile* tile = solids->get_tile(x, y);
314 Vector pos(x*32, y*32);
316 if(tile->getID() == 112) {
317 add_object(new InvisibleBlock(pos));
318 solids->change(x, y, 0);
319 } else if(tile->getID() == 295) {
320 add_object(new Spike(pos, Spike::NORTH));
321 solids->change(x, y, 0);
322 } else if(tile->getID() == 296) {
323 add_object(new Spike(pos, Spike::EAST));
324 solids->change(x, y, 0);
325 } else if(tile->getID() == 297) {
326 add_object(new Spike(pos, Spike::SOUTH));
327 solids->change(x, y, 0);
328 } else if(tile->getID() == 298) {
329 add_object(new Spike(pos, Spike::WEST));
330 solids->change(x, y, 0);
331 } else if(tile->getAttributes() & Tile::COIN) {
332 add_object(new Coin(pos));
333 solids->change(x, y, 0);
334 } else if(tile->getAttributes() & Tile::FULLBOX) {
335 add_object(new BonusBlock(pos, tile->getData()));
336 solids->change(x, y, 0);
337 } else if(tile->getAttributes() & Tile::BRICK) {
338 add_object(new Brick(pos, tile->getData()));
339 solids->change(x, y, 0);
340 } else if(tile->getAttributes() & Tile::GOAL) {
341 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
342 add_object(new SequenceTrigger(pos, sequence));
343 solids->change(x, y, 0);
350 Sector::write(lisp::Writer& writer)
352 writer.write_string("name", name);
353 writer.write_float("gravity", gravity);
354 writer.write_string("music", song_title);
357 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
359 SpawnPoint* spawn = *i;
360 writer.start_list("spawn-points");
361 writer.write_string("name", spawn->name);
362 writer.write_float("x", spawn->pos.x);
363 writer.write_float("y", spawn->pos.y);
364 writer.end_list("spawn-points");
368 for(GameObjects::iterator i = gameobjects.begin();
369 i != gameobjects.end(); ++i) {
370 Serializable* serializable = dynamic_cast<Serializable*> (*i);
372 serializable->write(writer);
377 Sector::add_object(GameObject* object)
379 // make sure the object isn't already in the list
381 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
384 assert("object already added to sector" == 0);
387 for(GameObjects::iterator i = gameobjects_new.begin();
388 i != gameobjects_new.end(); ++i) {
390 assert("object already added to sector" == 0);
395 gameobjects_new.push_back(object);
399 Sector::activate(const std::string& spawnpoint)
402 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
404 if((*i)->name == spawnpoint) {
410 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
411 if(spawnpoint != "main") {
414 activate(Vector(0, 0));
421 if(init_script != "") {
423 // TODO we should keep the interpreter across sessions (or some variables)
424 // so that you can store information across levels/sectors...
427 interpreter = new ScriptInterpreter();
429 // expose ScriptedObjects to the script
430 for(GameObjects::iterator i = gameobjects.begin();
431 i != gameobjects.end(); ++i) {
432 GameObject* object = *i;
433 Scripting::ScriptedObject* scripted_object
434 = dynamic_cast<Scripting::ScriptedObject*> (object);
438 std::cout << "Exposing " << scripted_object->get_name() << "\n";
439 interpreter->expose_object(scripted_object,
440 scripted_object->get_name(),
443 Scripting::Sound* sound = new Scripting::Sound();
444 interpreter->expose_object(sound, "Sound", "Sound");
446 std::string sourcename = std::string("Sector(") + name + ") - init";
447 std::istringstream in(init_script);
448 printf("Load script.\n");
449 interpreter->load_script(in, sourcename);
450 printf("run script.\n");
451 interpreter->run_script();
452 } catch(std::exception& e) {
453 std::cerr << "Couldn't execute init script: " << e.what() << "\n";
459 Sector::activate(const Vector& player_pos)
463 player->move(player_pos);
464 camera->reset(player->get_pos());
468 Sector::get_active_region()
471 camera->get_translation() - Vector(1600, 1200),
472 camera->get_translation() + Vector(1600, 1200));
476 Sector::action(float elapsed_time)
479 interpreter->update();
481 player->check_bounds(camera);
484 CollisionGridIterator iter(*grid, get_active_region());
485 while(MovingObject* object = iter.next()) {
486 if(!object->is_valid())
489 object->action(elapsed_time);
493 for(GameObjects::iterator i = gameobjects.begin();
494 i != gameobjects.end(); ++i) {
495 GameObject* object = *i;
496 if(!object->is_valid())
499 object->action(elapsed_time);
503 /* Handle all possible collisions. */
505 update_game_objects();
509 Sector::update_game_objects()
511 /** cleanup marked objects */
512 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
513 i != gameobjects.end(); /* nothing */) {
514 GameObject* object = *i;
516 if(object->is_valid()) {
521 Bullet* bullet = dynamic_cast<Bullet*> (object);
524 std::remove(bullets.begin(), bullets.end(), bullet),
527 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
529 grid->remove_object(movingobject);
532 i = gameobjects.erase(i);
535 /* add newly created objects */
536 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
537 i != gameobjects_new.end(); ++i)
539 GameObject* object = *i;
541 Bullet* bullet = dynamic_cast<Bullet*> (object);
543 bullets.push_back(bullet);
545 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
547 grid->add_object(movingobject);
549 TileMap* tilemap = dynamic_cast<TileMap*> (object);
550 if(tilemap && tilemap->is_solid()) {
554 std::cerr << "Another solid tilemaps added. Ignoring.";
558 Camera* camera = dynamic_cast<Camera*> (object);
560 if(this->camera != 0) {
561 std::cerr << "Warning: Multiple cameras added. Ignoring.";
564 this->camera = camera;
567 gameobjects.push_back(object);
569 gameobjects_new.clear();
573 Sector::draw(DrawingContext& context)
575 context.push_transform();
576 context.set_translation(camera->get_translation());
579 CollisionGridIterator iter(*grid, get_active_region());
580 while(MovingObject* object = iter.next()) {
581 if(!object->is_valid())
584 object->draw(context);
587 for(GameObjects::iterator i = gameobjects.begin();
588 i != gameobjects.end(); ++i) {
589 GameObject* object = *i;
590 if(!object->is_valid())
593 object->draw(context);
597 context.pop_transform();
600 static const float DELTA = .001;
603 Sector::collision_tilemap(MovingObject* object, int depth)
607 std::cout << "Max collision depth reached.\n";
609 object->movement = Vector(0, 0);
613 // calculate rectangle where the object will move
615 if(object->get_movement().x >= 0) {
616 x1 = object->get_pos().x;
617 x2 = object->get_bbox().p2.x + object->get_movement().x;
619 x1 = object->get_pos().x + object->get_movement().x;
620 x2 = object->get_bbox().p2.x;
623 if(object->get_movement().y >= 0) {
624 y1 = object->get_pos().y;
625 y2 = object->get_bbox().p2.y + object->get_movement().y;
627 y1 = object->get_pos().y + object->get_movement().y;
628 y2 = object->get_bbox().p2.y;
631 // test with all tiles in this rectangle
632 int starttilex = int(x1-1) / 32;
633 int starttiley = int(y1-1) / 32;
634 int max_x = int(x2+1);
635 int max_y = int(y2+1);
637 CollisionHit temphit, hit;
638 Rect dest = object->get_bbox();
639 dest.move(object->movement);
640 hit.time = -1; // represents an invalid value
641 for(int x = starttilex; x*32 < max_x; ++x) {
642 for(int y = starttiley; y*32 < max_y; ++y) {
643 const Tile* tile = solids->get_tile(x, y);
646 // skip non-solid tiles
647 if(!(tile->getAttributes() & Tile::SOLID))
649 // only handle unisolid when the player is falling down and when he was
650 // above the tile before
651 if(tile->getAttributes() & Tile::UNISOLID) {
652 if(object->movement.y < 0 || object->get_bbox().p2.y > y*32)
656 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
658 Vector p1(x*32, y*32);
659 Vector p2((x+1)*32, (y+1)*32);
660 triangle = AATriangle(p1, p2, tile->getData());
662 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
664 if(temphit.time > hit.time)
667 } else { // normal rectangular tile
668 Rect rect(x*32, y*32, (x+1)*32, (y+1)*32);
669 if(Collision::rectangle_rectangle(temphit, dest,
670 object->movement, rect)) {
671 if(temphit.time > hit.time)
678 // did we collide at all?
682 // call collision function
683 HitResponse response = object->collision(*solids, hit);
684 if(response == ABORT_MOVE) {
685 object->movement = Vector(0, 0);
688 if(response == FORCE_MOVE) {
691 // move out of collision and try again
692 object->movement += hit.normal * (hit.depth + DELTA);
693 collision_tilemap(object, depth+1);
697 Sector::collision_object(MovingObject* object1, MovingObject* object2)
700 Rect dest1 = object1->get_bbox();
701 dest1.move(object1->get_movement());
702 Rect dest2 = object2->get_bbox();
703 dest2.move(object2->get_movement());
705 Vector movement = object1->get_movement() - object2->get_movement();
706 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
707 HitResponse response1 = object1->collision(*object2, hit);
709 HitResponse response2 = object2->collision(*object1, hit);
711 if(response1 != CONTINUE) {
712 if(response1 == ABORT_MOVE)
713 object1->movement = Vector(0, 0);
714 if(response2 == CONTINUE)
715 object2->movement += hit.normal * (hit.depth + DELTA);
716 } else if(response2 != CONTINUE) {
717 if(response2 == ABORT_MOVE)
718 object2->movement = Vector(0, 0);
719 if(response1 == CONTINUE)
720 object1->movement += -hit.normal * (hit.depth + DELTA);
722 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
723 object2->movement += hit.normal * (hit.depth/2 + DELTA);
729 Sector::collision_handler()
732 grid->check_collisions();
734 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
735 i != gameobjects.end(); ++i) {
736 GameObject* gameobject = *i;
737 if(!gameobject->is_valid())
739 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
742 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
743 movingobject->bbox.move(movingobject->movement);
744 movingobject->movement = Vector(0, 0);
748 // collision with tilemap
749 if(! (movingobject->movement == Vector(0, 0)))
750 collision_tilemap(movingobject, 0);
752 // collision with other objects
753 for(std::vector<GameObject*>::iterator i2 = i+1;
754 i2 != gameobjects.end(); ++i2) {
755 GameObject* other_object = *i2;
756 if(!other_object->is_valid()
757 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
759 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
763 collision_object(movingobject, movingobject2);
766 movingobject->bbox.move(movingobject->get_movement());
767 movingobject->movement = Vector(0, 0);
773 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
775 // TODO remove this function and move these checks elsewhere...
776 static const size_t MAX_FIRE_BULLETS = 2;
777 static const size_t MAX_ICE_BULLETS = 1;
779 Bullet* new_bullet = 0;
780 if(player_status.bonus == FIRE_BONUS) {
781 if(bullets.size() > MAX_FIRE_BULLETS-1)
783 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
784 } else if(player_status.bonus == ICE_BONUS) {
785 if(bullets.size() > MAX_ICE_BULLETS-1)
787 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
791 add_object(new_bullet);
793 sound_manager->play_sound("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));
814 level_song = sound_manager->load_music(
815 get_resource_filename("/music/" + song_title));
819 Sector::play_music(MusicType type)
822 switch(currentmusic) {
824 sound_manager->play_music(level_song);
827 sound_manager->play_music(herring_song);
830 sound_manager->halt_music();
836 Sector::get_music_type()
842 Sector::get_total_badguys()
844 int total_badguys = 0;
845 for(GameObjects::iterator i = gameobjects.begin();
846 i != gameobjects.end(); ++i) {
847 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
852 return total_badguys;
856 Sector::inside(const Rect& rect) const
858 if(rect.p1.x > solids->get_width() * 32
859 || rect.p1.y > solids->get_height() * 32
860 || rect.p2.x < 0 || rect.p2.y < 0)