Ed <icelus2k5@gmail.com>'s peeking patch
[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 /* this is the fractional distance toward the peek
43    position to move each frame; lower is slower,
44    0 is never get there, 1 is instant */
45 static const float PEEK_ARRIVE_RATIO = 0.1;
46
47 class CameraConfig
48 {
49 public:
50   // 0 = No, 1 = Fix, 2 = Mario/Yoshi, 3 = Kirby
51   int ymode;
52   // as above, 4 = super metroid like
53   int xmode;
54   float kirby_rectsize_x;
55   float kirby_rectsize_y;
56   // where to fix the player (used for Yoshi and Fix camera)
57   float target_y;
58   float target_x;
59   // maximum scrolling speed in Y direction
60   float max_speed_y;
61   float max_speed_x;
62   // factor to dynamically increase max_speed_x based on player speed
63   float dynamic_max_speed_x;
64
65   // time the player has to face into the other direction before we assume a
66   // changed direction
67   float dirchange_time;
68   // edge_x
69   float edge_x;
70   // when too change from noscroll mode back to lookahead left/right mode
71   // set to <= 0 to disable noscroll mode
72   float sensitive_x;
73
74   float clamp_y;
75   float clamp_x;
76
77   float dynamic_speed_sm;
78
79   CameraConfig() {
80     xmode = 1;
81     ymode = 1;
82     target_x = .5f;
83     target_y = 2.f/3.f;
84     max_speed_y = 140;
85     max_speed_x = 130;
86     clamp_x = 1.f/6.f;
87     clamp_y = 1.f/6.f;
88     kirby_rectsize_x = 0.2f;
89     kirby_rectsize_y = 0.34f;
90     edge_x = 1.f/3.f;
91     sensitive_x = 1.f/4.f;
92     dynamic_max_speed_x = 1.0;
93     dirchange_time = 0.2f;
94     dynamic_speed_sm = 1.0f;
95   }
96
97   void load(const std::string& filename)
98   {
99     lisp::Parser parser;
100     const lisp::Lisp* root = parser.parse(filename);
101     const lisp::Lisp* camconfig = root->get_lisp("camera-config");
102     if(camconfig == NULL)
103       throw std::runtime_error("file is not a camera config file.");
104
105     camconfig->get("xmode", xmode);
106     camconfig->get("ymode", ymode);
107     camconfig->get("target-x", target_x);
108     camconfig->get("target-y", target_y);
109     camconfig->get("max-speed-x", max_speed_x);
110     camconfig->get("max-speed-y", max_speed_y);
111     camconfig->get("dynamic-max-speed-x", dynamic_max_speed_x);
112     camconfig->get("dirchange-time", dirchange_time);
113     camconfig->get("clamp-x", clamp_x);
114     camconfig->get("clamp-y", clamp_y);
115     camconfig->get("kirby-rectsize-x", kirby_rectsize_x);
116     camconfig->get("kirby-rectsize-y", kirby_rectsize_y);
117     camconfig->get("edge-x", edge_x);
118     camconfig->get("sensitive-x", sensitive_x);
119     camconfig->get("dynamic-speed-sm", dynamic_speed_sm);
120   }
121 };
122
123 Camera::Camera(Sector* newsector, std::string name)
124   : mode(NORMAL), sector(newsector), lookahead_mode(LOOKAHEAD_NONE)
125 {
126   this->name = name;
127   config = new CameraConfig();
128   reload_config();
129 }
130
131 Camera::~Camera()
132 {
133   delete config;
134 }
135
136 void
137 Camera::expose(HSQUIRRELVM vm, SQInteger table_idx)
138 {
139   if(name.empty()) return;
140   Scripting::Camera* interface = new Scripting::Camera(this);
141   expose_object(vm, table_idx, interface, name, true);
142 }
143
144 void
145 Camera::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
146 {
147   if(name.empty()) return;
148   Scripting::unexpose_object(vm, table_idx, name);
149 }
150
151 void
152 Camera::draw(DrawingContext& )
153 {
154 }
155
156 const Vector&
157 Camera::get_translation() const
158 {
159   return translation;
160 }
161
162 void
163 Camera::parse(const lisp::Lisp& reader)
164 {
165   std::string modename;
166
167   reader.get("mode", modename);
168   if(modename == "normal") {
169     mode = NORMAL;
170   } else if(modename == "autoscroll") {
171     mode = AUTOSCROLL;
172
173     const lisp::Lisp* pathLisp = reader.get_lisp("path");
174     if(pathLisp == NULL)
175       throw std::runtime_error("No path specified in autoscroll camera.");
176
177     autoscroll_path.reset(new Path());
178     autoscroll_path->read(*pathLisp);
179     autoscroll_walker.reset(new PathWalker(autoscroll_path.get()));
180   } else if(modename == "manual") {
181     mode = MANUAL;
182   } else {
183     std::stringstream str;
184     str << "invalid camera mode '" << modename << "'found in worldfile.";
185     throw std::runtime_error(str.str());
186   }
187 }
188
189 void
190 Camera::write(lisp::Writer& writer)
191 {
192   writer.start_list("camera");
193
194   if(mode == NORMAL) {
195     writer.write_string("mode", "normal");
196   } else if(mode == AUTOSCROLL) {
197     writer.write_string("mode", "autoscroll");
198     autoscroll_path->write(writer);
199   } else if(mode == MANUAL) {
200     writer.write_string("mode", "manual");
201   }
202
203   writer.end_list("camera");
204 }
205
206 void
207 Camera::reset(const Vector& tuxpos)
208 {
209   translation.x = tuxpos.x - SCREEN_WIDTH/2;
210   translation.y = tuxpos.y - SCREEN_HEIGHT/2;
211
212   shakespeed = 0;
213   shaketimer.stop();
214   keep_in_bounds(translation);
215
216   yoshi_translation = translation;
217 }
218
219 void
220 Camera::shake(float time, float x, float y)
221 {
222   shaketimer.start(time);
223   shakedepth_x = x;
224   shakedepth_y = y;
225   shakespeed = M_PI/2 / time;
226 }
227
228 void
229 Camera::scroll_to(const Vector& goal, float scrolltime)
230 {
231   scroll_from = translation;
232   scroll_goal = goal;
233   keep_in_bounds(scroll_goal);
234
235   scroll_to_pos = 0;
236   scrollspeed = 1.0 / scrolltime;
237   mode = SCROLLTO;
238 }
239
240 static const float EPSILON = .00001f;
241 static const float MAX_SPEED_Y = 140;
242
243 void
244 Camera::update(float elapsed_time)
245 {
246   switch(mode) {
247     case NORMAL:
248       update_scroll_normal(elapsed_time);
249       break;
250     case AUTOSCROLL:
251       update_scroll_autoscroll(elapsed_time);
252       break;
253     case SCROLLTO:
254       update_scroll_to(elapsed_time);
255       break;
256     default:
257       break;
258   }
259   shake();
260 }
261
262 void
263 Camera::reload_config()
264 {
265   config->load("camera.cfg");
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 = player->get_bbox().get_middle();
309   static Vector last_player_pos = player_pos;
310   Vector player_delta = player_pos - last_player_pos;
311   last_player_pos = player_pos;
312
313   // check that we don't have division by zero later
314   if(elapsed_time < EPSILON)
315     return;
316
317   /****** Vertical Scrolling part ******/
318   int xmode = config.xmode;
319   int ymode = config.ymode;
320
321   if(player->is_dying() || sector->get_height() == 19*32) {
322     ymode = 0;
323   }
324   if(player->is_dying())
325     xmode = 0;
326
327   if(ymode == 1) {
328     translation.y = player_pos.y - SCREEN_HEIGHT * config.target_y;
329   }
330   if(ymode == 2) {
331     // target_y is the high we target our scrolling at. This is not always the
332     // high of the player, but if he is jumping upwards we should use the
333     // position where he last touched the ground. (this probably needs
334     // exceptions for trampolines and similar things in the future)
335     float target_y;
336     if(player->fall_mode == Player::JUMPING)
337       target_y = player->last_ground_y + player->get_bbox().get_height();
338     else
339       target_y = player->get_bbox().p2.y;
340     target_y -= SCREEN_HEIGHT * config.target_y;
341
342     // delta_y is the distance we'd have to travel to directly reach target_y
343     float delta_y = yoshi_translation.y - target_y;
344     // speed is the speed the camera would need to reach target_y in this frame
345     float speed_y = delta_y / elapsed_time;
346
347     // limit the camera speed when jumping upwards
348     if(player->fall_mode != Player::FALLING
349         && player->fall_mode != Player::TRAMPOLINE_JUMP) {
350       speed_y = clamp(speed_y, -config.max_speed_y, config.max_speed_y);
351     }
352
353     // scroll with calculated speed
354     yoshi_translation.y -= speed_y * elapsed_time;
355     translation.y = yoshi_translation.y;
356   }
357   if(ymode == 3) {
358     float halfsize = config.kirby_rectsize_y * 0.5f;
359     translation.y = clamp(translation.y,
360         player_pos.y - SCREEN_HEIGHT * (0.5f + halfsize),
361         player_pos.y - SCREEN_HEIGHT * (0.5f - halfsize));
362   }
363   if(ymode == 4) {
364     float upperend = SCREEN_HEIGHT * config.edge_x;
365     float lowerend = SCREEN_HEIGHT * (1 - config.edge_x);
366
367     if (player_delta.y < -EPSILON) {
368       // walking left
369       lookahead_pos.y -= player_delta.y * config.dynamic_speed_sm;
370
371       if(lookahead_pos.y > lowerend) {
372         lookahead_pos.y = lowerend;
373       }
374     } else if (player_delta.y > EPSILON) {
375       // walking right
376       lookahead_pos.y -= player_delta.y * config.dynamic_speed_sm;
377       if(lookahead_pos.y < upperend) {
378         lookahead_pos.y = upperend;
379       }
380     }
381
382     // adjust for level ends
383     if (player_pos.y < upperend) {
384       lookahead_pos.y = upperend;
385     }
386     if (player_pos.y > sector->get_width() - upperend) {
387       lookahead_pos.y = lowerend;
388     }
389
390     translation.y = player_pos.y - lookahead_pos.y;
391   }
392
393   if(ymode != 0) {
394     float top_edge, bottom_edge;
395     if(config.clamp_y <= 0) {
396       top_edge = 0;
397       bottom_edge = SCREEN_HEIGHT;
398     } else {
399       top_edge = SCREEN_HEIGHT*config.clamp_y;
400       bottom_edge = SCREEN_HEIGHT*(1-config.clamp_y);
401     }
402
403     float peek_to = 0;
404     float translation_compensation = player_pos.y - translation.y;
405
406     if(player->peeking_direction() == ::UP) {
407       peek_to = bottom_edge - translation_compensation;
408     } else if(player->peeking_direction() == ::DOWN) {
409       peek_to = top_edge - translation_compensation;
410     }
411
412     float peek_move = (peek_to - peek_pos.y) * PEEK_ARRIVE_RATIO;
413     if(fabs(peek_move) < 1.0) {
414       peek_move = 0.0;
415     }
416
417     peek_pos.y += peek_move;
418
419     translation.y -= peek_pos.y;
420
421     if(config.clamp_y > 0) {
422       translation.y = clamp(translation.y,
423                             player_pos.y - SCREEN_HEIGHT * (1-config.clamp_y),
424                             player_pos.y - SCREEN_HEIGHT * config.clamp_y);
425       if(ymode == 2) {
426         yoshi_translation.y = clamp(yoshi_translation.y,
427                                     player_pos.y - SCREEN_HEIGHT * (1-config.clamp_y),
428                                     player_pos.y - SCREEN_HEIGHT * config.clamp_y);
429       }
430     }
431   }
432
433   /****** Horizontal scrolling part *******/
434
435   if(xmode == 1) {
436     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 < yoshi_translation.x + LEFTEND) {
466         lookahead_mode = LOOKAHEAD_LEFT;
467       } else if(player_pos.x > yoshi_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 > yoshi_translation.x + RIGHTEND) {
487           lookahead_mode = LOOKAHEAD_RIGHT;
488         } else if(lookahead_mode == LOOKAHEAD_RIGHT &&
489                   player_pos.x < yoshi_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 = yoshi_translation.x;
510
511     // that's the distance we would have to travel to reach target_x
512     float delta_x = yoshi_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     yoshi_translation.x -= speed_x * elapsed_time;
523     translation.x = yoshi_translation.x;
524   }
525   if(xmode == 3) {
526     float halfsize = config.kirby_rectsize_x * 0.5f;
527     translation.x = clamp(translation.x,
528         player_pos.x - SCREEN_WIDTH * (0.5f + halfsize),
529         player_pos.x - SCREEN_WIDTH * (0.5f - halfsize));
530   }
531   if(xmode == 4) {
532     float LEFTEND = SCREEN_WIDTH * config.edge_x;
533     float RIGHTEND = SCREEN_WIDTH * (1 - config.edge_x);
534
535     if (player_delta.x < -EPSILON) {
536       // walking left
537       lookahead_pos.x -= player_delta.x * config.dynamic_speed_sm;
538       if(lookahead_pos.x > RIGHTEND) {
539         lookahead_pos.x = RIGHTEND;
540       }
541
542     } else if (player_delta.x > EPSILON) {
543       // walking right
544       lookahead_pos.x -= player_delta.x * config.dynamic_speed_sm;
545       if(lookahead_pos.x < LEFTEND) {
546           lookahead_pos.x = LEFTEND;
547       }
548     }
549
550     // adjust for level ends
551     if (player_pos.x < LEFTEND) {
552       lookahead_pos.x = LEFTEND;
553     }
554     if (player_pos.x > sector->get_width() - LEFTEND) {
555       lookahead_pos.x = RIGHTEND;
556     }
557
558     translation.x = player_pos.x - lookahead_pos.x;
559   }
560
561   if(xmode != 0) {
562     float left_edge, right_edge;
563     if(config.clamp_x <= 0) {
564       left_edge = 0;
565       right_edge = SCREEN_WIDTH;
566     } else {
567       left_edge = SCREEN_WIDTH*config.clamp_x;
568       right_edge = SCREEN_WIDTH*(1-config.clamp_x);
569     }
570
571     float peek_to = 0;
572     float translation_compensation = player_pos.x - translation.x;
573
574     if(player->peeking_direction() == ::LEFT) {
575       peek_to = right_edge - translation_compensation;
576     } else if(player->peeking_direction() == ::RIGHT) {
577       peek_to = left_edge - translation_compensation;
578     }
579
580     float peek_move = (peek_to - peek_pos.x) * PEEK_ARRIVE_RATIO;
581     if(fabs(peek_move) < 1.0) {
582       peek_move = 0.0;
583     }
584
585     peek_pos.x += peek_move;
586
587     translation.x -= peek_pos.x;
588
589     if(config.clamp_x > 0) {
590       translation.x = clamp(translation.x,
591                             player_pos.x - SCREEN_WIDTH * (1-config.clamp_x),
592                             player_pos.x - SCREEN_WIDTH * config.clamp_x);
593       if(xmode == 2) {
594         yoshi_translation.x = clamp(yoshi_translation.x,
595                                     player_pos.x - SCREEN_WIDTH * (1-config.clamp_x),
596                                     player_pos.x - SCREEN_WIDTH * config.clamp_x);
597       }
598     }
599   }
600
601   keep_in_bounds(translation);
602   if(xmode == 2 || ymode == 2) {
603     keep_in_bounds(yoshi_translation);
604   }
605 }
606
607 void
608 Camera::update_scroll_autoscroll(float elapsed_time)
609 {
610   Player* player = sector->player;
611   if(player->is_dying())
612     return;
613
614   translation = autoscroll_walker->advance(elapsed_time);
615
616   keep_in_bounds(translation);
617 }
618
619 void
620 Camera::update_scroll_to(float elapsed_time)
621 {
622   scroll_to_pos += elapsed_time * scrollspeed;
623   if(scroll_to_pos >= 1.0) {
624     mode = MANUAL;
625     translation = scroll_goal;
626     return;
627   }
628
629   translation = scroll_from + (scroll_goal - scroll_from) * scroll_to_pos;
630 }
631
632 Vector
633 Camera::get_center() const {
634   return translation + Vector(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2);
635 }
636