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