3 // SuperTux - A Jump'n Run
4 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 #include "object/player.hpp"
35 #include "object/gameobjs.hpp"
36 #include "object/camera.hpp"
37 #include "object/background.hpp"
38 #include "object/gradient.hpp"
39 #include "object/particlesystem.hpp"
40 #include "object/particlesystem_interactive.hpp"
41 #include "object/tilemap.hpp"
42 #include "lisp/parser.hpp"
43 #include "lisp/lisp.hpp"
44 #include "lisp/writer.hpp"
45 #include "lisp/list_iterator.hpp"
47 #include "audio/sound_manager.hpp"
48 #include "game_session.hpp"
49 #include "resources.hpp"
50 #include "statistics.hpp"
51 #include "object_factory.hpp"
52 #include "collision.hpp"
53 #include "spawn_point.hpp"
54 #include "math/rect.hpp"
55 #include "math/aatriangle.hpp"
56 #include "object/coin.hpp"
57 #include "object/block.hpp"
58 #include "object/invisible_block.hpp"
59 #include "object/light.hpp"
60 #include "object/pulsing_light.hpp"
61 #include "object/bullet.hpp"
62 #include "object/text_object.hpp"
63 #include "object/portable.hpp"
64 #include "badguy/jumpy.hpp"
65 #include "trigger/sequence_trigger.hpp"
66 #include "player_status.hpp"
67 #include "scripting/squirrel_util.hpp"
68 #include "script_interface.hpp"
71 Sector* Sector::_current = 0;
73 bool Sector::show_collrects = false;
74 bool Sector::draw_solids_only = false;
76 Sector::Sector(Level* parent)
77 : level(parent), currentmusic(LEVEL_MUSIC),
78 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10.0), player(0), camera(0)
80 add_object(new Player(player_status, "Tux"));
81 add_object(new DisplayEffect("Effect"));
82 add_object(new TextObject("Text"));
84 // create a new squirrel table for the sector
85 using namespace Scripting;
87 sq_collectgarbage(global_vm);
89 sq_newtable(global_vm);
90 sq_pushroottable(global_vm);
91 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
92 throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
94 sq_resetobject(§or_table);
95 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
96 throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
97 sq_addref(global_vm, §or_table);
103 using namespace Scripting;
107 for(ScriptList::iterator i = scripts.begin();
108 i != scripts.end(); ++i) {
109 HSQOBJECT& object = *i;
110 sq_release(global_vm, &object);
112 sq_release(global_vm, §or_table);
113 sq_collectgarbage(global_vm);
115 update_game_objects();
116 assert(gameobjects_new.size() == 0);
118 for(GameObjects::iterator i = gameobjects.begin();
119 i != gameobjects.end(); ++i) {
120 GameObject* object = *i;
121 before_object_remove(object);
125 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
137 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
139 if(name == "camera") {
140 Camera* camera = new Camera(this, "Camera");
141 camera->parse(reader);
143 } else if(name == "particles-snow") {
144 SnowParticleSystem* partsys = new SnowParticleSystem();
145 partsys->parse(reader);
147 } else if(name == "particles-rain") {
148 RainParticleSystem* partsys = new RainParticleSystem();
149 partsys->parse(reader);
151 } else if(name == "particles-comets") {
152 CometParticleSystem* partsys = new CometParticleSystem();
153 partsys->parse(reader);
155 } else if(name == "particles-ghosts") {
156 GhostParticleSystem* partsys = new GhostParticleSystem();
157 partsys->parse(reader);
159 } else if(name == "particles-clouds") {
160 CloudParticleSystem* partsys = new CloudParticleSystem();
161 partsys->parse(reader);
163 } else if(name == "money") { // for compatibility with old maps
164 return new Jumpy(reader);
168 return create_object(name, reader);
169 } catch(std::exception& e) {
170 log_warning << e.what() << "" << std::endl;
177 Sector::parse(const lisp::Lisp& sector)
179 lisp::ListIterator iter(§or);
181 const std::string& token = iter.item();
182 if(token == "name") {
183 iter.value()->get(name);
184 } else if(token == "gravity") {
185 iter.value()->get(gravity);
186 } else if(token == "music") {
187 iter.value()->get(music);
188 } else if(token == "spawnpoint") {
189 SpawnPoint* sp = new SpawnPoint(iter.lisp());
190 spawnpoints.push_back(sp);
191 } else if(token == "init-script") {
192 iter.value()->get(init_script);
193 } else if(token == "ambient-light") {
194 std::vector<float> vColor;
195 sector.get_vector( "ambient-light", vColor );
196 if(vColor.size() < 3) {
197 log_warning << "(ambient-light) requires a color as argument" << std::endl;
199 ambient_light = Color( vColor );
202 GameObject* object = parse_object(token, *(iter.lisp()));
209 update_game_objects();
211 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
215 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
216 update_game_objects();
217 add_object(new Camera(this, "Camera"));
220 update_game_objects();
224 Sector::parse_old_format(const lisp::Lisp& reader)
227 reader.get("gravity", gravity);
229 std::string backgroundimage;
230 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
231 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
232 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
233 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
234 backgroundimage = "images/background/" + backgroundimage;
235 if (!PHYSFS_exists(backgroundimage.c_str())) {
236 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
237 backgroundimage = "";
242 reader.get("bkgd_speed", bgspeed);
245 Color bkgd_top, bkgd_bottom;
246 int r = 0, g = 0, b = 128;
247 reader.get("bkgd_red_top", r);
248 reader.get("bkgd_green_top", g);
249 reader.get("bkgd_blue_top", b);
250 bkgd_top.red = static_cast<float> (r) / 255.0f;
251 bkgd_top.green = static_cast<float> (g) / 255.0f;
252 bkgd_top.blue = static_cast<float> (b) / 255.0f;
254 reader.get("bkgd_red_bottom", r);
255 reader.get("bkgd_green_bottom", g);
256 reader.get("bkgd_blue_bottom", b);
257 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
258 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
259 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
261 if(backgroundimage != "") {
262 Background* background = new Background();
263 background->set_image(backgroundimage, bgspeed);
264 add_object(background);
266 Gradient* gradient = new Gradient();
267 gradient->set_gradient(bkgd_top, bkgd_bottom);
268 add_object(gradient);
271 std::string particlesystem;
272 reader.get("particle_system", particlesystem);
273 if(particlesystem == "clouds")
274 add_object(new CloudParticleSystem());
275 else if(particlesystem == "snow")
276 add_object(new SnowParticleSystem());
277 else if(particlesystem == "rain")
278 add_object(new RainParticleSystem());
280 Vector startpos(100, 170);
281 reader.get("start_pos_x", startpos.x);
282 reader.get("start_pos_y", startpos.y);
284 SpawnPoint* spawn = new SpawnPoint;
285 spawn->pos = startpos;
286 spawn->name = "main";
287 spawnpoints.push_back(spawn);
289 music = "chipdisko.ogg";
290 // skip reading music filename. It's all .ogg now, anyway
292 reader.get("music", music);
294 music = "music/" + music;
296 int width = 30, height = 15;
297 reader.get("width", width);
298 reader.get("height", height);
300 std::vector<unsigned int> tiles;
301 if(reader.get_vector("interactive-tm", tiles)
302 || reader.get_vector("tilemap", tiles)) {
303 TileMap* tilemap = new TileMap();
304 tilemap->set(width, height, tiles, LAYER_TILES, true);
306 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
307 for(size_t x=0; x < tilemap->get_width(); ++x) {
308 for(size_t y=0; y < tilemap->get_height(); ++y) {
309 const Tile* tile = tilemap->get_tile(x, y);
310 if(tile->getID() == 112) tilemap->change(x, y, 1311);
314 if (height < 19) tilemap->resize(width, 19);
318 if(reader.get_vector("background-tm", tiles)) {
319 TileMap* tilemap = new TileMap();
320 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
321 if (height < 19) tilemap->resize(width, 19);
325 if(reader.get_vector("foreground-tm", tiles)) {
326 TileMap* tilemap = new TileMap();
327 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
329 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
330 if (height < 19) tilemap->resize(width, 19, 2035);
335 // read reset-points (now spawn-points)
336 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
338 lisp::ListIterator iter(resetpoints);
340 if(iter.item() == "point") {
342 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
344 SpawnPoint* sp = new SpawnPoint;
347 spawnpoints.push_back(sp);
350 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
356 const lisp::Lisp* objects = reader.get_lisp("objects");
358 lisp::ListIterator iter(objects);
360 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
364 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
370 Camera* camera = new Camera(this, "Camera");
373 update_game_objects();
375 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
378 update_game_objects();
382 Sector::fix_old_tiles()
384 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
385 TileMap* solids = *i;
386 for(size_t x=0; x < solids->get_width(); ++x) {
387 for(size_t y=0; y < solids->get_height(); ++y) {
388 const Tile* tile = solids->get_tile(x, y);
389 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
391 if(tile->getID() == 112) {
392 add_object(new InvisibleBlock(pos));
393 solids->change(x, y, 0);
394 } else if(tile->getAttributes() & Tile::COIN) {
395 add_object(new Coin(pos));
396 solids->change(x, y, 0);
397 } else if(tile->getAttributes() & Tile::FULLBOX) {
398 add_object(new BonusBlock(pos, tile->getData()));
399 solids->change(x, y, 0);
400 } else if(tile->getAttributes() & Tile::BRICK) {
401 add_object(new Brick(pos, tile->getData()));
402 solids->change(x, y, 0);
403 } else if(tile->getAttributes() & Tile::GOAL) {
404 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
405 add_object(new SequenceTrigger(pos, sequence));
406 solids->change(x, y, 0);
412 // add lights for special tiles
413 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
414 TileMap* tm = dynamic_cast<TileMap*>(*i);
416 for(size_t x=0; x < tm->get_width(); ++x) {
417 for(size_t y=0; y < tm->get_height(); ++y) {
418 const Tile* tile = tm->get_tile(x, y);
419 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
420 Vector center(pos.x + 16, pos.y + 16);
423 if (tile->getID() == 1517) {
424 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
425 add_object(new PulsingLight(center, 1.0 + pseudo_rnd, 0.9, 1.0, Color(1.0, 1.0, 0.6, 1.0)));
428 if ((tile->getID() == 173) || (tile->getID() == 1700) || (tile->getID() == 1705) || (tile->getID() == 1706)) {
429 // space lights a bit
430 if (((tm->get_tile(x-1, y)->getID() != tm->get_tile(x,y)->getID())
431 && (tm->get_tile(x, y-1)->getID() != tm->get_tile(x,y)->getID()))
432 || ((x % 3 == 0) && (y % 3 == 0))) {
433 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
434 add_object(new PulsingLight(center, 1.0 + pseudo_rnd, 0.8, 1.0, Color(1.0, 0.3, 0.0, 1.0)));
446 Sector::write(lisp::Writer& writer)
448 writer.write_string("name", name);
449 writer.write_float("gravity", gravity);
450 writer.write_string("music", music);
453 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
455 SpawnPoint* spawn = *i;
456 writer.start_list("spawn-points");
457 writer.write_string("name", spawn->name);
458 writer.write_float("x", spawn->pos.x);
459 writer.write_float("y", spawn->pos.y);
460 writer.end_list("spawn-points");
464 for(GameObjects::iterator i = gameobjects.begin();
465 i != gameobjects.end(); ++i) {
466 Serializable* serializable = dynamic_cast<Serializable*> (*i);
468 serializable->write(writer);
473 Sector::run_script(std::istream& in, const std::string& sourcename)
475 using namespace Scripting;
477 // garbage collect thread list
478 for(ScriptList::iterator i = scripts.begin();
479 i != scripts.end(); ) {
480 HSQOBJECT& object = *i;
481 HSQUIRRELVM vm = object_to_vm(object);
483 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
484 sq_release(global_vm, &object);
485 i = scripts.erase(i);
492 HSQOBJECT object = create_thread(global_vm);
493 scripts.push_back(object);
495 HSQUIRRELVM vm = object_to_vm(object);
497 // set sector_table as roottable for the thread
498 sq_pushobject(vm, sector_table);
501 compile_and_run(vm, in, sourcename);
507 Sector::add_object(GameObject* object)
509 // make sure the object isn't already in the list
511 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
514 assert("object already added to sector" == 0);
517 for(GameObjects::iterator i = gameobjects_new.begin();
518 i != gameobjects_new.end(); ++i) {
520 assert("object already added to sector" == 0);
526 gameobjects_new.push_back(object);
530 Sector::activate(const std::string& spawnpoint)
533 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
535 if((*i)->name == spawnpoint) {
541 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
542 if(spawnpoint != "main") {
545 activate(Vector(0, 0));
553 Sector::activate(const Vector& player_pos)
555 if(_current != this) {
557 _current->deactivate();
560 // register sectortable as sector in scripting
561 HSQUIRRELVM vm = Scripting::global_vm;
562 sq_pushroottable(vm);
563 sq_pushstring(vm, "sector", -1);
564 sq_pushobject(vm, sector_table);
565 if(SQ_FAILED(sq_createslot(vm, -3)))
566 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
569 for(GameObjects::iterator i = gameobjects.begin();
570 i != gameobjects.end(); ++i) {
571 GameObject* object = *i;
578 // spawn smalltux below spawnpoint
579 if (!player->is_big()) {
580 player->move(player_pos + Vector(0,32));
582 player->move(player_pos);
585 // spawning tux in the ground would kill him
586 if(!is_free_of_tiles(player->get_bbox())) {
587 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
588 Vector npos = player->get_bbox().p1;
593 camera->reset(player->get_pos());
594 update_game_objects();
597 if(init_script != "") {
598 std::istringstream in(init_script);
599 run_script(in, std::string("Sector(") + name + ") - init");
609 // remove sector entry from global vm
610 HSQUIRRELVM vm = Scripting::global_vm;
611 sq_pushroottable(vm);
612 sq_pushstring(vm, "sector", -1);
613 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
614 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
617 for(GameObjects::iterator i = gameobjects.begin();
618 i != gameobjects.end(); ++i) {
619 GameObject* object = *i;
621 try_unexpose(object);
629 Sector::get_active_region()
632 camera->get_translation() - Vector(1600, 1200),
633 camera->get_translation() + Vector(1600, 1200));
637 Sector::update(float elapsed_time)
639 player->check_bounds(camera);
642 for(GameObjects::iterator i = gameobjects.begin();
643 i != gameobjects.end(); ++i) {
644 GameObject* object = *i;
645 if(!object->is_valid())
648 object->update(elapsed_time);
651 /* Handle all possible collisions. */
653 update_game_objects();
657 Sector::update_game_objects()
659 /** cleanup marked objects */
660 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
661 i != gameobjects.end(); /* nothing */) {
662 GameObject* object = *i;
664 if(object->is_valid()) {
669 before_object_remove(object);
672 i = gameobjects.erase(i);
675 /* add newly created objects */
676 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
677 i != gameobjects_new.end(); ++i)
679 GameObject* object = *i;
681 before_object_add(object);
683 gameobjects.push_back(object);
685 gameobjects_new.clear();
689 Sector::before_object_add(GameObject* object)
691 Bullet* bullet = dynamic_cast<Bullet*> (object);
693 bullets.push_back(bullet);
696 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
697 if(movingobject != NULL) {
698 moving_objects.push_back(movingobject);
701 Portable* portable = dynamic_cast<Portable*> (object);
702 if(portable != NULL) {
703 portables.push_back(portable);
706 TileMap* tilemap = dynamic_cast<TileMap*> (object);
707 if(tilemap != NULL && tilemap->is_solid()) {
708 solid_tilemaps.push_back(tilemap);
711 Camera* camera = dynamic_cast<Camera*> (object);
713 if(this->camera != 0) {
714 log_warning << "Multiple cameras added. Ignoring" << std::endl;
717 this->camera = camera;
720 Player* player = dynamic_cast<Player*> (object);
722 if(this->player != 0) {
723 log_warning << "Multiple players added. Ignoring" << std::endl;
726 this->player = player;
729 UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
732 physic_object->physic.set_gravity(gravity);
736 if(_current == this) {
744 Sector::try_expose(GameObject* object)
746 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
747 if(interface != NULL) {
748 HSQUIRRELVM vm = Scripting::global_vm;
749 sq_pushobject(vm, sector_table);
750 interface->expose(vm, -1);
756 Sector::try_expose_me()
758 HSQUIRRELVM vm = Scripting::global_vm;
759 sq_pushobject(vm, sector_table);
760 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
761 expose_object(vm, -1, interface, "settings", false);
766 Sector::before_object_remove(GameObject* object)
768 Portable* portable = dynamic_cast<Portable*> (object);
769 if(portable != NULL) {
770 portables.erase(std::find(portables.begin(), portables.end(), portable));
772 Bullet* bullet = dynamic_cast<Bullet*> (object);
774 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
776 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
777 if(moving_object != NULL) {
778 moving_objects.erase(
779 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
783 try_unexpose(object);
787 Sector::try_unexpose(GameObject* object)
789 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
790 if(interface != NULL) {
791 HSQUIRRELVM vm = Scripting::global_vm;
792 SQInteger oldtop = sq_gettop(vm);
793 sq_pushobject(vm, sector_table);
795 interface->unexpose(vm, -1);
796 } catch(std::exception& e) {
797 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
799 sq_settop(vm, oldtop);
804 Sector::try_unexpose_me()
806 HSQUIRRELVM vm = Scripting::global_vm;
807 SQInteger oldtop = sq_gettop(vm);
808 sq_pushobject(vm, sector_table);
810 Scripting::unexpose_object(vm, -1, "settings");
811 } catch(std::exception& e) {
812 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
814 sq_settop(vm, oldtop);
817 Sector::draw(DrawingContext& context)
819 context.set_ambient_color( ambient_light );
820 context.push_transform();
821 context.set_translation(camera->get_translation());
823 for(GameObjects::iterator i = gameobjects.begin();
824 i != gameobjects.end(); ++i) {
825 GameObject* object = *i;
826 if(!object->is_valid())
829 if (draw_solids_only)
831 TileMap* tm = dynamic_cast<TileMap*>(object);
832 if (tm && !tm->is_solid())
836 object->draw(context);
840 Color col(0.2, 0.2, 0.2, 0.7);
841 for(MovingObjects::iterator i = moving_objects.begin();
842 i != moving_objects.end(); ++i) {
843 MovingObject* object = *i;
844 const Rect& rect = object->get_bbox();
846 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
850 context.pop_transform();
853 /*-------------------------------------------------------------------------
854 * Collision Detection
855 *-------------------------------------------------------------------------*/
857 static const float SHIFT_DELTA = 7.0f;
859 /** r1 is supposed to be moving, r2 a solid object */
860 void check_collisions(collision::Constraints* constraints,
861 const Vector& movement, const Rect& r1, const Rect& r2,
862 GameObject* object = NULL, MovingObject* other = NULL)
864 if(!collision::intersects(r1, r2))
867 // calculate intersection
868 float itop = r1.get_bottom() - r2.get_top();
869 float ibottom = r2.get_bottom() - r1.get_top();
870 float ileft = r1.get_right() - r2.get_left();
871 float iright = r2.get_right() - r1.get_left();
873 if(fabsf(movement.y) > fabsf(movement.x)) {
874 if(ileft < SHIFT_DELTA) {
875 constraints->right = std::min(constraints->right, r2.get_left());
877 } else if(iright < SHIFT_DELTA) {
878 constraints->left = std::max(constraints->left, r2.get_right());
882 // shiftout bottom/top
883 if(itop < SHIFT_DELTA) {
884 constraints->bottom = std::min(constraints->bottom, r2.get_top());
886 } else if(ibottom < SHIFT_DELTA) {
887 constraints->top = std::max(constraints->top, r2.get_bottom());
894 HitResponse response = other->collision(*object, dummy);
895 if(response == PASSTHROUGH)
897 if(other->get_movement() != Vector(0, 0)) {
898 // TODO what todo when we collide with 2 moving objects?!?
899 constraints->ground_movement = other->get_movement();
903 float vert_penetration = std::min(itop, ibottom);
904 float horiz_penetration = std::min(ileft, iright);
905 if(vert_penetration < horiz_penetration) {
907 constraints->bottom = std::min(constraints->bottom, r2.get_top());
908 constraints->hit.bottom = true;
910 constraints->top = std::max(constraints->top, r2.get_bottom());
911 constraints->hit.top = true;
915 constraints->right = std::min(constraints->right, r2.get_left());
916 constraints->hit.right = true;
918 constraints->left = std::max(constraints->left, r2.get_right());
919 constraints->hit.left = true;
924 static const float DELTA = .001;
927 Sector::collision_tilemap(collision::Constraints* constraints,
928 const Vector& movement, const Rect& dest) const
930 // calculate rectangle where the object will move
931 float x1 = dest.get_left();
932 float x2 = dest.get_right();
933 float y1 = dest.get_top();
934 float y2 = dest.get_bottom();
936 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
937 TileMap* solids = *i;
939 // test with all tiles in this rectangle
940 int starttilex = int(x1 - solids->get_x_offset()) / 32;
941 int starttiley = int(y1 - solids->get_y_offset()) / 32;
942 int max_x = int(x2 - solids->get_x_offset());
943 int max_y = int(y2+1 - solids->get_y_offset());
945 for(int x = starttilex; x*32 < max_x; ++x) {
946 for(int y = starttiley; y*32 < max_y; ++y) {
947 const Tile* tile = solids->get_tile(x, y);
950 // skip non-solid tiles
951 if((tile->getAttributes() & Tile::SOLID) == 0)
953 // only handle unisolid when the player is falling down and when he was
954 // above the tile before
955 if(tile->getAttributes() & Tile::UNISOLID) {
956 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
960 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
962 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
963 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
964 triangle = AATriangle(p1, p2, tile->getData());
966 collision::rectangle_aatriangle(constraints, dest, triangle);
967 } else { // normal rectangular tile
968 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());
969 check_collisions(constraints, movement, dest, rect);
977 Sector::collision_tile_attributes(const Rect& dest) const
979 float x1 = dest.p1.x;
980 float y1 = dest.p1.y;
981 float x2 = dest.p2.x;
982 float y2 = dest.p2.y;
985 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
986 TileMap* solids = *i;
988 // test with all tiles in this rectangle
989 int starttilex = int(x1 - solids->get_x_offset()) / 32;
990 int starttiley = int(y1 - solids->get_y_offset()) / 32;
991 int max_x = int(x2 - solids->get_x_offset());
992 int max_y = int(y2+1 - solids->get_y_offset());
994 for(int x = starttilex; x*32 < max_x; ++x) {
995 for(int y = starttiley; y*32 < max_y; ++y) {
996 const Tile* tile = solids->get_tile(x, y);
999 result |= tile->getAttributes();
1007 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1008 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1011 float itop = r1.get_bottom() - r2.get_top();
1012 float ibottom = r2.get_bottom() - r1.get_top();
1013 float ileft = r1.get_right() - r2.get_left();
1014 float iright = r2.get_right() - r1.get_left();
1016 float vert_penetration = std::min(itop, ibottom);
1017 float horiz_penetration = std::min(ileft, iright);
1018 if(vert_penetration < horiz_penetration) {
1019 if(itop < ibottom) {
1021 normal.y = vert_penetration;
1024 normal.y = -vert_penetration;
1027 if(ileft < iright) {
1029 normal.x = horiz_penetration;
1032 normal.x = -horiz_penetration;
1038 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1040 using namespace collision;
1042 const Rect& r1 = object1->dest;
1043 const Rect& r2 = object2->dest;
1046 if(intersects(object1->dest, object2->dest)) {
1048 get_hit_normal(r1, r2, hit, normal);
1050 HitResponse response1 = object1->collision(*object2, hit);
1051 std::swap(hit.left, hit.right);
1052 std::swap(hit.top, hit.bottom);
1053 HitResponse response2 = object2->collision(*object1, hit);
1054 assert( response1 != SOLID && response1 != PASSTHROUGH );
1055 assert( response2 != SOLID && response2 != PASSTHROUGH );
1056 if(response1 == CONTINUE && response2 == CONTINUE) {
1057 normal *= (0.5 + DELTA);
1058 object1->dest.move(-normal);
1059 object2->dest.move(normal);
1060 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1061 normal *= (1 + DELTA);
1062 object1->dest.move(-normal);
1063 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1064 normal *= (1 + DELTA);
1065 object2->dest.move(normal);
1071 Sector::collision_static(collision::Constraints* constraints,
1072 const Vector& movement, const Rect& dest,
1075 collision_tilemap(constraints, movement, dest);
1077 // collision with other (static) objects
1078 for(MovingObjects::iterator i = moving_objects.begin();
1079 i != moving_objects.end(); ++i) {
1080 MovingObject* moving_object = *i;
1081 if(moving_object->get_group() != COLGROUP_STATIC
1082 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1084 if(!moving_object->is_valid())
1087 if(moving_object != &object)
1088 check_collisions(constraints, movement, dest, moving_object->bbox,
1089 &object, moving_object);
1094 Sector::collision_static_constrains(MovingObject& object)
1096 using namespace collision;
1097 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1099 Constraints constraints;
1100 Vector movement = object.get_movement();
1101 Rect& dest = object.dest;
1102 float owidth = object.get_bbox().get_width();
1103 float oheight = object.get_bbox().get_height();
1105 for(int i = 0; i < 2; ++i) {
1106 collision_static(&constraints, Vector(0, movement.y), dest, object);
1107 if(!constraints.has_constraints())
1110 // apply calculated horizontal constraints
1111 if(constraints.bottom < infinity) {
1112 float height = constraints.bottom - constraints.top;
1113 if(height < oheight) {
1114 // we're crushed, but ignore this for now, we'll get this again
1115 // later if we're really crushed or things will solve itself when
1116 // looking at the vertical constraints
1118 dest.p2.y = constraints.bottom - DELTA;
1119 dest.p1.y = dest.p2.y - oheight;
1120 } else if(constraints.top > -infinity) {
1121 dest.p1.y = constraints.top + DELTA;
1122 dest.p2.y = dest.p1.y + oheight;
1125 if(constraints.has_constraints()) {
1126 if(constraints.hit.bottom) {
1127 dest.move(constraints.ground_movement);
1129 if(constraints.hit.top || constraints.hit.bottom) {
1130 constraints.hit.left = false;
1131 constraints.hit.right = false;
1132 object.collision_solid(constraints.hit);
1136 constraints = Constraints();
1137 for(int i = 0; i < 2; ++i) {
1138 collision_static(&constraints, movement, dest, object);
1139 if(!constraints.has_constraints())
1142 // apply calculated vertical constraints
1143 if(constraints.right < infinity) {
1144 float width = constraints.right - constraints.left;
1145 if(width + SHIFT_DELTA < owidth) {
1146 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1147 constraints.left, constraints.right);
1152 object.collision_solid(h);
1154 dest.p2.x = constraints.right - DELTA;
1155 dest.p1.x = dest.p2.x - owidth;
1157 } else if(constraints.left > -infinity) {
1158 dest.p1.x = constraints.left + DELTA;
1159 dest.p2.x = dest.p1.x + owidth;
1163 if(constraints.has_constraints()) {
1164 if( constraints.hit.left || constraints.hit.right
1165 || constraints.hit.top || constraints.hit.bottom
1166 || constraints.hit.crush )
1167 object.collision_solid(constraints.hit);
1170 // an extra pass to make sure we're not crushed horizontally
1171 constraints = Constraints();
1172 collision_static(&constraints, movement, dest, object);
1173 if(constraints.bottom < infinity) {
1174 float height = constraints.bottom - constraints.top;
1175 if(height + SHIFT_DELTA < oheight) {
1176 printf("Object %p crushed vertically...\n", &object);
1181 object.collision_solid(h);
1187 Sector::handle_collisions()
1189 using namespace collision;
1191 // calculate destination positions of the objects
1192 for(MovingObjects::iterator i = moving_objects.begin();
1193 i != moving_objects.end(); ++i) {
1194 MovingObject* moving_object = *i;
1196 moving_object->dest = moving_object->get_bbox();
1197 moving_object->dest.move(moving_object->get_movement());
1200 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1201 for(MovingObjects::iterator i = moving_objects.begin();
1202 i != moving_objects.end(); ++i) {
1203 MovingObject* moving_object = *i;
1204 if((moving_object->get_group() != COLGROUP_MOVING
1205 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1206 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1207 || !moving_object->is_valid())
1210 collision_static_constrains(*moving_object);
1214 // part2: COLGROUP_MOVING vs tile attributes
1215 for(MovingObjects::iterator i = moving_objects.begin();
1216 i != moving_objects.end(); ++i) {
1217 MovingObject* moving_object = *i;
1218 if((moving_object->get_group() != COLGROUP_MOVING
1219 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1220 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1221 || !moving_object->is_valid())
1224 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1225 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1226 moving_object->collision_tile(tile_attributes);
1230 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1231 for(MovingObjects::iterator i = moving_objects.begin();
1232 i != moving_objects.end(); ++i) {
1233 MovingObject* moving_object = *i;
1234 if((moving_object->get_group() != COLGROUP_MOVING
1235 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1236 || !moving_object->is_valid())
1239 for(MovingObjects::iterator i2 = moving_objects.begin();
1240 i2 != moving_objects.end(); ++i2) {
1241 MovingObject* moving_object_2 = *i2;
1242 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1243 || !moving_object_2->is_valid())
1246 if(intersects(moving_object->dest, moving_object_2->dest)) {
1249 get_hit_normal(moving_object->dest, moving_object_2->dest,
1251 moving_object->collision(*moving_object_2, hit);
1252 moving_object_2->collision(*moving_object, hit);
1257 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1258 for(MovingObjects::iterator i = moving_objects.begin();
1259 i != moving_objects.end(); ++i) {
1260 MovingObject* moving_object = *i;
1262 if((moving_object->get_group() != COLGROUP_MOVING
1263 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1264 || !moving_object->is_valid())
1267 for(MovingObjects::iterator i2 = i+1;
1268 i2 != moving_objects.end(); ++i2) {
1269 MovingObject* moving_object_2 = *i2;
1270 if((moving_object_2->get_group() != COLGROUP_MOVING
1271 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1272 || !moving_object_2->is_valid())
1275 collision_object(moving_object, moving_object_2);
1279 // apply object movement
1280 for(MovingObjects::iterator i = moving_objects.begin();
1281 i != moving_objects.end(); ++i) {
1282 MovingObject* moving_object = *i;
1284 moving_object->bbox = moving_object->dest;
1285 moving_object->movement = Vector(0, 0);
1290 Sector::is_free_of_tiles(const Rect& rect) const
1292 using namespace collision;
1294 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1295 TileMap* solids = *i;
1297 // test with all tiles in this rectangle
1298 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1299 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1300 int max_x = int(rect.p2.x - solids->get_x_offset());
1301 int max_y = int(rect.p2.y - solids->get_y_offset());
1303 for(int x = starttilex; x*32 <= max_x; ++x) {
1304 for(int y = starttiley; y*32 <= max_y; ++y) {
1305 const Tile* tile = solids->get_tile(x, y);
1307 if(tile->getAttributes() & Tile::SLOPE) {
1308 AATriangle triangle;
1309 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1310 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1311 triangle = AATriangle(p1, p2, tile->getData());
1312 Constraints constraints;
1313 return collision::rectangle_aatriangle(&constraints, rect, triangle);
1315 if(tile->getAttributes() & Tile::SOLID) return false;
1324 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object) const
1326 using namespace collision;
1328 if (!is_free_of_tiles(rect)) return false;
1330 for(MovingObjects::const_iterator i = moving_objects.begin();
1331 i != moving_objects.end(); ++i) {
1332 const MovingObject* moving_object = *i;
1333 if (moving_object == ignore_object) continue;
1334 if (!moving_object->is_valid()) continue;
1335 if (moving_object->get_group() == COLGROUP_STATIC) {
1336 if(intersects(rect, moving_object->get_bbox())) return false;
1344 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1346 using namespace collision;
1348 if (!is_free_of_tiles(rect)) return false;
1350 for(MovingObjects::const_iterator i = moving_objects.begin();
1351 i != moving_objects.end(); ++i) {
1352 const MovingObject* moving_object = *i;
1353 if (moving_object == ignore_object) continue;
1354 if (!moving_object->is_valid()) continue;
1355 if ((moving_object->get_group() == COLGROUP_MOVING)
1356 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1357 || (moving_object->get_group() == COLGROUP_STATIC)) {
1358 if(intersects(rect, moving_object->get_bbox())) return false;
1366 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1368 // TODO remove this function and move these checks elsewhere...
1370 Bullet* new_bullet = 0;
1371 if((player_status->bonus == FIRE_BONUS &&
1372 (int)bullets.size() >= player_status->max_fire_bullets) ||
1373 (player_status->bonus == ICE_BONUS &&
1374 (int)bullets.size() >= player_status->max_ice_bullets))
1376 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1377 add_object(new_bullet);
1379 sound_manager->play("sounds/shoot.wav");
1385 Sector::add_smoke_cloud(const Vector& pos)
1387 add_object(new SmokeCloud(pos));
1392 Sector::play_music(MusicType type)
1394 currentmusic = type;
1395 switch(currentmusic) {
1397 sound_manager->play_music(music);
1400 sound_manager->play_music("music/salcon.ogg");
1402 case HERRING_WARNING_MUSIC:
1403 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1406 sound_manager->play_music("");
1412 Sector::get_music_type()
1414 return currentmusic;
1418 Sector::get_total_badguys()
1420 int total_badguys = 0;
1421 for(GameObjects::iterator i = gameobjects.begin();
1422 i != gameobjects.end(); ++i) {
1423 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1424 if (badguy && badguy->countMe)
1428 return total_badguys;
1432 Sector::inside(const Rect& rect) const
1434 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1435 TileMap* solids = *i;
1436 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1437 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1438 if (horizontally && vertically) return true;
1444 Sector::get_width() const
1447 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1448 TileMap* solids = *i;
1449 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) width = (solids->get_width() * 32 + solids->get_x_offset());
1455 Sector::get_height() const
1458 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1459 TileMap* solids = *i;
1460 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) height = (solids->get_height() * 32 + solids->get_y_offset());
1466 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1468 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1469 TileMap* solids = *i;
1470 solids->change_all(old_tile_id, new_tile_id);
1476 Sector::set_ambient_light(float red, float green, float blue)
1478 ambient_light.red = red;
1479 ambient_light.green = green;
1480 ambient_light.blue = blue;
1484 Sector::get_ambient_red()
1486 return ambient_light.red;
1490 Sector::get_ambient_green()
1492 return ambient_light.green;
1496 Sector::get_ambient_blue()
1498 return ambient_light.blue;