Renamed namespaces to all lowercase
[supertux.git] / src / object / camera.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 "object/camera.hpp"
18
19 #include <math.h>
20 #include <physfs.h>
21
22 #include "util/reader.hpp"
23 #include "util/writer.hpp"
24 #include "lisp/parser.hpp"
25 #include "object/path_walker.hpp"
26 #include "object/player.hpp"
27 #include "scripting/camera.hpp"
28 #include "scripting/squirrel_util.hpp"
29 #include "supertux/globals.hpp"
30 #include "supertux/sector.hpp"
31
32 /* this is the fractional distance toward the peek
33    position to move each frame; lower is slower,
34    0 is never get there, 1 is instant */
35 static const float PEEK_ARRIVE_RATIO = 0.1;
36
37 class CameraConfig
38 {
39 public:
40   // 0 = No, 1 = Fix, 2 = Mario/Yoshi, 3 = Kirby, 4 = Super Metroid-like
41   int xmode;
42   // as above
43   int ymode;
44   float kirby_rectsize_x;
45   float kirby_rectsize_y;
46   // where to fix the player (used for Yoshi and Fix camera)
47   float target_x;
48   float target_y;
49   // maximum scrolling speed in Y direction
50   float max_speed_x;
51   float max_speed_y;
52   // factor to dynamically increase max_speed_x based on player speed
53   float dynamic_max_speed_x;
54
55   // time the player has to face into the other direction before we assume a
56   // changed direction
57   float dirchange_time;
58   // edge_x
59   float edge_x;
60   // when too change from noscroll mode back to lookahead left/right mode
61   // set to <= 0 to disable noscroll mode
62   float sensitive_x;
63
64   float clamp_x;
65   float clamp_y;
66
67   float dynamic_speed_sm;
68
69   CameraConfig() :
70     xmode(4),
71     ymode(3),
72     kirby_rectsize_x(0.2f),
73     kirby_rectsize_y(0.34f),
74     target_x(.5f),
75     target_y(.5f),
76     max_speed_x(100),
77     max_speed_y(100),
78     dynamic_max_speed_x(1.0),
79     dirchange_time(0.2f),
80     edge_x(0.4f),
81     sensitive_x(-1),
82     clamp_x(0.1666f),
83     clamp_y(0.3f),
84     dynamic_speed_sm(0.8f)
85   {
86   }
87
88   void load(const std::string& filename)
89   {
90     lisp::Parser parser;
91     const lisp::Lisp* root = parser.parse(filename);
92     const lisp::Lisp* camconfig = root->get_lisp("camera-config");
93     if(camconfig == NULL)
94       throw std::runtime_error("file is not a camera config file.");
95
96     camconfig->get("xmode", xmode);
97     camconfig->get("ymode", ymode);
98     camconfig->get("target-x", target_x);
99     camconfig->get("target-y", target_y);
100     camconfig->get("max-speed-x", max_speed_x);
101     camconfig->get("max-speed-y", max_speed_y);
102     camconfig->get("dynamic-max-speed-x", dynamic_max_speed_x);
103     camconfig->get("dirchange-time", dirchange_time);
104     camconfig->get("clamp-x", clamp_x);
105     camconfig->get("clamp-y", clamp_y);
106     camconfig->get("kirby-rectsize-x", kirby_rectsize_x);
107     camconfig->get("kirby-rectsize-y", kirby_rectsize_y);
108     camconfig->get("edge-x", edge_x);
109     camconfig->get("sensitive-x", sensitive_x);
110     camconfig->get("dynamic-speed-sm", dynamic_speed_sm);
111   }
112 };
113
114 Camera::Camera(Sector* newsector, std::string name) :
115   mode(NORMAL),
116   translation(),
117   sector(newsector), 
118   lookahead_mode(LOOKAHEAD_NONE),
119   changetime(),
120   lookahead_pos(),
121   peek_pos(),
122   cached_translation(),
123   autoscroll_path(),
124   autoscroll_walker(),
125   shaketimer(),
126   shakespeed(),
127   shakedepth_x(),
128   shakedepth_y(),
129   scroll_from(),
130   scroll_goal(),
131   scroll_to_pos(),
132   scrollspeed(),
133   config()
134 {
135   this->name = name;
136   config = new CameraConfig();
137   reload_config();
138 }
139
140 Camera::~Camera()
141 {
142   delete config;
143 }
144
145 void
146 Camera::expose(HSQUIRRELVM vm, SQInteger table_idx)
147 {
148   if(name.empty()) return;
149   scripting::Camera* interface = new scripting::Camera(this);
150   expose_object(vm, table_idx, interface, name, true);
151 }
152
153 void
154 Camera::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
155 {
156   if(name.empty()) return;
157   scripting::unexpose_object(vm, table_idx, name);
158 }
159
160 void
161 Camera::draw(DrawingContext& )
162 {
163 }
164
165 const Vector&
166 Camera::get_translation() const
167 {
168   return translation;
169 }
170
171 void
172 Camera::parse(const Reader& reader)
173 {
174   std::string modename;
175
176   reader.get("mode", modename);
177   if(modename == "normal") {
178     mode = NORMAL;
179   } else if(modename == "autoscroll") {
180     mode = AUTOSCROLL;
181
182     const lisp::Lisp* pathLisp = reader.get_lisp("path");
183     if(pathLisp == NULL)
184       throw std::runtime_error("No path specified in autoscroll camera.");
185
186     autoscroll_path.reset(new Path());
187     autoscroll_path->read(*pathLisp);
188     autoscroll_walker.reset(new PathWalker(autoscroll_path.get()));
189   } else if(modename == "manual") {
190     mode = MANUAL;
191   } else {
192     std::stringstream str;
193     str << "invalid camera mode '" << modename << "'found in worldfile.";
194     throw std::runtime_error(str.str());
195   }
196 }
197
198 void
199 Camera::reset(const Vector& tuxpos)
200 {
201   translation.x = tuxpos.x - SCREEN_WIDTH/2;
202   translation.y = tuxpos.y - SCREEN_HEIGHT/2;
203
204   shakespeed = 0;
205   shaketimer.stop();
206   keep_in_bounds(translation);
207
208   cached_translation = translation;
209 }
210
211 void
212 Camera::shake(float time, float x, float y)
213 {
214   shaketimer.start(time);
215   shakedepth_x = x;
216   shakedepth_y = y;
217   shakespeed = M_PI/2 / time;
218 }
219
220 void
221 Camera::scroll_to(const Vector& goal, float scrolltime)
222 {
223   scroll_from = translation;
224   scroll_goal = goal;
225   keep_in_bounds(scroll_goal);
226
227   scroll_to_pos = 0;
228   scrollspeed = 1.0 / scrolltime;
229   mode = SCROLLTO;
230 }
231
232 static const float EPSILON = .00001f;
233 static const float MAX_SPEED_Y = 140;
234
235 void
236 Camera::update(float elapsed_time)
237 {
238   switch(mode) {
239     case NORMAL:
240       update_scroll_normal(elapsed_time);
241       break;
242     case AUTOSCROLL:
243       update_scroll_autoscroll(elapsed_time);
244       break;
245     case SCROLLTO:
246       update_scroll_to(elapsed_time);
247       break;
248     default:
249       break;
250   }
251   shake();
252 }
253
254 void
255 Camera::reload_config()
256 {
257   if(PHYSFS_exists("camera.cfg")) {
258     try {
259       config->load("camera.cfg");
260       log_info << "Loaded camera.cfg." << std::endl;
261     } catch(std::exception &e) {
262       log_debug << "Couldn't load camera.cfg, using defaults ("
263                 << e.what() << ")" << std::endl;
264     }
265   }
266 }
267
268 float clamp(float val, float min, float max)
269 {
270   if(val < min)
271     return min;
272   if(val > max)
273     return max;
274
275   return val;
276 }
277
278 void
279 Camera::keep_in_bounds(Vector& translation)
280 {
281   float width = sector->get_width();
282   float height = sector->get_height();
283
284   // don't scroll before the start or after the level's end
285   translation.x = clamp(translation.x, 0, width - SCREEN_WIDTH);
286   translation.y = clamp(translation.y, 0, height - SCREEN_HEIGHT);
287
288   if (height < SCREEN_HEIGHT)
289     translation.y = height/2.0 - SCREEN_HEIGHT/2.0;
290   if (width < SCREEN_WIDTH)
291     translation.x = width/2.0 - SCREEN_WIDTH/2.0;
292 }
293
294 void
295 Camera::shake()
296 {
297   if(shaketimer.started()) {
298     translation.x -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_x;
299     translation.y -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_y;
300   }
301 }
302
303 void
304 Camera::update_scroll_normal(float elapsed_time)
305 {
306   const CameraConfig& config = *(this->config);
307   Player* player = sector->player;
308   const Vector& player_pos = Vector(player->get_bbox().get_middle().x,
309                                     player->get_bbox().get_bottom());
310   static Vector last_player_pos = player_pos;
311   Vector player_delta = player_pos - last_player_pos;
312   last_player_pos = player_pos;
313
314   // check that we don't have division by zero later
315   if(elapsed_time < EPSILON)
316     return;
317
318   /****** Vertical Scrolling part ******/
319   int ymode = config.ymode;
320
321   if(player->is_dying() || sector->get_height() == 19*32) {
322     ymode = 0;
323   }
324   if(ymode == 1) {
325     cached_translation.y = player_pos.y - SCREEN_HEIGHT * config.target_y;
326   }
327   if(ymode == 2) {
328     // target_y is the high we target our scrolling at. This is not always the
329     // high of the player, but if he is jumping upwards we should use the
330     // position where he last touched the ground. (this probably needs
331     // exceptions for trampolines and similar things in the future)
332     float target_y;
333     if(player->fall_mode == Player::JUMPING)
334       target_y = player->last_ground_y + player->get_bbox().get_height();
335     else
336       target_y = player->get_bbox().p2.y;
337     target_y -= SCREEN_HEIGHT * config.target_y;
338
339     // delta_y is the distance we'd have to travel to directly reach target_y
340     float delta_y = cached_translation.y - target_y;
341     // speed is the speed the camera would need to reach target_y in this frame
342     float speed_y = delta_y / elapsed_time;
343
344     // limit the camera speed when jumping upwards
345     if(player->fall_mode != Player::FALLING
346        && player->fall_mode != Player::TRAMPOLINE_JUMP) {
347       speed_y = clamp(speed_y, -config.max_speed_y, config.max_speed_y);
348     }
349
350     // scroll with calculated speed
351     cached_translation.y -= speed_y * elapsed_time;
352   }
353   if(ymode == 3) {
354     float halfsize = config.kirby_rectsize_y * 0.5f;
355     cached_translation.y = clamp(cached_translation.y,
356                                  player_pos.y - SCREEN_HEIGHT * (0.5f + halfsize),
357                                  player_pos.y - SCREEN_HEIGHT * (0.5f - halfsize));
358   }
359   if(ymode == 4) {
360     float upperend = SCREEN_HEIGHT * config.edge_x;
361     float lowerend = SCREEN_HEIGHT * (1 - config.edge_x);
362
363     if (player_delta.y < -EPSILON) {
364       // walking left
365       lookahead_pos.y -= player_delta.y * config.dynamic_speed_sm;
366
367       if(lookahead_pos.y > lowerend) {
368         lookahead_pos.y = lowerend;
369       }
370     } else if (player_delta.y > EPSILON) {
371       // walking right
372       lookahead_pos.y -= player_delta.y * config.dynamic_speed_sm;
373       if(lookahead_pos.y < upperend) {
374         lookahead_pos.y = upperend;
375       }
376     }
377
378     // adjust for level ends
379     if (player_pos.y < upperend) {
380       lookahead_pos.y = upperend;
381     }
382     if (player_pos.y > sector->get_width() - upperend) {
383       lookahead_pos.y = lowerend;
384     }
385
386     cached_translation.y = player_pos.y - lookahead_pos.y;
387   }
388
389   translation.y = cached_translation.y;
390
391   if(ymode != 0) {
392     float top_edge, bottom_edge;
393     if(config.clamp_y <= 0) {
394       top_edge = 0;
395       bottom_edge = SCREEN_HEIGHT;
396     } else {
397       top_edge = SCREEN_HEIGHT*config.clamp_y;
398       bottom_edge = SCREEN_HEIGHT*(1-config.clamp_y);
399     }
400
401     float peek_to = 0;
402     float translation_compensation = player_pos.y - translation.y;
403
404     if(player->peeking_direction_y() == ::UP) {
405       peek_to = bottom_edge - translation_compensation;
406     } else if(player->peeking_direction_y() == ::DOWN) {
407       peek_to = top_edge - translation_compensation;
408     }
409
410     float peek_move = (peek_to - peek_pos.y) * PEEK_ARRIVE_RATIO;
411     if(fabs(peek_move) < 1.0) {
412       peek_move = 0.0;
413     }
414
415     peek_pos.y += peek_move;
416
417     translation.y -= peek_pos.y;
418
419     if(config.clamp_y > 0) {
420       translation.y = clamp(translation.y,
421                             player_pos.y - SCREEN_HEIGHT * (1-config.clamp_y),
422                             player_pos.y - SCREEN_HEIGHT * config.clamp_y);
423       cached_translation.y = clamp(cached_translation.y,
424                                    player_pos.y - SCREEN_HEIGHT * (1-config.clamp_y),
425                                    player_pos.y - SCREEN_HEIGHT * config.clamp_y);
426     }
427   }
428
429   /****** Horizontal scrolling part *******/
430   int xmode = config.xmode;
431
432   if(player->is_dying())
433     xmode = 0;
434
435   if(xmode == 1) {
436     cached_translation.x = player_pos.x - SCREEN_WIDTH * config.target_x;
437   }
438   if(xmode == 2) {
439     // our camera is either in leftscrolling, rightscrolling or
440     // nonscrollingmode.
441     //
442     // when suddenly changing directions while scrolling into the other
443     // direction abort scrolling, since tux might be going left/right at a
444     // relatively small part of the map (like when jumping upwards)
445
446     // Find out direction in which the player moves
447     LookaheadMode walkDirection;
448     if (player_delta.x < -EPSILON) walkDirection = LOOKAHEAD_LEFT;
449     else if (player_delta.x > EPSILON) walkDirection = LOOKAHEAD_RIGHT;
450     else if (player->dir == ::LEFT) walkDirection = LOOKAHEAD_LEFT;
451     else walkDirection = LOOKAHEAD_RIGHT;
452
453     float LEFTEND, RIGHTEND;
454     if(config.sensitive_x > 0) {
455       LEFTEND = SCREEN_WIDTH * config.sensitive_x;
456       RIGHTEND = SCREEN_WIDTH * (1-config.sensitive_x);
457     } else {
458       LEFTEND = SCREEN_WIDTH;
459       RIGHTEND = 0;
460     }
461
462     if(lookahead_mode == LOOKAHEAD_NONE) {
463       /* if we're undecided then look if we crossed the left or right
464        * "sensitive" area */
465       if(player_pos.x < cached_translation.x + LEFTEND) {
466         lookahead_mode = LOOKAHEAD_LEFT;
467       } else if(player_pos.x > cached_translation.x + RIGHTEND) {
468         lookahead_mode = LOOKAHEAD_RIGHT;
469       }
470       /* at the ends of a level it's obvious which way we will go */
471       if(player_pos.x < SCREEN_WIDTH*0.5) {
472         lookahead_mode = LOOKAHEAD_RIGHT;
473       } else if(player_pos.x >= sector->get_width() - SCREEN_WIDTH*0.5) {
474         lookahead_mode = LOOKAHEAD_LEFT;
475       }
476
477       changetime = -1;
478     } else if(lookahead_mode != walkDirection) {
479       /* player changed direction while camera was scrolling...
480        * he has to do this for a certain time to add robustness against
481        * sudden changes */
482       if(changetime < 0) {
483         changetime = game_time;
484       } else if(game_time - changetime > config.dirchange_time) {
485         if(lookahead_mode == LOOKAHEAD_LEFT &&
486            player_pos.x > cached_translation.x + RIGHTEND) {
487           lookahead_mode = LOOKAHEAD_RIGHT;
488         } else if(lookahead_mode == LOOKAHEAD_RIGHT &&
489                   player_pos.x < cached_translation.x + LEFTEND) {
490           lookahead_mode = LOOKAHEAD_LEFT;
491         } else {
492           lookahead_mode = LOOKAHEAD_NONE;
493         }
494       }
495     } else {
496       changetime = -1;
497     }
498
499     LEFTEND = SCREEN_WIDTH * config.edge_x;
500     RIGHTEND = SCREEN_WIDTH * (1-config.edge_x);
501
502     // calculate our scroll target depending on scroll mode
503     float target_x;
504     if(lookahead_mode == LOOKAHEAD_LEFT)
505       target_x = player_pos.x - RIGHTEND;
506     else if(lookahead_mode == LOOKAHEAD_RIGHT)
507       target_x = player_pos.x - LEFTEND;
508     else
509       target_x = cached_translation.x;
510
511     // that's the distance we would have to travel to reach target_x
512     float delta_x = cached_translation.x - target_x;
513     // the speed we'd need to travel to reach target_x in this frame
514     float speed_x = delta_x / elapsed_time;
515
516     // limit our speed
517     float player_speed_x = player_delta.x / elapsed_time;
518     float maxv = config.max_speed_x + (fabsf(player_speed_x * config.dynamic_max_speed_x));
519     speed_x = clamp(speed_x, -maxv, maxv);
520
521     // apply scrolling
522     cached_translation.x -= speed_x * elapsed_time;
523   }
524   if(xmode == 3) {
525     float halfsize = config.kirby_rectsize_x * 0.5f;
526     cached_translation.x = clamp(cached_translation.x,
527                                  player_pos.x - SCREEN_WIDTH * (0.5f + halfsize),
528                                  player_pos.x - SCREEN_WIDTH * (0.5f - halfsize));
529   }
530   if(xmode == 4) {
531     float LEFTEND = SCREEN_WIDTH * config.edge_x;
532     float RIGHTEND = SCREEN_WIDTH * (1 - config.edge_x);
533
534     if (player_delta.x < -EPSILON) {
535       // walking left
536       lookahead_pos.x -= player_delta.x * config.dynamic_speed_sm;
537       if(lookahead_pos.x > RIGHTEND) {
538         lookahead_pos.x = RIGHTEND;
539       }
540
541     } else if (player_delta.x > EPSILON) {
542       // walking right
543       lookahead_pos.x -= player_delta.x * config.dynamic_speed_sm;
544       if(lookahead_pos.x < LEFTEND) {
545         lookahead_pos.x = LEFTEND;
546       }
547     }
548
549     // adjust for level ends
550     if (player_pos.x < LEFTEND) {
551       lookahead_pos.x = LEFTEND;
552     }
553     if (player_pos.x > sector->get_width() - LEFTEND) {
554       lookahead_pos.x = RIGHTEND;
555     }
556
557     cached_translation.x = player_pos.x - lookahead_pos.x;
558   }
559
560   translation.x = cached_translation.x;
561
562   if(xmode != 0) {
563     float left_edge, right_edge;
564     if(config.clamp_x <= 0) {
565       left_edge = 0;
566       right_edge = SCREEN_WIDTH;
567     } else {
568       left_edge = SCREEN_WIDTH*config.clamp_x;
569       right_edge = SCREEN_WIDTH*(1-config.clamp_x);
570     }
571
572     float peek_to = 0;
573     float translation_compensation = player_pos.x - translation.x;
574
575     if(player->peeking_direction_x() == ::LEFT) {
576       peek_to = right_edge - translation_compensation;
577     } else if(player->peeking_direction_x() == ::RIGHT) {
578       peek_to = left_edge - translation_compensation;
579     }
580
581     float peek_move = (peek_to - peek_pos.x) * PEEK_ARRIVE_RATIO;
582     if(fabs(peek_move) < 1.0) {
583       peek_move = 0.0;
584     }
585
586     peek_pos.x += peek_move;
587
588     translation.x -= peek_pos.x;
589
590     if(config.clamp_x > 0) {
591       translation.x = clamp(translation.x,
592                             player_pos.x - SCREEN_WIDTH * (1-config.clamp_x),
593                             player_pos.x - SCREEN_WIDTH * config.clamp_x);
594
595       cached_translation.x = clamp(cached_translation.x,
596                                    player_pos.x - SCREEN_WIDTH * (1-config.clamp_x),
597                                    player_pos.x - SCREEN_WIDTH * config.clamp_x);
598     }
599   }
600
601   keep_in_bounds(translation);
602   keep_in_bounds(cached_translation);
603 }
604
605 void
606 Camera::update_scroll_autoscroll(float elapsed_time)
607 {
608   Player* player = sector->player;
609   if(player->is_dying())
610     return;
611
612   translation = autoscroll_walker->advance(elapsed_time);
613
614   keep_in_bounds(translation);
615 }
616
617 void
618 Camera::update_scroll_to(float elapsed_time)
619 {
620   scroll_to_pos += elapsed_time * scrollspeed;
621   if(scroll_to_pos >= 1.0) {
622     mode = MANUAL;
623     translation = scroll_goal;
624     return;
625   }
626
627   translation = scroll_from + (scroll_goal - scroll_from) * scroll_to_pos;
628 }
629
630 Vector
631 Camera::get_center() const {
632   return translation + Vector(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2);
633 }
634
635 /* EOF */