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