6e04514a3885afef16ceecf928a072149b6b484b
[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
53 static const int TILES_FOR_BUTTJUMP = 3;
54 static const float SHOOTING_TIME = .150;
55 /// time before idle animation starts
56 static const float IDLE_TIME = 2.5;
57
58 static const float WALK_ACCELERATION_X = 300;
59 static const float RUN_ACCELERATION_X = 400;
60 static const float SKID_XM = 200;
61 static const float SKID_TIME = .3;
62 static const float MAX_WALK_XM = 230;
63 static const float MAX_RUN_XM = 320;
64 static const float WALK_SPEED = 100;
65
66 static const float KICK_TIME = .3;
67 static const float CHEER_TIME = 1;
68
69 static const float UNDUCK_HURT_TIME = 0.25; /**< if Tux cannot unduck for this long, he will get hurt */
70
71 // growing animation
72 Surface* growingtux_left[GROWING_FRAMES];
73 Surface* growingtux_right[GROWING_FRAMES];
74
75 Surface* tux_life = 0;
76
77 TuxBodyParts* small_tux = 0;
78 TuxBodyParts* big_tux = 0;
79 TuxBodyParts* fire_tux = 0;
80 TuxBodyParts* ice_tux = 0;
81
82 void
83 TuxBodyParts::set_action(std::string action, int loops)
84 {
85   if(head != NULL)
86     head->set_action(action, loops);
87   if(body != NULL)
88     body->set_action(action, loops);
89   if(arms != NULL)
90     arms->set_action(action, loops);
91   if(feet != NULL)
92     feet->set_action(action, loops);
93 }
94
95 void
96 TuxBodyParts::draw(DrawingContext& context, const Vector& pos, int layer)
97 {
98   if(head != NULL)
99     head->draw(context, pos, layer-1);
100   if(body != NULL)
101     body->draw(context, pos, layer-3);
102   if(arms != NULL)
103     arms->draw(context, pos, layer+10);
104   if(feet != NULL)
105     feet->draw(context, pos, layer-2);
106 }
107
108 Player::Player(PlayerStatus* _player_status)
109   : player_status(_player_status), grabbed_object(NULL), ghost_mode(false)
110 {
111   controller = main_controller;
112   smalltux_gameover = sprite_manager->create("images/creatures/tux_small/smalltux-gameover.sprite");
113   smalltux_star = sprite_manager->create("images/creatures/tux_small/smalltux-star.sprite");
114   bigtux_star = sprite_manager->create("images/creatures/tux_big/bigtux-star.sprite");
115
116   sound_manager->preload("sounds/bigjump.wav");
117   sound_manager->preload("sounds/jump.wav");
118   sound_manager->preload("sounds/hurt.wav");
119   sound_manager->preload("sounds/skid.wav");
120   sound_manager->preload("sounds/flip.wav");
121   sound_manager->preload("sounds/invincible.wav");
122
123   init();
124 }
125
126 Player::~Player()
127 {
128   delete smalltux_gameover;
129   delete smalltux_star;
130   delete bigtux_star;
131 }
132
133 void
134 Player::init()
135 {
136   if(is_big())
137     set_size(31.8, 62.8);
138   else
139     set_size(31.8, 30.8);
140
141   dir = RIGHT;
142   old_dir = dir;
143   duck = false;
144   dead = false;
145
146   dying = false;
147   last_ground_y = 0;
148   fall_mode = ON_GROUND;
149   jumping = false;
150   can_jump = true;
151   butt_jump = false;
152   deactivated = false;
153   backflipping = false;
154   backflip_direction = 0;
155   visible = true;
156   
157   on_ground_flag = false;
158   grabbed_object = NULL;
159
160   floor_normal = Vector(0,-1);
161
162   physic.reset();
163 }
164
165 void
166 Player::expose(HSQUIRRELVM vm, SQInteger table_idx)
167 {
168   Scripting::Player* interface = static_cast<Scripting::Player*> (this);
169   Scripting::expose_object(vm, table_idx, interface, "Tux", false);
170 }
171
172 void
173 Player::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
174 {
175   Scripting::unexpose_object(vm, table_idx, "Tux");
176 }
177
178 void
179 Player::set_controller(Controller* controller)
180 {
181   this->controller = controller;
182 }
183
184 bool
185 Player::adjust_height(float new_height)
186 {
187   Rect bbox2 = bbox;
188   bbox2.move(Vector(0, bbox.get_height() - new_height));
189   bbox2.set_height(new_height);
190   if (!Sector::current()->is_free_space(bbox2)) return false;
191   // adjust bbox accordingly
192   // note that we use members of moving_object for this, so we can run this during CD, too
193   set_pos(bbox2.p1);
194   set_size(bbox2.get_width(), bbox2.get_height());
195   return true;
196 }
197
198 void
199 Player::update(float elapsed_time)
200 {
201   if(dying && dying_timer.check()) {
202     dead = true;
203     return;
204   }
205
206   if(!dying && !deactivated)
207     handle_input();
208
209   // handle_input() calls apply_friction() when Tux is not walking, so we'll have to do this ourselves
210   if (deactivated) apply_friction();
211
212   // extend/shrink tux collision rectangle so that we fall through/walk over 1
213   // tile holes
214   if(fabsf(physic.get_velocity_x()) > MAX_WALK_XM) {
215     set_width(34);
216   } else {
217     set_width(31.8);
218   }
219
220   // on downward slopes, adjust vertical velocity to match slope angle
221   if (on_ground()) {
222     if (floor_normal.y != 0) {
223       if ((floor_normal.x * physic.get_velocity_x()) > 0) {
224         // we overdo it a little, just to be on the safe side
225         physic.set_velocity_y(-physic.get_velocity_x() * (floor_normal.x / floor_normal.y) * 2);
226       }
227     }
228   }
229
230   // handle backflipping
231   if (backflipping) {
232     //prevent player from changing direction when backflipping 
233     dir = (backflip_direction == 1) ? LEFT : RIGHT; 
234     if (backflip_timer.started()) physic.set_velocity_x(100 * backflip_direction);
235   }
236
237   // set fall mode...
238   if(on_ground()) {
239     fall_mode = ON_GROUND;
240     last_ground_y = get_pos().y;
241   } else {
242     if(get_pos().y > last_ground_y)
243       fall_mode = FALLING;
244     else if(fall_mode == ON_GROUND)
245       fall_mode = JUMPING;
246   }
247
248   // check if we landed
249   if(on_ground()) { 
250     jumping = false;
251     if (backflipping && (!backflip_timer.started())) {
252       backflipping = false;
253       backflip_direction = 0;
254
255       // if controls are currently deactivated, we take care of standing up ourselves
256       if (deactivated) do_standup();
257     }
258   }
259  
260 #if 0
261   // Do butt jump
262   if (butt_jump && on_ground() && is_big()) {
263     // Add a smoke cloud
264     if (duck) 
265       Sector::current()->add_smoke_cloud(Vector(get_pos().x - 32, get_pos().y));
266     else 
267       Sector::current()->add_smoke_cloud(
268         Vector(get_pos().x - 32, get_pos().y + 32));
269     
270     butt_jump = false;
271     
272     // Break bricks beneath Tux
273     if(Sector::current()->trybreakbrick(
274          Vector(base.x + 1, base.y + base.height), false)
275        || Sector::current()->trybreakbrick(
276          Vector(base.x + base.width - 1, base.y + base.height), false)) {
277       physic.set_velocity_y(-2);
278       butt_jump = true;
279     }
280     
281     // Kill nearby badguys
282     std::vector<GameObject*> gameobjects = Sector::current()->gameobjects;
283     for (std::vector<GameObject*>::iterator i = gameobjects.begin();
284          i != gameobjects.end();
285          i++) {
286       BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
287       if(badguy) {
288         // don't kill when badguys are already dying or in a certain mode
289         if(badguy->dying == DYING_NOT && badguy->mode != BadGuy::BOMB_TICKING &&
290            badguy->mode != BadGuy::BOMB_EXPLODE) {
291           if (fabsf(base.x - badguy->base.x) < 96 &&
292               fabsf(base.y - badguy->base.y) < 64)
293             badguy->kill_me(25);
294         }
295       }
296     }
297   }
298 #endif
299
300   // calculate movement for this frame
301   movement = physic.get_movement(elapsed_time);
302
303   if(grabbed_object != NULL && !dying) {
304     Vector pos = get_pos() + 
305       Vector(dir == LEFT ? -16 : 16, get_bbox().get_height()*0.66666 - 32);
306     grabbed_object->grab(*this, pos, dir);
307   }
308   
309   if(grabbed_object != NULL && dying){
310     grabbed_object->ungrab(*this, dir);
311     grabbed_object = NULL;
312   }
313
314   on_ground_flag = false;
315
316   // when invincible, spawn particles
317   if (invincible_timer.started() &&
318      (invincible_timer.get_timeleft() > TUX_INVINCIBLE_TIME_WARNING
319       || size_t(game_time*20)%2)
320      && !dying)
321   {
322     if (systemRandom.rand(0, 2) == 0) {
323       float px = systemRandom.randf(bbox.p1.x+0, bbox.p2.x-0);
324       float py = systemRandom.randf(bbox.p1.y+0, bbox.p2.y-0);
325       Vector ppos = Vector(px, py);
326       Vector pspeed = Vector(0, 0);
327       Vector paccel = Vector(0, 0);
328       Sector::current()->add_object(new SpriteParticle("images/objects/particles/sparkle.sprite", "small", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
329     }
330   } 
331
332 }
333
334 bool
335 Player::on_ground()
336 {
337   return on_ground_flag;
338 }
339
340 bool
341 Player::is_big()
342 {
343   if(player_status->bonus == NO_BONUS)
344     return false;
345
346   return true;
347 }
348
349 void
350 Player::apply_friction()
351 {
352   if ((on_ground()) && (fabs(physic.get_velocity_x()) < WALK_SPEED)) {
353     physic.set_velocity_x(0);
354     physic.set_acceleration_x(0);
355   } else if(physic.get_velocity_x() < 0) {
356     physic.set_acceleration_x(WALK_ACCELERATION_X * 1.5);
357   } else {
358     physic.set_acceleration_x(WALK_ACCELERATION_X * -1.5);
359   }
360
361 #if 0
362   // if we're on ice slow down acceleration or deceleration
363   if (isice(base.x, base.y + base.height))
364   {
365     /* the acceleration/deceleration rate on ice is inversely proportional to
366      * the current velocity.
367      */
368
369     // increasing 1 will increase acceleration/deceleration rate
370     // decreasing 1 will decrease acceleration/deceleration rate
371     //  must stay above zero, though
372     if (ax != 0) ax *= 1 / fabs(vx);
373   }
374 #endif
375
376 }
377
378 void
379 Player::handle_horizontal_input()
380 {
381   float vx = physic.get_velocity_x();
382   float vy = physic.get_velocity_y();
383   float ax = physic.get_acceleration_x();
384   float ay = physic.get_acceleration_y();
385
386   float dirsign = 0;
387   if(!duck || physic.get_velocity_y() != 0) {
388     if(controller->hold(Controller::LEFT) && !controller->hold(Controller::RIGHT)) {
389       old_dir = dir;
390       dir = LEFT;
391       dirsign = -1;
392     } else if(!controller->hold(Controller::LEFT)
393               && controller->hold(Controller::RIGHT)) {
394       old_dir = dir;
395       dir = RIGHT;
396       dirsign = 1;
397     }
398   }
399
400   if (!controller->hold(Controller::ACTION)) {
401     ax = dirsign * WALK_ACCELERATION_X;
402     // limit speed
403     if(vx >= MAX_WALK_XM && dirsign > 0) {
404       vx = MAX_WALK_XM;
405       ax = 0;
406     } else if(vx <= -MAX_WALK_XM && dirsign < 0) {
407       vx = -MAX_WALK_XM;
408       ax = 0;
409     }
410   } else {
411     ax = dirsign * RUN_ACCELERATION_X;
412     // limit speed
413     if(vx >= MAX_RUN_XM && dirsign > 0) {
414       vx = MAX_RUN_XM;
415       ax = 0;
416     } else if(vx <= -MAX_RUN_XM && dirsign < 0) {
417       vx = -MAX_RUN_XM;
418       ax = 0;
419     }
420   }
421
422   // we can reach WALK_SPEED without any acceleration
423   if(dirsign != 0 && fabs(vx) < WALK_SPEED) {
424     vx = dirsign * WALK_SPEED;
425   }
426
427   // changing directions?
428   if(on_ground() && ((vx < 0 && dirsign >0) || (vx>0 && dirsign<0))) {
429     // let's skid!
430     if(fabs(vx)>SKID_XM && !skidding_timer.started()) {
431       skidding_timer.start(SKID_TIME);
432       sound_manager->play("sounds/skid.wav");
433       // dust some particles
434       Sector::current()->add_object(
435         new Particles(
436           Vector(dir == RIGHT ? get_bbox().p2.x : get_bbox().p1.x, get_bbox().p2.y),
437           dir == RIGHT ? 270+20 : 90-40, dir == RIGHT ? 270+40 : 90-20,
438           Vector(280, -260), Vector(0, 300), 3, Color(.4, .4, .4), 3, .8,
439           LAYER_OBJECTS+1));
440       
441       ax *= 2.5;
442     } else {
443       ax *= 2;
444     }
445   }
446
447   physic.set_velocity(vx, vy);
448   physic.set_acceleration(ax, ay);
449
450   // we get slower when not pressing any keys
451   if(dirsign == 0) {
452     apply_friction();
453   }
454
455 }
456
457 void
458 Player::do_cheer()
459 {
460   do_duck();
461   do_backflip();
462   do_standup();
463 }
464
465 void
466 Player::do_duck() {
467   if (duck) return;
468   if (!is_big()) return;
469
470   if (physic.get_velocity_y() != 0) return;
471   if (!on_ground()) return;
472
473   if (adjust_height(31.8)) {
474     duck = true;
475     unduck_hurt_timer.stop();
476   } else {
477     // FIXME: what now?
478   }
479 }
480
481 void 
482 Player::do_standup() {
483   if (!duck) return;
484   if (!is_big()) return;
485   if (backflipping) return;
486
487   if (adjust_height(63.8)) {
488     duck = false;
489     unduck_hurt_timer.stop();
490   } else {
491     // if timer is not already running, start it.
492     if (unduck_hurt_timer.get_period() == 0) {
493       unduck_hurt_timer.start(UNDUCK_HURT_TIME);
494     } 
495     else if (unduck_hurt_timer.check()) {
496       kill(false);
497     }
498   }
499
500 }
501
502 void
503 Player::do_backflip() {
504   if (!duck) return;
505   if (!on_ground()) return;
506
507   // TODO: we don't have an animation for firetux backflipping, so let's revert to bigtux
508   set_bonus(GROWUP_BONUS, true);
509
510   backflip_direction = (dir == LEFT)?(+1):(-1);
511   backflipping = true;
512   do_jump(-580);
513   sound_manager->play("sounds/flip.wav");
514   backflip_timer.start(0.15);
515 }
516
517 void
518 Player::do_jump(float yspeed) {
519   if (!on_ground()) return;
520
521   physic.set_velocity_y(yspeed);
522   //bbox.move(Vector(0, -1));
523   jumping = true;
524   on_ground_flag = false;
525   can_jump = false;
526
527   // play sound
528   if (is_big()) {
529     sound_manager->play("sounds/bigjump.wav");
530   } else {
531     sound_manager->play("sounds/jump.wav");
532   }
533 }
534
535 void
536 Player::handle_vertical_input()
537 {
538
539   // Press jump key
540   if(controller->pressed(Controller::JUMP) && (can_jump)) {
541     if (duck) { 
542       // when running, only jump a little bit; else do a backflip
543       if (physic.get_velocity_x() != 0) do_jump(-300); else do_backflip();
544     } else {
545       // jump a bit higher if we are running; else do a normal jump
546       if (fabs(physic.get_velocity_x()) > MAX_WALK_XM) do_jump(-580); else do_jump(-520);
547     }
548   } 
549   // Let go of jump key
550   else if(!controller->hold(Controller::JUMP)) { 
551     if (!backflipping && jumping && physic.get_velocity_y() < 0) {
552       jumping = false;
553       physic.set_velocity_y(0);
554     }
555   }
556
557   /* In case the player has pressed Down while in a certain range of air,
558      enable butt jump action */
559   if (controller->hold(Controller::DOWN) && !butt_jump && !duck && is_big() && jumping) {
560     butt_jump = true;
561   }
562   
563   /* When Down is not held anymore, disable butt jump */
564   if(butt_jump && !controller->hold(Controller::DOWN)) butt_jump = false;
565  
566   /** jumping is only allowed if we're about to touch ground soon and if the
567    * button has been up in between the last jump
568    */
569   // FIXME
570 #if 0
571   if ( (issolid(get_pos().x + bbox.get_width() / 2,
572           get_pos().y + bbox.get_height() + 64) ||
573         issolid(get_pos().x + 1, get_pos().y + bbox.get_height() + 64) ||
574         issolid(get_pos().x + bbox.get_width() - 1,
575           get_pos().y + bbox.get_height() + 64))
576        && jumping  == false
577        && can_jump == false
578        && input.jump && !input.old_jump)
579     {
580       can_jump = true;
581     }
582 #endif
583 }
584
585 void
586 Player::handle_input()
587 {
588   if (ghost_mode) {
589     handle_input_ghost();
590     return;
591   }
592
593   if(!controller->hold(Controller::ACTION) && grabbed_object) {
594     // move the grabbed object a bit away from tux
595     Vector pos = get_pos() + 
596         Vector(dir == LEFT ? -bbox.get_width()-1 : bbox.get_width()+1,
597                 bbox.get_height()*0.66666 - 32);
598     Rect dest(pos, pos + Vector(32, 32));
599     if(Sector::current()->is_free_space(dest)) {
600       MovingObject* moving_object = dynamic_cast<MovingObject*> (grabbed_object);
601       if(moving_object) {
602         moving_object->set_pos(pos);
603       } else {
604         log_debug << "Non MovingObjetc grabbed?!?" << std::endl;
605       }
606       grabbed_object->ungrab(*this, dir);
607       grabbed_object = NULL;
608     }
609   }
610  
611   /* Handle horizontal movement: */
612   if (!backflipping) handle_horizontal_input();
613   
614   /* Jump/jumping? */
615   if (on_ground() && !controller->hold(Controller::JUMP))
616     can_jump = true;
617
618   /* Handle vertical movement: */
619   handle_vertical_input();
620
621   /* Shoot! */
622   if (controller->pressed(Controller::ACTION) && player_status->bonus == FIRE_BONUS) {
623     if(Sector::current()->add_bullet(
624          get_pos() + ((dir == LEFT)? Vector(0, bbox.get_height()/2) 
625                       : Vector(32, bbox.get_height()/2)),
626          physic.get_velocity_x(), dir))
627       shooting_timer.start(SHOOTING_TIME);
628   }
629   
630   /* Duck or Standup! */
631   if (controller->hold(Controller::DOWN)) do_duck(); else do_standup();
632
633 }
634
635 void
636 Player::handle_input_ghost()
637 {
638   float vx = 0;
639   float vy = 0;
640   if (controller->hold(Controller::LEFT)) { 
641     dir = LEFT; 
642     vx -= MAX_RUN_XM * 2; 
643   }
644   if (controller->hold(Controller::RIGHT)) { 
645     dir = RIGHT; 
646     vx += MAX_RUN_XM * 2; 
647   }
648   if ((controller->hold(Controller::UP)) || (controller->hold(Controller::JUMP))) {
649     vy -= MAX_RUN_XM * 2;
650   }
651   if (controller->hold(Controller::DOWN)) {
652     vy += MAX_RUN_XM * 2;
653   }
654   if (controller->hold(Controller::ACTION)) {
655     set_ghost_mode(false);
656   }
657   physic.set_velocity(vx, vy);
658   physic.set_acceleration(0, 0);
659 }
660
661 void
662 Player::add_coins(int count)
663 {
664   player_status->add_coins(count);
665 }
666
667 void
668 Player::add_bonus(const std::string& bonustype)
669 {
670   if(bonustype == "grow") {
671     add_bonus(GROWUP_BONUS);
672   } else if(bonustype == "fireflower") {
673     add_bonus(FIRE_BONUS);
674   } else if(bonustype == "iceflower") {
675     add_bonus(ICE_BONUS);
676   } else if(bonustype == "none") {
677     add_bonus(NO_BONUS);
678   } else {
679     std::ostringstream msg;
680     msg << "Unknown bonus type "  << bonustype;
681     throw std::runtime_error(msg.str());
682   }
683 }
684
685 void
686 Player::add_bonus(BonusType type, bool animate)
687 {
688   // always ignore NO_BONUS
689   if (type == NO_BONUS) {
690     return;
691   }
692
693   // ignore GROWUP_BONUS if we're already big
694   if (type == GROWUP_BONUS) {
695     if (player_status->bonus == GROWUP_BONUS) return; 
696     if (player_status->bonus == FIRE_BONUS) return;
697     if (player_status->bonus == ICE_BONUS) return;
698   }
699
700   set_bonus(type, animate);
701 }
702
703 void
704 Player::set_bonus(BonusType type, bool animate)
705 {
706   if(player_status->bonus == NO_BONUS) {
707     if (!adjust_height(62.8)) return;
708     if(animate)
709       growing_timer.start(GROWING_TIME);
710   }
711
712   if ((type == NO_BONUS) || (type == GROWUP_BONUS)) {
713     if ((player_status->bonus == FIRE_BONUS) && (animate)) {
714       // visually lose helmet
715       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
716       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
717       Vector paccel = Vector(0, 1000);
718       std::string action = (dir==LEFT)?"left":"right";
719       Sector::current()->add_object(new SpriteParticle("images/objects/particles/firetux-helmet.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
720     }
721     player_status->max_fire_bullets = 0;
722     player_status->max_ice_bullets = 0;
723   }
724   if (type == FIRE_BONUS) player_status->max_fire_bullets++;
725   if (type == ICE_BONUS) player_status->max_ice_bullets++;
726
727   player_status->bonus = type;
728 }
729
730 void
731 Player::set_visible(bool visible)
732 {
733   this->visible = visible;
734 }
735
736 bool
737 Player::get_visible()
738 {
739   return visible;
740 }
741
742 void
743 Player::kick()
744 {
745   kick_timer.start(KICK_TIME);
746 }
747
748 void
749 Player::draw(DrawingContext& context)
750 {
751   if(!visible)
752     return;
753
754   TuxBodyParts* tux_body;
755           
756   if (player_status->bonus == GROWUP_BONUS)
757     tux_body = big_tux;
758   else if (player_status->bonus == FIRE_BONUS)
759     tux_body = fire_tux;
760   else if (player_status->bonus == ICE_BONUS)
761     tux_body = ice_tux;
762   else
763     tux_body = small_tux;
764
765   int layer = LAYER_OBJECTS + 1;
766
767   /* Set Tux sprite action */
768   if (backflipping)
769     {
770     if(dir == LEFT)
771       tux_body->set_action("backflip-left");
772     else // dir == RIGHT
773       tux_body->set_action("backflip-right");
774     }
775   else if (duck && is_big())
776     {
777     if(dir == LEFT)
778       tux_body->set_action("duck-left");
779     else // dir == RIGHT
780       tux_body->set_action("duck-right");
781     }
782   else if (skidding_timer.started() && !skidding_timer.check())
783     {
784     if(dir == LEFT)
785       tux_body->set_action("skid-left");
786     else // dir == RIGHT
787       tux_body->set_action("skid-right");
788     }
789   else if (kick_timer.started() && !kick_timer.check())
790     {
791     if(dir == LEFT)
792       tux_body->set_action("kick-left");
793     else // dir == RIGHT
794       tux_body->set_action("kick-right");
795     }
796   else if (butt_jump && is_big())
797     {
798     if(dir == LEFT)
799       tux_body->set_action("buttjump-left");
800     else // dir == RIGHT
801       tux_body->set_action("buttjump-right");
802     }
803   else if (!on_ground())
804     {
805     if(dir == LEFT)
806       tux_body->set_action("jump-left");
807     else // dir == RIGHT
808       tux_body->set_action("jump-right");
809     }
810   else
811     {
812     if (fabsf(physic.get_velocity_x()) < 1.0f) // standing
813       {
814       if(dir == LEFT)
815         tux_body->set_action("stand-left");
816       else // dir == RIGHT
817         tux_body->set_action("stand-right");
818       }
819     else // moving
820       {
821       if(dir == LEFT)
822         tux_body->set_action("walk-left");
823       else // dir == RIGHT
824         tux_body->set_action("walk-right");
825       }
826     }
827
828   if(idle_timer.check())
829     {
830     if(is_big())
831       {
832       if(dir == LEFT)
833         tux_body->head->set_action("idle-left", 1);
834       else // dir == RIGHT
835         tux_body->head->set_action("idle-right", 1);
836       }
837
838     }
839
840   // Tux is holding something
841   if ((grabbed_object != 0 && physic.get_velocity_y() == 0) ||
842       (shooting_timer.get_timeleft() > 0 && !shooting_timer.check()))
843     {
844     if (duck)
845       {
846       if(dir == LEFT)
847         tux_body->arms->set_action("duck+grab-left");
848       else // dir == RIGHT
849         tux_body->arms->set_action("duck+grab-right");
850       }
851     else
852       {
853       if(dir == LEFT)
854         tux_body->arms->set_action("grab-left");
855       else // dir == RIGHT
856         tux_body->arms->set_action("grab-right");
857       }
858     }
859
860   /* Draw Tux */
861   if(dying) {
862     smalltux_gameover->draw(context, get_pos(), LAYER_FLOATINGOBJECTS + 1);
863   } 
864   else if ((growing_timer.get_timeleft() > 0) && (!duck)) {
865       if (dir == RIGHT) {
866         context.draw_surface(growingtux_right[int((growing_timer.get_timegone() *
867                  GROWING_FRAMES) / GROWING_TIME)], get_pos(), layer);
868       } else {
869         context.draw_surface(growingtux_left[int((growing_timer.get_timegone() *
870                 GROWING_FRAMES) / GROWING_TIME)], get_pos(), layer);
871       }
872     }
873   else if (safe_timer.started() && size_t(game_time*40)%2)
874     ;  // don't draw Tux
875   else
876     tux_body->draw(context, get_pos(), layer);
877
878 }
879
880 void
881 Player::collision_tile(uint32_t tile_attributes)
882 {
883   if(tile_attributes & Tile::HURTS)
884     kill(false);
885 }
886
887 HitResponse
888 Player::collision(GameObject& other, const CollisionHit& hit)
889 {
890   Bullet* bullet = dynamic_cast<Bullet*> (&other);
891   if(bullet) {
892     return FORCE_MOVE;
893   }
894
895   if(other.get_flags() & FLAG_PORTABLE) {
896     Portable* portable = dynamic_cast<Portable*> (&other);
897     assert(portable != NULL);
898     if(portable && grabbed_object == NULL
899         && controller->hold(Controller::ACTION)
900         && fabsf(hit.normal.x) > .9) {
901       grabbed_object = portable;
902       grabbed_object->grab(*this, get_pos(), dir);
903       return CONTINUE;
904     }
905   }
906  
907   if(other.get_flags() & FLAG_SOLID) {
908     /*
909     printf("Col %p: HN: %3.1f %3.1f D %.1f P: %3.1f %3.1f M: %3.1f %3.1f\n",
910         &other,
911         hit.normal.x, hit.normal.y, hit.depth,
912         get_pos().x, get_pos().y,
913         movement.x, movement.y);
914     */
915     
916     if(hit.normal.y < 0) { // landed on floor?
917       if(physic.get_velocity_y() > 0)
918         physic.set_velocity_y(0);
919
920       on_ground_flag = true;
921
922       // remember normal of this tile
923       if (hit.normal.y > -0.9) {
924         floor_normal.x = hit.normal.x;
925         floor_normal.y = hit.normal.y;
926       } else {
927         // slowly adjust to unisolid tiles. 
928         // Necessary because our bounding box sometimes reaches through slopes and thus hits unisolid tiles
929         floor_normal.x = (floor_normal.x * 0.9) + (hit.normal.x * 0.1);
930         floor_normal.y = (floor_normal.y * 0.9) + (hit.normal.y * 0.1);
931       }
932
933       // hack platforms so that we stand normally on them when going down...
934       Platform* platform = dynamic_cast<Platform*> (&other);
935       if(platform != NULL) {
936         if(platform->get_speed().y > 0)
937           physic.set_velocity_y(platform->get_speed().y);
938         //physic.set_velocity_x(platform->get_speed().x);
939       }
940     } else if(hit.normal.y > 0) { // bumped against the roof
941       physic.set_velocity_y(-.1);
942
943       // hack platform so that we are not glued to it from below
944       Platform* platform = dynamic_cast<Platform*> (&other);
945       if(platform != NULL) {
946         physic.set_velocity_y(platform->get_speed().y);
947       }      
948     }
949     
950     if(fabsf(hit.normal.x) > .9) { // hit on the side?
951       physic.set_velocity_x(0);
952     }
953
954     MovingObject* omov = dynamic_cast<MovingObject*> (&other);
955     if(omov != NULL) {
956       Vector mov = movement - omov->get_movement();
957       /*
958       printf("W %p - HITN: %3.1f %3.1f D:%3.1f TM: %3.1f %3.1f TD: %3.1f %3.1f PM: %3.2f %3.1f\n",
959           omov,
960           hit.normal.x, hit.normal.y,
961           hit.depth,
962           movement.x, movement.y,
963           dest.p1.x, dest.p1.y,
964           omov->get_movement().x, omov->get_movement().y);
965       */
966     }
967     
968     return CONTINUE;
969   }
970
971 #ifdef DEBUG
972   assert(dynamic_cast<MovingObject*> (&other) != NULL);
973 #endif
974   MovingObject* moving_object = static_cast<MovingObject*> (&other); 
975   if(moving_object->get_group() == COLGROUP_TOUCHABLE) {
976     TriggerBase* trigger = dynamic_cast<TriggerBase*> (&other);
977     if(trigger) {
978       if(controller->pressed(Controller::UP))
979         trigger->event(*this, TriggerBase::EVENT_ACTIVATE);
980     }
981
982     return FORCE_MOVE;
983   }
984
985   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
986   if(badguy != NULL) {
987     if(safe_timer.started() || invincible_timer.started())
988       return FORCE_MOVE;
989
990     return CONTINUE;
991   }
992
993   return FORCE_MOVE;
994 }
995
996 void
997 Player::make_invincible()
998 {
999   sound_manager->play("sounds/invincible.wav");
1000   invincible_timer.start(TUX_INVINCIBLE_TIME);
1001   Sector::current()->play_music(HERRING_MUSIC);               
1002 }
1003
1004 /* Kill Player! */
1005 void
1006 Player::kill(bool completely)
1007 {
1008   if(dying || deactivated)
1009     return;
1010
1011   if(!completely && safe_timer.started() || invincible_timer.started())
1012     return;                          
1013   
1014   sound_manager->play("sounds/hurt.wav");
1015
1016   physic.set_velocity_x(0);
1017
1018   if(!completely && is_big()) {
1019     if(player_status->bonus == FIRE_BONUS
1020         || player_status->bonus == ICE_BONUS) {
1021       safe_timer.start(TUX_SAFE_TIME);
1022       set_bonus(GROWUP_BONUS, true);
1023     } else {
1024       //growing_timer.start(GROWING_TIME);
1025       safe_timer.start(TUX_SAFE_TIME /* + GROWING_TIME */);
1026       adjust_height(30.8);
1027       duck = false;
1028       set_bonus(NO_BONUS, true);
1029     }
1030   } else {
1031     for (int i = 0; (i < 5) && (i < player_status->coins); i++)
1032     {
1033       // the numbers: starting x, starting y, velocity y
1034       Sector::current()->add_object(new FallingCoin(get_pos() + 
1035             Vector(systemRandom.rand(5), systemRandom.rand(-32,18)), 
1036             systemRandom.rand(-100,100)));
1037     }
1038     physic.enable_gravity(true);
1039     physic.set_acceleration(0, 0);
1040     physic.set_velocity(0, -700);
1041     player_status->coins -= 25;
1042     set_bonus(NO_BONUS, true);
1043     dying = true;
1044     dying_timer.start(3.0);
1045     set_group(COLGROUP_DISABLED);
1046
1047     DisplayEffect* effect = new DisplayEffect();
1048     effect->fade_out(3.0);
1049     Sector::current()->add_object(effect);
1050     sound_manager->stop_music(3.0);
1051   }
1052 }
1053
1054 void
1055 Player::move(const Vector& vector)
1056 {
1057   set_pos(vector);
1058
1059   // TODO: do we need the following? Seems irrelevant to moving the player
1060   if(is_big())
1061     set_size(31.8, 63.8);
1062   else
1063     set_size(31.8, 31.8);
1064   duck = false;
1065   last_ground_y = vector.y;
1066
1067   physic.reset();
1068 }
1069
1070 void
1071 Player::check_bounds(Camera* camera)
1072 {
1073   /* Keep tux in bounds: */
1074   if (get_pos().x < 0) {
1075     // Lock Tux to the size of the level, so that he doesn't fall of
1076     // on the left side
1077     set_pos(Vector(0, get_pos().y));
1078   }
1079
1080   /* Keep in-bounds, vertically: */
1081   if (get_pos().y > Sector::current()->solids->get_height() * 32) {
1082     kill(true);
1083     return;
1084   }
1085
1086   bool adjust = false;
1087   // can happen if back scrolling is disabled
1088   if(get_pos().x < camera->get_translation().x) {
1089     set_pos(Vector(camera->get_translation().x, get_pos().y));
1090     adjust = true;
1091   }
1092   if(get_pos().x >= camera->get_translation().x + SCREEN_WIDTH - bbox.get_width())
1093   {
1094     set_pos(Vector(
1095           camera->get_translation().x + SCREEN_WIDTH - bbox.get_width(),
1096           get_pos().y));
1097     adjust = true;
1098   }
1099
1100   if(adjust) {
1101     // FIXME
1102 #if 0
1103     // squished now?
1104     if(collision_object_map(bbox)) {
1105       kill(KILL);
1106       return;
1107     }
1108 #endif
1109   }
1110 }
1111
1112 void
1113 Player::add_velocity(const Vector& velocity)
1114 {
1115   physic.set_velocity(physic.get_velocity() + velocity);
1116 }
1117
1118 void
1119 Player::add_velocity(const Vector& velocity, const Vector& end_speed)
1120 {
1121   if (end_speed.x > 0) physic.set_velocity_x(std::min(physic.get_velocity_x() + velocity.x, end_speed.x));
1122   if (end_speed.x < 0) physic.set_velocity_x(std::max(physic.get_velocity_x() + velocity.x, end_speed.x));
1123   if (end_speed.y > 0) physic.set_velocity_y(std::min(physic.get_velocity_y() + velocity.y, end_speed.y));
1124   if (end_speed.y < 0) physic.set_velocity_y(std::max(physic.get_velocity_y() + velocity.y, end_speed.y));
1125 }
1126
1127 void
1128 Player::bounce(BadGuy& )
1129 {
1130   if(controller->hold(Controller::JUMP))
1131     physic.set_velocity_y(-520);
1132   else
1133     physic.set_velocity_y(-300);
1134 }
1135
1136 //Scripting Functions Below
1137
1138 void
1139 Player::deactivate()
1140 {
1141   if (deactivated) return;
1142   deactivated = true;
1143   physic.set_velocity_x(0);
1144   physic.set_velocity_y(0);
1145   physic.set_acceleration_x(0);
1146   physic.set_acceleration_y(0);
1147 }
1148
1149 void
1150 Player::activate()
1151 {
1152   if (!deactivated) return;
1153   deactivated = false;
1154 }
1155
1156 void Player::walk(float speed)
1157 {
1158   physic.set_velocity_x(speed);
1159 }
1160
1161 void
1162 Player::set_ghost_mode(bool enable)
1163 {
1164   if (ghost_mode == enable) return;
1165   if (enable) {
1166     ghost_mode = true;
1167     set_group(COLGROUP_DISABLED);
1168     physic.enable_gravity(false);
1169     log_debug << "You feel lightheaded. Use movement controls to float around, press ACTION to scare badguys." << std::endl;
1170   } else {
1171     ghost_mode = false;
1172     set_group(COLGROUP_MOVING);
1173     physic.enable_gravity(true);
1174     log_debug << "You feel solid again." << std::endl;
1175   }
1176 }
1177