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/bullet.hpp"
28 #include "object/camera.hpp"
29 #include "object/coin.hpp"
30 #include "object/display_effect.hpp"
31 #include "object/gradient.hpp"
32 #include "object/invisible_block.hpp"
33 #include "object/particlesystem.hpp"
34 #include "object/particlesystem_interactive.hpp"
35 #include "object/player.hpp"
36 #include "object/portable.hpp"
37 #include "object/pulsing_light.hpp"
38 #include "object/smoke_cloud.hpp"
39 #include "object/text_object.hpp"
40 #include "object/tilemap.hpp"
41 #include "physfs/physfs_stream.hpp"
42 #include "scripting/squirrel_util.hpp"
43 #include "supertux/collision.hpp"
44 #include "supertux/constants.hpp"
45 #include "supertux/level.hpp"
46 #include "supertux/main.hpp"
47 #include "supertux/object_factory.hpp"
48 #include "supertux/spawn_point.hpp"
49 #include "supertux/tile.hpp"
50 #include "trigger/sequence_trigger.hpp"
51 #include "util/file_system.hpp"
53 Sector* Sector::_current = 0;
55 bool Sector::show_collrects = false;
56 bool Sector::draw_solids_only = false;
58 Sector::Sector(Level* parent) :
64 currentmusic(LEVEL_MUSIC),
67 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ),
79 add_object(new Player(player_status, "Tux"));
80 add_object(new DisplayEffect("Effect"));
81 add_object(new TextObject("Text"));
83 sound_manager->preload("sounds/shoot.wav");
85 // create a new squirrel table for the sector
86 using namespace Scripting;
88 sq_collectgarbage(global_vm);
90 sq_newtable(global_vm);
91 sq_pushroottable(global_vm);
92 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
93 throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
95 sq_resetobject(§or_table);
96 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
97 throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
98 sq_addref(global_vm, §or_table);
104 using namespace Scripting;
108 for(ScriptList::iterator i = scripts.begin();
109 i != scripts.end(); ++i) {
110 HSQOBJECT& object = *i;
111 sq_release(global_vm, &object);
113 sq_release(global_vm, §or_table);
114 sq_collectgarbage(global_vm);
116 update_game_objects();
117 assert(gameobjects_new.size() == 0);
119 for(GameObjects::iterator i = gameobjects.begin();
120 i != gameobjects.end(); ++i) {
121 GameObject* object = *i;
122 before_object_remove(object);
126 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
138 Sector::parse_object(const std::string& name, const Reader& reader)
140 if(name == "camera") {
141 Camera* camera = new Camera(this, "Camera");
142 camera->parse(reader);
144 } else if(name == "particles-snow") {
145 SnowParticleSystem* partsys = new SnowParticleSystem();
146 partsys->parse(reader);
148 } else if(name == "particles-rain") {
149 RainParticleSystem* partsys = new RainParticleSystem();
150 partsys->parse(reader);
152 } else if(name == "particles-comets") {
153 CometParticleSystem* partsys = new CometParticleSystem();
154 partsys->parse(reader);
156 } else if(name == "particles-ghosts") {
157 GhostParticleSystem* partsys = new GhostParticleSystem();
158 partsys->parse(reader);
160 } else if(name == "particles-clouds") {
161 CloudParticleSystem* partsys = new CloudParticleSystem();
162 partsys->parse(reader);
164 } else if(name == "money") { // for compatibility with old maps
165 return new Jumpy(reader);
169 return create_object(name, reader);
170 } catch(std::exception& e) {
171 log_warning << e.what() << "" << std::endl;
178 Sector::parse(const Reader& sector)
180 bool has_background = false;
181 lisp::ListIterator iter(§or);
183 const std::string& token = iter.item();
184 if(token == "name") {
185 iter.value()->get(name);
186 } else if(token == "gravity") {
187 iter.value()->get(gravity);
188 } else if(token == "music") {
189 iter.value()->get(music);
190 } else if(token == "spawnpoint") {
191 SpawnPoint* sp = new SpawnPoint(iter.lisp());
192 spawnpoints.push_back(sp);
193 } else if(token == "init-script") {
194 iter.value()->get(init_script);
195 } else if(token == "ambient-light") {
196 std::vector<float> vColor;
197 sector.get( "ambient-light", vColor );
198 if(vColor.size() < 3) {
199 log_warning << "(ambient-light) requires a color as argument" << std::endl;
201 ambient_light = Color( vColor );
204 GameObject* object = parse_object(token, *(iter.lisp()));
206 if(dynamic_cast<Background *>(object)) {
207 has_background = true;
208 } else if(dynamic_cast<Gradient *>(object)) {
209 has_background = true;
216 if(!has_background) {
217 Gradient* gradient = new Gradient();
218 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
219 add_object(gradient);
222 update_game_objects();
224 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
228 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
229 update_game_objects();
230 add_object(new Camera(this, "Camera"));
233 update_game_objects();
237 Sector::parse_old_format(const Reader& reader)
240 reader.get("gravity", gravity);
242 std::string backgroundimage;
243 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
244 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
245 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
246 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
247 backgroundimage = "images/background/" + backgroundimage;
248 if (!PHYSFS_exists(backgroundimage.c_str())) {
249 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
250 backgroundimage = "";
255 reader.get("bkgd_speed", bgspeed);
258 Color bkgd_top, bkgd_bottom;
259 int r = 0, g = 0, b = 128;
260 reader.get("bkgd_red_top", r);
261 reader.get("bkgd_green_top", g);
262 reader.get("bkgd_blue_top", b);
263 bkgd_top.red = static_cast<float> (r) / 255.0f;
264 bkgd_top.green = static_cast<float> (g) / 255.0f;
265 bkgd_top.blue = static_cast<float> (b) / 255.0f;
267 reader.get("bkgd_red_bottom", r);
268 reader.get("bkgd_green_bottom", g);
269 reader.get("bkgd_blue_bottom", b);
270 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
271 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
272 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
274 if(backgroundimage != "") {
275 Background* background = new Background();
276 background->set_image(backgroundimage, bgspeed);
277 add_object(background);
279 Gradient* gradient = new Gradient();
280 gradient->set_gradient(bkgd_top, bkgd_bottom);
281 add_object(gradient);
284 std::string particlesystem;
285 reader.get("particle_system", particlesystem);
286 if(particlesystem == "clouds")
287 add_object(new CloudParticleSystem());
288 else if(particlesystem == "snow")
289 add_object(new SnowParticleSystem());
290 else if(particlesystem == "rain")
291 add_object(new RainParticleSystem());
293 Vector startpos(100, 170);
294 reader.get("start_pos_x", startpos.x);
295 reader.get("start_pos_y", startpos.y);
297 SpawnPoint* spawn = new SpawnPoint;
298 spawn->pos = startpos;
299 spawn->name = "main";
300 spawnpoints.push_back(spawn);
302 music = "chipdisko.ogg";
303 // skip reading music filename. It's all .ogg now, anyway
305 reader.get("music", music);
307 music = "music/" + music;
309 int width = 30, height = 15;
310 reader.get("width", width);
311 reader.get("height", height);
313 std::vector<unsigned int> tiles;
314 if(reader.get("interactive-tm", tiles)
315 || reader.get("tilemap", tiles)) {
316 TileMap* tilemap = new TileMap(level->get_tileset());
317 tilemap->set(width, height, tiles, LAYER_TILES, true);
319 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
320 for(size_t x=0; x < tilemap->get_width(); ++x) {
321 for(size_t y=0; y < tilemap->get_height(); ++y) {
322 uint32_t id = tilemap->get_tile_id(x, y);
324 tilemap->change(x, y, 1311);
328 if (height < 19) tilemap->resize(width, 19);
332 if(reader.get("background-tm", tiles)) {
333 TileMap* tilemap = new TileMap(level->get_tileset());
334 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
335 if (height < 19) tilemap->resize(width, 19);
339 if(reader.get("foreground-tm", tiles)) {
340 TileMap* tilemap = new TileMap(level->get_tileset());
341 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
343 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
344 if (height < 19) tilemap->resize(width, 19, 2035);
349 // read reset-points (now spawn-points)
350 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
352 lisp::ListIterator iter(resetpoints);
354 if(iter.item() == "point") {
356 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
358 SpawnPoint* sp = new SpawnPoint;
361 spawnpoints.push_back(sp);
364 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
370 const lisp::Lisp* objects = reader.get_lisp("objects");
372 lisp::ListIterator iter(objects);
374 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
378 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
384 Camera* camera = new Camera(this, "Camera");
387 update_game_objects();
389 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
392 update_game_objects();
396 Sector::fix_old_tiles()
398 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
399 TileMap* solids = *i;
400 for(size_t x=0; x < solids->get_width(); ++x) {
401 for(size_t y=0; y < solids->get_height(); ++y) {
402 uint32_t id = solids->get_tile_id(x, y);
403 const Tile *tile = solids->get_tile(x, y);
404 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
407 add_object(new InvisibleBlock(pos));
408 solids->change(x, y, 0);
409 } else if(tile->getAttributes() & Tile::COIN) {
410 add_object(new Coin(pos));
411 solids->change(x, y, 0);
412 } else if(tile->getAttributes() & Tile::FULLBOX) {
413 add_object(new BonusBlock(pos, tile->getData()));
414 solids->change(x, y, 0);
415 } else if(tile->getAttributes() & Tile::BRICK) {
416 add_object(new Brick(pos, tile->getData()));
417 solids->change(x, y, 0);
418 } else if(tile->getAttributes() & Tile::GOAL) {
419 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
420 add_object(new SequenceTrigger(pos, sequence));
421 solids->change(x, y, 0);
427 // add lights for special tiles
428 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
429 TileMap* tm = dynamic_cast<TileMap*>(*i);
431 for(size_t x=0; x < tm->get_width(); ++x) {
432 for(size_t y=0; y < tm->get_height(); ++y) {
433 uint32_t id = tm->get_tile_id(x, y);
434 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
435 Vector center(pos.x + 16, pos.y + 16);
439 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
440 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
443 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
444 // space lights a bit
445 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
446 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
447 || ((x % 3 == 0) && (y % 3 == 0))) {
448 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
449 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
460 Sector::run_script(std::istream& in, const std::string& sourcename)
462 using namespace Scripting;
464 // garbage collect thread list
465 for(ScriptList::iterator i = scripts.begin();
466 i != scripts.end(); ) {
467 HSQOBJECT& object = *i;
468 HSQUIRRELVM vm = object_to_vm(object);
470 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
471 sq_release(global_vm, &object);
472 i = scripts.erase(i);
479 HSQOBJECT object = create_thread(global_vm);
480 scripts.push_back(object);
482 HSQUIRRELVM vm = object_to_vm(object);
484 // set sector_table as roottable for the thread
485 sq_pushobject(vm, sector_table);
489 compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
490 } catch(std::exception& e) {
491 log_warning << "Error running script: " << e.what() << std::endl;
498 Sector::add_object(GameObject* object)
500 // make sure the object isn't already in the list
502 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
505 assert("object already added to sector" == 0);
508 for(GameObjects::iterator i = gameobjects_new.begin();
509 i != gameobjects_new.end(); ++i) {
511 assert("object already added to sector" == 0);
517 gameobjects_new.push_back(object);
521 Sector::activate(const std::string& spawnpoint)
524 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
526 if((*i)->name == spawnpoint) {
532 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
533 if(spawnpoint != "main") {
536 activate(Vector(0, 0));
544 Sector::activate(const Vector& player_pos)
546 if(_current != this) {
548 _current->deactivate();
551 // register sectortable as sector in scripting
552 HSQUIRRELVM vm = Scripting::global_vm;
553 sq_pushroottable(vm);
554 sq_pushstring(vm, "sector", -1);
555 sq_pushobject(vm, sector_table);
556 if(SQ_FAILED(sq_createslot(vm, -3)))
557 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
560 for(GameObjects::iterator i = gameobjects.begin();
561 i != gameobjects.end(); ++i) {
562 GameObject* object = *i;
569 // spawn smalltux below spawnpoint
570 if (!player->is_big()) {
571 player->move(player_pos + Vector(0,32));
573 player->move(player_pos);
576 // spawning tux in the ground would kill him
577 if(!is_free_of_tiles(player->get_bbox())) {
578 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
579 Vector npos = player->get_bbox().p1;
584 camera->reset(player->get_pos());
585 update_game_objects();
587 //Run default.nut just before init script
588 //Check to see if it's in a levelset (info file)
589 std::string basedir = FileSystem::dirname(get_level()->filename);
590 if(PHYSFS_exists((basedir + "/info").c_str())) {
592 IFileStream in(basedir + "/default.nut");
593 run_script(in, "default.nut");
594 } catch(std::exception& ) {
595 // doesn't exist or erroneous; do nothing
600 if(init_script != "") {
601 std::istringstream in(init_script);
602 run_script(in, "init-script");
612 // remove sector entry from global vm
613 HSQUIRRELVM vm = Scripting::global_vm;
614 sq_pushroottable(vm);
615 sq_pushstring(vm, "sector", -1);
616 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
617 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
620 for(GameObjects::iterator i = gameobjects.begin();
621 i != gameobjects.end(); ++i) {
622 GameObject* object = *i;
624 try_unexpose(object);
632 Sector::get_active_region()
635 camera->get_translation() - Vector(1600, 1200),
636 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
640 Sector::update(float elapsed_time)
642 player->check_bounds(camera);
645 for(GameObjects::iterator i = gameobjects.begin();
646 i != gameobjects.end(); ++i) {
647 GameObject* object = *i;
648 if(!object->is_valid())
651 object->update(elapsed_time);
654 /* Handle all possible collisions. */
656 update_game_objects();
660 Sector::update_game_objects()
662 /** cleanup marked objects */
663 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
664 i != gameobjects.end(); /* nothing */) {
665 GameObject* object = *i;
667 if(object->is_valid()) {
672 before_object_remove(object);
675 i = gameobjects.erase(i);
678 /* add newly created objects */
679 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
680 i != gameobjects_new.end(); ++i)
682 GameObject* object = *i;
684 before_object_add(object);
686 gameobjects.push_back(object);
688 gameobjects_new.clear();
690 /* update solid_tilemaps list */
691 //FIXME: this could be more efficient
692 solid_tilemaps.clear();
693 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
694 i != gameobjects.end(); ++i)
696 TileMap* tm = dynamic_cast<TileMap*>(*i);
698 if (tm->is_solid()) solid_tilemaps.push_back(tm);
704 Sector::before_object_add(GameObject* object)
706 Bullet* bullet = dynamic_cast<Bullet*> (object);
708 bullets.push_back(bullet);
711 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
712 if(movingobject != NULL) {
713 moving_objects.push_back(movingobject);
716 Portable* portable = dynamic_cast<Portable*> (object);
717 if(portable != NULL) {
718 portables.push_back(portable);
721 TileMap* tilemap = dynamic_cast<TileMap*> (object);
722 if(tilemap != NULL && tilemap->is_solid()) {
723 solid_tilemaps.push_back(tilemap);
726 Camera* camera = dynamic_cast<Camera*> (object);
728 if(this->camera != 0) {
729 log_warning << "Multiple cameras added. Ignoring" << std::endl;
732 this->camera = camera;
735 Player* player = dynamic_cast<Player*> (object);
737 if(this->player != 0) {
738 log_warning << "Multiple players added. Ignoring" << std::endl;
741 this->player = player;
744 DisplayEffect* effect = dynamic_cast<DisplayEffect*> (object);
746 if(this->effect != 0) {
747 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
750 this->effect = effect;
753 if(_current == this) {
761 Sector::try_expose(GameObject* object)
763 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
764 if(interface != NULL) {
765 HSQUIRRELVM vm = Scripting::global_vm;
766 sq_pushobject(vm, sector_table);
767 interface->expose(vm, -1);
773 Sector::try_expose_me()
775 HSQUIRRELVM vm = Scripting::global_vm;
776 sq_pushobject(vm, sector_table);
777 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
778 expose_object(vm, -1, interface, "settings", false);
783 Sector::before_object_remove(GameObject* object)
785 Portable* portable = dynamic_cast<Portable*> (object);
786 if(portable != NULL) {
787 portables.erase(std::find(portables.begin(), portables.end(), portable));
789 Bullet* bullet = dynamic_cast<Bullet*> (object);
791 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
793 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
794 if(moving_object != NULL) {
795 moving_objects.erase(
796 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
800 try_unexpose(object);
804 Sector::try_unexpose(GameObject* object)
806 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
807 if(interface != NULL) {
808 HSQUIRRELVM vm = Scripting::global_vm;
809 SQInteger oldtop = sq_gettop(vm);
810 sq_pushobject(vm, sector_table);
812 interface->unexpose(vm, -1);
813 } catch(std::exception& e) {
814 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
816 sq_settop(vm, oldtop);
821 Sector::try_unexpose_me()
823 HSQUIRRELVM vm = Scripting::global_vm;
824 SQInteger oldtop = sq_gettop(vm);
825 sq_pushobject(vm, sector_table);
827 Scripting::unexpose_object(vm, -1, "settings");
828 } catch(std::exception& e) {
829 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
831 sq_settop(vm, oldtop);
834 Sector::draw(DrawingContext& context)
836 context.set_ambient_color( ambient_light );
837 context.push_transform();
838 context.set_translation(camera->get_translation());
840 for(GameObjects::iterator i = gameobjects.begin();
841 i != gameobjects.end(); ++i) {
842 GameObject* object = *i;
843 if(!object->is_valid())
846 if (draw_solids_only)
848 TileMap* tm = dynamic_cast<TileMap*>(object);
849 if (tm && !tm->is_solid())
853 object->draw(context);
857 Color col(0.2f, 0.2f, 0.2f, 0.7f);
858 for(MovingObjects::iterator i = moving_objects.begin();
859 i != moving_objects.end(); ++i) {
860 MovingObject* object = *i;
861 const Rect& rect = object->get_bbox();
863 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
867 context.pop_transform();
870 /*-------------------------------------------------------------------------
871 * Collision Detection
872 *-------------------------------------------------------------------------*/
874 /** r1 is supposed to be moving, r2 a solid object */
875 void check_collisions(collision::Constraints* constraints,
876 const Vector& movement, const Rect& r1, const Rect& r2,
877 GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
879 if(!collision::intersects(r1, r2))
882 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
884 if(other != NULL && !other->collides(*object, dummy))
886 if(moving_object != NULL && !moving_object->collides(*other, dummy))
889 // calculate intersection
890 float itop = r1.get_bottom() - r2.get_top();
891 float ibottom = r2.get_bottom() - r1.get_top();
892 float ileft = r1.get_right() - r2.get_left();
893 float iright = r2.get_right() - r1.get_left();
895 if(fabsf(movement.y) > fabsf(movement.x)) {
896 if(ileft < SHIFT_DELTA) {
897 constraints->right = std::min(constraints->right, r2.get_left());
899 } else if(iright < SHIFT_DELTA) {
900 constraints->left = std::max(constraints->left, r2.get_right());
904 // shiftout bottom/top
905 if(itop < SHIFT_DELTA) {
906 constraints->bottom = std::min(constraints->bottom, r2.get_top());
908 } else if(ibottom < SHIFT_DELTA) {
909 constraints->top = std::max(constraints->top, r2.get_bottom());
914 constraints->ground_movement += addl_ground_movement;
916 HitResponse response = other->collision(*object, dummy);
917 if(response == PASSTHROUGH)
920 if(other->get_movement() != Vector(0, 0)) {
921 // TODO what todo when we collide with 2 moving objects?!?
922 constraints->ground_movement = other->get_movement();
926 float vert_penetration = std::min(itop, ibottom);
927 float horiz_penetration = std::min(ileft, iright);
928 if(vert_penetration < horiz_penetration) {
930 constraints->bottom = std::min(constraints->bottom, r2.get_top());
931 constraints->hit.bottom = true;
933 constraints->top = std::max(constraints->top, r2.get_bottom());
934 constraints->hit.top = true;
938 constraints->right = std::min(constraints->right, r2.get_left());
939 constraints->hit.right = true;
941 constraints->left = std::max(constraints->left, r2.get_right());
942 constraints->hit.left = true;
948 Sector::collision_tilemap(collision::Constraints* constraints,
949 const Vector& movement, const Rect& dest) const
951 // calculate rectangle where the object will move
952 float x1 = dest.get_left();
953 float x2 = dest.get_right();
954 float y1 = dest.get_top();
955 float y2 = dest.get_bottom();
957 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
958 TileMap* solids = *i;
960 // test with all tiles in this rectangle
961 int starttilex = int(x1 - solids->get_x_offset()) / 32;
962 int starttiley = int(y1 - solids->get_y_offset()) / 32;
963 int max_x = int(x2 - solids->get_x_offset());
964 int max_y = int(y2+1 - solids->get_y_offset());
966 for(int x = starttilex; x*32 < max_x; ++x) {
967 for(int y = starttiley; y*32 < max_y; ++y) {
968 const Tile* tile = solids->get_tile(x, y);
971 // skip non-solid tiles
972 if((tile->getAttributes() & Tile::SOLID) == 0)
974 // only handle unisolid when the player is falling down and when he was
975 // above the tile before
976 if(tile->getAttributes() & Tile::UNISOLID) {
977 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
981 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
983 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
984 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
985 triangle = AATriangle(p1, p2, tile->getData());
987 collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
988 } else { // normal rectangular tile
989 Rect 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());
990 check_collisions(constraints, movement, dest, rect, NULL, NULL, solids->get_movement());
998 Sector::collision_tile_attributes(const Rect& dest) const
1000 float x1 = dest.p1.x;
1001 float y1 = dest.p1.y;
1002 float x2 = dest.p2.x;
1003 float y2 = dest.p2.y + SHIFT_DELTA;
1005 uint32_t result = 0;
1006 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1007 TileMap* solids = *i;
1009 // test with all tiles in this rectangle
1010 int starttilex = int(x1 - solids->get_x_offset()) / 32;
1011 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1012 int max_x = int(x2 - solids->get_x_offset());
1013 int max_y = int(y2+1 - solids->get_y_offset());
1015 for(int x = starttilex; x*32 < max_x; ++x) {
1016 for(int y = starttiley; y*32 < max_y; ++y) {
1017 const Tile* tile = solids->get_tile(x, y);
1020 result |= tile->getAttributes();
1028 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1029 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1032 float itop = r1.get_bottom() - r2.get_top();
1033 float ibottom = r2.get_bottom() - r1.get_top();
1034 float ileft = r1.get_right() - r2.get_left();
1035 float iright = r2.get_right() - r1.get_left();
1037 float vert_penetration = std::min(itop, ibottom);
1038 float horiz_penetration = std::min(ileft, iright);
1039 if(vert_penetration < horiz_penetration) {
1040 if(itop < ibottom) {
1042 normal.y = vert_penetration;
1045 normal.y = -vert_penetration;
1048 if(ileft < iright) {
1050 normal.x = horiz_penetration;
1053 normal.x = -horiz_penetration;
1059 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1061 using namespace collision;
1063 const Rect& r1 = object1->dest;
1064 const Rect& r2 = object2->dest;
1067 if(intersects(object1->dest, object2->dest)) {
1069 get_hit_normal(r1, r2, hit, normal);
1071 if(!object1->collides(*object2, hit))
1073 std::swap(hit.left, hit.right);
1074 std::swap(hit.top, hit.bottom);
1075 if(!object2->collides(*object1, hit))
1077 std::swap(hit.left, hit.right);
1078 std::swap(hit.top, hit.bottom);
1080 HitResponse response1 = object1->collision(*object2, hit);
1081 std::swap(hit.left, hit.right);
1082 std::swap(hit.top, hit.bottom);
1083 HitResponse response2 = object2->collision(*object1, hit);
1084 if(response1 == CONTINUE && response2 == CONTINUE) {
1085 normal *= (0.5 + DELTA);
1086 object1->dest.move(-normal);
1087 object2->dest.move(normal);
1088 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1089 normal *= (1 + DELTA);
1090 object1->dest.move(-normal);
1091 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1092 normal *= (1 + DELTA);
1093 object2->dest.move(normal);
1099 Sector::collision_static(collision::Constraints* constraints,
1100 const Vector& movement, const Rect& dest,
1103 collision_tilemap(constraints, movement, dest);
1105 // collision with other (static) objects
1106 for(MovingObjects::iterator i = moving_objects.begin();
1107 i != moving_objects.end(); ++i) {
1108 MovingObject* moving_object = *i;
1109 if(moving_object->get_group() != COLGROUP_STATIC
1110 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1112 if(!moving_object->is_valid())
1115 if(moving_object != &object)
1116 check_collisions(constraints, movement, dest, moving_object->bbox,
1117 &object, moving_object);
1122 Sector::collision_static_constrains(MovingObject& object)
1124 using namespace collision;
1125 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1127 Constraints constraints;
1128 Vector movement = object.get_movement();
1129 Rect& dest = object.dest;
1130 float owidth = object.get_bbox().get_width();
1131 float oheight = object.get_bbox().get_height();
1133 for(int i = 0; i < 2; ++i) {
1134 collision_static(&constraints, Vector(0, movement.y), dest, object);
1135 if(!constraints.has_constraints())
1138 // apply calculated horizontal constraints
1139 if(constraints.bottom < infinity) {
1140 float height = constraints.bottom - constraints.top;
1141 if(height < oheight) {
1142 // we're crushed, but ignore this for now, we'll get this again
1143 // later if we're really crushed or things will solve itself when
1144 // looking at the vertical constraints
1146 dest.p2.y = constraints.bottom - DELTA;
1147 dest.p1.y = dest.p2.y - oheight;
1148 } else if(constraints.top > -infinity) {
1149 dest.p1.y = constraints.top + DELTA;
1150 dest.p2.y = dest.p1.y + oheight;
1153 if(constraints.has_constraints()) {
1154 if(constraints.hit.bottom) {
1155 dest.move(constraints.ground_movement);
1157 if(constraints.hit.top || constraints.hit.bottom) {
1158 constraints.hit.left = false;
1159 constraints.hit.right = false;
1160 object.collision_solid(constraints.hit);
1164 constraints = Constraints();
1165 for(int i = 0; i < 2; ++i) {
1166 collision_static(&constraints, movement, dest, object);
1167 if(!constraints.has_constraints())
1170 // apply calculated vertical constraints
1171 if(constraints.right < infinity) {
1172 float width = constraints.right - constraints.left;
1173 if(width + SHIFT_DELTA < owidth) {
1175 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1176 constraints.left, constraints.right);
1182 object.collision_solid(h);
1184 dest.p2.x = constraints.right - DELTA;
1185 dest.p1.x = dest.p2.x - owidth;
1187 } else if(constraints.left > -infinity) {
1188 dest.p1.x = constraints.left + DELTA;
1189 dest.p2.x = dest.p1.x + owidth;
1193 if(constraints.has_constraints()) {
1194 if( constraints.hit.left || constraints.hit.right
1195 || constraints.hit.top || constraints.hit.bottom
1196 || constraints.hit.crush )
1197 object.collision_solid(constraints.hit);
1200 // an extra pass to make sure we're not crushed horizontally
1201 constraints = Constraints();
1202 collision_static(&constraints, movement, dest, object);
1203 if(constraints.bottom < infinity) {
1204 float height = constraints.bottom - constraints.top;
1205 if(height + SHIFT_DELTA < oheight) {
1207 printf("Object %p crushed vertically...\n", &object);
1213 object.collision_solid(h);
1219 const float MAX_SPEED = 16.0f;
1223 Sector::handle_collisions()
1225 using namespace collision;
1227 // calculate destination positions of the objects
1228 for(MovingObjects::iterator i = moving_objects.begin();
1229 i != moving_objects.end(); ++i) {
1230 MovingObject* moving_object = *i;
1231 Vector mov = moving_object->get_movement();
1233 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1234 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1235 moving_object->movement = mov.unit() * MAX_SPEED;
1236 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1239 moving_object->dest = moving_object->get_bbox();
1240 moving_object->dest.move(moving_object->get_movement());
1243 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1244 for(MovingObjects::iterator i = moving_objects.begin();
1245 i != moving_objects.end(); ++i) {
1246 MovingObject* moving_object = *i;
1247 if((moving_object->get_group() != COLGROUP_MOVING
1248 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1249 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1250 || !moving_object->is_valid())
1253 collision_static_constrains(*moving_object);
1256 // part2: COLGROUP_MOVING vs tile attributes
1257 for(MovingObjects::iterator i = moving_objects.begin();
1258 i != moving_objects.end(); ++i) {
1259 MovingObject* moving_object = *i;
1260 if((moving_object->get_group() != COLGROUP_MOVING
1261 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1262 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1263 || !moving_object->is_valid())
1266 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1267 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1268 moving_object->collision_tile(tile_attributes);
1272 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1273 for(MovingObjects::iterator i = moving_objects.begin();
1274 i != moving_objects.end(); ++i) {
1275 MovingObject* moving_object = *i;
1276 if((moving_object->get_group() != COLGROUP_MOVING
1277 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1278 || !moving_object->is_valid())
1281 for(MovingObjects::iterator i2 = moving_objects.begin();
1282 i2 != moving_objects.end(); ++i2) {
1283 MovingObject* moving_object_2 = *i2;
1284 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1285 || !moving_object_2->is_valid())
1288 if(intersects(moving_object->dest, moving_object_2->dest)) {
1291 get_hit_normal(moving_object->dest, moving_object_2->dest,
1293 if(!moving_object->collides(*moving_object_2, hit))
1295 if(!moving_object_2->collides(*moving_object, hit))
1298 moving_object->collision(*moving_object_2, hit);
1299 moving_object_2->collision(*moving_object, hit);
1304 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1305 for(MovingObjects::iterator i = moving_objects.begin();
1306 i != moving_objects.end(); ++i) {
1307 MovingObject* moving_object = *i;
1309 if((moving_object->get_group() != COLGROUP_MOVING
1310 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1311 || !moving_object->is_valid())
1314 for(MovingObjects::iterator i2 = i+1;
1315 i2 != moving_objects.end(); ++i2) {
1316 MovingObject* moving_object_2 = *i2;
1317 if((moving_object_2->get_group() != COLGROUP_MOVING
1318 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1319 || !moving_object_2->is_valid())
1322 collision_object(moving_object, moving_object_2);
1326 // apply object movement
1327 for(MovingObjects::iterator i = moving_objects.begin();
1328 i != moving_objects.end(); ++i) {
1329 MovingObject* moving_object = *i;
1331 moving_object->bbox = moving_object->dest;
1332 moving_object->movement = Vector(0, 0);
1337 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1339 using namespace collision;
1341 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1342 TileMap* solids = *i;
1344 // test with all tiles in this rectangle
1345 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1346 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1347 int max_x = int(rect.p2.x - solids->get_x_offset());
1348 int max_y = int(rect.p2.y - solids->get_y_offset());
1350 for(int x = starttilex; x*32 <= max_x; ++x) {
1351 for(int y = starttiley; y*32 <= max_y; ++y) {
1352 const Tile* tile = solids->get_tile(x, y);
1354 if(tile->getAttributes() & Tile::SLOPE) {
1355 AATriangle triangle;
1356 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1357 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1358 triangle = AATriangle(p1, p2, tile->getData());
1359 Constraints constraints;
1360 if(collision::rectangle_aatriangle(&constraints, rect, triangle) && (!ignoreUnisolid || !(tile->getAttributes() & Tile::UNISOLID))) return false;
1362 if((tile->getAttributes() & Tile::SOLID) && (!ignoreUnisolid || !(tile->getAttributes() & Tile::UNISOLID))) return false;
1371 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1373 using namespace collision;
1375 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1377 for(MovingObjects::const_iterator i = moving_objects.begin();
1378 i != moving_objects.end(); ++i) {
1379 const MovingObject* moving_object = *i;
1380 if (moving_object == ignore_object) continue;
1381 if (!moving_object->is_valid()) continue;
1382 if (moving_object->get_group() == COLGROUP_STATIC) {
1383 if(intersects(rect, moving_object->get_bbox())) return false;
1391 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1393 using namespace collision;
1395 if (!is_free_of_tiles(rect)) return false;
1397 for(MovingObjects::const_iterator i = moving_objects.begin();
1398 i != moving_objects.end(); ++i) {
1399 const MovingObject* moving_object = *i;
1400 if (moving_object == ignore_object) continue;
1401 if (!moving_object->is_valid()) continue;
1402 if ((moving_object->get_group() == COLGROUP_MOVING)
1403 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1404 || (moving_object->get_group() == COLGROUP_STATIC)) {
1405 if(intersects(rect, moving_object->get_bbox())) return false;
1413 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1415 // TODO remove this function and move these checks elsewhere...
1417 Bullet* new_bullet = 0;
1418 if((player_status->bonus == FIRE_BONUS &&
1419 (int)bullets.size() >= player_status->max_fire_bullets) ||
1420 (player_status->bonus == ICE_BONUS &&
1421 (int)bullets.size() >= player_status->max_ice_bullets))
1423 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1424 add_object(new_bullet);
1426 sound_manager->play("sounds/shoot.wav");
1432 Sector::add_smoke_cloud(const Vector& pos)
1434 add_object(new SmokeCloud(pos));
1439 Sector::play_music(MusicType type)
1441 currentmusic = type;
1442 switch(currentmusic) {
1444 sound_manager->play_music(music);
1447 sound_manager->play_music("music/invincible.music");
1449 case HERRING_WARNING_MUSIC:
1450 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1453 sound_manager->play_music("");
1459 Sector::get_music_type()
1461 return currentmusic;
1465 Sector::get_total_badguys()
1467 int total_badguys = 0;
1468 for(GameObjects::iterator i = gameobjects.begin();
1469 i != gameobjects.end(); ++i) {
1470 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1471 if (badguy && badguy->countMe)
1475 return total_badguys;
1479 Sector::inside(const Rect& rect) const
1481 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1482 TileMap* solids = *i;
1483 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1484 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1486 if (horizontally && vertically)
1493 Sector::get_width() const
1496 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1497 i != solid_tilemaps.end(); i++) {
1498 TileMap* solids = *i;
1499 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1500 width = solids->get_width() * 32 + solids->get_x_offset();
1508 Sector::get_height() const
1511 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1512 i != solid_tilemaps.end(); i++) {
1513 TileMap* solids = *i;
1514 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1515 height = solids->get_height() * 32 + solids->get_y_offset();
1523 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1525 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1526 TileMap* solids = *i;
1527 solids->change_all(old_tile_id, new_tile_id);
1532 Sector::set_ambient_light(float red, float green, float blue)
1534 ambient_light.red = red;
1535 ambient_light.green = green;
1536 ambient_light.blue = blue;
1540 Sector::get_ambient_red()
1542 return ambient_light.red;
1546 Sector::get_ambient_green()
1548 return ambient_light.green;
1552 Sector::get_ambient_blue()
1554 return ambient_light.blue;
1558 Sector::set_gravity(float gravity)
1560 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1561 this->gravity = gravity;
1565 Sector::get_gravity() const