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/cloud_particle_system.hpp"
35 #include "object/ghost_particle_system.hpp"
36 #include "object/snow_particle_system.hpp"
37 #include "object/particlesystem_interactive.hpp"
38 #include "object/player.hpp"
39 #include "object/portable.hpp"
40 #include "object/pulsing_light.hpp"
41 #include "object/smoke_cloud.hpp"
42 #include "object/text_object.hpp"
43 #include "object/tilemap.hpp"
44 #include "physfs/physfs_stream.hpp"
45 #include "scripting/squirrel_util.hpp"
46 #include "supertux/collision.hpp"
47 #include "supertux/constants.hpp"
48 #include "supertux/level.hpp"
49 #include "supertux/main.hpp"
50 #include "supertux/object_factory.hpp"
51 #include "supertux/spawn_point.hpp"
52 #include "supertux/tile.hpp"
53 #include "trigger/sequence_trigger.hpp"
54 #include "util/file_system.hpp"
56 Sector* Sector::_current = 0;
58 bool Sector::show_collrects = false;
59 bool Sector::draw_solids_only = false;
61 Sector::Sector(Level* parent) :
67 currentmusic(LEVEL_MUSIC),
70 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ),
82 add_object(new Player(player_status, "Tux"));
83 add_object(new DisplayEffect("Effect"));
84 add_object(new TextObject("Text"));
86 sound_manager->preload("sounds/shoot.wav");
88 // create a new squirrel table for the sector
89 using namespace Scripting;
91 sq_collectgarbage(global_vm);
93 sq_newtable(global_vm);
94 sq_pushroottable(global_vm);
95 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
96 throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
98 sq_resetobject(§or_table);
99 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
100 throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
101 sq_addref(global_vm, §or_table);
102 sq_pop(global_vm, 1);
107 using namespace Scripting;
111 for(ScriptList::iterator i = scripts.begin();
112 i != scripts.end(); ++i) {
113 HSQOBJECT& object = *i;
114 sq_release(global_vm, &object);
116 sq_release(global_vm, §or_table);
117 sq_collectgarbage(global_vm);
119 update_game_objects();
120 assert(gameobjects_new.size() == 0);
122 for(GameObjects::iterator i = gameobjects.begin();
123 i != gameobjects.end(); ++i) {
124 GameObject* object = *i;
125 before_object_remove(object);
129 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
141 Sector::parse_object(const std::string& name, const Reader& reader)
143 if(name == "camera") {
144 Camera* camera = new Camera(this, "Camera");
145 camera->parse(reader);
147 } else if(name == "particles-snow") {
148 SnowParticleSystem* partsys = new SnowParticleSystem();
149 partsys->parse(reader);
151 } else if(name == "particles-rain") {
152 RainParticleSystem* partsys = new RainParticleSystem();
153 partsys->parse(reader);
155 } else if(name == "particles-comets") {
156 CometParticleSystem* partsys = new CometParticleSystem();
157 partsys->parse(reader);
159 } else if(name == "particles-ghosts") {
160 GhostParticleSystem* partsys = new GhostParticleSystem();
161 partsys->parse(reader);
163 } else if(name == "particles-clouds") {
164 CloudParticleSystem* partsys = new CloudParticleSystem();
165 partsys->parse(reader);
167 } else if(name == "money") { // for compatibility with old maps
168 return new Jumpy(reader);
172 return create_object(name, reader);
173 } catch(std::exception& e) {
174 log_warning << e.what() << "" << std::endl;
181 Sector::parse(const Reader& sector)
183 bool has_background = false;
184 lisp::ListIterator iter(§or);
186 const std::string& token = iter.item();
187 if(token == "name") {
188 iter.value()->get(name);
189 } else if(token == "gravity") {
190 iter.value()->get(gravity);
191 } else if(token == "music") {
192 iter.value()->get(music);
193 } else if(token == "spawnpoint") {
194 SpawnPoint* sp = new SpawnPoint(iter.lisp());
195 spawnpoints.push_back(sp);
196 } else if(token == "init-script") {
197 iter.value()->get(init_script);
198 } else if(token == "ambient-light") {
199 std::vector<float> vColor;
200 sector.get( "ambient-light", vColor );
201 if(vColor.size() < 3) {
202 log_warning << "(ambient-light) requires a color as argument" << std::endl;
204 ambient_light = Color( vColor );
207 GameObject* object = parse_object(token, *(iter.lisp()));
209 if(dynamic_cast<Background *>(object)) {
210 has_background = true;
211 } else if(dynamic_cast<Gradient *>(object)) {
212 has_background = true;
219 if(!has_background) {
220 Gradient* gradient = new Gradient();
221 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
222 add_object(gradient);
225 update_game_objects();
227 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
231 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
232 update_game_objects();
233 add_object(new Camera(this, "Camera"));
236 update_game_objects();
240 Sector::parse_old_format(const Reader& reader)
243 reader.get("gravity", gravity);
245 std::string backgroundimage;
246 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
247 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
248 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
249 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
250 backgroundimage = "images/background/" + backgroundimage;
251 if (!PHYSFS_exists(backgroundimage.c_str())) {
252 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
253 backgroundimage = "";
258 reader.get("bkgd_speed", bgspeed);
261 Color bkgd_top, bkgd_bottom;
262 int r = 0, g = 0, b = 128;
263 reader.get("bkgd_red_top", r);
264 reader.get("bkgd_green_top", g);
265 reader.get("bkgd_blue_top", b);
266 bkgd_top.red = static_cast<float> (r) / 255.0f;
267 bkgd_top.green = static_cast<float> (g) / 255.0f;
268 bkgd_top.blue = static_cast<float> (b) / 255.0f;
270 reader.get("bkgd_red_bottom", r);
271 reader.get("bkgd_green_bottom", g);
272 reader.get("bkgd_blue_bottom", b);
273 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
274 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
275 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
277 if(backgroundimage != "") {
278 Background* background = new Background();
279 background->set_image(backgroundimage, bgspeed);
280 add_object(background);
282 Gradient* gradient = new Gradient();
283 gradient->set_gradient(bkgd_top, bkgd_bottom);
284 add_object(gradient);
287 std::string particlesystem;
288 reader.get("particle_system", particlesystem);
289 if(particlesystem == "clouds")
290 add_object(new CloudParticleSystem());
291 else if(particlesystem == "snow")
292 add_object(new SnowParticleSystem());
293 else if(particlesystem == "rain")
294 add_object(new RainParticleSystem());
296 Vector startpos(100, 170);
297 reader.get("start_pos_x", startpos.x);
298 reader.get("start_pos_y", startpos.y);
300 SpawnPoint* spawn = new SpawnPoint;
301 spawn->pos = startpos;
302 spawn->name = "main";
303 spawnpoints.push_back(spawn);
305 music = "chipdisko.ogg";
306 // skip reading music filename. It's all .ogg now, anyway
308 reader.get("music", music);
310 music = "music/" + music;
312 int width = 30, height = 15;
313 reader.get("width", width);
314 reader.get("height", height);
316 std::vector<unsigned int> tiles;
317 if(reader.get("interactive-tm", tiles)
318 || reader.get("tilemap", tiles)) {
319 TileMap* tilemap = new TileMap(level->get_tileset());
320 tilemap->set(width, height, tiles, LAYER_TILES, true);
322 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
323 for(size_t x=0; x < tilemap->get_width(); ++x) {
324 for(size_t y=0; y < tilemap->get_height(); ++y) {
325 uint32_t id = tilemap->get_tile_id(x, y);
327 tilemap->change(x, y, 1311);
331 if (height < 19) tilemap->resize(width, 19);
335 if(reader.get("background-tm", tiles)) {
336 TileMap* tilemap = new TileMap(level->get_tileset());
337 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
338 if (height < 19) tilemap->resize(width, 19);
342 if(reader.get("foreground-tm", tiles)) {
343 TileMap* tilemap = new TileMap(level->get_tileset());
344 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
346 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
347 if (height < 19) tilemap->resize(width, 19, 2035);
352 // read reset-points (now spawn-points)
353 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
355 lisp::ListIterator iter(resetpoints);
357 if(iter.item() == "point") {
359 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
361 SpawnPoint* sp = new SpawnPoint;
364 spawnpoints.push_back(sp);
367 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
373 const lisp::Lisp* objects = reader.get_lisp("objects");
375 lisp::ListIterator iter(objects);
377 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
381 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
387 Camera* camera = new Camera(this, "Camera");
390 update_game_objects();
392 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
395 update_game_objects();
399 Sector::fix_old_tiles()
401 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
402 TileMap* solids = *i;
403 for(size_t x=0; x < solids->get_width(); ++x) {
404 for(size_t y=0; y < solids->get_height(); ++y) {
405 uint32_t id = solids->get_tile_id(x, y);
406 const Tile *tile = solids->get_tile(x, y);
407 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
410 add_object(new InvisibleBlock(pos));
411 solids->change(x, y, 0);
412 } else if(tile->getAttributes() & Tile::COIN) {
413 add_object(new Coin(pos));
414 solids->change(x, y, 0);
415 } else if(tile->getAttributes() & Tile::FULLBOX) {
416 add_object(new BonusBlock(pos, tile->getData()));
417 solids->change(x, y, 0);
418 } else if(tile->getAttributes() & Tile::BRICK) {
419 add_object(new Brick(pos, tile->getData()));
420 solids->change(x, y, 0);
421 } else if(tile->getAttributes() & Tile::GOAL) {
422 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
423 add_object(new SequenceTrigger(pos, sequence));
424 solids->change(x, y, 0);
430 // add lights for special tiles
431 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
432 TileMap* tm = dynamic_cast<TileMap*>(*i);
434 for(size_t x=0; x < tm->get_width(); ++x) {
435 for(size_t y=0; y < tm->get_height(); ++y) {
436 uint32_t id = tm->get_tile_id(x, y);
437 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
438 Vector center(pos.x + 16, pos.y + 16);
442 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
443 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
446 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
447 // space lights a bit
448 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
449 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
450 || ((x % 3 == 0) && (y % 3 == 0))) {
451 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
452 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
463 Sector::run_script(std::istream& in, const std::string& sourcename)
465 using namespace Scripting;
467 // garbage collect thread list
468 for(ScriptList::iterator i = scripts.begin();
469 i != scripts.end(); ) {
470 HSQOBJECT& object = *i;
471 HSQUIRRELVM vm = object_to_vm(object);
473 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
474 sq_release(global_vm, &object);
475 i = scripts.erase(i);
482 HSQOBJECT object = create_thread(global_vm);
483 scripts.push_back(object);
485 HSQUIRRELVM vm = object_to_vm(object);
487 // set sector_table as roottable for the thread
488 sq_pushobject(vm, sector_table);
492 compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
493 } catch(std::exception& e) {
494 log_warning << "Error running script: " << e.what() << std::endl;
501 Sector::add_object(GameObject* object)
503 // make sure the object isn't already in the list
505 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
508 assert("object already added to sector" == 0);
511 for(GameObjects::iterator i = gameobjects_new.begin();
512 i != gameobjects_new.end(); ++i) {
514 assert("object already added to sector" == 0);
520 gameobjects_new.push_back(object);
524 Sector::activate(const std::string& spawnpoint)
527 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
529 if((*i)->name == spawnpoint) {
535 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
536 if(spawnpoint != "main") {
539 activate(Vector(0, 0));
547 Sector::activate(const Vector& player_pos)
549 if(_current != this) {
551 _current->deactivate();
554 // register sectortable as sector in scripting
555 HSQUIRRELVM vm = Scripting::global_vm;
556 sq_pushroottable(vm);
557 sq_pushstring(vm, "sector", -1);
558 sq_pushobject(vm, sector_table);
559 if(SQ_FAILED(sq_createslot(vm, -3)))
560 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
563 for(GameObjects::iterator i = gameobjects.begin();
564 i != gameobjects.end(); ++i) {
565 GameObject* object = *i;
572 // spawn smalltux below spawnpoint
573 if (!player->is_big()) {
574 player->move(player_pos + Vector(0,32));
576 player->move(player_pos);
579 // spawning tux in the ground would kill him
580 if(!is_free_of_tiles(player->get_bbox())) {
581 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
582 Vector npos = player->get_bbox().p1;
587 camera->reset(player->get_pos());
588 update_game_objects();
590 //Run default.nut just before init script
591 //Check to see if it's in a levelset (info file)
592 std::string basedir = FileSystem::dirname(get_level()->filename);
593 if(PHYSFS_exists((basedir + "/info").c_str())) {
595 IFileStream in(basedir + "/default.nut");
596 run_script(in, "default.nut");
597 } catch(std::exception& ) {
598 // doesn't exist or erroneous; do nothing
603 if(init_script != "") {
604 std::istringstream in(init_script);
605 run_script(in, "init-script");
615 // remove sector entry from global vm
616 HSQUIRRELVM vm = Scripting::global_vm;
617 sq_pushroottable(vm);
618 sq_pushstring(vm, "sector", -1);
619 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
620 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
623 for(GameObjects::iterator i = gameobjects.begin();
624 i != gameobjects.end(); ++i) {
625 GameObject* object = *i;
627 try_unexpose(object);
635 Sector::get_active_region()
638 camera->get_translation() - Vector(1600, 1200),
639 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
643 Sector::update(float elapsed_time)
645 player->check_bounds(camera);
648 for(GameObjects::iterator i = gameobjects.begin();
649 i != gameobjects.end(); ++i) {
650 GameObject* object = *i;
651 if(!object->is_valid())
654 object->update(elapsed_time);
657 /* Handle all possible collisions. */
659 update_game_objects();
663 Sector::update_game_objects()
665 /** cleanup marked objects */
666 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
667 i != gameobjects.end(); /* nothing */) {
668 GameObject* object = *i;
670 if(object->is_valid()) {
675 before_object_remove(object);
678 i = gameobjects.erase(i);
681 /* add newly created objects */
682 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
683 i != gameobjects_new.end(); ++i)
685 GameObject* object = *i;
687 before_object_add(object);
689 gameobjects.push_back(object);
691 gameobjects_new.clear();
693 /* update solid_tilemaps list */
694 //FIXME: this could be more efficient
695 solid_tilemaps.clear();
696 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
697 i != gameobjects.end(); ++i)
699 TileMap* tm = dynamic_cast<TileMap*>(*i);
701 if (tm->is_solid()) solid_tilemaps.push_back(tm);
707 Sector::before_object_add(GameObject* object)
709 Bullet* bullet = dynamic_cast<Bullet*> (object);
711 bullets.push_back(bullet);
714 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
715 if(movingobject != NULL) {
716 moving_objects.push_back(movingobject);
719 Portable* portable = dynamic_cast<Portable*> (object);
720 if(portable != NULL) {
721 portables.push_back(portable);
724 TileMap* tilemap = dynamic_cast<TileMap*> (object);
725 if(tilemap != NULL && tilemap->is_solid()) {
726 solid_tilemaps.push_back(tilemap);
729 Camera* camera = dynamic_cast<Camera*> (object);
731 if(this->camera != 0) {
732 log_warning << "Multiple cameras added. Ignoring" << std::endl;
735 this->camera = camera;
738 Player* player = dynamic_cast<Player*> (object);
740 if(this->player != 0) {
741 log_warning << "Multiple players added. Ignoring" << std::endl;
744 this->player = player;
747 DisplayEffect* effect = dynamic_cast<DisplayEffect*> (object);
749 if(this->effect != 0) {
750 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
753 this->effect = effect;
756 if(_current == this) {
764 Sector::try_expose(GameObject* object)
766 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
767 if(interface != NULL) {
768 HSQUIRRELVM vm = Scripting::global_vm;
769 sq_pushobject(vm, sector_table);
770 interface->expose(vm, -1);
776 Sector::try_expose_me()
778 HSQUIRRELVM vm = Scripting::global_vm;
779 sq_pushobject(vm, sector_table);
780 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
781 expose_object(vm, -1, interface, "settings", false);
786 Sector::before_object_remove(GameObject* object)
788 Portable* portable = dynamic_cast<Portable*> (object);
789 if(portable != NULL) {
790 portables.erase(std::find(portables.begin(), portables.end(), portable));
792 Bullet* bullet = dynamic_cast<Bullet*> (object);
794 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
796 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
797 if(moving_object != NULL) {
798 moving_objects.erase(
799 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
803 try_unexpose(object);
807 Sector::try_unexpose(GameObject* object)
809 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
810 if(interface != NULL) {
811 HSQUIRRELVM vm = Scripting::global_vm;
812 SQInteger oldtop = sq_gettop(vm);
813 sq_pushobject(vm, sector_table);
815 interface->unexpose(vm, -1);
816 } catch(std::exception& e) {
817 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
819 sq_settop(vm, oldtop);
824 Sector::try_unexpose_me()
826 HSQUIRRELVM vm = Scripting::global_vm;
827 SQInteger oldtop = sq_gettop(vm);
828 sq_pushobject(vm, sector_table);
830 Scripting::unexpose_object(vm, -1, "settings");
831 } catch(std::exception& e) {
832 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
834 sq_settop(vm, oldtop);
837 Sector::draw(DrawingContext& context)
839 context.set_ambient_color( ambient_light );
840 context.push_transform();
841 context.set_translation(camera->get_translation());
843 for(GameObjects::iterator i = gameobjects.begin();
844 i != gameobjects.end(); ++i) {
845 GameObject* object = *i;
846 if(!object->is_valid())
849 if (draw_solids_only)
851 TileMap* tm = dynamic_cast<TileMap*>(object);
852 if (tm && !tm->is_solid())
856 object->draw(context);
860 Color col(0.2f, 0.2f, 0.2f, 0.7f);
861 for(MovingObjects::iterator i = moving_objects.begin();
862 i != moving_objects.end(); ++i) {
863 MovingObject* object = *i;
864 const Rect& rect = object->get_bbox();
866 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
870 context.pop_transform();
873 /*-------------------------------------------------------------------------
874 * Collision Detection
875 *-------------------------------------------------------------------------*/
877 /** r1 is supposed to be moving, r2 a solid object */
878 void check_collisions(collision::Constraints* constraints,
879 const Vector& movement, const Rect& r1, const Rect& r2,
880 GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
882 if(!collision::intersects(r1, r2))
885 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
887 if(other != NULL && !other->collides(*object, dummy))
889 if(moving_object != NULL && !moving_object->collides(*other, dummy))
892 // calculate intersection
893 float itop = r1.get_bottom() - r2.get_top();
894 float ibottom = r2.get_bottom() - r1.get_top();
895 float ileft = r1.get_right() - r2.get_left();
896 float iright = r2.get_right() - r1.get_left();
898 if(fabsf(movement.y) > fabsf(movement.x)) {
899 if(ileft < SHIFT_DELTA) {
900 constraints->right = std::min(constraints->right, r2.get_left());
902 } else if(iright < SHIFT_DELTA) {
903 constraints->left = std::max(constraints->left, r2.get_right());
907 // shiftout bottom/top
908 if(itop < SHIFT_DELTA) {
909 constraints->bottom = std::min(constraints->bottom, r2.get_top());
911 } else if(ibottom < SHIFT_DELTA) {
912 constraints->top = std::max(constraints->top, r2.get_bottom());
917 constraints->ground_movement += addl_ground_movement;
919 HitResponse response = other->collision(*object, dummy);
920 if(response == PASSTHROUGH)
923 if(other->get_movement() != Vector(0, 0)) {
924 // TODO what todo when we collide with 2 moving objects?!?
925 constraints->ground_movement = other->get_movement();
929 float vert_penetration = std::min(itop, ibottom);
930 float horiz_penetration = std::min(ileft, iright);
931 if(vert_penetration < horiz_penetration) {
933 constraints->bottom = std::min(constraints->bottom, r2.get_top());
934 constraints->hit.bottom = true;
936 constraints->top = std::max(constraints->top, r2.get_bottom());
937 constraints->hit.top = true;
941 constraints->right = std::min(constraints->right, r2.get_left());
942 constraints->hit.right = true;
944 constraints->left = std::max(constraints->left, r2.get_right());
945 constraints->hit.left = true;
951 Sector::collision_tilemap(collision::Constraints* constraints,
952 const Vector& movement, const Rect& dest) const
954 // calculate rectangle where the object will move
955 float x1 = dest.get_left();
956 float x2 = dest.get_right();
957 float y1 = dest.get_top();
958 float y2 = dest.get_bottom();
960 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
961 TileMap* solids = *i;
963 // test with all tiles in this rectangle
964 int starttilex = int(x1 - solids->get_x_offset()) / 32;
965 int starttiley = int(y1 - solids->get_y_offset()) / 32;
966 int max_x = int(x2 - solids->get_x_offset());
967 int max_y = int(y2+1 - solids->get_y_offset());
969 for(int x = starttilex; x*32 < max_x; ++x) {
970 for(int y = starttiley; y*32 < max_y; ++y) {
971 const Tile* tile = solids->get_tile(x, y);
974 // skip non-solid tiles
975 if((tile->getAttributes() & Tile::SOLID) == 0)
977 // only handle unisolid when the player is falling down and when he was
978 // above the tile before
979 if(tile->getAttributes() & Tile::UNISOLID) {
980 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
984 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
986 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
987 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
988 triangle = AATriangle(p1, p2, tile->getData());
990 collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
991 } else { // normal rectangular tile
992 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());
993 check_collisions(constraints, movement, dest, rect, NULL, NULL, solids->get_movement());
1001 Sector::collision_tile_attributes(const Rect& dest) const
1003 float x1 = dest.p1.x;
1004 float y1 = dest.p1.y;
1005 float x2 = dest.p2.x;
1006 float y2 = dest.p2.y + SHIFT_DELTA;
1008 uint32_t result = 0;
1009 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1010 TileMap* solids = *i;
1012 // test with all tiles in this rectangle
1013 int starttilex = int(x1 - solids->get_x_offset()) / 32;
1014 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1015 int max_x = int(x2 - solids->get_x_offset());
1016 int max_y = int(y2+1 - solids->get_y_offset());
1018 for(int x = starttilex; x*32 < max_x; ++x) {
1019 for(int y = starttiley; y*32 < max_y; ++y) {
1020 const Tile* tile = solids->get_tile(x, y);
1023 result |= tile->getAttributes();
1031 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1032 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1035 float itop = r1.get_bottom() - r2.get_top();
1036 float ibottom = r2.get_bottom() - r1.get_top();
1037 float ileft = r1.get_right() - r2.get_left();
1038 float iright = r2.get_right() - r1.get_left();
1040 float vert_penetration = std::min(itop, ibottom);
1041 float horiz_penetration = std::min(ileft, iright);
1042 if(vert_penetration < horiz_penetration) {
1043 if(itop < ibottom) {
1045 normal.y = vert_penetration;
1048 normal.y = -vert_penetration;
1051 if(ileft < iright) {
1053 normal.x = horiz_penetration;
1056 normal.x = -horiz_penetration;
1062 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1064 using namespace collision;
1066 const Rect& r1 = object1->dest;
1067 const Rect& r2 = object2->dest;
1070 if(intersects(object1->dest, object2->dest)) {
1072 get_hit_normal(r1, r2, hit, normal);
1074 if(!object1->collides(*object2, hit))
1076 std::swap(hit.left, hit.right);
1077 std::swap(hit.top, hit.bottom);
1078 if(!object2->collides(*object1, hit))
1080 std::swap(hit.left, hit.right);
1081 std::swap(hit.top, hit.bottom);
1083 HitResponse response1 = object1->collision(*object2, hit);
1084 std::swap(hit.left, hit.right);
1085 std::swap(hit.top, hit.bottom);
1086 HitResponse response2 = object2->collision(*object1, hit);
1087 if(response1 == CONTINUE && response2 == CONTINUE) {
1088 normal *= (0.5 + DELTA);
1089 object1->dest.move(-normal);
1090 object2->dest.move(normal);
1091 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1092 normal *= (1 + DELTA);
1093 object1->dest.move(-normal);
1094 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1095 normal *= (1 + DELTA);
1096 object2->dest.move(normal);
1102 Sector::collision_static(collision::Constraints* constraints,
1103 const Vector& movement, const Rect& dest,
1106 collision_tilemap(constraints, movement, dest);
1108 // collision with other (static) objects
1109 for(MovingObjects::iterator i = moving_objects.begin();
1110 i != moving_objects.end(); ++i) {
1111 MovingObject* moving_object = *i;
1112 if(moving_object->get_group() != COLGROUP_STATIC
1113 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1115 if(!moving_object->is_valid())
1118 if(moving_object != &object)
1119 check_collisions(constraints, movement, dest, moving_object->bbox,
1120 &object, moving_object);
1125 Sector::collision_static_constrains(MovingObject& object)
1127 using namespace collision;
1128 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1130 Constraints constraints;
1131 Vector movement = object.get_movement();
1132 Rect& dest = object.dest;
1133 float owidth = object.get_bbox().get_width();
1134 float oheight = object.get_bbox().get_height();
1136 for(int i = 0; i < 2; ++i) {
1137 collision_static(&constraints, Vector(0, movement.y), dest, object);
1138 if(!constraints.has_constraints())
1141 // apply calculated horizontal constraints
1142 if(constraints.bottom < infinity) {
1143 float height = constraints.bottom - constraints.top;
1144 if(height < oheight) {
1145 // we're crushed, but ignore this for now, we'll get this again
1146 // later if we're really crushed or things will solve itself when
1147 // looking at the vertical constraints
1149 dest.p2.y = constraints.bottom - DELTA;
1150 dest.p1.y = dest.p2.y - oheight;
1151 } else if(constraints.top > -infinity) {
1152 dest.p1.y = constraints.top + DELTA;
1153 dest.p2.y = dest.p1.y + oheight;
1156 if(constraints.has_constraints()) {
1157 if(constraints.hit.bottom) {
1158 dest.move(constraints.ground_movement);
1160 if(constraints.hit.top || constraints.hit.bottom) {
1161 constraints.hit.left = false;
1162 constraints.hit.right = false;
1163 object.collision_solid(constraints.hit);
1167 constraints = Constraints();
1168 for(int i = 0; i < 2; ++i) {
1169 collision_static(&constraints, movement, dest, object);
1170 if(!constraints.has_constraints())
1173 // apply calculated vertical constraints
1174 if(constraints.right < infinity) {
1175 float width = constraints.right - constraints.left;
1176 if(width + SHIFT_DELTA < owidth) {
1178 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1179 constraints.left, constraints.right);
1185 object.collision_solid(h);
1187 dest.p2.x = constraints.right - DELTA;
1188 dest.p1.x = dest.p2.x - owidth;
1190 } else if(constraints.left > -infinity) {
1191 dest.p1.x = constraints.left + DELTA;
1192 dest.p2.x = dest.p1.x + owidth;
1196 if(constraints.has_constraints()) {
1197 if( constraints.hit.left || constraints.hit.right
1198 || constraints.hit.top || constraints.hit.bottom
1199 || constraints.hit.crush )
1200 object.collision_solid(constraints.hit);
1203 // an extra pass to make sure we're not crushed horizontally
1204 constraints = Constraints();
1205 collision_static(&constraints, movement, dest, object);
1206 if(constraints.bottom < infinity) {
1207 float height = constraints.bottom - constraints.top;
1208 if(height + SHIFT_DELTA < oheight) {
1210 printf("Object %p crushed vertically...\n", &object);
1216 object.collision_solid(h);
1222 const float MAX_SPEED = 16.0f;
1226 Sector::handle_collisions()
1228 using namespace collision;
1230 // calculate destination positions of the objects
1231 for(MovingObjects::iterator i = moving_objects.begin();
1232 i != moving_objects.end(); ++i) {
1233 MovingObject* moving_object = *i;
1234 Vector mov = moving_object->get_movement();
1236 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1237 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1238 moving_object->movement = mov.unit() * MAX_SPEED;
1239 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1242 moving_object->dest = moving_object->get_bbox();
1243 moving_object->dest.move(moving_object->get_movement());
1246 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1247 for(MovingObjects::iterator i = moving_objects.begin();
1248 i != moving_objects.end(); ++i) {
1249 MovingObject* moving_object = *i;
1250 if((moving_object->get_group() != COLGROUP_MOVING
1251 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1252 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1253 || !moving_object->is_valid())
1256 collision_static_constrains(*moving_object);
1259 // part2: COLGROUP_MOVING vs tile attributes
1260 for(MovingObjects::iterator i = moving_objects.begin();
1261 i != moving_objects.end(); ++i) {
1262 MovingObject* moving_object = *i;
1263 if((moving_object->get_group() != COLGROUP_MOVING
1264 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1265 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1266 || !moving_object->is_valid())
1269 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1270 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1271 moving_object->collision_tile(tile_attributes);
1275 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1276 for(MovingObjects::iterator i = moving_objects.begin();
1277 i != moving_objects.end(); ++i) {
1278 MovingObject* moving_object = *i;
1279 if((moving_object->get_group() != COLGROUP_MOVING
1280 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1281 || !moving_object->is_valid())
1284 for(MovingObjects::iterator i2 = moving_objects.begin();
1285 i2 != moving_objects.end(); ++i2) {
1286 MovingObject* moving_object_2 = *i2;
1287 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1288 || !moving_object_2->is_valid())
1291 if(intersects(moving_object->dest, moving_object_2->dest)) {
1294 get_hit_normal(moving_object->dest, moving_object_2->dest,
1296 if(!moving_object->collides(*moving_object_2, hit))
1298 if(!moving_object_2->collides(*moving_object, hit))
1301 moving_object->collision(*moving_object_2, hit);
1302 moving_object_2->collision(*moving_object, hit);
1307 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1308 for(MovingObjects::iterator i = moving_objects.begin();
1309 i != moving_objects.end(); ++i) {
1310 MovingObject* moving_object = *i;
1312 if((moving_object->get_group() != COLGROUP_MOVING
1313 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1314 || !moving_object->is_valid())
1317 for(MovingObjects::iterator i2 = i+1;
1318 i2 != moving_objects.end(); ++i2) {
1319 MovingObject* moving_object_2 = *i2;
1320 if((moving_object_2->get_group() != COLGROUP_MOVING
1321 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1322 || !moving_object_2->is_valid())
1325 collision_object(moving_object, moving_object_2);
1329 // apply object movement
1330 for(MovingObjects::iterator i = moving_objects.begin();
1331 i != moving_objects.end(); ++i) {
1332 MovingObject* moving_object = *i;
1334 moving_object->bbox = moving_object->dest;
1335 moving_object->movement = Vector(0, 0);
1340 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1342 using namespace collision;
1344 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1345 TileMap* solids = *i;
1347 // test with all tiles in this rectangle
1348 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1349 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1350 int max_x = int(rect.p2.x - solids->get_x_offset());
1351 int max_y = int(rect.p2.y - solids->get_y_offset());
1353 for(int x = starttilex; x*32 <= max_x; ++x) {
1354 for(int y = starttiley; y*32 <= max_y; ++y) {
1355 const Tile* tile = solids->get_tile(x, y);
1357 if(tile->getAttributes() & Tile::SLOPE) {
1358 AATriangle triangle;
1359 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1360 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1361 triangle = AATriangle(p1, p2, tile->getData());
1362 Constraints constraints;
1363 if(collision::rectangle_aatriangle(&constraints, rect, triangle) && (!ignoreUnisolid || !(tile->getAttributes() & Tile::UNISOLID))) return false;
1365 if((tile->getAttributes() & Tile::SOLID) && (!ignoreUnisolid || !(tile->getAttributes() & Tile::UNISOLID))) return false;
1374 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1376 using namespace collision;
1378 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1380 for(MovingObjects::const_iterator i = moving_objects.begin();
1381 i != moving_objects.end(); ++i) {
1382 const MovingObject* moving_object = *i;
1383 if (moving_object == ignore_object) continue;
1384 if (!moving_object->is_valid()) continue;
1385 if (moving_object->get_group() == COLGROUP_STATIC) {
1386 if(intersects(rect, moving_object->get_bbox())) return false;
1394 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1396 using namespace collision;
1398 if (!is_free_of_tiles(rect)) return false;
1400 for(MovingObjects::const_iterator i = moving_objects.begin();
1401 i != moving_objects.end(); ++i) {
1402 const MovingObject* moving_object = *i;
1403 if (moving_object == ignore_object) continue;
1404 if (!moving_object->is_valid()) continue;
1405 if ((moving_object->get_group() == COLGROUP_MOVING)
1406 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1407 || (moving_object->get_group() == COLGROUP_STATIC)) {
1408 if(intersects(rect, moving_object->get_bbox())) return false;
1416 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1418 // TODO remove this function and move these checks elsewhere...
1420 Bullet* new_bullet = 0;
1421 if((player_status->bonus == FIRE_BONUS &&
1422 (int)bullets.size() >= player_status->max_fire_bullets) ||
1423 (player_status->bonus == ICE_BONUS &&
1424 (int)bullets.size() >= player_status->max_ice_bullets))
1426 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1427 add_object(new_bullet);
1429 sound_manager->play("sounds/shoot.wav");
1435 Sector::add_smoke_cloud(const Vector& pos)
1437 add_object(new SmokeCloud(pos));
1442 Sector::play_music(MusicType type)
1444 currentmusic = type;
1445 switch(currentmusic) {
1447 sound_manager->play_music(music);
1450 sound_manager->play_music("music/invincible.music");
1452 case HERRING_WARNING_MUSIC:
1453 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1456 sound_manager->play_music("");
1462 Sector::get_music_type()
1464 return currentmusic;
1468 Sector::get_total_badguys()
1470 int total_badguys = 0;
1471 for(GameObjects::iterator i = gameobjects.begin();
1472 i != gameobjects.end(); ++i) {
1473 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1474 if (badguy && badguy->countMe)
1478 return total_badguys;
1482 Sector::inside(const Rect& rect) const
1484 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1485 TileMap* solids = *i;
1486 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1487 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1489 if (horizontally && vertically)
1496 Sector::get_width() 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_width() * 32 + solids->get_x_offset()) > width) {
1503 width = solids->get_width() * 32 + solids->get_x_offset();
1511 Sector::get_height() const
1514 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1515 i != solid_tilemaps.end(); i++) {
1516 TileMap* solids = *i;
1517 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1518 height = solids->get_height() * 32 + solids->get_y_offset();
1526 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1528 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1529 TileMap* solids = *i;
1530 solids->change_all(old_tile_id, new_tile_id);
1535 Sector::set_ambient_light(float red, float green, float blue)
1537 ambient_light.red = red;
1538 ambient_light.green = green;
1539 ambient_light.blue = blue;
1543 Sector::get_ambient_red()
1545 return ambient_light.red;
1549 Sector::get_ambient_green()
1551 return ambient_light.green;
1555 Sector::get_ambient_blue()
1557 return ambient_light.blue;
1561 Sector::set_gravity(float gravity)
1563 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1564 this->gravity = gravity;
1568 Sector::get_gravity() const