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