e4fd50ae739703ab84447f047f1ecdf57f39a552
[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 "scripting/camera.hpp"
29 #include "scripting/squirrel_util.hpp"
30 #include "camera.hpp"
31 #include "player.hpp"
32 #include "tilemap.hpp"
33 #include "game_session.hpp"
34 #include "sector.hpp"
35 #include "main.hpp"
36 #include "object_factory.hpp"
37 #include "log.hpp"
38 #include "path.hpp"
39 #include "path_walker.hpp"
40
41 namespace {
42   enum CameraStyle { CameraStyleYI, CameraStyleKD, CameraStyleEXP };
43   const CameraStyle cameraStyle = CameraStyleYI;
44 }
45
46 Camera::Camera(Sector* newsector, std::string name)
47   : mode(NORMAL), sector(newsector), do_backscrolling(true),
48     scrollchange(NONE)
49 {
50   this->name = name;
51 }
52
53 Camera::~Camera()
54 {
55 }
56
57 void
58 Camera::expose(HSQUIRRELVM vm, SQInteger table_idx)
59 {
60   if(name.empty()) return;
61   Scripting::Camera* interface = new Scripting::Camera(this);
62   expose_object(vm, table_idx, interface, name, true);
63 }
64
65 void
66 Camera::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
67 {
68   if(name.empty()) return;
69   Scripting::unexpose_object(vm, table_idx, name);
70 }
71
72 const Vector&
73 Camera::get_translation() const
74 {
75   return translation;
76 }
77
78 void
79 Camera::parse(const lisp::Lisp& reader)
80 {
81   std::string modename;
82
83   reader.get("mode", modename);
84   if(modename == "normal") {
85     mode = NORMAL;
86
87     do_backscrolling = true;
88     reader.get("backscrolling", do_backscrolling);
89   } else if(modename == "autoscroll") {
90     mode = AUTOSCROLL;
91
92     const lisp::Lisp* pathLisp = reader.get_lisp("path");
93     if(pathLisp == NULL)
94       throw std::runtime_error("No path specified in autoscroll camera.");
95
96     autoscroll_path.reset(new Path());
97     autoscroll_path->read(*pathLisp);
98     autoscroll_walker.reset(new PathWalker(autoscroll_path.get()));
99   } else if(modename == "manual") {
100     mode = MANUAL;
101   } else {
102     std::stringstream str;
103     str << "invalid camera mode '" << modename << "'found in worldfile.";
104     throw std::runtime_error(str.str());
105   }
106 }
107
108 void
109 Camera::write(lisp::Writer& writer)
110 {
111   writer.start_list("camera");
112
113   if(mode == NORMAL) {
114     writer.write_string("mode", "normal");
115     writer.write_bool("backscrolling", do_backscrolling);
116   } else if(mode == AUTOSCROLL) {
117     writer.write_string("mode", "autoscroll");
118     autoscroll_path->write(writer);
119   } else if(mode == MANUAL) {
120     writer.write_string("mode", "manual");
121   }
122
123   writer.end_list("camera");
124 }
125
126 void
127 Camera::reset_kd(const Vector& tuxpos)
128 {
129   translation.x = tuxpos.x - (SCREEN_WIDTH * 0.5);
130   translation.y = tuxpos.y - (SCREEN_HEIGHT * 0.5);
131
132   shakespeed = 0;
133   shaketimer.stop();
134   keep_in_bounds(translation);
135 }
136
137
138 void
139 Camera::reset(const Vector& tuxpos)
140 {
141   if (cameraStyle == CameraStyleKD) {
142     reset_kd(tuxpos);
143     return;
144   }
145
146   translation.x = tuxpos.x - SCREEN_WIDTH/3 * 2;
147   translation.y = tuxpos.y - SCREEN_HEIGHT/2;
148   shakespeed = 0;
149   shaketimer.stop();
150   keep_in_bounds(translation);
151 }
152
153 void
154 Camera::shake(float time, float x, float y)
155 {
156   shaketimer.start(time);
157   shakedepth_x = x;
158   shakedepth_y = y;
159   shakespeed = M_PI/2 / time;
160 }
161
162 void
163 Camera::scroll_to(const Vector& goal, float scrolltime)
164 {
165   scroll_from = translation;
166   scroll_goal = goal;
167   keep_in_bounds(scroll_goal);
168
169   scroll_to_pos = 0;
170   scrollspeed = 1.0 / scrolltime;
171   mode = SCROLLTO;
172 }
173
174 static const float EPSILON = .00001f;
175 static const float max_speed_y = 140;
176
177 void
178 Camera::update(float elapsed_time)
179 {
180   switch(mode) {
181     case NORMAL:
182       update_scroll_normal(elapsed_time);
183       break;
184     case AUTOSCROLL:
185       update_scroll_autoscroll(elapsed_time);
186       break;
187     case SCROLLTO:
188       update_scroll_to(elapsed_time);
189       break;
190     default:
191       break;
192   }
193 }
194
195 void
196 Camera::keep_in_bounds(Vector& translation)
197 {
198   float width = sector->get_width();
199   float height = sector->get_height();
200
201   // don't scroll before the start or after the level's end
202   if(translation.y > height - SCREEN_HEIGHT)
203     translation.y = height - SCREEN_HEIGHT;
204   if(translation.y < 0)
205     translation.y = 0;
206   if (height < SCREEN_HEIGHT)
207     translation.y = height/2.0 - SCREEN_HEIGHT/2.0;
208   if(translation.x > width - SCREEN_WIDTH)
209     translation.x = width - SCREEN_WIDTH;
210   if(translation.x < 0)
211     translation.x = 0;
212   if (width < SCREEN_WIDTH)
213     translation.x = width/2.0 - SCREEN_WIDTH/2.0;
214 }
215
216 void
217 Camera::shake()
218 {
219   if(shaketimer.started()) {
220     translation.x -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_x;
221     translation.y -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_y;
222   }
223 }
224
225 void
226 Camera::update_scroll_normal_kd(float elapsed_time)
227 {
228   // make sure some time has actually passed
229   if(elapsed_time < EPSILON) return;
230
231   // make sure we have an active player
232   assert(sector != 0);
233   Player* player = sector->player;
234   Vector playerCenter = player->get_bbox().get_middle();
235
236   // If player is peeking, scroll in that direction
237   if (player->peeking_direction() == ::LEFT) {
238         translation.x -= elapsed_time * 128.0f;
239   }
240   else if (player->peeking_direction() == ::RIGHT) {
241         translation.x += elapsed_time * 128.0f;
242   }
243
244   // keep player within a small box, centered on the screen (vertical part)
245   bool do_y_scrolling = true;
246   if (player->is_dying() || sector->get_height() == 19*32) do_y_scrolling = false;
247   if (do_y_scrolling) {
248     translation.y = std::min(player->get_bbox().p1.y - SCREEN_HEIGHT * (0.5f - 0.17f), translation.y);
249     translation.y = std::max(player->get_bbox().p2.y - SCREEN_HEIGHT * (0.5f + 0.17f), translation.y);
250   }
251
252   // keep player within a small box, centered on the screen (horizontal part)
253   translation.x = std::min(player->get_bbox().p1.x - SCREEN_WIDTH * (0.5f - 0.1f), translation.x);
254   translation.x = std::max(player->get_bbox().p2.x - SCREEN_WIDTH * (0.5f + 0.1f), translation.x);
255
256   // make sure camera doesn't point outside level borders
257   keep_in_bounds(translation);
258
259   // handle shaking of camera (if applicable)
260   shake();
261 }
262
263 template<typename T>
264 T clamp(T min, T max, T val)
265 {
266   if(val < min)
267     return min;
268   if(val > max)
269     return max;
270
271   return val;
272 }
273
274 void
275 Camera::update_scroll_normal_exp(float elapsed_time)
276 {
277   static const Vector camera_speed = Vector(300, 100);
278
279   Player* player = sector->player;
280   const Vector& player_pos = player->get_bbox().get_middle();
281   static Vector last_player_pos = player_pos;
282   static Vector camera_delta = Vector(0, 0);
283
284   (void) elapsed_time;
285
286   Vector player_delta_x = player_pos - last_player_pos;
287   last_player_pos = player_pos;
288
289   Vector camera_delta_antic = Vector(0, 0) + player_delta_x * 25;
290   Vector myspeed = (camera_delta_antic - camera_delta) / elapsed_time;
291   myspeed.x = clamp(-camera_speed.x, camera_speed.x, myspeed.x);
292   myspeed.y = clamp(-camera_speed.y, camera_speed.y, myspeed.y);
293
294   camera_delta += myspeed * elapsed_time;
295
296   translation.x = camera_delta.x + player_pos.x - 0.5f * SCREEN_WIDTH;
297   translation.y = camera_delta.y + player_pos.y - 0.5f * SCREEN_HEIGHT;
298
299   keep_in_bounds(translation);
300   shake();
301 }
302
303 void
304 Camera::update_scroll_normal(float elapsed_time)
305 {
306   if (cameraStyle == CameraStyleEXP) {
307     update_scroll_normal_exp(elapsed_time);
308     return;
309   }
310   if (cameraStyle == CameraStyleKD) {
311     update_scroll_normal_kd(elapsed_time);
312     return;
313   }
314
315   assert(sector != 0);
316   Player* player = sector->player;
317
318   // check that we don't have division by zero later
319   if(elapsed_time < EPSILON)
320     return;
321
322   /****** Vertical Scrolling part ******/
323   bool do_y_scrolling = true;
324
325   if(player->is_dying() || sector->get_height() == 19*32)
326     do_y_scrolling = false;
327
328   if(do_y_scrolling) {
329     // target_y is the high we target our scrolling at. This is not always the
330     // high of the player, but if he is jumping upwards we should use the
331     // position where he last touched the ground. (this probably needs
332     // exceptions for trampolines and similar things in the future)
333     float target_y;
334     if(player->fall_mode == Player::JUMPING)
335       target_y = player->last_ground_y + player->get_bbox().get_height();
336     else
337       target_y = player->get_bbox().p2.y;
338
339     // delta_y is the distance we'd have to travel to directly reach target_y
340     float delta_y = translation.y - (target_y - SCREEN_HEIGHT*2/3);
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       if(speed_y > max_speed_y)
348         speed_y = max_speed_y;
349       else if(speed_y < -max_speed_y)
350         speed_y = -max_speed_y;
351     }
352
353     // finally scroll with calculated speed
354     translation.y -= speed_y * elapsed_time;
355
356     // make sure to always keep the player inside the middle 1/6 of the screen
357     translation.y = std::min(player->get_bbox().p1.y - SCREEN_HEIGHT*1/6, translation.y);
358     translation.y = std::max(player->get_bbox().p2.y - SCREEN_HEIGHT*5/6, translation.y);
359   }
360
361   /****** Horizontal scrolling part *******/
362
363   // our camera is either in leftscrolling, rightscrolling or nonscrollingmode.
364
365   // when suddenly changing directions while scrolling into the other direction.
366   // abort scrolling, since tux might be going left/right at a relatively small
367   // part of the map (like when jumping upwards)
368
369
370   // Find out direction in which the player walks: We want to try and show a
371   // bit more of what's in front of the player and less of what's behind
372   LeftRightScrollChange walkDirection;
373   if (player->physic.get_velocity_x() < -EPSILON) walkDirection = LEFT;
374   else if (player->physic.get_velocity_x() > EPSILON) walkDirection = RIGHT;
375   else if (player->dir == ::LEFT) walkDirection = LEFT;
376   else walkDirection = RIGHT;
377
378
379   if((walkDirection == LEFT && scrollchange == RIGHT)
380       || (walkDirection == RIGHT && scrollchange == LEFT))
381     scrollchange = NONE;
382   // when in left 1/3rd of screen scroll left
383   if(player->get_bbox().get_middle().x < translation.x + SCREEN_WIDTH/3 - 16
384       && do_backscrolling)
385     scrollchange = LEFT;
386   // scroll right when in right 1/3rd of screen
387   else if(player->get_bbox().get_middle().x > translation.x + SCREEN_WIDTH/3*2+16)
388     scrollchange = RIGHT;
389
390   // calculate our scroll target depending on scroll mode
391   float target_x;
392   if(scrollchange == LEFT)
393     target_x = player->get_bbox().get_middle().x - SCREEN_WIDTH/3*2;
394   else if(scrollchange == RIGHT)
395     target_x = player->get_bbox().get_middle().x - SCREEN_WIDTH/3;
396   else
397     target_x = translation.x;
398
399   // that's the distance we would have to travel to reach target_x
400   float delta_x = translation.x - target_x;
401   // the speed we'd need to travel to reach target_x in this frame
402   float speed_x = delta_x / elapsed_time;
403
404   // limit our speed
405   float maxv = 130 + (fabsf(player->physic.get_velocity_x() * 1.3));
406   if(speed_x > maxv)
407     speed_x = maxv;
408   else if(speed_x < -maxv)
409     speed_x = -maxv;
410
411   // If player is peeking scroll in that direction. Fast.
412   if( player->peeking_direction() == ::LEFT ){
413         speed_x = maxv;
414   }
415   if( player->peeking_direction() == ::RIGHT ){
416         speed_x = -maxv;
417   }
418
419   // apply scrolling
420   translation.x -= speed_x * elapsed_time;
421
422   // make sure to always keep the player inside the middle 4/6 of the screen
423   translation.x = std::min(player->get_bbox().p1.x - SCREEN_WIDTH*1/6, translation.x);
424   translation.x = std::max(player->get_bbox().p2.x - SCREEN_WIDTH*5/6, translation.x);
425
426   keep_in_bounds(translation);
427   shake();
428 }
429
430 void
431 Camera::update_scroll_autoscroll(float elapsed_time)
432 {
433   Player* player = sector->player;
434   if(player->is_dying())
435     return;
436
437   translation = autoscroll_walker->advance(elapsed_time);
438
439   keep_in_bounds(translation);
440   shake();
441 }
442
443 void
444 Camera::update_scroll_to(float elapsed_time)
445 {
446   scroll_to_pos += elapsed_time * scrollspeed;
447   if(scroll_to_pos >= 1.0) {
448     mode = MANUAL;
449     translation = scroll_goal;
450     return;
451   }
452
453   translation = scroll_from + (scroll_goal - scroll_from) * scroll_to_pos;
454 }