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