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