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/scripting.hpp"
50 #include "scripting/squirrel_util.hpp"
51 #include "supertux/collision.hpp"
52 #include "supertux/constants.hpp"
53 #include "supertux/game_session.hpp"
54 #include "supertux/globals.hpp"
55 #include "supertux/level.hpp"
56 #include "supertux/object_factory.hpp"
57 #include "supertux/player_status.hpp"
58 #include "supertux/savegame.hpp"
59 #include "supertux/spawn_point.hpp"
60 #include "supertux/tile.hpp"
61 #include "trigger/sequence_trigger.hpp"
62 #include "util/file_system.hpp"
64 Sector* Sector::_current = 0;
66 bool Sector::show_collrects = false;
67 bool Sector::draw_solids_only = false;
69 Sector::Sector(Level* parent) :
75 currentmusic(LEVEL_MUSIC),
78 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ),
90 add_object(new Player(GameSession::current()->get_savegame().get_player_status(), "Tux"));
91 add_object(new DisplayEffect("Effect"));
92 add_object(new TextObject("Text"));
94 SoundManager::current()->preload("sounds/shoot.wav");
96 // create a new squirrel table for the sector
97 using namespace scripting;
99 sq_collectgarbage(global_vm);
101 sq_newtable(global_vm);
102 sq_pushroottable(global_vm);
103 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
104 throw scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
106 sq_resetobject(§or_table);
107 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
108 throw scripting::SquirrelError(global_vm, "Couldn't get sector table");
109 sq_addref(global_vm, §or_table);
110 sq_pop(global_vm, 1);
115 using namespace scripting;
119 for(ScriptList::iterator i = scripts.begin();
120 i != scripts.end(); ++i) {
121 HSQOBJECT& object = *i;
122 sq_release(global_vm, &object);
124 sq_release(global_vm, §or_table);
125 sq_collectgarbage(global_vm);
127 update_game_objects();
128 assert(gameobjects_new.size() == 0);
130 for(GameObjects::iterator i = gameobjects.begin();
131 i != gameobjects.end(); ++i) {
132 GameObject* object = *i;
133 before_object_remove(object);
137 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
149 Sector::parse_object(const std::string& name_, const Reader& reader)
151 if(name_ == "camera") {
152 Camera* camera_ = new Camera(this, "Camera");
153 camera_->parse(reader);
155 } else if(name_ == "particles-snow") {
156 SnowParticleSystem* partsys = new SnowParticleSystem();
157 partsys->parse(reader);
159 } else if(name_ == "particles-rain") {
160 RainParticleSystem* partsys = new RainParticleSystem();
161 partsys->parse(reader);
163 } else if(name_ == "particles-comets") {
164 CometParticleSystem* partsys = new CometParticleSystem();
165 partsys->parse(reader);
167 } else if(name_ == "particles-ghosts") {
168 GhostParticleSystem* partsys = new GhostParticleSystem();
169 partsys->parse(reader);
171 } else if(name_ == "particles-clouds") {
172 CloudParticleSystem* partsys = new CloudParticleSystem();
173 partsys->parse(reader);
175 } else if(name_ == "money") { // for compatibility with old maps
176 return new Jumpy(reader);
179 return ObjectFactory::instance().create(name_, reader);
180 } catch(std::exception& e) {
181 log_warning << e.what() << "" << std::endl;
188 Sector::parse(const Reader& sector)
190 bool has_background = false;
191 lisp::ListIterator iter(§or);
193 const std::string& token = iter.item();
194 if(token == "name") {
195 iter.value()->get(name);
196 } else if(token == "gravity") {
197 iter.value()->get(gravity);
198 } else if(token == "music") {
199 iter.value()->get(music);
200 } else if(token == "spawnpoint") {
201 SpawnPoint* sp = new SpawnPoint(*iter.lisp());
202 spawnpoints.push_back(sp);
203 } else if(token == "init-script") {
204 iter.value()->get(init_script);
205 } else if(token == "ambient-light") {
206 std::vector<float> vColor;
207 sector.get( "ambient-light", vColor );
208 if(vColor.size() < 3) {
209 log_warning << "(ambient-light) requires a color as argument" << std::endl;
211 ambient_light = Color( vColor );
214 GameObject* object = parse_object(token, *(iter.lisp()));
216 if(dynamic_cast<Background *>(object)) {
217 has_background = true;
218 } else if(dynamic_cast<Gradient *>(object)) {
219 has_background = true;
226 if(!has_background) {
227 Gradient* gradient = new Gradient();
228 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
229 add_object(gradient);
232 update_game_objects();
234 if(solid_tilemaps.size() < 1) { log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl; }
238 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
239 update_game_objects();
240 add_object(new Camera(this, "Camera"));
243 update_game_objects();
247 Sector::parse_old_format(const Reader& reader)
250 reader.get("gravity", gravity);
252 std::string backgroundimage;
253 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
254 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
255 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
256 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
257 backgroundimage = "images/background/" + backgroundimage;
258 if (!PHYSFS_exists(backgroundimage.c_str())) {
259 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
260 backgroundimage = "";
265 reader.get("bkgd_speed", bgspeed);
268 Color bkgd_top, bkgd_bottom;
269 int r = 0, g = 0, b = 128;
270 reader.get("bkgd_red_top", r);
271 reader.get("bkgd_green_top", g);
272 reader.get("bkgd_blue_top", b);
273 bkgd_top.red = static_cast<float> (r) / 255.0f;
274 bkgd_top.green = static_cast<float> (g) / 255.0f;
275 bkgd_top.blue = static_cast<float> (b) / 255.0f;
277 reader.get("bkgd_red_bottom", r);
278 reader.get("bkgd_green_bottom", g);
279 reader.get("bkgd_blue_bottom", b);
280 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
281 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
282 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
284 if(backgroundimage != "") {
285 Background* background = new Background();
286 background->set_image(backgroundimage, bgspeed);
287 add_object(background);
289 Gradient* gradient = new Gradient();
290 gradient->set_gradient(bkgd_top, bkgd_bottom);
291 add_object(gradient);
294 std::string particlesystem;
295 reader.get("particle_system", particlesystem);
296 if(particlesystem == "clouds")
297 add_object(new CloudParticleSystem());
298 else if(particlesystem == "snow")
299 add_object(new SnowParticleSystem());
300 else if(particlesystem == "rain")
301 add_object(new RainParticleSystem());
303 Vector startpos(100, 170);
304 reader.get("start_pos_x", startpos.x);
305 reader.get("start_pos_y", startpos.y);
307 SpawnPoint* spawn = new SpawnPoint;
308 spawn->pos = startpos;
309 spawn->name = "main";
310 spawnpoints.push_back(spawn);
312 music = "chipdisko.ogg";
313 // skip reading music filename. It's all .ogg now, anyway
315 reader.get("music", music);
317 music = "music/" + music;
319 int width = 30, height = 15;
320 reader.get("width", width);
321 reader.get("height", height);
323 std::vector<unsigned int> tiles;
324 if(reader.get("interactive-tm", tiles)
325 || reader.get("tilemap", tiles)) {
326 TileMap* tilemap = new TileMap(level->get_tileset());
327 tilemap->set(width, height, tiles, LAYER_TILES, true);
329 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
330 for(size_t x=0; x < tilemap->get_width(); ++x) {
331 for(size_t y=0; y < tilemap->get_height(); ++y) {
332 uint32_t id = tilemap->get_tile_id(x, y);
334 tilemap->change(x, y, 1311);
338 if (height < 19) tilemap->resize(width, 19);
342 if(reader.get("background-tm", tiles)) {
343 TileMap* tilemap = new TileMap(level->get_tileset());
344 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
345 if (height < 19) tilemap->resize(width, 19);
349 if(reader.get("foreground-tm", tiles)) {
350 TileMap* tilemap = new TileMap(level->get_tileset());
351 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
353 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
354 if (height < 19) tilemap->resize(width, 19, 2035);
359 // read reset-points (now spawn-points)
360 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
362 lisp::ListIterator iter(resetpoints);
364 if(iter.item() == "point") {
366 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
368 SpawnPoint* sp = new SpawnPoint;
371 spawnpoints.push_back(sp);
374 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
380 const lisp::Lisp* objects = reader.get_lisp("objects");
382 lisp::ListIterator iter(objects);
384 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
388 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
394 Camera* camera_ = new Camera(this, "Camera");
397 update_game_objects();
399 if(solid_tilemaps.size() < 1) { log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl; }
402 update_game_objects();
406 Sector::fix_old_tiles()
408 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
409 TileMap* solids = *i;
410 for(size_t x=0; x < solids->get_width(); ++x) {
411 for(size_t y=0; y < solids->get_height(); ++y) {
412 uint32_t id = solids->get_tile_id(x, y);
413 const Tile *tile = solids->get_tile(x, y);
414 Vector pos = solids->get_tile_position(x, y);
417 add_object(new InvisibleBlock(pos));
418 solids->change(x, y, 0);
419 } else if(tile->getAttributes() & Tile::COIN) {
420 add_object(new Coin(pos, solids));
421 solids->change(x, y, 0);
422 } else if(tile->getAttributes() & Tile::FULLBOX) {
423 add_object(new BonusBlock(pos, tile->getData()));
424 solids->change(x, y, 0);
425 } else if(tile->getAttributes() & Tile::BRICK) {
426 if( ( id == 78 ) || ( id == 105 ) ){
427 add_object( new Brick(pos, tile->getData(), "images/objects/bonus_block/brickIce.sprite") );
428 } else if( ( id == 77 ) || ( id == 104 ) ){
429 add_object( new Brick(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
431 log_warning << "attribute 'brick #t' is not supported for tile-id " << id << std::endl;
432 add_object( new Brick(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
434 solids->change(x, y, 0);
435 } else if(tile->getAttributes() & Tile::GOAL) {
436 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
437 add_object(new SequenceTrigger(pos, sequence));
438 solids->change(x, y, 0);
444 // add lights for special tiles
445 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
446 TileMap* tm = dynamic_cast<TileMap*>(*i);
448 for(size_t x=0; x < tm->get_width(); ++x) {
449 for(size_t y=0; y < tm->get_height(); ++y) {
450 uint32_t id = tm->get_tile_id(x, y);
451 Vector pos = tm->get_tile_position(x, y);
452 Vector center = pos + Vector(16, 16);
456 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
457 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
460 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
461 // space lights a bit
462 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
463 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
464 || ((x % 3 == 0) && (y % 3 == 0))) {
465 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
466 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
477 Sector::run_script(std::istream& in, const std::string& sourcename)
479 using namespace scripting;
481 // garbage collect thread list
482 for(ScriptList::iterator i = scripts.begin();
483 i != scripts.end(); ) {
484 HSQOBJECT& object = *i;
485 HSQUIRRELVM vm = object_to_vm(object);
487 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
488 sq_release(global_vm, &object);
489 i = scripts.erase(i);
496 HSQOBJECT object = create_thread(global_vm);
497 scripts.push_back(object);
499 HSQUIRRELVM vm = object_to_vm(object);
501 // set sector_table as roottable for the thread
502 sq_pushobject(vm, sector_table);
506 compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
507 } catch(std::exception& e) {
508 log_warning << "Error running script: " << e.what() << std::endl;
515 Sector::add_object(GameObject* object)
517 // make sure the object isn't already in the list
519 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
521 assert(*i != object);
523 for(GameObjects::iterator i = gameobjects_new.begin();
524 i != gameobjects_new.end(); ++i) {
525 assert(*i != object);
530 gameobjects_new.push_back(object);
534 Sector::activate(const std::string& spawnpoint)
537 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
539 if((*i)->name == spawnpoint) {
545 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
546 if(spawnpoint != "main") {
549 activate(Vector(0, 0));
557 Sector::activate(const Vector& player_pos)
559 if(_current != this) {
561 _current->deactivate();
564 // register sectortable as sector in scripting
565 HSQUIRRELVM vm = scripting::global_vm;
566 sq_pushroottable(vm);
567 sq_pushstring(vm, "sector", -1);
568 sq_pushobject(vm, sector_table);
569 if(SQ_FAILED(sq_createslot(vm, -3)))
570 throw scripting::SquirrelError(vm, "Couldn't set sector in roottable");
573 for(GameObjects::iterator i = gameobjects.begin();
574 i != gameobjects.end(); ++i) {
575 GameObject* object = *i;
583 // two-player hack: move other players to main player's position
584 // Maybe specify 2 spawnpoints in the level?
585 for(GameObjects::iterator i = gameobjects.begin();
586 i != gameobjects.end(); ++i) {
587 Player* p = dynamic_cast<Player*>(*i);
590 // spawn smalltux below spawnpoint
592 p->move(player_pos + Vector(0,32));
597 // spawning tux in the ground would kill him
598 if(!is_free_of_tiles(p->get_bbox())) {
599 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
600 Vector npos = p->get_bbox().p1;
606 //FIXME: This is a really dirty workaround for this strange camera jump
607 player->move(player->get_pos()+Vector(-32, 0));
608 camera->reset(player->get_pos());
610 player->move(player->get_pos()+(Vector(32, 0)));
613 update_game_objects();
615 //Run default.nut just before init script
616 //Check to see if it's in a levelset (info file)
617 std::string basedir = FileSystem::dirname(get_level()->filename);
618 if(PHYSFS_exists((basedir + "/info").c_str())) {
620 IFileStreambuf ins(basedir + "/default.nut");
621 std::istream in(&ins);
622 run_script(in, "default.nut");
623 } catch(std::exception& ) {
624 // doesn't exist or erroneous; do nothing
629 if(init_script != "") {
630 std::istringstream in(init_script);
631 run_script(in, "init-script");
641 // remove sector entry from global vm
642 HSQUIRRELVM vm = scripting::global_vm;
643 sq_pushroottable(vm);
644 sq_pushstring(vm, "sector", -1);
645 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
646 throw scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
649 for(GameObjects::iterator i = gameobjects.begin();
650 i != gameobjects.end(); ++i) {
651 GameObject* object = *i;
653 try_unexpose(object);
661 Sector::get_active_region()
664 camera->get_translation() - Vector(1600, 1200),
665 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
669 Sector::update(float elapsed_time)
671 player->check_bounds();
674 for(GameObjects::iterator i = gameobjects.begin();
675 i != gameobjects.end(); ++i) {
676 GameObject* object = *i;
677 if(!object->is_valid())
680 object->update(elapsed_time);
683 /* Handle all possible collisions. */
685 update_game_objects();
689 Sector::update_game_objects()
691 /** cleanup marked objects */
692 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
693 i != gameobjects.end(); /* nothing */) {
694 GameObject* object = *i;
696 if(object->is_valid()) {
701 before_object_remove(object);
704 i = gameobjects.erase(i);
707 /* add newly created objects */
708 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
709 i != gameobjects_new.end(); ++i)
711 GameObject* object = *i;
713 before_object_add(object);
715 gameobjects.push_back(object);
717 gameobjects_new.clear();
719 /* update solid_tilemaps list */
720 //FIXME: this could be more efficient
721 solid_tilemaps.clear();
722 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
723 i != gameobjects.end(); ++i)
725 TileMap* tm = dynamic_cast<TileMap*>(*i);
727 if (tm->is_solid()) solid_tilemaps.push_back(tm);
733 Sector::before_object_add(GameObject* object)
735 Bullet* bullet = dynamic_cast<Bullet*> (object);
737 bullets.push_back(bullet);
740 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
741 if(movingobject != NULL) {
742 moving_objects.push_back(movingobject);
745 Portable* portable = dynamic_cast<Portable*> (object);
746 if(portable != NULL) {
747 portables.push_back(portable);
750 TileMap* tilemap = dynamic_cast<TileMap*> (object);
751 if(tilemap != NULL && tilemap->is_solid()) {
752 solid_tilemaps.push_back(tilemap);
755 Camera* camera_ = dynamic_cast<Camera*> (object);
756 if(camera_ != NULL) {
757 if(this->camera != 0) {
758 log_warning << "Multiple cameras added. Ignoring" << std::endl;
761 this->camera = camera_;
764 Player* player_ = dynamic_cast<Player*> (object);
765 if(player_ != NULL) {
766 if(this->player != 0) {
767 log_warning << "Multiple players added. Ignoring" << std::endl;
770 this->player = player_;
773 DisplayEffect* effect_ = dynamic_cast<DisplayEffect*> (object);
774 if(effect_ != NULL) {
775 if(this->effect != 0) {
776 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
779 this->effect = effect_;
782 if(_current == this) {
790 Sector::try_expose(GameObject* object)
792 ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
793 if(object_ != NULL) {
794 HSQUIRRELVM vm = scripting::global_vm;
795 sq_pushobject(vm, sector_table);
796 object_->expose(vm, -1);
802 Sector::try_expose_me()
804 HSQUIRRELVM vm = scripting::global_vm;
805 sq_pushobject(vm, sector_table);
806 scripting::SSector* this_ = static_cast<scripting::SSector*> (this);
807 expose_object(vm, -1, this_, "settings", false);
812 Sector::before_object_remove(GameObject* object)
814 Portable* portable = dynamic_cast<Portable*> (object);
815 if(portable != NULL) {
816 portables.erase(std::find(portables.begin(), portables.end(), portable));
818 Bullet* bullet = dynamic_cast<Bullet*> (object);
820 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
822 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
823 if(moving_object != NULL) {
824 moving_objects.erase(
825 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
829 try_unexpose(object);
833 Sector::try_unexpose(GameObject* object)
835 ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
836 if(object_ != NULL) {
837 HSQUIRRELVM vm = scripting::global_vm;
838 SQInteger oldtop = sq_gettop(vm);
839 sq_pushobject(vm, sector_table);
841 object_->unexpose(vm, -1);
842 } catch(std::exception& e) {
843 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
845 sq_settop(vm, oldtop);
850 Sector::try_unexpose_me()
852 HSQUIRRELVM vm = scripting::global_vm;
853 SQInteger oldtop = sq_gettop(vm);
854 sq_pushobject(vm, sector_table);
856 scripting::unexpose_object(vm, -1, "settings");
857 } catch(std::exception& e) {
858 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
860 sq_settop(vm, oldtop);
863 Sector::draw(DrawingContext& context)
865 context.set_ambient_color( ambient_light );
866 context.push_transform();
867 context.set_translation(camera->get_translation());
869 for(GameObjects::iterator i = gameobjects.begin();
870 i != gameobjects.end(); ++i) {
871 GameObject* object = *i;
872 if(!object->is_valid())
875 if (draw_solids_only)
877 TileMap* tm = dynamic_cast<TileMap*>(object);
878 if (tm && !tm->is_solid())
882 object->draw(context);
886 Color color(1.0f, 0.0f, 0.0f, 0.75f);
887 for(MovingObjects::iterator i = moving_objects.begin();
888 i != moving_objects.end(); ++i) {
889 MovingObject* object = *i;
890 const Rectf& rect = object->get_bbox();
892 context.draw_filled_rect(rect, color, LAYER_FOREGROUND1 + 10);
896 context.pop_transform();
899 /*-------------------------------------------------------------------------
900 * Collision Detection
901 *-------------------------------------------------------------------------*/
903 /** r1 is supposed to be moving, r2 a solid object */
904 void check_collisions(collision::Constraints* constraints,
905 const Vector& obj_movement, const Rectf& obj_rect, const Rectf& other_rect,
906 GameObject* object = NULL, MovingObject* other = NULL, const Vector& other_movement = Vector(0,0))
908 if(!collision::intersects(obj_rect, other_rect))
911 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
913 if(other != NULL && !other->collides(*object, dummy))
915 if(moving_object != NULL && !moving_object->collides(*other, dummy))
918 // calculate intersection
919 float itop = obj_rect.get_bottom() - other_rect.get_top();
920 float ibottom = other_rect.get_bottom() - obj_rect.get_top();
921 float ileft = obj_rect.get_right() - other_rect.get_left();
922 float iright = other_rect.get_right() - obj_rect.get_left();
924 if(fabsf(obj_movement.y) > fabsf(obj_movement.x)) {
925 if(ileft < SHIFT_DELTA) {
926 constraints->constrain_right(other_rect.get_left(), other_movement.x);
928 } else if(iright < SHIFT_DELTA) {
929 constraints->constrain_left(other_rect.get_right(), other_movement.x);
933 // shiftout bottom/top
934 if(itop < SHIFT_DELTA) {
935 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
937 } else if(ibottom < SHIFT_DELTA) {
938 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
943 constraints->ground_movement += other_movement;
945 HitResponse response = other->collision(*object, dummy);
946 if(response == ABORT_MOVE)
949 if(other->get_movement() != Vector(0, 0)) {
950 // TODO what todo when we collide with 2 moving objects?!?
951 constraints->ground_movement = other->get_movement();
955 float vert_penetration = std::min(itop, ibottom);
956 float horiz_penetration = std::min(ileft, iright);
957 if(vert_penetration < horiz_penetration) {
959 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
960 constraints->hit.bottom = true;
962 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
963 constraints->hit.top = true;
967 constraints->constrain_right(other_rect.get_left(), other_movement.x);
968 constraints->hit.right = true;
970 constraints->constrain_left(other_rect.get_right(), other_movement.x);
971 constraints->hit.left = true;
977 Sector::collision_tilemap(collision::Constraints* constraints,
978 const Vector& movement, const Rectf& dest,
979 MovingObject& object) const
981 // calculate rectangle where the object will move
982 float x1 = dest.get_left();
983 float x2 = dest.get_right();
984 float y1 = dest.get_top();
985 float y2 = dest.get_bottom();
987 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
988 TileMap* solids = *i;
990 // test with all tiles in this rectangle
991 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
993 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
994 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
995 const Tile* tile = solids->get_tile(x, y);
998 // skip non-solid tiles
999 if(!tile->is_solid ())
1001 Rectf tile_bbox = solids->get_tile_bbox(x, y);
1003 /* If the tile is a unisolid tile, the "is_solid()" function above
1004 * didn't do a thorough check. Calculate the position and (relative)
1005 * movement of the object and determine whether or not the tile is
1006 * solid with regard to those parameters. */
1007 if(tile->is_unisolid ()) {
1008 Vector relative_movement = movement
1009 - solids->get_movement(/* actual = */ true);
1011 if (!tile->is_solid (tile_bbox, object.get_bbox(), relative_movement))
1013 } /* if (tile->is_unisolid ()) */
1015 if(tile->is_slope ()) { // slope tile
1016 AATriangle triangle;
1017 int slope_data = tile->getData();
1018 if (solids->get_drawing_effect() & VERTICAL_FLIP)
1019 slope_data = AATriangle::vertical_flip(slope_data);
1020 triangle = AATriangle(tile_bbox, slope_data);
1022 collision::rectangle_aatriangle(constraints, dest, triangle,
1023 solids->get_movement(/* actual = */ false));
1024 } else { // normal rectangular tile
1025 check_collisions(constraints, movement, dest, tile_bbox, NULL, NULL,
1026 solids->get_movement(/* actual = */ false));
1034 Sector::collision_tile_attributes(const Rectf& dest) const
1036 float x1 = dest.p1.x;
1037 float y1 = dest.p1.y;
1038 float x2 = dest.p2.x;
1039 float y2 = dest.p2.y;
1041 uint32_t result = 0;
1042 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1043 TileMap* solids = *i;
1045 // test with all tiles in this rectangle
1046 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1047 // For ice (only), add a little fudge to recognize tiles Tux is standing on.
1048 Rect test_tiles_ice = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2 + SHIFT_DELTA));
1050 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1052 for(y = test_tiles.top; y < test_tiles.bottom; ++y) {
1053 const Tile* tile = solids->get_tile(x, y);
1056 result |= tile->getAttributes();
1058 for(; y < test_tiles_ice.bottom; ++y) {
1059 const Tile* tile = solids->get_tile(x, y);
1062 result |= (tile->getAttributes() & Tile::ICE);
1070 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1071 static void get_hit_normal(const Rectf& r1, const Rectf& r2, CollisionHit& hit,
1074 float itop = r1.get_bottom() - r2.get_top();
1075 float ibottom = r2.get_bottom() - r1.get_top();
1076 float ileft = r1.get_right() - r2.get_left();
1077 float iright = r2.get_right() - r1.get_left();
1079 float vert_penetration = std::min(itop, ibottom);
1080 float horiz_penetration = std::min(ileft, iright);
1081 if(vert_penetration < horiz_penetration) {
1082 if(itop < ibottom) {
1084 normal.y = vert_penetration;
1087 normal.y = -vert_penetration;
1090 if(ileft < iright) {
1092 normal.x = horiz_penetration;
1095 normal.x = -horiz_penetration;
1101 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1103 using namespace collision;
1105 const Rectf& r1 = object1->dest;
1106 const Rectf& r2 = object2->dest;
1109 if(intersects(object1->dest, object2->dest)) {
1111 get_hit_normal(r1, r2, hit, normal);
1113 if(!object1->collides(*object2, hit))
1115 std::swap(hit.left, hit.right);
1116 std::swap(hit.top, hit.bottom);
1117 if(!object2->collides(*object1, hit))
1119 std::swap(hit.left, hit.right);
1120 std::swap(hit.top, hit.bottom);
1122 HitResponse response1 = object1->collision(*object2, hit);
1123 std::swap(hit.left, hit.right);
1124 std::swap(hit.top, hit.bottom);
1125 HitResponse response2 = object2->collision(*object1, hit);
1126 if(response1 == CONTINUE && response2 == CONTINUE) {
1127 normal *= (0.5 + DELTA);
1128 object1->dest.move(-normal);
1129 object2->dest.move(normal);
1130 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1131 normal *= (1 + DELTA);
1132 object1->dest.move(-normal);
1133 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1134 normal *= (1 + DELTA);
1135 object2->dest.move(normal);
1141 Sector::collision_static(collision::Constraints* constraints,
1142 const Vector& movement, const Rectf& dest,
1143 MovingObject& object)
1145 collision_tilemap(constraints, movement, dest, object);
1147 // collision with other (static) objects
1148 for(MovingObjects::iterator i = moving_objects.begin();
1149 i != moving_objects.end(); ++i) {
1150 MovingObject* moving_object = *i;
1151 if(moving_object->get_group() != COLGROUP_STATIC
1152 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1154 if(!moving_object->is_valid())
1157 if(moving_object != &object)
1158 check_collisions(constraints, movement, dest, moving_object->bbox,
1159 &object, moving_object);
1164 Sector::collision_static_constrains(MovingObject& object)
1166 using namespace collision;
1167 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1169 Constraints constraints;
1170 Vector movement = object.get_movement();
1171 Rectf& dest = object.dest;
1173 for(int i = 0; i < 2; ++i) {
1174 collision_static(&constraints, Vector(0, movement.y), dest, object);
1175 if(!constraints.has_constraints())
1178 // apply calculated horizontal constraints
1179 if(constraints.get_position_bottom() < infinity) {
1180 float height = constraints.get_height ();
1181 if(height < object.get_bbox().get_height()) {
1182 // we're crushed, but ignore this for now, we'll get this again
1183 // later if we're really crushed or things will solve itself when
1184 // looking at the vertical constraints
1186 dest.p2.y = constraints.get_position_bottom() - DELTA;
1187 dest.p1.y = dest.p2.y - object.get_bbox().get_height();
1188 } else if(constraints.get_position_top() > -infinity) {
1189 dest.p1.y = constraints.get_position_top() + DELTA;
1190 dest.p2.y = dest.p1.y + object.get_bbox().get_height();
1193 if(constraints.has_constraints()) {
1194 if(constraints.hit.bottom) {
1195 dest.move(constraints.ground_movement);
1197 if(constraints.hit.top || constraints.hit.bottom) {
1198 constraints.hit.left = false;
1199 constraints.hit.right = false;
1200 object.collision_solid(constraints.hit);
1204 constraints = Constraints();
1205 for(int i = 0; i < 2; ++i) {
1206 collision_static(&constraints, movement, dest, object);
1207 if(!constraints.has_constraints())
1210 // apply calculated vertical constraints
1211 float width = constraints.get_width ();
1212 if(width < infinity) {
1213 if(width + SHIFT_DELTA < object.get_bbox().get_width()) {
1215 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1216 constraints.get_position_left(), constraints.get_position_right());
1222 object.collision_solid(h);
1224 float xmid = constraints.get_x_midpoint ();
1225 dest.p1.x = xmid - object.get_bbox().get_width()/2;
1226 dest.p2.x = xmid + object.get_bbox().get_width()/2;
1228 } else if(constraints.get_position_right() < infinity) {
1229 dest.p2.x = constraints.get_position_right() - DELTA;
1230 dest.p1.x = dest.p2.x - object.get_bbox().get_width();
1231 } else if(constraints.get_position_left() > -infinity) {
1232 dest.p1.x = constraints.get_position_left() + DELTA;
1233 dest.p2.x = dest.p1.x + object.get_bbox().get_width();
1237 if(constraints.has_constraints()) {
1238 if( constraints.hit.left || constraints.hit.right
1239 || constraints.hit.top || constraints.hit.bottom
1240 || constraints.hit.crush )
1241 object.collision_solid(constraints.hit);
1244 // an extra pass to make sure we're not crushed horizontally
1245 constraints = Constraints();
1246 collision_static(&constraints, movement, dest, object);
1247 if(constraints.get_position_bottom() < infinity) {
1248 float height = constraints.get_height ();
1249 if(height + SHIFT_DELTA < object.get_bbox().get_height()) {
1251 printf("Object %p crushed vertically...\n", &object);
1257 object.collision_solid(h);
1263 const float MAX_SPEED = 16.0f;
1267 Sector::handle_collisions()
1269 using namespace collision;
1271 // calculate destination positions of the objects
1272 for(MovingObjects::iterator i = moving_objects.begin();
1273 i != moving_objects.end(); ++i) {
1274 MovingObject* moving_object = *i;
1275 Vector mov = moving_object->get_movement();
1277 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1278 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1279 moving_object->movement = mov.unit() * MAX_SPEED;
1280 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1283 moving_object->dest = moving_object->get_bbox();
1284 moving_object->dest.move(moving_object->get_movement());
1287 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1288 for(MovingObjects::iterator i = moving_objects.begin();
1289 i != moving_objects.end(); ++i) {
1290 MovingObject* moving_object = *i;
1291 if((moving_object->get_group() != COLGROUP_MOVING
1292 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1293 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1294 || !moving_object->is_valid())
1297 collision_static_constrains(*moving_object);
1300 // part2: COLGROUP_MOVING vs tile attributes
1301 for(MovingObjects::iterator i = moving_objects.begin();
1302 i != moving_objects.end(); ++i) {
1303 MovingObject* moving_object = *i;
1304 if((moving_object->get_group() != COLGROUP_MOVING
1305 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1306 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1307 || !moving_object->is_valid())
1310 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1311 if(tile_attributes >= Tile::FIRST_INTERESTING_FLAG) {
1312 moving_object->collision_tile(tile_attributes);
1316 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1317 for(MovingObjects::iterator i = moving_objects.begin();
1318 i != moving_objects.end(); ++i) {
1319 MovingObject* moving_object = *i;
1320 if((moving_object->get_group() != COLGROUP_MOVING
1321 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1322 || !moving_object->is_valid())
1325 for(MovingObjects::iterator i2 = moving_objects.begin();
1326 i2 != moving_objects.end(); ++i2) {
1327 MovingObject* moving_object_2 = *i2;
1328 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1329 || !moving_object_2->is_valid())
1332 if(intersects(moving_object->dest, moving_object_2->dest)) {
1335 get_hit_normal(moving_object->dest, moving_object_2->dest,
1337 if(!moving_object->collides(*moving_object_2, hit))
1339 if(!moving_object_2->collides(*moving_object, hit))
1342 moving_object->collision(*moving_object_2, hit);
1343 moving_object_2->collision(*moving_object, hit);
1348 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1349 for(MovingObjects::iterator i = moving_objects.begin();
1350 i != moving_objects.end(); ++i) {
1351 MovingObject* moving_object = *i;
1353 if((moving_object->get_group() != COLGROUP_MOVING
1354 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1355 || !moving_object->is_valid())
1358 for(MovingObjects::iterator i2 = i+1;
1359 i2 != moving_objects.end(); ++i2) {
1360 MovingObject* moving_object_2 = *i2;
1361 if((moving_object_2->get_group() != COLGROUP_MOVING
1362 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1363 || !moving_object_2->is_valid())
1366 collision_object(moving_object, moving_object_2);
1370 // apply object movement
1371 for(MovingObjects::iterator i = moving_objects.begin();
1372 i != moving_objects.end(); ++i) {
1373 MovingObject* moving_object = *i;
1375 moving_object->bbox = moving_object->dest;
1376 moving_object->movement = Vector(0, 0);
1381 Sector::is_free_of_tiles(const Rectf& rect, const bool ignoreUnisolid) const
1383 using namespace collision;
1385 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1386 TileMap* solids = *i;
1388 // test with all tiles in this rectangle
1389 Rect test_tiles = solids->get_tiles_overlapping(rect);
1391 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1392 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1393 const Tile* tile = solids->get_tile(x, y);
1395 if(!(tile->getAttributes() & Tile::SOLID))
1397 if(tile->is_unisolid () && ignoreUnisolid)
1399 if(tile->is_slope ()) {
1400 AATriangle triangle;
1401 Rectf tbbox = solids->get_tile_bbox(x, y);
1402 triangle = AATriangle(tbbox, tile->getData());
1403 Constraints constraints;
1404 if(!collision::rectangle_aatriangle(&constraints, rect, triangle))
1407 // We have a solid tile that overlaps the given rectangle.
1417 Sector::is_free_of_statics(const Rectf& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1419 using namespace collision;
1421 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1423 for(MovingObjects::const_iterator i = moving_objects.begin();
1424 i != moving_objects.end(); ++i) {
1425 const MovingObject* moving_object = *i;
1426 if (moving_object == ignore_object) continue;
1427 if (!moving_object->is_valid()) continue;
1428 if (moving_object->get_group() == COLGROUP_STATIC) {
1429 if(intersects(rect, moving_object->get_bbox())) return false;
1437 Sector::is_free_of_movingstatics(const Rectf& rect, const MovingObject* ignore_object) const
1439 using namespace collision;
1441 if (!is_free_of_tiles(rect)) return false;
1443 for(MovingObjects::const_iterator i = moving_objects.begin();
1444 i != moving_objects.end(); ++i) {
1445 const MovingObject* moving_object = *i;
1446 if (moving_object == ignore_object) continue;
1447 if (!moving_object->is_valid()) continue;
1448 if ((moving_object->get_group() == COLGROUP_MOVING)
1449 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1450 || (moving_object->get_group() == COLGROUP_STATIC)) {
1451 if(intersects(rect, moving_object->get_bbox())) return false;
1459 Sector::add_bullet(const Vector& pos, const PlayerStatus* player_status, float xm, Direction dir)
1461 // TODO remove this function and move these checks elsewhere...
1463 Bullet* new_bullet = 0;
1464 if((player_status->bonus == FIRE_BONUS &&
1465 (int)bullets.size() >= player_status->max_fire_bullets) ||
1466 (player_status->bonus == ICE_BONUS &&
1467 (int)bullets.size() >= player_status->max_ice_bullets))
1469 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1470 add_object(new_bullet);
1472 SoundManager::current()->play("sounds/shoot.wav");
1478 Sector::add_smoke_cloud(const Vector& pos)
1480 add_object(new SmokeCloud(pos));
1485 Sector::play_music(MusicType type)
1487 currentmusic = type;
1488 switch(currentmusic) {
1490 SoundManager::current()->play_music(music);
1493 SoundManager::current()->play_music("music/invincible.ogg");
1495 case HERRING_WARNING_MUSIC:
1496 SoundManager::current()->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1499 SoundManager::current()->play_music("");
1505 Sector::get_music_type()
1507 return currentmusic;
1511 Sector::get_total_badguys()
1513 int total_badguys = 0;
1514 for(GameObjects::iterator i = gameobjects.begin();
1515 i != gameobjects.end(); ++i) {
1516 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1517 if (badguy && badguy->countMe)
1521 return total_badguys;
1525 Sector::inside(const Rectf& rect) const
1527 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1528 TileMap* solids = *i;
1530 Rectf bbox = solids->get_bbox();
1531 bbox.p1.y = -INFINITY; // pretend the tilemap extends infinitely far upwards
1533 if (bbox.contains(rect))
1540 Sector::get_width() const
1543 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1544 i != solid_tilemaps.end(); i++) {
1545 TileMap* solids = *i;
1546 width = std::max(width, solids->get_bbox().get_right());
1553 Sector::get_height() const
1556 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1557 i != solid_tilemaps.end(); i++) {
1558 TileMap* solids = *i;
1559 height = std::max(height, solids->get_bbox().get_bottom());
1566 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1568 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1569 TileMap* solids = *i;
1570 solids->change_all(old_tile_id, new_tile_id);
1575 Sector::set_ambient_light(float red, float green, float blue)
1577 ambient_light.red = red;
1578 ambient_light.green = green;
1579 ambient_light.blue = blue;
1583 Sector::get_ambient_red()
1585 return ambient_light.red;
1589 Sector::get_ambient_green()
1591 return ambient_light.green;
1595 Sector::get_ambient_blue()
1597 return ambient_light.blue;
1601 Sector::set_gravity(float gravity_)
1603 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1604 this->gravity = gravity_;
1608 Sector::get_gravity() const
1614 Sector::get_nearest_player (const Vector& pos)
1616 Player *nearest_player = NULL;
1617 float nearest_dist = std::numeric_limits<float>::max();
1619 std::vector<Player*> players = Sector::current()->get_players();
1620 for (std::vector<Player*>::iterator playerIter = players.begin();
1621 playerIter != players.end();
1624 Player *this_player = *playerIter;
1625 if (this_player->is_dying() || this_player->is_dead())
1628 float this_dist = this_player->get_bbox ().distance(pos);
1630 if (this_dist < nearest_dist) {
1631 nearest_player = this_player;
1632 nearest_dist = this_dist;
1636 return nearest_player;
1637 } /* Player *get_nearest_player */
1639 std::vector<MovingObject*>
1640 Sector::get_nearby_objects (const Vector& center, float max_distance)
1642 std::vector<MovingObject*> ret;
1643 std::vector<Player*> players = Sector::current()->get_players();
1645 for (size_t i = 0; i < players.size (); i++) {
1646 float distance = players[i]->get_bbox ().distance (center);
1647 if (distance <= max_distance)
1648 ret.push_back (players[i]);
1651 for (size_t i = 0; i < moving_objects.size (); i++) {
1652 float distance = moving_objects[i]->get_bbox ().distance (center);
1653 if (distance <= max_distance)
1654 ret.push_back (moving_objects[i]);
1660 /* vim: set sw=2 sts=2 et : */