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