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