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