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"
72 Sector* Sector::_current = 0;
74 bool Sector::show_collrects = false;
75 bool Sector::draw_solids_only = false;
77 Sector::Sector(Level* parent)
78 : level(parent), currentmusic(LEVEL_MUSIC),
79 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10.0), player(0), camera(0)
81 add_object(new Player(player_status, "Tux"));
82 add_object(new DisplayEffect("Effect"));
83 add_object(new TextObject("Text"));
85 // create a new squirrel table for the sector
86 using namespace Scripting;
88 sq_collectgarbage(global_vm);
90 sq_newtable(global_vm);
91 sq_pushroottable(global_vm);
92 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
93 throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
95 sq_resetobject(§or_table);
96 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
97 throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
98 sq_addref(global_vm, §or_table);
104 using namespace Scripting;
108 for(ScriptList::iterator i = scripts.begin();
109 i != scripts.end(); ++i) {
110 HSQOBJECT& object = *i;
111 sq_release(global_vm, &object);
113 sq_release(global_vm, §or_table);
114 sq_collectgarbage(global_vm);
116 update_game_objects();
117 assert(gameobjects_new.size() == 0);
119 for(GameObjects::iterator i = gameobjects.begin();
120 i != gameobjects.end(); ++i) {
121 GameObject* object = *i;
122 before_object_remove(object);
126 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
138 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
140 if(name == "camera") {
141 Camera* camera = new Camera(this, "Camera");
142 camera->parse(reader);
144 } else if(name == "particles-snow") {
145 SnowParticleSystem* partsys = new SnowParticleSystem();
146 partsys->parse(reader);
148 } else if(name == "particles-rain") {
149 RainParticleSystem* partsys = new RainParticleSystem();
150 partsys->parse(reader);
152 } else if(name == "particles-comets") {
153 CometParticleSystem* partsys = new CometParticleSystem();
154 partsys->parse(reader);
156 } else if(name == "particles-ghosts") {
157 GhostParticleSystem* partsys = new GhostParticleSystem();
158 partsys->parse(reader);
160 } else if(name == "particles-clouds") {
161 CloudParticleSystem* partsys = new CloudParticleSystem();
162 partsys->parse(reader);
164 } else if(name == "money") { // for compatibility with old maps
165 return new Jumpy(reader);
169 return create_object(name, reader);
170 } catch(std::exception& e) {
171 log_warning << e.what() << "" << std::endl;
178 Sector::parse(const lisp::Lisp& sector)
180 bool has_background = false;
181 lisp::ListIterator iter(§or);
183 const std::string& token = iter.item();
184 if(token == "name") {
185 iter.value()->get(name);
186 } else if(token == "gravity") {
187 iter.value()->get(gravity);
188 } else if(token == "music") {
189 iter.value()->get(music);
190 } else if(token == "spawnpoint") {
191 SpawnPoint* sp = new SpawnPoint(iter.lisp());
192 spawnpoints.push_back(sp);
193 } else if(token == "init-script") {
194 iter.value()->get(init_script);
195 } else if(token == "ambient-light") {
196 std::vector<float> vColor;
197 sector.get_vector( "ambient-light", vColor );
198 if(vColor.size() < 3) {
199 log_warning << "(ambient-light) requires a color as argument" << std::endl;
201 ambient_light = Color( vColor );
204 GameObject* object = parse_object(token, *(iter.lisp()));
206 if(dynamic_cast<Background *>(object)) {
207 has_background = true;
208 } else if(dynamic_cast<Gradient *>(object)) {
209 has_background = true;
216 if(!has_background) {
217 Gradient* gradient = new Gradient();
218 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
219 add_object(gradient);
222 update_game_objects();
224 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
228 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
229 update_game_objects();
230 add_object(new Camera(this, "Camera"));
233 update_game_objects();
237 Sector::parse_old_format(const lisp::Lisp& reader)
240 reader.get("gravity", gravity);
242 std::string backgroundimage;
243 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
244 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
245 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
246 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
247 backgroundimage = "images/background/" + backgroundimage;
248 if (!PHYSFS_exists(backgroundimage.c_str())) {
249 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
250 backgroundimage = "";
255 reader.get("bkgd_speed", bgspeed);
258 Color bkgd_top, bkgd_bottom;
259 int r = 0, g = 0, b = 128;
260 reader.get("bkgd_red_top", r);
261 reader.get("bkgd_green_top", g);
262 reader.get("bkgd_blue_top", b);
263 bkgd_top.red = static_cast<float> (r) / 255.0f;
264 bkgd_top.green = static_cast<float> (g) / 255.0f;
265 bkgd_top.blue = static_cast<float> (b) / 255.0f;
267 reader.get("bkgd_red_bottom", r);
268 reader.get("bkgd_green_bottom", g);
269 reader.get("bkgd_blue_bottom", b);
270 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
271 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
272 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
274 if(backgroundimage != "") {
275 Background* background = new Background();
276 background->set_image(backgroundimage, bgspeed);
277 add_object(background);
279 Gradient* gradient = new Gradient();
280 gradient->set_gradient(bkgd_top, bkgd_bottom);
281 add_object(gradient);
284 std::string particlesystem;
285 reader.get("particle_system", particlesystem);
286 if(particlesystem == "clouds")
287 add_object(new CloudParticleSystem());
288 else if(particlesystem == "snow")
289 add_object(new SnowParticleSystem());
290 else if(particlesystem == "rain")
291 add_object(new RainParticleSystem());
293 Vector startpos(100, 170);
294 reader.get("start_pos_x", startpos.x);
295 reader.get("start_pos_y", startpos.y);
297 SpawnPoint* spawn = new SpawnPoint;
298 spawn->pos = startpos;
299 spawn->name = "main";
300 spawnpoints.push_back(spawn);
302 music = "chipdisko.ogg";
303 // skip reading music filename. It's all .ogg now, anyway
305 reader.get("music", music);
307 music = "music/" + music;
309 int width = 30, height = 15;
310 reader.get("width", width);
311 reader.get("height", height);
313 std::vector<unsigned int> tiles;
314 if(reader.get_vector("interactive-tm", tiles)
315 || reader.get_vector("tilemap", tiles)) {
316 TileMap* tilemap = new TileMap();
317 tilemap->set(width, height, tiles, LAYER_TILES, true);
319 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
320 for(size_t x=0; x < tilemap->get_width(); ++x) {
321 for(size_t y=0; y < tilemap->get_height(); ++y) {
322 const Tile* tile = tilemap->get_tile(x, y);
323 if(tile->getID() == 112) tilemap->change(x, y, 1311);
327 if (height < 19) tilemap->resize(width, 19);
331 if(reader.get_vector("background-tm", tiles)) {
332 TileMap* tilemap = new TileMap();
333 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
334 if (height < 19) tilemap->resize(width, 19);
338 if(reader.get_vector("foreground-tm", tiles)) {
339 TileMap* tilemap = new TileMap();
340 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
342 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
343 if (height < 19) tilemap->resize(width, 19, 2035);
348 // read reset-points (now spawn-points)
349 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
351 lisp::ListIterator iter(resetpoints);
353 if(iter.item() == "point") {
355 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
357 SpawnPoint* sp = new SpawnPoint;
360 spawnpoints.push_back(sp);
363 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
369 const lisp::Lisp* objects = reader.get_lisp("objects");
371 lisp::ListIterator iter(objects);
373 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
377 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
383 Camera* camera = new Camera(this, "Camera");
386 update_game_objects();
388 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
391 update_game_objects();
395 Sector::fix_old_tiles()
397 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
398 TileMap* solids = *i;
399 for(size_t x=0; x < solids->get_width(); ++x) {
400 for(size_t y=0; y < solids->get_height(); ++y) {
401 const Tile* tile = solids->get_tile(x, y);
402 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
404 if(tile->getID() == 112) {
405 add_object(new InvisibleBlock(pos));
406 solids->change(x, y, 0);
407 } else if(tile->getAttributes() & Tile::COIN) {
408 add_object(new Coin(pos));
409 solids->change(x, y, 0);
410 } else if(tile->getAttributes() & Tile::FULLBOX) {
411 add_object(new BonusBlock(pos, tile->getData()));
412 solids->change(x, y, 0);
413 } else if(tile->getAttributes() & Tile::BRICK) {
414 add_object(new Brick(pos, tile->getData()));
415 solids->change(x, y, 0);
416 } else if(tile->getAttributes() & Tile::GOAL) {
417 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
418 add_object(new SequenceTrigger(pos, sequence));
419 solids->change(x, y, 0);
425 // add lights for special tiles
426 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
427 TileMap* tm = dynamic_cast<TileMap*>(*i);
429 for(size_t x=0; x < tm->get_width(); ++x) {
430 for(size_t y=0; y < tm->get_height(); ++y) {
431 const Tile* tile = tm->get_tile(x, y);
432 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
433 Vector center(pos.x + 16, pos.y + 16);
436 if (tile->getID() == 1517) {
437 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
438 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
441 if ((tile->getID() == 173) || (tile->getID() == 1700) || (tile->getID() == 1705) || (tile->getID() == 1706)) {
442 // space lights a bit
443 if (((tm->get_tile(x-1, y)->getID() != tm->get_tile(x,y)->getID())
444 && (tm->get_tile(x, y-1)->getID() != tm->get_tile(x,y)->getID()))
445 || ((x % 3 == 0) && (y % 3 == 0))) {
446 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
447 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
459 Sector::write(lisp::Writer& writer)
461 writer.write_string("name", name);
462 writer.write_float("gravity", gravity);
463 writer.write_string("music", music);
466 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
468 SpawnPoint* spawn = *i;
469 writer.start_list("spawn-points");
470 writer.write_string("name", spawn->name);
471 writer.write_float("x", spawn->pos.x);
472 writer.write_float("y", spawn->pos.y);
473 writer.end_list("spawn-points");
477 for(GameObjects::iterator i = gameobjects.begin();
478 i != gameobjects.end(); ++i) {
479 Serializable* serializable = dynamic_cast<Serializable*> (*i);
481 serializable->write(writer);
486 Sector::run_script(std::istream& in, const std::string& sourcename)
488 using namespace Scripting;
490 // garbage collect thread list
491 for(ScriptList::iterator i = scripts.begin();
492 i != scripts.end(); ) {
493 HSQOBJECT& object = *i;
494 HSQUIRRELVM vm = object_to_vm(object);
496 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
497 sq_release(global_vm, &object);
498 i = scripts.erase(i);
505 HSQOBJECT object = create_thread(global_vm);
506 scripts.push_back(object);
508 HSQUIRRELVM vm = object_to_vm(object);
510 // set sector_table as roottable for the thread
511 sq_pushobject(vm, sector_table);
514 compile_and_run(vm, in, sourcename);
520 Sector::add_object(GameObject* object)
522 // make sure the object isn't already in the list
524 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
527 assert("object already added to sector" == 0);
530 for(GameObjects::iterator i = gameobjects_new.begin();
531 i != gameobjects_new.end(); ++i) {
533 assert("object already added to sector" == 0);
539 gameobjects_new.push_back(object);
543 Sector::activate(const std::string& spawnpoint)
546 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
548 if((*i)->name == spawnpoint) {
554 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
555 if(spawnpoint != "main") {
558 activate(Vector(0, 0));
566 Sector::activate(const Vector& player_pos)
568 if(_current != this) {
570 _current->deactivate();
573 // register sectortable as sector in scripting
574 HSQUIRRELVM vm = Scripting::global_vm;
575 sq_pushroottable(vm);
576 sq_pushstring(vm, "sector", -1);
577 sq_pushobject(vm, sector_table);
578 if(SQ_FAILED(sq_createslot(vm, -3)))
579 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
582 for(GameObjects::iterator i = gameobjects.begin();
583 i != gameobjects.end(); ++i) {
584 GameObject* object = *i;
591 // spawn smalltux below spawnpoint
592 if (!player->is_big()) {
593 player->move(player_pos + Vector(0,32));
595 player->move(player_pos);
598 // spawning tux in the ground would kill him
599 if(!is_free_of_tiles(player->get_bbox())) {
600 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
601 Vector npos = player->get_bbox().p1;
606 camera->reset(player->get_pos());
607 update_game_objects();
610 if(init_script != "") {
611 std::istringstream in(init_script);
612 run_script(in, std::string("Sector(") + name + ") - init");
622 // remove sector entry from global vm
623 HSQUIRRELVM vm = Scripting::global_vm;
624 sq_pushroottable(vm);
625 sq_pushstring(vm, "sector", -1);
626 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
627 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
630 for(GameObjects::iterator i = gameobjects.begin();
631 i != gameobjects.end(); ++i) {
632 GameObject* object = *i;
634 try_unexpose(object);
642 Sector::get_active_region()
645 camera->get_translation() - Vector(1600, 1200),
646 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
650 Sector::update(float elapsed_time)
652 player->check_bounds(camera);
655 for(GameObjects::iterator i = gameobjects.begin();
656 i != gameobjects.end(); ++i) {
657 GameObject* object = *i;
658 if(!object->is_valid())
661 object->update(elapsed_time);
664 /* Handle all possible collisions. */
666 update_game_objects();
670 Sector::update_game_objects()
672 /** cleanup marked objects */
673 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
674 i != gameobjects.end(); /* nothing */) {
675 GameObject* object = *i;
677 if(object->is_valid()) {
682 before_object_remove(object);
685 i = gameobjects.erase(i);
688 /* add newly created objects */
689 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
690 i != gameobjects_new.end(); ++i)
692 GameObject* object = *i;
694 before_object_add(object);
696 gameobjects.push_back(object);
698 gameobjects_new.clear();
702 Sector::before_object_add(GameObject* object)
704 Bullet* bullet = dynamic_cast<Bullet*> (object);
706 bullets.push_back(bullet);
709 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
710 if(movingobject != NULL) {
711 moving_objects.push_back(movingobject);
714 Portable* portable = dynamic_cast<Portable*> (object);
715 if(portable != NULL) {
716 portables.push_back(portable);
719 TileMap* tilemap = dynamic_cast<TileMap*> (object);
720 if(tilemap != NULL && tilemap->is_solid()) {
721 solid_tilemaps.push_back(tilemap);
724 Camera* camera = dynamic_cast<Camera*> (object);
726 if(this->camera != 0) {
727 log_warning << "Multiple cameras added. Ignoring" << std::endl;
730 this->camera = camera;
733 Player* player = dynamic_cast<Player*> (object);
735 if(this->player != 0) {
736 log_warning << "Multiple players added. Ignoring" << std::endl;
739 this->player = player;
742 UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
745 physic_object->physic.set_gravity(gravity);
749 if(_current == this) {
757 Sector::try_expose(GameObject* object)
759 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
760 if(interface != NULL) {
761 HSQUIRRELVM vm = Scripting::global_vm;
762 sq_pushobject(vm, sector_table);
763 interface->expose(vm, -1);
769 Sector::try_expose_me()
771 HSQUIRRELVM vm = Scripting::global_vm;
772 sq_pushobject(vm, sector_table);
773 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
774 expose_object(vm, -1, interface, "settings", false);
779 Sector::before_object_remove(GameObject* object)
781 Portable* portable = dynamic_cast<Portable*> (object);
782 if(portable != NULL) {
783 portables.erase(std::find(portables.begin(), portables.end(), portable));
785 Bullet* bullet = dynamic_cast<Bullet*> (object);
787 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
789 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
790 if(moving_object != NULL) {
791 moving_objects.erase(
792 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
796 try_unexpose(object);
800 Sector::try_unexpose(GameObject* object)
802 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
803 if(interface != NULL) {
804 HSQUIRRELVM vm = Scripting::global_vm;
805 SQInteger oldtop = sq_gettop(vm);
806 sq_pushobject(vm, sector_table);
808 interface->unexpose(vm, -1);
809 } catch(std::exception& e) {
810 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
812 sq_settop(vm, oldtop);
817 Sector::try_unexpose_me()
819 HSQUIRRELVM vm = Scripting::global_vm;
820 SQInteger oldtop = sq_gettop(vm);
821 sq_pushobject(vm, sector_table);
823 Scripting::unexpose_object(vm, -1, "settings");
824 } catch(std::exception& e) {
825 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
827 sq_settop(vm, oldtop);
830 Sector::draw(DrawingContext& context)
832 context.set_ambient_color( ambient_light );
833 context.push_transform();
834 context.set_translation(camera->get_translation());
836 for(GameObjects::iterator i = gameobjects.begin();
837 i != gameobjects.end(); ++i) {
838 GameObject* object = *i;
839 if(!object->is_valid())
842 if (draw_solids_only)
844 TileMap* tm = dynamic_cast<TileMap*>(object);
845 if (tm && !tm->is_solid())
849 object->draw(context);
853 Color col(0.2f, 0.2f, 0.2f, 0.7f);
854 for(MovingObjects::iterator i = moving_objects.begin();
855 i != moving_objects.end(); ++i) {
856 MovingObject* object = *i;
857 const Rect& rect = object->get_bbox();
859 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
863 context.pop_transform();
866 /*-------------------------------------------------------------------------
867 * Collision Detection
868 *-------------------------------------------------------------------------*/
870 static const float SHIFT_DELTA = 7.0f;
872 /** r1 is supposed to be moving, r2 a solid object */
873 void check_collisions(collision::Constraints* constraints,
874 const Vector& movement, const Rect& r1, const Rect& r2,
875 GameObject* object = NULL, MovingObject* other = NULL)
877 if(!collision::intersects(r1, r2))
880 // calculate intersection
881 float itop = r1.get_bottom() - r2.get_top();
882 float ibottom = r2.get_bottom() - r1.get_top();
883 float ileft = r1.get_right() - r2.get_left();
884 float iright = r2.get_right() - r1.get_left();
886 if(fabsf(movement.y) > fabsf(movement.x)) {
887 if(ileft < SHIFT_DELTA) {
888 constraints->right = std::min(constraints->right, r2.get_left());
890 } else if(iright < SHIFT_DELTA) {
891 constraints->left = std::max(constraints->left, r2.get_right());
895 // shiftout bottom/top
896 if(itop < SHIFT_DELTA) {
897 constraints->bottom = std::min(constraints->bottom, r2.get_top());
899 } else if(ibottom < SHIFT_DELTA) {
900 constraints->top = std::max(constraints->top, r2.get_bottom());
907 HitResponse response = other->collision(*object, dummy);
908 if(response == PASSTHROUGH)
910 if(other->get_movement() != Vector(0, 0)) {
911 // TODO what todo when we collide with 2 moving objects?!?
912 constraints->ground_movement = other->get_movement();
916 float vert_penetration = std::min(itop, ibottom);
917 float horiz_penetration = std::min(ileft, iright);
918 if(vert_penetration < horiz_penetration) {
920 constraints->bottom = std::min(constraints->bottom, r2.get_top());
921 constraints->hit.bottom = true;
923 constraints->top = std::max(constraints->top, r2.get_bottom());
924 constraints->hit.top = true;
928 constraints->right = std::min(constraints->right, r2.get_left());
929 constraints->hit.right = true;
931 constraints->left = std::max(constraints->left, r2.get_right());
932 constraints->hit.left = true;
937 static const float DELTA = .001f;
940 Sector::collision_tilemap(collision::Constraints* constraints,
941 const Vector& movement, const Rect& dest) const
943 // calculate rectangle where the object will move
944 float x1 = dest.get_left();
945 float x2 = dest.get_right();
946 float y1 = dest.get_top();
947 float y2 = dest.get_bottom();
949 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
950 TileMap* solids = *i;
952 // test with all tiles in this rectangle
953 int starttilex = int(x1 - solids->get_x_offset()) / 32;
954 int starttiley = int(y1 - solids->get_y_offset()) / 32;
955 int max_x = int(x2 - solids->get_x_offset());
956 int max_y = int(y2+1 - solids->get_y_offset());
958 for(int x = starttilex; x*32 < max_x; ++x) {
959 for(int y = starttiley; y*32 < max_y; ++y) {
960 const Tile* tile = solids->get_tile(x, y);
963 // skip non-solid tiles
964 if((tile->getAttributes() & Tile::SOLID) == 0)
966 // only handle unisolid when the player is falling down and when he was
967 // above the tile before
968 if(tile->getAttributes() & Tile::UNISOLID) {
969 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
973 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
975 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
976 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
977 triangle = AATriangle(p1, p2, tile->getData());
979 collision::rectangle_aatriangle(constraints, dest, triangle);
980 } else { // normal rectangular tile
981 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());
982 check_collisions(constraints, movement, dest, rect);
990 Sector::collision_tile_attributes(const Rect& dest) const
992 float x1 = dest.p1.x;
993 float y1 = dest.p1.y;
994 float x2 = dest.p2.x;
995 float y2 = dest.p2.y;
998 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
999 TileMap* solids = *i;
1001 // test with all tiles in this rectangle
1002 int starttilex = int(x1 - solids->get_x_offset()) / 32;
1003 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1004 int max_x = int(x2 - solids->get_x_offset());
1005 int max_y = int(y2+1 - solids->get_y_offset());
1007 for(int x = starttilex; x*32 < max_x; ++x) {
1008 for(int y = starttiley; y*32 < max_y; ++y) {
1009 const Tile* tile = solids->get_tile(x, y);
1012 result |= tile->getAttributes();
1020 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1021 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1024 float itop = r1.get_bottom() - r2.get_top();
1025 float ibottom = r2.get_bottom() - r1.get_top();
1026 float ileft = r1.get_right() - r2.get_left();
1027 float iright = r2.get_right() - r1.get_left();
1029 float vert_penetration = std::min(itop, ibottom);
1030 float horiz_penetration = std::min(ileft, iright);
1031 if(vert_penetration < horiz_penetration) {
1032 if(itop < ibottom) {
1034 normal.y = vert_penetration;
1037 normal.y = -vert_penetration;
1040 if(ileft < iright) {
1042 normal.x = horiz_penetration;
1045 normal.x = -horiz_penetration;
1051 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1053 using namespace collision;
1055 const Rect& r1 = object1->dest;
1056 const Rect& r2 = object2->dest;
1059 if(intersects(object1->dest, object2->dest)) {
1061 get_hit_normal(r1, r2, hit, normal);
1063 HitResponse response1 = object1->collision(*object2, hit);
1064 std::swap(hit.left, hit.right);
1065 std::swap(hit.top, hit.bottom);
1066 HitResponse response2 = object2->collision(*object1, hit);
1067 assert( response1 != SOLID && response1 != PASSTHROUGH );
1068 assert( response2 != SOLID && response2 != PASSTHROUGH );
1069 if(response1 == CONTINUE && response2 == CONTINUE) {
1070 normal *= (0.5 + DELTA);
1071 object1->dest.move(-normal);
1072 object2->dest.move(normal);
1073 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1074 normal *= (1 + DELTA);
1075 object1->dest.move(-normal);
1076 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1077 normal *= (1 + DELTA);
1078 object2->dest.move(normal);
1084 Sector::collision_static(collision::Constraints* constraints,
1085 const Vector& movement, const Rect& dest,
1088 collision_tilemap(constraints, movement, dest);
1090 // collision with other (static) objects
1091 for(MovingObjects::iterator i = moving_objects.begin();
1092 i != moving_objects.end(); ++i) {
1093 MovingObject* moving_object = *i;
1094 if(moving_object->get_group() != COLGROUP_STATIC
1095 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1097 if(!moving_object->is_valid())
1100 if(moving_object != &object)
1101 check_collisions(constraints, movement, dest, moving_object->bbox,
1102 &object, moving_object);
1107 Sector::collision_static_constrains(MovingObject& object)
1109 using namespace collision;
1110 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1112 Constraints constraints;
1113 Vector movement = object.get_movement();
1114 Rect& dest = object.dest;
1115 float owidth = object.get_bbox().get_width();
1116 float oheight = object.get_bbox().get_height();
1118 for(int i = 0; i < 2; ++i) {
1119 collision_static(&constraints, Vector(0, movement.y), dest, object);
1120 if(!constraints.has_constraints())
1123 // apply calculated horizontal constraints
1124 if(constraints.bottom < infinity) {
1125 float height = constraints.bottom - constraints.top;
1126 if(height < oheight) {
1127 // we're crushed, but ignore this for now, we'll get this again
1128 // later if we're really crushed or things will solve itself when
1129 // looking at the vertical constraints
1131 dest.p2.y = constraints.bottom - DELTA;
1132 dest.p1.y = dest.p2.y - oheight;
1133 } else if(constraints.top > -infinity) {
1134 dest.p1.y = constraints.top + DELTA;
1135 dest.p2.y = dest.p1.y + oheight;
1138 if(constraints.has_constraints()) {
1139 if(constraints.hit.bottom) {
1140 dest.move(constraints.ground_movement);
1142 if(constraints.hit.top || constraints.hit.bottom) {
1143 constraints.hit.left = false;
1144 constraints.hit.right = false;
1145 object.collision_solid(constraints.hit);
1149 constraints = Constraints();
1150 for(int i = 0; i < 2; ++i) {
1151 collision_static(&constraints, movement, dest, object);
1152 if(!constraints.has_constraints())
1155 // apply calculated vertical constraints
1156 if(constraints.right < infinity) {
1157 float width = constraints.right - constraints.left;
1158 if(width + SHIFT_DELTA < owidth) {
1159 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1160 constraints.left, constraints.right);
1165 object.collision_solid(h);
1167 dest.p2.x = constraints.right - DELTA;
1168 dest.p1.x = dest.p2.x - owidth;
1170 } else if(constraints.left > -infinity) {
1171 dest.p1.x = constraints.left + DELTA;
1172 dest.p2.x = dest.p1.x + owidth;
1176 if(constraints.has_constraints()) {
1177 if( constraints.hit.left || constraints.hit.right
1178 || constraints.hit.top || constraints.hit.bottom
1179 || constraints.hit.crush )
1180 object.collision_solid(constraints.hit);
1183 // an extra pass to make sure we're not crushed horizontally
1184 constraints = Constraints();
1185 collision_static(&constraints, movement, dest, object);
1186 if(constraints.bottom < infinity) {
1187 float height = constraints.bottom - constraints.top;
1188 if(height + SHIFT_DELTA < oheight) {
1189 printf("Object %p crushed vertically...\n", &object);
1194 object.collision_solid(h);
1200 const float MAX_SPEED = 16.0f;
1204 Sector::handle_collisions()
1206 using namespace collision;
1208 // calculate destination positions of the objects
1209 for(MovingObjects::iterator i = moving_objects.begin();
1210 i != moving_objects.end(); ++i) {
1211 MovingObject* moving_object = *i;
1212 Vector mov = moving_object->get_movement();
1214 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1215 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1216 moving_object->movement = mov.unit() * MAX_SPEED;
1217 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1220 moving_object->dest = moving_object->get_bbox();
1221 moving_object->dest.move(moving_object->get_movement());
1224 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1225 for(MovingObjects::iterator i = moving_objects.begin();
1226 i != moving_objects.end(); ++i) {
1227 MovingObject* moving_object = *i;
1228 if((moving_object->get_group() != COLGROUP_MOVING
1229 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1230 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1231 || !moving_object->is_valid())
1234 collision_static_constrains(*moving_object);
1238 // part2: COLGROUP_MOVING vs tile attributes
1239 for(MovingObjects::iterator i = moving_objects.begin();
1240 i != moving_objects.end(); ++i) {
1241 MovingObject* moving_object = *i;
1242 if((moving_object->get_group() != COLGROUP_MOVING
1243 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1244 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1245 || !moving_object->is_valid())
1248 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1249 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1250 moving_object->collision_tile(tile_attributes);
1254 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1255 for(MovingObjects::iterator i = moving_objects.begin();
1256 i != moving_objects.end(); ++i) {
1257 MovingObject* moving_object = *i;
1258 if((moving_object->get_group() != COLGROUP_MOVING
1259 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1260 || !moving_object->is_valid())
1263 for(MovingObjects::iterator i2 = moving_objects.begin();
1264 i2 != moving_objects.end(); ++i2) {
1265 MovingObject* moving_object_2 = *i2;
1266 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1267 || !moving_object_2->is_valid())
1270 if(intersects(moving_object->dest, moving_object_2->dest)) {
1273 get_hit_normal(moving_object->dest, moving_object_2->dest,
1275 moving_object->collision(*moving_object_2, hit);
1276 moving_object_2->collision(*moving_object, hit);
1281 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1282 for(MovingObjects::iterator i = moving_objects.begin();
1283 i != moving_objects.end(); ++i) {
1284 MovingObject* moving_object = *i;
1286 if((moving_object->get_group() != COLGROUP_MOVING
1287 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1288 || !moving_object->is_valid())
1291 for(MovingObjects::iterator i2 = i+1;
1292 i2 != moving_objects.end(); ++i2) {
1293 MovingObject* moving_object_2 = *i2;
1294 if((moving_object_2->get_group() != COLGROUP_MOVING
1295 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1296 || !moving_object_2->is_valid())
1299 collision_object(moving_object, moving_object_2);
1303 // apply object movement
1304 for(MovingObjects::iterator i = moving_objects.begin();
1305 i != moving_objects.end(); ++i) {
1306 MovingObject* moving_object = *i;
1308 moving_object->bbox = moving_object->dest;
1309 moving_object->movement = Vector(0, 0);
1314 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1316 using namespace collision;
1318 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1319 TileMap* solids = *i;
1321 // test with all tiles in this rectangle
1322 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1323 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1324 int max_x = int(rect.p2.x - solids->get_x_offset());
1325 int max_y = int(rect.p2.y - solids->get_y_offset());
1327 for(int x = starttilex; x*32 <= max_x; ++x) {
1328 for(int y = starttiley; y*32 <= max_y; ++y) {
1329 const Tile* tile = solids->get_tile(x, y);
1331 if(tile->getAttributes() & Tile::SLOPE) {
1332 AATriangle triangle;
1333 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1334 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1335 triangle = AATriangle(p1, p2, tile->getData());
1336 Constraints constraints;
1337 return collision::rectangle_aatriangle(&constraints, rect, triangle);
1339 if((tile->getAttributes() & Tile::SOLID) && !ignoreUnisolid) return false;
1340 if((tile->getAttributes() & Tile::SOLID) && !(tile->getAttributes() & Tile::UNISOLID)) return false;
1349 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1351 using namespace collision;
1353 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1355 for(MovingObjects::const_iterator i = moving_objects.begin();
1356 i != moving_objects.end(); ++i) {
1357 const MovingObject* moving_object = *i;
1358 if (moving_object == ignore_object) continue;
1359 if (!moving_object->is_valid()) continue;
1360 if (moving_object->get_group() == COLGROUP_STATIC) {
1361 if(intersects(rect, moving_object->get_bbox())) return false;
1369 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1371 using namespace collision;
1373 if (!is_free_of_tiles(rect)) return false;
1375 for(MovingObjects::const_iterator i = moving_objects.begin();
1376 i != moving_objects.end(); ++i) {
1377 const MovingObject* moving_object = *i;
1378 if (moving_object == ignore_object) continue;
1379 if (!moving_object->is_valid()) continue;
1380 if ((moving_object->get_group() == COLGROUP_MOVING)
1381 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1382 || (moving_object->get_group() == COLGROUP_STATIC)) {
1383 if(intersects(rect, moving_object->get_bbox())) return false;
1391 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1393 // TODO remove this function and move these checks elsewhere...
1395 Bullet* new_bullet = 0;
1396 if((player_status->bonus == FIRE_BONUS &&
1397 (int)bullets.size() >= player_status->max_fire_bullets) ||
1398 (player_status->bonus == ICE_BONUS &&
1399 (int)bullets.size() >= player_status->max_ice_bullets))
1401 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1402 add_object(new_bullet);
1404 sound_manager->play("sounds/shoot.wav");
1410 Sector::add_smoke_cloud(const Vector& pos)
1412 add_object(new SmokeCloud(pos));
1417 Sector::play_music(MusicType type)
1419 currentmusic = type;
1420 switch(currentmusic) {
1422 sound_manager->play_music(music);
1425 sound_manager->play_music("music/salcon.ogg");
1427 case HERRING_WARNING_MUSIC:
1428 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1431 sound_manager->play_music("");
1437 Sector::get_music_type()
1439 return currentmusic;
1443 Sector::get_total_badguys()
1445 int total_badguys = 0;
1446 for(GameObjects::iterator i = gameobjects.begin();
1447 i != gameobjects.end(); ++i) {
1448 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1449 if (badguy && badguy->countMe)
1453 return total_badguys;
1457 Sector::inside(const Rect& rect) const
1459 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1460 TileMap* solids = *i;
1461 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1462 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1463 if (horizontally && vertically) return true;
1469 Sector::get_width() const
1472 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1473 TileMap* solids = *i;
1474 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) width = (solids->get_width() * 32 + solids->get_x_offset());
1480 Sector::get_height() const
1483 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1484 TileMap* solids = *i;
1485 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) height = (solids->get_height() * 32 + solids->get_y_offset());
1491 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1493 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1494 TileMap* solids = *i;
1495 solids->change_all(old_tile_id, new_tile_id);
1501 Sector::set_ambient_light(float red, float green, float blue)
1503 ambient_light.red = red;
1504 ambient_light.green = green;
1505 ambient_light.blue = blue;
1509 Sector::get_ambient_red()
1511 return ambient_light.red;
1515 Sector::get_ambient_green()
1517 return ambient_light.green;
1521 Sector::get_ambient_blue()
1523 return ambient_light.blue;