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