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