eac5fce2e704fd54fbf837c37355245d6a70d5ae
[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 velocity (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     sprite->set_action_continued((dir == LEFT)?"grow-left":"grow-right");
921     // while growing, do not change action
922     // do_duck() will take care of cancelling growing manually
923     // update() will take care of cancelling when growing completed
924   }
925   else if (climbing) {
926     sprite->set_action(sa_prefix+((dir == LEFT)?"-skid-left":"-skid-right"));
927   }
928   else if (backflipping) {
929     sprite->set_action(sa_prefix+((dir == LEFT)?"-backflip-left":"-backflip-right"));
930   }
931   else if (duck && is_big()) {
932     sprite->set_action(sa_prefix+((dir == LEFT)?"-duck-left":"-duck-right"));
933   }
934   else if (skidding_timer.started() && !skidding_timer.check()) {
935     sprite->set_action(sa_prefix+((dir == LEFT)?"-skid-left":"-skid-right"));
936   }
937   else if (kick_timer.started() && !kick_timer.check()) {
938     sprite->set_action(sa_prefix+((dir == LEFT)?"-kick-left":"-kick-right"));
939   }
940   else if ((wants_buttjump || does_buttjump) && is_big()) {
941     sprite->set_action(sa_prefix+((dir == LEFT)?"-buttjump-left":"-buttjump-right"));
942   }
943   else if (!on_ground()) {
944     sprite->set_action(sa_prefix+((dir == LEFT)?"-jump-left":"-jump-right"));
945   }
946   else {
947     if (fabsf(physic.get_velocity_x()) < 1.0f) {
948 //      if(idle_timer.check()) {
949 //        sprite->set_action(sa_prefix+((dir == LEFT)?"-idle-left":"-idle-right"));
950 //      } else {
951         sprite->set_action(sa_prefix+((dir == LEFT)?"-stand-left":"-stand-right"));
952 //      }
953     }
954     else {
955       sprite->set_action(sa_prefix+((dir == LEFT)?"-walk-left":"-walk-right"));
956     }
957   }
958
959
960 /*
961   // Tux is holding something
962   if ((grabbed_object != 0 && physic.get_velocity_y() == 0) ||
963       (shooting_timer.get_timeleft() > 0 && !shooting_timer.check())) {
964     if (duck) {
965     } else {
966     }
967   }
968 */
969
970   if(dying) {
971     sprite->set_action("gameover");
972   }
973
974   /* Draw Tux */
975   if (safe_timer.started() && size_t(game_time*40)%2)
976     ;  // don't draw Tux
977   else {
978     sprite->draw(context, get_pos(), LAYER_OBJECTS + 1);
979   }
980
981 }
982
983 void
984 Player::collision_tile(uint32_t tile_attributes)
985 {
986   if(tile_attributes & Tile::HURTS)
987     kill(false);
988
989 #ifdef SWIMMING
990   if( swimming ){
991     if( tile_attributes & Tile::WATER ){
992       no_water = false;
993     } else {
994       swimming = false;
995     }
996   } else {
997     if( tile_attributes & Tile::WATER ){
998       swimming = true;
999       no_water = false;
1000       sound_manager->play( "sounds/splash.ogg" );
1001     }
1002   }
1003 #endif
1004 }
1005
1006 void
1007 Player::collision_solid(const CollisionHit& hit)
1008 {
1009   if(hit.bottom) {
1010     if(physic.get_velocity_y() > 0)
1011       physic.set_velocity_y(0);
1012
1013     on_ground_flag = true;
1014     floor_normal = hit.slope_normal;
1015
1016     // Butt Jump landed    
1017     if (does_buttjump) {
1018       does_buttjump = false;
1019       physic.set_velocity_y(-300);
1020       on_ground_flag = false;
1021       Sector::current()->add_object(new Particles(
1022           Vector(get_bbox().p2.x, get_bbox().p2.y),
1023           270+20, 270+40,
1024           Vector(280, -260), Vector(0, 300), 3, Color(.4f, .4f, .4f), 3, .8f,
1025           LAYER_OBJECTS+1));
1026       Sector::current()->add_object(new Particles(
1027           Vector(get_bbox().p1.x, get_bbox().p2.y),
1028           90-40, 90-20,
1029           Vector(280, -260), Vector(0, 300), 3, Color(.4f, .4f, .4f), 3, .8f,
1030           LAYER_OBJECTS+1));
1031     }
1032
1033   } else if(hit.top) {
1034     if(physic.get_velocity_y() < 0)
1035       physic.set_velocity_y(.2f);
1036   }
1037
1038   if(hit.left || hit.right) {
1039     physic.set_velocity_x(0);
1040   }
1041
1042   // crushed?
1043   if(hit.crush) {
1044     if(hit.left || hit.right) {
1045       kill(true);
1046     } else if(hit.top || hit.bottom) {
1047       kill(false);
1048     }
1049   }
1050 }
1051
1052 HitResponse
1053 Player::collision(GameObject& other, const CollisionHit& hit)
1054 {
1055   Bullet* bullet = dynamic_cast<Bullet*> (&other);
1056   if(bullet) {
1057     return FORCE_MOVE;
1058   }
1059
1060   if(hit.left || hit.right) {
1061     try_grab(); //grab objects right now, in update it will be too late
1062   }
1063 #ifdef DEBUG
1064   assert(dynamic_cast<MovingObject*> (&other) != NULL);
1065 #endif
1066   MovingObject* moving_object = static_cast<MovingObject*> (&other);
1067   if(moving_object->get_group() == COLGROUP_TOUCHABLE) {
1068     TriggerBase* trigger = dynamic_cast<TriggerBase*> (&other);
1069     if(trigger) {
1070       if(controller->pressed(Controller::UP))
1071         trigger->event(*this, TriggerBase::EVENT_ACTIVATE);
1072     }
1073
1074     return FORCE_MOVE;
1075   }
1076
1077   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
1078   if(badguy != NULL) {
1079     if(safe_timer.started() || invincible_timer.started())
1080       return FORCE_MOVE;
1081
1082     return CONTINUE;
1083   }
1084
1085   return CONTINUE;
1086 }
1087
1088 void
1089 Player::make_invincible()
1090 {
1091   sound_manager->play("sounds/invincible.wav");
1092   invincible_timer.start(TUX_INVINCIBLE_TIME);
1093   Sector::current()->play_music(HERRING_MUSIC);
1094 }
1095
1096 /* Kill Player! */
1097 void
1098 Player::kill(bool completely)
1099 {
1100   if(dying || deactivated)
1101     return;
1102
1103   if(!completely && (safe_timer.started() || invincible_timer.started()))
1104     return;
1105
1106   growing = false;
1107
1108   sound_manager->play("sounds/hurt.wav");
1109
1110   if (climbing) stop_climbing(*climbing);
1111
1112   physic.set_velocity_x(0);
1113
1114   if(!completely && is_big()) {
1115     if(player_status->bonus == FIRE_BONUS
1116         || player_status->bonus == ICE_BONUS) {
1117       safe_timer.start(TUX_SAFE_TIME);
1118       set_bonus(GROWUP_BONUS, true);
1119     } else if(player_status->bonus == GROWUP_BONUS) {
1120       safe_timer.start(TUX_SAFE_TIME /* + GROWING_TIME */);
1121       adjust_height(30.8f);
1122       duck = false;
1123       set_bonus(NO_BONUS, true);
1124     } else if(player_status->bonus == NO_BONUS) {
1125       safe_timer.start(TUX_SAFE_TIME);
1126       adjust_height(30.8f);
1127       duck = false;
1128     }
1129   } else {
1130
1131     // do not die when in edit mode
1132     if (edit_mode) {
1133       set_ghost_mode(true);
1134       return;
1135     }
1136
1137     if (player_status->coins >= 25 && !GameSession::current()->get_reset_point_sectorname().empty())
1138     {
1139       for (int i = 0; i < 5; i++)
1140       {
1141         // the numbers: starting x, starting y, velocity y
1142         Sector::current()->add_object(new FallingCoin(get_pos() +
1143               Vector(systemRandom.rand(5), systemRandom.rand(-32,18)),
1144               systemRandom.rand(-100,100)));
1145       }
1146       player_status->coins -= std::max(player_status->coins/10, 25);
1147     }
1148     else
1149     {
1150       GameSession::current()->set_reset_point("", Vector());
1151     }
1152     physic.enable_gravity(true);
1153     physic.set_acceleration(0, 0);
1154     physic.set_velocity(0, -700);
1155     set_bonus(NO_BONUS, true);
1156     dying = true;
1157     dying_timer.start(3.0);
1158     set_group(COLGROUP_DISABLED);
1159
1160     DisplayEffect* effect = new DisplayEffect();
1161     effect->fade_out(3.0);
1162     Sector::current()->add_object(effect);
1163     sound_manager->stop_music(3.0);
1164   }
1165 }
1166
1167 void
1168 Player::move(const Vector& vector)
1169 {
1170   set_pos(vector);
1171
1172   // TODO: do we need the following? Seems irrelevant to moving the player
1173   if(is_big())
1174     set_size(31.8f, 63.8f);
1175   else
1176     set_size(31.8f, 31.8f);
1177   duck = false;
1178   last_ground_y = vector.y;
1179   if (climbing) stop_climbing(*climbing);
1180
1181   physic.reset();
1182 }
1183
1184 void
1185 Player::check_bounds(Camera* camera)
1186 {
1187   /* Keep tux in bounds: */
1188   if (get_pos().x < 0) {
1189     // Lock Tux to the size of the level, so that he doesn't fall of
1190     // on the left side
1191     set_pos(Vector(0, get_pos().y));
1192   }
1193
1194   /* fallen out of the level? */
1195   if ((get_pos().y > Sector::current()->get_height()) && (!ghost_mode)) {
1196     kill(true);
1197     return;
1198   }
1199
1200   // can happen if back scrolling is disabled
1201   if(get_pos().x < camera->get_translation().x) {
1202     set_pos(Vector(camera->get_translation().x, get_pos().y));
1203   }
1204   if(get_pos().x >= camera->get_translation().x + SCREEN_WIDTH - bbox.get_width())
1205   {
1206     set_pos(Vector(
1207           camera->get_translation().x + SCREEN_WIDTH - bbox.get_width(),
1208           get_pos().y));
1209   }
1210 }
1211
1212 void
1213 Player::add_velocity(const Vector& velocity)
1214 {
1215   physic.set_velocity(physic.get_velocity() + velocity);
1216 }
1217
1218 void
1219 Player::add_velocity(const Vector& velocity, const Vector& end_speed)
1220 {
1221   if (end_speed.x > 0)
1222     physic.set_velocity_x(std::min(physic.get_velocity_x() + velocity.x, end_speed.x));
1223   if (end_speed.x < 0)
1224     physic.set_velocity_x(std::max(physic.get_velocity_x() + velocity.x, end_speed.x));
1225   if (end_speed.y > 0)
1226     physic.set_velocity_y(std::min(physic.get_velocity_y() + velocity.y, end_speed.y));
1227   if (end_speed.y < 0)
1228     physic.set_velocity_y(std::max(physic.get_velocity_y() + velocity.y, end_speed.y));
1229 }
1230
1231 Vector 
1232 Player::get_velocity()
1233 {
1234   return physic.get_velocity();
1235 }
1236
1237 void
1238 Player::bounce(BadGuy& )
1239 {
1240   if(controller->hold(Controller::JUMP))
1241     physic.set_velocity_y(-520);
1242   else
1243     physic.set_velocity_y(-300);
1244 }
1245
1246 //Scripting Functions Below
1247
1248 void
1249 Player::deactivate()
1250 {
1251   if (deactivated)
1252     return;
1253   deactivated = true;
1254   physic.set_velocity_x(0);
1255   physic.set_velocity_y(0);
1256   physic.set_acceleration_x(0);
1257   physic.set_acceleration_y(0);
1258   if (climbing) stop_climbing(*climbing);
1259 }
1260
1261 void
1262 Player::activate()
1263 {
1264   if (!deactivated)
1265     return;
1266   deactivated = false;
1267 }
1268
1269 void Player::walk(float speed)
1270 {
1271   physic.set_velocity_x(speed);
1272 }
1273
1274 void
1275 Player::set_ghost_mode(bool enable)
1276 {
1277   if (ghost_mode == enable)
1278     return;
1279
1280   if (climbing) stop_climbing(*climbing);
1281
1282   if (enable) {
1283     ghost_mode = true;
1284     set_group(COLGROUP_DISABLED);
1285     physic.enable_gravity(false);
1286     log_debug << "You feel lightheaded. Use movement controls to float around, press ACTION to scare badguys." << std::endl;
1287   } else {
1288     ghost_mode = false;
1289     set_group(COLGROUP_MOVING);
1290     physic.enable_gravity(true);
1291     log_debug << "You feel solid again." << std::endl;
1292   }
1293 }
1294
1295
1296 void
1297 Player::set_edit_mode(bool enable)
1298 {
1299   edit_mode = enable;
1300 }
1301
1302 void 
1303 Player::start_climbing(Climbable& climbable)
1304 {
1305   if (climbing == &climbable) return;
1306
1307   climbing = &climbable;
1308   physic.enable_gravity(false);
1309   physic.set_velocity(0, 0);
1310   physic.set_acceleration(0, 0);
1311 }
1312
1313 void 
1314 Player::stop_climbing(Climbable& /*climbable*/)
1315 {
1316   if (!climbing) return;
1317
1318   climbing = 0;
1319
1320   if (grabbed_object) {    
1321     grabbed_object->ungrab(*this, dir);
1322     grabbed_object = NULL;
1323   }
1324
1325   physic.enable_gravity(true);
1326   physic.set_velocity(0, 0);
1327   physic.set_acceleration(0, 0);
1328
1329   if ((controller->hold(Controller::JUMP)) || (controller->hold(Controller::UP))) {
1330     on_ground_flag = true;
1331     // TODO: This won't help. Why?
1332     do_jump(-300);
1333   }
1334 }
1335
1336 void
1337 Player::handle_input_climbing()
1338 {
1339   if (!climbing) {
1340     log_warning << "handle_input_climbing called with climbing set to 0. Input handling skipped" << std::endl;
1341     return;
1342   }
1343
1344   float vx = 0;
1345   float vy = 0;
1346   if (controller->hold(Controller::LEFT)) {
1347     dir = LEFT;
1348     vx -= MAX_CLIMB_XM;
1349   }
1350   if (controller->hold(Controller::RIGHT)) {
1351     dir = RIGHT;
1352     vx += MAX_CLIMB_XM;
1353   }
1354   if (controller->hold(Controller::UP)) {
1355     vy -= MAX_CLIMB_YM;
1356   }
1357   if (controller->hold(Controller::DOWN)) {
1358     vy += MAX_CLIMB_YM;
1359   }
1360   if (controller->hold(Controller::JUMP)) {
1361     if (can_jump) {
1362       stop_climbing(*climbing);
1363       return;
1364     }  
1365   } else {
1366     can_jump = true;
1367   }
1368   if (controller->hold(Controller::ACTION)) {
1369     stop_climbing(*climbing);
1370     return;
1371   }
1372   physic.set_velocity(vx, vy);
1373   physic.set_acceleration(0, 0);
1374 }
1375
1376