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