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 ),
91 add_object(std::make_shared<Player>(GameSession::current()->get_savegame().get_player_status(), "Tux"));
92 add_object(std::make_shared<DisplayEffect>("Effect"));
93 add_object(std::make_shared<TextObject>("Text"));
95 SoundManager::current()->preload("sounds/shoot.wav");
97 // create a new squirrel table for the sector
98 using namespace scripting;
100 sq_collectgarbage(global_vm);
102 sq_newtable(global_vm);
103 sq_pushroottable(global_vm);
104 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
105 throw scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
107 sq_resetobject(§or_table);
108 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
109 throw scripting::SquirrelError(global_vm, "Couldn't get sector table");
110 sq_addref(global_vm, §or_table);
111 sq_pop(global_vm, 1);
113 foremost_layer = calculate_foremost_layer();
118 using namespace scripting;
122 for(auto i = scripts.begin(); i != scripts.end(); ++i) {
123 HSQOBJECT& object = *i;
124 sq_release(global_vm, &object);
126 sq_release(global_vm, §or_table);
127 sq_collectgarbage(global_vm);
129 update_game_objects();
130 assert(gameobjects_new.size() == 0);
132 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
133 GameObjectPtr object = *i;
134 before_object_remove(object);
145 Sector::parse_object(const std::string& name_, const Reader& reader)
147 if(name_ == "camera") {
148 auto camera_ = std::make_shared<Camera>(this, "Camera");
149 camera_->parse(reader);
151 } else if(name_ == "particles-snow") {
152 auto partsys = std::make_shared<SnowParticleSystem>();
153 partsys->parse(reader);
155 } else if(name_ == "particles-rain") {
156 auto partsys = std::make_shared<RainParticleSystem>();
157 partsys->parse(reader);
159 } else if(name_ == "particles-comets") {
160 auto partsys = std::make_shared<CometParticleSystem>();
161 partsys->parse(reader);
163 } else if(name_ == "particles-ghosts") {
164 auto partsys = std::make_shared<GhostParticleSystem>();
165 partsys->parse(reader);
167 } else if(name_ == "particles-clouds") {
168 auto partsys = std::make_shared<CloudParticleSystem>();
169 partsys->parse(reader);
171 } else if(name_ == "money") { // for compatibility with old maps
172 return std::make_shared<Jumpy>(reader);
175 return ObjectFactory::instance().create(name_, reader);
176 } catch(std::exception& e) {
177 log_warning << e.what() << "" << std::endl;
184 Sector::parse(const Reader& sector)
186 bool has_background = false;
187 lisp::ListIterator iter(§or);
189 const std::string& token = iter.item();
190 if(token == "name") {
191 iter.value()->get(name);
192 } else if(token == "gravity") {
193 iter.value()->get(gravity);
194 } else if(token == "music") {
195 iter.value()->get(music);
196 } else if(token == "spawnpoint") {
197 auto sp = std::make_shared<SpawnPoint>(*iter.lisp());
198 spawnpoints.push_back(sp);
199 } else if(token == "init-script") {
200 iter.value()->get(init_script);
201 } else if(token == "ambient-light") {
202 std::vector<float> vColor;
203 sector.get( "ambient-light", vColor );
204 if(vColor.size() < 3) {
205 log_warning << "(ambient-light) requires a color as argument" << std::endl;
207 ambient_light = Color( vColor );
210 GameObjectPtr object = parse_object(token, *(iter.lisp()));
212 if(std::dynamic_pointer_cast<Background>(object)) {
213 has_background = true;
214 } else if(std::dynamic_pointer_cast<Gradient>(object)) {
215 has_background = true;
222 if(!has_background) {
223 auto gradient = std::make_shared<Gradient>();
224 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
225 add_object(gradient);
228 update_game_objects();
230 if(solid_tilemaps.size() < 1) { log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl; }
234 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
235 update_game_objects();
236 add_object(std::make_shared<Camera>(this, "Camera"));
239 update_game_objects();
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.size() < 1) { 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 == 78 ) || ( id == 105 ) ){
423 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brickIce.sprite") );
424 } else if( ( id == 77 ) || ( id == 104 ) ){
425 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
427 log_warning << "attribute 'brick #t' is not supported for tile-id " << id << std::endl;
428 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
430 solids->change(x, y, 0);
431 } else if(tile->getAttributes() & Tile::GOAL) {
432 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
433 add_object(std::make_shared<SequenceTrigger>(pos, sequence));
434 solids->change(x, y, 0);
440 // add lights for special tiles
441 for(auto i = gameobjects.begin(); i != gameobjects.end(); i++) {
442 TileMap* tm = dynamic_cast<TileMap*>(i->get());
444 for(size_t x=0; x < tm->get_width(); ++x) {
445 for(size_t y=0; y < tm->get_height(); ++y) {
446 uint32_t id = tm->get_tile_id(x, y);
447 Vector pos = tm->get_tile_position(x, y);
448 Vector center = pos + Vector(16, 16);
452 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
453 add_object(std::make_shared<PulsingLight>(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
456 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
457 // space lights a bit
458 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
459 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
460 || ((x % 3 == 0) && (y % 3 == 0))) {
461 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
462 add_object(std::make_shared<PulsingLight>(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
473 Sector::run_script(std::istream& in, const std::string& sourcename)
475 using namespace scripting;
477 // garbage collect thread list
478 for(auto i = scripts.begin(); i != scripts.end(); ) {
479 HSQOBJECT& object = *i;
480 HSQUIRRELVM vm = object_to_vm(object);
482 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
483 sq_release(global_vm, &object);
484 i = scripts.erase(i);
491 HSQOBJECT object = create_thread(global_vm);
492 scripts.push_back(object);
494 HSQUIRRELVM vm = object_to_vm(object);
496 // set sector_table as roottable for the thread
497 sq_pushobject(vm, sector_table);
501 compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
502 } catch(std::exception& e) {
503 log_warning << "Error running script: " << e.what() << std::endl;
510 Sector::add_object(GameObjectPtr object)
512 // make sure the object isn't already in the list
514 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
515 assert(*i != object);
517 for(auto i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i) {
518 assert(*i != object);
522 gameobjects_new.push_back(object);
526 Sector::activate(const std::string& spawnpoint)
528 std::shared_ptr<SpawnPoint> sp;
529 for(auto i = spawnpoints.begin(); i != spawnpoints.end(); ++i) {
530 if((*i)->name == spawnpoint) {
536 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
537 if(spawnpoint != "main") {
540 activate(Vector(0, 0));
548 Sector::activate(const Vector& player_pos)
550 if(_current != this) {
552 _current->deactivate();
555 // register sectortable as sector in scripting
556 HSQUIRRELVM vm = scripting::global_vm;
557 sq_pushroottable(vm);
558 sq_pushstring(vm, "sector", -1);
559 sq_pushobject(vm, sector_table);
560 if(SQ_FAILED(sq_createslot(vm, -3)))
561 throw scripting::SquirrelError(vm, "Couldn't set sector in roottable");
564 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
565 GameObjectPtr object = *i;
573 // two-player hack: move other players to main player's position
574 // Maybe specify 2 spawnpoints in the level?
575 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
576 Player* p = dynamic_cast<Player*>(i->get());
579 // spawn smalltux below spawnpoint
581 p->move(player_pos + Vector(0,32));
586 // spawning tux in the ground would kill him
587 if(!is_free_of_tiles(p->get_bbox())) {
588 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
589 Vector npos = p->get_bbox().p1;
595 //FIXME: This is a really dirty workaround for this strange camera jump
596 player->move(player->get_pos()+Vector(-32, 0));
597 camera->reset(player->get_pos());
599 player->move(player->get_pos()+(Vector(32, 0)));
602 update_game_objects();
604 //Run default.nut just before init script
605 //Check to see if it's in a levelset (info file)
606 std::string basedir = FileSystem::dirname(get_level()->filename);
607 if(PHYSFS_exists((basedir + "/info").c_str())) {
609 IFileStreambuf ins(basedir + "/default.nut");
610 std::istream in(&ins);
611 run_script(in, "default.nut");
612 } catch(std::exception& ) {
613 // doesn't exist or erroneous; do nothing
618 if(init_script != "") {
619 std::istringstream in(init_script);
620 run_script(in, "init-script");
630 // remove sector entry from global vm
631 HSQUIRRELVM vm = scripting::global_vm;
632 sq_pushroottable(vm);
633 sq_pushstring(vm, "sector", -1);
634 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
635 throw scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
638 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
639 GameObjectPtr object = *i;
641 try_unexpose(object);
649 Sector::get_active_region()
652 camera->get_translation() - Vector(1600, 1200),
653 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
657 Sector::calculate_foremost_layer()
660 std::vector<std::string> secret_area_layers;
661 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
663 SecretAreaTrigger* trigger = dynamic_cast<SecretAreaTrigger*>(i->get());
664 if (!trigger) continue;
665 secret_area_layers.push_back(trigger->get_fade_tilemap_name());
668 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
670 TileMap* tm = dynamic_cast<TileMap*>(i->get());
672 if(tm->get_layer() > foremost_layer)
674 if (std::find(secret_area_layers.begin(), secret_area_layers.end(), tm->get_name())
675 != secret_area_layers.end() || tm->is_solid())
677 layer = tm->get_layer();
685 Sector::get_foremost_layer()
687 return foremost_layer;
691 Sector::update(float elapsed_time)
693 player->check_bounds();
696 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
697 GameObjectPtr& object = *i;
698 if(!object->is_valid())
701 object->update(elapsed_time);
704 /* Handle all possible collisions. */
706 update_game_objects();
710 Sector::update_game_objects()
712 /** cleanup marked objects */
713 for(auto i = gameobjects.begin();
714 i != gameobjects.end(); /* nothing */) {
715 GameObjectPtr& object = *i;
717 if(object->is_valid()) {
722 before_object_remove(object);
724 i = gameobjects.erase(i);
727 /* add newly created objects */
728 for(auto i = gameobjects_new.begin();
729 i != gameobjects_new.end(); ++i)
731 GameObjectPtr object = *i;
733 before_object_add(object);
735 gameobjects.push_back(object);
737 gameobjects_new.clear();
739 /* update solid_tilemaps list */
740 //FIXME: this could be more efficient
741 solid_tilemaps.clear();
742 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
744 TileMap* tm = dynamic_cast<TileMap*>(i->get());
746 if (tm->is_solid()) solid_tilemaps.push_back(tm);
752 Sector::before_object_add(GameObjectPtr object)
754 auto bullet = dynamic_cast<Bullet*>(object.get());
757 bullets.push_back(bullet);
760 auto movingobject = dynamic_cast<MovingObject*>(object.get());
763 moving_objects.push_back(movingobject);
766 auto portable = dynamic_cast<Portable*>(object.get());
769 portables.push_back(portable);
772 auto tilemap = dynamic_cast<TileMap*>(object.get());
773 if(tilemap && tilemap->is_solid()) {
774 solid_tilemaps.push_back(tilemap);
777 auto camera_ = dynamic_cast<Camera*>(object.get());
779 if(this->camera != 0) {
780 log_warning << "Multiple cameras added. Ignoring" << std::endl;
783 this->camera = camera_;
786 auto player_ = dynamic_cast<Player*>(object.get());
788 if(this->player != 0) {
789 log_warning << "Multiple players added. Ignoring" << std::endl;
792 this->player = player_;
795 auto effect_ = dynamic_cast<DisplayEffect*>(object.get());
797 if(this->effect != 0) {
798 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
801 this->effect = effect_;
804 if(_current == this) {
812 Sector::try_expose(GameObjectPtr object)
814 ScriptInterface* object_ = dynamic_cast<ScriptInterface*>(object.get());
815 if(object_ != NULL) {
816 HSQUIRRELVM vm = scripting::global_vm;
817 sq_pushobject(vm, sector_table);
818 object_->expose(vm, -1);
824 Sector::try_expose_me()
826 HSQUIRRELVM vm = scripting::global_vm;
827 sq_pushobject(vm, sector_table);
828 scripting::SSector* this_ = static_cast<scripting::SSector*>(this);
829 expose_object(vm, -1, this_, "settings", false);
834 Sector::before_object_remove(GameObjectPtr object)
836 Portable* portable = dynamic_cast<Portable*>(object.get());
838 portables.erase(std::find(portables.begin(), portables.end(), portable));
840 Bullet* bullet = dynamic_cast<Bullet*>(object.get());
842 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
844 MovingObject* moving_object = dynamic_cast<MovingObject*>(object.get());
846 moving_objects.erase(
847 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
851 try_unexpose(object);
855 Sector::try_unexpose(GameObjectPtr object)
857 ScriptInterface* object_ = dynamic_cast<ScriptInterface*>(object.get());
858 if(object_ != NULL) {
859 HSQUIRRELVM vm = scripting::global_vm;
860 SQInteger oldtop = sq_gettop(vm);
861 sq_pushobject(vm, sector_table);
863 object_->unexpose(vm, -1);
864 } catch(std::exception& e) {
865 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
867 sq_settop(vm, oldtop);
872 Sector::try_unexpose_me()
874 HSQUIRRELVM vm = scripting::global_vm;
875 SQInteger oldtop = sq_gettop(vm);
876 sq_pushobject(vm, sector_table);
878 scripting::unexpose_object(vm, -1, "settings");
879 } catch(std::exception& e) {
880 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
882 sq_settop(vm, oldtop);
885 Sector::draw(DrawingContext& context)
887 context.set_ambient_color( ambient_light );
888 context.push_transform();
889 context.set_translation(camera->get_translation());
891 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
892 GameObjectPtr& object = *i;
893 if(!object->is_valid())
896 if (draw_solids_only)
898 TileMap* tm = dynamic_cast<TileMap*>(object.get());
899 if (tm && !tm->is_solid())
903 object->draw(context);
907 Color color(1.0f, 0.0f, 0.0f, 0.75f);
908 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
909 MovingObject* object = *i;
910 const Rectf& rect = object->get_bbox();
912 context.draw_filled_rect(rect, color, LAYER_FOREGROUND1 + 10);
916 context.pop_transform();
919 /*-------------------------------------------------------------------------
920 * Collision Detection
921 *-------------------------------------------------------------------------*/
923 /** r1 is supposed to be moving, r2 a solid object */
924 void check_collisions(collision::Constraints* constraints,
925 const Vector& obj_movement, const Rectf& obj_rect, const Rectf& other_rect,
926 GameObject* object = NULL, MovingObject* other = NULL, const Vector& other_movement = Vector(0,0))
928 if(!collision::intersects(obj_rect, other_rect))
931 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
933 if(other != NULL && !other->collides(*object, dummy))
935 if(moving_object != NULL && !moving_object->collides(*other, dummy))
938 // calculate intersection
939 float itop = obj_rect.get_bottom() - other_rect.get_top();
940 float ibottom = other_rect.get_bottom() - obj_rect.get_top();
941 float ileft = obj_rect.get_right() - other_rect.get_left();
942 float iright = other_rect.get_right() - obj_rect.get_left();
944 if(fabsf(obj_movement.y) > fabsf(obj_movement.x)) {
945 if(ileft < SHIFT_DELTA) {
946 constraints->constrain_right(other_rect.get_left(), other_movement.x);
948 } else if(iright < SHIFT_DELTA) {
949 constraints->constrain_left(other_rect.get_right(), other_movement.x);
953 // shiftout bottom/top
954 if(itop < SHIFT_DELTA) {
955 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
957 } else if(ibottom < SHIFT_DELTA) {
958 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
963 constraints->ground_movement += other_movement;
965 HitResponse response = other->collision(*object, dummy);
966 if(response == ABORT_MOVE)
969 if(other->get_movement() != Vector(0, 0)) {
970 // TODO what todo when we collide with 2 moving objects?!?
971 constraints->ground_movement = other->get_movement();
975 float vert_penetration = std::min(itop, ibottom);
976 float horiz_penetration = std::min(ileft, iright);
977 if(vert_penetration < horiz_penetration) {
979 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
980 constraints->hit.bottom = true;
982 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
983 constraints->hit.top = true;
987 constraints->constrain_right(other_rect.get_left(), other_movement.x);
988 constraints->hit.right = true;
990 constraints->constrain_left(other_rect.get_right(), other_movement.x);
991 constraints->hit.left = true;
997 Sector::collision_tilemap(collision::Constraints* constraints,
998 const Vector& movement, const Rectf& dest,
999 MovingObject& object) const
1001 // calculate rectangle where the object will move
1002 float x1 = dest.get_left();
1003 float x2 = dest.get_right();
1004 float y1 = dest.get_top();
1005 float y2 = dest.get_bottom();
1007 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1008 TileMap* solids = *i;
1010 // test with all tiles in this rectangle
1011 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1013 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1014 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1015 const Tile* tile = solids->get_tile(x, y);
1018 // skip non-solid tiles
1019 if(!tile->is_solid ())
1021 Rectf tile_bbox = solids->get_tile_bbox(x, y);
1023 /* If the tile is a unisolid tile, the "is_solid()" function above
1024 * didn't do a thorough check. Calculate the position and (relative)
1025 * movement of the object and determine whether or not the tile is
1026 * solid with regard to those parameters. */
1027 if(tile->is_unisolid ()) {
1028 Vector relative_movement = movement
1029 - solids->get_movement(/* actual = */ true);
1031 if (!tile->is_solid (tile_bbox, object.get_bbox(), relative_movement))
1033 } /* if (tile->is_unisolid ()) */
1035 if(tile->is_slope ()) { // slope tile
1036 AATriangle triangle;
1037 int slope_data = tile->getData();
1038 if (solids->get_drawing_effect() & VERTICAL_FLIP)
1039 slope_data = AATriangle::vertical_flip(slope_data);
1040 triangle = AATriangle(tile_bbox, slope_data);
1042 collision::rectangle_aatriangle(constraints, dest, triangle,
1043 solids->get_movement(/* actual = */ false));
1044 } else { // normal rectangular tile
1045 check_collisions(constraints, movement, dest, tile_bbox, NULL, NULL,
1046 solids->get_movement(/* actual = */ false));
1054 Sector::collision_tile_attributes(const Rectf& dest) const
1056 float x1 = dest.p1.x;
1057 float y1 = dest.p1.y;
1058 float x2 = dest.p2.x;
1059 float y2 = dest.p2.y;
1061 uint32_t result = 0;
1062 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1063 TileMap* solids = *i;
1065 // test with all tiles in this rectangle
1066 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1067 // For ice (only), add a little fudge to recognize tiles Tux is standing on.
1068 Rect test_tiles_ice = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2 + SHIFT_DELTA));
1070 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1072 for(y = test_tiles.top; y < test_tiles.bottom; ++y) {
1073 const Tile* tile = solids->get_tile(x, y);
1076 result |= tile->getAttributes();
1078 for(; y < test_tiles_ice.bottom; ++y) {
1079 const Tile* tile = solids->get_tile(x, y);
1082 result |= (tile->getAttributes() & Tile::ICE);
1090 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1091 static void get_hit_normal(const Rectf& r1, const Rectf& r2, CollisionHit& hit,
1094 float itop = r1.get_bottom() - r2.get_top();
1095 float ibottom = r2.get_bottom() - r1.get_top();
1096 float ileft = r1.get_right() - r2.get_left();
1097 float iright = r2.get_right() - r1.get_left();
1099 float vert_penetration = std::min(itop, ibottom);
1100 float horiz_penetration = std::min(ileft, iright);
1101 if(vert_penetration < horiz_penetration) {
1102 if(itop < ibottom) {
1104 normal.y = vert_penetration;
1107 normal.y = -vert_penetration;
1110 if(ileft < iright) {
1112 normal.x = horiz_penetration;
1115 normal.x = -horiz_penetration;
1121 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1123 using namespace collision;
1125 const Rectf& r1 = object1->dest;
1126 const Rectf& r2 = object2->dest;
1129 if(intersects(object1->dest, object2->dest)) {
1131 get_hit_normal(r1, r2, hit, normal);
1133 if(!object1->collides(*object2, hit))
1135 std::swap(hit.left, hit.right);
1136 std::swap(hit.top, hit.bottom);
1137 if(!object2->collides(*object1, hit))
1139 std::swap(hit.left, hit.right);
1140 std::swap(hit.top, hit.bottom);
1142 HitResponse response1 = object1->collision(*object2, hit);
1143 std::swap(hit.left, hit.right);
1144 std::swap(hit.top, hit.bottom);
1145 HitResponse response2 = object2->collision(*object1, hit);
1146 if(response1 == CONTINUE && response2 == CONTINUE) {
1147 normal *= (0.5 + DELTA);
1148 object1->dest.move(-normal);
1149 object2->dest.move(normal);
1150 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1151 normal *= (1 + DELTA);
1152 object1->dest.move(-normal);
1153 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1154 normal *= (1 + DELTA);
1155 object2->dest.move(normal);
1161 Sector::collision_static(collision::Constraints* constraints,
1162 const Vector& movement, const Rectf& dest,
1163 MovingObject& object)
1165 collision_tilemap(constraints, movement, dest, object);
1167 // collision with other (static) objects
1168 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1169 MovingObject* moving_object = *i;
1170 if(moving_object->get_group() != COLGROUP_STATIC
1171 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1173 if(!moving_object->is_valid())
1176 if(moving_object != &object)
1177 check_collisions(constraints, movement, dest, moving_object->bbox,
1178 &object, moving_object);
1183 Sector::collision_static_constrains(MovingObject& object)
1185 using namespace collision;
1186 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1188 Constraints constraints;
1189 Vector movement = object.get_movement();
1190 Rectf& dest = object.dest;
1192 for(int i = 0; i < 2; ++i) {
1193 collision_static(&constraints, Vector(0, movement.y), dest, object);
1194 if(!constraints.has_constraints())
1197 // apply calculated horizontal constraints
1198 if(constraints.get_position_bottom() < infinity) {
1199 float height = constraints.get_height ();
1200 if(height < object.get_bbox().get_height()) {
1201 // we're crushed, but ignore this for now, we'll get this again
1202 // later if we're really crushed or things will solve itself when
1203 // looking at the vertical constraints
1205 dest.p2.y = constraints.get_position_bottom() - DELTA;
1206 dest.p1.y = dest.p2.y - object.get_bbox().get_height();
1207 } else if(constraints.get_position_top() > -infinity) {
1208 dest.p1.y = constraints.get_position_top() + DELTA;
1209 dest.p2.y = dest.p1.y + object.get_bbox().get_height();
1212 if(constraints.has_constraints()) {
1213 if(constraints.hit.bottom) {
1214 dest.move(constraints.ground_movement);
1216 if(constraints.hit.top || constraints.hit.bottom) {
1217 constraints.hit.left = false;
1218 constraints.hit.right = false;
1219 object.collision_solid(constraints.hit);
1223 constraints = Constraints();
1224 for(int i = 0; i < 2; ++i) {
1225 collision_static(&constraints, movement, dest, object);
1226 if(!constraints.has_constraints())
1229 // apply calculated vertical constraints
1230 float width = constraints.get_width ();
1231 if(width < infinity) {
1232 if(width + SHIFT_DELTA < object.get_bbox().get_width()) {
1234 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1235 constraints.get_position_left(), constraints.get_position_right());
1241 object.collision_solid(h);
1243 float xmid = constraints.get_x_midpoint ();
1244 dest.p1.x = xmid - object.get_bbox().get_width()/2;
1245 dest.p2.x = xmid + object.get_bbox().get_width()/2;
1247 } else if(constraints.get_position_right() < infinity) {
1248 dest.p2.x = constraints.get_position_right() - DELTA;
1249 dest.p1.x = dest.p2.x - object.get_bbox().get_width();
1250 } else if(constraints.get_position_left() > -infinity) {
1251 dest.p1.x = constraints.get_position_left() + DELTA;
1252 dest.p2.x = dest.p1.x + object.get_bbox().get_width();
1256 if(constraints.has_constraints()) {
1257 if( constraints.hit.left || constraints.hit.right
1258 || constraints.hit.top || constraints.hit.bottom
1259 || constraints.hit.crush )
1260 object.collision_solid(constraints.hit);
1263 // an extra pass to make sure we're not crushed horizontally
1264 constraints = Constraints();
1265 collision_static(&constraints, movement, dest, object);
1266 if(constraints.get_position_bottom() < infinity) {
1267 float height = constraints.get_height ();
1268 if(height + SHIFT_DELTA < object.get_bbox().get_height()) {
1270 printf("Object %p crushed vertically...\n", &object);
1276 object.collision_solid(h);
1282 const float MAX_SPEED = 16.0f;
1286 Sector::handle_collisions()
1288 using namespace collision;
1290 // calculate destination positions of the objects
1291 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1292 MovingObject* moving_object = *i;
1293 Vector mov = moving_object->get_movement();
1295 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1296 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1297 moving_object->movement = mov.unit() * MAX_SPEED;
1298 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1301 moving_object->dest = moving_object->get_bbox();
1302 moving_object->dest.move(moving_object->get_movement());
1305 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1306 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1307 MovingObject* moving_object = *i;
1308 if((moving_object->get_group() != COLGROUP_MOVING
1309 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1310 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1311 || !moving_object->is_valid())
1314 collision_static_constrains(*moving_object);
1317 // part2: COLGROUP_MOVING vs tile attributes
1318 for(auto i = moving_objects.begin(); 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->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1323 || !moving_object->is_valid())
1326 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1327 if(tile_attributes >= Tile::FIRST_INTERESTING_FLAG) {
1328 moving_object->collision_tile(tile_attributes);
1332 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1333 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1334 MovingObject* moving_object = *i;
1335 if((moving_object->get_group() != COLGROUP_MOVING
1336 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1337 || !moving_object->is_valid())
1340 for(auto i2 = moving_objects.begin(); i2 != moving_objects.end(); ++i2) {
1341 MovingObject* moving_object_2 = *i2;
1342 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1343 || !moving_object_2->is_valid())
1346 if(intersects(moving_object->dest, moving_object_2->dest)) {
1349 get_hit_normal(moving_object->dest, moving_object_2->dest,
1351 if(!moving_object->collides(*moving_object_2, hit))
1353 if(!moving_object_2->collides(*moving_object, hit))
1356 moving_object->collision(*moving_object_2, hit);
1357 moving_object_2->collision(*moving_object, hit);
1362 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1363 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1364 MovingObject* moving_object = *i;
1366 if((moving_object->get_group() != COLGROUP_MOVING
1367 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1368 || !moving_object->is_valid())
1371 for(auto i2 = i+1; i2 != moving_objects.end(); ++i2) {
1372 MovingObject* moving_object_2 = *i2;
1373 if((moving_object_2->get_group() != COLGROUP_MOVING
1374 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1375 || !moving_object_2->is_valid())
1378 collision_object(moving_object, moving_object_2);
1382 // apply object movement
1383 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1384 MovingObject* moving_object = *i;
1386 moving_object->bbox = moving_object->dest;
1387 moving_object->movement = Vector(0, 0);
1392 Sector::is_free_of_tiles(const Rectf& rect, const bool ignoreUnisolid) const
1394 using namespace collision;
1396 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1397 TileMap* solids = *i;
1399 // test with all tiles in this rectangle
1400 Rect test_tiles = solids->get_tiles_overlapping(rect);
1402 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1403 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1404 const Tile* tile = solids->get_tile(x, y);
1406 if(!(tile->getAttributes() & Tile::SOLID))
1408 if(tile->is_unisolid () && ignoreUnisolid)
1410 if(tile->is_slope ()) {
1411 AATriangle triangle;
1412 Rectf tbbox = solids->get_tile_bbox(x, y);
1413 triangle = AATriangle(tbbox, tile->getData());
1414 Constraints constraints;
1415 if(!collision::rectangle_aatriangle(&constraints, rect, triangle))
1418 // We have a solid tile that overlaps the given rectangle.
1428 Sector::is_free_of_statics(const Rectf& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1430 using namespace collision;
1432 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1434 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1435 const MovingObject* moving_object = *i;
1436 if (moving_object == ignore_object) continue;
1437 if (!moving_object->is_valid()) continue;
1438 if (moving_object->get_group() == COLGROUP_STATIC) {
1439 if(intersects(rect, moving_object->get_bbox())) return false;
1447 Sector::is_free_of_movingstatics(const Rectf& rect, const MovingObject* ignore_object) const
1449 using namespace collision;
1451 if (!is_free_of_tiles(rect)) return false;
1453 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1454 const MovingObject* moving_object = *i;
1455 if (moving_object == ignore_object) continue;
1456 if (!moving_object->is_valid()) continue;
1457 if ((moving_object->get_group() == COLGROUP_MOVING)
1458 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1459 || (moving_object->get_group() == COLGROUP_STATIC)) {
1460 if(intersects(rect, moving_object->get_bbox())) return false;
1468 Sector::add_bullet(const Vector& pos, const PlayerStatus* player_status, float xm, Direction dir)
1470 // TODO remove this function and move these checks elsewhere...
1471 if((player_status->bonus == FIRE_BONUS &&
1472 (int)bullets.size() >= player_status->max_fire_bullets) ||
1473 (player_status->bonus == ICE_BONUS &&
1474 (int)bullets.size() >= player_status->max_ice_bullets))
1476 auto new_bullet = std::make_shared<Bullet>(pos, xm, dir, player_status->bonus);
1477 add_object(new_bullet);
1479 SoundManager::current()->play("sounds/shoot.wav");
1485 Sector::add_smoke_cloud(const Vector& pos)
1487 add_object(std::make_shared<SmokeCloud>(pos));
1492 Sector::play_music(MusicType type)
1494 currentmusic = type;
1495 switch(currentmusic) {
1497 SoundManager::current()->play_music(music);
1500 SoundManager::current()->play_music("music/invincible.ogg");
1502 case HERRING_WARNING_MUSIC:
1503 SoundManager::current()->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1506 SoundManager::current()->play_music("");
1512 Sector::get_music_type()
1514 return currentmusic;
1518 Sector::get_total_badguys()
1520 int total_badguys = 0;
1521 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
1522 BadGuy* badguy = dynamic_cast<BadGuy*>(i->get());
1523 if (badguy && badguy->countMe)
1527 return total_badguys;
1531 Sector::inside(const Rectf& rect) const
1533 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1534 TileMap* solids = *i;
1536 Rectf bbox = solids->get_bbox();
1537 bbox.p1.y = -INFINITY; // pretend the tilemap extends infinitely far upwards
1539 if (bbox.contains(rect))
1546 Sector::get_width() const
1549 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1550 TileMap* solids = *i;
1551 width = std::max(width, solids->get_bbox().get_right());
1558 Sector::get_height() const
1561 for(auto i = solid_tilemaps.begin();
1562 i != solid_tilemaps.end(); i++) {
1563 TileMap* solids = *i;
1564 height = std::max(height, solids->get_bbox().get_bottom());
1571 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1573 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1574 TileMap* solids = *i;
1575 solids->change_all(old_tile_id, new_tile_id);
1580 Sector::set_ambient_light(float red, float green, float blue)
1582 ambient_light.red = red;
1583 ambient_light.green = green;
1584 ambient_light.blue = blue;
1588 Sector::get_ambient_red()
1590 return ambient_light.red;
1594 Sector::get_ambient_green()
1596 return ambient_light.green;
1600 Sector::get_ambient_blue()
1602 return ambient_light.blue;
1606 Sector::set_gravity(float gravity_)
1608 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1609 this->gravity = gravity_;
1613 Sector::get_gravity() const
1619 Sector::get_nearest_player (const Vector& pos)
1621 Player *nearest_player = NULL;
1622 float nearest_dist = std::numeric_limits<float>::max();
1624 std::vector<Player*> players = Sector::current()->get_players();
1625 for (auto playerIter = players.begin(); playerIter != players.end(); ++playerIter)
1627 Player *this_player = *playerIter;
1628 if (this_player->is_dying() || this_player->is_dead())
1631 float this_dist = this_player->get_bbox ().distance(pos);
1633 if (this_dist < nearest_dist) {
1634 nearest_player = this_player;
1635 nearest_dist = this_dist;
1639 return nearest_player;
1640 } /* Player *get_nearest_player */
1642 std::vector<MovingObject*>
1643 Sector::get_nearby_objects (const Vector& center, float max_distance)
1645 std::vector<MovingObject*> ret;
1646 std::vector<Player*> players = Sector::current()->get_players();
1648 for (size_t i = 0; i < players.size (); i++) {
1649 float distance = players[i]->get_bbox ().distance (center);
1650 if (distance <= max_distance)
1651 ret.push_back (players[i]);
1654 for (size_t i = 0; i < moving_objects.size (); i++) {
1655 float distance = moving_objects[i]->get_bbox ().distance (center);
1656 if (distance <= max_distance)
1657 ret.push_back (moving_objects[i]);
1663 /* vim: set sw=2 sts=2 et : */