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