Add some more sound_manager->preloads into object constructors
[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
317 bool
318 Player::on_ground()
319 {
320   return on_ground_flag;
321 }
322
323 bool
324 Player::is_big()
325 {
326   if(player_status->bonus == NO_BONUS)
327     return false;
328
329   return true;
330 }
331
332 void
333 Player::apply_friction()
334 {
335   if ((on_ground()) && (fabs(physic.get_velocity_x()) < WALK_SPEED)) {
336     physic.set_velocity_x(0);
337     physic.set_acceleration_x(0);
338   } else if(physic.get_velocity_x() < 0) {
339     physic.set_acceleration_x(WALK_ACCELERATION_X * 1.5);
340   } else {
341     physic.set_acceleration_x(WALK_ACCELERATION_X * -1.5);
342   }
343
344 #if 0
345   // if we're on ice slow down acceleration or deceleration
346   if (isice(base.x, base.y + base.height))
347   {
348     /* the acceleration/deceleration rate on ice is inversely proportional to
349      * the current velocity.
350      */
351
352     // increasing 1 will increase acceleration/deceleration rate
353     // decreasing 1 will decrease acceleration/deceleration rate
354     //  must stay above zero, though
355     if (ax != 0) ax *= 1 / fabs(vx);
356   }
357 #endif
358
359 }
360
361 void
362 Player::handle_horizontal_input()
363 {
364   float vx = physic.get_velocity_x();
365   float vy = physic.get_velocity_y();
366   float ax = physic.get_acceleration_x();
367   float ay = physic.get_acceleration_y();
368
369   float dirsign = 0;
370   if(!duck || physic.get_velocity_y() != 0) {
371     if(controller->hold(Controller::LEFT) && !controller->hold(Controller::RIGHT)) {
372       old_dir = dir;
373       dir = LEFT;
374       dirsign = -1;
375     } else if(!controller->hold(Controller::LEFT)
376               && controller->hold(Controller::RIGHT)) {
377       old_dir = dir;
378       dir = RIGHT;
379       dirsign = 1;
380     }
381   }
382
383   if (!controller->hold(Controller::ACTION)) {
384     ax = dirsign * WALK_ACCELERATION_X;
385     // limit speed
386     if(vx >= MAX_WALK_XM && dirsign > 0) {
387       vx = MAX_WALK_XM;
388       ax = 0;
389     } else if(vx <= -MAX_WALK_XM && dirsign < 0) {
390       vx = -MAX_WALK_XM;
391       ax = 0;
392     }
393   } else {
394     ax = dirsign * RUN_ACCELERATION_X;
395     // limit speed
396     if(vx >= MAX_RUN_XM && dirsign > 0) {
397       vx = MAX_RUN_XM;
398       ax = 0;
399     } else if(vx <= -MAX_RUN_XM && dirsign < 0) {
400       vx = -MAX_RUN_XM;
401       ax = 0;
402     }
403   }
404
405   // we can reach WALK_SPEED without any acceleration
406   if(dirsign != 0 && fabs(vx) < WALK_SPEED) {
407     vx = dirsign * WALK_SPEED;
408   }
409
410   // changing directions?
411   if(on_ground() && ((vx < 0 && dirsign >0) || (vx>0 && dirsign<0))) {
412     // let's skid!
413     if(fabs(vx)>SKID_XM && !skidding_timer.started()) {
414       skidding_timer.start(SKID_TIME);
415       sound_manager->play("sounds/skid.wav");
416       // dust some particles
417       Sector::current()->add_object(
418         new Particles(
419           Vector(dir == RIGHT ? get_bbox().p2.x : get_bbox().p1.x, get_bbox().p2.y),
420           dir == RIGHT ? 270+20 : 90-40, dir == RIGHT ? 270+40 : 90-20,
421           Vector(280, -260), Vector(0, 300), 3, Color(.4, .4, .4), 3, .8,
422           LAYER_OBJECTS+1));
423       
424       ax *= 2.5;
425     } else {
426       ax *= 2;
427     }
428   }
429
430   physic.set_velocity(vx, vy);
431   physic.set_acceleration(ax, ay);
432
433   // we get slower when not pressing any keys
434   if(dirsign == 0) {
435     apply_friction();
436   }
437
438 }
439
440 void
441 Player::do_cheer()
442 {
443   do_duck();
444   do_backflip();
445   do_standup();
446 }
447
448 void
449 Player::do_duck() {
450   if (duck) return;
451   if (!is_big()) return;
452
453   if (physic.get_velocity_y() != 0) return;
454   if (!on_ground()) return;
455
456   if (adjust_height(31.8)) {
457     duck = true;
458     unduck_hurt_timer.stop();
459   } else {
460     // FIXME: what now?
461   }
462 }
463
464 void 
465 Player::do_standup() {
466   if (!duck) return;
467   if (!is_big()) return;
468   if (backflipping) return;
469
470   if (adjust_height(63.8)) {
471     duck = false;
472     unduck_hurt_timer.stop();
473   } else {
474     // if timer is not already running, start it.
475     if (unduck_hurt_timer.get_period() == 0) {
476       unduck_hurt_timer.start(UNDUCK_HURT_TIME);
477     } 
478     else if (unduck_hurt_timer.check()) {
479       kill(false);
480     }
481   }
482
483 }
484
485 void
486 Player::do_backflip() {
487   if (!duck) return;
488   if (!on_ground()) return;
489
490   // TODO: we don't have an animation for firetux backflipping, so let's revert to bigtux
491   set_bonus(GROWUP_BONUS, true);
492
493   backflip_direction = (dir == LEFT)?(+1):(-1);
494   backflipping = true;
495   do_jump(-580);
496   sound_manager->play("sounds/flip.wav");
497   backflip_timer.start(0.15);
498 }
499
500 void
501 Player::do_jump(float yspeed) {
502   if (!on_ground()) return;
503
504   physic.set_velocity_y(yspeed);
505   //bbox.move(Vector(0, -1));
506   jumping = true;
507   on_ground_flag = false;
508   can_jump = false;
509
510   // play sound
511   if (is_big()) {
512     sound_manager->play("sounds/bigjump.wav");
513   } else {
514     sound_manager->play("sounds/jump.wav");
515   }
516 }
517
518 void
519 Player::handle_vertical_input()
520 {
521
522   // Press jump key
523   if(controller->pressed(Controller::JUMP) && (can_jump)) {
524     if (duck) { 
525       // when running, only jump a little bit; else do a backflip
526       if (physic.get_velocity_x() != 0) do_jump(-300); else do_backflip();
527     } else {
528       // jump a bit higher if we are running; else do a normal jump
529       if (fabs(physic.get_velocity_x()) > MAX_WALK_XM) do_jump(-580); else do_jump(-520);
530     }
531   } 
532   // Let go of jump key
533   else if(!controller->hold(Controller::JUMP)) { 
534     if (!backflipping && jumping && physic.get_velocity_y() < 0) {
535       jumping = false;
536       physic.set_velocity_y(0);
537     }
538   }
539
540   /* In case the player has pressed Down while in a certain range of air,
541      enable butt jump action */
542   if (controller->hold(Controller::DOWN) && !butt_jump && !duck && is_big() && jumping) {
543     butt_jump = true;
544   }
545   
546   /* When Down is not held anymore, disable butt jump */
547   if(butt_jump && !controller->hold(Controller::DOWN)) butt_jump = false;
548  
549   /** jumping is only allowed if we're about to touch ground soon and if the
550    * button has been up in between the last jump
551    */
552   // FIXME
553 #if 0
554   if ( (issolid(get_pos().x + bbox.get_width() / 2,
555           get_pos().y + bbox.get_height() + 64) ||
556         issolid(get_pos().x + 1, get_pos().y + bbox.get_height() + 64) ||
557         issolid(get_pos().x + bbox.get_width() - 1,
558           get_pos().y + bbox.get_height() + 64))
559        && jumping  == false
560        && can_jump == false
561        && input.jump && !input.old_jump)
562     {
563       can_jump = true;
564     }
565 #endif
566 }
567
568 void
569 Player::handle_input()
570 {
571   if (ghost_mode) {
572     handle_input_ghost();
573     return;
574   }
575
576   if(!controller->hold(Controller::ACTION) && grabbed_object) {
577     // move the grabbed object a bit away from tux
578     Vector pos = get_pos() + 
579         Vector(dir == LEFT ? -bbox.get_width()-1 : bbox.get_width()+1,
580                 bbox.get_height()*0.66666 - 32);
581     Rect dest(pos, pos + Vector(32, 32));
582     if(Sector::current()->is_free_space(dest)) {
583       MovingObject* moving_object = dynamic_cast<MovingObject*> (grabbed_object);
584       if(moving_object) {
585         moving_object->set_pos(pos);
586       } else {
587         log_debug << "Non MovingObjetc grabbed?!?" << std::endl;
588       }
589       grabbed_object->ungrab(*this, dir);
590       grabbed_object = NULL;
591     }
592   }
593  
594   /* Handle horizontal movement: */
595   if (!backflipping) handle_horizontal_input();
596   
597   /* Jump/jumping? */
598   if (on_ground() && !controller->hold(Controller::JUMP))
599     can_jump = true;
600
601   /* Handle vertical movement: */
602   handle_vertical_input();
603
604   /* Shoot! */
605   if (controller->pressed(Controller::ACTION) && player_status->bonus == FIRE_BONUS) {
606     if(Sector::current()->add_bullet(
607          get_pos() + ((dir == LEFT)? Vector(0, bbox.get_height()/2) 
608                       : Vector(32, bbox.get_height()/2)),
609          physic.get_velocity_x(), dir))
610       shooting_timer.start(SHOOTING_TIME);
611   }
612   
613   /* Duck or Standup! */
614   if (controller->hold(Controller::DOWN)) do_duck(); else do_standup();
615
616 }
617
618 void
619 Player::handle_input_ghost()
620 {
621   float vx = 0;
622   float vy = 0;
623   if (controller->hold(Controller::LEFT)) { 
624     dir = LEFT; 
625     vx -= MAX_RUN_XM * 2; 
626   }
627   if (controller->hold(Controller::RIGHT)) { 
628     dir = RIGHT; 
629     vx += MAX_RUN_XM * 2; 
630   }
631   if ((controller->hold(Controller::UP)) || (controller->hold(Controller::JUMP))) {
632     vy -= MAX_RUN_XM * 2;
633   }
634   if (controller->hold(Controller::DOWN)) {
635     vy += MAX_RUN_XM * 2;
636   }
637   if (controller->hold(Controller::ACTION)) {
638     set_ghost_mode(false);
639   }
640   physic.set_velocity(vx, vy);
641   physic.set_acceleration(0, 0);
642 }
643
644 void
645 Player::add_coins(int count)
646 {
647   player_status->add_coins(count);
648 }
649
650 void
651 Player::add_bonus(const std::string& bonustype)
652 {
653   if(bonustype == "grow") {
654     add_bonus(GROWUP_BONUS);
655   } else if(bonustype == "fireflower") {
656     add_bonus(FIRE_BONUS);
657   } else if(bonustype == "iceflower") {
658     add_bonus(ICE_BONUS);
659   } else if(bonustype == "none") {
660     add_bonus(NO_BONUS);
661   } else {
662     std::ostringstream msg;
663     msg << "Unknown bonus type "  << bonustype;
664     throw std::runtime_error(msg.str());
665   }
666 }
667
668 void
669 Player::add_bonus(BonusType type, bool animate)
670 {
671   // always ignore NO_BONUS
672   if (type == NO_BONUS) {
673     return;
674   }
675
676   // ignore GROWUP_BONUS if we're already big
677   if (type == GROWUP_BONUS) {
678     if (player_status->bonus == GROWUP_BONUS) return; 
679     if (player_status->bonus == FIRE_BONUS) return;
680     if (player_status->bonus == ICE_BONUS) return;
681   }
682
683   set_bonus(type, animate);
684 }
685
686 void
687 Player::set_bonus(BonusType type, bool animate)
688 {
689   if(player_status->bonus == NO_BONUS) {
690     if (!adjust_height(62.8)) return;
691     if(animate)
692       growing_timer.start(GROWING_TIME);
693   }
694
695   if ((type == NO_BONUS) || (type == GROWUP_BONUS)) {
696     if ((player_status->bonus == FIRE_BONUS) && (animate)) {
697       // visually lose helmet
698       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
699       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
700       Vector paccel = Vector(0, 1000);
701       std::string action = (dir==LEFT)?"left":"right";
702       Sector::current()->add_object(new SpriteParticle("images/objects/particles/firetux-helmet.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
703     }
704     player_status->max_fire_bullets = 0;
705     player_status->max_ice_bullets = 0;
706   }
707   if (type == FIRE_BONUS) player_status->max_fire_bullets++;
708   if (type == ICE_BONUS) player_status->max_ice_bullets++;
709
710   player_status->bonus = type;
711 }
712
713 void
714 Player::set_visible(bool visible)
715 {
716   this->visible = visible;
717 }
718
719 bool
720 Player::get_visible()
721 {
722   return visible;
723 }
724
725 void
726 Player::kick()
727 {
728   kick_timer.start(KICK_TIME);
729 }
730
731 void
732 Player::draw(DrawingContext& context)
733 {
734   if(!visible)
735     return;
736
737   TuxBodyParts* tux_body;
738           
739   if (player_status->bonus == GROWUP_BONUS)
740     tux_body = big_tux;
741   else if (player_status->bonus == FIRE_BONUS)
742     tux_body = fire_tux;
743   else if (player_status->bonus == ICE_BONUS)
744     tux_body = ice_tux;
745   else
746     tux_body = small_tux;
747
748   int layer = LAYER_OBJECTS + 1;
749
750   /* Set Tux sprite action */
751   if (backflipping)
752     {
753     if(dir == LEFT)
754       tux_body->set_action("backflip-left");
755     else // dir == RIGHT
756       tux_body->set_action("backflip-right");
757     }
758   else if (duck && is_big())
759     {
760     if(dir == LEFT)
761       tux_body->set_action("duck-left");
762     else // dir == RIGHT
763       tux_body->set_action("duck-right");
764     }
765   else if (skidding_timer.started() && !skidding_timer.check())
766     {
767     if(dir == LEFT)
768       tux_body->set_action("skid-left");
769     else // dir == RIGHT
770       tux_body->set_action("skid-right");
771     }
772   else if (kick_timer.started() && !kick_timer.check())
773     {
774     if(dir == LEFT)
775       tux_body->set_action("kick-left");
776     else // dir == RIGHT
777       tux_body->set_action("kick-right");
778     }
779   else if (butt_jump && is_big())
780     {
781     if(dir == LEFT)
782       tux_body->set_action("buttjump-left");
783     else // dir == RIGHT
784       tux_body->set_action("buttjump-right");
785     }
786   else if (!on_ground())
787     {
788     if(dir == LEFT)
789       tux_body->set_action("jump-left");
790     else // dir == RIGHT
791       tux_body->set_action("jump-right");
792     }
793   else
794     {
795     if (fabsf(physic.get_velocity_x()) < 1.0f) // standing
796       {
797       if(dir == LEFT)
798         tux_body->set_action("stand-left");
799       else // dir == RIGHT
800         tux_body->set_action("stand-right");
801       }
802     else // moving
803       {
804       if(dir == LEFT)
805         tux_body->set_action("walk-left");
806       else // dir == RIGHT
807         tux_body->set_action("walk-right");
808       }
809     }
810
811   if(idle_timer.check())
812     {
813     if(is_big())
814       {
815       if(dir == LEFT)
816         tux_body->head->set_action("idle-left", 1);
817       else // dir == RIGHT
818         tux_body->head->set_action("idle-right", 1);
819       }
820
821     }
822
823   // Tux is holding something
824   if ((grabbed_object != 0 && physic.get_velocity_y() == 0) ||
825       (shooting_timer.get_timeleft() > 0 && !shooting_timer.check()))
826     {
827     if (duck)
828       {
829       if(dir == LEFT)
830         tux_body->arms->set_action("duck+grab-left");
831       else // dir == RIGHT
832         tux_body->arms->set_action("duck+grab-right");
833       }
834     else
835       {
836       if(dir == LEFT)
837         tux_body->arms->set_action("grab-left");
838       else // dir == RIGHT
839         tux_body->arms->set_action("grab-right");
840       }
841     }
842
843   /* Draw Tux */
844   if(dying) {
845     smalltux_gameover->draw(context, get_pos(), LAYER_FLOATINGOBJECTS + 1);
846   } 
847   else if ((growing_timer.get_timeleft() > 0) && (!duck)) {
848       if (dir == RIGHT) {
849         context.draw_surface(growingtux_right[int((growing_timer.get_timegone() *
850                  GROWING_FRAMES) / GROWING_TIME)], get_pos(), layer);
851       } else {
852         context.draw_surface(growingtux_left[int((growing_timer.get_timegone() *
853                 GROWING_FRAMES) / GROWING_TIME)], get_pos(), layer);
854       }
855     }
856   else if (safe_timer.started() && size_t(game_time*40)%2)
857     ;  // don't draw Tux
858   else
859     tux_body->draw(context, get_pos(), layer);
860
861   // Draw blinking star overlay
862   if (invincible_timer.started() &&
863      (invincible_timer.get_timeleft() > TUX_INVINCIBLE_TIME_WARNING
864       || size_t(game_time*20)%2)
865      && !dying)
866   {
867     if (!is_big() || duck)
868       smalltux_star->draw(context, get_pos(), layer + 5);
869     else
870       bigtux_star->draw(context, get_pos(), layer + 5);
871   } 
872 }
873
874 void
875 Player::collision_tile(uint32_t tile_attributes)
876 {
877   if(tile_attributes & Tile::HURTS)
878     kill(false);
879 }
880
881 HitResponse
882 Player::collision(GameObject& other, const CollisionHit& hit)
883 {
884   Bullet* bullet = dynamic_cast<Bullet*> (&other);
885   if(bullet) {
886     return FORCE_MOVE;
887   }
888
889   if(other.get_flags() & FLAG_PORTABLE) {
890     Portable* portable = dynamic_cast<Portable*> (&other);
891     assert(portable != NULL);
892     if(portable && grabbed_object == NULL
893         && controller->hold(Controller::ACTION)
894         && fabsf(hit.normal.x) > .9) {
895       grabbed_object = portable;
896       grabbed_object->grab(*this, get_pos(), dir);
897       return CONTINUE;
898     }
899   }
900  
901   if(other.get_flags() & FLAG_SOLID) {
902     /*
903     printf("Col %p: HN: %3.1f %3.1f D %.1f P: %3.1f %3.1f M: %3.1f %3.1f\n",
904         &other,
905         hit.normal.x, hit.normal.y, hit.depth,
906         get_pos().x, get_pos().y,
907         movement.x, movement.y);
908     */
909     
910     if(hit.normal.y < 0) { // landed on floor?
911       if(physic.get_velocity_y() > 0)
912         physic.set_velocity_y(0);
913
914       on_ground_flag = true;
915
916       // remember normal of this tile
917       if (hit.normal.y > -0.9) {
918         floor_normal.x = hit.normal.x;
919         floor_normal.y = hit.normal.y;
920       } else {
921         // slowly adjust to unisolid tiles. 
922         // Necessary because our bounding box sometimes reaches through slopes and thus hits unisolid tiles
923         floor_normal.x = (floor_normal.x * 0.9) + (hit.normal.x * 0.1);
924         floor_normal.y = (floor_normal.y * 0.9) + (hit.normal.y * 0.1);
925       }
926
927       // hack platforms so that we stand normally on them when going down...
928       Platform* platform = dynamic_cast<Platform*> (&other);
929       if(platform != NULL) {
930         if(platform->get_speed().y > 0)
931           physic.set_velocity_y(platform->get_speed().y);
932         //physic.set_velocity_x(platform->get_speed().x);
933       }
934     } else if(hit.normal.y > 0) { // bumped against the roof
935       physic.set_velocity_y(-.1);
936
937       // hack platform so that we are not glued to it from below
938       Platform* platform = dynamic_cast<Platform*> (&other);
939       if(platform != NULL) {
940         physic.set_velocity_y(platform->get_speed().y);
941       }      
942     }
943     
944     if(fabsf(hit.normal.x) > .9) { // hit on the side?
945       physic.set_velocity_x(0);
946     }
947
948     MovingObject* omov = dynamic_cast<MovingObject*> (&other);
949     if(omov != NULL) {
950       Vector mov = movement - omov->get_movement();
951       /*
952       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",
953           omov,
954           hit.normal.x, hit.normal.y,
955           hit.depth,
956           movement.x, movement.y,
957           dest.p1.x, dest.p1.y,
958           omov->get_movement().x, omov->get_movement().y);
959       */
960     }
961     
962     return CONTINUE;
963   }
964
965 #ifdef DEBUG
966   assert(dynamic_cast<MovingObject*> (&other) != NULL);
967 #endif
968   MovingObject* moving_object = static_cast<MovingObject*> (&other); 
969   if(moving_object->get_group() == COLGROUP_TOUCHABLE) {
970     TriggerBase* trigger = dynamic_cast<TriggerBase*> (&other);
971     if(trigger) {
972       if(controller->pressed(Controller::UP))
973         trigger->event(*this, TriggerBase::EVENT_ACTIVATE);
974     }
975
976     return FORCE_MOVE;
977   }
978
979   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
980   if(badguy != NULL) {
981     if(safe_timer.started() || invincible_timer.started())
982       return FORCE_MOVE;
983
984     return CONTINUE;
985   }
986
987   return FORCE_MOVE;
988 }
989
990 void
991 Player::make_invincible()
992 {
993   sound_manager->play("sounds/invincible.wav");
994   invincible_timer.start(TUX_INVINCIBLE_TIME);
995   Sector::current()->play_music(HERRING_MUSIC);               
996 }
997
998 /* Kill Player! */
999 void
1000 Player::kill(bool completely)
1001 {
1002   if(dying || deactivated)
1003     return;
1004
1005   if(!completely && safe_timer.started() || invincible_timer.started())
1006     return;                          
1007   
1008   sound_manager->play("sounds/hurt.wav");
1009
1010   physic.set_velocity_x(0);
1011
1012   if(!completely && is_big()) {
1013     if(player_status->bonus == FIRE_BONUS
1014         || player_status->bonus == ICE_BONUS) {
1015       safe_timer.start(TUX_SAFE_TIME);
1016       set_bonus(GROWUP_BONUS, true);
1017     } else {
1018       //growing_timer.start(GROWING_TIME);
1019       safe_timer.start(TUX_SAFE_TIME /* + GROWING_TIME */);
1020       adjust_height(30.8);
1021       duck = false;
1022       set_bonus(NO_BONUS, true);
1023     }
1024   } else {
1025     for (int i = 0; (i < 5) && (i < player_status->coins); i++)
1026     {
1027       // the numbers: starting x, starting y, velocity y
1028       Sector::current()->add_object(new FallingCoin(get_pos() + 
1029             Vector(systemRandom.rand(5), systemRandom.rand(-32,18)), 
1030             systemRandom.rand(-100,100)));
1031     }
1032     physic.enable_gravity(true);
1033     physic.set_acceleration(0, 0);
1034     physic.set_velocity(0, -700);
1035     player_status->coins -= 25;
1036     set_bonus(NO_BONUS, true);
1037     dying = true;
1038     dying_timer.start(3.0);
1039     set_group(COLGROUP_DISABLED);
1040
1041     DisplayEffect* effect = new DisplayEffect();
1042     effect->fade_out(3.0);
1043     Sector::current()->add_object(effect);
1044     sound_manager->stop_music(3.0);
1045   }
1046 }
1047
1048 void
1049 Player::move(const Vector& vector)
1050 {
1051   set_pos(vector);
1052
1053   // TODO: do we need the following? Seems irrelevant to moving the player
1054   if(is_big())
1055     set_size(31.8, 63.8);
1056   else
1057     set_size(31.8, 31.8);
1058   duck = false;
1059   last_ground_y = vector.y;
1060
1061   physic.reset();
1062 }
1063
1064 void
1065 Player::check_bounds(Camera* camera)
1066 {
1067   /* Keep tux in bounds: */
1068   if (get_pos().x < 0) {
1069     // Lock Tux to the size of the level, so that he doesn't fall of
1070     // on the left side
1071     set_pos(Vector(0, get_pos().y));
1072   }
1073
1074   /* Keep in-bounds, vertically: */
1075   if (get_pos().y > Sector::current()->solids->get_height() * 32) {
1076     kill(true);
1077     return;
1078   }
1079
1080   bool adjust = false;
1081   // can happen if back scrolling is disabled
1082   if(get_pos().x < camera->get_translation().x) {
1083     set_pos(Vector(camera->get_translation().x, get_pos().y));
1084     adjust = true;
1085   }
1086   if(get_pos().x >= camera->get_translation().x + SCREEN_WIDTH - bbox.get_width())
1087   {
1088     set_pos(Vector(
1089           camera->get_translation().x + SCREEN_WIDTH - bbox.get_width(),
1090           get_pos().y));
1091     adjust = true;
1092   }
1093
1094   if(adjust) {
1095     // FIXME
1096 #if 0
1097     // squished now?
1098     if(collision_object_map(bbox)) {
1099       kill(KILL);
1100       return;
1101     }
1102 #endif
1103   }
1104 }
1105
1106 void
1107 Player::add_velocity(const Vector& velocity)
1108 {
1109   physic.set_velocity(physic.get_velocity() + velocity);
1110 }
1111
1112 void
1113 Player::add_velocity(const Vector& velocity, const Vector& end_speed)
1114 {
1115   if (end_speed.x > 0) physic.set_velocity_x(std::min(physic.get_velocity_x() + velocity.x, end_speed.x));
1116   if (end_speed.x < 0) physic.set_velocity_x(std::max(physic.get_velocity_x() + velocity.x, end_speed.x));
1117   if (end_speed.y > 0) physic.set_velocity_y(std::min(physic.get_velocity_y() + velocity.y, end_speed.y));
1118   if (end_speed.y < 0) physic.set_velocity_y(std::max(physic.get_velocity_y() + velocity.y, end_speed.y));
1119 }
1120
1121 void
1122 Player::bounce(BadGuy& )
1123 {
1124   if(controller->hold(Controller::JUMP))
1125     physic.set_velocity_y(-520);
1126   else
1127     physic.set_velocity_y(-300);
1128 }
1129
1130 //Scripting Functions Below
1131
1132 void
1133 Player::deactivate()
1134 {
1135   if (deactivated) return;
1136   deactivated = true;
1137   physic.set_velocity_x(0);
1138   physic.set_velocity_y(0);
1139   physic.set_acceleration_x(0);
1140   physic.set_acceleration_y(0);
1141 }
1142
1143 void
1144 Player::activate()
1145 {
1146   if (!deactivated) return;
1147   deactivated = false;
1148 }
1149
1150 void Player::walk(float speed)
1151 {
1152   physic.set_velocity_x(speed);
1153 }
1154
1155 void
1156 Player::set_ghost_mode(bool enable)
1157 {
1158   if (ghost_mode == enable) return;
1159   if (enable) {
1160     ghost_mode = true;
1161     set_group(COLGROUP_DISABLED);
1162     physic.enable_gravity(false);
1163     log_debug << "You feel lightheaded. Use movement controls to float around, press ACTION to scare badguys." << std::endl;
1164   } else {
1165     ghost_mode = false;
1166     set_group(COLGROUP_MOVING);
1167     physic.enable_gravity(true);
1168     log_debug << "You feel solid again." << std::endl;
1169   }
1170 }
1171