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