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