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