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;
122 catch(const std::exception& err)
124 log_warning << err.what() << std::endl;
128 for(auto i = scripts.begin(); i != scripts.end(); ++i) {
129 HSQOBJECT& object = *i;
130 sq_release(global_vm, &object);
132 sq_release(global_vm, §or_table);
133 sq_collectgarbage(global_vm);
135 update_game_objects();
136 assert(gameobjects_new.size() == 0);
138 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
139 GameObjectPtr object = *i;
140 before_object_remove(object);
151 Sector::parse_object(const std::string& name_, const Reader& reader)
153 if(name_ == "camera") {
154 auto camera_ = std::make_shared<Camera>(this, "Camera");
155 camera_->parse(reader);
157 } else if(name_ == "particles-snow") {
158 auto partsys = std::make_shared<SnowParticleSystem>();
159 partsys->parse(reader);
161 } else if(name_ == "particles-rain") {
162 auto partsys = std::make_shared<RainParticleSystem>();
163 partsys->parse(reader);
165 } else if(name_ == "particles-comets") {
166 auto partsys = std::make_shared<CometParticleSystem>();
167 partsys->parse(reader);
169 } else if(name_ == "particles-ghosts") {
170 auto partsys = std::make_shared<GhostParticleSystem>();
171 partsys->parse(reader);
173 } else if(name_ == "particles-clouds") {
174 auto partsys = std::make_shared<CloudParticleSystem>();
175 partsys->parse(reader);
177 } else if(name_ == "money") { // for compatibility with old maps
178 return std::make_shared<Jumpy>(reader);
181 return ObjectFactory::instance().create(name_, reader);
182 } catch(std::exception& e) {
183 log_warning << e.what() << "" << std::endl;
190 Sector::parse(const Reader& sector)
192 bool has_background = false;
193 lisp::ListIterator iter(§or);
195 const std::string& token = iter.item();
196 if(token == "name") {
197 iter.value()->get(name);
198 } else if(token == "gravity") {
199 iter.value()->get(gravity);
200 } else if(token == "music") {
201 iter.value()->get(music);
202 } else if(token == "spawnpoint") {
203 auto sp = std::make_shared<SpawnPoint>(*iter.lisp());
204 spawnpoints.push_back(sp);
205 } else if(token == "init-script") {
206 iter.value()->get(init_script);
207 } else if(token == "ambient-light") {
208 std::vector<float> vColor;
209 sector.get( "ambient-light", vColor );
210 if(vColor.size() < 3) {
211 log_warning << "(ambient-light) requires a color as argument" << std::endl;
213 ambient_light = Color( vColor );
216 GameObjectPtr object = parse_object(token, *(iter.lisp()));
218 if(std::dynamic_pointer_cast<Background>(object)) {
219 has_background = true;
220 } else if(std::dynamic_pointer_cast<Gradient>(object)) {
221 has_background = true;
228 if(!has_background) {
229 auto gradient = std::make_shared<Gradient>();
230 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
231 add_object(gradient);
234 update_game_objects();
236 if(solid_tilemaps.empty()) { log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl; }
240 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
241 update_game_objects();
242 add_object(std::make_shared<Camera>(this, "Camera"));
245 update_game_objects();
246 foremost_layer = calculate_foremost_layer();
250 Sector::parse_old_format(const Reader& reader)
253 reader.get("gravity", gravity);
255 std::string backgroundimage;
256 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
257 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
258 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
259 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
260 backgroundimage = "images/background/" + backgroundimage;
261 if (!PHYSFS_exists(backgroundimage.c_str())) {
262 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
263 backgroundimage = "";
268 reader.get("bkgd_speed", bgspeed);
271 Color bkgd_top, bkgd_bottom;
272 int r = 0, g = 0, b = 128;
273 reader.get("bkgd_red_top", r);
274 reader.get("bkgd_green_top", g);
275 reader.get("bkgd_blue_top", b);
276 bkgd_top.red = static_cast<float> (r) / 255.0f;
277 bkgd_top.green = static_cast<float> (g) / 255.0f;
278 bkgd_top.blue = static_cast<float> (b) / 255.0f;
280 reader.get("bkgd_red_bottom", r);
281 reader.get("bkgd_green_bottom", g);
282 reader.get("bkgd_blue_bottom", b);
283 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
284 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
285 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
287 if(backgroundimage != "") {
288 auto background = std::make_shared<Background>();
289 background->set_image(backgroundimage, bgspeed);
290 add_object(background);
292 auto gradient = std::make_shared<Gradient>();
293 gradient->set_gradient(bkgd_top, bkgd_bottom);
294 add_object(gradient);
297 std::string particlesystem;
298 reader.get("particle_system", particlesystem);
299 if(particlesystem == "clouds")
300 add_object(std::make_shared<CloudParticleSystem>());
301 else if(particlesystem == "snow")
302 add_object(std::make_shared<SnowParticleSystem>());
303 else if(particlesystem == "rain")
304 add_object(std::make_shared<RainParticleSystem>());
306 Vector startpos(100, 170);
307 reader.get("start_pos_x", startpos.x);
308 reader.get("start_pos_y", startpos.y);
310 auto spawn = std::make_shared<SpawnPoint>();
311 spawn->pos = startpos;
312 spawn->name = "main";
313 spawnpoints.push_back(spawn);
315 music = "chipdisko.ogg";
316 // skip reading music filename. It's all .ogg now, anyway
318 reader.get("music", music);
320 music = "music/" + music;
322 int width = 30, height = 15;
323 reader.get("width", width);
324 reader.get("height", height);
326 std::vector<unsigned int> tiles;
327 if(reader.get("interactive-tm", tiles)
328 || reader.get("tilemap", tiles)) {
329 auto tilemap = std::make_shared<TileMap>(level->get_tileset());
330 tilemap->set(width, height, tiles, LAYER_TILES, true);
332 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
333 for(size_t x=0; x < tilemap->get_width(); ++x) {
334 for(size_t y=0; y < tilemap->get_height(); ++y) {
335 uint32_t id = tilemap->get_tile_id(x, y);
337 tilemap->change(x, y, 1311);
341 if (height < 19) tilemap->resize(width, 19);
345 if(reader.get("background-tm", tiles)) {
346 auto tilemap = std::make_shared<TileMap>(level->get_tileset());
347 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
348 if (height < 19) tilemap->resize(width, 19);
352 if(reader.get("foreground-tm", tiles)) {
353 auto tilemap = std::make_shared<TileMap>(level->get_tileset());
354 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
356 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
357 if (height < 19) tilemap->resize(width, 19, 2035);
362 // read reset-points (now spawn-points)
363 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
365 lisp::ListIterator iter(resetpoints);
367 if(iter.item() == "point") {
369 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
371 auto sp = std::make_shared<SpawnPoint>();
374 spawnpoints.push_back(sp);
377 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
383 const lisp::Lisp* objects = reader.get_lisp("objects");
385 lisp::ListIterator iter(objects);
387 auto object = parse_object(iter.item(), *(iter.lisp()));
391 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
397 auto camera_ = std::make_shared<Camera>(this, "Camera");
400 update_game_objects();
402 if(solid_tilemaps.empty()) { log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl; }
405 update_game_objects();
409 Sector::fix_old_tiles()
411 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
412 TileMap* solids = *i;
413 for(size_t x=0; x < solids->get_width(); ++x) {
414 for(size_t y=0; y < solids->get_height(); ++y) {
415 uint32_t id = solids->get_tile_id(x, y);
416 const Tile *tile = solids->get_tile(x, y);
417 Vector pos = solids->get_tile_position(x, y);
420 add_object(std::make_shared<InvisibleBlock>(pos));
421 solids->change(x, y, 0);
422 } else if(tile->getAttributes() & Tile::COIN) {
423 add_object(std::make_shared<Coin>(pos, solids));
424 solids->change(x, y, 0);
425 } else if(tile->getAttributes() & Tile::FULLBOX) {
426 add_object(std::make_shared<BonusBlock>(pos, tile->getData()));
427 solids->change(x, y, 0);
428 } else if(tile->getAttributes() & Tile::BRICK) {
429 if( ( id == 3159 ) || ( id == 3160 ) ){
430 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brickWeb.sprite") );
431 } else if( ( id == 78 ) || ( id == 105 ) ){
432 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brickIce.sprite") );
433 } else if( ( id == 77 ) || ( id == 104 ) ){
434 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
436 log_warning << "attribute 'brick #t' is not supported for tile-id " << id << std::endl;
437 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
439 solids->change(x, y, 0);
440 } else if(tile->getAttributes() & Tile::GOAL) {
441 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
442 add_object(std::make_shared<SequenceTrigger>(pos, sequence));
443 solids->change(x, y, 0);
449 // add lights for special tiles
450 for(auto i = gameobjects.begin(); i != gameobjects.end(); i++) {
451 TileMap* tm = dynamic_cast<TileMap*>(i->get());
453 for(size_t x=0; x < tm->get_width(); ++x) {
454 for(size_t y=0; y < tm->get_height(); ++y) {
455 uint32_t id = tm->get_tile_id(x, y);
456 Vector pos = tm->get_tile_position(x, y);
457 Vector center = pos + Vector(16, 16);
461 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
462 add_object(std::make_shared<PulsingLight>(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
465 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
466 // space lights a bit
467 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
468 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
469 || ((x % 3 == 0) && (y % 3 == 0))) {
470 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
471 add_object(std::make_shared<PulsingLight>(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
482 Sector::run_script(std::istream& in, const std::string& sourcename)
484 using namespace scripting;
486 // garbage collect thread list
487 for(auto i = scripts.begin(); i != scripts.end(); ) {
488 HSQOBJECT& object = *i;
489 HSQUIRRELVM vm = object_to_vm(object);
491 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
492 sq_release(global_vm, &object);
493 i = scripts.erase(i);
500 HSQOBJECT object = create_thread(global_vm);
501 scripts.push_back(object);
503 HSQUIRRELVM vm = object_to_vm(object);
505 // set sector_table as roottable for the thread
506 sq_pushobject(vm, sector_table);
510 compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
511 } catch(std::exception& e) {
512 log_warning << "Error running script: " << e.what() << std::endl;
519 Sector::add_object(GameObjectPtr object)
521 // make sure the object isn't already in the list
523 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
524 assert(*i != object);
526 for(auto i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i) {
527 assert(*i != object);
531 gameobjects_new.push_back(object);
535 Sector::activate(const std::string& spawnpoint)
537 std::shared_ptr<SpawnPoint> sp;
538 for(auto i = spawnpoints.begin(); i != spawnpoints.end(); ++i) {
539 if((*i)->name == spawnpoint) {
545 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
546 if(spawnpoint != "main") {
549 activate(Vector(0, 0));
557 Sector::activate(const Vector& player_pos)
559 if(_current != this) {
561 _current->deactivate();
564 // register sectortable as sector in scripting
565 HSQUIRRELVM vm = scripting::global_vm;
566 sq_pushroottable(vm);
567 sq_pushstring(vm, "sector", -1);
568 sq_pushobject(vm, sector_table);
569 if(SQ_FAILED(sq_createslot(vm, -3)))
570 throw scripting::SquirrelError(vm, "Couldn't set sector in roottable");
573 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
574 GameObjectPtr object = *i;
582 // two-player hack: move other players to main player's position
583 // Maybe specify 2 spawnpoints in the level?
584 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
585 Player* p = dynamic_cast<Player*>(i->get());
588 // spawn smalltux below spawnpoint
590 p->move(player_pos + Vector(0,32));
595 // spawning tux in the ground would kill him
596 if(!is_free_of_tiles(p->get_bbox())) {
597 std::string current_level = "[" + Sector::current()->get_level()->filename + "] ";
598 log_warning << current_level << "Tried spawning Tux in solid matter. Compensating." << std::endl;
599 Vector npos = p->get_bbox().p1;
605 //FIXME: This is a really dirty workaround for this strange camera jump
606 player->move(player->get_pos()+Vector(-32, 0));
607 camera->reset(player->get_pos());
609 player->move(player->get_pos()+(Vector(32, 0)));
612 update_game_objects();
614 //Run default.nut just before init script
615 //Check to see if it's in a levelset (info file)
616 std::string basedir = FileSystem::dirname(get_level()->filename);
617 if(PHYSFS_exists((basedir + "/info").c_str())) {
619 IFileStreambuf ins(basedir + "/default.nut");
620 std::istream in(&ins);
621 run_script(in, "default.nut");
622 } catch(std::exception& ) {
623 // doesn't exist or erroneous; do nothing
628 if(init_script != "") {
629 std::istringstream in(init_script);
630 run_script(in, "init-script");
640 // remove sector entry from global vm
641 HSQUIRRELVM vm = scripting::global_vm;
642 sq_pushroottable(vm);
643 sq_pushstring(vm, "sector", -1);
644 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
645 throw scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
648 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
649 GameObjectPtr object = *i;
651 try_unexpose(object);
659 Sector::get_active_region()
662 camera->get_translation() - Vector(1600, 1200),
663 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
667 Sector::calculate_foremost_layer()
669 int layer = LAYER_BACKGROUND0;
670 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
672 TileMap* tm = dynamic_cast<TileMap*>(i->get());
674 if(tm->get_layer() > layer)
676 if( (tm->get_alpha() < 1.0) )
678 layer = tm->get_layer() - 1;
682 layer = tm->get_layer() + 1;
686 log_debug << "Calculated baduy falling layer was: " << layer << std::endl;
691 Sector::get_foremost_layer()
693 return foremost_layer;
697 Sector::update(float elapsed_time)
699 player->check_bounds();
702 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
703 GameObjectPtr& object = *i;
704 if(!object->is_valid())
707 object->update(elapsed_time);
710 /* Handle all possible collisions. */
712 update_game_objects();
716 Sector::update_game_objects()
718 /** cleanup marked objects */
719 for(auto i = gameobjects.begin();
720 i != gameobjects.end(); /* nothing */) {
721 GameObjectPtr& object = *i;
723 if(object->is_valid()) {
728 before_object_remove(object);
730 i = gameobjects.erase(i);
733 /* add newly created objects */
734 for(auto i = gameobjects_new.begin();
735 i != gameobjects_new.end(); ++i)
737 GameObjectPtr object = *i;
739 before_object_add(object);
741 gameobjects.push_back(object);
743 gameobjects_new.clear();
745 /* update solid_tilemaps list */
746 //FIXME: this could be more efficient
747 solid_tilemaps.clear();
748 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
750 TileMap* tm = dynamic_cast<TileMap*>(i->get());
752 if (tm->is_solid()) solid_tilemaps.push_back(tm);
758 Sector::before_object_add(GameObjectPtr object)
760 auto bullet = dynamic_cast<Bullet*>(object.get());
763 bullets.push_back(bullet);
766 auto movingobject = dynamic_cast<MovingObject*>(object.get());
769 moving_objects.push_back(movingobject);
772 auto portable = dynamic_cast<Portable*>(object.get());
775 portables.push_back(portable);
778 auto tilemap = dynamic_cast<TileMap*>(object.get());
779 if(tilemap && tilemap->is_solid()) {
780 solid_tilemaps.push_back(tilemap);
783 auto camera_ = dynamic_cast<Camera*>(object.get());
785 if(this->camera != 0) {
786 log_warning << "Multiple cameras added. Ignoring" << std::endl;
789 this->camera = camera_;
792 auto player_ = dynamic_cast<Player*>(object.get());
794 if(this->player != 0) {
795 log_warning << "Multiple players added. Ignoring" << std::endl;
798 this->player = player_;
801 auto effect_ = dynamic_cast<DisplayEffect*>(object.get());
803 if(this->effect != 0) {
804 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
807 this->effect = effect_;
810 if(_current == this) {
818 Sector::try_expose(GameObjectPtr object)
820 ScriptInterface* object_ = dynamic_cast<ScriptInterface*>(object.get());
821 if(object_ != NULL) {
822 HSQUIRRELVM vm = scripting::global_vm;
823 sq_pushobject(vm, sector_table);
824 object_->expose(vm, -1);
830 Sector::try_expose_me()
832 HSQUIRRELVM vm = scripting::global_vm;
833 sq_pushobject(vm, sector_table);
834 scripting::SSector* this_ = static_cast<scripting::SSector*>(this);
835 expose_object(vm, -1, this_, "settings", false);
840 Sector::before_object_remove(GameObjectPtr object)
842 Portable* portable = dynamic_cast<Portable*>(object.get());
844 portables.erase(std::find(portables.begin(), portables.end(), portable));
846 Bullet* bullet = dynamic_cast<Bullet*>(object.get());
848 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
850 MovingObject* moving_object = dynamic_cast<MovingObject*>(object.get());
852 moving_objects.erase(
853 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
857 try_unexpose(object);
861 Sector::try_unexpose(GameObjectPtr object)
863 ScriptInterface* object_ = dynamic_cast<ScriptInterface*>(object.get());
864 if(object_ != NULL) {
865 HSQUIRRELVM vm = scripting::global_vm;
866 SQInteger oldtop = sq_gettop(vm);
867 sq_pushobject(vm, sector_table);
869 object_->unexpose(vm, -1);
870 } catch(std::exception& e) {
871 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
873 sq_settop(vm, oldtop);
878 Sector::try_unexpose_me()
880 HSQUIRRELVM vm = scripting::global_vm;
881 SQInteger oldtop = sq_gettop(vm);
882 sq_pushobject(vm, sector_table);
884 scripting::unexpose_object(vm, -1, "settings");
885 } catch(std::exception& e) {
886 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
888 sq_settop(vm, oldtop);
891 Sector::draw(DrawingContext& context)
893 context.set_ambient_color( ambient_light );
894 context.push_transform();
895 context.set_translation(camera->get_translation());
897 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
898 GameObjectPtr& object = *i;
899 if(!object->is_valid())
902 if (draw_solids_only)
904 TileMap* tm = dynamic_cast<TileMap*>(object.get());
905 if (tm && !tm->is_solid())
909 object->draw(context);
913 Color color(1.0f, 0.0f, 0.0f, 0.75f);
914 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
915 MovingObject* object = *i;
916 const Rectf& rect = object->get_bbox();
918 context.draw_filled_rect(rect, color, LAYER_FOREGROUND1 + 10);
922 context.pop_transform();
925 /*-------------------------------------------------------------------------
926 * Collision Detection
927 *-------------------------------------------------------------------------*/
929 /** r1 is supposed to be moving, r2 a solid object */
930 void check_collisions(collision::Constraints* constraints,
931 const Vector& obj_movement, const Rectf& obj_rect, const Rectf& other_rect,
932 GameObject* object = NULL, MovingObject* other = NULL, const Vector& other_movement = Vector(0,0))
934 if(!collision::intersects(obj_rect, other_rect))
937 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
939 if(other != NULL && !other->collides(*object, dummy))
941 if(moving_object != NULL && !moving_object->collides(*other, dummy))
944 // calculate intersection
945 float itop = obj_rect.get_bottom() - other_rect.get_top();
946 float ibottom = other_rect.get_bottom() - obj_rect.get_top();
947 float ileft = obj_rect.get_right() - other_rect.get_left();
948 float iright = other_rect.get_right() - obj_rect.get_left();
950 if(fabsf(obj_movement.y) > fabsf(obj_movement.x)) {
951 if(ileft < SHIFT_DELTA) {
952 constraints->constrain_right(other_rect.get_left(), other_movement.x);
954 } else if(iright < SHIFT_DELTA) {
955 constraints->constrain_left(other_rect.get_right(), other_movement.x);
959 // shiftout bottom/top
960 if(itop < SHIFT_DELTA) {
961 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
963 } else if(ibottom < SHIFT_DELTA) {
964 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
969 constraints->ground_movement += other_movement;
971 HitResponse response = other->collision(*object, dummy);
972 if(response == ABORT_MOVE)
975 if(other->get_movement() != Vector(0, 0)) {
976 // TODO what todo when we collide with 2 moving objects?!?
977 constraints->ground_movement = other->get_movement();
981 float vert_penetration = std::min(itop, ibottom);
982 float horiz_penetration = std::min(ileft, iright);
983 if(vert_penetration < horiz_penetration) {
985 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
986 constraints->hit.bottom = true;
988 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
989 constraints->hit.top = true;
993 constraints->constrain_right(other_rect.get_left(), other_movement.x);
994 constraints->hit.right = true;
996 constraints->constrain_left(other_rect.get_right(), other_movement.x);
997 constraints->hit.left = true;
1003 Sector::collision_tilemap(collision::Constraints* constraints,
1004 const Vector& movement, const Rectf& dest,
1005 MovingObject& object) const
1007 // calculate rectangle where the object will move
1008 float x1 = dest.get_left();
1009 float x2 = dest.get_right();
1010 float y1 = dest.get_top();
1011 float y2 = dest.get_bottom();
1013 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1014 TileMap* solids = *i;
1016 // test with all tiles in this rectangle
1017 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1019 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1020 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1021 const Tile* tile = solids->get_tile(x, y);
1024 // skip non-solid tiles
1025 if(!tile->is_solid ())
1027 Rectf tile_bbox = solids->get_tile_bbox(x, y);
1029 /* If the tile is a unisolid tile, the "is_solid()" function above
1030 * didn't do a thorough check. Calculate the position and (relative)
1031 * movement of the object and determine whether or not the tile is
1032 * solid with regard to those parameters. */
1033 if(tile->is_unisolid ()) {
1034 Vector relative_movement = movement
1035 - solids->get_movement(/* actual = */ true);
1037 if (!tile->is_solid (tile_bbox, object.get_bbox(), relative_movement))
1039 } /* if (tile->is_unisolid ()) */
1041 if(tile->is_slope ()) { // slope tile
1042 AATriangle triangle;
1043 int slope_data = tile->getData();
1044 if (solids->get_drawing_effect() & VERTICAL_FLIP)
1045 slope_data = AATriangle::vertical_flip(slope_data);
1046 triangle = AATriangle(tile_bbox, slope_data);
1048 collision::rectangle_aatriangle(constraints, dest, triangle,
1049 solids->get_movement(/* actual = */ false));
1050 } else { // normal rectangular tile
1051 check_collisions(constraints, movement, dest, tile_bbox, NULL, NULL,
1052 solids->get_movement(/* actual = */ false));
1060 Sector::collision_tile_attributes(const Rectf& dest) const
1062 float x1 = dest.p1.x;
1063 float y1 = dest.p1.y;
1064 float x2 = dest.p2.x;
1065 float y2 = dest.p2.y;
1067 uint32_t result = 0;
1068 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1069 TileMap* solids = *i;
1071 // test with all tiles in this rectangle
1072 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1073 // For ice (only), add a little fudge to recognize tiles Tux is standing on.
1074 Rect test_tiles_ice = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2 + SHIFT_DELTA));
1076 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1078 for(y = test_tiles.top; y < test_tiles.bottom; ++y) {
1079 const Tile* tile = solids->get_tile(x, y);
1082 result |= tile->getAttributes();
1084 for(; y < test_tiles_ice.bottom; ++y) {
1085 const Tile* tile = solids->get_tile(x, y);
1088 result |= (tile->getAttributes() & Tile::ICE);
1096 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1097 static void get_hit_normal(const Rectf& r1, const Rectf& r2, CollisionHit& hit,
1100 float itop = r1.get_bottom() - r2.get_top();
1101 float ibottom = r2.get_bottom() - r1.get_top();
1102 float ileft = r1.get_right() - r2.get_left();
1103 float iright = r2.get_right() - r1.get_left();
1105 float vert_penetration = std::min(itop, ibottom);
1106 float horiz_penetration = std::min(ileft, iright);
1107 if(vert_penetration < horiz_penetration) {
1108 if(itop < ibottom) {
1110 normal.y = vert_penetration;
1113 normal.y = -vert_penetration;
1116 if(ileft < iright) {
1118 normal.x = horiz_penetration;
1121 normal.x = -horiz_penetration;
1127 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1129 using namespace collision;
1131 const Rectf& r1 = object1->dest;
1132 const Rectf& r2 = object2->dest;
1135 if(intersects(object1->dest, object2->dest)) {
1137 get_hit_normal(r1, r2, hit, normal);
1139 if(!object1->collides(*object2, hit))
1141 std::swap(hit.left, hit.right);
1142 std::swap(hit.top, hit.bottom);
1143 if(!object2->collides(*object1, hit))
1145 std::swap(hit.left, hit.right);
1146 std::swap(hit.top, hit.bottom);
1148 HitResponse response1 = object1->collision(*object2, hit);
1149 std::swap(hit.left, hit.right);
1150 std::swap(hit.top, hit.bottom);
1151 HitResponse response2 = object2->collision(*object1, hit);
1152 if(response1 == CONTINUE && response2 == CONTINUE) {
1153 normal *= (0.5 + DELTA);
1154 object1->dest.move(-normal);
1155 object2->dest.move(normal);
1156 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1157 normal *= (1 + DELTA);
1158 object1->dest.move(-normal);
1159 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1160 normal *= (1 + DELTA);
1161 object2->dest.move(normal);
1167 Sector::collision_static(collision::Constraints* constraints,
1168 const Vector& movement, const Rectf& dest,
1169 MovingObject& object)
1171 collision_tilemap(constraints, movement, dest, object);
1173 // collision with other (static) objects
1174 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1175 MovingObject* moving_object = *i;
1176 if(moving_object->get_group() != COLGROUP_STATIC
1177 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1179 if(!moving_object->is_valid())
1182 if(moving_object != &object)
1183 check_collisions(constraints, movement, dest, moving_object->bbox,
1184 &object, moving_object);
1189 Sector::collision_static_constrains(MovingObject& object)
1191 using namespace collision;
1192 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1194 Constraints constraints;
1195 Vector movement = object.get_movement();
1196 Rectf& dest = object.dest;
1198 for(int i = 0; i < 2; ++i) {
1199 collision_static(&constraints, Vector(0, movement.y), dest, object);
1200 if(!constraints.has_constraints())
1203 // apply calculated horizontal constraints
1204 if(constraints.get_position_bottom() < infinity) {
1205 float height = constraints.get_height ();
1206 if(height < object.get_bbox().get_height()) {
1207 // we're crushed, but ignore this for now, we'll get this again
1208 // later if we're really crushed or things will solve itself when
1209 // looking at the vertical constraints
1211 dest.p2.y = constraints.get_position_bottom() - DELTA;
1212 dest.p1.y = dest.p2.y - object.get_bbox().get_height();
1213 } else if(constraints.get_position_top() > -infinity) {
1214 dest.p1.y = constraints.get_position_top() + DELTA;
1215 dest.p2.y = dest.p1.y + object.get_bbox().get_height();
1218 if(constraints.has_constraints()) {
1219 if(constraints.hit.bottom) {
1220 dest.move(constraints.ground_movement);
1222 if(constraints.hit.top || constraints.hit.bottom) {
1223 constraints.hit.left = false;
1224 constraints.hit.right = false;
1225 object.collision_solid(constraints.hit);
1229 constraints = Constraints();
1230 for(int i = 0; i < 2; ++i) {
1231 collision_static(&constraints, movement, dest, object);
1232 if(!constraints.has_constraints())
1235 // apply calculated vertical constraints
1236 float width = constraints.get_width ();
1237 if(width < infinity) {
1238 if(width + SHIFT_DELTA < object.get_bbox().get_width()) {
1240 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1241 constraints.get_position_left(), constraints.get_position_right());
1247 object.collision_solid(h);
1249 float xmid = constraints.get_x_midpoint ();
1250 dest.p1.x = xmid - object.get_bbox().get_width()/2;
1251 dest.p2.x = xmid + object.get_bbox().get_width()/2;
1253 } else if(constraints.get_position_right() < infinity) {
1254 dest.p2.x = constraints.get_position_right() - DELTA;
1255 dest.p1.x = dest.p2.x - object.get_bbox().get_width();
1256 } else if(constraints.get_position_left() > -infinity) {
1257 dest.p1.x = constraints.get_position_left() + DELTA;
1258 dest.p2.x = dest.p1.x + object.get_bbox().get_width();
1262 if(constraints.has_constraints()) {
1263 if( constraints.hit.left || constraints.hit.right
1264 || constraints.hit.top || constraints.hit.bottom
1265 || constraints.hit.crush )
1266 object.collision_solid(constraints.hit);
1269 // an extra pass to make sure we're not crushed horizontally
1270 constraints = Constraints();
1271 collision_static(&constraints, movement, dest, object);
1272 if(constraints.get_position_bottom() < infinity) {
1273 float height = constraints.get_height ();
1274 if(height + SHIFT_DELTA < object.get_bbox().get_height()) {
1276 printf("Object %p crushed vertically...\n", &object);
1282 object.collision_solid(h);
1288 const float MAX_SPEED = 16.0f;
1292 Sector::handle_collisions()
1294 using namespace collision;
1296 // calculate destination positions of the objects
1297 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1298 MovingObject* moving_object = *i;
1299 Vector mov = moving_object->get_movement();
1301 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1302 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1303 moving_object->movement = mov.unit() * MAX_SPEED;
1304 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1307 moving_object->dest = moving_object->get_bbox();
1308 moving_object->dest.move(moving_object->get_movement());
1311 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1312 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1313 MovingObject* moving_object = *i;
1314 if((moving_object->get_group() != COLGROUP_MOVING
1315 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1316 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1317 || !moving_object->is_valid())
1320 collision_static_constrains(*moving_object);
1323 // part2: COLGROUP_MOVING vs tile attributes
1324 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1325 MovingObject* moving_object = *i;
1326 if((moving_object->get_group() != COLGROUP_MOVING
1327 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1328 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1329 || !moving_object->is_valid())
1332 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1333 if(tile_attributes >= Tile::FIRST_INTERESTING_FLAG) {
1334 moving_object->collision_tile(tile_attributes);
1338 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1339 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1340 MovingObject* moving_object = *i;
1341 if((moving_object->get_group() != COLGROUP_MOVING
1342 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1343 || !moving_object->is_valid())
1346 for(auto i2 = moving_objects.begin(); i2 != moving_objects.end(); ++i2) {
1347 MovingObject* moving_object_2 = *i2;
1348 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1349 || !moving_object_2->is_valid())
1352 if(intersects(moving_object->dest, moving_object_2->dest)) {
1355 get_hit_normal(moving_object->dest, moving_object_2->dest,
1357 if(!moving_object->collides(*moving_object_2, hit))
1359 if(!moving_object_2->collides(*moving_object, hit))
1362 moving_object->collision(*moving_object_2, hit);
1363 moving_object_2->collision(*moving_object, hit);
1368 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1369 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1370 MovingObject* moving_object = *i;
1372 if((moving_object->get_group() != COLGROUP_MOVING
1373 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1374 || !moving_object->is_valid())
1377 for(auto i2 = i+1; i2 != moving_objects.end(); ++i2) {
1378 MovingObject* moving_object_2 = *i2;
1379 if((moving_object_2->get_group() != COLGROUP_MOVING
1380 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1381 || !moving_object_2->is_valid())
1384 collision_object(moving_object, moving_object_2);
1388 // apply object movement
1389 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1390 MovingObject* moving_object = *i;
1392 moving_object->bbox = moving_object->dest;
1393 moving_object->movement = Vector(0, 0);
1398 Sector::is_free_of_tiles(const Rectf& rect, const bool ignoreUnisolid) const
1400 using namespace collision;
1402 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1403 TileMap* solids = *i;
1405 // test with all tiles in this rectangle
1406 Rect test_tiles = solids->get_tiles_overlapping(rect);
1408 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1409 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1410 const Tile* tile = solids->get_tile(x, y);
1412 if(!(tile->getAttributes() & Tile::SOLID))
1414 if(tile->is_unisolid () && ignoreUnisolid)
1416 if(tile->is_slope ()) {
1417 AATriangle triangle;
1418 Rectf tbbox = solids->get_tile_bbox(x, y);
1419 triangle = AATriangle(tbbox, tile->getData());
1420 Constraints constraints;
1421 if(!collision::rectangle_aatriangle(&constraints, rect, triangle))
1424 // We have a solid tile that overlaps the given rectangle.
1434 Sector::is_free_of_statics(const Rectf& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1436 using namespace collision;
1438 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1440 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1441 const MovingObject* moving_object = *i;
1442 if (moving_object == ignore_object) continue;
1443 if (!moving_object->is_valid()) continue;
1444 if (moving_object->get_group() == COLGROUP_STATIC) {
1445 if(intersects(rect, moving_object->get_bbox())) return false;
1453 Sector::is_free_of_movingstatics(const Rectf& rect, const MovingObject* ignore_object) const
1455 using namespace collision;
1457 if (!is_free_of_tiles(rect)) return false;
1459 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1460 const MovingObject* moving_object = *i;
1461 if (moving_object == ignore_object) continue;
1462 if (!moving_object->is_valid()) continue;
1463 if ((moving_object->get_group() == COLGROUP_MOVING)
1464 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1465 || (moving_object->get_group() == COLGROUP_STATIC)) {
1466 if(intersects(rect, moving_object->get_bbox())) return false;
1474 Sector::add_smoke_cloud(const Vector& pos)
1476 add_object(std::make_shared<SmokeCloud>(pos));
1481 Sector::play_music(MusicType type)
1483 currentmusic = type;
1484 switch(currentmusic) {
1486 SoundManager::current()->play_music(music);
1489 SoundManager::current()->play_music("music/invincible.ogg");
1491 case HERRING_WARNING_MUSIC:
1492 SoundManager::current()->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1495 SoundManager::current()->play_music("");
1501 Sector::resume_music()
1503 SoundManager::current()->resume_music(1.5f);
1507 Sector::get_music_type()
1509 return currentmusic;
1513 Sector::get_total_badguys()
1515 int total_badguys = 0;
1516 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
1517 BadGuy* badguy = dynamic_cast<BadGuy*>(i->get());
1518 if (badguy && badguy->countMe)
1522 return total_badguys;
1526 Sector::inside(const Rectf& rect) const
1528 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1529 TileMap* solids = *i;
1531 Rectf bbox = solids->get_bbox();
1532 bbox.p1.y = -INFINITY; // pretend the tilemap extends infinitely far upwards
1534 if (bbox.contains(rect))
1541 Sector::get_width() const
1544 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1545 TileMap* solids = *i;
1546 width = std::max(width, solids->get_bbox().get_right());
1553 Sector::get_height() const
1556 for(auto i = solid_tilemaps.begin();
1557 i != solid_tilemaps.end(); i++) {
1558 TileMap* solids = *i;
1559 height = std::max(height, solids->get_bbox().get_bottom());
1566 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1568 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1569 TileMap* solids = *i;
1570 solids->change_all(old_tile_id, new_tile_id);
1575 Sector::set_ambient_light(float red, float green, float blue)
1577 ambient_light.red = red;
1578 ambient_light.green = green;
1579 ambient_light.blue = blue;
1583 Sector::get_ambient_red()
1585 return ambient_light.red;
1589 Sector::get_ambient_green()
1591 return ambient_light.green;
1595 Sector::get_ambient_blue()
1597 return ambient_light.blue;
1601 Sector::set_gravity(float gravity_)
1603 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1604 this->gravity = gravity_;
1608 Sector::get_gravity() const
1614 Sector::get_nearest_player (const Vector& pos)
1616 Player *nearest_player = NULL;
1617 float nearest_dist = std::numeric_limits<float>::max();
1619 std::vector<Player*> players = Sector::current()->get_players();
1620 for (auto playerIter = players.begin(); playerIter != players.end(); ++playerIter)
1622 Player *this_player = *playerIter;
1623 if (this_player->is_dying() || this_player->is_dead())
1626 float this_dist = this_player->get_bbox ().distance(pos);
1628 if (this_dist < nearest_dist) {
1629 nearest_player = this_player;
1630 nearest_dist = this_dist;
1634 return nearest_player;
1635 } /* Player *get_nearest_player */
1637 std::vector<MovingObject*>
1638 Sector::get_nearby_objects (const Vector& center, float max_distance)
1640 std::vector<MovingObject*> ret;
1641 std::vector<Player*> players = Sector::current()->get_players();
1643 for (size_t i = 0; i < players.size (); i++) {
1644 float distance = players[i]->get_bbox ().distance (center);
1645 if (distance <= max_distance)
1646 ret.push_back (players[i]);
1649 for (size_t i = 0; i < moving_objects.size (); i++) {
1650 float distance = moving_objects[i]->get_bbox ().distance (center);
1651 if (distance <= max_distance)
1652 ret.push_back (moving_objects[i]);
1658 /* vim: set sw=2 sts=2 et : */