move over rewritten lispreader from tuxkart (with additional fixes), generalized...
[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
20 #include <config.h>
21
22 #include <stdexcept>
23 #include <sstream>
24 #include <cmath>
25
26 #include "lisp/lisp.h"
27 #include "lisp/writer.h"
28 #include "lisp/list_iterator.h"
29 #include "camera.h"
30 #include "player.h"
31 #include "tilemap.h"
32 #include "gameloop.h"
33 #include "app/globals.h"
34 #include "sector.h"
35
36 using namespace SuperTux;
37
38 Camera::Camera(Sector* newsector)
39   : sector(newsector), do_backscrolling(true), scrollchange(NONE),
40     auto_idx(0), auto_t(0)
41 {
42   mode = NORMAL;
43 }
44
45 Camera::~Camera()
46 {
47 }
48
49 const Vector&
50 Camera::get_translation() const
51 {
52   return translation;
53 }
54
55 void
56 Camera::parse(const lisp::Lisp& reader)
57 {
58   std::string modename;
59   
60   reader.get("mode", modename);
61   if(modename == "normal") {
62     mode = NORMAL;
63
64     do_backscrolling = true;
65     reader.get("backscrolling", do_backscrolling);
66   } else if(modename == "autoscroll") {
67     mode = AUTOSCROLL;
68     
69     const lisp::Lisp* path_lisp = reader.get_lisp("path");
70     if(!path_lisp)
71       throw std::runtime_error("No path specified in autoscroll camera.");
72
73     lisp::ListIterator iter(path_lisp);
74     float speed = .5;
75     while(iter.next()) {
76       if(iter.item() != "point") {
77         std::cerr << "Warning: unknown token '" << iter.item() 
78           << "' in camera path.\n";
79         continue;
80       }
81       const lisp::Lisp* point_lisp = iter.lisp();
82
83       ScrollPoint point;
84       if(!point_lisp->get("x", point.position.x) ||
85          !point_lisp->get("y", point.position.y)) {
86         throw std::runtime_error("x and y missing in point of camerapath");
87       }
88       point_lisp->get("speed", speed);
89       point.speed = speed;
90       scrollpoints.push_back(point);
91     }
92   } else if(modename == "manual") {
93     mode = MANUAL;
94   } else {
95     std::stringstream str;
96     str << "invalid camera mode '" << modename << "'found in worldfile.";
97     throw std::runtime_error(str.str());
98   }
99 }
100
101 void
102 Camera::write(lisp::Writer& writer)
103 {
104   writer.start_list("camera");
105   
106   if(mode == NORMAL) {
107     writer.write_string("mode", "normal");
108     writer.write_bool("backscrolling", do_backscrolling);
109   } else if(mode == AUTOSCROLL) {
110     writer.write_string("mode", "autoscroll");
111     writer.start_list("path");
112     for(std::vector<ScrollPoint>::iterator i = scrollpoints.begin();
113         i != scrollpoints.end(); ++i) {
114       writer.start_list("point");
115       writer.write_float("x", i->position.x);
116       writer.write_float("y", i->position.y);
117       writer.write_float("speed", i->speed);
118       writer.end_list("point");
119     }
120
121     writer.end_list("path");
122   } else if(mode == MANUAL) {
123     writer.write_string("mode", "manual");
124   }
125                      
126   writer.end_list("camera");
127 }
128
129 void
130 Camera::reset(const Vector& tuxpos)
131 {
132   translation.x = tuxpos.x - screen->w/3 * 2;
133   translation.y = tuxpos.y - screen->h/2;
134   keep_in_bounds();
135 }
136
137 static const float EPSILON = .00001;
138 static const float max_speed_y = 140;
139
140 void
141 Camera::action(float elapsed_time)
142 {
143   if(mode == NORMAL)
144     scroll_normal(elapsed_time);
145   else if(mode == AUTOSCROLL)
146     scroll_autoscroll(elapsed_time);
147 }
148
149 void
150 Camera::keep_in_bounds()
151 {
152   float width = sector->solids->get_width() * 32;
153   float height = sector->solids->get_height() * 32;
154
155   // don't scroll before the start or after the level's end
156   if(translation.y > height - screen->h)
157     translation.y = height - screen->h;
158   if(translation.y < 0)                                      
159     translation.y = 0; 
160   if(translation.x > width - screen->w)
161     translation.x = width - screen->w;
162   if(translation.x < 0)
163     translation.x = 0;                                         
164 }
165
166 void
167 Camera::scroll_normal(float elapsed_time)
168 {
169   assert(sector != 0);
170   Player* player = sector->player;
171   
172   // check that we don't have division by zero later
173   if(elapsed_time < EPSILON)
174     return;
175
176   /****** Vertical Scrolling part ******/
177   bool do_y_scrolling = true;
178
179   if(player->dying || sector->solids->get_height() == 19)
180     do_y_scrolling = false;
181
182   if(do_y_scrolling) {
183     // target_y is the high we target our scrolling at. This is not always the
184     // high of the player, but if he is jumping upwards we should use the
185     // position where he last touched the ground. (this probably needs
186     // exceptions for trampolines and similar things in the future)
187     float target_y;
188     if(player->fall_mode == Player::JUMPING)
189       target_y = player->last_ground_y + player->get_bbox().get_height();
190     else
191       target_y = player->get_bbox().p2.y;
192
193     // delta_y is the distance we'd have to travel to directly reach target_y
194     float delta_y = translation.y - (target_y - screen->h/2);
195     // speed is the speed the camera would need to reach target_y in this frame
196     float speed_y = delta_y / elapsed_time;
197
198     // limit the camera speed when jumping upwards
199     if(player->fall_mode != Player::FALLING 
200         && player->fall_mode != Player::TRAMPOLINE_JUMP) {
201       if(speed_y > max_speed_y)
202         speed_y = max_speed_y;
203       else if(speed_y < -max_speed_y)
204         speed_y = -max_speed_y;
205     }
206
207     // finally scroll with calculated speed
208     translation.y -= speed_y * elapsed_time;
209   }
210
211   /****** Horizontal scrolling part *******/
212
213   // our camera is either in leftscrolling, rightscrolling or nonscrollingmode.
214   
215   // when suddenly changing directions while scrolling into the other direction.
216   // abort scrolling, since tux might be going left/right at a relatively small
217   // part of the map (like when jumping upwards)
218   if((player->dir == ::LEFT && scrollchange == RIGHT)
219       || (player->dir == ::RIGHT && scrollchange == LEFT))
220     scrollchange = NONE;
221   // when in left 1/3rd of screen scroll left
222   if(player->get_bbox().get_middle().x < translation.x + screen->w/3 - 16
223       && do_backscrolling)
224     scrollchange = LEFT;
225   // scroll right when in right 1/3rd of screen
226   else if(player->get_bbox().get_middle().x > translation.x + screen->w/3*2+16)
227     scrollchange = RIGHT;
228
229   // calculate our scroll target depending on scroll mode
230   float target_x;
231   if(scrollchange == LEFT)
232     target_x = player->get_bbox().get_middle().x - screen->w/3*2;
233   else if(scrollchange == RIGHT)
234     target_x = player->get_bbox().get_middle().x - screen->w/3;
235   else
236     target_x = translation.x;
237
238   // that's the distance we would have to travel to reach target_x
239   float delta_x = translation.x - target_x;
240   // the speed we'd need to travel to reach target_x in this frame
241   float speed_x = delta_x / elapsed_time;
242
243   // limit our speed
244   float maxv = 130 + (fabsf(player->physic.get_velocity_x() * 1.3));
245   if(speed_x > maxv)
246     speed_x = maxv;
247   else if(speed_x < -maxv)
248     speed_x = -maxv;
249  
250   // apply scrolling
251   translation.x -= speed_x * elapsed_time;
252
253   keep_in_bounds();
254 }
255
256 void
257 Camera::scroll_autoscroll(float elapsed_time)
258 {
259   Player* player = sector->player;
260   
261   if(player->dying)
262     return;
263
264   if(auto_t - elapsed_time >= 0) {
265     translation += current_dir * elapsed_time;
266     auto_t -= elapsed_time;
267   } else {
268     // do the rest of the old movement
269     translation += current_dir * auto_t;
270     elapsed_time -= auto_t;
271     auto_t = 0;
272
273     // construct path for next point
274     if(auto_idx+1 >= scrollpoints.size()) {
275       keep_in_bounds();
276       return;
277     }
278     Vector distance = scrollpoints[auto_idx+1].position 
279                       - scrollpoints[auto_idx].position;
280     current_dir = distance.unit() * scrollpoints[auto_idx].speed;
281     auto_t = distance.norm() / scrollpoints[auto_idx].speed;
282
283     // do movement for the remaining time
284     translation += current_dir * elapsed_time;
285     auto_t -= elapsed_time;
286     auto_idx++;
287   }
288
289   keep_in_bounds();
290 }