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