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 std::string current_level = "[" + Sector::current()->get_level()->filename + "] ";
591 log_warning << current_level << "Tried spawning Tux in solid matter. Compensating." << std::endl;
592 Vector npos = p->get_bbox().p1;
598 //FIXME: This is a really dirty workaround for this strange camera jump
599 player->move(player->get_pos()+Vector(-32, 0));
600 camera->reset(player->get_pos());
602 player->move(player->get_pos()+(Vector(32, 0)));
605 update_game_objects();
607 //Run default.nut just before init script
608 //Check to see if it's in a levelset (info file)
609 std::string basedir = FileSystem::dirname(get_level()->filename);
610 if(PHYSFS_exists((basedir + "/info").c_str())) {
612 IFileStreambuf ins(basedir + "/default.nut");
613 std::istream in(&ins);
614 run_script(in, "default.nut");
615 } catch(std::exception& ) {
616 // doesn't exist or erroneous; do nothing
621 if(init_script != "") {
622 std::istringstream in(init_script);
623 run_script(in, "init-script");
633 // remove sector entry from global vm
634 HSQUIRRELVM vm = scripting::global_vm;
635 sq_pushroottable(vm);
636 sq_pushstring(vm, "sector", -1);
637 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
638 throw scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
641 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
642 GameObjectPtr object = *i;
644 try_unexpose(object);
652 Sector::get_active_region()
655 camera->get_translation() - Vector(1600, 1200),
656 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
660 Sector::calculate_foremost_layer()
662 int layer = LAYER_BACKGROUND0;
663 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
665 TileMap* tm = dynamic_cast<TileMap*>(i->get());
667 if(tm->get_layer() > layer)
669 if( (tm->get_alpha() < 1.0) )
671 layer = tm->get_layer() - 1;
675 layer = tm->get_layer() + 1;
679 log_debug << "Calculated baduy falling layer was: " << layer << std::endl;
684 Sector::get_foremost_layer()
686 return foremost_layer;
690 Sector::update(float elapsed_time)
692 player->check_bounds();
695 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
696 GameObjectPtr& object = *i;
697 if(!object->is_valid())
700 object->update(elapsed_time);
703 /* Handle all possible collisions. */
705 update_game_objects();
709 Sector::update_game_objects()
711 /** cleanup marked objects */
712 for(auto i = gameobjects.begin();
713 i != gameobjects.end(); /* nothing */) {
714 GameObjectPtr& object = *i;
716 if(object->is_valid()) {
721 before_object_remove(object);
723 i = gameobjects.erase(i);
726 /* add newly created objects */
727 for(auto i = gameobjects_new.begin();
728 i != gameobjects_new.end(); ++i)
730 GameObjectPtr object = *i;
732 before_object_add(object);
734 gameobjects.push_back(object);
736 gameobjects_new.clear();
738 /* update solid_tilemaps list */
739 //FIXME: this could be more efficient
740 solid_tilemaps.clear();
741 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
743 TileMap* tm = dynamic_cast<TileMap*>(i->get());
745 if (tm->is_solid()) solid_tilemaps.push_back(tm);
751 Sector::before_object_add(GameObjectPtr object)
753 auto bullet = dynamic_cast<Bullet*>(object.get());
756 bullets.push_back(bullet);
759 auto movingobject = dynamic_cast<MovingObject*>(object.get());
762 moving_objects.push_back(movingobject);
765 auto portable = dynamic_cast<Portable*>(object.get());
768 portables.push_back(portable);
771 auto tilemap = dynamic_cast<TileMap*>(object.get());
772 if(tilemap && tilemap->is_solid()) {
773 solid_tilemaps.push_back(tilemap);
776 auto camera_ = dynamic_cast<Camera*>(object.get());
778 if(this->camera != 0) {
779 log_warning << "Multiple cameras added. Ignoring" << std::endl;
782 this->camera = camera_;
785 auto player_ = dynamic_cast<Player*>(object.get());
787 if(this->player != 0) {
788 log_warning << "Multiple players added. Ignoring" << std::endl;
791 this->player = player_;
794 auto effect_ = dynamic_cast<DisplayEffect*>(object.get());
796 if(this->effect != 0) {
797 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
800 this->effect = effect_;
803 if(_current == this) {
811 Sector::try_expose(GameObjectPtr object)
813 ScriptInterface* object_ = dynamic_cast<ScriptInterface*>(object.get());
814 if(object_ != NULL) {
815 HSQUIRRELVM vm = scripting::global_vm;
816 sq_pushobject(vm, sector_table);
817 object_->expose(vm, -1);
823 Sector::try_expose_me()
825 HSQUIRRELVM vm = scripting::global_vm;
826 sq_pushobject(vm, sector_table);
827 scripting::SSector* this_ = static_cast<scripting::SSector*>(this);
828 expose_object(vm, -1, this_, "settings", false);
833 Sector::before_object_remove(GameObjectPtr object)
835 Portable* portable = dynamic_cast<Portable*>(object.get());
837 portables.erase(std::find(portables.begin(), portables.end(), portable));
839 Bullet* bullet = dynamic_cast<Bullet*>(object.get());
841 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
843 MovingObject* moving_object = dynamic_cast<MovingObject*>(object.get());
845 moving_objects.erase(
846 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
850 try_unexpose(object);
854 Sector::try_unexpose(GameObjectPtr object)
856 ScriptInterface* object_ = dynamic_cast<ScriptInterface*>(object.get());
857 if(object_ != NULL) {
858 HSQUIRRELVM vm = scripting::global_vm;
859 SQInteger oldtop = sq_gettop(vm);
860 sq_pushobject(vm, sector_table);
862 object_->unexpose(vm, -1);
863 } catch(std::exception& e) {
864 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
866 sq_settop(vm, oldtop);
871 Sector::try_unexpose_me()
873 HSQUIRRELVM vm = scripting::global_vm;
874 SQInteger oldtop = sq_gettop(vm);
875 sq_pushobject(vm, sector_table);
877 scripting::unexpose_object(vm, -1, "settings");
878 } catch(std::exception& e) {
879 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
881 sq_settop(vm, oldtop);
884 Sector::draw(DrawingContext& context)
886 context.set_ambient_color( ambient_light );
887 context.push_transform();
888 context.set_translation(camera->get_translation());
890 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
891 GameObjectPtr& object = *i;
892 if(!object->is_valid())
895 if (draw_solids_only)
897 TileMap* tm = dynamic_cast<TileMap*>(object.get());
898 if (tm && !tm->is_solid())
902 object->draw(context);
906 Color color(1.0f, 0.0f, 0.0f, 0.75f);
907 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
908 MovingObject* object = *i;
909 const Rectf& rect = object->get_bbox();
911 context.draw_filled_rect(rect, color, LAYER_FOREGROUND1 + 10);
915 context.pop_transform();
918 /*-------------------------------------------------------------------------
919 * Collision Detection
920 *-------------------------------------------------------------------------*/
922 /** r1 is supposed to be moving, r2 a solid object */
923 void check_collisions(collision::Constraints* constraints,
924 const Vector& obj_movement, const Rectf& obj_rect, const Rectf& other_rect,
925 GameObject* object = NULL, MovingObject* other = NULL, const Vector& other_movement = Vector(0,0))
927 if(!collision::intersects(obj_rect, other_rect))
930 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
932 if(other != NULL && !other->collides(*object, dummy))
934 if(moving_object != NULL && !moving_object->collides(*other, dummy))
937 // calculate intersection
938 float itop = obj_rect.get_bottom() - other_rect.get_top();
939 float ibottom = other_rect.get_bottom() - obj_rect.get_top();
940 float ileft = obj_rect.get_right() - other_rect.get_left();
941 float iright = other_rect.get_right() - obj_rect.get_left();
943 if(fabsf(obj_movement.y) > fabsf(obj_movement.x)) {
944 if(ileft < SHIFT_DELTA) {
945 constraints->constrain_right(other_rect.get_left(), other_movement.x);
947 } else if(iright < SHIFT_DELTA) {
948 constraints->constrain_left(other_rect.get_right(), other_movement.x);
952 // shiftout bottom/top
953 if(itop < SHIFT_DELTA) {
954 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
956 } else if(ibottom < SHIFT_DELTA) {
957 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
962 constraints->ground_movement += other_movement;
964 HitResponse response = other->collision(*object, dummy);
965 if(response == ABORT_MOVE)
968 if(other->get_movement() != Vector(0, 0)) {
969 // TODO what todo when we collide with 2 moving objects?!?
970 constraints->ground_movement = other->get_movement();
974 float vert_penetration = std::min(itop, ibottom);
975 float horiz_penetration = std::min(ileft, iright);
976 if(vert_penetration < horiz_penetration) {
978 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
979 constraints->hit.bottom = true;
981 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
982 constraints->hit.top = true;
986 constraints->constrain_right(other_rect.get_left(), other_movement.x);
987 constraints->hit.right = true;
989 constraints->constrain_left(other_rect.get_right(), other_movement.x);
990 constraints->hit.left = true;
996 Sector::collision_tilemap(collision::Constraints* constraints,
997 const Vector& movement, const Rectf& dest,
998 MovingObject& object) const
1000 // calculate rectangle where the object will move
1001 float x1 = dest.get_left();
1002 float x2 = dest.get_right();
1003 float y1 = dest.get_top();
1004 float y2 = dest.get_bottom();
1006 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1007 TileMap* solids = *i;
1009 // test with all tiles in this rectangle
1010 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1012 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1013 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1014 const Tile* tile = solids->get_tile(x, y);
1017 // skip non-solid tiles
1018 if(!tile->is_solid ())
1020 Rectf tile_bbox = solids->get_tile_bbox(x, y);
1022 /* If the tile is a unisolid tile, the "is_solid()" function above
1023 * didn't do a thorough check. Calculate the position and (relative)
1024 * movement of the object and determine whether or not the tile is
1025 * solid with regard to those parameters. */
1026 if(tile->is_unisolid ()) {
1027 Vector relative_movement = movement
1028 - solids->get_movement(/* actual = */ true);
1030 if (!tile->is_solid (tile_bbox, object.get_bbox(), relative_movement))
1032 } /* if (tile->is_unisolid ()) */
1034 if(tile->is_slope ()) { // slope tile
1035 AATriangle triangle;
1036 int slope_data = tile->getData();
1037 if (solids->get_drawing_effect() & VERTICAL_FLIP)
1038 slope_data = AATriangle::vertical_flip(slope_data);
1039 triangle = AATriangle(tile_bbox, slope_data);
1041 collision::rectangle_aatriangle(constraints, dest, triangle,
1042 solids->get_movement(/* actual = */ false));
1043 } else { // normal rectangular tile
1044 check_collisions(constraints, movement, dest, tile_bbox, NULL, NULL,
1045 solids->get_movement(/* actual = */ false));
1053 Sector::collision_tile_attributes(const Rectf& dest) const
1055 float x1 = dest.p1.x;
1056 float y1 = dest.p1.y;
1057 float x2 = dest.p2.x;
1058 float y2 = dest.p2.y;
1060 uint32_t result = 0;
1061 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1062 TileMap* solids = *i;
1064 // test with all tiles in this rectangle
1065 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1066 // For ice (only), add a little fudge to recognize tiles Tux is standing on.
1067 Rect test_tiles_ice = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2 + SHIFT_DELTA));
1069 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1071 for(y = test_tiles.top; y < test_tiles.bottom; ++y) {
1072 const Tile* tile = solids->get_tile(x, y);
1075 result |= tile->getAttributes();
1077 for(; y < test_tiles_ice.bottom; ++y) {
1078 const Tile* tile = solids->get_tile(x, y);
1081 result |= (tile->getAttributes() & Tile::ICE);
1089 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1090 static void get_hit_normal(const Rectf& r1, const Rectf& r2, CollisionHit& hit,
1093 float itop = r1.get_bottom() - r2.get_top();
1094 float ibottom = r2.get_bottom() - r1.get_top();
1095 float ileft = r1.get_right() - r2.get_left();
1096 float iright = r2.get_right() - r1.get_left();
1098 float vert_penetration = std::min(itop, ibottom);
1099 float horiz_penetration = std::min(ileft, iright);
1100 if(vert_penetration < horiz_penetration) {
1101 if(itop < ibottom) {
1103 normal.y = vert_penetration;
1106 normal.y = -vert_penetration;
1109 if(ileft < iright) {
1111 normal.x = horiz_penetration;
1114 normal.x = -horiz_penetration;
1120 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1122 using namespace collision;
1124 const Rectf& r1 = object1->dest;
1125 const Rectf& r2 = object2->dest;
1128 if(intersects(object1->dest, object2->dest)) {
1130 get_hit_normal(r1, r2, hit, normal);
1132 if(!object1->collides(*object2, hit))
1134 std::swap(hit.left, hit.right);
1135 std::swap(hit.top, hit.bottom);
1136 if(!object2->collides(*object1, hit))
1138 std::swap(hit.left, hit.right);
1139 std::swap(hit.top, hit.bottom);
1141 HitResponse response1 = object1->collision(*object2, hit);
1142 std::swap(hit.left, hit.right);
1143 std::swap(hit.top, hit.bottom);
1144 HitResponse response2 = object2->collision(*object1, hit);
1145 if(response1 == CONTINUE && response2 == CONTINUE) {
1146 normal *= (0.5 + DELTA);
1147 object1->dest.move(-normal);
1148 object2->dest.move(normal);
1149 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1150 normal *= (1 + DELTA);
1151 object1->dest.move(-normal);
1152 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1153 normal *= (1 + DELTA);
1154 object2->dest.move(normal);
1160 Sector::collision_static(collision::Constraints* constraints,
1161 const Vector& movement, const Rectf& dest,
1162 MovingObject& object)
1164 collision_tilemap(constraints, movement, dest, object);
1166 // collision with other (static) objects
1167 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1168 MovingObject* moving_object = *i;
1169 if(moving_object->get_group() != COLGROUP_STATIC
1170 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1172 if(!moving_object->is_valid())
1175 if(moving_object != &object)
1176 check_collisions(constraints, movement, dest, moving_object->bbox,
1177 &object, moving_object);
1182 Sector::collision_static_constrains(MovingObject& object)
1184 using namespace collision;
1185 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1187 Constraints constraints;
1188 Vector movement = object.get_movement();
1189 Rectf& dest = object.dest;
1191 for(int i = 0; i < 2; ++i) {
1192 collision_static(&constraints, Vector(0, movement.y), dest, object);
1193 if(!constraints.has_constraints())
1196 // apply calculated horizontal constraints
1197 if(constraints.get_position_bottom() < infinity) {
1198 float height = constraints.get_height ();
1199 if(height < object.get_bbox().get_height()) {
1200 // we're crushed, but ignore this for now, we'll get this again
1201 // later if we're really crushed or things will solve itself when
1202 // looking at the vertical constraints
1204 dest.p2.y = constraints.get_position_bottom() - DELTA;
1205 dest.p1.y = dest.p2.y - object.get_bbox().get_height();
1206 } else if(constraints.get_position_top() > -infinity) {
1207 dest.p1.y = constraints.get_position_top() + DELTA;
1208 dest.p2.y = dest.p1.y + object.get_bbox().get_height();
1211 if(constraints.has_constraints()) {
1212 if(constraints.hit.bottom) {
1213 dest.move(constraints.ground_movement);
1215 if(constraints.hit.top || constraints.hit.bottom) {
1216 constraints.hit.left = false;
1217 constraints.hit.right = false;
1218 object.collision_solid(constraints.hit);
1222 constraints = Constraints();
1223 for(int i = 0; i < 2; ++i) {
1224 collision_static(&constraints, movement, dest, object);
1225 if(!constraints.has_constraints())
1228 // apply calculated vertical constraints
1229 float width = constraints.get_width ();
1230 if(width < infinity) {
1231 if(width + SHIFT_DELTA < object.get_bbox().get_width()) {
1233 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1234 constraints.get_position_left(), constraints.get_position_right());
1240 object.collision_solid(h);
1242 float xmid = constraints.get_x_midpoint ();
1243 dest.p1.x = xmid - object.get_bbox().get_width()/2;
1244 dest.p2.x = xmid + object.get_bbox().get_width()/2;
1246 } else if(constraints.get_position_right() < infinity) {
1247 dest.p2.x = constraints.get_position_right() - DELTA;
1248 dest.p1.x = dest.p2.x - object.get_bbox().get_width();
1249 } else if(constraints.get_position_left() > -infinity) {
1250 dest.p1.x = constraints.get_position_left() + DELTA;
1251 dest.p2.x = dest.p1.x + object.get_bbox().get_width();
1255 if(constraints.has_constraints()) {
1256 if( constraints.hit.left || constraints.hit.right
1257 || constraints.hit.top || constraints.hit.bottom
1258 || constraints.hit.crush )
1259 object.collision_solid(constraints.hit);
1262 // an extra pass to make sure we're not crushed horizontally
1263 constraints = Constraints();
1264 collision_static(&constraints, movement, dest, object);
1265 if(constraints.get_position_bottom() < infinity) {
1266 float height = constraints.get_height ();
1267 if(height + SHIFT_DELTA < object.get_bbox().get_height()) {
1269 printf("Object %p crushed vertically...\n", &object);
1275 object.collision_solid(h);
1281 const float MAX_SPEED = 16.0f;
1285 Sector::handle_collisions()
1287 using namespace collision;
1289 // calculate destination positions of the objects
1290 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1291 MovingObject* moving_object = *i;
1292 Vector mov = moving_object->get_movement();
1294 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1295 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1296 moving_object->movement = mov.unit() * MAX_SPEED;
1297 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1300 moving_object->dest = moving_object->get_bbox();
1301 moving_object->dest.move(moving_object->get_movement());
1304 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1305 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1306 MovingObject* moving_object = *i;
1307 if((moving_object->get_group() != COLGROUP_MOVING
1308 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1309 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1310 || !moving_object->is_valid())
1313 collision_static_constrains(*moving_object);
1316 // part2: COLGROUP_MOVING vs tile attributes
1317 for(auto i = moving_objects.begin(); 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->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1322 || !moving_object->is_valid())
1325 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1326 if(tile_attributes >= Tile::FIRST_INTERESTING_FLAG) {
1327 moving_object->collision_tile(tile_attributes);
1331 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1332 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1333 MovingObject* moving_object = *i;
1334 if((moving_object->get_group() != COLGROUP_MOVING
1335 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1336 || !moving_object->is_valid())
1339 for(auto i2 = moving_objects.begin(); i2 != moving_objects.end(); ++i2) {
1340 MovingObject* moving_object_2 = *i2;
1341 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1342 || !moving_object_2->is_valid())
1345 if(intersects(moving_object->dest, moving_object_2->dest)) {
1348 get_hit_normal(moving_object->dest, moving_object_2->dest,
1350 if(!moving_object->collides(*moving_object_2, hit))
1352 if(!moving_object_2->collides(*moving_object, hit))
1355 moving_object->collision(*moving_object_2, hit);
1356 moving_object_2->collision(*moving_object, hit);
1361 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1362 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1363 MovingObject* moving_object = *i;
1365 if((moving_object->get_group() != COLGROUP_MOVING
1366 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1367 || !moving_object->is_valid())
1370 for(auto i2 = i+1; i2 != moving_objects.end(); ++i2) {
1371 MovingObject* moving_object_2 = *i2;
1372 if((moving_object_2->get_group() != COLGROUP_MOVING
1373 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1374 || !moving_object_2->is_valid())
1377 collision_object(moving_object, moving_object_2);
1381 // apply object movement
1382 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1383 MovingObject* moving_object = *i;
1385 moving_object->bbox = moving_object->dest;
1386 moving_object->movement = Vector(0, 0);
1391 Sector::is_free_of_tiles(const Rectf& rect, const bool ignoreUnisolid) const
1393 using namespace collision;
1395 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1396 TileMap* solids = *i;
1398 // test with all tiles in this rectangle
1399 Rect test_tiles = solids->get_tiles_overlapping(rect);
1401 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1402 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1403 const Tile* tile = solids->get_tile(x, y);
1405 if(!(tile->getAttributes() & Tile::SOLID))
1407 if(tile->is_unisolid () && ignoreUnisolid)
1409 if(tile->is_slope ()) {
1410 AATriangle triangle;
1411 Rectf tbbox = solids->get_tile_bbox(x, y);
1412 triangle = AATriangle(tbbox, tile->getData());
1413 Constraints constraints;
1414 if(!collision::rectangle_aatriangle(&constraints, rect, triangle))
1417 // We have a solid tile that overlaps the given rectangle.
1427 Sector::is_free_of_statics(const Rectf& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1429 using namespace collision;
1431 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1433 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1434 const MovingObject* moving_object = *i;
1435 if (moving_object == ignore_object) continue;
1436 if (!moving_object->is_valid()) continue;
1437 if (moving_object->get_group() == COLGROUP_STATIC) {
1438 if(intersects(rect, moving_object->get_bbox())) return false;
1446 Sector::is_free_of_movingstatics(const Rectf& rect, const MovingObject* ignore_object) const
1448 using namespace collision;
1450 if (!is_free_of_tiles(rect)) return false;
1452 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1453 const MovingObject* moving_object = *i;
1454 if (moving_object == ignore_object) continue;
1455 if (!moving_object->is_valid()) continue;
1456 if ((moving_object->get_group() == COLGROUP_MOVING)
1457 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1458 || (moving_object->get_group() == COLGROUP_STATIC)) {
1459 if(intersects(rect, moving_object->get_bbox())) return false;
1467 Sector::add_smoke_cloud(const Vector& pos)
1469 add_object(std::make_shared<SmokeCloud>(pos));
1474 Sector::play_music(MusicType type)
1476 currentmusic = type;
1477 switch(currentmusic) {
1479 SoundManager::current()->play_music(music);
1482 SoundManager::current()->play_music("music/invincible.ogg");
1484 case HERRING_WARNING_MUSIC:
1485 SoundManager::current()->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1488 SoundManager::current()->play_music("");
1494 Sector::get_music_type()
1496 return currentmusic;
1500 Sector::get_total_badguys()
1502 int total_badguys = 0;
1503 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
1504 BadGuy* badguy = dynamic_cast<BadGuy*>(i->get());
1505 if (badguy && badguy->countMe)
1509 return total_badguys;
1513 Sector::inside(const Rectf& rect) const
1515 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1516 TileMap* solids = *i;
1518 Rectf bbox = solids->get_bbox();
1519 bbox.p1.y = -INFINITY; // pretend the tilemap extends infinitely far upwards
1521 if (bbox.contains(rect))
1528 Sector::get_width() const
1531 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1532 TileMap* solids = *i;
1533 width = std::max(width, solids->get_bbox().get_right());
1540 Sector::get_height() const
1543 for(auto i = solid_tilemaps.begin();
1544 i != solid_tilemaps.end(); i++) {
1545 TileMap* solids = *i;
1546 height = std::max(height, solids->get_bbox().get_bottom());
1553 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1555 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1556 TileMap* solids = *i;
1557 solids->change_all(old_tile_id, new_tile_id);
1562 Sector::set_ambient_light(float red, float green, float blue)
1564 ambient_light.red = red;
1565 ambient_light.green = green;
1566 ambient_light.blue = blue;
1570 Sector::get_ambient_red()
1572 return ambient_light.red;
1576 Sector::get_ambient_green()
1578 return ambient_light.green;
1582 Sector::get_ambient_blue()
1584 return ambient_light.blue;
1588 Sector::set_gravity(float gravity_)
1590 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1591 this->gravity = gravity_;
1595 Sector::get_gravity() const
1601 Sector::get_nearest_player (const Vector& pos)
1603 Player *nearest_player = NULL;
1604 float nearest_dist = std::numeric_limits<float>::max();
1606 std::vector<Player*> players = Sector::current()->get_players();
1607 for (auto playerIter = players.begin(); playerIter != players.end(); ++playerIter)
1609 Player *this_player = *playerIter;
1610 if (this_player->is_dying() || this_player->is_dead())
1613 float this_dist = this_player->get_bbox ().distance(pos);
1615 if (this_dist < nearest_dist) {
1616 nearest_player = this_player;
1617 nearest_dist = this_dist;
1621 return nearest_player;
1622 } /* Player *get_nearest_player */
1624 std::vector<MovingObject*>
1625 Sector::get_nearby_objects (const Vector& center, float max_distance)
1627 std::vector<MovingObject*> ret;
1628 std::vector<Player*> players = Sector::current()->get_players();
1630 for (size_t i = 0; i < players.size (); i++) {
1631 float distance = players[i]->get_bbox ().distance (center);
1632 if (distance <= max_distance)
1633 ret.push_back (players[i]);
1636 for (size_t i = 0; i < moving_objects.size (); i++) {
1637 float distance = moving_objects[i]->get_bbox ().distance (center);
1638 if (distance <= max_distance)
1639 ret.push_back (moving_objects[i]);
1645 /* vim: set sw=2 sts=2 et : */