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.
32 #include <unison/vfs/FileSystem.hpp>
35 #include "object/player.hpp"
36 #include "object/gameobjs.hpp"
37 #include "object/camera.hpp"
38 #include "object/background.hpp"
39 #include "object/gradient.hpp"
40 #include "object/particlesystem.hpp"
41 #include "object/particlesystem_interactive.hpp"
42 #include "object/tilemap.hpp"
43 #include "lisp/parser.hpp"
44 #include "lisp/lisp.hpp"
45 #include "lisp/writer.hpp"
46 #include "lisp/list_iterator.hpp"
48 #include "audio/sound_manager.hpp"
49 #include "game_session.hpp"
50 #include "resources.hpp"
51 #include "statistics.hpp"
52 #include "object_factory.hpp"
53 #include "collision.hpp"
54 #include "spawn_point.hpp"
55 #include "math/rect.hpp"
56 #include "math/aatriangle.hpp"
57 #include "object/coin.hpp"
58 #include "object/block.hpp"
59 #include "object/invisible_block.hpp"
60 #include "object/light.hpp"
61 #include "object/pulsing_light.hpp"
62 #include "object/bullet.hpp"
63 #include "object/text_object.hpp"
64 #include "object/portable.hpp"
65 #include "badguy/jumpy.hpp"
66 #include "trigger/sequence_trigger.hpp"
67 #include "player_status.hpp"
68 #include "scripting/squirrel_util.hpp"
69 #include "script_interface.hpp"
73 Sector* Sector::_current = 0;
75 bool Sector::show_collrects = false;
76 bool Sector::draw_solids_only = false;
78 Sector::Sector(Level* parent)
79 : level(parent), currentmusic(LEVEL_MUSIC),
80 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10.0), player(0), camera(0)
82 add_object(new Player(player_status, "Tux"));
83 add_object(new DisplayEffect("Effect"));
84 add_object(new TextObject("Text"));
86 // create a new squirrel table for the sector
87 using namespace Scripting;
89 sq_collectgarbage(global_vm);
91 sq_newtable(global_vm);
92 sq_pushroottable(global_vm);
93 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
94 throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
96 sq_resetobject(§or_table);
97 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
98 throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
99 sq_addref(global_vm, §or_table);
100 sq_pop(global_vm, 1);
105 using namespace Scripting;
109 for(ScriptList::iterator i = scripts.begin();
110 i != scripts.end(); ++i) {
111 HSQOBJECT& object = *i;
112 sq_release(global_vm, &object);
114 sq_release(global_vm, §or_table);
115 sq_collectgarbage(global_vm);
117 update_game_objects();
118 assert(gameobjects_new.size() == 0);
120 for(GameObjects::iterator i = gameobjects.begin();
121 i != gameobjects.end(); ++i) {
122 GameObject* object = *i;
123 before_object_remove(object);
127 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
139 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
141 if(name == "camera") {
142 Camera* camera = new Camera(this, "Camera");
143 camera->parse(reader);
145 } else if(name == "particles-snow") {
146 SnowParticleSystem* partsys = new SnowParticleSystem();
147 partsys->parse(reader);
149 } else if(name == "particles-rain") {
150 RainParticleSystem* partsys = new RainParticleSystem();
151 partsys->parse(reader);
153 } else if(name == "particles-comets") {
154 CometParticleSystem* partsys = new CometParticleSystem();
155 partsys->parse(reader);
157 } else if(name == "particles-ghosts") {
158 GhostParticleSystem* partsys = new GhostParticleSystem();
159 partsys->parse(reader);
161 } else if(name == "particles-clouds") {
162 CloudParticleSystem* partsys = new CloudParticleSystem();
163 partsys->parse(reader);
165 } else if(name == "money") { // for compatibility with old maps
166 return new Jumpy(reader);
170 return create_object(name, reader);
171 } catch(std::exception& e) {
172 log_warning << e.what() << "" << std::endl;
179 Sector::parse(const lisp::Lisp& sector)
181 bool has_background = false;
182 lisp::ListIterator iter(§or);
184 const std::string& token = iter.item();
185 if(token == "name") {
186 iter.value()->get(name);
187 } else if(token == "gravity") {
188 iter.value()->get(gravity);
189 } else if(token == "music") {
190 iter.value()->get(music);
191 } else if(token == "spawnpoint") {
192 SpawnPoint* sp = new SpawnPoint(iter.lisp());
193 spawnpoints.push_back(sp);
194 } else if(token == "init-script") {
195 iter.value()->get(init_script);
196 } else if(token == "ambient-light") {
197 std::vector<float> vColor;
198 sector.get_vector( "ambient-light", vColor );
199 if(vColor.size() < 3) {
200 log_warning << "(ambient-light) requires a color as argument" << std::endl;
202 ambient_light = Color( vColor );
205 GameObject* object = parse_object(token, *(iter.lisp()));
207 if(dynamic_cast<Background *>(object)) {
208 has_background = true;
209 } else if(dynamic_cast<Gradient *>(object)) {
210 has_background = true;
217 if(!has_background) {
218 Gradient* gradient = new Gradient();
219 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
220 add_object(gradient);
223 update_game_objects();
225 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
229 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
230 update_game_objects();
231 add_object(new Camera(this, "Camera"));
234 update_game_objects();
238 Sector::parse_old_format(const lisp::Lisp& reader)
241 reader.get("gravity", gravity);
243 std::string backgroundimage;
244 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
245 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
246 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
247 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
248 backgroundimage = "images/background/" + backgroundimage;
249 if (!Unison::VFS::FileSystem::get().exists(backgroundimage)) {
250 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
251 backgroundimage = "";
256 reader.get("bkgd_speed", bgspeed);
259 Color bkgd_top, bkgd_bottom;
260 int r = 0, g = 0, b = 128;
261 reader.get("bkgd_red_top", r);
262 reader.get("bkgd_green_top", g);
263 reader.get("bkgd_blue_top", b);
264 bkgd_top.red = static_cast<float> (r) / 255.0f;
265 bkgd_top.green = static_cast<float> (g) / 255.0f;
266 bkgd_top.blue = static_cast<float> (b) / 255.0f;
268 reader.get("bkgd_red_bottom", r);
269 reader.get("bkgd_green_bottom", g);
270 reader.get("bkgd_blue_bottom", b);
271 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
272 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
273 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
275 if(backgroundimage != "") {
276 Background* background = new Background();
277 background->set_image(backgroundimage, bgspeed);
278 add_object(background);
280 Gradient* gradient = new Gradient();
281 gradient->set_gradient(bkgd_top, bkgd_bottom);
282 add_object(gradient);
285 std::string particlesystem;
286 reader.get("particle_system", particlesystem);
287 if(particlesystem == "clouds")
288 add_object(new CloudParticleSystem());
289 else if(particlesystem == "snow")
290 add_object(new SnowParticleSystem());
291 else if(particlesystem == "rain")
292 add_object(new RainParticleSystem());
294 Vector startpos(100, 170);
295 reader.get("start_pos_x", startpos.x);
296 reader.get("start_pos_y", startpos.y);
298 SpawnPoint* spawn = new SpawnPoint;
299 spawn->pos = startpos;
300 spawn->name = "main";
301 spawnpoints.push_back(spawn);
303 music = "chipdisko.ogg";
304 // skip reading music filename. It's all .ogg now, anyway
306 reader.get("music", music);
308 music = "music/" + music;
310 int width = 30, height = 15;
311 reader.get("width", width);
312 reader.get("height", height);
314 std::vector<unsigned int> tiles;
315 if(reader.get_vector("interactive-tm", tiles)
316 || reader.get_vector("tilemap", tiles)) {
317 TileMap* tilemap = new TileMap();
318 tilemap->set(width, height, tiles, LAYER_TILES, true);
320 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
321 for(size_t x=0; x < tilemap->get_width(); ++x) {
322 for(size_t y=0; y < tilemap->get_height(); ++y) {
323 const Tile* tile = tilemap->get_tile(x, y);
324 if(tile->getID() == 112) tilemap->change(x, y, 1311);
328 if (height < 19) tilemap->resize(width, 19);
332 if(reader.get_vector("background-tm", tiles)) {
333 TileMap* tilemap = new TileMap();
334 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
335 if (height < 19) tilemap->resize(width, 19);
339 if(reader.get_vector("foreground-tm", tiles)) {
340 TileMap* tilemap = new TileMap();
341 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
343 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
344 if (height < 19) tilemap->resize(width, 19, 2035);
349 // read reset-points (now spawn-points)
350 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
352 lisp::ListIterator iter(resetpoints);
354 if(iter.item() == "point") {
356 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
358 SpawnPoint* sp = new SpawnPoint;
361 spawnpoints.push_back(sp);
364 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
370 const lisp::Lisp* objects = reader.get_lisp("objects");
372 lisp::ListIterator iter(objects);
374 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
378 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
384 Camera* camera = new Camera(this, "Camera");
387 update_game_objects();
389 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
392 update_game_objects();
396 Sector::fix_old_tiles()
398 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
399 TileMap* solids = *i;
400 for(size_t x=0; x < solids->get_width(); ++x) {
401 for(size_t y=0; y < solids->get_height(); ++y) {
402 const Tile* tile = solids->get_tile(x, y);
403 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
405 if(tile->getID() == 112) {
406 add_object(new InvisibleBlock(pos));
407 solids->change(x, y, 0);
408 } else if(tile->getAttributes() & Tile::COIN) {
409 add_object(new Coin(pos));
410 solids->change(x, y, 0);
411 } else if(tile->getAttributes() & Tile::FULLBOX) {
412 add_object(new BonusBlock(pos, tile->getData()));
413 solids->change(x, y, 0);
414 } else if(tile->getAttributes() & Tile::BRICK) {
415 add_object(new Brick(pos, tile->getData()));
416 solids->change(x, y, 0);
417 } else if(tile->getAttributes() & Tile::GOAL) {
418 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
419 add_object(new SequenceTrigger(pos, sequence));
420 solids->change(x, y, 0);
426 // add lights for special tiles
427 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
428 TileMap* tm = dynamic_cast<TileMap*>(*i);
430 for(size_t x=0; x < tm->get_width(); ++x) {
431 for(size_t y=0; y < tm->get_height(); ++y) {
432 const Tile* tile = tm->get_tile(x, y);
433 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
434 Vector center(pos.x + 16, pos.y + 16);
437 if (tile->getID() == 1517) {
438 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
439 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
442 if ((tile->getID() == 173) || (tile->getID() == 1700) || (tile->getID() == 1705) || (tile->getID() == 1706)) {
443 // space lights a bit
444 if (((tm->get_tile(x-1, y)->getID() != tm->get_tile(x,y)->getID())
445 && (tm->get_tile(x, y-1)->getID() != tm->get_tile(x,y)->getID()))
446 || ((x % 3 == 0) && (y % 3 == 0))) {
447 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
448 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
460 Sector::write(lisp::Writer& writer)
462 writer.write_string("name", name);
463 writer.write_float("gravity", gravity);
464 writer.write_string("music", music);
467 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
469 SpawnPoint* spawn = *i;
470 writer.start_list("spawn-points");
471 writer.write_string("name", spawn->name);
472 writer.write_float("x", spawn->pos.x);
473 writer.write_float("y", spawn->pos.y);
474 writer.end_list("spawn-points");
478 for(GameObjects::iterator i = gameobjects.begin();
479 i != gameobjects.end(); ++i) {
480 Serializable* serializable = dynamic_cast<Serializable*> (*i);
482 serializable->write(writer);
487 Sector::run_script(std::istream& in, const std::string& sourcename)
489 using namespace Scripting;
491 // garbage collect thread list
492 for(ScriptList::iterator i = scripts.begin();
493 i != scripts.end(); ) {
494 HSQOBJECT& object = *i;
495 HSQUIRRELVM vm = object_to_vm(object);
497 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
498 sq_release(global_vm, &object);
499 i = scripts.erase(i);
506 HSQOBJECT object = create_thread(global_vm);
507 scripts.push_back(object);
509 HSQUIRRELVM vm = object_to_vm(object);
511 // set sector_table as roottable for the thread
512 sq_pushobject(vm, sector_table);
515 compile_and_run(vm, in, sourcename);
521 Sector::add_object(GameObject* object)
523 // make sure the object isn't already in the list
525 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
528 assert("object already added to sector" == 0);
531 for(GameObjects::iterator i = gameobjects_new.begin();
532 i != gameobjects_new.end(); ++i) {
534 assert("object already added to sector" == 0);
540 gameobjects_new.push_back(object);
544 Sector::activate(const std::string& spawnpoint)
547 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
549 if((*i)->name == spawnpoint) {
555 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
556 if(spawnpoint != "main") {
559 activate(Vector(0, 0));
567 Sector::activate(const Vector& player_pos)
569 if(_current != this) {
571 _current->deactivate();
574 // register sectortable as sector in scripting
575 HSQUIRRELVM vm = Scripting::global_vm;
576 sq_pushroottable(vm);
577 sq_pushstring(vm, "sector", -1);
578 sq_pushobject(vm, sector_table);
579 if(SQ_FAILED(sq_createslot(vm, -3)))
580 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
583 for(GameObjects::iterator i = gameobjects.begin();
584 i != gameobjects.end(); ++i) {
585 GameObject* object = *i;
592 // spawn smalltux below spawnpoint
593 if (!player->is_big()) {
594 player->move(player_pos + Vector(0,32));
596 player->move(player_pos);
599 // spawning tux in the ground would kill him
600 if(!is_free_of_tiles(player->get_bbox())) {
601 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
602 Vector npos = player->get_bbox().p1;
607 camera->reset(player->get_pos());
608 update_game_objects();
611 if(init_script != "") {
612 std::istringstream in(init_script);
613 run_script(in, std::string("Sector(") + name + ") - init");
623 // remove sector entry from global vm
624 HSQUIRRELVM vm = Scripting::global_vm;
625 sq_pushroottable(vm);
626 sq_pushstring(vm, "sector", -1);
627 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
628 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
631 for(GameObjects::iterator i = gameobjects.begin();
632 i != gameobjects.end(); ++i) {
633 GameObject* object = *i;
635 try_unexpose(object);
643 Sector::get_active_region()
646 camera->get_translation() - Vector(1600, 1200),
647 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
651 Sector::update(float elapsed_time)
653 player->check_bounds(camera);
656 for(GameObjects::iterator i = gameobjects.begin();
657 i != gameobjects.end(); ++i) {
658 GameObject* object = *i;
659 if(!object->is_valid())
662 object->update(elapsed_time);
665 /* Handle all possible collisions. */
667 update_game_objects();
671 Sector::update_game_objects()
673 /** cleanup marked objects */
674 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
675 i != gameobjects.end(); /* nothing */) {
676 GameObject* object = *i;
678 if(object->is_valid()) {
683 before_object_remove(object);
686 i = gameobjects.erase(i);
689 /* add newly created objects */
690 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
691 i != gameobjects_new.end(); ++i)
693 GameObject* object = *i;
695 before_object_add(object);
697 gameobjects.push_back(object);
699 gameobjects_new.clear();
701 /* update solid_tilemaps list */
702 //FIXME: this could be more efficient
703 solid_tilemaps.clear();
704 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
705 i != gameobjects.end(); ++i)
707 TileMap* tm = dynamic_cast<TileMap*>(*i);
709 if (tm->is_solid()) solid_tilemaps.push_back(tm);
715 Sector::before_object_add(GameObject* object)
717 Bullet* bullet = dynamic_cast<Bullet*> (object);
719 bullets.push_back(bullet);
722 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
723 if(movingobject != NULL) {
724 moving_objects.push_back(movingobject);
727 Portable* portable = dynamic_cast<Portable*> (object);
728 if(portable != NULL) {
729 portables.push_back(portable);
732 TileMap* tilemap = dynamic_cast<TileMap*> (object);
733 if(tilemap != NULL && tilemap->is_solid()) {
734 solid_tilemaps.push_back(tilemap);
737 Camera* camera = dynamic_cast<Camera*> (object);
739 if(this->camera != 0) {
740 log_warning << "Multiple cameras added. Ignoring" << std::endl;
743 this->camera = camera;
746 Player* player = dynamic_cast<Player*> (object);
748 if(this->player != 0) {
749 log_warning << "Multiple players added. Ignoring" << std::endl;
752 this->player = player;
755 UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
758 physic_object->physic.set_gravity(gravity);
762 if(_current == this) {
770 Sector::try_expose(GameObject* object)
772 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
773 if(interface != NULL) {
774 HSQUIRRELVM vm = Scripting::global_vm;
775 sq_pushobject(vm, sector_table);
776 interface->expose(vm, -1);
782 Sector::try_expose_me()
784 HSQUIRRELVM vm = Scripting::global_vm;
785 sq_pushobject(vm, sector_table);
786 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
787 expose_object(vm, -1, interface, "settings", false);
792 Sector::before_object_remove(GameObject* object)
794 Portable* portable = dynamic_cast<Portable*> (object);
795 if(portable != NULL) {
796 portables.erase(std::find(portables.begin(), portables.end(), portable));
798 Bullet* bullet = dynamic_cast<Bullet*> (object);
800 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
802 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
803 if(moving_object != NULL) {
804 moving_objects.erase(
805 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
809 try_unexpose(object);
813 Sector::try_unexpose(GameObject* object)
815 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
816 if(interface != NULL) {
817 HSQUIRRELVM vm = Scripting::global_vm;
818 SQInteger oldtop = sq_gettop(vm);
819 sq_pushobject(vm, sector_table);
821 interface->unexpose(vm, -1);
822 } catch(std::exception& e) {
823 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
825 sq_settop(vm, oldtop);
830 Sector::try_unexpose_me()
832 HSQUIRRELVM vm = Scripting::global_vm;
833 SQInteger oldtop = sq_gettop(vm);
834 sq_pushobject(vm, sector_table);
836 Scripting::unexpose_object(vm, -1, "settings");
837 } catch(std::exception& e) {
838 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
840 sq_settop(vm, oldtop);
843 Sector::draw(DrawingContext& context)
845 context.set_ambient_color( ambient_light );
846 context.push_transform();
847 context.set_translation(camera->get_translation());
849 for(GameObjects::iterator i = gameobjects.begin();
850 i != gameobjects.end(); ++i) {
851 GameObject* object = *i;
852 if(!object->is_valid())
855 if (draw_solids_only)
857 TileMap* tm = dynamic_cast<TileMap*>(object);
858 if (tm && !tm->is_solid())
862 object->draw(context);
866 Color col(0.2f, 0.2f, 0.2f, 0.7f);
867 for(MovingObjects::iterator i = moving_objects.begin();
868 i != moving_objects.end(); ++i) {
869 MovingObject* object = *i;
870 const Rect& rect = object->get_bbox();
872 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
876 context.pop_transform();
879 /*-------------------------------------------------------------------------
880 * Collision Detection
881 *-------------------------------------------------------------------------*/
883 static const float SHIFT_DELTA = 7.0f;
885 /** r1 is supposed to be moving, r2 a solid object */
886 void check_collisions(collision::Constraints* constraints,
887 const Vector& movement, const Rect& r1, const Rect& r2,
888 GameObject* object = NULL, MovingObject* other = NULL)
890 if(!collision::intersects(r1, r2))
893 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
895 if(other != NULL && !other->collides(*object, dummy))
897 if(moving_object != NULL && !moving_object->collides(*other, dummy))
900 // calculate intersection
901 float itop = r1.get_bottom() - r2.get_top();
902 float ibottom = r2.get_bottom() - r1.get_top();
903 float ileft = r1.get_right() - r2.get_left();
904 float iright = r2.get_right() - r1.get_left();
906 if(fabsf(movement.y) > fabsf(movement.x)) {
907 if(ileft < SHIFT_DELTA) {
908 constraints->right = std::min(constraints->right, r2.get_left());
910 } else if(iright < SHIFT_DELTA) {
911 constraints->left = std::max(constraints->left, r2.get_right());
915 // shiftout bottom/top
916 if(itop < SHIFT_DELTA) {
917 constraints->bottom = std::min(constraints->bottom, r2.get_top());
919 } else if(ibottom < SHIFT_DELTA) {
920 constraints->top = std::max(constraints->top, r2.get_bottom());
926 HitResponse response = other->collision(*object, dummy);
927 if(response == PASSTHROUGH)
930 if(other->get_movement() != Vector(0, 0)) {
931 // TODO what todo when we collide with 2 moving objects?!?
932 constraints->ground_movement = other->get_movement();
936 float vert_penetration = std::min(itop, ibottom);
937 float horiz_penetration = std::min(ileft, iright);
938 if(vert_penetration < horiz_penetration) {
940 constraints->bottom = std::min(constraints->bottom, r2.get_top());
941 constraints->hit.bottom = true;
943 constraints->top = std::max(constraints->top, r2.get_bottom());
944 constraints->hit.top = true;
948 constraints->right = std::min(constraints->right, r2.get_left());
949 constraints->hit.right = true;
951 constraints->left = std::max(constraints->left, r2.get_right());
952 constraints->hit.left = true;
957 static const float DELTA = .001f;
960 Sector::collision_tilemap(collision::Constraints* constraints,
961 const Vector& movement, const Rect& dest) const
963 // calculate rectangle where the object will move
964 float x1 = dest.get_left();
965 float x2 = dest.get_right();
966 float y1 = dest.get_top();
967 float y2 = dest.get_bottom();
969 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
970 TileMap* solids = *i;
972 // test with all tiles in this rectangle
973 int starttilex = int(x1 - solids->get_x_offset()) / 32;
974 int starttiley = int(y1 - solids->get_y_offset()) / 32;
975 int max_x = int(x2 - solids->get_x_offset());
976 int max_y = int(y2+1 - solids->get_y_offset());
978 for(int x = starttilex; x*32 < max_x; ++x) {
979 for(int y = starttiley; y*32 < max_y; ++y) {
980 const Tile* tile = solids->get_tile(x, y);
983 // skip non-solid tiles
984 if((tile->getAttributes() & Tile::SOLID) == 0)
986 // only handle unisolid when the player is falling down and when he was
987 // above the tile before
988 if(tile->getAttributes() & Tile::UNISOLID) {
989 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
993 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
995 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
996 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
997 triangle = AATriangle(p1, p2, tile->getData());
999 collision::rectangle_aatriangle(constraints, dest, triangle);
1000 } else { // normal rectangular tile
1001 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());
1002 check_collisions(constraints, movement, dest, rect);
1010 Sector::collision_tile_attributes(const Rect& dest) const
1012 float x1 = dest.p1.x;
1013 float y1 = dest.p1.y;
1014 float x2 = dest.p2.x;
1015 float y2 = dest.p2.y;
1017 uint32_t result = 0;
1018 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1019 TileMap* solids = *i;
1021 // test with all tiles in this rectangle
1022 int starttilex = int(x1 - solids->get_x_offset()) / 32;
1023 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1024 int max_x = int(x2 - solids->get_x_offset());
1025 int max_y = int(y2+1 - solids->get_y_offset());
1027 for(int x = starttilex; x*32 < max_x; ++x) {
1028 for(int y = starttiley; y*32 < max_y; ++y) {
1029 const Tile* tile = solids->get_tile(x, y);
1032 result |= tile->getAttributes();
1040 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1041 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1044 float itop = r1.get_bottom() - r2.get_top();
1045 float ibottom = r2.get_bottom() - r1.get_top();
1046 float ileft = r1.get_right() - r2.get_left();
1047 float iright = r2.get_right() - r1.get_left();
1049 float vert_penetration = std::min(itop, ibottom);
1050 float horiz_penetration = std::min(ileft, iright);
1051 if(vert_penetration < horiz_penetration) {
1052 if(itop < ibottom) {
1054 normal.y = vert_penetration;
1057 normal.y = -vert_penetration;
1060 if(ileft < iright) {
1062 normal.x = horiz_penetration;
1065 normal.x = -horiz_penetration;
1071 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1073 using namespace collision;
1075 const Rect& r1 = object1->dest;
1076 const Rect& r2 = object2->dest;
1079 if(intersects(object1->dest, object2->dest)) {
1081 get_hit_normal(r1, r2, hit, normal);
1083 if(!object1->collides(*object2, hit))
1085 std::swap(hit.left, hit.right);
1086 std::swap(hit.top, hit.bottom);
1087 if(!object2->collides(*object1, hit))
1089 std::swap(hit.left, hit.right);
1090 std::swap(hit.top, hit.bottom);
1092 HitResponse response1 = object1->collision(*object2, hit);
1093 std::swap(hit.left, hit.right);
1094 std::swap(hit.top, hit.bottom);
1095 HitResponse response2 = object2->collision(*object1, hit);
1096 if(response1 == CONTINUE && response2 == CONTINUE) {
1097 normal *= (0.5 + DELTA);
1098 object1->dest.move(-normal);
1099 object2->dest.move(normal);
1100 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1101 normal *= (1 + DELTA);
1102 object1->dest.move(-normal);
1103 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1104 normal *= (1 + DELTA);
1105 object2->dest.move(normal);
1111 Sector::collision_static(collision::Constraints* constraints,
1112 const Vector& movement, const Rect& dest,
1115 collision_tilemap(constraints, movement, dest);
1117 // collision with other (static) objects
1118 for(MovingObjects::iterator i = moving_objects.begin();
1119 i != moving_objects.end(); ++i) {
1120 MovingObject* moving_object = *i;
1121 if(moving_object->get_group() != COLGROUP_STATIC
1122 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1124 if(!moving_object->is_valid())
1127 if(moving_object != &object)
1128 check_collisions(constraints, movement, dest, moving_object->bbox,
1129 &object, moving_object);
1134 Sector::collision_static_constrains(MovingObject& object)
1136 using namespace collision;
1137 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1139 Constraints constraints;
1140 Vector movement = object.get_movement();
1141 Rect& dest = object.dest;
1142 float owidth = object.get_bbox().get_width();
1143 float oheight = object.get_bbox().get_height();
1145 for(int i = 0; i < 2; ++i) {
1146 collision_static(&constraints, Vector(0, movement.y), dest, object);
1147 if(!constraints.has_constraints())
1150 // apply calculated horizontal constraints
1151 if(constraints.bottom < infinity) {
1152 float height = constraints.bottom - constraints.top;
1153 if(height < oheight) {
1154 // we're crushed, but ignore this for now, we'll get this again
1155 // later if we're really crushed or things will solve itself when
1156 // looking at the vertical constraints
1158 dest.p2.y = constraints.bottom - DELTA;
1159 dest.p1.y = dest.p2.y - oheight;
1160 } else if(constraints.top > -infinity) {
1161 dest.p1.y = constraints.top + DELTA;
1162 dest.p2.y = dest.p1.y + oheight;
1165 if(constraints.has_constraints()) {
1166 if(constraints.hit.bottom) {
1167 dest.move(constraints.ground_movement);
1169 if(constraints.hit.top || constraints.hit.bottom) {
1170 constraints.hit.left = false;
1171 constraints.hit.right = false;
1172 object.collision_solid(constraints.hit);
1176 constraints = Constraints();
1177 for(int i = 0; i < 2; ++i) {
1178 collision_static(&constraints, movement, dest, object);
1179 if(!constraints.has_constraints())
1182 // apply calculated vertical constraints
1183 if(constraints.right < infinity) {
1184 float width = constraints.right - constraints.left;
1185 if(width + SHIFT_DELTA < owidth) {
1187 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1188 constraints.left, constraints.right);
1194 object.collision_solid(h);
1196 dest.p2.x = constraints.right - DELTA;
1197 dest.p1.x = dest.p2.x - owidth;
1199 } else if(constraints.left > -infinity) {
1200 dest.p1.x = constraints.left + DELTA;
1201 dest.p2.x = dest.p1.x + owidth;
1205 if(constraints.has_constraints()) {
1206 if( constraints.hit.left || constraints.hit.right
1207 || constraints.hit.top || constraints.hit.bottom
1208 || constraints.hit.crush )
1209 object.collision_solid(constraints.hit);
1212 // an extra pass to make sure we're not crushed horizontally
1213 constraints = Constraints();
1214 collision_static(&constraints, movement, dest, object);
1215 if(constraints.bottom < infinity) {
1216 float height = constraints.bottom - constraints.top;
1217 if(height + SHIFT_DELTA < oheight) {
1219 printf("Object %p crushed vertically...\n", &object);
1225 object.collision_solid(h);
1231 const float MAX_SPEED = 16.0f;
1235 Sector::handle_collisions()
1237 using namespace collision;
1239 // calculate destination positions of the objects
1240 for(MovingObjects::iterator i = moving_objects.begin();
1241 i != moving_objects.end(); ++i) {
1242 MovingObject* moving_object = *i;
1243 Vector mov = moving_object->get_movement();
1245 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1246 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1247 moving_object->movement = mov.unit() * MAX_SPEED;
1248 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1251 moving_object->dest = moving_object->get_bbox();
1252 moving_object->dest.move(moving_object->get_movement());
1255 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1256 for(MovingObjects::iterator i = moving_objects.begin();
1257 i != moving_objects.end(); ++i) {
1258 MovingObject* moving_object = *i;
1259 if((moving_object->get_group() != COLGROUP_MOVING
1260 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1261 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1262 || !moving_object->is_valid())
1265 collision_static_constrains(*moving_object);
1269 // part2: COLGROUP_MOVING vs tile attributes
1270 for(MovingObjects::iterator i = moving_objects.begin();
1271 i != moving_objects.end(); ++i) {
1272 MovingObject* moving_object = *i;
1273 if((moving_object->get_group() != COLGROUP_MOVING
1274 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1275 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1276 || !moving_object->is_valid())
1279 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1280 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1281 moving_object->collision_tile(tile_attributes);
1285 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
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->is_valid())
1294 for(MovingObjects::iterator i2 = moving_objects.begin();
1295 i2 != moving_objects.end(); ++i2) {
1296 MovingObject* moving_object_2 = *i2;
1297 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1298 || !moving_object_2->is_valid())
1301 if(intersects(moving_object->dest, moving_object_2->dest)) {
1304 get_hit_normal(moving_object->dest, moving_object_2->dest,
1306 if(!moving_object->collides(*moving_object_2, hit))
1308 if(!moving_object_2->collides(*moving_object, hit))
1311 moving_object->collision(*moving_object_2, hit);
1312 moving_object_2->collision(*moving_object, hit);
1317 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1318 for(MovingObjects::iterator i = moving_objects.begin();
1319 i != moving_objects.end(); ++i) {
1320 MovingObject* moving_object = *i;
1322 if((moving_object->get_group() != COLGROUP_MOVING
1323 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1324 || !moving_object->is_valid())
1327 for(MovingObjects::iterator i2 = i+1;
1328 i2 != moving_objects.end(); ++i2) {
1329 MovingObject* moving_object_2 = *i2;
1330 if((moving_object_2->get_group() != COLGROUP_MOVING
1331 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1332 || !moving_object_2->is_valid())
1335 collision_object(moving_object, moving_object_2);
1339 // apply object movement
1340 for(MovingObjects::iterator i = moving_objects.begin();
1341 i != moving_objects.end(); ++i) {
1342 MovingObject* moving_object = *i;
1344 moving_object->bbox = moving_object->dest;
1345 moving_object->movement = Vector(0, 0);
1350 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1352 using namespace collision;
1354 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1355 TileMap* solids = *i;
1357 // test with all tiles in this rectangle
1358 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1359 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1360 int max_x = int(rect.p2.x - solids->get_x_offset());
1361 int max_y = int(rect.p2.y - solids->get_y_offset());
1363 for(int x = starttilex; x*32 <= max_x; ++x) {
1364 for(int y = starttiley; y*32 <= max_y; ++y) {
1365 const Tile* tile = solids->get_tile(x, y);
1367 if(tile->getAttributes() & Tile::SLOPE) {
1368 AATriangle triangle;
1369 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1370 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1371 triangle = AATriangle(p1, p2, tile->getData());
1372 Constraints constraints;
1373 return collision::rectangle_aatriangle(&constraints, rect, triangle);
1375 if((tile->getAttributes() & Tile::SOLID) && !ignoreUnisolid) return false;
1376 if((tile->getAttributes() & Tile::SOLID) && !(tile->getAttributes() & Tile::UNISOLID)) return false;
1385 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1387 using namespace collision;
1389 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1391 for(MovingObjects::const_iterator i = moving_objects.begin();
1392 i != moving_objects.end(); ++i) {
1393 const MovingObject* moving_object = *i;
1394 if (moving_object == ignore_object) continue;
1395 if (!moving_object->is_valid()) continue;
1396 if (moving_object->get_group() == COLGROUP_STATIC) {
1397 if(intersects(rect, moving_object->get_bbox())) return false;
1405 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1407 using namespace collision;
1409 if (!is_free_of_tiles(rect)) return false;
1411 for(MovingObjects::const_iterator i = moving_objects.begin();
1412 i != moving_objects.end(); ++i) {
1413 const MovingObject* moving_object = *i;
1414 if (moving_object == ignore_object) continue;
1415 if (!moving_object->is_valid()) continue;
1416 if ((moving_object->get_group() == COLGROUP_MOVING)
1417 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1418 || (moving_object->get_group() == COLGROUP_STATIC)) {
1419 if(intersects(rect, moving_object->get_bbox())) return false;
1427 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1429 // TODO remove this function and move these checks elsewhere...
1431 Bullet* new_bullet = 0;
1432 if((player_status->bonus == FIRE_BONUS &&
1433 (int)bullets.size() >= player_status->max_fire_bullets) ||
1434 (player_status->bonus == ICE_BONUS &&
1435 (int)bullets.size() >= player_status->max_ice_bullets))
1437 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1438 add_object(new_bullet);
1440 sound_manager->play("sounds/shoot.wav");
1446 Sector::add_smoke_cloud(const Vector& pos)
1448 add_object(new SmokeCloud(pos));
1453 Sector::play_music(MusicType type)
1455 currentmusic = type;
1456 switch(currentmusic) {
1458 sound_manager->play_music(music);
1461 sound_manager->play_music("music/salcon.ogg");
1463 case HERRING_WARNING_MUSIC:
1464 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1467 sound_manager->play_music("");
1473 Sector::get_music_type()
1475 return currentmusic;
1479 Sector::get_total_badguys()
1481 int total_badguys = 0;
1482 for(GameObjects::iterator i = gameobjects.begin();
1483 i != gameobjects.end(); ++i) {
1484 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1485 if (badguy && badguy->countMe)
1489 return total_badguys;
1493 Sector::inside(const Rect& rect) const
1495 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1496 TileMap* solids = *i;
1497 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1498 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1500 if (horizontally && vertically)
1507 Sector::get_width() const
1510 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1511 i != solid_tilemaps.end(); i++) {
1512 TileMap* solids = *i;
1513 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1514 width = solids->get_width() * 32 + solids->get_x_offset();
1522 Sector::get_height() const
1525 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1526 i != solid_tilemaps.end(); i++) {
1527 TileMap* solids = *i;
1528 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1529 height = solids->get_height() * 32 + solids->get_y_offset();
1537 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1539 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1540 TileMap* solids = *i;
1541 solids->change_all(old_tile_id, new_tile_id);
1547 Sector::set_ambient_light(float red, float green, float blue)
1549 ambient_light.red = red;
1550 ambient_light.green = green;
1551 ambient_light.blue = blue;
1555 Sector::get_ambient_red()
1557 return ambient_light.red;
1561 Sector::get_ambient_green()
1563 return ambient_light.green;
1567 Sector::get_ambient_blue()
1569 return ambient_light.blue;