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) :
60 currentmusic(LEVEL_MUSIC),
61 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ),
67 add_object(new Player(player_status, "Tux"));
68 add_object(new DisplayEffect("Effect"));
69 add_object(new TextObject("Text"));
71 sound_manager->preload("sounds/shoot.wav");
73 // create a new squirrel table for the sector
74 using namespace Scripting;
76 sq_collectgarbage(global_vm);
78 sq_newtable(global_vm);
79 sq_pushroottable(global_vm);
80 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
81 throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
83 sq_resetobject(§or_table);
84 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
85 throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
86 sq_addref(global_vm, §or_table);
92 using namespace Scripting;
96 for(ScriptList::iterator i = scripts.begin();
97 i != scripts.end(); ++i) {
98 HSQOBJECT& object = *i;
99 sq_release(global_vm, &object);
101 sq_release(global_vm, §or_table);
102 sq_collectgarbage(global_vm);
104 update_game_objects();
105 assert(gameobjects_new.size() == 0);
107 for(GameObjects::iterator i = gameobjects.begin();
108 i != gameobjects.end(); ++i) {
109 GameObject* object = *i;
110 before_object_remove(object);
114 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
126 Sector::parse_object(const std::string& name, const Reader& reader)
128 if(name == "camera") {
129 Camera* camera = new Camera(this, "Camera");
130 camera->parse(reader);
132 } else if(name == "particles-snow") {
133 SnowParticleSystem* partsys = new SnowParticleSystem();
134 partsys->parse(reader);
136 } else if(name == "particles-rain") {
137 RainParticleSystem* partsys = new RainParticleSystem();
138 partsys->parse(reader);
140 } else if(name == "particles-comets") {
141 CometParticleSystem* partsys = new CometParticleSystem();
142 partsys->parse(reader);
144 } else if(name == "particles-ghosts") {
145 GhostParticleSystem* partsys = new GhostParticleSystem();
146 partsys->parse(reader);
148 } else if(name == "particles-clouds") {
149 CloudParticleSystem* partsys = new CloudParticleSystem();
150 partsys->parse(reader);
152 } else if(name == "money") { // for compatibility with old maps
153 return new Jumpy(reader);
157 return create_object(name, reader);
158 } catch(std::exception& e) {
159 log_warning << e.what() << "" << std::endl;
166 Sector::parse(const Reader& sector)
168 bool has_background = false;
169 lisp::ListIterator iter(§or);
171 const std::string& token = iter.item();
172 if(token == "name") {
173 iter.value()->get(name);
174 } else if(token == "gravity") {
175 iter.value()->get(gravity);
176 } else if(token == "music") {
177 iter.value()->get(music);
178 } else if(token == "spawnpoint") {
179 SpawnPoint* sp = new SpawnPoint(iter.lisp());
180 spawnpoints.push_back(sp);
181 } else if(token == "init-script") {
182 iter.value()->get(init_script);
183 } else if(token == "ambient-light") {
184 std::vector<float> vColor;
185 sector.get( "ambient-light", vColor );
186 if(vColor.size() < 3) {
187 log_warning << "(ambient-light) requires a color as argument" << std::endl;
189 ambient_light = Color( vColor );
192 GameObject* object = parse_object(token, *(iter.lisp()));
194 if(dynamic_cast<Background *>(object)) {
195 has_background = true;
196 } else if(dynamic_cast<Gradient *>(object)) {
197 has_background = true;
204 if(!has_background) {
205 Gradient* gradient = new Gradient();
206 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
207 add_object(gradient);
210 update_game_objects();
212 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
216 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
217 update_game_objects();
218 add_object(new Camera(this, "Camera"));
221 update_game_objects();
225 Sector::parse_old_format(const Reader& reader)
228 reader.get("gravity", gravity);
230 std::string backgroundimage;
231 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
232 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
233 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
234 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
235 backgroundimage = "images/background/" + backgroundimage;
236 if (!PHYSFS_exists(backgroundimage.c_str())) {
237 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
238 backgroundimage = "";
243 reader.get("bkgd_speed", bgspeed);
246 Color bkgd_top, bkgd_bottom;
247 int r = 0, g = 0, b = 128;
248 reader.get("bkgd_red_top", r);
249 reader.get("bkgd_green_top", g);
250 reader.get("bkgd_blue_top", b);
251 bkgd_top.red = static_cast<float> (r) / 255.0f;
252 bkgd_top.green = static_cast<float> (g) / 255.0f;
253 bkgd_top.blue = static_cast<float> (b) / 255.0f;
255 reader.get("bkgd_red_bottom", r);
256 reader.get("bkgd_green_bottom", g);
257 reader.get("bkgd_blue_bottom", b);
258 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
259 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
260 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
262 if(backgroundimage != "") {
263 Background* background = new Background();
264 background->set_image(backgroundimage, bgspeed);
265 add_object(background);
267 Gradient* gradient = new Gradient();
268 gradient->set_gradient(bkgd_top, bkgd_bottom);
269 add_object(gradient);
272 std::string particlesystem;
273 reader.get("particle_system", particlesystem);
274 if(particlesystem == "clouds")
275 add_object(new CloudParticleSystem());
276 else if(particlesystem == "snow")
277 add_object(new SnowParticleSystem());
278 else if(particlesystem == "rain")
279 add_object(new RainParticleSystem());
281 Vector startpos(100, 170);
282 reader.get("start_pos_x", startpos.x);
283 reader.get("start_pos_y", startpos.y);
285 SpawnPoint* spawn = new SpawnPoint;
286 spawn->pos = startpos;
287 spawn->name = "main";
288 spawnpoints.push_back(spawn);
290 music = "chipdisko.ogg";
291 // skip reading music filename. It's all .ogg now, anyway
293 reader.get("music", music);
295 music = "music/" + music;
297 int width = 30, height = 15;
298 reader.get("width", width);
299 reader.get("height", height);
301 std::vector<unsigned int> tiles;
302 if(reader.get("interactive-tm", tiles)
303 || reader.get("tilemap", tiles)) {
304 TileMap* tilemap = new TileMap(level->get_tileset());
305 tilemap->set(width, height, tiles, LAYER_TILES, true);
307 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
308 for(size_t x=0; x < tilemap->get_width(); ++x) {
309 for(size_t y=0; y < tilemap->get_height(); ++y) {
310 uint32_t id = tilemap->get_tile_id(x, y);
312 tilemap->change(x, y, 1311);
316 if (height < 19) tilemap->resize(width, 19);
320 if(reader.get("background-tm", tiles)) {
321 TileMap* tilemap = new TileMap(level->get_tileset());
322 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
323 if (height < 19) tilemap->resize(width, 19);
327 if(reader.get("foreground-tm", tiles)) {
328 TileMap* tilemap = new TileMap(level->get_tileset());
329 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
331 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
332 if (height < 19) tilemap->resize(width, 19, 2035);
337 // read reset-points (now spawn-points)
338 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
340 lisp::ListIterator iter(resetpoints);
342 if(iter.item() == "point") {
344 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
346 SpawnPoint* sp = new SpawnPoint;
349 spawnpoints.push_back(sp);
352 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
358 const lisp::Lisp* objects = reader.get_lisp("objects");
360 lisp::ListIterator iter(objects);
362 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
366 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
372 Camera* camera = new Camera(this, "Camera");
375 update_game_objects();
377 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
380 update_game_objects();
384 Sector::fix_old_tiles()
386 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
387 TileMap* solids = *i;
388 for(size_t x=0; x < solids->get_width(); ++x) {
389 for(size_t y=0; y < solids->get_height(); ++y) {
390 uint32_t id = solids->get_tile_id(x, y);
391 const Tile *tile = solids->get_tile(x, y);
392 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
395 add_object(new InvisibleBlock(pos));
396 solids->change(x, y, 0);
397 } else if(tile->getAttributes() & Tile::COIN) {
398 add_object(new Coin(pos));
399 solids->change(x, y, 0);
400 } else if(tile->getAttributes() & Tile::FULLBOX) {
401 add_object(new BonusBlock(pos, tile->getData()));
402 solids->change(x, y, 0);
403 } else if(tile->getAttributes() & Tile::BRICK) {
404 add_object(new Brick(pos, tile->getData()));
405 solids->change(x, y, 0);
406 } else if(tile->getAttributes() & Tile::GOAL) {
407 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
408 add_object(new SequenceTrigger(pos, sequence));
409 solids->change(x, y, 0);
415 // add lights for special tiles
416 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
417 TileMap* tm = dynamic_cast<TileMap*>(*i);
419 for(size_t x=0; x < tm->get_width(); ++x) {
420 for(size_t y=0; y < tm->get_height(); ++y) {
421 uint32_t id = tm->get_tile_id(x, y);
422 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
423 Vector center(pos.x + 16, pos.y + 16);
427 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
428 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
431 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
432 // space lights a bit
433 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
434 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
435 || ((x % 3 == 0) && (y % 3 == 0))) {
436 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
437 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
448 Sector::run_script(std::istream& in, const std::string& sourcename)
450 using namespace Scripting;
452 // garbage collect thread list
453 for(ScriptList::iterator i = scripts.begin();
454 i != scripts.end(); ) {
455 HSQOBJECT& object = *i;
456 HSQUIRRELVM vm = object_to_vm(object);
458 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
459 sq_release(global_vm, &object);
460 i = scripts.erase(i);
467 HSQOBJECT object = create_thread(global_vm);
468 scripts.push_back(object);
470 HSQUIRRELVM vm = object_to_vm(object);
472 // set sector_table as roottable for the thread
473 sq_pushobject(vm, sector_table);
477 compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
478 } catch(std::exception& e) {
479 log_warning << "Error running script: " << e.what() << std::endl;
486 Sector::add_object(GameObject* object)
488 // make sure the object isn't already in the list
490 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
493 assert("object already added to sector" == 0);
496 for(GameObjects::iterator i = gameobjects_new.begin();
497 i != gameobjects_new.end(); ++i) {
499 assert("object already added to sector" == 0);
505 gameobjects_new.push_back(object);
509 Sector::activate(const std::string& spawnpoint)
512 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
514 if((*i)->name == spawnpoint) {
520 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
521 if(spawnpoint != "main") {
524 activate(Vector(0, 0));
532 Sector::activate(const Vector& player_pos)
534 if(_current != this) {
536 _current->deactivate();
539 // register sectortable as sector in scripting
540 HSQUIRRELVM vm = Scripting::global_vm;
541 sq_pushroottable(vm);
542 sq_pushstring(vm, "sector", -1);
543 sq_pushobject(vm, sector_table);
544 if(SQ_FAILED(sq_createslot(vm, -3)))
545 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
548 for(GameObjects::iterator i = gameobjects.begin();
549 i != gameobjects.end(); ++i) {
550 GameObject* object = *i;
557 // spawn smalltux below spawnpoint
558 if (!player->is_big()) {
559 player->move(player_pos + Vector(0,32));
561 player->move(player_pos);
564 // spawning tux in the ground would kill him
565 if(!is_free_of_tiles(player->get_bbox())) {
566 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
567 Vector npos = player->get_bbox().p1;
572 camera->reset(player->get_pos());
573 update_game_objects();
575 //Run default.nut just before init script
576 //Check to see if it's in a levelset (info file)
577 std::string basedir = FileSystem::dirname(get_level()->filename);
578 if(PHYSFS_exists((basedir + "/info").c_str())) {
580 IFileStream in(basedir + "/default.nut");
581 run_script(in, "default.nut");
582 } catch(std::exception& ) {
583 // doesn't exist or erroneous; do nothing
588 if(init_script != "") {
589 std::istringstream in(init_script);
590 run_script(in, "init-script");
600 // remove sector entry from global vm
601 HSQUIRRELVM vm = Scripting::global_vm;
602 sq_pushroottable(vm);
603 sq_pushstring(vm, "sector", -1);
604 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
605 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
608 for(GameObjects::iterator i = gameobjects.begin();
609 i != gameobjects.end(); ++i) {
610 GameObject* object = *i;
612 try_unexpose(object);
620 Sector::get_active_region()
623 camera->get_translation() - Vector(1600, 1200),
624 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
628 Sector::update(float elapsed_time)
630 player->check_bounds(camera);
633 for(GameObjects::iterator i = gameobjects.begin();
634 i != gameobjects.end(); ++i) {
635 GameObject* object = *i;
636 if(!object->is_valid())
639 object->update(elapsed_time);
642 /* Handle all possible collisions. */
644 update_game_objects();
648 Sector::update_game_objects()
650 /** cleanup marked objects */
651 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
652 i != gameobjects.end(); /* nothing */) {
653 GameObject* object = *i;
655 if(object->is_valid()) {
660 before_object_remove(object);
663 i = gameobjects.erase(i);
666 /* add newly created objects */
667 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
668 i != gameobjects_new.end(); ++i)
670 GameObject* object = *i;
672 before_object_add(object);
674 gameobjects.push_back(object);
676 gameobjects_new.clear();
678 /* update solid_tilemaps list */
679 //FIXME: this could be more efficient
680 solid_tilemaps.clear();
681 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
682 i != gameobjects.end(); ++i)
684 TileMap* tm = dynamic_cast<TileMap*>(*i);
686 if (tm->is_solid()) solid_tilemaps.push_back(tm);
692 Sector::before_object_add(GameObject* object)
694 Bullet* bullet = dynamic_cast<Bullet*> (object);
696 bullets.push_back(bullet);
699 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
700 if(movingobject != NULL) {
701 moving_objects.push_back(movingobject);
704 Portable* portable = dynamic_cast<Portable*> (object);
705 if(portable != NULL) {
706 portables.push_back(portable);
709 TileMap* tilemap = dynamic_cast<TileMap*> (object);
710 if(tilemap != NULL && tilemap->is_solid()) {
711 solid_tilemaps.push_back(tilemap);
714 Camera* camera = dynamic_cast<Camera*> (object);
716 if(this->camera != 0) {
717 log_warning << "Multiple cameras added. Ignoring" << std::endl;
720 this->camera = camera;
723 Player* player = dynamic_cast<Player*> (object);
725 if(this->player != 0) {
726 log_warning << "Multiple players added. Ignoring" << std::endl;
729 this->player = player;
732 DisplayEffect* effect = dynamic_cast<DisplayEffect*> (object);
734 if(this->effect != 0) {
735 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
738 this->effect = effect;
741 if(_current == this) {
749 Sector::try_expose(GameObject* object)
751 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
752 if(interface != NULL) {
753 HSQUIRRELVM vm = Scripting::global_vm;
754 sq_pushobject(vm, sector_table);
755 interface->expose(vm, -1);
761 Sector::try_expose_me()
763 HSQUIRRELVM vm = Scripting::global_vm;
764 sq_pushobject(vm, sector_table);
765 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
766 expose_object(vm, -1, interface, "settings", false);
771 Sector::before_object_remove(GameObject* object)
773 Portable* portable = dynamic_cast<Portable*> (object);
774 if(portable != NULL) {
775 portables.erase(std::find(portables.begin(), portables.end(), portable));
777 Bullet* bullet = dynamic_cast<Bullet*> (object);
779 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
781 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
782 if(moving_object != NULL) {
783 moving_objects.erase(
784 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
788 try_unexpose(object);
792 Sector::try_unexpose(GameObject* object)
794 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
795 if(interface != NULL) {
796 HSQUIRRELVM vm = Scripting::global_vm;
797 SQInteger oldtop = sq_gettop(vm);
798 sq_pushobject(vm, sector_table);
800 interface->unexpose(vm, -1);
801 } catch(std::exception& e) {
802 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
804 sq_settop(vm, oldtop);
809 Sector::try_unexpose_me()
811 HSQUIRRELVM vm = Scripting::global_vm;
812 SQInteger oldtop = sq_gettop(vm);
813 sq_pushobject(vm, sector_table);
815 Scripting::unexpose_object(vm, -1, "settings");
816 } catch(std::exception& e) {
817 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
819 sq_settop(vm, oldtop);
822 Sector::draw(DrawingContext& context)
824 context.set_ambient_color( ambient_light );
825 context.push_transform();
826 context.set_translation(camera->get_translation());
828 for(GameObjects::iterator i = gameobjects.begin();
829 i != gameobjects.end(); ++i) {
830 GameObject* object = *i;
831 if(!object->is_valid())
834 if (draw_solids_only)
836 TileMap* tm = dynamic_cast<TileMap*>(object);
837 if (tm && !tm->is_solid())
841 object->draw(context);
845 Color col(0.2f, 0.2f, 0.2f, 0.7f);
846 for(MovingObjects::iterator i = moving_objects.begin();
847 i != moving_objects.end(); ++i) {
848 MovingObject* object = *i;
849 const Rect& rect = object->get_bbox();
851 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
855 context.pop_transform();
858 /*-------------------------------------------------------------------------
859 * Collision Detection
860 *-------------------------------------------------------------------------*/
862 /** r1 is supposed to be moving, r2 a solid object */
863 void check_collisions(collision::Constraints* constraints,
864 const Vector& movement, const Rect& r1, const Rect& r2,
865 GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
867 if(!collision::intersects(r1, r2))
870 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
872 if(other != NULL && !other->collides(*object, dummy))
874 if(moving_object != NULL && !moving_object->collides(*other, dummy))
877 // calculate intersection
878 float itop = r1.get_bottom() - r2.get_top();
879 float ibottom = r2.get_bottom() - r1.get_top();
880 float ileft = r1.get_right() - r2.get_left();
881 float iright = r2.get_right() - r1.get_left();
883 if(fabsf(movement.y) > fabsf(movement.x)) {
884 if(ileft < SHIFT_DELTA) {
885 constraints->right = std::min(constraints->right, r2.get_left());
887 } else if(iright < SHIFT_DELTA) {
888 constraints->left = std::max(constraints->left, r2.get_right());
892 // shiftout bottom/top
893 if(itop < SHIFT_DELTA) {
894 constraints->bottom = std::min(constraints->bottom, r2.get_top());
896 } else if(ibottom < SHIFT_DELTA) {
897 constraints->top = std::max(constraints->top, r2.get_bottom());
902 constraints->ground_movement += addl_ground_movement;
904 HitResponse response = other->collision(*object, dummy);
905 if(response == PASSTHROUGH)
908 if(other->get_movement() != Vector(0, 0)) {
909 // TODO what todo when we collide with 2 moving objects?!?
910 constraints->ground_movement = other->get_movement();
914 float vert_penetration = std::min(itop, ibottom);
915 float horiz_penetration = std::min(ileft, iright);
916 if(vert_penetration < horiz_penetration) {
918 constraints->bottom = std::min(constraints->bottom, r2.get_top());
919 constraints->hit.bottom = true;
921 constraints->top = std::max(constraints->top, r2.get_bottom());
922 constraints->hit.top = true;
926 constraints->right = std::min(constraints->right, r2.get_left());
927 constraints->hit.right = true;
929 constraints->left = std::max(constraints->left, r2.get_right());
930 constraints->hit.left = true;
936 Sector::collision_tilemap(collision::Constraints* constraints,
937 const Vector& movement, const Rect& dest) const
939 // calculate rectangle where the object will move
940 float x1 = dest.get_left();
941 float x2 = dest.get_right();
942 float y1 = dest.get_top();
943 float y2 = dest.get_bottom();
945 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
946 TileMap* solids = *i;
948 // test with all tiles in this rectangle
949 int starttilex = int(x1 - solids->get_x_offset()) / 32;
950 int starttiley = int(y1 - solids->get_y_offset()) / 32;
951 int max_x = int(x2 - solids->get_x_offset());
952 int max_y = int(y2+1 - solids->get_y_offset());
954 for(int x = starttilex; x*32 < max_x; ++x) {
955 for(int y = starttiley; y*32 < max_y; ++y) {
956 const Tile* tile = solids->get_tile(x, y);
959 // skip non-solid tiles
960 if((tile->getAttributes() & Tile::SOLID) == 0)
962 // only handle unisolid when the player is falling down and when he was
963 // above the tile before
964 if(tile->getAttributes() & Tile::UNISOLID) {
965 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
969 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
971 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
972 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
973 triangle = AATriangle(p1, p2, tile->getData());
975 collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
976 } else { // normal rectangular tile
977 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());
978 check_collisions(constraints, movement, dest, rect, NULL, NULL, solids->get_movement());
986 Sector::collision_tile_attributes(const Rect& dest) const
988 float x1 = dest.p1.x;
989 float y1 = dest.p1.y;
990 float x2 = dest.p2.x;
991 float y2 = dest.p2.y + SHIFT_DELTA;
994 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
995 TileMap* solids = *i;
997 // test with all tiles in this rectangle
998 int starttilex = int(x1 - solids->get_x_offset()) / 32;
999 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1000 int max_x = int(x2 - solids->get_x_offset());
1001 int max_y = int(y2+1 - solids->get_y_offset());
1003 for(int x = starttilex; x*32 < max_x; ++x) {
1004 for(int y = starttiley; y*32 < max_y; ++y) {
1005 const Tile* tile = solids->get_tile(x, y);
1008 result |= tile->getAttributes();
1016 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1017 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1020 float itop = r1.get_bottom() - r2.get_top();
1021 float ibottom = r2.get_bottom() - r1.get_top();
1022 float ileft = r1.get_right() - r2.get_left();
1023 float iright = r2.get_right() - r1.get_left();
1025 float vert_penetration = std::min(itop, ibottom);
1026 float horiz_penetration = std::min(ileft, iright);
1027 if(vert_penetration < horiz_penetration) {
1028 if(itop < ibottom) {
1030 normal.y = vert_penetration;
1033 normal.y = -vert_penetration;
1036 if(ileft < iright) {
1038 normal.x = horiz_penetration;
1041 normal.x = -horiz_penetration;
1047 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1049 using namespace collision;
1051 const Rect& r1 = object1->dest;
1052 const Rect& r2 = object2->dest;
1055 if(intersects(object1->dest, object2->dest)) {
1057 get_hit_normal(r1, r2, hit, normal);
1059 if(!object1->collides(*object2, hit))
1061 std::swap(hit.left, hit.right);
1062 std::swap(hit.top, hit.bottom);
1063 if(!object2->collides(*object1, hit))
1065 std::swap(hit.left, hit.right);
1066 std::swap(hit.top, hit.bottom);
1068 HitResponse response1 = object1->collision(*object2, hit);
1069 std::swap(hit.left, hit.right);
1070 std::swap(hit.top, hit.bottom);
1071 HitResponse response2 = object2->collision(*object1, hit);
1072 if(response1 == CONTINUE && response2 == CONTINUE) {
1073 normal *= (0.5 + DELTA);
1074 object1->dest.move(-normal);
1075 object2->dest.move(normal);
1076 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1077 normal *= (1 + DELTA);
1078 object1->dest.move(-normal);
1079 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1080 normal *= (1 + DELTA);
1081 object2->dest.move(normal);
1087 Sector::collision_static(collision::Constraints* constraints,
1088 const Vector& movement, const Rect& dest,
1091 collision_tilemap(constraints, movement, dest);
1093 // collision with other (static) objects
1094 for(MovingObjects::iterator i = moving_objects.begin();
1095 i != moving_objects.end(); ++i) {
1096 MovingObject* moving_object = *i;
1097 if(moving_object->get_group() != COLGROUP_STATIC
1098 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1100 if(!moving_object->is_valid())
1103 if(moving_object != &object)
1104 check_collisions(constraints, movement, dest, moving_object->bbox,
1105 &object, moving_object);
1110 Sector::collision_static_constrains(MovingObject& object)
1112 using namespace collision;
1113 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1115 Constraints constraints;
1116 Vector movement = object.get_movement();
1117 Rect& dest = object.dest;
1118 float owidth = object.get_bbox().get_width();
1119 float oheight = object.get_bbox().get_height();
1121 for(int i = 0; i < 2; ++i) {
1122 collision_static(&constraints, Vector(0, movement.y), dest, object);
1123 if(!constraints.has_constraints())
1126 // apply calculated horizontal constraints
1127 if(constraints.bottom < infinity) {
1128 float height = constraints.bottom - constraints.top;
1129 if(height < oheight) {
1130 // we're crushed, but ignore this for now, we'll get this again
1131 // later if we're really crushed or things will solve itself when
1132 // looking at the vertical constraints
1134 dest.p2.y = constraints.bottom - DELTA;
1135 dest.p1.y = dest.p2.y - oheight;
1136 } else if(constraints.top > -infinity) {
1137 dest.p1.y = constraints.top + DELTA;
1138 dest.p2.y = dest.p1.y + oheight;
1141 if(constraints.has_constraints()) {
1142 if(constraints.hit.bottom) {
1143 dest.move(constraints.ground_movement);
1145 if(constraints.hit.top || constraints.hit.bottom) {
1146 constraints.hit.left = false;
1147 constraints.hit.right = false;
1148 object.collision_solid(constraints.hit);
1152 constraints = Constraints();
1153 for(int i = 0; i < 2; ++i) {
1154 collision_static(&constraints, movement, dest, object);
1155 if(!constraints.has_constraints())
1158 // apply calculated vertical constraints
1159 if(constraints.right < infinity) {
1160 float width = constraints.right - constraints.left;
1161 if(width + SHIFT_DELTA < owidth) {
1163 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1164 constraints.left, constraints.right);
1170 object.collision_solid(h);
1172 dest.p2.x = constraints.right - DELTA;
1173 dest.p1.x = dest.p2.x - owidth;
1175 } else if(constraints.left > -infinity) {
1176 dest.p1.x = constraints.left + DELTA;
1177 dest.p2.x = dest.p1.x + owidth;
1181 if(constraints.has_constraints()) {
1182 if( constraints.hit.left || constraints.hit.right
1183 || constraints.hit.top || constraints.hit.bottom
1184 || constraints.hit.crush )
1185 object.collision_solid(constraints.hit);
1188 // an extra pass to make sure we're not crushed horizontally
1189 constraints = Constraints();
1190 collision_static(&constraints, movement, dest, object);
1191 if(constraints.bottom < infinity) {
1192 float height = constraints.bottom - constraints.top;
1193 if(height + SHIFT_DELTA < oheight) {
1195 printf("Object %p crushed vertically...\n", &object);
1201 object.collision_solid(h);
1207 const float MAX_SPEED = 16.0f;
1211 Sector::handle_collisions()
1213 using namespace collision;
1215 // calculate destination positions of the objects
1216 for(MovingObjects::iterator i = moving_objects.begin();
1217 i != moving_objects.end(); ++i) {
1218 MovingObject* moving_object = *i;
1219 Vector mov = moving_object->get_movement();
1221 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1222 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1223 moving_object->movement = mov.unit() * MAX_SPEED;
1224 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1227 moving_object->dest = moving_object->get_bbox();
1228 moving_object->dest.move(moving_object->get_movement());
1231 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1232 for(MovingObjects::iterator i = moving_objects.begin();
1233 i != moving_objects.end(); ++i) {
1234 MovingObject* moving_object = *i;
1235 if((moving_object->get_group() != COLGROUP_MOVING
1236 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1237 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1238 || !moving_object->is_valid())
1241 collision_static_constrains(*moving_object);
1244 // part2: COLGROUP_MOVING vs tile attributes
1245 for(MovingObjects::iterator i = moving_objects.begin();
1246 i != moving_objects.end(); ++i) {
1247 MovingObject* moving_object = *i;
1248 if((moving_object->get_group() != COLGROUP_MOVING
1249 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1250 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1251 || !moving_object->is_valid())
1254 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1255 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1256 moving_object->collision_tile(tile_attributes);
1260 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1261 for(MovingObjects::iterator i = moving_objects.begin();
1262 i != moving_objects.end(); ++i) {
1263 MovingObject* moving_object = *i;
1264 if((moving_object->get_group() != COLGROUP_MOVING
1265 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1266 || !moving_object->is_valid())
1269 for(MovingObjects::iterator i2 = moving_objects.begin();
1270 i2 != moving_objects.end(); ++i2) {
1271 MovingObject* moving_object_2 = *i2;
1272 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1273 || !moving_object_2->is_valid())
1276 if(intersects(moving_object->dest, moving_object_2->dest)) {
1279 get_hit_normal(moving_object->dest, moving_object_2->dest,
1281 if(!moving_object->collides(*moving_object_2, hit))
1283 if(!moving_object_2->collides(*moving_object, hit))
1286 moving_object->collision(*moving_object_2, hit);
1287 moving_object_2->collision(*moving_object, hit);
1292 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1293 for(MovingObjects::iterator i = moving_objects.begin();
1294 i != moving_objects.end(); ++i) {
1295 MovingObject* moving_object = *i;
1297 if((moving_object->get_group() != COLGROUP_MOVING
1298 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1299 || !moving_object->is_valid())
1302 for(MovingObjects::iterator i2 = i+1;
1303 i2 != moving_objects.end(); ++i2) {
1304 MovingObject* moving_object_2 = *i2;
1305 if((moving_object_2->get_group() != COLGROUP_MOVING
1306 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1307 || !moving_object_2->is_valid())
1310 collision_object(moving_object, moving_object_2);
1314 // apply object movement
1315 for(MovingObjects::iterator i = moving_objects.begin();
1316 i != moving_objects.end(); ++i) {
1317 MovingObject* moving_object = *i;
1319 moving_object->bbox = moving_object->dest;
1320 moving_object->movement = Vector(0, 0);
1325 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1327 using namespace collision;
1329 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1330 TileMap* solids = *i;
1332 // test with all tiles in this rectangle
1333 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1334 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1335 int max_x = int(rect.p2.x - solids->get_x_offset());
1336 int max_y = int(rect.p2.y - solids->get_y_offset());
1338 for(int x = starttilex; x*32 <= max_x; ++x) {
1339 for(int y = starttiley; y*32 <= max_y; ++y) {
1340 const Tile* tile = solids->get_tile(x, y);
1342 if(tile->getAttributes() & Tile::SLOPE) {
1343 AATriangle triangle;
1344 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1345 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1346 triangle = AATriangle(p1, p2, tile->getData());
1347 Constraints constraints;
1348 if(collision::rectangle_aatriangle(&constraints, rect, triangle) && (!ignoreUnisolid || !(tile->getAttributes() & Tile::UNISOLID))) return false;
1350 if((tile->getAttributes() & Tile::SOLID) && (!ignoreUnisolid || !(tile->getAttributes() & Tile::UNISOLID))) return false;
1359 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1361 using namespace collision;
1363 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1365 for(MovingObjects::const_iterator i = moving_objects.begin();
1366 i != moving_objects.end(); ++i) {
1367 const MovingObject* moving_object = *i;
1368 if (moving_object == ignore_object) continue;
1369 if (!moving_object->is_valid()) continue;
1370 if (moving_object->get_group() == COLGROUP_STATIC) {
1371 if(intersects(rect, moving_object->get_bbox())) return false;
1379 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1381 using namespace collision;
1383 if (!is_free_of_tiles(rect)) 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_MOVING)
1391 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1392 || (moving_object->get_group() == COLGROUP_STATIC)) {
1393 if(intersects(rect, moving_object->get_bbox())) return false;
1401 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1403 // TODO remove this function and move these checks elsewhere...
1405 Bullet* new_bullet = 0;
1406 if((player_status->bonus == FIRE_BONUS &&
1407 (int)bullets.size() >= player_status->max_fire_bullets) ||
1408 (player_status->bonus == ICE_BONUS &&
1409 (int)bullets.size() >= player_status->max_ice_bullets))
1411 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1412 add_object(new_bullet);
1414 sound_manager->play("sounds/shoot.wav");
1420 Sector::add_smoke_cloud(const Vector& pos)
1422 add_object(new SmokeCloud(pos));
1427 Sector::play_music(MusicType type)
1429 currentmusic = type;
1430 switch(currentmusic) {
1432 sound_manager->play_music(music);
1435 sound_manager->play_music("music/invincible.music");
1437 case HERRING_WARNING_MUSIC:
1438 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1441 sound_manager->play_music("");
1447 Sector::get_music_type()
1449 return currentmusic;
1453 Sector::get_total_badguys()
1455 int total_badguys = 0;
1456 for(GameObjects::iterator i = gameobjects.begin();
1457 i != gameobjects.end(); ++i) {
1458 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1459 if (badguy && badguy->countMe)
1463 return total_badguys;
1467 Sector::inside(const Rect& rect) const
1469 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1470 TileMap* solids = *i;
1471 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1472 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1474 if (horizontally && vertically)
1481 Sector::get_width() const
1484 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1485 i != solid_tilemaps.end(); i++) {
1486 TileMap* solids = *i;
1487 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1488 width = solids->get_width() * 32 + solids->get_x_offset();
1496 Sector::get_height() const
1499 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1500 i != solid_tilemaps.end(); i++) {
1501 TileMap* solids = *i;
1502 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1503 height = solids->get_height() * 32 + solids->get_y_offset();
1511 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1513 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1514 TileMap* solids = *i;
1515 solids->change_all(old_tile_id, new_tile_id);
1520 Sector::set_ambient_light(float red, float green, float blue)
1522 ambient_light.red = red;
1523 ambient_light.green = green;
1524 ambient_light.blue = blue;
1528 Sector::get_ambient_red()
1530 return ambient_light.red;
1534 Sector::get_ambient_green()
1536 return ambient_light.green;
1540 Sector::get_ambient_blue()
1542 return ambient_light.blue;
1546 Sector::set_gravity(float gravity)
1548 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1549 this->gravity = gravity;
1553 Sector::get_gravity() const