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_stream.hpp"
49 #include "scripting/squirrel_util.hpp"
50 #include "supertux/collision.hpp"
51 #include "supertux/constants.hpp"
52 #include "supertux/game_session.hpp"
53 #include "supertux/globals.hpp"
54 #include "supertux/level.hpp"
55 #include "supertux/object_factory.hpp"
56 #include "supertux/player_status.hpp"
57 #include "supertux/spawn_point.hpp"
58 #include "supertux/tile.hpp"
59 #include "trigger/sequence_trigger.hpp"
60 #include "util/file_system.hpp"
62 Sector* Sector::_current = 0;
64 bool Sector::show_collrects = false;
65 bool Sector::draw_solids_only = false;
67 Sector::Sector(Level* parent) :
73 currentmusic(LEVEL_MUSIC),
76 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ),
88 add_object(new Player(GameSession::current()->get_player_status(), "Tux"));
89 add_object(new DisplayEffect("Effect"));
90 add_object(new TextObject("Text"));
92 sound_manager->preload("sounds/shoot.wav");
94 // create a new squirrel table for the sector
95 using namespace scripting;
97 sq_collectgarbage(global_vm);
99 sq_newtable(global_vm);
100 sq_pushroottable(global_vm);
101 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
102 throw scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
104 sq_resetobject(§or_table);
105 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
106 throw scripting::SquirrelError(global_vm, "Couldn't get sector table");
107 sq_addref(global_vm, §or_table);
108 sq_pop(global_vm, 1);
113 using namespace scripting;
117 for(ScriptList::iterator i = scripts.begin();
118 i != scripts.end(); ++i) {
119 HSQOBJECT& object = *i;
120 sq_release(global_vm, &object);
122 sq_release(global_vm, §or_table);
123 sq_collectgarbage(global_vm);
125 update_game_objects();
126 assert(gameobjects_new.size() == 0);
128 for(GameObjects::iterator i = gameobjects.begin();
129 i != gameobjects.end(); ++i) {
130 GameObject* object = *i;
131 before_object_remove(object);
135 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
147 Sector::parse_object(const std::string& name, const Reader& reader)
149 if(name == "camera") {
150 Camera* camera = new Camera(this, "Camera");
151 camera->parse(reader);
153 } else if(name == "particles-snow") {
154 SnowParticleSystem* partsys = new SnowParticleSystem();
155 partsys->parse(reader);
157 } else if(name == "particles-rain") {
158 RainParticleSystem* partsys = new RainParticleSystem();
159 partsys->parse(reader);
161 } else if(name == "particles-comets") {
162 CometParticleSystem* partsys = new CometParticleSystem();
163 partsys->parse(reader);
165 } else if(name == "particles-ghosts") {
166 GhostParticleSystem* partsys = new GhostParticleSystem();
167 partsys->parse(reader);
169 } else if(name == "particles-clouds") {
170 CloudParticleSystem* partsys = new CloudParticleSystem();
171 partsys->parse(reader);
173 } else if(name == "money") { // for compatibility with old maps
174 return new Jumpy(reader);
177 return ObjectFactory::instance().create(name, reader);
178 } catch(std::exception& e) {
179 log_warning << e.what() << "" << std::endl;
186 Sector::parse(const Reader& sector)
188 bool has_background = false;
189 lisp::ListIterator iter(§or);
191 const std::string& token = iter.item();
192 if(token == "name") {
193 iter.value()->get(name);
194 } else if(token == "gravity") {
195 iter.value()->get(gravity);
196 } else if(token == "music") {
197 iter.value()->get(music);
198 } else if(token == "spawnpoint") {
199 SpawnPoint* sp = new SpawnPoint(*iter.lisp());
200 spawnpoints.push_back(sp);
201 } else if(token == "init-script") {
202 iter.value()->get(init_script);
203 } else if(token == "ambient-light") {
204 std::vector<float> vColor;
205 sector.get( "ambient-light", vColor );
206 if(vColor.size() < 3) {
207 log_warning << "(ambient-light) requires a color as argument" << std::endl;
209 ambient_light = Color( vColor );
212 GameObject* object = parse_object(token, *(iter.lisp()));
214 if(dynamic_cast<Background *>(object)) {
215 has_background = true;
216 } else if(dynamic_cast<Gradient *>(object)) {
217 has_background = true;
224 if(!has_background) {
225 Gradient* gradient = new Gradient();
226 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
227 add_object(gradient);
230 update_game_objects();
232 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
236 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
237 update_game_objects();
238 add_object(new Camera(this, "Camera"));
241 update_game_objects();
245 Sector::parse_old_format(const Reader& reader)
248 reader.get("gravity", gravity);
250 std::string backgroundimage;
251 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
252 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
253 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
254 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
255 backgroundimage = "images/background/" + backgroundimage;
256 if (!PHYSFS_exists(backgroundimage.c_str())) {
257 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
258 backgroundimage = "";
263 reader.get("bkgd_speed", bgspeed);
266 Color bkgd_top, bkgd_bottom;
267 int r = 0, g = 0, b = 128;
268 reader.get("bkgd_red_top", r);
269 reader.get("bkgd_green_top", g);
270 reader.get("bkgd_blue_top", b);
271 bkgd_top.red = static_cast<float> (r) / 255.0f;
272 bkgd_top.green = static_cast<float> (g) / 255.0f;
273 bkgd_top.blue = static_cast<float> (b) / 255.0f;
275 reader.get("bkgd_red_bottom", r);
276 reader.get("bkgd_green_bottom", g);
277 reader.get("bkgd_blue_bottom", b);
278 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
279 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
280 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
282 if(backgroundimage != "") {
283 Background* background = new Background();
284 background->set_image(backgroundimage, bgspeed);
285 add_object(background);
287 Gradient* gradient = new Gradient();
288 gradient->set_gradient(bkgd_top, bkgd_bottom);
289 add_object(gradient);
292 std::string particlesystem;
293 reader.get("particle_system", particlesystem);
294 if(particlesystem == "clouds")
295 add_object(new CloudParticleSystem());
296 else if(particlesystem == "snow")
297 add_object(new SnowParticleSystem());
298 else if(particlesystem == "rain")
299 add_object(new RainParticleSystem());
301 Vector startpos(100, 170);
302 reader.get("start_pos_x", startpos.x);
303 reader.get("start_pos_y", startpos.y);
305 SpawnPoint* spawn = new SpawnPoint;
306 spawn->pos = startpos;
307 spawn->name = "main";
308 spawnpoints.push_back(spawn);
310 music = "chipdisko.ogg";
311 // skip reading music filename. It's all .ogg now, anyway
313 reader.get("music", music);
315 music = "music/" + music;
317 int width = 30, height = 15;
318 reader.get("width", width);
319 reader.get("height", height);
321 std::vector<unsigned int> tiles;
322 if(reader.get("interactive-tm", tiles)
323 || reader.get("tilemap", tiles)) {
324 TileMap* tilemap = new TileMap(level->get_tileset());
325 tilemap->set(width, height, tiles, LAYER_TILES, true);
327 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
328 for(size_t x=0; x < tilemap->get_width(); ++x) {
329 for(size_t y=0; y < tilemap->get_height(); ++y) {
330 uint32_t id = tilemap->get_tile_id(x, y);
332 tilemap->change(x, y, 1311);
336 if (height < 19) tilemap->resize(width, 19);
340 if(reader.get("background-tm", tiles)) {
341 TileMap* tilemap = new TileMap(level->get_tileset());
342 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
343 if (height < 19) tilemap->resize(width, 19);
347 if(reader.get("foreground-tm", tiles)) {
348 TileMap* tilemap = new TileMap(level->get_tileset());
349 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
351 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
352 if (height < 19) tilemap->resize(width, 19, 2035);
357 // read reset-points (now spawn-points)
358 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
360 lisp::ListIterator iter(resetpoints);
362 if(iter.item() == "point") {
364 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
366 SpawnPoint* sp = new SpawnPoint;
369 spawnpoints.push_back(sp);
372 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
378 const lisp::Lisp* objects = reader.get_lisp("objects");
380 lisp::ListIterator iter(objects);
382 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
386 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
392 Camera* camera = new Camera(this, "Camera");
395 update_game_objects();
397 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
400 update_game_objects();
404 Sector::fix_old_tiles()
406 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
407 TileMap* solids = *i;
408 for(size_t x=0; x < solids->get_width(); ++x) {
409 for(size_t y=0; y < solids->get_height(); ++y) {
410 uint32_t id = solids->get_tile_id(x, y);
411 const Tile *tile = solids->get_tile(x, y);
412 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
415 add_object(new InvisibleBlock(pos));
416 solids->change(x, y, 0);
417 } else if(tile->getAttributes() & Tile::COIN) {
418 add_object(new Coin(pos));
419 solids->change(x, y, 0);
420 } else if(tile->getAttributes() & Tile::FULLBOX) {
421 add_object(new BonusBlock(pos, tile->getData()));
422 solids->change(x, y, 0);
423 } else if(tile->getAttributes() & Tile::BRICK) {
424 add_object(new Brick(pos, tile->getData()));
425 solids->change(x, y, 0);
426 } else if(tile->getAttributes() & Tile::GOAL) {
427 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
428 add_object(new SequenceTrigger(pos, sequence));
429 solids->change(x, y, 0);
435 // add lights for special tiles
436 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
437 TileMap* tm = dynamic_cast<TileMap*>(*i);
439 for(size_t x=0; x < tm->get_width(); ++x) {
440 for(size_t y=0; y < tm->get_height(); ++y) {
441 uint32_t id = tm->get_tile_id(x, y);
442 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
443 Vector center(pos.x + 16, pos.y + 16);
447 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
448 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
451 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
452 // space lights a bit
453 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
454 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
455 || ((x % 3 == 0) && (y % 3 == 0))) {
456 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
457 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
468 Sector::run_script(std::istream& in, const std::string& sourcename)
470 using namespace scripting;
472 // garbage collect thread list
473 for(ScriptList::iterator i = scripts.begin();
474 i != scripts.end(); ) {
475 HSQOBJECT& object = *i;
476 HSQUIRRELVM vm = object_to_vm(object);
478 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
479 sq_release(global_vm, &object);
480 i = scripts.erase(i);
487 HSQOBJECT object = create_thread(global_vm);
488 scripts.push_back(object);
490 HSQUIRRELVM vm = object_to_vm(object);
492 // set sector_table as roottable for the thread
493 sq_pushobject(vm, sector_table);
497 compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
498 } catch(std::exception& e) {
499 log_warning << "Error running script: " << e.what() << std::endl;
506 Sector::add_object(GameObject* object)
508 // make sure the object isn't already in the list
510 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
513 assert("object already added to sector" == 0);
516 for(GameObjects::iterator i = gameobjects_new.begin();
517 i != gameobjects_new.end(); ++i) {
519 assert("object already added to sector" == 0);
525 gameobjects_new.push_back(object);
529 Sector::activate(const std::string& spawnpoint)
532 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
534 if((*i)->name == spawnpoint) {
540 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
541 if(spawnpoint != "main") {
544 activate(Vector(0, 0));
552 Sector::activate(const Vector& player_pos)
554 if(_current != this) {
556 _current->deactivate();
559 // register sectortable as sector in scripting
560 HSQUIRRELVM vm = scripting::global_vm;
561 sq_pushroottable(vm);
562 sq_pushstring(vm, "sector", -1);
563 sq_pushobject(vm, sector_table);
564 if(SQ_FAILED(sq_createslot(vm, -3)))
565 throw scripting::SquirrelError(vm, "Couldn't set sector in roottable");
568 for(GameObjects::iterator i = gameobjects.begin();
569 i != gameobjects.end(); ++i) {
570 GameObject* object = *i;
577 // spawn smalltux below spawnpoint
578 if (!player->is_big()) {
579 player->move(player_pos + Vector(0,32));
581 player->move(player_pos);
584 // spawning tux in the ground would kill him
585 if(!is_free_of_tiles(player->get_bbox())) {
586 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
587 Vector npos = player->get_bbox().p1;
592 camera->reset(player->get_pos());
593 update_game_objects();
595 //Run default.nut just before init script
596 //Check to see if it's in a levelset (info file)
597 std::string basedir = FileSystem::dirname(get_level()->filename);
598 if(PHYSFS_exists((basedir + "/info").c_str())) {
600 IFileStream in(basedir + "/default.nut");
601 run_script(in, "default.nut");
602 } catch(std::exception& ) {
603 // doesn't exist or erroneous; do nothing
608 if(init_script != "") {
609 std::istringstream in(init_script);
610 run_script(in, "init-script");
620 // remove sector entry from global vm
621 HSQUIRRELVM vm = scripting::global_vm;
622 sq_pushroottable(vm);
623 sq_pushstring(vm, "sector", -1);
624 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
625 throw scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
628 for(GameObjects::iterator i = gameobjects.begin();
629 i != gameobjects.end(); ++i) {
630 GameObject* object = *i;
632 try_unexpose(object);
640 Sector::get_active_region()
643 camera->get_translation() - Vector(1600, 1200),
644 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
648 Sector::update(float elapsed_time)
650 player->check_bounds(camera);
653 for(GameObjects::iterator i = gameobjects.begin();
654 i != gameobjects.end(); ++i) {
655 GameObject* object = *i;
656 if(!object->is_valid())
659 object->update(elapsed_time);
662 /* Handle all possible collisions. */
664 update_game_objects();
668 Sector::update_game_objects()
670 /** cleanup marked objects */
671 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
672 i != gameobjects.end(); /* nothing */) {
673 GameObject* object = *i;
675 if(object->is_valid()) {
680 before_object_remove(object);
683 i = gameobjects.erase(i);
686 /* add newly created objects */
687 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
688 i != gameobjects_new.end(); ++i)
690 GameObject* object = *i;
692 before_object_add(object);
694 gameobjects.push_back(object);
696 gameobjects_new.clear();
698 /* update solid_tilemaps list */
699 //FIXME: this could be more efficient
700 solid_tilemaps.clear();
701 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
702 i != gameobjects.end(); ++i)
704 TileMap* tm = dynamic_cast<TileMap*>(*i);
706 if (tm->is_solid()) solid_tilemaps.push_back(tm);
712 Sector::before_object_add(GameObject* object)
714 Bullet* bullet = dynamic_cast<Bullet*> (object);
716 bullets.push_back(bullet);
719 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
720 if(movingobject != NULL) {
721 moving_objects.push_back(movingobject);
724 Portable* portable = dynamic_cast<Portable*> (object);
725 if(portable != NULL) {
726 portables.push_back(portable);
729 TileMap* tilemap = dynamic_cast<TileMap*> (object);
730 if(tilemap != NULL && tilemap->is_solid()) {
731 solid_tilemaps.push_back(tilemap);
734 Camera* camera = dynamic_cast<Camera*> (object);
736 if(this->camera != 0) {
737 log_warning << "Multiple cameras added. Ignoring" << std::endl;
740 this->camera = camera;
743 Player* player = dynamic_cast<Player*> (object);
745 if(this->player != 0) {
746 log_warning << "Multiple players added. Ignoring" << std::endl;
749 this->player = player;
752 DisplayEffect* effect = dynamic_cast<DisplayEffect*> (object);
754 if(this->effect != 0) {
755 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
758 this->effect = effect;
761 if(_current == this) {
769 Sector::try_expose(GameObject* object)
771 ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
772 if(object_ != NULL) {
773 HSQUIRRELVM vm = scripting::global_vm;
774 sq_pushobject(vm, sector_table);
775 object_->expose(vm, -1);
781 Sector::try_expose_me()
783 HSQUIRRELVM vm = scripting::global_vm;
784 sq_pushobject(vm, sector_table);
785 scripting::SSector* this_ = static_cast<scripting::SSector*> (this);
786 expose_object(vm, -1, this_, "settings", false);
791 Sector::before_object_remove(GameObject* object)
793 Portable* portable = dynamic_cast<Portable*> (object);
794 if(portable != NULL) {
795 portables.erase(std::find(portables.begin(), portables.end(), portable));
797 Bullet* bullet = dynamic_cast<Bullet*> (object);
799 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
801 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
802 if(moving_object != NULL) {
803 moving_objects.erase(
804 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
808 try_unexpose(object);
812 Sector::try_unexpose(GameObject* object)
814 ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
815 if(object_ != NULL) {
816 HSQUIRRELVM vm = scripting::global_vm;
817 SQInteger oldtop = sq_gettop(vm);
818 sq_pushobject(vm, sector_table);
820 object_->unexpose(vm, -1);
821 } catch(std::exception& e) {
822 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
824 sq_settop(vm, oldtop);
829 Sector::try_unexpose_me()
831 HSQUIRRELVM vm = scripting::global_vm;
832 SQInteger oldtop = sq_gettop(vm);
833 sq_pushobject(vm, sector_table);
835 scripting::unexpose_object(vm, -1, "settings");
836 } catch(std::exception& e) {
837 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
839 sq_settop(vm, oldtop);
842 Sector::draw(DrawingContext& context)
844 context.set_ambient_color( ambient_light );
845 context.push_transform();
846 context.set_translation(camera->get_translation());
848 for(GameObjects::iterator i = gameobjects.begin();
849 i != gameobjects.end(); ++i) {
850 GameObject* object = *i;
851 if(!object->is_valid())
854 if (draw_solids_only)
856 TileMap* tm = dynamic_cast<TileMap*>(object);
857 if (tm && !tm->is_solid())
861 object->draw(context);
865 Color col(0.2f, 0.2f, 0.2f, 0.7f);
866 for(MovingObjects::iterator i = moving_objects.begin();
867 i != moving_objects.end(); ++i) {
868 MovingObject* object = *i;
869 const Rectf& rect = object->get_bbox();
871 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
875 context.pop_transform();
878 /*-------------------------------------------------------------------------
879 * Collision Detection
880 *-------------------------------------------------------------------------*/
882 /** r1 is supposed to be moving, r2 a solid object */
883 void check_collisions(collision::Constraints* constraints,
884 const Vector& movement, const Rectf& r1, const Rectf& r2,
885 GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
887 if(!collision::intersects(r1, r2))
890 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
892 if(other != NULL && !other->collides(*object, dummy))
894 if(moving_object != NULL && !moving_object->collides(*other, dummy))
897 // calculate intersection
898 float itop = r1.get_bottom() - r2.get_top();
899 float ibottom = r2.get_bottom() - r1.get_top();
900 float ileft = r1.get_right() - r2.get_left();
901 float iright = r2.get_right() - r1.get_left();
903 if(fabsf(movement.y) > fabsf(movement.x)) {
904 if(ileft < SHIFT_DELTA) {
905 constraints->right = std::min(constraints->right, r2.get_left());
907 } else if(iright < SHIFT_DELTA) {
908 constraints->left = std::max(constraints->left, r2.get_right());
912 // shiftout bottom/top
913 if(itop < SHIFT_DELTA) {
914 constraints->bottom = std::min(constraints->bottom, r2.get_top());
916 } else if(ibottom < SHIFT_DELTA) {
917 constraints->top = std::max(constraints->top, r2.get_bottom());
922 constraints->ground_movement += addl_ground_movement;
924 HitResponse response = other->collision(*object, dummy);
925 if(response == ABORT_MOVE)
928 if(other->get_movement() != Vector(0, 0)) {
929 // TODO what todo when we collide with 2 moving objects?!?
930 constraints->ground_movement = other->get_movement();
934 float vert_penetration = std::min(itop, ibottom);
935 float horiz_penetration = std::min(ileft, iright);
936 if(vert_penetration < horiz_penetration) {
938 constraints->bottom = std::min(constraints->bottom, r2.get_top());
939 constraints->hit.bottom = true;
941 constraints->top = std::max(constraints->top, r2.get_bottom());
942 constraints->hit.top = true;
946 constraints->right = std::min(constraints->right, r2.get_left());
947 constraints->hit.right = true;
949 constraints->left = std::max(constraints->left, r2.get_right());
950 constraints->hit.left = true;
956 Sector::collision_tilemap(collision::Constraints* constraints,
957 const Vector& movement, const Rectf& dest) const
959 // calculate rectangle where the object will move
960 float x1 = dest.get_left();
961 float x2 = dest.get_right();
962 float y1 = dest.get_top();
963 float y2 = dest.get_bottom();
965 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
966 TileMap* solids = *i;
968 // test with all tiles in this rectangle
969 int starttilex = int(x1 - solids->get_x_offset()) / 32;
970 int starttiley = int(y1 - solids->get_y_offset()) / 32;
971 int max_x = int(x2 - solids->get_x_offset());
972 int max_y = int(y2+1 - solids->get_y_offset());
974 for(int x = starttilex; x*32 < max_x; ++x) {
975 for(int y = starttiley; y*32 < max_y; ++y) {
976 const Tile* tile = solids->get_tile(x, y);
979 // skip non-solid tiles
980 if((tile->getAttributes() & Tile::SOLID) == 0)
982 // only handle unisolid when the player is falling down and when he was
983 // above the tile before
984 if(tile->getAttributes() & Tile::UNISOLID) {
985 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
989 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
991 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
992 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
993 triangle = AATriangle(p1, p2, tile->getData());
995 collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
996 } else { // normal rectangular tile
997 Rectf rect(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset(), (x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
998 check_collisions(constraints, movement, dest, rect, NULL, NULL, solids->get_movement());
1006 Sector::collision_tile_attributes(const Rectf& dest) const
1008 float x1 = dest.p1.x;
1009 float y1 = dest.p1.y;
1010 float x2 = dest.p2.x;
1011 float y2 = dest.p2.y + SHIFT_DELTA;
1013 uint32_t result = 0;
1014 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1015 TileMap* solids = *i;
1017 // test with all tiles in this rectangle
1018 int starttilex = int(x1 - solids->get_x_offset()) / 32;
1019 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1020 int max_x = int(x2 - solids->get_x_offset());
1021 int max_y = int(y2+1 - solids->get_y_offset());
1023 for(int x = starttilex; x*32 < max_x; ++x) {
1024 for(int y = starttiley; y*32 < max_y; ++y) {
1025 const Tile* tile = solids->get_tile(x, y);
1028 result |= tile->getAttributes();
1036 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1037 static void get_hit_normal(const Rectf& r1, const Rectf& r2, CollisionHit& hit,
1040 float itop = r1.get_bottom() - r2.get_top();
1041 float ibottom = r2.get_bottom() - r1.get_top();
1042 float ileft = r1.get_right() - r2.get_left();
1043 float iright = r2.get_right() - r1.get_left();
1045 float vert_penetration = std::min(itop, ibottom);
1046 float horiz_penetration = std::min(ileft, iright);
1047 if(vert_penetration < horiz_penetration) {
1048 if(itop < ibottom) {
1050 normal.y = vert_penetration;
1053 normal.y = -vert_penetration;
1056 if(ileft < iright) {
1058 normal.x = horiz_penetration;
1061 normal.x = -horiz_penetration;
1067 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1069 using namespace collision;
1071 const Rectf& r1 = object1->dest;
1072 const Rectf& r2 = object2->dest;
1075 if(intersects(object1->dest, object2->dest)) {
1077 get_hit_normal(r1, r2, hit, normal);
1079 if(!object1->collides(*object2, hit))
1081 std::swap(hit.left, hit.right);
1082 std::swap(hit.top, hit.bottom);
1083 if(!object2->collides(*object1, hit))
1085 std::swap(hit.left, hit.right);
1086 std::swap(hit.top, hit.bottom);
1088 HitResponse response1 = object1->collision(*object2, hit);
1089 std::swap(hit.left, hit.right);
1090 std::swap(hit.top, hit.bottom);
1091 HitResponse response2 = object2->collision(*object1, hit);
1092 if(response1 == CONTINUE && response2 == CONTINUE) {
1093 normal *= (0.5 + DELTA);
1094 object1->dest.move(-normal);
1095 object2->dest.move(normal);
1096 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1097 normal *= (1 + DELTA);
1098 object1->dest.move(-normal);
1099 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1100 normal *= (1 + DELTA);
1101 object2->dest.move(normal);
1107 Sector::collision_static(collision::Constraints* constraints,
1108 const Vector& movement, const Rectf& dest,
1111 collision_tilemap(constraints, movement, dest);
1113 // collision with other (static) objects
1114 for(MovingObjects::iterator i = moving_objects.begin();
1115 i != moving_objects.end(); ++i) {
1116 MovingObject* moving_object = *i;
1117 if(moving_object->get_group() != COLGROUP_STATIC
1118 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1120 if(!moving_object->is_valid())
1123 if(moving_object != &object)
1124 check_collisions(constraints, movement, dest, moving_object->bbox,
1125 &object, moving_object);
1130 Sector::collision_static_constrains(MovingObject& object)
1132 using namespace collision;
1133 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1135 Constraints constraints;
1136 Vector movement = object.get_movement();
1137 Rectf& dest = object.dest;
1138 float owidth = object.get_bbox().get_width();
1139 float oheight = object.get_bbox().get_height();
1141 for(int i = 0; i < 2; ++i) {
1142 collision_static(&constraints, Vector(0, movement.y), dest, object);
1143 if(!constraints.has_constraints())
1146 // apply calculated horizontal constraints
1147 if(constraints.bottom < infinity) {
1148 float height = constraints.bottom - constraints.top;
1149 if(height < oheight) {
1150 // we're crushed, but ignore this for now, we'll get this again
1151 // later if we're really crushed or things will solve itself when
1152 // looking at the vertical constraints
1154 dest.p2.y = constraints.bottom - DELTA;
1155 dest.p1.y = dest.p2.y - oheight;
1156 } else if(constraints.top > -infinity) {
1157 dest.p1.y = constraints.top + DELTA;
1158 dest.p2.y = dest.p1.y + oheight;
1161 if(constraints.has_constraints()) {
1162 if(constraints.hit.bottom) {
1163 dest.move(constraints.ground_movement);
1165 if(constraints.hit.top || constraints.hit.bottom) {
1166 constraints.hit.left = false;
1167 constraints.hit.right = false;
1168 object.collision_solid(constraints.hit);
1172 constraints = Constraints();
1173 for(int i = 0; i < 2; ++i) {
1174 collision_static(&constraints, movement, dest, object);
1175 if(!constraints.has_constraints())
1178 // apply calculated vertical constraints
1179 if(constraints.right < infinity) {
1180 float width = constraints.right - constraints.left;
1181 if(width + SHIFT_DELTA < owidth) {
1183 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1184 constraints.left, constraints.right);
1190 object.collision_solid(h);
1192 dest.p2.x = constraints.right - DELTA;
1193 dest.p1.x = dest.p2.x - owidth;
1195 } else if(constraints.left > -infinity) {
1196 dest.p1.x = constraints.left + DELTA;
1197 dest.p2.x = dest.p1.x + owidth;
1201 if(constraints.has_constraints()) {
1202 if( constraints.hit.left || constraints.hit.right
1203 || constraints.hit.top || constraints.hit.bottom
1204 || constraints.hit.crush )
1205 object.collision_solid(constraints.hit);
1208 // an extra pass to make sure we're not crushed horizontally
1209 constraints = Constraints();
1210 collision_static(&constraints, movement, dest, object);
1211 if(constraints.bottom < infinity) {
1212 float height = constraints.bottom - constraints.top;
1213 if(height + SHIFT_DELTA < oheight) {
1215 printf("Object %p crushed vertically...\n", &object);
1221 object.collision_solid(h);
1227 const float MAX_SPEED = 16.0f;
1231 Sector::handle_collisions()
1233 using namespace collision;
1235 // calculate destination positions of the objects
1236 for(MovingObjects::iterator i = moving_objects.begin();
1237 i != moving_objects.end(); ++i) {
1238 MovingObject* moving_object = *i;
1239 Vector mov = moving_object->get_movement();
1241 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1242 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1243 moving_object->movement = mov.unit() * MAX_SPEED;
1244 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1247 moving_object->dest = moving_object->get_bbox();
1248 moving_object->dest.move(moving_object->get_movement());
1251 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1252 for(MovingObjects::iterator i = moving_objects.begin();
1253 i != moving_objects.end(); ++i) {
1254 MovingObject* moving_object = *i;
1255 if((moving_object->get_group() != COLGROUP_MOVING
1256 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1257 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1258 || !moving_object->is_valid())
1261 collision_static_constrains(*moving_object);
1264 // part2: COLGROUP_MOVING vs tile attributes
1265 for(MovingObjects::iterator i = moving_objects.begin();
1266 i != moving_objects.end(); ++i) {
1267 MovingObject* moving_object = *i;
1268 if((moving_object->get_group() != COLGROUP_MOVING
1269 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1270 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1271 || !moving_object->is_valid())
1274 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1275 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1276 moving_object->collision_tile(tile_attributes);
1280 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1281 for(MovingObjects::iterator i = moving_objects.begin();
1282 i != moving_objects.end(); ++i) {
1283 MovingObject* moving_object = *i;
1284 if((moving_object->get_group() != COLGROUP_MOVING
1285 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1286 || !moving_object->is_valid())
1289 for(MovingObjects::iterator i2 = moving_objects.begin();
1290 i2 != moving_objects.end(); ++i2) {
1291 MovingObject* moving_object_2 = *i2;
1292 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1293 || !moving_object_2->is_valid())
1296 if(intersects(moving_object->dest, moving_object_2->dest)) {
1299 get_hit_normal(moving_object->dest, moving_object_2->dest,
1301 if(!moving_object->collides(*moving_object_2, hit))
1303 if(!moving_object_2->collides(*moving_object, hit))
1306 moving_object->collision(*moving_object_2, hit);
1307 moving_object_2->collision(*moving_object, hit);
1312 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1313 for(MovingObjects::iterator i = moving_objects.begin();
1314 i != moving_objects.end(); ++i) {
1315 MovingObject* moving_object = *i;
1317 if((moving_object->get_group() != COLGROUP_MOVING
1318 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1319 || !moving_object->is_valid())
1322 for(MovingObjects::iterator i2 = i+1;
1323 i2 != moving_objects.end(); ++i2) {
1324 MovingObject* moving_object_2 = *i2;
1325 if((moving_object_2->get_group() != COLGROUP_MOVING
1326 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1327 || !moving_object_2->is_valid())
1330 collision_object(moving_object, moving_object_2);
1334 // apply object movement
1335 for(MovingObjects::iterator i = moving_objects.begin();
1336 i != moving_objects.end(); ++i) {
1337 MovingObject* moving_object = *i;
1339 moving_object->bbox = moving_object->dest;
1340 moving_object->movement = Vector(0, 0);
1345 Sector::is_free_of_tiles(const Rectf& rect, const bool ignoreUnisolid) const
1347 using namespace collision;
1349 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1350 TileMap* solids = *i;
1352 // test with all tiles in this rectangle
1353 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1354 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1355 int max_x = int(rect.p2.x - solids->get_x_offset());
1356 int max_y = int(rect.p2.y - solids->get_y_offset());
1358 for(int x = starttilex; x*32 <= max_x; ++x) {
1359 for(int y = starttiley; y*32 <= max_y; ++y) {
1360 const Tile* tile = solids->get_tile(x, y);
1362 if(tile->getAttributes() & Tile::SLOPE) {
1363 AATriangle triangle;
1364 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1365 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1366 triangle = AATriangle(p1, p2, tile->getData());
1367 Constraints constraints;
1368 if(collision::rectangle_aatriangle(&constraints, rect, triangle) && (!ignoreUnisolid || !(tile->getAttributes() & Tile::UNISOLID))) return false;
1370 if((tile->getAttributes() & Tile::SOLID) && (!ignoreUnisolid || !(tile->getAttributes() & Tile::UNISOLID))) return false;
1379 Sector::is_free_of_statics(const Rectf& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1381 using namespace collision;
1383 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1385 for(MovingObjects::const_iterator i = moving_objects.begin();
1386 i != moving_objects.end(); ++i) {
1387 const MovingObject* moving_object = *i;
1388 if (moving_object == ignore_object) continue;
1389 if (!moving_object->is_valid()) continue;
1390 if (moving_object->get_group() == COLGROUP_STATIC) {
1391 if(intersects(rect, moving_object->get_bbox())) return false;
1399 Sector::is_free_of_movingstatics(const Rectf& rect, const MovingObject* ignore_object) const
1401 using namespace collision;
1403 if (!is_free_of_tiles(rect)) return false;
1405 for(MovingObjects::const_iterator i = moving_objects.begin();
1406 i != moving_objects.end(); ++i) {
1407 const MovingObject* moving_object = *i;
1408 if (moving_object == ignore_object) continue;
1409 if (!moving_object->is_valid()) continue;
1410 if ((moving_object->get_group() == COLGROUP_MOVING)
1411 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1412 || (moving_object->get_group() == COLGROUP_STATIC)) {
1413 if(intersects(rect, moving_object->get_bbox())) return false;
1421 Sector::add_bullet(const Vector& pos, const PlayerStatus* player_status, float xm, Direction dir)
1423 // TODO remove this function and move these checks elsewhere...
1425 Bullet* new_bullet = 0;
1426 if((player_status->bonus == FIRE_BONUS &&
1427 (int)bullets.size() >= player_status->max_fire_bullets) ||
1428 (player_status->bonus == ICE_BONUS &&
1429 (int)bullets.size() >= player_status->max_ice_bullets))
1431 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1432 add_object(new_bullet);
1434 sound_manager->play("sounds/shoot.wav");
1440 Sector::add_smoke_cloud(const Vector& pos)
1442 add_object(new SmokeCloud(pos));
1447 Sector::play_music(MusicType type)
1449 currentmusic = type;
1450 switch(currentmusic) {
1452 sound_manager->play_music(music);
1455 sound_manager->play_music("music/invincible.music");
1457 case HERRING_WARNING_MUSIC:
1458 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1461 sound_manager->play_music("");
1467 Sector::get_music_type()
1469 return currentmusic;
1473 Sector::get_total_badguys()
1475 int total_badguys = 0;
1476 for(GameObjects::iterator i = gameobjects.begin();
1477 i != gameobjects.end(); ++i) {
1478 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1479 if (badguy && badguy->countMe)
1483 return total_badguys;
1487 Sector::inside(const Rectf& rect) const
1489 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1490 TileMap* solids = *i;
1491 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1492 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1494 if (horizontally && vertically)
1501 Sector::get_width() const
1504 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1505 i != solid_tilemaps.end(); i++) {
1506 TileMap* solids = *i;
1507 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1508 width = solids->get_width() * 32 + solids->get_x_offset();
1516 Sector::get_height() const
1519 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1520 i != solid_tilemaps.end(); i++) {
1521 TileMap* solids = *i;
1522 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1523 height = solids->get_height() * 32 + solids->get_y_offset();
1531 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1533 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1534 TileMap* solids = *i;
1535 solids->change_all(old_tile_id, new_tile_id);
1540 Sector::set_ambient_light(float red, float green, float blue)
1542 ambient_light.red = red;
1543 ambient_light.green = green;
1544 ambient_light.blue = blue;
1548 Sector::get_ambient_red()
1550 return ambient_light.red;
1554 Sector::get_ambient_green()
1556 return ambient_light.green;
1560 Sector::get_ambient_blue()
1562 return ambient_light.blue;
1566 Sector::set_gravity(float gravity)
1568 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1569 this->gravity = gravity;
1573 Sector::get_gravity() const