1 // SuperTux - A Jump'n Run
2 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #include "supertux/sector.hpp"
22 #include "audio/sound_manager.hpp"
23 #include "badguy/jumpy.hpp"
24 #include "lisp/list_iterator.hpp"
25 #include "math/aatriangle.hpp"
26 #include "object/background.hpp"
27 #include "object/bonus_block.hpp"
28 #include "object/brick.hpp"
29 #include "object/bullet.hpp"
30 #include "object/camera.hpp"
31 #include "object/cloud_particle_system.hpp"
32 #include "object/coin.hpp"
33 #include "object/comet_particle_system.hpp"
34 #include "object/display_effect.hpp"
35 #include "object/ghost_particle_system.hpp"
36 #include "object/gradient.hpp"
37 #include "object/invisible_block.hpp"
38 #include "object/particlesystem.hpp"
39 #include "object/particlesystem_interactive.hpp"
40 #include "object/player.hpp"
41 #include "object/portable.hpp"
42 #include "object/pulsing_light.hpp"
43 #include "object/rain_particle_system.hpp"
44 #include "object/smoke_cloud.hpp"
45 #include "object/snow_particle_system.hpp"
46 #include "object/text_object.hpp"
47 #include "object/tilemap.hpp"
48 #include "physfs/ifile_streambuf.hpp"
49 #include "scripting/squirrel_util.hpp"
50 #include "supertux/collision.hpp"
51 #include "supertux/constants.hpp"
52 #include "supertux/game_session.hpp"
53 #include "supertux/globals.hpp"
54 #include "supertux/level.hpp"
55 #include "supertux/object_factory.hpp"
56 #include "supertux/player_status.hpp"
57 #include "supertux/savegame.hpp"
58 #include "supertux/spawn_point.hpp"
59 #include "supertux/tile.hpp"
60 #include "trigger/sequence_trigger.hpp"
61 #include "util/file_system.hpp"
63 Sector* Sector::_current = 0;
65 bool Sector::show_collrects = false;
66 bool Sector::draw_solids_only = false;
68 Sector::Sector(Level* parent) :
74 currentmusic(LEVEL_MUSIC),
77 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ),
89 add_object(new Player(GameSession::current()->get_savegame().get_player_status(), "Tux"));
90 add_object(new DisplayEffect("Effect"));
91 add_object(new TextObject("Text"));
93 sound_manager->preload("sounds/shoot.wav");
95 // create a new squirrel table for the sector
96 using namespace scripting;
98 sq_collectgarbage(global_vm);
100 sq_newtable(global_vm);
101 sq_pushroottable(global_vm);
102 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
103 throw scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
105 sq_resetobject(§or_table);
106 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
107 throw scripting::SquirrelError(global_vm, "Couldn't get sector table");
108 sq_addref(global_vm, §or_table);
109 sq_pop(global_vm, 1);
114 using namespace scripting;
118 for(ScriptList::iterator i = scripts.begin();
119 i != scripts.end(); ++i) {
120 HSQOBJECT& object = *i;
121 sq_release(global_vm, &object);
123 sq_release(global_vm, §or_table);
124 sq_collectgarbage(global_vm);
126 update_game_objects();
127 assert(gameobjects_new.size() == 0);
129 for(GameObjects::iterator i = gameobjects.begin();
130 i != gameobjects.end(); ++i) {
131 GameObject* object = *i;
132 before_object_remove(object);
136 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
148 Sector::parse_object(const std::string& name_, const Reader& reader)
150 if(name_ == "camera") {
151 Camera* camera_ = new Camera(this, "Camera");
152 camera_->parse(reader);
154 } else if(name_ == "particles-snow") {
155 SnowParticleSystem* partsys = new SnowParticleSystem();
156 partsys->parse(reader);
158 } else if(name_ == "particles-rain") {
159 RainParticleSystem* partsys = new RainParticleSystem();
160 partsys->parse(reader);
162 } else if(name_ == "particles-comets") {
163 CometParticleSystem* partsys = new CometParticleSystem();
164 partsys->parse(reader);
166 } else if(name_ == "particles-ghosts") {
167 GhostParticleSystem* partsys = new GhostParticleSystem();
168 partsys->parse(reader);
170 } else if(name_ == "particles-clouds") {
171 CloudParticleSystem* partsys = new CloudParticleSystem();
172 partsys->parse(reader);
174 } else if(name_ == "money") { // for compatibility with old maps
175 return new Jumpy(reader);
178 return ObjectFactory::instance().create(name_, reader);
179 } catch(std::exception& e) {
180 log_warning << e.what() << "" << std::endl;
187 Sector::parse(const Reader& sector)
189 bool has_background = false;
190 lisp::ListIterator iter(§or);
192 const std::string& token = iter.item();
193 if(token == "name") {
194 iter.value()->get(name);
195 } else if(token == "gravity") {
196 iter.value()->get(gravity);
197 } else if(token == "music") {
198 iter.value()->get(music);
199 } else if(token == "spawnpoint") {
200 SpawnPoint* sp = new SpawnPoint(*iter.lisp());
201 spawnpoints.push_back(sp);
202 } else if(token == "init-script") {
203 iter.value()->get(init_script);
204 } else if(token == "ambient-light") {
205 std::vector<float> vColor;
206 sector.get( "ambient-light", vColor );
207 if(vColor.size() < 3) {
208 log_warning << "(ambient-light) requires a color as argument" << std::endl;
210 ambient_light = Color( vColor );
213 GameObject* object = parse_object(token, *(iter.lisp()));
215 if(dynamic_cast<Background *>(object)) {
216 has_background = true;
217 } else if(dynamic_cast<Gradient *>(object)) {
218 has_background = true;
225 if(!has_background) {
226 Gradient* gradient = new Gradient();
227 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
228 add_object(gradient);
231 update_game_objects();
233 if(solid_tilemaps.size() < 1) { log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl; }
237 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
238 update_game_objects();
239 add_object(new Camera(this, "Camera"));
242 update_game_objects();
246 Sector::parse_old_format(const Reader& reader)
249 reader.get("gravity", gravity);
251 std::string backgroundimage;
252 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
253 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
254 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
255 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
256 backgroundimage = "images/background/" + backgroundimage;
257 if (!PHYSFS_exists(backgroundimage.c_str())) {
258 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
259 backgroundimage = "";
264 reader.get("bkgd_speed", bgspeed);
267 Color bkgd_top, bkgd_bottom;
268 int r = 0, g = 0, b = 128;
269 reader.get("bkgd_red_top", r);
270 reader.get("bkgd_green_top", g);
271 reader.get("bkgd_blue_top", b);
272 bkgd_top.red = static_cast<float> (r) / 255.0f;
273 bkgd_top.green = static_cast<float> (g) / 255.0f;
274 bkgd_top.blue = static_cast<float> (b) / 255.0f;
276 reader.get("bkgd_red_bottom", r);
277 reader.get("bkgd_green_bottom", g);
278 reader.get("bkgd_blue_bottom", b);
279 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
280 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
281 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
283 if(backgroundimage != "") {
284 Background* background = new Background();
285 background->set_image(backgroundimage, bgspeed);
286 add_object(background);
288 Gradient* gradient = new Gradient();
289 gradient->set_gradient(bkgd_top, bkgd_bottom);
290 add_object(gradient);
293 std::string particlesystem;
294 reader.get("particle_system", particlesystem);
295 if(particlesystem == "clouds")
296 add_object(new CloudParticleSystem());
297 else if(particlesystem == "snow")
298 add_object(new SnowParticleSystem());
299 else if(particlesystem == "rain")
300 add_object(new RainParticleSystem());
302 Vector startpos(100, 170);
303 reader.get("start_pos_x", startpos.x);
304 reader.get("start_pos_y", startpos.y);
306 SpawnPoint* spawn = new SpawnPoint;
307 spawn->pos = startpos;
308 spawn->name = "main";
309 spawnpoints.push_back(spawn);
311 music = "chipdisko.ogg";
312 // skip reading music filename. It's all .ogg now, anyway
314 reader.get("music", music);
316 music = "music/" + music;
318 int width = 30, height = 15;
319 reader.get("width", width);
320 reader.get("height", height);
322 std::vector<unsigned int> tiles;
323 if(reader.get("interactive-tm", tiles)
324 || reader.get("tilemap", tiles)) {
325 TileMap* tilemap = new TileMap(level->get_tileset());
326 tilemap->set(width, height, tiles, LAYER_TILES, true);
328 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
329 for(size_t x=0; x < tilemap->get_width(); ++x) {
330 for(size_t y=0; y < tilemap->get_height(); ++y) {
331 uint32_t id = tilemap->get_tile_id(x, y);
333 tilemap->change(x, y, 1311);
337 if (height < 19) tilemap->resize(width, 19);
341 if(reader.get("background-tm", tiles)) {
342 TileMap* tilemap = new TileMap(level->get_tileset());
343 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
344 if (height < 19) tilemap->resize(width, 19);
348 if(reader.get("foreground-tm", tiles)) {
349 TileMap* tilemap = new TileMap(level->get_tileset());
350 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
352 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
353 if (height < 19) tilemap->resize(width, 19, 2035);
358 // read reset-points (now spawn-points)
359 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
361 lisp::ListIterator iter(resetpoints);
363 if(iter.item() == "point") {
365 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
367 SpawnPoint* sp = new SpawnPoint;
370 spawnpoints.push_back(sp);
373 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
379 const lisp::Lisp* objects = reader.get_lisp("objects");
381 lisp::ListIterator iter(objects);
383 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
387 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
393 Camera* camera_ = new Camera(this, "Camera");
396 update_game_objects();
398 if(solid_tilemaps.size() < 1) { log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl; }
401 update_game_objects();
405 Sector::fix_old_tiles()
407 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
408 TileMap* solids = *i;
409 for(size_t x=0; x < solids->get_width(); ++x) {
410 for(size_t y=0; y < solids->get_height(); ++y) {
411 uint32_t id = solids->get_tile_id(x, y);
412 const Tile *tile = solids->get_tile(x, y);
413 Vector pos = solids->get_tile_position(x, y);
416 add_object(new InvisibleBlock(pos));
417 solids->change(x, y, 0);
418 } else if(tile->getAttributes() & Tile::COIN) {
419 add_object(new Coin(pos, solids));
420 solids->change(x, y, 0);
421 } else if(tile->getAttributes() & Tile::FULLBOX) {
422 add_object(new BonusBlock(pos, tile->getData()));
423 solids->change(x, y, 0);
424 } else if(tile->getAttributes() & Tile::BRICK) {
425 if( ( id == 78 ) || ( id == 105 ) ){
426 add_object( new Brick(pos, tile->getData(), "images/objects/bonus_block/brickIce.sprite") );
427 } else if( ( id == 77 ) || ( id == 104 ) ){
428 add_object( new Brick(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
430 log_warning << "attribute 'brick #t' is not supported for tile-id " << id << std::endl;
431 add_object( new Brick(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
433 solids->change(x, y, 0);
434 } else if(tile->getAttributes() & Tile::GOAL) {
435 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
436 add_object(new SequenceTrigger(pos, sequence));
437 solids->change(x, y, 0);
443 // add lights for special tiles
444 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
445 TileMap* tm = dynamic_cast<TileMap*>(*i);
447 for(size_t x=0; x < tm->get_width(); ++x) {
448 for(size_t y=0; y < tm->get_height(); ++y) {
449 uint32_t id = tm->get_tile_id(x, y);
450 Vector pos = tm->get_tile_position(x, y);
451 Vector center = pos + Vector(16, 16);
455 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
456 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
459 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
460 // space lights a bit
461 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
462 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
463 || ((x % 3 == 0) && (y % 3 == 0))) {
464 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
465 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
476 Sector::run_script(std::istream& in, const std::string& sourcename)
478 using namespace scripting;
480 // garbage collect thread list
481 for(ScriptList::iterator i = scripts.begin();
482 i != scripts.end(); ) {
483 HSQOBJECT& object = *i;
484 HSQUIRRELVM vm = object_to_vm(object);
486 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
487 sq_release(global_vm, &object);
488 i = scripts.erase(i);
495 HSQOBJECT object = create_thread(global_vm);
496 scripts.push_back(object);
498 HSQUIRRELVM vm = object_to_vm(object);
500 // set sector_table as roottable for the thread
501 sq_pushobject(vm, sector_table);
505 compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
506 } catch(std::exception& e) {
507 log_warning << "Error running script: " << e.what() << std::endl;
514 Sector::add_object(GameObject* object)
516 // make sure the object isn't already in the list
518 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
520 assert(*i != object);
522 for(GameObjects::iterator i = gameobjects_new.begin();
523 i != gameobjects_new.end(); ++i) {
524 assert(*i != object);
529 gameobjects_new.push_back(object);
533 Sector::activate(const std::string& spawnpoint)
536 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
538 if((*i)->name == spawnpoint) {
544 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
545 if(spawnpoint != "main") {
548 activate(Vector(0, 0));
556 Sector::activate(const Vector& player_pos)
558 if(_current != this) {
560 _current->deactivate();
563 // register sectortable as sector in scripting
564 HSQUIRRELVM vm = scripting::global_vm;
565 sq_pushroottable(vm);
566 sq_pushstring(vm, "sector", -1);
567 sq_pushobject(vm, sector_table);
568 if(SQ_FAILED(sq_createslot(vm, -3)))
569 throw scripting::SquirrelError(vm, "Couldn't set sector in roottable");
572 for(GameObjects::iterator i = gameobjects.begin();
573 i != gameobjects.end(); ++i) {
574 GameObject* object = *i;
582 // two-player hack: move other players to main player's position
583 // Maybe specify 2 spawnpoints in the level?
584 for(GameObjects::iterator i = gameobjects.begin();
585 i != gameobjects.end(); ++i) {
586 Player* p = dynamic_cast<Player*>(*i);
589 // spawn smalltux below spawnpoint
591 p->move(player_pos + Vector(0,32));
596 // spawning tux in the ground would kill him
597 if(!is_free_of_tiles(p->get_bbox())) {
598 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
599 Vector npos = p->get_bbox().p1;
605 //FIXME: This is a really dirty workaround for this strange camera jump
606 player->move(player->get_pos()+Vector(-32, 0));
607 camera->reset(player->get_pos());
609 player->move(player->get_pos()+(Vector(32, 0)));
612 update_game_objects();
614 //Run default.nut just before init script
615 //Check to see if it's in a levelset (info file)
616 std::string basedir = FileSystem::dirname(get_level()->filename);
617 if(PHYSFS_exists((basedir + "/info").c_str())) {
619 IFileStreambuf ins(basedir + "/default.nut");
620 std::istream in(&ins);
621 run_script(in, "default.nut");
622 } catch(std::exception& ) {
623 // doesn't exist or erroneous; do nothing
628 if(init_script != "") {
629 std::istringstream in(init_script);
630 run_script(in, "init-script");
640 // remove sector entry from global vm
641 HSQUIRRELVM vm = scripting::global_vm;
642 sq_pushroottable(vm);
643 sq_pushstring(vm, "sector", -1);
644 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
645 throw scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
648 for(GameObjects::iterator i = gameobjects.begin();
649 i != gameobjects.end(); ++i) {
650 GameObject* object = *i;
652 try_unexpose(object);
660 Sector::get_active_region()
663 camera->get_translation() - Vector(1600, 1200),
664 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
668 Sector::update(float elapsed_time)
670 player->check_bounds();
673 for(GameObjects::iterator i = gameobjects.begin();
674 i != gameobjects.end(); ++i) {
675 GameObject* object = *i;
676 if(!object->is_valid())
679 object->update(elapsed_time);
682 /* Handle all possible collisions. */
684 update_game_objects();
688 Sector::update_game_objects()
690 /** cleanup marked objects */
691 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
692 i != gameobjects.end(); /* nothing */) {
693 GameObject* object = *i;
695 if(object->is_valid()) {
700 before_object_remove(object);
703 i = gameobjects.erase(i);
706 /* add newly created objects */
707 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
708 i != gameobjects_new.end(); ++i)
710 GameObject* object = *i;
712 before_object_add(object);
714 gameobjects.push_back(object);
716 gameobjects_new.clear();
718 /* update solid_tilemaps list */
719 //FIXME: this could be more efficient
720 solid_tilemaps.clear();
721 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
722 i != gameobjects.end(); ++i)
724 TileMap* tm = dynamic_cast<TileMap*>(*i);
726 if (tm->is_solid()) solid_tilemaps.push_back(tm);
732 Sector::before_object_add(GameObject* object)
734 Bullet* bullet = dynamic_cast<Bullet*> (object);
736 bullets.push_back(bullet);
739 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
740 if(movingobject != NULL) {
741 moving_objects.push_back(movingobject);
744 Portable* portable = dynamic_cast<Portable*> (object);
745 if(portable != NULL) {
746 portables.push_back(portable);
749 TileMap* tilemap = dynamic_cast<TileMap*> (object);
750 if(tilemap != NULL && tilemap->is_solid()) {
751 solid_tilemaps.push_back(tilemap);
754 Camera* camera_ = dynamic_cast<Camera*> (object);
755 if(camera_ != NULL) {
756 if(this->camera != 0) {
757 log_warning << "Multiple cameras added. Ignoring" << std::endl;
760 this->camera = camera_;
763 Player* player_ = dynamic_cast<Player*> (object);
764 if(player_ != NULL) {
765 if(this->player != 0) {
766 log_warning << "Multiple players added. Ignoring" << std::endl;
769 this->player = player_;
772 DisplayEffect* effect_ = dynamic_cast<DisplayEffect*> (object);
773 if(effect_ != NULL) {
774 if(this->effect != 0) {
775 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
778 this->effect = effect_;
781 if(_current == this) {
789 Sector::try_expose(GameObject* object)
791 ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
792 if(object_ != NULL) {
793 HSQUIRRELVM vm = scripting::global_vm;
794 sq_pushobject(vm, sector_table);
795 object_->expose(vm, -1);
801 Sector::try_expose_me()
803 HSQUIRRELVM vm = scripting::global_vm;
804 sq_pushobject(vm, sector_table);
805 scripting::SSector* this_ = static_cast<scripting::SSector*> (this);
806 expose_object(vm, -1, this_, "settings", false);
811 Sector::before_object_remove(GameObject* object)
813 Portable* portable = dynamic_cast<Portable*> (object);
814 if(portable != NULL) {
815 portables.erase(std::find(portables.begin(), portables.end(), portable));
817 Bullet* bullet = dynamic_cast<Bullet*> (object);
819 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
821 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
822 if(moving_object != NULL) {
823 moving_objects.erase(
824 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
828 try_unexpose(object);
832 Sector::try_unexpose(GameObject* object)
834 ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
835 if(object_ != NULL) {
836 HSQUIRRELVM vm = scripting::global_vm;
837 SQInteger oldtop = sq_gettop(vm);
838 sq_pushobject(vm, sector_table);
840 object_->unexpose(vm, -1);
841 } catch(std::exception& e) {
842 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
844 sq_settop(vm, oldtop);
849 Sector::try_unexpose_me()
851 HSQUIRRELVM vm = scripting::global_vm;
852 SQInteger oldtop = sq_gettop(vm);
853 sq_pushobject(vm, sector_table);
855 scripting::unexpose_object(vm, -1, "settings");
856 } catch(std::exception& e) {
857 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
859 sq_settop(vm, oldtop);
862 Sector::draw(DrawingContext& context)
864 context.set_ambient_color( ambient_light );
865 context.push_transform();
866 context.set_translation(camera->get_translation());
868 for(GameObjects::iterator i = gameobjects.begin();
869 i != gameobjects.end(); ++i) {
870 GameObject* object = *i;
871 if(!object->is_valid())
874 if (draw_solids_only)
876 TileMap* tm = dynamic_cast<TileMap*>(object);
877 if (tm && !tm->is_solid())
881 object->draw(context);
885 Color color(1.0f, 0.0f, 0.0f, 0.75f);
886 for(MovingObjects::iterator i = moving_objects.begin();
887 i != moving_objects.end(); ++i) {
888 MovingObject* object = *i;
889 const Rectf& rect = object->get_bbox();
891 context.draw_filled_rect(rect, color, LAYER_FOREGROUND1 + 10);
895 context.pop_transform();
898 /*-------------------------------------------------------------------------
899 * Collision Detection
900 *-------------------------------------------------------------------------*/
902 /** r1 is supposed to be moving, r2 a solid object */
903 void check_collisions(collision::Constraints* constraints,
904 const Vector& obj_movement, const Rectf& obj_rect, const Rectf& other_rect,
905 GameObject* object = NULL, MovingObject* other = NULL, const Vector& other_movement = Vector(0,0))
907 if(!collision::intersects(obj_rect, other_rect))
910 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
912 if(other != NULL && !other->collides(*object, dummy))
914 if(moving_object != NULL && !moving_object->collides(*other, dummy))
917 // calculate intersection
918 float itop = obj_rect.get_bottom() - other_rect.get_top();
919 float ibottom = other_rect.get_bottom() - obj_rect.get_top();
920 float ileft = obj_rect.get_right() - other_rect.get_left();
921 float iright = other_rect.get_right() - obj_rect.get_left();
923 if(fabsf(obj_movement.y) > fabsf(obj_movement.x)) {
924 if(ileft < SHIFT_DELTA) {
925 constraints->constrain_right(other_rect.get_left(), other_movement.x);
927 } else if(iright < SHIFT_DELTA) {
928 constraints->constrain_left(other_rect.get_right(), other_movement.x);
932 // shiftout bottom/top
933 if(itop < SHIFT_DELTA) {
934 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
936 } else if(ibottom < SHIFT_DELTA) {
937 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
942 constraints->ground_movement += other_movement;
944 HitResponse response = other->collision(*object, dummy);
945 if(response == ABORT_MOVE)
948 if(other->get_movement() != Vector(0, 0)) {
949 // TODO what todo when we collide with 2 moving objects?!?
950 constraints->ground_movement = other->get_movement();
954 float vert_penetration = std::min(itop, ibottom);
955 float horiz_penetration = std::min(ileft, iright);
956 if(vert_penetration < horiz_penetration) {
958 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
959 constraints->hit.bottom = true;
961 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
962 constraints->hit.top = true;
966 constraints->constrain_right(other_rect.get_left(), other_movement.x);
967 constraints->hit.right = true;
969 constraints->constrain_left(other_rect.get_right(), other_movement.x);
970 constraints->hit.left = true;
976 Sector::collision_tilemap(collision::Constraints* constraints,
977 const Vector& movement, const Rectf& dest,
978 MovingObject& object) const
980 // calculate rectangle where the object will move
981 float x1 = dest.get_left();
982 float x2 = dest.get_right();
983 float y1 = dest.get_top();
984 float y2 = dest.get_bottom();
986 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
987 TileMap* solids = *i;
989 // test with all tiles in this rectangle
990 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
992 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
993 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
994 const Tile* tile = solids->get_tile(x, y);
997 // skip non-solid tiles
998 if(!tile->is_solid ())
1000 Rectf tile_bbox = solids->get_tile_bbox(x, y);
1002 /* If the tile is a unisolid tile, the "is_solid()" function above
1003 * didn't do a thorough check. Calculate the position and (relative)
1004 * movement of the object and determine whether or not the tile is
1005 * solid with regard to those parameters. */
1006 if(tile->is_unisolid ()) {
1007 Vector relative_movement = movement
1008 - solids->get_movement(/* actual = */ true);
1010 if (!tile->is_solid (tile_bbox, object.get_bbox(), relative_movement))
1012 } /* if (tile->is_unisolid ()) */
1014 if(tile->is_slope ()) { // slope tile
1015 AATriangle triangle;
1016 int slope_data = tile->getData();
1017 if (solids->get_drawing_effect() & VERTICAL_FLIP)
1018 slope_data = AATriangle::vertical_flip(slope_data);
1019 triangle = AATriangle(tile_bbox, slope_data);
1021 collision::rectangle_aatriangle(constraints, dest, triangle,
1022 solids->get_movement(/* actual = */ false));
1023 } else { // normal rectangular tile
1024 check_collisions(constraints, movement, dest, tile_bbox, NULL, NULL,
1025 solids->get_movement(/* actual = */ false));
1033 Sector::collision_tile_attributes(const Rectf& dest) const
1035 float x1 = dest.p1.x;
1036 float y1 = dest.p1.y;
1037 float x2 = dest.p2.x;
1038 float y2 = dest.p2.y;
1040 uint32_t result = 0;
1041 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1042 TileMap* solids = *i;
1044 // test with all tiles in this rectangle
1045 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1046 // For ice (only), add a little fudge to recognize tiles Tux is standing on.
1047 Rect test_tiles_ice = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2 + SHIFT_DELTA));
1049 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1051 for(y = test_tiles.top; y < test_tiles.bottom; ++y) {
1052 const Tile* tile = solids->get_tile(x, y);
1055 result |= tile->getAttributes();
1057 for(; y < test_tiles_ice.bottom; ++y) {
1058 const Tile* tile = solids->get_tile(x, y);
1061 result |= (tile->getAttributes() & Tile::ICE);
1069 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1070 static void get_hit_normal(const Rectf& r1, const Rectf& r2, CollisionHit& hit,
1073 float itop = r1.get_bottom() - r2.get_top();
1074 float ibottom = r2.get_bottom() - r1.get_top();
1075 float ileft = r1.get_right() - r2.get_left();
1076 float iright = r2.get_right() - r1.get_left();
1078 float vert_penetration = std::min(itop, ibottom);
1079 float horiz_penetration = std::min(ileft, iright);
1080 if(vert_penetration < horiz_penetration) {
1081 if(itop < ibottom) {
1083 normal.y = vert_penetration;
1086 normal.y = -vert_penetration;
1089 if(ileft < iright) {
1091 normal.x = horiz_penetration;
1094 normal.x = -horiz_penetration;
1100 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1102 using namespace collision;
1104 const Rectf& r1 = object1->dest;
1105 const Rectf& r2 = object2->dest;
1108 if(intersects(object1->dest, object2->dest)) {
1110 get_hit_normal(r1, r2, hit, normal);
1112 if(!object1->collides(*object2, hit))
1114 std::swap(hit.left, hit.right);
1115 std::swap(hit.top, hit.bottom);
1116 if(!object2->collides(*object1, hit))
1118 std::swap(hit.left, hit.right);
1119 std::swap(hit.top, hit.bottom);
1121 HitResponse response1 = object1->collision(*object2, hit);
1122 std::swap(hit.left, hit.right);
1123 std::swap(hit.top, hit.bottom);
1124 HitResponse response2 = object2->collision(*object1, hit);
1125 if(response1 == CONTINUE && response2 == CONTINUE) {
1126 normal *= (0.5 + DELTA);
1127 object1->dest.move(-normal);
1128 object2->dest.move(normal);
1129 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1130 normal *= (1 + DELTA);
1131 object1->dest.move(-normal);
1132 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1133 normal *= (1 + DELTA);
1134 object2->dest.move(normal);
1140 Sector::collision_static(collision::Constraints* constraints,
1141 const Vector& movement, const Rectf& dest,
1142 MovingObject& object)
1144 collision_tilemap(constraints, movement, dest, object);
1146 // collision with other (static) objects
1147 for(MovingObjects::iterator i = moving_objects.begin();
1148 i != moving_objects.end(); ++i) {
1149 MovingObject* moving_object = *i;
1150 if(moving_object->get_group() != COLGROUP_STATIC
1151 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1153 if(!moving_object->is_valid())
1156 if(moving_object != &object)
1157 check_collisions(constraints, movement, dest, moving_object->bbox,
1158 &object, moving_object);
1163 Sector::collision_static_constrains(MovingObject& object)
1165 using namespace collision;
1166 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1168 Constraints constraints;
1169 Vector movement = object.get_movement();
1170 Rectf& dest = object.dest;
1172 for(int i = 0; i < 2; ++i) {
1173 collision_static(&constraints, Vector(0, movement.y), dest, object);
1174 if(!constraints.has_constraints())
1177 // apply calculated horizontal constraints
1178 if(constraints.get_position_bottom() < infinity) {
1179 float height = constraints.get_height ();
1180 if(height < object.get_bbox().get_height()) {
1181 // we're crushed, but ignore this for now, we'll get this again
1182 // later if we're really crushed or things will solve itself when
1183 // looking at the vertical constraints
1185 dest.p2.y = constraints.get_position_bottom() - DELTA;
1186 dest.p1.y = dest.p2.y - object.get_bbox().get_height();
1187 } else if(constraints.get_position_top() > -infinity) {
1188 dest.p1.y = constraints.get_position_top() + DELTA;
1189 dest.p2.y = dest.p1.y + object.get_bbox().get_height();
1192 if(constraints.has_constraints()) {
1193 if(constraints.hit.bottom) {
1194 dest.move(constraints.ground_movement);
1196 if(constraints.hit.top || constraints.hit.bottom) {
1197 constraints.hit.left = false;
1198 constraints.hit.right = false;
1199 object.collision_solid(constraints.hit);
1203 constraints = Constraints();
1204 for(int i = 0; i < 2; ++i) {
1205 collision_static(&constraints, movement, dest, object);
1206 if(!constraints.has_constraints())
1209 // apply calculated vertical constraints
1210 float width = constraints.get_width ();
1211 if(width < infinity) {
1212 if(width + SHIFT_DELTA < object.get_bbox().get_width()) {
1214 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1215 constraints.get_position_left(), constraints.get_position_right());
1221 object.collision_solid(h);
1223 float xmid = constraints.get_x_midpoint ();
1224 dest.p1.x = xmid - object.get_bbox().get_width()/2;
1225 dest.p2.x = xmid + object.get_bbox().get_width()/2;
1227 } else if(constraints.get_position_right() < infinity) {
1228 dest.p2.x = constraints.get_position_right() - DELTA;
1229 dest.p1.x = dest.p2.x - object.get_bbox().get_width();
1230 } else if(constraints.get_position_left() > -infinity) {
1231 dest.p1.x = constraints.get_position_left() + DELTA;
1232 dest.p2.x = dest.p1.x + object.get_bbox().get_width();
1236 if(constraints.has_constraints()) {
1237 if( constraints.hit.left || constraints.hit.right
1238 || constraints.hit.top || constraints.hit.bottom
1239 || constraints.hit.crush )
1240 object.collision_solid(constraints.hit);
1243 // an extra pass to make sure we're not crushed horizontally
1244 constraints = Constraints();
1245 collision_static(&constraints, movement, dest, object);
1246 if(constraints.get_position_bottom() < infinity) {
1247 float height = constraints.get_height ();
1248 if(height + SHIFT_DELTA < object.get_bbox().get_height()) {
1250 printf("Object %p crushed vertically...\n", &object);
1256 object.collision_solid(h);
1262 const float MAX_SPEED = 16.0f;
1266 Sector::handle_collisions()
1268 using namespace collision;
1270 // calculate destination positions of the objects
1271 for(MovingObjects::iterator i = moving_objects.begin();
1272 i != moving_objects.end(); ++i) {
1273 MovingObject* moving_object = *i;
1274 Vector mov = moving_object->get_movement();
1276 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1277 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1278 moving_object->movement = mov.unit() * MAX_SPEED;
1279 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1282 moving_object->dest = moving_object->get_bbox();
1283 moving_object->dest.move(moving_object->get_movement());
1286 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1287 for(MovingObjects::iterator i = moving_objects.begin();
1288 i != moving_objects.end(); ++i) {
1289 MovingObject* moving_object = *i;
1290 if((moving_object->get_group() != COLGROUP_MOVING
1291 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1292 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1293 || !moving_object->is_valid())
1296 collision_static_constrains(*moving_object);
1299 // part2: COLGROUP_MOVING vs tile attributes
1300 for(MovingObjects::iterator i = moving_objects.begin();
1301 i != moving_objects.end(); ++i) {
1302 MovingObject* moving_object = *i;
1303 if((moving_object->get_group() != COLGROUP_MOVING
1304 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1305 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1306 || !moving_object->is_valid())
1309 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1310 if(tile_attributes >= Tile::FIRST_INTERESTING_FLAG) {
1311 moving_object->collision_tile(tile_attributes);
1315 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1316 for(MovingObjects::iterator i = moving_objects.begin();
1317 i != moving_objects.end(); ++i) {
1318 MovingObject* moving_object = *i;
1319 if((moving_object->get_group() != COLGROUP_MOVING
1320 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1321 || !moving_object->is_valid())
1324 for(MovingObjects::iterator i2 = moving_objects.begin();
1325 i2 != moving_objects.end(); ++i2) {
1326 MovingObject* moving_object_2 = *i2;
1327 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1328 || !moving_object_2->is_valid())
1331 if(intersects(moving_object->dest, moving_object_2->dest)) {
1334 get_hit_normal(moving_object->dest, moving_object_2->dest,
1336 if(!moving_object->collides(*moving_object_2, hit))
1338 if(!moving_object_2->collides(*moving_object, hit))
1341 moving_object->collision(*moving_object_2, hit);
1342 moving_object_2->collision(*moving_object, hit);
1347 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1348 for(MovingObjects::iterator i = moving_objects.begin();
1349 i != moving_objects.end(); ++i) {
1350 MovingObject* moving_object = *i;
1352 if((moving_object->get_group() != COLGROUP_MOVING
1353 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1354 || !moving_object->is_valid())
1357 for(MovingObjects::iterator i2 = i+1;
1358 i2 != moving_objects.end(); ++i2) {
1359 MovingObject* moving_object_2 = *i2;
1360 if((moving_object_2->get_group() != COLGROUP_MOVING
1361 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1362 || !moving_object_2->is_valid())
1365 collision_object(moving_object, moving_object_2);
1369 // apply object movement
1370 for(MovingObjects::iterator i = moving_objects.begin();
1371 i != moving_objects.end(); ++i) {
1372 MovingObject* moving_object = *i;
1374 moving_object->bbox = moving_object->dest;
1375 moving_object->movement = Vector(0, 0);
1380 Sector::is_free_of_tiles(const Rectf& rect, const bool ignoreUnisolid) const
1382 using namespace collision;
1384 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1385 TileMap* solids = *i;
1387 // test with all tiles in this rectangle
1388 Rect test_tiles = solids->get_tiles_overlapping(rect);
1390 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1391 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1392 const Tile* tile = solids->get_tile(x, y);
1394 if(!(tile->getAttributes() & Tile::SOLID))
1396 if(tile->is_unisolid () && ignoreUnisolid)
1398 if(tile->is_slope ()) {
1399 AATriangle triangle;
1400 Rectf tbbox = solids->get_tile_bbox(x, y);
1401 triangle = AATriangle(tbbox, tile->getData());
1402 Constraints constraints;
1403 if(!collision::rectangle_aatriangle(&constraints, rect, triangle))
1406 // We have a solid tile that overlaps the given rectangle.
1416 Sector::is_free_of_statics(const Rectf& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1418 using namespace collision;
1420 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1422 for(MovingObjects::const_iterator i = moving_objects.begin();
1423 i != moving_objects.end(); ++i) {
1424 const MovingObject* moving_object = *i;
1425 if (moving_object == ignore_object) continue;
1426 if (!moving_object->is_valid()) continue;
1427 if (moving_object->get_group() == COLGROUP_STATIC) {
1428 if(intersects(rect, moving_object->get_bbox())) return false;
1436 Sector::is_free_of_movingstatics(const Rectf& rect, const MovingObject* ignore_object) const
1438 using namespace collision;
1440 if (!is_free_of_tiles(rect)) return false;
1442 for(MovingObjects::const_iterator i = moving_objects.begin();
1443 i != moving_objects.end(); ++i) {
1444 const MovingObject* moving_object = *i;
1445 if (moving_object == ignore_object) continue;
1446 if (!moving_object->is_valid()) continue;
1447 if ((moving_object->get_group() == COLGROUP_MOVING)
1448 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1449 || (moving_object->get_group() == COLGROUP_STATIC)) {
1450 if(intersects(rect, moving_object->get_bbox())) return false;
1458 Sector::add_bullet(const Vector& pos, const PlayerStatus* player_status, float xm, Direction dir)
1460 // TODO remove this function and move these checks elsewhere...
1462 Bullet* new_bullet = 0;
1463 if((player_status->bonus == FIRE_BONUS &&
1464 (int)bullets.size() >= player_status->max_fire_bullets) ||
1465 (player_status->bonus == ICE_BONUS &&
1466 (int)bullets.size() >= player_status->max_ice_bullets))
1468 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1469 add_object(new_bullet);
1471 sound_manager->play("sounds/shoot.wav");
1477 Sector::add_smoke_cloud(const Vector& pos)
1479 add_object(new SmokeCloud(pos));
1484 Sector::play_music(MusicType type)
1486 currentmusic = type;
1487 switch(currentmusic) {
1489 sound_manager->play_music(music);
1492 sound_manager->play_music("music/invincible.ogg");
1494 case HERRING_WARNING_MUSIC:
1495 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1498 sound_manager->play_music("");
1504 Sector::get_music_type()
1506 return currentmusic;
1510 Sector::get_total_badguys()
1512 int total_badguys = 0;
1513 for(GameObjects::iterator i = gameobjects.begin();
1514 i != gameobjects.end(); ++i) {
1515 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1516 if (badguy && badguy->countMe)
1520 return total_badguys;
1524 Sector::inside(const Rectf& rect) const
1526 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1527 TileMap* solids = *i;
1529 Rectf bbox = solids->get_bbox();
1530 bbox.p1.y = -INFINITY; // pretend the tilemap extends infinitely far upwards
1532 if (bbox.contains(rect))
1539 Sector::get_width() const
1542 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1543 i != solid_tilemaps.end(); i++) {
1544 TileMap* solids = *i;
1545 width = std::max(width, solids->get_bbox().get_right());
1552 Sector::get_height() const
1555 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1556 i != solid_tilemaps.end(); i++) {
1557 TileMap* solids = *i;
1558 height = std::max(height, solids->get_bbox().get_bottom());
1565 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1567 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1568 TileMap* solids = *i;
1569 solids->change_all(old_tile_id, new_tile_id);
1574 Sector::set_ambient_light(float red, float green, float blue)
1576 ambient_light.red = red;
1577 ambient_light.green = green;
1578 ambient_light.blue = blue;
1582 Sector::get_ambient_red()
1584 return ambient_light.red;
1588 Sector::get_ambient_green()
1590 return ambient_light.green;
1594 Sector::get_ambient_blue()
1596 return ambient_light.blue;
1600 Sector::set_gravity(float gravity_)
1602 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1603 this->gravity = gravity_;
1607 Sector::get_gravity() const
1613 Sector::get_nearest_player (const Vector& pos)
1615 Player *nearest_player = NULL;
1616 float nearest_dist = std::numeric_limits<float>::max();
1618 std::vector<Player*> players = Sector::current()->get_players();
1619 for (std::vector<Player*>::iterator playerIter = players.begin();
1620 playerIter != players.end();
1623 Player *this_player = *playerIter;
1624 if (this_player->is_dying() || this_player->is_dead())
1627 float this_dist = this_player->get_bbox ().distance(pos);
1629 if (this_dist < nearest_dist) {
1630 nearest_player = this_player;
1631 nearest_dist = this_dist;
1635 return nearest_player;
1636 } /* Player *get_nearest_player */
1638 std::vector<MovingObject*>
1639 Sector::get_nearby_objects (const Vector& center, float max_distance)
1641 std::vector<MovingObject*> ret;
1642 std::vector<Player*> players = Sector::current()->get_players();
1644 for (size_t i = 0; i < players.size (); i++) {
1645 float distance = players[i]->get_bbox ().distance (center);
1646 if (distance <= max_distance)
1647 ret.push_back (players[i]);
1650 for (size_t i = 0; i < moving_objects.size (); i++) {
1651 float distance = moving_objects[i]->get_bbox ().distance (center);
1652 if (distance <= max_distance)
1653 ret.push_back (moving_objects[i]);
1659 /* vim: set sw=2 sts=2 et : */