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/secretarea_trigger.hpp"
62 #include "trigger/sequence_trigger.hpp"
63 #include "util/file_system.hpp"
65 Sector* Sector::_current = 0;
67 bool Sector::show_collrects = false;
68 bool Sector::draw_solids_only = false;
70 Sector::Sector(Level* parent) :
76 currentmusic(LEVEL_MUSIC),
79 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ),
92 add_object(std::make_shared<Player>(GameSession::current()->get_savegame().get_player_status(), "Tux"));
93 add_object(std::make_shared<DisplayEffect>("Effect"));
94 add_object(std::make_shared<TextObject>("Text"));
96 SoundManager::current()->preload("sounds/shoot.wav");
98 // create a new squirrel table for the sector
99 using namespace scripting;
101 sq_collectgarbage(global_vm);
103 sq_newtable(global_vm);
104 sq_pushroottable(global_vm);
105 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
106 throw scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
108 sq_resetobject(§or_table);
109 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
110 throw scripting::SquirrelError(global_vm, "Couldn't get sector table");
111 sq_addref(global_vm, §or_table);
112 sq_pop(global_vm, 1);
117 using namespace scripting;
121 for(auto i = scripts.begin(); i != scripts.end(); ++i) {
122 HSQOBJECT& object = *i;
123 sq_release(global_vm, &object);
125 sq_release(global_vm, §or_table);
126 sq_collectgarbage(global_vm);
128 update_game_objects();
129 assert(gameobjects_new.size() == 0);
131 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
132 GameObjectPtr object = *i;
133 before_object_remove(object);
144 Sector::parse_object(const std::string& name_, const Reader& reader)
146 if(name_ == "camera") {
147 auto camera_ = std::make_shared<Camera>(this, "Camera");
148 camera_->parse(reader);
150 } else if(name_ == "particles-snow") {
151 auto partsys = std::make_shared<SnowParticleSystem>();
152 partsys->parse(reader);
154 } else if(name_ == "particles-rain") {
155 auto partsys = std::make_shared<RainParticleSystem>();
156 partsys->parse(reader);
158 } else if(name_ == "particles-comets") {
159 auto partsys = std::make_shared<CometParticleSystem>();
160 partsys->parse(reader);
162 } else if(name_ == "particles-ghosts") {
163 auto partsys = std::make_shared<GhostParticleSystem>();
164 partsys->parse(reader);
166 } else if(name_ == "particles-clouds") {
167 auto partsys = std::make_shared<CloudParticleSystem>();
168 partsys->parse(reader);
170 } else if(name_ == "money") { // for compatibility with old maps
171 return std::make_shared<Jumpy>(reader);
174 return ObjectFactory::instance().create(name_, reader);
175 } catch(std::exception& e) {
176 log_warning << e.what() << "" << std::endl;
183 Sector::parse(const Reader& sector)
185 bool has_background = false;
186 lisp::ListIterator iter(§or);
188 const std::string& token = iter.item();
189 if(token == "name") {
190 iter.value()->get(name);
191 } else if(token == "gravity") {
192 iter.value()->get(gravity);
193 } else if(token == "music") {
194 iter.value()->get(music);
195 } else if(token == "spawnpoint") {
196 auto sp = std::make_shared<SpawnPoint>(*iter.lisp());
197 spawnpoints.push_back(sp);
198 } else if(token == "init-script") {
199 iter.value()->get(init_script);
200 } else if(token == "ambient-light") {
201 std::vector<float> vColor;
202 sector.get( "ambient-light", vColor );
203 if(vColor.size() < 3) {
204 log_warning << "(ambient-light) requires a color as argument" << std::endl;
206 ambient_light = Color( vColor );
209 GameObjectPtr object = parse_object(token, *(iter.lisp()));
211 if(std::dynamic_pointer_cast<Background>(object)) {
212 has_background = true;
213 } else if(std::dynamic_pointer_cast<Gradient>(object)) {
214 has_background = true;
221 if(!has_background) {
222 auto gradient = std::make_shared<Gradient>();
223 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
224 add_object(gradient);
227 update_game_objects();
229 if(solid_tilemaps.empty()) { log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl; }
233 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
234 update_game_objects();
235 add_object(std::make_shared<Camera>(this, "Camera"));
238 update_game_objects();
239 foremost_layer = calculate_foremost_layer();
243 Sector::parse_old_format(const Reader& reader)
246 reader.get("gravity", gravity);
248 std::string backgroundimage;
249 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
250 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
251 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
252 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
253 backgroundimage = "images/background/" + backgroundimage;
254 if (!PHYSFS_exists(backgroundimage.c_str())) {
255 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
256 backgroundimage = "";
261 reader.get("bkgd_speed", bgspeed);
264 Color bkgd_top, bkgd_bottom;
265 int r = 0, g = 0, b = 128;
266 reader.get("bkgd_red_top", r);
267 reader.get("bkgd_green_top", g);
268 reader.get("bkgd_blue_top", b);
269 bkgd_top.red = static_cast<float> (r) / 255.0f;
270 bkgd_top.green = static_cast<float> (g) / 255.0f;
271 bkgd_top.blue = static_cast<float> (b) / 255.0f;
273 reader.get("bkgd_red_bottom", r);
274 reader.get("bkgd_green_bottom", g);
275 reader.get("bkgd_blue_bottom", b);
276 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
277 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
278 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
280 if(backgroundimage != "") {
281 auto background = std::make_shared<Background>();
282 background->set_image(backgroundimage, bgspeed);
283 add_object(background);
285 auto gradient = std::make_shared<Gradient>();
286 gradient->set_gradient(bkgd_top, bkgd_bottom);
287 add_object(gradient);
290 std::string particlesystem;
291 reader.get("particle_system", particlesystem);
292 if(particlesystem == "clouds")
293 add_object(std::make_shared<CloudParticleSystem>());
294 else if(particlesystem == "snow")
295 add_object(std::make_shared<SnowParticleSystem>());
296 else if(particlesystem == "rain")
297 add_object(std::make_shared<RainParticleSystem>());
299 Vector startpos(100, 170);
300 reader.get("start_pos_x", startpos.x);
301 reader.get("start_pos_y", startpos.y);
303 auto spawn = std::make_shared<SpawnPoint>();
304 spawn->pos = startpos;
305 spawn->name = "main";
306 spawnpoints.push_back(spawn);
308 music = "chipdisko.ogg";
309 // skip reading music filename. It's all .ogg now, anyway
311 reader.get("music", music);
313 music = "music/" + music;
315 int width = 30, height = 15;
316 reader.get("width", width);
317 reader.get("height", height);
319 std::vector<unsigned int> tiles;
320 if(reader.get("interactive-tm", tiles)
321 || reader.get("tilemap", tiles)) {
322 auto tilemap = std::make_shared<TileMap>(level->get_tileset());
323 tilemap->set(width, height, tiles, LAYER_TILES, true);
325 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
326 for(size_t x=0; x < tilemap->get_width(); ++x) {
327 for(size_t y=0; y < tilemap->get_height(); ++y) {
328 uint32_t id = tilemap->get_tile_id(x, y);
330 tilemap->change(x, y, 1311);
334 if (height < 19) tilemap->resize(width, 19);
338 if(reader.get("background-tm", tiles)) {
339 auto tilemap = std::make_shared<TileMap>(level->get_tileset());
340 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
341 if (height < 19) tilemap->resize(width, 19);
345 if(reader.get("foreground-tm", tiles)) {
346 auto tilemap = std::make_shared<TileMap>(level->get_tileset());
347 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
349 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
350 if (height < 19) tilemap->resize(width, 19, 2035);
355 // read reset-points (now spawn-points)
356 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
358 lisp::ListIterator iter(resetpoints);
360 if(iter.item() == "point") {
362 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
364 auto sp = std::make_shared<SpawnPoint>();
367 spawnpoints.push_back(sp);
370 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
376 const lisp::Lisp* objects = reader.get_lisp("objects");
378 lisp::ListIterator iter(objects);
380 auto object = parse_object(iter.item(), *(iter.lisp()));
384 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
390 auto camera_ = std::make_shared<Camera>(this, "Camera");
393 update_game_objects();
395 if(solid_tilemaps.empty()) { log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl; }
398 update_game_objects();
402 Sector::fix_old_tiles()
404 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
405 TileMap* solids = *i;
406 for(size_t x=0; x < solids->get_width(); ++x) {
407 for(size_t y=0; y < solids->get_height(); ++y) {
408 uint32_t id = solids->get_tile_id(x, y);
409 const Tile *tile = solids->get_tile(x, y);
410 Vector pos = solids->get_tile_position(x, y);
413 add_object(std::make_shared<InvisibleBlock>(pos));
414 solids->change(x, y, 0);
415 } else if(tile->getAttributes() & Tile::COIN) {
416 add_object(std::make_shared<Coin>(pos, solids));
417 solids->change(x, y, 0);
418 } else if(tile->getAttributes() & Tile::FULLBOX) {
419 add_object(std::make_shared<BonusBlock>(pos, tile->getData()));
420 solids->change(x, y, 0);
421 } else if(tile->getAttributes() & Tile::BRICK) {
422 if( ( id == 3159 ) || ( id == 3160 ) ){
423 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brickWeb.sprite") );
424 } else if( ( id == 78 ) || ( id == 105 ) ){
425 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brickIce.sprite") );
426 } else if( ( id == 77 ) || ( id == 104 ) ){
427 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
429 log_warning << "attribute 'brick #t' is not supported for tile-id " << id << std::endl;
430 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
432 solids->change(x, y, 0);
433 } else if(tile->getAttributes() & Tile::GOAL) {
434 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
435 add_object(std::make_shared<SequenceTrigger>(pos, sequence));
436 solids->change(x, y, 0);
442 // add lights for special tiles
443 for(auto i = gameobjects.begin(); i != gameobjects.end(); i++) {
444 TileMap* tm = dynamic_cast<TileMap*>(i->get());
446 for(size_t x=0; x < tm->get_width(); ++x) {
447 for(size_t y=0; y < tm->get_height(); ++y) {
448 uint32_t id = tm->get_tile_id(x, y);
449 Vector pos = tm->get_tile_position(x, y);
450 Vector center = pos + Vector(16, 16);
454 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
455 add_object(std::make_shared<PulsingLight>(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
458 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
459 // space lights a bit
460 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
461 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
462 || ((x % 3 == 0) && (y % 3 == 0))) {
463 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
464 add_object(std::make_shared<PulsingLight>(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
475 Sector::run_script(std::istream& in, const std::string& sourcename)
477 using namespace scripting;
479 // garbage collect thread list
480 for(auto i = scripts.begin(); i != scripts.end(); ) {
481 HSQOBJECT& object = *i;
482 HSQUIRRELVM vm = object_to_vm(object);
484 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
485 sq_release(global_vm, &object);
486 i = scripts.erase(i);
493 HSQOBJECT object = create_thread(global_vm);
494 scripts.push_back(object);
496 HSQUIRRELVM vm = object_to_vm(object);
498 // set sector_table as roottable for the thread
499 sq_pushobject(vm, sector_table);
503 compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
504 } catch(std::exception& e) {
505 log_warning << "Error running script: " << e.what() << std::endl;
512 Sector::add_object(GameObjectPtr object)
514 // make sure the object isn't already in the list
516 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
517 assert(*i != object);
519 for(auto i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i) {
520 assert(*i != object);
524 gameobjects_new.push_back(object);
528 Sector::activate(const std::string& spawnpoint)
530 std::shared_ptr<SpawnPoint> sp;
531 for(auto i = spawnpoints.begin(); i != spawnpoints.end(); ++i) {
532 if((*i)->name == spawnpoint) {
538 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
539 if(spawnpoint != "main") {
542 activate(Vector(0, 0));
550 Sector::activate(const Vector& player_pos)
552 if(_current != this) {
554 _current->deactivate();
557 // register sectortable as sector in scripting
558 HSQUIRRELVM vm = scripting::global_vm;
559 sq_pushroottable(vm);
560 sq_pushstring(vm, "sector", -1);
561 sq_pushobject(vm, sector_table);
562 if(SQ_FAILED(sq_createslot(vm, -3)))
563 throw scripting::SquirrelError(vm, "Couldn't set sector in roottable");
566 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
567 GameObjectPtr object = *i;
575 // two-player hack: move other players to main player's position
576 // Maybe specify 2 spawnpoints in the level?
577 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
578 Player* p = dynamic_cast<Player*>(i->get());
581 // spawn smalltux below spawnpoint
583 p->move(player_pos + Vector(0,32));
588 // spawning tux in the ground would kill him
589 if(!is_free_of_tiles(p->get_bbox())) {
590 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
591 Vector npos = p->get_bbox().p1;
597 //FIXME: This is a really dirty workaround for this strange camera jump
598 player->move(player->get_pos()+Vector(-32, 0));
599 camera->reset(player->get_pos());
601 player->move(player->get_pos()+(Vector(32, 0)));
604 update_game_objects();
606 //Run default.nut just before init script
607 //Check to see if it's in a levelset (info file)
608 std::string basedir = FileSystem::dirname(get_level()->filename);
609 if(PHYSFS_exists((basedir + "/info").c_str())) {
611 IFileStreambuf ins(basedir + "/default.nut");
612 std::istream in(&ins);
613 run_script(in, "default.nut");
614 } catch(std::exception& ) {
615 // doesn't exist or erroneous; do nothing
620 if(init_script != "") {
621 std::istringstream in(init_script);
622 run_script(in, "init-script");
632 // remove sector entry from global vm
633 HSQUIRRELVM vm = scripting::global_vm;
634 sq_pushroottable(vm);
635 sq_pushstring(vm, "sector", -1);
636 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
637 throw scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
640 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
641 GameObjectPtr object = *i;
643 try_unexpose(object);
651 Sector::get_active_region()
654 camera->get_translation() - Vector(1600, 1200),
655 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
659 Sector::calculate_foremost_layer()
661 int layer = LAYER_BACKGROUND0;
662 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
664 TileMap* tm = dynamic_cast<TileMap*>(i->get());
666 if(tm->get_layer() > layer)
668 if( (tm->get_alpha() < 1.0) )
670 layer = tm->get_layer() - 1;
674 layer = tm->get_layer() + 1;
678 log_debug << "Calculated baduy falling layer was: " << layer << std::endl;
683 Sector::get_foremost_layer()
685 return foremost_layer;
689 Sector::update(float elapsed_time)
691 player->check_bounds();
694 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
695 GameObjectPtr& object = *i;
696 if(!object->is_valid())
699 object->update(elapsed_time);
702 /* Handle all possible collisions. */
704 update_game_objects();
708 Sector::update_game_objects()
710 /** cleanup marked objects */
711 for(auto i = gameobjects.begin();
712 i != gameobjects.end(); /* nothing */) {
713 GameObjectPtr& object = *i;
715 if(object->is_valid()) {
720 before_object_remove(object);
722 i = gameobjects.erase(i);
725 /* add newly created objects */
726 for(auto i = gameobjects_new.begin();
727 i != gameobjects_new.end(); ++i)
729 GameObjectPtr object = *i;
731 before_object_add(object);
733 gameobjects.push_back(object);
735 gameobjects_new.clear();
737 /* update solid_tilemaps list */
738 //FIXME: this could be more efficient
739 solid_tilemaps.clear();
740 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
742 TileMap* tm = dynamic_cast<TileMap*>(i->get());
744 if (tm->is_solid()) solid_tilemaps.push_back(tm);
750 Sector::before_object_add(GameObjectPtr object)
752 auto bullet = dynamic_cast<Bullet*>(object.get());
755 bullets.push_back(bullet);
758 auto movingobject = dynamic_cast<MovingObject*>(object.get());
761 moving_objects.push_back(movingobject);
764 auto portable = dynamic_cast<Portable*>(object.get());
767 portables.push_back(portable);
770 auto tilemap = dynamic_cast<TileMap*>(object.get());
771 if(tilemap && tilemap->is_solid()) {
772 solid_tilemaps.push_back(tilemap);
775 auto camera_ = dynamic_cast<Camera*>(object.get());
777 if(this->camera != 0) {
778 log_warning << "Multiple cameras added. Ignoring" << std::endl;
781 this->camera = camera_;
784 auto player_ = dynamic_cast<Player*>(object.get());
786 if(this->player != 0) {
787 log_warning << "Multiple players added. Ignoring" << std::endl;
790 this->player = player_;
793 auto effect_ = dynamic_cast<DisplayEffect*>(object.get());
795 if(this->effect != 0) {
796 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
799 this->effect = effect_;
802 if(_current == this) {
810 Sector::try_expose(GameObjectPtr object)
812 ScriptInterface* object_ = dynamic_cast<ScriptInterface*>(object.get());
813 if(object_ != NULL) {
814 HSQUIRRELVM vm = scripting::global_vm;
815 sq_pushobject(vm, sector_table);
816 object_->expose(vm, -1);
822 Sector::try_expose_me()
824 HSQUIRRELVM vm = scripting::global_vm;
825 sq_pushobject(vm, sector_table);
826 scripting::SSector* this_ = static_cast<scripting::SSector*>(this);
827 expose_object(vm, -1, this_, "settings", false);
832 Sector::before_object_remove(GameObjectPtr object)
834 Portable* portable = dynamic_cast<Portable*>(object.get());
836 portables.erase(std::find(portables.begin(), portables.end(), portable));
838 Bullet* bullet = dynamic_cast<Bullet*>(object.get());
840 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
842 MovingObject* moving_object = dynamic_cast<MovingObject*>(object.get());
844 moving_objects.erase(
845 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
849 try_unexpose(object);
853 Sector::try_unexpose(GameObjectPtr object)
855 ScriptInterface* object_ = dynamic_cast<ScriptInterface*>(object.get());
856 if(object_ != NULL) {
857 HSQUIRRELVM vm = scripting::global_vm;
858 SQInteger oldtop = sq_gettop(vm);
859 sq_pushobject(vm, sector_table);
861 object_->unexpose(vm, -1);
862 } catch(std::exception& e) {
863 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
865 sq_settop(vm, oldtop);
870 Sector::try_unexpose_me()
872 HSQUIRRELVM vm = scripting::global_vm;
873 SQInteger oldtop = sq_gettop(vm);
874 sq_pushobject(vm, sector_table);
876 scripting::unexpose_object(vm, -1, "settings");
877 } catch(std::exception& e) {
878 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
880 sq_settop(vm, oldtop);
883 Sector::draw(DrawingContext& context)
885 context.set_ambient_color( ambient_light );
886 context.push_transform();
887 context.set_translation(camera->get_translation());
889 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
890 GameObjectPtr& object = *i;
891 if(!object->is_valid())
894 if (draw_solids_only)
896 TileMap* tm = dynamic_cast<TileMap*>(object.get());
897 if (tm && !tm->is_solid())
901 object->draw(context);
905 Color color(1.0f, 0.0f, 0.0f, 0.75f);
906 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
907 MovingObject* object = *i;
908 const Rectf& rect = object->get_bbox();
910 context.draw_filled_rect(rect, color, LAYER_FOREGROUND1 + 10);
914 context.pop_transform();
917 /*-------------------------------------------------------------------------
918 * Collision Detection
919 *-------------------------------------------------------------------------*/
921 /** r1 is supposed to be moving, r2 a solid object */
922 void check_collisions(collision::Constraints* constraints,
923 const Vector& obj_movement, const Rectf& obj_rect, const Rectf& other_rect,
924 GameObject* object = NULL, MovingObject* other = NULL, const Vector& other_movement = Vector(0,0))
926 if(!collision::intersects(obj_rect, other_rect))
929 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
931 if(other != NULL && !other->collides(*object, dummy))
933 if(moving_object != NULL && !moving_object->collides(*other, dummy))
936 // calculate intersection
937 float itop = obj_rect.get_bottom() - other_rect.get_top();
938 float ibottom = other_rect.get_bottom() - obj_rect.get_top();
939 float ileft = obj_rect.get_right() - other_rect.get_left();
940 float iright = other_rect.get_right() - obj_rect.get_left();
942 if(fabsf(obj_movement.y) > fabsf(obj_movement.x)) {
943 if(ileft < SHIFT_DELTA) {
944 constraints->constrain_right(other_rect.get_left(), other_movement.x);
946 } else if(iright < SHIFT_DELTA) {
947 constraints->constrain_left(other_rect.get_right(), other_movement.x);
951 // shiftout bottom/top
952 if(itop < SHIFT_DELTA) {
953 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
955 } else if(ibottom < SHIFT_DELTA) {
956 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
961 constraints->ground_movement += other_movement;
963 HitResponse response = other->collision(*object, dummy);
964 if(response == ABORT_MOVE)
967 if(other->get_movement() != Vector(0, 0)) {
968 // TODO what todo when we collide with 2 moving objects?!?
969 constraints->ground_movement = other->get_movement();
973 float vert_penetration = std::min(itop, ibottom);
974 float horiz_penetration = std::min(ileft, iright);
975 if(vert_penetration < horiz_penetration) {
977 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
978 constraints->hit.bottom = true;
980 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
981 constraints->hit.top = true;
985 constraints->constrain_right(other_rect.get_left(), other_movement.x);
986 constraints->hit.right = true;
988 constraints->constrain_left(other_rect.get_right(), other_movement.x);
989 constraints->hit.left = true;
995 Sector::collision_tilemap(collision::Constraints* constraints,
996 const Vector& movement, const Rectf& dest,
997 MovingObject& object) const
999 // calculate rectangle where the object will move
1000 float x1 = dest.get_left();
1001 float x2 = dest.get_right();
1002 float y1 = dest.get_top();
1003 float y2 = dest.get_bottom();
1005 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1006 TileMap* solids = *i;
1008 // test with all tiles in this rectangle
1009 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1011 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1012 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1013 const Tile* tile = solids->get_tile(x, y);
1016 // skip non-solid tiles
1017 if(!tile->is_solid ())
1019 Rectf tile_bbox = solids->get_tile_bbox(x, y);
1021 /* If the tile is a unisolid tile, the "is_solid()" function above
1022 * didn't do a thorough check. Calculate the position and (relative)
1023 * movement of the object and determine whether or not the tile is
1024 * solid with regard to those parameters. */
1025 if(tile->is_unisolid ()) {
1026 Vector relative_movement = movement
1027 - solids->get_movement(/* actual = */ true);
1029 if (!tile->is_solid (tile_bbox, object.get_bbox(), relative_movement))
1031 } /* if (tile->is_unisolid ()) */
1033 if(tile->is_slope ()) { // slope tile
1034 AATriangle triangle;
1035 int slope_data = tile->getData();
1036 if (solids->get_drawing_effect() & VERTICAL_FLIP)
1037 slope_data = AATriangle::vertical_flip(slope_data);
1038 triangle = AATriangle(tile_bbox, slope_data);
1040 collision::rectangle_aatriangle(constraints, dest, triangle,
1041 solids->get_movement(/* actual = */ false));
1042 } else { // normal rectangular tile
1043 check_collisions(constraints, movement, dest, tile_bbox, NULL, NULL,
1044 solids->get_movement(/* actual = */ false));
1052 Sector::collision_tile_attributes(const Rectf& dest) const
1054 float x1 = dest.p1.x;
1055 float y1 = dest.p1.y;
1056 float x2 = dest.p2.x;
1057 float y2 = dest.p2.y;
1059 uint32_t result = 0;
1060 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1061 TileMap* solids = *i;
1063 // test with all tiles in this rectangle
1064 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1065 // For ice (only), add a little fudge to recognize tiles Tux is standing on.
1066 Rect test_tiles_ice = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2 + SHIFT_DELTA));
1068 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1070 for(y = test_tiles.top; y < test_tiles.bottom; ++y) {
1071 const Tile* tile = solids->get_tile(x, y);
1074 result |= tile->getAttributes();
1076 for(; y < test_tiles_ice.bottom; ++y) {
1077 const Tile* tile = solids->get_tile(x, y);
1080 result |= (tile->getAttributes() & Tile::ICE);
1088 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1089 static void get_hit_normal(const Rectf& r1, const Rectf& r2, CollisionHit& hit,
1092 float itop = r1.get_bottom() - r2.get_top();
1093 float ibottom = r2.get_bottom() - r1.get_top();
1094 float ileft = r1.get_right() - r2.get_left();
1095 float iright = r2.get_right() - r1.get_left();
1097 float vert_penetration = std::min(itop, ibottom);
1098 float horiz_penetration = std::min(ileft, iright);
1099 if(vert_penetration < horiz_penetration) {
1100 if(itop < ibottom) {
1102 normal.y = vert_penetration;
1105 normal.y = -vert_penetration;
1108 if(ileft < iright) {
1110 normal.x = horiz_penetration;
1113 normal.x = -horiz_penetration;
1119 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1121 using namespace collision;
1123 const Rectf& r1 = object1->dest;
1124 const Rectf& r2 = object2->dest;
1127 if(intersects(object1->dest, object2->dest)) {
1129 get_hit_normal(r1, r2, hit, normal);
1131 if(!object1->collides(*object2, hit))
1133 std::swap(hit.left, hit.right);
1134 std::swap(hit.top, hit.bottom);
1135 if(!object2->collides(*object1, hit))
1137 std::swap(hit.left, hit.right);
1138 std::swap(hit.top, hit.bottom);
1140 HitResponse response1 = object1->collision(*object2, hit);
1141 std::swap(hit.left, hit.right);
1142 std::swap(hit.top, hit.bottom);
1143 HitResponse response2 = object2->collision(*object1, hit);
1144 if(response1 == CONTINUE && response2 == CONTINUE) {
1145 normal *= (0.5 + DELTA);
1146 object1->dest.move(-normal);
1147 object2->dest.move(normal);
1148 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1149 normal *= (1 + DELTA);
1150 object1->dest.move(-normal);
1151 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1152 normal *= (1 + DELTA);
1153 object2->dest.move(normal);
1159 Sector::collision_static(collision::Constraints* constraints,
1160 const Vector& movement, const Rectf& dest,
1161 MovingObject& object)
1163 collision_tilemap(constraints, movement, dest, object);
1165 // collision with other (static) objects
1166 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1167 MovingObject* moving_object = *i;
1168 if(moving_object->get_group() != COLGROUP_STATIC
1169 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1171 if(!moving_object->is_valid())
1174 if(moving_object != &object)
1175 check_collisions(constraints, movement, dest, moving_object->bbox,
1176 &object, moving_object);
1181 Sector::collision_static_constrains(MovingObject& object)
1183 using namespace collision;
1184 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1186 Constraints constraints;
1187 Vector movement = object.get_movement();
1188 Rectf& dest = object.dest;
1190 for(int i = 0; i < 2; ++i) {
1191 collision_static(&constraints, Vector(0, movement.y), dest, object);
1192 if(!constraints.has_constraints())
1195 // apply calculated horizontal constraints
1196 if(constraints.get_position_bottom() < infinity) {
1197 float height = constraints.get_height ();
1198 if(height < object.get_bbox().get_height()) {
1199 // we're crushed, but ignore this for now, we'll get this again
1200 // later if we're really crushed or things will solve itself when
1201 // looking at the vertical constraints
1203 dest.p2.y = constraints.get_position_bottom() - DELTA;
1204 dest.p1.y = dest.p2.y - object.get_bbox().get_height();
1205 } else if(constraints.get_position_top() > -infinity) {
1206 dest.p1.y = constraints.get_position_top() + DELTA;
1207 dest.p2.y = dest.p1.y + object.get_bbox().get_height();
1210 if(constraints.has_constraints()) {
1211 if(constraints.hit.bottom) {
1212 dest.move(constraints.ground_movement);
1214 if(constraints.hit.top || constraints.hit.bottom) {
1215 constraints.hit.left = false;
1216 constraints.hit.right = false;
1217 object.collision_solid(constraints.hit);
1221 constraints = Constraints();
1222 for(int i = 0; i < 2; ++i) {
1223 collision_static(&constraints, movement, dest, object);
1224 if(!constraints.has_constraints())
1227 // apply calculated vertical constraints
1228 float width = constraints.get_width ();
1229 if(width < infinity) {
1230 if(width + SHIFT_DELTA < object.get_bbox().get_width()) {
1232 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1233 constraints.get_position_left(), constraints.get_position_right());
1239 object.collision_solid(h);
1241 float xmid = constraints.get_x_midpoint ();
1242 dest.p1.x = xmid - object.get_bbox().get_width()/2;
1243 dest.p2.x = xmid + object.get_bbox().get_width()/2;
1245 } else if(constraints.get_position_right() < infinity) {
1246 dest.p2.x = constraints.get_position_right() - DELTA;
1247 dest.p1.x = dest.p2.x - object.get_bbox().get_width();
1248 } else if(constraints.get_position_left() > -infinity) {
1249 dest.p1.x = constraints.get_position_left() + DELTA;
1250 dest.p2.x = dest.p1.x + object.get_bbox().get_width();
1254 if(constraints.has_constraints()) {
1255 if( constraints.hit.left || constraints.hit.right
1256 || constraints.hit.top || constraints.hit.bottom
1257 || constraints.hit.crush )
1258 object.collision_solid(constraints.hit);
1261 // an extra pass to make sure we're not crushed horizontally
1262 constraints = Constraints();
1263 collision_static(&constraints, movement, dest, object);
1264 if(constraints.get_position_bottom() < infinity) {
1265 float height = constraints.get_height ();
1266 if(height + SHIFT_DELTA < object.get_bbox().get_height()) {
1268 printf("Object %p crushed vertically...\n", &object);
1274 object.collision_solid(h);
1280 const float MAX_SPEED = 16.0f;
1284 Sector::handle_collisions()
1286 using namespace collision;
1288 // calculate destination positions of the objects
1289 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1290 MovingObject* moving_object = *i;
1291 Vector mov = moving_object->get_movement();
1293 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1294 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1295 moving_object->movement = mov.unit() * MAX_SPEED;
1296 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1299 moving_object->dest = moving_object->get_bbox();
1300 moving_object->dest.move(moving_object->get_movement());
1303 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1304 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1305 MovingObject* moving_object = *i;
1306 if((moving_object->get_group() != COLGROUP_MOVING
1307 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1308 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1309 || !moving_object->is_valid())
1312 collision_static_constrains(*moving_object);
1315 // part2: COLGROUP_MOVING vs tile attributes
1316 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1317 MovingObject* moving_object = *i;
1318 if((moving_object->get_group() != COLGROUP_MOVING
1319 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1320 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1321 || !moving_object->is_valid())
1324 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1325 if(tile_attributes >= Tile::FIRST_INTERESTING_FLAG) {
1326 moving_object->collision_tile(tile_attributes);
1330 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1331 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1332 MovingObject* moving_object = *i;
1333 if((moving_object->get_group() != COLGROUP_MOVING
1334 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1335 || !moving_object->is_valid())
1338 for(auto i2 = moving_objects.begin(); i2 != moving_objects.end(); ++i2) {
1339 MovingObject* moving_object_2 = *i2;
1340 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1341 || !moving_object_2->is_valid())
1344 if(intersects(moving_object->dest, moving_object_2->dest)) {
1347 get_hit_normal(moving_object->dest, moving_object_2->dest,
1349 if(!moving_object->collides(*moving_object_2, hit))
1351 if(!moving_object_2->collides(*moving_object, hit))
1354 moving_object->collision(*moving_object_2, hit);
1355 moving_object_2->collision(*moving_object, hit);
1360 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1361 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1362 MovingObject* moving_object = *i;
1364 if((moving_object->get_group() != COLGROUP_MOVING
1365 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1366 || !moving_object->is_valid())
1369 for(auto i2 = i+1; i2 != moving_objects.end(); ++i2) {
1370 MovingObject* moving_object_2 = *i2;
1371 if((moving_object_2->get_group() != COLGROUP_MOVING
1372 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1373 || !moving_object_2->is_valid())
1376 collision_object(moving_object, moving_object_2);
1380 // apply object movement
1381 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1382 MovingObject* moving_object = *i;
1384 moving_object->bbox = moving_object->dest;
1385 moving_object->movement = Vector(0, 0);
1390 Sector::is_free_of_tiles(const Rectf& rect, const bool ignoreUnisolid) const
1392 using namespace collision;
1394 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1395 TileMap* solids = *i;
1397 // test with all tiles in this rectangle
1398 Rect test_tiles = solids->get_tiles_overlapping(rect);
1400 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1401 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1402 const Tile* tile = solids->get_tile(x, y);
1404 if(!(tile->getAttributes() & Tile::SOLID))
1406 if(tile->is_unisolid () && ignoreUnisolid)
1408 if(tile->is_slope ()) {
1409 AATriangle triangle;
1410 Rectf tbbox = solids->get_tile_bbox(x, y);
1411 triangle = AATriangle(tbbox, tile->getData());
1412 Constraints constraints;
1413 if(!collision::rectangle_aatriangle(&constraints, rect, triangle))
1416 // We have a solid tile that overlaps the given rectangle.
1426 Sector::is_free_of_statics(const Rectf& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1428 using namespace collision;
1430 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1432 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1433 const MovingObject* moving_object = *i;
1434 if (moving_object == ignore_object) continue;
1435 if (!moving_object->is_valid()) continue;
1436 if (moving_object->get_group() == COLGROUP_STATIC) {
1437 if(intersects(rect, moving_object->get_bbox())) return false;
1445 Sector::is_free_of_movingstatics(const Rectf& rect, const MovingObject* ignore_object) const
1447 using namespace collision;
1449 if (!is_free_of_tiles(rect)) return false;
1451 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1452 const MovingObject* moving_object = *i;
1453 if (moving_object == ignore_object) continue;
1454 if (!moving_object->is_valid()) continue;
1455 if ((moving_object->get_group() == COLGROUP_MOVING)
1456 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1457 || (moving_object->get_group() == COLGROUP_STATIC)) {
1458 if(intersects(rect, moving_object->get_bbox())) return false;
1466 Sector::add_smoke_cloud(const Vector& pos)
1468 add_object(std::make_shared<SmokeCloud>(pos));
1473 Sector::play_music(MusicType type)
1475 currentmusic = type;
1476 switch(currentmusic) {
1478 SoundManager::current()->play_music(music);
1481 SoundManager::current()->play_music("music/invincible.ogg");
1483 case HERRING_WARNING_MUSIC:
1484 SoundManager::current()->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1487 SoundManager::current()->play_music("");
1493 Sector::get_music_type()
1495 return currentmusic;
1499 Sector::get_total_badguys()
1501 int total_badguys = 0;
1502 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
1503 BadGuy* badguy = dynamic_cast<BadGuy*>(i->get());
1504 if (badguy && badguy->countMe)
1508 return total_badguys;
1512 Sector::inside(const Rectf& rect) const
1514 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1515 TileMap* solids = *i;
1517 Rectf bbox = solids->get_bbox();
1518 bbox.p1.y = -INFINITY; // pretend the tilemap extends infinitely far upwards
1520 if (bbox.contains(rect))
1527 Sector::get_width() const
1530 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1531 TileMap* solids = *i;
1532 width = std::max(width, solids->get_bbox().get_right());
1539 Sector::get_height() const
1542 for(auto i = solid_tilemaps.begin();
1543 i != solid_tilemaps.end(); i++) {
1544 TileMap* solids = *i;
1545 height = std::max(height, solids->get_bbox().get_bottom());
1552 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1554 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1555 TileMap* solids = *i;
1556 solids->change_all(old_tile_id, new_tile_id);
1561 Sector::set_ambient_light(float red, float green, float blue)
1563 ambient_light.red = red;
1564 ambient_light.green = green;
1565 ambient_light.blue = blue;
1569 Sector::get_ambient_red()
1571 return ambient_light.red;
1575 Sector::get_ambient_green()
1577 return ambient_light.green;
1581 Sector::get_ambient_blue()
1583 return ambient_light.blue;
1587 Sector::set_gravity(float gravity_)
1589 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1590 this->gravity = gravity_;
1594 Sector::get_gravity() const
1600 Sector::get_nearest_player (const Vector& pos)
1602 Player *nearest_player = NULL;
1603 float nearest_dist = std::numeric_limits<float>::max();
1605 std::vector<Player*> players = Sector::current()->get_players();
1606 for (auto playerIter = players.begin(); playerIter != players.end(); ++playerIter)
1608 Player *this_player = *playerIter;
1609 if (this_player->is_dying() || this_player->is_dead())
1612 float this_dist = this_player->get_bbox ().distance(pos);
1614 if (this_dist < nearest_dist) {
1615 nearest_player = this_player;
1616 nearest_dist = this_dist;
1620 return nearest_player;
1621 } /* Player *get_nearest_player */
1623 std::vector<MovingObject*>
1624 Sector::get_nearby_objects (const Vector& center, float max_distance)
1626 std::vector<MovingObject*> ret;
1627 std::vector<Player*> players = Sector::current()->get_players();
1629 for (size_t i = 0; i < players.size (); i++) {
1630 float distance = players[i]->get_bbox ().distance (center);
1631 if (distance <= max_distance)
1632 ret.push_back (players[i]);
1635 for (size_t i = 0; i < moving_objects.size (); i++) {
1636 float distance = moving_objects[i]->get_bbox ().distance (center);
1637 if (distance <= max_distance)
1638 ret.push_back (moving_objects[i]);
1644 /* vim: set sw=2 sts=2 et : */