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