871ea709d066b86674adf108e9632a06ba544ee6
[oweals/minetest.git] / src / client / camera.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "camera.h"
21 #include "debug.h"
22 #include "client.h"
23 #include "config.h"
24 #include "map.h"
25 #include "clientmap.h"     // MapDrawControl
26 #include "player.h"
27 #include <cmath>
28 #include "client/renderingengine.h"
29 #include "settings.h"
30 #include "wieldmesh.h"
31 #include "noise.h"         // easeCurve
32 #include "sound.h"
33 #include "event.h"
34 #include "nodedef.h"
35 #include "util/numeric.h"
36 #include "constants.h"
37 #include "fontengine.h"
38 #include "script/scripting_client.h"
39
40 #define CAMERA_OFFSET_STEP 200
41 #define WIELDMESH_OFFSET_X 55.0f
42 #define WIELDMESH_OFFSET_Y -35.0f
43 #define WIELDMESH_AMPLITUDE_X 7.0f
44 #define WIELDMESH_AMPLITUDE_Y 10.0f
45
46 Camera::Camera(MapDrawControl &draw_control, Client *client):
47         m_draw_control(draw_control),
48         m_client(client)
49 {
50         scene::ISceneManager *smgr = RenderingEngine::get_scene_manager();
51         // note: making the camera node a child of the player node
52         // would lead to unexpected behaviour, so we don't do that.
53         m_playernode = smgr->addEmptySceneNode(smgr->getRootSceneNode());
54         m_headnode = smgr->addEmptySceneNode(m_playernode);
55         m_cameranode = smgr->addCameraSceneNode(smgr->getRootSceneNode());
56         m_cameranode->bindTargetAndRotation(true);
57
58         // This needs to be in its own scene manager. It is drawn after
59         // all other 3D scene nodes and before the GUI.
60         m_wieldmgr = smgr->createNewSceneManager();
61         m_wieldmgr->addCameraSceneNode();
62         m_wieldnode = new WieldMeshSceneNode(m_wieldmgr, -1, false);
63         m_wieldnode->setItem(ItemStack(), m_client);
64         m_wieldnode->drop(); // m_wieldmgr grabbed it
65
66         /* TODO: Add a callback function so these can be updated when a setting
67          *       changes.  At this point in time it doesn't matter (e.g. /set
68          *       is documented to change server settings only)
69          *
70          * TODO: Local caching of settings is not optimal and should at some stage
71          *       be updated to use a global settings object for getting thse values
72          *       (as opposed to the this local caching). This can be addressed in
73          *       a later release.
74          */
75         m_cache_fall_bobbing_amount = g_settings->getFloat("fall_bobbing_amount");
76         m_cache_view_bobbing_amount = g_settings->getFloat("view_bobbing_amount");
77         // 45 degrees is the lowest FOV that doesn't cause the server to treat this
78         // as a zoom FOV and load world beyond the set server limits.
79         m_cache_fov                 = std::fmax(g_settings->getFloat("fov"), 45.0f);
80         m_arm_inertia               = g_settings->getBool("arm_inertia");
81         m_nametags.clear();
82 }
83
84 Camera::~Camera()
85 {
86         m_wieldmgr->drop();
87 }
88
89 bool Camera::successfullyCreated(std::string &error_message)
90 {
91         if (!m_playernode) {
92                 error_message = "Failed to create the player scene node";
93         } else if (!m_headnode) {
94                 error_message = "Failed to create the head scene node";
95         } else if (!m_cameranode) {
96                 error_message = "Failed to create the camera scene node";
97         } else if (!m_wieldmgr) {
98                 error_message = "Failed to create the wielded item scene manager";
99         } else if (!m_wieldnode) {
100                 error_message = "Failed to create the wielded item scene node";
101         } else {
102                 error_message.clear();
103         }
104
105         if (m_client->modsLoaded())
106                 m_client->getScript()->on_camera_ready(this);
107
108         return error_message.empty();
109 }
110
111 // Returns the fractional part of x
112 inline f32 my_modf(f32 x)
113 {
114         double dummy;
115         return modf(x, &dummy);
116 }
117
118 void Camera::step(f32 dtime)
119 {
120         if(m_view_bobbing_fall > 0)
121         {
122                 m_view_bobbing_fall -= 3 * dtime;
123                 if(m_view_bobbing_fall <= 0)
124                         m_view_bobbing_fall = -1; // Mark the effect as finished
125         }
126
127         bool was_under_zero = m_wield_change_timer < 0;
128         m_wield_change_timer = MYMIN(m_wield_change_timer + dtime, 0.125);
129
130         if (m_wield_change_timer >= 0 && was_under_zero)
131                 m_wieldnode->setItem(m_wield_item_next, m_client);
132
133         if (m_view_bobbing_state != 0)
134         {
135                 //f32 offset = dtime * m_view_bobbing_speed * 0.035;
136                 f32 offset = dtime * m_view_bobbing_speed * 0.030;
137                 if (m_view_bobbing_state == 2) {
138                         // Animation is getting turned off
139                         if (m_view_bobbing_anim < 0.25) {
140                                 m_view_bobbing_anim -= offset;
141                         } else if (m_view_bobbing_anim > 0.75) {
142                                 m_view_bobbing_anim += offset;
143                         }
144
145                         if (m_view_bobbing_anim < 0.5) {
146                                 m_view_bobbing_anim += offset;
147                                 if (m_view_bobbing_anim > 0.5)
148                                         m_view_bobbing_anim = 0.5;
149                         } else {
150                                 m_view_bobbing_anim -= offset;
151                                 if (m_view_bobbing_anim < 0.5)
152                                         m_view_bobbing_anim = 0.5;
153                         }
154
155                         if (m_view_bobbing_anim <= 0 || m_view_bobbing_anim >= 1 ||
156                                         fabs(m_view_bobbing_anim - 0.5) < 0.01) {
157                                 m_view_bobbing_anim = 0;
158                                 m_view_bobbing_state = 0;
159                         }
160                 }
161                 else {
162                         float was = m_view_bobbing_anim;
163                         m_view_bobbing_anim = my_modf(m_view_bobbing_anim + offset);
164                         bool step = (was == 0 ||
165                                         (was < 0.5f && m_view_bobbing_anim >= 0.5f) ||
166                                         (was > 0.5f && m_view_bobbing_anim <= 0.5f));
167                         if(step) {
168                                 m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::VIEW_BOBBING_STEP));
169                         }
170                 }
171         }
172
173         if (m_digging_button != -1) {
174                 f32 offset = dtime * 3.5f;
175                 float m_digging_anim_was = m_digging_anim;
176                 m_digging_anim += offset;
177                 if (m_digging_anim >= 1)
178                 {
179                         m_digging_anim = 0;
180                         m_digging_button = -1;
181                 }
182                 float lim = 0.15;
183                 if(m_digging_anim_was < lim && m_digging_anim >= lim)
184                 {
185                         if (m_digging_button == 0) {
186                                 m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::CAMERA_PUNCH_LEFT));
187                         } else if(m_digging_button == 1) {
188                                 m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::CAMERA_PUNCH_RIGHT));
189                         }
190                 }
191         }
192 }
193
194 static inline v2f dir(const v2f &pos_dist)
195 {
196         f32 x = pos_dist.X - WIELDMESH_OFFSET_X;
197         f32 y = pos_dist.Y - WIELDMESH_OFFSET_Y;
198
199         f32 x_abs = std::fabs(x);
200         f32 y_abs = std::fabs(y);
201
202         if (x_abs >= y_abs) {
203                 y *= (1.0f / x_abs);
204                 x /= x_abs;
205         }
206
207         if (y_abs >= x_abs) {
208                 x *= (1.0f / y_abs);
209                 y /= y_abs;
210         }
211
212         return v2f(std::fabs(x), std::fabs(y));
213 }
214
215 void Camera::addArmInertia(f32 player_yaw)
216 {
217         m_cam_vel.X = std::fabs(rangelim(m_last_cam_pos.X - player_yaw,
218                 -100.0f, 100.0f) / 0.016f) * 0.01f;
219         m_cam_vel.Y = std::fabs((m_last_cam_pos.Y - m_camera_direction.Y) / 0.016f);
220         f32 gap_X = std::fabs(WIELDMESH_OFFSET_X - m_wieldmesh_offset.X);
221         f32 gap_Y = std::fabs(WIELDMESH_OFFSET_Y - m_wieldmesh_offset.Y);
222
223         if (m_cam_vel.X > 1.0f || m_cam_vel.Y > 1.0f) {
224                 /*
225                     The arm moves relative to the camera speed,
226                     with an acceleration factor.
227                 */
228
229                 if (m_cam_vel.X > 1.0f) {
230                         if (m_cam_vel.X > m_cam_vel_old.X)
231                                 m_cam_vel_old.X = m_cam_vel.X;
232
233                         f32 acc_X = 0.12f * (m_cam_vel.X - (gap_X * 0.1f));
234                         m_wieldmesh_offset.X += m_last_cam_pos.X < player_yaw ? acc_X : -acc_X;
235
236                         if (m_last_cam_pos.X != player_yaw)
237                                 m_last_cam_pos.X = player_yaw;
238
239                         m_wieldmesh_offset.X = rangelim(m_wieldmesh_offset.X,
240                                 WIELDMESH_OFFSET_X - (WIELDMESH_AMPLITUDE_X * 0.5f),
241                                 WIELDMESH_OFFSET_X + (WIELDMESH_AMPLITUDE_X * 0.5f));
242                 }
243
244                 if (m_cam_vel.Y > 1.0f) {
245                         if (m_cam_vel.Y > m_cam_vel_old.Y)
246                                 m_cam_vel_old.Y = m_cam_vel.Y;
247
248                         f32 acc_Y = 0.12f * (m_cam_vel.Y - (gap_Y * 0.1f));
249                         m_wieldmesh_offset.Y +=
250                                 m_last_cam_pos.Y > m_camera_direction.Y ? acc_Y : -acc_Y;
251
252                         if (m_last_cam_pos.Y != m_camera_direction.Y)
253                                 m_last_cam_pos.Y = m_camera_direction.Y;
254
255                         m_wieldmesh_offset.Y = rangelim(m_wieldmesh_offset.Y,
256                                 WIELDMESH_OFFSET_Y - (WIELDMESH_AMPLITUDE_Y * 0.5f),
257                                 WIELDMESH_OFFSET_Y + (WIELDMESH_AMPLITUDE_Y * 0.5f));
258                 }
259
260                 m_arm_dir = dir(m_wieldmesh_offset);
261         } else {
262                 /*
263                     Now the arm gets back to its default position when the camera stops,
264                     following a vector, with a smooth deceleration factor.
265                 */
266
267                 f32 dec_X = 0.35f * (std::min(15.0f, m_cam_vel_old.X) * (1.0f +
268                         (1.0f - m_arm_dir.X))) * (gap_X / 20.0f);
269
270                 f32 dec_Y = 0.25f * (std::min(15.0f, m_cam_vel_old.Y) * (1.0f +
271                         (1.0f - m_arm_dir.Y))) * (gap_Y / 15.0f);
272
273                 if (gap_X < 0.1f)
274                         m_cam_vel_old.X = 0.0f;
275
276                 m_wieldmesh_offset.X -=
277                         m_wieldmesh_offset.X > WIELDMESH_OFFSET_X ? dec_X : -dec_X;
278
279                 if (gap_Y < 0.1f)
280                         m_cam_vel_old.Y = 0.0f;
281
282                 m_wieldmesh_offset.Y -=
283                         m_wieldmesh_offset.Y > WIELDMESH_OFFSET_Y ? dec_Y : -dec_Y;
284         }
285 }
286
287 void Camera::update(LocalPlayer* player, f32 frametime, f32 busytime, f32 tool_reload_ratio)
288 {
289         // Get player position
290         // Smooth the movement when walking up stairs
291         v3f old_player_position = m_playernode->getPosition();
292         v3f player_position = player->getPosition();
293
294         // This is worse than `LocalPlayer::getPosition()` but
295         // mods expect the player head to be at the parent's position
296         // plus eye height.
297         if (player->getParent())
298                 player_position = player->getParent()->getPosition();
299
300         if(player->touching_ground &&
301                         player_position.Y > old_player_position.Y)
302         {
303                 f32 oldy = old_player_position.Y;
304                 f32 newy = player_position.Y;
305                 f32 t = std::exp(-23 * frametime);
306                 player_position.Y = oldy * t + newy * (1-t);
307         }
308
309         // Set player node transformation
310         m_playernode->setPosition(player_position);
311         m_playernode->setRotation(v3f(0, -1 * player->getYaw(), 0));
312         m_playernode->updateAbsolutePosition();
313
314         // Get camera tilt timer (hurt animation)
315         float cameratilt = fabs(fabs(player->hurt_tilt_timer-0.75)-0.75);
316
317         // Fall bobbing animation
318         float fall_bobbing = 0;
319         if(player->camera_impact >= 1 && m_camera_mode < CAMERA_MODE_THIRD)
320         {
321                 if(m_view_bobbing_fall == -1) // Effect took place and has finished
322                         player->camera_impact = m_view_bobbing_fall = 0;
323                 else if(m_view_bobbing_fall == 0) // Initialize effect
324                         m_view_bobbing_fall = 1;
325
326                 // Convert 0 -> 1 to 0 -> 1 -> 0
327                 fall_bobbing = m_view_bobbing_fall < 0.5 ? m_view_bobbing_fall * 2 : -(m_view_bobbing_fall - 0.5) * 2 + 1;
328                 // Smoothen and invert the above
329                 fall_bobbing = sin(fall_bobbing * 0.5 * M_PI) * -1;
330                 // Amplify according to the intensity of the impact
331                 fall_bobbing *= (1 - rangelim(50 / player->camera_impact, 0, 1)) * 5;
332
333                 fall_bobbing *= m_cache_fall_bobbing_amount;
334         }
335
336         // Calculate players eye offset for different camera modes
337         v3f PlayerEyeOffset = player->getEyeOffset();
338         if (m_camera_mode == CAMERA_MODE_FIRST)
339                 PlayerEyeOffset += player->eye_offset_first;
340         else
341                 PlayerEyeOffset += player->eye_offset_third;
342
343         // Set head node transformation
344         m_headnode->setPosition(PlayerEyeOffset+v3f(0,cameratilt*-player->hurt_tilt_strength+fall_bobbing,0));
345         m_headnode->setRotation(v3f(player->getPitch(), 0, cameratilt*player->hurt_tilt_strength));
346         m_headnode->updateAbsolutePosition();
347
348         // Compute relative camera position and target
349         v3f rel_cam_pos = v3f(0,0,0);
350         v3f rel_cam_target = v3f(0,0,1);
351         v3f rel_cam_up = v3f(0,1,0);
352
353         if (m_cache_view_bobbing_amount != 0.0f && m_view_bobbing_anim != 0.0f &&
354                 m_camera_mode < CAMERA_MODE_THIRD) {
355                 f32 bobfrac = my_modf(m_view_bobbing_anim * 2);
356                 f32 bobdir = (m_view_bobbing_anim < 0.5) ? 1.0 : -1.0;
357
358                 #if 1
359                 f32 bobknob = 1.2;
360                 f32 bobtmp = sin(pow(bobfrac, bobknob) * M_PI);
361                 //f32 bobtmp2 = cos(pow(bobfrac, bobknob) * M_PI);
362
363                 v3f bobvec = v3f(
364                         0.3 * bobdir * sin(bobfrac * M_PI),
365                         -0.28 * bobtmp * bobtmp,
366                         0.);
367
368                 //rel_cam_pos += 0.2 * bobvec;
369                 //rel_cam_target += 0.03 * bobvec;
370                 //rel_cam_up.rotateXYBy(0.02 * bobdir * bobtmp * M_PI);
371                 float f = 1.0;
372                 f *= m_cache_view_bobbing_amount;
373                 rel_cam_pos += bobvec * f;
374                 //rel_cam_target += 0.995 * bobvec * f;
375                 rel_cam_target += bobvec * f;
376                 rel_cam_target.Z -= 0.005 * bobvec.Z * f;
377                 //rel_cam_target.X -= 0.005 * bobvec.X * f;
378                 //rel_cam_target.Y -= 0.005 * bobvec.Y * f;
379                 rel_cam_up.rotateXYBy(-0.03 * bobdir * bobtmp * M_PI * f);
380                 #else
381                 f32 angle_deg = 1 * bobdir * sin(bobfrac * M_PI);
382                 f32 angle_rad = angle_deg * M_PI / 180;
383                 f32 r = 0.05;
384                 v3f off = v3f(
385                         r * sin(angle_rad),
386                         r * (cos(angle_rad) - 1),
387                         0);
388                 rel_cam_pos += off;
389                 //rel_cam_target += off;
390                 rel_cam_up.rotateXYBy(angle_deg);
391                 #endif
392
393         }
394
395         // Compute absolute camera position and target
396         m_headnode->getAbsoluteTransformation().transformVect(m_camera_position, rel_cam_pos);
397         m_headnode->getAbsoluteTransformation().rotateVect(m_camera_direction, rel_cam_target - rel_cam_pos);
398
399         v3f abs_cam_up;
400         m_headnode->getAbsoluteTransformation().rotateVect(abs_cam_up, rel_cam_up);
401
402         // Seperate camera position for calculation
403         v3f my_cp = m_camera_position;
404
405         // Reposition the camera for third person view
406         if (m_camera_mode > CAMERA_MODE_FIRST)
407         {
408                 if (m_camera_mode == CAMERA_MODE_THIRD_FRONT)
409                         m_camera_direction *= -1;
410
411                 my_cp.Y += 2;
412
413                 // Calculate new position
414                 bool abort = false;
415                 for (int i = BS; i <= BS * 2.75; i++) {
416                         my_cp.X = m_camera_position.X + m_camera_direction.X * -i;
417                         my_cp.Z = m_camera_position.Z + m_camera_direction.Z * -i;
418                         if (i > 12)
419                                 my_cp.Y = m_camera_position.Y + (m_camera_direction.Y * -i);
420
421                         // Prevent camera positioned inside nodes
422                         const NodeDefManager *nodemgr = m_client->ndef();
423                         MapNode n = m_client->getEnv().getClientMap()
424                                 .getNode(floatToInt(my_cp, BS));
425
426                         const ContentFeatures& features = nodemgr->get(n);
427                         if (features.walkable) {
428                                 my_cp.X += m_camera_direction.X*-1*-BS/2;
429                                 my_cp.Z += m_camera_direction.Z*-1*-BS/2;
430                                 my_cp.Y += m_camera_direction.Y*-1*-BS/2;
431                                 abort = true;
432                                 break;
433                         }
434                 }
435
436                 // If node blocks camera position don't move y to heigh
437                 if (abort && my_cp.Y > player_position.Y+BS*2)
438                         my_cp.Y = player_position.Y+BS*2;
439         }
440
441         // Update offset if too far away from the center of the map
442         m_camera_offset.X += CAMERA_OFFSET_STEP*
443                         (((s16)(my_cp.X/BS) - m_camera_offset.X)/CAMERA_OFFSET_STEP);
444         m_camera_offset.Y += CAMERA_OFFSET_STEP*
445                         (((s16)(my_cp.Y/BS) - m_camera_offset.Y)/CAMERA_OFFSET_STEP);
446         m_camera_offset.Z += CAMERA_OFFSET_STEP*
447                         (((s16)(my_cp.Z/BS) - m_camera_offset.Z)/CAMERA_OFFSET_STEP);
448
449         // Set camera node transformation
450         m_cameranode->setPosition(my_cp-intToFloat(m_camera_offset, BS));
451         m_cameranode->setUpVector(abs_cam_up);
452         // *100.0 helps in large map coordinates
453         m_cameranode->setTarget(my_cp-intToFloat(m_camera_offset, BS) + 100 * m_camera_direction);
454
455         // update the camera position in third-person mode to render blocks behind player
456         // and correctly apply liquid post FX.
457         if (m_camera_mode != CAMERA_MODE_FIRST)
458                 m_camera_position = my_cp;
459
460         /*
461          * Apply server-sent FOV. If server doesn't enforce FOV,
462          * check for zoom and set to zoom FOV.
463          * Otherwise, default to m_cache_fov
464          */
465
466         f32 fov_degrees;
467         PlayerFovSpec fov_spec = player->getFov();
468         if (fov_spec.fov > 0.0f) {
469                 // If server-sent FOV is a multiplier, multiply
470                 // it with m_cache_fov instead of overriding
471                 if (fov_spec.is_multiplier)
472                         fov_degrees = m_cache_fov * fov_spec.fov;
473                 else
474                         fov_degrees = fov_spec.fov;
475         } else if (player->getPlayerControl().zoom && player->getZoomFOV() > 0.001f) {
476                 // Player requests zoom, apply zoom FOV
477                 fov_degrees = player->getZoomFOV();
478         } else {
479                 // Set to client's selected FOV
480                 fov_degrees = m_cache_fov;
481         }
482         fov_degrees = rangelim(fov_degrees, 1.0f, 160.0f);
483
484         // FOV and aspect ratio
485         const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
486         m_aspect = (f32) window_size.X / (f32) window_size.Y;
487         m_fov_y = fov_degrees * M_PI / 180.0;
488         // Increase vertical FOV on lower aspect ratios (<16:10)
489         m_fov_y *= MYMAX(1.0, MYMIN(1.4, sqrt(16./10. / m_aspect)));
490         m_fov_x = 2 * atan(m_aspect * tan(0.5 * m_fov_y));
491         m_cameranode->setAspectRatio(m_aspect);
492         m_cameranode->setFOV(m_fov_y);
493
494         if (m_arm_inertia)
495                 addArmInertia(player->getYaw());
496
497         // Position the wielded item
498         //v3f wield_position = v3f(45, -35, 65);
499         v3f wield_position = v3f(m_wieldmesh_offset.X, m_wieldmesh_offset.Y, 65);
500         //v3f wield_rotation = v3f(-100, 120, -100);
501         v3f wield_rotation = v3f(-100, 120, -100);
502         wield_position.Y += fabs(m_wield_change_timer)*320 - 40;
503         if(m_digging_anim < 0.05 || m_digging_anim > 0.5)
504         {
505                 f32 frac = 1.0;
506                 if(m_digging_anim > 0.5)
507                         frac = 2.0 * (m_digging_anim - 0.5);
508                 // This value starts from 1 and settles to 0
509                 f32 ratiothing = std::pow((1.0f - tool_reload_ratio), 0.5f);
510                 //f32 ratiothing2 = pow(ratiothing, 0.5f);
511                 f32 ratiothing2 = (easeCurve(ratiothing*0.5))*2.0;
512                 wield_position.Y -= frac * 25.0 * pow(ratiothing2, 1.7f);
513                 //wield_position.Z += frac * 5.0 * ratiothing2;
514                 wield_position.X -= frac * 35.0 * pow(ratiothing2, 1.1f);
515                 wield_rotation.Y += frac * 70.0 * pow(ratiothing2, 1.4f);
516                 //wield_rotation.X -= frac * 15.0 * pow(ratiothing2, 1.4f);
517                 //wield_rotation.Z += frac * 15.0 * pow(ratiothing2, 1.0f);
518         }
519         if (m_digging_button != -1)
520         {
521                 f32 digfrac = m_digging_anim;
522                 wield_position.X -= 50 * sin(pow(digfrac, 0.8f) * M_PI);
523                 wield_position.Y += 24 * sin(digfrac * 1.8 * M_PI);
524                 wield_position.Z += 25 * 0.5;
525
526                 // Euler angles are PURE EVIL, so why not use quaternions?
527                 core::quaternion quat_begin(wield_rotation * core::DEGTORAD);
528                 core::quaternion quat_end(v3f(80, 30, 100) * core::DEGTORAD);
529                 core::quaternion quat_slerp;
530                 quat_slerp.slerp(quat_begin, quat_end, sin(digfrac * M_PI));
531                 quat_slerp.toEuler(wield_rotation);
532                 wield_rotation *= core::RADTODEG;
533         } else {
534                 f32 bobfrac = my_modf(m_view_bobbing_anim);
535                 wield_position.X -= sin(bobfrac*M_PI*2.0) * 3.0;
536                 wield_position.Y += sin(my_modf(bobfrac*2.0)*M_PI) * 3.0;
537         }
538         m_wieldnode->setPosition(wield_position);
539         m_wieldnode->setRotation(wield_rotation);
540
541         m_wieldnode->setColor(player->light_color);
542
543         // Set render distance
544         updateViewingRange();
545
546         // If the player is walking, swimming, or climbing,
547         // view bobbing is enabled and free_move is off,
548         // start (or continue) the view bobbing animation.
549         const v3f &speed = player->getSpeed();
550         const bool movement_XZ = hypot(speed.X, speed.Z) > BS;
551         const bool movement_Y = fabs(speed.Y) > BS;
552
553         const bool walking = movement_XZ && player->touching_ground;
554         const bool swimming = (movement_XZ || player->swimming_vertical) && player->in_liquid;
555         const bool climbing = movement_Y && player->is_climbing;
556         if ((walking || swimming || climbing) &&
557                         (!g_settings->getBool("free_move") || !m_client->checkLocalPrivilege("fly"))) {
558                 // Start animation
559                 m_view_bobbing_state = 1;
560                 m_view_bobbing_speed = MYMIN(speed.getLength(), 70);
561         }
562         else if (m_view_bobbing_state == 1)
563         {
564                 // Stop animation
565                 m_view_bobbing_state = 2;
566                 m_view_bobbing_speed = 60;
567         }
568 }
569
570 void Camera::updateViewingRange()
571 {
572         f32 viewing_range = g_settings->getFloat("viewing_range");
573
574         // Ignore near_plane setting on all other platforms to prevent abuse
575 #if ENABLE_GLES
576         m_cameranode->setNearValue(rangelim(
577                 g_settings->getFloat("near_plane"), 0.0f, 0.25f) * BS);
578 #else
579         m_cameranode->setNearValue(0.1f * BS);
580 #endif
581
582         m_draw_control.wanted_range = std::fmin(adjustDist(viewing_range, getFovMax()), 4000);
583         if (m_draw_control.range_all) {
584                 m_cameranode->setFarValue(100000.0);
585                 return;
586         }
587         m_cameranode->setFarValue((viewing_range < 2000) ? 2000 * BS : viewing_range * BS);
588 }
589
590 void Camera::setDigging(s32 button)
591 {
592         if (m_digging_button == -1)
593                 m_digging_button = button;
594 }
595
596 void Camera::wield(const ItemStack &item)
597 {
598         if (item.name != m_wield_item_next.name ||
599                         item.metadata != m_wield_item_next.metadata) {
600                 m_wield_item_next = item;
601                 if (m_wield_change_timer > 0)
602                         m_wield_change_timer = -m_wield_change_timer;
603                 else if (m_wield_change_timer == 0)
604                         m_wield_change_timer = -0.001;
605         }
606 }
607
608 void Camera::drawWieldedTool(irr::core::matrix4* translation)
609 {
610         // Clear Z buffer so that the wielded tool stays in front of world geometry
611         m_wieldmgr->getVideoDriver()->clearZBuffer();
612
613         // Draw the wielded node (in a separate scene manager)
614         scene::ICameraSceneNode* cam = m_wieldmgr->getActiveCamera();
615         cam->setAspectRatio(m_cameranode->getAspectRatio());
616         cam->setFOV(72.0*M_PI/180.0);
617         cam->setNearValue(10);
618         cam->setFarValue(1000);
619         if (translation != NULL)
620         {
621                 irr::core::matrix4 startMatrix = cam->getAbsoluteTransformation();
622                 irr::core::vector3df focusPoint = (cam->getTarget()
623                                 - cam->getAbsolutePosition()).setLength(1)
624                                 + cam->getAbsolutePosition();
625
626                 irr::core::vector3df camera_pos =
627                                 (startMatrix * *translation).getTranslation();
628                 cam->setPosition(camera_pos);
629                 cam->setTarget(focusPoint);
630         }
631         m_wieldmgr->drawAll();
632 }
633
634 void Camera::drawNametags()
635 {
636         core::matrix4 trans = m_cameranode->getProjectionMatrix();
637         trans *= m_cameranode->getViewMatrix();
638
639         for (std::list<Nametag *>::const_iterator
640                         i = m_nametags.begin();
641                         i != m_nametags.end(); ++i) {
642                 Nametag *nametag = *i;
643                 if (nametag->nametag_color.getAlpha() == 0) {
644                         // Enforce hiding nametag,
645                         // because if freetype is enabled, a grey
646                         // shadow can remain.
647                         continue;
648                 }
649                 v3f pos = nametag->parent_node->getAbsolutePosition() + nametag->nametag_pos * BS;
650                 f32 transformed_pos[4] = { pos.X, pos.Y, pos.Z, 1.0f };
651                 trans.multiplyWith1x4Matrix(transformed_pos);
652                 if (transformed_pos[3] > 0) {
653                         std::wstring nametag_colorless =
654                                 unescape_translate(utf8_to_wide(nametag->nametag_text));
655                         core::dimension2d<u32> textsize =
656                                 g_fontengine->getFont()->getDimension(
657                                 nametag_colorless.c_str());
658                         f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f :
659                                 core::reciprocal(transformed_pos[3]);
660                         v2u32 screensize = RenderingEngine::get_video_driver()->getScreenSize();
661                         v2s32 screen_pos;
662                         screen_pos.X = screensize.X *
663                                 (0.5 * transformed_pos[0] * zDiv + 0.5) - textsize.Width / 2;
664                         screen_pos.Y = screensize.Y *
665                                 (0.5 - transformed_pos[1] * zDiv * 0.5) - textsize.Height / 2;
666                         core::rect<s32> size(0, 0, textsize.Width, textsize.Height);
667                         g_fontengine->getFont()->draw(
668                                 translate_string(utf8_to_wide(nametag->nametag_text)).c_str(),
669                                 size + screen_pos, nametag->nametag_color);
670                 }
671         }
672 }
673
674 Nametag *Camera::addNametag(scene::ISceneNode *parent_node,
675                 const std::string &nametag_text, video::SColor nametag_color,
676                 const v3f &pos)
677 {
678         Nametag *nametag = new Nametag(parent_node, nametag_text, nametag_color, pos);
679         m_nametags.push_back(nametag);
680         return nametag;
681 }
682
683 void Camera::removeNametag(Nametag *nametag)
684 {
685         m_nametags.remove(nametag);
686         delete nametag;
687 }