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 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 ScriptInterpreter* interpreter = new ScriptInterpreter(this);
426 std::string sourcename = std::string("Sector(") + name + ") - init";
427 std::istringstream in(init_script);
428 interpreter->load_script(in, sourcename);
429 interpreter->start_script();
430 add_object(interpreter);
432 } catch(std::exception& e) {
433 std::cerr << "Couldn't execute init script: " << e.what() << "\n";
439 Sector::activate(const Vector& player_pos)
443 player->move(player_pos);
444 camera->reset(player->get_pos());
448 Sector::get_active_region()
451 camera->get_translation() - Vector(1600, 1200),
452 camera->get_translation() + Vector(1600, 1200));
456 Sector::update(float elapsed_time)
458 player->check_bounds(camera);
461 CollisionGridIterator iter(*grid, get_active_region());
462 while(MovingObject* object = iter.next()) {
463 if(!object->is_valid())
466 object->update(elapsed_time);
470 for(GameObjects::iterator i = gameobjects.begin();
471 i != gameobjects.end(); ++i) {
472 GameObject* object = *i;
473 if(!object->is_valid())
476 object->update(elapsed_time);
480 /* Handle all possible collisions. */
482 update_game_objects();
486 Sector::update_game_objects()
488 /** cleanup marked objects */
489 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
490 i != gameobjects.end(); /* nothing */) {
491 GameObject* object = *i;
493 if(object->is_valid()) {
498 Bullet* bullet = dynamic_cast<Bullet*> (object);
501 std::remove(bullets.begin(), bullets.end(), bullet),
504 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
506 grid->remove_object(movingobject);
509 i = gameobjects.erase(i);
512 /* add newly created objects */
513 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
514 i != gameobjects_new.end(); ++i)
516 GameObject* object = *i;
518 Bullet* bullet = dynamic_cast<Bullet*> (object);
520 bullets.push_back(bullet);
522 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
524 grid->add_object(movingobject);
526 TileMap* tilemap = dynamic_cast<TileMap*> (object);
527 if(tilemap && tilemap->is_solid()) {
531 std::cerr << "Another solid tilemaps added. Ignoring.";
535 Camera* camera = dynamic_cast<Camera*> (object);
537 if(this->camera != 0) {
538 std::cerr << "Warning: Multiple cameras added. Ignoring.";
541 this->camera = camera;
544 gameobjects.push_back(object);
546 gameobjects_new.clear();
550 Sector::draw(DrawingContext& context)
552 context.push_transform();
553 context.set_translation(camera->get_translation());
556 CollisionGridIterator iter(*grid, get_active_region());
557 while(MovingObject* object = iter.next()) {
558 if(!object->is_valid())
561 object->draw(context);
564 for(GameObjects::iterator i = gameobjects.begin();
565 i != gameobjects.end(); ++i) {
566 GameObject* object = *i;
567 if(!object->is_valid())
570 object->draw(context);
574 context.pop_transform();
577 static const float DELTA = .001;
580 Sector::collision_tilemap(MovingObject* object, int depth)
584 std::cout << "Max collision depth reached.\n";
586 object->movement = Vector(0, 0);
590 // calculate rectangle where the object will move
592 if(object->get_movement().x >= 0) {
593 x1 = object->get_pos().x;
594 x2 = object->get_bbox().p2.x + object->get_movement().x;
596 x1 = object->get_pos().x + object->get_movement().x;
597 x2 = object->get_bbox().p2.x;
600 if(object->get_movement().y >= 0) {
601 y1 = object->get_pos().y;
602 y2 = object->get_bbox().p2.y + object->get_movement().y;
604 y1 = object->get_pos().y + object->get_movement().y;
605 y2 = object->get_bbox().p2.y;
608 // test with all tiles in this rectangle
609 int starttilex = int(x1-1) / 32;
610 int starttiley = int(y1-1) / 32;
611 int max_x = int(x2+1);
612 int max_y = int(y2+1);
614 CollisionHit temphit, hit;
615 Rect dest = object->get_bbox();
616 dest.move(object->movement);
617 hit.time = -1; // represents an invalid value
618 for(int x = starttilex; x*32 < max_x; ++x) {
619 for(int y = starttiley; y*32 < max_y; ++y) {
620 const Tile* tile = solids->get_tile(x, y);
623 // skip non-solid tiles
624 if(!(tile->getAttributes() & Tile::SOLID))
626 // only handle unisolid when the player is falling down and when he was
627 // above the tile before
628 if(tile->getAttributes() & Tile::UNISOLID) {
629 if(object->movement.y < 0 || object->get_bbox().p2.y > y*32)
633 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
635 Vector p1(x*32, y*32);
636 Vector p2((x+1)*32, (y+1)*32);
637 triangle = AATriangle(p1, p2, tile->getData());
639 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
641 if(temphit.time > hit.time)
644 } else { // normal rectangular tile
645 Rect rect(x*32, y*32, (x+1)*32, (y+1)*32);
646 if(Collision::rectangle_rectangle(temphit, dest,
647 object->movement, rect)) {
648 if(temphit.time > hit.time)
655 // did we collide at all?
659 // call collision function
660 HitResponse response = object->collision(*solids, hit);
661 if(response == ABORT_MOVE) {
662 object->movement = Vector(0, 0);
665 if(response == FORCE_MOVE) {
668 // move out of collision and try again
669 object->movement += hit.normal * (hit.depth + DELTA);
670 collision_tilemap(object, depth+1);
674 Sector::collision_object(MovingObject* object1, MovingObject* object2)
677 Rect dest1 = object1->get_bbox();
678 dest1.move(object1->get_movement());
679 Rect dest2 = object2->get_bbox();
680 dest2.move(object2->get_movement());
682 Vector movement = object1->get_movement() - object2->get_movement();
683 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
684 HitResponse response1 = object1->collision(*object2, hit);
686 HitResponse response2 = object2->collision(*object1, hit);
688 if(response1 != CONTINUE) {
689 if(response1 == ABORT_MOVE)
690 object1->movement = Vector(0, 0);
691 if(response2 == CONTINUE)
692 object2->movement += hit.normal * (hit.depth + DELTA);
693 } else if(response2 != CONTINUE) {
694 if(response2 == ABORT_MOVE)
695 object2->movement = Vector(0, 0);
696 if(response1 == CONTINUE)
697 object1->movement += -hit.normal * (hit.depth + DELTA);
699 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
700 object2->movement += hit.normal * (hit.depth/2 + DELTA);
706 Sector::collision_handler()
709 grid->check_collisions();
711 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
712 i != gameobjects.end(); ++i) {
713 GameObject* gameobject = *i;
714 if(!gameobject->is_valid())
716 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
719 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
720 movingobject->bbox.move(movingobject->movement);
721 movingobject->movement = Vector(0, 0);
725 // collision with tilemap
726 if(! (movingobject->movement == Vector(0, 0)))
727 collision_tilemap(movingobject, 0);
729 // collision with other objects
730 for(std::vector<GameObject*>::iterator i2 = i+1;
731 i2 != gameobjects.end(); ++i2) {
732 GameObject* other_object = *i2;
733 if(!other_object->is_valid()
734 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
736 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
740 collision_object(movingobject, movingobject2);
743 movingobject->bbox.move(movingobject->get_movement());
744 movingobject->movement = Vector(0, 0);
750 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
752 // TODO remove this function and move these checks elsewhere...
753 static const size_t MAX_FIRE_BULLETS = 2;
754 static const size_t MAX_ICE_BULLETS = 1;
756 Bullet* new_bullet = 0;
757 if(player_status.bonus == FIRE_BONUS) {
758 if(bullets.size() > MAX_FIRE_BULLETS-1)
760 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
761 } else if(player_status.bonus == ICE_BONUS) {
762 if(bullets.size() > MAX_ICE_BULLETS-1)
764 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
768 add_object(new_bullet);
770 sound_manager->play_sound("shoot");
776 Sector::add_smoke_cloud(const Vector& pos)
778 add_object(new SmokeCloud(pos));
783 Sector::add_floating_text(const Vector& pos, const std::string& text)
785 add_object(new FloatingText(pos, text));
791 level_song = sound_manager->load_music(
792 get_resource_filename("/music/" + song_title));
796 Sector::play_music(MusicType type)
799 switch(currentmusic) {
801 sound_manager->play_music(level_song);
804 sound_manager->play_music(herring_song);
807 sound_manager->halt_music();
813 Sector::get_music_type()
819 Sector::get_total_badguys()
821 int total_badguys = 0;
822 for(GameObjects::iterator i = gameobjects.begin();
823 i != gameobjects.end(); ++i) {
824 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
829 return total_badguys;
833 Sector::inside(const Rect& rect) const
835 if(rect.p1.x > solids->get_width() * 32
836 || rect.p1.y > solids->get_height() * 32
837 || rect.p2.x < 0 || rect.p2.y < 0)