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