More robust way of calculating the falling layer
[supertux.git] / src / badguy / badguy.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 modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (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, see <http://www.gnu.org/licenses/>.
16
17 #include "badguy/badguy.hpp"
18
19 #include "audio/sound_manager.hpp"
20 #include "object/bullet.hpp"
21 #include "object/player.hpp"
22 #include "supertux/level.hpp"
23 #include "supertux/sector.hpp"
24 #include "supertux/tile.hpp"
25 #include "util/reader.hpp"
26
27 #include <math.h>
28 #include <sstream>
29
30 static const float SQUISH_TIME = 2;
31
32 static const float X_OFFSCREEN_DISTANCE = 1280;
33 static const float Y_OFFSCREEN_DISTANCE = 800;
34
35 BadGuy::BadGuy(const Vector& pos, const std::string& sprite_name_, int layer_) :
36   MovingSprite(pos, sprite_name_, layer_, COLGROUP_DISABLED),
37   physic(),
38   countMe(true),
39   is_initialized(false),
40   start_position(),
41   dir(LEFT),
42   start_dir(AUTO),
43   frozen(false),
44   ignited(false),
45   dead_script(),
46   state(STATE_INIT),
47   is_active_flag(),
48   state_timer(),
49   on_ground_flag(false),
50   floor_normal(),
51   colgroup_active(COLGROUP_MOVING)
52 {
53   start_position = bbox.p1;
54
55   SoundManager::current()->preload("sounds/squish.wav");
56   SoundManager::current()->preload("sounds/fall.wav");
57
58   dir = (start_dir == AUTO) ? LEFT : start_dir;
59 }
60
61 BadGuy::BadGuy(const Vector& pos, Direction direction, const std::string& sprite_name_, int layer_) :
62   MovingSprite(pos, sprite_name_, layer_, COLGROUP_DISABLED),
63   physic(),
64   countMe(true),
65   is_initialized(false),
66   start_position(),
67   dir(direction),
68   start_dir(direction),
69   frozen(false),
70   ignited(false),
71   dead_script(),
72   state(STATE_INIT),
73   is_active_flag(),
74   state_timer(),
75   on_ground_flag(false),
76   floor_normal(),
77   colgroup_active(COLGROUP_MOVING)
78 {
79   start_position = bbox.p1;
80
81   SoundManager::current()->preload("sounds/squish.wav");
82   SoundManager::current()->preload("sounds/fall.wav");
83
84   dir = (start_dir == AUTO) ? LEFT : start_dir;
85 }
86
87 BadGuy::BadGuy(const Reader& reader, const std::string& sprite_name_, int layer_) :
88   MovingSprite(reader, sprite_name_, layer_, COLGROUP_DISABLED),
89   physic(),
90   countMe(true),
91   is_initialized(false),
92   start_position(),
93   dir(LEFT),
94   start_dir(AUTO),
95   frozen(false),
96   ignited(false),
97   dead_script(),
98   state(STATE_INIT),
99   is_active_flag(),
100   state_timer(),
101   on_ground_flag(false),
102   floor_normal(),
103   colgroup_active(COLGROUP_MOVING)
104 {
105   start_position = bbox.p1;
106
107   std::string dir_str = "auto";
108   reader.get("direction", dir_str);
109   start_dir = str2dir( dir_str );
110   dir = start_dir;
111
112   reader.get("dead-script", dead_script);
113
114   SoundManager::current()->preload("sounds/squish.wav");
115   SoundManager::current()->preload("sounds/fall.wav");
116
117   dir = (start_dir == AUTO) ? LEFT : start_dir;
118 }
119
120 void
121 BadGuy::draw(DrawingContext& context)
122 {
123   if(!sprite.get())
124     return;
125   if(state == STATE_INIT || state == STATE_INACTIVE)
126     return;
127   if(state == STATE_FALLING) {
128     DrawingEffect old_effect = context.get_drawing_effect();
129     context.set_drawing_effect(old_effect | VERTICAL_FLIP);
130     sprite->draw(context, get_pos(), layer);
131     context.set_drawing_effect(old_effect);
132   } else {
133     sprite->draw(context, get_pos(), layer);
134   }
135 }
136
137 void
138 BadGuy::update(float elapsed_time)
139 {
140   if(!Sector::current()->inside(bbox)) {
141     is_active_flag = false;
142     remove_me();
143     if(countMe) {
144       // get badguy name from sprite_name ignoring path and extension
145       std::string badguy = sprite_name.substr(0, sprite_name.length() - 7);
146       int path_chars = badguy.rfind("/",badguy.length());
147       badguy = badguy.substr(path_chars + 1, badguy.length() - path_chars);
148       // log warning since badguys_killed can no longer reach total_badguys
149       std::string current_level = "[" + Sector::current()->get_level()->filename + "] ";
150       log_warning << current_level << "Counted badguy " << badguy << " starting at " << start_position << " has left the sector" <<std::endl;;
151     }
152     return;
153   }
154   if ((state != STATE_INACTIVE) && is_offscreen()) {
155     if (state == STATE_ACTIVE) deactivate();
156     set_state(STATE_INACTIVE);
157   }
158
159   switch(state) {
160     case STATE_ACTIVE:
161       is_active_flag = true;
162       active_update(elapsed_time);
163       break;
164     case STATE_INIT:
165     case STATE_INACTIVE:
166       is_active_flag = false;
167       inactive_update(elapsed_time);
168       try_activate();
169       break;
170     case STATE_SQUISHED:
171       is_active_flag = false;
172       if(state_timer.check()) {
173         remove_me();
174         break;
175       }
176       movement = physic.get_movement(elapsed_time);
177       break;
178     case STATE_FALLING:
179       is_active_flag = false;
180       movement = physic.get_movement(elapsed_time);
181       break;
182   }
183
184   on_ground_flag = false;
185 }
186
187 Direction
188 BadGuy::str2dir( std::string dir_str )
189 {
190   if( dir_str == "auto" )
191     return AUTO;
192   if( dir_str == "left" )
193     return LEFT;
194   if( dir_str == "right" )
195     return RIGHT;
196
197   //default to "auto"
198   log_warning << "Badguy::str2dir: unknown direction \"" << dir_str << "\"" << std::endl;;
199   return AUTO;
200 }
201
202 void
203 BadGuy::initialize()
204 {
205 }
206
207 void
208 BadGuy::activate()
209 {
210 }
211
212 void
213 BadGuy::deactivate()
214 {
215 }
216
217 void
218 BadGuy::active_update(float elapsed_time)
219 {
220   movement = physic.get_movement(elapsed_time);
221   if(frozen)
222     sprite->stop_animation();
223 }
224
225 void
226 BadGuy::inactive_update(float )
227 {
228 }
229
230 void
231 BadGuy::collision_tile(uint32_t tile_attributes)
232 {
233   // Don't kill badguys that have already been killed
234   if (!is_active()) return;
235
236   if(tile_attributes & Tile::HURTS) {
237     if (tile_attributes & Tile::FIRE) {
238       if (is_flammable()) ignite();
239     }
240     else if (tile_attributes & Tile::ICE) {
241       if (is_freezable()) freeze();
242     }
243     else {
244       kill_fall();
245     }
246   }
247 }
248
249 HitResponse
250 BadGuy::collision(GameObject& other, const CollisionHit& hit)
251 {
252   if (!is_active()) return ABORT_MOVE;
253
254   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
255   if(badguy && badguy->is_active() && badguy->get_group() == COLGROUP_MOVING) {
256
257     /* Badguys don't let badguys squish other badguys. It's bad. */
258 #if 0
259     // hit from above?
260     if (badguy->get_bbox().p2.y < (bbox.p1.y + 16)) {
261       if(collision_squished(*badguy)) {
262         return ABORT_MOVE;
263       }
264     }
265 #endif
266
267     return collision_badguy(*badguy, hit);
268   }
269
270   Player* player = dynamic_cast<Player*> (&other);
271   if(player) {
272
273     // hit from above?
274     if (player->get_bbox().p2.y < (bbox.p1.y + 16)) {
275       if(collision_squished(*player)) {
276         return FORCE_MOVE;
277       }
278     }
279
280     return collision_player(*player, hit);
281   }
282
283   Bullet* bullet = dynamic_cast<Bullet*> (&other);
284   if(bullet)
285     return collision_bullet(*bullet, hit);
286
287   return FORCE_MOVE;
288 }
289
290 void
291 BadGuy::collision_solid(const CollisionHit& hit)
292 {
293   physic.set_velocity_x(0);
294   physic.set_velocity_y(0);
295   update_on_ground_flag(hit);
296 }
297
298 HitResponse
299 BadGuy::collision_player(Player& player, const CollisionHit& )
300 {
301   if(player.is_invincible()) {
302     kill_fall();
303     return ABORT_MOVE;
304   }
305
306   //TODO: unfreeze timer
307   if(frozen)
308     //unfreeze();
309     return FORCE_MOVE;
310
311   player.kill(false);
312   return FORCE_MOVE;
313 }
314
315 HitResponse
316 BadGuy::collision_badguy(BadGuy& , const CollisionHit& )
317 {
318   return FORCE_MOVE;
319 }
320
321 bool
322 BadGuy::collision_squished(GameObject& object)
323 {
324   // frozen badguys can be killed with butt-jump
325   if(frozen)
326   {
327     Player* player = dynamic_cast<Player*>(&object);
328     if(player && (player->does_buttjump)) {
329       player->bounce(*this);
330       kill_fall();//TODO: shatter frozen badguys
331       return true;
332     }
333   }
334     return false;
335 }
336
337 HitResponse
338 BadGuy::collision_bullet(Bullet& bullet, const CollisionHit& hit)
339 {
340   if (is_frozen()) {
341     if(bullet.get_type() == FIRE_BONUS) {
342       // fire bullet thaws frozen badguys
343       unfreeze();
344       bullet.remove_me();
345       return ABORT_MOVE;
346     } else {
347       // other bullets ricochet
348       bullet.ricochet(*this, hit);
349       return FORCE_MOVE;
350     }
351   }
352   else if (is_ignited()) {
353     if(bullet.get_type() == ICE_BONUS) {
354       // ice bullets extinguish ignited badguys
355       extinguish();
356       bullet.remove_me();
357       return ABORT_MOVE;
358     } else {
359       // other bullets are absorbed by ignited badguys
360       bullet.remove_me();
361       return FORCE_MOVE;
362     }
363   }
364   else if(bullet.get_type() == FIRE_BONUS && is_flammable()) {
365     // fire bullets ignite flammable badguys
366     ignite();
367     bullet.remove_me();
368     return ABORT_MOVE;
369   }
370   else if(bullet.get_type() == ICE_BONUS && is_freezable()) {
371     // ice bullets freeze freezable badguys
372     freeze();
373     bullet.remove_me();
374     return ABORT_MOVE;
375   }
376   else {
377     // in all other cases, bullets ricochet
378     bullet.ricochet(*this, hit);
379     return FORCE_MOVE;
380   }
381 }
382
383 void
384 BadGuy::kill_squished(GameObject& object)
385 {
386   if (!is_active()) return;
387
388   SoundManager::current()->play("sounds/squish.wav", get_pos());
389   physic.enable_gravity(true);
390   physic.set_velocity_x(0);
391   physic.set_velocity_y(0);
392   set_state(STATE_SQUISHED);
393   set_group(COLGROUP_MOVING_ONLY_STATIC);
394   Player* player = dynamic_cast<Player*>(&object);
395   if (player) {
396     player->bounce(*this);
397   }
398
399   // start dead-script
400   run_dead_script();
401 }
402
403 void
404 BadGuy::kill_fall()
405 {
406   if (!is_active()) return;
407
408   SoundManager::current()->play("sounds/fall.wav", get_pos());
409   physic.set_velocity_y(0);
410   physic.set_acceleration_y(0);
411   physic.enable_gravity(true);
412   set_state(STATE_FALLING);
413
414   // Set the badguy layer to be the foremost, so that
415   // this does not reveal secret tilemaps:
416   layer = Sector::current()->get_foremost_layer() + 1;
417
418   // start dead-script
419   run_dead_script();
420 }
421
422 void
423 BadGuy::run_dead_script()
424 {
425   if (countMe)
426     Sector::current()->get_level()->stats.badguys++;
427
428   countMe = false;
429
430   // start dead-script
431   if(dead_script != "") {
432     std::istringstream stream(dead_script);
433     Sector::current()->run_script(stream, "dead-script");
434   }
435 }
436
437 void
438 BadGuy::set_state(State state_)
439 {
440   if(this->state == state_)
441     return;
442
443   State laststate = this->state;
444   this->state = state_;
445   switch(state_) {
446     case STATE_SQUISHED:
447       state_timer.start(SQUISH_TIME);
448       break;
449     case STATE_ACTIVE:
450       set_group(colgroup_active);
451       //bbox.set_pos(start_position);
452       break;
453     case STATE_INACTIVE:
454       // was the badguy dead anyway?
455       if(laststate == STATE_SQUISHED || laststate == STATE_FALLING) {
456         remove_me();
457       }
458       set_group(COLGROUP_DISABLED);
459       break;
460     case STATE_FALLING:
461       set_group(COLGROUP_DISABLED);
462       break;
463     default:
464       break;
465   }
466 }
467
468 bool
469 BadGuy::is_offscreen()
470 {
471   Player* player = get_nearest_player();
472   if (!player) return false;
473   Vector dist = player->get_bbox().get_middle() - get_bbox().get_middle();
474   // In SuperTux 0.1.x, Badguys were activated when Tux<->Badguy center distance was approx. <= ~668px
475   // This doesn't work for wide-screen monitors which give us a virt. res. of approx. 1066px x 600px
476   if ((fabsf(dist.x) <= X_OFFSCREEN_DISTANCE) && (fabsf(dist.y) <= Y_OFFSCREEN_DISTANCE)) {
477     return false;
478   }
479   return true;
480 }
481
482 void
483 BadGuy::try_activate()
484 {
485   // Don't activate if player is dying
486   Player* player = get_nearest_player();
487   if (!player) return;
488
489   if (!is_offscreen()) {
490     set_state(STATE_ACTIVE);
491     if (!is_initialized) {
492
493       // if starting direction was set to AUTO, this is our chance to re-orient the badguy
494       if (start_dir == AUTO) {
495         Player* player_ = get_nearest_player();
496         if (player_ && (player_->get_bbox().p1.x > get_bbox().p2.x)) {
497           dir = RIGHT;
498         } else {
499           dir = LEFT;
500         }
501       }
502
503       initialize();
504       is_initialized = true;
505     }
506     activate();
507   }
508 }
509
510 bool
511 BadGuy::might_fall(int height)
512 {
513   // make sure we check for at least a 1-pixel fall
514   assert(height > 0);
515
516   float x1;
517   float x2;
518   float y1 = bbox.p2.y + 1;
519   float y2 = bbox.p2.y + 1 + height;
520   if (dir == LEFT) {
521     x1 = bbox.p1.x - 1;
522     x2 = bbox.p1.x;
523   } else {
524     x1 = bbox.p2.x;
525     x2 = bbox.p2.x + 1;
526   }
527   return Sector::current()->is_free_of_statics(Rectf(x1, y1, x2, y2));
528 }
529
530 Player*
531 BadGuy::get_nearest_player()
532 {
533   return Sector::current()->get_nearest_player (this->get_bbox ());
534 }
535
536 void
537 BadGuy::update_on_ground_flag(const CollisionHit& hit)
538 {
539   if (hit.bottom) {
540     on_ground_flag = true;
541     floor_normal = hit.slope_normal;
542   }
543 }
544
545 bool
546 BadGuy::on_ground()
547 {
548   return on_ground_flag;
549 }
550
551 bool
552 BadGuy::is_active()
553 {
554   return is_active_flag;
555 }
556
557 Vector
558 BadGuy::get_floor_normal()
559 {
560   return floor_normal;
561 }
562
563 void
564 BadGuy::freeze()
565 {
566   set_group(COLGROUP_MOVING_STATIC);
567   frozen = true;
568
569   if(sprite->has_action("iced-left"))
570     sprite->set_action(dir == LEFT ? "iced-left" : "iced-right", 1);
571   // when no iced action exists, default to shading badguy blue
572   else
573   {
574     sprite->set_color(Color(0.60, 0.72, 0.88f));
575     sprite->stop_animation();
576   }
577 }
578
579 void
580 BadGuy::unfreeze()
581 {
582   set_group(colgroup_active);
583   frozen = false;
584
585   // restore original color if needed
586   if(!sprite->has_action("iced-left"))
587   {
588     sprite->set_color(Color(1.00, 1.00, 1.00f));
589     sprite->set_animation_loops();
590   }
591 }
592
593 bool
594 BadGuy::is_freezable() const
595 {
596   return false;
597 }
598
599 bool
600 BadGuy::is_frozen() const
601 {
602   return frozen;
603 }
604
605 void
606 BadGuy::ignite()
607 {
608   kill_fall();
609 }
610
611 void
612 BadGuy::extinguish()
613 {
614 }
615
616 bool
617 BadGuy::is_flammable() const
618 {
619   return true;
620 }
621
622 bool
623 BadGuy::is_ignited() const
624 {
625   return ignited;
626 }
627
628 void
629 BadGuy::set_colgroup_active(CollisionGroup group_)
630 {
631   this->colgroup_active = group_;
632   if (state == STATE_ACTIVE) set_group(group_);
633 }
634
635 /* EOF */