restore trunk
[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/3 * 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     // TODO...
357   }
358
359   if(ymode != 0 && config.clamp_y > 0) {
360     translation.y = clamp(translation.y,
361         player_pos.y - SCREEN_HEIGHT * (1-config.clamp_y),
362         player_pos.y - SCREEN_HEIGHT * config.clamp_y);
363   }
364
365   /****** Horizontal scrolling part *******/
366
367   if(xmode == 1) {
368     translation.x = player_pos.x - SCREEN_WIDTH * config.target_x;
369   }
370   if(xmode == 2) {
371     // our camera is either in leftscrolling, rightscrolling or
372     // nonscrollingmode.
373     //
374     // when suddenly changing directions while scrolling into the other
375     // direction abort scrolling, since tux might be going left/right at a
376     // relatively small part of the map (like when jumping upwards)
377
378     // Find out direction in which the player moves
379     LookaheadMode walkDirection;
380     if (player_delta.x < -EPSILON) walkDirection = LOOKAHEAD_LEFT;
381     else if (player_delta.x > EPSILON) walkDirection = LOOKAHEAD_RIGHT;
382     else if (player->dir == ::LEFT) walkDirection = LOOKAHEAD_LEFT;
383     else walkDirection = LOOKAHEAD_RIGHT;
384
385     float LEFTEND, RIGHTEND;
386     if(config.sensitive_x > 0) {
387       LEFTEND = SCREEN_WIDTH * config.sensitive_x;
388       RIGHTEND = SCREEN_WIDTH * (1-config.sensitive_x);
389     } else {
390       LEFTEND = SCREEN_WIDTH;
391       RIGHTEND = 0;
392     }
393
394     if(lookahead_mode == LOOKAHEAD_NONE) {
395       /* if we're undecided then look if we crossed the left or right
396        * "sensitive" area */
397       if(player_pos.x < translation.x + LEFTEND) {
398         lookahead_mode = LOOKAHEAD_LEFT;
399       } else if(player_pos.x > translation.x + RIGHTEND) {
400         lookahead_mode = LOOKAHEAD_RIGHT;
401       }
402       /* at the ends of a level it's obvious which way we will go */
403       if(player_pos.x < SCREEN_WIDTH*0.5) {
404         lookahead_mode = LOOKAHEAD_RIGHT;
405       } else if(player_pos.x >= sector->get_width() - SCREEN_WIDTH*0.5) {
406         lookahead_mode = LOOKAHEAD_LEFT;
407       }
408
409       changetime = -1;
410     } else if(lookahead_mode != walkDirection) {
411       /* player changed direction while camera was scrolling...
412        * he has to do this for a certain time to add robustness against
413        * sudden changes */
414       if(changetime < 0) {
415         changetime = game_time;
416       } else if(game_time - changetime > config.dirchange_time) {
417         if(lookahead_mode == LOOKAHEAD_LEFT &&
418            player_pos.x > translation.x + RIGHTEND) {
419           lookahead_mode = LOOKAHEAD_RIGHT;
420         } else if(lookahead_mode == LOOKAHEAD_RIGHT &&
421                   player_pos.x < translation.x + LEFTEND) {
422           lookahead_mode = LOOKAHEAD_LEFT;
423         } else {
424           lookahead_mode = LOOKAHEAD_NONE;
425         }
426       }
427     } else {
428       changetime = -1;
429     }
430
431     LEFTEND = SCREEN_WIDTH * config.edge_x;
432     RIGHTEND = SCREEN_WIDTH * (1-config.edge_x);
433
434     // calculate our scroll target depending on scroll mode
435     float target_x;
436     if(lookahead_mode == LOOKAHEAD_LEFT)
437       target_x = player_pos.x - RIGHTEND;
438     else if(lookahead_mode == LOOKAHEAD_RIGHT)
439       target_x = player_pos.x - LEFTEND;
440     else
441       target_x = translation.x;
442
443     // that's the distance we would have to travel to reach target_x
444     float delta_x = translation.x - target_x;
445     // the speed we'd need to travel to reach target_x in this frame
446     float speed_x = delta_x / elapsed_time;
447
448     // limit our speed
449     float player_speed_x = player_delta.x / elapsed_time;
450     float maxv = config.max_speed_x + (fabsf(player_speed_x * config.dynamic_max_speed_x));
451     speed_x = clamp(speed_x, -maxv, maxv);
452
453     // If player is peeking scroll in that direction. Fast.
454     if(player->peeking_direction() == ::LEFT) {
455       speed_x = config.max_speed_x;
456     }
457     if(player->peeking_direction() == ::RIGHT) {
458       speed_x = -config.max_speed_x;
459     }
460
461     // apply scrolling
462     translation.x -= speed_x * elapsed_time;
463   }
464   if(xmode == 3) {
465     float halfsize = config.kirby_rectsize_x * 0.5f;
466     translation.x = clamp(translation.x,
467         player_pos.x - SCREEN_WIDTH * (0.5f + halfsize),
468         player_pos.x - SCREEN_WIDTH * (0.5f - halfsize));
469   }
470   if(xmode == 4) {
471     float LEFTEND = SCREEN_WIDTH * config.edge_x;
472     float RIGHTEND = SCREEN_WIDTH * (1 - config.edge_x);
473
474     if (player_delta.x < -EPSILON) {
475       // walking left
476       lookahead_pos -= player_delta.x * config.dynamic_speed_sm;
477
478       if(lookahead_pos > RIGHTEND) {
479         lookahead_pos = RIGHTEND;
480       }
481     } else if (player_delta.x > EPSILON) {
482       // walking right
483       lookahead_pos -= player_delta.x * config.dynamic_speed_sm;
484       if(lookahead_pos < LEFTEND) {
485         lookahead_pos = LEFTEND;
486       }
487     }
488
489     if(player->peeking_direction() == ::LEFT) {
490       lookahead_pos += config.max_speed_x * elapsed_time * 3.0f;
491     } else if(player->peeking_direction() == ::RIGHT) {
492       lookahead_pos -= config.max_speed_x * elapsed_time * 3.0f;
493     }
494
495     // adjust for level ends
496     if (player_pos.x < LEFTEND) {
497       lookahead_pos = LEFTEND;
498     }
499     if (player_pos.x > sector->get_width() - LEFTEND) {
500       lookahead_pos = RIGHTEND;
501     }
502
503     translation.x = player_pos.x - lookahead_pos;
504   }
505
506   if(xmode != 0 && config.clamp_x > 0) {
507     translation.x = clamp(translation.x,
508         player_pos.x - SCREEN_WIDTH * (1-config.clamp_x),
509         player_pos.x - SCREEN_WIDTH * config.clamp_x);
510   }
511
512   keep_in_bounds(translation);
513 }
514
515 void
516 Camera::update_scroll_autoscroll(float elapsed_time)
517 {
518   Player* player = sector->player;
519   if(player->is_dying())
520     return;
521
522   translation = autoscroll_walker->advance(elapsed_time);
523
524   keep_in_bounds(translation);
525 }
526
527 void
528 Camera::update_scroll_to(float elapsed_time)
529 {
530   scroll_to_pos += elapsed_time * scrollspeed;
531   if(scroll_to_pos >= 1.0) {
532     mode = MANUAL;
533     translation = scroll_goal;
534     return;
535   }
536
537   translation = scroll_from + (scroll_goal - scroll_from) * scroll_to_pos;
538 }