]> git.lizzy.rs Git - minetest.git/blob - src/client/camera.cpp
Add setting to mirror hands
[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 "client/content_cao.h"
30 #include "settings.h"
31 #include "wieldmesh.h"
32 #include "noise.h"         // easeCurve
33 #include "sound.h"
34 #include "mtevent.h"
35 #include "nodedef.h"
36 #include "util/numeric.h"
37 #include "constants.h"
38 #include "fontengine.h"
39 #include "script/scripting_client.h"
40 #include "gettext.h"
41 #include <SViewFrustum.h>
42
43 #define CAMERA_OFFSET_STEP 200
44 #define WIELDMESH_OFFSET_X 55.0f
45 #define WIELDMESH_OFFSET_Y -35.0f
46 #define WIELDMESH_AMPLITUDE_X 7.0f
47 #define WIELDMESH_AMPLITUDE_Y 10.0f
48
49 // Returns the fractional part of x
50 inline f32 my_modf(f32 x)
51 {
52         f32 dummy;
53         return modff(x, &dummy);
54 }
55
56 WieldNode::WieldNode(HandIndex index, Client *client, scene::ISceneManager *mgr) :
57         m_index(index),
58         m_direction(index == MAINHAND ? +1 : -1),
59         m_client(client),
60         m_meshnode(new WieldMeshSceneNode(mgr, -1, false)),
61         m_player_light_color(0xFFFFFFFF)
62 {
63         m_meshnode->setItem(ItemStack(), m_client);
64         m_meshnode->drop(); // mgr grabbed it
65 }
66
67 int WieldNode::getDirection()
68 {
69         return g_settings->getBool("mirror_hands") ? -m_direction : m_direction;
70 }
71
72 void WieldNode::step(f32 dtime)
73 {
74         bool was_under_zero = m_change_timer < 0;
75         m_change_timer = MYMIN(m_change_timer + dtime, 0.125);
76
77         if (m_change_timer >= 0 && was_under_zero) {
78                 m_meshnode->setItem(m_item_next, m_client);
79                 m_meshnode->setNodeLightColor(m_player_light_color);
80         }
81
82         if (m_digging_button == -1)
83                 return;
84
85         f32 offset = dtime * 3.5f;
86         float m_digging_anim_was = m_digging_anim;
87         m_digging_anim += offset;
88         if (m_digging_anim >= 1)
89         {
90                 m_digging_anim = 0;
91                 m_digging_button = -1;
92         }
93         float lim = 0.15;
94         if(m_digging_anim_was < lim && m_digging_anim >= lim)
95         {
96                 if (m_digging_button == 0) {
97                         m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::CAMERA_PUNCH_LEFT));
98                 } else if(m_digging_button == 1) {
99                         m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::CAMERA_PUNCH_RIGHT));
100                 }
101         }
102 }
103
104 static inline v2f dir(const v2f &pos_dist)
105 {
106         f32 x = pos_dist.X - WIELDMESH_OFFSET_X;
107         f32 y = pos_dist.Y - WIELDMESH_OFFSET_Y;
108
109         f32 x_abs = std::fabs(x);
110         f32 y_abs = std::fabs(y);
111
112         if (x_abs >= y_abs) {
113                 y *= (1.0f / x_abs);
114                 x /= x_abs;
115         }
116
117         if (y_abs >= x_abs) {
118                 x *= (1.0f / y_abs);
119                 y /= y_abs;
120         }
121
122         return v2f(std::fabs(x), std::fabs(y));
123 }
124
125 void WieldNode::addArmInertia(f32 player_yaw, v3f camera_direction)
126 {
127         m_cam_vel.X = std::fabs(rangelim(m_last_cam_pos.X - player_yaw,
128                 -100.0f, 100.0f) / 0.016f) * 0.01f;
129         m_cam_vel.Y = std::fabs((m_last_cam_pos.Y - camera_direction.Y) / 0.016f);
130         f32 gap_X = std::fabs(WIELDMESH_OFFSET_X - m_offset.X);
131         f32 gap_Y = std::fabs(WIELDMESH_OFFSET_Y - m_offset.Y);
132
133         if (m_cam_vel.X > 1.0f || m_cam_vel.Y > 1.0f) {
134                 /*
135                         The arm moves relative to the camera speed,
136                         with an acceleration factor.
137                 */
138
139                 if (m_cam_vel.X > 1.0f) {
140                         if (m_cam_vel.X > m_cam_vel_old.X)
141                                 m_cam_vel_old.X = m_cam_vel.X;
142
143                         f32 acc_X = 0.12f * (m_cam_vel.X - (gap_X * 0.1f));
144                         m_offset.X += (m_last_cam_pos.X < player_yaw ? acc_X : -acc_X) * getDirection();
145
146                         if (m_last_cam_pos.X != player_yaw)
147                                 m_last_cam_pos.X = player_yaw;
148
149                         m_offset.X = rangelim(m_offset.X,
150                                 WIELDMESH_OFFSET_X - (WIELDMESH_AMPLITUDE_X * 0.5f),
151                                 WIELDMESH_OFFSET_X + (WIELDMESH_AMPLITUDE_X * 0.5f));
152                 }
153
154                 if (m_cam_vel.Y > 1.0f) {
155                         if (m_cam_vel.Y > m_cam_vel_old.Y)
156                                 m_cam_vel_old.Y = m_cam_vel.Y;
157
158                         f32 acc_Y = 0.12f * (m_cam_vel.Y - (gap_Y * 0.1f));
159                         m_offset.Y +=
160                                 m_last_cam_pos.Y > camera_direction.Y ? acc_Y : -acc_Y;
161
162                         if (m_last_cam_pos.Y != camera_direction.Y)
163                                 m_last_cam_pos.Y = camera_direction.Y;
164
165                         m_offset.Y = rangelim(m_offset.Y,
166                                 WIELDMESH_OFFSET_Y - (WIELDMESH_AMPLITUDE_Y * 0.5f),
167                                 WIELDMESH_OFFSET_Y + (WIELDMESH_AMPLITUDE_Y * 0.5f));
168                 }
169
170                 m_arm_dir = dir(m_offset);
171         } else {
172                 /*
173                         Now the arm gets back to its default position when the camera stops,
174                         following a vector, with a smooth deceleration factor.
175                 */
176
177                 f32 dec_X = 0.35f * (std::min(15.0f, m_cam_vel_old.X) * (1.0f +
178                         (1.0f - m_arm_dir.X))) * (gap_X / 20.0f);
179
180                 f32 dec_Y = 0.25f * (std::min(15.0f, m_cam_vel_old.Y) * (1.0f +
181                         (1.0f - m_arm_dir.Y))) * (gap_Y / 15.0f);
182
183                 if (gap_X < 0.1f)
184                         m_cam_vel_old.X = 0.0f;
185
186                 m_offset.X -=
187                         m_offset.X > WIELDMESH_OFFSET_X ? dec_X : -dec_X;
188
189                 if (gap_Y < 0.1f)
190                         m_cam_vel_old.Y = 0.0f;
191
192                 m_offset.Y -=
193                         m_offset.Y > WIELDMESH_OFFSET_Y ? dec_Y : -dec_Y;
194         }
195 }
196
197 void WieldNode::update(video::SColor player_light_color, f32 view_bobbing_anim, f32 tool_reload_ratio)
198 {
199         int direction = getDirection();
200         m_player_light_color = player_light_color;
201
202         // Position the wielded item
203         //v3f pos = v3f(45, -35, 65);
204         v3f pos = v3f(m_offset.X, m_offset.Y, 65);
205         //v3f rot = v3f(-100, 120, -100);
206         v3f rot = v3f(-100, 120, -100);
207
208         if (m_index == OFFHAND)
209                 tool_reload_ratio = 1.0f;
210
211         pos.Y += fabs(m_change_timer)*320 - 40;
212         if(m_digging_anim < 0.05 || m_digging_anim > 0.5)
213         {
214                 f32 frac = 1.0;
215                 if(m_digging_anim > 0.5)
216                         frac = 2.0 * (m_digging_anim - 0.5);
217                 // This value starts from 1 and settles to 0
218                 f32 ratiothing = std::pow((1.0f - tool_reload_ratio), 0.5f);
219                 //f32 ratiothing2 = pow(ratiothing, 0.5f);
220                 f32 ratiothing2 = (easeCurve(ratiothing*0.5))*2.0;
221                 pos.Y -= frac * 25.0 * pow(ratiothing2, 1.7f);
222                 //rot.Z += frac * 5.0 * ratiothing2;
223                 pos.X -= frac * 35.0 * pow(ratiothing2, 1.1f);
224                 rot.Y += frac * 70.0 * pow(ratiothing2, 1.4f);
225                 //rot.X -= frac * 15.0 * pow(ratiothing2, 1.4f);
226                 //rot.Z += frac * 15.0 * pow(ratiothing2, 1.0f);
227         }
228         if (m_digging_button != -1)
229         {
230                 f32 digfrac = m_digging_anim;
231                 pos.X -= 50 * sin(pow(digfrac, 0.8f) * M_PI);
232                 pos.Y += 24 * sin(digfrac * 1.8 * M_PI);
233                 pos.Z += 25 * 0.5;
234
235                 // Euler angles are PURE EVIL, so why not use quaternions?
236                 core::quaternion quat_begin(rot * core::DEGTORAD);
237                 //core::quaternion quat_end(v3f(s * 80, 30, s * 100) * core::DEGTORAD);
238                 core::quaternion quat_end(v3f(80, 30, 100) * core::DEGTORAD);
239                 core::quaternion quat_slerp;
240                 quat_slerp.slerp(quat_begin, quat_end, sin(digfrac * M_PI));
241                 quat_slerp.W *= direction;
242                 quat_slerp.X *= direction;
243                 quat_slerp.toEuler(rot);
244                 rot *= core::RADTODEG;
245                 pos.X *= direction;
246         } else {
247                 f32 bobfrac = my_modf(view_bobbing_anim);
248                 pos.X *= direction;
249                 pos.X -= sin(bobfrac*M_PI*2.0+M_PI*m_index) * 3.0 * direction;
250                 pos.Y += sin(my_modf(bobfrac*2.0)*M_PI+M_PI*m_index) * 3.0;
251         }
252
253         m_meshnode->setPosition(pos);
254         m_meshnode->setRotation(rot);
255
256         m_meshnode->setNodeLightColor(m_player_light_color);
257
258         if (m_index == OFFHAND) {
259                 m_meshnode->setVisible(
260                         m_change_timer > 0 ? !m_item_next.name.empty() : m_item_old);
261         }
262
263 }
264
265 void WieldNode::setDigging(s32 button)
266 {
267         if (m_digging_button == -1)
268                 m_digging_button = button;
269 }
270
271 void WieldNode::wield(const ItemStack &item)
272 {
273         if (item.name == m_item_next.name &&
274                         item.metadata == m_item_next.metadata)
275                 return;
276
277         m_item_old = m_item_next.name != "";
278         m_item_next = item;
279         if (m_change_timer > 0)
280                 m_change_timer = -m_change_timer;
281         else if (m_change_timer == 0)
282                 m_change_timer = -0.001;
283 }
284
285 Camera::Camera(MapDrawControl &draw_control, Client *client, RenderingEngine *rendering_engine):
286         m_draw_control(draw_control),
287         m_client(client),
288         m_player_light_color(0xFFFFFFFF)
289 {
290         auto smgr = rendering_engine->get_scene_manager();
291         // note: making the camera node a child of the player node
292         // would lead to unexpected behavior, so we don't do that.
293         m_playernode = smgr->addEmptySceneNode(smgr->getRootSceneNode());
294         m_headnode = smgr->addEmptySceneNode(m_playernode);
295         m_cameranode = smgr->addCameraSceneNode(smgr->getRootSceneNode());
296         m_cameranode->bindTargetAndRotation(true);
297
298         // This needs to be in its own scene manager. It is drawn after
299         // all other 3D scene nodes and before the GUI.
300         m_wieldmgr = smgr->createNewSceneManager();
301         m_wieldmgr->addCameraSceneNode();
302
303         m_wieldnodes[MAINHAND] = new WieldNode(MAINHAND, m_client, m_wieldmgr);
304         m_wieldnodes[ OFFHAND] = new WieldNode( OFFHAND, m_client, m_wieldmgr);
305
306         /* TODO: Add a callback function so these can be updated when a setting
307          *       changes.  At this point in time it doesn't matter (e.g. /set
308          *       is documented to change server settings only)
309          *
310          * TODO: Local caching of settings is not optimal and should at some stage
311          *       be updated to use a global settings object for getting thse values
312          *       (as opposed to the this local caching). This can be addressed in
313          *       a later release.
314          */
315         m_cache_fall_bobbing_amount = g_settings->getFloat("fall_bobbing_amount", 0.0f, 100.0f);
316         m_cache_view_bobbing_amount = g_settings->getFloat("view_bobbing_amount", 0.0f, 7.9f);
317         // 45 degrees is the lowest FOV that doesn't cause the server to treat this
318         // as a zoom FOV and load world beyond the set server limits.
319         m_cache_fov                 = g_settings->getFloat("fov", 45.0f, 160.0f);
320         m_arm_inertia               = g_settings->getBool("arm_inertia");
321         m_nametags.clear();
322         m_show_nametag_backgrounds  = g_settings->getBool("show_nametag_backgrounds");
323 }
324
325 Camera::~Camera()
326 {
327         for (auto node : m_wieldnodes)
328                 delete node;
329         m_wieldmgr->drop();
330 }
331
332 void Camera::notifyFovChange()
333 {
334         LocalPlayer *player = m_client->getEnv().getLocalPlayer();
335         assert(player);
336
337         PlayerFovSpec spec = player->getFov();
338
339         /*
340          * Update m_old_fov_degrees first - it serves as the starting point of the
341          * upcoming transition.
342          *
343          * If an FOV transition is already active, mark current FOV as the start of
344          * the new transition. If not, set it to the previous transition's target FOV.
345          */
346         if (m_fov_transition_active)
347                 m_old_fov_degrees = m_curr_fov_degrees;
348         else
349                 m_old_fov_degrees = m_server_sent_fov ? m_target_fov_degrees : m_cache_fov;
350
351         /*
352          * Update m_server_sent_fov next - it corresponds to the target FOV of the
353          * upcoming transition.
354          *
355          * Set it to m_cache_fov, if server-sent FOV is 0. Otherwise check if
356          * server-sent FOV is a multiplier, and multiply it with m_cache_fov instead
357          * of overriding.
358          */
359         if (spec.fov == 0.0f) {
360                 m_server_sent_fov = false;
361                 m_target_fov_degrees = m_cache_fov;
362         } else {
363                 m_server_sent_fov = true;
364                 m_target_fov_degrees = spec.is_multiplier ? m_cache_fov * spec.fov : spec.fov;
365         }
366
367         if (spec.transition_time > 0.0f)
368                 m_fov_transition_active = true;
369
370         // If FOV smooth transition is active, initialize required variables
371         if (m_fov_transition_active) {
372                 m_transition_time = spec.transition_time;
373                 m_fov_diff = m_target_fov_degrees - m_old_fov_degrees;
374         }
375 }
376
377 void Camera::step(f32 dtime)
378 {
379         for (auto node : m_wieldnodes)
380                 node->step(dtime);
381
382         if(m_view_bobbing_fall > 0)
383         {
384                 m_view_bobbing_fall -= 3 * dtime;
385                 if(m_view_bobbing_fall <= 0)
386                         m_view_bobbing_fall = -1; // Mark the effect as finished
387         }
388
389         if (m_view_bobbing_state != 0)
390         {
391                 //f32 offset = dtime * m_view_bobbing_speed * 0.035;
392                 f32 offset = dtime * m_view_bobbing_speed * 0.030;
393                 if (m_view_bobbing_state == 2) {
394                         // Animation is getting turned off
395                         if (m_view_bobbing_anim < 0.25) {
396                                 m_view_bobbing_anim -= offset;
397                         } else if (m_view_bobbing_anim > 0.75) {
398                                 m_view_bobbing_anim += offset;
399                         } else if (m_view_bobbing_anim < 0.5) {
400                                 m_view_bobbing_anim += offset;
401                                 if (m_view_bobbing_anim > 0.5)
402                                         m_view_bobbing_anim = 0.5;
403                         } else {
404                                 m_view_bobbing_anim -= offset;
405                                 if (m_view_bobbing_anim < 0.5)
406                                         m_view_bobbing_anim = 0.5;
407                         }
408
409                         if (m_view_bobbing_anim <= 0 || m_view_bobbing_anim >= 1 ||
410                                         fabs(m_view_bobbing_anim - 0.5) < 0.01) {
411                                 m_view_bobbing_anim = 0;
412                                 m_view_bobbing_state = 0;
413                         }
414                 }
415                 else {
416                         float was = m_view_bobbing_anim;
417                         m_view_bobbing_anim = my_modf(m_view_bobbing_anim + offset);
418                         bool step = (was == 0 ||
419                                         (was < 0.5f && m_view_bobbing_anim >= 0.5f) ||
420                                         (was > 0.5f && m_view_bobbing_anim <= 0.5f));
421                         if(step) {
422                                 m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::VIEW_BOBBING_STEP));
423                         }
424                 }
425         }
426 }
427
428 void Camera::addArmInertia(f32 player_yaw)
429 {
430         for (auto node : m_wieldnodes)
431                 node->addArmInertia(player_yaw, m_camera_direction);
432 }
433
434 void Camera::update(LocalPlayer* player, f32 frametime, f32 tool_reload_ratio)
435 {
436         // Get player position
437         // Smooth the movement when walking up stairs
438         v3f old_player_position = m_playernode->getPosition();
439         v3f player_position = player->getPosition();
440
441         f32 yaw = player->getYaw();
442         f32 pitch = player->getPitch();
443
444         // This is worse than `LocalPlayer::getPosition()` but
445         // mods expect the player head to be at the parent's position
446         // plus eye height.
447         if (player->getParent())
448                 player_position = player->getParent()->getPosition();
449
450         // Smooth the camera movement after the player instantly moves upward due to stepheight.
451         // The smoothing usually continues until the camera position reaches the player position.
452         float player_stepheight = player->getCAO() ? player->getCAO()->getStepHeight() : HUGE_VALF;
453         float upward_movement = player_position.Y - old_player_position.Y;
454         if (upward_movement < 0.01f || upward_movement > player_stepheight) {
455                 m_stepheight_smooth_active = false;
456         } else if (player->touching_ground) {
457                 m_stepheight_smooth_active = true;
458         }
459         if (m_stepheight_smooth_active) {
460                 f32 oldy = old_player_position.Y;
461                 f32 newy = player_position.Y;
462                 f32 t = std::exp(-23 * frametime);
463                 player_position.Y = oldy * t + newy * (1-t);
464         }
465
466         // Set player node transformation
467         m_playernode->setPosition(player_position);
468         m_playernode->setRotation(v3f(0, -1 * yaw, 0));
469         m_playernode->updateAbsolutePosition();
470
471         // Get camera tilt timer (hurt animation)
472         float cameratilt = fabs(fabs(player->hurt_tilt_timer-0.75)-0.75);
473
474         // Fall bobbing animation
475         float fall_bobbing = 0;
476         if(player->camera_impact >= 1 && m_camera_mode < CAMERA_MODE_THIRD)
477         {
478                 if(m_view_bobbing_fall == -1) // Effect took place and has finished
479                         player->camera_impact = m_view_bobbing_fall = 0;
480                 else if(m_view_bobbing_fall == 0) // Initialize effect
481                         m_view_bobbing_fall = 1;
482
483                 // Convert 0 -> 1 to 0 -> 1 -> 0
484                 fall_bobbing = m_view_bobbing_fall < 0.5 ? m_view_bobbing_fall * 2 : -(m_view_bobbing_fall - 0.5) * 2 + 1;
485                 // Smoothen and invert the above
486                 fall_bobbing = sin(fall_bobbing * 0.5 * M_PI) * -1;
487                 // Amplify according to the intensity of the impact
488                 if (player->camera_impact > 0.0f)
489                         fall_bobbing *= (1 - rangelim(50 / player->camera_impact, 0, 1)) * 5;
490
491                 fall_bobbing *= m_cache_fall_bobbing_amount;
492         }
493
494         // Calculate and translate the head SceneNode offsets
495         {
496                 v3f eye_offset = player->getEyeOffset();
497                 if (m_camera_mode == CAMERA_MODE_FIRST)
498                         eye_offset += player->eye_offset_first;
499                 else
500                         eye_offset += player->eye_offset_third;
501
502                 // Set head node transformation
503                 eye_offset.Y += cameratilt * -player->hurt_tilt_strength + fall_bobbing;
504                 m_headnode->setPosition(eye_offset);
505                 m_headnode->setRotation(v3f(pitch, 0,
506                         cameratilt * player->hurt_tilt_strength));
507                 m_headnode->updateAbsolutePosition();
508         }
509
510         // Compute relative camera position and target
511         v3f rel_cam_pos = v3f(0,0,0);
512         v3f rel_cam_target = v3f(0,0,1);
513         v3f rel_cam_up = v3f(0,1,0);
514
515         if (m_cache_view_bobbing_amount != 0.0f && m_view_bobbing_anim != 0.0f &&
516                 m_camera_mode < CAMERA_MODE_THIRD) {
517                 f32 bobfrac = my_modf(m_view_bobbing_anim * 2);
518                 f32 bobdir = (m_view_bobbing_anim < 0.5) ? 1.0 : -1.0;
519
520                 f32 bobknob = 1.2;
521                 f32 bobtmp = sin(pow(bobfrac, bobknob) * M_PI);
522
523                 v3f bobvec = v3f(
524                         0.3 * bobdir * sin(bobfrac * M_PI),
525                         -0.28 * bobtmp * bobtmp,
526                         0.);
527
528                 rel_cam_pos += bobvec * m_cache_view_bobbing_amount;
529                 rel_cam_target += bobvec * m_cache_view_bobbing_amount;
530                 rel_cam_up.rotateXYBy(-0.03 * bobdir * bobtmp * M_PI * m_cache_view_bobbing_amount);
531         }
532
533         // Compute absolute camera position and target
534         m_headnode->getAbsoluteTransformation().transformVect(m_camera_position, rel_cam_pos);
535         m_headnode->getAbsoluteTransformation().rotateVect(m_camera_direction, rel_cam_target - rel_cam_pos);
536
537         v3f abs_cam_up;
538         m_headnode->getAbsoluteTransformation().rotateVect(abs_cam_up, rel_cam_up);
539
540         // Separate camera position for calculation
541         v3f my_cp = m_camera_position;
542
543         // Reposition the camera for third person view
544         if (m_camera_mode > CAMERA_MODE_FIRST)
545         {
546                 if (m_camera_mode == CAMERA_MODE_THIRD_FRONT)
547                         m_camera_direction *= -1;
548
549                 my_cp.Y += 2;
550
551                 // Calculate new position
552                 bool abort = false;
553                 for (int i = BS; i <= BS * 2.75; i++) {
554                         my_cp.X = m_camera_position.X + m_camera_direction.X * -i;
555                         my_cp.Z = m_camera_position.Z + m_camera_direction.Z * -i;
556                         if (i > 12)
557                                 my_cp.Y = m_camera_position.Y + (m_camera_direction.Y * -i);
558
559                         // Prevent camera positioned inside nodes
560                         const NodeDefManager *nodemgr = m_client->ndef();
561                         MapNode n = m_client->getEnv().getClientMap()
562                                 .getNode(floatToInt(my_cp, BS));
563
564                         const ContentFeatures& features = nodemgr->get(n);
565                         if (features.walkable) {
566                                 my_cp.X += m_camera_direction.X*-1*-BS/2;
567                                 my_cp.Z += m_camera_direction.Z*-1*-BS/2;
568                                 my_cp.Y += m_camera_direction.Y*-1*-BS/2;
569                                 abort = true;
570                                 break;
571                         }
572                 }
573
574                 // If node blocks camera position don't move y to heigh
575                 if (abort && my_cp.Y > player_position.Y+BS*2)
576                         my_cp.Y = player_position.Y+BS*2;
577         }
578
579         // Update offset if too far away from the center of the map
580         m_camera_offset.X += CAMERA_OFFSET_STEP*
581                         (((s16)(my_cp.X/BS) - m_camera_offset.X)/CAMERA_OFFSET_STEP);
582         m_camera_offset.Y += CAMERA_OFFSET_STEP*
583                         (((s16)(my_cp.Y/BS) - m_camera_offset.Y)/CAMERA_OFFSET_STEP);
584         m_camera_offset.Z += CAMERA_OFFSET_STEP*
585                         (((s16)(my_cp.Z/BS) - m_camera_offset.Z)/CAMERA_OFFSET_STEP);
586
587         // Set camera node transformation
588         m_cameranode->setPosition(my_cp-intToFloat(m_camera_offset, BS));
589         m_cameranode->updateAbsolutePosition();
590         m_cameranode->setUpVector(abs_cam_up);
591         // *100.0 helps in large map coordinates
592         m_cameranode->setTarget(my_cp-intToFloat(m_camera_offset, BS) + 100 * m_camera_direction);
593
594         // update the camera position in third-person mode to render blocks behind player
595         // and correctly apply liquid post FX.
596         if (m_camera_mode != CAMERA_MODE_FIRST)
597                 m_camera_position = my_cp;
598
599         /*
600          * Apply server-sent FOV, instantaneous or smooth transition.
601          * If not, check for zoom and set to zoom FOV.
602          * Otherwise, default to m_cache_fov.
603          */
604         if (m_fov_transition_active) {
605                 // Smooth FOV transition
606                 // Dynamically calculate FOV delta based on frametimes
607                 f32 delta = (frametime / m_transition_time) * m_fov_diff;
608                 m_curr_fov_degrees += delta;
609
610                 // Mark transition as complete if target FOV has been reached
611                 if ((m_fov_diff > 0.0f && m_curr_fov_degrees >= m_target_fov_degrees) ||
612                                 (m_fov_diff < 0.0f && m_curr_fov_degrees <= m_target_fov_degrees)) {
613                         m_fov_transition_active = false;
614                         m_curr_fov_degrees = m_target_fov_degrees;
615                 }
616         } else if (m_server_sent_fov) {
617                 // Instantaneous FOV change
618                 m_curr_fov_degrees = m_target_fov_degrees;
619         } else if (player->getPlayerControl().zoom && player->getZoomFOV() > 0.001f) {
620                 // Player requests zoom, apply zoom FOV
621                 m_curr_fov_degrees = player->getZoomFOV();
622         } else {
623                 // Set to client's selected FOV
624                 m_curr_fov_degrees = m_cache_fov;
625         }
626         m_curr_fov_degrees = rangelim(m_curr_fov_degrees, 1.0f, 160.0f);
627
628         // FOV and aspect ratio
629         const v2u32 &window_size = RenderingEngine::getWindowSize();
630         m_aspect = (f32) window_size.X / (f32) window_size.Y;
631         m_fov_y = m_curr_fov_degrees * M_PI / 180.0;
632         // Increase vertical FOV on lower aspect ratios (<16:10)
633         m_fov_y *= core::clamp(sqrt(16./10. / m_aspect), 1.0, 1.4);
634         m_fov_x = 2 * atan(m_aspect * tan(0.5 * m_fov_y));
635         m_cameranode->setAspectRatio(m_aspect);
636         m_cameranode->setFOV(m_fov_y);
637
638         // Make new matrices and frustum
639         m_cameranode->updateMatrices();
640
641         if (m_arm_inertia)
642                 addArmInertia(yaw);
643
644         m_player_light_color = player->light_color;
645
646         for (auto node : m_wieldnodes)
647                 node->update(m_player_light_color, m_view_bobbing_anim, tool_reload_ratio);
648
649         // Set render distance
650         updateViewingRange();
651
652         // If the player is walking, swimming, or climbing,
653         // view bobbing is enabled and free_move is off,
654         // start (or continue) the view bobbing animation.
655         const v3f &speed = player->getSpeed();
656         const bool movement_XZ = hypot(speed.X, speed.Z) > BS;
657         const bool movement_Y = fabs(speed.Y) > BS;
658
659         const bool walking = movement_XZ && player->touching_ground;
660         const bool swimming = (movement_XZ || player->swimming_vertical) && player->in_liquid;
661         const bool climbing = movement_Y && player->is_climbing;
662         const bool flying = g_settings->getBool("free_move")
663                 && m_client->checkLocalPrivilege("fly");
664         if ((walking || swimming || climbing) && !flying) {
665                 // Start animation
666                 m_view_bobbing_state = 1;
667                 m_view_bobbing_speed = MYMIN(speed.getLength(), 70);
668         } else if (m_view_bobbing_state == 1) {
669                 // Stop animation
670                 m_view_bobbing_state = 2;
671                 m_view_bobbing_speed = 60;
672         }
673 }
674
675 void Camera::updateViewingRange()
676 {
677         f32 viewing_range = g_settings->getFloat("viewing_range");
678
679         // Ignore near_plane setting on all other platforms to prevent abuse
680 #if ENABLE_GLES
681         m_cameranode->setNearValue(rangelim(
682                 g_settings->getFloat("near_plane"), 0.0f, 0.25f) * BS);
683 #else
684         m_cameranode->setNearValue(0.1f * BS);
685 #endif
686
687         m_draw_control.wanted_range = std::fmin(adjustDist(viewing_range, getFovMax()), 4000);
688         if (m_draw_control.range_all) {
689                 m_cameranode->setFarValue(100000.0);
690                 return;
691         }
692         m_cameranode->setFarValue((viewing_range < 2000) ? 2000 * BS : viewing_range * BS);
693 }
694
695 void Camera::setDigging(s32 button, HandIndex hand)
696 {
697         m_wieldnodes[hand]->setDigging(button);
698 }
699
700 void Camera::wield(const ItemStack &item, HandIndex hand)
701 {
702         m_wieldnodes[hand]->wield(item);
703 }
704
705 void Camera::drawWieldedTool(irr::core::matrix4* translation)
706 {
707         // Draw the wielded node (in a separate scene manager)
708         scene::ICameraSceneNode* cam = m_wieldmgr->getActiveCamera();
709         cam->setAspectRatio(m_cameranode->getAspectRatio());
710         cam->setFOV(72.0*M_PI/180.0);
711         cam->setNearValue(40); // give wield tool smaller z-depth than the world in most cases.
712         cam->setFarValue(1000);
713         if (translation != NULL)
714         {
715                 irr::core::matrix4 startMatrix = cam->getAbsoluteTransformation();
716                 irr::core::vector3df focusPoint = (cam->getTarget()
717                                 - cam->getAbsolutePosition()).setLength(1)
718                                 + cam->getAbsolutePosition();
719
720                 irr::core::vector3df camera_pos =
721                                 (startMatrix * *translation).getTranslation();
722                 cam->setPosition(camera_pos);
723                 cam->updateAbsolutePosition();
724                 cam->setTarget(focusPoint);
725         }
726         m_wieldmgr->drawAll();
727 }
728
729 void Camera::drawNametags()
730 {
731         core::matrix4 trans = m_cameranode->getProjectionMatrix();
732         trans *= m_cameranode->getViewMatrix();
733
734         gui::IGUIFont *font = g_fontengine->getFont();
735         video::IVideoDriver *driver = RenderingEngine::get_video_driver();
736         v2u32 screensize = driver->getScreenSize();
737
738         for (const Nametag *nametag : m_nametags) {
739                 // Nametags are hidden in GenericCAO::updateNametag()
740
741                 v3f pos = nametag->parent_node->getAbsolutePosition() + nametag->pos * BS;
742                 f32 transformed_pos[4] = { pos.X, pos.Y, pos.Z, 1.0f };
743                 trans.multiplyWith1x4Matrix(transformed_pos);
744                 if (transformed_pos[3] > 0) {
745                         std::wstring nametag_colorless =
746                                 unescape_translate(utf8_to_wide(nametag->text));
747                         core::dimension2d<u32> textsize = font->getDimension(
748                                 nametag_colorless.c_str());
749                         f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f :
750                                 core::reciprocal(transformed_pos[3]);
751                         v2s32 screen_pos;
752                         screen_pos.X = screensize.X *
753                                 (0.5 * transformed_pos[0] * zDiv + 0.5) - textsize.Width / 2;
754                         screen_pos.Y = screensize.Y *
755                                 (0.5 - transformed_pos[1] * zDiv * 0.5) - textsize.Height / 2;
756                         core::rect<s32> size(0, 0, textsize.Width, textsize.Height);
757
758                         auto bgcolor = nametag->getBgColor(m_show_nametag_backgrounds);
759                         if (bgcolor.getAlpha() != 0) {
760                                 core::rect<s32> bg_size(-2, 0, textsize.Width + 2, textsize.Height);
761                                 driver->draw2DRectangle(bgcolor, bg_size + screen_pos);
762                         }
763
764                         font->draw(
765                                 translate_string(utf8_to_wide(nametag->text)).c_str(),
766                                 size + screen_pos, nametag->textcolor);
767                 }
768         }
769 }
770
771 Nametag *Camera::addNametag(scene::ISceneNode *parent_node,
772                 const std::string &text, video::SColor textcolor,
773                 Optional<video::SColor> bgcolor, const v3f &pos)
774 {
775         Nametag *nametag = new Nametag(parent_node, text, textcolor, bgcolor, pos);
776         m_nametags.push_back(nametag);
777         return nametag;
778 }
779
780 void Camera::removeNametag(Nametag *nametag)
781 {
782         m_nametags.remove(nametag);
783         delete nametag;
784 }
785
786 std::array<core::plane3d<f32>, 4> Camera::getFrustumCullPlanes() const
787 {
788         using irr::scene::SViewFrustum;
789         const auto &frustum_planes = m_cameranode->getViewFrustum()->planes;
790         return {
791                 frustum_planes[SViewFrustum::VF_LEFT_PLANE],
792                 frustum_planes[SViewFrustum::VF_RIGHT_PLANE],
793                 frustum_planes[SViewFrustum::VF_BOTTOM_PLANE],
794                 frustum_planes[SViewFrustum::VF_TOP_PLANE],
795         };
796 }