better sound for splash effect
[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.wav");
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       if (!stone) {
420         sprite->set_angle(0.0f);
421         powersprite->set_angle(0.0f);
422         lightsprite->set_angle(0.0f);
423       }
424
425       // if controls are currently deactivated, we take care of standing up ourselves
426       if (deactivated)
427         do_standup();
428     }
429     if (player_status->bonus == AIR_BONUS)
430       ability_time = player_status->max_air_time * GLIDE_TIME_PER_FLOWER;
431   }
432
433   // calculate movement for this frame
434   movement = physic.get_movement(elapsed_time);
435
436   if(grabbed_object != NULL && !dying) {
437     position_grabbed_object();
438   }
439
440   if(grabbed_object != NULL && dying){
441     grabbed_object->ungrab(*this, dir);
442     grabbed_object = NULL;
443   }
444
445   if(!ice_this_frame && on_ground())
446     on_ice = false;
447
448   on_ground_flag = false;
449   ice_this_frame = false;
450
451   // when invincible, spawn particles
452   if (invincible_timer.started())
453   {
454     if (graphicsRandom.rand(0, 2) == 0) {
455       float px = graphicsRandom.randf(bbox.p1.x+0, bbox.p2.x-0);
456       float py = graphicsRandom.randf(bbox.p1.y+0, bbox.p2.y-0);
457       Vector ppos = Vector(px, py);
458       Vector pspeed = Vector(0, 0);
459       Vector paccel = Vector(0, 0);
460       Sector::current()->add_object(std::make_shared<SpriteParticle>(
461                                       "images/objects/particles/sparkle.sprite",
462                                       // draw bright sparkle when there is lots of time left,
463                                       // dark sparkle when invincibility is about to end
464                                       (invincible_timer.get_timeleft() > TUX_INVINCIBLE_TIME_WARNING) ?
465                                       // make every other a longer sparkle to make trail a bit fuzzy
466                                       (size_t(game_time*20)%2) ? "small" : "medium"
467                                       :
468                                       "dark", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
469     }
470   }
471
472   if (growing) {
473     if (sprite->animation_done()) growing = false;
474   }
475
476   // when climbing animate only while moving
477   if(climbing){
478     if((physic.get_velocity_x()==0)&&(physic.get_velocity_y()==0))
479       sprite->stop_animation();
480     else
481       sprite->set_animation_loops(-1);
482   }
483
484 }
485
486 bool
487 Player::on_ground()
488 {
489   return on_ground_flag;
490 }
491
492 bool
493 Player::is_big()
494 {
495   if(player_status->bonus == NO_BONUS)
496     return false;
497
498   return true;
499 }
500
501 void
502 Player::apply_friction()
503 {
504   if ((on_ground()) && (fabs(physic.get_velocity_x()) < WALK_SPEED)) {
505     physic.set_velocity_x(0);
506     physic.set_acceleration_x(0);
507   } else {
508     float friction = WALK_ACCELERATION_X * (on_ice ? ICE_FRICTION_MULTIPLIER : NORMAL_FRICTION_MULTIPLIER);
509     if(physic.get_velocity_x() < 0) {
510       physic.set_acceleration_x(friction);
511     } else if(physic.get_velocity_x() > 0) {
512       physic.set_acceleration_x(-friction);
513     } // no friction for physic.get_velocity_x() == 0
514   }
515 }
516
517 void
518 Player::handle_horizontal_input()
519 {
520   float vx = physic.get_velocity_x();
521   float vy = physic.get_velocity_y();
522   float ax = physic.get_acceleration_x();
523   float ay = physic.get_acceleration_y();
524
525   float dirsign = 0;
526   if(!duck || physic.get_velocity_y() != 0) {
527     if(controller->hold(Controller::LEFT) && !controller->hold(Controller::RIGHT)) {
528       old_dir = dir;
529       dir = LEFT;
530       dirsign = -1;
531     } else if(!controller->hold(Controller::LEFT)
532               && controller->hold(Controller::RIGHT)) {
533       old_dir = dir;
534       dir = RIGHT;
535       dirsign = 1;
536     }
537   }
538
539   // do not run if we're holding something which slows us down
540   if ( grabbed_object && grabbed_object->is_hampering() ) {
541     ax = dirsign * WALK_ACCELERATION_X;
542     // limit speed
543     if(vx >= MAX_WALK_XM && dirsign > 0) {
544       vx = MAX_WALK_XM;
545       ax = 0;
546     } else if(vx <= -MAX_WALK_XM && dirsign < 0) {
547       vx = -MAX_WALK_XM;
548       ax = 0;
549     }
550   } else {
551     if( vx * dirsign < MAX_WALK_XM ) {
552       ax = dirsign * WALK_ACCELERATION_X;
553     } else {
554       ax = dirsign * RUN_ACCELERATION_X;
555     }
556     // limit speed
557     if(vx >= MAX_RUN_XM + BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0) && dirsign > 0) {
558       vx = MAX_RUN_XM + BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0);
559       ax = 0;
560     } else if(vx <= -MAX_RUN_XM - BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0) && dirsign < 0) {
561       vx = -MAX_RUN_XM - BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0);
562       ax = 0;
563     }
564   }
565
566   // we can reach WALK_SPEED without any acceleration
567   if(dirsign != 0 && fabs(vx) < WALK_SPEED) {
568     vx = dirsign * WALK_SPEED;
569   }
570
571   //Check speedlimit.
572   if( speedlimit > 0 &&  vx * dirsign >= speedlimit ) {
573     vx = dirsign * speedlimit;
574     ax = 0;
575   }
576
577   // changing directions?
578   if(on_ground() && ((vx < 0 && dirsign >0) || (vx>0 && dirsign<0))) {
579     // let's skid!
580     if(fabs(vx)>SKID_XM && !skidding_timer.started()) {
581       skidding_timer.start(SKID_TIME);
582       SoundManager::current()->play("sounds/skid.wav");
583       // dust some particles
584       Sector::current()->add_object(
585         std::make_shared<Particles>(
586           Vector(dir == LEFT ? get_bbox().p2.x : get_bbox().p1.x, get_bbox().p2.y),
587           dir == LEFT ? 50 : -70, dir == LEFT ? 70 : -50, 260, 280,
588           Vector(0, 300), 3, Color(.4f, .4f, .4f), 3, .8f, LAYER_OBJECTS+1));
589
590       ax *= 2.5;
591     } else {
592       ax *= 2;
593     }
594   }
595
596   if(on_ice) {
597     ax *= ICE_ACCELERATION_MULTIPLIER;
598   }
599
600   physic.set_velocity(vx, vy);
601   physic.set_acceleration(ax, ay);
602
603   // we get slower when not pressing any keys
604   if(dirsign == 0) {
605     apply_friction();
606   }
607
608 }
609
610 void
611 Player::do_cheer()
612 {
613   do_duck();
614   do_backflip();
615   do_standup();
616 }
617
618 void
619 Player::do_duck() {
620   if (duck)
621     return;
622   if (!is_big())
623     return;
624
625   if (physic.get_velocity_y() != 0)
626     return;
627   if (!on_ground())
628     return;
629   if (does_buttjump)
630     return;
631
632   if (adjust_height(DUCKED_TUX_HEIGHT)) {
633     duck = true;
634     growing = false;
635     unduck_hurt_timer.stop();
636   } else {
637     // FIXME: what now?
638   }
639 }
640
641 void
642 Player::do_standup() {
643   if (!duck)
644     return;
645   if (!is_big())
646     return;
647   if (backflipping)
648     return;
649   if (stone)
650     return;
651
652   if (adjust_height(BIG_TUX_HEIGHT)) {
653     duck = false;
654     unduck_hurt_timer.stop();
655   } else {
656     // if timer is not already running, start it.
657     if (unduck_hurt_timer.get_period() == 0) {
658       unduck_hurt_timer.start(UNDUCK_HURT_TIME);
659     }
660     else if (unduck_hurt_timer.check()) {
661       kill(false);
662     }
663   }
664
665 }
666
667 void
668 Player::do_backflip() {
669   if (!duck)
670     return;
671   if (!on_ground())
672     return;
673
674   backflip_direction = (dir == LEFT)?(+1):(-1);
675   backflipping = true;
676   do_jump((player_status->bonus == AIR_BONUS) ? -720 : -580);
677   SoundManager::current()->play("sounds/flip.wav");
678   backflip_timer.start(TUX_BACKFLIP_TIME);
679 }
680
681 void
682 Player::do_jump(float yspeed) {
683   if (!on_ground())
684     return;
685
686   physic.set_velocity_y(yspeed);
687   //bbox.move(Vector(0, -1));
688   jumping = true;
689   on_ground_flag = false;
690   can_jump = false;
691
692   // play sound
693   if (is_big()) {
694     SoundManager::current()->play("sounds/bigjump.wav");
695   } else {
696     SoundManager::current()->play("sounds/jump.wav");
697   }
698 }
699
700 void
701 Player::early_jump_apex()
702 {
703   if (!jump_early_apex)
704   {
705     jump_early_apex = true;
706     physic.set_gravity_modifier(JUMP_EARLY_APEX_FACTOR);
707   }
708 }
709
710 void
711 Player::do_jump_apex()
712 {
713   if (jump_early_apex)
714   {
715     jump_early_apex = false;
716     physic.set_gravity_modifier(1.0f);
717   }
718 }
719
720 void
721 Player::handle_vertical_input()
722 {
723   // Press jump key
724   if(controller->pressed(Controller::JUMP)) jump_button_timer.start(JUMP_GRACE_TIME);
725   if(controller->hold(Controller::JUMP) && jump_button_timer.started() && can_jump) {
726     jump_button_timer.stop();
727     if (duck) {
728       // when running, only jump a little bit; else do a backflip
729       if ((physic.get_velocity_x() != 0) ||
730           (controller->hold(Controller::LEFT)) ||
731           (controller->hold(Controller::RIGHT)))
732       {
733         do_jump(-300);
734       }
735       else
736       {
737         do_backflip();
738       }
739     } else {
740       // airflower allows for higher jumps-
741       // jump a bit higher if we are running; else do a normal jump
742       if(player_status->bonus == AIR_BONUS)
743         do_jump((fabs(physic.get_velocity_x()) > MAX_WALK_XM) ? -620 : -580);
744       else
745         do_jump((fabs(physic.get_velocity_x()) > MAX_WALK_XM) ? -580 : -520);
746     }
747     // airflower glide only when holding jump key
748   } else  if (controller->hold(Controller::JUMP) && player_status->bonus == AIR_BONUS && physic.get_velocity_y() > MAX_GLIDE_YM) {
749       if (ability_time > 0 && !ability_timer.started())
750         ability_timer.start(ability_time);
751       else if (ability_timer.started()) {
752         // glide stops after some duration or if buttjump is initiated
753         if ((ability_timer.get_timeleft() <= 0.05f) || controller->hold(Controller::DOWN)) {
754           ability_time = 0;
755           ability_timer.stop();
756         } else {
757           physic.set_velocity_y(MAX_GLIDE_YM);
758           physic.set_acceleration_y(0);
759         }
760       }
761     }
762
763
764   // Let go of jump key
765   else if(!controller->hold(Controller::JUMP)) {
766     if (!backflipping && jumping && physic.get_velocity_y() < 0) {
767       jumping = false;
768       early_jump_apex();
769     }
770     if (player_status->bonus == AIR_BONUS && ability_timer.started()){
771       ability_time = ability_timer.get_timeleft();
772       ability_timer.stop();
773     }
774   }
775
776   if(jump_early_apex && physic.get_velocity_y() >= 0) {
777     do_jump_apex();
778   }
779
780   /* In case the player has pressed Down while in a certain range of air,
781      enable butt jump action */
782   if (controller->hold(Controller::DOWN) && !duck && is_big() && !on_ground()) {
783     wants_buttjump = true;
784     if (physic.get_velocity_y() >= BUTTJUMP_MIN_VELOCITY_Y) does_buttjump = true;
785   }
786
787   /* When Down is not held anymore, disable butt jump */
788   if(!controller->hold(Controller::DOWN)) {
789     wants_buttjump = false;
790     does_buttjump = false;
791   }
792
793   // swimming
794   physic.set_acceleration_y(0);
795 #ifdef SWIMMING
796   if (swimming) {
797     if (controller->hold(Controller::UP) || controller->hold(Controller::JUMP))
798       physic.set_acceleration_y(-2000);
799     physic.set_velocity_y(physic.get_velocity_y() * 0.94);
800   }
801 #endif
802 }
803
804 void
805 Player::handle_input()
806 {
807   if (ghost_mode) {
808     handle_input_ghost();
809     return;
810   }
811   if (climbing) {
812     handle_input_climbing();
813     return;
814   }
815
816   /* Peeking */
817   if( controller->released( Controller::PEEK_LEFT ) || controller->released( Controller::PEEK_RIGHT ) ) {
818     peekingX = AUTO;
819   }
820   if( controller->released( Controller::PEEK_UP ) || controller->released( Controller::PEEK_DOWN ) ) {
821     peekingY = AUTO;
822   }
823   if( controller->pressed( Controller::PEEK_LEFT ) ) {
824     peekingX = LEFT;
825   }
826   if( controller->pressed( Controller::PEEK_RIGHT ) ) {
827     peekingX = RIGHT;
828   }
829   if(!backflipping && !jumping && on_ground()) {
830     if( controller->pressed( Controller::PEEK_UP ) ) {
831       peekingY = UP;
832     } else if( controller->pressed( Controller::PEEK_DOWN ) ) {
833       peekingY = DOWN;
834     }
835   }
836
837   /* Handle horizontal movement: */
838   if (!backflipping && !stone) handle_horizontal_input();
839
840   /* Jump/jumping? */
841   if (on_ground())
842     can_jump = true;
843
844   /* Handle vertical movement: */
845   if (!stone) handle_vertical_input();
846
847   /* Shoot! */
848   if (controller->pressed(Controller::ACTION) && (player_status->bonus == FIRE_BONUS || player_status->bonus == ICE_BONUS)) {
849     if((player_status->bonus == FIRE_BONUS &&
850       Sector::current()->get_active_bullets() < player_status->max_fire_bullets) ||
851       (player_status->bonus == ICE_BONUS &&
852       Sector::current()->get_active_bullets() < player_status->max_ice_bullets))
853     {
854       Vector pos = get_pos() + ((dir == LEFT)? Vector(0, bbox.get_height()/2) : Vector(32, bbox.get_height()/2));
855       auto new_bullet = std::make_shared<Bullet>(pos, physic.get_velocity_x(), dir, player_status->bonus);
856       Sector::current()->add_object(new_bullet);
857
858       SoundManager::current()->play("sounds/shoot.wav");
859       shooting_timer.start(SHOOTING_TIME);
860     }
861   }
862
863   /* Turn to Stone */
864   if (controller->pressed(Controller::DOWN) && player_status->bonus == EARTH_BONUS && !cooldown_timer.started()) {
865     if (controller->hold(Controller::ACTION) && !ability_timer.started()) {
866       ability_timer.start(player_status->max_earth_time * STONE_TIME_PER_FLOWER);
867       powersprite->stop_animation();
868       stone = true;
869       physic.set_gravity_modifier(1.0f); // Undo jump_early_apex
870     }
871   }
872
873   if (stone)
874     apply_friction();
875
876   /* Revert from Stone */
877   if (stone && (!controller->hold(Controller::ACTION) || ability_timer.get_timeleft() <= 0.5f)) {
878     cooldown_timer.start(ability_timer.get_timegone()/2.0f); //The longer stone form is used, the longer until it can be used again
879     ability_timer.stop();
880     sprite->set_angle(0.0f);
881     powersprite->set_angle(0.0f);
882     lightsprite->set_angle(0.0f);
883     stone = false;
884     for (int i = 0; i < 8; i++)
885     {
886       Vector ppos = Vector(get_bbox().get_left() + 8 + 16*((int)i/4), get_bbox().get_top() + 16*(i%4));
887       float grey = graphicsRandom.randf(.4f, .8f);
888       Color pcolor = Color(grey, grey, grey);
889       Sector::current()->add_object(std::make_shared<Particles>(ppos, -60, 240, 42, 81, Vector(0, 500),
890                                                                 8, pcolor, 4 + graphicsRandom.randf(-0.4, 0.4),
891                                                                 0.8 + graphicsRandom.randf(0, 0.4), LAYER_OBJECTS+2));
892     }
893   }
894
895   /* Duck or Standup! */
896   if (controller->hold(Controller::DOWN) && !stone) {
897     do_duck();
898   } else {
899     do_standup();
900   }
901
902   /* grabbing */
903   try_grab();
904
905   if(!controller->hold(Controller::ACTION) && grabbed_object) {
906     MovingObject* moving_object = dynamic_cast<MovingObject*> (grabbed_object);
907     if(moving_object) {
908       // move the grabbed object a bit away from tux
909       Rectf grabbed_bbox = moving_object->get_bbox();
910       Rectf dest_;
911       dest_.p2.y = bbox.get_top() + bbox.get_height()*0.66666;
912       dest_.p1.y = dest_.p2.y - grabbed_bbox.get_height();
913       if(dir == LEFT) {
914         dest_.p2.x = bbox.get_left() - 1;
915         dest_.p1.x = dest_.p2.x - grabbed_bbox.get_width();
916       } else {
917         dest_.p1.x = bbox.get_right() + 1;
918         dest_.p2.x = dest_.p1.x + grabbed_bbox.get_width();
919       }
920       if(Sector::current()->is_free_of_tiles(dest_, true)) {
921         moving_object->set_pos(dest_.p1);
922         if(controller->hold(Controller::UP)) {
923           grabbed_object->ungrab(*this, UP);
924         } else {
925           grabbed_object->ungrab(*this, dir);
926         }
927         grabbed_object = NULL;
928       }
929     } else {
930       log_debug << "Non MovingObject grabbed?!?" << std::endl;
931     }
932   }
933
934   /* stop backflipping at will */
935   if( backflipping && ( !controller->hold(Controller::JUMP) && !backflip_timer.started()) ){
936     backflipping = false;
937     backflip_direction = 0;
938     sprite->set_angle(0.0f);
939     powersprite->set_angle(0.0f);
940     lightsprite->set_angle(0.0f);
941   }
942 }
943
944 void
945 Player::position_grabbed_object()
946 {
947   MovingObject* moving_object = dynamic_cast<MovingObject*>(grabbed_object);
948   assert(moving_object);
949
950   // Position where we will hold the lower-inner corner
951   Vector pos(get_bbox().get_left() + get_bbox().get_width()/2,
952       get_bbox().get_top() + get_bbox().get_height()*0.66666);
953
954   // Adjust to find the grabbed object's upper-left corner
955   if (dir == LEFT)
956     pos.x -= moving_object->get_bbox().get_width();
957   pos.y -= moving_object->get_bbox().get_height();
958
959   grabbed_object->grab(*this, pos, dir);
960 }
961
962 void
963 Player::try_grab()
964 {
965   if(controller->hold(Controller::ACTION) && !grabbed_object
966      && !duck) {
967     Sector* sector = Sector::current();
968     Vector pos;
969     if(dir == LEFT) {
970       pos = Vector(bbox.get_left() - 5, bbox.get_bottom() - 16);
971     } else {
972       pos = Vector(bbox.get_right() + 5, bbox.get_bottom() - 16);
973     }
974
975     for(Sector::Portables::iterator i = sector->portables.begin();
976         i != sector->portables.end(); ++i) {
977       Portable* portable = *i;
978       if(!portable->is_portable())
979         continue;
980
981       // make sure the Portable is a MovingObject
982       MovingObject* moving_object = dynamic_cast<MovingObject*> (portable);
983       assert(moving_object);
984
985       // make sure the Portable isn't currently non-solid
986       if(moving_object->get_group() == COLGROUP_DISABLED) continue;
987
988       // check if we are within reach
989       if(moving_object->get_bbox().contains(pos)) {
990         if (climbing) stop_climbing(*climbing);
991         grabbed_object = portable;
992         position_grabbed_object();
993         break;
994       }
995     }
996   }
997 }
998
999 void
1000 Player::handle_input_ghost()
1001 {
1002   float vx = 0;
1003   float vy = 0;
1004   if (controller->hold(Controller::LEFT)) {
1005     dir = LEFT;
1006     vx -= MAX_RUN_XM * 2;
1007   }
1008   if (controller->hold(Controller::RIGHT)) {
1009     dir = RIGHT;
1010     vx += MAX_RUN_XM * 2;
1011   }
1012   if ((controller->hold(Controller::UP)) || (controller->hold(Controller::JUMP))) {
1013     vy -= MAX_RUN_XM * 2;
1014   }
1015   if (controller->hold(Controller::DOWN)) {
1016     vy += MAX_RUN_XM * 2;
1017   }
1018   if (controller->hold(Controller::ACTION)) {
1019     set_ghost_mode(false);
1020   }
1021   physic.set_velocity(vx, vy);
1022   physic.set_acceleration(0, 0);
1023 }
1024
1025 void
1026 Player::add_coins(int count)
1027 {
1028   player_status->add_coins(count);
1029 }
1030
1031 int
1032 Player::get_coins()
1033 {
1034   return player_status->coins;
1035 }
1036
1037 bool
1038 Player::add_bonus(const std::string& bonustype)
1039 {
1040   BonusType type = NO_BONUS;
1041
1042   if(bonustype == "grow") {
1043     type = GROWUP_BONUS;
1044   } else if(bonustype == "fireflower") {
1045     type = FIRE_BONUS;
1046   } else if(bonustype == "iceflower") {
1047     type = ICE_BONUS;
1048   } else if(bonustype == "airflower") {
1049     type = AIR_BONUS;
1050   } else if(bonustype == "earthflower") {
1051     type = EARTH_BONUS;
1052   } else if(bonustype == "none") {
1053     type = NO_BONUS;
1054   } else {
1055     std::ostringstream msg;
1056     msg << "Unknown bonus type "  << bonustype;
1057     throw std::runtime_error(msg.str());
1058   }
1059
1060   return add_bonus(type);
1061 }
1062
1063 bool
1064 Player::add_bonus(BonusType type, bool animate)
1065 {
1066   // always ignore NO_BONUS
1067   if (type == NO_BONUS) {
1068     return true;
1069   }
1070
1071   // ignore GROWUP_BONUS if we're already big
1072   if (type == GROWUP_BONUS) {
1073     if (player_status->bonus != NO_BONUS)
1074       return true;
1075   }
1076
1077   return set_bonus(type, animate);
1078 }
1079
1080 bool
1081 Player::set_bonus(BonusType type, bool animate)
1082 {
1083   if((player_status->bonus == NO_BONUS) && (type != NO_BONUS)) {
1084     if (!adjust_height(BIG_TUX_HEIGHT)) {
1085       log_debug << "Can't adjust Tux height" << std::endl;
1086       return false;
1087     }
1088     if(animate) {
1089       growing = true;
1090       sprite->set_action((dir == LEFT)?"grow-left":"grow-right", 1);
1091     }
1092     if (climbing) stop_climbing(*climbing);
1093   }
1094
1095   if (type == NO_BONUS) {
1096     if (does_buttjump) does_buttjump = false;
1097   }
1098
1099   if ((type == NO_BONUS) || (type == GROWUP_BONUS)) {
1100     if ((player_status->bonus == FIRE_BONUS) && (animate)) {
1101       // visually lose helmet
1102       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1103       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1104       Vector paccel = Vector(0, 1000);
1105       std::string action = (dir==LEFT)?"left":"right";
1106       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/firetux-helmet.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1107       if (climbing) stop_climbing(*climbing);
1108     }
1109     if ((player_status->bonus == ICE_BONUS) && (animate)) {
1110       // visually lose cap
1111       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1112       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1113       Vector paccel = Vector(0, 1000);
1114       std::string action = (dir==LEFT)?"left":"right";
1115       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/icetux-cap.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1116       if (climbing) stop_climbing(*climbing);
1117     }
1118     if ((player_status->bonus == AIR_BONUS) && (animate)) {
1119       // visually lose hat
1120       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1121       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1122       Vector paccel = Vector(0, 1000);
1123       std::string action = (dir==LEFT)?"left":"right";
1124       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/airtux-hat.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1125       if (climbing) stop_climbing(*climbing);
1126     }
1127     if ((player_status->bonus == EARTH_BONUS) && (animate)) {
1128       // visually lose hard-hat
1129       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1130       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1131       Vector paccel = Vector(0, 1000);
1132       std::string action = (dir==LEFT)?"left":"right";
1133       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/earthtux-hardhat.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1134       if (climbing) stop_climbing(*climbing);
1135     }
1136     player_status->max_fire_bullets = 0;
1137     player_status->max_ice_bullets = 0;
1138     player_status->max_air_time = 0;
1139     player_status->max_earth_time = 0;
1140   }
1141   if (type == FIRE_BONUS) player_status->max_fire_bullets++;
1142   if (type == ICE_BONUS) player_status->max_ice_bullets++;
1143   if (type == AIR_BONUS) player_status->max_air_time++;
1144   if (type == EARTH_BONUS) player_status->max_earth_time++;
1145
1146   player_status->bonus = type;
1147   return true;
1148 }
1149
1150 void
1151 Player::set_visible(bool visible_)
1152 {
1153   this->visible = visible_;
1154   if( visible_ )
1155     set_group(COLGROUP_MOVING);
1156   else
1157     set_group(COLGROUP_DISABLED);
1158 }
1159
1160 bool
1161 Player::get_visible()
1162 {
1163   return visible;
1164 }
1165
1166 void
1167 Player::kick()
1168 {
1169   kick_timer.start(KICK_TIME);
1170 }
1171
1172 void
1173 Player::draw(DrawingContext& context)
1174 {
1175   if(!visible)
1176     return;
1177
1178   // if Tux is above camera, draw little "air arrow" to show where he is x-wise
1179   if (Sector::current() && Sector::current()->camera && (get_bbox().p2.y - 16 < Sector::current()->camera->get_translation().y)) {
1180     float px = get_pos().x + (get_bbox().p2.x - get_bbox().p1.x - airarrow.get()->get_width()) / 2;
1181     float py = Sector::current()->camera->get_translation().y;
1182     py += std::min(((py - (get_bbox().p2.y + 16)) / 4), 16.0f);
1183     context.draw_surface(airarrow, Vector(px, py), LAYER_HUD - 1);
1184   }
1185
1186   std::string sa_prefix = "";
1187   std::string sa_postfix = "";
1188
1189   if (player_status->bonus == GROWUP_BONUS)
1190     sa_prefix = "big";
1191   else if (player_status->bonus == FIRE_BONUS)
1192     sa_prefix = "fire";
1193   else if (player_status->bonus == ICE_BONUS)
1194     sa_prefix = "ice";
1195   else if (player_status->bonus == AIR_BONUS)
1196     sa_prefix = "air";
1197   else if (player_status->bonus == EARTH_BONUS)
1198     sa_prefix = "earth";
1199   else
1200     sa_prefix = "small";
1201
1202   if(dir == LEFT)
1203     sa_postfix = "-left";
1204   else
1205     sa_postfix = "-right";
1206
1207   /* Set Tux sprite action */
1208   if(dying) {
1209     sprite->set_action("gameover");
1210   }
1211   else if (growing) {
1212     sprite->set_action_continued("grow"+sa_postfix);
1213     // while growing, do not change action
1214     // do_duck() will take care of cancelling growing manually
1215     // update() will take care of cancelling when growing completed
1216   }
1217   else if (stone) {
1218     sprite->set_action(sprite->get_action()+"-stone");
1219   }
1220   else if (climbing) {
1221     sprite->set_action(sa_prefix+"-climbing"+sa_postfix);
1222   }
1223   else if (backflipping) {
1224     sprite->set_action(sa_prefix+"-backflip"+sa_postfix);
1225   }
1226   else if (duck && is_big()) {
1227     sprite->set_action(sa_prefix+"-duck"+sa_postfix);
1228   }
1229   else if (skidding_timer.started() && !skidding_timer.check()) {
1230     sprite->set_action(sa_prefix+"-skid"+sa_postfix);
1231   }
1232   else if (kick_timer.started() && !kick_timer.check()) {
1233     sprite->set_action(sa_prefix+"-kick"+sa_postfix);
1234   }
1235   else if ((wants_buttjump || does_buttjump) && is_big()) {
1236     sprite->set_action(sa_prefix+"-buttjump"+sa_postfix);
1237   }
1238   else if (!on_ground() || fall_mode != ON_GROUND) {
1239     if(physic.get_velocity_x() != 0 || fall_mode != ON_GROUND) {
1240         sprite->set_action(sa_prefix+"-jump"+sa_postfix);
1241     }
1242   }
1243   else {
1244     if (fabsf(physic.get_velocity_x()) < 1.0f) {
1245       // Determine which idle stage we're at
1246       if (sprite->get_action().find("-stand-") == std::string::npos && sprite->get_action().find("-idle-") == std::string::npos) {
1247         idle_stage = 0;
1248         idle_timer.start(IDLE_TIME[idle_stage]/1000.0f);
1249
1250         sprite->set_action_continued(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1251       }
1252       else if (idle_timer.check() || (IDLE_TIME[idle_stage] == 0 && sprite->animation_done())) {
1253         idle_stage++;
1254         if (idle_stage >= IDLE_STAGE_COUNT)
1255           idle_stage = 1;
1256
1257         idle_timer.start(IDLE_TIME[idle_stage]/1000.0f);
1258
1259         if (IDLE_TIME[idle_stage] == 0)
1260           sprite->set_action(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix, 1);
1261         else
1262           sprite->set_action(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1263       }
1264       else {
1265         sprite->set_action_continued(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1266       }
1267     }
1268     else {
1269       sprite->set_action(sa_prefix+"-walk"+sa_postfix);
1270     }
1271   }
1272
1273   /* Set Tux powerup sprite action */
1274   if (player_status->bonus == EARTH_BONUS) {
1275     powersprite->set_action(sprite->get_action());
1276     lightsprite->set_action(sprite->get_action());
1277   } else if (player_status->bonus == AIR_BONUS)
1278     powersprite->set_action(sprite->get_action());
1279
1280   /*
1281   // Tux is holding something
1282   if ((grabbed_object != 0 && physic.get_velocity_y() == 0) ||
1283   (shooting_timer.get_timeleft() > 0 && !shooting_timer.check())) {
1284   if (duck) {
1285   } else {
1286   }
1287   }
1288   */
1289
1290   /* Draw Tux */
1291   if (safe_timer.started() && size_t(game_time*40)%2)
1292     ;  // don't draw Tux
1293   else if (player_status->bonus == EARTH_BONUS){ // draw special effects with earthflower bonus
1294     // shake at end of maximum stone duration
1295     Vector shake_delta = (stone && ability_timer.get_timeleft() < 1.0f) ? Vector(graphicsRandom.rand(-3,3), 0) : Vector(0,0);
1296     sprite->draw(context, get_pos() + shake_delta, LAYER_OBJECTS + 1);
1297     // draw hardhat
1298     powersprite->draw(context, get_pos() + shake_delta, LAYER_OBJECTS + 1);
1299     // light
1300     context.push_target();
1301     context.set_target(DrawingContext::LIGHTMAP);
1302     lightsprite->draw(context, get_pos(), 0);
1303     context.pop_target();
1304     // give an indicator that stone form cannot be used for a while
1305     if (cooldown_timer.started() && graphicsRandom.rand(0, 4) == 0) {
1306       float px = graphicsRandom.randf(bbox.p1.x, bbox.p2.x);
1307       float py = bbox.p2.y+8;
1308       Vector ppos = Vector(px, py);
1309       Sector::current()->add_object(std::make_shared<SpriteParticle>(
1310         "images/objects/particles/sparkle.sprite", "dark",
1311         ppos, ANCHOR_MIDDLE, Vector(0, 0), Vector(0, 0), LAYER_OBJECTS+1+5));
1312     }
1313   }
1314   else {
1315     sprite->draw(context, get_pos(), LAYER_OBJECTS + 1);
1316     if (player_status->bonus == AIR_BONUS)
1317       powersprite->draw(context, get_pos(), LAYER_OBJECTS + 1);
1318   }
1319
1320 }
1321
1322 void
1323 Player::collision_tile(uint32_t tile_attributes)
1324 {
1325   if(tile_attributes & Tile::HURTS)
1326     kill(false);
1327
1328 #ifdef SWIMMING
1329   if( swimming ){
1330     if( tile_attributes & Tile::WATER ){
1331       no_water = false;
1332     } else {
1333       swimming = false;
1334     }
1335   } else {
1336     if( tile_attributes & Tile::WATER ){
1337       swimming = true;
1338       no_water = false;
1339       SoundManager::current()->play( "sounds/splash.wav" );
1340     }
1341   }
1342 #endif
1343
1344   if(tile_attributes & Tile::ICE) {
1345     ice_this_frame = true;
1346     on_ice = true;
1347   }
1348 }
1349
1350 void
1351 Player::collision_solid(const CollisionHit& hit)
1352 {
1353   if(hit.bottom) {
1354     if(physic.get_velocity_y() > 0)
1355       physic.set_velocity_y(0);
1356
1357     on_ground_flag = true;
1358     floor_normal = hit.slope_normal;
1359
1360     // Butt Jump landed
1361     if (does_buttjump) {
1362       does_buttjump = false;
1363       physic.set_velocity_y(-300);
1364       on_ground_flag = false;
1365       Sector::current()->add_object(std::make_shared<Particles>(
1366                                       Vector(get_bbox().p2.x, get_bbox().p2.y),
1367                                       50, 70, 260, 280, Vector(0, 300), 3,
1368                                       Color(.4f, .4f, .4f), 3, .8f, LAYER_OBJECTS+1));
1369       Sector::current()->add_object(std::make_shared<Particles>(
1370                                       Vector(get_bbox().p1.x, get_bbox().p2.y),
1371                                       -70, -50, 260, 280, Vector(0, 300), 3,
1372                                       Color(.4f, .4f, .4f), 3, .8f, LAYER_OBJECTS+1));
1373       Sector::current()->camera->shake(.1f, 0, 5);
1374     }
1375
1376   } else if(hit.top) {
1377     if(physic.get_velocity_y() < 0)
1378       physic.set_velocity_y(.2f);
1379   }
1380
1381   if(hit.left || hit.right) {
1382     physic.set_velocity_x(0);
1383   }
1384
1385   // crushed?
1386   if(hit.crush) {
1387     if(hit.left || hit.right) {
1388       kill(true);
1389     } else if(hit.top || hit.bottom) {
1390       kill(false);
1391     }
1392   }
1393 }
1394
1395 HitResponse
1396 Player::collision(GameObject& other, const CollisionHit& hit)
1397 {
1398   Bullet* bullet = dynamic_cast<Bullet*> (&other);
1399   if(bullet) {
1400     return FORCE_MOVE;
1401   }
1402
1403   Player* player = dynamic_cast<Player*> (&other);
1404   if(player) {
1405     return ABORT_MOVE;
1406   }
1407
1408   if(hit.left || hit.right) {
1409     try_grab(); //grab objects right now, in update it will be too late
1410   }
1411   assert(dynamic_cast<MovingObject*> (&other) != NULL);
1412   MovingObject* moving_object = static_cast<MovingObject*> (&other);
1413   if(moving_object->get_group() == COLGROUP_TOUCHABLE) {
1414     TriggerBase* trigger = dynamic_cast<TriggerBase*> (&other);
1415     if(trigger) {
1416       if(controller->pressed(Controller::UP))
1417         trigger->event(*this, TriggerBase::EVENT_ACTIVATE);
1418     }
1419
1420     return FORCE_MOVE;
1421   }
1422
1423   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
1424   if(badguy != NULL) {
1425     if(safe_timer.started() || invincible_timer.started())
1426       return FORCE_MOVE;
1427     if(stone)
1428       return ABORT_MOVE;
1429
1430     return CONTINUE;
1431   }
1432
1433   return CONTINUE;
1434 }
1435
1436 void
1437 Player::make_invincible()
1438 {
1439   SoundManager::current()->play("sounds/invincible_start.ogg");
1440   invincible_timer.start(TUX_INVINCIBLE_TIME);
1441   Sector::current()->play_music(HERRING_MUSIC);
1442 }
1443
1444 /* Kill Player! */
1445 void
1446 Player::kill(bool completely)
1447 {
1448   if(dying || deactivated || is_winning() )
1449     return;
1450
1451   if(!completely && (safe_timer.started() || invincible_timer.started() || stone))
1452     return;
1453
1454   growing = false;
1455
1456   if (climbing) stop_climbing(*climbing);
1457
1458   physic.set_velocity_x(0);
1459
1460   sprite->set_angle(0.0f);
1461   powersprite->set_angle(0.0f);
1462   lightsprite->set_angle(0.0f);
1463
1464   if(!completely && is_big()) {
1465     SoundManager::current()->play("sounds/hurt.wav");
1466
1467     if(player_status->bonus == FIRE_BONUS
1468       || player_status->bonus == ICE_BONUS
1469       || player_status->bonus == AIR_BONUS
1470       || player_status->bonus == EARTH_BONUS) {
1471       safe_timer.start(TUX_SAFE_TIME);
1472       set_bonus(GROWUP_BONUS, true);
1473     } else if(player_status->bonus == GROWUP_BONUS) {
1474       safe_timer.start(TUX_SAFE_TIME /* + GROWING_TIME */);
1475       adjust_height(SMALL_TUX_HEIGHT);
1476       duck = false;
1477       backflipping = false;
1478       sprite->set_angle(0.0f);
1479       powersprite->set_angle(0.0f);
1480       lightsprite->set_angle(0.0f);
1481       set_bonus(NO_BONUS, true);
1482     } else if(player_status->bonus == NO_BONUS) {
1483       safe_timer.start(TUX_SAFE_TIME);
1484       adjust_height(SMALL_TUX_HEIGHT);
1485       duck = false;
1486     }
1487   } else {
1488     SoundManager::current()->play("sounds/kill.wav");
1489
1490     // do not die when in edit mode
1491     if (edit_mode) {
1492       set_ghost_mode(true);
1493       return;
1494     }
1495
1496     if (player_status->coins >= 25 && !GameSession::current()->get_reset_point_sectorname().empty())
1497     {
1498       for (int i = 0; i < 5; i++)
1499       {
1500         // the numbers: starting x, starting y, velocity y
1501         Sector::current()->add_object(std::make_shared<FallingCoin>(get_pos() +
1502                                                       Vector(graphicsRandom.rand(5), graphicsRandom.rand(-32,18)),
1503                                                       graphicsRandom.rand(-100,100)));
1504       }
1505       player_status->coins -= std::max(player_status->coins/10, 25);
1506     }
1507     else
1508     {
1509       GameSession::current()->set_reset_point("", Vector());
1510     }
1511     physic.enable_gravity(true);
1512     physic.set_gravity_modifier(1.0f); // Undo jump_early_apex
1513     safe_timer.stop();
1514     invincible_timer.stop();
1515     physic.set_acceleration(0, 0);
1516     physic.set_velocity(0, -700);
1517     set_bonus(NO_BONUS, true);
1518     dying = true;
1519     dying_timer.start(3.0);
1520     set_group(COLGROUP_DISABLED);
1521
1522     // TODO: need nice way to handle players dying in co-op mode
1523     Sector::current()->effect->fade_out(3.0);
1524     SoundManager::current()->stop_music(3.0);
1525   }
1526 }
1527
1528 void
1529 Player::move(const Vector& vector)
1530 {
1531   set_pos(vector);
1532
1533   // Reset size to get correct hitbox if Tux was eg. ducked before moving
1534   if(is_big())
1535     set_size(TUX_WIDTH, BIG_TUX_HEIGHT);
1536   else
1537     set_size(TUX_WIDTH, SMALL_TUX_HEIGHT);
1538   duck = false;
1539   backflipping = false;
1540   sprite->set_angle(0.0f);
1541   powersprite->set_angle(0.0f);
1542   lightsprite->set_angle(0.0f);
1543   last_ground_y = vector.y;
1544   if (climbing) stop_climbing(*climbing);
1545
1546   physic.reset();
1547 }
1548
1549 void
1550 Player::check_bounds()
1551 {
1552   /* Keep tux in sector bounds: */
1553   if (get_pos().x < 0) {
1554     // Lock Tux to the size of the level, so that he doesn't fall off
1555     // the left side
1556     set_pos(Vector(0, get_pos().y));
1557   }
1558
1559   if (get_bbox().get_right() > Sector::current()->get_width()) {
1560     // Lock Tux to the size of the level, so that he doesn't fall off
1561     // the right side
1562     set_pos(Vector(Sector::current()->get_width() - get_bbox().get_width(), get_pos().y));
1563   }
1564
1565   /* fallen out of the level? */
1566   if ((get_pos().y > Sector::current()->get_height()) && (!ghost_mode)) {
1567     kill(true);
1568     return;
1569   }
1570 }
1571
1572 void
1573 Player::add_velocity(const Vector& velocity)
1574 {
1575   physic.set_velocity(physic.get_velocity() + velocity);
1576 }
1577
1578 void
1579 Player::add_velocity(const Vector& velocity, const Vector& end_speed)
1580 {
1581   if (end_speed.x > 0)
1582     physic.set_velocity_x(std::min(physic.get_velocity_x() + velocity.x, end_speed.x));
1583   if (end_speed.x < 0)
1584     physic.set_velocity_x(std::max(physic.get_velocity_x() + velocity.x, end_speed.x));
1585   if (end_speed.y > 0)
1586     physic.set_velocity_y(std::min(physic.get_velocity_y() + velocity.y, end_speed.y));
1587   if (end_speed.y < 0)
1588     physic.set_velocity_y(std::max(physic.get_velocity_y() + velocity.y, end_speed.y));
1589 }
1590
1591 Vector
1592 Player::get_velocity()
1593 {
1594   return physic.get_velocity();
1595 }
1596
1597 void
1598 Player::bounce(BadGuy& )
1599 {
1600   if(!(player_status->bonus == AIR_BONUS))
1601     physic.set_velocity_y(controller->hold(Controller::JUMP) ? -520 : -300);
1602   else {
1603     physic.set_velocity_y(controller->hold(Controller::JUMP) ? -580 : -340);
1604     ability_time = player_status->max_air_time * GLIDE_TIME_PER_FLOWER;
1605   }
1606 }
1607
1608 //scripting Functions Below
1609
1610 void
1611 Player::deactivate()
1612 {
1613   if (deactivated)
1614     return;
1615   deactivated = true;
1616   physic.set_velocity_x(0);
1617   physic.set_velocity_y(0);
1618   physic.set_acceleration_x(0);
1619   physic.set_acceleration_y(0);
1620   if (climbing) stop_climbing(*climbing);
1621 }
1622
1623 void
1624 Player::activate()
1625 {
1626   if (!deactivated)
1627     return;
1628   deactivated = false;
1629 }
1630
1631 void Player::walk(float speed)
1632 {
1633   physic.set_velocity_x(speed);
1634 }
1635
1636 void Player::set_dir(bool right)
1637 {
1638   dir = right ? RIGHT : LEFT;
1639 }
1640
1641 void
1642 Player::set_ghost_mode(bool enable)
1643 {
1644   if (ghost_mode == enable)
1645     return;
1646
1647   if (climbing) stop_climbing(*climbing);
1648
1649   if (enable) {
1650     ghost_mode = true;
1651     set_group(COLGROUP_DISABLED);
1652     physic.enable_gravity(false);
1653     log_debug << "You feel lightheaded. Use movement controls to float around, press ACTION to scare badguys." << std::endl;
1654   } else {
1655     ghost_mode = false;
1656     set_group(COLGROUP_MOVING);
1657     physic.enable_gravity(true);
1658     log_debug << "You feel solid again." << std::endl;
1659   }
1660 }
1661
1662 void
1663 Player::set_edit_mode(bool enable)
1664 {
1665   edit_mode = enable;
1666 }
1667
1668 void
1669 Player::start_climbing(Climbable& climbable)
1670 {
1671   if (climbing || !&climbable) return;
1672
1673   climbing = &climbable;
1674   physic.enable_gravity(false);
1675   physic.set_velocity(0, 0);
1676   physic.set_acceleration(0, 0);
1677   if (backflipping) {
1678     backflipping = false;
1679     backflip_direction = 0;
1680     sprite->set_angle(0.0f);
1681     powersprite->set_angle(0.0f);
1682     lightsprite->set_angle(0.0f);
1683   }
1684 }
1685
1686 void
1687 Player::stop_climbing(Climbable& /*climbable*/)
1688 {
1689   if (!climbing) return;
1690
1691   climbing = 0;
1692
1693   if (grabbed_object) {
1694     grabbed_object->ungrab(*this, dir);
1695     grabbed_object = NULL;
1696   }
1697
1698   physic.enable_gravity(true);
1699   physic.set_velocity(0, 0);
1700   physic.set_acceleration(0, 0);
1701
1702   if ((controller->hold(Controller::JUMP)) || (controller->hold(Controller::UP))) {
1703     on_ground_flag = true;
1704     // TODO: This won't help. Why?
1705     do_jump(-300);
1706   }
1707 }
1708
1709 void
1710 Player::handle_input_climbing()
1711 {
1712   if (!climbing) {
1713     log_warning << "handle_input_climbing called with climbing set to 0. Input handling skipped" << std::endl;
1714     return;
1715   }
1716
1717   float vx = 0;
1718   float vy = 0;
1719   if (controller->hold(Controller::LEFT)) {
1720     dir = LEFT;
1721     vx -= MAX_CLIMB_XM;
1722   }
1723   if (controller->hold(Controller::RIGHT)) {
1724     dir = RIGHT;
1725     vx += MAX_CLIMB_XM;
1726   }
1727   if (controller->hold(Controller::UP)) {
1728     vy -= MAX_CLIMB_YM;
1729   }
1730   if (controller->hold(Controller::DOWN)) {
1731     vy += MAX_CLIMB_YM;
1732   }
1733   if (controller->hold(Controller::JUMP)) {
1734     if (can_jump) {
1735       stop_climbing(*climbing);
1736       return;
1737     }
1738   } else {
1739     can_jump = true;
1740   }
1741   if (controller->hold(Controller::ACTION)) {
1742     stop_climbing(*climbing);
1743     return;
1744   }
1745   physic.set_velocity(vx, vy);
1746   physic.set_acceleration(0, 0);
1747 }
1748
1749 /* EOF */