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