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"
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 (!PHYSFS_exists(backgroundimage.c_str())) {
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(level->get_tileset());
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 uint32_t id = tilemap->get_tile_id(x, y);
325 tilemap->change(x, y, 1311);
329 if (height < 19) tilemap->resize(width, 19);
333 if(reader.get_vector("background-tm", tiles)) {
334 TileMap* tilemap = new TileMap(level->get_tileset());
335 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
336 if (height < 19) tilemap->resize(width, 19);
340 if(reader.get_vector("foreground-tm", tiles)) {
341 TileMap* tilemap = new TileMap(level->get_tileset());
342 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
344 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
345 if (height < 19) tilemap->resize(width, 19, 2035);
350 // read reset-points (now spawn-points)
351 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
353 lisp::ListIterator iter(resetpoints);
355 if(iter.item() == "point") {
357 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
359 SpawnPoint* sp = new SpawnPoint;
362 spawnpoints.push_back(sp);
365 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
371 const lisp::Lisp* objects = reader.get_lisp("objects");
373 lisp::ListIterator iter(objects);
375 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
379 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
385 Camera* camera = new Camera(this, "Camera");
388 update_game_objects();
390 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
393 update_game_objects();
397 Sector::fix_old_tiles()
399 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
400 TileMap* solids = *i;
401 for(size_t x=0; x < solids->get_width(); ++x) {
402 for(size_t y=0; y < solids->get_height(); ++y) {
403 uint32_t id = solids->get_tile_id(x, y);
404 const Tile *tile = solids->get_tile(x, y);
405 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
408 add_object(new InvisibleBlock(pos));
409 solids->change(x, y, 0);
410 } else if(tile->getAttributes() & Tile::COIN) {
411 add_object(new Coin(pos));
412 solids->change(x, y, 0);
413 } else if(tile->getAttributes() & Tile::FULLBOX) {
414 add_object(new BonusBlock(pos, tile->getData()));
415 solids->change(x, y, 0);
416 } else if(tile->getAttributes() & Tile::BRICK) {
417 add_object(new Brick(pos, tile->getData()));
418 solids->change(x, y, 0);
419 } else if(tile->getAttributes() & Tile::GOAL) {
420 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
421 add_object(new SequenceTrigger(pos, sequence));
422 solids->change(x, y, 0);
428 // add lights for special tiles
429 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
430 TileMap* tm = dynamic_cast<TileMap*>(*i);
432 for(size_t x=0; x < tm->get_width(); ++x) {
433 for(size_t y=0; y < tm->get_height(); ++y) {
434 uint32_t id = tm->get_tile_id(x, y);
435 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
436 Vector center(pos.x + 16, pos.y + 16);
440 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
441 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
444 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
445 // space lights a bit
446 if (((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
447 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y))
448 || ((x % 3 == 0) && (y % 3 == 0))) {
449 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
450 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
462 Sector::write(lisp::Writer& writer)
464 writer.write_string("name", name);
465 writer.write_float("gravity", gravity);
466 writer.write_string("music", music);
469 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
471 SpawnPoint* spawn = *i;
472 writer.start_list("spawn-points");
473 writer.write_string("name", spawn->name);
474 writer.write_float("x", spawn->pos.x);
475 writer.write_float("y", spawn->pos.y);
476 writer.end_list("spawn-points");
480 for(GameObjects::iterator i = gameobjects.begin();
481 i != gameobjects.end(); ++i) {
482 Serializable* serializable = dynamic_cast<Serializable*> (*i);
484 serializable->write(writer);
489 Sector::run_script(std::istream& in, const std::string& sourcename)
491 using namespace Scripting;
493 // garbage collect thread list
494 for(ScriptList::iterator i = scripts.begin();
495 i != scripts.end(); ) {
496 HSQOBJECT& object = *i;
497 HSQUIRRELVM vm = object_to_vm(object);
499 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
500 sq_release(global_vm, &object);
501 i = scripts.erase(i);
508 HSQOBJECT object = create_thread(global_vm);
509 scripts.push_back(object);
511 HSQUIRRELVM vm = object_to_vm(object);
513 // set sector_table as roottable for the thread
514 sq_pushobject(vm, sector_table);
517 compile_and_run(vm, in, sourcename);
523 Sector::add_object(GameObject* object)
525 // make sure the object isn't already in the list
527 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
530 assert("object already added to sector" == 0);
533 for(GameObjects::iterator i = gameobjects_new.begin();
534 i != gameobjects_new.end(); ++i) {
536 assert("object already added to sector" == 0);
542 gameobjects_new.push_back(object);
546 Sector::activate(const std::string& spawnpoint)
549 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
551 if((*i)->name == spawnpoint) {
557 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
558 if(spawnpoint != "main") {
561 activate(Vector(0, 0));
569 Sector::activate(const Vector& player_pos)
571 if(_current != this) {
573 _current->deactivate();
576 // register sectortable as sector in scripting
577 HSQUIRRELVM vm = Scripting::global_vm;
578 sq_pushroottable(vm);
579 sq_pushstring(vm, "sector", -1);
580 sq_pushobject(vm, sector_table);
581 if(SQ_FAILED(sq_createslot(vm, -3)))
582 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
585 for(GameObjects::iterator i = gameobjects.begin();
586 i != gameobjects.end(); ++i) {
587 GameObject* object = *i;
594 // spawn smalltux below spawnpoint
595 if (!player->is_big()) {
596 player->move(player_pos + Vector(0,32));
598 player->move(player_pos);
601 // spawning tux in the ground would kill him
602 if(!is_free_of_tiles(player->get_bbox())) {
603 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
604 Vector npos = player->get_bbox().p1;
609 camera->reset(player->get_pos());
610 update_game_objects();
613 if(init_script != "") {
614 std::istringstream in(init_script);
615 run_script(in, std::string("Sector(") + name + ") - init");
625 // remove sector entry from global vm
626 HSQUIRRELVM vm = Scripting::global_vm;
627 sq_pushroottable(vm);
628 sq_pushstring(vm, "sector", -1);
629 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
630 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
633 for(GameObjects::iterator i = gameobjects.begin();
634 i != gameobjects.end(); ++i) {
635 GameObject* object = *i;
637 try_unexpose(object);
645 Sector::get_active_region()
648 camera->get_translation() - Vector(1600, 1200),
649 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
653 Sector::update(float elapsed_time)
655 player->check_bounds(camera);
658 for(GameObjects::iterator i = gameobjects.begin();
659 i != gameobjects.end(); ++i) {
660 GameObject* object = *i;
661 if(!object->is_valid())
664 object->update(elapsed_time);
667 /* Handle all possible collisions. */
669 update_game_objects();
673 Sector::update_game_objects()
675 /** cleanup marked objects */
676 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
677 i != gameobjects.end(); /* nothing */) {
678 GameObject* object = *i;
680 if(object->is_valid()) {
685 before_object_remove(object);
688 i = gameobjects.erase(i);
691 /* add newly created objects */
692 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
693 i != gameobjects_new.end(); ++i)
695 GameObject* object = *i;
697 before_object_add(object);
699 gameobjects.push_back(object);
701 gameobjects_new.clear();
703 /* update solid_tilemaps list */
704 //FIXME: this could be more efficient
705 solid_tilemaps.clear();
706 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
707 i != gameobjects.end(); ++i)
709 TileMap* tm = dynamic_cast<TileMap*>(*i);
711 if (tm->is_solid()) solid_tilemaps.push_back(tm);
717 Sector::before_object_add(GameObject* object)
719 Bullet* bullet = dynamic_cast<Bullet*> (object);
721 bullets.push_back(bullet);
724 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
725 if(movingobject != NULL) {
726 moving_objects.push_back(movingobject);
729 Portable* portable = dynamic_cast<Portable*> (object);
730 if(portable != NULL) {
731 portables.push_back(portable);
734 TileMap* tilemap = dynamic_cast<TileMap*> (object);
735 if(tilemap != NULL && tilemap->is_solid()) {
736 solid_tilemaps.push_back(tilemap);
739 Camera* camera = dynamic_cast<Camera*> (object);
741 if(this->camera != 0) {
742 log_warning << "Multiple cameras added. Ignoring" << std::endl;
745 this->camera = camera;
748 Player* player = dynamic_cast<Player*> (object);
750 if(this->player != 0) {
751 log_warning << "Multiple players added. Ignoring" << std::endl;
754 this->player = player;
757 UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
760 physic_object->physic.set_gravity(gravity);
764 if(_current == this) {
772 Sector::try_expose(GameObject* object)
774 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
775 if(interface != NULL) {
776 HSQUIRRELVM vm = Scripting::global_vm;
777 sq_pushobject(vm, sector_table);
778 interface->expose(vm, -1);
784 Sector::try_expose_me()
786 HSQUIRRELVM vm = Scripting::global_vm;
787 sq_pushobject(vm, sector_table);
788 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
789 expose_object(vm, -1, interface, "settings", false);
794 Sector::before_object_remove(GameObject* object)
796 Portable* portable = dynamic_cast<Portable*> (object);
797 if(portable != NULL) {
798 portables.erase(std::find(portables.begin(), portables.end(), portable));
800 Bullet* bullet = dynamic_cast<Bullet*> (object);
802 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
804 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
805 if(moving_object != NULL) {
806 moving_objects.erase(
807 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
811 try_unexpose(object);
815 Sector::try_unexpose(GameObject* object)
817 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
818 if(interface != NULL) {
819 HSQUIRRELVM vm = Scripting::global_vm;
820 SQInteger oldtop = sq_gettop(vm);
821 sq_pushobject(vm, sector_table);
823 interface->unexpose(vm, -1);
824 } catch(std::exception& e) {
825 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
827 sq_settop(vm, oldtop);
832 Sector::try_unexpose_me()
834 HSQUIRRELVM vm = Scripting::global_vm;
835 SQInteger oldtop = sq_gettop(vm);
836 sq_pushobject(vm, sector_table);
838 Scripting::unexpose_object(vm, -1, "settings");
839 } catch(std::exception& e) {
840 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
842 sq_settop(vm, oldtop);
845 Sector::draw(DrawingContext& context)
847 context.set_ambient_color( ambient_light );
848 context.push_transform();
849 context.set_translation(camera->get_translation());
851 for(GameObjects::iterator i = gameobjects.begin();
852 i != gameobjects.end(); ++i) {
853 GameObject* object = *i;
854 if(!object->is_valid())
857 if (draw_solids_only)
859 TileMap* tm = dynamic_cast<TileMap*>(object);
860 if (tm && !tm->is_solid())
864 object->draw(context);
868 Color col(0.2f, 0.2f, 0.2f, 0.7f);
869 for(MovingObjects::iterator i = moving_objects.begin();
870 i != moving_objects.end(); ++i) {
871 MovingObject* object = *i;
872 const Rect& rect = object->get_bbox();
874 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
878 context.pop_transform();
881 /*-------------------------------------------------------------------------
882 * Collision Detection
883 *-------------------------------------------------------------------------*/
885 static const float SHIFT_DELTA = 7.0f;
887 /** r1 is supposed to be moving, r2 a solid object */
888 void check_collisions(collision::Constraints* constraints,
889 const Vector& movement, const Rect& r1, const Rect& r2,
890 GameObject* object = NULL, MovingObject* other = NULL)
892 if(!collision::intersects(r1, r2))
895 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
897 if(other != NULL && !other->collides(*object, dummy))
899 if(moving_object != NULL && !moving_object->collides(*other, dummy))
902 // calculate intersection
903 float itop = r1.get_bottom() - r2.get_top();
904 float ibottom = r2.get_bottom() - r1.get_top();
905 float ileft = r1.get_right() - r2.get_left();
906 float iright = r2.get_right() - r1.get_left();
908 if(fabsf(movement.y) > fabsf(movement.x)) {
909 if(ileft < SHIFT_DELTA) {
910 constraints->right = std::min(constraints->right, r2.get_left());
912 } else if(iright < SHIFT_DELTA) {
913 constraints->left = std::max(constraints->left, r2.get_right());
917 // shiftout bottom/top
918 if(itop < SHIFT_DELTA) {
919 constraints->bottom = std::min(constraints->bottom, r2.get_top());
921 } else if(ibottom < SHIFT_DELTA) {
922 constraints->top = std::max(constraints->top, r2.get_bottom());
928 HitResponse response = other->collision(*object, dummy);
929 if(response == PASSTHROUGH)
932 if(other->get_movement() != Vector(0, 0)) {
933 // TODO what todo when we collide with 2 moving objects?!?
934 constraints->ground_movement = other->get_movement();
938 float vert_penetration = std::min(itop, ibottom);
939 float horiz_penetration = std::min(ileft, iright);
940 if(vert_penetration < horiz_penetration) {
942 constraints->bottom = std::min(constraints->bottom, r2.get_top());
943 constraints->hit.bottom = true;
945 constraints->top = std::max(constraints->top, r2.get_bottom());
946 constraints->hit.top = true;
950 constraints->right = std::min(constraints->right, r2.get_left());
951 constraints->hit.right = true;
953 constraints->left = std::max(constraints->left, r2.get_right());
954 constraints->hit.left = true;
959 static const float DELTA = .001f;
962 Sector::collision_tilemap(collision::Constraints* constraints,
963 const Vector& movement, const Rect& dest) const
965 // calculate rectangle where the object will move
966 float x1 = dest.get_left();
967 float x2 = dest.get_right();
968 float y1 = dest.get_top();
969 float y2 = dest.get_bottom();
971 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
972 TileMap* solids = *i;
974 // test with all tiles in this rectangle
975 int starttilex = int(x1 - solids->get_x_offset()) / 32;
976 int starttiley = int(y1 - solids->get_y_offset()) / 32;
977 int max_x = int(x2 - solids->get_x_offset());
978 int max_y = int(y2+1 - solids->get_y_offset());
980 for(int x = starttilex; x*32 < max_x; ++x) {
981 for(int y = starttiley; y*32 < max_y; ++y) {
982 const Tile* tile = solids->get_tile(x, y);
985 // skip non-solid tiles
986 if((tile->getAttributes() & Tile::SOLID) == 0)
988 // only handle unisolid when the player is falling down and when he was
989 // above the tile before
990 if(tile->getAttributes() & Tile::UNISOLID) {
991 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
995 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
997 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
998 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
999 triangle = AATriangle(p1, p2, tile->getData());
1001 collision::rectangle_aatriangle(constraints, dest, triangle);
1002 } else { // normal rectangular tile
1003 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());
1004 check_collisions(constraints, movement, dest, rect);
1012 Sector::collision_tile_attributes(const Rect& dest) const
1014 float x1 = dest.p1.x;
1015 float y1 = dest.p1.y;
1016 float x2 = dest.p2.x;
1017 float y2 = dest.p2.y;
1019 uint32_t result = 0;
1020 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1021 TileMap* solids = *i;
1023 // test with all tiles in this rectangle
1024 int starttilex = int(x1 - solids->get_x_offset()) / 32;
1025 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1026 int max_x = int(x2 - solids->get_x_offset());
1027 int max_y = int(y2+1 - solids->get_y_offset());
1029 for(int x = starttilex; x*32 < max_x; ++x) {
1030 for(int y = starttiley; y*32 < max_y; ++y) {
1031 const Tile* tile = solids->get_tile(x, y);
1034 result |= tile->getAttributes();
1042 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1043 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1046 float itop = r1.get_bottom() - r2.get_top();
1047 float ibottom = r2.get_bottom() - r1.get_top();
1048 float ileft = r1.get_right() - r2.get_left();
1049 float iright = r2.get_right() - r1.get_left();
1051 float vert_penetration = std::min(itop, ibottom);
1052 float horiz_penetration = std::min(ileft, iright);
1053 if(vert_penetration < horiz_penetration) {
1054 if(itop < ibottom) {
1056 normal.y = vert_penetration;
1059 normal.y = -vert_penetration;
1062 if(ileft < iright) {
1064 normal.x = horiz_penetration;
1067 normal.x = -horiz_penetration;
1073 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1075 using namespace collision;
1077 const Rect& r1 = object1->dest;
1078 const Rect& r2 = object2->dest;
1081 if(intersects(object1->dest, object2->dest)) {
1083 get_hit_normal(r1, r2, hit, normal);
1085 if(!object1->collides(*object2, hit))
1087 std::swap(hit.left, hit.right);
1088 std::swap(hit.top, hit.bottom);
1089 if(!object2->collides(*object1, hit))
1091 std::swap(hit.left, hit.right);
1092 std::swap(hit.top, hit.bottom);
1094 HitResponse response1 = object1->collision(*object2, hit);
1095 std::swap(hit.left, hit.right);
1096 std::swap(hit.top, hit.bottom);
1097 HitResponse response2 = object2->collision(*object1, hit);
1098 if(response1 == CONTINUE && response2 == CONTINUE) {
1099 normal *= (0.5 + DELTA);
1100 object1->dest.move(-normal);
1101 object2->dest.move(normal);
1102 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1103 normal *= (1 + DELTA);
1104 object1->dest.move(-normal);
1105 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1106 normal *= (1 + DELTA);
1107 object2->dest.move(normal);
1113 Sector::collision_static(collision::Constraints* constraints,
1114 const Vector& movement, const Rect& dest,
1117 collision_tilemap(constraints, movement, dest);
1119 // collision with other (static) objects
1120 for(MovingObjects::iterator i = moving_objects.begin();
1121 i != moving_objects.end(); ++i) {
1122 MovingObject* moving_object = *i;
1123 if(moving_object->get_group() != COLGROUP_STATIC
1124 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1126 if(!moving_object->is_valid())
1129 if(moving_object != &object)
1130 check_collisions(constraints, movement, dest, moving_object->bbox,
1131 &object, moving_object);
1136 Sector::collision_static_constrains(MovingObject& object)
1138 using namespace collision;
1139 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1141 Constraints constraints;
1142 Vector movement = object.get_movement();
1143 Rect& dest = object.dest;
1144 float owidth = object.get_bbox().get_width();
1145 float oheight = object.get_bbox().get_height();
1147 for(int i = 0; i < 2; ++i) {
1148 collision_static(&constraints, Vector(0, movement.y), dest, object);
1149 if(!constraints.has_constraints())
1152 // apply calculated horizontal constraints
1153 if(constraints.bottom < infinity) {
1154 float height = constraints.bottom - constraints.top;
1155 if(height < oheight) {
1156 // we're crushed, but ignore this for now, we'll get this again
1157 // later if we're really crushed or things will solve itself when
1158 // looking at the vertical constraints
1160 dest.p2.y = constraints.bottom - DELTA;
1161 dest.p1.y = dest.p2.y - oheight;
1162 } else if(constraints.top > -infinity) {
1163 dest.p1.y = constraints.top + DELTA;
1164 dest.p2.y = dest.p1.y + oheight;
1167 if(constraints.has_constraints()) {
1168 if(constraints.hit.bottom) {
1169 dest.move(constraints.ground_movement);
1171 if(constraints.hit.top || constraints.hit.bottom) {
1172 constraints.hit.left = false;
1173 constraints.hit.right = false;
1174 object.collision_solid(constraints.hit);
1178 constraints = Constraints();
1179 for(int i = 0; i < 2; ++i) {
1180 collision_static(&constraints, movement, dest, object);
1181 if(!constraints.has_constraints())
1184 // apply calculated vertical constraints
1185 if(constraints.right < infinity) {
1186 float width = constraints.right - constraints.left;
1187 if(width + SHIFT_DELTA < owidth) {
1189 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1190 constraints.left, constraints.right);
1196 object.collision_solid(h);
1198 dest.p2.x = constraints.right - DELTA;
1199 dest.p1.x = dest.p2.x - owidth;
1201 } else if(constraints.left > -infinity) {
1202 dest.p1.x = constraints.left + DELTA;
1203 dest.p2.x = dest.p1.x + owidth;
1207 if(constraints.has_constraints()) {
1208 if( constraints.hit.left || constraints.hit.right
1209 || constraints.hit.top || constraints.hit.bottom
1210 || constraints.hit.crush )
1211 object.collision_solid(constraints.hit);
1214 // an extra pass to make sure we're not crushed horizontally
1215 constraints = Constraints();
1216 collision_static(&constraints, movement, dest, object);
1217 if(constraints.bottom < infinity) {
1218 float height = constraints.bottom - constraints.top;
1219 if(height + SHIFT_DELTA < oheight) {
1221 printf("Object %p crushed vertically...\n", &object);
1227 object.collision_solid(h);
1233 const float MAX_SPEED = 16.0f;
1237 Sector::handle_collisions()
1239 using namespace collision;
1241 // calculate destination positions of the objects
1242 for(MovingObjects::iterator i = moving_objects.begin();
1243 i != moving_objects.end(); ++i) {
1244 MovingObject* moving_object = *i;
1245 Vector mov = moving_object->get_movement();
1247 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1248 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1249 moving_object->movement = mov.unit() * MAX_SPEED;
1250 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1253 moving_object->dest = moving_object->get_bbox();
1254 moving_object->dest.move(moving_object->get_movement());
1257 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1258 for(MovingObjects::iterator i = moving_objects.begin();
1259 i != moving_objects.end(); ++i) {
1260 MovingObject* moving_object = *i;
1261 if((moving_object->get_group() != COLGROUP_MOVING
1262 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1263 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1264 || !moving_object->is_valid())
1267 collision_static_constrains(*moving_object);
1271 // part2: COLGROUP_MOVING vs tile attributes
1272 for(MovingObjects::iterator i = moving_objects.begin();
1273 i != moving_objects.end(); ++i) {
1274 MovingObject* moving_object = *i;
1275 if((moving_object->get_group() != COLGROUP_MOVING
1276 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1277 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1278 || !moving_object->is_valid())
1281 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1282 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1283 moving_object->collision_tile(tile_attributes);
1287 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1288 for(MovingObjects::iterator i = moving_objects.begin();
1289 i != moving_objects.end(); ++i) {
1290 MovingObject* moving_object = *i;
1291 if((moving_object->get_group() != COLGROUP_MOVING
1292 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1293 || !moving_object->is_valid())
1296 for(MovingObjects::iterator i2 = moving_objects.begin();
1297 i2 != moving_objects.end(); ++i2) {
1298 MovingObject* moving_object_2 = *i2;
1299 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1300 || !moving_object_2->is_valid())
1303 if(intersects(moving_object->dest, moving_object_2->dest)) {
1306 get_hit_normal(moving_object->dest, moving_object_2->dest,
1308 if(!moving_object->collides(*moving_object_2, hit))
1310 if(!moving_object_2->collides(*moving_object, hit))
1313 moving_object->collision(*moving_object_2, hit);
1314 moving_object_2->collision(*moving_object, hit);
1319 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1320 for(MovingObjects::iterator i = moving_objects.begin();
1321 i != moving_objects.end(); ++i) {
1322 MovingObject* moving_object = *i;
1324 if((moving_object->get_group() != COLGROUP_MOVING
1325 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1326 || !moving_object->is_valid())
1329 for(MovingObjects::iterator i2 = i+1;
1330 i2 != moving_objects.end(); ++i2) {
1331 MovingObject* moving_object_2 = *i2;
1332 if((moving_object_2->get_group() != COLGROUP_MOVING
1333 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1334 || !moving_object_2->is_valid())
1337 collision_object(moving_object, moving_object_2);
1341 // apply object movement
1342 for(MovingObjects::iterator i = moving_objects.begin();
1343 i != moving_objects.end(); ++i) {
1344 MovingObject* moving_object = *i;
1346 moving_object->bbox = moving_object->dest;
1347 moving_object->movement = Vector(0, 0);
1352 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1354 using namespace collision;
1356 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1357 TileMap* solids = *i;
1359 // test with all tiles in this rectangle
1360 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1361 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1362 int max_x = int(rect.p2.x - solids->get_x_offset());
1363 int max_y = int(rect.p2.y - solids->get_y_offset());
1365 for(int x = starttilex; x*32 <= max_x; ++x) {
1366 for(int y = starttiley; y*32 <= max_y; ++y) {
1367 const Tile* tile = solids->get_tile(x, y);
1369 if(tile->getAttributes() & Tile::SLOPE) {
1370 AATriangle triangle;
1371 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1372 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1373 triangle = AATriangle(p1, p2, tile->getData());
1374 Constraints constraints;
1375 return collision::rectangle_aatriangle(&constraints, rect, triangle);
1377 if((tile->getAttributes() & Tile::SOLID) && !ignoreUnisolid) return false;
1378 if((tile->getAttributes() & Tile::SOLID) && !(tile->getAttributes() & Tile::UNISOLID)) return false;
1387 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1389 using namespace collision;
1391 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1393 for(MovingObjects::const_iterator i = moving_objects.begin();
1394 i != moving_objects.end(); ++i) {
1395 const MovingObject* moving_object = *i;
1396 if (moving_object == ignore_object) continue;
1397 if (!moving_object->is_valid()) continue;
1398 if (moving_object->get_group() == COLGROUP_STATIC) {
1399 if(intersects(rect, moving_object->get_bbox())) return false;
1407 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1409 using namespace collision;
1411 if (!is_free_of_tiles(rect)) return false;
1413 for(MovingObjects::const_iterator i = moving_objects.begin();
1414 i != moving_objects.end(); ++i) {
1415 const MovingObject* moving_object = *i;
1416 if (moving_object == ignore_object) continue;
1417 if (!moving_object->is_valid()) continue;
1418 if ((moving_object->get_group() == COLGROUP_MOVING)
1419 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1420 || (moving_object->get_group() == COLGROUP_STATIC)) {
1421 if(intersects(rect, moving_object->get_bbox())) return false;
1429 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1431 // TODO remove this function and move these checks elsewhere...
1433 Bullet* new_bullet = 0;
1434 if((player_status->bonus == FIRE_BONUS &&
1435 (int)bullets.size() >= player_status->max_fire_bullets) ||
1436 (player_status->bonus == ICE_BONUS &&
1437 (int)bullets.size() >= player_status->max_ice_bullets))
1439 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1440 add_object(new_bullet);
1442 sound_manager->play("sounds/shoot.wav");
1448 Sector::add_smoke_cloud(const Vector& pos)
1450 add_object(new SmokeCloud(pos));
1455 Sector::play_music(MusicType type)
1457 currentmusic = type;
1458 switch(currentmusic) {
1460 sound_manager->play_music(music);
1463 sound_manager->play_music("music/salcon.ogg");
1465 case HERRING_WARNING_MUSIC:
1466 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1469 sound_manager->play_music("");
1475 Sector::get_music_type()
1477 return currentmusic;
1481 Sector::get_total_badguys()
1483 int total_badguys = 0;
1484 for(GameObjects::iterator i = gameobjects.begin();
1485 i != gameobjects.end(); ++i) {
1486 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1487 if (badguy && badguy->countMe)
1491 return total_badguys;
1495 Sector::inside(const Rect& rect) const
1497 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1498 TileMap* solids = *i;
1499 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1500 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1502 if (horizontally && vertically)
1509 Sector::get_width() const
1512 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1513 i != solid_tilemaps.end(); i++) {
1514 TileMap* solids = *i;
1515 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1516 width = solids->get_width() * 32 + solids->get_x_offset();
1524 Sector::get_height() const
1527 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1528 i != solid_tilemaps.end(); i++) {
1529 TileMap* solids = *i;
1530 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1531 height = solids->get_height() * 32 + solids->get_y_offset();
1539 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1541 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1542 TileMap* solids = *i;
1543 solids->change_all(old_tile_id, new_tile_id);
1549 Sector::set_ambient_light(float red, float green, float blue)
1551 ambient_light.red = red;
1552 ambient_light.green = green;
1553 ambient_light.blue = blue;
1557 Sector::get_ambient_red()
1559 return ambient_light.red;
1563 Sector::get_ambient_green()
1565 return ambient_light.green;
1569 Sector::get_ambient_blue()
1571 return ambient_light.blue;