Changed jump behaviour: Tux will now jump even if the button was pressed (up to)...
[supertux.git] / src / object / player.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
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.
10 //
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.
15 //
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.
19 #include <config.h>
20
21 #include <typeinfo>
22 #include <cmath>
23 #include <iostream>
24 #include <cassert>
25
26 #include "gettext.hpp"
27 #include "sprite/sprite_manager.hpp"
28 #include "audio/sound_manager.hpp"
29 #include "player.hpp"
30 #include "tile.hpp"
31 #include "sprite/sprite.hpp"
32 #include "sector.hpp"
33 #include "resources.hpp"
34 #include "statistics.hpp"
35 #include "game_session.hpp"
36 #include "object/tilemap.hpp"
37 #include "object/camera.hpp"
38 #include "object/particles.hpp"
39 #include "object/portable.hpp"
40 #include "object/bullet.hpp"
41 #include "trigger/trigger_base.hpp"
42 #include "control/joystickkeyboardcontroller.hpp"
43 #include "scripting/squirrel_util.hpp"
44 #include "main.hpp"
45 #include "platform.hpp"
46 #include "badguy/badguy.hpp"
47 #include "player_status.hpp"
48 #include "log.hpp"
49 #include "falling_coin.hpp"
50 #include "random_generator.hpp"
51 #include "object/sprite_particle.hpp"
52 #include "trigger/climbable.hpp"
53
54 //#define SWIMMING
55
56 namespace {
57   static const int TILES_FOR_BUTTJUMP = 3;
58   static const float BUTTJUMP_MIN_VELOCITY_Y = 400.0f;
59   static const float SHOOTING_TIME = .150f;
60
61   /** number of idle stages, including standing */
62   static const unsigned int IDLE_STAGE_COUNT = 5;
63   /**
64    * how long to play each idle animation in milliseconds
65    * '0' means the sprite action is played once before moving onto the next
66    * animation
67    */
68   static const int IDLE_TIME[] = { 5000, 0, 2500, 0, 2500 };
69   /** idle stages */
70   static const std::string IDLE_STAGES[] =
71     { "stand",
72       "idle",
73       "stand",
74       "idle",
75       "stand" };
76
77   /** acceleration in horizontal direction when walking
78    * (all accelerations are in  pixel/s^2) */
79   static const float WALK_ACCELERATION_X = 300;
80   /** acceleration in horizontal direction when running */ 
81   static const float RUN_ACCELERATION_X = 400;
82   /** acceleration when skidding */
83   static const float SKID_XM = 200;
84   /** time of skidding in seconds */
85   static const float SKID_TIME = .3f;
86   /** maximum walk velocity (pixel/s) */
87   static const float MAX_WALK_XM = 230;
88   /** maximum run velocity (pixel/s) */
89   static const float MAX_RUN_XM = 320;
90   /** maximum horizontal climb velocity */
91   static const float MAX_CLIMB_XM = 48;
92   /** maximum vertical climb velocity */
93   static const float MAX_CLIMB_YM = 128;
94   /** instant velocity when tux starts to walk */
95   static const float WALK_SPEED = 100;
96
97   /** time of the kick (kicking mriceblock) animation */
98   static const float KICK_TIME = .3f;
99   /** time of tux cheering (currently unused) */
100   static const float CHEER_TIME = 1.0f;
101
102   /** if Tux cannot unduck for this long, he will get hurt */
103   static const float UNDUCK_HURT_TIME = 0.25f;
104   /** gravity is higher after the jump key is released before
105       the apex of the jump is reached */
106   static const float JUMP_EARLY_APEX_FACTOR = 3.0;
107
108   static const float JUMP_GRACE_TIME = 0.25f; /**< time before hitting the ground that the jump button may be pressed (and still trigger a jump) */
109
110   bool no_water = true;
111 }
112
113 Player::Player(PlayerStatus* _player_status, const std::string& name)
114   : scripting_controller(0), 
115     player_status(_player_status), 
116     scripting_controller_old(0),
117     grabbed_object(NULL), ghost_mode(false), edit_mode(false), idle_stage(0),
118     climbing(0)
119 {
120   this->name = name;
121   controller = main_controller;
122   scripting_controller = new CodeController();
123   sprite = sprite_manager->create("images/creatures/tux/tux.sprite");
124   airarrow.reset(new Surface("images/engine/hud/airarrow.png"));
125   idle_timer.start(IDLE_TIME[0]/1000.0f);
126
127   sound_manager->preload("sounds/bigjump.wav");
128   sound_manager->preload("sounds/jump.wav");
129   sound_manager->preload("sounds/hurt.wav");
130   sound_manager->preload("sounds/skid.wav");
131   sound_manager->preload("sounds/flip.wav");
132   sound_manager->preload("sounds/invincible_start.ogg");
133   sound_manager->preload("sounds/splash.ogg");
134
135   init();
136 }
137
138 Player::~Player()
139 {
140   if (climbing) stop_climbing(*climbing);
141   delete sprite;
142   delete scripting_controller;
143 }
144
145 void
146 Player::init()
147 {
148   if(is_big())
149     set_size(31.8f, 62.8f);
150   else
151     set_size(31.8f, 30.8f);
152
153   dir = RIGHT;
154   old_dir = dir;
155   duck = false;
156   dead = false;
157
158   dying = false;
159   peekingX = AUTO;
160   peekingY = AUTO;
161   last_ground_y = 0;
162   fall_mode = ON_GROUND;
163   jumping = false;
164   jump_early_apex = false;
165   can_jump = true;
166   wants_buttjump = false;
167   does_buttjump = false;
168   growing = false;
169   deactivated = false;
170   backflipping = false;
171   backflip_direction = 0;
172   visible = true;
173   swimming = false;
174   speedlimit = 0; //no special limit
175
176   on_ground_flag = false;
177   grabbed_object = NULL;
178
179   climbing = 0;
180
181   physic.reset();
182 }
183
184 void
185 Player::expose(HSQUIRRELVM vm, SQInteger table_idx)
186 {
187   if (name.empty())
188     return;
189
190   Scripting::expose_object(vm, table_idx, dynamic_cast<Scripting::Player *>(this), name, false);
191 }
192
193 void
194 Player::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
195 {
196   if (name.empty())
197     return;
198
199   Scripting::unexpose_object(vm, table_idx, name);
200 }
201
202 float
203 Player::get_speedlimit()
204 {
205   return speedlimit;
206 }
207
208 void
209 Player::set_speedlimit(float newlimit)
210 {
211   speedlimit=newlimit;
212 }
213
214 void
215 Player::set_controller(Controller* controller)
216 {
217   this->controller = controller;
218 }
219
220 void 
221 Player::use_scripting_controller(bool use_or_release)
222 {
223   if ((use_or_release == true) && (controller != scripting_controller)) {
224     scripting_controller_old = get_controller();
225     set_controller(scripting_controller);
226   }
227   if ((use_or_release == false) && (controller == scripting_controller)) {
228     set_controller(scripting_controller_old);
229     scripting_controller_old = 0;
230   }
231 }
232
233 void 
234 Player::do_scripting_controller(std::string control, bool pressed)
235 {
236   for(int i = 0; Controller::controlNames[i] != 0; ++i) {
237     if(control == std::string(Controller::controlNames[i])) {
238       scripting_controller->press(Controller::Control(i), pressed);
239     }
240   }
241 }
242
243 bool
244 Player::adjust_height(float new_height)
245 {
246   Rect bbox2 = bbox;
247   bbox2.move(Vector(0, bbox.get_height() - new_height));
248   bbox2.set_height(new_height);
249
250   if(new_height > bbox.get_height()) {
251     Rect additional_space = bbox2;
252     additional_space.set_height(new_height - bbox.get_height());
253     if(!Sector::current()->is_free_of_statics(additional_space, this, true))
254       return false;
255   }
256
257   // adjust bbox accordingly
258   // note that we use members of moving_object for this, so we can run this during CD, too
259   set_pos(bbox2.p1);
260   set_size(bbox2.get_width(), bbox2.get_height());
261   return true;
262 }
263
264 void
265 Player::trigger_sequence(std::string sequence_name)
266 {
267   if (climbing) stop_climbing(*climbing);
268   GameSession::current()->start_sequence(sequence_name);
269 }
270
271 void
272 Player::update(float elapsed_time)
273 {
274   if( no_water ){
275     swimming = false;
276   }
277   no_water = true;
278
279   if(dying && dying_timer.check()) {
280     dead = true;
281     return;
282   }
283
284   if(!dying && !deactivated)
285     handle_input();
286
287   // handle_input() calls apply_friction() when Tux is not walking, so we'll have to do this ourselves
288   if (deactivated)
289     apply_friction();
290
291   // extend/shrink tux collision rectangle so that we fall through/walk over 1
292   // tile holes
293   if(fabsf(physic.get_velocity_x()) > MAX_WALK_XM) {
294     set_width(34);
295   } else {
296     set_width(31.8f);
297   }
298
299   // on downward slopes, adjust vertical velocity so tux walks smoothly down
300   if (on_ground()) {
301     if(floor_normal.y != 0) {
302       if ((floor_normal.x * physic.get_velocity_x()) >= 0) {
303         physic.set_velocity_y(250);
304       }
305     }
306   }
307
308   // handle backflipping
309   if (backflipping) {
310     //prevent player from changing direction when backflipping
311     dir = (backflip_direction == 1) ? LEFT : RIGHT;
312     if (backflip_timer.started()) physic.set_velocity_x(100 * backflip_direction);
313   }
314
315   // set fall mode...
316   if(on_ground()) {
317     fall_mode = ON_GROUND;
318     last_ground_y = get_pos().y;
319   } else {
320     if(get_pos().y > last_ground_y)
321       fall_mode = FALLING;
322     else if(fall_mode == ON_GROUND)
323       fall_mode = JUMPING;
324   }
325
326   // check if we landed
327   if(on_ground()) {
328     jumping = false;
329     if (backflipping && (!backflip_timer.started())) {
330       backflipping = false;
331       backflip_direction = 0;
332
333       // if controls are currently deactivated, we take care of standing up ourselves
334       if (deactivated)
335         do_standup();
336     }
337   }
338
339   // calculate movement for this frame
340   movement = physic.get_movement(elapsed_time);
341
342   if(grabbed_object != NULL && !dying) {
343     Vector pos = get_pos() +
344       Vector(dir == LEFT ? -16 : 16, get_bbox().get_height()*0.66666 - 32);
345     grabbed_object->grab(*this, pos, dir);
346   }
347
348   if(grabbed_object != NULL && dying){
349     grabbed_object->ungrab(*this, dir);
350     grabbed_object = NULL;
351   }
352
353   on_ground_flag = false;
354
355   // when invincible, spawn particles
356   if (invincible_timer.started() && !dying)
357   {
358     if (systemRandom.rand(0, 2) == 0) {
359       float px = systemRandom.randf(bbox.p1.x+0, bbox.p2.x-0);
360       float py = systemRandom.randf(bbox.p1.y+0, bbox.p2.y-0);
361       Vector ppos = Vector(px, py);
362       Vector pspeed = Vector(0, 0);
363       Vector paccel = Vector(0, 0);
364       // draw bright sparkle when there is lots of time left, dark sparkle when invincibility is about to end
365       if (invincible_timer.get_timeleft() > TUX_INVINCIBLE_TIME_WARNING) {
366         // make every other a longer sparkle to make trail a bit fuzzy
367         if (size_t(game_time*20)%2) {
368           Sector::current()->add_object(new SpriteParticle("images/objects/particles/sparkle.sprite", "small", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
369         } else {
370           Sector::current()->add_object(new SpriteParticle("images/objects/particles/sparkle.sprite", "medium", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
371         }
372       } else {
373         Sector::current()->add_object(new SpriteParticle("images/objects/particles/sparkle.sprite", "dark", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
374       }
375     }
376   }
377
378   if (growing) {
379     if (sprite->animation_done()) growing = false;
380   }
381
382 }
383
384 bool
385 Player::on_ground()
386 {
387   return on_ground_flag;
388 }
389
390 bool
391 Player::is_big()
392 {
393   if(player_status->bonus == NO_BONUS)
394     return false;
395
396   return true;
397 }
398
399 void
400 Player::apply_friction()
401 {
402   if ((on_ground()) && (fabs(physic.get_velocity_x()) < WALK_SPEED)) {
403     physic.set_velocity_x(0);
404     physic.set_acceleration_x(0);
405   } else if(physic.get_velocity_x() < 0) {
406     physic.set_acceleration_x(WALK_ACCELERATION_X * 1.5);
407     } else if(physic.get_velocity_x() > 0) {
408     physic.set_acceleration_x(WALK_ACCELERATION_X * -1.5);
409   }
410 }
411
412 void
413 Player::handle_horizontal_input()
414 {
415   float vx = physic.get_velocity_x();
416   float vy = physic.get_velocity_y();
417   float ax = physic.get_acceleration_x();
418   float ay = physic.get_acceleration_y();
419
420   float dirsign = 0;
421   if(!duck || physic.get_velocity_y() != 0) {
422     if(controller->hold(Controller::LEFT) && !controller->hold(Controller::RIGHT)) {
423       old_dir = dir;
424       dir = LEFT;
425       dirsign = -1;
426     } else if(!controller->hold(Controller::LEFT)
427               && controller->hold(Controller::RIGHT)) {
428       old_dir = dir;
429       dir = RIGHT;
430       dirsign = 1;
431     }
432   }
433
434   // do not run if action key is pressed or we're holding something
435   // so tux can only walk while shooting
436   if ( controller->hold(Controller::ACTION) || grabbed_object ) {
437     ax = dirsign * WALK_ACCELERATION_X;
438     // limit speed
439     if(vx >= MAX_WALK_XM && dirsign > 0) {
440       vx = MAX_WALK_XM;
441       ax = 0;
442     } else if(vx <= -MAX_WALK_XM && dirsign < 0) {
443       vx = -MAX_WALK_XM;
444       ax = 0;
445     }
446   } else {
447     if( vx * dirsign < MAX_WALK_XM ) {
448       ax = dirsign * WALK_ACCELERATION_X;
449     } else {
450       ax = dirsign * RUN_ACCELERATION_X;
451     }
452     // limit speed
453     if(vx >= MAX_RUN_XM && dirsign > 0) {
454       vx = MAX_RUN_XM;
455       ax = 0;
456     } else if(vx <= -MAX_RUN_XM && dirsign < 0) {
457       vx = -MAX_RUN_XM;
458       ax = 0;
459     }
460   }
461
462   // we can reach WALK_SPEED without any acceleration
463   if(dirsign != 0 && fabs(vx) < WALK_SPEED) {
464     vx = dirsign * WALK_SPEED;
465   }
466
467   //Check speedlimit.
468   if( speedlimit > 0 &&  vx * dirsign >= speedlimit ) {
469       vx = dirsign * speedlimit;
470       ax = 0;
471   }
472
473   // changing directions?
474   if(on_ground() && ((vx < 0 && dirsign >0) || (vx>0 && dirsign<0))) {
475     // let's skid!
476     if(fabs(vx)>SKID_XM && !skidding_timer.started()) {
477       skidding_timer.start(SKID_TIME);
478       sound_manager->play("sounds/skid.wav");
479       // dust some particles
480       Sector::current()->add_object(
481         new Particles(
482           Vector(dir == RIGHT ? get_bbox().p2.x : get_bbox().p1.x, get_bbox().p2.y),
483           dir == RIGHT ? 270+20 : 90-40, dir == RIGHT ? 270+40 : 90-20,
484           Vector(280, -260), Vector(0, 300), 3, Color(.4f, .4f, .4f), 3, .8f,
485           LAYER_OBJECTS+1));
486
487       ax *= 2.5;
488     } else {
489       ax *= 2;
490     }
491   }
492
493   physic.set_velocity(vx, vy);
494   physic.set_acceleration(ax, ay);
495
496   // we get slower when not pressing any keys
497   if(dirsign == 0) {
498     apply_friction();
499   }
500
501 }
502
503 void
504 Player::do_cheer()
505 {
506   do_duck();
507   do_backflip();
508   do_standup();
509 }
510
511 void
512 Player::do_duck() {
513   if (duck)
514     return;
515   if (!is_big())
516     return;
517
518   if (physic.get_velocity_y() != 0)
519     return;
520   if (!on_ground())
521     return;
522   if (does_buttjump)
523     return;
524
525   if (adjust_height(31.8f)) {
526     duck = true;
527     growing = false;
528     unduck_hurt_timer.stop();
529   } else {
530     // FIXME: what now?
531   }
532 }
533
534 void
535 Player::do_standup() {
536   if (!duck)
537     return;
538   if (!is_big())
539     return;
540   if (backflipping)
541     return;
542
543   if (adjust_height(63.8f)) {
544     duck = false;
545     unduck_hurt_timer.stop();
546   } else {
547     // if timer is not already running, start it.
548     if (unduck_hurt_timer.get_period() == 0) {
549       unduck_hurt_timer.start(UNDUCK_HURT_TIME);
550     }
551     else if (unduck_hurt_timer.check()) {
552       kill(false);
553     }
554   }
555
556 }
557
558 void
559 Player::do_backflip() {
560   if (!duck)
561     return;
562   if (!on_ground())
563     return;
564
565   backflip_direction = (dir == LEFT)?(+1):(-1);
566   backflipping = true;
567   do_jump(-580);
568   sound_manager->play("sounds/flip.wav");
569   backflip_timer.start(0.15f);
570 }
571
572 void
573 Player::do_jump(float yspeed) {
574   if (!on_ground())
575     return;
576
577   physic.set_velocity_y(yspeed);
578   //bbox.move(Vector(0, -1));
579   jumping = true;
580   on_ground_flag = false;
581   can_jump = false;
582
583   // play sound
584   if (is_big()) {
585     sound_manager->play("sounds/bigjump.wav");
586   } else {
587     sound_manager->play("sounds/jump.wav");
588   }
589 }
590
591 void
592 Player::early_jump_apex() {
593   if(jump_early_apex) {
594     return;
595   }
596   jump_early_apex = true;
597   physic.set_gravity(physic.get_gravity() * JUMP_EARLY_APEX_FACTOR);
598 };
599
600 void
601 Player::do_jump_apex() {
602   if(!jump_early_apex) {
603     return;
604   }
605   jump_early_apex = false;
606   physic.set_gravity(physic.get_gravity() / JUMP_EARLY_APEX_FACTOR);
607 }
608
609 void
610 Player::handle_vertical_input()
611 {
612   // Press jump key
613   if(controller->pressed(Controller::JUMP)) jump_button_timer.start(JUMP_GRACE_TIME);
614   if(controller->hold(Controller::JUMP) && jump_button_timer.started() && can_jump) {
615     jump_button_timer.stop();
616     if (duck) {
617       // when running, only jump a little bit; else do a backflip
618       if ((physic.get_velocity_x() != 0) || (controller->hold(Controller::LEFT)) || (controller->hold(Controller::RIGHT))) do_jump(-300); else do_backflip();
619     } else {
620       // jump a bit higher if we are running; else do a normal jump
621       if (fabs(physic.get_velocity_x()) > MAX_WALK_XM) do_jump(-580); else do_jump(-520);
622     }
623   }
624   // Let go of jump key
625   else if(!controller->hold(Controller::JUMP)) {
626     if (!backflipping && jumping && physic.get_velocity_y() < 0) {
627       jumping = false;
628       early_jump_apex();
629     }
630   }
631
632   if(jump_early_apex && physic.get_velocity_y() >= 0) {
633     do_jump_apex();
634   }
635
636   /* In case the player has pressed Down while in a certain range of air,
637      enable butt jump action */
638   if (controller->hold(Controller::DOWN) && !duck && is_big() && !on_ground()) {
639     wants_buttjump = true;
640     if (physic.get_velocity_y() >= BUTTJUMP_MIN_VELOCITY_Y) does_buttjump = true;
641   }
642
643   /* When Down is not held anymore, disable butt jump */
644   if(!controller->hold(Controller::DOWN)) {
645     wants_buttjump = false;
646     does_buttjump = false;
647   }
648
649   // swimming
650   physic.set_acceleration_y(0);
651 #ifdef SWIMMING
652   if (swimming) {
653     if (controller->hold(Controller::UP) || controller->hold(Controller::JUMP))
654       physic.set_acceleration_y(-2000);
655     physic.set_velocity_y(physic.get_velocity_y() * 0.94);
656   }
657 #endif
658 }
659
660 void
661 Player::handle_input()
662 {
663   if (ghost_mode) {
664     handle_input_ghost();
665     return;
666   }
667   if (climbing) {
668     handle_input_climbing();
669     return;
670   }
671
672   /* Peeking */
673   if( controller->released( Controller::PEEK_LEFT ) ) {
674     peekingX = AUTO;
675   }
676   if( controller->released( Controller::PEEK_RIGHT ) ) {
677     peekingX = AUTO;
678   }
679   if( controller->released( Controller::PEEK_UP ) ) {
680     peekingY = AUTO;
681   }
682   if( controller->released( Controller::PEEK_DOWN ) ) {
683     peekingY = AUTO;
684   }
685   if( controller->pressed( Controller::PEEK_LEFT ) ) {
686     peekingX = LEFT;
687   }
688   if( controller->pressed( Controller::PEEK_RIGHT ) ) {
689     peekingX = RIGHT;
690   }
691   if(!backflipping && !jumping && on_ground()) {
692     if( controller->pressed( Controller::PEEK_UP ) ) {
693       peekingY = UP;
694     } else if( controller->pressed( Controller::PEEK_DOWN ) ) {
695       peekingY = DOWN;
696     }
697   }
698
699   /* Handle horizontal movement: */
700   if (!backflipping) handle_horizontal_input();
701
702   /* Jump/jumping? */
703   if (on_ground())
704     can_jump = true;
705
706   /* Handle vertical movement: */
707   handle_vertical_input();
708
709   /* Shoot! */
710   if (controller->pressed(Controller::ACTION) && (player_status->bonus == FIRE_BONUS || player_status->bonus == ICE_BONUS)) {
711     if(Sector::current()->add_bullet(
712          get_pos() + ((dir == LEFT)? Vector(0, bbox.get_height()/2)
713                       : Vector(32, bbox.get_height()/2)),
714          physic.get_velocity_x(), dir))
715       shooting_timer.start(SHOOTING_TIME);
716   }
717
718   /* Duck or Standup! */
719   if (controller->hold(Controller::DOWN)) {
720     do_duck();
721   } else {
722     do_standup();
723   }
724
725   /* grabbing */
726   try_grab();
727
728   if(!controller->hold(Controller::ACTION) && grabbed_object) {
729     // move the grabbed object a bit away from tux
730     Vector pos = get_pos() +
731         Vector(dir == LEFT ? -bbox.get_width()-1 : bbox.get_width()+1,
732                 bbox.get_height()*0.66666 - 32);
733     Rect dest(pos, pos + Vector(32, 32));
734     if(Sector::current()->is_free_of_movingstatics(dest)) {
735       MovingObject* moving_object = dynamic_cast<MovingObject*> (grabbed_object);
736       if(moving_object) {
737         moving_object->set_pos(pos);
738       } else {
739         log_debug << "Non MovingObject grabbed?!?" << std::endl;
740       }
741       if(controller->hold(Controller::UP)) {
742         grabbed_object->ungrab(*this, UP);
743       } else {
744         grabbed_object->ungrab(*this, dir);
745       }
746       grabbed_object = NULL;
747     }
748   }
749 }
750
751 void
752 Player::try_grab()
753 {
754   if(controller->hold(Controller::ACTION) && !grabbed_object
755       && !duck) {
756   Sector* sector = Sector::current();
757     Vector pos;
758     if(dir == LEFT) {
759       pos = Vector(bbox.get_left() - 5, bbox.get_bottom() - 16);
760     } else {
761       pos = Vector(bbox.get_right() + 5, bbox.get_bottom() - 16);
762     }
763
764     for(Sector::Portables::iterator i = sector->portables.begin();
765         i != sector->portables.end(); ++i) {
766       Portable* portable = *i;
767       if(!portable->is_portable())
768         continue;
769
770       // make sure the Portable is a MovingObject
771       MovingObject* moving_object = dynamic_cast<MovingObject*> (portable);
772       assert(moving_object);
773       if(moving_object == NULL)
774         continue;
775
776       // make sure the Portable isn't currently non-solid
777       if(moving_object->get_group() == COLGROUP_DISABLED) continue;
778
779       // check if we are within reach
780       if(moving_object->get_bbox().contains(pos)) {
781         if (climbing) stop_climbing(*climbing);
782         grabbed_object = portable;
783         grabbed_object->grab(*this, get_pos(), dir);
784         break;
785       }
786     }
787   }
788 }
789
790 void
791 Player::handle_input_ghost()
792 {
793   float vx = 0;
794   float vy = 0;
795   if (controller->hold(Controller::LEFT)) {
796     dir = LEFT;
797     vx -= MAX_RUN_XM * 2;
798   }
799   if (controller->hold(Controller::RIGHT)) {
800     dir = RIGHT;
801     vx += MAX_RUN_XM * 2;
802   }
803   if ((controller->hold(Controller::UP)) || (controller->hold(Controller::JUMP))) {
804     vy -= MAX_RUN_XM * 2;
805   }
806   if (controller->hold(Controller::DOWN)) {
807     vy += MAX_RUN_XM * 2;
808   }
809   if (controller->hold(Controller::ACTION)) {
810     set_ghost_mode(false);
811   }
812   physic.set_velocity(vx, vy);
813   physic.set_acceleration(0, 0);
814 }
815
816 void
817 Player::add_coins(int count)
818 {
819   player_status->add_coins(count);
820 }
821
822 int
823 Player::get_coins()
824 {
825   return player_status->coins;
826 }
827
828 bool
829 Player::add_bonus(const std::string& bonustype)
830 {
831   BonusType type = NO_BONUS;
832
833   if(bonustype == "grow") {
834     type = GROWUP_BONUS;
835   } else if(bonustype == "fireflower") {
836     type = FIRE_BONUS;
837   } else if(bonustype == "iceflower") {
838     type = ICE_BONUS;
839   } else if(bonustype == "none") {
840     type = NO_BONUS;
841   } else {
842     std::ostringstream msg;
843     msg << "Unknown bonus type "  << bonustype;
844     throw std::runtime_error(msg.str());
845   }
846
847   return add_bonus(type);
848 }
849
850 bool
851 Player::add_bonus(BonusType type, bool animate)
852 {
853   // always ignore NO_BONUS
854   if (type == NO_BONUS) {
855     return true;
856   }
857
858   // ignore GROWUP_BONUS if we're already big
859   if (type == GROWUP_BONUS) {
860     if (player_status->bonus == GROWUP_BONUS)
861       return true;
862     if (player_status->bonus == FIRE_BONUS)
863       return true;
864     if (player_status->bonus == ICE_BONUS)
865       return true;
866   }
867
868   return set_bonus(type, animate);
869 }
870
871 bool
872 Player::set_bonus(BonusType type, bool animate)
873 {
874   if(player_status->bonus == NO_BONUS) {
875     if (!adjust_height(62.8f)) {
876       printf("can't adjust\n");
877       return false;
878     }
879     if(animate) {
880       growing = true;
881       sprite->set_action((dir == LEFT)?"grow-left":"grow-right", 1);
882     }
883     if (climbing) stop_climbing(*climbing);
884   }
885
886   if (type == NO_BONUS) {
887     if (does_buttjump) does_buttjump = false;
888   }
889
890   if ((type == NO_BONUS) || (type == GROWUP_BONUS)) {
891     if ((player_status->bonus == FIRE_BONUS) && (animate)) {
892       // visually lose helmet
893       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
894       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
895       Vector paccel = Vector(0, 1000);
896       std::string action = (dir==LEFT)?"left":"right";
897       Sector::current()->add_object(new SpriteParticle("images/objects/particles/firetux-helmet.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
898       if (climbing) stop_climbing(*climbing);
899     }
900     if ((player_status->bonus == ICE_BONUS) && (animate)) {
901       // visually lose cap
902       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
903       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
904       Vector paccel = Vector(0, 1000);
905       std::string action = (dir==LEFT)?"left":"right";
906       Sector::current()->add_object(new SpriteParticle("images/objects/particles/icetux-cap.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
907       if (climbing) stop_climbing(*climbing);
908     }
909     player_status->max_fire_bullets = 0;
910     player_status->max_ice_bullets = 0;
911   }
912   if (type == FIRE_BONUS) player_status->max_fire_bullets++;
913   if (type == ICE_BONUS) player_status->max_ice_bullets++;
914
915   player_status->bonus = type;
916   return true;
917 }
918
919 void
920 Player::set_visible(bool visible)
921 {
922   this->visible = visible;
923   if( visible )
924     set_group(COLGROUP_MOVING);
925   else
926     set_group(COLGROUP_DISABLED);
927 }
928
929 bool
930 Player::get_visible()
931 {
932   return visible;
933 }
934
935 void
936 Player::kick()
937 {
938   kick_timer.start(KICK_TIME);
939 }
940
941 void
942 Player::draw(DrawingContext& context)
943 {
944   if(!visible)
945     return;
946
947   // if Tux is above camera, draw little "air arrow" to show where he is x-wise
948   if (Sector::current() && Sector::current()->camera && (get_bbox().p2.y - 16 < Sector::current()->camera->get_translation().y)) {
949     float px = get_pos().x + (get_bbox().p2.x - get_bbox().p1.x - airarrow.get()->get_width()) / 2;
950     float py = Sector::current()->camera->get_translation().y;
951     py += std::min(((py - (get_bbox().p2.y + 16)) / 4), 16.0f);
952     context.draw_surface(airarrow.get(), Vector(px, py), LAYER_HUD - 1);
953   }
954
955   std::string sa_prefix = "";
956   std::string sa_postfix = "";
957
958   if (player_status->bonus == GROWUP_BONUS)
959     sa_prefix = "big";
960   else if (player_status->bonus == FIRE_BONUS)
961     sa_prefix = "fire";
962   else if (player_status->bonus == ICE_BONUS)
963     sa_prefix = "ice";
964   else
965     sa_prefix = "small";
966
967   if(dir == LEFT)
968     sa_postfix = "-left";
969   else
970     sa_postfix = "-right";
971
972   /* Set Tux sprite action */
973   if(dying) {
974     sprite->set_action("gameover");
975   }
976   else if (growing) {
977     sprite->set_action_continued("grow"+sa_postfix);
978     // while growing, do not change action
979     // do_duck() will take care of cancelling growing manually
980     // update() will take care of cancelling when growing completed
981   }
982   else if (climbing) {
983     sprite->set_action(sa_prefix+"-skid"+sa_postfix);
984   }
985   else if (backflipping) {
986     sprite->set_action(sa_prefix+"-backflip"+sa_postfix);
987   }
988   else if (duck && is_big()) {
989     sprite->set_action(sa_prefix+"-duck"+sa_postfix);
990   }
991   else if (skidding_timer.started() && !skidding_timer.check()) {
992     sprite->set_action(sa_prefix+"-skid"+sa_postfix);
993   }
994   else if (kick_timer.started() && !kick_timer.check()) {
995     sprite->set_action(sa_prefix+"-kick"+sa_postfix);
996   }
997   else if ((wants_buttjump || does_buttjump) && is_big()) {
998     sprite->set_action(sa_prefix+"-buttjump"+sa_postfix);
999   }
1000   else if (!on_ground()) {
1001     sprite->set_action(sa_prefix+"-jump"+sa_postfix);
1002   }
1003   else {
1004     if (fabsf(physic.get_velocity_x()) < 1.0f) {
1005       // Determine which idle stage we're at
1006       if (sprite->get_action().find("-stand-") == std::string::npos && sprite->get_action().find("-idle-") == std::string::npos) {
1007         idle_stage = 0;
1008         idle_timer.start(IDLE_TIME[idle_stage]/1000.0f);
1009
1010         sprite->set_action_continued(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1011       }
1012       else if (idle_timer.check() || (IDLE_TIME[idle_stage] == 0 && sprite->animation_done())) {
1013         idle_stage++;
1014         if (idle_stage >= IDLE_STAGE_COUNT)
1015             idle_stage = 1;
1016
1017         idle_timer.start(IDLE_TIME[idle_stage]/1000.0f);
1018
1019         if (IDLE_TIME[idle_stage] == 0)
1020           sprite->set_action(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix, 1);
1021         else
1022           sprite->set_action(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1023       }
1024       else {
1025         sprite->set_action_continued(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1026       }
1027     }
1028     else {
1029       sprite->set_action(sa_prefix+"-walk"+sa_postfix);
1030     }
1031   }
1032
1033
1034 /*
1035   // Tux is holding something
1036   if ((grabbed_object != 0 && physic.get_velocity_y() == 0) ||
1037       (shooting_timer.get_timeleft() > 0 && !shooting_timer.check())) {
1038     if (duck) {
1039     } else {
1040     }
1041   }
1042 */
1043
1044   /* Draw Tux */
1045   if (safe_timer.started() && size_t(game_time*40)%2)
1046     ;  // don't draw Tux
1047   else {
1048     sprite->draw(context, get_pos(), LAYER_OBJECTS + 1);
1049   }
1050
1051 }
1052
1053 void
1054 Player::collision_tile(uint32_t tile_attributes)
1055 {
1056   if(tile_attributes & Tile::HURTS)
1057     kill(false);
1058
1059 #ifdef SWIMMING
1060   if( swimming ){
1061     if( tile_attributes & Tile::WATER ){
1062       no_water = false;
1063     } else {
1064       swimming = false;
1065     }
1066   } else {
1067     if( tile_attributes & Tile::WATER ){
1068       swimming = true;
1069       no_water = false;
1070       sound_manager->play( "sounds/splash.ogg" );
1071     }
1072   }
1073 #endif
1074 }
1075
1076 void
1077 Player::collision_solid(const CollisionHit& hit)
1078 {
1079   if(hit.bottom) {
1080     if(physic.get_velocity_y() > 0)
1081       physic.set_velocity_y(0);
1082
1083     on_ground_flag = true;
1084     floor_normal = hit.slope_normal;
1085
1086     // Butt Jump landed    
1087     if (does_buttjump) {
1088       does_buttjump = false;
1089       physic.set_velocity_y(-300);
1090       on_ground_flag = false;
1091       Sector::current()->add_object(new Particles(
1092           Vector(get_bbox().p2.x, get_bbox().p2.y),
1093           270+20, 270+40,
1094           Vector(280, -260), Vector(0, 300), 3, Color(.4f, .4f, .4f), 3, .8f,
1095           LAYER_OBJECTS+1));
1096       Sector::current()->add_object(new Particles(
1097           Vector(get_bbox().p1.x, get_bbox().p2.y),
1098           90-40, 90-20,
1099           Vector(280, -260), Vector(0, 300), 3, Color(.4f, .4f, .4f), 3, .8f,
1100           LAYER_OBJECTS+1));
1101     }
1102
1103   } else if(hit.top) {
1104     if(physic.get_velocity_y() < 0)
1105       physic.set_velocity_y(.2f);
1106   }
1107
1108   if(hit.left || hit.right) {
1109     physic.set_velocity_x(0);
1110   }
1111
1112   // crushed?
1113   if(hit.crush) {
1114     if(hit.left || hit.right) {
1115       kill(true);
1116     } else if(hit.top || hit.bottom) {
1117       kill(false);
1118     }
1119   }
1120 }
1121
1122 HitResponse
1123 Player::collision(GameObject& other, const CollisionHit& hit)
1124 {
1125   Bullet* bullet = dynamic_cast<Bullet*> (&other);
1126   if(bullet) {
1127     return FORCE_MOVE;
1128   }
1129
1130   if(hit.left || hit.right) {
1131     try_grab(); //grab objects right now, in update it will be too late
1132   }
1133 #ifdef DEBUG
1134   assert(dynamic_cast<MovingObject*> (&other) != NULL);
1135 #endif
1136   MovingObject* moving_object = static_cast<MovingObject*> (&other);
1137   if(moving_object->get_group() == COLGROUP_TOUCHABLE) {
1138     TriggerBase* trigger = dynamic_cast<TriggerBase*> (&other);
1139     if(trigger) {
1140       if(controller->pressed(Controller::UP))
1141         trigger->event(*this, TriggerBase::EVENT_ACTIVATE);
1142     }
1143
1144     return FORCE_MOVE;
1145   }
1146
1147   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
1148   if(badguy != NULL) {
1149     if(safe_timer.started() || invincible_timer.started())
1150       return FORCE_MOVE;
1151
1152     return CONTINUE;
1153   }
1154
1155   return CONTINUE;
1156 }
1157
1158 void
1159 Player::make_invincible()
1160 {
1161   sound_manager->play("sounds/invincible_start.ogg");
1162   invincible_timer.start(TUX_INVINCIBLE_TIME);
1163   Sector::current()->play_music(HERRING_MUSIC);
1164 }
1165
1166 /* Kill Player! */
1167 void
1168 Player::kill(bool completely)
1169 {
1170   if(dying || deactivated)
1171     return;
1172
1173   if(!completely && (safe_timer.started() || invincible_timer.started()))
1174     return;
1175
1176   growing = false;
1177
1178   sound_manager->play("sounds/hurt.wav");
1179
1180   if (climbing) stop_climbing(*climbing);
1181
1182   physic.set_velocity_x(0);
1183
1184   if(!completely && is_big()) {
1185     if(player_status->bonus == FIRE_BONUS
1186         || player_status->bonus == ICE_BONUS) {
1187       safe_timer.start(TUX_SAFE_TIME);
1188       set_bonus(GROWUP_BONUS, true);
1189     } else if(player_status->bonus == GROWUP_BONUS) {
1190       safe_timer.start(TUX_SAFE_TIME /* + GROWING_TIME */);
1191       adjust_height(30.8f);
1192       duck = false;
1193       backflipping = false;
1194       set_bonus(NO_BONUS, true);
1195     } else if(player_status->bonus == NO_BONUS) {
1196       safe_timer.start(TUX_SAFE_TIME);
1197       adjust_height(30.8f);
1198       duck = false;
1199     }
1200   } else {
1201
1202     // do not die when in edit mode
1203     if (edit_mode) {
1204       set_ghost_mode(true);
1205       return;
1206     }
1207
1208     if (player_status->coins >= 25 && !GameSession::current()->get_reset_point_sectorname().empty())
1209     {
1210       for (int i = 0; i < 5; i++)
1211       {
1212         // the numbers: starting x, starting y, velocity y
1213         Sector::current()->add_object(new FallingCoin(get_pos() +
1214               Vector(systemRandom.rand(5), systemRandom.rand(-32,18)),
1215               systemRandom.rand(-100,100)));
1216       }
1217       player_status->coins -= std::max(player_status->coins/10, 25);
1218     }
1219     else
1220     {
1221       GameSession::current()->set_reset_point("", Vector());
1222     }
1223     physic.enable_gravity(true);
1224     physic.set_acceleration(0, 0);
1225     physic.set_velocity(0, -700);
1226     set_bonus(NO_BONUS, true);
1227     dying = true;
1228     dying_timer.start(3.0);
1229     set_group(COLGROUP_DISABLED);
1230
1231     DisplayEffect* effect = new DisplayEffect();
1232     effect->fade_out(3.0);
1233     Sector::current()->add_object(effect);
1234     sound_manager->stop_music(3.0);
1235   }
1236 }
1237
1238 void
1239 Player::move(const Vector& vector)
1240 {
1241   set_pos(vector);
1242
1243   // TODO: do we need the following? Seems irrelevant to moving the player
1244   if(is_big())
1245     set_size(31.8f, 63.8f);
1246   else
1247     set_size(31.8f, 31.8f);
1248   duck = false;
1249   last_ground_y = vector.y;
1250   if (climbing) stop_climbing(*climbing);
1251
1252   physic.reset();
1253 }
1254
1255 void
1256 Player::check_bounds(Camera* camera)
1257 {
1258   /* Keep tux in bounds: */
1259   if (get_pos().x < 0) {
1260     // Lock Tux to the size of the level, so that he doesn't fall of
1261     // on the left side
1262     set_pos(Vector(0, get_pos().y));
1263   }
1264
1265   /* fallen out of the level? */
1266   if ((get_pos().y > Sector::current()->get_height()) && (!ghost_mode)) {
1267     kill(true);
1268     return;
1269   }
1270
1271   // can happen if back scrolling is disabled
1272   if(get_pos().x < camera->get_translation().x) {
1273     set_pos(Vector(camera->get_translation().x, get_pos().y));
1274   }
1275   if(get_pos().x >= camera->get_translation().x + SCREEN_WIDTH - bbox.get_width())
1276   {
1277     set_pos(Vector(
1278           camera->get_translation().x + SCREEN_WIDTH - bbox.get_width(),
1279           get_pos().y));
1280   }
1281 }
1282
1283 void
1284 Player::add_velocity(const Vector& velocity)
1285 {
1286   physic.set_velocity(physic.get_velocity() + velocity);
1287 }
1288
1289 void
1290 Player::add_velocity(const Vector& velocity, const Vector& end_speed)
1291 {
1292   if (end_speed.x > 0)
1293     physic.set_velocity_x(std::min(physic.get_velocity_x() + velocity.x, end_speed.x));
1294   if (end_speed.x < 0)
1295     physic.set_velocity_x(std::max(physic.get_velocity_x() + velocity.x, end_speed.x));
1296   if (end_speed.y > 0)
1297     physic.set_velocity_y(std::min(physic.get_velocity_y() + velocity.y, end_speed.y));
1298   if (end_speed.y < 0)
1299     physic.set_velocity_y(std::max(physic.get_velocity_y() + velocity.y, end_speed.y));
1300 }
1301
1302 Vector 
1303 Player::get_velocity()
1304 {
1305   return physic.get_velocity();
1306 }
1307
1308 void
1309 Player::bounce(BadGuy& )
1310 {
1311   if(controller->hold(Controller::JUMP))
1312     physic.set_velocity_y(-520);
1313   else
1314     physic.set_velocity_y(-300);
1315 }
1316
1317 //Scripting Functions Below
1318
1319 void
1320 Player::deactivate()
1321 {
1322   if (deactivated)
1323     return;
1324   deactivated = true;
1325   physic.set_velocity_x(0);
1326   physic.set_velocity_y(0);
1327   physic.set_acceleration_x(0);
1328   physic.set_acceleration_y(0);
1329   if (climbing) stop_climbing(*climbing);
1330 }
1331
1332 void
1333 Player::activate()
1334 {
1335   if (!deactivated)
1336     return;
1337   deactivated = false;
1338 }
1339
1340 void Player::walk(float speed)
1341 {
1342   physic.set_velocity_x(speed);
1343 }
1344
1345 void
1346 Player::set_ghost_mode(bool enable)
1347 {
1348   if (ghost_mode == enable)
1349     return;
1350
1351   if (climbing) stop_climbing(*climbing);
1352
1353   if (enable) {
1354     ghost_mode = true;
1355     set_group(COLGROUP_DISABLED);
1356     physic.enable_gravity(false);
1357     log_debug << "You feel lightheaded. Use movement controls to float around, press ACTION to scare badguys." << std::endl;
1358   } else {
1359     ghost_mode = false;
1360     set_group(COLGROUP_MOVING);
1361     physic.enable_gravity(true);
1362     log_debug << "You feel solid again." << std::endl;
1363   }
1364 }
1365
1366
1367 void
1368 Player::set_edit_mode(bool enable)
1369 {
1370   edit_mode = enable;
1371 }
1372
1373 void 
1374 Player::start_climbing(Climbable& climbable)
1375 {
1376   if (climbing == &climbable) return;
1377
1378   climbing = &climbable;
1379   physic.enable_gravity(false);
1380   physic.set_velocity(0, 0);
1381   physic.set_acceleration(0, 0);
1382 }
1383
1384 void 
1385 Player::stop_climbing(Climbable& /*climbable*/)
1386 {
1387   if (!climbing) return;
1388
1389   climbing = 0;
1390
1391   if (grabbed_object) {    
1392     grabbed_object->ungrab(*this, dir);
1393     grabbed_object = NULL;
1394   }
1395
1396   physic.enable_gravity(true);
1397   physic.set_velocity(0, 0);
1398   physic.set_acceleration(0, 0);
1399
1400   if ((controller->hold(Controller::JUMP)) || (controller->hold(Controller::UP))) {
1401     on_ground_flag = true;
1402     // TODO: This won't help. Why?
1403     do_jump(-300);
1404   }
1405 }
1406
1407 void
1408 Player::handle_input_climbing()
1409 {
1410   if (!climbing) {
1411     log_warning << "handle_input_climbing called with climbing set to 0. Input handling skipped" << std::endl;
1412     return;
1413   }
1414
1415   float vx = 0;
1416   float vy = 0;
1417   if (controller->hold(Controller::LEFT)) {
1418     dir = LEFT;
1419     vx -= MAX_CLIMB_XM;
1420   }
1421   if (controller->hold(Controller::RIGHT)) {
1422     dir = RIGHT;
1423     vx += MAX_CLIMB_XM;
1424   }
1425   if (controller->hold(Controller::UP)) {
1426     vy -= MAX_CLIMB_YM;
1427   }
1428   if (controller->hold(Controller::DOWN)) {
1429     vy += MAX_CLIMB_YM;
1430   }
1431   if (controller->hold(Controller::JUMP)) {
1432     if (can_jump) {
1433       stop_climbing(*climbing);
1434       return;
1435     }  
1436   } else {
1437     can_jump = true;
1438   }
1439   if (controller->hold(Controller::ACTION)) {
1440     stop_climbing(*climbing);
1441     return;
1442   }
1443   physic.set_velocity(vx, vy);
1444   physic.set_acceleration(0, 0);
1445 }
1446
1447