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