3 // SuperTux - A Jump'n Run
4 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 #include "object/player.hpp"
35 #include "object/gameobjs.hpp"
36 #include "object/camera.hpp"
37 #include "object/background.hpp"
38 #include "object/gradient.hpp"
39 #include "object/particlesystem.hpp"
40 #include "object/particlesystem_interactive.hpp"
41 #include "object/tilemap.hpp"
42 #include "lisp/parser.hpp"
43 #include "lisp/lisp.hpp"
44 #include "lisp/writer.hpp"
45 #include "lisp/list_iterator.hpp"
47 #include "file_system.hpp"
48 #include "physfs/physfs_stream.hpp"
49 #include "audio/sound_manager.hpp"
50 #include "game_session.hpp"
51 #include "constants.hpp"
52 #include "resources.hpp"
53 #include "statistics.hpp"
54 #include "object_factory.hpp"
55 #include "collision.hpp"
56 #include "spawn_point.hpp"
57 #include "math/rect.hpp"
58 #include "math/aatriangle.hpp"
59 #include "object/coin.hpp"
60 #include "object/block.hpp"
61 #include "object/invisible_block.hpp"
62 #include "object/light.hpp"
63 #include "object/pulsing_light.hpp"
64 #include "object/bullet.hpp"
65 #include "object/text_object.hpp"
66 #include "object/portable.hpp"
67 #include "object/display_effect.hpp"
68 #include "badguy/jumpy.hpp"
69 #include "trigger/sequence_trigger.hpp"
70 #include "player_status.hpp"
71 #include "scripting/squirrel_util.hpp"
72 #include "script_interface.hpp"
77 Sector* Sector::_current = 0;
79 bool Sector::show_collrects = false;
80 bool Sector::draw_solids_only = false;
82 Sector::Sector(Level* parent)
83 : level(parent), currentmusic(LEVEL_MUSIC),
84 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10.0), player(0), camera(0), effect(0)
86 add_object(new Player(player_status, "Tux"));
87 add_object(new DisplayEffect("Effect"));
88 add_object(new TextObject("Text"));
90 sound_manager->preload("sounds/shoot.wav");
92 // create a new squirrel table for the sector
93 using namespace Scripting;
95 sq_collectgarbage(global_vm);
97 sq_newtable(global_vm);
98 sq_pushroottable(global_vm);
99 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
100 throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
102 sq_resetobject(§or_table);
103 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
104 throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
105 sq_addref(global_vm, §or_table);
106 sq_pop(global_vm, 1);
111 using namespace Scripting;
115 for(ScriptList::iterator i = scripts.begin();
116 i != scripts.end(); ++i) {
117 HSQOBJECT& object = *i;
118 sq_release(global_vm, &object);
120 sq_release(global_vm, §or_table);
121 sq_collectgarbage(global_vm);
123 update_game_objects();
124 assert(gameobjects_new.size() == 0);
126 for(GameObjects::iterator i = gameobjects.begin();
127 i != gameobjects.end(); ++i) {
128 GameObject* object = *i;
129 before_object_remove(object);
133 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
145 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
147 if(name == "camera") {
148 Camera* camera = new Camera(this, "Camera");
149 camera->parse(reader);
151 } else if(name == "particles-snow") {
152 SnowParticleSystem* partsys = new SnowParticleSystem();
153 partsys->parse(reader);
155 } else if(name == "particles-rain") {
156 RainParticleSystem* partsys = new RainParticleSystem();
157 partsys->parse(reader);
159 } else if(name == "particles-comets") {
160 CometParticleSystem* partsys = new CometParticleSystem();
161 partsys->parse(reader);
163 } else if(name == "particles-ghosts") {
164 GhostParticleSystem* partsys = new GhostParticleSystem();
165 partsys->parse(reader);
167 } else if(name == "particles-clouds") {
168 CloudParticleSystem* partsys = new CloudParticleSystem();
169 partsys->parse(reader);
171 } else if(name == "money") { // for compatibility with old maps
172 return new Jumpy(reader);
176 return create_object(name, reader);
177 } catch(std::exception& e) {
178 log_warning << e.what() << "" << std::endl;
185 Sector::parse(const lisp::Lisp& sector)
187 bool has_background = false;
188 lisp::ListIterator iter(§or);
190 const std::string& token = iter.item();
191 if(token == "name") {
192 iter.value()->get(name);
193 } else if(token == "gravity") {
194 iter.value()->get(gravity);
195 } else if(token == "music") {
196 iter.value()->get(music);
197 } else if(token == "spawnpoint") {
198 SpawnPoint* sp = new SpawnPoint(iter.lisp());
199 spawnpoints.push_back(sp);
200 } else if(token == "init-script") {
201 iter.value()->get(init_script);
202 } else if(token == "ambient-light") {
203 std::vector<float> vColor;
204 sector.get( "ambient-light", vColor );
205 if(vColor.size() < 3) {
206 log_warning << "(ambient-light) requires a color as argument" << std::endl;
208 ambient_light = Color( vColor );
211 GameObject* object = parse_object(token, *(iter.lisp()));
213 if(dynamic_cast<Background *>(object)) {
214 has_background = true;
215 } else if(dynamic_cast<Gradient *>(object)) {
216 has_background = true;
223 if(!has_background) {
224 Gradient* gradient = new Gradient();
225 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
226 add_object(gradient);
229 update_game_objects();
231 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
235 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
236 update_game_objects();
237 add_object(new Camera(this, "Camera"));
240 update_game_objects();
244 Sector::parse_old_format(const lisp::Lisp& reader)
247 reader.get("gravity", gravity);
249 std::string backgroundimage;
250 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
251 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
252 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
253 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
254 backgroundimage = "images/background/" + backgroundimage;
255 if (!PHYSFS_exists(backgroundimage.c_str())) {
256 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
257 backgroundimage = "";
262 reader.get("bkgd_speed", bgspeed);
265 Color bkgd_top, bkgd_bottom;
266 int r = 0, g = 0, b = 128;
267 reader.get("bkgd_red_top", r);
268 reader.get("bkgd_green_top", g);
269 reader.get("bkgd_blue_top", b);
270 bkgd_top.red = static_cast<float> (r) / 255.0f;
271 bkgd_top.green = static_cast<float> (g) / 255.0f;
272 bkgd_top.blue = static_cast<float> (b) / 255.0f;
274 reader.get("bkgd_red_bottom", r);
275 reader.get("bkgd_green_bottom", g);
276 reader.get("bkgd_blue_bottom", b);
277 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
278 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
279 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
281 if(backgroundimage != "") {
282 Background* background = new Background();
283 background->set_image(backgroundimage, bgspeed);
284 add_object(background);
286 Gradient* gradient = new Gradient();
287 gradient->set_gradient(bkgd_top, bkgd_bottom);
288 add_object(gradient);
291 std::string particlesystem;
292 reader.get("particle_system", particlesystem);
293 if(particlesystem == "clouds")
294 add_object(new CloudParticleSystem());
295 else if(particlesystem == "snow")
296 add_object(new SnowParticleSystem());
297 else if(particlesystem == "rain")
298 add_object(new RainParticleSystem());
300 Vector startpos(100, 170);
301 reader.get("start_pos_x", startpos.x);
302 reader.get("start_pos_y", startpos.y);
304 SpawnPoint* spawn = new SpawnPoint;
305 spawn->pos = startpos;
306 spawn->name = "main";
307 spawnpoints.push_back(spawn);
309 music = "chipdisko.ogg";
310 // skip reading music filename. It's all .ogg now, anyway
312 reader.get("music", music);
314 music = "music/" + music;
316 int width = 30, height = 15;
317 reader.get("width", width);
318 reader.get("height", height);
320 std::vector<unsigned int> tiles;
321 if(reader.get("interactive-tm", tiles)
322 || reader.get("tilemap", tiles)) {
323 TileMap* tilemap = new TileMap(level->get_tileset());
324 tilemap->set(width, height, tiles, LAYER_TILES, true);
326 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
327 for(size_t x=0; x < tilemap->get_width(); ++x) {
328 for(size_t y=0; y < tilemap->get_height(); ++y) {
329 uint32_t id = tilemap->get_tile_id(x, y);
331 tilemap->change(x, y, 1311);
335 if (height < 19) tilemap->resize(width, 19);
339 if(reader.get("background-tm", tiles)) {
340 TileMap* tilemap = new TileMap(level->get_tileset());
341 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
342 if (height < 19) tilemap->resize(width, 19);
346 if(reader.get("foreground-tm", tiles)) {
347 TileMap* tilemap = new TileMap(level->get_tileset());
348 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
350 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
351 if (height < 19) tilemap->resize(width, 19, 2035);
356 // read reset-points (now spawn-points)
357 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
359 lisp::ListIterator iter(resetpoints);
361 if(iter.item() == "point") {
363 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
365 SpawnPoint* sp = new SpawnPoint;
368 spawnpoints.push_back(sp);
371 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
377 const lisp::Lisp* objects = reader.get_lisp("objects");
379 lisp::ListIterator iter(objects);
381 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
385 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
391 Camera* camera = new Camera(this, "Camera");
394 update_game_objects();
396 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
399 update_game_objects();
403 Sector::fix_old_tiles()
405 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
406 TileMap* solids = *i;
407 for(size_t x=0; x < solids->get_width(); ++x) {
408 for(size_t y=0; y < solids->get_height(); ++y) {
409 uint32_t id = solids->get_tile_id(x, y);
410 const Tile *tile = solids->get_tile(x, y);
411 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
414 add_object(new InvisibleBlock(pos));
415 solids->change(x, y, 0);
416 } else if(tile->getAttributes() & Tile::COIN) {
417 add_object(new Coin(pos));
418 solids->change(x, y, 0);
419 } else if(tile->getAttributes() & Tile::FULLBOX) {
420 add_object(new BonusBlock(pos, tile->getData()));
421 solids->change(x, y, 0);
422 } else if(tile->getAttributes() & Tile::BRICK) {
423 add_object(new Brick(pos, tile->getData()));
424 solids->change(x, y, 0);
425 } else if(tile->getAttributes() & Tile::GOAL) {
426 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
427 add_object(new SequenceTrigger(pos, sequence));
428 solids->change(x, y, 0);
434 // add lights for special tiles
435 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
436 TileMap* tm = dynamic_cast<TileMap*>(*i);
438 for(size_t x=0; x < tm->get_width(); ++x) {
439 for(size_t y=0; y < tm->get_height(); ++y) {
440 uint32_t id = tm->get_tile_id(x, y);
441 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
442 Vector center(pos.x + 16, pos.y + 16);
446 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
447 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
450 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
451 // space lights a bit
452 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
453 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
454 || ((x % 3 == 0) && (y % 3 == 0))) {
455 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
456 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
468 Sector::write(lisp::Writer& writer)
470 writer.write("name", name);
471 writer.write("gravity", gravity);
472 writer.write("music", music);
475 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
477 SpawnPoint* spawn = *i;
478 writer.start_list("spawn-points");
479 writer.write("name", spawn->name);
480 writer.write("x", spawn->pos.x);
481 writer.write("y", spawn->pos.y);
482 writer.end_list("spawn-points");
486 for(GameObjects::iterator i = gameobjects.begin();
487 i != gameobjects.end(); ++i) {
488 Serializable* serializable = dynamic_cast<Serializable*> (*i);
490 serializable->write(writer);
495 Sector::run_script(std::istream& in, const std::string& sourcename)
497 using namespace Scripting;
499 // garbage collect thread list
500 for(ScriptList::iterator i = scripts.begin();
501 i != scripts.end(); ) {
502 HSQOBJECT& object = *i;
503 HSQUIRRELVM vm = object_to_vm(object);
505 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
506 sq_release(global_vm, &object);
507 i = scripts.erase(i);
514 HSQOBJECT object = create_thread(global_vm);
515 scripts.push_back(object);
517 HSQUIRRELVM vm = object_to_vm(object);
519 // set sector_table as roottable for the thread
520 sq_pushobject(vm, sector_table);
524 compile_and_run(vm, in, sourcename);
525 } catch(std::exception& e) {
526 log_warning << "Couldn't run script: " << e.what() << std::endl;
533 Sector::add_object(GameObject* object)
535 // make sure the object isn't already in the list
537 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
540 assert("object already added to sector" == 0);
543 for(GameObjects::iterator i = gameobjects_new.begin();
544 i != gameobjects_new.end(); ++i) {
546 assert("object already added to sector" == 0);
552 gameobjects_new.push_back(object);
556 Sector::activate(const std::string& spawnpoint)
559 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
561 if((*i)->name == spawnpoint) {
567 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
568 if(spawnpoint != "main") {
571 activate(Vector(0, 0));
579 Sector::activate(const Vector& player_pos)
581 if(_current != this) {
583 _current->deactivate();
586 // register sectortable as sector in scripting
587 HSQUIRRELVM vm = Scripting::global_vm;
588 sq_pushroottable(vm);
589 sq_pushstring(vm, "sector", -1);
590 sq_pushobject(vm, sector_table);
591 if(SQ_FAILED(sq_createslot(vm, -3)))
592 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
595 for(GameObjects::iterator i = gameobjects.begin();
596 i != gameobjects.end(); ++i) {
597 GameObject* object = *i;
604 // spawn smalltux below spawnpoint
605 if (!player->is_big()) {
606 player->move(player_pos + Vector(0,32));
608 player->move(player_pos);
611 // spawning tux in the ground would kill him
612 if(!is_free_of_tiles(player->get_bbox())) {
613 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
614 Vector npos = player->get_bbox().p1;
619 camera->reset(player->get_pos());
620 update_game_objects();
622 //Run default.nut just before init script
623 //Check to see if it's in a levelset (info file)
624 std::string basedir = FileSystem::dirname(get_level()->filename);
625 if(PHYSFS_exists((basedir + "/info").c_str())) {
627 IFileStream in(basedir + "/default.nut");
628 run_script(in, std::string("Sector(") + name + ") - default.nut");
629 } catch(std::exception& ) {
630 // doesn't exist or erroneous; do nothing
635 if(init_script != "") {
636 std::istringstream in(init_script);
637 run_script(in, std::string("Sector(") + name + ") - init");
647 // remove sector entry from global vm
648 HSQUIRRELVM vm = Scripting::global_vm;
649 sq_pushroottable(vm);
650 sq_pushstring(vm, "sector", -1);
651 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
652 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
655 for(GameObjects::iterator i = gameobjects.begin();
656 i != gameobjects.end(); ++i) {
657 GameObject* object = *i;
659 try_unexpose(object);
667 Sector::get_active_region()
670 camera->get_translation() - Vector(1600, 1200),
671 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
675 Sector::update(float elapsed_time)
677 player->check_bounds(camera);
680 for(GameObjects::iterator i = gameobjects.begin();
681 i != gameobjects.end(); ++i) {
682 GameObject* object = *i;
683 if(!object->is_valid())
686 object->update(elapsed_time);
689 /* Handle all possible collisions. */
691 update_game_objects();
695 Sector::update_game_objects()
697 /** cleanup marked objects */
698 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
699 i != gameobjects.end(); /* nothing */) {
700 GameObject* object = *i;
702 if(object->is_valid()) {
707 before_object_remove(object);
710 i = gameobjects.erase(i);
713 /* add newly created objects */
714 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
715 i != gameobjects_new.end(); ++i)
717 GameObject* object = *i;
719 before_object_add(object);
721 gameobjects.push_back(object);
723 gameobjects_new.clear();
725 /* update solid_tilemaps list */
726 //FIXME: this could be more efficient
727 solid_tilemaps.clear();
728 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
729 i != gameobjects.end(); ++i)
731 TileMap* tm = dynamic_cast<TileMap*>(*i);
733 if (tm->is_solid()) solid_tilemaps.push_back(tm);
739 Sector::before_object_add(GameObject* object)
741 Bullet* bullet = dynamic_cast<Bullet*> (object);
743 bullets.push_back(bullet);
746 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
747 if(movingobject != NULL) {
748 moving_objects.push_back(movingobject);
751 Portable* portable = dynamic_cast<Portable*> (object);
752 if(portable != NULL) {
753 portables.push_back(portable);
756 TileMap* tilemap = dynamic_cast<TileMap*> (object);
757 if(tilemap != NULL && tilemap->is_solid()) {
758 solid_tilemaps.push_back(tilemap);
761 Camera* camera = dynamic_cast<Camera*> (object);
763 if(this->camera != 0) {
764 log_warning << "Multiple cameras added. Ignoring" << std::endl;
767 this->camera = camera;
770 Player* player = dynamic_cast<Player*> (object);
772 if(this->player != 0) {
773 log_warning << "Multiple players added. Ignoring" << std::endl;
776 this->player = player;
779 DisplayEffect* effect = dynamic_cast<DisplayEffect*> (object);
781 if(this->effect != 0) {
782 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
785 this->effect = effect;
788 UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
791 physic_object->physic.set_gravity(gravity);
795 if(_current == this) {
803 Sector::try_expose(GameObject* object)
805 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
806 if(interface != NULL) {
807 HSQUIRRELVM vm = Scripting::global_vm;
808 sq_pushobject(vm, sector_table);
809 interface->expose(vm, -1);
815 Sector::try_expose_me()
817 HSQUIRRELVM vm = Scripting::global_vm;
818 sq_pushobject(vm, sector_table);
819 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
820 expose_object(vm, -1, interface, "settings", false);
825 Sector::before_object_remove(GameObject* object)
827 Portable* portable = dynamic_cast<Portable*> (object);
828 if(portable != NULL) {
829 portables.erase(std::find(portables.begin(), portables.end(), portable));
831 Bullet* bullet = dynamic_cast<Bullet*> (object);
833 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
835 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
836 if(moving_object != NULL) {
837 moving_objects.erase(
838 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
842 try_unexpose(object);
846 Sector::try_unexpose(GameObject* object)
848 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
849 if(interface != NULL) {
850 HSQUIRRELVM vm = Scripting::global_vm;
851 SQInteger oldtop = sq_gettop(vm);
852 sq_pushobject(vm, sector_table);
854 interface->unexpose(vm, -1);
855 } catch(std::exception& e) {
856 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
858 sq_settop(vm, oldtop);
863 Sector::try_unexpose_me()
865 HSQUIRRELVM vm = Scripting::global_vm;
866 SQInteger oldtop = sq_gettop(vm);
867 sq_pushobject(vm, sector_table);
869 Scripting::unexpose_object(vm, -1, "settings");
870 } catch(std::exception& e) {
871 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
873 sq_settop(vm, oldtop);
876 Sector::draw(DrawingContext& context)
878 context.set_ambient_color( ambient_light );
879 context.push_transform();
880 context.set_translation(camera->get_translation());
882 for(GameObjects::iterator i = gameobjects.begin();
883 i != gameobjects.end(); ++i) {
884 GameObject* object = *i;
885 if(!object->is_valid())
888 if (draw_solids_only)
890 TileMap* tm = dynamic_cast<TileMap*>(object);
891 if (tm && !tm->is_solid())
895 object->draw(context);
899 Color col(0.2f, 0.2f, 0.2f, 0.7f);
900 for(MovingObjects::iterator i = moving_objects.begin();
901 i != moving_objects.end(); ++i) {
902 MovingObject* object = *i;
903 const Rect& rect = object->get_bbox();
905 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
909 context.pop_transform();
912 /*-------------------------------------------------------------------------
913 * Collision Detection
914 *-------------------------------------------------------------------------*/
916 /** r1 is supposed to be moving, r2 a solid object */
917 void check_collisions(collision::Constraints* constraints,
918 const Vector& movement, const Rect& r1, const Rect& r2,
919 GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
921 if(!collision::intersects(r1, r2))
924 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
926 if(other != NULL && !other->collides(*object, dummy))
928 if(moving_object != NULL && !moving_object->collides(*other, dummy))
931 // calculate intersection
932 float itop = r1.get_bottom() - r2.get_top();
933 float ibottom = r2.get_bottom() - r1.get_top();
934 float ileft = r1.get_right() - r2.get_left();
935 float iright = r2.get_right() - r1.get_left();
937 if(fabsf(movement.y) > fabsf(movement.x)) {
938 if(ileft < SHIFT_DELTA) {
939 constraints->right = std::min(constraints->right, r2.get_left());
941 } else if(iright < SHIFT_DELTA) {
942 constraints->left = std::max(constraints->left, r2.get_right());
946 // shiftout bottom/top
947 if(itop < SHIFT_DELTA) {
948 constraints->bottom = std::min(constraints->bottom, r2.get_top());
950 } else if(ibottom < SHIFT_DELTA) {
951 constraints->top = std::max(constraints->top, r2.get_bottom());
956 constraints->ground_movement += addl_ground_movement;
958 HitResponse response = other->collision(*object, dummy);
959 if(response == PASSTHROUGH)
962 if(other->get_movement() != Vector(0, 0)) {
963 // TODO what todo when we collide with 2 moving objects?!?
964 constraints->ground_movement += other->get_movement();
968 float vert_penetration = std::min(itop, ibottom);
969 float horiz_penetration = std::min(ileft, iright);
970 if(vert_penetration < horiz_penetration) {
972 constraints->bottom = std::min(constraints->bottom, r2.get_top());
973 constraints->hit.bottom = true;
975 constraints->top = std::max(constraints->top, r2.get_bottom());
976 constraints->hit.top = true;
980 constraints->right = std::min(constraints->right, r2.get_left());
981 constraints->hit.right = true;
983 constraints->left = std::max(constraints->left, r2.get_right());
984 constraints->hit.left = true;
990 Sector::collision_tilemap(collision::Constraints* constraints,
991 const Vector& movement, const Rect& dest) const
993 // calculate rectangle where the object will move
994 float x1 = dest.get_left();
995 float x2 = dest.get_right();
996 float y1 = dest.get_top();
997 float y2 = dest.get_bottom();
999 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1000 TileMap* solids = *i;
1002 // test with all tiles in this rectangle
1003 int starttilex = int(x1 - solids->get_x_offset()) / 32;
1004 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1005 int max_x = int(x2 - solids->get_x_offset());
1006 int max_y = int(y2+1 - solids->get_y_offset());
1008 for(int x = starttilex; x*32 < max_x; ++x) {
1009 for(int y = starttiley; y*32 < max_y; ++y) {
1010 const Tile* tile = solids->get_tile(x, y);
1013 // skip non-solid tiles
1014 if((tile->getAttributes() & Tile::SOLID) == 0)
1016 // only handle unisolid when the player is falling down and when he was
1017 // above the tile before
1018 if(tile->getAttributes() & Tile::UNISOLID) {
1019 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
1023 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
1024 AATriangle triangle;
1025 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1026 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1027 triangle = AATriangle(p1, p2, tile->getData());
1029 collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
1030 } else { // normal rectangular tile
1031 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());
1032 check_collisions(constraints, movement, dest, rect, NULL, NULL, solids->get_movement());
1040 Sector::collision_tile_attributes(const Rect& dest) const
1042 float x1 = dest.p1.x;
1043 float y1 = dest.p1.y;
1044 float x2 = dest.p2.x;
1045 float y2 = dest.p2.y + SHIFT_DELTA;
1047 uint32_t result = 0;
1048 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1049 TileMap* solids = *i;
1051 // test with all tiles in this rectangle
1052 int starttilex = int(x1 - solids->get_x_offset()) / 32;
1053 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1054 int max_x = int(x2 - solids->get_x_offset());
1055 int max_y = int(y2+1 - solids->get_y_offset());
1057 for(int x = starttilex; x*32 < max_x; ++x) {
1058 for(int y = starttiley; y*32 < max_y; ++y) {
1059 const Tile* tile = solids->get_tile(x, y);
1062 result |= tile->getAttributes();
1070 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1071 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1074 float itop = r1.get_bottom() - r2.get_top();
1075 float ibottom = r2.get_bottom() - r1.get_top();
1076 float ileft = r1.get_right() - r2.get_left();
1077 float iright = r2.get_right() - r1.get_left();
1079 float vert_penetration = std::min(itop, ibottom);
1080 float horiz_penetration = std::min(ileft, iright);
1081 if(vert_penetration < horiz_penetration) {
1082 if(itop < ibottom) {
1084 normal.y = vert_penetration;
1087 normal.y = -vert_penetration;
1090 if(ileft < iright) {
1092 normal.x = horiz_penetration;
1095 normal.x = -horiz_penetration;
1101 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1103 using namespace collision;
1105 const Rect& r1 = object1->dest;
1106 const Rect& r2 = object2->dest;
1109 if(intersects(object1->dest, object2->dest)) {
1111 get_hit_normal(r1, r2, hit, normal);
1113 if(!object1->collides(*object2, hit))
1115 std::swap(hit.left, hit.right);
1116 std::swap(hit.top, hit.bottom);
1117 if(!object2->collides(*object1, hit))
1119 std::swap(hit.left, hit.right);
1120 std::swap(hit.top, hit.bottom);
1122 HitResponse response1 = object1->collision(*object2, hit);
1123 std::swap(hit.left, hit.right);
1124 std::swap(hit.top, hit.bottom);
1125 HitResponse response2 = object2->collision(*object1, hit);
1126 if(response1 == CONTINUE && response2 == CONTINUE) {
1127 normal *= (0.5 + DELTA);
1128 object1->dest.move(-normal);
1129 object2->dest.move(normal);
1130 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1131 normal *= (1 + DELTA);
1132 object1->dest.move(-normal);
1133 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1134 normal *= (1 + DELTA);
1135 object2->dest.move(normal);
1141 Sector::collision_static(collision::Constraints* constraints,
1142 const Vector& movement, const Rect& dest,
1145 collision_tilemap(constraints, movement, dest);
1147 // collision with other (static) objects
1148 for(MovingObjects::iterator i = moving_objects.begin();
1149 i != moving_objects.end(); ++i) {
1150 MovingObject* moving_object = *i;
1151 if(moving_object->get_group() != COLGROUP_STATIC
1152 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1154 if(!moving_object->is_valid())
1157 if(moving_object != &object)
1158 check_collisions(constraints, movement, dest, moving_object->bbox,
1159 &object, moving_object);
1164 Sector::collision_static_constrains(MovingObject& object)
1166 using namespace collision;
1167 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1169 Constraints constraints;
1170 Vector movement = object.get_movement();
1171 Rect& dest = object.dest;
1172 float owidth = object.get_bbox().get_width();
1173 float oheight = object.get_bbox().get_height();
1175 for(int i = 0; i < 2; ++i) {
1176 collision_static(&constraints, Vector(0, movement.y), dest, object);
1177 if(!constraints.has_constraints())
1180 // apply calculated horizontal constraints
1181 if(constraints.bottom < infinity) {
1182 float height = constraints.bottom - constraints.top;
1183 if(height < oheight) {
1184 // we're crushed, but ignore this for now, we'll get this again
1185 // later if we're really crushed or things will solve itself when
1186 // looking at the vertical constraints
1188 dest.p2.y = constraints.bottom - DELTA;
1189 dest.p1.y = dest.p2.y - oheight;
1190 } else if(constraints.top > -infinity) {
1191 dest.p1.y = constraints.top + DELTA;
1192 dest.p2.y = dest.p1.y + oheight;
1195 if(constraints.has_constraints()) {
1196 if(constraints.hit.bottom) {
1197 dest.move(constraints.ground_movement);
1199 if(constraints.hit.top || constraints.hit.bottom) {
1200 constraints.hit.left = false;
1201 constraints.hit.right = false;
1202 object.collision_solid(constraints.hit);
1206 constraints = Constraints();
1207 for(int i = 0; i < 2; ++i) {
1208 collision_static(&constraints, movement, dest, object);
1209 if(!constraints.has_constraints())
1212 // apply calculated vertical constraints
1213 if(constraints.right < infinity) {
1214 float width = constraints.right - constraints.left;
1215 if(width + SHIFT_DELTA < owidth) {
1217 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1218 constraints.left, constraints.right);
1224 object.collision_solid(h);
1226 dest.p2.x = constraints.right - DELTA;
1227 dest.p1.x = dest.p2.x - owidth;
1229 } else if(constraints.left > -infinity) {
1230 dest.p1.x = constraints.left + DELTA;
1231 dest.p2.x = dest.p1.x + owidth;
1235 if(constraints.has_constraints()) {
1236 if( constraints.hit.left || constraints.hit.right
1237 || constraints.hit.top || constraints.hit.bottom
1238 || constraints.hit.crush )
1239 object.collision_solid(constraints.hit);
1242 // an extra pass to make sure we're not crushed horizontally
1243 constraints = Constraints();
1244 collision_static(&constraints, movement, dest, object);
1245 if(constraints.bottom < infinity) {
1246 float height = constraints.bottom - constraints.top;
1247 if(height + SHIFT_DELTA < oheight) {
1249 printf("Object %p crushed vertically...\n", &object);
1255 object.collision_solid(h);
1261 const float MAX_SPEED = 16.0f;
1265 Sector::handle_collisions()
1267 using namespace collision;
1269 // calculate destination positions of the objects
1270 for(MovingObjects::iterator i = moving_objects.begin();
1271 i != moving_objects.end(); ++i) {
1272 MovingObject* moving_object = *i;
1273 Vector mov = moving_object->get_movement();
1275 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1276 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1277 moving_object->movement = mov.unit() * MAX_SPEED;
1278 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1281 moving_object->dest = moving_object->get_bbox();
1282 moving_object->dest.move(moving_object->get_movement());
1285 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1286 for(MovingObjects::iterator i = moving_objects.begin();
1287 i != moving_objects.end(); ++i) {
1288 MovingObject* moving_object = *i;
1289 if((moving_object->get_group() != COLGROUP_MOVING
1290 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1291 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1292 || !moving_object->is_valid())
1295 collision_static_constrains(*moving_object);
1299 // part2: COLGROUP_MOVING vs tile attributes
1300 for(MovingObjects::iterator i = moving_objects.begin();
1301 i != moving_objects.end(); ++i) {
1302 MovingObject* moving_object = *i;
1303 if((moving_object->get_group() != COLGROUP_MOVING
1304 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1305 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1306 || !moving_object->is_valid())
1309 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1310 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1311 moving_object->collision_tile(tile_attributes);
1315 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1316 for(MovingObjects::iterator i = moving_objects.begin();
1317 i != moving_objects.end(); ++i) {
1318 MovingObject* moving_object = *i;
1319 if((moving_object->get_group() != COLGROUP_MOVING
1320 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1321 || !moving_object->is_valid())
1324 for(MovingObjects::iterator i2 = moving_objects.begin();
1325 i2 != moving_objects.end(); ++i2) {
1326 MovingObject* moving_object_2 = *i2;
1327 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1328 || !moving_object_2->is_valid())
1331 if(intersects(moving_object->dest, moving_object_2->dest)) {
1334 get_hit_normal(moving_object->dest, moving_object_2->dest,
1336 if(!moving_object->collides(*moving_object_2, hit))
1338 if(!moving_object_2->collides(*moving_object, hit))
1341 moving_object->collision(*moving_object_2, hit);
1342 moving_object_2->collision(*moving_object, hit);
1347 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1348 for(MovingObjects::iterator i = moving_objects.begin();
1349 i != moving_objects.end(); ++i) {
1350 MovingObject* moving_object = *i;
1352 if((moving_object->get_group() != COLGROUP_MOVING
1353 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1354 || !moving_object->is_valid())
1357 for(MovingObjects::iterator i2 = i+1;
1358 i2 != moving_objects.end(); ++i2) {
1359 MovingObject* moving_object_2 = *i2;
1360 if((moving_object_2->get_group() != COLGROUP_MOVING
1361 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1362 || !moving_object_2->is_valid())
1365 collision_object(moving_object, moving_object_2);
1369 // apply object movement
1370 for(MovingObjects::iterator i = moving_objects.begin();
1371 i != moving_objects.end(); ++i) {
1372 MovingObject* moving_object = *i;
1374 moving_object->bbox = moving_object->dest;
1375 moving_object->movement = Vector(0, 0);
1380 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1382 using namespace collision;
1384 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1385 TileMap* solids = *i;
1387 // test with all tiles in this rectangle
1388 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1389 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1390 int max_x = int(rect.p2.x - solids->get_x_offset());
1391 int max_y = int(rect.p2.y - solids->get_y_offset());
1393 for(int x = starttilex; x*32 <= max_x; ++x) {
1394 for(int y = starttiley; y*32 <= max_y; ++y) {
1395 const Tile* tile = solids->get_tile(x, y);
1397 if(tile->getAttributes() & Tile::SLOPE) {
1398 AATriangle triangle;
1399 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1400 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1401 triangle = AATriangle(p1, p2, tile->getData());
1402 Constraints constraints;
1403 return collision::rectangle_aatriangle(&constraints, rect, triangle);
1405 if((tile->getAttributes() & Tile::SOLID) && !ignoreUnisolid) return false;
1406 if((tile->getAttributes() & Tile::SOLID) && !(tile->getAttributes() & Tile::UNISOLID)) return false;
1415 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1417 using namespace collision;
1419 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1421 for(MovingObjects::const_iterator i = moving_objects.begin();
1422 i != moving_objects.end(); ++i) {
1423 const MovingObject* moving_object = *i;
1424 if (moving_object == ignore_object) continue;
1425 if (!moving_object->is_valid()) continue;
1426 if (moving_object->get_group() == COLGROUP_STATIC) {
1427 if(intersects(rect, moving_object->get_bbox())) return false;
1435 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1437 using namespace collision;
1439 if (!is_free_of_tiles(rect)) return false;
1441 for(MovingObjects::const_iterator i = moving_objects.begin();
1442 i != moving_objects.end(); ++i) {
1443 const MovingObject* moving_object = *i;
1444 if (moving_object == ignore_object) continue;
1445 if (!moving_object->is_valid()) continue;
1446 if ((moving_object->get_group() == COLGROUP_MOVING)
1447 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1448 || (moving_object->get_group() == COLGROUP_STATIC)) {
1449 if(intersects(rect, moving_object->get_bbox())) return false;
1457 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1459 // TODO remove this function and move these checks elsewhere...
1461 Bullet* new_bullet = 0;
1462 if((player_status->bonus == FIRE_BONUS &&
1463 (int)bullets.size() >= player_status->max_fire_bullets) ||
1464 (player_status->bonus == ICE_BONUS &&
1465 (int)bullets.size() >= player_status->max_ice_bullets))
1467 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1468 add_object(new_bullet);
1470 sound_manager->play("sounds/shoot.wav");
1476 Sector::add_smoke_cloud(const Vector& pos)
1478 add_object(new SmokeCloud(pos));
1483 Sector::play_music(MusicType type)
1485 currentmusic = type;
1486 switch(currentmusic) {
1488 sound_manager->play_music(music);
1491 sound_manager->play_music("music/invincible.ogg");
1493 case HERRING_WARNING_MUSIC:
1494 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1497 sound_manager->play_music("");
1503 Sector::get_music_type()
1505 return currentmusic;
1509 Sector::get_total_badguys()
1511 int total_badguys = 0;
1512 for(GameObjects::iterator i = gameobjects.begin();
1513 i != gameobjects.end(); ++i) {
1514 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1515 if (badguy && badguy->countMe)
1519 return total_badguys;
1523 Sector::inside(const Rect& rect) const
1525 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1526 TileMap* solids = *i;
1527 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1528 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1530 if (horizontally && vertically)
1537 Sector::get_width() const
1540 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1541 i != solid_tilemaps.end(); i++) {
1542 TileMap* solids = *i;
1543 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1544 width = solids->get_width() * 32 + solids->get_x_offset();
1552 Sector::get_height() const
1555 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1556 i != solid_tilemaps.end(); i++) {
1557 TileMap* solids = *i;
1558 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1559 height = solids->get_height() * 32 + solids->get_y_offset();
1567 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1569 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1570 TileMap* solids = *i;
1571 solids->change_all(old_tile_id, new_tile_id);
1577 Sector::set_ambient_light(float red, float green, float blue)
1579 ambient_light.red = red;
1580 ambient_light.green = green;
1581 ambient_light.blue = blue;
1585 Sector::get_ambient_red()
1587 return ambient_light.red;
1591 Sector::get_ambient_green()
1593 return ambient_light.green;
1597 Sector::get_ambient_blue()
1599 return ambient_light.blue;
1603 Sector::set_gravity(float gravity)
1605 log_warning << "Changing a Sector's gravitational constant might have unforseen side-effects" << std::endl;
1607 this->gravity = gravity;
1609 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); ++i) {
1610 GameObject* game_object = *i;
1611 if(!game_object) continue;
1612 if(!game_object->is_valid()) continue;
1613 UsesPhysic *physics_object = dynamic_cast<UsesPhysic*>(game_object);
1614 if (!physics_object) continue;
1616 physics_object->physic.set_gravity(gravity);