New Path based on time intervals; see levels/test/platform.stl
[supertux.git] / src / object / camera.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 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 "camera.hpp"
29 #include "player.hpp"
30 #include "tilemap.hpp"
31 #include "game_session.hpp"
32 #include "sector.hpp"
33 #include "main.hpp"
34 #include "object_factory.hpp"
35
36 Camera::Camera(Sector* newsector)
37   : sector(newsector), do_backscrolling(true), scrollchange(NONE),
38     auto_idx(0), auto_t(0)
39 {
40   mode = NORMAL;
41 }
42
43 Camera::~Camera()
44 {
45 }
46
47 const Vector&
48 Camera::get_translation() const
49 {
50   return translation;
51 }
52
53 void
54 Camera::parse(const lisp::Lisp& reader)
55 {
56   std::string modename;
57   
58   reader.get("mode", modename);
59   if(modename == "normal") {
60     mode = NORMAL;
61
62     do_backscrolling = true;
63     reader.get("backscrolling", do_backscrolling);
64   } else if(modename == "autoscroll") {
65     mode = AUTOSCROLL;
66     
67     const lisp::Lisp* path_lisp = reader.get_lisp("path");
68     if(!path_lisp)
69       throw std::runtime_error("No path specified in autoscroll camera.");
70
71     lisp::ListIterator iter(path_lisp);
72     float speed = .5;
73     while(iter.next()) {
74       if(iter.item() != "point") {
75         std::cerr << "Warning: unknown token '" << iter.item() 
76           << "' in camera path.\n";
77         continue;
78       }
79       const lisp::Lisp* point_lisp = iter.lisp();
80
81       ScrollPoint point;
82       if(!point_lisp->get("x", point.position.x) ||
83          !point_lisp->get("y", point.position.y)) {
84         throw std::runtime_error("x and y missing in point of camerapath");
85       }
86       point_lisp->get("speed", speed);
87       point.speed = speed;
88       scrollpoints.push_back(point);
89     }
90   } else if(modename == "manual") {
91     mode = MANUAL;
92   } else {
93     std::stringstream str;
94     str << "invalid camera mode '" << modename << "'found in worldfile.";
95     throw std::runtime_error(str.str());
96   }
97 }
98
99 void
100 Camera::write(lisp::Writer& writer)
101 {
102   writer.start_list("camera");
103   
104   if(mode == NORMAL) {
105     writer.write_string("mode", "normal");
106     writer.write_bool("backscrolling", do_backscrolling);
107   } else if(mode == AUTOSCROLL) {
108     writer.write_string("mode", "autoscroll");
109     writer.start_list("path");
110     for(std::vector<ScrollPoint>::iterator i = scrollpoints.begin();
111         i != scrollpoints.end(); ++i) {
112       writer.start_list("point");
113       writer.write_float("x", i->position.x);
114       writer.write_float("y", i->position.y);
115       writer.write_float("speed", i->speed);
116       writer.end_list("point");
117     }
118
119     writer.end_list("path");
120   } else if(mode == MANUAL) {
121     writer.write_string("mode", "manual");
122   }
123                      
124   writer.end_list("camera");
125 }
126
127 void
128 Camera::reset(const Vector& tuxpos)
129 {
130   translation.x = tuxpos.x - SCREEN_WIDTH/3 * 2;
131   translation.y = tuxpos.y - SCREEN_HEIGHT/2;
132   shakespeed = 0;
133   shaketimer.stop();
134   keep_in_bounds(translation);
135 }
136
137 void
138 Camera::shake(float time, float x, float y)
139 {
140   shaketimer.start(time);
141   shakedepth_x = x;
142   shakedepth_y = y;
143   shakespeed = M_PI/2 / time;
144 }
145
146 void
147 Camera::scroll_to(const Vector& goal, float scrolltime)
148 {
149   scroll_from = translation;
150   scroll_goal = goal;
151   keep_in_bounds(scroll_goal);
152
153   scroll_to_pos = 0;
154   scrollspeed = 1.0 / scrolltime;
155   mode = SCROLLTO;
156 }
157
158 static const float EPSILON = .00001;
159 static const float max_speed_y = 140;
160
161 void
162 Camera::update(float elapsed_time)
163 {
164   switch(mode) {
165     case NORMAL:
166       update_scroll_normal(elapsed_time);
167       break;
168     case AUTOSCROLL:
169       update_scroll_autoscroll(elapsed_time);
170       break;
171     case SCROLLTO:
172       update_scroll_to(elapsed_time);
173       break;
174     default:
175       break;
176   }
177 }
178
179 void
180 Camera::keep_in_bounds(Vector& translation)
181 {
182   float width = sector->solids->get_width() * 32;
183   float height = sector->solids->get_height() * 32;
184
185   // don't scroll before the start or after the level's end
186   if(translation.y > height - SCREEN_HEIGHT)
187     translation.y = height - SCREEN_HEIGHT;
188   if(translation.y < 0)                                      
189     translation.y = 0; 
190   if(translation.x > width - SCREEN_WIDTH)
191     translation.x = width - SCREEN_WIDTH;
192   if(translation.x < 0)
193     translation.x = 0;                                         
194 }
195
196 void
197 Camera::shake()
198 {
199   if(shaketimer.started()) {
200     translation.x -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_x;
201     translation.y -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_y;
202   }
203 }
204
205 void
206 Camera::update_scroll_normal(float elapsed_time)
207 {
208   assert(sector != 0);
209   Player* player = sector->player;
210   
211   // check that we don't have division by zero later
212   if(elapsed_time < EPSILON)
213     return;
214
215   /****** Vertical Scrolling part ******/
216   bool do_y_scrolling = true;
217
218   if(player->is_dying() || sector->solids->get_height() == 19)
219     do_y_scrolling = false;
220
221   if(do_y_scrolling) {
222     // target_y is the high we target our scrolling at. This is not always the
223     // high of the player, but if he is jumping upwards we should use the
224     // position where he last touched the ground. (this probably needs
225     // exceptions for trampolines and similar things in the future)
226     float target_y;
227     if(player->fall_mode == Player::JUMPING)
228       target_y = player->last_ground_y + player->get_bbox().get_height();
229     else
230       target_y = player->get_bbox().p2.y;
231
232     // delta_y is the distance we'd have to travel to directly reach target_y
233     float delta_y = translation.y - (target_y - SCREEN_HEIGHT*2/3);
234     // speed is the speed the camera would need to reach target_y in this frame
235     float speed_y = delta_y / elapsed_time;
236
237     // limit the camera speed when jumping upwards
238     if(player->fall_mode != Player::FALLING 
239         && player->fall_mode != Player::TRAMPOLINE_JUMP) {
240       if(speed_y > max_speed_y)
241         speed_y = max_speed_y;
242       else if(speed_y < -max_speed_y)
243         speed_y = -max_speed_y;
244     }
245
246     // finally scroll with calculated speed
247     translation.y -= speed_y * elapsed_time;
248   }
249
250   /****** Horizontal scrolling part *******/
251
252   // our camera is either in leftscrolling, rightscrolling or nonscrollingmode.
253   
254   // when suddenly changing directions while scrolling into the other direction.
255   // abort scrolling, since tux might be going left/right at a relatively small
256   // part of the map (like when jumping upwards)
257   if((player->dir == ::LEFT && scrollchange == RIGHT)
258       || (player->dir == ::RIGHT && scrollchange == LEFT))
259     scrollchange = NONE;
260   // when in left 1/3rd of screen scroll left
261   if(player->get_bbox().get_middle().x < translation.x + SCREEN_WIDTH/3 - 16
262       && do_backscrolling)
263     scrollchange = LEFT;
264   // scroll right when in right 1/3rd of screen
265   else if(player->get_bbox().get_middle().x > translation.x + SCREEN_WIDTH/3*2+16)
266     scrollchange = RIGHT;
267
268   // calculate our scroll target depending on scroll mode
269   float target_x;
270   if(scrollchange == LEFT)
271     target_x = player->get_bbox().get_middle().x - SCREEN_WIDTH/3*2;
272   else if(scrollchange == RIGHT)
273     target_x = player->get_bbox().get_middle().x - SCREEN_WIDTH/3;
274   else
275     target_x = translation.x;
276
277   // that's the distance we would have to travel to reach target_x
278   float delta_x = translation.x - target_x;
279   // the speed we'd need to travel to reach target_x in this frame
280   float speed_x = delta_x / elapsed_time;
281
282   // limit our speed
283   float maxv = 130 + (fabsf(player->physic.get_velocity_x() * 1.3));
284   if(speed_x > maxv)
285     speed_x = maxv;
286   else if(speed_x < -maxv)
287     speed_x = -maxv;
288  
289   // apply scrolling
290   translation.x -= speed_x * elapsed_time;
291
292   keep_in_bounds(translation);
293   shake();
294 }
295
296 void
297 Camera::update_scroll_autoscroll(float elapsed_time)
298 {
299   Player* player = sector->player;
300   
301   if(player->is_dying())
302     return;
303
304   if(auto_t - elapsed_time >= 0) {
305     translation += current_dir * elapsed_time;
306     auto_t -= elapsed_time;
307   } else {
308     // do the rest of the old movement
309     translation += current_dir * auto_t;
310     elapsed_time -= auto_t;
311     auto_t = 0;
312
313     // construct path for next point
314     if(auto_idx+1 >= scrollpoints.size()) {
315       keep_in_bounds(translation);
316       return;
317     }
318     Vector distance = scrollpoints[auto_idx+1].position 
319                       - scrollpoints[auto_idx].position;
320     current_dir = distance.unit() * scrollpoints[auto_idx].speed;
321     auto_t = distance.norm() / scrollpoints[auto_idx].speed;
322
323     // do movement for the remaining time
324     translation += current_dir * elapsed_time;
325     auto_t -= elapsed_time;
326     auto_idx++;
327   }
328
329   keep_in_bounds(translation);
330   shake();
331 }
332
333 void
334 Camera::update_scroll_to(float elapsed_time)
335 {
336   scroll_to_pos += elapsed_time * scrollspeed;
337   if(scroll_to_pos >= 1.0) {
338     mode = MANUAL;
339     translation = scroll_goal;
340     return;
341   }
342
343   translation = scroll_from + (scroll_goal - scroll_from) * scroll_to_pos;
344 }
345