experimental code to influence camera, adjusted some parameters, tried to improve...
[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 namespace {
43   enum CameraStyle { CameraStyleYI, CameraStyleKD, CameraStyleEXP };
44   const CameraStyle cameraStyle = CameraStyleEXP;
45 }
46
47 class CameraConfig
48 {
49 public:
50   // 0 = No, 1 = Fix, 2 = Mario/Yoshi, 3 = Kirby, 4 = inverse rubber
51   int ymode;
52   int xmode;
53   float kirby_rectsize_x;
54   float kirby_rectsize_y;
55   // where to fix the player (used for Yoshi and Fix camera)
56   float target_y;
57   float target_x;
58   // maximum scrolling speed in Y direction
59   float max_speed_y;
60   float max_speed_x;
61   // factor to dynamically increase max_speed_x based on player speed
62   float dynamic_max_speed_x;
63   // edge_x
64   float edge_x;
65   float sensitive_x;
66
67   float clamp_y;
68   float clamp_x;
69
70   CameraConfig() {
71     xmode = 1;
72     ymode = 1;
73     target_x = .5f;
74     target_y = 2.f/3.f;
75     max_speed_y = 140;
76     max_speed_x = 130;
77     clamp_x = 1.f/6.f;
78     clamp_y = 1.f/6.f;
79     kirby_rectsize_x = 0.2f;
80     kirby_rectsize_y = 0.34f;
81     edge_x = 1.f/3.f;
82     sensitive_x = 1.f/4.f;
83         dynamic_max_speed_x = 1.0;
84   }
85
86   void load(const std::string& filename)
87   {
88     lisp::Parser parser;
89     const lisp::Lisp* root = parser.parse(filename);
90     const lisp::Lisp* camconfig = root->get_lisp("camera-config");
91     if(camconfig == NULL)
92       throw std::runtime_error("file is not a camera config file.");
93
94     camconfig->get("xmode", xmode);
95     camconfig->get("ymode", ymode);
96     camconfig->get("target-x", target_x);
97     camconfig->get("target-y", target_y);
98     camconfig->get("max-speed-x", max_speed_x);
99     camconfig->get("max-speed-y", max_speed_y);
100         camconfig->get("dynamic-max-speed-x", dynamic_max_speed_x);
101     camconfig->get("clamp-x", clamp_x);
102     camconfig->get("clamp-y", clamp_y);
103     camconfig->get("kirby-rectsize-x", kirby_rectsize_x);
104     camconfig->get("kirby-rectsize-y", kirby_rectsize_y);
105     camconfig->get("edge-x", edge_x);
106     camconfig->get("sensitive-x", sensitive_x);
107   }
108 };
109
110 Camera::Camera(Sector* newsector, std::string name)
111   : mode(NORMAL), sector(newsector), scrollchange(NONE)
112 {
113   this->name = name;
114   config = new CameraConfig();
115   reload_config();
116 }
117
118 Camera::~Camera()
119 {
120   delete config;
121 }
122
123 void
124 Camera::expose(HSQUIRRELVM vm, SQInteger table_idx)
125 {
126   if(name.empty()) return;
127   Scripting::Camera* interface = new Scripting::Camera(this);
128   expose_object(vm, table_idx, interface, name, true);
129 }
130
131 void
132 Camera::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
133 {
134   if(name.empty()) return;
135   Scripting::unexpose_object(vm, table_idx, name);
136 }
137
138 void
139 Camera::draw(DrawingContext& )
140 {
141 }
142
143 const Vector&
144 Camera::get_translation() const
145 {
146   return translation;
147 }
148
149 void
150 Camera::parse(const lisp::Lisp& reader)
151 {
152   std::string modename;
153
154   reader.get("mode", modename);
155   if(modename == "normal") {
156     mode = NORMAL;
157   } else if(modename == "autoscroll") {
158     mode = AUTOSCROLL;
159
160     const lisp::Lisp* pathLisp = reader.get_lisp("path");
161     if(pathLisp == NULL)
162       throw std::runtime_error("No path specified in autoscroll camera.");
163
164     autoscroll_path.reset(new Path());
165     autoscroll_path->read(*pathLisp);
166     autoscroll_walker.reset(new PathWalker(autoscroll_path.get()));
167   } else if(modename == "manual") {
168     mode = MANUAL;
169   } else {
170     std::stringstream str;
171     str << "invalid camera mode '" << modename << "'found in worldfile.";
172     throw std::runtime_error(str.str());
173   }
174 }
175
176 void
177 Camera::write(lisp::Writer& writer)
178 {
179   writer.start_list("camera");
180
181   if(mode == NORMAL) {
182     writer.write_string("mode", "normal");
183   } else if(mode == AUTOSCROLL) {
184     writer.write_string("mode", "autoscroll");
185     autoscroll_path->write(writer);
186   } else if(mode == MANUAL) {
187     writer.write_string("mode", "manual");
188   }
189
190   writer.end_list("camera");
191 }
192
193 void
194 Camera::reset_kd(const Vector& tuxpos)
195 {
196   translation.x = tuxpos.x - (SCREEN_WIDTH * 0.5);
197   translation.y = tuxpos.y - (SCREEN_HEIGHT * 0.5);
198
199   shakespeed = 0;
200   shaketimer.stop();
201   keep_in_bounds(translation);
202 }
203
204
205 void
206 Camera::reset(const Vector& tuxpos)
207 {
208   if (cameraStyle == CameraStyleKD) {
209     reset_kd(tuxpos);
210     return;
211   }
212
213   translation.x = tuxpos.x - SCREEN_WIDTH/3 * 2;
214   translation.y = tuxpos.y - SCREEN_HEIGHT/2;
215   shakespeed = 0;
216   shaketimer.stop();
217   keep_in_bounds(translation);
218 }
219
220 void
221 Camera::shake(float time, float x, float y)
222 {
223   shaketimer.start(time);
224   shakedepth_x = x;
225   shakedepth_y = y;
226   shakespeed = M_PI/2 / time;
227 }
228
229 void
230 Camera::scroll_to(const Vector& goal, float scrolltime)
231 {
232   scroll_from = translation;
233   scroll_goal = goal;
234   keep_in_bounds(scroll_goal);
235
236   scroll_to_pos = 0;
237   scrollspeed = 1.0 / scrolltime;
238   mode = SCROLLTO;
239 }
240
241 static const float EPSILON = .00001f;
242 static const float MAX_SPEED_Y = 140;
243
244 void
245 Camera::update(float elapsed_time)
246 {
247   switch(mode) {
248     case NORMAL:
249       update_scroll_normal(elapsed_time);
250       break;
251     case AUTOSCROLL:
252       update_scroll_autoscroll(elapsed_time);
253       break;
254     case SCROLLTO:
255       update_scroll_to(elapsed_time);
256       break;
257     default:
258       break;
259   }
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_kd(float elapsed_time)
305 {
306   // make sure some time has actually passed
307   if(elapsed_time < EPSILON)
308     return;
309
310   // make sure we have an active player
311   assert(sector != NULL);
312   Player* player = sector->player;
313   Vector playerCenter = player->get_bbox().get_middle();
314
315   // If player is peeking, scroll in that direction
316   if (player->peeking_direction() == ::LEFT) {
317     translation.x -= elapsed_time * 128.0f;
318   } else if (player->peeking_direction() == ::RIGHT) {
319     translation.x += elapsed_time * 128.0f;
320   }
321
322   // keep player within a small box, centered on the screen (vertical part)
323   bool do_y_scrolling = true;
324   if (player->is_dying() || sector->get_height() == 19*32)
325     do_y_scrolling = false;
326
327   if (do_y_scrolling) {
328     translation.y = clamp(translation.y,
329         player->get_bbox().p1.y - SCREEN_HEIGHT * (0.5f - 0.17f),
330         player->get_bbox().p2.y - SCREEN_HEIGHT * (0.5f + 0.17f));
331   }
332
333   // keep player within a small box, centered on the screen (horizontal part)
334   translation.x = clamp(translation.x,
335       player->get_bbox().p1.x - SCREEN_WIDTH * (0.5f - 0.1f),
336       player->get_bbox().p2.x - SCREEN_WIDTH * (0.5f + 0.1f));
337
338   // make sure camera doesn't point outside level borders
339   keep_in_bounds(translation);
340
341   // handle shaking of camera (if applicable)
342   shake();
343 }
344
345 void
346 Camera::update_scroll_normal_exp(float elapsed_time)
347 {
348   const CameraConfig& config = *(this->config);
349   Player* player = sector->player;
350   const Vector& player_pos = player->get_bbox().get_middle();
351   static Vector last_player_pos = player_pos;
352   Vector player_delta = player_pos - last_player_pos;
353
354   // check that we don't have division by zero later
355   if(elapsed_time < EPSILON)
356     return;
357
358   /****** Vertical Scrolling part ******/
359   int ymode = config.ymode;
360
361   if(player->is_dying() || sector->get_height() == 19*32) {
362     ymode = 0;
363   }
364
365   if(ymode == 1) {
366     translation.y = player_pos.y - SCREEN_HEIGHT * config.target_y;
367   }
368   if(ymode == 2) {
369     // target_y is the high we target our scrolling at. This is not always the
370     // high of the player, but if he is jumping upwards we should use the
371     // position where he last touched the ground. (this probably needs
372     // exceptions for trampolines and similar things in the future)
373     float target_y;
374     if(player->fall_mode == Player::JUMPING)
375       target_y = player->last_ground_y + player->get_bbox().get_height();
376     else
377       target_y = player->get_bbox().p2.y;
378     target_y -= SCREEN_HEIGHT * config.target_y;
379
380     // delta_y is the distance we'd have to travel to directly reach target_y
381     float delta_y = translation.y - target_y;
382     // speed is the speed the camera would need to reach target_y in this frame
383     float speed_y = delta_y / elapsed_time;
384
385     // limit the camera speed when jumping upwards
386     if(player->fall_mode != Player::FALLING
387         && player->fall_mode != Player::TRAMPOLINE_JUMP) {
388       speed_y = clamp(speed_y, -config.max_speed_y, config.max_speed_y);
389     }
390
391     // scroll with calculated speed
392     translation.y -= speed_y * elapsed_time;
393   }
394   if(ymode == 3) {
395     float halfsize = config.kirby_rectsize_y * 0.5f;
396     translation.y = clamp(translation.y,
397         player_pos.y - SCREEN_HEIGHT * (0.5f - halfsize),
398         player_pos.y - SCREEN_HEIGHT * (0.5f + halfsize));
399   }
400   if(ymode == 4) {
401     // TODO...
402   }
403
404   if(ymode != 0 && config.clamp_y > 0) {
405     translation.y = clamp(translation.y,
406         player_pos.y - SCREEN_HEIGHT * config.clamp_y,
407         player_pos.y - SCREEN_HEIGHT * (1-config.clamp_y));
408   }
409
410   /****** Horizontal scrolling part *******/
411
412   if(config.xmode == 1) {
413     translation.x = player_pos.x - SCREEN_WIDTH * config.target_x;
414   }
415   if(config.xmode == 2) {
416     // our camera is either in leftscrolling, rightscrolling or
417     // nonscrollingmode.
418     //
419     // when suddenly changing directions while scrolling into the other
420     // direction abort scrolling, since tux might be going left/right at a
421     // relatively small part of the map (like when jumping upwards)
422
423     // Find out direction in which the player walks
424     LeftRightScrollChange walkDirection;
425     if (player->physic.get_velocity_x() < -EPSILON) walkDirection = LEFT;
426     else if (player->physic.get_velocity_x() > EPSILON) walkDirection = RIGHT;
427     else if (player->dir == ::LEFT) walkDirection = LEFT;
428     else walkDirection = RIGHT;
429
430     float LEFTEND = SCREEN_WIDTH * config.sensitive_x;
431     float RIGHTEND = SCREEN_WIDTH * (1-config.sensitive_x);
432
433     if((walkDirection == LEFT && scrollchange == RIGHT)
434         || (walkDirection == RIGHT && scrollchange == LEFT))
435       scrollchange = NONE;
436     // when in left 1/3rd of screen scroll left
437     if(player_pos.x < translation.x + LEFTEND)
438       scrollchange = LEFT;
439     // scroll right when in right 1/3rd of screen
440     else if(player_pos.x > translation.x + RIGHTEND)
441       scrollchange = RIGHT;
442
443     LEFTEND = SCREEN_WIDTH * config.edge_x;
444     RIGHTEND = SCREEN_HEIGHT * (1- config.edge_x);
445
446     // calculate our scroll target depending on scroll mode
447     float target_x;
448     if(scrollchange == LEFT)
449       target_x = player->get_bbox().get_middle().x - RIGHTEND;
450     else if(scrollchange == RIGHT)
451       target_x = player->get_bbox().get_middle().x - LEFTEND;
452     else
453       target_x = translation.x;
454
455     // that's the distance we would have to travel to reach target_x
456     float delta_x = translation.x - target_x;
457     // the speed we'd need to travel to reach target_x in this frame
458     float speed_x = delta_x / elapsed_time;
459
460     // limit our speed
461     float maxv = config.max_speed_x + (fabsf(player->physic.get_velocity_x() * config.dynamic_max_speed_x));
462     speed_x = clamp(speed_x, -maxv, maxv);
463
464     // If player is peeking scroll in that direction. Fast.
465     if(player->peeking_direction() == ::LEFT) {
466       speed_x = config.max_speed_x;
467     }
468     if(player->peeking_direction() == ::RIGHT) {
469       speed_x = -config.max_speed_x;
470     }
471
472     // apply scrolling
473     translation.x -= speed_x * elapsed_time;
474   }
475   if(config.xmode == 3) {
476     float halfsize = config.kirby_rectsize_x * 0.5f;
477     translation.x = clamp(translation.x,
478         player_pos.x - SCREEN_WIDTH * (0.5f - halfsize),
479         player_pos.x - SCREEN_WIDTH * (0.5f + halfsize));
480   }
481   if(config.xmode == 4) {
482     // TODO...
483   }
484
485   if(config.xmode != 0 && config.clamp_x > 0) {
486     translation.x = clamp(translation.x,
487         player_pos.x - SCREEN_WIDTH * config.clamp_x,
488         player_pos.x - SCREEN_WIDTH * (1-config.clamp_x));
489   }
490
491   keep_in_bounds(translation);
492   shake();
493
494 #if 0
495   static const Vector camera_speed = Vector(300, 100);
496
497   Player* player = sector->player;
498   const Vector& player_pos = player->get_bbox().get_middle();
499   static Vector last_player_pos = player_pos;
500   static Vector camera_delta = Vector(0, 0);
501
502   (void) elapsed_time;
503
504   Vector player_delta_x = player_pos - last_player_pos;
505   last_player_pos = player_pos;
506
507   Vector camera_delta_antic = Vector(0, 0) + player_delta_x * 25;
508   Vector myspeed = (camera_delta_antic - camera_delta) / elapsed_time;
509   myspeed.x = clamp(-camera_speed.x, camera_speed.x, myspeed.x);
510   myspeed.y = clamp(-camera_speed.y, camera_speed.y, myspeed.y);
511
512   camera_delta += myspeed * elapsed_time;
513
514   translation.x = camera_delta.x + player_pos.x - 0.5f * SCREEN_WIDTH;
515   translation.y = camera_delta.y + player_pos.y - 0.5f * SCREEN_HEIGHT;
516
517   keep_in_bounds(translation);
518   shake();
519 #endif
520 }
521
522 void
523 Camera::update_scroll_normal(float elapsed_time)
524 {
525   if (cameraStyle == CameraStyleEXP) {
526     update_scroll_normal_exp(elapsed_time);
527     return;
528   }
529   if (cameraStyle == CameraStyleKD) {
530     update_scroll_normal_kd(elapsed_time);
531     return;
532   }
533
534   assert(sector != 0);
535   Player* player = sector->player;
536
537   // check that we don't have division by zero later
538   if(elapsed_time < EPSILON)
539     return;
540
541   /****** Vertical Scrolling part ******/
542   bool do_y_scrolling = true;
543
544   if(player->is_dying() || sector->get_height() == 19*32)
545     do_y_scrolling = false;
546
547   if(do_y_scrolling) {
548     // target_y is the high we target our scrolling at. This is not always the
549     // high of the player, but if he is jumping upwards we should use the
550     // position where he last touched the ground. (this probably needs
551     // exceptions for trampolines and similar things in the future)
552     float target_y;
553     if(player->fall_mode == Player::JUMPING)
554       target_y = player->last_ground_y + player->get_bbox().get_height();
555     else
556       target_y = player->get_bbox().p2.y;
557
558     // delta_y is the distance we'd have to travel to directly reach target_y
559     float delta_y = translation.y - (target_y - SCREEN_HEIGHT*2/3);
560     // speed is the speed the camera would need to reach target_y in this frame
561     float speed_y = delta_y / elapsed_time;
562
563     // limit the camera speed when jumping upwards
564     if(player->fall_mode != Player::FALLING
565         && player->fall_mode != Player::TRAMPOLINE_JUMP) {
566       speed_y = clamp(speed_y, -MAX_SPEED_Y, MAX_SPEED_Y);
567     }
568
569     // finally scroll with calculated speed
570     translation.y -= speed_y * elapsed_time;
571
572     // make sure to always keep the player inside the middle 1/6 of the screen
573     translation.y = clamp(translation.y,
574         player->get_bbox().p1.y - SCREEN_HEIGHT*1/6,
575         player->get_bbox().p2.y - SCREEN_HEIGHT*5/6);
576   }
577
578   /****** Horizontal scrolling part *******/
579
580   // our camera is either in leftscrolling, rightscrolling or nonscrollingmode.
581
582   // when suddenly changing directions while scrolling into the other direction.
583   // abort scrolling, since tux might be going left/right at a relatively small
584   // part of the map (like when jumping upwards)
585
586
587   // Find out direction in which the player walks: We want to try and show a
588   // bit more of what's in front of the player and less of what's behind
589   LeftRightScrollChange walkDirection;
590   if (player->physic.get_velocity_x() < -EPSILON) walkDirection = LEFT;
591   else if (player->physic.get_velocity_x() > EPSILON) walkDirection = RIGHT;
592   else if (player->dir == ::LEFT) walkDirection = LEFT;
593   else walkDirection = RIGHT;
594
595   static const float LEFTEND = SCREEN_WIDTH*2/5;
596   static const float RIGHTEND = SCREEN_WIDTH*4/5;
597
598   if((walkDirection == LEFT && scrollchange == RIGHT)
599       || (walkDirection == RIGHT && scrollchange == LEFT))
600     scrollchange = NONE;
601   // when in left 1/3rd of screen scroll left
602   if(player->get_bbox().get_middle().x < translation.x + LEFTEND - 16
603       && do_backscrolling)
604     scrollchange = LEFT;
605   // scroll right when in right 1/3rd of screen
606   else if(player->get_bbox().get_middle().x > translation.x + RIGHTEND + 16)
607     scrollchange = RIGHT;
608
609   // calculate our scroll target depending on scroll mode
610   float target_x;
611   if(scrollchange == LEFT)
612     target_x = player->get_bbox().get_middle().x - RIGHTEND;
613   else if(scrollchange == RIGHT)
614     target_x = player->get_bbox().get_middle().x - LEFTEND;
615   else
616     target_x = translation.x;
617
618   // that's the distance we would have to travel to reach target_x
619   float delta_x = translation.x - target_x;
620   // the speed we'd need to travel to reach target_x in this frame
621   float speed_x = delta_x / elapsed_time;
622
623   // limit our speed
624   float maxv = 130 + (fabsf(player->physic.get_velocity_x() * 1.3));
625   if(speed_x > maxv)
626     speed_x = maxv;
627   else if(speed_x < -maxv)
628     speed_x = -maxv;
629
630   // If player is peeking scroll in that direction. Fast.
631   if( player->peeking_direction() == ::LEFT ){
632         speed_x = maxv;
633   }
634   if( player->peeking_direction() == ::RIGHT ){
635         speed_x = -maxv;
636   }
637
638   // apply scrolling
639   translation.x -= speed_x * elapsed_time;
640
641   // make sure to always keep the player inside the middle 4/6 of the screen
642   translation.x = std::min(player->get_bbox().p1.x - SCREEN_WIDTH*1/6, translation.x);
643   translation.x = std::max(player->get_bbox().p2.x - SCREEN_WIDTH*5/6, translation.x);
644
645   keep_in_bounds(translation);
646   shake();
647 }
648
649 void
650 Camera::update_scroll_autoscroll(float elapsed_time)
651 {
652   Player* player = sector->player;
653   if(player->is_dying())
654     return;
655
656   translation = autoscroll_walker->advance(elapsed_time);
657
658   keep_in_bounds(translation);
659   shake();
660 }
661
662 void
663 Camera::update_scroll_to(float elapsed_time)
664 {
665   scroll_to_pos += elapsed_time * scrollspeed;
666   if(scroll_to_pos >= 1.0) {
667     mode = MANUAL;
668     translation = scroll_goal;
669     return;
670   }
671
672   translation = scroll_from + (scroll_goal - scroll_from) * scroll_to_pos;
673 }